@skyphusion/create-prism 1.0.4 → 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.
Files changed (45) hide show
  1. package/README.md +10 -8
  2. package/index.js +3 -2
  3. package/package.json +1 -1
  4. package/template/CONTRIBUTING.md +18 -3
  5. package/template/MIGRATIONS.md +52 -0
  6. package/template/README.md +79 -52
  7. package/template/docs/legal/INSTANCE-ACCEPTABLE-USE.md +5 -2
  8. package/template/docs/legal/INSTANCE-PRIVACY.md +128 -27
  9. package/template/migrations/0005_auth_attempts_retention.sql +23 -0
  10. package/template/package.json +6 -6
  11. package/template/public/app.js +21 -8
  12. package/template/public/index.html +23 -9
  13. package/template/public/styles.css +45 -7
  14. package/template/public/url-safety.js +6 -6
  15. package/template/schema.sql +6 -0
  16. package/template/src/ai-binding.ts +125 -3
  17. package/template/src/auth.ts +6 -0
  18. package/template/src/env.ts +38 -10
  19. package/template/src/gateway-credentials.ts +118 -22
  20. package/template/src/index.ts +2 -0
  21. package/template/src/providers/anthropic.ts +4 -4
  22. package/template/src/providers/openai-image.ts +10 -0
  23. package/template/src/providers/xai.ts +4 -4
  24. package/template/src/rate-limit.ts +26 -0
  25. package/template/src/routes/chat.ts +18 -9
  26. package/template/src/routes/prefs.ts +46 -5
  27. package/template/src/routes/rag.ts +135 -61
  28. package/template/src/routes/shared.ts +27 -11
  29. package/template/src/routes/workflow.ts +2 -5
  30. package/template/src/skyphusion-search.ts +108 -0
  31. package/template/src/user-prefs.ts +16 -3
  32. package/template/src/version.ts +1 -1
  33. package/template/tests/ai-binding-rest.test.ts +154 -0
  34. package/template/tests/csp.test.ts +11 -6
  35. package/template/tests/gateway-credentials.test.ts +101 -3
  36. package/template/tests/openai-image.test.ts +21 -1
  37. package/template/tests/rag-metadata-filter.test.ts +135 -0
  38. package/template/tests/skip-link.test.ts +164 -0
  39. package/template/tests/skyphusion-search.test.ts +144 -0
  40. package/template/tests/vectorize-backfill-metadata.test.ts +166 -0
  41. package/template/tests-integration/auth.test.ts +346 -2
  42. package/template/tests-integration/pdf-extract.test.ts +71 -0
  43. package/template/wrangler.example.toml +26 -11
  44. package/template/src/searxng.ts +0 -75
  45. package/template/tests/searxng.test.ts +0 -51
@@ -1,11 +1,16 @@
1
1
  // Per-user AI Gateway preference routes (GET/PATCH /api/prefs). Stores the
2
- // user gateway slug + Unified Billing token in D1 user_prefs; the token is
3
- // never echoed back raw (maskSecret). Optional control_plane_key (pcp_) for
2
+ // user's Cloudflare account id (v1.1.0), gateway slug, and Unified Billing
3
+ // token in D1 user_prefs; the token is never echoed back raw (maskSecret). Optional control_plane_key (pcp_) for
4
4
  // metered chat via allowlisted play-proxy (URL is never user-set).
5
5
 
6
6
  import type { Env } from "../env";
7
7
  import { loadUserPrefs, saveUserPrefs, type UserPrefsJson } from "../user-prefs";
8
- import { loadGatewayStatus, maskSecret } from "../gateway-credentials";
8
+ import {
9
+ isValidGatewayId,
10
+ loadGatewayStatus,
11
+ maskSecret,
12
+ normalizeAccountId,
13
+ } from "../gateway-credentials";
9
14
  import {
10
15
  DEFAULT_CONTROL_PLANE_URL,
11
16
  looksLikeClientKey,
@@ -29,6 +34,8 @@ export async function handlePrefsGet(request: Request, env: Env): Promise<Respon
29
34
  const prefs = await loadUserPrefs(env.DB, userEmail);
30
35
  const status = await loadGatewayStatus(env, userEmail);
31
36
  return json({
37
+ account_id: status.account_id,
38
+ account_id_required: status.account_id_required,
32
39
  gateway_id: status.gateway_id,
33
40
  cf_aig_token_set: status.cf_aig_token_set,
34
41
  cf_aig_token_preview: maskSecret(prefs?.cf_aig_token),
@@ -41,6 +48,7 @@ export async function handlePrefsGet(request: Request, env: Env): Promise<Respon
41
48
  export async function handlePrefsPatch(request: Request, env: Env): Promise<Response> {
42
49
  const userEmail = await getUserEmail(request, env);
43
50
  let body: {
51
+ account_id?: string;
44
52
  gateway_id?: string;
45
53
  cf_aig_token?: string;
46
54
  clear_cf_aig_token?: boolean;
@@ -54,7 +62,38 @@ export async function handlePrefsPatch(request: Request, env: Env): Promise<Resp
54
62
  }
55
63
 
56
64
  const patch: UserPrefsJson = {};
57
- if (body.gateway_id !== undefined) patch.gateway_id = body.gateway_id;
65
+ if (body.account_id !== undefined) {
66
+ if (typeof body.account_id !== "string") {
67
+ return json({ error: "account_id must be a string", code: "invalid_account_id" }, { status: 400 });
68
+ }
69
+ // Empty clears it; anything else must be a real account id, since it
70
+ // becomes a path segment in every request we send on the user's behalf.
71
+ if (body.account_id.trim() && !normalizeAccountId(body.account_id)) {
72
+ return json(
73
+ {
74
+ error: "account_id must be your 32-character Cloudflare account ID (hex), from the Cloudflare dashboard.",
75
+ code: "invalid_account_id",
76
+ },
77
+ { status: 400 },
78
+ );
79
+ }
80
+ patch.account_id = body.account_id;
81
+ }
82
+ if (body.gateway_id !== undefined) {
83
+ if (typeof body.gateway_id !== "string") {
84
+ return json({ error: "gateway_id must be a string", code: "invalid_gateway_id" }, { status: 400 });
85
+ }
86
+ if (body.gateway_id.trim() && !isValidGatewayId(body.gateway_id)) {
87
+ return json(
88
+ {
89
+ error: "gateway_id must be your AI Gateway slug: letters, digits, '-' or '_', up to 64 characters.",
90
+ code: "invalid_gateway_id",
91
+ },
92
+ { status: 400 },
93
+ );
94
+ }
95
+ patch.gateway_id = body.gateway_id;
96
+ }
58
97
  if (body.cf_aig_token !== undefined) patch.cf_aig_token = body.cf_aig_token;
59
98
  if (body.clear_cf_aig_token) patch.cf_aig_token = "";
60
99
  if (body.control_plane_key !== undefined) {
@@ -76,7 +115,7 @@ export async function handlePrefsPatch(request: Request, env: Env): Promise<Resp
76
115
  if (Object.keys(patch).length === 0) {
77
116
  return json(
78
117
  {
79
- error: "Provide gateway_id, cf_aig_token, and/or control_plane_key to update",
118
+ error: "Provide account_id, gateway_id, cf_aig_token, and/or control_plane_key to update",
80
119
  },
81
120
  { status: 400 },
82
121
  );
@@ -85,6 +124,8 @@ export async function handlePrefsPatch(request: Request, env: Env): Promise<Resp
85
124
  const merged = await saveUserPrefs(env.DB, userEmail, patch);
86
125
  const status = await loadGatewayStatus(env, userEmail);
87
126
  return json({
127
+ account_id: status.account_id,
128
+ account_id_required: status.account_id_required,
88
129
  gateway_id: status.gateway_id,
89
130
  cf_aig_token_set: status.cf_aig_token_set,
90
131
  cf_aig_token_preview: maskSecret(merged.cf_aig_token),
@@ -9,9 +9,9 @@ import { getDocumentProxy } from "unpdf";
9
9
  import * as XLSX from "xlsx";
10
10
  import type { Env } from "../env";
11
11
  import { aiRun, type AiContext } from "../ai-binding";
12
- import { loadGatewayCredentials, GATEWAY_NOT_CONFIGURED_MSG } from "../gateway-credentials";
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
 
@@ -221,10 +220,7 @@ export async function extractChunks(bytes: Uint8Array, mime: string, filename: s
221
220
 
222
221
  export async function embedBatch(env: Env, userEmail: string, texts: string[]): Promise<number[][]> {
223
222
  if (texts.length === 0) return [];
224
- const gateway = await loadGatewayCredentials(env, userEmail);
225
- if (!gateway?.gatewayId) {
226
- throw new Error(GATEWAY_NOT_CONFIGURED_MSG);
227
- }
223
+ const gateway = await requireGatewayCredentials(env, userEmail);
228
224
  const aiCtx: AiContext = { env, gateway };
229
225
  const result = await aiRun(aiCtx, EMBED_MODEL, { text: texts }) as {
230
226
  shape?: [number, number];
@@ -239,13 +235,26 @@ export async function embedBatch(env: Env, userEmail: string, texts: string[]):
239
235
  // ---------- RAG: retrieval (Pass 2) ----------
240
236
  //
241
237
  // Embeds the user prompt, queries Vectorize for the top-K nearest chunks,
242
- // then looks up source text in D1. We filter by user_email in the D1 JOIN
243
- // (not in the Vectorize filter param) so this works without a metadata
244
- // index on the Vectorize side - simpler for single-user deployments.
245
- // Vectorize score ordering is preserved.
238
+ // then looks up source text in D1. Tenant scope is the user_email filter in
239
+ // the D1 JOIN, always. Vectorize score ordering is preserved.
240
+ //
241
+ // With VEC_METADATA_FILTER on (fleet-chezmoi#1636), the Vectorize query is
242
+ // ALSO filtered on user_email, so the top-K is drawn from the caller's own
243
+ // vectors. Without it the query is global, and a caller with a small share of
244
+ // a large index can get a top-K made entirely of other users' vectors, which
245
+ // the D1 join then drops: zero results even when their own documents match.
246
+ // The flag needs a user_email metadata index plus a re-upsert of existing
247
+ // vectors first (scripts/vectorize-backfill-metadata.mjs), so it defaults off
248
+ // and a deployment that has not done both keeps the global query.
246
249
 
247
250
  export const RETRIEVE_TOP_K = 5;
248
251
 
252
+ /** VEC_METADATA_FILTER is on only for an explicit "on" / "1" / "true" (fleet-chezmoi#1636). */
253
+ export function vecMetadataFilterOn(env: Pick<Env, "VEC_METADATA_FILTER">): boolean {
254
+ const v = (env.VEC_METADATA_FILTER ?? "").trim().toLowerCase();
255
+ return v === "on" || v === "1" || v === "true";
256
+ }
257
+
249
258
  export async function retrieveContext(
250
259
  env: Env,
251
260
  userEmail: string,
@@ -273,8 +282,9 @@ export async function retrieveContext(
273
282
  return { chunks: [], error: `embed failed: ${m}` };
274
283
  }
275
284
 
276
- // 2) Query Vectorize. No metadata filter - we scope by user in D1 below.
277
- // When projectId is set, we overfetch (3x topK) at the Vectorize stage
285
+ // 2) Query Vectorize. Filtered on user_email when VEC_METADATA_FILTER is on;
286
+ // global otherwise. Either way the D1 join below is the tenant scope and
287
+ // stays, as the second layer. When projectId is set, we overfetch (3x topK) at the Vectorize stage
278
288
  // and filter by project membership in D1, since Vectorize doesn't know
279
289
  // about project membership. Without overfetch, a small topK that all
280
290
  // misses the project would return zero results even when the project
@@ -282,7 +292,12 @@ export async function retrieveContext(
282
292
  const vectorizeTopK = projectId !== undefined ? topK * 3 : topK;
283
293
  let matches: { id: string; score: number }[];
284
294
  try {
285
- const q = await env.VEC.query(queryVec, { topK: vectorizeTopK });
295
+ const q = await env.VEC.query(
296
+ queryVec,
297
+ vecMetadataFilterOn(env)
298
+ ? { topK: vectorizeTopK, filter: { user_email: userEmail } }
299
+ : { topK: vectorizeTopK },
300
+ );
286
301
  matches = (q?.matches ?? []).map((m) => ({ id: m.id, score: m.score }));
287
302
  } catch (err) {
288
303
  const m = err instanceof Error ? err.message : String(err);
@@ -414,58 +429,117 @@ export function formatRetrievalForSystemPrompt(chunks: RetrievedChunk[]): string
414
429
 
415
430
  // ---------- Web search (v0.17.0) ----------
416
431
  //
417
- // Optional retrieval source: SearXNG (self-hosted metasearch) for general web,
418
- // Wikipedia for lore / reference. Both run in parallel; failure of one doesn't
419
- // kill the other. Per-source timeouts (WEB_SEARCH_TIMEOUT_MS) prevent a slow
420
- // 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.
421
436
  //
422
- // SearXNG requires SEARXNG_URL; when unset, that source is silently skipped.
423
- // Wikipedia needs no config. (v0.166.0: SearXNG replaced the retired Tavily +
424
- // 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.
425
446
  //
426
447
  // Results are persisted to the existing retrieved_context column alongside
427
448
  // RAG chunks, with source_type discriminator. The frontend renders branches
428
449
  // on source_type to show the source URL for web results.
429
450
 
430
- export async function searchWeb(
431
- env: Env,
432
- query: string
433
- ): Promise<{ results: RetrievedWebResult[]; error: string | null }> {
434
- const q = query.trim();
435
- if (!q) return { results: [], error: null };
436
-
437
- // Each upstream is wrapped in its own timeout + catch so a single failure
438
- // doesn't abort the other. Partial results are better than nothing.
439
- const searxngPromise: Promise<RetrievedWebResult[]> = env.SEARXNG_URL
440
- ? searchSearxng(env, q).catch(() => [])
441
- : Promise.resolve([]);
442
- const wikipediaPromise: Promise<RetrievedWebResult[]> = searchWikipedia(q).catch(() => []);
443
-
444
- const [searxng, wikipedia] = await Promise.all([searxngPromise, wikipediaPromise]);
445
- const results = [...searxng, ...wikipedia];
446
-
447
- // Empty results is fine; it just means the query didn't match anything in
448
- // any source. Real per-source failures are swallowed by the .catch above
449
- // so the other source can still return its hits.
450
- 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;
451
457
  }
452
458
 
453
- export async function searchSearxng(env: Env, query: string): Promise<RetrievedWebResult[]> {
454
- // Access service-token headers are sent only when both halves are set, so an
455
- // un-gated self-hosted instance is reached with no headers.
456
- const hits = await searchSearxngWeb(env.SEARXNG_URL!, query, {
457
- maxResults: SEARXNG_MAX_RESULTS,
458
- timeoutMs: WEB_SEARCH_TIMEOUT_MS,
459
- accessClientId: env.SEARXNG_ACCESS_CLIENT_ID,
460
- accessClientSecret: env.SEARXNG_ACCESS_CLIENT_SECRET,
461
- });
462
- return hits.map((r): RetrievedWebResult => ({
463
- source_type: "web",
464
- source: "searxng",
465
- url: r.url,
466
- title: r.title,
467
- snippet: r.snippet,
468
- }));
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
+ };
469
543
  }
470
544
 
471
545
  export async function searchWikipedia(query: string): Promise<RetrievedWebResult[]> {
@@ -536,7 +610,7 @@ export function stripWikipediaSnippet(html: string): string {
536
610
 
537
611
  export function webSourceSystemLabel(source: RetrievedWebResult["source"]): string {
538
612
  switch (source) {
539
- case "searxng": return "Web";
613
+ case "skyphusion-search": return "Web";
540
614
  case "wikipedia": return "Wikipedia";
541
615
  }
542
616
  }
@@ -11,15 +11,15 @@ import type { InputAttachment } from "../types";
11
11
  import { extFromMime, bytesToBase64 } from "../utils";
12
12
  import { type AiContext } from "../ai-binding";
13
13
  import {
14
- loadGatewayCredentials,
15
- GATEWAY_NOT_CONFIGURED_MSG,
14
+ resolveGateway,
15
+ gatewayProblemMessage,
16
16
  CF_AIG_TOKEN_REQUIRED_MSG,
17
17
  } from "../gateway-credentials";
18
18
  import {
19
19
  resolveControlPlane,
20
20
  type ControlPlaneCredentials,
21
21
  } from "../control-plane";
22
- import { loadUserPrefs } from "../user-prefs";
22
+ import { loadUserPrefs, type UserPrefsJson } from "../user-prefs";
23
23
  import { resolveIdentity } from "../auth";
24
24
 
25
25
  // ---------- Types ----------
@@ -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
@@ -139,14 +142,27 @@ export async function requireAiContext(
139
142
  userEmail: string,
140
143
  opts?: { requireCfToken?: boolean },
141
144
  ): Promise<AiContext | Response> {
142
- const gateway = await loadGatewayCredentials(env, userEmail);
143
- if (!gateway?.gatewayId) {
144
- return json({ error: GATEWAY_NOT_CONFIGURED_MSG, code: "gateway_not_configured" }, { status: 412 });
145
+ const prefs = await loadUserPrefs(env.DB, userEmail);
146
+ return aiContextFromPrefs(prefs, env, opts);
147
+ }
148
+
149
+ // v1.1.0: every refusal carries its own code so the SPA can say what is
150
+ // missing. gateway_account_id_required is the pre-v1.1.0 shape (slug + token,
151
+ // no account id) in public mode: refused, never resolved on our binding.
152
+ export function aiContextFromPrefs(
153
+ prefs: UserPrefsJson | null,
154
+ env: Env,
155
+ opts?: { requireCfToken?: boolean },
156
+ ): AiContext | Response {
157
+ const { creds, problem } = resolveGateway(prefs, env);
158
+ if (!creds) {
159
+ const code = problem ?? "gateway_not_configured";
160
+ return json({ error: gatewayProblemMessage(code), code }, { status: 412 });
145
161
  }
146
- if (opts?.requireCfToken && !gateway.cfAigToken) {
162
+ if (opts?.requireCfToken && !creds.cfAigToken) {
147
163
  return json({ error: CF_AIG_TOKEN_REQUIRED_MSG, code: "cf_aig_token_required" }, { status: 412 });
148
164
  }
149
- return { env, gateway };
165
+ return { env, gateway: creds };
150
166
  }
151
167
 
152
168
  /**
@@ -168,7 +184,7 @@ export async function requireInferenceBackend(
168
184
  const cp = resolveControlPlane(prefs, env);
169
185
  if (cp) return { kind: "control_plane", cp };
170
186
 
171
- const gatewayOrErr = await requireAiContext(env, userEmail, opts);
187
+ const gatewayOrErr = aiContextFromPrefs(prefs, env, opts);
172
188
  if (gatewayOrErr instanceof Response) return gatewayOrErr;
173
189
  return { kind: "gateway", ctx: gatewayOrErr };
174
190
  }
@@ -9,7 +9,7 @@ import { WorkflowEntrypoint, WorkflowStep } from "cloudflare:workers";
9
9
  import type { WorkflowEvent } from "cloudflare:workers";
10
10
  import type { Env } from "../env";
11
11
  import { aiRun, type AiContext } from "../ai-binding";
12
- import { loadGatewayCredentials, GATEWAY_NOT_CONFIGURED_MSG } from "../gateway-credentials";
12
+ import { requireGatewayCredentials } from "../gateway-credentials";
13
13
  import { buildGenParams } from "../longrun-params";
14
14
  import { unzip } from "../zip";
15
15
  import { r2Put, r2KeyToDataUri, r2DeleteSafe } from "./shared";
@@ -231,10 +231,7 @@ export class LongRunWorkflow extends WorkflowEntrypoint<Env, LongRunParams> {
231
231
  : imageUrl;
232
232
  const params = buildGenParams(kind, { modelId, prompt, lyrics, imageUrl: resolvedImage });
233
233
 
234
- const gateway = await loadGatewayCredentials(this.env, userEmail);
235
- if (!gateway?.gatewayId) {
236
- throw new Error(GATEWAY_NOT_CONFIGURED_MSG);
237
- }
234
+ const gateway = await requireGatewayCredentials(this.env, userEmail);
238
235
  const aiCtx: AiContext = { env: this.env, gateway };
239
236
  const result = await aiRun(aiCtx, modelId, params) as LongRunResult;
240
237
 
@@ -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
+ }
@@ -1,10 +1,16 @@
1
1
  // Per-user preferences stored in D1 (v0.164.0).
2
2
  //
3
- // JSON blob keyed by Cloudflare Access email. Gateway fields are the first
4
- // use case for a public demo deployment where each visitor brings their own
5
- // AI Gateway slug and CF_AIG_TOKEN.
3
+ // JSON blob keyed by the caller's identity (Access email or public account
4
+ // id). Gateway fields are the first use case for a public demo deployment
5
+ // where each visitor brings their own AI Gateway.
6
+ //
7
+ // v1.1.0: account_id added. Being a key in the JSON blob, it needs no DDL;
8
+ // pre-v1.1.0 rows simply lack it and resolve as "account id required" in
9
+ // public mode (see resolveGateway in gateway-credentials.ts).
6
10
 
7
11
  export interface UserPrefsJson {
12
+ /** v1.1.0: Cloudflare account id (32 hex) that owns gateway_id. */
13
+ account_id?: string;
8
14
  gateway_id?: string;
9
15
  cf_aig_token?: string;
10
16
  /**
@@ -43,6 +49,13 @@ export async function saveUserPrefs(
43
49
  const existing = (await loadUserPrefs(db, userEmail)) ?? {};
44
50
  const merged: UserPrefsJson = { ...existing };
45
51
 
52
+ if (patch.account_id !== undefined) {
53
+ // Callers validate before saving; stored lowercase so comparisons and
54
+ // the URL builder see one canonical form.
55
+ const trimmed = patch.account_id.trim().toLowerCase();
56
+ if (trimmed) merged.account_id = trimmed;
57
+ else delete merged.account_id;
58
+ }
46
59
  if (patch.gateway_id !== undefined) {
47
60
  const trimmed = patch.gateway_id.trim();
48
61
  if (trimmed) merged.gateway_id = trimmed;
@@ -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.0.4";
18
+ export const VERSION = "1.3.0";