@konneal/engine 0.2.194 → 0.2.196

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-GJHB3LY4.js";
3
+ } from "./chunk-FOCGVXCX.js";
4
4
  import "./chunk-IRCDOFP4.js";
5
5
  import "./chunk-2DBXRO4E.js";
6
- import "./chunk-JEPZ7SNP.js";
6
+ import "./chunk-CTSEDLL2.js";
7
7
  import "./chunk-5OSQMWRV.js";
8
8
  import "./chunk-M4OCMIWU.js";
9
9
  import "./chunk-ETLSWSZ7.js";
@@ -23043,15 +23043,20 @@ var figureSeat = {
23043
23043
  const dn = String(h.metadata.doc_number ?? "");
23044
23044
  if (dn) counts.set(dn, (counts.get(dn) ?? 0) + 1);
23045
23045
  }
23046
- const docNumber = c.u?.doc_number ?? [...counts.entries()].sort((a, b) => b[1] - a[1])[0]?.[0];
23047
- if (!docNumber) return;
23046
+ const namedDoc = String(c.u?.docidentifier ?? "").trim();
23047
+ const number = String(c.u?.doc_number ?? "");
23048
+ const byIdentifier = /-\d|-[A-Z]\b/.test(namedDoc.replace(/:\d{4}.*$/, ""));
23049
+ const scope = byIdentifier ? namedDoc : number || [...counts.entries()].sort((a, b) => b[1] - a[1])[0]?.[0];
23050
+ if (!scope) return;
23048
23051
  const seated = new Set(
23049
23052
  c.finalHits.filter((h) => h.metadata.block === "figure").map((h) => String(h.metadata.unit_id ?? h.id))
23050
23053
  );
23051
- const rows = await portStore(c.env).prepare(
23052
- `SELECT id, doc_id, docidentifier, clause_anchor, clause_title, doc_number, edition, language, status, corpus, tier, text, unit_id
23053
- FROM chunks WHERE doc_number = ?1 AND block = 'figure' AND unit_id IS NOT NULL LIMIT 3`
23054
- ).bind(String(docNumber)).all();
23054
+ const cols = "id, doc_id, docidentifier, clause_anchor, clause_title, doc_number, edition, language, status, corpus, tier, text, unit_id";
23055
+ const store = portStore(c.env);
23056
+ let rows = byIdentifier ? await store.prepare(`SELECT ${cols} FROM chunks WHERE docidentifier LIKE ?1 AND block = 'figure' AND unit_id IS NOT NULL ORDER BY clause_anchor LIMIT 3`).bind(`%${namedDoc}`).all() : await store.prepare(`SELECT ${cols} FROM chunks WHERE doc_number = ?1 AND block = 'figure' AND unit_id IS NOT NULL LIMIT 3`).bind(String(scope)).all();
23057
+ if (byIdentifier && !(rows.results ?? []).length && number) {
23058
+ rows = await store.prepare(`SELECT ${cols} FROM chunks WHERE doc_number = ?1 AND block = 'figure' AND unit_id IS NOT NULL LIMIT 3`).bind(number).all();
23059
+ }
23055
23060
  const fresh = [];
23056
23061
  for (const r of rows.results ?? []) {
23057
23062
  if (seated.has(String(r.unit_id))) continue;
@@ -23063,7 +23068,7 @@ var figureSeat = {
23063
23068
  metadata: {
23064
23069
  doc_id: String(r.doc_id ?? ""),
23065
23070
  docidentifier: String(r.docidentifier ?? ""),
23066
- doc_number: String(r.doc_number ?? docNumber),
23071
+ doc_number: String(r.doc_number ?? number ?? scope),
23067
23072
  clause_anchor: r.clause_anchor ? String(r.clause_anchor) : void 0,
23068
23073
  clause_title: r.clause_title ? String(r.clause_title) : void 0,
23069
23074
  edition: r.edition ? String(r.edition) : void 0,
@@ -23078,7 +23083,7 @@ var figureSeat = {
23078
23083
  }
23079
23084
  if (!fresh.length) return;
23080
23085
  c.finalHits = [...fresh, ...c.finalHits];
23081
- console.log("figure-seat: seated", fresh.length, "figure chunk(s) of doc", docNumber);
23086
+ console.log("figure-seat: seated", fresh.length, "figure chunk(s) of", byIdentifier ? namedDoc : "doc " + scope, byIdentifier ? "(named)" : "");
23082
23087
  } catch {
23083
23088
  }
23084
23089
  }
@@ -6,7 +6,7 @@ import {
6
6
  sessionFrom,
7
7
  telemetry,
8
8
  understandQuery
9
- } from "./chunk-JEPZ7SNP.js";
9
+ } from "./chunk-CTSEDLL2.js";
10
10
  import {
11
11
  corsHeaders,
12
12
  err,
@@ -77,7 +77,7 @@ import {
77
77
  tokenBudget,
78
78
  understandQuery,
79
79
  usageTotal
80
- } from "./chunk-JEPZ7SNP.js";
80
+ } from "./chunk-CTSEDLL2.js";
81
81
  import {
82
82
  CAPACITY_PAUSE_MS,
83
83
  embed,
@@ -519,17 +519,20 @@ async function completeTables(db, answer, used) {
519
519
  }
520
520
  return blocks;
521
521
  }
522
- async function completeFigures(db, answer, alreadyAttached, used = [], query) {
522
+ async function completeFigures(db, answer, alreadyAttached, used = [], query, namedDoc = null) {
523
523
  const unitForm = (answer.match(/u:fig[\w.-]*/g) ?? []).map((x) => x.replace(/[.,;:)]+$/, ""));
524
524
  const bareForm = (answer.match(/\bfig-[\w.-]+\b/g) ?? []).map((x) => x.replace(/[.,;:)]+$/, ""));
525
525
  let mentioned = [.../* @__PURE__ */ new Set([...unitForm, ...bareForm.map((x) => x.startsWith("u:") ? x : "u:" + x)])].slice(0, 6);
526
+ const namedLabel = namedDoc ? namedDoc.split(":")[0].trim().toUpperCase() : "";
527
+ const namedPart = namedLabel && /-\d|-[A-Z]\b/.test(namedLabel) ? namedLabel : "";
528
+ const ofNamedPart = (h) => !namedPart || String(h.metadata.docidentifier ?? "").toUpperCase().startsWith(namedPart);
526
529
  const docOf = /* @__PURE__ */ new Map();
527
530
  const proseNums = new Set(
528
531
  (answer.match(/\bFig(?:ure|\.)s?\s*([0-9]{1,2}[a-z]?)/g) ?? []).map((x) => x.replace(/\bFig(?:ure|\.)s?\s*/i, "").toLowerCase())
529
532
  );
530
533
  if (query && /\bfig(ure|s)?\b/i.test(query)) {
531
534
  for (const h of used.slice(0, 12)) {
532
- if (h.metadata.unit_id && h.metadata.block === "figure") {
535
+ if (h.metadata.unit_id && h.metadata.block === "figure" && ofNamedPart(h)) {
533
536
  mentioned.push(h.metadata.unit_id);
534
537
  if (!docOf.has(h.metadata.unit_id)) docOf.set(h.metadata.unit_id, { unit_id: h.metadata.unit_id, doc_id: h.metadata.doc_id, docidentifier: h.metadata.docidentifier });
535
538
  }
@@ -537,7 +540,7 @@ async function completeFigures(db, answer, alreadyAttached, used = [], query) {
537
540
  mentioned = [...new Set(mentioned)].slice(0, 6);
538
541
  }
539
542
  if (proseNums.size) {
540
- const fams = [...new Set(used.map((h) => h.metadata.docidentifier).filter(Boolean))].slice(0, 3);
543
+ const fams = [...new Set([namedPart, ...used.map((h) => h.metadata.docidentifier).filter(Boolean)].filter(Boolean))].slice(0, 3);
541
544
  for (const fam of fams) {
542
545
  const base = String(fam).replace(/\s*\([A-Z]\)\s*$/, "").split(":")[0].trim();
543
546
  const rows = await publicationUnitRows(db, "figure", `%${base}%`, 24);
@@ -3451,7 +3454,7 @@ ${doc.text}` }
3451
3454
  if (!canonical0.includes(refusalAnswer())) {
3452
3455
  try {
3453
3456
  streamedCompletionBlocks = await completeTables(env.DB, canonical0, usedHits);
3454
- streamedCompletionBlocks.push(...await completeFigures(env.DB, canonical0, [...c2.blocks, ...streamedCompletionBlocks], usedHits, q2.query));
3457
+ streamedCompletionBlocks.push(...await completeFigures(env.DB, canonical0, [...c2.blocks, ...streamedCompletionBlocks], usedHits, q2.query, understanding?.docidentifier ?? null));
3455
3458
  if (streamedCompletionBlocks.length) console.log("streamed completion:", streamedCompletionBlocks.length, "block(s) attached");
3456
3459
  } catch {
3457
3460
  }
@@ -3684,7 +3687,7 @@ ${doc.text}` }
3684
3687
  completionBlocks = await completeTables(env.DB, answer, used);
3685
3688
  if (completionBlocks.length) console.log("contract completion:", completionBlocks.length, "table block(s) attached server-side");
3686
3689
  }
3687
- completionBlocks.push(...await completeFigures(env.DB, answer, [...c2ns.blocks, ...completionBlocks], used, q2.query));
3690
+ completionBlocks.push(...await completeFigures(env.DB, answer, [...c2ns.blocks, ...completionBlocks], used, q2.query, understanding?.docidentifier ?? null));
3688
3691
  if (register?.rows?.length && answer.includes(refusalAnswer())) {
3689
3692
  console.log("blind-answer: the register note carried rows but the answer refused \u2014 regenerating once");
3690
3693
  mark("Re-answering from the register results");
@@ -2,4 +2,4 @@ import type { StoreQuery } from "./ports/store.ts";
2
2
  import { type ResolvedBlock } from "./refs.ts";
3
3
  import type { Hit } from "./pipeline.ts";
4
4
  export declare function completeTables(db: StoreQuery, answer: string, used: Hit[]): Promise<ResolvedBlock[]>;
5
- export declare function completeFigures(db: StoreQuery, answer: string, alreadyAttached: ResolvedBlock[], used?: Hit[], query?: string): Promise<ResolvedBlock[]>;
5
+ export declare function completeFigures(db: StoreQuery, answer: string, alreadyAttached: ResolvedBlock[], used?: Hit[], query?: string, namedDoc?: string | null): Promise<ResolvedBlock[]>;
package/dist/env.d.ts CHANGED
@@ -30,6 +30,9 @@ export interface Env {
30
30
  ADMIN_TOKEN?: string;
31
31
  MEMBER_DAY_ASK?: string;
32
32
  ENRICH_MODEL?: string;
33
+ VISION_FALLBACK_KEY?: string;
34
+ VISION_FALLBACK_MODEL?: string;
35
+ VISION_FALLBACK_URL?: string;
33
36
  OIDC_ISSUER?: string;
34
37
  OIDC_CLIENT_ID?: string;
35
38
  OIDC_CLIENT_SECRET?: string;
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  handleSearch
3
- } from "./chunk-6HW7R5SI.js";
4
- import "./chunk-JEPZ7SNP.js";
3
+ } from "./chunk-F4VDXM3W.js";
4
+ import "./chunk-CTSEDLL2.js";
5
5
  import "./chunk-5OSQMWRV.js";
6
6
  import "./chunk-M4OCMIWU.js";
7
7
  import "./chunk-ETLSWSZ7.js";
@@ -0,0 +1,21 @@
1
+ export interface VisionFallbackConfig {
2
+ url: string;
3
+ key: string;
4
+ model: string;
5
+ }
6
+ export declare const DEFAULT_VISION_FALLBACK_URL = "https://api.z.ai/api/paas/v4/chat/completions";
7
+ type FallbackEnv = {
8
+ VISION_FALLBACK_KEY?: string;
9
+ VISION_FALLBACK_MODEL?: string;
10
+ VISION_FALLBACK_URL?: string;
11
+ };
12
+ export declare function visionFallbackConfig(env: FallbackEnv): VisionFallbackConfig | null;
13
+ /** One image-conditioned completion. Returns the message text, or null
14
+ * for any failure — the caller treats null as "no description". */
15
+ export declare function visionFallbackComplete(cfg: VisionFallbackConfig, ask: {
16
+ prompt: string;
17
+ b64: string;
18
+ mime: string;
19
+ maxTokens: number;
20
+ }, fetchFn?: typeof fetch, timeoutMs?: number): Promise<string | null>;
21
+ export {};
@@ -9,7 +9,7 @@ import {
9
9
  listUserDocuments,
10
10
  scoreFaithfulness,
11
11
  scoreJudge
12
- } from "../../chunk-GJHB3LY4.js";
12
+ } from "../../chunk-FOCGVXCX.js";
13
13
  import "../../chunk-IRCDOFP4.js";
14
14
  import {
15
15
  TOOLS_REGISTRY,
@@ -18,7 +18,7 @@ import {
18
18
  } from "../../chunk-2DBXRO4E.js";
19
19
  import {
20
20
  handleSearch
21
- } from "../../chunk-6HW7R5SI.js";
21
+ } from "../../chunk-F4VDXM3W.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-JEPZ7SNP.js";
46
+ } from "../../chunk-CTSEDLL2.js";
47
47
  import {
48
48
  embed,
49
49
  generateOnce,
@@ -391,6 +391,50 @@ var relevancy_default = `You judge ANSWER RELEVANCY for a legal-metrology Q&A sy
391
391
  // workers/worker_public/prompts/precision.md
392
392
  var precision_default = 'You judge CONTEXT PRECISION for a retrieval system over {{PUBLISHER_NAME}} publications. Given the question and the ranked passages (in the order they were presented), score the fraction of passages that contain material USEFUL for answering the question: 1.0 = all useful; 0.5 = half; 0.0 = none. Judge each passage on its own content, not its rank. Reply with ONLY: {"score": 0.0-1.0}\n';
393
393
 
394
+ // workers/worker_public/src/visionFallback.ts
395
+ var DEFAULT_VISION_FALLBACK_URL = "https://api.z.ai/api/paas/v4/chat/completions";
396
+ function visionFallbackConfig(env) {
397
+ const key = typeof env.VISION_FALLBACK_KEY === "string" ? env.VISION_FALLBACK_KEY.trim() : "";
398
+ const model = typeof env.VISION_FALLBACK_MODEL === "string" ? env.VISION_FALLBACK_MODEL.trim() : "";
399
+ if (!key || !model) return null;
400
+ const override = typeof env.VISION_FALLBACK_URL === "string" ? env.VISION_FALLBACK_URL.trim() : "";
401
+ const url = /^https:\/\/\S+$/.test(override) ? override : DEFAULT_VISION_FALLBACK_URL;
402
+ return { url, key, model };
403
+ }
404
+ async function visionFallbackComplete(cfg, ask, fetchFn = fetch, timeoutMs = 6e4) {
405
+ try {
406
+ const res = await fetchFn(cfg.url, {
407
+ method: "POST",
408
+ headers: { authorization: `Bearer ${cfg.key}`, "content-type": "application/json" },
409
+ body: JSON.stringify({
410
+ model: cfg.model,
411
+ max_tokens: ask.maxTokens,
412
+ messages: [
413
+ {
414
+ role: "user",
415
+ content: [
416
+ { type: "text", text: ask.prompt },
417
+ { type: "image_url", image_url: { url: `data:${ask.mime};base64,${ask.b64}` } }
418
+ ]
419
+ }
420
+ ]
421
+ }),
422
+ signal: AbortSignal.timeout(timeoutMs)
423
+ });
424
+ if (!res.ok) {
425
+ console.log("vision fallback: HTTP", res.status);
426
+ return null;
427
+ }
428
+ const d = await res.json();
429
+ const content = d?.choices?.[0]?.message?.content;
430
+ const text = typeof content === "string" ? content : "";
431
+ return text.trim() || null;
432
+ } catch (e) {
433
+ console.log("vision fallback failed:", String(e).slice(0, 120));
434
+ return null;
435
+ }
436
+ }
437
+
394
438
  // workers/worker_public/src/admin.ts
395
439
  async function handleEnrich(env, ctx, req) {
396
440
  if (!env.ADMIN_TOKEN) return err(501, "admin_disabled", "ADMIN_TOKEN secret is not configured");
@@ -624,18 +668,19 @@ async function handleVisionJudge(env, req) {
624
668
  const swap = Math.random() < 0.5;
625
669
  const first = swap ? capB : capA;
626
670
  const second = swap ? capA : capB;
627
- const res = await env.AI.run(roleModel(env, "visionJudge"), {
628
- messages: [
629
- {
630
- role: "user",
631
- content: [
632
- { type: "text", text: `You are judging two descriptions of the same figure (from ${loaded.row.docidentifier}) written for a reader who cannot see it. The figure is attached.
671
+ const prompt = `You are judging two descriptions of the same figure (from ${loaded.row.docidentifier}) written for a reader who cannot see it. The figure is attached.
633
672
 
634
673
  Description 1: ${first}
635
674
 
636
675
  Description 2: ${second}
637
676
 
638
- Which description better tells the reader what the figure shows and its normative point? Reply with ONLY JSON: {"better": 1 or 2, "reason": "one sentence"}.` },
677
+ Which description better tells the reader what the figure shows and its normative point? Reply with ONLY JSON: {"better": 1 or 2, "reason": "one sentence"}.`;
678
+ const res = await env.AI.run(roleModel(env, "visionJudge"), {
679
+ messages: [
680
+ {
681
+ role: "user",
682
+ content: [
683
+ { type: "text", text: prompt },
639
684
  { type: "image_url", image_url: { url: `data:${loaded.mime};base64,${loaded.b64}` } }
640
685
  ]
641
686
  }
@@ -646,12 +691,23 @@ Which description better tells the reader what the figure shows and its normativ
646
691
  max_tokens: 4096
647
692
  });
648
693
  const anyRes = res;
649
- const text = typeof anyRes?.response === "string" ? anyRes.response : anyRes?.choices?.[0]?.message?.content ?? "";
694
+ let text = typeof anyRes?.response === "string" ? anyRes.response : anyRes?.choices?.[0]?.message?.content ?? "";
695
+ let judge = roleModel(env, "visionJudge");
696
+ if (!text.trim()) {
697
+ const fb = visionFallbackConfig(env);
698
+ if (fb) {
699
+ const out = await visionFallbackComplete(fb, { prompt, b64: loaded.b64, mime: loaded.mime, maxTokens: 4096 });
700
+ if (out) {
701
+ text = out;
702
+ judge = `fallback:${fb.model}`;
703
+ }
704
+ }
705
+ }
650
706
  const parsed = JSON.parse(text.replace(/^[^\{]*/, "").replace(/[^\}]*$/, ""));
651
707
  const said = parsed?.better === 1 ? "first" : parsed?.better === 2 ? "second" : null;
652
708
  if (!said) return err(502, "judge_failed", "no decision in the judge's reply: " + text.slice(0, 120));
653
709
  const winner = said === "first" === swap ? "b" : "a";
654
- return json({ ok: true, unit_id: unitId, better: winner, judge: roleModel(env, "visionJudge"), reason: String(parsed.reason ?? "").slice(0, 500) });
710
+ return json({ ok: true, unit_id: unitId, better: winner, judge, reason: String(parsed.reason ?? "").slice(0, 500) });
655
711
  } catch (e) {
656
712
  return err(502, "vision_judge_failed", String(e).slice(0, 200));
657
713
  }
@@ -673,6 +729,8 @@ async function handleCaption(env, req) {
673
729
  const row = loaded.row;
674
730
  const b64 = loaded.b64;
675
731
  const mime = loaded.mime;
732
+ const budget = Math.min(8192, Math.max(256, Math.floor(Number(body?.max_tokens) || 1024)));
733
+ const prompt = `Describe this figure from ${row.docidentifier}${context ? ` (${context})` : ""} for a reader who cannot see it: what is plotted/shown, the axes or structure, and the normative point it makes. 2-3 plain sentences.`;
676
734
  let res = null;
677
735
  for (let attempt = 0; attempt < 2 && !res; attempt++) {
678
736
  try {
@@ -681,12 +739,12 @@ async function handleCaption(env, req) {
681
739
  {
682
740
  role: "user",
683
741
  content: [
684
- { type: "text", text: `Describe this figure from ${row.docidentifier}${context ? ` (${context})` : ""} for a reader who cannot see it: what is plotted/shown, the axes or structure, and the normative point it makes. 2-3 plain sentences.` },
742
+ { type: "text", text: prompt },
685
743
  { type: "image_url", image_url: { url: `data:${mime};base64,${b64}` } }
686
744
  ]
687
745
  }
688
746
  ],
689
- max_tokens: 1024,
747
+ max_tokens: budget,
690
748
  // GLM-5.3-Flash defaults to reasoning_effort "max" when the parameter
691
749
  // is absent — max-effort reasoning starves a 1024-token budget and
692
750
  // the caption comes back empty (the u:fig-2 straggler)
@@ -695,7 +753,20 @@ async function handleCaption(env, req) {
695
753
  } catch {
696
754
  }
697
755
  }
698
- const text = typeof res?.response === "string" ? res.response : res?.choices?.[0]?.message?.content;
756
+ let text = typeof res?.response === "string" ? res.response : res?.choices?.[0]?.message?.content;
757
+ let model = override ?? roleModel(env, "caption");
758
+ let viaFallback = false;
759
+ if (!text?.trim()) {
760
+ const fb = visionFallbackConfig(env);
761
+ if (fb) {
762
+ const out = await visionFallbackComplete(fb, { prompt, b64, mime, maxTokens: budget });
763
+ if (out) {
764
+ text = out;
765
+ model = `fallback:${fb.model}`;
766
+ viaFallback = true;
767
+ }
768
+ }
769
+ }
699
770
  if (!text?.trim()) return err(502, "generation_failed", "vision model returned no description");
700
771
  const trimmed = text.trim();
701
772
  const cap = 900;
@@ -705,7 +776,7 @@ async function handleCaption(env, req) {
705
776
  return end === -1 ? cut.slice(0, cut.lastIndexOf(" ")) : cut.slice(0, end + 1);
706
777
  })();
707
778
  if (!dryRun) await writeUnitDescription(env.DB, unitId, desc, docId);
708
- return json({ ok: true, unit_id: unitId, doc_id: docId || void 0, model: override ?? roleModel(env, "caption"), dry_run: dryRun || void 0, description: desc });
779
+ return json({ ok: true, unit_id: unitId, doc_id: docId || void 0, model, max_tokens: budget, fallback: viaFallback || void 0, dry_run: dryRun || void 0, description: desc });
709
780
  } catch (e) {
710
781
  return err(502, "caption_failed", String(e).slice(0, 200));
711
782
  }
@@ -1194,7 +1265,7 @@ async function callToolOnce(env, ctx, _req, tier, key, name, args, t0) {
1194
1265
  const r = await runTool({ ...env, DB: env.DB }, { name, args }, "mcp");
1195
1266
  payload = r ? { tool: r.name, query: r.query, result: r.output } : { error: { message: `tool ${name} returned nothing for the given arguments` } };
1196
1267
  } else {
1197
- const res = name === "ask" ? await (await import("../../ask-CDJCSFI4.js")).handleAsk(env, ctx, inner, tier, key) : await (await import("../../search-3V6EFKFX.js")).handleSearch(env, ctx, inner, tier, key);
1268
+ const res = name === "ask" ? await (await import("../../ask-PYJFLK5H.js")).handleAsk(env, ctx, inner, tier, key) : await (await import("../../search-WEZGZDO2.js")).handleSearch(env, ctx, inner, tier, key);
1198
1269
  payload = await res.json().catch(() => ({ error: { message: "tool transport failed", status: res.status } }));
1199
1270
  }
1200
1271
  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 });
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.194",
30
+ "version": "0.2.196",
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",
@@ -16,6 +16,7 @@ import { scoreFaithfulness } from "./faithfulness";
16
16
  import { scoreJudge } from "./grader";
17
17
  import { portModelRunner } from "./env.ts";
18
18
  import { unitPayloadRows, writeUnitDescription } from "./unitPayloads.ts";
19
+ import { visionFallbackComplete, visionFallbackConfig } from "./visionFallback.ts";
19
20
  import { P } from "./profile.ts";
20
21
  import { fill, promptVars } from "./pipeline.ts";
21
22
 
@@ -311,12 +312,13 @@ export async function handleVisionJudge(env: Env, req: Request): Promise<Respons
311
312
  const swap = Math.random() < 0.5;
312
313
  const first = swap ? capB : capA;
313
314
  const second = swap ? capA : capB;
315
+ const prompt = `You are judging two descriptions of the same figure (from ${loaded.row.docidentifier}) written for a reader who cannot see it. The figure is attached.\n\nDescription 1: ${first}\n\nDescription 2: ${second}\n\nWhich description better tells the reader what the figure shows and its normative point? Reply with ONLY JSON: {"better": 1 or 2, "reason": "one sentence"}.`;
314
316
  const res = await env.AI.run(roleModel(env, "visionJudge"), {
315
317
  messages: [
316
318
  {
317
319
  role: "user",
318
320
  content: [
319
- { type: "text", text: `You are judging two descriptions of the same figure (from ${loaded.row.docidentifier}) written for a reader who cannot see it. The figure is attached.\n\nDescription 1: ${first}\n\nDescription 2: ${second}\n\nWhich description better tells the reader what the figure shows and its normative point? Reply with ONLY JSON: {"better": 1 or 2, "reason": "one sentence"}.` },
321
+ { type: "text", text: prompt },
320
322
  { type: "image_url", image_url: { url: `data:${loaded.mime};base64,${loaded.b64}` } },
321
323
  ],
322
324
  },
@@ -327,13 +329,26 @@ export async function handleVisionJudge(env: Env, req: Request): Promise<Respons
327
329
  max_tokens: 4096,
328
330
  });
329
331
  const anyRes = res as any;
330
- const text = typeof anyRes?.response === "string" ? anyRes.response : anyRes?.choices?.[0]?.message?.content ?? "";
332
+ let text = typeof anyRes?.response === "string" ? anyRes.response : anyRes?.choices?.[0]?.message?.content ?? "";
333
+ let judge = roleModel(env, "visionJudge");
334
+ if (!text.trim()) {
335
+ // the platform's one image-capable model emptied on this figure —
336
+ // the configured outside model judges before the route gives up
337
+ const fb = visionFallbackConfig(env);
338
+ if (fb) {
339
+ const out = await visionFallbackComplete(fb, { prompt, b64: loaded.b64, mime: loaded.mime, maxTokens: 4096 });
340
+ if (out) {
341
+ text = out;
342
+ judge = `fallback:${fb.model}`;
343
+ }
344
+ }
345
+ }
331
346
  const parsed = JSON.parse(text.replace(/^[^\{]*/, "").replace(/[^\}]*$/, ""));
332
347
  const said = parsed?.better === 1 ? "first" : parsed?.better === 2 ? "second" : null;
333
348
  if (!said) return err(502, "judge_failed", "no decision in the judge's reply: " + text.slice(0, 120));
334
349
  // map back through the presentation swap
335
350
  const winner = (said === "first") === swap ? "b" : "a";
336
- return json({ ok: true, unit_id: unitId, better: winner, judge: roleModel(env, "visionJudge"), reason: String(parsed.reason ?? "").slice(0, 500) });
351
+ return json({ ok: true, unit_id: unitId, better: winner, judge, reason: String(parsed.reason ?? "").slice(0, 500) });
337
352
  } catch (e) {
338
353
  return err(502, "vision_judge_failed", String(e).slice(0, 200));
339
354
  }
@@ -362,6 +377,12 @@ export async function handleCaption(env: Env, req: Request): Promise<Response> {
362
377
  const row = loaded.row;
363
378
  const b64 = loaded.b64;
364
379
  const mime = loaded.mime;
380
+ // the output budget is the caller's to raise: the platform's model
381
+ // reasons inside it, and a dense figure can spend the whole 1024 on
382
+ // reasoning and return no description at all (3 of 4 figures in the
383
+ // 2026-12-05 dry-runs)
384
+ const budget = Math.min(8192, Math.max(256, Math.floor(Number(body?.max_tokens) || 1024)));
385
+ const prompt = `Describe this figure from ${row.docidentifier}${context ? ` (${context})` : ""} for a reader who cannot see it: what is plotted/shown, the axes or structure, and the normative point it makes. 2-3 plain sentences.`;
365
386
  let res: any = null;
366
387
  for (let attempt = 0; attempt < 2 && !res; attempt++) {
367
388
  try {
@@ -370,12 +391,12 @@ export async function handleCaption(env: Env, req: Request): Promise<Response> {
370
391
  {
371
392
  role: "user",
372
393
  content: [
373
- { type: "text", text: `Describe this figure from ${row.docidentifier}${context ? ` (${context})` : ""} for a reader who cannot see it: what is plotted/shown, the axes or structure, and the normative point it makes. 2-3 plain sentences.` },
394
+ { type: "text", text: prompt },
374
395
  { type: "image_url", image_url: { url: `data:${mime};base64,${b64}` } },
375
396
  ],
376
397
  },
377
398
  ],
378
- max_tokens: 1024,
399
+ max_tokens: budget,
379
400
  // GLM-5.3-Flash defaults to reasoning_effort "max" when the parameter
380
401
  // is absent — max-effort reasoning starves a 1024-token budget and
381
402
  // the caption comes back empty (the u:fig-2 straggler)
@@ -385,7 +406,22 @@ export async function handleCaption(env: Env, req: Request): Promise<Response> {
385
406
  // transient Workers AI flake (8005) — retry once
386
407
  }
387
408
  }
388
- const text = typeof res?.response === "string" ? res.response : res?.choices?.[0]?.message?.content;
409
+ let text = typeof res?.response === "string" ? res.response : res?.choices?.[0]?.message?.content;
410
+ let model = override ?? roleModel(env, "caption");
411
+ let viaFallback = false;
412
+ if (!text?.trim()) {
413
+ // the platform's one image-capable model emptied on this figure — the
414
+ // configured outside model is asked before the route gives up
415
+ const fb = visionFallbackConfig(env);
416
+ if (fb) {
417
+ const out = await visionFallbackComplete(fb, { prompt, b64, mime, maxTokens: budget });
418
+ if (out) {
419
+ text = out;
420
+ model = `fallback:${fb.model}`;
421
+ viaFallback = true;
422
+ }
423
+ }
424
+ }
389
425
  if (!text?.trim()) return err(502, "generation_failed", "vision model returned no description");
390
426
  // store complete sentences: a description cut mid-word reads as an
391
427
  // error to the reader, so the cap trims to the last sentence
@@ -401,7 +437,7 @@ export async function handleCaption(env: Env, req: Request): Promise<Response> {
401
437
  return end === -1 ? cut.slice(0, cut.lastIndexOf(" ")) : cut.slice(0, end + 1);
402
438
  })();
403
439
  if (!dryRun) await writeUnitDescription(env.DB, unitId, desc, docId);
404
- return json({ ok: true, unit_id: unitId, doc_id: docId || undefined, model: override ?? roleModel(env, "caption"), dry_run: dryRun || undefined, description: desc });
440
+ return json({ ok: true, unit_id: unitId, doc_id: docId || undefined, model, max_tokens: budget, fallback: viaFallback || undefined, dry_run: dryRun || undefined, description: desc });
405
441
  } catch (e) {
406
442
  return err(502, "caption_failed", String(e).slice(0, 200));
407
443
  }
@@ -1959,7 +1959,7 @@ let convEntities: Array<{ entity: string; kind: string }> = [];
1959
1959
  if (!canonical0.includes(refusalAnswer())) {
1960
1960
  try {
1961
1961
  streamedCompletionBlocks = await completeTables(env.DB, canonical0, usedHits);
1962
- streamedCompletionBlocks.push(...(await completeFigures(env.DB, canonical0, [...c2.blocks, ...streamedCompletionBlocks], usedHits, q.query)));
1962
+ streamedCompletionBlocks.push(...(await completeFigures(env.DB, canonical0, [...c2.blocks, ...streamedCompletionBlocks], usedHits, q.query, understanding?.docidentifier ?? null)));
1963
1963
  if (streamedCompletionBlocks.length) console.log("streamed completion:", streamedCompletionBlocks.length, "block(s) attached");
1964
1964
  } catch { /* additive — the answer stands without the blocks */ }
1965
1965
  }
@@ -2283,7 +2283,7 @@ let convEntities: Array<{ entity: string; kind: string }> = [];
2283
2283
  }
2284
2284
 
2285
2285
  // figure completion (#172) — see ./completion for the rationale
2286
- completionBlocks.push(...(await completeFigures(env.DB, answer!, [...c2ns.blocks, ...completionBlocks], used, q.query)));
2286
+ completionBlocks.push(...(await completeFigures(env.DB, answer!, [...c2ns.blocks, ...completionBlocks], used, q.query, understanding?.docidentifier ?? null)));
2287
2287
 
2288
2288
  // the blind-answer regeneration (2026-10-03, live on the photo case):
2289
2289
  // the multimodal call can answer AROUND an attached image — a 200 whose
@@ -59,6 +59,7 @@ export async function completeFigures(
59
59
  alreadyAttached: ResolvedBlock[],
60
60
  used: Hit[] = [],
61
61
  query?: string,
62
+ namedDoc: string | null = null,
62
63
  ): Promise<ResolvedBlock[]> {
63
64
  // the model names figures BOTH ways: unit ids (u:fig-3) and bare
64
65
  // producer anchors (fig-2a of D 36) — collect both forms; bare
@@ -67,7 +68,15 @@ export async function completeFigures(
67
68
  const unitForm = (answer.match(/u:fig[\w.-]*/g) ?? []).map((x) => x.replace(/[.,;:)]+$/, ""));
68
69
  const bareForm = (answer.match(/\bfig-[\w.-]+\b/g) ?? []).map((x) => x.replace(/[.,;:)]+$/, ""));
69
70
  let mentioned = [...new Set([...unitForm, ...bareForm.map((x) => (x.startsWith("u:") ? x : "u:" + x))])].slice(0, 6);
70
- // the document behind each mentioned unit — a unit id is shared across publications, so a block resolves within the document that named it
71
+ // the part the question names ("Figure 2 in OIML R 60-2"): every part of
72
+ // a family carries the family's number, so without this the completion
73
+ // attached the sibling part's figures — R 60-1's under a question about
74
+ // R 60-2 (measured 2026-12-05). The part comes from the understanding's
75
+ // normalized reference (the text scan keeps only the family); a
76
+ // family-level or absent reference changes nothing.
77
+ const namedLabel = namedDoc ? namedDoc.split(":")[0].trim().toUpperCase() : "";
78
+ const namedPart = namedLabel && /-\d|-[A-Z]\b/.test(namedLabel) ? namedLabel : "";
79
+ const ofNamedPart = (h: Hit) => !namedPart || String(h.metadata.docidentifier ?? "").toUpperCase().startsWith(namedPart);
71
80
  const docOf = new Map<string, UnitKey>();
72
81
  // natural prose names figures without any identifier at all — "Figure 3
73
82
  // of R 60-2 shows…" (the #172 residual): resolve those by number within
@@ -84,7 +93,7 @@ export async function completeFigures(
84
93
  // a hope that the model names an unnameable id
85
94
  if (query && /\bfig(ure|s)?\b/i.test(query)) {
86
95
  for (const h of used.slice(0, 12)) {
87
- if (h.metadata.unit_id && h.metadata.block === "figure") {
96
+ if (h.metadata.unit_id && h.metadata.block === "figure" && ofNamedPart(h)) {
88
97
  mentioned.push(h.metadata.unit_id);
89
98
  if (!docOf.has(h.metadata.unit_id)) docOf.set(h.metadata.unit_id, { unit_id: h.metadata.unit_id, doc_id: h.metadata.doc_id, docidentifier: h.metadata.docidentifier });
90
99
  }
@@ -92,7 +101,7 @@ export async function completeFigures(
92
101
  mentioned = [...new Set(mentioned)].slice(0, 6);
93
102
  }
94
103
  if (proseNums.size) {
95
- const fams = [...new Set(used.map((h) => h.metadata.docidentifier).filter(Boolean))].slice(0, 3);
104
+ const fams = [...new Set([namedPart, ...used.map((h) => h.metadata.docidentifier).filter(Boolean)].filter(Boolean))].slice(0, 3);
96
105
  for (const fam of fams) {
97
106
  const base = String(fam).replace(/\s*\([A-Z]\)\s*$/, "").split(":")[0].trim();
98
107
  const rows = await publicationUnitRows(db, "figure", `%${base}%`, 24);
@@ -32,6 +32,9 @@ export interface Env {
32
32
  ADMIN_TOKEN?: string;
33
33
  MEMBER_DAY_ASK?: string;
34
34
  ENRICH_MODEL?: string;
35
+ VISION_FALLBACK_KEY?: string;
36
+ VISION_FALLBACK_MODEL?: string;
37
+ VISION_FALLBACK_URL?: string;
35
38
  OIDC_ISSUER?: string;
36
39
  OIDC_CLIENT_ID?: string;
37
40
  OIDC_CLIENT_SECRET?: string;
@@ -23,18 +23,32 @@ export const figureSeat: Stage = {
23
23
  const dn = String((h.metadata as any).doc_number ?? "");
24
24
  if (dn) counts.set(dn, (counts.get(dn) ?? 0) + 1);
25
25
  }
26
- const docNumber = (c.u as any)?.doc_number ?? [...counts.entries()].sort((a, b) => b[1] - a[1])[0]?.[0];
27
- if (!docNumber) return;
26
+ // The asked publication at its own grain: every part of a family
27
+ // carries the family's doc_number (R 60-1, R 60-2 and R 60-A all say
28
+ // "60"), so a seat by number returned three of the family's eight
29
+ // figures regardless of the part the question named — "Figure 2 in
30
+ // OIML R 60-2" seated R 60-1's figures (measured 2026-12-05). A part
31
+ // reference is seated by its own identifier; a family reference keeps
32
+ // the number.
33
+ const namedDoc = String((c.u as any)?.docidentifier ?? "").trim();
34
+ const number = String((c.u as any)?.doc_number ?? "");
35
+ const byIdentifier = /-\d|-[A-Z]\b/.test(namedDoc.replace(/:\d{4}.*$/, ""));
36
+ const scope = byIdentifier ? namedDoc : number || [...counts.entries()].sort((a, b) => b[1] - a[1])[0]?.[0];
37
+ if (!scope) return;
28
38
  const seated = new Set(
29
39
  c.finalHits.filter((h: Hit) => (h.metadata as any).block === "figure").map((h: Hit) => String((h.metadata as any).unit_id ?? h.id)),
30
40
  );
31
- const rows = await portStore(c.env)
32
- .prepare(
33
- `SELECT id, doc_id, docidentifier, clause_anchor, clause_title, doc_number, edition, language, status, corpus, tier, text, unit_id
34
- FROM chunks WHERE doc_number = ?1 AND block = 'figure' AND unit_id IS NOT NULL LIMIT 3`,
35
- )
36
- .bind(String(docNumber))
37
- .all();
41
+ const cols =
42
+ "id, doc_id, docidentifier, clause_anchor, clause_title, doc_number, edition, language, status, corpus, tier, text, unit_id";
43
+ const store = portStore(c.env);
44
+ let rows = byIdentifier
45
+ ? await store.prepare(`SELECT ${cols} FROM chunks WHERE docidentifier LIKE ?1 AND block = 'figure' AND unit_id IS NOT NULL ORDER BY clause_anchor LIMIT 3`).bind(`%${namedDoc}`).all()
46
+ : await store.prepare(`SELECT ${cols} FROM chunks WHERE doc_number = ?1 AND block = 'figure' AND unit_id IS NOT NULL LIMIT 3`).bind(String(scope)).all();
47
+ if (byIdentifier && !(rows.results ?? []).length && number) {
48
+ // an identifier spelling the chunks do not carry — the family's
49
+ // figures stand in rather than none
50
+ rows = await store.prepare(`SELECT ${cols} FROM chunks WHERE doc_number = ?1 AND block = 'figure' AND unit_id IS NOT NULL LIMIT 3`).bind(number).all();
51
+ }
38
52
  const fresh: Hit[] = [];
39
53
  for (const r of (rows.results ?? []) as any[]) {
40
54
  if (seated.has(String(r.unit_id))) continue;
@@ -46,7 +60,7 @@ export const figureSeat: Stage = {
46
60
  metadata: {
47
61
  doc_id: String(r.doc_id ?? ""),
48
62
  docidentifier: String(r.docidentifier ?? ""),
49
- doc_number: String(r.doc_number ?? docNumber),
63
+ doc_number: String(r.doc_number ?? number ?? scope),
50
64
  clause_anchor: r.clause_anchor ? String(r.clause_anchor) : undefined,
51
65
  clause_title: r.clause_title ? String(r.clause_title) : undefined,
52
66
  edition: r.edition ? String(r.edition) : undefined,
@@ -61,7 +75,7 @@ export const figureSeat: Stage = {
61
75
  }
62
76
  if (!fresh.length) return;
63
77
  c.finalHits = [...fresh, ...c.finalHits];
64
- console.log("figure-seat: seated", fresh.length, "figure chunk(s) of doc", docNumber);
78
+ console.log("figure-seat: seated", fresh.length, "figure chunk(s) of", byIdentifier ? namedDoc : "doc " + scope, byIdentifier ? "(named)" : "");
65
79
  } catch {
66
80
  // additive — the text ranking stands
67
81
  }
@@ -0,0 +1,69 @@
1
+ // The vision fallback — the model ladder's third rung, for the one-time
2
+ // caption and judge lanes only. The platform's single image-capable model
3
+ // returns an empty generation for some figures (8 of 24 in the 2026-10-27
4
+ // A/B; 3 of 4 dry-runs on 2026-12-05); when it does, the same question is
5
+ // asked of an OpenAI-compatible vision model outside the platform (the
6
+ // estate's z.ai account, directly or through an AI Gateway). Configured,
7
+ // never assumed: no key or no model, no fallback — the route reports the
8
+ // empty generation exactly as it does today. Serving never calls this: the
9
+ // answer path reads the description a figure carries, and this is how a
10
+ // figure gets one.
11
+ export interface VisionFallbackConfig {
12
+ url: string;
13
+ key: string;
14
+ model: string;
15
+ }
16
+
17
+ export const DEFAULT_VISION_FALLBACK_URL = "https://api.z.ai/api/paas/v4/chat/completions";
18
+
19
+ type FallbackEnv = { VISION_FALLBACK_KEY?: string; VISION_FALLBACK_MODEL?: string; VISION_FALLBACK_URL?: string };
20
+
21
+ export function visionFallbackConfig(env: FallbackEnv): VisionFallbackConfig | null {
22
+ const key = typeof env.VISION_FALLBACK_KEY === "string" ? env.VISION_FALLBACK_KEY.trim() : "";
23
+ const model = typeof env.VISION_FALLBACK_MODEL === "string" ? env.VISION_FALLBACK_MODEL.trim() : "";
24
+ if (!key || !model) return null;
25
+ const override = typeof env.VISION_FALLBACK_URL === "string" ? env.VISION_FALLBACK_URL.trim() : "";
26
+ const url = /^https:\/\/\S+$/.test(override) ? override : DEFAULT_VISION_FALLBACK_URL;
27
+ return { url, key, model };
28
+ }
29
+
30
+ /** One image-conditioned completion. Returns the message text, or null
31
+ * for any failure — the caller treats null as "no description". */
32
+ export async function visionFallbackComplete(
33
+ cfg: VisionFallbackConfig,
34
+ ask: { prompt: string; b64: string; mime: string; maxTokens: number },
35
+ fetchFn: typeof fetch = fetch,
36
+ timeoutMs = 60_000,
37
+ ): Promise<string | null> {
38
+ try {
39
+ const res = await fetchFn(cfg.url, {
40
+ method: "POST",
41
+ headers: { authorization: `Bearer ${cfg.key}`, "content-type": "application/json" },
42
+ body: JSON.stringify({
43
+ model: cfg.model,
44
+ max_tokens: ask.maxTokens,
45
+ messages: [
46
+ {
47
+ role: "user",
48
+ content: [
49
+ { type: "text", text: ask.prompt },
50
+ { type: "image_url", image_url: { url: `data:${ask.mime};base64,${ask.b64}` } },
51
+ ],
52
+ },
53
+ ],
54
+ }),
55
+ signal: AbortSignal.timeout(timeoutMs),
56
+ });
57
+ if (!res.ok) {
58
+ console.log("vision fallback: HTTP", res.status);
59
+ return null;
60
+ }
61
+ const d = (await res.json()) as any;
62
+ const content = d?.choices?.[0]?.message?.content;
63
+ const text = typeof content === "string" ? content : "";
64
+ return text.trim() || null;
65
+ } catch (e) {
66
+ console.log("vision fallback failed:", String(e).slice(0, 120));
67
+ return null;
68
+ }
69
+ }