1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
//! Unified coding-agent **harness catalog** — the single source of truth for
//! how BitRouter finds, launches, and routes each supported harness.
//!
//! A harness is drivable in either of two facets:
//!
//! - **interactive** (`bitrouter launch`) — the harness's own native TUI
//! (`claude`, `codex`), launched as a child with its LLM traffic env-wrapped
//! to the daemon; the human drives it directly.
//! - **ACP** (`bitrouter spawn`) — a headless ACP adapter
//! (`@zed-industries/claude-code-acp`, …) driven as a sub-agent by a program.
//!
//! The crucial fact this module encodes once: **both facets route through the
//! daemon with the same [`Routing`]**, because the interactive binary and the
//! ACP adapter of a given harness share a config/env surface (verified against
//! adapter source — see `internal/SPAWN_SPEC.md` §6). So the routing knowledge that used
//! to live in `spawn::AgentSpec` *and* would have been duplicated onto the ACP
//! side lives here exactly once, and `launch`, `spawn`, and `agents install`
//! all read it.
/// BitRouter's own API-key env var (`brk_…`). When set, it is forwarded to the
/// harness as the gateway bearer credential.
pub const BITROUTER_API_KEY_ENV: &str = "BITROUTER_API_KEY";
/// Placeholder credential injected when no real key is available. Ignored by
/// the daemon under `skip_auth: true` (the `bitrouter init` default); the
/// harness merely needs *some* credential to start.
pub const PLACEHOLDER_API_KEY: &str = "bitrouter-local";
use anyhow::Context;
/// One catalog harness. Keyed by [`id`](Self::id), which is the ACP-facet
/// id used under `agents:` in `bitrouter.yaml` and by `bitrouter agents`.
#[derive(Debug, Clone, Copy)]
pub struct Harness {
/// Catalog / ACP-config id (e.g. `claude-acp`). Also the `agents install`
/// key.
pub id: &'static str,
/// One-line human description (shown in `agents list`).
pub description: &'static str,
/// Upstream project URL — the source of the recommended invocation.
pub project_url: &'static str,
/// The ACP adapter invocation (`command` + `args`) for `bitrouter spawn`,
/// when the harness has one. `None` for interactive-only harnesses
/// (grok, antigravity) — they have no headless ACP adapter today.
pub acp_command: Option<&'static str>,
/// Args passed to [`acp_command`](Self::acp_command).
pub acp_args: &'static [&'static str],
/// A substring that identifies this harness inside a configured agent's
/// invocation (command or any arg) — used to map a user-renamed
/// `agents:` entry back to its catalog routing (invocation matching, so
/// the YAML key carries no semantics). Usually the adapter package name.
pub package_marker: &'static str,
/// The interactive native-TUI binary for `bitrouter launch`, when the
/// harness has one. `None` for adapter-only harnesses (gemini, pi).
pub interactive_binary: Option<&'static str>,
/// How this harness's LLM traffic is pointed at the daemon.
pub routing: Routing,
}
/// How a harness's LLM traffic is redirected to the BitRouter gateway. One
/// value per harness, applied identically to both facets.
#[derive(Debug, Clone, Copy)]
pub enum Routing {
/// Env-var redirection: set `base_url_env` to the gateway URL and
/// `auth_env` to the bearer credential (BitRouter's inbound scheme is
/// `Authorization: Bearer`; never a provider `x-api-key` var). Optional
/// `model_env` pins the model; `extra` carries fixed vars the redirect
/// needs. Used by claude-code-acp (and interactive Claude Code) and,
/// best-effort, gemini-cli.
Env {
/// Var the harness reads its gateway base URL from.
base_url_env: &'static str,
/// Var the harness turns into the gateway credential.
auth_env: &'static str,
/// Whether the harness sends `auth_env` as `Authorization: Bearer`
/// (BitRouter's inbound scheme). `false` means a provider-native
/// header the daemon's auth hook rejects under `skip_auth: false`
/// (e.g. gemini's `x-goog-api-key`) — routing then only works under
/// `skip_auth: true`, and callers warn when auth is required.
bearer_auth: bool,
/// Var that pins the model, when the harness supports one.
model_env: Option<&'static str>,
/// Fixed vars required for the redirect to take effect.
extra: &'static [(&'static str, &'static str)],
},
/// Codex `-c` one-shot config overrides (codex-acp forwards argv to codex
/// core, so the same overrides work for both facets). The gateway must
/// speak the OpenAI **Responses** API — pinned codex builds dropped
/// `wire_api = "chat"`.
CodexArgs,
/// Config-file synthesis (opencode): the harness loads the JSON config
/// `OPENCODE_CONFIG` points at, and routing, the default model, and MCP
/// injection all ride that one synthesized file. There is no pure
/// env/args overlay — headless spawn launches direct with a note; the
/// interactive facet synthesizes via [`Harness::orchestrator_overlay`].
OpencodeConfig,
/// Config-dir synthesis (pi — SPAWN_SPEC §6.4): pi has no base-URL env
/// var, so routing synthesizes a `models.json` in a per-launch dir and
/// points `PI_CODING_AGENT_DIR` at it, selecting the provider/model by
/// CLI flag. Interactive facet only; headless spawn launches direct
/// with a note.
PiConfigDir,
/// Home-dir synthesis (hermes): routing synthesizes a `config.yaml`
/// (`model.provider: custom` + a loopback `base_url` — hermes trusts
/// loopback custom endpoints) in a per-launch dir, points `HERMES_HOME`
/// at it, and passes the credential via `CUSTOM_API_KEY`. The same file
/// carries the default model and `mcp_servers` (fleet bridge).
/// Interactive facet only; headless spawn launches direct with a note
/// (hermes then uses the user's own `~/.hermes` provider).
HermesHome,
/// Profile-dir synthesis (openclaw): the interactive facet synthesizes
/// an isolated profile (`OPENCLAW_STATE_DIR`/`OPENCLAW_CONFIG_PATH`)
/// whose `openclaw.json` declares a `bitrouter` custom provider and
/// default model, and runs the embedded runtime (`tui --local`). The
/// ACP facet (`openclaw acp`) bridges into the user's running gateway,
/// which owns model routing — headless spawn launches direct with a
/// note.
OpenclawProfile,
/// No gateway redirection, by design: the harness IS a subscription
/// client whose session the daemon itself borrows as a provider (grok →
/// `supergrok`, agy → `google-ai`) — routing it through the daemon would
/// loop back to the same backend on the same credential. It launches
/// with its own auth; `--model` forwards as the harness's native flag.
OwnAuth,
}
/// The child-process overrides a [`Routing`] contributes: env vars to set
/// (injection wins over inherited/config env) and args to append to the
/// harness invocation.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct RoutingOverlay {
/// Env vars to set on the child (each overrides any inherited value).
pub env: Vec<(String, String)>,
/// Args appended to the harness invocation.
pub args: Vec<String>,
}
/// The bundled catalog. Limited to publicly-available, actively-maintained
/// harnesses. Extend by PR to bitrouter.
pub const CATALOG: &[Harness] = &[
Harness {
id: "claude-acp",
description: "Anthropic Claude via Zed's `claude-code-acp`",
project_url: "https://github.com/zed-industries/claude-code-acp",
acp_command: Some("npx"),
acp_args: &["-y", "@zed-industries/claude-code-acp@latest"],
// A substring of both the npm spec (`@zed-industries/claude-code-acp`)
// and the globally-installed binary name (`claude-code-acp`), so a
// `command: claude-code-acp` config still catalog-matches.
package_marker: "claude-code-acp",
interactive_binary: Some("claude"),
// claude-code-acp passes process env through to the SDK-spawned CLI,
// which honors these exactly as interactive Claude Code does.
// ANTHROPIC_AUTH_TOKEN → `Authorization: Bearer` (also suppresses the
// login requirement); ANTHROPIC_API_KEY would be `x-api-key`, not
// BitRouter's inbound scheme, so we never touch it.
routing: Routing::Env {
base_url_env: "ANTHROPIC_BASE_URL",
auth_env: "ANTHROPIC_AUTH_TOKEN",
bearer_auth: true,
model_env: Some("ANTHROPIC_MODEL"),
extra: &[],
},
},
Harness {
id: "codex-acp",
description: "OpenAI Codex via Zed's `codex-acp`",
project_url: "https://github.com/zed-industries/codex-acp",
acp_command: Some("npx"),
acp_args: &["-y", "@zed-industries/codex-acp@latest"],
package_marker: "codex-acp",
interactive_binary: Some("codex"),
routing: Routing::CodexArgs,
},
Harness {
id: "gemini-cli",
description: "Google's Gemini CLI with `--experimental-acp` (best-effort routing)",
project_url: "https://github.com/google-gemini/gemini-cli",
acp_command: Some("npx"),
acp_args: &[
"-y",
"--",
"@google/gemini-cli@latest",
"--experimental-acp",
],
// Substring of both `@google/gemini-cli` and the `gemini-cli` binary.
package_marker: "gemini-cli",
interactive_binary: None,
// Best-effort: gemini-cli is deprecated upstream (Antigravity). Sends
// GEMINI_API_KEY as `x-goog-api-key`, which the daemon accepts only
// under skip_auth; GOOGLE_GEMINI_BASE_URL auto-selects GATEWAY auth.
routing: Routing::Env {
base_url_env: "GOOGLE_GEMINI_BASE_URL",
auth_env: "GEMINI_API_KEY",
// gemini sends GEMINI_API_KEY as `x-goog-api-key`, not Bearer —
// the daemon accepts it only under `skip_auth: true`.
bearer_auth: false,
model_env: Some("GEMINI_MODEL"),
extra: &[],
},
},
Harness {
id: "opencode",
description: "sst's opencode via its native `opencode acp`",
project_url: "https://github.com/sst/opencode",
acp_command: Some("opencode"),
acp_args: &["acp"],
package_marker: "opencode",
interactive_binary: Some("opencode"),
routing: Routing::OpencodeConfig,
},
Harness {
id: "pi-acp",
description: "pi coding agent via `pi-acp` (needs `pi` on PATH)",
project_url: "https://github.com/svkozak/pi-acp",
acp_command: Some("npx"),
acp_args: &["-y", "pi-acp@latest"],
package_marker: "pi-acp",
interactive_binary: Some("pi"),
routing: Routing::PiConfigDir,
},
Harness {
id: "hermes-acp",
description: "Nous Research's Hermes Agent via its native `hermes acp`",
project_url: "https://github.com/NousResearch/hermes-agent",
acp_command: Some("hermes"),
acp_args: &["acp"],
package_marker: "hermes",
interactive_binary: Some("hermes"),
routing: Routing::HermesHome,
},
Harness {
id: "openclaw",
description: "OpenClaw assistant via its gateway ACP bridge `openclaw acp`",
project_url: "https://github.com/openclaw/openclaw",
acp_command: Some("openclaw"),
acp_args: &["acp"],
package_marker: "openclaw",
interactive_binary: Some("openclaw"),
routing: Routing::OpenclawProfile,
},
Harness {
id: "grok",
description: "xAI's Grok CLI (interactive only; own SuperGrok auth)",
project_url: "https://x.ai/",
acp_command: None,
acp_args: &[],
package_marker: "grok-cli",
interactive_binary: Some("grok"),
routing: Routing::OwnAuth,
},
Harness {
id: "antigravity",
description: "Google's Antigravity CLI `agy` (interactive only; own Google auth)",
project_url: "https://antigravity.google/",
acp_command: None,
acp_args: &[],
package_marker: "antigravity-cli",
interactive_binary: Some("agy"),
routing: Routing::OwnAuth,
},
];
/// Look up a harness by its catalog id.
pub fn by_id(id: &str) -> Option<&'static Harness> {
CATALOG.iter().find(|h| h.id == id)
}
/// Look up a harness by its interactive binary name (`launch` uses this to
/// share the ACP-side routing knowledge).
pub fn by_interactive_binary(binary: &str) -> Option<&'static Harness> {
CATALOG
.iter()
.find(|h| h.interactive_binary == Some(binary))
}
/// Match a configured agent's invocation back to a catalog harness by its
/// [`package_marker`](Harness::package_marker), so routing follows the
/// *invocation*, not the user-chosen YAML key. Checks the command and every
/// arg for the marker substring.
pub fn match_invocation(command: &str, args: &[String]) -> Option<&'static Harness> {
CATALOG.iter().find(|h| {
command.contains(h.package_marker) || args.iter().any(|a| a.contains(h.package_marker))
})
}
impl Harness {
/// Compute the child-process overlay that routes this harness's LLM
/// traffic through `base_url`, authenticating with `auth` (already
/// resolved by precedence — see [`resolve_gateway_auth`]). `model` pins
/// the model when the harness supports it. Returns an empty overlay for
/// harnesses env/args can't route ([`OpencodeConfig`](Routing::OpencodeConfig)
/// / [`PiConfigDir`](Routing::PiConfigDir) / [`OwnAuth`](Routing::OwnAuth)
/// — the caller warns and runs direct; see [`env_args_routable`](Self::env_args_routable)).
pub fn routing_overlay(
&self,
base_url: &str,
auth: &str,
model: Option<&str>,
) -> RoutingOverlay {
match &self.routing {
Routing::Env {
base_url_env,
auth_env,
model_env,
extra,
..
} => {
let mut env = vec![
((*base_url_env).to_string(), base_url.to_string()),
((*auth_env).to_string(), auth.to_string()),
];
for (k, v) in *extra {
env.push(((*k).to_string(), (*v).to_string()));
}
if let (Some(var), Some(m)) = (model_env, model) {
env.push(((*var).to_string(), m.to_string()));
}
RoutingOverlay {
env,
args: Vec::new(),
}
}
Routing::CodexArgs => codex_overlay(base_url, auth, model),
// Config-synthesis harnesses have no pure env/args overlay —
// callers that can't synthesize launch direct (and say so) —
// and own-auth harnesses are never redirected at all.
Routing::OpencodeConfig
| Routing::PiConfigDir
| Routing::HermesHome
| Routing::OpenclawProfile
| Routing::OwnAuth => RoutingOverlay::default(),
}
}
/// Whether this harness routes through pure env/args injection (the
/// headless-spawn facet). Config-synthesis harnesses (opencode, pi)
/// route only through [`Self::orchestrator_overlay`] — headless callers
/// launch them direct with a note.
pub fn env_args_routable(&self) -> bool {
matches!(self.routing, Routing::Env { .. } | Routing::CodexArgs)
}
/// Whether the harness sends its gateway credential as `Authorization:
/// Bearer` (BitRouter's inbound scheme). `false` means a provider-native
/// header the daemon rejects under `skip_auth: false` (gemini). Codex's
/// `env_key` path is Bearer, so non-`Env` routings are bearer-compatible.
pub fn auth_is_bearer(&self) -> bool {
match self.routing {
Routing::Env { bearer_auth, .. } => bearer_auth,
_ => true,
}
}
/// Whether `--model` can be applied to this harness on the pure
/// env/args path. Config-synthesis harnesses pin their model through
/// [`Self::orchestrator_overlay`] instead.
pub fn supports_model_pin(&self) -> bool {
match self.routing {
Routing::Env { model_env, .. } => model_env.is_some(),
Routing::CodexArgs => true,
Routing::OpencodeConfig
| Routing::PiConfigDir
| Routing::HermesHome
| Routing::OpenclawProfile
| Routing::OwnAuth => false,
}
}
/// Interactive-orchestrator overlay (TUI_SPEC §2): the routing overlay
/// plus MCP-bridge injection, synthesizing config files under
/// `state_dir` for the config-routed harnesses (opencode, pi).
///
/// `catalog` is the daemon's advertised model ids — it fills the
/// synthesized providers' model lists so the harness's own model picker
/// shows what the daemon can serve. `model` pins the model (and becomes
/// the synthesized default); when absent, the first catalog entry is
/// the default. `mcp` lists the servers to inject where the harness has
/// an MCP mechanism — pi has none, so its orchestrator runs without
/// them.
pub fn orchestrator_overlay(
&self,
base_url: &str,
auth: &str,
model: Option<&str>,
catalog: &[String],
mcp: &[McpServer],
state_dir: &std::path::Path,
) -> anyhow::Result<RoutingOverlay> {
match self.id {
// Claude Code loads extra MCP servers from `--mcp-config <file>`.
// Stdio entries are `{command, args}`; HTTP entries need an
// explicit `"type": "http"` (a `url` without `type` is a hard
// error) plus a `headers` object.
"claude-acp" => {
let mut overlay = self.routing_overlay(base_url, auth, model);
if !mcp.is_empty() {
std::fs::create_dir_all(state_dir)
.with_context(|| format!("creating {}", state_dir.display()))?;
let path = state_dir.join("mcp.json");
let mut servers = serde_json::Map::new();
for s in mcp {
let entry = match &s.transport {
McpTransport::Stdio { command, args } => {
serde_json::json!({ "command": command, "args": args })
}
McpTransport::Http { url, headers } => serde_json::json!({
"type": "http",
"url": url,
"headers": headers_map(headers),
}),
};
servers.insert(s.name.clone(), entry);
}
let config = serde_json::json!({ "mcpServers": servers });
std::fs::write(&path, serde_json::to_string_pretty(&config)?)
.context("writing claude MCP config")?;
overlay
.args
.extend(["--mcp-config".to_string(), path.display().to_string()]);
}
Ok(overlay)
}
// codex takes MCP servers as `-c mcp_servers.*` TOML overrides.
// `url` presence selects the streamable-HTTP transport (codex
// 0.144+); auth rides `http_headers.<Name>` overrides.
"codex-acp" => {
let mut overlay = self.routing_overlay(base_url, auth, model);
for s in mcp {
match &s.transport {
McpTransport::Stdio { command, args } => {
let items: Vec<String> = args.iter().map(|a| toml_string(a)).collect();
overlay.args.extend([
"-c".to_string(),
format!("mcp_servers.{}.command={}", s.name, toml_string(command)),
"-c".to_string(),
format!("mcp_servers.{}.args=[{}]", s.name, items.join(",")),
]);
}
McpTransport::Http { url, headers } => {
overlay.args.extend([
"-c".to_string(),
format!("mcp_servers.{}.url={}", s.name, toml_string(url)),
]);
for (name, value) in headers {
overlay.args.extend([
"-c".to_string(),
format!(
"mcp_servers.{}.http_headers.{}={}",
s.name,
name,
toml_string(value)
),
]);
}
}
}
}
Ok(overlay)
}
// opencode: one synthesized JSON config carries the provider,
// the default model, and the MCP bridge; OPENCODE_CONFIG points
// at it.
"opencode" => {
std::fs::create_dir_all(state_dir)
.with_context(|| format!("creating {}", state_dir.display()))?;
let path = state_dir.join("opencode.json");
let config = opencode_config(base_url, auth, model, catalog, mcp);
std::fs::write(&path, serde_json::to_string_pretty(&config)?)
.context("writing opencode config")?;
Ok(RoutingOverlay {
env: vec![("OPENCODE_CONFIG".to_string(), path.display().to_string())],
args: Vec::new(),
})
}
// pi: synthesize `models.json` in a dir, point
// PI_CODING_AGENT_DIR at it, and select provider/model by flag
// (SPAWN_SPEC §6.4). No MCP mechanism — `mcp` is ignored.
"pi-acp" => {
let dir = state_dir.join("pi-agent");
std::fs::create_dir_all(&dir)
.with_context(|| format!("creating {}", dir.display()))?;
let mut models: Vec<serde_json::Value> = catalog
.iter()
.map(|id| serde_json::json!({ "id": id }))
.collect();
if let Some(m) = model
&& !catalog.iter().any(|id| id == m)
{
models.push(serde_json::json!({ "id": m }));
}
let config = serde_json::json!({
"providers": {
"bitrouter": {
"name": "BitRouter",
"baseUrl": v1_base_url(base_url),
"api": "openai-completions",
"apiKey": auth,
"models": models,
}
}
});
std::fs::write(
dir.join("models.json"),
serde_json::to_string_pretty(&config)?,
)
.context("writing pi models.json")?;
let mut args = Vec::new();
// Select the routed provider only when it has a model to
// offer; otherwise pi falls back to its own defaults.
if let Some(default) = model
.map(str::to_string)
.or_else(|| catalog.first().cloned())
{
args.extend([
"--provider".to_string(),
"bitrouter".to_string(),
"--model".to_string(),
default,
]);
}
Ok(RoutingOverlay {
env: vec![("PI_CODING_AGENT_DIR".to_string(), dir.display().to_string())],
args,
})
}
// hermes: synthesize an isolated `HERMES_HOME` whose config.yaml
// routes via a `custom` loopback provider (hermes trusts loopback
// custom endpoints) and carries the fleet MCP server; the
// credential rides `CUSTOM_API_KEY`. The file is written as JSON
// — hermes parses config.yaml with a YAML 1.2 loader, and JSON
// is a YAML subset — so no YAML serializer dependency is needed.
"hermes-acp" => {
let dir = state_dir.join("hermes");
std::fs::create_dir_all(&dir)
.with_context(|| format!("creating {}", dir.display()))?;
let default = model
.map(str::to_string)
.or_else(|| catalog.first().cloned());
let mut config = serde_json::json!({
"model": {
"provider": "custom",
"base_url": v1_base_url(base_url),
}
});
if let Some(default) = default {
config["model"]["default"] = serde_json::Value::String(default);
}
if !mcp.is_empty() {
let mut entries = serde_json::Map::new();
for s in mcp {
let entry = match &s.transport {
McpTransport::Stdio { command, args } => {
serde_json::json!({ "command": command, "args": args })
}
// hermes selects the HTTP transport by `url`
// presence.
McpTransport::Http { url, headers } => serde_json::json!({
"url": url,
"headers": headers_map(headers),
}),
};
entries.insert(s.name.clone(), entry);
}
config["mcp_servers"] = serde_json::Value::Object(entries);
}
std::fs::write(
dir.join("config.yaml"),
serde_json::to_string_pretty(&config)?,
)
.context("writing hermes config.yaml")?;
Ok(RoutingOverlay {
env: vec![
("HERMES_HOME".to_string(), dir.display().to_string()),
("CUSTOM_API_KEY".to_string(), auth.to_string()),
],
args: Vec::new(),
})
}
// openclaw: synthesize an isolated profile (state dir + config)
// whose `openclaw.json` declares a `bitrouter` custom provider,
// and run the embedded local runtime (`tui --local` — no gateway
// needed). Model entries need the full schema (name/cost/window)
// or config validation rejects the file. No MCP injection yet —
// openclaw's MCP surface is gateway-scoped.
"openclaw" => {
let dir = state_dir.join("openclaw");
std::fs::create_dir_all(&dir)
.with_context(|| format!("creating {}", dir.display()))?;
let ids: Vec<&str> = model
.into_iter()
.chain(catalog.iter().map(String::as_str))
.collect();
let models: Vec<serde_json::Value> = ids
.iter()
.map(|id| {
serde_json::json!({
"id": id,
"name": id,
"reasoning": false,
"input": ["text"],
"cost": { "input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0 },
"contextWindow": 200000,
"maxTokens": 8192,
})
})
.collect();
let mut config = serde_json::json!({
"gateway": { "mode": "local" },
"models": {
"mode": "merge",
"providers": {
"bitrouter": {
"baseUrl": v1_base_url(base_url),
"apiKey": auth,
"api": "openai-completions",
"models": models,
}
}
}
});
if let Some(default) = ids.first() {
config["agents"] = serde_json::json!({
"defaults": { "model": format!("bitrouter/{default}") }
});
}
std::fs::write(
dir.join("openclaw.json"),
serde_json::to_string_pretty(&config)?,
)
.context("writing openclaw.json")?;
Ok(RoutingOverlay {
env: vec![
("OPENCLAW_STATE_DIR".to_string(), dir.display().to_string()),
(
"OPENCLAW_CONFIG_PATH".to_string(),
dir.join("openclaw.json").display().to_string(),
),
],
args: vec!["tui".to_string(), "--local".to_string()],
})
}
// Own-auth harnesses (grok, agy): no redirection, no MCP
// mechanism we can inject non-invasively — hosted with their own
// subscription auth; `--model` forwards as their native flag.
"grok" => Ok(RoutingOverlay {
env: Vec::new(),
args: model
.map(|m| vec!["-m".to_string(), m.to_string()])
.unwrap_or_default(),
}),
"antigravity" => Ok(RoutingOverlay {
env: Vec::new(),
args: model
.map(|m| vec!["--model".to_string(), m.to_string()])
.unwrap_or_default(),
}),
// Unknown interactive harness: routing only, no MCP mechanism.
_ => Ok(self.routing_overlay(base_url, auth, model)),
}
}
}
/// An MCP server to inject into an orchestrator harness — the TUI's fleet
/// bridge plus the gateway servers (`bitrouter_tools` / `bitrouter_skills`,
/// see `crate::gateways`).
#[derive(Debug, Clone)]
pub struct McpServer {
/// Server name as the harness will list it (e.g. `bitrouter_fleet`).
pub name: String,
/// How the harness dials it.
pub transport: McpTransport,
}
/// How a harness dials an injected MCP server. Headers are an ordered list
/// (not a map) so synthesized configs and `-c` overrides stay deterministic.
#[derive(Debug, Clone)]
pub enum McpTransport {
/// Spawn `command` with `args` and exchange JSON-RPC over stdio.
Stdio { command: String, args: Vec<String> },
/// Streamable HTTP at `url`, sending the static request `headers`
/// (e.g. `Authorization`) on every call.
Http {
url: String,
headers: Vec<(String, String)>,
},
}
/// Render ordered header pairs as the JSON object shape harness config files
/// expect (`{"Authorization": "Bearer …"}`).
fn headers_map(headers: &[(String, String)]) -> serde_json::Map<String, serde_json::Value> {
headers
.iter()
.map(|(k, v)| (k.clone(), serde_json::Value::String(v.clone())))
.collect()
}
/// The synthesized opencode config: a `bitrouter` provider over the OpenAI
/// wire, the daemon's catalog as its model list, an optional default model,
/// and the injected MCP servers.
fn opencode_config(
base_url: &str,
auth: &str,
model: Option<&str>,
catalog: &[String],
mcp: &[McpServer],
) -> serde_json::Value {
let mut models = serde_json::Map::new();
for id in catalog {
models.insert(id.clone(), serde_json::json!({}));
}
if let Some(m) = model {
models
.entry(m.to_string())
.or_insert_with(|| serde_json::json!({}));
}
let mut config = serde_json::json!({
"$schema": "https://opencode.ai/config.json",
"provider": {
"bitrouter": {
"npm": "@ai-sdk/openai-compatible",
"name": "BitRouter",
"options": { "baseURL": v1_base_url(base_url), "apiKey": auth },
"models": serde_json::Value::Object(models),
}
},
});
if let Some(default) = model
.map(str::to_string)
.or_else(|| catalog.first().cloned())
{
config["model"] = serde_json::json!(format!("bitrouter/{default}"));
}
if !mcp.is_empty() {
let mut entries = serde_json::Map::new();
for s in mcp {
let entry = match &s.transport {
// opencode folds command+args into one invocation array.
McpTransport::Stdio { command, args } => {
let mut invocation = vec![command.clone()];
invocation.extend(args.iter().cloned());
serde_json::json!({ "type": "local", "command": invocation, "enabled": true })
}
McpTransport::Http { url, headers } => serde_json::json!({
"type": "remote",
"url": url,
"enabled": true,
"headers": headers_map(headers),
}),
};
entries.insert(s.name.clone(), entry);
}
config["mcp"] = serde_json::Value::Object(entries);
}
config
}
/// Resolve the gateway credential by precedence: a real `BITROUTER_API_KEY`
/// (`brk_…`) when exported, else the local placeholder. Returns `None` only
/// when `require_key` is set (daemon auth is on) and no real key is present —
/// the caller then fails fast (`SPAWN_SPEC` §5.4).
pub fn resolve_gateway_auth(bitrouter_key: Option<String>, require_key: bool) -> Option<String> {
match bitrouter_key {
Some(key) => Some(key),
None if require_key => None,
None => Some(PLACEHOLDER_API_KEY.to_string()),
}
}
/// The Codex `-c` provider-override overlay. Mirrors the interactive
/// `bitrouter launch` codex wiring so both facets route identically.
fn codex_overlay(base_url: &str, auth: &str, model: Option<&str>) -> RoutingOverlay {
let mut env = Vec::new();
let mut args = vec![
"-c".to_string(),
codex_config_string("model_provider", "bitrouter"),
"-c".to_string(),
codex_config_string("model_providers.bitrouter.name", "BitRouter"),
"-c".to_string(),
codex_config_string("model_providers.bitrouter.base_url", &v1_base_url(base_url)),
"-c".to_string(),
codex_config_string("model_providers.bitrouter.wire_api", "responses"),
];
// Real key → env_key indirection (keeps the secret out of argv/process
// listing); placeholder → inline experimental_bearer_token.
if auth == PLACEHOLDER_API_KEY {
args.push("-c".to_string());
args.push(codex_config_string(
"model_providers.bitrouter.experimental_bearer_token",
PLACEHOLDER_API_KEY,
));
} else {
env.push((BITROUTER_API_KEY_ENV.to_string(), auth.to_string()));
args.push("-c".to_string());
args.push(codex_config_string(
"model_providers.bitrouter.env_key",
BITROUTER_API_KEY_ENV,
));
}
if let Some(m) = model {
args.push("-c".to_string());
args.push(codex_config_string("model", m));
}
RoutingOverlay { env, args }
}
/// `/v1`-suffixed base URL — the shape codex custom providers, opencode's
/// openai-compatible provider, and pi's `baseUrl` all expect.
fn v1_base_url(base_url: &str) -> String {
let trimmed = base_url.trim_end_matches('/');
if trimmed.ends_with("/v1") {
trimmed.to_string()
} else {
format!("{trimmed}/v1")
}
}
fn codex_config_string(key: &str, value: &str) -> String {
format!("{key}={}", toml_string(value))
}
/// Quote a value as a TOML basic string for a `-c key=value` override.
fn toml_string(value: &str) -> String {
let mut out = String::with_capacity(value.len() + 2);
out.push('"');
for ch in value.chars() {
match ch {
'\\' => out.push_str("\\\\"),
'"' => out.push_str("\\\""),
'\n' => out.push_str("\\n"),
'\r' => out.push_str("\\r"),
'\t' => out.push_str("\\t"),
other => out.push(other),
}
}
out.push('"');
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn catalog_ids_are_unique() {
let mut ids: Vec<_> = CATALOG.iter().map(|h| h.id).collect();
ids.sort_unstable();
let before = ids.len();
ids.dedup();
assert_eq!(before, ids.len(), "catalog ids must be unique");
}
#[test]
fn by_interactive_binary_finds_the_orchestrator_harnesses() {
assert_eq!(by_interactive_binary("claude").unwrap().id, "claude-acp");
assert_eq!(by_interactive_binary("codex").unwrap().id, "codex-acp");
assert_eq!(by_interactive_binary("opencode").unwrap().id, "opencode");
assert_eq!(by_interactive_binary("pi").unwrap().id, "pi-acp");
assert_eq!(by_interactive_binary("hermes").unwrap().id, "hermes-acp");
assert_eq!(by_interactive_binary("openclaw").unwrap().id, "openclaw");
assert_eq!(by_interactive_binary("grok").unwrap().id, "grok");
assert_eq!(by_interactive_binary("agy").unwrap().id, "antigravity");
assert!(by_interactive_binary("gemini").is_none());
}
#[test]
fn own_auth_harnesses_never_redirect_and_forward_model_natively() {
let dir = tempfile::tempdir().expect("tempdir");
for (id, flag) in [("grok", "-m"), ("antigravity", "--model")] {
let h = by_id(id).unwrap();
assert!(!h.env_args_routable(), "{id} launches with its own auth");
assert!(h.acp_command.is_none(), "{id} has no ACP adapter");
assert_eq!(
h.routing_overlay("http://x:1", "t", None),
RoutingOverlay::default()
);
// The orchestrator overlay sets no env (no redirection) and
// forwards --model as the harness's native flag.
let o = h
.orchestrator_overlay(
"http://x:1",
"t",
Some("some-model"),
&[],
&[mcp()],
dir.path(),
)
.expect("overlay");
assert!(o.env.is_empty(), "{id}: no redirection env");
assert_eq!(o.args, vec![flag, "some-model"], "{id}");
let bare = h
.orchestrator_overlay("http://x:1", "t", None, &[], &[], dir.path())
.expect("overlay");
assert_eq!(bare, RoutingOverlay::default(), "{id}: bare launch");
}
}
#[test]
fn match_invocation_maps_renamed_key_by_package_marker() {
// A user-renamed entry ("my-claude") still maps to claude-acp routing.
let h = match_invocation(
"npx",
&[
"-y".to_string(),
"@zed-industries/claude-code-acp@latest".to_string(),
],
)
.expect("matches claude-acp");
assert_eq!(h.id, "claude-acp");
}
#[test]
fn match_invocation_none_for_unknown_command() {
assert!(match_invocation("./my-custom-agent", &[]).is_none());
}
#[test]
fn match_invocation_matches_globally_installed_binary_command() {
// A `command: claude-code-acp` (npm -g binary) must catalog-match the
// same as the `npx @zed-industries/claude-code-acp` package form.
assert_eq!(
match_invocation("claude-code-acp", &[]).unwrap().id,
"claude-acp"
);
assert_eq!(
match_invocation("gemini-cli", &[]).unwrap().id,
"gemini-cli"
);
assert_eq!(match_invocation("codex-acp", &[]).unwrap().id, "codex-acp");
}
#[test]
fn catalog_markers_are_mutually_non_substrings() {
// A false-positive would mis-route one harness as another.
for a in CATALOG {
for b in CATALOG {
if a.id != b.id {
assert!(
!a.package_marker.contains(b.package_marker),
"marker '{}' contains '{}'",
a.package_marker,
b.package_marker
);
}
}
}
}
#[test]
fn auth_is_bearer_flags_gemini_as_non_bearer() {
assert!(by_id("claude-acp").unwrap().auth_is_bearer());
assert!(by_id("codex-acp").unwrap().auth_is_bearer());
assert!(!by_id("gemini-cli").unwrap().auth_is_bearer());
}
#[test]
fn supports_model_pin_reflects_catalog() {
assert!(by_id("claude-acp").unwrap().supports_model_pin());
assert!(by_id("codex-acp").unwrap().supports_model_pin());
assert!(by_id("gemini-cli").unwrap().supports_model_pin());
assert!(!by_id("pi-acp").unwrap().supports_model_pin());
}
#[test]
fn claude_overlay_sets_base_url_and_bearer_token() {
let h = by_id("claude-acp").unwrap();
let o = h.routing_overlay("http://127.0.0.1:4356", "brk_real", None);
assert!(o.env.contains(&(
"ANTHROPIC_BASE_URL".to_string(),
"http://127.0.0.1:4356".to_string()
)));
assert!(
o.env
.contains(&("ANTHROPIC_AUTH_TOKEN".to_string(), "brk_real".to_string()))
);
// Never the x-api-key var.
assert!(o.env.iter().all(|(k, _)| k != "ANTHROPIC_API_KEY"));
assert!(o.args.is_empty());
}
#[test]
fn claude_overlay_pins_model_when_given() {
let h = by_id("claude-acp").unwrap();
let o = h.routing_overlay("http://x:1", "t", Some("claude-sonnet-5"));
assert!(
o.env
.contains(&("ANTHROPIC_MODEL".to_string(), "claude-sonnet-5".to_string()))
);
// Absent when no model requested.
let o2 = h.routing_overlay("http://x:1", "t", None);
assert!(o2.env.iter().all(|(k, _)| k != "ANTHROPIC_MODEL"));
}
#[test]
fn codex_overlay_routes_responses_to_v1_and_uses_env_key_for_real_key() {
let h = by_id("codex-acp").unwrap();
let o = h.routing_overlay("http://127.0.0.1:4356", "brk_real", None);
assert!(o.args.contains(&"model_provider=\"bitrouter\"".to_string()));
assert!(o.args.contains(
&"model_providers.bitrouter.base_url=\"http://127.0.0.1:4356/v1\"".to_string()
));
assert!(
o.args
.contains(&"model_providers.bitrouter.wire_api=\"responses\"".to_string())
);
assert!(
o.args
.contains(&"model_providers.bitrouter.env_key=\"BITROUTER_API_KEY\"".to_string())
);
assert!(
o.env
.contains(&("BITROUTER_API_KEY".to_string(), "brk_real".to_string()))
);
assert!(
o.args
.iter()
.all(|a| !a.contains("experimental_bearer_token"))
);
}
#[test]
fn codex_overlay_uses_inline_token_for_placeholder() {
let h = by_id("codex-acp").unwrap();
let o = h.routing_overlay("http://127.0.0.1:4356", PLACEHOLDER_API_KEY, None);
assert!(o.args.contains(
&"model_providers.bitrouter.experimental_bearer_token=\"bitrouter-local\"".to_string()
));
assert!(o.env.iter().all(|(k, _)| k != "BITROUTER_API_KEY"));
}
#[test]
fn codex_overlay_pins_model() {
let h = by_id("codex-acp").unwrap();
let o = h.routing_overlay("http://x:1", PLACEHOLDER_API_KEY, Some("gpt-5.2"));
assert!(o.args.contains(&"model=\"gpt-5.2\"".to_string()));
}
#[test]
fn config_synthesis_harnesses_have_no_pure_overlay() {
for id in ["pi-acp", "opencode"] {
let h = by_id(id).unwrap();
assert!(!h.env_args_routable(), "{id} routes by synthesis only");
assert_eq!(
h.routing_overlay("http://x:1", "t", None),
RoutingOverlay::default(),
"{id}"
);
}
assert!(by_id("claude-acp").unwrap().env_args_routable());
assert!(by_id("codex-acp").unwrap().env_args_routable());
}
// ── Orchestrator overlays (TUI facet). ──
fn mcp() -> McpServer {
McpServer {
name: "bitrouter_fleet".into(),
transport: McpTransport::Stdio {
command: "/bin/bitrouter".into(),
args: vec![
"mcp".into(),
"serve".into(),
"--backend".into(),
"fleet".into(),
],
},
}
}
/// An HTTP gateway server (the `bitrouter_tools` shape) for the
/// synthesizer tests.
fn tools() -> McpServer {
McpServer {
name: "bitrouter_tools".into(),
transport: McpTransport::Http {
url: "http://127.0.0.1:4356/mcp".into(),
headers: vec![("Authorization".into(), "Bearer tok".into())],
},
}
}
#[test]
fn claude_orchestrator_overlay_writes_mcp_config_and_flag() {
let dir = tempfile::tempdir().expect("tempdir");
let h = by_id("claude-acp").unwrap();
let o = h
.orchestrator_overlay("http://x:1", "t", None, &[], &[mcp(), tools()], dir.path())
.expect("overlay");
assert_eq!(o.args[0], "--mcp-config");
let config: serde_json::Value =
serde_json::from_str(&std::fs::read_to_string(&o.args[1]).expect("config written"))
.expect("json");
// Stdio entry: bare command/args.
assert_eq!(
config["mcpServers"]["bitrouter_fleet"]["command"],
"/bin/bitrouter"
);
assert_eq!(config["mcpServers"]["bitrouter_fleet"]["args"][3], "fleet");
// HTTP entry: explicit type (a url without type is a hard error in
// Claude Code) plus the auth header as an object.
let tools = &config["mcpServers"]["bitrouter_tools"];
assert_eq!(tools["type"], "http");
assert_eq!(tools["url"], "http://127.0.0.1:4356/mcp");
assert_eq!(tools["headers"]["Authorization"], "Bearer tok");
// Routing env comes through unchanged.
assert!(o.env.iter().any(|(k, _)| k == "ANTHROPIC_BASE_URL"));
}
#[test]
fn codex_orchestrator_overlay_appends_mcp_toml_overrides() {
let dir = tempfile::tempdir().expect("tempdir");
let h = by_id("codex-acp").unwrap();
let o = h
.orchestrator_overlay("http://x:1", "t", None, &[], &[mcp(), tools()], dir.path())
.expect("overlay");
assert!(
o.args
.contains(&"mcp_servers.bitrouter_fleet.command=\"/bin/bitrouter\"".to_string()),
"{:?}",
o.args
);
assert!(
o.args.contains(
&"mcp_servers.bitrouter_fleet.args=[\"mcp\",\"serve\",\"--backend\",\"fleet\"]"
.to_string()
),
"{:?}",
o.args
);
// HTTP entry: url selects the streamable-HTTP transport, auth rides
// http_headers.
assert!(
o.args.contains(
&"mcp_servers.bitrouter_tools.url=\"http://127.0.0.1:4356/mcp\"".to_string()
),
"{:?}",
o.args
);
assert!(
o.args.contains(
&"mcp_servers.bitrouter_tools.http_headers.Authorization=\"Bearer tok\""
.to_string()
),
"{:?}",
o.args
);
}
#[test]
fn hermes_orchestrator_overlay_synthesizes_home_dir() {
let dir = tempfile::tempdir().expect("tempdir");
let h = by_id("hermes-acp").unwrap();
let o = h
.orchestrator_overlay(
"http://127.0.0.1:4356",
"tok",
Some("supergrok:grok-4.5"),
&[],
&[mcp(), tools()],
dir.path(),
)
.expect("overlay");
assert!(o.args.is_empty(), "hermes routes purely by config");
let env: std::collections::HashMap<_, _> = o.env.iter().cloned().collect();
assert_eq!(env["CUSTOM_API_KEY"], "tok");
let home = std::path::PathBuf::from(&env["HERMES_HOME"]);
// JSON body in config.yaml — YAML 1.2 parses JSON, no yaml dep needed.
let config: serde_json::Value =
serde_json::from_str(&std::fs::read_to_string(home.join("config.yaml")).expect("read"))
.expect("json");
assert_eq!(config["model"]["provider"], "custom");
assert_eq!(config["model"]["base_url"], "http://127.0.0.1:4356/v1");
assert_eq!(config["model"]["default"], "supergrok:grok-4.5");
assert_eq!(
config["mcp_servers"]["bitrouter_fleet"]["command"],
"/bin/bitrouter"
);
// HTTP entry: url presence selects the transport; auth is a header.
let tools = &config["mcp_servers"]["bitrouter_tools"];
assert_eq!(tools["url"], "http://127.0.0.1:4356/mcp");
assert_eq!(tools["headers"]["Authorization"], "Bearer tok");
assert!(tools.get("command").is_none(), "http entry has no command");
}
#[test]
fn openclaw_orchestrator_overlay_synthesizes_profile() {
let dir = tempfile::tempdir().expect("tempdir");
let h = by_id("openclaw").unwrap();
let o = h
.orchestrator_overlay(
"http://127.0.0.1:4356",
"tok",
Some("supergrok:grok-4.5"),
&["x-ai/grok-4.5".to_string()],
&[],
dir.path(),
)
.expect("overlay");
assert_eq!(
o.args,
vec!["tui".to_string(), "--local".to_string()],
"embedded runtime, no gateway"
);
let env: std::collections::HashMap<_, _> = o.env.iter().cloned().collect();
let config: serde_json::Value = serde_json::from_str(
&std::fs::read_to_string(&env["OPENCLAW_CONFIG_PATH"]).expect("read"),
)
.expect("json");
let provider = &config["models"]["providers"]["bitrouter"];
assert_eq!(provider["baseUrl"], "http://127.0.0.1:4356/v1");
assert_eq!(provider["apiKey"], "tok");
assert_eq!(provider["api"], "openai-completions");
// Full model entries (config validation rejects bare ids), pinned
// model first and default.
assert_eq!(provider["models"][0]["id"], "supergrok:grok-4.5");
assert_eq!(provider["models"][1]["id"], "x-ai/grok-4.5");
assert!(provider["models"][0]["cost"].is_object());
assert_eq!(
config["agents"]["defaults"]["model"],
"bitrouter/supergrok:grok-4.5"
);
assert!(env.contains_key("OPENCLAW_STATE_DIR"));
}
#[test]
fn opencode_orchestrator_overlay_synthesizes_one_config_file() {
let dir = tempfile::tempdir().expect("tempdir");
let h = by_id("opencode").unwrap();
let catalog = vec!["x-ai/grok-4.5".to_string()];
let o = h
.orchestrator_overlay(
"http://127.0.0.1:4356",
"tok",
Some("supergrok:grok-4.5"),
&catalog,
&[mcp(), tools()],
dir.path(),
)
.expect("overlay");
let (key, path) = &o.env[0];
assert_eq!(key, "OPENCODE_CONFIG");
assert!(o.args.is_empty(), "opencode routes purely by config file");
let config: serde_json::Value =
serde_json::from_str(&std::fs::read_to_string(path).expect("written")).expect("json");
assert_eq!(
config["provider"]["bitrouter"]["options"]["baseURL"],
"http://127.0.0.1:4356/v1"
);
// The pinned model is the default and joins the catalog list.
assert_eq!(config["model"], "bitrouter/supergrok:grok-4.5");
assert!(config["provider"]["bitrouter"]["models"]["supergrok:grok-4.5"].is_object());
assert!(config["provider"]["bitrouter"]["models"]["x-ai/grok-4.5"].is_object());
// The MCP bridge rides the same file, command+args folded into one
// invocation array.
assert_eq!(config["mcp"]["bitrouter_fleet"]["type"], "local");
assert_eq!(
config["mcp"]["bitrouter_fleet"]["command"][0],
"/bin/bitrouter"
);
// HTTP entry: opencode's remote type with the auth header.
let tools = &config["mcp"]["bitrouter_tools"];
assert_eq!(tools["type"], "remote");
assert_eq!(tools["url"], "http://127.0.0.1:4356/mcp");
assert_eq!(tools["enabled"], true);
assert_eq!(tools["headers"]["Authorization"], "Bearer tok");
}
#[test]
fn opencode_overlay_defaults_model_to_catalog_head() {
let dir = tempfile::tempdir().expect("tempdir");
let h = by_id("opencode").unwrap();
let catalog = vec!["a/one".to_string(), "b/two".to_string()];
let o = h
.orchestrator_overlay("http://x:1", "t", None, &catalog, &[], dir.path())
.expect("overlay");
let config: serde_json::Value =
serde_json::from_str(&std::fs::read_to_string(&o.env[0].1).expect("written"))
.expect("json");
assert_eq!(config["model"], "bitrouter/a/one");
assert!(config.get("mcp").is_none(), "no servers requested");
}
#[test]
fn pi_orchestrator_overlay_synthesizes_agent_dir_and_flags() {
let dir = tempfile::tempdir().expect("tempdir");
let h = by_id("pi-acp").unwrap();
let catalog = vec!["x-ai/grok-4.5".to_string()];
let o = h
.orchestrator_overlay(
"http://127.0.0.1:4356",
"tok",
Some("supergrok:grok-4.5"),
&catalog,
&[mcp(), tools()], // pi has no MCP mechanism — ignored
dir.path(),
)
.expect("overlay");
let (key, agent_dir) = &o.env[0];
assert_eq!(key, "PI_CODING_AGENT_DIR");
let models: serde_json::Value = serde_json::from_str(
&std::fs::read_to_string(std::path::Path::new(agent_dir).join("models.json"))
.expect("models.json written"),
)
.expect("json");
let provider = &models["providers"]["bitrouter"];
assert_eq!(provider["baseUrl"], "http://127.0.0.1:4356/v1");
assert_eq!(provider["api"], "openai-completions");
assert_eq!(provider["apiKey"], "tok");
// Catalog + the pinned model, deduped.
assert_eq!(provider["models"][0]["id"], "x-ai/grok-4.5");
assert_eq!(provider["models"][1]["id"], "supergrok:grok-4.5");
assert_eq!(
o.args,
vec!["--provider", "bitrouter", "--model", "supergrok:grok-4.5"]
);
}
#[test]
fn pi_overlay_without_any_model_selects_nothing() {
let dir = tempfile::tempdir().expect("tempdir");
let h = by_id("pi-acp").unwrap();
let o = h
.orchestrator_overlay("http://x:1", "t", None, &[], &[], dir.path())
.expect("overlay");
assert!(
o.args.is_empty(),
"no routable model — pi keeps its own defaults"
);
}
#[test]
fn resolve_gateway_auth_precedence() {
// Real key wins.
assert_eq!(
resolve_gateway_auth(Some("brk_x".into()), false).as_deref(),
Some("brk_x")
);
// No key, auth off → placeholder.
assert_eq!(
resolve_gateway_auth(None, false).as_deref(),
Some(PLACEHOLDER_API_KEY)
);
// No key, auth required → None (caller fails fast).
assert_eq!(resolve_gateway_auth(None, true), None);
// Real key satisfies required auth.
assert_eq!(
resolve_gateway_auth(Some("brk_x".into()), true).as_deref(),
Some("brk_x")
);
}
}