aegisone 1.0.5 → 1.0.8

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 (45) hide show
  1. package/README.md +2 -2
  2. package/bin/aegis.js +28 -3
  3. package/package.json +1 -1
  4. package/scripts/predist.mjs +230 -0
  5. package/src/permissions.js +134 -7
  6. package/src/release.js +14 -5
  7. package/vendor/cli/README.md +42 -3
  8. package/vendor/cli/bin/aegiscode.js +15 -3
  9. package/vendor/cli/package.json +1 -1
  10. package/vendor/cli/src/app.js +167 -37
  11. package/vendor/cli/src/chatflow.js +285 -39
  12. package/vendor/cli/src/commands.js +251 -30
  13. package/vendor/cli/src/config.js +41 -11
  14. package/vendor/cli/src/engine.js +33 -4
  15. package/vendor/cli/src/entitlement.js +30 -1
  16. package/vendor/cli/src/format.js +175 -3
  17. package/vendor/cli/src/overlays.js +13 -9
  18. package/vendor/cli/src/panels.js +19 -6
  19. package/vendor/cli/src/render.js +49 -14
  20. package/vendor/cli/src/screen.js +12 -1
  21. package/vendor/cli/src/screens.js +118 -25
  22. package/vendor/cli/src/todos.js +7 -4
  23. package/vendor/cli/src/tokens.js +31 -1
  24. package/vendor/cli/vendor/client/aegis.js +22 -0
  25. package/vendor/cli/vendor/client/byok-catalog.js +43 -8
  26. package/vendor/cli/vendor/client/user-models.js +378 -0
  27. package/vendor/cli/vendor/desktop/lib/local/autonomous.js +81 -0
  28. package/vendor/cli/vendor/desktop/lib/local/engine.js +447 -14
  29. package/vendor/cli/vendor/desktop/renderer/usage.js +274 -21
  30. package/vendor/cli/vendor/mcp/tools.js +1 -1
  31. package/vendor/desktop/README.md +11 -0
  32. package/vendor/desktop/lib/deep-link.js +35 -1
  33. package/vendor/desktop/lib/local/autonomous.js +81 -0
  34. package/vendor/desktop/lib/local/engine.js +447 -14
  35. package/vendor/desktop/main.js +271 -6
  36. package/vendor/desktop/package.json +1 -1
  37. package/vendor/desktop/preload.js +18 -0
  38. package/vendor/desktop/renderer/app.js +631 -43
  39. package/vendor/desktop/renderer/index.html +4 -5
  40. package/vendor/desktop/renderer/stream-policy.js +24 -2
  41. package/vendor/desktop/renderer/style.css +81 -7
  42. package/vendor/desktop/renderer/usage.js +274 -21
  43. package/vendor/desktop/vendor/aegis.js +22 -0
  44. package/vendor/desktop/vendor/byok-catalog.js +43 -8
  45. package/vendor/desktop/vendor/user-models.js +378 -0
@@ -139,9 +139,36 @@ function estimatedBuckets(prompt, reply, reasoning) {
139
139
  // Keys are matched by exact id first, then by prefix (ratesFor below), so a
140
140
  // family row covers every dated variant of it.
141
141
  const RATES = {
142
+ // Sonnet, Opus, Fable, Haiku — the four FAMILY rows, matched by prefix, and
143
+ // deliberately NOT re-pointed at any one generation's price.
144
+ //
145
+ // The tempting change is to price this row as Claude Sonnet 5's published
146
+ // $2.00/$10.00, on the theory that `sonnet` names Sonnet 5. It does not: this
147
+ // repo's own alias tables carry no such id. `cli/src/models.js` lists pooled
148
+ // seats by name and `cli/src/config.js` records that the platform "does not
149
+ // advertise" `sonnet` at all — a pin on it was a phantom that made the pool
150
+ // answer from its own default with no error. So a bare `sonnet` is a LABEL,
151
+ // not a route: `cli/src/tokens.js` uses it as the default stand-in when no
152
+ // model is named, and the family row here is what a non-`claude-`-prefixed
153
+ // spelling resolves to by prefix.
154
+ //
155
+ // $3.00/$15.00 is therefore the honest figure for it, and it is the SAME
156
+ // figure as `RATES.default` below — which is the point: an id that names no
157
+ // real vendored route prices exactly like an unpriced one, never like a
158
+ // current-generation model. Every id that DOES name a real model has an exact
159
+ // row in the Claude 5 block below, and an exact id out-ranks a prefix match,
160
+ // so correcting those is what fixes the money — re-pointing this family row
161
+ // only moves the number an admitted placeholder reports, and silently
162
+ // re-prices every dated spelling that resolves here by prefix
163
+ // (`sonnet-4-5-20250929` is pinned at $3.00 in test/turn-accounting.test.mjs
164
+ // for exactly that reason).
142
165
  sonnet: { input: 3.00, output: 15.00, cacheRead: 0.30, cacheWrite: 3.75 },
143
166
  default: { input: 3.00, output: 15.00, cacheRead: 0.30, cacheWrite: 3.75 },
144
- fable: { input: 5.00, output: 25.00, cacheRead: 0.50, cacheWrite: 6.25 },
167
+ // Fable — the alias for **claude-fable-5**, at Fable's published
168
+ // $10.00/$50.00. The $5.00/$25.00 this row used to carry is the Opus-class
169
+ // figure; Fable has never been priced there, and the error ran in the
170
+ // under-reporting direction on the most expensive model in the lineup.
171
+ fable: { input: 10.00, output: 50.00, cacheRead: 1.00, cacheWrite: 12.50 },
145
172
  opus: { input: 5.00, output: 25.00, cacheRead: 0.50, cacheWrite: 6.25 },
146
173
  // Haiku — the same class of hole as the DeepSeek row below, on the provider
147
174
  // whose prices we already thought we knew. The three rows above price Sonnet,
@@ -160,6 +187,46 @@ const RATES = {
160
187
  // match is EXACT and cannot be reordered away.
161
188
  'claude-haiku': { input: 1.00, output: 5.00, cacheRead: 0.10, cacheWrite: 1.25 },
162
189
 
190
+ // ── the Claude 5 line, one row per ID ────────────────────────────────────
191
+ //
192
+ // Every figure here is Anthropic's own published rate (docs.claude.com
193
+ // pricing table, fetched 2026-10-11), not a fraction derived from a sibling
194
+ // row. They are EXACT rows because the family fallback prices this
195
+ // generation wrong in both directions: `claude-sonnet-5-5` family-matched
196
+ // `sonnet` and `claude-fable-5-1` family-matched `fable`, so the very ids
197
+ // the picker offers and the BYOK relay forwards were billed at rates the
198
+ // vendor does not charge for them.
199
+ //
200
+ // cacheRead is NOT the 0.1x-input convention the 4.x rows above use.
201
+ // Anthropic changed the cache-hit multiplier on this generation and quotes
202
+ // it per model — 5% of input on Opus 5.5 and Sonnet 5.5 ($0.20 / $0.10),
203
+ // 2.5% on Fable 5.1 ($0.25), 10% on Fable 5 and Haiku 5.5 ($1.00 / $0.01)
204
+ // — so each row carries the published number rather than a multiplier this
205
+ // file computed. cacheWrite stays 1.25x input, which the same table
206
+ // confirms for all of them.
207
+ //
208
+ // Haiku 5.5 is priced by PROMPT LENGTH: the vendor charges 5x input and 5x
209
+ // output once a request's prompt passes 100k tokens ($0.50/$2.50). This
210
+ // schema has no prompt-size field — the only tiering it models is
211
+ // DeepSeek's time-of-day peak/offPeak — so the row carries the up-to-100k
212
+ // tier and a long-context Haiku turn UNDER-reports. Said out loud rather
213
+ // than left implicit: the alternative is 5x-ing every ordinary Haiku turn,
214
+ // which is the louder error.
215
+ 'claude-opus-5': { input: 5.00, output: 25.00, cacheRead: 0.50, cacheWrite: 6.25 },
216
+ 'claude-opus-5-5': { input: 4.00, output: 20.00, cacheRead: 0.20, cacheWrite: 5.00 },
217
+ 'claude-sonnet-5': { input: 2.00, output: 10.00, cacheRead: 0.20, cacheWrite: 2.50 },
218
+ 'claude-sonnet-5-5': { input: 2.00, output: 10.00, cacheRead: 0.10, cacheWrite: 2.50 },
219
+ 'claude-haiku-5-5': { input: 0.10, output: 0.50, cacheRead: 0.01, cacheWrite: 0.125 },
220
+ 'claude-fable-5': { input: 10.00, output: 50.00, cacheRead: 1.00, cacheWrite: 12.50 },
221
+ 'claude-fable-5-1': { input: 10.00, output: 50.00, cacheRead: 0.25, cacheWrite: 12.50 },
222
+ // The Sonnet 4.x spellings keep their own line items now that `sonnet`
223
+ // above carries the 5-line price: without these, a Claude Sonnet 4.x turn —
224
+ // the id a config saved before this change still holds, and the wire model
225
+ // the dated form names — would family-match the alias row and be billed
226
+ // $2.00/$10.00 against the vendor's $3.00/$15.00.
227
+ 'claude-sonnet-4-6': { input: 3.00, output: 15.00, cacheRead: 0.30, cacheWrite: 3.75 },
228
+ 'claude-sonnet-4-5': { input: 3.00, output: 15.00, cacheRead: 0.30, cacheWrite: 3.75 },
229
+
163
230
  // DeepSeek — read off the vendor's own pricing table
164
231
  // (api-docs.deepseek.com/quick_start/pricing), not from a secondary blog and
165
232
  // not from a mirror of our own catalog.
@@ -609,14 +676,23 @@ function usageCost(usage, model, opts = {}) {
609
676
  * @param {object|null|undefined} usage the response's `usage` object
610
677
  * @param {string} model the model id that answered
611
678
  * @param {{costUsd?: number}} [opts] the server-settled charge, if any
612
- * @returns {{tokens: number|null, cost: number|null, real: boolean, estimated: boolean}}
679
+ * @returns {{tokens: number|null, output: number|null, cost: number|null,
680
+ * real: boolean, estimated: boolean}}
613
681
  * `real` is true only when `cost` is the settled charge. `cost` is
614
682
  * `null` when nothing was reported and no model was named — an
615
683
  * unpriced turn must render as nothing, never as $0.0000.
684
+ * `tokens` is the wire's TOTAL (input + output) and is what the ledger
685
+ * and the rolling fold need; `output` is the half a person reads, and
686
+ * it is what every per-turn surface shows (see `displayTokens`).
616
687
  */
617
688
  function turnAccounting(usage, model, opts = {}) {
618
689
  const tokens = usageTokens(usage);
619
690
  const u = usage && typeof usage === 'object' ? usage : {};
691
+ // The half the turn PRODUCED. Kept beside the total rather than replacing it:
692
+ // `tokens` still has to fold the ledger, and a rebuild from stored buckets
693
+ // must agree with the live fold to the unit.
694
+ const output =
695
+ usage && typeof usage === 'object' ? usageBuckets(usage).output : null;
620
696
  // The settled charge can arrive either on the response or folded into the
621
697
  // usage object — the upstream engine does the latter
622
698
  // (`{ ...result.usage, costUsd: result.costUsd }`), so both are accepted.
@@ -628,15 +704,23 @@ function turnAccounting(usage, model, opts = {}) {
628
704
  // because a settled charge is a fact and a table match is a guess — and the
629
705
  // pool's bill carries a margin and a prompt-cache discount this table
630
706
  // cannot see, so the two must never be averaged or confused.
631
- return { tokens, cost: settled, real: true, estimated: false, basis: 'settled', priced: true };
707
+ return {
708
+ tokens, output, cost: settled, real: true, estimated: false, basis: 'settled', priced: true,
709
+ };
710
+ }
711
+ if (tokens == null) {
712
+ return {
713
+ tokens, output, cost: null, real: false, estimated: false, basis: null, priced: false,
714
+ };
632
715
  }
633
- if (tokens == null) return { tokens, cost: null, real: false, estimated: false, basis: null, priced: false };
634
716
  const b = costBreakdown(u, model, opts);
635
717
  // A model the table cannot place still yields a number (ratesFor never
636
718
  // returns nothing), so this is always an estimate — but `priced: false` says
637
719
  // the figure is a placeholder rather than this model's rate, so the caller
638
720
  // can label it instead of printing it as though it had been measured.
639
- return { tokens, cost: b.cost, real: false, estimated: true, basis: b.basis, priced: b.priced };
721
+ return {
722
+ tokens, output, cost: b.cost, real: false, estimated: true, basis: b.basis, priced: b.priced,
723
+ };
640
724
  }
641
725
 
642
726
  /**
@@ -648,7 +732,7 @@ function turnAccounting(usage, model, opts = {}) {
648
732
  * — `tokens`, `inputTokens`, `outputTokens`, `calls` — and what the user reads
649
733
  * back is that RUNNING TOTAL. The status bar prints `state.tokens`
650
734
  * (renderStatus), and `ctrl+t` prints the tallies in one line
651
- * (`tokenSummary`: `12,400 tok (10,100 in / 2,300 out) · 4 calls · €0.03`).
735
+ * (`tokenSummary`: `12,400 tokens (10,100 in / 2,300 out) · 4 calls · €0.03`).
652
736
  * The tallies are reproduced; that one abbreviation is not — `fmtRoll` explains
653
737
  * why it drops the parenthetical rather than carrying the CLI's line verbatim.
654
738
  *
@@ -869,36 +953,104 @@ function fmtTokens(n) {
869
953
  .replace(/\B(?=(\d{3})+(?!\d))/g, ',');
870
954
  }
871
955
 
956
+ /**
957
+ * The token figure a person is SHOWN for a finished turn or a session roll.
958
+ *
959
+ * One authority, because there are two shapes that reach it and they had
960
+ * drifted apart: `turnAccounting` (a single dispatch, `{tokens, output}`) and
961
+ * `emptyRoll`/`rollTurn` (a session tally, same two fields). Every per-turn row
962
+ * and the topbar both route through here, so no surface can print a different
963
+ * quantity than another.
964
+ *
965
+ * What it returns is the OUTPUT — what the turn produced. The wire's total is
966
+ * input + output, and on any cached or long-context turn the input half
967
+ * dominates it: a 3,145-token call whose prompt was 3,000 tokens is a turn that
968
+ * wrote 145. Showing 3,145 beside a `session:` line that also reads 3,145 told
969
+ * the reader the model had emitted ten times what it did, and there is no way
970
+ * to tell from the row which of the two numbers is the prompt restated. The
971
+ * CLI settled this the same way (`fmtUsageSplit`, cli/src/format.js): the figure
972
+ * is the output, and the input half is not shown unlabelled beside it.
973
+ *
974
+ * It does NOT fall back to the total. Fall back to `tokens` and the input half
975
+ * is back on the screen with no label: a wire that priced a turn but did not
976
+ * itemise it would print `3,145` for a turn that wrote 145. Returns `null`
977
+ * rather than `0` in that case — `0 tokens` is a figure no provider sent,
978
+ * and this file refuses that fabrication everywhere else (`fmtRoll`).
979
+ *
980
+ * @param {{tokens?: number|null, output?: number|null}} [source]
981
+ * @returns {number|null}
982
+ */
983
+ function displayTokens(source) {
984
+ if (!source || typeof source !== 'object') return null;
985
+ // The half the turn PRODUCED, from either shape this file is handed: an
986
+ // accounting or roll record (`output`), or a stored token bucket
987
+ // (`tokens: {output}` — what `rollMessages` reads back out of the shared
988
+ // store, and what a rebuilt session presents).
989
+ const nested = source.tokens;
990
+ const candidates = [source.output];
991
+ if (nested && typeof nested === 'object') {
992
+ candidates.push(nested.output, nested.output_tokens, nested.completion_tokens);
993
+ } else {
994
+ candidates.push(source.output_tokens, source.completion_tokens);
995
+ }
996
+ for (const c of candidates) {
997
+ if (typeof c === 'number' && isFinite(c) && c > 0) return c;
998
+ }
999
+ // The wire's TOTAL is deliberately NOT a fallback here. `tokens` is
1000
+ // input + output, and on a cached turn the input half is the larger one, so
1001
+ // falling back to it put back the exact reading this rule exists to remove:
1002
+ // `tokens: 3,145` on a turn that wrote 145. This was the last surviving
1003
+ // place the input half reached the screen — the split had been dropped, and
1004
+ // the total it fell back to still carried it.
1005
+ //
1006
+ // Stated once more, because it is the whole point: a turn the wire priced but
1007
+ // did not itemise has NO output figure, and inventing one from the total
1008
+ // would be a number no provider sent. That turn's row states its own text
1009
+ // estimate instead (`~N tokens`), which is at least a figure about what was
1010
+ // written.
1011
+ return null;
1012
+ }
1013
+
872
1014
  /**
873
1015
  * The rolling session total as one line — the desktop's counterpart of the
874
1016
  * CLI's `tokenSummary`. Empty string when nothing has been accounted for, so
875
1017
  * an untouched session adds no noise to a turn's meta line.
876
1018
  *
877
1019
  * @param {object} [roll]
878
- * @returns {string} e.g. `12,400 tok · 4 calls · $0.0310` — the CLI's fields in
879
- * the CLI's order, minus the input/output parenthetical (see below).
1020
+ * @returns {string} e.g. `2,300 tokens · 4 calls · $0.0310` — the CLI's fields in
1021
+ * the CLI's order, minus the input/output parenthetical (see below). The
1022
+ * figure is the OUTPUT (see `displayTokens`).
880
1023
  */
881
- function fmtRoll(roll) {
1024
+ function fmtRoll(roll, opts = {}) {
882
1025
  const r = roll || emptyRoll();
883
1026
  if (!r.turns && !r.calls) return '';
884
1027
  // The fields are `tokenSummary`'s (cli/src/app.js:1413) in its order — tokens,
885
1028
  // calls, money — with one dropped: the `(10,100 in / 2,300 out)` split. `in`
886
1029
  // and `out` are a terminal status-line shorthand, legible to someone already
887
1030
  // reading that status line and to nobody else, which is what an unlabelled
888
- // abbreviation in a GUI topbar turns into. The total is the figure a reader
889
- // wants; `r.input`/`r.output` are still folded onto the roll (see `rollTurn`)
890
- // for any surface that wants to show the split with real labels. The call
891
- // count stays unconditional, because it is the number that reveals a
892
- // fan-out, and it is not hidden at 1.
1031
+ // abbreviation in a GUI topbar turns into.
1032
+ //
1033
+ // …and the figure that remains is the OUTPUT, not the wire's total. This line
1034
+ // used to print `r.tokens`, which is input + output: on a cached turn the
1035
+ // prompt restated is the larger half, so a session that wrote 2,300 tokens on
1036
+ // a 10,100-token prompt read `12,400 tokens` and looked like a model emitting
1037
+ // five times what it did. The parenthetical was not the only place the input
1038
+ // half showed up — it was in the total too, and dropping the split alone left
1039
+ // the reader comparing two numbers that were both mostly their own prompt.
1040
+ // `displayTokens` holds the rule, the same one the CLI's `fmtUsageSplit` uses.
1041
+ // `r.input` is still folded onto the roll (see `rollTurn`) for any surface
1042
+ // that wants to show the split with real labels.
893
1043
  const bits = [];
894
1044
  // The token half only when something was actually counted. `rollTurn` counts
895
1045
  // turns and calls BEFORE it looks at the token count, so a dispatch that
896
- // reported nothing still reaches here — and printing its empty tally would
897
- // put `0 tok` on the topbar, a figure the meter never took, which reads as a
898
- // counter that does not move. The turn count is still stated, because that
899
- // much is true.
900
- if (r.tokens > 0) {
901
- bits.push(`${fmtTokens(r.tokens)} tok`);
1046
+ // reported nothing still reaches here — and printing an empty tally would put
1047
+ // `0 tokens` on the topbar, a figure the meter never took, which reads as a
1048
+ // counter that does not move. `displayTokens` returns null rather than 0 for
1049
+ // exactly that case, and falls back to the total only when no split arrived.
1050
+ // The turn count is still stated, because that much is true.
1051
+ const produced = displayTokens(r);
1052
+ if (produced != null) {
1053
+ bits.push(`${fmtTokens(produced)} tokens`);
902
1054
  }
903
1055
  bits.push(`${r.calls} call${r.calls === 1 ? '' : 's'}`);
904
1056
  // Money is where this line departs from `tokenSummary`, deliberately: that
@@ -906,7 +1058,10 @@ function fmtRoll(roll) {
906
1058
  // a settled charge and a local estimate apart so a `~`-estimate can never be
907
1059
  // read as part of the bill. Desktop's pre-existing fmtCost renders both, and
908
1060
  // its `$` convention is left exactly as it was.
909
- if (r.cost > 0 || r.estimate > 0) {
1061
+ // Money is omitted entirely on a tier AEGIS does not bill a fee to
1062
+ // (`opts.omitMoney` — see `feeWaived`). Not zeroed, not marked `~`: a `$0.0000`
1063
+ // states a price, and this account has no price on this turn.
1064
+ if (!opts.omitMoney && (r.cost > 0 || r.estimate > 0)) {
910
1065
  const money = [];
911
1066
  if (r.cost > 0) money.push(fmtCost(r.cost, true));
912
1067
  if (r.estimate > 0) money.push(fmtCost(r.estimate, false));
@@ -935,11 +1090,108 @@ function fmtRoll(roll) {
935
1090
  */
936
1091
  function fmtCost(cost, real) {
937
1092
  if (typeof cost !== 'number' || !isFinite(cost)) return '';
1093
+ // The `$` is not decoration: its loss was a regression, not a decision.
1094
+ // `4d5d1e9` introduced this function with it (`~$18.0000`); `6d48470` — a
1095
+ // commit about the token TOTAL, unrelated to money — dropped it as a stray
1096
+ // hunk. Every desktop turn row then painted a bare `18.0000`, a number with no
1097
+ // currency on it, where the CLI paints `€0.03` for the same figure.
938
1098
  return `${real ? '' : '~'}$${cost.toFixed(4)}`;
939
1099
  }
940
1100
 
1101
+ /**
1102
+ * True when this account's tier means AEGIS bills no per-turn fee, so no money
1103
+ * figure belongs on a turn row or a session roll.
1104
+ *
1105
+ * The fee in question is the BYOK handling fee — the only charge AEGIS adds on
1106
+ * top of a caller's own provider bill — and aegis1 waives it on Unlimited:
1107
+ * `lib/local/entitlement.js` states the rule in as many words ("the throughput
1108
+ * allowance and the BYOK fee waiver are `is_unlimited()`-gated"), and the tier
1109
+ * a welcome trial grants IS Unlimited (a 30-day `unlimited` row in
1110
+ * `subscriptions`, which `register_device` writes in the same request that mints
1111
+ * the key). So a trial account resolves here exactly like a paying one, which is
1112
+ * what "trial unlimited" means — the trial is not a separate tier with its own
1113
+ * money rule, it is Unlimited for 30 days.
1114
+ *
1115
+ * Matching is on the resolved tier rather than `pro`: `pro` is "the PLAN is paid
1116
+ * for" and is also true of the €9 tier's aliases, while the waiver is gated on
1117
+ * `unlimited` specifically. A funded bank on a free plan is not a tier at all
1118
+ * (`entitlement.js` refuses to name one) and is therefore NOT waived — that
1119
+ * account pays the fee from the bank, and hiding the number would leave it with
1120
+ * no meter for the only money it spends.
1121
+ *
1122
+ * @param {{tier?: string|null, plan?: string|null, planRaw?: string|null}} [entitlement]
1123
+ * @returns {boolean}
1124
+ */
1125
+ function feeWaived(entitlement) {
1126
+ if (!entitlement || typeof entitlement !== 'object') return false;
1127
+ const named = [
1128
+ entitlement.tier,
1129
+ entitlement.plan,
1130
+ entitlement.planRaw,
1131
+ entitlement.subscription,
1132
+ entitlement.subscriptionTier,
1133
+ entitlement.product,
1134
+ // The server's own two fields, as `register_device` writes them: a welcome
1135
+ // trial is a 30-day `unlimited` row in `subscriptions`, and `item`/`sku` is
1136
+ // that row's product name. Naming them here is what keeps a trial account
1137
+ // from resolving to "no tier" and being billed a fee it does not owe.
1138
+ entitlement.item,
1139
+ entitlement.sku,
1140
+ ]
1141
+ .filter((v) => typeof v === 'string')
1142
+ .map((v) => v.trim().toLowerCase());
1143
+ // An explicit boolean outranks every spelling below: aegis1's `is_unlimited()`
1144
+ // verdict is the fact, and the strings are only what it is written as on the
1145
+ // wire. A probe that answers with the bit and not the tier is still an answer.
1146
+ if (entitlement.unlimited === true) return true;
1147
+ if (named.some((v) => v === 'unlimited' || v === 'trial')) return true;
1148
+ // A tier string that merely CONTAINS the word — `unlimited_trial`,
1149
+ // `plan.unlimited`, `Unlimited (trial)` — so a server that decorates the name
1150
+ // cannot put the fee back on an account whose tier is Unlimited.
1151
+ return named.some((v) => /(^|[^a-z])unlimited([^a-z]|$)/.test(v));
1152
+ }
1153
+
1154
+ /**
1155
+ * Whether a money figure belongs on this account's turn row or session roll.
1156
+ *
1157
+ * The CLI's exact rule (`cli/src/format.js` → `feeBillable`), and it is the same
1158
+ * rule on purpose — the two hosts render the same turn from the same engine, so
1159
+ * a row that shows a fee on one and waives it on the other is a disagreement
1160
+ * about what the user owes.
1161
+ *
1162
+ * A price is printed UNLESS AEGIS either waives it or has not proven it owed:
1163
+ *
1164
+ * - a tier AEGIS waives (`feeWaived`) → no price. Unlimited, paid or on the
1165
+ * 30-day welcome trial, has no per-turn charge and no bank draw;
1166
+ * - a snapshot asserting a plan it cannot prove (`degraded`) → no price. The
1167
+ * entitlement module STARTS at exactly that: `makeFreeSnapshot()` reads
1168
+ * `plan: 'free'`, `tier: null`, `source: 'unresolved'`, `degraded: true`,
1169
+ * which says "no verdict yet", not "this account is free". Reading the
1170
+ * placeholder as a verdict is what put `~$0.0005` and an "AEGIS handling fee"
1171
+ * line on the turns of trial accounts whose probe had not answered — a fee
1172
+ * charged in writing to the one account that does not pay it;
1173
+ * - everything else → the price stands, including when no snapshot exists at
1174
+ * all. A cost figure is a measurement of the turn, and dropping a real number
1175
+ * because no tier was published would leave a self-hosted or BYO-key run with
1176
+ * no meter for money it actually spent.
1177
+ *
1178
+ * The token figure is never gated by this, on any branch: what a turn produced
1179
+ * is not a price, and hiding it would leave an Unlimited account with no meter.
1180
+ *
1181
+ * @param {{tier?: string|null, plan?: string|null, planRaw?: string|null,
1182
+ * degraded?: boolean, source?: string|null, unlimited?: boolean}} [entitlement]
1183
+ * @returns {boolean}
1184
+ */
1185
+ function feeBillable(entitlement) {
1186
+ if (!entitlement || typeof entitlement !== 'object') return true;
1187
+ if (feeWaived(entitlement)) return false;
1188
+ return entitlement.degraded !== true;
1189
+ }
1190
+
941
1191
  if (typeof module !== 'undefined' && module.exports) {
942
1192
  module.exports = {
1193
+ feeWaived,
1194
+ feeBillable,
943
1195
  RATES,
944
1196
  RATE_BASIS,
945
1197
  UNPRICED_BY_DESIGN,
@@ -951,6 +1203,7 @@ if (typeof module !== 'undefined' && module.exports) {
951
1203
  usageCost,
952
1204
  costBreakdown,
953
1205
  turnAccounting,
1206
+ displayTokens,
954
1207
  estimateTokens,
955
1208
  estimatedBuckets,
956
1209
  emptyRoll,
@@ -159,7 +159,7 @@ function createTools(client) {
159
159
  const kind = l.kind === 'topup' ? 'top-up' : (l.kind || '');
160
160
  const model = l.model_key || kind || '';
161
161
  const tokens = (l.tokens_in || l.tokens_out)
162
- ? ` ${l.tokens_in || 0}/${l.tokens_out || 0} tok`
162
+ ? ` ${l.tokens_in || 0}/${l.tokens_out || 0} tokens`
163
163
  : '';
164
164
  lines.push(` ${l.created_at || ''} ${model}${tokens} ${amount}`);
165
165
  }
@@ -101,6 +101,17 @@ the models that key unlocks appear as their own entries, one per provider.
101
101
  startup, and a provider with no key saved in Settings is resolved from it.
102
102
  3. Select the **Bring your own key** class and pick a model.
103
103
 
104
+ **A model the catalogue does not name yet.** Vendors ship models faster than any
105
+ client release, and the relay forwards whatever model string it is handed — so
106
+ Settings ends with an **Add model** row (provider + model id + *Add model*). It
107
+ writes the same `~/.aegiscode/models.json` the CLI's `/model-add` writes, so a
108
+ model added here appears in the terminal's `/models` immediately and one added
109
+ there appears in this picker on its next refresh; the row prints the file path,
110
+ which is also the bulk-edit path. The provider id is offered from the live
111
+ catalogue but you may type one, and a provider the relay takes no key for is
112
+ refused rather than stored (a declaration nothing can attach a key to would show
113
+ up in no picker at all). Each declared model gets a **Remove** row.
114
+
104
115
  **What it costs.** AEGIS pays your provider nothing on this lane, so there is no
105
116
  provider cost to take a margin on — instead your AEGIS account is charged a flat
106
117
  **handling fee** per 1k tokens, for the routing, prompt assembly, caching, tool
@@ -14,6 +14,36 @@
14
14
  const PROTOCOL = 'aegis';
15
15
  const SCHEME_PREFIX = `${PROTOCOL}://`;
16
16
 
17
+ /**
18
+ * Ceilings on the two values a *remote* caller controls.
19
+ *
20
+ * Any web page or any other app on the machine can hand the OS an `aegis://`
21
+ * URL, so both fields are attacker-chosen input on a channel nobody authenticates
22
+ * (there is no "is this link from the user?" check, and there cannot be one for
23
+ * a custom scheme). Bounding them keeps a hostile link from parking megabytes of
24
+ * text in the composer, from filling the window with a wall of pre-filled prompt,
25
+ * or from using the deep link as a bulk data channel into a session that can run
26
+ * tools. The renderer pre-fills rather than auto-sends (renderer/app.js
27
+ * handleDeepLink), so the cost is bounded, but a pre-filled prompt is still the
28
+ * most direct route from "a page I visited" to "text the user is invited to send
29
+ * to a model with tools on".
30
+ *
31
+ * These are generous on purpose: a real hand-written link is a sentence or two.
32
+ */
33
+ const MAX_PROMPT_LENGTH = 2000;
34
+ /** Session ids are uuids (36 chars); the slack is for a future format, not a payload. */
35
+ const MAX_SESSION_ID_LENGTH = 128;
36
+ /**
37
+ * …and the charset is pinned too, because this id does not stay a string: the
38
+ * renderer's `open` handler hands it to openSession(), which loads the session
39
+ * by name. A hostile link could otherwise offer `../../…` or an absolute path
40
+ * and have the *renderer* ask main to open whatever that resolves to. Ids this
41
+ * app mints are `[0-9a-f-]`; anything outside a conservative id alphabet is not
42
+ * one of ours, so it is rejected rather than escaped or repaired.
43
+ */
44
+ const SESSION_ID_PATTERN = /^[A-Za-z0-9_-]{1,128}$/;
45
+
46
+
17
47
  /** True for any string that looks like our protocol, cheap enough to filter
18
48
  * argv with before the full URL parse (which throws on most argv entries —
19
49
  * flags, file paths — so callers should not run it against every arg). */
@@ -44,11 +74,15 @@ function parseDeepLinkUrl(url) {
44
74
  if (action === 'open') {
45
75
  const sessionId = parsed.searchParams.get('session');
46
76
  if (!sessionId) return null;
77
+ if (sessionId.length > MAX_SESSION_ID_LENGTH) return null;
78
+ if (!SESSION_ID_PATTERN.test(sessionId)) return null;
47
79
  return { action: 'open', sessionId };
48
80
  }
49
81
 
50
82
  if (action === 'new') {
51
- return { action: 'new', prompt: parsed.searchParams.get('prompt') || '' };
83
+ const prompt = parsed.searchParams.get('prompt') || '';
84
+ if (prompt.length > MAX_PROMPT_LENGTH) return null;
85
+ return { action: 'new', prompt };
52
86
  }
53
87
 
54
88
  return null;
@@ -73,6 +73,83 @@ const MAX_ROUND_STOPS = 3;
73
73
  */
74
74
  const WRITE_TOOLS = new Set(['writeFile', 'editFile']);
75
75
 
76
+ // ── Auto mode and the round horizon ─────────────────────────────────────────
77
+ //
78
+ // The two halves of "auto mode" the upstream engine (aegiscodex-dev) defines
79
+ // are independent, and a host that wires only one of them is *not* running auto
80
+ // mode — it is running "no approval cards", which is half the feature and all
81
+ // the friction:
82
+ //
83
+ // 1. no approval keystroke per mutating tool call;
84
+ // 2. a turn that hits its round horizon is EXTENDED silently a few times
85
+ // before a human is asked.
86
+ //
87
+ // (1) is the posture (the desktop's Tool-approvals switch, the CLI's
88
+ // /automode); (2) needs the arithmetic below, and the plugin's Electron host
89
+ // had none of it — with auto mode ON, every horizon hit still raised the
90
+ // blocking round card, which is precisely the question auto mode exists to stop
91
+ // asking ("12 rounds — keep going?" answered the same way every time).
92
+ //
93
+ // Ported verbatim from the engine's src/autonomous.js (DEFAULT_AUTO_CONTINUES,
94
+ // autoContinueLimit, autoRoundsDefault, autoContinuePlan) rather than vendored,
95
+ // because this repo hosts no build of that ESM module — but with the SAME
96
+ // numbers and the SAME env knobs, so a turn behaves identically in either
97
+ // client. cli/src/chatflow.js carries the third copy, which is what the CLI
98
+ // presenter uses to answer the ask.
99
+
100
+ /** Automatic continuations an attended turn may take while auto mode is on. */
101
+ const DEFAULT_AUTO_CONTINUES = 3;
102
+
103
+ /**
104
+ * The auto-continue allowance, honouring AEGIS_AUTO_CONTINUE_MAX.
105
+ *
106
+ * Bounded and pure, and a garbage value falls back to the default rather than
107
+ * to 0: an unparseable env var must not silently switch auto mode off, because
108
+ * the visible symptom of that ("why is it asking me again?") points nowhere
109
+ * near the environment.
110
+ */
111
+ function autoContinueLimit(env = process.env) {
112
+ const n = Number.parseInt(env && env.AEGIS_AUTO_CONTINUE_MAX, 10);
113
+ return Number.isFinite(n) && n > 0 ? n : DEFAULT_AUTO_CONTINUES;
114
+ }
115
+
116
+ /**
117
+ * Values of AEGIS_AUTO_ROUNDS that mean "start in manual mode". Anything else —
118
+ * unset, empty, a typo like `flase` — leaves auto mode's default in place, so a
119
+ * misspelt opt-out cannot silently disable the mode the operator asked for.
120
+ * Same set, same reasoning, as the engine's AUTO_ROUNDS_OFF.
121
+ */
122
+ const AUTO_ROUNDS_OFF = new Set(['0', 'false', 'off', 'no']);
123
+
124
+ /** False only when AEGIS_AUTO_ROUNDS explicitly says so. */
125
+ function autoRoundsDefault(env = process.env) {
126
+ const raw = env && env.AEGIS_AUTO_ROUNDS;
127
+ if (raw === undefined || raw === null) return true;
128
+ const val = String(raw).trim().toLowerCase();
129
+ if (!val) return true;
130
+ return !AUTO_ROUNDS_OFF.has(val);
131
+ }
132
+
133
+ /**
134
+ * Decide what one round-horizon ask becomes while auto mode is on.
135
+ *
136
+ * Pure, because this is budget arithmetic on a keystroke-less path: the caller
137
+ * only renders the answer and must not be trusted to keep the count. `used` is
138
+ * the running tally the caller holds and echoes back, so an ask that IS shown
139
+ * to the human resets it — the human was asked, so the next block of automatic
140
+ * continuations starts clean.
141
+ *
142
+ * { auto: true, used: n } → answer the ask "yes" without a dialog
143
+ * { auto: false, used: n } → show the real ask (allowance spent, or off)
144
+ */
145
+ function autoContinuePlan({ on = false, used = 0, limit = DEFAULT_AUTO_CONTINUES } = {}) {
146
+ const cap = Number.isFinite(limit) && limit > 0 ? Math.floor(limit) : DEFAULT_AUTO_CONTINUES;
147
+ const spent = Number.isFinite(used) && used > 0 ? Math.floor(used) : 0;
148
+ if (!on) return { auto: false, used: spent, cap };
149
+ if (spent >= cap) return { auto: false, used: 0, cap };
150
+ return { auto: true, used: spent + 1, cap };
151
+ }
152
+
76
153
  /** The path a file-writing tool call names, in either spelling the engine uses. */
77
154
  function writtenPath(tool) {
78
155
  const args = (tool && tool.args) || {};
@@ -906,6 +983,10 @@ module.exports = {
906
983
  isAutonomousRequest,
907
984
  maxRounds,
908
985
  withRoundHorizon,
986
+ DEFAULT_AUTO_CONTINUES,
987
+ autoContinueLimit,
988
+ autoRoundsDefault,
989
+ autoContinuePlan,
909
990
  resolveModel,
910
991
  ignoredEnvModel,
911
992
  resolveEffort,