@causyne/agent 1.18.0 → 1.20.0

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 (76) hide show
  1. package/package.json +1 -1
  2. package/src/agentLoop.js +2348 -2531
  3. package/src/agentLoop.ts +2865 -0
  4. package/src/checkpoints.d.ts +4 -0
  5. package/src/cliMode.js +30 -17
  6. package/src/commands.js +307 -57
  7. package/src/config.js +22 -0
  8. package/src/contextManager.d.ts +10 -0
  9. package/src/continuum/adapters/antigravity.js +193 -0
  10. package/src/continuum/adapters/antigravity.ts +204 -0
  11. package/src/continuum/adapters/base.js +48 -0
  12. package/src/continuum/adapters/base.ts +57 -0
  13. package/src/continuum/adapters/causyne.js +66 -0
  14. package/src/continuum/adapters/causyne.ts +72 -0
  15. package/src/continuum/adapters/claudeCode.js +171 -0
  16. package/src/continuum/adapters/claudeCode.ts +179 -0
  17. package/src/continuum/adapters/codex.js +181 -0
  18. package/src/continuum/adapters/codex.ts +193 -0
  19. package/src/continuum/adapters/opencode.js +134 -0
  20. package/src/continuum/adapters/opencode.ts +153 -0
  21. package/src/continuum/compactor.js +54 -0
  22. package/src/continuum/compactor.ts +83 -0
  23. package/src/continuum/index.js +8 -0
  24. package/src/continuum/index.ts +9 -0
  25. package/src/continuum/ingest.js +63 -0
  26. package/src/continuum/ingest.ts +89 -0
  27. package/src/continuum/sanitizer.js +55 -0
  28. package/src/continuum/sanitizer.ts +59 -0
  29. package/src/continuum/scanner.js +86 -0
  30. package/src/continuum/scanner.ts +106 -0
  31. package/src/continuum/types.js +3 -0
  32. package/src/continuum/types.ts +51 -0
  33. package/src/continuum/ui/continuumPicker.js +111 -0
  34. package/src/continuum/ui/continuumPicker.ts +145 -0
  35. package/src/cortex/autoCondenser.d.ts +2 -0
  36. package/src/cortex/vectorDb.d.ts +1 -0
  37. package/src/designPalettes.d.ts +2 -0
  38. package/src/devMode.d.ts +1 -0
  39. package/src/dynamicCatalogue.js +5 -3
  40. package/src/dynamicCatalogue.ts +7 -4
  41. package/src/embodimentSession.d.ts +2 -0
  42. package/src/entrypoint.js +12 -0
  43. package/src/memory.d.ts +1 -0
  44. package/src/memoryManager.d.ts +1 -0
  45. package/src/memoryManager.js +10 -6
  46. package/src/modelIds.d.ts +2 -0
  47. package/src/outputStore.d.ts +4 -0
  48. package/src/providers/acp.js +320 -299
  49. package/src/providers/acp.ts +360 -0
  50. package/src/providers/antigravity.js +387 -278
  51. package/src/providers/antigravity.ts +450 -0
  52. package/src/providers/base.d.ts +68 -0
  53. package/src/providers/factory.d.ts +1 -0
  54. package/src/provisioning/capabilityProvisioner.d.ts +2 -0
  55. package/src/sandbox.d.ts +1 -0
  56. package/src/sessionJournal.js +14 -1
  57. package/src/sessionJournal.ts +21 -1
  58. package/src/skillsManager.d.ts +3 -0
  59. package/src/slopDetector.d.ts +3 -0
  60. package/src/taskBuffer.d.ts +1 -0
  61. package/src/tokenTracker.d.ts +1 -0
  62. package/src/toolPacks.d.ts +8 -0
  63. package/src/tools/registry.d.ts +4 -0
  64. package/src/tui/chatRenderer.js +148 -8
  65. package/src/tui/clipboardSync.js +36 -0
  66. package/src/tui/clipboardSync.ts +36 -0
  67. package/src/tui/dialogs.js +15 -2
  68. package/src/tui/home.js +2 -1
  69. package/src/tui/modelPicker.js +254 -0
  70. package/src/tui/modelPicker.ts +318 -0
  71. package/src/tui/prompt.js +90 -8
  72. package/src/tui/selectList.js +20 -0
  73. package/src/tui/sessionPicker.js +185 -0
  74. package/src/tui/sessionPicker.ts +259 -0
  75. package/src/tui/stageSurface.js +9 -0
  76. package/src/tui/statusLine.js +5 -5
@@ -0,0 +1,4 @@
1
+ export function beginTask(...args: any[]): any;
2
+ export function captureBeforeMutation(...args: any[]): any;
3
+ export function pruneStore(...args: any[]): any;
4
+ export function resolveProjectRoot(...args: any[]): any;
package/src/cliMode.js CHANGED
@@ -192,7 +192,7 @@ function openHomeMenu(prompt, conn) {
192
192
  * terminal over after stopping the prompt. That is what keeps the menu from
193
193
  * becoming a second, subtly different CLI.
194
194
  */
195
- async function runHomeAction(action, { prompt, conn, finish }) {
195
+ async function runHomeAction(action, { prompt, conn, finish, loop }) {
196
196
  const reopen = () => { if (prompt) openHomeMenu(prompt, conn); };
197
197
 
198
198
  switch (action.kind) {
@@ -217,11 +217,15 @@ async function runHomeAction(action, { prompt, conn, finish }) {
217
217
  }
218
218
 
219
219
  case 'command': {
220
- const result = await handleInput(action.command, { surface: 'terminal', prompt });
220
+ const result = await handleInput(action.command, { surface: 'terminal', prompt, loop });
221
221
  if (result) {
222
222
  const wrapped = wrapBlock(result.output, conn.renderer.width()).join('\n');
223
223
  conn.renderer.write('\n' + (result.ok ? wrapped : paint('danger', wrapped)) + '\n');
224
224
  }
225
+ if (action.id === 'model' || action.id === 'continuum' || action.id === 'sessions') {
226
+ conn.renderer.write(homeStatusLine({ config: loadConfig() }) + '\n');
227
+ return null;
228
+ }
225
229
  reopen();
226
230
  return null;
227
231
  }
@@ -378,6 +382,18 @@ export async function chatMode({ home = false } = {}) {
378
382
  if (surface) prompt.attachSurface(surface);
379
383
  prompt.attach(conn.renderer);
380
384
  prompt.start();
385
+
386
+ // If active session has prior conversation history, render it into the viewport (OpenCode architecture)
387
+ const initialHistory = loop.memoryManager ? loop.memoryManager.loadHistory() : [];
388
+ if (initialHistory.length > 0) {
389
+ conn.renderer.renderSessionHistory(initialHistory, {
390
+ id: loop.memoryManager?.sessionId,
391
+ title: loop.memoryManager?.sessionTitle,
392
+ messagesCount: initialHistory.length
393
+ });
394
+ if (surface?.viewport) surface.viewport.toBottom();
395
+ }
396
+
381
397
  // The band is blank until something paints it, so the Stage needs a first
382
398
  // frame here. The scrollback path deliberately does NOT get one: there it
383
399
  // has always waited for the first keystroke, and changing that as a side
@@ -428,7 +444,7 @@ export async function chatMode({ home = false } = {}) {
428
444
  // A menu pick arrives through the same read() a typed line does, so there
429
445
  // is one place the loop waits and one place it dispatches.
430
446
  if (task && typeof task === 'object' && task.homeAction) {
431
- const outcome = await runHomeAction(task.homeAction, { prompt, conn, finish });
447
+ const outcome = await runHomeAction(task.homeAction, { prompt, conn, finish, loop });
432
448
  if (outcome === 'exit') break;
433
449
  continue;
434
450
  }
@@ -475,20 +491,14 @@ export async function chatMode({ home = false } = {}) {
475
491
  }
476
492
 
477
493
  if (commandResult.effect === 'pick-session' && prompt) {
478
- const active = commandResult.active;
479
- prompt.openLayer(new SelectLayer({
480
- title: 'Sessions',
481
- emptyText: 'No sessions yet',
482
- items: (commandResult.items || []).map((session) => ({
483
- id: session.id,
484
- label: `${session.id === active ? `${GLYPHS.bullet} ` : ''}${session.title}`,
485
- description: `${session.messageCount} messages ${GLYPHS.dot} ${session.workspace || 'no workspace'}`,
486
- value: session
487
- })),
488
- onPick: (item) => {
489
- if (item) prompt.deliver(`/sessions switch ${item.value.id}`);
490
- }
491
- }));
494
+ const { runInteractiveSessionPicker } = await import('./tui/sessionPicker.js');
495
+ const outcome = await runInteractiveSessionPicker(prompt, {
496
+ loop,
497
+ workspace: loop?.workspaceRoot || process.cwd()
498
+ });
499
+ if (outcome) {
500
+ conn.renderer.write(`\n${outcome}\n`);
501
+ }
492
502
  continue;
493
503
  }
494
504
 
@@ -525,6 +535,9 @@ export async function chatMode({ home = false } = {}) {
525
535
  const wrapped = wrapBlock(commandResult.output, width).join('\n');
526
536
  const body = commandResult.ok ? wrapped : paint('danger', wrapped);
527
537
  conn.renderer.write('\n' + body + '\n');
538
+ if (commandResult.output && (commandResult.output.includes('Now using') || commandResult.output.includes('Active model switched') || commandResult.output.includes('Saved API key'))) {
539
+ conn.renderer.write(homeStatusLine({ config: loadConfig() }) + '\n');
540
+ }
528
541
  if (commandResult.effect === 'exit') { finish(); break; }
529
542
  continue;
530
543
  }
package/src/commands.js CHANGED
@@ -21,8 +21,9 @@ import {
21
21
  import { buildContextText, buildUsageText, buildCheckpointsText, buildUndoText, buildStatusText } from './reporting.js';
22
22
  import { loadConfig, saveConfig } from './config.js';
23
23
  import { resolveAvailableModels, getCuratedModels, getAvailableProvidersOverview } from './dynamicCatalogue.js';
24
- import { DEFAULT_MODEL_BY_PROVIDER } from './modelCatalogue.js';
24
+ import { DEFAULT_MODEL_BY_PROVIDER, PEER_MODEL_CATALOGUE } from './modelCatalogue.js';
25
25
  import { isAcpProvider } from './providers/acp.js';
26
+ import { listSessions, getActiveSessionId } from './sessionStore.js';
26
27
  import {
27
28
  serverStatus, grantServer, revokeServer, addServer, removeServer,
28
29
  connectServer, disconnectServer, refreshServer
@@ -581,30 +582,125 @@ export const COMMANDS = [
581
582
  }
582
583
  },
583
584
 
585
+ {
586
+ name: 'new',
587
+ aliases: ['new-session'],
588
+ scope: 'local',
589
+ usage: '/new',
590
+ description: 'Start a new clean chat session in this workspace',
591
+ dialogTitle: 'New Session',
592
+ run: async (_args = [], context = {}) => {
593
+ const store = await import('./sessionStore.js');
594
+ const memory = context.loop && context.loop.memoryManager;
595
+ const workspace = context.loop?.workspaceRoot || process.cwd();
596
+ const next = memory ? memory.startNewSession('Untitled') : store.createSession(workspace, 'Untitled', true);
597
+ if (context.loop) {
598
+ context.loop.messages = [];
599
+ context.loop.taskId = `cli_chat_${Date.now()}`;
600
+ if (context.loop.tokenTracker && typeof context.loop.tokenTracker.reset === 'function') {
601
+ context.loop.tokenTracker.reset();
602
+ }
603
+ }
604
+ const renderer = context.prompt?.renderer || context.loop?.connection?.renderer;
605
+ if (renderer && typeof renderer.renderSessionHistory === 'function') {
606
+ renderer.renderSessionHistory([], { id: next.id, title: next.title, messagesCount: 0 });
607
+ }
608
+ if (context.prompt?.surface?.viewport && typeof context.prompt.surface.viewport.toBottom === 'function') {
609
+ context.prompt.surface.viewport.toBottom();
610
+ }
611
+ if (context.prompt?.editor?.clear) {
612
+ context.prompt.editor.clear();
613
+ if (typeof context.prompt.scheduleDraw === 'function') context.prompt.scheduleDraw();
614
+ }
615
+ return ok(`Started new session: "${next.title}" (${next.id}).`, { effect: 'inline' });
616
+ }
617
+ },
618
+
584
619
  {
585
620
  name: 'sessions',
586
621
  aliases: ['session'],
587
622
  scope: 'local',
588
- usage: '/sessions [switch <id> | delete <id>]',
623
+ usage: '/sessions [new | switch <id> | delete <id>]',
589
624
  description: 'List chat sessions, or switch to one',
590
625
  dialogTitle: 'Sessions',
591
- // Sessions replaced ONE global chat_history.json that every directory read.
592
- // A session you cannot list or switch to is not a session, so this ships
593
- // with the store rather than after it.
626
+ complete: () => {
627
+ try {
628
+ const rows = listSessions().slice(0, 15);
629
+ return [
630
+ { value: 'new', label: 'new', description: 'start a fresh conversation in this workspace' },
631
+ ...rows.map(r => ({
632
+ value: `switch ${r.id}`,
633
+ label: `switch ${r.id}`,
634
+ description: `${r.title} (${r.messageCount} msgs)`
635
+ }))
636
+ ];
637
+ } catch (e) {
638
+ return [{ value: 'new', label: 'new', description: 'start a fresh conversation' }];
639
+ }
640
+ },
594
641
  run: async (args = [], context = {}) => {
595
642
  const store = await import('./sessionStore.js');
596
643
  const verb = String(args[0] || '').toLowerCase();
597
644
  const memory = context.loop && context.loop.memoryManager;
645
+ const workspace = context.loop?.workspaceRoot || process.cwd();
646
+
647
+ // If interactive TUI prompt is available and no sub-arguments are given, open interactive picker modal
648
+ if ((!args || args.length === 0 || (args.length === 1 && args[0] === '')) && context.prompt) {
649
+ const { runInteractiveSessionPicker } = await import('./tui/sessionPicker.js');
650
+ const message = await runInteractiveSessionPicker(context.prompt, {
651
+ loop: context.loop,
652
+ workspace
653
+ });
654
+ return ok(message, { effect: 'inline' });
655
+ }
656
+
657
+ if (verb === 'new') {
658
+ const next = memory ? memory.startNewSession('Untitled') : store.createSession(workspace, 'Untitled', true);
659
+ if (context.loop) {
660
+ context.loop.messages = [];
661
+ context.loop.taskId = `cli_chat_${Date.now()}`;
662
+ if (context.loop.tokenTracker && typeof context.loop.tokenTracker.reset === 'function') {
663
+ context.loop.tokenTracker.reset();
664
+ }
665
+ }
666
+ if (context.prompt?.editor?.clear) {
667
+ context.prompt.editor.clear();
668
+ if (typeof context.prompt.scheduleDraw === 'function') context.prompt.scheduleDraw();
669
+ }
670
+ return ok(`Started new session: "${next.title}" (${next.id}).`, { effect: 'inline' });
671
+ }
598
672
 
599
673
  if (verb === 'switch' && args[1]) {
600
674
  const next = memory ? memory.useSession(args[1]) : store.switchSession(args[1]);
601
675
  if (!next) return fail(`No session "${args[1]}".`);
602
- if (context.loop) context.loop.messages = next.messages.filter(m => m.role !== 'system');
603
- return ok(`Switched to "${next.title}" (${next.messages.length} messages).`);
676
+ const historyMessages = memory ? memory.loadHistory() : next.messages.filter(m => m.role !== 'system');
677
+ if (context.loop) {
678
+ context.loop.messages = historyMessages;
679
+ context.loop.taskId = `cli_chat_${Date.now()}`;
680
+ if (context.loop.tokenTracker && typeof context.loop.tokenTracker.reset === 'function') {
681
+ context.loop.tokenTracker.reset();
682
+ }
683
+ }
684
+ const renderer = context.prompt?.renderer || context.loop?.connection?.renderer;
685
+ if (renderer && typeof renderer.renderSessionHistory === 'function') {
686
+ renderer.renderSessionHistory(historyMessages, {
687
+ id: next.id,
688
+ title: next.title,
689
+ messagesCount: next.messages.length
690
+ });
691
+ }
692
+ if (context.prompt?.surface?.viewport && typeof context.prompt.surface.viewport.toBottom === 'function') {
693
+ context.prompt.surface.viewport.toBottom();
694
+ }
695
+ if (context.prompt?.editor?.clear) {
696
+ context.prompt.editor.clear();
697
+ if (typeof context.prompt.scheduleDraw === 'function') context.prompt.scheduleDraw();
698
+ }
699
+ return ok(`Switched to "${next.title}" (${next.messages.length} messages, ${next.id}).`, { effect: 'inline' });
604
700
  }
605
701
 
606
702
  if (verb === 'delete' && args[1]) {
607
- return store.deleteSession(args[1]) ? ok('Session deleted.') : fail(`No session "${args[1]}".`);
703
+ return store.deleteSession(args[1]) ? ok(`Deleted session "${args[1]}".`) : fail(`No session "${args[1]}".`);
608
704
  }
609
705
 
610
706
  const rows = store.listSessions();
@@ -624,12 +720,86 @@ export const COMMANDS = [
624
720
  return ok(
625
721
  `${rows.length} session${rows.length === 1 ? '' : 's'} (* = active):\n`
626
722
  + lines.join('\n')
627
- + '\n\nSwitch with /sessions switch <id>. A new directory always starts a new session.',
723
+ + '\n\nSwitch with /sessions switch <id>, or run /sessions to open interactive modal picker.',
628
724
  { effect: 'pick-session', items: rows, active }
629
725
  );
630
726
  }
631
727
  },
632
728
 
729
+ {
730
+ name: 'continuum',
731
+ aliases: ['resume'],
732
+ scope: 'local',
733
+ usage: '/continuum [list | read <id> | adopt <id>]',
734
+ description: 'Cross-agent session extraction and resumption (Antigravity, OpenCode, Codex, Claude Code)',
735
+ dialogTitle: 'Continuum',
736
+ run: async (args = [], context = {}) => {
737
+ const {
738
+ ContinuumScanner,
739
+ adoptContinuumSession,
740
+ runInteractiveContinuum,
741
+ openContinuumPreview
742
+ } = await import('./continuum/index.js');
743
+
744
+ const verb = String(args[0] || '').toLowerCase();
745
+ const targetId = args[1];
746
+
747
+ // If interactive modal prompt is available and no subverb is passed
748
+ if (!verb && context.prompt && typeof context.prompt.openLayer === 'function') {
749
+ const resultText = await runInteractiveContinuum(context.prompt, {
750
+ loop: context.loop
751
+ });
752
+ return ok(resultText, { effect: 'inline' });
753
+ }
754
+
755
+ const scanner = context.scanner || new ContinuumScanner();
756
+
757
+ if (verb === 'read' && targetId) {
758
+ if (context.prompt && typeof context.prompt.openLayer === 'function') {
759
+ const opened = await openContinuumPreview(targetId, context.prompt, scanner);
760
+ if (opened) return ok(`Displaying preview for ${targetId}.`);
761
+ }
762
+ const detail = await scanner.fetchSession(targetId);
763
+ if (!detail) return fail(`No peer session found with ID "${targetId}".`);
764
+ const transcriptText = detail.messages.map(m => `[${m.role.toUpperCase()}] ${m.content}`).join('\n\n');
765
+ return ok(`=== ${detail.title} (${detail.sourceLabel}) ===\nWorkspace: ${detail.workspacePath}\n\n${transcriptText}`);
766
+ }
767
+
768
+ if (verb === 'adopt' && targetId) {
769
+ const adoptRes = await adoptContinuumSession(targetId, {
770
+ scanner,
771
+ currentLoopMessages: context.loop?.messages
772
+ });
773
+ if (!adoptRes.ok) return fail(adoptRes.error || `Failed to adopt session "${targetId}".`);
774
+ if (context.loop?.memoryManager) {
775
+ context.loop.memoryManager.useSession(adoptRes.sessionId);
776
+ if (typeof context.loop.memoryManager.loadHistory === 'function') {
777
+ context.loop.messages = context.loop.memoryManager.loadHistory();
778
+ }
779
+ }
780
+ return ok(`Successfully adopted session "${adoptRes.title}" from ${adoptRes.sourcePlatform.toUpperCase()} (${adoptRes.messageCount} messages compacted).\nActive Causyne session: ${adoptRes.sessionId}.`);
781
+ }
782
+
783
+ // Default or 'list':
784
+ const sessions = await scanner.scanAllSessions({ limit: 40 });
785
+ if (sessions.length === 0) {
786
+ return ok('No peer agent sessions discovered across Antigravity, OpenCode, Codex, or Claude Code.');
787
+ }
788
+
789
+ const lines = sessions.map(s => {
790
+ const when = new Date(s.updatedAt).toISOString().slice(0, 16).replace('T', ' ');
791
+ const ws = s.workspacePath ? path.basename(s.workspacePath) : '(default)';
792
+ return ` [${s.sourceLabel.padEnd(12)}] ${s.id.padEnd(38)} ${when} ${String(s.messageCount).padStart(3)} msgs ${ws}\n ${s.title}`;
793
+ });
794
+
795
+ return ok(
796
+ `Discovered ${sessions.length} cross-agent sessions:\n`
797
+ + lines.join('\n')
798
+ + '\n\nUsage:\n /continuum — open interactive picker\n /continuum adopt <id> — adopt & resume session\n /continuum read <id> — preview full transcript'
799
+ );
800
+ }
801
+ },
802
+
633
803
  {
634
804
  name: 'approvals',
635
805
  scope: 'local',
@@ -663,7 +833,7 @@ export const COMMANDS = [
663
833
 
664
834
  {
665
835
  name: 'clear',
666
- aliases: ['reset', 'new'],
836
+ aliases: ['reset'],
667
837
  scope: 'local',
668
838
  usage: '/clear',
669
839
  description: 'Clear the conversation and start from a fresh context',
@@ -678,6 +848,14 @@ export const COMMANDS = [
678
848
  loop.isInitialized = false;
679
849
  if (typeof loop.rearmAbortController === 'function') loop.rearmAbortController();
680
850
  if (loop.memoryManager) loop.memoryManager.clearHistory();
851
+ const renderer = ctx.prompt?.renderer || loop.connection?.renderer;
852
+ if (renderer && typeof renderer.clearTranscript === 'function') {
853
+ renderer.clearTranscript();
854
+ }
855
+ if (ctx.prompt?.surface?.viewport && typeof ctx.prompt.surface.viewport.toBottom === 'function') {
856
+ ctx.prompt.surface.viewport.toBottom();
857
+ }
858
+ if (ctx.prompt?.scheduleDraw) ctx.prompt.scheduleDraw();
681
859
  return ok('Conversation cleared. The next task starts from a clean context.');
682
860
  }
683
861
  return fail('No active session to clear.');
@@ -767,11 +945,23 @@ export const COMMANDS = [
767
945
 
768
946
  return items;
769
947
  },
770
- run: async (argv) => {
948
+ run: async (argv, ctx = {}) => {
771
949
  const config = loadConfig();
772
950
  const overview = getAvailableProvidersOverview(config);
773
951
 
774
952
  if (argv.length === 0) {
953
+ if (ctx.prompt) {
954
+ const { runInteractiveModelPicker } = await import('./tui/modelPicker.js');
955
+ const output = await runInteractiveModelPicker(ctx.prompt, { loadConfig, saveConfig }, { loop: ctx.loop });
956
+ if (ctx.loop) {
957
+ ctx.loop.config = loadConfig();
958
+ if (typeof ctx.loop.updateTierLimits === 'function') {
959
+ ctx.loop.updateTierLimits();
960
+ }
961
+ }
962
+ return ok(output, { effect: 'inline' });
963
+ }
964
+
775
965
  const lines = [
776
966
  `Active Provider : ${config.provider || 'no provider configured'}`,
777
967
  `Active Model : ${config.model || 'none'}`,
@@ -868,67 +1058,127 @@ export const COMMANDS = [
868
1058
  return ok(`Refreshed ${config.provider} models (${result.models.length} available, source: ${result.source}). Run /model list to view.`);
869
1059
  }
870
1060
 
871
- const requested = argv.join(' ').trim();
1061
+ const rawRequested = argv.join(' ').trim().replace(/^\/model\s+/i, '');
1062
+
1063
+ // Helper to cleanly activate a provider + model, persist config, update live loop & prompt
1064
+ const activateModel = (nextProvider, nextModel, feedbackMessage) => {
1065
+ const isProviderChange = nextProvider !== config.provider;
1066
+ if (isProviderChange) {
1067
+ if (nextProvider === 'antigravity' || nextProvider.startsWith('acp/')) {
1068
+ config.apiKey = '';
1069
+ delete config.baseUrl;
1070
+ } else {
1071
+ config.apiKey = (config.providerKeys && config.providerKeys[nextProvider]) || '';
1072
+ delete config.baseUrl;
1073
+ }
1074
+ }
1075
+ config.provider = nextProvider;
1076
+ config.model = nextModel;
1077
+ saveConfig(config);
1078
+
1079
+ if (ctx.loop) {
1080
+ ctx.loop.config = loadConfig();
1081
+ if (typeof ctx.loop.updateTierLimits === 'function') {
1082
+ ctx.loop.updateTierLimits();
1083
+ }
1084
+ }
1085
+ if (ctx.prompt) {
1086
+ if (typeof ctx.prompt.updateModel === 'function') {
1087
+ ctx.prompt.updateModel(config.provider, config.model);
1088
+ } else if (ctx.prompt.renderer?.status) {
1089
+ ctx.prompt.renderer.status.setSession({ provider: config.provider, model: config.model });
1090
+ if (typeof ctx.prompt.scheduleDraw === 'function') ctx.prompt.scheduleDraw();
1091
+ }
1092
+ }
1093
+ return ok(feedbackMessage || `Now using ${config.provider} / ${config.model}.`, { effect: 'inline' });
1094
+ };
1095
+
1096
+ // 1. Antigravity provider (e.g. antigravity or antigravity/Gemini 3.8 Flash (High))
1097
+ if (rawRequested.toLowerCase() === 'antigravity' || rawRequested.toLowerCase().startsWith('antigravity/')) {
1098
+ const agyModel = rawRequested.includes('/')
1099
+ ? rawRequested.slice(rawRequested.indexOf('/') + 1).trim()
1100
+ : (DEFAULT_MODEL_BY_PROVIDER['antigravity'] || 'Gemini 3.8 Flash (Low)');
1101
+ const agyPeer = overview.acp.find(p => p.id === 'antigravity');
1102
+ const notice = agyPeer && !agyPeer.installed
1103
+ ? `⚠️ Notice: Antigravity CLI (agy) is not installed on this machine.\nSetup: ${agyPeer.setupInstruction}\n\nNow using Google Antigravity / ${agyModel}.`
1104
+ : `Now using Google Antigravity / ${agyModel}.`;
1105
+ return activateModel('antigravity', agyModel, notice);
1106
+ }
872
1107
 
873
- // Check if user requested an ACP peer
874
- const acpTarget = requested.match(/^acp\/([a-z0-9_-]+)(?:\/(.+))?$/i);
1108
+ // 2. acp/<peer> or acp/<peer>/<model>
1109
+ const acpTarget = rawRequested.match(/^acp\/([a-z0-9_-]+)(?:\/(.+))?$/i);
875
1110
  if (acpTarget) {
876
1111
  const peer = acpTarget[1].toLowerCase();
877
1112
  const nextProvider = `acp/${peer}`;
1113
+ const peerModel = acpTarget[2] ? acpTarget[2].trim() : (DEFAULT_MODEL_BY_PROVIDER[nextProvider] || peer);
878
1114
  const peerInfo = overview.acp.find(p => p.id === peer);
879
-
880
- if (nextProvider !== config.provider) { config.apiKey = ''; delete config.baseUrl; }
881
- config.provider = nextProvider;
882
- config.model = acpTarget[2] || DEFAULT_MODEL_BY_PROVIDER[nextProvider] || peer;
883
- saveConfig(config);
884
-
885
- if (peerInfo && !peerInfo.installed) {
886
- return ok(
887
- `⚠️ Notice: "${peerInfo.label}" CLI is not installed on this machine.\n` +
888
- `Binary "${peerInfo.id}" was not found on PATH.\n` +
889
- `Setup: ${peerInfo.setupInstruction}\n\n` +
890
- `Now using ${config.provider} / ${config.model}.`
891
- );
1115
+ const notice = peerInfo && !peerInfo.installed
1116
+ ? `⚠️ Notice: "${peerInfo.label}" CLI is not installed on this machine.\nBinary "${peerInfo.id}" was not found on PATH.\nSetup: ${peerInfo.setupInstruction}\n\nNow using ${nextProvider} / ${peerModel}.`
1117
+ : `Now using ${nextProvider} / ${peerModel}.`;
1118
+ return activateModel(nextProvider, peerModel, notice);
1119
+ }
1120
+
1121
+ // 3. Known ACP peer directly (e.g. opencode, opencode/deepseek-v4.1-flash-free, claude)
1122
+ const slashIndex = rawRequested.indexOf('/');
1123
+ const prefix = (slashIndex > 0 ? rawRequested.slice(0, slashIndex) : rawRequested).toLowerCase();
1124
+ const acpPeer = overview.acp.find(p => p.id === prefix || p.providerKey === prefix);
1125
+ if (acpPeer && acpPeer.id !== 'antigravity') {
1126
+ const nextProvider = acpPeer.providerKey;
1127
+ let peerModel;
1128
+ if (slashIndex > 0) {
1129
+ const rest = rawRequested.slice(slashIndex + 1).trim();
1130
+ if (
1131
+ (PEER_MODEL_CATALOGUE[acpPeer.id] && PEER_MODEL_CATALOGUE[acpPeer.id].includes(rawRequested)) ||
1132
+ (acpPeer.id === 'opencode' && rawRequested.startsWith('opencode/'))
1133
+ ) {
1134
+ peerModel = rawRequested;
1135
+ } else {
1136
+ peerModel = rest;
1137
+ }
1138
+ } else {
1139
+ peerModel = DEFAULT_MODEL_BY_PROVIDER[nextProvider] || acpPeer.id;
892
1140
  }
893
- return ok(`Now using ${config.provider} / ${config.model}.`);
1141
+ const notice = !acpPeer.installed
1142
+ ? `⚠️ Notice: "${acpPeer.label}" CLI is not installed on this machine.\nBinary "${acpPeer.id}" was not found on PATH.\nSetup: ${acpPeer.setupInstruction}\n\nNow using ${nextProvider} / ${peerModel}.`
1143
+ : `Now using ${nextProvider} / ${peerModel}.`;
1144
+ return activateModel(nextProvider, peerModel, notice);
894
1145
  }
895
1146
 
896
- // If peer model is set while in ACP
897
- if (isAcpProvider(config.provider) && requested.includes('/')) {
898
- config.model = requested;
899
- saveConfig(config);
900
- return ok(`Now using ${config.provider} / ${config.model}.`);
1147
+ // 4. Known BYOK provider prefix (e.g. gemini/gemini-2.5-flash, anthropic/claude-3-7-sonnet)
1148
+ const byokProvider = overview.byok.find(p => p.id === prefix || (p.id === 'qwen' && prefix === 'dashscope-byok'));
1149
+ if (byokProvider) {
1150
+ const nextProvider = byokProvider.id;
1151
+ const byokModel = slashIndex > 0 ? rawRequested.slice(slashIndex + 1).trim() : (DEFAULT_MODEL_BY_PROVIDER[nextProvider] || byokProvider.defaultModel);
1152
+ return activateModel(nextProvider, byokModel, `Now using ${nextProvider} / ${byokModel}.`);
901
1153
  }
902
1154
 
903
- // If user typed bare 'antigravity' or 'antigravity/model'
904
- if (requested === 'antigravity' || requested.startsWith('antigravity/')) {
905
- const agyModel = requested.includes('/') ? requested.split('/')[1] : (DEFAULT_MODEL_BY_PROVIDER['antigravity'] || 'Gemini 3.8 Flash (Low)');
906
- if (config.provider !== 'antigravity') { config.apiKey = ''; delete config.baseUrl; }
907
- config.provider = 'antigravity';
908
- config.model = agyModel;
909
- saveConfig(config);
910
- const agyPeer = overview.acp.find(p => p.id === 'antigravity');
911
- if (agyPeer && !agyPeer.installed) {
912
- return ok(
913
- `⚠️ Notice: Antigravity CLI (agy) is not installed on this machine.\n` +
914
- `Setup: ${agyPeer.setupInstruction}\n\n` +
915
- `Now using antigravity / ${config.model}.`
916
- );
1155
+ // 5. Look up by model name across BYOK and ACP catalogues
1156
+ for (const p of overview.byok) {
1157
+ if (p.models && p.models.some(m => m.toLowerCase() === rawRequested.toLowerCase())) {
1158
+ const exactModel = p.models.find(m => m.toLowerCase() === rawRequested.toLowerCase()) || rawRequested;
1159
+ return activateModel(p.id, exactModel, `Now using ${p.id} / ${exactModel}.`);
1160
+ }
1161
+ }
1162
+ for (const peer of overview.acp) {
1163
+ if (peer.models && peer.models.some(m => m.toLowerCase() === rawRequested.toLowerCase())) {
1164
+ const exactModel = peer.models.find(m => m.toLowerCase() === rawRequested.toLowerCase()) || rawRequested;
1165
+ return activateModel(peer.providerKey, exactModel, `Now using ${peer.providerKey} / ${exactModel}.`);
917
1166
  }
918
- return ok(`Now using antigravity / ${config.model}.`);
919
1167
  }
920
1168
 
921
- const separator = requested.indexOf('/');
922
- if (separator > 0) {
923
- const provider = requested.slice(0, separator);
924
- if (provider !== config.provider) { config.apiKey = ''; delete config.baseUrl; }
925
- config.provider = provider;
926
- config.model = requested.slice(separator + 1);
1169
+ // 6. If currently in ACP and model is custom for that peer
1170
+ if (isAcpProvider(config.provider)) {
1171
+ return activateModel(config.provider, rawRequested, `Now using ${config.provider} / ${rawRequested}.`);
1172
+ }
1173
+
1174
+ // 7. Generic provider/model separator or bare model
1175
+ if (slashIndex > 0) {
1176
+ const prov = rawRequested.slice(0, slashIndex).trim();
1177
+ const mod = rawRequested.slice(slashIndex + 1).trim();
1178
+ return activateModel(prov, mod, `Now using ${prov} / ${mod}.`);
927
1179
  } else {
928
- config.model = requested;
1180
+ return activateModel(config.provider || 'antigravity', rawRequested, `Now using ${config.provider || 'antigravity'} / ${rawRequested}.`);
929
1181
  }
930
- saveConfig(config);
931
- return ok(`Now using ${config.provider} / ${config.model}.`);
932
1182
  }
933
1183
  },
934
1184
 
package/src/config.js CHANGED
@@ -78,6 +78,21 @@ export function loadConfig() {
78
78
  }
79
79
  }
80
80
 
81
+ // Decrypt provider-specific API keys if stored
82
+ if (parsed.providerKeys && typeof parsed.providerKeys === 'object') {
83
+ for (const [provider, keyVal] of Object.entries(parsed.providerKeys)) {
84
+ if (typeof keyVal === 'string' && keyVal) {
85
+ parsed.providerKeys[provider] = decryptString(keyVal);
86
+ }
87
+ }
88
+ }
89
+ if (parsed.apiKey && parsed.provider) {
90
+ parsed.providerKeys = parsed.providerKeys || {};
91
+ if (!parsed.providerKeys[parsed.provider]) {
92
+ parsed.providerKeys[parsed.provider] = parsed.apiKey;
93
+ }
94
+ }
95
+
81
96
  // Self-heal a model id written before src/modelIds.js existed.
82
97
  const canonicalModel = canonicalModelId(parsed.model);
83
98
  if (canonicalModel !== parsed.model) {
@@ -265,6 +280,13 @@ export function saveConfig(config) {
265
280
  if (configToSave.apiKey) {
266
281
  configToSave.apiKey = encryptString(configToSave.apiKey);
267
282
  }
283
+ if (configToSave.providerKeys && typeof configToSave.providerKeys === 'object') {
284
+ for (const [provider, keyVal] of Object.entries(configToSave.providerKeys)) {
285
+ if (typeof keyVal === 'string' && keyVal) {
286
+ configToSave.providerKeys[provider] = encryptString(keyVal);
287
+ }
288
+ }
289
+ }
268
290
 
269
291
  // SECURITY: Config file contains encrypted keys, must be 0600 (owner read/write only)
270
292
  fs.writeFileSync(CONFIG_FILE, JSON.stringify(configToSave, null, 2), { encoding: 'utf8', mode: 0o600 });
@@ -0,0 +1,10 @@
1
+ export function resolveCharPool(...args: any[]): any;
2
+ export function measureMessages(...args: any[]): any;
3
+ export function resultCapFor(...args: any[]): any;
4
+ export function decayToolResults(...args: any[]): any;
5
+ export function buildWindow(...args: any[]): any;
6
+ export function compactInPlace(...args: any[]): any;
7
+ export function describeDroppedMessages(...args: any[]): any;
8
+ export function sanitizeSequences(...args: any[]): any;
9
+ export function applyProgressiveCompaction(...args: any[]): any;
10
+ export function snipOversizedToolOutputs(...args: any[]): any;