@konneal/engine 0.2.188 → 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 (41) hide show
  1. package/dist/ai.d.ts +7 -0
  2. package/dist/ask-LPNODCPM.js +16 -0
  3. package/dist/{chunk-4AP763GX.js → chunk-22WB6IVC.js} +7 -9
  4. package/dist/{chunk-G435JWGV.js → chunk-5PKKAHY4.js} +5 -5
  5. package/dist/{chunk-4BQA7PJ3.js → chunk-7YMIUTPY.js} +1 -1
  6. package/dist/{chunk-L32WSANI.js → chunk-AVNHVFEB.js} +26 -3
  7. package/dist/{chunk-VT5ZHCOC.js → chunk-ECNBEZGK.js} +5 -5
  8. package/dist/{chunk-A2HQNENL.js → chunk-FCRTWZQE.js} +121 -25
  9. package/dist/{chunk-NHYYMRZC.js → chunk-GJQT4IMD.js} +1 -1
  10. package/dist/{chunk-YGQCVPX6.js → chunk-H6ZULBW2.js} +4 -1
  11. package/dist/{chunk-SLYQ6L52.js → chunk-Q7QL3457.js} +52 -38
  12. package/dist/config.d.ts +1 -2
  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/prompts/understanding.md +2 -1
  17. package/dist/reflect.d.ts +1 -1
  18. package/dist/search-DE5ADCVM.js +14 -0
  19. package/dist/{tools-CYSL26HX.js → tools-7GKMDWVB.js} +5 -5
  20. package/dist/understandContract.d.ts +3 -0
  21. package/dist/worker_mcp/src/index.js +2 -2
  22. package/dist/worker_public/src/config.js +1 -1
  23. package/dist/worker_public/src/index.js +11 -11
  24. package/dist/worker_public/src/requestScope.js +2 -2
  25. package/package.json +1 -1
  26. package/workers/worker_public/prompts/understanding.md +2 -1
  27. package/workers/worker_public/src/ai.ts +30 -6
  28. package/workers/worker_public/src/ask.ts +83 -16
  29. package/workers/worker_public/src/config.ts +7 -9
  30. package/workers/worker_public/src/context.ts +14 -0
  31. package/workers/worker_public/src/docOverview.ts +77 -0
  32. package/workers/worker_public/src/faithfulness.ts +11 -1
  33. package/workers/worker_public/src/lexical.ts +21 -19
  34. package/workers/worker_public/src/ports/cloudflare/adapters.ts +4 -2
  35. package/workers/worker_public/src/reflect.ts +8 -7
  36. package/workers/worker_public/src/stages/dense.ts +29 -42
  37. package/workers/worker_public/src/stages/glossary.ts +1 -1
  38. package/workers/worker_public/src/stages/rerank.ts +6 -2
  39. package/workers/worker_public/src/understandContract.ts +4 -0
  40. package/dist/ask-TJK7DQ45.js +0 -16
  41. package/dist/search-FJAOGMEO.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
+ };
@@ -33,10 +33,13 @@ var MODELS = {
33
33
  // operations deployment points ACTS_MODEL at the stronger reasoning
34
34
  // tier; the floor is the understand lane
35
35
  acts: FLASH,
36
- // generation fallback when the answer model is unavailable — the same
37
- // model as the primary while it is the only live cheap option: the
38
- // retry inside generateOnce is the only diversity this lane has
39
- fallback: 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",
40
43
  grader: FLASH,
41
44
  // CRAG grader + judges
42
45
  // contextual enrichment is the QUALITY-FIRST lane (one-time spend over
@@ -103,11 +106,6 @@ var THRESHOLDS = {
103
106
  // the extractive compression arm (TODO.sota/02 row 5): when ablated
104
107
  // on, each passage body is compressed to this share of its budget
105
108
  compressShare: 0.6,
106
- // the dense scope's starvation fallback (the R 134-2 figure question):
107
- // when the in-code doc scope cuts the vector-level top-K to zero, the
108
- // re-query runs at this depth and scopes in code (the native filter is
109
- // dead — measured 2026-10-05)
110
- denseStarveK: 100,
111
109
  // the decision pass (TODO.decisions): the gate fires at decisionsGateMin
112
110
  // noul; the bands assemble met / not clearly stated / not met
113
111
  decisionsGateMin: 0.5,
@@ -6,27 +6,27 @@ import {
6
6
  sessionFrom,
7
7
  telemetry,
8
8
  understandQuery
9
- } from "./chunk-SLYQ6L52.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-NHYYMRZC.js";
16
+ } from "./chunk-GJQT4IMD.js";
17
17
  import {
18
18
  entitlementScope,
19
19
  standardKeysFrom
20
- } from "./chunk-4BQA7PJ3.js";
20
+ } from "./chunk-7YMIUTPY.js";
21
21
  import {
22
22
  LIMITS,
23
23
  MODELS,
24
24
  num,
25
25
  sha256Hex
26
- } from "./chunk-4AP763GX.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-4AP763GX.js";
4
+ } from "./chunk-22WB6IVC.js";
5
5
  import {
6
6
  P
7
7
  } from "./chunk-3FYJM7LH.js";
@@ -2,7 +2,7 @@ import {
2
2
  answerEffort,
3
3
  effortBudget,
4
4
  generationSampling
5
- } from "./chunk-4AP763GX.js";
5
+ } from "./chunk-22WB6IVC.js";
6
6
 
7
7
  // workers/worker_public/src/ai.ts
8
8
  var delay = (ms) => new Promise((r) => setTimeout(r, ms));
@@ -20,10 +20,30 @@ async function embed(ai, _model, text) {
20
20
  }
21
21
  throw new Error(`embed failed after retries: ${String(lastError)}`);
22
22
  }
23
+ function isCapacityError(e) {
24
+ return /3021|rate limit|3040|capacity/i.test(String(e));
25
+ }
26
+ var CAPACITY_PAUSE_MS = 15e3;
23
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;
24
37
  for (let attempt = 0; attempt < 2; attempt++) {
25
- const scores = await ai.rerank(model, query, texts);
26
- 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
+ }
27
47
  }
28
48
  console.error("rerank failed, using vector order");
29
49
  return null;
@@ -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-L32WSANI.js";
3
+ } from "./chunk-AVNHVFEB.js";
4
4
  import {
5
5
  standardKeysFrom
6
- } from "./chunk-4BQA7PJ3.js";
6
+ } from "./chunk-7YMIUTPY.js";
7
7
  import {
8
8
  THRESHOLDS
9
- } from "./chunk-4AP763GX.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-VT5ZHCOC.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-SLYQ6L52.js";
80
+ } from "./chunk-Q7QL3457.js";
80
81
  import {
82
+ CAPACITY_PAUSE_MS,
81
83
  embed,
82
- generateOnce
83
- } from "./chunk-L32WSANI.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-NHYYMRZC.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-4BQA7PJ3.js";
106
+ } from "./chunk-7YMIUTPY.js";
104
107
  import {
105
108
  ESCALATION_DAILY_DEFAULT,
106
109
  LIMITS,
@@ -113,7 +116,7 @@ import {
113
116
  requestEffort,
114
117
  roleModel,
115
118
  sha256Hex
116
- } from "./chunk-4AP763GX.js";
119
+ } from "./chunk-22WB6IVC.js";
117
120
  import {
118
121
  P
119
122
  } from "./chunk-3FYJM7LH.js";
@@ -123,7 +126,7 @@ import {
123
126
  cfVectorIndex,
124
127
  portModelRunner,
125
128
  portStore
126
- } from "./chunk-YGQCVPX6.js";
129
+ } from "./chunk-H6ZULBW2.js";
127
130
 
128
131
  // workers/worker_public/src/internal_gateway.ts
129
132
  async function retrieveInternal(service, auth, query) {
@@ -262,9 +265,13 @@ var summarize_default = "Summarize this conversation so a Q&A assistant can cont
262
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';
263
266
 
264
267
  // workers/worker_public/src/reflect.ts
265
- async function reflect(ai, model, question, answer, passages) {
268
+ async function reflect(ai, model, question, answer, passages, notes) {
266
269
  if (!answer || !passages.length) return null;
267
- 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)}` : "";
268
275
  const timeout = new Promise((r) => setTimeout(() => r(null), 6e3));
269
276
  const call = (async () => {
270
277
  const res = await ai.run(model, {
@@ -281,16 +288,12 @@ Answer:
281
288
  ${answer.slice(0, 1500)}
282
289
 
283
290
  Passages:
284
- ${ctx}`
291
+ ${ctx}${noteBlock}`
285
292
  }
286
293
  ],
287
- // reasoning shares this budget — starved budgets silently disable
288
- // the reflection layer (null = no retry ever fires); DeepSeek-V4
289
- // card: keep reasoning on with headroom + temp 1.0 / top_p 1.0
290
294
  max_tokens: 3072,
291
295
  reasoning_effort: "low",
292
- temperature: 1,
293
- top_p: 1
296
+ ...generationSampling(model)
294
297
  });
295
298
  const text = typeof res?.response === "string" ? res.response : res?.choices?.[0]?.message?.content;
296
299
  const m = (text ?? "").match(/\{[\s\S]*\}/);
@@ -421,7 +424,12 @@ ${context}${machine.length ? buildJudgeContext([], machine) : ""}` }
421
424
  }
422
425
  return verdict;
423
426
  })();
424
- 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
+ }
425
433
  }
426
434
 
427
435
  // workers/worker_public/src/entailment.ts
@@ -449,6 +457,38 @@ function checkQuoteAnchors(answer, passages) {
449
457
  }
450
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.";
451
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
+
452
492
  // workers/worker_public/src/completion.ts
453
493
  async function completeTables(db, answer, used) {
454
494
  const blocks = [];
@@ -2303,6 +2343,7 @@ async function generateStream(env, model, messages, effort) {
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;
@@ -3075,7 +3116,7 @@ Answer account questions from these records ONLY: name the record when you use i
3075
3116
  if (grade === "weak" && understanding?.docidentifier) {
3076
3117
  const broaden = `${understanding.standalone_query || q2.query} ${understanding.docidentifier}`.trim();
3077
3118
  const tc = Date.now();
3078
- 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 } : {} });
3079
3120
  const grade2 = await gradeRetrieval(env.AI, roleModel(env, "grader"), q2.query, second.hits.map((h) => h.text));
3080
3121
  stageTiming.corrective = Date.now() - tc;
3081
3122
  if (grade2 === "good") retrieved = second;
@@ -3141,13 +3182,14 @@ Answer account questions from these records ONLY: name the record when you use i
3141
3182
  text: `${m.anchor} \u2014 ${m.text}`
3142
3183
  }));
3143
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;
3144
3187
  const built = buildMessages(
3145
3188
  q2.query,
3146
3189
  passagePool,
3147
3190
  q2.lang,
3148
3191
  keptHistory,
3149
- // stage-extracted graph facts (GraphRAG) ride the same note channel
3150
- [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,
3151
3193
  summary,
3152
3194
  budget,
3153
3195
  ablate?.noCompress !== true
@@ -3324,6 +3366,31 @@ ${doc.text}` }
3324
3366
  }
3325
3367
  }
3326
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
+ }
3327
3394
  if (escalateAnswer && escalatedDoc && !full.includes(refusalAnswer())) {
3328
3395
  const verdict = verifyAnchors(full, escalatedDoc.clauses);
3329
3396
  if (!verdict.ok) {
@@ -3480,6 +3547,22 @@ ${doc.text}` }
3480
3547
  if (answer) answer = canonicalRefusal(answer, refusalScope(answerCites(answer)));
3481
3548
  if (answer) answer = scrubToolLines(answer);
3482
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
+ }
3483
3566
  stageTiming.generate = Date.now() - tGen;
3484
3567
  let used = usedHits;
3485
3568
  if (answer && !answer.includes(refusalAnswer())) {
@@ -3512,24 +3595,37 @@ ${doc.text}` }
3512
3595
  }
3513
3596
  }
3514
3597
  }
3515
- if (answer && !answer.includes(refusalAnswer())) {
3516
- 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);
3517
3600
  console.log("reflection:", reflection ? reflection.grounded ? "grounded" : "ungrounded" : "null");
3518
3601
  if (reflection && !reflection.grounded && reflection.missing_info) {
3519
3602
  const retryRetrieve = await retrieve(env, q2.query, {
3520
3603
  prev,
3521
3604
  understanding: { ...understanding, standalone_query: `${understanding?.standalone_query || q2.query} ${reflection.missing_info}` },
3605
+ federate,
3606
+ userDocs,
3522
3607
  sealScope: declaredScoped ? docScope : null,
3523
3608
  datasetScope: narrowed ? corpora : null,
3524
3609
  standardKeys,
3610
+ lexicalBoost,
3611
+ licensedDocNumbers,
3525
3612
  ...routeSubset ? { stageSubset: routeSubset ?? void 0 } : {}
3526
3613
  });
3527
3614
  if (retryRetrieve.hits.length > 0) {
3528
- 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);
3529
3617
  const retryAnswer = await generateOnce(env, model, retryMessages, routeEffort(routed.route));
3530
3618
  if (retryAnswer) {
3531
- answer = canonicalRefusal(retryAnswer, refusalScope(answerCites(retryAnswer)));
3532
- 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
+ }
3533
3629
  }
3534
3630
  }
3535
3631
  }
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  LIMITS,
3
3
  sha256Hex
4
- } from "./chunk-4AP763GX.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) {