@konneal/engine 0.2.190 → 0.2.192
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/ask-Q63SLXRD.js +16 -0
- package/dist/{chunk-22WB6IVC.js → chunk-5Y3CDK64.js} +13 -0
- package/dist/{chunk-7YMIUTPY.js → chunk-J4UAO5XI.js} +1 -1
- package/dist/{chunk-GJQT4IMD.js → chunk-M4OCMIWU.js} +1 -1
- package/dist/{chunk-ECNBEZGK.js → chunk-NHNCW6KQ.js} +3 -3
- package/dist/{chunk-5PKKAHY4.js → chunk-UDHM3G5N.js} +6 -5
- package/dist/{chunk-AVNHVFEB.js → chunk-VGBZYYVH.js} +1 -1
- package/dist/{chunk-Q7QL3457.js → chunk-W4F22Y4M.js} +134 -34
- package/dist/{chunk-WRSUXIS7.js → chunk-ZPNYAANP.js} +35 -32
- package/dist/config.d.ts +13 -0
- package/dist/nameplate.d.ts +0 -1
- package/dist/search-7ANUZAYL.js +14 -0
- package/dist/{tools-7GKMDWVB.js → tools-LOQBTAFQ.js} +4 -4
- package/dist/userDocuments.d.ts +1 -0
- package/dist/worker_mcp/src/index.js +2 -2
- package/dist/worker_public/src/config.js +1 -1
- package/dist/worker_public/src/index.js +19 -18
- package/dist/worker_public/src/requestScope.js +2 -2
- package/docs/ARCHITECTURE.md +7 -5
- package/package.json +1 -1
- package/workers/worker_public/src/ask.ts +42 -32
- package/workers/worker_public/src/config.ts +13 -0
- package/workers/worker_public/src/decisionWire.ts +2 -2
- package/workers/worker_public/src/index.ts +1 -1
- package/workers/worker_public/src/nameplate.ts +0 -3
- package/workers/worker_public/src/quota.ts +8 -1
- package/workers/worker_public/src/research.ts +9 -8
- package/workers/worker_public/src/search.ts +2 -2
- package/workers/worker_public/src/stages/sectionDescent.ts +9 -21
- package/workers/worker_public/src/stages/typedPin.ts +133 -15
- package/workers/worker_public/src/stages/vlmFigureRerank.ts +2 -2
- package/workers/worker_public/src/userDocuments.ts +7 -6
- package/dist/ask-6SWT3KSC.js +0 -16
- package/dist/search-DE5ADCVM.js +0 -14
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import {
|
|
2
|
+
handleSearch
|
|
3
|
+
} from "./chunk-UDHM3G5N.js";
|
|
4
|
+
import "./chunk-W4F22Y4M.js";
|
|
5
|
+
import "./chunk-VGBZYYVH.js";
|
|
6
|
+
import "./chunk-M4OCMIWU.js";
|
|
7
|
+
import "./chunk-ETLSWSZ7.js";
|
|
8
|
+
import "./chunk-J4UAO5XI.js";
|
|
9
|
+
import "./chunk-5Y3CDK64.js";
|
|
10
|
+
import "./chunk-3FYJM7LH.js";
|
|
11
|
+
import "./chunk-H6ZULBW2.js";
|
|
12
|
+
export {
|
|
13
|
+
handleSearch
|
|
14
|
+
};
|
|
@@ -4,10 +4,10 @@ import {
|
|
|
4
4
|
parseToolCall,
|
|
5
5
|
runTool,
|
|
6
6
|
toolNote
|
|
7
|
-
} from "./chunk-
|
|
8
|
-
import "./chunk-
|
|
9
|
-
import "./chunk-
|
|
10
|
-
import "./chunk-
|
|
7
|
+
} from "./chunk-NHNCW6KQ.js";
|
|
8
|
+
import "./chunk-VGBZYYVH.js";
|
|
9
|
+
import "./chunk-J4UAO5XI.js";
|
|
10
|
+
import "./chunk-5Y3CDK64.js";
|
|
11
11
|
import "./chunk-3FYJM7LH.js";
|
|
12
12
|
import "./chunk-H6ZULBW2.js";
|
|
13
13
|
export {
|
package/dist/userDocuments.d.ts
CHANGED
|
@@ -9,16 +9,16 @@ import {
|
|
|
9
9
|
listUserDocuments,
|
|
10
10
|
scoreFaithfulness,
|
|
11
11
|
scoreJudge
|
|
12
|
-
} from "../../chunk-
|
|
12
|
+
} from "../../chunk-ZPNYAANP.js";
|
|
13
13
|
import "../../chunk-IRCDOFP4.js";
|
|
14
14
|
import {
|
|
15
15
|
TOOLS_REGISTRY,
|
|
16
16
|
bindModelNode,
|
|
17
17
|
modelGroundingBlock
|
|
18
|
-
} from "../../chunk-
|
|
18
|
+
} from "../../chunk-NHNCW6KQ.js";
|
|
19
19
|
import {
|
|
20
20
|
handleSearch
|
|
21
|
-
} from "../../chunk-
|
|
21
|
+
} from "../../chunk-UDHM3G5N.js";
|
|
22
22
|
import {
|
|
23
23
|
buildMessages,
|
|
24
24
|
citations,
|
|
@@ -43,11 +43,11 @@ import {
|
|
|
43
43
|
sessionFrom,
|
|
44
44
|
telemetry,
|
|
45
45
|
understandQuery
|
|
46
|
-
} from "../../chunk-
|
|
46
|
+
} from "../../chunk-W4F22Y4M.js";
|
|
47
47
|
import {
|
|
48
48
|
embed,
|
|
49
49
|
generateOnce
|
|
50
|
-
} from "../../chunk-
|
|
50
|
+
} from "../../chunk-VGBZYYVH.js";
|
|
51
51
|
import {
|
|
52
52
|
authenticate,
|
|
53
53
|
corsHeaders,
|
|
@@ -56,14 +56,14 @@ import {
|
|
|
56
56
|
readJson,
|
|
57
57
|
validateQuery,
|
|
58
58
|
withCors
|
|
59
|
-
} from "../../chunk-
|
|
59
|
+
} from "../../chunk-M4OCMIWU.js";
|
|
60
60
|
import {
|
|
61
61
|
canonicalRefusal
|
|
62
62
|
} from "../../chunk-ETLSWSZ7.js";
|
|
63
63
|
import {
|
|
64
64
|
entitlementScope,
|
|
65
65
|
standardKeysFrom
|
|
66
|
-
} from "../../chunk-
|
|
66
|
+
} from "../../chunk-J4UAO5XI.js";
|
|
67
67
|
import {
|
|
68
68
|
LIMITS,
|
|
69
69
|
MODELS,
|
|
@@ -74,7 +74,7 @@ import {
|
|
|
74
74
|
roleModel,
|
|
75
75
|
sha256Hex,
|
|
76
76
|
today
|
|
77
|
-
} from "../../chunk-
|
|
77
|
+
} from "../../chunk-5Y3CDK64.js";
|
|
78
78
|
import {
|
|
79
79
|
P,
|
|
80
80
|
setProfile
|
|
@@ -878,7 +878,7 @@ async function handleResearch(env, ctx, req, session) {
|
|
|
878
878
|
async function run(env, ctx, q, maxIters, emit) {
|
|
879
879
|
const started = Date.now();
|
|
880
880
|
const queryHash = await sha256Hex(q.query);
|
|
881
|
-
const understanding = await understandQuery(portModelRunner(env),
|
|
881
|
+
const understanding = await understandQuery(portModelRunner(env), roleModel(env, "understand"), q.query, [], []);
|
|
882
882
|
const graphDocNumbers = await graphExpand(env, understanding);
|
|
883
883
|
const eNote = await editionNote(env, understanding);
|
|
884
884
|
const accumulated = /* @__PURE__ */ new Map();
|
|
@@ -910,7 +910,7 @@ ${older.map((h) => `- ${h.metadata.docidentifier ?? ""} \xA7${h.metadata.clause_
|
|
|
910
910
|
` : "";
|
|
911
911
|
judge = await (async () => {
|
|
912
912
|
try {
|
|
913
|
-
const res = await env.AI.run(
|
|
913
|
+
const res = await env.AI.run(roleModel(env, "grader"), {
|
|
914
914
|
messages: [
|
|
915
915
|
{ role: "system", content: fill(research_default, promptVars()).trimEnd() },
|
|
916
916
|
{ role: "user", content: `Research question: ${q.query}
|
|
@@ -955,10 +955,11 @@ ${recent.map((h, n) => `[${n + 1}] ${h.metadata.docidentifier ?? ""} \xA7${h.met
|
|
|
955
955
|
throw new Error("Search is briefly busy \u2014 please retry in a moment.");
|
|
956
956
|
}
|
|
957
957
|
const { messages, usedHits } = buildMessages(q.query, used, q.lang, [], eNote || void 0, void 0, LIMITS.inputTokenBudget);
|
|
958
|
-
|
|
959
|
-
|
|
958
|
+
const researchModel = roleModel(env, "research");
|
|
959
|
+
let answer = await generateOnce(env, researchModel, messages);
|
|
960
|
+
if (answer === null) answer = await generateOnce(env, roleModel(env, "fallback"), messages);
|
|
960
961
|
if (answer === null) {
|
|
961
|
-
telemetry(env, ctx, "member", "research",
|
|
962
|
+
telemetry(env, ctx, "member", "research", researchModel, false, 0, queryHash, q.lang);
|
|
962
963
|
throw new Error("The generation model is unavailable; please retry.");
|
|
963
964
|
}
|
|
964
965
|
answer = canonicalRefusal(answer, { cited: /\[[^\]]+\]/.test(answer), conversational: false });
|
|
@@ -967,11 +968,11 @@ ${recent.map((h, n) => `[${n + 1}] ${h.metadata.docidentifier ?? ""} \xA7${h.met
|
|
|
967
968
|
const out = {
|
|
968
969
|
answer,
|
|
969
970
|
citations: citations(usedHits),
|
|
970
|
-
model:
|
|
971
|
+
model: researchModel,
|
|
971
972
|
query_hash: queryHash,
|
|
972
973
|
research: { iterations, passages: used.length, elapsed_ms: Date.now() - started, sufficient: judge?.sufficient ?? null }
|
|
973
974
|
};
|
|
974
|
-
telemetry(env, ctx, "member", "research",
|
|
975
|
+
telemetry(env, ctx, "member", "research", researchModel, true, answer.length, queryHash, q.lang);
|
|
975
976
|
emit?.({ type: "pass", n: iterations, of: maxIters, phase: "writing", passages: used.length });
|
|
976
977
|
return out;
|
|
977
978
|
}
|
|
@@ -1183,13 +1184,13 @@ async function callToolOnce(env, ctx, _req, tier, key, name, args, t0) {
|
|
|
1183
1184
|
// stream:false forces the JSON lane (anon defaults to SSE)
|
|
1184
1185
|
body: JSON.stringify({ ...args, stream: false })
|
|
1185
1186
|
});
|
|
1186
|
-
const { runTool, TOOLS_REGISTRY: TOOLS_REGISTRY2 } = await import("../../tools-
|
|
1187
|
+
const { runTool, TOOLS_REGISTRY: TOOLS_REGISTRY2 } = await import("../../tools-LOQBTAFQ.js");
|
|
1187
1188
|
let payload;
|
|
1188
1189
|
if (TOOLS_REGISTRY2.some((t) => t.name === name && t.audiences.includes("mcp"))) {
|
|
1189
1190
|
const r = await runTool({ ...env, DB: env.DB }, { name, args }, "mcp");
|
|
1190
1191
|
payload = r ? { tool: r.name, query: r.query, result: r.output } : { error: { message: `tool ${name} returned nothing for the given arguments` } };
|
|
1191
1192
|
} else {
|
|
1192
|
-
const res = name === "ask" ? await (await import("../../ask-
|
|
1193
|
+
const res = name === "ask" ? await (await import("../../ask-Q63SLXRD.js")).handleAsk(env, ctx, inner, tier, key) : await (await import("../../search-7ANUZAYL.js")).handleSearch(env, ctx, inner, tier, key);
|
|
1193
1194
|
payload = await res.json().catch(() => ({ error: { message: "tool transport failed", status: res.status } }));
|
|
1194
1195
|
}
|
|
1195
1196
|
telemetry(env, ctx, tier, `mcp:${name}`, null, !payload?.error, JSON.stringify(payload).length, await sha256Hex(`${name}:${JSON.stringify(args ?? {})}`), void 0, void 0, { durationMs: Date.now() - t0 });
|
|
@@ -1605,7 +1606,7 @@ async function memoriesRoute(c) {
|
|
|
1605
1606
|
return withCors(await handleMemories(c.env, who.sub, c.req, { method: c.req.method, id: c.params.id }), corsHeaders(c.req));
|
|
1606
1607
|
}
|
|
1607
1608
|
function userDocumentPorts(env) {
|
|
1608
|
-
return { store: cfStore(env.DB), blobs: cfBlobs(env.USER_DOCS), lane: cfVectorIndex(env.USER_DOCS_INDEX), model: cfModelRunner(env.AI) };
|
|
1609
|
+
return { store: cfStore(env.DB), blobs: cfBlobs(env.USER_DOCS), lane: cfVectorIndex(env.USER_DOCS_INDEX), model: cfModelRunner(env.AI), answerModel: roleModel(env, "member") };
|
|
1609
1610
|
}
|
|
1610
1611
|
async function userDocumentsRoute(c) {
|
|
1611
1612
|
const who = await opIdentity(c, "Sign in to manage your documents");
|
|
@@ -4,8 +4,8 @@ import {
|
|
|
4
4
|
requestSalt,
|
|
5
5
|
resolveRequestScope,
|
|
6
6
|
standardKeysFrom
|
|
7
|
-
} from "../../chunk-
|
|
8
|
-
import "../../chunk-
|
|
7
|
+
} from "../../chunk-J4UAO5XI.js";
|
|
8
|
+
import "../../chunk-5Y3CDK64.js";
|
|
9
9
|
import "../../chunk-3FYJM7LH.js";
|
|
10
10
|
export {
|
|
11
11
|
entitlementScope,
|
package/docs/ARCHITECTURE.md
CHANGED
|
@@ -29,7 +29,7 @@ failure modes in `docs/spec-pipeline.md`; the HTTP surface in
|
|
|
29
29
|
│ └────────────────────────────────────────────────────────────────┘ │
|
|
30
30
|
│ ↓ │
|
|
31
31
|
│ ┌─ 1. QUERY UNDERSTANDING (LLM) ─────────────────────────────────┐ │
|
|
32
|
-
│ │
|
|
32
|
+
│ │ deepseek-v4.1-flash (roleModel "understand") → strict JSON: │ │
|
|
33
33
|
│ │ · intent (see layer 0) · docidentifier/docnumber │ │
|
|
34
34
|
│ │ · process_intent (certify/apply → B-series, not R-series) │ │
|
|
35
35
|
│ │ · term ("what is a load cell" → "load cell") │ │
|
|
@@ -92,7 +92,7 @@ failure modes in `docs/spec-pipeline.md`; the HTTP surface in
|
|
|
92
92
|
│ └────────────────────────────────────────────────────────────────┘ │
|
|
93
93
|
│ ↓ │
|
|
94
94
|
│ ┌─ 9. CRAG GRADER ───────────────────────────────────────────────┐ │
|
|
95
|
-
│ │ deepseek-v4-flash grades
|
|
95
|
+
│ │ deepseek-v4.1-flash (roleModel "grader") grades good/weak/bad │ │
|
|
96
96
|
│ │ · good → generate │ │
|
|
97
97
|
│ │ · weak → ONE corrective re-retrieval (doc ident made │ │
|
|
98
98
|
│ │ explicit); accepted only on strictly better grade │ │
|
|
@@ -101,7 +101,8 @@ failure modes in `docs/spec-pipeline.md`; the HTTP surface in
|
|
|
101
101
|
│ └────────────────────────────────────────────────────────────────┘ │
|
|
102
102
|
│ ↓ │
|
|
103
103
|
│ ┌─ 10. GENERATION ───────────────────────────────────────────────┐ │
|
|
104
|
-
│ │
|
|
104
|
+
│ │ Both tiers: deepseek-v4.1-flash (roleModel member/anon; │ │
|
|
105
|
+
│ │ glm-5.3 fallback). Every model call goes through roleModel() │ │
|
|
105
106
|
│ │ System prompt is DATA (prompts/system.md, {{PLACEHOLDERS}} │ │
|
|
106
107
|
│ │ filled from code; per-corpus notes travel with the DATASETS │ │
|
|
107
108
|
│ │ catalog entry) │ │
|
|
@@ -232,7 +233,7 @@ failure modes in `docs/spec-pipeline.md`; the HTTP surface in
|
|
|
232
233
|
│ ES256 via JWKS, RFC 8414 discovery) │
|
|
233
234
|
│ · RAG-minted HMAC session cookie (7-day, sliding renewal) │
|
|
234
235
|
│ · Anon: 20/day per IP (KV counter) │
|
|
235
|
-
│ · Member: 300/day,
|
|
236
|
+
│ · Member: 300/day, deepseek-v4.1-flash (roleModel member) │
|
|
236
237
|
│ · API key: per-key limits, D1-backed │
|
|
237
238
|
│ · Operator IP exemption (env + KV override) │
|
|
238
239
|
│ · Role-gated datasets panel (ISO corpus: mc_member, etc.) │
|
|
@@ -283,7 +284,8 @@ failure modes in `docs/spec-pipeline.md`; the HTTP surface in
|
|
|
283
284
|
## 2026-09 additions (delta over the 2026-08-26 map)
|
|
284
285
|
|
|
285
286
|
- **Multimodal generation**: figure units among the used passages attach
|
|
286
|
-
their R2 pixels to the
|
|
287
|
+
their R2 pixels to the answer model's call (`attachFigureImages`;
|
|
288
|
+
glm-5.3 fallback) — the
|
|
287
289
|
model reads labels that exist only in the image. Users can attach a
|
|
288
290
|
photo (`image` data URL on /v1/ask, validated, 6MB) — text still drives
|
|
289
291
|
retrieval; image asks bypass both caches.
|
package/package.json
CHANGED
|
@@ -27,7 +27,7 @@
|
|
|
27
27
|
"playwright": "^1.62.1",
|
|
28
28
|
"yaml": "^2.9.1"
|
|
29
29
|
},
|
|
30
|
-
"version": "0.2.
|
|
30
|
+
"version": "0.2.192",
|
|
31
31
|
"description": "The Konneal engine: the publisher-agnostic build pipeline and API plane for standards intelligence (retrieval, answer contract, verdicts, evaluation).",
|
|
32
32
|
"license": "BSD-3-Clause",
|
|
33
33
|
"type": "module",
|
|
@@ -240,6 +240,25 @@ async function generateStream(env: Env, model: string, messages: any[], effort?:
|
|
|
240
240
|
return null;
|
|
241
241
|
}
|
|
242
242
|
|
|
243
|
+
/** The fallback is a text-only model: image parts must be flattened out
|
|
244
|
+
* first or it errors on (or silently ignores) the pixels the primary
|
|
245
|
+
* was carrying — and the figure-attach NOTE with them: a message saying
|
|
246
|
+
* "the image is attached" to a model that cannot see images gets
|
|
247
|
+
* ANSWERED instead of the question (observed in the wild). The
|
|
248
|
+
* user-image message keeps its text (the question) minus its note. */
|
|
249
|
+
function flattenForTextModel(messages: any[]): any[] {
|
|
250
|
+
const isFigureAttachMessage = (m: any) =>
|
|
251
|
+
Array.isArray(m.content) &&
|
|
252
|
+
m.content.some((part: any) => part?.type === "text" && /^The original image of figure unit /.test(part.text ?? ""));
|
|
253
|
+
return messages
|
|
254
|
+
.filter((m: any) => !isFigureAttachMessage(m))
|
|
255
|
+
.map((m: any) =>
|
|
256
|
+
typeof m.content === "string"
|
|
257
|
+
? m
|
|
258
|
+
: { ...m, content: m.content.filter((p: any) => p?.type === "text").map((p: any) => (p?.text ?? "").replace(/\n?\(The user attached an image with this question; interpret it directly when answering\.\)/, "")).join("\n") },
|
|
259
|
+
);
|
|
260
|
+
}
|
|
261
|
+
|
|
243
262
|
/** Compact overflow history into a short continuity summary. Null = keep
|
|
244
263
|
* nothing (degrades to plain truncation, never to failure). */
|
|
245
264
|
async function summarizeHistory(
|
|
@@ -539,7 +558,7 @@ async function handleAsk(
|
|
|
539
558
|
: undefined;
|
|
540
559
|
|
|
541
560
|
const ns = tier === "key" ? `k:${key!.id}` : member ? `m:${member.sub}` : "anon";
|
|
542
|
-
const model = member ?
|
|
561
|
+
const model = roleModel(env, member ? "member" : "anon");
|
|
543
562
|
const prev = typeof body?.prev === "string" ? body.prev.slice(0, 800) : undefined;
|
|
544
563
|
const rawHistory = Array.isArray(body?.history) ? body.history : [];
|
|
545
564
|
const history = rawHistory
|
|
@@ -586,7 +605,7 @@ async function handleAsk(
|
|
|
586
605
|
let nameplate: Awaited<ReturnType<typeof extractNameplate>> | null = null;
|
|
587
606
|
if (effectiveImage && /certificate|certified|certification/i.test(q.query)) {
|
|
588
607
|
mark("Reading the nameplate photograph");
|
|
589
|
-
nameplate = await extractNameplate((env as any).AI,
|
|
608
|
+
nameplate = await extractNameplate((env as any).AI, roleModel(env, "member"), effectiveImage).catch(() => null);
|
|
590
609
|
if (nameplate?.manufacturer) {
|
|
591
610
|
mark(`Nameplate read: ${nameplate.manufacturer}${nameplate.model ? ` ${nameplate.model}` : ""}`);
|
|
592
611
|
}
|
|
@@ -596,7 +615,7 @@ async function handleAsk(
|
|
|
596
615
|
// continuity block (below) instead of silently dropped
|
|
597
616
|
const budget = num(env as any, "INPUT_TOKEN_BUDGET", LIMITS.inputTokenBudget);
|
|
598
617
|
const { kept: keptHistory, overflow } = splitHistory(history, budget);
|
|
599
|
-
const summary = overflow.length >= 2 ? ((await summarizeHistory(env,
|
|
618
|
+
const summary = overflow.length >= 2 ? ((await summarizeHistory(env, roleModel(env, "understand"), overflow)) ?? undefined) : undefined;
|
|
600
619
|
let retrieved;
|
|
601
620
|
// fresh (regenerate) skips the cache read; contextual follow-ups,
|
|
602
621
|
// declared-context asks, draft asks and image asks skip the cache
|
|
@@ -634,7 +653,7 @@ async function handleAsk(
|
|
|
634
653
|
const finishLine = (message: string) => {
|
|
635
654
|
if (live) {
|
|
636
655
|
live!.send({ type: "token", v: message });
|
|
637
|
-
live!.send({ type: "done", model
|
|
656
|
+
live!.send({ type: "done", model, query_hash: "", context_applied: NO_CONTEXT });
|
|
638
657
|
live!.close();
|
|
639
658
|
return null;
|
|
640
659
|
}
|
|
@@ -662,7 +681,7 @@ async function handleAsk(
|
|
|
662
681
|
if (live) {
|
|
663
682
|
live!.send({ type: "citations", citations: cached.value.citations ?? [], quota, context_applied: cctx, ...(cached.value.source_quality ? { source_quality: cached.value.source_quality, confidence_note: cached.value.confidence_note ?? null, ...(cached.value.experimental_sources ? { experimental_sources: cached.value.experimental_sources } : {}), ...(cached.value.entailment ? { entailment: cached.value.entailment } : {}) } : {}) });
|
|
664
683
|
live!.send({ type: "token", v: cached.value.answer ?? "" });
|
|
665
|
-
live!.send({ type: "done", model: cached.value.model ??
|
|
684
|
+
live!.send({ type: "done", model: cached.value.model ?? model, query_hash: cached.value.query_hash, served_from: "cache", context_applied: cctx });
|
|
666
685
|
live!.close();
|
|
667
686
|
return null;
|
|
668
687
|
}
|
|
@@ -904,12 +923,12 @@ let convEntities: Array<{ entity: string; kind: string }> = [];
|
|
|
904
923
|
registerBlock = block;
|
|
905
924
|
aggregateNoteText = aggregateNote(agg);
|
|
906
925
|
const queryHash = await sha256Hex(q.query);
|
|
907
|
-
telemetry(env, ctx, tier, "ask",
|
|
926
|
+
telemetry(env, ctx, tier, "ask", model, true, answer!.length, queryHash, q.lang, undefined, telemetryMeta());
|
|
908
927
|
const tq = await chargeAnswerTokens(env, bucketId, undefined, q.query.length, answer!.length, keyDayLimit);
|
|
909
928
|
const payload = {
|
|
910
929
|
answer,
|
|
911
930
|
citations: [{ docidentifier: `${P().publisher.name}-CS certificate register (family ${agg.family})`, corpus: "register" }],
|
|
912
|
-
model
|
|
931
|
+
model,
|
|
913
932
|
query_hash: queryHash,
|
|
914
933
|
follow_ups: [] as string[],
|
|
915
934
|
blocks: [block],
|
|
@@ -921,7 +940,7 @@ let convEntities: Array<{ entity: string; kind: string }> = [];
|
|
|
921
940
|
if (live) {
|
|
922
941
|
live!.send({ type: "citations", citations: payload.citations, quota: payload.quota, context_applied: NO_CONTEXT });
|
|
923
942
|
live!.send({ type: "token", v: answer });
|
|
924
|
-
live!.send({ type: "done", model
|
|
943
|
+
live!.send({ type: "done", model, query_hash: queryHash, blocks: [block], follow_ups: [], context_applied: NO_CONTEXT, read: readAs() });
|
|
925
944
|
live!.send({ type: "quota", quota: payload.quota });
|
|
926
945
|
live!.close();
|
|
927
946
|
return null;
|
|
@@ -1024,7 +1043,7 @@ let convEntities: Array<{ entity: string; kind: string }> = [];
|
|
|
1024
1043
|
return null;
|
|
1025
1044
|
}
|
|
1026
1045
|
let answer = await generateOnce(env, model, messages, effort);
|
|
1027
|
-
if (answer === null) answer = await generateOnce(env,
|
|
1046
|
+
if (answer === null) answer = await generateOnce(env, roleModel(env, "fallback"), messages, effort);
|
|
1028
1047
|
if (answer === null) {
|
|
1029
1048
|
telemetry(env, ctx, tier, "ask", model, false, 0, queryHash, q.lang, undefined, telemetryMeta());
|
|
1030
1049
|
return err(502, "generation_failed", "The generation model is unavailable; please retry.");
|
|
@@ -1468,7 +1487,7 @@ let convEntities: Array<{ entity: string; kind: string }> = [];
|
|
|
1468
1487
|
})();
|
|
1469
1488
|
if (retrieved.hits.length >= 4 && (member || understanding?.complexity === "complex")) {
|
|
1470
1489
|
const tl = Date.now();
|
|
1471
|
-
const reordered = await listwiseRerank(env,
|
|
1490
|
+
const reordered = await listwiseRerank(env, roleModel(env, "listwise"), understanding?.standalone_query || q.query, retrieved.hits);
|
|
1472
1491
|
stageTiming.listwise = Date.now() - tl;
|
|
1473
1492
|
if (reordered) {
|
|
1474
1493
|
console.log("listwise: reordered", reordered[0]?.metadata?.docidentifier ?? "?", "to top");
|
|
@@ -1760,7 +1779,12 @@ let convEntities: Array<{ entity: string; kind: string }> = [];
|
|
|
1760
1779
|
const cites = escalateAnswer ? escalationCitation() : [...registerCitation, ...(boundModel ? [modelCitation(boundModel), ...citations(usedHits)] : citations(usedHits))];
|
|
1761
1780
|
|
|
1762
1781
|
if (live) {
|
|
1763
|
-
|
|
1782
|
+
// the streamed lane gets the same fallback diversity as the JSON
|
|
1783
|
+
// lane: when the primary's stream cannot be established after its
|
|
1784
|
+
// retry, one attempt on the fallback model (text-only — the image
|
|
1785
|
+
// parts are flattened first) before the honest unavailable line
|
|
1786
|
+
const stream = (await generateStream(env, model, messages, routeEffort(routed.route)))
|
|
1787
|
+
?? (await generateStream(env, roleModel(env, "fallback"), flattenForTextModel(messages), routeEffort(routed.route)));
|
|
1764
1788
|
if (stream) {
|
|
1765
1789
|
const send = (obj: unknown) => live!.send(obj);
|
|
1766
1790
|
// the agent trace arrives first: every questioning round the
|
|
@@ -2025,7 +2049,7 @@ let convEntities: Array<{ entity: string; kind: string }> = [];
|
|
|
2025
2049
|
// the streamed lane's generation is unavailable — the line goes
|
|
2026
2050
|
// out on the already-open SSE; the json lane never enters this block
|
|
2027
2051
|
live!.send({ type: "token", v: "The generation model is unavailable; please retry." });
|
|
2028
|
-
live!.send({ type: "done", model
|
|
2052
|
+
live!.send({ type: "done", model, query_hash: "", context_applied: NO_CONTEXT });
|
|
2029
2053
|
live!.close();
|
|
2030
2054
|
return null;
|
|
2031
2055
|
}
|
|
@@ -2043,7 +2067,7 @@ let convEntities: Array<{ entity: string; kind: string }> = [];
|
|
|
2043
2067
|
if (ablate?.speculative) {
|
|
2044
2068
|
const spec = await speculativeDraftVerify(env, {
|
|
2045
2069
|
query: q.query, hits: usedHits, lang: q.lang,
|
|
2046
|
-
draftModel:
|
|
2070
|
+
draftModel: roleModel(env, "member"), verifierModel: roleModel(env, "verifier"),
|
|
2047
2071
|
}).catch((e: unknown) => {
|
|
2048
2072
|
console.log("speculative: failed, falling through —", String(e).slice(0, 120));
|
|
2049
2073
|
return null;
|
|
@@ -2057,24 +2081,10 @@ let convEntities: Array<{ entity: string; kind: string }> = [];
|
|
|
2057
2081
|
if (!answer) answer = await generateOnce(env, model, messages, routeEffort(routed.route));
|
|
2058
2082
|
if (answer === null) {
|
|
2059
2083
|
generateRetries += 1;
|
|
2060
|
-
// the fallback is a text-only model: image parts
|
|
2061
|
-
//
|
|
2062
|
-
|
|
2063
|
-
|
|
2064
|
-
// images gets ANSWERED ("I don't have access to the original
|
|
2065
|
-
// image…") instead of the question (observed in the wild). The
|
|
2066
|
-
// user-image message keeps its text (the question) minus its note.
|
|
2067
|
-
const isFigureAttachMessage = (m: any) =>
|
|
2068
|
-
Array.isArray(m.content) &&
|
|
2069
|
-
m.content.some((part: any) => part?.type === "text" && /^The original image of figure unit /.test(part.text ?? ""));
|
|
2070
|
-
const flat = messages
|
|
2071
|
-
.filter((m: any) => !isFigureAttachMessage(m))
|
|
2072
|
-
.map((m: any) =>
|
|
2073
|
-
typeof m.content === "string"
|
|
2074
|
-
? m
|
|
2075
|
-
: { ...m, content: m.content.filter((p: any) => p?.type === "text").map((p: any) => (p?.text ?? "").replace(/\n?\(The user attached an image with this question; interpret it directly when answering\.\)/, "")).join("\n") },
|
|
2076
|
-
);
|
|
2077
|
-
answer = await generateOnce(env, MODELS.fallback, flat, routeEffort(routed.route));
|
|
2084
|
+
// the fallback is a text-only model: flatten the image parts first
|
|
2085
|
+
// (and the figure-attach NOTE with them)
|
|
2086
|
+
const flat = flattenForTextModel(messages);
|
|
2087
|
+
answer = await generateOnce(env, roleModel(env, "fallback"), flat, routeEffort(routed.route));
|
|
2078
2088
|
}
|
|
2079
2089
|
if (answer === null) {
|
|
2080
2090
|
// both generations failed — the json lane returns the error shape; the
|
|
@@ -2315,7 +2325,7 @@ let convEntities: Array<{ entity: string; kind: string }> = [];
|
|
|
2315
2325
|
}
|
|
2316
2326
|
telemetryDecisions(env, ctx, tier, queryHash, decisionsOut ?? null, Date.now() - tStart);
|
|
2317
2327
|
}
|
|
2318
|
-
const out = { answer, citations: finalCites, ...(jsonQuality ? { source_quality: jsonQuality!, confidence_note: entailmentNote || qualityNote(jsonQuality!), ...(entailment ? { entailment } : {}), ...(jsonQuality === "ocr" ? { experimental_sources: experimentalSourceLabels(finalCites) } : {}) } : {}), model
|
|
2328
|
+
const out = { answer, citations: finalCites, ...(jsonQuality ? { source_quality: jsonQuality!, confidence_note: entailmentNote || qualityNote(jsonQuality!), ...(entailment ? { entailment } : {}), ...(jsonQuality === "ocr" ? { experimental_sources: experimentalSourceLabels(finalCites) } : {}) } : {}), model, query_hash: queryHash, follow_ups: refusalShaped(answer!, refusalScope(answerCites(answer!))) ? [] : (understanding?.follow_ups ?? []), blocks: [...c2ns.blocks, ...(verdictBlock ? [verdictBlock] : []), ...(conditionBlock ? [conditionBlock] : []), ...(aggregationBlock ? [aggregationBlock] : []), ...(registerBlock ? [registerBlock] : []), ...completionBlocks], context_applied: ctxApplied, ...(liveRecords ? { records: liveRecords } : {}), ...(decisionsOut ? { decisions: decisionsOut } : {}), ...(ablate ? { ablate } : {}), route: { route: routed.route, features: routed.features } };
|
|
2319
2329
|
const cacheable = !contextual && !declaredCtx && !ablate && !registerBypass && cacheableAnswer(answer!, refusalScope(answerCites(answer!))) && finalAnchors.violations.length === 0;
|
|
2320
2330
|
if (cacheable) {
|
|
2321
2331
|
const ck = exactCacheKey(env.INDEX_VERSION, gen, ns, await sha256Hex(cacheKeyMaterial(q.query, q.lang, salt)));
|
|
@@ -181,6 +181,19 @@ export const THRESHOLDS = {
|
|
|
181
181
|
/** Section-descent child discount — children fetched from a ranked
|
|
182
182
|
* depth-1 summary enter discounted. */
|
|
183
183
|
sectionDescentDiscount: 0.8,
|
|
184
|
+
/** Typed-pin label weight — for an object-seeking question (a stated
|
|
185
|
+
* value, a named table/figure/formula) a query term met in a unit's
|
|
186
|
+
* LABELS (caption, column headers, row labels) is worth this many
|
|
187
|
+
* body mentions. A blank report form mentions every term of the
|
|
188
|
+
* question and holds no answer: measured 2026-12-05 on the R 60
|
|
189
|
+
* family, the test-report symbol list scored 10 against the limits
|
|
190
|
+
* table's 8 and was pinned — the gate lost the class-B value. */
|
|
191
|
+
typedLabelWeight: 4,
|
|
192
|
+
/** Typed-pin clause completion — how many of the top-ranked prose
|
|
193
|
+
* clauses have their typed siblings (table/figure/formula under the
|
|
194
|
+
* same exact clause) fetched from D1, so the answering object is a
|
|
195
|
+
* candidate even when no retrieval lane surfaced it. */
|
|
196
|
+
typedSiblingProse: 5,
|
|
184
197
|
/** History budget share — the fraction of the context budget the
|
|
185
198
|
* conversation slice may consume; older turns overflow into the
|
|
186
199
|
* compacted summary instead of starving the passages. */
|
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
// bound, and the gate's noul clears decisionsGateMin.
|
|
6
6
|
import { portModelRunner } from "./env.ts";
|
|
7
7
|
import { telemetry } from "./quota";
|
|
8
|
-
import { MODELS, THRESHOLDS } from "./config.ts";
|
|
8
|
+
import { MODELS, THRESHOLDS, roleModel } from "./config.ts";
|
|
9
9
|
import {
|
|
10
10
|
buildDecisionQuestions, matchAnswers, parseDerivation,
|
|
11
11
|
assembleSection, type DecisionItem, type DecisionMode,
|
|
@@ -74,7 +74,7 @@ export async function runDecisionPass(
|
|
|
74
74
|
if (!passages.length) return null;
|
|
75
75
|
try {
|
|
76
76
|
// 1. derive the checklist candidates from the used passages
|
|
77
|
-
const deriveModel = (env as any).DECISIONS_EXTRACT_MODEL ||
|
|
77
|
+
const deriveModel = (env as any).DECISIONS_EXTRACT_MODEL || roleModel(env, "member");
|
|
78
78
|
const derived = await portModelRunner(env).run({
|
|
79
79
|
model: deriveModel,
|
|
80
80
|
messages: [
|
|
@@ -129,7 +129,7 @@ async function memoriesRoute(c: RouteContext): Promise<Response> {
|
|
|
129
129
|
}
|
|
130
130
|
|
|
131
131
|
function userDocumentPorts(env: Env): UserDocumentPorts {
|
|
132
|
-
return { store: cfStore(env.DB), blobs: cfBlobs(env.USER_DOCS), lane: cfVectorIndex(env.USER_DOCS_INDEX), model: cfModelRunner(env.AI) };
|
|
132
|
+
return { store: cfStore(env.DB), blobs: cfBlobs(env.USER_DOCS), lane: cfVectorIndex(env.USER_DOCS_INDEX), model: cfModelRunner(env.AI), answerModel: roleModel(env, "member") };
|
|
133
133
|
}
|
|
134
134
|
|
|
135
135
|
async function userDocumentsRoute(c: RouteContext): Promise<Response> {
|
|
@@ -8,7 +8,6 @@
|
|
|
8
8
|
// rides its OWN short user message, never a long passage.
|
|
9
9
|
import nameplatePrompt from "../prompts/nameplate.md";
|
|
10
10
|
import { parseNameplate, nameplateRegisterQuery, type Nameplate } from "./nameplate-parse.ts";
|
|
11
|
-
import { MODELS } from "./config.ts";
|
|
12
11
|
|
|
13
12
|
export type { Nameplate };
|
|
14
13
|
export { nameplateRegisterQuery };
|
|
@@ -59,5 +58,3 @@ export async function extractNameplate(ai: any, model: string, image: string): P
|
|
|
59
58
|
}
|
|
60
59
|
return null; // the bridge is optional — the ask never depends on it
|
|
61
60
|
}
|
|
62
|
-
|
|
63
|
-
export const nameplateModel = () => MODELS.member;
|
|
@@ -7,7 +7,14 @@ import type { Background } from "./ports/runtime.ts";
|
|
|
7
7
|
export async function kvIncr(cache: KVNamespace, key: string, step = 1): Promise<number> {
|
|
8
8
|
const cur = Number((await cache.get(key)) ?? "0");
|
|
9
9
|
const next = cur + step;
|
|
10
|
-
|
|
10
|
+
// Cloudflare KV rate-limits writes to the same key to 1/s (429 Too Many
|
|
11
|
+
// Requests). Fail open on a rejected counter write so rapid back-to-back
|
|
12
|
+
// requests (e.g. /mcp tool calls) never 500 on telemetry/quota accounting.
|
|
13
|
+
try {
|
|
14
|
+
await cache.put(key, String(next), { expirationTtl: 90000 });
|
|
15
|
+
} catch (e) {
|
|
16
|
+
console.error("kvIncr: put failed —", String(e).slice(0, 120));
|
|
17
|
+
}
|
|
11
18
|
return next;
|
|
12
19
|
}
|
|
13
20
|
|
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
import { err, json, corsHeaders, readJson, validateQuery } from "./lib/http";
|
|
4
4
|
import { portModelRunner } from "./env.ts";
|
|
5
5
|
import { telemetry } from "./quota";
|
|
6
|
-
import { LIMITS,
|
|
6
|
+
import { LIMITS, sha256Hex, roleModel } from "./config";
|
|
7
7
|
import { retrieve, buildMessages, citations } from "./pipeline";
|
|
8
8
|
import { understandQuery } from "./understand";
|
|
9
9
|
import { generateOnce } from "./ai";
|
|
@@ -75,7 +75,7 @@ async function run(
|
|
|
75
75
|
): Promise<{ answer: string; citations: unknown[]; model: string; query_hash: string; research: { iterations: number; passages: number; elapsed_ms: number; sufficient: boolean | null } }> {
|
|
76
76
|
const started = Date.now();
|
|
77
77
|
const queryHash = await sha256Hex(q.query);
|
|
78
|
-
const understanding = await understandQuery(portModelRunner(env),
|
|
78
|
+
const understanding = await understandQuery(portModelRunner(env), roleModel(env, "understand"), q.query, [], []);
|
|
79
79
|
const graphDocNumbers = await graphExpand(env, understanding);
|
|
80
80
|
const eNote = await editionNote(env, understanding);
|
|
81
81
|
|
|
@@ -114,7 +114,7 @@ async function run(
|
|
|
114
114
|
: "";
|
|
115
115
|
judge = await (async () => {
|
|
116
116
|
try {
|
|
117
|
-
const res: any = await env.AI.run(
|
|
117
|
+
const res: any = await env.AI.run(roleModel(env, "grader"), {
|
|
118
118
|
messages: [
|
|
119
119
|
{ role: "system", content: fill(researchPromptText, promptVars()).trimEnd() },
|
|
120
120
|
{ role: "user", content: `Research question: ${q.query}\n\n${digest}Collected passages (${recent.length}):\n${recent.map((h, n) => `[${n + 1}] ${h.metadata.docidentifier ?? ""} §${h.metadata.clause_anchor ?? ""}: ${h.text.slice(0, 700)}`).join("\n")}` },
|
|
@@ -159,10 +159,11 @@ async function run(
|
|
|
159
159
|
throw new Error("Search is briefly busy — please retry in a moment.");
|
|
160
160
|
}
|
|
161
161
|
const { messages, usedHits } = buildMessages(q.query, used, q.lang, [], eNote || undefined, undefined, LIMITS.inputTokenBudget);
|
|
162
|
-
|
|
163
|
-
|
|
162
|
+
const researchModel = roleModel(env, "research");
|
|
163
|
+
let answer = await generateOnce(env, researchModel, messages);
|
|
164
|
+
if (answer === null) answer = await generateOnce(env, roleModel(env, "fallback"), messages);
|
|
164
165
|
if (answer === null) {
|
|
165
|
-
telemetry(env, ctx, "member", "research",
|
|
166
|
+
telemetry(env, ctx, "member", "research", researchModel, false, 0, queryHash, q.lang);
|
|
166
167
|
throw new Error("The generation model is unavailable; please retry.");
|
|
167
168
|
}
|
|
168
169
|
answer = canonicalRefusal(answer, { cited: /\[[^\]]+\]/.test(answer), conversational: false });
|
|
@@ -171,11 +172,11 @@ async function run(
|
|
|
171
172
|
const out = {
|
|
172
173
|
answer,
|
|
173
174
|
citations: citations(usedHits),
|
|
174
|
-
model:
|
|
175
|
+
model: researchModel,
|
|
175
176
|
query_hash: queryHash,
|
|
176
177
|
research: { iterations, passages: used.length, elapsed_ms: Date.now() - started, sufficient: judge?.sufficient ?? null },
|
|
177
178
|
};
|
|
178
|
-
telemetry(env, ctx, "member", "research",
|
|
179
|
+
telemetry(env, ctx, "member", "research", researchModel, true, answer.length, queryHash, q.lang);
|
|
179
180
|
emit?.({ type: "pass", n: iterations, of: maxIters, phase: "writing", passages: used.length });
|
|
180
181
|
return out;
|
|
181
182
|
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// Passage search: retrieval without generation (TODO.impl/23).
|
|
2
|
-
import { LIMITS, MODELS, num, sha256Hex } from "./config";
|
|
2
|
+
import { LIMITS, MODELS, num, sha256Hex, roleModel } from "./config";
|
|
3
3
|
import { portModelRunner } from "./env.ts";
|
|
4
4
|
import type { Background } from "./ports/runtime.ts";
|
|
5
5
|
import { retrieve } from "./pipeline";
|
|
@@ -31,7 +31,7 @@ export async function handleSearch(
|
|
|
31
31
|
return err(429, "quota_exceeded", `Daily search limit reached (${quota.limit}). Try again tomorrow.`);
|
|
32
32
|
}
|
|
33
33
|
|
|
34
|
-
const understanding = await understandQuery(portModelRunner(env),
|
|
34
|
+
const understanding = await understandQuery(portModelRunner(env), roleModel(env, "understand"), q.query, []);
|
|
35
35
|
const graphDocNumbers = await graphExpand(env, understanding);
|
|
36
36
|
// the license entitlement set rides the body exactly as it does on the
|
|
37
37
|
// ask path (TODO.external-refs/08): request-scoped, whitelist-validated,
|
|
@@ -109,27 +109,15 @@ export const sectionDescent: Stage = {
|
|
|
109
109
|
.map((s) => s.trim())
|
|
110
110
|
.filter(Boolean)
|
|
111
111
|
.slice(0, 25);
|
|
112
|
-
if (kids.length) {
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
},
|
|
122
|
-
});
|
|
123
|
-
const childHits = (cv.matches ?? [])
|
|
124
|
-
.filter((m: any) => !m.metadata?.section_summary)
|
|
125
|
-
.map((m: any) => ({
|
|
126
|
-
id: m.id,
|
|
127
|
-
score: m.score * THRESHOLDS.sectionDescentDiscount,
|
|
128
|
-
metadata: m.metadata as ChunkMeta,
|
|
129
|
-
text: (m.metadata?.chunk_text as string) ?? "",
|
|
130
|
-
}))
|
|
131
|
-
.filter((x: Hit) => !c.finalHits.some((h) => h.id === x.id))
|
|
132
|
-
.slice(0, 2);
|
|
112
|
+
if (kids.length && c.env.DB) {
|
|
113
|
+
// Read child clauses from D1 directly (same as level 2 above): Vectorize
|
|
114
|
+
// rejects $and arrays (40026) and does not index doc_id / clause_anchor.
|
|
115
|
+
const order = new Map(kids.map((a, i) => [a, i]));
|
|
116
|
+
const childHits = (await clausesOf(c.env, String(sectionHit.metadata.doc_id), kids, 6))
|
|
117
|
+
.filter((x) => !x.metadata?.section_summary && !c.finalHits.some((h) => h.id === x.id))
|
|
118
|
+
.sort((a, b) => (order.get(String(a.metadata.clause_anchor ?? "")) ?? 99) - (order.get(String(b.metadata.clause_anchor ?? "")) ?? 99))
|
|
119
|
+
.slice(0, 2)
|
|
120
|
+
.map((x) => ({ ...x, score: sectionHit.score * THRESHOLDS.sectionDescentDiscount }));
|
|
133
121
|
if (childHits.length) {
|
|
134
122
|
c.finalHits = [...c.finalHits.filter((h) => h !== sectionHit), ...childHits];
|
|
135
123
|
console.log(
|