aegiscode 7.0.8 → 7.0.9

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/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "aegiscode",
3
3
  "productName": "AEGIS Code",
4
- "version": "7.0.8",
4
+ "version": "7.0.9",
5
5
  "description": "aegiscode — the command-line version of AEGIS Desktop. The shared tool surface in your shell, over the same thin transport and tool registry as the MCP plugin and the desktop app. Ships transport + UI only; no brain.",
6
6
  "author": {
7
7
  "name": "AEGIS Code",
package/src/app.js CHANGED
@@ -982,6 +982,13 @@ function createApp(options = {}) {
982
982
  let chars = 0;
983
983
  let partial = '';
984
984
  let reasoning = 0;
985
+ // Thinking tokens the PROVIDER measured, added verbatim. A subscription
986
+ // turn withholds its deliberation text (`thinking_delta.thinking` is the
987
+ // empty string), so the `reasoning` char count above stays 0 for the whole
988
+ // thinking phase and the spinner read `↓0 tokens` while thousands of
989
+ // thinking tokens were billed. Not routed through `w()`/4: this is already
990
+ // a token count, and dividing it would print a quarter of the truth.
991
+ let thinkingTokens = 0;
985
992
  let verb = VERBS[Math.floor(Math.random() * VERBS.length)];
986
993
  let sawReasoning = false;
987
994
  let usedTools = false;
@@ -1005,7 +1012,10 @@ function createApp(options = {}) {
1005
1012
  // distinguishable — but leaving it out of the figure here stalled the
1006
1013
  // spinner on `↓0 tokens` for the whole thinking phase of every turn,
1007
1014
  // which is the row that exists to show the turn is moving.
1008
- streamed: estimateTokensFromCells(chars + reasoning),
1015
+ streamed: estimateTokensFromCells(chars + reasoning) + thinkingTokens,
1016
+ // See render.js: any contribution from `thinkingTokens` is Anthropic's
1017
+ // own under-counting running estimate, not the real billed figure.
1018
+ streamedFloor: thinkingTokens > 0,
1009
1019
  }),
1010
1020
  ]);
1011
1021
  };
@@ -1043,6 +1053,13 @@ function createApp(options = {}) {
1043
1053
  if (p.reasoning) return p.reasoning(r);
1044
1054
  return undefined;
1045
1055
  },
1056
+ // Token-count channel, distinct from `reasoning` above (which is text).
1057
+ // A presenter drives its own spinner, so it must receive this or the live
1058
+ // figure stays at 0 for the whole thinking phase of a subscription turn.
1059
+ thinkingTokens: (n) => {
1060
+ if (p.thinkingTokens) return p.thinkingTokens(n);
1061
+ return undefined;
1062
+ },
1046
1063
  tool: (tool) => {
1047
1064
  if (p.tool) return p.tool(tool);
1048
1065
  if (live) live.clear();
@@ -1099,6 +1116,19 @@ function createApp(options = {}) {
1099
1116
  // same function the tests import is the one the live path calls.
1100
1117
  const onDelta = (chunk) => {
1101
1118
  if (!chunk) return;
1119
+ // Provider-measured thinking progress — the ONLY live signal on a
1120
+ // subscription turn, whose deliberation text is withheld. Counted and
1121
+ // repainted, but never handed to `present.reasoning`: that channel is
1122
+ // text and its consumers accumulate display width from it.
1123
+ if (chunk.thinkingTokens) {
1124
+ thinkingTokens += chunk.thinkingTokens;
1125
+ if (!sawReasoning) {
1126
+ sawReasoning = true;
1127
+ verb = 'Reasoning';
1128
+ }
1129
+ present.thinkingTokens(chunk.thinkingTokens);
1130
+ paint();
1131
+ }
1102
1132
  if (chunk.reasoning) {
1103
1133
  reasoning += w(chunk.reasoning);
1104
1134
  // The pool's worker findings arrive on the reasoning channel before
@@ -1110,8 +1140,7 @@ function createApp(options = {}) {
1110
1140
  }
1111
1141
  present.reasoning(chunk.reasoning);
1112
1142
  }
1113
- if (chunk.delta) {
1114
- chars += w(chunk.delta);
1143
+ if (chunk.delta) { chars += w(chunk.delta);
1115
1144
  partial += chunk.delta;
1116
1145
  present.text(chunk.delta);
1117
1146
  }
package/src/chatflow.js CHANGED
@@ -386,7 +386,7 @@ function spinnerLine(state, ctx) {
386
386
  // from the spinner while the model was working.
387
387
  const tail = ctx && ctx.thinking
388
388
  ? span(t.gray, ` (${secs}s · thinking)`)
389
- : span(t.gray, ` (${secs}s · ↓${fmtTokens(state.streamed || 0)} tokens)`);
389
+ : span(t.gray, ` (${secs}s · ↓${state.streamedFloor ? '≥' : ''}${fmtTokens(state.streamed || 0)} tokens)`);
390
390
  const glyph = GLYPH.spin[(state.frame || 0) % GLYPH.spin.length];
391
391
  return [span(t.coral, glyph), ...tinted, span(t.white, '… '), tail];
392
392
  }
@@ -1189,7 +1189,8 @@ async function runSession(host) {
1189
1189
  // Both spinner renderers label this field `tokens`, so handing them
1190
1190
  // cells printed the character count as a token count and the live
1191
1191
  // figure read ~4x high.
1192
- streamed: estimateTokensFromCells(streamedCells()),
1192
+ streamed: estimateTokensFromCells(streamedCells()) + thinkingTokens,
1193
+ streamedFloor: thinkingTokens > 0,
1193
1194
  },
1194
1195
  ctx
1195
1196
  )
@@ -1336,6 +1337,12 @@ async function runSession(host) {
1336
1337
  // reset per turn and never reaches the accounting row, which is built from
1337
1338
  // what the provider measured.
1338
1339
  let streamedChars = 0;
1340
+ // Thinking tokens the PROVIDER measured, added verbatim. `streamedChars` is a
1341
+ // display width that becomes tokens at 4:1, which cannot express this: a
1342
+ // subscription turn sends `thinking_delta.thinking` as the empty string and
1343
+ // reports progress in `estimated_tokens` instead, so the char counter stayed
1344
+ // at 0 for the entire thinking phase while thousands of tokens were billed.
1345
+ let thinkingTokens = 0;
1339
1346
  const streamedCells = () => streamedChars;
1340
1347
  // ── the turn ──
1341
1348
 
@@ -1445,6 +1452,7 @@ async function runSession(host) {
1445
1452
  spinnerFrame = 0;
1446
1453
  startedAt = Date.now();
1447
1454
  streamedChars = 0;
1455
+ thinkingTokens = 0;
1448
1456
  toolSeq = 0;
1449
1457
  turnTools = [];
1450
1458
  verb = VERBS[turnCount % VERBS.length];
@@ -1486,6 +1494,12 @@ async function runSession(host) {
1486
1494
  // nothing needs a different explanation from one that produced nothing at
1487
1495
  // all.
1488
1496
  reasoning: (delta) => { sawReasoning = true; streamedChars += w(delta); },
1497
+ // Provider-measured thinking progress, in tokens. Separate from
1498
+ // `reasoning` above because that one is TEXT (accumulated as display
1499
+ // width, converted at 4:1) and this is already a token count. On a
1500
+ // subscription turn this is the only live signal that arrives during the
1501
+ // thinking phase — the text channel sends empty strings throughout.
1502
+ thinkingTokens: (n) => { sawReasoning = true; thinkingTokens += n; scheduleRender(); },
1489
1503
  tool: (tool) => {
1490
1504
  // One entry per tool call, not one per frame. The engine opens a `run`
1491
1505
  // frame before the tool executes and closes it with a `done` frame
package/src/commands.js CHANGED
@@ -531,6 +531,63 @@ async function offeredModelIds(c, provider, key) {
531
531
  return res && res.ok && Array.isArray(res.ids) && res.ids.length ? res.ids : undefined;
532
532
  }
533
533
 
534
+ /**
535
+ * One argument string, tokenized with the SAME quote rule the app's own parser
536
+ * uses (`app.js` tokenize): a quoted run is one token and the quotes are not
537
+ * part of it.
538
+ *
539
+ * `_rest` is the raw remainder of the line (app.js parseArgs keeps it
540
+ * verbatim), so the only unambiguous way to type a base URL — `/model-add
541
+ * custom "https://my-vllm.example/v1" sk-… llama-3-70b` — arrives here still
542
+ * wrapped in its quotes. Splitting on whitespace alone stores the quote
543
+ * characters as part of the URL: the row then looks saved while every call on
544
+ * it is refused upstream, which is the silent no-op this whole command exists
545
+ * to avoid. The app's tokenizer is not reachable from here (it is a closure in
546
+ * app.js), so the rule is restated once, beside the only command that needs it.
547
+ */
548
+ function splitCommandWords(rest) {
549
+ const out = [];
550
+ let cur = '';
551
+ let quote = null;
552
+ let has = false;
553
+ for (const ch of String(rest == null ? '' : rest)) {
554
+ if (quote) {
555
+ if (ch === quote) quote = null;
556
+ else cur += ch;
557
+ continue;
558
+ }
559
+ if (ch === '"' || ch === "'") { quote = ch; has = true; continue; }
560
+ if (/\s/.test(ch)) {
561
+ if (cur || has) { out.push(cur); cur = ''; has = false; }
562
+ continue;
563
+ }
564
+ cur += ch;
565
+ has = true;
566
+ }
567
+ if (cur || has) out.push(cur);
568
+ return out;
569
+ }
570
+
571
+ /**
572
+ * The base URL this machine already holds for a provider, or ''.
573
+ *
574
+ * Only `custom` needs it, and only to answer one question: `/model-add custom
575
+ * <word>` with a single leftover word is ambiguous on a machine with no
576
+ * endpoint configured — the word could be the base URL (key and model still to
577
+ * come) or a model id for an endpoint nobody has named — and unambiguous once
578
+ * one IS configured, because then the word can be nothing but a model id.
579
+ */
580
+ function savedByokBaseURL(c, provider) {
581
+ try {
582
+ const store = c && c.settings && c.settings();
583
+ if (!store || typeof store.get !== 'function' || typeof c.byokNamespace !== 'function') return '';
584
+ const row = store.get(c.byokNamespace(provider)) || {};
585
+ return String(row.baseURL || '').trim();
586
+ } catch {
587
+ return '';
588
+ }
589
+ }
590
+
534
591
  /**
535
592
  * Declare ids into the store, skipping the ones already there. Returns the
536
593
  * count added, plus what was skipped and WHY, so the caller can say
@@ -3240,19 +3297,33 @@ const COMMANDS = [
3240
3297
  // the next refresh and the window shows it on ITS next refresh. The file is
3241
3298
  // printed on success, because a hand-edit is the bulk path and a store the
3242
3299
  // user cannot find is a store they will not use.
3243
- name: 'model-add', aliases: ['add-model'], args: ['provider'], hint: '<provider> [model-id|*]',
3300
+ name: 'model-add', aliases: ['add-model'], args: ['provider'],
3301
+ hint: '<provider> [api-key] [model-id|*] (custom: <base-url> <api-key> [model-id|*])',
3244
3302
  category: 'model',
3245
- desc: 'Offer a model id the AEGIS catalog does not name (asks the vendor when it can)',
3303
+ desc: 'Save a provider key and offer a model id in one step (asks the vendor when it can)',
3246
3304
  handler: async (c, a) => {
3247
3305
  const args = a || {};
3248
3306
  const typed = String(args.provider || '').trim();
3249
3307
  if (!typed) {
3250
- c.push({ role: 'error', text: 'Usage: /model-add <provider> <model-id> — /byok lists the providers.' });
3308
+ c.push({
3309
+ role: 'error',
3310
+ text: 'Usage: /model-add <provider> [api-key] <model-id> — /byok lists the providers. '
3311
+ + 'A vendor this catalog does not name yet: /model-add custom <https-base-url> <api-key> <model-id>. '
3312
+ + 'Example: /model-add deepseek sk-xxxxxxxx deepseek-v4.3-preview',
3313
+ });
3251
3314
  return true;
3252
3315
  }
3253
3316
  const rest = String(args._rest || '').trim();
3254
- const sp = rest.indexOf(' ');
3255
- let model = sp === -1 ? '' : rest.slice(sp + 1).trim();
3317
+ // Quote-aware, because the one word on this line that MAY need quoting is
3318
+ // the base URL — see splitCommandWords.
3319
+ const words = splitCommandWords(rest);
3320
+ // `words[0]` is the provider token itself, echoed into `_rest` the same
3321
+ // way `/byok-key` reads it — everything after it is ours to read. A
3322
+ // `_rest` without it (a caller that passes only the trailing words) is
3323
+ // tolerated rather than misread as the provider being the model id.
3324
+ let extra = words.length && words[0].toLowerCase() === typed.toLowerCase()
3325
+ ? words.slice(1)
3326
+ : words;
3256
3327
  // Resolve the provider against the relay's catalog first. A slug the
3257
3328
  // server does not list can never be attached to a key, so storing it
3258
3329
  // would produce a declaration that is invisible in every picker — the
@@ -3273,6 +3344,95 @@ const COMMANDS = [
3273
3344
  return true;
3274
3345
  }
3275
3346
  const id = (match && match.provider && match.provider.id) || typed.toLowerCase();
3347
+ // ── fold the key-save step in, so one command does both ──────────────
3348
+ //
3349
+ // Before this, a never-configured provider needed /byok-key THEN
3350
+ // /model-add — two commands for one outcome the user has in mind as
3351
+ // one. Two extra words can only mean key-then-model (the one-word shape
3352
+ // just below is already the model-id-alone case this command always
3353
+ // had, and guessing "key or model id" from a single token is the
3354
+ // ambiguity this rule avoids rather than resolves): `/model-add
3355
+ // deepseek sk-… deepseek-v4.3-preview` saves the key and declares the
3356
+ // model in the same breath, and shows up in the picker right after —
3357
+ // no separate /byok-key round trip.
3358
+ //
3359
+ // "custom" (a vendor this catalog does not name, or a self-hosted
3360
+ // OpenAI-compatible endpoint) reads one word EARLIER than every other
3361
+ // provider: the base URL aegis1 has no constant for and must be told
3362
+ // per call (`_byok_custom_base_url` there validates it — https, no
3363
+ // loopback/private/link-local target). It gets its own branch rather
3364
+ // than folding into the generic rule below, because with the base URL
3365
+ // in play a lone leftover word is still ambiguous between "no model"
3366
+ // and "no key" in a way the generic one-word-is-the-model-id rule
3367
+ // cannot resolve.
3368
+ let typedBaseURL = '';
3369
+ let typedKey = '';
3370
+ if (id === 'custom') {
3371
+ // ONE leftover word for `custom` is genuinely ambiguous, so it is
3372
+ // refused rather than guessed: with no endpoint on this machine the
3373
+ // word could be the base URL (key and model still to come) or a model
3374
+ // id for an endpoint nobody has named — and the guess that writes a
3375
+ // model row against no endpoint is a row that cannot be called. Once an
3376
+ // endpoint IS saved the ambiguity is gone, because a second endpoint
3377
+ // needs its key with it (the two-word branch below), so a lone word can
3378
+ // only be a model id. Named, not silently dropped.
3379
+ if (extra.length === 1 && !savedByokBaseURL(c, id)) {
3380
+ c.push({
3381
+ role: 'error',
3382
+ text: 'one word cannot say whether it is the URL or the model id — nothing was saved. '
3383
+ + 'Type the endpoint first: /model-add custom <https-base-url> <api-key> [model-id]',
3384
+ });
3385
+ return true;
3386
+ }
3387
+ if (extra.length >= 2) {
3388
+ typedBaseURL = extra.shift();
3389
+ typedKey = extra.shift();
3390
+ }
3391
+ } else if (extra.length >= 2) {
3392
+ typedKey = extra.shift();
3393
+ }
3394
+ let model = extra.join(' ').trim();
3395
+ if (typedKey) {
3396
+ const keyStore = c.settings && c.settings();
3397
+ if (!keyStore || typeof keyStore.set !== 'function') {
3398
+ c.push({ role: 'error', text: 'this client has no provider-key store.' });
3399
+ return true;
3400
+ }
3401
+ const p = match && match.provider;
3402
+ if (p && p.key_prefix && !typedKey.startsWith(p.key_prefix)) {
3403
+ c.push({ role: 'note', text: `heads up: ${id} keys normally start with "${p.key_prefix}" — saved anyway.` });
3404
+ }
3405
+ if (typedBaseURL && !/^https:\/\//i.test(typedBaseURL)) {
3406
+ c.push({ role: 'note', text: `heads up: aegis1 only dials an https:// base_url — saved anyway, but calls on it will be refused.` });
3407
+ }
3408
+ keyStore.set(c.byokNamespace(id), { key: typedKey, ...(typedBaseURL ? { baseURL: typedBaseURL } : {}) });
3409
+ // Mirror it into ~/.aegiscode/.env too — the same file the model picker
3410
+ // writes (models.js storeModelKey) and byokKeyForProvider() already
3411
+ // falls back to reading. Without this a key saved here was invisible to
3412
+ // anything that only reads process.env/.env (a shell, the other host
3413
+ // before its settings store syncs), even though the two files name the
3414
+ // same provider through the identical envVarFor() mapping. Best-effort:
3415
+ // the settings-store save above is the row of record, so a failure here
3416
+ // (e.g. an unwritable .env) is reported but never undoes it.
3417
+ try {
3418
+ const { envVarFor, setEnvValue } = require(resolveShared(path.join('client', 'env-file.js')));
3419
+ const envName = envVarFor(id);
3420
+ if (envName) {
3421
+ const res = setEnvValue(envName, typedKey);
3422
+ if (!res.ok) {
3423
+ c.push({ role: 'note', text: `heads up: could not mirror the key into ~/.aegiscode/.env (${res.error}).` });
3424
+ }
3425
+ }
3426
+ } catch {
3427
+ /* the settings-store save is the row of record; this mirror is best-effort */
3428
+ }
3429
+ c.push({
3430
+ role: 'done',
3431
+ text: typedBaseURL
3432
+ ? `saved a ${id} key and base URL (${typedBaseURL}) on this machine.`
3433
+ : `saved a ${id} key on this machine.`,
3434
+ });
3435
+ }
3276
3436
  // ── what the vendor says, before we ask the user to remember it ──────
3277
3437
  //
3278
3438
  // The whole cost of this feature used to be "know the vendor's model id",
@@ -3336,8 +3496,13 @@ const COMMANDS = [
3336
3496
  // A bare number picks the row it is listed under. Only an in-range
3337
3497
  // integer is read that way, so an id that happens to start with a digit
3338
3498
  // is still stored verbatim unless it is exactly a listed position.
3339
- const n = /^\d+$/.test(typedId) ? Number(typedId) : 0;
3340
- model = n >= 1 && n <= offered.length ? offered[n - 1] : typedId;
3499
+ // `offered` is undefined whenever the vendor could not be asked (no
3500
+ // key, no endpoint, no network) — reading `.length` off it here threw a
3501
+ // TypeError out of the handler, which reads to the user as the command
3502
+ // crashing rather than as the id being stored, so the position rule is
3503
+ // applied only when there is a list to be a position IN.
3504
+ const n = offered && /^\d+$/.test(typedId) ? Number(typedId) : 0;
3505
+ model = offered && n >= 1 && n <= offered.length ? offered[n - 1] : typedId;
3341
3506
  }
3342
3507
  if (!model) {
3343
3508
  c.push({ role: 'note', text: 'nothing saved.' });
package/src/render.js CHANGED
@@ -406,7 +406,15 @@ function renderWorking(ctx, state = {}) {
406
406
  const verb = state.verb || VERBS[0];
407
407
  const tail = [];
408
408
  if (state.elapsedMs != null) tail.push(fmtElapsed(state.elapsedMs));
409
- if (state.streamed != null) tail.push(`↓${fmtTokens(state.streamed)} tokens`);
409
+ // `streamedFloor` marks a figure that has folded in Anthropic's own
410
+ // `thinking_delta.estimated_tokens` (desktop/lib/local/claude-pro.js) — a
411
+ // running count that measurement showed landing under the real billed
412
+ // thinking-token total (1900 vs 1943, 1800 vs 1832, 250 vs 339). Flagged
413
+ // with `≥` rather than shown as an exact figure, because the true number
414
+ // only arrives with the turn's final `usage`.
415
+ if (state.streamed != null) {
416
+ tail.push(`↓${state.streamedFloor ? '≥' : ''}${fmtTokens(state.streamed)} tokens`);
417
+ }
410
418
  const tailStr = tail.length ? ` ${t.gray}(${tail.join(` ${GLYPH.bullet} `)})${RESET}` : '';
411
419
  return (
412
420
  `${t.coral}${frame}${RESET} ${t.white}${verb}${RESET}${t.white}…${RESET}${tailStr}` +
@@ -1133,6 +1133,7 @@ function createClient(opts = {}) {
1133
1133
  onStream,
1134
1134
  signal,
1135
1135
  providerKey,
1136
+ baseURL,
1136
1137
  } = {}) {
1137
1138
  const key = providerKey !== undefined ? providerKey : opts.providerKey;
1138
1139
  // Same rule as the pooled path above: omit `max_tokens` entirely when the
@@ -1169,6 +1170,11 @@ function createClient(opts = {}) {
1169
1170
  // `tools: []` differently from the field's plain absence.
1170
1171
  ...(Array.isArray(tools) && tools.length ? { tools } : {}),
1171
1172
  ...(toolChoice ? { tool_choice: toolChoice } : {}),
1173
+ // Read server-side ONLY for provider "custom" (aegis1 app.py
1174
+ // byok_chat_completions) — every other provider's upstream host is a
1175
+ // constant the server already knows, so sending this for them is a
1176
+ // no-op rather than a behaviour change.
1177
+ ...(baseURL ? { base_url: baseURL } : {}),
1172
1178
  };
1173
1179
  if (model) body.model = model;
1174
1180
  const headers = {
@@ -27,7 +27,7 @@
27
27
  *
28
28
  * ── what a user does now ───────────────────────────────────────────────────
29
29
  *
30
- * CLI `/model-add <provider> <model-id>` (and `/model-rm …`)
30
+ * CLI `/model-add <provider> [api-key] <model-id>` (and `/model-rm …`)
31
31
  * Desktop Settings → "Add a model" → provider + id
32
32
  * Either hand-edit `$AEGISCODE_HOME/models.json` (default `~/.aegiscode`)
33
33
  *
@@ -317,11 +317,25 @@ function turnArgs(payload) {
317
317
  * "the first collecting block" pairs a fragment with the wrong call.
318
318
  * - one `user` line can carry a tool_result for EVERY call in a parallel
319
319
  * round, so all of them are resolved, not just the first.
320
+ *
321
+ * `thinking_delta` is the third delta type and is NOT folded into `text`: an
322
+ * extended-thinking block is deliberation, not the answer, so it goes out on
323
+ * its own callback and its own accumulator. Dropping it entirely (which is what
324
+ * this parser did) left BOTH channels empty for the whole thinking phase, which
325
+ * is the longest stretch of a Pro turn — so the renderers' live meters, whose
326
+ * only literal `0` is the "nothing received yet" branch, read `↓0 tokens` for
327
+ * the entire time the turn was visibly working. Claude Code Pro runs extended
328
+ * thinking by default, so this was the normal case, not an edge.
320
329
  */
321
330
  function createStreamParser(handlers) {
322
331
  const h = handlers || {};
323
332
  const tools = new Map(); // id -> {id, index, name, args, startedAt, phase}
324
333
  let text = '';
334
+ let thinking = '';
335
+ // Thinking progress the provider MEASURED, in tokens. On a real Pro turn
336
+ // `thinking_delta.thinking` is the empty string and this is the only figure
337
+ // the frame carries — see the `thinking_delta` branch below.
338
+ let thinkingTokens = 0;
325
339
  let resultLine = null;
326
340
 
327
341
  const emitRun = (block) => {
@@ -366,6 +380,30 @@ function createStreamParser(handlers) {
366
380
  const t = (e.delta.text || '').replace(/\x00/g, '');
367
381
  text += t;
368
382
  if (h.onText && t) h.onText(t);
383
+ } else if (e.delta.type === 'thinking_delta') {
384
+ // Same `\x00` scrub as the visible text, for the same reason: a
385
+ // NUL in the frame would otherwise be handed to a terminal.
386
+ const t = (e.delta.thinking || '').replace(/\x00/g, '');
387
+ thinking += t;
388
+ if (h.onThinking && t) h.onThinking(t);
389
+ // The figure that ACTUALLY moves on a subscription turn. Measured
390
+ // against Claude Code 2.1.228: every real `thinking_delta` carries
391
+ // `thinking: ""` with the deliberation withheld (the finished
392
+ // block ships a 5.4 KB `signature` and no text), while
393
+ // `estimated_tokens` advances in increments that sum to just under
394
+ // the billed `usage.output_tokens_details.thinking_tokens`
395
+ // (measured: 1900 vs 1943, 1800 vs 1832, 250 vs 339). So the text
396
+ // channel is empty for the WHOLE thinking phase on a Pro turn and
397
+ // the earlier `onThinking`-only fix never fired — the live meter
398
+ // still read `↓0 tokens` while 4114 thinking tokens were billed
399
+ // across three captured turns. Incremental, not cumulative: the
400
+ // increments sum to the billed figure, so they are added as they
401
+ // arrive rather than treated as a running total.
402
+ const est = e.delta.estimated_tokens;
403
+ if (typeof est === 'number' && est > 0 && Number.isFinite(est)) {
404
+ thinkingTokens += est;
405
+ if (h.onThinkingProgress) h.onThinkingProgress(est);
406
+ }
369
407
  } else if (e.delta.type === 'input_json_delta') {
370
408
  const t = collecting(e.index == null ? 0 : e.index);
371
409
  if (t) t.args += e.delta.partial_json || '';
@@ -396,6 +434,13 @@ function createStreamParser(handlers) {
396
434
  costUsd: typeof j.total_cost_usd === 'number' ? j.total_cost_usd : undefined,
397
435
  durationMs: j.duration_ms,
398
436
  sessionId: j.session_id,
437
+ // The deliberation this round DID produce, handed up so the engine
438
+ // can tell a thinking-only round apart from a genuinely empty one.
439
+ // On a real Pro turn the text is normally withheld and only the
440
+ // billed token count is available, so `thinking` is often empty
441
+ // even when the child thought — hence both fields, and the count.
442
+ thinking: thinking || '',
443
+ thinkingTokens,
399
444
  });
400
445
  }
401
446
  }
@@ -404,6 +449,14 @@ function createStreamParser(handlers) {
404
449
  get text() {
405
450
  return text;
406
451
  },
452
+ get thinking() {
453
+ return thinking;
454
+ },
455
+ // Thinking tokens the PROVIDER measured, not inferred from text — the only
456
+ // honest way to meter a Pro turn, whose thinking text is withheld.
457
+ get thinkingTokens() {
458
+ return thinkingTokens;
459
+ },
407
460
  get resultLine() {
408
461
  return resultLine;
409
462
  },
@@ -454,6 +507,41 @@ function seamAvailable(dir) {
454
507
  }
455
508
  }
456
509
 
510
+ /**
511
+ * The `choices[0].message` a Pro turn reports.
512
+ *
513
+ * `content` is the child's own final answer, as before. The addition is the
514
+ * deliberation, carried on the shape the engine already reads: `reasoning_content`
515
+ * is what `engine.js` `reasoningTextOf()` looks for first, so a Pro round that
516
+ * spent its output thinking is now visible as exactly that.
517
+ *
518
+ * This matters because of how a Pro turn fails. When extended thinking is on —
519
+ * which is Claude Code's default — the child can finish a round having produced
520
+ * deliberation and no answer, and the engine's recovery ladder decides what to
521
+ * do next by asking `reasonedButSilent(res)`, i.e. "was this round empty, or did
522
+ * it think and stay silent?". Before this field existed, a Pro result never
523
+ * carried reasoning at all, so that question always answered "genuinely empty"
524
+ * and the ladder burned its rounds on the generic nudge — the ask that invites
525
+ * the same silent thinking pass a second time. Worse, `emptyTurnError` reported
526
+ * it as "No visible text came back from any of those calls", which is the wrong
527
+ * diagnosis: the model was not silent, it was thinking.
528
+ *
529
+ * `thinking_tokens` rides alongside as the provider's own billed count. On a
530
+ * real Pro turn the deliberation TEXT is withheld — measured across three turns,
531
+ * every `thinking_delta` carried `thinking: ""` while thousands of tokens were
532
+ * billed — so a text-only signal would still miss the case this exists for. The
533
+ * count is the honest figure, and it is the only one that arrives.
534
+ */
535
+ function proMessage(text, thinking, thinkingTokens) {
536
+ const msg = { content: text || '' };
537
+ const deliberation = typeof thinking === 'string' ? thinking : '';
538
+ if (deliberation) msg.reasoning_content = deliberation;
539
+ if (typeof thinkingTokens === 'number' && thinkingTokens > 0 && Number.isFinite(thinkingTokens)) {
540
+ msg.thinking_tokens = thinkingTokens;
541
+ }
542
+ return msg;
543
+ }
544
+
457
545
  /**
458
546
  * Run one turn on the user's Claude Code subscription.
459
547
  *
@@ -635,6 +723,30 @@ function runClaudePro(opts, deps) {
635
723
  armIdle();
636
724
  if (o.onDelta) o.onDelta({ delta: t });
637
725
  },
726
+ // Extended thinking, forwarded on the SAME channel the engine's pooled
727
+ // brain path already uses for a worker's deliberation (`onReasoning`,
728
+ // engine.js — `onDelta({ reasoning })`). Both renderers already consume
729
+ // that field, so the live token meter counts the thinking phase on a Pro
730
+ // turn exactly as it does everywhere else, with no consumer-side edit.
731
+ // `engine.js` hands `runClaudePro` the RAW `opts.onDelta` (not the wrapped
732
+ // `onReasoning`), so this transport is the one that must emit the field.
733
+ onThinking: (t) => {
734
+ armIdle();
735
+ if (o.onDelta) o.onDelta({ reasoning: t });
736
+ },
737
+ // The channel that actually fires on a Pro turn. `onThinking` above is
738
+ // kept for any provider that does stream deliberation text, but Claude
739
+ // Code withholds it: measured across three real turns, every
740
+ // `thinking_delta` carried `thinking: ""`, so `onThinking` never fired
741
+ // once while 4114 thinking tokens were billed. This carries the
742
+ // provider's own MEASURED count, on a numeric channel of its own rather
743
+ // than the text one — the consumers turn `reasoning` text into tokens at
744
+ // 4 chars:1 token, so a token count sent down that path would be divided
745
+ // by four and read as a quarter of the truth.
746
+ onThinkingProgress: (est) => {
747
+ armIdle();
748
+ if (o.onDelta) o.onDelta({ thinkingTokens: est });
749
+ },
638
750
  onTool: (info) => {
639
751
  armIdle();
640
752
  if (!o.onDelta) return;
@@ -662,7 +774,7 @@ function runClaudePro(opts, deps) {
662
774
  return;
663
775
  }
664
776
  settle({
665
- choices: [{ message: { content: r.text || '' }, finish_reason: 'stop' }],
777
+ choices: [{ message: proMessage(r.text || '', r.thinking, r.thinkingTokens), finish_reason: 'stop' }],
666
778
  usage: r.usage || undefined,
667
779
  costUsd: r.costUsd,
668
780
  durationMs: r.durationMs,
@@ -704,7 +816,12 @@ function runClaudePro(opts, deps) {
704
816
  // one. Anything else is a real failure and is reported as one rather than
705
817
  // as an empty successful answer.
706
818
  settle({
707
- choices: [{ message: { content: parser.text }, finish_reason: 'stop' }],
819
+ choices: [
820
+ {
821
+ message: proMessage(parser.text, parser.thinking, parser.thinkingTokens),
822
+ finish_reason: 'stop',
823
+ },
824
+ ],
708
825
  usage: (parser.resultLine && parser.resultLine.usage) || undefined,
709
826
  childRecord: built.record,
710
827
  error:
@@ -743,6 +743,51 @@ function extractToolCalls(res) {
743
743
  }
744
744
 
745
745
  /** The textual content of one assistant turn (empty when it only called tools). */
746
+ /**
747
+ * The prompt a Pro turn actually hands the child.
748
+ *
749
+ * `pro` is the one class that does not replay `opts.messages` into its
750
+ * transport: the `claude` child runs its own agent loop, so sending this
751
+ * engine's transcript would make it re-run every tool call a second time. That
752
+ * decision is right for an ordinary turn and silently wrong for the engine's
753
+ * RE-ASK rounds — the synthesis pass and the recovery ladder both re-dispatch
754
+ * with `prompt: ''` plus a grown `messages`, which is the shape every other
755
+ * class reads as "continue this conversation; the new instruction is the last
756
+ * user message in the history". The Pro branch read only `opts.prompt`, so each
757
+ * of those rounds spawned `claude -p ''`: an empty prompt, on a child whose
758
+ * stdin is `'ignore'`, with `--resume` as its only other context.
759
+ *
760
+ * The consequence was the failure this function exists to prevent. A Pro turn
761
+ * whose first round came back empty could never be recovered, because every
762
+ * recovery round was guaranteed empty too — the ladder then reported "2 extra
763
+ * recovery calls with a larger budget and a changed ask came back empty too"
764
+ * over a transport that had been asked nothing at all. Measured on
765
+ * claude-code-pro, 2026-10-11.
766
+ *
767
+ * So when a round carries no prompt of its own, the LAST user message in
768
+ * `opts.messages` becomes the child's prompt. The nudges the ladder appends are
769
+ * exactly that, and `--resume` reattaches the child to its own session, so the
770
+ * instruction lands in a conversation that already holds the findings — which
771
+ * is what makes the recovery round a re-ask rather than a fresh, empty one.
772
+ *
773
+ * An ordinary turn is untouched: it has its own prompt, so the first branch
774
+ * returns before `messages` is ever consulted.
775
+ */
776
+ function proTurnPrompt(opts) {
777
+ const own = typeof opts.prompt === 'string' ? opts.prompt.trim() : '';
778
+ if (own) return opts.prompt;
779
+ const messages = Array.isArray(opts.messages) ? opts.messages : [];
780
+ for (let i = messages.length - 1; i >= 0; i -= 1) {
781
+ const m = messages[i];
782
+ if (!m || m.role !== 'user') continue;
783
+ if (typeof m.content === 'string' && m.content.trim()) return m.content;
784
+ }
785
+ // Nothing to borrow: keep the caller's own value rather than inventing text,
786
+ // so a round with genuinely no ask still reaches the ladder and is reported
787
+ // as the empty round it is.
788
+ return opts.prompt;
789
+ }
790
+
746
791
  function assistantText(res) {
747
792
  const msg = res && res.choices && res.choices[0] && res.choices[0].message;
748
793
  return (msg && typeof msg.content === 'string' && msg.content) || '';
@@ -808,6 +853,42 @@ function reasoningTextOf(res) {
808
853
  return '';
809
854
  }
810
855
 
856
+ /**
857
+ * Deliberation the provider MEASURED but withheld, in tokens.
858
+ *
859
+ * The companion to `reasoningTextOf()` above, for the one case where there is no
860
+ * text to read: Claude Code Pro runs extended thinking by default and withholds
861
+ * the deliberation itself, so `thinking_delta.thinking` arrives as the empty
862
+ * string while the billed count climbs. A round like that carries real reasoning
863
+ * and no reasoning TEXT, so a text-only predicate reads it as "the model said
864
+ * nothing" — the wrong diagnosis, and the one that made a Pro turn report
865
+ * "No visible text came back" while the child had in fact been thinking.
866
+ *
867
+ * Read from the message shape first (what `claude-pro.js` `proMessage()` sets)
868
+ * and then from the standard usage detail `completion_tokens_details.
869
+ * reasoning_tokens`, so a provider that meters deliberation on the usage
870
+ * envelope is seen too.
871
+ */
872
+ function reasoningTokensOf(res) {
873
+ if (!res) return 0;
874
+ const choice = res.choices && res.choices[0];
875
+ const msg = (choice && choice.message) || {};
876
+ const usage = res.usage || {};
877
+ const details = usage.completion_tokens_details || usage.output_tokens_details || {};
878
+ const candidates = [
879
+ msg.thinking_tokens,
880
+ msg.reasoning_tokens,
881
+ choice && choice.thinking_tokens,
882
+ res.thinking_tokens,
883
+ details.reasoning_tokens,
884
+ details.thinking_tokens,
885
+ ];
886
+ for (const c of candidates) {
887
+ if (typeof c === 'number' && Number.isFinite(c) && c > 0) return c;
888
+ }
889
+ return 0;
890
+ }
891
+
811
892
  /**
812
893
  * The empty turn `isTruncated()` cannot see, and the reason this error survived
813
894
  * a truncation retry that was already in place: a reasoning model that spends
@@ -818,9 +899,14 @@ function reasoningTextOf(res) {
818
899
  * `reasoning_content`, which fell straight through both retry gates to
819
900
  * emptyTurnError. Reasoning tokens and answer tokens share one budget, so the
820
901
  * recovery is identical to a 'length' cut: buy room and ask once more.
902
+ *
903
+ * A round with no reasoning TEXT but a non-zero reasoning-token count counts as
904
+ * reasoning here: that is a Pro turn whose deliberation was withheld, and
905
+ * treating it as genuinely empty is what sent it to the generic nudge instead
906
+ * of the ask that names the problem.
821
907
  */
822
908
  function reasonedButSilent(res) {
823
- return !assistantText(res) && reasoningTextOf(res) !== '';
909
+ return !assistantText(res) && (reasoningTextOf(res) !== '' || reasoningTokensOf(res) > 0);
824
910
  }
825
911
 
826
912
  /**
@@ -979,8 +1065,20 @@ const RECOVERY_ROUNDS = 2;
979
1065
  * real tool log on screen, keeps the transcript honest, and names the cause
980
1066
  * (renderer prints `Error: <message>`).
981
1067
  */
982
- function emptyTurnError({ cls, model, finishReason, reasoningChars, effort, recoveryRounds }) {
1068
+ function emptyTurnError({ cls, model, finishReason, reasoningChars, reasoningTokens, effort, recoveryRounds }) {
983
1069
  const calls = Number(recoveryRounds) || 0;
1070
+ // A withheld deliberation has no chars to count, so the two signals are
1071
+ // reported as the one fact they both are: the round spent its output on
1072
+ // thinking. Without this the Pro case printed "No visible text came back from
1073
+ // any of those calls", which describes a transport that produced nothing —
1074
+ // the opposite of a child that reasoned at length and wrote no answer.
1075
+ const tokens = Number(reasoningTokens) || 0;
1076
+ const reasoned = !!reasoningChars || tokens > 0;
1077
+ const reasonClause = reasoningChars
1078
+ ? `, hidden reasoning: ${reasoningChars} chars and no visible text`
1079
+ : tokens > 0
1080
+ ? `, ~${tokens} thinking tokens billed and no visible text`
1081
+ : '';
984
1082
  const err = new Error(
985
1083
  `The model returned no answer after ${cls}/${model} was asked to summarise its results` +
986
1084
  (calls
@@ -989,8 +1087,8 @@ function emptyTurnError({ cls, model, finishReason, reasoningChars, effort, reco
989
1087
  : '') +
990
1088
  ` (stop reason: ${finishReason || 'none'}` +
991
1089
  `${effort ? `, effort: ${effort}` : ''}` +
992
- `${reasoningChars ? `, hidden reasoning: ${reasoningChars} chars and no visible text` : ''}). ` +
993
- (reasoningChars
1090
+ `${reasonClause}). ` +
1091
+ (reasoned
994
1092
  ? // Deliberately NOT "raise the Effort rung". The budget was already taken
995
1093
  // out of the equation before this error could be reached: the recovery
996
1094
  // calls above ran at the top of the ladder, so pointing at the ceiling
@@ -1878,6 +1976,12 @@ function createLocalEngine({
1878
1976
  provider,
1879
1977
  model: bareModel,
1880
1978
  providerKey: opts.apiKey,
1979
+ // Only meaningful for provider "custom" (aegis1 reads it ONLY on
1980
+ // that id) — forwarded unconditionally anyway, same as the other
1981
+ // fields above, rather than special-cased per provider here.
1982
+ // `cfg` is this provider's settings row (byokNamespace(provider)),
1983
+ // the same row /byok-key and /model-add write.
1984
+ baseURL: opts.cfg && opts.cfg.baseURL,
1881
1985
  prompt: opts.prompt,
1882
1986
  system: opts.system,
1883
1987
  messages: opts.messages,
@@ -2017,7 +2121,10 @@ function createLocalEngine({
2017
2121
  // (one/src/child.js), so this host and AEGISONE's faces cannot disagree
2018
2122
  // about what the child was allowed to do.
2019
2123
  const proRes = await claudePro.runClaudePro({
2020
- prompt: opts.prompt,
2124
+ // The re-ask round's instruction, when this round has none of its own.
2125
+ // See proTurnPrompt(): without it every recovery round spawned the
2126
+ // child with an empty prompt and the turn could never be recovered.
2127
+ prompt: proTurnPrompt(opts),
2021
2128
  model: opts.model && opts.model !== 'default' ? opts.model : undefined,
2022
2129
  system: opts.system,
2023
2130
  cwd: opts.cwd,
@@ -2771,6 +2878,10 @@ function createLocalEngine({
2771
2878
  recoveryRounds,
2772
2879
  finishReason: finishReasonOf(res),
2773
2880
  reasoningChars: reasoningTextOf(res).length,
2881
+ // The withheld-deliberation case (a Pro turn with extended
2882
+ // thinking on): no chars to count, but the provider billed the
2883
+ // thinking. Without this the report claims nothing came back.
2884
+ reasoningTokens: reasoningTokensOf(res),
2774
2885
  });
2775
2886
  }
2776
2887
  return withTurnUsage(res);
@@ -828,16 +828,35 @@ function rollTurn(roll, usage, opts = {}) {
828
828
  // number, and what stops the total standing still on exactly the turns the
829
829
  // pool declined to report on — the symptom this fallback exists to remove.
830
830
  const est = estimatedBuckets(opts.prompt, opts.reply, opts.reasoning);
831
+ // Thinking tokens the provider MEASURED, not estimated. On a subscription
832
+ // turn the deliberation text is withheld entirely (every real
833
+ // `thinking_delta` carries `thinking: ""`), so `estimatedBuckets` above
834
+ // cannot see the longest, priciest part of the turn and the live preview
835
+ // read 0 for the whole thinking phase. Added verbatim — it is already a
836
+ // token count, and it is billed output exactly as the reply is.
837
+ const measured =
838
+ typeof opts.measuredReasoningTokens === 'number' && opts.measuredReasoningTokens > 0
839
+ ? opts.measuredReasoningTokens
840
+ : 0;
831
841
  if (!est) {
832
- // Nothing reported AND no text to estimate from. The single case that
833
- // stays uncounted: `unknown` names the gap, where a fabricated zero would
834
- // read as a measurement.
835
- next.unknown += 1;
842
+ // A subscription turn with nothing written yet but thinking under way is
843
+ // NOT the `unknown` case: the provider measured it, so a zero would be a
844
+ // fabricated reading rather than an absent one.
845
+ if (!measured) {
846
+ // Nothing reported AND no text to estimate from. The single case that
847
+ // stays uncounted: `unknown` names the gap, where a fabricated zero
848
+ // would read as a measurement.
849
+ next.unknown += 1;
850
+ return next;
851
+ }
852
+ next.tokens += measured;
853
+ next.output += measured;
854
+ next.estimated += 1;
836
855
  return next;
837
856
  }
838
- next.tokens += est.input + est.output;
857
+ next.tokens += est.input + est.output + measured;
839
858
  next.input += est.input;
840
- next.output += est.output;
859
+ next.output += est.output + measured;
841
860
  next.estimated += 1;
842
861
  return next;
843
862
  }