aegiscode 6.8.12 → 6.8.13

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/src/panels.js CHANGED
@@ -60,6 +60,39 @@ function str(v) {
60
60
  return v == null ? '' : String(v);
61
61
  }
62
62
 
63
+ /**
64
+ * Word-wrap one sentence into span rows, indented, so a long claim survives
65
+ * `padLine()`.
66
+ *
67
+ * Local rather than imported on purpose (see the header: this file stays
68
+ * self-contained apart from theme/screen). `screens.js` has a `wrapped()` that
69
+ * does the same job, but it lives behind the screen-drawing module, which
70
+ * requires this one — importing it here would close a require cycle to reuse
71
+ * fifteen lines.
72
+ *
73
+ * Anything one word longer than the terminal is emitted on its own row rather
74
+ * than dropped: `padLine()` clips it, which is what already happens today, and
75
+ * losing a word is better than losing the sentence.
76
+ */
77
+ function wrapRows(text, indent, style, cols) {
78
+ const width = Math.max(20, (Number(cols) || 80) - 2 - indent);
79
+ const pad = ' '.repeat(indent);
80
+ const words = str(text).split(/\s+/).filter(Boolean);
81
+ const out = [];
82
+ let line = '';
83
+ for (const word of words) {
84
+ const next = line ? `${line} ${word}` : word;
85
+ if (line && next.length > width) {
86
+ out.push([span('', pad), span(style, line)]);
87
+ line = word;
88
+ } else {
89
+ line = next;
90
+ }
91
+ }
92
+ if (line) out.push([span('', pad), span(style, line)]);
93
+ return out.length ? out : [[span('', pad), span(style, '')]];
94
+ }
95
+
63
96
  /**
64
97
  * The four token buckets these panels render, in the shared shape.
65
98
  *
@@ -913,16 +946,53 @@ function buildBilling(state, ctx = {}) {
913
946
  }
914
947
  lines.push([span('', '')]);
915
948
  lines.push([span(t.white, 'AEGIS pooled inference'), span(t.gray, ' metered against your token bank')]);
916
- lines.push([span(t.gray, ' AEGIS has no subscription of its own — /cost shows this session\'s spend.')]);
917
- // Was a literal `https://aegiscloud.org/billing`, which has never been a
918
- // route on aegis1 — only `/billing/success` is real; the page is `/topup`.
919
- // So the one row on the one screen that exists to convert a free user sent
920
- // every user who reached it to a 404, and correcting a wrong path needed an
921
- // npm release because it was compiled into the client. Now it points at
922
- // `/go/topup`, a server-side indirection: the destination can change without
923
- // a client release, and the click arrives tagged with the channel. 75 cells
924
- // of 80 — measured, because `padLine()` truncates rather than wraps.
925
- lines.push([span(t.gray, ` Top-ups and invoices: ${goUrl('topup', 'cost_screen')}`)]);
949
+ // ── the paid prompt ───────────────────────────────────────────────────────
950
+ // `/billing` is the one screen a free user reaches when they are already
951
+ // thinking about money, and it used to spend that moment saying "AEGIS has no
952
+ // subscription of its own" — a claim that contradicted the plan Pro is sold
953
+ // as, on the only surface where the contradiction could cost a sale. It is
954
+ // now the place the ONE reason to pay is stated, in the words the desktop's
955
+ // welcome panel and the drain's refusal both use (`state.payment`, built by
956
+ // `cli/src/entitlement.js` from the shared module, so a terminal and a GUI
957
+ // cannot pitch two different products).
958
+ //
959
+ // The panel stays pure: it renders the view it is handed and never probes,
960
+ // never decides entitlement, and never invents a link. A caller that passes
961
+ // no view gets the top-up row it always printed, minus the false claim.
962
+ const pay = s.payment && typeof s.payment === 'object' ? s.payment : null;
963
+ if (pay) {
964
+ const { cols } = getSize();
965
+ const mark = pay.paid ? '✔' : '✦';
966
+ lines.push(...wrapRows(`${mark} ${str(pay.label) || 'Pro'}: ${str(pay.reason)}`, 2, pay.paid ? t.green : t.gold, cols));
967
+ // The honesty line rides every paid prompt, wrapped rather than clipped —
968
+ // `padLine()` truncates, and a truncated honesty line would read as the
969
+ // promise alone.
970
+ lines.push(...wrapRows(str(pay.honesty), 2, t.gray, cols));
971
+ if (!pay.paid && pay.unlock) lines.push(...wrapRows(str(pay.unlock), 2, t.gray, cols));
972
+ // The relay's price, on the lane a BYOK user is actually billed on. Printed
973
+ // only when the server published a rate (`pay.byok` is '' otherwise) —
974
+ // a hardcoded fee here would be a client disagreeing with the ledger, and
975
+ // saying nothing is the only honest alternative to inventing one. Wrapped,
976
+ // never clipped: `padLine()` truncates, and a truncated fee line would read
977
+ // as a cheaper lane than the one that bills.
978
+ if (pay.byok) lines.push(...wrapRows(str(pay.byok), 2, t.gray, cols));
979
+ // `verified === false` is the module's "we did not get a real answer"
980
+ // (timeout, unreadable body, no key). The offer still renders — this panel
981
+ // is allowed to sell — but a timeout is not presented as a fact about the
982
+ // account, which is the difference between a prompt and a lie.
983
+ if (pay.verified === false) lines.push(...wrapRows('(account not confirmed this session — verdict may be stale)', 2, t.gray, cols));
984
+ if (pay.url) lines.push([span('', ' '), span(t.gray, str(pay.url))]);
985
+ } else {
986
+ // Was a literal `https://aegiscloud.org/billing`, which has never been a
987
+ // route on aegis1 — only `/billing/success` is real; the page is `/topup`.
988
+ // So the one row on the one screen that exists to convert a free user sent
989
+ // every user who reached it to a 404, and correcting a wrong path needed an
990
+ // npm release because it was compiled into the client. Now it points at
991
+ // `/go/topup`, a server-side indirection: the destination can change without
992
+ // a client release, and the click arrives tagged with the channel. 75 cells
993
+ // of 80 — measured, because `padLine()` truncates rather than wraps.
994
+ lines.push([span(t.gray, ` Top-ups and invoices: ${goUrl('topup', 'cost_screen')}`)]);
995
+ }
926
996
  return lines;
927
997
  }
928
998
 
@@ -90,6 +90,84 @@ const LEGACY_PLAN_ALIASES = Object.freeze({
90
90
  const PRO_VALUE =
91
91
  'Pro puts the drain in the cloud, so the job keeps running after you close the laptop';
92
92
 
93
+ /**
94
+ * The honesty line — Phase 3's rule, and the second half of the same claim:
95
+ * everything that runs on the user's own machine stays free forever, and the
96
+ * cloud drain is the thing being sold. Both hosts that print a paid prompt
97
+ * print this beside it (the desktop keeps its own literal in
98
+ * `desktop/renderer/app.js`; the terminal reads it from here), because the
99
+ * promise without the honesty line is the four-bullet feature list again.
100
+ *
101
+ * Kept byte-identical to the renderer's `FREE_HONESTY`, and asserted verbatim
102
+ * by both hosts' tests, so the terminal and the GUI cannot come to disagree
103
+ * about what is free — a disagreement that would either overcharge a promise
104
+ * or undercut the offer, depending on which copy a user believed.
105
+ */
106
+ const FREE_HONESTY =
107
+ 'Everything on your machine is free, permanently. The cloud drain is what you pay for.';
108
+
109
+ /**
110
+ * The BYOK lane's price, in words — built from the SERVER's published rate.
111
+ *
112
+ * The desktop README says the byok lane is "billed a flat handling fee" and
113
+ * aegis1 charges exactly that (services/pricing.price_byok_call), but no client
114
+ * surface said so: a user who pasted their own Anthropic key into AEGIS read
115
+ * "your provider's cost" and never learned AEGIS adds a fee. That is the one
116
+ * place in this product where the bill and the pitch disagreed, and it is the
117
+ * copy the desktop session flagged as an unresolved honesty conflict.
118
+ *
119
+ * `fee` is aegis1's own `/api/v1/byok/providers` payload — a live payload, never
120
+ * a hardcoded number, for the reason the engine already states: a client that
121
+ * hardcodes a fee is a client that can disagree with the ledger. No published
122
+ * fee (old server, offline, unauthenticated read that returned nothing) returns
123
+ * '' and every host then says NOTHING about the price, which is the only honest
124
+ * alternative to inventing one.
125
+ *
126
+ * `require_account` / `anonymous_daily_calls` come from the same payload and
127
+ * describe enforcement, not price: with the relay requiring an AEGIS account the
128
+ * sentence has to say so, or the user meets a 402 the client never warned about
129
+ * — the exact failure tests/test_byok_fee.py::test_the_published_gate_warning_is
130
+ * _true_whenever_the_gate_can_402 exists to prevent.
131
+ */
132
+ const BYOK_FEE_NOTE =
133
+ 'Bring your own key is relayed through AEGIS, not dialled from here — the routing, prompt assembly and caching are billed as a flat handling fee, on top of your provider\'s own bill.';
134
+
135
+ /** Per-million-token rendering of a published per-1k rate. */
136
+ function ratePerMillion(usdPer1k) {
137
+ return `$${(Number(usdPer1k) * 1000).toFixed(2)}/M`;
138
+ }
139
+
140
+ function byokFeeLine(fee) {
141
+ const f = fee && typeof fee === 'object' ? fee : null;
142
+ if (!f) return '';
143
+ const inRate = Number(f.in_usd_per_1k);
144
+ const outRate = Number(f.out_usd_per_1k);
145
+ if (!Number.isFinite(inRate) || !Number.isFinite(outRate)) return '';
146
+ if (f.disabled === true) {
147
+ // The deployment switched the fee off; saying "free" is then the truth
148
+ // rather than a promise this client cannot keep.
149
+ return 'Bring your own key is relayed free on this deployment right now.';
150
+ }
151
+ // The price clause stands alone when the server published no enforcement
152
+ // detail — which is every server deployed before this change, and the
153
+ // default-off gate after it. Joined with ' — ' only when there IS a second
154
+ // clause: a sentence-ending dash with nothing after it ("…provider's bill —.")
155
+ // is what the first live run of this line actually printed.
156
+ const price = `Bring your own key: relayed through AEGIS, handled at `
157
+ + `${ratePerMillion(inRate)} in / ${ratePerMillion(outRate)} out, `
158
+ + `on top of your provider's bill`;
159
+ let clause = '';
160
+ if (f.require_account === true) {
161
+ clause = 'and needs an AEGIS account key (X-AEGIS-Key) for the fee to be billed';
162
+ } else {
163
+ const cap = Number(f.anonymous_daily_calls);
164
+ if (Number.isFinite(cap) && cap > 0) {
165
+ clause = `with ${cap} relayed turns/24h before an AEGIS account is required`;
166
+ }
167
+ }
168
+ return clause ? `${price} — ${clause}.` : `${price}.`;
169
+ }
170
+
93
171
  /** Campaign id for this prompt (Phase 1's fixed ids; aegis1 keeps the slug). */
94
172
  const CAMPAIGN = 'queue_cap';
95
173
 
@@ -478,6 +556,9 @@ module.exports = {
478
556
  BALANCE_CAMPAIGN,
479
557
  BALANCE_URL,
480
558
  PRO_VALUE,
559
+ FREE_HONESTY,
560
+ BYOK_FEE_NOTE,
561
+ byokFeeLine,
481
562
  DEFAULT_TTL_MS,
482
563
  // Phase 7: the host seam + the builder the CLI binds itself to.
483
564
  SIGNUP_SOURCES,
@@ -42,6 +42,7 @@ const { spawn } = require('node:child_process');
42
42
  const crypto = require('node:crypto');
43
43
  const fs = require('node:fs');
44
44
  const path = require('node:path');
45
+ const { pathToFileURL } = require('node:url');
45
46
  const { agentRoles } = require('./agents.js');
46
47
 
47
48
  const OUTPUT_CAP = 30_000; // chars fed back to the model per tool result
@@ -770,9 +771,121 @@ function isTool(name) {
770
771
  * all land on the error branch rather than rejecting. `ctx` carries per-turn
771
772
  * state (getShell, signal); omit it and exec falls back to a one-shot spawn.
772
773
  */
774
+ /**
775
+ * `tools/agent-gate.mjs` is ESM and this module is CJS, so it is imported
776
+ * dynamically and once. The candidates are tried in order; the first that
777
+ * resolves wins:
778
+ *
779
+ * 1. `../../../tools/agent-gate.mjs` — the repo checkout (dev / CI). This is
780
+ * the SAME file the git hooks execute, so "what is allowed" is computed
781
+ * once, by one implementation.
782
+ * 2. `<process.resourcesPath>/tools/agent-gate.mjs` — where electron-builder's
783
+ * `extraResources` puts it in a packaged build, as a real file OUTSIDE the
784
+ * asar. That placement is load-bearing, not cosmetic: the gate is loaded
785
+ * with dynamic `import()`, and Node's ESM loader does not go through
786
+ * Electron's asar-aware fs patch (electron/asar#249), so a copy living only
787
+ * inside the archive can fail to resolve — leaving the packaged app with no
788
+ * gate at all. This is the app's only dynamic ESM import, so nothing else
789
+ * here exercises that path. Conveniently this is also what candidate (1)
790
+ * resolves to from `resources/app.asar/lib/local/`, so dev and packaged
791
+ * builds agree on one file.
792
+ * 3. `../../vendor/agent-gate.mjs` — the staged copy inside the app dir, kept
793
+ * as the last resort for a build that is not archived (`asar: false`) or an
794
+ * npm-installed tree. It is the candidate that fails inside an asar, hence
795
+ * third and not first.
796
+ *
797
+ * Before (2) existed a packaged build had no gate at all: the manifest is found
798
+ * by climbing from the working directory, so the packaged app would open a
799
+ * guarded tree and every write through it succeeded while the same call through
800
+ * the repo copy was refused.
801
+ *
802
+ * If nothing resolves, that is a broken gate rather than a permissive one, and
803
+ * executeTool refuses mutating calls into a tree that declares a manifest.
804
+ */
805
+ let agentGatePromise;
806
+
807
+ function agentGateCandidates({ resourcesPath = process.resourcesPath, dirname = __dirname } = {}) {
808
+ const candidates = ['../../../tools/agent-gate.mjs'];
809
+ // process.resourcesPath is an Electron-provided value and is absent under
810
+ // plain node, so this is guarded rather than assumed. An absolute path must
811
+ // be a file URL to be imported.
812
+ if (typeof resourcesPath === 'string' && resourcesPath) {
813
+ candidates.push(pathToFileURL(path.join(resourcesPath, 'tools', 'agent-gate.mjs')).href);
814
+ }
815
+ candidates.push('../../vendor/agent-gate.mjs');
816
+ return candidates;
817
+ }
818
+
819
+ function loadAgentGate() {
820
+ if (!agentGatePromise) {
821
+ const candidates = agentGateCandidates();
822
+ const tryNext = (i) => (i >= candidates.length
823
+ ? null
824
+ : import(candidates[i]).catch(() => tryNext(i + 1)));
825
+ agentGatePromise = tryNext(0);
826
+ }
827
+ return agentGatePromise;
828
+ }
829
+
830
+ /**
831
+ * The nearest `.aegis/guard.json` at or above `start`, or null. The identical
832
+ * climb as findManifest() in tools/agent-gate.mjs and src/repoguard.js. It is
833
+ * used ONLY to decide whether a call that could not load the gate module is
834
+ * unsafe; when the module loads it is the sole authority.
835
+ */
836
+ function nearestManifest(start) {
837
+ let dir = path.resolve(start || process.cwd());
838
+ try { if (fs.statSync(dir).isFile()) dir = path.dirname(dir); } catch { /* keep as-is */ }
839
+ for (;;) {
840
+ const candidate = path.join(dir, '.aegis', 'guard.json');
841
+ if (fs.existsSync(candidate)) return candidate;
842
+ const parent = path.dirname(dir);
843
+ if (parent === dir) return null;
844
+ dir = parent;
845
+ }
846
+ }
847
+
773
848
  async function executeTool(name, args, ctx) {
774
849
  if (!isTool(name)) return fail(`unknown tool "${name}" (known: ${toolNames().join(', ')})`);
775
850
  const input = args && typeof args === 'object' ? args : {};
851
+ // ── agent-key gate (tools/agent-gate.mjs) ──────────────────────────────
852
+ // The in-process half of the lock whose other half is .githooks/. A tree
853
+ // that declares .aegis/guard.json must not be mutated through this app
854
+ // without the key, exactly as it cannot be mutated by the engine or
855
+ // committed by git. Reads are never gated. Refused — not warned — when the
856
+ // key is absent, the manifest is unreadable, or the key file is
857
+ // world-readable; AEGIS_GATE_SKIP=1 is the one bypass, and it is refused in
858
+ // an unattended run. The module is required lazily so a packaged app whose
859
+ // tree has no tools/ directory still starts and simply has no gate.
860
+ let gate = null;
861
+ try {
862
+ gate = await loadAgentGate();
863
+ } catch { /* not running from the repo: no manifest to honour */ }
864
+ if (gate) {
865
+ const verdict = gate.guardTool({
866
+ tool: name, args: input, cwd: (ctx && ctx.cwd) || process.cwd(),
867
+ env: process.env, unattended: Boolean(ctx && ctx.autonomous),
868
+ });
869
+ if (!verdict.allowed) return fail(gate.refusalText(verdict));
870
+ if (verdict.code === 'skipped') {
871
+ const res = await EXECUTORS[name](input, ctx || {});
872
+ return res && typeof res === 'object' ? { ...res, output: `⚠ ${verdict.reason}\n${res.output || ''}` } : res;
873
+ }
874
+ } else if (MUTATING_TOOLS.has(name)) {
875
+ // Neither the repo copy nor the staged one loaded. A broken gate must
876
+ // never silently allow (the hooks exit 4 for exactly this reason), so a
877
+ // mutating call into a tree that declares a manifest is refused with the
878
+ // path of the manifest that could not be honoured.
879
+ const man = nearestManifest((ctx && ctx.cwd) || process.cwd());
880
+ if (man) {
881
+ return fail(
882
+ `error: refused — ${man} declares an agent-gated tree, but the agent-key gate module could not be loaded `
883
+ + '(tried tools/agent-gate.mjs beside the app and vendor/agent-gate.mjs inside it), so this '
884
+ + `${name} cannot be authorised. A build that missed the staged copy is the usual cause: `
885
+ + 'run scripts/predist.mjs before packaging.',
886
+ );
887
+ }
888
+ }
776
889
  try {
777
890
  return await EXECUTORS[name](input, ctx || {});
778
891
  } catch (e) {