ilink-hub 0.1.17

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
//! Quote-aware routing: map iLink `ref_msg` / item `msg_id` back to the backend (or Hub)
//! that produced the quoted message, without requiring a short-id in the visible body.
//!
//! **Population**: when a downstream client (or Hub) calls `sendmessage`, we record a
//! pending entry keyed by outbound `client_id` (`ilink-hub:…`). If the real iLink
//! `getupdates` stream echoes that bot message (`message_type == 2`) with the same
//! `client_id`, we register `item.msg_id` (and top-level `message_id`) → origin.
//!
//! **Resolution**: inbound user messages that carry `ref_msg.message_item.msg_id`
//! hit the index first (unless the user message is an explicit `/…` hub command).

use std::collections::HashMap;
use std::time::{Duration, Instant};

use serde_json::Value as Json;

use super::router::{HubCommand, RoutingDecision};

/// Apply quote-based override when the user did not send an explicit hub `/…` command.
pub fn merge_routing_with_quote(
    base: RoutingDecision,
    quoted: Option<QuoteOrigin>,
) -> RoutingDecision {
    if matches!(&base, RoutingDecision::HubInternal(_)) {
        return base;
    }
    match quoted {
        Some(QuoteOrigin::Client { vtoken, .. }) => RoutingDecision::ForwardTo(vtoken),
        Some(QuoteOrigin::Hub { cmd }) => RoutingDecision::HubInternal(cmd),
        None => base,
    }
}

/// Who should receive a follow-up when the user quote-replies.
#[derive(Debug, Clone)]
pub enum QuoteOrigin {
    /// A registered downstream client.
    Client {
        vtoken: String,
        name: String,
        label: Option<String>,
    },
    /// Hub-generated reply (e.g. `/list`); re-run the same hub action.
    Hub { cmd: HubCommand },
}

#[derive(Debug, Clone)]
struct PendingOutbound {
    origin: QuoteOrigin,
    deadline: Instant,
}

#[derive(Debug, Clone)]
struct IndexedOrigin {
    origin: QuoteOrigin,
    deadline: Instant,
}

/// In-memory index with TTL eviction (no persistence yet).
#[derive(Debug, Default)]
pub struct QuoteRouteIndex {
    pending_by_client_id: HashMap<String, PendingOutbound>,
    by_msg_key: HashMap<String, IndexedOrigin>,
}

const PENDING_TTL: Duration = Duration::from_secs(600);
const INDEX_TTL: Duration = Duration::from_secs(86400 * 7);

impl QuoteRouteIndex {
    /// After building the outbound `WeixinMessage` (with `ensure_outbound`), register
    /// so a later upstream echo can attach `msg_id` keys.
    pub fn register_pending_client(
        &mut self,
        client_id: &str,
        vtoken: String,
        name: String,
        label: Option<String>,
    ) {
        if client_id.is_empty() {
            return;
        }
        self.evict_expired();
        self.pending_by_client_id.insert(
            client_id.to_string(),
            PendingOutbound {
                origin: QuoteOrigin::Client {
                    vtoken,
                    name,
                    label,
                },
                deadline: Instant::now() + PENDING_TTL,
            },
        );
    }

    pub fn register_pending_hub(&mut self, client_id: &str, cmd: HubCommand) {
        if client_id.is_empty() {
            return;
        }
        self.evict_expired();
        self.pending_by_client_id.insert(
            client_id.to_string(),
            PendingOutbound {
                origin: QuoteOrigin::Hub { cmd },
                deadline: Instant::now() + PENDING_TTL,
            },
        );
    }

    /// Call for upstream messages that look like bot-side copies (`message_type == 2`).
    pub fn observe_upstream_bot_message(&mut self, msg: &crate::ilink::types::WeixinMessage) {
        self.evict_expired();
        let client_id = match msg.client_id.as_deref() {
            Some(s) if !s.is_empty() => s,
            _ => return,
        };
        let Some(pending) = self.pending_by_client_id.remove(client_id) else {
            return;
        };
        if Instant::now() > pending.deadline {
            return;
        }
        let origin = pending.origin;
        if let Some(mid) = msg.message_id {
            self.insert_key(format!("m:{mid}"), origin.clone());
        }
        if let Some(items) = &msg.item_list {
            for item in items {
                if let Some(id) = item_msg_id(item) {
                    self.insert_key(format!("i:{id}"), origin.clone());
                }
            }
        }
    }

    fn insert_key(&mut self, key: String, origin: QuoteOrigin) {
        self.by_msg_key.insert(
            key,
            IndexedOrigin {
                origin,
                deadline: Instant::now() + INDEX_TTL,
            },
        );
    }

    /// If the user quote-replies, resolve the quoted bot item to a [`QuoteOrigin`].
    pub fn resolve_user_quote(
        &mut self,
        msg: &crate::ilink::types::WeixinMessage,
    ) -> Option<QuoteOrigin> {
        self.evict_expired();
        for key in collect_quoted_msg_keys(msg) {
            if let Some(entry) = self.by_msg_key.get(&key) {
                if Instant::now() <= entry.deadline {
                    return Some(entry.origin.clone());
                }
            }
        }
        None
    }

    fn evict_expired(&mut self) {
        let now = Instant::now();
        self.pending_by_client_id.retain(|_, p| now <= p.deadline);
        self.by_msg_key.retain(|_, v| now <= v.deadline);
    }
}

fn item_msg_id(item: &crate::ilink::types::MessageItem) -> Option<String> {
    extra_str(&item.extra, &["msg_id"])
}

/// Pull quoted message item ids from the first text-like item's `ref_msg`.
fn collect_quoted_msg_keys(msg: &crate::ilink::types::WeixinMessage) -> Vec<String> {
    let mut out = Vec::new();
    let Some(items) = &msg.item_list else {
        return out;
    };
    for item in items {
        let Some(extra) = item.extra.as_object() else {
            continue;
        };
        let Some(ref_msg) = extra.get("ref_msg") else {
            continue;
        };
        let Some(mi) = ref_msg.get("message_item") else {
            continue;
        };
        if let Some(id) = json_str(mi.get("msg_id")) {
            out.push(format!("i:{id}"));
        }
        if let Some(mid) = mi.get("message_id").and_then(|v| v.as_i64()) {
            out.push(format!("m:{mid}"));
        }
        if let Some(Json::Object(map)) = mi.get("extra") {
            if let Some(id) = map.get("msg_id").and_then(|v| v.as_str()) {
                out.push(format!("i:{id}"));
            }
        }
    }
    out
}

fn extra_str(extra: &Json, path: &[&str]) -> Option<String> {
    let mut cur = extra;
    for p in path {
        cur = cur.get(*p)?;
    }
    json_str(Some(cur))
}

fn json_str(v: Option<&Json>) -> Option<String> {
    let v = v?;
    if let Some(s) = v.as_str() {
        if !s.is_empty() {
            return Some(s.to_string());
        }
    }
    if let Some(n) = v.as_i64() {
        return Some(n.to_string());
    }
    None
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ilink::types::{MessageItem, TextItem, WeixinMessage};

    #[test]
    fn collect_keys_from_sample_ref() {
        let extra: Json = serde_json::from_str(
            r#"{
            "ref_msg": {
                "message_item": {
                    "msg_id": "v1:quoted-bot-item",
                    "message_id": 999888777,
                    "type": 1,
                    "text_item": { "text": "hello" }
                }
            }
        }"#,
        )
        .unwrap();
        let msg = WeixinMessage {
            item_list: Some(vec![MessageItem {
                item_type: Some(1),
                text_item: Some(TextItem {
                    text: Some("再来一次".into()),
                }),
                extra,
            }]),
            ..Default::default()
        };
        let keys = collect_quoted_msg_keys(&msg);
        assert!(keys.contains(&"i:v1:quoted-bot-item".to_string()));
        assert!(keys.contains(&"m:999888777".to_string()));
    }

    #[test]
    fn merge_quote_overrides_forward() {
        let base = RoutingDecision::ForwardTo("default_vt".into());
        let q = QuoteOrigin::Client {
            vtoken: "quoted_vt".into(),
            name: "n".into(),
            label: None,
        };
        let out = merge_routing_with_quote(base, Some(q));
        assert!(matches!(
            out,
            RoutingDecision::ForwardTo(ref v) if v == "quoted_vt"
        ));
    }

    #[test]
    fn merge_quote_overrides_broadcast() {
        let out = merge_routing_with_quote(
            RoutingDecision::Broadcast,
            Some(QuoteOrigin::Client {
                vtoken: "vt".into(),
                name: "n".into(),
                label: None,
            }),
        );
        assert!(matches!(out, RoutingDecision::ForwardTo(ref v) if v == "vt"));
    }

    #[test]
    fn merge_hub_internal_from_quote() {
        let out = merge_routing_with_quote(
            RoutingDecision::ForwardTo("x".into()),
            Some(QuoteOrigin::Hub {
                cmd: HubCommand::List,
            }),
        );
        assert!(matches!(
            out,
            RoutingDecision::HubInternal(HubCommand::List)
        ));
    }

    #[test]
    fn merge_explicit_hub_command_not_overridden_by_quote() {
        let base = RoutingDecision::HubInternal(HubCommand::Status);
        let out = merge_routing_with_quote(
            base,
            Some(QuoteOrigin::Client {
                vtoken: "vt".into(),
                name: "n".into(),
                label: None,
            }),
        );
        assert!(matches!(
            out,
            RoutingDecision::HubInternal(HubCommand::Status)
        ));
    }

    #[test]
    fn merge_no_quote_keeps_forward() {
        let base = RoutingDecision::ForwardTo("keep".into());
        let out = merge_routing_with_quote(base, None);
        assert!(matches!(out, RoutingDecision::ForwardTo(ref v) if v == "keep"));
    }

    #[test]
    fn observe_unknown_client_id_never_indexes() {
        let mut idx = QuoteRouteIndex::default();
        let echo = WeixinMessage {
            message_type: Some(2),
            client_id: Some("orphan".into()),
            message_id: Some(777),
            item_list: Some(vec![MessageItem {
                item_type: Some(1),
                text_item: Some(TextItem {
                    text: Some("b".into()),
                }),
                extra: serde_json::json!({ "msg_id": "v1:orphan" }),
            }]),
            ..Default::default()
        };
        idx.observe_upstream_bot_message(&echo);
        let user = WeixinMessage {
            item_list: Some(vec![MessageItem {
                item_type: Some(1),
                text_item: Some(TextItem {
                    text: Some("u".into()),
                }),
                extra: serde_json::json!({
                    "ref_msg": { "message_item": { "msg_id": "v1:orphan" } }
                }),
            }]),
            ..Default::default()
        };
        assert!(idx.resolve_user_quote(&user).is_none());
    }

    #[test]
    fn resolve_without_ref_returns_none() {
        let mut idx = QuoteRouteIndex::default();
        idx.register_pending_client("c1", "vt".into(), "n".into(), None);
        let user = WeixinMessage {
            item_list: Some(vec![MessageItem {
                item_type: Some(1),
                text_item: Some(TextItem {
                    text: Some("hi".into()),
                }),
                extra: serde_json::Value::Object(Default::default()),
            }]),
            ..Default::default()
        };
        assert!(idx.resolve_user_quote(&user).is_none());
    }

    #[test]
    fn observe_then_resolve() {
        let mut idx = QuoteRouteIndex::default();
        idx.register_pending_client(
            "ilink-hub:test-client-id",
            "vhub_abc".into(),
            "echo".into(),
            Some("echo test".into()),
        );
        let echo = WeixinMessage {
            message_type: Some(2),
            client_id: Some("ilink-hub:test-client-id".into()),
            message_id: Some(42),
            item_list: Some(vec![MessageItem {
                item_type: Some(1),
                text_item: Some(TextItem {
                    text: Some("bot said".into()),
                }),
                extra: serde_json::json!({ "msg_id": "v1:item-1" }),
            }]),
            ..Default::default()
        };
        idx.observe_upstream_bot_message(&echo);
        let user = WeixinMessage {
            message_type: Some(1),
            from_user_id: Some("user@x".into()),
            item_list: Some(vec![MessageItem {
                item_type: Some(1),
                text_item: Some(TextItem {
                    text: Some("again".into()),
                }),
                extra: serde_json::json!({
                    "ref_msg": {
                        "message_item": {
                            "msg_id": "v1:item-1"
                        }
                    }
                }),
            }]),
            ..Default::default()
        };
        let origin = idx.resolve_user_quote(&user).expect("resolve");
        match origin {
            QuoteOrigin::Client { vtoken, name, .. } => {
                assert_eq!(vtoken, "vhub_abc");
                assert_eq!(name, "echo");
            }
            QuoteOrigin::Hub { .. } => panic!("expected client"),
        }
    }
}