@koed-labs/server 0.0.0-stage → 0.10.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 (56) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +64 -2
  3. package/bin/koed.js +7 -0
  4. package/package.json +26 -4
  5. package/third-party-notices.json +92 -0
  6. package/vendor/chunk-2BWTLF7A.js +13883 -0
  7. package/vendor/chunk-2DA7EFZV.js +924 -0
  8. package/vendor/chunk-2S3OGPUC.js +58 -0
  9. package/vendor/chunk-473OA62O.js +26827 -0
  10. package/vendor/chunk-6JRWGOQG.js +236 -0
  11. package/vendor/chunk-7NOQSX4T.js +14 -0
  12. package/vendor/chunk-7NXKPDF3.js +1586 -0
  13. package/vendor/chunk-A4NKL2PK.js +153 -0
  14. package/vendor/chunk-A6WMU2GG.js +48 -0
  15. package/vendor/chunk-AFLKCQHF.js +73 -0
  16. package/vendor/chunk-BTS4ZTF3.js +43 -0
  17. package/vendor/chunk-C3N4N5HR.js +108 -0
  18. package/vendor/chunk-DXTAWHY3.js +25 -0
  19. package/vendor/chunk-G4IIVVJO.js +56 -0
  20. package/vendor/chunk-GELDEJJ2.js +4337 -0
  21. package/vendor/chunk-HFM6ROJL.js +188 -0
  22. package/vendor/chunk-HK2H3MVE.js +328 -0
  23. package/vendor/chunk-HZJK5RWC.js +5088 -0
  24. package/vendor/chunk-J2L726BC.js +2497 -0
  25. package/vendor/chunk-JBGD4JLR.js +3779 -0
  26. package/vendor/chunk-JJNLH5GA.js +2470 -0
  27. package/vendor/chunk-JKOG52PE.js +128 -0
  28. package/vendor/chunk-K2EIFEQF.js +89 -0
  29. package/vendor/chunk-KUIWH33N.js +16 -0
  30. package/vendor/chunk-NEWIOOM6.js +34 -0
  31. package/vendor/chunk-NM5NXCVM.js +2404 -0
  32. package/vendor/chunk-PT3AUPGE.js +459 -0
  33. package/vendor/chunk-PY5LYLV7.js +143 -0
  34. package/vendor/chunk-QIIKMG3M.js +103 -0
  35. package/vendor/chunk-QT24SAW6.js +110 -0
  36. package/vendor/chunk-RVYJKKWA.js +22 -0
  37. package/vendor/chunk-SKVYP7NY.js +1647 -0
  38. package/vendor/chunk-TSRPHKAC.js +780 -0
  39. package/vendor/chunk-UI5RLBKQ.js +30 -0
  40. package/vendor/chunk-VPC5NLZG.js +259 -0
  41. package/vendor/chunk-W2HNI6AA.js +75 -0
  42. package/vendor/chunk-X6M525ZJ.js +20 -0
  43. package/vendor/chunk-XIZVLPHZ.js +18 -0
  44. package/vendor/chunk-XNFVSVBS.js +242 -0
  45. package/vendor/chunk-YCDEMYY6.js +2076 -0
  46. package/vendor/chunk-YJ6XUZT6.js +292 -0
  47. package/vendor/chunk-YJWREXN6.js +26020 -0
  48. package/vendor/chunk-YK4F4VY2.js +173 -0
  49. package/vendor/chunk-YOFI4PCH.js +36 -0
  50. package/vendor/chunk-ZUGNCQZE.js +247 -0
  51. package/vendor/chunk-ZXX4ZNJY.js +21 -0
  52. package/vendor/cli.js +7 -0
  53. package/vendor/component-manifest-catalog.js +8 -0
  54. package/vendor/control-plane.js +23 -0
  55. package/vendor/package.json +1 -0
  56. package/vendor/privacy-service-bootstrap.js +6 -0
@@ -0,0 +1,459 @@
1
+ import { createRequire as createKoedRequire } from "node:module"; const require = createKoedRequire(import.meta.url);
2
+ import {
3
+ resolvePackagedKoedRuntimeRoot
4
+ } from "./chunk-UI5RLBKQ.js";
5
+ import "./chunk-BTS4ZTF3.js";
6
+
7
+ // packages/koed-server/dist/runtime-packaged.js
8
+ import { createHash } from "node:crypto";
9
+ import { chmodSync, cpSync, existsSync, closeSync, openSync, mkdirSync, readFileSync, readSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
10
+ import { spawnSync as nodeSpawnSync } from "node:child_process";
11
+ import { dirname, relative, resolve } from "node:path";
12
+ var MANIFEST_FILENAME = "runtime-asset-manifest.json";
13
+ var METADATA_FILENAME = "runtime-packaged.json";
14
+ var platformKey = (platform) => {
15
+ if (platform === "darwin")
16
+ return "macos";
17
+ if (platform === "win32")
18
+ return "windows";
19
+ return platform;
20
+ };
21
+ var trim = (value) => {
22
+ const trimmed = value?.trim();
23
+ return trimmed ? trimmed : void 0;
24
+ };
25
+ var normalizeSha256 = (value) => {
26
+ const normalized = value.trim().toLowerCase();
27
+ if (!/^[a-f0-9]{64}$/.test(normalized)) {
28
+ throw new Error("Packaged runtime SHA-256 must be 64 hex characters.");
29
+ }
30
+ return normalized;
31
+ };
32
+ var isInside = (base, child) => {
33
+ const rel = relative(resolve(base), resolve(child));
34
+ return rel === "" || !rel.startsWith("..") && rel !== "..";
35
+ };
36
+ var safeResolve = (base, path) => {
37
+ if (path.includes("\0")) {
38
+ throw new Error(`Packaged runtime path contains NUL byte: ${path}`);
39
+ }
40
+ const resolved = resolve(base, path);
41
+ if (!isInside(base, resolved)) {
42
+ throw new Error(`Packaged runtime path escapes base directory: ${path}`);
43
+ }
44
+ return resolved;
45
+ };
46
+ var assetFiles = (entry) => [
47
+ .../* @__PURE__ */ new Set([
48
+ ...entry.expectedFiles,
49
+ ...Object.values(entry.executablePaths)
50
+ ])
51
+ ].sort();
52
+ var executableModeOk = (path) => (statSync(path).mode & 73) !== 0;
53
+ var updateHashFromFile = (hash, path) => {
54
+ const descriptor = openSync(path, "r");
55
+ const buffer = Buffer.allocUnsafe(1024 * 1024);
56
+ try {
57
+ let bytesRead = 0;
58
+ do {
59
+ bytesRead = readSync(descriptor, buffer, 0, buffer.length, null);
60
+ if (bytesRead > 0)
61
+ hash.update(buffer.subarray(0, bytesRead));
62
+ } while (bytesRead > 0);
63
+ } finally {
64
+ closeSync(descriptor);
65
+ }
66
+ };
67
+ var run = (command, args, spawnSync) => spawnSync(command, args, {
68
+ encoding: "utf8",
69
+ stdio: ["ignore", "pipe", "pipe"]
70
+ });
71
+ var commandOutput = (result) => `${result.stdout ?? ""}
72
+ ${result.stderr ?? ""}`.trim();
73
+ var postgres17Ok = (output) => /PostgreSQL\)?\s+17(?:\.|\s|$)/i.test(output) || /\(PostgreSQL\)\s+17(?:\.|\s|$)/i.test(output);
74
+ var collectCommandValidation = (installPath, executablePaths, spawnSync) => {
75
+ const commands = [];
76
+ const postgresVersionExecutable = executablePaths.pg_config ?? executablePaths.initdb;
77
+ if (postgresVersionExecutable) {
78
+ const command = safeResolve(installPath, postgresVersionExecutable);
79
+ const result = run(command, ["--version"], spawnSync);
80
+ const output = commandOutput(result);
81
+ const ok = result.status === 0 && postgres17Ok(output);
82
+ commands.push({
83
+ name: "postgres-17",
84
+ command,
85
+ ok,
86
+ ...ok ? {} : {
87
+ message: output || `Postgres version check exited ${result.status ?? 1}`
88
+ }
89
+ });
90
+ }
91
+ const llamaServerExecutable = executablePaths.llama_server;
92
+ if (llamaServerExecutable) {
93
+ const command = safeResolve(installPath, llamaServerExecutable);
94
+ const version = run(command, ["--version"], spawnSync);
95
+ const help = version.status === 0 ? version : run(command, ["--help"], spawnSync);
96
+ const output = commandOutput(help);
97
+ const ok = help.status === 0 && /llama|version:|built with/i.test(output);
98
+ commands.push({
99
+ name: "llama-server",
100
+ command,
101
+ ok,
102
+ ...ok ? {} : {
103
+ message: output || `llama-server validation exited ${help.status ?? 1}`
104
+ }
105
+ });
106
+ }
107
+ return commands;
108
+ };
109
+ var isShellScript = (path) => {
110
+ try {
111
+ return readFileSync(path, "utf8").startsWith("#!");
112
+ } catch {
113
+ return false;
114
+ }
115
+ };
116
+ var collectLoaderValidation = (platform, executablePaths, installPath, spawnSync) => {
117
+ const tool = platform === "darwin" ? "otool" : platform === "linux" ? "ldd" : void 0;
118
+ if (!tool)
119
+ return [];
120
+ return Object.values(executablePaths).map((relativePath) => {
121
+ const command = safeResolve(installPath, relativePath);
122
+ if (isShellScript(command)) {
123
+ return {
124
+ command,
125
+ ok: true,
126
+ skipped: true,
127
+ message: "loader validation skipped for shell launcher script."
128
+ };
129
+ }
130
+ const result = run(tool, platform === "darwin" ? ["-L", command] : [command], spawnSync);
131
+ const output = commandOutput(result);
132
+ if (result.error && result.error.message.includes("ENOENT")) {
133
+ return {
134
+ command,
135
+ ok: true,
136
+ skipped: true,
137
+ message: `${tool} is not available; loader validation skipped.`
138
+ };
139
+ }
140
+ const missing = /not found/i.test(output);
141
+ const ok = result.status === 0 && !missing;
142
+ return {
143
+ command,
144
+ ok,
145
+ ...ok ? {} : {
146
+ message: output || `${tool} validation exited ${result.status ?? 1}`
147
+ }
148
+ };
149
+ });
150
+ };
151
+ var validateInstalledAsset = (platform, installPath, executablePaths, spawnSync) => {
152
+ const executablePermissions = Object.entries(executablePaths).map(([name, relativePath]) => {
153
+ const path = safeResolve(installPath, relativePath);
154
+ return { name, path, ok: executableModeOk(path) };
155
+ });
156
+ const commands = collectCommandValidation(installPath, executablePaths, spawnSync);
157
+ const loader = collectLoaderValidation(platform, executablePaths, installPath, spawnSync);
158
+ const errors = [
159
+ ...executablePermissions.flatMap((entry) => entry.ok ? [] : [`${entry.name} is not executable (${entry.path})`]),
160
+ ...commands.flatMap((entry) => entry.ok ? [] : [`${entry.name} validation failed: ${entry.message}`]),
161
+ ...loader.flatMap((entry) => entry.ok ? [] : [`loader validation failed for ${entry.command}: ${entry.message}`])
162
+ ];
163
+ return {
164
+ ok: errors.length === 0,
165
+ executablePermissions,
166
+ commands,
167
+ loader,
168
+ errors
169
+ };
170
+ };
171
+ var sha256PackagedRuntimeFiles = (root, files) => {
172
+ const hash = createHash("sha256");
173
+ for (const file of [...new Set(files)].sort()) {
174
+ const absolute = safeResolve(root, file);
175
+ const stat = statSync(absolute);
176
+ if (stat.isDirectory())
177
+ continue;
178
+ hash.update(file.replaceAll("\\", "/"));
179
+ hash.update("\0");
180
+ updateHashFromFile(hash, absolute);
181
+ hash.update("\0");
182
+ }
183
+ return hash.digest("hex");
184
+ };
185
+ var manifestPath = (paths, root) => root ? resolve(root, MANIFEST_FILENAME) : resolve(paths.cacheDir, MANIFEST_FILENAME);
186
+ var metadataPath = (paths) => resolve(paths.cacheDir, METADATA_FILENAME);
187
+ var readManifest = (paths, packagedRuntimeRoot) => {
188
+ const candidates = (packagedRuntimeRoot ? [manifestPath(paths, packagedRuntimeRoot)] : [manifestPath(paths)]).filter((value) => Boolean(value));
189
+ const path = candidates[0] ?? manifestPath(paths);
190
+ for (const candidate of candidates) {
191
+ if (!existsSync(candidate))
192
+ continue;
193
+ try {
194
+ return {
195
+ manifest: validateManifest(JSON.parse(readFileSync(candidate, "utf8"))),
196
+ path: candidate
197
+ };
198
+ } catch (error) {
199
+ return {
200
+ path: candidate,
201
+ error: error instanceof Error ? error.message : String(error)
202
+ };
203
+ }
204
+ }
205
+ return { path, error: "manifest not found" };
206
+ };
207
+ var validateManifest = (value) => {
208
+ if (!value || typeof value !== "object") {
209
+ throw new Error("Packaged runtime manifest must be an object.");
210
+ }
211
+ const manifest = value;
212
+ if (manifest.schemaVersion !== 1 || !Array.isArray(manifest.assets)) {
213
+ throw new Error("Packaged runtime manifest schemaVersion 1 with assets is required.");
214
+ }
215
+ for (const asset of manifest.assets) {
216
+ if (!asset.id || !asset.platform || !asset.architecture || !asset.version) {
217
+ throw new Error("Packaged runtime asset requires id, platform, architecture, and version.");
218
+ }
219
+ if (!trim(asset.url) && !trim(asset.packagedResourcePath)) {
220
+ throw new Error("Packaged runtime asset requires url or packagedResourcePath.");
221
+ }
222
+ normalizeSha256(asset.sha256);
223
+ if (!Array.isArray(asset.expectedFiles)) {
224
+ throw new Error("Packaged runtime asset expectedFiles must be an array.");
225
+ }
226
+ if (!asset.executablePaths || typeof asset.executablePaths !== "object") {
227
+ throw new Error("Packaged runtime asset executablePaths must be an object.");
228
+ }
229
+ for (const variant of asset.variants ?? []) {
230
+ if (!["cpu", "metal", "cuda"].includes(variant.backend)) {
231
+ throw new Error("Packaged runtime variant backend is invalid.");
232
+ }
233
+ safeResolve("/runtime", variant.executablePath);
234
+ if (!asset.expectedFiles.includes(variant.executablePath) || !variant.requirements?.platform || !variant.requirements.architecture) {
235
+ throw new Error("Packaged runtime variant must reference an expected executable and host requirements.");
236
+ }
237
+ }
238
+ }
239
+ return manifest;
240
+ };
241
+ var linuxCompatibility = (platform, spawnSync) => {
242
+ if (platform !== "linux")
243
+ return { ok: true };
244
+ const result = run("ldd", ["--version"], spawnSync);
245
+ const output = commandOutput(result);
246
+ if (result.error || result.status !== 0) {
247
+ return {
248
+ ok: false,
249
+ message: "Linux packaged native runtime requires glibc 2.35+; ldd is unavailable or failed.",
250
+ action: "Use Ubuntu 22.04+/Debian 12+ or a WSL Linux distro with glibc 2.35+, or use external dependency mode."
251
+ };
252
+ }
253
+ if (/musl/i.test(output)) {
254
+ return {
255
+ ok: false,
256
+ message: "Linux packaged native runtime requires glibc 2.35+ and does not support musl/Alpine hosts.",
257
+ action: "Use Ubuntu 22.04+/Debian 12+ or a WSL Linux distro with glibc 2.35+, or use external dependency mode."
258
+ };
259
+ }
260
+ const match = output.match(/(?:glibc|GNU libc|ldd)\D+(\d+)\.(\d+)/i);
261
+ const major = match ? Number.parseInt(match[1] ?? "", 10) : Number.NaN;
262
+ const minor = match ? Number.parseInt(match[2] ?? "", 10) : Number.NaN;
263
+ if (!Number.isFinite(major) || !Number.isFinite(minor)) {
264
+ return {
265
+ ok: false,
266
+ message: "Linux packaged native runtime requires glibc 2.35+; could not determine glibc version from ldd.",
267
+ action: "Use Ubuntu 22.04+/Debian 12+ or a WSL Linux distro with glibc 2.35+, or use external dependency mode."
268
+ };
269
+ }
270
+ if (major < 2 || major === 2 && minor < 35) {
271
+ return {
272
+ ok: false,
273
+ message: `Linux packaged native runtime requires glibc 2.35+; host reports glibc ${major}.${minor}.`,
274
+ action: "Use Ubuntu 22.04+/Debian 12+ or a WSL Linux distro with glibc 2.35+, or use external dependency mode."
275
+ };
276
+ }
277
+ return { ok: true };
278
+ };
279
+ var matchesHost = (asset, platform, architecture) => {
280
+ const hostPlatform = platformKey(platform);
281
+ return (asset.platform === platform || asset.platform === hostPlatform) && asset.architecture === architecture;
282
+ };
283
+ var installRoot = (paths) => resolve(paths.koedHome, "runtime");
284
+ var assetInstallPath = (paths, asset) => safeResolve(installRoot(paths), asset.installPath ?? asset.id);
285
+ var assetSourceRoot = (root, asset) => root && asset.packagedResourcePath ? safeResolve(root, asset.packagedResourcePath) : void 0;
286
+ var assetStatus = (paths, root, asset, platform, spawnSync, knownSourceSha256) => {
287
+ const expectedSha = normalizeSha256(asset.sha256);
288
+ const sourceRoot = assetSourceRoot(root, asset);
289
+ const targetRoot = assetInstallPath(paths, asset);
290
+ const files = assetFiles(asset);
291
+ const missingSource = sourceRoot ? files.filter((file) => !existsSync(safeResolve(sourceRoot, file))) : ["packagedResourcePath"];
292
+ const missingInstalled = files.filter((file) => !existsSync(safeResolve(targetRoot, file)));
293
+ const sourceSha256 = sourceRoot && missingSource.length === 0 ? knownSourceSha256 ?? sha256PackagedRuntimeFiles(sourceRoot, files) : void 0;
294
+ const installedSha256 = missingInstalled.length === 0 ? sha256PackagedRuntimeFiles(targetRoot, files) : void 0;
295
+ const installed = installedSha256 === expectedSha;
296
+ const validation = installed ? validateInstalledAsset(platform, targetRoot, asset.executablePaths, spawnSync) : void 0;
297
+ const mismatch = sourceSha256 !== void 0 && sourceSha256 !== expectedSha || installedSha256 !== void 0 && installedSha256 !== expectedSha || validation?.ok === false;
298
+ return {
299
+ id: asset.id,
300
+ platform: asset.platform,
301
+ architecture: asset.architecture,
302
+ version: asset.version,
303
+ source: asset.packagedResourcePath ? { type: "packaged-resource", path: sourceRoot } : { type: "url", url: asset.url },
304
+ sha256: expectedSha,
305
+ expectedFiles: asset.expectedFiles,
306
+ executablePaths: asset.executablePaths,
307
+ installPath: targetRoot,
308
+ state: installed && validation?.ok !== false ? "installed" : mismatch ? "incompatible" : "missing",
309
+ installed: installed && validation?.ok !== false,
310
+ sourceAvailable: missingSource.length === 0,
311
+ sourceSha256,
312
+ installedSha256,
313
+ validation,
314
+ missing: [
315
+ ...missingSource,
316
+ ...missingInstalled,
317
+ ...validation?.errors ?? []
318
+ ]
319
+ };
320
+ };
321
+ var statusFromAssets = (paths, platform, architecture, manifestFile, root, assets) => {
322
+ const incompatible = assets.some((asset) => asset.state === "incompatible");
323
+ const ok = assets.length > 0 && assets.every((asset) => asset.installed);
324
+ const state = ok ? "installed" : incompatible ? "incompatible" : "missing";
325
+ return {
326
+ ok,
327
+ state,
328
+ provider: "packaged",
329
+ platform: platformKey(platform),
330
+ architecture,
331
+ koedHome: paths.koedHome,
332
+ manifestPath: manifestFile,
333
+ packagedRuntimeRoot: root,
334
+ assets,
335
+ message: ok ? "Packaged bundled-local runtime is installed under KOED_HOME." : state === "incompatible" ? "Packaged bundled-local runtime manifest or installed assets are incompatible." : "Packaged bundled-local runtime assets are missing from KOED_HOME/runtime.",
336
+ action: ok ? void 0 : "Run koed runtime install --provider packaged --dependency-mode bundled-local --json."
337
+ };
338
+ };
339
+ var collectPackagedRuntimeStatusInternal = (paths, environment = process.env, dependencies = {}, knownSourceSha256 = /* @__PURE__ */ new Map()) => {
340
+ const root = resolvePackagedKoedRuntimeRoot(environment);
341
+ const platform = dependencies.platform ?? process.platform;
342
+ const architecture = dependencies.architecture ?? process.arch;
343
+ const spawnSync = dependencies.spawnSync ?? nodeSpawnSync;
344
+ const linux = linuxCompatibility(platform, spawnSync);
345
+ if (!linux.ok) {
346
+ return {
347
+ ok: false,
348
+ state: "not_supported",
349
+ provider: "packaged",
350
+ platform: platformKey(platform),
351
+ architecture,
352
+ koedHome: paths.koedHome,
353
+ manifestPath: manifestPath(paths, root),
354
+ packagedRuntimeRoot: root,
355
+ assets: [],
356
+ message: linux.message,
357
+ action: linux.action
358
+ };
359
+ }
360
+ const loaded = readManifest(paths, root);
361
+ if (!loaded.manifest) {
362
+ return {
363
+ ok: false,
364
+ state: "missing",
365
+ provider: "packaged",
366
+ platform: platformKey(platform),
367
+ architecture,
368
+ koedHome: paths.koedHome,
369
+ manifestPath: loaded.path,
370
+ packagedRuntimeRoot: root,
371
+ assets: [],
372
+ message: `Packaged runtime asset manifest is missing or invalid: ${loaded.error ?? "unknown error"}.`,
373
+ action: "Ship runtime-asset-manifest.json with packaged runtime resources."
374
+ };
375
+ }
376
+ const matching = loaded.manifest.assets.filter((asset) => matchesHost(asset, platform, architecture));
377
+ if (matching.length === 0) {
378
+ return {
379
+ ok: false,
380
+ state: "incompatible",
381
+ provider: "packaged",
382
+ platform: platformKey(platform),
383
+ architecture,
384
+ koedHome: paths.koedHome,
385
+ manifestPath: loaded.path,
386
+ packagedRuntimeRoot: root,
387
+ assets: [],
388
+ message: `Packaged runtime asset manifest has no assets for ${platformKey(platform)}/${architecture}.`,
389
+ action: platform === "linux" ? "Ship matching linux/x64 or linux/arm64 packaged assets for a glibc 2.35+ host, or use external dependency mode." : "Install Homebrew-backed runtime assets or ship matching packaged assets."
390
+ };
391
+ }
392
+ return statusFromAssets(paths, platform, architecture, loaded.path, root, matching.map((asset) => assetStatus(paths, root, asset, platform, spawnSync, knownSourceSha256.get(asset.id))));
393
+ };
394
+ var collectPackagedRuntimeStatus = (paths, environment = process.env, dependencies = {}) => collectPackagedRuntimeStatusInternal(paths, environment, dependencies);
395
+ var copyAsset = (paths, root, asset) => {
396
+ const source = assetSourceRoot(root, asset);
397
+ if (!source) {
398
+ throw new Error(`Packaged runtime asset ${asset.id} has no packagedResourcePath.`);
399
+ }
400
+ const target = assetInstallPath(paths, asset);
401
+ const tmpName = `.install-${asset.id.replace(/[^a-zA-Z0-9._-]/g, "_")}-${process.pid}`;
402
+ const tmp = resolve(dirname(target), tmpName);
403
+ mkdirSync(dirname(target), { recursive: true, mode: 448 });
404
+ rmSync(tmp, { recursive: true, force: true });
405
+ rmSync(target, { recursive: true, force: true });
406
+ cpSync(source, tmp, {
407
+ recursive: true,
408
+ preserveTimestamps: true,
409
+ verbatimSymlinks: true
410
+ });
411
+ for (const executable of Object.values(asset.executablePaths)) {
412
+ chmodSync(safeResolve(tmp, executable), 493);
413
+ }
414
+ renameSync(tmp, target);
415
+ return target;
416
+ };
417
+ var installPackagedRuntime = (paths, environment = process.env, dependencies = {}) => {
418
+ const root = resolvePackagedKoedRuntimeRoot(environment);
419
+ const platform = dependencies.platform ?? process.platform;
420
+ const architecture = dependencies.architecture ?? process.arch;
421
+ const before = collectPackagedRuntimeStatus(paths, environment, dependencies);
422
+ const sourceChecksumMismatch = before.assets.some((asset) => asset.sourceSha256 !== void 0 && asset.sourceSha256 !== asset.sha256);
423
+ if (!root || before.assets.length === 0 || sourceChecksumMismatch) {
424
+ return { ...before, copiedPaths: [] };
425
+ }
426
+ const copiedPaths = [];
427
+ for (const asset of before.assets) {
428
+ if (asset.installed)
429
+ continue;
430
+ if (!asset.sourceAvailable || asset.sourceSha256 !== asset.sha256) {
431
+ return { ...before, copiedPaths };
432
+ }
433
+ const loaded = readManifest(paths, root);
434
+ const manifestAsset = loaded.manifest?.assets.find((entry) => entry.id === asset.id && matchesHost(entry, platform, architecture));
435
+ if (!manifestAsset)
436
+ continue;
437
+ copiedPaths.push(copyAsset(paths, root, manifestAsset));
438
+ }
439
+ mkdirSync(paths.cacheDir, { recursive: true, mode: 448 });
440
+ cpSync(manifestPath(paths, root), manifestPath(paths));
441
+ writeFileSync(metadataPath(paths), `${JSON.stringify({
442
+ provider: "packaged",
443
+ installedAt: (dependencies.now ?? (() => /* @__PURE__ */ new Date()))().toISOString(),
444
+ manifestPath: manifestPath(paths),
445
+ packagedRuntimeRoot: root,
446
+ copiedPaths
447
+ }, null, 2)}
448
+ `, { mode: 384 });
449
+ const verifiedSourceSha256 = new Map(before.assets.flatMap((asset) => asset.sourceSha256 ? [[asset.id, asset.sourceSha256]] : []));
450
+ return {
451
+ ...collectPackagedRuntimeStatusInternal(paths, environment, dependencies, verifiedSourceSha256),
452
+ copiedPaths
453
+ };
454
+ };
455
+ export {
456
+ collectPackagedRuntimeStatus,
457
+ installPackagedRuntime,
458
+ sha256PackagedRuntimeFiles
459
+ };
@@ -0,0 +1,143 @@
1
+ import { createRequire as createKoedRequire } from "node:module"; const require = createKoedRequire(import.meta.url);
2
+ import {
3
+ checkCoreSetupNeeded,
4
+ createCliServiceContext,
5
+ getNoAgentsWarning,
6
+ persistDoctorVerification,
7
+ printJson,
8
+ safeLifecycle
9
+ } from "./chunk-YCDEMYY6.js";
10
+ import "./chunk-HZJK5RWC.js";
11
+ import "./chunk-QT24SAW6.js";
12
+ import "./chunk-SKVYP7NY.js";
13
+ import "./chunk-HFM6ROJL.js";
14
+ import "./chunk-AFLKCQHF.js";
15
+ import "./chunk-NM5NXCVM.js";
16
+ import "./chunk-G4IIVVJO.js";
17
+ import "./chunk-JKOG52PE.js";
18
+ import "./chunk-A4NKL2PK.js";
19
+ import "./chunk-QIIKMG3M.js";
20
+ import "./chunk-2DA7EFZV.js";
21
+ import "./chunk-VPC5NLZG.js";
22
+ import "./chunk-YJWREXN6.js";
23
+ import "./chunk-J2L726BC.js";
24
+ import "./chunk-2S3OGPUC.js";
25
+ import "./chunk-XNFVSVBS.js";
26
+ import "./chunk-7NXKPDF3.js";
27
+ import "./chunk-K2EIFEQF.js";
28
+ import "./chunk-UI5RLBKQ.js";
29
+ import "./chunk-W2HNI6AA.js";
30
+ import "./chunk-473OA62O.js";
31
+ import "./chunk-ZUGNCQZE.js";
32
+ import "./chunk-BTS4ZTF3.js";
33
+
34
+ // packages/koed-server/dist/cli-lifecycle-operations.js
35
+ var runLifecycleCommand = async (command, options, dependencies) => {
36
+ const { collectStatus, collectStartupStatus, collectDoctor, inspectDeviceIdentity, rotateIdentity, invalidateEnrollmentReferences, start, startDaemon, stop, restart, resolvePaths, stdout, stderr } = createCliServiceContext(dependencies);
37
+ const wantsJson = options.json;
38
+ const subcommand = options.identityAction;
39
+ try {
40
+ if (command === "status") {
41
+ const paths = resolvePaths();
42
+ const setupNeeded = checkCoreSetupNeeded(paths);
43
+ if (setupNeeded) {
44
+ stderr.write(`${setupNeeded}
45
+ `);
46
+ return 1;
47
+ }
48
+ const isStartup = Boolean(options.startup);
49
+ const status = isStartup ? await collectStartupStatus() : await collectStatus();
50
+ if (wantsJson) {
51
+ printJson(stdout, isStartup ? status : { ...status, lifecycle: safeLifecycle(paths) });
52
+ } else {
53
+ stdout.write(`${status.state}
54
+ `);
55
+ if (!isStartup && "codex" in status) {
56
+ const warning = getNoAgentsWarning(status);
57
+ if (warning)
58
+ stdout.write(`Warning: ${warning}
59
+ `);
60
+ }
61
+ }
62
+ return 0;
63
+ }
64
+ if (command === "doctor") {
65
+ const doctor = await collectDoctor();
66
+ persistDoctorVerification(resolvePaths(), doctor);
67
+ if (wantsJson) {
68
+ printJson(stdout, doctor);
69
+ } else {
70
+ stdout.write(`${doctor.summary}
71
+ `);
72
+ const status = await collectStatus();
73
+ const warning = getNoAgentsWarning(status);
74
+ if (warning)
75
+ stdout.write(`Warning: ${warning}
76
+ `);
77
+ }
78
+ return doctor.ok ? 0 : 1;
79
+ }
80
+ if (command === "identity") {
81
+ const paths = resolvePaths();
82
+ const identity = subcommand === "status" ? await inspectDeviceIdentity(paths) : subcommand === "rotate" ? await rotateIdentity(paths, {
83
+ invalidateRemoteReferences: () => invalidateEnrollmentReferences(paths)
84
+ }) : null;
85
+ if (!identity) {
86
+ throw new Error("identity command must be status or rotate.");
87
+ }
88
+ if (wantsJson) {
89
+ printJson(stdout, identity);
90
+ } else {
91
+ stdout.write(`${identity.health}
92
+ `);
93
+ }
94
+ return identity.remoteOperationsAllowed ? 0 : 1;
95
+ }
96
+ if (command === "start") {
97
+ if (options.daemon) {
98
+ const result = startDaemon();
99
+ if (wantsJson) {
100
+ printJson(stdout, result);
101
+ } else {
102
+ stdout.write(`${result.message}
103
+ `);
104
+ }
105
+ return result.ok ? 0 : 1;
106
+ }
107
+ await start();
108
+ return 0;
109
+ }
110
+ if (command === "stop") {
111
+ const result = stop();
112
+ if (wantsJson) {
113
+ printJson(stdout, result);
114
+ } else {
115
+ stdout.write(`${result.message}
116
+ `);
117
+ }
118
+ return result.ok ? 0 : 1;
119
+ }
120
+ if (command === "restart") {
121
+ const result = await restart();
122
+ if (wantsJson) {
123
+ printJson(stdout, result);
124
+ } else {
125
+ stdout.write(`${result.message}
126
+ `);
127
+ }
128
+ return result.ok ? 0 : 1;
129
+ }
130
+ throw new Error("Unknown lifecycle operation.");
131
+ } catch (error) {
132
+ const message = error instanceof Error ? error.message : String(error);
133
+ if (wantsJson)
134
+ printJson(stdout, { ok: false, error: message });
135
+ else
136
+ stderr.write(`${message}
137
+ `);
138
+ return 1;
139
+ }
140
+ };
141
+ export {
142
+ runLifecycleCommand
143
+ };