@lensmcp/protocol-types 1.26.16 → 1.26.17
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.
- package/lib/ai-cache-facts.js +1 -1
- package/lib/ai-cache-verdict.js +1 -1
- package/lib/ai-cache.js +3 -3
- package/lib/ai-call-groups.js +2 -2
- package/lib/ai-call-row.js +3 -3
- package/lib/ai-call.js +9 -9
- package/lib/ai-compare.js +3 -3
- package/lib/ai-context.js +6 -6
- package/lib/ai-origins.js +9 -9
- package/lib/ai-together.js +5 -5
- package/lib/bounded-clone.js +1 -1
- package/lib/bounded-map.js +1 -1
- package/lib/bounded-writer.js +1 -1
- package/lib/capture-demand.js +1 -1
- package/lib/dashboard-path.js +1 -1
- package/lib/docker-errors.js +1 -1
- package/lib/docker-jobs.js +1 -1
- package/lib/docker-report.js +2 -2
- package/lib/docker-runs.js +3 -3
- package/lib/error-cause.js +6 -6
- package/lib/error-dismissal.js +1 -1
- package/lib/error-verdict.js +3 -3
- package/lib/event-loop.js +1 -1
- package/lib/expected-failure.js +2 -2
- package/lib/finding-proof.js +1 -1
- package/lib/flood-guard.js +1 -1
- package/lib/goal-design.js +1 -1
- package/lib/host-agents.js +1 -1
- package/lib/lint-coverage.js +1 -1
- package/lib/lint-ignores.js +2 -2
- package/lib/log-query.js +1 -1
- package/lib/metrics-reset.js +1 -1
- package/lib/overseer-findings.js +1 -1
- package/lib/peers.js +1 -1
- package/lib/perf-rules.js +1 -1
- package/lib/pod-memory.js +1 -1
- package/lib/producer-health.js +1 -1
- package/lib/remote-instances.js +1 -1
- package/lib/sources.js +1 -1
- package/lib/static-checks.js +1 -1
- package/lib/system-report.js +1 -1
- package/lib/team.js +1 -1
- package/package.json +1 -1
package/lib/ai-cache-facts.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var l=Object.defineProperty;var o=(e,
|
|
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");
|
package/lib/ai-cache-verdict.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var Ct=Object.defineProperty;var F=(e,o)=>Ct(e,"name",{value:o,configurable:!0});var Ut=Object.defineProperty,k=F((e,o)=>Ut(e,"name",{value:o,configurable:!0}),"w");import{AI_CACHE_TTL_MS as et,AI_GUIDANCE_SOURCES as kt,aiCacheMinTokens as It,aiGuidanceAge as Dt}from"./ai-cache-facts.js";export const AI_CACHE_VERDICT_LABEL={read:"read","first-writer":"first writer","duplicate-write":"duplicate write","broken-prefix":"broken prefix",cold:"cold","write-nothing-read":"write nothing read","no-cache":"no cache",unknown:"unknown"};const b=k(e=>Math.round(e).toLocaleString("en-US"),"fmt"),ot=k(e=>`$${e<.01&&e>0?e.toFixed(4):e.toFixed(2)}`,"money"),R=k(e=>`$${Number(e.toFixed(4))}`,"rate"),_=k(e=>Math.round(e*1e6)/1e6,"usd"),V=k(e=>e<1e3?`${Math.round(e)} ms`:e<12e4?`${(e/1e3).toFixed(1)} s`:e<72e5?`${Math.round(e/6e4)} min`:`${(e/36e5).toFixed(1)} h`,"dur"),Et=k(e=>e.tokens?.input!==void 0&&e.cache!==void 0&&!e.failed,"counted");export function aiCacheVerdicts(e,o,g=Date.now()){const h=new Map,l=new Map;for(const d of e){if(!d.cache)continue;const i=l.get(d.agent.key);i?i.push(d):l.set(d.agent.key,[d])}for(const d of l.values()){d.sort((i,s)=>i.at-s.at||i.id.localeCompare(s.id));for(const[i,s]of $t(d,o,g))h.set(i,s)}return h}F(aiCacheVerdicts,"aiCacheVerdicts"),k(aiCacheVerdicts,"aiCacheVerdicts");function gt(e,o){const g=e==="anthropic"?kt.anthropicCaching:kt.openaiCaching;return{source:g.url,readAt:g.readAt,...Dt(g.readAt,o).stale?{stale:!0}:{}}}F(gt,"It"),k(gt,"factsOf");function $t(e,o,g){const h=[],l=new Map,d=new Map;e.forEach((i,s)=>{const n=i.cache,$=i.at,x=i.durationMs!==void 0?i.at+i.durationMs:void 0,I=et[n.ttl],a={row:i,start:$,...x!==void 0?{end:x}:{},ttlMs:I,wrote:[]};h.push(a);const r=n.marks??[],w=r.filter(t=>t.bp),A=i.tokens?.input??0,m=i.tokens?.cached??0,f=i.tokens?.written??0,v=Et(i),c=i.model?o(i.model,A):void 0,J=gt(i.provider,g),K={...c?{price:{...c.source?{source:c.source}:{},...c.readAt?{readAt:c.readAt}:{},...c.stale?{stale:!0}:{}}}:{},facts:J},Z=k(()=>{for(const t of r){const u=d.get(t.h);u?u.push(s):d.set(t.h,[s])}},"remember"),tt=k((t,u)=>{const p=l.get(t);p?p.push({i:s,how:u}):l.set(t,[{i:s,how:u}])},"hold"),Q=It(i.provider,i.model);if(!v){if(!i.failed)for(const t of w)tt(t.h,"unknown");Z(),a.verdict=it(n,A,Q,K)??{kind:"unknown",said:i.failed?"It failed \u2014 the provider counted nothing for it.":"Its token count was not kept (the answer was cut by the capture): no verdict.",costs:[],basis:K},i.prewarm&&(a.verdict.prewarm=!0);return}const O=it(n,A,Q,K);if(O){const t=st(a,h,d,s);if(t&&t.tokens>=Q&&c){const u=c.cacheRead??c.input,p=t.tokens*(c.input-u)/1e6;O.costs.push({kind:"no-cache",tokens:t.tokens,usd:_(p),arithmetic:`${b(t.tokens)} \xD7 (${R(c.input)} \u2212 ${R(u)})/M`,estimate:!0}),O.lostUsd=_(p),O.said+=` It shares \u2248 ${b(t.tokens)} tokens with ${t.id} (${V($-h[t.i].start)} before): read from a cache, they would cost \u2248 ${ot(p)} less.`}i.prewarm&&(O.prewarm=!0),a.verdict=O,Z();return}const z=Math.max(256,A*.03),xt=k((t,u)=>u.reduce((p,B)=>!p||Math.abs(B.t-t)<Math.abs(p.t-t)?B:p,void 0),"nearest");let S=-1;if(m>0){const t=xt(m,w.length?w:r);t&&Math.abs(t.t-m)<=Math.max(z,m*.15)&&(a.readBp={h:t.h,t:t.t,s:t.s},S=w.indexOf(t))}w.forEach((t,u)=>(u<=S||S<0&&t.t<=m+z)&&tt(t.h,"read"));const at=w.filter((t,u)=>S>=0?u>S:t.t>m+z),vt=S>=0?w[S].t:m;let D=f>0?at.filter(t=>t.t<=vt+f+Math.max(z,f*.15)):[];if(f>0&&!D.length){const t=at[0]??w[w.length-1];D=t?[t]:[]}const nt=D.map((t,u)=>Math.max(1,t.t-(u?D[u-1].t:Math.max(m,w.filter(p=>p.t<t.t).pop()?.t??0)))),Bt=nt.reduce((t,u)=>t+u,0);D.forEach((t,u)=>{const p=D.length===1?f:Math.round(nt[u]/Bt*f),B=n.breakpoints.find(U=>Math.abs(U.tokens-t.t)<=1)?.ttl??n.ttl,N=et[B],T=(l.get(t.h)??[]).filter(U=>U.i<s),W=T.filter(U=>$-h[U.i].start<=N);if(W.length){const U=k(M=>h[M.i].end!==void 0&&h[M.i].end<=$,"done"),q=k(M=>M[M.length-1],"last"),ft=W.filter(M=>M.how==="wrote"),pt=W.filter(M=>M.how==="unknown"),wt=q(ft.filter(U))??q(pt.filter(U)),mt=q(ft.filter(M=>!U(M)))??q(pt.filter(M=>!U(M))),bt=wt??mt??q(W),At=!wt&&!!mt,yt=W.filter(M=>M.how==="read").length;a.wrote.push({h:t.h,s:t.s,tokens:p,estimate:D.length>1,ttl:B,status:"duplicate",against:bt,race:At,readFirst:yt})}else T.length?a.wrote.push({h:t.h,s:t.s,tokens:p,estimate:D.length>1,ttl:B,status:"cold",against:T[T.length-1],idleMs:$-h[T[T.length-1].i].start}):a.wrote.push({h:t.h,s:t.s,tokens:p,estimate:D.length>1,ttl:B,status:"first"});tt(t.h,"wrote")});const y=st(a,h,d,s);Z();const L=c?c.cacheRead??c.input:void 0,dt=c?Y(c,n.writes,n.ttl):void 0,H=[];let X,ct;if(y){const t=w.filter(B=>B.t<=y.tokens+1&&y.hashes.has(B.h)).reduce((B,N)=>Math.max(B,N.t),0),u=Math.max(m,t),p=y.tokens-u;if(y.tokens>=Q&&p>z){X={region:y.next??"(the end of the prompt)",tokens:y.tokens,id:h[y.i].row.id},ct=h[y.i];const B=m+f>=y.tokens-z,N=c?B?dt-L:c.input-L:void 0;H.push({kind:"broken-prefix",tokens:p,estimate:!0,...N!==void 0?{usd:_(p*N/1e6),arithmetic:`${b(p)} \xD7 (${R(B?dt:c.input)} \u2212 ${R(L)})/M`}:{}})}}for(const t of a.wrote){if(t.status==="first")continue;const u=c?Y(c,n.writes,t.ttl):void 0;H.push({kind:t.status==="duplicate"?"duplicate-write":"cold",tokens:t.tokens,estimate:t.estimate,...c?{usd:_(t.tokens*(u-L)/1e6),arithmetic:`${b(t.tokens)} \xD7 (${R(u)} \u2212 ${R(L)})/M`}:{}})}const C=[];a.wrote.some(t=>t.status==="duplicate")&&C.push("duplicate-write"),X&&C.push("broken-prefix"),a.wrote.some(t=>t.status==="cold")&&C.push("cold"),a.wrote.some(t=>t.status==="first")&&C.push("first-writer"),m>0&&C.push("read"),C.length||C.push("no-cache");const j=a.wrote.find(t=>t.status==="duplicate"),P=a.wrote.find(t=>t.status==="cold"),ht=j?.against??P?.against,E=ht?h[ht.i]:ct,ut=H.some(t=>t.usd!==void 0)?_(H.reduce((t,u)=>t+(u.usd??0),0)):void 0,lt=c&&m>0?_(m*(c.input-L)/1e6):void 0,Mt=C[0];a.verdict={kind:Mt,...C.length>1?{also:C.slice(1)}:{},said:"",costs:H,...ut!==void 0?{lostUsd:ut}:{},...lt!==void 0?{savedUsd:lt}:{},...j||P||a.wrote[0]||a.readBp?{prefix:(j??P??a.wrote[0])?.h??a.readBp.h}:{},read:m,written:f,...E?{against:{id:E.row.id,at:E.start,...E.end!==void 0?{ended:E.end}:{},inFlight:E.end===void 0||E.end>$,gapMs:$-E.start,...E.row.prewarm?{prewarm:!0}:{}}}:{},...j?{race:!!j.race,...j.readFirst?{readBefore:j.readFirst}:{}}:{},...X?{brokeAt:X}:{},...P?.idleMs!==void 0?{idleMs:P.idleMs}:{},...i.prewarm?{prewarm:!0}:{},basis:K}});for(const i of h){const s=i.verdict;if(!i.wrote.length){s.said=rt(i,s);continue}const n=new Set,$=new Set;let x=!1;const I=[];for(const a of i.wrote){const r=et[a.ttl],w=(l.get(a.h)??[]).filter(f=>h[f.i].start>i.start&&h[f.i].start-i.start<=r),A=w.filter(f=>f.how==="read"),m=w.filter(f=>f.how==="unknown");for(const f of A)n.add(f.i);for(const f of m)$.add(f.i);i.start+r>g?x=!0:!A.length&&!m.length&&I.push(a)}for(const a of n)$.delete(a);if(n.size&&(s.readBy=n.size),$.size&&(s.maybeReadBy=$.size),x&&(s.open=!0),I.length){const a=i.row,r=a.model?o(a.model,a.tokens?.input??0):void 0;let w=s.costs.find(v=>v.kind==="broken-prefix")?.tokens??0;for(const v of I){if(v.status!=="first")continue;const c=Math.max(0,v.tokens-w);if(w=0,!c)continue;const J=r?Y(r,a.cache.writes,v.ttl):void 0;s.costs.push({kind:"write-nothing-read",tokens:c,estimate:v.estimate||c!==v.tokens,...r?{usd:_(c*(J-r.input)/1e6),arithmetic:`${b(c)} \xD7 (${R(J)} \u2212 ${R(r.input)})/M`}:{}})}r&&(s.lostUsd=_(s.costs.reduce((v,c)=>v+(c.usd??0),0)));const A=[s.kind,...s.also??[]],m=A.findIndex(v=>v!=="duplicate-write"&&v!=="broken-prefix"&&v!=="cold");A.splice(m<0?A.length:m,0,"write-nothing-read"),s.kind=A[0];const f=A.slice(1);f.length?s.also=f:delete s.also}s.said=rt(i,s)}return new Map(h.map(i=>[i.row.id,i.verdict]))}F($t,"Ut"),k($t,"judgeAgent");function Y(e,o,g){const h=Object.entries(o??{}).filter(d=>typeof d[1]=="number"&&d[1]>0);if(h.length>1){const d=h.reduce((i,[,s])=>i+s,0);return h.reduce((i,[s,n])=>i+(e.writes[s]??e.input)*n,0)/d}const l=h[0]?.[0]??g;return e.writes[l]??e.input}F(Y,"et"),k(Y,"writeRate");function it(e,o,g,h){const l=k(d=>({kind:"no-cache",said:d,costs:[],basis:h}),"no");if(e.mode==="explicit"&&!e.breakpoints.length)return l("Explicit mode with no breakpoint: it read and wrote nothing.");if(e.mode==="none")return l("No `cache_control`: Anthropic cached nothing of it.");if(o>0&&o<g)return l(`${b(o)} input tokens \u2014 under the ${b(g)}-token minimum: nothing is cached.`)}F(it,"pt"),k(it,"structural");function st(e,o,g,h){const l=e.row.cache?.marks??[];let d;for(let s=0;s<l.length;s++){const n=g.get(l[s].h);if(n)for(let $=n.length-1;$>=0;$--){const x=n[$];if(!(x>=h)){if(e.start-o[x].start>e.ttlMs)break;d={i:x,at:s};break}}}if(!d)return;const i=o[d.i];return{i:d.i,id:i.row.id,tokens:l[d.at].t,...l[d.at+1]?{next:l[d.at+1].s}:{},hashes:new Set((i.row.cache?.marks??[]).map(s=>s.h))}}F(st,"wt"),k(st,"sharedWith");const G=k(e=>e.split(" \u203A ")[0],"block");function rt(e,o){if(o.said)return o.said;const g=e.row,h=g.cache,l=g.tokens?.input??0,d=o.read??0,i=o.written??0,s=h.ttl,n=[],$=o.prewarm?"A prewarm (it answers nothing): it ":"It ";n.push(`${$}read ${b(d)} of its ${b(l)} input tokens from the cache${i?` and wrote ${b(i)}`:""} (${h.mode} mode, ${s}).`);const x=e.wrote.find(r=>r.status==="duplicate");if(x&&o.against){const r=o.against,w=o.readBefore?` ${b(o.readBefore)} call${o.readBefore===1?"":"s"} sent before this one read it.`:"";n.push(o.race?`Duplicate write \u2014 a race: ${r.id}${x.against?.how==="unknown"?" (its count was not kept: it may have)":""} wrote the same prefix (to the end of \xAB${G(x.s)}\xBB) and was still in flight when this one was sent, ${V(r.gapMs)} after it.${w}`:x.against?.how==="read"?`Duplicate write: ${r.id} had read the same prefix (to the end of \xAB${G(x.s)}\xBB) ${V(r.gapMs)} before \u2014 the entry was there, and this call did not read it.`:`Duplicate write: ${r.id}${r.prewarm?" (a prewarm)":""}${x.against?.how==="unknown"?" (its count was not kept: it may have)":""} wrote the same prefix (to the end of \xAB${G(x.s)}\xBB) ${V(r.gapMs)} before${r.ended!==void 0&&r.ended<=e.start?` and had ended ${V(e.start-r.ended)} before this one was sent \u2014 not a race: the write had finished and this call did not read it`:""}.${w}`)}o.brokeAt&&n.push(`Broken prefix: it shares \u2248 ${b(o.brokeAt.tokens)} tokens with ${o.brokeAt.id}, then they part in \xAB${o.brokeAt.region}\xBB \u2014 no breakpoint ends where they part, so it read only ${b(d)}.`);const I=e.wrote.find(r=>r.status==="cold");I&&o.idleMs!==void 0&&n.push(`Cold: the same prefix (to the end of \xAB${G(I.s)}\xBB) was last used ${V(o.idleMs)} before \u2014 past its ${I.ttl} lifetime.`);const a=e.wrote.filter(r=>r.status==="first");return a.length&&n.push(`First writer of the prefix to the end of \xAB${a.map(r=>G(r.s)).join("\xBB, \xAB")}\xBB.`),e.wrote.length&&(o.kind==="write-nothing-read"||o.also?.includes("write-nothing-read")?n.push("No later call of its agent read what it wrote inside its lifetime."):o.readBy?n.push(`${b(o.readBy)} later call${o.readBy===1?"":"s"} read what it wrote.`):o.maybeReadBy?n.push(`${b(o.maybeReadBy)} later call${o.maybeReadBy===1?"":"s"} may have read it (their counts were not kept).`):o.open&&n.push("Its lifetime has not run out: a later call may still read it.")),!e.wrote.length&&d>0&&!o.brokeAt&&n.push(`Read${e.readBp?` to the end of \xAB${G(e.readBp.s)}\xBB`:""}.`),o.lostUsd!==void 0&&o.lostUsd>0&&n.push(`\u2248 ${ot(o.lostUsd)} lost: ${o.costs.filter(r=>r.arithmetic).map(r=>`${r.arithmetic}${r.estimate?" (estimate)":""}`).join(" + ")}.`),o.savedUsd&&n.push(`Its reads saved \u2248 ${ot(o.savedUsd)} against plain input.`),n.join(" ")}F(rt,"kt"),k(rt,"said");
|
|
1
|
+
"use strict";var It=Object.defineProperty;var F=(e,s)=>It(e,"name",{value:s,configurable:!0});var Ut=Object.defineProperty,R=F((e,s)=>Ut(e,"name",{value:s,configurable:!0}),"F"),Dt=Object.defineProperty,k=R((e,s)=>Dt(e,"name",{value:s,configurable:!0}),"w");import{AI_CACHE_TTL_MS as at,AI_GUIDANCE_SOURCES as xt,aiCacheMinTokens as Et,aiGuidanceAge as Ft}from"./ai-cache-facts.js";export const AI_CACHE_VERDICT_LABEL={read:"read","first-writer":"first writer","duplicate-write":"duplicate write","broken-prefix":"broken prefix",cold:"cold","write-nothing-read":"write nothing read","no-cache":"no cache",unknown:"unknown"};const M=k(e=>Math.round(e).toLocaleString("en-US"),"fmt"),rt=k(e=>`$${e<.01&&e>0?e.toFixed(4):e.toFixed(2)}`,"money"),_=k(e=>`$${Number(e.toFixed(4))}`,"rate"),S=k(e=>Math.round(e*1e6)/1e6,"usd"),G=k(e=>e<1e3?`${Math.round(e)} ms`:e<12e4?`${(e/1e3).toFixed(1)} s`:e<72e5?`${Math.round(e/6e4)} min`:`${(e/36e5).toFixed(1)} h`,"dur"),Rt=k(e=>e.tokens?.input!==void 0&&e.cache!==void 0&&!e.failed,"counted");export function aiCacheVerdicts(e,s,g=Date.now()){const h=new Map,u=new Map;for(const d of e){if(!d.cache)continue;const n=u.get(d.agent.key);n?n.push(d):u.set(d.agent.key,[d])}for(const d of u.values()){d.sort((n,i)=>n.at-i.at||n.id.localeCompare(i.id));for(const[n,i]of dt(d,s,g))h.set(n,i)}return h}F(aiCacheVerdicts,"aiCacheVerdicts"),R(aiCacheVerdicts,"aiCacheVerdicts"),k(aiCacheVerdicts,"aiCacheVerdicts");function ot(e,s){const g=e==="anthropic"?xt.anthropicCaching:xt.openaiCaching;return{source:g.url,readAt:g.readAt,...Ft(g.readAt,s).stale?{stale:!0}:{}}}F(ot,"gt"),R(ot,"It"),k(ot,"factsOf");function dt(e,s,g){const h=[],u=new Map,d=new Map;e.forEach((n,i)=>{const o=n.cache,$=n.at,x=n.durationMs!==void 0?n.at+n.durationMs:void 0,U=at[o.ttl],r={row:n,start:$,...x!==void 0?{end:x}:{},ttlMs:U,wrote:[]};h.push(r);const a=o.marks??[],w=a.filter(t=>t.bp),A=n.tokens?.input??0,m=n.tokens?.cached??0,f=n.tokens?.written??0,v=Rt(n),c=n.model?s(n.model,A):void 0,Q=ot(n.provider,g),X={...c?{price:{...c.source?{source:c.source}:{},...c.readAt?{readAt:c.readAt}:{},...c.stale?{stale:!0}:{}}}:{},facts:Q},nt=k(()=>{for(const t of a){const l=d.get(t.h);l?l.push(i):d.set(t.h,[i])}},"remember"),it=k((t,l)=>{const p=u.get(t);p?p.push({i,how:l}):u.set(t,[{i,how:l}])},"hold"),Y=Et(n.provider,n.model);if(!v){if(!n.failed)for(const t of w)it(t.h,"unknown");nt(),r.verdict=tt(o,A,Y,X)??{kind:"unknown",said:n.failed?"It failed \u2014 the provider counted nothing for it.":"Its token count was not kept (the answer was cut by the capture): no verdict.",costs:[],basis:X},n.prewarm&&(r.verdict.prewarm=!0);return}const N=tt(o,A,Y,X);if(N){const t=et(r,h,d,i);if(t&&t.tokens>=Y&&c){const l=c.cacheRead??c.input,p=t.tokens*(c.input-l)/1e6;N.costs.push({kind:"no-cache",tokens:t.tokens,usd:S(p),arithmetic:`${M(t.tokens)} \xD7 (${_(c.input)} \u2212 ${_(l)})/M`,estimate:!0}),N.lostUsd=S(p),N.said+=` It shares \u2248 ${M(t.tokens)} tokens with ${t.id} (${G($-h[t.i].start)} before): read from a cache, they would cost \u2248 ${rt(p)} less.`}n.prewarm&&(N.prewarm=!0),r.verdict=N,nt();return}const z=Math.max(256,A*.03),vt=k((t,l)=>l.reduce((p,b)=>!p||Math.abs(b.t-t)<Math.abs(p.t-t)?b:p,void 0),"nearest");let j=-1;if(m>0){const t=vt(m,w.length?w:a);t&&Math.abs(t.t-m)<=Math.max(z,m*.15)&&(r.readBp={h:t.h,t:t.t,s:t.s},j=w.indexOf(t))}w.forEach((t,l)=>(l<=j||j<0&&t.t<=m+z)&&it(t.h,"read"));const ct=w.filter((t,l)=>j>=0?l>j:t.t>m+z),bt=j>=0?w[j].t:m;let D=f>0?ct.filter(t=>t.t<=bt+f+Math.max(z,f*.15)):[];if(f>0&&!D.length){const t=ct[0]??w[w.length-1];D=t?[t]:[]}const ht=D.map((t,l)=>Math.max(1,t.t-(l?D[l-1].t:Math.max(m,w.filter(p=>p.t<t.t).pop()?.t??0)))),Bt=ht.reduce((t,l)=>t+l,0);D.forEach((t,l)=>{const p=D.length===1?f:Math.round(ht[l]/Bt*f),b=o.breakpoints.find(I=>Math.abs(I.tokens-t.t)<=1)?.ttl??o.ttl,T=at[b],V=(u.get(t.h)??[]).filter(I=>I.i<i),W=V.filter(I=>$-h[I.i].start<=T);if(W.length){const I=k(B=>h[B.i].end!==void 0&&h[B.i].end<=$,"done"),q=k(B=>B[B.length-1],"last"),mt=W.filter(B=>B.how==="wrote"),kt=W.filter(B=>B.how==="unknown"),gt=q(mt.filter(I))??q(kt.filter(I)),$t=q(mt.filter(B=>!I(B)))??q(kt.filter(B=>!I(B))),At=gt??$t??q(W),yt=!gt&&!!$t,Ct=W.filter(B=>B.how==="read").length;r.wrote.push({h:t.h,s:t.s,tokens:p,estimate:D.length>1,ttl:b,status:"duplicate",against:At,race:yt,readFirst:Ct})}else V.length?r.wrote.push({h:t.h,s:t.s,tokens:p,estimate:D.length>1,ttl:b,status:"cold",against:V[V.length-1],idleMs:$-h[V[V.length-1].i].start}):r.wrote.push({h:t.h,s:t.s,tokens:p,estimate:D.length>1,ttl:b,status:"first"});it(t.h,"wrote")});const y=et(r,h,d,i);nt();const L=c?c.cacheRead??c.input:void 0,lt=c?K(c,o.writes,o.ttl):void 0,P=[];let Z,ut;if(y){const t=w.filter(b=>b.t<=y.tokens+1&&y.hashes.has(b.h)).reduce((b,T)=>Math.max(b,T.t),0),l=Math.max(m,t),p=y.tokens-l;if(y.tokens>=Y&&p>z){Z={region:y.next??"(the end of the prompt)",tokens:y.tokens,id:h[y.i].row.id},ut=h[y.i];const b=m+f>=y.tokens-z,T=c?b?lt-L:c.input-L:void 0;P.push({kind:"broken-prefix",tokens:p,estimate:!0,...T!==void 0?{usd:S(p*T/1e6),arithmetic:`${M(p)} \xD7 (${_(b?lt:c.input)} \u2212 ${_(L)})/M`}:{}})}}for(const t of r.wrote){if(t.status==="first")continue;const l=c?K(c,o.writes,t.ttl):void 0;P.push({kind:t.status==="duplicate"?"duplicate-write":"cold",tokens:t.tokens,estimate:t.estimate,...c?{usd:S(t.tokens*(l-L)/1e6),arithmetic:`${M(t.tokens)} \xD7 (${_(l)} \u2212 ${_(L)})/M`}:{}})}const C=[];r.wrote.some(t=>t.status==="duplicate")&&C.push("duplicate-write"),Z&&C.push("broken-prefix"),r.wrote.some(t=>t.status==="cold")&&C.push("cold"),r.wrote.some(t=>t.status==="first")&&C.push("first-writer"),m>0&&C.push("read"),C.length||C.push("no-cache");const O=r.wrote.find(t=>t.status==="duplicate"),J=r.wrote.find(t=>t.status==="cold"),ft=O?.against??J?.against,E=ft?h[ft.i]:ut,pt=P.some(t=>t.usd!==void 0)?S(P.reduce((t,l)=>t+(l.usd??0),0)):void 0,wt=c&&m>0?S(m*(c.input-L)/1e6):void 0,Mt=C[0];r.verdict={kind:Mt,...C.length>1?{also:C.slice(1)}:{},said:"",costs:P,...pt!==void 0?{lostUsd:pt}:{},...wt!==void 0?{savedUsd:wt}:{},...O||J||r.wrote[0]||r.readBp?{prefix:(O??J??r.wrote[0])?.h??r.readBp.h}:{},read:m,written:f,...E?{against:{id:E.row.id,at:E.start,...E.end!==void 0?{ended:E.end}:{},inFlight:E.end===void 0||E.end>$,gapMs:$-E.start,...E.row.prewarm?{prewarm:!0}:{}}}:{},...O?{race:!!O.race,...O.readFirst?{readBefore:O.readFirst}:{}}:{},...Z?{brokeAt:Z}:{},...J?.idleMs!==void 0?{idleMs:J.idleMs}:{},...n.prewarm?{prewarm:!0}:{},basis:X}});for(const n of h){const i=n.verdict;if(!n.wrote.length){i.said=st(n,i);continue}const o=new Set,$=new Set;let x=!1;const U=[];for(const r of n.wrote){const a=at[r.ttl],w=(u.get(r.h)??[]).filter(f=>h[f.i].start>n.start&&h[f.i].start-n.start<=a),A=w.filter(f=>f.how==="read"),m=w.filter(f=>f.how==="unknown");for(const f of A)o.add(f.i);for(const f of m)$.add(f.i);n.start+a>g?x=!0:!A.length&&!m.length&&U.push(r)}for(const r of o)$.delete(r);if(o.size&&(i.readBy=o.size),$.size&&(i.maybeReadBy=$.size),x&&(i.open=!0),U.length){const r=n.row,a=r.model?s(r.model,r.tokens?.input??0):void 0;let w=i.costs.find(v=>v.kind==="broken-prefix")?.tokens??0;for(const v of U){if(v.status!=="first")continue;const c=Math.max(0,v.tokens-w);if(w=0,!c)continue;const Q=a?K(a,r.cache.writes,v.ttl):void 0;i.costs.push({kind:"write-nothing-read",tokens:c,estimate:v.estimate||c!==v.tokens,...a?{usd:S(c*(Q-a.input)/1e6),arithmetic:`${M(c)} \xD7 (${_(Q)} \u2212 ${_(a.input)})/M`}:{}})}a&&(i.lostUsd=S(i.costs.reduce((v,c)=>v+(c.usd??0),0)));const A=[i.kind,...i.also??[]],m=A.findIndex(v=>v!=="duplicate-write"&&v!=="broken-prefix"&&v!=="cold");A.splice(m<0?A.length:m,0,"write-nothing-read"),i.kind=A[0];const f=A.slice(1);f.length?i.also=f:delete i.also}i.said=st(n,i)}return new Map(h.map(n=>[n.row.id,n.verdict]))}F(dt,"$t"),R(dt,"Ut"),k(dt,"judgeAgent");function K(e,s,g){const h=Object.entries(s??{}).filter(d=>typeof d[1]=="number"&&d[1]>0);if(h.length>1){const d=h.reduce((n,[,i])=>n+i,0);return h.reduce((n,[i,o])=>n+(e.writes[i]??e.input)*o,0)/d}const u=h[0]?.[0]??g;return e.writes[u]??e.input}F(K,"Y"),R(K,"et"),k(K,"writeRate");function tt(e,s,g,h){const u=k(d=>({kind:"no-cache",said:d,costs:[],basis:h}),"no");if(e.mode==="explicit"&&!e.breakpoints.length)return u("Explicit mode with no breakpoint: it read and wrote nothing.");if(e.mode==="none")return u("No `cache_control`: Anthropic cached nothing of it.");if(s>0&&s<g)return u(`${M(s)} input tokens \u2014 under the ${M(g)}-token minimum: nothing is cached.`)}F(tt,"it"),R(tt,"pt"),k(tt,"structural");function et(e,s,g,h){const u=e.row.cache?.marks??[];let d;for(let i=0;i<u.length;i++){const o=g.get(u[i].h);if(o)for(let $=o.length-1;$>=0;$--){const x=o[$];if(!(x>=h)){if(e.start-s[x].start>e.ttlMs)break;d={i:x,at:i};break}}}if(!d)return;const n=s[d.i];return{i:d.i,id:n.row.id,tokens:u[d.at].t,...u[d.at+1]?{next:u[d.at+1].s}:{},hashes:new Set((n.row.cache?.marks??[]).map(i=>i.h))}}F(et,"st"),R(et,"wt"),k(et,"sharedWith");const H=k(e=>e.split(" \u203A ")[0],"block");function st(e,s){if(s.said)return s.said;const g=e.row,h=g.cache,u=g.tokens?.input??0,d=s.read??0,n=s.written??0,i=h.ttl,o=[],$=s.prewarm?"A prewarm (it answers nothing): it ":"It ";o.push(`${$}read ${M(d)} of its ${M(u)} input tokens from the cache${n?` and wrote ${M(n)}`:""} (${h.mode} mode, ${i}).`);const x=e.wrote.find(a=>a.status==="duplicate");if(x&&s.against){const a=s.against,w=s.readBefore?` ${M(s.readBefore)} call${s.readBefore===1?"":"s"} sent before this one read it.`:"";o.push(s.race?`Duplicate write \u2014 a race: ${a.id}${x.against?.how==="unknown"?" (its count was not kept: it may have)":""} wrote the same prefix (to the end of \xAB${H(x.s)}\xBB) and was still in flight when this one was sent, ${G(a.gapMs)} after it.${w}`:x.against?.how==="read"?`Duplicate write: ${a.id} had read the same prefix (to the end of \xAB${H(x.s)}\xBB) ${G(a.gapMs)} before \u2014 the entry was there, and this call did not read it.`:`Duplicate write: ${a.id}${a.prewarm?" (a prewarm)":""}${x.against?.how==="unknown"?" (its count was not kept: it may have)":""} wrote the same prefix (to the end of \xAB${H(x.s)}\xBB) ${G(a.gapMs)} before${a.ended!==void 0&&a.ended<=e.start?` and had ended ${G(e.start-a.ended)} before this one was sent \u2014 not a race: the write had finished and this call did not read it`:""}.${w}`)}s.brokeAt&&o.push(`Broken prefix: it shares \u2248 ${M(s.brokeAt.tokens)} tokens with ${s.brokeAt.id}, then they part in \xAB${s.brokeAt.region}\xBB \u2014 no breakpoint ends where they part, so it read only ${M(d)}.`);const U=e.wrote.find(a=>a.status==="cold");U&&s.idleMs!==void 0&&o.push(`Cold: the same prefix (to the end of \xAB${H(U.s)}\xBB) was last used ${G(s.idleMs)} before \u2014 past its ${U.ttl} lifetime.`);const r=e.wrote.filter(a=>a.status==="first");return r.length&&o.push(`First writer of the prefix to the end of \xAB${r.map(a=>H(a.s)).join("\xBB, \xAB")}\xBB.`),e.wrote.length&&(s.kind==="write-nothing-read"||s.also?.includes("write-nothing-read")?o.push("No later call of its agent read what it wrote inside its lifetime."):s.readBy?o.push(`${M(s.readBy)} later call${s.readBy===1?"":"s"} read what it wrote.`):s.maybeReadBy?o.push(`${M(s.maybeReadBy)} later call${s.maybeReadBy===1?"":"s"} may have read it (their counts were not kept).`):s.open&&o.push("Its lifetime has not run out: a later call may still read it.")),!e.wrote.length&&d>0&&!s.brokeAt&&o.push(`Read${e.readBp?` to the end of \xAB${H(e.readBp.s)}\xBB`:""}.`),s.lostUsd!==void 0&&s.lostUsd>0&&o.push(`\u2248 ${rt(s.lostUsd)} lost: ${s.costs.filter(a=>a.arithmetic).map(a=>`${a.arithmetic}${a.estimate?" (estimate)":""}`).join(" + ")}.`),s.savedUsd&&o.push(`Its reads saved \u2248 ${rt(s.savedUsd)} against plain input.`),o.join(" ")}F(st,"rt"),R(st,"kt"),k(st,"said");
|
package/lib/ai-cache.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
`,e),p=l<0?h:l;let
|
|
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(`
|
|
3
3
|
`,o-1)+1,h=t.indexOf(`
|
|
4
|
-
`,o),l=t.slice(e,h<0?t.length:h).trim();return l.length>
|
|
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");
|
package/lib/ai-call-groups.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var m=Object.defineProperty;var i=(
|
|
2
|
-
`).toLowerCase();return
|
|
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");
|
package/lib/ai-call-row.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
`).map(n=>n.trim()).find(Boolean)??"",
|
|
3
|
-
`).map(
|
|
1
|
+
"use strict";var B=Object.defineProperty;var m=(e,a)=>B(e,"name",{value:a,configurable:!0});var S=Object.defineProperty,d=m((e,a)=>S(e,"name",{value:a,configurable:!0}),"m"),T=Object.defineProperty,c=d((e,a)=>T(e,"name",{value:a,configurable:!0}),"d");import{aiCallOf as z}from"./ai-call.js";import{aiContextOf as E,aiSplitOf as K}from"./ai-context.js";export function aiCallCacheOf(e){return{mode:e.mode,...e.modeSaid?{modeSaid:!0}:{},ttl:e.ttl,...e.ttlSaid?{ttlSaid:!0}:{},...e.key?{key:!0}:{},breakpoints:e.breakpoints.map(a=>({at:a.at,tokens:a.tokens,...a.ttl?{ttl:a.ttl}:{},...a.implicit?{implicit:!0}:{}})),...e.writes?{writes:{...e.writes}}:{},...e.marks.length?{marks:e.marks}:{}}}m(aiCallCacheOf,"aiCallCacheOf"),d(aiCallCacheOf,"aiCallCacheOf"),c(aiCallCacheOf,"aiCallCacheOf");export function aiRowOut(e){if(!e.cache?.marks)return e;const{marks:a,...t}=e.cache;return{...e,cache:t}}m(aiRowOut,"aiRowOut"),d(aiRowOut,"aiRowOut"),c(aiRowOut,"aiRowOut");export const EMPTY_AI_NAMES={version:1,names:{},merge:{}};export function aiModelUses(e,a){const t=a.toLowerCase(),s=new Map;for(const n of e){if(n.host.toLowerCase()!==t)continue;const r=n.model??"unknown";let o=s.get(r);o||(o={use:{model:r,calls:0,failed:0,unmetered:0,input:0,cached:0,output:0,costUsd:0,priced:0,agents:0,first:n.at,last:n.at},agents:new Set},s.set(r,o));const i=o.use;n.prewarm?i.prewarms=(i.prewarms??0)+1:i.calls+=1,n.failed&&(i.failed+=1),n.tokens?(i.input+=n.tokens.input??0,i.cached+=n.tokens.cached??0,i.output+=n.tokens.output??0):i.unmetered+=1,n.costUsd!==void 0&&(i.costUsd+=n.costUsd,i.priced+=1),o.agents.add(n.agent.key),i.first=Math.min(i.first,n.at),i.last=Math.max(i.last,n.at)}return[...s.values()].map(({use:n,agents:r})=>({...n,agents:r.size})).sort((n,r)=>r.calls-n.calls||r.last-n.last)}m(aiModelUses,"aiModelUses"),d(aiModelUses,"aiModelUses"),c(aiModelUses,"aiModelUses");export function aiAgentUses(e,a){const t=a?.toLowerCase(),s=new Map;for(const n of e){if(t!==void 0&&n.host.toLowerCase()!==t)continue;let r=s.get(n.agent.key);r||(r={use:{key:n.agent.key,name:n.agent.name,from:n.agent.from,calls:0,runs:0,failed:0,input:0,cached:0,written:0,output:0,costUsd:0,priced:0,split:{},models:[],last:n.at},runs:new Set,models:new Map},s.set(n.agent.key,r));const o=r.use;n.prewarm?o.prewarms=(o.prewarms??0)+1:(o.calls+=1,r.runs.add(n.run.key)),n.failed&&(o.failed+=1),o.input+=n.tokens?.input??0,o.cached+=n.tokens?.cached??0,o.written+=n.tokens?.written??0,o.output+=n.tokens?.output??0,n.costUsd!==void 0&&(o.costUsd+=n.costUsd,o.priced+=1);for(const[i,p]of Object.entries(n.split??{}))o.split[i]=(o.split[i]??0)+p;n.model&&r.models.set(n.model,(r.models.get(n.model)??0)+1),o.last=Math.max(o.last,n.at)}return[...s.values()].map(({use:n,runs:r,models:o})=>({...n,runs:r.size,models:[...o].sort((i,p)=>p[1]-i[1]).map(([i])=>i)})).sort((n,r)=>r.input-n.input||r.calls-n.calls)}m(aiAgentUses,"aiAgentUses"),d(aiAgentUses,"aiAgentUses"),c(aiAgentUses,"aiAgentUses");export const MAX_TOOLS=40,MAX_THREAD_CALLS=300,MAX_META=24;const q=160,R="unknown service";export const aiKeyOf=c((e,a)=>`${e}:${a.normalize("NFKD").toLowerCase().replace(/[^a-z0-9:.]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80)||"unnamed"}`,"aiKeyOf");export function humanName(e){const a=e.trim();if(/[A-Z]/.test(a)||/ /.test(a))return a;const t=a.replace(/[-_.]+/g," ").trim();return t?t[0].toUpperCase()+t.slice(1):a}m(humanName,"humanName"),d(humanName,"humanName"),c(humanName,"humanName");const g=c((e,a=q)=>{if(!e)return;const t=e.replace(/\s+/g," ").trim();if(t)return t.length>a?`${t.slice(0,a-1)}\u2026`:t},"line");export function promptTitle(e){const a=e.split(`
|
|
2
|
+
`).map(n=>n.trim()).find(Boolean)??"",t=/^#{1,6}\s+(.+)$/.exec(a);if(t){const n=t[1].split(/\s+[—–]\s+|\s+-\s+|:\s/)[0].replace(/[*_`]/g,"").trim();return n?n.slice(0,60):void 0}const s=/^you are (?:an? |the )?(.+?)(?:[.,;:!]|\s+(?:who|that|which|for|in|on|whose|with|and|following|using|working|based|at|to)\b|$)/i.exec(a);if(s){const n=s[1].trim().split(/\s+/);if(n.length>6||/^(?:going|about|given|now|here|responsible|able|allowed|expected|tasked|asked|helping|working|being|not)$/i.test(n[0]))return;const r=n.join(" ");return r[0].toUpperCase()+r.slice(1)}}m(promptTitle,"promptTitle"),d(promptTitle,"promptTitle"),c(promptTitle,"promptTitle");export function promptOpening(e){const a=e.split(`
|
|
3
|
+
`).map(s=>s.trim()).find(Boolean);if(!a)return;const t=a.replace(/^[#>*\s-]+/,"").split(/\s+/).filter(Boolean);if(!(t.length<3))return t.length>7?`${t.slice(0,7).join(" ")} \u2026`:t.join(" ")}m(promptOpening,"promptOpening"),d(promptOpening,"promptOpening"),c(promptOpening,"promptOpening");export function actionName(e){const a=e.split("::")[0],t=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|[0-9a-f]{8,}|\d{4,})$/i;return a.split(":").map(s=>s.split(".").filter(n=>!t.test(n)).join(".")).filter((s,n,r)=>s||n<r.length-1).join(":").slice(0,120)}m(actionName,"actionName"),d(actionName,"actionName"),c(actionName,"actionName");const h=c((e,a)=>{const t=e.request.headers.find(([s])=>s.toLowerCase()===a)?.[1];if(t===void 0||!a.startsWith("x-lensmcp-")||!t.includes("%"))return t;try{return decodeURIComponent(t)}catch{return t}},"header"),_=c(e=>e!==void 0&&/^\d{1,6}$/.test(e.trim())?Number(e.trim()):void 0,"intOf"),k=c((e,...a)=>{for(const t of a)if(e[t]?.trim())return e[t].trim()},"first");function b(e){const a={};for(const t of e.settings)if(t.name.startsWith("metadata.")){if(Object.keys(a).length>=MAX_META)break;a[t.name.slice(9)]=t.value.slice(0,200)}return a}m(b,"j"),d(b,"T"),c(b,"metaOf");function O(e,a,t){const s=c((f,w)=>({key:aiKeyOf("agent",f),name:humanName(f),from:w}),"named"),n=k(t,"agent","agent_name","agentName","assistant");if(n)return s(n,"metadata");const r=h(e,"x-lensmcp-agent");if(r?.trim())return s(r.trim(),"header");const o=a.system.map(f=>promptTitle(f.text)).find(Boolean);if(o)return s(o,"prompt");const i=a.answer.format?.name;if(i)return s(i,"schema");const p=[...a.tools,...a.answer.toolCalls].map(f=>f.server).find(Boolean);if(p)return s(p,"tools");const l=a.system.map(f=>promptOpening(f.text)).find(Boolean);return l?{key:aiKeyOf("agent",`prompt ${l.replace(/ …$/,"")}`),name:l,from:"prompt"}:s(`${e.service??R} ${a.api==="embeddings"?"embeddings":a.model??a.api}`,"service")}m(O,"U"),d(O,"B"),c(O,"agentOf");function $(e,a,t){const s=c((o,i)=>({key:aiKeyOf("action",o),name:o,from:i}),"named"),n=k(t,"act","action","task","step","operation");if(n&&actionName(n))return s(actionName(n),"metadata");const r=h(e,"x-lensmcp-action");if(r?.trim())return s(actionName(r.trim()),"header");if(a.answer.format?.name)return s(a.answer.format.name,"schema")}m($,"_"),d($,"E"),c($,"actionOf");function C(e){if(e.kind==="message")return g(e.text);if(e.kind==="tool")return g(e.output!==void 0?`${e.tool} \u2192 ${e.output}`:`${e.tool}(${e.arguments})`)}m(C,"N"),d(C,"x"),c(C,"turnLine");function y(e){const a=e.answer;return a.error?g(`error: ${a.error}`):a.refusal?g(`refused: ${a.refusal}`):a.toolCalls.length?g(a.toolCalls.map(t=>`${t.tool}(${t.arguments})`).join(" \xB7 ")):e.embedding?`${e.embedding.vectors??e.embedding.count} vector${(e.embedding.vectors??e.embedding.count)===1?"":"s"}${e.embedding.dimensions?` \xD7 ${e.embedding.dimensions}`:""}`:g(a.text)}m(y,"v"),d(y,"_"),c(y,"saidLine");export function aiCallRow(e,a){const t=z(e);if(!t||!e.ai)return;const s=b(t),n=new Map(t.settings.map(u=>[u.name,u.value])),r=k(s,"run","run_id","runId"),o=h(e,"x-lensmcp-run")?.trim(),i=t.turns.filter(u=>u.kind==="tool").filter(u=>u.output!==void 0&&u.callId).map(u=>u.callId),p=t.answer.toolCalls.map(u=>u.callId).filter(u=>!!u),l=t.usage,f=l?{...l.input!==void 0?{input:l.input}:{},...l.cached?{cached:l.cached}:{},...l.written?{written:l.written}:{},...l.output!==void 0?{output:l.output}:{},...l.reasoning?{reasoning:l.reasoning}:{}}:void 0,w=t.shape==="embedding"||l?.input===void 0?{}:K(E(t,{sections:!1})),v=k(s,"thread","thread_id","threadId","conversation","conversation_id","conversationId","case","case_id","caseId"),x=h(e,"x-lensmcp-thread")?.trim(),I=k(s,"parent_run","parentRun","parent")??h(e,"x-lensmcp-parent")?.trim(),M=$(e,t,s),A=_(s.round),j=_(s.attempt),U=n.get("continues response"),N=[...t.turns].reverse().map(C).find(Boolean),L=t.answer.status==="failed"||!!t.answer.error||(e.status??0)>=400||!!e.error;return{id:e.id,at:e.startedAt,...e.durationMs!==void 0?{durationMs:e.durationMs}:{},...e.status!==void 0?{status:e.status}:{},...L?{failed:!0}:{},service:e.service??R,...e.flowId?{flowId:e.flowId}:{},...e.requestId?{requestId:e.requestId}:{},provider:e.ai.provider,host:e.host,api:t.api,shape:t.shape,...t.model?{model:t.model}:{},...e.response.stream?{streamed:!0}:{},...f&&Object.keys(f).length?{tokens:f}:{},...Object.keys(w).length?{split:w}:{},...t.cache?.prewarm?{prewarm:!0}:{},...t.cache?{cache:aiCallCacheOf(t.cache)}:{},agent:O(e,t,s),run:r?{key:`run:${r}`,from:"metadata"}:o?{key:`run:${o}`,from:"header"}:{key:`run:${e.id}`,from:"alone"},...v?{thread:{key:`thread:${v}`,name:v,from:"metadata"}}:x?{thread:{key:`thread:${x}`,name:x,from:"header"}}:{},...I?{parent:`run:${I}`}:{},...A!==void 0?{round:A}:{},...j!==void 0?{attempt:j}:{},...M?{action:M}:{},...t.answer.format?.name?{schema:t.answer.format.name}:{},...t.tools.length?{tools:t.tools.slice(0,MAX_TOOLS).map(u=>u.name)}:{},...t.answer.toolCalls.length?{called:t.answer.toolCalls.map(u=>u.name)}:{},...p.length?{callIds:p}:{},...i.length?{answers:i}:{},...t.responseId?{responseId:t.responseId}:{},...U?{previousResponseId:U}:{},...Object.keys(s).length?{meta:s}:{},...t.gaps.some(u=>/kept to its first|cut/.test(u))?{cut:!0}:{},...a.content&&N?{asked:N}:{},...a.content&&y(t)?{said:y(t)}:{}}}m(aiCallRow,"aiCallRow"),d(aiCallRow,"aiCallRow"),c(aiCallRow,"aiCallRow");export function linkAiRuns(e){const a=[...e].sort((r,o)=>r.at-o.at||r.id.localeCompare(o.id)),t=new Map,s=new Map;for(const r of a){if(r.run.from==="alone"){const o=r.previousResponseId?t.get(r.previousResponseId):void 0,i=o?void 0:r.answers?.map(l=>s.get(l)).find(Boolean),p=o??i;if(p){const l=o?"chain":"tools";r.run={key:p.run.key,from:p.run.from==="alone"||p.run.from===l?l:p.run.from},p.run.from==="alone"&&(p.run={key:p.run.key,from:l})}}r.responseId&&t.set(r.responseId,r);for(const o of r.callIds??[])s.set(o,r)}const n=new Map;for(const r of a){const o=(n.get(r.run.key)??0)+1;n.set(r.run.key,o),r.step=o}return e}m(linkAiRuns,"linkAiRuns"),d(linkAiRuns,"linkAiRuns"),c(linkAiRuns,"linkAiRuns");export function mergedKey(e,a){let t=a;for(let s=0;s<8&&e.merge[t]&&e.merge[t]!==a;s++)t=e.merge[t];return t}m(mergedKey,"mergedKey"),d(mergedKey,"mergedKey"),c(mergedKey,"mergedKey");export function applyAiNames(e,a){if(!Object.keys(a.names).length&&!Object.keys(a.merge).length)return e;const t=new Map;for(const n of e)t.has(n.agent.key)||t.set(n.agent.key,n.agent),n.action&&!t.has(n.action.key)&&t.set(n.action.key,n.action);const s=c(n=>{const r=mergedKey(a,n.key),o=a.names[r];if(o)return{key:r,name:o,from:"renamed"};if(r===n.key)return n;const i=t.get(r);return{key:r,name:i?.name??humanName(r.replace(/^[a-z]+:/,"")),from:i?.from??n.from}},"resolve");for(const n of e)n.agent=s(n.agent),n.action&&(n.action=s(n.action));return e}m(applyAiNames,"applyAiNames"),d(applyAiNames,"applyAiNames"),c(applyAiNames,"applyAiNames");export function aiNamesOf(e){const a=e&&typeof e=="object"?e:{},t=c(s=>{const n={};if(s&&typeof s=="object"&&!Array.isArray(s))for(const[r,o]of Object.entries(s))/^(agent|action):/.test(r)&&typeof o=="string"&&o.trim()&&(n[r]=o.trim().slice(0,120));return n},"pick");return{version:1,names:t(a.names),merge:t(a.merge)}}m(aiNamesOf,"aiNamesOf"),d(aiNamesOf,"aiNamesOf"),c(aiNamesOf,"aiNamesOf");
|
package/lib/ai-call.js
CHANGED
|
@@ -1,19 +1,19 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
`||d==="\r"||d===" ")continue;const _=
|
|
3
|
-
\r `.includes(
|
|
1
|
+
"use strict";var re=Object.defineProperty;var v=(e,o)=>re(e,"name",{value:o,configurable:!0});var ae=Object.defineProperty,k=v((e,o)=>ae(e,"name",{value:o,configurable:!0}),"v"),ie=Object.defineProperty,f=k((e,o)=>ie(e,"name",{value:o,configurable:!0}),"d");import{aiCacheOf as le}from"./ai-cache.js";const $=f(e=>!!e&&typeof e=="object"&&!Array.isArray(e),"isObj"),t=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 q(e){const o={};for(const[n,i]of e)typeof i=="number"&&Number.isFinite(i)&&i>0&&(o[n]=i);return Object.keys(o).length?{writes:o}:{}}v(q,"q"),k(q,"J"),f(q,"writesOf");function P(e,o){const n=y(o.cache_write_tokens)??y(e.cache_write_tokens),i=u(o.cache_write_tokens_details??e.cache_write_tokens_details);return{...n?{written:n}:{},...q([["30m",i.ttl_30m_tokens],["12h",i.ttl_12h_tokens]])}}v(P,"E"),k(P,"K"),f(P,"openaiWrites");const se=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 o=[];let n=0,i=!1,a=!1,r=!1;const s=e.length,l=f(m=>{const d=o[o.length-1];d&&(d.state="after"),n=m},"ended");for(let m=0;m<s;m++){const d=e[m];if(i){r?r=!1:d==="\\"?r=!0:d==='"'&&(i=!1,a?o[o.length-1].state="colon":l(m+1));continue}if(d===" "||d===`
|
|
2
|
+
`||d==="\r"||d===" ")continue;const _=o[o.length-1];if(d==='"'){i=!0,a=!!_&&_.c==="{"&&_.state==="key";continue}if(d==="{"||d==="["){o.push({c:d,state:d==="{"?"key":"value"}),n=m+1;continue}if(d==="}"||d==="]"){o.pop(),l(m+1);continue}if(d===":"){_&&(_.state="value");continue}if(d===","){_&&(_.state=_.c==="{"?"key":"value");continue}let h=m;for(;h<s&&!`,}]
|
|
3
|
+
\r `.includes(e[h]);)h++;if(h>=s)break;l(h),m=h-1}const c=o.map(m=>m.c==="{"?"}":"]").reverse().join("");if(i&&!a)for(let m=0;m<=6;m++)try{return{value:JSON.parse(`${e.slice(0,s-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 o=e.split("?")[0].replace(/\/+$/,"");if(/\/responses$/.test(o))return"responses";if(/\/chat\/completions$/.test(o))return"chat";if(/\/embeddings$/.test(o))return"embeddings";if(/\/messages$/.test(o))return"messages"}v(aiApiOf,"aiApiOf"),k(aiApiOf,"aiApiOf"),f(aiApiOf,"aiApiOf");export function splitToolName(e,o){if(o)return{server:o,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,o,n={})=>({...n.callId?{callId:n.callId}:{},name:e,...splitToolName(e,n.server),arguments:o,...n.output!==void 0?{output:n.output}:{},...n.error?{error:n.error}:{}}),"toolCall");function J(e,o,n){if(!e)return;if(e.omitted==="ai"){n.push(`The ${o==="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 i=parseJsonPrefix(e.text);if(i)return(i.cut||e.truncated)&&n.push(`The ${o} was kept to its first ${se(e.kept)} of ${se(e.size)} \u2014 read as far as it goes; what follows is not shown (the ${o==="request"?"end of the conversation":"rest of the answer"}, marked ${CUT_MARK}).`),i.value}v(J,"M"),k(J,"N"),f(J,"readBody");function M(e){if(e.data===void 0||e.data==="[DONE]")return;const o=parseJsonPrefix(e.data);return o&&$(o.value)?{v:o.value,cut:o.cut}:void 0}v(M,"J"),k(M,"E"),f(M,"eventJson");function I(e){if(typeof e=="string")return{text:e,attachments:[]};const o=[],n=[];for(const i of w(e)){if(typeof i=="string"){o.push(i);continue}const a=u(i),r=t(a.type)??"",s=t(a.text)??t(a.refusal);s!==void 0?o.push(s):/image/.test(r)?n.push(t(a.detail)?`image (${t(a.detail)})`:"image"):/file|document/.test(r)?n.push(`file ${t(a.filename)??t(u(a.source).media_type)??t(a.file_id)??""}`.trim()):/audio/.test(r)?n.push("audio"):r&&n.push(r)}return{text:o.join(`
|
|
4
4
|
|
|
5
|
-
`),attachments:n}}v(O,"I"),f(
|
|
5
|
+
`),attachments:n}}v(I,"O"),k(I,"I"),f(I,"contentOf");const E=f(e=>typeof e=="string"?e:Array.isArray(e)&&I(e).text||j(e),"outputOf");function C(e,o){const n=[];for(const[a,r]of o){let s=e;for(const c of a.split("."))s=u(s)[c];if(s==null)continue;const l=typeof s=="string"?s:typeof s=="number"||typeof s=="boolean"?String(s):$(s)&&t(s.name)?`${t(s.type)??"tool"} ${t(s.name)}`:$(s)&&t(s.type)?t(s.type):JSON.stringify(s);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,"I"),k(C,"O"),f(C,"settingsOf");function S(e,o,n,i){const a=o?e.byCallId.get(o):void 0;if(a){a.output=n,i&&(a.error=i);return}e.call.turns.push({kind:"tool",...A("(an earlier call)","",{callId:o,output:n,error:i})})}v(S,"C"),k(S,"T"),f(S,"addOutput");function O(e,o){const n={kind:"tool",...o};e.call.turns.push(n),o.callId&&e.byCallId.set(o.callId,n)}v(O,"j"),k(O,"S"),f(O,"addCall");const ce=[["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(([o])=>o!=="type"&&o!=="id"&&o!=="status"))),"builtInCall");function W(e,o){const n=t(o.type)??(o.role?"message":"");if(n==="message"){const i=t(o.role)??"user",{text:a,attachments:r}=I(o.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(t(o.name)??"?",t(o.arguments)??j(o.input),{callId:t(o.call_id)}));else if(n==="function_call_output"||n==="custom_tool_call_output"||n==="computer_call_output"||n==="local_shell_call_output")S(e,t(o.call_id),E(o.output));else if(n==="mcp_call")O(e,A(t(o.name)??"?",t(o.arguments)??"",{callId:t(o.id),server:t(o.server_label),...o.output!==void 0&&o.output!==null?{output:E(o.output)}:{},error:t(o.error)}));else if(n==="mcp_list_tools"){const i=w(o.tools).map(a=>t(u(a).name)).filter(Boolean);O(e,A("list_tools","",{server:t(o.server_label),output:i.join(", ")}))}else if(n==="reasoning"){const i=w(o.summary).map(a=>t(u(a).text)).filter(Boolean).join(`
|
|
6
6
|
|
|
7
|
-
`);
|
|
7
|
+
`);e.call.turns.push({kind:"reasoning",...i?{text:i}:{}})}else n&&O(e,A(n.replace(/_call$/,""),ne(o),{callId:t(o.call_id)??t(o.id)}))}v(W,"H"),k(W,"D"),f(W,"responsesItem");function D(e){return w(e.tools).map(o=>{const n=u(o),i=t(n.type)??"function";if(i==="mcp"){const r=t(n.server_label)??"mcp",s=w(n.allowed_tools).map(l=>t(l)).filter(Boolean);return{name:r,server:r,tool:s.length?s.join(", "):"every tool",type:i,...t(n.server_description)??t(n.server_url)?{description:t(n.server_description)??t(n.server_url)}:{},called:0}}const a=t(n.name)??i;return{name:a,...splitToolName(a),type:i,...t(n.description)?{description:t(n.description)}:{},...n.parameters!==void 0?{parameters:n.parameters}:{},...typeof n.strict=="boolean"?{strict:n.strict}:{},called:0}})}v(D,"R"),k(D,"Q"),f(D,"responsesTools");function K(e,o){const n=e.call.answer;t(o.status)&&(n.status=t(o.status));const i=t(u(o.incomplete_details).reason);i&&(n.finish=i);const a=u(o.error);t(a.message)&&(n.error=t(a.message)),t(o.model)&&(e.call.model??=t(o.model)),t(o.id)&&(e.call.responseId=t(o.id)),L(e,w(o.output).map(u));const r=u(o.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)}:{},...P(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,"L"),f(K,"responsesAnswer");function L(e,o){const n=e.call.answer,i=[],a=[];for(const r of o){const s=t(r.type);if(s==="message")for(const l of w(r.content).map(u))t(l.refusal)?n.refusal=t(l.refusal):t(l.text)!==void 0&&i.push(t(l.text));else if(s==="function_call"||s==="custom_tool_call")n.toolCalls.push(A(t(r.name)??"?",t(r.arguments)??j(r.input),{callId:t(r.call_id)}));else if(s==="mcp_call")n.toolCalls.push(A(t(r.name)??"?",t(r.arguments)??"",{callId:t(r.id),server:t(r.server_label),...r.output!==void 0&&r.output!==null?{output:E(r.output)}:{},error:t(r.error)}));else if(s==="reasoning"){const l=w(r.summary).map(c=>t(u(c).text)).filter(Boolean).join(`
|
|
8
8
|
|
|
9
|
-
`);l&&a.push(l)}else
|
|
9
|
+
`);l&&a.push(l)}else s&&s!=="mcp_list_tools"&&n.toolCalls.push(A(s.replace(/_call$/,""),ne(r),{callId:t(r.call_id)??t(r.id)}))}i.length&&(n.text=i.join(`
|
|
10
10
|
|
|
11
11
|
`)),a.length&&(n.reasoning=a.join(`
|
|
12
12
|
|
|
13
|
-
`))}v(z,"F"),f(
|
|
13
|
+
`))}v(L,"z"),k(L,"F"),f(L,"responsesOutput");function Z(e,o,n){let i,a=0;const r=new Map,s=new Set,l=new Map,c=new Map,m=new Map;for(const _ of o){const h=M(_);if(!h)continue;h.cut&&a++;const p=h.v,g=t(p.type)??_.event,x=y(p.output_index)??0;if(g==="response.completed"||g==="response.incomplete"||g==="response.failed"){if(!h.cut&&$(p.response))i=p.response;else if($(p.response)){const b=p.response;t(b.status)&&(e.call.answer.status=t(b.status))}}else if(g==="response.created"||g==="response.in_progress"){const b=u(p.response);t(b.model)&&(e.call.model??=t(b.model)),t(b.id)&&(e.call.responseId??=t(b.id))}else g==="response.output_item.added"||g==="response.output_item.done"?$(p.item)&&(!s.has(x)||!h.cut)&&(r.set(x,{...r.get(x)??{},...p.item}),g.endsWith(".done")&&!h.cut&&s.add(x)):g==="response.output_text.delta"||g==="response.refusal.delta"?l.set(x,(l.get(x)??"")+(t(p.delta)??"")):g==="response.output_text.done"&&!h.cut&&t(p.text)!==void 0?l.set(x,t(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)??"")+(t(p.delta)??"")):(g==="response.function_call_arguments.done"||g==="response.mcp_call_arguments.done")&&!h.cut&&t(p.arguments)!==void 0?c.set(x,t(p.arguments)):g==="response.reasoning_summary_text.delta"?m.set(x,(m.get(x)??"")+(t(p.delta)??"")):(g==="error"||g==="response.error")&&(e.call.answer.error=t(p.message)??t(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(s.has(_))return h;const p=t(h.type);return p==="message"&&l.has(_)?{...h,content:[{type:"output_text",text:l.get(_)}]}:(p==="function_call"||p==="mcp_call")&&c.has(_)?{...h,arguments:c.get(_)}:p==="custom_tool_call"&&c.has(_)?{...h,input:c.get(_)}:p==="reasoning"&&m.has(_)?{...h,summary:[{type:"summary_text",text:m.get(_)}]}:h});for(const[_,h]of l)r.has(_)||d.push({type:"message",content:[{type:"output_text",text:h}]});L(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,"V"),f(Z,"responsesStream");function H(e,o,n,i){const a=e.call;t(o.model)&&(a.model=t(o.model)),t(o.instructions)&&a.system.push({source:"instructions",text:t(o.instructions)});const r=o.input;if(typeof r=="string")a.turns.push({kind:"message",role:"user",text:r});else for(const l of w(r))$(l)&&W(e,l);a.tools=D(o),a.settings=C(o,ce);const s=u(u(o.text).format);t(s.type)&&s.type!=="text"&&(a.answer.format={type:t(s.type),...t(s.name)?{name:t(s.name)}:{},...s.schema!==void 0?{schema:s.schema}:{},...typeof s.strict=="boolean"?{strict:s.strict}:{}}),N(e,n,i,l=>K(e,l),l=>Z(e,l,i))}v(H,"Q"),k(H,"X"),f(H,"responsesCall");const ue=[["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 z(e){const o=w(e.tool_calls).map(u).map(i=>{const a=u(i.function);return A(t(a.name)??t(u(i.custom).name)??"?",t(a.arguments)??t(u(i.custom).input)??"",{callId:t(i.id)})}),n=u(e.function_call);return t(n.name)&&o.push(A(t(n.name),t(n.arguments)??"",{})),o}v(z,"L"),k(z,"P"),f(z,"chatCalls");function F(e,o){const n=e.call.answer;t(o.model)&&(e.call.model??=t(o.model)),t(o.id)&&(e.call.responseId??=t(o.id));const i=u(w(o.choices)[0]),a=u(i.message),r=I(a.content).text;r&&(n.text=r),t(a.refusal)&&(n.refusal=t(a.refusal));const s=t(a.reasoning_content)??t(a.reasoning);s&&(n.reasoning=s),n.toolCalls.push(...z(a)),t(i.finish_reason)&&(n.finish=t(i.finish_reason)),n.status=n.finish?"completed":n.status??"unknown";const l=u(o.error);t(l.message)&&(n.error=t(l.message));const c=u(o.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)}:{},...P(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"),k(F,"U"),f(F,"chatAnswer");function Q(e,o,n){let i="",a="",r="",s,l,c,m,d=0;const _=new Map;for(const p of o){const g=M(p);if(!g)continue;g.cut&&d++,c??=t(g.v.model),m??=t(g.v.id),$(g.v.usage)&&(l=g.v.usage),$(g.v.error)&&(e.call.answer.error=t(g.v.error.message)??"the stream reported an error");const x=u(w(g.v.choices)[0]),b=u(x.delta);i+=t(b.content)??"",a+=t(b.reasoning_content)??t(b.reasoning)??"",r+=t(b.refusal)??"";for(const B of w(b.tool_calls).map(u)){const te=y(B.index)??0,T=_.get(te)??{name:"",args:""},oe=u(B.function);t(B.id)&&(T.id=t(B.id)),T.name+=t(oe.name)??"",T.args+=t(oe.arguments)??"",_.set(te,T)}t(x.finish_reason)&&(s=t(x.finish_reason))}const h={content:i,...a?{reasoning_content:a}:{},...r?{refusal:r}:{},tool_calls:[..._.entries()].sort(([p],[g])=>p-g).map(([,p])=>({id:p.id,function:{name:p.name,arguments:p.args}}))};F(e,{...c?{model:c}:{},...m?{id:m}:{},choices:[{message:h,...s?{finish_reason:s}:{}}],...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(Q,"V"),k(Q,"ee"),f(Q,"chatStream");function R(e,o,n,i){const a=e.call;t(o.model)&&(a.model=t(o.model));for(const s of w(o.messages).map(u)){const l=t(s.role)??"user",{text:c,attachments:m}=I(s.content);if(l==="system")a.system.push({source:"system message",text:c});else if(l==="tool")S(e,t(s.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 z(s))O(e,d)}}a.tools=[...w(o.tools).map(u),...w(o.functions).map(s=>({type:"function",function:s}))].map(s=>{const l=u(s.function),c=t(s.type)??"function",m=t(l.name)??t(u(s.custom).name)??c;return{name:m,...splitToolName(m),type:c,...t(l.description)??t(u(s.custom).description)?{description:t(l.description)??t(u(s.custom).description)}:{},...l.parameters!==void 0?{parameters:l.parameters}:{},...typeof l.strict=="boolean"?{strict:l.strict}:{},called:0}}),a.settings=C(o,ue);const r=u(o.response_format);if(t(r.type)&&r.type!=="text"){const s=u(r.json_schema);a.answer.format={type:t(r.type),...t(s.name)?{name:t(s.name)}:{},...s.schema!==void 0?{schema:s.schema}:{},...typeof s.strict=="boolean"?{strict:s.strict}:{}}}N(e,n,i,s=>F(e,s),s=>Q(e,s,i))}v(R,"X"),k(R,"te"),f(R,"chatCall");const pe=[["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 V(e,o,n){if(typeof n=="string"){e.call.turns.push({kind:"message",role:o,text:n});return}const i=[],a=[],r=f(()=>{(i.length||a.length)&&e.call.turns.push({kind:"message",role:o,text:i.join(`
|
|
14
14
|
|
|
15
|
-
`),...a.length?{attachments:[...a]}:{}}),i.length=0,a.length=0},"flush");for(const
|
|
15
|
+
`),...a.length?{attachments:[...a]}:{}}),i.length=0,a.length=0},"flush");for(const s of w(n).map(u)){const l=t(s.type)??"";l==="text"?i.push(t(s.text)??""):l==="tool_use"||l==="server_tool_use"||l==="mcp_tool_use"?(r(),O(e,A(t(s.name)??"?",j(s.input),{callId:t(s.id),server:t(s.server_name)}))):l==="tool_result"||l==="mcp_tool_result"||/_tool_result$/.test(l)?(r(),S(e,t(s.tool_use_id),E(s.content),s.is_error===!0?"the tool reported an error":void 0)):l==="thinking"||l==="redacted_thinking"?(r(),e.call.turns.push({kind:"reasoning",...t(s.thinking)?{text:t(s.thinking)}:{}})):a.push(l==="image"?"image":l==="document"?`document ${t(s.title)??""}`.trim():l)}r()}v(V,"Y"),k(V,"se"),f(V,"anthropicBlocks");function U(e,o){const n=e.call.answer;t(o.model)&&(e.call.model??=t(o.model)),t(o.id)&&(e.call.responseId??=t(o.id));const i=[],a=[];for(const l of w(o.content).map(u)){const c=t(l.type);c==="text"?i.push(t(l.text)??""):c==="tool_use"||c==="server_tool_use"||c==="mcp_tool_use"?n.toolCalls.push(A(t(l.name)??"?",j(l.input),{callId:t(l.id),server:t(l.server_name)})):c==="thinking"&&a.push(t(l.thinking)??"")}i.length&&(n.text=i.join(`
|
|
16
16
|
|
|
17
17
|
`)),a.length&&(n.reasoning=a.join(`
|
|
18
18
|
|
|
19
|
-
`)),
|
|
19
|
+
`)),t(o.stop_reason)&&(n.finish=t(o.stop_reason)),n.status=o.type==="error"?"failed":n.finish?"completed":n.status??"unknown";const r=u(o.error);t(r.message)&&(n.error=t(r.message));const s=u(o.usage);if(Object.keys(s).length){const l=y(s.input_tokens),c=y(s.cache_read_input_tokens),m=y(s.output_tokens);e.call.usage={...l!==void 0?{input:l+(c??0)+(y(s.cache_creation_input_tokens)??0)}:{},...c!==void 0?{cached:c}:{},...y(s.cache_creation_input_tokens)?{written:y(s.cache_creation_input_tokens)}:{},...q([["5m",u(s.cache_creation).ephemeral_5m_input_tokens],["1h",u(s.cache_creation).ephemeral_1h_input_tokens]]),...m!==void 0?{output:m}:{}}}}v(U,"F"),k(U,"W"),f(U,"anthropicAnswer");function X(e,o,n){let i={};const a=new Map,r=new Map;let s={},l=0;for(const c of o){const m=M(c);if(!m)continue;m.cut&&l++;const d=m.v,_=t(d.type)??c.event,h=y(d.index)??0;if(_==="message_start")i=u(d.message),s={...u(i.usage)};else if(_==="content_block_start")a.set(h,{...u(d.content_block)});else if(_==="content_block_delta"){const p=u(d.delta),g=a.get(h)??{};t(p.text)!==void 0&&(g.text=(t(g.text)??"")+t(p.text)),t(p.thinking)!==void 0&&(g.thinking=(t(g.thinking)??"")+t(p.thinking)),t(p.partial_json)!==void 0&&r.set(h,(r.get(h)??"")+t(p.partial_json)),a.set(h,g)}else _==="message_delta"?(i={...i,...u(d.delta)},s={...s,...u(d.usage)}):_==="error"&&(e.call.answer.error=t(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(e,{...i,content:[...a.entries()].sort(([c],[m])=>c-m).map(([,c])=>c),usage:s}),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(X,"ee"),k(X,"oe"),f(X,"anthropicStream");function G(e,o,n,i){const a=e.call;t(o.model)&&(a.model=t(o.model));const r=o.system;if(typeof r=="string"&&r)a.system.push({source:"system",text:r});else for(const s of w(r).map(u))t(s.text)&&a.system.push({source:"system",text:t(s.text)});for(const s of w(o.messages).map(u))V(e,t(s.role)??"user",s.content);a.tools=[...w(o.tools).map(u).map(s=>{const l=t(s.name)??t(s.type)??"tool";return{name:l,...splitToolName(l),type:t(s.type)??"custom",...t(s.description)?{description:t(s.description)}:{},...s.input_schema!==void 0?{parameters:s.input_schema}:{},called:0}}),...w(o.mcp_servers).map(u).map(s=>({name:t(s.name)??"mcp",server:t(s.name)??"mcp",tool:"every tool",type:"mcp",...t(s.url)?{description:t(s.url)}:{},called:0}))],a.settings=C(o,pe),N(e,n,i,s=>U(e,s),s=>X(e,s,i))}v(G,"te"),k(G,"re"),f(G,"anthropicCall");function Y(e,o,n,i){const a=e.call;t(o.model)&&(a.model=t(o.model));const r=o.input,s=typeof r=="string"?[r]:w(r),l=s.slice(0,200).map(p=>typeof p=="string"?p:typeof p=="number"?`token ${p}`:Array.isArray(p)?`${p.length} tokens`:j(p)),c=s.length>0&&s.every(p=>typeof p=="number");a.embedding={inputs:c?[`${s.length} tokens`]:l,count:c?1:s.length,...y(o.dimensions)!==void 0?{dimensions:y(o.dimensions)}:{}},a.settings=C(o,[["dimensions","dimensions"],["encoding_format","encoding"],["user","user"]]);const m=u(J(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 _=u(m.usage);y(_.prompt_tokens)!==void 0&&(a.usage={input:y(_.prompt_tokens),...y(_.total_tokens)!==void 0?{total:y(_.total_tokens)}:{}}),a.answer.status=n.status!==void 0&&n.status<400?"completed":"failed";const h=u(m.error);t(h.message)&&(a.answer.error=t(h.message))}v(Y,"se"),k(Y,"ae"),f(Y,"embeddingsCall");function N(e,o,n,i,a){const r=o.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}a(r.events),r.cut&&n.push(`The stream was cut after ${r.events.length.toLocaleString("en-US")} of its ${r.total.toLocaleString("en-US")} events \u2014 what came after is not shown.`);return}const s=J(o.response.body,"answer",n);$(s)?i(s):o.error&&(e.call.answer.error=o.error),e.call.answer.status||(e.call.answer.status=o.error||(o.status??0)>=400?"failed":"unknown")}v(N,"T"),k(N,"M"),f(N,"answerOf");function ee(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(o=>o.kind==="tool")?"tools":e.turns.filter(o=>o.kind==="message"&&(o.role==="user"||o.role==="assistant")).length>1?"chat":"prompt"}v(ee,"oe"),k(ee,"ie"),f(ee,"shapeOf");export function aiCallOf(e){if(!e.ai)return;const o=aiApiOf(e.path);if(!o)return;const n=[],i={call:{provider:e.ai.provider,api:o,shape:"prompt",settings:[],system:[],turns:[],tools:[],answer:{toolCalls:[]},gaps:n},byCallId:new Map},a=u(J(e.request.body,"request",n));o==="responses"?H(i,a,e,n):o==="chat"?R(i,a,e,n):o==="messages"?G(i,a,e,n):Y(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 s=new Map;for(const c of r.turns)c.kind==="tool"&&s.set(c.name,(s.get(c.name)??0)+1);for(const c of r.answer.toolCalls)s.set(c.name,(s.get(c.name)??0)+1);for(const c of r.tools)c.called=s.get(c.name)??0;r.shape=ee(r);const l=le(o,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 o=e.trim()?parseJsonPrefix(e):void 0;return o&&($(o.value)||Array.isArray(o.value))?{value:o.value,text:e}:{text:e}}v(prettyJson,"prettyJson"),k(prettyJson,"prettyJson"),f(prettyJson,"prettyJson");
|