@lensmcp/protocol-types 1.26.10 → 1.26.12

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 (54) hide show
  1. package/index.d.ts +6 -0
  2. package/index.js +1 -1
  3. package/lib/ai-cache-facts.d.ts +69 -0
  4. package/lib/ai-cache-facts.js +1 -0
  5. package/lib/ai-cache-verdict.d.ts +112 -0
  6. package/lib/ai-cache-verdict.js +1 -0
  7. package/lib/ai-cache.d.ts +133 -0
  8. package/lib/ai-cache.js +4 -0
  9. package/lib/ai-call-groups.d.ts +2 -0
  10. package/lib/ai-call-groups.js +2 -2
  11. package/lib/ai-call-row.d.ts +44 -0
  12. package/lib/ai-call-row.js +3 -3
  13. package/lib/ai-call.d.ts +6 -0
  14. package/lib/ai-call.js +9 -9
  15. package/lib/ai-compare.d.ts +298 -0
  16. package/lib/ai-compare.js +4 -0
  17. package/lib/ai-context.js +6 -6
  18. package/lib/ai-origins.js +9 -9
  19. package/lib/ai-together.d.ts +374 -0
  20. package/lib/ai-together.js +5 -0
  21. package/lib/bounded-clone.js +1 -1
  22. package/lib/bounded-map.js +1 -1
  23. package/lib/bounded-writer.js +1 -1
  24. package/lib/capture-demand.js +1 -1
  25. package/lib/dashboard-path.js +1 -1
  26. package/lib/dashboard.d.ts +11 -0
  27. package/lib/docker-errors.js +1 -1
  28. package/lib/docker-jobs.js +1 -1
  29. package/lib/docker-report.js +2 -2
  30. package/lib/docker-runs.js +3 -3
  31. package/lib/error-cause.js +6 -6
  32. package/lib/error-dismissal.js +1 -1
  33. package/lib/error-verdict.js +3 -3
  34. package/lib/event-loop.js +1 -1
  35. package/lib/expected-failure.js +2 -2
  36. package/lib/finding-proof.d.ts +35 -0
  37. package/lib/finding-proof.js +1 -0
  38. package/lib/flood-guard.js +1 -1
  39. package/lib/goal-design.js +1 -1
  40. package/lib/host-agents.js +1 -1
  41. package/lib/lint-coverage.js +1 -1
  42. package/lib/log-query.js +1 -1
  43. package/lib/metrics-reset.js +1 -1
  44. package/lib/overseer-findings.js +1 -1
  45. package/lib/peers.js +1 -1
  46. package/lib/perf-rules.js +1 -1
  47. package/lib/pod-memory.js +1 -1
  48. package/lib/producer-health.js +1 -1
  49. package/lib/remote-instances.js +1 -1
  50. package/lib/sources.js +1 -1
  51. package/lib/static-checks.js +1 -1
  52. package/lib/system-report.js +1 -1
  53. package/lib/team.js +1 -1
  54. package/package.json +1 -1
package/index.d.ts CHANGED
@@ -22,6 +22,7 @@ export * from './lib/log-query.js';
22
22
  export * from './lib/error-dismissal.js';
23
23
  export * from './lib/expected-failure.js';
24
24
  export * from './lib/error-verdict.js';
25
+ export * from './lib/finding-proof.js';
25
26
  export * from './lib/error-cause.js';
26
27
  export * from './lib/metrics-reset.js';
27
28
  export * from './lib/ai-content.js';
@@ -30,8 +31,13 @@ export * from './lib/ai-call.js';
30
31
  export * from './lib/ai-call-row.js';
31
32
  export * from './lib/ai-call-groups.js';
32
33
  export * from './lib/ai-context.js';
34
+ export * from './lib/ai-cache-facts.js';
35
+ export * from './lib/ai-cache.js';
36
+ export * from './lib/ai-cache-verdict.js';
37
+ export * from './lib/ai-together.js';
33
38
  export * from './lib/ai-origins.js';
34
39
  export * from './lib/ai-playground.js';
40
+ export * from './lib/ai-compare.js';
35
41
  export * from './lib/pod-memory.js';
36
42
  export * from './lib/perf-rules.js';
37
43
  export * from './lib/sources.js';
package/index.js CHANGED
@@ -1 +1 @@
1
- "use strict";export*from"./lib/schema-version.js";export*from"./lib/source-location.js";export*from"./lib/context.js";export*from"./lib/event.js";export*from"./lib/node.js";export*from"./lib/edge.js";export*from"./lib/attributes.js";export*from"./lib/producer-health.js";export*from"./lib/resources.js";export*from"./lib/tokens.js";export*from"./lib/capture-demand.js";export*from"./lib/bounded-clone.js";export*from"./lib/bounded-map.js";export*from"./lib/flood-guard.js";export*from"./lib/dashboard.js";export*from"./lib/dashboard-path.js";export*from"./lib/dashboard-lint.js";export*from"./lib/dashboard-typecheck.js";export*from"./lib/lint-coverage.js";export*from"./lib/static-checks.js";export*from"./lib/log-query.js";export*from"./lib/error-dismissal.js";export*from"./lib/expected-failure.js";export*from"./lib/error-verdict.js";export*from"./lib/error-cause.js";export*from"./lib/metrics-reset.js";export*from"./lib/ai-content.js";export*from"./lib/http-exchange.js";export*from"./lib/ai-call.js";export*from"./lib/ai-call-row.js";export*from"./lib/ai-call-groups.js";export*from"./lib/ai-context.js";export*from"./lib/ai-origins.js";export*from"./lib/ai-playground.js";export*from"./lib/pod-memory.js";export*from"./lib/perf-rules.js";export*from"./lib/sources.js";export*from"./lib/page-visit.js";export*from"./lib/replay.js";export*from"./lib/event-loop.js";export*from"./lib/workspace-actions.js";export*from"./lib/docker-jobs.js";export*from"./lib/docker-report.js";export*from"./lib/docker-runs.js";export*from"./lib/docker-errors.js";export*from"./lib/peers.js";export*from"./lib/hosts.js";export*from"./lib/cluster-hosts.js";export*from"./lib/dashboard-updates.js";export*from"./lib/host-agents.js";export*from"./lib/remote-instances.js";export*from"./lib/team.js";export*from"./lib/sessions.js";export*from"./lib/backlog.js";export*from"./lib/team-review-changes.js";export*from"./lib/goal-outcome.js";export*from"./lib/role-fidelity.js";export*from"./lib/goal-retro.js";export*from"./lib/follow-ups.js";export*from"./lib/changes.js";export*from"./lib/main-mirror.js";export*from"./lib/team-design.js";export*from"./lib/team-library.js";export*from"./lib/team-skills.js";export*from"./lib/system-report.js";export*from"./lib/overseer-findings.js";export*from"./lib/overseer-rounds.js";export*from"./lib/goal-design.js";export*from"./lib/overseer-messages.js";export*from"./lib/team-roadmap.js";export*from"./lib/team-prompts.js";export{PROOF_ACTIONS,NOT_RUN_KINDS}from"./lib/team-delivery.js";
1
+ "use strict";export*from"./lib/schema-version.js";export*from"./lib/source-location.js";export*from"./lib/context.js";export*from"./lib/event.js";export*from"./lib/node.js";export*from"./lib/edge.js";export*from"./lib/attributes.js";export*from"./lib/producer-health.js";export*from"./lib/resources.js";export*from"./lib/tokens.js";export*from"./lib/capture-demand.js";export*from"./lib/bounded-clone.js";export*from"./lib/bounded-map.js";export*from"./lib/flood-guard.js";export*from"./lib/dashboard.js";export*from"./lib/dashboard-path.js";export*from"./lib/dashboard-lint.js";export*from"./lib/dashboard-typecheck.js";export*from"./lib/lint-coverage.js";export*from"./lib/static-checks.js";export*from"./lib/log-query.js";export*from"./lib/error-dismissal.js";export*from"./lib/expected-failure.js";export*from"./lib/error-verdict.js";export*from"./lib/finding-proof.js";export*from"./lib/error-cause.js";export*from"./lib/metrics-reset.js";export*from"./lib/ai-content.js";export*from"./lib/http-exchange.js";export*from"./lib/ai-call.js";export*from"./lib/ai-call-row.js";export*from"./lib/ai-call-groups.js";export*from"./lib/ai-context.js";export*from"./lib/ai-cache-facts.js";export*from"./lib/ai-cache.js";export*from"./lib/ai-cache-verdict.js";export*from"./lib/ai-together.js";export*from"./lib/ai-origins.js";export*from"./lib/ai-playground.js";export*from"./lib/ai-compare.js";export*from"./lib/pod-memory.js";export*from"./lib/perf-rules.js";export*from"./lib/sources.js";export*from"./lib/page-visit.js";export*from"./lib/replay.js";export*from"./lib/event-loop.js";export*from"./lib/workspace-actions.js";export*from"./lib/docker-jobs.js";export*from"./lib/docker-report.js";export*from"./lib/docker-runs.js";export*from"./lib/docker-errors.js";export*from"./lib/peers.js";export*from"./lib/hosts.js";export*from"./lib/cluster-hosts.js";export*from"./lib/dashboard-updates.js";export*from"./lib/host-agents.js";export*from"./lib/remote-instances.js";export*from"./lib/team.js";export*from"./lib/sessions.js";export*from"./lib/backlog.js";export*from"./lib/team-review-changes.js";export*from"./lib/goal-outcome.js";export*from"./lib/role-fidelity.js";export*from"./lib/goal-retro.js";export*from"./lib/follow-ups.js";export*from"./lib/changes.js";export*from"./lib/main-mirror.js";export*from"./lib/team-design.js";export*from"./lib/team-library.js";export*from"./lib/team-skills.js";export*from"./lib/system-report.js";export*from"./lib/overseer-findings.js";export*from"./lib/overseer-rounds.js";export*from"./lib/goal-design.js";export*from"./lib/overseer-messages.js";export*from"./lib/team-roadmap.js";export*from"./lib/team-prompts.js";export{PROOF_ACTIONS,NOT_RUN_KINDS}from"./lib/team-delivery.js";
@@ -0,0 +1,69 @@
1
+ /**
2
+ * What the providers publish about their prompt caches, as dated data (foodguard-301 F): each fact with the page it
3
+ * was read from and the day it was read, so the cache verdicts ({@link aiCacheVerdicts}) and the review's guide quote
4
+ * the same numbers — and say when they are old. A fact older than {@link AI_GUIDANCE_STALE_DAYS} is shown as stale:
5
+ * read the page again, change the fact and its `readAt` here.
6
+ *
7
+ * Pure, and shared: the verdicts run on the server and the page names their sources.
8
+ */
9
+ /** A cache entry's lifetime, as the request sets it: OpenAI `30m`, `12h` (and `24h` / `in_memory` before GPT-5.6); Anthropic `5m`, `1h`. */
10
+ export type AiCacheTtl = '5m' | '1h' | '30m' | '12h' | '24h' | 'in_memory';
11
+ /** Where a fact was read, when, and how — `summary` when the page was read through a summarising fetch, not as written. */
12
+ export interface AiGuidanceSource {
13
+ url: string;
14
+ /** The day it was read, `YYYY-MM-DD`. */
15
+ readAt: string;
16
+ how: 'page' | 'summary';
17
+ }
18
+ /** A fact older than this many days is shown as stale. */
19
+ export declare const AI_GUIDANCE_STALE_DAYS = 45;
20
+ export declare const AI_GUIDANCE_SOURCES: {
21
+ /** Read twice on 2026-11-17 through a summarising fetch: the page refuses a verbatim copy. */
22
+ readonly openaiCaching: {
23
+ readonly url: "https://developers.openai.com/api/docs/guides/prompt-caching";
24
+ readonly readAt: "2026-11-17";
25
+ readonly how: "summary";
26
+ };
27
+ /** Read on 2026-11-17 through a summarising fetch. */
28
+ readonly openaiPricing: {
29
+ readonly url: "https://developers.openai.com/api/docs/pricing";
30
+ readonly readAt: "2026-11-17";
31
+ readonly how: "summary";
32
+ };
33
+ /** Read whole on 2026-11-17 (the platform's docs tool). */
34
+ readonly anthropicCaching: {
35
+ readonly url: "https://platform.claude.com/docs/en/build-with-claude/prompt-caching";
36
+ readonly readAt: "2026-11-17";
37
+ readonly how: "page";
38
+ };
39
+ };
40
+ export type AiGuidanceSourceId = keyof typeof AI_GUIDANCE_SOURCES;
41
+ /** How old a dated fact is, and whether it is stale — `undefined` days for a date that is not one. */
42
+ export declare function aiGuidanceAge(readAt: string, now?: number, staleDays?: number): {
43
+ days?: number;
44
+ stale: boolean;
45
+ };
46
+ /** One provider fact as data: what it says, its value where it has one, and its source. */
47
+ export interface AiCacheFact {
48
+ id: string;
49
+ provider: 'openai' | 'anthropic';
50
+ /** The models it holds for, in words (`GPT-5.6 and later`). */
51
+ models: string;
52
+ says: string;
53
+ value?: number | string | readonly string[];
54
+ source: AiGuidanceSourceId;
55
+ }
56
+ /** How long an entry lives, by the lifetime a request names. `in_memory` (before GPT-5.6): «5 to 10 minutes of inactivity, up to one hour» — 10 minutes here. */
57
+ export declare const AI_CACHE_TTL_MS: Record<AiCacheTtl, number>;
58
+ /** The provider facts the verdicts and the guide quote. */
59
+ export declare const AI_CACHE_FACTS: readonly AiCacheFact[];
60
+ /** One fact by its id, with its source. */
61
+ export declare function aiCacheFact(id: string): (AiCacheFact & {
62
+ from: AiGuidanceSource;
63
+ }) | undefined;
64
+ /** OpenAI's newer cache (GPT-5.6 and later, GPT-6.x): explicit mode, lifetimes, prewarm. */
65
+ export declare const openaiNewCache: (model: string | undefined) => boolean;
66
+ /** The shortest prefix a model caches, in tokens (the facts above). */
67
+ export declare function aiCacheMinTokens(provider: string, model: string | undefined): number;
68
+ /** The lifetime a request gets when it names none. */
69
+ export declare const aiDefaultTtl: (provider: string, model: string | undefined) => AiCacheTtl;
@@ -0,0 +1 @@
1
+ "use strict";var l=Object.defineProperty;var o=(e,t)=>l(e,"name",{value:t,configurable:!0});var c=Object.defineProperty,i=o((e,t)=>c(e,"name",{value:t,configurable:!0}),"a");export const AI_GUIDANCE_STALE_DAYS=45,AI_GUIDANCE_SOURCES={openaiCaching:{url:"https://developers.openai.com/api/docs/guides/prompt-caching",readAt:"2026-11-17",how:"summary"},openaiPricing:{url:"https://developers.openai.com/api/docs/pricing",readAt:"2026-11-17",how:"summary"},anthropicCaching:{url:"https://platform.claude.com/docs/en/build-with-claude/prompt-caching",readAt:"2026-11-17",how:"page"}};export function aiGuidanceAge(e,t=Date.now(),a=45){const s=Date.parse(`${e}T00:00:00Z`);if(!Number.isFinite(s))return{stale:!0};const p=Math.max(0,Math.floor((t-s)/864e5));return{days:p,stale:p>a}}o(aiGuidanceAge,"aiGuidanceAge"),i(aiGuidanceAge,"aiGuidanceAge");const n=6e4,r=60*n;export const AI_CACHE_TTL_MS={"5m":5*n,"1h":r,"30m":30*n,"12h":12*r,"24h":24*r,in_memory:10*n},AI_CACHE_FACTS=[{id:"openai.min-tokens",provider:"openai",models:"GPT-5.6 and later",says:"A prefix is cached from 1,024 visible input tokens; hidden system content does not count. Earlier models: the minimum depends on the request settings.",value:1024,source:"openaiCaching"},{id:"openai.modes",provider:"openai",models:"GPT-5.6 and later",says:'`prompt_cache_options.mode`: `implicit` puts one breakpoint at the end of the latest eligible message (a user message, the last tool response of a group, the last developer message of the opening group); `explicit` caches only where a content block carries `prompt_cache_breakpoint: { "mode": "explicit" }`.',value:["implicit","explicit"],source:"openaiCaching"},{id:"openai.no-breakpoint",provider:"openai",models:"GPT-5.6 and later",says:"Explicit mode with no breakpoint: the request reads and writes nothing.",source:"openaiCaching"},{id:"openai.max-writes",provider:"openai",models:"GPT-5.6 and later",says:"A request creates at most four cache writes; in implicit mode the implicit breakpoint takes one of them.",value:4,source:"openaiCaching"},{id:"openai.instructions",provider:"openai",models:"GPT-5.6 and later",says:"Top-level `instructions` cannot hold a breakpoint: reusable instructions go in an `input_text` block of a developer message.",source:"openaiCaching"},{id:"openai.after-last",provider:"openai",models:"GPT-5.6 and later",says:"Content after the last breakpoint is billed at the plain input rate, with no write charge.",source:"openaiCaching"},{id:"openai.ttl",provider:"openai",models:"GPT-5.6 and later",says:'`ttl: "30m"` (the default) writes at 1.25\xD7 the input rate; `"12h"` at 2.5\xD7. A breakpoint may set its own `ttl`. Moving 30-minute coverage to 12 hours is a new 12-hour write, with no credit for the earlier one.',value:["30m","12h"],source:"openaiCaching"},{id:"openai.write-x",provider:"openai",models:"GPT-5.6 and later",says:"Write multipliers on the input rate, by lifetime: 30m 1.25\xD7, 12h 2.5\xD7 \u2014 total rates, not surcharges.",value:["30m:1.25","12h:2.5"],source:"openaiCaching"},{id:"openai.read-x",provider:"openai",models:"GPT-5.6 and later",says:"A read costs 0.1\xD7 the input rate; 0.05\xD7 on GPT-6.2 Astra, GPT-6.2 Sol, GPT-6.1 Sol and GPT-6.1 Terra, whatever the lifetime.",value:.1,source:"openaiCaching"},{id:"openai.prewarm",provider:"openai",models:"GPT-5.6 and later",says:"`prompt_cache_options.prewarm: true` writes the cache and generates no output, billed at the write rate of its lifetime; the real request follows with the same prefix.",source:"openaiCaching"},{id:"openai.key",provider:"openai",models:"GPT-5.6 and later",says:"`prompt_cache_key` is optional (routing is automatic); a key keeps the cache apart per key.",source:"openaiCaching"},{id:"openai.usage",provider:"openai",models:"GPT-5.6 and later",says:"`input_tokens` includes reads and writes. `input_tokens_details.cached_tokens` are reads (writes excluded); `input_tokens_details.cache_write_tokens` are writes, split in `cache_write_tokens_details.ttl_30m_tokens` and `ttl_12h_tokens`. Plain input = input \u2212 cached \u2212 written.",source:"openaiCaching"},{id:"openai.ends-reuse",provider:"openai",models:"GPT-5.6 and later",says:"Reuse needs the whole rendered prefix to match up to a breakpoint. These settings are part of the cached prefix: `model`, `tools`, `parallel_tool_calls`, `text.format`, `reasoning.effort`, `text.verbosity`, `context_management`.",value:["model","tools","parallel_tool_calls","text.format","reasoning.effort","text.verbosity","context_management"],source:"openaiCaching"},{id:"openai.lookup",provider:"openai",models:"GPT-5.6 and later",says:"Lookup walks from the longest prefix to the shortest, on the machine the request lands on; it considers the first 2 and the latest 50 breakpoints.",source:"openaiCaching"},{id:"openai.concurrent",provider:"openai",models:"all",says:"The page does not say when a write becomes readable by a request sent at the same moment; it says a prewarm\u2019s follow-up should wait for the prewarm to complete.",source:"openaiCaching"},{id:"openai.tpm",provider:"openai",models:"all",says:"Cached input tokens still count toward the tokens-per-minute limit.",source:"openaiCaching"},{id:"openai.retention",provider:"openai",models:"before GPT-5.6",says:"Earlier models cache implicitly only, with `prompt_cache_retention`: `in_memory` (about 5\u201310 minutes of inactivity, up to an hour) or `24h` (the default without Zero Data Retention).",value:["in_memory","24h"],source:"openaiCaching"},{id:"anthropic.breakpoints",provider:"anthropic",models:"all Claude models",says:'A block marked `cache_control: { "type": "ephemeral" }` ends a cacheable prefix, in the order tools \u2192 system \u2192 messages; up to 4 breakpoints. A top-level `cache_control` (automatic caching) puts one on the last cacheable block and takes one of the 4. No `cache_control`: nothing is cached.',value:4,source:"anthropicCaching"},{id:"anthropic.ttl",provider:"anthropic",models:"all Claude models",says:'The default lifetime is 5 minutes, refreshed free on each read; `"ttl": "1h"` lives an hour. Longer lifetimes must come before shorter ones.',value:["5m","1h"],source:"anthropicCaching"},{id:"anthropic.write-x",provider:"anthropic",models:"all Claude models",says:"A 5-minute write costs 1.25\xD7 the input rate, a 1-hour write 2\xD7.",value:["5m:1.25","1h:2"],source:"anthropicCaching"},{id:"anthropic.read-x",provider:"anthropic",models:"all Claude models",says:"A read costs 0.1\xD7 the input rate; 0.05\xD7 on Claude Opus 5.5 and Sonnet 5.5; 0.025\xD7 on Claude Fable and Mythos 5.1 and 5.2.",value:.1,source:"anthropicCaching"},{id:"anthropic.min-tokens",provider:"anthropic",models:"by model",says:"The shortest cacheable prompt: 512 tokens on Claude Opus 5.5, Opus 5, Sonnet 5.5, Haiku 5.5 and Fable/Mythos 5.x; 1,024 on Sonnet 5, Opus 4.8 and Sonnet 4.x; 2,048 on Opus 4.7; 4,096 on Opus 4.5/4.6 and Haiku 4.5. Shorter prompts are not cached, without an error.",value:512,source:"anthropicCaching"},{id:"anthropic.lookback",provider:"anthropic",models:"all Claude models",says:"A breakpoint looks back at most 20 blocks for an entry earlier requests wrote; writes happen only at breakpoints.",value:20,source:"anthropicCaching"},{id:"anthropic.concurrent",provider:"anthropic",models:"all Claude models",says:"A cache entry becomes available only after the first response starts: for parallel requests to hit it, wait for the first response before sending the rest.",source:"anthropicCaching"},{id:"anthropic.usage",provider:"anthropic",models:"all Claude models",says:"`cache_read_input_tokens` are reads, `cache_creation_input_tokens` writes (split in `cache_creation.ephemeral_5m_input_tokens` / `ephemeral_1h_input_tokens`), `input_tokens` the rest after the last breakpoint.",source:"anthropicCaching"},{id:"anthropic.ends-reuse",provider:"anthropic",models:"all Claude models",says:"A change to the tools ends every level; web search, citations and speed end system and messages; `tool_choice`, images, thinking and effort settings end the messages level.",value:["tools","tool_choice","thinking","output_config.effort","speed"],source:"anthropicCaching"}];export function aiCacheFact(e){const t=AI_CACHE_FACTS.find(a=>a.id===e);return t?{...t,from:AI_GUIDANCE_SOURCES[t.source]}:void 0}o(aiCacheFact,"aiCacheFact"),i(aiCacheFact,"aiCacheFact");export const openaiNewCache=i(e=>!!e&&/^(?:openai\/)?gpt-(?:5\.(?:[6-9]|\d{2,})|[6-9]|\d{2,})/.test(e),"openaiNewCache");export function aiCacheMinTokens(e,t){if(e!=="anthropic")return 1024;const a=(t??"").replace(/^anthropic\//,"");return/^claude-(?:opus-4-[56]|haiku-4-5)/.test(a)?4096:/^claude-opus-4-7/.test(a)?2048:/^claude-(?:sonnet-5(?!-5)|opus-4-8|sonnet-4|opus-4(?:-1)?(?![-\d]))/.test(a)?1024:512}o(aiCacheMinTokens,"aiCacheMinTokens"),i(aiCacheMinTokens,"aiCacheMinTokens");export const aiDefaultTtl=i((e,t)=>e==="anthropic"?"5m":openaiNewCache(t)?"30m":"24h","aiDefaultTtl");
@@ -0,0 +1,112 @@
1
+ import type { AiCallRow } from './ai-call-row.js';
2
+ import { type AiCacheTtl } from './ai-cache-facts.js';
3
+ /**
4
+ * A verdict on every kept call's prompt cache, by arithmetic — no model (foodguard-301 B). Each call is set against the
5
+ * earlier calls of its agent inside the cache's lifetime, and its writes against the later ones:
6
+ *
7
+ * - `read` — it read the prefix it could;
8
+ * - `first-writer` — it wrote a prefix no earlier call of its agent had;
9
+ * - `duplicate-write` — an earlier call had already written (or read) the same prefix inside the lifetime; `race` when
10
+ * every such call was still in flight when this one was sent — the write had not finished;
11
+ * - `broken-prefix` — it shares more of its prefix with an earlier call than it read: no breakpoint ends where they
12
+ * part; the region they part in is named (and, on the call's page, the first line that differs);
13
+ * - `cold` — the same prefix was last used longer ago than its lifetime;
14
+ * - `write-nothing-read` — no later call of its agent read what it wrote inside the lifetime;
15
+ * - `no-cache` — under the minimum, explicit mode with no breakpoint, an Anthropic call with no `cache_control`;
16
+ * - `unknown` — the provider's count was not kept (a failed call, an answer the capture cut).
17
+ *
18
+ * Each with its cost in dollars by § 2.2 of the issue: a call that misses adds `P·(w − r)`, a write nothing reads
19
+ * loses `P·(w − p)`, a prefix that could have been read and was sent plain loses `P·(p − r)` — with the arithmetic
20
+ * written out, and `estimate` where `P` comes from the estimated position of a breakpoint or a mark rather than from
21
+ * the provider's count. A verdict's `prefix` (the breakpoint's hash) is what calls reviewed together can be grouped by.
22
+ *
23
+ * Pure: run on the rows the AI calls index holds (their `cache`, with its marks), with the server's prices.
24
+ */
25
+ export type AiCacheVerdictKind = 'read' | 'first-writer' | 'duplicate-write' | 'broken-prefix' | 'cold' | 'write-nothing-read' | 'no-cache' | 'unknown';
26
+ export declare const AI_CACHE_VERDICT_LABEL: Record<AiCacheVerdictKind, string>;
27
+ /** One line of what a verdict cost: the tokens it is about, the dollars, the arithmetic. */
28
+ export interface AiCacheCost {
29
+ kind: AiCacheVerdictKind;
30
+ tokens: number;
31
+ /** Lost against the best this call could have done, USD — none without a price. */
32
+ usd?: number;
33
+ /** `22,657 × ($2.50 − $0.10)/M` */
34
+ arithmetic?: string;
35
+ /** `tokens` comes from an estimated position, not from the provider's count. */
36
+ estimate: boolean;
37
+ }
38
+ export interface AiCacheVerdict {
39
+ kind: AiCacheVerdictKind;
40
+ /** Also true of it — a broken prefix whose write nothing read… */
41
+ also?: AiCacheVerdictKind[];
42
+ /** In words, with the numbers. */
43
+ said: string;
44
+ costs: AiCacheCost[];
45
+ /** The costs summed. */
46
+ lostUsd?: number;
47
+ /** What its reads saved against plain input, USD. */
48
+ savedUsd?: number;
49
+ /** The breakpoint it is about (its prefix's hash): what calls reviewed together group by. */
50
+ prefix?: string;
51
+ /** The tokens read and written, as the provider counted them. */
52
+ read?: number;
53
+ written?: number;
54
+ /** The earlier call it is set against: when it was sent and ended, and whether it was still in flight. */
55
+ against?: {
56
+ id: string;
57
+ at: number;
58
+ ended?: number;
59
+ inFlight: boolean;
60
+ gapMs: number;
61
+ prewarm?: true;
62
+ };
63
+ /** A duplicate write while the call that wrote the prefix was still in flight: the write had not finished when this one was sent. */
64
+ race?: boolean;
65
+ /** A duplicate write: earlier calls inside the lifetime that read the prefix before this one was sent. */
66
+ readBefore?: number;
67
+ /** A broken prefix: where it parts from the earlier call, and the tokens they share (estimated). */
68
+ brokeAt?: {
69
+ region: string;
70
+ tokens: number;
71
+ id: string;
72
+ };
73
+ /** Cold: how long the prefix had been idle. */
74
+ idleMs?: number;
75
+ /** Later calls of its agent that read what it wrote, inside the lifetime — and those whose count was not kept. */
76
+ readBy?: number;
77
+ maybeReadBy?: number;
78
+ /** Its lifetime has not run out: a later call may still read what it wrote. */
79
+ open?: true;
80
+ prewarm?: true;
81
+ /** What it rests on: the price's source and date, the provider's facts' — `stale` past their age. */
82
+ basis: {
83
+ price?: {
84
+ source?: string;
85
+ readAt?: string;
86
+ stale?: true;
87
+ };
88
+ facts: {
89
+ source: string;
90
+ readAt: string;
91
+ stale?: true;
92
+ };
93
+ };
94
+ }
95
+ /** A model's prices for the verdicts, USD per million tokens. */
96
+ export interface AiCacheRates {
97
+ input: number;
98
+ cacheRead?: number;
99
+ writes: Partial<Record<AiCacheTtl, number>>;
100
+ source?: string;
101
+ readAt?: string;
102
+ stale?: boolean;
103
+ }
104
+ export type AiCacheRatesOf = (model: string, inputTokens: number) => AiCacheRates | undefined;
105
+ /** The rows the verdicts need — what an index row carries. */
106
+ type Row = Pick<AiCallRow, 'id' | 'at' | 'durationMs' | 'agent' | 'model' | 'provider' | 'tokens' | 'cache' | 'prewarm' | 'failed' | 'api'>;
107
+ /**
108
+ * Every row's verdict, by id — rows with no cache (an embedding) have none. `now` decides which writes may still be
109
+ * read (their lifetime has not run out).
110
+ */
111
+ export declare function aiCacheVerdicts(rows: readonly Row[], ratesOf: AiCacheRatesOf, now?: number): Map<string, AiCacheVerdict>;
112
+ export {};
@@ -0,0 +1 @@
1
+ "use strict";var Ct=Object.defineProperty;var F=(e,o)=>Ct(e,"name",{value:o,configurable:!0});var Ut=Object.defineProperty,k=F((e,o)=>Ut(e,"name",{value:o,configurable:!0}),"w");import{AI_CACHE_TTL_MS as et,AI_GUIDANCE_SOURCES as kt,aiCacheMinTokens as It,aiGuidanceAge as Dt}from"./ai-cache-facts.js";export const AI_CACHE_VERDICT_LABEL={read:"read","first-writer":"first writer","duplicate-write":"duplicate write","broken-prefix":"broken prefix",cold:"cold","write-nothing-read":"write nothing read","no-cache":"no cache",unknown:"unknown"};const b=k(e=>Math.round(e).toLocaleString("en-US"),"fmt"),ot=k(e=>`$${e<.01&&e>0?e.toFixed(4):e.toFixed(2)}`,"money"),R=k(e=>`$${Number(e.toFixed(4))}`,"rate"),_=k(e=>Math.round(e*1e6)/1e6,"usd"),V=k(e=>e<1e3?`${Math.round(e)} ms`:e<12e4?`${(e/1e3).toFixed(1)} s`:e<72e5?`${Math.round(e/6e4)} min`:`${(e/36e5).toFixed(1)} h`,"dur"),Et=k(e=>e.tokens?.input!==void 0&&e.cache!==void 0&&!e.failed,"counted");export function aiCacheVerdicts(e,o,g=Date.now()){const h=new Map,l=new Map;for(const d of e){if(!d.cache)continue;const i=l.get(d.agent.key);i?i.push(d):l.set(d.agent.key,[d])}for(const d of l.values()){d.sort((i,s)=>i.at-s.at||i.id.localeCompare(s.id));for(const[i,s]of $t(d,o,g))h.set(i,s)}return h}F(aiCacheVerdicts,"aiCacheVerdicts"),k(aiCacheVerdicts,"aiCacheVerdicts");function gt(e,o){const g=e==="anthropic"?kt.anthropicCaching:kt.openaiCaching;return{source:g.url,readAt:g.readAt,...Dt(g.readAt,o).stale?{stale:!0}:{}}}F(gt,"It"),k(gt,"factsOf");function $t(e,o,g){const h=[],l=new Map,d=new Map;e.forEach((i,s)=>{const n=i.cache,$=i.at,x=i.durationMs!==void 0?i.at+i.durationMs:void 0,I=et[n.ttl],a={row:i,start:$,...x!==void 0?{end:x}:{},ttlMs:I,wrote:[]};h.push(a);const r=n.marks??[],w=r.filter(t=>t.bp),A=i.tokens?.input??0,m=i.tokens?.cached??0,f=i.tokens?.written??0,v=Et(i),c=i.model?o(i.model,A):void 0,J=gt(i.provider,g),K={...c?{price:{...c.source?{source:c.source}:{},...c.readAt?{readAt:c.readAt}:{},...c.stale?{stale:!0}:{}}}:{},facts:J},Z=k(()=>{for(const t of r){const u=d.get(t.h);u?u.push(s):d.set(t.h,[s])}},"remember"),tt=k((t,u)=>{const p=l.get(t);p?p.push({i:s,how:u}):l.set(t,[{i:s,how:u}])},"hold"),Q=It(i.provider,i.model);if(!v){if(!i.failed)for(const t of w)tt(t.h,"unknown");Z(),a.verdict=it(n,A,Q,K)??{kind:"unknown",said:i.failed?"It failed \u2014 the provider counted nothing for it.":"Its token count was not kept (the answer was cut by the capture): no verdict.",costs:[],basis:K},i.prewarm&&(a.verdict.prewarm=!0);return}const O=it(n,A,Q,K);if(O){const t=st(a,h,d,s);if(t&&t.tokens>=Q&&c){const u=c.cacheRead??c.input,p=t.tokens*(c.input-u)/1e6;O.costs.push({kind:"no-cache",tokens:t.tokens,usd:_(p),arithmetic:`${b(t.tokens)} \xD7 (${R(c.input)} \u2212 ${R(u)})/M`,estimate:!0}),O.lostUsd=_(p),O.said+=` It shares \u2248 ${b(t.tokens)} tokens with ${t.id} (${V($-h[t.i].start)} before): read from a cache, they would cost \u2248 ${ot(p)} less.`}i.prewarm&&(O.prewarm=!0),a.verdict=O,Z();return}const z=Math.max(256,A*.03),xt=k((t,u)=>u.reduce((p,B)=>!p||Math.abs(B.t-t)<Math.abs(p.t-t)?B:p,void 0),"nearest");let S=-1;if(m>0){const t=xt(m,w.length?w:r);t&&Math.abs(t.t-m)<=Math.max(z,m*.15)&&(a.readBp={h:t.h,t:t.t,s:t.s},S=w.indexOf(t))}w.forEach((t,u)=>(u<=S||S<0&&t.t<=m+z)&&tt(t.h,"read"));const at=w.filter((t,u)=>S>=0?u>S:t.t>m+z),vt=S>=0?w[S].t:m;let D=f>0?at.filter(t=>t.t<=vt+f+Math.max(z,f*.15)):[];if(f>0&&!D.length){const t=at[0]??w[w.length-1];D=t?[t]:[]}const nt=D.map((t,u)=>Math.max(1,t.t-(u?D[u-1].t:Math.max(m,w.filter(p=>p.t<t.t).pop()?.t??0)))),Bt=nt.reduce((t,u)=>t+u,0);D.forEach((t,u)=>{const p=D.length===1?f:Math.round(nt[u]/Bt*f),B=n.breakpoints.find(U=>Math.abs(U.tokens-t.t)<=1)?.ttl??n.ttl,N=et[B],T=(l.get(t.h)??[]).filter(U=>U.i<s),W=T.filter(U=>$-h[U.i].start<=N);if(W.length){const U=k(M=>h[M.i].end!==void 0&&h[M.i].end<=$,"done"),q=k(M=>M[M.length-1],"last"),ft=W.filter(M=>M.how==="wrote"),pt=W.filter(M=>M.how==="unknown"),wt=q(ft.filter(U))??q(pt.filter(U)),mt=q(ft.filter(M=>!U(M)))??q(pt.filter(M=>!U(M))),bt=wt??mt??q(W),At=!wt&&!!mt,yt=W.filter(M=>M.how==="read").length;a.wrote.push({h:t.h,s:t.s,tokens:p,estimate:D.length>1,ttl:B,status:"duplicate",against:bt,race:At,readFirst:yt})}else T.length?a.wrote.push({h:t.h,s:t.s,tokens:p,estimate:D.length>1,ttl:B,status:"cold",against:T[T.length-1],idleMs:$-h[T[T.length-1].i].start}):a.wrote.push({h:t.h,s:t.s,tokens:p,estimate:D.length>1,ttl:B,status:"first"});tt(t.h,"wrote")});const y=st(a,h,d,s);Z();const L=c?c.cacheRead??c.input:void 0,dt=c?Y(c,n.writes,n.ttl):void 0,H=[];let X,ct;if(y){const t=w.filter(B=>B.t<=y.tokens+1&&y.hashes.has(B.h)).reduce((B,N)=>Math.max(B,N.t),0),u=Math.max(m,t),p=y.tokens-u;if(y.tokens>=Q&&p>z){X={region:y.next??"(the end of the prompt)",tokens:y.tokens,id:h[y.i].row.id},ct=h[y.i];const B=m+f>=y.tokens-z,N=c?B?dt-L:c.input-L:void 0;H.push({kind:"broken-prefix",tokens:p,estimate:!0,...N!==void 0?{usd:_(p*N/1e6),arithmetic:`${b(p)} \xD7 (${R(B?dt:c.input)} \u2212 ${R(L)})/M`}:{}})}}for(const t of a.wrote){if(t.status==="first")continue;const u=c?Y(c,n.writes,t.ttl):void 0;H.push({kind:t.status==="duplicate"?"duplicate-write":"cold",tokens:t.tokens,estimate:t.estimate,...c?{usd:_(t.tokens*(u-L)/1e6),arithmetic:`${b(t.tokens)} \xD7 (${R(u)} \u2212 ${R(L)})/M`}:{}})}const C=[];a.wrote.some(t=>t.status==="duplicate")&&C.push("duplicate-write"),X&&C.push("broken-prefix"),a.wrote.some(t=>t.status==="cold")&&C.push("cold"),a.wrote.some(t=>t.status==="first")&&C.push("first-writer"),m>0&&C.push("read"),C.length||C.push("no-cache");const j=a.wrote.find(t=>t.status==="duplicate"),P=a.wrote.find(t=>t.status==="cold"),ht=j?.against??P?.against,E=ht?h[ht.i]:ct,ut=H.some(t=>t.usd!==void 0)?_(H.reduce((t,u)=>t+(u.usd??0),0)):void 0,lt=c&&m>0?_(m*(c.input-L)/1e6):void 0,Mt=C[0];a.verdict={kind:Mt,...C.length>1?{also:C.slice(1)}:{},said:"",costs:H,...ut!==void 0?{lostUsd:ut}:{},...lt!==void 0?{savedUsd:lt}:{},...j||P||a.wrote[0]||a.readBp?{prefix:(j??P??a.wrote[0])?.h??a.readBp.h}:{},read:m,written:f,...E?{against:{id:E.row.id,at:E.start,...E.end!==void 0?{ended:E.end}:{},inFlight:E.end===void 0||E.end>$,gapMs:$-E.start,...E.row.prewarm?{prewarm:!0}:{}}}:{},...j?{race:!!j.race,...j.readFirst?{readBefore:j.readFirst}:{}}:{},...X?{brokeAt:X}:{},...P?.idleMs!==void 0?{idleMs:P.idleMs}:{},...i.prewarm?{prewarm:!0}:{},basis:K}});for(const i of h){const s=i.verdict;if(!i.wrote.length){s.said=rt(i,s);continue}const n=new Set,$=new Set;let x=!1;const I=[];for(const a of i.wrote){const r=et[a.ttl],w=(l.get(a.h)??[]).filter(f=>h[f.i].start>i.start&&h[f.i].start-i.start<=r),A=w.filter(f=>f.how==="read"),m=w.filter(f=>f.how==="unknown");for(const f of A)n.add(f.i);for(const f of m)$.add(f.i);i.start+r>g?x=!0:!A.length&&!m.length&&I.push(a)}for(const a of n)$.delete(a);if(n.size&&(s.readBy=n.size),$.size&&(s.maybeReadBy=$.size),x&&(s.open=!0),I.length){const a=i.row,r=a.model?o(a.model,a.tokens?.input??0):void 0;let w=s.costs.find(v=>v.kind==="broken-prefix")?.tokens??0;for(const v of I){if(v.status!=="first")continue;const c=Math.max(0,v.tokens-w);if(w=0,!c)continue;const J=r?Y(r,a.cache.writes,v.ttl):void 0;s.costs.push({kind:"write-nothing-read",tokens:c,estimate:v.estimate||c!==v.tokens,...r?{usd:_(c*(J-r.input)/1e6),arithmetic:`${b(c)} \xD7 (${R(J)} \u2212 ${R(r.input)})/M`}:{}})}r&&(s.lostUsd=_(s.costs.reduce((v,c)=>v+(c.usd??0),0)));const A=[s.kind,...s.also??[]],m=A.findIndex(v=>v!=="duplicate-write"&&v!=="broken-prefix"&&v!=="cold");A.splice(m<0?A.length:m,0,"write-nothing-read"),s.kind=A[0];const f=A.slice(1);f.length?s.also=f:delete s.also}s.said=rt(i,s)}return new Map(h.map(i=>[i.row.id,i.verdict]))}F($t,"Ut"),k($t,"judgeAgent");function Y(e,o,g){const h=Object.entries(o??{}).filter(d=>typeof d[1]=="number"&&d[1]>0);if(h.length>1){const d=h.reduce((i,[,s])=>i+s,0);return h.reduce((i,[s,n])=>i+(e.writes[s]??e.input)*n,0)/d}const l=h[0]?.[0]??g;return e.writes[l]??e.input}F(Y,"et"),k(Y,"writeRate");function it(e,o,g,h){const l=k(d=>({kind:"no-cache",said:d,costs:[],basis:h}),"no");if(e.mode==="explicit"&&!e.breakpoints.length)return l("Explicit mode with no breakpoint: it read and wrote nothing.");if(e.mode==="none")return l("No `cache_control`: Anthropic cached nothing of it.");if(o>0&&o<g)return l(`${b(o)} input tokens \u2014 under the ${b(g)}-token minimum: nothing is cached.`)}F(it,"pt"),k(it,"structural");function st(e,o,g,h){const l=e.row.cache?.marks??[];let d;for(let s=0;s<l.length;s++){const n=g.get(l[s].h);if(n)for(let $=n.length-1;$>=0;$--){const x=n[$];if(!(x>=h)){if(e.start-o[x].start>e.ttlMs)break;d={i:x,at:s};break}}}if(!d)return;const i=o[d.i];return{i:d.i,id:i.row.id,tokens:l[d.at].t,...l[d.at+1]?{next:l[d.at+1].s}:{},hashes:new Set((i.row.cache?.marks??[]).map(s=>s.h))}}F(st,"wt"),k(st,"sharedWith");const G=k(e=>e.split(" \u203A ")[0],"block");function rt(e,o){if(o.said)return o.said;const g=e.row,h=g.cache,l=g.tokens?.input??0,d=o.read??0,i=o.written??0,s=h.ttl,n=[],$=o.prewarm?"A prewarm (it answers nothing): it ":"It ";n.push(`${$}read ${b(d)} of its ${b(l)} input tokens from the cache${i?` and wrote ${b(i)}`:""} (${h.mode} mode, ${s}).`);const x=e.wrote.find(r=>r.status==="duplicate");if(x&&o.against){const r=o.against,w=o.readBefore?` ${b(o.readBefore)} call${o.readBefore===1?"":"s"} sent before this one read it.`:"";n.push(o.race?`Duplicate write \u2014 a race: ${r.id}${x.against?.how==="unknown"?" (its count was not kept: it may have)":""} wrote the same prefix (to the end of \xAB${G(x.s)}\xBB) and was still in flight when this one was sent, ${V(r.gapMs)} after it.${w}`:x.against?.how==="read"?`Duplicate write: ${r.id} had read the same prefix (to the end of \xAB${G(x.s)}\xBB) ${V(r.gapMs)} before \u2014 the entry was there, and this call did not read it.`:`Duplicate write: ${r.id}${r.prewarm?" (a prewarm)":""}${x.against?.how==="unknown"?" (its count was not kept: it may have)":""} wrote the same prefix (to the end of \xAB${G(x.s)}\xBB) ${V(r.gapMs)} before${r.ended!==void 0&&r.ended<=e.start?` and had ended ${V(e.start-r.ended)} before this one was sent \u2014 not a race: the write had finished and this call did not read it`:""}.${w}`)}o.brokeAt&&n.push(`Broken prefix: it shares \u2248 ${b(o.brokeAt.tokens)} tokens with ${o.brokeAt.id}, then they part in \xAB${o.brokeAt.region}\xBB \u2014 no breakpoint ends where they part, so it read only ${b(d)}.`);const I=e.wrote.find(r=>r.status==="cold");I&&o.idleMs!==void 0&&n.push(`Cold: the same prefix (to the end of \xAB${G(I.s)}\xBB) was last used ${V(o.idleMs)} before \u2014 past its ${I.ttl} lifetime.`);const a=e.wrote.filter(r=>r.status==="first");return a.length&&n.push(`First writer of the prefix to the end of \xAB${a.map(r=>G(r.s)).join("\xBB, \xAB")}\xBB.`),e.wrote.length&&(o.kind==="write-nothing-read"||o.also?.includes("write-nothing-read")?n.push("No later call of its agent read what it wrote inside its lifetime."):o.readBy?n.push(`${b(o.readBy)} later call${o.readBy===1?"":"s"} read what it wrote.`):o.maybeReadBy?n.push(`${b(o.maybeReadBy)} later call${o.maybeReadBy===1?"":"s"} may have read it (their counts were not kept).`):o.open&&n.push("Its lifetime has not run out: a later call may still read it.")),!e.wrote.length&&d>0&&!o.brokeAt&&n.push(`Read${e.readBp?` to the end of \xAB${G(e.readBp.s)}\xBB`:""}.`),o.lostUsd!==void 0&&o.lostUsd>0&&n.push(`\u2248 ${ot(o.lostUsd)} lost: ${o.costs.filter(r=>r.arithmetic).map(r=>`${r.arithmetic}${r.estimate?" (estimate)":""}`).join(" + ")}.`),o.savedUsd&&n.push(`Its reads saved \u2248 ${ot(o.savedUsd)} against plain input.`),n.join(" ")}F(rt,"kt"),k(rt,"said");
@@ -0,0 +1,133 @@
1
+ import type { AiApi, AiUsage } from './ai-call.js';
2
+ import { type AiCacheTtl } from './ai-cache-facts.js';
3
+ /**
4
+ * A call's prompt cache as the provider reports it (foodguard-301 A): the mode the request asked for, each breakpoint
5
+ * and the tokens before it, the lifetime, a prewarm — and the prefix's checkpoints (`marks`), what the cache verdicts
6
+ * ({@link aiCacheVerdicts}) compare calls by.
7
+ *
8
+ * OpenAI Responses: `prompt_cache_options` (`mode` implicit | explicit, `ttl` 30m | 12h, `prewarm`), a content block's
9
+ * `prompt_cache_breakpoint` (`{ mode: "explicit", ttl? }`), `prompt_cache_key`; before GPT-5.6, `prompt_cache_retention`.
10
+ * Chat Completions: implicit only. Anthropic Messages: a block's `cache_control` (`ttl` 5m | 1h), a top-level one
11
+ * (automatic caching: the last block). The usage — reads, writes by lifetime — is read in `ai-call.ts`.
12
+ *
13
+ * A mark is a checkpoint of the prefix in the order the provider reads it: a hash of everything before it (the
14
+ * settings that end reuse first — model, tools, the answer's format, effort, verbosity, the cache key), the tokens
15
+ * before it, and the region that ends there (a block, or a section of one: `--- TITLE ---`, a heading, a tag). Two
16
+ * calls with the same hash at a mark share everything before it; the first mark where they differ names the region
17
+ * the difference is in. Tokens are estimated in the same pass as the hash (a character loop — the regex estimate of
18
+ * `ai-context.ts` costs ~25 ms on a 200 KB request) and scaled to the provider's count.
19
+ *
20
+ * Pure, and shared: the server keeps a row's cache, the page shows it.
21
+ */
22
+ export type AiCacheMode = 'implicit' | 'explicit' | 'automatic' | 'none';
23
+ export interface AiCacheBreakpoint {
24
+ /** Where it sits, as a person reads it: «user · block 1 of 3», «system · block 2», «tools · lookup». */
25
+ at: string;
26
+ /** Its own lifetime, where it names one; else the request's. */
27
+ ttl?: AiCacheTtl;
28
+ /** The provider's own: implicit mode's (the end of the latest eligible message), Anthropic's automatic one. */
29
+ implicit?: true;
30
+ /** The request's characters before it, in the order the provider reads. */
31
+ chars: number;
32
+ /** The tokens before it — estimated, scaled to the provider's count when it counted. */
33
+ tokens: number;
34
+ }
35
+ /** A checkpoint of the prefix (see the file's comment): what calls are compared by — kept on a row, not shown. */
36
+ export interface AiCacheMark {
37
+ /** A hash of everything before it, settings first. */
38
+ h: string;
39
+ /** Tokens before it, estimated (scaled to the provider's count when it counted). */
40
+ t: number;
41
+ /** The region that ends here: «user · block 1 › Captured hazard method». */
42
+ s: string;
43
+ /** A breakpoint ends here. */
44
+ bp?: 1;
45
+ }
46
+ export interface AiCache {
47
+ provider: string;
48
+ mode: AiCacheMode;
49
+ /** The request said its mode (`prompt_cache_options.mode`, a `cache_control`) — else it is the provider's default. */
50
+ modeSaid: boolean;
51
+ /** The request's lifetime: what it set (`prompt_cache_options.ttl`, `prompt_cache_retention`, a top-level `cache_control.ttl`), else the provider's default. */
52
+ ttl: AiCacheTtl;
53
+ ttlSaid: boolean;
54
+ /** `prompt_cache_options.prewarm: true` — it writes the cache and answers nothing: counted in tokens, not in calls. */
55
+ prewarm?: true;
56
+ /** A `prompt_cache_key` was sent: the cache is kept apart per key. */
57
+ key?: true;
58
+ breakpoints: AiCacheBreakpoint[];
59
+ /** The provider's count: tokens read from the cache, written to it (by lifetime), and the plain rest — none when it counted nothing. */
60
+ read?: number;
61
+ written?: number;
62
+ writes?: Partial<Record<AiCacheTtl, number>>;
63
+ plain?: number;
64
+ /** The prefix's checkpoints, in order (at most {@link MAX_MARKS}). */
65
+ marks: AiCacheMark[];
66
+ /** Estimated: the tokens before the marks and breakpoints are not the provider's count. */
67
+ estimated: boolean;
68
+ }
69
+ /** A row keeps at most this many marks; past it only block ends and breakpoints are marked. */
70
+ export declare const MAX_MARKS = 48;
71
+ /** One block of the prompt, in the provider's order. */
72
+ export interface AiCacheBlock {
73
+ label: string;
74
+ /** Who said it — part of what the provider renders, so of the prefix. */
75
+ role?: string;
76
+ text: string;
77
+ /** A tool's or a schema's JSON is rendered tighter than its text. */
78
+ weight?: number;
79
+ /** A breakpoint ends this block. */
80
+ bp?: {
81
+ ttl?: AiCacheTtl;
82
+ implicit?: true;
83
+ };
84
+ }
85
+ /** The request as its cache sees it: the settings that end reuse, and the blocks in order. */
86
+ export interface AiCacheRequest {
87
+ provider: string;
88
+ api: AiApi;
89
+ model?: string;
90
+ /** What ends reuse when it changes, as written (JSON) — hashed before the blocks. */
91
+ settings: string;
92
+ blocks: AiCacheBlock[];
93
+ mode: AiCacheMode;
94
+ modeSaid: boolean;
95
+ ttl: AiCacheTtl;
96
+ ttlSaid: boolean;
97
+ prewarm: boolean;
98
+ key: boolean;
99
+ }
100
+ /** The request as its cache reads it — `undefined` for an embedding, or a body that is not an object. */
101
+ export declare function aiCacheRequestOf(api: AiApi, req: unknown): AiCacheRequest | undefined;
102
+ /** Where a block's sections start: its `--- TITLE ---` lines, headings (`#`–`###`) and tags at a line's start. */
103
+ export declare function aiCacheSections(text: string): Array<{
104
+ at: number;
105
+ title: string;
106
+ }>;
107
+ /**
108
+ * The request read for its cache: each breakpoint and the marks, with the provider's count (reads, writes by
109
+ * lifetime) — `undefined` for a call with no prompt (an embedding, a body not kept).
110
+ */
111
+ export declare function aiCacheOf(api: AiApi, req: unknown, usage?: AiUsage, opts?: {
112
+ prewarm?: boolean;
113
+ }): AiCache | undefined;
114
+ /** Where two calls' prefixes part: the region, the tokens before it (estimated), and the first line that differs in each. */
115
+ export interface AiCacheDiff {
116
+ /** «settings» when what ends reuse differs (the model, the tools, the format…) — which, in `setting`. */
117
+ region: string;
118
+ setting?: string;
119
+ /** Characters both share, in the provider's order. */
120
+ chars: number;
121
+ /** Of this call's tokens, those before the difference — estimated. */
122
+ tokens: number;
123
+ /** The first line that differs, in this call and in the other — cut to 200 characters. */
124
+ line?: string;
125
+ otherLine?: string;
126
+ /** The two prompts are the same, to their end. */
127
+ same?: true;
128
+ }
129
+ /**
130
+ * Where `a` stops sharing its prefix with `b`, read from the two requests: the settings first, then block by block, to
131
+ * the character. `tokens` scales `a`'s characters before the difference to its own count (`inputTokens`).
132
+ */
133
+ export declare function aiCacheDiff(a: AiCacheRequest, b: AiCacheRequest, inputTokens?: number): AiCacheDiff;
@@ -0,0 +1,4 @@
1
+ "use strict";var H=Object.defineProperty;var b=(t,o)=>H(t,"name",{value:o,configurable:!0});var Q=Object.defineProperty,u=b((t,o)=>Q(t,"name",{value:o,configurable:!0}),"u");import{aiDefaultTtl as D,openaiNewCache as U}from"./ai-cache-facts.js";export const MAX_MARKS=48;const L=400,V=72,S=u(t=>!!t&&typeof t=="object"&&!Array.isArray(t),"isObj"),g=u(t=>typeof t=="string"?t:void 0,"str"),v=u(t=>Array.isArray(t)?t:[],"arr"),x=u(t=>S(t)?t:{},"obj"),W=["5m","1h","30m","12h","24h","in_memory"],O=u(t=>typeof t=="string"&&W.includes(t)?t:void 0,"ttlOf");function A(t){if(typeof t=="string")return t;const o=x(t),e=g(o.text)??g(o.refusal);if(e!==void 0)return e;const{prompt_cache_breakpoint:h,cache_control:l,...p}=o;return JSON.stringify(p)}b(A,"C"),u(A,"partText");const R=u((t,o)=>{const e={};for(const h of o){let l=t;for(const p of h.split("."))l=x(l)[p];l!==void 0&&(e[h]=l)}return e},"pick");function P(t){const o=x(t).prompt_cache_breakpoint;if(o==null||o===!1)return;const e=O(x(o).ttl);return e?{ttl:e}:{}}b(P,"F"),u(P,"openaiBreakpoint");function j(t){const o=x(t).cache_control;if(!S(o))return;const e=O(o.ttl);return e?{ttl:e}:{}}b(j,"L"),u(j,"anthropicBreakpoint");function T(t){const o=g(t.model),e=x(t.prompt_cache_options),h=U(o),l=g(e.mode)==="explicit"||g(e.mode)==="implicit",p=g(e.mode)==="explicit"?"explicit":"implicit",i=O(h?e.ttl:t.prompt_cache_retention),s=[],r=g(t.instructions);r&&s.push({label:"instructions",role:"developer",text:r}),v(t.tools).length&&s.push({label:"tools",text:JSON.stringify(t.tools),weight:.7});const n=x(x(t.text).format);n.schema!==void 0&&s.push({label:`answer schema${g(n.name)?` \xB7 ${g(n.name)}`:""}`,text:JSON.stringify(n.schema),weight:.7});let m=-1;const a=t.input;if(typeof a=="string")s.push({label:"user",role:"user",text:a}),m=s.length-1;else{const y=v(a).map(x);let _=!0;y.forEach((c,k)=>{const f=g(c.type)??(c.role?"message":""),w=g(c.role)??(f==="function_call_output"?"tool":"item"),M=f==="message"?c.content:f==="function_call_output"?c.output:void 0,J=typeof M=="string"?[M]:Array.isArray(M)?M:void 0,B=f==="message"?w:f||"item";if(J)J.forEach((E,z)=>{const C=P(E);s.push({label:J.length>1?`${B} \xB7 block ${z+1} of ${J.length}`:B,role:w,text:A(E),...C?{bp:C}:{}})});else{const{id:E,status:z,...C}=c;s.push({label:B,role:w,text:JSON.stringify(C)})}const N=y[k+1],q=N?g(N.type)??(N.role?"message":""):"";(f==="message"&&w==="user"||f==="function_call_output"&&q!=="function_call_output"||_&&f==="message"&&w==="developer"&&!(q==="message"&&g(N.role)==="developer"))&&(m=s.length-1),f==="message"&&w==="developer"||(_=!1)})}p==="implicit"&&m>=0&&(s[m].bp={...s[m].bp??{},implicit:!0});const d={model:o,...R(t,["tools","parallel_tool_calls","text.format","reasoning.effort","text.verbosity","context_management","prompt_cache_key","previous_response_id","conversation"])};return{provider:"openai",api:"responses",...o?{model:o}:{},settings:JSON.stringify(d),blocks:s,mode:p,modeSaid:l,ttl:i??D("openai",o),ttlSaid:!!i,prewarm:e.prewarm===!0,key:typeof t.prompt_cache_key=="string"}}b(T,"G"),u(T,"responsesRequest");function I(t){const o=g(t.model),e=[];v(t.tools).length&&e.push({label:"tools",text:JSON.stringify(t.tools),weight:.7});const h=x(t.response_format);h.json_schema!==void 0&&e.push({label:"answer schema",text:JSON.stringify(h.json_schema),weight:.7});let l=-1;const p=v(t.messages).map(x);p.forEach((r,n)=>{const m=g(r.role)??"user",a=r.content,d=typeof a=="string"?[a]:Array.isArray(a)?a:[];d.length||e.push({label:m,role:m,text:JSON.stringify({...r,content:void 0})}),d.forEach((_,c)=>e.push({label:d.length>1?`${m} \xB7 block ${c+1} of ${d.length}`:m,role:m,text:A(_)})),r.tool_calls!==void 0&&e.push({label:`${m} \xB7 tool calls`,role:m,text:JSON.stringify(r.tool_calls)});const y=g(p[n+1]?.role);(m==="user"||m==="tool"&&y!=="tool")&&(l=e.length-1)}),l>=0&&(e[l].bp={implicit:!0});const i=O(t.prompt_cache_retention),s={model:o,...R(t,["tools","parallel_tool_calls","response_format","reasoning_effort","verbosity","prompt_cache_key"])};return{provider:"openai",api:"chat",...o?{model:o}:{},settings:JSON.stringify(s),blocks:e,mode:"implicit",modeSaid:!1,ttl:i??D("openai",o),ttlSaid:!!i,prewarm:!1,key:typeof t.prompt_cache_key=="string"}}b(I,"Q"),u(I,"chatRequest");function K(t){const o=g(t.model),e=[];for(const n of v(t.tools).map(x)){const m=j(n),{cache_control:a,...d}=n;e.push({label:`tools \xB7 ${g(n.name)??g(n.type)??"tool"}`,text:JSON.stringify(d),weight:.7,...m?{bp:m}:{}})}const h=t.system;if(typeof h=="string"&&h)e.push({label:"system",role:"system",text:h});else{const n=v(h);n.forEach((m,a)=>{const d=j(m);e.push({label:n.length>1?`system \xB7 block ${a+1} of ${n.length}`:"system",role:"system",text:A(m),...d?{bp:d}:{}})})}for(const n of v(t.messages).map(x)){const m=g(n.role)??"user",a=n.content,d=typeof a=="string"?[a]:v(a);d.forEach((y,_)=>{const c=j(y);e.push({label:d.length>1?`${m} \xB7 block ${_+1} of ${d.length}`:m,role:m,text:A(y),...c?{bp:c}:{}})})}const l=t.cache_control,p=e.some(n=>n.bp);if(S(l)&&e.length){const n=e[e.length-1];n.bp={...n.bp??(O(l.ttl)?{ttl:O(l.ttl)}:{}),implicit:!0}}const i=p?"explicit":S(l)?"automatic":"none",s=S(l)?O(l.ttl):void 0,r={model:o,...R(t,["tool_choice","thinking","output_config.effort","speed"])};return{provider:"anthropic",api:"messages",...o?{model:o}:{},settings:JSON.stringify(r),blocks:e,mode:i,modeSaid:p||S(l),ttl:s??"5m",ttlSaid:!!s,prewarm:!1,key:!1}}b(K,"U"),u(K,"messagesRequest");export function aiCacheRequestOf(t,o){if(S(o)){if(t==="responses")return T(o);if(t==="chat")return I(o);if(t==="messages")return K(o)}}b(aiCacheRequestOf,"aiCacheRequestOf"),u(aiCacheRequestOf,"aiCacheRequestOf");class Y{static{b(this,"V")}static{u(this,"Prefix")}constructor(){this.h1=3735928559,this.h2=1103547991,this.tokens=0,this.chars=0,this.word=0,this.digits=0,this.space=0}feed(o,e=!0,h=1){let l=this.h1,p=this.h2,i=0,s=this.word,r=this.digits,n=this.space;for(let m=0;m<o.length;m++){const a=o.charCodeAt(m);l=Math.imul(l^a,2654435761),p=Math.imul(p^a,1597334677),e&&(a>=65&&a<=90||a>=97&&a<=122?((s===0||s>=8&&(s-8)%4===3)&&(i+=1),s++,r=0,n=0):a>=48&&a<=57?(r%3===0&&(i+=1),r++,s=0,n=0):a===32||a===9||a===10||a===13?((a===10||n===1)&&(i+=n<2?1:0),n=a===10?2:n+1,s=0,r=0):(s=0,r=0,n=0,i+=a>=11904?.9:a>=192?.66:.75))}this.h1=l,this.h2=p,this.word=s,this.digits=r,this.space=n,e&&(this.tokens+=i*h,this.chars+=o.length)}digest(){let o=this.h1,e=this.h2;return o=Math.imul(o^o>>>16,2246822507)^Math.imul(e^e>>>13,3266489909),e=Math.imul(e^e>>>16,2246822507)^Math.imul(o^o>>>13,3266489909),(4294967296*(2097151&e)+(o>>>0)).toString(36)}}export function aiCacheSections(t){const o=[];let e=0;const h=t.length;for(;e<h;){const l=t.indexOf(`
2
+ `,e),p=l<0?h:l;let i=e;for(;i<p&&(t.charCodeAt(i)===32||t.charCodeAt(i)===9);)i++;const s=t[i];if(s==="-"||s==="#"||s==="<"){const r=t.slice(i,Math.min(p,i+240)),n=s==="-"?/^-{3,}[ \t]*(.+?)[ \t]*-{3,}[ \t]*$/.exec(r):s==="#"?/^#{1,3}[ \t]+(.+?)[ \t#]*$/.exec(r):/^<([a-z][a-z0-9_-]{0,40})(?:[\s>])/.exec(r);n&&n[1].trim()&&o.push({at:e,title:n[1].trim().slice(0,V)})}e=p+1}return o}b(aiCacheSections,"aiCacheSections"),u(aiCacheSections,"aiCacheSections");function X(t,o){const e=t.text.length,h=e>=2*L?aiCacheSections(t.text):[],l=[{block:o,from:0,to:e,title:t.label,end:!0}];if(!h.length)return l;const p=h[0].at===0?h[0].title:void 0;let i={at:0,title:p??"(opening)",last:void 0,opening:!p};const s=[],r=u(n=>`${t.label} \u203A ${n.last?`${F(n.title)} \u2026 ${F(n.last)}`:n.title}`,"titled");for(const n of h)if(n.at!==0){if(n.at-i.at<L){i.opening?i={at:i.at,title:n.title,last:void 0,opening:!1}:i.last=n.title;continue}s.push({block:o,from:i.at,to:n.at,title:r(i),end:!1}),i={at:n.at,title:n.title,last:void 0,opening:!1}}return s.length?(s.push({block:o,from:i.at,to:e,title:r(i),end:!0}),s):l}b(X,"W"),u(X,"regionsOf");const F=u(t=>t.length>36?`${t.slice(0,35)}\u2026`:t,"clip"),Z=4;export function aiCacheOf(t,o,e,h={}){const l=aiCacheRequestOf(t,o);if(!l)return;const p=new Y;p.feed(l.settings,!1);const i=[];l.blocks.forEach((c,k)=>{p.feed(`\0${c.role??""}`,!1),p.tokens+=Z;for(const f of X(c,k))p.feed(c.text.slice(f.from,f.to),!0,c.weight??1),(f.end||i.length<MAX_MARKS-8)&&i.push({h:p.digest(),chars:p.chars,tokens:p.tokens,s:f.title,...f.end&&c.bp?{bp:c.bp}:{},blockEnd:f.end})});const s=p.tokens,r=e?.input!==void 0&&e.input>0,n=r&&s>0?e.input/s:1,m=u(c=>Math.round(c*n),"round");let a=i.map(c=>({h:c.h,t:m(c.tokens),s:c.s,...c.bp?{bp:1}:{}}));if(a.length>MAX_MARKS){const c=new Set;a.forEach((k,f)=>k.bp&&c.add(f));for(let k=a.length-1;k>=0&&c.size<MAX_MARKS;k--)c.add(k);a=a.filter((k,f)=>c.has(f))}const d=i.filter(c=>c.bp).map(c=>({at:c.s.split(" \u203A ")[0],...c.bp.ttl?{ttl:c.bp.ttl}:{},...c.bp.implicit?{implicit:!0}:{},chars:c.chars,tokens:m(c.tokens)})),y=e?.cached,_=e?.written;return{provider:l.provider,mode:l.mode,modeSaid:l.modeSaid,ttl:l.ttl,ttlSaid:l.ttlSaid,...l.prewarm||h.prewarm?{prewarm:!0}:{},...l.key?{key:!0}:{},breakpoints:d,...r?{read:y??0,written:_??0,plain:Math.max(0,e.input-(y??0)-(_??0))}:{},...e?.writes&&Object.keys(e.writes).length?{writes:{...e.writes}}:{},marks:a,estimated:!r}}b(aiCacheOf,"aiCacheOf"),u(aiCacheOf,"aiCacheOf");const G=200,$=u((t,o)=>{const e=t.lastIndexOf(`
3
+ `,o-1)+1,h=t.indexOf(`
4
+ `,o),l=t.slice(e,h<0?t.length:h).trim();return l.length>G?`${l.slice(0,G-1)}\u2026`:l},"lineAt");export function aiCacheDiff(t,o,e){if(t.settings!==o.settings){const i=JSON.parse(t.settings),s=JSON.parse(o.settings);return{region:"settings",setting:[...new Set([...Object.keys(i),...Object.keys(s)])].filter(r=>JSON.stringify(i[r])!==JSON.stringify(s[r])).join(", "),chars:0,tokens:0}}let h=0;const l=t.blocks.reduce((i,s)=>i+s.text.length,0),p=u(i=>e!==void 0&&l>0?Math.round(i/l*e):Math.round(i/4),"tokensAt");for(let i=0;i<Math.max(t.blocks.length,o.blocks.length);i++){const s=t.blocks[i],r=o.blocks[i];if(!s||!r)return{region:s?s.label:"the end of this prompt",chars:h,tokens:p(h),...s?{line:$(s.text,0)}:{},...r?{otherLine:$(r.text,0)}:{}};if(s.role!==r.role)return{region:s.label,chars:h,tokens:p(h),line:$(s.text,0),otherLine:$(r.text,0)};if(s.text===r.text){h+=s.text.length;continue}let n=0;const m=Math.min(s.text.length,r.text.length);for(;n<m&&s.text.charCodeAt(n)===r.text.charCodeAt(n);)n++;const a=[...aiCacheSections(s.text)].reverse().find(d=>d.at<=n);return{region:a?`${s.label} \u203A ${a.title}`:s.label,chars:h+n,tokens:p(h+n),line:$(s.text,Math.min(n,Math.max(0,s.text.length-1))),otherLine:$(r.text,Math.min(n,Math.max(0,r.text.length-1)))}}return{region:"(none)",chars:h,tokens:p(h),same:!0}}b(aiCacheDiff,"aiCacheDiff"),u(aiCacheDiff,"aiCacheDiff");
@@ -10,7 +10,9 @@ import type { AiPartKind } from './ai-context.js';
10
10
  */
11
11
  export type AiGroupBy = 'agent' | 'action' | 'run' | 'thread' | 'flow' | 'model' | 'service' | `meta:${string}`;
12
12
  export interface AiTotals {
13
+ /** Its calls — prewarms apart (`prewarms`): a prewarm writes the cache and answers nothing; its tokens are in the totals. */
13
14
  calls: number;
15
+ prewarms: number;
14
16
  runs: number;
15
17
  failed: number;
16
18
  input: number;
@@ -1,2 +1,2 @@
1
- "use strict";var m=Object.defineProperty;var i=(e,t)=>m(e,"name",{value:t,configurable:!0});var d=Object.defineProperty,l=i((e,t)=>d(e,"name",{value:t,configurable:!0}),"i"),p=Object.defineProperty,u=l((e,t)=>p(e,"name",{value:t,configurable:!0}),"i");export function aiTotalsOf(e){const t={calls:e.length,runs:new Set(e.map(a=>a.run.key)).size,failed:0,input:0,cached:0,written:0,output:0,split:{},costUsd:0,priced:0,first:1/0,last:0,models:[]},r=new Map;for(const a of e){a.failed&&t.failed++,t.input+=a.tokens?.input??0,t.cached+=a.tokens?.cached??0,t.written+=a.tokens?.written??0,t.output+=a.tokens?.output??0;for(const[n,o]of Object.entries(a.split??{}))t.split[n]=(t.split[n]??0)+o;a.costUsd!==void 0&&(t.costUsd+=a.costUsd,t.priced++),t.first=Math.min(t.first,a.at),t.last=Math.max(t.last,a.at),a.model&&r.set(a.model,(r.get(a.model)??0)+1)}return t.models=[...r].sort((a,n)=>n[1]-a[1]).map(([a])=>a),e.length||(t.first=0),t}i(aiTotalsOf,"aiTotalsOf"),l(aiTotalsOf,"aiTotalsOf"),u(aiTotalsOf,"aiTotalsOf");export function aiRunsOf(e,t=!1){const r=new Map;for(const a of e){const n=r.get(a.run.key);n?n.push(a):r.set(a.run.key,[a])}return[...r.entries()].map(([a,n])=>{n.sort((s,c)=>(s.step??0)-(c.step??0)||s.at-c.at);const o=aiTotalsOf(n);return{key:a,from:n[0].run.from,calls:n,at:o.first,last:o.last,totals:o}}).sort((a,n)=>t?a.at-n.at:n.last-a.last)}i(aiRunsOf,"aiRunsOf"),l(aiRunsOf,"aiRunsOf"),u(aiRunsOf,"aiRunsOf");const k="(none)";function f(e,t){if(t==="agent")return e.agent;if(t==="action")return e.action??{key:"action:",name:"(no action)"};if(t==="run")return{key:e.run.key,name:e.agent.name};if(t==="thread")return e.thread?{key:e.thread.key,name:`thread ${e.thread.name}`}:{key:"thread:",name:"(no thread)"};if(t==="flow")return e.flowId?{key:`flow:${e.flowId}`,name:e.flowId}:e.requestId?{key:`request:${e.requestId}`,name:`request ${e.requestId}`}:{key:"flow:",name:"(no flow)"};if(t==="model")return{key:`model:${e.model??""}`,name:e.model??"(unknown model)"};if(t==="service")return{key:`service:${e.service}`,name:e.service};const r=t.slice(5),a=e.meta?.[r];return{key:`${t}=${a??""}`,name:a??k}}i(f,"f"),l(f,"m"),u(f,"keyOf");export function groupAiCalls(e,t,r){const a=new Map;for(const o of e){const s=f(o,t),c=a.get(s.key);c?c.rows.push(o):a.set(s.key,{...s,rows:[o]})}const n=t==="agent"||t==="action";return[...a.values()].map(o=>({key:o.key,name:o.name,...o.from?{from:o.from}:{},nameable:n&&/^(agent|action):./.test(o.key),merged:r?Object.entries(r.merge).filter(([,s])=>s===o.key).map(([s])=>s).sort():[],runs:aiRunsOf(o.rows,t==="flow"),totals:aiTotalsOf(o.rows)})).sort((o,s)=>s.totals.last-o.totals.last||o.name.localeCompare(s.name))}i(groupAiCalls,"groupAiCalls"),l(groupAiCalls,"groupAiCalls"),u(groupAiCalls,"groupAiCalls");export function matchesAi(e,t){const r=t.toLowerCase().split(/\s+/).filter(Boolean);if(!r.length)return!0;const a=[e.id,e.agent.name,e.action?.name,e.model,e.service,e.flowId,e.requestId,e.schema,e.asked,e.said,...e.called??[],...Object.entries(e.meta??{}).map(([n,o])=>`${n}:${o}`)].filter(Boolean).join(`
2
- `).toLowerCase();return r.every(n=>a.includes(n))}i(matchesAi,"matchesAi"),l(matchesAi,"matchesAi"),u(matchesAi,"matchesAi");
1
+ "use strict";var m=Object.defineProperty;var i=(t,a)=>m(t,"name",{value:a,configurable:!0});var u=Object.defineProperty,c=i((t,a)=>u(t,"name",{value:a,configurable:!0}),"i");export function aiTotalsOf(t){const a=t.filter(e=>!e.prewarm),n={calls:a.length,prewarms:t.length-a.length,runs:new Set(a.map(e=>e.run.key)).size,failed:0,input:0,cached:0,written:0,output:0,split:{},costUsd:0,priced:0,first:1/0,last:0,models:[]},o=new Map;for(const e of t){e.failed&&n.failed++,n.input+=e.tokens?.input??0,n.cached+=e.tokens?.cached??0,n.written+=e.tokens?.written??0,n.output+=e.tokens?.output??0;for(const[r,s]of Object.entries(e.split??{}))n.split[r]=(n.split[r]??0)+s;e.costUsd!==void 0&&(n.costUsd+=e.costUsd,n.priced++),n.first=Math.min(n.first,e.at),n.last=Math.max(n.last,e.at),e.model&&o.set(e.model,(o.get(e.model)??0)+1)}return n.models=[...o].sort((e,r)=>r[1]-e[1]).map(([e])=>e),t.length||(n.first=0),n}i(aiTotalsOf,"aiTotalsOf"),c(aiTotalsOf,"aiTotalsOf");export function aiRunsOf(t,a=!1){const n=new Map;for(const o of t){const e=n.get(o.run.key);e?e.push(o):n.set(o.run.key,[o])}return[...n.entries()].map(([o,e])=>{e.sort((s,l)=>(s.step??0)-(l.step??0)||s.at-l.at);const r=aiTotalsOf(e);return{key:o,from:e[0].run.from,calls:e,at:r.first,last:r.last,totals:r}}).sort((o,e)=>a?o.at-e.at:e.last-o.last)}i(aiRunsOf,"aiRunsOf"),c(aiRunsOf,"aiRunsOf");const d="(none)";function f(t,a){if(a==="agent")return t.agent;if(a==="action")return t.action??{key:"action:",name:"(no action)"};if(a==="run")return{key:t.run.key,name:t.agent.name};if(a==="thread")return t.thread?{key:t.thread.key,name:`thread ${t.thread.name}`}:{key:"thread:",name:"(no thread)"};if(a==="flow")return t.flowId?{key:`flow:${t.flowId}`,name:t.flowId}:t.requestId?{key:`request:${t.requestId}`,name:`request ${t.requestId}`}:{key:"flow:",name:"(no flow)"};if(a==="model")return{key:`model:${t.model??""}`,name:t.model??"(unknown model)"};if(a==="service")return{key:`service:${t.service}`,name:t.service};const n=a.slice(5),o=t.meta?.[n];return{key:`${a}=${o??""}`,name:o??d}}i(f,"m"),c(f,"keyOf");export function groupAiCalls(t,a,n){const o=new Map;for(const r of t){const s=f(r,a),l=o.get(s.key);l?l.rows.push(r):o.set(s.key,{...s,rows:[r]})}const e=a==="agent"||a==="action";return[...o.values()].map(r=>({key:r.key,name:r.name,...r.from?{from:r.from}:{},nameable:e&&/^(agent|action):./.test(r.key),merged:n?Object.entries(n.merge).filter(([,s])=>s===r.key).map(([s])=>s).sort():[],runs:aiRunsOf(r.rows,a==="flow"),totals:aiTotalsOf(r.rows)})).sort((r,s)=>s.totals.last-r.totals.last||r.name.localeCompare(s.name))}i(groupAiCalls,"groupAiCalls"),c(groupAiCalls,"groupAiCalls");export function matchesAi(t,a){const n=a.toLowerCase().split(/\s+/).filter(Boolean);if(!n.length)return!0;const o=[t.id,t.agent.name,t.action?.name,t.model,t.service,t.flowId,t.requestId,t.schema,t.asked,t.said,...t.called??[],...Object.entries(t.meta??{}).map(([e,r])=>`${e}:${r}`)].filter(Boolean).join(`
2
+ `).toLowerCase();return n.every(e=>o.includes(e))}i(matchesAi,"matchesAi"),c(matchesAi,"matchesAi");
@@ -2,6 +2,9 @@ import type { HttpExchange } from './http-exchange.js';
2
2
  import { type AiApi, type AiShape } from './ai-call.js';
3
3
  import { type AiPartKind } from './ai-context.js';
4
4
  import type { AiOrigins } from './ai-origins.js';
5
+ import type { AiCache, AiCacheDiff, AiCacheMark, AiCacheMode } from './ai-cache.js';
6
+ import type { AiCacheTtl } from './ai-cache-facts.js';
7
+ import type { AiCacheVerdict } from './ai-cache-verdict.js';
5
8
  /**
6
9
  * One AI provider's call as a line of the AI calls page — and what it belongs to: the agent that made it, the run
7
10
  * (one turn of an agent's tool loop, its rounds) it is part of, the action it was for, its flow.
@@ -57,6 +60,10 @@ export interface AiCallRow {
57
60
  split?: Partial<Record<AiPartKind, number>>;
58
61
  /** What it cost, estimated from its tokens by the lens's price table (the server's) — none for a model it has no price for. */
59
62
  costUsd?: number;
63
+ /** A prewarm (`prompt_cache_options.prewarm`): it wrote the cache and answered nothing — in the token totals, not in the call counts. */
64
+ prewarm?: true;
65
+ /** Its prompt cache as the provider reported it, and the verdict on it over the calls of its agent ({@link AiCallCache}). */
66
+ cache?: AiCallCache;
60
67
  agent: AiNamed;
61
68
  run: {
62
69
  key: string;
@@ -96,6 +103,35 @@ export interface AiCallRow {
96
103
  asked?: string;
97
104
  said?: string;
98
105
  }
106
+ /**
107
+ * A row's prompt cache: the mode, the lifetime and the breakpoints the request set, the writes by lifetime the provider
108
+ * counted — and the verdict, by arithmetic over the earlier and later calls of its agent ({@link aiCacheVerdicts}).
109
+ * `marks` (the prefix's checkpoints, what calls are compared by) stay in the server's index: rows sent out lack them.
110
+ */
111
+ export interface AiCallCache {
112
+ mode: AiCacheMode;
113
+ /** The request said its mode; else it is the provider's default. */
114
+ modeSaid?: true;
115
+ ttl: AiCacheTtl;
116
+ ttlSaid?: true;
117
+ /** A `prompt_cache_key` was sent. */
118
+ key?: true;
119
+ /** Each breakpoint: where it sits, the tokens before it (estimated, scaled to the provider's count), its own lifetime. */
120
+ breakpoints: Array<{
121
+ at: string;
122
+ tokens: number;
123
+ ttl?: AiCacheTtl;
124
+ implicit?: true;
125
+ }>;
126
+ /** The provider's writes by lifetime. */
127
+ writes?: Partial<Record<AiCacheTtl, number>>;
128
+ marks?: AiCacheMark[];
129
+ verdict?: AiCacheVerdict;
130
+ }
131
+ /** A call's cache as its row keeps it. */
132
+ export declare function aiCallCacheOf(c: AiCache): AiCallCache;
133
+ /** A row as it is sent out — to the page, to an agent: without its cache's marks. */
134
+ export declare function aiRowOut(r: AiCallRow): AiCallRow;
99
135
  /** A person's names for groups, kept in `.lensmcp/ai-names/names.json` and committed: the team sees the same names. */
100
136
  export interface AiNames {
101
137
  version: 1;
@@ -139,11 +175,17 @@ export interface AiCallView {
139
175
  names: AiNames;
140
176
  /** Where each part of what the model was given came from — set beside the earlier calls of its run, thread and flow (`aiOriginsOf`); only with the exchange. */
141
177
  origins?: AiOrigins;
178
+ /** A broken prefix ({@link AiCacheVerdict}): where its prompt parts from the earlier call's, to the line — only with the exchange. */
179
+ cacheDiff?: AiCacheDiff & {
180
+ against: string;
181
+ };
142
182
  }
143
183
  /** One model's share of an AI provider's kept calls — Data › External APIs › its host › AI models, when the AI tap read none. */
144
184
  export interface AiModelUse {
145
185
  model: string;
186
+ /** Its calls — a prewarm not among them ({@link AiCallRow.prewarm}): its tokens are in the totals, it is counted in `prewarms`. */
146
187
  calls: number;
188
+ prewarms?: number;
147
189
  failed: number;
148
190
  /** Calls its provider reported no usage for. */
149
191
  unmetered: number;
@@ -163,7 +205,9 @@ export interface AiAgentUse {
163
205
  key: string;
164
206
  name: string;
165
207
  from: AiNameSource;
208
+ /** Its calls, prewarms apart (`prewarms`): a prewarm's tokens are in the totals. */
166
209
  calls: number;
210
+ prewarms?: number;
167
211
  runs: number;
168
212
  failed: number;
169
213
  input: number;