@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.
Files changed (34) hide show
  1. package/dist/ask-Q63SLXRD.js +16 -0
  2. package/dist/{chunk-22WB6IVC.js → chunk-5Y3CDK64.js} +13 -0
  3. package/dist/{chunk-7YMIUTPY.js → chunk-J4UAO5XI.js} +1 -1
  4. package/dist/{chunk-GJQT4IMD.js → chunk-M4OCMIWU.js} +1 -1
  5. package/dist/{chunk-ECNBEZGK.js → chunk-NHNCW6KQ.js} +3 -3
  6. package/dist/{chunk-5PKKAHY4.js → chunk-UDHM3G5N.js} +6 -5
  7. package/dist/{chunk-AVNHVFEB.js → chunk-VGBZYYVH.js} +1 -1
  8. package/dist/{chunk-Q7QL3457.js → chunk-W4F22Y4M.js} +134 -34
  9. package/dist/{chunk-WRSUXIS7.js → chunk-ZPNYAANP.js} +35 -32
  10. package/dist/config.d.ts +13 -0
  11. package/dist/nameplate.d.ts +0 -1
  12. package/dist/search-7ANUZAYL.js +14 -0
  13. package/dist/{tools-7GKMDWVB.js → tools-LOQBTAFQ.js} +4 -4
  14. package/dist/userDocuments.d.ts +1 -0
  15. package/dist/worker_mcp/src/index.js +2 -2
  16. package/dist/worker_public/src/config.js +1 -1
  17. package/dist/worker_public/src/index.js +19 -18
  18. package/dist/worker_public/src/requestScope.js +2 -2
  19. package/docs/ARCHITECTURE.md +7 -5
  20. package/package.json +1 -1
  21. package/workers/worker_public/src/ask.ts +42 -32
  22. package/workers/worker_public/src/config.ts +13 -0
  23. package/workers/worker_public/src/decisionWire.ts +2 -2
  24. package/workers/worker_public/src/index.ts +1 -1
  25. package/workers/worker_public/src/nameplate.ts +0 -3
  26. package/workers/worker_public/src/quota.ts +8 -1
  27. package/workers/worker_public/src/research.ts +9 -8
  28. package/workers/worker_public/src/search.ts +2 -2
  29. package/workers/worker_public/src/stages/sectionDescent.ts +9 -21
  30. package/workers/worker_public/src/stages/typedPin.ts +133 -15
  31. package/workers/worker_public/src/stages/vlmFigureRerank.ts +2 -2
  32. package/workers/worker_public/src/userDocuments.ts +7 -6
  33. package/dist/ask-6SWT3KSC.js +0 -16
  34. package/dist/search-DE5ADCVM.js +0 -14
@@ -0,0 +1,16 @@
1
+ import {
2
+ handleAsk
3
+ } from "./chunk-ZPNYAANP.js";
4
+ import "./chunk-IRCDOFP4.js";
5
+ import "./chunk-NHNCW6KQ.js";
6
+ import "./chunk-W4F22Y4M.js";
7
+ import "./chunk-VGBZYYVH.js";
8
+ import "./chunk-M4OCMIWU.js";
9
+ import "./chunk-ETLSWSZ7.js";
10
+ import "./chunk-J4UAO5XI.js";
11
+ import "./chunk-5Y3CDK64.js";
12
+ import "./chunk-3FYJM7LH.js";
13
+ import "./chunk-H6ZULBW2.js";
14
+ export {
15
+ handleAsk
16
+ };
@@ -177,6 +177,19 @@ var THRESHOLDS = {
177
177
  /** Section-descent child discount — children fetched from a ranked
178
178
  * depth-1 summary enter discounted. */
179
179
  sectionDescentDiscount: 0.8,
180
+ /** Typed-pin label weight — for an object-seeking question (a stated
181
+ * value, a named table/figure/formula) a query term met in a unit's
182
+ * LABELS (caption, column headers, row labels) is worth this many
183
+ * body mentions. A blank report form mentions every term of the
184
+ * question and holds no answer: measured 2026-12-05 on the R 60
185
+ * family, the test-report symbol list scored 10 against the limits
186
+ * table's 8 and was pinned — the gate lost the class-B value. */
187
+ typedLabelWeight: 4,
188
+ /** Typed-pin clause completion — how many of the top-ranked prose
189
+ * clauses have their typed siblings (table/figure/formula under the
190
+ * same exact clause) fetched from D1, so the answering object is a
191
+ * candidate even when no retrieval lane surfaced it. */
192
+ typedSiblingProse: 5,
180
193
  /** History budget share — the fraction of the context budget the
181
194
  * conversation slice may consume; older turns overflow into the
182
195
  * compacted summary instead of starving the passages. */
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  DATASETS,
3
3
  datasetAllowed
4
- } from "./chunk-22WB6IVC.js";
4
+ } from "./chunk-5Y3CDK64.js";
5
5
  import {
6
6
  P
7
7
  } from "./chunk-3FYJM7LH.js";
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  LIMITS,
3
3
  sha256Hex
4
- } from "./chunk-22WB6IVC.js";
4
+ } from "./chunk-5Y3CDK64.js";
5
5
  import {
6
6
  P
7
7
  } from "./chunk-3FYJM7LH.js";
@@ -1,12 +1,12 @@
1
1
  import {
2
2
  embed
3
- } from "./chunk-AVNHVFEB.js";
3
+ } from "./chunk-VGBZYYVH.js";
4
4
  import {
5
5
  standardKeysFrom
6
- } from "./chunk-7YMIUTPY.js";
6
+ } from "./chunk-J4UAO5XI.js";
7
7
  import {
8
8
  THRESHOLDS
9
- } from "./chunk-22WB6IVC.js";
9
+ } from "./chunk-5Y3CDK64.js";
10
10
  import {
11
11
  P
12
12
  } from "./chunk-3FYJM7LH.js";
@@ -6,24 +6,25 @@ import {
6
6
  sessionFrom,
7
7
  telemetry,
8
8
  understandQuery
9
- } from "./chunk-Q7QL3457.js";
9
+ } from "./chunk-W4F22Y4M.js";
10
10
  import {
11
11
  corsHeaders,
12
12
  err,
13
13
  json,
14
14
  readJson,
15
15
  validateQuery
16
- } from "./chunk-GJQT4IMD.js";
16
+ } from "./chunk-M4OCMIWU.js";
17
17
  import {
18
18
  entitlementScope,
19
19
  standardKeysFrom
20
- } from "./chunk-7YMIUTPY.js";
20
+ } from "./chunk-J4UAO5XI.js";
21
21
  import {
22
22
  LIMITS,
23
23
  MODELS,
24
24
  num,
25
+ roleModel,
25
26
  sha256Hex
26
- } from "./chunk-22WB6IVC.js";
27
+ } from "./chunk-5Y3CDK64.js";
27
28
  import {
28
29
  portModelRunner
29
30
  } from "./chunk-H6ZULBW2.js";
@@ -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;
@@ -2,7 +2,7 @@ import {
2
2
  answerEffort,
3
3
  effortBudget,
4
4
  generationSampling
5
- } from "./chunk-22WB6IVC.js";
5
+ } from "./chunk-5Y3CDK64.js";
6
6
 
7
7
  // workers/worker_public/src/ai.ts
8
8
  var delay = (ms) => new Promise((r) => setTimeout(r, ms));
@@ -1,11 +1,11 @@
1
1
  import {
2
2
  embed,
3
3
  rerank
4
- } from "./chunk-AVNHVFEB.js";
4
+ } from "./chunk-VGBZYYVH.js";
5
5
  import {
6
6
  bubbleConfirmPage,
7
7
  isAllowedBubbleOrigin
8
- } from "./chunk-GJQT4IMD.js";
8
+ } from "./chunk-M4OCMIWU.js";
9
9
  import {
10
10
  DATASETS,
11
11
  LIMITS,
@@ -14,9 +14,10 @@ import {
14
14
  generationSampling,
15
15
  num,
16
16
  processExpansion,
17
+ roleModel,
17
18
  sha256Hex,
18
19
  today
19
- } from "./chunk-22WB6IVC.js";
20
+ } from "./chunk-5Y3CDK64.js";
20
21
  import {
21
22
  P
22
23
  } from "./chunk-3FYJM7LH.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);
@@ -23336,11 +23337,96 @@ var diversity = {
23336
23337
  };
23337
23338
 
23338
23339
  // workers/worker_public/src/stages/typedPin.ts
23340
+ var UNIT_COLS = "id, doc_id, docidentifier, doctype, doc_number, edition, language, clause_anchor, clause_title, status, superseded_by, corpus, tier, text, unit_id, block";
23341
+ var OBJECT_SEEKING = /\b(minimum|maximum|min|max|least|lowest|highest|numbers?|counts?|values?|limits?|ranges?|mpe|errors?|intervals?|tiers?|tables?|figures?|formulas?|equations?)\b|how many/i;
23342
+ var LABEL_STOP = /* @__PURE__ */ new Set([
23343
+ "the",
23344
+ "and",
23345
+ "for",
23346
+ "per",
23347
+ "with",
23348
+ "from",
23349
+ "into",
23350
+ "that",
23351
+ "this",
23352
+ "what",
23353
+ "which",
23354
+ "according",
23355
+ "does",
23356
+ "are",
23357
+ "how",
23358
+ "why",
23359
+ "when",
23360
+ "where",
23361
+ "who",
23362
+ "its",
23363
+ "their",
23364
+ "there",
23365
+ "about",
23366
+ "between",
23367
+ "across",
23368
+ "after",
23369
+ "before",
23370
+ "not",
23371
+ "can",
23372
+ "must",
23373
+ "shall",
23374
+ "has",
23375
+ "have",
23376
+ "had",
23377
+ "was",
23378
+ "were",
23379
+ "will",
23380
+ "would",
23381
+ "should"
23382
+ ]);
23383
+ function labelText(h) {
23384
+ const t = h.text.toLowerCase();
23385
+ const cols = /columns:(.*?)(?:; row:|$)/s.exec(t)?.[1] ?? "";
23386
+ const rows = [...t.matchAll(/(?:^|; )row: ([^|]+)/g)].map((m) => m[1]).join(" ");
23387
+ return `${h.metadata.clause_title ?? ""} ${cols} ${rows}`.toLowerCase();
23388
+ }
23389
+ function clauseKeyOf(h) {
23390
+ const m = /^u:sec-(.+)$/.exec(String(h.metadata.unit_id ?? ""));
23391
+ const key = m ? m[1] : String(h.metadata.clause_anchor ?? "");
23392
+ return /^(\d+|[A-Z])(\.\d+)*[A-Z]?$/.test(key) ? key : "";
23393
+ }
23394
+ var isProse = (h) => !h.metadata.section_summary && (!h.metadata.unit_id || h.metadata.block === "clause" || !h.metadata.block);
23395
+ async function siblingUnits(env, prose) {
23396
+ if (!env.DB || !prose.length) return [];
23397
+ const found = await Promise.all(
23398
+ prose.map(async (h) => {
23399
+ const docId = String(h.metadata.doc_id ?? "");
23400
+ const key = clauseKeyOf(h);
23401
+ if (!docId || !key) return [];
23402
+ try {
23403
+ const res = await env.DB.prepare(
23404
+ `SELECT ${UNIT_COLS} FROM chunks WHERE doc_id = ?1 AND clause_anchor = ?2 AND block IN ('table','figure','formula') AND unit_id != '' LIMIT 8`
23405
+ ).bind(docId, key).all();
23406
+ return (res.results ?? []).map(
23407
+ (r) => ({
23408
+ id: String(r.id),
23409
+ // it arrives through a ranked passage, like a descent child
23410
+ score: h.score * THRESHOLDS.sectionDescentDiscount,
23411
+ metadata: r,
23412
+ text: String(r.text ?? "")
23413
+ })
23414
+ );
23415
+ } catch {
23416
+ return [];
23417
+ }
23418
+ })
23419
+ );
23420
+ const out = [];
23421
+ for (const list of found) for (const h of list) if (!out.some((x) => x.id === h.id)) out.push(h);
23422
+ return out;
23423
+ }
23339
23424
  function pickTypedChunk(query, candidates, ranked) {
23340
23425
  if (!candidates.length) return null;
23341
23426
  const pool = candidates;
23342
23427
  const q = query.toLowerCase();
23343
23428
  const terms = q.replace(/[^\p{L}\p{N}\s]/gu, " ").split(/\s+/).filter((t) => t.length > 2);
23429
+ const labelTerms = OBJECT_SEEKING.test(q) ? terms.filter((t) => !LABEL_STOP.has(t)) : [];
23344
23430
  const typeBonus = {};
23345
23431
  if (/\bfig(ure)?s?\b/.test(q)) typeBonus.figure = 1;
23346
23432
  if (/\btables?\b/.test(q)) typeBonus.table = 1;
@@ -23359,6 +23445,10 @@ function pickTypedChunk(query, candidates, ranked) {
23359
23445
  const filled = cells.filter((x) => x.length > 0).length;
23360
23446
  const density = cells.length ? filled / cells.length : 0;
23361
23447
  score += density * 2;
23448
+ if (labelTerms.length) {
23449
+ const labels = labelText(h);
23450
+ for (const t of labelTerms) if (labels.includes(t)) score += THRESHOLDS.typedLabelWeight;
23451
+ }
23362
23452
  if (score > bestScore) {
23363
23453
  bestScore = score;
23364
23454
  best = h;
@@ -23375,7 +23465,7 @@ var typedPin = {
23375
23465
  return new Set(pinFamily ? [pinFamily.split("-")[0]] : [...glossaryFamilies]).size > 0;
23376
23466
  },
23377
23467
  run: async (c) => {
23378
- const { query, filters, u, glossary: glossary2, hits, env, vector } = c;
23468
+ const { query, filters, u, glossary: glossary2, hits, env } = c;
23379
23469
  const glossaryFamilies = /* @__PURE__ */ new Set();
23380
23470
  for (const g of glossary2) if (g.doc_number) glossaryFamilies.add(g.doc_number.split("-")[0]);
23381
23471
  const pinFamily = filters?.doc_number ?? u?.doc_number ?? null;
@@ -23383,7 +23473,23 @@ var typedPin = {
23383
23473
  const base = (dn) => String(dn ?? "").split("-")[0];
23384
23474
  const sameDocTyped = (h) => !!h.metadata.unit_id && !!h.metadata.block && pinFamilies.has(base(h.metadata.doc_number));
23385
23475
  {
23386
- const typed = pickTypedChunk(query, hits.filter(sameDocTyped), hits);
23476
+ let pool = hits.filter(sameDocTyped);
23477
+ const fromClause = /* @__PURE__ */ new Set();
23478
+ if (OBJECT_SEEKING.test(query.toLowerCase())) {
23479
+ const prose = hits.filter((h) => isProse(h) && pinFamilies.has(base(h.metadata.doc_number))).slice(0, THRESHOLDS.typedSiblingProse);
23480
+ const siblings = (await siblingUnits(env, prose)).filter(
23481
+ (x) => !pool.some((h) => h.id === x.id) && !c.finalHits.some((h) => h.id === x.id)
23482
+ );
23483
+ if (siblings.length) {
23484
+ pool = [...pool, ...siblings];
23485
+ for (const x of siblings) fromClause.add(x.id);
23486
+ console.log(
23487
+ "typed pin: clause completion \u2014",
23488
+ siblings.map((x) => `${x.metadata.docidentifier} \xA7${x.metadata.clause_anchor} (${x.metadata.block})`).join(", ")
23489
+ );
23490
+ }
23491
+ }
23492
+ const typed = pickTypedChunk(query, pool, hits);
23387
23493
  const hardScope = !!pinFamily;
23388
23494
  const overlap2 = (() => {
23389
23495
  if (!typed || hardScope) return Infinity;
@@ -23394,22 +23500,26 @@ var typedPin = {
23394
23500
  const tableExempt = typed?.metadata.block === "table";
23395
23501
  if (typed && (overlap2 >= 3 || tableExempt) && !c.finalHits.some((h) => h.id === typed.id)) {
23396
23502
  c.finalHits = [...c.finalHits.slice(0, LIMITS.rerankKeep - 1), typed];
23397
- console.log("typed pin:", typed.metadata.docidentifier, "\xA7", typed.metadata.clause_anchor, `(${typed.metadata.block})${hardScope ? "" : " [glossary families]"}`);
23503
+ console.log("typed pin:", typed.metadata.docidentifier, "\xA7", typed.metadata.clause_anchor, `(${typed.metadata.block})${fromClause.has(typed.id) ? " [clause sibling]" : ""}${hardScope ? "" : " [glossary families]"}`);
23398
23504
  const anchor = typed.metadata.clause_anchor;
23399
23505
  const docId = typed.metadata.doc_id;
23400
23506
  const parentPresent = c.finalHits.some(
23401
23507
  (h) => h.metadata.doc_id === docId && h.metadata.clause_anchor === anchor && !h.metadata.unit_id
23402
23508
  );
23403
- if (anchor && docId && !parentPresent) {
23509
+ if (anchor && docId && !parentPresent && env.DB) {
23404
23510
  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 }];
23511
+ const res = await env.DB.prepare(
23512
+ `SELECT ${UNIT_COLS} FROM chunks WHERE doc_id = ?1 AND clause_anchor = ?2 AND (unit_id IS NULL OR unit_id = '') LIMIT 2`
23513
+ ).bind(docId, anchor).all();
23514
+ const row = (res.results ?? [])[0];
23515
+ if (row && !c.finalHits.some((h) => h.id === String(row.id))) {
23516
+ const parent = {
23517
+ id: String(row.id),
23518
+ score: typed.score * THRESHOLDS.smallToBigDiscount,
23519
+ metadata: { ...row, unit_id: void 0, block: row.block || void 0 },
23520
+ text: String(row.text ?? "")
23521
+ };
23522
+ c.finalHits = [...c.finalHits, parent];
23413
23523
  console.log("small-to-big: parent \xA7", anchor, "of", typed.metadata.docidentifier, "added");
23414
23524
  }
23415
23525
  } catch {
@@ -23486,23 +23596,9 @@ var sectionDescent = {
23486
23596
  return;
23487
23597
  }
23488
23598
  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);
23599
+ if (kids.length && c.env.DB) {
23600
+ const order = new Map(kids.map((a, i) => [a, i]));
23601
+ 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
23602
  if (childHits.length) {
23507
23603
  c.finalHits = [...c.finalHits.filter((h) => h !== sectionHit), ...childHits];
23508
23604
  console.log(
@@ -24886,7 +24982,11 @@ async function understandQuery(ai, model, query, history, entities = []) {
24886
24982
  async function kvIncr(cache, key, step = 1) {
24887
24983
  const cur = Number(await cache.get(key) ?? "0");
24888
24984
  const next = cur + step;
24889
- await cache.put(key, String(next), { expirationTtl: 9e4 });
24985
+ try {
24986
+ await cache.put(key, String(next), { expirationTtl: 9e4 });
24987
+ } catch (e) {
24988
+ console.error("kvIncr: put failed \u2014", String(e).slice(0, 120));
24989
+ }
24890
24990
  return next;
24891
24991
  }
24892
24992
  function clientIp(req) {
@@ -33,7 +33,7 @@ import {
33
33
  tableRetyped,
34
34
  toolNote,
35
35
  verdictNote
36
- } from "./chunk-ECNBEZGK.js";
36
+ } from "./chunk-NHNCW6KQ.js";
37
37
  import {
38
38
  NO_CONTEXT,
39
39
  STAGE_NAMES,
@@ -77,20 +77,20 @@ import {
77
77
  tokenBudget,
78
78
  understandQuery,
79
79
  usageTotal
80
- } from "./chunk-Q7QL3457.js";
80
+ } from "./chunk-W4F22Y4M.js";
81
81
  import {
82
82
  CAPACITY_PAUSE_MS,
83
83
  embed,
84
84
  generateOnce,
85
85
  isCapacityError
86
- } from "./chunk-AVNHVFEB.js";
86
+ } from "./chunk-VGBZYYVH.js";
87
87
  import {
88
88
  corsHeaders,
89
89
  err,
90
90
  json,
91
91
  readJson,
92
92
  validateQuery
93
- } from "./chunk-GJQT4IMD.js";
93
+ } from "./chunk-M4OCMIWU.js";
94
94
  import {
95
95
  cacheableAnswer,
96
96
  canonicalRefusal,
@@ -103,7 +103,7 @@ import {
103
103
  requestSalt,
104
104
  resolveRequestScope,
105
105
  standardKeysFrom
106
- } from "./chunk-7YMIUTPY.js";
106
+ } from "./chunk-J4UAO5XI.js";
107
107
  import {
108
108
  DATASETS,
109
109
  ESCALATION_DAILY_DEFAULT,
@@ -117,7 +117,7 @@ import {
117
117
  requestEffort,
118
118
  roleModel,
119
119
  sha256Hex
120
- } from "./chunk-22WB6IVC.js";
120
+ } from "./chunk-5Y3CDK64.js";
121
121
  import {
122
122
  P
123
123
  } from "./chunk-3FYJM7LH.js";
@@ -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)));
package/dist/config.d.ts CHANGED
@@ -125,6 +125,19 @@ export declare const THRESHOLDS: {
125
125
  /** Section-descent child discount — children fetched from a ranked
126
126
  * depth-1 summary enter discounted. */
127
127
  readonly sectionDescentDiscount: 0.8;
128
+ /** Typed-pin label weight — for an object-seeking question (a stated
129
+ * value, a named table/figure/formula) a query term met in a unit's
130
+ * LABELS (caption, column headers, row labels) is worth this many
131
+ * body mentions. A blank report form mentions every term of the
132
+ * question and holds no answer: measured 2026-12-05 on the R 60
133
+ * family, the test-report symbol list scored 10 against the limits
134
+ * table's 8 and was pinned — the gate lost the class-B value. */
135
+ readonly typedLabelWeight: 4;
136
+ /** Typed-pin clause completion — how many of the top-ranked prose
137
+ * clauses have their typed siblings (table/figure/formula under the
138
+ * same exact clause) fetched from D1, so the answering object is a
139
+ * candidate even when no retrieval lane surfaced it. */
140
+ readonly typedSiblingProse: 5;
128
141
  /** History budget share — the fraction of the context budget the
129
142
  * conversation slice may consume; older turns overflow into the
130
143
  * compacted summary instead of starving the passages. */
@@ -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";