@konneal/engine 0.2.187 → 0.2.189

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/dist/ai.d.ts +7 -0
  2. package/dist/ask-LPNODCPM.js +16 -0
  3. package/dist/{chunk-IZ3GSYMD.js → chunk-22WB6IVC.js} +35 -30
  4. package/dist/{chunk-VDFOVWE6.js → chunk-5PKKAHY4.js} +5 -5
  5. package/dist/{chunk-MZQEI4VJ.js → chunk-7YMIUTPY.js} +1 -1
  6. package/dist/{chunk-BAOKHV2D.js → chunk-AVNHVFEB.js} +29 -6
  7. package/dist/{chunk-BMODSEKT.js → chunk-ECNBEZGK.js} +5 -5
  8. package/dist/{chunk-IDQND3AA.js → chunk-FCRTWZQE.js} +128 -31
  9. package/dist/{chunk-TLPUJMAF.js → chunk-GJQT4IMD.js} +1 -1
  10. package/dist/{chunk-YGQCVPX6.js → chunk-H6ZULBW2.js} +4 -1
  11. package/dist/{chunk-RBRBQJYT.js → chunk-Q7QL3457.js} +58 -44
  12. package/dist/config.d.ts +17 -11
  13. package/dist/context.d.ts +14 -0
  14. package/dist/docOverview.d.ts +35 -0
  15. package/dist/{env-BZWHCSCL.js → env-4LR6Y5CC.js} +1 -1
  16. package/dist/nameplate.d.ts +1 -1
  17. package/dist/prompts/understanding.md +2 -1
  18. package/dist/reflect.d.ts +1 -1
  19. package/dist/search-DE5ADCVM.js +14 -0
  20. package/dist/{tools-VMZSXLXM.js → tools-7GKMDWVB.js} +5 -5
  21. package/dist/understandContract.d.ts +3 -0
  22. package/dist/worker_mcp/src/index.js +2 -2
  23. package/dist/worker_public/src/config.js +3 -1
  24. package/dist/worker_public/src/index.js +11 -11
  25. package/dist/worker_public/src/requestScope.js +2 -2
  26. package/package.json +1 -1
  27. package/workers/worker_public/prompts/understanding.md +2 -1
  28. package/workers/worker_public/src/ai.ts +32 -9
  29. package/workers/worker_public/src/ask.ts +90 -23
  30. package/workers/worker_public/src/config.ts +44 -29
  31. package/workers/worker_public/src/context.ts +14 -0
  32. package/workers/worker_public/src/docOverview.ts +77 -0
  33. package/workers/worker_public/src/faithfulness.ts +11 -1
  34. package/workers/worker_public/src/lexical.ts +21 -19
  35. package/workers/worker_public/src/ports/cloudflare/adapters.ts +4 -2
  36. package/workers/worker_public/src/reflect.ts +8 -7
  37. package/workers/worker_public/src/stages/dense.ts +29 -42
  38. package/workers/worker_public/src/stages/glossary.ts +1 -1
  39. package/workers/worker_public/src/stages/rerank.ts +6 -2
  40. package/workers/worker_public/src/understand.ts +6 -6
  41. package/workers/worker_public/src/understandContract.ts +4 -0
  42. package/dist/ask-O7HJIZPK.js +0 -16
  43. package/dist/search-3H2ENWHQ.js +0 -14
package/dist/ai.d.ts CHANGED
@@ -1,6 +1,13 @@
1
1
  import type { ModelRunner } from "./ports/model.ts";
2
2
  type AnyAi = ModelRunner;
3
3
  export declare function embed(ai: ModelRunner, _model: string, text: string): Promise<number[]>;
4
+ /** The platform's per-minute inference allowance (3021) and its capacity
5
+ * signal (3040) reset with the minute: an immediate retry hits the same
6
+ * wall, so the caller waits before trying again. Measured 2026-12-03 —
7
+ * with every generation role on one model, two parallel question streams
8
+ * exhausted it and half the judging calls failed. */
9
+ export declare function isCapacityError(e: unknown): boolean;
10
+ export declare const CAPACITY_PAUSE_MS = 15000;
4
11
  export declare function rerank(ai: AnyAi, model: string, query: string, texts: string[]): Promise<number[] | null>;
5
12
  export declare function generateOnce(env: any, model: string, messages: any[], effort?: string): Promise<string | null>;
6
13
  export {};
@@ -0,0 +1,16 @@
1
+ import {
2
+ handleAsk
3
+ } from "./chunk-FCRTWZQE.js";
4
+ import "./chunk-IRCDOFP4.js";
5
+ import "./chunk-ECNBEZGK.js";
6
+ import "./chunk-Q7QL3457.js";
7
+ import "./chunk-AVNHVFEB.js";
8
+ import "./chunk-GJQT4IMD.js";
9
+ import "./chunk-ETLSWSZ7.js";
10
+ import "./chunk-7YMIUTPY.js";
11
+ import "./chunk-22WB6IVC.js";
12
+ import "./chunk-3FYJM7LH.js";
13
+ import "./chunk-H6ZULBW2.js";
14
+ export {
15
+ handleAsk
16
+ };
@@ -3,53 +3,59 @@ import {
3
3
  } from "./chunk-3FYJM7LH.js";
4
4
 
5
5
  // workers/worker_public/src/config.ts
6
+ var FLASH = "@cf/deepseek-ai/deepseek-v4.1-flash-1017";
6
7
  var MODELS = {
7
8
  embed: "@cf/qwen/qwen3-embedding-0.6b",
8
9
  rerank: "@cf/baai/bge-reranker-base",
9
- // ANSWER MODEL (all tiers, user decision 2026-08-29): glm-5.3-flash —
10
- // natively multimodal (vision-unified contract), GLM family, flash tier.
11
- // Vision image-parts land with answer contract v2; text answers work now.
12
- anon: "@cf/zai-org/glm-5.3-flash",
13
- member: "@cf/zai-org/glm-5.3-flash",
10
+ // ANSWER MODEL (all tiers): natively multimodal (vision-unified contract)
11
+ anon: FLASH,
12
+ member: FLASH,
14
13
  // figure captions + the vision lane (one-time, quality-first; the A/B
15
14
  // lever is CAPTION_MODEL, the per-request arm is the admin route's
16
- // body.model)
17
- caption: "@cf/zai-org/glm-5.3-flash",
18
- // the pairwise vision judge (sees the image; a THIRD model never
19
- // judges its own arm)
20
- visionJudge: "@cf/deepseek-ai/deepseek-v4.1-flash-1017",
21
- // the VLM figure rerank (TODO.sota/18.3): the newly-landed
22
- // vision-capable MoE scores figure IMAGES against figure-seeking
23
- // questions — one bounded call per figure question, ablatable stage
24
- vlmFigure: "@cf/deepseek-ai/deepseek-v4.1-flash-1017",
15
+ // body.model). It emptied on 8/24 figure images in the 2026-10-27 A/B —
16
+ // those captions fall to the serve-raw path.
17
+ caption: FLASH,
18
+ // the pairwise vision judge (sees the image; a THIRD model never judges
19
+ // its own arm) — no other live multimodal model exists in the policy
20
+ // line, so a v4.1 caption arm is judged by its own family
21
+ visionJudge: FLASH,
22
+ // the VLM figure rerank (TODO.sota/18.3): a vision-capable MoE scores
23
+ // figure IMAGES against figure-seeking questions — one bounded call per
24
+ // figure question, ablatable stage
25
+ vlmFigure: FLASH,
25
26
  // the decision pass (TODO.decisions/01): clef-flash gates the
26
27
  // requirement-shaped questions, clef decides the derived checklist
27
28
  decisionsGate: "@cf/cloudflare/clef-flash",
28
29
  decisionsModel: "@cf/cloudflare/clef",
29
- // hot-path understanding/summarize stays on the cheap Qwen (cost-first lane)
30
- understand: "@cf/qwen/qwen3-30b-a3b-fp8",
30
+ // hot-path understanding/summarize (cost-first lane)
31
+ understand: FLASH,
31
32
  // the api_call act's intent-to-act mapping (TODO.ai-platform/09) — the
32
33
  // operations deployment points ACTS_MODEL at the stronger reasoning
33
34
  // tier; the floor is the understand lane
34
- acts: "@cf/qwen/qwen3-30b-a3b-fp8",
35
- // generation fallback when the answer model is unavailable
36
- fallback: "@cf/qwen/qwen3-30b-a3b-fp8",
37
- grader: "@cf/deepseek-ai/deepseek-v4-flash-0731",
38
- // CRAG grader + judges (unsuffixed slug was retired → silent 5018s)
35
+ acts: FLASH,
36
+ // generation fallback when the answer model is unavailable. A fallback
37
+ // has to be ANOTHER model — as the primary's own twin (0.2.188) it added
38
+ // nothing to the retry inside generateOnce. glm-5.3 is a different
39
+ // family and fast; its flagship price only applies on the rare path
40
+ // where the primary failed. Text-only: the call sites flatten image
41
+ // parts before handing messages to it.
42
+ fallback: "@cf/zai-org/glm-5.3",
43
+ grader: FLASH,
44
+ // CRAG grader + judges
39
45
  // contextual enrichment is the QUALITY-FIRST lane (one-time spend over
40
46
  // the corpus, its quality persists into every future retrieval)
41
- enrich: "@cf/deepseek-ai/deepseek-v4-pro-0813",
47
+ enrich: "@cf/zai-org/glm-5.3",
42
48
  // final-tier listwise reranker for hard/member queries (cascade:
43
49
  // cross-encoder prunes, listwise orders jointly)
44
50
  listwise: "@cf/zai-org/glm-4.7-flash",
45
51
  // deep-research loop (G10): bounded agentic iterations, members-only
46
- escalation: "@cf/deepseek-ai/deepseek-v4.1-flash-1017",
47
- research: "@cf/zai-org/glm-5.3-flash",
52
+ escalation: FLASH,
53
+ research: FLASH,
48
54
  // speculative draft-verify (TODO.sota/02 row 2): the strong verifier
49
55
  // over the cheap drafts — the research-tier model verifies; the drafter
50
56
  // is the standard answer model (MODELS.member). VERIFIER_MODEL swaps it
51
57
  // live, same lever as every role.
52
- verifier: "@cf/zai-org/glm-5.2"
58
+ verifier: "@cf/zai-org/glm-5.3"
53
59
  };
54
60
  var LIMITS = {
55
61
  /** Attachment quotas (TODO.new-era/8): per-member ceilings so a member's
@@ -100,11 +106,6 @@ var THRESHOLDS = {
100
106
  // the extractive compression arm (TODO.sota/02 row 5): when ablated
101
107
  // on, each passage body is compressed to this share of its budget
102
108
  compressShare: 0.6,
103
- // the dense scope's starvation fallback (the R 134-2 figure question):
104
- // when the in-code doc scope cuts the vector-level top-K to zero, the
105
- // re-query runs at this depth and scopes in code (the native filter is
106
- // dead — measured 2026-10-05)
107
- denseStarveK: 100,
108
109
  // the decision pass (TODO.decisions): the gate fires at decisionsGateMin
109
110
  // noul; the bands assemble met / not clearly stated / not met
110
111
  decisionsGateMin: 0.5,
@@ -199,6 +200,9 @@ function effortBudget(effort) {
199
200
  if (effort === "high" || effort === "max") return LIMITS.maxOutputTokens * 4;
200
201
  return LIMITS.maxOutputTokens;
201
202
  }
203
+ function generationSampling(model) {
204
+ return model.includes("deepseek") ? { temperature: 1, top_p: 1 } : { temperature: 0.6, top_p: 0.95 };
205
+ }
202
206
  function requestEffort(env, session, requested) {
203
207
  if (typeof requested !== "string" || !EFFORTS.has(requested)) return answerEffort(env);
204
208
  if (requested === "low") return requested;
@@ -253,6 +257,7 @@ export {
253
257
  roleModel,
254
258
  answerEffort,
255
259
  effortBudget,
260
+ generationSampling,
256
261
  requestEffort,
257
262
  DATASETS,
258
263
  hasPermission,
@@ -6,27 +6,27 @@ import {
6
6
  sessionFrom,
7
7
  telemetry,
8
8
  understandQuery
9
- } from "./chunk-RBRBQJYT.js";
9
+ } from "./chunk-Q7QL3457.js";
10
10
  import {
11
11
  corsHeaders,
12
12
  err,
13
13
  json,
14
14
  readJson,
15
15
  validateQuery
16
- } from "./chunk-TLPUJMAF.js";
16
+ } from "./chunk-GJQT4IMD.js";
17
17
  import {
18
18
  entitlementScope,
19
19
  standardKeysFrom
20
- } from "./chunk-MZQEI4VJ.js";
20
+ } from "./chunk-7YMIUTPY.js";
21
21
  import {
22
22
  LIMITS,
23
23
  MODELS,
24
24
  num,
25
25
  sha256Hex
26
- } from "./chunk-IZ3GSYMD.js";
26
+ } from "./chunk-22WB6IVC.js";
27
27
  import {
28
28
  portModelRunner
29
- } from "./chunk-YGQCVPX6.js";
29
+ } from "./chunk-H6ZULBW2.js";
30
30
 
31
31
  // workers/worker_public/src/search.ts
32
32
  async function handleSearch(env, ctx, req, tier, key) {
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  DATASETS,
3
3
  datasetAllowed
4
- } from "./chunk-IZ3GSYMD.js";
4
+ } from "./chunk-22WB6IVC.js";
5
5
  import {
6
6
  P
7
7
  } from "./chunk-3FYJM7LH.js";
@@ -1,7 +1,8 @@
1
1
  import {
2
2
  answerEffort,
3
- effortBudget
4
- } from "./chunk-IZ3GSYMD.js";
3
+ effortBudget,
4
+ generationSampling
5
+ } from "./chunk-22WB6IVC.js";
5
6
 
6
7
  // workers/worker_public/src/ai.ts
7
8
  var delay = (ms) => new Promise((r) => setTimeout(r, ms));
@@ -19,10 +20,30 @@ async function embed(ai, _model, text) {
19
20
  }
20
21
  throw new Error(`embed failed after retries: ${String(lastError)}`);
21
22
  }
23
+ function isCapacityError(e) {
24
+ return /3021|rate limit|3040|capacity/i.test(String(e));
25
+ }
26
+ var CAPACITY_PAUSE_MS = 15e3;
22
27
  async function rerank(ai, model, query, texts) {
28
+ const idx = [];
29
+ const nonEmpty = [];
30
+ for (let i = 0; i < texts.length; i++) {
31
+ if (typeof texts[i] === "string" && texts[i].trim().length > 0) {
32
+ idx.push(i);
33
+ nonEmpty.push(texts[i]);
34
+ }
35
+ }
36
+ if (!nonEmpty.length) return null;
23
37
  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;
38
+ const scores = await ai.rerank(model, query, nonEmpty);
39
+ if (scores && scores.some((s) => Number.isFinite(s))) {
40
+ if (idx.length === texts.length) return scores;
41
+ const out = new Array(texts.length).fill(NaN);
42
+ idx.forEach((orig, k) => {
43
+ out[orig] = scores[k];
44
+ });
45
+ return out;
46
+ }
26
47
  }
27
48
  console.error("rerank failed, using vector order");
28
49
  return null;
@@ -35,8 +56,7 @@ async function generateOnce(env, model, messages, effort) {
35
56
  messages,
36
57
  max_tokens: effortBudget(effort ?? answerEffort(env)),
37
58
  reasoning_effort: effort ?? answerEffort(env),
38
- temperature: 0.6,
39
- top_p: 0.95
59
+ ...generationSampling(model)
40
60
  }),
41
61
  new Promise((r) => setTimeout(() => r(null), 12e4))
42
62
  ]);
@@ -45,6 +65,7 @@ async function generateOnce(env, model, messages, effort) {
45
65
  if (attempt === 0) console.error("generate returned empty:", model);
46
66
  } catch (e) {
47
67
  console.error("generate failed:", model, String(e).slice(0, 120));
68
+ if (attempt === 0 && isCapacityError(e)) await delay(CAPACITY_PAUSE_MS);
48
69
  }
49
70
  }
50
71
  return null;
@@ -52,6 +73,8 @@ async function generateOnce(env, model, messages, effort) {
52
73
 
53
74
  export {
54
75
  embed,
76
+ isCapacityError,
77
+ CAPACITY_PAUSE_MS,
55
78
  rerank,
56
79
  generateOnce
57
80
  };
@@ -1,12 +1,12 @@
1
1
  import {
2
2
  embed
3
- } from "./chunk-BAOKHV2D.js";
3
+ } from "./chunk-AVNHVFEB.js";
4
4
  import {
5
5
  standardKeysFrom
6
- } from "./chunk-MZQEI4VJ.js";
6
+ } from "./chunk-7YMIUTPY.js";
7
7
  import {
8
8
  THRESHOLDS
9
- } from "./chunk-IZ3GSYMD.js";
9
+ } from "./chunk-22WB6IVC.js";
10
10
  import {
11
11
  P
12
12
  } from "./chunk-3FYJM7LH.js";
@@ -15,7 +15,7 @@ import {
15
15
  portIndex,
16
16
  portModelRunner,
17
17
  portStore
18
- } from "./chunk-YGQCVPX6.js";
18
+ } from "./chunk-H6ZULBW2.js";
19
19
 
20
20
  // workers/worker_public/src/refs.ts
21
21
  var REF = /\[\[(u:(?:u:)?[A-Za-z0-9_-]+)\]\]/g;
@@ -1509,7 +1509,7 @@ async function runFind(env, args) {
1509
1509
  };
1510
1510
  }
1511
1511
  try {
1512
- const { portStore: portStore2 } = await import("./env-BZWHCSCL.js");
1512
+ const { portStore: portStore2 } = await import("./env-4LR6Y5CC.js");
1513
1513
  const res = await portStore2(env).prepare(compiled.sql).bind(...compiled.params).all();
1514
1514
  const rows = res?.results ?? [];
1515
1515
  const body = rows.length ? rows.map((r) => JSON.stringify(r)).join("\n") : "No rows matched. Either the predicates are too narrow or the data is absent \u2014 state which, and consider widening.";
@@ -33,7 +33,7 @@ import {
33
33
  tableRetyped,
34
34
  toolNote,
35
35
  verdictNote
36
- } from "./chunk-BMODSEKT.js";
36
+ } from "./chunk-ECNBEZGK.js";
37
37
  import {
38
38
  NO_CONTEXT,
39
39
  STAGE_NAMES,
@@ -57,6 +57,7 @@ import {
57
57
  liveDataConfig,
58
58
  liveTokenFor,
59
59
  machineOffers,
60
+ matchesDocScope,
60
61
  namedDocumentIn,
61
62
  opCfg,
62
63
  opTokenMember,
@@ -76,18 +77,20 @@ import {
76
77
  tokenBudget,
77
78
  understandQuery,
78
79
  usageTotal
79
- } from "./chunk-RBRBQJYT.js";
80
+ } from "./chunk-Q7QL3457.js";
80
81
  import {
82
+ CAPACITY_PAUSE_MS,
81
83
  embed,
82
- generateOnce
83
- } from "./chunk-BAOKHV2D.js";
84
+ generateOnce,
85
+ isCapacityError
86
+ } from "./chunk-AVNHVFEB.js";
84
87
  import {
85
88
  corsHeaders,
86
89
  err,
87
90
  json,
88
91
  readJson,
89
92
  validateQuery
90
- } from "./chunk-TLPUJMAF.js";
93
+ } from "./chunk-GJQT4IMD.js";
91
94
  import {
92
95
  cacheableAnswer,
93
96
  canonicalRefusal,
@@ -100,7 +103,7 @@ import {
100
103
  requestSalt,
101
104
  resolveRequestScope,
102
105
  standardKeysFrom
103
- } from "./chunk-MZQEI4VJ.js";
106
+ } from "./chunk-7YMIUTPY.js";
104
107
  import {
105
108
  ESCALATION_DAILY_DEFAULT,
106
109
  LIMITS,
@@ -108,11 +111,12 @@ import {
108
111
  THRESHOLDS,
109
112
  answerEffort,
110
113
  effortBudget,
114
+ generationSampling,
111
115
  num,
112
116
  requestEffort,
113
117
  roleModel,
114
118
  sha256Hex
115
- } from "./chunk-IZ3GSYMD.js";
119
+ } from "./chunk-22WB6IVC.js";
116
120
  import {
117
121
  P
118
122
  } from "./chunk-3FYJM7LH.js";
@@ -122,7 +126,7 @@ import {
122
126
  cfVectorIndex,
123
127
  portModelRunner,
124
128
  portStore
125
- } from "./chunk-YGQCVPX6.js";
129
+ } from "./chunk-H6ZULBW2.js";
126
130
 
127
131
  // workers/worker_public/src/internal_gateway.ts
128
132
  async function retrieveInternal(service, auth, query) {
@@ -261,9 +265,13 @@ var summarize_default = "Summarize this conversation so a Q&A assistant can cont
261
265
  var reflect_default = 'You are a factuality critic. Given a question, an answer, and the passages the answer was based on, determine if every factual claim in the answer is directly supported by the passages. Reply with ONLY: {"grounded": true} or {"grounded": false, "missing_info": "what is missing"}\n';
262
266
 
263
267
  // workers/worker_public/src/reflect.ts
264
- async function reflect(ai, model, question, answer, passages) {
268
+ async function reflect(ai, model, question, answer, passages, notes) {
265
269
  if (!answer || !passages.length) return null;
266
- const ctx = passages.slice(0, 8).map((p, i) => `[${i + 1}] ${p.replace(/\s+/g, " ").slice(0, 300)}`).join("\n");
270
+ const ctx = passages.slice(0, 8).map((p, i) => `[${i + 1}] ${p.replace(/\s+/g, " ").slice(0, 900)}`).join("\n");
271
+ const noteBlock = notes?.trim() ? `
272
+
273
+ Authoritative notes:
274
+ ${notes.trim().slice(0, 1500)}` : "";
267
275
  const timeout = new Promise((r) => setTimeout(() => r(null), 6e3));
268
276
  const call = (async () => {
269
277
  const res = await ai.run(model, {
@@ -280,16 +288,12 @@ Answer:
280
288
  ${answer.slice(0, 1500)}
281
289
 
282
290
  Passages:
283
- ${ctx}`
291
+ ${ctx}${noteBlock}`
284
292
  }
285
293
  ],
286
- // reasoning shares this budget — starved budgets silently disable
287
- // the reflection layer (null = no retry ever fires); DeepSeek-V4
288
- // card: keep reasoning on with headroom + temp 1.0 / top_p 1.0
289
294
  max_tokens: 3072,
290
295
  reasoning_effort: "low",
291
- temperature: 1,
292
- top_p: 1
296
+ ...generationSampling(model)
293
297
  });
294
298
  const text = typeof res?.response === "string" ? res.response : res?.choices?.[0]?.message?.content;
295
299
  const m = (text ?? "").match(/\{[\s\S]*\}/);
@@ -420,7 +424,12 @@ ${context}${machine.length ? buildJudgeContext([], machine) : ""}` }
420
424
  }
421
425
  return verdict;
422
426
  })();
423
- return await Promise.race([call, timeout]);
427
+ try {
428
+ return await Promise.race([call, timeout]);
429
+ } catch (e) {
430
+ console.error("faithfulness: judge failed \u2014", String(e).slice(0, 140));
431
+ return null;
432
+ }
424
433
  }
425
434
 
426
435
  // workers/worker_public/src/entailment.ts
@@ -448,6 +457,38 @@ function checkQuoteAnchors(answer, passages) {
448
457
  }
449
458
  var ANCHOR_CORRECTION_NOTE = "Correction notice: your draft quoted text that does not appear verbatim in the provided passages. Rewrite the answer \u2014 every quoted phrase must be an exact copy from a passage, or cite the clause without quoting.";
450
459
 
460
+ // workers/worker_public/src/docOverview.ts
461
+ function identKey(docidentifier) {
462
+ const m = String(docidentifier ?? "").replace(/\s*\([A-Z]\)\s*$/, "").replace(/:\d+$/, "").match(/([A-Z])\s*-?\s*(\d+(?:-[A-Za-z0-9]+)?)\s*$/i);
463
+ return m ? `${m[1].toLowerCase()} ${m[2].toLowerCase()}` : null;
464
+ }
465
+ var baseOf = (key) => key.split(" ")[1].split("-")[0];
466
+ function isNamedDocumentPassage(meta, docNumber, docidentifier) {
467
+ const named = identKey(docidentifier);
468
+ const own = identKey(meta.docidentifier);
469
+ if (!named || !own) return matchesDocScope(meta, named?.split(" ")[1] ?? docNumber);
470
+ const [namedType, namedNum] = named.split(" ");
471
+ const [ownType, ownNum] = own.split(" ");
472
+ if (namedType !== ownType) return false;
473
+ return namedNum.includes("-") ? ownNum === namedNum : baseOf(named) === baseOf(own);
474
+ }
475
+ function inScopePassages(used, docNumber, docidentifier) {
476
+ let n = 0;
477
+ for (const h of used) if (h.metadata && isNamedDocumentPassage(h.metadata, docNumber, docidentifier)) n += 1;
478
+ return n;
479
+ }
480
+ function docOverviewRefusal(args) {
481
+ const { answer, refusal: refusal3, understanding, used } = args;
482
+ if (!understanding?.doc_overview) return false;
483
+ const docNumber = understanding.doc_number;
484
+ if (!docNumber) return false;
485
+ return answer.includes(refusal3) && inScopePassages(used, docNumber, understanding.docidentifier) > 0;
486
+ }
487
+ function docOverviewInstruction(docidentifier) {
488
+ const doc = docidentifier.trim();
489
+ return `The passages above include ${doc}'s own text, and the question asks what ${doc} is. Answer it from those passages \u2014 what the publication is, what it specifies or covers \u2014 citing a passage for each claim. Only say the information is missing if none of the ${doc} passages describes the publication.`;
490
+ }
491
+
451
492
  // workers/worker_public/src/completion.ts
452
493
  async function completeTables(db, answer, used) {
453
494
  const blocks = [];
@@ -2296,13 +2337,13 @@ async function generateStream(env, model, messages, effort) {
2296
2337
  stream: true,
2297
2338
  max_tokens: effortBudget(effort ?? answerEffort(env)),
2298
2339
  reasoning_effort: effort ?? answerEffort(env),
2299
- temperature: 0.6,
2300
- top_p: 0.95
2340
+ ...generationSampling(model)
2301
2341
  });
2302
2342
  if (res && typeof res.getReader === "function") return res;
2303
2343
  if (res && res.body && typeof res.body.getReader === "function") return res.body;
2304
2344
  } catch (e) {
2305
2345
  console.error("stream failed:", model, String(e).slice(0, 120));
2346
+ if (attempt === 0 && isCapacityError(e)) await new Promise((r) => setTimeout(r, CAPACITY_PAUSE_MS));
2306
2347
  }
2307
2348
  }
2308
2349
  return null;
@@ -2318,13 +2359,14 @@ async function summarizeHistory(env, model, turns) {
2318
2359
  },
2319
2360
  { role: "user", content: convo }
2320
2361
  ],
2321
- max_tokens: 2048,
2362
+ // reasoning tokens share this budget — DeepSeek-V4 needs 3072+ or
2363
+ // the summary is never reached
2364
+ max_tokens: model.includes("deepseek") ? 3072 : 2048,
2322
2365
  reasoning_effort: "low",
2366
+ ...generationSampling(model),
2323
2367
  // Qwen3 thinking-mode sampling (model card) — prevents the
2324
2368
  // repetition loops that eat the budget before the summary lands
2325
- temperature: 0.6,
2326
- top_p: 0.95,
2327
- top_k: 20
2369
+ ...model.includes("deepseek") ? {} : { top_k: 20 }
2328
2370
  });
2329
2371
  const text = typeof res?.response === "string" ? res.response : res?.choices?.[0]?.message?.content;
2330
2372
  return typeof text === "string" && text.trim() ? text.trim().slice(0, 1200) : null;
@@ -3074,7 +3116,7 @@ Answer account questions from these records ONLY: name the record when you use i
3074
3116
  if (grade === "weak" && understanding?.docidentifier) {
3075
3117
  const broaden = `${understanding.standalone_query || q2.query} ${understanding.docidentifier}`.trim();
3076
3118
  const tc = Date.now();
3077
- const second = await retrieve(env, q2.query, { prev, understanding, queryOverride: broaden, federate, userDocs, datasetScope: narrowed ? corpora : null, standardKeys, sealScope: declaredScoped ? docScope : null, lexicalBoost, ...routeSubset ? { stageSubset: routeSubset } : {} });
3119
+ const second = await retrieve(env, q2.query, { prev, understanding, queryOverride: broaden, federate, userDocs, datasetScope: narrowed ? corpora : null, standardKeys, sealScope: declaredScoped ? docScope : null, lexicalBoost, licensedDocNumbers, ...routeSubset ? { stageSubset: routeSubset } : {} });
3078
3120
  const grade2 = await gradeRetrieval(env.AI, roleModel(env, "grader"), q2.query, second.hits.map((h) => h.text));
3079
3121
  stageTiming.corrective = Date.now() - tc;
3080
3122
  if (grade2 === "good") retrieved = second;
@@ -3140,13 +3182,14 @@ Answer account questions from these records ONLY: name the record when you use i
3140
3182
  text: `${m.anchor} \u2014 ${m.text}`
3141
3183
  }));
3142
3184
  const passagePool = registerOwns ? [...opsHits, ...hits].filter((h) => !!h.metadata.cert_holder) : [...opsHits, ...hits];
3185
+ const baseNotes = [ops.note, processNote, eNote, regNote, memberDocNote, contextNote(declaredCtx, docScope), accountNote, modelNote, vocabNote, memNote, machineNote, conditionNote, aggregationNote, boundaryNote, licenseNote];
3186
+ const promptNotes = [...baseNotes, ...retrieved.notes ?? []].filter(Boolean).join("\n") || void 0;
3143
3187
  const built = buildMessages(
3144
3188
  q2.query,
3145
3189
  passagePool,
3146
3190
  q2.lang,
3147
3191
  keptHistory,
3148
- // stage-extracted graph facts (GraphRAG) ride the same note channel
3149
- [ops.note, processNote, eNote, regNote, memberDocNote, contextNote(declaredCtx, docScope), accountNote, modelNote, vocabNote, memNote, machineNote, conditionNote, aggregationNote, boundaryNote, licenseNote, ...retrieved.notes ?? []].filter(Boolean).join("\n") || void 0,
3192
+ promptNotes,
3150
3193
  summary,
3151
3194
  budget,
3152
3195
  ablate?.noCompress !== true
@@ -3323,6 +3366,31 @@ ${doc.text}` }
3323
3366
  }
3324
3367
  }
3325
3368
  }
3369
+ if (!escalateAnswer && docOverviewRefusal({ answer: full, refusal: refusalAnswer(), understanding, used: usedHits })) {
3370
+ console.log("blind-answer(doc, stream): the named document's passages were in the prompt but the answer refused \u2014 regenerating once");
3371
+ streamRestarts += 1;
3372
+ mark("Re-answering from the document's passages");
3373
+ send({ type: "retry" });
3374
+ const regen = await generateStream(env, model, [
3375
+ ...messages.slice(0, -1),
3376
+ { role: "user", content: docOverviewInstruction(understanding.docidentifier ?? understanding.doc_number) },
3377
+ messages[messages.length - 1]
3378
+ ], routeEffort(routed.route));
3379
+ if (regen) {
3380
+ let replaced = false;
3381
+ try {
3382
+ for await (const tok of sseTokens(regen)) {
3383
+ if (!replaced) {
3384
+ full = "";
3385
+ replaced = true;
3386
+ }
3387
+ full += tok;
3388
+ send({ type: "token", v: tok });
3389
+ }
3390
+ } catch {
3391
+ }
3392
+ }
3393
+ }
3326
3394
  if (escalateAnswer && escalatedDoc && !full.includes(refusalAnswer())) {
3327
3395
  const verdict = verifyAnchors(full, escalatedDoc.clauses);
3328
3396
  if (!verdict.ok) {
@@ -3479,6 +3547,22 @@ ${doc.text}` }
3479
3547
  if (answer) answer = canonicalRefusal(answer, refusalScope(answerCites(answer)));
3480
3548
  if (answer) answer = scrubToolLines(answer);
3481
3549
  if (answer) answer = exciseMisplacedPin(answer, answerCites(answer));
3550
+ if (answer && !escalateAnswer && docOverviewRefusal({ answer, refusal: refusalAnswer(), understanding, used: usedHits })) {
3551
+ console.log("blind-answer(doc): the named document's passages were in the prompt but the answer refused \u2014 regenerating once");
3552
+ generateRetries += 1;
3553
+ const regen = await generateOnce(env, model, [
3554
+ ...messages.slice(0, -1),
3555
+ { role: "user", content: docOverviewInstruction(understanding.docidentifier ?? understanding.doc_number) },
3556
+ messages[messages.length - 1]
3557
+ ], routeEffort(routed.route));
3558
+ if (regen) {
3559
+ const grounded = exciseMisplacedPin(canonicalRefusal(scrubToolLines(regen), refusalScope(answerCites(regen))), answerCites(regen));
3560
+ if (!grounded.includes(refusalAnswer())) {
3561
+ answer = grounded;
3562
+ console.log("blind-answer(doc): regeneration grounded");
3563
+ }
3564
+ }
3565
+ }
3482
3566
  stageTiming.generate = Date.now() - tGen;
3483
3567
  let used = usedHits;
3484
3568
  if (answer && !answer.includes(refusalAnswer())) {
@@ -3511,24 +3595,37 @@ ${doc.text}` }
3511
3595
  }
3512
3596
  }
3513
3597
  }
3514
- if (answer && !answer.includes(refusalAnswer())) {
3515
- const reflection = await reflect(env.AI, MODELS.grader, q2.query, answer, hits.map((h) => h.text));
3598
+ if (answer && !escalateAnswer && !registerOwns && !answer.includes(refusalAnswer())) {
3599
+ const reflection = await reflect(env.AI, roleModel(env, "grader"), q2.query, answer, used.map((h) => h.text), promptNotes);
3516
3600
  console.log("reflection:", reflection ? reflection.grounded ? "grounded" : "ungrounded" : "null");
3517
3601
  if (reflection && !reflection.grounded && reflection.missing_info) {
3518
3602
  const retryRetrieve = await retrieve(env, q2.query, {
3519
3603
  prev,
3520
3604
  understanding: { ...understanding, standalone_query: `${understanding?.standalone_query || q2.query} ${reflection.missing_info}` },
3605
+ federate,
3606
+ userDocs,
3521
3607
  sealScope: declaredScoped ? docScope : null,
3522
3608
  datasetScope: narrowed ? corpora : null,
3523
3609
  standardKeys,
3610
+ lexicalBoost,
3611
+ licensedDocNumbers,
3524
3612
  ...routeSubset ? { stageSubset: routeSubset ?? void 0 } : {}
3525
3613
  });
3526
3614
  if (retryRetrieve.hits.length > 0) {
3527
- const { messages: retryMessages, usedHits: retryUsed } = buildMessages(q2.query, retryRetrieve.hits, q2.lang, keptHistory, void 0, summary, budget, ablate?.noCompress !== true);
3615
+ const retryNotes = [...baseNotes, ...retryRetrieve.notes ?? []].filter(Boolean).join("\n") || void 0;
3616
+ const { messages: retryMessages, usedHits: retryUsed } = buildMessages(q2.query, retryRetrieve.hits, q2.lang, keptHistory, retryNotes, summary, budget, ablate?.noCompress !== true);
3528
3617
  const retryAnswer = await generateOnce(env, model, retryMessages, routeEffort(routed.route));
3529
3618
  if (retryAnswer) {
3530
- answer = canonicalRefusal(retryAnswer, refusalScope(answerCites(retryAnswer)));
3531
- used = retryUsed;
3619
+ const retryCanonical = exciseMisplacedPin(
3620
+ canonicalRefusal(scrubToolLines(retryAnswer), refusalScope(answerCites(retryAnswer))),
3621
+ answerCites(retryAnswer)
3622
+ );
3623
+ if (!retryCanonical.includes(refusalAnswer())) {
3624
+ answer = retryCanonical;
3625
+ used = retryUsed;
3626
+ } else {
3627
+ console.log("reflection: retry refused \u2014 keeping initial answer");
3628
+ }
3532
3629
  }
3533
3630
  }
3534
3631
  }
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  LIMITS,
3
3
  sha256Hex
4
- } from "./chunk-IZ3GSYMD.js";
4
+ } from "./chunk-22WB6IVC.js";
5
5
  import {
6
6
  P
7
7
  } from "./chunk-3FYJM7LH.js";
@@ -52,6 +52,7 @@ function cfModelRunner(ai) {
52
52
  throw new Error(`embedding failed for all request shapes (${texts.length} text(s))`);
53
53
  },
54
54
  async rerank(model, query, texts) {
55
+ let firstErr = null;
55
56
  for (const body of RERANK_SHAPES(query, texts)) {
56
57
  try {
57
58
  const res = await A.run(model, body);
@@ -68,9 +69,11 @@ function cfModelRunner(ai) {
68
69
  if (Number.isInteger(id) && id >= 0 && id < texts.length && Number.isFinite(s)) scores[id] = s;
69
70
  });
70
71
  if (scores.some((s) => Number.isFinite(s))) return scores;
71
- } catch {
72
+ } catch (e) {
73
+ if (firstErr === null) firstErr = e;
72
74
  }
73
75
  }
76
+ if (firstErr !== null) console.error("rerank adapter failed:", String(firstErr).slice(0, 180));
74
77
  return null;
75
78
  },
76
79
  async run(req) {