@konneal/engine 0.2.185 → 0.2.187

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.
@@ -0,0 +1,16 @@
1
+ import {
2
+ handleAsk
3
+ } from "./chunk-IDQND3AA.js";
4
+ import "./chunk-IRCDOFP4.js";
5
+ import "./chunk-BMODSEKT.js";
6
+ import "./chunk-RBRBQJYT.js";
7
+ import "./chunk-BAOKHV2D.js";
8
+ import "./chunk-TLPUJMAF.js";
9
+ import "./chunk-ETLSWSZ7.js";
10
+ import "./chunk-MZQEI4VJ.js";
11
+ import "./chunk-IZ3GSYMD.js";
12
+ import "./chunk-3FYJM7LH.js";
13
+ import "./chunk-YGQCVPX6.js";
14
+ export {
15
+ handleAsk
16
+ };
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  answerEffort,
3
3
  effortBudget
4
- } from "./chunk-QYTCQIA6.js";
4
+ } from "./chunk-IZ3GSYMD.js";
5
5
 
6
6
  // workers/worker_public/src/ai.ts
7
7
  var delay = (ms) => new Promise((r) => setTimeout(r, ms));
@@ -1,12 +1,12 @@
1
1
  import {
2
2
  embed
3
- } from "./chunk-7RZ2D64X.js";
3
+ } from "./chunk-BAOKHV2D.js";
4
4
  import {
5
5
  standardKeysFrom
6
- } from "./chunk-5HCVX34C.js";
6
+ } from "./chunk-MZQEI4VJ.js";
7
7
  import {
8
8
  THRESHOLDS
9
- } from "./chunk-QYTCQIA6.js";
9
+ } from "./chunk-IZ3GSYMD.js";
10
10
  import {
11
11
  P
12
12
  } from "./chunk-3FYJM7LH.js";
@@ -33,7 +33,7 @@ import {
33
33
  tableRetyped,
34
34
  toolNote,
35
35
  verdictNote
36
- } from "./chunk-XO26UIFH.js";
36
+ } from "./chunk-BMODSEKT.js";
37
37
  import {
38
38
  NO_CONTEXT,
39
39
  STAGE_NAMES,
@@ -76,18 +76,18 @@ import {
76
76
  tokenBudget,
77
77
  understandQuery,
78
78
  usageTotal
79
- } from "./chunk-XTWH3PS6.js";
79
+ } from "./chunk-RBRBQJYT.js";
80
80
  import {
81
81
  embed,
82
82
  generateOnce
83
- } from "./chunk-7RZ2D64X.js";
83
+ } from "./chunk-BAOKHV2D.js";
84
84
  import {
85
85
  corsHeaders,
86
86
  err,
87
87
  json,
88
88
  readJson,
89
89
  validateQuery
90
- } from "./chunk-XMUG75ZV.js";
90
+ } from "./chunk-TLPUJMAF.js";
91
91
  import {
92
92
  cacheableAnswer,
93
93
  canonicalRefusal,
@@ -100,8 +100,9 @@ import {
100
100
  requestSalt,
101
101
  resolveRequestScope,
102
102
  standardKeysFrom
103
- } from "./chunk-5HCVX34C.js";
103
+ } from "./chunk-MZQEI4VJ.js";
104
104
  import {
105
+ ESCALATION_DAILY_DEFAULT,
105
106
  LIMITS,
106
107
  MODELS,
107
108
  THRESHOLDS,
@@ -111,7 +112,7 @@ import {
111
112
  requestEffort,
112
113
  roleModel,
113
114
  sha256Hex
114
- } from "./chunk-QYTCQIA6.js";
115
+ } from "./chunk-IZ3GSYMD.js";
115
116
  import {
116
117
  P
117
118
  } from "./chunk-3FYJM7LH.js";
@@ -1919,6 +1920,57 @@ function fieldsAsText(docs) {
1919
1920
  return docs.map((d) => Object.entries(d.fields).map(([k, v]) => `${k.replace(/_/g, " ")}: ${v}`).join("; ")).join("\n");
1920
1921
  }
1921
1922
 
1923
+ // workers/worker_public/src/escalation.ts
1924
+ async function assembleDocument(store, docidentifier, capChars, lang = "en") {
1925
+ const res = await store.prepare(
1926
+ `SELECT text, clause_anchor, status, language FROM chunks
1927
+ WHERE docidentifier = ?1 AND language = ?2 AND status = 'in-force'
1928
+ ORDER BY rowid`
1929
+ ).bind(docidentifier, lang).all();
1930
+ const rows = res.results ?? [];
1931
+ if (!rows.length) return null;
1932
+ const clauses = /* @__PURE__ */ new Set();
1933
+ const parts = [];
1934
+ let total = 0;
1935
+ let truncated = false;
1936
+ for (const r of rows) {
1937
+ const anchor = (r.clause_anchor || "").trim();
1938
+ if (anchor) {
1939
+ clauses.add(anchor);
1940
+ const segs = anchor.split(".");
1941
+ for (let i = 1; i < segs.length; i++) clauses.add(segs.slice(0, i).join("."));
1942
+ }
1943
+ if (total + r.text.length > capChars) {
1944
+ truncated = true;
1945
+ break;
1946
+ }
1947
+ parts.push(r.text);
1948
+ total += r.text.length;
1949
+ }
1950
+ if (!parts.length) return null;
1951
+ return { docidentifier, text: parts.join("\n\n"), clauses, truncated };
1952
+ }
1953
+ function verifyAnchors(answer, clauses) {
1954
+ const cited = /* @__PURE__ */ new Set();
1955
+ for (const m of answer.matchAll(/\b(\d{1,2}(?:\.\d{1,2}){1,3})\b/g)) cited.add(m[1]);
1956
+ for (const m of answer.matchAll(/\b(\d{1,2}\.\d{1,2})\s?[–—-]\s?(\d{1,2}(?:\.\d{1,2}){1,3})\b/g)) cited.add(m[2]);
1957
+ const missing = [];
1958
+ for (const c of cited) {
1959
+ if (!clauses.has(c) && ![...clauses].some((k) => k.startsWith(`${c}.`) || k === c)) missing.push(c);
1960
+ }
1961
+ return { ok: missing.length === 0, missing };
1962
+ }
1963
+ var escalationSystem = () => `You are ${P().publisher.name}, the answer service over legal-metrology publications. Answer the question using ONLY the publication text below. Cite the clause numbers you use. If the publication does not answer it, say so plainly.`;
1964
+ async function escalationAllowed(kv, bucketId, dailyCap, day) {
1965
+ if (dailyCap <= 0) return false;
1966
+ const n = Number(await kv.get(`esc:${day}:${bucketId}`) ?? "0");
1967
+ return n < dailyCap;
1968
+ }
1969
+ async function chargeEscalation(kv, bucketId, day) {
1970
+ const key = `esc:${day}:${bucketId}`;
1971
+ await kv.put(key, String(Number(await kv.get(key) ?? "0") + 1), { expirationTtl: 172800 });
1972
+ }
1973
+
1922
1974
  // workers/worker_public/src/operations.ts
1923
1975
  function isOperationIntent(query) {
1924
1976
  return /\b(operations?|endpoints?)\b/i.test(query);
@@ -2290,10 +2342,10 @@ function messageChars(messages) {
2290
2342
  }
2291
2343
  return n;
2292
2344
  }
2293
- async function chargeAnswerTokens(env, bucketId, stats, promptChars, answerChars, extraTokens = 0) {
2345
+ async function chargeAnswerTokens(env, bucketId, stats, promptChars, answerChars, extraTokens = 0, keyDayLimitAsks) {
2294
2346
  const total = (usageTotal(stats?.usage) ?? estimateTokens(promptChars + answerChars)) + extraTokens;
2295
2347
  await chargeTokens(env, bucketId, total);
2296
- const budget = await tokenBudget(env, bucketId);
2348
+ const budget = await tokenBudget(env, bucketId, keyDayLimitAsks);
2297
2349
  return { tokens_used: budget.used, token_limit: budget.limit };
2298
2350
  }
2299
2351
  async function* sseTokens(stream, stats) {
@@ -2355,14 +2407,15 @@ async function handleAsk(env, ctx, req, tier, key) {
2355
2407
  const memberKey = tier === "key" ? key?.owner_sub ?? null : null;
2356
2408
  const limit = memberKey ? num(env, "MEMBER_DAY_ASK", 300) : tier === "key" ? key.day_limit : tier === "member" || member ? num(env, "MEMBER_DAY_ASK", 300) : num(env, "ANON_DAY_ASK", 20);
2357
2409
  const bucketId = memberKey ? `sub:${memberKey}` : tier === "key" ? `key:${key.id}` : member ? `sub:${member.sub}` : clientIp(req);
2410
+ const keyDayLimit = tier === "key" ? key?.day_limit : void 0;
2358
2411
  const quota = await checkQuota(env, "ask", bucketId, limit, effort === "low" ? 1 : 2);
2359
2412
  const creditPreview = creditEstimate({ effort, toolTurns: body?.multi_turn !== false ? 3 : 0, image: false });
2360
2413
  if (!quota.ok) {
2361
2414
  return err(429, "quota_exceeded", `Daily question limit reached (${quota.limit}). Try again tomorrow.`);
2362
2415
  }
2363
- const tokBudget = await tokenBudget(env, bucketId);
2416
+ const tokBudget = await tokenBudget(env, bucketId, keyDayLimit);
2364
2417
  if (tokBudget.used >= tokBudget.limit) {
2365
- const cb = await creditBudget(env, bucketId);
2418
+ const cb = await creditBudget(env, bucketId, keyDayLimit);
2366
2419
  return err(429, "quota_exceeded", `Daily credits reached (${cb.credits_limit} credits, ${cb.credits_used} used). Try again tomorrow.`);
2367
2420
  }
2368
2421
  quota.tokens_used = tokBudget.used;
@@ -2653,7 +2706,7 @@ Certificates are issued per recommendation family \u2014 the register carries no
2653
2706
  aggregateNoteText = aggregateNote(agg);
2654
2707
  const queryHash2 = await sha256Hex(q2.query);
2655
2708
  telemetry(env, ctx, tier, "ask", MODELS.member, true, answer2.length, queryHash2, q2.lang, void 0, telemetryMeta());
2656
- const tq2 = await chargeAnswerTokens(env, bucketId, void 0, q2.query.length, answer2.length);
2709
+ const tq2 = await chargeAnswerTokens(env, bucketId, void 0, q2.query.length, answer2.length, keyDayLimit);
2657
2710
  const payload = {
2658
2711
  answer: answer2,
2659
2712
  citations: [{ docidentifier: `${P().publisher.name}-CS certificate register (family ${agg.family})`, corpus: "register" }],
@@ -2664,7 +2717,7 @@ Certificates are issued per recommendation family \u2014 the register carries no
2664
2717
  context_applied: NO_CONTEXT,
2665
2718
  read: readAs(),
2666
2719
  ...ablate ? { ablate } : {},
2667
- quota: { ...quota, ...tq2, credits: await creditBudget(env, bucketId), credit_estimate: creditPreview }
2720
+ quota: { ...quota, ...tq2, credits: await creditBudget(env, bucketId, keyDayLimit), credit_estimate: creditPreview }
2668
2721
  };
2669
2722
  if (live2) {
2670
2723
  live2.send({ type: "citations", citations: payload.citations, quota: payload.quota, context_applied: NO_CONTEXT });
@@ -2682,6 +2735,7 @@ Certificates are issued per recommendation family \u2014 the register carries no
2682
2735
  const ops = await operationsLane(env.DB, q2.query);
2683
2736
  const registerOwns = !!register?.rows?.length;
2684
2737
  const registerCitation = registerOwns ? [{ docidentifier: `${P().publisher.name}-CS certificate register`, corpus: "register" }] : [];
2738
+ const escalationCitation = () => escalatedDoc ? [{ docidentifier: `${escalatedDoc.docidentifier} (the complete publication)`, corpus: "escalated" }] : [];
2685
2739
  if (understanding?.intent === "conversational") {
2686
2740
  const queryHash2 = await sha256Hex(q2.query);
2687
2741
  const messages2 = [
@@ -2708,8 +2762,8 @@ ${summary}` }] : [],
2708
2762
  }
2709
2763
  } catch {
2710
2764
  }
2711
- const tq2 = await chargeAnswerTokens(env, bucketId, stats, messageChars(messages2), full.length, probeTokensUsed);
2712
- live2.send({ type: "quota", quota: { ...quota, ...tq2, credits: await creditBudget(env, bucketId), credit_estimate: creditPreview } });
2765
+ const tq2 = await chargeAnswerTokens(env, bucketId, stats, messageChars(messages2), full.length, probeTokensUsed, keyDayLimit);
2766
+ live2.send({ type: "quota", quota: { ...quota, ...tq2, credits: await creditBudget(env, bucketId, keyDayLimit), credit_estimate: creditPreview } });
2713
2767
  live2.send({ type: "done", model, query_hash: queryHash2, context_applied: NO_CONTEXT, read: readAs() });
2714
2768
  telemetry(env, ctx, tier, "ask", model, true, full.length, queryHash2, q2.lang, void 0, telemetryMeta());
2715
2769
  live2.close();
@@ -2757,8 +2811,8 @@ ${summary}` }] : [],
2757
2811
  live2.close();
2758
2812
  return null;
2759
2813
  }
2760
- const tq2 = await chargeAnswerTokens(env, bucketId, void 0, q2.query.length, verdict.answer.length);
2761
- return json({ answer: verdict.answer, citations: citations2, model, query_hash: queryHash2, follow_ups: [], context_applied: draftCtxApplied, read: readAs(), ...draftPayload ? { draft: draftPayload } : {}, ...ablate ? { ablate } : {}, quota: { ...quota, ...tq2, credits: await creditBudget(env, bucketId), credit_estimate: creditPreview } });
2814
+ const tq2 = await chargeAnswerTokens(env, bucketId, void 0, q2.query.length, verdict.answer.length, keyDayLimit);
2815
+ return json({ answer: verdict.answer, citations: citations2, model, query_hash: queryHash2, follow_ups: [], context_applied: draftCtxApplied, read: readAs(), ...draftPayload ? { draft: draftPayload } : {}, ...ablate ? { ablate } : {}, quota: { ...quota, ...tq2, credits: await creditBudget(env, bucketId, keyDayLimit), credit_estimate: creditPreview } });
2762
2816
  }
2763
2817
  if (apiCallIntent) {
2764
2818
  const callCtxApplied = declaredCtx ? appliedContext(declaredCtx, null) : NO_CONTEXT;
@@ -2782,8 +2836,8 @@ ${summary}` }] : [],
2782
2836
  live2.close();
2783
2837
  return null;
2784
2838
  }
2785
- const tq2 = await chargeAnswerTokens(env, bucketId, void 0, q2.query.length, verdict.answer.length);
2786
- return json({ answer: verdict.answer, citations: [], model, query_hash: queryHash2, follow_ups: [], context_applied: callCtxApplied, read: readAs(), ...draftPayload ? { draft: draftPayload } : {}, ...ablate ? { ablate } : {}, quota: { ...quota, ...tq2, credits: await creditBudget(env, bucketId), credit_estimate: creditPreview } });
2839
+ const tq2 = await chargeAnswerTokens(env, bucketId, void 0, q2.query.length, verdict.answer.length, keyDayLimit);
2840
+ return json({ answer: verdict.answer, citations: [], model, query_hash: queryHash2, follow_ups: [], context_applied: callCtxApplied, read: readAs(), ...draftPayload ? { draft: draftPayload } : {}, ...ablate ? { ablate } : {}, quota: { ...quota, ...tq2, credits: await creditBudget(env, bucketId, keyDayLimit), credit_estimate: creditPreview } });
2787
2841
  }
2788
2842
  let liveRecords;
2789
2843
  let accountNote;
@@ -3086,7 +3140,7 @@ Answer account questions from these records ONLY: name the record when you use i
3086
3140
  text: `${m.anchor} \u2014 ${m.text}`
3087
3141
  }));
3088
3142
  const passagePool = registerOwns ? [...opsHits, ...hits].filter((h) => !!h.metadata.cert_holder) : [...opsHits, ...hits];
3089
- const { messages, usedHits } = buildMessages(
3143
+ const built = buildMessages(
3090
3144
  q2.query,
3091
3145
  passagePool,
3092
3146
  q2.lang,
@@ -3097,6 +3151,35 @@ Answer account questions from these records ONLY: name the record when you use i
3097
3151
  budget,
3098
3152
  ablate?.noCompress !== true
3099
3153
  );
3154
+ let escalateAnswer = false;
3155
+ let escalatedDoc = null;
3156
+ let messages = built.messages;
3157
+ let usedHits = built.usedHits;
3158
+ const escalateWanted = crag.grade === "weak" && !crag.corrective?.accepted;
3159
+ if (escalateWanted && understanding?.docidentifier && (tier === "member" || tier === "key") && !withImage) {
3160
+ const day = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
3161
+ const bucket = tier === "key" ? `key:${key.id}` : `sub:${member.sub}`;
3162
+ if (await escalationAllowed(env.CACHE, bucket, num(env, "ESCALATION_DAILY", ESCALATION_DAILY_DEFAULT), day)) {
3163
+ const doc = await assembleDocument(cfStore(env.DB), understanding.docidentifier, 9e5, q2.lang || "en").catch(() => null);
3164
+ if (doc && doc.text.length > 2e4) {
3165
+ const history2 = keptHistory.slice(-6);
3166
+ messages = [
3167
+ { role: "system", content: escalationSystem() },
3168
+ ...history2,
3169
+ { role: "user", content: `Question: ${q2.query}
3170
+
3171
+ Publication ${doc.docidentifier}${doc.truncated ? " (truncated)" : ""}:
3172
+
3173
+ ${doc.text}` }
3174
+ ];
3175
+ usedHits = [];
3176
+ escalatedDoc = doc;
3177
+ escalateAnswer = true;
3178
+ await chargeEscalation(env.CACHE, bucket, day);
3179
+ console.log("escalation: answering from the whole", doc.docidentifier, `(${doc.text.length} chars)`);
3180
+ }
3181
+ }
3182
+ }
3100
3183
  const decisionPromise = decisionsArmed && decisionsGatePromise ? decisionsGatePromise.then((g) => g != null && g >= THRESHOLDS.decisionsGateMin ? runDecisionPass(env, {
3101
3184
  question: q2.query,
3102
3185
  gate: g,
@@ -3157,7 +3240,7 @@ Answer account questions from these records ONLY: name the record when you use i
3157
3240
  console.log("user image attached to generation");
3158
3241
  }
3159
3242
  const queryHash = await sha256Hex(q2.query);
3160
- const cites = [...registerCitation, ...boundModel ? [modelCitation(boundModel), ...citations(usedHits)] : citations(usedHits)];
3243
+ const cites = escalateAnswer ? escalationCitation() : [...registerCitation, ...boundModel ? [modelCitation(boundModel), ...citations(usedHits)] : citations(usedHits)];
3161
3244
  if (live2) {
3162
3245
  const stream = await generateStream(env, model, messages, routeEffort(routed.route));
3163
3246
  if (stream) {
@@ -3217,8 +3300,8 @@ Answer account questions from these records ONLY: name the record when you use i
3217
3300
  }
3218
3301
  } catch {
3219
3302
  }
3220
- const tq2 = await chargeAnswerTokens(env, bucketId, stats, messageChars(messages), full.length, probeTokensUsed);
3221
- send({ type: "quota", quota: { ...quota, ...tq2, credits: await creditBudget(env, bucketId), credit_estimate: creditPreview } });
3303
+ const tq2 = await chargeAnswerTokens(env, bucketId, stats, messageChars(messages), full.length, probeTokensUsed, keyDayLimit);
3304
+ send({ type: "quota", quota: { ...quota, ...tq2, credits: await creditBudget(env, bucketId, keyDayLimit), credit_estimate: creditPreview } });
3222
3305
  if (register?.rows?.length && full.includes(refusalAnswer())) {
3223
3306
  console.log("blind-answer(stream): regenerating once");
3224
3307
  streamRestarts += 1;
@@ -3240,6 +3323,14 @@ Answer account questions from these records ONLY: name the record when you use i
3240
3323
  }
3241
3324
  }
3242
3325
  }
3326
+ if (escalateAnswer && escalatedDoc && !full.includes(refusalAnswer())) {
3327
+ const verdict = verifyAnchors(full, escalatedDoc.clauses);
3328
+ if (!verdict.ok) {
3329
+ console.log("escalation: unverifiable clause citations", verdict.missing.join(","), "\u2014 refusing honestly");
3330
+ full = refusalAnswer();
3331
+ send({ type: "token", v: refusalAnswer() });
3332
+ }
3333
+ }
3243
3334
  let canonical0 = exciseMisplacedPin(canonicalRefusal(full.replace(/^TOOL [a-z_.]+.*$\n?/gm, "").replace(/^\n+/, ""), refusalScope(answerCites(full))), answerCites(full));
3244
3335
  const c2 = canonical0.includes(refusalAnswer()) ? { text: canonical0, blocks: [], dropped: [] } : await contractV2(env.DB, canonical0, usedHits);
3245
3336
  let streamedCompletionBlocks = [];
@@ -3446,7 +3537,14 @@ Answer account questions from these records ONLY: name the record when you use i
3446
3537
  telemetry(env, ctx, tier, "ask", model, false, 0, queryHash, q2.lang, void 0, telemetryMeta());
3447
3538
  return err(502, "generation_failed", "The generation model is unavailable; please retry.");
3448
3539
  }
3449
- const finalCites = [...registerCitation, ...boundModel ? [modelCitation(boundModel), ...citations(used)] : citations(used)];
3540
+ const finalCites = escalateAnswer ? escalationCitation() : [...registerCitation, ...boundModel ? [modelCitation(boundModel), ...citations(used)] : citations(used)];
3541
+ if (escalateAnswer && escalatedDoc && !answer.includes(refusalAnswer())) {
3542
+ const verdict = verifyAnchors(answer, escalatedDoc.clauses);
3543
+ if (!verdict.ok) {
3544
+ console.log("escalation: unverifiable clause citations", verdict.missing.join(","), "\u2014 refusing honestly");
3545
+ answer = canonicalRefusal(refusalAnswer(), refusalScope(false));
3546
+ }
3547
+ }
3450
3548
  const c2ns = answer.includes(refusalAnswer()) ? { text: answer, blocks: [], dropped: [] } : await contractV2(env.DB, answer, used);
3451
3549
  answer = c2ns.text;
3452
3550
  const finalAnchors = answer.includes(refusalAnswer()) ? { total: 0, violations: [] } : checkQuoteAnchors(answer, used.map((h) => h.text));
@@ -3509,7 +3607,7 @@ Answer account questions from these records ONLY: name the record when you use i
3509
3607
  text: h.text.slice(0, 1200),
3510
3608
  ...h.metadata.table_selection ? { sel: h.metadata.table_selection } : {}
3511
3609
  }));
3512
- const tq = await chargeAnswerTokens(env, bucketId, void 0, messageChars(messages), answer.length, probeTokensUsed);
3610
+ const tq = await chargeAnswerTokens(env, bucketId, void 0, messageChars(messages), answer.length, probeTokensUsed, keyDayLimit);
3513
3611
  let cragPassages = null;
3514
3612
  if (body?.manifest === true && used.length) {
3515
3613
  const grades = await gradePassages(env.AI, roleModel(env, "grader"), q2.query, used.map((h) => h.text));
@@ -3535,7 +3633,7 @@ Answer account questions from these records ONLY: name the record when you use i
3535
3633
  entailment,
3536
3634
  total_ms: Date.now() - tStart
3537
3635
  } } : {};
3538
- return json({ ...out, context: contextOut, read: readAs(), ...manifestOut, quota: { ...quota, ...tq, credits: await creditBudget(env, bucketId), credit_estimate: creditPreview } }, 200, { ...corsHeaders(req), "server-timing": serverTiming() });
3636
+ return json({ ...out, context: contextOut, read: readAs(), ...manifestOut, quota: { ...quota, ...tq, credits: await creditBudget(env, bucketId, keyDayLimit), credit_estimate: creditPreview } }, 200, { ...corsHeaders(req), "server-timing": serverTiming() });
3539
3637
  };
3540
3638
  if (liveResponse) {
3541
3639
  void pipeline(live, q).catch(() => {
@@ -43,6 +43,7 @@ var MODELS = {
43
43
  // cross-encoder prunes, listwise orders jointly)
44
44
  listwise: "@cf/zai-org/glm-4.7-flash",
45
45
  // deep-research loop (G10): bounded agentic iterations, members-only
46
+ escalation: "@cf/deepseek-ai/deepseek-v4.1-flash-1017",
46
47
  research: "@cf/zai-org/glm-5.3-flash",
47
48
  // speculative draft-verify (TODO.sota/02 row 2): the strong verifier
48
49
  // over the cheap drafts — the research-tier model verifies; the drafter
@@ -183,6 +184,7 @@ var THRESHOLDS = {
183
184
  function processExpansion() {
184
185
  return P().retrieval.process_expansion;
185
186
  }
187
+ var ESCALATION_DAILY_DEFAULT = 10;
186
188
  function roleModel(env, role) {
187
189
  const ov = env[`${role.toUpperCase()}_MODEL`];
188
190
  return typeof ov === "string" && ov.startsWith("@cf/") ? ov : MODELS[role];
@@ -247,6 +249,7 @@ export {
247
249
  LIMITS,
248
250
  THRESHOLDS,
249
251
  processExpansion,
252
+ ESCALATION_DAILY_DEFAULT,
250
253
  roleModel,
251
254
  answerEffort,
252
255
  effortBudget,
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  DATASETS,
3
3
  datasetAllowed
4
- } from "./chunk-QYTCQIA6.js";
4
+ } from "./chunk-IZ3GSYMD.js";
5
5
  import {
6
6
  P
7
7
  } from "./chunk-3FYJM7LH.js";
@@ -1,11 +1,11 @@
1
1
  import {
2
2
  embed,
3
3
  rerank
4
- } from "./chunk-7RZ2D64X.js";
4
+ } from "./chunk-BAOKHV2D.js";
5
5
  import {
6
6
  bubbleConfirmPage,
7
7
  isAllowedBubbleOrigin
8
- } from "./chunk-XMUG75ZV.js";
8
+ } from "./chunk-TLPUJMAF.js";
9
9
  import {
10
10
  DATASETS,
11
11
  LIMITS,
@@ -15,7 +15,7 @@ import {
15
15
  processExpansion,
16
16
  sha256Hex,
17
17
  today
18
- } from "./chunk-QYTCQIA6.js";
18
+ } from "./chunk-IZ3GSYMD.js";
19
19
  import {
20
20
  P
21
21
  } from "./chunk-3FYJM7LH.js";
@@ -24902,13 +24902,19 @@ function estimateTokens(chars) {
24902
24902
  function tokenTier(bucketId) {
24903
24903
  return bucketId.startsWith("key:") ? "key" : bucketId.startsWith("sub:") ? "member" : "anon";
24904
24904
  }
24905
- function tokenLimit(env, bucketId) {
24905
+ function tokenLimit(env, bucketId, keyDayLimitAsks) {
24906
24906
  const tier = tokenTier(bucketId);
24907
- return tier === "key" ? num(env, "KEY_DAY_TOKENS", 4e6) : tier === "member" ? num(env, "MEMBER_DAY_TOKENS", 15e5) : num(env, "ANON_DAY_TOKENS", 3e5);
24908
- }
24909
- async function tokenBudget(env, bucketId) {
24907
+ return tier === "key" ? (
24908
+ // the key's OWN day_limit is the one truth for both counters (the
24909
+ // owner's 2026-11-09 ruling: the serving cap is for USERS, not
24910
+ // operators): 1 ask ≈ 2000 tokens, so day_limit × 2000 — the
24911
+ // default 2000 asks reproduces the historic 4M exactly
24912
+ keyDayLimitAsks ? keyDayLimitAsks * 2e3 : num(env, "KEY_DAY_TOKENS", 4e6)
24913
+ ) : tier === "member" ? num(env, "MEMBER_DAY_TOKENS", 15e5) : num(env, "ANON_DAY_TOKENS", 3e5);
24914
+ }
24915
+ async function tokenBudget(env, bucketId, keyDayLimitAsks) {
24910
24916
  const used = Number(await env.CACHE.get(`t:${today()}:ask:${await sha256Hex(bucketId)}`) ?? "0");
24911
- return { used, limit: tokenLimit(env, bucketId) };
24917
+ return { used, limit: tokenLimit(env, bucketId, keyDayLimitAsks) };
24912
24918
  }
24913
24919
  async function chargeTokens(env, bucketId, tokens2) {
24914
24920
  if (!(tokens2 > 0)) return;
@@ -24926,8 +24932,8 @@ var CREDIT_TOKEN_UNIT = 1e3;
24926
24932
  function creditLimit(env, bucketId) {
24927
24933
  return Math.floor(tokenLimit(env, bucketId) / CREDIT_TOKEN_UNIT);
24928
24934
  }
24929
- async function creditBudget(env, bucketId) {
24930
- const b = await tokenBudget(env, bucketId);
24935
+ async function creditBudget(env, bucketId, keyDayLimitAsks) {
24936
+ const b = await tokenBudget(env, bucketId, keyDayLimitAsks);
24931
24937
  return { credits_used: Math.ceil(b.used / CREDIT_TOKEN_UNIT), credits_limit: creditLimit(env, bucketId) };
24932
24938
  }
24933
24939
  function creditEstimate(opts) {
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  LIMITS,
3
3
  sha256Hex
4
- } from "./chunk-QYTCQIA6.js";
4
+ } from "./chunk-IZ3GSYMD.js";
5
5
  import {
6
6
  P
7
7
  } from "./chunk-3FYJM7LH.js";
@@ -6,24 +6,24 @@ import {
6
6
  sessionFrom,
7
7
  telemetry,
8
8
  understandQuery
9
- } from "./chunk-XTWH3PS6.js";
9
+ } from "./chunk-RBRBQJYT.js";
10
10
  import {
11
11
  corsHeaders,
12
12
  err,
13
13
  json,
14
14
  readJson,
15
15
  validateQuery
16
- } from "./chunk-XMUG75ZV.js";
16
+ } from "./chunk-TLPUJMAF.js";
17
17
  import {
18
18
  entitlementScope,
19
19
  standardKeysFrom
20
- } from "./chunk-5HCVX34C.js";
20
+ } from "./chunk-MZQEI4VJ.js";
21
21
  import {
22
22
  LIMITS,
23
23
  MODELS,
24
24
  num,
25
25
  sha256Hex
26
- } from "./chunk-QYTCQIA6.js";
26
+ } from "./chunk-IZ3GSYMD.js";
27
27
  import {
28
28
  portModelRunner
29
29
  } from "./chunk-YGQCVPX6.js";
package/dist/config.d.ts CHANGED
@@ -14,6 +14,7 @@ export declare const MODELS: {
14
14
  readonly grader: "@cf/deepseek-ai/deepseek-v4-flash-0731";
15
15
  readonly enrich: "@cf/deepseek-ai/deepseek-v4-pro-0813";
16
16
  readonly listwise: "@cf/zai-org/glm-4.7-flash";
17
+ readonly escalation: "@cf/deepseek-ai/deepseek-v4.1-flash-1017";
17
18
  readonly research: "@cf/zai-org/glm-5.3-flash";
18
19
  readonly verifier: "@cf/zai-org/glm-5.2";
19
20
  };
@@ -136,6 +137,10 @@ export declare function processExpansion(): string;
136
137
  /** Per-deployment model override: <ROLE>_MODEL (e.g. UNDERSTAND_MODEL)
137
138
  * replaces the pinned default for that role. Ops lever for A/B-ing a
138
139
  * role's model without a code change; absent/invalid = the default. */
140
+ /** The escalation's daily per-bucket cap (TODO.sota/21): the whole-doc
141
+ * answer costs ~200–250k input tokens, so the spend is capped hard
142
+ * and measured (route "ask-escalation"). */
143
+ export declare const ESCALATION_DAILY_DEFAULT = 10;
139
144
  export declare function roleModel(env: any, role: keyof typeof MODELS): string;
140
145
  /** Per-deployment effort override for the answer lane (ANSWER_EFFORT).
141
146
  * The effort–accuracy curve is front-loaded (DeepSeek-V4.1-Flash report,
@@ -0,0 +1,27 @@
1
+ import type { StoreQuery } from "./ports/store.ts";
2
+ export interface AssembledDocument {
3
+ docidentifier: string;
4
+ text: string;
5
+ clauses: Set<string>;
6
+ truncated: boolean;
7
+ }
8
+ /** Assemble the WHOLE document from the chunks table in reading order
9
+ * (rowid preserves the parse's order — TODO.impl/02's invariant),
10
+ * capped. The clause set is every clause anchor the document carries,
11
+ * plus their dotted prefixes (a citation of 5.3.2 verifies when the
12
+ * document carries 5.3.2 itself or a longer clause beneath it). */
13
+ export declare function assembleDocument(store: StoreQuery, docidentifier: string, capChars: number, lang?: string): Promise<AssembledDocument | null>;
14
+ /** The clause-like tokens the ANSWER references (d.d and d.d.d shapes,
15
+ * including ranges "5.3–5.5"). Every token must resolve in the
16
+ * document's clause set — a cited clause the document does not carry
17
+ * makes the whole answer unverifiable. */
18
+ export declare function verifyAnchors(answer: string, clauses: Set<string>): {
19
+ ok: boolean;
20
+ missing: string[];
21
+ };
22
+ /** The system prompt reads the publisher from the profile — the
23
+ * publisher-leak lint's law (a hardcoded name is a leak). */
24
+ export declare const escalationSystem: () => string;
25
+ /** The escalation's daily budget: a per-bucket KV counter. */
26
+ export declare function escalationAllowed(kv: any, bucketId: string, dailyCap: number, day: string): Promise<boolean>;
27
+ export declare function chargeEscalation(kv: any, bucketId: string, day: string): Promise<void>;
package/dist/quota.d.ts CHANGED
@@ -16,8 +16,8 @@ export declare function telemetry(env: Env, ctx: Background, tier: string, route
16
16
  retries?: number;
17
17
  }): void;
18
18
  export declare function estimateTokens(chars: number): number;
19
- export declare function tokenLimit(env: Env, bucketId: string): number;
20
- export declare function tokenBudget(env: Env, bucketId: string): Promise<{
19
+ export declare function tokenLimit(env: Env, bucketId: string, keyDayLimitAsks?: number): number;
20
+ export declare function tokenBudget(env: Env, bucketId: string, keyDayLimitAsks?: number): Promise<{
21
21
  used: number;
22
22
  limit: number;
23
23
  }>;
@@ -25,7 +25,7 @@ export declare function chargeTokens(env: Env, bucketId: string, tokens: number)
25
25
  export declare function usageTotal(usage: unknown): number | null;
26
26
  export declare const CREDIT_TOKEN_UNIT = 1000;
27
27
  export declare function creditLimit(env: Env, bucketId: string): number;
28
- export declare function creditBudget(env: Env, bucketId: string): Promise<{
28
+ export declare function creditBudget(env: Env, bucketId: string, keyDayLimitAsks?: number): Promise<{
29
29
  credits_used: number;
30
30
  credits_limit: number;
31
31
  }>;
@@ -0,0 +1,14 @@
1
+ import {
2
+ handleSearch
3
+ } from "./chunk-VDFOVWE6.js";
4
+ import "./chunk-RBRBQJYT.js";
5
+ import "./chunk-BAOKHV2D.js";
6
+ import "./chunk-TLPUJMAF.js";
7
+ import "./chunk-ETLSWSZ7.js";
8
+ import "./chunk-MZQEI4VJ.js";
9
+ import "./chunk-IZ3GSYMD.js";
10
+ import "./chunk-3FYJM7LH.js";
11
+ import "./chunk-YGQCVPX6.js";
12
+ export {
13
+ handleSearch
14
+ };
@@ -4,10 +4,10 @@ import {
4
4
  parseToolCall,
5
5
  runTool,
6
6
  toolNote
7
- } from "./chunk-XO26UIFH.js";
8
- import "./chunk-7RZ2D64X.js";
9
- import "./chunk-5HCVX34C.js";
10
- import "./chunk-QYTCQIA6.js";
7
+ } from "./chunk-BMODSEKT.js";
8
+ import "./chunk-BAOKHV2D.js";
9
+ import "./chunk-MZQEI4VJ.js";
10
+ import "./chunk-IZ3GSYMD.js";
11
11
  import "./chunk-3FYJM7LH.js";
12
12
  import "./chunk-YGQCVPX6.js";
13
13
  export {
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  authenticate
3
- } from "../../chunk-XMUG75ZV.js";
4
- import "../../chunk-QYTCQIA6.js";
3
+ } from "../../chunk-TLPUJMAF.js";
4
+ import "../../chunk-IZ3GSYMD.js";
5
5
  import {
6
6
  P,
7
7
  setProfile
@@ -1,5 +1,6 @@
1
1
  import {
2
2
  DATASETS,
3
+ ESCALATION_DAILY_DEFAULT,
3
4
  LIMITS,
4
5
  MODELS,
5
6
  STARTERS,
@@ -16,10 +17,11 @@ import {
16
17
  roleModel,
17
18
  sha256Hex,
18
19
  today
19
- } from "../../chunk-QYTCQIA6.js";
20
+ } from "../../chunk-IZ3GSYMD.js";
20
21
  import "../../chunk-3FYJM7LH.js";
21
22
  export {
22
23
  DATASETS,
24
+ ESCALATION_DAILY_DEFAULT,
23
25
  LIMITS,
24
26
  MODELS,
25
27
  STARTERS,
@@ -9,16 +9,16 @@ import {
9
9
  listUserDocuments,
10
10
  scoreFaithfulness,
11
11
  scoreJudge
12
- } from "../../chunk-JVKJWLI7.js";
12
+ } from "../../chunk-IDQND3AA.js";
13
13
  import "../../chunk-IRCDOFP4.js";
14
14
  import {
15
15
  TOOLS_REGISTRY,
16
16
  bindModelNode,
17
17
  modelGroundingBlock
18
- } from "../../chunk-XO26UIFH.js";
18
+ } from "../../chunk-BMODSEKT.js";
19
19
  import {
20
20
  handleSearch
21
- } from "../../chunk-YQQ3W5CE.js";
21
+ } from "../../chunk-VDFOVWE6.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-XTWH3PS6.js";
46
+ } from "../../chunk-RBRBQJYT.js";
47
47
  import {
48
48
  embed,
49
49
  generateOnce
50
- } from "../../chunk-7RZ2D64X.js";
50
+ } from "../../chunk-BAOKHV2D.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-XMUG75ZV.js";
59
+ } from "../../chunk-TLPUJMAF.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-5HCVX34C.js";
66
+ } from "../../chunk-MZQEI4VJ.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-QYTCQIA6.js";
77
+ } from "../../chunk-IZ3GSYMD.js";
78
78
  import {
79
79
  P,
80
80
  setProfile
@@ -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-BTH6YAOB.js");
1186
+ const { runTool, TOOLS_REGISTRY: TOOLS_REGISTRY2 } = await import("../../tools-VMZSXLXM.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-5KXF53IL.js")).handleAsk(env, ctx, inner, tier, key) : await (await import("../../search-4FWS4HVI.js")).handleSearch(env, ctx, inner, tier, key);
1192
+ const res = name === "ask" ? await (await import("../../ask-O7HJIZPK.js")).handleAsk(env, ctx, inner, tier, key) : await (await import("../../search-3H2ENWHQ.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-5HCVX34C.js";
8
- import "../../chunk-QYTCQIA6.js";
7
+ } from "../../chunk-MZQEI4VJ.js";
8
+ import "../../chunk-IZ3GSYMD.js";
9
9
  import "../../chunk-3FYJM7LH.js";
10
10
  export {
11
11
  entitlementScope,
package/package.json CHANGED
@@ -27,7 +27,7 @@
27
27
  "playwright": "^1.62.1",
28
28
  "yaml": "^2.9.1"
29
29
  },
30
- "version": "0.2.185",
30
+ "version": "0.2.187",
31
31
  "description": "The Konneal engine: the publisher-agnostic build pipeline and API plane for standards intelligence (retrieval, answer contract, verdicts, evaluation).",
32
32
  "license": "BSD-3-Clause",
33
33
  "type": "module",
@@ -48,6 +48,8 @@ import { chargeTokens, checkQuota, clientIp, creditBudget, creditEstimate, estim
48
48
  import { graphExpand, editionNote } from "./graph";
49
49
  import { registerNote, searchRegister, certificateLinks, registerAggregateIntent, registerAggregate, aggregateNote, aggregateBlock, queryFamily, registerBypassesCache } from "./certificates";
50
50
  import { queryUserLane, memberDocFields, fieldsAsText } from "./userDocuments";
51
+ import { assembleDocument, verifyAnchors, escalationAllowed, chargeEscalation, escalationSystem } from "./escalation";
52
+ import { ESCALATION_DAILY_DEFAULT } from "./config";
51
53
  import { cfModelRunner, cfStore, cfVectorIndex } from "./ports/cloudflare/adapters";
52
54
  import { TOOL_DECLARATION, parseToolCall, runTool, toolNote } from "./tools";
53
55
  import { operationsLane } from "./operations.ts";
@@ -286,10 +288,10 @@ function messageChars(messages: any[]): number {
286
288
  /** Post-generation true-up: the model's own usage when the stream
287
289
  * reported it, the character estimate otherwise — charged, then the
288
290
  * budget's fresh state returned for the quota payload. */
289
- async function chargeAnswerTokens(env: Env, bucketId: string, stats: { usage?: unknown } | undefined, promptChars: number, answerChars: number, extraTokens = 0): Promise<{ tokens_used: number; token_limit: number }> {
291
+ async function chargeAnswerTokens(env: Env, bucketId: string, stats: { usage?: unknown } | undefined, promptChars: number, answerChars: number, extraTokens = 0, keyDayLimitAsks?: number): Promise<{ tokens_used: number; token_limit: number }> {
290
292
  const total = (usageTotal(stats?.usage) ?? estimateTokens(promptChars + answerChars)) + extraTokens;
291
293
  await chargeTokens(env, bucketId, total);
292
- const budget = await tokenBudget(env, bucketId);
294
+ const budget = await tokenBudget(env, bucketId, keyDayLimitAsks);
293
295
  return { tokens_used: budget.used, token_limit: budget.limit };
294
296
  }
295
297
 
@@ -419,6 +421,12 @@ async function handleAsk(
419
421
  : tier === "member" || member ? num(env as any, "MEMBER_DAY_ASK", 300)
420
422
  : num(env as any, "ANON_DAY_ASK", 20);
421
423
  const bucketId = memberKey ? `sub:${memberKey}` : tier === "key" ? `key:${key!.id}` : member ? `sub:${member.sub}` : clientIp(req);
424
+ // the KEY'S OWN day_limit drives BOTH counters (asks and tokens) — the
425
+ // owner's 2026-11-09 ruling: the serving cap is for USERS, not
426
+ // operators; quota.ts derives tokens = asks × 2000, so an operator
427
+ // key minted at day_limit 50000 carries a 100M-token day, while the
428
+ // default user key stays at 4M
429
+ const keyDayLimit = tier === "key" ? key?.day_limit : undefined;
422
430
  const quota = await checkQuota(env, "ask", bucketId, limit, effort === "low" ? 1 : 2);
423
431
  const creditPreview = creditEstimate({ effort, toolTurns: body?.multi_turn !== false ? 3 : 0, image: false });
424
432
  if (!quota.ok) {
@@ -426,12 +434,12 @@ async function handleAsk(
426
434
  }
427
435
  // the real allowance is the day's TOKENS (the 2026-09-29 shift): the
428
436
  // request cap above is the anti-abuse backstop, this is the budget
429
- const tokBudget = await tokenBudget(env, bucketId);
437
+ const tokBudget = await tokenBudget(env, bucketId, keyDayLimit);
430
438
  // the credit preview (2026-10-11): what this ask will cost, shown in
431
439
  // the refusal when the day's credits are spent — effort + armed tool
432
440
  // turns + multimodality, one honest number
433
441
  if (tokBudget.used >= tokBudget.limit) {
434
- const cb = await creditBudget(env, bucketId);
442
+ const cb = await creditBudget(env, bucketId, keyDayLimit);
435
443
  return err(429, "quota_exceeded", `Daily credits reached (${cb.credits_limit} credits, ${cb.credits_used} used). Try again tomorrow.`);
436
444
  }
437
445
  (quota as any).tokens_used = tokBudget.used;
@@ -895,7 +903,7 @@ let convEntities: Array<{ entity: string; kind: string }> = [];
895
903
  aggregateNoteText = aggregateNote(agg);
896
904
  const queryHash = await sha256Hex(q.query);
897
905
  telemetry(env, ctx, tier, "ask", MODELS.member, true, answer!.length, queryHash, q.lang, undefined, telemetryMeta());
898
- const tq = await chargeAnswerTokens(env, bucketId, undefined, q.query.length, answer!.length);
906
+ const tq = await chargeAnswerTokens(env, bucketId, undefined, q.query.length, answer!.length, keyDayLimit);
899
907
  const payload = {
900
908
  answer,
901
909
  citations: [{ docidentifier: `${P().publisher.name}-CS certificate register (family ${agg.family})`, corpus: "register" }],
@@ -906,7 +914,7 @@ let convEntities: Array<{ entity: string; kind: string }> = [];
906
914
  context_applied: NO_CONTEXT,
907
915
  read: readAs(),
908
916
  ...(ablate ? { ablate } : {}),
909
- quota: { ...quota, ...tq, credits: await creditBudget(env, bucketId), credit_estimate: creditPreview },
917
+ quota: { ...quota, ...tq, credits: await creditBudget(env, bucketId, keyDayLimit), credit_estimate: creditPreview },
910
918
  };
911
919
  if (live) {
912
920
  live!.send({ type: "citations", citations: payload.citations, quota: payload.quota, context_applied: NO_CONTEXT });
@@ -938,6 +946,10 @@ let convEntities: Array<{ entity: string; kind: string }> = [];
938
946
  const registerCitation = registerOwns
939
947
  ? [{ docidentifier: `${P().publisher.name}-CS certificate register`, corpus: "register" }]
940
948
  : [];
949
+ const escalationCitation = () =>
950
+ escalatedDoc
951
+ ? [{ docidentifier: `${escalatedDoc.docidentifier} (the complete publication)`, corpus: "escalated" }]
952
+ : [];
941
953
 
942
954
  // Conversational route, decided by query UNDERSTANDING (any language, any
943
955
  // phrasing) — not string matching. No retrieval: nothing in the corpus
@@ -972,8 +984,8 @@ let convEntities: Array<{ entity: string; kind: string }> = [];
972
984
  } catch {
973
985
  // stream ended prematurely — deliver what we have
974
986
  }
975
- const tq = await chargeAnswerTokens(env, bucketId, stats, messageChars(messages!), full.length, probeTokensUsed);
976
- live!.send({ type: "quota", quota: { ...quota, ...tq, credits: await creditBudget(env, bucketId), credit_estimate: creditPreview } });
987
+ const tq = await chargeAnswerTokens(env, bucketId, stats, messageChars(messages!), full.length, probeTokensUsed, keyDayLimit);
988
+ live!.send({ type: "quota", quota: { ...quota, ...tq, credits: await creditBudget(env, bucketId, keyDayLimit), credit_estimate: creditPreview } });
977
989
  live!.send({ type: "done", model, query_hash: queryHash, context_applied: NO_CONTEXT, read: readAs() });
978
990
  telemetry(env, ctx, tier, "ask", model, true, full.length, queryHash, q.lang, undefined, telemetryMeta());
979
991
  live!.close();
@@ -1037,8 +1049,8 @@ let convEntities: Array<{ entity: string; kind: string }> = [];
1037
1049
  live!.close();
1038
1050
  return null;
1039
1051
  }
1040
- const tq = await chargeAnswerTokens(env, bucketId, undefined, q.query.length, verdict.answer!.length);
1041
- return json({ answer: verdict.answer, citations, model, query_hash: queryHash, follow_ups: [], context_applied: draftCtxApplied, read: readAs(), ...(draftPayload ? { draft: draftPayload } : {}), ...(ablate ? { ablate } : {}), quota: { ...quota, ...tq, credits: await creditBudget(env, bucketId), credit_estimate: creditPreview } });
1052
+ const tq = await chargeAnswerTokens(env, bucketId, undefined, q.query.length, verdict.answer!.length, keyDayLimit);
1053
+ return json({ answer: verdict.answer, citations, model, query_hash: queryHash, follow_ups: [], context_applied: draftCtxApplied, read: readAs(), ...(draftPayload ? { draft: draftPayload } : {}), ...(ablate ? { ablate } : {}), quota: { ...quota, ...tq, credits: await creditBudget(env, bucketId, keyDayLimit), credit_estimate: creditPreview } });
1042
1054
  }
1043
1055
 
1044
1056
  // ── The api_call draft (TODO.ai-platform/09) — the operations
@@ -1072,8 +1084,8 @@ let convEntities: Array<{ entity: string; kind: string }> = [];
1072
1084
  live!.close();
1073
1085
  return null;
1074
1086
  }
1075
- const tq = await chargeAnswerTokens(env, bucketId, undefined, q.query.length, verdict.answer!.length);
1076
- return json({ answer: verdict.answer, citations: [], model, query_hash: queryHash, follow_ups: [], context_applied: callCtxApplied, read: readAs(), ...(draftPayload ? { draft: draftPayload } : {}), ...(ablate ? { ablate } : {}), quota: { ...quota, ...tq, credits: await creditBudget(env, bucketId), credit_estimate: creditPreview } });
1087
+ const tq = await chargeAnswerTokens(env, bucketId, undefined, q.query.length, verdict.answer!.length, keyDayLimit);
1088
+ return json({ answer: verdict.answer, citations: [], model, query_hash: queryHash, follow_ups: [], context_applied: callCtxApplied, read: readAs(), ...(draftPayload ? { draft: draftPayload } : {}), ...(ablate ? { ablate } : {}), quota: { ...quota, ...tq, credits: await creditBudget(env, bucketId, keyDayLimit), credit_estimate: creditPreview } });
1077
1089
  }
1078
1090
 
1079
1091
  // (declared before the retrieval try: the account block, the refusal
@@ -1548,7 +1560,7 @@ let convEntities: Array<{ entity: string; kind: string }> = [];
1548
1560
  const passagePool = registerOwns
1549
1561
  ? [...opsHits, ...hits].filter((h) => !!(h.metadata as any).cert_holder)
1550
1562
  : [...opsHits, ...hits];
1551
- const { messages, usedHits } = buildMessages(
1563
+ const built = buildMessages(
1552
1564
  q.query,
1553
1565
  passagePool,
1554
1566
  q.lang,
@@ -1559,6 +1571,43 @@ let convEntities: Array<{ entity: string; kind: string }> = [];
1559
1571
  budget,
1560
1572
  ablate?.noCompress !== true,
1561
1573
  );
1574
+ // The selective brute-force escalation (TODO.sota/21): the compressed
1575
+ // pipeline graded weak on a DOCUMENT-SCOPED question and the
1576
+ // corrective retry did not recover — answer from the WHOLE publication
1577
+ // uncut on the 1M-ctx model. The measured trade (18.1): brute force
1578
+ // 100% vs the window's ~92.9% at ~1/20th... reversed: the escalation
1579
+ // BUYS ~7pp at ~250k tokens, member/key only, daily-capped. One
1580
+ // message swap here feeds both delivery lanes.
1581
+ let escalateAnswer = false;
1582
+ let escalatedDoc: Awaited<ReturnType<typeof assembleDocument>> | null = null;
1583
+ let messages = built.messages;
1584
+ let usedHits = built.usedHits;
1585
+ const escalateWanted = crag.grade === "weak" && !crag.corrective?.accepted;
1586
+ if (
1587
+ escalateWanted &&
1588
+ understanding?.docidentifier &&
1589
+ (tier === "member" || tier === "key") &&
1590
+ !withImage
1591
+ ) {
1592
+ const day = new Date().toISOString().slice(0, 10);
1593
+ const bucket = tier === "key" ? `key:${key!.id}` : `sub:${member!.sub}`;
1594
+ if (await escalationAllowed(env.CACHE, bucket, num(env as any, "ESCALATION_DAILY", ESCALATION_DAILY_DEFAULT), day)) {
1595
+ const doc = await assembleDocument(cfStore(env.DB), understanding.docidentifier, 900_000, q.lang || "en").catch(() => null);
1596
+ if (doc && doc.text.length > 20_000) {
1597
+ const history = keptHistory.slice(-6);
1598
+ messages = [
1599
+ { role: "system", content: escalationSystem() },
1600
+ ...history,
1601
+ { role: "user", content: `Question: ${q.query}\n\nPublication ${doc.docidentifier}${doc.truncated ? " (truncated)" : ""}:\n\n${doc.text}` },
1602
+ ];
1603
+ usedHits = [];
1604
+ escalatedDoc = doc;
1605
+ escalateAnswer = true;
1606
+ await chargeEscalation(env.CACHE, bucket, day);
1607
+ console.log("escalation: answering from the whole", doc.docidentifier, `(${doc.text.length} chars)`);
1608
+ }
1609
+ }
1610
+ }
1562
1611
  // the decision pass (TODO.decisions/01): starts here so its calls run
1563
1612
  // concurrently with generation — the checklist section arrives the
1564
1613
  // moment the model's last token lands, never delaying the answer
@@ -1675,7 +1724,7 @@ let convEntities: Array<{ entity: string; kind: string }> = [];
1675
1724
  // provenance — ahead of the prose passages. The register rides first
1676
1725
  // when it owns the answer (the standing citation the aggregate path
1677
1726
  // has always attached).
1678
- const cites = [...registerCitation, ...(boundModel ? [modelCitation(boundModel), ...citations(usedHits)] : citations(usedHits))];
1727
+ const cites = escalateAnswer ? escalationCitation() : [...registerCitation, ...(boundModel ? [modelCitation(boundModel), ...citations(usedHits)] : citations(usedHits))];
1679
1728
 
1680
1729
  if (live) {
1681
1730
  const stream = await generateStream(env, model, messages, routeEffort(routed.route));
@@ -1739,8 +1788,8 @@ let convEntities: Array<{ entity: string; kind: string }> = [];
1739
1788
  } catch {
1740
1789
  // stream ended prematurely — deliver what we have
1741
1790
  }
1742
- const tq = await chargeAnswerTokens(env, bucketId, stats, messageChars(messages!), full.length, probeTokensUsed);
1743
- send({ type: "quota", quota: { ...quota, ...tq, credits: await creditBudget(env, bucketId), credit_estimate: creditPreview } });
1791
+ const tq = await chargeAnswerTokens(env, bucketId, stats, messageChars(messages!), full.length, probeTokensUsed, keyDayLimit);
1792
+ send({ type: "quota", quota: { ...quota, ...tq, credits: await creditBudget(env, bucketId, keyDayLimit), credit_estimate: creditPreview } });
1744
1793
  // the blind-answer guard ON THE STREAM PATH (the JSON path has
1745
1794
  // had it since 0.2.80): the register note carries rows and the
1746
1795
  // streamed text is the no-information refusal — the model
@@ -1773,6 +1822,17 @@ let convEntities: Array<{ entity: string; kind: string }> = [];
1773
1822
  }
1774
1823
  // the misplaced-pin wall rides the streamed path too: a
1775
1824
  // CITED stream is not a refusal
1825
+ // the escalation's citation contract (TODO.sota/21): every
1826
+ // clause the answer references must exist in the assembled
1827
+ // document — an unverifiable escalation IS the honest refusal
1828
+ if (escalateAnswer && escalatedDoc && !full.includes(refusalAnswer())) {
1829
+ const verdict = verifyAnchors(full, escalatedDoc.clauses);
1830
+ if (!verdict.ok) {
1831
+ console.log("escalation: unverifiable clause citations", verdict.missing.join(","), "— refusing honestly");
1832
+ full = refusalAnswer();
1833
+ send({ type: "token", v: refusalAnswer() });
1834
+ }
1835
+ }
1776
1836
  let canonical0 = exciseMisplacedPin(canonicalRefusal(full.replace(/^TOOL [a-z_.]+.*$\n?/gm, "").replace(/^\n+/, ""), refusalScope(answerCites(full))), answerCites(full));
1777
1837
  // answer contract v2: validate [[u:]] refs, resolve typed blocks
1778
1838
  const c2 = canonical0.includes(refusalAnswer())
@@ -2075,7 +2135,15 @@ let convEntities: Array<{ entity: string; kind: string }> = [];
2075
2135
  telemetry(env, ctx, tier, "ask", model, false, 0, queryHash, q.lang, undefined, telemetryMeta());
2076
2136
  return err(502, "generation_failed", "The generation model is unavailable; please retry.");
2077
2137
  }
2078
- const finalCites = [...registerCitation, ...(boundModel ? [modelCitation(boundModel!), ...citations(used)] : citations(used))];
2138
+ const finalCites = escalateAnswer ? escalationCitation() : [...registerCitation, ...(boundModel ? [modelCitation(boundModel!), ...citations(used)] : citations(used))];
2139
+ // the escalation's citation contract (the JSON lane's half)
2140
+ if (escalateAnswer && escalatedDoc && !answer!.includes(refusalAnswer())) {
2141
+ const verdict = verifyAnchors(answer!, escalatedDoc.clauses);
2142
+ if (!verdict.ok) {
2143
+ console.log("escalation: unverifiable clause citations", verdict.missing.join(","), "— refusing honestly");
2144
+ answer = canonicalRefusal(refusalAnswer(), refusalScope(false));
2145
+ }
2146
+ }
2079
2147
  const c2ns = answer!.includes(refusalAnswer())
2080
2148
  ? { text: answer, blocks: [] as Awaited<ReturnType<typeof contractV2>>["blocks"], dropped: [] as string[] }
2081
2149
  : await contractV2(env.DB, answer!, used);
@@ -2166,7 +2234,7 @@ let convEntities: Array<{ entity: string; kind: string }> = [];
2166
2234
  text: h.text.slice(0, 1200),
2167
2235
  ...((h.metadata as any).table_selection ? { sel: (h.metadata as any).table_selection } : {}),
2168
2236
  }));
2169
- const tq = await chargeAnswerTokens(env, bucketId, undefined, messageChars(messages!), answer!.length, probeTokensUsed);
2237
+ const tq = await chargeAnswerTokens(env, bucketId, undefined, messageChars(messages!), answer!.length, probeTokensUsed, keyDayLimit);
2170
2238
  // the reproducibility manifest (TODO.sota/14.6, v1): an opt-in, one-object
2171
2239
  // derivation record — the served snapshot identity, the answer model, the
2172
2240
  // retrieval anatomy (rank, corpus score, rerank score per used passage),
@@ -2205,7 +2273,7 @@ let convEntities: Array<{ entity: string; kind: string }> = [];
2205
2273
  total_ms: Date.now() - tStart,
2206
2274
  } }
2207
2275
  : {};
2208
- return json({ ...out, context: contextOut, read: readAs(), ...manifestOut, quota: { ...quota, ...tq, credits: await creditBudget(env, bucketId), credit_estimate: creditPreview } }, 200, { ...corsHeaders(req), "server-timing": serverTiming() });
2276
+ return json({ ...out, context: contextOut, read: readAs(), ...manifestOut, quota: { ...quota, ...tq, credits: await creditBudget(env, bucketId, keyDayLimit), credit_estimate: creditPreview } }, 200, { ...corsHeaders(req), "server-timing": serverTiming() });
2209
2277
  }
2210
2278
 
2211
2279
  // THE DISPATCH: the streamed lane's response went out at the top — the
@@ -38,6 +38,7 @@ export const MODELS = {
38
38
  // cross-encoder prunes, listwise orders jointly)
39
39
  listwise: "@cf/zai-org/glm-4.7-flash",
40
40
  // deep-research loop (G10): bounded agentic iterations, members-only
41
+ escalation: "@cf/deepseek-ai/deepseek-v4.1-flash-1017",
41
42
  research: "@cf/zai-org/glm-5.3-flash",
42
43
  // speculative draft-verify (TODO.sota/02 row 2): the strong verifier
43
44
  // over the cheap drafts — the research-tier model verifies; the drafter
@@ -187,6 +188,11 @@ export function processExpansion(): string {
187
188
  /** Per-deployment model override: <ROLE>_MODEL (e.g. UNDERSTAND_MODEL)
188
189
  * replaces the pinned default for that role. Ops lever for A/B-ing a
189
190
  * role's model without a code change; absent/invalid = the default. */
191
+ /** The escalation's daily per-bucket cap (TODO.sota/21): the whole-doc
192
+ * answer costs ~200–250k input tokens, so the spend is capped hard
193
+ * and measured (route "ask-escalation"). */
194
+ export const ESCALATION_DAILY_DEFAULT = 10;
195
+
190
196
  export function roleModel(env: any, role: keyof typeof MODELS): string {
191
197
  const ov = env[`${role.toUpperCase()}_MODEL`];
192
198
  return typeof ov === "string" && ov.startsWith("@cf/") ? ov : MODELS[role];
@@ -0,0 +1,97 @@
1
+ // The selective brute-force escalation (TODO.sota/21): when the
2
+ // compressed pipeline's retrieval grades weak on a DOCUMENT-SCOPED
3
+ // question, answer from the WHOLE publication uncut — deepseek's 1M
4
+ // context — instead of the window. The measured justification
5
+ // (TODO.sota/18.1): brute force answers 13/13 doc-scoped dev cases
6
+ // (100%) where the compressed window scores ~92.9%, at ~200–250k
7
+ // tokens per question. The trigger gates the spend: member/key tier
8
+ // only, one resolved document, after the corrective retry failed.
9
+ //
10
+ // The citation contract (settled in writing before the build,
11
+ // TODO.sota/21): the escalated answer cites clause numbers in prose,
12
+ // verified AGAINST THE ASSEMBLED DOCUMENT — every clause-like token
13
+ // the answer references must exist in the document's own clause set.
14
+ // Verified clause citations are honest anchors; anything else fails
15
+ // the answer to the honest refusal.
16
+
17
+ import type { StoreQuery } from "./ports/store.ts";
18
+ import { P } from "./profile.ts";
19
+
20
+ export interface AssembledDocument {
21
+ docidentifier: string;
22
+ text: string;
23
+ clauses: Set<string>;
24
+ truncated: boolean;
25
+ }
26
+
27
+ /** Assemble the WHOLE document from the chunks table in reading order
28
+ * (rowid preserves the parse's order — TODO.impl/02's invariant),
29
+ * capped. The clause set is every clause anchor the document carries,
30
+ * plus their dotted prefixes (a citation of 5.3.2 verifies when the
31
+ * document carries 5.3.2 itself or a longer clause beneath it). */
32
+ export async function assembleDocument(store: StoreQuery, docidentifier: string, capChars: number, lang = "en"): Promise<AssembledDocument | null> {
33
+ const res = await store
34
+ .prepare(
35
+ `SELECT text, clause_anchor, status, language FROM chunks
36
+ WHERE docidentifier = ?1 AND language = ?2 AND status = 'in-force'
37
+ ORDER BY rowid`,
38
+ )
39
+ .bind(docidentifier, lang)
40
+ .all();
41
+ const rows = (res.results ?? []) as unknown as { text: string; clause_anchor: string }[];
42
+ if (!rows.length) return null;
43
+ const clauses = new Set<string>();
44
+ const parts: string[] = [];
45
+ let total = 0;
46
+ let truncated = false;
47
+ for (const r of rows) {
48
+ const anchor = (r.clause_anchor || "").trim();
49
+ if (anchor) {
50
+ clauses.add(anchor);
51
+ const segs = anchor.split(".");
52
+ for (let i = 1; i < segs.length; i++) clauses.add(segs.slice(0, i).join("."));
53
+ }
54
+ if (total + r.text.length > capChars) {
55
+ truncated = true;
56
+ break;
57
+ }
58
+ parts.push(r.text);
59
+ total += r.text.length;
60
+ }
61
+ if (!parts.length) return null;
62
+ return { docidentifier, text: parts.join("\n\n"), clauses, truncated };
63
+ }
64
+
65
+ /** The clause-like tokens the ANSWER references (d.d and d.d.d shapes,
66
+ * including ranges "5.3–5.5"). Every token must resolve in the
67
+ * document's clause set — a cited clause the document does not carry
68
+ * makes the whole answer unverifiable. */
69
+ export function verifyAnchors(answer: string, clauses: Set<string>): { ok: boolean; missing: string[] } {
70
+ const cited = new Set<string>();
71
+ for (const m of answer.matchAll(/\b(\d{1,2}(?:\.\d{1,2}){1,3})\b/g)) cited.add(m[1]);
72
+ for (const m of answer.matchAll(/\b(\d{1,2}\.\d{1,2})\s?[–—-]\s?(\d{1,2}(?:\.\d{1,2}){1,3})\b/g)) cited.add(m[2]);
73
+ const missing: string[] = [];
74
+ for (const c of cited) {
75
+ if (!clauses.has(c) && ![...clauses].some((k) => k.startsWith(`${c}.`) || k === c)) missing.push(c);
76
+ }
77
+ return { ok: missing.length === 0, missing };
78
+ }
79
+
80
+ /** The system prompt reads the publisher from the profile — the
81
+ * publisher-leak lint's law (a hardcoded name is a leak). */
82
+ export const escalationSystem = (): string =>
83
+ `You are ${P().publisher.name}, the answer service over legal-metrology publications. ` +
84
+ "Answer the question using ONLY the publication text below. Cite the clause numbers you use. " +
85
+ "If the publication does not answer it, say so plainly.";
86
+
87
+ /** The escalation's daily budget: a per-bucket KV counter. */
88
+ export async function escalationAllowed(kv: any, bucketId: string, dailyCap: number, day: string): Promise<boolean> {
89
+ if (dailyCap <= 0) return false;
90
+ const n = Number((await kv.get(`esc:${day}:${bucketId}`)) ?? "0");
91
+ return n < dailyCap;
92
+ }
93
+
94
+ export async function chargeEscalation(kv: any, bucketId: string, day: string): Promise<void> {
95
+ const key = `esc:${day}:${bucketId}`;
96
+ await kv.put(key, String(Number((await kv.get(key)) ?? "0") + 1), { expirationTtl: 172_800 });
97
+ }
@@ -68,18 +68,24 @@ function tokenTier(bucketId: string): "anon" | "member" | "key" {
68
68
  return bucketId.startsWith("key:") ? "key" : bucketId.startsWith("sub:") ? "member" : "anon";
69
69
  }
70
70
 
71
- export function tokenLimit(env: Env, bucketId: string): number {
71
+ export function tokenLimit(env: Env, bucketId: string, keyDayLimitAsks?: number): number {
72
72
  const tier = tokenTier(bucketId);
73
73
  return tier === "key"
74
- ? num(env as any, "KEY_DAY_TOKENS", 4_000_000)
74
+ ? // the key's OWN day_limit is the one truth for both counters (the
75
+ // owner's 2026-11-09 ruling: the serving cap is for USERS, not
76
+ // operators): 1 ask ≈ 2000 tokens, so day_limit × 2000 — the
77
+ // default 2000 asks reproduces the historic 4M exactly
78
+ keyDayLimitAsks
79
+ ? keyDayLimitAsks * 2_000
80
+ : num(env as any, "KEY_DAY_TOKENS", 4_000_000)
75
81
  : tier === "member"
76
82
  ? num(env as any, "MEMBER_DAY_TOKENS", 1_500_000)
77
83
  : num(env as any, "ANON_DAY_TOKENS", 300_000);
78
84
  }
79
85
 
80
- export async function tokenBudget(env: Env, bucketId: string): Promise<{ used: number; limit: number }> {
86
+ export async function tokenBudget(env: Env, bucketId: string, keyDayLimitAsks?: number): Promise<{ used: number; limit: number }> {
81
87
  const used = Number((await env.CACHE.get(`t:${today()}:ask:${await sha256Hex(bucketId)}`)) ?? "0");
82
- return { used, limit: tokenLimit(env, bucketId) };
88
+ return { used, limit: tokenLimit(env, bucketId, keyDayLimitAsks) };
83
89
  }
84
90
 
85
91
  export async function chargeTokens(env: Env, bucketId: string, tokens: number): Promise<void> {
@@ -109,8 +115,8 @@ export function creditLimit(env: Env, bucketId: string): number {
109
115
  return Math.floor(tokenLimit(env, bucketId) / CREDIT_TOKEN_UNIT);
110
116
  }
111
117
 
112
- export async function creditBudget(env: Env, bucketId: string): Promise<{ credits_used: number; credits_limit: number }> {
113
- const b = await tokenBudget(env, bucketId);
118
+ export async function creditBudget(env: Env, bucketId: string, keyDayLimitAsks?: number): Promise<{ credits_used: number; credits_limit: number }> {
119
+ const b = await tokenBudget(env, bucketId, keyDayLimitAsks);
114
120
  return { credits_used: Math.ceil(b.used / CREDIT_TOKEN_UNIT), credits_limit: creditLimit(env, bucketId) };
115
121
  }
116
122
 
@@ -1,16 +0,0 @@
1
- import {
2
- handleAsk
3
- } from "./chunk-JVKJWLI7.js";
4
- import "./chunk-IRCDOFP4.js";
5
- import "./chunk-XO26UIFH.js";
6
- import "./chunk-XTWH3PS6.js";
7
- import "./chunk-7RZ2D64X.js";
8
- import "./chunk-XMUG75ZV.js";
9
- import "./chunk-ETLSWSZ7.js";
10
- import "./chunk-5HCVX34C.js";
11
- import "./chunk-QYTCQIA6.js";
12
- import "./chunk-3FYJM7LH.js";
13
- import "./chunk-YGQCVPX6.js";
14
- export {
15
- handleAsk
16
- };
@@ -1,14 +0,0 @@
1
- import {
2
- handleSearch
3
- } from "./chunk-YQQ3W5CE.js";
4
- import "./chunk-XTWH3PS6.js";
5
- import "./chunk-7RZ2D64X.js";
6
- import "./chunk-XMUG75ZV.js";
7
- import "./chunk-ETLSWSZ7.js";
8
- import "./chunk-5HCVX34C.js";
9
- import "./chunk-QYTCQIA6.js";
10
- import "./chunk-3FYJM7LH.js";
11
- import "./chunk-YGQCVPX6.js";
12
- export {
13
- handleSearch
14
- };