formal-ai 0.86.0

Formal symbolic AI implementation with OpenAI-compatible APIs
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
//! URL fetch, URL navigation, and browser-search handlers.

use crate::concepts::extract_concept_query;
use crate::engine::{normalize_prompt, select_rule_for, SelectedRule, SymbolicAnswer};
use crate::event_log::EventLog;
use crate::language::detect as detect_language;
use crate::seed::{projects_registry, ProjectRecord};
use crate::summarization::{describe_project, SummarizationConfig, SummarizationMode};
use crate::web_search_core::{
    WEB_SEARCH_PROVIDERS as CORE_WEB_SEARCH_PROVIDERS, WEB_SEARCH_RRF_K as CORE_WEB_SEARCH_RRF_K,
};

use super::finalize_simple;

/// Match prompts that explicitly ask the engine to perform an HTTP request
/// (e.g. `fetch google.com`, `Сделай запрос к google.com`). In the browser
/// web app the actual `fetch()` is attempted first, with an iframe fallback when
/// CORS blocks the request only after target frame-policy headers have been
/// checked. Non-fetch URL prompts (`Navigate to github.com`, `Visit github.com`,
/// ...) are handled by [`try_url_navigate`] instead.
pub fn try_http_fetch(
    prompt: &str,
    normalized: &str,
    log: &mut EventLog,
) -> Option<SymbolicAnswer> {
    let url = extract_http_fetch_url(prompt, normalized)?;
    log.append("http_fetch:request", url.clone());
    let language = detect_language(prompt).slug();
    let project_summary = match_curated_github_url(&url).map(|project| {
        log.append("http_fetch:curated_project", project.repo_slug());
        log.append("summarization:mode", "standard".to_owned());
        log.append("summarization:language", language.to_owned());
        let config = SummarizationConfig::default()
            .with_mode(SummarizationMode::Standard)
            .with_language(language);
        describe_project(project, &config)
    });
    let body = project_summary.map_or_else(
        || {
            format!(
                "HTTP fetch requested for `{url}`.\n\n\
                 The browser web app attempts a direct `fetch()` first and shows the \
                 response body when the server allows CORS. If the request is blocked \
                 by CORS, the web app checks CORS-readable frame-policy metadata before \
                 deciding whether to show an embedded iframe or keep a direct external \
                 link.\n\n\
                 Source: [{url}]({url})"
            )
        },
        |summary| match language {
            "ru" => format!(
                "HTTP-запрос на `{url}`.\n\n\
                 Этот URL соответствует курируемому продвигаемому проекту. \
                 Резюме README (через formalize → summarize → \
                 deformalize): {summary}\n\n\
                 В браузерной демо-версии сначала выполняется прямой `fetch()`; \
                 если CORS блокирует ответ, проверяется frame-policy и при \
                 необходимости открывается iframe или показывается прямая \
                 ссылка.\n\n\
                 Source: [{url}]({url})"
            ),
            _ => format!(
                "HTTP fetch requested for `{url}`.\n\n\
                 This URL matches a curated promoted project. README summary \
                 (through the formalize → summarize → \
                 deformalize pipeline): {summary}\n\n\
                 The browser web app attempts a direct `fetch()` first and shows \
                 the response body when the server allows CORS. If the request \
                 is blocked by CORS, the web app checks CORS-readable \
                 frame-policy metadata before deciding whether to show an \
                 embedded iframe or keep a direct external link.\n\n\
                 Source: [{url}]({url})"
            ),
        },
    );
    Some(finalize_simple(
        prompt,
        log,
        "http_fetch",
        "response:http_fetch",
        &body,
        0.95,
    ))
}

/// Match an absolute URL against the curated project registry. Returns the
/// project record when the URL points to a `github.com/<org>/<name>`
/// repository whose `<org>/<name>` matches a curated entry. Sub-paths
/// (`/blob/`, `/tree/`, etc.) are also matched so a README fetch URL like
/// `https://github.com/link-assistant/hive-mind/blob/main/README.md` still
/// resolves to the curated record.
fn match_curated_github_url(url: &str) -> Option<&'static ProjectRecord> {
    let lower = url.to_lowercase();
    let after_scheme = lower
        .strip_prefix("https://")
        .or_else(|| lower.strip_prefix("http://"))?;
    let after_host = after_scheme.strip_prefix("github.com/")?;
    let mut segments = after_host.split('/');
    let org = segments.next()?.trim_matches('/');
    let name = segments.next()?.trim_matches('/');
    if org.is_empty() || name.is_empty() {
        return None;
    }
    let registry = registry_static();
    registry.projects.iter().find(|project| {
        project.org.eq_ignore_ascii_case(org) && project.name.eq_ignore_ascii_case(name)
    })
}

/// Match prompts that ask the assistant to navigate to or display a URL
/// without performing an HTTP request (e.g. `Navigate to github.com`,
/// `Go to github.com`, `Перейди на github.com`). The browser web app renders
/// an iframe preview only when CORS-readable frame-policy metadata does not
/// report blocking X-Frame-Options or CSP frame-ancestors headers.
pub fn try_url_navigate(
    prompt: &str,
    normalized: &str,
    log: &mut EventLog,
) -> Option<SymbolicAnswer> {
    let url = extract_url_navigate_url(prompt, normalized)?;
    log.append("url_navigate:request", url.clone());
    log.append("url_preview:frame_policy_check", url.clone());
    log.append("url_preview:external_link", url.clone());
    let body = format!(
        "I suggest opening this in a new tab: [{url}]({url}).\n\n\
         In the browser web app, this URL is checked with browser-readable \
         frame-policy metadata before any embedded preview is attempted. If \
         X-Frame-Options or CSP frame-ancestors blocks embedding, the web app \
         keeps the direct external link instead."
    );
    Some(finalize_simple(
        prompt,
        log,
        "url_navigate",
        "response:url_navigate",
        &body,
        0.95,
    ))
}

/// Reciprocal Rank Fusion constant used to combine the top-10 results returned
/// by each search provider. Re-exported from `crate::web_search_core` so the
/// CLI, server, browser worker, and the Rust→WASM port all share one value.
///
/// Source: <https://plg.uwaterloo.ca/~gvcormac/cormacksigir09-rrf.pdf>
pub const WEB_SEARCH_RRF_K: u32 = CORE_WEB_SEARCH_RRF_K;

/// Provider order used by the browser worker and by the offline Rust solver
/// when describing the multi-engine plan for `web_search`. Sourced from
/// `crate::web_search_core::WEB_SEARCH_PROVIDERS` so the WASM worker and the
/// JS planner cannot drift apart (issue #133).
pub const WEB_SEARCH_PROVIDERS: &[&str] = CORE_WEB_SEARCH_PROVIDERS;

pub fn try_web_search(
    prompt: &str,
    normalized: &str,
    log: &mut EventLog,
) -> Option<SymbolicAnswer> {
    let query = extract_web_search_query(prompt, normalized)?;
    log.append("web_search:request", query.clone());
    for provider in WEB_SEARCH_PROVIDERS {
        log.append("web_search:provider", (*provider).to_owned());
    }
    log.append("web_search:combined", format!("rrf:k={WEB_SEARCH_RRF_K}"));
    let provider_summary = WEB_SEARCH_PROVIDERS.join(", ");
    let language = detect_language(prompt).slug();
    let body = match language {
        "ru" => format!(
            "Поиск в интернете запрошен для `{query}`.\n\n\
             В браузерной демо-версии formal-ai по умолчанию использует DuckDuckGo \
             Instant Answer (CORS-совместимый, без ключа) и параллельно опрашивает \
             Internet Archive, Wikipedia REST, Wikidata и Wiktionary в указанном \
             порядке приоритета. Топ-10 ссылок от каждого провайдера объединяются \
             через reciprocal rank fusion (`score(d) = Σ 1 / ({WEB_SEARCH_RRF_K} + \
             rank_i(d))`), поэтому URL, которые встречаются у нескольких провайдеров, \
             всплывают вверх. Дубликаты одной и той же сущности (например, \
             Викидата + Википедия) сворачиваются в один пункт с пометкой \
             «Другие источники». Для произвольной страницы используйте \
             `fetch example.com`; если прямой `fetch()` заблокирован CORS, \
             браузер проверит frame-policy перед встроенным iframe.\n\n\
             Provider: duckduckgo (default)\n\
             Providers considered: {provider_summary}\n\
             Combined ranking: reciprocal rank fusion (k = {WEB_SEARCH_RRF_K})"
        ),
        _ => format!(
            "Web search requested for `{query}`.\n\n\
             In the browser demo formal-ai defaults to the DuckDuckGo Instant \
             Answer endpoint (CORS-readable, keyless) and queries Internet Archive, \
             Wikipedia REST, Wikidata, and Wiktionary in that priority order. The \
             top-10 links from each provider are merged with reciprocal rank fusion \
             (`score(d) = Σ 1 / ({WEB_SEARCH_RRF_K} + rank_i(d))`), so URLs that \
             appear in more than one provider bubble up. Duplicate entries for the \
             same entity (e.g. Wikidata + Wikipedia) are collapsed into a single \
             bullet with an \"other sources\" footnote. For an arbitrary page, use \
             `fetch example.com`; if direct `fetch()` is blocked by CORS, the \
             browser checks frame policy before an embedded iframe.\n\n\
             Provider: duckduckgo (default)\n\
             Providers considered: {provider_summary}\n\
             Combined ranking: reciprocal rank fusion (k = {WEB_SEARCH_RRF_K})"
        ),
    };
    Some(finalize_simple(
        prompt,
        log,
        "web_search",
        "response:web_search",
        &body,
        0.8,
    ))
}

const PROMOTED_PROJECT_ORGS: &[&str] = &["link-assistant", "link-foundation", "linksplatform"];

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum RepositoryPlatform {
    GitHub,
    GitLab,
    Bitbucket,
}

impl RepositoryPlatform {
    const fn label(self) -> &'static str {
        match self {
            Self::GitHub => "GitHub",
            Self::GitLab => "GitLab",
            Self::Bitbucket => "Bitbucket",
        }
    }

    const fn host(self) -> &'static str {
        match self {
            Self::GitHub => "github.com",
            Self::GitLab => "gitlab.com",
            Self::Bitbucket => "bitbucket.org",
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct RepositoryReference {
    platform: RepositoryPlatform,
    owner: String,
    name: String,
    url: String,
}

impl RepositoryReference {
    fn slug(&self) -> String {
        format!("{}/{}", self.owner, self.name)
    }
}

/// Lookup repository/project prompts. Runs *after* `concept_lookup` so
/// seed-backed concept terms (`Links Notation`, `Wikipedia`, `Rust`, …) keep
/// their existing intent.
///
/// With promotion enabled (the default), known projects from Link Assistant,
/// Link Foundation, and `LinksPlatform` are listed first. With promotion
/// disabled, the same prompts stay on the generic repository lookup path.
pub fn try_project_lookup(
    prompt: &str,
    _normalized: &str,
    log: &mut EventLog,
    promote_associative_repositories: bool,
) -> Option<SymbolicAnswer> {
    if let Some(repo) = repository_from_prompt(prompt) {
        if promote_associative_repositories {
            if let Some(project) = promoted_project_by_repo(&repo.owner, &repo.name) {
                return Some(render_project_lookup(prompt, log, project));
            }
        }
        return Some(render_generic_repository_lookup(
            prompt,
            log,
            Some(&repo),
            promote_associative_repositories,
        ));
    }
    if matches!(select_rule_for(prompt), SelectedRule::Identity) {
        return None;
    }

    let project = matched_project(prompt)?;
    if promote_associative_repositories && is_promoted_project(project) {
        return Some(render_project_lookup(prompt, log, project));
    }

    Some(render_generic_repository_lookup(
        prompt,
        log,
        None,
        promote_associative_repositories,
    ))
}

fn render_project_lookup(
    prompt: &str,
    log: &mut EventLog,
    project: &ProjectRecord,
) -> SymbolicAnswer {
    let language = detect_language(prompt).slug();
    let config = SummarizationConfig::default()
        .with_mode(SummarizationMode::Short)
        .with_language(language);
    let description = describe_project(project, &config);
    let display_name = project.display_name_for(language);
    let repo_slug = project.repo_slug();
    let project_url = project.url.clone();

    log.append("project:promoted", repo_slug.clone());
    log.append("source", project_url.clone());
    log.append("summarization:mode", "short".to_owned());
    log.append("summarization:language", language.to_owned());
    log.append("web_search:request", display_name.to_owned());
    for provider in WEB_SEARCH_PROVIDERS {
        log.append("web_search:provider", (*provider).to_owned());
    }
    log.append("web_search:combined", format!("rrf:k={WEB_SEARCH_RRF_K}"));

    let provider_summary = WEB_SEARCH_PROVIDERS.join(", ");
    let promoted_orgs = PROMOTED_PROJECT_ORGS.join(", ");
    let body = match language {
        "ru" => format!(
            "В контексте репозиториев {promoted_orgs} под `{display_name}` я прежде всего \
             имею в виду [{repo_slug}]({project_url}) — {description}\n\n\
             Другие найденные в интернете репозитории и сущности должна показывать \
             браузерная демо-версия через поиск по запросу `{display_name}`. \
             Провайдеры: {provider_summary}. Ранжирование: reciprocal rank fusion \
             (k = {WEB_SEARCH_RRF_K}). Продвижение ассоциативных репозиториев \
             можно отключить, тогда ответ пойдет по обычному поиску GitHub, \
             GitLab и Bitbucket."
        ),
        _ => format!(
            "In the {promoted_orgs} repository context, `{display_name}` should first mean \
             [{repo_slug}]({project_url}) — {description}\n\n\
             Other repositories and entities found online are shown by the browser \
             demo through a web search for `{display_name}`. Providers: \
             {provider_summary}. Combined ranking: reciprocal rank fusion \
             (k = {WEB_SEARCH_RRF_K}). Associative repository promotion can be \
             switched off; then the answer follows the generic GitHub, GitLab, \
             and Bitbucket project lookup path."
        ),
    };
    finalize_simple(
        prompt,
        log,
        "project_lookup",
        "response:project_lookup",
        &body,
        0.9,
    )
}

fn render_generic_repository_lookup(
    prompt: &str,
    log: &mut EventLog,
    repository: Option<&RepositoryReference>,
    promotion_enabled: bool,
) -> SymbolicAnswer {
    let language = detect_language(prompt).slug();
    let provider_summary = ["GitHub", "GitLab", "Bitbucket"].join(", ");
    if !promotion_enabled {
        log.append("project_lookup:promotion", "disabled".to_owned());
    }
    if let Some(repo) = repository {
        let slug = repo.slug();
        append_repository_evidence(log, repo.platform, slug.clone());
        log.append("source", repo.url.clone());
        let label = repo.platform.label();
        let body = match language {
            "ru" => format!(
                "Это запрос о репозитории [{slug}]({url}) на {label}.\n\n\
                 Обычный путь project_lookup ищет и резюмирует README или описание \
                 проекта на GitHub, GitLab и Bitbucket без особого правила для \
                 отдельного названия. Если репозиторий находится в продвигаемых \
                 организациях и продвижение включено, он будет показан первым.",
                url = repo.url
            ),
            _ => format!(
                "This is a repository lookup for [{slug}]({url}) on {label}.\n\n\
                 The generic project_lookup path can summarize README or project \
                 descriptions from GitHub, GitLab, and Bitbucket without a special \
                 case for any single name. If the repository belongs to a promoted \
                 organization and promotion is enabled, that repository is listed \
                 first.",
                url = repo.url
            ),
        };
        return finalize_simple(
            prompt,
            log,
            "project_lookup",
            "response:project_lookup",
            &body,
            0.82,
        );
    }

    log.append("project_lookup:repository_hosts", provider_summary.clone());
    let body = match language {
        "ru" => format!(
            "Это обычный запрос project_lookup о проекте или репозитории.\n\n\
             Я не выделяю специальный репозиторий, потому что продвижение \
             ассоциативных репозиториев отключено. Дальше следует искать и \
             резюмировать подходящие проекты на {provider_summary} и похожих \
             хостингах."
        ),
        _ => format!(
            "This is a generic project_lookup request for a project or repository.\n\n\
             I am not privileging a specific repository because associative \
             repository promotion is disabled. The next step is to search and \
             summarize matching projects across {provider_summary} and similar \
             hosts."
        ),
    };
    finalize_simple(
        prompt,
        log,
        "project_lookup",
        "response:project_lookup",
        &body,
        0.72,
    )
}

fn append_repository_evidence(log: &mut EventLog, platform: RepositoryPlatform, slug: String) {
    let kind = match platform {
        RepositoryPlatform::GitHub => "project_lookup:repository:github",
        RepositoryPlatform::GitLab => "project_lookup:repository:gitlab",
        RepositoryPlatform::Bitbucket => "project_lookup:repository:bitbucket",
    };
    log.append(kind, slug);
}

/// Match the concept term against the curated project registry. Returns the
/// matching [`ProjectRecord`] or `None` when no curated project matches.
fn matched_project(prompt: &str) -> Option<&'static ProjectRecord> {
    let query = extract_concept_query(prompt)?;
    let term = normalize_concept_term(&query.term);
    if term.is_empty() {
        return None;
    }
    let registry = registry_static();
    if let Some(project) = registry.by_alias(&term) {
        return Some(project);
    }
    if term == "hivemind" {
        return registry.by_alias("hive mind");
    }
    None
}

fn promoted_project_by_repo(org: &str, name: &str) -> Option<&'static ProjectRecord> {
    let registry = registry_static();
    registry.projects.iter().find(|project| {
        is_promoted_project(project)
            && project.org.eq_ignore_ascii_case(org)
            && project.name.eq_ignore_ascii_case(name)
    })
}

fn is_promoted_project(project: &ProjectRecord) -> bool {
    PROMOTED_PROJECT_ORGS
        .iter()
        .any(|org| project.org.eq_ignore_ascii_case(org))
}

fn repository_from_prompt(prompt: &str) -> Option<RepositoryReference> {
    first_url_candidate(prompt)
        .and_then(|(_, url)| repository_from_url(&url))
        .or_else(|| repository_from_concept_term(prompt))
}

fn repository_from_concept_term(prompt: &str) -> Option<RepositoryReference> {
    let query = extract_concept_query(prompt)?;
    let term = query.term.trim();
    if term.contains("://") || looks_like_hostname(term) {
        return normalize_url_candidate(term).and_then(|url| repository_from_url(&url));
    }
    repository_from_slug(term)
}

fn repository_from_slug(term: &str) -> Option<RepositoryReference> {
    let trimmed = term
        .trim()
        .trim_matches(is_url_wrapper_punctuation)
        .trim_end_matches(is_url_trailing_punctuation);
    let mut segments = trimmed.split('/');
    let owner = clean_repository_segment(segments.next()?)?;
    let name = clean_repository_segment(segments.next()?)?;
    if segments.next().is_some() {
        return None;
    }
    Some(RepositoryReference {
        platform: RepositoryPlatform::GitHub,
        url: format!("https://github.com/{owner}/{name}"),
        owner,
        name,
    })
}

fn repository_from_url(url: &str) -> Option<RepositoryReference> {
    let after_scheme = url.split_once("://")?.1;
    let (host_port, path_with_suffix) = after_scheme.split_once('/')?;
    let host = host_port
        .split(':')
        .next()
        .unwrap_or_default()
        .trim_start_matches("www.")
        .to_ascii_lowercase();
    let platform = match host.as_str() {
        "github.com" => RepositoryPlatform::GitHub,
        "gitlab.com" => RepositoryPlatform::GitLab,
        "bitbucket.org" => RepositoryPlatform::Bitbucket,
        _ => return None,
    };
    let path = path_with_suffix
        .split(['?', '#'])
        .next()
        .unwrap_or_default();
    let mut segments = path.split('/').filter(|segment| !segment.is_empty());
    let owner = clean_repository_segment(segments.next()?)?;
    let name = clean_repository_segment(segments.next()?)?;
    Some(RepositoryReference {
        platform,
        url: format!("https://{}/{owner}/{name}", platform.host()),
        owner,
        name,
    })
}

fn clean_repository_segment(segment: &str) -> Option<String> {
    let trimmed = segment.trim().trim_end_matches(".git");
    if trimmed.is_empty() {
        return None;
    }
    if !trimmed
        .chars()
        .all(|ch| ch.is_ascii_alphanumeric() || matches!(ch, '-' | '_' | '.'))
    {
        return None;
    }
    Some(trimmed.to_owned())
}

fn normalize_concept_term(value: &str) -> String {
    normalize_prompt(value)
        .replace(['-', '_'], " ")
        .split_whitespace()
        .collect::<Vec<_>>()
        .join(" ")
}

/// Lazy-init the curated projects registry once per process. The seed file is
/// embedded via `include_str!` and the parsed form is immutable, so a `OnceLock`
/// is enough and avoids re-parsing on every prompt.
fn registry_static() -> &'static crate::seed::ProjectsRegistry {
    use std::sync::OnceLock;
    static REGISTRY: OnceLock<crate::seed::ProjectsRegistry> = OnceLock::new();
    REGISTRY.get_or_init(projects_registry)
}

fn extract_http_fetch_url(prompt: &str, normalized: &str) -> Option<String> {
    let (raw_candidate, url) = first_url_candidate(prompt)?;
    if !is_http_fetch_prompt(prompt, normalized, &raw_candidate) {
        return None;
    }
    Some(url)
}

fn extract_url_navigate_url(prompt: &str, normalized: &str) -> Option<String> {
    let (raw_candidate, url) = first_url_candidate(prompt)?;
    if !is_url_navigate_prompt(prompt, normalized, &raw_candidate) {
        return None;
    }
    Some(url)
}

fn first_url_candidate(prompt: &str) -> Option<(String, String)> {
    for token in prompt.split_whitespace() {
        let trimmed = trim_url_token(token);
        if let Some(url) = normalize_url_candidate(trimmed) {
            return Some((trimmed.to_owned(), url));
        }
    }
    None
}

fn trim_url_token(token: &str) -> &str {
    token
        .trim_matches(is_url_wrapper_punctuation)
        .trim_end_matches(is_url_trailing_punctuation)
}

const fn is_url_wrapper_punctuation(character: char) -> bool {
    matches!(
        character,
        '<' | '>' | '(' | ')' | '[' | ']' | '{' | '}' | '"' | '\'' | '`' | '«' | '»'
    )
}

const fn is_url_trailing_punctuation(character: char) -> bool {
    matches!(character, '.' | ',' | '!' | '?' | ';' | ':' | '')
}

fn normalize_url_candidate(candidate: &str) -> Option<String> {
    let candidate = candidate.trim();
    if candidate.is_empty() || candidate.contains(char::is_whitespace) || candidate.contains('@') {
        return None;
    }
    let lower = candidate.to_lowercase();
    let url = if lower.starts_with("http://") || lower.starts_with("https://") {
        candidate.to_owned()
    } else if lower.starts_with("www.") || looks_like_hostname(candidate) {
        format!("https://{candidate}")
    } else {
        return None;
    };
    let after_scheme = url.split_once("://")?.1;
    let host_port = after_scheme
        .split(['/', '?', '#'])
        .next()
        .unwrap_or_default();
    let host = host_port.split(':').next().unwrap_or_default();
    if !looks_like_hostname(host) {
        return None;
    }
    Some(url)
}

fn looks_like_hostname(value: &str) -> bool {
    let host = value.trim();
    if !host.contains('.') || host.starts_with('.') || host.ends_with('.') {
        return false;
    }
    let labels: Vec<&str> = host.split('.').collect();
    if labels.iter().any(|label| label.is_empty()) {
        return false;
    }
    let Some(tld) = labels.last() else {
        return false;
    };
    if tld.len() < 2 {
        return false;
    }
    labels.iter().all(|label| {
        label
            .chars()
            .all(|character| character.is_ascii_alphanumeric() || character == '-')
            && !label.starts_with('-')
            && !label.ends_with('-')
    })
}

/// Prefixes that mean "perform an HTTP request" — the browser worker will
/// attempt a real `fetch()` for these prompts before falling back to iframe.
const HTTP_FETCH_PREFIXES: &[&str] = &[
    "fetch ",
    "fetch url ",
    "http fetch ",
    "request ",
    "make request to ",
    "send request to ",
    "сделай запрос ",
    "сделай http запрос ",
    "выполни запрос ",
    "выполни http запрос ",
    "запроси ",
    "получи ",
    "http запрос к ",
    "http запрос на ",
    "сделать запрос к ",
    "выполнить запрос к ",
];

/// Markers that mean "perform an HTTP request" even when they appear after
/// other words in the prompt.
const HTTP_FETCH_MARKERS: &[&str] = &[
    "make a request to",
    "make an http request to",
    "send a request to",
    "send an http request to",
    "http request to",
    "http get to",
    "fetch the url",
    "fetch this url",
    "fetch the page",
    "сделай запрос к",
    "сделай запрос на",
    "сделай http запрос к",
    "сделай http запрос на",
    "выполни запрос к",
    "выполни запрос на",
    "выполни http запрос к",
    "выполни http запрос на",
    "запрос к",
    "запрос на",
    "http запрос к",
    "http запрос на",
];

fn is_http_fetch_prompt(prompt: &str, normalized: &str, _raw_candidate: &str) -> bool {
    let normalized_words = normalize_prompt(prompt);
    let raw = prompt.trim_start().to_lowercase();
    if HTTP_FETCH_PREFIXES.iter().any(|prefix| {
        normalized_words.starts_with(prefix)
            || normalized.starts_with(prefix)
            || raw.starts_with(prefix)
    }) {
        return true;
    }
    HTTP_FETCH_MARKERS.iter().any(|marker| {
        normalized_words.contains(marker) || normalized.contains(marker) || raw.contains(marker)
    })
}

/// Prefixes that mean "navigate to / show this page" — the browser worker
/// must NOT attempt `fetch()` for these prompts; it returns a direct external
/// link that the user can open in a new tab.
const URL_NAVIGATE_PREFIXES: &[&str] = &[
    "navigate to ",
    "navigate ",
    "go to ",
    "goto ",
    "visit ",
    "browse to ",
    "browse ",
    "show ",
    "show me ",
    "display ",
    "load ",
    "open ",
    "open url ",
    "open the url ",
    "open site ",
    "open website ",
    "open page ",
    "open the page ",
    "open the website ",
    "take me to ",
    "preview ",
    "view ",
    "see ",
    "перейди ",
    "перейди на ",
    "переходи на ",
    "переходи ",
    "перейдите на ",
    "открой ",
    "открой сайт ",
    "открой страницу ",
    "открой ссылку ",
    "открой урл ",
    "покажи ",
    "покажи сайт ",
    "покажи страницу ",
    "покажи мне ",
    "загрузи ",
    "загрузи страницу ",
    "посети ",
    "зайди на ",
    "зайди ",
    "просмотри ",
    "отобрази ",
];

/// Markers (anywhere in the prompt) that route to the URL navigation intent.
const URL_NAVIGATE_MARKERS: &[&str] = &[
    "navigate to",
    "go to",
    "goto",
    "browse to",
    "take me to",
    "open the page",
    "open the site",
    "open the website",
    "open the url",
    "open url",
    "перейди на",
    "переходи на",
    "перейдите на",
    "открой сайт",
    "открой страницу",
    "открой ссылку",
    "открой урл",
    "покажи сайт",
    "покажи страницу",
    "зайди на",
];

fn is_url_navigate_prompt(prompt: &str, normalized: &str, raw_candidate: &str) -> bool {
    let normalized_words = normalize_prompt(prompt);
    let prompt_trimmed = prompt.trim_start();
    if prompt_trimmed.starts_with(raw_candidate) {
        // Bare URL — treat as navigation, not a request to fetch.
        return true;
    }
    let raw = prompt_trimmed.to_lowercase();
    if URL_NAVIGATE_PREFIXES.iter().any(|prefix| {
        normalized_words.starts_with(prefix)
            || normalized.starts_with(prefix)
            || raw.starts_with(prefix)
    }) {
        return true;
    }
    URL_NAVIGATE_MARKERS.iter().any(|marker| {
        normalized_words.contains(marker) || normalized.contains(marker) || raw.contains(marker)
    })
}

fn extract_web_search_query(prompt: &str, normalized: &str) -> Option<String> {
    let normalized_words = normalize_prompt(prompt);
    if normalized_words.starts_with("search conversations ")
        || normalized_words.starts_with("search my conversations ")
        || normalized_words.starts_with("search my chats ")
    {
        return None;
    }
    let prefixes = [
        "search the web for ",
        "search web for ",
        "search the internet for ",
        "search internet for ",
        "search online for ",
        "web search for ",
        "find on the internet ",
        "find online ",
        "look up online ",
        "найди в интернете ",
        "поищи в интернете ",
        "поиск в интернете ",
        "найди онлайн ",
        "поищи онлайн ",
        "найди в сети ",
        "поищи в сети ",
    ];
    for prefix in prefixes {
        if let Some(query) = normalized_words.strip_prefix(prefix) {
            let query = clean_search_query(query);
            if !query.is_empty() && normalize_url_candidate(&query).is_none() {
                return Some(query);
            }
        }
        if let Some(query) = normalized.strip_prefix(prefix) {
            let query = clean_search_query(query);
            if !query.is_empty() && normalize_url_candidate(&query).is_none() {
                return Some(query);
            }
        }
    }
    None
}

fn clean_search_query(value: &str) -> String {
    value
        .trim()
        .trim_matches(is_url_wrapper_punctuation)
        .trim_end_matches(is_url_trailing_punctuation)
        .split_whitespace()
        .collect::<Vec<_>>()
        .join(" ")
}