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
//! Channel Search Tool
//!
//! Searches passively captured channel messages (Telegram groups, etc.).
//! Provides list_chats, recent, and search operations.
use super::error::Result;
use super::r#trait::{Tool, ToolCapability, ToolExecutionContext, ToolResult};
use crate::db::ChannelMessageRepository;
use async_trait::async_trait;
use chrono::DateTime;
use serde_json::Value;
/// Is this thread id the General-topic SESSION-SCOPING sentinel (#1220)?
/// Telegram-only: `channel_search` is built on every feature set, but the
/// constant lives behind the `telegram` feature, and no other channel
/// produces a forum thread at all.
#[cfg(feature = "telegram")]
fn is_general_topic(thread: i32) -> bool {
thread == crate::channels::telegram::session_resolve::GENERAL_TOPIC_ID
}
#[cfg(not(feature = "telegram"))]
fn is_general_topic(_thread: i32) -> bool {
false
}
/// Which slice of a chat's message history an operation reads (#718/#719).
/// ONE parameter carries all three states a topic-bound reader needs. Before
/// this, `thread_id` was free-form and omitting it meant "no filter at all",
/// so a session bound to a forum topic silently read every OTHER topic too.
#[derive(Debug, Clone, PartialEq, Eq)]
enum TopicScope {
/// This chat's General topic. Rows persist with `thread_id IS NULL`
/// (General messages carry no `message_thread_id`), so this resolves to
/// the `*_general` repository readers — never to a literal `'1'`
/// comparison, which would match only the legacy sentinel rows instead.
General,
/// One real forum topic, keyed exactly as persisted.
Thread(String),
/// No thread filter: every topic of the chat, interleaved. The pre-#718
/// behaviour, now an explicit opt-in.
All,
}
impl TopicScope {
/// Human label for the output header (D4). A wide read must be visible in
/// the transcript, so the header states the scope actually used —
/// including when it was inherited from the session binding rather than
/// passed.
fn label(&self, inherited: bool) -> String {
let base = match self {
Self::General => "General".to_string(),
Self::Thread(t) => format!("topic {t}"),
Self::All => "all topics".to_string(),
};
if inherited {
format!("{base} inherited")
} else {
base
}
}
}
/// Tool for listing and searching channel message history.
pub struct ChannelSearchTool {
repo: ChannelMessageRepository,
}
impl ChannelSearchTool {
pub fn new(repo: ChannelMessageRepository) -> Self {
Self { repo }
}
}
/// Compare two chat ids. Both sides are platform ids rendered as strings, so
/// a textual compare is normally right; the numeric fallback means a
/// formatting difference cannot silently drop the session's topic and fall
/// through to an unfiltered read — which is the whole defect class (#718).
fn same_chat(a: &str, b: &str) -> bool {
if a == b {
return true;
}
match (a.parse::<i64>(), b.parse::<i64>()) {
(Ok(x), Ok(y)) => x == y,
_ => false,
}
}
/// Parse an explicit `topic_scope` value. `None` means the caller asked for
/// the SESSION's own topic, which is resolved against the ambient binding
/// below. An unknown value is a hard error naming the vocabulary: silently
/// falling back to `all` is exactly the leak #718 is about.
fn parse_topic_scope(raw: &str) -> Result<Option<TopicScope>> {
match raw {
"session" => Ok(None),
"all" => Ok(Some(TopicScope::All)),
"general" => Ok(Some(TopicScope::General)),
other => match other.strip_prefix("thread:") {
Some(id) if !id.is_empty() => Ok(Some(TopicScope::Thread(id.to_string()))),
_ => Err(super::error::ToolError::InvalidInput(format!(
"unknown topic_scope '{other}'. Valid: 'session' (default), 'general', 'all', 'thread:<id>'"
))),
},
}
}
/// Resolve the effective topic scope for one operation (#718/#719). Returns
/// the scope plus whether it was INHERITED from the session binding rather
/// than passed explicitly — the header says which, so a wide read can never
/// hide.
async fn resolve_topic_scope(
input: &Value,
ctx: &ToolExecutionContext,
requested_chat: Option<&str>,
) -> Result<(TopicScope, bool)> {
// An explicit request always wins over inheritance.
if let Some(raw) = input.get("topic_scope").and_then(|v| v.as_str()) {
if let Some(scope) = parse_topic_scope(raw.trim())? {
return Ok((scope, false));
}
// "session" — fall through and inherit from the ambient binding.
} else if let Some(tid) = input.get("thread_id").and_then(|v| v.as_str()) {
// Deprecated alias (D2): `thread_id:"5"` keeps its old meaning.
if !tid.is_empty() {
return Ok((TopicScope::Thread(tid.to_string()), false));
}
}
let Some(o) = ctx.origin_target.as_deref() else {
// No ambient binding (DM, cron, CLI, sub-agent, TUI): there is no
// topic to inherit, so read the whole chat — the pre-#718 behaviour.
return Ok((TopicScope::All, true));
};
let Some(requested) = requested_chat else {
// No chat given (a cross-chat `search`): topic ids are per-chat, so
// there is nothing to inherit.
return Ok((TopicScope::All, true));
};
if !same_chat(requested, &o.chat_id) {
// #718 explicitly defers this choice to the fix. Falling back to
// explicit-All rather than refusing, because the session has no topic
// context for a foreign chat, the tool legitimately supports
// cross-chat reads, and the header makes the wide read visible.
return Ok((TopicScope::All, true));
}
match o.thread {
Some(t) if !is_general_topic(t) => Ok((TopicScope::Thread(t.to_string()), true)),
// A known forum's General topic normalizes to this sentinel (#1220).
Some(_) => Ok((TopicScope::General, true)),
// The binding carries no thread. On a known forum that is still the
// General topic — a legacy NULL-encoded binding, or a row written
// before the sentinel existed. The forum evidence is the same
// `telegram_chat_topics` lookup the target resolver uses. When the
// world is not wired (cron, CLI, tests) or the chat is not a forum,
// this is a genuine DM / non-forum group and reads unfiltered.
None => {
let is_forum = match (ctx.world.as_ref(), o.channel) {
(Some(world), "telegram") => match o.chat_id.parse::<i64>() {
Ok(cid) => {
matches!(world.telegram_chat_topics(cid).await, Ok(Some(t)) if !t.is_empty())
}
Err(_) => false,
},
_ => false,
};
if is_forum {
Ok((TopicScope::General, true))
} else {
Ok((TopicScope::All, true))
}
}
}
}
#[async_trait]
impl Tool for ChannelSearchTool {
fn name(&self) -> &str {
"channel_search"
}
fn description(&self) -> &str {
"Search or list channel message history captured from Telegram groups, Telegram userbot chats, Discord, Slack, etc. \
Use 'list_chats' to see known groups/channels with message counts. \
Use 'recent' to get the last N messages from a specific chat. \
Use 'search' to find messages by content across chats. \
On a forum, results are scoped to the calling session's own topic by default — \
the output header names the scope actually used."
}
fn input_schema(&self) -> Value {
serde_json::json!({
"type": "object",
"properties": {
"operation": {
"type": "string",
"enum": ["list_chats", "recent", "search", "attachments"],
"description": "'list_chats' to see known chats, 'recent' for last N messages, 'search' to find by content, 'attachments' to list stored files"
},
"channel": {
"type": "string",
"enum": ["telegram", "telegram-userbot", "discord", "slack", "whatsapp"],
"description": "Filter by channel platform (omit for all)"
},
"chat_id": {
"type": "string",
"description": "Chat/channel/group ID (required for 'recent' and 'attachments', optional for 'search')"
},
"query": {
"type": "string",
"description": "Search text (required for 'search')"
},
"n": {
"type": "integer",
"description": "Max results to return (default: 20)",
"default": 20
},
"topic_scope": {
"type": "string",
"description": "Which messages to read (optional; default 'session'). 'session': the calling session's own forum topic (on a DM/cron/CLI surface with no topic binding this reads the whole chat); 'general': the chat's General topic; 'all': every topic interleaved — an explicit opt-in, since omitting this no longer means 'no filter'; 'thread:<id>': one specific forum topic."
},
"thread_id": {
"type": "string",
"description": "DEPRECATED — use topic_scope 'thread:<id>'. Filter by thread/topic ID (optional, for Telegram forum topics)"
},
"message_type": {
"type": "string",
"enum": ["text", "document", "photo", "video", "voice", "video_note", "animation"],
"description": "Filter by message type (optional, for 'recent' and 'search')"
}
},
"required": ["operation"]
})
}
fn capabilities(&self) -> Vec<ToolCapability> {
vec![ToolCapability::ReadFiles]
}
fn requires_approval(&self) -> bool {
false
}
async fn execute(&self, input: Value, context: &ToolExecutionContext) -> Result<ToolResult> {
let operation = input
.get("operation")
.and_then(|v| v.as_str())
.unwrap_or("list_chats");
let channel = input.get("channel").and_then(|v| v.as_str());
let n = input.get("n").and_then(|v| v.as_i64()).unwrap_or(20);
match operation {
"list_chats" => {
let chats = self
.repo
.list_chats(channel)
.await
.map_err(|e| super::error::ToolError::Execution(e.to_string()))?;
if chats.is_empty() {
return Ok(ToolResult::success(
"No channel messages captured yet.".to_string(),
));
}
let lines: Vec<String> = chats
.iter()
.map(|c| {
let name = c.channel_chat_name.as_deref().unwrap_or("unnamed");
let ts = DateTime::from_timestamp(c.last_message_at, 0)
.map(|dt| dt.format("%Y-%m-%d %H:%M").to_string())
.unwrap_or_default();
// One id, in one place (#985). This used to print the
// chat id twice, the first time quoted directly after
// the name, where it read as a handle rather than the
// same number again. The oc:// form (#148) is the
// target-URL half of the dual-form listing: raw id
// for humans, URL for targeting tools.
format!(
"- [{}] {} (id={}, target `oc://{}/{}`), {} msgs, last: {}",
c.channel,
name,
c.channel_chat_id,
c.channel,
c.channel_chat_id,
c.message_count,
ts
)
})
.collect();
Ok(ToolResult::success(format!(
"Known chats ({}):\n{}",
chats.len(),
lines.join("\n")
)))
}
"recent" => {
let chat_id = match input.get("chat_id").and_then(|v| v.as_str()) {
Some(id) if !id.is_empty() => id,
_ => {
return Ok(ToolResult::error(
"'chat_id' is required for 'recent' operation.".to_string(),
));
}
};
let (scope, inherited) =
resolve_topic_scope(&input, context, Some(chat_id)).await?;
let messages = match &scope {
TopicScope::General => {
self.repo
.recent_general(channel.unwrap_or("telegram"), chat_id, n, None)
.await
}
TopicScope::Thread(t) => {
self.repo
.recent(channel, chat_id, n, Some(t.as_str()), None)
.await
}
TopicScope::All => self.repo.recent(channel, chat_id, n, None, None).await,
}
.map_err(|e| super::error::ToolError::Execution(e.to_string()))?;
if messages.is_empty() {
return Ok(ToolResult::success(format!(
"No messages found in chat {chat_id}."
)));
}
let lines: Vec<String> = messages
.iter()
.rev() // oldest first for readability
.map(|m| {
let ts = m.created_at.format("%m-%d %H:%M");
let pmid = m
.platform_message_id
.as_deref()
.map(|id| format!(" [msgid:{}]", id))
.unwrap_or_default();
format!("[{}]{} {}: {}", ts, pmid, m.sender_name, m.content)
})
.collect();
Ok(ToolResult::success(format!(
"Recent messages in {} ({}, {} messages):\n{}",
chat_id,
scope.label(inherited),
messages.len(),
lines.join("\n")
)))
}
"search" => {
let query = match input.get("query").and_then(|v| v.as_str()) {
Some(q) if !q.is_empty() => q,
_ => {
return Ok(ToolResult::error(
"'query' is required for 'search' operation.".to_string(),
));
}
};
let chat_id = input.get("chat_id").and_then(|v| v.as_str());
let (scope, inherited) = resolve_topic_scope(&input, context, chat_id).await?;
if matches!(scope, TopicScope::General) && chat_id.is_none() {
return Ok(ToolResult::error(
"'topic_scope: general' requires 'chat_id' — General is per-chat."
.to_string(),
));
}
let messages = match &scope {
TopicScope::General => {
self.repo
.search_general(
channel.unwrap_or("telegram"),
chat_id.unwrap_or_default(),
query,
n,
)
.await
}
TopicScope::Thread(t) => {
self.repo
.search(channel, chat_id, query, n, Some(t.as_str()))
.await
}
TopicScope::All => self.repo.search(channel, chat_id, query, n, None).await,
}
.map_err(|e| super::error::ToolError::Execution(e.to_string()))?;
if messages.is_empty() {
return Ok(ToolResult::success(format!(
"No messages matching \"{query}\"."
)));
}
let lines: Vec<String> = messages
.iter()
.map(|m| {
let ts = m.created_at.format("%m-%d %H:%M");
let chat = m.channel_chat_name.as_deref().unwrap_or(&m.channel_chat_id);
let thread = m
.thread_id
.as_deref()
.map(|t| format!(" [{}]", t))
.unwrap_or_default();
let topic = m
.topic_name
.as_deref()
.map(|t| format!(" ({})", t))
.unwrap_or_default();
let pmid = m
.platform_message_id
.as_deref()
.map(|id| format!(" [msgid:{}]", id))
.unwrap_or_default();
format!(
"[{}] [{}:{}]{}{}{}: {}: {}",
ts, m.channel, chat, thread, topic, pmid, m.sender_name, m.content
)
})
.collect();
Ok(ToolResult::success(format!(
"Search results for \"{}\" ({}, {} messages):\n{}",
query,
scope.label(inherited),
messages.len(),
lines.join("\n")
)))
}
"attachments" => {
let chat_id = match input.get("chat_id").and_then(|v| v.as_str()) {
Some(id) if !id.is_empty() => id,
_ => {
return Ok(ToolResult::error(
"'chat_id' is required for 'attachments' operation.".to_string(),
));
}
};
let (scope, inherited) =
resolve_topic_scope(&input, context, Some(chat_id)).await?;
let messages = match &scope {
TopicScope::General => {
self.repo
.recent_general(channel.unwrap_or("telegram"), chat_id, n, None)
.await
}
TopicScope::Thread(t) => {
self.repo
.recent(channel, chat_id, n, Some(t.as_str()), None)
.await
}
TopicScope::All => self.repo.recent(channel, chat_id, n, None, None).await,
}
.map_err(|e| super::error::ToolError::Execution(e.to_string()))?;
// Filter to only attachment types
let attachments: Vec<_> = messages
.iter()
.filter(|m| {
matches!(
m.message_type.as_str(),
"document" | "photo" | "video" | "voice" | "video_note" | "animation"
)
})
.collect();
if attachments.is_empty() {
return Ok(ToolResult::success(format!(
"No attachments found in chat {chat_id}."
)));
}
let lines: Vec<String> = attachments
.iter()
.map(|m| {
let ts = m.created_at.format("%m-%d %H:%M");
let topic = m
.topic_name
.as_deref()
.map(|t| format!(" ({})", t))
.unwrap_or_default();
format!(
"[{}] [{}]{} {}: {}",
ts, m.message_type, topic, m.sender_name, m.content
)
})
.collect();
Ok(ToolResult::success(format!(
"Attachments in {} ({}, {} messages):\n{}",
chat_id,
scope.label(inherited),
attachments.len(),
lines.join("\n")
)))
}
unknown => Ok(ToolResult::error(format!(
"Unknown operation '{unknown}'. Valid: list_chats, recent, search, attachments"
))),
}
}
}