@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,73 @@
1
+ import { createRequire as createKoedRequire } from "node:module"; const require = createKoedRequire(import.meta.url);
2
+ import {
3
+ resolveKoedServerConfig
4
+ } from "./chunk-ALJUSOF7.js";
5
+ import {
6
+ parseEnvFile
7
+ } from "./chunk-W2HNI6AA.js";
8
+ import {
9
+ resolveTeamCollaborationEnabled
10
+ } from "./chunk-ZOHNXUDY.js";
11
+
12
+ // packages/koed-server/dist/effective-runtime-config.js
13
+ import { existsSync, readFileSync } from "node:fs";
14
+ import { resolve } from "node:path";
15
+ function resolveEffectiveRuntimeConfig(paths, environment, execution) {
16
+ const envPath = environment.KOED_ENV_PATH?.trim() ? resolve(environment.KOED_ENV_PATH) : execution === "source" ? resolve(paths.repoRoot, ".env") : void 0;
17
+ let fileEnvironment = {};
18
+ if (envPath) {
19
+ if (!existsSync(envPath)) {
20
+ if (environment.KOED_ENV_PATH?.trim()) {
21
+ throw new Error(`Explicit environment file does not exist: ${envPath}`);
22
+ }
23
+ } else {
24
+ fileEnvironment = parseEnvFile(readFileSync(envPath, "utf8"), {
25
+ strict: Boolean(environment.KOED_ENV_PATH?.trim()),
26
+ source: envPath
27
+ });
28
+ }
29
+ }
30
+ const effectiveEnvironment = { ...fileEnvironment, ...environment };
31
+ const config = resolveKoedServerConfig(paths, effectiveEnvironment, {
32
+ strict: execution === "packaged" || Boolean(environment.KOED_ENV_PATH?.trim())
33
+ });
34
+ return {
35
+ config,
36
+ environment: effectiveEnvironment,
37
+ teamEnabled: resolveTeamCollaborationEnabled(effectiveEnvironment),
38
+ explicitWorkQueueBackend: environment.WORK_QUEUE_BACKEND?.trim() || null
39
+ };
40
+ }
41
+ function calculateRuntimeRequirements(effective) {
42
+ const localPrivacy = effective.config.dependencyMode === "bundled-local" && effective.teamEnabled;
43
+ const components = localPrivacy ? ["base", "privacy"] : ["base"];
44
+ const processes = [
45
+ "api",
46
+ "worker"
47
+ ];
48
+ if (effective.config.runtimeMode !== "external")
49
+ processes.push("local-ai-runtime");
50
+ if (effective.config.dependencyMode === "bundled-local") {
51
+ processes.push("postgres", "embedding-service");
52
+ if (localPrivacy)
53
+ processes.push("privacy-service");
54
+ }
55
+ const bundled = effective.config.dependencyMode === "bundled-local";
56
+ const queueValue = effective.explicitWorkQueueBackend === null ? bundled ? void 0 : effective.environment.WORK_QUEUE_BACKEND?.trim() : effective.explicitWorkQueueBackend ?? effective.environment.WORK_QUEUE_BACKEND?.trim();
57
+ if (queueValue && queueValue !== "local" && queueValue !== "bullmq") {
58
+ throw new Error('WORK_QUEUE_BACKEND must be "local" or "bullmq"');
59
+ }
60
+ const queue = queueValue === "local" || queueValue === "bullmq" ? queueValue : effective.config.dependencyMode === "bundled-local" ? "local" : "bullmq";
61
+ return {
62
+ components,
63
+ processes,
64
+ queue,
65
+ native: bundled ? ["postgres", "llama-server"] : [],
66
+ models: bundled ? localPrivacy ? ["embedding", "privacy"] : ["embedding"] : []
67
+ };
68
+ }
69
+
70
+ export {
71
+ resolveEffectiveRuntimeConfig,
72
+ calculateRuntimeRequirements
73
+ };
@@ -0,0 +1,35 @@
1
+ import { createRequire as createKoedRequire } from "node:module"; const require = createKoedRequire(import.meta.url);
2
+ import {
3
+ clearUpstreamBackendCapabilities,
4
+ collectUpstreamRegistryStatus,
5
+ getActiveUpstreamBackend,
6
+ listUpstreamBackends,
7
+ refreshUpstreamBackendCapabilities,
8
+ registerUpstreamBackend,
9
+ removeUpstreamBackend,
10
+ setActiveUpstreamBackend,
11
+ updateUpstreamBackendCredential,
12
+ updateUpstreamBackendRoutePolicy,
13
+ upstreamBackendAdvertisesCapability,
14
+ upstreamBackendSupportsTeamMemoryAnswerTasks
15
+ } from "./chunk-RCR4XPE3.js";
16
+ import {
17
+ isTeamMemoryAnswerTaskCapability
18
+ } from "./chunk-ZOHNXUDY.js";
19
+ import "./chunk-FSNLU46W.js";
20
+ import "./chunk-BTS4ZTF3.js";
21
+ export {
22
+ clearUpstreamBackendCapabilities,
23
+ collectUpstreamRegistryStatus,
24
+ getActiveUpstreamBackend,
25
+ isTeamMemoryAnswerTaskCapability,
26
+ listUpstreamBackends,
27
+ refreshUpstreamBackendCapabilities,
28
+ registerUpstreamBackend,
29
+ removeUpstreamBackend,
30
+ setActiveUpstreamBackend,
31
+ updateUpstreamBackendCredential,
32
+ updateUpstreamBackendRoutePolicy,
33
+ upstreamBackendAdvertisesCapability,
34
+ upstreamBackendSupportsTeamMemoryAnswerTasks
35
+ };
@@ -0,0 +1,242 @@
1
+ import { createRequire as createKoedRequire } from "node:module"; const require = createKoedRequire(import.meta.url);
2
+ import {
3
+ require_proper_lockfile
4
+ } from "./chunk-7NXKPDF3.js";
5
+ import {
6
+ createPlatformHostProofStore,
7
+ deviceIdentityStatePathFor,
8
+ deviceProofFingerprint,
9
+ hostProofReferenceFor,
10
+ inspectDeviceIdentity,
11
+ serializeHostProof
12
+ } from "./chunk-ZOHNXUDY.js";
13
+ import {
14
+ __toESM
15
+ } from "./chunk-BTS4ZTF3.js";
16
+
17
+ // packages/koed-server/dist/device-identity.js
18
+ var import_proper_lockfile = __toESM(require_proper_lockfile(), 1);
19
+ import { randomBytes, randomUUID } from "node:crypto";
20
+ import { existsSync, lstatSync, mkdirSync, realpathSync, renameSync, rmSync, writeFileSync } from "node:fs";
21
+ import { resolve } from "node:path";
22
+ var lockStaleMs = 3e4;
23
+ var defaultProof = () => randomBytes(32).toString("base64url");
24
+ var testProofDirectory = (paths) => {
25
+ const proofRoot = resolve(`${paths.koedHome}-proof-root`);
26
+ mkdirSync(proofRoot, { recursive: true, mode: 448 });
27
+ return resolve(proofRoot, "proof");
28
+ };
29
+ var dependencies = (paths, deps) => {
30
+ const environment = deps.environment ?? process.env;
31
+ return {
32
+ environment,
33
+ proofStore: deps.proofStore ?? createPlatformHostProofStore({
34
+ koedHome: paths.koedHome,
35
+ environment: environment.NODE_ENV === "test" ? {
36
+ ...environment,
37
+ KOED_DEVICE_PROOF_DIR: testProofDirectory(paths)
38
+ } : environment
39
+ }),
40
+ now: deps.now ?? (() => /* @__PURE__ */ new Date()),
41
+ randomId: deps.randomId ?? randomUUID,
42
+ randomProof: deps.randomProof ?? defaultProof,
43
+ onPhase: deps.onPhase ?? (() => void 0)
44
+ };
45
+ };
46
+ var lockTarget = (paths) => resolve(paths.runDir, "device-identity");
47
+ var bootstrapTombstonePath = (paths) => resolve(paths.configDir, "device-identity-bootstrap.json");
48
+ var withDeviceIdentityLock = async (paths, mutation) => {
49
+ mkdirSync(paths.runDir, { recursive: true, mode: 448 });
50
+ const release = await import_proper_lockfile.default.lock(lockTarget(paths), {
51
+ realpath: false,
52
+ stale: lockStaleMs,
53
+ update: lockStaleMs / 3,
54
+ retries: {
55
+ retries: 100,
56
+ factor: 1,
57
+ minTimeout: 25,
58
+ maxTimeout: 100,
59
+ randomize: true
60
+ }
61
+ });
62
+ try {
63
+ return await mutation();
64
+ } finally {
65
+ await release();
66
+ }
67
+ };
68
+ var writeState = (statePath, state) => {
69
+ mkdirSync(resolve(statePath, ".."), { recursive: true, mode: 448 });
70
+ const temporary = `${statePath}.${randomUUID()}.tmp`;
71
+ try {
72
+ writeFileSync(temporary, `${JSON.stringify(state, null, 2)}
73
+ `, {
74
+ mode: 384,
75
+ flag: "wx"
76
+ });
77
+ renameSync(temporary, statePath);
78
+ } finally {
79
+ rmSync(temporary, { force: true });
80
+ }
81
+ };
82
+ var prepareIdentityStorage = (paths) => {
83
+ mkdirSync(paths.koedHome, { recursive: true, mode: 448 });
84
+ if (lstatSync(paths.koedHome).isSymbolicLink()) {
85
+ throw new Error("KOED_HOME must not be a symbolic link.");
86
+ }
87
+ mkdirSync(paths.configDir, { recursive: true, mode: 448 });
88
+ if (lstatSync(paths.configDir).isSymbolicLink()) {
89
+ throw new Error("Device identity config directory must not be a symbolic link.");
90
+ }
91
+ return realpathSync(paths.koedHome);
92
+ };
93
+ var writeBootstrapTombstone = (paths, now) => {
94
+ const tombstonePath = bootstrapTombstonePath(paths);
95
+ if (existsSync(tombstonePath))
96
+ return;
97
+ const temporary = `${tombstonePath}.${randomUUID()}.tmp`;
98
+ try {
99
+ writeFileSync(temporary, `${JSON.stringify({ schemaVersion: 1, initializedAt: now.toISOString() })}
100
+ `, { mode: 384, flag: "wx" });
101
+ renameSync(temporary, tombstonePath);
102
+ } finally {
103
+ rmSync(temporary, { force: true });
104
+ }
105
+ };
106
+ var newIdentityState = (now, randomId, randomProof, remoteOperations, deploymentId = randomId(), pendingRemoteRevocation = false) => {
107
+ const deviceInstanceId = randomId();
108
+ const proof = randomProof();
109
+ const timestamp = now.toISOString();
110
+ return {
111
+ state: {
112
+ schemaVersion: 1,
113
+ deploymentId,
114
+ deviceInstanceId,
115
+ proof: {
116
+ reference: hostProofReferenceFor(deviceInstanceId),
117
+ fingerprint: deviceProofFingerprint(proof)
118
+ },
119
+ remoteOperations,
120
+ deploymentIdentityAdoptionPending: true,
121
+ ...pendingRemoteRevocation ? { pendingRemoteRevocation: true } : {},
122
+ createdAt: timestamp,
123
+ updatedAt: timestamp
124
+ },
125
+ proof
126
+ };
127
+ };
128
+ var result = (identity, options = {}) => ({
129
+ ...identity,
130
+ initialized: options.initialized ?? false,
131
+ rotated: options.rotated ?? false,
132
+ ...options.referencesInvalidated === void 0 ? {} : { referencesInvalidated: options.referencesInvalidated }
133
+ });
134
+ var inspect = (paths, proofStore) => inspectDeviceIdentity({
135
+ statePath: deviceIdentityStatePathFor(paths.koedHome),
136
+ proofStore
137
+ });
138
+ var inspectDeviceIdentityStatus = (paths, deps = {}) => {
139
+ const resolved = dependencies(paths, deps);
140
+ return Promise.resolve(result(inspect(paths, resolved.proofStore)));
141
+ };
142
+ var ensureDeviceIdentity = async (paths, deps = {}) => {
143
+ const resolved = dependencies(paths, deps);
144
+ return withDeviceIdentityLock(paths, () => {
145
+ try {
146
+ const canonicalKoedHome = prepareIdentityStorage(paths);
147
+ const current = inspect(paths, resolved.proofStore);
148
+ if (current.health !== "missing_state")
149
+ return result(current);
150
+ if (existsSync(bootstrapTombstonePath(paths)))
151
+ return result(current);
152
+ writeBootstrapTombstone(paths, resolved.now());
153
+ resolved.onPhase("tombstone");
154
+ const next = newIdentityState(resolved.now(), resolved.randomId, resolved.randomProof, "repair_required");
155
+ resolved.proofStore.write(next.state.proof.reference, serializeHostProof({
156
+ deploymentId: next.state.deploymentId,
157
+ deviceInstanceId: next.state.deviceInstanceId,
158
+ proof: next.proof,
159
+ canonicalKoedHome
160
+ }));
161
+ resolved.onPhase("proof");
162
+ writeState(deviceIdentityStatePathFor(paths.koedHome), next.state);
163
+ resolved.onPhase("state");
164
+ writeState(deviceIdentityStatePathFor(paths.koedHome), {
165
+ ...next.state,
166
+ remoteOperations: "enabled",
167
+ updatedAt: resolved.now().toISOString()
168
+ });
169
+ return result(inspect(paths, resolved.proofStore), { initialized: true });
170
+ } catch {
171
+ return result(inspect(paths, resolved.proofStore));
172
+ }
173
+ });
174
+ };
175
+ var rotateDeviceIdentity = async (paths, options) => {
176
+ const resolved = dependencies(paths, options.dependencies ?? {});
177
+ return withDeviceIdentityLock(paths, async () => {
178
+ let canonicalKoedHome;
179
+ try {
180
+ canonicalKoedHome = prepareIdentityStorage(paths);
181
+ } catch {
182
+ return result(inspect(paths, resolved.proofStore), { rotated: false });
183
+ }
184
+ const previous = inspect(paths, resolved.proofStore);
185
+ const previousReference = previous.deviceInstanceId ? hostProofReferenceFor(previous.deviceInstanceId) : null;
186
+ const next = newIdentityState(resolved.now(), resolved.randomId, resolved.randomProof, "repair_required", previous.deploymentId ?? void 0, true);
187
+ delete next.state.deploymentIdentityAdoptionPending;
188
+ try {
189
+ writeBootstrapTombstone(paths, resolved.now());
190
+ resolved.proofStore.write(next.state.proof.reference, serializeHostProof({
191
+ deploymentId: next.state.deploymentId,
192
+ deviceInstanceId: next.state.deviceInstanceId,
193
+ proof: next.proof,
194
+ canonicalKoedHome
195
+ }));
196
+ writeState(deviceIdentityStatePathFor(paths.koedHome), next.state);
197
+ } catch {
198
+ return result(inspect(paths, resolved.proofStore), { rotated: false });
199
+ }
200
+ try {
201
+ const invalidation = await options.invalidateRemoteReferences();
202
+ if (invalidation?.pendingRemoteRevocation) {
203
+ return result(inspect(paths, resolved.proofStore), {
204
+ rotated: true,
205
+ referencesInvalidated: false
206
+ });
207
+ }
208
+ } catch {
209
+ return result(inspect(paths, resolved.proofStore), {
210
+ rotated: true,
211
+ referencesInvalidated: false
212
+ });
213
+ }
214
+ const completed = {
215
+ ...next.state,
216
+ remoteOperations: "enabled",
217
+ updatedAt: resolved.now().toISOString()
218
+ };
219
+ delete completed.pendingRemoteRevocation;
220
+ try {
221
+ writeState(deviceIdentityStatePathFor(paths.koedHome), completed);
222
+ if (previousReference && previousReference !== completed.proof.reference) {
223
+ resolved.proofStore.remove(previousReference);
224
+ }
225
+ return result(inspect(paths, resolved.proofStore), {
226
+ rotated: true,
227
+ referencesInvalidated: true
228
+ });
229
+ } catch {
230
+ return result(inspect(paths, resolved.proofStore), {
231
+ rotated: true,
232
+ referencesInvalidated: false
233
+ });
234
+ }
235
+ });
236
+ };
237
+
238
+ export {
239
+ inspectDeviceIdentityStatus,
240
+ ensureDeviceIdentity,
241
+ rotateDeviceIdentity
242
+ };
@@ -0,0 +1,124 @@
1
+ import { createRequire as createKoedRequire } from "node:module"; const require = createKoedRequire(import.meta.url);
2
+ import {
3
+ require_proper_lockfile
4
+ } from "./chunk-7NXKPDF3.js";
5
+ import {
6
+ __toESM
7
+ } from "./chunk-BTS4ZTF3.js";
8
+
9
+ // packages/koed-server/dist/file-lock.js
10
+ var import_proper_lockfile = __toESM(require_proper_lockfile(), 1);
11
+ import { mkdirSync } from "node:fs";
12
+ import { dirname } from "node:path";
13
+ var withFileLock = (file, operation) => {
14
+ mkdirSync(dirname(file), { recursive: true, mode: 448 });
15
+ const deadline = Date.now() + 5e3;
16
+ let release;
17
+ while (true) {
18
+ try {
19
+ release = import_proper_lockfile.default.lockSync(file, { realpath: false, stale: 3e4 });
20
+ break;
21
+ } catch (error) {
22
+ if (error.code !== "ELOCKED" || Date.now() >= deadline)
23
+ throw error;
24
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 10);
25
+ }
26
+ }
27
+ try {
28
+ return operation();
29
+ } finally {
30
+ release();
31
+ }
32
+ };
33
+
34
+ // packages/koed-server/dist/runtime-state.js
35
+ import { randomUUID } from "node:crypto";
36
+ import { readFileSync as nodeReadFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
37
+
38
+ // packages/koed-server/dist/process-liveness.js
39
+ var isProcessRunning = (pid) => {
40
+ try {
41
+ process.kill(pid, 0);
42
+ return true;
43
+ } catch {
44
+ return false;
45
+ }
46
+ };
47
+
48
+ // packages/koed-server/dist/runtime-state.js
49
+ var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
50
+ var validHttpUrl = (value) => {
51
+ if (typeof value !== "string")
52
+ return false;
53
+ try {
54
+ return ["http:", "https:"].includes(new URL(value).protocol);
55
+ } catch {
56
+ return false;
57
+ }
58
+ };
59
+ var validProcessMap = (value) => value === void 0 || isRecord(value) && Object.values(value).every((pid) => typeof pid === "number" && Number.isInteger(pid) && pid >= 0);
60
+ var validIdentityMap = (value) => value === void 0 || isRecord(value) && Object.values(value).every((identity) => typeof identity === "string" && identity.length > 0);
61
+ var validRuntimeState = (value) => {
62
+ if (!isRecord(value))
63
+ return false;
64
+ const validRuntimeMode = value.runtimeMode === void 0 || value.runtimeMode === "local-personal" || value.runtimeMode === "external" || value.runtimeMode === "developer";
65
+ const validDependencyMode = value.dependencyMode === void 0 || value.dependencyMode === "bundled-local" || value.dependencyMode === "external";
66
+ const validAutomaticPorts = value.automaticPorts === void 0 || typeof value.automaticPorts === "boolean";
67
+ return typeof value.pid === "number" && Number.isInteger(value.pid) && value.pid > 0 && typeof value.startedAt === "string" && !Number.isNaN(Date.parse(value.startedAt)) && typeof value.repoRoot === "string" && Boolean(value.repoRoot.trim()) && validHttpUrl(value.apiUrl) && Array.isArray(value.services) && value.services.every((service) => typeof service === "string") && validRuntimeMode && validDependencyMode && validAutomaticPorts && validProcessMap(value.processes) && validIdentityMap(value.processIdentities);
68
+ };
69
+ var isRuntimeGenerationState = (value) => isRecord(value) && (Object.keys(value).length === 7 || Object.keys(value).length === 8 && ["manifest-pinned-store", "signed-store", "desktop-bundle"].includes(String(value.source))) && value.schemaVersion === 1 && typeof value.generationId === "string" && /^[a-f0-9]{64}$/.test(value.generationId) && typeof value.pid === "number" && Number.isInteger(value.pid) && value.pid > 0 && typeof value.processIdentity === "string" && value.processIdentity.length > 0 && typeof value.startedAt === "string" && !Number.isNaN(Date.parse(value.startedAt)) && isRecord(value.owner) && Object.keys(value.owner).length === 2 && ["cli", "desktop", "standalone"].includes(String(value.owner.kind)) && typeof value.owner.installationId === "string" && /^[A-Za-z0-9._-]{1,128}$/.test(value.owner.installationId) && typeof value.pinToken === "string" && /^[a-f0-9]{64}$/.test(value.pinToken);
70
+ function writeRuntimeState(path, state) {
71
+ withFileLock(path, () => {
72
+ const temporary = `${path}.${randomUUID()}.tmp`;
73
+ try {
74
+ writeFileSync(temporary, `${JSON.stringify(state, null, 2)}
75
+ `, {
76
+ flag: "wx",
77
+ mode: 384
78
+ });
79
+ renameSync(temporary, path);
80
+ } finally {
81
+ rmSync(temporary, { force: true });
82
+ }
83
+ });
84
+ }
85
+ function removeOwnedRuntimeState(path, owner, read = nodeReadFileSync, remove = rmSync) {
86
+ return withFileLock(path, () => {
87
+ let contents;
88
+ try {
89
+ contents = read(path, "utf8");
90
+ } catch (error) {
91
+ if (error.code === "ENOENT")
92
+ return true;
93
+ throw error;
94
+ }
95
+ const state = JSON.parse(contents);
96
+ if (!isRecord(state) || state.pid !== owner.pid || state.startedAt !== owner.startedAt)
97
+ return false;
98
+ remove(path, { force: true });
99
+ return true;
100
+ });
101
+ }
102
+ var readActiveRuntimeState = (path, readFileSync = nodeReadFileSync, checkPid = isProcessRunning) => {
103
+ try {
104
+ const parsed = JSON.parse(String(readFileSync(path, "utf8")));
105
+ return validRuntimeState(parsed) && checkPid(parsed.pid) ? parsed : null;
106
+ } catch {
107
+ return null;
108
+ }
109
+ };
110
+ var applyActiveRuntimeUrls = (environment, runtime) => ({
111
+ ...environment,
112
+ ...runtime?.apiUrl ? { MEMORY_API_URL: runtime.apiUrl } : {},
113
+ ...runtime?.automaticPorts ? { KOED_AUTO_PORTS: "1" } : {}
114
+ });
115
+
116
+ export {
117
+ isProcessRunning,
118
+ withFileLock,
119
+ isRuntimeGenerationState,
120
+ writeRuntimeState,
121
+ removeOwnedRuntimeState,
122
+ readActiveRuntimeState,
123
+ applyActiveRuntimeUrls
124
+ };
@@ -0,0 +1,23 @@
1
+ import { createRequire as createKoedRequire } from "node:module"; const require = createKoedRequire(import.meta.url);
2
+ import {
3
+ cancelUpstreamEnrollment,
4
+ disconnectUpstreamBackendEnrollment,
5
+ getUpstreamEnrollmentStatus,
6
+ invalidateUpstreamEnrollmentReferences,
7
+ readUpstreamEnrollmentBinding,
8
+ startUpstreamEnrollment
9
+ } from "./chunk-WPIEF4LY.js";
10
+ import "./chunk-SRKIBFOE.js";
11
+ import "./chunk-7NXKPDF3.js";
12
+ import "./chunk-RCR4XPE3.js";
13
+ import "./chunk-ZOHNXUDY.js";
14
+ import "./chunk-FSNLU46W.js";
15
+ import "./chunk-BTS4ZTF3.js";
16
+ export {
17
+ cancelUpstreamEnrollment,
18
+ disconnectUpstreamBackendEnrollment,
19
+ getUpstreamEnrollmentStatus,
20
+ invalidateUpstreamEnrollmentReferences,
21
+ readUpstreamEnrollmentBinding,
22
+ startUpstreamEnrollment
23
+ };
@@ -0,0 +1,188 @@
1
+ import { createRequire as createKoedRequire } from "node:module"; const require = createKoedRequire(import.meta.url);
2
+ import {
3
+ isProcessRunning
4
+ } from "./chunk-T6UB5PNX.js";
5
+ import {
6
+ require_proper_lockfile
7
+ } from "./chunk-7NXKPDF3.js";
8
+ import {
9
+ __toESM
10
+ } from "./chunk-BTS4ZTF3.js";
11
+
12
+ // packages/koed-server/dist/ports.js
13
+ var import_proper_lockfile = __toESM(require_proper_lockfile(), 1);
14
+ import { createServer } from "node:net";
15
+ import { existsSync, readFileSync, writeFileSync } from "node:fs";
16
+ import { homedir } from "node:os";
17
+ import { dirname, resolve } from "node:path";
18
+ import { mkdirSync } from "node:fs";
19
+ var DEFAULT_PORTS = {
20
+ api: "43300",
21
+ postgres: "45432",
22
+ embedding: "43800",
23
+ privacy: "48092",
24
+ llamaEmbedding: "18080"
25
+ };
26
+ var localPortLeaseSchemaVersion = 1;
27
+ var ENV_KEYS = {
28
+ api: ["API_HOST_PORT"],
29
+ postgres: ["POSTGRES_HOST_PORT"],
30
+ embedding: ["EMBEDDING_SERVICE_HOST_PORT"],
31
+ privacy: ["PRIVACY_SERVICE_PORT"],
32
+ llamaEmbedding: [
33
+ "EMBEDDING_LLAMA_EMBEDDING_SERVER_PORT",
34
+ "LLAMA_EMBEDDING_SERVER_PORT"
35
+ ]
36
+ };
37
+ var trim = (value) => {
38
+ const trimmed = value?.trim();
39
+ return trimmed ? trimmed : void 0;
40
+ };
41
+ var validPort = (value) => {
42
+ const trimmed = trim(value);
43
+ if (!trimmed)
44
+ return void 0;
45
+ const parsed = Number.parseInt(trimmed, 10);
46
+ return Number.isInteger(parsed) && parsed > 0 && parsed < 65536 ? String(parsed) : void 0;
47
+ };
48
+ var canListen = (port) => new Promise((resolve2) => {
49
+ const server = createServer();
50
+ server.once("error", () => resolve2(false));
51
+ server.listen(Number(port), "127.0.0.1", () => {
52
+ server.close(() => resolve2(true));
53
+ });
54
+ });
55
+ var nextFreePort = async (preferred, unavailablePorts, canListenOnPort) => {
56
+ const start = Number(preferred);
57
+ for (let port = start; port < Math.min(start + 1e3, 65536); port += 1) {
58
+ const candidate = String(port);
59
+ if (!unavailablePorts.has(candidate) && await canListenOnPort(candidate)) {
60
+ return candidate;
61
+ }
62
+ }
63
+ throw new Error(`Could not find a free local port near ${preferred}.`);
64
+ };
65
+ var defaultLocalPortLeaseRegistryPath = () => resolve(homedir(), ".koed", "run", "local-port-leases.json");
66
+ var resolveLocalPortLeaseRegistryPath = (environment, dependencyPath) => {
67
+ const configured = environment.KOED_LOCAL_PORT_LEASES_PATH?.trim();
68
+ return resolve(dependencyPath ?? configured ?? defaultLocalPortLeaseRegistryPath());
69
+ };
70
+ var emptyLocalPortLeaseRegistry = () => ({
71
+ schemaVersion: localPortLeaseSchemaVersion,
72
+ leases: {}
73
+ });
74
+ var isLocalPortLease = (value) => typeof value === "object" && value !== null && typeof value.koedHome === "string" && typeof value.pid === "number" && typeof value.ports === "object" && value.ports !== null;
75
+ var ensureLocalPortLeaseRegistry = (path) => {
76
+ mkdirSync(dirname(path), { recursive: true, mode: 448 });
77
+ if (!existsSync(path)) {
78
+ writeFileSync(path, `${JSON.stringify(emptyLocalPortLeaseRegistry())}
79
+ `, {
80
+ mode: 384
81
+ });
82
+ }
83
+ };
84
+ var readLocalPortLeaseRegistry = (path) => {
85
+ try {
86
+ const parsed = JSON.parse(readFileSync(path, "utf8"));
87
+ if (parsed.schemaVersion !== localPortLeaseSchemaVersion || !parsed.leases || typeof parsed.leases !== "object") {
88
+ return emptyLocalPortLeaseRegistry();
89
+ }
90
+ return {
91
+ schemaVersion: localPortLeaseSchemaVersion,
92
+ leases: Object.fromEntries(Object.entries(parsed.leases).filter(([, lease]) => isLocalPortLease(lease)))
93
+ };
94
+ } catch {
95
+ return emptyLocalPortLeaseRegistry();
96
+ }
97
+ };
98
+ var writeLocalPortLeaseRegistry = (path, registry) => {
99
+ writeFileSync(path, `${JSON.stringify(registry, null, 2)}
100
+ `, {
101
+ mode: 384
102
+ });
103
+ };
104
+ var readPersistedLocalPorts = (paths) => {
105
+ if (!existsSync(paths.localPortsPath))
106
+ return {};
107
+ try {
108
+ const parsed = JSON.parse(readFileSync(paths.localPortsPath, "utf8"));
109
+ return {
110
+ ...validPort(parsed.api) ? { api: validPort(parsed.api) } : {},
111
+ ...validPort(parsed.postgres) ? { postgres: validPort(parsed.postgres) } : {},
112
+ ...validPort(parsed.embedding) ? { embedding: validPort(parsed.embedding) } : {},
113
+ ...validPort(parsed.privacy) ? { privacy: validPort(parsed.privacy) } : {},
114
+ ...validPort(parsed.llamaEmbedding) ? { llamaEmbedding: validPort(parsed.llamaEmbedding) } : {}
115
+ };
116
+ } catch {
117
+ return {};
118
+ }
119
+ };
120
+ var writePersistedLocalPorts = (paths, ports) => {
121
+ mkdirSync(dirname(paths.localPortsPath), { recursive: true, mode: 448 });
122
+ writeFileSync(paths.localPortsPath, `${JSON.stringify(ports, null, 2)}
123
+ `, {
124
+ mode: 384
125
+ });
126
+ };
127
+ var applyPersistedLocalPorts = (paths, environment, options = {}) => {
128
+ if (!options.force && environment.KOED_AUTO_PORTS !== "1")
129
+ return environment;
130
+ const persisted = readPersistedLocalPorts(paths);
131
+ return {
132
+ ...environment,
133
+ ...persisted.api && !trim(environment.API_HOST_PORT) ? { API_HOST_PORT: persisted.api } : {},
134
+ ...persisted.postgres && !trim(environment.POSTGRES_HOST_PORT) ? { POSTGRES_HOST_PORT: persisted.postgres } : {},
135
+ ...persisted.embedding && !trim(environment.EMBEDDING_SERVICE_HOST_PORT) ? { EMBEDDING_SERVICE_HOST_PORT: persisted.embedding } : {},
136
+ ...persisted.privacy && !trim(environment.PRIVACY_SERVICE_PORT) ? { PRIVACY_SERVICE_PORT: persisted.privacy } : {},
137
+ ...persisted.llamaEmbedding && !ENV_KEYS.llamaEmbedding.some((key) => trim(environment[key])) ? { EMBEDDING_LLAMA_EMBEDDING_SERVER_PORT: persisted.llamaEmbedding } : {}
138
+ };
139
+ };
140
+ var allocateAndPersistLocalPorts = async (paths, environment, dependencies = {}) => {
141
+ if (environment.KOED_AUTO_PORTS !== "1")
142
+ return environment;
143
+ const registryPath = resolveLocalPortLeaseRegistryPath(environment, dependencies.leaseRegistryPath);
144
+ ensureLocalPortLeaseRegistry(registryPath);
145
+ const release = await import_proper_lockfile.default.lock(registryPath, {
146
+ realpath: false,
147
+ retries: { retries: 20, factor: 1.2, minTimeout: 25, maxTimeout: 250 }
148
+ });
149
+ try {
150
+ const processIsRunning = dependencies.isProcessRunning ?? isProcessRunning;
151
+ const canListenOnPort = dependencies.canListen ?? canListen;
152
+ const registry = readLocalPortLeaseRegistry(registryPath);
153
+ const activeLeases = Object.values(registry.leases).filter((lease) => lease.koedHome !== paths.koedHome && processIsRunning(lease.pid));
154
+ registry.leases = Object.fromEntries(Object.entries(registry.leases).filter(([, lease]) => lease.koedHome === paths.koedHome || processIsRunning(lease.pid)));
155
+ const unavailablePorts = new Set(activeLeases.flatMap((lease) => Object.keys(DEFAULT_PORTS).map((key) => lease.ports[key])));
156
+ const persisted = readPersistedLocalPorts(paths);
157
+ const allocated = { ...DEFAULT_PORTS, ...persisted };
158
+ for (const key of Object.keys(ENV_KEYS)) {
159
+ const fromEnv = ENV_KEYS[key].map((envKey) => validPort(environment[envKey])).find((port) => port !== void 0);
160
+ const preferred = fromEnv ?? validPort(allocated[key]) ?? DEFAULT_PORTS[key];
161
+ allocated[key] = !unavailablePorts.has(preferred) && await canListenOnPort(preferred) ? preferred : await nextFreePort(preferred, unavailablePorts, canListenOnPort);
162
+ unavailablePorts.add(allocated[key]);
163
+ }
164
+ writePersistedLocalPorts(paths, allocated);
165
+ registry.leases[paths.koedHome] = {
166
+ koedHome: paths.koedHome,
167
+ pid: dependencies.processId ?? process.pid,
168
+ ports: allocated,
169
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
170
+ };
171
+ writeLocalPortLeaseRegistry(registryPath, registry);
172
+ return {
173
+ ...environment,
174
+ API_HOST_PORT: allocated.api,
175
+ POSTGRES_HOST_PORT: allocated.postgres,
176
+ EMBEDDING_SERVICE_HOST_PORT: allocated.embedding,
177
+ PRIVACY_SERVICE_PORT: allocated.privacy,
178
+ EMBEDDING_LLAMA_EMBEDDING_SERVER_PORT: allocated.llamaEmbedding
179
+ };
180
+ } finally {
181
+ await release();
182
+ }
183
+ };
184
+
185
+ export {
186
+ applyPersistedLocalPorts,
187
+ allocateAndPersistLocalPorts
188
+ };