@causyne/agent 1.17.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 (70) hide show
  1. package/package.json +1 -1
  2. package/src/agentLoop.js +2348 -2518
  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 +274 -25
  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 +140 -1
  40. package/src/dynamicCatalogue.ts +179 -1
  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 +321 -267
  48. package/src/providers/acp.ts +360 -0
  49. package/src/providers/antigravity.js +389 -239
  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 +71 -12
  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 +27 -25
  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
  70. package/src/tui/theme.js +4 -0
@@ -95,7 +95,9 @@ function renderMarkdown(text, width) {
95
95
  continue;
96
96
  }
97
97
 
98
- if (line.trim() === '') { lines.push(''); continue; }
98
+ const trimmed = line.trim();
99
+ if (trimmed === '') { lines.push(''); continue; }
100
+ if (trimmed === '[' || trimmed === ']') continue;
99
101
  for (const part of wrap(inline(line), width)) lines.push(part);
100
102
  }
101
103
 
@@ -121,7 +123,7 @@ function renderMarkdown(text, width) {
121
123
  // A bare URL, allowing one level of balanced parentheses so a link to
122
124
  // `.../URL_(disambiguation)` is not cut at the first `)`.
123
125
  const BARE_URL = /https?:\/\/[^\s<>()\[\]"'`]+(?:\([^\s<>()"'`]*\)[^\s<>()\[\]"'`]*)*/g;
124
- const MD_LINK = /\[([^\]\n]{1,80})\]\((https?:\/\/[^\s)]+(?:\([^\s)]*\)[^\s)]*)*)\)/g;
126
+ const MD_LINK = /\[([^\]\n]{1,80})\]\(((?:https?|file):\/\/[^\s)]+(?:\([^\s)]*\)[^\s)]*)*)\)/g;
125
127
 
126
128
  // The longest label a link may show. Anything longer would reach wrap()'s
127
129
  // hard-split branch, which cuts a long unbroken token by column — and cutting
@@ -144,7 +146,7 @@ function trimUrlPunctuation(url) {
144
146
 
145
147
  /** `https://docs.example.com/a/very/long/path?x=1` → `docs.example.com/a/…`. */
146
148
  function compactUrlLabel(url) {
147
- let label = url.replace(/^https?:\/\//, '').replace(/\/$/, '');
149
+ let label = url.replace(/^(?:https?|file):\/\//, '').replace(/\/$/, '');
148
150
  if (label.length > MAX_LINK_LABEL) label = label.slice(0, MAX_LINK_LABEL - 1) + GLYPHS.ellipsis;
149
151
  return label;
150
152
  }
@@ -186,7 +188,10 @@ function inline(text) {
186
188
  });
187
189
  } else {
188
190
  // No OSC 8 here, so a markdown link must still show where it points.
189
- out = out.replace(MD_LINK, (whole, label, url) => `${label} (${url})`);
191
+ out = out.replace(MD_LINK, (whole, label, url) => {
192
+ if (url.startsWith('file:')) return label;
193
+ return `${label} (${url})`;
194
+ });
190
195
  }
191
196
 
192
197
  out = HAS_COLOR
@@ -284,6 +289,15 @@ export class ChatRenderer {
284
289
  });
285
290
  }
286
291
 
292
+ updateTailFrame(kind, produce, meta = null) {
293
+ if (!this.transcript) { produce(); return; }
294
+ this.transcript.replaceTail({
295
+ kind,
296
+ meta,
297
+ produce: (width) => this.capture(width, produce)
298
+ });
299
+ }
300
+
287
301
  /**
288
302
  * Run a producer with write() redirected and the width pinned.
289
303
  */
@@ -524,28 +538,72 @@ export class ChatRenderer {
524
538
  * Reasoning that shouts as loudly as the reply trains the user to read
525
539
  * neither, and the reply is the part they asked for.
526
540
  */
541
+ /**
542
+ * The chain of thought the user requested: streamed live directly into the
543
+ * chat transcript, with real-time updates and clear elapsed time.
544
+ */
527
545
  onAgentReasoning(msg) {
528
546
  const content = safeDisplay(msg.content || '');
529
- if (!content.trim()) return;
530
- this.frame('reasoning', () => this.renderReasoning(content), { reasoning: true });
547
+ const isStreaming = Boolean(msg.streaming);
548
+ const elapsedMs = Number(msg.elapsedMs) || 0;
549
+ const durationText = elapsedMs > 0 ? formatDuration(elapsedMs) : '';
550
+
551
+ if (isStreaming) {
552
+ if (!this._activeReasoning) {
553
+ this._activeReasoning = true;
554
+ this.frame('reasoning', () => this.renderReasoning(content, { streaming: true }), { reasoning: true });
555
+ } else {
556
+ this.updateTailFrame('reasoning', () => this.renderReasoning(content, { streaming: true }), { reasoning: true });
557
+ }
558
+ return;
559
+ }
560
+
561
+ if (this._activeReasoning) {
562
+ this._activeReasoning = false;
563
+ this.updateTailFrame('reasoning', () => this.renderReasoning(content, { streaming: false, durationText }), { reasoning: true, done: true });
564
+ } else if (content.trim()) {
565
+ this.frame('reasoning', () => this.renderReasoning(content, { streaming: false, durationText }), { reasoning: true, done: true });
566
+ }
531
567
  }
532
568
 
533
- renderReasoning(content) {
569
+ renderReasoning(content, { streaming = false, durationText = '' } = {}) {
534
570
  const width = this.measure();
535
- const rows = wrapBlock(content, Math.max(20, width - 4));
571
+ const rows = content.trim()
572
+ ? wrapBlock(content, Math.max(20, width - 4))
573
+ : ['Contemplating task and formulating approach…'];
536
574
 
537
575
  this.write();
538
- this.write(`${paint('muted', GLYPHS.vLine)} ${dim('thinking')}`);
539
- for (const row of rows.slice(0, REASONING_LINES)) {
540
- this.write(`${paint('rule', GLYPHS.vLine)} ${dim(row)}`);
576
+ if (streaming) {
577
+ this.write(`${paint('warn', GLYPHS.vLine || '│')} ${bold(paint('warn', 'thinking…'))}`);
578
+ } else {
579
+ const timePart = durationText ? ` · ${durationText}` : '';
580
+ this.write(`${paint('muted', GLYPHS.vLine || '│')} ${dim(`thinking${timePart}`)}`);
541
581
  }
582
+
583
+ const displayRows = rows.slice(0, REASONING_LINES);
584
+ for (const row of displayRows) {
585
+ this.write(`${paint('rule', GLYPHS.vLine || '│')} ${dim(row)}`);
586
+ }
587
+
542
588
  if (rows.length > REASONING_LINES) {
543
589
  const hidden = rows.length - REASONING_LINES;
544
- this.write(`${paint('rule', GLYPHS.corner)} ${dim(`${GLYPHS.ellipsis} ${hidden} more line${hidden === 1 ? '' : 's'} of reasoning`)}`);
590
+ this.write(`${paint('rule', GLYPHS.corner || '└')} ${dim(`${GLYPHS.ellipsis} ${hidden} more line${hidden === 1 ? '' : 's'} of reasoning`)}`);
591
+ } else if (streaming) {
592
+ this.write(`${paint('rule', GLYPHS.corner || '└')} ${dim('streaming thoughts…')}`);
593
+ } else {
594
+ this.write(`${paint('rule', GLYPHS.corner || '└')}`);
545
595
  }
546
596
  this.write();
547
597
  }
548
598
 
599
+ onAgentActivity(msg) {
600
+ const text = safeDisplay(msg.activity || msg.message || '').trim();
601
+ if (!text) return;
602
+ this.frame('notice', () => {
603
+ this.write(`${paint('accent', GLYPHS.arrow || '▸')} ${dim(text)}`);
604
+ }, { activity: true });
605
+ }
606
+
549
607
  onAgentPlan(msg) {
550
608
  if (!Array.isArray(msg.plan) || msg.plan.length === 0) return;
551
609
  const plan = msg.plan.slice();
@@ -958,6 +1016,7 @@ export class ChatRenderer {
958
1016
 
959
1017
  switch (msg.type) {
960
1018
  case 'status': this.onStatus(msg); return true;
1019
+ case 'agent_activity': this.onAgentActivity(msg); return true;
961
1020
  case 'agent_message': this.onAgentMessage(msg); return true;
962
1021
  case 'agent_reasoning': this.onAgentReasoning(msg); return true;
963
1022
  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
@@ -5,7 +5,8 @@ import { paint, dim, bold, badge, GLYPHS } from './theme.js';
5
5
  import { runSetup } from './setup.js';
6
6
  import { DEFAULT_MODEL_BY_PROVIDER } from '../modelCatalogue.js';
7
7
  import { isAcpProvider } from '../providers/acp.js';
8
- import { isAntigravityProvider } from '../providers/antigravity.js';
8
+ import { isAntigravityProvider, resolveAgyBinary } from '../providers/antigravity.js';
9
+ import { isBinaryOnPath } from '../acp/agentCatalog.js';
9
10
 
10
11
  /** Local runtime and provider summary. */
11
12
  export function homeStatusLine(arg = {}) {
@@ -61,8 +62,9 @@ export const PRIMARY_ACTIONS = [
61
62
  * stays readable while the complete command surface remains discoverable.
62
63
  */
63
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' },
64
66
  { id: 'sessions', label: 'sessions', category: 'workspace', hint: 'browse saved local sessions', kind: 'command', command: '/sessions' },
65
- { 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' },
66
68
  { id: 'approvals', label: 'approvals', category: 'workspace', hint: 'review standing session approvals', kind: 'command', command: '/approvals' },
67
69
  {
68
70
  id: 'context', label: 'context', category: 'reports', hint: 'what fills the context window', kind: 'stay',
@@ -135,29 +137,29 @@ export { badge };
135
137
 
136
138
  // stale values again. Labels and hints stay local because they are terminal UI.
137
139
  export const PROVIDERS = [
138
- { id: 'deepseek', label: 'DeepSeek', hint: 'recommended for STEM' },
139
- { id: 'qwen', label: 'Qwen / Alibaba Cloud', hint: 'fastest' },
140
- { id: 'dashscope-byok', label: 'Alibaba DashScope', hint: 'multi-model gateway' },
141
- { id: 'muse', label: 'Meta Model API', hint: 'Muse Spark · 1M context' },
142
- { id: 'anthropic', label: 'Anthropic', hint: 'Claude' },
143
- { id: 'openai', label: 'OpenAI', hint: 'GPT' },
144
- { id: 'gemini', label: 'Gemini', hint: 'Google' },
145
- { id: 'moonshot', label: 'Moonshot', hint: 'Kimi' },
146
- { id: 'xai', label: 'xAI', hint: 'Grok' },
147
- { id: 'openai-compatible', label: 'OpenAI-compatible endpoint', hint: 'custom base URL' },
148
- { id: 'ollama', label: 'Ollama', hint: 'local / offline' },
149
- { id: 'antigravity', label: 'Google Antigravity (AGY)', hint: 'local AGY · Gemini & Claude models' },
150
- { id: 'acp/opencode', label: 'OpenCode', hint: 'ACP · free models available' },
151
- { id: 'acp/claude', label: 'Claude Code', hint: 'ACP · your Anthropic subscription' },
152
- { id: 'acp/codex', label: 'Codex CLI', hint: 'ACP · your OpenAI login' },
153
- { id: 'acp/gemini', label: 'Gemini CLI', hint: 'ACP · free tier / Google login' },
154
- { id: 'acp/cursor', label: 'Cursor CLI', hint: 'ACP · your Cursor subscription' },
155
- { id: 'acp/qwen', label: 'Qwen Code', hint: 'ACP · DashScope login' },
156
- { id: 'acp/copilot', label: 'GitHub Copilot CLI', hint: 'ACP · your Copilot subscription' },
157
- { id: 'acp/kimi', label: 'Kimi CLI', hint: 'ACP · Moonshot login' },
158
- { id: 'acp/goose', label: 'Goose', hint: 'ACP · your configured providers' },
159
- { id: 'acp/hermes', label: 'Hermes Agent', hint: 'ACP · Nous Research' },
160
- { id: 'acp', label: 'ACP peer agent (custom)', hint: 'any ACP-compatible CLI' }
140
+ { id: 'deepseek', label: 'DeepSeek', hint: 'recommended for STEM', category: 'BYOK (Cloud API)' },
141
+ { id: 'qwen', label: 'Qwen / Alibaba Cloud', hint: 'fastest', category: 'BYOK (Cloud API)' },
142
+ { id: 'dashscope-byok', label: 'Alibaba DashScope', hint: 'multi-model gateway', category: 'BYOK (Cloud API)' },
143
+ { id: 'muse', label: 'Meta Model API', hint: 'Muse Spark · 1M context', category: 'BYOK (Cloud API)' },
144
+ { id: 'anthropic', label: 'Anthropic', hint: 'Claude', category: 'BYOK (Cloud API)' },
145
+ { id: 'openai', label: 'OpenAI', hint: 'GPT', category: 'BYOK (Cloud API)' },
146
+ { id: 'gemini', label: 'Gemini', hint: 'Google', category: 'BYOK (Cloud API)' },
147
+ { id: 'moonshot', label: 'Moonshot', hint: 'Kimi', category: 'BYOK (Cloud API)' },
148
+ { id: 'xai', label: 'xAI', hint: 'Grok', category: 'BYOK (Cloud API)' },
149
+ { id: 'openai-compatible', label: 'OpenAI-compatible endpoint', hint: 'custom base URL', category: 'BYOK (Custom)' },
150
+ { id: 'ollama', label: 'Ollama', hint: 'local / offline', category: 'BYOK (Local Server)' },
151
+ { id: 'antigravity', label: 'Google Antigravity (AGY)', hint: resolveAgyBinary() ? 'local AGY · Gemini & Claude (ready)' : 'local AGY · (not installed)', category: 'ACP (Peer Agent)' },
152
+ { id: 'acp/opencode', label: 'OpenCode', hint: isBinaryOnPath('opencode') ? 'ACP · free models (ready)' : 'ACP · (not installed)', category: 'ACP (Peer Agent)' },
153
+ { id: 'acp/claude', label: 'Claude Code', hint: isBinaryOnPath('claude') ? 'ACP · Anthropic subscription (ready)' : 'ACP · (not installed)', category: 'ACP (Peer Agent)' },
154
+ { id: 'acp/codex', label: 'Codex CLI', hint: isBinaryOnPath('codex') ? 'ACP · OpenAI login (ready)' : 'ACP · (not installed)', category: 'ACP (Peer Agent)' },
155
+ { id: 'acp/gemini', label: 'Gemini CLI', hint: isBinaryOnPath('gemini') ? 'ACP · Google login (ready)' : 'ACP · (not installed)', category: 'ACP (Peer Agent)' },
156
+ { id: 'acp/cursor', label: 'Cursor CLI', hint: (isBinaryOnPath('cursor-agent') || isBinaryOnPath('cursor')) ? 'ACP · Cursor subscription (ready)' : 'ACP · (not installed)', category: 'ACP (Peer Agent)' },
157
+ { id: 'acp/qwen', label: 'Qwen Code', hint: isBinaryOnPath('qwen') ? 'ACP · DashScope login (ready)' : 'ACP · (not installed)', category: 'ACP (Peer Agent)' },
158
+ { id: 'acp/copilot', label: 'GitHub Copilot CLI', hint: isBinaryOnPath('copilot') ? 'ACP · Copilot subscription (ready)' : 'ACP · (not installed)', category: 'ACP (Peer Agent)' },
159
+ { id: 'acp/kimi', label: 'Kimi CLI', hint: isBinaryOnPath('kimi') ? 'ACP · Moonshot login (ready)' : 'ACP · (not installed)', category: 'ACP (Peer Agent)' },
160
+ { id: 'acp/goose', label: 'Goose', hint: isBinaryOnPath('goose') ? 'ACP · configured providers (ready)' : 'ACP · (not installed)', category: 'ACP (Peer Agent)' },
161
+ { id: 'acp/hermes', label: 'Hermes Agent', hint: isBinaryOnPath('hermes') ? 'ACP · Nous Research (ready)' : 'ACP · (not installed)', category: 'ACP (Peer Agent)' },
162
+ { id: 'acp', label: 'ACP peer agent (custom)', hint: 'any ACP-compatible CLI', category: 'ACP (Custom)' }
161
163
  ].map((entry) => ({ ...entry, model: DEFAULT_MODEL_BY_PROVIDER[entry.id] ?? '' }));
162
164
 
163
165
  /** Run the shared setup transaction inside the existing prompt. */
@@ -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
+ }