@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,259 @@
1
+ import { createRequire as createKoedRequire } from "node:module"; const require = createKoedRequire(import.meta.url);
2
+ import {
3
+ PINNED_PRIVACY_MODEL_FILES,
4
+ PINNED_PRIVACY_MODEL_ID,
5
+ PINNED_PRIVACY_MODEL_REVISION
6
+ } from "./chunk-ZOHNXUDY.js";
7
+
8
+ // packages/koed-server/dist/privacy-model-runtime.js
9
+ import { createHash, randomUUID } from "node:crypto";
10
+ import { createReadStream, createWriteStream, existsSync, linkSync, lstatSync, mkdirSync, renameSync, rmSync, statSync } from "node:fs";
11
+ import { dirname, resolve } from "node:path";
12
+ import { Readable, Transform } from "node:stream";
13
+ import { pipeline } from "node:stream/promises";
14
+ import { setTimeout as delay } from "node:timers/promises";
15
+ var PRIVACY_MODEL_ID = PINNED_PRIVACY_MODEL_ID;
16
+ var PRIVACY_MODEL_REVISION = PINNED_PRIVACY_MODEL_REVISION;
17
+ var PRIVACY_MODEL_FILES = PINNED_PRIVACY_MODEL_FILES;
18
+ var resolvePrivacyModelPaths = (paths) => ({
19
+ blobsDir: resolve(paths.modelsDir, "privacy", "blobs", "sha256"),
20
+ cacheDir: resolve(paths.modelsDir, "privacy", "transformers-cache")
21
+ });
22
+ var cachePath = (paths, file) => resolve(paths.cacheDir, PRIVACY_MODEL_ID, PRIVACY_MODEL_REVISION, file.path);
23
+ var blobPath = (paths, file) => resolve(paths.blobsDir, file.sha256);
24
+ var isSameFile = (left, right) => {
25
+ try {
26
+ const leftStat = statSync(left);
27
+ const rightStat = lstatSync(right);
28
+ return rightStat.isFile() && leftStat.dev === rightStat.dev && leftStat.ino === rightStat.ino;
29
+ } catch (error) {
30
+ if (error.code === "ENOENT")
31
+ return false;
32
+ throw error;
33
+ }
34
+ };
35
+ var materializePrivacyModelCacheEntry = (blob, target) => {
36
+ if (isSameFile(blob, target))
37
+ return;
38
+ rmSync(target, { force: true });
39
+ try {
40
+ linkSync(blob, target);
41
+ } catch (error) {
42
+ if (error.code === "EEXIST" && isSameFile(blob, target)) {
43
+ return;
44
+ }
45
+ throw error;
46
+ }
47
+ };
48
+ var sha256File = async (path, signal) => {
49
+ const hash = createHash("sha256");
50
+ await pipeline(createReadStream(path), hash, signal ? { signal } : {});
51
+ return hash.digest("hex");
52
+ };
53
+ var materializeCacheEntry = (paths, file) => {
54
+ const target = cachePath(paths, file);
55
+ mkdirSync(dirname(target), { recursive: true, mode: 448 });
56
+ materializePrivacyModelCacheEntry(blobPath(paths, file), target);
57
+ };
58
+ var retryableTransferError = (error) => {
59
+ if (error instanceof TypeError)
60
+ return true;
61
+ const code = error?.code;
62
+ return [
63
+ "ECONNRESET",
64
+ "ECONNREFUSED",
65
+ "ETIMEDOUT",
66
+ "EAI_AGAIN",
67
+ "UND_ERR_SOCKET",
68
+ "UND_ERR_CONNECT_TIMEOUT",
69
+ "UND_ERR_HEADERS_TIMEOUT",
70
+ "UND_ERR_BODY_TIMEOUT"
71
+ ].includes(code ?? "");
72
+ };
73
+ var downloadPrivacyAsset = async (file, temporary, fetcher, options) => {
74
+ const url = `https://huggingface.co/${PRIVACY_MODEL_ID}/resolve/${PRIVACY_MODEL_REVISION}/${file.path}`;
75
+ for (let attempt = 1; attempt <= 3; attempt++) {
76
+ options.signal?.throwIfAborted();
77
+ rmSync(temporary, { force: true });
78
+ const idle = new AbortController();
79
+ let idleTimer;
80
+ const activity = () => {
81
+ clearTimeout(idleTimer);
82
+ idleTimer = setTimeout(() => idle.abort(new Error("Privacy model transfer stalled.")), 3e4);
83
+ };
84
+ activity();
85
+ const signal = options.signal ? AbortSignal.any([options.signal, idle.signal]) : idle.signal;
86
+ try {
87
+ const response = await fetcher(url, { signal });
88
+ if (!response.ok || !response.body) {
89
+ await response.body?.cancel();
90
+ const retryAfter = response.headers.get("retry-after");
91
+ const seconds = retryAfter === null ? NaN : Number(retryAfter);
92
+ const requestedDelay = retryAfter === null ? NaN : Number.isFinite(seconds) ? seconds * 1e3 : Date.parse(retryAfter) - Date.now();
93
+ const retryDelay = Number.isFinite(requestedDelay) ? Math.max(0, requestedDelay) : 250 * attempt;
94
+ if (attempt < 3 && retryDelay <= 3e4 && (response.status === 408 || response.status === 429 || response.status >= 500)) {
95
+ clearTimeout(idleTimer);
96
+ await delay(retryDelay, void 0, options.signal ? { signal: options.signal } : {});
97
+ continue;
98
+ }
99
+ return response.status;
100
+ }
101
+ let transferredBytes = 0;
102
+ let lastProgressAt = 0;
103
+ const headerSize = Number(response.headers.get("content-length"));
104
+ const totalBytes = file.size ?? (Number.isSafeInteger(headerSize) && headerSize > 0 ? headerSize : void 0);
105
+ options.progress?.({
106
+ phase: "model-download",
107
+ transferredBytes,
108
+ ...totalBytes === void 0 ? {} : { totalBytes },
109
+ file: file.path
110
+ });
111
+ const monitor = new Transform({
112
+ transform(chunk, _encoding, callback) {
113
+ activity();
114
+ transferredBytes += chunk.length;
115
+ if (Date.now() - lastProgressAt >= 100) {
116
+ options.progress?.({
117
+ phase: "model-download",
118
+ transferredBytes,
119
+ ...totalBytes === void 0 ? {} : { totalBytes },
120
+ file: file.path
121
+ });
122
+ lastProgressAt = Date.now();
123
+ }
124
+ callback(null, chunk);
125
+ }
126
+ });
127
+ await pipeline(Readable.fromWeb(response.body), monitor, createWriteStream(temporary, { mode: 384 }), { signal });
128
+ options.progress?.({
129
+ phase: "model-download",
130
+ transferredBytes,
131
+ ...totalBytes === void 0 ? {} : { totalBytes },
132
+ file: file.path
133
+ });
134
+ return void 0;
135
+ } catch (error) {
136
+ rmSync(temporary, { force: true });
137
+ options.signal?.throwIfAborted();
138
+ if (!idle.signal.aborted && !retryableTransferError(error))
139
+ throw error;
140
+ if (attempt === 3) {
141
+ throw new Error(`Could not download pinned Privacy Filter model asset ${file.path}: transfer failed after ${attempt} attempts.`, { cause: error });
142
+ }
143
+ clearTimeout(idleTimer);
144
+ await delay(250 * attempt, void 0, options.signal ? { signal: options.signal } : {});
145
+ } finally {
146
+ clearTimeout(idleTimer);
147
+ }
148
+ }
149
+ throw new Error("Privacy Filter model transfer did not complete.");
150
+ };
151
+ var collectPrivacyModelStatus = async (serverPaths, signal) => {
152
+ const paths = resolvePrivacyModelPaths(serverPaths);
153
+ const files = [];
154
+ for (const file of PRIVACY_MODEL_FILES) {
155
+ signal?.throwIfAborted();
156
+ const blob = blobPath(paths, file);
157
+ if (!existsSync(blob)) {
158
+ return {
159
+ ok: false,
160
+ state: "missing",
161
+ message: `Pinned Privacy Filter model asset is missing: ${file.path}.`,
162
+ action: "Run koed models install --kind privacy.",
163
+ modelPath: paths.cacheDir,
164
+ files
165
+ };
166
+ }
167
+ const sizeBytes = statSync(blob).size;
168
+ const actual = await sha256File(blob, signal);
169
+ files.push({ path: file.path, sha256: actual, sizeBytes });
170
+ if (actual !== file.sha256 || file.size !== void 0 && sizeBytes !== file.size) {
171
+ return {
172
+ ok: false,
173
+ state: "checksum_mismatch",
174
+ message: `Pinned Privacy Filter model asset failed verification: ${file.path}.`,
175
+ action: "Run koed models install --kind privacy to replace the invalid content-addressed asset.",
176
+ modelPath: paths.cacheDir,
177
+ files
178
+ };
179
+ }
180
+ materializeCacheEntry(paths, file);
181
+ }
182
+ return {
183
+ ok: true,
184
+ state: "installed",
185
+ message: "Pinned Privacy Filter model assets are installed and verified.",
186
+ modelPath: paths.cacheDir,
187
+ files
188
+ };
189
+ };
190
+ var installPrivacyModel = async (serverPaths, environment = process.env, fetcher = globalThis.fetch.bind(globalThis), options = {}) => {
191
+ if (environment.KOED_DEPENDENCY_MODE?.trim() === "external") {
192
+ return {
193
+ ok: false,
194
+ state: "not_configured",
195
+ message: "Privacy Filter model downloads are disabled in external dependency mode.",
196
+ action: "Run the Operator-managed Privacy Filter Service with its pinned model assets.",
197
+ modelPath: resolvePrivacyModelPaths(serverPaths).cacheDir,
198
+ files: []
199
+ };
200
+ }
201
+ const paths = resolvePrivacyModelPaths(serverPaths);
202
+ mkdirSync(paths.blobsDir, { recursive: true, mode: 448 });
203
+ for (const file of PRIVACY_MODEL_FILES) {
204
+ options.signal?.throwIfAborted();
205
+ const blob = blobPath(paths, file);
206
+ if (existsSync(blob) && await sha256File(blob, options.signal) === file.sha256) {
207
+ materializeCacheEntry(paths, file);
208
+ continue;
209
+ }
210
+ const temporary = `${blob}.${process.pid}.${randomUUID()}.download`;
211
+ try {
212
+ const failedStatus = await downloadPrivacyAsset(file, temporary, fetcher, options);
213
+ if (failedStatus !== void 0) {
214
+ return {
215
+ ok: false,
216
+ state: "missing",
217
+ message: `Could not download pinned Privacy Filter model asset ${file.path} (HTTP ${failedStatus}).`,
218
+ action: "Check network access to huggingface.co and retry.",
219
+ modelPath: paths.cacheDir,
220
+ files: []
221
+ };
222
+ }
223
+ const sizeBytes = statSync(temporary).size;
224
+ options.progress?.({
225
+ phase: "model-verify",
226
+ transferredBytes: sizeBytes,
227
+ totalBytes: sizeBytes,
228
+ file: file.path
229
+ });
230
+ const actual = await sha256File(temporary, options.signal);
231
+ if (actual !== file.sha256 || file.size !== void 0 && sizeBytes !== file.size) {
232
+ return {
233
+ ok: false,
234
+ state: "checksum_mismatch",
235
+ message: `Downloaded Privacy Filter model asset failed verification: ${file.path}.`,
236
+ action: "Do not use the asset; verify the pinned upstream revision and retry.",
237
+ modelPath: paths.cacheDir,
238
+ files: [{ path: file.path, sha256: actual, sizeBytes }]
239
+ };
240
+ }
241
+ rmSync(blob, { force: true });
242
+ renameSync(temporary, blob);
243
+ materializeCacheEntry(paths, file);
244
+ } finally {
245
+ rmSync(temporary, { force: true });
246
+ }
247
+ }
248
+ return collectPrivacyModelStatus(serverPaths, options.signal);
249
+ };
250
+
251
+ export {
252
+ PRIVACY_MODEL_ID,
253
+ PRIVACY_MODEL_REVISION,
254
+ PRIVACY_MODEL_FILES,
255
+ resolvePrivacyModelPaths,
256
+ materializePrivacyModelCacheEntry,
257
+ collectPrivacyModelStatus,
258
+ installPrivacyModel
259
+ };
@@ -0,0 +1,332 @@
1
+ import { createRequire as createKoedRequire } from "node:module"; const require = createKoedRequire(import.meta.url);
2
+ import {
3
+ assertNoReleaseRuntime
4
+ } from "./chunk-YZLQZU5E.js";
5
+ import "./chunk-BTS4ZTF3.js";
6
+
7
+ // packages/koed-server/dist/runtime-homebrew.js
8
+ import { existsSync, mkdirSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
9
+ import { dirname, isAbsolute, resolve } from "node:path";
10
+ import { spawnSync as nodeSpawnSync } from "node:child_process";
11
+ var REQUIRED_PACKAGES = [
12
+ "postgresql@17",
13
+ "pgvector",
14
+ "llama.cpp"
15
+ ];
16
+ var trim = (value) => {
17
+ const trimmed = value?.trim();
18
+ return trimmed ? trimmed : void 0;
19
+ };
20
+ var homebrewCommandCandidates = (platform, environment, exists) => {
21
+ const configuredPrefix = trim(environment.HOMEBREW_PREFIX);
22
+ const configuredCommand = configuredPrefix && isAbsolute(configuredPrefix) ? resolve(configuredPrefix, "bin", "brew") : void 0;
23
+ const platformCommands = platform === "darwin" ? ["/opt/homebrew/bin/brew", "/usr/local/bin/brew"] : platform === "linux" ? ["/home/linuxbrew/.linuxbrew/bin/brew"] : [];
24
+ return [
25
+ .../* @__PURE__ */ new Set([
26
+ ...[configuredCommand, ...platformCommands].filter((command) => Boolean(command && exists(command))),
27
+ "brew"
28
+ ])
29
+ ];
30
+ };
31
+ var run = (command, args, spawnSync) => spawnSync(command, args, {
32
+ encoding: "utf8",
33
+ stdio: ["ignore", "pipe", "pipe"]
34
+ });
35
+ var brewPrefix = (formula, command, spawnSync) => {
36
+ const args = formula ? ["--prefix", formula] : ["--prefix"];
37
+ const result = run(command, args, spawnSync);
38
+ if (result.error) {
39
+ return { ok: false, error: result.error.message };
40
+ }
41
+ if (result.status !== 0) {
42
+ return {
43
+ ok: false,
44
+ error: result.stderr.trim() || `brew ${args.join(" ")} failed`
45
+ };
46
+ }
47
+ return { ok: true, prefix: result.stdout.trim() };
48
+ };
49
+ var resolveHomebrewCommand = (platform, environment, exists, spawnSync) => {
50
+ let error = "Homebrew is not available";
51
+ for (const command of homebrewCommandCandidates(platform, environment, exists)) {
52
+ const result = brewPrefix(null, command, spawnSync);
53
+ if (result.ok && result.prefix) {
54
+ return { ok: true, command, prefix: result.prefix };
55
+ }
56
+ error = result.error ?? error;
57
+ }
58
+ return { ok: false, error };
59
+ };
60
+ var packageStatus = (name, command, spawnSync) => {
61
+ const listed = run(command, ["list", "--versions", name], spawnSync);
62
+ if (listed.error || listed.status !== 0 || !listed.stdout.trim()) {
63
+ return {
64
+ name,
65
+ installed: false,
66
+ missing: [
67
+ listed.stderr.trim() || listed.error?.message || "not installed"
68
+ ]
69
+ };
70
+ }
71
+ const result = brewPrefix(name, command, spawnSync);
72
+ return result.ok && result.prefix ? { name, installed: true, prefix: result.prefix } : { name, installed: false, missing: [result.error ?? "not installed"] };
73
+ };
74
+ var binary = (paths, key, path, exists) => {
75
+ paths[key] = path;
76
+ return { path, exists: exists(path) };
77
+ };
78
+ var candidatePgvectorControlPaths = (postgresPrefix, pgvectorPrefix, pgSharedir2) => [
79
+ pgSharedir2 ? resolve(pgSharedir2, "extension", "vector.control") : void 0,
80
+ postgresPrefix ? resolve(postgresPrefix, "share", "postgresql@17", "extension", "vector.control") : void 0,
81
+ postgresPrefix ? resolve(postgresPrefix, "share", "postgresql", "extension", "vector.control") : void 0,
82
+ pgvectorPrefix ? resolve(pgvectorPrefix, "share", "postgresql@17", "extension", "vector.control") : void 0,
83
+ pgvectorPrefix ? resolve(pgvectorPrefix, "share", "postgresql", "extension", "vector.control") : void 0
84
+ ].filter((value) => Boolean(value));
85
+ var candidatePgvectorSqlPaths = (controlPath) => controlPath ? [resolve(dirname(controlPath), "vector--*.sql")] : [];
86
+ var pgSharedir = (pgConfigBin, exists, spawnSync) => {
87
+ if (!exists(pgConfigBin))
88
+ return void 0;
89
+ const result = run(pgConfigBin, ["--sharedir"], spawnSync);
90
+ if (result.status !== 0 || result.error)
91
+ return void 0;
92
+ return trim(result.stdout);
93
+ };
94
+ var runtimePaths = (paths) => ({
95
+ postgresBinDir: resolve(paths.koedHome, "runtime", "postgres", "bin"),
96
+ llamaServerBin: resolve(paths.koedHome, "runtime", "llama.cpp", "llama-server"),
97
+ metadataPath: resolve(paths.cacheDir, "runtime-homebrew.json")
98
+ });
99
+ var emptyBinaries = () => ({
100
+ initdb: { path: "", exists: false },
101
+ pg_ctl: { path: "", exists: false },
102
+ psql: { path: "", exists: false },
103
+ pg_dump: { path: "", exists: false },
104
+ pg_restore: { path: "", exists: false },
105
+ pg_config: { path: "", exists: false },
106
+ llama_server: { path: "", exists: false }
107
+ });
108
+ var binaryEntries = (binaries) => Object.entries(binaries);
109
+ var isSupportedHomebrewPlatform = (platform) => platform === "darwin" || platform === "linux";
110
+ var statusFrom = ({ paths, platform, environment, exists, spawnSync }) => {
111
+ const koedRuntime = runtimePaths(paths);
112
+ if (!isSupportedHomebrewPlatform(platform)) {
113
+ return {
114
+ ok: false,
115
+ state: "not_supported",
116
+ provider: "homebrew",
117
+ platform,
118
+ koedHome: paths.koedHome,
119
+ homebrew: { installed: false },
120
+ packages: [],
121
+ binaries: emptyBinaries(),
122
+ pgvector: { compatible: false, sqlPaths: [], missing: ["macOS/Linux"] },
123
+ koedRuntime: { ...koedRuntime, linked: false },
124
+ message: "Homebrew-backed bundled-local runtime provisioning is supported on macOS, Linux, and WSL only.",
125
+ action: "Use external dependency mode or a supported Homebrew/Linuxbrew environment on macOS, Linux, or WSL."
126
+ };
127
+ }
128
+ const homebrew = resolveHomebrewCommand(platform, environment, exists, spawnSync);
129
+ if (!homebrew.ok) {
130
+ return {
131
+ ok: false,
132
+ state: "missing",
133
+ provider: "homebrew",
134
+ platform,
135
+ koedHome: paths.koedHome,
136
+ homebrew: { installed: false, error: homebrew.error },
137
+ packages: REQUIRED_PACKAGES.map((name) => ({
138
+ name,
139
+ installed: false,
140
+ missing: ["Homebrew is not available"]
141
+ })),
142
+ binaries: emptyBinaries(),
143
+ pgvector: { compatible: false, sqlPaths: [], missing: ["Homebrew"] },
144
+ koedRuntime: { ...koedRuntime, linked: false },
145
+ message: "Homebrew is required for Homebrew-backed bundled-local runtime provisioning.",
146
+ action: "Install Homebrew or Linuxbrew on macOS, Linux, or WSL, then run koed runtime install --provider homebrew --dependency-mode bundled-local --json."
147
+ };
148
+ }
149
+ const command = homebrew.command;
150
+ const packages = REQUIRED_PACKAGES.map((name) => packageStatus(name, command, spawnSync));
151
+ const postgres = packages.find((pkg) => pkg.name === "postgresql@17");
152
+ const pgvectorPackage = packages.find((pkg) => pkg.name === "pgvector");
153
+ const llama = packages.find((pkg) => pkg.name === "llama.cpp");
154
+ const binaryPaths = {};
155
+ const postgresBin = (name) => postgres?.prefix ? resolve(postgres.prefix, "bin", name) : "";
156
+ const llamaBin = (name) => llama?.prefix ? resolve(llama.prefix, "bin", name) : "";
157
+ const binaries = {
158
+ initdb: binary(binaryPaths, "initdb", postgresBin("initdb"), exists),
159
+ pg_ctl: binary(binaryPaths, "pg_ctl", postgresBin("pg_ctl"), exists),
160
+ psql: binary(binaryPaths, "psql", postgresBin("psql"), exists),
161
+ pg_dump: binary(binaryPaths, "pg_dump", postgresBin("pg_dump"), exists),
162
+ pg_restore: binary(binaryPaths, "pg_restore", postgresBin("pg_restore"), exists),
163
+ pg_config: binary(binaryPaths, "pg_config", postgresBin("pg_config"), exists),
164
+ llama_server: binary(binaryPaths, "llama_server", llamaBin("llama-server"), exists)
165
+ };
166
+ const sharedir = pgSharedir(binaries.pg_config.path, exists, spawnSync);
167
+ const controlPath = candidatePgvectorControlPaths(postgres?.prefix, pgvectorPackage?.prefix, sharedir).find((candidate) => exists(candidate));
168
+ const missing = [
169
+ ...packages.flatMap((pkg) => pkg.installed ? [] : [pkg.name]),
170
+ ...binaryEntries(binaries).flatMap(([name, info]) => info.exists ? [] : [name]),
171
+ ...controlPath ? [] : ["pgvector extension files"]
172
+ ];
173
+ const linked = exists(resolve(koedRuntime.postgresBinDir, "initdb")) && exists(resolve(koedRuntime.postgresBinDir, "pg_ctl")) && exists(resolve(koedRuntime.postgresBinDir, "psql")) && exists(resolve(koedRuntime.postgresBinDir, "pg_dump")) && exists(resolve(koedRuntime.postgresBinDir, "pg_restore")) && exists(koedRuntime.llamaServerBin);
174
+ const ok = missing.length === 0 && linked;
175
+ return {
176
+ ok,
177
+ state: ok ? "installed" : missing.length === 0 ? "missing" : "missing",
178
+ provider: "homebrew",
179
+ platform,
180
+ koedHome: paths.koedHome,
181
+ homebrew: { installed: true, prefix: homebrew.prefix },
182
+ packages,
183
+ binaries,
184
+ pgvector: {
185
+ compatible: Boolean(controlPath),
186
+ controlPath,
187
+ sqlPaths: candidatePgvectorSqlPaths(controlPath),
188
+ ...controlPath ? {} : { missing: ["vector.control"] }
189
+ },
190
+ koedRuntime: { ...koedRuntime, linked },
191
+ message: ok ? "Homebrew-backed bundled-local runtime is installed under KOED_HOME." : "Homebrew-backed bundled-local runtime is missing required assets or KOED_HOME links.",
192
+ action: ok ? void 0 : "Run koed runtime install --provider homebrew --dependency-mode bundled-local --json."
193
+ };
194
+ };
195
+ var collectHomebrewRuntimeStatus = (paths, environment = process.env, dependencies = {}) => {
196
+ return statusFrom({
197
+ paths,
198
+ platform: dependencies.platform ?? process.platform,
199
+ environment,
200
+ exists: dependencies.existsSync ?? existsSync,
201
+ spawnSync: dependencies.spawnSync ?? nodeSpawnSync
202
+ });
203
+ };
204
+ var linkRuntimePath = (source, target, koedHome, deps) => {
205
+ const resolvedTarget = resolve(target);
206
+ const resolvedKoedHome = resolve(koedHome);
207
+ if (resolvedTarget !== resolvedKoedHome && !resolvedTarget.startsWith(`${resolvedKoedHome}/`)) {
208
+ throw new Error(`Refusing to link runtime asset outside KOED_HOME: ${target}`);
209
+ }
210
+ deps.mkdirSync(dirname(resolvedTarget), { recursive: true, mode: 448 });
211
+ deps.rmSync(resolvedTarget, { force: true });
212
+ deps.symlinkSync(source, resolvedTarget);
213
+ };
214
+ var installHomebrewRuntime = (paths, environment = process.env, dependencies = {}) => {
215
+ assertNoReleaseRuntime(paths);
216
+ const deps = {
217
+ platform: dependencies.platform ?? process.platform,
218
+ existsSync: dependencies.existsSync ?? existsSync,
219
+ mkdirSync: dependencies.mkdirSync ?? mkdirSync,
220
+ rmSync: dependencies.rmSync ?? rmSync,
221
+ symlinkSync: dependencies.symlinkSync ?? symlinkSync,
222
+ writeFileSync: dependencies.writeFileSync ?? writeFileSync,
223
+ readFileSync: dependencies.readFileSync ?? readFileSync,
224
+ spawnSync: dependencies.spawnSync ?? nodeSpawnSync
225
+ };
226
+ const before = collectHomebrewRuntimeStatus(paths, environment, deps);
227
+ if (before.state === "not_supported") {
228
+ return { ...before, installedPackages: [], linkedPaths: [] };
229
+ }
230
+ if (!before.homebrew.installed) {
231
+ return {
232
+ ...before,
233
+ state: "needs_attention",
234
+ message: "Homebrew is required before installing bundled-local runtime assets.",
235
+ action: "Install Homebrew or Linuxbrew on macOS, Linux, or WSL, then rerun koed runtime install --provider homebrew --dependency-mode bundled-local --json.",
236
+ installedPackages: [],
237
+ linkedPaths: []
238
+ };
239
+ }
240
+ const missingPackages = before.packages.filter((pkg) => !pkg.installed).map((pkg) => pkg.name);
241
+ if (missingPackages.length > 0) {
242
+ const homebrew = resolveHomebrewCommand(deps.platform, environment, deps.existsSync, deps.spawnSync);
243
+ if (!homebrew.ok) {
244
+ return {
245
+ ...before,
246
+ state: "needs_attention",
247
+ message: "Homebrew became unavailable before package installation.",
248
+ action: homebrew.error,
249
+ installedPackages: [],
250
+ linkedPaths: []
251
+ };
252
+ }
253
+ const result = run(homebrew.command, ["install", ...missingPackages], deps.spawnSync);
254
+ if (result.error || result.status !== 0) {
255
+ return {
256
+ ...before,
257
+ state: "needs_attention",
258
+ message: "Homebrew package installation failed.",
259
+ action: result.stderr.trim() || result.error?.message || "Inspect Homebrew output and retry.",
260
+ installedPackages: [],
261
+ linkedPaths: []
262
+ };
263
+ }
264
+ }
265
+ const afterInstall = collectHomebrewRuntimeStatus(paths, environment, deps);
266
+ const missingAfterInstall = [
267
+ ...afterInstall.packages.flatMap((pkg) => pkg.installed ? [] : [pkg.name]),
268
+ ...binaryEntries(afterInstall.binaries).flatMap(([name, info]) => info.exists ? [] : [name]),
269
+ ...afterInstall.pgvector.compatible ? [] : ["pgvector"]
270
+ ];
271
+ if (missingAfterInstall.length > 0) {
272
+ return {
273
+ ...afterInstall,
274
+ state: "needs_attention",
275
+ message: `Homebrew runtime assets are still missing: ${missingAfterInstall.join(", ")}.`,
276
+ installedPackages: missingPackages,
277
+ linkedPaths: []
278
+ };
279
+ }
280
+ const linkedPaths = [
281
+ [
282
+ afterInstall.binaries.initdb.path,
283
+ resolve(afterInstall.koedRuntime.postgresBinDir, "initdb")
284
+ ],
285
+ [
286
+ afterInstall.binaries.pg_ctl.path,
287
+ resolve(afterInstall.koedRuntime.postgresBinDir, "pg_ctl")
288
+ ],
289
+ [
290
+ afterInstall.binaries.psql.path,
291
+ resolve(afterInstall.koedRuntime.postgresBinDir, "psql")
292
+ ],
293
+ [
294
+ afterInstall.binaries.pg_dump.path,
295
+ resolve(afterInstall.koedRuntime.postgresBinDir, "pg_dump")
296
+ ],
297
+ [
298
+ afterInstall.binaries.pg_restore.path,
299
+ resolve(afterInstall.koedRuntime.postgresBinDir, "pg_restore")
300
+ ],
301
+ [
302
+ afterInstall.binaries.pg_config.path,
303
+ resolve(afterInstall.koedRuntime.postgresBinDir, "pg_config")
304
+ ],
305
+ [
306
+ afterInstall.binaries.llama_server.path,
307
+ afterInstall.koedRuntime.llamaServerBin
308
+ ]
309
+ ];
310
+ for (const [source, target] of linkedPaths) {
311
+ linkRuntimePath(source, target, paths.koedHome, deps);
312
+ }
313
+ deps.mkdirSync(paths.cacheDir, { recursive: true, mode: 448 });
314
+ deps.writeFileSync(afterInstall.koedRuntime.metadataPath, `${JSON.stringify({
315
+ provider: "homebrew",
316
+ installedAt: (/* @__PURE__ */ new Date()).toISOString(),
317
+ packages: afterInstall.packages,
318
+ binaries: afterInstall.binaries,
319
+ pgvector: afterInstall.pgvector
320
+ }, null, 2)}
321
+ `, { mode: 384 });
322
+ const finalStatus = collectHomebrewRuntimeStatus(paths, environment, deps);
323
+ return {
324
+ ...finalStatus,
325
+ installedPackages: missingPackages,
326
+ linkedPaths: linkedPaths.map(([, target]) => target)
327
+ };
328
+ };
329
+ export {
330
+ collectHomebrewRuntimeStatus,
331
+ installHomebrewRuntime
332
+ };