@koed-labs/server 0.0.0-stage → 0.11.1

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 (67) 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-2XKSVKQA.js +49 -0
  7. package/vendor/chunk-4OO6VAU3.js +259 -0
  8. package/vendor/chunk-53ZFCDHP.js +332 -0
  9. package/vendor/chunk-6JRWGOQG.js +236 -0
  10. package/vendor/chunk-6KS67EQE.js +75 -0
  11. package/vendor/chunk-7EGSY3E4.js +8 -0
  12. package/vendor/chunk-7FSHVVTZ.js +128 -0
  13. package/vendor/chunk-7NOQSX4T.js +14 -0
  14. package/vendor/chunk-7NXKPDF3.js +1586 -0
  15. package/vendor/chunk-ALJUSOF7.js +175 -0
  16. package/vendor/chunk-AVQCUFYQ.js +16 -0
  17. package/vendor/chunk-BGENSONI.js +18 -0
  18. package/vendor/chunk-BTS4ZTF3.js +43 -0
  19. package/vendor/chunk-BUIM2M4R.js +22 -0
  20. package/vendor/chunk-C4V72GXC.js +194 -0
  21. package/vendor/chunk-C5SNDPAP.js +2472 -0
  22. package/vendor/chunk-CHMH4LH5.js +2497 -0
  23. package/vendor/chunk-EA4QDDQA.js +58 -0
  24. package/vendor/chunk-EDPNYIX5.js +5448 -0
  25. package/vendor/chunk-FN3HUUO2.js +1974 -0
  26. package/vendor/chunk-FSNLU46W.js +14548 -0
  27. package/vendor/chunk-FYYRFX4U.js +4423 -0
  28. package/vendor/chunk-GFASBPV2.js +42 -0
  29. package/vendor/chunk-HC76426R.js +48 -0
  30. package/vendor/chunk-IY2HRXOZ.js +99 -0
  31. package/vendor/chunk-JBGD4JLR.js +3779 -0
  32. package/vendor/chunk-JYK6UL6D.js +261 -0
  33. package/vendor/chunk-LRP66XEY.js +13907 -0
  34. package/vendor/chunk-NOU7RHYZ.js +26 -0
  35. package/vendor/chunk-NVTMIAAF.js +113 -0
  36. package/vendor/chunk-O7DW2VAV.js +14 -0
  37. package/vendor/chunk-OCILJ737.js +299 -0
  38. package/vendor/chunk-PL3LWC5C.js +754 -0
  39. package/vendor/chunk-QRKHHWJJ.js +104 -0
  40. package/vendor/chunk-QT24SAW6.js +110 -0
  41. package/vendor/chunk-RCR4XPE3.js +26020 -0
  42. package/vendor/chunk-SHLRINKO.js +73 -0
  43. package/vendor/chunk-SNKWETM5.js +35 -0
  44. package/vendor/chunk-SRKIBFOE.js +242 -0
  45. package/vendor/chunk-T6UB5PNX.js +124 -0
  46. package/vendor/chunk-TG26CZGQ.js +23 -0
  47. package/vendor/chunk-TISYUUEJ.js +188 -0
  48. package/vendor/chunk-TSAYTRX3.js +89 -0
  49. package/vendor/chunk-TVYEB2GN.js +343 -0
  50. package/vendor/chunk-UB6JCVQ3.js +461 -0
  51. package/vendor/chunk-V67IQB7H.js +153 -0
  52. package/vendor/chunk-VGIYSDNU.js +522 -0
  53. package/vendor/chunk-W2HNI6AA.js +75 -0
  54. package/vendor/chunk-W2OJZZ6X.js +20 -0
  55. package/vendor/chunk-WDFERJG3.js +2208 -0
  56. package/vendor/chunk-WPIEF4LY.js +1647 -0
  57. package/vendor/chunk-XIZVLPHZ.js +18 -0
  58. package/vendor/chunk-YZLQZU5E.js +46 -0
  59. package/vendor/chunk-Z5WCAUA6.js +148 -0
  60. package/vendor/chunk-ZIOKV2X6.js +1589 -0
  61. package/vendor/chunk-ZOHNXUDY.js +12501 -0
  62. package/vendor/chunk-ZUDSZGVO.js +11 -0
  63. package/vendor/cli.js +7 -0
  64. package/vendor/component-manifest-catalog.js +9 -0
  65. package/vendor/control-plane.js +28 -0
  66. package/vendor/package.json +1 -0
  67. package/vendor/privacy-service-bootstrap.js +6 -0
@@ -0,0 +1,89 @@
1
+ import { createRequire as createKoedRequire } from "node:module"; const require = createKoedRequire(import.meta.url);
2
+ import {
3
+ isPackagedRuntimeMode,
4
+ resolvePackagedResourcesPath
5
+ } from "./chunk-YZLQZU5E.js";
6
+
7
+ // packages/koed-server/dist/paths.js
8
+ import { mkdirSync } from "node:fs";
9
+ import { homedir } from "node:os";
10
+ import { dirname, resolve } from "node:path";
11
+ import { fileURLToPath } from "node:url";
12
+ var packageDir = resolve(dirname(fileURLToPath(import.meta.url)), "..");
13
+ var resolveRepoRoot = (environment = process.env) => {
14
+ const fromEnv = environment.KOED_REPO_ROOT?.trim();
15
+ if (fromEnv) {
16
+ return resolve(fromEnv);
17
+ }
18
+ if (isPackagedRuntimeMode(environment)) {
19
+ const resourcesPath = resolvePackagedResourcesPath(environment);
20
+ if (resourcesPath) {
21
+ return resourcesPath;
22
+ }
23
+ }
24
+ return resolve(packageDir, "..", "..");
25
+ };
26
+ var documentationPlaceholderPath = (value) => {
27
+ const normalized = resolve(value);
28
+ return normalized === "/path" || normalized === "/path/to" || normalized.startsWith("/path/to/");
29
+ };
30
+ var resolveKoedHome = (environment = process.env) => {
31
+ const configured = environment.KOED_HOME?.trim();
32
+ const expanded = configured === "~" ? homedir() : configured?.startsWith("~/") || configured?.startsWith("~\\") ? resolve(homedir(), configured.slice(2)) : configured;
33
+ if (expanded && documentationPlaceholderPath(expanded)) {
34
+ throw new Error(`KOED_HOME is set to the documentation placeholder ${expanded}. Unset KOED_HOME or set it to a writable local state directory such as ${resolve(`${homedir()}/.koed`)}.`);
35
+ }
36
+ return resolve(expanded || `${homedir()}/.koed`);
37
+ };
38
+ var resolveKoedServerPaths = (environment = process.env) => {
39
+ const koedHome = resolveKoedHome(environment);
40
+ const repoRoot = resolveRepoRoot(environment);
41
+ const modelsDir = environment.KOED_MODELS_DIR?.trim() ? resolve(environment.KOED_MODELS_DIR) : resolve(koedHome, "models");
42
+ return {
43
+ koedHome,
44
+ configDir: resolve(koedHome, "config"),
45
+ logsDir: resolve(koedHome, "logs"),
46
+ runDir: resolve(koedHome, "run"),
47
+ dataDir: resolve(koedHome, "data"),
48
+ modelsDir,
49
+ cacheDir: resolve(koedHome, "cache"),
50
+ componentsDir: resolve(koedHome, "runtime", "components"),
51
+ generationsDir: resolve(koedHome, "runtime", "generations"),
52
+ postgresDataDir: resolve(koedHome, "data", "postgres"),
53
+ postgresRunDir: resolve(koedHome, "run", "postgres"),
54
+ postgresLogPath: resolve(koedHome, "logs", "postgres.log"),
55
+ runtimeStatePath: resolve(koedHome, "run", "koed-server.json"),
56
+ generationStatePath: resolve(koedHome, "run", "runtime-generation.json"),
57
+ lastVerificationPath: resolve(koedHome, "run", "last-verification.json"),
58
+ serverConfigPath: resolve(koedHome, "config", "server.json"),
59
+ localPortsPath: resolve(koedHome, "config", "local-ports.json"),
60
+ localAppCredentialPath: resolve(koedHome, "config", "local-app-credential.json"),
61
+ upstreamBackendsPath: resolve(koedHome, "config", "upstream-backends.json"),
62
+ projectMetadataPath: resolve(koedHome, "config", "projects.json"),
63
+ projectTeamWorkspaceLinksPath: resolve(koedHome, "config", "project-team-workspaces.json"),
64
+ upstreamEnrollmentsPath: resolve(koedHome, "run", "upstream-enrollments.json"),
65
+ upstreamDisconnectCleanupPath: resolve(koedHome, "run", "upstream-disconnect-cleanup.json"),
66
+ repoRoot
67
+ };
68
+ };
69
+ var ensureKoedHome = (paths) => {
70
+ for (const dir of [
71
+ paths.koedHome,
72
+ paths.configDir,
73
+ paths.logsDir,
74
+ paths.runDir,
75
+ paths.dataDir,
76
+ paths.modelsDir,
77
+ paths.cacheDir,
78
+ paths.postgresDataDir,
79
+ paths.postgresRunDir
80
+ ]) {
81
+ mkdirSync(dir, { recursive: true, mode: 448 });
82
+ }
83
+ };
84
+
85
+ export {
86
+ resolveKoedHome,
87
+ resolveKoedServerPaths,
88
+ ensureKoedHome
89
+ };
@@ -0,0 +1,343 @@
1
+ import { createRequire as createKoedRequire } from "node:module"; const require = createKoedRequire(import.meta.url);
2
+ import {
3
+ collectLocalModelStatus
4
+ } from "./chunk-JYK6UL6D.js";
5
+ import {
6
+ compareNativeVersions
7
+ } from "./chunk-QRKHHWJJ.js";
8
+ import {
9
+ external_exports
10
+ } from "./chunk-FSNLU46W.js";
11
+
12
+ // packages/koed-server/dist/runtime-release-validation.js
13
+ import { mkdtempSync, rmSync } from "node:fs";
14
+ import { dirname, join, resolve } from "node:path";
15
+
16
+ // packages/koed-server/dist/native-validation-process.js
17
+ import { spawn } from "node:child_process";
18
+ import { request } from "node:http";
19
+ import { setTimeout as delay } from "node:timers/promises";
20
+ async function withNativeProbe(binary, args, context, action, observeOutput) {
21
+ context.signal.throwIfAborted();
22
+ const child = spawn(binary, args, {
23
+ cwd: context.cwd,
24
+ env: context.env,
25
+ detached: true,
26
+ stdio: ["ignore", "pipe", "pipe"]
27
+ });
28
+ let output = "";
29
+ const append = (chunk) => {
30
+ output = (output + chunk).slice(-64 * 1024);
31
+ observeOutput?.(output);
32
+ };
33
+ child.stdout.setEncoding("utf8").on("data", append);
34
+ child.stderr.setEncoding("utf8").on("data", append);
35
+ const ended = new AbortController();
36
+ const killGroup = () => {
37
+ if (child.pid) {
38
+ try {
39
+ process.kill(-child.pid, "SIGKILL");
40
+ } catch (error) {
41
+ if (error.code !== "ESRCH")
42
+ throw error;
43
+ }
44
+ }
45
+ };
46
+ let exited = false;
47
+ child.once("error", (error) => {
48
+ append(error.message);
49
+ ended.abort(error);
50
+ });
51
+ child.once("exit", () => {
52
+ killGroup();
53
+ exited = true;
54
+ ended.abort(new Error("Native probe exited."));
55
+ });
56
+ const stop = () => {
57
+ if (!exited)
58
+ killGroup();
59
+ };
60
+ const closed = new Promise((done) => child.once("close", done));
61
+ context.signal.addEventListener("abort", stop, { once: true });
62
+ try {
63
+ return await action({
64
+ closed,
65
+ log: () => output,
66
+ lifetime: AbortSignal.any([context.signal, ended.signal])
67
+ });
68
+ } finally {
69
+ context.signal.removeEventListener("abort", stop);
70
+ stop();
71
+ await closed;
72
+ }
73
+ }
74
+ async function nativeCommand(binary, args, context) {
75
+ const signal = AbortSignal.any([context.signal, AbortSignal.timeout(1e4)]);
76
+ return withNativeProbe(binary, args, { ...context, signal }, async (probe) => {
77
+ const code = await probe.closed;
78
+ signal.throwIfAborted();
79
+ if (code !== 0)
80
+ throw new Error(probe.log().trim().slice(-1500) || `Exited with code ${code}.`);
81
+ return probe.log().trim();
82
+ });
83
+ }
84
+ function socketRequest(socketPath, path, signal, body) {
85
+ return new Promise((done, fail) => {
86
+ const req = request({
87
+ socketPath,
88
+ path,
89
+ signal,
90
+ agent: false,
91
+ method: body ? "POST" : "GET",
92
+ headers: body ? { "Content-Type": "application/json" } : {}
93
+ }, (res) => {
94
+ const chunks = [];
95
+ let bytes = 0;
96
+ res.on("error", fail);
97
+ res.on("data", (chunk) => {
98
+ bytes += chunk.length;
99
+ if (bytes > 1024 * 1024)
100
+ res.destroy(new Error("Validation response exceeded 1 MiB."));
101
+ else
102
+ chunks.push(chunk);
103
+ });
104
+ res.on("end", () => done({
105
+ status: res.statusCode ?? 0,
106
+ body: Buffer.concat(chunks).toString("utf8")
107
+ }));
108
+ });
109
+ req.on("error", fail);
110
+ req.end(body);
111
+ });
112
+ }
113
+ async function requestProbeEmbeddings(socket, inputs2, signal) {
114
+ const startup = AbortSignal.any([signal, AbortSignal.timeout(4e4)]);
115
+ for (; ; ) {
116
+ startup.throwIfAborted();
117
+ try {
118
+ const health = await socketRequest(socket, "/health", startup);
119
+ if (health.status === 200)
120
+ break;
121
+ if (health.status !== 503)
122
+ throw new Error(`Embedding health check returned HTTP ${health.status}.`);
123
+ } catch (error) {
124
+ if (!["ENOENT", "ECONNREFUSED"].includes(error.code ?? ""))
125
+ throw error;
126
+ }
127
+ await delay(100, void 0, { signal: startup });
128
+ }
129
+ const result = await socketRequest(socket, "/v1/embeddings", signal, JSON.stringify({ model: "qualification", input: inputs2 }));
130
+ if (result.status !== 200)
131
+ throw new Error(`Embedding request returned HTTP ${result.status}.`);
132
+ return JSON.parse(result.body);
133
+ }
134
+
135
+ // packages/koed-server/dist/runtime-release-validation.js
136
+ var minimumDriver = "550.54.14";
137
+ var minimumCosine = 0.999;
138
+ var inputs = [
139
+ "The train arrives at noon.",
140
+ "A red kite is flying over the lake.",
141
+ "Measure twice, cut once."
142
+ ];
143
+ var NativeValidationError = class extends Error {
144
+ reason;
145
+ constructor(reason, message2) {
146
+ super(message2);
147
+ this.reason = reason;
148
+ }
149
+ };
150
+ async function checkCudaHost(signal) {
151
+ const context = {
152
+ cwd: "/",
153
+ env: { PATH: "/usr/bin:/bin", LANG: "C", LC_ALL: "C" },
154
+ signal
155
+ };
156
+ let driverVersion;
157
+ try {
158
+ const output = await nativeCommand("/usr/bin/nvidia-smi", ["--query-gpu=driver_version", "--format=csv,noheader"], context);
159
+ const versions = new Set(output.split(/\r?\n/).map((row) => row.trim()));
160
+ driverVersion = [...versions][0] ?? "";
161
+ if (versions.size !== 1 || !/^\d{1,4}\.\d{1,4}(\.\d{1,4})?$/.test(driverVersion))
162
+ throw new Error("No consistent NVIDIA driver version was reported.");
163
+ } catch (error) {
164
+ context.signal.throwIfAborted();
165
+ throw new NativeValidationError("cuda_device_unavailable", `Cannot query the NVIDIA GPU driver: ${message(error)}`);
166
+ }
167
+ const [major, minor, patch = 0] = driverVersion.split(".").map(Number);
168
+ if (compareNativeVersions(`${major}.${minor}.${patch}`, minimumDriver) < 0)
169
+ throw new NativeValidationError("cuda_driver_too_old", `NVIDIA driver ${driverVersion} is older than required ${minimumDriver}.`);
170
+ const loaded = await nativeCommand(process.execPath, [
171
+ "-p",
172
+ String.raw`process.report.getReport().sharedObjects.some(p => /\/libcuda\.so(?:\.\d+)*$/.test(p))`
173
+ ], {
174
+ ...context,
175
+ env: { ...context.env, LD_PRELOAD: "libcuda.so.1" }
176
+ });
177
+ if (loaded !== "true")
178
+ throw new NativeValidationError("cuda_driver_library_unavailable", "The host loader could not load libcuda.so.1.");
179
+ return driverVersion;
180
+ }
181
+ async function discover(root, context) {
182
+ const driverVersion = await checkCudaHost(context.signal);
183
+ const binary = resolve(root, "llama.cpp/cuda/llama-server");
184
+ try {
185
+ const listing = await nativeCommand(binary, ["--list-devices"], {
186
+ ...context,
187
+ env: { ...context.env, LD_LIBRARY_PATH: dirname(binary) }
188
+ });
189
+ const match = /^\s*(CUDA\d+):[ \t]+([^\r\n]+)/m.exec(listing);
190
+ if (!match)
191
+ throw new Error("The staged binary listed no CUDA device.");
192
+ return { driverVersion, device: match[1], description: match[2].trim() };
193
+ } catch (error) {
194
+ context.signal.throwIfAborted();
195
+ throw new NativeValidationError("cuda_device_unavailable", `CUDA device discovery failed: ${message(error)}`);
196
+ }
197
+ }
198
+ var message = (error) => error instanceof Error ? error.message : String(error);
199
+ var responseSchema = external_exports.object({
200
+ data: external_exports.array(external_exports.object({
201
+ index: external_exports.number().int(),
202
+ embedding: external_exports.array(external_exports.number().finite()).min(1)
203
+ })).length(inputs.length)
204
+ });
205
+ function vectors(body) {
206
+ const parsed = responseSchema.safeParse(body);
207
+ if (!parsed.success)
208
+ throw new NativeValidationError("vector_agreement_failed", "Expected one finite, nonempty embedding per test input.");
209
+ const rows = parsed.data.data.sort((a, b) => a.index - b.index);
210
+ if (rows.some((row, index) => row.index !== index))
211
+ throw new NativeValidationError("vector_agreement_failed", "The embedding response did not identify each input exactly once.");
212
+ return rows.map((row) => row.embedding);
213
+ }
214
+ async function embed(root, model, device, context) {
215
+ const backend = device ? "cuda" : "cpu";
216
+ const binary = resolve(root, `llama.cpp/${backend}/llama-server`);
217
+ const socket = join(context.cwd, `${backend}.sock`);
218
+ const args = [
219
+ "--model",
220
+ model,
221
+ "--alias",
222
+ "qualification",
223
+ "--embedding",
224
+ "--pooling",
225
+ "last",
226
+ "--ctx-size",
227
+ "2048",
228
+ "--batch-size",
229
+ "512",
230
+ "--ubatch-size",
231
+ "512",
232
+ "--parallel",
233
+ "1",
234
+ "--threads",
235
+ "2",
236
+ "--threads-batch",
237
+ "2",
238
+ "--n-gpu-layers",
239
+ device ? "all" : "0",
240
+ "--device",
241
+ device ?? "none",
242
+ "--fit",
243
+ "off",
244
+ "--host",
245
+ socket,
246
+ "-lv",
247
+ "4"
248
+ ];
249
+ let offloaded = false, allocationFailed = false;
250
+ return withNativeProbe(binary, args, { ...context, env: { ...context.env, LD_LIBRARY_PATH: dirname(binary) } }, async (probe) => {
251
+ try {
252
+ const result = vectors(await requestProbeEmbeddings(socket, inputs, probe.lifetime));
253
+ if (device && !offloaded)
254
+ throw new NativeValidationError("cuda_offload_unconfirmed", "The staged server did not confirm GPU layer offload.");
255
+ return result;
256
+ } catch (error) {
257
+ context.signal.throwIfAborted();
258
+ if (probe.lifetime.aborted)
259
+ await probe.closed;
260
+ const log = probe.log();
261
+ if (device && allocationFailed)
262
+ throw new NativeValidationError("cuda_memory_pressure", "CUDA ran out of VRAM during validation. Check nvidia-smi for competing GPU workloads and retry.");
263
+ if (error instanceof NativeValidationError)
264
+ throw error;
265
+ throw new NativeValidationError("inference_failed", `${backend.toUpperCase()} embedding probe failed: ${message(error)} ${log.slice(-650).trim()}`);
266
+ }
267
+ }, (tail) => {
268
+ offloaded ||= /offloaded [1-9]\d*\/\d+ layers to GPU/i.test(tail);
269
+ allocationFailed ||= /out of memory|cudaErrorMemoryAllocation|cudaMalloc.*fail/i.test(tail);
270
+ });
271
+ }
272
+ function compare(cpu, gpu) {
273
+ const dimensions = cpu[0].length;
274
+ return cpu.map((left, i) => {
275
+ const right = gpu[i];
276
+ if (left.length !== dimensions || right.length !== dimensions)
277
+ throw new NativeValidationError("vector_agreement_failed", `Embedding dimensions differ for input ${i + 1}.`);
278
+ let dot = 0, normA = 0, normB = 0;
279
+ for (let j = 0; j < dimensions; j++) {
280
+ const a = left[j], b = right[j];
281
+ dot += a * b;
282
+ normA += a * a;
283
+ normB += b * b;
284
+ }
285
+ const cosine = dot / (Math.sqrt(normA) * Math.sqrt(normB));
286
+ if (!Number.isFinite(cosine) || cosine < minimumCosine)
287
+ throw new NativeValidationError("vector_agreement_failed", `CPU/GPU agreement failed for input ${i + 1}: cosine ${cosine}; required ${minimumCosine}.`);
288
+ return { dimensions, cosine };
289
+ });
290
+ }
291
+ async function validateStagedCuda(paths, root, environment, options) {
292
+ const signal = AbortSignal.any([
293
+ options.signal,
294
+ AbortSignal.timeout(12e4)
295
+ ]);
296
+ const cwd = mkdtempSync("/tmp/koed-native-probe-");
297
+ try {
298
+ const env = {
299
+ PATH: "/usr/bin:/bin",
300
+ LANG: "C",
301
+ LC_ALL: "C",
302
+ HOME: cwd,
303
+ TMPDIR: cwd
304
+ };
305
+ for (const key of ["CUDA_VISIBLE_DEVICES", "CUDA_DEVICE_ORDER"])
306
+ if (environment[key] !== void 0)
307
+ env[key] = environment[key];
308
+ const context = { cwd, env, signal };
309
+ const device = await discover(root, context);
310
+ const model = await collectLocalModelStatus(paths, "embedding", environment, signal);
311
+ signal.throwIfAborted();
312
+ if (model.state === "missing" && !options.requireModel)
313
+ return {
314
+ ok: true,
315
+ scope: "device-only",
316
+ ...device,
317
+ message: "CUDA device discovery passed. Install the embedding model for inference validation."
318
+ };
319
+ if (model.state !== "installed")
320
+ throw new NativeValidationError(`model_${model.state}`, model.message);
321
+ const cpu = await embed(root, model.modelPath, null, context);
322
+ const gpu = await embed(root, model.modelPath, device.device, context);
323
+ const agreement = compare(cpu, gpu);
324
+ signal.throwIfAborted();
325
+ return {
326
+ ok: true,
327
+ scope: "inference",
328
+ ...device,
329
+ modelSha256: model.sha256,
330
+ minimumCosine,
331
+ agreement,
332
+ message: "CUDA device discovery, GPU offload and CPU/GPU embedding agreement passed."
333
+ };
334
+ } finally {
335
+ rmSync(cwd, { recursive: true, force: true });
336
+ }
337
+ }
338
+
339
+ export {
340
+ nativeCommand,
341
+ checkCudaHost,
342
+ validateStagedCuda
343
+ };