@koed-labs/server 0.10.3 → 1.0.0

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/README.md +3 -3
  2. package/bin/koed.js +1 -1
  3. package/package.json +2 -2
  4. package/vendor/chunk-273NMYXE.js +605 -0
  5. package/vendor/{chunk-VPC5NLZG.js → chunk-4DHYSJJT.js} +1 -1
  6. package/vendor/{chunk-HK2H3MVE.js → chunk-53ZFCDHP.js} +4 -0
  7. package/vendor/{chunk-YCDEMYY6.js → chunk-54UL4U2E.js} +261 -110
  8. package/vendor/{chunk-X6M525ZJ.js → chunk-64AST7WZ.js} +5 -5
  9. package/vendor/{chunk-JKOG52PE.js → chunk-7FSHVVTZ.js} +1 -1
  10. package/vendor/chunk-7HLNJ2BI.js +1669 -0
  11. package/vendor/chunk-ALJUSOF7.js +175 -0
  12. package/vendor/{chunk-A6WMU2GG.js → chunk-AOZ3LMTF.js} +5 -4
  13. package/vendor/{chunk-KUIWH33N.js → chunk-AVQCUFYQ.js} +1 -1
  14. package/vendor/{chunk-JJNLH5GA.js → chunk-BYN6KXNP.js} +21 -19
  15. package/vendor/{chunk-PY5LYLV7.js → chunk-DWWMBGHX.js} +26 -21
  16. package/vendor/chunk-E6YVGIEW.js +12518 -0
  17. package/vendor/{chunk-C3N4N5HR.js → chunk-EEBIYWTE.js} +26 -21
  18. package/vendor/{chunk-YOFI4PCH.js → chunk-F77ZTTNS.js} +7 -1
  19. package/vendor/{chunk-RVYJKKWA.js → chunk-F7AMEDDU.js} +5 -4
  20. package/vendor/{chunk-473OA62O.js → chunk-FSNLU46W.js} +218 -12497
  21. package/vendor/{chunk-2S3OGPUC.js → chunk-GY5GATZL.js} +2 -2
  22. package/vendor/chunk-ILQVLZ2I.js +50 -0
  23. package/vendor/{chunk-QIIKMG3M.js → chunk-IY2HRXOZ.js} +1 -5
  24. package/vendor/{chunk-ZUGNCQZE.js → chunk-JYK6UL6D.js} +22 -8
  25. package/vendor/chunk-KG3RANR4.js +75 -0
  26. package/vendor/{chunk-YJ6XUZT6.js → chunk-KRBZZ6GS.js} +23 -16
  27. package/vendor/{chunk-AFLKCQHF.js → chunk-L4RD3TAZ.js} +2 -2
  28. package/vendor/{chunk-XNFVSVBS.js → chunk-LHUMBHG7.js} +1 -1
  29. package/vendor/{chunk-J2L726BC.js → chunk-NGV45YWB.js} +3 -3
  30. package/vendor/{chunk-A4NKL2PK.js → chunk-OG7G6DIR.js} +1 -1
  31. package/vendor/{chunk-DXTAWHY3.js → chunk-OZU6JFB4.js} +8 -7
  32. package/vendor/chunk-QV3WPU7A.js +8 -0
  33. package/vendor/{chunk-ZXX4ZNJY.js → chunk-S6HD3MDU.js} +3 -2
  34. package/vendor/{chunk-NEWIOOM6.js → chunk-SQZ2OSP6.js} +3 -2
  35. package/vendor/{chunk-G4IIVVJO.js → chunk-T6UB5PNX.js} +70 -2
  36. package/vendor/{chunk-SKVYP7NY.js → chunk-T7OGE5E5.js} +8 -8
  37. package/vendor/{chunk-GELDEJJ2.js → chunk-TIBYKMRW.js} +173 -51
  38. package/vendor/{chunk-HFM6ROJL.js → chunk-TISYUUEJ.js} +1 -1
  39. package/vendor/{chunk-K2EIFEQF.js → chunk-TSAYTRX3.js} +1 -1
  40. package/vendor/{chunk-PT3AUPGE.js → chunk-UB6JCVQ3.js} +3 -1
  41. package/vendor/{chunk-NM5NXCVM.js → chunk-UCOHFZ77.js} +626 -996
  42. package/vendor/{chunk-2BWTLF7A.js → chunk-UIMUUIH7.js} +45 -21
  43. package/vendor/{chunk-HZJK5RWC.js → chunk-USHFSJT7.js} +695 -280
  44. package/vendor/chunk-VGL5AZN5.js +152 -0
  45. package/vendor/{chunk-TSRPHKAC.js → chunk-VLP72QWX.js} +16 -42
  46. package/vendor/chunk-W6632NOX.js +14 -0
  47. package/vendor/{chunk-YJWREXN6.js → chunk-WBMO7YCO.js} +1 -1
  48. package/vendor/chunk-XCO3RV3Z.js +11 -0
  49. package/vendor/chunk-XKXSC6YS.js +373 -0
  50. package/vendor/{chunk-YK4F4VY2.js → chunk-Y6GE52OP.js} +51 -30
  51. package/vendor/{chunk-UI5RLBKQ.js → chunk-YZLQZU5E.js} +17 -1
  52. package/vendor/chunk-ZKKWLLPU.js +18 -0
  53. package/vendor/cli.js +1 -1
  54. package/vendor/component-manifest-catalog.js +2 -1
  55. package/vendor/control-plane.js +11 -6
  56. package/vendor/chunk-2DA7EFZV.js +0 -924
@@ -1,253 +1,34 @@
1
1
  import { createRequire as createKoedRequire } from "node:module"; const require = createKoedRequire(import.meta.url);
2
2
  import {
3
3
  isRuntimeGenerationState
4
- } from "./chunk-G4IIVVJO.js";
4
+ } from "./chunk-T6UB5PNX.js";
5
5
  import {
6
- lookupManifestPin,
7
- productionComponentManifestCatalog,
8
- validateManifestCatalog
9
- } from "./chunk-QIIKMG3M.js";
6
+ productionComponentManifestCatalog
7
+ } from "./chunk-XCO3RV3Z.js";
10
8
  import {
11
- canonicalArtifactBytes,
12
9
  canonicalArtifactJson,
13
10
  extractVerifiedPackageArchive,
14
- isVersionDowngrade
15
- } from "./chunk-2DA7EFZV.js";
16
-
17
- // packages/koed-server/dist/component-runtime-identity.js
18
- import process2 from "node:process";
19
- var isVersion = (value) => typeof value === "string" && /^(?:0|[1-9]\d*)(?:\.(?:0|[1-9]\d*)){1,2}$/.test(value) && value.split(".").every((part) => Number.isSafeInteger(Number(part)));
20
- function discoverRuntimeIdentityFromProcess(source) {
21
- const platform = source.platform === "darwin" ? "macos" : source.platform === "linux" ? "linux" : void 0;
22
- const architecture = source.arch === "arm64" || source.arch === "x64" ? source.arch : void 0;
23
- const runtimeVersion = source.versions.electron ?? source.versions.node;
24
- const nodeVersion = source.versions.node;
25
- const modulesAbi = source.versions.modules;
26
- const napiVersion = Number(source.versions.napi ?? "0");
27
- let libcVersion;
28
- if (platform === "linux") {
29
- try {
30
- libcVersion = source.report?.getReport().header?.glibcVersionRuntime;
31
- } catch {
32
- throw new Error("actual runtime identity is unsupported or incomplete");
33
- }
34
- }
35
- if (!platform || !architecture || !isVersion(runtimeVersion) || !isVersion(nodeVersion) || typeof modulesAbi !== "string" || !/^\d+$/.test(modulesAbi) || !Number.isSafeInteger(napiVersion) || napiVersion < 0 || platform === "linux" && !isVersion(libcVersion))
36
- throw new Error("actual runtime identity is unsupported or incomplete");
37
- return {
38
- kind: source.versions.electron === void 0 ? "node" : "electron",
39
- version: runtimeVersion,
40
- nodeVersion,
41
- modulesAbi,
42
- napiVersion,
43
- platform,
44
- architecture,
45
- ...libcVersion === void 0 ? {} : { libcVersion }
46
- };
47
- }
48
- function discoverActualRuntimeIdentity() {
49
- return discoverRuntimeIdentityFromProcess(process2);
50
- }
51
-
52
- // packages/koed-server/dist/config.js
53
- import { existsSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
54
- import { randomUUID } from "node:crypto";
55
- import { dirname } from "node:path";
56
- import { mkdirSync } from "node:fs";
57
- var defaultKoedServerConfig = {
58
- runtimeMode: "local-personal",
59
- dependencyMode: "bundled-local",
60
- codexTranscriptWatcherEnabled: true,
61
- claudeTranscriptWatcherEnabled: true,
62
- piTranscriptWatcherEnabled: true,
63
- codexGlobalMemoryGuidanceEnabled: true,
64
- hardwareAcceleration: "auto"
65
- };
66
- var trim = (value) => {
67
- const trimmed = value?.trim();
68
- return trimmed ? trimmed : void 0;
69
- };
70
- var runtimeMode = (value) => value === "local-personal" || value === "external" || value === "developer" ? value : void 0;
71
- var dependencyMode = (value) => value === "external" || value === "bundled-local" ? value : void 0;
72
- var codexTranscriptWatcherSetting = (value) => {
73
- if (value === true || value === "true")
74
- return true;
75
- if (value === false || value === "false")
76
- return false;
77
- return void 0;
78
- };
79
- var claudeTranscriptWatcherSetting = codexTranscriptWatcherSetting;
80
- var piTranscriptWatcherSetting = codexTranscriptWatcherSetting;
81
- var booleanSetting = codexTranscriptWatcherSetting;
82
- var hardwareAccelerationPreference = (value, source) => value === void 0 ? void 0 : value === "auto" || value === "cpu" ? value : (() => {
83
- throw new Error(`${source} must be auto or cpu`);
84
- })();
85
- var readConfig = (paths, deps) => {
86
- if (!deps.existsSync(paths.serverConfigPath)) {
87
- return {};
88
- }
89
- try {
90
- const parsed = JSON.parse(deps.readFileSync(paths.serverConfigPath, "utf8"));
91
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
92
- throw new Error("expected a JSON object");
93
- }
94
- const record = parsed;
95
- if (!deps.strict)
96
- return record;
97
- const stringFields = ["runtimeMode", "dependencyMode"];
98
- const booleanFields = [
99
- "codexTranscriptWatcherEnabled",
100
- "claudeTranscriptWatcherEnabled",
101
- "piTranscriptWatcherEnabled",
102
- "codexGlobalMemoryGuidanceEnabled"
103
- ];
104
- for (const field of stringFields) {
105
- if (record[field] !== void 0 && typeof record[field] !== "string") {
106
- throw new Error(`${field} must be a string`);
107
- }
108
- }
109
- if (record.runtimeMode !== void 0 && !runtimeMode(record.runtimeMode)) {
110
- throw new Error("runtimeMode must be local-personal, external, or developer");
111
- }
112
- if (record.dependencyMode !== void 0 && !dependencyMode(record.dependencyMode)) {
113
- throw new Error("dependencyMode must be bundled-local or external");
114
- }
115
- for (const field of booleanFields) {
116
- if (record[field] !== void 0 && typeof record[field] !== "boolean") {
117
- throw new Error(`${field} must be a boolean`);
118
- }
119
- }
120
- if (record.hardwareAcceleration !== void 0) {
121
- hardwareAccelerationPreference(record.hardwareAcceleration, "server.json hardwareAcceleration");
122
- }
123
- if (record.external !== void 0 && (!record.external || typeof record.external !== "object" || Array.isArray(record.external))) {
124
- throw new Error("external must be an object");
125
- }
126
- if (record.external && typeof record.external === "object") {
127
- const external = record.external;
128
- const supportedExternalFields = [
129
- "databaseUrl",
130
- "redisUrl",
131
- "embeddingServiceUrl",
132
- "privacyServiceUrl"
133
- ];
134
- for (const [field, value] of Object.entries(external)) {
135
- if (!supportedExternalFields.includes(field)) {
136
- throw new Error(`external.${field} is not supported`);
137
- }
138
- if (value !== void 0 && typeof value !== "string") {
139
- throw new Error(`external.${field} must be a string`);
140
- }
141
- }
142
- }
143
- return record;
144
- } catch (error) {
145
- if (!deps.strict)
146
- return {};
147
- const message = error instanceof Error ? error.message : String(error);
148
- throw new Error(`Cannot read ${paths.serverConfigPath}: ${message}`, {
149
- cause: error
150
- });
151
- }
152
- };
153
- var resolveKoedServerConfig = (paths, environment = process.env, deps = {}) => {
154
- const file = readConfig(paths, {
155
- existsSync: deps.existsSync ?? existsSync,
156
- readFileSync: deps.readFileSync ?? readFileSync,
157
- strict: deps.strict
158
- });
159
- if (deps.strict) {
160
- if (environment.KOED_RUNTIME_MODE !== void 0 && !runtimeMode(environment.KOED_RUNTIME_MODE)) {
161
- throw new Error("KOED_RUNTIME_MODE must be local-personal, external, or developer");
162
- }
163
- if (environment.KOED_DEPENDENCY_MODE !== void 0 && !dependencyMode(environment.KOED_DEPENDENCY_MODE)) {
164
- throw new Error("KOED_DEPENDENCY_MODE must be bundled-local or external");
165
- }
166
- }
167
- const resolvedRuntimeMode = runtimeMode(environment.KOED_RUNTIME_MODE) ?? runtimeMode(file.runtimeMode) ?? defaultKoedServerConfig.runtimeMode;
168
- const resolvedTranscriptWatcherSetting = codexTranscriptWatcherSetting(environment.MEMORY_CODEX_TRANSCRIPT_WATCHER_ENABLED) ?? codexTranscriptWatcherSetting(file.codexTranscriptWatcherEnabled);
169
- const resolvedClaudeTranscriptWatcherSetting = claudeTranscriptWatcherSetting(environment.MEMORY_CLAUDE_TRANSCRIPT_WATCHER_ENABLED) ?? claudeTranscriptWatcherSetting(file.claudeTranscriptWatcherEnabled);
170
- const resolvedPiTranscriptWatcherSetting = piTranscriptWatcherSetting(environment.MEMORY_PI_TRANSCRIPT_WATCHER_ENABLED) ?? piTranscriptWatcherSetting(file.piTranscriptWatcherEnabled);
171
- if (resolvedRuntimeMode === "external" && (resolvedTranscriptWatcherSetting === true || resolvedClaudeTranscriptWatcherSetting === true || resolvedPiTranscriptWatcherSetting === true)) {
172
- throw new Error("Transcript Watchers cannot run in external runtime mode; run capture through a local-personal koed-server.");
173
- }
174
- return {
175
- runtimeMode: resolvedRuntimeMode,
176
- dependencyMode: dependencyMode(environment.KOED_DEPENDENCY_MODE) ?? dependencyMode(file.dependencyMode) ?? (resolvedRuntimeMode === "local-personal" ? "bundled-local" : "external"),
177
- codexTranscriptWatcherEnabled: resolvedTranscriptWatcherSetting ?? resolvedRuntimeMode !== "external",
178
- claudeTranscriptWatcherEnabled: resolvedClaudeTranscriptWatcherSetting ?? resolvedRuntimeMode !== "external",
179
- piTranscriptWatcherEnabled: resolvedPiTranscriptWatcherSetting ?? resolvedRuntimeMode !== "external",
180
- codexGlobalMemoryGuidanceEnabled: booleanSetting(environment.KOED_CODEX_GLOBAL_MEMORY_GUIDANCE_ENABLED) ?? booleanSetting(file.codexGlobalMemoryGuidanceEnabled) ?? defaultKoedServerConfig.codexGlobalMemoryGuidanceEnabled,
181
- hardwareAcceleration: hardwareAccelerationPreference(environment.KOED_HARDWARE_ACCELERATION, "KOED_HARDWARE_ACCELERATION") ?? hardwareAccelerationPreference(file.hardwareAcceleration, "server.json hardwareAcceleration") ?? defaultKoedServerConfig.hardwareAcceleration,
182
- external: {
183
- databaseUrl: trim(environment.KOED_EXTERNAL_DATABASE_URL) ?? trim(environment.DATABASE_URL) ?? trim(file.external?.databaseUrl),
184
- redisUrl: trim(environment.KOED_EXTERNAL_REDIS_URL) ?? trim(environment.REDIS_URL) ?? trim(file.external?.redisUrl),
185
- embeddingServiceUrl: trim(environment.KOED_EXTERNAL_EMBEDDING_SERVICE_URL) ?? trim(environment.EMBEDDING_SERVICE_URL) ?? trim(file.external?.embeddingServiceUrl),
186
- privacyServiceUrl: trim(environment.KOED_EXTERNAL_PRIVACY_SERVICE_URL) ?? trim(environment.PRIVACY_SERVICE_URL) ?? trim(file.external?.privacyServiceUrl)
187
- }
188
- };
189
- };
190
- var writeServerConfigAtomically = (paths, config, deps = {}) => {
191
- mkdirSync(dirname(paths.serverConfigPath), { recursive: true, mode: 448 });
192
- const temporary = `${paths.serverConfigPath}.${process.pid}.${randomUUID()}.tmp`;
193
- try {
194
- (deps.writeFileSync ?? writeFileSync)(temporary, `${JSON.stringify(config, null, 2)}
195
- `, { mode: 384 });
196
- (deps.renameSync ?? renameSync)(temporary, paths.serverConfigPath);
197
- } catch (error) {
198
- (deps.rmSync ?? rmSync)(temporary, { force: true });
199
- throw error;
200
- }
201
- };
202
- var writeCodexGlobalMemoryGuidancePreference = (paths, enabled, deps = {}) => {
203
- const fileExists = deps.existsSync ?? existsSync;
204
- const read = deps.readFileSync ?? readFileSync;
205
- let existing = {};
206
- if (fileExists(paths.serverConfigPath)) {
207
- try {
208
- const parsed = JSON.parse(read(paths.serverConfigPath, "utf8"));
209
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
210
- throw new Error("expected a JSON object");
211
- }
212
- existing = parsed;
213
- } catch (error) {
214
- const message = error instanceof Error ? error.message : String(error);
215
- throw new Error(`Cannot update Codex memory guidance preference because ${paths.serverConfigPath} is malformed: ${message}.`, { cause: error });
216
- }
217
- }
218
- writeServerConfigAtomically(paths, { ...existing, codexGlobalMemoryGuidanceEnabled: enabled }, deps);
219
- };
220
-
221
- // packages/koed-server/dist/component-store.js
222
- import { createHash as createHash3 } from "node:crypto";
223
- import { chmodSync, closeSync as closeSync3, constants as constants3, copyFileSync, createWriteStream, existsSync as existsSync2, fstatSync as fstatSync2, lstatSync as lstatSync3, openSync as openSync3, mkdirSync as mkdirSync3, mkdtempSync, readFileSync as readFileSync3, readdirSync as readdirSync3, renameSync as renameSync2, rmSync as rmSync3, writeFileSync as writeFileSync2 } from "node:fs";
224
- import { basename as basename2, dirname as dirname2, isAbsolute as isAbsolute3, parse, relative as relative3, resolve as resolve3, sep as sep3 } from "node:path";
225
- import { Readable as Readable2, Transform } from "node:stream";
226
- import { pipeline } from "node:stream/promises";
11
+ isVersionDowngrade,
12
+ validateComponentManifest,
13
+ verifyComponent,
14
+ verifyComponentManifestPin,
15
+ verifyExtractedComponent
16
+ } from "./chunk-7HLNJ2BI.js";
17
+ import {
18
+ lookupManifestPin,
19
+ validateManifestCatalog
20
+ } from "./chunk-IY2HRXOZ.js";
227
21
 
228
- // packages/koed-server/dist/directory-lock.js
229
- import { mkdirSync as mkdirSync2, rmSync as rmSync2 } from "node:fs";
230
- var acquireDirectoryLock = (path) => {
231
- try {
232
- mkdirSync2(path, { mode: 448 });
233
- } catch (error) {
234
- if (error.code !== "EEXIST")
235
- throw error;
236
- throw Object.assign(new Error("lock is already held"), { code: "ELOCKED" });
237
- }
238
- let released = false;
239
- return () => {
240
- if (released)
241
- return;
242
- released = true;
243
- rmSync2(path, { recursive: true, force: true });
244
- };
245
- };
22
+ // packages/koed-server/dist/generation-lifecycle.js
23
+ import { createHash as createHash3, randomBytes } from "node:crypto";
24
+ import { existsSync as existsSync2, closeSync as closeSync5, constants as constants4, fstatSync as fstatSync3, openSync as openSync5, readSync, lstatSync as lstatSync3, mkdirSync as mkdirSync4, readFileSync as readFileSync5, readdirSync as readdirSync3, renameSync as renameSync3, rmSync as rmSync6, statSync, writeFileSync as writeFileSync3 } from "node:fs";
25
+ import { dirname as dirname2, isAbsolute as isAbsolute3, parse as parse2, relative as relative3, resolve as resolve5, sep as sep3 } from "node:path";
246
26
 
247
27
  // packages/koed-server/dist/desktop-runtime-capability.js
248
28
  import { createHash } from "node:crypto";
249
- import { closeSync, constants, lstatSync, openSync, readFileSync as readFileSync2, readlinkSync, readdirSync, realpathSync } from "node:fs";
29
+ import { closeSync, constants, lstatSync, openSync, readFileSync, readlinkSync, readdirSync, realpathSync } from "node:fs";
250
30
  import { isAbsolute, relative, resolve, sep } from "node:path";
31
+ import process2 from "node:process";
251
32
  var issuedCapabilities = /* @__PURE__ */ new WeakSet();
252
33
  var hash = (bytes) => createHash("sha256").update(bytes).digest("hex");
253
34
  function validateDesktopRuntimeManifest(value) {
@@ -272,12 +53,46 @@ var regularFile = (path) => {
272
53
  try {
273
54
  if (!lstatSync(path).isFile())
274
55
  throw new Error("Desktop runtime bundle entry is not a regular file");
275
- return readFileSync2(fd);
56
+ return readFileSync(fd);
276
57
  } finally {
277
58
  closeSync(fd);
278
59
  }
279
60
  };
280
- function verifyDesktopRuntimeBundle(resourcesPath) {
61
+ var isWithin = (root, path) => {
62
+ const rel = relative(root, path);
63
+ return rel === "" || !!rel && !rel.startsWith(`..${sep}`) && rel !== ".." && !isAbsolute(rel);
64
+ };
65
+ function resolveDesktopInstallationPath(actualResources, environment = process2.env) {
66
+ const image = environment.APPIMAGE?.trim();
67
+ const mount = environment.APPDIR?.trim();
68
+ if (!image || !mount || !isAbsolute(image) || !isAbsolute(mount))
69
+ return actualResources;
70
+ let actualMount;
71
+ let actualImage;
72
+ try {
73
+ actualMount = realpathSync.native(mount);
74
+ actualImage = realpathSync.native(image);
75
+ } catch {
76
+ return actualResources;
77
+ }
78
+ if (!isWithin(actualMount, actualResources) || !lstatSync(actualImage).isFile())
79
+ return actualResources;
80
+ return actualImage;
81
+ }
82
+ function resolveDesktopInstallationResources(installationPath, environment = process2.env) {
83
+ if (!isAbsolute(installationPath))
84
+ throw new Error("Desktop installation path is invalid");
85
+ if (lstatSync(installationPath, { throwIfNoEntry: false })?.isDirectory())
86
+ return installationPath;
87
+ const mount = environment.APPDIR?.trim();
88
+ if (!mount || !isAbsolute(mount))
89
+ throw new Error("Desktop installation is not the running AppImage");
90
+ const resources = resolve(realpathSync.native(mount), "resources");
91
+ if (resolveDesktopInstallationPath(realpathSync.native(resources), environment) !== installationPath)
92
+ throw new Error("Desktop installation is not the running AppImage");
93
+ return resources;
94
+ }
95
+ function verifyDesktopRuntimeBundle(resourcesPath, environment = process2.env) {
281
96
  const actualResources = realpathSync.native(resolve(resourcesPath));
282
97
  const runtimeRoot = resolve(actualResources, "koed-runtime");
283
98
  const manifestPath = resolve(runtimeRoot, "desktop-bundle-manifest.json");
@@ -330,6 +145,7 @@ function verifyDesktopRuntimeBundle(resourcesPath) {
330
145
  });
331
146
  const capability = Object.freeze({
332
147
  resourcesPath: actualResources,
148
+ installationPath: resolveDesktopInstallationPath(actualResources, environment),
333
149
  productVersion: record.productVersion,
334
150
  bundleDigest: hash(canonicalArtifactJson(record)),
335
151
  manifest: verifiedManifest,
@@ -352,532 +168,225 @@ function resolveDesktopRuntimeOwner(capability, koedHome) {
352
168
  if (!validateDesktopRuntimeCapability(capability)) {
353
169
  throw new Error("validated private Desktop runtime capability is required");
354
170
  }
355
- return deriveDesktopRuntimeOwner(koedHome, capability.resourcesPath);
171
+ return deriveDesktopRuntimeOwner(koedHome, capability.installationPath);
356
172
  }
357
173
 
358
- // packages/koed-server/dist/component-verification.js
174
+ // packages/koed-server/dist/component-store.js
359
175
  import { createHash as createHash2 } from "node:crypto";
360
- import { closeSync as closeSync2, constants as constants2, fstatSync, lstatSync as lstatSync2, openSync as openSync2, readdirSync as readdirSync2, readSync } from "node:fs";
361
- import { Readable } from "node:stream";
362
- import { basename, isAbsolute as isAbsolute2, relative as relative2, resolve as resolve2, sep as sep2 } from "node:path";
363
- import { createGunzip } from "node:zlib";
364
-
365
- // packages/koed-server/dist/component-artifact-identity.mjs
366
- var componentArchiveName = ({ component, productVersion, target, variant }) => `koed-${component}-${productVersion}-${target.platform}-${target.architecture}${variant === void 0 ? "" : `-${variant}`}.tar.gz`;
367
- var validateComponentVariantIdentity = (value) => {
368
- if (value.schemaVersion === 1 && !Object.hasOwn(value, "variant"))
369
- return;
370
- if (value.schemaVersion === 2 && value.component === "privacy" && value.target?.platform === "linux" && value.target.architecture === "x64" && ["cpu", "cuda"].includes(value.variant))
371
- return;
372
- throw new Error("Unsupported component variant identity; update to a compatible control plane.");
373
- };
176
+ import { chmodSync, closeSync as closeSync2, constants as constants2, copyFileSync, existsSync, fstatSync, lstatSync as lstatSync2, openSync as openSync2, mkdirSync as mkdirSync2, mkdtempSync, readFileSync as readFileSync2, readdirSync as readdirSync2, renameSync, rmSync as rmSync3, writeFileSync } from "node:fs";
177
+ import { dirname, isAbsolute as isAbsolute2, parse, relative as relative2, resolve as resolve2, sep as sep2 } from "node:path";
374
178
 
375
- // packages/koed-server/dist/component-verification.js
376
- var MAX_ARCHIVE_BYTES = 2 * 1024 * 1024 * 1024;
377
- var MAX_MANIFEST_BYTES = 64 * 1024 * 1024;
378
- var MAX_EXPANDED_BYTES = 4 * 1024 * 1024 * 1024;
379
- var MAX_FILE_BYTES = 1024 * 1024 * 1024;
380
- var MAX_FILES = 1e5;
381
- var MAX_DEPTH = 128;
382
- var MAX_DIRECTORIES = 1e5;
383
- var MAX_TAR_BYTES = MAX_EXPANDED_BYTES + MAX_FILES * 1024 + 1024;
384
- var canonicalComponentManifestBytes = (manifest) => canonicalArtifactBytes(manifest);
385
- function assertRecord(value, name, keys) {
386
- if (!value || typeof value !== "object" || Array.isArray(value))
387
- throw new Error(`${name} must be an object`);
388
- const actual = Object.keys(value);
389
- if (actual.length !== keys.length || keys.some((key) => !actual.includes(key)))
390
- throw new Error(`${name} has invalid fields`);
391
- }
392
- function safeRelativePath(path, label) {
393
- if (typeof path !== "string" || !path || path.includes("\\") || path.includes("\0") || isAbsolute2(path) || path.split("/").some((part) => part === ".." || part === "." || !part)) {
394
- throw new Error(`${label} is unsafe`);
395
- }
396
- }
397
- function validateComponentManifest(value) {
398
- assertRecord(value, "component manifest", [
399
- "schemaVersion",
400
- "productVersion",
401
- "component",
402
- "target",
403
- "runtimes",
404
- "archive",
405
- "requiredFiles",
406
- "files",
407
- ...value && typeof value === "object" && Object.hasOwn(value, "variant") ? ["variant"] : []
408
- ]);
409
- const manifest = value;
410
- if (![1, 2].includes(manifest.schemaVersion) || !/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(manifest.productVersion) || !["base", "privacy"].includes(manifest.component))
411
- throw new Error("component manifest identity is invalid");
412
- validateComponentVariantIdentity(manifest);
413
- assertRecord(manifest.target, "component target", manifest.target.libc ? ["platform", "architecture", "libc"] : ["platform", "architecture"]);
414
- if (!["macos", "linux"].includes(manifest.target.platform) || !["arm64", "x64"].includes(manifest.target.architecture))
415
- throw new Error("unsupported component target");
416
- if (manifest.target.libc) {
417
- assertRecord(manifest.target.libc, "component libc target", [
418
- "family",
419
- "minimumVersion"
420
- ]);
421
- if (manifest.target.platform !== "linux" || manifest.target.libc.family !== "glibc" || !isVersion2(manifest.target.libc.minimumVersion))
422
- throw new Error("component libc target is invalid");
423
- }
424
- assertRecord(manifest.archive, "component archive", [
425
- "name",
426
- "bytes",
427
- "sha256"
428
- ]);
429
- if (typeof manifest.archive.name !== "string" || basename(manifest.archive.name) !== manifest.archive.name || !Number.isSafeInteger(manifest.archive.bytes) || manifest.archive.bytes < 1 || !isHash(manifest.archive.sha256))
430
- throw new Error("component archive metadata is invalid");
431
- if (manifest.variant !== void 0 && manifest.archive.name !== componentArchiveName(manifest))
432
- throw new Error("Component archive variant identity mismatch.");
433
- if (!Array.isArray(manifest.runtimes) || manifest.runtimes.length === 0 || !Array.isArray(manifest.requiredFiles) || manifest.requiredFiles.length > MAX_FILES || !Array.isArray(manifest.files) || manifest.files.length > MAX_FILES)
434
- throw new Error("component manifest lists are invalid");
435
- for (const runtime of manifest.runtimes) {
436
- if (!runtime || typeof runtime !== "object" || Array.isArray(runtime))
437
- throw new Error("component runtime compatibility is invalid");
438
- const runtimeRecord = runtime;
439
- const runtimeKeys = [
440
- "kind",
441
- "runtimeRange",
442
- "nodeRange",
443
- ...runtimeRecord.modulesAbi === void 0 ? [] : ["modulesAbi"],
444
- ...runtimeRecord.minimumNapi === void 0 ? [] : ["minimumNapi"]
445
- ];
446
- assertRecord(runtime, "component runtime compatibility", runtimeKeys);
447
- if (typeof runtimeRecord.kind !== "string" || !["node", "electron"].includes(runtimeRecord.kind) || !validRange(runtime.runtimeRange) || !validRange(runtime.nodeRange) || runtimeRecord.modulesAbi !== void 0 && (typeof runtimeRecord.modulesAbi !== "string" || !/^\d+$/.test(runtimeRecord.modulesAbi)) || runtimeRecord.minimumNapi !== void 0 && (typeof runtimeRecord.minimumNapi !== "number" || !Number.isSafeInteger(runtimeRecord.minimumNapi) || runtimeRecord.minimumNapi < 1))
448
- throw new Error("component runtime compatibility is invalid");
449
- if (runtime.modulesAbi === void 0 && runtime.minimumNapi === void 0)
450
- throw new Error("component runtime compatibility must bind ABI or N-API");
451
- }
452
- const paths = /* @__PURE__ */ new Set();
453
- for (const item of manifest.files) {
454
- assertRecord(item, "component file entry", ["path", "sha256"]);
455
- safeRelativePath(item.path, "component file path");
456
- if (!isHash(item.sha256) || paths.has(item.path))
457
- throw new Error("component file inventory is invalid or duplicate");
458
- paths.add(item.path);
179
+ // packages/koed-server/dist/bounded-download.js
180
+ import { createWriteStream, rmSync } from "node:fs";
181
+ import { basename } from "node:path";
182
+ import { Readable, Transform } from "node:stream";
183
+ import { pipeline } from "node:stream/promises";
184
+ var MAX_REDIRECTS = 5;
185
+ var REQUEST_TIMEOUT_MS = 3e4;
186
+ var abortedError = (signal, cause) => new Error(signal.reason?.name === "TimeoutError" ? "component installation timed out" : "component installation cancelled", cause === void 0 ? void 0 : { cause });
187
+ var stalledError = (cause) => new Error(`component download stalled: no data for ${REQUEST_TIMEOUT_MS / 1e3} s`, { cause });
188
+ var cancelBody = async (response) => {
189
+ try {
190
+ await response.body?.cancel();
191
+ } catch {
459
192
  }
460
- const required = /* @__PURE__ */ new Set();
461
- for (const path of manifest.requiredFiles) {
462
- safeRelativePath(path, "required component path");
463
- if (required.has(path) || !paths.has(path))
464
- throw new Error("required component file is duplicate or missing from inventory");
465
- required.add(path);
193
+ };
194
+ async function fetchBounded(urlText, destination, limit, signal, progress, collectBytes = true, attempt = 0) {
195
+ let url;
196
+ try {
197
+ url = new URL(urlText);
198
+ } catch {
199
+ throw new Error("component source URL is invalid");
466
200
  }
467
- }
468
- var isHash = (value) => typeof value === "string" && /^[a-f0-9]{64}$/.test(value);
469
- var isVersion2 = (value) => typeof value === "string" && /^(?:0|[1-9]\d*)(?:\.(?:0|[1-9]\d*)){1,2}$/.test(value) && value.split(".").every((part) => Number.isSafeInteger(Number(part)));
470
- function versionParts(value) {
471
- if (typeof value !== "string" || !/^(?:0|[1-9]\d*)(?:\.(?:0|[1-9]\d*)){0,2}$/.test(value))
472
- return;
473
- const parts = value.split(".").map(Number);
474
- if (parts.some((part) => !Number.isSafeInteger(part)))
475
- return;
476
- return [...parts, 0, 0].slice(0, 3);
477
- }
478
- function compareVersions(a, b) {
479
- const left = versionParts(a);
480
- const right = versionParts(b);
481
- if (!left || !right)
482
- return;
483
- for (let i = 0; i < 3; i++)
484
- if (left[i] !== right[i])
485
- return left[i] - right[i];
486
- return 0;
487
- }
488
- function validRange(range) {
489
- return typeof range === "string" && range.trim().length > 0 && range.split(/\s+/).every((part) => {
490
- const match = /^(?:>=|>|<=|<|=)?((?:0|[1-9]\d*)(?:\.(?:0|[1-9]\d*)){0,2})$/.exec(part);
491
- return Boolean(match && versionParts(match[1]));
492
- });
493
- }
494
- function satisfies(version, range) {
495
- return range.split(/\s+/).every((part) => {
496
- const match = /^(>=|>|<=|<|=)?((?:0|[1-9]\d*)(?:\.(?:0|[1-9]\d*)){0,2})$/.exec(part);
497
- if (!match)
498
- return false;
499
- const comparison = compareVersions(version, match[2]);
500
- if (comparison === void 0)
501
- return false;
502
- switch (match[1]) {
503
- case ">=":
504
- return comparison >= 0;
505
- case ">":
506
- return comparison > 0;
507
- case "<=":
508
- return comparison <= 0;
509
- case "<":
510
- return comparison < 0;
511
- default:
512
- return comparison === 0;
201
+ if (url.protocol !== "https:" || url.username || url.password)
202
+ throw new Error("component downloads require safe HTTPS URLs");
203
+ for (let redirects = 0; ; redirects++) {
204
+ if (signal?.aborted)
205
+ throw abortedError(signal);
206
+ let response;
207
+ const timeoutController = new AbortController();
208
+ const requestSignal = signal ? AbortSignal.any([signal, timeoutController.signal]) : timeoutController.signal;
209
+ let timeout = setTimeout(() => timeoutController.abort(), REQUEST_TIMEOUT_MS);
210
+ const resetIdleTimeout = () => {
211
+ clearTimeout(timeout);
212
+ timeout = setTimeout(() => timeoutController.abort(), REQUEST_TIMEOUT_MS);
213
+ };
214
+ try {
215
+ response = await fetch(url, {
216
+ redirect: "manual",
217
+ signal: requestSignal
218
+ });
219
+ } catch (error) {
220
+ if (signal?.aborted)
221
+ throw abortedError(signal, error);
222
+ if (timeoutController.signal.aborted)
223
+ throw stalledError(error);
224
+ if (attempt < 2 && error instanceof TypeError) {
225
+ await new Promise((resolveRetry) => setTimeout(resolveRetry, 100 * (attempt + 1)));
226
+ return fetchBounded(url.href, destination, limit, signal, progress, collectBytes, attempt + 1);
227
+ }
228
+ throw error;
229
+ } finally {
230
+ clearTimeout(timeout);
513
231
  }
514
- });
515
- }
516
- function verifyCompatibility(manifest, input) {
517
- if (manifest.component !== input.expectedComponent)
518
- throw new Error("component mismatch");
519
- if (manifest.variant !== input.expectedVariant)
520
- throw new Error("component variant mismatch");
521
- if (manifest.productVersion !== input.expectedVersion)
522
- throw new Error("product version mismatch");
523
- if (canonicalArtifactJson(manifest.target) !== canonicalArtifactJson(input.target))
524
- throw new Error("component target mismatch");
525
- if (manifest.target.platform !== input.runtime.platform || manifest.target.architecture !== input.runtime.architecture)
526
- throw new Error("runtime target mismatch");
527
- if (!isVersion2(input.runtime.version) || !isVersion2(input.runtime.nodeVersion) || typeof input.runtime.modulesAbi !== "string" || !/^\d+$/.test(input.runtime.modulesAbi) || !Number.isSafeInteger(input.runtime.napiVersion) || input.runtime.napiVersion < 0)
528
- throw new Error("runtime identity is invalid");
529
- const versionMatches = manifest.runtimes.filter((item) => item.kind === input.runtime.kind && satisfies(input.runtime.version, item.runtimeRange) && satisfies(input.runtime.nodeVersion, item.nodeRange));
530
- if (!versionMatches.length)
531
- throw new Error("runtime version is incompatible");
532
- const abiMatches = versionMatches.filter((item) => item.modulesAbi === void 0 || item.modulesAbi === input.runtime.modulesAbi);
533
- if (!abiMatches.length)
534
- throw new Error("runtime ABI mismatch");
535
- const compatibility = abiMatches.find((item) => item.minimumNapi === void 0 || input.runtime.napiVersion >= item.minimumNapi);
536
- if (!compatibility)
537
- throw new Error("runtime N-API version is incompatible");
538
- if (manifest.target.libc) {
539
- const comparison = isVersion2(input.runtime.libcVersion) ? compareVersions(input.runtime.libcVersion, manifest.target.libc.minimumVersion) : void 0;
540
- if (comparison === void 0 || comparison < 0)
541
- throw new Error("runtime libc version is incompatible");
542
- }
543
- }
544
- function tarString(header, offset, length) {
545
- const value = header.subarray(offset, offset + length);
546
- const end = value.indexOf(0);
547
- return value.subarray(0, end < 0 ? value.length : end).toString("utf8");
548
- }
549
- function tarNumber(header, offset, length) {
550
- const text = tarString(header, offset, length).trim();
551
- if (!/^[0-7]+$/.test(text))
552
- throw new Error("malformed component tar numeric field");
553
- const number = Number.parseInt(text, 8);
554
- if (!Number.isSafeInteger(number))
555
- throw new Error("component tar field exceeds safe integer range");
556
- return number;
557
- }
558
- function* archiveChunks(archiveFd) {
559
- let position = 0;
560
- while (true) {
561
- const buffer = Buffer.allocUnsafe(64 * 1024);
562
- const bytesRead = readSync(archiveFd, buffer, 0, buffer.length, position);
563
- if (bytesRead === 0)
564
- return;
565
- position += bytesRead;
566
- yield buffer.subarray(0, bytesRead);
567
- }
568
- }
569
- async function* tarBlocks(stream) {
570
- let pending = Buffer.alloc(0);
571
- let totalBytes = 0;
572
- for await (const chunk of stream) {
573
- pending = pending.length ? Buffer.concat([pending, chunk]) : chunk;
574
- while (pending.length >= 512) {
575
- totalBytes += 512;
576
- if (totalBytes > MAX_TAR_BYTES)
577
- throw new Error("component archive exceeds expanded size limit");
578
- yield pending.subarray(0, 512);
579
- pending = pending.subarray(512);
232
+ if (response.status >= 500 && attempt < 2) {
233
+ await cancelBody(response);
234
+ await new Promise((resolveRetry) => setTimeout(resolveRetry, 100 * (attempt + 1)));
235
+ return fetchBounded(url.href, destination, limit, signal, progress, collectBytes, attempt + 1);
580
236
  }
581
- }
582
- if (pending.length)
583
- throw new Error("component archive has partial tar block");
584
- }
585
- async function verifyTarArchive(archiveFd, manifest) {
586
- const contents = /* @__PURE__ */ new Map();
587
- const seenPaths = /* @__PURE__ */ new Set();
588
- let expandedBytes = 0;
589
- let zeroBlocks = 0;
590
- let ended = false;
591
- const gunzip = createGunzip();
592
- const archiveSource = Readable.from(archiveChunks(archiveFd));
593
- const blocks = tarBlocks(archiveSource.pipe(gunzip));
594
- try {
595
- for await (const header of blocks) {
596
- if (ended) {
597
- if (!header.every((byte) => byte === 0))
598
- throw new Error("component archive contains data after tar terminator");
599
- continue;
237
+ if ([301, 302, 303, 307, 308].includes(response.status)) {
238
+ if (redirects >= MAX_REDIRECTS) {
239
+ await cancelBody(response);
240
+ throw new Error("too many component redirects");
600
241
  }
601
- if (header.every((byte) => byte === 0)) {
602
- zeroBlocks++;
603
- if (zeroBlocks === 2)
604
- ended = true;
605
- continue;
242
+ const location = response.headers.get("location");
243
+ if (!location) {
244
+ await cancelBody(response);
245
+ throw new Error("component redirect has no location");
606
246
  }
607
- if (zeroBlocks)
608
- throw new Error("component archive has incomplete tar terminator");
609
- const storedChecksum = tarNumber(header, 148, 8);
610
- const check = Buffer.from(header);
611
- check.fill(32, 148, 156);
612
- if (storedChecksum !== check.reduce((sum, byte) => sum + byte, 0))
613
- throw new Error("malformed component tar header checksum");
614
- const type = tarString(header, 156, 1) || "0";
615
- if (type === "1")
616
- throw new Error("component archives must not contain hard links");
617
- if (type === "2")
618
- throw new Error("component archives must not contain symbolic links");
619
- if (type !== "0" && type !== "5")
620
- throw new Error(`unsupported component tar entry type: ${type}`);
621
- const name = tarString(header, 0, 100);
622
- const prefix = tarString(header, 345, 155);
623
- const rawPath = prefix ? `${prefix}/${name}` : name;
624
- const path = rawPath.replace(/\/$/, "");
625
- safeRelativePath(path, "component archive path");
626
- const size = tarNumber(header, 124, 12);
627
- if (type === "5" && size !== 0)
628
- throw new Error("component directory tar entry must be empty");
629
- if (size > MAX_FILE_BYTES)
630
- throw new Error("component archive entry exceeds individual file limit");
631
- expandedBytes += size;
632
- if (expandedBytes > MAX_EXPANDED_BYTES)
633
- throw new Error("component archive exceeds expanded size limit");
634
- if (seenPaths.has(path))
635
- throw new Error(`duplicate component archive path: ${path}`);
636
- seenPaths.add(path);
637
- if (seenPaths.size > MAX_FILES)
638
- throw new Error("component archive exceeds file count limit");
639
- if (type === "5")
640
- continue;
641
- const digest = createHash2("sha256");
642
- let remaining = size;
643
- while (remaining > 0) {
644
- const data = await blocks.next();
645
- if (data.done)
646
- throw new Error("component archive is truncated");
647
- const count = Math.min(remaining, 512);
648
- digest.update(data.value.subarray(0, count));
649
- remaining -= count;
247
+ try {
248
+ url = new URL(location, url);
249
+ } catch {
250
+ await cancelBody(response);
251
+ throw new Error("component redirect URL is invalid");
252
+ }
253
+ if (url.protocol !== "https:" || url.username || url.password) {
254
+ await cancelBody(response);
255
+ throw new Error("component redirect requires safe HTTPS");
650
256
  }
651
- contents.set(path, digest.digest("hex"));
257
+ await cancelBody(response);
258
+ continue;
652
259
  }
653
- } finally {
654
- archiveSource.destroy();
655
- gunzip.destroy();
656
- }
657
- if (!ended)
658
- throw new Error("component archive is missing tar terminator");
659
- for (const path of contents.keys()) {
660
- const parents = path.split("/").slice(0, -1);
661
- for (let index = 1; index <= parents.length; index++) {
662
- const parentPath = parents.slice(0, index).join("/");
663
- if (contents.has(parentPath))
664
- throw new Error(`component archive file path conflict: ${parentPath}`);
260
+ if (!response.ok || !response.body) {
261
+ await cancelBody(response);
262
+ throw new Error(`component download failed with HTTP ${response.status}`);
665
263
  }
264
+ const length = Number(response.headers.get("content-length"));
265
+ if (Number.isFinite(length) && length > limit) {
266
+ await cancelBody(response);
267
+ throw new Error("component download exceeds size limit");
268
+ }
269
+ let transferredBytes = 0;
270
+ const chunks = [];
271
+ const limiter = new Transform({
272
+ transform(chunk, _encoding, callback) {
273
+ resetIdleTimeout();
274
+ transferredBytes += chunk.length;
275
+ if (transferredBytes > limit) {
276
+ callback(new Error("component download exceeds size limit"));
277
+ return;
278
+ }
279
+ progress?.({
280
+ phase: basename(destination),
281
+ transferredBytes,
282
+ ...Number.isFinite(length) && length > 0 ? { totalBytes: length } : {}
283
+ });
284
+ if (collectBytes)
285
+ chunks.push(Buffer.from(chunk));
286
+ callback(null, chunk);
287
+ }
288
+ });
289
+ const output = createWriteStream(destination, { flags: "wx", mode: 384 });
290
+ resetIdleTimeout();
291
+ try {
292
+ await pipeline(Readable.fromWeb(response.body), limiter, output, { signal: requestSignal });
293
+ } catch (error) {
294
+ rmSync(destination, { force: true });
295
+ if (signal?.aborted)
296
+ throw abortedError(signal, error);
297
+ if (timeoutController.signal.aborted)
298
+ throw stalledError(error);
299
+ if (attempt < 2 && error instanceof TypeError) {
300
+ await new Promise((resolveRetry) => setTimeout(resolveRetry, 100 * (attempt + 1)));
301
+ return fetchBounded(url.href, destination, limit, signal, progress, collectBytes, attempt + 1);
302
+ }
303
+ throw error;
304
+ } finally {
305
+ clearTimeout(timeout);
306
+ }
307
+ return collectBytes ? Buffer.concat(chunks) : void 0;
666
308
  }
667
- const expected = new Map(manifest.files.map((file) => [file.path, file.sha256]));
668
- if (contents.size !== expected.size)
669
- throw new Error("component archive file inventory mismatch");
670
- for (const [path, digest] of contents)
671
- if (!expected.has(path) || digest !== expected.get(path))
672
- throw new Error(`component archive file hash mismatch: ${path}`);
673
- for (const required of manifest.requiredFiles)
674
- if (!contents.has(required))
675
- throw new Error(`required component file is missing: ${required}`);
676
- }
677
- function verifyComponentManifestPin(input) {
678
- if (input.manifestBytes.length > MAX_MANIFEST_BYTES)
679
- throw new Error("component manifest exceeds size limit");
680
- let parsed;
681
- try {
682
- parsed = JSON.parse(input.manifestBytes.toString("utf8"));
683
- } catch {
684
- throw new Error("component manifest JSON is invalid");
685
- }
686
- validateComponentManifest(parsed);
687
- const manifest = parsed;
688
- const canonical = canonicalComponentManifestBytes(manifest);
689
- if (!canonical.equals(input.manifestBytes))
690
- throw new Error("component manifest is not canonical");
691
- const pinnedDigest = lookupManifestPin(input.manifestCatalog, {
692
- component: input.expectedComponent,
693
- ...input.expectedVariant === void 0 ? {} : { variant: input.expectedVariant },
694
- productVersion: input.expectedVersion,
695
- target: input.target
696
- });
697
- if (createHash2("sha256").update(canonical).digest("hex") !== pinnedDigest)
698
- throw new Error("component manifest pin mismatch");
699
- if (manifest.component !== input.expectedComponent)
700
- throw new Error("component mismatch");
701
- if (manifest.variant !== input.expectedVariant)
702
- throw new Error("component variant mismatch");
703
- if (manifest.productVersion !== input.expectedVersion)
704
- throw new Error("product version mismatch");
705
- if (canonicalArtifactJson(manifest.target) !== canonicalArtifactJson(input.target))
706
- throw new Error("component target mismatch");
707
- return manifest;
708
309
  }
709
- async function verifyComponentSync(input) {
710
- const manifest = verifyComponentManifestPin(input);
711
- verifyCompatibility(manifest, input);
712
- const stat = lstatSync2(input.archivePath);
713
- if (!stat.isFile() || stat.isSymbolicLink() || stat.size > MAX_ARCHIVE_BYTES)
714
- throw new Error("component archive is not a bounded regular file");
715
- if (basename(input.archivePath) !== manifest.archive.name)
716
- throw new Error("component archive name mismatch");
717
- if (stat.size !== manifest.archive.bytes)
718
- throw new Error("component archive size mismatch");
719
- if (constants2.O_NOFOLLOW === void 0)
720
- throw new Error("component archive no-follow access is unavailable");
721
- const archiveFd = openSync2(input.archivePath, constants2.O_RDONLY | constants2.O_NOFOLLOW);
310
+
311
+ // packages/koed-server/dist/directory-lock.js
312
+ import { mkdirSync, rmSync as rmSync2 } from "node:fs";
313
+ var acquireDirectoryLock = (path) => {
722
314
  try {
723
- const opened = fstatSync(archiveFd);
724
- if (!opened.isFile() || !sameObject(stat, opened))
725
- throw new Error("component archive changed during verification");
726
- const archiveHash = createHash2("sha256");
727
- for (const chunk of archiveChunks(archiveFd))
728
- archiveHash.update(chunk);
729
- if (!sameArchiveState(opened, fstatSync(archiveFd)))
730
- throw new Error("component archive changed during verification");
731
- if (archiveHash.digest("hex") !== manifest.archive.sha256)
732
- throw new Error("component archive SHA-256 mismatch");
733
- await verifyTarArchive(archiveFd, manifest);
734
- if (!sameArchiveState(opened, fstatSync(archiveFd)))
735
- throw new Error("component archive changed during verification");
736
- } finally {
737
- closeSync2(archiveFd);
738
- }
739
- return manifest;
740
- }
741
- var verifyComponent = (input) => verifyComponentSync(input);
742
- function hashFileDescriptor(fd) {
743
- const digest = createHash2("sha256");
744
- let position = 0;
745
- while (true) {
746
- const buffer = Buffer.allocUnsafe(64 * 1024);
747
- const bytesRead = readSync(fd, buffer, 0, buffer.length, position);
748
- if (bytesRead === 0)
749
- return digest.digest("hex");
750
- digest.update(buffer.subarray(0, bytesRead));
751
- position += bytesRead;
315
+ mkdirSync(path, { mode: 448 });
316
+ } catch (error) {
317
+ if (error.code !== "EEXIST")
318
+ throw error;
319
+ throw Object.assign(new Error("lock is already held"), { code: "ELOCKED" });
752
320
  }
753
- }
754
- function sameObject(left, right) {
755
- return left.dev === right.dev && left.ino === right.ino;
756
- }
757
- function sameArchiveState(left, right) {
758
- return sameObject(left, right) && left.size === right.size && left.mtimeMs === right.mtimeMs && left.ctimeMs === right.ctimeMs;
759
- }
760
- var EXTRACTED_TREE_LIMITS = {
761
- maxFileBytes: MAX_FILE_BYTES,
762
- maxExpandedBytes: MAX_EXPANDED_BYTES,
763
- maxFiles: MAX_FILES,
764
- maxDirectories: MAX_DIRECTORIES,
765
- maxDepth: MAX_DEPTH,
766
- maxEntries: MAX_FILES + MAX_DIRECTORIES
321
+ let released = false;
322
+ return () => {
323
+ if (released)
324
+ return;
325
+ released = true;
326
+ rmSync2(path, { recursive: true, force: true });
327
+ };
767
328
  };
768
- function verifyExtractedComponentSync(root, manifest, seams = {}) {
769
- validateComponentManifest(manifest);
770
- const canonicalRoot = resolve2(root);
771
- const rootStat = lstatSync2(canonicalRoot);
772
- if (rootStat.isSymbolicLink() || !rootStat.isDirectory())
773
- throw new Error("component root is not a regular directory");
774
- const observed = /* @__PURE__ */ new Set();
775
- const expectedFiles = new Map(manifest.files.map((file) => [file.path, file.sha256]));
776
- const limits = { ...EXTRACTED_TREE_LIMITS, ...seams.limits };
777
- const stack = [canonicalRoot];
778
- let directories = 0;
779
- let entries = 0;
780
- let totalBytes = 0;
781
- while (stack.length) {
782
- const current = stack.pop();
783
- const beforeDirectory = lstatSync2(current);
784
- if (!beforeDirectory.isDirectory() || beforeDirectory.isSymbolicLink())
785
- throw new Error("component directory ancestry changed during verification");
786
- seams.beforeReadDirectory?.(current);
787
- const directoryEntries = readdirSync2(current, { withFileTypes: true });
788
- for (const entry of directoryEntries) {
789
- if (++entries > limits.maxEntries)
790
- throw new Error("component tree exceeds entry count limit");
791
- const path = resolve2(current, entry.name);
792
- const relativePath = relative2(canonicalRoot, path).split(sep2).join("/");
793
- safeRelativePath(relativePath, "extracted component path");
794
- const stat = lstatSync2(path);
795
- if (stat.isSymbolicLink() || !stat.isFile() && !stat.isDirectory())
796
- throw new Error("component files must not contain links or special files");
797
- if (stat.isDirectory()) {
798
- if (++directories > limits.maxDirectories)
799
- throw new Error("component tree exceeds directory count limit");
800
- const depth = relativePath.split("/").length;
801
- if (depth > limits.maxDepth)
802
- throw new Error("component tree exceeds directory depth limit");
803
- stack.push(path);
804
- continue;
805
- }
806
- if (stat.nlink > 1)
807
- throw new Error("component files must not contain links or special files");
808
- if (stat.size > limits.maxFileBytes)
809
- throw new Error("component file exceeds individual file limit");
810
- totalBytes += stat.size;
811
- if (totalBytes > limits.maxExpandedBytes)
812
- throw new Error("component tree exceeds expanded size limit");
813
- if (observed.size >= limits.maxFiles)
814
- throw new Error("component tree exceeds file count limit");
815
- observed.add(relativePath);
816
- const expectedHash = expectedFiles.get(relativePath);
817
- seams.beforeOpenFile?.(path);
818
- if (constants2.O_NOFOLLOW === void 0)
819
- throw new Error("component file no-follow access is unavailable");
820
- const fd = openSync2(path, constants2.O_RDONLY | constants2.O_NOFOLLOW);
821
- try {
822
- const opened = fstatSync(fd);
823
- if (!opened.isFile() || !sameObject(stat, opened))
824
- throw new Error("component file changed during verification");
825
- const fileHash = hashFileDescriptor(fd);
826
- const after = fstatSync(fd);
827
- const afterPath = lstatSync2(path);
828
- if (!sameArchiveState(opened, after) || !sameArchiveState(after, afterPath))
829
- throw new Error("component file changed during verification");
830
- if (!expectedHash || fileHash !== expectedHash)
831
- throw new Error(`component file hash mismatch: ${relativePath}`);
832
- } finally {
833
- closeSync2(fd);
834
- }
329
+
330
+ // packages/koed-server/dist/component-runtime-identity.js
331
+ import process3 from "node:process";
332
+ var isVersion = (value) => typeof value === "string" && /^(?:0|[1-9]\d*)(?:\.(?:0|[1-9]\d*)){1,2}$/.test(value) && value.split(".").every((part) => Number.isSafeInteger(Number(part)));
333
+ function discoverRuntimeIdentityFromProcess(source) {
334
+ const platform = source.platform === "darwin" ? "macos" : source.platform === "linux" ? "linux" : void 0;
335
+ const architecture = source.arch === "arm64" || source.arch === "x64" ? source.arch : void 0;
336
+ const runtimeVersion = source.versions.electron ?? source.versions.node;
337
+ const nodeVersion = source.versions.node;
338
+ const modulesAbi = source.versions.modules;
339
+ const napiVersion = Number(source.versions.napi ?? "0");
340
+ let libcVersion;
341
+ if (platform === "linux") {
342
+ try {
343
+ libcVersion = source.report?.getReport().header?.glibcVersionRuntime;
344
+ } catch {
345
+ throw new Error("actual runtime identity is unsupported or incomplete");
835
346
  }
836
- if (!sameObject(beforeDirectory, lstatSync2(current)))
837
- throw new Error("component directory ancestry changed during verification");
838
347
  }
839
- for (const file of manifest.files)
840
- if (!observed.has(file.path))
841
- throw new Error(`required component file is missing or incomplete: ${file.path}`);
842
- for (const file of manifest.requiredFiles)
843
- if (!observed.has(file))
844
- throw new Error(`required component file is missing: ${file}`);
348
+ if (!platform || !architecture || !isVersion(runtimeVersion) || !isVersion(nodeVersion) || typeof modulesAbi !== "string" || !/^\d+$/.test(modulesAbi) || !Number.isSafeInteger(napiVersion) || napiVersion < 0 || platform === "linux" && !isVersion(libcVersion))
349
+ throw new Error("actual runtime identity is unsupported or incomplete");
350
+ return {
351
+ kind: source.versions.electron === void 0 ? "node" : "electron",
352
+ version: runtimeVersion,
353
+ nodeVersion,
354
+ modulesAbi,
355
+ napiVersion,
356
+ platform,
357
+ architecture,
358
+ ...libcVersion === void 0 ? {} : { libcVersion }
359
+ };
360
+ }
361
+ function discoverActualRuntimeIdentity() {
362
+ return discoverRuntimeIdentityFromProcess(process3);
845
363
  }
846
- var verifyExtractedComponent = (root, manifest) => Promise.resolve().then(() => verifyExtractedComponentSync(root, manifest));
847
364
 
848
365
  // packages/koed-server/dist/component-store.js
849
- var MAX_MANIFEST_BYTES2 = 64 * 1024 * 1024;
850
- var MAX_ARCHIVE_BYTES2 = 2 * 1024 * 1024 * 1024;
851
- var MAX_REDIRECTS = 5;
852
- var MAX_GENERATION_RECORD_BYTES = 2 * MAX_MANIFEST_BYTES2 + 1024 * 1024;
853
- var REQUEST_TIMEOUT_MS = 3e4;
854
- var hash2 = (value) => createHash3("sha256").update(value).digest("hex");
366
+ var MAX_MANIFEST_BYTES = 64 * 1024 * 1024;
367
+ var MAX_ARCHIVE_BYTES = 2 * 1024 * 1024 * 1024;
368
+ var MAX_GENERATION_RECORD_BYTES = 2 * MAX_MANIFEST_BYTES + 1024 * 1024;
369
+ var hash2 = (value) => createHash2("sha256").update(value).digest("hex");
855
370
  var isPlainRecord = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
856
371
  var aborted = (signal) => {
857
372
  if (signal?.aborted)
858
373
  throw new Error("component installation cancelled");
859
374
  };
860
- var cancelBody = async (response) => {
861
- try {
862
- await response.body?.cancel();
863
- } catch {
864
- }
865
- };
866
375
  var exactKeys = (value, keys) => Object.keys(value).length === keys.length && keys.every((key) => Object.hasOwn(value, key));
867
376
  var assertInside = (base, path) => {
868
- const rel = relative3(resolve3(base), resolve3(path));
869
- if (rel.startsWith("..") || isAbsolute3(rel))
377
+ const rel = relative2(resolve2(base), resolve2(path));
378
+ if (rel.startsWith("..") || isAbsolute2(rel))
870
379
  throw new Error("component store path escaped KOED_HOME");
871
380
  };
872
381
  var assertDirectoryChain = (base, path) => {
873
382
  assertInside(base, path);
874
- const absolute = resolve3(path);
383
+ const absolute = resolve2(path);
875
384
  let cursor = parse(absolute).root;
876
- for (const part of absolute.slice(cursor.length).split(sep3).filter(Boolean)) {
877
- cursor = resolve3(cursor, part);
385
+ for (const part of absolute.slice(cursor.length).split(sep2).filter(Boolean)) {
386
+ cursor = resolve2(cursor, part);
878
387
  let stat;
879
388
  try {
880
- stat = lstatSync3(cursor);
389
+ stat = lstatSync2(cursor);
881
390
  } catch (error) {
882
391
  if (error.code === "ENOENT")
883
392
  return;
@@ -889,12 +398,12 @@ var assertDirectoryChain = (base, path) => {
889
398
  };
890
399
  var ensureSecureDirectory = (home, directory) => {
891
400
  assertDirectoryChain(home, directory);
892
- mkdirSync3(directory, { recursive: true, mode: 448 });
401
+ mkdirSync2(directory, { recursive: true, mode: 448 });
893
402
  assertDirectoryChain(home, directory);
894
403
  };
895
404
  var privateDirectory = (path) => {
896
- mkdirSync3(path, { recursive: true, mode: 448 });
897
- const stat = lstatSync3(path);
405
+ mkdirSync2(path, { recursive: true, mode: 448 });
406
+ const stat = lstatSync2(path);
898
407
  if (!stat.isDirectory() || stat.isSymbolicLink())
899
408
  throw new Error("component store directory is not a regular directory");
900
409
  chmodSync(path, 448);
@@ -953,149 +462,38 @@ var resolveComponentManifestPinTarget = (catalog, input) => {
953
462
  return target;
954
463
  };
955
464
  var parseJsonFile = (path, maxBytes, requireCanonical = false) => {
956
- if (constants3.O_NOFOLLOW === void 0)
465
+ if (constants2.O_NOFOLLOW === void 0)
957
466
  throw new Error("component metadata no-follow access is unavailable");
958
- const descriptor = openSync3(path, constants3.O_RDONLY | constants3.O_NOFOLLOW);
467
+ const descriptor = openSync2(path, constants2.O_RDONLY | constants2.O_NOFOLLOW);
959
468
  try {
960
- const stat = fstatSync2(descriptor);
469
+ const stat = fstatSync(descriptor);
961
470
  if (!stat.isFile() || stat.size > maxBytes)
962
471
  throw new Error("component metadata is not a bounded regular file");
963
- const bytes = readFileSync3(descriptor, "utf8");
472
+ const bytes = readFileSync2(descriptor, "utf8");
964
473
  const value = JSON.parse(bytes);
965
474
  if (requireCanonical && canonicalArtifactJson(value) !== bytes)
966
475
  throw new Error("component metadata is not canonical JSON");
967
476
  return value;
968
477
  } finally {
969
- closeSync3(descriptor);
478
+ closeSync2(descriptor);
970
479
  }
971
480
  };
972
481
  var readOfflineSource = (source) => {
973
- const archivePath = resolve3(source.archivePath);
974
- const archiveStat = lstatSync3(archivePath);
975
- if (!archiveStat.isFile() || archiveStat.isSymbolicLink() || archiveStat.size > MAX_ARCHIVE_BYTES2)
482
+ const archivePath = resolve2(source.archivePath);
483
+ const archiveStat = lstatSync2(archivePath);
484
+ if (!archiveStat.isFile() || archiveStat.isSymbolicLink() || archiveStat.size > MAX_ARCHIVE_BYTES)
976
485
  throw new Error("component archive is not a bounded regular file");
977
486
  return {
978
487
  archivePath,
979
- manifestBytes: readBoundedFile(source.manifestPath, MAX_MANIFEST_BYTES2)
488
+ manifestBytes: readBoundedFile(source.manifestPath, MAX_MANIFEST_BYTES)
980
489
  };
981
490
  };
982
491
  var readBoundedFile = (path, limit) => {
983
- const stat = lstatSync3(path);
492
+ const stat = lstatSync2(path);
984
493
  if (!stat.isFile() || stat.isSymbolicLink() || stat.size > limit)
985
494
  throw new Error("component metadata is not a bounded regular file");
986
- return readFileSync3(path);
495
+ return readFileSync2(path);
987
496
  };
988
- async function fetchBounded(urlText, destination, limit, signal, progress, collectBytes = true, attempt = 0) {
989
- let url;
990
- try {
991
- url = new URL(urlText);
992
- } catch {
993
- throw new Error("component source URL is invalid");
994
- }
995
- if (url.protocol !== "https:" || url.username || url.password)
996
- throw new Error("component downloads require safe HTTPS URLs");
997
- for (let redirects = 0; ; redirects++) {
998
- aborted(signal);
999
- let response;
1000
- const timeoutController = new AbortController();
1001
- const requestSignal = signal ? AbortSignal.any([signal, timeoutController.signal]) : timeoutController.signal;
1002
- let timeout = setTimeout(() => timeoutController.abort(), REQUEST_TIMEOUT_MS);
1003
- const resetIdleTimeout = () => {
1004
- clearTimeout(timeout);
1005
- timeout = setTimeout(() => timeoutController.abort(), REQUEST_TIMEOUT_MS);
1006
- };
1007
- try {
1008
- response = await fetch(url, {
1009
- redirect: "manual",
1010
- signal: requestSignal
1011
- });
1012
- } catch (error) {
1013
- if (signal?.aborted)
1014
- throw new Error("component installation cancelled", { cause: error });
1015
- if (attempt < 2 && error instanceof TypeError) {
1016
- await new Promise((resolveRetry) => setTimeout(resolveRetry, 100 * (attempt + 1)));
1017
- return fetchBounded(url.href, destination, limit, signal, progress, collectBytes, attempt + 1);
1018
- }
1019
- throw error;
1020
- } finally {
1021
- clearTimeout(timeout);
1022
- }
1023
- if (response.status >= 500 && attempt < 2) {
1024
- await cancelBody(response);
1025
- await new Promise((resolveRetry) => setTimeout(resolveRetry, 100 * (attempt + 1)));
1026
- return fetchBounded(url.href, destination, limit, signal, progress, collectBytes, attempt + 1);
1027
- }
1028
- if ([301, 302, 303, 307, 308].includes(response.status)) {
1029
- if (redirects >= MAX_REDIRECTS) {
1030
- await cancelBody(response);
1031
- throw new Error("too many component redirects");
1032
- }
1033
- const location = response.headers.get("location");
1034
- if (!location) {
1035
- await cancelBody(response);
1036
- throw new Error("component redirect has no location");
1037
- }
1038
- try {
1039
- url = new URL(location, url);
1040
- } catch {
1041
- await cancelBody(response);
1042
- throw new Error("component redirect URL is invalid");
1043
- }
1044
- if (url.protocol !== "https:" || url.username || url.password) {
1045
- await cancelBody(response);
1046
- throw new Error("component redirect requires safe HTTPS");
1047
- }
1048
- await cancelBody(response);
1049
- continue;
1050
- }
1051
- if (!response.ok || !response.body) {
1052
- await cancelBody(response);
1053
- throw new Error(`component download failed with HTTP ${response.status}`);
1054
- }
1055
- const length = Number(response.headers.get("content-length"));
1056
- if (Number.isFinite(length) && length > limit) {
1057
- await cancelBody(response);
1058
- throw new Error("component download exceeds size limit");
1059
- }
1060
- let transferredBytes = 0;
1061
- const chunks = [];
1062
- const limiter = new Transform({
1063
- transform(chunk, _encoding, callback) {
1064
- resetIdleTimeout();
1065
- transferredBytes += chunk.length;
1066
- if (transferredBytes > limit) {
1067
- callback(new Error("component download exceeds size limit"));
1068
- return;
1069
- }
1070
- progress?.({
1071
- phase: basename2(destination),
1072
- transferredBytes,
1073
- ...Number.isFinite(length) && length > 0 ? { totalBytes: length } : {}
1074
- });
1075
- if (collectBytes)
1076
- chunks.push(Buffer.from(chunk));
1077
- callback(null, chunk);
1078
- }
1079
- });
1080
- const output = createWriteStream(destination, { flags: "wx", mode: 384 });
1081
- resetIdleTimeout();
1082
- try {
1083
- await pipeline(Readable2.fromWeb(response.body), limiter, output, { signal: requestSignal });
1084
- } catch (error) {
1085
- rmSync3(destination, { force: true });
1086
- if (signal?.aborted)
1087
- throw new Error("component installation cancelled", { cause: error });
1088
- if (attempt < 2 && error instanceof TypeError) {
1089
- await new Promise((resolveRetry) => setTimeout(resolveRetry, 100 * (attempt + 1)));
1090
- return fetchBounded(url.href, destination, limit, signal, progress, collectBytes, attempt + 1);
1091
- }
1092
- throw error;
1093
- } finally {
1094
- clearTimeout(timeout);
1095
- }
1096
- return collectBytes ? Buffer.concat(chunks) : void 0;
1097
- }
1098
- }
1099
497
  async function acquireLock(home, root, signal, fn) {
1100
498
  ensureSecureDirectory(home, root);
1101
499
  let release;
@@ -1145,23 +543,23 @@ function validateOwner(owner) {
1145
543
  throw new Error("runtime owner is invalid");
1146
544
  }
1147
545
  function writeIndex(home, indexPath, manifestDigest, tempRoot, signal) {
1148
- const temporaryIndex = resolve3(tempRoot, `index-${manifestDigest}.json`);
1149
- writeFileSync2(temporaryIndex, JSON.stringify({ manifestDigest }), {
546
+ const temporaryIndex = resolve2(tempRoot, `index-${manifestDigest}.json`);
547
+ writeFileSync(temporaryIndex, JSON.stringify({ manifestDigest }), {
1150
548
  flag: "wx",
1151
549
  mode: 384
1152
550
  });
1153
551
  aborted(signal);
1154
- assertDirectoryChain(home, dirname2(indexPath));
1155
- renameSync2(temporaryIndex, indexPath);
552
+ assertDirectoryChain(home, dirname(indexPath));
553
+ renameSync(temporaryIndex, indexPath);
1156
554
  }
1157
555
  function componentRecordPath(root) {
1158
- return resolve3(root, "component.json");
556
+ return resolve2(root, "component.json");
1159
557
  }
1160
558
  function componentPayloadPath(root) {
1161
- return resolve3(root, "payload");
559
+ return resolve2(root, "payload");
1162
560
  }
1163
561
  function readComponentRecord(path) {
1164
- const value = parseJsonFile(path, MAX_MANIFEST_BYTES2 + 32768);
562
+ const value = parseJsonFile(path, MAX_MANIFEST_BYTES + 32768);
1165
563
  if (isPlainRecord(value) && value.schemaVersion === 1)
1166
564
  throw new Error("Stored component predates manifest pin admission; reinstall components using a trusted versioned control plane.");
1167
565
  if (!isPlainRecord(value) || !exactKeys(value, [
@@ -1199,7 +597,7 @@ async function verifyStoredComponent(home, root, expected) {
1199
597
  },
1200
598
  runtime: expected.runtime
1201
599
  });
1202
- const archivePath = resolve3(root, record.archivePath);
600
+ const archivePath = resolve2(root, record.archivePath);
1203
601
  assertInside(root, archivePath);
1204
602
  const manifest = await verifyComponent({
1205
603
  manifestBytes,
@@ -1211,9 +609,9 @@ async function verifyStoredComponent(home, root, expected) {
1211
609
  target,
1212
610
  runtime: expected.runtime
1213
611
  });
1214
- if (archivePath !== resolve3(root, manifest.archive.name))
612
+ if (archivePath !== resolve2(root, manifest.archive.name))
1215
613
  throw new Error("stored component archive path is invalid");
1216
- const archiveStat = lstatSync3(archivePath);
614
+ const archiveStat = lstatSync2(archivePath);
1217
615
  if (!archiveStat.isFile() || archiveStat.isSymbolicLink())
1218
616
  throw new Error("stored component archive is not a regular file");
1219
617
  const payload = componentPayloadPath(root);
@@ -1228,11 +626,11 @@ async function verifyStoredComponent(home, root, expected) {
1228
626
  }
1229
627
  async function stageComponentInternal(paths, source, context, runtime) {
1230
628
  aborted(context.signal);
1231
- const storeRoot = resolve3(paths.componentsDir);
629
+ const storeRoot = resolve2(paths.componentsDir);
1232
630
  assertInside(paths.koedHome, storeRoot);
1233
631
  assertDirectoryChain(paths.koedHome, storeRoot);
1234
632
  ensureSecureDirectory(paths.koedHome, storeRoot);
1235
- const tempRoot = mkdtempSync(resolve3(storeRoot, ".stage-"));
633
+ const tempRoot = mkdtempSync(resolve2(storeRoot, ".stage-"));
1236
634
  chmodSync(tempRoot, 448);
1237
635
  try {
1238
636
  const catalog = readProductionManifestPinCatalog();
@@ -1240,7 +638,7 @@ async function stageComponentInternal(paths, source, context, runtime) {
1240
638
  if (source.kind === "offline") {
1241
639
  manifestBytes = readOfflineSource(source).manifestBytes;
1242
640
  } else {
1243
- manifestBytes = await fetchBounded(source.manifestUrl, resolve3(tempRoot, "manifest.json"), MAX_MANIFEST_BYTES2, context.signal, context.progress);
641
+ manifestBytes = await fetchBounded(source.manifestUrl, resolve2(tempRoot, "manifest.json"), MAX_MANIFEST_BYTES, context.signal, context.progress);
1244
642
  }
1245
643
  if (context.target.platform !== runtime.platform || context.target.architecture !== runtime.architecture)
1246
644
  throw new Error("component target does not match actual runtime");
@@ -1259,12 +657,12 @@ async function stageComponentInternal(paths, source, context, runtime) {
1259
657
  expectedVersion: context.expectedVersion,
1260
658
  target
1261
659
  });
1262
- const archivePath = resolve3(tempRoot, manifest.archive.name);
660
+ const archivePath = resolve2(tempRoot, manifest.archive.name);
1263
661
  if (source.kind === "offline") {
1264
- copyFileSync(resolve3(source.archivePath), archivePath, 1);
662
+ copyFileSync(resolve2(source.archivePath), archivePath, 1);
1265
663
  chmodSync(archivePath, 384);
1266
664
  } else {
1267
- await fetchBounded(source.archiveUrl, archivePath, MAX_ARCHIVE_BYTES2, context.signal, context.progress, false);
665
+ await fetchBounded(source.archiveUrl, archivePath, MAX_ARCHIVE_BYTES, context.signal, context.progress, false);
1268
666
  }
1269
667
  aborted(context.signal);
1270
668
  context.progress?.({ phase: "verify", transferredBytes: 0 });
@@ -1280,12 +678,12 @@ async function stageComponentInternal(paths, source, context, runtime) {
1280
678
  });
1281
679
  aborted(context.signal);
1282
680
  const manifestDigest = hash2(manifestBytes);
1283
- const componentDir = resolve3(storeRoot, manifest.component);
681
+ const componentDir = resolve2(storeRoot, manifest.component);
1284
682
  assertDirectoryChain(paths.koedHome, componentDir);
1285
- const indexPath = resolve3(componentDir, `${targetKey(manifest)}.json`);
1286
- const versionRoot = resolve3(componentDir, manifest.productVersion, manifestDigest);
1287
- const stagedRoot = resolve3(tempRoot, "verified");
1288
- const completeRoot = resolve3(tempRoot, "complete");
683
+ const indexPath = resolve2(componentDir, `${targetKey(manifest)}.json`);
684
+ const versionRoot = resolve2(componentDir, manifest.productVersion, manifestDigest);
685
+ const stagedRoot = resolve2(tempRoot, "verified");
686
+ const completeRoot = resolve2(tempRoot, "complete");
1289
687
  aborted(context.signal);
1290
688
  context.progress?.({ phase: "extract", transferredBytes: 0 });
1291
689
  await extractVerifiedPackageArchive(archivePath, stagedRoot);
@@ -1293,24 +691,24 @@ async function stageComponentInternal(paths, source, context, runtime) {
1293
691
  await verifyExtractedComponent(stagedRoot, manifest);
1294
692
  aborted(context.signal);
1295
693
  privateDirectory(completeRoot);
1296
- renameSync2(stagedRoot, resolve3(completeRoot, "payload"));
1297
- renameSync2(archivePath, resolve3(completeRoot, manifest.archive.name));
1298
- writeFileSync2(componentRecordPath(completeRoot), JSON.stringify({
694
+ renameSync(stagedRoot, resolve2(completeRoot, "payload"));
695
+ renameSync(archivePath, resolve2(completeRoot, manifest.archive.name));
696
+ writeFileSync(componentRecordPath(completeRoot), JSON.stringify({
1299
697
  schemaVersion: 2,
1300
698
  manifest,
1301
699
  manifestDigest,
1302
- archivePath: resolve3(versionRoot, manifest.archive.name)
700
+ archivePath: resolve2(versionRoot, manifest.archive.name)
1303
701
  }), { flag: "wx", mode: 384 });
1304
702
  return await acquireLock(paths.koedHome, storeRoot, context.signal, async () => {
1305
703
  ensureSecureDirectory(paths.koedHome, componentDir);
1306
704
  assertDirectoryChain(paths.koedHome, versionRoot);
1307
- assertDirectoryChain(paths.koedHome, dirname2(indexPath));
1308
- if (existsSync2(indexPath)) {
705
+ assertDirectoryChain(paths.koedHome, dirname(indexPath));
706
+ if (existsSync(indexPath)) {
1309
707
  const index = parseJsonFile(indexPath, 4096);
1310
708
  if (!isPlainRecord(index) || index.manifestDigest !== manifestDigest)
1311
709
  throw new Error("component version already installed with different digest");
1312
710
  }
1313
- if (existsSync2(versionRoot)) {
711
+ if (existsSync(versionRoot)) {
1314
712
  const cached = await verifyStoredComponent(paths.koedHome, versionRoot, {
1315
713
  component: manifest.component,
1316
714
  productVersion: manifest.productVersion,
@@ -1320,25 +718,25 @@ async function stageComponentInternal(paths, source, context, runtime) {
1320
718
  aborted(context.signal);
1321
719
  if (cached.manifestDigest !== manifestDigest)
1322
720
  throw new Error("component version already installed with different digest");
1323
- if (!existsSync2(indexPath)) {
721
+ if (!existsSync(indexPath)) {
1324
722
  aborted(context.signal);
1325
- assertDirectoryChain(paths.koedHome, dirname2(indexPath));
723
+ assertDirectoryChain(paths.koedHome, dirname(indexPath));
1326
724
  writeIndex(paths.koedHome, indexPath, manifestDigest, tempRoot, context.signal);
1327
725
  }
1328
726
  return cached;
1329
727
  }
1330
- if (existsSync2(indexPath))
728
+ if (existsSync(indexPath))
1331
729
  throw new Error("component cache record is missing");
1332
- ensureSecureDirectory(paths.koedHome, dirname2(versionRoot));
730
+ ensureSecureDirectory(paths.koedHome, dirname(versionRoot));
1333
731
  let publishedRoot;
1334
732
  let committed = false;
1335
733
  try {
1336
734
  aborted(context.signal);
1337
- assertDirectoryChain(paths.koedHome, dirname2(versionRoot));
1338
- renameSync2(completeRoot, versionRoot);
735
+ assertDirectoryChain(paths.koedHome, dirname(versionRoot));
736
+ renameSync(completeRoot, versionRoot);
1339
737
  publishedRoot = versionRoot;
1340
738
  aborted(context.signal);
1341
- assertDirectoryChain(paths.koedHome, dirname2(indexPath));
739
+ assertDirectoryChain(paths.koedHome, dirname(indexPath));
1342
740
  writeIndex(paths.koedHome, indexPath, manifestDigest, tempRoot, context.signal);
1343
741
  committed = true;
1344
742
  return {
@@ -1367,21 +765,21 @@ async function stageGeneration(paths, input) {
1367
765
  validateOwner(input.owner);
1368
766
  const { base, privacy } = input;
1369
767
  assertDirectoryChain(paths.koedHome, paths.componentsDir);
1370
- assertDirectoryChain(paths.componentsDir, dirname2(base.root));
1371
- const baseVerified = await verifyStoredComponent(paths.koedHome, dirname2(base.root), {
768
+ assertDirectoryChain(paths.componentsDir, dirname(base.root));
769
+ const baseVerified = await verifyStoredComponent(paths.koedHome, dirname(base.root), {
1372
770
  component: "base",
1373
771
  runtime: actualRuntime
1374
772
  });
1375
- if (baseVerified.manifestDigest !== base.manifestDigest || resolve3(baseVerified.root) !== resolve3(base.root))
773
+ if (baseVerified.manifestDigest !== base.manifestDigest || resolve2(baseVerified.root) !== resolve2(base.root))
1376
774
  throw new Error("base component is not a verified store entry");
1377
775
  let privacyVerified;
1378
776
  if (privacy) {
1379
- assertDirectoryChain(paths.componentsDir, dirname2(privacy.root));
1380
- privacyVerified = await verifyStoredComponent(paths.koedHome, dirname2(privacy.root), {
777
+ assertDirectoryChain(paths.componentsDir, dirname(privacy.root));
778
+ privacyVerified = await verifyStoredComponent(paths.koedHome, dirname(privacy.root), {
1381
779
  component: "privacy",
1382
780
  runtime: actualRuntime
1383
781
  });
1384
- if (privacyVerified.manifestDigest !== privacy.manifestDigest || resolve3(privacyVerified.root) !== resolve3(privacy.root))
782
+ if (privacyVerified.manifestDigest !== privacy.manifestDigest || resolve2(privacyVerified.root) !== resolve2(privacy.root))
1385
783
  throw new Error("privacy component is not a verified store entry");
1386
784
  }
1387
785
  if (privacyVerified && baseVerified.manifest.productVersion !== privacyVerified.manifest.productVersion)
@@ -1394,31 +792,31 @@ async function stageGeneration(paths, input) {
1394
792
  owner: input.owner,
1395
793
  base: {
1396
794
  manifestDigest: baseVerified.manifestDigest,
1397
- root: relative3(paths.koedHome, baseVerified.root)
795
+ root: relative2(paths.koedHome, baseVerified.root)
1398
796
  },
1399
797
  ...privacyVerified ? {
1400
798
  privacy: {
1401
799
  manifestDigest: privacyVerified.manifestDigest,
1402
- root: relative3(paths.koedHome, privacyVerified.root)
800
+ root: relative2(paths.koedHome, privacyVerified.root)
1403
801
  }
1404
802
  } : {}
1405
803
  };
1406
804
  const id = hash2(canonicalArtifactJson(identity));
1407
- const generationRoot = resolve3(paths.generationsDir, id);
805
+ const generationRoot = resolve2(paths.generationsDir, id);
1408
806
  assertDirectoryChain(paths.koedHome, generationRoot);
1409
807
  assertDirectoryChain(paths.koedHome, paths.generationsDir);
1410
808
  return acquireLock(paths.koedHome, paths.generationsDir, void 0, async () => {
1411
- if (existsSync2(generationRoot))
809
+ if (existsSync(generationRoot))
1412
810
  return readStagedGeneration(paths, id);
1413
811
  ensureSecureDirectory(paths.koedHome, paths.generationsDir);
1414
- const tempRoot = mkdtempSync(resolve3(paths.generationsDir, ".stage-"));
812
+ const tempRoot = mkdtempSync(resolve2(paths.generationsDir, ".stage-"));
1415
813
  chmodSync(tempRoot, 448);
1416
814
  try {
1417
- const freshBase = await verifyStoredComponent(paths.koedHome, dirname2(baseVerified.root), {
815
+ const freshBase = await verifyStoredComponent(paths.koedHome, dirname(baseVerified.root), {
1418
816
  component: "base",
1419
817
  runtime: actualRuntime
1420
818
  });
1421
- const freshPrivacy = privacyVerified ? await verifyStoredComponent(paths.koedHome, dirname2(privacyVerified.root), {
819
+ const freshPrivacy = privacyVerified ? await verifyStoredComponent(paths.koedHome, dirname(privacyVerified.root), {
1422
820
  component: "privacy",
1423
821
  runtime: actualRuntime
1424
822
  }) : void 0;
@@ -1441,13 +839,13 @@ async function stageGeneration(paths, input) {
1441
839
  const recordBytes = Buffer.from(canonicalArtifactJson(record));
1442
840
  if (recordBytes.length > MAX_GENERATION_RECORD_BYTES)
1443
841
  throw new Error("generation record exceeds size limit");
1444
- writeFileSync2(resolve3(tempRoot, "generation.json"), recordBytes, {
842
+ writeFileSync(resolve2(tempRoot, "generation.json"), recordBytes, {
1445
843
  flag: "wx",
1446
844
  mode: 384
1447
845
  });
1448
846
  assertDirectoryChain(paths.koedHome, paths.generationsDir);
1449
847
  assertDirectoryChain(paths.generationsDir, generationRoot);
1450
- renameSync2(tempRoot, generationRoot);
848
+ renameSync(tempRoot, generationRoot);
1451
849
  return {
1452
850
  id,
1453
851
  productVersion: identity.productVersion,
@@ -1456,7 +854,7 @@ async function stageGeneration(paths, input) {
1456
854
  owner: input.owner
1457
855
  };
1458
856
  } finally {
1459
- if (existsSync2(tempRoot))
857
+ if (existsSync(tempRoot))
1460
858
  rmSync3(tempRoot, { recursive: true, force: true });
1461
859
  }
1462
860
  });
@@ -1464,23 +862,23 @@ async function stageGeneration(paths, input) {
1464
862
  async function readStoredComponents(paths, runtime) {
1465
863
  const components = [];
1466
864
  for (const component of ["base", "privacy"]) {
1467
- const componentRoot = resolve3(paths.componentsDir, component);
1468
- if (!existsSync2(componentRoot))
865
+ const componentRoot = resolve2(paths.componentsDir, component);
866
+ if (!existsSync(componentRoot))
1469
867
  continue;
1470
868
  assertDirectoryChain(paths.koedHome, componentRoot);
1471
- for (const versionEntry of readdirSync3(componentRoot, {
869
+ for (const versionEntry of readdirSync2(componentRoot, {
1472
870
  withFileTypes: true
1473
871
  })) {
1474
872
  if (!versionEntry.isDirectory() || !/^(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)(?:\.(?:0|[1-9]\d*))?(?:-[0-9A-Za-z.-]+)?$/.test(versionEntry.name))
1475
873
  continue;
1476
- const versionRoot = resolve3(componentRoot, versionEntry.name);
1477
- for (const digestEntry of readdirSync3(versionRoot, {
874
+ const versionRoot = resolve2(componentRoot, versionEntry.name);
875
+ for (const digestEntry of readdirSync2(versionRoot, {
1478
876
  withFileTypes: true
1479
877
  })) {
1480
878
  if (!digestEntry.isDirectory() || !/^[a-f0-9]{64}$/.test(digestEntry.name))
1481
879
  continue;
1482
880
  try {
1483
- components.push(await verifyStoredComponent(paths.koedHome, resolve3(versionRoot, digestEntry.name), {
881
+ components.push(await verifyStoredComponent(paths.koedHome, resolve2(versionRoot, digestEntry.name), {
1484
882
  component,
1485
883
  productVersion: versionEntry.name,
1486
884
  runtime
@@ -1507,13 +905,13 @@ var readDesktopPrivacyGeneration = async (paths, id, record) => {
1507
905
  ]) || record.schemaVersion !== 1 || record.kind !== "desktop-bundle-with-privacy" || record.id !== id || typeof record.productVersion !== "string" || typeof record.resourcesPath !== "string" || typeof record.bundleDigest !== "string" || !/^[a-f0-9]{64}$/.test(record.bundleDigest) || !isPlainRecord(record.privacy) || !exactKeys(record.privacy, ["root", "manifestDigest"]) || typeof record.privacy.root !== "string" || typeof record.privacy.manifestDigest !== "string")
1508
906
  throw new Error("stored Desktop privacy generation record is invalid");
1509
907
  validateOwner(record.owner);
1510
- const bundle = verifyDesktopRuntimeBundle(record.resourcesPath);
1511
- if (bundle.productVersion !== record.productVersion || bundle.bundleDigest !== record.bundleDigest)
908
+ const bundle = verifyDesktopRuntimeBundle(resolveDesktopInstallationResources(record.resourcesPath));
909
+ if (bundle.installationPath !== record.resourcesPath || bundle.productVersion !== record.productVersion || bundle.bundleDigest !== record.bundleDigest)
1512
910
  throw new Error("Desktop runtime bundle changed after generation staging");
1513
911
  const runtime = discoverActualRuntimeIdentity();
1514
- const privacyRoot = resolve3(paths.koedHome, record.privacy.root);
912
+ const privacyRoot = resolve2(paths.koedHome, record.privacy.root);
1515
913
  assertInside(paths.koedHome, privacyRoot);
1516
- const privacy = await verifyStoredComponent(paths.koedHome, dirname2(privacyRoot), {
914
+ const privacy = await verifyStoredComponent(paths.koedHome, dirname(privacyRoot), {
1517
915
  component: "privacy",
1518
916
  productVersion: bundle.productVersion,
1519
917
  target: bundle.target,
@@ -1526,10 +924,10 @@ var readDesktopPrivacyGeneration = async (paths, id, record) => {
1526
924
  kind: "desktop-bundle-with-privacy",
1527
925
  productVersion: bundle.productVersion,
1528
926
  owner: record.owner,
1529
- resourcesPath: bundle.resourcesPath,
927
+ resourcesPath: bundle.installationPath,
1530
928
  bundleDigest: bundle.bundleDigest,
1531
929
  privacy: {
1532
- root: relative3(paths.koedHome, privacy.root),
930
+ root: relative2(paths.koedHome, privacy.root),
1533
931
  manifestDigest: privacy.manifestDigest
1534
932
  }
1535
933
  };
@@ -1541,7 +939,7 @@ var readDesktopPrivacyGeneration = async (paths, id, record) => {
1541
939
  base: {
1542
940
  kind: "desktop-bundle",
1543
941
  manifest: bundle.manifest,
1544
- root: resolve3(bundle.resourcesPath, "koed-runtime"),
942
+ root: resolve2(bundle.resourcesPath, "koed-runtime"),
1545
943
  manifestDigest: bundle.bundleDigest
1546
944
  },
1547
945
  privacy,
@@ -1552,13 +950,13 @@ function readGenerationRecord(paths, id) {
1552
950
  if (!/^[a-f0-9]{64}$/.test(id))
1553
951
  throw new Error("generation id is invalid");
1554
952
  assertDirectoryChain(paths.koedHome, paths.generationsDir);
1555
- const root = resolve3(paths.generationsDir, id);
953
+ const root = resolve2(paths.generationsDir, id);
1556
954
  assertDirectoryChain(paths.generationsDir, root);
1557
- return parseJsonFile(resolve3(root, "generation.json"), MAX_GENERATION_RECORD_BYTES, true);
955
+ return parseJsonFile(resolve2(root, "generation.json"), MAX_GENERATION_RECORD_BYTES, true);
1558
956
  }
1559
957
  function assertOrderingStoreMetadata(root, manifest, digest) {
1560
958
  const stored = readComponentRecord(componentRecordPath(root));
1561
- if (stored.manifestDigest !== digest || canonicalArtifactJson(stored.manifest) !== canonicalArtifactJson(manifest) || stored.archivePath !== resolve3(root, manifest.archive.name))
959
+ if (stored.manifestDigest !== digest || canonicalArtifactJson(stored.manifest) !== canonicalArtifactJson(manifest) || stored.archivePath !== resolve2(root, manifest.archive.name))
1562
960
  throw new Error("generation component metadata differs from store");
1563
961
  }
1564
962
  function readOrderingComponent(paths, component, version, reference, embedded) {
@@ -1569,10 +967,10 @@ function readOrderingComponent(paths, component, version, reference, embedded) {
1569
967
  const digest = hash2(canonicalArtifactJson(manifest));
1570
968
  if (manifest.component !== component || manifest.productVersion !== version || reference.manifestDigest !== digest || embedded.manifestDigest !== digest)
1571
969
  throw new Error("generation component identity mismatch");
1572
- const componentRoot = resolve3(paths.componentsDir, component, version, digest);
970
+ const componentRoot = resolve2(paths.componentsDir, component, version, digest);
1573
971
  const payload = componentPayloadPath(componentRoot);
1574
972
  assertInside(paths.koedHome, componentRoot);
1575
- if (reference.root !== relative3(paths.koedHome, payload))
973
+ if (reference.root !== relative2(paths.koedHome, payload))
1576
974
  throw new Error("stored generation root is invalid");
1577
975
  assertDirectoryChain(paths.koedHome, payload);
1578
976
  assertOrderingStoreMetadata(componentRoot, manifest, digest);
@@ -1654,9 +1052,9 @@ async function readStagedGeneration(paths, id) {
1654
1052
  const baseRelative = record.base.root;
1655
1053
  if (typeof baseRelative !== "string")
1656
1054
  throw new Error("stored generation root is invalid");
1657
- const baseRoot = resolve3(paths.koedHome, baseRelative);
1055
+ const baseRoot = resolve2(paths.koedHome, baseRelative);
1658
1056
  assertInside(paths.koedHome, baseRoot);
1659
- const base = await verifyStoredComponent(paths.koedHome, dirname2(baseRoot), {
1057
+ const base = await verifyStoredComponent(paths.koedHome, dirname(baseRoot), {
1660
1058
  component: "base",
1661
1059
  runtime
1662
1060
  });
@@ -1667,9 +1065,9 @@ async function readStagedGeneration(paths, id) {
1667
1065
  const reference = record.privacy;
1668
1066
  if (!isPlainRecord(reference) || !exactKeys(reference, ["manifestDigest", "root"]) || typeof reference.root !== "string")
1669
1067
  throw new Error("stored generation privacy reference is invalid");
1670
- const privacyRoot = resolve3(paths.koedHome, reference.root);
1068
+ const privacyRoot = resolve2(paths.koedHome, reference.root);
1671
1069
  assertInside(paths.koedHome, privacyRoot);
1672
- privacy = await verifyStoredComponent(paths.koedHome, dirname2(privacyRoot), {
1070
+ privacy = await verifyStoredComponent(paths.koedHome, dirname(privacyRoot), {
1673
1071
  component: "privacy",
1674
1072
  runtime
1675
1073
  });
@@ -1684,12 +1082,12 @@ async function readStagedGeneration(paths, id) {
1684
1082
  owner: record.owner,
1685
1083
  base: {
1686
1084
  manifestDigest: base.manifestDigest,
1687
- root: relative3(paths.koedHome, base.root)
1085
+ root: relative2(paths.koedHome, base.root)
1688
1086
  },
1689
1087
  ...privacy ? {
1690
1088
  privacy: {
1691
1089
  manifestDigest: privacy.manifestDigest,
1692
- root: relative3(paths.koedHome, privacy.root)
1090
+ root: relative2(paths.koedHome, privacy.root)
1693
1091
  }
1694
1092
  } : {}
1695
1093
  };
@@ -1704,16 +1102,12 @@ async function readStagedGeneration(paths, id) {
1704
1102
  };
1705
1103
  }
1706
1104
 
1707
- // packages/koed-server/dist/generation-lifecycle.js
1708
- import { createHash as createHash4, randomBytes } from "node:crypto";
1709
- import { existsSync as existsSync3, closeSync as closeSync5, constants as constants4, fstatSync as fstatSync3, openSync as openSync5, readSync as readSync2, lstatSync as lstatSync4, mkdirSync as mkdirSync5, readFileSync as readFileSync5, readdirSync as readdirSync4, renameSync as renameSync4, rmSync as rmSync5, statSync, writeFileSync as writeFileSync4 } from "node:fs";
1710
- import { dirname as dirname3, isAbsolute as isAbsolute4, parse as parse2, relative as relative4, resolve as resolve5, sep as sep4 } from "node:path";
1711
-
1712
1105
  // packages/koed-server/dist/supervisor-lock.js
1713
- import { closeSync as closeSync4, mkdirSync as mkdirSync4, openSync as openSync4, readFileSync as readFileSync4, rmSync as rmSync4, writeFileSync as writeFileSync3 } from "node:fs";
1106
+ import { closeSync as closeSync3, mkdirSync as mkdirSync3, openSync as openSync3, readFileSync as readFileSync3, rmSync as rmSync4, writeFileSync as writeFileSync2 } from "node:fs";
1714
1107
  import { spawnSync } from "node:child_process";
1715
1108
  import { hostname } from "node:os";
1716
- import { resolve as resolve4 } from "node:path";
1109
+ import { resolve as resolve3 } from "node:path";
1110
+ var isSourceOwner = (value) => typeof value === "object" && value !== null && Object.keys(value).length === 2 && "kind" in value && value.kind === "standalone" && "installationId" in value && typeof value.installationId === "string" && /^[a-f0-9]{32}$/.test(value.installationId);
1717
1111
  var processIsRunning = (pid) => {
1718
1112
  if (!Number.isInteger(pid) || pid <= 0)
1719
1113
  return false;
@@ -1730,7 +1124,7 @@ var resolveProcessIdentity = (pid) => {
1730
1124
  return null;
1731
1125
  try {
1732
1126
  if (process.platform === "linux") {
1733
- const stat = readFileSync4(`/proc/${pid}/stat`, "utf8");
1127
+ const stat = readFileSync3(`/proc/${pid}/stat`, "utf8");
1734
1128
  const commandEnd = stat.lastIndexOf(")");
1735
1129
  if (commandEnd < 0)
1736
1130
  return null;
@@ -1738,7 +1132,7 @@ var resolveProcessIdentity = (pid) => {
1738
1132
  const startTime = fields[19];
1739
1133
  if (!startTime)
1740
1134
  return null;
1741
- const bootId = readFileSync4("/proc/sys/kernel/random/boot_id", "utf8").trim();
1135
+ const bootId = readFileSync3("/proc/sys/kernel/random/boot_id", "utf8").trim();
1742
1136
  return `${hostname()}:linux:${bootId}:${startTime}`;
1743
1137
  }
1744
1138
  if (process.platform === "win32") {
@@ -1761,12 +1155,26 @@ var resolveProcessIdentity = (pid) => {
1761
1155
  return null;
1762
1156
  }
1763
1157
  };
1158
+ var readLockText = (lockPath2) => {
1159
+ try {
1160
+ return readFileSync3(lockPath2, "utf8");
1161
+ } catch {
1162
+ return null;
1163
+ }
1164
+ };
1764
1165
  var readSupervisorLock = (lockPath2) => {
1166
+ const text = readLockText(lockPath2);
1167
+ return text === null ? null : parseSupervisorLock(text);
1168
+ };
1169
+ var parseSupervisorLock = (text) => {
1765
1170
  try {
1766
- const value = JSON.parse(readFileSync4(lockPath2, "utf8"));
1171
+ const value = JSON.parse(text);
1172
+ if (value.sourceOwner !== void 0 && !isSourceOwner(value.sourceOwner))
1173
+ return null;
1767
1174
  return Number.isInteger(value.pid) && Number(value.pid) > 0 ? {
1768
1175
  pid: Number(value.pid),
1769
1176
  acquiredAt: String(value.acquiredAt ?? "unknown"),
1177
+ ...value.sourceOwner ? { sourceOwner: { ...value.sourceOwner } } : {},
1770
1178
  ...typeof value.processIdentity === "string" && value.processIdentity.length > 0 ? { processIdentity: value.processIdentity } : {}
1771
1179
  } : null;
1772
1180
  } catch {
@@ -1775,32 +1183,37 @@ var readSupervisorLock = (lockPath2) => {
1775
1183
  };
1776
1184
  var acquireKoedServerSupervisorLock = (paths, options = {}) => {
1777
1185
  const pid = options.pid ?? process.pid;
1186
+ if (options.sourceOwner !== void 0 && !isSourceOwner(options.sourceOwner))
1187
+ throw new Error("Source runtime owner must identify a standalone control plane.");
1188
+ const exclusive = options.exclusive ?? ((action) => action());
1778
1189
  const isRunning = options.isProcessRunning ?? processIsRunning;
1779
1190
  const identify = options.resolveProcessIdentity ?? resolveProcessIdentity;
1780
1191
  const processIdentity = identify(pid);
1781
1192
  if (!processIdentity) {
1782
1193
  throw new Error(`Could not resolve process identity for PID ${pid}.`);
1783
1194
  }
1784
- const lockPath2 = resolve4(paths.runDir, "koed-server.lock");
1785
- mkdirSync4(paths.runDir, { recursive: true, mode: 448 });
1195
+ const lockPath2 = resolve3(paths.runDir, "koed-server.lock");
1196
+ mkdirSync3(paths.runDir, { recursive: true, mode: 448 });
1786
1197
  for (let attempt = 0; attempt < 2; attempt += 1) {
1787
1198
  try {
1788
- const descriptor = openSync4(lockPath2, "wx", 384);
1199
+ const descriptor = openSync3(lockPath2, "wx", 384);
1789
1200
  try {
1790
- writeFileSync3(descriptor, `${JSON.stringify({
1201
+ writeFileSync2(descriptor, `${JSON.stringify({
1791
1202
  pid,
1792
1203
  acquiredAt: (options.now ?? (() => /* @__PURE__ */ new Date()))().toISOString(),
1793
- processIdentity
1204
+ processIdentity,
1205
+ ...options.sourceOwner ? { sourceOwner: options.sourceOwner } : {}
1794
1206
  }, null, 2)}
1795
1207
  `);
1796
1208
  } finally {
1797
- closeSync4(descriptor);
1209
+ closeSync3(descriptor);
1798
1210
  }
1799
1211
  return { acquired: true, lockPath: lockPath2, ownerPid: pid, processIdentity };
1800
1212
  } catch (error) {
1801
1213
  if (error.code !== "EEXIST")
1802
1214
  throw error;
1803
- const owner2 = readSupervisorLock(lockPath2);
1215
+ const observed = readLockText(lockPath2);
1216
+ const owner2 = observed === null ? null : parseSupervisorLock(observed);
1804
1217
  if (!owner2)
1805
1218
  return { acquired: false, lockPath: lockPath2 };
1806
1219
  if (isRunning(owner2.pid)) {
@@ -1817,7 +1230,10 @@ var acquireKoedServerSupervisorLock = (paths, options = {}) => {
1817
1230
  }
1818
1231
  }
1819
1232
  }
1820
- rmSync4(lockPath2, { force: true });
1233
+ exclusive(() => {
1234
+ if (readLockText(lockPath2) === observed)
1235
+ rmSync4(lockPath2, { force: true });
1236
+ });
1821
1237
  }
1822
1238
  }
1823
1239
  const owner = readSupervisorLock(lockPath2);
@@ -1836,31 +1252,168 @@ var releaseKoedServerSupervisorLock = (lock, pid = process.pid) => {
1836
1252
  };
1837
1253
 
1838
1254
  // packages/koed-server/dist/generation-lifecycle-filesystem.js
1839
- import { renameSync as renameSync3 } from "node:fs";
1840
- var renameAtomically = (source, destination) => renameSync3(source, destination);
1255
+ import { renameSync as renameSync2 } from "node:fs";
1256
+ var renameAtomically = (source, destination) => renameSync2(source, destination);
1257
+
1258
+ // packages/koed-server/dist/stopped-runtime.js
1259
+ import { spawnSync as spawnSync2 } from "node:child_process";
1260
+ import { closeSync as closeSync4, constants as constants3, fstatSync as fstatSync2, openSync as openSync4, readFileSync as readFileSync4, rmSync as rmSync5 } from "node:fs";
1261
+ import { resolve as resolve4 } from "node:path";
1262
+ var processState = (pid) => {
1263
+ try {
1264
+ process.kill(pid, 0);
1265
+ return "running";
1266
+ } catch (error) {
1267
+ return error.code === "ESRCH" ? "stopped" : "uncertain";
1268
+ }
1269
+ };
1270
+ var processSnapshot = () => {
1271
+ const result = spawnSync2("ps", ["-axww", "-o", "pid=,command="], {
1272
+ encoding: "utf8",
1273
+ timeout: 2e3,
1274
+ maxBuffer: 4 * 1024 * 1024
1275
+ });
1276
+ if (result.error || result.status !== 0 || !result.stdout.trim())
1277
+ throw new Error("Native process discovery failed.");
1278
+ return result.stdout.trim().split("\n").map((line) => {
1279
+ const match = line.trim().match(/^(\d+)\s+(.+)$/);
1280
+ if (!match)
1281
+ throw new Error("Native process discovery was incomplete.");
1282
+ return { pid: Number(match[1]), command: match[2] };
1283
+ });
1284
+ };
1285
+ var readState = (path) => {
1286
+ let descriptor;
1287
+ try {
1288
+ descriptor = openSync4(path, constants3.O_RDONLY | constants3.O_NOFOLLOW | constants3.O_NONBLOCK);
1289
+ } catch (error) {
1290
+ if (error.code === "ENOENT")
1291
+ return null;
1292
+ throw error;
1293
+ }
1294
+ try {
1295
+ const stat = fstatSync2(descriptor);
1296
+ if (!stat.isFile() || stat.size > 1024 * 1024)
1297
+ throw new Error("Runtime state is not a bounded regular file.");
1298
+ return readFileSync4(descriptor, "utf8");
1299
+ } finally {
1300
+ closeSync4(descriptor);
1301
+ }
1302
+ };
1303
+ var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1304
+ var isPid = (value) => typeof value === "number" && Number.isSafeInteger(value) && value > 0;
1305
+ function observeStoppedRuntime(paths, dependencies = {}) {
1306
+ const stateOf = dependencies.processState ?? processState;
1307
+ const identify = dependencies.processIdentity ?? resolveProcessIdentity;
1308
+ const uncertain = (message) => ({
1309
+ state: "uncertain",
1310
+ message
1311
+ });
1312
+ const staleRecords = [];
1313
+ try {
1314
+ for (const name of ["koed-server.lock", "runtime-generation.json"]) {
1315
+ const path = name === "runtime-generation.json" ? paths.generationStatePath ?? resolve4(paths.runDir, name) : resolve4(paths.runDir, name);
1316
+ const contents = readState(path);
1317
+ if (contents === null)
1318
+ continue;
1319
+ const value = JSON.parse(contents);
1320
+ if (!isRecord(value) || !isPid(value.pid) || typeof value.processIdentity !== "string" || name === "runtime-generation.json" && !isRuntimeGenerationState(value))
1321
+ return uncertain(`${name} is unreadable or lacks process identity.`);
1322
+ const identity = identify(value.pid);
1323
+ if (identity && identity === value.processIdentity)
1324
+ return {
1325
+ state: "running",
1326
+ pid: value.pid,
1327
+ message: "Koed is running or pinned."
1328
+ };
1329
+ if (stateOf(value.pid) === "stopped") {
1330
+ staleRecords.push({ path, contents });
1331
+ continue;
1332
+ }
1333
+ return uncertain(`${name} is stale or its process identity is uncertain. Operator recovery is required.`);
1334
+ }
1335
+ const runtime = readState(paths.runtimeStatePath);
1336
+ if (runtime !== null) {
1337
+ const value = JSON.parse(runtime);
1338
+ if (!isRecord(value) || !isPid(value.pid) || value.processes !== void 0 && !isRecord(value.processes))
1339
+ return uncertain("Koed runtime process state is unreadable.");
1340
+ const pids = [
1341
+ value.pid,
1342
+ ...Object.values(value.processes ?? {})
1343
+ ];
1344
+ for (const pid of pids) {
1345
+ if (pid === 0)
1346
+ continue;
1347
+ if (!isPid(pid))
1348
+ return uncertain("Koed runtime contains an invalid process ID.");
1349
+ if (stateOf(pid) !== "stopped")
1350
+ return {
1351
+ state: "uncertain",
1352
+ pid,
1353
+ message: "A recorded Koed process is live or its identity is uncertain."
1354
+ };
1355
+ }
1356
+ }
1357
+ const postmaster = readState(resolve4(paths.postgresDataDir, "postmaster.pid"));
1358
+ if (postmaster !== null) {
1359
+ const line = postmaster.split("\n")[0];
1360
+ if (!/^-?[1-9]\d*$/.test(line) || !isPid(Math.abs(Number(line))))
1361
+ return uncertain("Postgres process state is unreadable.");
1362
+ const pid = Math.abs(Number(line));
1363
+ return {
1364
+ state: "uncertain",
1365
+ pid,
1366
+ message: "Postgres retains a process lock. Stop Postgres or complete Operator recovery before changing its runtime."
1367
+ };
1368
+ }
1369
+ const roots = [resolve4(paths.koedHome, "runtime"), paths.postgresDataDir];
1370
+ const patterns = roots.map((root) => new RegExp(`(?:^|[\\s"'])${root.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?:[/\\s"']|$)`));
1371
+ const native = (dependencies.processes ?? processSnapshot)().find(({ pid, command }) => pid !== process.pid && patterns.some((pattern) => pattern.test(command)));
1372
+ if (native)
1373
+ return {
1374
+ state: "uncertain",
1375
+ pid: native.pid,
1376
+ message: "A process still references this native runtime or Postgres data directory."
1377
+ };
1378
+ return {
1379
+ state: "stopped",
1380
+ message: "Koed and its recorded native processes are stopped.",
1381
+ ...staleRecords.length > 0 ? { staleRecords } : {}
1382
+ };
1383
+ } catch {
1384
+ return uncertain("Stopped runtime state could not be established. Inspect process state and runtime files before retrying.");
1385
+ }
1386
+ }
1387
+ function removeStaleRuntimeRecords(observation) {
1388
+ if (observation.state !== "stopped")
1389
+ return;
1390
+ for (const record of observation.staleRecords ?? [])
1391
+ if (readState(record.path) === record.contents)
1392
+ rmSync5(record.path, { force: true });
1393
+ }
1841
1394
 
1842
1395
  // packages/koed-server/dist/generation-lifecycle.js
1843
1396
  var generationStatePath = (paths) => paths.generationStatePath ?? resolve5(paths.runDir, "runtime-generation.json");
1844
1397
  var lockPath = (paths) => resolve5(paths.runDir, "generation-lifecycle.lock");
1845
- var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1846
- var isRuntimeOwnerRecord = (value) => isRecord(value) && Object.keys(value).length === 2 && ["cli", "desktop", "standalone"].includes(String(value.kind)) && typeof value.installationId === "string" && /^[A-Za-z0-9._-]{1,128}$/.test(value.installationId);
1398
+ var isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1399
+ var isRuntimeOwnerRecord = (value) => isRecord2(value) && Object.keys(value).length === 2 && ["cli", "desktop", "standalone"].includes(String(value.kind)) && typeof value.installationId === "string" && /^[A-Za-z0-9._-]{1,128}$/.test(value.installationId);
1847
1400
  var readRegularFile = (path) => {
1848
- const stat = lstatSync4(path);
1401
+ const stat = lstatSync3(path);
1849
1402
  if (!stat.isFile() || stat.isSymbolicLink())
1850
1403
  throw new Error("runtime lifecycle state is not a regular file");
1851
1404
  return readFileSync5(path, "utf8");
1852
1405
  };
1853
1406
  var sameOwner = (left, right) => left.kind === right.kind && left.installationId === right.installationId;
1854
1407
  var assertDirectoryChain2 = (base, target) => {
1855
- const relativePath = relative4(resolve5(base), resolve5(target));
1856
- if (relativePath.startsWith("..") || isAbsolute4(relativePath))
1408
+ const relativePath = relative3(resolve5(base), resolve5(target));
1409
+ if (relativePath.startsWith("..") || isAbsolute3(relativePath))
1857
1410
  throw new Error("runtime lifecycle path escaped KOED_HOME");
1858
1411
  const absolute = resolve5(target);
1859
1412
  let cursor = parse2(absolute).root;
1860
- for (const part of absolute.slice(cursor.length).split(sep4).filter(Boolean)) {
1413
+ for (const part of absolute.slice(cursor.length).split(sep3).filter(Boolean)) {
1861
1414
  cursor = resolve5(cursor, part);
1862
1415
  try {
1863
- const stat = lstatSync4(cursor);
1416
+ const stat = lstatSync3(cursor);
1864
1417
  if (stat.isSymbolicLink() || !stat.isDirectory())
1865
1418
  throw new Error("runtime lifecycle path contains a symbolic link or non-directory");
1866
1419
  } catch (error) {
@@ -1881,7 +1434,7 @@ var processIsRunning2 = (pid) => {
1881
1434
  var readLockRecord = (path) => {
1882
1435
  try {
1883
1436
  const parsed = JSON.parse(readRegularFile(resolve5(path, "owner.json")));
1884
- if (!isRecord(parsed))
1437
+ if (!isRecord2(parsed))
1885
1438
  return null;
1886
1439
  const record = parsed;
1887
1440
  if (Object.keys(record).length !== 3 || typeof record.pid !== "number" || !Number.isInteger(record.pid) || record.pid <= 0 || typeof record.processIdentity !== "string" || record.processIdentity.length === 0 || typeof record.token !== "string" || !/^[a-f0-9]{64}$/.test(record.token))
@@ -1897,7 +1450,7 @@ var readLockRecord = (path) => {
1897
1450
  };
1898
1451
  var acquireLifecycleLock = (paths) => {
1899
1452
  assertDirectoryChain2(paths.koedHome, paths.runDir);
1900
- mkdirSync5(paths.runDir, { recursive: true, mode: 448 });
1453
+ mkdirSync4(paths.runDir, { recursive: true, mode: 448 });
1901
1454
  assertDirectoryChain2(paths.koedHome, paths.runDir);
1902
1455
  const path = lockPath(paths);
1903
1456
  assertDirectoryChain2(paths.koedHome, path);
@@ -1910,9 +1463,9 @@ var acquireLifecycleLock = (paths) => {
1910
1463
  token: randomBytes(32).toString("hex")
1911
1464
  };
1912
1465
  try {
1913
- mkdirSync5(path, { mode: 448 });
1466
+ mkdirSync4(path, { mode: 448 });
1914
1467
  assertDirectoryChain2(paths.koedHome, path);
1915
- writeFileSync4(resolve5(path, "owner.json"), `${JSON.stringify(record)}
1468
+ writeFileSync3(resolve5(path, "owner.json"), `${JSON.stringify(record)}
1916
1469
  `, {
1917
1470
  flag: "wx",
1918
1471
  mode: 384
@@ -1921,7 +1474,7 @@ var acquireLifecycleLock = (paths) => {
1921
1474
  } catch (error) {
1922
1475
  if (error.code !== "EEXIST")
1923
1476
  throw error;
1924
- throw new Error("runtime lifecycle is locked; stale locks require stopped-runtime operator recovery", { cause: error });
1477
+ throw new Error("runtime lifecycle is locked; if Koed is running, run koed stop and retry. Wait for any active installation. Stale locks require stopped-runtime operator recovery", { cause: error });
1925
1478
  }
1926
1479
  };
1927
1480
  var releaseLifecycleLock = (paths, expected) => {
@@ -1929,11 +1482,19 @@ var releaseLifecycleLock = (paths, expected) => {
1929
1482
  const actual = readLockRecord(path);
1930
1483
  if (!actual || actual.pid !== expected.pid || actual.token !== expected.token || actual.processIdentity !== expected.processIdentity)
1931
1484
  return;
1932
- rmSync5(path, { recursive: true, force: true });
1485
+ rmSync6(path, { recursive: true, force: true });
1933
1486
  };
1487
+ function withLifecycleLock(paths, action) {
1488
+ const lock = acquireLifecycleLock(paths);
1489
+ try {
1490
+ return action();
1491
+ } finally {
1492
+ releaseLifecycleLock(paths, lock);
1493
+ }
1494
+ }
1934
1495
  var withStoreLock = async (paths, action) => {
1935
1496
  assertDirectoryChain2(paths.koedHome, paths.componentsDir);
1936
- mkdirSync5(paths.componentsDir, { recursive: true, mode: 448 });
1497
+ mkdirSync4(paths.componentsDir, { recursive: true, mode: 448 });
1937
1498
  assertDirectoryChain2(paths.koedHome, paths.componentsDir);
1938
1499
  const lockPath2 = `${paths.componentsDir}.lock`;
1939
1500
  assertDirectoryChain2(paths.koedHome, lockPath2);
@@ -1947,10 +1508,10 @@ var withStoreLock = async (paths, action) => {
1947
1508
  var readCurrentId = (paths) => {
1948
1509
  assertDirectoryChain2(paths.koedHome, paths.componentsDir);
1949
1510
  const pointerPath = resolve5(paths.componentsDir, "current.json");
1950
- if (!existsSync3(pointerPath))
1511
+ if (!existsSync2(pointerPath))
1951
1512
  return null;
1952
1513
  const value = JSON.parse(readRegularFile(pointerPath));
1953
- if (!isRecord(value))
1514
+ if (!isRecord2(value))
1954
1515
  throw new Error("current generation pointer is invalid");
1955
1516
  const pointer = value;
1956
1517
  if (Object.keys(pointer).length !== 2 || pointer.schemaVersion !== 1 || typeof pointer.generationId !== "string" || !/^[a-f0-9]{64}$/.test(pointer.generationId))
@@ -1959,26 +1520,41 @@ var readCurrentId = (paths) => {
1959
1520
  };
1960
1521
  var writeCurrentPointer = (paths, id) => {
1961
1522
  const pointer = resolve5(paths.componentsDir, "current.json");
1962
- const temporary = resolve5(dirname3(pointer), `.current-${randomBytes(8).toString("hex")}.tmp`);
1963
- writeFileSync4(temporary, `${JSON.stringify({ schemaVersion: 1, generationId: id })}
1523
+ const temporary = resolve5(dirname2(pointer), `.current-${randomBytes(8).toString("hex")}.tmp`);
1524
+ writeFileSync3(temporary, `${JSON.stringify({ schemaVersion: 1, generationId: id })}
1964
1525
  `, { flag: "wx", mode: 384 });
1965
1526
  try {
1966
1527
  renameAtomically(temporary, pointer);
1967
1528
  } catch (error) {
1968
- rmSync5(temporary, { force: true });
1529
+ rmSync6(temporary, { force: true });
1969
1530
  throw error;
1970
1531
  }
1971
1532
  };
1972
1533
  var readPinState = (paths) => {
1973
1534
  const path = generationStatePath(paths);
1974
- assertDirectoryChain2(paths.koedHome, dirname3(path));
1975
- if (!existsSync3(path))
1535
+ assertDirectoryChain2(paths.koedHome, dirname2(path));
1536
+ if (!existsSync2(path))
1976
1537
  return null;
1977
1538
  const parsed = JSON.parse(readRegularFile(path));
1978
1539
  if (!isRuntimeGenerationState(parsed))
1979
1540
  throw new Error("runtime generation state is invalid");
1980
1541
  return parsed;
1981
1542
  };
1543
+ var removeStaleGenerationPin = (paths) => {
1544
+ let pin;
1545
+ try {
1546
+ pin = readPinState(paths);
1547
+ } catch {
1548
+ return false;
1549
+ }
1550
+ if (!pin)
1551
+ return false;
1552
+ const identity = resolveProcessIdentity(pin.pid);
1553
+ if (identity === pin.processIdentity || !identity && processIsRunning2(pin.pid))
1554
+ return false;
1555
+ rmSync6(generationStatePath(paths), { force: true });
1556
+ return true;
1557
+ };
1982
1558
  var assertOwner = (generation, requester) => {
1983
1559
  if (!sameOwner(generation.owner, requester))
1984
1560
  throw new Error("runtime owner mismatch");
@@ -1989,10 +1565,10 @@ var assertNoActivePin = (paths, allowCurrentSupervisor = false) => {
1989
1565
  const identity2 = resolveProcessIdentity(pin.pid);
1990
1566
  if (identity2 === pin.processIdentity || !identity2 && processIsRunning2(pin.pid))
1991
1567
  throw new Error("runtime generation is running or pinned");
1992
- rmSync5(generationStatePath(paths), { force: true });
1568
+ rmSync6(generationStatePath(paths), { force: true });
1993
1569
  }
1994
1570
  const supervisorPath = resolve5(paths.runDir, "koed-server.lock");
1995
- if (!existsSync3(supervisorPath))
1571
+ if (!existsSync2(supervisorPath))
1996
1572
  return;
1997
1573
  const supervisor = readSupervisorLock(supervisorPath);
1998
1574
  if (!supervisor)
@@ -2019,7 +1595,7 @@ var desktopBundleRecordPath = (paths, id) => resolve5(paths.generationsDir, id,
2019
1595
  var persistDesktopBundleRecord = (paths, generation, capability) => {
2020
1596
  const root = resolve5(paths.generationsDir, generation.id);
2021
1597
  assertDirectoryChain2(paths.koedHome, root);
2022
- mkdirSync5(root, { recursive: true, mode: 448 });
1598
+ mkdirSync4(root, { recursive: true, mode: 448 });
2023
1599
  const path = desktopBundleRecordPath(paths, generation.id);
2024
1600
  const record = {
2025
1601
  schemaVersion: 1,
@@ -2028,10 +1604,11 @@ var persistDesktopBundleRecord = (paths, generation, capability) => {
2028
1604
  productVersion: generation.productVersion,
2029
1605
  owner: generation.owner,
2030
1606
  bundleDigest: capability.bundleDigest,
2031
- resourcesPath: capability.resourcesPath
1607
+ // Stable installation identity; see DesktopRuntimeCapability.
1608
+ resourcesPath: capability.installationPath
2032
1609
  };
2033
1610
  try {
2034
- writeFileSync4(path, `${JSON.stringify(record)}
1611
+ writeFileSync3(path, `${JSON.stringify(record)}
2035
1612
  `, {
2036
1613
  flag: "wx",
2037
1614
  mode: 384
@@ -2040,7 +1617,7 @@ var persistDesktopBundleRecord = (paths, generation, capability) => {
2040
1617
  if (error.code !== "EEXIST")
2041
1618
  throw error;
2042
1619
  const existing = JSON.parse(readRegularFile(path));
2043
- if (!isRecord(existing) || existing.schemaVersion !== record.schemaVersion || existing.kind !== record.kind || existing.id !== record.id || existing.productVersion !== record.productVersion || existing.bundleDigest !== record.bundleDigest || existing.resourcesPath !== record.resourcesPath || !isRecord(existing.owner) || existing.owner.kind !== generation.owner.kind || existing.owner.installationId !== generation.owner.installationId)
1620
+ if (!isRecord2(existing) || existing.schemaVersion !== record.schemaVersion || existing.kind !== record.kind || existing.id !== record.id || existing.productVersion !== record.productVersion || existing.bundleDigest !== record.bundleDigest || existing.resourcesPath !== record.resourcesPath || !isRecord2(existing.owner) || existing.owner.kind !== generation.owner.kind || existing.owner.installationId !== generation.owner.installationId)
2044
1621
  throw new Error("private Desktop bundle generation record is invalid", {
2045
1622
  cause: error
2046
1623
  });
@@ -2051,7 +1628,7 @@ var readDesktopBundleGenerationById = async (paths, id, capability) => {
2051
1628
  if (generation.id !== id)
2052
1629
  throw new Error("runtime owner mismatch");
2053
1630
  const record = JSON.parse(readRegularFile(desktopBundleRecordPath(paths, id)));
2054
- if (!isRecord(record) || record.schemaVersion !== 1 || record.kind !== "desktop-bundle" || record.id !== generation.id || record.productVersion !== generation.productVersion || record.bundleDigest !== capability.bundleDigest || record.resourcesPath !== capability.resourcesPath || !isRecord(record.owner) || record.owner.kind !== generation.owner.kind || record.owner.installationId !== generation.owner.installationId)
1631
+ if (!isRecord2(record) || record.schemaVersion !== 1 || record.kind !== "desktop-bundle" || record.id !== generation.id || record.productVersion !== generation.productVersion || record.bundleDigest !== capability.bundleDigest || record.resourcesPath !== capability.installationPath || !isRecord2(record.owner) || record.owner.kind !== generation.owner.kind || record.owner.installationId !== generation.owner.installationId)
2055
1632
  throw new Error("private Desktop bundle generation record is invalid");
2056
1633
  return generation;
2057
1634
  };
@@ -2092,7 +1669,7 @@ var readOrderingJournalFile = (path) => {
2092
1669
  const bytes = Buffer.alloc(stat.size + 1);
2093
1670
  let length = 0;
2094
1671
  while (length < bytes.length) {
2095
- const count = readSync2(descriptor, bytes, length, bytes.length - length, null);
1672
+ const count = readSync(descriptor, bytes, length, bytes.length - length, null);
2096
1673
  if (count === 0)
2097
1674
  break;
2098
1675
  length += count;
@@ -2106,11 +1683,11 @@ var readOrderingJournalFile = (path) => {
2106
1683
  };
2107
1684
  var readDesktopOrderingJournal = (paths, id) => {
2108
1685
  const bundlePath = desktopBundleRecordPath(paths, id);
2109
- const hasBundle = existsSync3(bundlePath);
1686
+ const hasBundle = existsSync2(bundlePath);
2110
1687
  if (hasBundle)
2111
- assertDirectoryChain2(paths.koedHome, dirname3(bundlePath));
1688
+ assertDirectoryChain2(paths.koedHome, dirname2(bundlePath));
2112
1689
  const record = hasBundle ? JSON.parse(readOrderingJournalFile(bundlePath)) : readGenerationRecord(paths, id);
2113
- if (!isRecord(record))
1690
+ if (!isRecord2(record))
2114
1691
  throw new Error("generation record is invalid");
2115
1692
  if (record.kind !== "desktop-bundle" && record.kind !== "desktop-bundle-with-privacy")
2116
1693
  return null;
@@ -2137,20 +1714,20 @@ function validateDesktopOrderingJournal(record, id) {
2137
1714
  "resourcesPath",
2138
1715
  ...privacy ? ["privacy"] : []
2139
1716
  ];
2140
- if (Object.keys(record).length !== keys.length || !keys.every((key) => Object.hasOwn(record, key)) || record.schemaVersion !== 1 || record.id !== id || typeof record.productVersion !== "string" || !/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(record.productVersion) || !isRuntimeOwnerRecord(record.owner) || record.owner.kind !== "desktop" || typeof record.resourcesPath !== "string" || !isAbsolute4(record.resourcesPath) || typeof record.bundleDigest !== "string" || !/^[a-f0-9]{64}$/.test(record.bundleDigest))
1717
+ if (Object.keys(record).length !== keys.length || !keys.every((key) => Object.hasOwn(record, key)) || record.schemaVersion !== 1 || record.id !== id || typeof record.productVersion !== "string" || !/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(record.productVersion) || !isRuntimeOwnerRecord(record.owner) || record.owner.kind !== "desktop" || typeof record.resourcesPath !== "string" || !isAbsolute3(record.resourcesPath) || typeof record.bundleDigest !== "string" || !/^[a-f0-9]{64}$/.test(record.bundleDigest))
2141
1718
  throw new Error("private Desktop bundle generation record is invalid");
2142
1719
  if (privacy)
2143
1720
  validateDesktopPrivacyJournal(record, id);
2144
- else if (createHash4("sha256").update(`${record.owner.installationId}
1721
+ else if (createHash3("sha256").update(`${record.owner.installationId}
2145
1722
  ${record.bundleDigest}`).digest("hex") !== id)
2146
1723
  throw new Error("Desktop bundle generation identity mismatch");
2147
1724
  }
2148
1725
  function validateDesktopPrivacyJournal(record, id) {
2149
- if (!isRecord(record.privacy) || Object.keys(record.privacy).length !== 2 || typeof record.privacy.root !== "string" || isAbsolute4(record.privacy.root) || record.privacy.root.split(/[\\/]/).includes("..") || typeof record.privacy.manifestDigest !== "string" || !/^[a-f0-9]{64}$/.test(record.privacy.manifestDigest))
1726
+ if (!isRecord2(record.privacy) || Object.keys(record.privacy).length !== 2 || typeof record.privacy.root !== "string" || isAbsolute3(record.privacy.root) || record.privacy.root.split(/[\\/]/).includes("..") || typeof record.privacy.manifestDigest !== "string" || !/^[a-f0-9]{64}$/.test(record.privacy.manifestDigest))
2150
1727
  throw new Error("private Desktop privacy journal is invalid");
2151
1728
  const identity = { ...record };
2152
1729
  delete identity.id;
2153
- if (createHash4("sha256").update(canonicalArtifactJson(identity)).digest("hex") !== id)
1730
+ if (createHash3("sha256").update(canonicalArtifactJson(identity)).digest("hex") !== id)
2154
1731
  throw new Error("Desktop privacy generation digest mismatch");
2155
1732
  }
2156
1733
  function readCurrentDesktopGenerationOrderingEvidence(paths, capability) {
@@ -2160,19 +1737,56 @@ function readCurrentDesktopGenerationOrderingEvidence(paths, capability) {
2160
1737
  if (!id)
2161
1738
  throw new Error("no active runtime generation");
2162
1739
  const evidence = readDesktopOrderingJournal(paths, id) ?? readGenerationOrderingEvidence(paths, id);
2163
- if (evidence.kind === "desktop-generation-ordering-evidence" && evidence.resourcesPath !== capability.resourcesPath)
1740
+ if (evidence.kind === "desktop-generation-ordering-evidence" && evidence.resourcesPath !== capability.installationPath)
2164
1741
  throw new Error("runtime owner mismatch");
2165
1742
  assertOwner(evidence, resolveDesktopRuntimeOwner(capability, paths.koedHome));
2166
1743
  return evidence;
2167
1744
  }
2168
1745
  async function readCurrentRuntimeOwner(paths) {
2169
- if (!existsSync3(resolve5(paths.componentsDir, "current.json")))
1746
+ if (!existsSync2(resolve5(paths.componentsDir, "current.json")))
2170
1747
  return null;
2171
1748
  const id = readCurrentId(paths);
2172
1749
  if (!id)
2173
1750
  return null;
2174
1751
  return (await Promise.resolve(readDesktopOrderingJournal(paths, id) ?? readGenerationOrderingEvidence(paths, id))).owner;
2175
1752
  }
1753
+ function withSourceNativeStartLock(paths, check) {
1754
+ const lock = acquireLifecycleLock(paths);
1755
+ try {
1756
+ const owner = readSupervisorLock(resolve5(paths.runDir, "koed-server.lock"));
1757
+ if (!owner || owner.pid !== process.pid || !owner.processIdentity || owner.processIdentity !== resolveProcessIdentity(process.pid))
1758
+ throw new Error("Source native selection requires the active supervisor lock.");
1759
+ return check();
1760
+ } finally {
1761
+ releaseLifecycleLock(paths, lock);
1762
+ }
1763
+ }
1764
+ async function withStoppedRuntime(paths, requester, action) {
1765
+ const lock = acquireLifecycleLock(paths);
1766
+ try {
1767
+ assertDirectoryChain2(paths.koedHome, paths.postgresDataDir);
1768
+ assertDirectoryChain2(paths.koedHome, dirname2(paths.runtimeStatePath));
1769
+ assertDirectoryChain2(paths.koedHome, dirname2(generationStatePath(paths)));
1770
+ assertDirectoryChain2(paths.koedHome, paths.componentsDir);
1771
+ try {
1772
+ if (!lstatSync3(resolve5(paths.componentsDir, "current.json")).isFile())
1773
+ throw new Error("current generation pointer is not a regular file");
1774
+ } catch (error) {
1775
+ if (error.code !== "ENOENT")
1776
+ throw error;
1777
+ }
1778
+ const owner = await readCurrentRuntimeOwner(paths);
1779
+ if (owner)
1780
+ assertOwner({ owner }, requester);
1781
+ const observation = observeStoppedRuntime(paths);
1782
+ if (observation.state !== "stopped")
1783
+ throw new Error(`${observation.message} Run koed stop before retrying. Stale or unreadable locks require stopped-runtime Operator recovery.`);
1784
+ removeStaleRuntimeRecords(observation);
1785
+ return await action();
1786
+ } finally {
1787
+ releaseLifecycleLock(paths, lock);
1788
+ }
1789
+ }
2176
1790
  var persistPinState = (paths, generation, requester, lock, source = "manifest-pinned-store") => {
2177
1791
  const processIdentity = resolveProcessIdentity(process.pid);
2178
1792
  if (!processIdentity)
@@ -2188,14 +1802,14 @@ var persistPinState = (paths, generation, requester, lock, source = "manifest-pi
2188
1802
  ...source === "desktop-bundle" ? { source } : {}
2189
1803
  };
2190
1804
  const path = generationStatePath(paths);
2191
- mkdirSync5(dirname3(path), { recursive: true, mode: 448 });
1805
+ mkdirSync4(dirname2(path), { recursive: true, mode: 448 });
2192
1806
  const temporary = `${path}.${lock.token}.tmp`;
2193
- writeFileSync4(temporary, `${JSON.stringify(state)}
1807
+ writeFileSync3(temporary, `${JSON.stringify(state)}
2194
1808
  `, {
2195
1809
  flag: "wx",
2196
1810
  mode: 384
2197
1811
  });
2198
- renameSync4(temporary, path);
1812
+ renameSync3(temporary, path);
2199
1813
  return { path, processIdentity };
2200
1814
  };
2201
1815
  var createPinRelease = (paths, lock, pinPath, processIdentity) => {
@@ -2207,7 +1821,7 @@ var createPinRelease = (paths, lock, pinPath, processIdentity) => {
2207
1821
  try {
2208
1822
  const current = readPinState(paths);
2209
1823
  if (current?.pinToken === lock.token && current.processIdentity === processIdentity)
2210
- rmSync5(pinPath, { force: true });
1824
+ rmSync6(pinPath, { force: true });
2211
1825
  } finally {
2212
1826
  releaseLifecycleLock(paths, lock);
2213
1827
  }
@@ -2223,6 +1837,13 @@ function readDesktopBundleGeneration(paths, capability) {
2223
1837
  const generation = desktopBundleGeneration(currentCapability, owner);
2224
1838
  return Promise.resolve(generation);
2225
1839
  }
1840
+ async function stageDesktopBundleForRecovery(paths, capability) {
1841
+ return withStoreLock(paths, async () => {
1842
+ const generation = await readDesktopBundleGeneration(paths, capability);
1843
+ persistDesktopBundleRecord(paths, generation, capability);
1844
+ return generation;
1845
+ });
1846
+ }
2226
1847
  async function pinDesktopBundleGenerationForStart(paths, capability) {
2227
1848
  if (!validateDesktopRuntimeCapability(capability))
2228
1849
  throw new Error("validated private Desktop runtime capability is required");
@@ -2261,7 +1882,7 @@ async function pinDesktopBundleGenerationForStart(paths, capability) {
2261
1882
  }
2262
1883
  var desktopBundleGeneration = (capability, owner) => {
2263
1884
  const manifest = capability.manifest;
2264
- const id = createHash4("sha256").update(`${owner.installationId}
1885
+ const id = createHash3("sha256").update(`${owner.installationId}
2265
1886
  ${capability.bundleDigest}`).digest("hex");
2266
1887
  return {
2267
1888
  id,
@@ -2320,7 +1941,7 @@ var listOwnedGenerations = async (paths, requester) => {
2320
1941
  assertDirectoryChain2(paths.koedHome, paths.generationsDir);
2321
1942
  let entries;
2322
1943
  try {
2323
- entries = readdirSync4(paths.generationsDir, { withFileTypes: true });
1944
+ entries = readdirSync3(paths.generationsDir, { withFileTypes: true });
2324
1945
  } catch (error) {
2325
1946
  if (error.code === "ENOENT")
2326
1947
  return [];
@@ -2350,7 +1971,7 @@ var removeUnretainedGenerations = (generations, retain, currentId) => {
2350
1971
  for (const entry of generations) {
2351
1972
  if (kept.has(entry.id))
2352
1973
  continue;
2353
- rmSync5(entry.path, { recursive: true, force: true });
1974
+ rmSync6(entry.path, { recursive: true, force: true });
2354
1975
  removed.push(entry.id);
2355
1976
  }
2356
1977
  return removed;
@@ -2375,10 +1996,9 @@ async function cleanupGenerations(paths, retain, requester) {
2375
1996
  }
2376
1997
 
2377
1998
  export {
2378
- resolveKoedServerConfig,
2379
- writeCodexGlobalMemoryGuidancePreference,
2380
1999
  validateDesktopRuntimeCapability,
2381
2000
  resolveDesktopRuntimeOwner,
2001
+ fetchBounded,
2382
2002
  discoverActualRuntimeIdentity,
2383
2003
  resolveComponentManifestPinTarget,
2384
2004
  stageComponent,
@@ -2390,13 +2010,23 @@ export {
2390
2010
  readSupervisorLock,
2391
2011
  acquireKoedServerSupervisorLock,
2392
2012
  releaseKoedServerSupervisorLock,
2013
+ renameAtomically,
2014
+ observeStoppedRuntime,
2015
+ removeStaleRuntimeRecords,
2016
+ assertDirectoryChain2 as assertDirectoryChain,
2017
+ withLifecycleLock,
2018
+ removeStaleGenerationPin,
2393
2019
  readCurrentGenerationOrderingEvidence,
2394
2020
  readCurrentGeneration,
2021
+ readDesktopGenerationForCapability,
2395
2022
  readCurrentDesktopGeneration,
2396
2023
  readCurrentGenerationForOwner,
2397
2024
  readCurrentDesktopGenerationOrderingEvidence,
2398
2025
  readCurrentRuntimeOwner,
2026
+ withSourceNativeStartLock,
2027
+ withStoppedRuntime,
2399
2028
  readDesktopBundleGeneration,
2029
+ stageDesktopBundleForRecovery,
2400
2030
  pinDesktopBundleGenerationForStart,
2401
2031
  pinGenerationForStart,
2402
2032
  activateGeneration,