bcode_web_search_plugin 0.0.1-alpha.0

web search and fetch tool plugin for bcode
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
//! Native TUI rendering for web search and fetch visuals.

use bcode_tui_components::compact::truncate_width;
use bcode_tui_components::tool_card::{
    ToolCardStyle, push_tool_card_detail, tool_card_header, tool_card_header_rows,
};
use bmux_tui::prelude::{Line, Span};
use serde_json::Value;

/// Web search/fetch TUI visual adapter.
pub struct WebSearchTuiVisualAdapter;

impl bcode_plugin_sdk::tui::PluginTuiVisualAdapter for WebSearchTuiVisualAdapter {
    fn supports(&self, kind: &str) -> bool {
        matches!(
            kind,
            "bcode.web-search.search_request"
                | "bcode.web-search.fetch_request"
                | "bcode.web-search.status_request"
                | "bcode.web-search.inspect_request"
                | "bcode.web-search.search_results"
                | "bcode.web-search.fetch_result"
                | "bcode.web-search.status"
                | "bcode.web-search.inspect_result"
        )
    }

    fn render_mode(
        &self,
        _kind: &str,
        _payload: &Value,
    ) -> bcode_plugin_sdk::tui::PluginTuiVisualRenderMode {
        bcode_plugin_sdk::tui::PluginTuiVisualRenderMode::TranscriptBlock
    }

    fn rows(
        &self,
        kind: &str,
        payload: &Value,
        context: &bcode_plugin_sdk::tui::PluginTuiVisualRenderContext,
    ) -> Vec<Line> {
        let width = context.width();
        let style = tool_card_style(context);
        match kind {
            "bcode.web-search.search_request" => search_request_rows(payload, style),
            "bcode.web-search.fetch_request" => fetch_request_rows(payload, style),
            "bcode.web-search.status_request" => simple_request_rows("Web status", style),
            "bcode.web-search.inspect_request" => inspect_request_rows(payload, style),
            "bcode.web-search.search_results" => search_result_rows(payload, width, style),
            "bcode.web-search.fetch_result" => fetch_result_rows(payload, width, style),
            "bcode.web-search.status" => status_rows(payload, style),
            "bcode.web-search.inspect_result" => inspect_result_rows(payload, style),
            _ => Vec::new(),
        }
    }
}

fn search_request_rows(payload: &Value, style: ToolCardStyle) -> Vec<Line> {
    let arguments = payload.get("arguments").unwrap_or(payload);
    let mut rows = header("Web search", style);
    push_kv(&mut rows, "query", text(arguments, "query"), style);
    push_kv(&mut rows, "provider", text(arguments, "provider"), style);
    push_kv(&mut rows, "site", text(arguments, "site"), style);
    push_kv(&mut rows, "freshness", text(arguments, "freshness"), style);
    push_kv(&mut rows, "region", text(arguments, "region"), style);
    push_kv(
        &mut rows,
        "safe search",
        text(arguments, "safe_search"),
        style,
    );
    push_kv(
        &mut rows,
        "max results",
        number(arguments, "max_results"),
        style,
    );
    push_kv(
        &mut rows,
        "provider options",
        compact_json(arguments, "provider_options"),
        style,
    );
    rows
}

fn fetch_request_rows(payload: &Value, style: ToolCardStyle) -> Vec<Line> {
    let arguments = payload.get("arguments").unwrap_or(payload);
    let mut rows = header("Web fetch", style);
    push_kv(&mut rows, "url", text(arguments, "url"), style);
    push_kv(&mut rows, "rendered", bool_text(arguments, "render"), style);
    push_kv(&mut rows, "provider", text(arguments, "provider"), style);
    push_kv(
        &mut rows,
        "max bytes",
        number(arguments, "max_bytes"),
        style,
    );
    push_kv(&mut rows, "prompt", text(arguments, "prompt"), style);
    rows
}

fn simple_request_rows(title: &str, style: ToolCardStyle) -> Vec<Line> {
    header(title, style)
}

fn inspect_request_rows(payload: &Value, style: ToolCardStyle) -> Vec<Line> {
    let arguments = payload.get("arguments").unwrap_or(payload);
    let mut rows = header("Inspect URL", style);
    push_kv(&mut rows, "url", text(arguments, "url"), style);
    rows
}

fn search_result_rows(payload: &Value, width: u16, style: ToolCardStyle) -> Vec<Line> {
    let result_count = payload
        .get("results")
        .and_then(Value::as_array)
        .map_or(0, Vec::len);
    let metadata = std::iter::once(
        text(payload, "query").map(|value| Span::styled(format!("“{value}”"), style.value)),
    )
    .flatten();
    let mut rows = tool_card_header_rows(
        Span::styled("◆ ", style.accent),
        Span::styled(format!("Search results ({result_count})"), style.title),
        metadata,
        width,
        style.muted,
    );
    rows.push(Line::raw(""));
    if let Some(results) = payload.get("results").and_then(Value::as_array) {
        for (index, result) in results.iter().take(10).enumerate() {
            let url = text(result, "url").unwrap_or_default();
            let host = url
                .split_once("://")
                .map_or(url, |(_, rest)| rest)
                .split('/')
                .next()
                .unwrap_or_default();
            rows.push(Line::from_spans(vec![
                Span::styled(format!("  {}  ", index + 1), style.accent),
                Span::styled(
                    text(result, "title").unwrap_or("Untitled").to_owned(),
                    style.title,
                ),
                Span::styled(format!(" · {host}"), style.muted),
            ]));
            if !url.is_empty() {
                rows.push(Line::from_spans(vec![
                    Span::styled("     ↳ ", style.muted),
                    Span::styled(
                        truncate_width(url, usize::from(width.saturating_sub(8))),
                        style.link,
                    ),
                ]));
            }
            if let Some(snippet) = text(result, "snippet") {
                rows.push(Line::from_spans(vec![
                    Span::styled("     │ ", style.muted),
                    Span::raw(truncate_width(
                        snippet,
                        usize::from(width.saturating_sub(8)),
                    )),
                ]));
            }
        }
        if results.len() > 10 {
            rows.push(Line::from_spans(vec![Span::styled(
                format!("  … {} more results", results.len() - 10),
                style.muted,
            )]));
        }
    }
    if text(payload, "provider").is_some()
        || payload.get("partial").and_then(Value::as_bool) == Some(true)
        || text(payload, "message").is_some()
    {
        rows.push(Line::raw(""));
        push_kv(&mut rows, "provider", text(payload, "provider"), style);
        if payload.get("partial").and_then(Value::as_bool) == Some(true) {
            push_kv(&mut rows, "partial", Some("yes"), style);
        }
        push_kv(&mut rows, "note", text(payload, "message"), style);
    }
    rows
}

fn fetch_result_rows(payload: &Value, width: u16, style: ToolCardStyle) -> Vec<Line> {
    let mut rows = header("Fetched page", style);
    push_kv(&mut rows, "title", text(payload, "title"), style);
    push_kv(
        &mut rows,
        "url",
        text(payload, "final_url").or_else(|| text(payload, "url")),
        style,
    );
    push_kv(&mut rows, "status", number(payload, "status"), style);
    push_kv(&mut rows, "type", text(payload, "content_type"), style);
    push_kv(&mut rows, "format", text(payload, "content_format"), style);
    push_kv(&mut rows, "rendered", bool_text(payload, "rendered"), style);
    push_kv(
        &mut rows,
        "truncated",
        bool_text(payload, "truncated"),
        style,
    );
    rows.push(Line::raw(""));
    if let Some(text) = text(payload, "markdown").or_else(|| text(payload, "text")) {
        rows.extend(preview_rows(text, width, style));
    }
    rows
}

fn status_rows(payload: &Value, style: ToolCardStyle) -> Vec<Line> {
    let mut rows = header("Web capabilities", style);
    if let Some(search) = payload.get("search") {
        rows.push(Line::from_spans(vec![Span::styled(
            "  Search",
            style.title,
        )]));
        push_kv(
            &mut rows,
            "available",
            bool_text(search, "available"),
            style,
        );
        push_kv(&mut rows, "provider", text(search, "provider"), style);
        push_kv(&mut rows, "quality", text(search, "quality"), style);
        push_kv(
            &mut rows,
            "configured",
            string_array(search, "configured_providers"),
            style,
        );
        push_kv(
            &mut rows,
            "recommended",
            string_array(search, "recommended"),
            style,
        );
    }
    if let Some(fetch) = payload.get("fetch") {
        rows.push(Line::raw(""));
        rows.push(Line::from_spans(vec![Span::styled("  Fetch", style.title)]));
        push_kv(&mut rows, "available", bool_text(fetch, "available"), style);
        push_kv(
            &mut rows,
            "fallbacks",
            string_array(fetch, "fallbacks"),
            style,
        );
        push_kv(
            &mut rows,
            "rendered fetch",
            bool_text(fetch, "rendered_fetch"),
            style,
        );
        push_kv(&mut rows, "max bytes", number(fetch, "max_bytes"), style);
    }
    rows
}

fn inspect_result_rows(payload: &Value, style: ToolCardStyle) -> Vec<Line> {
    let mut rows = header("URL inspection", style);
    push_kv(&mut rows, "url", text(payload, "url"), style);
    push_kv(&mut rows, "kind", text(payload, "kind"), style);
    push_kv(
        &mut rows,
        "recommended tool",
        text(payload, "recommended_tool"),
        style,
    );
    push_kv(
        &mut rows,
        "action",
        text(payload, "recommended_action"),
        style,
    );
    if let Some(notes) = payload.get("notes").and_then(Value::as_array) {
        rows.push(Line::raw(""));
        for note in notes.iter().filter_map(Value::as_str) {
            rows.push(Line::from_spans(vec![
                Span::styled("  • ", style.accent),
                Span::raw(note.to_owned()),
            ]));
        }
    }
    rows
}

fn preview_rows(text: &str, width: u16, style: ToolCardStyle) -> Vec<Line> {
    let max_width = usize::from(width.saturating_sub(4));
    let mut rows = Vec::new();
    for line in text.lines().take(24) {
        rows.push(Line::from_spans(vec![
            Span::styled(truncate_width("  │ ", usize::from(width)), style.muted),
            Span::raw(truncate(line, max_width)),
        ]));
    }
    if text.lines().count() > 24 {
        rows.push(Line::from_spans(vec![Span::styled(
            "  … preview truncated",
            style.muted,
        )]));
    }
    rows
}

fn header(title: &str, style: ToolCardStyle) -> Vec<Line> {
    vec![tool_card_header(
        Span::styled("◆ ", style.accent),
        Span::styled(title.to_owned(), style.title),
    )]
}

fn push_kv<T>(rows: &mut Vec<Line>, key: &str, value: Option<T>, style: ToolCardStyle)
where
    T: Into<String>,
{
    if let Some(value) = value.map(Into::into) {
        push_tool_card_detail(rows, key, Some(&value), style.muted, style.value);
    }
}

fn text<'a>(payload: &'a Value, key: &str) -> Option<&'a str> {
    payload.get(key).and_then(Value::as_str)
}

fn compact_json(payload: &Value, key: &str) -> Option<String> {
    payload
        .get(key)
        .filter(|value| !value.is_null())
        .and_then(|value| serde_json::to_string(value).ok())
}

fn number(payload: &Value, key: &str) -> Option<String> {
    payload
        .get(key)
        .and_then(Value::as_u64)
        .map(|value| value.to_string())
}

fn bool_text(payload: &Value, key: &str) -> Option<String> {
    payload
        .get(key)
        .and_then(Value::as_bool)
        .map(|value| if value { "yes" } else { "no" }.to_owned())
}

fn string_array(payload: &Value, key: &str) -> Option<String> {
    payload.get(key).and_then(Value::as_array).map(|values| {
        values
            .iter()
            .filter_map(Value::as_str)
            .collect::<Vec<_>>()
            .join(", ")
    })
}

fn truncate(value: &str, width: usize) -> String {
    truncate_width(value, width)
}

fn tool_card_style(context: &bcode_plugin_sdk::tui::PluginTuiVisualRenderContext) -> ToolCardStyle {
    ToolCardStyle::from_component_theme(context.theme().and_then(|theme| theme.component_theme()))
}

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

    #[test]
    fn previews_fit_tiny_and_unicode_widths() {
        for width in 0..30 {
            let rows = preview_rows(
                "界界界 emoji 👩‍💻 and a long line",
                width,
                ToolCardStyle::from_component_theme(None),
            );
            assert!(rows.iter().all(|row| row.width() <= usize::from(width)));
        }
    }

    fn line_text(line: &Line) -> String {
        line.spans
            .iter()
            .map(|span| span.content.as_ref() as &str)
            .collect::<String>()
    }

    #[test]
    fn renders_search_results() {
        let payload = serde_json::json!({
            "query": "rust tui",
            "provider": "test",
            "partial": false,
            "results": [{
                "title": "Ratatui",
                "url": "https://ratatui.rs",
                "snippet": "Build terminal user interfaces"
            }]
        });
        let rows = bcode_plugin_sdk::tui::PluginTuiVisualAdapter::rows(
            &WebSearchTuiVisualAdapter,
            "bcode.web-search.search_results",
            &payload,
            &bcode_plugin_sdk::tui::PluginTuiVisualRenderContext::new(
                80,
                bcode_plugin_sdk::tui::PluginTuiDiffLayout::Auto { breakpoint: 120 },
                None,
            ),
        );
        let rendered = rows.iter().map(line_text).collect::<Vec<_>>().join("\n");
        assert!(rendered.contains("Search results (1)"), "{rendered}");
        assert!(rendered.contains("Ratatui"), "{rendered}");
        assert!(rendered.contains("https://ratatui.rs"), "{rendered}");
    }
}