reevesagents 2.1.0 → 2.2.1

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.
@@ -1,3222 +0,0 @@
1
- #!/usr/bin/env node
2
- import {
3
- WEB_EXTRA_MODULES
4
- } from "./chunk-Q3WWQP2R.js";
5
-
6
- // src/core/model-data.ts
7
- var CC_MODEL_SOURCE = "curated Claude Code aliases";
8
- var CC_MODELS = [
9
- "fable",
10
- "opus",
11
- "sonnet",
12
- "haiku"
13
- ];
14
- var CODEX_MODEL_SOURCE = "curated Codex CLI model ids";
15
- var CODEX_MODELS = [
16
- "gpt-5.6-sol",
17
- "gpt-5.5",
18
- "gpt-5.4-mini"
19
- ];
20
- var OPENCODE_MODEL_SOURCE = "curated OpenCode provider/model ids";
21
- var OPENCODE_MODELS = [
22
- "opencode/claude-sonnet-4-6",
23
- "opencode/claude-opus-4-8",
24
- "opencode/gpt-5.2-codex",
25
- "anthropic/claude-opus-4-8",
26
- "anthropic/claude-haiku-4-5",
27
- "openai/gpt-5.5"
28
- ];
29
- var HERMES_MODEL_SOURCE = "curated Hermes model ids";
30
- var HERMES_MODELS = [
31
- "anthropic:claude-opus-4-8",
32
- "anthropic:claude-fable-5",
33
- "openai-codex:gpt-5.5",
34
- "openai-codex:gpt-5.4-mini"
35
- ];
36
- var KIMI_MODEL_SOURCE = "curated Kimi Code model aliases";
37
- var KIMI_MODELS = [
38
- "kimi-code/k3",
39
- "kimi-code/kimi-for-coding",
40
- "kimi-code/kimi-for-coding-highspeed"
41
- ];
42
- var DEEPSEEK_MODEL_SOURCE = "curated DeepSeek CLI model ids";
43
- var DEEPSEEK_MODELS = [
44
- "deepseek-v4-pro",
45
- "deepseek-v4-flash"
46
- ];
47
- var PI_MODEL_SOURCE = "curated Pi model aliases";
48
- var PI_MODELS = [
49
- "sonnet",
50
- "opus",
51
- "deepseek/deepseek-chat",
52
- "openai/gpt-4o"
53
- ];
54
- var QWEN_MODEL_SOURCE = "curated Qwen Code model ids";
55
- var QWEN_MODELS = [
56
- "qwen3-coder-plus",
57
- "qwen3-coder-flash",
58
- "qwen3-coder-next"
59
- ];
60
- var AIDER_MODEL_SOURCE = "curated Aider model aliases";
61
- var AIDER_MODELS = [
62
- "sonnet",
63
- "opus",
64
- "haiku",
65
- "deepseek/deepseek-chat"
66
- ];
67
- var GEMINI_MODEL_SOURCE = "curated Gemini CLI model ids";
68
- var GEMINI_MODELS = [
69
- "gemini-3.1-pro-preview",
70
- "gemini-3.5-flash",
71
- "gemini-3.1-flash-lite"
72
- ];
73
- var CLINE_MODEL_SOURCE = "curated Cline CLI model ids";
74
- var CLINE_MODELS = [
75
- "anthropic/claude-sonnet-4-6",
76
- "anthropic/claude-opus-4-8",
77
- "google/gemini-3.1-pro"
78
- ];
79
- var CRUSH_MODEL_SOURCE = "chosen inside Crush (its TUI model picker); the launch has no model flag";
80
- var CRUSH_MODELS = [];
81
- var GOOSE_MODEL_SOURCE = "curated Goose model ids";
82
- var GOOSE_MODELS = [
83
- "claude-sonnet-4-6",
84
- "claude-opus-4-8",
85
- "deepseek-v4-pro"
86
- ];
87
- var KILO_MODEL_SOURCE = "curated Kilo Code model ids";
88
- var KILO_MODELS = [
89
- "kilo/~anthropic/claude-sonnet-latest",
90
- "kilo/~anthropic/claude-opus-latest",
91
- "kilo/~google/gemini-pro-latest",
92
- "kilo/~openai/gpt-sol-latest"
93
- ];
94
- var LETTA_MODEL_SOURCE = "curated Letta Code model ids";
95
- var LETTA_MODELS = [
96
- "zai-org/GLM-5.3-max",
97
- "moonshotai/Kimi-K2-Instruct",
98
- "Qwen/Qwen3-Coder-480B-A35B-Instruct"
99
- ];
100
- var VIBE_MODEL_SOURCE = "set in vibe config (active_model or VIBE_ACTIVE_MODEL); the launch has no model flag";
101
- var VIBE_MODELS = [];
102
- var GROK_MODEL_SOURCE = "curated Grok Build model ids";
103
- var GROK_MODELS = [
104
- "grok-4.6",
105
- "grok-4.5",
106
- "grok-4.7"
107
- ];
108
- var KIRO_MODEL_SOURCE = "curated Kiro CLI model ids";
109
- var KIRO_MODELS = [
110
- "claude-sonnet-4.6",
111
- "claude-opus-4.7",
112
- "claude-opus-4.6"
113
- ];
114
- var DROID_MODEL_SOURCE = "chosen inside Factory Droid itself; the launch has no model flag";
115
- var DROID_MODELS = [];
116
- var QODER_MODEL_SOURCE = "curated Qoder CLI model ids";
117
- var QODER_MODELS = [
118
- "auto",
119
- "performance",
120
- "lite"
121
- ];
122
- var WARP_MODEL_SOURCE = "chosen inside the Warp TUI; the launch has no model flag";
123
- var WARP_MODELS = [];
124
- var JUNIE_MODEL_SOURCE = "curated Junie CLI model ids";
125
- var JUNIE_MODELS = [
126
- "sonnet",
127
- "opus",
128
- "gpt-sol"
129
- ];
130
- var COPILOT_MODEL_SOURCE = "curated GitHub Copilot CLI model ids";
131
- var COPILOT_MODELS = [
132
- "auto",
133
- "gpt-5.4",
134
- "claude-opus-4.8"
135
- ];
136
- var CURSOR_MODEL_SOURCE = "curated Cursor CLI model ids";
137
- var CURSOR_MODELS = [
138
- "gpt-5",
139
- "sonnet-4-thinking",
140
- "claude-opus-4-8"
141
- ];
142
- var ROVO_MODEL_SOURCE = "set in Rovo Dev itself (/models or agent.modelId in config); the launch has no model flag";
143
- var ROVO_MODELS = [];
144
-
145
- // src/core/provider-registry.ts
146
- var HERMES_PROVIDER_PREFIXES = /* @__PURE__ */ new Set([
147
- "auto",
148
- "openrouter",
149
- "nous",
150
- "openai-codex",
151
- "copilot-acp",
152
- "copilot",
153
- "anthropic",
154
- "huggingface",
155
- "novita",
156
- "zai",
157
- "kimi-coding",
158
- "kimi-coding-cn",
159
- "minimax",
160
- "minimax-cn",
161
- "minimax-oauth",
162
- "kilocode",
163
- "xiaomi",
164
- "arcee",
165
- "gmi",
166
- "alibaba",
167
- "alibaba-coding-plan",
168
- "deepseek",
169
- "nvidia",
170
- "ollama-cloud",
171
- "xai",
172
- "xai-oauth",
173
- "qwen-oauth",
174
- "bedrock",
175
- "opencode-zen",
176
- "opencode-go",
177
- "azure-foundry",
178
- "lmstudio",
179
- "stepfun",
180
- "tencent-tokenhub",
181
- "custom"
182
- ]);
183
- function parseHermesModel(value) {
184
- const separator = value.indexOf(":");
185
- if (separator <= 0) return { model: value };
186
- const provider = value.slice(0, separator).trim();
187
- const model = value.slice(separator + 1).trim();
188
- if (!provider || !model || !HERMES_PROVIDER_PREFIXES.has(provider)) return { model: value };
189
- return { provider, model };
190
- }
191
- var PROVIDER_REGISTRY = {
192
- cc: {
193
- id: "cc",
194
- bin: "claude",
195
- displayName: "Claude Code",
196
- color: "#d97757",
197
- // Anthropic Orange (Claude brand); the one warm color in the palette
198
- aliases: ["cc", "claude", "claude code", "claude-code", "claudecode"],
199
- models: CC_MODELS,
200
- modelSource: CC_MODEL_SOURCE,
201
- helpRequirements: [
202
- { feature: "skip permissions", tokens: ["--dangerously-skip-permissions"] }
203
- ],
204
- supportsAuthMode: true,
205
- supportsEffort: true,
206
- buildArgs: ({ permissions, model, auth_mode, effort }) => {
207
- const args = [];
208
- if (permissions === "skip") args.push("--dangerously-skip-permissions");
209
- if (auth_mode === "api-key") args.push("--bare");
210
- if (effort !== "default") args.push("--effort", effort);
211
- if (model) args.push("--model", model);
212
- return args;
213
- }
214
- },
215
- codex: {
216
- id: "codex",
217
- bin: "codex",
218
- displayName: "Codex CLI",
219
- color: "#7aa8c4",
220
- // cool teal-blue
221
- aliases: ["codex", "codex cli", "codex-cli"],
222
- models: CODEX_MODELS,
223
- modelSource: CODEX_MODEL_SOURCE,
224
- helpRequirements: [
225
- { feature: "skip permissions", tokens: ["--dangerously-bypass-approvals-and-sandbox"] },
226
- { feature: "config override", tokens: ["--config"] }
227
- ],
228
- supportsEffort: true,
229
- buildArgs: ({ permissions, model, effort }) => {
230
- const args = [];
231
- if (permissions === "skip") args.push("--dangerously-bypass-approvals-and-sandbox");
232
- if (effort !== "default") {
233
- const codexEffort = effort === "max" ? "xhigh" : effort;
234
- args.push("-c", `model_reasoning_effort=${codexEffort}`);
235
- }
236
- if (model) args.push("--model", model);
237
- return args;
238
- }
239
- },
240
- opencode: {
241
- id: "opencode",
242
- bin: "opencode",
243
- displayName: "OpenCode CLI",
244
- color: "#a890d1",
245
- // muted purple
246
- aliases: ["opencode", "opencode cli", "opencode-cli", "open_code"],
247
- models: OPENCODE_MODELS,
248
- modelSource: OPENCODE_MODEL_SOURCE,
249
- helpRequirements: [
250
- { feature: "prompt launch", tokens: ["--prompt"] },
251
- { feature: "model selection", tokens: ["--model"] }
252
- ],
253
- buildArgs: ({ model }) => {
254
- const args = [];
255
- if (model) args.push("--model", model);
256
- return args;
257
- }
258
- },
259
- hermes: {
260
- id: "hermes",
261
- bin: "hermes",
262
- displayName: "Hermes",
263
- color: "#c97b9b",
264
- // muted rose
265
- aliases: ["hermes"],
266
- models: HERMES_MODELS,
267
- modelSource: HERMES_MODEL_SOURCE,
268
- helpRequirements: [
269
- { feature: "chat launch", tokens: ["--model"] },
270
- { feature: "skip permissions", tokens: ["--yolo"] }
271
- ],
272
- helpArgs: ["chat", "--help"],
273
- buildArgs: ({ permissions, model }) => {
274
- const args = ["chat"];
275
- if (permissions === "skip") args.push("--yolo");
276
- if (model) {
277
- const parsed = parseHermesModel(model);
278
- if (parsed.provider) args.push("--provider", parsed.provider);
279
- args.push("--model", parsed.model);
280
- }
281
- return args;
282
- }
283
- },
284
- kimi: {
285
- id: "kimi",
286
- bin: "kimi",
287
- displayName: "Kimi Code",
288
- color: "#b6a45d",
289
- // muted gold
290
- aliases: ["kimi", "kimi code", "kimi-code"],
291
- models: KIMI_MODELS,
292
- modelSource: KIMI_MODEL_SOURCE,
293
- helpRequirements: [
294
- { feature: "model selection", tokens: ["--model"] },
295
- { feature: "skip permissions", tokens: ["--yolo"] }
296
- ],
297
- buildArgs: ({ permissions, model }) => {
298
- const args = [];
299
- if (permissions === "skip") args.push("--yolo");
300
- if (model) args.push("--model", model);
301
- return args;
302
- }
303
- },
304
- deepseek: {
305
- id: "deepseek",
306
- bin: "deepseek",
307
- displayName: "DeepSeek CLI",
308
- color: "#6fb0a8",
309
- // muted cyan
310
- aliases: ["deepseek", "deepseek cli", "deepseek-cli"],
311
- models: DEEPSEEK_MODELS,
312
- modelSource: DEEPSEEK_MODEL_SOURCE,
313
- helpRequirements: [
314
- { feature: "model selection", tokens: ["--model"] }
315
- ],
316
- buildArgs: ({ model }) => {
317
- const args = [];
318
- if (model) args.push("--model", model);
319
- return args;
320
- }
321
- },
322
- pi: {
323
- id: "pi",
324
- bin: "pi",
325
- displayName: "Pi",
326
- color: "#86a76b",
327
- // muted olive
328
- aliases: ["pi"],
329
- models: PI_MODELS,
330
- modelSource: PI_MODEL_SOURCE,
331
- helpRequirements: [
332
- { feature: "model selection", tokens: ["--model"] }
333
- ],
334
- buildArgs: ({ model }) => {
335
- const args = [];
336
- if (model) args.push("--model", model);
337
- return args;
338
- }
339
- },
340
- qwen: {
341
- id: "qwen",
342
- bin: "qwen",
343
- displayName: "Qwen Code",
344
- color: "#c58c63",
345
- // muted copper
346
- aliases: ["qwen", "qwen code", "qwen-code"],
347
- models: QWEN_MODELS,
348
- modelSource: QWEN_MODEL_SOURCE,
349
- helpRequirements: [
350
- { feature: "model selection", tokens: ["--model"] },
351
- { feature: "skip permissions", tokens: ["--approval-mode"] }
352
- ],
353
- buildArgs: ({ permissions, model }) => {
354
- const args = [];
355
- if (permissions === "skip") args.push("--approval-mode", "yolo");
356
- if (model) args.push("--model", model);
357
- return args;
358
- }
359
- },
360
- aider: {
361
- id: "aider",
362
- bin: "aider",
363
- displayName: "Aider",
364
- color: "#8fa6d4",
365
- // muted periwinkle
366
- aliases: ["aider"],
367
- models: AIDER_MODELS,
368
- modelSource: AIDER_MODEL_SOURCE,
369
- helpRequirements: [
370
- { feature: "model selection", tokens: ["--model"] },
371
- { feature: "skip confirmations", tokens: ["--yes-always"] }
372
- ],
373
- buildArgs: ({ permissions, model }) => {
374
- const args = [];
375
- if (permissions === "skip") args.push("--yes-always");
376
- if (model) args.push("--model", model);
377
- return args;
378
- }
379
- },
380
- gemini: {
381
- id: "gemini",
382
- bin: "gemini",
383
- displayName: "Gemini CLI",
384
- color: "#8b7fe8",
385
- // muted blue-violet, the Gemini spark gradient
386
- aliases: ["gemini", "gemini cli", "gemini-cli"],
387
- models: GEMINI_MODELS,
388
- modelSource: GEMINI_MODEL_SOURCE,
389
- helpRequirements: [
390
- { feature: "model selection", tokens: ["--model"] },
391
- { feature: "skip permissions", tokens: ["--approval-mode"] }
392
- ],
393
- buildArgs: ({ permissions, model }) => {
394
- const args = [];
395
- if (permissions === "skip") args.push("--approval-mode", "yolo");
396
- if (model) args.push("--model", model);
397
- return args;
398
- }
399
- },
400
- cline: {
401
- id: "cline",
402
- bin: "cline",
403
- displayName: "Cline CLI",
404
- color: "#6b9fd6",
405
- // muted Cline blue
406
- aliases: ["cline", "cline cli", "cline-cli"],
407
- models: CLINE_MODELS,
408
- modelSource: CLINE_MODEL_SOURCE,
409
- helpRequirements: [
410
- { feature: "model selection", tokens: ["--model"] },
411
- { feature: "skip permissions", tokens: ["--auto-approve"] }
412
- ],
413
- buildArgs: ({ permissions, model }) => {
414
- const args = ["--tui"];
415
- if (permissions === "skip") args.push("--auto-approve", "true");
416
- if (model) args.push("--model", model);
417
- return args;
418
- }
419
- },
420
- crush: {
421
- id: "crush",
422
- bin: "crush",
423
- displayName: "Crush",
424
- color: "#e092b8",
425
- // muted Charm pink
426
- aliases: ["crush", "charm crush", "charm-crush"],
427
- models: CRUSH_MODELS,
428
- modelSource: CRUSH_MODEL_SOURCE,
429
- helpRequirements: [
430
- { feature: "skip permissions", tokens: ["--yolo"] }
431
- ],
432
- buildArgs: ({ permissions }) => {
433
- const args = [];
434
- if (permissions === "skip") args.push("--yolo");
435
- return args;
436
- }
437
- },
438
- goose: {
439
- id: "goose",
440
- bin: "goose",
441
- displayName: "Goose",
442
- color: "#b39a80",
443
- // muted goose tan
444
- aliases: ["goose"],
445
- models: GOOSE_MODELS,
446
- modelSource: GOOSE_MODEL_SOURCE,
447
- helpRequirements: [
448
- { feature: "interactive session", tokens: ["session"] },
449
- { feature: "model selection", tokens: ["--model"] }
450
- ],
451
- helpArgs: ["session", "--help"],
452
- buildArgs: ({ model }) => {
453
- const args = ["session"];
454
- if (model) args.push("--model", model);
455
- return args;
456
- }
457
- },
458
- kilo: {
459
- id: "kilo",
460
- bin: "kilo",
461
- displayName: "Kilo Code",
462
- color: "#c46f6f",
463
- // muted soft red
464
- aliases: ["kilo", "kilo code", "kilo-code", "kilocode"],
465
- models: KILO_MODELS,
466
- modelSource: KILO_MODEL_SOURCE,
467
- helpRequirements: [
468
- { feature: "model selection", tokens: ["--model"] },
469
- { feature: "skip permissions", tokens: ["--auto"] }
470
- ],
471
- buildArgs: ({ permissions, model }) => {
472
- const args = [];
473
- if (permissions === "skip") args.push("--auto");
474
- if (model) args.push("--model", model);
475
- return args;
476
- }
477
- },
478
- letta: {
479
- id: "letta",
480
- bin: "letta",
481
- displayName: "Letta Code",
482
- color: "#6fb387",
483
- // muted starling green
484
- aliases: ["letta", "letta code", "letta-code"],
485
- models: LETTA_MODELS,
486
- modelSource: LETTA_MODEL_SOURCE,
487
- helpRequirements: [
488
- { feature: "fresh conversation", tokens: ["--new"] },
489
- { feature: "model selection", tokens: ["--model"] }
490
- ],
491
- buildArgs: ({ permissions, model }) => {
492
- const args = ["--new"];
493
- if (permissions === "skip") args.push("--permission-mode", "unrestricted");
494
- if (model) args.push("--model", model);
495
- return args;
496
- }
497
- },
498
- vibe: {
499
- id: "vibe",
500
- bin: "vibe",
501
- displayName: "Mistral Vibe",
502
- color: "#e3a35e",
503
- // muted Mistral amber
504
- aliases: ["vibe", "mistral vibe", "mistral-vibe", "mistral"],
505
- models: VIBE_MODELS,
506
- modelSource: VIBE_MODEL_SOURCE,
507
- helpRequirements: [
508
- { feature: "skip permissions", tokens: ["--auto-approve"] }
509
- ],
510
- buildArgs: ({ permissions }) => {
511
- const args = [];
512
- if (permissions === "skip") args.push("--auto-approve");
513
- return args;
514
- }
515
- },
516
- grok: {
517
- id: "grok",
518
- bin: "grok",
519
- displayName: "Grok Build",
520
- color: "#9a9a96",
521
- // muted xAI graphite
522
- aliases: ["grok", "grok build", "grok-build", "xai"],
523
- models: GROK_MODELS,
524
- modelSource: GROK_MODEL_SOURCE,
525
- helpRequirements: [
526
- { feature: "model selection", tokens: ["--model"] },
527
- { feature: "skip permissions", tokens: ["--always-approve"] }
528
- ],
529
- buildArgs: ({ permissions, model }) => {
530
- const args = [];
531
- if (permissions === "skip") args.push("--always-approve");
532
- if (model) args.push("--model", model);
533
- return args;
534
- }
535
- },
536
- kiro: {
537
- id: "kiro",
538
- bin: "kiro-cli",
539
- displayName: "Kiro CLI",
540
- color: "#b070c8",
541
- // muted Kiro violet
542
- aliases: ["kiro", "kiro cli", "kiro-cli"],
543
- models: KIRO_MODELS,
544
- modelSource: KIRO_MODEL_SOURCE,
545
- helpRequirements: [
546
- { feature: "model selection", tokens: ["--model"] },
547
- { feature: "skip permissions", tokens: ["--trust-all-tools"] }
548
- ],
549
- helpArgs: ["chat", "--help"],
550
- buildArgs: ({ permissions, model }) => {
551
- const args = ["chat"];
552
- if (permissions === "skip") args.push("--trust-all-tools");
553
- if (model) args.push("--model", model);
554
- return args;
555
- }
556
- },
557
- droid: {
558
- id: "droid",
559
- bin: "droid",
560
- displayName: "Factory Droid",
561
- color: "#7f8fa3",
562
- // muted slate
563
- aliases: ["droid", "factory", "factory droid", "factory-droid"],
564
- models: DROID_MODELS,
565
- modelSource: DROID_MODEL_SOURCE,
566
- helpRequirements: [
567
- { feature: "skip permissions", tokens: ["--auto"] }
568
- ],
569
- buildArgs: ({ permissions }) => {
570
- const args = [];
571
- if (permissions === "skip") args.push("--auto", "high");
572
- return args;
573
- }
574
- },
575
- qoder: {
576
- id: "qoder",
577
- bin: "qodercli",
578
- displayName: "Qoder CLI",
579
- color: "#57c785",
580
- // muted Qoder green
581
- aliases: ["qoder", "qoder cli", "qoder-cli", "qodercli"],
582
- models: QODER_MODELS,
583
- modelSource: QODER_MODEL_SOURCE,
584
- helpRequirements: [
585
- { feature: "model selection", tokens: ["--model"] },
586
- { feature: "skip permissions", tokens: ["--dangerously-skip-permissions"] }
587
- ],
588
- buildArgs: ({ permissions, model }) => {
589
- const args = [];
590
- if (permissions === "skip") args.push("--dangerously-skip-permissions");
591
- if (model) args.push("--model", model);
592
- return args;
593
- }
594
- },
595
- warp: {
596
- id: "warp",
597
- bin: "warp",
598
- displayName: "Warp",
599
- color: "#4aa3b0",
600
- // muted Warp teal
601
- aliases: ["warp", "warp agent", "warp-agent"],
602
- models: WARP_MODELS,
603
- modelSource: WARP_MODEL_SOURCE,
604
- helpRequirements: [
605
- { feature: "skip permissions", tokens: ["--auto-approve"] }
606
- ],
607
- buildArgs: ({ permissions }) => {
608
- const args = [];
609
- if (permissions === "skip") args.push("--auto-approve");
610
- return args;
611
- }
612
- },
613
- junie: {
614
- id: "junie",
615
- bin: "junie",
616
- displayName: "Junie CLI",
617
- color: "#a9c256",
618
- // muted Junie lime
619
- aliases: ["junie", "junie cli", "junie-cli", "jetbrains junie"],
620
- models: JUNIE_MODELS,
621
- modelSource: JUNIE_MODEL_SOURCE,
622
- helpRequirements: [
623
- { feature: "model selection", tokens: ["--model"] },
624
- { feature: "skip permissions", tokens: ["--brave"] }
625
- ],
626
- buildArgs: ({ permissions, model }) => {
627
- const args = [];
628
- if (permissions === "skip") args.push("--brave");
629
- if (model) args.push("--model", model);
630
- return args;
631
- }
632
- },
633
- copilot: {
634
- id: "copilot",
635
- bin: "copilot",
636
- displayName: "GitHub Copilot CLI",
637
- color: "#7d8ce8",
638
- // muted Copilot indigo
639
- aliases: ["copilot", "copilot cli", "copilot-cli", "github copilot"],
640
- models: COPILOT_MODELS,
641
- modelSource: COPILOT_MODEL_SOURCE,
642
- helpRequirements: [
643
- { feature: "model selection", tokens: ["--model"] },
644
- { feature: "skip permissions", tokens: ["--allow-all"] }
645
- ],
646
- buildArgs: ({ permissions, model }) => {
647
- const args = [];
648
- if (permissions === "skip") args.push("--allow-all");
649
- if (model) args.push("--model", model);
650
- return args;
651
- }
652
- },
653
- cursor: {
654
- id: "cursor",
655
- bin: "cursor-agent",
656
- displayName: "Cursor CLI",
657
- color: "#cfd8dc",
658
- // muted Cursor silver
659
- aliases: ["cursor", "cursor cli", "cursor-cli", "cursor-agent"],
660
- models: CURSOR_MODELS,
661
- modelSource: CURSOR_MODEL_SOURCE,
662
- helpRequirements: [
663
- { feature: "model selection", tokens: ["--model"] },
664
- { feature: "skip permissions", tokens: ["--force"] }
665
- ],
666
- buildArgs: ({ permissions, model }) => {
667
- const args = [];
668
- if (permissions === "skip") args.push("--force");
669
- if (model) args.push("--model", model);
670
- return args;
671
- }
672
- },
673
- rovo: {
674
- id: "rovo",
675
- bin: "acli",
676
- displayName: "Rovo Dev CLI",
677
- color: "#3f7fd0",
678
- // muted Atlassian blue
679
- aliases: ["rovo", "rovo dev", "rovo-dev", "rovodev"],
680
- models: ROVO_MODELS,
681
- modelSource: ROVO_MODEL_SOURCE,
682
- helpRequirements: [
683
- { feature: "skip permissions", tokens: ["--yolo"] }
684
- ],
685
- helpArgs: ["rovodev", "run", "--help"],
686
- buildArgs: ({ permissions }) => {
687
- const args = ["rovodev", "run"];
688
- if (permissions === "skip") args.push("--yolo");
689
- return args;
690
- }
691
- }
692
- };
693
- var PROVIDER_DEFS = Object.values(PROVIDER_REGISTRY);
694
-
695
- // src/core/providers.ts
696
- import { execFileSync, spawnSync } from "child_process";
697
- function coerceExtraArgs(value) {
698
- if (Array.isArray(value)) {
699
- return value.filter((item) => typeof item === "string").map((item) => item.trim()).filter(Boolean);
700
- }
701
- if (typeof value === "string") {
702
- return value.trim().split(/\s+/).filter(Boolean);
703
- }
704
- return [];
705
- }
706
- var BIN = Object.fromEntries(
707
- PROVIDER_DEFS.map((def) => [def.id, def.bin])
708
- );
709
- var PROVIDERS = Object.keys(PROVIDER_REGISTRY);
710
- var PROVIDER_ALIASES = Object.fromEntries(
711
- PROVIDER_DEFS.flatMap((def) => def.aliases.map((alias) => [alias, def.id]))
712
- );
713
- var HELP_INSPECT_TIMEOUT_MS = 3e3;
714
- var HELP_INSPECT_TOTAL_BUDGET_MS = Math.max(8e3, PROVIDERS.length * 1500);
715
- function isProvider(value) {
716
- return typeof value === "string" && Object.prototype.hasOwnProperty.call(PROVIDER_REGISTRY, value);
717
- }
718
- function normalizeProvider(value) {
719
- if (typeof value !== "string") return null;
720
- return PROVIDER_ALIASES[value.trim().toLowerCase()] ?? null;
721
- }
722
- function providerSupportsAuthMode(provider) {
723
- return PROVIDER_REGISTRY[provider]?.supportsAuthMode === true;
724
- }
725
- function providerSupportsEffort(provider) {
726
- return PROVIDER_REGISTRY[provider]?.supportsEffort === true;
727
- }
728
- function buildCommand(opts) {
729
- const { provider, permissions, model, auth_mode = "default", effort = "default", extra_args = [] } = opts;
730
- if (!isProvider(provider)) {
731
- throw new Error(`Unsupported provider: ${String(provider)}`);
732
- }
733
- const def = PROVIDER_REGISTRY[provider];
734
- return [def.bin, ...def.buildArgs({ permissions, model, auth_mode, effort }), ...extra_args];
735
- }
736
- function binaryOnPath(bin, platform = process.platform) {
737
- try {
738
- execFileSync(platform === "win32" ? "where" : "which", [bin], { stdio: "pipe" });
739
- return true;
740
- } catch {
741
- return false;
742
- }
743
- }
744
- function detectAvailable() {
745
- const result = {};
746
- for (const provider of PROVIDERS) {
747
- result[provider] = binaryOnPath(BIN[provider]);
748
- }
749
- return result;
750
- }
751
- function helpCommand(provider) {
752
- const def = PROVIDER_REGISTRY[provider];
753
- return [def.bin, ...def.helpArgs ?? ["--help"]];
754
- }
755
- function missingHelpFeatures(provider, helpText) {
756
- return PROVIDER_REGISTRY[provider].helpRequirements.filter((req) => req.tokens.some((token) => !helpText.includes(token))).map((req) => req.feature);
757
- }
758
- function resolveCliPath(bin) {
759
- try {
760
- const out = execFileSync(process.platform === "win32" ? "where" : "which", [bin], {
761
- encoding: "utf8",
762
- stdio: ["ignore", "pipe", "ignore"]
763
- });
764
- const candidates = out.trim().split(/\r?\n/).filter(Boolean);
765
- return candidates.find((c) => /\.(cmd|bat|exe)$/i.test(c)) ?? candidates[0] ?? null;
766
- } catch {
767
- return null;
768
- }
769
- }
770
- var isPlainToken = (token) => /^[A-Za-z0-9_:@%+=,./\\-]+$/.test(token);
771
- function spawnCliSync(bin, args, options = {}, platform = process.platform) {
772
- if (platform !== "win32") return spawnSync(bin, args, options);
773
- const resolved = resolveCliPath(bin);
774
- if (!resolved) return spawnSync(bin, args, options);
775
- if (/\.(cmd|bat)$/i.test(resolved)) {
776
- return spawnCmdShim(resolved, args, options);
777
- }
778
- return spawnSync(resolved, args, options);
779
- }
780
- function spawnCmdShim(resolved, args, options) {
781
- const cmdSafe = (token) => isPlainToken(token) ? token : '"' + token.replace(/["\\^&|<>()!%]/g, "").replace(/\s+/g, " ") + '"';
782
- return spawnSync(`"${resolved}"`, args.map(cmdSafe), { ...options, shell: true, windowsVerbatimArguments: true });
783
- }
784
- function inspectProviderCompatibility() {
785
- const available = detectAvailable();
786
- const result = {};
787
- const deadline = Date.now() + HELP_INSPECT_TOTAL_BUDGET_MS;
788
- for (const provider of PROVIDERS) {
789
- if (!available[provider]) {
790
- result[provider] = {
791
- provider,
792
- available: false,
793
- ok: true,
794
- detail: "not installed",
795
- missing: []
796
- };
797
- continue;
798
- }
799
- try {
800
- const remaining = deadline - Date.now();
801
- if (remaining <= 0) {
802
- result[provider] = {
803
- provider,
804
- available: true,
805
- ok: false,
806
- detail: "help inspection skipped after timeout budget",
807
- missing: ["help inspection"]
808
- };
809
- continue;
810
- }
811
- const [bin, ...args] = helpCommand(provider);
812
- const inspected = spawnCliSync(bin, args, {
813
- encoding: "utf8",
814
- stdio: ["ignore", "pipe", "pipe"],
815
- timeout: Math.min(HELP_INSPECT_TIMEOUT_MS, remaining)
816
- });
817
- if (inspected.error) throw inspected.error;
818
- const help = `${inspected.stdout ?? ""}
819
- ${inspected.stderr ?? ""}`;
820
- if (inspected.status !== 0 && help.trim().length === 0) {
821
- throw new Error(`help exited ${inspected.status}`);
822
- }
823
- const missing = missingHelpFeatures(provider, help);
824
- result[provider] = {
825
- provider,
826
- available: true,
827
- ok: missing.length === 0,
828
- detail: missing.length === 0 ? "compatible" : `missing ${missing.join(", ")}`,
829
- missing
830
- };
831
- } catch (err) {
832
- result[provider] = {
833
- provider,
834
- available: true,
835
- ok: false,
836
- detail: `could not inspect help: ${err instanceof Error ? err.message : "unknown error"}`,
837
- missing: ["help inspection"]
838
- };
839
- }
840
- }
841
- return result;
842
- }
843
-
844
- // src/core/runs.ts
845
- import {
846
- chmodSync,
847
- closeSync,
848
- existsSync as existsSync2,
849
- mkdirSync,
850
- openSync,
851
- readdirSync,
852
- readFileSync,
853
- renameSync,
854
- rmSync,
855
- statSync,
856
- unlinkSync,
857
- writeFileSync
858
- } from "fs";
859
- import { randomUUID } from "crypto";
860
- import { homedir } from "os";
861
- import { dirname as dirname2, join as join2 } from "path";
862
-
863
- // src/core/redact.ts
864
- var SECRET_PATTERNS = [
865
- /sk-ant-[A-Za-z0-9\-_]{20,}/g,
866
- /sk-[A-Za-z0-9\-_]{20,}/g,
867
- /AIza[A-Za-z0-9\-_]{35}/g,
868
- /gsk_[A-Za-z0-9\-_]{20,}/g
869
- ];
870
- function redactSecrets(text) {
871
- let result = text;
872
- for (const pattern of SECRET_PATTERNS) result = result.replace(pattern, "[REDACTED]");
873
- return result;
874
- }
875
-
876
- // src/core/process.ts
877
- import { spawnSync as spawnSync2 } from "child_process";
878
- function sleepSync(ms) {
879
- const buffer = new SharedArrayBuffer(4);
880
- const view = new Int32Array(buffer);
881
- Atomics.wait(view, 0, 0, ms);
882
- }
883
- function processAlive(pid) {
884
- try {
885
- process.kill(pid, 0);
886
- return true;
887
- } catch (err) {
888
- return err.code === "EPERM";
889
- }
890
- }
891
- function signalProcessGroup(pid, signal) {
892
- if (process.platform === "win32") {
893
- spawnSync2("taskkill", ["/PID", String(pid), "/T", "/F"], { stdio: "ignore" });
894
- return;
895
- }
896
- try {
897
- process.kill(-pid, signal);
898
- } catch {
899
- try {
900
- process.kill(pid, signal);
901
- } catch {
902
- }
903
- }
904
- }
905
- var KILL_GRACE_MS = 400;
906
- function reapPaneProcess(pid) {
907
- if (!pid || pid <= 0 || !processAlive(pid)) return;
908
- sleepSync(KILL_GRACE_MS);
909
- if (!processAlive(pid)) return;
910
- signalProcessGroup(pid, "SIGTERM");
911
- sleepSync(KILL_GRACE_MS);
912
- if (processAlive(pid)) signalProcessGroup(pid, "SIGKILL");
913
- }
914
-
915
- // src/core/tmux.ts
916
- import { execFileSync as execFileSync2, spawnSync as spawnSync3 } from "child_process";
917
- import { createRequire } from "module";
918
- import { existsSync } from "fs";
919
- import { dirname, join } from "path";
920
- import { fileURLToPath, URL } from "url";
921
- function winmuxEntry(platform = process.platform) {
922
- if (platform !== "win32") throw new Error("winmuxEntry is only meaningful on win32");
923
- const envEntry = process.env.REEVES_WINMUX_ENTRY;
924
- if (envEntry) return envEntry;
925
- const bundled = fileURLToPath(new URL("./winmux.js", import.meta.url));
926
- if (existsSync(bundled)) return bundled;
927
- let dir = dirname(fileURLToPath(import.meta.url));
928
- while (true) {
929
- if (existsSync(join(dir, "package.json"))) return join(dir, "dist", "winmux.js");
930
- const parent = dirname(dir);
931
- if (parent === dir) return bundled;
932
- dir = parent;
933
- }
934
- }
935
- function tmuxCommand(platform = process.platform) {
936
- if (platform === "win32") {
937
- return { file: process.execPath, prefix: [winmuxEntry(platform)] };
938
- }
939
- return { file: "tmux", prefix: [] };
940
- }
941
- function execTmux(args, options = {}) {
942
- const cmd = tmuxCommand();
943
- return execFileSync2(cmd.file, [...cmd.prefix, ...args], { encoding: "utf8", ...options });
944
- }
945
- function spawnTmux(args, options = {}) {
946
- const cmd = tmuxCommand();
947
- return spawnSync3(cmd.file, [...cmd.prefix, ...args], options);
948
- }
949
- var realDriver = {
950
- tmux(args, input) {
951
- return execTmux(args, {
952
- input,
953
- stdio: input === void 0 ? ["ignore", "pipe", "pipe"] : ["pipe", "pipe", "pipe"]
954
- }).trim();
955
- },
956
- delay(fn, ms) {
957
- setTimeout(fn, ms);
958
- }
959
- };
960
- var STALE_WINDOW_ERROR = "agent window no longer exists (tmux server may have restarted)";
961
- function exactSession(session) {
962
- return `=${session}`;
963
- }
964
- function tmuxAvailable(platform = process.platform) {
965
- if (platform === "win32") {
966
- const entry = winmuxEntry(platform);
967
- if (!existsSync(entry)) return false;
968
- const requireFrom = createRequire(import.meta.url);
969
- try {
970
- requireFrom.resolve("@lydell/node-pty");
971
- } catch {
972
- return false;
973
- }
974
- try {
975
- requireFrom.resolve("@xterm/headless");
976
- } catch {
977
- return false;
978
- }
979
- return true;
980
- }
981
- try {
982
- const cmd = tmuxCommand(platform);
983
- const result = spawnSync3(cmd.file, [...cmd.prefix, "-V"], { stdio: "ignore" });
984
- return result.status === 0;
985
- } catch {
986
- return false;
987
- }
988
- }
989
- function tmuxVersion() {
990
- try {
991
- return execTmux(["-V"]).trim();
992
- } catch {
993
- return null;
994
- }
995
- }
996
- function sessionExists(session) {
997
- if (!session) return false;
998
- try {
999
- const result = spawnTmux(["has-session", "-t", exactSession(session)], { stdio: "ignore" });
1000
- return result.status === 0;
1001
- } catch {
1002
- return false;
1003
- }
1004
- }
1005
- function targetExists(target, session) {
1006
- if (!target || !session) return false;
1007
- try {
1008
- const args = target.startsWith("%") ? ["list-panes", "-s", "-t", exactSession(session), "-F", "#{pane_id}"] : ["list-windows", "-t", exactSession(session), "-F", "#{window_id}"];
1009
- const result = spawnTmux(args, { encoding: "utf8" });
1010
- const stdout = typeof result.stdout === "string" ? result.stdout : "";
1011
- return result.status === 0 && stdout.split("\n").some((line) => line.trim() === target);
1012
- } catch {
1013
- return false;
1014
- }
1015
- }
1016
- function listSessions() {
1017
- try {
1018
- return execTmux(["list-sessions", "-F", "#{session_name} #{session_attached} #{session_group} #{session_group_list} #{session_created}"]).split("\n").map((line) => line.trim()).filter(Boolean).map((row) => {
1019
- const [name = "", attached = "0", group = "", groupList = "", created = "0"] = row.split(" ");
1020
- return {
1021
- name,
1022
- attached: attached !== "0",
1023
- group,
1024
- groupList: groupList.split(",").filter(Boolean),
1025
- createdSec: Number.parseInt(created, 10) || 0
1026
- };
1027
- });
1028
- } catch {
1029
- return [];
1030
- }
1031
- }
1032
- function sessionAttached(session) {
1033
- try {
1034
- const out = execTmux(["display-message", "-p", "-t", exactSession(session), "#{session_attached}"]).trim();
1035
- return out !== "0" && out !== "";
1036
- } catch {
1037
- return true;
1038
- }
1039
- }
1040
- function killSession(session) {
1041
- try {
1042
- spawnTmux(["kill-session", "-t", exactSession(session)], { stdio: "ignore" });
1043
- } catch {
1044
- }
1045
- }
1046
- function allWindowIds() {
1047
- try {
1048
- return new Set(
1049
- execTmux(["list-windows", "-a", "-F", "#{session_name} #{window_id}"]).split("\n").map((line) => line.trim()).filter(Boolean).map((row) => {
1050
- const [session = "", id = ""] = row.split(" ");
1051
- return `${session}\0${id}`;
1052
- })
1053
- );
1054
- } catch {
1055
- return /* @__PURE__ */ new Set();
1056
- }
1057
- }
1058
- var RUN_SESSION_PATTERN = /^reeves-.+-[0-9a-f]{8}$/;
1059
- var VIEWER_SESSION_PATTERN = /^reevesweb_[0-9a-f]{8}$/;
1060
- function sessionInGroup(info, runSession) {
1061
- return info.group === runSession || info.groupList.includes(runSession);
1062
- }
1063
- function killGroupedViewers(runSession) {
1064
- for (const info of listSessions()) {
1065
- if (VIEWER_SESSION_PATTERN.test(info.name) && sessionInGroup(info, runSession)) {
1066
- killSession(info.name);
1067
- }
1068
- }
1069
- }
1070
- function windowIds(session) {
1071
- try {
1072
- return execTmux(["list-windows", "-t", exactSession(session), "-F", "#{window_id}"]).split("\n").map((line) => line.trim()).filter(Boolean);
1073
- } catch {
1074
- return [];
1075
- }
1076
- }
1077
- function windowByName(session, name) {
1078
- try {
1079
- const rows = execTmux(["list-windows", "-t", exactSession(session), "-F", "#{window_id} #{window_name} #{pane_current_command}"]).split("\n").map((line) => line.trim()).filter(Boolean);
1080
- for (const row of rows) {
1081
- const [windowId, windowName, command = ""] = row.split(" ");
1082
- if (windowId && windowName === name) return { id: windowId, command };
1083
- }
1084
- } catch {
1085
- }
1086
- return null;
1087
- }
1088
- function windowInSession(driver, session, windowId) {
1089
- if (!session || !windowId) return false;
1090
- try {
1091
- return driver.tmux(["list-windows", "-t", exactSession(session), "-F", "#{window_id}"]).split("\n").some((line) => line.trim() === windowId);
1092
- } catch {
1093
- return false;
1094
- }
1095
- }
1096
- function paneInSession(driver, session, paneId) {
1097
- if (!session || !paneId) return false;
1098
- try {
1099
- return driver.tmux(["list-panes", "-s", "-t", exactSession(session), "-F", "#{pane_id}"]).split("\n").some((line) => line.trim() === paneId);
1100
- } catch {
1101
- return false;
1102
- }
1103
- }
1104
-
1105
- // src/core/runs.ts
1106
- function stateRoot() {
1107
- return process.env.REEVES_REGISTRY || join2(homedir(), ".reeves");
1108
- }
1109
- function runsDir() {
1110
- return join2(stateRoot(), "runs");
1111
- }
1112
- function historyDir() {
1113
- return join2(stateRoot(), "history", "runs");
1114
- }
1115
- function runDir(runId) {
1116
- return join2(runsDir(), runId);
1117
- }
1118
- function agentsDir(runId) {
1119
- return join2(runDir(runId), "agents");
1120
- }
1121
- function runPath(runId) {
1122
- return join2(runDir(runId), "run.json");
1123
- }
1124
- function agentPath(runId, agentId) {
1125
- return join2(agentsDir(runId), `${agentId}.json`);
1126
- }
1127
- function runHistoryPath(runId) {
1128
- return join2(historyDir(), `${runId}.json`);
1129
- }
1130
- function nowIso() {
1131
- return (/* @__PURE__ */ new Date()).toISOString();
1132
- }
1133
- function nowMs() {
1134
- return Date.now();
1135
- }
1136
- function sleepSync2(ms) {
1137
- Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
1138
- }
1139
- function withRunsLock(fn) {
1140
- mkdirSync(stateRoot(), { recursive: true });
1141
- const lockPath = join2(stateRoot(), ".runs.lock");
1142
- const staleMs = 5e3;
1143
- const deadline = Date.now() + staleMs;
1144
- while (true) {
1145
- try {
1146
- const fd = openSync(lockPath, "wx", 384);
1147
- try {
1148
- writeFileSync(fd, JSON.stringify({ pid: process.pid, created_at: nowIso() }));
1149
- } finally {
1150
- closeSync(fd);
1151
- }
1152
- break;
1153
- } catch {
1154
- try {
1155
- const age = Date.now() - statSync(lockPath).mtimeMs;
1156
- if (age > staleMs) unlinkSync(lockPath);
1157
- } catch {
1158
- }
1159
- if (Date.now() > deadline) throw new Error(`Timed out waiting for runs lock: ${lockPath}`);
1160
- sleepSync2(25);
1161
- }
1162
- }
1163
- try {
1164
- return fn();
1165
- } finally {
1166
- try {
1167
- unlinkSync(lockPath);
1168
- } catch {
1169
- }
1170
- }
1171
- }
1172
- function atomicWriteJson(path, data) {
1173
- mkdirSync(dirname2(path), { recursive: true });
1174
- const tmpPath = `${path}.tmp`;
1175
- writeFileSync(tmpPath, JSON.stringify(data, null, 2), "utf-8");
1176
- chmodSync(tmpPath, 384);
1177
- renameSync(tmpPath, path);
1178
- }
1179
- function normalizeTaskStatus(value) {
1180
- if (value === "queued" || value === "working" || value === "done" || value === "failed" || value === "blocked") return value;
1181
- return "queued";
1182
- }
1183
- function normalizePermissions(value) {
1184
- return value === "skip" ? "skip" : "ask";
1185
- }
1186
- function asString(value, fallback = "") {
1187
- return typeof value === "string" ? value : fallback;
1188
- }
1189
- function fallbackRunName(id) {
1190
- return id ? `Run ${id.slice(0, 8)}` : "Untitled run";
1191
- }
1192
- function asNullableString(value) {
1193
- return typeof value === "string" ? value : null;
1194
- }
1195
- function normalizeInbox(value) {
1196
- if (!Array.isArray(value)) return [];
1197
- return value.filter((item) => typeof item === "object" && item !== null).map((item) => ({
1198
- id: asString(item.id, randomUUID()),
1199
- from_id: asString(item.from_id),
1200
- text: asString(item.text),
1201
- sent_at: asString(item.sent_at, nowIso()),
1202
- read: typeof item.read === "boolean" ? item.read : false
1203
- }));
1204
- }
1205
- function normalizeRun(raw) {
1206
- const id = asString(raw.id);
1207
- const run = {
1208
- id,
1209
- name: asString(raw.name).trim() || fallbackRunName(id),
1210
- status: raw.status === "ended" ? "ended" : "running",
1211
- tmux_session: asString(raw.tmux_session),
1212
- reeves_window_id: asString(raw.reeves_window_id),
1213
- reeves_pane_id: asString(raw.reeves_pane_id),
1214
- root_agent_id: asString(raw.root_agent_id),
1215
- working_dir: asString(raw.working_dir),
1216
- preset_name: asNullableString(raw.preset_name),
1217
- started_at: asString(raw.started_at, nowIso()),
1218
- ended_at: asNullableString(raw.ended_at)
1219
- };
1220
- const reevesSession = asString(raw.reeves_session);
1221
- if (reevesSession) run.reeves_session = reevesSession;
1222
- return run;
1223
- }
1224
- function normalizeRunHistory(raw) {
1225
- return {
1226
- id: asString(raw.id),
1227
- name: asString(raw.name).trim() || fallbackRunName(asString(raw.id)),
1228
- status: raw.status === "stale" ? "stale" : "ended",
1229
- working_dir: asString(raw.working_dir),
1230
- started_at: asString(raw.started_at, nowIso()),
1231
- ended_at: asNullableString(raw.ended_at),
1232
- archived_at: asString(raw.archived_at, nowIso()),
1233
- agent_count: typeof raw.agent_count === "number" && Number.isFinite(raw.agent_count) ? Math.max(0, Math.floor(raw.agent_count)) : 0,
1234
- root_provider: isProvider(raw.root_provider) ? raw.root_provider : null
1235
- };
1236
- }
1237
- function normalizeAgent(raw) {
1238
- const id = asString(raw.id);
1239
- return {
1240
- id,
1241
- run_id: asString(raw.run_id),
1242
- nickname: asString(raw.nickname, id),
1243
- provider: isProvider(raw.provider) ? raw.provider : "cc",
1244
- model: asString(raw.model),
1245
- role: raw.role === "worker" ? "worker" : "root",
1246
- working_dir: asString(raw.working_dir),
1247
- task: asString(raw.task),
1248
- task_status: normalizeTaskStatus(raw.task_status),
1249
- task_note: asString(raw.task_note),
1250
- tmux_session: asString(raw.tmux_session),
1251
- tmux_window_id: asString(raw.tmux_window_id),
1252
- tmux_pane_id: asString(raw.tmux_pane_id),
1253
- pane_pid: typeof raw.pane_pid === "number" && raw.pane_pid > 0 ? raw.pane_pid : null,
1254
- rc_enabled: typeof raw.rc_enabled === "boolean" ? raw.rc_enabled : false,
1255
- permissions: normalizePermissions(raw.permissions),
1256
- headless: raw.headless === true,
1257
- inbox: normalizeInbox(raw.inbox),
1258
- last_seen: typeof raw.last_seen === "number" ? raw.last_seen : 0,
1259
- started_at: asString(raw.started_at, nowIso()),
1260
- ended_at: asNullableString(raw.ended_at)
1261
- };
1262
- }
1263
- function redactAgent(agent) {
1264
- return {
1265
- ...agent,
1266
- task: redactSecrets(agent.task),
1267
- task_note: redactSecrets(agent.task_note),
1268
- inbox: agent.inbox.map((message) => ({ ...message, text: redactSecrets(message.text) }))
1269
- };
1270
- }
1271
- function writeRunUnlocked(run) {
1272
- const path = runPath(run.id);
1273
- atomicWriteJson(path, run);
1274
- return path;
1275
- }
1276
- function readRunUnlocked(runId) {
1277
- try {
1278
- const raw = readFileSync(runPath(runId), "utf-8");
1279
- return normalizeRun(JSON.parse(raw));
1280
- } catch {
1281
- throw new Error(`Run not found: ${runId}`);
1282
- }
1283
- }
1284
- function writeAgentUnlocked(agent) {
1285
- const path = agentPath(agent.run_id, agent.id);
1286
- atomicWriteJson(path, redactAgent(agent));
1287
- return path;
1288
- }
1289
- function writeRunHistoryUnlocked(record) {
1290
- const path = runHistoryPath(record.id);
1291
- atomicWriteJson(path, record);
1292
- return path;
1293
- }
1294
- function readAgentUnlocked(runId, agentId) {
1295
- try {
1296
- return normalizeAgent(JSON.parse(readFileSync(agentPath(runId, agentId), "utf-8")));
1297
- } catch {
1298
- throw new Error(`Agent not found: ${agentId}`);
1299
- }
1300
- }
1301
- function writeRun(run) {
1302
- return withRunsLock(() => writeRunUnlocked(run));
1303
- }
1304
- function readRun(runId) {
1305
- return readRunUnlocked(runId);
1306
- }
1307
- function updateRun(runId, patch) {
1308
- withRunsLock(() => {
1309
- writeRunUnlocked({ ...readRunUnlocked(runId), ...patch });
1310
- });
1311
- }
1312
- function isRunEnded(run) {
1313
- return run.status === "ended" || run.ended_at !== null;
1314
- }
1315
- function listRunsUnlocked(includeEnded = false) {
1316
- let entries;
1317
- try {
1318
- entries = readdirSync(runsDir());
1319
- } catch {
1320
- return [];
1321
- }
1322
- const runs = [];
1323
- for (const entry of entries) {
1324
- if (!existsSync2(runPath(entry))) continue;
1325
- try {
1326
- const run = readRunUnlocked(entry);
1327
- if (!includeEnded && isRunEnded(run)) continue;
1328
- runs.push(run);
1329
- } catch {
1330
- }
1331
- }
1332
- return runs.sort((a, b) => new Date(b.started_at).getTime() - new Date(a.started_at).getTime());
1333
- }
1334
- function listRunHistoryUnlocked() {
1335
- let entries;
1336
- try {
1337
- entries = readdirSync(historyDir());
1338
- } catch {
1339
- return [];
1340
- }
1341
- const history = [];
1342
- for (const entry of entries) {
1343
- if (!entry.endsWith(".json")) continue;
1344
- try {
1345
- history.push(normalizeRunHistory(JSON.parse(readFileSync(join2(historyDir(), entry), "utf-8"))));
1346
- } catch {
1347
- }
1348
- }
1349
- return history.sort((a, b) => new Date(b.archived_at).getTime() - new Date(a.archived_at).getTime());
1350
- }
1351
- function listRuns() {
1352
- return listRunsUnlocked();
1353
- }
1354
- function latestActiveRun() {
1355
- const active = listRuns();
1356
- if (active.length === 0) return null;
1357
- return active.reduce((latest, run) => run.started_at > latest.started_at ? run : latest);
1358
- }
1359
- function listRunHistory() {
1360
- return listRunHistoryUnlocked();
1361
- }
1362
- function removeRun(runId) {
1363
- withRunsLock(() => {
1364
- rmSync(runDir(runId), { recursive: true, force: true });
1365
- });
1366
- }
1367
- function deleteAgent(agentId) {
1368
- return withRunsLock(() => {
1369
- const runs = listRunsUnlocked();
1370
- for (const run of runs) {
1371
- try {
1372
- const agent = readAgentUnlocked(run.id, agentId);
1373
- if (!agent.ended_at) throw new Error("Stop agent before deleting it");
1374
- rmSync(agentPath(run.id, agent.id), { force: true });
1375
- return agent;
1376
- } catch (err) {
1377
- if (err instanceof Error && err.message === "Stop agent before deleting it") throw err;
1378
- }
1379
- }
1380
- throw new Error(`Agent not found: ${agentId}`);
1381
- });
1382
- }
1383
- function deleteRunHistory(runId) {
1384
- withRunsLock(() => {
1385
- rmSync(runHistoryPath(runId), { force: true });
1386
- });
1387
- }
1388
- function computeRunStatus(run, tmuxSessionExists = true) {
1389
- if (run.status === "ended" || run.ended_at !== null) return "ended";
1390
- return tmuxSessionExists ? "running" : "stale";
1391
- }
1392
- function writeAgent(agent) {
1393
- return withRunsLock(() => writeAgentUnlocked(agent));
1394
- }
1395
- function readAgent(runId, agentId) {
1396
- return readAgentUnlocked(runId, agentId);
1397
- }
1398
- function updateAgent(runId, agentId, patch) {
1399
- withRunsLock(() => {
1400
- writeAgentUnlocked({ ...readAgentUnlocked(runId, agentId), ...patch });
1401
- });
1402
- }
1403
- function listAgentsForRunIds(runIds) {
1404
- const agents = [];
1405
- for (const id of runIds) {
1406
- let files;
1407
- try {
1408
- files = readdirSync(agentsDir(id));
1409
- } catch {
1410
- continue;
1411
- }
1412
- for (const file of files) {
1413
- if (!file.endsWith(".json")) continue;
1414
- try {
1415
- agents.push(readAgentUnlocked(id, file.slice(0, -5)));
1416
- } catch {
1417
- }
1418
- }
1419
- }
1420
- return agents.sort((a, b) => {
1421
- if (a.run_id !== b.run_id) return a.run_id.localeCompare(b.run_id);
1422
- if (a.role !== b.role) return a.role === "root" ? -1 : 1;
1423
- return new Date(a.started_at).getTime() - new Date(b.started_at).getTime();
1424
- });
1425
- }
1426
- function buildRunHistoryRecord(run, status) {
1427
- const agents = listAgentsForRunIds([run.id]);
1428
- const root = agents.find((agent) => agent.role === "root" && (!run.root_agent_id || agent.id === run.root_agent_id)) ?? agents.find((agent) => agent.role === "root") ?? null;
1429
- return {
1430
- id: run.id,
1431
- name: run.name,
1432
- status,
1433
- working_dir: run.working_dir,
1434
- started_at: run.started_at,
1435
- ended_at: run.ended_at,
1436
- archived_at: nowIso(),
1437
- agent_count: agents.length,
1438
- root_provider: root?.provider ?? null
1439
- };
1440
- }
1441
- function archiveAndRemoveRun(runId, status) {
1442
- return withRunsLock(() => {
1443
- const run = readRunUnlocked(runId);
1444
- const record = buildRunHistoryRecord(run, status);
1445
- writeRunHistoryUnlocked(record);
1446
- rmSync(runDir(runId), { recursive: true, force: true });
1447
- return record;
1448
- });
1449
- }
1450
- function endRunIfNoLiveAgents(runId, endedAt = nowIso()) {
1451
- return withRunsLock(() => {
1452
- const run = readRunUnlocked(runId);
1453
- if (run.status === "ended" || run.ended_at !== null) return run;
1454
- const liveAgents = listAgentsForRunIds([runId]).filter((agent) => !agent.ended_at && !agent.headless);
1455
- if (liveAgents.length > 0) return run;
1456
- const endedRun = { ...run, status: "ended", ended_at: endedAt };
1457
- writeRunUnlocked(endedRun);
1458
- return endedRun;
1459
- });
1460
- }
1461
- function listAgents(runId) {
1462
- return listAgentsForRunIds(runId ? [runId] : listRuns().map((run) => run.id));
1463
- }
1464
- function findAgent(agentId) {
1465
- for (const run of listRuns()) {
1466
- try {
1467
- return readAgentUnlocked(run.id, agentId);
1468
- } catch {
1469
- }
1470
- }
1471
- throw new Error(`Agent not found: ${agentId}`);
1472
- }
1473
- function runHasLiveTmuxTarget(run, options = {}) {
1474
- const targetExists2 = options.targetExists ?? targetExists;
1475
- const sessionExists2 = options.sessionExists ?? sessionExists;
1476
- const agents = listAgents(run.id).filter((agent) => !agent.ended_at);
1477
- const windowedAgents = agents.filter((agent) => !agent.headless && agent.tmux_window_id);
1478
- if (windowedAgents.length > 0) return windowedAgents.some((agent) => targetExists2(agent.tmux_window_id, agent.tmux_session));
1479
- return sessionExists2(run.tmux_session);
1480
- }
1481
- function autoCleanupRuns(options = {}) {
1482
- const sessionExists2 = options.sessionExists ?? sessionExists;
1483
- const targetExists2 = options.targetExists ?? targetExists;
1484
- const killSession2 = options.killSession ?? killSession;
1485
- const killViewers = options.killViewers ?? killGroupedViewers;
1486
- const tmuxAvailable2 = options.sessionExists || options.targetExists ? () => true : options.tmuxAvailable ?? tmuxAvailable;
1487
- const haveTmux = options.cleanStale === false ? false : tmuxAvailable2();
1488
- const removed = [];
1489
- const archived = [];
1490
- const runs = listRunsUnlocked(true);
1491
- const useBatch = haveTmux && !options.sessionExists && !options.targetExists && runs.length > 0;
1492
- const batchWindows = useBatch ? allWindowIds() : null;
1493
- const batchSessions = useBatch ? new Set(listSessions().map((info) => info.name)) : null;
1494
- const batchTargetExists = batchWindows ? (target, session) => batchWindows.has(`${session}\0${target}`) : void 0;
1495
- const batchSessionExists = batchSessions ? (session) => batchSessions.has(session) : void 0;
1496
- for (const run of runs) {
1497
- const isEnded = isRunEnded(run);
1498
- let isStale = false;
1499
- if (!isEnded && haveTmux) {
1500
- const looksDead = batchTargetExists && batchSessionExists ? !runHasLiveTmuxTarget(run, { sessionExists: batchSessionExists, targetExists: batchTargetExists }) : !runHasLiveTmuxTarget(run, { sessionExists: sessionExists2, targetExists: targetExists2 });
1501
- isStale = looksDead && !runHasLiveTmuxTarget(run, batchTargetExists ? {} : { sessionExists: sessionExists2, targetExists: targetExists2 });
1502
- }
1503
- if (!isEnded && !isStale) continue;
1504
- try {
1505
- if (isStale) {
1506
- killViewers(run.tmux_session);
1507
- if (sessionExists2(run.tmux_session)) {
1508
- killSession2(run.tmux_session);
1509
- for (const agent of listAgents(run.id)) {
1510
- if (!agent.ended_at && agent.pane_pid) reapPaneProcess(agent.pane_pid);
1511
- }
1512
- }
1513
- }
1514
- const record = archiveAndRemoveRun(run.id, isStale ? "stale" : "ended");
1515
- removed.push(run.id);
1516
- archived.push(record.id);
1517
- } catch {
1518
- }
1519
- }
1520
- return { removed, archived };
1521
- }
1522
-
1523
- // src/core/provider-launch.ts
1524
- import { existsSync as existsSync3, statSync as statSync2 } from "fs";
1525
- import { homedir as homedir2 } from "os";
1526
- import { join as join3 } from "path";
1527
- function expandHome(p) {
1528
- if (p === "~") return homedir2();
1529
- if (p.startsWith("~/")) return join3(homedir2(), p.slice(2));
1530
- return p;
1531
- }
1532
- function resolveWorkingDir(requested, fallback) {
1533
- if (!requested) return fallback;
1534
- const expanded = expandHome(requested.trim());
1535
- if (!expanded) return fallback;
1536
- if (existsSync3(expanded) && statSync2(expanded).isDirectory()) return expanded;
1537
- throw new Error(`Working directory does not exist: ${expanded}`);
1538
- }
1539
- function shellQuotePosix(s) {
1540
- return `'${s.replace(/'/g, "'\\''")}'`;
1541
- }
1542
- var CMD_SAFE = /^[A-Za-z0-9_\-.,:\\=:@+/]+$/;
1543
- function shellQuoteCmd(s) {
1544
- if (CMD_SAFE.test(s)) return s;
1545
- return `"${s.replace(/"/g, '""')}"`;
1546
- }
1547
- function shellQuoteFor(s, platform) {
1548
- if (platform === "win32") return shellQuoteCmd(s);
1549
- return shellQuotePosix(s);
1550
- }
1551
- function shellQuote(s) {
1552
- return shellQuoteFor(s, process.platform);
1553
- }
1554
-
1555
- // src/i18n/languages.ts
1556
- var LANGUAGES = ["en", "de", "fr", "es", "pt", "it", "tr", "ru", "zh-Hans", "ar"];
1557
- var LANGUAGE_OPTIONS = [
1558
- { code: "en", flag: "\u{1F1FA}\u{1F1F8}", name: "English", nativeName: "English", dir: "ltr" },
1559
- { code: "de", flag: "\u{1F1E9}\u{1F1EA}", name: "German", nativeName: "Deutsch", dir: "ltr" },
1560
- { code: "fr", flag: "\u{1F1EB}\u{1F1F7}", name: "French", nativeName: "Fran\xE7ais", dir: "ltr" },
1561
- { code: "es", flag: "\u{1F1EA}\u{1F1F8}", name: "Spanish", nativeName: "Espa\xF1ol", dir: "ltr" },
1562
- { code: "pt", flag: "\u{1F1F5}\u{1F1F9}", name: "Portuguese", nativeName: "Portugu\xEAs", dir: "ltr" },
1563
- { code: "it", flag: "\u{1F1EE}\u{1F1F9}", name: "Italian", nativeName: "Italiano", dir: "ltr" },
1564
- { code: "tr", flag: "\u{1F1F9}\u{1F1F7}", name: "Turkish", nativeName: "T\xFCrk\xE7e", dir: "ltr" },
1565
- { code: "ru", flag: "\u{1F1F7}\u{1F1FA}", name: "Russian", nativeName: "\u0420\u0443\u0441\u0441\u043A\u0438\u0439", dir: "ltr" },
1566
- { code: "zh-Hans", flag: "\u{1F1E8}\u{1F1F3}", name: "Simplified Chinese", nativeName: "\u7B80\u4F53\u4E2D\u6587", dir: "ltr" },
1567
- { code: "ar", flag: "\u{1F1F8}\u{1F1E6}", name: "Arabic", nativeName: "\u0627\u0644\u0639\u0631\u0628\u064A\u0629", dir: "rtl" }
1568
- ];
1569
- var DEFAULT_LANGUAGE = "en";
1570
- function isLanguageCode(value) {
1571
- return typeof value === "string" && LANGUAGES.includes(value);
1572
- }
1573
- function languageOption(code) {
1574
- return LANGUAGE_OPTIONS.find((option) => option.code === code) ?? LANGUAGE_OPTIONS[0];
1575
- }
1576
-
1577
- // src/core/config.ts
1578
- import { readFileSync as readFileSync2, writeFileSync as writeFileSync2, mkdirSync as mkdirSync2, renameSync as renameSync2 } from "fs";
1579
- import { homedir as homedir3 } from "os";
1580
- import { join as join4, dirname as dirname3 } from "path";
1581
- var SCHEMA_VERSION = 2;
1582
- var DEFAULT_GLOBAL = {
1583
- peek_interval_ms: 5e3,
1584
- peek_lines: 10,
1585
- max_depth: 5,
1586
- max_agents: 100,
1587
- ready_delay_ms: 5e3,
1588
- max_lifetime_ms: 0,
1589
- default_permissions: "ask",
1590
- language: DEFAULT_LANGUAGE,
1591
- web_theme: "dark"
1592
- };
1593
- function configPath() {
1594
- const base = process.env.REEVES_CONFIG;
1595
- if (base) return base;
1596
- return join4(homedir3(), ".reeves", "config.json");
1597
- }
1598
- function configExists() {
1599
- try {
1600
- readFileSync2(configPath(), "utf-8");
1601
- return true;
1602
- } catch {
1603
- return false;
1604
- }
1605
- }
1606
- function defaultConfig() {
1607
- return {
1608
- version: SCHEMA_VERSION,
1609
- global: { ...DEFAULT_GLOBAL }
1610
- };
1611
- }
1612
- function mergeDefaults(raw) {
1613
- if (typeof raw !== "object" || raw === null) return defaultConfig();
1614
- const obj = raw;
1615
- const merged = {
1616
- version: typeof obj.version === "number" ? obj.version : SCHEMA_VERSION,
1617
- global: { ...DEFAULT_GLOBAL }
1618
- };
1619
- if (typeof obj.global === "object" && obj.global !== null) {
1620
- const g = obj.global;
1621
- if (typeof g.peek_interval_ms === "number" && g.peek_interval_ms > 0) merged.global.peek_interval_ms = g.peek_interval_ms;
1622
- if (typeof g.peek_lines === "number" && g.peek_lines > 0) merged.global.peek_lines = g.peek_lines;
1623
- if (typeof g.max_depth === "number" && g.max_depth > 0) merged.global.max_depth = g.max_depth;
1624
- if (typeof g.max_agents === "number" && g.max_agents > 0) merged.global.max_agents = g.max_agents;
1625
- if (typeof g.ready_delay_ms === "number" && g.ready_delay_ms >= 0) merged.global.ready_delay_ms = g.ready_delay_ms;
1626
- if (typeof g.max_lifetime_ms === "number" && g.max_lifetime_ms >= 0) merged.global.max_lifetime_ms = g.max_lifetime_ms;
1627
- if (g.default_permissions === "skip" || g.default_permissions === "ask") merged.global.default_permissions = g.default_permissions;
1628
- if (isLanguageCode(g.language)) merged.global.language = g.language;
1629
- if (g.web_theme === "dark" || g.web_theme === "light") merged.global.web_theme = g.web_theme;
1630
- }
1631
- return merged;
1632
- }
1633
- function loadConfig() {
1634
- try {
1635
- const content = readFileSync2(configPath(), "utf-8");
1636
- return mergeDefaults(JSON.parse(content));
1637
- } catch {
1638
- return defaultConfig();
1639
- }
1640
- }
1641
- function saveConfig(cfg) {
1642
- const path = configPath();
1643
- const dir = dirname3(path);
1644
- mkdirSync2(dir, { recursive: true });
1645
- const tmp = `${path}.tmp`;
1646
- writeFileSync2(tmp, JSON.stringify(cfg, null, 2), "utf-8");
1647
- try {
1648
- renameSync2(tmp, path);
1649
- } catch {
1650
- writeFileSync2(path, JSON.stringify(cfg, null, 2), "utf-8");
1651
- }
1652
- return path;
1653
- }
1654
- var CONFIG_FIELDS = [
1655
- { key: "web_theme", kind: "web-theme", label: "web theme" },
1656
- { key: "peek_interval_ms", kind: "posint", label: "peek interval (ms)" },
1657
- { key: "peek_lines", kind: "posint", label: "peek lines" },
1658
- { key: "max_depth", kind: "posint", label: "max depth" },
1659
- { key: "max_agents", kind: "posint", label: "max agents" },
1660
- { key: "ready_delay_ms", kind: "nonneg-int", label: "ready delay (ms)" },
1661
- { key: "max_lifetime_ms", kind: "nonneg-int", label: "max agent lifetime (ms)" },
1662
- { key: "default_permissions", kind: "permissions", label: "default permissions" },
1663
- { key: "language", kind: "language", label: "language" }
1664
- ];
1665
- function configFieldSpec(key) {
1666
- const spec = CONFIG_FIELDS.find((field) => field.key === key);
1667
- if (!spec) throw new Error(`unknown config field: ${key}`);
1668
- return spec;
1669
- }
1670
- function parseConfigValue(key, raw) {
1671
- const spec = configFieldSpec(key);
1672
- if (spec.kind === "posint" || spec.kind === "nonneg-int") {
1673
- const n = Number(raw);
1674
- if (!Number.isFinite(n)) throw new Error(`${spec.label} must be a number`);
1675
- return n;
1676
- }
1677
- return raw;
1678
- }
1679
- function validateConfigField(spec, value) {
1680
- switch (spec.kind) {
1681
- case "posint":
1682
- if (typeof value !== "number" || !Number.isInteger(value) || value <= 0) throw new Error(`${spec.label} must be a positive integer`);
1683
- return value;
1684
- case "nonneg-int":
1685
- if (typeof value !== "number" || !Number.isInteger(value) || value < 0) throw new Error(`${spec.label} must be zero or a positive integer`);
1686
- return value;
1687
- case "permissions":
1688
- if (value !== "ask" && value !== "skip") throw new Error(`${spec.label} must be ask or skip`);
1689
- return value;
1690
- case "language":
1691
- if (!isLanguageCode(value)) throw new Error(`unknown language: ${String(value)}`);
1692
- return value;
1693
- case "web-theme":
1694
- if (value !== "dark" && value !== "light") throw new Error(`${spec.label} must be dark or light`);
1695
- return value;
1696
- }
1697
- }
1698
- function setConfigValues(patch) {
1699
- const cfg = loadConfig();
1700
- for (const [key, value] of Object.entries(patch)) {
1701
- const spec = configFieldSpec(key);
1702
- cfg.global[spec.key] = validateConfigField(spec, value);
1703
- }
1704
- saveConfig(cfg);
1705
- return cfg;
1706
- }
1707
-
1708
- // src/core/store.ts
1709
- import { readFileSync as readFileSync3, writeFileSync as writeFileSync3, mkdirSync as mkdirSync3, readdirSync as readdirSync2, unlinkSync as unlinkSync2, renameSync as renameSync3, existsSync as existsSync4, chmodSync as chmodSync2 } from "fs";
1710
- import { join as join5, dirname as dirname4 } from "path";
1711
- function stateDir() {
1712
- return stateRoot();
1713
- }
1714
- function presetsDir() {
1715
- return join5(stateDir(), "presets");
1716
- }
1717
- function atomicWrite(path, data) {
1718
- mkdirSync3(dirname4(path), { recursive: true });
1719
- const tmp = `${path}.tmp`;
1720
- writeFileSync3(tmp, JSON.stringify(data, null, 2), "utf-8");
1721
- chmodSync2(tmp, 384);
1722
- try {
1723
- renameSync3(tmp, path);
1724
- } catch {
1725
- writeFileSync3(path, JSON.stringify(data, null, 2), "utf-8");
1726
- }
1727
- }
1728
- function isEffort(value) {
1729
- return value === "default" || value === "low" || value === "medium" || value === "high" || value === "xhigh" || value === "max";
1730
- }
1731
- function normalizeSlot(raw, fallbackDir = "") {
1732
- const promptRaw = typeof raw.initial_prompt === "string" ? raw.initial_prompt : typeof raw.task_template === "string" ? raw.task_template : "";
1733
- return {
1734
- nickname_template: typeof raw.nickname_template === "string" ? raw.nickname_template : "agent",
1735
- provider: isProvider(raw.provider) ? raw.provider : "cc",
1736
- model: typeof raw.model === "string" ? raw.model : "",
1737
- auth_mode: raw.auth_mode === "api-key" ? "api-key" : "default",
1738
- effort: isEffort(raw.effort) ? raw.effort : "default",
1739
- initial_prompt: promptRaw,
1740
- working_dir: typeof raw.working_dir === "string" ? raw.working_dir : fallbackDir,
1741
- permissions: raw.permissions === "skip" ? "skip" : "ask",
1742
- rc_enabled: typeof raw.rc_enabled === "boolean" ? raw.rc_enabled : false
1743
- };
1744
- }
1745
- function normalizePreset(raw) {
1746
- if (typeof raw !== "object" || raw === null) return null;
1747
- const obj = raw;
1748
- const legacyDir = typeof obj.working_dir_pattern === "string" ? obj.working_dir_pattern : "";
1749
- const rootRaw = typeof obj.root === "object" && obj.root !== null ? obj.root : {};
1750
- const workersRaw = Array.isArray(obj.workers) ? obj.workers : [];
1751
- return {
1752
- name: typeof obj.name === "string" ? obj.name : "preset",
1753
- description: typeof obj.description === "string" ? obj.description : "",
1754
- root: normalizeSlot(rootRaw, legacyDir),
1755
- workers: workersRaw.filter((w) => typeof w === "object" && w !== null).map((w) => normalizeSlot(w, legacyDir)),
1756
- working_dir_pattern: legacyDir || void 0,
1757
- created_at: typeof obj.created_at === "string" ? obj.created_at : (/* @__PURE__ */ new Date()).toISOString(),
1758
- updated_at: typeof obj.updated_at === "string" ? obj.updated_at : (/* @__PURE__ */ new Date()).toISOString()
1759
- };
1760
- }
1761
- function listPresets() {
1762
- const dir = presetsDir();
1763
- if (!existsSync4(dir)) return [];
1764
- try {
1765
- return readdirSync2(dir).filter((f) => f.endsWith(".json")).map((f) => {
1766
- try {
1767
- return normalizePreset(JSON.parse(readFileSync3(join5(dir, f), "utf-8")));
1768
- } catch {
1769
- return null;
1770
- }
1771
- }).filter((t) => t !== null);
1772
- } catch {
1773
- return [];
1774
- }
1775
- }
1776
- function loadPreset(name) {
1777
- try {
1778
- return normalizePreset(JSON.parse(readFileSync3(join5(presetsDir(), `${name}.json`), "utf-8")));
1779
- } catch {
1780
- return null;
1781
- }
1782
- }
1783
- function savePreset(tree) {
1784
- atomicWrite(join5(presetsDir(), `${tree.name}.json`), tree);
1785
- }
1786
- function deletePreset(name) {
1787
- try {
1788
- unlinkSync2(join5(presetsDir(), `${name}.json`));
1789
- } catch {
1790
- }
1791
- }
1792
- function sanitizePresetName(raw) {
1793
- return raw.trim().replace(/[^a-zA-Z0-9_-]/g, "-").replace(/-+/g, "-").replace(/^-|-$/g, "").slice(0, 64);
1794
- }
1795
- function agentToSlot(agent) {
1796
- return {
1797
- nickname_template: agent.nickname,
1798
- provider: agent.provider,
1799
- model: agent.model,
1800
- auth_mode: "default",
1801
- effort: "default",
1802
- initial_prompt: agent.task,
1803
- working_dir: agent.working_dir,
1804
- permissions: agent.permissions,
1805
- rc_enabled: agent.rc_enabled
1806
- };
1807
- }
1808
- function savePresetFromRun(runId, name, description = "") {
1809
- const presetName = sanitizePresetName(name);
1810
- if (!presetName) throw new Error("preset name is required");
1811
- const run = readRun(runId);
1812
- const agents = listAgents(run.id).filter((agent) => !agent.headless);
1813
- if (agents.length === 0) throw new Error("run has no agents to save as a preset");
1814
- const root = agents.find((agent) => agent.role === "root") ?? agents[0];
1815
- const workers = agents.filter((agent) => agent !== root);
1816
- const existing = loadPreset(presetName);
1817
- const now = nowIso();
1818
- const tree = {
1819
- name: presetName,
1820
- description,
1821
- root: agentToSlot(root),
1822
- workers: workers.map(agentToSlot),
1823
- created_at: existing?.created_at ?? now,
1824
- updated_at: now
1825
- };
1826
- savePreset(tree);
1827
- return tree;
1828
- }
1829
-
1830
- // src/utils/display.ts
1831
- var MODEL_COLORS = {
1832
- default: "#9b9488",
1833
- // CLI default or unset model
1834
- claude: "#e0a06f",
1835
- // Claude family
1836
- openai: "#72b7d6",
1837
- // OpenAI family
1838
- deepseek: "#7ac8bc",
1839
- // DeepSeek family
1840
- qwen: "#d1a25d",
1841
- // Qwen family
1842
- kimi: "#d0c268",
1843
- // Kimi family
1844
- local: "#92b37a",
1845
- // local/open model family
1846
- other: "#9ca8bd"
1847
- // known provider, unclassified model
1848
- };
1849
- var PROVIDER_DISPLAY_NAMES = Object.fromEntries(
1850
- PROVIDER_DEFS.map((def) => [def.id, def.displayName])
1851
- );
1852
- function providerDisplayName(provider) {
1853
- return PROVIDER_DISPLAY_NAMES[provider] ?? provider;
1854
- }
1855
- function providerColor(p) {
1856
- return PROVIDER_REGISTRY[p]?.color ?? "gray";
1857
- }
1858
- function modelColor(model, provider) {
1859
- const lower = model.trim().toLowerCase();
1860
- if (!lower) return MODEL_COLORS.default;
1861
- if (lower.includes("claude") || lower.includes("sonnet") || lower.includes("opus") || lower.includes("haiku")) return MODEL_COLORS.claude;
1862
- if (lower.includes("gpt") || lower.includes("codex") || /\bo[134]\b/.test(lower)) return MODEL_COLORS.openai;
1863
- if (lower.includes("deepseek")) return MODEL_COLORS.deepseek;
1864
- if (lower.includes("qwen")) return MODEL_COLORS.qwen;
1865
- if (lower.includes("kimi") || lower.includes("moonshot")) return MODEL_COLORS.kimi;
1866
- if (lower.includes("llama") || lower.includes("mistral") || lower.includes("mixtral") || lower.includes("ollama") || lower.includes("lmstudio") || lower.includes("local")) return MODEL_COLORS.local;
1867
- if (provider === "cc") return MODEL_COLORS.claude;
1868
- if (provider === "codex") return MODEL_COLORS.openai;
1869
- if (provider === "deepseek") return MODEL_COLORS.deepseek;
1870
- if (provider === "qwen") return MODEL_COLORS.qwen;
1871
- if (provider === "kimi") return MODEL_COLORS.kimi;
1872
- return MODEL_COLORS.other;
1873
- }
1874
- function modelBadgeLabel(model) {
1875
- const value = model.trim();
1876
- if (!value) return "default";
1877
- const slashIdx = value.lastIndexOf("/");
1878
- const label = slashIdx >= 0 && slashIdx < value.length - 1 ? value.slice(slashIdx + 1) : value;
1879
- return truncateLabel(label, 24);
1880
- }
1881
- function truncateLabel(label, max) {
1882
- if (label.length <= max) return label;
1883
- return `${label.slice(0, Math.max(1, max - 3))}...`;
1884
- }
1885
-
1886
- // src/core/runtime.ts
1887
- import { randomUUID as randomUUID2 } from "crypto";
1888
- import stripAnsi from "strip-ansi";
1889
- var ALLOWED_KEYS = [
1890
- "enter",
1891
- "escape",
1892
- "backspace",
1893
- "tab",
1894
- "space",
1895
- "up",
1896
- "down",
1897
- "left",
1898
- "right",
1899
- "ctrl-c"
1900
- ];
1901
- var POST_PASTE_ENTER_DELAY_MS = 1e3;
1902
- var STARTUP_READY_POLL_MS = 1e3;
1903
- var STARTUP_READY_TIMEOUT_MS = 2e4;
1904
- var lastPasteAtByPane = /* @__PURE__ */ new Map();
1905
- function sleepSync3(ms) {
1906
- const buffer = new SharedArrayBuffer(4);
1907
- const view = new Int32Array(buffer);
1908
- Atomics.wait(view, 0, 0, ms);
1909
- }
1910
- function killViewerSessions(driver, runSession) {
1911
- let rows;
1912
- try {
1913
- rows = driver.tmux(["list-sessions", "-F", "#{session_name} #{session_group} #{session_group_list}"]);
1914
- } catch {
1915
- return;
1916
- }
1917
- for (const row of rows.split("\n")) {
1918
- const [name = "", group = "", groupList = ""] = row.trim().split(" ");
1919
- if (!VIEWER_SESSION_PATTERN.test(name)) continue;
1920
- if (!sessionInGroup({ group, groupList: groupList.split(",").filter(Boolean) }, runSession)) continue;
1921
- try {
1922
- driver.tmux(["kill-session", "-t", `=${name}`]);
1923
- } catch {
1924
- }
1925
- }
1926
- }
1927
- function waitAfterPaste(driver) {
1928
- if (driver === realDriver) sleepSync3(POST_PASTE_ENTER_DELAY_MS);
1929
- else driver.delay(() => {
1930
- }, POST_PASTE_ENTER_DELAY_MS);
1931
- }
1932
- function normalizePaneOutput(output) {
1933
- return stripAnsi(output).replace(/\s+/g, " ").trim().toLowerCase();
1934
- }
1935
- function paneLooksReady(output, previousOutput) {
1936
- const current = normalizePaneOutput(output);
1937
- if (!current) return false;
1938
- if (/\bready\b/.test(current)) return true;
1939
- if (current.includes("type a message") || current.includes("enter your prompt")) return true;
1940
- if (current.includes("what would you like") || current.includes("what do you want")) return true;
1941
- return !!previousOutput && current === normalizePaneOutput(previousOutput);
1942
- }
1943
- function pasteTextToPane(driver, paneId, text) {
1944
- const bufferName = `reeves_${randomUUID2().slice(0, 8)}`;
1945
- driver.tmux(["load-buffer", "-b", bufferName, "-"], text);
1946
- try {
1947
- driver.tmux(["paste-buffer", "-b", bufferName, "-t", paneId]);
1948
- } finally {
1949
- try {
1950
- driver.tmux(["delete-buffer", "-b", bufferName]);
1951
- } catch {
1952
- }
1953
- }
1954
- }
1955
- function sanitizeName(raw) {
1956
- const cleaned = raw.trim().replace(/[^a-zA-Z0-9_-]/g, "-").replace(/-+/g, "-").slice(0, 40);
1957
- return cleaned || "run";
1958
- }
1959
- function tmuxWindowName(provider, nickname) {
1960
- return sanitizeName(nickname || provider).slice(0, 64);
1961
- }
1962
- function tmuxRunSessionName(runId, rawName) {
1963
- return `reeves-${sanitizeName(rawName).slice(0, 24)}-${runId.slice(0, 8)}`.slice(0, 64);
1964
- }
1965
- function childProcessOutput(err) {
1966
- if (typeof err !== "object" || err === null) return "";
1967
- const maybe = err;
1968
- const stderr = Buffer.isBuffer(maybe.stderr) ? maybe.stderr.toString("utf8").trim() : "";
1969
- if (stderr) return stderr;
1970
- const stdout = Buffer.isBuffer(maybe.stdout) ? maybe.stdout.toString("utf8").trim() : "";
1971
- return stdout;
1972
- }
1973
- function parseTmuxIds(output) {
1974
- const [windowId, paneId, panePidRaw] = output.trim().split(/\s+/);
1975
- if (!windowId?.startsWith("@") || !paneId?.startsWith("%")) {
1976
- throw new Error(`Could not parse tmux ids from: ${output}`);
1977
- }
1978
- const panePid = panePidRaw === void 0 ? void 0 : Number.parseInt(panePidRaw, 10);
1979
- return { windowId, paneId, panePid: Number.isFinite(panePid) && panePid > 0 ? panePid : void 0 };
1980
- }
1981
- function readDisplayIds(driver, target) {
1982
- try {
1983
- const args = ["display-message", "-p"];
1984
- if (target) args.push("-t", target);
1985
- args.push("#{window_id} #{pane_id}");
1986
- return parseTmuxIds(driver.tmux(args));
1987
- } catch {
1988
- return null;
1989
- }
1990
- }
1991
- function requireProvider(provider, available) {
1992
- if (!isProvider(provider)) throw new Error(`Unsupported provider: ${String(provider)}`);
1993
- if (!available[provider]) throw new Error(`${providerDisplayName(provider)} not found on PATH`);
1994
- }
1995
- function pickReevesAnchor(driver) {
1996
- if (process.env.TMUX) {
1997
- try {
1998
- const sessionName = driver.tmux(["display-message", "-p", "#S"]).trim();
1999
- const ids2 = readDisplayIds(driver);
2000
- if (sessionName && ids2) {
2001
- return { sessionName, windowId: ids2.windowId, paneId: ids2.paneId };
2002
- }
2003
- } catch {
2004
- }
2005
- }
2006
- const fallbackName = "reeves";
2007
- try {
2008
- driver.tmux(["new-session", "-d", "-s", fallbackName, "-n", "reeves"]);
2009
- } catch {
2010
- }
2011
- let ids = readDisplayIds(driver, `=${fallbackName}:reeves`);
2012
- if (!ids) {
2013
- try {
2014
- driver.tmux(["new-window", "-d", "-t", `${fallbackName}:`, "-n", "reeves"]);
2015
- } catch {
2016
- }
2017
- ids = readDisplayIds(driver, `=${fallbackName}:reeves`);
2018
- }
2019
- return { sessionName: fallbackName, windowId: ids?.windowId ?? "", paneId: ids?.paneId ?? "" };
2020
- }
2021
- function createRunSessionWithReevesTab(driver, tmuxSession, reevesAnchor, workingDir) {
2022
- driver.tmux(["new-session", "-d", "-s", tmuxSession, "-n", "reeves", "-c", workingDir]);
2023
- const source = reevesAnchor.windowId || `${reevesAnchor.sessionName}:reeves`;
2024
- try {
2025
- driver.tmux(["link-window", "-k", "-s", source, "-t", `${tmuxSession}:0`]);
2026
- } catch {
2027
- }
2028
- }
2029
- function terminalShellCommand(config, permissions) {
2030
- const cmd = buildCommand({
2031
- provider: config.provider,
2032
- permissions,
2033
- model: config.model,
2034
- auth_mode: config.auth_mode,
2035
- effort: config.effort,
2036
- rc_enabled: false,
2037
- extra_args: config.extra_args
2038
- });
2039
- const joined = cmd.map(shellQuote).join(" ");
2040
- return process.platform === "win32" ? joined : `exec ${joined}`;
2041
- }
2042
- function sendDelayedStartupInput(driver, agent, config, readyDelayMs) {
2043
- const task = config.task.trim();
2044
- function sendStartupTask() {
2045
- pasteTextToPane(driver, agent.tmux_pane_id, task);
2046
- lastPasteAtByPane.set(agent.tmux_pane_id, Date.now());
2047
- waitAfterPaste(driver);
2048
- driver.tmux(["send-keys", "-t", agent.tmux_pane_id, "Enter"]);
2049
- const current = readAgent(agent.run_id, agent.id);
2050
- if (!current.ended_at && current.task_status === "queued") {
2051
- updateAgent(agent.run_id, agent.id, { task_status: "working" });
2052
- }
2053
- }
2054
- function waitForReadyThenSend(previousOutput = "", waitedMs = 0) {
2055
- try {
2056
- if (!paneInSession(driver, agent.tmux_session, agent.tmux_pane_id)) return;
2057
- const output = driver.tmux(["capture-pane", "-p", "-e", "-S", "-80", "-t", agent.tmux_pane_id]);
2058
- if (paneLooksReady(output, previousOutput) || waitedMs >= STARTUP_READY_TIMEOUT_MS) {
2059
- sendStartupTask();
2060
- return;
2061
- }
2062
- driver.delay(() => waitForReadyThenSend(output, waitedMs + STARTUP_READY_POLL_MS), STARTUP_READY_POLL_MS);
2063
- } catch {
2064
- }
2065
- }
2066
- if (!task) return;
2067
- driver.delay(() => waitForReadyThenSend(), readyDelayMs);
2068
- }
2069
- function newAgentRecord(id, runId, tmuxSession, role, config, workingDir, ids, permissions) {
2070
- return {
2071
- id,
2072
- run_id: runId,
2073
- nickname: config.nickname || (role === "root" ? providerDisplayName(config.provider) : `${providerDisplayName(config.provider)} agent`),
2074
- provider: config.provider,
2075
- model: config.model,
2076
- role,
2077
- working_dir: workingDir,
2078
- task: config.task.trim(),
2079
- task_status: "queued",
2080
- task_note: "",
2081
- tmux_session: tmuxSession,
2082
- tmux_window_id: ids.windowId,
2083
- tmux_pane_id: ids.paneId,
2084
- pane_pid: ids.panePid ?? null,
2085
- rc_enabled: false,
2086
- permissions,
2087
- inbox: [],
2088
- last_seen: nowMs(),
2089
- started_at: nowIso(),
2090
- ended_at: null
2091
- };
2092
- }
2093
- function createAgentWindow(runId, tmuxSession, role, config, inheritedWorkingDir, readyDelayMs, driver) {
2094
- const cfg = loadConfig();
2095
- const id = randomUUID2();
2096
- const workingDir = resolveWorkingDir(config.working_dir, inheritedWorkingDir);
2097
- const permissions = config.permissions ?? cfg.global.default_permissions;
2098
- const shellCommand = terminalShellCommand(config, permissions);
2099
- const nickname = config.nickname || providerDisplayName(config.provider);
2100
- const output = driver.tmux([
2101
- "new-window",
2102
- "-d",
2103
- "-P",
2104
- "-F",
2105
- "#{window_id} #{pane_id} #{pane_pid}",
2106
- "-t",
2107
- `${tmuxSession}:`,
2108
- "-n",
2109
- tmuxWindowName(config.provider, nickname),
2110
- "-c",
2111
- workingDir,
2112
- shellCommand
2113
- ]);
2114
- const agent = newAgentRecord(id, runId, tmuxSession, role, config, workingDir, parseTmuxIds(output), permissions);
2115
- writeAgent(agent);
2116
- sendDelayedStartupInput(driver, agent, config, readyDelayMs);
2117
- return agent;
2118
- }
2119
- function validateAgents(configs, available) {
2120
- for (const config of configs) requireProvider(config.provider, available);
2121
- }
2122
- function startRun(request, options = {}) {
2123
- const cfg = loadConfig();
2124
- const driver = options.driver ?? realDriver;
2125
- const available = options.available ?? detectAvailable();
2126
- const workers = request.workers ?? [];
2127
- validateAgents([request.root, ...workers], available);
2128
- const runId = randomUUID2();
2129
- const readyDelayMs = request.ready_delay_ms ?? cfg.global.ready_delay_ms;
2130
- const workingDir = resolveWorkingDir(request.working_dir, process.cwd());
2131
- const reevesAnchor = pickReevesAnchor(driver);
2132
- const tmuxSession = tmuxRunSessionName(runId, request.name);
2133
- let createdRunSession = false;
2134
- try {
2135
- createRunSessionWithReevesTab(driver, tmuxSession, reevesAnchor, workingDir);
2136
- createdRunSession = true;
2137
- const root = createAgentWindow(runId, tmuxSession, "root", request.root, workingDir, readyDelayMs, driver);
2138
- const run = {
2139
- id: runId,
2140
- name: request.name,
2141
- status: "running",
2142
- tmux_session: tmuxSession,
2143
- reeves_session: reevesAnchor.sessionName,
2144
- reeves_window_id: reevesAnchor.windowId,
2145
- reeves_pane_id: reevesAnchor.paneId,
2146
- root_agent_id: root.id,
2147
- working_dir: workingDir,
2148
- preset_name: request.preset_name ?? null,
2149
- started_at: nowIso(),
2150
- ended_at: null
2151
- };
2152
- writeRun(run);
2153
- const workerAgents = workers.map((worker) => {
2154
- return createAgentWindow(runId, tmuxSession, "worker", worker, workingDir, readyDelayMs, driver);
2155
- });
2156
- return { run, agents: [root, ...workerAgents] };
2157
- } catch (err) {
2158
- if (createdRunSession) {
2159
- try {
2160
- driver.tmux(["kill-session", "-t", tmuxSession]);
2161
- } catch {
2162
- }
2163
- }
2164
- removeRun(runId);
2165
- const detail = childProcessOutput(err) || (err instanceof Error ? err.message : "tmux returned a non-zero exit code");
2166
- throw new Error(`Failed to start run ${request.name}: ${detail}`, { cause: err });
2167
- }
2168
- }
2169
- function slotToLaunchConfig(slot) {
2170
- return {
2171
- nickname: slot.nickname_template,
2172
- provider: slot.provider,
2173
- model: slot.model,
2174
- auth_mode: slot.auth_mode,
2175
- effort: slot.effort,
2176
- task: slot.initial_prompt,
2177
- working_dir: slot.working_dir,
2178
- permissions: slot.permissions,
2179
- rc_enabled: slot.rc_enabled
2180
- };
2181
- }
2182
- function startRunFromPreset(presetName, opts = {}, options = {}) {
2183
- const tree = loadPreset(presetName);
2184
- if (!tree) throw new Error(`preset not found: ${presetName}`);
2185
- return startRun({
2186
- name: opts.name?.trim() || tree.name,
2187
- working_dir: opts.working_dir || process.cwd(),
2188
- root: slotToLaunchConfig(tree.root),
2189
- workers: tree.workers.map(slotToLaunchConfig),
2190
- preset_name: tree.name
2191
- }, options);
2192
- }
2193
- function createHeadlessHeadAgent(runId, tmuxSession, provider, workingDir) {
2194
- const cfg = loadConfig();
2195
- const agent = {
2196
- id: randomUUID2(),
2197
- run_id: runId,
2198
- nickname: providerDisplayName(provider),
2199
- provider,
2200
- model: "",
2201
- role: "root",
2202
- working_dir: workingDir,
2203
- task: "",
2204
- task_status: "working",
2205
- task_note: "",
2206
- tmux_session: tmuxSession,
2207
- tmux_window_id: "",
2208
- tmux_pane_id: "",
2209
- rc_enabled: false,
2210
- permissions: cfg.global.default_permissions,
2211
- headless: true,
2212
- inbox: [],
2213
- last_seen: nowMs(),
2214
- started_at: nowIso(),
2215
- ended_at: null
2216
- };
2217
- writeAgent(agent);
2218
- return agent;
2219
- }
2220
- function startRunWithHead(headProvider, firstWorker, options = {}) {
2221
- const cfg = loadConfig();
2222
- const driver = options.driver ?? realDriver;
2223
- const available = options.available ?? detectAvailable();
2224
- validateAgents([firstWorker], available);
2225
- const runId = randomUUID2();
2226
- const readyDelayMs = cfg.global.ready_delay_ms;
2227
- const workingDir = resolveWorkingDir(firstWorker.working_dir, process.cwd());
2228
- const reevesAnchor = pickReevesAnchor(driver);
2229
- const tmuxSession = tmuxRunSessionName(runId, providerDisplayName(headProvider));
2230
- let createdRunSession = false;
2231
- try {
2232
- createRunSessionWithReevesTab(driver, tmuxSession, reevesAnchor, workingDir);
2233
- createdRunSession = true;
2234
- const head = createHeadlessHeadAgent(runId, tmuxSession, headProvider, workingDir);
2235
- const run = {
2236
- id: runId,
2237
- name: providerDisplayName(headProvider),
2238
- status: "running",
2239
- tmux_session: tmuxSession,
2240
- reeves_session: reevesAnchor.sessionName,
2241
- reeves_window_id: reevesAnchor.windowId,
2242
- reeves_pane_id: reevesAnchor.paneId,
2243
- root_agent_id: head.id,
2244
- working_dir: workingDir,
2245
- preset_name: null,
2246
- started_at: nowIso(),
2247
- ended_at: null
2248
- };
2249
- writeRun(run);
2250
- const worker = createAgentWindow(runId, tmuxSession, "worker", firstWorker, workingDir, readyDelayMs, driver);
2251
- return { run, agents: [head, worker] };
2252
- } catch (err) {
2253
- if (createdRunSession) {
2254
- try {
2255
- driver.tmux(["kill-session", "-t", tmuxSession]);
2256
- } catch {
2257
- }
2258
- }
2259
- removeRun(runId);
2260
- const detail = childProcessOutput(err) || (err instanceof Error ? err.message : "tmux returned a non-zero exit code");
2261
- throw new Error(`Failed to start run ${providerDisplayName(headProvider)}: ${detail}`, { cause: err });
2262
- }
2263
- }
2264
- function spawnWorker(request, options = {}) {
2265
- const cfg = loadConfig();
2266
- const driver = options.driver ?? realDriver;
2267
- const available = options.available ?? detectAvailable();
2268
- requireProvider(request.provider, available);
2269
- const run = readRun(request.run_id);
2270
- if (run.status === "ended" || run.ended_at) throw new Error(`Run is ended: ${run.id}`);
2271
- return createAgentWindow(
2272
- run.id,
2273
- run.tmux_session,
2274
- "worker",
2275
- request,
2276
- run.working_dir,
2277
- request.ready_delay_ms ?? cfg.global.ready_delay_ms,
2278
- driver
2279
- );
2280
- }
2281
- function openReeves(runId, options = {}) {
2282
- const driver = options.driver ?? realDriver;
2283
- const run = readRun(runId);
2284
- const reevesSession = run.reeves_session ?? run.tmux_session;
2285
- if (!run.reeves_window_id || !windowInSession(driver, reevesSession, run.reeves_window_id)) {
2286
- throw new Error("Reeves TUI window is unavailable for this run");
2287
- }
2288
- const target = `${reevesSession}:${run.reeves_window_id}`;
2289
- try {
2290
- driver.tmux(["switch-client", "-t", target]);
2291
- } catch {
2292
- }
2293
- driver.tmux(["select-window", "-t", target]);
2294
- }
2295
- function openRunTabs(runId, options = {}) {
2296
- const driver = options.driver ?? realDriver;
2297
- const run = readRun(runId);
2298
- const target = `${run.tmux_session}:reeves`;
2299
- try {
2300
- driver.tmux(["switch-client", "-t", target]);
2301
- } catch {
2302
- }
2303
- driver.tmux(["select-window", "-t", target]);
2304
- }
2305
- function openAgent(agentId, options = {}) {
2306
- const driver = options.driver ?? realDriver;
2307
- const agent = findAgent(agentId);
2308
- if (agent.headless || !agent.tmux_window_id) throw new Error("This agent is headless - no tmux window exists");
2309
- if (!windowInSession(driver, agent.tmux_session, agent.tmux_window_id)) throw new Error(STALE_WINDOW_ERROR);
2310
- const target = `${agent.tmux_session}:${agent.tmux_window_id}`;
2311
- try {
2312
- driver.tmux(["switch-client", "-t", target]);
2313
- } catch {
2314
- }
2315
- driver.tmux(["select-window", "-t", target]);
2316
- }
2317
- function peekAgent(agentId, lines = 10, options = {}) {
2318
- const driver = options.driver ?? realDriver;
2319
- const n = Number.isFinite(lines) && lines > 0 ? Math.floor(lines) : 10;
2320
- try {
2321
- const agent = findAgent(agentId);
2322
- if (agent.headless || !agent.tmux_pane_id) return "(headless agent - no output)";
2323
- if (!paneInSession(driver, agent.tmux_session, agent.tmux_pane_id)) return "";
2324
- let output = driver.tmux(["capture-pane", "-p", "-e", "-S", String(-n), "-t", agent.tmux_pane_id]);
2325
- if (!output.trim()) {
2326
- try {
2327
- output = driver.tmux(["capture-pane", "-p", "-e", "-a", "-S", String(-n), "-t", agent.tmux_pane_id]);
2328
- } catch {
2329
- }
2330
- }
2331
- return redactSecrets(stripAnsi(output).trim());
2332
- } catch {
2333
- return "";
2334
- }
2335
- }
2336
- function sendText(agentId, text, options = {}) {
2337
- const driver = options.driver ?? realDriver;
2338
- const agent = findAgent(agentId);
2339
- if (agent.headless || !agent.tmux_pane_id) throw new Error("This agent is headless - no tmux pane exists");
2340
- if (!paneInSession(driver, agent.tmux_session, agent.tmux_pane_id)) throw new Error(STALE_WINDOW_ERROR);
2341
- pasteTextToPane(driver, agent.tmux_pane_id, text);
2342
- lastPasteAtByPane.set(agent.tmux_pane_id, Date.now());
2343
- if (!agent.ended_at && agent.task_status === "queued") updateAgent(agent.run_id, agent.id, { task_status: "working" });
2344
- }
2345
- function tmuxKey(key) {
2346
- if (key === "enter") return "Enter";
2347
- if (key === "escape") return "Escape";
2348
- if (key === "backspace") return "BSpace";
2349
- if (key === "tab") return "Tab";
2350
- if (key === "space") return "Space";
2351
- if (key === "up") return "Up";
2352
- if (key === "down") return "Down";
2353
- if (key === "left") return "Left";
2354
- if (key === "right") return "Right";
2355
- return "C-c";
2356
- }
2357
- function sendKey(agentId, key, options = {}) {
2358
- const driver = options.driver ?? realDriver;
2359
- const agent = findAgent(agentId);
2360
- if (agent.headless || !agent.tmux_pane_id) throw new Error("This agent is headless - no tmux pane exists");
2361
- if (!ALLOWED_KEYS.includes(key)) throw new Error(`Unsupported key: ${String(key)}`);
2362
- if (!paneInSession(driver, agent.tmux_session, agent.tmux_pane_id)) throw new Error(STALE_WINDOW_ERROR);
2363
- if (key === "enter") {
2364
- const lastPasteAt = lastPasteAtByPane.get(agent.tmux_pane_id) ?? 0;
2365
- const remaining = POST_PASTE_ENTER_DELAY_MS - (Date.now() - lastPasteAt);
2366
- if (remaining > 0) {
2367
- if (driver === realDriver) sleepSync3(remaining);
2368
- else driver.delay(() => {
2369
- }, remaining);
2370
- }
2371
- }
2372
- driver.tmux(["send-keys", "-t", agent.tmux_pane_id, tmuxKey(key)]);
2373
- if (!agent.ended_at && agent.task_status === "queued") updateAgent(agent.run_id, agent.id, { task_status: "working" });
2374
- }
2375
- function interrupt(agentId, options = {}) {
2376
- sendKey(agentId, "ctrl-c", options);
2377
- }
2378
- function killAgent(agentId, options = {}) {
2379
- const driver = options.driver ?? realDriver;
2380
- const agent = findAgent(agentId);
2381
- const run = readRun(agent.run_id);
2382
- const hadWindow = windowInSession(driver, agent.tmux_session, agent.tmux_window_id);
2383
- if (hadWindow) {
2384
- try {
2385
- driver.tmux(["kill-window", "-t", agent.tmux_window_id]);
2386
- } catch {
2387
- }
2388
- reapPaneProcess(agent.pane_pid);
2389
- }
2390
- lastPasteAtByPane.delete(agent.tmux_pane_id);
2391
- const endedAt = nowIso();
2392
- updateAgent(agent.run_id, agent.id, { ended_at: endedAt, task_status: "done" });
2393
- const updatedAgent = readAgent(agent.run_id, agent.id);
2394
- const endedRun = endRunIfNoLiveAgents(agent.run_id, endedAt);
2395
- if (endedRun.status === "ended" || endedRun.ended_at !== null) {
2396
- const runOwnsSession = !!run.reeves_session && run.reeves_session !== run.tmux_session;
2397
- if (runOwnsSession) {
2398
- killViewerSessions(driver, run.tmux_session);
2399
- try {
2400
- driver.tmux(["kill-session", "-t", `=${run.tmux_session}`]);
2401
- } catch {
2402
- }
2403
- }
2404
- archiveAndRemoveRun(run.id, "ended");
2405
- }
2406
- return updatedAgent;
2407
- }
2408
- function stopRun(runId, options = {}) {
2409
- const driver = options.driver ?? realDriver;
2410
- const run = readRun(runId);
2411
- const endedAt = nowIso();
2412
- const runOwnsSession = !!run.reeves_session && run.reeves_session !== run.tmux_session;
2413
- let sessionKilled = false;
2414
- if (runOwnsSession) {
2415
- killViewerSessions(driver, run.tmux_session);
2416
- try {
2417
- driver.tmux(["kill-session", "-t", `=${run.tmux_session}`]);
2418
- sessionKilled = true;
2419
- } catch {
2420
- }
2421
- }
2422
- for (const agent of listAgents(run.id)) {
2423
- if (agent.ended_at) continue;
2424
- if (!runOwnsSession && windowInSession(driver, agent.tmux_session, agent.tmux_window_id)) {
2425
- try {
2426
- driver.tmux(["kill-window", "-t", agent.tmux_window_id]);
2427
- } catch {
2428
- }
2429
- reapPaneProcess(agent.pane_pid);
2430
- } else if (sessionKilled) {
2431
- reapPaneProcess(agent.pane_pid);
2432
- }
2433
- lastPasteAtByPane.delete(agent.tmux_pane_id);
2434
- updateAgent(run.id, agent.id, { ended_at: endedAt });
2435
- }
2436
- const endedRun = { ...run, status: "ended", ended_at: endedAt };
2437
- updateRun(run.id, { status: endedRun.status, ended_at: endedRun.ended_at });
2438
- archiveAndRemoveRun(run.id, "ended");
2439
- return endedRun;
2440
- }
2441
- function openTmuxTarget(id, options = {}) {
2442
- const driver = options.driver ?? realDriver;
2443
- let session;
2444
- let window;
2445
- let label;
2446
- try {
2447
- const run = readRun(id);
2448
- session = run.tmux_session;
2449
- window = "reeves";
2450
- label = run.name;
2451
- } catch {
2452
- try {
2453
- const agent = findAgent(id);
2454
- session = agent.tmux_session;
2455
- window = agent.tmux_window_id;
2456
- label = agent.nickname;
2457
- } catch {
2458
- throw new Error(`no run or agent found: ${id}`);
2459
- }
2460
- if (!windowInSession(driver, session, window)) throw new Error(STALE_WINDOW_ERROR);
2461
- }
2462
- const target = `${session}:${window}`;
2463
- try {
2464
- driver.tmux(["switch-client", "-t", target]);
2465
- } catch {
2466
- }
2467
- try {
2468
- driver.tmux(["select-window", "-t", target]);
2469
- } catch {
2470
- }
2471
- return { session, window, label };
2472
- }
2473
-
2474
- // src/core/tool-registry.ts
2475
- import { statSync as statSync3 } from "fs";
2476
- import { homedir as homedir4 } from "os";
2477
- import { isAbsolute, join as join6 } from "path";
2478
- var TOOL_REGISTRY = {
2479
- pplx: {
2480
- id: "pplx",
2481
- bin: "pplx",
2482
- displayName: "Perplexity CLI",
2483
- color: "#3f7f8d",
2484
- // muted Perplexity teal
2485
- purpose: "Web search and page snippets from Perplexity, as JSON.",
2486
- authEnv: [],
2487
- probe: pplxSigninState,
2488
- stateLabel: "signed in",
2489
- example: 'pplx search web "node 24 release date" --limit 3',
2490
- docsUrl: "https://github.com/perplexityai/perplexity-cli"
2491
- },
2492
- colab: {
2493
- id: "colab",
2494
- bin: "colab",
2495
- displayName: "Google Colab CLI",
2496
- color: "#d9a13d",
2497
- // muted Colab amber
2498
- purpose: "CPU, GPU and TPU runtimes on Google Colab: run scripts and notebooks remotely.",
2499
- authEnv: [],
2500
- // --auth=oauth2 must precede the subcommand; never adc, which would use
2501
- // this machine's gcloud Application Default Credentials.
2502
- authCheckArgs: ["--auth=oauth2", "whoami"],
2503
- stateLabel: "signed in",
2504
- example: "colab --auth=oauth2 run job.py",
2505
- docsUrl: "https://github.com/googlecolab/google-colab-cli"
2506
- },
2507
- hf: {
2508
- id: "hf",
2509
- bin: "hf",
2510
- displayName: "Hugging Face CLI",
2511
- color: "#d4c04e",
2512
- // muted Hugging Face yellow
2513
- purpose: "Download and upload models and datasets, run jobs on the Hugging Face Hub.",
2514
- authEnv: ["HF_TOKEN"],
2515
- authCheckArgs: ["auth", "whoami"],
2516
- stateLabel: "signed in",
2517
- example: "hf download Qwen/Qwen3-0.6B config.json",
2518
- docsUrl: "https://huggingface.co/docs/huggingface_hub/en/guides/cli"
2519
- },
2520
- ollama: {
2521
- id: "ollama",
2522
- bin: "ollama",
2523
- displayName: "Ollama",
2524
- color: "#8b93a6",
2525
- // slate gray, the monochrome Ollama brand
2526
- purpose: "Run local or Ollama cloud models from the terminal.",
2527
- authEnv: [],
2528
- // The CLI always needs a running ollama server; there is no non-interactive
2529
- // sign-in status command, so `ollama list` reports the server instead.
2530
- authCheckArgs: ["list"],
2531
- stateLabel: "reachable",
2532
- example: 'ollama run gemma4:31b-cloud "summarize README.md"',
2533
- docsUrl: "https://github.com/ollama/ollama/tree/main/docs"
2534
- }
2535
- };
2536
- var TOOL_DEFS = Object.values(TOOL_REGISTRY);
2537
- var TOOLS = Object.keys(TOOL_REGISTRY);
2538
- var TOOL_AUTH_CHECK_TIMEOUT_MS = 3e3;
2539
- function pplxSigninState(env, home, platform = process.platform) {
2540
- const set = (name) => Boolean(env[name]?.trim());
2541
- const sdkBase = set("PPLX_SDK_BASE_URL");
2542
- const sdkKey = set("PPLX_SDK_API_KEY");
2543
- if (sdkBase !== sdkKey) return "no";
2544
- if (sdkBase && sdkKey) return "yes";
2545
- if (set("PERPLEXITY_API_KEY")) return "yes";
2546
- let credentials;
2547
- if (platform === "linux") {
2548
- const xdg = env.XDG_CONFIG_HOME;
2549
- credentials = join6(xdg && isAbsolute(xdg) ? xdg : join6(home, ".config"), "perplexity", "credentials.json");
2550
- } else if (platform === "darwin") {
2551
- credentials = join6(home, "Library", "Application Support", "perplexity", "credentials.json");
2552
- } else {
2553
- return "unknown";
2554
- }
2555
- try {
2556
- return statSync3(credentials, { throwIfNoEntry: false }) ? "yes" : "no";
2557
- } catch {
2558
- return "unknown";
2559
- }
2560
- }
2561
- function toolState(def, env = process.env, home = homedir4()) {
2562
- if (def.probe) return def.probe(env, home);
2563
- if (def.authEnv.some((name) => Boolean(env[name]))) return "yes";
2564
- if (!def.authCheckArgs) return "unknown";
2565
- try {
2566
- const checked = spawnCliSync(def.bin, [...def.authCheckArgs], {
2567
- stdio: "ignore",
2568
- timeout: TOOL_AUTH_CHECK_TIMEOUT_MS
2569
- });
2570
- if (checked.error) return "unknown";
2571
- return checked.status === 0 ? "yes" : "no";
2572
- } catch {
2573
- return "unknown";
2574
- }
2575
- }
2576
- function detectToolStatuses(env = process.env, home = homedir4()) {
2577
- return TOOL_DEFS.map((def) => ({
2578
- id: def.id,
2579
- bin: def.bin,
2580
- display_name: def.displayName,
2581
- color: def.color,
2582
- purpose: def.purpose,
2583
- example: def.example,
2584
- docs_url: def.docsUrl,
2585
- installed: binaryOnPath(def.bin),
2586
- state: toolState(def, env, home),
2587
- state_means: def.stateLabel
2588
- }));
2589
- }
2590
-
2591
- // src/surfaces/mcp/installer.ts
2592
- import { execFileSync as execFileSync3 } from "child_process";
2593
- import { realpathSync, readFileSync as readFileSync4, writeFileSync as writeFileSync4, existsSync as existsSync5, mkdirSync as mkdirSync4 } from "fs";
2594
- import { homedir as homedir5 } from "os";
2595
- import { join as join7, dirname as dirname5 } from "path";
2596
- var SERVER_NAME = "reevesagents";
2597
- var SERVER_BIN = "reevesagents";
2598
- var SERVER_ARG = "mcp";
2599
- var MGMT_TIMEOUT_MS = 15e3;
2600
- var STATUS_TIMEOUT_MS = 2e4;
2601
- var VERIFY_TIMEOUT_MS = 2e4;
2602
- function opencodeConfigPath() {
2603
- const base = process.env.REEVES_HOME || homedir5();
2604
- const dir = join7(base, ".config", "opencode");
2605
- const jsonc = join7(dir, "opencode.jsonc");
2606
- const json = join7(dir, "opencode.json");
2607
- if (existsSync5(json)) return json;
2608
- if (existsSync5(jsonc)) return jsonc;
2609
- return json;
2610
- }
2611
- function readOpencodeConfig(path) {
2612
- if (!existsSync5(path)) return {};
2613
- const raw = readFileSync4(path, "utf-8").trim();
2614
- if (!raw) return {};
2615
- return JSON.parse(raw);
2616
- }
2617
- function opencodeMcpEntry(cmd) {
2618
- return { type: "local", command: [cmd.command, ...cmd.args], enabled: true };
2619
- }
2620
- function opencodeAttached() {
2621
- try {
2622
- const cfg = readOpencodeConfig(opencodeConfigPath());
2623
- const mcp = cfg.mcp;
2624
- return !!mcp && typeof mcp === "object" && SERVER_NAME in mcp;
2625
- } catch {
2626
- return false;
2627
- }
2628
- }
2629
- function opencodeAttach(cmd) {
2630
- const path = opencodeConfigPath();
2631
- const cfg = readOpencodeConfig(path);
2632
- if (!cfg.$schema) cfg.$schema = "https://opencode.ai/config.json";
2633
- const mcp = typeof cfg.mcp === "object" && cfg.mcp !== null ? cfg.mcp : {};
2634
- mcp[SERVER_NAME] = opencodeMcpEntry(cmd);
2635
- cfg.mcp = mcp;
2636
- mkdirSync4(dirname5(path), { recursive: true });
2637
- writeFileSync4(path, `${JSON.stringify(cfg, null, 2)}
2638
- `, "utf-8");
2639
- }
2640
- function opencodeDetach() {
2641
- const path = opencodeConfigPath();
2642
- if (!existsSync5(path)) return;
2643
- const cfg = readOpencodeConfig(path);
2644
- const mcp = cfg.mcp;
2645
- if (mcp && SERVER_NAME in mcp) {
2646
- delete mcp[SERVER_NAME];
2647
- writeFileSync4(path, `${JSON.stringify(cfg, null, 2)}
2648
- `, "utf-8");
2649
- }
2650
- }
2651
- function kimiCodeHome() {
2652
- if (process.env.REEVES_HOME) return join7(process.env.REEVES_HOME, ".kimi-code");
2653
- return process.env.KIMI_CODE_HOME || join7(homedir5(), ".kimi-code");
2654
- }
2655
- function isKimiCode(bin) {
2656
- try {
2657
- const out = execFileSync3(bin, ["--version"], {
2658
- encoding: "utf8",
2659
- timeout: STATUS_TIMEOUT_MS,
2660
- stdio: ["ignore", "pipe", "pipe"]
2661
- }).trim();
2662
- return out !== "" && !/^kimi,/i.test(out);
2663
- } catch {
2664
- return false;
2665
- }
2666
- }
2667
- function kimiCodePluginAttached() {
2668
- try {
2669
- const installed = JSON.parse(readFileSync4(join7(kimiCodeHome(), "plugins", "installed.json"), "utf-8"));
2670
- return Array.isArray(installed.plugins) && installed.plugins.some((p) => p.id === SERVER_NAME && p.enabled !== false);
2671
- } catch {
2672
- return false;
2673
- }
2674
- }
2675
- function kimiCodeMcpConfig() {
2676
- try {
2677
- const raw = readFileSync4(join7(kimiCodeHome(), "mcp.json"), "utf-8").trim();
2678
- return raw ? JSON.parse(raw) : {};
2679
- } catch {
2680
- return {};
2681
- }
2682
- }
2683
- function kimiCodeMcpAttached() {
2684
- const servers = kimiCodeMcpConfig().mcpServers;
2685
- return !!servers && typeof servers === "object" && SERVER_NAME in servers;
2686
- }
2687
- var KIMI_CODE_FILE_OPS = {
2688
- attached: () => kimiCodePluginAttached() || kimiCodeMcpAttached(),
2689
- attach: (cmd) => {
2690
- if (kimiCodePluginAttached()) return;
2691
- const path = join7(kimiCodeHome(), "mcp.json");
2692
- const cfg = kimiCodeMcpConfig();
2693
- const servers = typeof cfg.mcpServers === "object" && cfg.mcpServers !== null ? cfg.mcpServers : {};
2694
- servers[SERVER_NAME] = { command: cmd.command, args: cmd.args };
2695
- cfg.mcpServers = servers;
2696
- mkdirSync4(dirname5(path), { recursive: true });
2697
- writeFileSync4(path, `${JSON.stringify(cfg, null, 2)}
2698
- `, "utf-8");
2699
- },
2700
- detach: () => {
2701
- const path = join7(kimiCodeHome(), "mcp.json");
2702
- if (!existsSync5(path)) return;
2703
- const cfg = kimiCodeMcpConfig();
2704
- const servers = cfg.mcpServers;
2705
- if (servers && SERVER_NAME in servers) {
2706
- delete servers[SERVER_NAME];
2707
- writeFileSync4(path, `${JSON.stringify(cfg, null, 2)}
2708
- `, "utf-8");
2709
- }
2710
- }
2711
- };
2712
- function resolveLaunchCmd(entry = process.argv[1]) {
2713
- if (entry) {
2714
- try {
2715
- const real = realpathSync(entry);
2716
- if (/\.[cm]?js$/.test(real)) return { command: process.execPath, args: [real, SERVER_ARG] };
2717
- } catch {
2718
- }
2719
- }
2720
- try {
2721
- const lookup = process.platform === "win32" ? "where" : "which";
2722
- const abs = (execFileSync3(lookup, [SERVER_BIN], { encoding: "utf8" }).split(/\r?\n/)[0] ?? "").trim();
2723
- if (abs) return { command: abs, args: [SERVER_ARG] };
2724
- } catch {
2725
- }
2726
- return { command: SERVER_BIN, args: [SERVER_ARG] };
2727
- }
2728
- var HOSTS = [
2729
- {
2730
- provider: "cc",
2731
- // Claude Code defaults a new server to `local` (this directory only); pin
2732
- // `user` so one attach covers every project on the machine.
2733
- add: (cmd) => ["mcp", "add", SERVER_NAME, "-s", "user", "--", cmd.command, ...cmd.args],
2734
- remove: ["mcp", "remove", SERVER_NAME],
2735
- list: ["mcp", "list"]
2736
- },
2737
- {
2738
- provider: "codex",
2739
- add: (cmd) => ["mcp", "add", SERVER_NAME, "--", cmd.command, ...cmd.args],
2740
- remove: ["mcp", "remove", SERVER_NAME],
2741
- list: ["mcp", "list"]
2742
- },
2743
- {
2744
- provider: "kimi",
2745
- add: (cmd) => ["mcp", "add", SERVER_NAME, "--", cmd.command, ...cmd.args],
2746
- remove: ["mcp", "remove", SERVER_NAME],
2747
- list: ["mcp", "list"]
2748
- },
2749
- {
2750
- provider: "qwen",
2751
- // qwen (a gemini-cli fork) takes `<commandOrUrl> [args...]` with no `--`
2752
- // separator, and already defaults its scope to `user`.
2753
- add: (cmd) => ["mcp", "add", SERVER_NAME, cmd.command, ...cmd.args],
2754
- remove: ["mcp", "remove", SERVER_NAME],
2755
- list: ["mcp", "list"]
2756
- },
2757
- {
2758
- provider: "hermes",
2759
- // hermes takes --command and a variadic --args, so the entry path and `mcp`
2760
- // both ride on one --args.
2761
- add: (cmd) => ["mcp", "add", SERVER_NAME, "--command", cmd.command, "--args", ...cmd.args],
2762
- remove: ["mcp", "remove", SERVER_NAME],
2763
- list: ["mcp", "list"]
2764
- },
2765
- {
2766
- // opencode's `mcp add` prompts interactively for a local server's command, so
2767
- // we attach it by writing its config JSON directly instead.
2768
- provider: "opencode",
2769
- list: ["mcp", "list"],
2770
- file: { attach: opencodeAttach, detach: opencodeDetach, attached: opencodeAttached }
2771
- }
2772
- ];
2773
- function hostBin(host) {
2774
- return PROVIDER_REGISTRY[host.provider].bin;
2775
- }
2776
- function hostLabel(host) {
2777
- return PROVIDER_REGISTRY[host.provider].displayName;
2778
- }
2779
- function hostFileOps(host) {
2780
- if (host.file) return host.file;
2781
- if (host.provider === "kimi" && isKimiCode(hostBin(host))) return KIMI_CODE_FILE_OPS;
2782
- return void 0;
2783
- }
2784
- function isInstalled(bin) {
2785
- try {
2786
- execFileSync3(process.platform === "win32" ? "where" : "which", [bin], { stdio: "pipe" });
2787
- return true;
2788
- } catch {
2789
- return false;
2790
- }
2791
- }
2792
- function isAttached(host) {
2793
- try {
2794
- const out = execFileSync3(hostBin(host), host.list, {
2795
- encoding: "utf8",
2796
- timeout: STATUS_TIMEOUT_MS,
2797
- stdio: ["ignore", "pipe", "pipe"]
2798
- });
2799
- return /reevesagents(?![-\w])/i.test(out);
2800
- } catch {
2801
- return false;
2802
- }
2803
- }
2804
- function runHostCommand(host, args) {
2805
- execFileSync3(hostBin(host), args, {
2806
- encoding: "utf8",
2807
- timeout: MGMT_TIMEOUT_MS,
2808
- stdio: ["ignore", "pipe", "pipe"]
2809
- });
2810
- }
2811
- function cliError(err) {
2812
- const stderr = err && typeof err === "object" ? err.stderr : void 0;
2813
- const text = typeof stderr === "string" ? stderr.trim() : Buffer.isBuffer(stderr) ? stderr.toString("utf8").trim() : "";
2814
- return text || (err instanceof Error ? err.message : String(err));
2815
- }
2816
- function findHost(key) {
2817
- const host = HOSTS.find((item) => item.provider === key);
2818
- if (!host) throw new Error(`Unknown CLI: ${key}`);
2819
- return host;
2820
- }
2821
- function hostStatus() {
2822
- return HOSTS.map((host) => {
2823
- const installed = isInstalled(hostBin(host));
2824
- const file = installed ? hostFileOps(host) : void 0;
2825
- return {
2826
- key: host.provider,
2827
- bin: hostBin(host),
2828
- label: hostLabel(host),
2829
- installed,
2830
- attached: installed && (file ? file.attached() : isAttached(host)),
2831
- manual: host.add === void 0 && host.file === void 0
2832
- };
2833
- });
2834
- }
2835
- function attach(key, force = false) {
2836
- const host = findHost(key);
2837
- const label = hostLabel(host);
2838
- if (!host.add && !host.file) {
2839
- return {
2840
- key,
2841
- label,
2842
- ok: false,
2843
- message: `${label} must be added manually: add a stdio MCP server named "${SERVER_NAME}" that runs reevesagents mcp`
2844
- };
2845
- }
2846
- if (!isInstalled(hostBin(host))) {
2847
- return { key, label, ok: false, message: `${hostBin(host)} is not installed` };
2848
- }
2849
- const file = hostFileOps(host);
2850
- if (file) {
2851
- try {
2852
- file.attach(resolveLaunchCmd());
2853
- return { key, label, ok: true, message: force ? "reattached" : "attached" };
2854
- } catch (err) {
2855
- return { key, label, ok: false, message: `could not edit config (add it manually): ${cliError(err)}` };
2856
- }
2857
- }
2858
- try {
2859
- if (force && host.remove) {
2860
- try {
2861
- runHostCommand(host, host.remove);
2862
- } catch {
2863
- }
2864
- }
2865
- runHostCommand(host, host.add(resolveLaunchCmd()));
2866
- return { key, label, ok: true, message: force ? "reattached" : "attached" };
2867
- } catch (err) {
2868
- return { key, label, ok: false, message: cliError(err) };
2869
- }
2870
- }
2871
- function detach(key) {
2872
- const host = findHost(key);
2873
- const label = hostLabel(host);
2874
- if (!host.remove && !host.file) {
2875
- return { key, label, ok: false, message: `${label} must be removed manually` };
2876
- }
2877
- if (!isInstalled(hostBin(host))) {
2878
- return { key, label, ok: false, message: `${hostBin(host)} is not installed` };
2879
- }
2880
- const file = hostFileOps(host);
2881
- if (file) {
2882
- try {
2883
- file.detach();
2884
- return { key, label, ok: true, message: "detached" };
2885
- } catch (err) {
2886
- return { key, label, ok: false, message: cliError(err) };
2887
- }
2888
- }
2889
- try {
2890
- runHostCommand(host, host.remove);
2891
- return { key, label, ok: true, message: "detached" };
2892
- } catch (err) {
2893
- return { key, label, ok: false, message: cliError(err) };
2894
- }
2895
- }
2896
- function attachAll(force = false) {
2897
- return HOSTS.filter((host) => (host.add || host.file) && isInstalled(hostBin(host))).map((host) => {
2898
- const file = hostFileOps(host);
2899
- const attached = file ? file.attached() : isAttached(host);
2900
- if (!force && attached) {
2901
- return { key: host.provider, label: hostLabel(host), ok: true, message: "already attached" };
2902
- }
2903
- return attach(host.provider, force);
2904
- });
2905
- }
2906
- async function verifyServerLaunch(cmd = resolveLaunchCmd()) {
2907
- const { Client } = await import("@modelcontextprotocol/sdk/client/index.js");
2908
- const { StdioClientTransport } = await import("@modelcontextprotocol/sdk/client/stdio.js");
2909
- const client = new Client({ name: "reevesagents-verify", version: "1" }, { capabilities: {} });
2910
- const transport = new StdioClientTransport({ command: cmd.command, args: cmd.args, stderr: "ignore" });
2911
- let timer;
2912
- const timeout = new Promise((_, reject) => {
2913
- timer = setTimeout(() => reject(new Error("timed out starting the MCP server")), VERIFY_TIMEOUT_MS);
2914
- timer.unref?.();
2915
- });
2916
- try {
2917
- await Promise.race([client.connect(transport), timeout]);
2918
- const listed = await Promise.race([client.listTools(), timeout]);
2919
- const toolCount = Array.isArray(listed.tools) ? listed.tools.length : 0;
2920
- return { ok: true, detail: `server started, ${toolCount} tools`, toolCount };
2921
- } catch (err) {
2922
- return { ok: false, detail: err instanceof Error ? err.message : String(err) };
2923
- } finally {
2924
- if (timer) clearTimeout(timer);
2925
- try {
2926
- await client.close();
2927
- } catch {
2928
- }
2929
- }
2930
- }
2931
-
2932
- // src/core/doctor.ts
2933
- import { accessSync, constants, existsSync as existsSync6, readFileSync as readFileSync5 } from "fs";
2934
- import { createRequire as createRequire2 } from "module";
2935
- import { join as join8 } from "path";
2936
- var MIN_NODE_VERSION = [22, 12, 0];
2937
- function parseNodeVersion(version) {
2938
- const clean = version.startsWith("v") ? version.slice(1) : version;
2939
- const [major = "0", minor = "0", patch = "0"] = clean.split(".");
2940
- return [parseInt(major, 10) || 0, parseInt(minor, 10) || 0, parseInt(patch, 10) || 0];
2941
- }
2942
- function nodeMeetsMinimum(version) {
2943
- for (let i = 0; i < MIN_NODE_VERSION.length; i++) {
2944
- if (version[i] > MIN_NODE_VERSION[i]) return true;
2945
- if (version[i] < MIN_NODE_VERSION[i]) return false;
2946
- }
2947
- return true;
2948
- }
2949
- function nodeVersionCheck(rawVersion = process.version) {
2950
- const version = rawVersion.startsWith("v") ? rawVersion.slice(1) : rawVersion;
2951
- const parsed = parseNodeVersion(version);
2952
- const ok = nodeMeetsMinimum(parsed);
2953
- return {
2954
- name: "node",
2955
- status: ok ? "ok" : "fail",
2956
- detail: ok ? version : `${version} (need >=22.12.0)`
2957
- };
2958
- }
2959
- function readProcVersion() {
2960
- try {
2961
- return readFileSync5("/proc/version", "utf-8");
2962
- } catch {
2963
- return "";
2964
- }
2965
- }
2966
- function isWsl(env, procVersion) {
2967
- return Boolean(
2968
- env.WSL_DISTRO_NAME || env.WSL_INTEROP || /microsoft|wsl/i.test(procVersion)
2969
- );
2970
- }
2971
- function platformSupportCheck(platform = process.platform, env = process.env, procVersion = platform === "linux" ? readProcVersion() : "") {
2972
- if (platform === "darwin") return { name: "platform", status: "ok", detail: "macOS supported" };
2973
- if (platform === "linux") {
2974
- return {
2975
- name: "platform",
2976
- status: "ok",
2977
- detail: isWsl(env, procVersion) ? "WSL supported" : "Linux supported"
2978
- };
2979
- }
2980
- if (platform === "win32") {
2981
- return {
2982
- name: "platform",
2983
- status: "ok",
2984
- detail: "Windows supported via the built-in winmux (ConPTY) multiplexer"
2985
- };
2986
- }
2987
- return {
2988
- name: "platform",
2989
- status: "warn",
2990
- detail: `${platform} is untested; supported targets are macOS, Linux, and WSL`
2991
- };
2992
- }
2993
- function checkTmux(platform = process.platform) {
2994
- if (platform === "win32") {
2995
- const versionStr2 = tmuxVersion();
2996
- if (!versionStr2 || !tmuxAvailable(platform)) {
2997
- return {
2998
- name: "tmux",
2999
- status: "fail",
3000
- detail: "winmux not found; reinstall reevesagents so the optional @lydell/node-pty and @xterm/headless packages install"
3001
- };
3002
- }
3003
- const match2 = versionStr2.match(/tmux (\d+)\.(\d+)/);
3004
- return {
3005
- name: "tmux",
3006
- status: "ok",
3007
- detail: `winmux (tmux ${match2 ? `${match2[1]}.${match2[2]}` : "3.x"} compatible, ConPTY)`
3008
- };
3009
- }
3010
- const versionStr = tmuxVersion();
3011
- if (!versionStr) return { name: "tmux", status: "fail", detail: "not on PATH" };
3012
- const match = versionStr.match(/tmux (\d+)\.(\d+)/);
3013
- if (!match) return { name: "tmux", status: "warn", detail: `unexpected version format: ${versionStr}` };
3014
- const major = parseInt(match[1] ?? "0", 10);
3015
- const minor = parseInt(match[2] ?? "0", 10);
3016
- if (major < 3) return { name: "tmux", status: "warn", detail: `tmux ${major}.${minor}; upgrade to 3.0+ recommended` };
3017
- return { name: "tmux", status: "ok", detail: `tmux ${major}.${minor}` };
3018
- }
3019
- function checkProviders() {
3020
- const available = detectAvailable();
3021
- const statuses = Object.entries(available).map(([name, isAvail]) => `${providerDisplayName(name)}: ${isAvail ? "ok" : "missing"}`).join("; ");
3022
- const noneAvail = Object.values(available).every((value) => !value);
3023
- return {
3024
- name: "providers",
3025
- status: noneAvail ? "fail" : "ok",
3026
- detail: statuses
3027
- };
3028
- }
3029
- function checkProviderCompatibility() {
3030
- if (process.env.REEVES_DOCTOR_SKIP_PROVIDER_COMPAT === "1") {
3031
- return { name: "provider compat", status: "warn", detail: "skipped by REEVES_DOCTOR_SKIP_PROVIDER_COMPAT" };
3032
- }
3033
- const compatibility = inspectProviderCompatibility();
3034
- const installed = Object.values(compatibility).filter((provider) => provider.available);
3035
- if (installed.length === 0) return { name: "provider compat", status: "warn", detail: "no installed providers to inspect" };
3036
- const problems = installed.filter((provider) => !provider.ok).map((provider) => `${providerDisplayName(provider.provider)}: ${provider.detail}`);
3037
- if (problems.length === 0) {
3038
- return { name: "provider compat", status: "ok", detail: `${installed.map((provider) => providerDisplayName(provider.provider)).join(", ")} compatible` };
3039
- }
3040
- return {
3041
- name: "provider compat",
3042
- status: "warn",
3043
- detail: problems.slice(0, 3).join("; ") + (problems.length > 3 ? `; +${problems.length - 3} more` : "")
3044
- };
3045
- }
3046
- function checkTools() {
3047
- const statuses = detectToolStatuses();
3048
- const detail = statuses.map((tool) => tool.installed ? `${tool.display_name}: installed, ${tool.state_means}: ${tool.state}` : `${tool.display_name}: missing`).join("; ");
3049
- return { name: "tools", status: "ok", detail };
3050
- }
3051
- function checkPathAccess(name, path) {
3052
- if (!existsSync6(path)) return { name, status: "warn", detail: `${path} (will be created on first use)` };
3053
- try {
3054
- accessSync(path, constants.R_OK | constants.W_OK);
3055
- return { name, status: "ok", detail: path };
3056
- } catch {
3057
- return { name, status: "fail", detail: `${path} (not readable/writable)` };
3058
- }
3059
- }
3060
- function checkWebExtras() {
3061
- const requireFrom = createRequire2(import.meta.url);
3062
- const missing = WEB_EXTRA_MODULES.filter((name) => {
3063
- try {
3064
- requireFrom.resolve(name);
3065
- return false;
3066
- } catch {
3067
- return true;
3068
- }
3069
- });
3070
- if (missing.length === 0) {
3071
- return { name: "web extras", status: "ok", detail: `${WEB_EXTRA_MODULES.join(" + ")} present (web UI available)` };
3072
- }
3073
- return { name: "web extras", status: "warn", detail: `${missing.join(", ")} not installed; TUI unaffected, web UI disabled` };
3074
- }
3075
- function checkRunsState() {
3076
- try {
3077
- const runs = listRuns();
3078
- return { name: "runs state", status: "ok", detail: `${runs.length} run${runs.length === 1 ? "" : "s"}` };
3079
- } catch (err) {
3080
- return {
3081
- name: "runs state",
3082
- status: "fail",
3083
- detail: `error reading runs: ${err instanceof Error ? err.message : "unknown"}`
3084
- };
3085
- }
3086
- }
3087
- function checkMcpServerCommand() {
3088
- const cmd = resolveLaunchCmd();
3089
- if (cmd.command === "reevesagents") {
3090
- return {
3091
- name: "mcp server",
3092
- status: "warn",
3093
- detail: "no absolute launcher resolved; attached host CLIs will fall back to their own PATH"
3094
- };
3095
- }
3096
- try {
3097
- accessSync(cmd.command, constants.X_OK);
3098
- return { name: "mcp server", status: "ok", detail: `${cmd.command} ${cmd.args.join(" ")}` };
3099
- } catch {
3100
- return {
3101
- name: "mcp server",
3102
- status: "warn",
3103
- detail: `${cmd.command} is not executable; re-run reevesagents attach after reinstalling`
3104
- };
3105
- }
3106
- }
3107
- function runDoctor() {
3108
- return {
3109
- checks: [
3110
- platformSupportCheck(),
3111
- nodeVersionCheck(),
3112
- checkTmux(),
3113
- checkProviders(),
3114
- checkProviderCompatibility(),
3115
- checkTools(),
3116
- checkPathAccess("state dir", stateRoot()),
3117
- checkPathAccess("runs dir", runsDir()),
3118
- checkPathAccess("presets dir", join8(stateRoot(), "presets")),
3119
- checkRunsState(),
3120
- checkWebExtras(),
3121
- checkMcpServerCommand()
3122
- ]
3123
- };
3124
- }
3125
-
3126
- export {
3127
- redactSecrets,
3128
- PROVIDER_DEFS,
3129
- coerceExtraArgs,
3130
- BIN,
3131
- PROVIDERS,
3132
- isProvider,
3133
- normalizeProvider,
3134
- providerSupportsAuthMode,
3135
- providerSupportsEffort,
3136
- buildCommand,
3137
- detectAvailable,
3138
- tmuxCommand,
3139
- execTmux,
3140
- spawnTmux,
3141
- exactSession,
3142
- tmuxAvailable,
3143
- sessionExists,
3144
- targetExists,
3145
- listSessions,
3146
- sessionAttached,
3147
- killSession,
3148
- allWindowIds,
3149
- RUN_SESSION_PATTERN,
3150
- VIEWER_SESSION_PATTERN,
3151
- sessionInGroup,
3152
- windowIds,
3153
- windowByName,
3154
- stateRoot,
3155
- runsDir,
3156
- runDir,
3157
- nowIso,
3158
- nowMs,
3159
- withRunsLock,
3160
- readRun,
3161
- listRuns,
3162
- latestActiveRun,
3163
- listRunHistory,
3164
- deleteAgent,
3165
- deleteRunHistory,
3166
- computeRunStatus,
3167
- readAgent,
3168
- archiveAndRemoveRun,
3169
- listAgents,
3170
- findAgent,
3171
- runHasLiveTmuxTarget,
3172
- autoCleanupRuns,
3173
- shellQuote,
3174
- LANGUAGE_OPTIONS,
3175
- DEFAULT_LANGUAGE,
3176
- isLanguageCode,
3177
- languageOption,
3178
- configPath,
3179
- configExists,
3180
- defaultConfig,
3181
- loadConfig,
3182
- saveConfig,
3183
- CONFIG_FIELDS,
3184
- parseConfigValue,
3185
- setConfigValues,
3186
- presetsDir,
3187
- listPresets,
3188
- loadPreset,
3189
- savePreset,
3190
- deletePreset,
3191
- savePresetFromRun,
3192
- providerDisplayName,
3193
- providerColor,
3194
- modelColor,
3195
- modelBadgeLabel,
3196
- ALLOWED_KEYS,
3197
- startRun,
3198
- startRunFromPreset,
3199
- startRunWithHead,
3200
- spawnWorker,
3201
- openReeves,
3202
- openRunTabs,
3203
- openAgent,
3204
- peekAgent,
3205
- sendText,
3206
- sendKey,
3207
- interrupt,
3208
- killAgent,
3209
- stopRun,
3210
- openTmuxTarget,
3211
- detectToolStatuses,
3212
- resolveLaunchCmd,
3213
- hostStatus,
3214
- attach,
3215
- detach,
3216
- attachAll,
3217
- verifyServerLaunch,
3218
- nodeVersionCheck,
3219
- checkTmux,
3220
- runDoctor
3221
- };
3222
- //# sourceMappingURL=chunk-DLWYZPW6.js.map