aegiscode 7.0.8 → 7.0.10

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.
@@ -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
  }