aegisone 1.0.6 → 1.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.
Files changed (222) hide show
  1. package/README.md +2 -2
  2. package/bin/aegis.js +5 -0
  3. package/install.ps1 +5 -0
  4. package/install.sh +5 -0
  5. package/package.json +1 -1
  6. package/scripts/bump.mjs +5 -0
  7. package/scripts/bundle.js +5 -0
  8. package/scripts/predist.mjs +9 -0
  9. package/src/child.js +5 -0
  10. package/src/dispatch.js +5 -0
  11. package/src/doctor.js +5 -0
  12. package/src/host.js +5 -0
  13. package/src/permissions.js +5 -0
  14. package/src/probes.js +5 -0
  15. package/src/release.js +19 -5
  16. package/vendor/cli/README.md +39 -1
  17. package/vendor/cli/bin/aegiscode.js +137 -0
  18. package/vendor/cli/package.json +1 -1
  19. package/vendor/cli/scripts/check.mjs +5 -0
  20. package/vendor/cli/scripts/demo.mjs +5 -0
  21. package/vendor/cli/scripts/predist.mjs +29 -2
  22. package/vendor/cli/scripts/runtests.mjs +5 -0
  23. package/vendor/cli/scripts/seal-gate.mjs +76 -0
  24. package/vendor/cli/src/agents.js +5 -0
  25. package/vendor/cli/src/app.js +79 -1
  26. package/vendor/cli/src/art.js +5 -0
  27. package/vendor/cli/src/autonomous.js +23 -0
  28. package/vendor/cli/src/caps.js +5 -0
  29. package/vendor/cli/src/chatflow.js +245 -32
  30. package/vendor/cli/src/checkpoint.js +5 -0
  31. package/vendor/cli/src/clipboard.js +5 -0
  32. package/vendor/cli/src/cloudsync.js +5 -0
  33. package/vendor/cli/src/commands.js +487 -4
  34. package/vendor/cli/src/config.js +5 -0
  35. package/vendor/cli/src/credentials.js +5 -0
  36. package/vendor/cli/src/deps.js +5 -0
  37. package/vendor/cli/src/devrun.js +5 -0
  38. package/vendor/cli/src/diff.js +5 -0
  39. package/vendor/cli/src/diffview.js +5 -0
  40. package/vendor/cli/src/engine.js +9 -2
  41. package/vendor/cli/src/entitlement.js +5 -0
  42. package/vendor/cli/src/events.js +15 -0
  43. package/vendor/cli/src/export.js +5 -0
  44. package/vendor/cli/src/fingerprint.js +5 -0
  45. package/vendor/cli/src/format.js +5 -0
  46. package/vendor/cli/src/fuzzy.js +5 -0
  47. package/vendor/cli/src/gate.js +12 -0
  48. package/vendor/cli/src/history.js +5 -0
  49. package/vendor/cli/src/init.js +5 -0
  50. package/vendor/cli/src/input.js +5 -0
  51. package/vendor/cli/src/keys.js +29 -2
  52. package/vendor/cli/src/limits.js +192 -0
  53. package/vendor/cli/src/markdown.js +5 -0
  54. package/vendor/cli/src/mcp.js +13 -0
  55. package/vendor/cli/src/models.js +5 -0
  56. package/vendor/cli/src/naming.js +5 -0
  57. package/vendor/cli/src/overlays.js +7 -2
  58. package/vendor/cli/src/panels.js +5 -0
  59. package/vendor/cli/src/permissions.js +56 -1
  60. package/vendor/cli/src/ping.js +5 -0
  61. package/vendor/cli/src/presence.js +5 -0
  62. package/vendor/cli/src/provenance.js +238 -0
  63. package/vendor/cli/src/provenance.lock.json +36 -0
  64. package/vendor/cli/src/render.js +5 -0
  65. package/vendor/cli/src/screen.js +5 -0
  66. package/vendor/cli/src/screens.js +166 -62
  67. package/vendor/cli/src/secret.js +5 -0
  68. package/vendor/cli/src/securefs.js +5 -0
  69. package/vendor/cli/src/settings.js +5 -0
  70. package/vendor/cli/src/shared.js +5 -0
  71. package/vendor/cli/src/sharedpaths.js +5 -0
  72. package/vendor/cli/src/signup.js +5 -0
  73. package/vendor/cli/src/summarize.js +5 -0
  74. package/vendor/cli/src/sysdiag.js +582 -0
  75. package/vendor/cli/src/system.js +5 -0
  76. package/vendor/cli/src/theme.js +5 -0
  77. package/vendor/cli/src/title.js +5 -0
  78. package/vendor/cli/src/todos.js +5 -0
  79. package/vendor/cli/src/tokens.js +5 -0
  80. package/vendor/cli/src/topup.js +5 -0
  81. package/vendor/cli/src/update.js +5 -0
  82. package/vendor/cli/vendor/client/aegis.js +27 -0
  83. package/vendor/cli/vendor/client/attest.js +5 -0
  84. package/vendor/cli/vendor/client/authorship-key.js +5 -0
  85. package/vendor/cli/vendor/client/auto-provision.js +5 -0
  86. package/vendor/cli/vendor/client/brain-catalog.js +5 -0
  87. package/vendor/cli/vendor/client/byok-catalog.js +48 -8
  88. package/vendor/cli/vendor/client/credentials.js +5 -0
  89. package/vendor/cli/vendor/client/device-fingerprint.js +5 -0
  90. package/vendor/cli/vendor/client/env-file.js +5 -0
  91. package/vendor/cli/vendor/client/fingerprint.js +5 -0
  92. package/vendor/cli/vendor/client/foreign-memory.js +5 -0
  93. package/vendor/cli/vendor/client/hooks.js +5 -0
  94. package/vendor/cli/vendor/client/model-discovery.js +332 -0
  95. package/vendor/cli/vendor/client/platform.js +5 -0
  96. package/vendor/cli/vendor/client/prefs.js +5 -0
  97. package/vendor/cli/vendor/client/presence-constants.js +5 -0
  98. package/vendor/cli/vendor/client/presence.js +5 -0
  99. package/vendor/cli/vendor/client/record-vault.js +5 -0
  100. package/vendor/cli/vendor/client/session-store.js +5 -0
  101. package/vendor/cli/vendor/client/topup.js +5 -0
  102. package/vendor/cli/vendor/client/touch.js +5 -0
  103. package/vendor/cli/vendor/client/update.js +5 -0
  104. package/vendor/cli/vendor/client/user-models.js +383 -0
  105. package/vendor/cli/vendor/desktop/lib/local/aegis-seal.mjs +5 -0
  106. package/vendor/cli/vendor/desktop/lib/local/agents.js +5 -0
  107. package/vendor/cli/vendor/desktop/lib/local/autonomous.js +86 -0
  108. package/vendor/cli/vendor/desktop/lib/local/context.js +5 -0
  109. package/vendor/cli/vendor/desktop/lib/local/covenant.js +5 -0
  110. package/vendor/cli/vendor/desktop/lib/local/engine.js +576 -14
  111. package/vendor/cli/vendor/desktop/lib/local/entitlement.js +5 -0
  112. package/vendor/cli/vendor/desktop/lib/local/git-scope.js +5 -0
  113. package/vendor/cli/vendor/desktop/lib/local/local.js +5 -0
  114. package/vendor/cli/vendor/desktop/lib/local/prompt.js +5 -0
  115. package/vendor/cli/vendor/desktop/lib/local/queue.js +5 -0
  116. package/vendor/cli/vendor/desktop/lib/local/session-rounds.js +5 -0
  117. package/vendor/cli/vendor/desktop/lib/local/shell.js +88 -9
  118. package/vendor/cli/vendor/desktop/lib/local/tools.js +13 -6
  119. package/vendor/cli/vendor/desktop/lib/local/turn-guard.js +5 -0
  120. package/vendor/cli/vendor/desktop/lib/local/worktree-lock.js +5 -0
  121. package/vendor/cli/vendor/desktop/lib/settings.js +5 -0
  122. package/vendor/cli/vendor/desktop/renderer/usage.js +73 -1
  123. package/vendor/cli/vendor/mcp/server.js +5 -0
  124. package/vendor/cli/vendor/mcp/tools.js +5 -0
  125. package/vendor/cli/vendor/tools/agent-gate.mjs +23 -0
  126. package/vendor/desktop/README.md +11 -0
  127. package/vendor/desktop/bin/aegis.js +5 -0
  128. package/vendor/desktop/lib/auto.js +5 -0
  129. package/vendor/desktop/lib/avatar/companion.js +5 -0
  130. package/vendor/desktop/lib/avatar/cosmetics.js +5 -0
  131. package/vendor/desktop/lib/avatar/events.js +5 -0
  132. package/vendor/desktop/lib/avatar/holder-turn.js +5 -0
  133. package/vendor/desktop/lib/avatar/holders.js +5 -0
  134. package/vendor/desktop/lib/avatar/identity.js +5 -0
  135. package/vendor/desktop/lib/avatar/level.js +5 -0
  136. package/vendor/desktop/lib/avatar/mirror.js +5 -0
  137. package/vendor/desktop/lib/avatar/persona.js +5 -0
  138. package/vendor/desktop/lib/avatar/profile.js +5 -0
  139. package/vendor/desktop/lib/avatar/register.js +5 -0
  140. package/vendor/desktop/lib/avatar/store.js +5 -0
  141. package/vendor/desktop/lib/avatar/tiers.js +5 -0
  142. package/vendor/desktop/lib/avatar/transfer.js +5 -0
  143. package/vendor/desktop/lib/avatar/turn.js +5 -0
  144. package/vendor/desktop/lib/avatar/voice.js +5 -0
  145. package/vendor/desktop/lib/avatar/xp.js +5 -0
  146. package/vendor/desktop/lib/deep-link.js +40 -1
  147. package/vendor/desktop/lib/fingerprint.js +5 -0
  148. package/vendor/desktop/lib/local/aegis-seal.mjs +5 -0
  149. package/vendor/desktop/lib/local/agents.js +5 -0
  150. package/vendor/desktop/lib/local/autonomous.js +86 -0
  151. package/vendor/desktop/lib/local/context.js +5 -0
  152. package/vendor/desktop/lib/local/covenant.js +5 -0
  153. package/vendor/desktop/lib/local/engine.js +576 -14
  154. package/vendor/desktop/lib/local/entitlement.js +5 -0
  155. package/vendor/desktop/lib/local/git-scope.js +5 -0
  156. package/vendor/desktop/lib/local/local.js +5 -0
  157. package/vendor/desktop/lib/local/prompt.js +5 -0
  158. package/vendor/desktop/lib/local/queue.js +5 -0
  159. package/vendor/desktop/lib/local/session-rounds.js +5 -0
  160. package/vendor/desktop/lib/local/shell.js +88 -9
  161. package/vendor/desktop/lib/local/telemetry.js +5 -0
  162. package/vendor/desktop/lib/local/tools.js +13 -6
  163. package/vendor/desktop/lib/local/turn-guard.js +5 -0
  164. package/vendor/desktop/lib/local/worktree-lock.js +5 -0
  165. package/vendor/desktop/lib/provider-key-mirror.js +5 -0
  166. package/vendor/desktop/lib/quick-launcher.js +5 -0
  167. package/vendor/desktop/lib/settings.js +5 -0
  168. package/vendor/desktop/lib/sync/memory-queue.js +5 -0
  169. package/vendor/desktop/lib/sync/persist-gate.js +5 -0
  170. package/vendor/desktop/lib/sync/sessions.js +5 -0
  171. package/vendor/desktop/lib/window-state.js +5 -0
  172. package/vendor/desktop/main.js +293 -6
  173. package/vendor/desktop/package.json +1 -1
  174. package/vendor/desktop/preload.js +32 -0
  175. package/vendor/desktop/renderer/app.js +506 -12
  176. package/vendor/desktop/renderer/avatar/assemble.js +5 -0
  177. package/vendor/desktop/renderer/avatar/avatar.css +7 -0
  178. package/vendor/desktop/renderer/avatar/avatar.js +5 -0
  179. package/vendor/desktop/renderer/avatar/cards.js +5 -0
  180. package/vendor/desktop/renderer/avatar/hud.js +5 -0
  181. package/vendor/desktop/renderer/avatar/machine.js +5 -0
  182. package/vendor/desktop/renderer/avatar/pane.js +5 -0
  183. package/vendor/desktop/renderer/avatar/parts.js +5 -0
  184. package/vendor/desktop/renderer/budget.js +5 -0
  185. package/vendor/desktop/renderer/diff.js +5 -0
  186. package/vendor/desktop/renderer/diffview.js +5 -0
  187. package/vendor/desktop/renderer/fingerprint.css +7 -0
  188. package/vendor/desktop/renderer/fingerprint.js +5 -0
  189. package/vendor/desktop/renderer/fonts/fonts.css +7 -0
  190. package/vendor/desktop/renderer/index.html +9 -2
  191. package/vendor/desktop/renderer/markdown.js +5 -0
  192. package/vendor/desktop/renderer/quick.css +7 -0
  193. package/vendor/desktop/renderer/quick.html +7 -0
  194. package/vendor/desktop/renderer/quick.js +5 -0
  195. package/vendor/desktop/renderer/stream-policy.js +5 -0
  196. package/vendor/desktop/renderer/style.css +39 -0
  197. package/vendor/desktop/renderer/transcript-view.js +5 -0
  198. package/vendor/desktop/renderer/usage.js +73 -1
  199. package/vendor/desktop/vendor/aegis.js +27 -0
  200. package/vendor/desktop/vendor/agent-gate.mjs +23 -0
  201. package/vendor/desktop/vendor/attest.js +5 -0
  202. package/vendor/desktop/vendor/authorship-key.js +5 -0
  203. package/vendor/desktop/vendor/auto-provision.js +5 -0
  204. package/vendor/desktop/vendor/brain-catalog.js +5 -0
  205. package/vendor/desktop/vendor/byok-catalog.js +48 -8
  206. package/vendor/desktop/vendor/credentials.js +5 -0
  207. package/vendor/desktop/vendor/device-fingerprint.js +5 -0
  208. package/vendor/desktop/vendor/env-file.js +5 -0
  209. package/vendor/desktop/vendor/fingerprint.js +5 -0
  210. package/vendor/desktop/vendor/foreign-memory.js +5 -0
  211. package/vendor/desktop/vendor/hooks.js +5 -0
  212. package/vendor/desktop/vendor/model-discovery.js +332 -0
  213. package/vendor/desktop/vendor/platform.js +5 -0
  214. package/vendor/desktop/vendor/prefs.js +5 -0
  215. package/vendor/desktop/vendor/presence-constants.js +5 -0
  216. package/vendor/desktop/vendor/presence.js +5 -0
  217. package/vendor/desktop/vendor/record-vault.js +5 -0
  218. package/vendor/desktop/vendor/session-store.js +5 -0
  219. package/vendor/desktop/vendor/topup.js +5 -0
  220. package/vendor/desktop/vendor/touch.js +5 -0
  221. package/vendor/desktop/vendor/update.js +5 -0
  222. package/vendor/desktop/vendor/user-models.js +383 -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;
@@ -797,6 +1035,7 @@ function createLocalEngine({
797
1035
  // remembering "no" makes the first answer stick.
798
1036
  const sessionDenials = new Map(); // rootSessionId -> Set<toolName>
799
1037
  const pendingApprovals = new Map(); // approvalId -> { resolve }
1038
+ const pendingRoundAsks = new Map(); // askId -> { resolve }
800
1039
 
801
1040
  function sessionAllows(rootId, name) {
802
1041
  const set = sessionAllowlists.get(rootId);
@@ -911,6 +1150,62 @@ function createLocalEngine({
911
1150
  });
912
1151
  }
913
1152
 
1153
+ /** The renderer's rounds-dialog answer resolves the pending
1154
+ * requestRoundsAsk() promise below. An unknown/already-answered id is a
1155
+ * no-op, same contract as respondApproval. */
1156
+ function respondRoundsAsk(askId, decision) {
1157
+ const pending = pendingRoundAsks.get(askId);
1158
+ if (!pending) return { ok: false };
1159
+ pendingRoundAsks.delete(askId);
1160
+ pending.resolve(decision === true || decision === 'continue');
1161
+ return { ok: true };
1162
+ }
1163
+
1164
+ /**
1165
+ * Ask the renderer whether to fund another block of tool rounds, mirroring
1166
+ * requestApproval's shape exactly: pushed over `rootOnDelta` as a `{ rounds }`
1167
+ * chunk (the one channel a detached renderer has into a running turn) and
1168
+ * resolved externally via `respondRoundsAsk`. Resolves `true` (fund one more
1169
+ * block) or `false` (stop here) — never throws. Fails safe to `false`: no
1170
+ * listener, an aborted turn, or an unanswered ask must not keep the loop
1171
+ * waiting forever (or, worse, spend rounds nobody agreed to).
1172
+ */
1173
+ function requestRoundsAsk(rootSessionId, rootOnDelta, signal, info) {
1174
+ return new Promise((resolve) => {
1175
+ if (signal && signal.aborted) {
1176
+ resolve(false);
1177
+ return;
1178
+ }
1179
+ const id = randomUUID();
1180
+ let settled = false;
1181
+ const onAbort = () => finish(false);
1182
+ const finish = (decision) => {
1183
+ if (settled) return;
1184
+ settled = true;
1185
+ pendingRoundAsks.delete(id);
1186
+ if (signal) signal.removeEventListener('abort', onAbort);
1187
+ resolve(decision);
1188
+ };
1189
+ if (signal) signal.addEventListener('abort', onAbort, { once: true });
1190
+ pendingRoundAsks.set(id, { resolve: finish });
1191
+ if (typeof rootOnDelta !== 'function') {
1192
+ finish(false);
1193
+ return;
1194
+ }
1195
+ rootOnDelta({
1196
+ delta: '',
1197
+ rounds: {
1198
+ id,
1199
+ sessionId: rootSessionId,
1200
+ spent: info.spent,
1201
+ extensions: info.extensions,
1202
+ max: info.max,
1203
+ size: info.size,
1204
+ },
1205
+ });
1206
+ });
1207
+ }
1208
+
914
1209
  /**
915
1210
  * The gate itself: read-only tools and already-session-allowed mutating
916
1211
  * tools run exactly like executeTool always did. A first-time mutating
@@ -1150,7 +1445,7 @@ function createLocalEngine({
1150
1445
  // of `providers` — the model list built just below, the renderer's
1151
1446
  // per-provider Settings rows, and the CLI's own `/byok` listing when it
1152
1447
  // runs on this engine — sees one list instead of three opinions.
1153
- providers = withByokAdditions((data && data.providers) || []);
1448
+ providers = withUserModels(withByokAdditions((data && data.providers) || []));
1154
1449
  // The handling fee AEGIS adds on top of the caller's vendor bill. It is
1155
1450
  // the server's own published rate (services/pricing.price_byok_call) and
1156
1451
  // is passed through untouched — never re-derived here, because a client
@@ -1522,6 +1817,12 @@ function createLocalEngine({
1522
1817
  // synthesis pass) instead of a single provider call. UI-gated to the
1523
1818
  // 'aegis' class only (see AUTONOMOUS_CLASS in app.js).
1524
1819
  const autonomous = cls === 'aegis' && Boolean(payload && payload.autonomous);
1820
+ // Opt-in only: the round-horizon dialog (requestRoundsAsk below) needs a
1821
+ // live renderer on the other end of `rootOnDelta` able to answer it. The
1822
+ // interactive CLI session sets this; the queue worker and `-p` one-shot
1823
+ // runs never do (nobody is there to click), so they keep the old
1824
+ // stop-and-record-session behaviour (sessionRounds below) untouched.
1825
+ const roundsAsk = Boolean(payload && payload.roundsAsk);
1525
1826
  const sessionId = (payload && payload.sessionId) || randomUUID();
1526
1827
  // Recursion depth for the task tool: 0 for a real user turn, N+1 for a
1527
1828
  // subagent spawned by depth N. Never set by an IPC caller — only by
@@ -1797,8 +2098,17 @@ function createLocalEngine({
1797
2098
  }
1798
2099
  // A resumed turn gets a small bonus on top of the base horizon so
1799
2100
  // re-orientation does not consume the new budget before any work lands.
1800
- const maxRounds = statedRounds || baseRounds + (resumed ? sessionRounds.bonus(baseRounds) : 0);
2101
+ let maxRounds = statedRounds || baseRounds + (resumed ? sessionRounds.bonus(baseRounds) : 0);
1801
2102
  let round = 0;
2103
+ // Rounds bought by one confirmed extension, and a hard cap on how many
2104
+ // extensions a single turn may spend — matching the upstream engine's
2105
+ // numbers (src/autonomous.js ROUND_EXTENSION_SIZE/MAX_ROUND_EXTENSIONS)
2106
+ // so a turn behaves the same whether it runs there or here. The cap
2107
+ // exists even though the renderer is the one asking: a dialog that
2108
+ // always says yes must still terminate (8 x baseRounds extra rounds).
2109
+ const ROUND_EXTENSION_SIZE = baseRounds;
2110
+ const MAX_ROUND_EXTENSIONS = 8;
2111
+ let extensions = 0;
1802
2112
 
1803
2113
  // Token accounting for the whole TURN, not just its last round. An
1804
2114
  // agentic turn makes one provider call per tool round, and returning only
@@ -1858,11 +2168,49 @@ function createLocalEngine({
1858
2168
  // which is the same "(empty response)" failure the guards below exist
1859
2169
  // to prevent.
1860
2170
  if (round >= maxRounds) {
2171
+ // Before conceding, give an interactive caller the chance to fund
2172
+ // another block of rounds instead of ending the turn outright — the
2173
+ // upstream engine's "asks" contract (src/backend.js requestExtension).
2174
+ // Only reachable with `roundsAsk` AND a live signal: a caller with no
2175
+ // renderer on the other end (queue, `-p`) falls straight through to
2176
+ // the session-hold stop below, unchanged.
2177
+ if (roundsAsk && extensions < MAX_ROUND_EXTENSIONS && !signal.aborted) {
2178
+ const granted = await requestRoundsAsk(rootSessionId, rootOnDelta, signal, {
2179
+ spent: maxRounds,
2180
+ extensions: extensions + 1,
2181
+ max: MAX_ROUND_EXTENSIONS,
2182
+ size: ROUND_EXTENSION_SIZE,
2183
+ });
2184
+ if (granted) {
2185
+ extensions += 1;
2186
+ const spent = maxRounds;
2187
+ maxRounds += ROUND_EXTENSION_SIZE;
2188
+ history.push({
2189
+ role: 'user',
2190
+ content: `You have used all ${spent} tool rounds allowed for this turn; ` +
2191
+ `${ROUND_EXTENSION_SIZE} more have been granted (do not restart). Continue the task ` +
2192
+ 'from exactly where you stopped — do not re-plan, do not repeat work already done, ' +
2193
+ 'and finish with an answer.',
2194
+ });
2195
+ continue;
2196
+ }
2197
+ // Declined (or the extension cap is spent): fall through to the
2198
+ // same session-hold stop a non-interactive caller gets, so a "no"
2199
+ // here is bit-for-bit the old hard stop rather than a dead end.
2200
+ }
2201
+ // The knob is only advice where nobody could have been asked about
2202
+ // it. An interactive caller was already offered another block of
2203
+ // rounds (requestRoundsAsk above) and declined or spent the cap, so
2204
+ // pointing it at an env var it cannot set from inside the app — and
2205
+ // would have to restart to apply — is obsolete text: drop it. The
2206
+ // queue worker and `-p` one-shots have no dialog, so for them the
2207
+ // variable remains the only lever and is still named.
2208
+ const knob = roundsAsk ? '' : `, or raise ${roundEnvName} for a longer single turn`;
1861
2209
  const note =
1862
2210
  `[stopped at ${maxRounds} tool rounds` +
1863
2211
  `${turnUsage.total_tokens ? `, ${turnUsage.total_tokens.toLocaleString()} tokens` : ''}` +
1864
2212
  `. This session holds the work: your next message here resumes it automatically` +
1865
- ` (with a continuation preamble), or raise ${roundEnvName} for a longer single turn.]`;
2213
+ ` (with a continuation preamble)${knob}.]`;
1866
2214
  // File the interruption before returning, so the horizon is a pause
1867
2215
  // in the session rather than the end of the job. `chain` carries the
1868
2216
  // count forward across resumes.
@@ -1922,8 +2270,9 @@ function createLocalEngine({
1922
2270
  // double up in the renderer's live view. When text *has* arrived the
1923
2271
  // turn is not empty — the answer is merely truncated — and a retry
1924
2272
  // would stream it a second time onto the same bubble.
1925
- if (!truncationRetried && !assistantText(res) && isTruncated(res)) {
2273
+ if (!truncationRetried && !assistantText(res) && (isTruncated(res) || reasonedButSilent(res))) {
1926
2274
  truncationRetried = true;
2275
+ const reasoningOnly = reasonedButSilent(res);
1927
2276
  // singlePass: this retry buys *budget*, not a second investigation.
1928
2277
  // The fan-out's workers would re-run the whole task from scratch for
1929
2278
  // it — 3 extra reasoning passes + a synthesis — which is the opposite
@@ -1936,7 +2285,11 @@ function createLocalEngine({
1936
2285
  // bought by round 1, and buying it again here would charge a
1937
2286
  // second one for the same context.
1938
2287
  recallDeep: false,
1939
- 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),
1940
2293
  // Doubling applies to the pooled path only when the caller stated a
1941
2294
  // number. With none stated, the server's effort ladder IS the
1942
2295
  // budget, and sending doubledBudget's 8192 floor would *lower* it
@@ -1963,14 +2316,20 @@ function createLocalEngine({
1963
2316
  // no gathered context to rescue, so a bare completion is just that.
1964
2317
  synthesisDone = true;
1965
2318
  foldPromptIntoHistory();
1966
- 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 });
1967
2326
  // singlePass: same reasoning as the truncation retry above, and it is
1968
2327
  // the same comment's literal promise ("force the summary out of the
1969
2328
  // context it already holds"). Escalating a write-up back into the
1970
2329
  // worker fan-out asked three fresh workers to redo an investigation
1971
2330
  // whose findings are already in `history`, at 4x the cost, to produce
1972
2331
  // a paragraph the model had all the material for.
1973
- res = await dispatch(cls, {
2332
+ const synthesisOpts = {
1974
2333
  ...opts,
1975
2334
  singlePass: true,
1976
2335
  // Same as the truncation retry above: this pass writes up findings
@@ -1979,7 +2338,13 @@ function createLocalEngine({
1979
2338
  messages: history,
1980
2339
  prompt: '',
1981
2340
  tools: [],
1982
- });
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;
1983
2348
  addUsage(res);
1984
2349
  // Same guard again: a cancel landing during the synthesis pass
1985
2350
  // resolves empty too, and without this check it fell through to
@@ -1987,12 +2352,108 @@ function createLocalEngine({
1987
2352
  // "no answer" failure over what was actually just the user hitting
1988
2353
  // Cancel.
1989
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
+ }
1990
2446
  if (!assistantText(res)) {
1991
2447
  throw emptyTurnError({
1992
2448
  cls,
1993
2449
  model,
1994
- 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,
1995
2455
  finishReason: finishReasonOf(res),
2456
+ reasoningChars: reasoningTextOf(res).length,
1996
2457
  });
1997
2458
  }
1998
2459
  return withTurnUsage(res);
@@ -2139,6 +2600,28 @@ function createLocalEngine({
2139
2600
  return localT.unloadAll();
2140
2601
  }
2141
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
+
2142
2625
  return {
2143
2626
  CLASSES,
2144
2627
  listClasses,
@@ -2146,9 +2629,88 @@ function createLocalEngine({
2146
2629
  chat,
2147
2630
  cancel,
2148
2631
  respondApproval,
2632
+ respondRoundsAsk,
2149
2633
  clearSessionApprovals,
2150
2634
  settings,
2151
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(),
2152
2714
  };
2153
2715
  }
2154
2716