aegisone 1.0.34 → 1.0.35

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 (226) hide show
  1. package/LICENSE +661 -0
  2. package/README.md +1 -1
  3. package/SOURCE-OFFER.txt +9 -0
  4. package/bin/aegis.js +1 -322
  5. package/package.json +4 -5
  6. package/scripts/bump.mjs +1 -211
  7. package/scripts/bundle.js +1 -129
  8. package/scripts/predist.mjs +1 -976
  9. package/src/child.js +1 -285
  10. package/src/dispatch.js +1 -269
  11. package/src/doctor.js +1 -639
  12. package/src/host.js +1 -111
  13. package/src/permissions.js +1 -383
  14. package/src/probes.js +1 -159
  15. package/src/release.js +1 -409
  16. package/vendor/cli/package.json +3 -7
  17. package/vendor/cli/scripts/check.mjs +1 -52
  18. package/vendor/cli/scripts/demo.mjs +1 -94
  19. package/vendor/cli/scripts/predist.mjs +1 -75
  20. package/vendor/cli/scripts/runtests.mjs +1 -56
  21. package/vendor/cli/scripts/seal-gate.mjs +1 -74
  22. package/vendor/cli/src/agents.js +1 -139
  23. package/vendor/cli/src/app.js +1 -2957
  24. package/vendor/cli/src/art.js +1 -289
  25. package/vendor/cli/src/chatflow.js +1 -3023
  26. package/vendor/cli/src/checkpoint.js +1 -90
  27. package/vendor/cli/src/clipboard.js +1 -424
  28. package/vendor/cli/src/cloudsync.js +1 -528
  29. package/vendor/cli/src/commands.js +1 -4089
  30. package/vendor/cli/src/config.js +1 -581
  31. package/vendor/cli/src/connect.js +1 -349
  32. package/vendor/cli/src/credentials.js +1 -33
  33. package/vendor/cli/src/deps.js +1 -232
  34. package/vendor/cli/src/devrun.js +1 -187
  35. package/vendor/cli/src/diff.js +1 -333
  36. package/vendor/cli/src/diffview.js +1 -296
  37. package/vendor/cli/src/engine.js +1 -297
  38. package/vendor/cli/src/entitlement.js +1 -355
  39. package/vendor/cli/src/events.js +1 -707
  40. package/vendor/cli/src/export.js +1 -67
  41. package/vendor/cli/src/filepreview.js +1 -153
  42. package/vendor/cli/src/fingerprint.js +1 -592
  43. package/vendor/cli/src/format.js +1 -259
  44. package/vendor/cli/src/fuzzy.js +1 -119
  45. package/vendor/cli/src/history.js +1 -423
  46. package/vendor/cli/src/init.js +1 -175
  47. package/vendor/cli/src/input.js +1 -139
  48. package/vendor/cli/src/keys.js +1 -183
  49. package/vendor/cli/src/markdown.js +1 -306
  50. package/vendor/cli/src/models.js +1 -507
  51. package/vendor/cli/src/naming.js +1 -57
  52. package/vendor/cli/src/overlays.js +1 -462
  53. package/vendor/cli/src/panels.js +1 -1418
  54. package/vendor/cli/src/ping.js +1 -226
  55. package/vendor/cli/src/presence.js +1 -238
  56. package/vendor/cli/src/render.js +1 -516
  57. package/vendor/cli/src/screen.js +1 -518
  58. package/vendor/cli/src/screens.js +1 -896
  59. package/vendor/cli/src/secret.js +1 -59
  60. package/vendor/cli/src/securefs.js +1 -359
  61. package/vendor/cli/src/settings.js +1 -155
  62. package/vendor/cli/src/shared.js +1 -52
  63. package/vendor/cli/src/sharedpaths.js +1 -53
  64. package/vendor/cli/src/signup.js +1 -156
  65. package/vendor/cli/src/summarize.js +1 -95
  66. package/vendor/cli/src/sysdiag.js +1 -585
  67. package/vendor/cli/src/system.js +1 -40
  68. package/vendor/cli/src/theme.js +1 -570
  69. package/vendor/cli/src/title.js +1 -220
  70. package/vendor/cli/src/todos.js +1 -115
  71. package/vendor/cli/src/tokens.js +1 -263
  72. package/vendor/cli/src/topup.js +1 -210
  73. package/vendor/cli/src/update.js +1 -191
  74. package/vendor/cli/vendor/client/aegis.js +1 -2441
  75. package/vendor/cli/vendor/client/attest.js +1 -518
  76. package/vendor/cli/vendor/client/authorship-key.js +1 -410
  77. package/vendor/cli/vendor/client/auto-provision.js +1 -134
  78. package/vendor/cli/vendor/client/brain-catalog.js +1 -268
  79. package/vendor/cli/vendor/client/byok-catalog.js +1 -199
  80. package/vendor/cli/vendor/client/catalog-client.js +1 -487
  81. package/vendor/cli/vendor/client/conversation-export.js +1 -177
  82. package/vendor/cli/vendor/client/credentials.js +1 -494
  83. package/vendor/cli/vendor/client/device-fingerprint.js +1 -141
  84. package/vendor/cli/vendor/client/drive-connect.js +1 -110
  85. package/vendor/cli/vendor/client/drive-upload.js +1 -234
  86. package/vendor/cli/vendor/client/env-file.js +1 -1273
  87. package/vendor/cli/vendor/client/fingerprint.js +1 -1064
  88. package/vendor/cli/vendor/client/foreign-memory.js +1 -669
  89. package/vendor/cli/vendor/client/google-signin.js +1 -133
  90. package/vendor/cli/vendor/client/hooks.js +1 -430
  91. package/vendor/cli/vendor/client/model-discovery.js +1 -373
  92. package/vendor/cli/vendor/client/naming.js +1 -283
  93. package/vendor/cli/vendor/client/platform.js +1 -937
  94. package/vendor/cli/vendor/client/prefs.js +1 -351
  95. package/vendor/cli/vendor/client/presence-constants.js +1 -107
  96. package/vendor/cli/vendor/client/presence.js +1 -438
  97. package/vendor/cli/vendor/client/record-vault.js +3 -1055
  98. package/vendor/cli/vendor/client/session-store.js +1 -575
  99. package/vendor/cli/vendor/client/topup.js +1 -297
  100. package/vendor/cli/vendor/client/touch.js +1 -458
  101. package/vendor/cli/vendor/client/update.js +1 -763
  102. package/vendor/cli/vendor/client/user-models.js +1 -381
  103. package/vendor/cli/vendor/desktop/lib/local/agents.js +1 -105
  104. package/vendor/cli/vendor/desktop/lib/local/attachments.js +1 -276
  105. package/vendor/cli/vendor/desktop/lib/local/autonomous.js +1 -1045
  106. package/vendor/cli/vendor/desktop/lib/local/claude-pro.js +1 -1028
  107. package/vendor/cli/vendor/desktop/lib/local/context.js +1 -125
  108. package/vendor/cli/vendor/desktop/lib/local/engine.js +1 -3666
  109. package/vendor/cli/vendor/desktop/lib/local/entitlement.js +1 -660
  110. package/vendor/cli/vendor/desktop/lib/local/git-scope.js +1 -228
  111. package/vendor/cli/vendor/desktop/lib/local/local.js +1 -2145
  112. package/vendor/cli/vendor/desktop/lib/local/prompt.js +1 -280
  113. package/vendor/cli/vendor/desktop/lib/local/queue.js +1 -560
  114. package/vendor/cli/vendor/desktop/lib/local/session-rounds.js +1 -238
  115. package/vendor/cli/vendor/desktop/lib/local/spill.js +1 -75
  116. package/vendor/cli/vendor/desktop/lib/local/turn-guard.js +1 -300
  117. package/vendor/cli/vendor/desktop/lib/local/worktree-lock.js +1 -235
  118. package/vendor/cli/vendor/desktop/lib/settings.js +1 -890
  119. package/vendor/cli/vendor/desktop/renderer/usage.js +1 -1239
  120. package/vendor/cli/vendor/hosts/install.js +1 -638
  121. package/vendor/cli/vendor/hosts/openai-shim.js +1 -515
  122. package/vendor/cli/vendor/hosts/spec.js +1 -164
  123. package/vendor/cli/vendor/hosts/targets.js +1 -346
  124. package/vendor/cli/vendor/mcp/server.js +1 -221
  125. package/vendor/cli/vendor/mcp/tools.js +1 -408
  126. package/vendor/cli/vendor/one/src/child.js +1 -285
  127. package/vendor/cli/vendor/one/src/permissions.js +1 -383
  128. package/vendor/desktop/bin/aegis.js +1 -32
  129. package/vendor/desktop/lib/account-key.js +1 -56
  130. package/vendor/desktop/lib/auto.js +1 -461
  131. package/vendor/desktop/lib/avatar/companion.js +1 -698
  132. package/vendor/desktop/lib/avatar/cosmetics.js +1 -532
  133. package/vendor/desktop/lib/avatar/events.js +1 -344
  134. package/vendor/desktop/lib/avatar/holder-turn.js +1 -350
  135. package/vendor/desktop/lib/avatar/holders.js +1 -612
  136. package/vendor/desktop/lib/avatar/identity.js +1 -641
  137. package/vendor/desktop/lib/avatar/level.js +1 -368
  138. package/vendor/desktop/lib/avatar/mirror.js +1 -524
  139. package/vendor/desktop/lib/avatar/persona.js +1 -388
  140. package/vendor/desktop/lib/avatar/profile.js +1 -977
  141. package/vendor/desktop/lib/avatar/register.js +1 -307
  142. package/vendor/desktop/lib/avatar/store.js +1 -472
  143. package/vendor/desktop/lib/avatar/tiers.js +1 -38
  144. package/vendor/desktop/lib/avatar/transfer.js +1 -415
  145. package/vendor/desktop/lib/avatar/turn.js +1 -216
  146. package/vendor/desktop/lib/avatar/voice.js +1 -328
  147. package/vendor/desktop/lib/avatar/xp.js +1 -404
  148. package/vendor/desktop/lib/deep-link.js +1 -120
  149. package/vendor/desktop/lib/fingerprint.js +2 -347
  150. package/vendor/desktop/lib/google-connect.js +1 -323
  151. package/vendor/desktop/lib/local/agents.js +1 -105
  152. package/vendor/desktop/lib/local/attachments.js +1 -276
  153. package/vendor/desktop/lib/local/autonomous.js +1 -1045
  154. package/vendor/desktop/lib/local/claude-pro.js +1 -1028
  155. package/vendor/desktop/lib/local/context.js +1 -125
  156. package/vendor/desktop/lib/local/engine.js +1 -3666
  157. package/vendor/desktop/lib/local/entitlement.js +1 -660
  158. package/vendor/desktop/lib/local/git-scope.js +1 -228
  159. package/vendor/desktop/lib/local/local.js +1 -2145
  160. package/vendor/desktop/lib/local/prompt.js +1 -280
  161. package/vendor/desktop/lib/local/queue.js +1 -560
  162. package/vendor/desktop/lib/local/session-rounds.js +1 -238
  163. package/vendor/desktop/lib/local/spill.js +1 -75
  164. package/vendor/desktop/lib/local/telemetry.js +1 -470
  165. package/vendor/desktop/lib/local/turn-guard.js +1 -300
  166. package/vendor/desktop/lib/local/worktree-lock.js +1 -235
  167. package/vendor/desktop/lib/provider-key-mirror.js +1 -252
  168. package/vendor/desktop/lib/quick-launcher.js +1 -84
  169. package/vendor/desktop/lib/settings.js +1 -890
  170. package/vendor/desktop/lib/sync/memory-queue.js +1 -60
  171. package/vendor/desktop/lib/sync/persist-gate.js +1 -148
  172. package/vendor/desktop/lib/sync/sessions.js +1 -106
  173. package/vendor/desktop/lib/window-state.js +1 -66
  174. package/vendor/desktop/package.json +2 -4
  175. package/vendor/desktop/preload.js +1 -679
  176. package/vendor/desktop/renderer/app.js +1 -7250
  177. package/vendor/desktop/renderer/avatar/assemble.js +1 -335
  178. package/vendor/desktop/renderer/avatar/avatar.js +1 -380
  179. package/vendor/desktop/renderer/avatar/cards.js +1 -141
  180. package/vendor/desktop/renderer/avatar/hud.js +1 -206
  181. package/vendor/desktop/renderer/avatar/machine.js +1 -213
  182. package/vendor/desktop/renderer/avatar/pane.js +1 -439
  183. package/vendor/desktop/renderer/avatar/parts.js +1 -437
  184. package/vendor/desktop/renderer/budget.js +1 -172
  185. package/vendor/desktop/renderer/companion.js +1 -223
  186. package/vendor/desktop/renderer/diff.js +1 -359
  187. package/vendor/desktop/renderer/diffview.js +1 -336
  188. package/vendor/desktop/renderer/filepreview.js +1 -211
  189. package/vendor/desktop/renderer/fingerprint.js +3 -789
  190. package/vendor/desktop/renderer/markdown.js +1 -168
  191. package/vendor/desktop/renderer/provider-mark.js +1 -311
  192. package/vendor/desktop/renderer/provider-toolbar.js +1 -134
  193. package/vendor/desktop/renderer/providers.js +1 -259
  194. package/vendor/desktop/renderer/quick.js +1 -285
  195. package/vendor/desktop/renderer/stream-policy.js +1 -387
  196. package/vendor/desktop/renderer/transcript-view.js +1 -323
  197. package/vendor/desktop/renderer/usage.js +1 -1239
  198. package/vendor/desktop/vendor/aegis.js +1 -2441
  199. package/vendor/desktop/vendor/attest.js +1 -518
  200. package/vendor/desktop/vendor/authorship-key.js +1 -410
  201. package/vendor/desktop/vendor/auto-provision.js +1 -134
  202. package/vendor/desktop/vendor/brain-catalog.js +1 -268
  203. package/vendor/desktop/vendor/byok-catalog.js +1 -199
  204. package/vendor/desktop/vendor/catalog-client.js +1 -487
  205. package/vendor/desktop/vendor/conversation-export.js +1 -177
  206. package/vendor/desktop/vendor/credentials.js +1 -494
  207. package/vendor/desktop/vendor/device-fingerprint.js +1 -141
  208. package/vendor/desktop/vendor/drive-connect.js +1 -110
  209. package/vendor/desktop/vendor/drive-upload.js +1 -234
  210. package/vendor/desktop/vendor/env-file.js +1 -1273
  211. package/vendor/desktop/vendor/fingerprint.js +1 -1064
  212. package/vendor/desktop/vendor/foreign-memory.js +1 -669
  213. package/vendor/desktop/vendor/google-signin.js +1 -133
  214. package/vendor/desktop/vendor/hooks.js +1 -430
  215. package/vendor/desktop/vendor/model-discovery.js +1 -373
  216. package/vendor/desktop/vendor/naming.js +1 -283
  217. package/vendor/desktop/vendor/platform.js +1 -937
  218. package/vendor/desktop/vendor/prefs.js +1 -351
  219. package/vendor/desktop/vendor/presence-constants.js +1 -107
  220. package/vendor/desktop/vendor/presence.js +1 -438
  221. package/vendor/desktop/vendor/record-vault.js +3 -1055
  222. package/vendor/desktop/vendor/session-store.js +1 -575
  223. package/vendor/desktop/vendor/topup.js +1 -297
  224. package/vendor/desktop/vendor/touch.js +1 -458
  225. package/vendor/desktop/vendor/update.js +1 -763
  226. package/vendor/desktop/vendor/user-models.js +1 -381
@@ -1,765 +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
- /**
7
- * "There is a newer version" — the notice this CLI never had.
8
- *
9
- * Checked on 2026-09-15: there was no update check anywhere in the client, so
10
- * a user learned about a release only by guessing to run
11
- * `npm i -g aegiscode@latest`. Publishing therefore reached almost nobody, and
12
- * the installed base drifted months behind the registry.
13
- *
14
- * Three rules, because an update check is a background nicety that must never
15
- * become a liability:
16
- * · it never blocks — the caller gets a cached answer immediately and the
17
- * network call settles whenever it settles;
18
- * · it never throws — offline, proxied, rate-limited or garbage JSON all
19
- * mean "no notice", not a broken CLI;
20
- * · it never nags — one check a day, cached, and nothing printed when the
21
- * user is already current.
22
- */
23
-
24
- const https = require('node:https');
25
- const fs = require('node:fs');
26
- // Optional: the platform resolver is a sibling in every staged layout
27
- // (`vendor/update.js` + `vendor/platform.js`, `vendor/client/update.js` +
28
- // `vendor/client/platform.js`), but a host that ships only the checker must
29
- // still load — a missing resolver degrades to the old bare-name behaviour
30
- // rather than throwing at require() time.
31
- let platformHelpers = null;
32
- try {
33
- platformHelpers = require('./platform.js');
34
- } catch {
35
- platformHelpers = null;
36
- }
37
-
38
- const REGISTRY = 'https://registry.npmjs.org';
39
- //: Default package. Both hosts ship from npm — the CLI as `aegiscode`, the
40
- //: desktop as `aegis-desktop` — so one checker serves both; the caller names
41
- //: which one it is.
42
- const PKG = 'aegiscode';
43
- /** One check a day. A CLI that pings the registry every launch is spyware. */
44
- const CHECK_INTERVAL_MS = 24 * 60 * 60 * 1000;
45
- /** The registry is not on the critical path; give up quickly and silently. */
46
- const TIMEOUT_MS = 2500;
47
-
48
- /** Compare two semver-ish strings. Returns true when `latest` is newer. */
49
- function isNewer(latest, current) {
50
- const parse = (v) =>
51
- String(v || '')
52
- .trim()
53
- .replace(/^v/, '')
54
- .split('-')[0] // a prerelease never counts as newer than its release
55
- .split('.')
56
- .map((n) => Number.parseInt(n, 10) || 0);
57
- const a = parse(latest);
58
- const b = parse(current);
59
- for (let i = 0; i < Math.max(a.length, b.length); i++) {
60
- const x = a[i] || 0;
61
- const y = b[i] || 0;
62
- if (x !== y) return x > y;
63
- }
64
- return false;
65
- }
66
-
67
- /**
68
- * Why a check produced no version. Every one of these used to collapse into a
69
- * bare `null`, which is enough for the CLI ("no notice") but NOT enough for a
70
- * host that shows the user a sentence about it: the desktop rendered all six
71
- * as "registry unreachable", so a 2.5s timeout on a slow VPN was reported as
72
- * fact about the registry — a false accusation, and unactionable.
73
- */
74
- const REASONS = Object.freeze({
75
- TIMEOUT: 'timeout',
76
- NETWORK: 'network',
77
- NOT_FOUND: 'not-found',
78
- FORBIDDEN: 'forbidden',
79
- HTTP: 'http',
80
- MALFORMED: 'malformed',
81
- TOO_LARGE: 'too-large',
82
- });
83
-
84
- /**
85
- * Does this failure mean "the network let us down" (worth retrying silently, and
86
- * NOT worth telling the user about) rather than "the registry answered, and the
87
- * answer was no" (a real condition the user may need to act on)?
88
- *
89
- * `status` is the HTTP status when there was one, so 5xx/429 count as transient
90
- * while 404/403 do not.
91
- */
92
- function isTransientReason(reason, status = null) {
93
- if (reason === REASONS.TIMEOUT || reason === REASONS.NETWORK) return true;
94
- if (reason === REASONS.HTTP) return !status || status >= 500 || status === 429;
95
- return false;
96
- }
97
-
98
- /**
99
- * Fetch the registry's `latest` dist-tag, saying WHY when it fails.
100
- *
101
- * Resolves `{ ok, latest, reason, status }` and never rejects: `ok` is the
102
- * version question, `reason` (one of REASONS) is the diagnosis. Use this when
103
- * you intend to tell someone what happened; use `fetchLatest` when you only
104
- * care whether there is a notice.
105
- */
106
- function fetchLatestDetailed({ pkg = PKG, timeoutMs = TIMEOUT_MS } = {}) {
107
- return new Promise((resolve) => {
108
- let settled = false;
109
- const done = (v) => {
110
- if (!settled) {
111
- settled = true;
112
- resolve(v);
113
- }
114
- };
115
- const fail = (reason, status = null) =>
116
- done({ ok: false, latest: null, reason, status });
117
- const succeed = (latest) => done({ ok: true, latest, reason: null, status: 200 });
118
- try {
119
- // The abbreviated metadata document: a few KB instead of the full
120
- // packument, which for a package with this many releases is megabytes.
121
- const req = https.get(
122
- `${REGISTRY}/${pkg}`,
123
- { headers: { accept: 'application/vnd.npm.install-v1+json' }, timeout: timeoutMs },
124
- (res) => {
125
- const status = res.statusCode;
126
- if (status !== 200) {
127
- res.resume();
128
- if (status === 404) return fail(REASONS.NOT_FOUND, status);
129
- if (status === 401 || status === 403) return fail(REASONS.FORBIDDEN, status);
130
- return fail(REASONS.HTTP, status);
131
- }
132
- let body = '';
133
- res.setEncoding('utf8');
134
- res.on('data', (c) => {
135
- body += c;
136
- if (body.length > 2_000_000) {
137
- req.destroy();
138
- fail(REASONS.TOO_LARGE, status);
139
- }
140
- });
141
- res.on('end', () => {
142
- try {
143
- const tags = JSON.parse(body)['dist-tags'];
144
- const latest = (tags && tags.latest) || null;
145
- // A 200 that parses but names no `latest` is a malformed
146
- // document, not a slow network — do not invite a retry for it.
147
- if (!latest) return fail(REASONS.MALFORMED, status);
148
- succeed(latest);
149
- } catch {
150
- fail(REASONS.MALFORMED, status);
151
- }
152
- });
153
- }
154
- );
155
- req.on('timeout', () => {
156
- req.destroy();
157
- fail(REASONS.TIMEOUT);
158
- });
159
- // Every socket-level failure — DNS (ENOTFOUND), refused (ECONNREFUSED),
160
- // TLS, proxy, reset mid-body — is the same story to a user: the network.
161
- req.on('error', () => fail(REASONS.NETWORK));
162
- } catch {
163
- fail(REASONS.NETWORK);
164
- }
165
- });
166
- }
167
-
168
- /** Fetch the registry's `latest` dist-tag. Resolves null on any failure. */
169
- function fetchLatest(opts = {}) {
170
- return fetchLatestDetailed(opts).then((r) => (r.ok ? r.latest : null));
171
- }
172
-
173
- //: Where the AEGIS server answers "am I still allowed to talk to you".
174
- const DEFAULT_API_BASE = 'https://aegiscloud.org';
175
- /** /api/v1/version is a tiny JSON document; anything bigger is a proxy page. */
176
- const VERSION_BODY_CAP = 64 * 1024;
177
-
178
- /**
179
- * Ask the SERVER whether this client is still serviceable.
180
- *
181
- * Why this exists next to the npm check: they answer different questions.
182
- * The registry says what was *published*; the server says what it will
183
- * *accept*. aegis1 refuses every request from a client below
184
- * `MIN_CLIENT_VERSION` with a 426, so a client that only asks npm learns it is
185
- * unservicable by being refused mid-task — an outage, not a notice. Asking
186
- * `/api/v1/version` first turns the same fact into a sentence the user reads
187
- * before they hit the wall.
188
- *
189
- * `/api/v1/version` is informational: it never refuses anyone, and it echoes
190
- * the verdict for the version header we send (`upgrade_required`).
191
- *
192
- * Resolves `{ ok, minClient, latestCli, latestDesktop, upgradeRequired,
193
- * downloadUrl, reason, status }` and never rejects — same contract as
194
- * `fetchLatestDetailed`, so a host can render "registry unreachable" and
195
- * "server unreachable" differently instead of inventing a third story.
196
- */
197
- function fetchServerVersionDetailed({
198
- base = DEFAULT_API_BASE,
199
- clientVersion = null,
200
- timeoutMs = TIMEOUT_MS,
201
- getImpl = null,
202
- } = {}) {
203
- return new Promise((resolve) => {
204
- let settled = false;
205
- const done = (v) => {
206
- if (!settled) {
207
- settled = true;
208
- resolve(v);
209
- }
210
- };
211
- const fail = (reason, status = null) =>
212
- done({
213
- ok: false, minClient: null, latestCli: null, latestDesktop: null,
214
- upgradeRequired: null, downloadUrl: '', reason, status,
215
- });
216
- const succeed = (body, status) => {
217
- const minClient = body && typeof body.min_client === 'string' ? body.min_client : null;
218
- // A 200 without `min_client` is malformed, not a slow network: do not
219
- // invite a retry ladder for a document that will parse the same way.
220
- if (!minClient) return fail(REASONS.MALFORMED, status);
221
- done({
222
- ok: true,
223
- minClient,
224
- latestCli: typeof body.latest_cli === 'string' ? body.latest_cli : '',
225
- latestDesktop: typeof body.latest_desktop === 'string' ? body.latest_desktop : '',
226
- // Trust the header echo only when we actually sent a version: without
227
- // one the server answers for `require_header=False` and the answer is
228
- // about nothing in particular. `null` here means "the server did not
229
- // say", which is different from "the server said no" — the caller must
230
- // be able to fall back without overriding an answer it was given.
231
- upgradeRequired:
232
- clientVersion && typeof body.upgrade_required === 'boolean'
233
- ? body.upgrade_required
234
- : null,
235
- downloadUrl: typeof body.download_url === 'string' ? body.download_url : '',
236
- reason: null,
237
- status,
238
- });
239
- };
240
-
241
- try {
242
- const url = `${String(base || DEFAULT_API_BASE).replace(/\/+$/, '')}/api/v1/version`;
243
- const headers = { accept: 'application/json' };
244
- if (clientVersion) headers['X-AEGIS-Version'] = String(clientVersion);
245
-
246
- const onResponse = (res) => {
247
- const status = res.statusCode;
248
- if (status !== 200) {
249
- res.resume();
250
- if (status === 404) return fail(REASONS.NOT_FOUND, status);
251
- if (status === 401 || status === 403) return fail(REASONS.FORBIDDEN, status);
252
- // 426 here would mean the endpoint itself were gated; treat it as a
253
- // real answer rather than a transport failure if it ever happens.
254
- if (status === 426) return fail(REASONS.HTTP, status);
255
- return fail(REASONS.HTTP, status);
256
- }
257
- let body = '';
258
- res.setEncoding('utf8');
259
- res.on('data', (c) => {
260
- body += c;
261
- if (body.length > VERSION_BODY_CAP) {
262
- res.destroy();
263
- fail(REASONS.TOO_LARGE, status);
264
- }
265
- });
266
- res.on('end', () => {
267
- if (settled) return;
268
- try {
269
- succeed(JSON.parse(body), status);
270
- } catch {
271
- fail(REASONS.MALFORMED, status);
272
- }
273
- });
274
- };
275
-
276
- if (typeof getImpl === 'function') {
277
- // Injected transport for tests and hosts that already own a fetch:
278
- // `getImpl({url, headers, timeoutMs})` resolves `{status, text}`.
279
- Promise.resolve(getImpl({ url, headers, timeoutMs }))
280
- .then((r) => {
281
- const status = r && r.status != null ? r.status : 0;
282
- if (!status) return fail(REASONS.NETWORK);
283
- if (status !== 200) {
284
- if (status === 404) return fail(REASONS.NOT_FOUND, status);
285
- if (status === 401 || status === 403) return fail(REASONS.FORBIDDEN, status);
286
- return fail(REASONS.HTTP, status);
287
- }
288
- const text = r && typeof r.text === 'string' ? r.text : '';
289
- if (text.length > VERSION_BODY_CAP) return fail(REASONS.TOO_LARGE, status);
290
- try {
291
- succeed(JSON.parse(text), status);
292
- } catch {
293
- fail(REASONS.MALFORMED, status);
294
- }
295
- })
296
- .catch(() => fail(REASONS.NETWORK));
297
- return;
298
- }
299
-
300
- const req = require(/^http:\/\//i.test(url) ? 'node:http' : 'node:https')
301
- .get(url, { headers, timeout: timeoutMs }, onResponse);
302
- req.on('timeout', () => {
303
- req.destroy();
304
- fail(REASONS.TIMEOUT);
305
- });
306
- req.on('error', () => fail(REASONS.NETWORK));
307
- } catch {
308
- fail(REASONS.NETWORK);
309
- }
310
- });
311
- }
312
-
313
- /** The server's minimum client version, or null. */
314
- function fetchServerVersion(opts = {}) {
315
- return fetchServerVersionDetailed(opts).then((r) => (r.ok ? r.minClient : null));
316
- }
317
-
318
- /**
319
- * The server's verdict, expressed in the shape the notice/plan code already
320
- * speaks: `{ behind, latest, required, downloadUrl, ok, reason, status }`.
321
- *
322
- * `behind` is true when the SERVER says this client is below its minimum —
323
- * regardless of whether npm happens to have something newer. That ordering is
324
- * deliberate: being refused is actionable now, being merely superseded is not.
325
- */
326
- async function serverUpdateVerdict({
327
- current,
328
- base = DEFAULT_API_BASE,
329
- timeoutMs = TIMEOUT_MS,
330
- getImpl = null,
331
- } = {}) {
332
- const res = await fetchServerVersionDetailed({ base, clientVersion: current, timeoutMs, getImpl });
333
- if (!res.ok) {
334
- return { ok: false, behind: false, latest: null, required: null, downloadUrl: '', reason: res.reason, status: res.status };
335
- }
336
- const required = res.minClient || null;
337
- // The server's echo decides. Falling back to local arithmetic only when it
338
- // said nothing (`null`) — OR'ing the two would let our own comparison
339
- // override the very authority we asked, which is the bug this line exists to
340
- // not have.
341
- const behind =
342
- res.upgradeRequired === true
343
- ? true
344
- : res.upgradeRequired === false
345
- ? false
346
- : required
347
- ? isNewer(required, current)
348
- : false;
349
- return {
350
- ok: true,
351
- behind,
352
- // The server's own minimum is the target when it is the thing refusing us;
353
- // a published version is preferred when it names one, because that is what
354
- // the user should actually install.
355
- latest: (behind && (res.latestCli || res.latestDesktop)) || required,
356
- latestCli: res.latestCli,
357
- latestDesktop: res.latestDesktop,
358
- required,
359
- downloadUrl: res.downloadUrl,
360
- reason: null,
361
- status: res.status,
362
- };
363
- }
364
-
365
- /**
366
- * The notice to show, from cache. Never waits on the network.
367
- *
368
- * `cache` is the persisted `{ checkedAt, latest }` blob; `save` persists a new
369
- * one. Returns `{ latest, behind }`, and kicks off a refresh in the background
370
- * when the cache is stale.
371
- */
372
- function updateNotice({
373
- current,
374
- cache,
375
- save,
376
- now = Date.now(),
377
- fetchImpl = fetchLatest,
378
- intervalMs = CHECK_INTERVAL_MS,
379
- } = {}) {
380
- const c = cache || {};
381
- const fresh = typeof c.checkedAt === 'number' && now - c.checkedAt < intervalMs;
382
-
383
- if (!fresh) {
384
- // Fire and forget: this run reports on what was already known, and the
385
- // answer lands for the next one. A first run therefore never shows a
386
- // notice, which is correct — it has nothing to compare against yet.
387
- Promise.resolve(fetchImpl())
388
- .then((latest) => {
389
- if (latest && typeof save === 'function') save({ checkedAt: now, latest });
390
- })
391
- .catch(() => {});
392
- }
393
-
394
- const latest = c.latest || null;
395
- return { latest, behind: !!(latest && isNewer(latest, current)) };
396
- }
397
-
398
- /**
399
- * Turn a plan's `apply` argv into something this host can actually spawn.
400
- *
401
- * `apply` is deliberately platform-neutral (`{command:'npm', args:[...]}`): it
402
- * is also the string shown to the user, and `npm i -g x@latest` is what they
403
- * should type on every OS. Spawning it is a different question, and the one
404
- * that was wrong in two ways:
405
- *
406
- * · win32 — npm is `npm.cmd`, a batch file. `execFile('npm', …)` cannot
407
- * execute it (Node refuses `.cmd` without a shell since the CVE-2024-27980
408
- * fix), so the button died with ENOENT while the printed instruction looked
409
- * correct. The fix is the host's own shell (`cmd.exe /d /s /c "…"`), not a
410
- * hardcoded `.cmd` suffix: PATHEXT decides, and `shellSpec` already knows
411
- * how to ask cmd to run a line.
412
- *
413
- * · GUI launches — a macOS `.app` and a Linux `.desktop` do not inherit the
414
- * user's shell PATH, so a bare `npm` is often not resolvable even where the
415
- * user just ran `npm i -g` in a terminal. Resolving the absolute path first
416
- * is the difference between updating and "npm: not found".
417
- *
418
- * Returns `{command, args, shell, script}`, `shell` always false (we hand the
419
- * line to `cmd.exe` ourselves rather than letting Node quote it), and `null`
420
- * for a plan with nothing to run.
421
- */
422
- function installSpawn(target, options = {}) {
423
- if (!target || typeof target.command !== 'string' || !target.command) return null;
424
- const o = options && typeof options === 'object' ? options : {};
425
- const platformName = typeof o.platform === 'string' && o.platform ? o.platform : process.platform;
426
- const env = o.env && typeof o.env === 'object' ? o.env : process.env;
427
- const helpers = o.helpers === undefined ? platformHelpers : o.helpers;
428
- const args = Array.isArray(target.args) ? target.args.map(String) : [];
429
- const script = [target.command, ...args].join(' ');
430
-
431
- if (platformName === 'win32') {
432
- const spec = helpers && typeof helpers.shellSpec === 'function'
433
- ? helpers.shellSpec({ platform: platformName, env })
434
- : { cmd: 'cmd.exe', arg: '/d /s /c' };
435
- return {
436
- command: spec.cmd,
437
- args: [...String(spec.arg).split(' '), script],
438
- shell: false,
439
- script,
440
- };
441
- }
442
-
443
- // POSIX. Prefer the absolute path: a GUI process' PATH is not the shell's.
444
- let command = target.command;
445
- if (helpers && typeof helpers.resolveExecutable === 'function') {
446
- try {
447
- const resolved = helpers.resolveExecutable(target.command, {
448
- platform: platformName,
449
- env,
450
- ...(typeof o.exists === 'function' ? { exists: o.exists } : {}),
451
- });
452
- if (resolved) command = resolved;
453
- } catch {
454
- /* resolution is an optimisation, not a precondition */
455
- }
456
- }
457
- return { command, args: args.slice(), shell: false, script };
458
- }
459
-
460
- /**
461
- * "What happens next", from a check result — the ONE verdict every applier
462
- * consumes (AEGISONE, decision D7).
463
- *
464
- * There is one channel: npm. The window and the CLI install different packages,
465
- * so the *pkg* differs, but both are applied with the installer that owns the
466
- * running copy (`APPLIERS[method]`). What must not be duplicated is the
467
- * *decision*: whether there is anything to do, which version it is, which
468
- * applier owns it and what the user is told to run. Both hosts ask this
469
- * function, so the sentence a user reads in the terminal and the sentence the
470
- * window shows cannot drift.
471
- *
472
- * Pure: no fetch, no clock, no cache. Feed it a result from `checkPublished`
473
- * (or from the cached `updateNotice`) and it names the next action.
474
- *
475
- * @param {{current: string, latest: ?string, behind: boolean, channel?: 'npm'|'desktop', pkg?: string}} input
476
- */
477
- function updatePlan({ current, latest, behind, channel = 'npm', pkg = PKG, method = 'npm' } = {}) {
478
- const currentText = String(current == null ? '' : current);
479
- const latestText = latest ? String(latest) : null;
480
- const pending = Boolean(behind) && Boolean(latestText);
481
- if (!pending) {
482
- return {
483
- channel,
484
- method,
485
- current: currentText,
486
- latest: latestText,
487
- behind: false,
488
- action: 'none',
489
- applier: 'none',
490
- instruction: null,
491
- apply: null,
492
- };
493
- }
494
- // Which installer owns this copy. The command is not cosmetic: `npm i -g`
495
- // against a pip-installed `aegiscode` writes a second copy beside the one the
496
- // user actually runs, and the "upgrade" appears to do nothing. Same for an
497
- // `npx` run, which has nothing installed to upgrade at all.
498
- const applier = APPLIERS[method] || APPLIERS.npm;
499
- return {
500
- channel,
501
- method,
502
- current: currentText,
503
- latest: latestText,
504
- behind: true,
505
- action: applier.action,
506
- applier: applier.name,
507
- instruction: applier.instruction(pkg),
508
- apply: applier.apply ? applier.apply(pkg) : null,
509
- };
510
- }
511
-
512
- /**
513
- * The ways this product reaches a machine, and what "update it" means for each.
514
- *
515
- * `apply` names argv to run — it is what the window's Update button and the
516
- * CLI's `/upgrade apply` execute. `null` means there is nothing to install:
517
- * `npx` fetches `latest` on every launch by definition, and a source checkout
518
- * belongs to its owner's git remote.
519
- */
520
- const APPLIERS = Object.freeze({
521
- npm: Object.freeze({
522
- name: 'npm',
523
- action: 'npm-update',
524
- instruction: (pkg) => `npm i -g ${pkg}@latest`,
525
- apply: (pkg) => ({ command: 'npm', args: ['i', '-g', `${pkg}@latest`] }),
526
- }),
527
- pip: Object.freeze({
528
- name: 'pip',
529
- action: 'pip-update',
530
- // The published pip package is a launcher for the npm one, so this is
531
- // genuinely a different command — not an npm call with a different word.
532
- instruction: (pkg) => `pip install -U ${pkg}`,
533
- apply: (pkg) => ({ command: process.platform === 'win32' ? 'python' : 'python3',
534
- args: ['-m', 'pip', 'install', '-U', pkg] }),
535
- }),
536
- npx: Object.freeze({
537
- name: 'none',
538
- action: 'npx-update',
539
- instruction: () => 'already fetched fresh on every run — restart to pick up the new version',
540
- apply: null,
541
- }),
542
- source: Object.freeze({
543
- name: 'git',
544
- action: 'source-update',
545
- instruction: () => 'git pull && npm ci (this copy is a source checkout)',
546
- apply: null,
547
- }),
548
- });
549
-
550
- /**
551
- * Which installer owns the copy that is running — so the sentence names a
552
- * command that actually changes THIS binary.
553
- *
554
- * Order matters. An explicit declaration wins (the pip launcher sets
555
- * `AEGIS_INSTALL_METHOD=pip` before exec'ing the real CLI, which is the only
556
- * way the npm package can know a Python install is driving it). Then npx, which
557
- * is detectable from the argv it builds. Then a source checkout, then npm.
558
- *
559
- * Pure and injectable: `env`, `argv` and a file probe, no `process` reads, so a
560
- * test can assert every branch without npm or pip being installed.
561
- */
562
- function detectInstallMethod({
563
- env = {}, argv = [], pkg = PKG, fileExists = () => false, entry = '',
564
- } = {}) {
565
- const declared = String((env && env.AEGIS_INSTALL_METHOD) || '').trim().toLowerCase();
566
- if (declared && Object.prototype.hasOwnProperty.call(APPLIERS, declared)) return declared;
567
-
568
- const joined = argv.map((a) => String(a)).join(' ');
569
- if (/\bnpx\b/.test(joined) || /_npx[\\/]/.test(joined) || /_npx[\\/]/.test(entry)) return 'npx';
570
- if (/[\\/]pipx[\\/]venvs[\\/]/.test(entry) || /[\\/]site-packages[\\/]/.test(entry)) return 'pip';
571
- if (/[\\/]node_modules[\\/]/.test(entry)) return 'npm';
572
- // A git checkout has the repo's own marker files; a global npm install does
573
- // not (they are not in the package's `files` list).
574
- if (fileExists('.git') && fileExists('client/update.js')) return 'source';
575
- return 'npm';
576
- }
577
-
578
- /**
579
- * The same once-a-day check as `updateNotice`, but *awaited* and detailed.
580
- *
581
- * Why both exist: `updateNotice` answers immediately from cache and lets the
582
- * refresh land later, which is right for a CLI that must never block a launch.
583
- * A host that is *showing the user a banner about it* — the window, or
584
- * `aegis doctor` — needs the full result (`.ok`, `.reason`, `.status`) and is
585
- * willing to wait for it. So this is not a second check: it is the same probe
586
- * (`fetchLatestDetailed`, same `TIMEOUT_MS`, same `REASONS` taxonomy) and the
587
- * same `CHECK_INTERVAL_MS` cache rule, extracted so that the desktop applier
588
- * stops carrying its own copy of the fetching logic (D7: the desktop keeps its
589
- * applier and loses its version fetch).
590
- *
591
- * Never throws: a failure is a result with `ok: false` and a reason.
592
- *
593
- * @returns {Promise<{ok: boolean, latest: ?string, behind: boolean, reason: ?string,
594
- * status: ?number, cached: boolean, checkedAt: ?number}>}
595
- */
596
- async function checkPublished({
597
- current,
598
- cache,
599
- save,
600
- now = Date.now(),
601
- fetchImpl = fetchLatestDetailed,
602
- intervalMs = CHECK_INTERVAL_MS,
603
- timeoutMs = TIMEOUT_MS,
604
- pkg = PKG,
605
- } = {}) {
606
- const c = cache || null;
607
- const fresh = Boolean(c) && typeof c.checkedAt === 'number' && now - c.checkedAt < intervalMs;
608
- if (fresh) {
609
- const latest = c.latest || null;
610
- return {
611
- ok: Boolean(latest),
612
- latest,
613
- behind: !!(latest && isNewer(latest, current)),
614
- reason: latest ? null : c.reason || null,
615
- status: latest ? 200 : c.status == null ? null : c.status,
616
- cached: true,
617
- checkedAt: c.checkedAt,
618
- };
619
- }
620
-
621
- let res;
622
- try {
623
- res = await fetchImpl({ pkg, timeoutMs });
624
- } catch (err) {
625
- res = { ok: false, latest: null, reason: REASONS.NETWORK, status: null, error: String((err && err.message) || err) };
626
- }
627
- const record = {
628
- checkedAt: now,
629
- latest: res && res.latest ? res.latest : null,
630
- reason: (res && res.reason) || null,
631
- status: res && res.status != null ? res.status : null,
632
- };
633
- if (typeof save === 'function') {
634
- try {
635
- save(record);
636
- } catch {
637
- /* failing to persist a notice is never worth failing the call */
638
- }
639
- }
640
- return {
641
- ok: Boolean(res && res.ok && res.latest),
642
- latest: record.latest,
643
- behind: !!(record.latest && isNewer(record.latest, current)),
644
- reason: record.reason,
645
- status: record.status,
646
- cached: false,
647
- checkedAt: now,
648
- };
649
- }
650
-
651
- /**
652
- * One line for the welcome box, or null when there is nothing to say.
653
- *
654
- * Rendered from `updatePlan`, not from a second copy of the sentence: the
655
- * command the terminal tells the user to run and the command the window's
656
- * banner offers are the same string produced by the same verdict.
657
- *
658
- * `method` is the install channel the caller detected (see
659
- * `detectInstallMethod`). It is threaded through rather than assumed to be npm
660
- * because the previous version returned `null` — silence — for every channel
661
- * that was not npm, so a pip install and an npx run were never told a release
662
- * existed. A host that knows how it was installed should say so.
663
- */
664
- function updateLine({ current, latest, behind, pkg = PKG, method = 'npm' }) {
665
- const plan = updatePlan({ current, latest, behind, channel: 'npm', pkg, method });
666
- if (!plan.behind) return null;
667
- const head = `Update available: ${plan.current} → ${plan.latest}`;
668
- // `apply` is null for the two channels with nothing to install, whose
669
- // instruction is already a sentence — prefixing those with "run:" would read
670
- // as a command that does not exist.
671
- return plan.apply
672
- ? `${head} run: ${plan.instruction}`
673
- : `${head} ${plan.instruction}`;
674
- }
675
-
676
- /**
677
- * The server's verdict, from cache. Never waits on the network.
678
- *
679
- * Same contract and the same once-a-day rule as `updateNotice`, for the same
680
- * reason: the welcome box draws from what the last run learned, and the
681
- * refresh lands for the next one. A first run shows nothing, which is right —
682
- * it has no verdict yet.
683
- *
684
- * Returns `{ behind, latest, required, downloadUrl }`. `behind` is the server's
685
- * answer, not a comparison this module invented, so the box says "update" only
686
- * when the server would actually refuse this client.
687
- */
688
- function serverNotice({
689
- current,
690
- cache,
691
- save,
692
- now = Date.now(),
693
- verdictImpl = serverUpdateVerdict,
694
- intervalMs = CHECK_INTERVAL_MS,
695
- } = {}) {
696
- const c = cache || {};
697
- const fresh = typeof c.checkedAt === 'number' && now - c.checkedAt < intervalMs;
698
-
699
- if (!fresh) {
700
- Promise.resolve()
701
- .then(() => verdictImpl({ current }))
702
- .then((v) => {
703
- if (!v || typeof save !== 'function') return;
704
- // Persist the verdict even when it is "not behind": that is what tells
705
- // the next run it already asked today, and stops a check per launch.
706
- save({
707
- checkedAt: now,
708
- behind: Boolean(v.behind),
709
- required: v.required || null,
710
- latest: v.latest || null,
711
- downloadUrl: v.downloadUrl || '',
712
- reason: v.reason || null,
713
- });
714
- })
715
- .catch(() => {});
716
- }
717
-
718
- return {
719
- behind: Boolean(c.behind),
720
- latest: c.latest || null,
721
- required: c.required || null,
722
- downloadUrl: c.downloadUrl || '',
723
- };
724
- }
725
-
726
- /**
727
- * The line for the welcome box when the SERVER says this build is too old.
728
- *
729
- * Distinct from `updateLine` on purpose: "a newer release exists" and "the
730
- * server will refuse you" are different urgency, and only the second one means
731
- * the app is about to stop working. Says where to get it, because a user who
732
- * is being cut off needs a destination, not a version number.
733
- */
734
- function serverUpdateLine({ behind, latest, required, downloadUrl } = {}) {
735
- if (!behind) return null;
736
- const target = latest || required || '';
737
- const head = target
738
- ? `This build is no longer served — update to v${target}.`
739
- : 'This build is no longer served — update to the latest release.';
740
- const where = downloadUrl ? ` ${downloadUrl}` : '';
741
- return `${head}${where}`;
742
- }
743
-
744
- module.exports = {
745
- isNewer,
746
- fetchLatest,
747
- fetchLatestDetailed,
748
- fetchServerVersion,
749
- fetchServerVersionDetailed,
750
- serverUpdateVerdict,
751
- serverNotice,
752
- serverUpdateLine,
753
- isTransientReason,
754
- updateNotice,
755
- checkPublished,
756
- updatePlan,
757
- installSpawn,
758
- updateLine,
759
- detectInstallMethod,
760
- APPLIERS,
761
- PKG,
762
- CHECK_INTERVAL_MS,
763
- REASONS,
764
- DEFAULT_API_BASE,
765
- };
3
+ const https=require("node:https"),fs=require("node:fs");let platformHelpers=null;try{platformHelpers=require("./platform.js")}catch{platformHelpers=null}const REGISTRY="https://registry.npmjs.org",PKG="aegiscode",CHECK_INTERVAL_MS=864e5,TIMEOUT_MS=2500;function isNewer(e,t){const n=e=>String(e||"").trim().replace(/^v/,"").split("-")[0].split(".").map((e=>Number.parseInt(e,10)||0)),r=n(e),s=n(t);for(let e=0;e<Math.max(r.length,s.length);e++){const t=r[e]||0,n=s[e]||0;if(t!==n)return t>n}return!1}const REASONS=Object.freeze({TIMEOUT:"timeout",NETWORK:"network",NOT_FOUND:"not-found",FORBIDDEN:"forbidden",HTTP:"http",MALFORMED:"malformed",TOO_LARGE:"too-large"});function isTransientReason(e,t=null){return e===REASONS.TIMEOUT||e===REASONS.NETWORK||e===REASONS.HTTP&&(!t||t>=500||429===t)}function fetchLatestDetailed({pkg:e=PKG,timeoutMs:t=TIMEOUT_MS}={}){return new Promise((n=>{let r=!1;const s=e=>{r||(r=!0,n(e))},l=(e,t=null)=>s({ok:!1,latest:null,reason:e,status:t});try{const n=https.get(`${REGISTRY}/${e}`,{headers:{accept:"application/vnd.npm.install-v1+json"},timeout:t},(e=>{const t=e.statusCode;if(200!==t)return e.resume(),l(404===t?REASONS.NOT_FOUND:401===t||403===t?REASONS.FORBIDDEN:REASONS.HTTP,t);let r="";e.setEncoding("utf8"),e.on("data",(e=>{r+=e,r.length>2e6&&(n.destroy(),l(REASONS.TOO_LARGE,t))})),e.on("end",(()=>{try{const e=JSON.parse(r)["dist-tags"],n=e&&e.latest||null;if(!n)return l(REASONS.MALFORMED,t);(e=>{s({ok:!0,latest:e,reason:null,status:200})})(n)}catch{l(REASONS.MALFORMED,t)}}))}));n.on("timeout",(()=>{n.destroy(),l(REASONS.TIMEOUT)})),n.on("error",(()=>l(REASONS.NETWORK)))}catch{l(REASONS.NETWORK)}}))}function fetchLatest(e={}){return fetchLatestDetailed(e).then((e=>e.ok?e.latest:null))}const DEFAULT_API_BASE="https://aegiscloud.org",VERSION_BODY_CAP=65536;function fetchServerVersionDetailed({base:e=DEFAULT_API_BASE,clientVersion:t=null,timeoutMs:n=TIMEOUT_MS,getImpl:r=null}={}){return new Promise((s=>{let l=!1;const o=e=>{l||(l=!0,s(e))},a=(e,t=null)=>o({ok:!1,minClient:null,latestCli:null,latestDesktop:null,upgradeRequired:null,downloadUrl:"",reason:e,status:t}),i=(e,n)=>{const r=e&&"string"==typeof e.min_client?e.min_client:null;if(!r)return a(REASONS.MALFORMED,n);o({ok:!0,minClient:r,latestCli:"string"==typeof e.latest_cli?e.latest_cli:"",latestDesktop:"string"==typeof e.latest_desktop?e.latest_desktop:"",upgradeRequired:t&&"boolean"==typeof e.upgrade_required?e.upgrade_required:null,downloadUrl:"string"==typeof e.download_url?e.download_url:"",reason:null,status:n})};try{const s=`${String(e||DEFAULT_API_BASE).replace(/\/+$/,"")}/api/v1/version`,o={accept:"application/json"};t&&(o["X-AEGIS-Version"]=String(t));const c=e=>{const t=e.statusCode;if(200!==t)return e.resume(),a(404===t?REASONS.NOT_FOUND:401===t||403===t?REASONS.FORBIDDEN:REASONS.HTTP,t);let n="";e.setEncoding("utf8"),e.on("data",(r=>{n+=r,n.length>VERSION_BODY_CAP&&(e.destroy(),a(REASONS.TOO_LARGE,t))})),e.on("end",(()=>{if(!l)try{i(JSON.parse(n),t)}catch{a(REASONS.MALFORMED,t)}}))};if("function"==typeof r)return void Promise.resolve(r({url:s,headers:o,timeoutMs:n})).then((e=>{const t=e&&null!=e.status?e.status:0;if(!t)return a(REASONS.NETWORK);if(200!==t)return a(404===t?REASONS.NOT_FOUND:401===t||403===t?REASONS.FORBIDDEN:REASONS.HTTP,t);const n=e&&"string"==typeof e.text?e.text:"";if(n.length>VERSION_BODY_CAP)return a(REASONS.TOO_LARGE,t);try{i(JSON.parse(n),t)}catch{a(REASONS.MALFORMED,t)}})).catch((()=>a(REASONS.NETWORK)));const u=require(/^http:\/\//i.test(s)?"node:http":"node:https").get(s,{headers:o,timeout:n},c);u.on("timeout",(()=>{u.destroy(),a(REASONS.TIMEOUT)})),u.on("error",(()=>a(REASONS.NETWORK)))}catch{a(REASONS.NETWORK)}}))}function fetchServerVersion(e={}){return fetchServerVersionDetailed(e).then((e=>e.ok?e.minClient:null))}async function serverUpdateVerdict({current:e,base:t=DEFAULT_API_BASE,timeoutMs:n=TIMEOUT_MS,getImpl:r=null}={}){const s=await fetchServerVersionDetailed({base:t,clientVersion:e,timeoutMs:n,getImpl:r});if(!s.ok)return{ok:!1,behind:!1,latest:null,required:null,downloadUrl:"",reason:s.reason,status:s.status};const l=s.minClient||null,o=!0===s.upgradeRequired||!1!==s.upgradeRequired&&!!l&&isNewer(l,e);return{ok:!0,behind:o,latest:o&&(s.latestCli||s.latestDesktop)||l,latestCli:s.latestCli,latestDesktop:s.latestDesktop,required:l,downloadUrl:s.downloadUrl,reason:null,status:s.status}}function updateNotice({current:e,cache:t,save:n,now:r=Date.now(),fetchImpl:s=fetchLatest,intervalMs:l=864e5}={}){const o=t||{};"number"==typeof o.checkedAt&&r-o.checkedAt<l||Promise.resolve(s()).then((e=>{e&&"function"==typeof n&&n({checkedAt:r,latest:e})})).catch((()=>{}));const a=o.latest||null;return{latest:a,behind:!(!a||!isNewer(a,e))}}function installSpawn(e,t={}){if(!e||"string"!=typeof e.command||!e.command)return null;const n=t&&"object"==typeof t?t:{},r="string"==typeof n.platform&&n.platform?n.platform:process.platform,s=n.env&&"object"==typeof n.env?n.env:process.env,l=void 0===n.helpers?platformHelpers:n.helpers,o=Array.isArray(e.args)?e.args.map(String):[],a=[e.command,...o].join(" ");if("win32"===r){const e=l&&"function"==typeof l.shellSpec?l.shellSpec({platform:r,env:s}):{cmd:"cmd.exe",arg:"/d /s /c"};return{command:e.cmd,args:[...String(e.arg).split(" "),a],shell:!1,script:a}}let i=e.command;if(l&&"function"==typeof l.resolveExecutable)try{const t=l.resolveExecutable(e.command,{platform:r,env:s,..."function"==typeof n.exists?{exists:n.exists}:{}});t&&(i=t)}catch{}return{command:i,args:o.slice(),shell:!1,script:a}}function updatePlan({current:e,latest:t,behind:n,channel:r="npm",pkg:s=PKG,method:l="npm"}={}){const o=String(null==e?"":e),a=t?String(t):null;if(!Boolean(n)||!Boolean(a))return{channel:r,method:l,current:o,latest:a,behind:!1,action:"none",applier:"none",instruction:null,apply:null};const i=APPLIERS[l]||APPLIERS.npm;return{channel:r,method:l,current:o,latest:a,behind:!0,action:i.action,applier:i.name,instruction:i.instruction(s),apply:i.apply?i.apply(s):null}}const APPLIERS=Object.freeze({npm:Object.freeze({name:"npm",action:"npm-update",instruction:e=>`npm i -g ${e}@latest`,apply:e=>({command:"npm",args:["i","-g",`${e}@latest`]})}),pip:Object.freeze({name:"pip",action:"pip-update",instruction:e=>`pip install -U ${e}`,apply:e=>({command:"win32"===process.platform?"python":"python3",args:["-m","pip","install","-U",e]})}),npx:Object.freeze({name:"none",action:"npx-update",instruction:()=>"already fetched fresh on every run — restart to pick up the new version",apply:null}),source:Object.freeze({name:"git",action:"source-update",instruction:()=>"git pull && npm ci (this copy is a source checkout)",apply:null})});function detectInstallMethod({env:e={},argv:t=[],pkg:n=PKG,fileExists:r=(()=>!1),entry:s=""}={}){const l=String(e&&e.AEGIS_INSTALL_METHOD||"").trim().toLowerCase();if(l&&Object.prototype.hasOwnProperty.call(APPLIERS,l))return l;const o=t.map((e=>String(e))).join(" ");return/\bnpx\b/.test(o)||/_npx[\\/]/.test(o)||/_npx[\\/]/.test(s)?"npx":/[\\/]pipx[\\/]venvs[\\/]/.test(s)||/[\\/]site-packages[\\/]/.test(s)?"pip":/[\\/]node_modules[\\/]/.test(s)?"npm":r(".git")&&r("client/update.js")?"source":"npm"}async function checkPublished({current:e,cache:t,save:n,now:r=Date.now(),fetchImpl:s=fetchLatestDetailed,intervalMs:l=864e5,timeoutMs:o=TIMEOUT_MS,pkg:a=PKG}={}){const i=t||null;if(Boolean(i)&&"number"==typeof i.checkedAt&&r-i.checkedAt<l){const t=i.latest||null;return{ok:Boolean(t),latest:t,behind:!(!t||!isNewer(t,e)),reason:t?null:i.reason||null,status:t?200:null==i.status?null:i.status,cached:!0,checkedAt:i.checkedAt}}let c;try{c=await s({pkg:a,timeoutMs:o})}catch(e){c={ok:!1,latest:null,reason:REASONS.NETWORK,status:null,error:String(e&&e.message||e)}}const u={checkedAt:r,latest:c&&c.latest?c.latest:null,reason:c&&c.reason||null,status:c&&null!=c.status?c.status:null};if("function"==typeof n)try{n(u)}catch{}return{ok:Boolean(c&&c.ok&&c.latest),latest:u.latest,behind:!(!u.latest||!isNewer(u.latest,e)),reason:u.reason,status:u.status,cached:!1,checkedAt:r}}function updateLine({current:e,latest:t,behind:n,pkg:r=PKG,method:s="npm"}){const l=updatePlan({current:e,latest:t,behind:n,channel:"npm",pkg:r,method:s});if(!l.behind)return null;const o=`Update available: ${l.current} → ${l.latest}`;return l.apply?`${o} run: ${l.instruction}`:`${o} ${l.instruction}`}function serverNotice({current:e,cache:t,save:n,now:r=Date.now(),verdictImpl:s=serverUpdateVerdict,intervalMs:l=864e5}={}){const o=t||{};return"number"==typeof o.checkedAt&&r-o.checkedAt<l||Promise.resolve().then((()=>s({current:e}))).then((e=>{e&&"function"==typeof n&&n({checkedAt:r,behind:Boolean(e.behind),required:e.required||null,latest:e.latest||null,downloadUrl:e.downloadUrl||"",reason:e.reason||null})})).catch((()=>{})),{behind:Boolean(o.behind),latest:o.latest||null,required:o.required||null,downloadUrl:o.downloadUrl||""}}function serverUpdateLine({behind:e,latest:t,required:n,downloadUrl:r}={}){if(!e)return null;const s=t||n||"";return`${s?`This build is no longer served — update to v${s}.`:"This build is no longer served — update to the latest release."}${r?` ${r}`:""}`}module.exports={isNewer:isNewer,fetchLatest:fetchLatest,fetchLatestDetailed:fetchLatestDetailed,fetchServerVersion:fetchServerVersion,fetchServerVersionDetailed:fetchServerVersionDetailed,serverUpdateVerdict:serverUpdateVerdict,serverNotice:serverNotice,serverUpdateLine:serverUpdateLine,isTransientReason:isTransientReason,updateNotice:updateNotice,checkPublished:checkPublished,updatePlan:updatePlan,installSpawn:installSpawn,updateLine:updateLine,detectInstallMethod:detectInstallMethod,APPLIERS:APPLIERS,PKG:PKG,CHECK_INTERVAL_MS:864e5,REASONS:REASONS,DEFAULT_API_BASE:DEFAULT_API_BASE};