aegiscode 7.0.14 → 7.0.16

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 (109) hide show
  1. package/SOURCE-OFFER.txt +9 -0
  2. package/package.json +4 -7
  3. package/scripts/check.mjs +1 -52
  4. package/scripts/demo.mjs +1 -94
  5. package/scripts/predist.mjs +1 -75
  6. package/scripts/runtests.mjs +1 -56
  7. package/scripts/seal-gate.mjs +1 -74
  8. package/src/agents.js +1 -139
  9. package/src/app.js +1 -2932
  10. package/src/art.js +1 -289
  11. package/src/chatflow.js +1 -3020
  12. package/src/checkpoint.js +1 -90
  13. package/src/clipboard.js +1 -424
  14. package/src/cloudsync.js +1 -528
  15. package/src/commands.js +1 -4003
  16. package/src/config.js +1 -581
  17. package/src/connect.js +1 -349
  18. package/src/credentials.js +1 -33
  19. package/src/deps.js +1 -232
  20. package/src/devrun.js +1 -187
  21. package/src/diff.js +1 -333
  22. package/src/diffview.js +1 -296
  23. package/src/engine.js +1 -297
  24. package/src/entitlement.js +1 -355
  25. package/src/events.js +1 -707
  26. package/src/export.js +1 -67
  27. package/src/fingerprint.js +1 -592
  28. package/src/format.js +1 -259
  29. package/src/fuzzy.js +1 -119
  30. package/src/history.js +1 -401
  31. package/src/init.js +1 -175
  32. package/src/input.js +1 -139
  33. package/src/keys.js +1 -183
  34. package/src/markdown.js +1 -306
  35. package/src/models.js +1 -487
  36. package/src/naming.js +1 -229
  37. package/src/overlays.js +1 -461
  38. package/src/panels.js +1 -1418
  39. package/src/ping.js +1 -226
  40. package/src/presence.js +1 -238
  41. package/src/render.js +1 -515
  42. package/src/screen.js +1 -518
  43. package/src/screens.js +1 -896
  44. package/src/secret.js +1 -59
  45. package/src/securefs.js +1 -359
  46. package/src/settings.js +1 -155
  47. package/src/shared.js +1 -52
  48. package/src/sharedpaths.js +1 -53
  49. package/src/signup.js +1 -156
  50. package/src/summarize.js +1 -95
  51. package/src/sysdiag.js +1 -585
  52. package/src/system.js +1 -40
  53. package/src/theme.js +1 -570
  54. package/src/title.js +1 -220
  55. package/src/todos.js +1 -115
  56. package/src/tokens.js +1 -263
  57. package/src/topup.js +1 -210
  58. package/src/update.js +1 -181
  59. package/vendor/client/aegis.js +1 -2179
  60. package/vendor/client/attest.js +1 -442
  61. package/vendor/client/authorship-key.js +1 -410
  62. package/vendor/client/auto-provision.js +1 -134
  63. package/vendor/client/brain-catalog.js +1 -268
  64. package/vendor/client/byok-catalog.js +1 -230
  65. package/vendor/client/credentials.js +1 -494
  66. package/vendor/client/device-fingerprint.js +1 -141
  67. package/vendor/client/drive-connect.js +1 -110
  68. package/vendor/client/drive-upload.js +1 -174
  69. package/vendor/client/env-file.js +1 -1273
  70. package/vendor/client/fingerprint.js +1 -1064
  71. package/vendor/client/foreign-memory.js +1 -669
  72. package/vendor/client/google-signin.js +1 -133
  73. package/vendor/client/hooks.js +1 -430
  74. package/vendor/client/model-discovery.js +1 -373
  75. package/vendor/client/platform.js +1 -937
  76. package/vendor/client/prefs.js +1 -351
  77. package/vendor/client/presence-constants.js +1 -107
  78. package/vendor/client/presence.js +1 -438
  79. package/vendor/client/record-vault.js +3 -1055
  80. package/vendor/client/session-store.js +1 -548
  81. package/vendor/client/topup.js +1 -297
  82. package/vendor/client/touch.js +1 -458
  83. package/vendor/client/update.js +1 -704
  84. package/vendor/client/user-models.js +1 -381
  85. package/vendor/desktop/lib/local/agents.js +1 -105
  86. package/vendor/desktop/lib/local/autonomous.js +1 -1045
  87. package/vendor/desktop/lib/local/claude-pro.js +1 -993
  88. package/vendor/desktop/lib/local/context.js +1 -95
  89. package/vendor/desktop/lib/local/engine.js +1 -3301
  90. package/vendor/desktop/lib/local/entitlement.js +1 -660
  91. package/vendor/desktop/lib/local/git-scope.js +1 -228
  92. package/vendor/desktop/lib/local/local.js +1 -2135
  93. package/vendor/desktop/lib/local/prompt.js +1 -275
  94. package/vendor/desktop/lib/local/queue.js +1 -560
  95. package/vendor/desktop/lib/local/session-rounds.js +1 -208
  96. package/vendor/desktop/lib/local/shell.js +1 -680
  97. package/vendor/desktop/lib/local/tools.js +1 -1238
  98. package/vendor/desktop/lib/local/turn-guard.js +1 -300
  99. package/vendor/desktop/lib/local/worktree-lock.js +1 -235
  100. package/vendor/desktop/lib/settings.js +1 -890
  101. package/vendor/desktop/renderer/usage.js +1 -1239
  102. package/vendor/hosts/install.js +1 -638
  103. package/vendor/hosts/openai-shim.js +1 -515
  104. package/vendor/hosts/spec.js +1 -164
  105. package/vendor/hosts/targets.js +1 -346
  106. package/vendor/mcp/server.js +1 -221
  107. package/vendor/mcp/tools.js +1 -408
  108. package/vendor/one/src/child.js +1 -285
  109. package/vendor/one/src/permissions.js +1 -369
@@ -1,939 +1,3 @@
1
1
  // SPDX-License-Identifier: AGPL-3.0-or-later
2
2
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
- // AEGIS Code (aegiscode) — source: https://github.com/aegisinfo/aegiscode-plugin
4
- // Conveying a modified copy, or running one as a network service, owes the
5
- // corresponding source under this licence (§5/§13) — see LICENSING.md.
6
- 'use strict';
7
-
8
- /**
9
- * platform.js — the ONE place in this repo that knows which OS it is running on.
10
- *
11
- * Phase 30.1. Every platform-dependent decision used to be made inline against
12
- * `process.platform`, which meant two things: the decision was duplicated
13
- * wherever it was needed (a private `shellSpec()` here, an `IS_WIN32` there),
14
- * and — the real cost — its win32 half could only ever be exercised on a
15
- * Windows host. Nothing on this Linux CI could prove the Windows branch even
16
- * parses, let alone behaves.
17
- *
18
- * So every function here takes an explicit options bag:
19
- *
20
- * { platform, env, exists, probe }
21
- *
22
- * each entry defaulting to the real process environment:
23
- *
24
- * platform process.platform 'win32' | 'darwin' | 'linux' | …
25
- * env process.env looked up case-insensitively on win32
26
- * exists (file) => boolean real statSync probe of the filesystem
27
- * probe (cmd, args) => string|null spawns cmd; stdout on exit 0, else null
28
- *
29
- * Passing a different bag is the whole point: `killTree(child, { platform:
30
- * 'win32', run })` exercises the Windows path on Linux, and the test suite
31
- * (test/platform.test.mjs) does exactly that for every branch below. This is
32
- * the seam the engine gained in its Phase 21b `resolveShell({env, platform})`
33
- * and that this repo's private `shellSpec()` lacked.
34
- *
35
- * Rules for this file:
36
- * - no branch may be reachable ONLY on a foreign host — if it is, the branch
37
- * is untestable and will rot, so it takes an injected seam above;
38
- * - nothing here throws: each function returns a value, or an `{ ok:false,
39
- * error }` result the caller must look at. A swallowed failure is how a
40
- * Windows dev server was orphaned by an empty `catch {}` (plan F3).
41
- *
42
- * Zero dependencies (node builtins only) so it can be vendored byte-identically
43
- * into both the desktop app dir and the CLI package by the two predist scripts.
44
- */
45
-
46
- const fs = require('node:fs');
47
- const os = require('node:os');
48
- const path = require('node:path');
49
- const { spawnSync } = require('node:child_process');
50
-
51
- /** The host's real answer. Import this only when a real OS answer is wanted. */
52
- const IS_WIN32 = process.platform === 'win32';
53
-
54
- /** Windows' default executable extensions, used when PATHEXT is absent. */
55
- const DEFAULT_PATHEXT = '.COM;.EXE;.BAT;.CMD';
56
-
57
- // ---------------------------------------------------------------------------
58
- // Defaults for the injected seams
59
- // ---------------------------------------------------------------------------
60
-
61
- function defaultExists(file) {
62
- try {
63
- return fs.statSync(file).isFile();
64
- } catch {
65
- return false;
66
- }
67
- }
68
-
69
- /**
70
- * Run a probe command synchronously. Returns stdout on exit 0 and `null` for
71
- * every other outcome (command missing, non-zero exit, timeout) — a probe
72
- * answers "is this true", and `null` is the one honest way to say "no".
73
- */
74
- function defaultProbe(cmd, args = [], opts = {}) {
75
- try {
76
- const res = spawnSync(cmd, args, {
77
- encoding: 'utf8',
78
- timeout: opts.timeout || 5000,
79
- windowsHide: true,
80
- env: opts.env,
81
- });
82
- if (res.error || res.status !== 0) return null;
83
- return typeof res.stdout === 'string' ? res.stdout : '';
84
- } catch {
85
- return null;
86
- }
87
- }
88
-
89
- function defaultDirExists(dir) {
90
- try {
91
- return fs.statSync(dir).isDirectory();
92
- } catch {
93
- return false;
94
- }
95
- }
96
-
97
- /**
98
- * Does this directory hold anything? Used only to break the OneDrive-vs-plain
99
- * Desktop tie below — OneDrive routinely scaffolds an empty `OneDrive\Desktop`
100
- * folder on install whether or not the user ever turned Desktop redirection
101
- * on, so mere existence cannot tell a genuinely redirected Desktop apart from
102
- * that empty placeholder. An unreadable/missing directory counts as empty
103
- * rather than throwing, since the caller already confirmed it exists with
104
- * `dirExists` and a race or permissions quirk here should not crash a
105
- * best-effort path guess.
106
- */
107
- function defaultDirNonEmpty(dir) {
108
- try {
109
- return fs.readdirSync(dir).length > 0;
110
- } catch {
111
- return false;
112
- }
113
- }
114
-
115
- /** Read a text file; `null` for every failure (missing, unreadable, not text). */
116
- function defaultReadText(file) {
117
- try {
118
- return fs.readFileSync(file, 'utf8');
119
- } catch {
120
- return null;
121
- }
122
- }
123
-
124
- /** Run a command for its side effect. Never throws; `{ ok, error, output }`. */
125
- function defaultRun(cmd, args = [], opts = {}) {
126
- try {
127
- const res = spawnSync(cmd, args, {
128
- encoding: 'utf8',
129
- windowsHide: true,
130
- timeout: opts.timeout || 10000,
131
- env: opts.env,
132
- });
133
- if (res.error) return { ok: false, error: res.error, output: '' };
134
- if (res.status !== 0) {
135
- const stderr = String(res.stderr || '').trim();
136
- return {
137
- ok: false,
138
- error: new Error(`${cmd} exited ${res.status}${stderr ? `: ${stderr}` : ''}`),
139
- status: res.status,
140
- output: String(res.stdout || ''),
141
- };
142
- }
143
- return { ok: true, error: null, output: String(res.stdout || '') };
144
- } catch (err) {
145
- return { ok: false, error: err, output: '' };
146
- }
147
- }
148
-
149
- /**
150
- * Resolve the options bag. `probe` defaults to the REAL probe, so a caller that
151
- * passes nothing gets real answers; branches that would otherwise have to spawn
152
- * something consult the probe only when the caller supplied one, which is why
153
- * `injectedProbe` is reported separately from `probe`.
154
- */
155
- function seams(options) {
156
- const o = options && typeof options === 'object' ? options : {};
157
- const platform = typeof o.platform === 'string' && o.platform ? o.platform : process.platform;
158
- const env = o.env && typeof o.env === 'object' ? o.env : process.env;
159
- return {
160
- o,
161
- platform,
162
- env,
163
- win32: platform === 'win32',
164
- exists: typeof o.exists === 'function' ? o.exists : defaultExists,
165
- probe: typeof o.probe === 'function' ? o.probe : defaultProbe,
166
- injectedProbe: typeof o.probe === 'function',
167
- kill: typeof o.kill === 'function' ? o.kill : (...args) => process.kill(...args),
168
- run: typeof o.run === 'function' ? o.run : defaultRun,
169
- };
170
- }
171
-
172
- /**
173
- * Environment lookup. Windows environment names are case-insensitive
174
- * (`ComSpec` and `COMSPEC` are the same variable; PATH is often `Path`), so on
175
- * win32 fall back to a case-insensitive scan after the exact and upper-case
176
- * keys both miss.
177
- */
178
- function envValue(env, name, platform) {
179
- if (!env || typeof env !== 'object') return undefined;
180
- const direct = env[name] !== undefined ? env[name] : env[name.toUpperCase()];
181
- if (direct !== undefined) return direct;
182
- if (platform !== 'win32') return undefined;
183
- const want = name.toLowerCase();
184
- for (const key of Object.keys(env)) {
185
- if (key.toLowerCase() === want) return env[key];
186
- }
187
- return undefined;
188
- }
189
-
190
- function pathEntries(env, platform, cwd, P) {
191
- const raw = String(envValue(env, 'PATH', platform) || '');
192
- const parts = raw.split(platform === 'win32' ? ';' : ':');
193
- const out = [];
194
- for (const part of parts) {
195
- const dir = part.trim().replace(/^"|"$/g, '');
196
- if (!dir) continue;
197
- out.push(P.isAbsolute(dir) ? dir : P.join(cwd, dir));
198
- }
199
- return out;
200
- }
201
-
202
- function extList(env, platform) {
203
- const raw = String(envValue(env, 'PATHEXT', platform) || DEFAULT_PATHEXT);
204
- const exts = raw
205
- .split(';')
206
- .map((e) => e.trim())
207
- .filter(Boolean)
208
- .map((e) => (e.startsWith('.') ? e : `.${e}`));
209
- return exts.length ? exts : DEFAULT_PATHEXT.split(';');
210
- }
211
-
212
- // ---------------------------------------------------------------------------
213
- // resolveExecutable
214
- // ---------------------------------------------------------------------------
215
-
216
- /**
217
- * Resolve a command name to a path this host can actually spawn, or `null`.
218
- *
219
- * resolveExecutable('claude') -> '/usr/local/bin/claude'
220
- * resolveExecutable('node', { platform:'win32',
221
- * env:{ Path:'C:\\bin', PATHEXT:'.EXE' },
222
- * exists:(f)=>f==='C:\\bin\\node.EXE' })
223
- * -> 'C:\\bin\\node.EXE'
224
- *
225
- * Names containing a separator (or a drive letter on win32) are treated as
226
- * paths and resolved against `cwd`; bare names are searched along PATH, in
227
- * order, trying the name itself first and then each PATHEXT extension on
228
- * win32 — which is what `cmd` itself does, and the difference between finding
229
- * `npm.cmd` and reporting "npm not found" on a Windows host.
230
- *
231
- * Returns a string, or `null` when nothing matches: a caller can spawn a path
232
- * or report that the program is missing, and cannot mistake one for the other.
233
- */
234
- function resolveExecutable(name, options = {}) {
235
- const { platform, env, exists, win32, o } = seams(options);
236
- if (typeof name !== 'string' || !name.trim()) return null;
237
- const raw = name.trim();
238
- const cwd = typeof o.cwd === 'string' && o.cwd ? o.cwd : process.cwd();
239
- // Path SEMANTICS follow the platform being asked about, not the host running
240
- // the code: `path.win32.join('C:\\Tools', 'npm.EXE')` is the answer a Windows
241
- // host gives, and using the host's own `path` here would make the win32
242
- // branch produce posix paths on Linux — which is exactly the difference this
243
- // module exists to make testable rather than platform-only.
244
- const P = win32 ? path.win32 : path;
245
-
246
- const looksLikePath = win32
247
- ? raw.includes('/') || raw.includes('\\') || /^[a-zA-Z]:/.test(raw)
248
- : raw.includes('/');
249
- if (looksLikePath) {
250
- const full = P.isAbsolute(raw) ? raw : P.join(cwd, raw);
251
- return exists(full) ? full : null;
252
- }
253
-
254
- const exts = win32 ? ['', ...extList(env, platform)] : [''];
255
- for (const dir of pathEntries(env, platform, cwd, P)) {
256
- for (const ext of exts) {
257
- const candidate = P.join(dir, raw + ext);
258
- if (exists(candidate)) return candidate;
259
- }
260
- }
261
- return null;
262
- }
263
-
264
- // ---------------------------------------------------------------------------
265
- // shellSpec
266
- // ---------------------------------------------------------------------------
267
-
268
- /**
269
- * The shell one-shot commands run in: `cmd.exe` on Windows, `$SHELL` (or
270
- * `/bin/sh`) elsewhere.
271
- *
272
- * { cmd, arg, kind } kind: 'cmd' | 'posix'
273
- *
274
- * `{ cmd, arg }` is the shape the caller needs for `spawn(cmd, [arg, script])`;
275
- * `kind` is there so a caller can stop re-deriving `platform === 'win32'` at
276
- * every site that needs to know which dialect it just got.
277
- *
278
- * This replaces the private copy that lived at desktop/lib/local/tools.js:630
279
- * and read `process.platform` directly. It is deliberately NOT a `$SHELL`
280
- * allowlist: which shells are POSIX enough for a given script is the script's
281
- * problem (plan 30.3), not this resolver's.
282
- */
283
- function shellSpec(options = {}) {
284
- const { platform, env, win32 } = seams(options);
285
- if (win32) {
286
- const cmd = envValue(env, 'ComSpec', platform) || envValue(env, 'COMSPEC', platform) || 'cmd.exe';
287
- return { cmd, arg: '/d /s /c', kind: 'cmd' };
288
- }
289
- const cmd = envValue(env, 'SHELL', platform) || '/bin/sh';
290
- return { cmd, arg: '-c', kind: 'posix' };
291
- }
292
-
293
- // ---------------------------------------------------------------------------
294
- // killTree
295
- // ---------------------------------------------------------------------------
296
-
297
- /**
298
- * Kill a child process AND its descendants.
299
- *
300
- * { ok, method: 'group'|'signal'|'taskkill'|'none', pid, error, groupError, gone }
301
- *
302
- * posix: the child is spawned `detached`, so it leads its own process group and
303
- * `kill(-pid)` reaches the whole tree; a group the caller never created (or one
304
- * already reaped) answers ESRCH/EPERM, and the fallback is a plain single-pid
305
- * signal. Anything else is reported, not swallowed.
306
- *
307
- * win32: there is no process group to signal, so it is `taskkill /PID <pid> /T
308
- * /F` — `/T` for the tree, `/F` because a Windows console app can ignore the
309
- * graceful message and stay alive.
310
- *
311
- * `ok:false` always carries an `error`; `gone:true` marks the "already dead"
312
- * case so a caller can treat it as done without guessing from a message string.
313
- */
314
- function killTree(target, options = {}) {
315
- const { platform, env, win32, kill, run, o } = seams(options);
316
- const pid = typeof target === 'number' ? target : target && target.pid;
317
- const signal = o.signal || 'SIGTERM';
318
- const detached = o.detached !== false;
319
- const timeout = o.timeout || 10000;
320
-
321
- if (!Number.isInteger(pid) || pid <= 0) {
322
- return {
323
- ok: false,
324
- method: 'none',
325
- pid: Number.isInteger(pid) ? pid : null,
326
- error: new Error(`killTree: no usable pid (got ${JSON.stringify(target && target.pid)})`),
327
- gone: false,
328
- };
329
- }
330
-
331
- if (win32) {
332
- const res = run('taskkill', ['/PID', String(pid), '/T', '/F'], { env, platform, timeout }) || {};
333
- if (res.ok === false) {
334
- return {
335
- ok: false,
336
- method: 'taskkill',
337
- pid,
338
- error: res.error || new Error('taskkill failed'),
339
- gone: false,
340
- };
341
- }
342
- return { ok: true, method: 'taskkill', pid, error: null, gone: false };
343
- }
344
-
345
- let groupError = null;
346
- if (detached) {
347
- try {
348
- kill(-pid, signal);
349
- return { ok: true, method: 'group', pid, error: null, gone: false };
350
- } catch (err) {
351
- groupError = err;
352
- const code = err && err.code;
353
- if (code !== 'ESRCH' && code !== 'EPERM') {
354
- return {
355
- ok: false,
356
- method: 'group',
357
- pid,
358
- error: err,
359
- gone: false,
360
- };
361
- }
362
- }
363
- }
364
-
365
- try {
366
- kill(pid, signal);
367
- return { ok: true, method: 'signal', pid, error: null, groupError, gone: false };
368
- } catch (err) {
369
- const code = err && err.code;
370
- return {
371
- ok: false,
372
- method: 'signal',
373
- pid,
374
- error: err,
375
- groupError,
376
- gone: code === 'ESRCH',
377
- };
378
- }
379
- }
380
-
381
- // ---------------------------------------------------------------------------
382
- // isAlive
383
- // ---------------------------------------------------------------------------
384
-
385
- /**
386
- * Is that pid still running? Never throws.
387
- *
388
- * posix: `kill(pid, 0)` — ESRCH means gone, EPERM means it exists but belongs
389
- * to someone else, and "exists but not ours" is alive.
390
- *
391
- * win32: signal 0 is not a portable existence test there, so ask the OS
392
- * directly — `tasklist /FI "PID eq <pid>"` — and match the pid in the output.
393
- * The probe is the injected seam, so this branch is exercised on Linux by
394
- * feeding it fabricated tasklist output rather than by waiting for a Windows
395
- * runner that, by configuration, does not exist (plan F6).
396
- */
397
- function isAlive(pid, options = {}) {
398
- const { platform, env, win32, probe, kill } = seams(options);
399
- const label = typeof pid === 'number' ? pid : Number(pid);
400
- if (!Number.isInteger(label) || label <= 0) return false;
401
-
402
- if (win32) {
403
- const out = probe('tasklist', ['/FI', `PID eq ${label}`, '/NH', '/FO', 'CSV'], { env, platform });
404
- if (out === null || out === undefined) return false;
405
- const text = String(out).trim();
406
- if (!text) return false;
407
- return new RegExp(`(^|[^0-9])${label}([^0-9]|$)`).test(text);
408
- }
409
-
410
- try {
411
- kill(label, 0);
412
- return true;
413
- } catch (err) {
414
- return Boolean(err && err.code === 'EPERM');
415
- }
416
- }
417
-
418
- // ---------------------------------------------------------------------------
419
- // hasDisplay
420
- // ---------------------------------------------------------------------------
421
-
422
- /**
423
- * Can this process reach a graphical display? (i.e. may a host open a window,
424
- * a browser or an Electron window here?)
425
- *
426
- * Windows and macOS: yes — an interactive session always has one, and a
427
- * headless service session is out of scope for this product.
428
- * Linux/BSD: only if `DISPLAY` or `WAYLAND_DISPLAY` says so. When neither is
429
- * set the answer is `false` rather than a guess, and a caller that has a
430
- * better oracle (a live X socket, a container's own check) can inject `probe`
431
- * to override it — the probe is consulted ONLY when injected, so this function
432
- * never spawns anything behind a caller's back.
433
- */
434
- function hasDisplay(options = {}) {
435
- const { platform, env, win32, probe, injectedProbe } = seams(options);
436
- if (win32 || platform === 'darwin') return true;
437
- if (envValue(env, 'DISPLAY', platform) || envValue(env, 'WAYLAND_DISPLAY', platform)) return true;
438
- if (injectedProbe) return probe('xdpyinfo', [], { env, platform }) !== null;
439
- return false;
440
- }
441
-
442
- // ---------------------------------------------------------------------------
443
- // homeDir / resolvePath
444
- // ---------------------------------------------------------------------------
445
-
446
- /**
447
- * Normalise anything a machine calls a locale into a BCP-47 `ll` / `ll-CC`
448
- * code, or `''` for "no answer".
449
- *
450
- * Four spellings reach this function and only the first is already usable:
451
- * `sv-SE`, the POSIX `sv_SE.UTF-8` (and `sv_SE.utf8`, `sv_SE`), the GNU
452
- * `LANGUAGE` list (`sv:en:de` — the caller splits it), and the two settings
453
- * that mean NOT a language: `C` and `POSIX`, which say "no locale configured"
454
- * and must never render as a language called "c". The modifier tail
455
- * (`@euro`, `@latin`) is dropped: it changes collation, not language.
456
- */
457
- function normalizeLocale(value) {
458
- if (value == null) return '';
459
- const raw = String(value).trim();
460
- if (!raw) return '';
461
- const head = raw.split('@')[0].split('.')[0];
462
- if (/^(c|posix)$/i.test(head)) return '';
463
- const m = /^([A-Za-z]{2,3})(?:[_-]([A-Za-z0-9]{2,8}))?$/.exec(head);
464
- if (!m) return '';
465
- const lang = m[1].toLowerCase();
466
- if (lang === 'c' || lang === 'posix') return '';
467
- return m[2] ? `${lang}-${m[2].toUpperCase()}` : lang;
468
- }
469
-
470
- /**
471
- * The language the user's own machine and account run in — `''` when nothing
472
- * can say.
473
- *
474
- * The model has always been told the platform, the home directory and the real
475
- * Desktop path, but never this, so a Swedish user's DeepSeek turn started with
476
- * no field saying the machine is Swedish: the model mirrored whatever language
477
- * arrived in the message and defaulted to the prompt's English otherwise.
478
- * Mirrored language is not the same as known language — an up-front
479
- * `locale: sv-SE` is what lets it answer a Swedish one-word request ("städa")
480
- * in Swedish instead of asking which language to use.
481
- *
482
- * POSIX order is the order below (`LC_ALL` overrides `LC_CTYPE` overrides
483
- * `LC_MESSAGES` overrides `LANG`); `LANGUAGE` is a GNU preference LIST and is
484
- * consulted last only for its first entry. Windows sets none of these, and
485
- * macOS sets none of them for an app launched from Finder, so `Intl` is the
486
- * fallback — it reads the ICU default the runtime was started with, which is
487
- * the same answer the OS gives the app. An `env` the caller INJECTED is trusted
488
- * as given (never topped up from `Intl`), which is what makes a test with
489
- * `env: {}` deterministic instead of dependent on the CI runner's locale.
490
- */
491
- function appLocale(options = {}) {
492
- const { platform, env, o } = seams(options);
493
- if (typeof o.locale === 'string') return normalizeLocale(o.locale);
494
- const injected = o.env && typeof o.env === 'object';
495
- for (const key of ['LC_ALL', 'LC_CTYPE', 'LC_MESSAGES', 'LANG']) {
496
- const hit = normalizeLocale(envValue(env, key, platform));
497
- if (hit) return hit;
498
- }
499
- const list = String(envValue(env, 'LANGUAGE', platform) || '');
500
- if (list) {
501
- // A colon list is a PREFERENCE order, and an empty field in it (":de" — how
502
- // a launch script that cleared the first entry leaves it) means "skip this
503
- // one", not "the answer is nothing".
504
- for (const part of list.split(':')) {
505
- const first = normalizeLocale(part);
506
- if (first) return first;
507
- }
508
- }
509
- if (injected) return ''; // the caller owns the environment; it said nothing
510
- try {
511
- return normalizeLocale(new Intl.DateTimeFormat().resolvedOptions().locale);
512
- } catch {
513
- return '';
514
- }
515
- }
516
-
517
- /**
518
- * The English name of a language code — `Swedish` for `sv`, `''` when the
519
- * runtime has no display table for it (Node without full ICU). Named in
520
- * ENGLISH on purpose: it is interpolated into the English system prompt, so a
521
- * Swedish host must not render it as "svenska".
522
- */
523
- function languageName(code, options = {}) {
524
- const { o } = seams(options);
525
- if (typeof o.languageName === 'string') return o.languageName;
526
- const hit = normalizeLocale(code);
527
- if (!hit) return '';
528
- const base = hit.split('-')[0];
529
- try {
530
- const display = new Intl.DisplayNames(['en'], { type: 'language' });
531
- return display.of(base) || '';
532
- } catch {
533
- return '';
534
- }
535
- }
536
-
537
- /**
538
- * This user's home directory, `''` when nothing can say what it is.
539
- *
540
- * `USERPROFILE` leads on win32 and `HOME` on posix because that is the variable
541
- * each OS actually sets; the other is accepted second (a Windows git-bash shell
542
- * exports `HOME`, and a posix host inheriting `USERPROFILE` is harmless), and
543
- * `os.homedir()` is the last word. Reading the env BEFORE `os.homedir()` is what
544
- * lets a test point a whole tool run at a temp directory.
545
- */
546
- function homeDir(options = {}) {
547
- const { platform, env, o } = seams(options);
548
- // An explicit `home` is honoured AS GIVEN, including `''`. That is the seam
549
- // for "this machine has no home directory" — a case the env/os fallbacks below
550
- // can never produce on a developer's own box, and therefore one that could
551
- // not be tested at all if an empty string fell through to them.
552
- if (typeof o.home === 'string') return o.home.trim();
553
- const keys = platform === 'win32' ? ['USERPROFILE', 'HOME'] : ['HOME', 'USERPROFILE'];
554
- for (const key of keys) {
555
- const value = envValue(env, key, platform);
556
- if (value && String(value).trim()) return String(value).trim();
557
- }
558
- try {
559
- return os.homedir() || '';
560
- } catch {
561
- return '';
562
- }
563
- }
564
-
565
- /**
566
- * Do the permission bits in `fs.stat().mode` carry real information here?
567
- *
568
- * On Windows they do not. libuv has no NTFS ACL to report, so it SYNTHESISES the
569
- * mode from a single bit — the read-only attribute — and hands back `0o666` for
570
- * every writable file and `0o444` for every read-only one, directories included.
571
- * Two consequences, and both were live bugs:
572
- *
573
- * - `(mode & 0o077) !== 0` — "is this readable by other users?" — is therefore
574
- * ALWAYS TRUE on Windows, for every file, no matter how locked down it is.
575
- * Code that refuses a secret on that test refuses it unconditionally there
576
- * (tools/agent-gate.mjs would not accept an agent key at all), and code that
577
- * reports it as exposure reports the user's whole data directory as exposed
578
- * with no way to fix it (`/doctor` in cli/src/commands.js).
579
- * - `chmodSync(f, 0o600)` cannot make that test pass, so a repair loop that
580
- * re-reads the mode to confirm never converges.
581
- *
582
- * Where this returns false the boundary is the DIRECTORY's ACL — a per-user
583
- * profile directory is already inaccessible to other non-admin accounts — which
584
- * is what `client/authorship-key.js` has always done for the key file. The right
585
- * behaviour is to skip the judgement and say so, never to assume the worst.
586
- */
587
- function hasPosixModes(options = {}) {
588
- const { win32 } = seams(options);
589
- return !win32;
590
- }
591
-
592
- /**
593
- * Windows' own answer for "where is this user's Desktop", straight from the
594
- * registry key Explorer itself reads and OneDrive itself rewrites when it
595
- * redirects a folder. This is the one source immune to BOTH ways `~/Desktop`
596
- * guesses wrong at once: it already names the OneDrive path when redirection
597
- * is active, and it already names the LOCALISED folder — Swedish "Skrivbord",
598
- * French "Bureau", whatever the session's physical folder is actually called
599
- * — because it is Windows' own record of a real path, not an English-language
600
- * guess with a `?` for an ending. Guessing per-language folder names instead
601
- * would mean enumerating every language Windows ships, forever one behind;
602
- * asking Windows is both simpler and exact.
603
- *
604
- * "Shell Folders" (not "User Shell Folders") is the one queried, because it
605
- * holds the already-expanded absolute path — "User Shell Folders" is allowed
606
- * to hold `%USERPROFILE%`-relative values, and this function has no reason to
607
- * carry its own copy of Windows' expansion rules when the other key already
608
- * did that work.
609
- *
610
- * Returns `''` on anything but a clean hit: `reg.exe` missing, a non-zero
611
- * exit, unparsable output, or a path the filesystem does not actually have —
612
- * each of those falls through to the candidate-guessing list in desktopDir()
613
- * below, which is where this function's absence has always been tolerated.
614
- */
615
- function winShellFolderDesktop(probe, dirExists) {
616
- const out = probe('reg', [
617
- 'query',
618
- 'HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders',
619
- '/v', 'Desktop',
620
- ]);
621
- if (!out) return '';
622
- const m = /^\s*Desktop\s+REG_(?:EXPAND_)?SZ\s+(.+)$/im.exec(out);
623
- const value = m && m[1].trim();
624
- return value && dirExists(value) ? value : '';
625
- }
626
-
627
- /**
628
- * This user's real Desktop directory, or `''` when none can be found.
629
- *
630
- * `~/Desktop` is a GUESS, and it is wrong on both of the hosts this function was
631
- * added for:
632
- *
633
- * - Windows with OneDrive, or a localised session. Folder redirection moves
634
- * the live Desktop to `%USERPROFILE%\OneDrive\Desktop` (or renames it
635
- * entirely, e.g. Swedish "Skrivbord"), and commonly leaves an empty
636
- * `%USERPROFILE%\Desktop` behind, so a write to the obvious English path
637
- * lands in a directory the user is not looking at — or at a name that
638
- * does not exist on their machine at all. `winShellFolderDesktop()` above
639
- * asks Windows directly and settles both cases at once; the `%OneDrive%`-
640
- * and `home`-based guesses below only run when that lookup comes back
641
- * empty (no `reg.exe`, or the path it names no longer exists).
642
- * - A localised Linux desktop. XDG translates the directory ITSELF, not just
643
- * its label: a Swedish session has `~/Skrivbord` and no `~/Desktop` at all.
644
- * `$XDG_DESKTOP_DIR` answers it, and `~/.config/user-dirs.dirs` is where
645
- * that variable is defined when the session did not export it.
646
- *
647
- * macOS is the one host where `~/Desktop` is simply correct.
648
- *
649
- * Seams: `dirExists` (default: a real statSync isDirectory probe), `dirNonEmpty`
650
- * (default: a real readdirSync length check, used only to break the win32
651
- * OneDrive-vs-plain guess below when the registry lookup did not settle it),
652
- * `probe` (default: a real `reg.exe` spawn, `null` on any failure) and
653
- * `readText` (default: a real utf8 read, `null` on any failure), so every
654
- * branch is exercised on one host.
655
- */
656
- function desktopDir(options = {}) {
657
- const { platform, env, win32, probe, o } = seams(options);
658
- const P = win32 ? path.win32 : path.posix;
659
- const home = homeDir(options);
660
- const dirExists = typeof o.dirExists === 'function' ? o.dirExists : defaultDirExists;
661
- const dirNonEmpty = typeof o.dirNonEmpty === 'function' ? o.dirNonEmpty : defaultDirNonEmpty;
662
-
663
- if (win32) {
664
- const fromRegistry = winShellFolderDesktop(probe, dirExists);
665
- if (fromRegistry) return fromRegistry;
666
- }
667
- const readText = typeof o.readText === 'function' ? o.readText : defaultReadText;
668
-
669
- const candidates = [];
670
- const push = (value) => {
671
- if (value && String(value).trim()) candidates.push(String(value).trim());
672
- };
673
-
674
- if (win32) {
675
- const oneDrive = envValue(env, 'OneDrive', platform) || envValue(env, 'OneDriveConsumer', platform);
676
- if (oneDrive) push(P.join(oneDrive, 'Desktop'));
677
- if (home) push(P.join(home, 'OneDrive', 'Desktop'));
678
- if (home) push(P.join(home, 'Desktop'));
679
- // OneDrive is tried first above — real folder redirection moves the live
680
- // Desktop there and leaves the plain one empty, exactly as the module
681
- // comment says. But OneDrive also scaffolds an empty `OneDrive\Desktop`
682
- // on install whether redirection was ever turned on, and that empty
683
- // placeholder must not outrank a Desktop the user is actually using —
684
- // reported live: a write landed in an untouched `OneDrive\Desktop` while
685
- // the populated plain Desktop sat right next to it. Demote every
686
- // OneDrive candidate below the plain one only in that one unambiguous
687
- // case (a OneDrive candidate exists but is empty, AND the plain Desktop
688
- // exists and has something in it); every other combination — including
689
- // "both empty", which is what a fresh profile and this file's own
690
- // stubbed tests both look like — keeps the order above, since a guess is
691
- // still owed and emptiness alone proves nothing there.
692
- const plainDesktop = home ? P.join(home, 'Desktop') : '';
693
- const plainIdx = candidates.indexOf(plainDesktop);
694
- if (plainIdx > 0 && dirExists(plainDesktop) && dirNonEmpty(plainDesktop)) {
695
- const oneDriveCandidates = candidates.slice(0, plainIdx);
696
- const allOneDriveEmpty = oneDriveCandidates.every(
697
- (c) => !dirExists(c) || !dirNonEmpty(c)
698
- );
699
- if (allOneDriveEmpty) {
700
- candidates.splice(plainIdx, 1);
701
- candidates.unshift(plainDesktop);
702
- }
703
- }
704
- } else if (platform === 'darwin') {
705
- if (home) push(P.join(home, 'Desktop'));
706
- } else {
707
- push(envValue(env, 'XDG_DESKTOP_DIR', platform));
708
- // user-dirs.dirs holds lines like: XDG_DESKTOP_DIR="$HOME/Skrivbord"
709
- if (home) {
710
- const conf = readText(P.join(home, '.config', 'user-dirs.dirs'));
711
- const match = conf && /^\s*XDG_DESKTOP_DIR\s*=\s*"?([^"\n]+)"?\s*$/m.exec(conf);
712
- if (match) push(match[1].replace(/\$HOME\b|\${HOME}/g, home));
713
- }
714
- if (home) push(P.join(home, 'Desktop'));
715
- }
716
-
717
- for (const candidate of candidates) {
718
- if (dirExists(candidate)) return candidate;
719
- }
720
- // Nothing on disk. The conventional path is still a better answer than '' for
721
- // a machine whose Desktop simply has not been created yet — but only where the
722
- // name is not localised, which is the one case we would be guessing at.
723
- if (home && (win32 || platform === 'darwin')) return P.join(home, 'Desktop');
724
- return '';
725
- }
726
-
727
- /**
728
- * If `work` names this user's home "Desktop" folder by its generic literal
729
- * name — the one a model guesses, in English, regardless of locale or
730
- * OneDrive redirection — rewrite it to the REAL desktop directory the caller
731
- * already asked Windows/XDG for (`desktopDir()` above).
732
- *
733
- * The environment preamble already NAMES the real directory and tells the
734
- * model to copy it verbatim rather than build it — but that is advisory, and
735
- * a model that still writes `~/Desktop/notes.txt` was silently creating (and
736
- * reporting success into) a spurious English "Desktop" folder next to the
737
- * user's real one, which on a redirected or localised Windows session is a
738
- * different, empty directory the user never sees. This is the opposite of
739
- * desktopDir()'s own job: that function stops US from guessing a locale name;
740
- * this stops a model's literal "Desktop" guess from winning when we were
741
- * already told the real answer.
742
- *
743
- * No-op when no `desktopdir` was supplied, when it is simply `home/Desktop`
744
- * (nothing to correct), or when `work` is not rooted at the guessed path.
745
- */
746
- function applyDesktopAlias(work, { home, desktopdir, win32, P }) {
747
- if (!home || !desktopdir) return work;
748
- const guessed = P.join(home, 'Desktop');
749
- const fold = (s) => (win32 ? s.toLowerCase() : s);
750
- if (fold(guessed) === fold(desktopdir)) return work;
751
- if (fold(work) === fold(guessed)) return desktopdir;
752
- const prefix = guessed + P.sep;
753
- if (fold(work).startsWith(fold(prefix))) return desktopdir + P.sep + work.slice(prefix.length);
754
- return work;
755
- }
756
-
757
- /** `C:\…` / `C:/…` — a drive-qualified Windows path. */
758
- const WIN_DRIVE_RE = /^[A-Za-z]:[\\/]/;
759
- /** `C:` with nothing after it — drive-relative, and never what a model means. */
760
- const WIN_BARE_DRIVE_RE = /^[A-Za-z]:$/;
761
- /** `\\server\share` — a UNC path, which IS absolute and stays allowed. */
762
- const WIN_UNC_RE = /^\\\\[^\\?.]/;
763
-
764
- /**
765
- * Turn a path a MODEL produced into a path this machine really has.
766
- *
767
- * { ok, path, error, expandedHome }
768
- *
769
- * Why this exists. The tool layer used to pass `file_path` straight to `fs`,
770
- * which quietly made two very common model outputs write to the wrong place:
771
- *
772
- * - `~/Desktop/notes.txt`. Node does not expand `~`; nothing in the tool
773
- * layer did either. `fs.mkdirSync(path.dirname(…))` therefore created a
774
- * directory literally NAMED `~` under the process cwd and wrote inside it —
775
- * and `writeFile` reported "Wrote 14 bytes to ~/Desktop/notes.txt", so the
776
- * model told the user it had saved a file to their Desktop that was not
777
- * there. A wrong write that reports success is worse than a refusal.
778
- * - `/home/user/Desktop/notes.txt` ON WINDOWS. A leading-slash path there is
779
- * relative to the current DRIVE, so that write succeeds — at
780
- * `C:\home\user\Desktop\notes.txt`. Same silent success, same missing file.
781
- * This is why the bug read as "the tools only work on Linux": on Linux a
782
- * model's posix guess happens to be right, and off Linux it is accepted
783
- * anyway. Windows is also where a model reaches for `~` most, because it
784
- * cannot guess `C:\Users\<name>` and the prompt only names the home dir.
785
- *
786
- * So: `~` and `~/…` are expanded (`~other/…` is refused — another user's home
787
- * is not ours to guess), a path that is absolute for a DIFFERENT OS than this
788
- * one is refused with the correct form named, a relative path resolves against
789
- * `cwd`, and anything already native is normalised. A refusal is the useful
790
- * outcome: the model gets the real home directory back in the error and retries
791
- * correctly in the next round, where before it got "success" and stopped.
792
- *
793
- * Idempotent — the output of one call is unchanged by the next — so a caller
794
- * may normalise early (before a guard inspects the path) without worrying that
795
- * a later layer will resolve it a second time.
796
- *
797
- * Path SEMANTICS follow the `platform` asked about, not the host, exactly as in
798
- * `resolveExecutable` above: that is what lets test/platform.test.mjs prove the
799
- * win32 branch on this Linux CI.
800
- */
801
- function resolvePath(input, options = {}) {
802
- const { platform, win32, o } = seams(options);
803
- const P = win32 ? path.win32 : path.posix;
804
- const refuse = (error) => ({ ok: false, path: null, error, expandedHome: false });
805
-
806
- if (typeof input !== 'string' || !input.trim()) {
807
- return refuse(`a path is required (got ${JSON.stringify(input)})`);
808
- }
809
- const raw = input.trim();
810
-
811
- // ── the home shorthand ────────────────────────────────────────────────────
812
- let work = raw;
813
- let expandedHome = false;
814
- const tildeRoot = raw === '~' || raw.startsWith('~/') || (win32 && raw.startsWith('~\\'));
815
- if (tildeRoot) {
816
- const home = homeDir(options);
817
- if (!home) {
818
- return refuse(
819
- `cannot expand "~" in ${JSON.stringify(raw)}: this machine reports no home directory. ` +
820
- 'Pass a full absolute path instead.',
821
- );
822
- }
823
- work = raw === '~' ? home : P.join(home, raw.slice(2));
824
- expandedHome = true;
825
- } else if (raw.startsWith('~')) {
826
- return refuse(
827
- `${JSON.stringify(raw)} names another user's home directory, which cannot be resolved from ` +
828
- 'here. Use "~" for this user, or pass a full absolute path.',
829
- );
830
- }
831
-
832
- // ── the desktop alias ─────────────────────────────────────────────────────
833
- // Runs before the wrong-OS check below because a corrected `work` is always
834
- // native by construction (desktopDir() returns a real path for THIS
835
- // platform), exactly like a `~` expansion already is.
836
- work = applyDesktopAlias(work, { home: homeDir(options), desktopdir: o.desktopdir, win32, P });
837
-
838
- // ── absolute-for-the-wrong-OS ─────────────────────────────────────────────
839
- // Skipped after a `~` expansion: that result is native by construction.
840
- if (!expandedHome) {
841
- const home = homeDir(options);
842
- const hint = home ? ` This machine's home directory is ${home}.` : '';
843
- if (win32) {
844
- // A leading slash on Windows is drive-relative, not absolute. Accepted
845
- // only as a UNC share, which genuinely is absolute.
846
- if ((work.startsWith('/') || work.startsWith('\\')) && !WIN_UNC_RE.test(work)) {
847
- return refuse(
848
- `${JSON.stringify(raw)} is not an absolute path on this machine, which runs ${platform}. ` +
849
- `A leading slash here means "the root of the current drive", so writing to it would ` +
850
- `silently land somewhere other than where you meant. Use a drive-qualified path ` +
851
- `(C:\\Users\\you\\Desktop\\file.txt) or "~/…".${hint}`,
852
- );
853
- }
854
- } else if (WIN_DRIVE_RE.test(work) || WIN_BARE_DRIVE_RE.test(work) || WIN_UNC_RE.test(work)) {
855
- return refuse(
856
- `${JSON.stringify(raw)} is a Windows path, but this machine runs ${platform}. ` +
857
- `Use a posix path (/home/you/file.txt) or "~/…".${hint}`,
858
- );
859
- }
860
- }
861
-
862
- // ── relative → the working directory ──────────────────────────────────────
863
- const cwd = typeof o.cwd === 'string' && o.cwd.trim() ? o.cwd.trim() : process.cwd();
864
- const resolved = P.isAbsolute(work) ? P.resolve(work) : P.resolve(cwd, work);
865
-
866
- // `P.resolve` falls back to the HOST's cwd when nothing it was given is
867
- // absolute, which on a foreign-platform query yields a path of the wrong
868
- // shape. Say so rather than hand back something unusable.
869
- if (!P.isAbsolute(resolved)) {
870
- return refuse(
871
- `${JSON.stringify(raw)} is relative and the working directory (${JSON.stringify(cwd)}) is ` +
872
- 'not absolute, so it cannot be resolved. Pass an absolute path.',
873
- );
874
- }
875
-
876
- return { ok: true, path: resolved, error: null, expandedHome };
877
- }
878
-
879
- /**
880
- * The last path segment of `input` — the NAME of a path, for display.
881
- *
882
- * This exists because `p.split('/').pop()` was the same expression in six CLI
883
- * files, and it is wrong on half the hosts this product ships to: a real win32
884
- * separator is `\`, so `C:\Users\you\proj` splits into ONE element and the
885
- * "name" reported is the whole path. The status line, the session list, the
886
- * resume picker and the `/export` file names all showed the full path there
887
- * where linux and darwin showed `proj` — a cosmetic drift, but drifts are how
888
- * the tool-layer bug shipped twice, and it is the same class of assumption
889
- * (`/` is the separator) that `resolvePath` above exists to refuse.
890
- *
891
- * BOTH separators are accepted on every platform, unlike `resolvePath` which
892
- * refuses a foreign path outright. That difference is deliberate: a name is not
893
- * a security decision. The value can come from a git remote, a session recorded
894
- * on another host, or a model's own output, and mis-slicing it produces a
895
- * shorter label, never a write to the wrong file — so refusing it would trade a
896
- * cosmetic bug for a worse one (an empty status line on a machine whose only
897
- * oddity is a backslash).
898
- *
899
- * Returns `''` for an absent or empty path so each caller keeps its own
900
- * fallback (`baseName(cwd) || '~'` is the CLI's "no cwd recorded" convention);
901
- * a path that is nothing but separators ("/", "C:\") names no segment, so it is
902
- * empty too rather than a stray "/" or a bare drive letter.
903
- */
904
- function baseName(input) {
905
- if (typeof input !== 'string') return '';
906
- const trimmed = input.trim().replace(/[/\\]+$/, '');
907
- if (!trimmed) return '';
908
- // "C:" is a drive, not a name: it is the Windows spelling of "/" (the root of
909
- // the current drive) and names no segment any more than a slash does.
910
- if (/^[A-Za-z]:$/.test(trimmed)) return '';
911
- const cut = Math.max(trimmed.lastIndexOf('/'), trimmed.lastIndexOf('\\'));
912
- return cut === -1 ? trimmed : trimmed.slice(cut + 1);
913
- }
914
-
915
- const api = {
916
- IS_WIN32,
917
- // The seam bag itself (`seams(options)` above), exported since ON6/ON7 of the
918
- // AEGISONE plan: `one/src/host.js` is the product's single OS answer and it
919
- // has to *ask* here rather than keep a second `process.platform` read. The
920
- // bag is what makes the answer injectable (`seams({ platform: 'win32' })`),
921
- // and the function itself was always the point of this module — it simply
922
- // was not reachable from outside it.
923
- seams,
924
- resolveExecutable,
925
- shellSpec,
926
- killTree,
927
- isAlive,
928
- hasDisplay,
929
- homeDir,
930
- desktopDir,
931
- resolvePath,
932
- baseName,
933
- hasPosixModes,
934
- appLocale,
935
- languageName,
936
- normalizeLocale,
937
- };
938
-
939
- module.exports = api;
3
+ const t=require("node:fs"),e=require("node:os"),r=require("node:path"),{spawnSync:n}=require("node:child_process"),o="win32"===process.platform,i=".COM;.EXE;.BAT;.CMD";function s(e){try{return t.statSync(e).isFile()}catch{return!1}}function u(t,e=[],r={}){try{const o=n(t,e,{encoding:"utf8",timeout:r.timeout||5e3,windowsHide:!0,env:r.env});return o.error||0!==o.status?null:"string"==typeof o.stdout?o.stdout:""}catch{return null}}function c(e){try{return t.statSync(e).isDirectory()}catch{return!1}}function l(e){try{return t.readdirSync(e).length>0}catch{return!1}}function f(e){try{return t.readFileSync(e,"utf8")}catch{return null}}function a(t,e=[],r={}){try{const o=n(t,e,{encoding:"utf8",windowsHide:!0,timeout:r.timeout||1e4,env:r.env});if(o.error)return{ok:!1,error:o.error,output:""};if(0!==o.status){const e=String(o.stderr||"").trim();return{ok:!1,error:new Error(`${t} exited ${o.status}${e?`: ${e}`:""}`),status:o.status,output:String(o.stdout||"")}}return{ok:!0,error:null,output:String(o.stdout||"")}}catch(t){return{ok:!1,error:t,output:""}}}function p(t){const e=t&&"object"==typeof t?t:{},r="string"==typeof e.platform&&e.platform?e.platform:process.platform;return{o:e,platform:r,env:e.env&&"object"==typeof e.env?e.env:process.env,win32:"win32"===r,exists:"function"==typeof e.exists?e.exists:s,probe:"function"==typeof e.probe?e.probe:u,injectedProbe:"function"==typeof e.probe,kill:"function"==typeof e.kill?e.kill:(...t)=>process.kill(...t),run:"function"==typeof e.run?e.run:a}}function d(t,e,r){if(!t||"object"!=typeof t)return;const n=void 0!==t[e]?t[e]:t[e.toUpperCase()];if(void 0!==n)return n;if("win32"!==r)return;const o=e.toLowerCase();for(const e of Object.keys(t))if(e.toLowerCase()===o)return t[e]}function m(t,e){const r=String(d(t,"PATHEXT",e)||i).split(";").map((t=>t.trim())).filter(Boolean).map((t=>t.startsWith(".")?t:`.${t}`));return r.length?r:i.split(";")}function h(t){if(null==t)return"";const e=String(t).trim();if(!e)return"";const r=e.split("@")[0].split(".")[0];if(/^(c|posix)$/i.test(r))return"";const n=/^([A-Za-z]{2,3})(?:[_-]([A-Za-z0-9]{2,8}))?$/.exec(r);if(!n)return"";const o=n[1].toLowerCase();return"c"===o||"posix"===o?"":n[2]?`${o}-${n[2].toUpperCase()}`:o}function g(t={}){const{platform:r,env:n,o:o}=p(t);if("string"==typeof o.home)return o.home.trim();const i="win32"===r?["USERPROFILE","HOME"]:["HOME","USERPROFILE"];for(const t of i){const e=d(n,t,r);if(e&&String(e).trim())return String(e).trim()}try{return e.homedir()||""}catch{return""}}const y=/^[A-Za-z]:[\\/]/,w=/^[A-Za-z]:$/,k=/^\\\\[^\\?.]/,S={IS_WIN32:o,seams:p,resolveExecutable:function(t,e={}){const{platform:n,env:o,exists:i,win32:s,o:u}=p(e);if("string"!=typeof t||!t.trim())return null;const c=t.trim(),l="string"==typeof u.cwd&&u.cwd?u.cwd:process.cwd(),f=s?r.win32:r;if(s?c.includes("/")||c.includes("\\")||/^[a-zA-Z]:/.test(c):c.includes("/")){const t=f.isAbsolute(c)?c:f.join(l,c);return i(t)?t:null}const a=s?["",...m(o,n)]:[""];for(const t of function(t,e,r,n){const o=String(d(t,"PATH",e)||"").split("win32"===e?";":":"),i=[];for(const t of o){const e=t.trim().replace(/^"|"$/g,"");e&&i.push(n.isAbsolute(e)?e:n.join(r,e))}return i}(o,n,l,f))for(const e of a){const r=f.join(t,c+e);if(i(r))return r}return null},shellSpec:function(t={}){const{platform:e,env:r,win32:n}=p(t);return n?{cmd:d(r,"ComSpec",e)||d(r,"COMSPEC",e)||"cmd.exe",arg:"/d /s /c",kind:"cmd"}:{cmd:d(r,"SHELL",e)||"/bin/sh",arg:"-c",kind:"posix"}},killTree:function(t,e={}){const{platform:r,env:n,win32:o,kill:i,run:s,o:u}=p(e),c="number"==typeof t?t:t&&t.pid,l=u.signal||"SIGTERM",f=!1!==u.detached,a=u.timeout||1e4;if(!Number.isInteger(c)||c<=0)return{ok:!1,method:"none",pid:Number.isInteger(c)?c:null,error:new Error(`killTree: no usable pid (got ${JSON.stringify(t&&t.pid)})`),gone:!1};if(o){const t=s("taskkill",["/PID",String(c),"/T","/F"],{env:n,platform:r,timeout:a})||{};return!1===t.ok?{ok:!1,method:"taskkill",pid:c,error:t.error||new Error("taskkill failed"),gone:!1}:{ok:!0,method:"taskkill",pid:c,error:null,gone:!1}}let d=null;if(f)try{return i(-c,l),{ok:!0,method:"group",pid:c,error:null,gone:!1}}catch(t){d=t;const e=t&&t.code;if("ESRCH"!==e&&"EPERM"!==e)return{ok:!1,method:"group",pid:c,error:t,gone:!1}}try{return i(c,l),{ok:!0,method:"signal",pid:c,error:null,groupError:d,gone:!1}}catch(t){return{ok:!1,method:"signal",pid:c,error:t,groupError:d,gone:"ESRCH"===(t&&t.code)}}},isAlive:function(t,e={}){const{platform:r,env:n,win32:o,probe:i,kill:s}=p(e),u="number"==typeof t?t:Number(t);if(!Number.isInteger(u)||u<=0)return!1;if(o){const t=i("tasklist",["/FI",`PID eq ${u}`,"/NH","/FO","CSV"],{env:n,platform:r});if(null==t)return!1;const e=String(t).trim();return!!e&&new RegExp(`(^|[^0-9])${u}([^0-9]|$)`).test(e)}try{return s(u,0),!0}catch(t){return Boolean(t&&"EPERM"===t.code)}},hasDisplay:function(t={}){const{platform:e,env:r,win32:n,probe:o,injectedProbe:i}=p(t);return!!(n||"darwin"===e||d(r,"DISPLAY",e)||d(r,"WAYLAND_DISPLAY",e)||i&&null!==o("xdpyinfo",[],{env:r,platform:e}))},homeDir:g,desktopDir:function(t={}){const{platform:e,env:n,win32:o,probe:i,o:s}=p(t),u=o?r.win32:r.posix,a=g(t),m="function"==typeof s.dirExists?s.dirExists:c,h="function"==typeof s.dirNonEmpty?s.dirNonEmpty:l;if(o){const t=function(t,e){const r=t("reg",["query","HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders","/v","Desktop"]);if(!r)return"";const n=/^\s*Desktop\s+REG_(?:EXPAND_)?SZ\s+(.+)$/im.exec(r),o=n&&n[1].trim();return o&&e(o)?o:""}(i,m);if(t)return t}const y="function"==typeof s.readText?s.readText:f,w=[],k=t=>{t&&String(t).trim()&&w.push(String(t).trim())};if(o){const t=d(n,"OneDrive",e)||d(n,"OneDriveConsumer",e);t&&k(u.join(t,"Desktop")),a&&k(u.join(a,"OneDrive","Desktop")),a&&k(u.join(a,"Desktop"));const r=a?u.join(a,"Desktop"):"",o=w.indexOf(r);o>0&&m(r)&&h(r)&&w.slice(0,o).every((t=>!m(t)||!h(t)))&&(w.splice(o,1),w.unshift(r))}else if("darwin"===e)a&&k(u.join(a,"Desktop"));else{if(k(d(n,"XDG_DESKTOP_DIR",e)),a){const t=y(u.join(a,".config","user-dirs.dirs")),e=t&&/^\s*XDG_DESKTOP_DIR\s*=\s*"?([^"\n]+)"?\s*$/m.exec(t);e&&k(e[1].replace(/\$HOME\b|\${HOME}/g,a))}a&&k(u.join(a,"Desktop"))}for(const t of w)if(m(t))return t;return a&&(o||"darwin"===e)?u.join(a,"Desktop"):""},resolvePath:function(t,e={}){const{platform:n,win32:o,o:i}=p(e),s=o?r.win32:r.posix,u=t=>({ok:!1,path:null,error:t,expandedHome:!1});if("string"!=typeof t||!t.trim())return u(`a path is required (got ${JSON.stringify(t)})`);const c=t.trim();let l=c,f=!1;if("~"===c||c.startsWith("~/")||o&&c.startsWith("~\\")){const t=g(e);if(!t)return u(`cannot expand "~" in ${JSON.stringify(c)}: this machine reports no home directory. Pass a full absolute path instead.`);l="~"===c?t:s.join(t,c.slice(2)),f=!0}else if(c.startsWith("~"))return u(`${JSON.stringify(c)} names another user's home directory, which cannot be resolved from here. Use "~" for this user, or pass a full absolute path.`);if(l=function(t,{home:e,desktopdir:r,win32:n,P:o}){if(!e||!r)return t;const i=o.join(e,"Desktop"),s=t=>n?t.toLowerCase():t;if(s(i)===s(r))return t;if(s(t)===s(i))return r;const u=i+o.sep;return s(t).startsWith(s(u))?r+o.sep+t.slice(u.length):t}(l,{home:g(e),desktopdir:i.desktopdir,win32:o,P:s}),!f){const t=g(e),r=t?` This machine's home directory is ${t}.`:"";if(o){if((l.startsWith("/")||l.startsWith("\\"))&&!k.test(l))return u(`${JSON.stringify(c)} is not an absolute path on this machine, which runs ${n}. A leading slash here means "the root of the current drive", so writing to it would silently land somewhere other than where you meant. Use a drive-qualified path (C:\\Users\\you\\Desktop\\file.txt) or "~/…".${r}`)}else if(y.test(l)||w.test(l)||k.test(l))return u(`${JSON.stringify(c)} is a Windows path, but this machine runs ${n}. Use a posix path (/home/you/file.txt) or "~/…".${r}`)}const a="string"==typeof i.cwd&&i.cwd.trim()?i.cwd.trim():process.cwd(),d=s.isAbsolute(l)?s.resolve(l):s.resolve(a,l);return s.isAbsolute(d)?{ok:!0,path:d,error:null,expandedHome:f}:u(`${JSON.stringify(c)} is relative and the working directory (${JSON.stringify(a)}) is not absolute, so it cannot be resolved. Pass an absolute path.`)},baseName:function(t){if("string"!=typeof t)return"";const e=t.trim().replace(/[/\\]+$/,"");if(!e)return"";if(/^[A-Za-z]:$/.test(e))return"";const r=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"));return-1===r?e:e.slice(r+1)},hasPosixModes:function(t={}){const{win32:e}=p(t);return!e},appLocale:function(t={}){const{platform:e,env:r,o:n}=p(t);if("string"==typeof n.locale)return h(n.locale);const o=n.env&&"object"==typeof n.env;for(const t of["LC_ALL","LC_CTYPE","LC_MESSAGES","LANG"]){const n=h(d(r,t,e));if(n)return n}const i=String(d(r,"LANGUAGE",e)||"");if(i)for(const t of i.split(":")){const e=h(t);if(e)return e}if(o)return"";try{return h((new Intl.DateTimeFormat).resolvedOptions().locale)}catch{return""}},languageName:function(t,e={}){const{o:r}=p(e);if("string"==typeof r.languageName)return r.languageName;const n=h(t);if(!n)return"";const o=n.split("-")[0];try{return new Intl.DisplayNames(["en"],{type:"language"}).of(o)||""}catch{return""}},normalizeLocale:h};module.exports=S;