aegiscode 7.0.24 → 7.0.26

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 (113) hide show
  1. package/package.json +7 -3
  2. package/scripts/check.mjs +52 -1
  3. package/scripts/demo.mjs +94 -1
  4. package/scripts/predist.mjs +75 -1
  5. package/scripts/runtests.mjs +56 -1
  6. package/scripts/seal-gate.mjs +74 -1
  7. package/src/agents.js +139 -1
  8. package/src/app.js +2957 -1
  9. package/src/art.js +289 -1
  10. package/src/chatflow.js +3023 -1
  11. package/src/checkpoint.js +90 -1
  12. package/src/clipboard.js +424 -1
  13. package/src/cloudsync.js +528 -1
  14. package/src/commands.js +4089 -1
  15. package/src/config.js +581 -1
  16. package/src/connect.js +349 -1
  17. package/src/credentials.js +33 -1
  18. package/src/deps.js +232 -1
  19. package/src/devrun.js +187 -1
  20. package/src/diff.js +333 -1
  21. package/src/diffview.js +296 -1
  22. package/src/engine.js +297 -1
  23. package/src/entitlement.js +355 -1
  24. package/src/events.js +707 -1
  25. package/src/export.js +67 -1
  26. package/src/filepreview.js +153 -1
  27. package/src/fingerprint.js +592 -1
  28. package/src/format.js +259 -1
  29. package/src/fuzzy.js +119 -1
  30. package/src/history.js +423 -1
  31. package/src/init.js +175 -1
  32. package/src/input.js +139 -1
  33. package/src/keys.js +183 -1
  34. package/src/markdown.js +306 -1
  35. package/src/models.js +507 -1
  36. package/src/naming.js +57 -1
  37. package/src/overlays.js +462 -1
  38. package/src/panels.js +1418 -1
  39. package/src/ping.js +226 -1
  40. package/src/presence.js +238 -1
  41. package/src/render.js +516 -1
  42. package/src/screen.js +518 -1
  43. package/src/screens.js +896 -1
  44. package/src/secret.js +59 -1
  45. package/src/securefs.js +359 -1
  46. package/src/settings.js +155 -1
  47. package/src/shared.js +52 -1
  48. package/src/sharedpaths.js +53 -1
  49. package/src/signup.js +156 -1
  50. package/src/summarize.js +95 -1
  51. package/src/sysdiag.js +585 -1
  52. package/src/system.js +40 -1
  53. package/src/theme.js +570 -1
  54. package/src/title.js +220 -1
  55. package/src/todos.js +115 -1
  56. package/src/tokens.js +263 -1
  57. package/src/topup.js +210 -1
  58. package/src/update.js +191 -1
  59. package/vendor/client/aegis.js +2441 -1
  60. package/vendor/client/attest.js +518 -1
  61. package/vendor/client/authorship-key.js +410 -1
  62. package/vendor/client/auto-provision.js +134 -1
  63. package/vendor/client/brain-catalog.js +268 -1
  64. package/vendor/client/byok-catalog.js +199 -1
  65. package/vendor/client/catalog-client.js +487 -1
  66. package/vendor/client/conversation-export.js +177 -1
  67. package/vendor/client/credentials.js +494 -1
  68. package/vendor/client/device-fingerprint.js +141 -1
  69. package/vendor/client/drive-connect.js +110 -1
  70. package/vendor/client/drive-upload.js +234 -1
  71. package/vendor/client/env-file.js +1273 -1
  72. package/vendor/client/fingerprint.js +1064 -1
  73. package/vendor/client/foreign-memory.js +669 -1
  74. package/vendor/client/google-signin.js +133 -1
  75. package/vendor/client/hooks.js +430 -1
  76. package/vendor/client/model-discovery.js +373 -1
  77. package/vendor/client/naming.js +283 -1
  78. package/vendor/client/platform.js +937 -1
  79. package/vendor/client/prefs.js +351 -1
  80. package/vendor/client/presence-constants.js +107 -1
  81. package/vendor/client/presence.js +438 -1
  82. package/vendor/client/record-vault.js +1055 -3
  83. package/vendor/client/session-store.js +575 -1
  84. package/vendor/client/topup.js +297 -1
  85. package/vendor/client/touch.js +458 -1
  86. package/vendor/client/update.js +763 -1
  87. package/vendor/client/user-models.js +381 -1
  88. package/vendor/desktop/lib/local/agents.js +105 -1
  89. package/vendor/desktop/lib/local/attachments.js +276 -1
  90. package/vendor/desktop/lib/local/autonomous.js +1045 -1
  91. package/vendor/desktop/lib/local/claude-pro.js +1028 -1
  92. package/vendor/desktop/lib/local/context.js +125 -1
  93. package/vendor/desktop/lib/local/engine.js +3666 -1
  94. package/vendor/desktop/lib/local/entitlement.js +660 -1
  95. package/vendor/desktop/lib/local/git-scope.js +228 -1
  96. package/vendor/desktop/lib/local/local.js +2145 -1
  97. package/vendor/desktop/lib/local/prompt.js +280 -1
  98. package/vendor/desktop/lib/local/queue.js +560 -1
  99. package/vendor/desktop/lib/local/session-rounds.js +238 -1
  100. package/vendor/desktop/lib/local/spill.js +75 -1
  101. package/vendor/desktop/lib/local/turn-guard.js +300 -1
  102. package/vendor/desktop/lib/local/worktree-lock.js +235 -1
  103. package/vendor/desktop/lib/settings.js +890 -1
  104. package/vendor/desktop/renderer/usage.js +1239 -1
  105. package/vendor/hosts/install.js +638 -1
  106. package/vendor/hosts/openai-shim.js +515 -1
  107. package/vendor/hosts/spec.js +164 -1
  108. package/vendor/hosts/targets.js +346 -1
  109. package/vendor/mcp/server.js +221 -1
  110. package/vendor/mcp/tools.js +408 -1
  111. package/vendor/one/src/child.js +285 -1
  112. package/vendor/one/src/permissions.js +383 -1
  113. package/SOURCE-OFFER.txt +0 -9
package/src/topup.js CHANGED
@@ -1,3 +1,212 @@
1
1
  // SPDX-License-Identifier: AGPL-3.0-or-later
2
2
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
- "use strict";const{resolveShared:resolveShared}=require("./sharedpaths.js"),{openUrl:defaultOpenUrl}=require("./system.js"),credentials=require("./credentials.js");function loadShared(e){return require(resolveShared(e))}function createCliClient(){const{createClient:e}=loadShared("client/aegis.js");return e(credentials.clientOptions({channel:"cli"}))}async function ensureKey(e,t){if(e.apiKey)return!0;try{const n=loadShared("client/auto-provision.js"),o=n.autoProvisionApiKey||n.default;if("function"==typeof o){const n=await o(e,t,{app:"cli"});n&&n.key&&"function"==typeof e.setApiKey&&e.setApiKey(n.key)}}catch{}return Boolean(e.apiKey)}async function runTopupCommand(e,t){const n=t||{},o=n.stdout||process.stdout,r=n.stderr||process.stderr,i=n.json?()=>{}:e=>o.write(e);let a=null;const s=(e,t)=>(n.json&&o.write(JSON.stringify(t)+"\n"),e);let c;try{c=loadShared("client/topup.js")}catch(e){return r.write(`aegiscode: the shared top-up module is missing — ${e&&e.message||e}\n`),2}const{parseTopupAmount:u,startTopup:l,createCreditWatch:d,TOPUP_POLL_MS:p,TOPUP_POLL_TRIES:h,TOPUP_MIN_EUR:m,TOPUP_MAX_EUR:g}=c,f=u(e);if(!f.ok)return r.write(`aegiscode: ${f.message}\n usage: aegiscode topup [${m}..${g}] (default 10)\n`),s(2,{ok:!1,credited:!1,amount_eur:null,url:null,balance_eur:null,error:f.message});a={ok:!1,credited:!1,amount_eur:f.amount,url:null,balance_eur:null},r.write(`aegiscode: requesting a ${f.amount} EUR top-up from the account service…\n`);const y=n.client||createCliClient();if(!y.apiKey&&!await ensureKey(y,credentials))return r.write("aegiscode: no AEGIS key on this machine and none could be provisioned —\n `aegiscode login <api_key>` (from https://aegiscloud.org/dashboard) first\n"),a.error="no usable AEGIS key",s(2,a);const w=await l(y,f.amount);if(!w.ok)return r.write(`aegiscode: the top-up could not be started — ${w.message}\n`),w.hint&&r.write(`aegiscode: ${w.hint}\n`),a.error=w.message,a.status=w.status,s(2,a);a.url=w.url;const b=n.openUrl||defaultOpenUrl,k=n.sleep||(e=>new Promise((t=>setTimeout(t,e)))),U=null==n.intervalMs?p:n.intervalMs,S=null==n.maxTries?h:n.maxTries,T=Math.max(1,Math.round(U*S/1e3));b(w.url)?i(`aegiscode: opening the payment page in your browser — ${w.amount} EUR\n`):i(`aegiscode: open this to pay ${w.amount} EUR:\n ${w.url}\n`),i(`aegiscode: watching this account's bank for up to ${T}s to confirm the credit\n`);const $=d(y,{maxTries:S});let _=!1;for(;;){const e=await $.tick();if("function"==typeof n.onStep&&n.onStep(e),"credited"===e.state)return a.ok=!0,a.credited=!0,a.balance_eur=e.amount,i(`aegiscode: credit confirmed — the bank is now ${e.amount.toFixed(2)} EUR\naegiscode: (this account was created by this machine, so the browser there has no\n session for it — the confirmation comes from the API, not the page)\n`),s(0,a);if("expired"===e.state)return i(`aegiscode: no credit observed within ${T}s — if you completed the payment it\naegiscode: may still land; re-run \`aegiscode topup\` or check \`/billing\` in a session\n`),a.error="no credit observed within the watch window",s(1,a);null==e.baseline||_||n.json||(_=!0,i(`aegiscode: bank before the payment: ${e.baseline.toFixed(2)} EUR\n`)),await k(U)}}module.exports={runTopupCommand:runTopupCommand,ensureKey:ensureKey,createCliClient:createCliClient};
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
+ * topup.js — `aegiscode topup [EUR]`: the terminal's own top-up.
10
+ *
11
+ * WHY THE TERMINAL NEEDS THIS AT ALL. `/billing` prints a link (`/go/topup`) and
12
+ * that was the whole funding affordance: the CLI could not start a checkout.
13
+ * The link is real but it lands on `/topup`, which is `@login_required` against
14
+ * a browser SESSION — and the account this product auto-provisions is created by
15
+ * `POST /api/v1/auth/register-device`, with a password that is never returned
16
+ * and an email at `@device.aegiscloud`. So the user who most needs to fund a
17
+ * free account is the one who cannot sign in to the page that funds it: they pay
18
+ * the link a visit, hit a login wall, and conclude it failed while the money is
19
+ * real.
20
+ *
21
+ * What makes this work is that the credential which CREATES the checkout can
22
+ * also READ the result: `POST /api/token-bank/topup` and `GET
23
+ * /api/token-bank/balance` are both `login_required`, which accepts
24
+ * `X-API-Key`/Bearer. So this command starts the session, opens the hosted page
25
+ * for the actual card entry, and then confirms the credit itself from the
26
+ * balance endpoint — the same confirmation the desktop does, over the same state
27
+ * machine (`client/topup.js`, `createCreditWatch`), so the terminal and the GUI
28
+ * cannot disagree about whether the money arrived.
29
+ *
30
+ * It BLOCKS on purpose. The desktop's watch is an unref'd interval because the
31
+ * window stays open for hours; here the process exits, so a detached timer would
32
+ * be killed before the webhook fires. A loop is the honest scheduler for a
33
+ * one-shot command, and it is why the shared module owns the state machine and
34
+ * not the timer.
35
+ *
36
+ * Exit codes (a script can gate on them): 0 credited, 1 checkout opened but no
37
+ * credit observed in the window, 2 usage / no usable credential / the server
38
+ * refused the checkout.
39
+ */
40
+
41
+ const { resolveShared } = require('./sharedpaths.js');
42
+ const { openUrl: defaultOpenUrl } = require('./system.js');
43
+ const credentials = require('./credentials.js');
44
+
45
+ /** Resolve a shared module by existence (repo checkout or the staged tree). */
46
+ function loadShared(rel) {
47
+ return require(resolveShared(rel));
48
+ }
49
+
50
+ /** The same thin client the session and the entitlement gate use. */
51
+ function createCliClient() {
52
+ const { createClient } = loadShared('client/aegis.js');
53
+ return createClient(credentials.clientOptions({ channel: 'cli' }));
54
+ }
55
+
56
+ /**
57
+ * A key is needed to create a checkout at all, so a fresh machine gets the same
58
+ * free device key the session path asks for — one implementation, the shared
59
+ * auto-provision helper (client/auto-provision.js), and one attempt.
60
+ *
61
+ * Best-effort by design: if the helper is unreachable or the server declines,
62
+ * this returns false and the caller says so, rather than throwing a module error
63
+ * at a user who is trying to give us money.
64
+ */
65
+ async function ensureKey(client, store) {
66
+ if (client.apiKey) return true;
67
+ try {
68
+ const mod = loadShared('client/auto-provision.js');
69
+ const provision = mod.autoProvisionApiKey || mod.default;
70
+ if (typeof provision === 'function') {
71
+ const res = await provision(client, store, { app: 'cli' });
72
+ if (res && res.key && typeof client.setApiKey === 'function') client.setApiKey(res.key);
73
+ }
74
+ } catch {
75
+ /* fall through: the caller reports the missing credential plainly */
76
+ }
77
+ return Boolean(client.apiKey);
78
+ }
79
+
80
+ /**
81
+ * Run the command and return a process exit code.
82
+ *
83
+ * @param {string|null} arg the typed amount (null ⇒ the server default, 10 EUR)
84
+ * @param {object} [io] injectable for tests: `stdout`, `stderr`, `client`,
85
+ * `openUrl`, `sleep`, `intervalMs`, `maxTries`, `json`, `onStep`.
86
+ */
87
+ async function runTopupCommand(arg, io) {
88
+ const options = io || {};
89
+ const stdout = options.stdout || process.stdout;
90
+ const stderr = options.stderr || process.stderr;
91
+ // JSON mode is a script's stdout: one object (written by finish()) and no
92
+ // human chatter, so a parser never has to skip progress lines. Errors still
93
+ // go to stderr, which is not the stream being parsed.
94
+ const out = options.json ? () => {} : (s) => stdout.write(s);
95
+ let payload = null;
96
+
97
+ // JSON mode prints ONE object and nothing else, so a script parsing stdout
98
+ // does not have to skip progress chatter.
99
+ const finish = (code, result) => {
100
+ if (options.json) stdout.write(JSON.stringify(result) + '\n');
101
+ return code;
102
+ };
103
+
104
+ let shared;
105
+ try {
106
+ shared = loadShared('client/topup.js');
107
+ } catch (error) {
108
+ stderr.write(`aegiscode: the shared top-up module is missing — ${(error && error.message) || error}\n`);
109
+ return 2;
110
+ }
111
+ const {
112
+ parseTopupAmount,
113
+ startTopup,
114
+ createCreditWatch,
115
+ TOPUP_POLL_MS,
116
+ TOPUP_POLL_TRIES,
117
+ TOPUP_MIN_EUR,
118
+ TOPUP_MAX_EUR,
119
+ } = shared;
120
+
121
+ const parsed = parseTopupAmount(arg);
122
+ if (!parsed.ok) {
123
+ stderr.write(
124
+ `aegiscode: ${parsed.message}\n` +
125
+ ` usage: aegiscode topup [${TOPUP_MIN_EUR}..${TOPUP_MAX_EUR}] (default 10)\n`
126
+ );
127
+ // JSON mode still emits its ONE object here: a script that checks the exit
128
+ // code must not be the only way to learn why — "no stdout at all" reads as
129
+ // a crash, not as a rejected amount.
130
+ return finish(2, { ok: false, credited: false, amount_eur: null, url: null, balance_eur: null, error: parsed.message });
131
+ }
132
+ payload = { ok: false, credited: false, amount_eur: parsed.amount, url: null, balance_eur: null };
133
+
134
+ // Say something BEFORE the first network call. The transport's ceiling is 60s
135
+ // per request and this path can make two (auto-provision, then the checkout),
136
+ // so an unreachable server used to mean two silent minutes and then a line —
137
+ // which a user reads as a hung command, not as a network problem. stderr, not
138
+ // stdout: in --json mode stdout is a script's parse target.
139
+ stderr.write(`aegiscode: requesting a ${parsed.amount} EUR top-up from the account service…\n`);
140
+
141
+ const client = options.client || createCliClient();
142
+ if (!client.apiKey && !(await ensureKey(client, credentials))) {
143
+ stderr.write(
144
+ 'aegiscode: no AEGIS key on this machine and none could be provisioned —\n' +
145
+ ' `aegiscode login <api_key>` (from https://aegiscloud.org/dashboard) first\n'
146
+ );
147
+ payload.error = 'no usable AEGIS key';
148
+ return finish(2, payload);
149
+ }
150
+
151
+ const started = await startTopup(client, parsed.amount);
152
+ if (!started.ok) {
153
+ stderr.write(`aegiscode: the top-up could not be started — ${started.message}\n`);
154
+ if (started.hint) stderr.write(`aegiscode: ${started.hint}\n`);
155
+ payload.error = started.message;
156
+ payload.status = started.status;
157
+ return finish(2, payload);
158
+ }
159
+ payload.url = started.url;
160
+
161
+ const open = options.openUrl || defaultOpenUrl;
162
+ const sleep = options.sleep || ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
163
+ const intervalMs = options.intervalMs == null ? TOPUP_POLL_MS : options.intervalMs;
164
+ const maxTries = options.maxTries == null ? TOPUP_POLL_TRIES : options.maxTries;
165
+ const windowSeconds = Math.max(1, Math.round((intervalMs * maxTries) / 1000));
166
+
167
+ // `openUrl` returns false when the platform opener is missing (a container, a
168
+ // server over ssh); the URL is then the ONLY way to pay, so it is printed
169
+ // rather than swallowed — a command that silently does nothing is worse than
170
+ // one that says "paste this".
171
+ if (open(started.url)) {
172
+ out(`aegiscode: opening the payment page in your browser — ${started.amount} EUR\n`);
173
+ } else {
174
+ out(`aegiscode: open this to pay ${started.amount} EUR:\n ${started.url}\n`);
175
+ }
176
+ out(`aegiscode: watching this account's bank for up to ${windowSeconds}s to confirm the credit\n`);
177
+
178
+ const watch = createCreditWatch(client, { maxTries });
179
+ let announcedBaseline = false;
180
+ for (;;) {
181
+ const step = await watch.tick();
182
+ if (typeof options.onStep === 'function') options.onStep(step);
183
+ if (step.state === 'credited') {
184
+ payload.ok = true;
185
+ payload.credited = true;
186
+ payload.balance_eur = step.amount;
187
+ out(
188
+ `aegiscode: credit confirmed — the bank is now ${step.amount.toFixed(2)} EUR\n` +
189
+ 'aegiscode: (this account was created by this machine, so the browser there has no\n' +
190
+ ' session for it — the confirmation comes from the API, not the page)\n'
191
+ );
192
+ return finish(0, payload);
193
+ }
194
+ if (step.state === 'expired') {
195
+ // Honest about what is and is not known: the window closed on OUR watch,
196
+ // which is not the same claim as "you were not charged".
197
+ out(
198
+ `aegiscode: no credit observed within ${windowSeconds}s — if you completed the payment it\n` +
199
+ 'aegiscode: may still land; re-run `aegiscode topup` or check `/billing` in a session\n'
200
+ );
201
+ payload.error = 'no credit observed within the watch window';
202
+ return finish(1, payload);
203
+ }
204
+ if (step.baseline != null && !announcedBaseline && !options.json) {
205
+ announcedBaseline = true;
206
+ out(`aegiscode: bank before the payment: ${step.baseline.toFixed(2)} EUR\n`);
207
+ }
208
+ await sleep(intervalMs);
209
+ }
210
+ }
211
+
212
+ module.exports = { runTopupCommand, ensureKey, createCliClient };
package/src/update.js CHANGED
@@ -1,3 +1,193 @@
1
1
  // SPDX-License-Identifier: AGPL-3.0-or-later
2
2
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
- "use strict";const path=require("node:path"),fs=require("node:fs"),{execFileSync:execFileSync}=require("node:child_process"),{resolveShared:resolveShared}=require("./deps.js"),shared=require(resolveShared("client/update.js")),VERSION=require("../package.json").version,PKG=shared.PKG||"aegiscode";let methodCache=null;function installMethod(){if(methodCache)return methodCache;const e=shared.detectInstallMethod;if("function"!=typeof e)return methodCache="npm",methodCache;try{methodCache=e({env:process.env,argv:process.argv,pkg:PKG,entry:path.resolve(__dirname,".."),fileExists:e=>fs.existsSync(path.resolve(__dirname,"..","..",e))})}catch{methodCache="npm"}return methodCache}function compareVersions(e,n){const t=String(e||"0").split("-")[0].split(".").map((e=>Number.parseInt(e,10)||0)),r=String(n||"0").split("-")[0].split(".").map((e=>Number.parseInt(e,10)||0));for(let e=0;e<Math.max(t.length,r.length);e++){const n=(t[e]||0)-(r[e]||0);if(n)return n>0?1:-1}return 0}function upgradeAdvice({current:e=VERSION,latest:n=null,packageName:t=PKG,method:r="npm"}={}){if(!n)return{upToDate:null,lines:[` Could not read the npm registry — local version is ${e}.`]};if(compareVersions(n,e)>0){const a="function"==typeof shared.updatePlan?shared.updatePlan({current:e,latest:n,behind:!0,channel:"npm",pkg:t,method:r}):null,s=[` Installed: ${e}`,` Published: ${n}`,` Channel: ${r}`,` Upgrade: ${a&&a.instruction||`npm i -g ${t}@latest`}`];return a&&a.apply&&s.push(" (or run `/upgrade apply` to do it here)"),{upToDate:!1,lines:s,plan:a}}return{upToDate:!0,lines:[` Installed ${e} is the published ${n} — nothing to upgrade.`]}}function applyUpgrade({current:e=VERSION,packageName:n=PKG,method:t="npm",latest:r=null}={}){const a="function"==typeof shared.updatePlan&&r?shared.updatePlan({current:e,latest:r,behind:!0,channel:"npm",pkg:n,method:t}):null,s=a&&a.apply?a.apply:null;if(!s)return{ok:!0,skipped:!0,channel:t,command:null,instruction:a&&a.instruction||("npm"===t?`npm i -g ${n}@latest`:"restart to pick up the new version")};try{const e=("function"==typeof shared.installSpawn?shared.installSpawn(s,{env:process.env}):{command:s.command,args:s.args,shell:!1})||{command:s.command,args:s.args,shell:!1},n=execFileSync(e.command,e.args,{encoding:"utf8",timeout:18e4,stdio:["ignore","pipe","pipe"],shell:!0===e.shell,windowsHide:!0});return{ok:!0,channel:t,command:`${s.command} ${s.args.join(" ")}`,output:String(n||"").trim()}}catch(e){return{ok:!1,channel:t,command:`${s.command} ${s.args.join(" ")}`,error:String(e&&(e.stderr||e.message)||e).trim()}}}function latestPublishedVersion({packageName:e=PKG,timeoutMs:n=5e3}={}){try{const t=execFileSync("npm",["view",e,"version"],{encoding:"utf8",timeout:n,stdio:["ignore","pipe","ignore"]}),r=String(t).trim();return/^\d+\.\d+\.\d+/.test(r)?r:null}catch{return null}}module.exports={...shared,VERSION:VERSION,compareVersions:compareVersions,upgradeAdvice:upgradeAdvice,applyUpgrade:applyUpgrade,installMethod:installMethod,latestPublishedVersion:latestPublishedVersion};
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
+ * The CLI's view of the shared npm update checker (client/update.js).
10
+ *
11
+ * It lives at the repo root rather than here because the desktop host needs
12
+ * the same thing for `aegis-desktop`: two hosts, two package names, one
13
+ * checker. Resolved through deps.js so the in-repo and published-vendor
14
+ * layouts both work.
15
+ *
16
+ * On top of the shared checker this module carries the pieces /upgrade needs —
17
+ * `compareVersions`, `upgradeAdvice`, `latestPublishedVersion` and
18
+ * `installMethod` — ported from the upstream engine reference. They belong
19
+ * here, next to `isNewer`/`updateLine`, so the CLI has ONE idea of "is there a
20
+ * newer published version": the welcome-box notice and /upgrade now answer
21
+ * from the same place and compare versions the same way. The shared module's
22
+ * own functions are spread through unchanged, keeping the identity the
23
+ * update-channel test pins (the shim and the shared file must be the SAME
24
+ * code, not a copy).
25
+ */
26
+
27
+ const path = require('node:path');
28
+ const fs = require('node:fs');
29
+ const { execFileSync } = require('node:child_process');
30
+
31
+ const { resolveShared } = require('./deps.js');
32
+
33
+ const shared = require(resolveShared('client/update.js'));
34
+
35
+ const VERSION = require('../package.json').version;
36
+ /** Both hosts publish from npm; the CLI is `aegiscode`. */
37
+ const PKG = shared.PKG || 'aegiscode';
38
+
39
+ /**
40
+ * How THIS copy was installed: 'npm' | 'pip' | 'npx' | 'source'.
41
+ *
42
+ * Lazy on purpose — `detectInstallMethod` probes the filesystem, and the four
43
+ * call sites that only want a version string should not pay for it. Memoised
44
+ * because the answer cannot change while the process runs.
45
+ */
46
+ let methodCache = null;
47
+ function installMethod() {
48
+ if (methodCache) return methodCache;
49
+ const detect = shared.detectInstallMethod;
50
+ if (typeof detect !== 'function') { methodCache = 'npm'; return methodCache; }
51
+ try {
52
+ methodCache = detect({
53
+ env: process.env,
54
+ argv: process.argv,
55
+ pkg: PKG,
56
+ // The directory the running file lives in, and the package root above it
57
+ // (`cli/src` → `cli/`), which is what tells a checkout from a global
58
+ // install: `.git` exists in the repo, and in no published package.
59
+ entry: path.resolve(__dirname, '..'),
60
+ fileExists: (rel) => fs.existsSync(path.resolve(__dirname, '..', '..', rel)),
61
+ });
62
+ } catch {
63
+ methodCache = 'npm';
64
+ }
65
+ return methodCache;
66
+ }
67
+
68
+ // ── /upgrade ─────────────────────────────────────────────────────────────────
69
+
70
+ /** Compare two dotted version strings: -1 | 0 | 1 (prerelease tags ignored). */
71
+ function compareVersions(a, b) {
72
+ const pa = String(a || '0').split('-')[0].split('.').map((n) => Number.parseInt(n, 10) || 0);
73
+ const pb = String(b || '0').split('-')[0].split('.').map((n) => Number.parseInt(n, 10) || 0);
74
+ for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
75
+ const d = (pa[i] || 0) - (pb[i] || 0);
76
+ if (d) return d > 0 ? 1 : -1;
77
+ }
78
+ return 0;
79
+ }
80
+
81
+ /** What /upgrade should say, given the local and published versions. */
82
+ function upgradeAdvice({ current = VERSION, latest = null, packageName = PKG, method = 'npm' } = {}) {
83
+ if (!latest) {
84
+ return {
85
+ upToDate: null,
86
+ lines: [` Could not read the npm registry — local version is ${current}.`],
87
+ };
88
+ }
89
+ const cmp = compareVersions(latest, current);
90
+ if (cmp > 0) {
91
+ // The command comes from the shared verdict, so /upgrade, the welcome box
92
+ // and the window's banner can never name three different installers — and
93
+ // so a pip install is not told to run npm (which would write a second copy
94
+ // beside the one it actually runs, and look like a no-op).
95
+ const plan = typeof shared.updatePlan === 'function'
96
+ ? shared.updatePlan({ current, latest, behind: true, channel: 'npm', pkg: packageName, method })
97
+ : null;
98
+ const instruction = (plan && plan.instruction) || `npm i -g ${packageName}@latest`;
99
+ const lines = [
100
+ ` Installed: ${current}`,
101
+ ` Published: ${latest}`,
102
+ ` Channel: ${method}`,
103
+ ` Upgrade: ${instruction}`,
104
+ ];
105
+ if (plan && plan.apply) lines.push(' (or run `/upgrade apply` to do it here)');
106
+ return { upToDate: false, lines, plan };
107
+ }
108
+ return {
109
+ upToDate: true,
110
+ lines: [` Installed ${current} is the published ${latest} — nothing to upgrade.`],
111
+ };
112
+ }
113
+
114
+ /**
115
+ * Actually run the upgrade, when the channel has a command to run.
116
+ *
117
+ * `/upgrade` used to print a command and stop there, which put the whole update
118
+ * behind "copy a shell line correctly" — and the window's banner had a button
119
+ * for the same thing. `apply: false` stays available because a source checkout
120
+ * and an npx run both have nothing for us to install.
121
+ *
122
+ * Never throws: a failing installer is a result, because a half-upgraded global
123
+ * package is exactly when a user needs to read the output rather than lose it
124
+ * to a traceback.
125
+ *
126
+ * @returns {{ok: boolean, skipped?: boolean, channel: string, command: ?string,
127
+ * output?: string, error?: string, instruction?: string}}
128
+ */
129
+ function applyUpgrade({ current = VERSION, packageName = PKG, method = 'npm', latest = null } = {}) {
130
+ const plan = typeof shared.updatePlan === 'function' && latest
131
+ ? shared.updatePlan({ current, latest, behind: true, channel: 'npm', pkg: packageName, method })
132
+ : null;
133
+ const target = plan && plan.apply ? plan.apply : null;
134
+ if (!target) {
135
+ const instruction = (plan && plan.instruction) || (method === 'npm'
136
+ ? `npm i -g ${packageName}@latest`
137
+ : 'restart to pick up the new version');
138
+ // Two different reasons to skip, and they are not interchangeable: a source
139
+ // checkout is the user's to pull, an npx run is already current by design.
140
+ return { ok: true, skipped: true, channel: method, command: null, instruction };
141
+ }
142
+ try {
143
+ // Spawn through the shared resolver, not the bare name: on win32 npm is
144
+ // `npm.cmd` (which `execFileSync` cannot execute without a shell) and a
145
+ // GUI/desktop launch may not inherit the shell's PATH. `installSpawn` is
146
+ // null only when the plan had nothing to run, which is handled above.
147
+ const spec = typeof shared.installSpawn === 'function'
148
+ ? shared.installSpawn(target, { env: process.env })
149
+ : { command: target.command, args: target.args, shell: false };
150
+ const spawned = spec || { command: target.command, args: target.args, shell: false };
151
+ const out = execFileSync(spawned.command, spawned.args, {
152
+ encoding: 'utf8',
153
+ timeout: 180_000,
154
+ stdio: ['ignore', 'pipe', 'pipe'],
155
+ shell: spawned.shell === true,
156
+ windowsHide: true,
157
+ });
158
+ return {
159
+ ok: true,
160
+ channel: method,
161
+ command: `${target.command} ${target.args.join(' ')}`,
162
+ output: String(out || '').trim(),
163
+ };
164
+ } catch (err) {
165
+ return {
166
+ ok: false,
167
+ channel: method,
168
+ command: `${target.command} ${target.args.join(' ')}`,
169
+ error: String((err && (err.stderr || err.message)) || err).trim(),
170
+ };
171
+ }
172
+ }
173
+
174
+ /** Best-effort registry lookup (5s cap). Returns a version string or null. */
175
+ function latestPublishedVersion({ packageName = PKG, timeoutMs = 5000 } = {}) {
176
+ try {
177
+ const out = execFileSync('npm', ['view', packageName, 'version'], {
178
+ encoding: 'utf8', timeout: timeoutMs, stdio: ['ignore', 'pipe', 'ignore'],
179
+ });
180
+ const v = String(out).trim();
181
+ return /^\d+\.\d+\.\d+/.test(v) ? v : null;
182
+ } catch { return null; }
183
+ }
184
+
185
+ module.exports = {
186
+ ...shared,
187
+ VERSION,
188
+ compareVersions,
189
+ upgradeAdvice,
190
+ applyUpgrade,
191
+ installMethod,
192
+ latestPublishedVersion,
193
+ };