@konneal/engine 0.2.190 → 0.2.191

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.
@@ -1,9 +1,9 @@
1
1
  import {
2
2
  handleAsk
3
- } from "./chunk-WRSUXIS7.js";
3
+ } from "./chunk-SWCKO4OB.js";
4
4
  import "./chunk-IRCDOFP4.js";
5
5
  import "./chunk-ECNBEZGK.js";
6
- import "./chunk-Q7QL3457.js";
6
+ import "./chunk-3SGGVZZ4.js";
7
7
  import "./chunk-AVNHVFEB.js";
8
8
  import "./chunk-GJQT4IMD.js";
9
9
  import "./chunk-ETLSWSZ7.js";
@@ -14,6 +14,7 @@ import {
14
14
  generationSampling,
15
15
  num,
16
16
  processExpansion,
17
+ roleModel,
17
18
  sha256Hex,
18
19
  today
19
20
  } from "./chunk-22WB6IVC.js";
@@ -23007,7 +23008,7 @@ Which of these figures best answers the question? Reply with ONLY: {"pick": N} u
23007
23008
  }
23008
23009
  if (!kept.length) return;
23009
23010
  const raced = await Promise.race([
23010
- portModelRunner(c.env).run({ model: MODELS.vlmFigure, messages: [{ role: "user", content }], maxTokens: 256, effort: "low" }),
23011
+ portModelRunner(c.env).run({ model: roleModel(c.env, "vlmFigure"), messages: [{ role: "user", content }], maxTokens: 256, effort: "low" }),
23011
23012
  new Promise((r) => setTimeout(() => r(null), 15e3))
23012
23013
  ]);
23013
23014
  const pick = parsePick(raced?.text ?? raced, kept.length);
@@ -23375,7 +23376,7 @@ var typedPin = {
23375
23376
  return new Set(pinFamily ? [pinFamily.split("-")[0]] : [...glossaryFamilies]).size > 0;
23376
23377
  },
23377
23378
  run: async (c) => {
23378
- const { query, filters, u, glossary: glossary2, hits, env, vector } = c;
23379
+ const { query, filters, u, glossary: glossary2, hits, env } = c;
23379
23380
  const glossaryFamilies = /* @__PURE__ */ new Set();
23380
23381
  for (const g of glossary2) if (g.doc_number) glossaryFamilies.add(g.doc_number.split("-")[0]);
23381
23382
  const pinFamily = filters?.doc_number ?? u?.doc_number ?? null;
@@ -23400,16 +23401,20 @@ var typedPin = {
23400
23401
  const parentPresent = c.finalHits.some(
23401
23402
  (h) => h.metadata.doc_id === docId && h.metadata.clause_anchor === anchor && !h.metadata.unit_id
23402
23403
  );
23403
- if (anchor && docId && !parentPresent) {
23404
+ if (anchor && docId && !parentPresent && env.DB) {
23404
23405
  try {
23405
- const pv = await env.VECTORIZE.query(vector, {
23406
- topK: 4,
23407
- returnMetadata: "all",
23408
- filter: { $and: [{ doc_id: { $eq: docId } }, { clause_anchor: { $eq: anchor } }] }
23409
- });
23410
- const parent = (pv.matches ?? []).map((m) => ({ id: m.id, score: m.score, metadata: m.metadata, text: m.metadata?.chunk_text ?? "" })).find((h) => !h.metadata?.unit_id);
23411
- if (parent && !c.finalHits.some((h) => h.id === parent.id)) {
23412
- c.finalHits = [...c.finalHits, { ...parent, score: parent.score * THRESHOLDS.smallToBigDiscount }];
23406
+ const res = await env.DB.prepare(
23407
+ "SELECT id, doc_id, docidentifier, doctype, doc_number, edition, language, clause_anchor, clause_title, status, superseded_by, corpus, tier, text, unit_id, block FROM chunks WHERE doc_id = ?1 AND clause_anchor = ?2 AND (unit_id IS NULL OR unit_id = '') LIMIT 2"
23408
+ ).bind(docId, anchor).all();
23409
+ const row = (res.results ?? [])[0];
23410
+ if (row && !c.finalHits.some((h) => h.id === String(row.id))) {
23411
+ const parent = {
23412
+ id: String(row.id),
23413
+ score: typed.score * THRESHOLDS.smallToBigDiscount,
23414
+ metadata: { ...row, unit_id: void 0, block: row.block || void 0 },
23415
+ text: String(row.text ?? "")
23416
+ };
23417
+ c.finalHits = [...c.finalHits, parent];
23413
23418
  console.log("small-to-big: parent \xA7", anchor, "of", typed.metadata.docidentifier, "added");
23414
23419
  }
23415
23420
  } catch {
@@ -23486,23 +23491,9 @@ var sectionDescent = {
23486
23491
  return;
23487
23492
  }
23488
23493
  const kids = sectionHit.metadata.child_anchors.split(",").map((s8) => s8.trim()).filter(Boolean).slice(0, 25);
23489
- if (kids.length) {
23490
- const cv = await c.env.VECTORIZE.query(c.vector, {
23491
- topK: 3,
23492
- returnMetadata: "all",
23493
- filter: {
23494
- $and: [
23495
- { doc_id: { $eq: sectionHit.metadata.doc_id } },
23496
- { clause_anchor: { $in: kids } }
23497
- ]
23498
- }
23499
- });
23500
- const childHits = (cv.matches ?? []).filter((m) => !m.metadata?.section_summary).map((m) => ({
23501
- id: m.id,
23502
- score: m.score * THRESHOLDS.sectionDescentDiscount,
23503
- metadata: m.metadata,
23504
- text: m.metadata?.chunk_text ?? ""
23505
- })).filter((x) => !c.finalHits.some((h) => h.id === x.id)).slice(0, 2);
23494
+ if (kids.length && c.env.DB) {
23495
+ const order = new Map(kids.map((a, i) => [a, i]));
23496
+ const childHits = (await clausesOf(c.env, String(sectionHit.metadata.doc_id), kids, 6)).filter((x) => !x.metadata?.section_summary && !c.finalHits.some((h) => h.id === x.id)).sort((a, b) => (order.get(String(a.metadata.clause_anchor ?? "")) ?? 99) - (order.get(String(b.metadata.clause_anchor ?? "")) ?? 99)).slice(0, 2).map((x) => ({ ...x, score: sectionHit.score * THRESHOLDS.sectionDescentDiscount }));
23506
23497
  if (childHits.length) {
23507
23498
  c.finalHits = [...c.finalHits.filter((h) => h !== sectionHit), ...childHits];
23508
23499
  console.log(
@@ -24886,7 +24877,11 @@ async function understandQuery(ai, model, query, history, entities = []) {
24886
24877
  async function kvIncr(cache, key, step = 1) {
24887
24878
  const cur = Number(await cache.get(key) ?? "0");
24888
24879
  const next = cur + step;
24889
- await cache.put(key, String(next), { expirationTtl: 9e4 });
24880
+ try {
24881
+ await cache.put(key, String(next), { expirationTtl: 9e4 });
24882
+ } catch (e) {
24883
+ console.error("kvIncr: put failed \u2014", String(e).slice(0, 120));
24884
+ }
24890
24885
  return next;
24891
24886
  }
24892
24887
  function clientIp(req) {
@@ -6,7 +6,7 @@ import {
6
6
  sessionFrom,
7
7
  telemetry,
8
8
  understandQuery
9
- } from "./chunk-Q7QL3457.js";
9
+ } from "./chunk-3SGGVZZ4.js";
10
10
  import {
11
11
  corsHeaders,
12
12
  err,
@@ -22,6 +22,7 @@ import {
22
22
  LIMITS,
23
23
  MODELS,
24
24
  num,
25
+ roleModel,
25
26
  sha256Hex
26
27
  } from "./chunk-22WB6IVC.js";
27
28
  import {
@@ -40,7 +41,7 @@ async function handleSearch(env, ctx, req, tier, key) {
40
41
  if (!quota.ok) {
41
42
  return err(429, "quota_exceeded", `Daily search limit reached (${quota.limit}). Try again tomorrow.`);
42
43
  }
43
- const understanding = await understandQuery(portModelRunner(env), MODELS.understand, q.query, []);
44
+ const understanding = await understandQuery(portModelRunner(env), roleModel(env, "understand"), q.query, []);
44
45
  const graphDocNumbers = await graphExpand(env, understanding);
45
46
  const standardKeys = entitlementScope(standardKeysFrom(body));
46
47
  let retrieved;
@@ -77,7 +77,7 @@ import {
77
77
  tokenBudget,
78
78
  understandQuery,
79
79
  usageTotal
80
- } from "./chunk-Q7QL3457.js";
80
+ } from "./chunk-3SGGVZZ4.js";
81
81
  import {
82
82
  CAPACITY_PAUSE_MS,
83
83
  embed,
@@ -1622,7 +1622,7 @@ async function runDecisionPass(env, opts) {
1622
1622
  const passages = opts.passages.filter(Boolean).slice(0, 8).map((p) => p.slice(0, 1600));
1623
1623
  if (!passages.length) return null;
1624
1624
  try {
1625
- const deriveModel = env.DECISIONS_EXTRACT_MODEL || MODELS.member;
1625
+ const deriveModel = env.DECISIONS_EXTRACT_MODEL || roleModel(env, "member");
1626
1626
  const derived = await portModelRunner(env).run({
1627
1627
  model: deriveModel,
1628
1628
  messages: [
@@ -1793,13 +1793,13 @@ async function processImport(ports, row, mime, bytes) {
1793
1793
  return;
1794
1794
  }
1795
1795
  } else {
1796
- text = await visionTranscribe(ports.model, mime, bytes);
1796
+ text = await visionTranscribe(ports.model, mime, bytes, ports.answerModel ?? MODELS.member);
1797
1797
  if (!text || text.replace(/\s+/g, "").length < 20) {
1798
1798
  await setStatus("failed", null, "The vision lane could not read this image. Try a sharper photo.");
1799
1799
  return;
1800
1800
  }
1801
1801
  }
1802
- const extraction = await structureDocument(ports.model, row.name, mime, text);
1802
+ const extraction = await structureDocument(ports.model, row.name, mime, text, ports.answerModel ?? MODELS.member);
1803
1803
  const fieldsLine = Object.entries(extraction.fields).map(([k, v]) => `${k}: ${v}`).join("; ");
1804
1804
  const chunkText = `Member document (${extraction.kind}) \u2014 ${row.name}. ${fieldsLine}. ${extraction.summary}
1805
1805
 
@@ -1837,13 +1837,13 @@ ${extraction.text.slice(0, 8e3)}`;
1837
1837
  function extractKind(fields) {
1838
1838
  return fields.kind || "other";
1839
1839
  }
1840
- async function visionTranscribe(model, mime, bytes) {
1840
+ async function visionTranscribe(model, mime, bytes, modelId) {
1841
1841
  let binary = "";
1842
1842
  const CHUNK = 32768;
1843
1843
  for (let i = 0; i < bytes.length; i += CHUNK) binary += String.fromCharCode(...bytes.subarray(i, i + CHUNK));
1844
1844
  const dataUrl = `data:${mime};base64,${btoa(binary)}`;
1845
1845
  const res = await model.run({
1846
- model: MODELS.member,
1846
+ model: modelId,
1847
1847
  messages: [
1848
1848
  { role: "system", content: "Transcribe everything you can read in this document image \u2014 certificate numbers, holders, models, values, dates, clause references. Transcribe first; organize nothing." },
1849
1849
  { role: "user", content: [{ type: "image_url", image_url: { url: dataUrl } }] }
@@ -1854,9 +1854,9 @@ async function visionTranscribe(model, mime, bytes) {
1854
1854
  });
1855
1855
  return res.text ?? "";
1856
1856
  }
1857
- async function structureDocument(model, name, mime, text) {
1857
+ async function structureDocument(model, name, mime, text, modelId) {
1858
1858
  const res = await model.run({
1859
- model: MODELS.member,
1859
+ model: modelId,
1860
1860
  messages: [
1861
1861
  { role: "system", content: `You classify and structure an imported metrology document. Answer with ONE JSON object: {"kind": "certificate"|"test_report"|"other", "fields": {\u2026short typed fields\u2026}, "summary": "one paragraph a retrieval engine can answer from"}. Certificates carry certificate numbers (like R60/2021-XX1-24.01), holders, models, issue dates. Test reports carry measured values, uncertainties, instruments, clause references. Fields use snake_case names, values verbatim from the text. Never invent a value the text does not carry.` },
1862
1862
  { role: "user", content: `Document name: ${name}
@@ -2360,6 +2360,12 @@ async function generateStream(env, model, messages, effort) {
2360
2360
  }
2361
2361
  return null;
2362
2362
  }
2363
+ function flattenForTextModel(messages) {
2364
+ const isFigureAttachMessage = (m) => Array.isArray(m.content) && m.content.some((part) => part?.type === "text" && /^The original image of figure unit /.test(part.text ?? ""));
2365
+ return messages.filter((m) => !isFigureAttachMessage(m)).map(
2366
+ (m) => typeof m.content === "string" ? m : { ...m, content: m.content.filter((p) => p?.type === "text").map((p) => (p?.text ?? "").replace(/\n?\(The user attached an image with this question; interpret it directly when answering\.\)/, "")).join("\n") }
2367
+ );
2368
+ }
2363
2369
  async function summarizeHistory(env, model, turns) {
2364
2370
  try {
2365
2371
  const convo = turns.map((t) => `${t.role === "user" ? "User" : "Assistant"}: ${t.content.slice(0, 1200)}`).join("\n").slice(0, 24e3);
@@ -2532,7 +2538,7 @@ async function handleAsk(env, ctx, req, tier, key) {
2532
2538
  const federate = (member || keyLicensed) && service && isoOn ? (q2) => retrieveInternal(service, fedAuth, q2) : void 0;
2533
2539
  const userDocs = member && env.USER_DOCS_INDEX ? (q2) => queryUserLane(cfModelRunner(env.AI), cfVectorIndex(env.USER_DOCS_INDEX), member.sub, q2, THRESHOLDS.userLaneK) : void 0;
2534
2540
  const ns = tier === "key" ? `k:${key.id}` : member ? `m:${member.sub}` : "anon";
2535
- const model = member ? MODELS.member : MODELS.anon;
2541
+ const model = roleModel(env, member ? "member" : "anon");
2536
2542
  const prev = typeof body?.prev === "string" ? body.prev.slice(0, 800) : void 0;
2537
2543
  const rawHistory = Array.isArray(body?.history) ? body.history : [];
2538
2544
  const history = rawHistory.filter((h) => (h?.role === "user" || h?.role === "assistant") && typeof h?.content === "string" && h.content.trim()).slice(-24).map((h) => ({ role: h.role, content: h.content.slice(0, 4e3) }));
@@ -2561,14 +2567,14 @@ async function handleAsk(env, ctx, req, tier, key) {
2561
2567
  let nameplate = null;
2562
2568
  if (effectiveImage && /certificate|certified|certification/i.test(q.query)) {
2563
2569
  mark("Reading the nameplate photograph");
2564
- nameplate = await extractNameplate(env.AI, MODELS.member, effectiveImage).catch(() => null);
2570
+ nameplate = await extractNameplate(env.AI, roleModel(env, "member"), effectiveImage).catch(() => null);
2565
2571
  if (nameplate?.manufacturer) {
2566
2572
  mark(`Nameplate read: ${nameplate.manufacturer}${nameplate.model ? ` ${nameplate.model}` : ""}`);
2567
2573
  }
2568
2574
  }
2569
2575
  const budget = num(env, "INPUT_TOKEN_BUDGET", LIMITS.inputTokenBudget);
2570
2576
  const { kept: keptHistory, overflow } = splitHistory(history, budget);
2571
- const summary = overflow.length >= 2 ? await summarizeHistory(env, MODELS.understand, overflow) ?? void 0 : void 0;
2577
+ const summary = overflow.length >= 2 ? await summarizeHistory(env, roleModel(env, "understand"), overflow) ?? void 0 : void 0;
2572
2578
  let retrieved;
2573
2579
  const fresh = freshRequested(body);
2574
2580
  const multiTurn = body?.multi_turn !== false;
@@ -2583,7 +2589,7 @@ async function handleAsk(env, ctx, req, tier, key) {
2583
2589
  const finishLine = (message) => {
2584
2590
  if (live2) {
2585
2591
  live2.send({ type: "token", v: message });
2586
- live2.send({ type: "done", model: MODELS.member, query_hash: "", context_applied: NO_CONTEXT });
2592
+ live2.send({ type: "done", model, query_hash: "", context_applied: NO_CONTEXT });
2587
2593
  live2.close();
2588
2594
  return null;
2589
2595
  }
@@ -2603,7 +2609,7 @@ async function handleAsk(env, ctx, req, tier, key) {
2603
2609
  if (live2) {
2604
2610
  live2.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 } : {} } : {} });
2605
2611
  live2.send({ type: "token", v: cached.value.answer ?? "" });
2606
- live2.send({ type: "done", model: cached.value.model ?? MODELS.member, query_hash: cached.value.query_hash, served_from: "cache", context_applied: cctx });
2612
+ live2.send({ type: "done", model: cached.value.model ?? model, query_hash: cached.value.query_hash, served_from: "cache", context_applied: cctx });
2607
2613
  live2.close();
2608
2614
  return null;
2609
2615
  }
@@ -2759,12 +2765,12 @@ Certificates are issued per recommendation family \u2014 the register carries no
2759
2765
  registerBlock = block;
2760
2766
  aggregateNoteText = aggregateNote(agg);
2761
2767
  const queryHash2 = await sha256Hex(q2.query);
2762
- telemetry(env, ctx, tier, "ask", MODELS.member, true, answer2.length, queryHash2, q2.lang, void 0, telemetryMeta());
2768
+ telemetry(env, ctx, tier, "ask", model, true, answer2.length, queryHash2, q2.lang, void 0, telemetryMeta());
2763
2769
  const tq2 = await chargeAnswerTokens(env, bucketId, void 0, q2.query.length, answer2.length, keyDayLimit);
2764
2770
  const payload = {
2765
2771
  answer: answer2,
2766
2772
  citations: [{ docidentifier: `${P().publisher.name}-CS certificate register (family ${agg.family})`, corpus: "register" }],
2767
- model: MODELS.member,
2773
+ model,
2768
2774
  query_hash: queryHash2,
2769
2775
  follow_ups: [],
2770
2776
  blocks: [block],
@@ -2776,7 +2782,7 @@ Certificates are issued per recommendation family \u2014 the register carries no
2776
2782
  if (live2) {
2777
2783
  live2.send({ type: "citations", citations: payload.citations, quota: payload.quota, context_applied: NO_CONTEXT });
2778
2784
  live2.send({ type: "token", v: answer2 });
2779
- live2.send({ type: "done", model: MODELS.member, query_hash: queryHash2, blocks: [block], follow_ups: [], context_applied: NO_CONTEXT, read: readAs() });
2785
+ live2.send({ type: "done", model, query_hash: queryHash2, blocks: [block], follow_ups: [], context_applied: NO_CONTEXT, read: readAs() });
2780
2786
  live2.send({ type: "quota", quota: payload.quota });
2781
2787
  live2.close();
2782
2788
  return null;
@@ -2827,7 +2833,7 @@ ${summary}` }] : [],
2827
2833
  return null;
2828
2834
  }
2829
2835
  let answer2 = await generateOnce(env, model, messages2, effort);
2830
- if (answer2 === null) answer2 = await generateOnce(env, MODELS.fallback, messages2, effort);
2836
+ if (answer2 === null) answer2 = await generateOnce(env, roleModel(env, "fallback"), messages2, effort);
2831
2837
  if (answer2 === null) {
2832
2838
  telemetry(env, ctx, tier, "ask", model, false, 0, queryHash2, q2.lang, void 0, telemetryMeta());
2833
2839
  return err(502, "generation_failed", "The generation model is unavailable; please retry.");
@@ -3117,7 +3123,7 @@ Answer account questions from these records ONLY: name the record when you use i
3117
3123
  })();
3118
3124
  if (retrieved.hits.length >= 4 && (member || understanding?.complexity === "complex")) {
3119
3125
  const tl = Date.now();
3120
- const reordered = await listwiseRerank(env, MODELS.listwise, understanding?.standalone_query || q2.query, retrieved.hits);
3126
+ const reordered = await listwiseRerank(env, roleModel(env, "listwise"), understanding?.standalone_query || q2.query, retrieved.hits);
3121
3127
  stageTiming.listwise = Date.now() - tl;
3122
3128
  if (reordered) {
3123
3129
  console.log("listwise: reordered", reordered[0]?.metadata?.docidentifier ?? "?", "to top");
@@ -3300,7 +3306,7 @@ ${doc.text}` }
3300
3306
  const queryHash = await sha256Hex(q2.query);
3301
3307
  const cites = escalateAnswer ? escalationCitation() : [...registerCitation, ...boundModel ? [modelCitation(boundModel), ...citations(usedHits)] : citations(usedHits)];
3302
3308
  if (live2) {
3303
- const stream = await generateStream(env, model, messages, routeEffort(routed.route));
3309
+ const stream = await generateStream(env, model, messages, routeEffort(routed.route)) ?? await generateStream(env, roleModel(env, "fallback"), flattenForTextModel(messages), routeEffort(routed.route));
3304
3310
  if (stream) {
3305
3311
  const send = (obj) => live2.send(obj);
3306
3312
  for (const step of agentSteps) {
@@ -3519,7 +3525,7 @@ ${doc.text}` }
3519
3525
  live2.close();
3520
3526
  } else {
3521
3527
  live2.send({ type: "token", v: "The generation model is unavailable; please retry." });
3522
- live2.send({ type: "done", model: MODELS.member, query_hash: "", context_applied: NO_CONTEXT });
3528
+ live2.send({ type: "done", model, query_hash: "", context_applied: NO_CONTEXT });
3523
3529
  live2.close();
3524
3530
  return null;
3525
3531
  }
@@ -3532,7 +3538,7 @@ ${doc.text}` }
3532
3538
  query: q2.query,
3533
3539
  hits: usedHits,
3534
3540
  lang: q2.lang,
3535
- draftModel: MODELS.member,
3541
+ draftModel: roleModel(env, "member"),
3536
3542
  verifierModel: roleModel(env, "verifier")
3537
3543
  }).catch((e) => {
3538
3544
  console.log("speculative: failed, falling through \u2014", String(e).slice(0, 120));
@@ -3547,11 +3553,8 @@ ${doc.text}` }
3547
3553
  if (!answer) answer = await generateOnce(env, model, messages, routeEffort(routed.route));
3548
3554
  if (answer === null) {
3549
3555
  generateRetries += 1;
3550
- const isFigureAttachMessage = (m) => Array.isArray(m.content) && m.content.some((part) => part?.type === "text" && /^The original image of figure unit /.test(part.text ?? ""));
3551
- const flat = messages.filter((m) => !isFigureAttachMessage(m)).map(
3552
- (m) => typeof m.content === "string" ? m : { ...m, content: m.content.filter((p) => p?.type === "text").map((p) => (p?.text ?? "").replace(/\n?\(The user attached an image with this question; interpret it directly when answering\.\)/, "")).join("\n") }
3553
- );
3554
- answer = await generateOnce(env, MODELS.fallback, flat, routeEffort(routed.route));
3556
+ const flat = flattenForTextModel(messages);
3557
+ answer = await generateOnce(env, roleModel(env, "fallback"), flat, routeEffort(routed.route));
3555
3558
  }
3556
3559
  if (answer === null) {
3557
3560
  telemetry(env, ctx, tier, "ask", model, false, 0, queryHash, q2.lang, void 0, telemetryMeta());
@@ -3706,7 +3709,7 @@ ${doc.text}` }
3706
3709
  }
3707
3710
  telemetryDecisions(env, ctx, tier, queryHash, decisionsOut ?? null, Date.now() - tStart);
3708
3711
  }
3709
- const out = { answer, citations: finalCites, ...jsonQuality ? { source_quality: jsonQuality, confidence_note: entailmentNote || qualityNote(jsonQuality), ...entailment ? { entailment } : {}, ...jsonQuality === "ocr" ? { experimental_sources: experimentalSourceLabels(finalCites) } : {} } : {}, model: MODELS.member, 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 } };
3712
+ 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 } };
3710
3713
  const cacheable = !contextual && !declaredCtx && !ablate && !registerBypass && cacheableAnswer(answer, refusalScope(answerCites(answer))) && finalAnchors.violations.length === 0;
3711
3714
  if (cacheable) {
3712
3715
  const ck = exactCacheKey(env.INDEX_VERSION, gen, ns, await sha256Hex(cacheKeyMaterial(q2.query, q2.lang, salt)));
@@ -2,4 +2,3 @@ import { nameplateRegisterQuery, type Nameplate } from "./nameplate-parse.ts";
2
2
  export type { Nameplate };
3
3
  export { nameplateRegisterQuery };
4
4
  export declare function extractNameplate(ai: any, model: string, image: string): Promise<Nameplate | null>;
5
- export declare const nameplateModel: () => "@cf/deepseek-ai/deepseek-v4.1-flash-1017";
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  handleSearch
3
- } from "./chunk-5PKKAHY4.js";
4
- import "./chunk-Q7QL3457.js";
3
+ } from "./chunk-CW6J3HTM.js";
4
+ import "./chunk-3SGGVZZ4.js";
5
5
  import "./chunk-AVNHVFEB.js";
6
6
  import "./chunk-GJQT4IMD.js";
7
7
  import "./chunk-ETLSWSZ7.js";
@@ -23,6 +23,7 @@ export interface UserDocumentPorts {
23
23
  blobs: Blobs;
24
24
  lane: VectorIndex;
25
25
  model: ModelRunner;
26
+ answerModel?: string;
26
27
  }
27
28
  export interface UploadBlob {
28
29
  arrayBuffer(): Promise<ArrayBuffer>;
@@ -9,7 +9,7 @@ import {
9
9
  listUserDocuments,
10
10
  scoreFaithfulness,
11
11
  scoreJudge
12
- } from "../../chunk-WRSUXIS7.js";
12
+ } from "../../chunk-SWCKO4OB.js";
13
13
  import "../../chunk-IRCDOFP4.js";
14
14
  import {
15
15
  TOOLS_REGISTRY,
@@ -18,7 +18,7 @@ import {
18
18
  } from "../../chunk-ECNBEZGK.js";
19
19
  import {
20
20
  handleSearch
21
- } from "../../chunk-5PKKAHY4.js";
21
+ } from "../../chunk-CW6J3HTM.js";
22
22
  import {
23
23
  buildMessages,
24
24
  citations,
@@ -43,7 +43,7 @@ import {
43
43
  sessionFrom,
44
44
  telemetry,
45
45
  understandQuery
46
- } from "../../chunk-Q7QL3457.js";
46
+ } from "../../chunk-3SGGVZZ4.js";
47
47
  import {
48
48
  embed,
49
49
  generateOnce
@@ -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), MODELS.understand, q.query, [], []);
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(MODELS.grader, {
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
- let answer = await generateOnce(env, MODELS.research, messages);
959
- if (answer === null) answer = await generateOnce(env, MODELS.fallback, messages);
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", MODELS.research, false, 0, queryHash, q.lang);
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: MODELS.research,
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", MODELS.research, true, answer.length, queryHash, q.lang);
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
  }
@@ -1189,7 +1190,7 @@ async function callToolOnce(env, ctx, _req, tier, key, name, args, t0) {
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-6SWT3KSC.js")).handleAsk(env, ctx, inner, tier, key) : await (await import("../../search-DE5ADCVM.js")).handleSearch(env, ctx, inner, tier, key);
1193
+ const res = name === "ask" ? await (await import("../../ask-WKHYCVT5.js")).handleAsk(env, ctx, inner, tier, key) : await (await import("../../search-KIN474QS.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");
@@ -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
- │ │ qwen3-30b-a3b → strict JSON (prompts/understanding.md): │ │
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 passages good/weak/bad │ │
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
- │ │ Anon: qwen3-30b-a3b-fp8 | Member: qwen3.8-27b │ │
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, qwen3.8-27b model │
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 glm-5.3-flash call (`attachFigureImages`) — 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.190",
30
+ "version": "0.2.191",
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 ? MODELS.member : MODELS.anon;
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, MODELS.member, effectiveImage).catch(() => null);
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, MODELS.understand, overflow)) ?? undefined) : undefined;
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: MODELS.member, query_hash: "", context_applied: NO_CONTEXT });
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 ?? MODELS.member, query_hash: cached.value.query_hash, served_from: "cache", context_applied: cctx });
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", MODELS.member, true, answer!.length, queryHash, q.lang, undefined, telemetryMeta());
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: MODELS.member,
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: MODELS.member, query_hash: queryHash, blocks: [block], follow_ups: [], context_applied: NO_CONTEXT, read: readAs() });
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, MODELS.fallback, messages, effort);
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, MODELS.listwise, understanding?.standalone_query || q.query, retrieved.hits);
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
- const stream = await generateStream(env, model, messages, routeEffort(routed.route));
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: MODELS.member, query_hash: "", context_applied: NO_CONTEXT });
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: MODELS.member, verifierModel: roleModel(env, "verifier"),
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 must be flattened
2061
- // out first or it errors on (or silently ignores) the pixels the
2062
- // primary was carrying — and the figure-attach NOTE with them: a
2063
- // message saying "the image is attached" to a model that cannot see
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: MODELS.member, 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 } };
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)));
@@ -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 || MODELS.member;
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
- await cache.put(key, String(next), { expirationTtl: 90000 });
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, MODELS, sha256Hex } from "./config";
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), MODELS.understand, q.query, [], []);
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(MODELS.grader, {
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
- let answer = await generateOnce(env, MODELS.research, messages);
163
- if (answer === null) answer = await generateOnce(env, MODELS.fallback, messages);
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", MODELS.research, false, 0, queryHash, q.lang);
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: MODELS.research,
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", MODELS.research, true, answer.length, queryHash, q.lang);
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), MODELS.understand, q.query, []);
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
- const cv = await c.env.VECTORIZE.query(c.vector, {
114
- topK: 3,
115
- returnMetadata: "all",
116
- filter: {
117
- $and: [
118
- { doc_id: { $eq: sectionHit.metadata.doc_id } },
119
- { clause_anchor: { $in: kids } },
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(
@@ -72,7 +72,7 @@ export const typedPin: Stage = {
72
72
  return new Set<string>(pinFamily ? [pinFamily.split("-")[0]] : [...glossaryFamilies]).size > 0;
73
73
  },
74
74
  run: async (c) => {
75
- const { query, filters, u, glossary, hits, env, vector } = c;
75
+ const { query, filters, u, glossary, hits, env } = c;
76
76
  const glossaryFamilies = new Set<string>();
77
77
  for (const g of glossary) if (g.doc_number) glossaryFamilies.add(g.doc_number.split("-")[0]);
78
78
  const pinFamily = filters?.doc_number ?? u?.doc_number ?? null;
@@ -109,16 +109,24 @@ export const typedPin: Stage = {
109
109
  const parentPresent = c.finalHits.some(
110
110
  (h) => h.metadata.doc_id === docId && h.metadata.clause_anchor === anchor && !h.metadata.unit_id,
111
111
  );
112
- if (anchor && docId && !parentPresent) {
112
+ if (anchor && docId && !parentPresent && env.DB) {
113
113
  try {
114
- const pv = await env.VECTORIZE.query(vector, {
115
- topK: 4,
116
- returnMetadata: "all",
117
- filter: { $and: [{ doc_id: { $eq: docId } }, { clause_anchor: { $eq: anchor } }] },
118
- });
119
- const parent = (pv.matches ?? []).map((m: any) => ({ id: m.id, score: m.score, metadata: m.metadata, text: m.metadata?.chunk_text ?? "" })).find((h: any) => !h.metadata?.unit_id);
120
- if (parent && !c.finalHits.some((h) => h.id === parent.id)) {
121
- c.finalHits = [...c.finalHits, { ...parent, score: parent.score * THRESHOLDS.smallToBigDiscount }];
114
+ // Read the parent prose clause from D1 directly: Vectorize rejects
115
+ // $and arrays (40026) and does not index doc_id / clause_anchor.
116
+ const res = await env.DB.prepare(
117
+ "SELECT id, doc_id, docidentifier, doctype, doc_number, edition, language, clause_anchor, clause_title, status, superseded_by, corpus, tier, text, unit_id, block FROM chunks WHERE doc_id = ?1 AND clause_anchor = ?2 AND (unit_id IS NULL OR unit_id = '') LIMIT 2",
118
+ )
119
+ .bind(docId, anchor)
120
+ .all();
121
+ const row = (res.results ?? [])[0] as any;
122
+ if (row && !c.finalHits.some((h) => h.id === String(row.id))) {
123
+ const parent: Hit = {
124
+ id: String(row.id),
125
+ score: typed.score * THRESHOLDS.smallToBigDiscount,
126
+ metadata: { ...row, unit_id: undefined, block: row.block || undefined },
127
+ text: String(row.text ?? ""),
128
+ };
129
+ c.finalHits = [...c.finalHits, parent];
122
130
  console.log("small-to-big: parent §", anchor, "of", typed.metadata.docidentifier, "added");
123
131
  }
124
132
  } catch {
@@ -7,7 +7,7 @@
7
7
  // the window with a rerank score above the incumbent top; every failure
8
8
  // mode is additive (the text ranking stands). Off via the registry
9
9
  // projection like any stage (ablate_stages drops it).
10
- import { MODELS } from "../config.ts";
10
+ import { roleModel } from "../config.ts";
11
11
  import { portBlobs, portModelRunner, portStore } from "../env.ts";
12
12
  import type { Stage } from "./types.ts";
13
13
  import type { Hit } from "../../../shared/chunk";
@@ -63,7 +63,7 @@ export const vlmFigureRerank: Stage = {
63
63
  }
64
64
  if (!kept.length) return;
65
65
  const raced: any = await Promise.race([
66
- portModelRunner(c.env).run({ model: MODELS.vlmFigure, messages: [{ role: "user", content }], maxTokens: 256, effort: "low" }),
66
+ portModelRunner(c.env).run({ model: roleModel(c.env, "vlmFigure"), messages: [{ role: "user", content }], maxTokens: 256, effort: "low" }),
67
67
  new Promise<null>((r) => setTimeout(() => r(null), 15000)),
68
68
  ]);
69
69
  const pick = parsePick(raced?.text ?? raced, kept.length);
@@ -55,6 +55,7 @@ export interface UserDocumentPorts {
55
55
  blobs: Blobs;
56
56
  lane: VectorIndex;
57
57
  model: ModelRunner;
58
+ answerModel?: string;
58
59
  }
59
60
 
60
61
  export interface UploadBlob {
@@ -159,13 +160,13 @@ export async function processImport(ports: UserDocumentPorts, row: UserDocumentR
159
160
  } else {
160
161
  // images: the vision lane transcribes (the nameplate pattern —
161
162
  // transcription-first framing beats extract-a-JSON on plates)
162
- text = await visionTranscribe(ports.model, mime, bytes);
163
+ text = await visionTranscribe(ports.model, mime, bytes, ports.answerModel ?? MODELS.member);
163
164
  if (!text || text.replace(/\s+/g, "").length < 20) {
164
165
  await setStatus("failed", null, "The vision lane could not read this image. Try a sharper photo.");
165
166
  return;
166
167
  }
167
168
  }
168
- const extraction = await structureDocument(ports.model, row.name, mime, text);
169
+ const extraction = await structureDocument(ports.model, row.name, mime, text, ports.answerModel ?? MODELS.member);
169
170
  // the lane chunk: the summary leads, the verbatim text carries the
170
171
  // rest — the federation cites THIS document's content
171
172
  const fieldsLine = Object.entries(extraction.fields).map(([k, v]) => `${k}: ${v}`).join("; ");
@@ -207,13 +208,13 @@ function extractKind(fields: Record<string, string>): string {
207
208
  return fields.kind || "other";
208
209
  }
209
210
 
210
- async function visionTranscribe(model: ModelRunner, mime: string, bytes: Uint8Array): Promise<string> {
211
+ async function visionTranscribe(model: ModelRunner, mime: string, bytes: Uint8Array, modelId: string): Promise<string> {
211
212
  let binary = "";
212
213
  const CHUNK = 0x8000;
213
214
  for (let i = 0; i < bytes.length; i += CHUNK) binary += String.fromCharCode(...bytes.subarray(i, i + CHUNK));
214
215
  const dataUrl = `data:${mime};base64,${btoa(binary)}`;
215
216
  const res = await model.run({
216
- model: MODELS.member,
217
+ model: modelId,
217
218
  messages: [
218
219
  { role: "system", content: "Transcribe everything you can read in this document image — certificate numbers, holders, models, values, dates, clause references. Transcribe first; organize nothing." },
219
220
  { role: "user", content: [{ type: "image_url", image_url: { url: dataUrl } }] },
@@ -227,9 +228,9 @@ async function visionTranscribe(model: ModelRunner, mime: string, bytes: Uint8Ar
227
228
 
228
229
  /** One structuring call: classify + typed fields + a retrieval summary.
229
230
  * The response's JSON object is taken; prose around it is ignored. */
230
- async function structureDocument(model: ModelRunner, name: string, mime: string, text: string): Promise<Extraction> {
231
+ async function structureDocument(model: ModelRunner, name: string, mime: string, text: string, modelId: string): Promise<Extraction> {
231
232
  const res = await model.run({
232
- model: MODELS.member,
233
+ model: modelId,
233
234
  messages: [
234
235
  { role: "system", content: `You classify and structure an imported metrology document. Answer with ONE JSON object: {"kind": "certificate"|"test_report"|"other", "fields": {…short typed fields…}, "summary": "one paragraph a retrieval engine can answer from"}. Certificates carry certificate numbers (like R60/2021-XX1-24.01), holders, models, issue dates. Test reports carry measured values, uncertainties, instruments, clause references. Fields use snake_case names, values verbatim from the text. Never invent a value the text does not carry.` },
235
236
  { role: "user", content: `Document name: ${name}\nFormat: ${mime}\n\nText:\n${text.slice(0, 12000)}` },