@konneal/engine 0.2.135 → 0.2.137

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,15 +1,16 @@
1
1
  import {
2
2
  handleAsk
3
- } from "./chunk-27NZR4HF.js";
4
- import "./chunk-J6LBR6GI.js";
5
- import "./chunk-7AXXR7GD.js";
6
- import "./chunk-TH5XGPD5.js";
3
+ } from "./chunk-4GNKOTIK.js";
4
+ import "./chunk-GBGRHXRU.js";
5
+ import "./chunk-RKNN3WAV.js";
6
+ import "./chunk-XH5QGX2O.js";
7
+ import "./chunk-NI4CIK6W.js";
7
8
  import "./chunk-W7J5SFXJ.js";
8
9
  import "./chunk-XBZIJMS7.js";
9
10
  import "./chunk-4NXH5ZI6.js";
10
11
  import "./chunk-VT7DR6NQ.js";
11
- import "./chunk-GBGRHXRU.js";
12
12
  import "./chunk-3FYJM7LH.js";
13
+ import "./chunk-LSZTJI7V.js";
13
14
  export {
14
15
  handleAsk
15
16
  };
@@ -1,3 +1,13 @@
1
+ import {
2
+ aggregateBlock,
3
+ aggregateNote,
4
+ certificateLinks,
5
+ queryFamily,
6
+ registerAggregate,
7
+ registerAggregateIntent,
8
+ registerNote,
9
+ searchRegister
10
+ } from "./chunk-GBGRHXRU.js";
1
11
  import {
2
12
  TOOL_DECLARATION,
3
13
  bindConstraintByQuantities,
@@ -22,7 +32,7 @@ import {
22
32
  tableRetyped,
23
33
  toolNote,
24
34
  verdictNote
25
- } from "./chunk-J6LBR6GI.js";
35
+ } from "./chunk-RKNN3WAV.js";
26
36
  import {
27
37
  NO_CONTEXT,
28
38
  STAGE_NAMES,
@@ -65,13 +75,11 @@ import {
65
75
  tokenBudget,
66
76
  understandQuery,
67
77
  usageTotal
68
- } from "./chunk-7AXXR7GD.js";
78
+ } from "./chunk-XH5QGX2O.js";
69
79
  import {
70
80
  embed,
71
- generateOnce,
72
- portModelRunner,
73
- portStore
74
- } from "./chunk-TH5XGPD5.js";
81
+ generateOnce
82
+ } from "./chunk-NI4CIK6W.js";
75
83
  import {
76
84
  corsHeaders,
77
85
  err,
@@ -102,19 +110,13 @@ import {
102
110
  roleModel,
103
111
  sha256Hex
104
112
  } from "./chunk-VT7DR6NQ.js";
105
- import {
106
- aggregateBlock,
107
- aggregateNote,
108
- certificateLinks,
109
- queryFamily,
110
- registerAggregate,
111
- registerAggregateIntent,
112
- registerNote,
113
- searchRegister
114
- } from "./chunk-GBGRHXRU.js";
115
113
  import {
116
114
  P
117
115
  } from "./chunk-3FYJM7LH.js";
116
+ import {
117
+ portModelRunner,
118
+ portStore
119
+ } from "./chunk-LSZTJI7V.js";
118
120
 
119
121
  // workers/worker_public/src/internal_gateway.ts
120
122
  async function retrieveInternal(service, auth, query) {
@@ -1981,6 +1983,7 @@ async function handleAsk(env, ctx, req, tier, key) {
1981
1983
  }
1982
1984
  }
1983
1985
  let understanding = null;
1986
+ const answerCites = (t) => /\[[^\]]+\]/.test(t);
1984
1987
  const refusalScope = (cited) => ({ cited, conversational: understanding?.intent === "conversational" });
1985
1988
  let optimisticVec = null;
1986
1989
  let optimisticHits = [];
@@ -2522,32 +2525,40 @@ Answer account questions from these records ONLY: name the record when you use i
2522
2525
  await attachFigureImages(env, messages, usedHits, q.query);
2523
2526
  const pendingTools = [];
2524
2527
  let probeTokensUsed = 0;
2525
- if (multiTurn && /certificate|certified|certification/i.test(q.query) && env.DB) {
2528
+ if (multiTurn && env.DB) {
2526
2529
  try {
2527
2530
  const imageTurn = typeof withImage === "string";
2528
2531
  if (imageTurn) mark("Reading the photograph to identify the instrument");
2529
- const probeMessages = [...messages.slice(0, -1), { role: "user", content: `${TOOL_DECLARATION}
2530
-
2531
- ${imageTurn ? "A photograph of the instrument is attached after this message. Transcribe the maker, model and any printed certificate number you can read FROM THE PHOTOGRAPH ITSELF, then emit the TOOL line with those tokens as the query \u2014 never invented, and never tokens taken from any register content elsewhere in the context (a register row's holder is not the plate's maker; observed live 2026-10-04)." : ""}
2532
-
2533
- ${q.query}`.replace("\n\n\n\n", "\n\n") }];
2534
- if (imageTurn) probeMessages.push({ role: "user", content: [{ type: "image_url", image_url: { url: withImage } }] });
2535
- const probe = await env.AI.run(model, {
2536
- messages: probeMessages,
2537
- max_tokens: 600,
2538
- reasoning_effort: imageTurn ? "high" : "low"
2539
- });
2540
- const probeText = typeof probe?.response === "string" ? probe.response : probe?.choices?.[0]?.message?.content ?? "";
2541
- probeTokensUsed += usageTotal(probe?.usage) ?? 0;
2542
- const call = parseToolCall(probeText);
2543
- if (call) {
2544
- mark(`Searching the certificate register for \u201C${String(call.args?.query ?? "")}\u201D`);
2532
+ for (let round = 0; round < 3; round++) {
2533
+ const imageNote = imageTurn && round === 0 ? "A photograph of the instrument is attached after this message. Transcribe the maker, model and any printed certificate number you can read FROM THE PHOTOGRAPH ITSELF, then emit the TOOL line with those tokens as the query \u2014 never invented, and never tokens taken from any register content elsewhere in the context (a register row's holder is not the plate's maker; observed live 2026-10-04)." : "";
2534
+ const continueNote = round > 0 ? "The tool results above are in hand. Answer now without a TOOL line, or issue exactly one more TOOL line if one more query is genuinely needed." : "";
2535
+ const probeMessages = [...messages.slice(0, -1), { role: "user", content: [TOOL_DECLARATION, imageNote, continueNote, q.query].filter(Boolean).join("\n\n") }];
2536
+ if (imageTurn && round === 0) probeMessages.push({ role: "user", content: [{ type: "image_url", image_url: { url: withImage } }] });
2537
+ const probe = await env.AI.run(model, {
2538
+ messages: probeMessages,
2539
+ max_tokens: 700,
2540
+ reasoning_effort: imageTurn && round === 0 ? "high" : "low"
2541
+ });
2542
+ const probeText = typeof probe?.response === "string" ? probe?.response : probe?.choices?.[0]?.message?.content ?? "";
2543
+ probeTokensUsed += usageTotal(probe?.usage) ?? 0;
2544
+ const nativeCall = Array.isArray(probe?.tool_calls) ? probe.tool_calls[0]?.function : null;
2545
+ const call = nativeCall ? {
2546
+ name: String(nativeCall.name ?? ""),
2547
+ args: (() => {
2548
+ try {
2549
+ return typeof nativeCall.arguments === "string" ? JSON.parse(nativeCall.arguments) : nativeCall.arguments ?? {};
2550
+ } catch {
2551
+ return {};
2552
+ }
2553
+ })()
2554
+ } : parseToolCall(probeText);
2555
+ if (!call || !call.name) break;
2545
2556
  const result = await runTool(env, call);
2546
- if (result) {
2547
- messages.push({ role: "system", content: toolNote(result) });
2548
- pendingTools.push(result);
2549
- console.log("agent-tool:", result.name, JSON.stringify(result.query), "->", result.output.slice(0, 80));
2550
- }
2557
+ if (!result) break;
2558
+ mark(`${result.name} \u2014 ${result.query}`.slice(0, 140));
2559
+ messages.push({ role: "system", content: toolNote(result) });
2560
+ pendingTools.push(result);
2561
+ console.log("agent-tool:", result.name, JSON.stringify(result.query), "->", result.output.slice(0, 80));
2551
2562
  }
2552
2563
  } catch {
2553
2564
  }
@@ -2622,7 +2633,7 @@ ${q.query}`.replace("\n\n\n\n", "\n\n") }];
2622
2633
  }
2623
2634
  }
2624
2635
  }
2625
- const canonical0 = usedHits.length > 0 ? exciseMisplacedPin(canonicalRefusal(full, refusalScope(usedHits.length > 0)), true) : canonicalRefusal(full, refusalScope(false));
2636
+ const canonical0 = usedHits.length > 0 ? exciseMisplacedPin(canonicalRefusal(full, refusalScope(answerCites(full))), true) : canonicalRefusal(full, refusalScope(false));
2626
2637
  const c2 = canonical0.includes(refusalAnswer()) ? { text: canonical0, blocks: [], dropped: [] } : await contractV2(env.DB, canonical0, usedHits);
2627
2638
  send({
2628
2639
  type: "done",
@@ -2660,7 +2671,7 @@ ${q.query}`.replace("\n\n\n\n", "\n\n") }];
2660
2671
  if (streamed.violations.length > 0) {
2661
2672
  console.log("anchors:", streamed.violations.length, "of", streamed.total, "unverified \u2014 not caching");
2662
2673
  }
2663
- if (streamed.violations.length === 0 && canonical.length > 0 && !contextual && !declaredCtx && cacheableAnswer(canonical, refusalScope(usedHits.length > 0)) && !ablate) {
2674
+ if (streamed.violations.length === 0 && canonical.length > 0 && !contextual && !declaredCtx && cacheableAnswer(canonical, refusalScope(answerCites(canonical))) && !ablate) {
2664
2675
  ctx.waitUntil(
2665
2676
  env.CACHE.put(exactCacheKey(env.INDEX_VERSION, gen, ns, await sha256Hex(cacheKeyMaterial(q.query, q.lang, salt))), JSON.stringify({ answer: canonical, citations: cites, model, query_hash: queryHash, ...sourceQuality ? { source_quality: sourceQuality, confidence_note: streamedNote || qualityNote(sourceQuality) } : {}, ...streamedEntailment ? { entailment: streamedEntailment } : {} }), { expirationTtl: LIMITS.cacheTtlSec })
2666
2677
  );
@@ -2706,7 +2717,7 @@ ${q.query}`.replace("\n\n\n\n", "\n\n") }];
2706
2717
  );
2707
2718
  answer = await generateOnce(env, MODELS.fallback, flat, routeEffort(routed.route));
2708
2719
  }
2709
- if (answer) answer = canonicalRefusal(answer, refusalScope(usedHits.length > 0));
2720
+ if (answer) answer = canonicalRefusal(answer, refusalScope(answerCites(answer)));
2710
2721
  if (answer && usedHits.length > 0) answer = exciseMisplacedPin(answer, true);
2711
2722
  stageTiming.generate = Date.now() - tGen;
2712
2723
  let used = usedHits;
@@ -2731,7 +2742,7 @@ ${q.query}`.replace("\n\n\n\n", "\n\n") }];
2731
2742
  generateRetries += 1;
2732
2743
  const corrected = await generateOnce(env, model, [...messages, { role: "system", content: note }], routeEffort(routed.route));
2733
2744
  if (corrected) {
2734
- const correctedAnswer = canonicalRefusal(corrected, refusalScope(usedHits.length > 0));
2745
+ const correctedAnswer = canonicalRefusal(corrected, refusalScope(answerCites(corrected)));
2735
2746
  const retryAnchors = checkQuoteAnchors(correctedAnswer, used.map((h) => h.text));
2736
2747
  const retryRetyped = tableRetyped(correctedAnswer, hasTableUnit);
2737
2748
  if (retryAnchors.violations.length < anchors.violations.length || !retryRetyped && retyped || unreferenced && correctedAnswer.includes("[[u:")) {
@@ -2756,7 +2767,7 @@ ${q.query}`.replace("\n\n\n\n", "\n\n") }];
2756
2767
  const { messages: retryMessages, usedHits: retryUsed } = buildMessages(q.query, retryRetrieve.hits, q.lang, keptHistory, void 0, summary, budget);
2757
2768
  const retryAnswer = await generateOnce(env, model, retryMessages, routeEffort(routed.route));
2758
2769
  if (retryAnswer) {
2759
- answer = canonicalRefusal(retryAnswer, refusalScope(retryRetrieve.hits.length > 0));
2770
+ answer = canonicalRefusal(retryAnswer, refusalScope(answerCites(retryAnswer)));
2760
2771
  used = retryUsed;
2761
2772
  }
2762
2773
  }
@@ -2788,7 +2799,7 @@ ${q.query}`.replace("\n\n\n\n", "\n\n") }];
2788
2799
  messages[messages.length - 1]
2789
2800
  ], effort);
2790
2801
  if (regen && !regen.includes(refusalAnswer())) {
2791
- answer = canonicalRefusal(regen, refusalScope(true));
2802
+ answer = canonicalRefusal(regen, refusalScope(answerCites(regen)));
2792
2803
  console.log("blind-answer: regeneration grounded");
2793
2804
  }
2794
2805
  }
@@ -2808,7 +2819,7 @@ ${q.query}`.replace("\n\n\n\n", "\n\n") }];
2808
2819
  }
2809
2820
  }
2810
2821
  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: understanding?.follow_ups ?? [], blocks: [...c2ns.blocks, ...verdictBlock ? [verdictBlock] : [], ...conditionBlock ? [conditionBlock] : [], ...aggregationBlock ? [aggregationBlock] : [], ...registerBlock ? [registerBlock] : [], ...completionBlocks], context_applied: ctxApplied, ...liveRecords ? { records: liveRecords } : {}, ...ablate ? { ablate } : {}, route: { route: routed.route, features: routed.features } };
2811
- const cacheable = !contextual && !declaredCtx && !ablate && cacheableAnswer(answer, refusalScope(usedHits.length > 0)) && finalAnchors.violations.length === 0;
2822
+ const cacheable = !contextual && !declaredCtx && !ablate && cacheableAnswer(answer, refusalScope(answerCites(answer))) && finalAnchors.violations.length === 0;
2812
2823
  if (cacheable) {
2813
2824
  const ck = exactCacheKey(env.INDEX_VERSION, gen, ns, await sha256Hex(cacheKeyMaterial(q.query, q.lang, salt)));
2814
2825
  ctx.waitUntil(env.CACHE.put(ck, JSON.stringify(out), { expirationTtl: LIMITS.cacheTtlSec }));
@@ -6,10 +6,7 @@ import {
6
6
  sessionFrom,
7
7
  telemetry,
8
8
  understandQuery
9
- } from "./chunk-7AXXR7GD.js";
10
- import {
11
- portModelRunner
12
- } from "./chunk-TH5XGPD5.js";
9
+ } from "./chunk-XH5QGX2O.js";
13
10
  import {
14
11
  corsHeaders,
15
12
  err,
@@ -27,6 +24,9 @@ import {
27
24
  num,
28
25
  sha256Hex
29
26
  } from "./chunk-VT7DR6NQ.js";
27
+ import {
28
+ portModelRunner
29
+ } from "./chunk-LSZTJI7V.js";
30
30
 
31
31
  // workers/worker_public/src/search.ts
32
32
  async function handleSearch(env, ctx, req, tier, key) {
@@ -1,55 +1,3 @@
1
- import {
2
- answerEffort,
3
- effortBudget
4
- } from "./chunk-VT7DR6NQ.js";
5
-
6
- // workers/worker_public/src/ai.ts
7
- var delay = (ms) => new Promise((r) => setTimeout(r, ms));
8
- async function embed(ai, _model, text) {
9
- let lastError = null;
10
- for (let attempt = 0; attempt < 3; attempt++) {
11
- try {
12
- const vecs = await ai.embed([text]);
13
- if (vecs?.[0]?.length) return vecs[0];
14
- lastError = new Error("adapter returned no vector");
15
- } catch (e) {
16
- lastError = e;
17
- }
18
- if (attempt < 2) await delay(250 * (attempt + 1));
19
- }
20
- throw new Error(`embed failed after retries: ${String(lastError)}`);
21
- }
22
- async function rerank(ai, model, query, texts) {
23
- for (let attempt = 0; attempt < 2; attempt++) {
24
- const scores = await ai.rerank(model, query, texts);
25
- if (scores && scores.some((s) => Number.isFinite(s))) return scores;
26
- }
27
- console.error("rerank failed, using vector order");
28
- return null;
29
- }
30
- async function generateOnce(env, model, messages, effort) {
31
- for (let attempt = 0; attempt < 2; attempt++) {
32
- try {
33
- const res = await Promise.race([
34
- env.AI.run(model, {
35
- messages,
36
- max_tokens: effortBudget(effort ?? answerEffort(env)),
37
- reasoning_effort: effort ?? answerEffort(env),
38
- temperature: 0.6,
39
- top_p: 0.95
40
- }),
41
- new Promise((r) => setTimeout(() => r(null), 12e4))
42
- ]);
43
- if (typeof res?.response === "string" && res.response.trim()) return res.response;
44
- if (typeof res?.choices?.[0]?.message?.content === "string" && res.choices[0].message.content.trim()) return res.choices[0].message.content;
45
- if (attempt === 0) console.error("generate returned empty:", model);
46
- } catch (e) {
47
- console.error("generate failed:", model, String(e).slice(0, 120));
48
- }
49
- }
50
- return null;
51
- }
52
-
53
1
  // workers/worker_public/src/ports/cloudflare/adapters.ts
54
2
  var EMBED_REQUEST_SHAPES = {
55
3
  // "text" first: the verified request shape for qwen3-embedding-0.6b
@@ -166,6 +114,13 @@ function cfVectorIndex(index) {
166
114
  }
167
115
  };
168
116
  }
117
+ function cfKv(ns) {
118
+ const kv = ns;
119
+ return {
120
+ get: (key) => kv.get(key),
121
+ put: (key, value, opts) => kv.put(key, value, opts?.ttlSec ? { expirationTtl: opts.ttlSec } : void 0)
122
+ };
123
+ }
169
124
  function cfBlobs(bucket) {
170
125
  const r2 = bucket;
171
126
  return {
@@ -185,6 +140,14 @@ function cfBlobs(bucket) {
185
140
  function cfStore(db) {
186
141
  return db;
187
142
  }
143
+ function cfRuntime(ctx) {
144
+ return {
145
+ defer(fn) {
146
+ if (ctx) ctx.waitUntil(fn());
147
+ else void fn();
148
+ }
149
+ };
150
+ }
188
151
 
189
152
  // workers/worker_public/src/env.ts
190
153
  function portModelRunner(env) {
@@ -194,6 +157,12 @@ function portIndex(env, which = "public") {
194
157
  const b = which === "public" ? env.VECTORIZE : which === "primmel" ? env.EXP_PRIMMEL : which === "composed" ? env.EXP_COMPOSED : which === "plain" ? env.EXP_PLAIN : which === "adoc" ? env.EXP_ADC : which === "mko" ? env.EXP_MKO : which === "pflat" ? env.EXP_PFLAT : env.GLOSSARY;
195
158
  return cfVectorIndex(b);
196
159
  }
160
+ function portKv(env) {
161
+ return cfKv(env.CACHE);
162
+ }
163
+ function portBlobs(env) {
164
+ return cfBlobs(env.UNIT_ASSETS);
165
+ }
197
166
  function portStore(env) {
198
167
  return cfStore(env.DB);
199
168
  }
@@ -203,14 +172,17 @@ function hasLane(env, which) {
203
172
  return !!env.GLOSSARY;
204
173
  }
205
174
  }
175
+ function portRuntime(ctx) {
176
+ return cfRuntime(ctx);
177
+ }
206
178
 
207
179
  export {
208
- embed,
209
- rerank,
210
- generateOnce,
211
180
  cfBlobs,
212
181
  portModelRunner,
213
182
  portIndex,
183
+ portKv,
184
+ portBlobs,
214
185
  portStore,
215
- hasLane
186
+ hasLane,
187
+ portRuntime
216
188
  };
@@ -0,0 +1,57 @@
1
+ import {
2
+ answerEffort,
3
+ effortBudget
4
+ } from "./chunk-VT7DR6NQ.js";
5
+
6
+ // workers/worker_public/src/ai.ts
7
+ var delay = (ms) => new Promise((r) => setTimeout(r, ms));
8
+ async function embed(ai, _model, text) {
9
+ let lastError = null;
10
+ for (let attempt = 0; attempt < 3; attempt++) {
11
+ try {
12
+ const vecs = await ai.embed([text]);
13
+ if (vecs?.[0]?.length) return vecs[0];
14
+ lastError = new Error("adapter returned no vector");
15
+ } catch (e) {
16
+ lastError = e;
17
+ }
18
+ if (attempt < 2) await delay(250 * (attempt + 1));
19
+ }
20
+ throw new Error(`embed failed after retries: ${String(lastError)}`);
21
+ }
22
+ async function rerank(ai, model, query, texts) {
23
+ for (let attempt = 0; attempt < 2; attempt++) {
24
+ const scores = await ai.rerank(model, query, texts);
25
+ if (scores && scores.some((s) => Number.isFinite(s))) return scores;
26
+ }
27
+ console.error("rerank failed, using vector order");
28
+ return null;
29
+ }
30
+ async function generateOnce(env, model, messages, effort) {
31
+ for (let attempt = 0; attempt < 2; attempt++) {
32
+ try {
33
+ const res = await Promise.race([
34
+ env.AI.run(model, {
35
+ messages,
36
+ max_tokens: effortBudget(effort ?? answerEffort(env)),
37
+ reasoning_effort: effort ?? answerEffort(env),
38
+ temperature: 0.6,
39
+ top_p: 0.95
40
+ }),
41
+ new Promise((r) => setTimeout(() => r(null), 12e4))
42
+ ]);
43
+ if (typeof res?.response === "string" && res.response.trim()) return res.response;
44
+ if (typeof res?.choices?.[0]?.message?.content === "string" && res.choices[0].message.content.trim()) return res.choices[0].message.content;
45
+ if (attempt === 0) console.error("generate returned empty:", model);
46
+ } catch (e) {
47
+ console.error("generate failed:", model, String(e).slice(0, 120));
48
+ }
49
+ }
50
+ return null;
51
+ }
52
+
53
+ export {
54
+ embed,
55
+ rerank,
56
+ generateOnce
57
+ };