aegiscode 6.8.35 → 6.8.36

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
@@ -26,7 +26,7 @@
26
26
  * renderSessionsOverlay buildPermissions buildModelList buildRewindList
27
27
  * buildOnboarding buildShellCompletion buildTerminalSetup buildPRs
28
28
  * buildBenchmark buildWaifu buildAegisStatus buildAegisRecall buildAegisMulti
29
- * buildBilling buildMemory buildMemoryTiers buildRouter buildYolo buildSkills
29
+ * buildBilling buildMemory buildMemoryTiers buildRouter buildAutomode buildSkills
30
30
  * buildMcp buildHooksStatus buildHooksList buildTroubleshooting
31
31
  * buildReleaseNotes
32
32
  * (plus the pure reference helpers with no missing capability)
@@ -279,7 +279,7 @@ function buildStatus(state, ctx = {}) {
279
279
  add('Model', s.model);
280
280
  // `null` = auto: the pool sizes each turn from the ask, so the row says so
281
281
  // rather than vanishing (add() skips empty values).
282
- add('Effort', s.effort || 'auto');
282
+ add('Effort', s.effort || 'high');
283
283
  if (s.thinking != null) add('Thinking', s.thinking ? 'on' : 'off');
284
284
  if (s.stream != null) add('Streaming', s.stream === false ? 'off' : 'on');
285
285
  if (s.vim != null) add('Vim keymap', s.vim ? 'on' : 'off');
@@ -1263,20 +1263,32 @@ function buildMemoryEmbeddings(status, stats, ctx = {}) {
1263
1263
  return lines;
1264
1264
  }
1265
1265
 
1266
- // ── /yolo ────────────────────────────────────────────────────────────────────
1266
+ // ── /automode ────────────────────────────────────────────────────────────────
1267
+ //
1268
+ // This mode is called "automode" here, the same word the engine repo
1269
+ // (aegiscodex-dev) uses for its ← -on-an-empty-input mode: one name for one
1270
+ // idea across the two faces. `/yolo` remains a working ALIAS — it is what the
1271
+ // desktop switch, the persisted posture and every existing install's muscle
1272
+ // memory say, so dropping it would break the command for people who typed it
1273
+ // yesterday — but nothing user-facing is *labelled* YOLO any more.
1267
1274
 
1268
- function buildYolo(state, ctx = {}) {
1275
+ function buildAutomode(state, ctx = {}) {
1269
1276
  const t = themeOf(ctx);
1270
1277
  const lines = [];
1271
- lines.push([span(t.gold + BOLD, '⚠ YOLO mode enabled'), span(BOLD_OFF, '')]);
1278
+ lines.push([span(t.gold + BOLD, '⚠ automode enabled'), span(BOLD_OFF, '')]);
1272
1279
  lines.push([span(t.gray, '─'.repeat(30))]);
1273
1280
  lines.push([span(t.white, 'All tool executions are auto-approved: file writes,')]);
1274
1281
  lines.push([span(t.white, 'bash commands, and network requests run without asking.')]);
1275
1282
  lines.push([span('', '')]);
1276
- lines.push([span(t.gray, 'Run /yolo off to restore confirmations.')]);
1283
+ lines.push([span(t.gray, 'Run /automode off to restore confirmations.')]);
1284
+ lines.push([span(t.gray, '(/yolo is accepted as an alias.)')]);
1277
1285
  return lines;
1278
1286
  }
1279
1287
 
1288
+ // The pre-rename name, kept as an export so vendored copies and the panels
1289
+ // test's export list cannot break on the rename. Same function object.
1290
+ const buildYolo = buildAutomode;
1291
+
1280
1292
  // ── /release-notes ───────────────────────────────────────────────────────────
1281
1293
 
1282
1294
  /**
@@ -1381,6 +1393,7 @@ module.exports = {
1381
1393
  buildMemory,
1382
1394
  buildMemoryTiers,
1383
1395
  buildRouter,
1396
+ buildAutomode,
1384
1397
  buildYolo,
1385
1398
  buildSkills,
1386
1399
  buildMcp,
package/src/render.js CHANGED
@@ -33,7 +33,7 @@ const {
33
33
  } = require('./theme.js');
34
34
  const { WELCOME_TITLE, WELCOME_BACK, TAGLINE, STAR, stencilGlyph, welcomeArtParts } = require('./art.js');
35
35
  const { w, pad, padStart, wrapBlock, clip, span } = require('./screen.js');
36
- const { fmtTokens, fmtEur, fmtElapsed } = require('./format.js');
36
+ const { fmtTokens, fmtEur, fmtElapsed, fmtUsageSplit, displayTokens, feeBillable } = require('./format.js');
37
37
  const { renderDiffBlock } = require('./diffview.js');
38
38
 
39
39
  // Guarded: a concurrent workstream owns ./markdown.js.
@@ -262,16 +262,23 @@ function renderTurn(ctx, turn, width = 80) {
262
262
  const body = assistantLines(ctx, text, Math.max(8, width - 2));
263
263
  if (!body.length) body.push('');
264
264
  body[0] = `${t.white}${GLYPH.block}${RESET} ` + body[0];
265
- // Two lines minimum, or the cursor lands on the marker's own line and a
266
- // one-line answer prints `● Working●` — two dots where there should be one.
267
- if (turn.streaming && body.length > 1) body[body.length - 1] += `${t.white}${GLYPH.block}${RESET}`;
265
+ // No trailing cursor, deliberately — the twin of the rule in chatflow.js's
266
+ // `rowLines`. Appending one to the last line only when the message ran past
267
+ // one row made the glyph count depend on the text's WRAP (`● Working` at one
268
+ // line, `● Working●` at two), so the extra dot appeared on exactly the long
269
+ // answers a reader is likeliest to look at. The head marker is the answer's
270
+ // gutter, not half of a bracket, and it is the same glyph the finished row
271
+ // keeps — the live turn is the working line's job to advertise.
268
272
  lines.push(...body);
269
273
  } else if (role === 'tool') {
270
274
  // turn.ok is only known once the call has actually run (the agent loop's
271
275
  // tool-activity event fires after execution); undefined means "no result
272
276
  // yet to report" (the plain registry-tool path, which never set it).
273
277
  const status = turn.ok === undefined ? '' : turn.ok ? ` ${t.green}${GLYPH.check}${RESET}` : ` ${t.red}${errMark()}${RESET}`;
274
- lines.push(`${t.white}${GLYPH.block}${RESET} ${t.gray}${turn.label || 'tool'}${RESET}${status}`);
278
+ // A tool row is a running command, not a bullet in a list — it carries no
279
+ // leading `●` mark. Only the assistant's answer keeps that marker (see the
280
+ // role branch above), so the two row kinds no longer look interchangeable.
281
+ lines.push(`${t.gray}${turn.label || 'tool'}${RESET}${status}`);
275
282
  const args =
276
283
  turn.args == null
277
284
  ? ''
@@ -303,24 +310,52 @@ function renderTurn(ctx, turn, width = 80) {
303
310
  }
304
311
 
305
312
  /**
306
- * The per-turn accounting line — tokens beside what they cost, in the `⎿` hook
307
- * row style, e.g. `⎿ 1,562 tok · 1,250/312 · €0.0007 · 4.2s`.
313
+ * The per-turn accounting line — what the turn produced beside what it cost, in
314
+ * the `⎿` hook row style, e.g. `⎿ 312 out · €0.0007 · 4.2s`. The figure is
315
+ * labelled and is the OUTPUT half alone (see `fmtUsageSplit`).
308
316
  */
309
317
  function renderMeta(ctx, meta = {}, width = 80) {
310
318
  const t = themeOf(ctx);
311
319
  const bits = [];
312
320
  if (meta.model) bits.push(`${t.blue}${meta.model}${RESET}`);
313
- if (meta.tokens != null) bits.push(`${t.white}${fmtTokens(meta.tokens)} tok${RESET}`);
314
- // The producer (chatflow.js's accounting row) pushes the split flat, as
321
+ // The producer (chatflow.js's accounting row) pushes the pair flat, as
315
322
  // `input`/`output` — reading it as `meta.usage.input` here meant the pair was
316
323
  // never printed on this path even though the docstring above promises it.
317
324
  // Both shapes are accepted: `usage` is what the desktop's renderer hands over.
318
325
  const split = meta.usage && typeof meta.usage === 'object' ? meta.usage : meta;
319
- const { input, output } = split;
320
- if (Number.isFinite(input) || Number.isFinite(output)) {
321
- bits.push(`${t.gray}${fmtTokens(input || 0)}/${fmtTokens(output || 0)}${RESET}`);
326
+ // The row's token figure is what the turn PRODUCED, and it is the only one it
327
+ // prints: labelled `tokens`, in this theme's strongest token — the figure the row
328
+ // exists to report. The input half is gone deliberately, not by omission. It
329
+ // is the prompt restated, on a cached turn it is the larger number by an order
330
+ // of magnitude, and it is the one figure in the row nobody can act on: you
331
+ // change what a turn costs by changing what it PRODUCES. Leading with it made
332
+ // the row read as a runaway (`156,189 tok · 151,175 in · 5,014 tokens`) while
333
+ // saying nothing about the answer. Its one remaining reader is `/cost`, which
334
+ // carries the full miss/hit breakdown — a panel you open, not a line painted
335
+ // under every answer.
336
+ //
337
+ // This is the twin of chatflow.js's accounting row (see `metaBits`): the two
338
+ // render the same row through different plumbing, so they state the same
339
+ // figure. The total does NOT stand in when no output figure arrived: `tokens`
340
+ // is input + output, so the fallback that used to sit here printed a turn's
341
+ // prompt back at it under an unlabelled figure — the exact reading this row
342
+ // exists to remove, and the one the desktop already refuses in
343
+ // `displayTokens` (desktop/renderer/usage.js). An unmeasurable output leaves
344
+ // the figure off rather than stating a total, and `0 tokens` is refused for the
345
+ // reason `fmtRoll` refuses `0 tokens`: it states a figure the provider never
346
+ // reported.
347
+ const parts = fmtUsageSplit(split);
348
+ if (parts) bits.push(`${t.white}${parts.output}${RESET}`);
349
+ else {
350
+ const produced = displayTokens(split);
351
+ if (produced != null) bits.push(`${t.white}${fmtTokens(produced)} tokens${RESET}`);
322
352
  }
323
- if (meta.eur != null) bits.push(`${meta.eur > 0 ? t.coral : t.green}${fmtEur(meta.eur)}${RESET}`);
353
+ // No money on a tier AEGIS bills no fee to, and none from a snapshot that has
354
+ // not proven a fee is owed — the desktop's rule, and now this host's too
355
+ // (`feeBillable`). The token figure above stays either way: what the turn
356
+ // produced is not a price, and hiding it would leave an Unlimited account with
357
+ // no meter at all.
358
+ if (meta.eur != null && feeBillable()) bits.push(`${meta.eur > 0 ? t.coral : t.green}${fmtEur(meta.eur)}${RESET}`);
324
359
  if (meta.ms != null) bits.push(`${t.gray}${fmtElapsed(meta.ms)}${RESET}`);
325
360
  if (meta.calls > 1) bits.push(`${t.gray}${meta.calls} calls${RESET}`);
326
361
  if (!bits.length) return '';
@@ -337,7 +372,7 @@ function renderStatus(ctx, state = {}, width = 80) {
337
372
  const t = themeOf(ctx);
338
373
  const left = ['aegis'];
339
374
  if (state.model) left.push(state.model);
340
- if (state.tokens != null) left.push(`${fmtTokens(state.tokens)} tok`);
375
+ if (state.tokens != null) left.push(`${fmtTokens(state.tokens)} tokens`);
341
376
  if (state.spend != null) left.push(fmtEur(state.spend));
342
377
  if (state.mode) left.push(state.mode);
343
378
 
package/src/screen.js CHANGED
@@ -444,7 +444,18 @@ class LiveRegion {
444
444
  // Back to the first row of the old block, rewrite, clear the tail.
445
445
  this.out.write(ESC.col(1) + ESC.up(this.rows) + body + '\n' + ESC.col(1) + ESC.up(1));
446
446
  }
447
- this.rows = lines.length;
447
+ // The PHYSICAL terminal rows the block just occupies, not the number of
448
+ // logical lines passed in. A working line (render.js's `renderWorking`,
449
+ // the only caller with a long verb + elapsed + token tail) can exceed the
450
+ // terminal width and wrap to two rows on anything narrower than ~65
451
+ // columns; recording `lines.length` (always 1) left the next tick's
452
+ // `up(this.rows)` one row short, so the wrapped second row was never
453
+ // erased. Since the line's content (elapsed time, token count) changes
454
+ // every 90ms tick, that stray row renewed itself every tick — a
455
+ // vertically growing stack of near-duplicate status lines while the
456
+ // model streamed, instead of one line updating in place.
457
+ const cols = Math.max(1, getSize().cols);
458
+ this.rows = lines.reduce((n, l) => n + Math.max(1, Math.ceil(w(l) / cols)), 0);
448
459
  }
449
460
 
450
461
  /** Erase the block and return the cursor to its start, so the caller can
package/src/todos.js CHANGED
@@ -29,6 +29,7 @@ const fs = require('node:fs');
29
29
  const path = require('node:path');
30
30
 
31
31
  const { aegisDir } = require('./config.js');
32
+ const { writePrivateFile } = require('./securefs.js');
32
33
 
33
34
  function todosFile() {
34
35
  return path.join(aegisDir(), 'todos.json');
@@ -53,10 +54,12 @@ function writeTodos(list) {
53
54
  .filter((t) => t && typeof t.text === 'string' && t.text.trim())
54
55
  .map((t) => ({ text: t.text.trim(), done: t.done === true, at: t.at || new Date().toISOString() }));
55
56
  try {
56
- fs.mkdirSync(aegisDir(), { recursive: true });
57
- const tmp = `${todosFile()}.tmp`;
58
- fs.writeFileSync(tmp, `${JSON.stringify(clean, null, 2)}\n`);
59
- fs.renameSync(tmp, todosFile());
57
+ // Through securefs, not `fs.writeFileSync`: todos.json lives in the data
58
+ // dir, so the raw write gave it umask mode (0664 — world-readable in a
59
+ // 0775 dir) and followed a symlink planted there. The temp-file + rename
60
+ // shape the old code spelled out by hand is what `writePrivateFile` does,
61
+ // plus 0600/0700 and O_NOFOLLOW.
62
+ writePrivateFile(todosFile(), `${JSON.stringify(clean, null, 2)}\n`);
60
63
  } catch {
61
64
  /* best-effort, like every other store in this host */
62
65
  }
package/src/tokens.js CHANGED
@@ -32,7 +32,7 @@ const path = require('node:path');
32
32
  const { resolveShared } = require('./sharedpaths.js');
33
33
  const shared = require(resolveShared(path.join('desktop', 'renderer', 'usage.js')));
34
34
 
35
- const { RATES, RATE_BASIS, UNPRICED_BY_DESIGN, isPeak, ratesFor, costBreakdown, cacheHitRate } = shared;
35
+ const { RATES, RATE_BASIS, UNPRICED_BY_DESIGN, isPeak, ratesFor, costBreakdown, cacheHitRate, usageBuckets } = shared;
36
36
 
37
37
  // System prompt + tool definitions overhead, roughly, in tokens.
38
38
  const SYSTEM_TOKENS = 18000;
@@ -94,6 +94,28 @@ function estimateTokens(text) {
94
94
  return Math.max(1, Math.ceil([...String(text)].length / 4));
95
95
  }
96
96
 
97
+ /**
98
+ * The same 4:1 rule, from a streamed LENGTH rather than from the text.
99
+ *
100
+ * The live tails count what has arrived as a display width, because they are
101
+ * painted from a counter on a timer rather than from a string — see app.js
102
+ * (`chars += w(chunk.delta)`) and chatflow.js (`streamedChars += w(delta)`).
103
+ * Both sites then label that number `tokens`, so the count form of the
104
+ * heuristic has to live beside the text form. Without it the two producers fed
105
+ * their raw cell count straight into `fmtTokens(...) tokens`, which printed the
106
+ * character count as a token count — the live spinner read ~4x high, and high
107
+ * against every settled figure for the same turn (the desktop meter included),
108
+ * which is exactly the "tokens spent" gap against the reference engine.
109
+ *
110
+ * Returns 0 for an empty stream so a caller can tell "nothing yet" from "some",
111
+ * rather than `estimateTokens`'s floor of 1.
112
+ */
113
+ function estimateTokensFromCells(cells) {
114
+ const n = Number(cells);
115
+ if (!(n > 0)) return 0;
116
+ return Math.ceil(n / 4);
117
+ }
118
+
97
119
  /**
98
120
  * Bucket the transcript's token usage.
99
121
  * input — user prompts + system + tools (per exchange)
@@ -220,7 +242,15 @@ module.exports = {
220
242
  ratesFor,
221
243
  costBreakdown,
222
244
  cacheHitRate,
245
+ // Re-exported so a caller that only needs the bucket shape (the per-turn
246
+ // in/out readout in chatflow.js and app.js) does not have to reach past this
247
+ // module into the desktop bundle itself — and, more importantly, so it has
248
+ // exactly ONE way to read a usage object rather than a hand-rolled
249
+ // `input_tokens ?? prompt_tokens`, which is how the two hosts came to
250
+ // disagree about the same turn's prompt size in the first place.
251
+ usageBuckets,
223
252
  estimateTokens,
253
+ estimateTokensFromCells,
224
254
  transcriptUsage,
225
255
  usageCost,
226
256
  sessionAccounting,
@@ -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
  }