@skyphusion/create-prism 1.2.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -64,10 +64,9 @@ template `wrangler.example.toml`.
64
64
 
65
65
  **Optional**
66
66
 
67
- - `SEARXNG_URL` (and the `SEARXNG_ACCESS_CLIENT_ID` / `SEARXNG_ACCESS_CLIENT_SECRET`
68
- halves when your SearXNG instance sits behind Cloudflare Access) enable the opt-in
69
- web-search source. Unset, web search silently skips SearXNG; keyless Wikipedia still
70
- runs.
67
+ - `SEARCH` service binding (`service = "skyphusion-search"`, `entrypoint = "SearchEntrypoint"`) enables the opt-in
68
+ web-search source. Delete the block if you have no such worker: the source then
69
+ reports `absent`, and keyless Wikipedia still runs.
71
70
 
72
71
  ## Auth: two modes, one identity seam (`AUTH_MODE`)
73
72
 
package/index.js CHANGED
@@ -131,8 +131,8 @@ Next steps:
131
131
  5. Set the worker secrets (access mode, the default):
132
132
  npx wrangler secret put GATEWAY_ID (your AI Gateway slug)
133
133
  npx wrangler secret put CF_AIG_TOKEN (AI Gateway Run token, for paid models)
134
- Optional web search: SEARXNG_URL (and the two SEARXNG_ACCESS_* halves if
135
- the instance is Access-gated). See the README for the full secret list.
134
+ Optional web search: the SEARCH service binding to skyphusion-search
135
+ (entrypoint SearchEntrypoint; delete the block if you have no such worker). See the README.
136
136
  6. Verify, then deploy:
137
137
  npm run typecheck
138
138
  npm test
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@skyphusion/create-prism",
3
- "version": "1.2.0",
3
+ "version": "1.3.0",
4
4
  "description": "Scaffold a new prism deployment: a multimodal AI playground on Cloudflare Workers.",
5
5
  "license": "AGPL-3.0-only",
6
6
  "author": "Conrad Rockenhaus",
@@ -231,7 +231,7 @@ One Worker, no framework, no build step beyond TypeScript. The interesting parts
231
231
 
232
232
  **Discord ingestion (v0.20.3+):** import a [DiscordChatExporter](https://github.com/Tyrrrz/DiscordChatExporter) JSON export into a project. The worker parses the export, groups messages into conversation-aware chunks (by author, time gap, and channel), and embeds them into the project's retrieval scope, so you can ask questions across an archived Discord channel's history. Import is a file picker in the project's "manage documents" modal.
233
233
 
234
- **Web search (v0.17.0):** opt-in retrieval source that queries self-hosted SearXNG (general web; v0.166.0) and Wikipedia (reference and lore) in parallel. Snippets folded into the system prompt the same way RAG chunks are. Per-turn toggle. SearXNG requires `SEARXNG_URL`; Wikipedia needs no setup. See [Web search](#web-search) below.
234
+ **Web search (v0.17.0):** opt-in retrieval source that queries the `skyphusion-search` Worker (service binding `SEARCH`) and Wikipedia (reference and lore) in parallel. Snippets folded into the system prompt the same way RAG chunks are. Per-turn toggle. Without the `SEARCH` binding that source reports absent; Wikipedia needs no setup. See [Web search](#web-search) below.
235
235
 
236
236
  **Streaming (v0.13.0+):** `POST /api/chat/stream` returns SSE for any chat model flagged `streaming: true` in the catalog. Token deltas surface as `{ type: "delta", text: "..." }` events, terminal completion as `{ type: "done", ... }` with token counts and conversation IDs. Client disconnect aborts the upstream model call immediately.
237
237
 
@@ -395,22 +395,18 @@ For an open, self-serve **public service**, do not use Cloudflare Access at all:
395
395
 
396
396
  Do **not** use a **Bypass** policy on the main app URL. Bypass skips login, so the worker never receives a user email and everyone shares the `anonymous` bucket.
397
397
 
398
- ### 7. Optional: web search (SearXNG)
398
+ ### 7. Optional: web search
399
399
 
400
- For the v0.17.0 web-search feature (SearXNG source added v0.166.0), point the worker at a self-hosted SearXNG instance with the JSON API enabled:
400
+ Web search calls the `skyphusion-search` Worker through a service binding. The committed template already declares it:
401
401
 
402
- ```
403
- npx wrangler secret put SEARXNG_URL
404
- ```
405
-
406
- If the instance is behind Cloudflare Access, also set the service-token halves:
407
-
408
- ```
409
- npx wrangler secret put SEARXNG_ACCESS_CLIENT_ID
410
- npx wrangler secret put SEARXNG_ACCESS_CLIENT_SECRET
402
+ ```toml
403
+ [[services]]
404
+ binding = "SEARCH"
405
+ service = "skyphusion-search"
406
+ entrypoint = "SearchEntrypoint"
411
407
  ```
412
408
 
413
- Without `SEARXNG_URL`, the SearXNG source is silently skipped. Wikipedia always works with no config. See [Web search](#web-search) below.
409
+ Copy that block into your `wrangler.toml`. If you do not run a worker with that script name, delete the block instead: `wrangler deploy` fails when the service does not exist. With the binding absent, the response says that source is `absent` and Wikipedia still runs. Wikipedia needs no config. See [Web search](#web-search) below.
414
410
 
415
411
  ### 8. Local development
416
412
 
@@ -464,7 +460,7 @@ npx wrangler secret put GATEWAY_ID
464
460
  npx wrangler secret put CF_AIG_TOKEN
465
461
  ```
466
462
 
467
- For local dev, leave those keys out of `.dev.vars` as well. The optional web-search config (`SEARXNG_URL`, plus `SEARXNG_ACCESS_CLIENT_ID` / `SEARXNG_ACCESS_CLIENT_SECRET` for a gated instance) still works if you want global features, but most public demos omit it so visitors rely on their own gateway for paid models.
463
+ For local dev, leave those keys out of `.dev.vars` as well. Web search is the `SEARCH` service binding, not a secret. Omit that block when you have no `skyphusion-search` worker; Wikipedia still runs. Most public demos omit gateway secrets so visitors rely on their own gateway for paid models.
468
464
 
469
465
  Do **not** create a Cloudflare Access application for a public-mode worker: the app has its own signup, and an Access gate in front would add a second login before it.
470
466
 
@@ -542,7 +538,7 @@ For D1 **schema** changes, see [Migrating an existing deployment](#migrating-an-
542
538
  |
543
539
  +---+---+
544
540
  | |
545
- SearXNG Wikipedia (web search)
541
+ SEARCH Wikipedia (web search)
546
542
  ```
547
543
 
548
544
  The worker is the only public surface. R2 is private; the worker streams objects through `GET /api/artifact/*` after verifying ownership via `customMetadata.user_email` on the R2 object.
@@ -624,7 +620,7 @@ Workers AI billing is per-token / per-image / per-minute depending on model. Fre
624
620
 
625
621
  D1 is roughly $0.75/GB-month for storage. R2 is roughly $0.015/GB-month with no egress fees inside Cloudflare. Free tiers on D1 and R2 cover small personal use indefinitely.
626
622
 
627
- Anthropic (Claude), xAI (Grok), OpenAI chat, Google Gemini, and proxied image / video / music models bill against your Cloudflare account via Unified Billing. Self-hosted SearXNG web search has no per-search API cost (you run the instance); Wikipedia is free. See per-provider sections below.
623
+ Anthropic (Claude), xAI (Grok), OpenAI chat, Google Gemini, and proxied image / video / music models bill against your Cloudflare account via Unified Billing. Web search through the `SEARCH` service binding stays on your Cloudflare account (no third-party search API). Wikipedia is free. See per-provider sections below.
628
624
 
629
625
  ## Anthropic models (Unified Billing)
630
626
 
@@ -941,48 +937,45 @@ DiscordChatExporter.Cli export -t <TOKEN> -c <CHANNEL_ID> -f Json \
941
937
 
942
938
  ## Web search
943
939
 
944
- An opt-in retrieval source (v0.17.0) that queries the web at request time and folds the snippets into the system prompt. Runs in parallel with RAG, so a single turn can pull from both your uploaded docs and the web. Designed for creative work, worldbuilding, and "what's current" questions where you want your model to do the synthesis rather than a search engine's pre-summary.
940
+ An opt-in retrieval source (v0.17.0) that retrieves at request time and folds the snippets into the system prompt. Runs in parallel with RAG, so a single turn can pull from your uploaded docs, the skyphusion-search corpus, and Wikipedia. The corpus half is Skyphusion public repos, not the open web. Wikipedia is the reference half.
945
941
 
946
942
  ### How it works
947
943
 
948
944
  When you check the "search the web" toggle next to the run button (chat models only), the worker fires two parallel queries on each turn:
949
945
 
950
- 1. **SearXNG** for general web results (v0.166.0). A self-hosted metasearch instance queried via its JSON API (`GET {SEARXNG_URL}/search?q=...&format=json`). Requires `SEARXNG_URL`; without it, this source is silently skipped. When the instance is gated by Cloudflare Access, the worker authenticates with a service token (`SEARXNG_ACCESS_CLIENT_ID` / `SEARXNG_ACCESS_CLIENT_SECRET`).
951
- 2. **Wikipedia** for reference and lore. No API key needed. Returns titles + HTML-stripped snippets via the public MediaWiki search endpoint.
946
+ 1. **skyphusion-search** for corpus hits. A service binding (`SEARCH`, entrypoint `SearchEntrypoint`) calls `search(question)` on the `skyphusion-search` Worker and reads `{ chunks }`. With the binding absent, the chat response reports `sources.web.status` `absent`. A thrown call reports `failed`. When the RPC throws `empty_question`, `question_too_long`, `rate_limited`, or `search_unavailable`, the error string is that code. An empty `chunks` array reports `ok` and count 0. Those three are different.
947
+ 2. **Wikipedia** for reference and lore. No API key needed. Returns titles + HTML-stripped snippets via the public MediaWiki search endpoint. Unchanged: it still answers when the web source fails or is absent.
952
948
 
953
- Both have an 8-second per-source timeout. If one fails or times out, the other still returns its hits. Results are persisted in the same `retrieved_context` column alongside any RAG chunks from the same turn, with a `source_type` discriminator so the UI can render web results (title + clickable URL + snippet) distinctly from doc chunks.
949
+ Both have an 8-second per-source timeout. If one fails or times out, the other still returns its hits. The chat JSON (and the stream `done` event) includes `sources.web` and `sources.wikipedia`, each `{ status, count, error? }`. `web_search_error` is set only when the web source failed. Results are persisted in the same `retrieved_context` column alongside any RAG chunks from the same turn, with a `source_type` discriminator so the UI can render web results (title + clickable URL + snippet) distinctly from doc chunks.
954
950
 
955
951
  Per-turn opt-in: the toggle is not sticky across turns. Each turn decides independently whether to search. Web search and RAG can be on simultaneously; the model sees both in the system prompt.
956
952
 
957
953
  ### Setup
958
954
 
959
- Run a SearXNG instance with the JSON output format enabled, then point the worker at it (Wikipedia needs no config):
955
+ Add the service binding to your `wrangler.toml` (already in `wrangler.example.toml`) and redeploy. Wikipedia needs no config.
960
956
 
961
- ```
962
- npx wrangler secret put SEARXNG_URL
963
- ```
964
-
965
- If the instance is behind Cloudflare Access (recommended for a private deployment), also set the service-token halves so the worker can authenticate:
966
-
967
- ```
968
- npx wrangler secret put SEARXNG_ACCESS_CLIENT_ID
969
- npx wrangler secret put SEARXNG_ACCESS_CLIENT_SECRET
957
+ ```toml
958
+ [[services]]
959
+ binding = "SEARCH"
960
+ service = "skyphusion-search"
961
+ entrypoint = "SearchEntrypoint"
970
962
  ```
971
963
 
972
- The worker sends them as `CF-Access-Client-Id` / `CF-Access-Client-Secret` only when both are set; leave them unset for an un-gated instance. Redeploy after setting secrets.
964
+ The binding calls the named entrypoint, not `POST /ask`. There is no Origin header and no Turnstile token. The search worker's script must export `SearchEntrypoint` (search-mcp). Delete the `[[services]]` block if that worker is not on your account.
973
965
 
974
966
  ### Caveats worth knowing
975
967
 
976
- - **Token budget.** Each turn with web search on adds roughly 2000-4000 tokens to the system prompt (up to 5 SearXNG snippets and 3 Wikipedia snippets). Long campaigns or document-heavy RAG turns may push against your model's context window.
977
- - **Self-hosting cost.** SearXNG is free and open-source; the only cost is running the instance. Search-every-turn would still burn context tokens, so the per-turn toggle is intentional.
968
+ - **Token budget.** Each turn with web search on adds roughly 2000-4000 tokens to the system prompt (up to 5 corpus snippets and 3 Wikipedia snippets). Long campaigns or document-heavy RAG turns may push against your model's context window.
969
+ - **Same-account call.** The binding does not leave your Cloudflare account and does not use a third-party search API. Search-every-turn would still burn context tokens, so the per-turn toggle is intentional.
970
+ - **The search worker can still refuse the call.** `search` throws `empty_question`, `question_too_long`, `rate_limited`, or `search_unavailable`. A refusal comes back as `sources.web.status` `failed` with that error code, and Wikipedia hits stay. An empty `chunks` array is `ok` with count 0.
978
971
  - **No fact-checking.** Web snippets are supplementary context, not authoritative. The system prompt tells the model so. Verify anything that matters before quoting it.
979
972
  - **Wikipedia User-Agent.** The worker identifies itself per Wikimedia's policy. If you fork to a different repo name, update the UA string in `searchWikipedia` so you're not lumped in with anonymous scrapers.
980
973
 
981
974
  ### When it shines
982
975
 
983
976
  - **Worldbuilding lore**: "Norse trickster mythology," "Edo period yokai," "Welsh place name etymology." Wikipedia alone covers most of this.
984
- - **Current events**: who holds an office, what just happened in the news.
985
- - **Mixed RAG + web**: your campaign uses a setting bible (uploaded as a doc) plus real-world historical detail. Toggle both; the model sees both context blocks.
977
+ - **This org's own docs**: how a Skyphusion repo is put together. That is what the corpus index holds. It is not a news search.
978
+ - **Mixed RAG + web**: your campaign uses a setting bible (uploaded as a doc) plus Wikipedia. Toggle both; the model sees both context blocks.
986
979
  - **Niche reference**: "17th-century apothecary daily routine," "Victorian funeral customs," anything where you want flavor without writing it yourself.
987
980
 
988
981
  ### When to leave it off
@@ -1077,7 +1070,7 @@ See [SECURITY.md](SECURITY.md) for vulnerability reporting.
1077
1070
 
1078
1071
  Built and maintained by [SkyPhusion](https://x.com/rockrockenhaus).
1079
1072
 
1080
- Built on Cloudflare Workers, Workers AI, AI Gateway, D1, R2, Vectorize, Workflows, and Cloudflare Access. Image generation models courtesy of Black Forest Labs and Leonardo.Ai. Text-to-speech via Deepgram. Speech-to-text via OpenAI Whisper. Web search via self-hosted SearXNG and Wikipedia.
1073
+ Built on Cloudflare Workers, Workers AI, AI Gateway, D1, R2, Vectorize, Workflows, and Cloudflare Access. Image generation models courtesy of Black Forest Labs and Leonardo.Ai. Text-to-speech via Deepgram. Speech-to-text via OpenAI Whisper. Web search via the skyphusion-search Worker and Wikipedia.
1081
1074
 
1082
1075
  ## Hosted instance policies (play.skyphusion.org)
1083
1076
 
@@ -172,20 +172,21 @@ if you have entered a control-plane client key, chat through play-proxy as descr
172
172
  through play-proxy" above.
173
173
 
174
174
  **Web search is opt-in and does not use any third-party search API.** Prism has a per-turn web search
175
- toggle. When you switch it on for a turn, the text of that one query is sent to keyless public sources,
176
- today Wikipedia (the public MediaWiki search endpoint). The software can also query a SearXNG metasearch
177
- instance, but **the hosted instance has no SearXNG service**: the one Skyphusion Labs ran at
178
- search.skyphusion.org was retired with the September 2026 infrastructure change and that hostname no
179
- longer resolves, so on this instance the SearXNG source returns nothing and the query reaches Wikipedia
180
- alone. No third-party search-API provider (and no per-provider API key) is in the path. The snippets
175
+ toggle. When you switch it on for a turn, the text of that one query is sent to two places, and nowhere
176
+ else. One is Wikipedia (the public MediaWiki search endpoint), which needs no key. The other is the
177
+ `skyphusion-search` Worker, a Skyphusion Labs Worker on the same Cloudflare account, reached by a
178
+ service binding named `SEARCH` (not over the public internet, and not with an API key). That Worker
179
+ searches Skyphusion's public corpus. If the binding is not configured, that half does not run and the
180
+ response says so (`sources.web.status` is `absent`). If the call fails, the response says `failed`
181
+ rather than pretending the corpus had nothing. Wikipedia still answers in both cases. The snippets
181
182
  that come back are stored with the turn as retrieved context, the same way your RAG chunks are. Your
182
183
  chat history, your uploaded documents, and your generated media are never sent out for search. Leave
183
184
  the toggle off and no query leaves the instance.
184
185
 
185
- **Correction (2026-10-13).** Earlier versions of this notice said the query also went to a self-hosted
186
- SearXNG service run by Skyphusion Labs. That service no longer exists, and the paragraph above describes
187
- the instance as it runs today. If a search service is stood up again, this notice will be updated to
188
- name it.
186
+ **Correction (2026-11-12).** Earlier versions of this notice said the query also went to a self-hosted
187
+ search service at search.skyphusion.org, and then that the hosted instance had no such service. That
188
+ host is gone. This version sends the query to the `skyphusion-search` Worker as described above. The
189
+ hosted worker has no search secret to remove.
189
190
 
190
191
  ## Deleting your data
191
192
 
@@ -880,7 +880,7 @@ function renderRetrievedChunksHTML(chunks) {
880
880
  if (c.source_type === "web") {
881
881
  const score = (typeof c.score === "number") ? ` \u00b7 score ${c.score.toFixed(3)}` : "";
882
882
  const sourceLabel =
883
- c.source === "searxng" ? "web" :
883
+ c.source === "searxng" || c.source === "skyphusion-search" ? "web" :
884
884
  c.source === "wikipedia" ? "wikipedia" : "web";
885
885
  return `
886
886
  <details class="retrieved-chunk retrieved-web">
@@ -1438,7 +1438,7 @@ async function run() {
1438
1438
  if (m.type === "chat" && useDocsCheckbox.checked && state.documentCount > 0) {
1439
1439
  requestBody.use_docs = true;
1440
1440
  }
1441
- // v0.17.0: web search. Chat models only; SearXNG + Wikipedia when toggled (v0.166.0).
1441
+ // v0.17.0: web search. Chat models only; skyphusion-search + Wikipedia when toggled.
1442
1442
  if (m.type === "chat" && useWebSearchCheckbox.checked) {
1443
1443
  requestBody.use_web_search = true;
1444
1444
  }
@@ -1,11 +1,11 @@
1
1
  // URL safety for values this app did not construct.
2
2
  //
3
- // Web-search results reach the transcript carrying a `url` field that
4
- // originates off-box. SearXNG hands upstream engine results through with a
5
- // truthiness filter only (src/searxng.ts filters on `r.url && r.title` and
6
- // never parses), src/routes/rag.ts maps them to source_type:"web", and the
7
- // value is persisted in retrieved_context and replayed on every subsequent
8
- // transcript render. So the string in an href there is not ours.
3
+ // Web-search rows reach the transcript carrying a `url` field that is
4
+ // persisted in retrieved_context and replayed on every later render.
5
+ // Current rows use a URL this worker built (src/skyphusion-search.ts).
6
+ // Older rows carry a URL from an upstream engine that the worker stored
7
+ // after a truthiness check only. Either way the href is replayed from D1,
8
+ // so the string is not trusted at render time.
9
9
  //
10
10
  // WHY ESCAPING IS THE WRONG TOOL HERE. escapeHtml() replaces & < > " ' and is
11
11
  // exactly right for stopping attribute injection. It does nothing whatever to
@@ -12,6 +12,26 @@
12
12
  // secret runtime paths surface meaningful errors instead of TypeScript
13
13
  // telling deployers they need fields they may legitimately not have set.
14
14
 
15
+ // Subset of search-mcp AiSearchChunk that SearchEntrypoint.search returns.
16
+ // Extra fields on the wire are ignored. The mapper lives in
17
+ // src/skyphusion-search.ts.
18
+ export interface SearchChunk {
19
+ score?: number;
20
+ text?: string;
21
+ item?: {
22
+ key?: string;
23
+ metadata?: { repo?: string; path?: string };
24
+ };
25
+ }
26
+
27
+ // Named RPC entrypoint on the skyphusion-search Worker. The binding
28
+ // field in wrangler is `entrypoint = "SearchEntrypoint"`. The method
29
+ // is search(question), not POST /ask.
30
+ // https://developers.cloudflare.com/workers/runtime-apis/bindings/service-bindings/rpc/#named-entrypoints
31
+ export interface SearchEntrypoint extends Rpc.WorkerEntrypointBranded {
32
+ search(question: string): Promise<{ chunks: SearchChunk[] }>;
33
+ }
34
+
15
35
  export interface Env {
16
36
  AI: Ai;
17
37
  DB: D1Database;
@@ -68,14 +88,11 @@ export interface Env {
68
88
  // stay on Unified Billing and render opaque. No other provider reads a
69
89
  // deployer key.
70
90
  OPENAI_API_KEY?: string;
71
- // v0.166.0: base URL of the self-hosted SearXNG instance for the optional
72
- // web-search retrieval source (our deploy: https://search.skyphusion.org).
73
- // Optional: when unset, the SearXNG source is silently skipped (Wikipedia,
74
- // which needs no config, still runs). May be a plain [vars] entry or a secret.
75
- SEARXNG_URL?: string;
76
- // v0.166.0: Cloudflare Access service-token halves for a gated SearXNG
77
- // instance. Sent as CF-Access-Client-Id / CF-Access-Client-Secret ONLY when
78
- // both are set; a self-hoster running an un-gated instance leaves them unset.
79
- SEARXNG_ACCESS_CLIENT_ID?: string;
80
- SEARXNG_ACCESS_CLIENT_SECRET?: string;
91
+ // Service binding to the skyphusion-search Worker, named entrypoint
92
+ // SearchEntrypoint. Optional: when the binding is absent, web search
93
+ // reports that source as "absent" and Wikipedia still runs. Declared
94
+ // in wrangler.example.toml as [[services]] binding = "SEARCH",
95
+ // service = "skyphusion-search", entrypoint = "SearchEntrypoint".
96
+ // search(question) returns { chunks }. This is not POST /ask.
97
+ SEARCH?: Service<SearchEntrypoint>;
81
98
  }
@@ -43,9 +43,11 @@ import {
43
43
  retrieveContext,
44
44
  RETRIEVE_TOP_K,
45
45
  searchWeb,
46
+ noWebSearch,
46
47
  formatRetrievalForSystemPrompt,
47
48
  formatWebForSystemPrompt,
48
49
  looksBinary,
50
+ type WebSearchOutcome,
49
51
  } from "./rag";
50
52
  import { resolveProjectForChat } from "./projects";
51
53
  import type { LongRunParams } from "./workflow";
@@ -237,10 +239,10 @@ export async function runChat(request: Request, env: Env, model: ModelEntry, bod
237
239
  // v0.17.0: web search runs in parallel with RAG retrieval and the
238
240
  // attachment walk. Per-source timeouts + catches inside searchWeb bound
239
241
  // the worst-case latency to WEB_SEARCH_TIMEOUT_MS.
240
- const webSearchPromise: Promise<{ results: RetrievedWebResult[]; error: string | null }> =
242
+ const webSearchPromise: Promise<WebSearchOutcome> =
241
243
  body.use_web_search
242
244
  ? searchWeb(env, body.user_input)
243
- : Promise.resolve({ results: [], error: null });
245
+ : Promise.resolve(noWebSearch());
244
246
 
245
247
  // Walk inputs: write images / video frames to R2, transcribe audio via
246
248
  // Whisper. Build three parallel structures used after the loop:
@@ -360,7 +362,7 @@ export async function runChat(request: Request, env: Env, model: ModelEntry, bod
360
362
  const { chunks: retrievedChunks, error: retrievalError } = await retrievePromise;
361
363
 
362
364
  // v0.17.0: web-search retrieval, same parallelism pattern as RAG.
363
- const { results: webResults, error: webSearchError } = await webSearchPromise;
365
+ const { results: webResults, error: webSearchError, sources: webSources } = await webSearchPromise;
364
366
  const allRetrieved: RetrievedItem[] = [...retrievedChunks, ...webResults];
365
367
 
366
368
  // Build the effective system prompt: user-supplied prompt, optional compact
@@ -522,6 +524,9 @@ export async function runChat(request: Request, env: Env, model: ModelEntry, bod
522
524
  effective_system_prompt: (body.use_docs || body.use_web_search) ? effectiveSystemPrompt : undefined,
523
525
  retrieval_error: body.use_docs ? retrievalError : undefined,
524
526
  web_search_error: body.use_web_search ? webSearchError : undefined,
527
+ // Per-source status. "ok" with count 0 is zero hits. "failed" is a
528
+ // broken web source. "absent" means the SEARCH binding is not configured.
529
+ sources: body.use_web_search ? webSources : undefined,
525
530
  });
526
531
  }
527
532
 
@@ -1274,10 +1279,10 @@ export async function runChatStream(request: Request, env: Env, model: ModelEntr
1274
1279
  : Promise.resolve({ chunks: [], error: null });
1275
1280
 
1276
1281
  // v0.17.0: web search runs in parallel with RAG retrieval, same as runChat.
1277
- const webSearchPromise: Promise<{ results: RetrievedWebResult[]; error: string | null }> =
1282
+ const webSearchPromise: Promise<WebSearchOutcome> =
1278
1283
  body.use_web_search
1279
1284
  ? searchWeb(env, body.user_input)
1280
- : Promise.resolve({ results: [], error: null });
1285
+ : Promise.resolve(noWebSearch());
1281
1286
 
1282
1287
  // Attachment walk. Reach completion before any bytes flow back; streaming
1283
1288
  // helps with time-to-last-token, not time-to-first-token on multimodal turns.
@@ -1374,7 +1379,7 @@ export async function runChatStream(request: Request, env: Env, model: ModelEntr
1374
1379
  }
1375
1380
 
1376
1381
  const { chunks: retrievedChunks } = await retrievePromise;
1377
- const { results: webResults } = await webSearchPromise;
1382
+ const { results: webResults, error: webSearchError, sources: webSources } = await webSearchPromise;
1378
1383
  const allRetrieved: RetrievedItem[] = [...retrievedChunks, ...webResults];
1379
1384
 
1380
1385
  const userSystemPrompt = body.system_prompt?.trim() ?? "";
@@ -1497,6 +1502,8 @@ export async function runChatStream(request: Request, env: Env, model: ModelEntr
1497
1502
  tokens_out: usageOut,
1498
1503
  conversation_id: conversationId,
1499
1504
  turn_index: turnIndex,
1505
+ web_search_error: body.use_web_search ? webSearchError : undefined,
1506
+ sources: body.use_web_search ? webSources : undefined,
1500
1507
  });
1501
1508
  } catch (err) {
1502
1509
  // Self-triggered AbortError (we aborted because client disconnected)
@@ -11,7 +11,7 @@ import type { Env } from "../env";
11
11
  import { aiRun, type AiContext } from "../ai-binding";
12
12
  import { requireGatewayCredentials } from "../gateway-credentials";
13
13
  import { chunkText } from "../chunking";
14
- import { searchSearxngWeb } from "../searxng";
14
+ import { askSkyphusionSearch } from "../skyphusion-search";
15
15
  import { r2Put, r2DeleteSafe } from "./shared";
16
16
  import type { RetrievedChunk, RetrievedWebResult } from "./shared";
17
17
 
@@ -66,10 +66,9 @@ export function mimeFromName(name: string): string {
66
66
  }
67
67
 
68
68
  // v0.17.0: web-search retrieval limits and timeouts. Each upstream is
69
- // time-bounded per source so a slow SearXNG doesn't block Wikipedia.
69
+ // time-bounded per source so a slow web source does not block Wikipedia.
70
70
  // Counts kept small to bound context-token spend when the toggle is on.
71
- // v0.166.0: SearXNG replaced the retired Tavily + Brave SaaS sources.
72
- export const SEARXNG_MAX_RESULTS = 5;
71
+ export const SEARCH_MAX_RESULTS = 5;
73
72
  export const WIKIPEDIA_MAX_RESULTS = 3;
74
73
  export const WEB_SEARCH_TIMEOUT_MS = 8000;
75
74
 
@@ -430,58 +429,117 @@ export function formatRetrievalForSystemPrompt(chunks: RetrievedChunk[]): string
430
429
 
431
430
  // ---------- Web search (v0.17.0) ----------
432
431
  //
433
- // Optional retrieval source: SearXNG (self-hosted metasearch) for general web,
434
- // Wikipedia for lore / reference. Both run in parallel; failure of one doesn't
435
- // kill the other. Per-source timeouts (WEB_SEARCH_TIMEOUT_MS) prevent a slow
436
- // upstream from blocking the whole turn.
432
+ // Optional retrieval source: the skyphusion-search Worker (service binding
433
+ // SEARCH) for corpus hits, Wikipedia for lore / reference. Both run in
434
+ // parallel; failure of one does not kill the other. Per-source timeouts
435
+ // (WEB_SEARCH_TIMEOUT_MS) prevent a slow upstream from blocking the turn.
437
436
  //
438
- // SearXNG requires SEARXNG_URL; when unset, that source is silently skipped.
439
- // Wikipedia needs no config. (v0.166.0: SearXNG replaced the retired Tavily +
440
- // Brave SaaS sources; see prism#93.)
437
+ // SEARCH absent is its own status ("absent"), not a failure and not zero
438
+ // hits. A thrown RPC error is "failed". The error string is the RPC
439
+ // message: empty_question, question_too_long, rate_limited,
440
+ // search_unavailable, or whatever else was thrown. An empty chunks
441
+ // array is "ok" with count 0. Callers read `sources` to tell those
442
+ // apart. `error` is set only when the web source failed, so a
443
+ // Wikipedia miss does not look like a web-source failure. Wikipedia
444
+ // itself is unchanged: same MediaWiki request, and its hits still
445
+ // return when the web source fails or is absent.
441
446
  //
442
447
  // Results are persisted to the existing retrieved_context column alongside
443
448
  // RAG chunks, with source_type discriminator. The frontend renders branches
444
449
  // on source_type to show the source URL for web results.
445
450
 
446
- export async function searchWeb(
447
- env: Env,
448
- query: string
449
- ): Promise<{ results: RetrievedWebResult[]; error: string | null }> {
450
- const q = query.trim();
451
- if (!q) return { results: [], error: null };
452
-
453
- // Each upstream is wrapped in its own timeout + catch so a single failure
454
- // doesn't abort the other. Partial results are better than nothing.
455
- const searxngPromise: Promise<RetrievedWebResult[]> = env.SEARXNG_URL
456
- ? searchSearxng(env, q).catch(() => [])
457
- : Promise.resolve([]);
458
- const wikipediaPromise: Promise<RetrievedWebResult[]> = searchWikipedia(q).catch(() => []);
459
-
460
- const [searxng, wikipedia] = await Promise.all([searxngPromise, wikipediaPromise]);
461
- const results = [...searxng, ...wikipedia];
462
-
463
- // Empty results is fine; it just means the query didn't match anything in
464
- // any source. Real per-source failures are swallowed by the .catch above
465
- // so the other source can still return its hits.
466
- return { results, error: null };
451
+ export type WebSourceStatus = "ok" | "failed" | "absent";
452
+
453
+ export interface WebSourceReport {
454
+ status: WebSourceStatus;
455
+ count: number;
456
+ error?: string;
467
457
  }
468
458
 
469
- export async function searchSearxng(env: Env, query: string): Promise<RetrievedWebResult[]> {
470
- // Access service-token headers are sent only when both halves are set, so an
471
- // un-gated self-hosted instance is reached with no headers.
472
- const hits = await searchSearxngWeb(env.SEARXNG_URL!, query, {
473
- maxResults: SEARXNG_MAX_RESULTS,
474
- timeoutMs: WEB_SEARCH_TIMEOUT_MS,
475
- accessClientId: env.SEARXNG_ACCESS_CLIENT_ID,
476
- accessClientSecret: env.SEARXNG_ACCESS_CLIENT_SECRET,
477
- });
478
- return hits.map((r): RetrievedWebResult => ({
479
- source_type: "web",
480
- source: "searxng",
481
- url: r.url,
482
- title: r.title,
483
- snippet: r.snippet,
484
- }));
459
+ export interface WebSearchOutcome {
460
+ results: RetrievedWebResult[];
461
+ error: string | null;
462
+ sources: {
463
+ web: WebSourceReport;
464
+ wikipedia: WebSourceReport;
465
+ };
466
+ }
467
+
468
+ export function noWebSearch(): WebSearchOutcome {
469
+ return {
470
+ results: [],
471
+ error: null,
472
+ sources: {
473
+ web: { status: "ok", count: 0 },
474
+ wikipedia: { status: "ok", count: 0 },
475
+ },
476
+ };
477
+ }
478
+
479
+ interface SourceRun {
480
+ results: RetrievedWebResult[];
481
+ status: WebSourceStatus;
482
+ error?: string;
483
+ }
484
+
485
+ function reportSource(run: SourceRun): WebSourceReport {
486
+ const report: WebSourceReport = { status: run.status, count: run.results.length };
487
+ if (run.error) report.error = run.error;
488
+ return report;
489
+ }
490
+
491
+ async function runWebSource(env: Env, query: string): Promise<SourceRun> {
492
+ if (!env.SEARCH) return { results: [], status: "absent" };
493
+ try {
494
+ const hits = await askSkyphusionSearch(env.SEARCH, query, {
495
+ timeoutMs: WEB_SEARCH_TIMEOUT_MS,
496
+ maxResults: SEARCH_MAX_RESULTS,
497
+ });
498
+ return {
499
+ status: "ok",
500
+ results: hits.map((hit): RetrievedWebResult => ({
501
+ source_type: "web",
502
+ source: "skyphusion-search",
503
+ url: hit.url,
504
+ title: hit.title,
505
+ snippet: hit.snippet,
506
+ ...(hit.score !== undefined ? { score: hit.score } : {}),
507
+ })),
508
+ };
509
+ } catch (err) {
510
+ const message = err instanceof Error ? err.message : String(err);
511
+ return { results: [], status: "failed", error: message };
512
+ }
513
+ }
514
+
515
+ async function runWikipedia(query: string): Promise<SourceRun> {
516
+ try {
517
+ return { results: await searchWikipedia(query), status: "ok" };
518
+ } catch (err) {
519
+ const message = err instanceof Error ? err.message : String(err);
520
+ return { results: [], status: "failed", error: message };
521
+ }
522
+ }
523
+
524
+ export async function searchWeb(env: Env, query: string): Promise<WebSearchOutcome> {
525
+ const q = query.trim();
526
+ if (!q) return noWebSearch();
527
+
528
+ const [web, wiki] = await Promise.all([runWebSource(env, q), runWikipedia(q)]);
529
+ if (web.status === "failed") {
530
+ console.error("searchWeb: skyphusion-search failed:", web.error ?? "unknown");
531
+ }
532
+ if (wiki.status === "failed") {
533
+ console.error("searchWeb: wikipedia failed:", wiki.error ?? "unknown");
534
+ }
535
+ return {
536
+ results: [...web.results, ...wiki.results],
537
+ error: web.status === "failed" ? (web.error ?? "web search failed") : null,
538
+ sources: {
539
+ web: reportSource(web),
540
+ wikipedia: reportSource(wiki),
541
+ },
542
+ };
485
543
  }
486
544
 
487
545
  export async function searchWikipedia(query: string): Promise<RetrievedWebResult[]> {
@@ -552,7 +610,7 @@ export function stripWikipediaSnippet(html: string): string {
552
610
 
553
611
  export function webSourceSystemLabel(source: RetrievedWebResult["source"]): string {
554
612
  switch (source) {
555
- case "searxng": return "Web";
613
+ case "skyphusion-search": return "Web";
556
614
  case "wikipedia": return "Wikipedia";
557
615
  }
558
616
  }
@@ -32,7 +32,7 @@ export interface ChatRequest {
32
32
  image_url?: string; // v0.21.5: source image for image-to-video models (hh1-i2v); a fetchable URL
33
33
  image_key?: string; // v0.21.6: source image as an R2 key (e.g. a prior nano-banana output) for image-to-video chaining
34
34
  use_docs?: boolean; // Pass 2: when true, retrieve top-K chunks from Vectorize and inject as context
35
- use_web_search?: boolean; // v0.17.0: when true, query SearXNG + Wikipedia and inject snippets as context
35
+ use_web_search?: boolean; // v0.17.0: when true, query skyphusion-search + Wikipedia and inject snippets as context
36
36
  conversation_id?: string; // Multi-turn: when present, continue an existing conversation
37
37
  project_id?: number; // v0.20.0: when present, scope RAG retrieval to the project's docs
38
38
  // and apply the project's system_prompt as default if system_prompt is empty
@@ -55,7 +55,10 @@ export interface RetrievedChunk {
55
55
  // retrieved_context column. The frontend renders branches on source_type.
56
56
  export interface RetrievedWebResult {
57
57
  source_type: "web";
58
- source: "searxng" | "wikipedia";
58
+ // "skyphusion-search" is the service-binding corpus source. Older rows
59
+ // stored "searxng"; the UI still labels those as web. New writes use
60
+ // "skyphusion-search" only.
61
+ source: "skyphusion-search" | "wikipedia";
59
62
  url: string;
60
63
  title: string;
61
64
  snippet: string; // already HTML-stripped
@@ -0,0 +1,108 @@
1
+ // skyphusion-search retrieval, via the SEARCH service binding.
2
+ //
3
+ // Contract pinned from skyphusion-labs/search-mcp (PR #147). The worker
4
+ // exports a named entrypoint SearchEntrypoint. The caller selects it
5
+ // with wrangler `entrypoint = "SearchEntrypoint"` on the service
6
+ // binding. Internet fetch still hits the default export, so this client
7
+ // does not call POST /ask and does not send an Origin header.
8
+ //
9
+ // search(question: string) returns { chunks }. Fields used here match
10
+ // AiSearchChunk: score, text, item.key, item.metadata.repo,
11
+ // item.metadata.path. Chunks carry no URL. A hit links to
12
+ // https://github.com/skyphusion-labs/<repo>/blob/main/<path>, the
13
+ // public corpus that worker indexes. metadata.path wins over the R2
14
+ // key. A path taken from the key drops a trailing ".txt" that corpus
15
+ // ingest adds (same rule as search-mcp src/mcp.ts mapSearchChunks).
16
+ //
17
+ // The question must be a non-empty string of at most 2000 characters
18
+ // after trim. A bad call throws Error with one of these messages:
19
+ // empty_question, question_too_long, rate_limited, search_unavailable.
20
+ // The caller reports that message as sources.web error and status
21
+ // "failed". An empty chunks array is zero hits, not a failure. A
22
+ // missing binding is "absent", and the caller decides that before
23
+ // this function runs.
24
+
25
+ import type { SearchChunk, SearchEntrypoint } from "./env";
26
+
27
+ const GITHUB_BLOB = "https://github.com/skyphusion-labs";
28
+ const PATH_SEGMENT = /^[A-Za-z0-9._-]+$/;
29
+
30
+ export interface SearchHit {
31
+ title: string;
32
+ url: string;
33
+ snippet: string;
34
+ score?: number;
35
+ }
36
+
37
+ function repoAndPath(chunk: SearchChunk): { repo: string; path: string } | null {
38
+ const meta = chunk.item?.metadata;
39
+ const key = typeof chunk.item?.key === "string" ? chunk.item.key.trim() : "";
40
+ const slash = key.indexOf("/");
41
+ const keyRepo = slash > 0 ? key.slice(0, slash) : "";
42
+ const keyPath = slash > 0 ? key.slice(slash + 1).replace(/\.txt$/, "") : "";
43
+ const repo = (typeof meta?.repo === "string" ? meta.repo.trim() : "") || keyRepo;
44
+ const path = (typeof meta?.path === "string" ? meta.path.trim() : "") || keyPath;
45
+ if (!repo || !path) return null;
46
+ return { repo, path };
47
+ }
48
+
49
+ function corpusUrl(repo: string, path: string): string | null {
50
+ if (!PATH_SEGMENT.test(repo)) return null;
51
+ const parts = path.split("/");
52
+ // "." and ".." match the segment pattern (dots and nothing else) and must
53
+ // still be refused, or a key can climb out of the repo path.
54
+ if (parts.some((seg) => seg === "." || seg === ".." || !PATH_SEGMENT.test(seg))) return null;
55
+ return `${GITHUB_BLOB}/${repo}/blob/main/${parts.map((seg) => encodeURIComponent(seg)).join("/")}`;
56
+ }
57
+
58
+ export function mapSearchChunks(chunks: readonly SearchChunk[], maxResults: number): SearchHit[] {
59
+ const out: SearchHit[] = [];
60
+ const seen = new Set<string>();
61
+ const cap = Math.max(0, maxResults);
62
+ for (const chunk of chunks) {
63
+ if (!chunk || typeof chunk !== "object") continue;
64
+ const id = repoAndPath(chunk);
65
+ if (!id) continue;
66
+ const url = corpusUrl(id.repo, id.path);
67
+ if (!url || seen.has(url)) continue;
68
+ seen.add(url);
69
+ const snippet = typeof chunk.text === "string"
70
+ ? chunk.text.replace(/\s+/g, " ").trim()
71
+ : "";
72
+ const hit: SearchHit = { title: `${id.repo}/${id.path}`, url, snippet };
73
+ if (typeof chunk.score === "number" && Number.isFinite(chunk.score)) hit.score = chunk.score;
74
+ out.push(hit);
75
+ if (out.length >= cap) break;
76
+ }
77
+ return out;
78
+ }
79
+
80
+ // The RPC method takes no AbortSignal. Race a timer so a stuck call still
81
+ // fails this source inside the caller's timeout, then clear the timer so
82
+ // a fast call does not hold the process open.
83
+ function withTimeout<T>(work: Promise<T>, ms: number): Promise<T> {
84
+ let timer: ReturnType<typeof setTimeout> | undefined;
85
+ const timeout = new Promise<never>((_, reject) => {
86
+ timer = setTimeout(() => reject(new Error("skyphusion-search timeout")), ms);
87
+ });
88
+ // If the timer wins, a later rejection of `work` must not surface as
89
+ // unhandled. The race below still rejects with the original error when
90
+ // `work` loses first.
91
+ void work.catch(() => {});
92
+ return Promise.race([work, timeout]).finally(() => {
93
+ if (timer !== undefined) clearTimeout(timer);
94
+ });
95
+ }
96
+
97
+ export async function askSkyphusionSearch(
98
+ binding: Service<SearchEntrypoint>,
99
+ query: string,
100
+ opts: { timeoutMs: number; maxResults: number },
101
+ ): Promise<SearchHit[]> {
102
+ const question = query.trim();
103
+ const result = await withTimeout(binding.search(question), opts.timeoutMs);
104
+ if (!result || !Array.isArray(result.chunks)) {
105
+ throw new Error("search_unavailable");
106
+ }
107
+ return mapSearchChunks(result.chunks, opts.maxResults);
108
+ }
@@ -15,4 +15,4 @@
15
15
  // That distinction is the entire point. In prism-mcp the advertised version was a literal and
16
16
  // the test asserting it carried a TRANSCRIBED duplicate, so the assertion only ever proved
17
17
  // that someone had typed the same thing twice, and a correct version bump went red.
18
- export const VERSION = "1.2.0";
18
+ export const VERSION = "1.3.0";
@@ -0,0 +1,144 @@
1
+ import { afterEach, describe, expect, it, vi } from "vitest";
2
+ import type { Env } from "../src/env";
3
+ import { searchWeb } from "../src/routes/rag";
4
+ import { mapSearchChunks } from "../src/skyphusion-search";
5
+
6
+ const RPC_ERRORS = [
7
+ "empty_question",
8
+ "question_too_long",
9
+ "rate_limited",
10
+ "search_unavailable",
11
+ ] as const;
12
+
13
+ const WIKI_HIT = {
14
+ query: {
15
+ search: [{ title: "Ada Lovelace", snippet: "Mathematician", pageid: 42 }],
16
+ },
17
+ };
18
+
19
+ const CHUNK = {
20
+ text: " prism workers ",
21
+ score: 0.42,
22
+ item: {
23
+ key: "prism/README.md.txt",
24
+ metadata: { repo: "prism", path: "README.md" },
25
+ },
26
+ };
27
+
28
+ function wikiResponse(): Response {
29
+ return new Response(JSON.stringify(WIKI_HIT), {
30
+ status: 200,
31
+ headers: { "content-type": "application/json" },
32
+ });
33
+ }
34
+
35
+ function installWikipediaFetch() {
36
+ const fetchMock = vi.fn(async (input: RequestInfo | URL) => {
37
+ const url = typeof input === "string"
38
+ ? input
39
+ : input instanceof URL
40
+ ? input.toString()
41
+ : input.url;
42
+ if (!url.includes("https://en.wikipedia.org/w/api.php")) {
43
+ throw new Error(`unexpected global fetch: ${url}`);
44
+ }
45
+ return wikiResponse();
46
+ });
47
+ vi.stubGlobal("fetch", fetchMock);
48
+ return fetchMock;
49
+ }
50
+
51
+ function binding(search: (question: string) => Promise<{ chunks: unknown[] }>): Env {
52
+ return { SEARCH: { search } } as unknown as Env;
53
+ }
54
+
55
+ afterEach(() => {
56
+ vi.unstubAllGlobals();
57
+ vi.restoreAllMocks();
58
+ });
59
+
60
+ describe("mapSearchChunks", () => {
61
+ it("maps a chunk to a github blob link", () => {
62
+ expect(mapSearchChunks([CHUNK], 5)).toEqual([{
63
+ title: "prism/README.md",
64
+ url: "https://github.com/skyphusion-labs/prism/blob/main/README.md",
65
+ snippet: "prism workers",
66
+ score: 0.42,
67
+ }]);
68
+ });
69
+
70
+ it("drops a chunk whose path is not a safe corpus path", () => {
71
+ expect(mapSearchChunks([{
72
+ text: "nope",
73
+ item: { key: "prism/../etc/passwd", metadata: { repo: "prism", path: "../etc/passwd" } },
74
+ }], 5)).toEqual([]);
75
+ });
76
+ });
77
+
78
+ describe("searchWeb sources", () => {
79
+ it("binding returns hits", async () => {
80
+ const wiki = installWikipediaFetch();
81
+ const search = vi.fn(async (_question: string) => ({ chunks: [CHUNK] }));
82
+ const out = await searchWeb(binding(search), "prism workers");
83
+ expect(search).toHaveBeenCalledTimes(1);
84
+ expect(search.mock.calls[0]).toEqual(["prism workers"]);
85
+ expect(out.error).toBeNull();
86
+ expect(out.sources.web).toEqual({ status: "ok", count: 1 });
87
+ expect(out.sources.wikipedia.status).toBe("ok");
88
+ expect(out.sources.wikipedia.count).toBe(1);
89
+ expect(out.results.map((r) => r.source)).toEqual(["skyphusion-search", "wikipedia"]);
90
+ expect(out.results[0]).toMatchObject({
91
+ title: "prism/README.md",
92
+ url: "https://github.com/skyphusion-labs/prism/blob/main/README.md",
93
+ snippet: "prism workers",
94
+ });
95
+ expect(out.results[1]).toMatchObject({
96
+ title: "Ada Lovelace",
97
+ url: "https://en.wikipedia.org/?curid=42",
98
+ });
99
+ expect(wiki).toHaveBeenCalled();
100
+ });
101
+
102
+ it.each(RPC_ERRORS)("%s: web source failed, Wikipedia still answers", async (code) => {
103
+ const wiki = installWikipediaFetch();
104
+ const search = vi.fn(async () => {
105
+ throw new Error(code);
106
+ });
107
+ const out = await searchWeb(binding(search), "prism workers");
108
+ expect(search).toHaveBeenCalledTimes(1);
109
+ expect(out.sources.web).toEqual({ status: "failed", count: 0, error: code });
110
+ expect(out.error).toBe(code);
111
+ expect(out.sources.wikipedia).toEqual({ status: "ok", count: 1 });
112
+ expect(out.results.map((r) => r.source)).toEqual(["wikipedia"]);
113
+ expect(wiki).toHaveBeenCalled();
114
+ });
115
+
116
+ it("a thrown binding is failed and does not clear Wikipedia", async () => {
117
+ installWikipediaFetch();
118
+ const env = binding(async () => {
119
+ throw new Error("binding down");
120
+ });
121
+ const out = await searchWeb(env, "prism workers");
122
+ expect(out.sources.web).toEqual({ status: "failed", count: 0, error: "binding down" });
123
+ expect(out.results.map((r) => r.source)).toEqual(["wikipedia"]);
124
+ });
125
+
126
+ it("binding absent is not a failure and not zero hits", async () => {
127
+ const wiki = installWikipediaFetch();
128
+ const out = await searchWeb({} as Env, "prism workers");
129
+ expect(out.sources.web).toEqual({ status: "absent", count: 0 });
130
+ expect(out.error).toBeNull();
131
+ expect(out.sources.wikipedia).toEqual({ status: "ok", count: 1 });
132
+ expect(out.results.map((r) => r.source)).toEqual(["wikipedia"]);
133
+ expect(wiki).toHaveBeenCalled();
134
+ });
135
+
136
+ it("an empty chunks array is zero hits, not a failure", async () => {
137
+ installWikipediaFetch();
138
+ const env = binding(async () => ({ chunks: [] }));
139
+ const out = await searchWeb(env, "prism workers");
140
+ expect(out.sources.web).toEqual({ status: "ok", count: 0 });
141
+ expect(out.error).toBeNull();
142
+ expect(out.results.map((r) => r.source)).toEqual(["wikipedia"]);
143
+ });
144
+ });
@@ -54,6 +54,18 @@ bucket_name = "skyphusion-llm"
54
54
  binding = "VEC"
55
55
  index_name = "skyphusion-llm-vec"
56
56
 
57
+ # Opt-in web search. Service binding to the skyphusion-search Worker,
58
+ # named entrypoint SearchEntrypoint, method search(question). Source
59
+ # repo skyphusion-labs/search-mcp. This is not POST /ask: that route
60
+ # checks Origin and Turnstile. Self-hosters who do not run that worker
61
+ # delete this block: wrangler deploy fails when the named service does
62
+ # not exist. With the binding absent, that source reports status
63
+ # "absent" and Wikipedia still runs.
64
+ [[services]]
65
+ binding = "SEARCH"
66
+ service = "skyphusion-search"
67
+ entrypoint = "SearchEntrypoint"
68
+
57
69
  # Static frontend (HTML, CSS, JS).
58
70
  [assets]
59
71
  directory = "./public"
@@ -195,12 +207,5 @@ enabled = true
195
207
  # CF_AIG_TOKEN (required for Anthropic, xAI, OpenAI chat, Google, and proxied
196
208
  # image/video/music on Unified Billing when using worker-level
197
209
  # credentials; optional in public demo mode where users supply
198
- # their own token via /api/prefs; v0.93.0+),
199
- # SEARXNG_URL (optional, v0.166.0; base URL of a self-hosted SearXNG instance
200
- # for the opt-in web-search source, e.g. https://search.skyphusion.org.
201
- # May be a plain [vars] entry instead of a secret. Skipped when
202
- # unset; Wikipedia still runs keyless),
203
- # SEARXNG_ACCESS_CLIENT_ID / SEARXNG_ACCESS_CLIENT_SECRET (optional, v0.166.0;
204
- # Cloudflare Access service-token halves for a gated SearXNG
205
- # instance. Sent as CF-Access-Client-Id / CF-Access-Client-Secret
206
- # only when BOTH are set; leave unset for an un-gated instance).
210
+ # their own token via /api/prefs; v0.93.0+).
211
+ # Web search uses the SEARCH service binding above. It does not take a secret.
@@ -1,75 +0,0 @@
1
- // SearXNG web retrieval (v0.166.0).
2
- //
3
- // Self-hosted metasearch source, slotted in beside the keyless Wikipedia
4
- // retriever (replacing the retired Tavily + Brave SaaS sources, prism#93).
5
- // Requests the JSON API: GET {SEARXNG_URL}/search?q=...&format=json.
6
- //
7
- // When the instance is gated by Cloudflare Access (our deploy at
8
- // search.skyphusion.org is), a per-function Access service token is sent as
9
- // the standard CF-Access-Client-Id / CF-Access-Client-Secret headers. A
10
- // self-hoster running an un-gated instance sets neither, and no Access headers
11
- // are sent.
12
-
13
- export interface SearxngHit {
14
- title: string;
15
- url: string;
16
- snippet: string;
17
- }
18
-
19
- // Pure parser for the SearXNG JSON response. The relevant shape is
20
- // { results: [ { url, title, content }, ... ] }; other top-level keys
21
- // (query, number_of_results, suggestions, ...) are ignored. Rows missing a
22
- // url or title are dropped; content is the snippet (may be absent).
23
- export function mapSearxngResults(data: unknown, maxResults: number): SearxngHit[] {
24
- const root = data as {
25
- results?: Array<{ title?: string; url?: string; content?: string }>;
26
- };
27
- const items = root.results ?? [];
28
- return items
29
- .filter((r) => r.url && r.title)
30
- .slice(0, maxResults)
31
- .map((r) => ({
32
- title: r.title!,
33
- url: r.url!,
34
- snippet: normalizeSearxngSnippet(r.content ?? ""),
35
- }));
36
- }
37
-
38
- function normalizeSearxngSnippet(text: string): string {
39
- return text.replace(/\s+/g, " ").trim();
40
- }
41
-
42
- export async function searchSearxngWeb(
43
- baseUrl: string,
44
- query: string,
45
- opts: {
46
- maxResults: number;
47
- timeoutMs: number;
48
- accessClientId?: string;
49
- accessClientSecret?: string;
50
- },
51
- ): Promise<SearxngHit[]> {
52
- // baseUrl may or may not carry a trailing slash; URL() with an absolute
53
- // "/search" path normalizes either way.
54
- const url = new URL("/search", baseUrl);
55
- url.searchParams.set("q", query);
56
- url.searchParams.set("format", "json");
57
-
58
- const headers: Record<string, string> = { Accept: "application/json" };
59
- // Access service-token headers are sent ONLY when both halves are set, so an
60
- // un-gated self-hosted instance is reached with no headers.
61
- if (opts.accessClientId && opts.accessClientSecret) {
62
- headers["CF-Access-Client-Id"] = opts.accessClientId;
63
- headers["CF-Access-Client-Secret"] = opts.accessClientSecret;
64
- }
65
-
66
- const resp = await fetch(url.toString(), {
67
- headers,
68
- signal: AbortSignal.timeout(opts.timeoutMs),
69
- });
70
- if (!resp.ok) {
71
- throw new Error(`SearXNG ${resp.status}: ${(await resp.text()).slice(0, 200)}`);
72
- }
73
- const data: unknown = await resp.json();
74
- return mapSearxngResults(data, opts.maxResults);
75
- }
@@ -1,51 +0,0 @@
1
- import { describe, it, expect } from "vitest";
2
- import { mapSearxngResults } from "../src/searxng";
3
-
4
- describe("mapSearxngResults", () => {
5
- it("maps results into title/url/snippet hits", () => {
6
- const data = {
7
- query: "cloudflare workers",
8
- number_of_results: 2,
9
- results: [
10
- { title: "Example", url: "https://example.com/a", content: "First hit." },
11
- { title: "Other", url: "https://example.com/b", content: "Second hit." },
12
- ],
13
- };
14
- expect(mapSearxngResults(data, 5)).toEqual([
15
- { title: "Example", url: "https://example.com/a", snippet: "First hit." },
16
- { title: "Other", url: "https://example.com/b", snippet: "Second hit." },
17
- ]);
18
- });
19
-
20
- it("drops rows missing title or url and respects maxResults", () => {
21
- const data = {
22
- results: [
23
- { title: "Keep", url: "https://example.com/keep", content: "ok" },
24
- { title: "No URL", content: "skip" },
25
- { url: "https://example.com/no-title", content: "skip" },
26
- { title: "Third", url: "https://example.com/third", content: "ok" },
27
- ],
28
- };
29
- expect(mapSearxngResults(data, 1)).toEqual([
30
- { title: "Keep", url: "https://example.com/keep", snippet: "ok" },
31
- ]);
32
- });
33
-
34
- it("collapses whitespace in snippets and tolerates a missing content field", () => {
35
- const data = {
36
- results: [
37
- { title: "Spacey", url: "https://example.com/s", content: " multi line\n\ttext " },
38
- { title: "NoContent", url: "https://example.com/n" },
39
- ],
40
- };
41
- expect(mapSearxngResults(data, 5)).toEqual([
42
- { title: "Spacey", url: "https://example.com/s", snippet: "multi line text" },
43
- { title: "NoContent", url: "https://example.com/n", snippet: "" },
44
- ]);
45
- });
46
-
47
- it("returns an empty array when results is missing", () => {
48
- expect(mapSearxngResults({}, 5)).toEqual([]);
49
- expect(mapSearxngResults({ results: [] }, 5)).toEqual([]);
50
- });
51
- });