@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
@@ -20,6 +20,7 @@ import { sessionBanner } from './banner.js';
20
20
  import { describeTool } from './toolDisplay.js';
21
21
  import { approvalDiff } from './diff.js';
22
22
  import { StatusLine } from './statusLine.js';
23
+ import { barBlock } from './block.js';
23
24
 
24
25
  // Bound the preview AFTER wrapping, not by source newlines: one 400 KB line of
25
26
  // minified output would otherwise become thousands of rows and lock the
@@ -289,6 +290,15 @@ export class ChatRenderer {
289
290
  });
290
291
  }
291
292
 
293
+ updateTailFrame(kind, produce, meta = null) {
294
+ if (!this.transcript) { produce(); return; }
295
+ this.transcript.replaceTail({
296
+ kind,
297
+ meta,
298
+ produce: (width) => this.capture(width, produce)
299
+ });
300
+ }
301
+
292
302
  /**
293
303
  * Run a producer with write() redirected and the width pinned.
294
304
  */
@@ -503,6 +513,91 @@ export class ChatRenderer {
503
513
  // Frames
504
514
  // -------------------------------------------------------------------------
505
515
 
516
+ renderUserMessage(content) {
517
+ const text = typeof content === 'string'
518
+ ? content
519
+ : (Array.isArray(content)
520
+ ? content.map(p => (typeof p === 'string' ? p : (p && p.text) || '')).filter(Boolean).join('\n')
521
+ : String(content || ''));
522
+ if (!text.trim()) return;
523
+
524
+ this.frame('user', () => {
525
+ const width = this.measure();
526
+ const blockWidth = Math.max(8, width - 1);
527
+ const innerWidth = Math.max(8, blockWidth - visibleWidth(GLYPHS.bar) - 1);
528
+ const rows = barBlock(
529
+ wrapBlock(safeDisplay(text), innerWidth),
530
+ { width: blockWidth, role: 'user', filled: true, surface: 'surfaceHi' }
531
+ );
532
+ this.write();
533
+ for (const row of rows) {
534
+ this.write(row);
535
+ }
536
+ this.write();
537
+ });
538
+ }
539
+
540
+ renderAssistantMessage(content) {
541
+ const text = typeof content === 'string'
542
+ ? content
543
+ : (Array.isArray(content)
544
+ ? content.map(p => (typeof p === 'string' ? p : (p && p.text) || '')).filter(Boolean).join('\n')
545
+ : String(content || ''));
546
+ if (!text.trim()) return;
547
+
548
+ this.onAgentMessage({ content: text });
549
+ }
550
+
551
+ renderSessionDivider(info = {}) {
552
+ this.frame('session', () => {
553
+ const width = this.measure();
554
+ const title = safeDisplay(info.title || 'Session');
555
+ const count = info.messagesCount ?? 0;
556
+ const countText = count > 0 ? ` (${count} message${count === 1 ? '' : 's'})` : '';
557
+ const badgeText = `${title}${countText}`;
558
+ const ruleWidth = Math.max(2, Math.floor((width - visibleWidth(badgeText) - 4) / 2));
559
+ this.write();
560
+ this.write(`${paint('rule', GLYPHS.hLine.repeat(ruleWidth))} ${bold(paint('accent', title))}${dim(countText)} ${paint('rule', GLYPHS.hLine.repeat(ruleWidth))}`);
561
+ this.write();
562
+ });
563
+ }
564
+
565
+ clearTranscript() {
566
+ if (this.transcript && typeof this.transcript.clear === 'function') {
567
+ this.transcript.clear();
568
+ }
569
+ }
570
+
571
+ /**
572
+ * Render conversation history frames from a selected or resumed session.
573
+ * Mirrors OpenCode's session conversation loader so prior turns are visible in viewport.
574
+ */
575
+ renderSessionHistory(messages = [], sessionInfo = null) {
576
+ this.clearTranscript();
577
+
578
+ if (sessionInfo && (sessionInfo.title || sessionInfo.id)) {
579
+ this.renderSessionDivider(sessionInfo);
580
+ }
581
+
582
+ for (const msg of messages) {
583
+ if (!msg) continue;
584
+ const role = String(msg.role || '').toLowerCase();
585
+ if (role === 'user') {
586
+ this.renderUserMessage(msg.content);
587
+ } else if (role === 'assistant') {
588
+ this.renderAssistantMessage(msg.content);
589
+ } else if (role === 'system') {
590
+ const text = typeof msg.content === 'string' ? msg.content : '';
591
+ if (text.startsWith('[Continuum Context')) {
592
+ this.frame('notice', () => {
593
+ const firstLine = text.split('\n')[0] || '[Continuum Context]';
594
+ this.write(`${paint('accent', GLYPHS.bullet)} ${dim(firstLine)}`);
595
+ });
596
+ }
597
+ }
598
+ }
599
+ }
600
+
506
601
  onAgentMessage(msg) {
507
602
  const content = safeDisplay(msg.content || '');
508
603
  this.frame('assistant', () => {
@@ -529,28 +624,72 @@ export class ChatRenderer {
529
624
  * Reasoning that shouts as loudly as the reply trains the user to read
530
625
  * neither, and the reply is the part they asked for.
531
626
  */
627
+ /**
628
+ * The chain of thought the user requested: streamed live directly into the
629
+ * chat transcript, with real-time updates and clear elapsed time.
630
+ */
532
631
  onAgentReasoning(msg) {
533
632
  const content = safeDisplay(msg.content || '');
534
- if (!content.trim()) return;
535
- this.frame('reasoning', () => this.renderReasoning(content), { reasoning: true });
633
+ const isStreaming = Boolean(msg.streaming);
634
+ const elapsedMs = Number(msg.elapsedMs) || 0;
635
+ const durationText = elapsedMs > 0 ? formatDuration(elapsedMs) : '';
636
+
637
+ if (isStreaming) {
638
+ if (!this._activeReasoning) {
639
+ this._activeReasoning = true;
640
+ this.frame('reasoning', () => this.renderReasoning(content, { streaming: true }), { reasoning: true });
641
+ } else {
642
+ this.updateTailFrame('reasoning', () => this.renderReasoning(content, { streaming: true }), { reasoning: true });
643
+ }
644
+ return;
645
+ }
646
+
647
+ if (this._activeReasoning) {
648
+ this._activeReasoning = false;
649
+ this.updateTailFrame('reasoning', () => this.renderReasoning(content, { streaming: false, durationText }), { reasoning: true, done: true });
650
+ } else if (content.trim()) {
651
+ this.frame('reasoning', () => this.renderReasoning(content, { streaming: false, durationText }), { reasoning: true, done: true });
652
+ }
536
653
  }
537
654
 
538
- renderReasoning(content) {
655
+ renderReasoning(content, { streaming = false, durationText = '' } = {}) {
539
656
  const width = this.measure();
540
- const rows = wrapBlock(content, Math.max(20, width - 4));
657
+ const rows = content.trim()
658
+ ? wrapBlock(content, Math.max(20, width - 4))
659
+ : ['Contemplating task and formulating approach…'];
541
660
 
542
661
  this.write();
543
- this.write(`${paint('muted', GLYPHS.vLine)} ${dim('thinking')}`);
544
- for (const row of rows.slice(0, REASONING_LINES)) {
545
- this.write(`${paint('rule', GLYPHS.vLine)} ${dim(row)}`);
662
+ if (streaming) {
663
+ this.write(`${paint('warn', GLYPHS.vLine || '│')} ${bold(paint('warn', 'thinking…'))}`);
664
+ } else {
665
+ const timePart = durationText ? ` · ${durationText}` : '';
666
+ this.write(`${paint('muted', GLYPHS.vLine || '│')} ${dim(`thinking${timePart}`)}`);
546
667
  }
668
+
669
+ const displayRows = rows.slice(0, REASONING_LINES);
670
+ for (const row of displayRows) {
671
+ this.write(`${paint('rule', GLYPHS.vLine || '│')} ${dim(row)}`);
672
+ }
673
+
547
674
  if (rows.length > REASONING_LINES) {
548
675
  const hidden = rows.length - REASONING_LINES;
549
- this.write(`${paint('rule', GLYPHS.corner)} ${dim(`${GLYPHS.ellipsis} ${hidden} more line${hidden === 1 ? '' : 's'} of reasoning`)}`);
676
+ this.write(`${paint('rule', GLYPHS.corner || '└')} ${dim(`${GLYPHS.ellipsis} ${hidden} more line${hidden === 1 ? '' : 's'} of reasoning`)}`);
677
+ } else if (streaming) {
678
+ this.write(`${paint('rule', GLYPHS.corner || '└')} ${dim('streaming thoughts…')}`);
679
+ } else {
680
+ this.write(`${paint('rule', GLYPHS.corner || '└')}`);
550
681
  }
551
682
  this.write();
552
683
  }
553
684
 
685
+ onAgentActivity(msg) {
686
+ const text = safeDisplay(msg.activity || msg.message || '').trim();
687
+ if (!text) return;
688
+ this.frame('notice', () => {
689
+ this.write(`${paint('accent', GLYPHS.arrow || '▸')} ${dim(text)}`);
690
+ }, { activity: true });
691
+ }
692
+
554
693
  onAgentPlan(msg) {
555
694
  if (!Array.isArray(msg.plan) || msg.plan.length === 0) return;
556
695
  const plan = msg.plan.slice();
@@ -963,6 +1102,7 @@ export class ChatRenderer {
963
1102
 
964
1103
  switch (msg.type) {
965
1104
  case 'status': this.onStatus(msg); return true;
1105
+ case 'agent_activity': this.onAgentActivity(msg); return true;
966
1106
  case 'agent_message': this.onAgentMessage(msg); return true;
967
1107
  case 'agent_reasoning': this.onAgentReasoning(msg); return true;
968
1108
  case 'agent_plan': this.onAgentPlan(msg); return true;
@@ -0,0 +1,36 @@
1
+ // Sovereign Synchronous Clipboard Reader for TUI prompts & modal dialogs.
2
+ // Supports macOS (pbpaste), Windows (powershell Get-Clipboard), and Linux (wl-paste, xclip).
3
+ import { execFileSync } from 'node:child_process';
4
+ /**
5
+ * Read system clipboard text synchronously without hanging or throwing.
6
+ * Returns empty string if clipboard is empty, unavailable, or unsupported.
7
+ */
8
+ export function readClipboardSync() {
9
+ try {
10
+ if (process.platform === 'darwin') {
11
+ return execFileSync('pbpaste', { encoding: 'utf8', timeout: 500 });
12
+ }
13
+ if (process.platform === 'win32') {
14
+ return execFileSync('powershell.exe', ['-NoProfile', '-Command', 'Get-Clipboard'], {
15
+ encoding: 'utf8',
16
+ timeout: 1000,
17
+ windowsHide: true
18
+ });
19
+ }
20
+ if (process.platform === 'linux') {
21
+ try {
22
+ return execFileSync('wl-paste', { encoding: 'utf8', timeout: 500 });
23
+ }
24
+ catch {
25
+ return execFileSync('xclip', ['-selection', 'clipboard', '-o'], {
26
+ encoding: 'utf8',
27
+ timeout: 500
28
+ });
29
+ }
30
+ }
31
+ }
32
+ catch {
33
+ // Clipboard reading is best-effort: never crash the TUI on failure
34
+ }
35
+ return '';
36
+ }
@@ -0,0 +1,36 @@
1
+ // Sovereign Synchronous Clipboard Reader for TUI prompts & modal dialogs.
2
+ // Supports macOS (pbpaste), Windows (powershell Get-Clipboard), and Linux (wl-paste, xclip).
3
+
4
+ import { execFileSync } from 'node:child_process';
5
+
6
+ /**
7
+ * Read system clipboard text synchronously without hanging or throwing.
8
+ * Returns empty string if clipboard is empty, unavailable, or unsupported.
9
+ */
10
+ export function readClipboardSync(): string {
11
+ try {
12
+ if (process.platform === 'darwin') {
13
+ return execFileSync('pbpaste', { encoding: 'utf8', timeout: 500 });
14
+ }
15
+ if (process.platform === 'win32') {
16
+ return execFileSync('powershell.exe', ['-NoProfile', '-Command', 'Get-Clipboard'], {
17
+ encoding: 'utf8',
18
+ timeout: 1000,
19
+ windowsHide: true
20
+ });
21
+ }
22
+ if (process.platform === 'linux') {
23
+ try {
24
+ return execFileSync('wl-paste', { encoding: 'utf8', timeout: 500 });
25
+ } catch {
26
+ return execFileSync('xclip', ['-selection', 'clipboard', '-o'], {
27
+ encoding: 'utf8',
28
+ timeout: 500
29
+ });
30
+ }
31
+ }
32
+ } catch {
33
+ // Clipboard reading is best-effort: never crash the TUI on failure
34
+ }
35
+ return '';
36
+ }
@@ -23,6 +23,7 @@ import { paint, bold, dim, badge, GLYPHS } from './theme.js';
23
23
  import { truncate, wrap, visibleWidth, safeDisplay, shortenHome } from './text.js';
24
24
  import { approvalDiff } from './diff.js';
25
25
  import { isChar } from './keys.js';
26
+ import { readClipboardSync } from './clipboardSync.js';
26
27
 
27
28
  /**
28
29
  * A picker. `items` are SelectList items; `onPick(item)` fires on enter.
@@ -121,7 +122,7 @@ export class InputLayer extends Layer {
121
122
 
122
123
  // Park the caret after what is displayed — which for a masked field is the
123
124
  // dot count, not the character count, or the caret drifts off the value.
124
- this.cursor = { x: 2 + (this.mask ? raw.length : visibleWidth(raw.slice(0, this.editor.col))), y: rows.length - 1 };
125
+ this.cursor = { x: 2 + (this.mask ? this.editor.col : visibleWidth(raw.slice(0, this.editor.col))), y: rows.length - 1 };
125
126
  return rows;
126
127
  }
127
128
 
@@ -148,7 +149,11 @@ export class InputLayer extends Layer {
148
149
  case 'home': this.editor.moveHome(); return 'handled';
149
150
  case 'end': this.editor.moveEnd(); return 'handled';
150
151
  case 'char': this.editor.insert(event.text); return 'handled';
151
- case 'paste': this.editor.insert(event.text); return 'handled';
152
+ case 'paste': {
153
+ const clean = String(event.text || '').replace(/[\r\n]+/g, '').trim();
154
+ if (clean) this.editor.insert(clean);
155
+ return 'handled';
156
+ }
152
157
  default: break;
153
158
  }
154
159
 
@@ -159,6 +164,14 @@ export class InputLayer extends Layer {
159
164
  case 'k': this.editor.killToEnd(); return 'handled';
160
165
  case 'u': this.editor.killToStart(); return 'handled';
161
166
  case 'w': this.editor.killWordLeft(); return 'handled';
167
+ case 'v': {
168
+ const text = readClipboardSync();
169
+ if (text) {
170
+ const clean = String(text).replace(/[\r\n]+/g, '').trim();
171
+ if (clean) this.editor.insert(clean);
172
+ }
173
+ return 'handled';
174
+ }
162
175
  default: break;
163
176
  }
164
177
  }
package/src/tui/home.js CHANGED
@@ -62,8 +62,9 @@ export const PRIMARY_ACTIONS = [
62
62
  * stays readable while the complete command surface remains discoverable.
63
63
  */
64
64
  export const MORE_ACTIONS = [
65
+ { id: 'continuum', label: 'continuum', category: 'workspace', hint: 'resume past sessions across Antigravity, OpenCode, Codex, Claude Code', kind: 'command', command: '/continuum' },
65
66
  { id: 'sessions', label: 'sessions', category: 'workspace', hint: 'browse saved local sessions', kind: 'command', command: '/sessions' },
66
- { id: 'model', label: 'model', category: 'workspace', hint: 'show the active provider and model', kind: 'command', command: '/model' },
67
+ { id: 'model', label: 'model', category: 'workspace', hint: 'choose or switch active provider and model', kind: 'command', command: '/model' },
67
68
  { id: 'approvals', label: 'approvals', category: 'workspace', hint: 'review standing session approvals', kind: 'command', command: '/approvals' },
68
69
  {
69
70
  id: 'context', label: 'context', category: 'reports', hint: 'what fills the context window', kind: 'stay',
@@ -0,0 +1,254 @@
1
+ // Sovereign Interactive Model Picker — modal dialog for ACP & BYOK models.
2
+ //
3
+ // Pure Node over ./dialogs.js, ../dynamicCatalogue.js, and ../config.js.
4
+ // No shell, zero malware, source-available under BUSL-1.1.
5
+ // @ts-expect-error untyped local TUI dialogs
6
+ import { SelectLayer, InputLayer } from './dialogs.js';
7
+ import { loadConfig, saveConfig } from '../config.js';
8
+ import { getAvailableProvidersOverview } from '../dynamicCatalogue.js';
9
+ async function showConfiguringAnimation(providerLabel) {
10
+ if (!process.stdout.isTTY)
11
+ return;
12
+ const frames = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
13
+ const text = `Configuring ${providerLabel} in secure local vault…`;
14
+ for (let i = 0; i < 5; i++) {
15
+ const f = frames[i % frames.length];
16
+ process.stdout.write(`\r \x1b[36m${f}\x1b[0m ${text}`);
17
+ await new Promise(r => setTimeout(r, 60));
18
+ }
19
+ process.stdout.write(`\r\x1b[K \x1b[32m✓\x1b[0m ${providerLabel} credentials saved.\n`);
20
+ }
21
+ /**
22
+ * Build items for SelectLayer categorized by ACP peers and BYOK providers.
23
+ */
24
+ export function buildModelPickerItems(config, overview) {
25
+ const items = [];
26
+ const activeProvider = config.provider || '';
27
+ const activeModel = config.model || '';
28
+ // 1. ACP Peer Agents & Sovereign Local Engines
29
+ for (const peer of overview.acp) {
30
+ const isCurrentProvider = activeProvider === peer.providerKey;
31
+ const catTitle = peer.installed
32
+ ? `ACP · ${peer.label} (ready)`
33
+ : `ACP · ${peer.label} (not installed)`;
34
+ if (peer.installed && Array.isArray(peer.models) && peer.models.length > 0) {
35
+ for (const m of peer.models) {
36
+ const isCurrent = isCurrentProvider && activeModel === m;
37
+ items.push({
38
+ id: `${peer.providerKey}/${m}`,
39
+ label: m,
40
+ category: catTitle,
41
+ description: isCurrent ? '● active' : 'ready',
42
+ value: {
43
+ type: 'acp',
44
+ providerId: peer.providerKey,
45
+ modelId: m,
46
+ providerLabel: peer.label,
47
+ installed: true,
48
+ isCurrent,
49
+ isConfigured: true,
50
+ setupInstruction: peer.setupInstruction
51
+ }
52
+ });
53
+ }
54
+ }
55
+ else {
56
+ // Uninstalled ACP agent: show entry so user can see it's supported
57
+ items.push({
58
+ id: `${peer.providerKey}:uninstalled`,
59
+ label: peer.label,
60
+ category: catTitle,
61
+ description: 'not installed — setup needed',
62
+ value: {
63
+ type: 'acp',
64
+ providerId: peer.providerKey,
65
+ modelId: peer.models[0] || peer.id,
66
+ providerLabel: peer.label,
67
+ installed: false,
68
+ isCurrent: false,
69
+ isConfigured: false,
70
+ setupInstruction: peer.setupInstruction
71
+ }
72
+ });
73
+ }
74
+ }
75
+ // 2. BYOK Providers (Cloud & Local APIs)
76
+ for (const p of overview.byok) {
77
+ const isCurrentProvider = activeProvider === p.id || (p.id === 'qwen' && activeProvider === 'dashscope-byok');
78
+ const catTitle = p.id === 'ollama'
79
+ ? `BYOK · ${p.label}`
80
+ : `BYOK · ${p.label} ${p.isConfigured ? '(configured)' : '(needs key)'}`;
81
+ const models = Array.isArray(p.models) && p.models.length > 0 ? p.models : [p.defaultModel];
82
+ for (const m of models) {
83
+ const isCurrent = isCurrentProvider && activeModel === m;
84
+ const desc = isCurrent ? '● active' : (p.id === 'ollama' ? 'local' : (p.isConfigured ? 'configured' : 'needs API key'));
85
+ items.push({
86
+ id: `${p.id}/${m}`,
87
+ label: m,
88
+ category: catTitle,
89
+ description: desc,
90
+ value: {
91
+ type: 'byok',
92
+ providerId: p.id,
93
+ modelId: m,
94
+ providerLabel: p.label,
95
+ installed: true,
96
+ isCurrent,
97
+ isConfigured: p.isConfigured,
98
+ envVar: p.envVar
99
+ }
100
+ });
101
+ }
102
+ }
103
+ return items;
104
+ }
105
+ /**
106
+ * Run interactive model picker in the provided TUI prompt.
107
+ *
108
+ * Automatically handles:
109
+ * - Direct selection of ACP models without prompting for an API key.
110
+ * - Direct selection of configured BYOK models without prompting for an API key.
111
+ * - InputLayer modal prompt for API key when selecting an unconfigured BYOK model,
112
+ * safely encrypting it into ~/.causyne/config.json.
113
+ * - Synchronous runtime loop re-initialization so the live session switches immediately.
114
+ */
115
+ export async function runInteractiveModelPicker(prompt, store = { loadConfig, saveConfig }, options = {}) {
116
+ if (!prompt || typeof prompt.openLayer !== 'function') {
117
+ return 'Run causyne in an interactive terminal to use the model picker.';
118
+ }
119
+ const config = store.loadConfig();
120
+ const overview = getAvailableProvidersOverview(config);
121
+ const items = buildModelPickerItems(config, overview);
122
+ const picked = await new Promise((resolve) => {
123
+ const layer = new SelectLayer({
124
+ title: 'Select Model',
125
+ placeholder: 'type to filter (e.g. gemini, sonnet, opencode)…',
126
+ emptyText: 'No models matched your search',
127
+ items,
128
+ width: 76,
129
+ height: 20,
130
+ onPick: resolve
131
+ });
132
+ prompt.openLayer(layer);
133
+ });
134
+ const notifyPromptAndClean = (providerId, modelId) => {
135
+ if (typeof prompt.updateModel === 'function') {
136
+ prompt.updateModel(providerId, modelId);
137
+ }
138
+ else if (prompt.renderer?.status) {
139
+ prompt.renderer.status.setSession({ provider: providerId, model: modelId });
140
+ if (typeof prompt.scheduleDraw === 'function')
141
+ prompt.scheduleDraw();
142
+ }
143
+ if (prompt.editor && typeof prompt.editor.clear === 'function') {
144
+ prompt.editor.clear();
145
+ if (typeof prompt.scheduleDraw === 'function')
146
+ prompt.scheduleDraw();
147
+ }
148
+ };
149
+ if (!picked || !picked.value) {
150
+ if (prompt.editor && typeof prompt.editor.clear === 'function') {
151
+ prompt.editor.clear();
152
+ if (typeof prompt.scheduleDraw === 'function')
153
+ prompt.scheduleDraw();
154
+ }
155
+ return 'Cancelled. Model was not changed.';
156
+ }
157
+ const target = picked.value;
158
+ // Case 1: ACP Peer Agent or Antigravity
159
+ if (target.type === 'acp') {
160
+ if (!target.installed) {
161
+ if (prompt.editor && typeof prompt.editor.clear === 'function') {
162
+ prompt.editor.clear();
163
+ if (typeof prompt.scheduleDraw === 'function')
164
+ prompt.scheduleDraw();
165
+ }
166
+ return (`⚠️ Notice: "${target.providerLabel}" is not installed on this machine.\n` +
167
+ `Setup: ${target.setupInstruction || 'Install the CLI binary.'}\n\n` +
168
+ `Model was not changed.`);
169
+ }
170
+ config['provider'] = target.providerId;
171
+ config['model'] = target.modelId;
172
+ config['apiKey'] = '';
173
+ delete config['baseUrl'];
174
+ store.saveConfig(config);
175
+ if (options.loop) {
176
+ options.loop.config = config;
177
+ if (typeof options.loop.updateTierLimits === 'function') {
178
+ options.loop.updateTierLimits();
179
+ }
180
+ }
181
+ notifyPromptAndClean(target.providerId, target.modelId);
182
+ return `Now using ${target.providerLabel} / ${target.modelId}.`;
183
+ }
184
+ // Case 2: BYOK Provider (Cloud or Local API)
185
+ let existingKey = '';
186
+ const providerKeys = (config['providerKeys'] && typeof config['providerKeys'] === 'object') ? config['providerKeys'] : {};
187
+ if (config['provider'] === target.providerId && typeof config['apiKey'] === 'string' && config['apiKey']) {
188
+ existingKey = config['apiKey'];
189
+ }
190
+ else if (providerKeys[target.providerId] || (target.providerId === 'qwen' && providerKeys['dashscope-byok'])) {
191
+ existingKey = providerKeys[target.providerId] || providerKeys['dashscope-byok'] || '';
192
+ }
193
+ else if (target.envVar && process.env[target.envVar]) {
194
+ existingKey = process.env[target.envVar] || '';
195
+ }
196
+ // If provider is Ollama (needs no key) or key is already present
197
+ if (target.providerId === 'ollama' || existingKey) {
198
+ config['provider'] = target.providerId;
199
+ config['model'] = target.modelId;
200
+ if (existingKey) {
201
+ config['apiKey'] = existingKey;
202
+ config['providerKeys'] = providerKeys;
203
+ config['providerKeys'][target.providerId] = existingKey;
204
+ }
205
+ store.saveConfig(config);
206
+ if (options.loop) {
207
+ options.loop.config = config;
208
+ if (typeof options.loop.updateTierLimits === 'function') {
209
+ options.loop.updateTierLimits();
210
+ }
211
+ }
212
+ notifyPromptAndClean(target.providerId, target.modelId);
213
+ return `Now using ${target.providerLabel} / ${target.modelId}.`;
214
+ }
215
+ // Key is required: open modal input dialog (InputLayer)
216
+ const enteredKey = await new Promise((resolve) => {
217
+ const layer = new InputLayer({
218
+ title: `Set API Key · ${target.providerLabel}`,
219
+ lines: [
220
+ `Enter your ${target.providerLabel} API key to use ${target.modelId}.`,
221
+ 'Stored encrypted in your local vault (~/.causyne/config.json).'
222
+ ],
223
+ mask: true,
224
+ placeholder: 'paste API key (Esc to cancel)',
225
+ onSubmit: resolve,
226
+ onCancel: () => resolve(null)
227
+ });
228
+ prompt.openLayer(layer);
229
+ });
230
+ if (!enteredKey || !enteredKey.trim()) {
231
+ if (prompt.editor && typeof prompt.editor.clear === 'function') {
232
+ prompt.editor.clear();
233
+ if (typeof prompt.scheduleDraw === 'function')
234
+ prompt.scheduleDraw();
235
+ }
236
+ return `Cancelled. An API key is required to use ${target.providerLabel} / ${target.modelId}. Model was not changed.`;
237
+ }
238
+ const cleanKey = enteredKey.trim();
239
+ await showConfiguringAnimation(target.providerLabel);
240
+ config['provider'] = target.providerId;
241
+ config['model'] = target.modelId;
242
+ config['apiKey'] = cleanKey;
243
+ config['providerKeys'] = providerKeys;
244
+ config['providerKeys'][target.providerId] = cleanKey;
245
+ store.saveConfig(config);
246
+ if (options.loop) {
247
+ options.loop.config = config;
248
+ if (typeof options.loop.updateTierLimits === 'function') {
249
+ options.loop.updateTierLimits();
250
+ }
251
+ }
252
+ notifyPromptAndClean(target.providerId, target.modelId);
253
+ return `Saved API key. Now using ${target.providerLabel} / ${target.modelId}.`;
254
+ }