aegiscode 6.8.37 → 7.0.1

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.
Files changed (110) hide show
  1. package/README.md +39 -1
  2. package/bin/aegiscode.js +137 -0
  3. package/package.json +1 -1
  4. package/scripts/check.mjs +5 -0
  5. package/scripts/demo.mjs +5 -0
  6. package/scripts/predist.mjs +29 -2
  7. package/scripts/runtests.mjs +5 -0
  8. package/scripts/seal-gate.mjs +76 -0
  9. package/src/agents.js +5 -0
  10. package/src/app.js +59 -1
  11. package/src/art.js +5 -0
  12. package/src/autonomous.js +23 -0
  13. package/src/caps.js +5 -0
  14. package/src/chatflow.js +104 -31
  15. package/src/checkpoint.js +5 -0
  16. package/src/clipboard.js +5 -0
  17. package/src/cloudsync.js +5 -0
  18. package/src/commands.js +487 -4
  19. package/src/config.js +5 -0
  20. package/src/credentials.js +5 -0
  21. package/src/deps.js +5 -0
  22. package/src/devrun.js +5 -0
  23. package/src/diff.js +5 -0
  24. package/src/diffview.js +5 -0
  25. package/src/engine.js +5 -0
  26. package/src/entitlement.js +5 -0
  27. package/src/events.js +15 -0
  28. package/src/export.js +5 -0
  29. package/src/fingerprint.js +5 -0
  30. package/src/format.js +5 -0
  31. package/src/fuzzy.js +5 -0
  32. package/src/gate.js +12 -0
  33. package/src/history.js +5 -0
  34. package/src/init.js +5 -0
  35. package/src/input.js +5 -0
  36. package/src/keys.js +29 -2
  37. package/src/limits.js +192 -0
  38. package/src/markdown.js +5 -0
  39. package/src/mcp.js +13 -0
  40. package/src/models.js +5 -0
  41. package/src/naming.js +5 -0
  42. package/src/overlays.js +7 -2
  43. package/src/panels.js +5 -0
  44. package/src/permissions.js +56 -1
  45. package/src/ping.js +5 -0
  46. package/src/presence.js +5 -0
  47. package/src/provenance.js +238 -0
  48. package/src/provenance.lock.json +36 -0
  49. package/src/render.js +5 -0
  50. package/src/screen.js +5 -0
  51. package/src/screens.js +48 -37
  52. package/src/secret.js +5 -0
  53. package/src/securefs.js +5 -0
  54. package/src/settings.js +5 -0
  55. package/src/shared.js +5 -0
  56. package/src/sharedpaths.js +5 -0
  57. package/src/signup.js +5 -0
  58. package/src/summarize.js +5 -0
  59. package/src/sysdiag.js +582 -0
  60. package/src/system.js +5 -0
  61. package/src/theme.js +5 -0
  62. package/src/title.js +5 -0
  63. package/src/todos.js +5 -0
  64. package/src/tokens.js +5 -0
  65. package/src/topup.js +5 -0
  66. package/src/update.js +5 -0
  67. package/vendor/client/aegis.js +27 -0
  68. package/vendor/client/attest.js +5 -0
  69. package/vendor/client/authorship-key.js +5 -0
  70. package/vendor/client/auto-provision.js +5 -0
  71. package/vendor/client/brain-catalog.js +5 -0
  72. package/vendor/client/byok-catalog.js +48 -8
  73. package/vendor/client/credentials.js +5 -0
  74. package/vendor/client/device-fingerprint.js +5 -0
  75. package/vendor/client/env-file.js +5 -0
  76. package/vendor/client/fingerprint.js +5 -0
  77. package/vendor/client/foreign-memory.js +5 -0
  78. package/vendor/client/hooks.js +5 -0
  79. package/vendor/client/model-discovery.js +332 -0
  80. package/vendor/client/platform.js +5 -0
  81. package/vendor/client/prefs.js +5 -0
  82. package/vendor/client/presence-constants.js +5 -0
  83. package/vendor/client/presence.js +5 -0
  84. package/vendor/client/record-vault.js +5 -0
  85. package/vendor/client/session-store.js +5 -0
  86. package/vendor/client/topup.js +5 -0
  87. package/vendor/client/touch.js +5 -0
  88. package/vendor/client/update.js +5 -0
  89. package/vendor/client/user-models.js +383 -0
  90. package/vendor/desktop/lib/local/aegis-seal.mjs +5 -0
  91. package/vendor/desktop/lib/local/agents.js +5 -0
  92. package/vendor/desktop/lib/local/autonomous.js +86 -0
  93. package/vendor/desktop/lib/local/context.js +5 -0
  94. package/vendor/desktop/lib/local/covenant.js +5 -0
  95. package/vendor/desktop/lib/local/engine.js +463 -12
  96. package/vendor/desktop/lib/local/entitlement.js +5 -0
  97. package/vendor/desktop/lib/local/git-scope.js +5 -0
  98. package/vendor/desktop/lib/local/local.js +5 -0
  99. package/vendor/desktop/lib/local/prompt.js +5 -0
  100. package/vendor/desktop/lib/local/queue.js +5 -0
  101. package/vendor/desktop/lib/local/session-rounds.js +5 -0
  102. package/vendor/desktop/lib/local/shell.js +88 -9
  103. package/vendor/desktop/lib/local/tools.js +13 -6
  104. package/vendor/desktop/lib/local/turn-guard.js +5 -0
  105. package/vendor/desktop/lib/local/worktree-lock.js +5 -0
  106. package/vendor/desktop/lib/settings.js +5 -0
  107. package/vendor/desktop/renderer/usage.js +73 -1
  108. package/vendor/mcp/server.js +5 -0
  109. package/vendor/mcp/tools.js +5 -0
  110. package/vendor/tools/agent-gate.mjs +23 -0
@@ -1,3 +1,8 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
+ // AEGIS Code (aegiscode) — source: https://github.com/aegisinfo/aegiscode-plugin
4
+ // Conveying a modified copy, or running one as a network service, owes the
5
+ // corresponding source under this licence (§5/§13) — see LICENSING.md.
1
6
  'use strict';
2
7
 
3
8
  /**
@@ -305,6 +310,63 @@ function requireSharedByokCatalog() {
305
310
  throw last;
306
311
  }
307
312
 
313
+ /**
314
+ * The models the USER declares (`client/user-models.js`) — resolved exactly as
315
+ * the two modules above, and required here for the same reason: it is the ONE
316
+ * store the CLI's `/model-add` and this window's Settings row both write, so a
317
+ * model added in the terminal is a row in this picker and vice versa. A second
318
+ * implementation would be a second file, and "the two hosts show one account
319
+ * two different model lists" is the defect class this resolution rule exists
320
+ * to end.
321
+ *
322
+ * Unlike the two catalog modules this one touches the disk (it reads
323
+ * `$AEGISCODE_HOME/models.json`), which is why it is required through the
324
+ * staged-tree fallback like any other shared module — the packaged app has no
325
+ * `client/` beside it.
326
+ */
327
+ function requireSharedUserModels() {
328
+ const candidates = [
329
+ () => require('../../../client/user-models.js'),
330
+ () => require('../../vendor/user-models.js'),
331
+ ];
332
+ let last = null;
333
+ for (const load of candidates) {
334
+ try {
335
+ return load();
336
+ } catch (err) {
337
+ last = err;
338
+ }
339
+ }
340
+ throw last;
341
+ }
342
+
343
+ /**
344
+ * The vendor-list helper (`client/model-discovery.js`) — the module that asks a
345
+ * provider's OWN API which model ids exist, so a desktop user is not asked to
346
+ * recall an id the vendor publishes at a URL. Same resolution rule as the two
347
+ * catalog modules above, for the same reason: the CLI's `/model-discover` reads
348
+ * this one module too, so the terminal and the window cannot answer "what does
349
+ * this key reach" differently.
350
+ *
351
+ * It does no I/O at load time (no key store, no network), so requiring it here
352
+ * costs the window nothing until a user asks for a list.
353
+ */
354
+ function requireSharedModelDiscovery() {
355
+ const candidates = [
356
+ () => require('../../../client/model-discovery.js'),
357
+ () => require('../../vendor/model-discovery.js'),
358
+ ];
359
+ let last = null;
360
+ for (const load of candidates) {
361
+ try {
362
+ return load();
363
+ } catch (err) {
364
+ last = err;
365
+ }
366
+ }
367
+ throw last;
368
+ }
369
+
308
370
  /**
309
371
  * How long a turn waits for the working-tree lock before running anyway.
310
372
  *
@@ -578,6 +640,18 @@ const { offerableCatalog } = requireSharedBrain();
578
640
  * provider row the other does not.
579
641
  */
580
642
  const { withByokAdditions } = requireSharedByokCatalog();
643
+ const {
644
+ withUserModels,
645
+ load: loadUserModels,
646
+ addUserModel,
647
+ removeUserModel,
648
+ } = requireSharedUserModels();
649
+ const {
650
+ discoverModels: discoverVendorModels,
651
+ canDiscover: canDiscoverVendorModels,
652
+ endpointFor: vendorEndpointFor,
653
+ discoverableProviders,
654
+ } = requireSharedModelDiscovery();
581
655
 
582
656
  // ── Agent-loop helpers ──────────────────────────────────────────────────────
583
657
 
@@ -652,6 +726,91 @@ function isTruncated(res) {
652
726
  return reason === 'length' || reason === 'max_tokens';
653
727
  }
654
728
 
729
+ /**
730
+ * The hidden chain-of-thought a completion carried, read from every wire shape
731
+ * that reports one. DeepSeek returns `message.reasoning_content`, OpenAI's
732
+ * o-series/gpt-5 shape returns `message.reasoning`, and the Anthropic parser
733
+ * folds thinking into content blocks. All three are the same thing here: tokens
734
+ * the model spent out of the same budget as its answer.
735
+ */
736
+ function reasoningTextOf(res) {
737
+ if (!res) return '';
738
+ const choice = res.choices && res.choices[0];
739
+ const msg = (choice && choice.message) || {};
740
+ if (Array.isArray(msg.content)) {
741
+ const blocks = msg.content
742
+ .filter((b) => b && (b.type === 'thinking' || b.type === 'reasoning'))
743
+ .map((b) => b.thinking || b.text || '')
744
+ .join('');
745
+ if (blocks) return blocks;
746
+ }
747
+ const fromContent = msg.content && typeof msg.content === 'object' ? msg.content.reasoning_content : '';
748
+ const candidates = [
749
+ msg.reasoning_content,
750
+ msg.reasoning,
751
+ choice && choice.reasoning_content,
752
+ res.reasoning_content,
753
+ res.reasoning,
754
+ fromContent,
755
+ ];
756
+ for (const c of candidates) if (typeof c === 'string' && c) return c;
757
+ return '';
758
+ }
759
+
760
+ /**
761
+ * The empty turn `isTruncated()` cannot see, and the reason this error survived
762
+ * a truncation retry that was already in place: a reasoning model that spends
763
+ * the budget on hidden chain-of-thought and then finishes with NO visible text
764
+ * still reports `finish_reason: 'stop'` — the provider considers the call
765
+ * complete, because to it the model did stop, it just stopped while thinking.
766
+ * Measured live on byok/deepseek-v4-flash: `stop` + empty content + non-empty
767
+ * `reasoning_content`, which fell straight through both retry gates to
768
+ * emptyTurnError. Reasoning tokens and answer tokens share one budget, so the
769
+ * recovery is identical to a 'length' cut: buy room and ask once more.
770
+ */
771
+ function reasonedButSilent(res) {
772
+ return !assistantText(res) && reasoningTextOf(res) !== '';
773
+ }
774
+
775
+ /**
776
+ * The rung a reasoning-only retry is raised to. Every reasoning retry is paid
777
+ * for out of the same budget twice — the chain-of-thought is paid for again
778
+ * before a single visible word can be written — so a rung that merely doubled
779
+ * (the 8k floor -> 16k) still finished silent: the floor is what an unstated
780
+ * budget yields, and it is the rung the live failure had already exhausted.
781
+ */
782
+ const REASONING_RETRY_FLOOR = 32768;
783
+
784
+ /**
785
+ * The one budget decision every empty-turn retry makes, in one place: is the
786
+ * number we hold ours (a rung we derived, which a retry may raise) or the
787
+ * caller's (a deliberate cap the retry may only double)?
788
+ *
789
+ * It matters exactly here. The floor above is a floor on OUR rung; applying it
790
+ * to a stated cap would turn the flow lane's deliberate 1024-token ceiling into
791
+ * 32768 because the model happened to think out loud — the same "a guessed
792
+ * number goes on the wire as a ceiling" bug statedCapOf() exists to prevent.
793
+ */
794
+ function retryBudgetFor(opts, reasoningOnly) {
795
+ const doubled = doubledBudget(opts.maxTokens);
796
+ if (!reasoningOnly) return doubled;
797
+ // Which number is this? A budget that is one of EFFORT_TOKEN_BUDGET's own
798
+ // rungs (8192/16384/32768) is the rung this call was sized at, so a reasoning
799
+ // retry may raise it to the top of the ladder — that is the live failure this
800
+ // exists for: 16384 burned on hidden chain-of-thought, finish_reason 'stop',
801
+ // empty content. Any OTHER number belongs to someone who chose it (the flow
802
+ // lane's deliberate 1024, a caller's own 4096), and doubling is as far as a
803
+ // retry may go: promoting it by an order of magnitude would put a ceiling the
804
+ // user never asked for on the wire.
805
+ return ladderRung(opts.maxTokens) ? Math.max(doubled, REASONING_RETRY_FLOOR) : doubled;
806
+ }
807
+
808
+ /** Is this budget one of the effort ladder's own rungs (a size WE derived)? */
809
+ function ladderRung(maxTokens) {
810
+ const n = Number(maxTokens);
811
+ return Number.isFinite(n) && Object.values(EFFORT_TOKEN_BUDGET).includes(n);
812
+ }
813
+
655
814
  /**
656
815
  * Double a budget for the one-shot truncation retry. A budget the caller set
657
816
  * on purpose (the flow lane's deliberate 1024-token cap, say) is merely
@@ -701,6 +860,62 @@ const EMPTY_TURN_NUDGE =
701
860
  'No tools are available in this reply, so do not call any: respond in plain ' +
702
861
  'prose or markdown.';
703
862
 
863
+ /**
864
+ * The nudge for an empty round that was NOT really empty: the model spent it
865
+ * thinking. A reasoning model that burns its budget on hidden chain-of-thought
866
+ * and stops without writing a visible word (`finish_reason: 'stop'`, empty
867
+ * content, non-empty `reasoning_content`) is the normal shape of this failure on
868
+ * DeepSeek, and the generic nudge above does not describe it — "write your answer
869
+ * now" invites the same reasoning pass a second time, because nothing told the
870
+ * model that the thinking was the problem.
871
+ *
872
+ * Naming the failure IS the fix, and it is the upstream engine's own last resort
873
+ * (`src/backend.js`, the `thoughtOnly` recovery round). Buying budget is the
874
+ * other lever, already tried below; when that has failed the budget is not what
875
+ * is wrong, so the ask changes instead: answer WITHOUT thinking first.
876
+ */
877
+ const THOUGHT_ONLY_NUDGE =
878
+ 'Your previous round was spent entirely on hidden reasoning and produced no visible reply. ' +
879
+ 'Answer the user directly and briefly now. Do not reason, explain, or think first — write only ' +
880
+ 'the answer, no tools.';
881
+
882
+ /**
883
+ * The last ask of the recovery ladder, for a turn that stayed silent even after
884
+ * being told not to think first.
885
+ *
886
+ * A model that is going to reason anyway will reason whatever the nudge says, so
887
+ * the final round stops asking it not to: the ask becomes "say anything usable
888
+ * about what you already have", which a model that has demonstrably read the
889
+ * context can always satisfy. Producing a slightly thin write-up is strictly
890
+ * better than the alternative — the transcript keeps the answer, and the user
891
+ * can ask for detail on the one point that was skimped, in a turn where the
892
+ * material is already in context.
893
+ */
894
+ const FINAL_ANSWER_NUDGE =
895
+ 'Write your answer now, in plain prose, using only what is already in this conversation. ' +
896
+ 'If your information is incomplete, say what you have and what is missing — an incomplete ' +
897
+ 'answer is the expected outcome here and is better than none. No tools, no preface.';
898
+
899
+ /**
900
+ * How many EXTRA calls an empty write-up round is worth before the turn is
901
+ * declared failed.
902
+ *
903
+ * The upstream engine spends additional calls on a silent round rather than
904
+ * telling the reader to go and change a setting (`src/backend.js`'s thoughtOnly
905
+ * recovery), and this is the same trade, made explicit because the trade is the
906
+ * whole point of the number: an extra dispatch costs tokens, a failed turn costs
907
+ * the entire investigation the tool log on screen paid for. Two calls — one
908
+ * after the budget-retry above, one after the ask changes — is where the curve
909
+ * flattens: measured on byok/deepseek-v4-flash, a round that reasons and stays
910
+ * silent either answers on the first changed ask or is not going to answer at
911
+ * all, because the failure is the model's habit and not the wording.
912
+ *
913
+ * Crucially, every one of these rounds runs with `tools: []` on `synthesisOpts`:
914
+ * they re-ask for the write-up out of a context that already holds the findings,
915
+ * so "more calls" can never mean "do the investigation again".
916
+ */
917
+ const RECOVERY_ROUNDS = 2;
918
+
704
919
  /**
705
920
  * Last resort for a turn that is still empty after the synthesis pass.
706
921
  *
@@ -713,12 +928,29 @@ const EMPTY_TURN_NUDGE =
713
928
  * real tool log on screen, keeps the transcript honest, and names the cause
714
929
  * (renderer prints `Error: <message>`).
715
930
  */
716
- function emptyTurnError({ cls, model, maxTokens, finishReason }) {
931
+ function emptyTurnError({ cls, model, finishReason, reasoningChars, effort, recoveryRounds }) {
932
+ const calls = Number(recoveryRounds) || 0;
717
933
  const err = new Error(
718
- `The model returned no answer after ${cls}/${model} was asked to summarise its results ` +
719
- `(stop reason: ${finishReason || 'none'}, max_tokens: ${maxTokens || 'unstated'}). The token budget ` +
720
- 'was most likely consumed before any visible text — raise the Effort rung, which is ' +
721
- 'what sizes this call, or ask for a smaller piece of work.'
934
+ `The model returned no answer after ${cls}/${model} was asked to summarise its results` +
935
+ (calls
936
+ ? `, and ${calls} extra recovery call${calls === 1 ? '' : 's'} with a larger budget ` +
937
+ 'and a changed ask came back empty too'
938
+ : '') +
939
+ ` (stop reason: ${finishReason || 'none'}` +
940
+ `${effort ? `, effort: ${effort}` : ''}` +
941
+ `${reasoningChars ? `, hidden reasoning: ${reasoningChars} chars and no visible text` : ''}). ` +
942
+ (reasoningChars
943
+ ? // Deliberately NOT "raise the Effort rung". The budget was already taken
944
+ // out of the equation before this error could be reached: the recovery
945
+ // calls above ran at the top of the ladder, so pointing at the ceiling
946
+ // would send the reader to change the one setting that is already
947
+ // maxed out. The unchanged thing is the model's habit of answering
948
+ // inside its head, and that is what gets named.
949
+ 'Every one of those calls spent its output on hidden reasoning instead of writing a ' +
950
+ 'word, so this is the model rather than the budget: pick a model that answers without ' +
951
+ 'a thinking pass, or ask for a smaller piece of work.'
952
+ : 'No visible text came back from any of those calls. Send the request again, in smaller ' +
953
+ 'pieces, or from a different model.')
722
954
  );
723
955
  err.status = 502;
724
956
  return err;
@@ -747,6 +979,12 @@ function createLocalEngine({
747
979
  // caller (desktop/main.js, the CLI's deps.js) wires the local class by
748
980
  // simply existing.
749
981
  localTransport: localT = localTransport,
982
+ // Injectable for tests (and for a host that fronts the network itself): the
983
+ // fetch used ONLY by `discoverModels`, which asks a vendor's list API. Every
984
+ // other request in this file goes through `localT`, so this is deliberately
985
+ // not the transport — discovery is an outbound call to api.<vendor>, not to
986
+ // the AEGIS relay. Undefined in production, which means the global fetch.
987
+ fetchImpl,
750
988
  }) {
751
989
  const controllers = new Map(); // sessionId -> AbortController
752
990
  const T = tools || toolsModule;
@@ -1207,7 +1445,7 @@ function createLocalEngine({
1207
1445
  // of `providers` — the model list built just below, the renderer's
1208
1446
  // per-provider Settings rows, and the CLI's own `/byok` listing when it
1209
1447
  // runs on this engine — sees one list instead of three opinions.
1210
- providers = withByokAdditions((data && data.providers) || []);
1448
+ providers = withUserModels(withByokAdditions((data && data.providers) || []));
1211
1449
  // The handling fee AEGIS adds on top of the caller's vendor bill. It is
1212
1450
  // the server's own published rate (services/pricing.price_byok_call) and
1213
1451
  // is passed through untouched — never re-derived here, because a client
@@ -2032,8 +2270,9 @@ function createLocalEngine({
2032
2270
  // double up in the renderer's live view. When text *has* arrived the
2033
2271
  // turn is not empty — the answer is merely truncated — and a retry
2034
2272
  // would stream it a second time onto the same bubble.
2035
- if (!truncationRetried && !assistantText(res) && isTruncated(res)) {
2273
+ if (!truncationRetried && !assistantText(res) && (isTruncated(res) || reasonedButSilent(res))) {
2036
2274
  truncationRetried = true;
2275
+ const reasoningOnly = reasonedButSilent(res);
2037
2276
  // singlePass: this retry buys *budget*, not a second investigation.
2038
2277
  // The fan-out's workers would re-run the whole task from scratch for
2039
2278
  // it — 3 extra reasoning passes + a synthesis — which is the opposite
@@ -2046,7 +2285,11 @@ function createLocalEngine({
2046
2285
  // bought by round 1, and buying it again here would charge a
2047
2286
  // second one for the same context.
2048
2287
  recallDeep: false,
2049
- maxTokens: doubledBudget(opts.maxTokens),
2288
+ // A reasoning-only completion gets the high rung AND high effort:
2289
+ // the model is about to re-pay for the same chain-of-thought, and
2290
+ // on DeepSeek that pair is what actually moves the ceiling.
2291
+ effort: reasoningOnly ? 'high' : opts.effort,
2292
+ maxTokens: retryBudgetFor(opts, reasoningOnly),
2050
2293
  // Doubling applies to the pooled path only when the caller stated a
2051
2294
  // number. With none stated, the server's effort ladder IS the
2052
2295
  // budget, and sending doubledBudget's 8192 floor would *lower* it
@@ -2073,14 +2316,20 @@ function createLocalEngine({
2073
2316
  // no gathered context to rescue, so a bare completion is just that.
2074
2317
  synthesisDone = true;
2075
2318
  foldPromptIntoHistory();
2076
- history.push({ role: 'user', content: EMPTY_TURN_NUDGE });
2319
+ // The nudge is chosen by what the empty round actually WAS, not by the
2320
+ // fact that it was empty. A round that spent its budget on hidden
2321
+ // reasoning and stopped without writing a word needs to be told not to
2322
+ // think; the generic wording invites the same silent pass a second
2323
+ // time, which is precisely how a recoverable turn became
2324
+ // `emptyTurnError` on byok/deepseek-v4-flash (2026-10-11).
2325
+ history.push({ role: 'user', content: reasonedButSilent(res) ? THOUGHT_ONLY_NUDGE : EMPTY_TURN_NUDGE });
2077
2326
  // singlePass: same reasoning as the truncation retry above, and it is
2078
2327
  // the same comment's literal promise ("force the summary out of the
2079
2328
  // context it already holds"). Escalating a write-up back into the
2080
2329
  // worker fan-out asked three fresh workers to redo an investigation
2081
2330
  // whose findings are already in `history`, at 4x the cost, to produce
2082
2331
  // a paragraph the model had all the material for.
2083
- res = await dispatch(cls, {
2332
+ const synthesisOpts = {
2084
2333
  ...opts,
2085
2334
  singlePass: true,
2086
2335
  // Same as the truncation retry above: this pass writes up findings
@@ -2089,7 +2338,13 @@ function createLocalEngine({
2089
2338
  messages: history,
2090
2339
  prompt: '',
2091
2340
  tools: [],
2092
- });
2341
+ };
2342
+ res = await dispatch(cls, synthesisOpts);
2343
+ // The ceiling and the rung of the last dispatch that came back empty,
2344
+ // so the failure below reports the call that actually failed instead of
2345
+ // the original one it was retried away from.
2346
+ let lastBudget = synthesisOpts.maxTokens;
2347
+ let lastEffort = synthesisOpts.effort;
2093
2348
  addUsage(res);
2094
2349
  // Same guard again: a cancel landing during the synthesis pass
2095
2350
  // resolves empty too, and without this check it fell through to
@@ -2097,12 +2352,108 @@ function createLocalEngine({
2097
2352
  // "no answer" failure over what was actually just the user hitting
2098
2353
  // Cancel.
2099
2354
  if (signal.aborted) return withTurnUsage(res);
2355
+ // The SAME truncation retry the main round gets, one level down: the
2356
+ // write-up pass is itself a fresh dispatch billed against `opts.maxTokens`,
2357
+ // and a reasoning model can burn that whole budget on hidden
2358
+ // chain-of-thought a SECOND time while composing the summary — history
2359
+ // is bigger than round 1's, so if anything this pass is more likely to
2360
+ // need the room. Without this, "the synthesis pass also got
2361
+ // truncated" and "the model is simply done" were indistinguishable —
2362
+ // both threw the same emptyTurnError — even though the first is
2363
+ // recoverable with the exact one-line fix already proven above.
2364
+ if (!assistantText(res) && (isTruncated(res) || reasonedButSilent(res))) {
2365
+ const reasoningOnly = reasonedButSilent(res);
2366
+ lastBudget = retryBudgetFor(synthesisOpts, reasoningOnly);
2367
+ lastEffort = reasoningOnly ? 'high' : synthesisOpts.effort;
2368
+ res = await dispatch(cls, {
2369
+ ...synthesisOpts,
2370
+ effort: lastEffort,
2371
+ maxTokens: lastBudget,
2372
+ statedMaxTokens: synthesisOpts.statedMaxTokens
2373
+ ? doubledBudget(synthesisOpts.statedMaxTokens)
2374
+ : undefined,
2375
+ });
2376
+ addUsage(res);
2377
+ if (signal.aborted) return withTurnUsage(res);
2378
+ }
2379
+ // ── The recovery ladder: extra calls, not a verdict ────────────────
2380
+ // Everything above bought a bigger ceiling; this changes the ASK —
2381
+ // and repeats it — because a round that reasoned and then stayed
2382
+ // silent has already been handed more room and still did not write a
2383
+ // word.
2384
+ //
2385
+ // This is the upstream engine's own trade (`src/backend.js`, the
2386
+ // `thoughtOnly` recovery round): spend another call rather than hand
2387
+ // the reader a red "backend error: … raise the Effort rung" over work
2388
+ // that is finished and already sitting in `history`. Telling someone
2389
+ // to go and raise a setting is not a recovery, and the ceiling it
2390
+ // points at was raised by the retry above — so the ladder spends
2391
+ // calls, with a variant of the ask each time, and only reports
2392
+ // failure when every one of them comes back empty as well.
2393
+ //
2394
+ // Bounded by construction: `RECOVERY_ROUNDS` caps the calls,
2395
+ // `synthesisDone` is already true, and each nudge JOINS `history`
2396
+ // rather than replacing it — every round here runs with `tools: []`,
2397
+ // so a round is a re-ask out of context the model already holds and
2398
+ // can never become a fresh investigation.
2399
+ //
2400
+ // The ceiling lift below is computed ONCE, not per round. A ladder
2401
+ // that doubled the budget each time would turn "two more calls" into
2402
+ // "two more calls at double the price" for a model whose problem is
2403
+ // demonstrably not the price, and Math.max keeps it monotone: for a
2404
+ // rung this is the top of the ladder, and a number a previous retry
2405
+ // already raised past it (a caller's doubled cap) is never lowered.
2406
+ const ladderBudget = (() => {
2407
+ const owned = Number(lastBudget) || 0;
2408
+ // No number in hand — the caller stated none and the model is not a
2409
+ // reasoning model, so `reasoningBudget()` sends no `max_tokens` at
2410
+ // all and the provider's own limit governs. Inventing one here
2411
+ // (retryBudgetFor's 8192 floor) would put a ceiling on the wire that
2412
+ // nobody asked for, which is the very defect this file's budget
2413
+ // comments were written about. The ladder's extra call is then the
2414
+ // same price as the call it repeats, and only the ask changes.
2415
+ if (!owned) return lastBudget;
2416
+ const ask = { maxTokens: lastBudget };
2417
+ if (synthesisOpts.statedMaxTokens) ask.statedMaxTokens = synthesisOpts.statedMaxTokens;
2418
+ return Math.max(owned, retryBudgetFor(ask, true));
2419
+ })();
2420
+ let recoveryRounds = 0;
2421
+ while (!assistantText(res) && recoveryRounds < RECOVERY_ROUNDS && !signal.aborted) {
2422
+ const reasoningOnly = reasonedButSilent(res);
2423
+ recoveryRounds += 1;
2424
+ history.push({
2425
+ role: 'user',
2426
+ content: reasoningOnly
2427
+ ? recoveryRounds === 1
2428
+ ? THOUGHT_ONLY_NUDGE
2429
+ : FINAL_ANSWER_NUDGE
2430
+ : EMPTY_TURN_NUDGE,
2431
+ });
2432
+ if (reasoningOnly) lastEffort = 'high';
2433
+ lastBudget = ladderBudget;
2434
+ res = await dispatch(cls, {
2435
+ ...synthesisOpts,
2436
+ messages: history,
2437
+ effort: lastEffort,
2438
+ maxTokens: lastBudget,
2439
+ statedMaxTokens: synthesisOpts.statedMaxTokens
2440
+ ? doubledBudget(synthesisOpts.statedMaxTokens)
2441
+ : undefined,
2442
+ });
2443
+ addUsage(res);
2444
+ if (signal.aborted) return withTurnUsage(res);
2445
+ }
2100
2446
  if (!assistantText(res)) {
2101
2447
  throw emptyTurnError({
2102
2448
  cls,
2103
2449
  model,
2104
- maxTokens: opts.maxTokens,
2450
+ // What the LAST call looked like, and how many extra calls the
2451
+ // ladder already spent: the report describes the call that failed
2452
+ // rather than the first one it was retried away from.
2453
+ effort: lastEffort,
2454
+ recoveryRounds,
2105
2455
  finishReason: finishReasonOf(res),
2456
+ reasoningChars: reasoningTextOf(res).length,
2106
2457
  });
2107
2458
  }
2108
2459
  return withTurnUsage(res);
@@ -2249,6 +2600,28 @@ function createLocalEngine({
2249
2600
  return localT.unloadAll();
2250
2601
  }
2251
2602
 
2603
+ /**
2604
+ * The vendor key for a provider, resolved in the order the NEXT TURN will
2605
+ * resolve it: the saved `byok:<provider>` row first, then `~/.aegiscode/.env`
2606
+ * (loaded into the environment at host start-up by `client/env-file.js`) and
2607
+ * the shell. Discovery must ask with the key the call will run on — a list
2608
+ * fetched with a different one describes a catalog this machine cannot reach.
2609
+ *
2610
+ * Read-only by construction: it never writes a key, never hands the value to
2611
+ * a renderer and never logs it.
2612
+ */
2613
+ function byokKeyForProviderLookup(providerId) {
2614
+ const id = String(providerId == null ? '' : providerId).trim().toLowerCase();
2615
+ if (!id) return '';
2616
+ try {
2617
+ if (settings && typeof settings.rawKey === 'function') {
2618
+ const stored = settings.rawKey(byokNamespace(id));
2619
+ if (typeof stored === 'string' && stored.trim()) return stored.trim();
2620
+ }
2621
+ } catch { /* a store that throws has no key, and that is a reportable state */ }
2622
+ return providerKeyFromEnv(id);
2623
+ }
2624
+
2252
2625
  return {
2253
2626
  CLASSES,
2254
2627
  listClasses,
@@ -2260,6 +2633,84 @@ function createLocalEngine({
2260
2633
  clearSessionApprovals,
2261
2634
  settings,
2262
2635
  unloadLocalModels,
2636
+ // The user's own model declarations (`$AEGISCODE_HOME/models.json`), read,
2637
+ // added and removed through ONE implementation because THREE faces write
2638
+ // them: the desktop's Settings row (via main.js's model dispatch), the
2639
+ // CLI's `/model-add`, and the user's own editor. `userModels()` returns
2640
+ // `{ dir, file, map, invalid }` so a host can SHOW where the file is and
2641
+ // name the rows it refused (`invalid`), instead of a declaration vanishing
2642
+ // into a picker that looks like the feature did nothing.
2643
+ //
2644
+ // Add/remove THROW on a malformed provider or model id (that is the point —
2645
+ // an id the relay would forward to a vendor 404s on the user's first turn,
2646
+ // where a rejected input 404s never), so every caller surfaces the message
2647
+ // rather than storing it.
2648
+ userModels: () => loadUserModels(),
2649
+ addUserModel: (provider, model) => addUserModel(provider, model),
2650
+ removeUserModel: (provider, model) => removeUserModel(provider, model),
2651
+ // ── asking the vendor, so the user does not have to remember ids ───────
2652
+ //
2653
+ // `discoverModels(provider)` resolves and returns the ids the provider's own
2654
+ // list API serves RIGHT NOW, which is the fix for the chore that produced
2655
+ // `client/byok-catalog.js`'s hand-copied Anthropic table. It never throws:
2656
+ // the shape is the discovery module's own
2657
+ // `{ ok, provider, ids, others, count }` / `{ ok:false, error }`, and the
2658
+ // renderer prints `error` verbatim. A window that guessed at an id and
2659
+ // silently pinned a 404 is the outcome this exists to prevent.
2660
+ //
2661
+ // The key comes from the SAME chain the next turn will use (the saved
2662
+ // `byok:<provider>` row, then `~/.aegiscode/.env`, then the shell), because
2663
+ // a list fetched with a different key than the call runs on would describe
2664
+ // somebody else's catalog.
2665
+ discoverModels: async (provider) => {
2666
+ const id = String(provider == null ? '' : provider).trim().toLowerCase();
2667
+ const key = byokKeyForProviderLookup(id);
2668
+ const res = await discoverVendorModels(id, { key, fetchImpl });
2669
+ // Say what the caller needs to offer the next step: which of these the
2670
+ // relay itself already lists, and which this machine has declared, so the
2671
+ // UI can mark a row instead of the user diffing two lists by eye.
2672
+ if (!res || !res.ok) return res;
2673
+ const declared = [];
2674
+ try {
2675
+ const map = loadUserModels().map;
2676
+ for (const m of Array.isArray(map[id]) ? map[id] : []) declared.push(m);
2677
+ } catch { /* a store that cannot be read marks nothing */ }
2678
+ return { ...res, declared, endpoint: (vendorEndpointFor(id) || {}).url || '' };
2679
+ },
2680
+ // The bulk write (`/model-add <provider> '*'` and the desktop's "Add all"
2681
+ // button): declare every id in one pass, skipping what is already there and
2682
+ // NAMING what was refused rather than aborting the whole batch on one bad
2683
+ // row. Returns counts, never a bare boolean, so both faces can report
2684
+ // "3 added, 2 already declared" instead of claiming work they did not do.
2685
+ addUserModels: (provider, ids) => {
2686
+ const list = Array.isArray(ids) ? ids : [];
2687
+ const out = { provider, added: 0, already: [], failed: [], capped: 0, file: '' };
2688
+ for (const raw of list) {
2689
+ try {
2690
+ const res = addUserModel(provider, raw);
2691
+ out.file = res.file || out.file;
2692
+ if (res.added) out.added += 1;
2693
+ else out.already.push(res.model);
2694
+ } catch (err) {
2695
+ const message = (err && err.message) || String(err);
2696
+ // The store's per-provider ceiling ends the batch as a CEILING. A
2697
+ // vendor serves a hundred ids and the store holds 32, so reporting
2698
+ // that as sixty-eight refused models would describe one deliberate
2699
+ // limit as sixty-eight broken ids.
2700
+ if (/the cap/.test(message)) {
2701
+ out.capped = list.length - out.added - out.already.length - out.failed.length;
2702
+ break;
2703
+ }
2704
+ out.failed.push({ id: String(raw), reason: message });
2705
+ }
2706
+ }
2707
+ return out;
2708
+ },
2709
+ // What the Settings row uses to decide whether to OFFER a list at all: a
2710
+ // provider this client cannot ask (or has no key for) falls back to the
2711
+ // free-form input, which is the path that always works.
2712
+ canDiscoverModels: (provider) => canDiscoverVendorModels(provider),
2713
+ discoverableProviders: () => discoverableProviders(),
2263
2714
  };
2264
2715
  }
2265
2716
 
@@ -1,3 +1,8 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
+ // AEGIS Code (aegiscode) — source: https://github.com/aegisinfo/aegiscode-plugin
4
+ // Conveying a modified copy, or running one as a network service, owes the
5
+ // corresponding source under this licence (§5/§13) — see LICENSING.md.
1
6
  'use strict';
2
7
 
3
8
  /**
@@ -1,3 +1,8 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
+ // AEGIS Code (aegiscode) — source: https://github.com/aegisinfo/aegiscode-plugin
4
+ // Conveying a modified copy, or running one as a network service, owes the
5
+ // corresponding source under this licence (§5/§13) — see LICENSING.md.
1
6
  'use strict';
2
7
 
3
8
  /**
@@ -1,3 +1,8 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
+ // AEGIS Code (aegiscode) — source: https://github.com/aegisinfo/aegiscode-plugin
4
+ // Conveying a modified copy, or running one as a network service, owes the
5
+ // corresponding source under this licence (§5/§13) — see LICENSING.md.
1
6
  'use strict';
2
7
 
3
8
  /**
@@ -1,3 +1,8 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
+ // AEGIS Code (aegiscode) — source: https://github.com/aegisinfo/aegiscode-plugin
4
+ // Conveying a modified copy, or running one as a network service, owes the
5
+ // corresponding source under this licence (§5/§13) — see LICENSING.md.
1
6
  'use strict';
2
7
 
3
8
  /**
@@ -1,3 +1,8 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
+ // AEGIS Code (aegiscode) — source: https://github.com/aegisinfo/aegiscode-plugin
4
+ // Conveying a modified copy, or running one as a network service, owes the
5
+ // corresponding source under this licence (§5/§13) — see LICENSING.md.
1
6
  'use strict';
2
7
 
3
8
  /**
@@ -1,3 +1,8 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
+ // AEGIS Code (aegiscode) — source: https://github.com/aegisinfo/aegiscode-plugin
4
+ // Conveying a modified copy, or running one as a network service, owes the
5
+ // corresponding source under this licence (§5/§13) — see LICENSING.md.
1
6
  'use strict';
2
7
 
3
8
  /**