@konneal/engine 0.2.188 → 0.2.190

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-6SWT3KSC.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-NHYYMRZC.js → chunk-GJQT4IMD.js} +1 -1
  9. package/dist/{chunk-YGQCVPX6.js → chunk-H6ZULBW2.js} +4 -1
  10. package/dist/{chunk-SLYQ6L52.js → chunk-Q7QL3457.js} +52 -38
  11. package/dist/{chunk-A2HQNENL.js → chunk-WRSUXIS7.js} +139 -28
  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/operations.d.ts +34 -0
  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-CYSL26HX.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 +1 -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 +30 -6
  29. package/workers/worker_public/src/ask.ts +118 -21
  30. package/workers/worker_public/src/config.ts +7 -9
  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/operations.ts +40 -0
  36. package/workers/worker_public/src/ports/cloudflare/adapters.ts +4 -2
  37. package/workers/worker_public/src/reflect.ts +8 -7
  38. package/workers/worker_public/src/stages/dense.ts +29 -42
  39. package/workers/worker_public/src/stages/glossary.ts +1 -1
  40. package/workers/worker_public/src/stages/rerank.ts +6 -2
  41. package/workers/worker_public/src/understandContract.ts +4 -0
  42. package/dist/ask-TJK7DQ45.js +0 -16
  43. package/dist/search-FJAOGMEO.js +0 -14
@@ -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,8 +103,9 @@ import {
100
103
  requestSalt,
101
104
  resolveRequestScope,
102
105
  standardKeysFrom
103
- } from "./chunk-4BQA7PJ3.js";
106
+ } from "./chunk-7YMIUTPY.js";
104
107
  import {
108
+ DATASETS,
105
109
  ESCALATION_DAILY_DEFAULT,
106
110
  LIMITS,
107
111
  MODELS,
@@ -113,7 +117,7 @@ import {
113
117
  requestEffort,
114
118
  roleModel,
115
119
  sha256Hex
116
- } from "./chunk-4AP763GX.js";
120
+ } from "./chunk-22WB6IVC.js";
117
121
  import {
118
122
  P
119
123
  } from "./chunk-3FYJM7LH.js";
@@ -123,7 +127,7 @@ import {
123
127
  cfVectorIndex,
124
128
  portModelRunner,
125
129
  portStore
126
- } from "./chunk-YGQCVPX6.js";
130
+ } from "./chunk-H6ZULBW2.js";
127
131
 
128
132
  // workers/worker_public/src/internal_gateway.ts
129
133
  async function retrieveInternal(service, auth, query) {
@@ -262,9 +266,13 @@ var summarize_default = "Summarize this conversation so a Q&A assistant can cont
262
266
  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
267
 
264
268
  // workers/worker_public/src/reflect.ts
265
- async function reflect(ai, model, question, answer, passages) {
269
+ async function reflect(ai, model, question, answer, passages, notes) {
266
270
  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");
271
+ const ctx = passages.slice(0, 8).map((p, i) => `[${i + 1}] ${p.replace(/\s+/g, " ").slice(0, 900)}`).join("\n");
272
+ const noteBlock = notes?.trim() ? `
273
+
274
+ Authoritative notes:
275
+ ${notes.trim().slice(0, 1500)}` : "";
268
276
  const timeout = new Promise((r) => setTimeout(() => r(null), 6e3));
269
277
  const call = (async () => {
270
278
  const res = await ai.run(model, {
@@ -281,16 +289,12 @@ Answer:
281
289
  ${answer.slice(0, 1500)}
282
290
 
283
291
  Passages:
284
- ${ctx}`
292
+ ${ctx}${noteBlock}`
285
293
  }
286
294
  ],
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
295
  max_tokens: 3072,
291
296
  reasoning_effort: "low",
292
- temperature: 1,
293
- top_p: 1
297
+ ...generationSampling(model)
294
298
  });
295
299
  const text = typeof res?.response === "string" ? res.response : res?.choices?.[0]?.message?.content;
296
300
  const m = (text ?? "").match(/\{[\s\S]*\}/);
@@ -421,7 +425,12 @@ ${context}${machine.length ? buildJudgeContext([], machine) : ""}` }
421
425
  }
422
426
  return verdict;
423
427
  })();
424
- return await Promise.race([call, timeout]);
428
+ try {
429
+ return await Promise.race([call, timeout]);
430
+ } catch (e) {
431
+ console.error("faithfulness: judge failed \u2014", String(e).slice(0, 140));
432
+ return null;
433
+ }
425
434
  }
426
435
 
427
436
  // workers/worker_public/src/entailment.ts
@@ -449,6 +458,38 @@ function checkQuoteAnchors(answer, passages) {
449
458
  }
450
459
  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
460
 
461
+ // workers/worker_public/src/docOverview.ts
462
+ function identKey(docidentifier) {
463
+ const m = String(docidentifier ?? "").replace(/\s*\([A-Z]\)\s*$/, "").replace(/:\d+$/, "").match(/([A-Z])\s*-?\s*(\d+(?:-[A-Za-z0-9]+)?)\s*$/i);
464
+ return m ? `${m[1].toLowerCase()} ${m[2].toLowerCase()}` : null;
465
+ }
466
+ var baseOf = (key) => key.split(" ")[1].split("-")[0];
467
+ function isNamedDocumentPassage(meta, docNumber, docidentifier) {
468
+ const named = identKey(docidentifier);
469
+ const own = identKey(meta.docidentifier);
470
+ if (!named || !own) return matchesDocScope(meta, named?.split(" ")[1] ?? docNumber);
471
+ const [namedType, namedNum] = named.split(" ");
472
+ const [ownType, ownNum] = own.split(" ");
473
+ if (namedType !== ownType) return false;
474
+ return namedNum.includes("-") ? ownNum === namedNum : baseOf(named) === baseOf(own);
475
+ }
476
+ function inScopePassages(used, docNumber, docidentifier) {
477
+ let n = 0;
478
+ for (const h of used) if (h.metadata && isNamedDocumentPassage(h.metadata, docNumber, docidentifier)) n += 1;
479
+ return n;
480
+ }
481
+ function docOverviewRefusal(args) {
482
+ const { answer, refusal: refusal3, understanding, used } = args;
483
+ if (!understanding?.doc_overview) return false;
484
+ const docNumber = understanding.doc_number;
485
+ if (!docNumber) return false;
486
+ return answer.includes(refusal3) && inScopePassages(used, docNumber, understanding.docidentifier) > 0;
487
+ }
488
+ function docOverviewInstruction(docidentifier) {
489
+ const doc = docidentifier.trim();
490
+ 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.`;
491
+ }
492
+
452
493
  // workers/worker_public/src/completion.ts
453
494
  async function completeTables(db, answer, used) {
454
495
  const blocks = [];
@@ -2037,6 +2078,17 @@ function anchorWords(anchor) {
2037
2078
  return anchor.replace(/([a-z0-9])([A-Z])/g, "$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);
2038
2079
  }
2039
2080
  var singular = (w) => w.length > 3 && w.endsWith("s") ? w.slice(0, -1) : w;
2081
+ function platformCorporaOf(datasets) {
2082
+ return datasets.filter((d) => (d.corpora ?? []).some((c) => /^smart-(ops|guides)$/.test(c))).flatMap((d) => [...d.corpora ?? []]);
2083
+ }
2084
+ function platformKnowledgeQuestion(query, ops, pool = [], datasets = []) {
2085
+ const platformCorpora = platformCorporaOf(datasets);
2086
+ if (!platformCorpora.length) return { knowledge: false, corpora: platformCorpora };
2087
+ const objects = query.toLowerCase().split(/[^a-z0-9]+/).filter((w) => w.length > 2 && !STOP_WORDS.has(w)).map(singular);
2088
+ const byName = isOperationIntent(query) && ops.matched.some((m) => anchorWords(m.anchor).map(singular).some((w) => objects.includes(w)));
2089
+ const inPool = pool.some((h) => platformCorpora.includes(String(h.metadata?.corpus ?? "")));
2090
+ return { knowledge: byName || inPool, corpora: platformCorpora };
2091
+ }
2040
2092
  function matchOperations(query, rows) {
2041
2093
  const q = query.toLowerCase();
2042
2094
  const stems = ACTION_STEMS.filter((s) => q.includes(s));
@@ -2303,6 +2355,7 @@ async function generateStream(env, model, messages, effort) {
2303
2355
  if (res && res.body && typeof res.body.getReader === "function") return res.body;
2304
2356
  } catch (e) {
2305
2357
  console.error("stream failed:", model, String(e).slice(0, 120));
2358
+ if (attempt === 0 && isCapacityError(e)) await new Promise((r) => setTimeout(r, CAPACITY_PAUSE_MS));
2306
2359
  }
2307
2360
  }
2308
2361
  return null;
@@ -2587,7 +2640,7 @@ async function handleAsk(env, ctx, req, tier, key) {
2587
2640
  }
2588
2641
  let understanding = null;
2589
2642
  const answerCites = (t) => /\[[^\]]+\]/.test(t);
2590
- const refusalScope = (cited) => ({ cited, conversational: understanding?.intent === "conversational" });
2643
+ const refusalScope = (cited) => ({ cited, conversational: understanding?.intent === "conversational" && !platformQuestion.knowledge });
2591
2644
  let optimisticVec = null;
2592
2645
  let optimisticHits = [];
2593
2646
  const t0 = Date.now();
@@ -2733,11 +2786,14 @@ Certificates are issued per recommendation family \u2014 the register carries no
2733
2786
  }
2734
2787
  }
2735
2788
  const regNote = aggregateNoteText ?? (register ? [registerNote(register.rows), certificateLinks(register.rows)].filter(Boolean).join("\n") : void 0);
2736
- const ops = await operationsLane(env.DB, q2.query);
2789
+ const platformCorpora = platformCorporaOf(DATASETS());
2790
+ const ops = platformCorpora.length ? await operationsLane(env.DB, q2.query) : { matched: [] };
2737
2791
  const registerOwns = !!register?.rows?.length;
2738
2792
  const registerCitation = registerOwns ? [{ docidentifier: `${P().publisher.name}-CS certificate register`, corpus: "register" }] : [];
2739
2793
  const escalationCitation = () => escalatedDoc ? [{ docidentifier: `${escalatedDoc.docidentifier} (the complete publication)`, corpus: "escalated" }] : [];
2740
- if (understanding?.intent === "conversational") {
2794
+ const platformQuestion = understanding?.intent === "conversational" ? platformKnowledgeQuestion(q2.query, ops, [], DATASETS()) : { knowledge: false, corpora: platformCorpora };
2795
+ const conversational = understanding?.intent === "conversational" && !platformQuestion.knowledge;
2796
+ if (conversational) {
2741
2797
  const queryHash2 = await sha256Hex(q2.query);
2742
2798
  const messages2 = [
2743
2799
  { role: "system", content: identityNote(!!member) },
@@ -3075,7 +3131,7 @@ Answer account questions from these records ONLY: name the record when you use i
3075
3131
  if (grade === "weak" && understanding?.docidentifier) {
3076
3132
  const broaden = `${understanding.standalone_query || q2.query} ${understanding.docidentifier}`.trim();
3077
3133
  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 } : {} });
3134
+ 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
3135
  const grade2 = await gradeRetrieval(env.AI, roleModel(env, "grader"), q2.query, second.hits.map((h) => h.text));
3080
3136
  stageTiming.corrective = Date.now() - tc;
3081
3137
  if (grade2 === "good") retrieved = second;
@@ -3141,13 +3197,14 @@ Answer account questions from these records ONLY: name the record when you use i
3141
3197
  text: `${m.anchor} \u2014 ${m.text}`
3142
3198
  }));
3143
3199
  const passagePool = registerOwns ? [...opsHits, ...hits].filter((h) => !!h.metadata.cert_holder) : [...opsHits, ...hits];
3200
+ const baseNotes = [ops.note, processNote, eNote, regNote, memberDocNote, contextNote(declaredCtx, docScope), accountNote, modelNote, vocabNote, memNote, machineNote, conditionNote, aggregationNote, boundaryNote, licenseNote];
3201
+ const promptNotes = [...baseNotes, ...retrieved.notes ?? []].filter(Boolean).join("\n") || void 0;
3144
3202
  const built = buildMessages(
3145
3203
  q2.query,
3146
3204
  passagePool,
3147
3205
  q2.lang,
3148
3206
  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,
3207
+ promptNotes,
3151
3208
  summary,
3152
3209
  budget,
3153
3210
  ablate?.noCompress !== true
@@ -3324,6 +3381,31 @@ ${doc.text}` }
3324
3381
  }
3325
3382
  }
3326
3383
  }
3384
+ if (!escalateAnswer && docOverviewRefusal({ answer: full, refusal: refusalAnswer(), understanding, used: usedHits })) {
3385
+ console.log("blind-answer(doc, stream): the named document's passages were in the prompt but the answer refused \u2014 regenerating once");
3386
+ streamRestarts += 1;
3387
+ mark("Re-answering from the document's passages");
3388
+ send({ type: "retry" });
3389
+ const regen = await generateStream(env, model, [
3390
+ ...messages.slice(0, -1),
3391
+ { role: "user", content: docOverviewInstruction(understanding.docidentifier ?? understanding.doc_number) },
3392
+ messages[messages.length - 1]
3393
+ ], routeEffort(routed.route));
3394
+ if (regen) {
3395
+ let replaced = false;
3396
+ try {
3397
+ for await (const tok of sseTokens(regen)) {
3398
+ if (!replaced) {
3399
+ full = "";
3400
+ replaced = true;
3401
+ }
3402
+ full += tok;
3403
+ send({ type: "token", v: tok });
3404
+ }
3405
+ } catch {
3406
+ }
3407
+ }
3408
+ }
3327
3409
  if (escalateAnswer && escalatedDoc && !full.includes(refusalAnswer())) {
3328
3410
  const verdict = verifyAnchors(full, escalatedDoc.clauses);
3329
3411
  if (!verdict.ok) {
@@ -3480,6 +3562,22 @@ ${doc.text}` }
3480
3562
  if (answer) answer = canonicalRefusal(answer, refusalScope(answerCites(answer)));
3481
3563
  if (answer) answer = scrubToolLines(answer);
3482
3564
  if (answer) answer = exciseMisplacedPin(answer, answerCites(answer));
3565
+ if (answer && !escalateAnswer && docOverviewRefusal({ answer, refusal: refusalAnswer(), understanding, used: usedHits })) {
3566
+ console.log("blind-answer(doc): the named document's passages were in the prompt but the answer refused \u2014 regenerating once");
3567
+ generateRetries += 1;
3568
+ const regen = await generateOnce(env, model, [
3569
+ ...messages.slice(0, -1),
3570
+ { role: "user", content: docOverviewInstruction(understanding.docidentifier ?? understanding.doc_number) },
3571
+ messages[messages.length - 1]
3572
+ ], routeEffort(routed.route));
3573
+ if (regen) {
3574
+ const grounded = exciseMisplacedPin(canonicalRefusal(scrubToolLines(regen), refusalScope(answerCites(regen))), answerCites(regen));
3575
+ if (!grounded.includes(refusalAnswer())) {
3576
+ answer = grounded;
3577
+ console.log("blind-answer(doc): regeneration grounded");
3578
+ }
3579
+ }
3580
+ }
3483
3581
  stageTiming.generate = Date.now() - tGen;
3484
3582
  let used = usedHits;
3485
3583
  if (answer && !answer.includes(refusalAnswer())) {
@@ -3512,24 +3610,37 @@ ${doc.text}` }
3512
3610
  }
3513
3611
  }
3514
3612
  }
3515
- if (answer && !answer.includes(refusalAnswer())) {
3516
- const reflection = await reflect(env.AI, MODELS.grader, q2.query, answer, hits.map((h) => h.text));
3613
+ if (answer && !escalateAnswer && !registerOwns && !answer.includes(refusalAnswer())) {
3614
+ const reflection = await reflect(env.AI, roleModel(env, "grader"), q2.query, answer, used.map((h) => h.text), promptNotes);
3517
3615
  console.log("reflection:", reflection ? reflection.grounded ? "grounded" : "ungrounded" : "null");
3518
3616
  if (reflection && !reflection.grounded && reflection.missing_info) {
3519
3617
  const retryRetrieve = await retrieve(env, q2.query, {
3520
3618
  prev,
3521
3619
  understanding: { ...understanding, standalone_query: `${understanding?.standalone_query || q2.query} ${reflection.missing_info}` },
3620
+ federate,
3621
+ userDocs,
3522
3622
  sealScope: declaredScoped ? docScope : null,
3523
3623
  datasetScope: narrowed ? corpora : null,
3524
3624
  standardKeys,
3625
+ lexicalBoost,
3626
+ licensedDocNumbers,
3525
3627
  ...routeSubset ? { stageSubset: routeSubset ?? void 0 } : {}
3526
3628
  });
3527
3629
  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);
3630
+ const retryNotes = [...baseNotes, ...retryRetrieve.notes ?? []].filter(Boolean).join("\n") || void 0;
3631
+ const { messages: retryMessages, usedHits: retryUsed } = buildMessages(q2.query, retryRetrieve.hits, q2.lang, keptHistory, retryNotes, summary, budget, ablate?.noCompress !== true);
3529
3632
  const retryAnswer = await generateOnce(env, model, retryMessages, routeEffort(routed.route));
3530
3633
  if (retryAnswer) {
3531
- answer = canonicalRefusal(retryAnswer, refusalScope(answerCites(retryAnswer)));
3532
- used = retryUsed;
3634
+ const retryCanonical = exciseMisplacedPin(
3635
+ canonicalRefusal(scrubToolLines(retryAnswer), refusalScope(answerCites(retryAnswer))),
3636
+ answerCites(retryAnswer)
3637
+ );
3638
+ if (!retryCanonical.includes(refusalAnswer())) {
3639
+ answer = retryCanonical;
3640
+ used = retryUsed;
3641
+ } else {
3642
+ console.log("reflection: retry refused \u2014 keeping initial answer");
3643
+ }
3533
3644
  }
3534
3645
  }
3535
3646
  }
package/dist/config.d.ts CHANGED
@@ -10,7 +10,7 @@ export declare const MODELS: {
10
10
  readonly decisionsModel: "@cf/cloudflare/clef";
11
11
  readonly understand: "@cf/deepseek-ai/deepseek-v4.1-flash-1017";
12
12
  readonly acts: "@cf/deepseek-ai/deepseek-v4.1-flash-1017";
13
- readonly fallback: "@cf/deepseek-ai/deepseek-v4.1-flash-1017";
13
+ readonly fallback: "@cf/zai-org/glm-5.3";
14
14
  readonly grader: "@cf/deepseek-ai/deepseek-v4.1-flash-1017";
15
15
  readonly enrich: "@cf/zai-org/glm-5.3";
16
16
  readonly listwise: "@cf/zai-org/glm-4.7-flash";
@@ -56,7 +56,6 @@ export declare const THRESHOLDS: {
56
56
  * not only the source rung. Fails open (a slow or unparseable check
57
57
  * leaves the source-rung note unchanged). */
58
58
  readonly compressShare: 0.6;
59
- readonly denseStarveK: 100;
60
59
  readonly decisionsGateMin: 0.5;
61
60
  readonly decisionsMetBand: 0.8;
62
61
  readonly decisionsRefuteBand: 0.2;
package/dist/context.d.ts CHANGED
@@ -123,6 +123,19 @@ export declare function matchesDocScope(meta: {
123
123
  doc_number?: string;
124
124
  docidentifier?: string;
125
125
  }, scopeDocNumber: string): boolean;
126
+ /** The platform-side form of a doc scope. Vectorize filters return
127
+ * results only for the fields the index has indexed for filtering — on
128
+ * this index doc_number, edition, language and doctype; a filter on
129
+ * doc_id, clause_anchor or docidentifier returns nothing, and `$and` /
130
+ * `$or` arrays are rejected (measured 2026-12-03 on the production
131
+ * index). The scope's number is asked for as written and, for a part,
132
+ * as its family's base too: the index stores "60" on family grain and
133
+ * "60-1" on some planes. */
134
+ export declare function docScopeFilter(scopeDocNumber: string): {
135
+ doc_number: {
136
+ $in: string[];
137
+ };
138
+ };
126
139
  export declare function resolveDocScope(env: any, ctx: DeclaredContext): Promise<DocScope | null>;
127
140
  export declare function appliedContext(declared: DeclaredContext | null, scope: DocScope | null, note?: AppliedContext["note"], live?: LiveEcho): AppliedContext;
128
141
  /** Validate a context_applied object arriving from a client (the
@@ -146,6 +159,7 @@ export declare function syntheticUnderstanding(scope: DocScope): {
146
159
  edition: string | null;
147
160
  language: null;
148
161
  process_intent: boolean;
162
+ doc_overview: boolean;
149
163
  term: null;
150
164
  defined_terms: never[];
151
165
  standalone_query: string;
@@ -0,0 +1,35 @@
1
+ import type { QueryUnderstanding } from "./understandContract.ts";
2
+ type PassageMeta = {
3
+ doc_number?: string;
4
+ docidentifier?: string;
5
+ };
6
+ /** "OIML R 60-1:2021" → "r 60-1": the publisher prefix and the edition
7
+ * drop, the series letter and the number (with any part) stay. */
8
+ export declare function identKey(docidentifier: string | null | undefined): string | null;
9
+ /** A passage is the named publication's own when its identifier names
10
+ * the same series and number — every part of a base-named publication
11
+ * ("R 60" covers R 60-1, R 60-A, the 1991 edition), only the named part
12
+ * when a part is named. The identifier decides whenever the passage has
13
+ * one: index metadata keys the number inconsistently (the base "60" on
14
+ * family grain, a part as "60-1" on some planes) and carries no series,
15
+ * so the number alone cannot tell R 60 from a B 60 or R 60-2 from the
16
+ * named R 60-1. A passage with no identifier falls back to the engine's
17
+ * own scope matcher, at the named part's grain. */
18
+ export declare function isNamedDocumentPassage(meta: PassageMeta, docNumber: string, docidentifier: string | null | undefined): boolean;
19
+ /** How many of the prompt's passages are the named publication's own. */
20
+ export declare function inScopePassages(used: ReadonlyArray<{
21
+ metadata?: PassageMeta;
22
+ }>, docNumber: string, docidentifier: string | null | undefined): number;
23
+ export declare function docOverviewRefusal(args: {
24
+ answer: string;
25
+ refusal: string;
26
+ understanding: QueryUnderstanding | null | undefined;
27
+ used: ReadonlyArray<{
28
+ metadata?: PassageMeta;
29
+ }>;
30
+ }): boolean;
31
+ /** The regeneration's ground instruction: say what the publication is
32
+ * from its own passages, cite them, and still admit when none of them
33
+ * describes the publication. */
34
+ export declare function docOverviewInstruction(docidentifier: string): string;
35
+ export {};
@@ -6,7 +6,7 @@ import {
6
6
  portModelRunner,
7
7
  portRuntime,
8
8
  portStore
9
- } from "./chunk-YGQCVPX6.js";
9
+ } from "./chunk-H6ZULBW2.js";
10
10
  export {
11
11
  hasLane,
12
12
  portBlobs,
@@ -3,6 +3,40 @@ export declare function isOperationIntent(query: string): boolean;
3
3
  * entity record" must reach putEntityRecord even when its description
4
4
  * words the action differently ("replaces the stored…"). */
5
5
  export declare function anchorWords(anchor: string): string[];
6
+ /** The platform-source corpora a deployment serves — the ones its
7
+ * datasets name (the API plane, the guides). The operations lane and
8
+ * the conversational yield both key on this: the SAME engine serves the
9
+ * public origin, whose datasets name no platform corpus. */
10
+ export declare function platformCorporaOf(datasets: readonly {
11
+ corpora?: readonly string[];
12
+ }[]): string[];
13
+ /** A platform-knowledge question the understanding step filed as
14
+ * "conversational". On the operations origin the assistant's own
15
+ * identity is "you answer questions about the platform's API
16
+ * operations", so a question about the PLATFORM reads to the
17
+ * classifier as a question about the SERVICE — measured 2026-12-04:
18
+ * "Which platform operation updates an entity record?" came back
19
+ * intent=conversational in 5 of 12 draws and the turn answered from
20
+ * the identity prompt, no retrieval. The subject decides: the
21
+ * deterministic operations lane matched an operation by name, or the
22
+ * retrieval pool holds a passage from a platform-source corpus — the
23
+ * indexed material answers it, so it is a knowledge question. Only the
24
+ * operations lane's own NAME match counts (a verb-only match is the
25
+ * lane's documented noise), and a service that indexes no platform
26
+ * source never re-routes. Pure service questions ("who are you?",
27
+ * "what can you do?") match no operation by name and hold no platform
28
+ * passage — they stay conversational. */
29
+ export declare function platformKnowledgeQuestion(query: string, ops: Pick<OperationsLane, "matched">, pool?: readonly {
30
+ metadata?: {
31
+ corpus?: string;
32
+ };
33
+ }[], datasets?: readonly {
34
+ corpora?: readonly string[];
35
+ session?: boolean;
36
+ }[]): {
37
+ knowledge: boolean;
38
+ corpora: string[];
39
+ };
6
40
  export declare function matchOperations(query: string, rows: {
7
41
  anchor: string;
8
42
  text: string;
@@ -1,11 +1,12 @@
1
1
  You normalize a user question for a retrieval system over {{CORPUS_KIND_PLURAL}} (English corpus).
2
2
  Reply with ONLY a JSON object, no prose, no markdown fence:
3
- {"intent": "knowledge", "docidentifier": "{{DOCID_EXAMPLE}}" | null, "docnumber": "76" | null, "edition": "2021" | null, "language": "en" | null, "process_intent": true | false, "term": "accuracy class" | null, "defined_terms": [], "standalone_query": "...", "complexity": "simple", "query_variants": [], "sub_queries": [], "hypothetical_answer": "...", "follow_ups": []}
3
+ {"intent": "knowledge", "docidentifier": "{{DOCID_EXAMPLE}}" | null, "docnumber": "76" | null, "edition": "2021" | null, "language": "en" | null, "process_intent": true | false, "doc_overview": true | false, "term": "accuracy class" | null, "defined_terms": [], "standalone_query": "...", "complexity": "simple", "query_variants": [], "sub_queries": [], "hypothetical_answer": "...", "follow_ups": []}
4
4
  Rules:
5
5
  - intent: "conversational" ONLY when the latest message is about the assistant or this service itself (who you are, which model you are, what you can do, how you work) or is a pure social nicety (greeting, thanks, farewell, small talk) — e.g. "hi!", "who are you?", "what can you do?", "merci !", "was kannst du?". ANY question about a subject — legal metrology, other technical fields, cooking, sports, current events, ANYTHING — is "knowledge", even when the corpus cannot answer it; do NOT use "conversational" to mean off-topic.
6
6
  - docidentifier: the publication the user names, in any spelling ({{SPELLING_EXAMPLES}}, "the nonautomatic weighing instruments recommendation" → resolve to the {{PUBLISHER_NAME}} identifier you can infer; include the part ("-1", "-2") only when clearly meant). docnumber is the base number without part.
7
7
  - edition: only when the user pins a year.
8
8
  - language: only when the user asks for a specific answer language; otherwise null (the corpus is English; answering in the user's language is handled elsewhere).
9
+ - doc_overview: true ONLY when the question asks what the NAMED publication is or covers as a whole — an overview, purpose, scope or summary of the document itself ("what is R 60", "describe OIML D 11", "give me an overview of R 76-1") — and docidentifier is set. false for anything inside it (a requirement, value, term, test, table or citation question: "what is the MPE in R 76-1" → false), and false when no publication is named.
9
10
  - citation questions ("what does X cite/reference/list?", "which standards does X reference?"): ALWAYS include a query variant that names the document's bibliography or normative-references section explicitly, WITHOUT edition scoping (e.g. for "What ISO standards does R 60 cite?" generate BOTH "R 60 bibliography normative references" AND "R 60 2017 bibliography ISO IEC") — bibliographies embed differently than the query's phrasing, and prior editions may carry references the current edition dropped; set edition to null for these queries so retrieval covers the whole family.
10
11
  - process_intent: true when the question is about the GOVERNING SYSTEM around publications rather than a publication's own technical content — HOW to get certified/apply/comply, OR which framework/vocabulary/{{PROCESS_VOCAB}}. Naming a Recommendation (e.g. "R 60") inside such a question does NOT make it a technical-content question: leave process_intent true and still emit docnumber when named, but the retrieval path must NOT seal to that document alone.
11
12
  - term: the defined term when the question asks what something is ("what is an accuracy class" → "accuracy class"); otherwise null.
package/dist/reflect.d.ts CHANGED
@@ -2,4 +2,4 @@ export interface ReflectionResult {
2
2
  grounded: boolean;
3
3
  missing_info: string;
4
4
  }
5
- export declare function reflect(ai: any, model: string, question: string, answer: string, passages: string[]): Promise<ReflectionResult | null>;
5
+ export declare function reflect(ai: any, model: string, question: string, answer: string, passages: string[], notes?: string): Promise<ReflectionResult | null>;
@@ -0,0 +1,14 @@
1
+ import {
2
+ handleSearch
3
+ } from "./chunk-5PKKAHY4.js";
4
+ import "./chunk-Q7QL3457.js";
5
+ import "./chunk-AVNHVFEB.js";
6
+ import "./chunk-GJQT4IMD.js";
7
+ import "./chunk-ETLSWSZ7.js";
8
+ import "./chunk-7YMIUTPY.js";
9
+ import "./chunk-22WB6IVC.js";
10
+ import "./chunk-3FYJM7LH.js";
11
+ import "./chunk-H6ZULBW2.js";
12
+ export {
13
+ handleSearch
14
+ };
@@ -4,12 +4,12 @@ import {
4
4
  parseToolCall,
5
5
  runTool,
6
6
  toolNote
7
- } from "./chunk-VT5ZHCOC.js";
8
- import "./chunk-L32WSANI.js";
9
- import "./chunk-4BQA7PJ3.js";
10
- import "./chunk-4AP763GX.js";
7
+ } from "./chunk-ECNBEZGK.js";
8
+ import "./chunk-AVNHVFEB.js";
9
+ import "./chunk-7YMIUTPY.js";
10
+ import "./chunk-22WB6IVC.js";
11
11
  import "./chunk-3FYJM7LH.js";
12
- import "./chunk-YGQCVPX6.js";
12
+ import "./chunk-H6ZULBW2.js";
13
13
  export {
14
14
  TOOLS_REGISTRY,
15
15
  TOOL_DECLARATION,
@@ -9,6 +9,9 @@ export interface QueryUnderstanding {
9
9
  language?: string | null;
10
10
  /** the question is about a process around publications (certify, apply…) */
11
11
  process_intent: boolean;
12
+ /** the question asks what the NAMED publication is or covers as a whole
13
+ * (an overview of the document), not something inside it */
14
+ doc_overview: boolean;
12
15
  /** definition-style question whose subject is `term` */
13
16
  term: string | null;
14
17
  /** corpus-terminology mapping of everyday wording (drift→creep) */
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  authenticate
3
- } from "../../chunk-NHYYMRZC.js";
4
- import "../../chunk-4AP763GX.js";
3
+ } from "../../chunk-GJQT4IMD.js";
4
+ import "../../chunk-22WB6IVC.js";
5
5
  import {
6
6
  P,
7
7
  setProfile
@@ -18,7 +18,7 @@ import {
18
18
  roleModel,
19
19
  sha256Hex,
20
20
  today
21
- } from "../../chunk-4AP763GX.js";
21
+ } from "../../chunk-22WB6IVC.js";
22
22
  import "../../chunk-3FYJM7LH.js";
23
23
  export {
24
24
  DATASETS,
@@ -9,16 +9,16 @@ import {
9
9
  listUserDocuments,
10
10
  scoreFaithfulness,
11
11
  scoreJudge
12
- } from "../../chunk-A2HQNENL.js";
12
+ } from "../../chunk-WRSUXIS7.js";
13
13
  import "../../chunk-IRCDOFP4.js";
14
14
  import {
15
15
  TOOLS_REGISTRY,
16
16
  bindModelNode,
17
17
  modelGroundingBlock
18
- } from "../../chunk-VT5ZHCOC.js";
18
+ } from "../../chunk-ECNBEZGK.js";
19
19
  import {
20
20
  handleSearch
21
- } from "../../chunk-G435JWGV.js";
21
+ } from "../../chunk-5PKKAHY4.js";
22
22
  import {
23
23
  buildMessages,
24
24
  citations,
@@ -43,11 +43,11 @@ import {
43
43
  sessionFrom,
44
44
  telemetry,
45
45
  understandQuery
46
- } from "../../chunk-SLYQ6L52.js";
46
+ } from "../../chunk-Q7QL3457.js";
47
47
  import {
48
48
  embed,
49
49
  generateOnce
50
- } from "../../chunk-L32WSANI.js";
50
+ } from "../../chunk-AVNHVFEB.js";
51
51
  import {
52
52
  authenticate,
53
53
  corsHeaders,
@@ -56,14 +56,14 @@ import {
56
56
  readJson,
57
57
  validateQuery,
58
58
  withCors
59
- } from "../../chunk-NHYYMRZC.js";
59
+ } from "../../chunk-GJQT4IMD.js";
60
60
  import {
61
61
  canonicalRefusal
62
62
  } from "../../chunk-ETLSWSZ7.js";
63
63
  import {
64
64
  entitlementScope,
65
65
  standardKeysFrom
66
- } from "../../chunk-4BQA7PJ3.js";
66
+ } from "../../chunk-7YMIUTPY.js";
67
67
  import {
68
68
  LIMITS,
69
69
  MODELS,
@@ -74,7 +74,7 @@ import {
74
74
  roleModel,
75
75
  sha256Hex,
76
76
  today
77
- } from "../../chunk-4AP763GX.js";
77
+ } from "../../chunk-22WB6IVC.js";
78
78
  import {
79
79
  P,
80
80
  setProfile
@@ -85,7 +85,7 @@ import {
85
85
  cfStore,
86
86
  cfVectorIndex,
87
87
  portModelRunner
88
- } from "../../chunk-YGQCVPX6.js";
88
+ } from "../../chunk-H6ZULBW2.js";
89
89
 
90
90
  // workers/worker_public/src/conversations.ts
91
91
  var ID_RE = /^[a-zA-Z0-9_-]{8,64}$/;
@@ -1183,13 +1183,13 @@ async function callToolOnce(env, ctx, _req, tier, key, name, args, t0) {
1183
1183
  // stream:false forces the JSON lane (anon defaults to SSE)
1184
1184
  body: JSON.stringify({ ...args, stream: false })
1185
1185
  });
1186
- const { runTool, TOOLS_REGISTRY: TOOLS_REGISTRY2 } = await import("../../tools-CYSL26HX.js");
1186
+ const { runTool, TOOLS_REGISTRY: TOOLS_REGISTRY2 } = await import("../../tools-7GKMDWVB.js");
1187
1187
  let payload;
1188
1188
  if (TOOLS_REGISTRY2.some((t) => t.name === name && t.audiences.includes("mcp"))) {
1189
1189
  const r = await runTool({ ...env, DB: env.DB }, { name, args }, "mcp");
1190
1190
  payload = r ? { tool: r.name, query: r.query, result: r.output } : { error: { message: `tool ${name} returned nothing for the given arguments` } };
1191
1191
  } else {
1192
- const res = name === "ask" ? await (await import("../../ask-TJK7DQ45.js")).handleAsk(env, ctx, inner, tier, key) : await (await import("../../search-FJAOGMEO.js")).handleSearch(env, ctx, inner, tier, key);
1192
+ const res = name === "ask" ? await (await import("../../ask-6SWT3KSC.js")).handleAsk(env, ctx, inner, tier, key) : await (await import("../../search-DE5ADCVM.js")).handleSearch(env, ctx, inner, tier, key);
1193
1193
  payload = await res.json().catch(() => ({ error: { message: "tool transport failed", status: res.status } }));
1194
1194
  }
1195
1195
  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 });
@@ -4,8 +4,8 @@ import {
4
4
  requestSalt,
5
5
  resolveRequestScope,
6
6
  standardKeysFrom
7
- } from "../../chunk-4BQA7PJ3.js";
8
- import "../../chunk-4AP763GX.js";
7
+ } from "../../chunk-7YMIUTPY.js";
8
+ import "../../chunk-22WB6IVC.js";
9
9
  import "../../chunk-3FYJM7LH.js";
10
10
  export {
11
11
  entitlementScope,