@konneal/engine 0.2.186 → 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.
@@ -1,9 +1,9 @@
1
1
  import {
2
2
  handleAsk
3
- } from "./chunk-PLONBTNM.js";
3
+ } from "./chunk-IDQND3AA.js";
4
4
  import "./chunk-IRCDOFP4.js";
5
5
  import "./chunk-BMODSEKT.js";
6
- import "./chunk-5ISPTV5G.js";
6
+ import "./chunk-RBRBQJYT.js";
7
7
  import "./chunk-BAOKHV2D.js";
8
8
  import "./chunk-TLPUJMAF.js";
9
9
  import "./chunk-ETLSWSZ7.js";
@@ -76,7 +76,7 @@ import {
76
76
  tokenBudget,
77
77
  understandQuery,
78
78
  usageTotal
79
- } from "./chunk-5ISPTV5G.js";
79
+ } from "./chunk-RBRBQJYT.js";
80
80
  import {
81
81
  embed,
82
82
  generateOnce
@@ -2342,10 +2342,10 @@ function messageChars(messages) {
2342
2342
  }
2343
2343
  return n;
2344
2344
  }
2345
- async function chargeAnswerTokens(env, bucketId, stats, promptChars, answerChars, extraTokens = 0) {
2345
+ async function chargeAnswerTokens(env, bucketId, stats, promptChars, answerChars, extraTokens = 0, keyDayLimitAsks) {
2346
2346
  const total = (usageTotal(stats?.usage) ?? estimateTokens(promptChars + answerChars)) + extraTokens;
2347
2347
  await chargeTokens(env, bucketId, total);
2348
- const budget = await tokenBudget(env, bucketId);
2348
+ const budget = await tokenBudget(env, bucketId, keyDayLimitAsks);
2349
2349
  return { tokens_used: budget.used, token_limit: budget.limit };
2350
2350
  }
2351
2351
  async function* sseTokens(stream, stats) {
@@ -2407,14 +2407,15 @@ async function handleAsk(env, ctx, req, tier, key) {
2407
2407
  const memberKey = tier === "key" ? key?.owner_sub ?? null : null;
2408
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);
2409
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;
2410
2411
  const quota = await checkQuota(env, "ask", bucketId, limit, effort === "low" ? 1 : 2);
2411
2412
  const creditPreview = creditEstimate({ effort, toolTurns: body?.multi_turn !== false ? 3 : 0, image: false });
2412
2413
  if (!quota.ok) {
2413
2414
  return err(429, "quota_exceeded", `Daily question limit reached (${quota.limit}). Try again tomorrow.`);
2414
2415
  }
2415
- const tokBudget = await tokenBudget(env, bucketId);
2416
+ const tokBudget = await tokenBudget(env, bucketId, keyDayLimit);
2416
2417
  if (tokBudget.used >= tokBudget.limit) {
2417
- const cb = await creditBudget(env, bucketId);
2418
+ const cb = await creditBudget(env, bucketId, keyDayLimit);
2418
2419
  return err(429, "quota_exceeded", `Daily credits reached (${cb.credits_limit} credits, ${cb.credits_used} used). Try again tomorrow.`);
2419
2420
  }
2420
2421
  quota.tokens_used = tokBudget.used;
@@ -2705,7 +2706,7 @@ Certificates are issued per recommendation family \u2014 the register carries no
2705
2706
  aggregateNoteText = aggregateNote(agg);
2706
2707
  const queryHash2 = await sha256Hex(q2.query);
2707
2708
  telemetry(env, ctx, tier, "ask", MODELS.member, true, answer2.length, queryHash2, q2.lang, void 0, telemetryMeta());
2708
- 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);
2709
2710
  const payload = {
2710
2711
  answer: answer2,
2711
2712
  citations: [{ docidentifier: `${P().publisher.name}-CS certificate register (family ${agg.family})`, corpus: "register" }],
@@ -2716,7 +2717,7 @@ Certificates are issued per recommendation family \u2014 the register carries no
2716
2717
  context_applied: NO_CONTEXT,
2717
2718
  read: readAs(),
2718
2719
  ...ablate ? { ablate } : {},
2719
- quota: { ...quota, ...tq2, credits: await creditBudget(env, bucketId), credit_estimate: creditPreview }
2720
+ quota: { ...quota, ...tq2, credits: await creditBudget(env, bucketId, keyDayLimit), credit_estimate: creditPreview }
2720
2721
  };
2721
2722
  if (live2) {
2722
2723
  live2.send({ type: "citations", citations: payload.citations, quota: payload.quota, context_applied: NO_CONTEXT });
@@ -2761,8 +2762,8 @@ ${summary}` }] : [],
2761
2762
  }
2762
2763
  } catch {
2763
2764
  }
2764
- const tq2 = await chargeAnswerTokens(env, bucketId, stats, messageChars(messages2), full.length, probeTokensUsed);
2765
- 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 } });
2766
2767
  live2.send({ type: "done", model, query_hash: queryHash2, context_applied: NO_CONTEXT, read: readAs() });
2767
2768
  telemetry(env, ctx, tier, "ask", model, true, full.length, queryHash2, q2.lang, void 0, telemetryMeta());
2768
2769
  live2.close();
@@ -2810,8 +2811,8 @@ ${summary}` }] : [],
2810
2811
  live2.close();
2811
2812
  return null;
2812
2813
  }
2813
- const tq2 = await chargeAnswerTokens(env, bucketId, void 0, q2.query.length, verdict.answer.length);
2814
- 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 } });
2815
2816
  }
2816
2817
  if (apiCallIntent) {
2817
2818
  const callCtxApplied = declaredCtx ? appliedContext(declaredCtx, null) : NO_CONTEXT;
@@ -2835,8 +2836,8 @@ ${summary}` }] : [],
2835
2836
  live2.close();
2836
2837
  return null;
2837
2838
  }
2838
- const tq2 = await chargeAnswerTokens(env, bucketId, void 0, q2.query.length, verdict.answer.length);
2839
- 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 } });
2840
2841
  }
2841
2842
  let liveRecords;
2842
2843
  let accountNote;
@@ -3299,8 +3300,8 @@ ${doc.text}` }
3299
3300
  }
3300
3301
  } catch {
3301
3302
  }
3302
- const tq2 = await chargeAnswerTokens(env, bucketId, stats, messageChars(messages), full.length, probeTokensUsed);
3303
- 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 } });
3304
3305
  if (register?.rows?.length && full.includes(refusalAnswer())) {
3305
3306
  console.log("blind-answer(stream): regenerating once");
3306
3307
  streamRestarts += 1;
@@ -3606,7 +3607,7 @@ ${doc.text}` }
3606
3607
  text: h.text.slice(0, 1200),
3607
3608
  ...h.metadata.table_selection ? { sel: h.metadata.table_selection } : {}
3608
3609
  }));
3609
- 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);
3610
3611
  let cragPassages = null;
3611
3612
  if (body?.manifest === true && used.length) {
3612
3613
  const grades = await gradePassages(env.AI, roleModel(env, "grader"), q2.query, used.map((h) => h.text));
@@ -3632,7 +3633,7 @@ ${doc.text}` }
3632
3633
  entailment,
3633
3634
  total_ms: Date.now() - tStart
3634
3635
  } } : {};
3635
- 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() });
3636
3637
  };
3637
3638
  if (liveResponse) {
3638
3639
  void pipeline(live, q).catch(() => {
@@ -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) {
@@ -6,7 +6,7 @@ import {
6
6
  sessionFrom,
7
7
  telemetry,
8
8
  understandQuery
9
- } from "./chunk-5ISPTV5G.js";
9
+ } from "./chunk-RBRBQJYT.js";
10
10
  import {
11
11
  corsHeaders,
12
12
  err,
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
  }>;
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  handleSearch
3
- } from "./chunk-TKGBLDLK.js";
4
- import "./chunk-5ISPTV5G.js";
3
+ } from "./chunk-VDFOVWE6.js";
4
+ import "./chunk-RBRBQJYT.js";
5
5
  import "./chunk-BAOKHV2D.js";
6
6
  import "./chunk-TLPUJMAF.js";
7
7
  import "./chunk-ETLSWSZ7.js";
@@ -9,7 +9,7 @@ import {
9
9
  listUserDocuments,
10
10
  scoreFaithfulness,
11
11
  scoreJudge
12
- } from "../../chunk-PLONBTNM.js";
12
+ } from "../../chunk-IDQND3AA.js";
13
13
  import "../../chunk-IRCDOFP4.js";
14
14
  import {
15
15
  TOOLS_REGISTRY,
@@ -18,7 +18,7 @@ import {
18
18
  } from "../../chunk-BMODSEKT.js";
19
19
  import {
20
20
  handleSearch
21
- } from "../../chunk-TKGBLDLK.js";
21
+ } from "../../chunk-VDFOVWE6.js";
22
22
  import {
23
23
  buildMessages,
24
24
  citations,
@@ -43,7 +43,7 @@ import {
43
43
  sessionFrom,
44
44
  telemetry,
45
45
  understandQuery
46
- } from "../../chunk-5ISPTV5G.js";
46
+ } from "../../chunk-RBRBQJYT.js";
47
47
  import {
48
48
  embed,
49
49
  generateOnce
@@ -1189,7 +1189,7 @@ async function callToolOnce(env, ctx, _req, tier, key, name, args, t0) {
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-CTYDXEQN.js")).handleAsk(env, ctx, inner, tier, key) : await (await import("../../search-5QSGBDBI.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 });
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.186",
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",
@@ -288,10 +288,10 @@ function messageChars(messages: any[]): number {
288
288
  /** Post-generation true-up: the model's own usage when the stream
289
289
  * reported it, the character estimate otherwise — charged, then the
290
290
  * budget's fresh state returned for the quota payload. */
291
- 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 }> {
292
292
  const total = (usageTotal(stats?.usage) ?? estimateTokens(promptChars + answerChars)) + extraTokens;
293
293
  await chargeTokens(env, bucketId, total);
294
- const budget = await tokenBudget(env, bucketId);
294
+ const budget = await tokenBudget(env, bucketId, keyDayLimitAsks);
295
295
  return { tokens_used: budget.used, token_limit: budget.limit };
296
296
  }
297
297
 
@@ -421,6 +421,12 @@ async function handleAsk(
421
421
  : tier === "member" || member ? num(env as any, "MEMBER_DAY_ASK", 300)
422
422
  : num(env as any, "ANON_DAY_ASK", 20);
423
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;
424
430
  const quota = await checkQuota(env, "ask", bucketId, limit, effort === "low" ? 1 : 2);
425
431
  const creditPreview = creditEstimate({ effort, toolTurns: body?.multi_turn !== false ? 3 : 0, image: false });
426
432
  if (!quota.ok) {
@@ -428,12 +434,12 @@ async function handleAsk(
428
434
  }
429
435
  // the real allowance is the day's TOKENS (the 2026-09-29 shift): the
430
436
  // request cap above is the anti-abuse backstop, this is the budget
431
- const tokBudget = await tokenBudget(env, bucketId);
437
+ const tokBudget = await tokenBudget(env, bucketId, keyDayLimit);
432
438
  // the credit preview (2026-10-11): what this ask will cost, shown in
433
439
  // the refusal when the day's credits are spent — effort + armed tool
434
440
  // turns + multimodality, one honest number
435
441
  if (tokBudget.used >= tokBudget.limit) {
436
- const cb = await creditBudget(env, bucketId);
442
+ const cb = await creditBudget(env, bucketId, keyDayLimit);
437
443
  return err(429, "quota_exceeded", `Daily credits reached (${cb.credits_limit} credits, ${cb.credits_used} used). Try again tomorrow.`);
438
444
  }
439
445
  (quota as any).tokens_used = tokBudget.used;
@@ -897,7 +903,7 @@ let convEntities: Array<{ entity: string; kind: string }> = [];
897
903
  aggregateNoteText = aggregateNote(agg);
898
904
  const queryHash = await sha256Hex(q.query);
899
905
  telemetry(env, ctx, tier, "ask", MODELS.member, true, answer!.length, queryHash, q.lang, undefined, telemetryMeta());
900
- 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);
901
907
  const payload = {
902
908
  answer,
903
909
  citations: [{ docidentifier: `${P().publisher.name}-CS certificate register (family ${agg.family})`, corpus: "register" }],
@@ -908,7 +914,7 @@ let convEntities: Array<{ entity: string; kind: string }> = [];
908
914
  context_applied: NO_CONTEXT,
909
915
  read: readAs(),
910
916
  ...(ablate ? { ablate } : {}),
911
- quota: { ...quota, ...tq, credits: await creditBudget(env, bucketId), credit_estimate: creditPreview },
917
+ quota: { ...quota, ...tq, credits: await creditBudget(env, bucketId, keyDayLimit), credit_estimate: creditPreview },
912
918
  };
913
919
  if (live) {
914
920
  live!.send({ type: "citations", citations: payload.citations, quota: payload.quota, context_applied: NO_CONTEXT });
@@ -978,8 +984,8 @@ let convEntities: Array<{ entity: string; kind: string }> = [];
978
984
  } catch {
979
985
  // stream ended prematurely — deliver what we have
980
986
  }
981
- const tq = await chargeAnswerTokens(env, bucketId, stats, messageChars(messages!), full.length, probeTokensUsed);
982
- 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 } });
983
989
  live!.send({ type: "done", model, query_hash: queryHash, context_applied: NO_CONTEXT, read: readAs() });
984
990
  telemetry(env, ctx, tier, "ask", model, true, full.length, queryHash, q.lang, undefined, telemetryMeta());
985
991
  live!.close();
@@ -1043,8 +1049,8 @@ let convEntities: Array<{ entity: string; kind: string }> = [];
1043
1049
  live!.close();
1044
1050
  return null;
1045
1051
  }
1046
- const tq = await chargeAnswerTokens(env, bucketId, undefined, q.query.length, verdict.answer!.length);
1047
- 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 } });
1048
1054
  }
1049
1055
 
1050
1056
  // ── The api_call draft (TODO.ai-platform/09) — the operations
@@ -1078,8 +1084,8 @@ let convEntities: Array<{ entity: string; kind: string }> = [];
1078
1084
  live!.close();
1079
1085
  return null;
1080
1086
  }
1081
- const tq = await chargeAnswerTokens(env, bucketId, undefined, q.query.length, verdict.answer!.length);
1082
- 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 } });
1083
1089
  }
1084
1090
 
1085
1091
  // (declared before the retrieval try: the account block, the refusal
@@ -1782,8 +1788,8 @@ let convEntities: Array<{ entity: string; kind: string }> = [];
1782
1788
  } catch {
1783
1789
  // stream ended prematurely — deliver what we have
1784
1790
  }
1785
- const tq = await chargeAnswerTokens(env, bucketId, stats, messageChars(messages!), full.length, probeTokensUsed);
1786
- 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 } });
1787
1793
  // the blind-answer guard ON THE STREAM PATH (the JSON path has
1788
1794
  // had it since 0.2.80): the register note carries rows and the
1789
1795
  // streamed text is the no-information refusal — the model
@@ -2228,7 +2234,7 @@ let convEntities: Array<{ entity: string; kind: string }> = [];
2228
2234
  text: h.text.slice(0, 1200),
2229
2235
  ...((h.metadata as any).table_selection ? { sel: (h.metadata as any).table_selection } : {}),
2230
2236
  }));
2231
- 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);
2232
2238
  // the reproducibility manifest (TODO.sota/14.6, v1): an opt-in, one-object
2233
2239
  // derivation record — the served snapshot identity, the answer model, the
2234
2240
  // retrieval anatomy (rank, corpus score, rerank score per used passage),
@@ -2267,7 +2273,7 @@ let convEntities: Array<{ entity: string; kind: string }> = [];
2267
2273
  total_ms: Date.now() - tStart,
2268
2274
  } }
2269
2275
  : {};
2270
- 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() });
2271
2277
  }
2272
2278
 
2273
2279
  // THE DISPATCH: the streamed lane's response went out at the top — the
@@ -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