@causyne/agent 1.18.0 → 1.19.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 (69) 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 +10 -3
  6. package/src/commands.js +109 -6
  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/modelIds.d.ts +2 -0
  46. package/src/outputStore.d.ts +4 -0
  47. package/src/providers/acp.js +320 -299
  48. package/src/providers/acp.ts +360 -0
  49. package/src/providers/antigravity.js +387 -278
  50. package/src/providers/antigravity.ts +450 -0
  51. package/src/providers/base.d.ts +68 -0
  52. package/src/providers/factory.d.ts +1 -0
  53. package/src/provisioning/capabilityProvisioner.d.ts +2 -0
  54. package/src/sandbox.d.ts +1 -0
  55. package/src/skillsManager.d.ts +3 -0
  56. package/src/slopDetector.d.ts +3 -0
  57. package/src/taskBuffer.d.ts +1 -0
  58. package/src/tokenTracker.d.ts +1 -0
  59. package/src/toolPacks.d.ts +8 -0
  60. package/src/tools/registry.d.ts +4 -0
  61. package/src/tui/chatRenderer.js +62 -8
  62. package/src/tui/clipboardSync.js +36 -0
  63. package/src/tui/clipboardSync.ts +36 -0
  64. package/src/tui/dialogs.js +15 -2
  65. package/src/tui/home.js +2 -1
  66. package/src/tui/modelPicker.js +221 -0
  67. package/src/tui/modelPicker.ts +290 -0
  68. package/src/tui/prompt.js +17 -6
  69. package/src/tui/selectList.js +20 -0
@@ -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,221 @@
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
+ if (!picked || !picked.value) {
135
+ return 'Cancelled. Model was not changed.';
136
+ }
137
+ const target = picked.value;
138
+ // Case 1: ACP Peer Agent or Antigravity
139
+ if (target.type === 'acp') {
140
+ if (!target.installed) {
141
+ return (`⚠️ Notice: "${target.providerLabel}" is not installed on this machine.\n` +
142
+ `Setup: ${target.setupInstruction || 'Install the CLI binary.'}\n\n` +
143
+ `Model was not changed.`);
144
+ }
145
+ config['provider'] = target.providerId;
146
+ config['model'] = target.modelId;
147
+ config['apiKey'] = '';
148
+ delete config['baseUrl'];
149
+ store.saveConfig(config);
150
+ if (options.loop) {
151
+ options.loop.config = config;
152
+ if (typeof options.loop.updateTierLimits === 'function') {
153
+ options.loop.updateTierLimits();
154
+ }
155
+ }
156
+ return `Now using ${target.providerLabel} / ${target.modelId}.`;
157
+ }
158
+ // Case 2: BYOK Provider (Cloud or Local API)
159
+ let existingKey = '';
160
+ const providerKeys = (config['providerKeys'] && typeof config['providerKeys'] === 'object') ? config['providerKeys'] : {};
161
+ if (config['provider'] === target.providerId && typeof config['apiKey'] === 'string' && config['apiKey']) {
162
+ existingKey = config['apiKey'];
163
+ }
164
+ else if (providerKeys[target.providerId] || (target.providerId === 'qwen' && providerKeys['dashscope-byok'])) {
165
+ existingKey = providerKeys[target.providerId] || providerKeys['dashscope-byok'] || '';
166
+ }
167
+ else if (target.envVar && process.env[target.envVar]) {
168
+ existingKey = process.env[target.envVar] || '';
169
+ }
170
+ // If provider is Ollama (needs no key) or key is already present
171
+ if (target.providerId === 'ollama' || existingKey) {
172
+ config['provider'] = target.providerId;
173
+ config['model'] = target.modelId;
174
+ if (existingKey) {
175
+ config['apiKey'] = existingKey;
176
+ config['providerKeys'] = providerKeys;
177
+ config['providerKeys'][target.providerId] = existingKey;
178
+ }
179
+ store.saveConfig(config);
180
+ if (options.loop) {
181
+ options.loop.config = config;
182
+ if (typeof options.loop.updateTierLimits === 'function') {
183
+ options.loop.updateTierLimits();
184
+ }
185
+ }
186
+ return `Now using ${target.providerLabel} / ${target.modelId}.`;
187
+ }
188
+ // Key is required: open modal input dialog (InputLayer)
189
+ const enteredKey = await new Promise((resolve) => {
190
+ const layer = new InputLayer({
191
+ title: `Set API Key · ${target.providerLabel}`,
192
+ lines: [
193
+ `Enter your ${target.providerLabel} API key to use ${target.modelId}.`,
194
+ 'Stored encrypted in your local vault (~/.causyne/config.json).'
195
+ ],
196
+ mask: true,
197
+ placeholder: 'paste API key (Esc to cancel)',
198
+ onSubmit: resolve,
199
+ onCancel: () => resolve(null)
200
+ });
201
+ prompt.openLayer(layer);
202
+ });
203
+ if (!enteredKey || !enteredKey.trim()) {
204
+ return `Cancelled. An API key is required to use ${target.providerLabel} / ${target.modelId}. Model was not changed.`;
205
+ }
206
+ const cleanKey = enteredKey.trim();
207
+ await showConfiguringAnimation(target.providerLabel);
208
+ config['provider'] = target.providerId;
209
+ config['model'] = target.modelId;
210
+ config['apiKey'] = cleanKey;
211
+ config['providerKeys'] = providerKeys;
212
+ config['providerKeys'][target.providerId] = cleanKey;
213
+ store.saveConfig(config);
214
+ if (options.loop) {
215
+ options.loop.config = config;
216
+ if (typeof options.loop.updateTierLimits === 'function') {
217
+ options.loop.updateTierLimits();
218
+ }
219
+ }
220
+ return `Saved API key. Now using ${target.providerLabel} / ${target.modelId}.`;
221
+ }
@@ -0,0 +1,290 @@
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
+
6
+ // @ts-expect-error untyped local TUI dialogs
7
+ import { SelectLayer, InputLayer } from './dialogs.js';
8
+ import { loadConfig, saveConfig } from '../config.js';
9
+ import { getAvailableProvidersOverview, type ProviderOverview } from '../dynamicCatalogue.js';
10
+
11
+ export interface ModelPickerItemValue {
12
+ type: 'acp' | 'byok';
13
+ providerId: string;
14
+ modelId: string;
15
+ providerLabel: string;
16
+ installed: boolean;
17
+ isCurrent: boolean;
18
+ isConfigured: boolean;
19
+ envVar?: string | undefined;
20
+ setupInstruction?: string | undefined;
21
+ }
22
+
23
+ export interface ModelPickerItem {
24
+ id: string;
25
+ label: string;
26
+ category: string;
27
+ description: string;
28
+ value: ModelPickerItemValue;
29
+ }
30
+
31
+ export interface ConfigStore {
32
+ loadConfig(): Record<string, any>;
33
+ saveConfig(config: Record<string, any>): void;
34
+ }
35
+
36
+ export interface PromptHost {
37
+ openLayer(layer: unknown): void;
38
+ }
39
+
40
+ export interface InteractiveModelPickerOptions {
41
+ loop?: {
42
+ config?: Record<string, any>;
43
+ updateTierLimits?: () => void;
44
+ initializeProvider?: () => any;
45
+ llm?: any;
46
+ _utilityLlm?: any;
47
+ } | undefined;
48
+ }
49
+
50
+ async function showConfiguringAnimation(providerLabel: string): Promise<void> {
51
+ if (!process.stdout.isTTY) return;
52
+ const frames = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
53
+ const text = `Configuring ${providerLabel} in secure local vault…`;
54
+ for (let i = 0; i < 5; i++) {
55
+ const f = frames[i % frames.length];
56
+ process.stdout.write(`\r \x1b[36m${f}\x1b[0m ${text}`);
57
+ await new Promise(r => setTimeout(r, 60));
58
+ }
59
+ process.stdout.write(`\r\x1b[K \x1b[32m✓\x1b[0m ${providerLabel} credentials saved.\n`);
60
+ }
61
+
62
+ /**
63
+ * Build items for SelectLayer categorized by ACP peers and BYOK providers.
64
+ */
65
+ export function buildModelPickerItems(
66
+ config: { provider?: string; model?: string; apiKey?: string; providerKeys?: Record<string, string> },
67
+ overview: ProviderOverview
68
+ ): ModelPickerItem[] {
69
+ const items: ModelPickerItem[] = [];
70
+ const activeProvider = config.provider || '';
71
+ const activeModel = config.model || '';
72
+
73
+ // 1. ACP Peer Agents & Sovereign Local Engines
74
+ for (const peer of overview.acp) {
75
+ const isCurrentProvider = activeProvider === peer.providerKey;
76
+ const catTitle = peer.installed
77
+ ? `ACP · ${peer.label} (ready)`
78
+ : `ACP · ${peer.label} (not installed)`;
79
+
80
+ if (peer.installed && Array.isArray(peer.models) && peer.models.length > 0) {
81
+ for (const m of peer.models) {
82
+ const isCurrent = isCurrentProvider && activeModel === m;
83
+ items.push({
84
+ id: `${peer.providerKey}/${m}`,
85
+ label: m,
86
+ category: catTitle,
87
+ description: isCurrent ? '● active' : 'ready',
88
+ value: {
89
+ type: 'acp',
90
+ providerId: peer.providerKey,
91
+ modelId: m,
92
+ providerLabel: peer.label,
93
+ installed: true,
94
+ isCurrent,
95
+ isConfigured: true,
96
+ setupInstruction: peer.setupInstruction
97
+ }
98
+ });
99
+ }
100
+ } else {
101
+ // Uninstalled ACP agent: show entry so user can see it's supported
102
+ items.push({
103
+ id: `${peer.providerKey}:uninstalled`,
104
+ label: peer.label,
105
+ category: catTitle,
106
+ description: 'not installed — setup needed',
107
+ value: {
108
+ type: 'acp',
109
+ providerId: peer.providerKey,
110
+ modelId: peer.models[0] || peer.id,
111
+ providerLabel: peer.label,
112
+ installed: false,
113
+ isCurrent: false,
114
+ isConfigured: false,
115
+ setupInstruction: peer.setupInstruction
116
+ }
117
+ });
118
+ }
119
+ }
120
+
121
+ // 2. BYOK Providers (Cloud & Local APIs)
122
+ for (const p of overview.byok) {
123
+ const isCurrentProvider = activeProvider === p.id || (p.id === 'qwen' && activeProvider === 'dashscope-byok');
124
+ const catTitle = p.id === 'ollama'
125
+ ? `BYOK · ${p.label}`
126
+ : `BYOK · ${p.label} ${p.isConfigured ? '(configured)' : '(needs key)'}`;
127
+
128
+ const models = Array.isArray(p.models) && p.models.length > 0 ? p.models : [p.defaultModel];
129
+ for (const m of models) {
130
+ const isCurrent = isCurrentProvider && activeModel === m;
131
+ const desc = isCurrent ? '● active' : (p.id === 'ollama' ? 'local' : (p.isConfigured ? 'configured' : 'needs API key'));
132
+ items.push({
133
+ id: `${p.id}/${m}`,
134
+ label: m,
135
+ category: catTitle,
136
+ description: desc,
137
+ value: {
138
+ type: 'byok',
139
+ providerId: p.id,
140
+ modelId: m,
141
+ providerLabel: p.label,
142
+ installed: true,
143
+ isCurrent,
144
+ isConfigured: p.isConfigured,
145
+ envVar: p.envVar
146
+ }
147
+ });
148
+ }
149
+ }
150
+
151
+ return items;
152
+ }
153
+
154
+ /**
155
+ * Run interactive model picker in the provided TUI prompt.
156
+ *
157
+ * Automatically handles:
158
+ * - Direct selection of ACP models without prompting for an API key.
159
+ * - Direct selection of configured BYOK models without prompting for an API key.
160
+ * - InputLayer modal prompt for API key when selecting an unconfigured BYOK model,
161
+ * safely encrypting it into ~/.causyne/config.json.
162
+ * - Synchronous runtime loop re-initialization so the live session switches immediately.
163
+ */
164
+ export async function runInteractiveModelPicker(
165
+ prompt: PromptHost,
166
+ store: ConfigStore = { loadConfig, saveConfig },
167
+ options: InteractiveModelPickerOptions = {}
168
+ ): Promise<string> {
169
+ if (!prompt || typeof prompt.openLayer !== 'function') {
170
+ return 'Run causyne in an interactive terminal to use the model picker.';
171
+ }
172
+
173
+ const config = store.loadConfig();
174
+ const overview = getAvailableProvidersOverview(config);
175
+ const items = buildModelPickerItems(config, overview);
176
+
177
+ const picked = await new Promise<ModelPickerItem | null>((resolve) => {
178
+ const layer = new SelectLayer({
179
+ title: 'Select Model',
180
+ placeholder: 'type to filter (e.g. gemini, sonnet, opencode)…',
181
+ emptyText: 'No models matched your search',
182
+ items,
183
+ width: 76,
184
+ height: 20,
185
+ onPick: resolve
186
+ });
187
+ prompt.openLayer(layer);
188
+ });
189
+
190
+ if (!picked || !picked.value) {
191
+ return 'Cancelled. Model was not changed.';
192
+ }
193
+
194
+ const target = picked.value;
195
+
196
+ // Case 1: ACP Peer Agent or Antigravity
197
+ if (target.type === 'acp') {
198
+ if (!target.installed) {
199
+ return (
200
+ `⚠️ Notice: "${target.providerLabel}" is not installed on this machine.\n` +
201
+ `Setup: ${target.setupInstruction || 'Install the CLI binary.'}\n\n` +
202
+ `Model was not changed.`
203
+ );
204
+ }
205
+
206
+ config['provider'] = target.providerId;
207
+ config['model'] = target.modelId;
208
+ config['apiKey'] = '';
209
+ delete config['baseUrl'];
210
+ store.saveConfig(config);
211
+
212
+ if (options.loop) {
213
+ options.loop.config = config;
214
+ if (typeof options.loop.updateTierLimits === 'function') {
215
+ options.loop.updateTierLimits();
216
+ }
217
+ }
218
+ return `Now using ${target.providerLabel} / ${target.modelId}.`;
219
+ }
220
+
221
+ // Case 2: BYOK Provider (Cloud or Local API)
222
+ let existingKey = '';
223
+ const providerKeys: Record<string, string> = (config['providerKeys'] && typeof config['providerKeys'] === 'object') ? config['providerKeys'] : {};
224
+ if (config['provider'] === target.providerId && typeof config['apiKey'] === 'string' && config['apiKey']) {
225
+ existingKey = config['apiKey'];
226
+ } else if (providerKeys[target.providerId] || (target.providerId === 'qwen' && providerKeys['dashscope-byok'])) {
227
+ existingKey = providerKeys[target.providerId] || providerKeys['dashscope-byok'] || '';
228
+ } else if (target.envVar && process.env[target.envVar]) {
229
+ existingKey = process.env[target.envVar] || '';
230
+ }
231
+
232
+ // If provider is Ollama (needs no key) or key is already present
233
+ if (target.providerId === 'ollama' || existingKey) {
234
+ config['provider'] = target.providerId;
235
+ config['model'] = target.modelId;
236
+ if (existingKey) {
237
+ config['apiKey'] = existingKey;
238
+ config['providerKeys'] = providerKeys;
239
+ config['providerKeys'][target.providerId] = existingKey;
240
+ }
241
+ store.saveConfig(config);
242
+
243
+ if (options.loop) {
244
+ options.loop.config = config;
245
+ if (typeof options.loop.updateTierLimits === 'function') {
246
+ options.loop.updateTierLimits();
247
+ }
248
+ }
249
+ return `Now using ${target.providerLabel} / ${target.modelId}.`;
250
+ }
251
+
252
+ // Key is required: open modal input dialog (InputLayer)
253
+ const enteredKey = await new Promise<string | null>((resolve) => {
254
+ const layer = new InputLayer({
255
+ title: `Set API Key · ${target.providerLabel}`,
256
+ lines: [
257
+ `Enter your ${target.providerLabel} API key to use ${target.modelId}.`,
258
+ 'Stored encrypted in your local vault (~/.causyne/config.json).'
259
+ ],
260
+ mask: true,
261
+ placeholder: 'paste API key (Esc to cancel)',
262
+ onSubmit: resolve,
263
+ onCancel: () => resolve(null)
264
+ });
265
+ prompt.openLayer(layer);
266
+ });
267
+
268
+ if (!enteredKey || !enteredKey.trim()) {
269
+ return `Cancelled. An API key is required to use ${target.providerLabel} / ${target.modelId}. Model was not changed.`;
270
+ }
271
+
272
+ const cleanKey = enteredKey.trim();
273
+ await showConfiguringAnimation(target.providerLabel);
274
+
275
+ config['provider'] = target.providerId;
276
+ config['model'] = target.modelId;
277
+ config['apiKey'] = cleanKey;
278
+ config['providerKeys'] = providerKeys;
279
+ config['providerKeys'][target.providerId] = cleanKey;
280
+ store.saveConfig(config);
281
+
282
+ if (options.loop) {
283
+ options.loop.config = config;
284
+ if (typeof options.loop.updateTierLimits === 'function') {
285
+ options.loop.updateTierLimits();
286
+ }
287
+ }
288
+
289
+ return `Saved API key. Now using ${target.providerLabel} / ${target.modelId}.`;
290
+ }