ilink-hub 0.1.12

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
//! 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>,
    pub routing: BridgeRoutingYaml,
}

#[derive(Debug, Clone, Deserialize, PartialEq, Eq, Default)]
#[serde(rename_all = "snake_case")]
pub enum StdinMode {
    #[default]
    None,
    Message,
}

/// 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>,
    #[serde(default)]
    pub stdin: StdinMode,
    #[serde(default)]
    pub cwd: Option<String>,
    #[serde(default)]
    pub env: HashMap<String, String>,
    #[serde(default = "default_timeout_secs")]
    pub timeout_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,
    /// If non-empty: stdout 的第一行若以该前缀开头,则该行去掉前缀后的剩余部分为 **CLI 会话 id**,
    /// 会随 `sendmessage` 写入 Hub;其余行作为发给微信的正文。
    #[serde(default)]
    pub cli_session_first_line_prefix: Option<String>,
}

fn default_timeout_secs() -> u64 {
    300
}

fn default_max_reply_chars() -> usize {
    8000
}

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

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 stdin: StdinMode,
    #[serde(default)]
    pub cwd: Option<String>,
    #[serde(default)]
    pub env: HashMap<String, String>,
    #[serde(default = "default_timeout_secs")]
    pub timeout_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)]
    pub cli_session_first_line_prefix: 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_yaml::from_str(raw).context("serde_yaml::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 mut profiles = HashMap::new();
        profiles.insert(
            "default".to_string(),
            BridgeProfile {
                profile_type: None,
                script: None,
                command: c.command.clone(),
                args: c.args.clone(),
                stdin: c.stdin.clone(),
                cwd: c.cwd.clone(),
                env: c.env.clone(),
                timeout_secs: c.timeout_secs,
                max_reply_chars: c.max_reply_chars,
                truncation_suffix: c.truncation_suffix.clone(),
                include_stderr_in_reply: c.include_stderr_in_reply,
                cli_session_first_line_prefix: c.cli_session_first_line_prefix.clone(),
            },
        );
        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`)"
                );
            }
        }
        if !profiles.contains_key(&m.routing.default_profile) {
            anyhow::bail!(
                "routing.default_profile `{}` is not a key in `profiles`",
                m.routing.default_profile
            );
        }
        for (i, rule) in m.routing.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 m.routing.strategy == RoutingStrategy::Prefix && m.routing.prefix_rules.is_empty() {
            anyhow::bail!("routing.strategy: `prefix` requires at least one `prefix_rules` entry (or use `fixed`)");
        }

        let routing = match m.routing.strategy {
            RoutingStrategy::Fixed => RoutingState::Fixed(m.routing.default_profile.clone()),
            RoutingStrategy::Prefix => RoutingState::Prefix {
                default: m.routing.default_profile.clone(),
                rules: m
                    .routing
                    .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 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.extend(p.args.drain(..));
            p.args = args;
        }
        "js" | "mjs" | "cjs" => {
            p.command = "node".to_string();
            let mut args = vec![script_path];
            args.extend(p.args.drain(..));
            p.args = args;
        }
        "ts" => {
            p.command = "npx".to_string();
            let mut args = vec!["tsx".to_string(), script_path];
            args.extend(p.args.drain(..));
            p.args = args;
        }
        "sh" | "bash" => {
            p.command = "bash".to_string();
            let mut args = vec![script_path];
            args.extend(p.args.drain(..));
            p.args = args;
        }
        "rb" => {
            p.command = "ruby".to_string();
            let mut args = vec![script_path];
            args.extend(p.args.drain(..));
            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.
///
/// Recognised shorthands:
/// - `"claude-code"` → `command: ilink-hub-bridge  args: [profile, claude-code]`
///   with `cli_session_first_line_prefix: "ILINK_SESSION:"` auto-set.
///
/// If `profile_type` is `None` or the command is already set, returns the profile unchanged.
fn expand_profile_type(mut 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);
    }
    match pt.as_str() {
        "claude-code" => {
            p.command = "ilink-hub-bridge".to_string();
            p.args = vec!["profile".to_string(), "claude-code".to_string()];
            p.stdin = StdinMode::Message;
            if p.cli_session_first_line_prefix.is_none() {
                p.cli_session_first_line_prefix = Some("ILINK_SESSION:".to_string());
            }
            Ok(p)
        }
        other => anyhow::bail!(
            "profile `{name}`: unknown `type: {other}`; supported built-in types: claude-code"
        ),
    }
}

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

    #[test]
    fn parse_legacy_flat_yaml() {
        let y = r#"
command: echo
args: ["{{MESSAGE}}"]
stdin: none
"#;
        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}}"]
    stdin: none
    timeout_secs: 5
  b:
    command: echo
    args: ["B", "{{MESSAGE}}"]
    stdin: none
    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}}"]
    stdin: none
    timeout_secs: 3
  p2:
    command: echo
    args: ["2", "{{MESSAGE}}"]
    stdin: none
    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());
    }
}