aegiscode 6.8.29 → 6.8.31

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.
package/README.md CHANGED
@@ -542,9 +542,9 @@ Desktop and the MCP plugin built on the same account:
542
542
  | `history.jsonl` | this host's per-exchange ledger (feeds `/cost`) | the CLI |
543
543
  | `config.json` | preferences, permissions | the CLI |
544
544
 
545
- Sign in once and all three hosts are signed in: they resolve the key with the
545
+ Sign in once and every face is signed in: they resolve the key with the
546
546
  same precedence (`$AEGIS_API_KEY` → `credentials.json` → an older `config.json`),
547
- and when two hosts hold a key the **most recently saved one wins** — so rotating
547
+ and when two faces hold a key the **most recently saved one wins** — so rotating
548
548
  it from the terminal does not leave the app 401-ing on a stale string.
549
549
 
550
550
  Sessions are shared too, and not only through the cloud. `/resume` lists a
package/bin/aegiscode.js CHANGED
@@ -40,6 +40,10 @@ Account:
40
40
  aegiscode login [<key>] save your AEGIS API key (prompts, no echo, if omitted)
41
41
  aegiscode logout remove the saved key
42
42
  aegiscode key status show which key is in use and where it came from
43
+ aegiscode topup [EUR] add credit to the token bank (2..1000, default 10):
44
+ opens the payment page, then confirms the credit
45
+ here — the account this machine auto-provisions
46
+ has no browser session, so the page cannot show it
43
47
 
44
48
  Automation:
45
49
  aegiscode autonomous help run queued tasks with no terminal at all
@@ -186,6 +190,16 @@ function parseArgs(argv) {
186
190
  opts.commandArg = sub;
187
191
  opts.commandArgv = argv.slice(argv[1] && !argv[1].startsWith('-') ? 2 : 1);
188
192
  argv = [];
193
+ } else if (head === 'topup') {
194
+ // Same position-0 rule and the same reason as `gate`: the one argument is
195
+ // the amount (`aegiscode topup 20`), never a prompt whose text happens to
196
+ // be "topup". A bare `aegiscode topup` means the default 10 EUR — the
197
+ // server's own default — rather than usage text, because "fund this
198
+ // account" is a complete intent.
199
+ const amount = argv[1] && !argv[1].startsWith('-') ? argv[1] : null;
200
+ opts.command = 'topup';
201
+ opts.commandArg = amount;
202
+ argv = amount ? argv.slice(2) : argv.slice(1);
189
203
  }
190
204
 
191
205
  for (let i = 0; i < argv.length; i++) {
@@ -525,6 +539,23 @@ async function main(argv = process.argv.slice(2)) {
525
539
  return runGate(opts.commandArg || 'status', opts.commandArgv || []);
526
540
  }
527
541
 
542
+ // Funding the account, dispatched here rather than among the account commands
543
+ // because it is interactive in a different way: it opens a browser and then
544
+ // BLOCKS on the balance endpoint until the Stripe webhook lands the credit
545
+ // (see src/topup.js for why blocking is right here and wrong in the desktop).
546
+ // The one failure this fixes is the account auto-provision creates — a device
547
+ // key whose owner can never sign in to `/topup`, the session-gated page every
548
+ // old link pointed at.
549
+ if (opts.command === 'topup') {
550
+ const { runTopupCommand } = require('../src/topup.js');
551
+ return runTopupCommand(opts.commandArg, {
552
+ json: opts.json,
553
+ stdin: process.stdin,
554
+ stdout: process.stdout,
555
+ stderr: process.stderr,
556
+ });
557
+ }
558
+
528
559
  if (ACCOUNT_COMMANDS.has(opts.command)) {
529
560
  return runAccountCommand(opts.command, opts.commandArg, {
530
561
  json: opts.json,
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "aegiscode",
3
3
  "productName": "AEGIS Code",
4
- "version": "6.8.29",
4
+ "version": "6.8.31",
5
5
  "description": "aegiscode — the command-line version of AEGIS Desktop. The shared tool surface in your shell, over the same thin transport and tool registry as the MCP plugin and the desktop app. Ships transport + UI only; no brain.",
6
6
  "author": {
7
7
  "name": "AEGIS Code",
@@ -1,344 +1,48 @@
1
1
  #!/usr/bin/env node
2
2
  /**
3
- * Pre-publish staging for the `aegiscode` package.
3
+ * Pre-publish staging for the `aegiscode` package — a THIN WRAPPER.
4
4
  *
5
- * The CLI is a host, not a fork: it consumes the repo's shared modules
6
- * (`client/aegis.js` transport, `mcp/tools.js` registry, the desktop's pure
7
- * `usage.js` mapping) rather than copies of them. npm can only publish a
8
- * package's own directory, so those files are staged into `cli/vendor/` here,
9
- * at publish time, keeping the repo's relative shape:
5
+ * The manifest (and both shape emitters, and both proofs) moved to
6
+ * `one/scripts/predist.mjs` in AEGISONE's phase ON2 (plan D6): one manifest,
7
+ * two shapes. This file used to hold its own list of forty repo-relative
8
+ * modules, kept in sync with `desktop/scripts/predist.mjs` by discipline alone.
9
+ * It now holds no list at all.
10
10
  *
11
- * cli/ repo/
12
- * vendor/mcp/tools.js ≡ mcp/tools.js
13
- * vendor/client/*.js ≡ client/*.js
14
- * vendor/desktop/... ≡ desktop/renderer/usage.js,
15
- * desktop/lib/local/{engine,tools,shell,agents,prompt}.js
11
+ * Everything the CLI needs is unchanged as seen from outside: `npm run predist`,
12
+ * `prepublishOnly`, `precheck` and `pretest` still run this file, it still
13
+ * stages `cli/vendor/` in the repo's relative shape, and it still prints the
14
+ * same proof lines (the staged registry loads standalone, the editor layer
15
+ * resolves the STAGED server, the staged gate module loads).
16
16
  *
17
- * The shape matters: `mcp/tools.js` requires `../client/foreign-memory.js`, and
18
- * because the staged tree mirrors the repo, that path resolves *inside* the
19
- * vendor tree with no rewrite in either file.
20
- *
21
- * `src/deps.js` resolves in-repo paths first and falls back to `vendor/`, so a
22
- * source checkout and an installed package run identical code.
17
+ * If the shared stager is not reachable the file is missing — this directory is
18
+ * inside the published tarball, where `one/` is not shipped, and running predist
19
+ * there is meaningless anyway (the vendor tree it would build is already in the
20
+ * package). Say that plainly instead of failing with a MODULE_NOT_FOUND.
23
21
  */
24
-
25
- import fs from 'node:fs';
26
22
  import path from 'node:path';
27
23
  import { fileURLToPath, pathToFileURL } from 'node:url';
28
- import { createRequire } from 'node:module';
29
-
30
- const require = createRequire(import.meta.url);
31
- const __dirname = path.dirname(fileURLToPath(import.meta.url));
32
24
 
33
- const CLI_DIR = path.join(__dirname, '..');
34
- const REPO_DIR = path.join(CLI_DIR, '..');
35
- const VENDOR = path.join(CLI_DIR, 'vendor');
25
+ const HERE = path.dirname(fileURLToPath(import.meta.url));
26
+ const SHARED = path.join(HERE, '..', '..', 'one', 'scripts', 'predist.mjs');
36
27
 
37
- /** repo-relative -> staged location (same relative shape, under vendor/) */
38
- const FILES = [
39
- 'client/aegis.js',
40
- 'client/update.js',
41
- 'client/foreign-memory.js',
42
- // The account credential store and the unified session store. Shared with the
43
- // desktop app and the MCP plugin so all three see one key and one session
44
- // list; `src/shared.js` resolves them from here in an installed package.
45
- 'client/credentials.js',
46
- 'client/session-store.js',
47
- // The shared `~/.aegiscode/.env` loader. bin/aegiscode.js resolves it through
48
- // resolveClientModule in src/shared.js and calls it before any credential is
49
- // read, so a key lives in ONE file for every host. (No apostrophes in the
50
- // comments in this array: test/packaging.test.mjs parses it by pairing single
51
- // quotes, and one stray one silently swallows the next real entry.)
52
- 'client/env-file.js',
53
- // Auto-provision a free device key when no key is configured anywhere —
54
- // shared with the desktop app and the MCP plugin so all three ask aegis1
55
- // for the same account on the same machine.
56
- 'client/auto-provision.js',
57
- 'client/device-fingerprint.js',
58
- // The presence beacon (src/presence.js, started by bin/aegiscode.js) — the
59
- // client half of the aegis1 route /api/v1/heartbeat. presence.js requires
60
- // presence-constants.js and device-fingerprint.js from the same directory, so
61
- // the three stay in one vendor tree; a package built without them loses the
62
- // beacon silently (src/presence.js turns a load failure into an inert store),
63
- // which is exactly the kind of missing-row bug no error message reports.
64
- 'client/presence.js',
65
- 'client/presence-constants.js',
66
- // φ(α): the authorship key, the sealed session record and the vendored
67
- // digest module they are built on. src/fingerprint.js resolves all three
68
- // through resolveClientModule, and they require each other by same-directory
69
- // relative paths (fingerprint.js -> ./touch.js, attest.js -> ./fingerprint.js
70
- // and ./authorship-key.js), so all four must land in one vendor tree. A
71
- // package missing them would fail the fingerprint subcommand at load — loud,
72
- // but only for the user who tried it.
73
- 'client/touch.js',
74
- 'client/fingerprint.js',
75
- 'client/authorship-key.js',
76
- 'client/attest.js',
77
- // The vault: where a sealed record travels so it can be looked at from
78
- // anywhere, and the module that refuses to send the key with it (a secret in
79
- // cloud storage can mint records that impersonate the owner). src/fingerprint.js
80
- // resolves it through resolveClientModule, so a package staged without it
81
- // loses `fingerprint publish|anchor|vault` at load with MODULE_NOT_FOUND.
82
- 'client/record-vault.js',
83
- // The pooled-brain selection rule: which single entry stands for the Aegis
84
- // class. Required at load time by src/models.js (through src/sharedpaths.js),
85
- // which the picker, /model and the OpenAI-compatible shim all build their
86
- // model list from — and by the desktop engine, so the GUI and the terminal
87
- // offer one account one list. Leaving it out stages a package whose every
88
- // model listing throws MODULE_NOT_FOUND before it can print a prompt.
89
- 'client/brain-catalog.js',
90
- // The BYOK model additions: the ids a provider relays but the server catalog
91
- // does not name (the DeepSeek flash route). Required at load time by
92
- // src/commands.js, so a package built without it throws MODULE_NOT_FOUND on
93
- // the first picker or /byok listing instead of showing a short one.
94
- 'client/byok-catalog.js',
95
- // The shared HOOK layer: the hook config reader behind /hooks and the
96
- // installer for this repo guard hooks, with one implementation for the
97
- // CLI, the desktop app and tools/agent-gate.mjs. src/commands.js resolves
98
- // it through resolveShared, so a package staged without it loses the
99
- // /hooks command at load time with MODULE_NOT_FOUND.
100
- 'client/hooks.js',
101
- // The shared platform module (Phase 30.1): the one place that decides which
102
- // OS this is. desktop/lib/local/tools.js requires it for its exec shell spec,
103
- // and desktop/lib/local/tools.js is staged below, so leaving this out stages
104
- // a vendor tree whose exec tool throws MODULE_NOT_FOUND on first use.
105
- 'client/platform.js',
106
- 'mcp/tools.js',
107
- // The stdio MCP server itself — the process every editor config written by
108
- // `aegiscode mcp install` points at. Staging the registry without it ships a
109
- // package whose configs name a file that is not in the package, and an editor
110
- // reports that as a server that simply never starts: no error the user can
111
- // see. It exports nothing and registers its stdin handlers at load time, so
112
- // it is verified by COMPILING it (see the probe below) and never required
113
- // here — requiring it would switch the predist process stdin to flowing mode
114
- // and it would then never exit.
115
- 'mcp/server.js',
116
- // The editor-integration layer: the host registry, the canonical server spec,
117
- // and the merge-only installer behind `aegiscode mcp install|status|remove`.
118
- // Staged under vendor/hosts/ so the tree keeps the repo shape — these files
119
- // require ../client/*.js, which resolves INSIDE the vendor tree, and
120
- // hosts/spec.js finds the server one level up as vendor/mcp/server.js.
121
- 'hosts/spec.js',
122
- 'hosts/targets.js',
123
- 'hosts/install.js',
124
- // The OpenAI-compatible shim (loopback /v1/chat/completions), for the many
125
- // coding programs that take a base URL but speak no MCP. It resolves
126
- // cli/src/models.js from either layout itself; in a checkout that is
127
- // cli/src/models.js and in the package it is src/models.js, which ships
128
- // because the CLI own source directory is published as-is.
129
- 'hosts/openai-shim.js',
130
- 'desktop/renderer/usage.js',
131
- // The agent-loop engine (persistent shell, editFile/grep/exec, Task
132
- // subagents) the desktop app already ships (desktop/lib/local/). The CLI
133
- // reuses it as-is, scoped to the 'aegis' class only (see src/engine.js) —
134
- // one tool loop implementation, not a second one drifting alongside it.
135
- 'desktop/lib/local/engine.js',
136
- // engine.js and settings.js both require this at load time: it is the local
137
- // model transport, and the module that owns the fail-closed check deciding
138
- // whether a base URL is on this machine. Leaving it out stages a vendor tree
139
- // whose engine throws MODULE_NOT_FOUND before it can answer anything.
140
- 'desktop/lib/local/local.js',
141
- // engine.js requires this at load time to hold a turn cut off at its tool
142
- // horizon: the interruption is filed against the session and the next turn
143
- // resumes it instead of starting cold. Staging engine.js without it ships a
144
- // CLI that throws `Cannot find module './session-rounds.js'` before it can
145
- // answer anything — the same failure class as the 6.5.6 tarball below.
146
- 'desktop/lib/local/session-rounds.js',
147
- 'desktop/lib/local/tools.js',
148
- 'desktop/lib/local/shell.js',
149
- 'desktop/lib/local/agents.js',
150
- 'desktop/lib/local/prompt.js',
151
- // The provider-config store: one row per provider (base URL + key), and the
152
- // row the 'byok' class reads for a per-provider key. The CLI now selects that
153
- // class (src/engine.js), so it needs the same store the desktop writes —
154
- // created without a safeStorage argument, which the store already supports
155
- // (base64 at rest, file mode 0600). Pure node builtins, so it stages cleanly.
156
- 'desktop/lib/settings.js',
157
- // engine.js requires all three at load time (turn-guard -> git-scope, and
158
- // worktree-lock), so leaving them out stages a vendor tree whose engine
159
- // throws MODULE_NOT_FOUND before it can answer anything — which is what
160
- // test/cli-package.test.mjs caught in the published 6.5.6 tarball.
161
- 'desktop/lib/local/turn-guard.js',
162
- 'desktop/lib/local/worktree-lock.js',
163
- 'desktop/lib/local/git-scope.js',
164
- // The autonomous work queue (`queue.js`) and its unattended worker
165
- // (`autonomous.js`), which `src/deps.js` requires at load time along with
166
- // everything above — a named interface, not a lazy one, so a vendor tree
167
- // missing either throws MODULE_NOT_FOUND before the CLI can print its usage.
168
- // `autonomous.js` requires `./queue.js` and `./git-scope.js` at load time and
169
- // both sit above; `queue.js` requires only node builtins.
170
- 'desktop/lib/local/queue.js',
171
- 'desktop/lib/local/autonomous.js',
172
- // The shared Pro gate. `autonomous.js` requires `src/entitlement.js` at load
173
- // time, and that module locates this file by EXISTENCE through
174
- // `resolveShared` — never by a fallback copy — so a vendor tree missing it
175
- // throws before the CLI can print its usage, the same failure class as 6.5.6.
176
- // The module requires nothing at all: the account probe is injected by the
177
- // caller, which is why staging it alone is enough.
178
- 'desktop/lib/local/entitlement.js',
179
- // ── the ÆGIS covenant (ÆL/1) ────────────────────────────────────────────
180
- // `engine.js` requires `./covenant.js` at LOAD time, unconditionally, at the
181
- // top of the file — before any tool can run. It is the pre-action gate
182
- // (`guardedExecute` → `covenant.preActionAssert`), so a vendor tree without
183
- // it does not merely lose the gate: `require(enginePath)` in src/deps.js
184
- // throws `Cannot find module './covenant.js'` and the CLI cannot print its
185
- // own usage. Same failure class as the 6.5.6 tarball above, one file over.
186
- 'desktop/lib/local/covenant.js',
187
- // covenant.js requires the codec the first time it decodes. Staged for the
188
- // same reason: without it the seal is unreadable and the gate degrades to
189
- // the hard-coded immutable trio instead of the full decoded covenant.
190
- 'desktop/lib/local/aegis-seal.mjs',
191
- // The sealed covenant itself (ÆS/1 container). This one is NOT optional
192
- // decoration: it is the artifact the whole module exists to decode, and it
193
- // lives at the repo root because it is the same file the desktop app and the
194
- // published COVENANT.md point at. `covenant.js` resolves it three levels up
195
- // from its own directory, which in this staged tree lands exactly on
196
- // `cli/vendor/covenant/aegis.seal` — the repo's own shape, mirrored, which is
197
- // the whole convention this file follows. No path rewrite is needed in
198
- // either copy.
199
- 'covenant/aegis.seal',
200
- // The decode command and the CC0 notice, shipped beside the artifact so a
201
- // reader who finds the seal in an installed package can reverse it.
202
- 'covenant/README.md',
203
- // The agent-key gate CLI (status/check/init/bind-machine/import-key/rotate/
204
- // add-key/lock-status). Resolved lazily by src/gate.js through
205
- // resolveShared() rather than eagerly by deps.js, since it is an ES module
206
- // (import/export) loaded via dynamic import(), not require(); a package
207
- // built without it fails only the gate subcommand, at the point someone runs
208
- // it, not at CLI load. Staged under vendor/tools so a checkout and a
209
- // published package resolve the same repo-relative path.
210
- 'tools/agent-gate.mjs',
211
- ];
212
-
213
- function main() {
214
- fs.rmSync(VENDOR, { recursive: true, force: true });
215
- const staged = [];
216
-
217
- for (const rel of FILES) {
218
- const from = path.join(REPO_DIR, rel);
219
- if (!fs.existsSync(from)) {
220
- console.error(`predist: missing shared module: ${rel} (expected at ${from})`);
221
- process.exit(1);
222
- }
223
- const to = path.join(VENDOR, rel);
224
- fs.mkdirSync(path.dirname(to), { recursive: true });
225
- fs.copyFileSync(from, to);
226
- const same = fs.readFileSync(from).equals(fs.readFileSync(to));
227
- if (!same) {
228
- console.error(`predist: staged copy differs from source: ${rel}`);
229
- process.exit(1);
230
- }
231
- staged.push(`${rel} -> vendor/${rel}`);
232
- }
233
-
234
- // Prove the staged tree stands on its own: the registry must load and
235
- // resolve its own dependencies from inside vendor/, not from the repo.
236
- const toolsPath = path.join(VENDOR, 'mcp', 'tools.js');
237
- delete require.cache[require.resolve(toolsPath)];
238
- const { createTools } = require(toolsPath);
239
- const tools = createTools({
240
- apiBase: 'http://127.0.0.1',
241
- apiKey: 'predist-probe',
242
- randomUUID: () => 'id',
243
- });
244
- const count = tools.toolList().length;
245
- if (count === 0) {
246
- console.error('predist: staged registry exposes no tools');
247
- process.exit(1);
248
- }
249
-
250
- console.log(`predist: staged ${staged.length} shared modules into cli/vendor/`);
251
- for (const s of staged) console.log(` ${s}`);
252
- console.log(`predist: staged registry loads standalone (${count} tools)`);
253
-
254
- // -------------------------------------------------------------------------
255
- // The editor layer, proven from inside the staged tree.
256
- // -------------------------------------------------------------------------
257
- //
258
- // Three things have to be true of the package we are about to publish, and
259
- // none of them are visible from the repo:
260
- //
261
- // 1. the stdio server is present and is valid JavaScript;
262
- // 2. `hosts/spec.js` resolves THAT copy of it, not a checkout path that
263
- // only exists on this machine — an editor config pointing at a missing
264
- // file fails silently, which is the worst failure mode there is;
265
- // 3. `hosts/install.js` loads with its siblings resolved from vendor/.
266
- //
267
- // The server is compiled rather than required, deliberately: it registers
268
- // process.stdin handlers at load time and exports nothing, so requiring it
269
- // here would take over predist's own stdin and keep it alive forever.
270
- const vm = require('node:vm');
271
- const serverJs = path.join(VENDOR, 'mcp', 'server.js');
28
+ async function main() {
29
+ let shared;
272
30
  try {
273
- new vm.Script(fs.readFileSync(serverJs, 'utf8'), { filename: serverJs });
274
- } catch (err) {
275
- console.error(`predist: staged mcp/server.js does not compile: ${err.message}`);
276
- process.exit(1);
277
- }
278
-
279
- const hostsDir = path.join(VENDOR, 'hosts');
280
- const spec = require(path.join(hostsDir, 'spec.js'));
281
- const install = require(path.join(hostsDir, 'install.js'));
282
- const targets = require(path.join(hostsDir, 'targets.js'));
283
-
284
- // An empty AEGIS_MCP_SERVER so a developer's own override cannot mask a
285
- // broken staged tree — the candidate we are asserting on must be the staged
286
- // one, and nothing else.
287
- const resolved = spec.resolveServer({ AEGIS_MCP_SERVER: '' });
288
- const stagedServer = path.join(VENDOR, 'mcp', 'server.js');
289
- if (!resolved.exists || resolved.path !== stagedServer) {
290
- console.error(
291
- `predist: staged hosts/spec.js resolves the server as ${resolved.path} ` +
292
- `(exists: ${resolved.exists}), expected ${stagedServer}. An installed ` +
293
- 'aegiscode would write editor configs pointing at a file the package ' +
294
- `never shipped. Candidates were:\n ${resolved.candidates.join('\n ')}`
295
- );
296
- process.exit(1);
297
- }
298
-
299
- // Plan one real install against a throwaway home: this is the exact document
300
- // `aegiscode mcp install vscode` would write, so it is the cheapest possible
301
- // proof that the packaged command points at a file that exists.
302
- const vscode = targets.getTarget('vscode');
303
- const plan = install.planTarget(vscode, 'user', {
304
- ctx: install.hostCtx({ home: path.join(VENDOR, '.predist-home'), env: {}, cwd: REPO_DIR }),
305
- specOpts: { env: { AEGIS_MCP_SERVER: '' } },
306
- });
307
- const wrote = JSON.stringify(plan.after || '');
308
- if (plan.error || !plan.changed || !wrote.includes(JSON.stringify(stagedServer).slice(1, -1))) {
309
- console.error(
310
- `predist: a planned vscode install does not name the staged server ` +
311
- `(error: ${plan.error && plan.error.message}, changed: ${plan.changed})`
31
+ shared = await import(pathToFileURL(SHARED).href);
32
+ } catch (error) {
33
+ process.stderr.write(
34
+ `predist: the shared stager is not reachable at ${SHARED}.\n` +
35
+ `predist: it lives in the repo (one/scripts/predist.mjs) and is not shipped ` +
36
+ `inside the aegiscode tarball — a built package already carries its vendor tree.\n` +
37
+ `${(error && error.message) || error}\n`
312
38
  );
313
- process.exit(1);
39
+ return 1;
314
40
  }
315
-
316
- // The shim resolves cli/src/models.js from either layout on its own load; a
317
- // checkout has it and the package ships it as src/models.js. Loading it here
318
- // is what catches a repo-shaped require that only works in development.
319
- const shim = require(path.join(hostsDir, 'openai-shim.js'));
320
- if (typeof shim.createShimServer !== 'function') {
321
- console.error('predist: staged hosts/openai-shim.js exposes no createShimServer');
322
- process.exit(1);
323
- }
324
-
325
- console.log(
326
- `predist: editor layer verified (${targets.targetIds().length} host targets, ` +
327
- `server resolves to vendor/mcp/server.js, shim loads)`
328
- );
41
+ return shared.main(['--mirror-only']);
329
42
  }
330
43
 
331
- main();
332
-
333
- // The gate module is an ES module (import/export), loaded by src/gate.js via
334
- // dynamic import() rather than require() — so this check is async and runs
335
- // after main()'s synchronous staging, and a broken staged copy must fail
336
- // predist here, not wait for the first `aegiscode gate` invocation someone
337
- // runs after publish.
338
- const gateStagedPath = path.join(VENDOR, 'tools', 'agent-gate.mjs');
339
- const gateMod = await import(pathToFileURL(gateStagedPath).href);
340
- if (typeof gateMod.run !== 'function') {
341
- console.error('predist: staged tools/agent-gate.mjs exposes no run()');
342
- process.exit(1);
44
+ if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
45
+ process.exitCode = await main();
343
46
  }
344
- console.log('predist: staged tools/agent-gate.mjs loads standalone and exposes run()');
47
+
48
+ export { main };
package/src/app.js CHANGED
@@ -166,6 +166,36 @@ function createApp(options = {}) {
166
166
  getClass: () => commandCtx.modelClass,
167
167
  getConfirmMode: () => {
168
168
  if (options.confirmMode !== undefined) return confirmMode;
169
+ // AEGISONE D8 rule 5 — the skip posture, resolved by the SAME function
170
+ // the product uses (cli/src/permissions.js resolveSkip), so the two
171
+ // faces cannot disagree about what a flag or an environment variable
172
+ // means. Two sources only:
173
+ //
174
+ // AEGISONE_SKIP_PERMISSIONS the `aegis` bin's forwarded decision,
175
+ // already checked against rule 5 upstream;
176
+ // AEGIS_SKIP_PERMISSIONS the CI/queue spelling, honored only when
177
+ // this process is NON-interactive. A stray
178
+ // `export` in a shell profile warns and is
179
+ // ignored here, which is the whole point:
180
+ // it must not be able to disarm a human's
181
+ // own gate.
182
+ //
183
+ // A rule-5 refusal is reported once per session, not per tool call —
184
+ // the gate is read on every round and a warning per round would be
185
+ // noise the user learns to scroll past.
186
+ try {
187
+ const skip = resolveSkip({
188
+ env: process.env,
189
+ interactive: Boolean(process.stdin.isTTY && process.stdout.isTTY),
190
+ });
191
+ if (skip.warned && !skipEnvWarned) {
192
+ skipEnvWarned = true;
193
+ process.stderr.write(`aegiscode: ${skip.warning}\n`);
194
+ }
195
+ if (skip.skip) return false;
196
+ } catch {
197
+ /* fall through to the store: a broken skip resolver must not skip */
198
+ }
169
199
  try {
170
200
  return loadPermissions().defaultMode !== 'allow';
171
201
  } catch {
package/src/commands.js CHANGED
@@ -2043,6 +2043,101 @@ const COMMANDS = [
2043
2043
  return true;
2044
2044
  },
2045
2045
  },
2046
+ {
2047
+ // The in-session top-up. `/billing` printed a link and that was the whole
2048
+ // funding story in the terminal; the link is real but it lands on `/topup`,
2049
+ // which is `@login_required` against a browser SESSION, and the account this
2050
+ // product auto-provisions is a device key with no password anyone holds and
2051
+ // an email at `@device.aegiscloud`. So the user who needs to fund a free
2052
+ // account could not sign in to the page that funds it — they paid a visit to
2053
+ // a login wall and read it as "my payment failed".
2054
+ //
2055
+ // This does what the desktop does, over the SAME shared core
2056
+ // (`client/topup.js`): the credential that creates the checkout is the one
2057
+ // that can read the bank, so the confirmation comes from the API rather than
2058
+ // from a page the account cannot open. Bounds and payload reading are shared,
2059
+ // never re-derived here.
2060
+ name: 'topup', aliases: ['fund'], args: ['amount'], hint: '[EUR]', category: 'support',
2061
+ desc: 'Top up the token bank — opens the payment page and confirms the credit here',
2062
+ handler: async (c, args) => {
2063
+ const raw = String(args.amount || args._rest || '').trim();
2064
+ let shared;
2065
+ try {
2066
+ // Lazy: the TUI pays for this only when someone asks to pay.
2067
+ shared = require(require('./sharedpaths.js').resolveShared('client/topup.js'));
2068
+ } catch (e) {
2069
+ note(c, `top-up is unavailable in this build — ${e.message}`);
2070
+ c.render();
2071
+ return true;
2072
+ }
2073
+ const parsed = shared.parseTopupAmount(raw);
2074
+ if (!parsed.ok) {
2075
+ note(c, parsed.message);
2076
+ c.render();
2077
+ return true;
2078
+ }
2079
+ if (!c.client.apiKey) {
2080
+ // Same honest refusal the rest of the account surfaces give, and the
2081
+ // same fix: the key is what pays. Auto-provisioning happens on session
2082
+ // start (app.js ensureApiKey), so this is the offline/failed case.
2083
+ note(c, `no AEGIS key on this machine — ${credentials.HOW_TO_SET}, then /topup ${parsed.amount}`);
2084
+ c.render();
2085
+ return true;
2086
+ }
2087
+ const started = c.withWorking
2088
+ ? await c.withWorking(() => shared.startTopup(c.client, parsed.amount))
2089
+ : await shared.startTopup(c.client, parsed.amount);
2090
+ if (!started.ok) {
2091
+ note(c, `the top-up could not be started — ${started.message}`);
2092
+ if (started.hint) note(c, started.hint);
2093
+ c.render();
2094
+ return true;
2095
+ }
2096
+ // The URL rides its own row: `note` rows are a single unwrapped span
2097
+ // (chatflow.js), so appending it to that sentence pushes the tail past
2098
+ // `cols` where `padLine()` cuts it — and the tail is the URL.
2099
+ note(c, `opening the payment page — ${parsed.amount} EUR`);
2100
+ note(c, started.url);
2101
+ const seconds = Math.round((shared.TOPUP_POLL_MS * shared.TOPUP_POLL_TRIES) / 1000);
2102
+ note(c, `watching this account's bank for up to ${seconds}s; the credit is confirmed here, not in the browser`);
2103
+ c.render();
2104
+ const open = openUrl(started.url);
2105
+ if (!open) note(c, 'could not open a browser — use the URL above');
2106
+
2107
+ // A recursive timeout rather than an interval: the balance call can take
2108
+ // longer than one period on a slow link, and an interval would start a
2109
+ // second read on top of the first — two reads, two announcements of one
2110
+ // credit. Unref'd so an unfinished payment never keeps the TUI alive.
2111
+ const watch = shared.createCreditWatch(c.client);
2112
+ let timer = null;
2113
+ let done = false;
2114
+ const settle = () => {
2115
+ done = true;
2116
+ if (timer) clearTimeout(timer);
2117
+ };
2118
+ const step = async () => {
2119
+ if (done) return;
2120
+ const res = await watch.tick();
2121
+ if (res.state === 'credited') {
2122
+ settle();
2123
+ note(c, `credit confirmed — the bank is now ${res.amount.toFixed(2)} EUR`);
2124
+ c.render();
2125
+ return;
2126
+ }
2127
+ if (res.state === 'expired') {
2128
+ settle();
2129
+ note(c, 'no credit observed within the watch window — if you completed the payment it may still land; /billing shows the bank');
2130
+ c.render();
2131
+ return;
2132
+ }
2133
+ timer = setTimeout(step, shared.TOPUP_POLL_MS);
2134
+ if (timer && typeof timer.unref === 'function') timer.unref();
2135
+ };
2136
+ timer = setTimeout(step, shared.TOPUP_POLL_MS);
2137
+ if (timer && typeof timer.unref === 'function') timer.unref();
2138
+ return true;
2139
+ },
2140
+ },
2046
2141
  {
2047
2142
  name: 'cloud', args: ['sub', 'value'], hint: '[status|key <api_key>|activate|deactivate|memory [on|off]|sync [on|off|now]]', category: 'support',
2048
2143
  desc: 'Show and control ÆGIS cloud sync',