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/commands.js CHANGED
@@ -56,7 +56,7 @@ const {
56
56
  // ON8 / D8 rule 1: the posture writers. Every "confirmations on/off" command
57
57
  // below goes through these rather than writing `defaultMode` itself, so the
58
58
  // window's switch and this face's gate cannot end up holding two answers.
59
- setConfirmPosture, setPermissionDefaultMode,
59
+ setConfirmPosture, setPermissionDefaultMode, confirmPosture,
60
60
  memoryPersistState, setMemoryPersist,
61
61
  } = require('./config.js');
62
62
  const { auditExposure, repairExposure } = require('./securefs.js');
@@ -66,6 +66,10 @@ const { signupUrl, goUrl } = require('./signup.js');
66
66
  const screens = require('./screens.js');
67
67
  const { summarizeTranscript, recapLine } = require('./summarize.js');
68
68
  const { sessionAccounting, accountingFromUsage, estimateTokens } = require('./tokens.js');
69
+ // The one effort normaliser, so `/config effort <x>` writes the same rung the
70
+ // turn will send (see effortRung in engine.js — it is what app.js puts on the
71
+ // request).
72
+ const { effortRung } = require('./engine.js');
69
73
  const { transcriptToMarkdown, transcriptToJSON, writeExportFile, lastAssistantText } = require('./export.js');
70
74
  const { detectDevCommand, runDevServer } = require('./devrun.js');
71
75
  // /ping — the terminal half of the desktop's "reply ready" alert. Pure and
@@ -129,7 +133,7 @@ const categoryLabel = (id) => (CATEGORIES.find((cat) => cat.id === id) || {}).la
129
133
  // strings, and overlays.js's label/note rows — so adding a level meant editing
130
134
  // three places, and the index a picker row reported was mapped back to a value
131
135
  // through whichever list happened to be in scope. EFFORT_VALUES is the picker's
132
- // own order, `null` first for "auto".
136
+ // own order: the three rungs, with no `auto` entry any more.
133
137
  const EFFORT_LEVELS = overlays.EFFORT_VALUES;
134
138
 
135
139
  // ── Small handler helpers ─────────────────────────────────────────────────────
@@ -145,7 +149,7 @@ const done = (c, text) => c.push({ role: 'done', text });
145
149
  // (single-model — the reference fans it out)" and handed the raw task to
146
150
  // c.runPrompt — a single turn, not a fan-out — while /multiyolo printed the
147
151
  // paste-ready panel and never executed anything at all, so its `savePermissions
148
- // ({ defaultMode: 'allow' })` turned YOLO on and then did nothing with it.
152
+ // ({ defaultMode: 'allow' })` turned automode on and then did nothing with it.
149
153
  //
150
154
  // The upstream engine calls `multiData(task, { signal })`, which
151
155
  // shells out to aegis-cli (`aegis --print "/multi <task>"`) because the fan-out
@@ -207,7 +211,7 @@ async function multiData(c, task) {
207
211
  }
208
212
 
209
213
  /**
210
- * Drive one of the three fan-out commands end to end. `yolo` is /multiyolo's
214
+ * Drive one of the three fan-out commands end to end. `automode` is /multiyolo's
211
215
  * edge: the permission mode is set to allow *and* the task then executes under
212
216
  * it (previously it was set and never used).
213
217
  */
@@ -217,7 +221,7 @@ async function runMultiCommand(c, task, { yolo = false, title = 'ÆGIS Multi' }
217
221
  // means "stop confirming", and that is now ONE fact in two stores rather than
218
222
  // a rule-file edit the window would never see.
219
223
  setConfirmPosture(false);
220
- panel(c, panels.buildYolo(c.state(), c.ctx));
224
+ panel(c, panels.buildAutomode(c.state(), c.ctx));
221
225
  }
222
226
  note(c, 'Running the multi-agent fan-out — the engine delegates to specialist subagents (headless: this skips aegis-cli\'s own confirmation step).');
223
227
  c.render();
@@ -1056,6 +1060,25 @@ const COMMANDS = [
1056
1060
  // A model/class/effort change is a live session decision, not just a file
1057
1061
  // write; say so rather than leaving the user to wonder when it applies.
1058
1062
  if (['model', 'currentModelId', 'modelClass', 'effort', 'themeIndex', 'vim'].includes(res.key)) {
1063
+ // ...and for `effort` the session value is written here, not just
1064
+ // promised. `setConfigValue` touches the file only, so the note used to
1065
+ // announce a change that the very next turn did NOT make: the session
1066
+ // kept its old rung until a relaunch, which is one more way `/effort`
1067
+ // appeared to do nothing. Floored through effortRung, so a hand-written
1068
+ // `/config effort ultra` cannot put a rung on the wire that the engine
1069
+ // does not know.
1070
+ if (res.key === 'effort') {
1071
+ c.ctx.effort = effortRung(res.value);
1072
+ // Persist the FLOORED rung, not the raw argument: `effort` is a
1073
+ // shared key AEGIS Desktop reads too, and writing `bogus` would put a
1074
+ // level in that file which every reader has to floor again. rungTaken
1075
+ // reports the correction rather than letting the note claim a value
1076
+ // the turn did not take.
1077
+ if (c.ctx.effort !== String(res.value).toLowerCase()) {
1078
+ c.saveConfig({ effort: c.ctx.effort });
1079
+ note(c, ` "${res.value}" is not a level this build sends — recorded as ${c.ctx.effort}.`);
1080
+ }
1081
+ }
1059
1082
  note(c, ` This takes effect on the next turn; /${res.key === 'currentModelId' ? 'model' : res.key} shows the live session value.`);
1060
1083
  }
1061
1084
  c.render();
@@ -1063,27 +1086,35 @@ const COMMANDS = [
1063
1086
  },
1064
1087
  },
1065
1088
  {
1066
- name: 'effort', args: ['level'], hint: '[auto|low|medium|high]', category: 'model',
1089
+ name: 'effort', args: ['level'], hint: '[low|medium|high]', category: 'model',
1067
1090
  desc: 'Set the token budget the pool sizes each turn from',
1068
1091
  handler: async (c, args) => {
1069
1092
  const level = (args.level || '').toLowerCase();
1093
+ // Validated against EFFORT_LEVELS, which IS the picker's value list
1094
+ // (overlays.EFFORT_VALUES, aliased above) — the same array the rows are
1095
+ // drawn from, so a level the picker offers can never be rejected here.
1070
1096
  if (level && level !== 'auto' && !EFFORT_LEVELS.includes(level)) {
1071
- note(c, `Unknown effort level "${args.level}". Use auto, ${EFFORT_LEVELS.filter(Boolean).join(', ')}.`);
1097
+ note(c, `Unknown effort level "${args.level}". Use ${EFFORT_LEVELS.join(', ')}.`);
1072
1098
  c.render();
1073
1099
  return true;
1074
1100
  }
1075
1101
  if (!level) {
1076
- c.openOverlay({ type: 'effort', sel: Math.max(0, EFFORT_LEVELS.indexOf(c.ctx.effort)) });
1102
+ // The picker opens on the rung actually in force; a session whose
1103
+ // config predates the default lands on high, which is what the engine
1104
+ // applies to an unstored value.
1105
+ c.openOverlay({ type: 'effort', sel: Math.max(0, EFFORT_LEVELS.indexOf(c.ctx.effort || 'high')) });
1077
1106
  return true;
1078
1107
  }
1079
- // 'auto' is the absence of a pin, not a fourth rung: it is stored as null
1080
- // so nothing is sent and the server sizes the turn from the ask.
1081
- const pinned = level === 'auto' ? null : level;
1108
+ // `auto` is retired, not a fourth rung: it pinned nothing, and a fresh
1109
+ // install therefore sent no effort and the knob did nothing. It is still
1110
+ // ACCEPTED so an old habit (or a script) is not a hard error — it now
1111
+ // resolves to the default rung, and says so.
1112
+ const pinned = level === 'auto' ? 'high' : level;
1082
1113
  c.ctx.effort = pinned;
1083
1114
  c.saveConfig({ effort: pinned });
1084
- note(c, pinned
1085
- ? `Effort level: ${pinned} — the pool sizes this turn's token budget from it`
1086
- : 'Effort level: auto — the pool sizes each turn from the ask');
1115
+ note(c, level === 'auto'
1116
+ ? `effort: auto is retired — high is the default, and it is what this session now sends`
1117
+ : `Effort level: ${pinned} — the pool sizes this turn's token budget from it`);
1087
1118
  c.render();
1088
1119
  return true;
1089
1120
  },
@@ -2086,10 +2117,21 @@ const COMMANDS = [
2086
2117
  name: 'confirm', aliases: ['confirmations'], args: ['mode'], hint: '[on|off]', category: 'model',
2087
2118
  desc: 'Toggle tool-call confirmation prompts',
2088
2119
  handler: async (c, args) => {
2089
- const rules = loadPermissions();
2090
2120
  const mode = (args.mode || '').toLowerCase();
2091
2121
  if (mode && !['on', 'off'].includes(mode)) { note(c, 'Usage: /confirm [on|off]'); c.render(); return true; }
2092
- const want = mode === 'on' ? true : mode === 'off' ? false : rules.defaultMode !== 'allow';
2122
+ // ON8: the bare toggle reads the POSTURE (the shared `confirmMode` key
2123
+ // both faces write), never the rule file's `defaultMode`.
2124
+ //
2125
+ // Two reasons, and the second one is the user-visible bug. (1) Since ON8
2126
+ // the rule file holds the *residual* (`ask`/`allow`/`deny`) and the shared
2127
+ // key holds the posture — reading the residual would answer a question the
2128
+ // user did not ask, and `defaultMode: 'deny'` would read as "on". (2) The
2129
+ // old spelling (`rules.defaultMode !== 'allow'`) could be turned ON and
2130
+ // never OFF from the keyboard: `defaultMode` ships as 'ask', so a fresh
2131
+ // install already read as "on" and a bare `/confirm` wrote `ask` — the
2132
+ // same state it had just read — leaving prompts on with no way to toggle
2133
+ // them off. `confirmPosture()` is the one read, exactly like the engine's.
2134
+ const want = mode === 'on' ? true : mode === 'off' ? false : !confirmPosture().enabled;
2093
2135
  // ON8: one writer for the posture — the shared key the window's switch
2094
2136
  // reads, plus the rule residual this face's gate reads.
2095
2137
  setConfirmPosture(want);
@@ -2099,31 +2141,39 @@ const COMMANDS = [
2099
2141
  },
2100
2142
  },
2101
2143
  {
2102
- name: 'yolo', args: ['mode'], hint: '[on|off]', category: 'model',
2103
- desc: 'Toggle YOLO mode — auto-approve all tool executions',
2144
+ name: 'automode', aliases: ['yolo'], args: ['mode'], hint: '[on|off]', category: 'model',
2145
+ desc: 'Toggle automode — auto-approve all tool executions',
2104
2146
  handler: async (c, args) => {
2105
- const rules = loadPermissions();
2106
2147
  const mode = (args.mode || '').toLowerCase();
2107
- if (mode && !['on', 'off'].includes(mode)) { note(c, 'Usage: /yolo [on|off]'); c.render(); return true; }
2108
- const want = mode === 'on' ? true : mode === 'off' ? false : rules.defaultMode !== 'allow';
2109
- // ON8: `/yolo` is the posture's OFF state, written through the one writer,
2110
- // so the window's switch shows it and the two faces cannot disagree.
2148
+ if (mode && !['on', 'off'].includes(mode)) { note(c, 'Usage: /automode [on|off]'); c.render(); return true; }
2149
+ // Same one read as `/confirm` above, with the polarity this command's
2150
+ // label implies: "automode" IS confirmations-off, so the bare toggle is
2151
+ // `!automode` == the posture itself. Reading the rule file here wrongly
2152
+ // reported automode as already-on for a fresh install (whose residual
2153
+ // ships as 'ask'), so the first bare `/automode` turned it OFF — the
2154
+ // opposite of what the word means to the person typing it — and the
2155
+ // inverse mistake (`!confirmPosture().enabled`) made the first press a
2156
+ // no-op with confirmations on. Both spellings are gone.
2157
+ const want = mode === 'on' ? true : mode === 'off' ? false : confirmPosture().enabled;
2158
+ // ON8: `/automode` (alias `/yolo`) is the posture's OFF state, written
2159
+ // through the one writer, so the window's switch shows it and the two
2160
+ // faces cannot disagree.
2111
2161
  setConfirmPosture(!want);
2112
- if (want) panel(c, panels.buildYolo(c.state(), c.ctx));
2113
- else note(c, 'YOLO mode off — confirmations restored.');
2162
+ if (want) panel(c, panels.buildAutomode(c.state(), c.ctx));
2163
+ else note(c, 'automode off — confirmations restored.');
2114
2164
  c.render();
2115
2165
  return true;
2116
2166
  },
2117
2167
  },
2118
2168
  {
2119
- name: 'multiyolo', args: ['task'], hint: '<task>', category: 'session',
2120
- desc: 'Multi-agent orchestration with YOLO mode — /multiyolo <task>',
2169
+ name: 'multiyolo', aliases: ['multiauto'], args: ['task'], hint: '<task>', category: 'session',
2170
+ desc: 'Multi-agent orchestration with automode — /multiyolo <task>',
2121
2171
  handler: async (c, args) => {
2122
2172
  const task = (args._rest || args.task || '').trim();
2123
2173
  if (!task) { note(c, 'Usage: /multiyolo <task>'); c.render(); return true; }
2124
- // YOLO is the point of this alias: auto-approve, then actually run the
2174
+ // automode is the point of this alias: auto-approve, then actually run the
2125
2175
  // fan-out. Composing the text and stopping (what this used to do) left the
2126
- // user with an enabled YOLO mode and an unexecuted task.
2176
+ // user with an enabled automode and an unexecuted task.
2127
2177
  return runMultiCommand(c, task, { yolo: true });
2128
2178
  },
2129
2179
  },
package/src/config.js CHANGED
@@ -89,12 +89,15 @@ const DEFAULT_CONFIG = {
89
89
  // aegiscode- name so /model add/remove/switch stay compatible both ways.
90
90
  models: null,
91
91
  currentModelId: null,
92
- // `null` = no effort pinned, i.e. "auto": each turn is sized by the server
93
- // from the ask itself (aegis1 services/pool_brain.py estimate_effort). The
94
- // old 'high' was a *pin* on the top rung of the budget ladder — the most the
95
- // server can grant — so the CLI's default turn was the most expensive one it
96
- // could make, and /effort could only ever move it down.
97
- effort: null,
92
+ // The effort rung every turn is sized from, stored as a real level so the
93
+ // value read back is the value sent. It used to be `null` ("auto": send no
94
+ // rung and let the server infer one from the ask), which made the DEFAULT a
95
+ // no-op — a fresh install carried no effort at all, so low/medium/high only
96
+ // ever changed the status line. `high` is the rung the engine and the desktop
97
+ // resolve an absent value to, so the default is now stated rather than
98
+ // implied. Anything unreadable (null, a stale 'auto', junk) is coerced to
99
+ // `high` by effortRung() in cli/src/engine.js before it reaches the wire.
100
+ effort: 'high',
98
101
  vim: false,
99
102
  lastCwd: '',
100
103
  };
@@ -279,7 +282,7 @@ function loadConfig() {
279
282
  * have written `undefined` — which `prefs.set()` drops. Every unrelated config
280
283
  * save (`/theme`, onboarding, an update-check cache write) would then DELETE the
281
284
  * gate's one shared copy, silently reverting the window's switch and the shell's
282
- * `/yolo` to the rule file on the next launch. And filling it with `true` instead
285
+ * `/automode` (alias `/yolo`) to the rule file on the next launch. And filling it with `true` instead
283
286
  * would be worse, not better: an install whose desktop still holds a legacy
284
287
  * `__confirmMode: { enabled: false }` would be flipped ON by the first CLI save,
285
288
  * which is exactly the migration `client/prefs.js`'s `adopt()` exists to get
@@ -390,6 +393,32 @@ function savePermissions(rules) {
390
393
  return rules;
391
394
  }
392
395
 
396
+ /**
397
+ * Write the rule file's residual mode WITHOUT the DERIVED `explicitAsk` field.
398
+ *
399
+ * `explicitAsk` is computed by loadPermissions() from `defaultMode`; it is a
400
+ * read-time derivation, not stored state. Spreading `{ ...loadPermissions() }`
401
+ * carries the value derived from the file being replaced, so `/confirm on` used
402
+ * to leave `{"defaultMode":"ask","explicitAsk":false}` — a file that denies the
403
+ * very field it sets — and `/confirm off` left `{"defaultMode":"allow",
404
+ * "explicitAsk":true}`, which is worse: two fields disagreeing about whether
405
+ * the user ever asked to be prompted.
406
+ *
407
+ * Harmless only while every reader recomputes (loadPermissions does), and a real
408
+ * bug the moment one does not: `one/src/permissions.js` builds its rule set from
409
+ * the file's `explicitAsk` as well as its `defaultMode`, and an operator reading
410
+ * permissions.json to answer "is confirmation on?" reads the stale line. Every
411
+ * writer here goes through this, so the file always says exactly one thing.
412
+ *
413
+ * This mirrors the engine's `persistRules` (aegiscodex-dev src/registry.js,
414
+ * commit e7bb9db, "a switch that turns off"); the plugin's CLI face was the copy
415
+ * that never got it.
416
+ */
417
+ function saveRuleMode(mode) {
418
+ const { explicitAsk, ...rest } = loadPermissions();
419
+ return savePermissions({ ...rest, defaultMode: mode });
420
+ }
421
+
393
422
  /**
394
423
  * Add a rule to a permission list if not already present.
395
424
  * Returns { added, rules } — added is false when the rule already exists.
@@ -466,8 +495,8 @@ function confirmPosture() {
466
495
  /**
467
496
  * Set the posture: the shared key (both faces) + the rule file's residual.
468
497
  *
469
- * Called by every command that means "confirmations on/off" — /confirm, /yolo,
470
- * /multiyolo and the flag the desktop's switch mirrors — so there is exactly one
498
+ * Called by every command that means "confirmations on/off" — /confirm,
499
+ * /automode (alias /yolo), /multiyolo and the flag the desktop's switch mirrors — so there is exactly one
471
500
  * writer per fact and no command can leave the two stores disagreeing.
472
501
  */
473
502
  function setConfirmPosture(enabled) {
@@ -477,7 +506,7 @@ function setConfirmPosture(enabled) {
477
506
  } catch (e) {
478
507
  if (process.env.AEGIS_HIST_DEBUG) console.error('[prefs] write failed:', e);
479
508
  }
480
- savePermissions({ ...loadPermissions(), defaultMode: want ? 'ask' : 'allow' });
509
+ saveRuleMode(want ? 'ask' : 'allow');
481
510
  return want;
482
511
  }
483
512
 
@@ -497,7 +526,7 @@ function setPermissionDefaultMode(mode) {
497
526
  } catch (e) {
498
527
  if (process.env.AEGIS_HIST_DEBUG) console.error('[prefs] write failed:', e);
499
528
  }
500
- savePermissions({ ...loadPermissions(), defaultMode: want });
529
+ saveRuleMode(want);
501
530
  return want;
502
531
  }
503
532
 
@@ -519,6 +548,7 @@ module.exports = {
519
548
  DEFAULT_PERMISSIONS,
520
549
  loadPermissions,
521
550
  savePermissions,
551
+ saveRuleMode,
522
552
  addPermissionRule,
523
553
  removePermissionRule,
524
554
  confirmPosture,
package/src/engine.js CHANGED
@@ -63,7 +63,7 @@ const CLASS_LABELS = Object.freeze({
63
63
  * @param {object} client A client from client/aegis.js (createClient()).
64
64
  * @param {() => boolean} getConfirmMode Whether mutating tools (exec,
65
65
  * writeFile, editFile) require approval before running. Read per call, so
66
- * toggling it (/permissions, /yolo) takes effect on the next tool round.
66
+ * toggling it (/permissions, /automode) takes effect on the next tool round.
67
67
  * @param {() => string} getClass Which class the next turn runs on — read per
68
68
  * call for the same reason getConfirmMode is: /class must take effect on the
69
69
  * very next turn, not on the next launch.
@@ -139,4 +139,31 @@ function byokNamespace(provider) {
139
139
  return `byok:${provider}`;
140
140
  }
141
141
 
142
- module.exports = { createEngine, HOST_CLASSES, DEFAULT_CLASS, CLASS_LABELS, byokNamespace };
142
+ /**
143
+ * The effort rung a turn travels with: always 'low' | 'medium' | 'high'.
144
+ *
145
+ * This host has exactly three levels and every one of them must reach the wire,
146
+ * so the normalisation lives here — on the path from session state to request —
147
+ * rather than in the renderers. An absent, empty, `null` or retired `auto`
148
+ * value resolves to `high`, the rung the desktop's select defaults to and the
149
+ * one the shared engine applies to an unstated effort (desktop/lib/local/
150
+ * engine.js reasoningBudget/nativeEffort both floor to high).
151
+ *
152
+ * WHY THIS IS NOT OPTIONAL: the pooled dispatch in the shared engine states the
153
+ * rung conditionally (`...(opts.effort ? { effort: opts.effort } : {})`), and
154
+ * the BYOK dispatch translates it (nativeEffort). A falsy value therefore is
155
+ * not "the default" — it is "state no opinion", and the server then sizes the
156
+ * turn itself. `auto` was the CLI's DEFAULT, so the default turn was the one
157
+ * turn that sent nothing: /effort changed the status line and nothing else.
158
+ *
159
+ * Mirrors effortRung() in desktop/renderer/budget.js (and the `=== 'low' ||
160
+ * === 'medium' ? : 'high'` floor in the shared engine). Carried rather than
161
+ * shared because the CLI must not require the renderer bundle — the same reason
162
+ * cli/src/tokens.js re-exports the shared usage folds instead of reaching into
163
+ * desktop/.
164
+ */
165
+ function effortRung(effort) {
166
+ return effort === 'low' || effort === 'medium' ? effort : 'high';
167
+ }
168
+
169
+ module.exports = { createEngine, HOST_CLASSES, DEFAULT_CLASS, CLASS_LABELS, byokNamespace, effortRung };
@@ -44,6 +44,10 @@
44
44
  */
45
45
 
46
46
  const { resolveShared } = require('./sharedpaths.js');
47
+ // The renderers' waiver rule, published to on every reading this gate takes —
48
+ // see `createCliEntitlement` below. `format.js` requires nothing from here, so
49
+ // this is a one-way edge and not a cycle.
50
+ const { noteTier } = require('./format.js');
47
51
 
48
52
  /** The shared decision, resolved by existence (repo checkout or staged tree). */
49
53
  function loadModule() {
@@ -97,12 +101,37 @@ function buildProbe(aegis) {
97
101
  function createCliEntitlement({ aegis, now, ttlMs } = {}) {
98
102
  const mod = loadModule();
99
103
  const client = aegis || loadClient();
100
- return mod.createEntitlement({
104
+ const gate = mod.createEntitlement({
101
105
  probe: buildProbe(client),
102
106
  host: 'cli',
103
107
  ...(now ? { now } : {}),
104
108
  ...(ttlMs ? { ttlMs } : {}),
105
109
  });
110
+ // Publish every reading this gate takes to the renderers' waiver rule
111
+ // (`format.js` → `feeWaived`). The gate is what decides whether a turn is
112
+ // ALLOWED; the waiver decides whether a `€0.0031` is PRINTED under it, and the
113
+ // two reading different tiers is how a trial account ended up shown a fee it
114
+ // does not owe. Wrapping the instance rather than returning a copy keeps the
115
+ // method identity the rest of the host already holds a reference to.
116
+ if (gate && typeof gate.current === 'function') {
117
+ const read = gate.current.bind(gate);
118
+ try {
119
+ gate.current = (...args) => {
120
+ const snap = read(...args);
121
+ noteTier(snap);
122
+ return snap;
123
+ };
124
+ if (typeof gate.refresh === 'function') {
125
+ const refresh = gate.refresh.bind(gate);
126
+ gate.refresh = async (...args) => {
127
+ const out = await refresh(...args);
128
+ try { noteTier(read()); } catch { /* a failed read publishes nothing */ }
129
+ return out;
130
+ };
131
+ }
132
+ } catch { /* a frozen instance is readable, just not publishable */ }
133
+ }
134
+ return gate;
106
135
  }
107
136
 
108
137
  // ── the payment surface ─────────────────────────────────────────────────────
package/src/format.js CHANGED
@@ -33,8 +33,180 @@ function fmtEurSigned(n) {
33
33
  return `${v < 0 ? '-' : '+'}${fmtEur(Math.abs(v))}`;
34
34
  }
35
35
 
36
- /** Compact duration: 850 -> "0.9s", 65000 -> "1m05s". */
37
- function fmtElapsed(ms) {
36
+ /**
37
+ * The per-turn token figure the accounting rows report: `312 tokens` — the
38
+ * OUTPUT half only.
39
+ *
40
+ * The input half is gone deliberately, not by omission. It is the prompt
41
+ * restated, on a cached turn it is the larger number by an order of magnitude,
42
+ * and it is the one figure in the row nobody can act on: you change what a turn
43
+ * costs by changing what it PRODUCES, while the input count grows on its own as
44
+ * the session does. Both meta rows printed it, so the same turn showed
45
+ * `156,189 tok · 151,175 in · 5,014 tokens` and read as a runaway — the eye landed
46
+ * on 151,175, which is the prompt, not the spend. The rows now report what the
47
+ * turn produced. `/cost` still carries the full miss/hit breakdown for anyone
48
+ * who wants it: that is a panel you open, not a line painted under every
49
+ * answer.
50
+ *
51
+ * The labels remain part of the job — both rows once printed the bare pair
52
+ * `1,250/312` in one colour, and an unlabelled figure only states what it
53
+ * measures to a reader who already knows the convention.
54
+ *
55
+ * The wording lives here, not in the two renderers that call it, because those
56
+ * two are documented as never drifting apart and this is the only part of the
57
+ * row they both spell out identically.
58
+ *
59
+ * Returns `null` when the output is not a number, so a caller falls back to the
60
+ * total it does have rather than print a figure it never measured — an absent
61
+ * half is omitted rather than rendered as `0`, because `0 tokens` states a figure
62
+ * the provider never reported and this codebase refuses that shape elsewhere:
63
+ * `fmtRoll` will not put `0 tokens` on a meter that never took a reading, for the
64
+ * same reason.
65
+ *
66
+ * The name is left over from when this returned both halves: it is re-exported
67
+ * to the desktop's renderer, and a rename for a wording change would be a
68
+ * compatibility break for nothing.
69
+ *
70
+ * @param {object} [usage] flat `{ input, output }`, or an object carrying them
71
+ * @returns {{output: string}|null}
72
+ */
73
+ function fmtUsageSplit(usage) {
74
+ const src = usage && typeof usage === 'object' ? usage : {};
75
+ if (!Number.isFinite(src.output)) return null;
76
+ return { output: `${fmtTokens(src.output || 0)} tokens` };
77
+ }
78
+
79
+ /**
80
+ * The OUTPUT half of a usage record, or `null` — never the wire's total.
81
+ *
82
+ * The twin of `desktop/renderer/usage.js`'s `displayTokens`, and here for the
83
+ * reason that file states at length: the row under a turn reports what the turn
84
+ * PRODUCED. `tokens` is input + output, and on a cached or long-context turn the
85
+ * prompt restated is the larger half — falling back to it printed `3,145 tokens`
86
+ * for a turn that wrote 145, which is the input half back on the screen with no
87
+ * label. Both CLI renderers (`renderMeta` in render.js, `metaBits` in
88
+ * chatflow.js) used to do exactly that once `output` was missing, and it was the
89
+ * last surviving place the input half reached a row: the split had been dropped,
90
+ * and the total they fell back to still carried it.
91
+ *
92
+ * `null` rather than `0` when no output figure arrived — `0 tokens` states a
93
+ * figure no provider sent, the rule `fmtUsageSplit` and `fmtRoll` already hold.
94
+ * A turn the wire priced but did not itemise has no output figure, and inventing
95
+ * one from the total would be a number that provider never sent.
96
+ *
97
+ * @param {object} [source] flat `{output}`, or a record carrying `tokens:{output}`
98
+ * @returns {number|null}
99
+ */
100
+ function displayTokens(source) {
101
+ const src = source && typeof source === 'object' ? source : {};
102
+ const nested = src.tokens && typeof src.tokens === 'object' ? src.tokens : null;
103
+ const candidates = [src.output];
104
+ if (nested) candidates.push(nested.output, nested.output_tokens, nested.completion_tokens);
105
+ else candidates.push(src.output_tokens, src.completion_tokens);
106
+ for (const c of candidates) {
107
+ if (typeof c === 'number' && isFinite(c) && c > 0) return c;
108
+ }
109
+ return null;
110
+ }
111
+
112
+ /**
113
+ * The account's tier, as the host last read it off the server. Held here
114
+ * because the RENDERERS need it and they run synchronously, on a path that
115
+ * cannot await a probe: `cli/src/entitlement.js` publishes every reading it
116
+ * takes (`noteTier`), and the money rule below spends it.
117
+ */
118
+ let tierSnapshot = null;
119
+
120
+ /**
121
+ * Publish the entitlement snapshot for the renderers. Called by the host's
122
+ * entitlement gate on every `current()`/`refresh()`, so the waiver rule and the
123
+ * gate the host enforces can never read two different tiers.
124
+ */
125
+ function noteTier(entitlement) {
126
+ tierSnapshot = entitlement && typeof entitlement === 'object' ? entitlement : null;
127
+ return tierSnapshot;
128
+ }
129
+
130
+ /**
131
+ * True when this account's tier means AEGIS bills no per-turn fee, so no money
132
+ * figure belongs on a turn row or a session total.
133
+ *
134
+ * The CLI's half of the desktop's rule (`desktop/renderer/usage.js`), and it is
135
+ * the same rule deliberately: the two hosts render the same turn from the same
136
+ * engine, so a row that shows a fee on one and waives it on the other is a
137
+ * disagreement about what the user owes. The desktop had this gate and the CLI
138
+ * did not, which is why a trial account saw `€0.0031` under every answer here
139
+ * and no money there.
140
+ *
141
+ * The fee is the BYOK handling fee, waived by aegis1 on Unlimited — and the tier
142
+ * a 30-day welcome trial grants IS Unlimited (`subscriptions` row), so a trial
143
+ * account resolves here exactly like a paying one. Matching is on the resolved
144
+ * tier rather than `pro`, and a funded bank on a free plan is NOT waived: that
145
+ * account pays from its bank, and hiding the number would leave it with no meter
146
+ * for the only money it spends.
147
+ *
148
+ * @param {{tier?: string|null, plan?: string|null, planRaw?: string|null,
149
+ * subscription?: string|null, item?: string|null, sku?: string|null,
150
+ * unlimited?: boolean}} [entitlement] the snapshot to read; omitted, the last
151
+ * one the host published (see `noteTier`).
152
+ * @returns {boolean}
153
+ */
154
+ function feeWaived(entitlement) {
155
+ const ent = entitlement === undefined ? tierSnapshot : entitlement;
156
+ if (!ent || typeof ent !== 'object') return false;
157
+ if (ent.unlimited === true) return true;
158
+ const named = [
159
+ ent.tier,
160
+ ent.plan,
161
+ ent.planRaw,
162
+ ent.subscription,
163
+ ent.subscriptionTier,
164
+ ent.product,
165
+ ent.item,
166
+ ent.sku,
167
+ ]
168
+ .filter((v) => typeof v === 'string')
169
+ .map((v) => v.trim().toLowerCase());
170
+ if (named.some((v) => v === 'unlimited' || v === 'trial')) return true;
171
+ // A tier string that merely CONTAINS the word — `unlimited_trial`,
172
+ // `plan.unlimited` — so a server that decorates the name cannot put the fee
173
+ // back on an account whose tier is Unlimited.
174
+ return named.some((v) => /(^|[^a-z])unlimited([^a-z]|$)/.test(v));
175
+ }
176
+
177
+ /**
178
+ * Whether a money figure belongs on this account's turn row or session total.
179
+ *
180
+ * A price is printed UNLESS AEGIS either waives it or has not proven it owed:
181
+ *
182
+ * - a tier AEGIS waives (`feeWaived`) → no price. Unlimited, paid or on the
183
+ * 30-day welcome trial, has no per-turn charge and no bank draw;
184
+ * - a snapshot that asserts a plan it cannot prove (`degraded`, i.e. the
185
+ * entitlement module's unresolved placeholder, whose `plan` reads `free`
186
+ * before any probe has answered) → no price. That placeholder says "no
187
+ * verdict yet", not "this account is free", and reading it as a verdict is
188
+ * what put `€0.0031` under a trial account's answers before its probe had
189
+ * replied — a fee charged in writing to the one account that does not pay it;
190
+ * - everything else → the price stands, including when NOTHING was claimed at
191
+ * all. A cost figure is a measurement of the turn, and silently dropping a
192
+ * real number because no tier was published would leave a BYO-key or offline
193
+ * run with no meter for money it actually spent.
194
+ *
195
+ * The token figure is never gated by this, on any branch: what a turn produced
196
+ * is not a price, and hiding it would leave an Unlimited account with no meter.
197
+ *
198
+ * @param {{tier?: string|null, plan?: string|null, planRaw?: string|null,
199
+ * degraded?: boolean, source?: string|null, unlimited?: boolean}} [entitlement]
200
+ * @returns {boolean}
201
+ */
202
+ function feeBillable(entitlement) {
203
+ const ent = entitlement === undefined ? tierSnapshot : entitlement;
204
+ if (!ent || typeof ent !== 'object') return true;
205
+ if (feeWaived(ent)) return false;
206
+ return ent.degraded !== true;
207
+ }
208
+
209
+ /** Compact duration: 850 -> "0.9s", 65000 -> "1m05s". */function fmtElapsed(ms) {
38
210
  const s = Math.max(0, Number(ms) || 0) / 1000;
39
211
  if (s < 10) return `${s.toFixed(1)}s`;
40
212
  if (s < 60) return `${Math.round(s)}s`;
@@ -81,4 +253,4 @@ function shortCwd() {
81
253
  return cwdName(process.cwd());
82
254
  }
83
255
 
84
- module.exports = { fmtTokens, fmtEur, fmtEurSigned, fmtElapsed, maskKey, pathName, cwdName, shortCwd };
256
+ module.exports = { fmtTokens, fmtEur, fmtEurSigned, fmtElapsed, fmtUsageSplit, displayTokens, feeWaived, feeBillable, noteTier, maskKey, pathName, cwdName, shortCwd };
package/src/overlays.js CHANGED
@@ -215,23 +215,29 @@ function renderModelPicker(models, sel = 0, width = 80, height = 24, current = n
215
215
 
216
216
  // ── Effort picker overlay (/effort) ──────────────────────────────────────────
217
217
 
218
+ // The three rungs, in the order the picker draws them. `High` is the default
219
+ // (config.js seeds `effort: 'high'`, and engine.js/desktop/renderer both resolve
220
+ // an unknown rung to high), so the list is exactly the levels that can be in
221
+ // force — there is no fourth "auto" row any more. "auto" was not a level: it
222
+ // meant "send no rung", and because it was the default, a fresh install sent no
223
+ // effort at all and the knob did nothing until it was set by hand.
218
224
  const EFFORT_LEVELS = [
219
- { label: 'Auto', value: null, note: 'Sized per turn from the ask (default)' },
220
225
  { label: 'Low', note: 'Fastest, cheapest budget' },
221
226
  { label: 'Medium', note: 'Balanced' },
222
- { label: 'High', note: 'Highest budget, slowest' },
227
+ { label: 'High', note: 'Highest budget, slowest (default)' },
223
228
  ];
224
229
 
225
230
  // The picker's order reduced to the values a selection means, so the row a user
226
231
  // picks and the value the session stores can never come from two different
227
232
  // lists (commands.js validates against this, chatflow.js resolves the overlay
228
- // through it). `null` is "auto" — no rung pinned.
233
+ // through it).
229
234
  const EFFORT_VALUES = EFFORT_LEVELS.map((lv) => (lv.value === undefined ? lv.label.toLowerCase() : lv.value));
230
235
 
231
236
  /**
232
237
  * @param {number} sel selected index
233
238
  * @param {number} width
234
- * @param {string|null} current the currently-selected effort level (null = auto)
239
+ * @param {string|null} current the currently-selected effort level (null = the
240
+ * high default, which is what the engine applies)
235
241
  * @param {Array} [levels] override the level table
236
242
  */
237
243
  function renderEffortPicker(sel = 0, width = 80, current = null, levels = EFFORT_LEVELS) {
@@ -243,11 +249,9 @@ function renderEffortPicker(sel = 0, width = 80, current = null, levels = EFFORT
243
249
  for (let i = 0; i < levels.length; i++) {
244
250
  const lv = levels[i];
245
251
  const active = i === sel;
246
- // `current == null` is auto, which is the first row's own value — matching
247
- // on the label alone would never mark the default as the current choice.
248
- const cur = current == null
249
- ? lv.value === null
250
- : String(current).toLowerCase() === String(lv.label).toLowerCase();
252
+ // `current == null` means no rung is stored, which is the high default the
253
+ // engine resolves — so the check mark lands on High rather than on nothing.
254
+ const cur = String(current || 'high').toLowerCase() === String(lv.label).toLowerCase();
251
255
  const left = active ? span(C.lavender, GLYPH.cursor) : span('', ' ');
252
256
  const nameSpan = active ? span(C.lavender, lv.label) : span(C.white, lv.label);
253
257
  const mark = cur ? span(C.green, ' ' + GLYPH.check) : span('', '');