@lensmcp/protocol-types 1.26.13 → 1.26.15

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 (59) hide show
  1. package/index.d.ts +2 -0
  2. package/index.js +1 -1
  3. package/lib/accounts.d.ts +35 -6
  4. package/lib/ai-cache-facts.js +1 -1
  5. package/lib/ai-cache-verdict.js +1 -1
  6. package/lib/ai-cache.js +3 -3
  7. package/lib/ai-call-groups.js +2 -2
  8. package/lib/ai-call-row.js +3 -3
  9. package/lib/ai-call.js +9 -9
  10. package/lib/ai-compare.js +3 -3
  11. package/lib/ai-context.js +6 -6
  12. package/lib/ai-origins.js +9 -9
  13. package/lib/ai-together.js +5 -5
  14. package/lib/bounded-clone.js +1 -1
  15. package/lib/bounded-map.js +1 -1
  16. package/lib/bounded-writer.js +1 -1
  17. package/lib/capture-demand.js +1 -1
  18. package/lib/cluster-hosts.d.ts +1 -1
  19. package/lib/conversations.d.ts +286 -0
  20. package/lib/conversations.js +1 -0
  21. package/lib/dashboard-lint.d.ts +31 -0
  22. package/lib/dashboard-path.js +1 -1
  23. package/lib/docker-errors.js +1 -1
  24. package/lib/docker-jobs.d.ts +1 -1
  25. package/lib/docker-jobs.js +1 -1
  26. package/lib/docker-report.js +2 -2
  27. package/lib/docker-runs.d.ts +1 -1
  28. package/lib/docker-runs.js +3 -3
  29. package/lib/error-cause.js +6 -6
  30. package/lib/error-dismissal.js +1 -1
  31. package/lib/error-verdict.js +3 -3
  32. package/lib/event-loop.js +1 -1
  33. package/lib/expected-failure.js +2 -2
  34. package/lib/finding-proof.js +1 -1
  35. package/lib/flood-guard.js +1 -1
  36. package/lib/goal-design.js +1 -1
  37. package/lib/host-agents.d.ts +1 -1
  38. package/lib/host-agents.js +1 -1
  39. package/lib/hosts.d.ts +1 -1
  40. package/lib/lint-coverage.js +1 -1
  41. package/lib/lint-ignores.d.ts +154 -0
  42. package/lib/lint-ignores.js +2 -0
  43. package/lib/log-query.js +1 -1
  44. package/lib/metrics-reset.js +1 -1
  45. package/lib/overseer-findings.js +1 -1
  46. package/lib/peers.d.ts +275 -23
  47. package/lib/peers.js +1 -1
  48. package/lib/perf-rules.js +1 -1
  49. package/lib/pod-memory.js +1 -1
  50. package/lib/producer-health.js +1 -1
  51. package/lib/remote-instances.d.ts +1 -1
  52. package/lib/remote-instances.js +1 -1
  53. package/lib/sources.js +1 -1
  54. package/lib/static-checks.d.ts +6 -0
  55. package/lib/static-checks.js +1 -1
  56. package/lib/system-report.js +1 -1
  57. package/lib/team.d.ts +21 -0
  58. package/lib/team.js +1 -1
  59. package/package.json +1 -1
package/index.d.ts CHANGED
@@ -17,6 +17,7 @@ export * from './lib/dashboard-path.js';
17
17
  export * from './lib/dashboard-lint.js';
18
18
  export * from './lib/dashboard-typecheck.js';
19
19
  export * from './lib/lint-coverage.js';
20
+ export * from './lib/lint-ignores.js';
20
21
  export * from './lib/static-checks.js';
21
22
  export * from './lib/log-query.js';
22
23
  export * from './lib/error-dismissal.js';
@@ -58,6 +59,7 @@ export * from './lib/host-agents.js';
58
59
  export * from './lib/remote-instances.js';
59
60
  export * from './lib/team.js';
60
61
  export * from './lib/sessions.js';
62
+ export * from './lib/conversations.js';
61
63
  export * from './lib/backlog.js';
62
64
  export * from './lib/team-review-changes.js';
63
65
  export * from './lib/goal-outcome.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/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/accounts.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/lint-ignores.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/accounts.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/conversations.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";
package/lib/accounts.d.ts CHANGED
@@ -32,8 +32,19 @@ export interface DashAccountRow {
32
32
  /** Its name — «The client's own sign-in» for an own one. */
33
33
  label: string;
34
34
  own?: true;
35
- /** The plan as the client names it (`Max 20×`, `Team`, `Business`…), when known. */
35
+ /** The plan in a word or two (`Ultra ×10`, `Max ×5`, `Pro`, `Team`, `Business`…), when known — its label only. */
36
36
  plan?: string;
37
+ /**
38
+ * The plan as a key — what the page decides from, never its label. Claude: `ultra` (Claude Code's `max_20x`), `max-5x`,
39
+ * `max` (a Max it does not size), `pro`, `team`, `enterprise`, `free`, or the word Claude Code said; Codex: its
40
+ * `planType` as Codex says it (`plus`, `prolite`, `team`, `self_serve_business_prolite`…). Ultra has no 5-hour window.
41
+ */
42
+ planTier?: string;
43
+ /**
44
+ * On a client's own sign-in: the added account it is (the server compared who the two sign-ins are one way — no email,
45
+ * nor any key of one, is sent). The page shows that account once.
46
+ */
47
+ sameAs?: string;
37
48
  /** New launches of its client use it (`lensmcp claude`, a goal with no account). */
38
49
  default?: true;
39
50
  /** Kept for the person's own sessions: no team agent runs on it; `run` starts the client on it by hand. */
@@ -52,9 +63,27 @@ export interface DashAccountRow {
52
63
  readHow?: string;
53
64
  /** Why the newest read failed, when it did — `windows` are then the last good reading. */
54
65
  readWhy?: string;
55
- /** While its sign-in runs: when it started, and the link the client printed. */
56
- signingIn?: {
57
- startedAt: number;
58
- link?: string;
59
- };
66
+ /** While its sign-in runs: when it started, the link the client printed, and what the page needs to finish it. */
67
+ signingIn?: DashAccountSigningIn;
68
+ }
69
+ /**
70
+ * A sign-in the dashboard runs (`POST /api/accounts/add`, `/login`). Claude Code's runs on a terminal of its own, so
71
+ * when claude.ai shows a code instead of returning to Claude Code, the page takes it (`POST /api/accounts/code`) and
72
+ * types it there; `POST /api/accounts/cancel` stops it. No code is ever in an answer.
73
+ */
74
+ export interface DashAccountSigningIn {
75
+ startedAt: number;
76
+ /** When the lens stops it if it has not finished (10 minutes on). Absent from a lens before it. */
77
+ stopsAt?: number;
78
+ /** The sign-in page's link, as the client printed it — the browser it opened may be another one. */
79
+ link?: string;
80
+ /** The client asks for the code its sign-in page shows («Paste code here if prompted»): the page offers a field for it. */
81
+ codeWanted?: true;
82
+ /** A code was typed into it and the client has not answered yet. */
83
+ checking?: true;
84
+ /**
85
+ * The client's last complaint, in its words — «Couldn't log in: Authentication failed: Invalid authorization code»,
86
+ * «That doesn't look like the full code…». Never what was typed.
87
+ */
88
+ problem?: string;
60
89
  }
@@ -1 +1 @@
1
- "use strict";var l=Object.defineProperty;var o=(e,a)=>l(e,"name",{value:a,configurable:!0});var d=Object.defineProperty,n=o((e,a)=>d(e,"name",{value:a,configurable:!0}),"o"),h=Object.defineProperty,i=n((e,a)=>h(e,"name",{value:a,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,a=Date.now(),t=45){const p=Date.parse(`${e}T00:00:00Z`);if(!Number.isFinite(p))return{stale:!0};const c=Math.max(0,Math.floor((a-p)/864e5));return{days:c,stale:c>t}}o(aiGuidanceAge,"aiGuidanceAge"),n(aiGuidanceAge,"aiGuidanceAge"),i(aiGuidanceAge,"aiGuidanceAge");const r=6e4,s=60*r;export const AI_CACHE_TTL_MS={"5m":5*r,"1h":s,"30m":30*r,"12h":12*s,"24h":24*s,in_memory:10*r},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 a=AI_CACHE_FACTS.find(t=>t.id===e);return a?{...a,from:AI_GUIDANCE_SOURCES[a.source]}:void 0}o(aiCacheFact,"aiCacheFact"),n(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,a){if(e!=="anthropic")return 1024;const t=(a??"").replace(/^anthropic\//,"");return/^claude-(?:opus-4-[56]|haiku-4-5)/.test(t)?4096:/^claude-opus-4-7/.test(t)?2048:/^claude-(?:sonnet-5(?!-5)|opus-4-8|sonnet-4|opus-4(?:-1)?(?![-\d]))/.test(t)?1024:512}o(aiCacheMinTokens,"aiCacheMinTokens"),n(aiCacheMinTokens,"aiCacheMinTokens"),i(aiCacheMinTokens,"aiCacheMinTokens");export const aiDefaultTtl=i((e,a)=>e==="anthropic"?"5m":openaiNewCache(a)?"30m":"24h","aiDefaultTtl");
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");
@@ -1 +1 @@
1
- "use strict";var It=Object.defineProperty;var F=(e,s)=>It(e,"name",{value:s,configurable:!0});var Ut=Object.defineProperty,R=F((e,s)=>Ut(e,"name",{value:s,configurable:!0}),"F"),Dt=Object.defineProperty,k=R((e,s)=>Dt(e,"name",{value:s,configurable:!0}),"w");import{AI_CACHE_TTL_MS as at,AI_GUIDANCE_SOURCES as xt,aiCacheMinTokens as Et,aiGuidanceAge as Ft}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 M=k(e=>Math.round(e).toLocaleString("en-US"),"fmt"),rt=k(e=>`$${e<.01&&e>0?e.toFixed(4):e.toFixed(2)}`,"money"),_=k(e=>`$${Number(e.toFixed(4))}`,"rate"),S=k(e=>Math.round(e*1e6)/1e6,"usd"),G=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"),Rt=k(e=>e.tokens?.input!==void 0&&e.cache!==void 0&&!e.failed,"counted");export function aiCacheVerdicts(e,s,g=Date.now()){const h=new Map,u=new Map;for(const d of e){if(!d.cache)continue;const n=u.get(d.agent.key);n?n.push(d):u.set(d.agent.key,[d])}for(const d of u.values()){d.sort((n,i)=>n.at-i.at||n.id.localeCompare(i.id));for(const[n,i]of dt(d,s,g))h.set(n,i)}return h}F(aiCacheVerdicts,"aiCacheVerdicts"),R(aiCacheVerdicts,"aiCacheVerdicts"),k(aiCacheVerdicts,"aiCacheVerdicts");function ot(e,s){const g=e==="anthropic"?xt.anthropicCaching:xt.openaiCaching;return{source:g.url,readAt:g.readAt,...Ft(g.readAt,s).stale?{stale:!0}:{}}}F(ot,"gt"),R(ot,"It"),k(ot,"factsOf");function dt(e,s,g){const h=[],u=new Map,d=new Map;e.forEach((n,i)=>{const o=n.cache,$=n.at,x=n.durationMs!==void 0?n.at+n.durationMs:void 0,U=at[o.ttl],r={row:n,start:$,...x!==void 0?{end:x}:{},ttlMs:U,wrote:[]};h.push(r);const a=o.marks??[],w=a.filter(t=>t.bp),A=n.tokens?.input??0,m=n.tokens?.cached??0,f=n.tokens?.written??0,v=Rt(n),c=n.model?s(n.model,A):void 0,Q=ot(n.provider,g),X={...c?{price:{...c.source?{source:c.source}:{},...c.readAt?{readAt:c.readAt}:{},...c.stale?{stale:!0}:{}}}:{},facts:Q},nt=k(()=>{for(const t of a){const l=d.get(t.h);l?l.push(i):d.set(t.h,[i])}},"remember"),it=k((t,l)=>{const p=u.get(t);p?p.push({i,how:l}):u.set(t,[{i,how:l}])},"hold"),Y=Et(n.provider,n.model);if(!v){if(!n.failed)for(const t of w)it(t.h,"unknown");nt(),r.verdict=tt(o,A,Y,X)??{kind:"unknown",said:n.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:X},n.prewarm&&(r.verdict.prewarm=!0);return}const N=tt(o,A,Y,X);if(N){const t=et(r,h,d,i);if(t&&t.tokens>=Y&&c){const l=c.cacheRead??c.input,p=t.tokens*(c.input-l)/1e6;N.costs.push({kind:"no-cache",tokens:t.tokens,usd:S(p),arithmetic:`${M(t.tokens)} \xD7 (${_(c.input)} \u2212 ${_(l)})/M`,estimate:!0}),N.lostUsd=S(p),N.said+=` It shares \u2248 ${M(t.tokens)} tokens with ${t.id} (${G($-h[t.i].start)} before): read from a cache, they would cost \u2248 ${rt(p)} less.`}n.prewarm&&(N.prewarm=!0),r.verdict=N,nt();return}const z=Math.max(256,A*.03),vt=k((t,l)=>l.reduce((p,b)=>!p||Math.abs(b.t-t)<Math.abs(p.t-t)?b:p,void 0),"nearest");let j=-1;if(m>0){const t=vt(m,w.length?w:a);t&&Math.abs(t.t-m)<=Math.max(z,m*.15)&&(r.readBp={h:t.h,t:t.t,s:t.s},j=w.indexOf(t))}w.forEach((t,l)=>(l<=j||j<0&&t.t<=m+z)&&it(t.h,"read"));const ct=w.filter((t,l)=>j>=0?l>j:t.t>m+z),bt=j>=0?w[j].t:m;let D=f>0?ct.filter(t=>t.t<=bt+f+Math.max(z,f*.15)):[];if(f>0&&!D.length){const t=ct[0]??w[w.length-1];D=t?[t]:[]}const ht=D.map((t,l)=>Math.max(1,t.t-(l?D[l-1].t:Math.max(m,w.filter(p=>p.t<t.t).pop()?.t??0)))),Bt=ht.reduce((t,l)=>t+l,0);D.forEach((t,l)=>{const p=D.length===1?f:Math.round(ht[l]/Bt*f),b=o.breakpoints.find(I=>Math.abs(I.tokens-t.t)<=1)?.ttl??o.ttl,T=at[b],V=(u.get(t.h)??[]).filter(I=>I.i<i),W=V.filter(I=>$-h[I.i].start<=T);if(W.length){const I=k(B=>h[B.i].end!==void 0&&h[B.i].end<=$,"done"),q=k(B=>B[B.length-1],"last"),mt=W.filter(B=>B.how==="wrote"),kt=W.filter(B=>B.how==="unknown"),gt=q(mt.filter(I))??q(kt.filter(I)),$t=q(mt.filter(B=>!I(B)))??q(kt.filter(B=>!I(B))),At=gt??$t??q(W),yt=!gt&&!!$t,Ct=W.filter(B=>B.how==="read").length;r.wrote.push({h:t.h,s:t.s,tokens:p,estimate:D.length>1,ttl:b,status:"duplicate",against:At,race:yt,readFirst:Ct})}else V.length?r.wrote.push({h:t.h,s:t.s,tokens:p,estimate:D.length>1,ttl:b,status:"cold",against:V[V.length-1],idleMs:$-h[V[V.length-1].i].start}):r.wrote.push({h:t.h,s:t.s,tokens:p,estimate:D.length>1,ttl:b,status:"first"});it(t.h,"wrote")});const y=et(r,h,d,i);nt();const L=c?c.cacheRead??c.input:void 0,lt=c?K(c,o.writes,o.ttl):void 0,P=[];let Z,ut;if(y){const t=w.filter(b=>b.t<=y.tokens+1&&y.hashes.has(b.h)).reduce((b,T)=>Math.max(b,T.t),0),l=Math.max(m,t),p=y.tokens-l;if(y.tokens>=Y&&p>z){Z={region:y.next??"(the end of the prompt)",tokens:y.tokens,id:h[y.i].row.id},ut=h[y.i];const b=m+f>=y.tokens-z,T=c?b?lt-L:c.input-L:void 0;P.push({kind:"broken-prefix",tokens:p,estimate:!0,...T!==void 0?{usd:S(p*T/1e6),arithmetic:`${M(p)} \xD7 (${_(b?lt:c.input)} \u2212 ${_(L)})/M`}:{}})}}for(const t of r.wrote){if(t.status==="first")continue;const l=c?K(c,o.writes,t.ttl):void 0;P.push({kind:t.status==="duplicate"?"duplicate-write":"cold",tokens:t.tokens,estimate:t.estimate,...c?{usd:S(t.tokens*(l-L)/1e6),arithmetic:`${M(t.tokens)} \xD7 (${_(l)} \u2212 ${_(L)})/M`}:{}})}const C=[];r.wrote.some(t=>t.status==="duplicate")&&C.push("duplicate-write"),Z&&C.push("broken-prefix"),r.wrote.some(t=>t.status==="cold")&&C.push("cold"),r.wrote.some(t=>t.status==="first")&&C.push("first-writer"),m>0&&C.push("read"),C.length||C.push("no-cache");const O=r.wrote.find(t=>t.status==="duplicate"),J=r.wrote.find(t=>t.status==="cold"),ft=O?.against??J?.against,E=ft?h[ft.i]:ut,pt=P.some(t=>t.usd!==void 0)?S(P.reduce((t,l)=>t+(l.usd??0),0)):void 0,wt=c&&m>0?S(m*(c.input-L)/1e6):void 0,Mt=C[0];r.verdict={kind:Mt,...C.length>1?{also:C.slice(1)}:{},said:"",costs:P,...pt!==void 0?{lostUsd:pt}:{},...wt!==void 0?{savedUsd:wt}:{},...O||J||r.wrote[0]||r.readBp?{prefix:(O??J??r.wrote[0])?.h??r.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}:{}}}:{},...O?{race:!!O.race,...O.readFirst?{readBefore:O.readFirst}:{}}:{},...Z?{brokeAt:Z}:{},...J?.idleMs!==void 0?{idleMs:J.idleMs}:{},...n.prewarm?{prewarm:!0}:{},basis:X}});for(const n of h){const i=n.verdict;if(!n.wrote.length){i.said=st(n,i);continue}const o=new Set,$=new Set;let x=!1;const U=[];for(const r of n.wrote){const a=at[r.ttl],w=(u.get(r.h)??[]).filter(f=>h[f.i].start>n.start&&h[f.i].start-n.start<=a),A=w.filter(f=>f.how==="read"),m=w.filter(f=>f.how==="unknown");for(const f of A)o.add(f.i);for(const f of m)$.add(f.i);n.start+a>g?x=!0:!A.length&&!m.length&&U.push(r)}for(const r of o)$.delete(r);if(o.size&&(i.readBy=o.size),$.size&&(i.maybeReadBy=$.size),x&&(i.open=!0),U.length){const r=n.row,a=r.model?s(r.model,r.tokens?.input??0):void 0;let w=i.costs.find(v=>v.kind==="broken-prefix")?.tokens??0;for(const v of U){if(v.status!=="first")continue;const c=Math.max(0,v.tokens-w);if(w=0,!c)continue;const Q=a?K(a,r.cache.writes,v.ttl):void 0;i.costs.push({kind:"write-nothing-read",tokens:c,estimate:v.estimate||c!==v.tokens,...a?{usd:S(c*(Q-a.input)/1e6),arithmetic:`${M(c)} \xD7 (${_(Q)} \u2212 ${_(a.input)})/M`}:{}})}a&&(i.lostUsd=S(i.costs.reduce((v,c)=>v+(c.usd??0),0)));const A=[i.kind,...i.also??[]],m=A.findIndex(v=>v!=="duplicate-write"&&v!=="broken-prefix"&&v!=="cold");A.splice(m<0?A.length:m,0,"write-nothing-read"),i.kind=A[0];const f=A.slice(1);f.length?i.also=f:delete i.also}i.said=st(n,i)}return new Map(h.map(n=>[n.row.id,n.verdict]))}F(dt,"$t"),R(dt,"Ut"),k(dt,"judgeAgent");function K(e,s,g){const h=Object.entries(s??{}).filter(d=>typeof d[1]=="number"&&d[1]>0);if(h.length>1){const d=h.reduce((n,[,i])=>n+i,0);return h.reduce((n,[i,o])=>n+(e.writes[i]??e.input)*o,0)/d}const u=h[0]?.[0]??g;return e.writes[u]??e.input}F(K,"Y"),R(K,"et"),k(K,"writeRate");function tt(e,s,g,h){const u=k(d=>({kind:"no-cache",said:d,costs:[],basis:h}),"no");if(e.mode==="explicit"&&!e.breakpoints.length)return u("Explicit mode with no breakpoint: it read and wrote nothing.");if(e.mode==="none")return u("No `cache_control`: Anthropic cached nothing of it.");if(s>0&&s<g)return u(`${M(s)} input tokens \u2014 under the ${M(g)}-token minimum: nothing is cached.`)}F(tt,"it"),R(tt,"pt"),k(tt,"structural");function et(e,s,g,h){const u=e.row.cache?.marks??[];let d;for(let i=0;i<u.length;i++){const o=g.get(u[i].h);if(o)for(let $=o.length-1;$>=0;$--){const x=o[$];if(!(x>=h)){if(e.start-s[x].start>e.ttlMs)break;d={i:x,at:i};break}}}if(!d)return;const n=s[d.i];return{i:d.i,id:n.row.id,tokens:u[d.at].t,...u[d.at+1]?{next:u[d.at+1].s}:{},hashes:new Set((n.row.cache?.marks??[]).map(i=>i.h))}}F(et,"st"),R(et,"wt"),k(et,"sharedWith");const H=k(e=>e.split(" \u203A ")[0],"block");function st(e,s){if(s.said)return s.said;const g=e.row,h=g.cache,u=g.tokens?.input??0,d=s.read??0,n=s.written??0,i=h.ttl,o=[],$=s.prewarm?"A prewarm (it answers nothing): it ":"It ";o.push(`${$}read ${M(d)} of its ${M(u)} input tokens from the cache${n?` and wrote ${M(n)}`:""} (${h.mode} mode, ${i}).`);const x=e.wrote.find(a=>a.status==="duplicate");if(x&&s.against){const a=s.against,w=s.readBefore?` ${M(s.readBefore)} call${s.readBefore===1?"":"s"} sent before this one read it.`:"";o.push(s.race?`Duplicate write \u2014 a race: ${a.id}${x.against?.how==="unknown"?" (its count was not kept: it may have)":""} wrote the same prefix (to the end of \xAB${H(x.s)}\xBB) and was still in flight when this one was sent, ${G(a.gapMs)} after it.${w}`:x.against?.how==="read"?`Duplicate write: ${a.id} had read the same prefix (to the end of \xAB${H(x.s)}\xBB) ${G(a.gapMs)} before \u2014 the entry was there, and this call did not read it.`:`Duplicate write: ${a.id}${a.prewarm?" (a prewarm)":""}${x.against?.how==="unknown"?" (its count was not kept: it may have)":""} wrote the same prefix (to the end of \xAB${H(x.s)}\xBB) ${G(a.gapMs)} before${a.ended!==void 0&&a.ended<=e.start?` and had ended ${G(e.start-a.ended)} before this one was sent \u2014 not a race: the write had finished and this call did not read it`:""}.${w}`)}s.brokeAt&&o.push(`Broken prefix: it shares \u2248 ${M(s.brokeAt.tokens)} tokens with ${s.brokeAt.id}, then they part in \xAB${s.brokeAt.region}\xBB \u2014 no breakpoint ends where they part, so it read only ${M(d)}.`);const U=e.wrote.find(a=>a.status==="cold");U&&s.idleMs!==void 0&&o.push(`Cold: the same prefix (to the end of \xAB${H(U.s)}\xBB) was last used ${G(s.idleMs)} before \u2014 past its ${U.ttl} lifetime.`);const r=e.wrote.filter(a=>a.status==="first");return r.length&&o.push(`First writer of the prefix to the end of \xAB${r.map(a=>H(a.s)).join("\xBB, \xAB")}\xBB.`),e.wrote.length&&(s.kind==="write-nothing-read"||s.also?.includes("write-nothing-read")?o.push("No later call of its agent read what it wrote inside its lifetime."):s.readBy?o.push(`${M(s.readBy)} later call${s.readBy===1?"":"s"} read what it wrote.`):s.maybeReadBy?o.push(`${M(s.maybeReadBy)} later call${s.maybeReadBy===1?"":"s"} may have read it (their counts were not kept).`):s.open&&o.push("Its lifetime has not run out: a later call may still read it.")),!e.wrote.length&&d>0&&!s.brokeAt&&o.push(`Read${e.readBp?` to the end of \xAB${H(e.readBp.s)}\xBB`:""}.`),s.lostUsd!==void 0&&s.lostUsd>0&&o.push(`\u2248 ${rt(s.lostUsd)} lost: ${s.costs.filter(a=>a.arithmetic).map(a=>`${a.arithmetic}${a.estimate?" (estimate)":""}`).join(" + ")}.`),s.savedUsd&&o.push(`Its reads saved \u2248 ${rt(s.savedUsd)} against plain input.`),o.join(" ")}F(st,"rt"),R(st,"kt"),k(st,"said");
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");
package/lib/ai-cache.js CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var V=Object.defineProperty;var b=(t,o)=>V(t,"name",{value:o,configurable:!0});var W=Object.defineProperty,x=b((t,o)=>W(t,"name",{value:o,configurable:!0}),"b"),X=Object.defineProperty,m=x((t,o)=>X(t,"name",{value:o,configurable:!0}),"u");import{aiDefaultTtl as I,openaiNewCache as H}from"./ai-cache-facts.js";export const MAX_MARKS=48;const K=400,Y=72,S=m(t=>!!t&&typeof t=="object"&&!Array.isArray(t),"isObj"),g=m(t=>typeof t=="string"?t:void 0,"str"),O=m(t=>Array.isArray(t)?t:[],"arr"),y=m(t=>S(t)?t:{},"obj"),Z=["5m","1h","30m","12h","24h","in_memory"],w=m(t=>typeof t=="string"&&Z.includes(t)?t:void 0,"ttlOf");function A(t){if(typeof t=="string")return t;const o=y(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,"A"),x(A,"C"),m(A,"partText");const q=m((t,o)=>{const e={};for(const h of o){let l=t;for(const p of h.split("."))l=y(l)[p];l!==void 0&&(e[h]=l)}return e},"pick");function D(t){const o=y(t).prompt_cache_breakpoint;if(o==null||o===!1)return;const e=w(y(o).ttl);return e?{ttl:e}:{}}b(D,"P"),x(D,"F"),m(D,"openaiBreakpoint");function M(t){const o=y(t).cache_control;if(!S(o))return;const e=w(o.ttl);return e?{ttl:e}:{}}b(M,"j"),x(M,"L"),m(M,"anthropicBreakpoint");function L(t){const o=g(t.model),e=y(t.prompt_cache_options),h=H(o),l=g(e.mode)==="explicit"||g(e.mode)==="implicit",p=g(e.mode)==="explicit"?"explicit":"implicit",n=w(h?e.ttl:t.prompt_cache_retention),s=[],r=g(t.instructions);r&&s.push({label:"instructions",role:"developer",text:r}),O(t.tools).length&&s.push({label:"tools",text:JSON.stringify(t.tools),weight:.7});const i=y(y(t.text).format);i.schema!==void 0&&s.push({label:`answer schema${g(i.name)?` \xB7 ${g(i.name)}`:""}`,text:JSON.stringify(i.schema),weight:.7});let f=-1;const a=t.input;if(typeof a=="string")s.push({label:"user",role:"user",text:a}),f=s.length-1;else{const k=O(a).map(y);let v=!0;k.forEach((c,_)=>{const u=g(c.type)??(c.role?"message":""),$=g(c.role)??(u==="function_call_output"?"tool":"item"),N=u==="message"?c.content:u==="function_call_output"?c.output:void 0,J=typeof N=="string"?[N]:Array.isArray(N)?N:void 0,E=u==="message"?$:u||"item";if(J)J.forEach((R,G)=>{const B=D(R);s.push({label:J.length>1?`${E} \xB7 block ${G+1} of ${J.length}`:E,role:$,text:A(R),...B?{bp:B}:{}})});else{const{id:R,status:G,...B}=c;s.push({label:E,role:$,text:JSON.stringify(B)})}const j=k[_+1],F=j?g(j.type)??(j.role?"message":""):"";(u==="message"&&$==="user"||u==="function_call_output"&&F!=="function_call_output"||v&&u==="message"&&$==="developer"&&!(F==="message"&&g(j.role)==="developer"))&&(f=s.length-1),u==="message"&&$==="developer"||(v=!1)})}p==="implicit"&&f>=0&&(s[f].bp={...s[f].bp??{},implicit:!0});const d={model:o,...q(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:n??I("openai",o),ttlSaid:!!n,prewarm:e.prewarm===!0,key:typeof t.prompt_cache_key=="string"}}b(L,"T"),x(L,"G"),m(L,"responsesRequest");function z(t){const o=g(t.model),e=[];O(t.tools).length&&e.push({label:"tools",text:JSON.stringify(t.tools),weight:.7});const h=y(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=O(t.messages).map(y);p.forEach((r,i)=>{const f=g(r.role)??"user",a=r.content,d=typeof a=="string"?[a]:Array.isArray(a)?a:[];d.length||e.push({label:f,role:f,text:JSON.stringify({...r,content:void 0})}),d.forEach((v,c)=>e.push({label:d.length>1?`${f} \xB7 block ${c+1} of ${d.length}`:f,role:f,text:A(v)})),r.tool_calls!==void 0&&e.push({label:`${f} \xB7 tool calls`,role:f,text:JSON.stringify(r.tool_calls)});const k=g(p[i+1]?.role);(f==="user"||f==="tool"&&k!=="tool")&&(l=e.length-1)}),l>=0&&(e[l].bp={implicit:!0});const n=w(t.prompt_cache_retention),s={model:o,...q(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:n??I("openai",o),ttlSaid:!!n,prewarm:!1,key:typeof t.prompt_cache_key=="string"}}b(z,"I"),x(z,"Q"),m(z,"chatRequest");function P(t){const o=g(t.model),e=[];for(const i of O(t.tools).map(y)){const f=M(i),{cache_control:a,...d}=i;e.push({label:`tools \xB7 ${g(i.name)??g(i.type)??"tool"}`,text:JSON.stringify(d),weight:.7,...f?{bp:f}:{}})}const h=t.system;if(typeof h=="string"&&h)e.push({label:"system",role:"system",text:h});else{const i=O(h);i.forEach((f,a)=>{const d=M(f);e.push({label:i.length>1?`system \xB7 block ${a+1} of ${i.length}`:"system",role:"system",text:A(f),...d?{bp:d}:{}})})}for(const i of O(t.messages).map(y)){const f=g(i.role)??"user",a=i.content,d=typeof a=="string"?[a]:O(a);d.forEach((k,v)=>{const c=M(k);e.push({label:d.length>1?`${f} \xB7 block ${v+1} of ${d.length}`:f,role:f,text:A(k),...c?{bp:c}:{}})})}const l=t.cache_control,p=e.some(i=>i.bp);if(S(l)&&e.length){const i=e[e.length-1];i.bp={...i.bp??(w(l.ttl)?{ttl:w(l.ttl)}:{}),implicit:!0}}const n=p?"explicit":S(l)?"automatic":"none",s=S(l)?w(l.ttl):void 0,r={model:o,...q(t,["tool_choice","thinking","output_config.effort","speed"])};return{provider:"anthropic",api:"messages",...o?{model:o}:{},settings:JSON.stringify(r),blocks:e,mode:n,modeSaid:p||S(l),ttl:s??"5m",ttlSaid:!!s,prewarm:!1,key:!1}}b(P,"K"),x(P,"U"),m(P,"messagesRequest");export function aiCacheRequestOf(t,o){if(S(o)){if(t==="responses")return L(o);if(t==="chat")return z(o);if(t==="messages")return P(o)}}b(aiCacheRequestOf,"aiCacheRequestOf"),x(aiCacheRequestOf,"aiCacheRequestOf"),m(aiCacheRequestOf,"aiCacheRequestOf");class tt{static{b(this,"Y")}static{x(this,"V")}static{m(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,n=0,s=this.word,r=this.digits,i=this.space;for(let f=0;f<o.length;f++){const a=o.charCodeAt(f);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)&&(n+=1),s++,r=0,i=0):a>=48&&a<=57?(r%3===0&&(n+=1),r++,s=0,i=0):a===32||a===9||a===10||a===13?((a===10||i===1)&&(n+=i<2?1:0),i=a===10?2:i+1,s=0,r=0):(s=0,r=0,i=0,n+=a>=11904?.9:a>=192?.66:.75))}this.h1=l,this.h2=p,this.word=s,this.digits=r,this.space=i,e&&(this.tokens+=n*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 n=e;for(;n<p&&(t.charCodeAt(n)===32||t.charCodeAt(n)===9);)n++;const s=t[n];if(s==="-"||s==="#"||s==="<"){const r=t.slice(n,Math.min(p,n+240)),i=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);i&&i[1].trim()&&o.push({at:e,title:i[1].trim().slice(0,Y)})}e=p+1}return o}b(aiCacheSections,"aiCacheSections"),x(aiCacheSections,"aiCacheSections"),m(aiCacheSections,"aiCacheSections");function T(t,o){const e=t.text.length,h=e>=2*K?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 n={at:0,title:p??"(opening)",last:void 0,opening:!p};const s=[],r=m(i=>`${t.label} \u203A ${i.last?`${Q(i.title)} \u2026 ${Q(i.last)}`:i.title}`,"titled");for(const i of h)if(i.at!==0){if(i.at-n.at<K){n.opening?n={at:n.at,title:i.title,last:void 0,opening:!1}:n.last=i.title;continue}s.push({block:o,from:n.at,to:i.at,title:r(n),end:!1}),n={at:i.at,title:i.title,last:void 0,opening:!1}}return s.length?(s.push({block:o,from:n.at,to:e,title:r(n),end:!0}),s):l}b(T,"X"),x(T,"W"),m(T,"regionsOf");const Q=m(t=>t.length>36?`${t.slice(0,35)}\u2026`:t,"clip"),et=4;export function aiCacheOf(t,o,e,h={}){const l=aiCacheRequestOf(t,o);if(!l)return;const p=new tt;p.feed(l.settings,!1);const n=[];l.blocks.forEach((c,_)=>{p.feed(`\0${c.role??""}`,!1),p.tokens+=et;for(const u of T(c,_))p.feed(c.text.slice(u.from,u.to),!0,c.weight??1),(u.end||n.length<MAX_MARKS-8)&&n.push({h:p.digest(),chars:p.chars,tokens:p.tokens,s:u.title,...u.end&&c.bp?{bp:c.bp}:{},blockEnd:u.end})});const s=p.tokens,r=e?.input!==void 0&&e.input>0,i=r&&s>0?e.input/s:1,f=m(c=>Math.round(c*i),"round");let a=n.map(c=>({h:c.h,t:f(c.tokens),s:c.s,...c.bp?{bp:1}:{}}));if(a.length>MAX_MARKS){const c=new Set;a.forEach((_,u)=>_.bp&&c.add(u));for(let _=a.length-1;_>=0&&c.size<MAX_MARKS;_--)c.add(_);a=a.filter((_,u)=>c.has(u))}const d=n.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:f(c.tokens)})),k=e?.cached,v=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:k??0,written:v??0,plain:Math.max(0,e.input-(k??0)-(v??0))}:{},...e?.writes&&Object.keys(e.writes).length?{writes:{...e.writes}}:{},marks:a,estimated:!r}}b(aiCacheOf,"aiCacheOf"),x(aiCacheOf,"aiCacheOf"),m(aiCacheOf,"aiCacheOf");const U=200,C=m((t,o)=>{const e=t.lastIndexOf(`
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
3
  `,o-1)+1,h=t.indexOf(`
4
- `,o),l=t.slice(e,h<0?t.length:h).trim();return l.length>U?`${l.slice(0,U-1)}\u2026`:l},"lineAt");export function aiCacheDiff(t,o,e){if(t.settings!==o.settings){const n=JSON.parse(t.settings),s=JSON.parse(o.settings);return{region:"settings",setting:[...new Set([...Object.keys(n),...Object.keys(s)])].filter(r=>JSON.stringify(n[r])!==JSON.stringify(s[r])).join(", "),chars:0,tokens:0}}let h=0;const l=t.blocks.reduce((n,s)=>n+s.text.length,0),p=m(n=>e!==void 0&&l>0?Math.round(n/l*e):Math.round(n/4),"tokensAt");for(let n=0;n<Math.max(t.blocks.length,o.blocks.length);n++){const s=t.blocks[n],r=o.blocks[n];if(!s||!r)return{region:s?s.label:"the end of this prompt",chars:h,tokens:p(h),...s?{line:C(s.text,0)}:{},...r?{otherLine:C(r.text,0)}:{}};if(s.role!==r.role)return{region:s.label,chars:h,tokens:p(h),line:C(s.text,0),otherLine:C(r.text,0)};if(s.text===r.text){h+=s.text.length;continue}let i=0;const f=Math.min(s.text.length,r.text.length);for(;i<f&&s.text.charCodeAt(i)===r.text.charCodeAt(i);)i++;const a=[...aiCacheSections(s.text)].reverse().find(d=>d.at<=i);return{region:a?`${s.label} \u203A ${a.title}`:s.label,chars:h+i,tokens:p(h+i),line:C(s.text,Math.min(i,Math.max(0,s.text.length-1))),otherLine:C(r.text,Math.min(i,Math.max(0,r.text.length-1)))}}return{region:"(none)",chars:h,tokens:p(h),same:!0}}b(aiCacheDiff,"aiCacheDiff"),x(aiCacheDiff,"aiCacheDiff"),m(aiCacheDiff,"aiCacheDiff");
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");
@@ -1,2 +1,2 @@
1
- "use strict";var m=Object.defineProperty;var i=(e,n)=>m(e,"name",{value:n,configurable:!0});var d=Object.defineProperty,l=i((e,n)=>d(e,"name",{value:n,configurable:!0}),"i"),p=Object.defineProperty,f=l((e,n)=>p(e,"name",{value:n,configurable:!0}),"i");export function aiTotalsOf(e){const n=e.filter(t=>!t.prewarm),o={calls:n.length,prewarms:e.length-n.length,runs:new Set(n.map(t=>t.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 t of e){t.failed&&o.failed++,o.input+=t.tokens?.input??0,o.cached+=t.tokens?.cached??0,o.written+=t.tokens?.written??0,o.output+=t.tokens?.output??0;for(const[s,a]of Object.entries(t.split??{}))o.split[s]=(o.split[s]??0)+a;t.costUsd!==void 0&&(o.costUsd+=t.costUsd,o.priced++),o.first=Math.min(o.first,t.at),o.last=Math.max(o.last,t.at),t.model&&r.set(t.model,(r.get(t.model)??0)+1)}return o.models=[...r].sort((t,s)=>s[1]-t[1]).map(([t])=>t),e.length||(o.first=0),o}i(aiTotalsOf,"aiTotalsOf"),l(aiTotalsOf,"aiTotalsOf"),f(aiTotalsOf,"aiTotalsOf");export function aiRunsOf(e,n=!1){const o=new Map;for(const r of e){const t=o.get(r.run.key);t?t.push(r):o.set(r.run.key,[r])}return[...o.entries()].map(([r,t])=>{t.sort((a,c)=>(a.step??0)-(c.step??0)||a.at-c.at);const s=aiTotalsOf(t);return{key:r,from:t[0].run.from,calls:t,at:s.first,last:s.last,totals:s}}).sort((r,t)=>n?r.at-t.at:t.last-r.last)}i(aiRunsOf,"aiRunsOf"),l(aiRunsOf,"aiRunsOf"),f(aiRunsOf,"aiRunsOf");const k="(none)";function u(e,n){if(n==="agent")return e.agent;if(n==="action")return e.action??{key:"action:",name:"(no action)"};if(n==="run")return{key:e.run.key,name:e.agent.name};if(n==="thread")return e.thread?{key:e.thread.key,name:`thread ${e.thread.name}`}:{key:"thread:",name:"(no thread)"};if(n==="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(n==="model")return{key:`model:${e.model??""}`,name:e.model??"(unknown model)"};if(n==="service")return{key:`service:${e.service}`,name:e.service};const o=n.slice(5),r=e.meta?.[o];return{key:`${n}=${r??""}`,name:r??k}}i(u,"f"),l(u,"m"),f(u,"keyOf");export function groupAiCalls(e,n,o){const r=new Map;for(const s of e){const a=u(s,n),c=r.get(a.key);c?c.rows.push(s):r.set(a.key,{...a,rows:[s]})}const t=n==="agent"||n==="action";return[...r.values()].map(s=>({key:s.key,name:s.name,...s.from?{from:s.from}:{},nameable:t&&/^(agent|action):./.test(s.key),merged:o?Object.entries(o.merge).filter(([,a])=>a===s.key).map(([a])=>a).sort():[],runs:aiRunsOf(s.rows,n==="flow"),totals:aiTotalsOf(s.rows)})).sort((s,a)=>a.totals.last-s.totals.last||s.name.localeCompare(a.name))}i(groupAiCalls,"groupAiCalls"),l(groupAiCalls,"groupAiCalls"),f(groupAiCalls,"groupAiCalls");export function matchesAi(e,n){const o=n.toLowerCase().split(/\s+/).filter(Boolean);if(!o.length)return!0;const r=[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(([t,s])=>`${t}:${s}`)].filter(Boolean).join(`
2
- `).toLowerCase();return o.every(t=>r.includes(t))}i(matchesAi,"matchesAi"),l(matchesAi,"matchesAi"),f(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");
@@ -1,3 +1,3 @@
1
- "use strict";var B=Object.defineProperty;var m=(e,a)=>B(e,"name",{value:a,configurable:!0});var S=Object.defineProperty,d=m((e,a)=>S(e,"name",{value:a,configurable:!0}),"m"),T=Object.defineProperty,c=d((e,a)=>T(e,"name",{value:a,configurable:!0}),"d");import{aiCallOf as z}from"./ai-call.js";import{aiContextOf as E,aiSplitOf as K}from"./ai-context.js";export function aiCallCacheOf(e){return{mode:e.mode,...e.modeSaid?{modeSaid:!0}:{},ttl:e.ttl,...e.ttlSaid?{ttlSaid:!0}:{},...e.key?{key:!0}:{},breakpoints:e.breakpoints.map(a=>({at:a.at,tokens:a.tokens,...a.ttl?{ttl:a.ttl}:{},...a.implicit?{implicit:!0}:{}})),...e.writes?{writes:{...e.writes}}:{},...e.marks.length?{marks:e.marks}:{}}}m(aiCallCacheOf,"aiCallCacheOf"),d(aiCallCacheOf,"aiCallCacheOf"),c(aiCallCacheOf,"aiCallCacheOf");export function aiRowOut(e){if(!e.cache?.marks)return e;const{marks:a,...t}=e.cache;return{...e,cache:t}}m(aiRowOut,"aiRowOut"),d(aiRowOut,"aiRowOut"),c(aiRowOut,"aiRowOut");export const EMPTY_AI_NAMES={version:1,names:{},merge:{}};export function aiModelUses(e,a){const t=a.toLowerCase(),s=new Map;for(const n of e){if(n.host.toLowerCase()!==t)continue;const r=n.model??"unknown";let o=s.get(r);o||(o={use:{model:r,calls:0,failed:0,unmetered:0,input:0,cached:0,output:0,costUsd:0,priced:0,agents:0,first:n.at,last:n.at},agents:new Set},s.set(r,o));const i=o.use;n.prewarm?i.prewarms=(i.prewarms??0)+1:i.calls+=1,n.failed&&(i.failed+=1),n.tokens?(i.input+=n.tokens.input??0,i.cached+=n.tokens.cached??0,i.output+=n.tokens.output??0):i.unmetered+=1,n.costUsd!==void 0&&(i.costUsd+=n.costUsd,i.priced+=1),o.agents.add(n.agent.key),i.first=Math.min(i.first,n.at),i.last=Math.max(i.last,n.at)}return[...s.values()].map(({use:n,agents:r})=>({...n,agents:r.size})).sort((n,r)=>r.calls-n.calls||r.last-n.last)}m(aiModelUses,"aiModelUses"),d(aiModelUses,"aiModelUses"),c(aiModelUses,"aiModelUses");export function aiAgentUses(e,a){const t=a?.toLowerCase(),s=new Map;for(const n of e){if(t!==void 0&&n.host.toLowerCase()!==t)continue;let r=s.get(n.agent.key);r||(r={use:{key:n.agent.key,name:n.agent.name,from:n.agent.from,calls:0,runs:0,failed:0,input:0,cached:0,written:0,output:0,costUsd:0,priced:0,split:{},models:[],last:n.at},runs:new Set,models:new Map},s.set(n.agent.key,r));const o=r.use;n.prewarm?o.prewarms=(o.prewarms??0)+1:(o.calls+=1,r.runs.add(n.run.key)),n.failed&&(o.failed+=1),o.input+=n.tokens?.input??0,o.cached+=n.tokens?.cached??0,o.written+=n.tokens?.written??0,o.output+=n.tokens?.output??0,n.costUsd!==void 0&&(o.costUsd+=n.costUsd,o.priced+=1);for(const[i,p]of Object.entries(n.split??{}))o.split[i]=(o.split[i]??0)+p;n.model&&r.models.set(n.model,(r.models.get(n.model)??0)+1),o.last=Math.max(o.last,n.at)}return[...s.values()].map(({use:n,runs:r,models:o})=>({...n,runs:r.size,models:[...o].sort((i,p)=>p[1]-i[1]).map(([i])=>i)})).sort((n,r)=>r.input-n.input||r.calls-n.calls)}m(aiAgentUses,"aiAgentUses"),d(aiAgentUses,"aiAgentUses"),c(aiAgentUses,"aiAgentUses");export const MAX_TOOLS=40,MAX_THREAD_CALLS=300,MAX_META=24;const q=160,R="unknown service";export const aiKeyOf=c((e,a)=>`${e}:${a.normalize("NFKD").toLowerCase().replace(/[^a-z0-9:.]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80)||"unnamed"}`,"aiKeyOf");export function humanName(e){const a=e.trim();if(/[A-Z]/.test(a)||/ /.test(a))return a;const t=a.replace(/[-_.]+/g," ").trim();return t?t[0].toUpperCase()+t.slice(1):a}m(humanName,"humanName"),d(humanName,"humanName"),c(humanName,"humanName");const g=c((e,a=q)=>{if(!e)return;const t=e.replace(/\s+/g," ").trim();if(t)return t.length>a?`${t.slice(0,a-1)}\u2026`:t},"line");export function promptTitle(e){const a=e.split(`
2
- `).map(n=>n.trim()).find(Boolean)??"",t=/^#{1,6}\s+(.+)$/.exec(a);if(t){const n=t[1].split(/\s+[—–]\s+|\s+-\s+|:\s/)[0].replace(/[*_`]/g,"").trim();return n?n.slice(0,60):void 0}const s=/^you are (?:an? |the )?(.+?)(?:[.,;:!]|\s+(?:who|that|which|for|in|on|whose|with|and|following|using|working|based|at|to)\b|$)/i.exec(a);if(s){const n=s[1].trim().split(/\s+/);if(n.length>6||/^(?:going|about|given|now|here|responsible|able|allowed|expected|tasked|asked|helping|working|being|not)$/i.test(n[0]))return;const r=n.join(" ");return r[0].toUpperCase()+r.slice(1)}}m(promptTitle,"promptTitle"),d(promptTitle,"promptTitle"),c(promptTitle,"promptTitle");export function promptOpening(e){const a=e.split(`
3
- `).map(s=>s.trim()).find(Boolean);if(!a)return;const t=a.replace(/^[#>*\s-]+/,"").split(/\s+/).filter(Boolean);if(!(t.length<3))return t.length>7?`${t.slice(0,7).join(" ")} \u2026`:t.join(" ")}m(promptOpening,"promptOpening"),d(promptOpening,"promptOpening"),c(promptOpening,"promptOpening");export function actionName(e){const a=e.split("::")[0],t=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|[0-9a-f]{8,}|\d{4,})$/i;return a.split(":").map(s=>s.split(".").filter(n=>!t.test(n)).join(".")).filter((s,n,r)=>s||n<r.length-1).join(":").slice(0,120)}m(actionName,"actionName"),d(actionName,"actionName"),c(actionName,"actionName");const h=c((e,a)=>{const t=e.request.headers.find(([s])=>s.toLowerCase()===a)?.[1];if(t===void 0||!a.startsWith("x-lensmcp-")||!t.includes("%"))return t;try{return decodeURIComponent(t)}catch{return t}},"header"),_=c(e=>e!==void 0&&/^\d{1,6}$/.test(e.trim())?Number(e.trim()):void 0,"intOf"),k=c((e,...a)=>{for(const t of a)if(e[t]?.trim())return e[t].trim()},"first");function b(e){const a={};for(const t of e.settings)if(t.name.startsWith("metadata.")){if(Object.keys(a).length>=MAX_META)break;a[t.name.slice(9)]=t.value.slice(0,200)}return a}m(b,"j"),d(b,"T"),c(b,"metaOf");function O(e,a,t){const s=c((f,w)=>({key:aiKeyOf("agent",f),name:humanName(f),from:w}),"named"),n=k(t,"agent","agent_name","agentName","assistant");if(n)return s(n,"metadata");const r=h(e,"x-lensmcp-agent");if(r?.trim())return s(r.trim(),"header");const o=a.system.map(f=>promptTitle(f.text)).find(Boolean);if(o)return s(o,"prompt");const i=a.answer.format?.name;if(i)return s(i,"schema");const p=[...a.tools,...a.answer.toolCalls].map(f=>f.server).find(Boolean);if(p)return s(p,"tools");const l=a.system.map(f=>promptOpening(f.text)).find(Boolean);return l?{key:aiKeyOf("agent",`prompt ${l.replace(/ …$/,"")}`),name:l,from:"prompt"}:s(`${e.service??R} ${a.api==="embeddings"?"embeddings":a.model??a.api}`,"service")}m(O,"U"),d(O,"B"),c(O,"agentOf");function $(e,a,t){const s=c((o,i)=>({key:aiKeyOf("action",o),name:o,from:i}),"named"),n=k(t,"act","action","task","step","operation");if(n&&actionName(n))return s(actionName(n),"metadata");const r=h(e,"x-lensmcp-action");if(r?.trim())return s(actionName(r.trim()),"header");if(a.answer.format?.name)return s(a.answer.format.name,"schema")}m($,"_"),d($,"E"),c($,"actionOf");function C(e){if(e.kind==="message")return g(e.text);if(e.kind==="tool")return g(e.output!==void 0?`${e.tool} \u2192 ${e.output}`:`${e.tool}(${e.arguments})`)}m(C,"N"),d(C,"x"),c(C,"turnLine");function y(e){const a=e.answer;return a.error?g(`error: ${a.error}`):a.refusal?g(`refused: ${a.refusal}`):a.toolCalls.length?g(a.toolCalls.map(t=>`${t.tool}(${t.arguments})`).join(" \xB7 ")):e.embedding?`${e.embedding.vectors??e.embedding.count} vector${(e.embedding.vectors??e.embedding.count)===1?"":"s"}${e.embedding.dimensions?` \xD7 ${e.embedding.dimensions}`:""}`:g(a.text)}m(y,"v"),d(y,"_"),c(y,"saidLine");export function aiCallRow(e,a){const t=z(e);if(!t||!e.ai)return;const s=b(t),n=new Map(t.settings.map(u=>[u.name,u.value])),r=k(s,"run","run_id","runId"),o=h(e,"x-lensmcp-run")?.trim(),i=t.turns.filter(u=>u.kind==="tool").filter(u=>u.output!==void 0&&u.callId).map(u=>u.callId),p=t.answer.toolCalls.map(u=>u.callId).filter(u=>!!u),l=t.usage,f=l?{...l.input!==void 0?{input:l.input}:{},...l.cached?{cached:l.cached}:{},...l.written?{written:l.written}:{},...l.output!==void 0?{output:l.output}:{},...l.reasoning?{reasoning:l.reasoning}:{}}:void 0,w=t.shape==="embedding"||l?.input===void 0?{}:K(E(t,{sections:!1})),v=k(s,"thread","thread_id","threadId","conversation","conversation_id","conversationId","case","case_id","caseId"),x=h(e,"x-lensmcp-thread")?.trim(),I=k(s,"parent_run","parentRun","parent")??h(e,"x-lensmcp-parent")?.trim(),M=$(e,t,s),A=_(s.round),j=_(s.attempt),U=n.get("continues response"),N=[...t.turns].reverse().map(C).find(Boolean),L=t.answer.status==="failed"||!!t.answer.error||(e.status??0)>=400||!!e.error;return{id:e.id,at:e.startedAt,...e.durationMs!==void 0?{durationMs:e.durationMs}:{},...e.status!==void 0?{status:e.status}:{},...L?{failed:!0}:{},service:e.service??R,...e.flowId?{flowId:e.flowId}:{},...e.requestId?{requestId:e.requestId}:{},provider:e.ai.provider,host:e.host,api:t.api,shape:t.shape,...t.model?{model:t.model}:{},...e.response.stream?{streamed:!0}:{},...f&&Object.keys(f).length?{tokens:f}:{},...Object.keys(w).length?{split:w}:{},...t.cache?.prewarm?{prewarm:!0}:{},...t.cache?{cache:aiCallCacheOf(t.cache)}:{},agent:O(e,t,s),run:r?{key:`run:${r}`,from:"metadata"}:o?{key:`run:${o}`,from:"header"}:{key:`run:${e.id}`,from:"alone"},...v?{thread:{key:`thread:${v}`,name:v,from:"metadata"}}:x?{thread:{key:`thread:${x}`,name:x,from:"header"}}:{},...I?{parent:`run:${I}`}:{},...A!==void 0?{round:A}:{},...j!==void 0?{attempt:j}:{},...M?{action:M}:{},...t.answer.format?.name?{schema:t.answer.format.name}:{},...t.tools.length?{tools:t.tools.slice(0,MAX_TOOLS).map(u=>u.name)}:{},...t.answer.toolCalls.length?{called:t.answer.toolCalls.map(u=>u.name)}:{},...p.length?{callIds:p}:{},...i.length?{answers:i}:{},...t.responseId?{responseId:t.responseId}:{},...U?{previousResponseId:U}:{},...Object.keys(s).length?{meta:s}:{},...t.gaps.some(u=>/kept to its first|cut/.test(u))?{cut:!0}:{},...a.content&&N?{asked:N}:{},...a.content&&y(t)?{said:y(t)}:{}}}m(aiCallRow,"aiCallRow"),d(aiCallRow,"aiCallRow"),c(aiCallRow,"aiCallRow");export function linkAiRuns(e){const a=[...e].sort((r,o)=>r.at-o.at||r.id.localeCompare(o.id)),t=new Map,s=new Map;for(const r of a){if(r.run.from==="alone"){const o=r.previousResponseId?t.get(r.previousResponseId):void 0,i=o?void 0:r.answers?.map(l=>s.get(l)).find(Boolean),p=o??i;if(p){const l=o?"chain":"tools";r.run={key:p.run.key,from:p.run.from==="alone"||p.run.from===l?l:p.run.from},p.run.from==="alone"&&(p.run={key:p.run.key,from:l})}}r.responseId&&t.set(r.responseId,r);for(const o of r.callIds??[])s.set(o,r)}const n=new Map;for(const r of a){const o=(n.get(r.run.key)??0)+1;n.set(r.run.key,o),r.step=o}return e}m(linkAiRuns,"linkAiRuns"),d(linkAiRuns,"linkAiRuns"),c(linkAiRuns,"linkAiRuns");export function mergedKey(e,a){let t=a;for(let s=0;s<8&&e.merge[t]&&e.merge[t]!==a;s++)t=e.merge[t];return t}m(mergedKey,"mergedKey"),d(mergedKey,"mergedKey"),c(mergedKey,"mergedKey");export function applyAiNames(e,a){if(!Object.keys(a.names).length&&!Object.keys(a.merge).length)return e;const t=new Map;for(const n of e)t.has(n.agent.key)||t.set(n.agent.key,n.agent),n.action&&!t.has(n.action.key)&&t.set(n.action.key,n.action);const s=c(n=>{const r=mergedKey(a,n.key),o=a.names[r];if(o)return{key:r,name:o,from:"renamed"};if(r===n.key)return n;const i=t.get(r);return{key:r,name:i?.name??humanName(r.replace(/^[a-z]+:/,"")),from:i?.from??n.from}},"resolve");for(const n of e)n.agent=s(n.agent),n.action&&(n.action=s(n.action));return e}m(applyAiNames,"applyAiNames"),d(applyAiNames,"applyAiNames"),c(applyAiNames,"applyAiNames");export function aiNamesOf(e){const a=e&&typeof e=="object"?e:{},t=c(s=>{const n={};if(s&&typeof s=="object"&&!Array.isArray(s))for(const[r,o]of Object.entries(s))/^(agent|action):/.test(r)&&typeof o=="string"&&o.trim()&&(n[r]=o.trim().slice(0,120));return n},"pick");return{version:1,names:t(a.names),merge:t(a.merge)}}m(aiNamesOf,"aiNamesOf"),d(aiNamesOf,"aiNamesOf"),c(aiNamesOf,"aiNamesOf");
1
+ "use strict";var L=Object.defineProperty;var m=(t,o)=>L(t,"name",{value:o,configurable:!0});var S=Object.defineProperty,c=m((t,o)=>S(t,"name",{value:o,configurable:!0}),"d");import{aiCallOf as B}from"./ai-call.js";import{aiContextOf as T,aiSplitOf as z}from"./ai-context.js";export function aiCallCacheOf(t){return{mode:t.mode,...t.modeSaid?{modeSaid:!0}:{},ttl:t.ttl,...t.ttlSaid?{ttlSaid:!0}:{},...t.key?{key:!0}:{},breakpoints:t.breakpoints.map(o=>({at:o.at,tokens:o.tokens,...o.ttl?{ttl:o.ttl}:{},...o.implicit?{implicit:!0}:{}})),...t.writes?{writes:{...t.writes}}:{},...t.marks.length?{marks:t.marks}:{}}}m(aiCallCacheOf,"aiCallCacheOf"),c(aiCallCacheOf,"aiCallCacheOf");export function aiRowOut(t){if(!t.cache?.marks)return t;const{marks:o,...e}=t.cache;return{...t,cache:e}}m(aiRowOut,"aiRowOut"),c(aiRowOut,"aiRowOut");export const EMPTY_AI_NAMES={version:1,names:{},merge:{}};export function aiModelUses(t,o){const e=o.toLowerCase(),a=new Map;for(const n of t){if(n.host.toLowerCase()!==e)continue;const s=n.model??"unknown";let r=a.get(s);r||(r={use:{model:s,calls:0,failed:0,unmetered:0,input:0,cached:0,output:0,costUsd:0,priced:0,agents:0,first:n.at,last:n.at},agents:new Set},a.set(s,r));const i=r.use;n.prewarm?i.prewarms=(i.prewarms??0)+1:i.calls+=1,n.failed&&(i.failed+=1),n.tokens?(i.input+=n.tokens.input??0,i.cached+=n.tokens.cached??0,i.output+=n.tokens.output??0):i.unmetered+=1,n.costUsd!==void 0&&(i.costUsd+=n.costUsd,i.priced+=1),r.agents.add(n.agent.key),i.first=Math.min(i.first,n.at),i.last=Math.max(i.last,n.at)}return[...a.values()].map(({use:n,agents:s})=>({...n,agents:s.size})).sort((n,s)=>s.calls-n.calls||s.last-n.last)}m(aiModelUses,"aiModelUses"),c(aiModelUses,"aiModelUses");export function aiAgentUses(t,o){const e=o?.toLowerCase(),a=new Map;for(const n of t){if(e!==void 0&&n.host.toLowerCase()!==e)continue;let s=a.get(n.agent.key);s||(s={use:{key:n.agent.key,name:n.agent.name,from:n.agent.from,calls:0,runs:0,failed:0,input:0,cached:0,written:0,output:0,costUsd:0,priced:0,split:{},models:[],last:n.at},runs:new Set,models:new Map},a.set(n.agent.key,s));const r=s.use;n.prewarm?r.prewarms=(r.prewarms??0)+1:(r.calls+=1,s.runs.add(n.run.key)),n.failed&&(r.failed+=1),r.input+=n.tokens?.input??0,r.cached+=n.tokens?.cached??0,r.written+=n.tokens?.written??0,r.output+=n.tokens?.output??0,n.costUsd!==void 0&&(r.costUsd+=n.costUsd,r.priced+=1);for(const[i,u]of Object.entries(n.split??{}))r.split[i]=(r.split[i]??0)+u;n.model&&s.models.set(n.model,(s.models.get(n.model)??0)+1),r.last=Math.max(r.last,n.at)}return[...a.values()].map(({use:n,runs:s,models:r})=>({...n,runs:s.size,models:[...r].sort((i,u)=>u[1]-i[1]).map(([i])=>i)})).sort((n,s)=>s.input-n.input||s.calls-n.calls)}m(aiAgentUses,"aiAgentUses"),c(aiAgentUses,"aiAgentUses");export const MAX_TOOLS=40,MAX_THREAD_CALLS=300,MAX_META=24;const E=160,M="unknown service";export const aiKeyOf=c((t,o)=>`${t}:${o.normalize("NFKD").toLowerCase().replace(/[^a-z0-9:.]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80)||"unnamed"}`,"aiKeyOf");export function humanName(t){const o=t.trim();if(/[A-Z]/.test(o)||/ /.test(o))return o;const e=o.replace(/[-_.]+/g," ").trim();return e?e[0].toUpperCase()+e.slice(1):o}m(humanName,"humanName"),c(humanName,"humanName");const f=c((t,o=E)=>{if(!t)return;const e=t.replace(/\s+/g," ").trim();if(e)return e.length>o?`${e.slice(0,o-1)}\u2026`:e},"line");export function promptTitle(t){const o=t.split(`
2
+ `).map(n=>n.trim()).find(Boolean)??"",e=/^#{1,6}\s+(.+)$/.exec(o);if(e){const n=e[1].split(/\s+[—–]\s+|\s+-\s+|:\s/)[0].replace(/[*_`]/g,"").trim();return n?n.slice(0,60):void 0}const a=/^you are (?:an? |the )?(.+?)(?:[.,;:!]|\s+(?:who|that|which|for|in|on|whose|with|and|following|using|working|based|at|to)\b|$)/i.exec(o);if(a){const n=a[1].trim().split(/\s+/);if(n.length>6||/^(?:going|about|given|now|here|responsible|able|allowed|expected|tasked|asked|helping|working|being|not)$/i.test(n[0]))return;const s=n.join(" ");return s[0].toUpperCase()+s.slice(1)}}m(promptTitle,"promptTitle"),c(promptTitle,"promptTitle");export function promptOpening(t){const o=t.split(`
3
+ `).map(a=>a.trim()).find(Boolean);if(!o)return;const e=o.replace(/^[#>*\s-]+/,"").split(/\s+/).filter(Boolean);if(!(e.length<3))return e.length>7?`${e.slice(0,7).join(" ")} \u2026`:e.join(" ")}m(promptOpening,"promptOpening"),c(promptOpening,"promptOpening");export function actionName(t){const o=t.split("::")[0],e=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|[0-9a-f]{8,}|\d{4,})$/i;return o.split(":").map(a=>a.split(".").filter(n=>!e.test(n)).join(".")).filter((a,n,s)=>a||n<s.length-1).join(":").slice(0,120)}m(actionName,"actionName"),c(actionName,"actionName");const g=c((t,o)=>{const e=t.request.headers.find(([a])=>a.toLowerCase()===o)?.[1];if(e===void 0||!o.startsWith("x-lensmcp-")||!e.includes("%"))return e;try{return decodeURIComponent(e)}catch{return e}},"header"),A=c(t=>t!==void 0&&/^\d{1,6}$/.test(t.trim())?Number(t.trim()):void 0,"intOf"),h=c((t,...o)=>{for(const e of o)if(t[e]?.trim())return t[e].trim()},"first");function j(t){const o={};for(const e of t.settings)if(e.name.startsWith("metadata.")){if(Object.keys(o).length>=MAX_META)break;o[e.name.slice(9)]=e.value.slice(0,200)}return o}m(j,"T"),c(j,"metaOf");function U(t,o,e){const a=c((p,k)=>({key:aiKeyOf("agent",p),name:humanName(p),from:k}),"named"),n=h(e,"agent","agent_name","agentName","assistant");if(n)return a(n,"metadata");const s=g(t,"x-lensmcp-agent");if(s?.trim())return a(s.trim(),"header");const r=o.system.map(p=>promptTitle(p.text)).find(Boolean);if(r)return a(r,"prompt");const i=o.answer.format?.name;if(i)return a(i,"schema");const u=[...o.tools,...o.answer.toolCalls].map(p=>p.server).find(Boolean);if(u)return a(u,"tools");const l=o.system.map(p=>promptOpening(p.text)).find(Boolean);return l?{key:aiKeyOf("agent",`prompt ${l.replace(/ …$/,"")}`),name:l,from:"prompt"}:a(`${t.service??M} ${o.api==="embeddings"?"embeddings":o.model??o.api}`,"service")}m(U,"B"),c(U,"agentOf");function _(t,o,e){const a=c((r,i)=>({key:aiKeyOf("action",r),name:r,from:i}),"named"),n=h(e,"act","action","task","step","operation");if(n&&actionName(n))return a(actionName(n),"metadata");const s=g(t,"x-lensmcp-action");if(s?.trim())return a(actionName(s.trim()),"header");if(o.answer.format?.name)return a(o.answer.format.name,"schema")}m(_,"E"),c(_,"actionOf");function N(t){if(t.kind==="message")return f(t.text);if(t.kind==="tool")return f(t.output!==void 0?`${t.tool} \u2192 ${t.output}`:`${t.tool}(${t.arguments})`)}m(N,"x"),c(N,"turnLine");function v(t){const o=t.answer;return o.error?f(`error: ${o.error}`):o.refusal?f(`refused: ${o.refusal}`):o.toolCalls.length?f(o.toolCalls.map(e=>`${e.tool}(${e.arguments})`).join(" \xB7 ")):t.embedding?`${t.embedding.vectors??t.embedding.count} vector${(t.embedding.vectors??t.embedding.count)===1?"":"s"}${t.embedding.dimensions?` \xD7 ${t.embedding.dimensions}`:""}`:f(o.text)}m(v,"_"),c(v,"saidLine");export function aiCallRow(t,o){const e=B(t);if(!e||!t.ai)return;const a=j(e),n=new Map(e.settings.map(d=>[d.name,d.value])),s=h(a,"run","run_id","runId"),r=g(t,"x-lensmcp-run")?.trim(),i=e.turns.filter(d=>d.kind==="tool").filter(d=>d.output!==void 0&&d.callId).map(d=>d.callId),u=e.answer.toolCalls.map(d=>d.callId).filter(d=>!!d),l=e.usage,p=l?{...l.input!==void 0?{input:l.input}:{},...l.cached?{cached:l.cached}:{},...l.written?{written:l.written}:{},...l.output!==void 0?{output:l.output}:{},...l.reasoning?{reasoning:l.reasoning}:{}}:void 0,k=e.shape==="embedding"||l?.input===void 0?{}:z(T(e,{sections:!1})),w=h(a,"thread","thread_id","threadId","conversation","conversation_id","conversationId","case","case_id","caseId"),y=g(t,"x-lensmcp-thread")?.trim(),x=h(a,"parent_run","parentRun","parent")??g(t,"x-lensmcp-parent")?.trim(),b=_(t,e,a),$=A(a.round),O=A(a.attempt),C=n.get("continues response"),I=[...e.turns].reverse().map(N).find(Boolean),R=e.answer.status==="failed"||!!e.answer.error||(t.status??0)>=400||!!t.error;return{id:t.id,at:t.startedAt,...t.durationMs!==void 0?{durationMs:t.durationMs}:{},...t.status!==void 0?{status:t.status}:{},...R?{failed:!0}:{},service:t.service??M,...t.flowId?{flowId:t.flowId}:{},...t.requestId?{requestId:t.requestId}:{},provider:t.ai.provider,host:t.host,api:e.api,shape:e.shape,...e.model?{model:e.model}:{},...t.response.stream?{streamed:!0}:{},...p&&Object.keys(p).length?{tokens:p}:{},...Object.keys(k).length?{split:k}:{},...e.cache?.prewarm?{prewarm:!0}:{},...e.cache?{cache:aiCallCacheOf(e.cache)}:{},agent:U(t,e,a),run:s?{key:`run:${s}`,from:"metadata"}:r?{key:`run:${r}`,from:"header"}:{key:`run:${t.id}`,from:"alone"},...w?{thread:{key:`thread:${w}`,name:w,from:"metadata"}}:y?{thread:{key:`thread:${y}`,name:y,from:"header"}}:{},...x?{parent:`run:${x}`}:{},...$!==void 0?{round:$}:{},...O!==void 0?{attempt:O}:{},...b?{action:b}:{},...e.answer.format?.name?{schema:e.answer.format.name}:{},...e.tools.length?{tools:e.tools.slice(0,MAX_TOOLS).map(d=>d.name)}:{},...e.answer.toolCalls.length?{called:e.answer.toolCalls.map(d=>d.name)}:{},...u.length?{callIds:u}:{},...i.length?{answers:i}:{},...e.responseId?{responseId:e.responseId}:{},...C?{previousResponseId:C}:{},...Object.keys(a).length?{meta:a}:{},...e.gaps.some(d=>/kept to its first|cut/.test(d))?{cut:!0}:{},...o.content&&I?{asked:I}:{},...o.content&&v(e)?{said:v(e)}:{}}}m(aiCallRow,"aiCallRow"),c(aiCallRow,"aiCallRow");export function linkAiRuns(t){const o=[...t].sort((s,r)=>s.at-r.at||s.id.localeCompare(r.id)),e=new Map,a=new Map;for(const s of o){if(s.run.from==="alone"){const r=s.previousResponseId?e.get(s.previousResponseId):void 0,i=r?void 0:s.answers?.map(l=>a.get(l)).find(Boolean),u=r??i;if(u){const l=r?"chain":"tools";s.run={key:u.run.key,from:u.run.from==="alone"||u.run.from===l?l:u.run.from},u.run.from==="alone"&&(u.run={key:u.run.key,from:l})}}s.responseId&&e.set(s.responseId,s);for(const r of s.callIds??[])a.set(r,s)}const n=new Map;for(const s of o){const r=(n.get(s.run.key)??0)+1;n.set(s.run.key,r),s.step=r}return t}m(linkAiRuns,"linkAiRuns"),c(linkAiRuns,"linkAiRuns");export function mergedKey(t,o){let e=o;for(let a=0;a<8&&t.merge[e]&&t.merge[e]!==o;a++)e=t.merge[e];return e}m(mergedKey,"mergedKey"),c(mergedKey,"mergedKey");export function applyAiNames(t,o){if(!Object.keys(o.names).length&&!Object.keys(o.merge).length)return t;const e=new Map;for(const n of t)e.has(n.agent.key)||e.set(n.agent.key,n.agent),n.action&&!e.has(n.action.key)&&e.set(n.action.key,n.action);const a=c(n=>{const s=mergedKey(o,n.key),r=o.names[s];if(r)return{key:s,name:r,from:"renamed"};if(s===n.key)return n;const i=e.get(s);return{key:s,name:i?.name??humanName(s.replace(/^[a-z]+:/,"")),from:i?.from??n.from}},"resolve");for(const n of t)n.agent=a(n.agent),n.action&&(n.action=a(n.action));return t}m(applyAiNames,"applyAiNames"),c(applyAiNames,"applyAiNames");export function aiNamesOf(t){const o=t&&typeof t=="object"?t:{},e=c(a=>{const n={};if(a&&typeof a=="object"&&!Array.isArray(a))for(const[s,r]of Object.entries(a))/^(agent|action):/.test(s)&&typeof r=="string"&&r.trim()&&(n[s]=r.trim().slice(0,120));return n},"pick");return{version:1,names:e(o.names),merge:e(o.merge)}}m(aiNamesOf,"aiNamesOf"),c(aiNamesOf,"aiNamesOf");