@adea-ai/app-framework 0.27.0 → 0.28.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (118) hide show
  1. package/README.md +177 -15
  2. package/dist/app/create-application.d.ts +2 -0
  3. package/dist/app/create-application.js +6 -0
  4. package/dist/app/service-registry.js +4 -0
  5. package/dist/appearance/custom-theme-import.js +43 -7
  6. package/dist/appearance/custom-theme-library.d.ts +2 -0
  7. package/dist/appearance/custom-theme-library.js +5 -1
  8. package/dist/appearance/theme-record-adapter.js +4 -2
  9. package/dist/appearance/theme-registry.js +7 -1
  10. package/dist/cli/create-application-cli.js +4 -2
  11. package/dist/cli/update-helper-cli.js +28 -6
  12. package/dist/desktop/client-asset-manifest.d.ts +47 -0
  13. package/dist/desktop/client-asset-manifest.js +114 -0
  14. package/dist/desktop/client-asset-stream.d.ts +10 -0
  15. package/dist/desktop/client-asset-stream.js +138 -33
  16. package/dist/desktop/client-assets.d.ts +20 -0
  17. package/dist/desktop/client-assets.js +132 -22
  18. package/dist/desktop/client-response-lifecycle.d.ts +22 -0
  19. package/dist/desktop/client-response-lifecycle.js +233 -0
  20. package/dist/desktop/desktop-host.d.ts +40 -2
  21. package/dist/desktop/desktop-host.js +159 -9
  22. package/dist/framework-source.json +1 -1
  23. package/dist/installer/command-artifact.d.ts +4 -2
  24. package/dist/installer/command-artifact.js +119 -19
  25. package/dist/installer/linux-process-group.d.ts +13 -0
  26. package/dist/installer/linux-process-group.js +58 -0
  27. package/dist/native/darwin-sync.d.ts +7 -0
  28. package/dist/native/darwin-sync.js +43 -0
  29. package/dist/native/desktop-build-hook.js +7 -0
  30. package/dist/native/directory-exchange.d.ts +10 -0
  31. package/dist/native/directory-exchange.js +90 -0
  32. package/dist/native/electrobun-source-patch.d.ts +5 -0
  33. package/dist/native/electrobun-source-patch.js +19 -1
  34. package/dist/native/posix-launcher-build.d.ts +24 -0
  35. package/dist/native/posix-launcher-build.js +232 -0
  36. package/dist/native/posix-tree-removal.d.ts +36 -0
  37. package/dist/native/posix-tree-removal.js +425 -0
  38. package/dist/update-helper.bundle.js +1483 -105
  39. package/dist/updates/channel-update-manager.d.ts +5 -0
  40. package/dist/updates/channel-update-manager.js +13 -1
  41. package/dist/updates/desktop-updater.d.ts +78 -2
  42. package/dist/updates/desktop-updater.js +320 -37
  43. package/dist/updates/launch-environment.d.ts +2 -0
  44. package/dist/updates/launch-environment.js +4 -0
  45. package/dist/updates/native-file-lock.d.ts +15 -0
  46. package/dist/updates/native-file-lock.js +189 -0
  47. package/dist/updates/packaged-launch-admission.d.ts +13 -0
  48. package/dist/updates/packaged-launch-admission.js +45 -0
  49. package/dist/updates/packaged-release-config.d.ts +18 -0
  50. package/dist/updates/packaged-release-config.js +60 -0
  51. package/dist/updates/packaged-update-startup.d.ts +44 -0
  52. package/dist/updates/packaged-update-startup.js +81 -0
  53. package/dist/updates/update-arm.d.ts +9 -8
  54. package/dist/updates/update-arm.js +227 -62
  55. package/dist/updates/update-cleanup-error.d.ts +23 -0
  56. package/dist/updates/update-cleanup-error.js +65 -0
  57. package/dist/updates/update-download-cleanup.d.ts +11 -0
  58. package/dist/updates/update-download-cleanup.js +112 -2
  59. package/dist/updates/update-download-lock.d.ts +20 -0
  60. package/dist/updates/update-download-lock.js +73 -0
  61. package/dist/updates/update-download.d.ts +2 -0
  62. package/dist/updates/update-download.js +7 -3
  63. package/dist/updates/update-generation-lease.d.ts +6 -0
  64. package/dist/updates/update-generation-lease.js +14 -0
  65. package/dist/updates/update-helper.d.ts +11 -2
  66. package/dist/updates/update-helper.js +322 -13
  67. package/dist/updates/update-inherited-launch-lease.d.ts +22 -0
  68. package/dist/updates/update-inherited-launch-lease.js +58 -0
  69. package/dist/updates/update-instance-lease.d.ts +15 -0
  70. package/dist/updates/update-instance-lease.js +25 -0
  71. package/dist/updates/update-launch-gate.d.ts +137 -0
  72. package/dist/updates/update-launch-gate.js +617 -0
  73. package/dist/updates/update-launch.js +3 -1
  74. package/dist/updates/update-lock.d.ts +12 -0
  75. package/dist/updates/update-lock.js +18 -0
  76. package/dist/updates/update-manager.d.ts +2 -0
  77. package/dist/updates/update-manager.js +9 -2
  78. package/dist/updates/update-marker.d.ts +7 -0
  79. package/dist/updates/update-marker.js +62 -0
  80. package/dist/updates/update-preflight-error.d.ts +7 -0
  81. package/dist/updates/update-preflight-error.js +11 -0
  82. package/dist/updates/update-process-fence.d.ts +4 -0
  83. package/dist/updates/update-process-fence.js +85 -73
  84. package/dist/updates/update-process-liveness.d.ts +2 -0
  85. package/dist/updates/update-process-liveness.js +11 -0
  86. package/dist/updates/update-resume.d.ts +37 -3
  87. package/dist/updates/update-resume.js +839 -23
  88. package/dist/updates/update-retention-marker.d.ts +67 -0
  89. package/dist/updates/update-retention-marker.js +165 -0
  90. package/dist/updates/update-retention-plan.d.ts +25 -0
  91. package/dist/updates/update-retention-plan.js +54 -0
  92. package/dist/updates/update-retention-sync.d.ts +34 -0
  93. package/dist/updates/update-retention-sync.js +83 -0
  94. package/dist/updates/update-retirement.d.ts +205 -0
  95. package/dist/updates/update-retirement.js +1485 -0
  96. package/dist/updates/update-shutdown.d.ts +16 -4
  97. package/dist/updates/update-shutdown.js +133 -8
  98. package/dist/updates/update-state-store.d.ts +58 -0
  99. package/dist/updates/update-state-store.js +139 -0
  100. package/dist/updates/update-swap-stage.d.ts +1 -1
  101. package/dist/updates/update-swap-stage.js +85 -14
  102. package/dist/updates/update-swap.d.ts +45 -2
  103. package/dist/updates/update-swap.js +207 -17
  104. package/package.json +31 -1
  105. package/src/appearance/custom-theme-import.ts +96 -14
  106. package/src/appearance/custom-theme-library.ts +5 -0
  107. package/src/appearance/theme-record-adapter.ts +15 -6
  108. package/src/appearance/theme-registry.ts +8 -1
  109. package/src/desktop/client-asset-manifest.ts +207 -0
  110. package/src/desktop/client-asset-stream.ts +193 -32
  111. package/src/desktop/client-assets.ts +210 -19
  112. package/src/desktop/client-response-lifecycle.ts +305 -0
  113. package/src/native/electrobun-posix-launch-lease.patch +398 -0
  114. package/templates/application/README.md +50 -0
  115. package/templates/application/electrobun.config.ts +5 -1
  116. package/templates/application/scripts/build-desktop.ts +4 -0
  117. package/templates/application/src/bun/index.ts +173 -16
  118. package/templates/application/vite.config.ts +112 -6
@@ -0,0 +1,73 @@
1
+ import { tryAcquireNativeFileLock } from "./native-file-lock.js";
2
+ // src/updates/update-download-lock.ts
3
+ var ROOT_LOCK_TIMEOUT_MS = 12e4;
4
+ var localQueues = /* @__PURE__ */ new Map();
5
+ /**
6
+ * Serialize creation and reclamation inside one versioned download root,
7
+ * across processes (a persistent native file lock beside the root) and within
8
+ * this JS process (a queue, so overlapping async callers wait instead of
9
+ * polling the OS lock). Every lease file is opened, released for reclamation
10
+ * and removed only while this gate is held, so removing a lease file cannot
11
+ * race another process opening it.
12
+ */
13
+ async function withUpdateDownloadRootLock(root, operation) {
14
+ const lockPath = `${root}.lock`;
15
+ const releaseLocal = await acquireLocalQueue(normalizeIdentity(lockPath));
16
+ try {
17
+ const lock = await acquireWithin(lockPath, ROOT_LOCK_TIMEOUT_MS);
18
+ try {
19
+ return await operation();
20
+ } finally {
21
+ await lock.release();
22
+ }
23
+ } finally {
24
+ releaseLocal();
25
+ }
26
+ }
27
+ /**
28
+ * Hold a process-owned lease for one download until it is staged or
29
+ * discarded. A process crash releases the OS lock, which is how startup
30
+ * distinguishes an abandoned download from a live one. With `tryOnly`, an
31
+ * existing owner returns undefined instead of waiting.
32
+ */
33
+ async function acquireUpdateDownloadLease(directory, tryOnly = false) {
34
+ const lockPath = `${directory}.lease`;
35
+ const lock = tryOnly ? await tryAcquireNativeFileLock(lockPath, "exclusive") : await acquireWithin(lockPath, ROOT_LOCK_TIMEOUT_MS);
36
+ if (!lock) return void 0;
37
+ let released = false;
38
+ return {
39
+ lockPath,
40
+ async release() {
41
+ if (released) return;
42
+ released = true;
43
+ await lock.release();
44
+ }
45
+ };
46
+ }
47
+ async function acquireWithin(path, timeoutMs) {
48
+ const deadline = Date.now() + timeoutMs;
49
+ while (true) {
50
+ const lock = await tryAcquireNativeFileLock(path, "exclusive");
51
+ if (lock) return lock;
52
+ if (Date.now() >= deadline) throw new Error("Update download lock timed out");
53
+ await Bun.sleep(25);
54
+ }
55
+ }
56
+ function normalizeIdentity(identity) {
57
+ return process.platform === "win32" ? identity.replace(/[\\/]+/g, "\\").toLowerCase() : identity;
58
+ }
59
+ async function acquireLocalQueue(key) {
60
+ const previous = localQueues.get(key);
61
+ let unlock;
62
+ const current = new Promise((resolve) => unlock = resolve);
63
+ localQueues.set(key, current);
64
+ await previous;
65
+ let released = false;
66
+ return () => {
67
+ if (released) return;
68
+ released = true;
69
+ unlock();
70
+ if (localQueues.get(key) === current) localQueues.delete(key);
71
+ };
72
+ }
73
+ export { acquireUpdateDownloadLease, withUpdateDownloadRootLock };
@@ -8,6 +8,8 @@ export declare function downloadVerifiedRelease(options: {
8
8
  timeoutMs?: number;
9
9
  signal?: AbortSignal;
10
10
  fetch?: FetchFunction;
11
+ /** Allocate an already-owned private directory when cross-process cleanup is required. */
12
+ createTemporaryDirectory?: (root: string) => Promise<string>;
11
13
  }): Promise<{
12
14
  path: string;
13
15
  directory: string;
@@ -1,7 +1,7 @@
1
1
  import { isVerifiedRelease, verifyReleaseStream } from "./signed-release.js";
2
2
  import { fetchReleaseLocation } from "./release-location.js";
3
- import { mkdtemp, open, rm } from "node:fs/promises";
4
- import { join, resolve } from "node:path";
3
+ import { mkdtemp, open, realpath, rm } from "node:fs/promises";
4
+ import { basename, dirname, join, resolve } from "node:path";
5
5
  // src/updates/update-download.ts
6
6
  /** Download an authenticated release to a new private directory; caller owns cleanup and installation. */
7
7
  async function downloadVerifiedRelease(options) {
@@ -23,7 +23,11 @@ async function downloadVerifiedRelease(options) {
23
23
  const body = response.body;
24
24
  const length = response.headers.get("content-length");
25
25
  if (length !== null && (!/^\d+$/.test(length) || Number(length) !== descriptor.asset.size)) throw new Error("Release download size mismatch");
26
- temporary = await mkdtemp(join(resolve(options.directory), "framework-update-"));
26
+ const root = options.createTemporaryDirectory ? await realpath(resolve(options.directory)) : resolve(options.directory);
27
+ const allocated = options.createTemporaryDirectory ? await options.createTemporaryDirectory(root) : await mkdtemp(join(root, "framework-update-"));
28
+ const temporaryDirectory = resolve(allocated);
29
+ if (dirname(temporaryDirectory) !== root || !basename(temporaryDirectory).startsWith("framework-update-")) throw new Error("Invalid update download directory");
30
+ temporary = temporaryDirectory;
27
31
  const path = join(temporary, "archive");
28
32
  const file = await open(path, "wx", 384);
29
33
  try {
@@ -0,0 +1,6 @@
1
+ /** A persistent lock outside the retained tree; never remove or replace it. */
2
+ export declare function updateGenerationLeasePath(target: string, generation: string): string;
3
+ /** Shared readers and future exclusive cleanup must use this same persistent lock. */
4
+ export declare function tryAcquireUpdateGenerationLease(target: string, generation: string, mode: 'shared' | 'exclusive'): Promise<Readonly<{
5
+ release(): Promise<void>;
6
+ }> | undefined>;
@@ -0,0 +1,14 @@
1
+ import { tryAcquireNativeFileLock } from "./native-file-lock.js";
2
+ import { basename, dirname, isAbsolute, join, resolve } from "node:path";
3
+ // src/updates/update-generation-lease.ts
4
+ var UUID = /^[0-9a-f]{8}-[0-9a-f-]{27}$/i;
5
+ /** A persistent lock outside the retained tree; never remove or replace it. */
6
+ function updateGenerationLeasePath(target, generation) {
7
+ if (typeof target !== "string" || !isAbsolute(target) || resolve(target) !== target || target.includes("\0") || typeof generation !== "string" || !UUID.test(generation)) throw new Error("Invalid update generation lease identity");
8
+ return join(dirname(target), `.${basename(target)}.framework-generation-${generation.toLowerCase()}.lock`);
9
+ }
10
+ /** Shared readers and future exclusive cleanup must use this same persistent lock. */
11
+ function tryAcquireUpdateGenerationLease(target, generation, mode) {
12
+ return tryAcquireNativeFileLock(updateGenerationLeasePath(target, generation), mode);
13
+ }
14
+ export { tryAcquireUpdateGenerationLease, updateGenerationLeasePath };
@@ -1,7 +1,7 @@
1
1
  import type { InstallerPlatform } from '../installer/installer-layout';
2
2
  /** Everything the post-exit helper needs, written by the app into its private staging directory. */
3
3
  export type UpdateHelperRequest = Readonly<{
4
- schema: 1;
4
+ schema: 1 | 2 | 3;
5
5
  target: string;
6
6
  platform: InstallerPlatform;
7
7
  version: string;
@@ -10,9 +10,15 @@ export type UpdateHelperRequest = Readonly<{
10
10
  executable: string;
11
11
  }>[];
12
12
  processTimeoutMs: number;
13
+ generation?: string;
14
+ helperOwner?: string;
13
15
  }>;
16
+ /** Return whether a staging directory contains artifacts from a helper handoff. */
17
+ export declare function hasUpdateHelperArtifacts(staging: string): Promise<boolean>;
14
18
  /** Validate a helper request's shape. */
15
19
  export declare function parseUpdateHelperRequest(value: unknown): UpdateHelperRequest;
20
+ /** Return false only when the path is absent; surface permission and path errors. */
21
+ export declare function updatePathExists(path: string): Promise<boolean>;
16
22
  /**
17
23
  * The post-exit helper: wait for the app's processes to exit, swap in the
18
24
  * staged candidate, record the new version and relaunch the app. Run from a
@@ -20,5 +26,8 @@ export declare function parseUpdateHelperRequest(value: unknown): UpdateHelperRe
20
26
  */
21
27
  export declare function runUpdateHelper(options: {
22
28
  staging: string;
29
+ target?: string;
30
+ generation?: string;
31
+ helperOwner?: string;
23
32
  env?: Record<string, string | undefined>;
24
- }): Promise<'updated' | 'failed'>;
33
+ }): Promise<'updated' | 'failed' | 'cancelled'>;
@@ -1,18 +1,38 @@
1
- import { swapUpdateTree, updateStagingFor } from "./update-swap.js";
1
+ import { acquireUpdateLock, readUpdateStageState, writeUpdateStageState, writeUpdateStageStateDurably } from "./update-state-store.js";
2
+ import { readUpdateTreeDigest, readUpdateTreeIdentity, readUpdateTreeVersion, sameUpdateTreeDigest, sameUpdateTreeIdentity, swapUpdateTreeWhileLocked, syncUpdateTree, syncUpdateTreeParent, updateStagingFor } from "./update-swap.js";
3
+ import { publishExclusiveUpdateMarker, publishExclusiveUpdateMarkerSync, readUpdateMarker } from "./update-marker.js";
2
4
  import { launchInstalledApp } from "./update-launch.js";
3
- import { waitForUpdateProcesses } from "./update-process-fence.js";
4
- import { lstat, open, writeFile } from "node:fs/promises";
5
+ import { UpdateProcessFenceCancelledError, waitForUpdateProcesses } from "./update-process-fence.js";
6
+ import { cancelUpdateLaunchGateBeforeTransition, publishUpdateLaunchGate, tryAcquireUpdateHelperLiveness, waitForUpdateLaunchGateWriter } from "./update-launch-gate.js";
7
+ import { lstat, open, realpath } from "node:fs/promises";
5
8
  import { isAbsolute, join, resolve } from "node:path";
6
- import { constants as constants$1, writeFileSync } from "node:fs";
9
+ import { constants as constants$1 } from "node:fs";
7
10
  // src/updates/update-helper.ts
11
+ /** Return whether a staging directory contains artifacts from a helper handoff. */
12
+ async function hasUpdateHelperArtifacts(staging) {
13
+ for (const name of [
14
+ "request.json",
15
+ "helper-armed",
16
+ "helper-ready",
17
+ "cancel.json",
18
+ "cancel-ack.json",
19
+ "helper"
20
+ ]) try {
21
+ await lstat(join(staging, name));
22
+ return true;
23
+ } catch (error) {
24
+ if (error.code !== "ENOENT") throw error;
25
+ }
26
+ return false;
27
+ }
8
28
  /** Validate a helper request's shape. */
9
29
  function parseUpdateHelperRequest(value) {
10
30
  const data = value;
11
- if (typeof value !== "object" || value === null || Array.isArray(value) || data.schema !== 1 || typeof data.target !== "string" || !isAbsolute(data.target) || resolve(data.target) !== data.target || ![
31
+ if (typeof value !== "object" || value === null || Array.isArray(value) || data.schema !== 1 && data.schema !== 2 && data.schema !== 3 || typeof data.target !== "string" || !isAbsolute(data.target) || resolve(data.target) !== data.target || ![
12
32
  "macos-arm64",
13
33
  "windows-x64",
14
34
  "linux-x64"
15
- ].includes(data.platform) || typeof data.version !== "string" || !/^\d+\.\d+\.\d+(?:-dev\.\d+)?$/.test(data.version) || !Array.isArray(data.processes) || !Number.isSafeInteger(data.processTimeoutMs) || data.processTimeoutMs < 1 || data.processTimeoutMs > 12e4) throw new Error("Invalid update helper request");
35
+ ].includes(data.platform) || typeof data.version !== "string" || !/^\d+\.\d+\.\d+(?:-dev\.\d+)?$/.test(data.version) || !Array.isArray(data.processes) || data.schema === 2 && (typeof data.generation !== "string" || !/^[0-9a-f-]{36}$/i.test(data.generation) || data.helperOwner !== void 0 && (typeof data.helperOwner !== "string" || !/^[0-9a-f-]{36}$/i.test(data.helperOwner))) || data.schema === 3 && (typeof data.generation !== "string" || !/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(data.generation) || typeof data.helperOwner !== "string" || !/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(data.helperOwner)) || !Number.isSafeInteger(data.processTimeoutMs) || data.processTimeoutMs < 1 || data.processTimeoutMs > 12e4) throw new Error("Invalid update helper request");
16
36
  return Object.freeze(data);
17
37
  }
18
38
  async function readRequest(staging) {
@@ -25,32 +45,321 @@ async function readRequest(staging) {
25
45
  await file.close();
26
46
  }
27
47
  }
48
+ async function cancellationRequested(staging, generation, helperOwner) {
49
+ const value = await readUpdateMarker(staging, "cancel.json");
50
+ if (!value) return false;
51
+ if (value.schema !== 1 || value.generation !== generation || value.helperOwner !== helperOwner) throw new Error("Update helper cancellation request does not match its generation");
52
+ return true;
53
+ }
54
+ async function acknowledgeUpdateCancellation(staging, request) {
55
+ if (request.schema !== 2 && request.schema !== 3 || !request.generation || !request.helperOwner) throw new Error("Update helper cancellation owner is unavailable");
56
+ const current = await readUpdateStageState(staging);
57
+ if (!current || current.phase !== "armed" || current.helperPid !== process.pid || current.generation !== request.generation || request.schema === 3 && current.helperOwner !== request.helperOwner || request.schema === 3 && !current.launchGateOwner || !await cancellationRequested(staging, request.generation, request.helperOwner)) throw new Error("Update helper cannot acknowledge a cancellation it no longer owns");
58
+ await publishExclusiveUpdateMarker(staging, "cancel-ack.json", {
59
+ schema: 1,
60
+ generation: request.generation,
61
+ helperOwner: request.helperOwner,
62
+ ...request.schema === 3 ? { launchGateOwner: current.launchGateOwner } : {}
63
+ });
64
+ }
65
+ /** Return false only when the path is absent; surface permission and path errors. */
66
+ async function updatePathExists(path) {
67
+ try {
68
+ await lstat(path);
69
+ return true;
70
+ } catch (error) {
71
+ if (error.code === "ENOENT") return false;
72
+ throw error;
73
+ }
74
+ }
28
75
  /**
29
76
  * The post-exit helper: wait for the app's processes to exit, swap in the
30
77
  * staged candidate, record the new version and relaunch the app. Run from a
31
78
  * copy outside the install tree; `armUpdateHelper` prepares that copy.
32
79
  */
33
80
  async function runUpdateHelper(options) {
81
+ if (options.target !== void 0 || options.generation !== void 0 || options.helperOwner !== void 0) {
82
+ if (typeof options.target !== "string" || !isAbsolute(options.target) || resolve(options.target) !== options.target || options.target.includes("\0") || !isAbsolute(options.staging) || resolve(options.staging) !== options.staging || options.staging.includes("\0") || updateStagingFor(options.target) !== options.staging || typeof options.generation !== "string" || !/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(options.generation) || typeof options.helperOwner !== "string" || !/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(options.helperOwner)) throw new Error("Invalid update helper invocation");
83
+ const liveness = await tryAcquireUpdateHelperLiveness(options.target);
84
+ if (!liveness) throw new Error("Update helper liveness is already owned");
85
+ try {
86
+ const stagingInfo = await lstat(options.staging);
87
+ if (!stagingInfo.isDirectory() || stagingInfo.isSymbolicLink() || await realpath(options.staging) !== options.staging) throw new Error("Invalid update staging directory");
88
+ const request = await readRequest(options.staging);
89
+ if (request.schema !== 3 || request.target !== options.target || request.generation !== options.generation || request.helperOwner !== options.helperOwner) throw new Error("Update helper request does not match its command-line owner");
90
+ return await runUpdateHelperWithRequest(options, request, {
91
+ target: options.target,
92
+ generation: options.generation,
93
+ helperOwner: options.helperOwner
94
+ }, liveness);
95
+ } finally {
96
+ await liveness.release();
97
+ }
98
+ }
34
99
  const request = await readRequest(options.staging);
100
+ if (request.schema === 3) throw new Error("Schema 3 update helper requires command-line ownership binding");
101
+ return runUpdateHelperWithRequest(options, request);
102
+ }
103
+ async function runUpdateHelperWithRequest(options, request, binding, helperLiveness) {
35
104
  if (updateStagingFor(request.target) !== options.staging) throw new Error("Update helper request does not match its staging directory");
105
+ if (binding && (request.target !== binding.target || request.generation !== binding.generation || request.helperOwner !== binding.helperOwner)) throw new Error("Update helper request does not match its command-line owner");
106
+ if (request.schema === 3) {
107
+ if (!binding || !helperLiveness) throw new Error("Schema 3 update helper requires liveness-bound gate ownership");
108
+ return runSchema3UpdateHelper(options, request, helperLiveness);
109
+ }
110
+ const lock = await acquireUpdateLock(request.target);
111
+ let state;
112
+ try {
113
+ state = await readUpdateStageState(options.staging);
114
+ if (!state || state.phase !== "armed" || state.helperPid !== process.pid || state.version !== request.version || request.schema === 2 && state.generation !== request.generation) throw new Error("Update helper no longer owns this staging directory");
115
+ } finally {
116
+ await lock.release();
117
+ }
118
+ let cancelled = false;
36
119
  await waitForUpdateProcesses({
37
120
  processes: request.processes,
38
121
  timeoutMs: request.processTimeoutMs,
39
- onVerified: () => writeFileSync(join(options.staging, "helper-armed"), String(process.pid), {
40
- flag: "wx",
41
- mode: 384
122
+ ...request.schema === 2 && request.generation && request.helperOwner ? { cancellationRequested: () => cancellationRequested(options.staging, request.generation, request.helperOwner) } : {},
123
+ onVerified: () => publishExclusiveUpdateMarkerSync(options.staging, "helper-ready", {
124
+ schema: 1,
125
+ generation: state.generation,
126
+ helperOwner: request.helperOwner ?? ""
42
127
  })
128
+ }).catch(async (error) => {
129
+ if (error instanceof UpdateProcessFenceCancelledError && request.schema === 2 && request.generation && request.helperOwner) {
130
+ const cancellationLock = await acquireUpdateLock(request.target);
131
+ try {
132
+ await acknowledgeUpdateCancellation(options.staging, request);
133
+ cancelled = true;
134
+ } finally {
135
+ await cancellationLock.release();
136
+ }
137
+ return;
138
+ }
139
+ throw error;
43
140
  });
141
+ if (cancelled) return "cancelled";
44
142
  let outcome = "failed";
143
+ const swapLock = await acquireUpdateLock(request.target);
45
144
  try {
46
- await swapUpdateTree({
145
+ const current = await readUpdateStageState(options.staging);
146
+ if (!current || current.phase !== "armed" || current.helperPid !== process.pid || current.generation !== state?.generation) throw new Error("Update helper ownership changed before swap");
147
+ if (request.schema === 2 && request.generation && request.helperOwner && await cancellationRequested(options.staging, request.generation, request.helperOwner)) {
148
+ await acknowledgeUpdateCancellation(options.staging, request);
149
+ return "cancelled";
150
+ }
151
+ const candidate = join(options.staging, "candidate");
152
+ if (await readUpdateTreeVersion(request.target) !== current.previousVersion || await readUpdateTreeVersion(candidate) !== current.version || !sameUpdateTreeIdentity(await readUpdateTreeIdentity(candidate), current.candidateTreeIdentity)) throw new Error("Installed and candidate versions do not match the staged update");
153
+ const previousTreeIdentity = await readUpdateTreeIdentity(request.target);
154
+ if (!previousTreeIdentity) throw new Error("Installed update tree identity could not be read");
155
+ const swapping = {
156
+ ...current,
157
+ phase: "swapping",
158
+ previousTreeIdentity
159
+ };
160
+ await writeUpdateStageState(options.staging, swapping);
161
+ await swapUpdateTreeWhileLocked({
47
162
  target: request.target,
48
163
  staging: options.staging
49
164
  });
50
- await writeFile(join(options.staging, "updated"), request.version, { mode: 384 });
165
+ if (await readUpdateTreeVersion(request.target) !== swapping.version || await readUpdateTreeVersion(join(options.staging, "candidate")) !== swapping.previousVersion || !sameUpdateTreeIdentity(await readUpdateTreeIdentity(request.target), swapping.candidateTreeIdentity) || !sameUpdateTreeIdentity(await readUpdateTreeIdentity(join(options.staging, "candidate")), swapping.previousTreeIdentity)) throw new Error("Atomic update exchange produced unexpected tree versions");
166
+ await writeUpdateStageState(options.staging, {
167
+ ...swapping,
168
+ phase: "completed"
169
+ });
51
170
  outcome = "updated";
52
- } catch {}
171
+ } catch {
172
+ if ((await readUpdateStageState(options.staging).catch(() => void 0))?.phase === "armed" && request.schema === 2 && request.generation && request.helperOwner && await updatePathExists(join(options.staging, "cancel.json")).catch(() => false)) throw new Error("Update helper could not acknowledge cancellation before the install transition");
173
+ } finally {
174
+ await swapLock.release();
175
+ }
53
176
  await launchInstalledApp(request.platform, request.target, options.env);
54
177
  return outcome;
55
178
  }
56
- export { parseUpdateHelperRequest, runUpdateHelper };
179
+ async function matchesArmedGateTree(target, staging, request, gate) {
180
+ const state = await readUpdateStageState(staging);
181
+ if (!state || state.phase !== "armed" || state.helperPid !== process.pid || state.generation !== request.generation || state.version !== request.version || state.helperOwner !== request.helperOwner || state.launchGateOwner !== gate.owner || !state.previousTreeIdentity || !state.candidateTreeDigest || gate.generation !== state.generation || gate.version !== state.version) return false;
182
+ const candidate = join(staging, "candidate");
183
+ const [installedVersion, candidateVersion, installedIdentity, candidateIdentity] = await Promise.all([
184
+ readUpdateTreeVersion(target),
185
+ readUpdateTreeVersion(candidate),
186
+ readUpdateTreeIdentity(target),
187
+ readUpdateTreeIdentity(candidate)
188
+ ]);
189
+ return installedVersion === state.previousVersion && candidateVersion === state.version && sameUpdateTreeIdentity(installedIdentity, state.previousTreeIdentity) && sameUpdateTreeIdentity(candidateIdentity, state.candidateTreeIdentity) && sameUpdateTreeDigest(await readUpdateTreeDigest(candidate), state.candidateTreeDigest);
190
+ }
191
+ async function acknowledgeSchema3Cancellation(options, request) {
192
+ const lock = await acquireUpdateLock(request.target);
193
+ try {
194
+ await acknowledgeUpdateCancellation(options.staging, request);
195
+ } finally {
196
+ await lock.release();
197
+ }
198
+ }
199
+ async function waitForSchema3GateWriter(options, request, helperLiveness, gate) {
200
+ const controller = new AbortController();
201
+ let watcherStopped = false;
202
+ let cancellationObserved = false;
203
+ let watchError;
204
+ const watcher = (async () => {
205
+ for (;;) {
206
+ if (watcherStopped) break;
207
+ try {
208
+ if (await cancellationRequested(options.staging, request.generation, request.helperOwner)) {
209
+ cancellationObserved = true;
210
+ controller.abort(/* @__PURE__ */ new Error("Update helper cancellation was requested"));
211
+ return;
212
+ }
213
+ } catch (error) {
214
+ watchError = error;
215
+ controller.abort(error);
216
+ return;
217
+ }
218
+ await Bun.sleep(20);
219
+ }
220
+ })();
221
+ let writer;
222
+ let waitError;
223
+ try {
224
+ writer = await waitForUpdateLaunchGateWriter(request.target, gate, {
225
+ helperLiveness,
226
+ signal: controller.signal,
227
+ beforeWriterGrant: () => cancellationRequested(options.staging, request.generation, request.helperOwner)
228
+ });
229
+ } catch (error) {
230
+ waitError = error;
231
+ }
232
+ watcherStopped = true;
233
+ await watcher;
234
+ if (watchError !== void 0) {
235
+ await writer?.release().catch(() => {});
236
+ throw watchError;
237
+ }
238
+ if (cancellationObserved || await cancellationRequested(options.staging, request.generation, request.helperOwner)) {
239
+ if (writer) {
240
+ let result;
241
+ try {
242
+ result = await cancelUpdateLaunchGateBeforeTransition(request.target, helperLiveness, gate, (active) => matchesArmedGateTree(request.target, options.staging, request, active));
243
+ } finally {
244
+ await writer.release();
245
+ }
246
+ if (result === "cleared") return { status: "cancelled" };
247
+ throw new Error("Update cancellation arrived after the helper acquired the writer lease");
248
+ }
249
+ if (await cancelUpdateLaunchGateBeforeTransition(request.target, helperLiveness, gate, (active) => matchesArmedGateTree(request.target, options.staging, request, active)) === "cleared") return { status: "cancelled" };
250
+ throw new Error("Update helper could not safely clear its launch gate for cancellation");
251
+ }
252
+ if (waitError !== void 0) throw waitError;
253
+ if (!writer) throw new Error("Update launch gate writer was not acquired");
254
+ return {
255
+ status: "writer",
256
+ writer
257
+ };
258
+ }
259
+ async function runSchema3UpdateHelper(options, request, helperLiveness) {
260
+ const initialLock = await acquireUpdateLock(request.target);
261
+ try {
262
+ const current = await readUpdateStageState(options.staging);
263
+ if (!current || current.phase !== "armed" || current.helperPid !== process.pid || current.version !== request.version || current.generation !== request.generation || current.helperOwner !== request.helperOwner || !current.candidateTreeDigest) throw new Error("Update helper no longer owns this staging directory");
264
+ } finally {
265
+ await initialLock.release();
266
+ }
267
+ const gate = await publishUpdateLaunchGate(request.target, helperLiveness, {
268
+ generation: request.generation,
269
+ version: request.version
270
+ }, async (published) => {
271
+ const current = await readUpdateStageState(options.staging);
272
+ if (!current || current.phase !== "armed" || current.helperPid !== process.pid || current.generation !== request.generation || current.version !== request.version || current.helperOwner !== request.helperOwner || current.launchGateOwner !== void 0) throw new Error("Update helper ownership changed during gate publication");
273
+ const candidate = join(options.staging, "candidate");
274
+ const [installedVersion, candidateVersion, installedIdentity, candidateIdentity] = await Promise.all([
275
+ readUpdateTreeVersion(request.target),
276
+ readUpdateTreeVersion(candidate),
277
+ readUpdateTreeIdentity(request.target),
278
+ readUpdateTreeIdentity(candidate)
279
+ ]);
280
+ const candidateDigest = await readUpdateTreeDigest(candidate);
281
+ if (installedVersion !== current.previousVersion || candidateVersion !== current.version || !installedIdentity || !sameUpdateTreeIdentity(candidateIdentity, current.candidateTreeIdentity) || !sameUpdateTreeDigest(candidateDigest, current.candidateTreeDigest)) throw new Error("Update helper cannot publish a gate for changed update trees");
282
+ await writeUpdateStageStateDurably(options.staging, {
283
+ ...current,
284
+ previousTreeIdentity: installedIdentity,
285
+ launchGateOwner: published.owner
286
+ });
287
+ });
288
+ const mapped = await readUpdateStageState(options.staging);
289
+ if (!mapped || mapped.phase !== "armed" || mapped.generation !== gate.generation || mapped.version !== gate.version || mapped.helperPid !== process.pid || mapped.helperOwner !== request.helperOwner || mapped.launchGateOwner !== gate.owner || !mapped.previousTreeIdentity || !mapped.candidateTreeDigest) throw new Error("Update helper gate owner was not durably recorded");
290
+ let cancelled = false;
291
+ try {
292
+ await waitForUpdateProcesses({
293
+ processes: request.processes,
294
+ timeoutMs: request.processTimeoutMs,
295
+ cancellationRequested: () => cancellationRequested(options.staging, request.generation, request.helperOwner),
296
+ onVerified: () => publishExclusiveUpdateMarkerSync(options.staging, "helper-ready", {
297
+ schema: 1,
298
+ generation: gate.generation,
299
+ helperOwner: request.helperOwner,
300
+ launchGateOwner: gate.owner
301
+ })
302
+ });
303
+ } catch (error) {
304
+ if (!(error instanceof UpdateProcessFenceCancelledError)) throw error;
305
+ if (await cancelUpdateLaunchGateBeforeTransition(request.target, helperLiveness, gate, (active) => matchesArmedGateTree(request.target, options.staging, request, active)) !== "cleared") throw new Error("Update helper could not safely clear its launch gate for cancellation", { cause: error });
306
+ await acknowledgeSchema3Cancellation(options, request);
307
+ cancelled = true;
308
+ }
309
+ if (cancelled) return "cancelled";
310
+ const waiting = await waitForSchema3GateWriter(options, request, helperLiveness, gate);
311
+ if (waiting.status === "cancelled") {
312
+ await acknowledgeSchema3Cancellation(options, request);
313
+ return "cancelled";
314
+ }
315
+ const writer = waiting.writer;
316
+ const candidate = join(options.staging, "candidate");
317
+ let completedDigestVerified = false;
318
+ try {
319
+ await syncUpdateTree(candidate);
320
+ await syncUpdateTreeParent(candidate);
321
+ const transitionResult = await writer.withTransition(async (active) => {
322
+ const current = await readUpdateStageState(options.staging);
323
+ if (!current || current.phase !== "armed" || current.helperPid !== process.pid || current.generation !== gate.generation || current.version !== gate.version || current.helperOwner !== request.helperOwner || current.launchGateOwner !== gate.owner || !current.previousTreeIdentity || !current.candidateTreeDigest || await readUpdateTreeVersion(request.target) !== current.previousVersion || await readUpdateTreeVersion(candidate) !== current.version || !sameUpdateTreeIdentity(await readUpdateTreeIdentity(request.target), current.previousTreeIdentity) || !sameUpdateTreeIdentity(await readUpdateTreeIdentity(candidate), current.candidateTreeIdentity) || !sameUpdateTreeDigest(await readUpdateTreeDigest(candidate), current.candidateTreeDigest)) throw new Error("Update helper ownership or tree identity changed before swap");
324
+ if (active.owner !== gate.owner) throw new Error("Update writer owner changed");
325
+ const swapping = {
326
+ ...current,
327
+ phase: "swapping"
328
+ };
329
+ await writeUpdateStageStateDurably(options.staging, swapping);
330
+ await swapUpdateTreeWhileLocked({
331
+ target: request.target,
332
+ staging: options.staging
333
+ });
334
+ await syncUpdateTreeParent(candidate);
335
+ await syncUpdateTreeParent(request.target);
336
+ if (await readUpdateTreeVersion(request.target) !== swapping.version || await readUpdateTreeVersion(candidate) !== swapping.previousVersion || !sameUpdateTreeIdentity(await readUpdateTreeIdentity(request.target), swapping.candidateTreeIdentity) || !sameUpdateTreeIdentity(await readUpdateTreeIdentity(candidate), swapping.previousTreeIdentity)) throw new Error("Atomic update exchange produced unexpected tree versions");
337
+ if (!sameUpdateTreeDigest(await readUpdateTreeDigest(request.target), swapping.candidateTreeDigest)) throw new Error("Installed update tree content changed during the directory exchange");
338
+ completedDigestVerified = true;
339
+ await writeUpdateStageStateDurably(options.staging, {
340
+ ...swapping,
341
+ phase: "completed"
342
+ });
343
+ return "updated";
344
+ });
345
+ if (await writer.clearGate(async (active) => {
346
+ const current = await readUpdateStageState(options.staging);
347
+ if (!current || current.phase !== "completed" || current.helperPid !== process.pid || current.generation !== active.generation || current.version !== active.version || current.helperOwner !== request.helperOwner || current.launchGateOwner !== active.owner || !current.previousTreeIdentity || !current.candidateTreeDigest) return false;
348
+ const [installedVersion, previousVersion, installedIdentity, previousIdentity] = await Promise.all([
349
+ readUpdateTreeVersion(request.target),
350
+ readUpdateTreeVersion(candidate),
351
+ readUpdateTreeIdentity(request.target),
352
+ readUpdateTreeIdentity(candidate)
353
+ ]);
354
+ return installedVersion === current.version && previousVersion === current.previousVersion && sameUpdateTreeIdentity(installedIdentity, current.candidateTreeIdentity) && sameUpdateTreeIdentity(previousIdentity, current.previousTreeIdentity) && completedDigestVerified;
355
+ }) !== "cleared") throw new Error("Completed update could not prove safe launch gate removal");
356
+ await writer.release();
357
+ if (transitionResult !== "updated") throw new Error("Update transition did not complete");
358
+ } catch {
359
+ await writer.release().catch(() => {});
360
+ return "failed";
361
+ }
362
+ await launchInstalledApp(request.platform, request.target, options.env);
363
+ return "updated";
364
+ }
365
+ export { hasUpdateHelperArtifacts, parseUpdateHelperRequest, runUpdateHelper, updatePathExists };
@@ -0,0 +1,22 @@
1
+ import { type UpdateLaunchLeaseAttempt } from './update-launch-gate';
2
+ /**
3
+ * Transfer a launcher's inherited POSIX shared-lock descriptor to an
4
+ * independent process lease. The native launcher must have acquired the shared
5
+ * lock under the coordinator before spawning and passed the same shared-locked
6
+ * open file description without unlocking it. Passing an exclusive lock can
7
+ * downgrade it. This API cannot prove what happened before
8
+ * it was called or protect bundle code that already ran.
9
+ *
10
+ * The caller must exclusively control the descriptor and its open-file
11
+ * description, must not close, unlock, or concurrently transfer it, and must
12
+ * never retry after success or an uncertain close. On busy, retain it through a
13
+ * retry or process exit. On gated or an error before close, stop startup and
14
+ * exit while keeping it open; retaining it while waiting for the gate can
15
+ * prevent the updater from finishing. On success this function closes it
16
+ * without LOCK_UN and returns the independent lease. A failed close retains the
17
+ * independent lease until process exit; descriptor state is then uncertain.
18
+ */
19
+ export declare function adoptInheritedUpdateLaunchLease(options: {
20
+ target: string;
21
+ descriptor: number;
22
+ }): Promise<UpdateLaunchLeaseAttempt>;
@@ -0,0 +1,58 @@
1
+ import { tryLockInheritedSharedFileDescriptor } from "./native-file-lock.js";
2
+ import { updateInstanceLeasePath } from "./update-instance-lease.js";
3
+ import { tryAcquireUpdateLaunchLease } from "./update-launch-gate.js";
4
+ import { closeSync, fstatSync, lstatSync } from "node:fs";
5
+ // src/updates/update-inherited-launch-lease.ts
6
+ var retainedAfterCloseFailure = /* @__PURE__ */ new Set();
7
+ var transfersInFlight = /* @__PURE__ */ new Set();
8
+ var uncertainDescriptors = /* @__PURE__ */ new Set();
9
+ /**
10
+ * Transfer a launcher's inherited POSIX shared-lock descriptor to an
11
+ * independent process lease. The native launcher must have acquired the shared
12
+ * lock under the coordinator before spawning and passed the same shared-locked
13
+ * open file description without unlocking it. Passing an exclusive lock can
14
+ * downgrade it. This API cannot prove what happened before
15
+ * it was called or protect bundle code that already ran.
16
+ *
17
+ * The caller must exclusively control the descriptor and its open-file
18
+ * description, must not close, unlock, or concurrently transfer it, and must
19
+ * never retry after success or an uncertain close. On busy, retain it through a
20
+ * retry or process exit. On gated or an error before close, stop startup and
21
+ * exit while keeping it open; retaining it while waiting for the gate can
22
+ * prevent the updater from finishing. On success this function closes it
23
+ * without LOCK_UN and returns the independent lease. A failed close retains the
24
+ * independent lease until process exit; descriptor state is then uncertain.
25
+ */
26
+ async function adoptInheritedUpdateLaunchLease(options) {
27
+ const { descriptor, target } = options;
28
+ if (process.platform !== "darwin" && process.platform !== "linux") throw new Error("Inherited update launch leases require POSIX flock");
29
+ if (!Number.isInteger(descriptor) || descriptor < 3 || descriptor > 2147483647) throw new Error("Invalid inherited update launch descriptor");
30
+ if (uncertainDescriptors.has(descriptor)) throw new Error("Inherited update launch descriptor has uncertain ownership");
31
+ if (transfersInFlight.has(descriptor)) throw new Error("Inherited update launch descriptor is already being transferred");
32
+ transfersInFlight.add(descriptor);
33
+ try {
34
+ const path = updateInstanceLeasePath(target);
35
+ const validate = () => {
36
+ const actual = fstatSync(descriptor, { bigint: true });
37
+ const expected = lstatSync(path, { bigint: true });
38
+ if (!actual.isFile() || !expected.isFile() || expected.isSymbolicLink() || actual.dev !== expected.dev || actual.ino !== expected.ino) throw new Error("Inherited update launch descriptor does not match the instance lock");
39
+ };
40
+ validate();
41
+ if (!tryLockInheritedSharedFileDescriptor(descriptor)) return { status: "busy" };
42
+ validate();
43
+ const result = await tryAcquireUpdateLaunchLease(target);
44
+ if (result.status !== "acquired") return result;
45
+ try {
46
+ validate();
47
+ closeSync(descriptor);
48
+ } catch (error) {
49
+ uncertainDescriptors.add(descriptor);
50
+ retainedAfterCloseFailure.add(result.lease);
51
+ throw new Error("Inherited update launch handoff could not be completed", { cause: error });
52
+ }
53
+ return result;
54
+ } finally {
55
+ transfersInFlight.delete(descriptor);
56
+ }
57
+ }
58
+ export { adoptInheritedUpdateLaunchLease };
@@ -0,0 +1,15 @@
1
+ export type UpdateInstanceLeaseMode = 'shared' | 'exclusive';
2
+ export type UpdateInstanceLease = Readonly<{
3
+ mode: UpdateInstanceLeaseMode;
4
+ release(): Promise<void>;
5
+ }>;
6
+ /** Stable app-lifetime path, separate from the updater transition lock. */
7
+ export declare function updateInstanceLeasePath(target: string): string;
8
+ /**
9
+ * Try to acquire a per-install app-lifetime lease without waiting. Application
10
+ * processes use shared mode and an updater uses exclusive mode. undefined means
11
+ * another process owns an incompatible lease; other failures reject.
12
+ *
13
+ * The lock file is persistent and must never be removed or replaced.
14
+ */
15
+ export declare function tryAcquireUpdateInstanceLease(target: string, mode: UpdateInstanceLeaseMode): Promise<UpdateInstanceLease | undefined>;