@lensmcp/protocol-types 1.26.27 → 1.26.29

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/lib/ai-cache-facts.js +1 -1
  2. package/lib/ai-cache-verdict.js +1 -1
  3. package/lib/ai-cache.js +3 -3
  4. package/lib/ai-call-groups.js +2 -2
  5. package/lib/ai-call-row.js +3 -3
  6. package/lib/ai-call.js +9 -9
  7. package/lib/ai-compare.js +3 -3
  8. package/lib/ai-context.js +6 -6
  9. package/lib/ai-origins.js +9 -9
  10. package/lib/ai-together.js +5 -5
  11. package/lib/bounded-clone.js +1 -1
  12. package/lib/bounded-map.js +1 -1
  13. package/lib/bounded-writer.js +1 -1
  14. package/lib/canvas-attachments.js +1 -1
  15. package/lib/canvas-catalog.js +3 -3
  16. package/lib/canvas-chat.d.ts +16 -0
  17. package/lib/canvas-chat.js +2 -2
  18. package/lib/canvas-editing.js +4 -4
  19. package/lib/canvas-frame-policy.js +1 -1
  20. package/lib/canvas-hub.js +1 -1
  21. package/lib/canvas.d.ts +77 -1
  22. package/lib/canvas.js +1 -1
  23. package/lib/capture-demand.js +1 -1
  24. package/lib/dashboard-path.js +1 -1
  25. package/lib/docker-errors.js +1 -1
  26. package/lib/docker-jobs.js +1 -1
  27. package/lib/docker-report.js +2 -2
  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.d.ts +24 -0
  37. package/lib/goal-design.js +1 -1
  38. package/lib/host-agents.js +1 -1
  39. package/lib/lens-hosts.js +1 -1
  40. package/lib/lint-coverage.js +1 -1
  41. package/lib/lint-ignores.js +2 -2
  42. package/lib/log-query.js +1 -1
  43. package/lib/metrics-reset.js +1 -1
  44. package/lib/overseer-findings.js +1 -1
  45. package/lib/peers.js +1 -1
  46. package/lib/perf-rules.js +1 -1
  47. package/lib/pod-memory.js +1 -1
  48. package/lib/producer-health.js +1 -1
  49. package/lib/remote-instances.js +1 -1
  50. package/lib/sources.js +1 -1
  51. package/lib/static-checks.js +1 -1
  52. package/lib/system-report.js +1 -1
  53. package/lib/team.js +1 -1
  54. package/package.json +1 -1
@@ -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 Ct=Object.defineProperty;var F=(e,s)=>Ct(e,"name",{value:s,configurable:!0});var It=Object.defineProperty,R=F((e,s)=>It(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 it,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,a)=>n.at-a.at||n.id.localeCompare(a.id));for(const[n,a]of dt(d,s,g))h.set(n,a)}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,"Ut"),k(ot,"factsOf");function dt(e,s,g){const h=[],u=new Map,d=new Map;e.forEach((n,a)=>{const o=n.cache,$=n.at,x=n.durationMs!==void 0?n.at+n.durationMs:void 0,I=it[o.ttl],r={row:n,start:$,...x!==void 0?{end:x}:{},ttlMs:I,wrote:[]};h.push(r);const i=o.marks??[],w=i.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 i){const l=d.get(t.h);l?l.push(a):d.set(t.h,[a])}},"remember"),at=k((t,l)=>{const p=u.get(t);p?p.push({i:a,how:l}):u.set(t,[{i:a,how:l}])},"hold"),Y=Et(n.provider,n.model);if(!v){if(!n.failed)for(const t of w)at(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.":n.noUsage?`${n.noUsage.said} No verdict.`:"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 L=tt(o,A,Y,X);if(L){const t=et(r,h,d,a);if(t&&t.tokens>=Y&&c){const l=c.cacheRead??c.input,p=t.tokens*(c.input-l)/1e6;L.costs.push({kind:"no-cache",tokens:t.tokens,usd:S(p),arithmetic:`${M(t.tokens)} \xD7 (${_(c.input)} \u2212 ${_(l)})/M`,estimate:!0}),L.lostUsd=S(p),L.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&&(L.prewarm=!0),r.verdict=L,nt();return}const N=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:i);t&&Math.abs(t.t-m)<=Math.max(N,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+N)&&at(t.h,"read"));const ct=w.filter((t,l)=>j>=0?l>j:t.t>m+N),bt=j>=0?w[j].t:m;let D=f>0?ct.filter(t=>t.t<=bt+f+Math.max(N,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(C=>Math.abs(C.tokens-t.t)<=1)?.ttl??o.ttl,T=it[b],V=(u.get(t.h)??[]).filter(C=>C.i<a),W=V.filter(C=>$-h[C.i].start<=T);if(W.length){const C=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(C))??q(kt.filter(C)),$t=q(mt.filter(B=>!C(B)))??q(kt.filter(B=>!C(B))),At=gt??$t??q(W),yt=!gt&&!!$t,Ut=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:Ut})}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"});at(t.h,"wrote")});const y=et(r,h,d,a);nt();const z=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>N){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-N,T=c?b?lt-z:c.input-z: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 ${_(z)})/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-z)/1e6),arithmetic:`${M(t.tokens)} \xD7 (${_(l)} \u2212 ${_(z)})/M`}:{}})}const U=[];r.wrote.some(t=>t.status==="duplicate")&&U.push("duplicate-write"),Z&&U.push("broken-prefix"),r.wrote.some(t=>t.status==="cold")&&U.push("cold"),r.wrote.some(t=>t.status==="first")&&U.push("first-writer"),m>0&&U.push("read"),U.length||U.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-z)/1e6):void 0,Mt=U[0];r.verdict={kind:Mt,...U.length>1?{also:U.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 a=n.verdict;if(!n.wrote.length){a.said=st(n,a);continue}const o=new Set,$=new Set;let x=!1;const I=[];for(const r of n.wrote){const i=it[r.ttl],w=(u.get(r.h)??[]).filter(f=>h[f.i].start>n.start&&h[f.i].start-n.start<=i),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+i>g?x=!0:!A.length&&!m.length&&I.push(r)}for(const r of o)$.delete(r);if(o.size&&(a.readBy=o.size),$.size&&(a.maybeReadBy=$.size),x&&(a.open=!0),I.length){const r=n.row,i=r.model?s(r.model,r.tokens?.input??0):void 0;let w=a.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 Q=i?K(i,r.cache.writes,v.ttl):void 0;a.costs.push({kind:"write-nothing-read",tokens:c,estimate:v.estimate||c!==v.tokens,...i?{usd:S(c*(Q-i.input)/1e6),arithmetic:`${M(c)} \xD7 (${_(Q)} \u2212 ${_(i.input)})/M`}:{}})}i&&(a.lostUsd=S(a.costs.reduce((v,c)=>v+(c.usd??0),0)));const A=[a.kind,...a.also??[]],m=A.findIndex(v=>v!=="duplicate-write"&&v!=="broken-prefix"&&v!=="cold");A.splice(m<0?A.length:m,0,"write-nothing-read"),a.kind=A[0];const f=A.slice(1);f.length?a.also=f:delete a.also}a.said=st(n,a)}return new Map(h.map(n=>[n.row.id,n.verdict]))}F(dt,"$t"),R(dt,"It"),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,[,a])=>n+a,0);return h.reduce((n,[a,o])=>n+(e.writes[a]??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 a=0;a<u.length;a++){const o=g.get(u[a].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:a};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(a=>a.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,a=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, ${a}).`);const x=e.wrote.find(i=>i.status==="duplicate");if(x&&s.against){const i=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: ${i.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(i.gapMs)} after it.${w}`:x.against?.how==="read"?`Duplicate write: ${i.id} had read the same prefix (to the end of \xAB${H(x.s)}\xBB) ${G(i.gapMs)} before \u2014 the entry was there, and this call did not read it.`:`Duplicate write: ${i.id}${i.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(i.gapMs)} before${i.ended!==void 0&&i.ended<=e.start?` and had ended ${G(e.start-i.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 I=e.wrote.find(i=>i.status==="cold");I&&s.idleMs!==void 0&&o.push(`Cold: the same prefix (to the end of \xAB${H(I.s)}\xBB) was last used ${G(s.idleMs)} before \u2014 past its ${I.ttl} lifetime.`);const r=e.wrote.filter(i=>i.status==="first");return r.length&&o.push(`First writer of the prefix to the end of \xAB${r.map(i=>H(i.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(i=>i.arithmetic).map(i=>`${i.arithmetic}${i.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 It=Object.defineProperty,k=F((e,o)=>It(e,"name",{value:o,configurable:!0}),"w");import{AI_CACHE_TTL_MS as et,AI_GUIDANCE_SOURCES as kt,aiCacheMinTokens as Ut,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,"Ut"),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,U=et[n.ttl],a={row:i,start:$,...x!==void 0?{end:x}:{},ttlMs:U,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=Ut(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.":i.noUsage?`${i.noUsage.said} No verdict.`:"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 N=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(N,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+N)&&tt(t.h,"read"));const at=w.filter((t,u)=>S>=0?u>S:t.t>m+N),vt=S>=0?w[S].t:m;let D=f>0?at.filter(t=>t.t<=vt+f+Math.max(N,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(I=>Math.abs(I.tokens-t.t)<=1)?.ttl??n.ttl,L=et[B],T=(l.get(t.h)??[]).filter(I=>I.i<s),W=T.filter(I=>$-h[I.i].start<=L);if(W.length){const I=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(I))??q(pt.filter(I)),mt=q(ft.filter(M=>!I(M)))??q(pt.filter(M=>!I(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 z=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,L)=>Math.max(B,L.t),0),u=Math.max(m,t),p=y.tokens-u;if(y.tokens>=Q&&p>N){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-N,L=c?B?dt-z:c.input-z:void 0;H.push({kind:"broken-prefix",tokens:p,estimate:!0,...L!==void 0?{usd:_(p*L/1e6),arithmetic:`${b(p)} \xD7 (${R(B?dt:c.input)} \u2212 ${R(z)})/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-z)/1e6),arithmetic:`${b(t.tokens)} \xD7 (${R(u)} \u2212 ${R(z)})/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-z)/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 U=[];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&&U.push(a)}for(const a of n)$.delete(a);if(n.size&&(s.readBy=n.size),$.size&&(s.maybeReadBy=$.size),x&&(s.open=!0),U.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 U){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,"It"),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 U=e.wrote.find(r=>r.status==="cold");U&&o.idleMs!==void 0&&n.push(`Cold: the same prefix (to the end of \xAB${G(U.s)}\xBB) was last used ${V(o.idleMs)} before \u2014 past its ${U.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 T=Object.defineProperty;var m=(e,s)=>T(e,"name",{value:s,configurable:!0});var z=Object.defineProperty,d=m((e,s)=>z(e,"name",{value:s,configurable:!0}),"m"),K=Object.defineProperty,c=d((e,s)=>K(e,"name",{value:s,configurable:!0}),"d");import{aiCallOf as q}from"./ai-call.js";import{aiContextOf as E,aiSplitOf as D}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(s=>({at:s.at,tokens:s.tokens,...s.ttl?{ttl:s.ttl}:{},...s.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:s,...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,s){const t=s.toLowerCase(),r=new Map;for(const n of e){if(n.host.toLowerCase()!==t)continue;const a=n.model??"unknown";let o=r.get(a);o||(o={use:{model:a,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},r.set(a,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[...r.values()].map(({use:n,agents:a})=>({...n,agents:a.size})).sort((n,a)=>a.calls-n.calls||a.last-n.last)}m(aiModelUses,"aiModelUses"),d(aiModelUses,"aiModelUses"),c(aiModelUses,"aiModelUses");export function aiAgentUses(e,s){const t=s?.toLowerCase(),r=new Map;for(const n of e){if(t!==void 0&&n.host.toLowerCase()!==t)continue;let a=r.get(n.agent.key);a||(a={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},r.set(n.agent.key,a));const o=a.use;n.prewarm?o.prewarms=(o.prewarms??0)+1:(o.calls+=1,a.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&&a.models.set(n.model,(a.models.get(n.model)??0)+1),o.last=Math.max(o.last,n.at)}return[...r.values()].map(({use:n,runs:a,models:o})=>({...n,runs:a.size,models:[...o].sort((i,p)=>p[1]-i[1]).map(([i])=>i)})).sort((n,a)=>a.input-n.input||a.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 P=160,B="unknown service";export const aiKeyOf=c((e,s)=>`${e}:${s.normalize("NFKD").toLowerCase().replace(/[^a-z0-9:.]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80)||"unnamed"}`,"aiKeyOf");export function humanName(e){const s=e.trim();if(/[A-Z]/.test(s)||/ /.test(s))return s;const t=s.replace(/[-_.]+/g," ").trim();return t?t[0].toUpperCase()+t.slice(1):s}m(humanName,"humanName"),d(humanName,"humanName"),c(humanName,"humanName");const g=c((e,s=P)=>{if(!e)return;const t=e.replace(/\s+/g," ").trim();if(t)return t.length>s?`${t.slice(0,s-1)}\u2026`:t},"line");export function promptTitle(e){const s=e.split(`
2
- `).map(n=>n.trim()).find(Boolean)??"",t=/^#{1,6}\s+(.+)$/.exec(s);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 r=/^you are (?:an? |the )?(.+?)(?:[.,;:!]|\s+(?:who|that|which|for|in|on|whose|with|and|following|using|working|based|at|to)\b|$)/i.exec(s);if(r){const n=r[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 a=n.join(" ");return a[0].toUpperCase()+a.slice(1)}}m(promptTitle,"promptTitle"),d(promptTitle,"promptTitle"),c(promptTitle,"promptTitle");export function promptOpening(e){const s=e.split(`
3
- `).map(r=>r.trim()).find(Boolean);if(!s)return;const t=s.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 s=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 s.split(":").map(r=>r.split(".").filter(n=>!t.test(n)).join(".")).filter((r,n,a)=>r||n<a.length-1).join(":").slice(0,120)}m(actionName,"actionName"),d(actionName,"actionName"),c(actionName,"actionName");const h=c((e,s)=>{const t=e.request.headers.find(([r])=>r.toLowerCase()===s)?.[1];if(t===void 0||!s.startsWith("x-lensmcp-")||!t.includes("%"))return t;try{return decodeURIComponent(t)}catch{return t}},"header"),S=c(e=>e!==void 0&&/^\d{1,6}$/.test(e.trim())?Number(e.trim()):void 0,"intOf"),k=c((e,...s)=>{for(const t of s)if(e[t]?.trim())return e[t].trim()},"first");function x(e){const s={};for(const t of e.settings)if(t.name.startsWith("metadata.")){if(Object.keys(s).length>=MAX_META)break;s[t.name.slice(9)]=t.value.slice(0,200)}return s}m(x,"_"),d(x,"B"),c(x,"metaOf");function O(e,s,t){const r=c((f,w)=>({key:aiKeyOf("agent",f),name:humanName(f),from:w}),"named"),n=k(t,"agent","agent_name","agentName","assistant");if(n)return r(n,"metadata");const a=h(e,"x-lensmcp-agent");if(a?.trim())return r(a.trim(),"header");const o=s.system.map(f=>promptTitle(f.text)).find(Boolean);if(o)return r(o,"prompt");const i=s.answer.format?.name;if(i)return r(i,"schema");const p=[...s.tools,...s.answer.toolCalls].map(f=>f.server).find(Boolean);if(p)return r(p,"tools");const l=s.system.map(f=>promptOpening(f.text)).find(Boolean);return l?{key:aiKeyOf("agent",`prompt ${l.replace(/ …$/,"")}`),name:l,from:"prompt"}:r(`${e.service??B} ${s.api==="embeddings"?"embeddings":s.model??s.api}`,"service")}m(O,"N"),d(O,"E"),c(O,"agentOf");function $(e,s,t){const r=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 r(actionName(n),"metadata");const a=h(e,"x-lensmcp-action");if(a?.trim())return r(actionName(a.trim()),"header");if(s.answer.format?.name)return r(s.answer.format.name,"schema")}m($,"R"),d($,"x"),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,"L"),d(C,"z"),c(C,"turnLine");function y(e){const s=e.answer;return s.error?g(`error: ${s.error}`):s.refusal?g(`refused: ${s.refusal}`):s.toolCalls.length?g(s.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(s.text)}m(y,"v"),d(y,"A"),c(y,"saidLine");function I(e,s){if(s)return{why:"failed",said:"It failed \u2014 the provider counted nothing for it."};const t=e.gaps.find(r=>/^The (answer|stream)\b/.test(r)||/of the stream’s events were kept/.test(r));return t&&/was not kept|only each event’s name/.test(t)?{why:"not-kept",said:t}:t?{why:"cut",said:`Its token counts were not kept: ${t}`}:{why:"not-sent",said:"Its answer was kept whole, and the provider counted no tokens in it."}}m(I,"S"),d(I,"q"),c(I,"noUsageOf");export function aiCallRow(e,s){const t=q(e);if(!t||!e.ai)return;const r=x(t),n=new Map(t.settings.map(u=>[u.name,u.value])),a=k(r,"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?{}:D(E(t,{sections:!1})),v=k(r,"thread","thread_id","threadId","conversation","conversation_id","conversationId","case","case_id","caseId"),b=h(e,"x-lensmcp-thread")?.trim(),M=k(r,"parent_run","parentRun","parent")??h(e,"x-lensmcp-parent")?.trim(),A=$(e,t,r),j=S(r.round),U=S(r.attempt),N=n.get("continues response"),R=[...t.turns].reverse().map(C).find(Boolean),_=t.answer.status==="failed"||!!t.answer.error||(e.status??0)>=400||!!e.error,L=f&&Object.keys(f).length?void 0:I(t,_);return{id:e.id,at:e.startedAt,...e.durationMs!==void 0?{durationMs:e.durationMs}:{},...e.status!==void 0?{status:e.status}:{},..._?{failed:!0}:{},service:e.service??B,...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,r),run:a?{key:`run:${a}`,from:"metadata"}:o?{key:`run:${o}`,from:"header"}:{key:`run:${e.id}`,from:"alone"},...v?{thread:{key:`thread:${v}`,name:v,from:"metadata"}}:b?{thread:{key:`thread:${b}`,name:b,from:"header"}}:{},...M?{parent:`run:${M}`}:{},...j!==void 0?{round:j}:{},...U!==void 0?{attempt:U}:{},...A?{action:A}:{},...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}:{},...N?{previousResponseId:N}:{},...Object.keys(r).length?{meta:r}:{},...t.gaps.some(u=>/kept to its first|cut/.test(u))?{cut:!0}:{},...L?{noUsage:L}:{},...s.content&&R?{asked:R}:{},...s.content&&y(t)?{said:y(t)}:{}}}m(aiCallRow,"aiCallRow"),d(aiCallRow,"aiCallRow"),c(aiCallRow,"aiCallRow");export function linkAiRuns(e){const s=[...e].sort((a,o)=>a.at-o.at||a.id.localeCompare(o.id)),t=new Map,r=new Map;for(const a of s){if(a.run.from==="alone"){const o=a.previousResponseId?t.get(a.previousResponseId):void 0,i=o?void 0:a.answers?.map(l=>r.get(l)).find(Boolean),p=o??i;if(p){const l=o?"chain":"tools";a.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})}}a.responseId&&t.set(a.responseId,a);for(const o of a.callIds??[])r.set(o,a)}const n=new Map;for(const a of s){const o=(n.get(a.run.key)??0)+1;n.set(a.run.key,o),a.step=o}return e}m(linkAiRuns,"linkAiRuns"),d(linkAiRuns,"linkAiRuns"),c(linkAiRuns,"linkAiRuns");export function mergedKey(e,s){let t=s;for(let r=0;r<8&&e.merge[t]&&e.merge[t]!==s;r++)t=e.merge[t];return t}m(mergedKey,"mergedKey"),d(mergedKey,"mergedKey"),c(mergedKey,"mergedKey");export function applyAiNames(e,s){if(!Object.keys(s.names).length&&!Object.keys(s.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 r=c(n=>{const a=mergedKey(s,n.key),o=s.names[a];if(o)return{key:a,name:o,from:"renamed"};if(a===n.key)return n;const i=t.get(a);return{key:a,name:i?.name??humanName(a.replace(/^[a-z]+:/,"")),from:i?.from??n.from}},"resolve");for(const n of e)n.agent=r(n.agent),n.action&&(n.action=r(n.action));return e}m(applyAiNames,"applyAiNames"),d(applyAiNames,"applyAiNames"),c(applyAiNames,"applyAiNames");export function aiNamesOf(e){const s=e&&typeof e=="object"?e:{},t=c(r=>{const n={};if(r&&typeof r=="object"&&!Array.isArray(r))for(const[a,o]of Object.entries(r))/^(agent|action):/.test(a)&&typeof o=="string"&&o.trim()&&(n[a]=o.trim().slice(0,120));return n},"pick");return{version:1,names:t(s.names),merge:t(s.merge)}}m(aiNamesOf,"aiNamesOf"),d(aiNamesOf,"aiNamesOf"),c(aiNamesOf,"aiNamesOf");
1
+ "use strict";var B=Object.defineProperty;var m=(t,o)=>B(t,"name",{value:o,configurable:!0});var T=Object.defineProperty,c=m((t,o)=>T(t,"name",{value:o,configurable:!0}),"d");import{aiCallOf as z}from"./ai-call.js";import{aiContextOf as q,aiSplitOf as E}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 K=160,A="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=K)=>{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"),U=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 _(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(_,"B"),c(_,"metaOf");function N(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??A} ${o.api==="embeddings"?"embeddings":o.model??o.api}`,"service")}m(N,"E"),c(N,"agentOf");function R(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(R,"x"),c(R,"actionOf");function L(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(L,"z"),c(L,"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,"A"),c(v,"saidLine");function S(t,o){if(o)return{why:"failed",said:"It failed \u2014 the provider counted nothing for it."};const e=t.gaps.find(a=>/^The (answer|stream)\b/.test(a)||/of the stream’s events were kept/.test(a));return e&&/was not kept|only each event’s name/.test(e)?{why:"not-kept",said:e}:e?{why:"cut",said:`Its token counts were not kept: ${e}`}:{why:"not-sent",said:"Its answer was kept whole, and the provider counted no tokens in it."}}m(S,"q"),c(S,"noUsageOf");export function aiCallRow(t,o){const e=z(t);if(!e||!t.ai)return;const a=_(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?{}:E(q(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(),b=h(a,"parent_run","parentRun","parent")??g(t,"x-lensmcp-parent")?.trim(),x=R(t,e,a),$=U(a.round),O=U(a.attempt),I=n.get("continues response"),C=[...e.turns].reverse().map(L).find(Boolean),M=e.answer.status==="failed"||!!e.answer.error||(t.status??0)>=400||!!t.error,j=p&&Object.keys(p).length?void 0:S(e,M);return{id:t.id,at:t.startedAt,...t.durationMs!==void 0?{durationMs:t.durationMs}:{},...t.status!==void 0?{status:t.status}:{},...M?{failed:!0}:{},service:t.service??A,...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:N(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"}}:{},...b?{parent:`run:${b}`}:{},...$!==void 0?{round:$}:{},...O!==void 0?{attempt:O}:{},...x?{action:x}:{},...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}:{},...I?{previousResponseId:I}:{},...Object.keys(a).length?{meta:a}:{},...e.gaps.some(d=>/kept to its first|cut/.test(d))?{cut:!0}:{},...j?{noUsage:j}:{},...o.content&&C?{asked:C}:{},...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");
package/lib/ai-call.js CHANGED
@@ -1,19 +1,19 @@
1
- "use strict";var re=Object.defineProperty;var v=(e,t)=>re(e,"name",{value:t,configurable:!0});var ae=Object.defineProperty,k=v((e,t)=>ae(e,"name",{value:t,configurable:!0}),"v"),ie=Object.defineProperty,f=k((e,t)=>ie(e,"name",{value:t,configurable:!0}),"d");import{aiCacheOf as le}from"./ai-cache.js";const $=f(e=>!!e&&typeof e=="object"&&!Array.isArray(e),"isObj"),s=f(e=>typeof e=="string"?e:void 0,"str"),y=f(e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,"num"),w=f(e=>Array.isArray(e)?e:[],"arr"),u=f(e=>$(e)?e:{},"obj"),j=f(e=>typeof e=="string"?e:e===void 0?"":JSON.stringify(e),"json");function P(e){const t={};for(const[n,i]of e)typeof i=="number"&&Number.isFinite(i)&&i>0&&(t[n]=i);return Object.keys(t).length?{writes:t}:{}}v(P,"z"),k(P,"K"),f(P,"writesOf");function z(e,t){const n=y(t.cache_write_tokens)??y(e.cache_write_tokens),i=u(t.cache_write_tokens_details??e.cache_write_tokens_details);return{...n?{written:n}:{},...P([["30m",i.ttl_30m_tokens],["12h",i.ttl_12h_tokens]])}}v(z,"E"),k(z,"z"),f(z,"openaiWrites");const B=f(e=>e>=1024*1024?`${(e/1024/1024).toFixed(1)} MB`:`${Math.round(e/1024)} KB`,"kb");export const CUT_MARK="\u2026";export function parseJsonPrefix(e){try{return{value:JSON.parse(e),cut:!1}}catch{}const t=[];let n=0,i=!1,a=!1,r=!1;const o=e.length,l=f(m=>{const d=t[t.length-1];d&&(d.state="after"),n=m},"ended");for(let m=0;m<o;m++){const d=e[m];if(i){r?r=!1:d==="\\"?r=!0:d==='"'&&(i=!1,a?t[t.length-1].state="colon":l(m+1));continue}if(d===" "||d===`
2
- `||d==="\r"||d===" ")continue;const h=t[t.length-1];if(d==='"'){i=!0,a=!!h&&h.c==="{"&&h.state==="key";continue}if(d==="{"||d==="["){t.push({c:d,state:d==="{"?"key":"value"}),n=m+1;continue}if(d==="}"||d==="]"){t.pop(),l(m+1);continue}if(d===":"){h&&(h.state="value");continue}if(d===","){h&&(h.state=h.c==="{"?"key":"value");continue}let _=m;for(;_<o&&!`,}]
3
- \r `.includes(e[_]);)_++;if(_>=o)break;l(_),m=_-1}const c=t.map(m=>m.c==="{"?"}":"]").reverse().join("");if(i&&!a)for(let m=0;m<=6;m++)try{return{value:JSON.parse(`${e.slice(0,o-m)}${CUT_MARK}"${c}`),cut:!0}}catch{}if(n)try{return{value:JSON.parse(`${e.slice(0,n)}${c}`),cut:!0}}catch{return}}v(parseJsonPrefix,"parseJsonPrefix"),k(parseJsonPrefix,"parseJsonPrefix"),f(parseJsonPrefix,"parseJsonPrefix");export function aiApiOf(e){const t=e.split("?")[0].replace(/\/+$/,"");if(/\/responses$/.test(t))return"responses";if(/\/chat\/completions$/.test(t))return"chat";if(/\/embeddings$/.test(t))return"embeddings";if(/\/messages$/.test(t))return"messages"}v(aiApiOf,"aiApiOf"),k(aiApiOf,"aiApiOf"),f(aiApiOf,"aiApiOf");export function splitToolName(e,t){if(t)return{server:t,tool:e};const n=/^(?:mcp__)?([A-Za-z0-9-]+(?:_[A-Za-z0-9-]+)*)__(.+)$/.exec(e);return n?{server:n[1],tool:n[2]}:{tool:e}}v(splitToolName,"splitToolName"),k(splitToolName,"splitToolName"),f(splitToolName,"splitToolName");const A=f((e,t,n={})=>({...n.callId?{callId:n.callId}:{},name:e,...splitToolName(e,n.server),arguments:t,...n.output!==void 0?{output:n.output}:{},...n.error?{error:n.error}:{}}),"toolCall"),ce=300*1e3,ue=f(e=>`${Math.floor(e/6e4)} min ${Math.round(e%6e4/1e3)} s`,"minutes");function M(e,t,n,i){if(!e)return;if(e.omitted==="ai"){n.push(`The ${t==="request"?"prompt":"answer"} was not kept \u2014 an AI provider\u2019s bodies are kept only when asked for: Settings \u203A Capture \u203A AI calls, for the calls made after.`);return}if(e.omitted||e.text===void 0)return;const a=parseJsonPrefix(e.text);if(!a)return;const r=`read as far as it goes; what follows is not shown (the ${t==="request"?"end of the conversation":"rest of the answer"}, marked ${CUT_MARK}).`;if(e.cut==="time")n.push(`The ${t} was cut by the capture after its first ${B(e.kept)}: its read ran out of time (5 minutes from the answer\u2019s first byte, 30 for an AI call kept whole) \u2014 ${r}`);else if(e.cut==="broken")n.push(`The ${t} was cut after its first ${B(e.kept)}: the caller or the network ended it before its end \u2014 ${r}`);else if(a.cut&&!e.truncated){const o=t==="answer"&&i!==void 0&&i>ce?` \u2014 its first byte came ${ue(i)} after the call, past the 5 minutes a capture before 2026-11-22 read an answer for, counted from the call\u2019s start`:"";n.push(`The ${t} was cut by the capture after its first ${B(e.kept)}${o} \u2014 ${r}`)}else(a.cut||e.truncated)&&n.push(`The ${t} was kept to its first ${B(e.kept)} of ${B(e.size)} \u2014 ${r}`);return a.value}v(M,"T"),k(M,"M"),f(M,"readBody");function T(e){if(e.data===void 0||e.data==="[DONE]")return;const t=parseJsonPrefix(e.data);return t&&$(t.value)?{v:t.value,cut:t.cut}:void 0}v(T,"J"),k(T,"E"),f(T,"eventJson");function I(e){if(typeof e=="string")return{text:e,attachments:[]};const t=[],n=[];for(const i of w(e)){if(typeof i=="string"){t.push(i);continue}const a=u(i),r=s(a.type)??"",o=s(a.text)??s(a.refusal);o!==void 0?t.push(o):/image/.test(r)?n.push(s(a.detail)?`image (${s(a.detail)})`:"image"):/file|document/.test(r)?n.push(`file ${s(a.filename)??s(u(a.source).media_type)??s(a.file_id)??""}`.trim()):/audio/.test(r)?n.push("audio"):r&&n.push(r)}return{text:t.join(`
1
+ "use strict";var nt=Object.defineProperty;var v=(t,e)=>nt(t,"name",{value:e,configurable:!0});var rt=Object.defineProperty,f=v((t,e)=>rt(t,"name",{value:e,configurable:!0}),"d");import{aiCacheOf as at}from"./ai-cache.js";const b=f(t=>!!t&&typeof t=="object"&&!Array.isArray(t),"isObj"),s=f(t=>typeof t=="string"?t:void 0,"str"),y=f(t=>typeof t=="number"&&Number.isFinite(t)?t:void 0,"num"),k=f(t=>Array.isArray(t)?t:[],"arr"),u=f(t=>b(t)?t:{},"obj"),A=f(t=>typeof t=="string"?t:t===void 0?"":JSON.stringify(t),"json");function z(t){const e={};for(const[n,i]of t)typeof i=="number"&&Number.isFinite(i)&&i>0&&(e[n]=i);return Object.keys(e).length?{writes:e}:{}}v(z,"K"),f(z,"writesOf");function E(t,e){const n=y(e.cache_write_tokens)??y(t.cache_write_tokens),i=u(e.cache_write_tokens_details??t.cache_write_tokens_details);return{...n?{written:n}:{},...z([["30m",i.ttl_30m_tokens],["12h",i.ttl_12h_tokens]])}}v(E,"z"),f(E,"openaiWrites");const I=f(t=>t>=1024*1024?`${(t/1024/1024).toFixed(1)} MB`:`${Math.round(t/1024)} KB`,"kb");export const CUT_MARK="\u2026";export function parseJsonPrefix(t){try{return{value:JSON.parse(t),cut:!1}}catch{}const e=[];let n=0,i=!1,a=!1,r=!1;const o=t.length,l=f(m=>{const d=e[e.length-1];d&&(d.state="after"),n=m},"ended");for(let m=0;m<o;m++){const d=t[m];if(i){r?r=!1:d==="\\"?r=!0:d==='"'&&(i=!1,a?e[e.length-1].state="colon":l(m+1));continue}if(d===" "||d===`
2
+ `||d==="\r"||d===" ")continue;const h=e[e.length-1];if(d==='"'){i=!0,a=!!h&&h.c==="{"&&h.state==="key";continue}if(d==="{"||d==="["){e.push({c:d,state:d==="{"?"key":"value"}),n=m+1;continue}if(d==="}"||d==="]"){e.pop(),l(m+1);continue}if(d===":"){h&&(h.state="value");continue}if(d===","){h&&(h.state=h.c==="{"?"key":"value");continue}let _=m;for(;_<o&&!`,}]
3
+ \r `.includes(t[_]);)_++;if(_>=o)break;l(_),m=_-1}const c=e.map(m=>m.c==="{"?"}":"]").reverse().join("");if(i&&!a)for(let m=0;m<=6;m++)try{return{value:JSON.parse(`${t.slice(0,o-m)}${CUT_MARK}"${c}`),cut:!0}}catch{}if(n)try{return{value:JSON.parse(`${t.slice(0,n)}${c}`),cut:!0}}catch{return}}v(parseJsonPrefix,"parseJsonPrefix"),f(parseJsonPrefix,"parseJsonPrefix");export function aiApiOf(t){const e=t.split("?")[0].replace(/\/+$/,"");if(/\/responses$/.test(e))return"responses";if(/\/chat\/completions$/.test(e))return"chat";if(/\/embeddings$/.test(e))return"embeddings";if(/\/messages$/.test(e))return"messages"}v(aiApiOf,"aiApiOf"),f(aiApiOf,"aiApiOf");export function splitToolName(t,e){if(e)return{server:e,tool:t};const n=/^(?:mcp__)?([A-Za-z0-9-]+(?:_[A-Za-z0-9-]+)*)__(.+)$/.exec(t);return n?{server:n[1],tool:n[2]}:{tool:t}}v(splitToolName,"splitToolName"),f(splitToolName,"splitToolName");const $=f((t,e,n={})=>({...n.callId?{callId:n.callId}:{},name:t,...splitToolName(t,n.server),arguments:e,...n.output!==void 0?{output:n.output}:{},...n.error?{error:n.error}:{}}),"toolCall"),it=300*1e3,lt=f(t=>`${Math.floor(t/6e4)} min ${Math.round(t%6e4/1e3)} s`,"minutes");function T(t,e,n,i){if(!t)return;if(t.omitted==="ai"){n.push(`The ${e==="request"?"prompt":"answer"} was not kept \u2014 an AI provider\u2019s bodies are kept only when asked for: Settings \u203A Capture \u203A AI calls, for the calls made after.`);return}if(t.omitted||t.text===void 0)return;const a=parseJsonPrefix(t.text);if(!a)return;const r=`read as far as it goes; what follows is not shown (the ${e==="request"?"end of the conversation":"rest of the answer"}, marked ${CUT_MARK}).`;if(t.cut==="time")n.push(`The ${e} was cut by the capture after its first ${I(t.kept)}: its read ran out of time (5 minutes from the answer\u2019s first byte, 30 for an AI call kept whole) \u2014 ${r}`);else if(t.cut==="broken")n.push(`The ${e} was cut after its first ${I(t.kept)}: the caller or the network ended it before its end \u2014 ${r}`);else if(a.cut&&!t.truncated){const o=e==="answer"&&i!==void 0&&i>it?` \u2014 its first byte came ${lt(i)} after the call, past the 5 minutes a capture before 2026-11-22 read an answer for, counted from the call\u2019s start`:"";n.push(`The ${e} was cut by the capture after its first ${I(t.kept)}${o} \u2014 ${r}`)}else(a.cut||t.truncated)&&n.push(`The ${e} was kept to its first ${I(t.kept)} of ${I(t.size)} \u2014 ${r}`);return a.value}v(T,"M"),f(T,"readBody");function J(t){if(t.data===void 0||t.data==="[DONE]")return;const e=parseJsonPrefix(t.data);return e&&b(e.value)?{v:e.value,cut:e.cut}:void 0}v(J,"E"),f(J,"eventJson");function O(t){if(typeof t=="string")return{text:t,attachments:[]};const e=[],n=[];for(const i of k(t)){if(typeof i=="string"){e.push(i);continue}const a=u(i),r=s(a.type)??"",o=s(a.text)??s(a.refusal);o!==void 0?e.push(o):/image/.test(r)?n.push(s(a.detail)?`image (${s(a.detail)})`:"image"):/file|document/.test(r)?n.push(`file ${s(a.filename)??s(u(a.source).media_type)??s(a.file_id)??""}`.trim()):/audio/.test(r)?n.push("audio"):r&&n.push(r)}return{text:e.join(`
4
4
 
5
- `),attachments:n}}v(I,"O"),k(I,"O"),f(I,"contentOf");const E=f(e=>typeof e=="string"?e:Array.isArray(e)&&I(e).text||j(e),"outputOf");function C(e,t){const n=[];for(const[a,r]of t){let o=e;for(const c of a.split("."))o=u(o)[c];if(o==null)continue;const l=typeof o=="string"?o:typeof o=="number"||typeof o=="boolean"?String(o):$(o)&&s(o.name)?`${s(o.type)??"tool"} ${s(o.name)}`:$(o)&&s(o.type)?s(o.type):JSON.stringify(o);n.push({name:r,value:l})}const i=u(e.metadata);for(const[a,r]of Object.entries(i))n.push({name:`metadata.${a}`,value:typeof r=="string"?r:JSON.stringify(r)});return n}v(C,"C"),k(C,"T"),f(C,"settingsOf");function S(e,t,n,i){const a=t?e.byCallId.get(t):void 0;if(a){a.output=n,i&&(a.error=i);return}e.call.turns.push({kind:"tool",...A("(an earlier call)","",{callId:t,output:n,error:i})})}v(S,"S"),k(S,"B"),f(S,"addOutput");function O(e,t){const n={kind:"tool",...t};e.call.turns.push(n),t.callId&&e.byCallId.set(t.callId,n)}v(O,"j"),k(O,"S"),f(O,"addCall");const pe=[["reasoning.effort","reasoning effort"],["reasoning.summary","reasoning summary"],["max_output_tokens","max output tokens"],["temperature","temperature"],["top_p","top_p"],["tool_choice","tool choice"],["parallel_tool_calls","parallel tool calls"],["text.verbosity","verbosity"],["truncation","truncation"],["previous_response_id","continues response"],["store","store"],["service_tier","service tier"],["stream","stream"],["prompt_cache_key","prompt cache key"],["user","user"],["safety_identifier","safety identifier"],["prompt_cache_options.mode","prompt cache mode"],["prompt_cache_options.ttl","prompt cache ttl"],["prompt_cache_options.prewarm","prompt cache prewarm"],["prompt_cache_retention","prompt cache retention"]],ne=f(e=>j(Object.fromEntries(Object.entries(e).filter(([t])=>t!=="type"&&t!=="id"&&t!=="status"))),"builtInCall");function D(e,t){const n=s(t.type)??(t.role?"message":"");if(n==="message"){const i=s(t.role)??"user",{text:a,attachments:r}=I(t.content);i==="system"?e.call.system.push({source:"system message",text:a}):e.call.turns.push({kind:"message",role:i,text:a,...r.length?{attachments:r}:{}})}else if(n==="function_call"||n==="custom_tool_call")O(e,A(s(t.name)??"?",s(t.arguments)??j(t.input),{callId:s(t.call_id)}));else if(n==="function_call_output"||n==="custom_tool_call_output"||n==="computer_call_output"||n==="local_shell_call_output")S(e,s(t.call_id),E(t.output));else if(n==="mcp_call")O(e,A(s(t.name)??"?",s(t.arguments)??"",{callId:s(t.id),server:s(t.server_label),...t.output!==void 0&&t.output!==null?{output:E(t.output)}:{},error:s(t.error)}));else if(n==="mcp_list_tools"){const i=w(t.tools).map(a=>s(u(a).name)).filter(Boolean);O(e,A("list_tools","",{server:s(t.server_label),output:i.join(", ")}))}else if(n==="reasoning"){const i=w(t.summary).map(a=>s(u(a).text)).filter(Boolean).join(`
5
+ `),attachments:n}}v(O,"O"),f(O,"contentOf");const N=f(t=>typeof t=="string"?t:Array.isArray(t)&&O(t).text||A(t),"outputOf");function C(t,e){const n=[];for(const[a,r]of e){let o=t;for(const c of a.split("."))o=u(o)[c];if(o==null)continue;const l=typeof o=="string"?o:typeof o=="number"||typeof o=="boolean"?String(o):b(o)&&s(o.name)?`${s(o.type)??"tool"} ${s(o.name)}`:b(o)&&s(o.type)?s(o.type):JSON.stringify(o);n.push({name:r,value:l})}const i=u(t.metadata);for(const[a,r]of Object.entries(i))n.push({name:`metadata.${a}`,value:typeof r=="string"?r:JSON.stringify(r)});return n}v(C,"T"),f(C,"settingsOf");function S(t,e,n,i){const a=e?t.byCallId.get(e):void 0;if(a){a.output=n,i&&(a.error=i);return}t.call.turns.push({kind:"tool",...$("(an earlier call)","",{callId:e,output:n,error:i})})}v(S,"B"),f(S,"addOutput");function j(t,e){const n={kind:"tool",...e};t.call.turns.push(n),e.callId&&t.byCallId.set(e.callId,n)}v(j,"S"),f(j,"addCall");const ct=[["reasoning.effort","reasoning effort"],["reasoning.summary","reasoning summary"],["max_output_tokens","max output tokens"],["temperature","temperature"],["top_p","top_p"],["tool_choice","tool choice"],["parallel_tool_calls","parallel tool calls"],["text.verbosity","verbosity"],["truncation","truncation"],["previous_response_id","continues response"],["store","store"],["service_tier","service tier"],["stream","stream"],["prompt_cache_key","prompt cache key"],["user","user"],["safety_identifier","safety identifier"],["prompt_cache_options.mode","prompt cache mode"],["prompt_cache_options.ttl","prompt cache ttl"],["prompt_cache_options.prewarm","prompt cache prewarm"],["prompt_cache_retention","prompt cache retention"]],D=f(t=>A(Object.fromEntries(Object.entries(t).filter(([e])=>e!=="type"&&e!=="id"&&e!=="status"))),"builtInCall");function H(t,e){const n=s(e.type)??(e.role?"message":"");if(n==="message"){const i=s(e.role)??"user",{text:a,attachments:r}=O(e.content);i==="system"?t.call.system.push({source:"system message",text:a}):t.call.turns.push({kind:"message",role:i,text:a,...r.length?{attachments:r}:{}})}else if(n==="function_call"||n==="custom_tool_call")j(t,$(s(e.name)??"?",s(e.arguments)??A(e.input),{callId:s(e.call_id)}));else if(n==="function_call_output"||n==="custom_tool_call_output"||n==="computer_call_output"||n==="local_shell_call_output")S(t,s(e.call_id),N(e.output));else if(n==="mcp_call")j(t,$(s(e.name)??"?",s(e.arguments)??"",{callId:s(e.id),server:s(e.server_label),...e.output!==void 0&&e.output!==null?{output:N(e.output)}:{},error:s(e.error)}));else if(n==="mcp_list_tools"){const i=k(e.tools).map(a=>s(u(a).name)).filter(Boolean);j(t,$("list_tools","",{server:s(e.server_label),output:i.join(", ")}))}else if(n==="reasoning"){const i=k(e.summary).map(a=>s(u(a).text)).filter(Boolean).join(`
6
6
 
7
- `);e.call.turns.push({kind:"reasoning",...i?{text:i}:{}})}else n&&O(e,A(n.replace(/_call$/,""),ne(t),{callId:s(t.call_id)??s(t.id)}))}v(D,"H"),k(D,"V"),f(D,"responsesItem");function R(e){return w(e.tools).map(t=>{const n=u(t),i=s(n.type)??"function";if(i==="mcp"){const r=s(n.server_label)??"mcp",o=w(n.allowed_tools).map(l=>s(l)).filter(Boolean);return{name:r,server:r,tool:o.length?o.join(", "):"every tool",type:i,...s(n.server_description)??s(n.server_url)?{description:s(n.server_description)??s(n.server_url)}:{},called:0}}const a=s(n.name)??i;return{name:a,...splitToolName(a),type:i,...s(n.description)?{description:s(n.description)}:{},...n.parameters!==void 0?{parameters:n.parameters}:{},...typeof n.strict=="boolean"?{strict:n.strict}:{},called:0}})}v(R,"R"),k(R,"X"),f(R,"responsesTools");function K(e,t){const n=e.call.answer;s(t.status)&&(n.status=s(t.status));const i=s(u(t.incomplete_details).reason);i&&(n.finish=i);const a=u(t.error);s(a.message)&&(n.error=s(a.message)),s(t.model)&&(e.call.model??=s(t.model)),s(t.id)&&(e.call.responseId=s(t.id)),F(e,w(t.output).map(u));const r=u(t.usage);Object.keys(r).length&&(e.call.usage={...y(r.input_tokens)!==void 0?{input:y(r.input_tokens)}:{},...y(u(r.input_tokens_details).cached_tokens)!==void 0?{cached:y(u(r.input_tokens_details).cached_tokens)}:{},...z(r,u(r.input_tokens_details)),...y(r.output_tokens)!==void 0?{output:y(r.output_tokens)}:{},...y(u(r.output_tokens_details).reasoning_tokens)!==void 0?{reasoning:y(u(r.output_tokens_details).reasoning_tokens)}:{},...y(r.total_tokens)!==void 0?{total:y(r.total_tokens)}:{}})}v(K,"K"),k(K,"G"),f(K,"responsesAnswer");function F(e,t){const n=e.call.answer,i=[],a=[];for(const r of t){const o=s(r.type);if(o==="message")for(const l of w(r.content).map(u))s(l.refusal)?n.refusal=s(l.refusal):s(l.text)!==void 0&&i.push(s(l.text));else if(o==="function_call"||o==="custom_tool_call")n.toolCalls.push(A(s(r.name)??"?",s(r.arguments)??j(r.input),{callId:s(r.call_id)}));else if(o==="mcp_call")n.toolCalls.push(A(s(r.name)??"?",s(r.arguments)??"",{callId:s(r.id),server:s(r.server_label),...r.output!==void 0&&r.output!==null?{output:E(r.output)}:{},error:s(r.error)}));else if(o==="reasoning"){const l=w(r.summary).map(c=>s(u(c).text)).filter(Boolean).join(`
7
+ `);t.call.turns.push({kind:"reasoning",...i?{text:i}:{}})}else n&&j(t,$(n.replace(/_call$/,""),D(e),{callId:s(e.call_id)??s(e.id)}))}v(H,"V"),f(H,"responsesItem");function R(t){return k(t.tools).map(e=>{const n=u(e),i=s(n.type)??"function";if(i==="mcp"){const r=s(n.server_label)??"mcp",o=k(n.allowed_tools).map(l=>s(l)).filter(Boolean);return{name:r,server:r,tool:o.length?o.join(", "):"every tool",type:i,...s(n.server_description)??s(n.server_url)?{description:s(n.server_description)??s(n.server_url)}:{},called:0}}const a=s(n.name)??i;return{name:a,...splitToolName(a),type:i,...s(n.description)?{description:s(n.description)}:{},...n.parameters!==void 0?{parameters:n.parameters}:{},...typeof n.strict=="boolean"?{strict:n.strict}:{},called:0}})}v(R,"X"),f(R,"responsesTools");function K(t,e){const n=t.call.answer;s(e.status)&&(n.status=s(e.status));const i=s(u(e.incomplete_details).reason);i&&(n.finish=i);const a=u(e.error);s(a.message)&&(n.error=s(a.message)),s(e.model)&&(t.call.model??=s(e.model)),s(e.id)&&(t.call.responseId=s(e.id)),L(t,k(e.output).map(u));const r=u(e.usage);Object.keys(r).length&&(t.call.usage={...y(r.input_tokens)!==void 0?{input:y(r.input_tokens)}:{},...y(u(r.input_tokens_details).cached_tokens)!==void 0?{cached:y(u(r.input_tokens_details).cached_tokens)}:{},...E(r,u(r.input_tokens_details)),...y(r.output_tokens)!==void 0?{output:y(r.output_tokens)}:{},...y(u(r.output_tokens_details).reasoning_tokens)!==void 0?{reasoning:y(u(r.output_tokens_details).reasoning_tokens)}:{},...y(r.total_tokens)!==void 0?{total:y(r.total_tokens)}:{}})}v(K,"G"),f(K,"responsesAnswer");function L(t,e){const n=t.call.answer,i=[],a=[];for(const r of e){const o=s(r.type);if(o==="message")for(const l of k(r.content).map(u))s(l.refusal)?n.refusal=s(l.refusal):s(l.text)!==void 0&&i.push(s(l.text));else if(o==="function_call"||o==="custom_tool_call")n.toolCalls.push($(s(r.name)??"?",s(r.arguments)??A(r.input),{callId:s(r.call_id)}));else if(o==="mcp_call")n.toolCalls.push($(s(r.name)??"?",s(r.arguments)??"",{callId:s(r.id),server:s(r.server_label),...r.output!==void 0&&r.output!==null?{output:N(r.output)}:{},error:s(r.error)}));else if(o==="reasoning"){const l=k(r.summary).map(c=>s(u(c).text)).filter(Boolean).join(`
8
8
 
9
- `);l&&a.push(l)}else o&&o!=="mcp_list_tools"&&n.toolCalls.push(A(o.replace(/_call$/,""),ne(r),{callId:s(r.call_id)??s(r.id)}))}i.length&&(n.text=i.join(`
9
+ `);l&&a.push(l)}else o&&o!=="mcp_list_tools"&&n.toolCalls.push($(o.replace(/_call$/,""),D(r),{callId:s(r.call_id)??s(r.id)}))}i.length&&(n.text=i.join(`
10
10
 
11
11
  `)),a.length&&(n.reasoning=a.join(`
12
12
 
13
- `))}v(F,"L"),k(F,"D"),f(F,"responsesOutput");function Z(e,t,n){let i,a=0;const r=new Map,o=new Set,l=new Map,c=new Map,m=new Map;for(const h of t){const _=T(h);if(!_)continue;_.cut&&a++;const p=_.v,g=s(p.type)??h.event,x=y(p.output_index)??0;if(g==="response.completed"||g==="response.incomplete"||g==="response.failed"){if(!_.cut&&$(p.response))i=p.response;else if($(p.response)){const b=p.response;s(b.status)&&(e.call.answer.status=s(b.status))}}else if(g==="response.created"||g==="response.in_progress"){const b=u(p.response);s(b.model)&&(e.call.model??=s(b.model)),s(b.id)&&(e.call.responseId??=s(b.id))}else g==="response.output_item.added"||g==="response.output_item.done"?$(p.item)&&(!o.has(x)||!_.cut)&&(r.set(x,{...r.get(x)??{},...p.item}),g.endsWith(".done")&&!_.cut&&o.add(x)):g==="response.output_text.delta"||g==="response.refusal.delta"?l.set(x,(l.get(x)??"")+(s(p.delta)??"")):g==="response.output_text.done"&&!_.cut&&s(p.text)!==void 0?l.set(x,s(p.text)):g==="response.function_call_arguments.delta"||g==="response.custom_tool_call_input.delta"||g==="response.mcp_call_arguments.delta"?c.set(x,(c.get(x)??"")+(s(p.delta)??"")):(g==="response.function_call_arguments.done"||g==="response.mcp_call_arguments.done")&&!_.cut&&s(p.arguments)!==void 0?c.set(x,s(p.arguments)):g==="response.reasoning_summary_text.delta"?m.set(x,(m.get(x)??"")+(s(p.delta)??"")):(g==="error"||g==="response.error")&&(e.call.answer.error=s(p.message)??s(u(p.error).message)??"the stream reported an error")}if(i){K(e,i);return}const d=[...r.entries()].sort(([h],[_])=>h-_).map(([h,_])=>{if(o.has(h))return _;const p=s(_.type);return p==="message"&&l.has(h)?{..._,content:[{type:"output_text",text:l.get(h)}]}:(p==="function_call"||p==="mcp_call")&&c.has(h)?{..._,arguments:c.get(h)}:p==="custom_tool_call"&&c.has(h)?{..._,input:c.get(h)}:p==="reasoning"&&m.has(h)?{..._,summary:[{type:"summary_text",text:m.get(h)}]}:_});for(const[h,_]of l)r.has(h)||d.push({type:"message",content:[{type:"output_text",text:_}]});F(e,d),e.call.answer.status||(e.call.answer.status=d.length?"completed":"unknown"),a&&n.push(`${a} of the stream\u2019s events were kept to their first 4 KB, so the answer was rebuilt from its pieces${e.call.usage?"":" \u2014 its token counts came in the last event, which was cut"}.`)}v(Z,"G"),k(Z,"Y"),f(Z,"responsesStream");function G(e,t,n,i){const a=e.call;s(t.model)&&(a.model=s(t.model)),s(t.instructions)&&a.system.push({source:"instructions",text:s(t.instructions)});const r=t.input;if(typeof r=="string")a.turns.push({kind:"message",role:"user",text:r});else for(const l of w(r))$(l)&&D(e,l);a.tools=R(t),a.settings=C(t,pe);const o=u(u(t.text).format);s(o.type)&&o.type!=="text"&&(a.answer.format={type:s(o.type),...s(o.name)?{name:s(o.name)}:{},...o.schema!==void 0?{schema:o.schema}:{},...typeof o.strict=="boolean"?{strict:o.strict}:{}}),J(e,n,i,l=>K(e,l),l=>Z(e,l,i))}v(G,"Q"),k(G,"ee"),f(G,"responsesCall");const me=[["reasoning_effort","reasoning effort"],["max_completion_tokens","max completion tokens"],["max_tokens","max tokens"],["temperature","temperature"],["top_p","top_p"],["tool_choice","tool choice"],["parallel_tool_calls","parallel tool calls"],["n","n"],["seed","seed"],["stop","stop"],["presence_penalty","presence penalty"],["frequency_penalty","frequency penalty"],["verbosity","verbosity"],["store","store"],["service_tier","service tier"],["stream","stream"],["user","user"]];function L(e){const t=w(e.tool_calls).map(u).map(i=>{const a=u(i.function);return A(s(a.name)??s(u(i.custom).name)??"?",s(a.arguments)??s(u(i.custom).input)??"",{callId:s(i.id)})}),n=u(e.function_call);return s(n.name)&&t.push(A(s(n.name),s(n.arguments)??"",{})),t}v(L,"P"),k(L,"F"),f(L,"chatCalls");function U(e,t){const n=e.call.answer;s(t.model)&&(e.call.model??=s(t.model)),s(t.id)&&(e.call.responseId??=s(t.id));const i=u(w(t.choices)[0]),a=u(i.message),r=I(a.content).text;r&&(n.text=r),s(a.refusal)&&(n.refusal=s(a.refusal));const o=s(a.reasoning_content)??s(a.reasoning);o&&(n.reasoning=o),n.toolCalls.push(...L(a)),s(i.finish_reason)&&(n.finish=s(i.finish_reason)),n.status=n.finish?"completed":n.status??"unknown";const l=u(t.error);s(l.message)&&(n.error=s(l.message));const c=u(t.usage);Object.keys(c).length&&(e.call.usage={...y(c.prompt_tokens)!==void 0?{input:y(c.prompt_tokens)}:{},...y(u(c.prompt_tokens_details).cached_tokens)!==void 0?{cached:y(u(c.prompt_tokens_details).cached_tokens)}:{},...z(c,u(c.prompt_tokens_details)),...y(c.completion_tokens)!==void 0?{output:y(c.completion_tokens)}:{},...y(u(c.completion_tokens_details).reasoning_tokens)!==void 0?{reasoning:y(u(c.completion_tokens_details).reasoning_tokens)}:{},...y(c.total_tokens)!==void 0?{total:y(c.total_tokens)}:{}})}v(U,"F"),k(U,"P"),f(U,"chatAnswer");function H(e,t,n){let i="",a="",r="",o,l,c,m,d=0;const h=new Map;for(const p of t){const g=T(p);if(!g)continue;g.cut&&d++,c??=s(g.v.model),m??=s(g.v.id),$(g.v.usage)&&(l=g.v.usage),$(g.v.error)&&(e.call.answer.error=s(g.v.error.message)??"the stream reported an error");const x=u(w(g.v.choices)[0]),b=u(x.delta);i+=s(b.content)??"",a+=s(b.reasoning_content)??s(b.reasoning)??"",r+=s(b.refusal)??"";for(const N of w(b.tool_calls).map(u)){const se=y(N.index)??0,q=h.get(se)??{name:"",args:""},oe=u(N.function);s(N.id)&&(q.id=s(N.id)),q.name+=s(oe.name)??"",q.args+=s(oe.arguments)??"",h.set(se,q)}s(x.finish_reason)&&(o=s(x.finish_reason))}const _={content:i,...a?{reasoning_content:a}:{},...r?{refusal:r}:{},tool_calls:[...h.entries()].sort(([p],[g])=>p-g).map(([,p])=>({id:p.id,function:{name:p.name,arguments:p.args}}))};U(e,{...c?{model:c}:{},...m?{id:m}:{},choices:[{message:_,...o?{finish_reason:o}:{}}],...l?{usage:l}:{}}),d&&n.push(`${d} of the stream\u2019s chunks were kept to their first 4 KB \u2014 the answer was joined from what was kept of them.`)}v(H,"V"),k(H,"ne"),f(H,"chatStream");function V(e,t,n,i){const a=e.call;s(t.model)&&(a.model=s(t.model));for(const o of w(t.messages).map(u)){const l=s(o.role)??"user",{text:c,attachments:m}=I(o.content);if(l==="system")a.system.push({source:"system message",text:c});else if(l==="tool")S(e,s(o.tool_call_id),c);else if(l==="function")S(e,void 0,c);else{(c||m.length||l!=="assistant")&&a.turns.push({kind:"message",role:l,text:c,...m.length?{attachments:m}:{}});for(const d of L(o))O(e,d)}}a.tools=[...w(t.tools).map(u),...w(t.functions).map(o=>({type:"function",function:o}))].map(o=>{const l=u(o.function),c=s(o.type)??"function",m=s(l.name)??s(u(o.custom).name)??c;return{name:m,...splitToolName(m),type:c,...s(l.description)??s(u(o.custom).description)?{description:s(l.description)??s(u(o.custom).description)}:{},...l.parameters!==void 0?{parameters:l.parameters}:{},...typeof l.strict=="boolean"?{strict:l.strict}:{},called:0}}),a.settings=C(t,me);const r=u(t.response_format);if(s(r.type)&&r.type!=="text"){const o=u(r.json_schema);a.answer.format={type:s(r.type),...s(o.name)?{name:s(o.name)}:{},...o.schema!==void 0?{schema:o.schema}:{},...typeof o.strict=="boolean"?{strict:o.strict}:{}}}J(e,n,i,o=>U(e,o),o=>H(e,o,i))}v(V,"X"),k(V,"se"),f(V,"chatCall");const de=[["max_tokens","max tokens"],["thinking.budget_tokens","thinking budget"],["temperature","temperature"],["top_p","top_p"],["top_k","top_k"],["tool_choice","tool choice"],["stop_sequences","stop sequences"],["stream","stream"],["metadata.user_id","user"],["cache_control.type","cache control"],["cache_control.ttl","cache ttl"]];function X(e,t,n){if(typeof n=="string"){e.call.turns.push({kind:"message",role:t,text:n});return}const i=[],a=[],r=f(()=>{(i.length||a.length)&&e.call.turns.push({kind:"message",role:t,text:i.join(`
13
+ `))}v(L,"D"),f(L,"responsesOutput");function G(t,e,n){let i,a=0;const r=new Map,o=new Set,l=new Map,c=new Map,m=new Map;for(const h of e){const _=J(h);if(!_)continue;_.cut&&a++;const p=_.v,g=s(p.type)??h.event,w=y(p.output_index)??0;if(g==="response.completed"||g==="response.incomplete"||g==="response.failed"){if(!_.cut&&b(p.response))i=p.response;else if(b(p.response)){const x=p.response;s(x.status)&&(t.call.answer.status=s(x.status))}}else if(g==="response.created"||g==="response.in_progress"){const x=u(p.response);s(x.model)&&(t.call.model??=s(x.model)),s(x.id)&&(t.call.responseId??=s(x.id))}else g==="response.output_item.added"||g==="response.output_item.done"?b(p.item)&&(!o.has(w)||!_.cut)&&(r.set(w,{...r.get(w)??{},...p.item}),g.endsWith(".done")&&!_.cut&&o.add(w)):g==="response.output_text.delta"||g==="response.refusal.delta"?l.set(w,(l.get(w)??"")+(s(p.delta)??"")):g==="response.output_text.done"&&!_.cut&&s(p.text)!==void 0?l.set(w,s(p.text)):g==="response.function_call_arguments.delta"||g==="response.custom_tool_call_input.delta"||g==="response.mcp_call_arguments.delta"?c.set(w,(c.get(w)??"")+(s(p.delta)??"")):(g==="response.function_call_arguments.done"||g==="response.mcp_call_arguments.done")&&!_.cut&&s(p.arguments)!==void 0?c.set(w,s(p.arguments)):g==="response.reasoning_summary_text.delta"?m.set(w,(m.get(w)??"")+(s(p.delta)??"")):(g==="error"||g==="response.error")&&(t.call.answer.error=s(p.message)??s(u(p.error).message)??"the stream reported an error")}if(i){K(t,i);return}const d=[...r.entries()].sort(([h],[_])=>h-_).map(([h,_])=>{if(o.has(h))return _;const p=s(_.type);return p==="message"&&l.has(h)?{..._,content:[{type:"output_text",text:l.get(h)}]}:(p==="function_call"||p==="mcp_call")&&c.has(h)?{..._,arguments:c.get(h)}:p==="custom_tool_call"&&c.has(h)?{..._,input:c.get(h)}:p==="reasoning"&&m.has(h)?{..._,summary:[{type:"summary_text",text:m.get(h)}]}:_});for(const[h,_]of l)r.has(h)||d.push({type:"message",content:[{type:"output_text",text:_}]});L(t,d),t.call.answer.status||(t.call.answer.status=d.length?"completed":"unknown"),a&&n.push(`${a} of the stream\u2019s events were kept to their first 4 KB, so the answer was rebuilt from its pieces${t.call.usage?"":" \u2014 its token counts came in the last event, which was cut"}.`)}v(G,"Y"),f(G,"responsesStream");function Q(t,e,n,i){const a=t.call;s(e.model)&&(a.model=s(e.model)),s(e.instructions)&&a.system.push({source:"instructions",text:s(e.instructions)});const r=e.input;if(typeof r=="string")a.turns.push({kind:"message",role:"user",text:r});else for(const l of k(r))b(l)&&H(t,l);a.tools=R(e),a.settings=C(e,ct);const o=u(u(e.text).format);s(o.type)&&o.type!=="text"&&(a.answer.format={type:s(o.type),...s(o.name)?{name:s(o.name)}:{},...o.schema!==void 0?{schema:o.schema}:{},...typeof o.strict=="boolean"?{strict:o.strict}:{}}),q(t,n,i,l=>K(t,l),l=>G(t,l,i))}v(Q,"ee"),f(Q,"responsesCall");const ut=[["reasoning_effort","reasoning effort"],["max_completion_tokens","max completion tokens"],["max_tokens","max tokens"],["temperature","temperature"],["top_p","top_p"],["tool_choice","tool choice"],["parallel_tool_calls","parallel tool calls"],["n","n"],["seed","seed"],["stop","stop"],["presence_penalty","presence penalty"],["frequency_penalty","frequency penalty"],["verbosity","verbosity"],["store","store"],["service_tier","service tier"],["stream","stream"],["user","user"]];function P(t){const e=k(t.tool_calls).map(u).map(i=>{const a=u(i.function);return $(s(a.name)??s(u(i.custom).name)??"?",s(a.arguments)??s(u(i.custom).input)??"",{callId:s(i.id)})}),n=u(t.function_call);return s(n.name)&&e.push($(s(n.name),s(n.arguments)??"",{})),e}v(P,"F"),f(P,"chatCalls");function F(t,e){const n=t.call.answer;s(e.model)&&(t.call.model??=s(e.model)),s(e.id)&&(t.call.responseId??=s(e.id));const i=u(k(e.choices)[0]),a=u(i.message),r=O(a.content).text;r&&(n.text=r),s(a.refusal)&&(n.refusal=s(a.refusal));const o=s(a.reasoning_content)??s(a.reasoning);o&&(n.reasoning=o),n.toolCalls.push(...P(a)),s(i.finish_reason)&&(n.finish=s(i.finish_reason)),n.status=n.finish?"completed":n.status??"unknown";const l=u(e.error);s(l.message)&&(n.error=s(l.message));const c=u(e.usage);Object.keys(c).length&&(t.call.usage={...y(c.prompt_tokens)!==void 0?{input:y(c.prompt_tokens)}:{},...y(u(c.prompt_tokens_details).cached_tokens)!==void 0?{cached:y(u(c.prompt_tokens_details).cached_tokens)}:{},...E(c,u(c.prompt_tokens_details)),...y(c.completion_tokens)!==void 0?{output:y(c.completion_tokens)}:{},...y(u(c.completion_tokens_details).reasoning_tokens)!==void 0?{reasoning:y(u(c.completion_tokens_details).reasoning_tokens)}:{},...y(c.total_tokens)!==void 0?{total:y(c.total_tokens)}:{}})}v(F,"P"),f(F,"chatAnswer");function V(t,e,n){let i="",a="",r="",o,l,c,m,d=0;const h=new Map;for(const p of e){const g=J(p);if(!g)continue;g.cut&&d++,c??=s(g.v.model),m??=s(g.v.id),b(g.v.usage)&&(l=g.v.usage),b(g.v.error)&&(t.call.answer.error=s(g.v.error.message)??"the stream reported an error");const w=u(k(g.v.choices)[0]),x=u(w.delta);i+=s(x.content)??"",a+=s(x.reasoning_content)??s(x.reasoning)??"",r+=s(x.refusal)??"";for(const B of k(x.tool_calls).map(u)){const W=y(B.index)??0,M=h.get(W)??{name:"",args:""},Z=u(B.function);s(B.id)&&(M.id=s(B.id)),M.name+=s(Z.name)??"",M.args+=s(Z.arguments)??"",h.set(W,M)}s(w.finish_reason)&&(o=s(w.finish_reason))}const _={content:i,...a?{reasoning_content:a}:{},...r?{refusal:r}:{},tool_calls:[...h.entries()].sort(([p],[g])=>p-g).map(([,p])=>({id:p.id,function:{name:p.name,arguments:p.args}}))};F(t,{...c?{model:c}:{},...m?{id:m}:{},choices:[{message:_,...o?{finish_reason:o}:{}}],...l?{usage:l}:{}}),d&&n.push(`${d} of the stream\u2019s chunks were kept to their first 4 KB \u2014 the answer was joined from what was kept of them.`)}v(V,"ne"),f(V,"chatStream");function X(t,e,n,i){const a=t.call;s(e.model)&&(a.model=s(e.model));for(const o of k(e.messages).map(u)){const l=s(o.role)??"user",{text:c,attachments:m}=O(o.content);if(l==="system")a.system.push({source:"system message",text:c});else if(l==="tool")S(t,s(o.tool_call_id),c);else if(l==="function")S(t,void 0,c);else{(c||m.length||l!=="assistant")&&a.turns.push({kind:"message",role:l,text:c,...m.length?{attachments:m}:{}});for(const d of P(o))j(t,d)}}a.tools=[...k(e.tools).map(u),...k(e.functions).map(o=>({type:"function",function:o}))].map(o=>{const l=u(o.function),c=s(o.type)??"function",m=s(l.name)??s(u(o.custom).name)??c;return{name:m,...splitToolName(m),type:c,...s(l.description)??s(u(o.custom).description)?{description:s(l.description)??s(u(o.custom).description)}:{},...l.parameters!==void 0?{parameters:l.parameters}:{},...typeof l.strict=="boolean"?{strict:l.strict}:{},called:0}}),a.settings=C(e,ut);const r=u(e.response_format);if(s(r.type)&&r.type!=="text"){const o=u(r.json_schema);a.answer.format={type:s(r.type),...s(o.name)?{name:s(o.name)}:{},...o.schema!==void 0?{schema:o.schema}:{},...typeof o.strict=="boolean"?{strict:o.strict}:{}}}q(t,n,i,o=>F(t,o),o=>V(t,o,i))}v(X,"se"),f(X,"chatCall");const pt=[["max_tokens","max tokens"],["thinking.budget_tokens","thinking budget"],["temperature","temperature"],["top_p","top_p"],["top_k","top_k"],["tool_choice","tool choice"],["stop_sequences","stop sequences"],["stream","stream"],["metadata.user_id","user"],["cache_control.type","cache control"],["cache_control.ttl","cache ttl"]];function Y(t,e,n){if(typeof n=="string"){t.call.turns.push({kind:"message",role:e,text:n});return}const i=[],a=[],r=f(()=>{(i.length||a.length)&&t.call.turns.push({kind:"message",role:e,text:i.join(`
14
14
 
15
- `),...a.length?{attachments:[...a]}:{}}),i.length=0,a.length=0},"flush");for(const o of w(n).map(u)){const l=s(o.type)??"";l==="text"?i.push(s(o.text)??""):l==="tool_use"||l==="server_tool_use"||l==="mcp_tool_use"?(r(),O(e,A(s(o.name)??"?",j(o.input),{callId:s(o.id),server:s(o.server_name)}))):l==="tool_result"||l==="mcp_tool_result"||/_tool_result$/.test(l)?(r(),S(e,s(o.tool_use_id),E(o.content),o.is_error===!0?"the tool reported an error":void 0)):l==="thinking"||l==="redacted_thinking"?(r(),e.call.turns.push({kind:"reasoning",...s(o.thinking)?{text:s(o.thinking)}:{}})):a.push(l==="image"?"image":l==="document"?`document ${s(o.title)??""}`.trim():l)}r()}v(X,"Y"),k(X,"re"),f(X,"anthropicBlocks");function W(e,t){const n=e.call.answer;s(t.model)&&(e.call.model??=s(t.model)),s(t.id)&&(e.call.responseId??=s(t.id));const i=[],a=[];for(const l of w(t.content).map(u)){const c=s(l.type);c==="text"?i.push(s(l.text)??""):c==="tool_use"||c==="server_tool_use"||c==="mcp_tool_use"?n.toolCalls.push(A(s(l.name)??"?",j(l.input),{callId:s(l.id),server:s(l.server_name)})):c==="thinking"&&a.push(s(l.thinking)??"")}i.length&&(n.text=i.join(`
15
+ `),...a.length?{attachments:[...a]}:{}}),i.length=0,a.length=0},"flush");for(const o of k(n).map(u)){const l=s(o.type)??"";l==="text"?i.push(s(o.text)??""):l==="tool_use"||l==="server_tool_use"||l==="mcp_tool_use"?(r(),j(t,$(s(o.name)??"?",A(o.input),{callId:s(o.id),server:s(o.server_name)}))):l==="tool_result"||l==="mcp_tool_result"||/_tool_result$/.test(l)?(r(),S(t,s(o.tool_use_id),N(o.content),o.is_error===!0?"the tool reported an error":void 0)):l==="thinking"||l==="redacted_thinking"?(r(),t.call.turns.push({kind:"reasoning",...s(o.thinking)?{text:s(o.thinking)}:{}})):a.push(l==="image"?"image":l==="document"?`document ${s(o.title)??""}`.trim():l)}r()}v(Y,"re"),f(Y,"anthropicBlocks");function U(t,e){const n=t.call.answer;s(e.model)&&(t.call.model??=s(e.model)),s(e.id)&&(t.call.responseId??=s(e.id));const i=[],a=[];for(const l of k(e.content).map(u)){const c=s(l.type);c==="text"?i.push(s(l.text)??""):c==="tool_use"||c==="server_tool_use"||c==="mcp_tool_use"?n.toolCalls.push($(s(l.name)??"?",A(l.input),{callId:s(l.id),server:s(l.server_name)})):c==="thinking"&&a.push(s(l.thinking)??"")}i.length&&(n.text=i.join(`
16
16
 
17
17
  `)),a.length&&(n.reasoning=a.join(`
18
18
 
19
- `)),s(t.stop_reason)&&(n.finish=s(t.stop_reason)),n.status=t.type==="error"?"failed":n.finish?"completed":n.status??"unknown";const r=u(t.error);s(r.message)&&(n.error=s(r.message));const o=u(t.usage);if(Object.keys(o).length){const l=y(o.input_tokens),c=y(o.cache_read_input_tokens),m=y(o.output_tokens);e.call.usage={...l!==void 0?{input:l+(c??0)+(y(o.cache_creation_input_tokens)??0)}:{},...c!==void 0?{cached:c}:{},...y(o.cache_creation_input_tokens)?{written:y(o.cache_creation_input_tokens)}:{},...P([["5m",u(o.cache_creation).ephemeral_5m_input_tokens],["1h",u(o.cache_creation).ephemeral_1h_input_tokens]]),...m!==void 0?{output:m}:{}}}}v(W,"U"),k(W,"R"),f(W,"anthropicAnswer");function Y(e,t,n){let i={};const a=new Map,r=new Map;let o={},l=0;for(const c of t){const m=T(c);if(!m)continue;m.cut&&l++;const d=m.v,h=s(d.type)??c.event,_=y(d.index)??0;if(h==="message_start")i=u(d.message),o={...u(i.usage)};else if(h==="content_block_start")a.set(_,{...u(d.content_block)});else if(h==="content_block_delta"){const p=u(d.delta),g=a.get(_)??{};s(p.text)!==void 0&&(g.text=(s(g.text)??"")+s(p.text)),s(p.thinking)!==void 0&&(g.thinking=(s(g.thinking)??"")+s(p.thinking)),s(p.partial_json)!==void 0&&r.set(_,(r.get(_)??"")+s(p.partial_json)),a.set(_,g)}else h==="message_delta"?(i={...i,...u(d.delta)},o={...o,...u(d.usage)}):h==="error"&&(e.call.answer.error=s(u(d.error).message)??"the stream reported an error")}for(const[c,m]of r){const d=a.get(c);d&&(d.input=parseJsonPrefix(m)?.value??m)}W(e,{...i,content:[...a.entries()].sort(([c],[m])=>c-m).map(([,c])=>c),usage:o}),l&&n.push(`${l} of the stream\u2019s events were kept to their first 4 KB \u2014 the answer was joined from what was kept of them.`)}v(Y,"tt"),k(Y,"ae"),f(Y,"anthropicStream");function Q(e,t,n,i){const a=e.call;s(t.model)&&(a.model=s(t.model));const r=t.system;if(typeof r=="string"&&r)a.system.push({source:"system",text:r});else for(const o of w(r).map(u))s(o.text)&&a.system.push({source:"system",text:s(o.text)});for(const o of w(t.messages).map(u))X(e,s(o.role)??"user",o.content);a.tools=[...w(t.tools).map(u).map(o=>{const l=s(o.name)??s(o.type)??"tool";return{name:l,...splitToolName(l),type:s(o.type)??"custom",...s(o.description)?{description:s(o.description)}:{},...o.input_schema!==void 0?{parameters:o.input_schema}:{},called:0}}),...w(t.mcp_servers).map(u).map(o=>({name:s(o.name)??"mcp",server:s(o.name)??"mcp",tool:"every tool",type:"mcp",...s(o.url)?{description:s(o.url)}:{},called:0}))],a.settings=C(t,de),J(e,n,i,o=>W(e,o),o=>Y(e,o,i))}v(Q,"et"),k(Q,"ie"),f(Q,"anthropicCall");function ee(e,t,n,i){const a=e.call;s(t.model)&&(a.model=s(t.model));const r=t.input,o=typeof r=="string"?[r]:w(r),l=o.slice(0,200).map(p=>typeof p=="string"?p:typeof p=="number"?`token ${p}`:Array.isArray(p)?`${p.length} tokens`:j(p)),c=o.length>0&&o.every(p=>typeof p=="number");a.embedding={inputs:c?[`${o.length} tokens`]:l,count:c?1:o.length,...y(t.dimensions)!==void 0?{dimensions:y(t.dimensions)}:{}},a.settings=C(t,[["dimensions","dimensions"],["encoding_format","encoding"],["user","user"]]);const m=u(M(n.response.body,"answer",[])),d=w(m.data);if(d.length){a.embedding.vectors=d.length;const p=u(d[0]).embedding;Array.isArray(p)&&a.embedding.dimensions===void 0&&(a.embedding.dimensions=p.length)}const h=u(m.usage);y(h.prompt_tokens)!==void 0&&(a.usage={input:y(h.prompt_tokens),...y(h.total_tokens)!==void 0?{total:y(h.total_tokens)}:{}}),a.answer.status=n.status!==void 0&&n.status<400?"completed":"failed";const _=u(m.error);s(_.message)&&(a.answer.error=s(_.message))}v(ee,"st"),k(ee,"le"),f(ee,"embeddingsCall");function J(e,t,n,i,a){const r=t.response.stream;if(r){if(r.events.length&&r.events.every(l=>l.data===void 0)){n.push("The answer streamed, and only each event\u2019s name, time and size were kept \u2014 an AI provider\u2019s bodies are kept only when asked for: Settings \u203A Capture \u203A AI calls.");return}if(a(r.events),r.cut){const l=r.cutBy==="time"?": its read ran out of time (5 minutes from the first byte, 30 for an AI call kept whole)":r.cutBy==="broken"?": the caller or the network ended it":r.cutBy==="size"?": past what a stream keeps":"";n.push(`The stream was cut after ${r.events.length.toLocaleString("en-US")} of its ${r.total.toLocaleString("en-US")} events${l} \u2014 what came after is not shown.`)}return}const o=M(t.response.body,"answer",n,t.ttfbMs);$(o)?i(o):t.error&&(e.call.answer.error=t.error),e.call.answer.status||(e.call.answer.status=t.error||(t.status??0)>=400?"failed":"unknown")}v(J,"q"),k(J,"N"),f(J,"answerOf");function te(e){return e.api==="embeddings"?"embedding":e.answer.format&&/json/.test(e.answer.format.type)?"decision":e.tools.length||e.answer.toolCalls.length||e.turns.some(t=>t.kind==="tool")?"tools":e.turns.filter(t=>t.kind==="message"&&(t.role==="user"||t.role==="assistant")).length>1?"chat":"prompt"}v(te,"ot"),k(te,"ce"),f(te,"shapeOf");export function aiCallOf(e){if(!e.ai)return;const t=aiApiOf(e.path);if(!t)return;const n=[],i={call:{provider:e.ai.provider,api:t,shape:"prompt",settings:[],system:[],turns:[],tools:[],answer:{toolCalls:[]},gaps:n},byCallId:new Map},a=u(M(e.request.body,"request",n));t==="responses"?G(i,a,e,n):t==="chat"?V(i,a,e,n):t==="messages"?Q(i,a,e,n):ee(i,a,e,n);const r=i.call;if(r.answer.text!==void 0&&(r.answer.format?/json/.test(r.answer.format.type):/^\s*[{[]/.test(r.answer.text))){const c=parseJsonPrefix(r.answer.text);c&&($(c.value)||Array.isArray(c.value))&&(r.answer.json=c.value)}!r.answer.finish&&r.answer.toolCalls.length&&(r.answer.finish="tool calls");const o=new Map;for(const c of r.turns)c.kind==="tool"&&o.set(c.name,(o.get(c.name)??0)+1);for(const c of r.answer.toolCalls)o.set(c.name,(o.get(c.name)??0)+1);for(const c of r.tools)c.called=o.get(c.name)??0;r.shape=te(r);const l=le(t,a,r.usage);l&&(r.cache=l);for(const c of r.system)c.text.endsWith(CUT_MARK)&&(c.cut=!0);return r}v(aiCallOf,"aiCallOf"),k(aiCallOf,"aiCallOf"),f(aiCallOf,"aiCallOf");export const SHAPE_LABEL={prompt:"Single prompt",chat:"Conversation",tools:"Tool calling",decision:"Structured decision",embedding:"Embedding"};export function prettyJson(e){const t=e.trim()?parseJsonPrefix(e):void 0;return t&&($(t.value)||Array.isArray(t.value))?{value:t.value,text:e}:{text:e}}v(prettyJson,"prettyJson"),k(prettyJson,"prettyJson"),f(prettyJson,"prettyJson");
19
+ `)),s(e.stop_reason)&&(n.finish=s(e.stop_reason)),n.status=e.type==="error"?"failed":n.finish?"completed":n.status??"unknown";const r=u(e.error);s(r.message)&&(n.error=s(r.message));const o=u(e.usage);if(Object.keys(o).length){const l=y(o.input_tokens),c=y(o.cache_read_input_tokens),m=y(o.output_tokens);t.call.usage={...l!==void 0?{input:l+(c??0)+(y(o.cache_creation_input_tokens)??0)}:{},...c!==void 0?{cached:c}:{},...y(o.cache_creation_input_tokens)?{written:y(o.cache_creation_input_tokens)}:{},...z([["5m",u(o.cache_creation).ephemeral_5m_input_tokens],["1h",u(o.cache_creation).ephemeral_1h_input_tokens]]),...m!==void 0?{output:m}:{}}}}v(U,"R"),f(U,"anthropicAnswer");function tt(t,e,n){let i={};const a=new Map,r=new Map;let o={},l=0;for(const c of e){const m=J(c);if(!m)continue;m.cut&&l++;const d=m.v,h=s(d.type)??c.event,_=y(d.index)??0;if(h==="message_start")i=u(d.message),o={...u(i.usage)};else if(h==="content_block_start")a.set(_,{...u(d.content_block)});else if(h==="content_block_delta"){const p=u(d.delta),g=a.get(_)??{};s(p.text)!==void 0&&(g.text=(s(g.text)??"")+s(p.text)),s(p.thinking)!==void 0&&(g.thinking=(s(g.thinking)??"")+s(p.thinking)),s(p.partial_json)!==void 0&&r.set(_,(r.get(_)??"")+s(p.partial_json)),a.set(_,g)}else h==="message_delta"?(i={...i,...u(d.delta)},o={...o,...u(d.usage)}):h==="error"&&(t.call.answer.error=s(u(d.error).message)??"the stream reported an error")}for(const[c,m]of r){const d=a.get(c);d&&(d.input=parseJsonPrefix(m)?.value??m)}U(t,{...i,content:[...a.entries()].sort(([c],[m])=>c-m).map(([,c])=>c),usage:o}),l&&n.push(`${l} of the stream\u2019s events were kept to their first 4 KB \u2014 the answer was joined from what was kept of them.`)}v(tt,"ae"),f(tt,"anthropicStream");function et(t,e,n,i){const a=t.call;s(e.model)&&(a.model=s(e.model));const r=e.system;if(typeof r=="string"&&r)a.system.push({source:"system",text:r});else for(const o of k(r).map(u))s(o.text)&&a.system.push({source:"system",text:s(o.text)});for(const o of k(e.messages).map(u))Y(t,s(o.role)??"user",o.content);a.tools=[...k(e.tools).map(u).map(o=>{const l=s(o.name)??s(o.type)??"tool";return{name:l,...splitToolName(l),type:s(o.type)??"custom",...s(o.description)?{description:s(o.description)}:{},...o.input_schema!==void 0?{parameters:o.input_schema}:{},called:0}}),...k(e.mcp_servers).map(u).map(o=>({name:s(o.name)??"mcp",server:s(o.name)??"mcp",tool:"every tool",type:"mcp",...s(o.url)?{description:s(o.url)}:{},called:0}))],a.settings=C(e,pt),q(t,n,i,o=>U(t,o),o=>tt(t,o,i))}v(et,"ie"),f(et,"anthropicCall");function st(t,e,n,i){const a=t.call;s(e.model)&&(a.model=s(e.model));const r=e.input,o=typeof r=="string"?[r]:k(r),l=o.slice(0,200).map(p=>typeof p=="string"?p:typeof p=="number"?`token ${p}`:Array.isArray(p)?`${p.length} tokens`:A(p)),c=o.length>0&&o.every(p=>typeof p=="number");a.embedding={inputs:c?[`${o.length} tokens`]:l,count:c?1:o.length,...y(e.dimensions)!==void 0?{dimensions:y(e.dimensions)}:{}},a.settings=C(e,[["dimensions","dimensions"],["encoding_format","encoding"],["user","user"]]);const m=u(T(n.response.body,"answer",[])),d=k(m.data);if(d.length){a.embedding.vectors=d.length;const p=u(d[0]).embedding;Array.isArray(p)&&a.embedding.dimensions===void 0&&(a.embedding.dimensions=p.length)}const h=u(m.usage);y(h.prompt_tokens)!==void 0&&(a.usage={input:y(h.prompt_tokens),...y(h.total_tokens)!==void 0?{total:y(h.total_tokens)}:{}}),a.answer.status=n.status!==void 0&&n.status<400?"completed":"failed";const _=u(m.error);s(_.message)&&(a.answer.error=s(_.message))}v(st,"le"),f(st,"embeddingsCall");function q(t,e,n,i,a){const r=e.response.stream;if(r){if(r.events.length&&r.events.every(l=>l.data===void 0)){n.push("The answer streamed, and only each event\u2019s name, time and size were kept \u2014 an AI provider\u2019s bodies are kept only when asked for: Settings \u203A Capture \u203A AI calls.");return}if(a(r.events),r.cut){const l=r.cutBy==="time"?": its read ran out of time (5 minutes from the first byte, 30 for an AI call kept whole)":r.cutBy==="broken"?": the caller or the network ended it":r.cutBy==="size"?": past what a stream keeps":"";n.push(`The stream was cut after ${r.events.length.toLocaleString("en-US")} of its ${r.total.toLocaleString("en-US")} events${l} \u2014 what came after is not shown.`)}return}const o=T(e.response.body,"answer",n,e.ttfbMs);b(o)?i(o):e.error&&(t.call.answer.error=e.error),t.call.answer.status||(t.call.answer.status=e.error||(e.status??0)>=400?"failed":"unknown")}v(q,"N"),f(q,"answerOf");function ot(t){return t.api==="embeddings"?"embedding":t.answer.format&&/json/.test(t.answer.format.type)?"decision":t.tools.length||t.answer.toolCalls.length||t.turns.some(e=>e.kind==="tool")?"tools":t.turns.filter(e=>e.kind==="message"&&(e.role==="user"||e.role==="assistant")).length>1?"chat":"prompt"}v(ot,"ce"),f(ot,"shapeOf");export function aiCallOf(t){if(!t.ai)return;const e=aiApiOf(t.path);if(!e)return;const n=[],i={call:{provider:t.ai.provider,api:e,shape:"prompt",settings:[],system:[],turns:[],tools:[],answer:{toolCalls:[]},gaps:n},byCallId:new Map},a=u(T(t.request.body,"request",n));e==="responses"?Q(i,a,t,n):e==="chat"?X(i,a,t,n):e==="messages"?et(i,a,t,n):st(i,a,t,n);const r=i.call;if(r.answer.text!==void 0&&(r.answer.format?/json/.test(r.answer.format.type):/^\s*[{[]/.test(r.answer.text))){const c=parseJsonPrefix(r.answer.text);c&&(b(c.value)||Array.isArray(c.value))&&(r.answer.json=c.value)}!r.answer.finish&&r.answer.toolCalls.length&&(r.answer.finish="tool calls");const o=new Map;for(const c of r.turns)c.kind==="tool"&&o.set(c.name,(o.get(c.name)??0)+1);for(const c of r.answer.toolCalls)o.set(c.name,(o.get(c.name)??0)+1);for(const c of r.tools)c.called=o.get(c.name)??0;r.shape=ot(r);const l=at(e,a,r.usage);l&&(r.cache=l);for(const c of r.system)c.text.endsWith(CUT_MARK)&&(c.cut=!0);return r}v(aiCallOf,"aiCallOf"),f(aiCallOf,"aiCallOf");export const SHAPE_LABEL={prompt:"Single prompt",chat:"Conversation",tools:"Tool calling",decision:"Structured decision",embedding:"Embedding"};export function prettyJson(t){const e=t.trim()?parseJsonPrefix(t):void 0;return e&&(b(e.value)||Array.isArray(e.value))?{value:e.value,text:t}:{text:t}}v(prettyJson,"prettyJson"),f(prettyJson,"prettyJson");