@koed-labs/server 0.10.3 → 0.11.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/README.md +3 -3
  2. package/package.json +1 -1
  3. package/vendor/{chunk-A6WMU2GG.js → chunk-2XKSVKQA.js} +5 -4
  4. package/vendor/{chunk-VPC5NLZG.js → chunk-4OO6VAU3.js} +1 -1
  5. package/vendor/{chunk-HK2H3MVE.js → chunk-53ZFCDHP.js} +4 -0
  6. package/vendor/chunk-6KS67EQE.js +75 -0
  7. package/vendor/chunk-7EGSY3E4.js +8 -0
  8. package/vendor/{chunk-JKOG52PE.js → chunk-7FSHVVTZ.js} +1 -1
  9. package/vendor/chunk-ALJUSOF7.js +175 -0
  10. package/vendor/{chunk-KUIWH33N.js → chunk-AVQCUFYQ.js} +1 -1
  11. package/vendor/chunk-BGENSONI.js +18 -0
  12. package/vendor/{chunk-ZXX4ZNJY.js → chunk-BUIM2M4R.js} +3 -2
  13. package/vendor/{chunk-YK4F4VY2.js → chunk-C4V72GXC.js} +51 -30
  14. package/vendor/{chunk-JJNLH5GA.js → chunk-C5SNDPAP.js} +21 -19
  15. package/vendor/{chunk-J2L726BC.js → chunk-CHMH4LH5.js} +3 -3
  16. package/vendor/{chunk-2S3OGPUC.js → chunk-EA4QDDQA.js} +2 -2
  17. package/vendor/{chunk-HZJK5RWC.js → chunk-EDPNYIX5.js} +575 -215
  18. package/vendor/{chunk-NM5NXCVM.js → chunk-FN3HUUO2.js} +558 -988
  19. package/vendor/{chunk-473OA62O.js → chunk-FSNLU46W.js} +218 -12497
  20. package/vendor/{chunk-GELDEJJ2.js → chunk-FYYRFX4U.js} +133 -47
  21. package/vendor/{chunk-YOFI4PCH.js → chunk-GFASBPV2.js} +7 -1
  22. package/vendor/chunk-HC76426R.js +48 -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-2BWTLF7A.js → chunk-LRP66XEY.js} +45 -21
  26. package/vendor/{chunk-DXTAWHY3.js → chunk-NOU7RHYZ.js} +8 -7
  27. package/vendor/{chunk-C3N4N5HR.js → chunk-NVTMIAAF.js} +26 -21
  28. package/vendor/chunk-O7DW2VAV.js +14 -0
  29. package/vendor/{chunk-YJ6XUZT6.js → chunk-OCILJ737.js} +23 -16
  30. package/vendor/{chunk-TSRPHKAC.js → chunk-PL3LWC5C.js} +16 -42
  31. package/vendor/chunk-QRKHHWJJ.js +104 -0
  32. package/vendor/{chunk-YJWREXN6.js → chunk-RCR4XPE3.js} +1 -1
  33. package/vendor/{chunk-AFLKCQHF.js → chunk-SHLRINKO.js} +2 -2
  34. package/vendor/{chunk-NEWIOOM6.js → chunk-SNKWETM5.js} +3 -2
  35. package/vendor/{chunk-XNFVSVBS.js → chunk-SRKIBFOE.js} +1 -1
  36. package/vendor/{chunk-G4IIVVJO.js → chunk-T6UB5PNX.js} +70 -2
  37. package/vendor/{chunk-RVYJKKWA.js → chunk-TG26CZGQ.js} +5 -4
  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-TVYEB2GN.js +343 -0
  41. package/vendor/{chunk-PT3AUPGE.js → chunk-UB6JCVQ3.js} +3 -1
  42. package/vendor/chunk-VGIYSDNU.js +522 -0
  43. package/vendor/{chunk-X6M525ZJ.js → chunk-W2OJZZ6X.js} +5 -5
  44. package/vendor/{chunk-YCDEMYY6.js → chunk-WDFERJG3.js} +231 -99
  45. package/vendor/{chunk-SKVYP7NY.js → chunk-WPIEF4LY.js} +8 -8
  46. package/vendor/{chunk-UI5RLBKQ.js → chunk-YZLQZU5E.js} +17 -1
  47. package/vendor/{chunk-PY5LYLV7.js → chunk-Z5WCAUA6.js} +26 -21
  48. package/vendor/chunk-ZIOKV2X6.js +1589 -0
  49. package/vendor/chunk-ZOHNXUDY.js +12501 -0
  50. package/vendor/chunk-ZUDSZGVO.js +11 -0
  51. package/vendor/component-manifest-catalog.js +2 -1
  52. package/vendor/control-plane.js +11 -6
  53. package/vendor/chunk-2DA7EFZV.js +0 -924
  54. /package/vendor/{chunk-A4NKL2PK.js → chunk-V67IQB7H.js} +0 -0
@@ -1,252 +1,32 @@
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-ZUDSZGVO.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-ZIOKV2X6.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";
251
31
  var issuedCapabilities = /* @__PURE__ */ new WeakSet();
252
32
  var hash = (bytes) => createHash("sha256").update(bytes).digest("hex");
@@ -272,7 +52,7 @@ var regularFile = (path) => {
272
52
  try {
273
53
  if (!lstatSync(path).isFile())
274
54
  throw new Error("Desktop runtime bundle entry is not a regular file");
275
- return readFileSync2(fd);
55
+ return readFileSync(fd);
276
56
  } finally {
277
57
  closeSync(fd);
278
58
  }
@@ -355,529 +135,222 @@ function resolveDesktopRuntimeOwner(capability, koedHome) {
355
135
  return deriveDesktopRuntimeOwner(koedHome, capability.resourcesPath);
356
136
  }
357
137
 
358
- // packages/koed-server/dist/component-verification.js
138
+ // packages/koed-server/dist/component-store.js
359
139
  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";
140
+ 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";
141
+ import { dirname, isAbsolute as isAbsolute2, parse, relative as relative2, resolve as resolve2, sep as sep2 } from "node:path";
364
142
 
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
- };
374
-
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);
143
+ // packages/koed-server/dist/bounded-download.js
144
+ import { createWriteStream, rmSync } from "node:fs";
145
+ import { basename } from "node:path";
146
+ import { Readable, Transform } from "node:stream";
147
+ import { pipeline } from "node:stream/promises";
148
+ var MAX_REDIRECTS = 5;
149
+ var REQUEST_TIMEOUT_MS = 3e4;
150
+ var abortedError = (signal, cause) => new Error(signal.reason?.name === "TimeoutError" ? "component installation timed out" : "component installation cancelled", cause === void 0 ? void 0 : { cause });
151
+ var stalledError = (cause) => new Error(`component download stalled: no data for ${REQUEST_TIMEOUT_MS / 1e3} s`, { cause });
152
+ var cancelBody = async (response) => {
153
+ try {
154
+ await response.body?.cancel();
155
+ } catch {
459
156
  }
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);
157
+ };
158
+ async function fetchBounded(urlText, destination, limit, signal, progress, collectBytes = true, attempt = 0) {
159
+ let url;
160
+ try {
161
+ url = new URL(urlText);
162
+ } catch {
163
+ throw new Error("component source URL is invalid");
466
164
  }
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;
165
+ if (url.protocol !== "https:" || url.username || url.password)
166
+ throw new Error("component downloads require safe HTTPS URLs");
167
+ for (let redirects = 0; ; redirects++) {
168
+ if (signal?.aborted)
169
+ throw abortedError(signal);
170
+ let response;
171
+ const timeoutController = new AbortController();
172
+ const requestSignal = signal ? AbortSignal.any([signal, timeoutController.signal]) : timeoutController.signal;
173
+ let timeout = setTimeout(() => timeoutController.abort(), REQUEST_TIMEOUT_MS);
174
+ const resetIdleTimeout = () => {
175
+ clearTimeout(timeout);
176
+ timeout = setTimeout(() => timeoutController.abort(), REQUEST_TIMEOUT_MS);
177
+ };
178
+ try {
179
+ response = await fetch(url, {
180
+ redirect: "manual",
181
+ signal: requestSignal
182
+ });
183
+ } catch (error) {
184
+ if (signal?.aborted)
185
+ throw abortedError(signal, error);
186
+ if (timeoutController.signal.aborted)
187
+ throw stalledError(error);
188
+ if (attempt < 2 && error instanceof TypeError) {
189
+ await new Promise((resolveRetry) => setTimeout(resolveRetry, 100 * (attempt + 1)));
190
+ return fetchBounded(url.href, destination, limit, signal, progress, collectBytes, attempt + 1);
191
+ }
192
+ throw error;
193
+ } finally {
194
+ clearTimeout(timeout);
513
195
  }
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);
196
+ if (response.status >= 500 && attempt < 2) {
197
+ await cancelBody(response);
198
+ await new Promise((resolveRetry) => setTimeout(resolveRetry, 100 * (attempt + 1)));
199
+ return fetchBounded(url.href, destination, limit, signal, progress, collectBytes, attempt + 1);
580
200
  }
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;
201
+ if ([301, 302, 303, 307, 308].includes(response.status)) {
202
+ if (redirects >= MAX_REDIRECTS) {
203
+ await cancelBody(response);
204
+ throw new Error("too many component redirects");
600
205
  }
601
- if (header.every((byte) => byte === 0)) {
602
- zeroBlocks++;
603
- if (zeroBlocks === 2)
604
- ended = true;
605
- continue;
206
+ const location = response.headers.get("location");
207
+ if (!location) {
208
+ await cancelBody(response);
209
+ throw new Error("component redirect has no location");
606
210
  }
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;
211
+ try {
212
+ url = new URL(location, url);
213
+ } catch {
214
+ await cancelBody(response);
215
+ throw new Error("component redirect URL is invalid");
650
216
  }
651
- contents.set(path, digest.digest("hex"));
217
+ if (url.protocol !== "https:" || url.username || url.password) {
218
+ await cancelBody(response);
219
+ throw new Error("component redirect requires safe HTTPS");
220
+ }
221
+ await cancelBody(response);
222
+ continue;
652
223
  }
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}`);
224
+ if (!response.ok || !response.body) {
225
+ await cancelBody(response);
226
+ throw new Error(`component download failed with HTTP ${response.status}`);
665
227
  }
228
+ const length = Number(response.headers.get("content-length"));
229
+ if (Number.isFinite(length) && length > limit) {
230
+ await cancelBody(response);
231
+ throw new Error("component download exceeds size limit");
232
+ }
233
+ let transferredBytes = 0;
234
+ const chunks = [];
235
+ const limiter = new Transform({
236
+ transform(chunk, _encoding, callback) {
237
+ resetIdleTimeout();
238
+ transferredBytes += chunk.length;
239
+ if (transferredBytes > limit) {
240
+ callback(new Error("component download exceeds size limit"));
241
+ return;
242
+ }
243
+ progress?.({
244
+ phase: basename(destination),
245
+ transferredBytes,
246
+ ...Number.isFinite(length) && length > 0 ? { totalBytes: length } : {}
247
+ });
248
+ if (collectBytes)
249
+ chunks.push(Buffer.from(chunk));
250
+ callback(null, chunk);
251
+ }
252
+ });
253
+ const output = createWriteStream(destination, { flags: "wx", mode: 384 });
254
+ resetIdleTimeout();
255
+ try {
256
+ await pipeline(Readable.fromWeb(response.body), limiter, output, { signal: requestSignal });
257
+ } catch (error) {
258
+ rmSync(destination, { force: true });
259
+ if (signal?.aborted)
260
+ throw abortedError(signal, error);
261
+ if (timeoutController.signal.aborted)
262
+ throw stalledError(error);
263
+ if (attempt < 2 && error instanceof TypeError) {
264
+ await new Promise((resolveRetry) => setTimeout(resolveRetry, 100 * (attempt + 1)));
265
+ return fetchBounded(url.href, destination, limit, signal, progress, collectBytes, attempt + 1);
266
+ }
267
+ throw error;
268
+ } finally {
269
+ clearTimeout(timeout);
270
+ }
271
+ return collectBytes ? Buffer.concat(chunks) : void 0;
666
272
  }
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
273
  }
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);
274
+
275
+ // packages/koed-server/dist/directory-lock.js
276
+ import { mkdirSync, rmSync as rmSync2 } from "node:fs";
277
+ var acquireDirectoryLock = (path) => {
722
278
  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;
279
+ mkdirSync(path, { mode: 448 });
280
+ } catch (error) {
281
+ if (error.code !== "EEXIST")
282
+ throw error;
283
+ throw Object.assign(new Error("lock is already held"), { code: "ELOCKED" });
752
284
  }
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
285
+ let released = false;
286
+ return () => {
287
+ if (released)
288
+ return;
289
+ released = true;
290
+ rmSync2(path, { recursive: true, force: true });
291
+ };
767
292
  };
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
- }
293
+
294
+ // packages/koed-server/dist/component-runtime-identity.js
295
+ import process2 from "node:process";
296
+ 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)));
297
+ function discoverRuntimeIdentityFromProcess(source) {
298
+ const platform = source.platform === "darwin" ? "macos" : source.platform === "linux" ? "linux" : void 0;
299
+ const architecture = source.arch === "arm64" || source.arch === "x64" ? source.arch : void 0;
300
+ const runtimeVersion = source.versions.electron ?? source.versions.node;
301
+ const nodeVersion = source.versions.node;
302
+ const modulesAbi = source.versions.modules;
303
+ const napiVersion = Number(source.versions.napi ?? "0");
304
+ let libcVersion;
305
+ if (platform === "linux") {
306
+ try {
307
+ libcVersion = source.report?.getReport().header?.glibcVersionRuntime;
308
+ } catch {
309
+ throw new Error("actual runtime identity is unsupported or incomplete");
835
310
  }
836
- if (!sameObject(beforeDirectory, lstatSync2(current)))
837
- throw new Error("component directory ancestry changed during verification");
838
311
  }
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}`);
312
+ if (!platform || !architecture || !isVersion(runtimeVersion) || !isVersion(nodeVersion) || typeof modulesAbi !== "string" || !/^\d+$/.test(modulesAbi) || !Number.isSafeInteger(napiVersion) || napiVersion < 0 || platform === "linux" && !isVersion(libcVersion))
313
+ throw new Error("actual runtime identity is unsupported or incomplete");
314
+ return {
315
+ kind: source.versions.electron === void 0 ? "node" : "electron",
316
+ version: runtimeVersion,
317
+ nodeVersion,
318
+ modulesAbi,
319
+ napiVersion,
320
+ platform,
321
+ architecture,
322
+ ...libcVersion === void 0 ? {} : { libcVersion }
323
+ };
324
+ }
325
+ function discoverActualRuntimeIdentity() {
326
+ return discoverRuntimeIdentityFromProcess(process2);
845
327
  }
846
- var verifyExtractedComponent = (root, manifest) => Promise.resolve().then(() => verifyExtractedComponentSync(root, manifest));
847
328
 
848
329
  // 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");
330
+ var MAX_MANIFEST_BYTES = 64 * 1024 * 1024;
331
+ var MAX_ARCHIVE_BYTES = 2 * 1024 * 1024 * 1024;
332
+ var MAX_GENERATION_RECORD_BYTES = 2 * MAX_MANIFEST_BYTES + 1024 * 1024;
333
+ var hash2 = (value) => createHash2("sha256").update(value).digest("hex");
855
334
  var isPlainRecord = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
856
335
  var aborted = (signal) => {
857
336
  if (signal?.aborted)
858
337
  throw new Error("component installation cancelled");
859
338
  };
860
- var cancelBody = async (response) => {
861
- try {
862
- await response.body?.cancel();
863
- } catch {
864
- }
865
- };
866
339
  var exactKeys = (value, keys) => Object.keys(value).length === keys.length && keys.every((key) => Object.hasOwn(value, key));
867
340
  var assertInside = (base, path) => {
868
- const rel = relative3(resolve3(base), resolve3(path));
869
- if (rel.startsWith("..") || isAbsolute3(rel))
341
+ const rel = relative2(resolve2(base), resolve2(path));
342
+ if (rel.startsWith("..") || isAbsolute2(rel))
870
343
  throw new Error("component store path escaped KOED_HOME");
871
344
  };
872
345
  var assertDirectoryChain = (base, path) => {
873
346
  assertInside(base, path);
874
- const absolute = resolve3(path);
347
+ const absolute = resolve2(path);
875
348
  let cursor = parse(absolute).root;
876
- for (const part of absolute.slice(cursor.length).split(sep3).filter(Boolean)) {
877
- cursor = resolve3(cursor, part);
349
+ for (const part of absolute.slice(cursor.length).split(sep2).filter(Boolean)) {
350
+ cursor = resolve2(cursor, part);
878
351
  let stat;
879
352
  try {
880
- stat = lstatSync3(cursor);
353
+ stat = lstatSync2(cursor);
881
354
  } catch (error) {
882
355
  if (error.code === "ENOENT")
883
356
  return;
@@ -889,12 +362,12 @@ var assertDirectoryChain = (base, path) => {
889
362
  };
890
363
  var ensureSecureDirectory = (home, directory) => {
891
364
  assertDirectoryChain(home, directory);
892
- mkdirSync3(directory, { recursive: true, mode: 448 });
365
+ mkdirSync2(directory, { recursive: true, mode: 448 });
893
366
  assertDirectoryChain(home, directory);
894
367
  };
895
368
  var privateDirectory = (path) => {
896
- mkdirSync3(path, { recursive: true, mode: 448 });
897
- const stat = lstatSync3(path);
369
+ mkdirSync2(path, { recursive: true, mode: 448 });
370
+ const stat = lstatSync2(path);
898
371
  if (!stat.isDirectory() || stat.isSymbolicLink())
899
372
  throw new Error("component store directory is not a regular directory");
900
373
  chmodSync(path, 448);
@@ -953,149 +426,38 @@ var resolveComponentManifestPinTarget = (catalog, input) => {
953
426
  return target;
954
427
  };
955
428
  var parseJsonFile = (path, maxBytes, requireCanonical = false) => {
956
- if (constants3.O_NOFOLLOW === void 0)
429
+ if (constants2.O_NOFOLLOW === void 0)
957
430
  throw new Error("component metadata no-follow access is unavailable");
958
- const descriptor = openSync3(path, constants3.O_RDONLY | constants3.O_NOFOLLOW);
431
+ const descriptor = openSync2(path, constants2.O_RDONLY | constants2.O_NOFOLLOW);
959
432
  try {
960
- const stat = fstatSync2(descriptor);
433
+ const stat = fstatSync(descriptor);
961
434
  if (!stat.isFile() || stat.size > maxBytes)
962
435
  throw new Error("component metadata is not a bounded regular file");
963
- const bytes = readFileSync3(descriptor, "utf8");
436
+ const bytes = readFileSync2(descriptor, "utf8");
964
437
  const value = JSON.parse(bytes);
965
438
  if (requireCanonical && canonicalArtifactJson(value) !== bytes)
966
439
  throw new Error("component metadata is not canonical JSON");
967
440
  return value;
968
441
  } finally {
969
- closeSync3(descriptor);
442
+ closeSync2(descriptor);
970
443
  }
971
444
  };
972
445
  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)
446
+ const archivePath = resolve2(source.archivePath);
447
+ const archiveStat = lstatSync2(archivePath);
448
+ if (!archiveStat.isFile() || archiveStat.isSymbolicLink() || archiveStat.size > MAX_ARCHIVE_BYTES)
976
449
  throw new Error("component archive is not a bounded regular file");
977
450
  return {
978
451
  archivePath,
979
- manifestBytes: readBoundedFile(source.manifestPath, MAX_MANIFEST_BYTES2)
452
+ manifestBytes: readBoundedFile(source.manifestPath, MAX_MANIFEST_BYTES)
980
453
  };
981
454
  };
982
455
  var readBoundedFile = (path, limit) => {
983
- const stat = lstatSync3(path);
456
+ const stat = lstatSync2(path);
984
457
  if (!stat.isFile() || stat.isSymbolicLink() || stat.size > limit)
985
458
  throw new Error("component metadata is not a bounded regular file");
986
- return readFileSync3(path);
459
+ return readFileSync2(path);
987
460
  };
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
461
  async function acquireLock(home, root, signal, fn) {
1100
462
  ensureSecureDirectory(home, root);
1101
463
  let release;
@@ -1145,23 +507,23 @@ function validateOwner(owner) {
1145
507
  throw new Error("runtime owner is invalid");
1146
508
  }
1147
509
  function writeIndex(home, indexPath, manifestDigest, tempRoot, signal) {
1148
- const temporaryIndex = resolve3(tempRoot, `index-${manifestDigest}.json`);
1149
- writeFileSync2(temporaryIndex, JSON.stringify({ manifestDigest }), {
510
+ const temporaryIndex = resolve2(tempRoot, `index-${manifestDigest}.json`);
511
+ writeFileSync(temporaryIndex, JSON.stringify({ manifestDigest }), {
1150
512
  flag: "wx",
1151
513
  mode: 384
1152
514
  });
1153
515
  aborted(signal);
1154
- assertDirectoryChain(home, dirname2(indexPath));
1155
- renameSync2(temporaryIndex, indexPath);
516
+ assertDirectoryChain(home, dirname(indexPath));
517
+ renameSync(temporaryIndex, indexPath);
1156
518
  }
1157
519
  function componentRecordPath(root) {
1158
- return resolve3(root, "component.json");
520
+ return resolve2(root, "component.json");
1159
521
  }
1160
522
  function componentPayloadPath(root) {
1161
- return resolve3(root, "payload");
523
+ return resolve2(root, "payload");
1162
524
  }
1163
525
  function readComponentRecord(path) {
1164
- const value = parseJsonFile(path, MAX_MANIFEST_BYTES2 + 32768);
526
+ const value = parseJsonFile(path, MAX_MANIFEST_BYTES + 32768);
1165
527
  if (isPlainRecord(value) && value.schemaVersion === 1)
1166
528
  throw new Error("Stored component predates manifest pin admission; reinstall components using a trusted versioned control plane.");
1167
529
  if (!isPlainRecord(value) || !exactKeys(value, [
@@ -1199,7 +561,7 @@ async function verifyStoredComponent(home, root, expected) {
1199
561
  },
1200
562
  runtime: expected.runtime
1201
563
  });
1202
- const archivePath = resolve3(root, record.archivePath);
564
+ const archivePath = resolve2(root, record.archivePath);
1203
565
  assertInside(root, archivePath);
1204
566
  const manifest = await verifyComponent({
1205
567
  manifestBytes,
@@ -1211,9 +573,9 @@ async function verifyStoredComponent(home, root, expected) {
1211
573
  target,
1212
574
  runtime: expected.runtime
1213
575
  });
1214
- if (archivePath !== resolve3(root, manifest.archive.name))
576
+ if (archivePath !== resolve2(root, manifest.archive.name))
1215
577
  throw new Error("stored component archive path is invalid");
1216
- const archiveStat = lstatSync3(archivePath);
578
+ const archiveStat = lstatSync2(archivePath);
1217
579
  if (!archiveStat.isFile() || archiveStat.isSymbolicLink())
1218
580
  throw new Error("stored component archive is not a regular file");
1219
581
  const payload = componentPayloadPath(root);
@@ -1228,11 +590,11 @@ async function verifyStoredComponent(home, root, expected) {
1228
590
  }
1229
591
  async function stageComponentInternal(paths, source, context, runtime) {
1230
592
  aborted(context.signal);
1231
- const storeRoot = resolve3(paths.componentsDir);
593
+ const storeRoot = resolve2(paths.componentsDir);
1232
594
  assertInside(paths.koedHome, storeRoot);
1233
595
  assertDirectoryChain(paths.koedHome, storeRoot);
1234
596
  ensureSecureDirectory(paths.koedHome, storeRoot);
1235
- const tempRoot = mkdtempSync(resolve3(storeRoot, ".stage-"));
597
+ const tempRoot = mkdtempSync(resolve2(storeRoot, ".stage-"));
1236
598
  chmodSync(tempRoot, 448);
1237
599
  try {
1238
600
  const catalog = readProductionManifestPinCatalog();
@@ -1240,7 +602,7 @@ async function stageComponentInternal(paths, source, context, runtime) {
1240
602
  if (source.kind === "offline") {
1241
603
  manifestBytes = readOfflineSource(source).manifestBytes;
1242
604
  } else {
1243
- manifestBytes = await fetchBounded(source.manifestUrl, resolve3(tempRoot, "manifest.json"), MAX_MANIFEST_BYTES2, context.signal, context.progress);
605
+ manifestBytes = await fetchBounded(source.manifestUrl, resolve2(tempRoot, "manifest.json"), MAX_MANIFEST_BYTES, context.signal, context.progress);
1244
606
  }
1245
607
  if (context.target.platform !== runtime.platform || context.target.architecture !== runtime.architecture)
1246
608
  throw new Error("component target does not match actual runtime");
@@ -1259,12 +621,12 @@ async function stageComponentInternal(paths, source, context, runtime) {
1259
621
  expectedVersion: context.expectedVersion,
1260
622
  target
1261
623
  });
1262
- const archivePath = resolve3(tempRoot, manifest.archive.name);
624
+ const archivePath = resolve2(tempRoot, manifest.archive.name);
1263
625
  if (source.kind === "offline") {
1264
- copyFileSync(resolve3(source.archivePath), archivePath, 1);
626
+ copyFileSync(resolve2(source.archivePath), archivePath, 1);
1265
627
  chmodSync(archivePath, 384);
1266
628
  } else {
1267
- await fetchBounded(source.archiveUrl, archivePath, MAX_ARCHIVE_BYTES2, context.signal, context.progress, false);
629
+ await fetchBounded(source.archiveUrl, archivePath, MAX_ARCHIVE_BYTES, context.signal, context.progress, false);
1268
630
  }
1269
631
  aborted(context.signal);
1270
632
  context.progress?.({ phase: "verify", transferredBytes: 0 });
@@ -1280,12 +642,12 @@ async function stageComponentInternal(paths, source, context, runtime) {
1280
642
  });
1281
643
  aborted(context.signal);
1282
644
  const manifestDigest = hash2(manifestBytes);
1283
- const componentDir = resolve3(storeRoot, manifest.component);
645
+ const componentDir = resolve2(storeRoot, manifest.component);
1284
646
  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");
647
+ const indexPath = resolve2(componentDir, `${targetKey(manifest)}.json`);
648
+ const versionRoot = resolve2(componentDir, manifest.productVersion, manifestDigest);
649
+ const stagedRoot = resolve2(tempRoot, "verified");
650
+ const completeRoot = resolve2(tempRoot, "complete");
1289
651
  aborted(context.signal);
1290
652
  context.progress?.({ phase: "extract", transferredBytes: 0 });
1291
653
  await extractVerifiedPackageArchive(archivePath, stagedRoot);
@@ -1293,24 +655,24 @@ async function stageComponentInternal(paths, source, context, runtime) {
1293
655
  await verifyExtractedComponent(stagedRoot, manifest);
1294
656
  aborted(context.signal);
1295
657
  privateDirectory(completeRoot);
1296
- renameSync2(stagedRoot, resolve3(completeRoot, "payload"));
1297
- renameSync2(archivePath, resolve3(completeRoot, manifest.archive.name));
1298
- writeFileSync2(componentRecordPath(completeRoot), JSON.stringify({
658
+ renameSync(stagedRoot, resolve2(completeRoot, "payload"));
659
+ renameSync(archivePath, resolve2(completeRoot, manifest.archive.name));
660
+ writeFileSync(componentRecordPath(completeRoot), JSON.stringify({
1299
661
  schemaVersion: 2,
1300
662
  manifest,
1301
663
  manifestDigest,
1302
- archivePath: resolve3(versionRoot, manifest.archive.name)
664
+ archivePath: resolve2(versionRoot, manifest.archive.name)
1303
665
  }), { flag: "wx", mode: 384 });
1304
666
  return await acquireLock(paths.koedHome, storeRoot, context.signal, async () => {
1305
667
  ensureSecureDirectory(paths.koedHome, componentDir);
1306
668
  assertDirectoryChain(paths.koedHome, versionRoot);
1307
- assertDirectoryChain(paths.koedHome, dirname2(indexPath));
1308
- if (existsSync2(indexPath)) {
669
+ assertDirectoryChain(paths.koedHome, dirname(indexPath));
670
+ if (existsSync(indexPath)) {
1309
671
  const index = parseJsonFile(indexPath, 4096);
1310
672
  if (!isPlainRecord(index) || index.manifestDigest !== manifestDigest)
1311
673
  throw new Error("component version already installed with different digest");
1312
674
  }
1313
- if (existsSync2(versionRoot)) {
675
+ if (existsSync(versionRoot)) {
1314
676
  const cached = await verifyStoredComponent(paths.koedHome, versionRoot, {
1315
677
  component: manifest.component,
1316
678
  productVersion: manifest.productVersion,
@@ -1320,25 +682,25 @@ async function stageComponentInternal(paths, source, context, runtime) {
1320
682
  aborted(context.signal);
1321
683
  if (cached.manifestDigest !== manifestDigest)
1322
684
  throw new Error("component version already installed with different digest");
1323
- if (!existsSync2(indexPath)) {
685
+ if (!existsSync(indexPath)) {
1324
686
  aborted(context.signal);
1325
- assertDirectoryChain(paths.koedHome, dirname2(indexPath));
687
+ assertDirectoryChain(paths.koedHome, dirname(indexPath));
1326
688
  writeIndex(paths.koedHome, indexPath, manifestDigest, tempRoot, context.signal);
1327
689
  }
1328
690
  return cached;
1329
691
  }
1330
- if (existsSync2(indexPath))
692
+ if (existsSync(indexPath))
1331
693
  throw new Error("component cache record is missing");
1332
- ensureSecureDirectory(paths.koedHome, dirname2(versionRoot));
694
+ ensureSecureDirectory(paths.koedHome, dirname(versionRoot));
1333
695
  let publishedRoot;
1334
696
  let committed = false;
1335
697
  try {
1336
698
  aborted(context.signal);
1337
- assertDirectoryChain(paths.koedHome, dirname2(versionRoot));
1338
- renameSync2(completeRoot, versionRoot);
699
+ assertDirectoryChain(paths.koedHome, dirname(versionRoot));
700
+ renameSync(completeRoot, versionRoot);
1339
701
  publishedRoot = versionRoot;
1340
702
  aborted(context.signal);
1341
- assertDirectoryChain(paths.koedHome, dirname2(indexPath));
703
+ assertDirectoryChain(paths.koedHome, dirname(indexPath));
1342
704
  writeIndex(paths.koedHome, indexPath, manifestDigest, tempRoot, context.signal);
1343
705
  committed = true;
1344
706
  return {
@@ -1367,21 +729,21 @@ async function stageGeneration(paths, input) {
1367
729
  validateOwner(input.owner);
1368
730
  const { base, privacy } = input;
1369
731
  assertDirectoryChain(paths.koedHome, paths.componentsDir);
1370
- assertDirectoryChain(paths.componentsDir, dirname2(base.root));
1371
- const baseVerified = await verifyStoredComponent(paths.koedHome, dirname2(base.root), {
732
+ assertDirectoryChain(paths.componentsDir, dirname(base.root));
733
+ const baseVerified = await verifyStoredComponent(paths.koedHome, dirname(base.root), {
1372
734
  component: "base",
1373
735
  runtime: actualRuntime
1374
736
  });
1375
- if (baseVerified.manifestDigest !== base.manifestDigest || resolve3(baseVerified.root) !== resolve3(base.root))
737
+ if (baseVerified.manifestDigest !== base.manifestDigest || resolve2(baseVerified.root) !== resolve2(base.root))
1376
738
  throw new Error("base component is not a verified store entry");
1377
739
  let privacyVerified;
1378
740
  if (privacy) {
1379
- assertDirectoryChain(paths.componentsDir, dirname2(privacy.root));
1380
- privacyVerified = await verifyStoredComponent(paths.koedHome, dirname2(privacy.root), {
741
+ assertDirectoryChain(paths.componentsDir, dirname(privacy.root));
742
+ privacyVerified = await verifyStoredComponent(paths.koedHome, dirname(privacy.root), {
1381
743
  component: "privacy",
1382
744
  runtime: actualRuntime
1383
745
  });
1384
- if (privacyVerified.manifestDigest !== privacy.manifestDigest || resolve3(privacyVerified.root) !== resolve3(privacy.root))
746
+ if (privacyVerified.manifestDigest !== privacy.manifestDigest || resolve2(privacyVerified.root) !== resolve2(privacy.root))
1385
747
  throw new Error("privacy component is not a verified store entry");
1386
748
  }
1387
749
  if (privacyVerified && baseVerified.manifest.productVersion !== privacyVerified.manifest.productVersion)
@@ -1394,31 +756,31 @@ async function stageGeneration(paths, input) {
1394
756
  owner: input.owner,
1395
757
  base: {
1396
758
  manifestDigest: baseVerified.manifestDigest,
1397
- root: relative3(paths.koedHome, baseVerified.root)
759
+ root: relative2(paths.koedHome, baseVerified.root)
1398
760
  },
1399
761
  ...privacyVerified ? {
1400
762
  privacy: {
1401
763
  manifestDigest: privacyVerified.manifestDigest,
1402
- root: relative3(paths.koedHome, privacyVerified.root)
764
+ root: relative2(paths.koedHome, privacyVerified.root)
1403
765
  }
1404
766
  } : {}
1405
767
  };
1406
768
  const id = hash2(canonicalArtifactJson(identity));
1407
- const generationRoot = resolve3(paths.generationsDir, id);
769
+ const generationRoot = resolve2(paths.generationsDir, id);
1408
770
  assertDirectoryChain(paths.koedHome, generationRoot);
1409
771
  assertDirectoryChain(paths.koedHome, paths.generationsDir);
1410
772
  return acquireLock(paths.koedHome, paths.generationsDir, void 0, async () => {
1411
- if (existsSync2(generationRoot))
773
+ if (existsSync(generationRoot))
1412
774
  return readStagedGeneration(paths, id);
1413
775
  ensureSecureDirectory(paths.koedHome, paths.generationsDir);
1414
- const tempRoot = mkdtempSync(resolve3(paths.generationsDir, ".stage-"));
776
+ const tempRoot = mkdtempSync(resolve2(paths.generationsDir, ".stage-"));
1415
777
  chmodSync(tempRoot, 448);
1416
778
  try {
1417
- const freshBase = await verifyStoredComponent(paths.koedHome, dirname2(baseVerified.root), {
779
+ const freshBase = await verifyStoredComponent(paths.koedHome, dirname(baseVerified.root), {
1418
780
  component: "base",
1419
781
  runtime: actualRuntime
1420
782
  });
1421
- const freshPrivacy = privacyVerified ? await verifyStoredComponent(paths.koedHome, dirname2(privacyVerified.root), {
783
+ const freshPrivacy = privacyVerified ? await verifyStoredComponent(paths.koedHome, dirname(privacyVerified.root), {
1422
784
  component: "privacy",
1423
785
  runtime: actualRuntime
1424
786
  }) : void 0;
@@ -1441,13 +803,13 @@ async function stageGeneration(paths, input) {
1441
803
  const recordBytes = Buffer.from(canonicalArtifactJson(record));
1442
804
  if (recordBytes.length > MAX_GENERATION_RECORD_BYTES)
1443
805
  throw new Error("generation record exceeds size limit");
1444
- writeFileSync2(resolve3(tempRoot, "generation.json"), recordBytes, {
806
+ writeFileSync(resolve2(tempRoot, "generation.json"), recordBytes, {
1445
807
  flag: "wx",
1446
808
  mode: 384
1447
809
  });
1448
810
  assertDirectoryChain(paths.koedHome, paths.generationsDir);
1449
811
  assertDirectoryChain(paths.generationsDir, generationRoot);
1450
- renameSync2(tempRoot, generationRoot);
812
+ renameSync(tempRoot, generationRoot);
1451
813
  return {
1452
814
  id,
1453
815
  productVersion: identity.productVersion,
@@ -1456,7 +818,7 @@ async function stageGeneration(paths, input) {
1456
818
  owner: input.owner
1457
819
  };
1458
820
  } finally {
1459
- if (existsSync2(tempRoot))
821
+ if (existsSync(tempRoot))
1460
822
  rmSync3(tempRoot, { recursive: true, force: true });
1461
823
  }
1462
824
  });
@@ -1464,23 +826,23 @@ async function stageGeneration(paths, input) {
1464
826
  async function readStoredComponents(paths, runtime) {
1465
827
  const components = [];
1466
828
  for (const component of ["base", "privacy"]) {
1467
- const componentRoot = resolve3(paths.componentsDir, component);
1468
- if (!existsSync2(componentRoot))
829
+ const componentRoot = resolve2(paths.componentsDir, component);
830
+ if (!existsSync(componentRoot))
1469
831
  continue;
1470
832
  assertDirectoryChain(paths.koedHome, componentRoot);
1471
- for (const versionEntry of readdirSync3(componentRoot, {
833
+ for (const versionEntry of readdirSync2(componentRoot, {
1472
834
  withFileTypes: true
1473
835
  })) {
1474
836
  if (!versionEntry.isDirectory() || !/^(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)(?:\.(?:0|[1-9]\d*))?(?:-[0-9A-Za-z.-]+)?$/.test(versionEntry.name))
1475
837
  continue;
1476
- const versionRoot = resolve3(componentRoot, versionEntry.name);
1477
- for (const digestEntry of readdirSync3(versionRoot, {
838
+ const versionRoot = resolve2(componentRoot, versionEntry.name);
839
+ for (const digestEntry of readdirSync2(versionRoot, {
1478
840
  withFileTypes: true
1479
841
  })) {
1480
842
  if (!digestEntry.isDirectory() || !/^[a-f0-9]{64}$/.test(digestEntry.name))
1481
843
  continue;
1482
844
  try {
1483
- components.push(await verifyStoredComponent(paths.koedHome, resolve3(versionRoot, digestEntry.name), {
845
+ components.push(await verifyStoredComponent(paths.koedHome, resolve2(versionRoot, digestEntry.name), {
1484
846
  component,
1485
847
  productVersion: versionEntry.name,
1486
848
  runtime
@@ -1511,9 +873,9 @@ var readDesktopPrivacyGeneration = async (paths, id, record) => {
1511
873
  if (bundle.productVersion !== record.productVersion || bundle.bundleDigest !== record.bundleDigest)
1512
874
  throw new Error("Desktop runtime bundle changed after generation staging");
1513
875
  const runtime = discoverActualRuntimeIdentity();
1514
- const privacyRoot = resolve3(paths.koedHome, record.privacy.root);
876
+ const privacyRoot = resolve2(paths.koedHome, record.privacy.root);
1515
877
  assertInside(paths.koedHome, privacyRoot);
1516
- const privacy = await verifyStoredComponent(paths.koedHome, dirname2(privacyRoot), {
878
+ const privacy = await verifyStoredComponent(paths.koedHome, dirname(privacyRoot), {
1517
879
  component: "privacy",
1518
880
  productVersion: bundle.productVersion,
1519
881
  target: bundle.target,
@@ -1529,7 +891,7 @@ var readDesktopPrivacyGeneration = async (paths, id, record) => {
1529
891
  resourcesPath: bundle.resourcesPath,
1530
892
  bundleDigest: bundle.bundleDigest,
1531
893
  privacy: {
1532
- root: relative3(paths.koedHome, privacy.root),
894
+ root: relative2(paths.koedHome, privacy.root),
1533
895
  manifestDigest: privacy.manifestDigest
1534
896
  }
1535
897
  };
@@ -1541,7 +903,7 @@ var readDesktopPrivacyGeneration = async (paths, id, record) => {
1541
903
  base: {
1542
904
  kind: "desktop-bundle",
1543
905
  manifest: bundle.manifest,
1544
- root: resolve3(bundle.resourcesPath, "koed-runtime"),
906
+ root: resolve2(bundle.resourcesPath, "koed-runtime"),
1545
907
  manifestDigest: bundle.bundleDigest
1546
908
  },
1547
909
  privacy,
@@ -1552,13 +914,13 @@ function readGenerationRecord(paths, id) {
1552
914
  if (!/^[a-f0-9]{64}$/.test(id))
1553
915
  throw new Error("generation id is invalid");
1554
916
  assertDirectoryChain(paths.koedHome, paths.generationsDir);
1555
- const root = resolve3(paths.generationsDir, id);
917
+ const root = resolve2(paths.generationsDir, id);
1556
918
  assertDirectoryChain(paths.generationsDir, root);
1557
- return parseJsonFile(resolve3(root, "generation.json"), MAX_GENERATION_RECORD_BYTES, true);
919
+ return parseJsonFile(resolve2(root, "generation.json"), MAX_GENERATION_RECORD_BYTES, true);
1558
920
  }
1559
921
  function assertOrderingStoreMetadata(root, manifest, digest) {
1560
922
  const stored = readComponentRecord(componentRecordPath(root));
1561
- if (stored.manifestDigest !== digest || canonicalArtifactJson(stored.manifest) !== canonicalArtifactJson(manifest) || stored.archivePath !== resolve3(root, manifest.archive.name))
923
+ if (stored.manifestDigest !== digest || canonicalArtifactJson(stored.manifest) !== canonicalArtifactJson(manifest) || stored.archivePath !== resolve2(root, manifest.archive.name))
1562
924
  throw new Error("generation component metadata differs from store");
1563
925
  }
1564
926
  function readOrderingComponent(paths, component, version, reference, embedded) {
@@ -1569,10 +931,10 @@ function readOrderingComponent(paths, component, version, reference, embedded) {
1569
931
  const digest = hash2(canonicalArtifactJson(manifest));
1570
932
  if (manifest.component !== component || manifest.productVersion !== version || reference.manifestDigest !== digest || embedded.manifestDigest !== digest)
1571
933
  throw new Error("generation component identity mismatch");
1572
- const componentRoot = resolve3(paths.componentsDir, component, version, digest);
934
+ const componentRoot = resolve2(paths.componentsDir, component, version, digest);
1573
935
  const payload = componentPayloadPath(componentRoot);
1574
936
  assertInside(paths.koedHome, componentRoot);
1575
- if (reference.root !== relative3(paths.koedHome, payload))
937
+ if (reference.root !== relative2(paths.koedHome, payload))
1576
938
  throw new Error("stored generation root is invalid");
1577
939
  assertDirectoryChain(paths.koedHome, payload);
1578
940
  assertOrderingStoreMetadata(componentRoot, manifest, digest);
@@ -1654,9 +1016,9 @@ async function readStagedGeneration(paths, id) {
1654
1016
  const baseRelative = record.base.root;
1655
1017
  if (typeof baseRelative !== "string")
1656
1018
  throw new Error("stored generation root is invalid");
1657
- const baseRoot = resolve3(paths.koedHome, baseRelative);
1019
+ const baseRoot = resolve2(paths.koedHome, baseRelative);
1658
1020
  assertInside(paths.koedHome, baseRoot);
1659
- const base = await verifyStoredComponent(paths.koedHome, dirname2(baseRoot), {
1021
+ const base = await verifyStoredComponent(paths.koedHome, dirname(baseRoot), {
1660
1022
  component: "base",
1661
1023
  runtime
1662
1024
  });
@@ -1667,9 +1029,9 @@ async function readStagedGeneration(paths, id) {
1667
1029
  const reference = record.privacy;
1668
1030
  if (!isPlainRecord(reference) || !exactKeys(reference, ["manifestDigest", "root"]) || typeof reference.root !== "string")
1669
1031
  throw new Error("stored generation privacy reference is invalid");
1670
- const privacyRoot = resolve3(paths.koedHome, reference.root);
1032
+ const privacyRoot = resolve2(paths.koedHome, reference.root);
1671
1033
  assertInside(paths.koedHome, privacyRoot);
1672
- privacy = await verifyStoredComponent(paths.koedHome, dirname2(privacyRoot), {
1034
+ privacy = await verifyStoredComponent(paths.koedHome, dirname(privacyRoot), {
1673
1035
  component: "privacy",
1674
1036
  runtime
1675
1037
  });
@@ -1684,12 +1046,12 @@ async function readStagedGeneration(paths, id) {
1684
1046
  owner: record.owner,
1685
1047
  base: {
1686
1048
  manifestDigest: base.manifestDigest,
1687
- root: relative3(paths.koedHome, base.root)
1049
+ root: relative2(paths.koedHome, base.root)
1688
1050
  },
1689
1051
  ...privacy ? {
1690
1052
  privacy: {
1691
1053
  manifestDigest: privacy.manifestDigest,
1692
- root: relative3(paths.koedHome, privacy.root)
1054
+ root: relative2(paths.koedHome, privacy.root)
1693
1055
  }
1694
1056
  } : {}
1695
1057
  };
@@ -1704,16 +1066,11 @@ async function readStagedGeneration(paths, id) {
1704
1066
  };
1705
1067
  }
1706
1068
 
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
1069
  // 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";
1070
+ import { closeSync as closeSync3, mkdirSync as mkdirSync3, openSync as openSync3, readFileSync as readFileSync3, rmSync as rmSync4, writeFileSync as writeFileSync2 } from "node:fs";
1714
1071
  import { spawnSync } from "node:child_process";
1715
1072
  import { hostname } from "node:os";
1716
- import { resolve as resolve4 } from "node:path";
1073
+ import { resolve as resolve3 } from "node:path";
1717
1074
  var processIsRunning = (pid) => {
1718
1075
  if (!Number.isInteger(pid) || pid <= 0)
1719
1076
  return false;
@@ -1730,7 +1087,7 @@ var resolveProcessIdentity = (pid) => {
1730
1087
  return null;
1731
1088
  try {
1732
1089
  if (process.platform === "linux") {
1733
- const stat = readFileSync4(`/proc/${pid}/stat`, "utf8");
1090
+ const stat = readFileSync3(`/proc/${pid}/stat`, "utf8");
1734
1091
  const commandEnd = stat.lastIndexOf(")");
1735
1092
  if (commandEnd < 0)
1736
1093
  return null;
@@ -1738,7 +1095,7 @@ var resolveProcessIdentity = (pid) => {
1738
1095
  const startTime = fields[19];
1739
1096
  if (!startTime)
1740
1097
  return null;
1741
- const bootId = readFileSync4("/proc/sys/kernel/random/boot_id", "utf8").trim();
1098
+ const bootId = readFileSync3("/proc/sys/kernel/random/boot_id", "utf8").trim();
1742
1099
  return `${hostname()}:linux:${bootId}:${startTime}`;
1743
1100
  }
1744
1101
  if (process.platform === "win32") {
@@ -1761,9 +1118,20 @@ var resolveProcessIdentity = (pid) => {
1761
1118
  return null;
1762
1119
  }
1763
1120
  };
1121
+ var readLockText = (lockPath2) => {
1122
+ try {
1123
+ return readFileSync3(lockPath2, "utf8");
1124
+ } catch {
1125
+ return null;
1126
+ }
1127
+ };
1764
1128
  var readSupervisorLock = (lockPath2) => {
1129
+ const text = readLockText(lockPath2);
1130
+ return text === null ? null : parseSupervisorLock(text);
1131
+ };
1132
+ var parseSupervisorLock = (text) => {
1765
1133
  try {
1766
- const value = JSON.parse(readFileSync4(lockPath2, "utf8"));
1134
+ const value = JSON.parse(text);
1767
1135
  return Number.isInteger(value.pid) && Number(value.pid) > 0 ? {
1768
1136
  pid: Number(value.pid),
1769
1137
  acquiredAt: String(value.acquiredAt ?? "unknown"),
@@ -1775,32 +1143,34 @@ var readSupervisorLock = (lockPath2) => {
1775
1143
  };
1776
1144
  var acquireKoedServerSupervisorLock = (paths, options = {}) => {
1777
1145
  const pid = options.pid ?? process.pid;
1146
+ const exclusive = options.exclusive ?? ((action) => action());
1778
1147
  const isRunning = options.isProcessRunning ?? processIsRunning;
1779
1148
  const identify = options.resolveProcessIdentity ?? resolveProcessIdentity;
1780
1149
  const processIdentity = identify(pid);
1781
1150
  if (!processIdentity) {
1782
1151
  throw new Error(`Could not resolve process identity for PID ${pid}.`);
1783
1152
  }
1784
- const lockPath2 = resolve4(paths.runDir, "koed-server.lock");
1785
- mkdirSync4(paths.runDir, { recursive: true, mode: 448 });
1153
+ const lockPath2 = resolve3(paths.runDir, "koed-server.lock");
1154
+ mkdirSync3(paths.runDir, { recursive: true, mode: 448 });
1786
1155
  for (let attempt = 0; attempt < 2; attempt += 1) {
1787
1156
  try {
1788
- const descriptor = openSync4(lockPath2, "wx", 384);
1157
+ const descriptor = openSync3(lockPath2, "wx", 384);
1789
1158
  try {
1790
- writeFileSync3(descriptor, `${JSON.stringify({
1159
+ writeFileSync2(descriptor, `${JSON.stringify({
1791
1160
  pid,
1792
1161
  acquiredAt: (options.now ?? (() => /* @__PURE__ */ new Date()))().toISOString(),
1793
1162
  processIdentity
1794
1163
  }, null, 2)}
1795
1164
  `);
1796
1165
  } finally {
1797
- closeSync4(descriptor);
1166
+ closeSync3(descriptor);
1798
1167
  }
1799
1168
  return { acquired: true, lockPath: lockPath2, ownerPid: pid, processIdentity };
1800
1169
  } catch (error) {
1801
1170
  if (error.code !== "EEXIST")
1802
1171
  throw error;
1803
- const owner2 = readSupervisorLock(lockPath2);
1172
+ const observed = readLockText(lockPath2);
1173
+ const owner2 = observed === null ? null : parseSupervisorLock(observed);
1804
1174
  if (!owner2)
1805
1175
  return { acquired: false, lockPath: lockPath2 };
1806
1176
  if (isRunning(owner2.pid)) {
@@ -1817,7 +1187,10 @@ var acquireKoedServerSupervisorLock = (paths, options = {}) => {
1817
1187
  }
1818
1188
  }
1819
1189
  }
1820
- rmSync4(lockPath2, { force: true });
1190
+ exclusive(() => {
1191
+ if (readLockText(lockPath2) === observed)
1192
+ rmSync4(lockPath2, { force: true });
1193
+ });
1821
1194
  }
1822
1195
  }
1823
1196
  const owner = readSupervisorLock(lockPath2);
@@ -1836,31 +1209,168 @@ var releaseKoedServerSupervisorLock = (lock, pid = process.pid) => {
1836
1209
  };
1837
1210
 
1838
1211
  // packages/koed-server/dist/generation-lifecycle-filesystem.js
1839
- import { renameSync as renameSync3 } from "node:fs";
1840
- var renameAtomically = (source, destination) => renameSync3(source, destination);
1212
+ import { renameSync as renameSync2 } from "node:fs";
1213
+ var renameAtomically = (source, destination) => renameSync2(source, destination);
1214
+
1215
+ // packages/koed-server/dist/stopped-runtime.js
1216
+ import { spawnSync as spawnSync2 } from "node:child_process";
1217
+ import { closeSync as closeSync4, constants as constants3, fstatSync as fstatSync2, openSync as openSync4, readFileSync as readFileSync4, rmSync as rmSync5 } from "node:fs";
1218
+ import { resolve as resolve4 } from "node:path";
1219
+ var processState = (pid) => {
1220
+ try {
1221
+ process.kill(pid, 0);
1222
+ return "running";
1223
+ } catch (error) {
1224
+ return error.code === "ESRCH" ? "stopped" : "uncertain";
1225
+ }
1226
+ };
1227
+ var processSnapshot = () => {
1228
+ const result = spawnSync2("ps", ["-axww", "-o", "pid=,command="], {
1229
+ encoding: "utf8",
1230
+ timeout: 2e3,
1231
+ maxBuffer: 4 * 1024 * 1024
1232
+ });
1233
+ if (result.error || result.status !== 0 || !result.stdout.trim())
1234
+ throw new Error("Native process discovery failed.");
1235
+ return result.stdout.trim().split("\n").map((line) => {
1236
+ const match = line.trim().match(/^(\d+)\s+(.+)$/);
1237
+ if (!match)
1238
+ throw new Error("Native process discovery was incomplete.");
1239
+ return { pid: Number(match[1]), command: match[2] };
1240
+ });
1241
+ };
1242
+ var readState = (path) => {
1243
+ let descriptor;
1244
+ try {
1245
+ descriptor = openSync4(path, constants3.O_RDONLY | constants3.O_NOFOLLOW | constants3.O_NONBLOCK);
1246
+ } catch (error) {
1247
+ if (error.code === "ENOENT")
1248
+ return null;
1249
+ throw error;
1250
+ }
1251
+ try {
1252
+ const stat = fstatSync2(descriptor);
1253
+ if (!stat.isFile() || stat.size > 1024 * 1024)
1254
+ throw new Error("Runtime state is not a bounded regular file.");
1255
+ return readFileSync4(descriptor, "utf8");
1256
+ } finally {
1257
+ closeSync4(descriptor);
1258
+ }
1259
+ };
1260
+ var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1261
+ var isPid = (value) => typeof value === "number" && Number.isSafeInteger(value) && value > 0;
1262
+ function observeStoppedRuntime(paths, dependencies = {}) {
1263
+ const stateOf = dependencies.processState ?? processState;
1264
+ const identify = dependencies.processIdentity ?? resolveProcessIdentity;
1265
+ const uncertain = (message) => ({
1266
+ state: "uncertain",
1267
+ message
1268
+ });
1269
+ const staleRecords = [];
1270
+ try {
1271
+ for (const name of ["koed-server.lock", "runtime-generation.json"]) {
1272
+ const path = name === "runtime-generation.json" ? paths.generationStatePath ?? resolve4(paths.runDir, name) : resolve4(paths.runDir, name);
1273
+ const contents = readState(path);
1274
+ if (contents === null)
1275
+ continue;
1276
+ const value = JSON.parse(contents);
1277
+ if (!isRecord(value) || !isPid(value.pid) || typeof value.processIdentity !== "string" || name === "runtime-generation.json" && !isRuntimeGenerationState(value))
1278
+ return uncertain(`${name} is unreadable or lacks process identity.`);
1279
+ const identity = identify(value.pid);
1280
+ if (identity && identity === value.processIdentity)
1281
+ return {
1282
+ state: "running",
1283
+ pid: value.pid,
1284
+ message: "Koed is running or pinned."
1285
+ };
1286
+ if (stateOf(value.pid) === "stopped") {
1287
+ staleRecords.push({ path, contents });
1288
+ continue;
1289
+ }
1290
+ return uncertain(`${name} is stale or its process identity is uncertain. Operator recovery is required.`);
1291
+ }
1292
+ const runtime = readState(paths.runtimeStatePath);
1293
+ if (runtime !== null) {
1294
+ const value = JSON.parse(runtime);
1295
+ if (!isRecord(value) || !isPid(value.pid) || value.processes !== void 0 && !isRecord(value.processes))
1296
+ return uncertain("Koed runtime process state is unreadable.");
1297
+ const pids = [
1298
+ value.pid,
1299
+ ...Object.values(value.processes ?? {})
1300
+ ];
1301
+ for (const pid of pids) {
1302
+ if (pid === 0)
1303
+ continue;
1304
+ if (!isPid(pid))
1305
+ return uncertain("Koed runtime contains an invalid process ID.");
1306
+ if (stateOf(pid) !== "stopped")
1307
+ return {
1308
+ state: "uncertain",
1309
+ pid,
1310
+ message: "A recorded Koed process is live or its identity is uncertain."
1311
+ };
1312
+ }
1313
+ }
1314
+ const postmaster = readState(resolve4(paths.postgresDataDir, "postmaster.pid"));
1315
+ if (postmaster !== null) {
1316
+ const line = postmaster.split("\n")[0];
1317
+ if (!/^-?[1-9]\d*$/.test(line) || !isPid(Math.abs(Number(line))))
1318
+ return uncertain("Postgres process state is unreadable.");
1319
+ const pid = Math.abs(Number(line));
1320
+ return {
1321
+ state: "uncertain",
1322
+ pid,
1323
+ message: "Postgres retains a process lock. Stop Postgres or complete Operator recovery before changing its runtime."
1324
+ };
1325
+ }
1326
+ const roots = [resolve4(paths.koedHome, "runtime"), paths.postgresDataDir];
1327
+ const patterns = roots.map((root) => new RegExp(`(?:^|[\\s"'])${root.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?:[/\\s"']|$)`));
1328
+ const native = (dependencies.processes ?? processSnapshot)().find(({ pid, command }) => pid !== process.pid && patterns.some((pattern) => pattern.test(command)));
1329
+ if (native)
1330
+ return {
1331
+ state: "uncertain",
1332
+ pid: native.pid,
1333
+ message: "A process still references this native runtime or Postgres data directory."
1334
+ };
1335
+ return {
1336
+ state: "stopped",
1337
+ message: "Koed and its recorded native processes are stopped.",
1338
+ ...staleRecords.length > 0 ? { staleRecords } : {}
1339
+ };
1340
+ } catch {
1341
+ return uncertain("Stopped runtime state could not be established. Inspect process state and runtime files before retrying.");
1342
+ }
1343
+ }
1344
+ function removeStaleRuntimeRecords(observation) {
1345
+ if (observation.state !== "stopped")
1346
+ return;
1347
+ for (const record of observation.staleRecords ?? [])
1348
+ if (readState(record.path) === record.contents)
1349
+ rmSync5(record.path, { force: true });
1350
+ }
1841
1351
 
1842
1352
  // packages/koed-server/dist/generation-lifecycle.js
1843
1353
  var generationStatePath = (paths) => paths.generationStatePath ?? resolve5(paths.runDir, "runtime-generation.json");
1844
1354
  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);
1355
+ var isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1356
+ 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
1357
  var readRegularFile = (path) => {
1848
- const stat = lstatSync4(path);
1358
+ const stat = lstatSync3(path);
1849
1359
  if (!stat.isFile() || stat.isSymbolicLink())
1850
1360
  throw new Error("runtime lifecycle state is not a regular file");
1851
1361
  return readFileSync5(path, "utf8");
1852
1362
  };
1853
1363
  var sameOwner = (left, right) => left.kind === right.kind && left.installationId === right.installationId;
1854
1364
  var assertDirectoryChain2 = (base, target) => {
1855
- const relativePath = relative4(resolve5(base), resolve5(target));
1856
- if (relativePath.startsWith("..") || isAbsolute4(relativePath))
1365
+ const relativePath = relative3(resolve5(base), resolve5(target));
1366
+ if (relativePath.startsWith("..") || isAbsolute3(relativePath))
1857
1367
  throw new Error("runtime lifecycle path escaped KOED_HOME");
1858
1368
  const absolute = resolve5(target);
1859
1369
  let cursor = parse2(absolute).root;
1860
- for (const part of absolute.slice(cursor.length).split(sep4).filter(Boolean)) {
1370
+ for (const part of absolute.slice(cursor.length).split(sep3).filter(Boolean)) {
1861
1371
  cursor = resolve5(cursor, part);
1862
1372
  try {
1863
- const stat = lstatSync4(cursor);
1373
+ const stat = lstatSync3(cursor);
1864
1374
  if (stat.isSymbolicLink() || !stat.isDirectory())
1865
1375
  throw new Error("runtime lifecycle path contains a symbolic link or non-directory");
1866
1376
  } catch (error) {
@@ -1881,7 +1391,7 @@ var processIsRunning2 = (pid) => {
1881
1391
  var readLockRecord = (path) => {
1882
1392
  try {
1883
1393
  const parsed = JSON.parse(readRegularFile(resolve5(path, "owner.json")));
1884
- if (!isRecord(parsed))
1394
+ if (!isRecord2(parsed))
1885
1395
  return null;
1886
1396
  const record = parsed;
1887
1397
  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 +1407,7 @@ var readLockRecord = (path) => {
1897
1407
  };
1898
1408
  var acquireLifecycleLock = (paths) => {
1899
1409
  assertDirectoryChain2(paths.koedHome, paths.runDir);
1900
- mkdirSync5(paths.runDir, { recursive: true, mode: 448 });
1410
+ mkdirSync4(paths.runDir, { recursive: true, mode: 448 });
1901
1411
  assertDirectoryChain2(paths.koedHome, paths.runDir);
1902
1412
  const path = lockPath(paths);
1903
1413
  assertDirectoryChain2(paths.koedHome, path);
@@ -1910,9 +1420,9 @@ var acquireLifecycleLock = (paths) => {
1910
1420
  token: randomBytes(32).toString("hex")
1911
1421
  };
1912
1422
  try {
1913
- mkdirSync5(path, { mode: 448 });
1423
+ mkdirSync4(path, { mode: 448 });
1914
1424
  assertDirectoryChain2(paths.koedHome, path);
1915
- writeFileSync4(resolve5(path, "owner.json"), `${JSON.stringify(record)}
1425
+ writeFileSync3(resolve5(path, "owner.json"), `${JSON.stringify(record)}
1916
1426
  `, {
1917
1427
  flag: "wx",
1918
1428
  mode: 384
@@ -1921,7 +1431,7 @@ var acquireLifecycleLock = (paths) => {
1921
1431
  } catch (error) {
1922
1432
  if (error.code !== "EEXIST")
1923
1433
  throw error;
1924
- throw new Error("runtime lifecycle is locked; stale locks require stopped-runtime operator recovery", { cause: error });
1434
+ 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
1435
  }
1926
1436
  };
1927
1437
  var releaseLifecycleLock = (paths, expected) => {
@@ -1929,11 +1439,19 @@ var releaseLifecycleLock = (paths, expected) => {
1929
1439
  const actual = readLockRecord(path);
1930
1440
  if (!actual || actual.pid !== expected.pid || actual.token !== expected.token || actual.processIdentity !== expected.processIdentity)
1931
1441
  return;
1932
- rmSync5(path, { recursive: true, force: true });
1442
+ rmSync6(path, { recursive: true, force: true });
1933
1443
  };
1444
+ function withLifecycleLock(paths, action) {
1445
+ const lock = acquireLifecycleLock(paths);
1446
+ try {
1447
+ return action();
1448
+ } finally {
1449
+ releaseLifecycleLock(paths, lock);
1450
+ }
1451
+ }
1934
1452
  var withStoreLock = async (paths, action) => {
1935
1453
  assertDirectoryChain2(paths.koedHome, paths.componentsDir);
1936
- mkdirSync5(paths.componentsDir, { recursive: true, mode: 448 });
1454
+ mkdirSync4(paths.componentsDir, { recursive: true, mode: 448 });
1937
1455
  assertDirectoryChain2(paths.koedHome, paths.componentsDir);
1938
1456
  const lockPath2 = `${paths.componentsDir}.lock`;
1939
1457
  assertDirectoryChain2(paths.koedHome, lockPath2);
@@ -1947,10 +1465,10 @@ var withStoreLock = async (paths, action) => {
1947
1465
  var readCurrentId = (paths) => {
1948
1466
  assertDirectoryChain2(paths.koedHome, paths.componentsDir);
1949
1467
  const pointerPath = resolve5(paths.componentsDir, "current.json");
1950
- if (!existsSync3(pointerPath))
1468
+ if (!existsSync2(pointerPath))
1951
1469
  return null;
1952
1470
  const value = JSON.parse(readRegularFile(pointerPath));
1953
- if (!isRecord(value))
1471
+ if (!isRecord2(value))
1954
1472
  throw new Error("current generation pointer is invalid");
1955
1473
  const pointer = value;
1956
1474
  if (Object.keys(pointer).length !== 2 || pointer.schemaVersion !== 1 || typeof pointer.generationId !== "string" || !/^[a-f0-9]{64}$/.test(pointer.generationId))
@@ -1959,20 +1477,20 @@ var readCurrentId = (paths) => {
1959
1477
  };
1960
1478
  var writeCurrentPointer = (paths, id) => {
1961
1479
  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 })}
1480
+ const temporary = resolve5(dirname2(pointer), `.current-${randomBytes(8).toString("hex")}.tmp`);
1481
+ writeFileSync3(temporary, `${JSON.stringify({ schemaVersion: 1, generationId: id })}
1964
1482
  `, { flag: "wx", mode: 384 });
1965
1483
  try {
1966
1484
  renameAtomically(temporary, pointer);
1967
1485
  } catch (error) {
1968
- rmSync5(temporary, { force: true });
1486
+ rmSync6(temporary, { force: true });
1969
1487
  throw error;
1970
1488
  }
1971
1489
  };
1972
1490
  var readPinState = (paths) => {
1973
1491
  const path = generationStatePath(paths);
1974
- assertDirectoryChain2(paths.koedHome, dirname3(path));
1975
- if (!existsSync3(path))
1492
+ assertDirectoryChain2(paths.koedHome, dirname2(path));
1493
+ if (!existsSync2(path))
1976
1494
  return null;
1977
1495
  const parsed = JSON.parse(readRegularFile(path));
1978
1496
  if (!isRuntimeGenerationState(parsed))
@@ -1989,10 +1507,10 @@ var assertNoActivePin = (paths, allowCurrentSupervisor = false) => {
1989
1507
  const identity2 = resolveProcessIdentity(pin.pid);
1990
1508
  if (identity2 === pin.processIdentity || !identity2 && processIsRunning2(pin.pid))
1991
1509
  throw new Error("runtime generation is running or pinned");
1992
- rmSync5(generationStatePath(paths), { force: true });
1510
+ rmSync6(generationStatePath(paths), { force: true });
1993
1511
  }
1994
1512
  const supervisorPath = resolve5(paths.runDir, "koed-server.lock");
1995
- if (!existsSync3(supervisorPath))
1513
+ if (!existsSync2(supervisorPath))
1996
1514
  return;
1997
1515
  const supervisor = readSupervisorLock(supervisorPath);
1998
1516
  if (!supervisor)
@@ -2019,7 +1537,7 @@ var desktopBundleRecordPath = (paths, id) => resolve5(paths.generationsDir, id,
2019
1537
  var persistDesktopBundleRecord = (paths, generation, capability) => {
2020
1538
  const root = resolve5(paths.generationsDir, generation.id);
2021
1539
  assertDirectoryChain2(paths.koedHome, root);
2022
- mkdirSync5(root, { recursive: true, mode: 448 });
1540
+ mkdirSync4(root, { recursive: true, mode: 448 });
2023
1541
  const path = desktopBundleRecordPath(paths, generation.id);
2024
1542
  const record = {
2025
1543
  schemaVersion: 1,
@@ -2031,7 +1549,7 @@ var persistDesktopBundleRecord = (paths, generation, capability) => {
2031
1549
  resourcesPath: capability.resourcesPath
2032
1550
  };
2033
1551
  try {
2034
- writeFileSync4(path, `${JSON.stringify(record)}
1552
+ writeFileSync3(path, `${JSON.stringify(record)}
2035
1553
  `, {
2036
1554
  flag: "wx",
2037
1555
  mode: 384
@@ -2040,7 +1558,7 @@ var persistDesktopBundleRecord = (paths, generation, capability) => {
2040
1558
  if (error.code !== "EEXIST")
2041
1559
  throw error;
2042
1560
  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)
1561
+ 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
1562
  throw new Error("private Desktop bundle generation record is invalid", {
2045
1563
  cause: error
2046
1564
  });
@@ -2051,7 +1569,7 @@ var readDesktopBundleGenerationById = async (paths, id, capability) => {
2051
1569
  if (generation.id !== id)
2052
1570
  throw new Error("runtime owner mismatch");
2053
1571
  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)
1572
+ 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.resourcesPath || !isRecord2(record.owner) || record.owner.kind !== generation.owner.kind || record.owner.installationId !== generation.owner.installationId)
2055
1573
  throw new Error("private Desktop bundle generation record is invalid");
2056
1574
  return generation;
2057
1575
  };
@@ -2092,7 +1610,7 @@ var readOrderingJournalFile = (path) => {
2092
1610
  const bytes = Buffer.alloc(stat.size + 1);
2093
1611
  let length = 0;
2094
1612
  while (length < bytes.length) {
2095
- const count = readSync2(descriptor, bytes, length, bytes.length - length, null);
1613
+ const count = readSync(descriptor, bytes, length, bytes.length - length, null);
2096
1614
  if (count === 0)
2097
1615
  break;
2098
1616
  length += count;
@@ -2106,11 +1624,11 @@ var readOrderingJournalFile = (path) => {
2106
1624
  };
2107
1625
  var readDesktopOrderingJournal = (paths, id) => {
2108
1626
  const bundlePath = desktopBundleRecordPath(paths, id);
2109
- const hasBundle = existsSync3(bundlePath);
1627
+ const hasBundle = existsSync2(bundlePath);
2110
1628
  if (hasBundle)
2111
- assertDirectoryChain2(paths.koedHome, dirname3(bundlePath));
1629
+ assertDirectoryChain2(paths.koedHome, dirname2(bundlePath));
2112
1630
  const record = hasBundle ? JSON.parse(readOrderingJournalFile(bundlePath)) : readGenerationRecord(paths, id);
2113
- if (!isRecord(record))
1631
+ if (!isRecord2(record))
2114
1632
  throw new Error("generation record is invalid");
2115
1633
  if (record.kind !== "desktop-bundle" && record.kind !== "desktop-bundle-with-privacy")
2116
1634
  return null;
@@ -2137,20 +1655,20 @@ function validateDesktopOrderingJournal(record, id) {
2137
1655
  "resourcesPath",
2138
1656
  ...privacy ? ["privacy"] : []
2139
1657
  ];
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))
1658
+ 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
1659
  throw new Error("private Desktop bundle generation record is invalid");
2142
1660
  if (privacy)
2143
1661
  validateDesktopPrivacyJournal(record, id);
2144
- else if (createHash4("sha256").update(`${record.owner.installationId}
1662
+ else if (createHash3("sha256").update(`${record.owner.installationId}
2145
1663
  ${record.bundleDigest}`).digest("hex") !== id)
2146
1664
  throw new Error("Desktop bundle generation identity mismatch");
2147
1665
  }
2148
1666
  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))
1667
+ 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
1668
  throw new Error("private Desktop privacy journal is invalid");
2151
1669
  const identity = { ...record };
2152
1670
  delete identity.id;
2153
- if (createHash4("sha256").update(canonicalArtifactJson(identity)).digest("hex") !== id)
1671
+ if (createHash3("sha256").update(canonicalArtifactJson(identity)).digest("hex") !== id)
2154
1672
  throw new Error("Desktop privacy generation digest mismatch");
2155
1673
  }
2156
1674
  function readCurrentDesktopGenerationOrderingEvidence(paths, capability) {
@@ -2166,13 +1684,50 @@ function readCurrentDesktopGenerationOrderingEvidence(paths, capability) {
2166
1684
  return evidence;
2167
1685
  }
2168
1686
  async function readCurrentRuntimeOwner(paths) {
2169
- if (!existsSync3(resolve5(paths.componentsDir, "current.json")))
1687
+ if (!existsSync2(resolve5(paths.componentsDir, "current.json")))
2170
1688
  return null;
2171
1689
  const id = readCurrentId(paths);
2172
1690
  if (!id)
2173
1691
  return null;
2174
1692
  return (await Promise.resolve(readDesktopOrderingJournal(paths, id) ?? readGenerationOrderingEvidence(paths, id))).owner;
2175
1693
  }
1694
+ function withSourceNativeStartLock(paths, check) {
1695
+ const lock = acquireLifecycleLock(paths);
1696
+ try {
1697
+ const owner = readSupervisorLock(resolve5(paths.runDir, "koed-server.lock"));
1698
+ if (!owner || owner.pid !== process.pid || !owner.processIdentity || owner.processIdentity !== resolveProcessIdentity(process.pid))
1699
+ throw new Error("Source native selection requires the active supervisor lock.");
1700
+ return check();
1701
+ } finally {
1702
+ releaseLifecycleLock(paths, lock);
1703
+ }
1704
+ }
1705
+ async function withStoppedRuntime(paths, requester, action) {
1706
+ const lock = acquireLifecycleLock(paths);
1707
+ try {
1708
+ assertDirectoryChain2(paths.koedHome, paths.postgresDataDir);
1709
+ assertDirectoryChain2(paths.koedHome, dirname2(paths.runtimeStatePath));
1710
+ assertDirectoryChain2(paths.koedHome, dirname2(generationStatePath(paths)));
1711
+ assertDirectoryChain2(paths.koedHome, paths.componentsDir);
1712
+ try {
1713
+ if (!lstatSync3(resolve5(paths.componentsDir, "current.json")).isFile())
1714
+ throw new Error("current generation pointer is not a regular file");
1715
+ } catch (error) {
1716
+ if (error.code !== "ENOENT")
1717
+ throw error;
1718
+ }
1719
+ const owner = await readCurrentRuntimeOwner(paths);
1720
+ if (owner)
1721
+ assertOwner({ owner }, requester);
1722
+ const observation = observeStoppedRuntime(paths);
1723
+ if (observation.state !== "stopped")
1724
+ throw new Error(`${observation.message} Run koed stop before retrying. Stale or unreadable locks require stopped-runtime Operator recovery.`);
1725
+ removeStaleRuntimeRecords(observation);
1726
+ return await action();
1727
+ } finally {
1728
+ releaseLifecycleLock(paths, lock);
1729
+ }
1730
+ }
2176
1731
  var persistPinState = (paths, generation, requester, lock, source = "manifest-pinned-store") => {
2177
1732
  const processIdentity = resolveProcessIdentity(process.pid);
2178
1733
  if (!processIdentity)
@@ -2188,14 +1743,14 @@ var persistPinState = (paths, generation, requester, lock, source = "manifest-pi
2188
1743
  ...source === "desktop-bundle" ? { source } : {}
2189
1744
  };
2190
1745
  const path = generationStatePath(paths);
2191
- mkdirSync5(dirname3(path), { recursive: true, mode: 448 });
1746
+ mkdirSync4(dirname2(path), { recursive: true, mode: 448 });
2192
1747
  const temporary = `${path}.${lock.token}.tmp`;
2193
- writeFileSync4(temporary, `${JSON.stringify(state)}
1748
+ writeFileSync3(temporary, `${JSON.stringify(state)}
2194
1749
  `, {
2195
1750
  flag: "wx",
2196
1751
  mode: 384
2197
1752
  });
2198
- renameSync4(temporary, path);
1753
+ renameSync3(temporary, path);
2199
1754
  return { path, processIdentity };
2200
1755
  };
2201
1756
  var createPinRelease = (paths, lock, pinPath, processIdentity) => {
@@ -2207,7 +1762,7 @@ var createPinRelease = (paths, lock, pinPath, processIdentity) => {
2207
1762
  try {
2208
1763
  const current = readPinState(paths);
2209
1764
  if (current?.pinToken === lock.token && current.processIdentity === processIdentity)
2210
- rmSync5(pinPath, { force: true });
1765
+ rmSync6(pinPath, { force: true });
2211
1766
  } finally {
2212
1767
  releaseLifecycleLock(paths, lock);
2213
1768
  }
@@ -2223,6 +1778,13 @@ function readDesktopBundleGeneration(paths, capability) {
2223
1778
  const generation = desktopBundleGeneration(currentCapability, owner);
2224
1779
  return Promise.resolve(generation);
2225
1780
  }
1781
+ async function stageDesktopBundleForRecovery(paths, capability) {
1782
+ return withStoreLock(paths, async () => {
1783
+ const generation = await readDesktopBundleGeneration(paths, capability);
1784
+ persistDesktopBundleRecord(paths, generation, capability);
1785
+ return generation;
1786
+ });
1787
+ }
2226
1788
  async function pinDesktopBundleGenerationForStart(paths, capability) {
2227
1789
  if (!validateDesktopRuntimeCapability(capability))
2228
1790
  throw new Error("validated private Desktop runtime capability is required");
@@ -2261,7 +1823,7 @@ async function pinDesktopBundleGenerationForStart(paths, capability) {
2261
1823
  }
2262
1824
  var desktopBundleGeneration = (capability, owner) => {
2263
1825
  const manifest = capability.manifest;
2264
- const id = createHash4("sha256").update(`${owner.installationId}
1826
+ const id = createHash3("sha256").update(`${owner.installationId}
2265
1827
  ${capability.bundleDigest}`).digest("hex");
2266
1828
  return {
2267
1829
  id,
@@ -2320,7 +1882,7 @@ var listOwnedGenerations = async (paths, requester) => {
2320
1882
  assertDirectoryChain2(paths.koedHome, paths.generationsDir);
2321
1883
  let entries;
2322
1884
  try {
2323
- entries = readdirSync4(paths.generationsDir, { withFileTypes: true });
1885
+ entries = readdirSync3(paths.generationsDir, { withFileTypes: true });
2324
1886
  } catch (error) {
2325
1887
  if (error.code === "ENOENT")
2326
1888
  return [];
@@ -2350,7 +1912,7 @@ var removeUnretainedGenerations = (generations, retain, currentId) => {
2350
1912
  for (const entry of generations) {
2351
1913
  if (kept.has(entry.id))
2352
1914
  continue;
2353
- rmSync5(entry.path, { recursive: true, force: true });
1915
+ rmSync6(entry.path, { recursive: true, force: true });
2354
1916
  removed.push(entry.id);
2355
1917
  }
2356
1918
  return removed;
@@ -2375,10 +1937,9 @@ async function cleanupGenerations(paths, retain, requester) {
2375
1937
  }
2376
1938
 
2377
1939
  export {
2378
- resolveKoedServerConfig,
2379
- writeCodexGlobalMemoryGuidancePreference,
2380
1940
  validateDesktopRuntimeCapability,
2381
1941
  resolveDesktopRuntimeOwner,
1942
+ fetchBounded,
2382
1943
  discoverActualRuntimeIdentity,
2383
1944
  resolveComponentManifestPinTarget,
2384
1945
  stageComponent,
@@ -2390,13 +1951,22 @@ export {
2390
1951
  readSupervisorLock,
2391
1952
  acquireKoedServerSupervisorLock,
2392
1953
  releaseKoedServerSupervisorLock,
1954
+ renameAtomically,
1955
+ observeStoppedRuntime,
1956
+ removeStaleRuntimeRecords,
1957
+ assertDirectoryChain2 as assertDirectoryChain,
1958
+ withLifecycleLock,
2393
1959
  readCurrentGenerationOrderingEvidence,
2394
1960
  readCurrentGeneration,
1961
+ readDesktopGenerationForCapability,
2395
1962
  readCurrentDesktopGeneration,
2396
1963
  readCurrentGenerationForOwner,
2397
1964
  readCurrentDesktopGenerationOrderingEvidence,
2398
1965
  readCurrentRuntimeOwner,
1966
+ withSourceNativeStartLock,
1967
+ withStoppedRuntime,
2399
1968
  readDesktopBundleGeneration,
1969
+ stageDesktopBundleForRecovery,
2400
1970
  pinDesktopBundleGenerationForStart,
2401
1971
  pinGenerationForStart,
2402
1972
  activateGeneration,