aegiscode 6.8.35 → 6.8.37

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.
@@ -797,6 +797,7 @@ function createLocalEngine({
797
797
  // remembering "no" makes the first answer stick.
798
798
  const sessionDenials = new Map(); // rootSessionId -> Set<toolName>
799
799
  const pendingApprovals = new Map(); // approvalId -> { resolve }
800
+ const pendingRoundAsks = new Map(); // askId -> { resolve }
800
801
 
801
802
  function sessionAllows(rootId, name) {
802
803
  const set = sessionAllowlists.get(rootId);
@@ -911,6 +912,62 @@ function createLocalEngine({
911
912
  });
912
913
  }
913
914
 
915
+ /** The renderer's rounds-dialog answer resolves the pending
916
+ * requestRoundsAsk() promise below. An unknown/already-answered id is a
917
+ * no-op, same contract as respondApproval. */
918
+ function respondRoundsAsk(askId, decision) {
919
+ const pending = pendingRoundAsks.get(askId);
920
+ if (!pending) return { ok: false };
921
+ pendingRoundAsks.delete(askId);
922
+ pending.resolve(decision === true || decision === 'continue');
923
+ return { ok: true };
924
+ }
925
+
926
+ /**
927
+ * Ask the renderer whether to fund another block of tool rounds, mirroring
928
+ * requestApproval's shape exactly: pushed over `rootOnDelta` as a `{ rounds }`
929
+ * chunk (the one channel a detached renderer has into a running turn) and
930
+ * resolved externally via `respondRoundsAsk`. Resolves `true` (fund one more
931
+ * block) or `false` (stop here) — never throws. Fails safe to `false`: no
932
+ * listener, an aborted turn, or an unanswered ask must not keep the loop
933
+ * waiting forever (or, worse, spend rounds nobody agreed to).
934
+ */
935
+ function requestRoundsAsk(rootSessionId, rootOnDelta, signal, info) {
936
+ return new Promise((resolve) => {
937
+ if (signal && signal.aborted) {
938
+ resolve(false);
939
+ return;
940
+ }
941
+ const id = randomUUID();
942
+ let settled = false;
943
+ const onAbort = () => finish(false);
944
+ const finish = (decision) => {
945
+ if (settled) return;
946
+ settled = true;
947
+ pendingRoundAsks.delete(id);
948
+ if (signal) signal.removeEventListener('abort', onAbort);
949
+ resolve(decision);
950
+ };
951
+ if (signal) signal.addEventListener('abort', onAbort, { once: true });
952
+ pendingRoundAsks.set(id, { resolve: finish });
953
+ if (typeof rootOnDelta !== 'function') {
954
+ finish(false);
955
+ return;
956
+ }
957
+ rootOnDelta({
958
+ delta: '',
959
+ rounds: {
960
+ id,
961
+ sessionId: rootSessionId,
962
+ spent: info.spent,
963
+ extensions: info.extensions,
964
+ max: info.max,
965
+ size: info.size,
966
+ },
967
+ });
968
+ });
969
+ }
970
+
914
971
  /**
915
972
  * The gate itself: read-only tools and already-session-allowed mutating
916
973
  * tools run exactly like executeTool always did. A first-time mutating
@@ -1522,6 +1579,12 @@ function createLocalEngine({
1522
1579
  // synthesis pass) instead of a single provider call. UI-gated to the
1523
1580
  // 'aegis' class only (see AUTONOMOUS_CLASS in app.js).
1524
1581
  const autonomous = cls === 'aegis' && Boolean(payload && payload.autonomous);
1582
+ // Opt-in only: the round-horizon dialog (requestRoundsAsk below) needs a
1583
+ // live renderer on the other end of `rootOnDelta` able to answer it. The
1584
+ // interactive CLI session sets this; the queue worker and `-p` one-shot
1585
+ // runs never do (nobody is there to click), so they keep the old
1586
+ // stop-and-record-session behaviour (sessionRounds below) untouched.
1587
+ const roundsAsk = Boolean(payload && payload.roundsAsk);
1525
1588
  const sessionId = (payload && payload.sessionId) || randomUUID();
1526
1589
  // Recursion depth for the task tool: 0 for a real user turn, N+1 for a
1527
1590
  // subagent spawned by depth N. Never set by an IPC caller — only by
@@ -1797,8 +1860,17 @@ function createLocalEngine({
1797
1860
  }
1798
1861
  // A resumed turn gets a small bonus on top of the base horizon so
1799
1862
  // re-orientation does not consume the new budget before any work lands.
1800
- const maxRounds = statedRounds || baseRounds + (resumed ? sessionRounds.bonus(baseRounds) : 0);
1863
+ let maxRounds = statedRounds || baseRounds + (resumed ? sessionRounds.bonus(baseRounds) : 0);
1801
1864
  let round = 0;
1865
+ // Rounds bought by one confirmed extension, and a hard cap on how many
1866
+ // extensions a single turn may spend — matching the upstream engine's
1867
+ // numbers (src/autonomous.js ROUND_EXTENSION_SIZE/MAX_ROUND_EXTENSIONS)
1868
+ // so a turn behaves the same whether it runs there or here. The cap
1869
+ // exists even though the renderer is the one asking: a dialog that
1870
+ // always says yes must still terminate (8 x baseRounds extra rounds).
1871
+ const ROUND_EXTENSION_SIZE = baseRounds;
1872
+ const MAX_ROUND_EXTENSIONS = 8;
1873
+ let extensions = 0;
1802
1874
 
1803
1875
  // Token accounting for the whole TURN, not just its last round. An
1804
1876
  // agentic turn makes one provider call per tool round, and returning only
@@ -1858,11 +1930,49 @@ function createLocalEngine({
1858
1930
  // which is the same "(empty response)" failure the guards below exist
1859
1931
  // to prevent.
1860
1932
  if (round >= maxRounds) {
1933
+ // Before conceding, give an interactive caller the chance to fund
1934
+ // another block of rounds instead of ending the turn outright — the
1935
+ // upstream engine's "asks" contract (src/backend.js requestExtension).
1936
+ // Only reachable with `roundsAsk` AND a live signal: a caller with no
1937
+ // renderer on the other end (queue, `-p`) falls straight through to
1938
+ // the session-hold stop below, unchanged.
1939
+ if (roundsAsk && extensions < MAX_ROUND_EXTENSIONS && !signal.aborted) {
1940
+ const granted = await requestRoundsAsk(rootSessionId, rootOnDelta, signal, {
1941
+ spent: maxRounds,
1942
+ extensions: extensions + 1,
1943
+ max: MAX_ROUND_EXTENSIONS,
1944
+ size: ROUND_EXTENSION_SIZE,
1945
+ });
1946
+ if (granted) {
1947
+ extensions += 1;
1948
+ const spent = maxRounds;
1949
+ maxRounds += ROUND_EXTENSION_SIZE;
1950
+ history.push({
1951
+ role: 'user',
1952
+ content: `You have used all ${spent} tool rounds allowed for this turn; ` +
1953
+ `${ROUND_EXTENSION_SIZE} more have been granted (do not restart). Continue the task ` +
1954
+ 'from exactly where you stopped — do not re-plan, do not repeat work already done, ' +
1955
+ 'and finish with an answer.',
1956
+ });
1957
+ continue;
1958
+ }
1959
+ // Declined (or the extension cap is spent): fall through to the
1960
+ // same session-hold stop a non-interactive caller gets, so a "no"
1961
+ // here is bit-for-bit the old hard stop rather than a dead end.
1962
+ }
1963
+ // The knob is only advice where nobody could have been asked about
1964
+ // it. An interactive caller was already offered another block of
1965
+ // rounds (requestRoundsAsk above) and declined or spent the cap, so
1966
+ // pointing it at an env var it cannot set from inside the app — and
1967
+ // would have to restart to apply — is obsolete text: drop it. The
1968
+ // queue worker and `-p` one-shots have no dialog, so for them the
1969
+ // variable remains the only lever and is still named.
1970
+ const knob = roundsAsk ? '' : `, or raise ${roundEnvName} for a longer single turn`;
1861
1971
  const note =
1862
1972
  `[stopped at ${maxRounds} tool rounds` +
1863
1973
  `${turnUsage.total_tokens ? `, ${turnUsage.total_tokens.toLocaleString()} tokens` : ''}` +
1864
1974
  `. This session holds the work: your next message here resumes it automatically` +
1865
- ` (with a continuation preamble), or raise ${roundEnvName} for a longer single turn.]`;
1975
+ ` (with a continuation preamble)${knob}.]`;
1866
1976
  // File the interruption before returning, so the horizon is a pause
1867
1977
  // in the session rather than the end of the job. `chain` carries the
1868
1978
  // count forward across resumes.
@@ -2146,6 +2256,7 @@ function createLocalEngine({
2146
2256
  chat,
2147
2257
  cancel,
2148
2258
  respondApproval,
2259
+ respondRoundsAsk,
2149
2260
  clearSessionApprovals,
2150
2261
  settings,
2151
2262
  unloadLocalModels,
@@ -609,14 +609,23 @@ function usageCost(usage, model, opts = {}) {
609
609
  * @param {object|null|undefined} usage the response's `usage` object
610
610
  * @param {string} model the model id that answered
611
611
  * @param {{costUsd?: number}} [opts] the server-settled charge, if any
612
- * @returns {{tokens: number|null, cost: number|null, real: boolean, estimated: boolean}}
612
+ * @returns {{tokens: number|null, output: number|null, cost: number|null,
613
+ * real: boolean, estimated: boolean}}
613
614
  * `real` is true only when `cost` is the settled charge. `cost` is
614
615
  * `null` when nothing was reported and no model was named — an
615
616
  * unpriced turn must render as nothing, never as $0.0000.
617
+ * `tokens` is the wire's TOTAL (input + output) and is what the ledger
618
+ * and the rolling fold need; `output` is the half a person reads, and
619
+ * it is what every per-turn surface shows (see `displayTokens`).
616
620
  */
617
621
  function turnAccounting(usage, model, opts = {}) {
618
622
  const tokens = usageTokens(usage);
619
623
  const u = usage && typeof usage === 'object' ? usage : {};
624
+ // The half the turn PRODUCED. Kept beside the total rather than replacing it:
625
+ // `tokens` still has to fold the ledger, and a rebuild from stored buckets
626
+ // must agree with the live fold to the unit.
627
+ const output =
628
+ usage && typeof usage === 'object' ? usageBuckets(usage).output : null;
620
629
  // The settled charge can arrive either on the response or folded into the
621
630
  // usage object — the upstream engine does the latter
622
631
  // (`{ ...result.usage, costUsd: result.costUsd }`), so both are accepted.
@@ -628,15 +637,23 @@ function turnAccounting(usage, model, opts = {}) {
628
637
  // because a settled charge is a fact and a table match is a guess — and the
629
638
  // pool's bill carries a margin and a prompt-cache discount this table
630
639
  // cannot see, so the two must never be averaged or confused.
631
- return { tokens, cost: settled, real: true, estimated: false, basis: 'settled', priced: true };
640
+ return {
641
+ tokens, output, cost: settled, real: true, estimated: false, basis: 'settled', priced: true,
642
+ };
643
+ }
644
+ if (tokens == null) {
645
+ return {
646
+ tokens, output, cost: null, real: false, estimated: false, basis: null, priced: false,
647
+ };
632
648
  }
633
- if (tokens == null) return { tokens, cost: null, real: false, estimated: false, basis: null, priced: false };
634
649
  const b = costBreakdown(u, model, opts);
635
650
  // A model the table cannot place still yields a number (ratesFor never
636
651
  // returns nothing), so this is always an estimate — but `priced: false` says
637
652
  // the figure is a placeholder rather than this model's rate, so the caller
638
653
  // 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 };
654
+ return {
655
+ tokens, output, cost: b.cost, real: false, estimated: true, basis: b.basis, priced: b.priced,
656
+ };
640
657
  }
641
658
 
642
659
  /**
@@ -648,7 +665,7 @@ function turnAccounting(usage, model, opts = {}) {
648
665
  * — `tokens`, `inputTokens`, `outputTokens`, `calls` — and what the user reads
649
666
  * back is that RUNNING TOTAL. The status bar prints `state.tokens`
650
667
  * (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`).
668
+ * (`tokenSummary`: `12,400 tokens (10,100 in / 2,300 out) · 4 calls · €0.03`).
652
669
  * The tallies are reproduced; that one abbreviation is not — `fmtRoll` explains
653
670
  * why it drops the parenthetical rather than carrying the CLI's line verbatim.
654
671
  *
@@ -869,36 +886,104 @@ function fmtTokens(n) {
869
886
  .replace(/\B(?=(\d{3})+(?!\d))/g, ',');
870
887
  }
871
888
 
889
+ /**
890
+ * The token figure a person is SHOWN for a finished turn or a session roll.
891
+ *
892
+ * One authority, because there are two shapes that reach it and they had
893
+ * drifted apart: `turnAccounting` (a single dispatch, `{tokens, output}`) and
894
+ * `emptyRoll`/`rollTurn` (a session tally, same two fields). Every per-turn row
895
+ * and the topbar both route through here, so no surface can print a different
896
+ * quantity than another.
897
+ *
898
+ * What it returns is the OUTPUT — what the turn produced. The wire's total is
899
+ * input + output, and on any cached or long-context turn the input half
900
+ * dominates it: a 3,145-token call whose prompt was 3,000 tokens is a turn that
901
+ * wrote 145. Showing 3,145 beside a `session:` line that also reads 3,145 told
902
+ * the reader the model had emitted ten times what it did, and there is no way
903
+ * to tell from the row which of the two numbers is the prompt restated. The
904
+ * CLI settled this the same way (`fmtUsageSplit`, cli/src/format.js): the figure
905
+ * is the output, and the input half is not shown unlabelled beside it.
906
+ *
907
+ * It does NOT fall back to the total. Fall back to `tokens` and the input half
908
+ * is back on the screen with no label: a wire that priced a turn but did not
909
+ * itemise it would print `3,145` for a turn that wrote 145. Returns `null`
910
+ * rather than `0` in that case — `0 tokens` is a figure no provider sent,
911
+ * and this file refuses that fabrication everywhere else (`fmtRoll`).
912
+ *
913
+ * @param {{tokens?: number|null, output?: number|null}} [source]
914
+ * @returns {number|null}
915
+ */
916
+ function displayTokens(source) {
917
+ if (!source || typeof source !== 'object') return null;
918
+ // The half the turn PRODUCED, from either shape this file is handed: an
919
+ // accounting or roll record (`output`), or a stored token bucket
920
+ // (`tokens: {output}` — what `rollMessages` reads back out of the shared
921
+ // store, and what a rebuilt session presents).
922
+ const nested = source.tokens;
923
+ const candidates = [source.output];
924
+ if (nested && typeof nested === 'object') {
925
+ candidates.push(nested.output, nested.output_tokens, nested.completion_tokens);
926
+ } else {
927
+ candidates.push(source.output_tokens, source.completion_tokens);
928
+ }
929
+ for (const c of candidates) {
930
+ if (typeof c === 'number' && isFinite(c) && c > 0) return c;
931
+ }
932
+ // The wire's TOTAL is deliberately NOT a fallback here. `tokens` is
933
+ // input + output, and on a cached turn the input half is the larger one, so
934
+ // falling back to it put back the exact reading this rule exists to remove:
935
+ // `tokens: 3,145` on a turn that wrote 145. This was the last surviving
936
+ // place the input half reached the screen — the split had been dropped, and
937
+ // the total it fell back to still carried it.
938
+ //
939
+ // Stated once more, because it is the whole point: a turn the wire priced but
940
+ // did not itemise has NO output figure, and inventing one from the total
941
+ // would be a number no provider sent. That turn's row states its own text
942
+ // estimate instead (`~N tokens`), which is at least a figure about what was
943
+ // written.
944
+ return null;
945
+ }
946
+
872
947
  /**
873
948
  * The rolling session total as one line — the desktop's counterpart of the
874
949
  * CLI's `tokenSummary`. Empty string when nothing has been accounted for, so
875
950
  * an untouched session adds no noise to a turn's meta line.
876
951
  *
877
952
  * @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).
953
+ * @returns {string} e.g. `2,300 tokens · 4 calls · $0.0310` — the CLI's fields in
954
+ * the CLI's order, minus the input/output parenthetical (see below). The
955
+ * figure is the OUTPUT (see `displayTokens`).
880
956
  */
881
- function fmtRoll(roll) {
957
+ function fmtRoll(roll, opts = {}) {
882
958
  const r = roll || emptyRoll();
883
959
  if (!r.turns && !r.calls) return '';
884
960
  // The fields are `tokenSummary`'s (cli/src/app.js:1413) in its order — tokens,
885
961
  // calls, money — with one dropped: the `(10,100 in / 2,300 out)` split. `in`
886
962
  // and `out` are a terminal status-line shorthand, legible to someone already
887
963
  // 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.
964
+ // abbreviation in a GUI topbar turns into.
965
+ //
966
+ // …and the figure that remains is the OUTPUT, not the wire's total. This line
967
+ // used to print `r.tokens`, which is input + output: on a cached turn the
968
+ // prompt restated is the larger half, so a session that wrote 2,300 tokens on
969
+ // a 10,100-token prompt read `12,400 tokens` and looked like a model emitting
970
+ // five times what it did. The parenthetical was not the only place the input
971
+ // half showed up — it was in the total too, and dropping the split alone left
972
+ // the reader comparing two numbers that were both mostly their own prompt.
973
+ // `displayTokens` holds the rule, the same one the CLI's `fmtUsageSplit` uses.
974
+ // `r.input` is still folded onto the roll (see `rollTurn`) for any surface
975
+ // that wants to show the split with real labels.
893
976
  const bits = [];
894
977
  // The token half only when something was actually counted. `rollTurn` counts
895
978
  // 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`);
979
+ // reported nothing still reaches here — and printing an empty tally would put
980
+ // `0 tokens` on the topbar, a figure the meter never took, which reads as a
981
+ // counter that does not move. `displayTokens` returns null rather than 0 for
982
+ // exactly that case, and falls back to the total only when no split arrived.
983
+ // The turn count is still stated, because that much is true.
984
+ const produced = displayTokens(r);
985
+ if (produced != null) {
986
+ bits.push(`${fmtTokens(produced)} tokens`);
902
987
  }
903
988
  bits.push(`${r.calls} call${r.calls === 1 ? '' : 's'}`);
904
989
  // Money is where this line departs from `tokenSummary`, deliberately: that
@@ -906,7 +991,10 @@ function fmtRoll(roll) {
906
991
  // a settled charge and a local estimate apart so a `~`-estimate can never be
907
992
  // read as part of the bill. Desktop's pre-existing fmtCost renders both, and
908
993
  // its `$` convention is left exactly as it was.
909
- if (r.cost > 0 || r.estimate > 0) {
994
+ // Money is omitted entirely on a tier AEGIS does not bill a fee to
995
+ // (`opts.omitMoney` — see `feeWaived`). Not zeroed, not marked `~`: a `$0.0000`
996
+ // states a price, and this account has no price on this turn.
997
+ if (!opts.omitMoney && (r.cost > 0 || r.estimate > 0)) {
910
998
  const money = [];
911
999
  if (r.cost > 0) money.push(fmtCost(r.cost, true));
912
1000
  if (r.estimate > 0) money.push(fmtCost(r.estimate, false));
@@ -935,11 +1023,108 @@ function fmtRoll(roll) {
935
1023
  */
936
1024
  function fmtCost(cost, real) {
937
1025
  if (typeof cost !== 'number' || !isFinite(cost)) return '';
1026
+ // The `$` is not decoration: its loss was a regression, not a decision.
1027
+ // `4d5d1e9` introduced this function with it (`~$18.0000`); `6d48470` — a
1028
+ // commit about the token TOTAL, unrelated to money — dropped it as a stray
1029
+ // hunk. Every desktop turn row then painted a bare `18.0000`, a number with no
1030
+ // currency on it, where the CLI paints `€0.03` for the same figure.
938
1031
  return `${real ? '' : '~'}$${cost.toFixed(4)}`;
939
1032
  }
940
1033
 
1034
+ /**
1035
+ * True when this account's tier means AEGIS bills no per-turn fee, so no money
1036
+ * figure belongs on a turn row or a session roll.
1037
+ *
1038
+ * The fee in question is the BYOK handling fee — the only charge AEGIS adds on
1039
+ * top of a caller's own provider bill — and aegis1 waives it on Unlimited:
1040
+ * `lib/local/entitlement.js` states the rule in as many words ("the throughput
1041
+ * allowance and the BYOK fee waiver are `is_unlimited()`-gated"), and the tier
1042
+ * a welcome trial grants IS Unlimited (a 30-day `unlimited` row in
1043
+ * `subscriptions`, which `register_device` writes in the same request that mints
1044
+ * the key). So a trial account resolves here exactly like a paying one, which is
1045
+ * what "trial unlimited" means — the trial is not a separate tier with its own
1046
+ * money rule, it is Unlimited for 30 days.
1047
+ *
1048
+ * Matching is on the resolved tier rather than `pro`: `pro` is "the PLAN is paid
1049
+ * for" and is also true of the €9 tier's aliases, while the waiver is gated on
1050
+ * `unlimited` specifically. A funded bank on a free plan is not a tier at all
1051
+ * (`entitlement.js` refuses to name one) and is therefore NOT waived — that
1052
+ * account pays the fee from the bank, and hiding the number would leave it with
1053
+ * no meter for the only money it spends.
1054
+ *
1055
+ * @param {{tier?: string|null, plan?: string|null, planRaw?: string|null}} [entitlement]
1056
+ * @returns {boolean}
1057
+ */
1058
+ function feeWaived(entitlement) {
1059
+ if (!entitlement || typeof entitlement !== 'object') return false;
1060
+ const named = [
1061
+ entitlement.tier,
1062
+ entitlement.plan,
1063
+ entitlement.planRaw,
1064
+ entitlement.subscription,
1065
+ entitlement.subscriptionTier,
1066
+ entitlement.product,
1067
+ // The server's own two fields, as `register_device` writes them: a welcome
1068
+ // trial is a 30-day `unlimited` row in `subscriptions`, and `item`/`sku` is
1069
+ // that row's product name. Naming them here is what keeps a trial account
1070
+ // from resolving to "no tier" and being billed a fee it does not owe.
1071
+ entitlement.item,
1072
+ entitlement.sku,
1073
+ ]
1074
+ .filter((v) => typeof v === 'string')
1075
+ .map((v) => v.trim().toLowerCase());
1076
+ // An explicit boolean outranks every spelling below: aegis1's `is_unlimited()`
1077
+ // verdict is the fact, and the strings are only what it is written as on the
1078
+ // wire. A probe that answers with the bit and not the tier is still an answer.
1079
+ if (entitlement.unlimited === true) return true;
1080
+ if (named.some((v) => v === 'unlimited' || v === 'trial')) return true;
1081
+ // A tier string that merely CONTAINS the word — `unlimited_trial`,
1082
+ // `plan.unlimited`, `Unlimited (trial)` — so a server that decorates the name
1083
+ // cannot put the fee back on an account whose tier is Unlimited.
1084
+ return named.some((v) => /(^|[^a-z])unlimited([^a-z]|$)/.test(v));
1085
+ }
1086
+
1087
+ /**
1088
+ * Whether a money figure belongs on this account's turn row or session roll.
1089
+ *
1090
+ * The CLI's exact rule (`cli/src/format.js` → `feeBillable`), and it is the same
1091
+ * rule on purpose — the two hosts render the same turn from the same engine, so
1092
+ * a row that shows a fee on one and waives it on the other is a disagreement
1093
+ * about what the user owes.
1094
+ *
1095
+ * A price is printed UNLESS AEGIS either waives it or has not proven it owed:
1096
+ *
1097
+ * - a tier AEGIS waives (`feeWaived`) → no price. Unlimited, paid or on the
1098
+ * 30-day welcome trial, has no per-turn charge and no bank draw;
1099
+ * - a snapshot asserting a plan it cannot prove (`degraded`) → no price. The
1100
+ * entitlement module STARTS at exactly that: `makeFreeSnapshot()` reads
1101
+ * `plan: 'free'`, `tier: null`, `source: 'unresolved'`, `degraded: true`,
1102
+ * which says "no verdict yet", not "this account is free". Reading the
1103
+ * placeholder as a verdict is what put `~$0.0005` and an "AEGIS handling fee"
1104
+ * line on the turns of trial accounts whose probe had not answered — a fee
1105
+ * charged in writing to the one account that does not pay it;
1106
+ * - everything else → the price stands, including when no snapshot exists at
1107
+ * all. A cost figure is a measurement of the turn, and dropping a real number
1108
+ * because no tier was published would leave a self-hosted or BYO-key run with
1109
+ * no meter for money it actually spent.
1110
+ *
1111
+ * The token figure is never gated by this, on any branch: what a turn produced
1112
+ * is not a price, and hiding it would leave an Unlimited account with no meter.
1113
+ *
1114
+ * @param {{tier?: string|null, plan?: string|null, planRaw?: string|null,
1115
+ * degraded?: boolean, source?: string|null, unlimited?: boolean}} [entitlement]
1116
+ * @returns {boolean}
1117
+ */
1118
+ function feeBillable(entitlement) {
1119
+ if (!entitlement || typeof entitlement !== 'object') return true;
1120
+ if (feeWaived(entitlement)) return false;
1121
+ return entitlement.degraded !== true;
1122
+ }
1123
+
941
1124
  if (typeof module !== 'undefined' && module.exports) {
942
1125
  module.exports = {
1126
+ feeWaived,
1127
+ feeBillable,
943
1128
  RATES,
944
1129
  RATE_BASIS,
945
1130
  UNPRICED_BY_DESIGN,
@@ -951,6 +1136,7 @@ if (typeof module !== 'undefined' && module.exports) {
951
1136
  usageCost,
952
1137
  costBreakdown,
953
1138
  turnAccounting,
1139
+ displayTokens,
954
1140
  estimateTokens,
955
1141
  estimatedBuckets,
956
1142
  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
  }