@benchme/site-kit 0.4.2 → 0.5.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/dist/html.d.ts +6 -0
- package/dist/html.js +3 -3
- package/dist/html.js.map +1 -1
- package/dist/index.d.ts +4 -0
- package/dist/index.js +4 -0
- package/dist/index.js.map +1 -1
- package/dist/jsonld.d.ts +91 -0
- package/dist/jsonld.js +98 -0
- package/dist/jsonld.js.map +1 -0
- package/dist/mcp-server.d.ts +4 -2
- package/dist/mcp-server.js +2 -1
- package/dist/mcp-server.js.map +1 -1
- package/dist/nlweb/ask-params.d.ts +25 -0
- package/dist/nlweb/ask-params.js +65 -0
- package/dist/nlweb/ask-params.js.map +1 -0
- package/dist/nlweb/ask-routes.d.ts +11 -0
- package/dist/nlweb/ask-routes.js +56 -0
- package/dist/nlweb/ask-routes.js.map +1 -0
- package/dist/nlweb/ask-service.d.ts +24 -0
- package/dist/nlweb/ask-service.js +57 -0
- package/dist/nlweb/ask-service.js.map +1 -0
- package/dist/nlweb/ask-sse.d.ts +10 -0
- package/dist/nlweb/ask-sse.js +42 -0
- package/dist/nlweb/ask-sse.js.map +1 -0
- package/dist/nlweb/eval-metrics.d.ts +37 -0
- package/dist/nlweb/eval-metrics.js +71 -0
- package/dist/nlweb/eval-metrics.js.map +1 -0
- package/dist/nlweb/index.d.ts +15 -0
- package/dist/nlweb/index.js +16 -0
- package/dist/nlweb/index.js.map +1 -0
- package/dist/nlweb/jev-ranker.d.ts +18 -0
- package/dist/nlweb/jev-ranker.js +54 -0
- package/dist/nlweb/jev-ranker.js.map +1 -0
- package/dist/nlweb/lexical.d.ts +28 -0
- package/dist/nlweb/lexical.js +69 -0
- package/dist/nlweb/lexical.js.map +1 -0
- package/dist/nlweb/llm-ranker.d.ts +37 -0
- package/dist/nlweb/llm-ranker.js +98 -0
- package/dist/nlweb/llm-ranker.js.map +1 -0
- package/dist/nlweb/p-limit.d.ts +8 -0
- package/dist/nlweb/p-limit.js +27 -0
- package/dist/nlweb/p-limit.js.map +1 -0
- package/dist/nlweb/ranker-config.d.ts +62 -0
- package/dist/nlweb/ranker-config.js +71 -0
- package/dist/nlweb/ranker-config.js.map +1 -0
- package/dist/nlweb/remote-ranker.d.ts +72 -0
- package/dist/nlweb/remote-ranker.js +92 -0
- package/dist/nlweb/remote-ranker.js.map +1 -0
- package/dist/nlweb/request-url.d.ts +16 -0
- package/dist/nlweb/request-url.js +25 -0
- package/dist/nlweb/request-url.js.map +1 -0
- package/dist/nlweb/schema-routes.d.ts +11 -0
- package/dist/nlweb/schema-routes.js +32 -0
- package/dist/nlweb/schema-routes.js.map +1 -0
- package/dist/nlweb/types.d.ts +121 -0
- package/dist/nlweb/types.js +28 -0
- package/dist/nlweb/types.js.map +1 -0
- package/dist/nlweb/word-variants.d.ts +10 -0
- package/dist/nlweb/word-variants.js +14 -0
- package/dist/nlweb/word-variants.js.map +1 -0
- package/dist/tool-schema.d.ts +14 -0
- package/dist/tool-schema.js +15 -0
- package/dist/tool-schema.js.map +1 -0
- package/dist/webmcp.d.ts +20 -0
- package/dist/webmcp.js +31 -0
- package/dist/webmcp.js.map +1 -0
- package/package.json +4 -3
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { loadConfig } from "@benchme/core";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
import { JevRanker } from "./jev-ranker.js";
|
|
4
|
+
import { LexicalRanker } from "./lexical.js";
|
|
5
|
+
import { LlmRanker } from "./llm-ranker.js";
|
|
6
|
+
import { RankerRegistry } from "./types.js";
|
|
7
|
+
/**
|
|
8
|
+
* Which ranker a deployment runs, and the credentials it needs. Selection is
|
|
9
|
+
* env-driven so the SAME site image serves a lexical, an llm and a jev arm of
|
|
10
|
+
* the grid — the only difference between the arms is this config.
|
|
11
|
+
*
|
|
12
|
+
* A missing key is a BOOT failure, never a quiet fall back to lexical: an arm
|
|
13
|
+
* that silently answers lexically would be recorded as an llm/jev measurement
|
|
14
|
+
* and poison every comparison made from it.
|
|
15
|
+
*/
|
|
16
|
+
export const rankerEnvSchema = z.object({
|
|
17
|
+
ASK_RANKER: z.enum(["lexical", "llm", "jev"]).default("lexical"),
|
|
18
|
+
/** Any Anthropic-Messages-compatible endpoint: the vendor API, a gateway, a mock. */
|
|
19
|
+
LLM_BASE_URL: z.string().url().optional(),
|
|
20
|
+
LLM_API_KEY: z.string().min(1).optional(),
|
|
21
|
+
LLM_MODEL: z.string().min(1).default("claude-haiku-4-5-20251001"),
|
|
22
|
+
/** Priced per run rather than hardcoded, so a model swap does not silently misreport cost. */
|
|
23
|
+
LLM_INPUT_USD_PER_MTOK: z.coerce.number().nonnegative().default(1.0),
|
|
24
|
+
LLM_OUTPUT_USD_PER_MTOK: z.coerce.number().nonnegative().default(5.0),
|
|
25
|
+
JEV_BASE_URL: z.string().url().default("https://api.typesafe.ai"),
|
|
26
|
+
JEV_API_KEY: z.string().min(1).optional(),
|
|
27
|
+
JEV_MODEL: z.string().min(1).default("jev-latest"),
|
|
28
|
+
/** Priced per run like the llm prices above; jev writes no tokens, so there is no output price. */
|
|
29
|
+
JEV_INPUT_USD_PER_MTOK: z.coerce.number().nonnegative().default(0.042),
|
|
30
|
+
/** In-flight upstream requests per /ask; one request is sent per candidate. */
|
|
31
|
+
RANKER_CONCURRENCY: z.coerce.number().int().positive().default(8),
|
|
32
|
+
});
|
|
33
|
+
/** Apps merge this into their own config schema, so one `readConfig` validates everything. */
|
|
34
|
+
export function readRankerEnv(env) {
|
|
35
|
+
return loadConfig(rankerEnvSchema, env);
|
|
36
|
+
}
|
|
37
|
+
/** Names only the keys that are ACTUALLY missing, so the operator sets the one thing that is wrong rather than re-checking both. */
|
|
38
|
+
function credentials(kind, baseUrl, apiKey) {
|
|
39
|
+
const prefix = kind.toUpperCase();
|
|
40
|
+
const missing = [...(baseUrl ? [] : [`${prefix}_BASE_URL`]), ...(apiKey ? [] : [`${prefix}_API_KEY`])];
|
|
41
|
+
if (missing.length > 0 || !baseUrl || !apiKey)
|
|
42
|
+
throw new Error(`invalid configuration: ASK_RANKER=${kind} requires ${missing.join(" and ")}`);
|
|
43
|
+
return { baseUrl, apiKey };
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* The three kinds that ship. A fourth ranker is a `register` call here (or on a
|
|
47
|
+
* registry a site owns) — never a branch in /ask or in this function.
|
|
48
|
+
*/
|
|
49
|
+
export function defaultRankerRegistry() {
|
|
50
|
+
return new RankerRegistry()
|
|
51
|
+
.register("lexical", () => new LexicalRanker())
|
|
52
|
+
.register("llm", (env) => {
|
|
53
|
+
const c = readRankerEnv(env);
|
|
54
|
+
return new LlmRanker({
|
|
55
|
+
...credentials("llm", c.LLM_BASE_URL, c.LLM_API_KEY),
|
|
56
|
+
model: c.LLM_MODEL,
|
|
57
|
+
concurrency: c.RANKER_CONCURRENCY,
|
|
58
|
+
inputUsdPerMTok: c.LLM_INPUT_USD_PER_MTOK,
|
|
59
|
+
outputUsdPerMTok: c.LLM_OUTPUT_USD_PER_MTOK,
|
|
60
|
+
});
|
|
61
|
+
})
|
|
62
|
+
.register("jev", (env) => {
|
|
63
|
+
const c = readRankerEnv(env);
|
|
64
|
+
return new JevRanker({ ...credentials("jev", c.JEV_BASE_URL, c.JEV_API_KEY), model: c.JEV_MODEL, concurrency: c.RANKER_CONCURRENCY, inputUsdPerMTok: c.JEV_INPUT_USD_PER_MTOK });
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
/** The ranker `ASK_RANKER` names; throws (failing boot) if it is unknown or unconfigured. */
|
|
68
|
+
export function buildRanker(env = process.env, registry = defaultRankerRegistry()) {
|
|
69
|
+
return registry.build(readRankerEnv(env).ASK_RANKER, env);
|
|
70
|
+
}
|
|
71
|
+
//# sourceMappingURL=ranker-config.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ranker-config.js","sourceRoot":"","sources":["../../src/nlweb/ranker-config.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UA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CAAC,GAAG,EAAE,EAAE;QACvB,MAAM,CAAC,GAAG,aAAa,CAAC,GAAG,CAAC,CAAC;QAC7B,OAAO,IAAI,SAAS,CAAC;YACnB,GAAG,WAAW,CAAC,KAAK,EAAE,CAAC,CAAC,YAAY,EAAE,CAAC,CAAC,WAAW,CAAC;YACpD,KAAK,EAAE,CAAC,CAAC,SAAS;YAClB,WAAW,EAAE,CAAC,CAAC,kBAAkB;YACjC,eAAe,EAAE,CAAC,CAAC,sBAAsB;YACzC,gBAAgB,EAAE,CAAC,CAAC,uBAAuB;SAC5C,CAAC,CAAC;IACL,CAAC,CAAC;SACD,QAAQ,CAAC,KAAK,EAAE,CAAC,GAAG,EAAE,EAAE;QACvB,MAAM,CAAC,GAAG,aAAa,CAAC,GAAG,CAAC,CAAC;QAC7B,OAAO,IAAI,SAAS,CAAC,EAAE,GAAG,WAAW,CAAC,KAAK,EAAE,CAAC,CAAC,YAAY,EAAE,CAAC,CAAC,WAAW,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC,SAAS,EAAE,WAAW,EAAE,CAAC,CAAC,kBAAkB,EAAE,eAAe,EAAE,CAAC,CAAC,sBAAsB,EAAE,CAAC,CAAC;IACnL,CAAC,CAAC,CAAC;AACP,CAAC;AAED,6FAA6F;AAC7F,MAAM,UAAU,WAAW,CAAC,MAAyB,OAAO,CAAC,GAAG,EAAE,WAA2B,qBAAqB,EAAE;IAClH,OAAO,QAAQ,CAAC,KAAK,CAAC,aAAa,CAAC,GAAG,CAAC,CAAC,UAAU,EAAE,GAAG,CAAC,CAAC;AAC5D,CAAC"}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import type { AskItem, RankedCandidate, Ranker, RankerUsage } from "./types.js";
|
|
2
|
+
/**
|
|
3
|
+
* The half every paid ranker shares: one bounded-concurrency request per
|
|
4
|
+
* candidate, retry on the two "come back later" statuses, and — the important
|
|
5
|
+
* part — PER-CANDIDATE degradation. A provider hiccup on one item must never
|
|
6
|
+
* fail the whole answer or, worse, silently drop that item from the results:
|
|
7
|
+
* it keeps its lexical score and the response is flagged `degraded` so a
|
|
8
|
+
* grader can tell a cheap answer from a paid one.
|
|
9
|
+
*
|
|
10
|
+
* Subclasses supply only the wire format (Template Method), so adding a
|
|
11
|
+
* provider is a new subclass plus a registry line — /ask never changes.
|
|
12
|
+
*/
|
|
13
|
+
export type FetchInit = NonNullable<Parameters<typeof fetch>[1]>;
|
|
14
|
+
export type RemoteRankerOptions = {
|
|
15
|
+
baseUrl: string;
|
|
16
|
+
apiKey: string;
|
|
17
|
+
model: string;
|
|
18
|
+
/** Injected so tests drive a local stub — and so a gateway can be slotted in. */
|
|
19
|
+
fetch?: typeof fetch;
|
|
20
|
+
concurrency?: number;
|
|
21
|
+
/** Called at most once per query; defaults to console.warn. */
|
|
22
|
+
log?: (msg: string) => void;
|
|
23
|
+
};
|
|
24
|
+
/** What the provider billed for one answered request. */
|
|
25
|
+
export type Tokens = {
|
|
26
|
+
inputTokens: number;
|
|
27
|
+
outputTokens: number;
|
|
28
|
+
};
|
|
29
|
+
/** What one upstream answer says about one candidate, before normalisation to the 0-1 result score. */
|
|
30
|
+
export type Verdict = {
|
|
31
|
+
score: number;
|
|
32
|
+
description?: string;
|
|
33
|
+
};
|
|
34
|
+
export declare abstract class RemoteRanker implements Ranker {
|
|
35
|
+
abstract readonly kind: string;
|
|
36
|
+
protected readonly baseUrl: string;
|
|
37
|
+
protected readonly apiKey: string;
|
|
38
|
+
protected readonly model: string;
|
|
39
|
+
private readonly fetchImpl;
|
|
40
|
+
private readonly concurrency;
|
|
41
|
+
private readonly log;
|
|
42
|
+
constructor(o: RemoteRankerOptions);
|
|
43
|
+
/** The request that scores ONE candidate. */
|
|
44
|
+
protected abstract request(query: string, item: AskItem): {
|
|
45
|
+
url: string;
|
|
46
|
+
init: FetchInit;
|
|
47
|
+
};
|
|
48
|
+
/**
|
|
49
|
+
* The BILLED half of a 200: what the provider charged for this answer.
|
|
50
|
+
* Deliberately separate from the verdict — a reply we cannot interpret was
|
|
51
|
+
* still paid for, and cost is this benchmark's headline number, so it is
|
|
52
|
+
* read (and metered) before anything can throw over the answer's content.
|
|
53
|
+
*/
|
|
54
|
+
protected abstract usageOf(body: unknown): Tokens;
|
|
55
|
+
/** The ANSWER half of a 200; throwing here degrades just this candidate, after it has been metered. */
|
|
56
|
+
protected abstract verdictOf(body: unknown): Verdict;
|
|
57
|
+
/** What those tokens cost in USD. */
|
|
58
|
+
protected abstract costUsd(t: Tokens): number;
|
|
59
|
+
rank(query: string, candidates: AskItem[]): Promise<{
|
|
60
|
+
ranked: RankedCandidate[];
|
|
61
|
+
usage: RankerUsage;
|
|
62
|
+
}>;
|
|
63
|
+
private scoreOne;
|
|
64
|
+
/** Issues the request (with retries) and returns the billed body, already metered. */
|
|
65
|
+
private call;
|
|
66
|
+
/**
|
|
67
|
+
* Adds an answered request's tokens and cost to the meter. An envelope so
|
|
68
|
+
* malformed that even the usage block is unreadable meters nothing — but it
|
|
69
|
+
* must not throw here, or a broken envelope would skip the degradation path.
|
|
70
|
+
*/
|
|
71
|
+
private meterBilled;
|
|
72
|
+
}
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import { pLimit } from "./p-limit.js";
|
|
2
|
+
/** 429 = rate limited, 529 = overloaded: both mean "the same request will work shortly". */
|
|
3
|
+
const RETRY_STATUS = new Set([429, 529]);
|
|
4
|
+
const BACKOFF_MS = [250, 1000];
|
|
5
|
+
const DEFAULT_CONCURRENCY = 8;
|
|
6
|
+
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
7
|
+
const clamp01 = (n) => (Number.isFinite(n) ? Math.min(1, Math.max(0, n)) : 0);
|
|
8
|
+
export class RemoteRanker {
|
|
9
|
+
baseUrl;
|
|
10
|
+
apiKey;
|
|
11
|
+
model;
|
|
12
|
+
fetchImpl;
|
|
13
|
+
concurrency;
|
|
14
|
+
log;
|
|
15
|
+
constructor(o) {
|
|
16
|
+
this.baseUrl = o.baseUrl.replace(/\/+$/, "");
|
|
17
|
+
this.apiKey = o.apiKey;
|
|
18
|
+
this.model = o.model;
|
|
19
|
+
this.fetchImpl = o.fetch ?? fetch;
|
|
20
|
+
this.concurrency = o.concurrency ?? DEFAULT_CONCURRENCY;
|
|
21
|
+
this.log = o.log ?? ((msg) => console.warn(msg));
|
|
22
|
+
}
|
|
23
|
+
async rank(query, candidates) {
|
|
24
|
+
const startedAt = Date.now();
|
|
25
|
+
const limit = pLimit(this.concurrency);
|
|
26
|
+
const meter = { calls: 0, inputTokens: 0, costUsd: 0 };
|
|
27
|
+
const failures = [];
|
|
28
|
+
const ranked = await Promise.all(candidates.map((item) => limit(() => this.scoreOne(query, item, meter, failures))));
|
|
29
|
+
// Once per query, not once per candidate: a broken key would otherwise emit
|
|
30
|
+
// a line per item and bury every other log on the site.
|
|
31
|
+
if (failures.length > 0) {
|
|
32
|
+
this.log(`${this.kind} ranker degraded: ${failures.length}/${candidates.length} candidates kept their lexical score (first error: ${failures[0]})`);
|
|
33
|
+
}
|
|
34
|
+
return {
|
|
35
|
+
ranked,
|
|
36
|
+
usage: { calls: meter.calls, inputTokens: meter.inputTokens, latencyMs: Date.now() - startedAt, costUsd: meter.costUsd, degraded: failures.length > 0 },
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
async scoreOne(query, item, meter, failures) {
|
|
40
|
+
try {
|
|
41
|
+
// `call` has already metered whatever the provider billed, so the only
|
|
42
|
+
// thing that can be lost below is this candidate's score — never its cost.
|
|
43
|
+
const verdict = this.verdictOf(await this.call(query, item, meter));
|
|
44
|
+
return { id: item.id, score: clamp01(verdict.score), ...(verdict.description ? { description: verdict.description } : {}) };
|
|
45
|
+
}
|
|
46
|
+
catch (e) {
|
|
47
|
+
failures.push(e instanceof Error ? e.message : String(e));
|
|
48
|
+
// The fallback score came from retrieval over the PREV-WIDENED query (earlier turns included), while a paid score judges the current question alone — so a degraded item is ranked on a slightly different question than its neighbours.
|
|
49
|
+
return { id: item.id, score: item.lexicalScore ?? 0 };
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
/** Issues the request (with retries) and returns the billed body, already metered. */
|
|
53
|
+
async call(query, item, meter) {
|
|
54
|
+
const { url, init } = this.request(query, item);
|
|
55
|
+
for (let attempt = 0;; attempt++) {
|
|
56
|
+
// Attempts, retries included: `calls` is what the provider's rate limit
|
|
57
|
+
// counts, so a query that retried its way to an answer still shows it.
|
|
58
|
+
meter.calls++;
|
|
59
|
+
// A network error throws straight out: retrying a refused connection just
|
|
60
|
+
// delays the degraded answer the caller is already waiting for.
|
|
61
|
+
const res = await this.fetchImpl(url, init);
|
|
62
|
+
if (res.ok) {
|
|
63
|
+
const body = await res.json();
|
|
64
|
+
this.meterBilled(body, meter);
|
|
65
|
+
return body;
|
|
66
|
+
}
|
|
67
|
+
const detail = await res.text().catch(() => "");
|
|
68
|
+
if (RETRY_STATUS.has(res.status) && attempt < BACKOFF_MS.length) {
|
|
69
|
+
await sleep(BACKOFF_MS[attempt]);
|
|
70
|
+
continue;
|
|
71
|
+
}
|
|
72
|
+
throw new Error(`${this.kind} ranker: ${res.status} ${detail.slice(0, 200)}`);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* Adds an answered request's tokens and cost to the meter. An envelope so
|
|
77
|
+
* malformed that even the usage block is unreadable meters nothing — but it
|
|
78
|
+
* must not throw here, or a broken envelope would skip the degradation path.
|
|
79
|
+
*/
|
|
80
|
+
meterBilled(body, meter) {
|
|
81
|
+
let tokens;
|
|
82
|
+
try {
|
|
83
|
+
tokens = this.usageOf(body);
|
|
84
|
+
}
|
|
85
|
+
catch {
|
|
86
|
+
return;
|
|
87
|
+
}
|
|
88
|
+
meter.inputTokens += tokens.inputTokens;
|
|
89
|
+
meter.costUsd += this.costUsd(tokens);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
//# sourceMappingURL=remote-ranker.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"rem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C,IAAI,GAAG,CAAC,EAAE,EAAE,CAAC;gBACX,MAAM,IAAI,GAAY,MAAM,GAAG,CAAC,IAAI,EAAE,CAAC;gBACvC,IAAI,CAAC,WAAW,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;gBAC9B,OAAO,IAAI,CAAC;YACd,CAAC;YACD,MAAM,MAAM,GAAG,MAAM,GAAG,CAAC,IAAI,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,EAAE,CAAC,CAAC;YAChD,IAAI,YAAY,CAAC,GAAG,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,OAAO,GAAG,UAAU,CAAC,MAAM,EAAE,CAAC;gBAChE,MAAM,KAAK,CAAC,UAAU,CAAC,OAAO,CAAW,CAAC,CAAC;gBAC3C,SAAS;YACX,CAAC;YACD,MAAM,IAAI,KAAK,CAAC,GAAG,IAAI,CAAC,IAAI,YAAY,GAAG,CAAC,MAAM,IAAI,MAAM,CAAC,KAAK,CAAC,CAAC,EAAE,GAAG,CAAC,EAAE,CAAC,CAAC;QAChF,CAAC;IACH,CAAC;IAED;;;;OAIG;IACK,WAAW,CAAC,IAAa,EAAE,KAAY;QAC7C,IAAI,MAAc,CAAC;QACnB,IAAI,CAAC;YACH,MAAM,GAAG,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;QAC9B,CAAC;QAAC,MAAM,CAAC;YACP,OAAO;QACT,CAAC;QACD,KAAK,CAAC,WAAW,IAAI,MAAM,CAAC,WAAW,CAAC;QACxC,KAAK,CAAC,OAAO,IAAI,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;IACxC,CAAC;CACF"}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { FastifyRequest } from "fastify";
|
|
2
|
+
/**
|
|
3
|
+
* The standard `SchemaDeps.publicBaseUrl`: the gateway's forwarded proto and
|
|
4
|
+
* host, plus the request-time forwarded prefix (`req.prefix` — which, under a
|
|
5
|
+
* `shared-<scenario>-<seed>` alias, is NOT the same as a prefix rebuilt from
|
|
6
|
+
* `req.workspaceId`; see `AskDeps.items`'s doc comment). Every app wires this
|
|
7
|
+
* one function rather than carrying its own copy; a site behind a different
|
|
8
|
+
* edge can still supply its own.
|
|
9
|
+
*
|
|
10
|
+
* `x-forwarded-host` WINS over `host`: the gateway proxies with reply-from,
|
|
11
|
+
* which rewrites Host to the INTERNAL target ("warehouse:3000"), so a site
|
|
12
|
+
* trusting `host` would advertise a robots.txt / schema map URL no crawler
|
|
13
|
+
* can reach (live-verified). Only the first value of a comma-separated chain
|
|
14
|
+
* is used — that is the original client's host; the rest are inner hops.
|
|
15
|
+
*/
|
|
16
|
+
export declare function defaultPublicBaseUrl(req: FastifyRequest): string;
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/** First value of a possibly-repeated, possibly-comma-chained forwarding header. */
|
|
2
|
+
function forwarded(req, name) {
|
|
3
|
+
const raw = req.headers[name];
|
|
4
|
+
const first = Array.isArray(raw) ? raw[0] : raw;
|
|
5
|
+
return first?.split(",")[0]?.trim() || undefined;
|
|
6
|
+
}
|
|
7
|
+
/**
|
|
8
|
+
* The standard `SchemaDeps.publicBaseUrl`: the gateway's forwarded proto and
|
|
9
|
+
* host, plus the request-time forwarded prefix (`req.prefix` — which, under a
|
|
10
|
+
* `shared-<scenario>-<seed>` alias, is NOT the same as a prefix rebuilt from
|
|
11
|
+
* `req.workspaceId`; see `AskDeps.items`'s doc comment). Every app wires this
|
|
12
|
+
* one function rather than carrying its own copy; a site behind a different
|
|
13
|
+
* edge can still supply its own.
|
|
14
|
+
*
|
|
15
|
+
* `x-forwarded-host` WINS over `host`: the gateway proxies with reply-from,
|
|
16
|
+
* which rewrites Host to the INTERNAL target ("warehouse:3000"), so a site
|
|
17
|
+
* trusting `host` would advertise a robots.txt / schema map URL no crawler
|
|
18
|
+
* can reach (live-verified). Only the first value of a comma-separated chain
|
|
19
|
+
* is used — that is the original client's host; the rest are inner hops.
|
|
20
|
+
*/
|
|
21
|
+
export function defaultPublicBaseUrl(req) {
|
|
22
|
+
const host = forwarded(req, "x-forwarded-host") ?? req.headers.host;
|
|
23
|
+
return `${forwarded(req, "x-forwarded-proto") ?? "http"}://${host}${req.prefix}`;
|
|
24
|
+
}
|
|
25
|
+
//# sourceMappingURL=request-url.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"request-url.js","sourceRoot":"","sources":["../../src/nlweb/request-url.ts"],"names":[],"mappings":"AAEA,oFAAoF;AACpF,SAAS,SAAS,CAAC,GAAmB,EAAE,IAAY;IAClD,MAAM,GAAG,GAAG,GAAG,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;IAC9B,MAAM,KAAK,GAAG,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC;IAChD,OAAO,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,IAAI,SAAS,CAAC;AACnD,CAAC;AAED;;;;;;;;;;;;;GAaG;AACH,MAAM,UAAU,oBAAoB,CAAC,GAAmB;IACtD,MAAM,IAAI,GAAG,SAAS,CAAC,GAAG,EAAE,kBAAkB,CAAC,IAAI,GAAG,CAAC,OAAO,CAAC,IAAI,CAAC;IACpE,OAAO,GAAG,SAAS,CAAC,GAAG,EAAE,mBAAmB,CAAC,IAAI,MAAM,MAAM,IAAI,GAAG,GAAG,CAAC,MAAM,EAAE,CAAC;AACnF,CAAC"}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { FastifyInstance, FastifyRequest } from "fastify";
|
|
2
|
+
import type { AskDeps } from "./types.js";
|
|
3
|
+
/**
|
|
4
|
+
* The crawler-facing half of NLWeb: a JSONL schema feed, a schema map pointing
|
|
5
|
+
* at it, and the robots.txt `schemamap:` directive that lets an agent discover
|
|
6
|
+
* both from the site root alone — no out-of-band configuration.
|
|
7
|
+
*/
|
|
8
|
+
export type SchemaDeps = AskDeps & {
|
|
9
|
+
publicBaseUrl: (req: FastifyRequest) => string;
|
|
10
|
+
};
|
|
11
|
+
export declare function registerSchemaRoutes(app: FastifyInstance, d: SchemaDeps): void;
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { esc } from "../html.js";
|
|
2
|
+
const SITEMAP_NS = "http://www.sitemaps.org/schemas/sitemap/0.9";
|
|
3
|
+
const SCHEMA_FEED_NS = "http://schema.org/schemas/schemafeed/0.1";
|
|
4
|
+
export function registerSchemaRoutes(app, d) {
|
|
5
|
+
const now = d.now ?? (() => new Date());
|
|
6
|
+
// One JSON-LD object per line: a consumer streams it and never has to hold
|
|
7
|
+
// the whole corpus (or a well-formed enclosing array) in memory.
|
|
8
|
+
app.get("/schema/feed.jsonl", async (req, reply) => {
|
|
9
|
+
const items = await d.items(req.workspaceId, req.prefix);
|
|
10
|
+
return reply.type("application/jsonl; charset=utf-8").send(items.map((i) => `${JSON.stringify(i.schema)}\n`).join(""));
|
|
11
|
+
});
|
|
12
|
+
app.get("/schema/map.xml", async (req, reply) => {
|
|
13
|
+
const base = d.publicBaseUrl(req);
|
|
14
|
+
const lastmod = now().toISOString().slice(0, 10);
|
|
15
|
+
const xml = `<?xml version="1.0" encoding="UTF-8"?>
|
|
16
|
+
<urlset xmlns="${SITEMAP_NS}" xmlns:sf="${SCHEMA_FEED_NS}">
|
|
17
|
+
<url>
|
|
18
|
+
<loc>${esc(base)}/schema/feed.jsonl</loc>
|
|
19
|
+
<lastmod>${lastmod}</lastmod>
|
|
20
|
+
<sf:contentType>structuredData/schema.org</sf:contentType>
|
|
21
|
+
</url>
|
|
22
|
+
</urlset>
|
|
23
|
+
`;
|
|
24
|
+
return reply.type("application/xml; charset=utf-8").send(xml);
|
|
25
|
+
});
|
|
26
|
+
// /account is the one authenticated area; everything else is meant to be read.
|
|
27
|
+
app.get("/robots.txt", async (req, reply) => {
|
|
28
|
+
const base = d.publicBaseUrl(req);
|
|
29
|
+
return reply.type("text/plain; charset=utf-8").send(`User-agent: *\nDisallow: /account\nschemamap: ${base}/schema/map.xml\n`);
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
//# sourceMappingURL=schema-routes.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"schema-routes.js","sourceRoot":"","sources":["../../src/nlweb/schema-routes.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,GAAG,EAAE,MAAM,YAAY,CAAC;AAUjC,MAAM,UAAU,GAAG,6CAA6C,CAAC;AACjE,MAAM,cAAc,GAAG,0CAA0C,CAAC;AAElE,MAAM,UAAU,oBAAoB,CAAC,GAAoB,EAAE,CAAa;IACtE,MAAM,GAAG,GAAG,CAAC,CAAC,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC,IAAI,IAAI,EAAE,CAAC,CAAC;IAExC,2EAA2E;IAC3E,iEAAiE;IACjE,GAAG,CAAC,GAAG,CAAC,oBAAoB,EAAE,KAAK,EAAE,GAAG,EAAE,KAAK,EAAE,EAAE;QACjD,MAAM,KAAK,GAAG,MAAM,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,WAAW,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC;QACzD,OAAO,KAAK,CAAC,IAAI,CAAC,kCAAkC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,GAAG,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC;IACzH,CAAC,CAAC,CAAC;IAEH,GAAG,CAAC,GAAG,CAAC,iBAAiB,EAAE,KAAK,EAAE,GAAG,EAAE,KAAK,EAAE,EAAE;QAC9C,MAAM,IAAI,GAAG,CAAC,CAAC,aAAa,CAAC,GAAG,CAAC,CAAC;QAClC,MAAM,OAAO,GAAG,GAAG,EAAE,CAAC,WAAW,EAAE,CAAC,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;QACjD,MAAM,GAAG,GAAG;iBACC,UAAU,eAAe,cAAc;;WAE7C,GAAG,CAAC,IAAI,CAAC;eACL,OAAO;;;;CAIrB,CAAC;QACE,OAAO,KAAK,CAAC,IAAI,CAAC,gCAAgC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;IAChE,CAAC,CAAC,CAAC;IAEH,+EAA+E;IAC/E,GAAG,CAAC,GAAG,CAAC,aAAa,EAAE,KAAK,EAAE,GAAG,EAAE,KAAK,EAAE,EAAE;QAC1C,MAAM,IAAI,GAAG,CAAC,CAAC,aAAa,CAAC,GAAG,CAAC,CAAC;QAClC,OAAO,KAAK,CAAC,IAAI,CAAC,2BAA2B,CAAC,CAAC,IAAI,CAAC,iDAAiD,IAAI,mBAAmB,CAAC,CAAC;IAChI,CAAC,CAAC,CAAC;AACL,CAAC"}
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The NLWeb wire model, kept separate from any site's own domain types: a site
|
|
3
|
+
* maps its rows to `AskItem`s (Task 7) and everything downstream — retrieval,
|
|
4
|
+
* ranking, /ask, the schema feed — works only against these.
|
|
5
|
+
*/
|
|
6
|
+
/** One answerable thing on a site, already carrying the JSON-LD a crawler or an agent gets back. */
|
|
7
|
+
export type AskItem = {
|
|
8
|
+
id: string;
|
|
9
|
+
/** Link an agent can follow; item mappers build it from the request prefix. */
|
|
10
|
+
url: string;
|
|
11
|
+
name: string;
|
|
12
|
+
/** Free text retrieval reads, and the fallback description of a result. */
|
|
13
|
+
text: string;
|
|
14
|
+
keywords?: string[];
|
|
15
|
+
/** JSON-LD for this item, including @context/@type/@id — served verbatim in results and in the feed. */
|
|
16
|
+
schema: Record<string, unknown>;
|
|
17
|
+
/**
|
|
18
|
+
* Stamped by `retrieve` on the copy it returns, so a Ranker can re-emit or
|
|
19
|
+
* blend the lexical score without paying to re-score the corpus.
|
|
20
|
+
*/
|
|
21
|
+
lexicalScore?: number;
|
|
22
|
+
};
|
|
23
|
+
/** One NLWeb result object, exactly as the /ask wire format names its fields. */
|
|
24
|
+
export type AskResult = {
|
|
25
|
+
url: string;
|
|
26
|
+
name: string;
|
|
27
|
+
site: string;
|
|
28
|
+
score: number;
|
|
29
|
+
description: string;
|
|
30
|
+
schema_object: Record<string, unknown>;
|
|
31
|
+
};
|
|
32
|
+
/** A ranker's verdict on one candidate; `description` lets a ranker explain the match. */
|
|
33
|
+
export type RankedCandidate = {
|
|
34
|
+
id: string;
|
|
35
|
+
score: number;
|
|
36
|
+
description?: string;
|
|
37
|
+
};
|
|
38
|
+
/** What one ranking pass cost, so a degraded (failed-over) ranker is visible in the response and in metrics. */
|
|
39
|
+
export type RankerUsage = {
|
|
40
|
+
calls: number;
|
|
41
|
+
inputTokens: number;
|
|
42
|
+
latencyMs: number;
|
|
43
|
+
costUsd: number;
|
|
44
|
+
degraded: boolean;
|
|
45
|
+
};
|
|
46
|
+
/**
|
|
47
|
+
* The ranking seam. Lexical ranking ships here; LLM and jev rankers (Task 6)
|
|
48
|
+
* are added by registering another implementation — never by editing /ask.
|
|
49
|
+
*/
|
|
50
|
+
export interface Ranker {
|
|
51
|
+
readonly kind: string;
|
|
52
|
+
rank(query: string, candidates: AskItem[]): Promise<{
|
|
53
|
+
ranked: RankedCandidate[];
|
|
54
|
+
usage: RankerUsage;
|
|
55
|
+
}>;
|
|
56
|
+
}
|
|
57
|
+
/** Builds a Ranker from process env (api keys, model ids, endpoints). */
|
|
58
|
+
export type RankerFactory = (env: NodeJS.ProcessEnv) => Ranker;
|
|
59
|
+
/**
|
|
60
|
+
* Registry (Open/Closed): a deployment picks a ranker by kind, and a new kind
|
|
61
|
+
* is added by registering a factory — no switch anywhere in the request path.
|
|
62
|
+
*/
|
|
63
|
+
export declare class RankerRegistry {
|
|
64
|
+
private readonly factories;
|
|
65
|
+
register(kind: string, make: RankerFactory): this;
|
|
66
|
+
build(kind: string, env: NodeJS.ProcessEnv): Ranker;
|
|
67
|
+
kinds(): string[];
|
|
68
|
+
}
|
|
69
|
+
/** Everything /ask needs, injected: the site never reaches into the service. */
|
|
70
|
+
export type AskDeps = {
|
|
71
|
+
/** The site's name, echoed in every result's `site` field. */
|
|
72
|
+
site: string;
|
|
73
|
+
/**
|
|
74
|
+
* The workspace's corpus. Scoped by workspace so one tenant never answers
|
|
75
|
+
* with another's rows. `prefix` is the gateway-forwarded, request-time
|
|
76
|
+
* path (`req.prefix`) — NOT derivable from `workspaceId` alone: under a
|
|
77
|
+
* shared alias (e.g. `/w/shared-<scenario>-<seed>/<app>`) the forwarded
|
|
78
|
+
* prefix carries the alias, while `workspaceId` is the resolved internal
|
|
79
|
+
* id. Item urls/@ids must be built from `prefix`, never a re-derived one.
|
|
80
|
+
*/
|
|
81
|
+
items: (workspaceId: string, prefix: string) => Promise<AskItem[]>;
|
|
82
|
+
ranker: Ranker;
|
|
83
|
+
/** Candidates retrieved before ranking, and the maximum results returned. */
|
|
84
|
+
topK?: number;
|
|
85
|
+
/** Injected clock, so the schema map's <lastmod> is testable. */
|
|
86
|
+
now?: () => Date;
|
|
87
|
+
/**
|
|
88
|
+
* Resolves an `X-Ask-Ranker` override to the Ranker it names, or `undefined`
|
|
89
|
+
* for a kind the deployment doesn't have (unregistered, or missing its
|
|
90
|
+
* credentials) — the route answers 422 rather than silently keeping the
|
|
91
|
+
* default ranker. Only consulted when `allowRankerOverride` is true; site-kit
|
|
92
|
+
* never builds a ranker itself here, so it stays free of ranker credentials
|
|
93
|
+
* and of `process.env`.
|
|
94
|
+
*/
|
|
95
|
+
rankerFor?: (kind: string) => Ranker | undefined;
|
|
96
|
+
/**
|
|
97
|
+
* Enables the `X-Ask-Ranker` override — an eval-only knob (tools/ask-eval.mjs
|
|
98
|
+
* scores every arm of the ranker grid against one running deployment instead
|
|
99
|
+
* of redeploying per arm) that must default OFF in production. The app sets
|
|
100
|
+
* this from its own `ASK_RANKER_OVERRIDE=1` env read; site-kit itself must
|
|
101
|
+
* never read process.env.
|
|
102
|
+
*/
|
|
103
|
+
allowRankerOverride?: boolean;
|
|
104
|
+
};
|
|
105
|
+
/** What one /ask call cost and how long it took, surfaced so an eval can compare rankers on cost/latency, not just relevance. */
|
|
106
|
+
export type AskUsage = {
|
|
107
|
+
calls: number;
|
|
108
|
+
inputTokens: number;
|
|
109
|
+
costUsd: number;
|
|
110
|
+
latencyMs: number;
|
|
111
|
+
};
|
|
112
|
+
/** The non-streaming /ask body; the SSE frames carry only `results` (and a `ranker` message on degrade) from the same answer. */
|
|
113
|
+
export type AskResponse = {
|
|
114
|
+
query_id: string;
|
|
115
|
+
results: AskResult[];
|
|
116
|
+
ranker: string;
|
|
117
|
+
/** Present only when the ranker fell back, so a grader can tell a degraded answer from a good one. */
|
|
118
|
+
ranker_degraded?: true;
|
|
119
|
+
/** What ranking this answer cost — the primitive tools/ask-eval.mjs reads for its cost/query and latency columns. */
|
|
120
|
+
usage: AskUsage;
|
|
121
|
+
};
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The NLWeb wire model, kept separate from any site's own domain types: a site
|
|
3
|
+
* maps its rows to `AskItem`s (Task 7) and everything downstream — retrieval,
|
|
4
|
+
* ranking, /ask, the schema feed — works only against these.
|
|
5
|
+
*/
|
|
6
|
+
/**
|
|
7
|
+
* Registry (Open/Closed): a deployment picks a ranker by kind, and a new kind
|
|
8
|
+
* is added by registering a factory — no switch anywhere in the request path.
|
|
9
|
+
*/
|
|
10
|
+
export class RankerRegistry {
|
|
11
|
+
factories = new Map();
|
|
12
|
+
register(kind, make) {
|
|
13
|
+
if (this.factories.has(kind))
|
|
14
|
+
throw new Error(`duplicate ranker: ${kind}`);
|
|
15
|
+
this.factories.set(kind, make);
|
|
16
|
+
return this;
|
|
17
|
+
}
|
|
18
|
+
build(kind, env) {
|
|
19
|
+
const make = this.factories.get(kind);
|
|
20
|
+
if (!make)
|
|
21
|
+
throw new Error(`unknown ranker: ${kind} (known: ${this.kinds().join(", ") || "none"})`);
|
|
22
|
+
return make(env);
|
|
23
|
+
}
|
|
24
|
+
kinds() {
|
|
25
|
+
return [...this.factories.keys()];
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
//# sourceMappingURL=types.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/nlweb/types.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAgDH;;;GAGG;AACH,MAAM,OAAO,cAAc;IACR,SAAS,GAAG,IAAI,GAAG,EAAyB,CAAC;IAE9D,QAAQ,CAAC,IAAY,EAAE,IAAmB;QACxC,IAAI,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,IAAI,CAAC;YAAE,MAAM,IAAI,KAAK,CAAC,qBAAqB,IAAI,EAAE,CAAC,CAAC;QAC3E,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;QAC/B,OAAO,IAAI,CAAC;IACd,CAAC;IAED,KAAK,CAAC,IAAY,EAAE,GAAsB;QACxC,MAAM,IAAI,GAAG,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;QACtC,IAAI,CAAC,IAAI;YAAE,MAAM,IAAI,KAAK,CAAC,mBAAmB,IAAI,YAAY,IAAI,CAAC,KAAK,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,MAAM,GAAG,CAAC,CAAC;QACpG,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC;IACnB,CAAC;IAED,KAAK;QACH,OAAO,CAAC,GAAG,IAAI,CAAC,SAAS,CAAC,IAAI,EAAE,CAAC,CAAC;IACpC,CAAC;CACF"}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Naive plural/singular pair for a keyword. `tokenize` (./lexical.ts) has no
|
|
3
|
+
* stemming, so a query for either form of a word ("fastener" vs "fasteners")
|
|
4
|
+
* is a different token to it — a site that only puts one form in an item's
|
|
5
|
+
* `keywords` silently misses the other. Not linguistically correct (just
|
|
6
|
+
* drop/add a trailing "s"); good enough for synthetic-corpus vocabulary,
|
|
7
|
+
* and shared here so every site's item mapper agrees on it instead of
|
|
8
|
+
* carrying its own copy that can drift.
|
|
9
|
+
*/
|
|
10
|
+
export declare function wordVariants(word: string): string[];
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Naive plural/singular pair for a keyword. `tokenize` (./lexical.ts) has no
|
|
3
|
+
* stemming, so a query for either form of a word ("fastener" vs "fasteners")
|
|
4
|
+
* is a different token to it — a site that only puts one form in an item's
|
|
5
|
+
* `keywords` silently misses the other. Not linguistically correct (just
|
|
6
|
+
* drop/add a trailing "s"); good enough for synthetic-corpus vocabulary,
|
|
7
|
+
* and shared here so every site's item mapper agrees on it instead of
|
|
8
|
+
* carrying its own copy that can drift.
|
|
9
|
+
*/
|
|
10
|
+
export function wordVariants(word) {
|
|
11
|
+
const w = word.toLowerCase();
|
|
12
|
+
return w.endsWith("s") ? [w, w.slice(0, -1)] : [w, `${w}s`];
|
|
13
|
+
}
|
|
14
|
+
//# sourceMappingURL=word-variants.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"word-variants.js","sourceRoot":"","sources":["../../src/nlweb/word-variants.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AACH,MAAM,UAAU,YAAY,CAAC,IAAY;IACvC,MAAM,CAAC,GAAG,IAAI,CAAC,WAAW,EAAE,CAAC;IAC7B,OAAO,CAAC,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,GAAG,CAAC,GAAG,CAAC,CAAC;AAC9D,CAAC"}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { ToolDef } from "./tool-registry.js";
|
|
2
|
+
/** The JSON Schema a WebMCP registration carries (draft-07 subset, no `$schema` key). */
|
|
3
|
+
export type JsonSchemaObject = {
|
|
4
|
+
type: "object";
|
|
5
|
+
properties: Record<string, unknown>;
|
|
6
|
+
required?: string[];
|
|
7
|
+
additionalProperties?: boolean;
|
|
8
|
+
};
|
|
9
|
+
/**
|
|
10
|
+
* One catalog, two surfaces: the MCP SDK converts `ToolDef.input` itself; the
|
|
11
|
+
* page-side WebMCP registration needs the same schema as data. Strip `$schema`
|
|
12
|
+
* so the object is exactly what `navigator.modelContext.registerTool` expects.
|
|
13
|
+
*/
|
|
14
|
+
export declare function toolInputJsonSchema(def: Pick<ToolDef<unknown>, "input">): JsonSchemaObject;
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { zodToJsonSchema } from "zod-to-json-schema";
|
|
3
|
+
/**
|
|
4
|
+
* One catalog, two surfaces: the MCP SDK converts `ToolDef.input` itself; the
|
|
5
|
+
* page-side WebMCP registration needs the same schema as data. Strip `$schema`
|
|
6
|
+
* so the object is exactly what `navigator.modelContext.registerTool` expects.
|
|
7
|
+
*/
|
|
8
|
+
export function toolInputJsonSchema(def) {
|
|
9
|
+
const { $schema: _drop, ...rest } = zodToJsonSchema(z.object(def.input).strict(), { target: "jsonSchema7" });
|
|
10
|
+
const out = rest;
|
|
11
|
+
if (!out.properties)
|
|
12
|
+
out.properties = {};
|
|
13
|
+
return out;
|
|
14
|
+
}
|
|
15
|
+
//# sourceMappingURL=tool-schema.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"tool-schema.js","sourceRoot":"","sources":["../src/tool-schema.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AAWrD;;;;GAIG;AACH,MAAM,UAAU,mBAAmB,CAAC,GAAoC;IACtE,MAAM,EAAE,OAAO,EAAE,KAAK,EAAE,GAAG,IAAI,EAAE,GAAG,eAAe,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,aAAa,EAAE,CAA4B,CAAC;IACxI,MAAM,GAAG,GAAG,IAAwB,CAAC;IACrC,IAAI,CAAC,GAAG,CAAC,UAAU;QAAE,GAAG,CAAC,UAAU,GAAG,EAAE,CAAC;IACzC,OAAO,GAAG,CAAC;AACb,CAAC"}
|
package/dist/webmcp.d.ts
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { ToolRegistry } from "./tool-registry.js";
|
|
2
|
+
export declare const WEBMCP_SCRIPT_MARKER = "data-webmcp=\"bridge\"";
|
|
3
|
+
/** The global a late-injecting agent sidecar can call once it has installed `navigator.modelContext`. */
|
|
4
|
+
export declare const WEBMCP_REGISTER_GLOBAL = "__benchmeWebmcpRegister";
|
|
5
|
+
/**
|
|
6
|
+
* WebMCP (`navigator.modelContext`) tools are closures inside the page. This
|
|
7
|
+
* script registers one per catalog entry and bridges `execute` to the app's
|
|
8
|
+
* own `/mcp` (JSON-RPC `tools/call`), so the page surface and the MCP surface
|
|
9
|
+
* can never disagree: both are rendered from `ToolRegistry.list()`.
|
|
10
|
+
*
|
|
11
|
+
* Registration is a FUNCTION, not a parse-time side effect, because the agent
|
|
12
|
+
* that provides `navigator.modelContext` usually injects it AFTER the page
|
|
13
|
+
* parses: a one-shot attempt at parse time silently registered nothing and
|
|
14
|
+
* never tried again. So it runs immediately, again on `DOMContentLoaded`, and
|
|
15
|
+
* on demand via `window.__benchmeWebmcpRegister()` — guarded by a flag so the
|
|
16
|
+
* three paths together still register each tool exactly once. `navigator`
|
|
17
|
+
* itself is read defensively: a non-browser runtime must be a no-op, never a
|
|
18
|
+
* ReferenceError that kills the rest of the page's scripts.
|
|
19
|
+
*/
|
|
20
|
+
export declare function webmcpScript<C>(tools: ToolRegistry<C>, prefix: string): string;
|
package/dist/webmcp.js
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { toolInputJsonSchema } from "./tool-schema.js";
|
|
2
|
+
export const WEBMCP_SCRIPT_MARKER = 'data-webmcp="bridge"';
|
|
3
|
+
/** The global a late-injecting agent sidecar can call once it has installed `navigator.modelContext`. */
|
|
4
|
+
export const WEBMCP_REGISTER_GLOBAL = "__benchmeWebmcpRegister";
|
|
5
|
+
/**
|
|
6
|
+
* WebMCP (`navigator.modelContext`) tools are closures inside the page. This
|
|
7
|
+
* script registers one per catalog entry and bridges `execute` to the app's
|
|
8
|
+
* own `/mcp` (JSON-RPC `tools/call`), so the page surface and the MCP surface
|
|
9
|
+
* can never disagree: both are rendered from `ToolRegistry.list()`.
|
|
10
|
+
*
|
|
11
|
+
* Registration is a FUNCTION, not a parse-time side effect, because the agent
|
|
12
|
+
* that provides `navigator.modelContext` usually injects it AFTER the page
|
|
13
|
+
* parses: a one-shot attempt at parse time silently registered nothing and
|
|
14
|
+
* never tried again. So it runs immediately, again on `DOMContentLoaded`, and
|
|
15
|
+
* on demand via `window.__benchmeWebmcpRegister()` — guarded by a flag so the
|
|
16
|
+
* three paths together still register each tool exactly once. `navigator`
|
|
17
|
+
* itself is read defensively: a non-browser runtime must be a no-op, never a
|
|
18
|
+
* ReferenceError that kills the rest of the page's scripts.
|
|
19
|
+
*/
|
|
20
|
+
export function webmcpScript(tools, prefix) {
|
|
21
|
+
const catalog = tools.list().map((t) => ({ name: t.name, description: t.description, inputSchema: toolInputJsonSchema(t) }));
|
|
22
|
+
const json = JSON.stringify({ endpoint: `${prefix}/mcp`, tools: catalog }).replace(/<\//g, "<\\/");
|
|
23
|
+
return `<script ${WEBMCP_SCRIPT_MARKER}>(function(){var cfg=${json};var seq=0;var registered=false;
|
|
24
|
+
function call(name,args){return fetch(cfg.endpoint,{method:"POST",headers:{"content-type":"application/json","accept":"application/json, text/event-stream"},body:JSON.stringify({jsonrpc:"2.0",id:++seq,method:"tools/call",params:{name:name,arguments:args||{}}})}).then(function(r){return r.text()}).then(function(t){var line=t.split("\\n").filter(function(l){return l.indexOf("data:")===0}).pop();var body=JSON.parse(line?line.slice(5):t);var c=body.result&&body.result.content;return c&&c[0]&&c[0].text?c[0].text:JSON.stringify(body.result||body.error)})}
|
|
25
|
+
function register(){if(registered)return true;if(typeof navigator==="undefined")return false;var mc=navigator.modelContext;if(!mc||typeof mc.registerTool!=="function")return false;
|
|
26
|
+
cfg.tools.forEach(function(t){mc.registerTool({name:t.name,description:t.description,inputSchema:t.inputSchema,execute:function(a){return call(t.name,a)}})});registered=true;return true}
|
|
27
|
+
if(typeof window!=="undefined")window.${WEBMCP_REGISTER_GLOBAL}=register;
|
|
28
|
+
register();
|
|
29
|
+
if(typeof document!=="undefined"&&document.addEventListener)document.addEventListener("DOMContentLoaded",register);})();</script>`;
|
|
30
|
+
}
|
|
31
|
+
//# sourceMappingURL=webmcp.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"webmcp.js","sourceRoot":"","sources":["../src/webmcp.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,mBAAmB,EAAE,MAAM,kBAAkB,CAAC;AAEvD,MAAM,CAAC,MAAM,oBAAoB,GAAG,sBAAsB,CAAC;AAE3D,yGAAyG;AACzG,MAAM,CAAC,MAAM,sBAAsB,GAAG,yBAAyB,CAAC;AAEhE;;;;;;;;;;;;;;GAcG;AACH,MAAM,UAAU,YAAY,CAAI,KAAsB,EAAE,MAAc;IACpE,MAAM,OAAO,GAAG,KAAK,CAAC,IAAI,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,EAAE,IAAI,EAAE,CAAC,CAAC,IAAI,EAAE,WAAW,EAAE,CAAC,CAAC,WAAW,EAAE,WAAW,EAAE,mBAAmB,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;IAC7H,MAAM,IAAI,GAAG,IAAI,CAAC,SAAS,CAAC,EAAE,QAAQ,EAAE,GAAG,MAAM,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC,CAAC,OAAO,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACnG,OAAO,WAAW,oBAAoB,wBAAwB,IAAI;;;;wCAI5B,sBAAsB;;kIAEoE,CAAC;AACnI,CAAC"}
|