@qilin-agent/desktop 0.0.0-stage → 3.1.6

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 (77) hide show
  1. package/LICENSE +21 -0
  2. package/README.i18n.yaml +79 -0
  3. package/README.md +383 -2
  4. package/README.zh.md +384 -0
  5. package/lib/command-manager-entry.js +554 -0
  6. package/lib/main.js +11534 -0
  7. package/lib/types/account-backend.d.ts +37 -0
  8. package/lib/types/account-types.d.ts +74 -0
  9. package/lib/types/backend-controller.d.ts +59 -0
  10. package/lib/types/background-notice.d.ts +29 -0
  11. package/lib/types/browser-bridge-types.d.ts +26 -0
  12. package/lib/types/browser-guests.d.ts +33 -0
  13. package/lib/types/client-metadata.d.ts +15 -0
  14. package/lib/types/command-installation.d.ts +54 -0
  15. package/lib/types/command-management.d.ts +46 -0
  16. package/lib/types/command-manager-entry.d.ts +3 -0
  17. package/lib/types/core-package-set.d.ts +51 -0
  18. package/lib/types/crash-report.d.ts +92 -0
  19. package/lib/types/desktop-home.d.ts +12 -0
  20. package/lib/types/device-info.d.ts +8 -0
  21. package/lib/types/directory-picker.d.ts +8 -0
  22. package/lib/types/duration-env.d.ts +10 -0
  23. package/lib/types/fatal-recovery.d.ts +37 -0
  24. package/lib/types/host-process.d.ts +97 -0
  25. package/lib/types/host-protocol.d.ts +4 -0
  26. package/lib/types/ipc.d.ts +78 -0
  27. package/lib/types/keybindings.d.ts +11 -0
  28. package/lib/types/keyboard.d.ts +40 -0
  29. package/lib/types/local-auth.d.ts +22 -0
  30. package/lib/types/locale.d.ts +407 -0
  31. package/lib/types/login-shell-environment.d.ts +66 -0
  32. package/lib/types/main.d.ts +2 -0
  33. package/lib/types/mandatory-update-ipc.d.ts +7 -0
  34. package/lib/types/mandatory-update-policy.d.ts +83 -0
  35. package/lib/types/mandatory-update-window.d.ts +90 -0
  36. package/lib/types/microphone-permissions.d.ts +9 -0
  37. package/lib/types/node-environment.d.ts +10 -0
  38. package/lib/types/owned-directory.d.ts +8 -0
  39. package/lib/types/paths.d.ts +13 -0
  40. package/lib/types/platform-ipc.d.ts +12 -0
  41. package/lib/types/platform-view.d.ts +77 -0
  42. package/lib/types/policy-test-auth.d.ts +49 -0
  43. package/lib/types/preload-app.d.ts +3 -0
  44. package/lib/types/preload-browser.d.ts +4 -0
  45. package/lib/types/preload-mandatory-overlay.d.ts +3 -0
  46. package/lib/types/preload-mandatory.d.ts +2 -0
  47. package/lib/types/preload-menu.d.ts +9 -0
  48. package/lib/types/preload-platform-account.d.ts +2 -0
  49. package/lib/types/preload-platform.d.ts +13 -0
  50. package/lib/types/preload-theme.d.ts +12 -0
  51. package/lib/types/preload-update-dialog.d.ts +2 -0
  52. package/lib/types/preload-welcome.d.ts +2 -0
  53. package/lib/types/preload-windows.d.ts +3 -0
  54. package/lib/types/project-manager.d.ts +39 -0
  55. package/lib/types/quit-confirmation.d.ts +47 -0
  56. package/lib/types/release.d.ts +14 -0
  57. package/lib/types/runtime-tree.d.ts +70 -0
  58. package/lib/types/settings.d.ts +13 -0
  59. package/lib/types/single-instance.d.ts +15 -0
  60. package/lib/types/startup-error.d.ts +11 -0
  61. package/lib/types/tray.d.ts +24 -0
  62. package/lib/types/update-attention.d.ts +28 -0
  63. package/lib/types/update-channel.d.ts +10 -0
  64. package/lib/types/update-coordinator.d.ts +60 -0
  65. package/lib/types/update-dialog.d.ts +69 -0
  66. package/lib/types/update-error.d.ts +14 -0
  67. package/lib/types/update-http-executor.d.ts +14 -0
  68. package/lib/types/update-journal.d.ts +35 -0
  69. package/lib/types/update-overlay.d.ts +23 -0
  70. package/lib/types/update-presentation.d.ts +16 -0
  71. package/lib/types/update-schedule.d.ts +47 -0
  72. package/lib/types/web-document.d.ts +69 -0
  73. package/lib/types/welcome-api.d.ts +86 -0
  74. package/lib/types/welcome-backend.d.ts +36 -0
  75. package/lib/types/welcome-window.d.ts +19 -0
  76. package/lib/types/windows-layout.d.ts +4 -0
  77. package/package.json +98 -3
@@ -0,0 +1,554 @@
1
+ import { execFile, spawn } from "node:child_process";
2
+ import { basename, dirname, isAbsolute, join, resolve } from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ import { createHash, randomBytes, randomUUID } from "node:crypto";
5
+ import { constants } from "node:fs";
6
+ import { access, link, lstat, mkdir, readFile, readlink, rename, rm, stat, symlink, unlink, writeFile } from "node:fs/promises";
7
+ import { promisify } from "node:util";
8
+ import { setTimeout as setTimeout$1 } from "node:timers/promises";
9
+ //#region ../../packages/util/atomic-write/lib/index.js
10
+ /**
11
+ * Zero-dependency atomic file replacement and writer coordination.
12
+ * `writeFileAtomic` writes a random-suffix sibling with exclusive create and
13
+ * the caller's permission bits, then renames it over the target, so readers
14
+ * observe either the old or the new complete content and a replaced file ends
15
+ * up with exactly the stated mode. `withFileLock` serializes cross-process
16
+ * writers of one file through a `wx`-created `<file>.lock` sibling, so a
17
+ * read-modify-write cycle can never resurrect a state another writer just
18
+ * replaced; readers stay lock-free because the rename commit is atomic. A lock
19
+ * whose recorded holder process no longer exists is taken over.
20
+ * @module @qilin-agent/atomic-write
21
+ */
22
+ const WINDOWS_TRANSIENT_RENAME_ERRORS = new Set([
23
+ "EACCES",
24
+ "EBUSY",
25
+ "EPERM"
26
+ ]);
27
+ const WINDOWS_RENAME_RETRY_INITIAL_MS = 20;
28
+ const WINDOWS_RENAME_RETRY_MAX_MS = 200;
29
+ const WINDOWS_RENAME_RETRY_LIMIT = 8;
30
+ /** Whether Windows reported temporary interference with an atomic replacement. */
31
+ function isTransientWindowsRenameError(error) {
32
+ if (process.platform !== "win32") return false;
33
+ return WINDOWS_TRANSIENT_RENAME_ERRORS.has(error?.code ?? "");
34
+ }
35
+ /** Replace the target after bounded retries for transient Windows interference. */
36
+ async function renameAtomicTemp(temp, filename) {
37
+ let delay = WINDOWS_RENAME_RETRY_INITIAL_MS;
38
+ for (let retries = 0;; retries += 1) {
39
+ try {
40
+ await rename(temp, filename);
41
+ return;
42
+ } catch (error) {
43
+ if (!isTransientWindowsRenameError(error)) throw error;
44
+ if (retries >= WINDOWS_RENAME_RETRY_LIMIT) throw error;
45
+ }
46
+ await new Promise((resolve) => setTimeout(resolve, delay));
47
+ delay = Math.min(delay * 2, WINDOWS_RENAME_RETRY_MAX_MS);
48
+ }
49
+ }
50
+ /**
51
+ * Replace `filename` with `content` in one atomic step, creating parent
52
+ * directories. The content is first written to a random-suffix sibling opened
53
+ * with exclusive create (`wx`): the open refuses to follow a symlink planted
54
+ * at the temp path, and the fresh inode carries `options.mode` through the
55
+ * rename, so replacing a wider-permission file narrows it without a chmod
56
+ * race. The rename also replaces a symlinked target itself instead of writing
57
+ * through to its referent, and the same-directory sibling keeps the rename on
58
+ * one filesystem. Windows replacement retries transient `EACCES`, `EBUSY`,
59
+ * and `EPERM` failures for a bounded interval while the complete temp file
60
+ * remains the rename source. On any remaining failure the temp file is
61
+ * removed and the failure rethrown. Crash durability (fsync) is out of scope.
62
+ * @param filename - final path receiving the content.
63
+ * @param content - complete next file content.
64
+ * @param options - permission bits for the replacement inode.
65
+ */
66
+ async function writeFileAtomic(filename, content, options) {
67
+ await mkdir(dirname(filename), {
68
+ recursive: true,
69
+ ...options.dirMode === void 0 ? {} : { mode: options.dirMode }
70
+ });
71
+ const temp = `${filename}.${randomBytes(6).toString("hex")}.tmp`;
72
+ try {
73
+ await writeFile(temp, content, {
74
+ mode: options.mode,
75
+ flag: "wx"
76
+ });
77
+ await renameAtomicTemp(temp, filename);
78
+ } catch (error) {
79
+ await rm(temp, { force: true });
80
+ throw error;
81
+ }
82
+ }
83
+ /** Whether an exclusive create found an existing lock. */
84
+ async function isLockContention(error, lockPath) {
85
+ const code = error?.code;
86
+ if (code === "EEXIST") return true;
87
+ if (code !== "EPERM") return false;
88
+ try {
89
+ await lstat(lockPath);
90
+ return true;
91
+ } catch {
92
+ return false;
93
+ }
94
+ }
95
+ /** Whether the holder a `<pid>\n` record names is proven gone: a signal probe finds no such process. */
96
+ function holderExited(record) {
97
+ if (!/^\d+\n$/.test(record)) return false;
98
+ const pid = Number(record.trim());
99
+ if (pid === 0 || pid > 2147483647) return false;
100
+ if (pid === process.pid) return false;
101
+ try {
102
+ process.kill(pid, 0);
103
+ return false;
104
+ } catch (error) {
105
+ return error.code === "ESRCH";
106
+ }
107
+ }
108
+ /** The lock file's content, or undefined when it cannot be read. */
109
+ async function readLockRecord(lockPath) {
110
+ try {
111
+ return await readFile(lockPath, "utf8");
112
+ } catch (error) {
113
+ return;
114
+ }
115
+ }
116
+ /**
117
+ * Remove the lock when its recorded holder exited. Contenders that read the
118
+ * same record serialize on a claim file named after it. Under the claim, the
119
+ * claimant re-reads the lock and probes its PID again, and removes it only
120
+ * when it still holds that record and that PID is still gone: the record's
121
+ * holder can no longer release it, and no other contender can remove it
122
+ * without the claim, so a removal never deletes a lock another contender
123
+ * acquired after the dead holder's, including one whose holder reused the PID.
124
+ * @returns Whether this call removed the dead holder's lock.
125
+ */
126
+ async function takeOverExitedLock(lockPath) {
127
+ const record = await readLockRecord(lockPath);
128
+ if (record === void 0 || !holderExited(record)) return false;
129
+ const claim = `${lockPath}.takeover-${createHash("sha256").update(record).digest("hex").slice(0, 16)}`;
130
+ try {
131
+ await writeFile(claim, `${process.pid}\n`, {
132
+ mode: 384,
133
+ flag: "wx"
134
+ });
135
+ } catch (error) {
136
+ const code = error.code;
137
+ if (code === "EEXIST" || code === "EPERM") return false;
138
+ throw error;
139
+ }
140
+ try {
141
+ if (await readLockRecord(lockPath) !== record || !holderExited(record)) return false;
142
+ try {
143
+ await rm(lockPath, { force: true });
144
+ } catch (error) {
145
+ return false;
146
+ }
147
+ return true;
148
+ } finally {
149
+ await rm(claim, { force: true }).catch((error) => {});
150
+ }
151
+ }
152
+ /**
153
+ * Retry cadence for a contended lock. These stay robustness invariants of the
154
+ * cross-process write protocol rather than deployment tunables: they govern how
155
+ * often a contender asks, which no caller has a reason to vary.
156
+ */
157
+ const LOCK_RETRY_INITIAL_MS = 20;
158
+ const LOCK_RETRY_MAX_MS = 200;
159
+ /**
160
+ * How long a contender waits when the caller states no limit — sized for the
161
+ * render-and-rename cycle every call site had when this package was written.
162
+ * Expiry fails the contender rather than guessing whether the existing lock
163
+ * still has an owner. How long is *worth* waiting is a property of the
164
+ * operation the lock holder runs, which is why {@link FileLockOptions.waitMs}
165
+ * exists; the value here is the floor for an operation that does file work
166
+ * alone.
167
+ */
168
+ const DEFAULT_LOCK_WAIT_MS = 2e3;
169
+ /**
170
+ * Hold the cross-process writer lock for `filename` around one operation. The
171
+ * lock is a `wx`-created sibling (`<filename>.lock`); paired with the
172
+ * rename-based commit of {@link writeFileAtomic}, readers stay lock-free and
173
+ * only writers contend. `EEXIST` is contention directly; an `EPERM` is
174
+ * contention only when a fresh `lstat` confirms the lock path exists, covering
175
+ * Windows exclusive-create behavior. Windows retries one unconfirmed EPERM
176
+ * because the holder can release before the probe; a repeated unconfirmed
177
+ * permission error is rethrown. The lock records its holder's PID. A contender
178
+ * removes the lock and retries at once when no process with that PID exists
179
+ * (`ESRCH`); any other lock, including one whose holder exists under another
180
+ * user (`EPERM`) or whose record is incomplete, is waited for. Contention backs
181
+ * off exponentially and times out after the deadline. A holder whose PID a
182
+ * live process reused keeps its lock until an operator removes it. Takeover
183
+ * proves only that the recorded process exited: an operation that starts other
184
+ * writers must stop them with it or leave its successor a way to find them.
185
+ * PIDs are compared on the contender's host, so writers on other hosts or in
186
+ * other PID namespaces sharing the file are unsupported and could both hold
187
+ * the lock. The parent directory must exist.
188
+ * @param filename - the file whose writers this lock serializes.
189
+ * @param operation - the read-render-commit cycle to run while holding the lock.
190
+ * @param options - acquisition options; omitted waits {@link DEFAULT_LOCK_WAIT_MS}.
191
+ * @returns the operation's result; the lock releases on both outcomes.
192
+ */
193
+ async function withFileLock(filename, operation, options) {
194
+ const lockPath = `${filename}.lock`;
195
+ const deadline = Date.now() + (options?.waitMs ?? DEFAULT_LOCK_WAIT_MS);
196
+ let delay = LOCK_RETRY_INITIAL_MS;
197
+ let retriedUnconfirmedPermissionError = false;
198
+ for (;;) {
199
+ options?.signal?.throwIfAborted();
200
+ try {
201
+ await writeFile(lockPath, `${process.pid}\n`, {
202
+ mode: 384,
203
+ flag: "wx"
204
+ });
205
+ break;
206
+ } catch (error) {
207
+ if (!await isLockContention(error, lockPath)) {
208
+ if (process.platform !== "win32" || error?.code !== "EPERM" || retriedUnconfirmedPermissionError) throw error;
209
+ retriedUnconfirmedPermissionError = true;
210
+ } else if (await takeOverExitedLock(lockPath)) continue;
211
+ }
212
+ if (Date.now() >= deadline) throw new Error(`atomic-write: timed out waiting for the writer lock at ${lockPath}`);
213
+ await setTimeout$1(delay, void 0, { signal: options?.signal });
214
+ delay = Math.min(delay * 2, LOCK_RETRY_MAX_MS);
215
+ }
216
+ try {
217
+ options?.signal?.throwIfAborted();
218
+ return await operation();
219
+ } finally {
220
+ await rm(lockPath, { force: true });
221
+ }
222
+ }
223
+ //#endregion
224
+ //#region lib/types/command-installation.js
225
+ /** Reversible command-link ownership; operations never follow or overwrite a changed command entry. */
226
+ /** A declined stale operation or a command entry outside this installer's ownership. */
227
+ var CommandInstallationError = class extends Error {
228
+ code;
229
+ constructor(code, message) {
230
+ super(message);
231
+ this.code = code;
232
+ }
233
+ };
234
+ function digest(value) {
235
+ return createHash("sha256").update(JSON.stringify(value)).digest("hex");
236
+ }
237
+ function receiptPath(options) {
238
+ return join(dirname(options.destination), ".qilin-desktop-command.json");
239
+ }
240
+ async function readEntry(path) {
241
+ let info;
242
+ try {
243
+ info = await lstat(path, { bigint: true });
244
+ } catch (error) {
245
+ if (error.code === "ENOENT") return {
246
+ kind: "missing",
247
+ fingerprint: digest("missing")
248
+ };
249
+ throw error;
250
+ }
251
+ const fields = [
252
+ info.dev,
253
+ info.ino,
254
+ info.mode,
255
+ info.uid,
256
+ info.gid,
257
+ info.size,
258
+ info.mtimeNs
259
+ ].map(String);
260
+ if (info.isSymbolicLink()) {
261
+ const target = await readlink(path);
262
+ return {
263
+ kind: "symlink",
264
+ fingerprint: digest({
265
+ kind: "symlink",
266
+ fields,
267
+ target
268
+ }),
269
+ target
270
+ };
271
+ }
272
+ const kind = info.isFile() ? "file" : "unsupported";
273
+ return {
274
+ kind,
275
+ fingerprint: digest({
276
+ kind,
277
+ fields
278
+ })
279
+ };
280
+ }
281
+ async function readReceipt(options) {
282
+ const path = receiptPath(options);
283
+ let info;
284
+ try {
285
+ info = await lstat(path);
286
+ } catch (error) {
287
+ if (error.code === "ENOENT") return void 0;
288
+ throw error;
289
+ }
290
+ if (!info.isFile() || info.size > 8192) throw new CommandInstallationError("EOWNERSHIP", "Invalid command ownership record.");
291
+ let value;
292
+ try {
293
+ value = JSON.parse(await readFile(path, "utf8"));
294
+ } catch (error) {
295
+ if (!(error instanceof SyntaxError)) throw error;
296
+ throw new CommandInstallationError("EOWNERSHIP", "Invalid command ownership record.");
297
+ }
298
+ if (typeof value !== "object" || value === null || Array.isArray(value)) throw new CommandInstallationError("EOWNERSHIP", "Invalid command ownership record.");
299
+ const record = value;
300
+ if (record.schemaVersion !== 1 || typeof record.launcher !== "string" || !isAbsolute(record.launcher) || typeof record.installedFingerprint !== "string" || !/^[a-f0-9]{64}$/u.test(record.installedFingerprint)) throw new CommandInstallationError("EOWNERSHIP", "Invalid command ownership record.");
301
+ let backup;
302
+ if (record.backup !== void 0) {
303
+ if (typeof record.backup !== "object" || record.backup === null) throw new CommandInstallationError("EOWNERSHIP", "Invalid command backup record.");
304
+ const candidate = record.backup;
305
+ if (typeof candidate.name !== "string" || !/^\.dsh-command-backup-[a-f0-9-]{36}$/u.test(candidate.name) || typeof candidate.fingerprint !== "string" || !/^[a-f0-9]{64}$/u.test(candidate.fingerprint)) throw new CommandInstallationError("EOWNERSHIP", "Invalid command backup record.");
306
+ backup = {
307
+ name: candidate.name,
308
+ fingerprint: candidate.fingerprint
309
+ };
310
+ }
311
+ return {
312
+ schemaVersion: 1,
313
+ launcher: record.launcher,
314
+ installedFingerprint: record.installedFingerprint,
315
+ ...backup === void 0 ? {} : { backup }
316
+ };
317
+ }
318
+ async function available(path) {
319
+ try {
320
+ await access(path, constants.X_OK);
321
+ return (await stat(path)).isFile();
322
+ } catch (error) {
323
+ if (["ENOENT", "EACCES"].includes(error.code ?? "")) return false;
324
+ throw error;
325
+ }
326
+ }
327
+ async function readSnapshot(options) {
328
+ const entry = await readEntry(options.destination);
329
+ const receipt = await readReceipt(options);
330
+ return {
331
+ entry,
332
+ receipt,
333
+ state: {
334
+ fingerprint: digest({
335
+ entry: entry.fingerprint,
336
+ receipt
337
+ }),
338
+ destination: options.destination,
339
+ launcher: options.launcher,
340
+ kind: entry.kind,
341
+ managed: receipt !== void 0 && entry.kind === "symlink" && entry.target === receipt.launcher && entry.fingerprint === receipt.installedFingerprint,
342
+ available: await available(options.destination),
343
+ ...entry.kind === "symlink" ? { target: entry.target } : {},
344
+ ...receipt?.backup === void 0 ? {} : { backup: join(dirname(options.destination), receipt.backup.name) }
345
+ }
346
+ };
347
+ }
348
+ /**
349
+ * Read the command and receipt without changing either.
350
+ * @param options - Fixed command destination and current installed launcher.
351
+ * @returns A fingerprint to bind a later user decision to the observed entries.
352
+ */
353
+ async function inspectFileCommand(options) {
354
+ return (await readSnapshot(options)).state;
355
+ }
356
+ async function restoreEntry(options, source, destination, expected) {
357
+ const entry = await readEntry(source);
358
+ if (expected !== void 0 && entry.fingerprint !== expected) throw new CommandInstallationError("EOWNERSHIP", "Command backup changed.");
359
+ if (entry.kind !== "symlink" && entry.kind !== "file") throw new CommandInstallationError("EOWNERSHIP", "Command backup is unavailable.");
360
+ if (expected !== void 0) {
361
+ const claimed = await withdraw(options, source, entry);
362
+ if (claimed === void 0) throw new CommandInstallationError("EOWNERSHIP", "Command backup is unavailable.");
363
+ try {
364
+ await restoreEntry(options, claimed, destination);
365
+ } catch (error) {
366
+ try {
367
+ await restoreEntry(options, claimed, source);
368
+ } catch (restoreError) {
369
+ throw new AggregateError([error, restoreError], "The command backup is preserved at " + claimed);
370
+ }
371
+ throw error;
372
+ }
373
+ return;
374
+ }
375
+ await linkEntry(options, source, destination);
376
+ if ((await readEntry(destination)).fingerprint !== entry.fingerprint) throw new CommandInstallationError("EOWNERSHIP", "Command backup changed during restoration.");
377
+ await unlink(source);
378
+ }
379
+ async function linkEntry(options, source, destination) {
380
+ if (process.platform === "darwin") await promisify(execFile)(options.linkHelper, [source, destination]);
381
+ else await link(source, destination);
382
+ }
383
+ async function withdraw(options, destination, expected) {
384
+ if (expected.kind === "missing") return void 0;
385
+ if (expected.kind === "unsupported") throw new CommandInstallationError("EUNSUPPORTED", "The command path is not a file or symbolic link.");
386
+ const path = join(dirname(destination), ".dsh-command-backup-" + randomUUID());
387
+ await rename(destination, path);
388
+ if ((await readEntry(path)).fingerprint !== expected.fingerprint) {
389
+ try {
390
+ await restoreEntry(options, path, destination);
391
+ } catch (error) {
392
+ throw new AggregateError([error], "The command changed; its entry is preserved at " + path);
393
+ }
394
+ throw new CommandInstallationError("ESTALE", "The command changed after confirmation.");
395
+ }
396
+ return path;
397
+ }
398
+ /**
399
+ * Install or repair a link, keeping the previous launcher available for removal.
400
+ * @param options - Fixed command destination and current installed launcher.
401
+ * @param expected - Fingerprint displayed in the user's confirmation.
402
+ * @returns Updated state and any older backup preserved after an external command replacement.
403
+ */
404
+ async function installFileCommand(options, expected) {
405
+ await mkdir(dirname(options.destination), { recursive: true });
406
+ return withFileLock(receiptPath(options), async () => {
407
+ const { state, entry, receipt } = await readSnapshot(options);
408
+ if (state.fingerprint !== expected) throw new CommandInstallationError("ESTALE", "The command changed after confirmation.");
409
+ if (!await available(options.launcher)) throw new CommandInstallationError("ENOENT", "The installed launcher is unavailable.");
410
+ const moved = await withdraw(options, options.destination, entry);
411
+ const pending = join(dirname(options.destination), ".dsh-command-new-" + randomUUID());
412
+ let created;
413
+ try {
414
+ await symlink(options.launcher, pending);
415
+ created = await readEntry(pending);
416
+ await linkEntry(options, pending, options.destination);
417
+ const backup = state.managed || moved === void 0 ? receipt?.backup : {
418
+ name: basename(moved),
419
+ fingerprint: entry.fingerprint
420
+ };
421
+ const next = {
422
+ schemaVersion: 1,
423
+ launcher: options.launcher,
424
+ installedFingerprint: created.fingerprint,
425
+ ...backup === void 0 ? {} : { backup }
426
+ };
427
+ await writeFileAtomic(receiptPath(options), JSON.stringify(next) + "\n", { mode: 420 });
428
+ } catch (error) {
429
+ if (created !== void 0 && (await readEntry(options.destination)).fingerprint === created.fingerprint) {
430
+ const rollback = await withdraw(options, options.destination, created);
431
+ if (rollback !== void 0) await unlink(rollback);
432
+ }
433
+ if (moved !== void 0) try {
434
+ await restoreEntry(options, moved, options.destination, entry.fingerprint);
435
+ } catch (restoreError) {
436
+ throw new AggregateError([error, restoreError], "The previous command is preserved at " + moved);
437
+ }
438
+ throw error;
439
+ } finally {
440
+ try {
441
+ await unlink(pending);
442
+ } catch (error) {
443
+ if (error.code !== "ENOENT") throw error;
444
+ }
445
+ }
446
+ if (state.managed && moved !== void 0) await unlink(moved);
447
+ const result = await inspectFileCommand(options);
448
+ const previousBackup = receipt?.backup === void 0 ? void 0 : join(dirname(options.destination), receipt.backup.name);
449
+ return previousBackup !== void 0 && !state.managed && moved !== void 0 && (await readEntry(previousBackup)).kind !== "missing" ? {
450
+ ...result,
451
+ preservedBackup: previousBackup
452
+ } : result;
453
+ }, { waitMs: 5e3 });
454
+ }
455
+ /**
456
+ * Remove only a recorded Desktop link and restore its unchanged previous entry.
457
+ * @param options - Fixed command destination and current installed launcher.
458
+ * @param expected - Fingerprint displayed when removal was requested.
459
+ * @returns State after removal; an externally replaced command remains untouched.
460
+ */
461
+ async function removeFileCommand(options, expected) {
462
+ return withFileLock(receiptPath(options), async () => {
463
+ const { state, entry, receipt } = await readSnapshot(options);
464
+ if (state.fingerprint !== expected) throw new CommandInstallationError("ESTALE", "The command changed after confirmation.");
465
+ if (receipt === void 0) return state;
466
+ const backup = receipt.backup === void 0 ? void 0 : join(dirname(options.destination), receipt.backup.name);
467
+ if (state.managed && backup !== void 0 && receipt.backup !== void 0 && (await readEntry(backup)).fingerprint !== receipt.backup.fingerprint) throw new CommandInstallationError("EOWNERSHIP", "The previous command backup changed or is missing.");
468
+ if (state.managed) {
469
+ const removed = await withdraw(options, options.destination, entry);
470
+ try {
471
+ if (backup !== void 0) await restoreEntry(options, backup, options.destination, receipt.backup?.fingerprint);
472
+ await unlink(receiptPath(options));
473
+ } catch (error) {
474
+ if (removed !== void 0) try {
475
+ if ((await readEntry(options.destination)).kind === "missing") await restoreEntry(options, removed, options.destination, entry.fingerprint);
476
+ else await unlink(removed);
477
+ } catch (restoreError) {
478
+ throw new AggregateError([error, restoreError], "The Desktop command link is preserved at " + removed);
479
+ }
480
+ throw error;
481
+ }
482
+ if (removed !== void 0) await unlink(removed);
483
+ } else await unlink(receiptPath(options));
484
+ const result = await inspectFileCommand(options);
485
+ return !state.managed && backup !== void 0 && (await readEntry(backup)).kind !== "missing" ? {
486
+ ...result,
487
+ preservedBackup: backup
488
+ } : result;
489
+ }, { waitMs: 5e3 });
490
+ }
491
+ //#endregion
492
+ //#region lib/types/command-manager-entry.js
493
+ /** Private command-management worker; macOS mutation targets are fixed before elevation. */
494
+ const [operation, expected] = process.argv.slice(2);
495
+ const fingerprint = expected ?? "";
496
+ const resources = resolve(dirname(fileURLToPath(import.meta.url)), "../..");
497
+ if (process.platform === "darwin") process.umask(18);
498
+ try {
499
+ if (![
500
+ "inspect",
501
+ "install",
502
+ "remove"
503
+ ].includes(operation ?? "")) throw new CommandInstallationError("EINVAL", "Invalid command-management operation.");
504
+ if (operation !== "inspect" && !/^[a-f0-9]{64}$/u.test(fingerprint)) throw new CommandInstallationError("EINVAL", "Missing command confirmation.");
505
+ if (process.platform === "darwin") {
506
+ const options = {
507
+ destination: "/usr/local/bin/dsh",
508
+ launcher: join(resources, "runtime", "cli", "bin", "qilin"),
509
+ linkHelper: join(resources, "runtime", "cli", "link-entry")
510
+ };
511
+ const state = operation === "inspect" ? await inspectFileCommand(options) : operation === "install" ? await installFileCommand(options, fingerprint) : await removeFileCommand(options, fingerprint);
512
+ process.stdout.write(JSON.stringify({
513
+ ok: true,
514
+ state
515
+ }) + "\n");
516
+ } else if (process.platform === "win32") {
517
+ const systemRoot = process.env.SystemRoot ?? process.env.WINDIR;
518
+ if (systemRoot === void 0) throw new CommandInstallationError("ENOENT", "Windows system directory is unavailable.");
519
+ const child = spawn(join(systemRoot, "System32", "WindowsPowerShell", "v1.0", "powershell.exe"), [
520
+ "-NoProfile",
521
+ "-NonInteractive",
522
+ "-ExecutionPolicy",
523
+ "Bypass",
524
+ "-File",
525
+ join(resources, "runtime", "cli", "command-path.ps1")
526
+ ], {
527
+ stdio: [
528
+ "pipe",
529
+ "pipe",
530
+ "inherit"
531
+ ],
532
+ windowsHide: true
533
+ });
534
+ child.stdout.pipe(process.stdout);
535
+ const exited = new Promise((accept, reject) => {
536
+ child.once("error", reject);
537
+ child.once("close", accept);
538
+ });
539
+ child.stdin.end(JSON.stringify({
540
+ operation,
541
+ expected,
542
+ directory: join(resources, "runtime", "cli", "bin")
543
+ }));
544
+ process.exitCode = await exited ?? 1;
545
+ } else throw new CommandInstallationError("EUNSUPPORTED", "Command installation is supported on macOS and Windows.");
546
+ } catch (error) {
547
+ process.stdout.write(JSON.stringify({
548
+ ok: false,
549
+ code: error instanceof CommandInstallationError ? error.code : error.code ?? "EIO",
550
+ message: error instanceof Error ? error.message : "Command management failed."
551
+ }) + "\n");
552
+ }
553
+ //#endregion
554
+ export {};