ilink-hub 0.3.0

iLink-compatible multiplexer hub for WeChat ClawBot — route one WeChat account to multiple AI agent backends
Documentation
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
//! Bridge YAML: single-profile (legacy) or multi-profile with routing.

use std::collections::HashMap;
use std::path::Path;

use anyhow::{Context, Result};
use serde::Deserialize;

/// How to pick a profile for each inbound text message (multi-profile YAML only).
#[derive(Debug, Clone, Deserialize, PartialEq, Eq, Default)]
#[serde(rename_all = "snake_case")]
pub enum RoutingStrategy {
    /// Always run `default_profile`; inbound text is passed unchanged to `{{MESSAGE}}`.
    #[default]
    Fixed,
    /// First matching `prefix_rules` wins (order matters; put longer prefixes first).
    /// The matched prefix is stripped from the string used for `{{MESSAGE}}` / stdin.
    Prefix,
}

#[derive(Debug, Deserialize)]
pub struct PrefixRuleYaml {
    pub prefix: String,
    pub profile: String,
}

#[derive(Debug, Deserialize)]
pub struct BridgeRoutingYaml {
    #[serde(default)]
    pub strategy: RoutingStrategy,
    pub default_profile: String,
    #[serde(default)]
    pub prefix_rules: Vec<PrefixRuleYaml>,
}

#[derive(Debug, Deserialize)]
pub struct BridgeMultiYaml {
    #[serde(default = "default_true")]
    pub skip_bot_messages: bool,
    #[serde(default = "default_true")]
    pub require_text: bool,
    #[serde(default = "default_true")]
    pub send_error_reply: bool,
    pub profiles: HashMap<String, BridgeProfile>,
    /// Optional: if omitted, routing defaults to `fixed` with the profile named
    /// `claude` (if present), then `default`, then the first alphabetically.
    #[serde(default)]
    pub routing: Option<BridgeRoutingYaml>,
}

/// Per-profile CLI settings (multi-profile YAML) or the only profile (legacy single file).
///
/// **`type` shorthand**: set `type: claude-code` to use a built-in profile.
///
/// **`script` shorthand**: set `script: ./my-handler.py` (or `.js`, `.sh`, `.ts`, `.rb`) and
/// bridge infers the runtime automatically:
/// - `.py`  → `python3 <script>`
/// - `.js` / `.mjs` → `node <script>`
/// - `.ts`  → `npx tsx <script>`
/// - `.sh`  → `bash <script>`
/// - `.rb`  → `ruby <script>`
/// - other  → execute directly (must be chmod +x)
///
/// An explicit `command` always wins over `type` / `script`.
#[derive(Debug, Clone, Deserialize)]
pub struct BridgeProfile {
    /// Optional built-in type shorthand (e.g. `"claude-code"`).
    /// When set and `command` is empty, the profile is expanded to the corresponding built-in.
    #[serde(default, rename = "type")]
    pub profile_type: Option<String>,

    /// Path to a script file. Bridge infers the runtime from the file extension.
    /// Expanded to `command` + `args` at load time. An explicit `command` takes priority.
    #[serde(default)]
    pub script: Option<String>,

    #[serde(default)]
    pub command: String,
    #[serde(default)]
    pub args: Vec<String>,
    /// Working directory for the agent process. Relative paths resolve against
    /// `{{PROFILE_DIR}}` (the profile file's directory); omitted defaults to the
    /// bridge's process cwd. `~` and placeholders are expanded.
    #[serde(default)]
    pub cwd: Option<String>,
    #[serde(default)]
    pub env: HashMap<String, String>,
    /// Restrict which `${VAR}` references the `env` block may expand against the
    /// bridge's environment. Absent = expand against the full environment (profiles
    /// are trusted input). Present = a `${VAR}` not in the list expands to empty
    /// with a stderr warning. Names must match exactly (no globbing).
    #[serde(default)]
    pub env_allowlist: Option<Vec<String>>,
    /// CLI 主操作超时(秒),只覆盖 stdout 读取阶段。子进程退出后还有额外的
    /// 10s `child.wait()` 等待,因此最坏情况总耗时为 `timeout_secs + 10s`。
    /// 默认 1800s(30 分钟)。
    #[serde(default = "default_timeout_secs")]
    pub timeout_secs: u64,
    /// SIGTERM → SIGKILL 宽限期(秒),默认 5。
    #[serde(default = "default_kill_grace_secs")]
    pub kill_grace_secs: u64,
    #[serde(default = "default_max_reply_chars")]
    pub max_reply_chars: usize,
    #[serde(default = "default_truncation_suffix")]
    pub truncation_suffix: String,
    #[serde(default)]
    pub include_stderr_in_reply: bool,
    /// 是否启用流式 partial 转发(bridge 侧 hint,不进 wire)。默认 `true`。
    /// 设为 `false` 时,agent 仍会输出 `{"type":"partial"}` 事件,但 bridge
    /// 不转发,只从 `{"type":"result"}` 事件取最终回复一次性发送。
    #[serde(default = "default_true")]
    pub streaming: bool,
    /// 启用可选的 tool-permission 通道(agentproc 0.4)。默认 `false`,bridge
    /// 写完 turn 对象即关闭 stdin;`true` 时保持 stdin 开着,处理
    /// `{"type":"permission_request"}` 并写回 `{"type":"permission_response"}`。
    #[serde(default)]
    pub permission: bool,
    /// 当 permission 通道开启但没有交互式用户批准闭环时,bridge 对每个
    /// permission_request 的默认动作。默认 `allow`(等价 skip-permissions)。
    /// `ask` 暂停 turn,经微信问用户允许/拒绝。
    #[serde(default)]
    pub permission_default: super::protocol::PermissionDefaultPolicy,
    /// `permission_default: ask` 时,等待用户微信回复的最长秒数;超时后
    /// 自动 deny 并提示用户「授权超时已拒绝」。默认 600s(10 分钟)。
    #[serde(default = "default_permission_ask_timeout_secs")]
    pub permission_ask_timeout_secs: u64,
    /// Agent 描述(用于 Hub MCP list_agents 工具返回,让其他 Agent 了解此 Agent 的能力)。
    #[serde(default)]
    pub description: Option<String>,
}

impl Default for BridgeProfile {
    fn default() -> Self {
        Self {
            profile_type: None,
            script: None,
            command: String::new(),
            args: Vec::new(),
            cwd: None,
            env: HashMap::new(),
            env_allowlist: None,
            timeout_secs: default_timeout_secs(),
            kill_grace_secs: default_kill_grace_secs(),
            max_reply_chars: default_max_reply_chars(),
            truncation_suffix: default_truncation_suffix(),
            include_stderr_in_reply: false,
            streaming: true,
            permission: false,
            permission_default: super::protocol::PermissionDefaultPolicy::default(),
            permission_ask_timeout_secs: default_permission_ask_timeout_secs(),
            description: None,
        }
    }
}

fn default_timeout_secs() -> u64 {
    1800
}

fn default_kill_grace_secs() -> u64 {
    5
}

fn default_max_reply_chars() -> usize {
    8000
}

fn default_truncation_suffix() -> String {
    "\n\n…(输出已截断)".to_string()
}

fn default_permission_ask_timeout_secs() -> u64 {
    600
}

fn default_true() -> bool {
    true
}

/// Legacy flat YAML (one `command`, optional global flags).
#[derive(Debug, Clone, Deserialize)]
pub struct BridgeConfig {
    pub command: String,
    #[serde(default)]
    pub args: Vec<String>,
    #[serde(default)]
    pub cwd: Option<String>,
    #[serde(default)]
    pub env: HashMap<String, String>,
    #[serde(default)]
    pub env_allowlist: Option<Vec<String>>,
    #[serde(default = "default_timeout_secs")]
    pub timeout_secs: u64,
    #[serde(default = "default_kill_grace_secs")]
    pub kill_grace_secs: u64,
    #[serde(default = "default_max_reply_chars")]
    pub max_reply_chars: usize,
    #[serde(default = "default_truncation_suffix")]
    pub truncation_suffix: String,
    #[serde(default = "default_true")]
    pub skip_bot_messages: bool,
    #[serde(default = "default_true")]
    pub require_text: bool,
    #[serde(default = "default_true")]
    pub send_error_reply: bool,
    #[serde(default)]
    pub include_stderr_in_reply: bool,
    #[serde(default = "default_true")]
    pub streaming: bool,
    #[serde(default)]
    pub permission: bool,
    #[serde(default)]
    pub permission_default: super::protocol::PermissionDefaultPolicy,
    #[serde(default = "default_permission_ask_timeout_secs")]
    pub permission_ask_timeout_secs: u64,
    /// Agent 描述(用于 Hub MCP list_agents 工具返回,让其他 Agent 了解此 Agent 的能力)。
    #[serde(default)]
    pub description: Option<String>,
}

impl BridgeConfig {
    pub fn validate(&self) -> Result<()> {
        if self.command.trim().is_empty() {
            anyhow::bail!("`command` must not be empty");
        }
        Ok(())
    }
}

#[derive(Debug, Deserialize)]
#[serde(untagged)]
enum BridgeFileRaw {
    /// Must contain top-level `profiles` + `routing`.
    Multi(BridgeMultiYaml),
    Single(BridgeConfig),
}

#[derive(Debug, Clone)]
enum RoutingState {
    Fixed(String),
    Prefix {
        default: String,
        rules: Vec<(String, String)>,
    },
}

/// Loaded bridge configuration: either migrated from a single flat file or from multi-profile YAML.
#[derive(Debug, Clone)]
pub struct BridgeApp {
    profiles: HashMap<String, BridgeProfile>,
    routing: RoutingState,
    pub skip_bot_messages: bool,
    pub require_text: bool,
    pub send_error_reply: bool,
}

impl BridgeApp {
    pub fn load(path: impl AsRef<Path>) -> Result<Self> {
        let path = path.as_ref();
        let raw =
            std::fs::read_to_string(path).with_context(|| format!("read {}", path.display()))?;
        Self::parse_yaml(&raw).with_context(|| format!("parse YAML {}", path.display()))
    }

    /// Parse YAML from a string (same as file body). Used by tests and for tooling.
    pub fn parse_yaml(raw: &str) -> Result<Self> {
        let file: BridgeFileRaw =
            serde_norway::from_str(raw).context("serde_norway::from_str BridgeFileRaw")?;
        match file {
            BridgeFileRaw::Single(c) => Self::from_single(c),
            BridgeFileRaw::Multi(m) => Self::from_multi(m),
        }
    }

    fn from_single(c: BridgeConfig) -> Result<Self> {
        c.validate()?;
        let profile = BridgeProfile {
            profile_type: None,
            script: None,
            command: c.command.clone(),
            args: c.args.clone(),
            cwd: c.cwd.clone(),
            env: c.env.clone(),
            env_allowlist: c.env_allowlist.clone(),
            timeout_secs: c.timeout_secs,
            kill_grace_secs: c.kill_grace_secs,
            max_reply_chars: c.max_reply_chars,
            truncation_suffix: c.truncation_suffix.clone(),
            include_stderr_in_reply: c.include_stderr_in_reply,
            streaming: c.streaming,
            permission: c.permission,
            permission_default: c.permission_default,
            permission_ask_timeout_secs: c.permission_ask_timeout_secs,
            description: c.description,
        };
        reject_shell_injection_risk(&profile, "default")?;
        let mut profiles = HashMap::new();
        profiles.insert("default".to_string(), profile);
        Ok(Self {
            profiles,
            routing: RoutingState::Fixed("default".to_string()),
            skip_bot_messages: c.skip_bot_messages,
            require_text: c.require_text,
            send_error_reply: c.send_error_reply,
        })
    }

    fn from_multi(m: BridgeMultiYaml) -> Result<Self> {
        if m.profiles.is_empty() {
            anyhow::bail!("`profiles` must contain at least one profile");
        }
        // Expand script/type shortcuts before validation so `command` is filled in.
        // Order matters: script → type (explicit command wins over both).
        let profiles: HashMap<String, BridgeProfile> = m
            .profiles
            .into_iter()
            .map(|(name, p)| {
                let expanded = expand_script_field(p, &name)?;
                let expanded = expand_profile_type(expanded, &name)?;
                Ok((name, expanded))
            })
            .collect::<Result<_>>()?;

        for (name, p) in &profiles {
            if p.command.trim().is_empty() {
                anyhow::bail!(
                    "profile `{name}`: `command` must not be empty \
                     (set `command`, `script`, or use a recognized `type`)"
                );
            }
            reject_shell_injection_risk(p, name)?;
        }

        // Resolve routing: if omitted, auto-detect fixed routing using a sensible default.
        let routing_cfg = m.routing.unwrap_or_else(|| {
            let default = if profiles.contains_key("claude") {
                "claude".to_string()
            } else if profiles.contains_key("default") {
                "default".to_string()
            } else {
                let mut keys: Vec<&String> = profiles.keys().collect();
                keys.sort();
                keys[0].clone()
            };
            BridgeRoutingYaml {
                strategy: RoutingStrategy::Fixed,
                default_profile: default,
                prefix_rules: vec![],
            }
        });

        if !profiles.contains_key(&routing_cfg.default_profile) {
            anyhow::bail!(
                "routing.default_profile `{}` is not a key in `profiles`",
                routing_cfg.default_profile
            );
        }
        for (i, rule) in routing_cfg.prefix_rules.iter().enumerate() {
            if rule.prefix.is_empty() {
                anyhow::bail!("routing.prefix_rules[{i}]: `prefix` must not be empty");
            }
            if !profiles.contains_key(&rule.profile) {
                anyhow::bail!(
                    "routing.prefix_rules[{i}]: unknown profile `{}`",
                    rule.profile
                );
            }
        }
        if routing_cfg.strategy == RoutingStrategy::Prefix && routing_cfg.prefix_rules.is_empty() {
            anyhow::bail!("routing.strategy: `prefix` requires at least one `prefix_rules` entry (or use `fixed`)");
        }

        let routing = match routing_cfg.strategy {
            RoutingStrategy::Fixed => RoutingState::Fixed(routing_cfg.default_profile.clone()),
            RoutingStrategy::Prefix => RoutingState::Prefix {
                default: routing_cfg.default_profile.clone(),
                rules: routing_cfg
                    .prefix_rules
                    .iter()
                    .map(|r| (r.prefix.clone(), r.profile.clone()))
                    .collect(),
            },
        };

        Ok(Self {
            profiles,
            routing,
            skip_bot_messages: m.skip_bot_messages,
            require_text: m.require_text,
            send_error_reply: m.send_error_reply,
        })
    }

    /// Pick profile and payload text for CLI (after Hub routing; `text` is usually `msg.text()`).
    pub fn resolve<'a>(&'a self, text: &str) -> Result<(&'a str, &'a BridgeProfile, String)> {
        match &self.routing {
            RoutingState::Fixed(name) => {
                let p = self
                    .profiles
                    .get(name)
                    .with_context(|| format!("internal: missing profile `{name}`"))?;
                Ok((name.as_str(), p, text.to_string()))
            }
            RoutingState::Prefix { default, rules } => {
                for (prefix, pname) in rules {
                    if text.starts_with(prefix) {
                        let p = self.profiles.get(pname).with_context(|| {
                            format!("internal: prefix rule references missing profile `{pname}`")
                        })?;
                        let rest = text[prefix.len()..].trim_start().to_string();
                        return Ok((pname.as_str(), p, rest));
                    }
                }
                let p = self
                    .profiles
                    .get(default)
                    .with_context(|| format!("internal: missing default profile `{default}`"))?;
                Ok((default.as_str(), p, text.to_string()))
            }
        }
    }

    pub fn profile_names(&self) -> Vec<&str> {
        let mut v: Vec<&str> = self.profiles.keys().map(|s| s.as_str()).collect();
        v.sort();
        v
    }

    pub fn profile(&self, name: &str) -> Option<&BridgeProfile> {
        self.profiles.get(name)
    }

    pub fn default_profile_name(&self) -> &str {
        match &self.routing {
            RoutingState::Fixed(name) => name,
            RoutingState::Prefix { default, .. } => default,
        }
    }

    pub fn routing_label(&self) -> &'static str {
        match &self.routing {
            RoutingState::Fixed(_) => "fixed",
            RoutingState::Prefix { .. } => "prefix",
        }
    }
}

/// Expand a `script: <path>` field to `command` + `args` based on file extension.
///
/// | Extension            | Inferred runtime              |
/// |----------------------|-------------------------------|
/// | `.py`                | `python3 <script>`            |
/// | `.js` / `.mjs`       | `node <script>`               |
/// | `.ts`                | `npx tsx <script>`            |
/// | `.sh` / `.bash`      | `bash <script>`               |
/// | `.rb`                | `ruby <script>`               |
/// | other / no extension | execute directly (chmod +x)   |
///
/// If `command` is already set, returns the profile unchanged (explicit wins).
fn expand_script_field(mut p: BridgeProfile, name: &str) -> Result<BridgeProfile> {
    let Some(ref script) = p.script.clone() else {
        return Ok(p);
    };
    if !p.command.trim().is_empty() {
        // Explicit command wins; script field is informational only.
        return Ok(p);
    }
    let script_path = script.trim().to_string();
    let ext = std::path::Path::new(&script_path)
        .extension()
        .and_then(|e| e.to_str())
        .unwrap_or("")
        .to_lowercase();

    match ext.as_str() {
        "py" => {
            p.command = "python3".to_string();
            let mut args = vec![script_path];
            args.append(&mut p.args);
            p.args = args;
        }
        "js" | "mjs" | "cjs" => {
            p.command = "node".to_string();
            let mut args = vec![script_path];
            args.append(&mut p.args);
            p.args = args;
        }
        "ts" => {
            p.command = "npx".to_string();
            let mut args = vec!["tsx".to_string(), script_path];
            args.append(&mut p.args);
            p.args = args;
        }
        "sh" | "bash" => {
            p.command = "bash".to_string();
            let mut args = vec![script_path];
            args.append(&mut p.args);
            p.args = args;
        }
        "rb" => {
            p.command = "ruby".to_string();
            let mut args = vec![script_path];
            args.append(&mut p.args);
            p.args = args;
        }
        _ => {
            // No known extension: run as executable (requires chmod +x / shebang).
            p.command = script_path;
        }
    }
    tracing::debug!(
        profile = name,
        command = %p.command,
        "script: field expanded"
    );
    Ok(p)
}

/// Expand a `type: <shorthand>` profile into a full exec-mode profile.
///
/// All built-in types delegate to `ilink-hub-bridge profile <type>` so that
/// the handler runs in the same binary with minimal external dependencies.
///
/// | `type:`       | CLI required  | Session resume | Extra env vars accepted              |
/// |---------------|---------------|----------------|--------------------------------------|
/// | `claude-code` | `claude`      | ✓              | `ILINK_CLAUDE_MODEL`                 |
/// | `codex`       | `codex`       | ✗              | `ILINK_CODEX_MODEL`                  |
/// | `cursor`      | `cursor`      | ✓ (optional)   | `ILINK_CURSOR_MODEL`, `ILINK_CURSOR_WORKSPACE`, `ILINK_CURSOR_EXTRA_ARGS` |
/// | `agy`         | `agy`         | ✓              | `ILINK_AGY_MODEL`, `ILINK_AGY_ADD_DIR`, `ILINK_AGY_SANDBOX`, `ILINK_AGY_EXTRA_ARGS` |
/// | `recursive`   | `recursive`   | ✓              | `RECURSIVE_*` (see recursive bridge docs) |
///
/// If `profile_type` is `None` or the command is already set, returns the profile unchanged.
fn expand_profile_type(p: BridgeProfile, name: &str) -> Result<BridgeProfile> {
    let Some(ref pt) = p.profile_type.clone() else {
        return Ok(p);
    };
    if !p.command.trim().is_empty() {
        // Explicit command wins; type is informational only.
        return Ok(p);
    }

    /// Build the standard ilink-hub-bridge self-invocation for built-in profile types.
    /// Under agentproc 0.3 the bridge always writes the NDJSON turn object to the
    /// child's stdin, so no per-profile stdin wiring is needed.
    fn make_builtin(mut p: BridgeProfile, type_name: &str, _with_session: bool) -> BridgeProfile {
        p.command = "ilink-hub-bridge".to_string();
        p.args = vec!["profile".to_string(), type_name.to_string()];
        p
    }

    match pt.as_str() {
        "claude-code" => Ok(make_builtin(p, "claude-code", true)),
        "codebuddy-code" => Ok(make_builtin(p, "codebuddy-code", true)),
        "codex" => Ok(make_builtin(p, "codex", false)),
        "cursor" => Ok(make_builtin(p, "cursor", true)),
        "agy" => Ok(make_builtin(p, "agy", true)),
        "recursive" => Ok(make_builtin(p, "recursive", true)),
        other => anyhow::bail!(
            "profile `{name}`: unknown `type: {other}`; \
             supported built-in types: claude-code, codebuddy-code, codex, cursor, agy, recursive"
        ),
    }
}

/// Reject profiles with a dangerous shell-injection pattern:
/// a shell interpreter (bash/sh/zsh/fish/dash) as the command with `-c` as an
/// arg AND `{{MESSAGE}}` somewhere in the args — user input would be
/// interpolated into a shell command string, enabling arbitrary command
/// execution.
///
/// `tokio::process::Command` does NOT invoke a shell automatically, so this is
/// only dangerous when the user explicitly invokes a shell with `-c`.
/// Safe alternatives: pass the message via the stdin turn object (always done
/// under agentproc 0.3), or use a non-shell command.
///
/// Only the dangerous combo is rejected; shell + `-c` without `{{MESSAGE}}`,
/// or shell with no placeholder in args/env, still loads.
fn reject_shell_injection_risk(p: &BridgeProfile, name: &str) -> Result<()> {
    // Include common POSIX / busybox shells. Interpreters (python -c, etc.)
    // and wrapper cmds (env/nice) are out of this round's scope.
    const SHELL_CMDS: &[&str] = &[
        "bash", "sh", "zsh", "fish", "dash", "ksh", "mksh", "ash", "busybox",
    ];
    let cmd = std::path::Path::new(&p.command)
        .file_name()
        .and_then(|s| s.to_str())
        .unwrap_or(&p.command);
    if !SHELL_CMDS.contains(&cmd) {
        return Ok(());
    }
    let has_dash_c = p.args.iter().any(|a| arg_enables_shell_command_string(a));
    // MESSAGE in args OR env values is the same RCE class when paired with shell -c
    // (e.g. `bash -c "$MSG"` with `env: {MSG: "{{MESSAGE}}"}`).
    let has_message_placeholder = p.args.iter().any(|a| a.contains("{{MESSAGE}}"))
        || p.env.values().any(|v| v.contains("{{MESSAGE}}"));
    if has_dash_c && has_message_placeholder {
        anyhow::bail!(
            "profile `{name}`: SECURITY: shell command with `-c` and `{{{{MESSAGE}}}}` in args \
             or env is rejected — user input would be interpolated into a shell command string. \
             Use `stdin: message` to pass the message safely via stdin instead."
        );
    }
    Ok(())
}

/// True when `arg` enables shell's "run command string" mode (`-c`).
///
/// Matches exact `-c` and combined short options that include `c` after a
/// single leading `-` (e.g. `-lc`, `-ic`, `-xc`, `-cl`). Does **not** match
/// long options like `--color` (double-dash).
fn arg_enables_shell_command_string(arg: &str) -> bool {
    if arg == "-c" {
        return true;
    }
    // Single-dash short cluster only: `-` + one or more flag letters.
    if arg.starts_with('-') && !arg.starts_with("--") {
        return arg
            .as_bytes()
            .get(1..)
            .is_some_and(|flags| flags.contains(&b'c'));
    }
    false
}

/// Expand `${VAR}` placeholders in `template` using values from `env`.
///
/// Rules:
/// - `${IDENT}` → value of `IDENT` from `env`; error if not found (even empty string is ok)
/// - `$$` → literal `$`
/// - No other `$...` forms are recognised; they pass through unchanged
/// - Invalid tokens like `${}` or `${1FOO}` are errors
///
/// Only exercised by unit tests today; the production path calls
/// [`expand_env_var_named`] directly.
#[allow(dead_code)]
pub fn expand_env_var(
    template: &str,
    env: &std::collections::HashMap<String, String>,
) -> Result<String> {
    expand_env_var_named(template, env, None, None)
}

/// Same as [`expand_env_var`] but includes profile/field context in error messages.
pub fn expand_env_var_named(
    template: &str,
    env: &std::collections::HashMap<String, String>,
    profile: Option<&str>,
    field: Option<&str>,
) -> Result<String> {
    let mut out = String::with_capacity(template.len());
    let bytes = template.as_bytes();
    let len = bytes.len();
    let mut i = 0;

    while i < len {
        if bytes[i] != b'$' {
            out.push(bytes[i] as char);
            i += 1;
            continue;
        }

        // We have a `$`
        if i + 1 >= len {
            // Trailing `$` with nothing after — pass through
            out.push('$');
            i += 1;
            continue;
        }

        match bytes[i + 1] {
            b'$' => {
                // `$$` → literal `$`
                out.push('$');
                i += 2;
            }
            b'{' => {
                // Find closing `}`
                let start = i + 2;
                let end = match template[start..].find('}') {
                    Some(rel) => start + rel,
                    None => {
                        anyhow::bail!(
                            "{}unclosed `${{` in env template: {:?}",
                            location_prefix(profile, field),
                            template
                        );
                    }
                };
                let ident = &template[start..end];
                // Validate identifier: must match [A-Za-z_][A-Za-z0-9_]*
                validate_env_ident(ident, template, profile, field)?;
                let value = env.get(ident).ok_or_else(|| {
                    anyhow::anyhow!(
                        "{}env var `{}` not found (referenced in template {:?})",
                        location_prefix(profile, field),
                        ident,
                        template
                    )
                })?;
                out.push_str(value);
                i = end + 1;
            }
            _ => {
                // Plain `$x` — not a recognised form, pass through unchanged
                out.push('$');
                i += 1;
            }
        }
    }

    Ok(out)
}

/// AgentProc 0.4 `${VAR}` expansion with `env_allowlist` filtering and POSIX
/// "unknown variable → empty string" semantics.
///
/// Differs from [`expand_env_var_named`] in two ways, both required by the 0.3
/// spec:
/// - When `allowlist` is `Some`, a `${VAR}` whose name is **not** in the list
///   expands to the empty string and a WARN is logged (the process still
///   starts — a typo surfaces as an empty variable, not a hard failure).
/// - Unknown variables (not present in `env`) expand to the empty string
///   rather than erroring, matching POSIX shell behaviour. A missing secret
///   therefore surfaces downstream as an auth error from the CLI, not here.
///
/// `$$` still collapses to a literal `$`; invalid identifiers (`${}`, `${1FOO}`)
/// remain hard errors because they signal a malformed profile, not a missing
/// environment value.
pub fn expand_env_var_named_with_allowlist(
    template: &str,
    env: &std::collections::HashMap<String, String>,
    allowlist: Option<&[String]>,
    profile: Option<&str>,
    field: Option<&str>,
) -> Result<String> {
    let mut out = String::with_capacity(template.len());
    let bytes = template.as_bytes();
    let len = bytes.len();
    let mut i = 0;

    while i < len {
        if bytes[i] != b'$' {
            out.push(bytes[i] as char);
            i += 1;
            continue;
        }
        if i + 1 >= len {
            out.push('$');
            i += 1;
            continue;
        }
        match bytes[i + 1] {
            b'$' => {
                out.push('$');
                i += 2;
            }
            b'{' => {
                let start = i + 2;
                let end = match template[start..].find('}') {
                    Some(rel) => start + rel,
                    None => {
                        anyhow::bail!(
                            "{}unclosed `${{` in env template: {:?}",
                            location_prefix(profile, field),
                            template
                        );
                    }
                };
                let ident = &template[start..end];
                validate_env_ident(ident, template, profile, field)?;
                if let Some(list) = allowlist {
                    if !list.iter().any(|name| name == ident) {
                        tracing::warn!(
                            profile = profile.unwrap_or(""),
                            field = field.unwrap_or(""),
                            var = ident,
                            "env_allowlist blocked ${{{}}}; expanded to empty",
                            ident
                        );
                        i = end + 1;
                        continue;
                    }
                }
                let value = env.get(ident).map(|s| s.as_str()).unwrap_or("");
                out.push_str(value);
                i = end + 1;
            }
            _ => {
                out.push('$');
                i += 1;
            }
        }
    }
    Ok(out)
}

fn validate_env_ident(
    ident: &str,
    template: &str,
    profile: Option<&str>,
    field: Option<&str>,
) -> Result<()> {
    let mut chars = ident.chars();
    let first = chars.next().ok_or_else(|| {
        anyhow::anyhow!(
            "{}empty identifier in `${{}}` in env template: {:?}",
            location_prefix(profile, field),
            template
        )
    })?;
    if !first.is_ascii_alphabetic() && first != '_' {
        anyhow::bail!(
            "{}invalid env var name `{}` in template {:?}: must start with [A-Za-z_]",
            location_prefix(profile, field),
            ident,
            template
        );
    }
    for c in chars {
        if !c.is_ascii_alphanumeric() && c != '_' {
            anyhow::bail!(
                "{}invalid env var name `{}` in template {:?}: only [A-Za-z0-9_] allowed",
                location_prefix(profile, field),
                ident,
                template
            );
        }
    }
    Ok(())
}

fn location_prefix(profile: Option<&str>, field: Option<&str>) -> String {
    match (profile, field) {
        (Some(p), Some(f)) => format!("profile `{p}`, field `{f}`: "),
        (Some(p), None) => format!("profile `{p}`: "),
        _ => String::new(),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parse_legacy_flat_yaml() {
        let y = r#"
command: echo
args: ["{{MESSAGE}}"]
"#;
        let app = BridgeApp::parse_yaml(y).unwrap();
        assert_eq!(app.profile_names(), vec!["default"]);
        let (_, p, payload) = app.resolve("hello").unwrap();
        assert_eq!(p.command, "echo");
        assert_eq!(payload, "hello");
    }

    #[test]
    fn parse_multi_prefix_routing() {
        let y = r#"
profiles:
  a:
    command: echo
    args: ["A", "{{MESSAGE}}"]
    timeout_secs: 5
  b:
    command: echo
    args: ["B", "{{MESSAGE}}"]
    timeout_secs: 5
routing:
  strategy: prefix
  default_profile: a
  prefix_rules:
    - prefix: "/b "
      profile: b
"#;
        let app = BridgeApp::parse_yaml(y).unwrap();
        let (n, _, pay) = app.resolve("plain").unwrap();
        assert_eq!(n, "a");
        assert_eq!(pay, "plain");

        let (n, _, pay) = app.resolve("/b hi").unwrap();
        assert_eq!(n, "b");
        assert_eq!(pay, "hi");
    }

    #[test]
    fn parse_multi_fixed_two_profiles() {
        let y = r#"
profiles:
  p1:
    command: echo
    args: ["1", "{{MESSAGE}}"]
    timeout_secs: 3
  p2:
    command: echo
    args: ["2", "{{MESSAGE}}"]
    timeout_secs: 3
routing:
  strategy: fixed
  default_profile: p2
"#;
        let app = BridgeApp::parse_yaml(y).unwrap();
        let (n, _, pay) = app.resolve("/b hello").unwrap();
        assert_eq!(n, "p2");
        assert_eq!(pay, "/b hello");
    }

    #[test]
    fn script_field_py_expands_to_python3() {
        let y = r#"
profiles:
  bot:
    script: ./my_handler.py
    timeout_secs: 60
routing:
  strategy: fixed
  default_profile: bot
"#;
        let app = BridgeApp::parse_yaml(y).unwrap();
        let (_, p, _) = app.resolve("hello").unwrap();
        assert_eq!(p.command, "python3");
        assert_eq!(p.args, vec!["./my_handler.py"]);
    }

    #[test]
    fn script_field_js_expands_to_node() {
        let y = r#"
profiles:
  bot:
    script: ./handler.js
routing:
  strategy: fixed
  default_profile: bot
"#;
        let app = BridgeApp::parse_yaml(y).unwrap();
        let (_, p, _) = app.resolve("hi").unwrap();
        assert_eq!(p.command, "node");
        assert_eq!(p.args, vec!["./handler.js"]);
    }

    #[test]
    fn script_field_ts_expands_to_npx_tsx() {
        let y = r#"
profiles:
  bot:
    script: ./handler.ts
routing:
  strategy: fixed
  default_profile: bot
"#;
        let app = BridgeApp::parse_yaml(y).unwrap();
        let (_, p, _) = app.resolve("hi").unwrap();
        assert_eq!(p.command, "npx");
        assert_eq!(p.args, vec!["tsx", "./handler.ts"]);
    }

    #[test]
    fn script_field_sh_expands_to_bash() {
        let y = r#"
profiles:
  bot:
    script: ./run.sh
routing:
  strategy: fixed
  default_profile: bot
"#;
        let app = BridgeApp::parse_yaml(y).unwrap();
        let (_, p, _) = app.resolve("hi").unwrap();
        assert_eq!(p.command, "bash");
        assert_eq!(p.args, vec!["./run.sh"]);
    }

    #[test]
    fn explicit_command_wins_over_script() {
        let y = r#"
profiles:
  bot:
    script: ./handler.py
    command: /usr/bin/python3.11
    args: ["./handler.py"]
routing:
  strategy: fixed
  default_profile: bot
"#;
        let app = BridgeApp::parse_yaml(y).unwrap();
        let (_, p, _) = app.resolve("hi").unwrap();
        assert_eq!(p.command, "/usr/bin/python3.11");
    }

    #[test]
    fn multi_empty_profiles_errors() {
        let y = r#"
profiles: {}
routing:
  strategy: fixed
  default_profile: x
"#;
        assert!(BridgeApp::parse_yaml(y).is_err());
    }

    #[test]
    fn shell_c_with_message_placeholder_rejected() {
        let y = r#"
command: bash
args: ["-c", "echo {{MESSAGE}}"]
"#;
        let err = BridgeApp::parse_yaml(y).unwrap_err();
        let msg = err.to_string();
        assert!(
            msg.contains("SECURITY") && msg.contains("MESSAGE"),
            "expected shell-injection reject, got: {msg}"
        );
    }

    #[test]
    fn shell_c_with_message_placeholder_rejected_multi_profile() {
        let y = r#"
profiles:
  bot:
    command: /bin/zsh
    args: ["-c", "printf '%s' '{{MESSAGE}}'"]
routing:
  strategy: fixed
  default_profile: bot
"#;
        let err = BridgeApp::parse_yaml(y).unwrap_err();
        let msg = err.to_string();
        assert!(
            msg.contains("SECURITY") && msg.contains("bot"),
            "expected named-profile reject, got: {msg}"
        );
    }

    #[test]
    fn shell_without_dash_c_still_loads() {
        // A shell running a script (no `-c`) is fine; the message travels via
        // the stdin turn object under agentproc 0.3, never via argv.
        let y = r#"
command: bash
args: ["./run.sh"]
"#;
        let app = BridgeApp::parse_yaml(y).unwrap();
        let (_, p, _) = app.resolve("hi").unwrap();
        assert_eq!(p.command, "bash");
    }

    #[test]
    fn shell_c_without_message_placeholder_still_loads() {
        // Only the dangerous combo (shell + -c + {{MESSAGE}}) is rejected.
        let y = r#"
command: bash
args: ["-c", "echo hello"]
"#;
        assert!(BridgeApp::parse_yaml(y).is_ok());
    }

    #[test]
    fn shell_lc_with_message_placeholder_rejected() {
        // Combined short options (-lc / -ic / -xc) must count as -c.
        let y = r#"
command: bash
args: ["-lc", "echo {{MESSAGE}}"]
"#;
        let err = BridgeApp::parse_yaml(y).unwrap_err();
        let msg = err.to_string();
        assert!(
            msg.contains("SECURITY") && msg.contains("MESSAGE"),
            "expected -lc shell-injection reject, got: {msg}"
        );
    }

    #[test]
    fn shell_c_with_message_in_env_rejected() {
        // MESSAGE via env + bash -c $MSG is the same RCE class as args.
        let y = r#"
command: bash
args: ["-c", "$MSG"]
env:
  MSG: "{{MESSAGE}}"
"#;
        let err = BridgeApp::parse_yaml(y).unwrap_err();
        let msg = err.to_string();
        assert!(
            msg.contains("SECURITY") && msg.contains("MESSAGE"),
            "expected env-based shell-injection reject, got: {msg}"
        );
    }

    #[test]
    fn shell_long_option_color_not_treated_as_dash_c() {
        // `--color` must not false-positive as enabling -c.
        let y = r#"
command: bash
args: ["--color", "echo {{MESSAGE}}"]
"#;
        assert!(
            BridgeApp::parse_yaml(y).is_ok(),
            "long option --color must not trigger -c reject"
        );
    }

    #[test]
    fn ksh_c_with_message_placeholder_rejected() {
        let y = r#"
command: ksh
args: ["-c", "echo {{MESSAGE}}"]
"#;
        let err = BridgeApp::parse_yaml(y).unwrap_err();
        assert!(
            err.to_string().contains("SECURITY"),
            "ksh -c + MESSAGE must be rejected"
        );
    }

    #[test]
    fn type_recursive_expands_to_builtin_invocation() {
        let y = r#"
profiles:
  rec:
    type: recursive
    cwd: ~/projects/recursive
routing:
  strategy: fixed
  default_profile: rec
"#;
        let app = BridgeApp::parse_yaml(y).unwrap();
        let (_, p, _) = app.resolve("hi").unwrap();
        assert_eq!(p.command, "ilink-hub-bridge");
        assert_eq!(p.args, vec!["profile", "recursive"]);
    }

    #[test]
    fn type_unknown_errors() {
        let y = r#"
profiles:
  x:
    type: not-a-real-type
routing:
  strategy: fixed
  default_profile: x
"#;
        let err = BridgeApp::parse_yaml(y).unwrap_err();
        let msg = err.to_string();
        assert!(msg.contains("unknown `type: not-a-real-type`"), "{msg}");
        assert!(
            msg.contains("recursive"),
            "supported list should include recursive: {msg}"
        );
    }

    // ── expand_env_var ────────────────────────────────────────────────────────

    fn env(pairs: &[(&str, &str)]) -> HashMap<String, String> {
        pairs
            .iter()
            .map(|(k, v)| (k.to_string(), v.to_string()))
            .collect()
    }

    #[test]
    fn expand_simple_substitution() {
        let e = env(&[("FOO", "bar")]);
        assert_eq!(expand_env_var("${FOO}", &e).unwrap(), "bar");
    }

    #[test]
    fn expand_multiple_occurrences() {
        let e = env(&[("X", "hello")]);
        assert_eq!(
            expand_env_var("${X} and ${X}", &e).unwrap(),
            "hello and hello"
        );
    }

    #[test]
    fn expand_multiple_different_vars() {
        let e = env(&[("USER", "alice"), ("KEY_SUFFIX", "abc123")]);
        assert_eq!(
            expand_env_var("hello ${USER}, your key ends in ${KEY_SUFFIX}", &e).unwrap(),
            "hello alice, your key ends in abc123"
        );
    }

    #[test]
    fn expand_double_dollar_escape() {
        let e = env(&[]);
        assert_eq!(expand_env_var("$$HOME", &e).unwrap(), "$HOME");
        assert_eq!(expand_env_var("price is $$5", &e).unwrap(), "price is $5");
    }

    #[test]
    fn expand_mixed_literal_and_var() {
        let e = env(&[("KEY", "sk-123")]);
        assert_eq!(
            expand_env_var("prefix-${KEY}-suffix", &e).unwrap(),
            "prefix-sk-123-suffix"
        );
    }

    #[test]
    fn expand_no_placeholder_passthrough() {
        let e = env(&[]);
        assert_eq!(expand_env_var("plain string", &e).unwrap(), "plain string");
        assert_eq!(expand_env_var("", &e).unwrap(), "");
    }

    #[test]
    fn expand_empty_value_is_ok() {
        let e = env(&[("EMPTY", "")]);
        assert_eq!(
            expand_env_var("before${EMPTY}after", &e).unwrap(),
            "beforeafter"
        );
    }

    #[test]
    fn expand_missing_var_errors() {
        let e = env(&[]);
        let err = expand_env_var("${MISSING}", &e).unwrap_err();
        assert!(err.to_string().contains("MISSING"));
    }

    #[test]
    fn expand_missing_var_error_includes_profile_and_field() {
        let e = env(&[]);
        let err =
            expand_env_var_named("${X}", &e, Some("myprofile"), Some("env.ANTHROPIC_API_KEY"))
                .unwrap_err();
        let msg = err.to_string();
        assert!(msg.contains("myprofile"));
        assert!(msg.contains("env.ANTHROPIC_API_KEY"));
        assert!(msg.contains("X"));
    }

    #[test]
    fn expand_invalid_empty_ident_errors() {
        let e = env(&[]);
        assert!(expand_env_var("${}", &e).is_err());
    }

    #[test]
    fn expand_invalid_leading_digit_errors() {
        let e = env(&[]);
        assert!(expand_env_var("${1FOO}", &e).is_err());
    }

    #[test]
    fn expand_invalid_space_in_ident_errors() {
        let e = env(&[]);
        assert!(expand_env_var("${VAR with space}", &e).is_err());
    }

    #[test]
    fn expand_unclosed_brace_errors() {
        let e = env(&[]);
        assert!(expand_env_var("${UNCLOSED", &e).is_err());
    }

    #[test]
    fn expand_plain_dollar_passthrough() {
        // `$x` (no braces) is not a recognised form — pass through unchanged
        let e = env(&[]);
        assert_eq!(expand_env_var("$HOME", &e).unwrap(), "$HOME");
    }

    #[test]
    fn expand_trailing_dollar_passthrough() {
        let e = env(&[]);
        assert_eq!(expand_env_var("end$", &e).unwrap(), "end$");
    }
}