@konneal/engine 0.2.193 → 0.2.195
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{ask-XQR7LQPG.js → ask-CDJCSFI4.js} +4 -4
- package/dist/{chunk-UZHUND67.js → chunk-2DBXRO4E.js} +1 -1
- package/dist/{chunk-QYNFNOKE.js → chunk-5OSQMWRV.js} +11 -1
- package/dist/{chunk-3MV3UO6Q.js → chunk-6HW7R5SI.js} +1 -1
- package/dist/{chunk-RX7FL5D6.js → chunk-GJHB3LY4.js} +3 -3
- package/dist/{chunk-73GZKS2T.js → chunk-JEPZ7SNP.js} +1 -1
- package/dist/env.d.ts +3 -0
- package/dist/{search-UMSZNYGP.js → search-3V6EFKFX.js} +3 -3
- package/dist/{tools-JWKGPVEG.js → tools-JBCL7UQO.js} +2 -2
- package/dist/unitPayloads.d.ts +5 -0
- package/dist/visionFallback.d.ts +21 -0
- package/dist/worker_public/src/index.js +101 -26
- package/package.json +1 -1
- package/workers/worker_public/src/admin.ts +55 -14
- package/workers/worker_public/src/env.ts +3 -0
- package/workers/worker_public/src/unitPayloads.ts +21 -0
- package/workers/worker_public/src/visionFallback.ts +69 -0
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import {
|
|
2
2
|
handleAsk
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-GJHB3LY4.js";
|
|
4
4
|
import "./chunk-IRCDOFP4.js";
|
|
5
|
-
import "./chunk-
|
|
6
|
-
import "./chunk-
|
|
7
|
-
import "./chunk-
|
|
5
|
+
import "./chunk-2DBXRO4E.js";
|
|
6
|
+
import "./chunk-JEPZ7SNP.js";
|
|
7
|
+
import "./chunk-5OSQMWRV.js";
|
|
8
8
|
import "./chunk-M4OCMIWU.js";
|
|
9
9
|
import "./chunk-ETLSWSZ7.js";
|
|
10
10
|
import "./chunk-J4UAO5XI.js";
|
|
@@ -114,6 +114,15 @@ async function publicationUnitRows(db, type, docidentifierLike, limit) {
|
|
|
114
114
|
}
|
|
115
115
|
return [];
|
|
116
116
|
}
|
|
117
|
+
async function writeUnitDescription(db, unitId, description, docId) {
|
|
118
|
+
if (docId) {
|
|
119
|
+
try {
|
|
120
|
+
await db.prepare("UPDATE unit_payloads_doc SET payload = json_set(payload, '$.description', ?1) WHERE unit_id = ?2 AND doc_id = ?3").bind(description, unitId, docId).run();
|
|
121
|
+
} catch {
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
await db.prepare("UPDATE unit_payloads SET payload = json_set(payload, '$.description', ?1) WHERE unit_id = ?2 AND (?3 IS NULL OR doc_id = ?3)").bind(description, unitId, docId ?? null).run();
|
|
125
|
+
}
|
|
117
126
|
|
|
118
127
|
export {
|
|
119
128
|
embed,
|
|
@@ -122,5 +131,6 @@ export {
|
|
|
122
131
|
rerank,
|
|
123
132
|
generateOnce,
|
|
124
133
|
unitPayloadRows,
|
|
125
|
-
publicationUnitRows
|
|
134
|
+
publicationUnitRows,
|
|
135
|
+
writeUnitDescription
|
|
126
136
|
};
|
|
@@ -33,7 +33,7 @@ import {
|
|
|
33
33
|
tableRetyped,
|
|
34
34
|
toolNote,
|
|
35
35
|
verdictNote
|
|
36
|
-
} from "./chunk-
|
|
36
|
+
} from "./chunk-2DBXRO4E.js";
|
|
37
37
|
import {
|
|
38
38
|
NO_CONTEXT,
|
|
39
39
|
STAGE_NAMES,
|
|
@@ -77,7 +77,7 @@ import {
|
|
|
77
77
|
tokenBudget,
|
|
78
78
|
understandQuery,
|
|
79
79
|
usageTotal
|
|
80
|
-
} from "./chunk-
|
|
80
|
+
} from "./chunk-JEPZ7SNP.js";
|
|
81
81
|
import {
|
|
82
82
|
CAPACITY_PAUSE_MS,
|
|
83
83
|
embed,
|
|
@@ -85,7 +85,7 @@ import {
|
|
|
85
85
|
isCapacityError,
|
|
86
86
|
publicationUnitRows,
|
|
87
87
|
unitPayloadRows
|
|
88
|
-
} from "./chunk-
|
|
88
|
+
} from "./chunk-5OSQMWRV.js";
|
|
89
89
|
import {
|
|
90
90
|
corsHeaders,
|
|
91
91
|
err,
|
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,8 +1,8 @@
|
|
|
1
1
|
import {
|
|
2
2
|
handleSearch
|
|
3
|
-
} from "./chunk-
|
|
4
|
-
import "./chunk-
|
|
5
|
-
import "./chunk-
|
|
3
|
+
} from "./chunk-6HW7R5SI.js";
|
|
4
|
+
import "./chunk-JEPZ7SNP.js";
|
|
5
|
+
import "./chunk-5OSQMWRV.js";
|
|
6
6
|
import "./chunk-M4OCMIWU.js";
|
|
7
7
|
import "./chunk-ETLSWSZ7.js";
|
|
8
8
|
import "./chunk-J4UAO5XI.js";
|
|
@@ -4,8 +4,8 @@ import {
|
|
|
4
4
|
parseToolCall,
|
|
5
5
|
runTool,
|
|
6
6
|
toolNote
|
|
7
|
-
} from "./chunk-
|
|
8
|
-
import "./chunk-
|
|
7
|
+
} from "./chunk-2DBXRO4E.js";
|
|
8
|
+
import "./chunk-5OSQMWRV.js";
|
|
9
9
|
import "./chunk-J4UAO5XI.js";
|
|
10
10
|
import "./chunk-5Y3CDK64.js";
|
|
11
11
|
import "./chunk-3FYJM7LH.js";
|
package/dist/unitPayloads.d.ts
CHANGED
|
@@ -22,3 +22,8 @@ export declare function unitPayloadRows(db: StoreQuery, keys: readonly UnitKey[]
|
|
|
22
22
|
* pattern), from the document-scoped table — or the legacy one where
|
|
23
23
|
* that deployment has none. */
|
|
24
24
|
export declare function publicationUnitRows(db: StoreQuery, type: string, docidentifierLike: string, limit: number): Promise<UnitRow[]>;
|
|
25
|
+
/** Store a generated description on a unit — on its document's row when
|
|
26
|
+
* the document is known, and on the legacy row only when that row IS
|
|
27
|
+
* the same document's: a bare unit id names the last writer, and a
|
|
28
|
+
* caption meant for one publication must never land on another's. */
|
|
29
|
+
export declare function writeUnitDescription(db: StoreQuery, unitId: string, description: string, docId?: string | null): Promise<void>;
|
|
@@ -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,16 +9,16 @@ import {
|
|
|
9
9
|
listUserDocuments,
|
|
10
10
|
scoreFaithfulness,
|
|
11
11
|
scoreJudge
|
|
12
|
-
} from "../../chunk-
|
|
12
|
+
} from "../../chunk-GJHB3LY4.js";
|
|
13
13
|
import "../../chunk-IRCDOFP4.js";
|
|
14
14
|
import {
|
|
15
15
|
TOOLS_REGISTRY,
|
|
16
16
|
bindModelNode,
|
|
17
17
|
modelGroundingBlock
|
|
18
|
-
} from "../../chunk-
|
|
18
|
+
} from "../../chunk-2DBXRO4E.js";
|
|
19
19
|
import {
|
|
20
20
|
handleSearch
|
|
21
|
-
} from "../../chunk-
|
|
21
|
+
} from "../../chunk-6HW7R5SI.js";
|
|
22
22
|
import {
|
|
23
23
|
buildMessages,
|
|
24
24
|
citations,
|
|
@@ -43,11 +43,13 @@ import {
|
|
|
43
43
|
sessionFrom,
|
|
44
44
|
telemetry,
|
|
45
45
|
understandQuery
|
|
46
|
-
} from "../../chunk-
|
|
46
|
+
} from "../../chunk-JEPZ7SNP.js";
|
|
47
47
|
import {
|
|
48
48
|
embed,
|
|
49
|
-
generateOnce
|
|
50
|
-
|
|
49
|
+
generateOnce,
|
|
50
|
+
unitPayloadRows,
|
|
51
|
+
writeUnitDescription
|
|
52
|
+
} from "../../chunk-5OSQMWRV.js";
|
|
51
53
|
import {
|
|
52
54
|
authenticate,
|
|
53
55
|
corsHeaders,
|
|
@@ -389,6 +391,50 @@ var relevancy_default = `You judge ANSWER RELEVANCY for a legal-metrology Q&A sy
|
|
|
389
391
|
// workers/worker_public/prompts/precision.md
|
|
390
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';
|
|
391
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
|
+
|
|
392
438
|
// workers/worker_public/src/admin.ts
|
|
393
439
|
async function handleEnrich(env, ctx, req) {
|
|
394
440
|
if (!env.ADMIN_TOKEN) return err(501, "admin_disabled", "ADMIN_TOKEN secret is not configured");
|
|
@@ -589,8 +635,8 @@ ${chain || "(no successor edges recorded)"}` }
|
|
|
589
635
|
return err(502, "family_summary_failed", String(e?.message ?? e).slice(0, 200));
|
|
590
636
|
}
|
|
591
637
|
}
|
|
592
|
-
async function loadUnitAsset(env, unitId) {
|
|
593
|
-
const row = await env.DB
|
|
638
|
+
async function loadUnitAsset(env, unitId, docId) {
|
|
639
|
+
const [row] = await unitPayloadRows(env.DB, [{ unit_id: unitId, doc_id: docId || null }]);
|
|
594
640
|
if (!row) return { error: err(404, "not_found", "no unit_payload row for that id") };
|
|
595
641
|
const payload = JSON.parse(String(row.payload));
|
|
596
642
|
const uri = payload.uri ?? "";
|
|
@@ -612,27 +658,29 @@ async function handleVisionJudge(env, req) {
|
|
|
612
658
|
if (auth !== `Bearer ${env.ADMIN_TOKEN}`) return err(401, "unauthorized", "Invalid admin token");
|
|
613
659
|
const body = await readJson(req);
|
|
614
660
|
const unitId = typeof body?.unit_id === "string" ? body.unit_id : "";
|
|
661
|
+
const docId = typeof body?.doc_id === "string" ? body.doc_id.slice(0, 200) : "";
|
|
615
662
|
const capA = typeof body?.captions?.a === "string" ? body.captions.a.slice(0, 2e3) : "";
|
|
616
663
|
const capB = typeof body?.captions?.b === "string" ? body.captions.b.slice(0, 2e3) : "";
|
|
617
664
|
if (!unitId || !capA || !capB) return err(400, "invalid_input", "unit_id and captions.a/.b required");
|
|
618
665
|
try {
|
|
619
|
-
const loaded = await loadUnitAsset(env, unitId);
|
|
666
|
+
const loaded = await loadUnitAsset(env, unitId, docId);
|
|
620
667
|
if (loaded.error) return loaded.error;
|
|
621
668
|
const swap = Math.random() < 0.5;
|
|
622
669
|
const first = swap ? capB : capA;
|
|
623
670
|
const second = swap ? capA : capB;
|
|
624
|
-
const
|
|
625
|
-
messages: [
|
|
626
|
-
{
|
|
627
|
-
role: "user",
|
|
628
|
-
content: [
|
|
629
|
-
{ 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.
|
|
630
672
|
|
|
631
673
|
Description 1: ${first}
|
|
632
674
|
|
|
633
675
|
Description 2: ${second}
|
|
634
676
|
|
|
635
|
-
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 },
|
|
636
684
|
{ type: "image_url", image_url: { url: `data:${loaded.mime};base64,${loaded.b64}` } }
|
|
637
685
|
]
|
|
638
686
|
}
|
|
@@ -643,12 +691,23 @@ Which description better tells the reader what the figure shows and its normativ
|
|
|
643
691
|
max_tokens: 4096
|
|
644
692
|
});
|
|
645
693
|
const anyRes = res;
|
|
646
|
-
|
|
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
|
+
}
|
|
647
706
|
const parsed = JSON.parse(text.replace(/^[^\{]*/, "").replace(/[^\}]*$/, ""));
|
|
648
707
|
const said = parsed?.better === 1 ? "first" : parsed?.better === 2 ? "second" : null;
|
|
649
708
|
if (!said) return err(502, "judge_failed", "no decision in the judge's reply: " + text.slice(0, 120));
|
|
650
709
|
const winner = said === "first" === swap ? "b" : "a";
|
|
651
|
-
return json({ ok: true, unit_id: unitId, better: winner, judge
|
|
710
|
+
return json({ ok: true, unit_id: unitId, better: winner, judge, reason: String(parsed.reason ?? "").slice(0, 500) });
|
|
652
711
|
} catch (e) {
|
|
653
712
|
return err(502, "vision_judge_failed", String(e).slice(0, 200));
|
|
654
713
|
}
|
|
@@ -659,16 +718,19 @@ async function handleCaption(env, req) {
|
|
|
659
718
|
if (auth !== `Bearer ${env.ADMIN_TOKEN}`) return err(401, "unauthorized", "Invalid admin token");
|
|
660
719
|
const body = await readJson(req);
|
|
661
720
|
const unitId = typeof body?.unit_id === "string" ? body.unit_id : "";
|
|
721
|
+
const docId = typeof body?.doc_id === "string" ? body.doc_id.slice(0, 200) : "";
|
|
662
722
|
const context = typeof body?.context === "string" ? body.context.slice(0, 400) : "";
|
|
663
723
|
const override = typeof body?.model === "string" && body.model.startsWith("@cf/") ? body.model : null;
|
|
664
724
|
const dryRun = body?.dry_run === true;
|
|
665
725
|
if (!unitId) return err(400, "invalid_input", "unit_id required");
|
|
666
726
|
try {
|
|
667
|
-
const loaded = await loadUnitAsset(env, unitId);
|
|
727
|
+
const loaded = await loadUnitAsset(env, unitId, docId);
|
|
668
728
|
if (loaded.error) return loaded.error;
|
|
669
729
|
const row = loaded.row;
|
|
670
730
|
const b64 = loaded.b64;
|
|
671
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.`;
|
|
672
734
|
let res = null;
|
|
673
735
|
for (let attempt = 0; attempt < 2 && !res; attempt++) {
|
|
674
736
|
try {
|
|
@@ -677,12 +739,12 @@ async function handleCaption(env, req) {
|
|
|
677
739
|
{
|
|
678
740
|
role: "user",
|
|
679
741
|
content: [
|
|
680
|
-
{ type: "text", text:
|
|
742
|
+
{ type: "text", text: prompt },
|
|
681
743
|
{ type: "image_url", image_url: { url: `data:${mime};base64,${b64}` } }
|
|
682
744
|
]
|
|
683
745
|
}
|
|
684
746
|
],
|
|
685
|
-
max_tokens:
|
|
747
|
+
max_tokens: budget,
|
|
686
748
|
// GLM-5.3-Flash defaults to reasoning_effort "max" when the parameter
|
|
687
749
|
// is absent — max-effort reasoning starves a 1024-token budget and
|
|
688
750
|
// the caption comes back empty (the u:fig-2 straggler)
|
|
@@ -691,7 +753,20 @@ async function handleCaption(env, req) {
|
|
|
691
753
|
} catch {
|
|
692
754
|
}
|
|
693
755
|
}
|
|
694
|
-
|
|
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
|
+
}
|
|
695
770
|
if (!text?.trim()) return err(502, "generation_failed", "vision model returned no description");
|
|
696
771
|
const trimmed = text.trim();
|
|
697
772
|
const cap = 900;
|
|
@@ -700,8 +775,8 @@ async function handleCaption(env, req) {
|
|
|
700
775
|
const end = Math.max(cut.lastIndexOf(". "), cut.lastIndexOf("! "), cut.lastIndexOf("? "));
|
|
701
776
|
return end === -1 ? cut.slice(0, cut.lastIndexOf(" ")) : cut.slice(0, end + 1);
|
|
702
777
|
})();
|
|
703
|
-
if (!dryRun) await env.DB
|
|
704
|
-
return json({ ok: true, unit_id: unitId,
|
|
778
|
+
if (!dryRun) await writeUnitDescription(env.DB, unitId, desc, docId);
|
|
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 });
|
|
705
780
|
} catch (e) {
|
|
706
781
|
return err(502, "caption_failed", String(e).slice(0, 200));
|
|
707
782
|
}
|
|
@@ -1184,13 +1259,13 @@ async function callToolOnce(env, ctx, _req, tier, key, name, args, t0) {
|
|
|
1184
1259
|
// stream:false forces the JSON lane (anon defaults to SSE)
|
|
1185
1260
|
body: JSON.stringify({ ...args, stream: false })
|
|
1186
1261
|
});
|
|
1187
|
-
const { runTool, TOOLS_REGISTRY: TOOLS_REGISTRY2 } = await import("../../tools-
|
|
1262
|
+
const { runTool, TOOLS_REGISTRY: TOOLS_REGISTRY2 } = await import("../../tools-JBCL7UQO.js");
|
|
1188
1263
|
let payload;
|
|
1189
1264
|
if (TOOLS_REGISTRY2.some((t) => t.name === name && t.audiences.includes("mcp"))) {
|
|
1190
1265
|
const r = await runTool({ ...env, DB: env.DB }, { name, args }, "mcp");
|
|
1191
1266
|
payload = r ? { tool: r.name, query: r.query, result: r.output } : { error: { message: `tool ${name} returned nothing for the given arguments` } };
|
|
1192
1267
|
} else {
|
|
1193
|
-
const res = name === "ask" ? await (await import("../../ask-
|
|
1268
|
+
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);
|
|
1194
1269
|
payload = await res.json().catch(() => ({ error: { message: "tool transport failed", status: res.status } }));
|
|
1195
1270
|
}
|
|
1196
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.
|
|
30
|
+
"version": "0.2.195",
|
|
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",
|
|
@@ -15,6 +15,8 @@ import precisionPrompt from "../prompts/precision.md";
|
|
|
15
15
|
import { scoreFaithfulness } from "./faithfulness";
|
|
16
16
|
import { scoreJudge } from "./grader";
|
|
17
17
|
import { portModelRunner } from "./env.ts";
|
|
18
|
+
import { unitPayloadRows, writeUnitDescription } from "./unitPayloads.ts";
|
|
19
|
+
import { visionFallbackComplete, visionFallbackConfig } from "./visionFallback.ts";
|
|
18
20
|
import { P } from "./profile.ts";
|
|
19
21
|
import { fill, promptVars } from "./pipeline.ts";
|
|
20
22
|
|
|
@@ -265,9 +267,11 @@ export async function handleFamilySummary(env: Env, req: Request): Promise<Respo
|
|
|
265
267
|
* passes like embedding smoothing (G-ETSI-4) — the binding is the
|
|
266
268
|
* credential, admin-token gated exactly like /admin/enrich. */
|
|
267
269
|
/** The unit's vision asset, base64-encoded for the message part — the
|
|
268
|
-
* one load path the caption and the pairwise judge share.
|
|
269
|
-
|
|
270
|
-
|
|
270
|
+
* one load path the caption and the pairwise judge share. The unit is
|
|
271
|
+
* read within its document when the caller names one: a unit id alone
|
|
272
|
+
* is shared across publications and names only its last writer. */
|
|
273
|
+
async function loadUnitAsset(env: Env, unitId: string, docId?: string) {
|
|
274
|
+
const [row] = await unitPayloadRows(env.DB, [{ unit_id: unitId, doc_id: docId || null }]);
|
|
271
275
|
if (!row) return { error: err(404, "not_found", "no unit_payload row for that id") };
|
|
272
276
|
const payload = JSON.parse(String(row.payload));
|
|
273
277
|
const uri = payload.uri ?? "";
|
|
@@ -296,23 +300,25 @@ export async function handleVisionJudge(env: Env, req: Request): Promise<Respons
|
|
|
296
300
|
if (auth !== `Bearer ${env.ADMIN_TOKEN}`) return err(401, "unauthorized", "Invalid admin token");
|
|
297
301
|
const body = await readJson(req);
|
|
298
302
|
const unitId = typeof body?.unit_id === "string" ? body.unit_id : "";
|
|
303
|
+
const docId = typeof body?.doc_id === "string" ? body.doc_id.slice(0, 200) : "";
|
|
299
304
|
const capA = typeof body?.captions?.a === "string" ? body.captions.a.slice(0, 2000) : "";
|
|
300
305
|
const capB = typeof body?.captions?.b === "string" ? body.captions.b.slice(0, 2000) : "";
|
|
301
306
|
if (!unitId || !capA || !capB) return err(400, "invalid_input", "unit_id and captions.a/.b required");
|
|
302
307
|
try {
|
|
303
|
-
const loaded = await loadUnitAsset(env, unitId);
|
|
308
|
+
const loaded = await loadUnitAsset(env, unitId, docId);
|
|
304
309
|
if (loaded.error) return loaded.error;
|
|
305
310
|
// randomized presentation order: the judge's letter bias must not
|
|
306
311
|
// correlate with either arm
|
|
307
312
|
const swap = Math.random() < 0.5;
|
|
308
313
|
const first = swap ? capB : capA;
|
|
309
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"}.`;
|
|
310
316
|
const res = await env.AI.run(roleModel(env, "visionJudge"), {
|
|
311
317
|
messages: [
|
|
312
318
|
{
|
|
313
319
|
role: "user",
|
|
314
320
|
content: [
|
|
315
|
-
{ type: "text", text:
|
|
321
|
+
{ type: "text", text: prompt },
|
|
316
322
|
{ type: "image_url", image_url: { url: `data:${loaded.mime};base64,${loaded.b64}` } },
|
|
317
323
|
],
|
|
318
324
|
},
|
|
@@ -323,13 +329,26 @@ export async function handleVisionJudge(env: Env, req: Request): Promise<Respons
|
|
|
323
329
|
max_tokens: 4096,
|
|
324
330
|
});
|
|
325
331
|
const anyRes = res as any;
|
|
326
|
-
|
|
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
|
+
}
|
|
327
346
|
const parsed = JSON.parse(text.replace(/^[^\{]*/, "").replace(/[^\}]*$/, ""));
|
|
328
347
|
const said = parsed?.better === 1 ? "first" : parsed?.better === 2 ? "second" : null;
|
|
329
348
|
if (!said) return err(502, "judge_failed", "no decision in the judge's reply: " + text.slice(0, 120));
|
|
330
349
|
// map back through the presentation swap
|
|
331
350
|
const winner = (said === "first") === swap ? "b" : "a";
|
|
332
|
-
return json({ ok: true, unit_id: unitId, better: winner, judge
|
|
351
|
+
return json({ ok: true, unit_id: unitId, better: winner, judge, reason: String(parsed.reason ?? "").slice(0, 500) });
|
|
333
352
|
} catch (e) {
|
|
334
353
|
return err(502, "vision_judge_failed", String(e).slice(0, 200));
|
|
335
354
|
}
|
|
@@ -344,19 +363,26 @@ export async function handleCaption(env: Env, req: Request): Promise<Response> {
|
|
|
344
363
|
if (auth !== `Bearer ${env.ADMIN_TOKEN}`) return err(401, "unauthorized", "Invalid admin token");
|
|
345
364
|
const body = await readJson(req);
|
|
346
365
|
const unitId = typeof body?.unit_id === "string" ? body.unit_id : "";
|
|
366
|
+
const docId = typeof body?.doc_id === "string" ? body.doc_id.slice(0, 200) : "";
|
|
347
367
|
const context = typeof body?.context === "string" ? body.context.slice(0, 400) : "";
|
|
348
368
|
// the A/B arm (TODO.sota/18.4): a per-request model override for the
|
|
349
369
|
// measurement, admin-gated like the route itself; dry_run skips the
|
|
350
|
-
// payload write so the arms never mix state in
|
|
370
|
+
// payload write so the arms never mix state in the unit payloads
|
|
351
371
|
const override = typeof body?.model === "string" && body.model.startsWith("@cf/") ? body.model : null;
|
|
352
372
|
const dryRun = body?.dry_run === true;
|
|
353
373
|
if (!unitId) return err(400, "invalid_input", "unit_id required");
|
|
354
374
|
try {
|
|
355
|
-
const loaded = await loadUnitAsset(env, unitId);
|
|
375
|
+
const loaded = await loadUnitAsset(env, unitId, docId);
|
|
356
376
|
if (loaded.error) return loaded.error;
|
|
357
377
|
const row = loaded.row;
|
|
358
378
|
const b64 = loaded.b64;
|
|
359
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.`;
|
|
360
386
|
let res: any = null;
|
|
361
387
|
for (let attempt = 0; attempt < 2 && !res; attempt++) {
|
|
362
388
|
try {
|
|
@@ -365,12 +391,12 @@ export async function handleCaption(env: Env, req: Request): Promise<Response> {
|
|
|
365
391
|
{
|
|
366
392
|
role: "user",
|
|
367
393
|
content: [
|
|
368
|
-
{ type: "text", text:
|
|
394
|
+
{ type: "text", text: prompt },
|
|
369
395
|
{ type: "image_url", image_url: { url: `data:${mime};base64,${b64}` } },
|
|
370
396
|
],
|
|
371
397
|
},
|
|
372
398
|
],
|
|
373
|
-
max_tokens:
|
|
399
|
+
max_tokens: budget,
|
|
374
400
|
// GLM-5.3-Flash defaults to reasoning_effort "max" when the parameter
|
|
375
401
|
// is absent — max-effort reasoning starves a 1024-token budget and
|
|
376
402
|
// the caption comes back empty (the u:fig-2 straggler)
|
|
@@ -380,7 +406,22 @@ export async function handleCaption(env: Env, req: Request): Promise<Response> {
|
|
|
380
406
|
// transient Workers AI flake (8005) — retry once
|
|
381
407
|
}
|
|
382
408
|
}
|
|
383
|
-
|
|
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
|
+
}
|
|
384
425
|
if (!text?.trim()) return err(502, "generation_failed", "vision model returned no description");
|
|
385
426
|
// store complete sentences: a description cut mid-word reads as an
|
|
386
427
|
// error to the reader, so the cap trims to the last sentence
|
|
@@ -395,8 +436,8 @@ export async function handleCaption(env: Env, req: Request): Promise<Response> {
|
|
|
395
436
|
const end = Math.max(cut.lastIndexOf(". "), cut.lastIndexOf("! "), cut.lastIndexOf("? "));
|
|
396
437
|
return end === -1 ? cut.slice(0, cut.lastIndexOf(" ")) : cut.slice(0, end + 1);
|
|
397
438
|
})();
|
|
398
|
-
if (!dryRun) await env.DB
|
|
399
|
-
return json({ ok: true, unit_id: unitId,
|
|
439
|
+
if (!dryRun) await writeUnitDescription(env.DB, unitId, desc, docId);
|
|
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 });
|
|
400
441
|
} catch (e) {
|
|
401
442
|
return err(502, "caption_failed", String(e).slice(0, 200));
|
|
402
443
|
}
|
|
@@ -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;
|
|
@@ -90,3 +90,24 @@ export async function publicationUnitRows(
|
|
|
90
90
|
}
|
|
91
91
|
return [];
|
|
92
92
|
}
|
|
93
|
+
|
|
94
|
+
/** Store a generated description on a unit — on its document's row when
|
|
95
|
+
* the document is known, and on the legacy row only when that row IS
|
|
96
|
+
* the same document's: a bare unit id names the last writer, and a
|
|
97
|
+
* caption meant for one publication must never land on another's. */
|
|
98
|
+
export async function writeUnitDescription(db: StoreQuery, unitId: string, description: string, docId?: string | null): Promise<void> {
|
|
99
|
+
if (docId) {
|
|
100
|
+
try {
|
|
101
|
+
await db
|
|
102
|
+
.prepare("UPDATE unit_payloads_doc SET payload = json_set(payload, '$.description', ?1) WHERE unit_id = ?2 AND doc_id = ?3")
|
|
103
|
+
.bind(description, unitId, docId)
|
|
104
|
+
.run();
|
|
105
|
+
} catch {
|
|
106
|
+
// a deployment without the document-scoped table
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
await db
|
|
110
|
+
.prepare("UPDATE unit_payloads SET payload = json_set(payload, '$.description', ?1) WHERE unit_id = ?2 AND (?3 IS NULL OR doc_id = ?3)")
|
|
111
|
+
.bind(description, unitId, docId ?? null)
|
|
112
|
+
.run();
|
|
113
|
+
}
|
|
@@ -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
|
+
}
|