Repository navigation
Expand file tree
/
Copy pathagents.ts
More file actions
875 lines (850 loc) · 32.7 KB
/
Copy pathagents.ts
File metadata and controls
875 lines (850 loc) · 32.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
// @ts-nocheck
import { execFile } from 'node:child_process';
import { promisify } from 'node:util';
import { existsSync, readdirSync } from 'node:fs';
import { delimiter } from 'node:path';
import path from 'node:path';
import { homedir } from 'node:os';
import { detectAcpModels } from './acp.js';
import { parsePiModels } from './pi-rpc.js';
const execFileP = promisify(execFile);
// Capability flags detected at probe time (per agent id). buildArgs consults
// this map so we only pass flags the installed CLI actually advertises in
// `--help`. Falls back to "off" when probing failed or hasn't run yet — that
// keeps the spawn safe across older Claude Code releases that pre-date a
// given flag (e.g. `--include-partial-messages`, added in 1.0.86).
const agentCapabilities = new Map();
// Per-agent model picker.
//
// - `listModels` : optional spec for fetching the model list from
// the CLI itself ({ args, parse, timeoutMs }).
// When defined we run it during agent detection
// (best-effort, with a timeout) and use the
// result. If the listing fails we fall back to
// `fallbackModels` so the UI still has something
// to show.
// - `fallbackModels` : static hint list. Used as the source of truth
// for CLIs that don't expose a listing command
// (Claude Code, Codex, Devin for Terminal, Gemini CLI, Qwen Code)
// and as the fallback for the others.
// - `reasoningOptions` : optional reasoning-effort presets (currently
// only Codex exposes this knob).
// - `buildArgs(prompt, imagePaths, extraAllowedDirs, options, runtimeContext)`
// returns argv for the child process. `options = { model, reasoning }`
// carries whatever the user picked in the model menu — agents that don't
// take a model flag ignore them. `runtimeContext` currently carries
// runtime execution details like `{ cwd }` for CLIs that need an explicit
// workspace flag in addition to process cwd.
//
// Every model list is prefixed with a synthetic `'default'` entry meaning
// "let the CLI pick" — the agent runs with no `--model` flag, so the
// user's local CLI config wins.
//
// `extraAllowedDirs` is a list of absolute directories the agent must be
// permitted to read files from (skill seeds, design-system specs) that live
// outside the project cwd. Currently only Claude Code wires this through
// (`--add-dir`); other agents either inherit broader access or run with cwd
// boundaries we can't widen via flags.
//
// `streamFormat` hints to the daemon how to interpret stdout:
// - 'claude-stream-json' : line-delimited JSON emitted by Claude Code's
// `--output-format stream-json`. Daemon parses it into typed events
// (text / thinking / tool_use / tool_result / status) for the UI.
// - 'acp-json-rpc' : ACP JSON-RPC over stdio. Daemon drives the
// initialize/session/new/session/prompt lifecycle and maps updates into
// typed UI events.
// - 'plain' (default) : raw text, forwarded chunk-by-chunk.
//
// Permission posture: the daemon spawns each CLI with cwd pinned to the
// project folder (`.od/projects/<id>/`), and the web app has no terminal
// to surface an interactive approve/deny prompt. So every agent runs with
// its non-interactive/auto-approve switch on — otherwise Write/Edit hangs
// or errors and the model has to hallucinate a permission button the UI
// never shows.
const DEFAULT_MODEL_OPTION = { id: 'default', label: 'Default (CLI config)' };
// Map a user-picked reasoning effort to one the chosen model will accept.
// Codex's CLI accepts `none | minimal | low | medium | high | xhigh`, but
// real models support narrower subsets — gpt-5.2/5.3/5.4/5.5 reject
// `minimal`, gpt-5.1 rejects `xhigh`, gpt-5.1-codex-mini accepts only
// `medium` / `high`.
// An undefined / 'default' modelId is clamped as if it were gpt-5.5,
// since that's codex's current default model. Unknown / future model ids
// pass through unchanged — if the API later rejects, the server error
// is the signal that a new rule belongs here.
function clampCodexReasoning(modelId, effort) {
if (!effort) return effort;
const raw = String(modelId ?? '').trim();
const id = raw.includes('/') ? raw.split('/').pop() : raw;
const isGpt5LateFamily =
!id ||
id === 'default' ||
id.startsWith('gpt-5.2') ||
id.startsWith('gpt-5.3') ||
id.startsWith('gpt-5.4') ||
id.startsWith('gpt-5.5');
if (isGpt5LateFamily && effort === 'minimal') return 'low';
if (id === 'gpt-5.1' && effort === 'xhigh') return 'high';
if (id === 'gpt-5.1-codex-mini') {
return effort === 'high' || effort === 'xhigh' ? 'high' : 'medium';
}
return effort;
}
// Parse one-id-per-line stdout from `<cli> models` and prepend the synthetic
// default option. Used by opencode / cursor-agent.
function parseLineSeparatedModels(stdout) {
const ids = String(stdout || '')
.split('\n')
.map((line) => line.trim())
.filter((line) => line.length > 0 && !line.startsWith('#'));
// De-dupe while preserving order — some CLIs print near-duplicates.
const seen = new Set();
const out = [DEFAULT_MODEL_OPTION];
for (const id of ids) {
if (seen.has(id)) continue;
seen.add(id);
out.push({ id, label: id });
}
return out;
}
export const AGENT_DEFS = [
{
id: 'claude',
name: 'Claude Code',
bin: 'claude',
// Drop-in forks that ship a CLI argv-compatible with `claude`. Tried in
// order if `claude` itself isn't on PATH, so users on a single-binary
// install (e.g. only OpenClaude — https://github.com/Gitlawb/openclaude
// — issue #235) get auto-detected without writing wrapper scripts.
fallbackBins: ['openclaude'],
versionArgs: ['--version'],
helpArgs: ['--help'],
capabilityFlags: {
// Flag string -> capability key. After probing `--help`, we set
// `agentCapabilities[id][key] = true` for each substring that matches.
'--include-partial-messages': 'partialMessages',
'--add-dir': 'addDir',
},
// `claude` has no list-models subcommand; the CLI accepts both short
// aliases (sonnet/opus/haiku) and the full ids, so we ship both as
// hints. Users who want a non-shipped model can paste it via the
// Settings dialog's custom-model input.
fallbackModels: [
DEFAULT_MODEL_OPTION,
{ id: 'sonnet', label: 'Sonnet (alias)' },
{ id: 'opus', label: 'Opus (alias)' },
{ id: 'haiku', label: 'Haiku (alias)' },
{ id: 'claude-opus-4-5', label: 'claude-opus-4-5' },
{ id: 'claude-sonnet-4-5', label: 'claude-sonnet-4-5' },
{ id: 'claude-haiku-4-5', label: 'claude-haiku-4-5' },
],
// Prompt delivered via stdin to avoid both Linux `spawn E2BIG`
// (MAX_ARG_STRLEN caps a single argv entry at ~128 KB) and Windows
// `spawn ENAMETOOLONG` (CreateProcess caps the full command line at
// ~32 KB direct, ~8 KB via .cmd shim). `claude -p` with no positional
// prompt reads the prompt from stdin under `--input-format text` (the
// default), which has no length cap. Mirrors the codex/gemini/opencode/
// cursor/qwen entries below.
buildArgs: (_prompt, _imagePaths, extraAllowedDirs = [], options = {}) => {
const caps = agentCapabilities.get('claude') || {};
const args = [
'-p',
'--output-format',
'stream-json',
'--verbose',
];
// `--include-partial-messages` lands richer streaming events but only
// exists in newer Claude Code builds. Older installs reject it with
// "unknown option" and exit 1, killing the chat. Gate on the probe.
if (caps.partialMessages) {
args.push('--include-partial-messages');
}
if (options.model && options.model !== 'default') {
args.push('--model', options.model);
}
const dirs = (extraAllowedDirs || []).filter(
(d) => typeof d === 'string' && d.length > 0,
);
// `--add-dir` is older but still gate it for symmetry — old/forked
// builds may lack it.
if (dirs.length > 0 && caps.addDir !== false) {
args.push('--add-dir', ...dirs);
}
args.push('--permission-mode', 'bypassPermissions');
return args;
},
promptViaStdin: true,
streamFormat: 'claude-stream-json',
},
{
id: 'codex',
name: 'Codex CLI',
bin: 'codex',
versionArgs: ['--version'],
// Codex doesn't have a `models` subcommand; ship the most common ids
// as a hint. Users can supply other ids via the custom-model input.
fallbackModels: [
DEFAULT_MODEL_OPTION,
{ id: 'gpt-5-codex', label: 'gpt-5-codex' },
{ id: 'gpt-5', label: 'gpt-5' },
{ id: 'o3', label: 'o3' },
{ id: 'o4-mini', label: 'o4-mini' },
],
reasoningOptions: [
{ id: 'default', label: 'Default' },
{ id: 'minimal', label: 'Minimal' },
{ id: 'low', label: 'Low' },
{ id: 'medium', label: 'Medium' },
{ id: 'high', label: 'High' },
],
// Prompt is delivered via stdin pipe (gated by `promptViaStdin: true`
// below) to avoid Windows `spawn ENAMETOOLONG` while keeping Codex on
// its structured JSON stream. Recent Codex CLI versions reject a bare
// `-` argv sentinel — passing both the pipe and `-` produces
// `error: unexpected argument '-' found` and the agent exits with
// code 2 before any prompt is read (see issue #237). The pipe alone
// is sufficient for stdin delivery.
buildArgs: (_prompt, _imagePaths, _extra, options = {}, runtimeContext = {}) => {
const args = [
'exec',
'--json',
'--skip-git-repo-check',
'--full-auto',
'-c',
'sandbox_workspace_write.network_access=true',
];
if (process.env.OD_CODEX_DISABLE_PLUGINS === '1') {
args.push('--disable', 'plugins');
}
if (runtimeContext.cwd) {
args.push('-C', runtimeContext.cwd);
}
if (options.model && options.model !== 'default') {
args.push('--model', options.model);
}
if (options.reasoning && options.reasoning !== 'default') {
const effort = clampCodexReasoning(options.model, options.reasoning);
// Codex accepts `-c key=value` config overrides; reasoning effort
// is exposed as `model_reasoning_effort`.
args.push('-c', `model_reasoning_effort="${effort}"`);
}
return args;
},
promptViaStdin: true,
streamFormat: 'json-event-stream',
eventParser: 'codex',
},
{
id: 'devin',
name: 'Devin for Terminal',
bin: 'devin',
versionArgs: ['--version'],
fetchModels: async (resolvedBin) =>
detectAcpModels({
bin: resolvedBin,
args: ['--permission-mode', 'dangerous', '--respect-workspace-trust', 'false', 'acp'],
timeoutMs: 15_000,
defaultModelOption: DEFAULT_MODEL_OPTION,
}),
// Fallback aliases from Devin for Terminal docs
// (https://cli.devin.ai/docs/models): `adaptive` appears in the config example;
// `opus`, `sonnet`, `swe`, `codex`, `gemini`, and `gpt` are documented
// as short model-family names / recommended picks.
fallbackModels: [
DEFAULT_MODEL_OPTION,
{ id: 'adaptive', label: 'adaptive' },
{ id: 'swe', label: 'swe' },
{ id: 'opus', label: 'opus' },
{ id: 'sonnet', label: 'sonnet' },
{ id: 'codex', label: 'codex' },
{ id: 'gpt', label: 'gpt' },
{ id: 'gemini', label: 'gemini' },
],
buildArgs: () => ['--permission-mode', 'dangerous', '--respect-workspace-trust', 'false', 'acp'],
streamFormat: 'acp-json-rpc',
},
{
id: 'gemini',
name: 'Gemini CLI',
bin: 'gemini',
versionArgs: ['--version'],
fallbackModels: [
DEFAULT_MODEL_OPTION,
{ id: 'gemini-2.5-pro', label: 'gemini-2.5-pro' },
{ id: 'gemini-2.5-flash', label: 'gemini-2.5-flash' },
],
// Gemini reads from stdin when `-p` is omitted and stdin is a pipe.
// Passing the full composed prompt as a CLI arg causes ENAMETOOLONG on
// Windows (CreateProcess limit ~32 KB) for any non-trivial prompt.
// `--yolo` skips interactive approval prompts in the no-TTY web UI.
buildArgs: (_prompt, _imagePaths, _extra, options = {}) => {
const args = ['--output-format', 'stream-json', '--skip-trust', '--yolo'];
if (options.model && options.model !== 'default') {
args.push('--model', options.model);
}
return args;
},
promptViaStdin: true,
streamFormat: 'json-event-stream',
eventParser: 'gemini',
},
{
id: 'opencode',
name: 'OpenCode',
bin: 'opencode',
versionArgs: ['--version'],
// `opencode models` prints `provider/model` per line.
listModels: {
args: ['models'],
parse: parseLineSeparatedModels,
timeoutMs: 8000,
},
fallbackModels: [
DEFAULT_MODEL_OPTION,
{ id: 'anthropic/claude-sonnet-4-5', label: 'anthropic/claude-sonnet-4-5' },
{ id: 'openai/gpt-5', label: 'openai/gpt-5' },
{ id: 'google/gemini-2.5-pro', label: 'google/gemini-2.5-pro' },
],
// Prompt delivered via stdin (`opencode run -`) to avoid Windows
// `spawn ENAMETOOLONG` while preserving OpenCode's structured stream.
buildArgs: (_prompt, _imagePaths, _extra, options = {}) => {
const args = ['run', '--format', 'json', '--dangerously-skip-permissions'];
if (options.model && options.model !== 'default') {
args.push('--model', options.model);
}
args.push('-');
return args;
},
promptViaStdin: true,
streamFormat: 'json-event-stream',
eventParser: 'opencode',
},
{
id: 'hermes',
name: 'Hermes',
bin: 'hermes',
versionArgs: ['--version'],
fetchModels: async (resolvedBin) =>
detectAcpModels({
bin: resolvedBin,
args: ['acp', '--accept-hooks'],
timeoutMs: 15_000,
defaultModelOption: DEFAULT_MODEL_OPTION,
}),
fallbackModels: [
DEFAULT_MODEL_OPTION,
{ id: 'openai-codex:gpt-5.5', label: 'gpt-5.5 (openai-codex:gpt-5.5)' },
{ id: 'openai-codex:gpt-5.4', label: 'gpt-5.4 (openai-codex:gpt-5.4)' },
{
id: 'openai-codex:gpt-5.4-mini',
label: 'gpt-5.4-mini (openai-codex:gpt-5.4-mini)',
},
],
buildArgs: () => ['acp', '--accept-hooks'],
streamFormat: 'acp-json-rpc',
},
{
id: 'kimi',
name: 'Kimi CLI',
bin: 'kimi',
versionArgs: ['--version'],
fetchModels: async (resolvedBin) =>
detectAcpModels({
bin: resolvedBin,
args: ['acp'],
timeoutMs: 15_000,
defaultModelOption: DEFAULT_MODEL_OPTION,
}),
fallbackModels: [
DEFAULT_MODEL_OPTION,
{ id: 'kimi-k2-turbo-preview', label: 'kimi-k2-turbo-preview' },
{ id: 'moonshot-v1-8k', label: 'moonshot-v1-8k' },
{ id: 'moonshot-v1-32k', label: 'moonshot-v1-32k' },
],
buildArgs: () => ['acp'],
streamFormat: 'acp-json-rpc',
},
{
id: 'cursor-agent',
name: 'Cursor Agent',
bin: 'cursor-agent',
versionArgs: ['--version'],
// `cursor-agent models` prints account-bound model ids per line. When
// the user isn't authed it prints "No models available for this
// account." — that's not a model list, so we detect it and fall back.
listModels: {
args: ['models'],
timeoutMs: 5000,
parse: (stdout) => {
const trimmed = String(stdout || '').trim();
if (!trimmed || /no models available/i.test(trimmed)) return null;
return parseLineSeparatedModels(trimmed);
},
},
fallbackModels: [
DEFAULT_MODEL_OPTION,
{ id: 'auto', label: 'auto' },
{ id: 'sonnet-4', label: 'sonnet-4' },
{ id: 'sonnet-4-thinking', label: 'sonnet-4-thinking' },
{ id: 'gpt-5', label: 'gpt-5' },
],
// Cursor Agent does not use `-` as a "read prompt from stdin" sentinel.
// Passing it makes the CLI treat the dash as the literal user prompt,
// which then surfaces as "your message only contains '-'". Keep stdin
// piped for prompt delivery, but do not append a fake prompt arg.
buildArgs: (_prompt, _imagePaths, _extra, options = {}, runtimeContext = {}) => {
const args = [];
args.push('--print', '--output-format', 'stream-json', '--stream-partial-output', '--force', '--trust');
if (runtimeContext.cwd) {
args.push('--workspace', runtimeContext.cwd);
}
if (options.model && options.model !== 'default') {
args.push('--model', options.model);
}
return args;
},
promptViaStdin: true,
streamFormat: 'json-event-stream',
eventParser: 'cursor-agent',
},
{
id: 'qwen',
name: 'Qwen Code',
bin: 'qwen',
versionArgs: ['--version'],
fallbackModels: [
DEFAULT_MODEL_OPTION,
{ id: 'qwen3-coder-plus', label: 'qwen3-coder-plus' },
{ id: 'qwen3-coder-flash', label: 'qwen3-coder-flash' },
],
// Prompt delivered via stdin (`qwen -`) to avoid Windows
// `spawn ENAMETOOLONG` for large composed prompts. Qwen Code is a
// Gemini-CLI fork and supports the same `--yolo` non-interactive mode.
buildArgs: (_prompt, _imagePaths, _extra, options = {}) => {
const args = ['--yolo'];
if (options.model && options.model !== 'default') {
args.push('--model', options.model);
}
args.push('-');
return args;
},
promptViaStdin: true,
streamFormat: 'plain',
},
{
id: 'copilot',
name: 'GitHub Copilot CLI',
bin: 'copilot',
versionArgs: ['--version'],
// `-p -` enters Copilot's prompt mode and tells the CLI to read the
// prompt body from stdin instead of expecting it as a positional argv
// element. Without it the daemon writes the prompt to the child's
// stdin pipe (because `promptViaStdin: true` below) but Copilot stays
// in interactive mode, never reads stdin, and rejects the run with
// `error: too many arguments. Expected 0 arguments but got N` —
// the regression filed in #350. PR #258 standardized agents on stdin
// delivery and dropped the per-prompt argv path, but missed flipping
// Copilot's mode from interactive to `-p -`.
//
// `--allow-all-tools` is required for non-interactive runs: without it
// the CLI blocks waiting for human approval on every tool call. Unlike
// Codex (where `exec` is a dedicated headless subcommand with
// auto-approve baked in) or Claude Code (which inherits its permission
// policy from the user's settings.json), Copilot's `-p` mode always
// prompts unless this flag is passed explicitly.
//
// `--output-format json` produces JSONL that copilot-stream.js parses
// into the same typed events as claude-stream.js.
//
// `--add-dir` (repeatable, same flag as Claude Code's) widens Copilot's
// path-level sandbox to skill seeds + design-system specs outside the
// project cwd.
//
// No `models` subcommand; the CLI accepts whatever the user's Copilot
// subscription exposes. Ship a small evidence-based hint list — the
// default we observed in the JSON stream and the example from
// `copilot --help`. Users can paste any other id via Settings.
fallbackModels: [
DEFAULT_MODEL_OPTION,
{ id: 'claude-sonnet-4.6', label: 'Claude Sonnet 4.6' },
{ id: 'gpt-5.2', label: 'GPT-5.2' },
],
buildArgs: (_prompt, _imagePaths, extraAllowedDirs = [], options = {}) => {
const args = [
'-p',
'-',
'--allow-all-tools',
'--output-format',
'json',
];
if (options.model && options.model !== 'default') {
args.push('--model', options.model);
}
const dirs = (extraAllowedDirs || []).filter(
(d) => typeof d === 'string' && d.length > 0,
);
for (const d of dirs) args.push('--add-dir', d);
return args;
},
promptViaStdin: true,
streamFormat: 'copilot-stream-json',
},
{
id: 'pi',
name: 'Pi',
bin: 'pi',
versionArgs: ['--version'],
// `pi --list-models` prints a TSV table to stderr (not stdout),
// so we use a custom fetchModels that reads stderr.
fetchModels: async (resolvedBin) => {
try {
const { stderr } = await execFileP(resolvedBin, ['--list-models'], {
timeout: 20_000,
maxBuffer: 8 * 1024 * 1024,
});
const parsed = parsePiModels(stderr);
if (!parsed || parsed.length === 0) return null;
return parsed;
} catch {
return null;
}
},
// Fallback models — the most commonly used providers/models when
// `pi --list-models` fails or times out.
fallbackModels: [
DEFAULT_MODEL_OPTION,
{ id: 'anthropic/claude-sonnet-4-5', label: 'Claude Sonnet 4.5 (anthropic)' },
{ id: 'anthropic/claude-opus-4-5', label: 'Claude Opus 4.5 (anthropic)' },
{ id: 'openai/gpt-5', label: 'GPT-5 (openai)' },
{ id: 'openai/o4-mini', label: 'o4-mini (openai)' },
{ id: 'google/gemini-2.5-pro', label: 'Gemini 2.5 Pro (google)' },
{ id: 'google/gemini-2.5-flash', label: 'Gemini 2.5 Flash (google)' },
],
// Thinking level presets mapped to pi's --thinking flag.
reasoningOptions: [
{ id: 'default', label: 'Default' },
{ id: 'off', label: 'Off' },
{ id: 'minimal', label: 'Minimal' },
{ id: 'low', label: 'Low' },
{ id: 'medium', label: 'Medium' },
{ id: 'high', label: 'High' },
{ id: 'xhigh', label: 'XHigh' },
],
// pi's RPC mode drives the entire conversation over stdio JSON-RPC.
// The daemon sends a `prompt` command and pi streams back typed events.
// No prompt in argv — avoids ENAMETOOLONG and keeps the protocol clean.
buildArgs: (_prompt, _imagePaths, _extra, options = {}, runtimeContext = {}) => {
const args = ['--mode', 'rpc', '--no-session'];
if (options.model && options.model !== 'default') {
// pi --model accepts patterns ("sonnet", "anthropic/claude-sonnet-4-5",
// "openai/gpt-5:high") so we pass the value through as-is.
args.push('--model', options.model);
}
if (options.reasoning && options.reasoning !== 'default') {
args.push('--thinking', options.reasoning);
}
// pi supports --append-system-prompt for cwd and extra context.
// For now we rely on the composed prompt containing the cwd hint
// (same pattern as other agents) rather than using system-prompt flags.
return args;
},
// Prompt is sent via RPC `prompt` command on stdin, not as a CLI arg.
promptViaStdin: true,
streamFormat: 'pi-rpc',
},
{
id: 'kiro',
name: 'Kiro CLI',
bin: 'kiro-cli',
versionArgs: ['--version'],
fetchModels: async (resolvedBin) =>
detectAcpModels({
bin: resolvedBin,
args: ['acp'],
timeoutMs: 15_000,
defaultModelOption: DEFAULT_MODEL_OPTION,
}),
fallbackModels: [
DEFAULT_MODEL_OPTION,
],
buildArgs: () => ['acp'],
streamFormat: 'acp-json-rpc',
},
{
id: 'vibe',
name: 'Mistral Vibe CLI',
bin: 'vibe-acp',
versionArgs: ['--version'],
fetchModels: async (resolvedBin) =>
detectAcpModels({
bin: resolvedBin,
args: [],
timeoutMs: 15_000,
defaultModelOption: DEFAULT_MODEL_OPTION,
}),
fallbackModels: [
DEFAULT_MODEL_OPTION,
],
buildArgs: () => [],
streamFormat: 'acp-json-rpc',
},
];
function existingDirsUnder(root, segments = []) {
const dirs = [];
let entries = [];
try {
entries = readdirSync(root, { withFileTypes: true });
} catch {
return dirs;
}
for (const entry of entries) {
if (!entry.isDirectory()) continue;
const full = path.join(root, entry.name, ...segments);
if (existsSync(full)) dirs.push(full);
}
return dirs;
}
const TOOLCHAIN_DIR_CACHE_TTL_MS = 5000;
let cachedToolchainHome = null;
let cachedToolchainDirs = null;
let cachedToolchainDirsAt = 0;
function userToolchainDirs() {
const homeOverride = process.env.OD_AGENT_HOME;
const home = homeOverride || homedir();
const now = Date.now();
if (
cachedToolchainHome === home &&
cachedToolchainDirs &&
now - cachedToolchainDirsAt < TOOLCHAIN_DIR_CACHE_TTL_MS
) {
return cachedToolchainDirs;
}
cachedToolchainHome = home;
cachedToolchainDirsAt = now;
cachedToolchainDirs = [
path.join(home, '.local', 'bin'),
path.join(home, '.opencode', 'bin'),
path.join(home, '.bun', 'bin'),
path.join(home, '.volta', 'bin'),
path.join(home, '.asdf', 'shims'),
path.join(home, 'Library', 'pnpm'),
path.join(home, '.cargo', 'bin'),
...(process.platform !== 'win32' && !homeOverride ? ['/opt/homebrew/bin', '/usr/local/bin'] : []),
...existingDirsUnder(path.join(home, '.local', 'share', 'mise', 'installs', 'node'), ['bin']),
...existingDirsUnder(path.join(home, '.nvm', 'versions', 'node'), ['bin']),
...existingDirsUnder(path.join(home, '.local', 'share', 'fnm', 'node-versions'), ['installation', 'bin']),
];
return cachedToolchainDirs;
}
function resolvePathDirs() {
const seen = new Set();
const dirs = [
...(process.env.PATH || '').split(delimiter),
// GUI launchers (macOS .app bundles, Linux .desktop files) often start
// with a minimal PATH. Include common user-level CLI install locations
// so agent detection matches the user's shell-installed tools,
// especially Node version managers.
...userToolchainDirs(),
];
return dirs.filter((dir) => {
if (!dir || seen.has(dir)) return false;
seen.add(dir);
return true;
});
}
export function resolveOnPath(bin) {
const exts =
process.platform === 'win32'
? (process.env.PATHEXT || '.EXE;.CMD;.BAT').split(';')
: [''];
const dirs = resolvePathDirs();
for (const dir of dirs) {
for (const ext of exts) {
const full = path.join(dir, bin + ext);
if (full && existsSync(full)) return full;
}
}
return null;
}
// Resolve the first available binary for an agent definition. Tries
// `def.bin` first, then walks `def.fallbackBins` in order. Used for
// agents whose forks ship under a different binary name but speak the
// exact same CLI (Claude Code → OpenClaude, issue #235). Returns null
// when no candidate is on PATH.
export function resolveAgentExecutable(def) {
if (!def?.bin) return null;
const candidates = [def.bin, ...(Array.isArray(def.fallbackBins) ? def.fallbackBins : [])];
for (const bin of candidates) {
const resolved = resolveOnPath(bin);
if (resolved) return resolved;
}
return null;
}
async function fetchModels(def, resolvedBin) {
if (typeof def.fetchModels === 'function') {
try {
const parsed = await def.fetchModels(resolvedBin);
if (!parsed || parsed.length === 0) return def.fallbackModels;
return parsed;
} catch {
return def.fallbackModels;
}
}
if (!def.listModels) return def.fallbackModels;
try {
const { stdout } = await execFileP(resolvedBin, def.listModels.args, {
timeout: def.listModels.timeoutMs ?? 5000,
// Models lists from popular CLIs (e.g. opencode) easily exceed the
// default 1MB buffer once you include every openrouter model. Bump
// it so we don't truncate the listing.
maxBuffer: 8 * 1024 * 1024,
});
const parsed = def.listModels.parse(stdout);
// Empty / null parse result means the CLI didn't actually return a
// usable list (e.g. cursor-agent's "No models available"); fall back
// to the static hint so the picker isn't stuck on Default-only.
if (!parsed || parsed.length === 0) return def.fallbackModels;
return parsed;
} catch {
return def.fallbackModels;
}
}
async function probe(def) {
const resolved = resolveAgentExecutable(def);
if (!resolved) {
return {
...stripFns(def),
models: def.fallbackModels ?? [DEFAULT_MODEL_OPTION],
available: false,
};
}
let version = null;
try {
const { stdout } = await execFileP(resolved, def.versionArgs, { timeout: 3000 });
version = stdout.trim().split('\n')[0];
} catch {
// binary exists but --version failed; still mark available
}
// Probe `--help` once per agent and record which flags the installed CLI
// advertises. Cached on `agentCapabilities` for buildArgs to consult.
if (def.helpArgs && def.capabilityFlags) {
const caps = {};
try {
const { stdout } = await execFileP(resolved, def.helpArgs, {
timeout: 5000,
maxBuffer: 4 * 1024 * 1024,
});
for (const [flag, key] of Object.entries(def.capabilityFlags)) {
caps[key] = stdout.includes(flag);
}
} catch {
// If --help fails, leave caps empty — buildArgs falls back to the safe
// baseline (no optional flags).
}
agentCapabilities.set(def.id, caps);
}
const models = await fetchModels(def, resolved);
return {
...stripFns(def),
models,
available: true,
path: resolved,
version,
};
}
function stripFns(def) {
// Drop the buildArgs / listModels closures but keep declarative metadata
// (reasoningOptions, streamFormat, name, bin, etc.). `models` is
// populated separately by `fetchModels`, so we strip the static
// `fallbackModels` slot here too. `helpArgs` / `capabilityFlags` /
// `fallbackBins` are probe-only metadata and shouldn't bleed into the
// API response either.
const {
buildArgs,
listModels,
fetchModels,
fallbackModels,
helpArgs,
capabilityFlags,
fallbackBins,
...rest
} = def;
return rest;
}
export async function detectAgents() {
const results = await Promise.all(AGENT_DEFS.map(probe));
// Refresh the validation cache from whatever we just surfaced to the UI
// so /api/chat can accept any model the user could have just picked,
// including ones that only showed up after a CLI re-auth.
for (const agent of results) {
rememberLiveModels(agent.id, agent.models);
}
return results;
}
export function getAgentDef(id) {
return AGENT_DEFS.find((a) => a.id === id) || null;
}
// Resolve the absolute path of an agent's binary on the current PATH.
// Used by the chat handler so spawn() gets the same executable that
// detection reported as available — fixes Windows ENOENT when the bare
// bin name isn't on the child process's PATH (issue #10).
export function resolveAgentBin(id) {
const def = getAgentDef(id);
if (!def?.bin) return null;
return resolveAgentExecutable(def);
}
// Build the env passed to spawn() for a given agent adapter.
//
// The claude adapter strips ANTHROPIC_API_KEY so Claude Code's own auth
// resolution (claude login / Pro/Max plan) wins instead of silently
// falling back to API-key billing whenever the daemon happened to be
// launched from a shell that exported the key for SDK or scripting use.
// See issue #398.
//
// Windows env-var names are case-insensitive at the kernel level
// (`GetEnvironmentVariable`), but spreading `process.env` into a plain
// object loses Node's case-insensitive accessor — `Anthropic_Api_Key`
// would survive a literal `delete env.ANTHROPIC_API_KEY` and still reach
// the child. Iterate keys and compare case-insensitively to close that.
export function spawnEnvForAgent(agentId, baseEnv) {
const env = { ...baseEnv };
if (agentId !== 'claude') return env;
for (const key of Object.keys(env)) {
if (key.toUpperCase() === 'ANTHROPIC_API_KEY') delete env[key];
}
return env;
}
// Daemon's /api/chat needs to validate the user's model pick against the
// list we last surfaced to the UI. We keep a per-agent cache of the most
// recent live list (refreshed every detectAgents() call) and additionally
// trust any value present in the static fallback. A model that's neither
// gets rejected so a stale or hostile value can't smuggle arbitrary flags.
const liveModelCache = new Map();
export function rememberLiveModels(agentId, models) {
if (!Array.isArray(models)) return;
liveModelCache.set(
agentId,
new Set(models.map((m) => m && m.id).filter((id) => typeof id === 'string')),
);
}
export function isKnownModel(def, modelId) {
if (!modelId) return false;
const live = liveModelCache.get(def.id);
if (live && live.has(modelId)) return true;
if (Array.isArray(def.fallbackModels)) {
return def.fallbackModels.some((m) => m.id === modelId);
}
return false;
}
// Permit user-typed model ids that didn't appear in either the live
// listing or the static fallback (e.g. the user is on a brand-new model
// the CLI's `models` command hasn't surfaced yet). The CLI gets the value
// as a child-process arg — not a shell string — so injection isn't a
// concern, but we still reject anything that could be misread as a flag
// by a downstream CLI or that contains whitespace / control chars.
export function sanitizeCustomModel(id) {
if (typeof id !== 'string') return null;
const trimmed = id.trim();
if (trimmed.length === 0 || trimmed.length > 200) return null;
if (!/^[A-Za-z0-9][A-Za-z0-9._/:@-]*$/.test(trimmed)) return null;
return trimmed;
}