omnius 1.0.971 → 1.0.973

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.
@@ -5000,6 +5000,24 @@ var init_process_lifecycle = __esm({
5000
5000
  }
5001
5001
  });
5002
5002
 
5003
+ // packages/execution/dist/tools/shell-authority.js
5004
+ var init_shell_authority = __esm({
5005
+ "packages/execution/dist/tools/shell-authority.js"() {
5006
+ "use strict";
5007
+ }
5008
+ });
5009
+
5010
+ // packages/execution/dist/shell-interruption-evidence.js
5011
+ var LEASE_JOURNAL_MAX_BYTES;
5012
+ var init_shell_interruption_evidence = __esm({
5013
+ "packages/execution/dist/shell-interruption-evidence.js"() {
5014
+ "use strict";
5015
+ init_shell_authority();
5016
+ init_process_lifecycle();
5017
+ LEASE_JOURNAL_MAX_BYTES = 64 * 1024 * 1024;
5018
+ }
5019
+ });
5020
+
5003
5021
  // packages/execution/dist/background-process-receipt.js
5004
5022
  var init_background_process_receipt = __esm({
5005
5023
  "packages/execution/dist/background-process-receipt.js"() {
@@ -5102,13 +5120,6 @@ var init_desktop_control = __esm({
5102
5120
  }
5103
5121
  });
5104
5122
 
5105
- // packages/execution/dist/tools/shell-authority.js
5106
- var init_shell_authority = __esm({
5107
- "packages/execution/dist/tools/shell-authority.js"() {
5108
- "use strict";
5109
- }
5110
- });
5111
-
5112
5123
  // packages/execution/dist/verificationPreviewReceipt.js
5113
5124
  var init_verificationPreviewReceipt = __esm({
5114
5125
  "packages/execution/dist/verificationPreviewReceipt.js"() {
@@ -303937,6 +303948,7 @@ var init_dist5 = __esm({
303937
303948
  init_broker_mediated_backend();
303938
303949
  init_evidence();
303939
303950
  init_process_lifecycle();
303951
+ init_shell_interruption_evidence();
303940
303952
  init_background_process_receipt();
303941
303953
  init_run_context();
303942
303954
  init_security_classifier();
@@ -304306,6 +304318,11 @@ function readDaemonSupervisionHealth(port, options = {}) {
304306
304318
  const record2 = pruneExpiredAttempts(readRecord(port, now, options), now, policy);
304307
304319
  return toHealth(record2, now, policy);
304308
304320
  }
304321
+ function findVerifiedDaemonSignalLease(pid, port, leases) {
304322
+ return leases.find(
304323
+ (lease) => lease.pid === pid && lease.status === "active" && lease.ownerKind === "daemon" && lease.ownerId === `daemon:${port}`
304324
+ ) ?? null;
304325
+ }
304309
304326
  var DAEMON_SUPERVISION_SCHEMA;
304310
304327
  var init_daemon_supervision = __esm({
304311
304328
  "packages/cli/src/daemon-supervision.ts"() {
@@ -304700,7 +304717,7 @@ var init_daemon_service = __esm({
304700
304717
 
304701
304718
  // packages/cli/src/daemon.ts
304702
304719
  import { spawn as spawn2 } from "node:child_process";
304703
- import { existsSync as existsSync7, readFileSync as readFileSync6, writeFileSync as writeFileSync4, mkdirSync as mkdirSync6, unlinkSync as unlinkSync2, openSync as openSync2, closeSync as closeSync2, writeSync, statSync as statSync2, renameSync as renameSync4 } from "node:fs";
304720
+ import { existsSync as existsSync7, readFileSync as readFileSync6, writeFileSync as writeFileSync4, mkdirSync as mkdirSync6, unlinkSync as unlinkSync2, openSync as openSync2, closeSync as closeSync2, writeSync, lstatSync as lstatSync2, statSync as statSync2, renameSync as renameSync4 } from "node:fs";
304704
304721
  import { join as join15 } from "node:path";
304705
304722
  import { homedir as homedir15 } from "node:os";
304706
304723
  import { createServer as createNetServer } from "node:net";
@@ -304729,10 +304746,52 @@ function processIsAlive(pid) {
304729
304746
  return error.code !== "ESRCH";
304730
304747
  }
304731
304748
  }
304749
+ function readLinuxBootId() {
304750
+ if (process.platform !== "linux") return;
304751
+ try {
304752
+ const id2 = readFileSync6("/proc/sys/kernel/random/boot_id", "utf8").trim();
304753
+ return LINUX_BOOT_ID.test(id2) ? id2 : void 0;
304754
+ } catch {
304755
+ return;
304756
+ }
304757
+ }
304758
+ function readLinuxProcessBirth(pid) {
304759
+ try {
304760
+ const stat = readFileSync6(`/proc/${pid}/stat`, "utf8");
304761
+ const fields = stat.slice(stat.lastIndexOf(")") + 2).trim().split(/\s+/);
304762
+ const state = fields[0], start = fields[19];
304763
+ return state && start && /^\d+$/.test(start) ? { start, state } : void 0;
304764
+ } catch {
304765
+ return;
304766
+ }
304767
+ }
304768
+ function currentDaemonLockIdentity() {
304769
+ const bootId = readLinuxBootId();
304770
+ const birth = bootId && readLinuxProcessBirth(process.pid);
304771
+ return birth ? { bootId, processStart: birth.start } : {};
304772
+ }
304773
+ function daemonLockOwnerIsStale(record2) {
304774
+ if (process.platform !== "linux") return false;
304775
+ if (record2.bootId === void 0 && record2.processStart === void 0) {
304776
+ try {
304777
+ const seconds = readFileSync6("/proc/stat", "utf8").match(/^btime (\d+)$/m)?.[1];
304778
+ const bootTime = Number(seconds) * 1e3;
304779
+ return Number.isSafeInteger(bootTime) && bootTime > 0 && record2.startedAt < bootTime;
304780
+ } catch {
304781
+ return false;
304782
+ }
304783
+ }
304784
+ if (typeof record2.bootId !== "string" || !LINUX_BOOT_ID.test(record2.bootId) || typeof record2.processStart !== "string" || !/^\d+$/.test(record2.processStart)) return false;
304785
+ const bootId = readLinuxBootId();
304786
+ if (!bootId) return false;
304787
+ if (record2.bootId.toLowerCase() !== bootId.toLowerCase()) return true;
304788
+ const birth = readLinuxProcessBirth(record2.pid);
304789
+ return Boolean(birth && (birth.start !== record2.processStart || birth.state === "Z" || birth.state === "X"));
304790
+ }
304732
304791
  function readDaemonLock(lockFile) {
304733
304792
  try {
304734
304793
  const value = JSON.parse(readFileSync6(lockFile, "utf8"));
304735
- if (typeof value.endpoint !== "string" || typeof value.pid !== "number" || !Number.isInteger(value.pid) || value.pid <= 0 || typeof value.token !== "string" || typeof value.startedAt !== "number") {
304794
+ if (typeof value.endpoint !== "string" || typeof value.pid !== "number" || !Number.isInteger(value.pid) || value.pid <= 0 || typeof value.token !== "string" || typeof value.startedAt !== "number" || !Number.isFinite(value.startedAt) || value.startedAt < 0) {
304736
304795
  return null;
304737
304796
  }
304738
304797
  return value;
@@ -304760,7 +304819,8 @@ function claimDaemonEndpoint(port = getDaemonPort(), inheritedToken) {
304760
304819
  endpoint,
304761
304820
  pid: process.pid,
304762
304821
  token,
304763
- startedAt: Date.now()
304822
+ startedAt: Date.now(),
304823
+ ...currentDaemonLockIdentity()
304764
304824
  };
304765
304825
  let fd = null;
304766
304826
  try {
@@ -304784,16 +304844,18 @@ function claimDaemonEndpoint(port = getDaemonPort(), inheritedToken) {
304784
304844
  }
304785
304845
  const existing = readDaemonLock(lockFile);
304786
304846
  if (existing?.endpoint === endpoint && inheritedToken && existing.token === inheritedToken) {
304787
- const transferred = { ...existing, pid: process.pid, startedAt: Date.now() };
304788
- writeFileSync4(lockFile, JSON.stringify(transferred), { encoding: "utf8", mode: 384 });
304847
+ writeFileSync4(lockFile, JSON.stringify(record2), { encoding: "utf8", mode: 384 });
304789
304848
  return { endpoint, lockFile, pid: process.pid, port, token: inheritedToken };
304790
304849
  }
304791
- if (existing && processIsAlive(existing.pid) || !existing && daemonLockIsInitializing(lockFile)) {
304792
- return null;
304793
- }
304794
- try {
304795
- unlinkSync2(lockFile);
304796
- } catch {
304850
+ if (existing) {
304851
+ if (existing.endpoint !== endpoint || processIsAlive(existing.pid) && !daemonLockOwnerIsStale(existing)) return null;
304852
+ if (!removeDaemonLockIfUnchanged(port, existing)) return null;
304853
+ } else {
304854
+ if (daemonLockIsInitializing(lockFile)) return null;
304855
+ try {
304856
+ unlinkSync2(lockFile);
304857
+ } catch {
304858
+ }
304797
304859
  }
304798
304860
  }
304799
304861
  return null;
@@ -304837,16 +304899,18 @@ async function getDaemonReportedIdentity(port) {
304837
304899
  return null;
304838
304900
  }
304839
304901
  }
304840
- async function waitForDaemonReady(port, expectedVersion, attempts = 24) {
304902
+ async function waitForDaemonReady(port, expectedVersion, attempts = 24, startupEnded) {
304841
304903
  let observedVersion = null;
304842
304904
  for (let attempt = 0; attempt < attempts; attempt++) {
304843
304905
  await new Promise((resolve13) => setTimeout(resolve13, 500));
304844
304906
  const identity = await getDaemonReportedIdentity(port);
304845
- if (!identity) continue;
304846
- observedVersion = identity.bootVersion;
304847
- if (!expectedVersion || expectedVersion === "0.0.0" || observedVersion === expectedVersion) {
304848
- return { ok: true, observedVersion };
304907
+ if (identity) {
304908
+ observedVersion = identity.bootVersion;
304909
+ if (!expectedVersion || expectedVersion === "0.0.0" || observedVersion === expectedVersion) {
304910
+ return { ok: true, observedVersion };
304911
+ }
304849
304912
  }
304913
+ if (startupEnded?.()) break;
304850
304914
  }
304851
304915
  return { ok: false, observedVersion };
304852
304916
  }
@@ -305062,10 +305126,13 @@ async function waitForDaemonStopped(port, attempts = DAEMON_GRACEFUL_STOP_ATTEMP
305062
305126
  }
305063
305127
  function removeDaemonLockIfUnchanged(port, expected) {
305064
305128
  const lockFile = daemonLockFile(port);
305065
- const current = readDaemonLock(lockFile);
305066
- if (!current) return true;
305067
- if (current.pid !== expected.pid || current.token !== expected.token) return false;
305068
305129
  try {
305130
+ const before = lstatSync2(lockFile);
305131
+ if (!before.isFile()) return false;
305132
+ const current = readDaemonLock(lockFile);
305133
+ if (!current || current.endpoint !== expected.endpoint || current.pid !== expected.pid || current.token !== expected.token || current.startedAt !== expected.startedAt || current.bootId !== expected.bootId || current.processStart !== expected.processStart) return false;
305134
+ const after = lstatSync2(lockFile);
305135
+ if (before.dev !== after.dev || before.ino !== after.ino || before.ctimeMs !== after.ctimeMs) return false;
305069
305136
  unlinkSync2(lockFile);
305070
305137
  return true;
305071
305138
  } catch (error) {
@@ -305075,9 +305142,10 @@ function removeDaemonLockIfUnchanged(port, expected) {
305075
305142
  async function reclaimStaleDaemonEndpointClaim(port, verifiedStoppedPids = /* @__PURE__ */ new Set(), dependencies = DEFAULT_CLAIM_RECLAIM_DEPENDENCIES) {
305076
305143
  const record2 = dependencies.readLock(port);
305077
305144
  if (!record2) return dependencies.portIsFree(port);
305145
+ if (record2.endpoint !== daemonEndpoint(port)) return false;
305078
305146
  if (!await dependencies.portIsFree(port)) return false;
305079
305147
  const clearExactClaim = async () => dependencies.removeLockIfUnchanged(port, record2) && dependencies.portIsFree(port);
305080
- if (verifiedStoppedPids.has(record2.pid) || !dependencies.processIsAlive(record2.pid)) {
305148
+ if (verifiedStoppedPids.has(record2.pid) || !dependencies.processIsAlive(record2.pid) || dependencies.ownerIsStale?.(record2)) {
305081
305149
  return clearExactClaim();
305082
305150
  }
305083
305151
  const lease = dependencies.leases().find(
@@ -305170,7 +305238,7 @@ async function restartDaemon(port, expectedVersion, preferredEntrypoint, service
305170
305238
  if (managed) {
305171
305239
  if (!await scopedDaemonServiceOwnsPort(managed, p)) {
305172
305240
  const holders = await portHolderPids(p);
305173
- if (!holders || holders.some((pid2) => pidIsInManagedDaemonUnit(pid2))) return false;
305241
+ if (!holders || holders.some((pid) => pidIsInManagedDaemonUnit(pid))) return false;
305174
305242
  const reclaimed2 = await reclaimOwnedDaemonListener(p);
305175
305243
  if (!reclaimed2.ok) return false;
305176
305244
  await reclaimStaleDaemonEndpointClaim(p, new Set(reclaimed2.clearedPids));
@@ -305203,9 +305271,9 @@ async function restartDaemon(port, expectedVersion, preferredEntrypoint, service
305203
305271
  const reclaimed = await reclaimOwnedDaemonListener(p);
305204
305272
  if (!reclaimed.ok) return false;
305205
305273
  if (!await reclaimStaleDaemonEndpointClaim(p, new Set(reclaimed.clearedPids))) return false;
305206
- const pid = await startDaemon(p, preferredEntrypoint);
305207
- if (!pid) return false;
305208
- return (await waitForDaemonReady(p, expectedVersion)).ok;
305274
+ const launch = await launchDetachedDaemon(p, preferredEntrypoint);
305275
+ if (!launch) return false;
305276
+ return (await settleDetachedDaemonStartup(launch, expectedVersion)).ok;
305209
305277
  }
305210
305278
  function looksLikeNodeEntrypoint(path3) {
305211
305279
  if (/\.(?:mjs|cjs|js)$/i.test(path3)) return true;
@@ -305269,25 +305337,28 @@ async function reinstallUserDaemonService(port, expectedVersion, preferredEntryp
305269
305337
  return false;
305270
305338
  }
305271
305339
  }
305272
- async function startDaemon(port = getDaemonPort(), preferredEntrypoint) {
305340
+ function daemonChildHasExited(child) {
305341
+ return child.exitCode !== null || child.signalCode !== null;
305342
+ }
305343
+ async function launchDetachedDaemon(port, preferredEntrypoint) {
305273
305344
  mkdirSync6(OMNIUS_DIR, { recursive: true });
305274
305345
  const daemonPort = port;
305275
305346
  const endpointClaim = claimDaemonEndpoint(daemonPort);
305276
305347
  if (!endpointClaim) return null;
305277
- const nodeExe = process.execPath;
305278
- const daemonCommand = await resolveDaemonCommand(nodeExe, preferredEntrypoint);
305279
- if (!daemonCommand) {
305280
- releaseDaemonEndpointClaim(endpointClaim);
305281
- return null;
305282
- }
305283
305348
  let outFd = null;
305284
305349
  let errFd = null;
305350
+ let child;
305285
305351
  try {
305352
+ const daemonCommand = await resolveDaemonCommand(process.execPath, preferredEntrypoint);
305353
+ if (!daemonCommand) {
305354
+ releaseDaemonEndpointClaim(endpointClaim);
305355
+ return null;
305356
+ }
305286
305357
  outFd = openSync2(join15(OMNIUS_DIR, "daemon.log"), "a");
305287
305358
  errFd = openSync2(join15(OMNIUS_DIR, "daemon.err.log"), "a");
305288
305359
  const leaseId = newProcessLeaseId("daemon");
305289
305360
  const ownerId = `daemon:${daemonPort}`;
305290
- const child = spawn2(daemonCommand.command, daemonCommand.args, {
305361
+ const launchedChild = child = spawn2(daemonCommand.command, daemonCommand.args, {
305291
305362
  detached: true,
305292
305363
  stdio: ["ignore", outFd, errFd],
305293
305364
  env: {
@@ -305303,27 +305374,34 @@ async function startDaemon(port = getDaemonPort(), preferredEntrypoint) {
305303
305374
  OMNIUS_PROCESS_PERSISTENT: "1"
305304
305375
  }
305305
305376
  });
305306
- child.unref();
305307
- const pid = child.pid ?? null;
305308
- if (pid) {
305309
- writeFileSync4(PID_FILE, String(pid), "utf8");
305310
- registerProcessLease({
305311
- leaseId,
305312
- pid,
305313
- pgid: process.platform === "win32" ? void 0 : pid,
305314
- ownerKind: "daemon",
305315
- ownerId,
305316
- projectRoot: process.cwd(),
305317
- lifecycle: "daemon",
305318
- persistent: true,
305319
- reason: `shared API daemon on port ${daemonPort}`,
305320
- command: [daemonCommand.command, ...daemonCommand.args].join(" "),
305321
- cwd: process.cwd()
305322
- });
305377
+ const launched = await new Promise((resolve13) => {
305378
+ launchedChild.once("spawn", () => resolve13(true));
305379
+ launchedChild.once("error", () => resolve13(false));
305380
+ });
305381
+ const pid = child.pid;
305382
+ if (!launched || !pid) {
305383
+ releaseDaemonEndpointClaim(endpointClaim);
305384
+ return null;
305323
305385
  }
305324
- return pid;
305386
+ child.unref();
305387
+ child.once("exit", () => releaseDaemonEndpointClaim(endpointClaim));
305388
+ registerProcessLease({
305389
+ leaseId,
305390
+ pid,
305391
+ pgid: process.platform === "win32" ? void 0 : pid,
305392
+ ownerKind: "daemon",
305393
+ ownerId,
305394
+ projectRoot: process.cwd(),
305395
+ lifecycle: "daemon",
305396
+ persistent: true,
305397
+ reason: `shared API daemon on port ${daemonPort}`,
305398
+ command: [daemonCommand.command, ...daemonCommand.args].join(" "),
305399
+ cwd: process.cwd()
305400
+ });
305401
+ writeFileSync4(PID_FILE, String(pid), "utf8");
305402
+ return { child, pid, claim: endpointClaim, leaseId };
305325
305403
  } catch {
305326
- releaseDaemonEndpointClaim(endpointClaim);
305404
+ if (!child?.pid || daemonChildHasExited(child)) releaseDaemonEndpointClaim(endpointClaim);
305327
305405
  return null;
305328
305406
  } finally {
305329
305407
  if (outFd !== null) try {
@@ -305336,6 +305414,38 @@ async function startDaemon(port = getDaemonPort(), preferredEntrypoint) {
305336
305414
  }
305337
305415
  }
305338
305416
  }
305417
+ async function settleDetachedDaemonStartup(launch, expectedVersion, attempts) {
305418
+ const { child, claim, pid, leaseId } = launch;
305419
+ const readOwnClaim = () => {
305420
+ const current2 = readDaemonLock(claim.lockFile);
305421
+ return current2?.token === claim.token && current2.endpoint === claim.endpoint ? current2 : null;
305422
+ };
305423
+ const ready = await waitForDaemonReady(
305424
+ claim.port,
305425
+ expectedVersion,
305426
+ attempts,
305427
+ () => daemonChildHasExited(child) && (readOwnClaim()?.pid ?? claim.pid) === claim.pid
305428
+ );
305429
+ if (ready.ok) return ready;
305430
+ const current = readOwnClaim();
305431
+ const ownerPid = current && current.pid !== claim.pid ? current.pid : pid;
305432
+ let settled = ownerPid === pid && daemonChildHasExited(child);
305433
+ if (!settled) {
305434
+ const lease = findVerifiedDaemonSignalLease(ownerPid, claim.port, listProcessLeases({ includeInactive: false }));
305435
+ if (lease?.leaseId === leaseId) {
305436
+ const stopped = await stopDaemonLeaseGracefully(leaseId, "daemon readiness deadline expired");
305437
+ settled = stopped.action === "dead" || stopped.action === "killed";
305438
+ }
305439
+ }
305440
+ if (settled) {
305441
+ releaseDaemonEndpointClaim({ ...claim, pid: current?.pid ?? claim.pid });
305442
+ try {
305443
+ if (readFileSync6(PID_FILE, "utf8").trim() === String(pid)) unlinkSync2(PID_FILE);
305444
+ } catch {
305445
+ }
305446
+ }
305447
+ return ready;
305448
+ }
305339
305449
  async function stopDaemonAtPort(port = getDaemonPort(), dependencies) {
305340
305450
  const deps = dependencies ?? daemonStopDependencies(await discoverDaemonServiceAtPort(port));
305341
305451
  if (await deps.managedServiceMatchesPort(port)) return await deps.stopManagedService() && await deps.waitForStopped(port);
@@ -305354,7 +305464,7 @@ async function quiesceDaemonForUpdate(port = getDaemonPort(), scope) {
305354
305464
  if (managed) dependencies.stopManagedService = () => stopManagedDaemonForUpdate(managed, () => waitForDaemonStopped(port));
305355
305465
  return stopDaemonAtPort(port, dependencies);
305356
305466
  }
305357
- var OMNIUS_DIR, PID_FILE, DEFAULT_PORT2, LOCK_INITIALIZATION_GRACE_MS, DAEMON_GRACEFUL_STOP_ATTEMPTS, DEFAULT_RECLAIM_DEPENDENCIES, DEFAULT_CLAIM_RECLAIM_DEPENDENCIES, daemonStopDependencies;
305467
+ var OMNIUS_DIR, PID_FILE, DEFAULT_PORT2, LOCK_INITIALIZATION_GRACE_MS, LINUX_BOOT_ID, DAEMON_GRACEFUL_STOP_ATTEMPTS, DEFAULT_RECLAIM_DEPENDENCIES, DEFAULT_CLAIM_RECLAIM_DEPENDENCIES, daemonStopDependencies;
305358
305468
  var init_daemon = __esm({
305359
305469
  "packages/cli/src/daemon.ts"() {
305360
305470
  init_dist5();
@@ -305365,6 +305475,7 @@ var init_daemon = __esm({
305365
305475
  PID_FILE = join15(OMNIUS_DIR, "daemon.pid");
305366
305476
  DEFAULT_PORT2 = 11435;
305367
305477
  LOCK_INITIALIZATION_GRACE_MS = 5e3;
305478
+ LINUX_BOOT_ID = /^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i;
305368
305479
  DAEMON_GRACEFUL_STOP_ATTEMPTS = 20;
305369
305480
  DEFAULT_RECLAIM_DEPENDENCIES = {
305370
305481
  holderPids: (port) => portHolderPids(port),
@@ -305377,6 +305488,7 @@ var init_daemon = __esm({
305377
305488
  readLock: (port) => readDaemonLock(daemonLockFile(port)),
305378
305489
  portIsFree: (port) => daemonPortIsFree(port),
305379
305490
  processIsAlive: (pid) => processIsAlive(pid),
305491
+ ownerIsStale: daemonLockOwnerIsStale,
305380
305492
  leases: () => listProcessLeases({ includeInactive: false }),
305381
305493
  stopLease: (leaseId, port) => stopDaemonLeaseGracefully(leaseId, `stale daemon endpoint claim on port ${port}`),
305382
305494
  removeLockIfUnchanged: (port, expected) => removeDaemonLockIfUnchanged(port, expected)
@@ -305410,7 +305522,7 @@ import {
305410
305522
  fchmodSync,
305411
305523
  fstatSync as fstatSync2,
305412
305524
  fsyncSync as fsyncSync2,
305413
- lstatSync as lstatSync4,
305525
+ lstatSync as lstatSync5,
305414
305526
  readlinkSync as readlinkSync2,
305415
305527
  mkdirSync as mkdirSync7,
305416
305528
  openSync as openSync4,
@@ -305484,8 +305596,8 @@ init_daemon_checkpoint_interrupted();
305484
305596
  init_daemon_service_authorization();
305485
305597
 
305486
305598
  // packages/cli/src/user-systemd-environment.ts
305487
- import { lstatSync as lstatSync2 } from "node:fs";
305488
- function userManagerEnvironment(env, uid = process.getuid?.(), inspect = lstatSync2) {
305599
+ import { lstatSync as lstatSync3 } from "node:fs";
305600
+ function userManagerEnvironment(env, uid = process.getuid?.(), inspect = lstatSync3) {
305489
305601
  if (env["XDG_RUNTIME_DIR"] && env["DBUS_SESSION_BUS_ADDRESS"]) return env;
305490
305602
  if (uid === void 0 || !Number.isSafeInteger(uid) || uid < 0) return env;
305491
305603
  const runtimeDir = env["XDG_RUNTIME_DIR"] || `/run/user/${uid}`;
@@ -305535,7 +305647,7 @@ async function pruneStaleUpdateRecoveries(modulesRoot, options = {}) {
305535
305647
 
305536
305648
  // packages/cli/src/npm-install-recovery.ts
305537
305649
  import { createHash as createHash4, randomUUID as randomUUID4 } from "node:crypto";
305538
- import { closeSync as closeSync3, constants as constants2, fstatSync, fsyncSync, ftruncateSync, lstatSync as lstatSync3, openSync as openSync3, readFileSync as readFileSync7, readdirSync, readSync as readSync2, unlinkSync as unlinkSync3, writeFileSync as writeFileSync5 } from "node:fs";
305650
+ import { closeSync as closeSync3, constants as constants2, fstatSync, fsyncSync, ftruncateSync, lstatSync as lstatSync4, openSync as openSync3, readFileSync as readFileSync7, readdirSync, readSync as readSync2, unlinkSync as unlinkSync3, writeFileSync as writeFileSync5 } from "node:fs";
305539
305651
  import { chmod, cp, lstat as lstat2, mkdir, readdir as readdir2, realpath, rename, rm as rm2 } from "node:fs/promises";
305540
305652
  import { basename as basename8, dirname as dirname9, isAbsolute as isAbsolute7, join as join17, resolve as resolve11 } from "node:path";
305541
305653
  var NpmInstallBusyError = class extends Error {
@@ -305677,7 +305789,7 @@ function processIdentity(pid) {
305677
305789
  }
305678
305790
  }
305679
305791
  function readInstallOwner(path3) {
305680
- const before = lstatSync3(path3);
305792
+ const before = lstatSync4(path3);
305681
305793
  const valid = (value) => value.isFile() && !value.isSymbolicLink() && value.size > 0 && value.size <= 4096 && value.nlink === 1 && (process.platform === "win32" || value.uid === process.getuid?.() && (value.mode & 63) === 0);
305682
305794
  if (!valid(before)) throw new NpmInstallBusyError("The npm install owner record is unsafe or unknown; it was retained for inspection.");
305683
305795
  const fd = openSync3(path3, constants2.O_RDONLY | constants2.O_NOFOLLOW | constants2.O_NONBLOCK);
@@ -305720,9 +305832,9 @@ function provedAbsent(owner) {
305720
305832
  var ABANDONED_EMPTY_GUARD_MS = 6e4;
305721
305833
  function removeAbandonedEmptyGuard(guardPath) {
305722
305834
  try {
305723
- const metadata = lstatSync3(guardPath);
305835
+ const metadata = lstatSync4(guardPath);
305724
305836
  if (!metadata.isFile() || metadata.size !== 0 || metadata.nlink !== 1 || metadata.uid !== process.getuid?.() || (metadata.mode & 63) !== 0 || Date.now() - metadata.mtimeMs < ABANDONED_EMPTY_GUARD_MS) return false;
305725
- const current = lstatSync3(guardPath);
305837
+ const current = lstatSync4(guardPath);
305726
305838
  if (!sameIdentity(metadata, current) || current.size !== 0) return false;
305727
305839
  unlinkSync3(guardPath);
305728
305840
  return true;
@@ -305740,7 +305852,7 @@ async function acquireNpmInstallLease(modulesRoot, options = {}) {
305740
305852
  if (!sameIdentity(logicalMetadata, rootMetadata)) throw new Error("npm modules root changed before installer admission.");
305741
305853
  const lockPath = join17(root, ".omnius-install.lock"), guardPath = lockPath + ".guard", nonce = randomUUID4();
305742
305854
  const assertRoot = () => {
305743
- const current = lstatSync3(root);
305855
+ const current = lstatSync4(root);
305744
305856
  assertOwnedDirectory(current, "global modules root");
305745
305857
  if (!sameIdentity(rootMetadata, current)) throw new Error("npm modules root changed; no installer may proceed.");
305746
305858
  };
@@ -305767,7 +305879,7 @@ async function acquireNpmInstallLease(modulesRoot, options = {}) {
305767
305879
  } finally {
305768
305880
  try {
305769
305881
  if (!recorded) {
305770
- if (sameIdentity(metadata, lstatSync3(guardPath))) unlinkSync3(guardPath);
305882
+ if (sameIdentity(metadata, lstatSync4(guardPath))) unlinkSync3(guardPath);
305771
305883
  } else {
305772
305884
  const current = readInstallOwner(guardPath);
305773
305885
  if (sameIdentity(metadata, current.metadata) && current.owner.nonce === guardNonce) unlinkSync3(guardPath);
@@ -305857,7 +305969,7 @@ var REQUIRED_OMNIUS_RUNTIME_FILES = [
305857
305969
  "dist/update-worker-runtime.js"
305858
305970
  ];
305859
305971
  function hashOwnedFile(path3) {
305860
- const before = lstatSync3(path3);
305972
+ const before = lstatSync4(path3);
305861
305973
  const valid = (metadata) => metadata.isFile() && !metadata.isSymbolicLink() && metadata.size > 0 && metadata.size <= 128 * 1024 * 1024 && (process.platform === "win32" || metadata.uid === process.getuid?.() && (metadata.mode & 2) === 0);
305862
305974
  if (!valid(before)) throw new Error(`Omnius runtime file is missing or unsafe: ${path3}`);
305863
305975
  const fd = openSync3(path3, constants2.O_RDONLY | constants2.O_NOFOLLOW | constants2.O_NONBLOCK);
@@ -305887,10 +305999,10 @@ function inspectNpmRuntimeInstallation(packagePath) {
305887
305999
  return inspectRuntimeDirectory(canonical2, root);
305888
306000
  }
305889
306001
  function inspectRuntimeDirectory(canonical2, root) {
305890
- const before = lstatSync3(canonical2);
305891
- assertOwnedDirectory(lstatSync3(root), "global modules root");
306002
+ const before = lstatSync4(canonical2);
306003
+ assertOwnedDirectory(lstatSync4(root), "global modules root");
305892
306004
  assertOwnedDirectory(before, "Omnius package");
305893
- assertOwnedDirectory(lstatSync3(join17(canonical2, "dist")), "Omnius runtime");
306005
+ assertOwnedDirectory(lstatSync4(join17(canonical2, "dist")), "Omnius runtime");
305894
306006
  const files = {};
305895
306007
  for (const file of REQUIRED_OMNIUS_RUNTIME_FILES) files[file] = hashOwnedFile(join17(canonical2, file));
305896
306008
  const manifest = JSON.parse(readFileSync7(join17(canonical2, "package.json"), "utf8"));
@@ -305900,11 +306012,11 @@ function inspectRuntimeDirectory(canonical2, root) {
305900
306012
  if (typeof binTarget !== "string" || !/^[A-Za-z0-9_./-]+$/.test(binTarget) || isAbsolute7(binTarget) || binTarget.split("/").some((part) => !part || part === ".." || part === "."))
305901
306013
  throw new Error("Omnius runtime manifest has no safe declared omnius executable.");
305902
306014
  for (const directory of binTarget.split("/").slice(0, -1).reduce((paths, part) => [...paths, join17(paths.at(-1) ?? canonical2, part)], []))
305903
- assertOwnedDirectory(lstatSync3(directory), "Omnius executable directory");
306015
+ assertOwnedDirectory(lstatSync4(directory), "Omnius executable directory");
305904
306016
  files[binTarget] ??= hashOwnedFile(join17(canonical2, binTarget));
305905
306017
  if (!readFileSync7(join17(canonical2, "dist/update-worker.js"), "utf8").includes("omnius.update-worker-bootstrap.v2"))
305906
306018
  throw new Error("Omnius runtime has no compatible update worker bootstrap.");
305907
- if (hashOwnedFile(join17(canonical2, "package.json")) !== files["package.json"] || !sameIdentity(before, lstatSync3(canonical2)))
306019
+ if (hashOwnedFile(join17(canonical2, "package.json")) !== files["package.json"] || !sameIdentity(before, lstatSync4(canonical2)))
305908
306020
  throw new Error("Omnius package changed during runtime verification.");
305909
306021
  return {
305910
306022
  modulesRoot: root,
@@ -305979,19 +306091,19 @@ async function restoreVerifiedNpmInstallation(snapshot, options) {
305979
306091
  if (!validPath(path3)) return false;
305980
306092
  let metadata;
305981
306093
  try {
305982
- metadata = lstatSync3(path3);
306094
+ metadata = lstatSync4(path3);
305983
306095
  } catch (error) {
305984
306096
  if (error.code === "ENOENT") return false;
305985
306097
  throw error;
305986
306098
  }
305987
306099
  if (metadata.dev !== snapshot.device || metadata.ino !== snapshot.inode) return false;
305988
306100
  assertOwnedDirectory(metadata, "prior Omnius package");
305989
- assertOwnedDirectory(lstatSync3(join17(path3, "dist")), "prior Omnius runtime");
306101
+ assertOwnedDirectory(lstatSync4(join17(path3, "dist")), "prior Omnius runtime");
305990
306102
  for (const [file, digest3] of Object.entries(snapshot.files)) {
305991
306103
  if (!/^[A-Za-z0-9_./-]+$/.test(file) || isAbsolute7(file) || file.split("/").some((part) => !part || part === "." || part === "..") || hashOwnedFile(join17(path3, file)) !== digest3) throw new Error("Prior Omnius runtime changed; restoration was held.");
305992
306104
  }
305993
306105
  for (const directory of snapshot.binTarget.split("/").slice(0, -1).reduce((paths, part) => [...paths, join17(paths.at(-1) ?? path3, part)], []))
305994
- assertOwnedDirectory(lstatSync3(directory), "prior Omnius executable directory");
306106
+ assertOwnedDirectory(lstatSync4(directory), "prior Omnius executable directory");
305995
306107
  return true;
305996
306108
  };
305997
306109
  const source = [canonical2, retiredNpmPackagePath(canonical2), ...(options.backups ?? []).map((backup) => backup.backupPath)].find(matches);
@@ -306066,6 +306178,11 @@ async function removeVerifiedNpmRetirementBackup(backup) {
306066
306178
  }
306067
306179
 
306068
306180
  // packages/cli/src/update-service.ts
306181
+ var AutomaticUpdateDeferredError = class extends Error {
306182
+ constructor() {
306183
+ super("Automatic update deferred because the daemon has not confirmed it is idle.");
306184
+ }
306185
+ };
306069
306186
  var UpdateCancelledError = class extends Error {
306070
306187
  constructor(message = "Update cancelled. Package changes already made are retained; no rollback is claimed.") {
306071
306188
  super(message);
@@ -306084,7 +306201,7 @@ function watchUpdateCancellation(operationId, paths = resolveUpdatePaths()) {
306084
306201
  const check = () => {
306085
306202
  if (controller.signal.aborted) return;
306086
306203
  try {
306087
- const metadata = lstatSync4(path3);
306204
+ const metadata = lstatSync5(path3);
306088
306205
  if (!metadata.isFile() || metadata.isSymbolicLink() || metadata.size > 1024) return;
306089
306206
  const request = JSON.parse(readFileSync8(path3, "utf8"));
306090
306207
  const state = readUpdateState(paths);
@@ -306119,7 +306236,7 @@ function resolveUpdatePaths(env = process.env, platform2 = process.platform, hom
306119
306236
  function ensurePrivateDirectories(paths) {
306120
306237
  for (const path3 of [paths.stateDir, paths.cacheDir]) {
306121
306238
  mkdirSync7(path3, { recursive: true, mode: 448 });
306122
- const before = lstatSync4(path3);
306239
+ const before = lstatSync5(path3);
306123
306240
  if (!before.isDirectory() || before.isSymbolicLink() || process.platform !== "win32" && (before.uid !== process.getuid?.() || (before.mode & 18) !== 0)) throw new Error("Update coordination directories must be owned and not writable by other users");
306124
306241
  const fd = openSync4(path3, constants3.O_RDONLY | constants3.O_DIRECTORY | constants3.O_NOFOLLOW);
306125
306242
  try {
@@ -306134,7 +306251,7 @@ function ensurePrivateDirectories(paths) {
306134
306251
  function privateRecord(path3, limit = 4096) {
306135
306252
  let before;
306136
306253
  try {
306137
- before = lstatSync4(path3);
306254
+ before = lstatSync5(path3);
306138
306255
  } catch (error) {
306139
306256
  if (error.code === "ENOENT") return null;
306140
306257
  throw error;
@@ -306174,7 +306291,7 @@ function processIdentity2(pid) {
306174
306291
  }
306175
306292
  function interruptedGuardSnapshot(path3) {
306176
306293
  try {
306177
- const before = lstatSync4(path3), owner = privateRecord(path3), metadata = lstatSync4(path3);
306294
+ const before = lstatSync5(path3), owner = privateRecord(path3), metadata = lstatSync5(path3);
306178
306295
  if (!owner || before.dev !== metadata.dev || before.ino !== metadata.ino || !Number.isSafeInteger(owner.pid) || owner.pid <= 0 || typeof owner.nonce !== "string" || !/^[A-Za-z0-9_-]{1,128}$/.test(owner.nonce) || process.platform === "linux" && (typeof owner.process_identity !== "string" || !/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}:\d+$/i.test(owner.process_identity))) return null;
306179
306296
  return { owner, metadata };
306180
306297
  } catch {
@@ -306216,13 +306333,13 @@ function recoverInterruptedUpdateGuard(path3) {
306216
306333
  recorded = true;
306217
306334
  const current = interruptedGuardSnapshot(path3);
306218
306335
  if (!current || current.metadata.dev !== initial.metadata.dev || current.metadata.ino !== initial.metadata.ino || current.owner.nonce !== initial.owner.nonce || current.owner.pid !== initial.owner.pid || current.owner.process_identity !== initial.owner.process_identity || !guardOwnerIsProvablyDead(current.owner)) return false;
306219
- const final = lstatSync4(path3);
306336
+ const final = lstatSync5(path3);
306220
306337
  if (final.dev !== current.metadata.dev || final.ino !== current.metadata.ino) return false;
306221
306338
  unlinkSync4(path3);
306222
306339
  return true;
306223
306340
  } finally {
306224
306341
  try {
306225
- const current = lstatSync4(recoveryPath);
306342
+ const current = lstatSync5(recoveryPath);
306226
306343
  if (current.dev === claimed.dev && current.ino === claimed.ino && (!recorded || privateRecord(recoveryPath)?.nonce === nonce)) unlinkSync4(recoveryPath);
306227
306344
  } catch {
306228
306345
  }
@@ -306261,7 +306378,7 @@ function withUpdateOwnership(paths, mutation) {
306261
306378
  }
306262
306379
  const created = () => {
306263
306380
  try {
306264
- const current = lstatSync4(path3);
306381
+ const current = lstatSync5(path3);
306265
306382
  return current.ino === original.ino && current.dev === original.dev;
306266
306383
  } catch {
306267
306384
  return false;
@@ -306560,7 +306677,7 @@ async function quiesceDaemonWithRetry(quiesce, attempts = 3, pauseMs = 250) {
306560
306677
  try {
306561
306678
  if (await quiesce()) return true;
306562
306679
  } catch (error) {
306563
- if (error instanceof DaemonServiceAuthorizationError || error instanceof DaemonCheckpointInterruptedError) throw error;
306680
+ if (error instanceof DaemonServiceAuthorizationError || error instanceof DaemonCheckpointInterruptedError || error instanceof AutomaticUpdateDeferredError) throw error;
306564
306681
  }
306565
306682
  if (attempt < boundedAttempts && pauseMs > 0) {
306566
306683
  await new Promise((resolve13) => setTimeout(resolve13, pauseMs));
@@ -306600,11 +306717,11 @@ function restoreOmniusExecutableLink(prefix, installation) {
306600
306717
  }
306601
306718
  const directory = dirname10(executable);
306602
306719
  if (!existsSync8(directory)) mkdirSync7(directory, { recursive: false, mode: 493 });
306603
- const metadata = lstatSync4(directory);
306720
+ const metadata = lstatSync5(directory);
306604
306721
  if (!metadata.isDirectory() || metadata.isSymbolicLink() || metadata.uid !== process.getuid?.() || (metadata.mode & 2) !== 0)
306605
306722
  throw new Error("The Omnius executable directory is unsafe; no link was changed.");
306606
306723
  try {
306607
- const existing = lstatSync4(executable);
306724
+ const existing = lstatSync5(executable);
306608
306725
  if (!existing.isSymbolicLink() || existing.uid !== process.getuid?.() || resolve12(directory, readlinkSync2(executable)) !== target)
306609
306726
  throw new Error("A different executable occupies the Omnius bin path; it was retained.");
306610
306727
  } catch (error) {
@@ -306618,6 +306735,7 @@ async function runVerifiedUpdateTransaction(initial, dependencies, paths = resol
306618
306735
  let installStarted = false;
306619
306736
  let installerSettled = true;
306620
306737
  let packageVerified = false;
306738
+ let recoveryInstallation;
306621
306739
  let previousInstallation;
306622
306740
  let previousInstallationCopy;
306623
306741
  const retirementBackups = [];
@@ -306784,6 +306902,7 @@ async function runVerifiedUpdateTransaction(initial, dependencies, paths = resol
306784
306902
  const evidence = dependencies.inspectInstall ? await dependencies.inspectInstall(target, npmPath, env) : await inspectGlobalOmniusInstall(target, { npmPath, env, cwd });
306785
306903
  throwIfCancelled();
306786
306904
  packageVerified = true;
306905
+ recoveryInstallation = evidence;
306787
306906
  state = await transition(state, {
306788
306907
  phase: "package_verified",
306789
306908
  npm_prefix: evidence.npmPrefix,
@@ -306883,7 +307002,8 @@ async function runVerifiedUpdateTransaction(initial, dependencies, paths = resol
306883
307002
  return state;
306884
307003
  } catch (error) {
306885
307004
  if (cancelPublication) await cancelPublication;
306886
- const cancelled = error instanceof UpdateCancelledError || dependencies.signal?.aborted === true;
307005
+ const deferred = error instanceof AutomaticUpdateDeferredError;
307006
+ const cancelled = deferred || error instanceof UpdateCancelledError || dependencies.signal?.aborted === true;
306887
307007
  const message = error instanceof Error ? error.message : String(error);
306888
307008
  let recoveryNote;
306889
307009
  let packageRecoveryNote;
@@ -306923,6 +307043,7 @@ async function runVerifiedUpdateTransaction(initial, dependencies, paths = resol
306923
307043
  assertRecoveryOwned();
306924
307044
  if (verified.packageHash !== previousInstallation.packageHash) throw new Error("Restored Omnius manifest differs from the pre-install verification.");
306925
307045
  restoredPackageVerified = true;
307046
+ recoveryInstallation = verified;
306926
307047
  state = await transition(state, {
306927
307048
  package_recovery: { status: recovered.status, ...journal(recovered) },
306928
307049
  npm_recoveries: state.npm_recoveries?.map((item) => item.backup_path === recovered.sourcePath ? { ...item, status: "restored" } : item),
@@ -306944,6 +307065,7 @@ async function runVerifiedUpdateTransaction(initial, dependencies, paths = resol
306944
307065
  }
306945
307066
  }
306946
307067
  if (!cancelled && packageVerified && installerSettled && installLease && previousInstallation && previousInstallationCopy) {
307068
+ recoveryInstallation = void 0;
306947
307069
  state = await transition(state, { phase: "rolling_back" }, paths);
306948
307070
  try {
306949
307071
  const recovered = await restoreVerifiedNpmInstallation(previousInstallationCopy, {
@@ -306966,6 +307088,7 @@ async function runVerifiedUpdateTransaction(initial, dependencies, paths = resol
306966
307088
  const verified = await inspectGlobalOmniusInstall(previousInstallation.version, { npmPath, env, cwd });
306967
307089
  if (verified.packageHash !== previousInstallation.packageHash) throw new Error("the restored manifest differs from the pre-install verification");
306968
307090
  restoredPackageVerified = rolledBack = true;
307091
+ recoveryInstallation = verified;
306969
307092
  state = await transition(state, {
306970
307093
  rolled_back_to: verified.installedVersion,
306971
307094
  package_recovery: {
@@ -306989,10 +307112,20 @@ async function runVerifiedUpdateTransaction(initial, dependencies, paths = resol
306989
307112
  packageRecoveryNote = `Rollback could not be verified: ${detail}`;
306990
307113
  }
306991
307114
  }
306992
- if ((daemonQuiesced || rolledBack || unchangedPackage) && dependencies.recoverDaemon && installerSettled && (!installStarted || packageVerified || restoredPackageVerified)) {
307115
+ if ((daemonQuiesced || rolledBack || unchangedPackage) && dependencies.recoverDaemon && installerSettled && (!installStarted || recoveryInstallation)) {
306993
307116
  state = await transition(state, { phase: "recovering" }, paths);
306994
307117
  try {
306995
- const recovered = await dependencies.recoverDaemon(unchangedPackage && { version: unchangedPackage.version, packageHash: unchangedPackage.packageHash });
307118
+ if (!installStarted && previousInstallation) {
307119
+ const retained = await inspectGlobalOmniusInstall(previousInstallation.version, { npmPath, env, cwd });
307120
+ if (retained.packageHash !== previousInstallation.packageHash) throw new Error("The retained Omnius manifest changed before daemon recovery.");
307121
+ recoveryInstallation = retained;
307122
+ }
307123
+ const recoveryTarget = recoveryInstallation && {
307124
+ version: recoveryInstallation.installedVersion,
307125
+ packageHash: recoveryInstallation.packageHash,
307126
+ executablePath: recoveryInstallation.executablePath
307127
+ };
307128
+ const recovered = await dependencies.recoverDaemon(recoveryTarget);
306996
307129
  recoveryNote = recovered ? "The daemon was restarted after the interrupted update." : "The daemon could not be recovered automatically after the failed update.";
306997
307130
  if (rolledBack && state.tray_was_running && dependencies.restartTray && state.global_executable) {
306998
307131
  recoveryNote += await dependencies.restartTray(state.global_executable).catch(() => false) ? " The indicator was relaunched on the restored version." : " The indicator could not be relaunched on the restored version.";
@@ -307007,7 +307140,8 @@ async function runVerifiedUpdateTransaction(initial, dependencies, paths = resol
307007
307140
  status: cancelled ? "cancelled" : "failed",
307008
307141
  phase: cancelled ? "cancelled" : "failed",
307009
307142
  completed_at: (/* @__PURE__ */ new Date()).toISOString(),
307010
- error: cancelled ? installerSettled ? "Update cancelled after the owned operation settled." : "Update cancellation requested; owned installer shutdown could not be confirmed." : message,
307143
+ ...deferred ? { automatic_deferred: true } : {},
307144
+ error: cancelled && !deferred ? installerSettled ? "Update cancelled after the owned operation settled." : "Update cancellation requested; owned installer shutdown could not be confirmed." : message,
307011
307145
  remediation: [
307012
307146
  packageRecoveryNote,
307013
307147
  cancelled && installStarted && !restoredPackageVerified ? "Package files may have changed. No rollback was performed; verify the installed version before retrying." : void 0,
@@ -307578,7 +307712,7 @@ var PROVIDER_PRESETS = [
307578
307712
  ];
307579
307713
 
307580
307714
  // packages/cli/src/provider-credentials.ts
307581
- import { constants as constants4, closeSync as closeSync5, existsSync as existsSync9, fstatSync as fstatSync3, fsyncSync as fsyncSync3, lstatSync as lstatSync5, mkdirSync as mkdirSync8, openSync as openSync5, readFileSync as readFileSync9, readdirSync as readdirSync2, renameSync as renameSync6, unlinkSync as unlinkSync5, writeFileSync as writeFileSync7 } from "node:fs";
307715
+ import { constants as constants4, closeSync as closeSync5, existsSync as existsSync9, fstatSync as fstatSync3, fsyncSync as fsyncSync3, lstatSync as lstatSync6, mkdirSync as mkdirSync8, openSync as openSync5, readFileSync as readFileSync9, readdirSync as readdirSync2, renameSync as renameSync6, unlinkSync as unlinkSync5, writeFileSync as writeFileSync7 } from "node:fs";
307582
307716
  var NOFOLLOW = constants4.O_NOFOLLOW ?? 0;
307583
307717
 
307584
307718
  // packages/cli/src/config.ts
@@ -308047,6 +308181,26 @@ async function launchDetachedTray(executable, endpoint) {
308047
308181
  }
308048
308182
  async function runUpdateWorkerRuntime(state, paths, endpoint) {
308049
308183
  const cancellation = watchUpdateCancellation(state.operation_id, paths);
308184
+ let idleHandoffRequested = false;
308185
+ const requestIdleHandoff = async (method) => {
308186
+ const url = new URL("/v1/update/idle-handoff", endpoint);
308187
+ if (!["127.0.0.1", "localhost", "[::1]"].includes(url.hostname) || url.username || url.password || url.protocol !== "http:" && url.protocol !== "https:") throw new AutomaticUpdateDeferredError();
308188
+ if (!state.automatic_handoff_token) throw new AutomaticUpdateDeferredError();
308189
+ const response = await fetch(url, {
308190
+ method,
308191
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${state.automatic_handoff_token}` },
308192
+ body: JSON.stringify({ operation_id: state.operation_id }),
308193
+ redirect: "error",
308194
+ signal: AbortSignal.timeout(method === "POST" ? 8e3 : 1e3)
308195
+ }).catch((error) => {
308196
+ if (error?.cause?.code === "ECONNREFUSED") return null;
308197
+ throw new AutomaticUpdateDeferredError();
308198
+ });
308199
+ if (method === "POST" && response) {
308200
+ const receipt = response.ok ? await response.json().catch(() => null) : null;
308201
+ if (receipt?.idle !== true || receipt.operation_id !== state.operation_id) throw new AutomaticUpdateDeferredError();
308202
+ }
308203
+ };
308050
308204
  try {
308051
308205
  const port = Number(new URL(endpoint).port || "11435");
308052
308206
  const trayWasRunning = state.tray_was_running || !cancellation.signal.aborted && (await getTrayStatus(endpoint)).running;
@@ -308057,13 +308211,18 @@ async function runUpdateWorkerRuntime(state, paths, endpoint) {
308057
308211
  {
308058
308212
  quiesceDaemon: async () => {
308059
308213
  if (daemonScope === void 0) daemonScope = (await discoverDaemonServiceAtPort(port))?.scope ?? null;
308214
+ if (state.automatic === true) {
308215
+ idleHandoffRequested = true;
308216
+ await requestIdleHandoff("POST");
308217
+ if (cancellation.signal.aborted) return false;
308218
+ }
308060
308219
  return quiesceDaemonForUpdate(port, daemonScope);
308061
308220
  },
308062
308221
  restartDaemon: (expected, executable) => restartDaemon(port, expected, executable, daemonScope),
308063
- recoverDaemon: async (unchangedPackage) => {
308064
- await restartDaemon(port, unchangedPackage?.version, void 0, daemonScope);
308222
+ recoverDaemon: async (target) => {
308223
+ await restartDaemon(port, target?.version, target?.executablePath, daemonScope);
308065
308224
  const ready = await getDaemonReportedIdentity(port);
308066
- return Boolean(ready && (!unchangedPackage || ready.bootVersion === unchangedPackage.version && ready.bootPackageHash === unchangedPackage.packageHash));
308225
+ return Boolean(ready && (!target || ready.bootVersion === target.version && ready.bootPackageHash === target.packageHash));
308067
308226
  },
308068
308227
  observeDaemon: async () => {
308069
308228
  const identity = await getDaemonReportedIdentity(port);
@@ -308081,6 +308240,7 @@ async function runUpdateWorkerRuntime(state, paths, endpoint) {
308081
308240
  );
308082
308241
  return finalState;
308083
308242
  } finally {
308243
+ if (idleHandoffRequested) await requestIdleHandoff("DELETE").catch(() => void 0);
308084
308244
  cancellation.close();
308085
308245
  }
308086
308246
  }