@lensmcp/protocol-types 1.26.32 → 1.26.33

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 (52) hide show
  1. package/lib/account-drain.js +1 -1
  2. package/lib/ai-cache-facts.js +1 -1
  3. package/lib/ai-cache-verdict.js +1 -1
  4. package/lib/ai-cache.js +3 -3
  5. package/lib/ai-call-groups.js +2 -2
  6. package/lib/ai-call-row.js +3 -3
  7. package/lib/ai-call.js +9 -9
  8. package/lib/ai-compare.js +3 -3
  9. package/lib/ai-context.js +6 -6
  10. package/lib/ai-origins.js +9 -9
  11. package/lib/ai-together.js +5 -5
  12. package/lib/bounded-clone.js +1 -1
  13. package/lib/bounded-map.js +1 -1
  14. package/lib/bounded-writer.js +1 -1
  15. package/lib/canvas-attachments.js +1 -1
  16. package/lib/canvas-catalog.js +3 -3
  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.js +1 -1
  22. package/lib/capture-demand.js +1 -1
  23. package/lib/dashboard-path.js +1 -1
  24. package/lib/docker-errors.js +1 -1
  25. package/lib/docker-jobs.js +1 -1
  26. package/lib/docker-report.js +2 -2
  27. package/lib/docker-runs.js +3 -3
  28. package/lib/error-cause.js +6 -6
  29. package/lib/error-dismissal.js +1 -1
  30. package/lib/error-verdict.js +3 -3
  31. package/lib/event-loop.js +1 -1
  32. package/lib/expected-failure.js +2 -2
  33. package/lib/finding-proof.js +1 -1
  34. package/lib/flood-guard.js +1 -1
  35. package/lib/goal-design.js +1 -1
  36. package/lib/host-agents.js +1 -1
  37. package/lib/lens-hosts.js +1 -1
  38. package/lib/lint-coverage.js +1 -1
  39. package/lib/lint-ignores.js +2 -2
  40. package/lib/log-query.js +1 -1
  41. package/lib/metrics-reset.js +1 -1
  42. package/lib/overseer-findings.js +1 -1
  43. package/lib/peers.js +1 -1
  44. package/lib/perf-rules.js +1 -1
  45. package/lib/pod-memory.js +1 -1
  46. package/lib/producer-health.js +1 -1
  47. package/lib/remote-instances.js +1 -1
  48. package/lib/sources.js +1 -1
  49. package/lib/static-checks.js +1 -1
  50. package/lib/system-report.js +1 -1
  51. package/lib/team.js +1 -1
  52. package/package.json +1 -1
package/lib/ai-compare.js CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var ke=Object.defineProperty;var k=(e,t)=>ke(e,"name",{value:t,configurable:!0});var ve=Object.defineProperty,r=k((e,t)=>ve(e,"name",{value:t,configurable:!0}),"r");import{aiCacheRequestOf as xe,aiCacheSections as ae}from"./ai-cache.js";import{estimateTokens as ye}from"./ai-context.js";export const AI_SPEED_SKEW=.15,AI_SPEED_MIN_OUTPUT=1e3,AI_COMPARE_MAX_CALLS=24,AI_COMPARE_MAX_RUNS=20,AI_COMPARE_MAX_SECTIONS=30;const ie=200,V=r(e=>Math.round(e).toLocaleString("en-US"),"fmt"),C=r(e=>Math.round(e*1e6)/1e6,"usd"),Me=r(e=>{const t=Math.abs(e);return`$${t===0?"0":t<.001?Number(e.toPrecision(2)).toString():t<.01?e.toFixed(4):e.toFixed(3)}`},"money"),Oe=r(e=>e>=9?`\xD7${Math.round(e+1).toLocaleString("en-US")}`:`${e>0?"+":e<0?"\u2212":""}${Math.abs(Math.round(e*100))}%`,"pct"),je=r(e=>e<1e3?`${Math.round(e)} ms`:`${(e/1e3).toFixed(e<1e4?1:0)} s`,"secs"),J=r(e=>Math.round(e*1e3)/1e3,"round3");function G(e,t){return t==="usd"?Me(e):t==="ms"?je(e):t==="share"?`${Math.round(e*100)}%`:t==="tok/s"?`${e.toFixed(1)} tok/s`:V(e)}k(G,"G"),r(G,"show");const Se=r((e,t)=>e.at-t.at||e.id.localeCompare(t.id),"byTime"),Ae=r(e=>e.tokens?.input!==void 0,"counted");function H(e){const t=new Map;for(const n of e.rows){const s=e.unit==="flow"?n.flowId??"(no flow)":n.run.key,a=t.get(s);a?a.push(n):t.set(s,[n])}return[...t].map(([n,s])=>({key:n,rows:s.sort(Se)})).sort((n,s)=>n.rows[0].at-s.rows[0].at||n.key.localeCompare(s.key))}k(H,"H"),r(H,"repetitionsOf");function D(e){let t;const n=r(s=>s.rows.filter(a=>!a.prewarm).length,"answering");for(const s of e)(!t||n(s)>n(t))&&(t=s);return t}k(D,"V"),r(D,"diffedOf");function Q(e){const t=e.tokens?.written??0;if(!t)return{};const n=e.cache?.writes,s=n?Object.values(n).reduce((c,u)=>c+(u??0),0):0;if(n&&s>=t)return{...n};const a=e.cache?.ttl??"30m";return{...n??{},[a]:(n?.[a]??0)+t-s}}k(Q,"ee"),r(Q,"writesOf");function Z(e,t){const n=e.tokens;if(!n||n.input===void 0||!e.model)return;const s=t(e.model,n.input);if(!s)return;const a=n.cached??0,c=n.written??0,u=Math.max(0,n.input-a-c);let d=0;for(const[b,O]of Object.entries(Q(e)))d+=O*(s.writes[b]??s.input);const l={plain:u*s.input/1e6,read:a*(s.cacheRead??s.input)/1e6,written:d/1e6,output:(n.output??0)*s.output/1e6},i=l.plain+l.read+l.written;return{...l,input:i,total:i+l.output}}k(Z,"te"),r(Z,"callUsd");const _e=r(e=>({plain:C(e.plain),read:C(e.read),written:C(e.written),input:C(e.input),output:C(e.output),total:C(e.total)}),"usdOut"),re=r(e=>!e.prewarm&&e.durationMs&&e.durationMs>0&&(e.tokens?.output??0)>=AI_SPEED_MIN_OUTPUT?e.tokens.output/e.durationMs*1e3:void 0,"speedOf"),le=r(e=>{if(!e.length)return;const t=[...e].sort((s,a)=>s-a),n=Math.floor(t.length/2);return t.length%2?t[n]:(t[n-1]+t[n])/2},"median");function ee(e,t,n){const s={input:0,plain:0,read:0,written:0,output:0,reasoning:0},a={};let c,u=0,d=0;for(const m of t){if(!Ae(m)){d++;continue}const w=m.tokens;s.input+=w.input,s.read+=w.cached??0,s.written+=w.written??0,s.plain+=Math.max(0,w.input-(w.cached??0)-(w.written??0)),s.output+=w.output??0,s.reasoning+=w.reasoning??0;for(const[h,f]of Object.entries(Q(m)))a[h]=(a[h]??0)+f;const $=Z(m,n);if(!$){u++;continue}c=c?{plain:c.plain+$.plain,read:c.read+$.read,written:c.written+$.written,input:c.input+$.input,output:c.output+$.output,total:c.total+$.total}:$}Object.keys(a).length&&(s.writes=a);const l=t.filter(m=>m.durationMs!==void 0),i=t.filter(m=>!m.prewarm),b=i.filter(m=>m.durationMs!==void 0).reduce((m,w)=>!m||w.durationMs>m.durationMs?w:m,void 0),O=b?.durationMs&&b.tokens?.output!==void 0?b.tokens.output/b.durationMs*1e3:void 0,x=le(i.map(re).filter(m=>m!==void 0));return{key:e,at:t[0].at,calls:i.length,prewarms:t.length-i.length,failed:t.filter(m=>m.failed).length,uncounted:d,tokens:s,...s.output?{reasoningShare:J(s.reasoning/s.output)}:{},...c?{usd:_e(c)}:{},...u?{unpriced:u}:{},...l.length?{wallMs:Math.max(...l.map(m=>m.at+m.durationMs))-t[0].at}:{},...b?{slowest:{id:b.id,ms:b.durationMs,...b.tokens?.output!==void 0?{output:b.tokens.output}:{},...O!==void 0?{tokPerSec:Math.round(O*10)/10}:{}}}:{},...x!==void 0?{tokPerSec:Math.round(x*10)/10}:{}}}k(ee,"oe"),r(ee,"runOf");const Be=[{key:"calls",label:"calls (a prewarm apart)",unit:"calls",of:r(e=>e.calls,"of")},{key:"input",label:"input tokens",unit:"tokens",of:r(e=>e.tokens.input,"of"),counts:!0},{key:"plain",label:"input, plain (neither read nor written)",unit:"tokens",of:r(e=>e.tokens.plain,"of"),counts:!0},{key:"read",label:"input, read from the cache",unit:"tokens",of:r(e=>e.tokens.read,"of"),counts:!0},{key:"written",label:"input, written to the cache",unit:"tokens",of:r(e=>e.tokens.written,"of"),counts:!0},{key:"output",label:"output tokens",unit:"tokens",of:r(e=>e.tokens.output,"of"),counts:!0},{key:"reasoningShare",label:"reasoning share of the output",unit:"share",of:r(e=>e.reasoningShare,"of"),counts:!0},{key:"plainUsd",label:"input $, plain",unit:"usd",of:r(e=>e.usd?.plain,"of"),counts:!0},{key:"readUsd",label:"input $, read",unit:"usd",of:r(e=>e.usd?.read,"of"),counts:!0},{key:"writtenUsd",label:"input $, written",unit:"usd",of:r(e=>e.usd?.written,"of"),counts:!0},{key:"inputUsd",label:"input $",unit:"usd",of:r(e=>e.usd?.input,"of"),counts:!0},{key:"outputUsd",label:"output $",unit:"usd",of:r(e=>e.usd?.output,"of"),counts:!0},{key:"totalUsd",label:"total $",unit:"usd",of:r(e=>e.usd?.total,"of"),counts:!0},{key:"wallMs",label:"the stage\u2019s wall time",unit:"ms",of:r(e=>e.wallMs,"of")},{key:"slowestMs",label:"its slowest call",unit:"ms",of:r(e=>e.slowest?.ms,"of")},{key:"tokPerSec",label:"provider speed (median output tokens a second)",unit:"tok/s",of:r(e=>e.tokPerSec,"of")}];function te(e,t){const n=e.map(t.of).filter(u=>typeof u=="number"&&Number.isFinite(u)),s=t.counts&&e.some(u=>u.uncounted>0||t.unit==="usd"&&(u.unpriced??0)>0);if(!n.length)return s?{partial:!0}:{};const a=n.reduce((u,d)=>u+d,0)/n.length,c={value:t.unit==="usd"?C(a):t.unit==="share"?J(a):Math.round(a*10)/10,...s?{partial:!0}:{}};if(n.length>=2){const u=Math.sqrt(n.reduce((l,i)=>l+(i-a)**2,0)/(n.length-1)),d=r(l=>t.unit==="usd"?C(l):t.unit==="share"?J(l):Math.round(l*10)/10,"r");c.spread={runs:n.length,min:d(Math.min(...n)),max:d(Math.max(...n)),mean:d(a),sd:d(u),...a?{cv:J(u/Math.abs(a))}:{}}}return c}k(te,"ae"),r(te,"valueOf");function ue(e,t){if(!e.spread&&!t.spread)return"none";if(e.spread&&t.spread)return e.spread.max<t.spread.min||t.spread.max<e.spread.min?"beyond":"within";const n=e.spread??t.spread,s=e.spread?t.value:e.value;return s===void 0?"none":s<n.min||s>n.max?"beyond":"within"}k(ue,"Me"),r(ue,"noiseOf");function de(e,t,n,s,a,c){const u=te(s,e),d=te(a,e),l=ue(u,d),i=u.value!==void 0&&d.value!==void 0?d.value-u.value:void 0,b=i!==void 0&&u.value?J(i/u.value):void 0,O=e.unit==="ms",x=r((h,f)=>f.value===void 0?`${h.name} \u2014`:`${h.name} ${G(f.value,e.unit)}${f.spread?` (${G(f.spread.min,e.unit)}\u2013${G(f.spread.max,e.unit)} over ${f.spread.runs})`:""}`,"side"),m=l==="none"?u.value===void 0||d.value===void 0?"nothing to compare":"one run a side: no noise floor":l==="beyond"?"beyond noise":"within noise",w=u.partial||d.partial?` \u2014 over the counted calls only (${[u.partial?t.name:"",d.partial?n.name:""].filter(Boolean).join(", ")})`:"",$=`${e.label}: ${x(t,u)} \u2192 ${x(n,d)}${b!==void 0&&i?` (${Oe(b)})`:""} \u2014 ${m}${w}`+(O&&c?" \u2014 the sides ran at different provider speeds: time is not comparable":"");return{key:e.key,label:e.label,unit:e.unit,basis:"measured",a:u,b:d,...i!==void 0?{delta:e.unit==="usd"?C(i):e.unit==="share"?J(i):Math.round(i*10)/10}:{},...b!==void 0?{change:b}:{},noise:l,...O&&c?{speedSkew:!0}:{},said:$}}k(de,"xe"),r(de,"measureOf");const qe=["temperature","top_p","top_k","max_output_tokens","max_tokens","max_completion_tokens","seed","stop","stop_sequences","tool_choice","frequency_penalty","presence_penalty","truncation","n"],Ne=new Set(["prompt_cache_key"]),Ce=/^(.*) · block (\d+) of \d+$/;export function aiJoinedRequest(e,t){const n=ne(e,t);return n?{settings:n.settings,segments:n.segments}:void 0}k(aiJoinedRequest,"aiJoinedRequest"),r(aiJoinedRequest,"aiJoinedRequest");function ne(e,t){const n=xe(e,t);if(!n)return;const s=[];for(const d of n.blocks){const l=Ce.exec(d.label),i=l?l[1]:d.label,b=s[s.length-1];l&&Number(l[2])>1&&b?.label===i?b.text+=d.text:s.push({label:i,text:d.text})}const a={},c=JSON.parse(n.settings);for(const[d,l]of Object.entries(c))!Ne.has(d)&&l!==void 0&&(a[d]=JSON.stringify(l));const u=t;for(const d of qe)u[d]!==void 0&&(a[d]=JSON.stringify(u[d]));return{settings:a,segments:s,flat:s.map(d=>`\0${d.label}${d.text}`).join(""),chars:s.reduce((d,l)=>d+l.text.length,0),blocks:n.blocks.length,breakpoints:n.blocks.filter(d=>d.bp).length,mode:n.mode}}k(ne,"ie"),r(ne,"joinedOf");function ce(e,t){let n=0;for(let s=0;s<t;s++){const a=e.charCodeAt(s);a<128?n+=1:a<2048?n+=2:a>=55296&&a<=56319&&s+1<t?(n+=4,s++):n+=3}return n}k(ce,"ve"),r(ce,"utf8");const he=r((e,t)=>{const n=e.lastIndexOf(`
1
+ "use strict";var ve=Object.defineProperty;var k=(e,t)=>ve(e,"name",{value:t,configurable:!0});var xe=Object.defineProperty,v=k((e,t)=>xe(e,"name",{value:t,configurable:!0}),"k"),ye=Object.defineProperty,r=v((e,t)=>ye(e,"name",{value:t,configurable:!0}),"r");import{aiCacheRequestOf as Me,aiCacheSections as fe}from"./ai-cache.js";import{estimateTokens as Oe}from"./ai-context.js";export const AI_SPEED_SKEW=.15,AI_SPEED_MIN_OUTPUT=1e3,AI_COMPARE_MAX_CALLS=24,AI_COMPARE_MAX_RUNS=20,AI_COMPARE_MAX_SECTIONS=30;const me=200,Q=r(e=>Math.round(e).toLocaleString("en-US"),"fmt"),E=r(e=>Math.round(e*1e6)/1e6,"usd"),je=r(e=>{const t=Math.abs(e);return`$${t===0?"0":t<.001?Number(e.toPrecision(2)).toString():t<.01?e.toFixed(4):e.toFixed(3)}`},"money"),Se=r(e=>e>=9?`\xD7${Math.round(e+1).toLocaleString("en-US")}`:`${e>0?"+":e<0?"\u2212":""}${Math.abs(Math.round(e*100))}%`,"pct"),Ae=r(e=>e<1e3?`${Math.round(e)} ms`:`${(e/1e3).toFixed(e<1e4?1:0)} s`,"secs"),J=r(e=>Math.round(e*1e3)/1e3,"round3");function W(e,t){return t==="usd"?je(e):t==="ms"?Ae(e):t==="share"?`${Math.round(e*100)}%`:t==="tok/s"?`${e.toFixed(1)} tok/s`:Q(e)}k(W,"G"),v(W,"G"),r(W,"show");const _e=r((e,t)=>e.at-t.at||e.id.localeCompare(t.id),"byTime"),qe=r(e=>e.tokens?.input!==void 0,"counted");function K(e){const t=new Map;for(const n of e.rows){const s=e.unit==="flow"?n.flowId??"(no flow)":n.run.key,a=t.get(s);a?a.push(n):t.set(s,[n])}return[...t].map(([n,s])=>({key:n,rows:s.sort(_e)})).sort((n,s)=>n.rows[0].at-s.rows[0].at||n.key.localeCompare(s.key))}k(K,"H"),v(K,"H"),r(K,"repetitionsOf");function D(e){let t;const n=r(s=>s.rows.filter(a=>!a.prewarm).length,"answering");for(const s of e)(!t||n(s)>n(t))&&(t=s);return t}k(D,"D"),v(D,"V"),r(D,"diffedOf");function Z(e){const t=e.tokens?.written??0;if(!t)return{};const n=e.cache?.writes,s=n?Object.values(n).reduce((c,u)=>c+(u??0),0):0;if(n&&s>=t)return{...n};const a=e.cache?.ttl??"30m";return{...n??{},[a]:(n?.[a]??0)+t-s}}k(Z,"Q"),v(Z,"ee"),r(Z,"writesOf");function ee(e,t){const n=e.tokens;if(!n||n.input===void 0||!e.model)return;const s=t(e.model,n.input);if(!s)return;const a=n.cached??0,c=n.written??0,u=Math.max(0,n.input-a-c);let d=0;for(const[b,j]of Object.entries(Z(e)))d+=j*(s.writes[b]??s.input);const l={plain:u*s.input/1e6,read:a*(s.cacheRead??s.input)/1e6,written:d/1e6,output:(n.output??0)*s.output/1e6},i=l.plain+l.read+l.written;return{...l,input:i,total:i+l.output}}k(ee,"Z"),v(ee,"te"),r(ee,"callUsd");const Be=r(e=>({plain:E(e.plain),read:E(e.read),written:E(e.written),input:E(e.input),output:E(e.output),total:E(e.total)}),"usdOut"),ge=r(e=>!e.prewarm&&e.durationMs&&e.durationMs>0&&(e.tokens?.output??0)>=AI_SPEED_MIN_OUTPUT?e.tokens.output/e.durationMs*1e3:void 0,"speedOf"),be=r(e=>{if(!e.length)return;const t=[...e].sort((s,a)=>s-a),n=Math.floor(t.length/2);return t.length%2?t[n]:(t[n-1]+t[n])/2},"median");function te(e,t,n){const s={input:0,plain:0,read:0,written:0,output:0,reasoning:0},a={};let c,u=0,d=0;for(const m of t){if(!qe(m)){d++;continue}const w=m.tokens;s.input+=w.input,s.read+=w.cached??0,s.written+=w.written??0,s.plain+=Math.max(0,w.input-(w.cached??0)-(w.written??0)),s.output+=w.output??0,s.reasoning+=w.reasoning??0;for(const[p,f]of Object.entries(Z(m)))a[p]=(a[p]??0)+f;const $=ee(m,n);if(!$){u++;continue}c=c?{plain:c.plain+$.plain,read:c.read+$.read,written:c.written+$.written,input:c.input+$.input,output:c.output+$.output,total:c.total+$.total}:$}Object.keys(a).length&&(s.writes=a);const l=t.filter(m=>m.durationMs!==void 0),i=t.filter(m=>!m.prewarm),b=i.filter(m=>m.durationMs!==void 0).reduce((m,w)=>!m||w.durationMs>m.durationMs?w:m,void 0),j=b?.durationMs&&b.tokens?.output!==void 0?b.tokens.output/b.durationMs*1e3:void 0,y=be(i.map(ge).filter(m=>m!==void 0));return{key:e,at:t[0].at,calls:i.length,prewarms:t.length-i.length,failed:t.filter(m=>m.failed).length,uncounted:d,tokens:s,...s.output?{reasoningShare:J(s.reasoning/s.output)}:{},...c?{usd:Be(c)}:{},...u?{unpriced:u}:{},...l.length?{wallMs:Math.max(...l.map(m=>m.at+m.durationMs))-t[0].at}:{},...b?{slowest:{id:b.id,ms:b.durationMs,...b.tokens?.output!==void 0?{output:b.tokens.output}:{},...j!==void 0?{tokPerSec:Math.round(j*10)/10}:{}}}:{},...y!==void 0?{tokPerSec:Math.round(y*10)/10}:{}}}k(te,"ee"),v(te,"oe"),r(te,"runOf");const Ce=[{key:"calls",label:"calls (a prewarm apart)",unit:"calls",of:r(e=>e.calls,"of")},{key:"input",label:"input tokens",unit:"tokens",of:r(e=>e.tokens.input,"of"),counts:!0},{key:"plain",label:"input, plain (neither read nor written)",unit:"tokens",of:r(e=>e.tokens.plain,"of"),counts:!0},{key:"read",label:"input, read from the cache",unit:"tokens",of:r(e=>e.tokens.read,"of"),counts:!0},{key:"written",label:"input, written to the cache",unit:"tokens",of:r(e=>e.tokens.written,"of"),counts:!0},{key:"output",label:"output tokens",unit:"tokens",of:r(e=>e.tokens.output,"of"),counts:!0},{key:"reasoningShare",label:"reasoning share of the output",unit:"share",of:r(e=>e.reasoningShare,"of"),counts:!0},{key:"plainUsd",label:"input $, plain",unit:"usd",of:r(e=>e.usd?.plain,"of"),counts:!0},{key:"readUsd",label:"input $, read",unit:"usd",of:r(e=>e.usd?.read,"of"),counts:!0},{key:"writtenUsd",label:"input $, written",unit:"usd",of:r(e=>e.usd?.written,"of"),counts:!0},{key:"inputUsd",label:"input $",unit:"usd",of:r(e=>e.usd?.input,"of"),counts:!0},{key:"outputUsd",label:"output $",unit:"usd",of:r(e=>e.usd?.output,"of"),counts:!0},{key:"totalUsd",label:"total $",unit:"usd",of:r(e=>e.usd?.total,"of"),counts:!0},{key:"wallMs",label:"the stage\u2019s wall time",unit:"ms",of:r(e=>e.wallMs,"of")},{key:"slowestMs",label:"its slowest call",unit:"ms",of:r(e=>e.slowest?.ms,"of")},{key:"tokPerSec",label:"provider speed (median output tokens a second)",unit:"tok/s",of:r(e=>e.tokPerSec,"of")}];function ne(e,t){const n=e.map(t.of).filter(u=>typeof u=="number"&&Number.isFinite(u)),s=t.counts&&e.some(u=>u.uncounted>0||t.unit==="usd"&&(u.unpriced??0)>0);if(!n.length)return s?{partial:!0}:{};const a=n.reduce((u,d)=>u+d,0)/n.length,c={value:t.unit==="usd"?E(a):t.unit==="share"?J(a):Math.round(a*10)/10,...s?{partial:!0}:{}};if(n.length>=2){const u=Math.sqrt(n.reduce((l,i)=>l+(i-a)**2,0)/(n.length-1)),d=r(l=>t.unit==="usd"?E(l):t.unit==="share"?J(l):Math.round(l*10)/10,"r");c.spread={runs:n.length,min:d(Math.min(...n)),max:d(Math.max(...n)),mean:d(a),sd:d(u),...a?{cv:J(u/Math.abs(a))}:{}}}return c}k(ne,"te"),v(ne,"ae"),r(ne,"valueOf");function ie(e,t){if(!e.spread&&!t.spread)return"none";if(e.spread&&t.spread)return e.spread.max<t.spread.min||t.spread.max<e.spread.min?"beyond":"within";const n=e.spread??t.spread,s=e.spread?t.value:e.value;return s===void 0?"none":s<n.min||s>n.max?"beyond":"within"}k(ie,"ue"),v(ie,"Me"),r(ie,"noiseOf");function re(e,t,n,s,a,c){const u=ne(s,e),d=ne(a,e),l=ie(u,d),i=u.value!==void 0&&d.value!==void 0?d.value-u.value:void 0,b=i!==void 0&&u.value?J(i/u.value):void 0,j=e.unit==="ms",y=r((p,f)=>f.value===void 0?`${p.name} \u2014`:`${p.name} ${W(f.value,e.unit)}${f.spread?` (${W(f.spread.min,e.unit)}\u2013${W(f.spread.max,e.unit)} over ${f.spread.runs})`:""}`,"side"),m=l==="none"?u.value===void 0||d.value===void 0?"nothing to compare":"one run a side: no noise floor":l==="beyond"?"beyond noise":"within noise",w=u.partial||d.partial?` \u2014 over the counted calls only (${[u.partial?t.name:"",d.partial?n.name:""].filter(Boolean).join(", ")})`:"",$=`${e.label}: ${y(t,u)} \u2192 ${y(n,d)}${b!==void 0&&i?` (${Se(b)})`:""} \u2014 ${m}${w}`+(j&&c?" \u2014 the sides ran at different provider speeds: time is not comparable":"");return{key:e.key,label:e.label,unit:e.unit,basis:"measured",a:u,b:d,...i!==void 0?{delta:e.unit==="usd"?E(i):e.unit==="share"?J(i):Math.round(i*10)/10}:{},...b!==void 0?{change:b}:{},noise:l,...j&&c?{speedSkew:!0}:{},said:$}}k(re,"de"),v(re,"xe"),r(re,"measureOf");const Ne=["temperature","top_p","top_k","max_output_tokens","max_tokens","max_completion_tokens","seed","stop","stop_sequences","tool_choice","frequency_penalty","presence_penalty","truncation","n"],Ee=new Set(["prompt_cache_key"]),Pe=/^(.*) · block (\d+) of \d+$/;export function aiJoinedRequest(e,t){const n=se(e,t);return n?{settings:n.settings,segments:n.segments}:void 0}k(aiJoinedRequest,"aiJoinedRequest"),v(aiJoinedRequest,"aiJoinedRequest"),r(aiJoinedRequest,"aiJoinedRequest");function se(e,t){const n=Me(e,t);if(!n)return;const s=[];for(const d of n.blocks){const l=Pe.exec(d.label),i=l?l[1]:d.label,b=s[s.length-1];l&&Number(l[2])>1&&b?.label===i?b.text+=d.text:s.push({label:i,text:d.text})}const a={},c=JSON.parse(n.settings);for(const[d,l]of Object.entries(c))!Ee.has(d)&&l!==void 0&&(a[d]=JSON.stringify(l));const u=t;for(const d of Ne)u[d]!==void 0&&(a[d]=JSON.stringify(u[d]));return{settings:a,segments:s,flat:s.map(d=>`\0${d.label}${d.text}`).join(""),chars:s.reduce((d,l)=>d+l.text.length,0),blocks:n.blocks.length,breakpoints:n.blocks.filter(d=>d.bp).length,mode:n.mode}}k(se,"ne"),v(se,"ie"),r(se,"joinedOf");function le(e,t){let n=0;for(let s=0;s<t;s++){const a=e.charCodeAt(s);a<128?n+=1:a<2048?n+=2:a>=55296&&a<=56319&&s+1<t?(n+=4,s++):n+=3}return n}k(le,"ce"),v(le,"ve"),r(le,"utf8");const $e=r((e,t)=>{const n=e.lastIndexOf(`
2
2
  `,t-1)+1,s=e.indexOf(`
3
- `,t),a=e.slice(n,s<0?e.length:s).trim();return a?a.length>ie?`${a.slice(0,ie-1)}\u2026`:a:"(an empty line)"},"lineAt"),pe=r((e,t)=>{const n=Math.min(e.length,t.length);let s=0;for(;s<n&&e.charCodeAt(s)===t.charCodeAt(s);)s++;return s},"commonPrefix");function se(e,t){const n=ae(e.text),s=[],a=r((c,u,d)=>{const l=`${e.label} \u203A ${c}`,i=(t.get(l)??0)+1;t.set(l,i),s.push({title:i>1?`${l} #${i}`:l,text:e.text.slice(u,d)})},"push");if(!n.length){const c=(t.get(e.label)??0)+1;return t.set(e.label,c),[{title:c>1?`${e.label} #${c}`:e.label,text:e.text}]}return n[0].at>0&&e.text.slice(0,n[0].at).trim()&&a("(opening)",0,n[0].at),n.forEach((c,u)=>a(c.title,c.at,u+1<n.length?n[u+1].at:e.text.length)),s}k(se,"ue"),r(se,"sectionsOf");class Ee{static{k(this,"_e")}static{r(this,"Estimates")}constructor(){this.memo=new Map}of(t){let n=this.memo.get(t);return n===void 0&&(n=ye(t),this.memo.set(t,n)),n}}function fe(e,t,n,s){const a=[...new Set([...Object.keys(e.settings),...Object.keys(t.settings)])].filter(p=>e.settings[p]!==t.settings[p]);let c=0,u,d;const l=r(()=>d??=e.segments.map(p=>p.text).join(""),"joinedX");for(let p=0;p<Math.max(e.segments.length,t.segments.length)&&!u;p++){const g=e.segments[p],A=t.segments[p];if(g&&A&&g.label===A.label&&g.text===A.text){c+=g.text.length;continue}const I=g&&A&&g.label===A.label?pe(g.text,A.text):0,Y=g?[...ae(g.text)].reverse().find(z=>z.at<=I):void 0,U=g?g.label!==A?.label?`${g.label}${A?` (the other has \xAB${A.label}\xBB here)`:" (the other request has ended)"}`:Y?`${g.label} \u203A ${Y.title}`:g.label:`the end of the first request (the other goes on with \xAB${A.label}\xBB)`,P=c+I;u={char:P,byte:ce(l(),P),region:U,tokensBefore:n[0]!==void 0&&e.chars>0?Math.round(P/e.chars*n[0]):Math.round(s.of(l().slice(0,P))),basis:"estimate",...g?{line:he(g.text,Math.min(I,Math.max(0,g.text.length-1)))}:{},...A?{otherLine:he(A.text,Math.min(I,Math.max(0,A.text.length-1)))}:{}}}const i={blocks:[e.blocks,t.blocks],breakpoints:[e.breakpoints,t.breakpoints],mode:[e.mode,t.mode]},b=!u&&!a.length,O=new Map,x=new Map,m=e.segments.flatMap(p=>se(p,O)),w=t.segments.flatMap(p=>se(p,x)),$=m.reduce((p,g)=>p+s.of(g.text),0),h=w.reduce((p,g)=>p+s.of(g.text),0),[f,y]=n,q=f!==void 0&&y!==void 0&&$+h>0?(f+y)/($+h):f!==void 0&&$>0?f/$:y!==void 0&&h>0?y/h:1,_=r(p=>Math.round(s.of(p)*q),"tok"),K=new Map(w.map(p=>[p.title,p.text])),W=new Set(m.map(p=>p.title)),M=[];let X=0,R=0,E=0;const T=r(p=>{for(;E<w.length&&w[E].title!==p;){const g=w[E++];W.has(g.title)||M.push({title:g.title,b:_(g.text),delta:_(g.text),state:"only-b"})}E<w.length&&E++},"onlyY");for(const p of m){const g=K.get(p.title);if(g===void 0){M.push({title:p.title,a:_(p.text),delta:-_(p.text),state:"only-a"});continue}T(p.title),g===p.text?(X++,R+=_(p.text)):M.push({title:p.title,a:_(p.text),b:_(g),delta:_(g)-_(p.text),state:"changed"})}return T(void 0),{same:b,...a.length?{settings:a}:{},...u?{diff:u}:{},cut:i,sections:{basis:"estimate",changed:M.slice(0,AI_COMPARE_MAX_SECTIONS),...M.length>AI_COMPARE_MAX_SECTIONS?{more:M.length-AI_COMPARE_MAX_SECTIONS}:{},same:X,sameTokens:R}}}k(fe,"Ae"),r(fe,"diffOf");function me(e){const t=e.meta?.part??e.meta?.group??e.meta?.label,n=e.action?.name??"call";return{key:`${e.action?.key??""}
4
- ${t??""}`,name:t?`${n} \xB7 ${t}`:n}}k(me,"Ne"),r(me,"labelOf");function ge(e,t,n){const s=[],a=e.filter(i=>i.prewarm),c=t.filter(i=>i.prewarm);for(let i=0;i<Math.max(a.length,c.length);i++)s.push({...a[i]?{a:a[i]}:{},...c[i]?{b:c[i]}:{},label:Math.max(a.length,c.length)>1?`prewarm \xB7 ${i+1}`:"prewarm",prewarm:!0,...a[i]&&c[i]?{match:"position"}:{}});const u=new Map,d=r((i,b)=>{const O=me(i);let x=u.get(O.key);x||u.set(O.key,x={name:O.name,a:[],b:[]}),x[b].push(i)},"put");for(const i of e)i.prewarm||d(i,"a");for(const i of t)i.prewarm||d(i,"b");const l=u.size>1;for(const i of u.values()){const b=Math.max(i.a.length,i.b.length),O=r(h=>b>1?`${i.name} \xB7 ${h+1} of ${b}`:i.name,"name");if(i.a.length===i.b.length||i.a.some(h=>!n(h.id))||i.b.some(h=>!n(h.id))){for(let h=0;h<b;h++){const f=i.a[h],y=i.b[h];s.push({...f?{a:f}:{},...y?{b:y}:{},label:O(h),...f&&y?{match:b===1&&l?"label":"position"}:{}})}continue}const x=[];for(let h=0;h<i.a.length;h++)for(let f=0;f<i.b.length;f++){const y=n(i.a[h].id),q=n(i.b[f].id),_=JSON.stringify(y.settings)===JSON.stringify(q.settings)?pe(y.flat,q.flat):0;x.push({i:h,j:f,n:_,rest:y.flat.length+q.flat.length-2*_})}x.sort((h,f)=>f.n-h.n||h.rest-f.rest||h.i-f.i||h.j-f.j);const m=new Set,w=new Set,$=[];for(const h of x)m.has(h.i)||w.has(h.j)||(m.add(h.i),w.add(h.j),$.push({i:h.i,j:h.j}));i.a.forEach((h,f)=>!m.has(f)&&$.push({i:f})),i.b.forEach((h,f)=>!w.has(f)&&$.push({j:f})),$.sort((h,f)=>(h.i??1/0)-(f.i??1/0)||(h.j??1/0)-(f.j??1/0)),$.forEach((h,f)=>{const y=h.i!==void 0?i.a[h.i]:void 0,q=h.j!==void 0?i.b[h.j]:void 0;s.push({...y?{a:y}:{},...q?{b:q}:{},label:O(f),...y&&q?{match:"prefix"}:{}})})}return s}k(ge,"Ce"),r(ge,"matchCalls");export function aiCompareNeeds(e,t){return[e,t].flatMap(n=>(D(H(n))?.rows??[]).slice(0,AI_COMPARE_MAX_CALLS).map(s=>s.id))}k(aiCompareNeeds,"aiCompareNeeds"),r(aiCompareNeeds,"aiCompareNeeds");function be(e,t){const n=new Map;for(const s of e){if(!s.model||n.has(s.model))continue;const a=t(s.model,s.tokens?.input??0);a&&n.set(s.model,{model:s.model,input:a.input,output:a.output,...a.cacheRead!==void 0?{cacheRead:a.cacheRead}:{},writes:{...a.writes},...a.source?{source:a.source}:{},...a.readAt?{readAt:a.readAt}:{},...a.stale?{stale:!0}:{}})}return[...n.values()]}k(be,"Ee"),r(be,"pricesOf");function oe(e,t,n,s){const a=e.rows.map(re).filter(l=>l!==void 0),c=le(a),u=[...new Set(e.rows.map(l=>l.model).filter(l=>!!l))],d=D(t);return{name:e.name,...e.said?{said:e.said}:{},unit:e.unit,runs:n.slice(0,AI_COMPARE_MAX_RUNS),...n.length>AI_COMPARE_MAX_RUNS?{moreRuns:n.length-AI_COMPARE_MAX_RUNS}:{},runCount:n.length,...d?{diffed:d.key}:{},models:u,prices:be(e.rows,s),...c!==void 0?{speed:{median:Math.round(c*10)/10,min:Math.round(Math.min(...a)*10)/10,max:Math.round(Math.max(...a)*10)/10,calls:a.length}}:{}}}k(oe,"de"),r(oe,"sideOf");function $e(e,t){const n=e.speed?.median,s=t.speed?.median,a={threshold:AI_SPEED_SKEW,...n!==void 0?{a:n}:{},...s!==void 0?{b:s}:{}};if(n===void 0||s===void 0){const l=[n===void 0?e.name:"",s===void 0?t.name:""].filter(Boolean).join(" and ");return{...a,differs:!1,said:`No speed for ${l}: no call wrote ${V(AI_SPEED_MIN_OUTPUT)} output tokens or more \u2014 whether the sides ran at one provider speed is not known.`}}const c=J(Math.max(n,s)/Math.min(n,s)-1),u=c>AI_SPEED_SKEW,d=`${e.name} ${n.toFixed(1)} tok/s (${e.speed.min}\u2013${e.speed.max} over ${e.speed.calls} call${e.speed.calls===1?"":"s"}), ${t.name} ${s.toFixed(1)} tok/s (${t.speed.min}\u2013${t.speed.max} over ${t.speed.calls})`;return{...a,apart:c,differs:u,said:u?`The sides ran at different provider speeds: ${d} \u2014 ${Math.round(c*100)}% apart, beyond the ${Math.round(AI_SPEED_SKEW*100)}% two runs of the same requests differ by in one session. Their times are not comparable: measure the two side by side, in one session.`:`One provider speed: ${d} \u2014 ${Math.round(c*100)}% apart, within ${Math.round(AI_SPEED_SKEW*100)}%.`}}k($e,"qe"),r($e,"speedOfSides");export function aiCompare(e){const{a:t,b:n,ratesOf:s}=e,a=H(t),c=H(n),u=a.map(o=>ee(o.key,o.rows,s)),d=c.map(o=>ee(o.key,o.rows,s)),l=oe(t,a,u,s),i=oe(n,c,d,s),b=$e(l,i),O=Be.map(o=>de(o,l,i,u,d,b.differs)),x=new Map,m=new Map,w=new Map([...t.rows,...n.rows].map(o=>[o.id,o])),$=r(o=>{if(x.has(o))return x.get(o);const v=e.requests?.get(o),j=w.get(o);let S;if(!v)m.set(o,"its request was not read");else if("why"in v)m.set(o,v.why);else if(j){try{S=ne(j.api,v.body)}catch{S=void 0}S||m.set(o,"its request is not one the lens can read (an embedding, or not an object)")}return x.set(o,S),S},"joined"),h=D(a),f=D(c),y=(h?.rows??[]).slice(0,AI_COMPARE_MAX_CALLS),q=(f?.rows??[]).slice(0,AI_COMPARE_MAX_CALLS),_=new Ee,K=r(o=>{const v=o?Z(o,s):void 0;return v?C(v.input):void 0},"usdOf"),W=ge(y,q,$).map(o=>{const v={...o.a?{a:o.a.id}:{},...o.b?{b:o.b.id}:{},label:o.label,...o.prewarm?{prewarm:!0}:{},...o.match?{match:o.match}:{},input:[o.a?.tokens?.input??null,o.b?.tokens?.input??null],inputUsd:[K(o.a)??null,K(o.b)??null],output:[o.a?.tokens?.output??null,o.b?.tokens?.output??null],ms:[o.a?.durationMs??null,o.b?.durationMs??null]};if(!o.a||!o.b)return v;const j=$(o.a.id),S=$(o.b.id);return!j||!S?{...v,unread:[j?"":`${t.name}: ${m.get(o.a.id)}`,S?"":`${n.name}: ${m.get(o.b.id)}`].filter(Boolean).join("; ")}:{...v,...fe(j,S,[o.a.tokens?.input,o.b.tokens?.input],_)}});for(const[o,v]of[[l,y],[i,q]]){const j=v.find(B=>B.prewarm),S=j?$(j.id):void 0;if(!j||!S)continue;const F=v.filter(B=>!B.prewarm).map(B=>$(B.id)).filter(B=>!!B);o.prewarm={id:j.id,prefixOf:F.filter(B=>JSON.stringify(B.settings)===JSON.stringify(S.settings)&&B.flat.startsWith(S.flat)).length,of:F.length}}const M=W.filter(o=>!o.prewarm),X=M.some(o=>o.a&&o.b&&o.same===void 0),R=M.filter(o=>!o.a||!o.b),E=M.filter(o=>o.same===!1),T=E.length||R.length?!1:X?void 0:M.length?!0:void 0,p=M.filter(o=>o.same&&o.cut&&(o.cut.blocks[0]!==o.cut.blocks[1]||o.cut.breakpoints[0]!==o.cut.breakpoints[1]||o.cut.mode[0]!==o.cut.mode[1])),g=E.find(o=>o.diff||o.settings),A=T===!0?`The ${i.name} requests, joined, are the ${l.name} requests byte for byte: ${M.length} call${M.length===1?"":"s"}, the same bytes and settings${p.length?` \u2014 ${p.length} cut otherwise (blocks ${p[0].cut.blocks.join(" \u2192 ")}, breakpoints ${p[0].cut.breakpoints.join(" \u2192 ")}, ${p[0].cut.mode.join(" \u2192 ")}): what the cache sees changed, what the model reads did not`:""}.`:T===!1?`Not the same bytes: ${E.length} of ${M.length} pair${M.length===1?"":"s"} differ${R.length?`, ${R.length} call${R.length===1?"":"s"} on one side only`:""}`+(g?.settings?` \u2014 settings ${g.settings.join(", ")}`:"")+(g?.diff?` \u2014 the first, \xAB${g.label}\xBB, parts at \xAB${g.diff.region}\xBB (character ${V(g.diff.char)}, byte ${V(g.diff.byte)}): \xAB${g.diff.line??""}\xBB vs \xAB${g.diff.otherLine??""}\xBB`:"")+".":M.length?`Not every request was read (${M.filter(o=>o.unread).length} pair${M.filter(o=>o.unread).length===1?"":"s"}): whether the requests are the same bytes is not known.`:"No answering call on either side to diff.",I=`The ${l.name} ${t.unit} ${h?.key??"\u2014"} and the ${i.name} ${n.unit} ${f?.key??"\u2014"} (each side's ${t.unit===n.unit?t.unit:"repetition"} with the most calls, the earliest of those) are set call by call: a prewarm to a prewarm; then by action (and the app\u2019s part label) \u2014 one call each, by label; several, by the order they were sent; counts that differ, by the longest prefix their joined requests share.`+((h?.rows.length??0)>AI_COMPARE_MAX_CALLS||(f?.rows.length??0)>AI_COMPARE_MAX_CALLS?` The first ${AI_COMPARE_MAX_CALLS} calls of each.`:""),Y=a.length<2&&c.length<2?"One run a side: no noise floor \u2014 a difference may be the model\u2019s own spread (seven runs of one request proposed 11 to 23 changes). Compare several runs a side.":`Noise floor: ${l.name} over ${a.length} ${t.unit}${a.length===1?"":"s"}, ${i.name} over ${c.length}${a.length===2||c.length===2?" \u2014 a floor of two runs is thin":""}. A measure is beyond noise when its ranges do not overlap, or a single run falls outside the other side\u2019s range.`,U=[];b.differs&&U.push(b.said);for(const[o,v]of[[l,u],[i,d]]){const j=v.reduce((N,L)=>N+L.uncounted,0),S=v.reduce((N,L)=>N+L.calls+L.prewarms,0);j&&U.push(`${o.name}: ${j} of ${S} calls kept no usage (a failed call, an answer the capture cut) \u2014 its tokens and dollars are over the ${S-j} counted.`);const F=v.reduce((N,L)=>N+(L.unpriced??0),0);F&&U.push(`${o.name}: ${F} counted call${F===1?"":"s"} with no price \u2014 in its tokens, not its dollars.`);const B=o.prices.filter(N=>N.stale);B.length&&U.push(`${o.name}: the price of ${B.map(N=>N.model).join(", ")} is stale (read ${B.map(N=>N.readAt??"?").join(", ")}): read the provider's page again.`),o.prewarm&&o.prewarm.prefixOf<o.prewarm.of&&U.push(`${o.name}: ${o.prewarm.of-o.prewarm.prefixOf} of ${o.prewarm.of} answering calls do not start with the prewarm's request \u2014 it warmed a prefix they do not share.`)}const P=l.models.join(", "),z=i.models.join(", ");P&&z&&P!==z&&U.push(`The sides called other models (${l.name}: ${P}; ${i.name}: ${z}).`);const we=["Section tokens and the tokens before a difference are estimated from the text, scaled to the provider\u2019s count.",`Dollars are the provider\u2019s counts at the price table\u2019s rates (${[...l.prices,...i.prices].map(o=>`${o.model}: ${o.source??"no source"}${o.readAt?`, read ${o.readAt}`:""}`).filter((o,v,j)=>j.indexOf(o)===v).join("; ")||"no price"}) \u2014 not the provider\u2019s bill.`,"A call\u2019s speed is its output over its whole time, the wait for the first token included.",...m.size?[`${m.size} request${m.size===1?"":"s"} not diffed: ${[...new Set(m.values())].join("; ")}.`]:[]];return{a:l,b:i,measures:O,speed:b,requests:{how:I,pairs:W,...T!==void 0?{identical:T}:{},said:A},noise:Y,warnings:U,notVerified:we}}k(aiCompare,"aiCompare"),r(aiCompare,"aiCompare");
3
+ `,t),a=e.slice(n,s<0?e.length:s).trim();return a?a.length>me?`${a.slice(0,me-1)}\u2026`:a:"(an empty line)"},"lineAt"),we=r((e,t)=>{const n=Math.min(e.length,t.length);let s=0;for(;s<n&&e.charCodeAt(s)===t.charCodeAt(s);)s++;return s},"commonPrefix");function oe(e,t){const n=fe(e.text),s=[],a=r((c,u,d)=>{const l=`${e.label} \u203A ${c}`,i=(t.get(l)??0)+1;t.set(l,i),s.push({title:i>1?`${l} #${i}`:l,text:e.text.slice(u,d)})},"push");if(!n.length){const c=(t.get(e.label)??0)+1;return t.set(e.label,c),[{title:c>1?`${e.label} #${c}`:e.label,text:e.text}]}return n[0].at>0&&e.text.slice(0,n[0].at).trim()&&a("(opening)",0,n[0].at),n.forEach((c,u)=>a(c.title,c.at,u+1<n.length?n[u+1].at:e.text.length)),s}k(oe,"se"),v(oe,"ue"),r(oe,"sectionsOf");class Re{static{k(this,"Ee")}static{v(this,"_e")}static{r(this,"Estimates")}constructor(){this.memo=new Map}of(t){let n=this.memo.get(t);return n===void 0&&(n=Oe(t),this.memo.set(t,n)),n}}function ue(e,t,n,s){const a=[...new Set([...Object.keys(e.settings),...Object.keys(t.settings)])].filter(h=>e.settings[h]!==t.settings[h]);let c=0,u,d;const l=r(()=>d??=e.segments.map(h=>h.text).join(""),"joinedX");for(let h=0;h<Math.max(e.segments.length,t.segments.length)&&!u;h++){const g=e.segments[h],_=t.segments[h];if(g&&_&&g.label===_.label&&g.text===_.text){c+=g.text.length;continue}const F=g&&_&&g.label===_.label?we(g.text,_.text):0,H=g?[...fe(g.text)].reverse().find(L=>L.at<=F):void 0,R=g?g.label!==_?.label?`${g.label}${_?` (the other has \xAB${_.label}\xBB here)`:" (the other request has ended)"}`:H?`${g.label} \u203A ${H.title}`:g.label:`the end of the first request (the other goes on with \xAB${_.label}\xBB)`,U=c+F;u={char:U,byte:le(l(),U),region:R,tokensBefore:n[0]!==void 0&&e.chars>0?Math.round(U/e.chars*n[0]):Math.round(s.of(l().slice(0,U))),basis:"estimate",...g?{line:$e(g.text,Math.min(F,Math.max(0,g.text.length-1)))}:{},..._?{otherLine:$e(_.text,Math.min(F,Math.max(0,_.text.length-1)))}:{}}}const i={blocks:[e.blocks,t.blocks],breakpoints:[e.breakpoints,t.breakpoints],mode:[e.mode,t.mode]},b=!u&&!a.length,j=new Map,y=new Map,m=e.segments.flatMap(h=>oe(h,j)),w=t.segments.flatMap(h=>oe(h,y)),$=m.reduce((h,g)=>h+s.of(g.text),0),p=w.reduce((h,g)=>h+s.of(g.text),0),[f,M]=n,C=f!==void 0&&M!==void 0&&$+p>0?(f+M)/($+p):f!==void 0&&$>0?f/$:M!==void 0&&p>0?M/p:1,q=r(h=>Math.round(s.of(h)*C),"tok"),V=new Map(w.map(h=>[h.title,h.text])),Y=new Set(m.map(h=>h.title)),O=[];let G=0,T=0,P=0;const I=r(h=>{for(;P<w.length&&w[P].title!==h;){const g=w[P++];Y.has(g.title)||O.push({title:g.title,b:q(g.text),delta:q(g.text),state:"only-b"})}P<w.length&&P++},"onlyY");for(const h of m){const g=V.get(h.title);if(g===void 0){O.push({title:h.title,a:q(h.text),delta:-q(h.text),state:"only-a"});continue}I(h.title),g===h.text?(G++,T+=q(h.text)):O.push({title:h.title,a:q(h.text),b:q(g),delta:q(g)-q(h.text),state:"changed"})}return I(void 0),{same:b,...a.length?{settings:a}:{},...u?{diff:u}:{},cut:i,sections:{basis:"estimate",changed:O.slice(0,AI_COMPARE_MAX_SECTIONS),...O.length>AI_COMPARE_MAX_SECTIONS?{more:O.length-AI_COMPARE_MAX_SECTIONS}:{},same:G,sameTokens:T}}}k(ue,"fe"),v(ue,"Ae"),r(ue,"diffOf");function de(e){const t=e.meta?.part??e.meta?.group??e.meta?.label,n=e.action?.name??"call";return{key:`${e.action?.key??""}
4
+ ${t??""}`,name:t?`${n} \xB7 ${t}`:n}}k(de,"me"),v(de,"Ne"),r(de,"labelOf");function ce(e,t,n){const s=[],a=e.filter(i=>i.prewarm),c=t.filter(i=>i.prewarm);for(let i=0;i<Math.max(a.length,c.length);i++)s.push({...a[i]?{a:a[i]}:{},...c[i]?{b:c[i]}:{},label:Math.max(a.length,c.length)>1?`prewarm \xB7 ${i+1}`:"prewarm",prewarm:!0,...a[i]&&c[i]?{match:"position"}:{}});const u=new Map,d=r((i,b)=>{const j=de(i);let y=u.get(j.key);y||u.set(j.key,y={name:j.name,a:[],b:[]}),y[b].push(i)},"put");for(const i of e)i.prewarm||d(i,"a");for(const i of t)i.prewarm||d(i,"b");const l=u.size>1;for(const i of u.values()){const b=Math.max(i.a.length,i.b.length),j=r(p=>b>1?`${i.name} \xB7 ${p+1} of ${b}`:i.name,"name");if(i.a.length===i.b.length||i.a.some(p=>!n(p.id))||i.b.some(p=>!n(p.id))){for(let p=0;p<b;p++){const f=i.a[p],M=i.b[p];s.push({...f?{a:f}:{},...M?{b:M}:{},label:j(p),...f&&M?{match:b===1&&l?"label":"position"}:{}})}continue}const y=[];for(let p=0;p<i.a.length;p++)for(let f=0;f<i.b.length;f++){const M=n(i.a[p].id),C=n(i.b[f].id),q=JSON.stringify(M.settings)===JSON.stringify(C.settings)?we(M.flat,C.flat):0;y.push({i:p,j:f,n:q,rest:M.flat.length+C.flat.length-2*q})}y.sort((p,f)=>f.n-p.n||p.rest-f.rest||p.i-f.i||p.j-f.j);const m=new Set,w=new Set,$=[];for(const p of y)m.has(p.i)||w.has(p.j)||(m.add(p.i),w.add(p.j),$.push({i:p.i,j:p.j}));i.a.forEach((p,f)=>!m.has(f)&&$.push({i:f})),i.b.forEach((p,f)=>!w.has(f)&&$.push({j:f})),$.sort((p,f)=>(p.i??1/0)-(f.i??1/0)||(p.j??1/0)-(f.j??1/0)),$.forEach((p,f)=>{const M=p.i!==void 0?i.a[p.i]:void 0,C=p.j!==void 0?i.b[p.j]:void 0;s.push({...M?{a:M}:{},...C?{b:C}:{},label:j(f),...M&&C?{match:"prefix"}:{}})})}return s}k(ce,"ge"),v(ce,"Ce"),r(ce,"matchCalls");export function aiCompareNeeds(e,t){return[e,t].flatMap(n=>(D(K(n))?.rows??[]).slice(0,AI_COMPARE_MAX_CALLS).map(s=>s.id))}k(aiCompareNeeds,"aiCompareNeeds"),v(aiCompareNeeds,"aiCompareNeeds"),r(aiCompareNeeds,"aiCompareNeeds");function pe(e,t){const n=new Map;for(const s of e){if(!s.model||n.has(s.model))continue;const a=t(s.model,s.tokens?.input??0);a&&n.set(s.model,{model:s.model,input:a.input,output:a.output,...a.cacheRead!==void 0?{cacheRead:a.cacheRead}:{},writes:{...a.writes},...a.source?{source:a.source}:{},...a.readAt?{readAt:a.readAt}:{},...a.stale?{stale:!0}:{}})}return[...n.values()]}k(pe,"be"),v(pe,"Ee"),r(pe,"pricesOf");function ae(e,t,n,s){const a=e.rows.map(ge).filter(l=>l!==void 0),c=be(a),u=[...new Set(e.rows.map(l=>l.model).filter(l=>!!l))],d=D(t);return{name:e.name,...e.said?{said:e.said}:{},unit:e.unit,runs:n.slice(0,AI_COMPARE_MAX_RUNS),...n.length>AI_COMPARE_MAX_RUNS?{moreRuns:n.length-AI_COMPARE_MAX_RUNS}:{},runCount:n.length,...d?{diffed:d.key}:{},models:u,prices:pe(e.rows,s),...c!==void 0?{speed:{median:Math.round(c*10)/10,min:Math.round(Math.min(...a)*10)/10,max:Math.round(Math.max(...a)*10)/10,calls:a.length}}:{}}}k(ae,"oe"),v(ae,"de"),r(ae,"sideOf");function he(e,t){const n=e.speed?.median,s=t.speed?.median,a={threshold:AI_SPEED_SKEW,...n!==void 0?{a:n}:{},...s!==void 0?{b:s}:{}};if(n===void 0||s===void 0){const l=[n===void 0?e.name:"",s===void 0?t.name:""].filter(Boolean).join(" and ");return{...a,differs:!1,said:`No speed for ${l}: no call wrote ${Q(AI_SPEED_MIN_OUTPUT)} output tokens or more \u2014 whether the sides ran at one provider speed is not known.`}}const c=J(Math.max(n,s)/Math.min(n,s)-1),u=c>AI_SPEED_SKEW,d=`${e.name} ${n.toFixed(1)} tok/s (${e.speed.min}\u2013${e.speed.max} over ${e.speed.calls} call${e.speed.calls===1?"":"s"}), ${t.name} ${s.toFixed(1)} tok/s (${t.speed.min}\u2013${t.speed.max} over ${t.speed.calls})`;return{...a,apart:c,differs:u,said:u?`The sides ran at different provider speeds: ${d} \u2014 ${Math.round(c*100)}% apart, beyond the ${Math.round(AI_SPEED_SKEW*100)}% two runs of the same requests differ by in one session. Their times are not comparable: measure the two side by side, in one session.`:`One provider speed: ${d} \u2014 ${Math.round(c*100)}% apart, within ${Math.round(AI_SPEED_SKEW*100)}%.`}}k(he,"$e"),v(he,"qe"),r(he,"speedOfSides");export function aiCompare(e){const{a:t,b:n,ratesOf:s}=e,a=K(t),c=K(n),u=a.map(o=>te(o.key,o.rows,s)),d=c.map(o=>te(o.key,o.rows,s)),l=ae(t,a,u,s),i=ae(n,c,d,s),b=he(l,i),j=Ce.map(o=>re(o,l,i,u,d,b.differs)),y=new Map,m=new Map,w=new Map([...t.rows,...n.rows].map(o=>[o.id,o])),$=r(o=>{if(y.has(o))return y.get(o);const x=e.requests?.get(o),S=w.get(o);let A;if(!x)m.set(o,"its request was not read");else if("why"in x)m.set(o,x.why);else if(S){try{A=se(S.api,x.body)}catch{A=void 0}A||m.set(o,"its request is not one the lens can read (an embedding, or not an object)")}return y.set(o,A),A},"joined"),p=D(a),f=D(c),M=(p?.rows??[]).slice(0,AI_COMPARE_MAX_CALLS),C=(f?.rows??[]).slice(0,AI_COMPARE_MAX_CALLS),q=new Re,V=r(o=>{const x=o?ee(o,s):void 0;return x?E(x.input):void 0},"usdOf"),Y=ce(M,C,$).map(o=>{const x={...o.a?{a:o.a.id}:{},...o.b?{b:o.b.id}:{},label:o.label,...o.prewarm?{prewarm:!0}:{},...o.match?{match:o.match}:{},input:[o.a?.tokens?.input??null,o.b?.tokens?.input??null],inputUsd:[V(o.a)??null,V(o.b)??null],output:[o.a?.tokens?.output??null,o.b?.tokens?.output??null],ms:[o.a?.durationMs??null,o.b?.durationMs??null]};if(!o.a||!o.b)return x;const S=$(o.a.id),A=$(o.b.id);return!S||!A?{...x,unread:[S?"":`${t.name}: ${m.get(o.a.id)}`,A?"":`${n.name}: ${m.get(o.b.id)}`].filter(Boolean).join("; ")}:{...x,...ue(S,A,[o.a.tokens?.input,o.b.tokens?.input],q)}});for(const[o,x]of[[l,M],[i,C]]){const S=x.find(B=>B.prewarm),A=S?$(S.id):void 0;if(!S||!A)continue;const X=x.filter(B=>!B.prewarm).map(B=>$(B.id)).filter(B=>!!B);o.prewarm={id:S.id,prefixOf:X.filter(B=>JSON.stringify(B.settings)===JSON.stringify(A.settings)&&B.flat.startsWith(A.flat)).length,of:X.length}}const O=Y.filter(o=>!o.prewarm),G=O.some(o=>o.a&&o.b&&o.same===void 0),T=O.filter(o=>!o.a||!o.b),P=O.filter(o=>o.same===!1),I=P.length||T.length?!1:G?void 0:O.length?!0:void 0,h=O.filter(o=>o.same&&o.cut&&(o.cut.blocks[0]!==o.cut.blocks[1]||o.cut.breakpoints[0]!==o.cut.breakpoints[1]||o.cut.mode[0]!==o.cut.mode[1])),g=P.find(o=>o.diff||o.settings),_=I===!0?`The ${i.name} requests, joined, are the ${l.name} requests byte for byte: ${O.length} call${O.length===1?"":"s"}, the same bytes and settings${h.length?` \u2014 ${h.length} cut otherwise (blocks ${h[0].cut.blocks.join(" \u2192 ")}, breakpoints ${h[0].cut.breakpoints.join(" \u2192 ")}, ${h[0].cut.mode.join(" \u2192 ")}): what the cache sees changed, what the model reads did not`:""}.`:I===!1?`Not the same bytes: ${P.length} of ${O.length} pair${O.length===1?"":"s"} differ${T.length?`, ${T.length} call${T.length===1?"":"s"} on one side only`:""}`+(g?.settings?` \u2014 settings ${g.settings.join(", ")}`:"")+(g?.diff?` \u2014 the first, \xAB${g.label}\xBB, parts at \xAB${g.diff.region}\xBB (character ${Q(g.diff.char)}, byte ${Q(g.diff.byte)}): \xAB${g.diff.line??""}\xBB vs \xAB${g.diff.otherLine??""}\xBB`:"")+".":O.length?`Not every request was read (${O.filter(o=>o.unread).length} pair${O.filter(o=>o.unread).length===1?"":"s"}): whether the requests are the same bytes is not known.`:"No answering call on either side to diff.",F=`The ${l.name} ${t.unit} ${p?.key??"\u2014"} and the ${i.name} ${n.unit} ${f?.key??"\u2014"} (each side's ${t.unit===n.unit?t.unit:"repetition"} with the most calls, the earliest of those) are set call by call: a prewarm to a prewarm; then by action (and the app\u2019s part label) \u2014 one call each, by label; several, by the order they were sent; counts that differ, by the longest prefix their joined requests share.`+((p?.rows.length??0)>AI_COMPARE_MAX_CALLS||(f?.rows.length??0)>AI_COMPARE_MAX_CALLS?` The first ${AI_COMPARE_MAX_CALLS} calls of each.`:""),H=a.length<2&&c.length<2?"One run a side: no noise floor \u2014 a difference may be the model\u2019s own spread (seven runs of one request proposed 11 to 23 changes). Compare several runs a side.":`Noise floor: ${l.name} over ${a.length} ${t.unit}${a.length===1?"":"s"}, ${i.name} over ${c.length}${a.length===2||c.length===2?" \u2014 a floor of two runs is thin":""}. A measure is beyond noise when its ranges do not overlap, or a single run falls outside the other side\u2019s range.`,R=[];b.differs&&R.push(b.said);for(const[o,x]of[[l,u],[i,d]]){const S=x.reduce((N,z)=>N+z.uncounted,0),A=x.reduce((N,z)=>N+z.calls+z.prewarms,0);S&&R.push(`${o.name}: ${S} of ${A} calls kept no usage (a failed call, an answer the capture cut) \u2014 its tokens and dollars are over the ${A-S} counted.`);const X=x.reduce((N,z)=>N+(z.unpriced??0),0);X&&R.push(`${o.name}: ${X} counted call${X===1?"":"s"} with no price \u2014 in its tokens, not its dollars.`);const B=o.prices.filter(N=>N.stale);B.length&&R.push(`${o.name}: the price of ${B.map(N=>N.model).join(", ")} is stale (read ${B.map(N=>N.readAt??"?").join(", ")}): read the provider's page again.`),o.prewarm&&o.prewarm.prefixOf<o.prewarm.of&&R.push(`${o.name}: ${o.prewarm.of-o.prewarm.prefixOf} of ${o.prewarm.of} answering calls do not start with the prewarm's request \u2014 it warmed a prefix they do not share.`)}const U=l.models.join(", "),L=i.models.join(", ");U&&L&&U!==L&&R.push(`The sides called other models (${l.name}: ${U}; ${i.name}: ${L}).`);const ke=["Section tokens and the tokens before a difference are estimated from the text, scaled to the provider\u2019s count.",`Dollars are the provider\u2019s counts at the price table\u2019s rates (${[...l.prices,...i.prices].map(o=>`${o.model}: ${o.source??"no source"}${o.readAt?`, read ${o.readAt}`:""}`).filter((o,x,S)=>S.indexOf(o)===x).join("; ")||"no price"}) \u2014 not the provider\u2019s bill.`,"A call\u2019s speed is its output over its whole time, the wait for the first token included.",...m.size?[`${m.size} request${m.size===1?"":"s"} not diffed: ${[...new Set(m.values())].join("; ")}.`]:[]];return{a:l,b:i,measures:j,speed:b,requests:{how:F,pairs:Y,...I!==void 0?{identical:I}:{},said:_},noise:H,warnings:R,notVerified:ke}}k(aiCompare,"aiCompare"),v(aiCompare,"aiCompare"),r(aiCompare,"aiCompare");
package/lib/ai-context.js CHANGED
@@ -1,6 +1,6 @@
1
- "use strict";var P=Object.defineProperty;var $=(t,e)=>P(t,"name",{value:e,configurable:!0});var G=Object.defineProperty,g=$((t,e)=>G(t,"name",{value:e,configurable:!0}),"g");export const AI_PART_KINDS=["system","tools","schema","context","history","tool","turn","carried","unkept"],AI_PART_LABEL={system:"System prompt",tools:"Tool definitions",schema:"Answer schema",context:"Context",history:"Earlier turns",tool:"Tool calls & results",turn:"This turn",carried:"Held by the provider",unkept:"Not kept"},AI_PART_SAID={system:"The instructions every call of this agent starts with",tools:"The tools it was offered, as defined \u2014 sent with every call, called or not",schema:"The JSON schema its answer had to fit",context:"What the app put in beside the conversation (developer messages)",history:"The conversation before this turn \u2014 what was said, and answered",tool:"The tools it called earlier in this run, what it sent them and what came back",turn:"What this call asks \u2014 the latest message",carried:"The conversation of the response it continues (previous_response_id): counted by the provider, not in this request",unkept:"The end of the request, which the capture did not keep (a lens before 1.25.32 kept its first 64 KB): counted by the provider, not known here"};const R=/[\p{L}\p{M}]/u,W=/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u,D=/(\s*)([A-Za-z]+|[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]+|[\p{L}\p{M}]+|[0-9]+|[^\s\p{L}\p{M}0-9]+)|(\s+)/gu,B=4,I=.7;export function estimateTokens(t){let e=0;for(const o of t.matchAll(D)){const s=o[1],n=o[2];if(o[3]!==void 0){/\n| {2,}/.test(o[3])&&(e+=1);continue}if(s&&/\n| {2,}/.test(s)&&(e+=1),!n)continue;const r=n.charCodeAt(0);r>=65&&r<=90||r>=97&&r<=122?e+=1+(n.length>8?(n.length-8)/4:0):r>=48&&r<=57?e+=Math.ceil(n.length/3):W.test(n)?e+=[...n].length*.9:R.test(n)?e+=[...n].length*.66:e+=n.length*.75}return e}$(estimateTokens,"estimateTokens"),g(estimateTokens,"estimateTokens");const Z=/^[ \t]*-{3,}[ \t]*(.+?)[ \t]*-{3,}[ \t]*$/gm,U=/^(#{1,4})[ \t]+(.+?)[ \t]*#*[ \t]*$/gm,_=60;function C(t,e){const o=[],s=t.slice(0,e[0].at);return s.trim().length>40&&o.push({title:"(opening)",chars:s.length,tokens:0,at:0,end:e[0].at}),e.forEach((n,r)=>{const h=r+1<e.length?e[r+1].at:t.length;o.push({title:n.title.slice(0,120),chars:h-n.at,tokens:0,at:n.at,end:h})}),o}$(C,"P"),g(C,"cutAt");function M(t){const e=t.trim();if(!e.startsWith("{")&&!e.startsWith("["))return[];let o;try{o=JSON.parse(e)}catch{return[]}const s=o&&typeof o=="object"&&!Array.isArray(o)?o.properties:void 0,n=s&&typeof s=="object"&&!Array.isArray(s)?s:o,r=Array.isArray(n)?n.map((h,u)=>[`[${u}]`,h]):n&&typeof n=="object"?Object.entries(n):[];return r.length<2?[]:r.slice(0,_).map(([h,u])=>{const c=JSON.stringify(u,null,2)??"";return{title:h,chars:c.length,tokens:estimateTokens(c)}})}$(M,"M"),g(M,"jsonSections");export function sectionsOf(t){const e=taggedSections(t);return e.length?e:j(t)}$(sectionsOf,"sectionsOf"),g(sectionsOf,"sectionsOf");function j(t){if(t.length<200)return[];let e=g((s,n,r=()=>!0)=>[...t.matchAll(s)].filter(r).map(h=>({at:h.index,title:n(h)})),"pick")(Z,s=>s[1]);if(e.length<2){const s=[...t.matchAll(U)],n=[1,2,3,4].find(r=>s.filter(h=>h[1].length===r).length>=2);e=n?s.filter(r=>r[1].length===n).map(r=>({at:r.index,title:r[2]})):[]}if(e.length<2)return M(t);const o=C(t,e.slice(0,_));for(const s of o){const n=t.slice(s.at,s.end);s.tokens=estimateTokens(n);const r=n.indexOf(`
2
- `),h=r>0?M(n.slice(r+1)):[];h.length&&(s.children=h)}return o}$(j,"N"),g(j,"plainSections");export const STABLE_TAGS=new Set(["instructions","rules","output","examples"]),CHANGING_TAGS=new Set(["memory","status","data","task"]);const F=/<([a-z][a-z0-9_-]{0,40})((?:\s+[A-Za-z_][\w.:-]*\s*=\s*(?:"[^"]*"|'[^']*'))*)\s*>/g,Q=/([A-Za-z_][\w.:-]*)\s*=\s*(?:"([^"]*)"|'([^']*)')/g,X=g(t=>t.replace(/&quot;/g,'"').replace(/&apos;/g,"'").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&"),"unescape");function H(t){const e={};for(const o of t.matchAll(Q))e[o[1]]=X(o[2]??o[3]??"");return e}$(H,"q"),g(H,"attrsOf");function L(t,e,o,s){const n=`<${e}`,r=`</${e}>`;let h=1,u=o;for(;u<s;){const c=t.indexOf(r,u);if(c<0||c>=s)return-1;let f=t.indexOf(n,u);for(;f>=0&&f<c&&!/[\s>]/.test(t[f+n.length]??"");)f=t.indexOf(n,f+1);if(f>=0&&f<c){h++,u=f+n.length;continue}if(--h===0)return c;u=c+r.length}return-1}$(L,"z"),g(L,"closeOf");const V=g((t,e)=>{for(let o=e-1;o>=0;o--){const s=t[o];if(s===`
3
- `)return!0;if(s!==" "&&s!==" ")return!1}return!0},"atLineStart");export function taggedSections(t,e=0,o=t.length,s=0){const n=[],r=new RegExp(F.source,"g");let h=e;for(;h<o&&n.length<_;){r.lastIndex=h;const l=r.exec(t);if(!l||l.index>=o)break;const p=l[1],k=l.index+l[0].length,x=V(t,l.index)?L(t,p,k,o):-1;if(x<0){h=k;continue}const i=x+p.length+3,d=H(l[2]??""),b={title:p,tag:p,...Object.keys(d).length?{attrs:d}:{},chars:i-l.index,tokens:estimateTokens(t.slice(l.index,i)),at:l.index,end:i};if(s<1){const w=taggedSections(t,k,x,s+1).filter(a=>a.tag),v=w.length?w:j(t.slice(k,x)).map(a=>a.at===void 0?a:{...a,at:a.at+k,end:a.end+k});v.length&&(b.children=v)}n.push(b),h=i}if(!n.length)return[];const u=[];let c=e;const f=g((l,p)=>{const k=t.slice(l,p);k.trim().length>20&&u.push({title:"(untagged)",chars:p-l,tokens:estimateTokens(k),at:l,end:p})},"gap");for(const l of n)f(c,l.at),u.push(l),c=l.end;f(c,o);const y=new Map;for(const l of u){if(!l.tag)continue;const p=l.attrs?.id?`${l.tag} \xB7 ${l.attrs.id}`:l.tag,k=(y.get(p)??0)+1;y.set(p,k),l.title=k>1?`${p} #${k}`:p}return u}$(taggedSections,"taggedSections"),g(taggedSections,"taggedSections");function N(t,e){const o=t.reduce((s,n)=>s+n.tokens,0);for(const s of t)s.tokens=o>0?Math.round(s.tokens/o*e):0,s.children&&N(s.children,s.tokens)}$(N,"I"),g(N,"scaleSections");const Y={user:"user",assistant:"assistant",developer:"Context \xB7 developer message",system:"system message"};function E(t,e,o){if(t.kind==="reasoning")return t.text?{kind:"history",label:"reasoning \xB7 sent back",role:"assistant",ref:{turn:e},text:t.text,estimate:estimateTokens(t.text)+B}:void 0;if(t.kind==="tool"){const s=`${t.name}(${t.arguments})${t.output!==void 0?`
4
- ${t.output}`:""}`;return{kind:"tool",label:`tool \xB7 ${t.tool}${t.output!==void 0?" \u2014 called, and its result":" \u2014 called"}`,role:"tool",ref:{turn:e},text:s,estimate:estimateTokens(s)+B*(t.output!==void 0?2:1)}}return{kind:o,label:Y[t.role],role:t.role,ref:{turn:e},text:t.text,estimate:estimateTokens(t.text)+B}}$(E,"Z"),g(E,"turnDraft");function J(t){const e=t.turns;let o=e.length;for(;o>0&&e[o-1].kind==="message"&&e[o-1].role!=="assistant";)o--;return e.map((s,n)=>s.kind==="tool"?"tool":s.kind==="reasoning"?"history":s.role==="developer"||s.role==="system"?"context":n>=o&&s.role==="user"?"turn":"history")}$(J,"F"),g(J,"turnKinds");function K(t){const e=t.system.map((c,f)=>({kind:"system",label:c.source==="instructions"?"System prompt \xB7 instructions":`System prompt \xB7 ${c.source}`,ref:{system:f},text:c.text,estimate:estimateTokens(c.text)+B})),o=t.tools.map(c=>JSON.stringify({name:c.name,description:c.description,parameters:c.parameters})).join(`
5
- `),s=t.tools.length?[{kind:"tools",label:`${t.tools.length} tool${t.tools.length===1?"":"s"} offered`,ref:{tools:!0},text:o,estimate:estimateTokens(o)*I}]:[],n=t.answer.format?.schema!==void 0?JSON.stringify(t.answer.format.schema):"",r=n?[{kind:"schema",label:`Answer schema${t.answer.format?.name?` \xB7 ${t.answer.format.name}`:""}`,ref:{schema:!0},text:n,estimate:estimateTokens(n)*I}]:[],h=J(t),u=t.turns.map((c,f)=>E(c,f,h[f])).filter(c=>!!c);for(const c of u){const f=t.turns[c.ref.turn];f.kind==="message"&&f.attachments?.length&&(c.label+=` \xB7 ${f.attachments.join(", ")}`)}return t.provider==="anthropic"?[...s,...e,...r,...u]:[...e,...s,...r,...u]}$(K,"U"),g(K,"draftsOf");export function aiContextOf(t,e={}){const o=e.sections!==!1,s=K(t),n=Math.round(s.reduce((a,m)=>a+m.estimate,0)),r=t.usage,h=r?.input!==void 0&&r.input>0,u=h?r.input:n,c=t.settings.some(a=>a.name==="continues response"),f=t.gaps.some(a=>/^The (request was kept to its first|prompt was not kept)/.test(a)),y=h&&(c||f)&&u>n*1.05?u-n:0,l=c?y:0,p=c?0:y,k=n>0?(u-y)/n:0,x=s.map((a,m)=>({i:m,kind:a.kind,label:a.label,...a.role?{role:a.role}:{},ref:a.ref,chars:a.text.length,tokens:Math.round(a.estimate*k),cached:0,sections:!o||a.kind==="tools"?[]:sectionsOf(a.text)}));l&&x.unshift({i:-1,kind:"carried",label:"The conversation it continues",ref:{carried:!0},chars:0,tokens:l,cached:0,sections:[]}),p&&x.push({i:-1,kind:"unkept",label:"The rest of the request \u2014 not kept",ref:{unkept:!0},chars:0,tokens:p,cached:0,sections:[]});const i=u-x.reduce((a,m)=>a+m.tokens,0);i&&x.length&&(x.reduce((a,m)=>m.tokens>a.tokens?m:a).tokens+=i);for(const a of x)a.kind==="tools"&&o&&(a.sections=t.tools.map(m=>({title:m.server?`${m.server} \u203A ${m.tool}`:m.tool,chars:0,tokens:estimateTokens(JSON.stringify({d:m.description,p:m.parameters}))}))),N(a.sections,a.tokens);x.forEach((a,m)=>a.i=m);const d=Math.min(r?.cached??0,u);let b=d;for(const a of x)a.cached=Math.min(a.tokens,b),b-=a.cached;const w=AI_PART_KINDS.map(a=>{const m=x.filter(A=>A.kind===a);return{kind:a,tokens:m.reduce((A,T)=>A+T.tokens,0),cached:m.reduce((A,T)=>A+T.cached,0),parts:m.length}}).filter(a=>a.parts),v=q(t);return{parts:x,byKind:w,input:u,counted:h,cached:d,...r?.written?{written:r.written}:{},estimated:n,output:v,findings:z(t,x,u,d,v)}}$(aiContextOf,"aiContextOf"),g(aiContextOf,"aiContextOf");function q(t){const e=t.answer,o=e.json!==void 0?JSON.stringify(e.json):e.text??e.refusal??"",s=e.toolCalls.map(p=>`${p.name}(${p.arguments})`).join(`
6
- `),n=estimateTokens(o),r=estimateTokens(s)+e.toolCalls.length*B,h=t.usage,u=h?.output!==void 0,c=u?h.output:Math.round(n+r),f=Math.min(h?.reasoning??0,c),y=c-f,l=n+r>0?Math.round(r/(n+r)*y):0;return{total:c,reasoning:f,answer:y-l,tools:l,counted:u}}$(q,"X"),g(q,"outputOf");const S=g(t=>Math.round(t).toLocaleString("en-US"),"fmt"),O=g((t,e)=>`${e>0?Math.round(t/e*100):0}%`,"pct");function z(t,e,o,s,n){const r=[],h=t.answer;if(h.status==="incomplete"||/max_output_tokens|length|max_tokens/.test(h.finish??"")){const i=t.settings.find(d=>/max output|max_tokens|max_completion/.test(d.name));r.push({tone:"bad",text:`It stopped at its output cap${i?` (${i.name} ${i.value})`:""} \u2014 the answer is cut.`})}t.gaps.length&&r.push({tone:"warn",text:"Part of the call was not kept \u2014 the split covers what was."});const u=t.turns.reduce((i,d)=>i+(d.kind==="message"?d.attachments?.length??0:0),0);u&&r.push({tone:"info",text:`${u} image${u===1?"":"s"} or file${u===1?"":"s"} went with its messages: their tokens are counted by the provider but not read from the text, so the split spreads them over the parts.`});const c=t.usage;if(c?.input!==void 0&&o>=1024){if(!s)r.push({tone:"warn",text:`None of its ${S(o)} input tokens came from the prompt cache${c.written?` \u2014 ${S(c.written)} were written to it, for a later call that opens the same way`:""}.`});else if(s<o*.9){const w=e.find(v=>v.cached<v.tokens);w&&r.push({tone:"info",text:`${O(s,o)} cached \u2014 the cache stopped in \xAB${w.label}\xBB: from there on the prompt differed from the last call that opened the same way.`})}const i=e.findIndex(w=>w.kind==="context"),d=i>=0?e.slice(i+1).filter(w=>w.kind==="history"||w.kind==="tool"):[],b=d.reduce((w,v)=>w+v.tokens,0);i>=0&&d.length>=2&&e[i].cached<e[i].tokens&&b>0&&r.push({tone:"info",text:`The context the app put in sits before ${d.length} earlier turns (${S(b)} tokens): when it changes between calls, nothing after it can be read from the cache.`})}const f=e.flatMap(i=>i.sections.filter(d=>d.tag).map(d=>({p:i,x:d}))),y=f.findIndex(({x:i})=>CHANGING_TAGS.has(i.tag)),l=y>=0?f.slice(y+1).filter(({x:i})=>STABLE_TAGS.has(i.tag)):[];if(y>=0&&l.length){const i=f[y].x,d=l.reduce((b,{x:w})=>b+w.tokens,0);r.push({tone:"info",text:`\xAB${i.title}\xBB changes from call to call and comes before ${l.length} section${l.length===1?"":"s"} that should not (\xAB${l[0].x.title}\xBB\u2026, ${S(d)} tokens): put the stable ones first, or they cannot be read from the cache.`})}const p=e.filter(i=>i.kind!=="carried").reduce((i,d)=>!i||d.tokens>i.tokens?d:i,void 0);if(p&&o>2e3&&p.tokens>o*.5){const i=p.sections.reduce((d,b)=>!d||b.tokens>d.tokens?b:d,void 0);r.push({tone:"info",text:`\xAB${p.label}\xBB is ${O(p.tokens,o)} of the input${i&&i.tokens>p.tokens*.4?` \u2014 most of it \xAB${i.title}\xBB (${S(i.tokens)} tokens)`:""}.`})}const k=e.find(i=>i.kind==="tools"),x=h.toolCalls.length;return k&&k.tokens>o*.2&&!x&&!t.turns.some(i=>i.kind==="tool")&&r.push({tone:"info",text:`${t.tools.length} tool definitions are ${O(k.tokens,o)} of the input, and it called none of them.`}),n.total>=200&&n.reasoning>n.total*.7&&r.push({tone:"info",text:`${O(n.reasoning,n.total)} of its output was reasoning (${S(n.reasoning)} tokens).`}),r}$(z,"Q"),g(z,"findingsOf");export function aiSplitOf(t){return Object.fromEntries(t.byKind.filter(e=>e.tokens>0).map(e=>[e.kind,e.tokens]))}$(aiSplitOf,"aiSplitOf"),g(aiSplitOf,"aiSplitOf");
1
+ "use strict";var G=Object.defineProperty;var $=(t,e)=>G(t,"name",{value:e,configurable:!0});var R=Object.defineProperty,y=$((t,e)=>R(t,"name",{value:e,configurable:!0}),"$"),W=Object.defineProperty,g=y((t,e)=>W(t,"name",{value:e,configurable:!0}),"g");export const AI_PART_KINDS=["system","tools","schema","context","history","tool","turn","carried","unkept"],AI_PART_LABEL={system:"System prompt",tools:"Tool definitions",schema:"Answer schema",context:"Context",history:"Earlier turns",tool:"Tool calls & results",turn:"This turn",carried:"Held by the provider",unkept:"Not kept"},AI_PART_SAID={system:"The instructions every call of this agent starts with",tools:"The tools it was offered, as defined \u2014 sent with every call, called or not",schema:"The JSON schema its answer had to fit",context:"What the app put in beside the conversation (developer messages)",history:"The conversation before this turn \u2014 what was said, and answered",tool:"The tools it called earlier in this run, what it sent them and what came back",turn:"What this call asks \u2014 the latest message",carried:"The conversation of the response it continues (previous_response_id): counted by the provider, not in this request",unkept:"The end of the request, which the capture did not keep (a lens before 1.25.32 kept its first 64 KB): counted by the provider, not known here"};const Z=/[\p{L}\p{M}]/u,D=/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u,U=/(\s*)([A-Za-z]+|[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]+|[\p{L}\p{M}]+|[0-9]+|[^\s\p{L}\p{M}0-9]+)|(\s+)/gu,B=4,z=.7;export function estimateTokens(t){let e=0;for(const s of t.matchAll(U)){const o=s[1],n=s[2];if(s[3]!==void 0){/\n| {2,}/.test(s[3])&&(e+=1);continue}if(o&&/\n| {2,}/.test(o)&&(e+=1),!n)continue;const r=n.charCodeAt(0);r>=65&&r<=90||r>=97&&r<=122?e+=1+(n.length>8?(n.length-8)/4:0):r>=48&&r<=57?e+=Math.ceil(n.length/3):D.test(n)?e+=[...n].length*.9:Z.test(n)?e+=[...n].length*.66:e+=n.length*.75}return e}$(estimateTokens,"estimateTokens"),y(estimateTokens,"estimateTokens"),g(estimateTokens,"estimateTokens");const F=/^[ \t]*-{3,}[ \t]*(.+?)[ \t]*-{3,}[ \t]*$/gm,Q=/^(#{1,4})[ \t]+(.+?)[ \t]*#*[ \t]*$/gm,I=60;function C(t,e){const s=[],o=t.slice(0,e[0].at);return o.trim().length>40&&s.push({title:"(opening)",chars:o.length,tokens:0,at:0,end:e[0].at}),e.forEach((n,r)=>{const h=r+1<e.length?e[r+1].at:t.length;s.push({title:n.title.slice(0,120),chars:h-n.at,tokens:0,at:n.at,end:h})}),s}$(C,"C"),y(C,"P"),g(C,"cutAt");function T(t){const e=t.trim();if(!e.startsWith("{")&&!e.startsWith("["))return[];let s;try{s=JSON.parse(e)}catch{return[]}const o=s&&typeof s=="object"&&!Array.isArray(s)?s.properties:void 0,n=o&&typeof o=="object"&&!Array.isArray(o)?o:s,r=Array.isArray(n)?n.map((h,u)=>[`[${u}]`,h]):n&&typeof n=="object"?Object.entries(n):[];return r.length<2?[]:r.slice(0,I).map(([h,u])=>{const c=JSON.stringify(u,null,2)??"";return{title:h,chars:c.length,tokens:estimateTokens(c)}})}$(T,"M"),y(T,"M"),g(T,"jsonSections");export function sectionsOf(t){const e=taggedSections(t);return e.length?e:_(t)}$(sectionsOf,"sectionsOf"),y(sectionsOf,"sectionsOf"),g(sectionsOf,"sectionsOf");function _(t){if(t.length<200)return[];let e=g((o,n,r=()=>!0)=>[...t.matchAll(o)].filter(r).map(h=>({at:h.index,title:n(h)})),"pick")(F,o=>o[1]);if(e.length<2){const o=[...t.matchAll(Q)],n=[1,2,3,4].find(r=>o.filter(h=>h[1].length===r).length>=2);e=n?o.filter(r=>r[1].length===n).map(r=>({at:r.index,title:r[2]})):[]}if(e.length<2)return T(t);const s=C(t,e.slice(0,I));for(const o of s){const n=t.slice(o.at,o.end);o.tokens=estimateTokens(n);const r=n.indexOf(`
2
+ `),h=r>0?T(n.slice(r+1)):[];h.length&&(o.children=h)}return s}$(_,"j"),y(_,"N"),g(_,"plainSections");export const STABLE_TAGS=new Set(["instructions","rules","output","examples"]),CHANGING_TAGS=new Set(["memory","status","data","task"]);const X=/<([a-z][a-z0-9_-]{0,40})((?:\s+[A-Za-z_][\w.:-]*\s*=\s*(?:"[^"]*"|'[^']*'))*)\s*>/g,V=/([A-Za-z_][\w.:-]*)\s*=\s*(?:"([^"]*)"|'([^']*)')/g,Y=g(t=>t.replace(/&quot;/g,'"').replace(/&apos;/g,"'").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&"),"unescape");function H(t){const e={};for(const s of t.matchAll(V))e[s[1]]=Y(s[2]??s[3]??"");return e}$(H,"H"),y(H,"q"),g(H,"attrsOf");function L(t,e,s,o){const n=`<${e}`,r=`</${e}>`;let h=1,u=s;for(;u<o;){const c=t.indexOf(r,u);if(c<0||c>=o)return-1;let f=t.indexOf(n,u);for(;f>=0&&f<c&&!/[\s>]/.test(t[f+n.length]??"");)f=t.indexOf(n,f+1);if(f>=0&&f<c){h++,u=f+n.length;continue}if(--h===0)return c;u=c+r.length}return-1}$(L,"L"),y(L,"z"),g(L,"closeOf");const tt=g((t,e)=>{for(let s=e-1;s>=0;s--){const o=t[s];if(o===`
3
+ `)return!0;if(o!==" "&&o!==" ")return!1}return!0},"atLineStart");export function taggedSections(t,e=0,s=t.length,o=0){const n=[],r=new RegExp(X.source,"g");let h=e;for(;h<s&&n.length<I;){r.lastIndex=h;const l=r.exec(t);if(!l||l.index>=s)break;const p=l[1],k=l.index+l[0].length,x=tt(t,l.index)?L(t,p,k,s):-1;if(x<0){h=k;continue}const a=x+p.length+3,d=H(l[2]??""),v={title:p,tag:p,...Object.keys(d).length?{attrs:d}:{},chars:a-l.index,tokens:estimateTokens(t.slice(l.index,a)),at:l.index,end:a};if(o<1){const w=taggedSections(t,k,x,o+1).filter(i=>i.tag),S=w.length?w:_(t.slice(k,x)).map(i=>i.at===void 0?i:{...i,at:i.at+k,end:i.end+k});S.length&&(v.children=S)}n.push(v),h=a}if(!n.length)return[];const u=[];let c=e;const f=g((l,p)=>{const k=t.slice(l,p);k.trim().length>20&&u.push({title:"(untagged)",chars:p-l,tokens:estimateTokens(k),at:l,end:p})},"gap");for(const l of n)f(c,l.at),u.push(l),c=l.end;f(c,s);const b=new Map;for(const l of u){if(!l.tag)continue;const p=l.attrs?.id?`${l.tag} \xB7 ${l.attrs.id}`:l.tag,k=(b.get(p)??0)+1;b.set(p,k),l.title=k>1?`${p} #${k}`:p}return u}$(taggedSections,"taggedSections"),y(taggedSections,"taggedSections"),g(taggedSections,"taggedSections");function M(t,e){const s=t.reduce((o,n)=>o+n.tokens,0);for(const o of t)o.tokens=s>0?Math.round(o.tokens/s*e):0,o.children&&M(o.children,o.tokens)}$(M,"N"),y(M,"I"),g(M,"scaleSections");const et={user:"user",assistant:"assistant",developer:"Context \xB7 developer message",system:"system message"};function E(t,e,s){if(t.kind==="reasoning")return t.text?{kind:"history",label:"reasoning \xB7 sent back",role:"assistant",ref:{turn:e},text:t.text,estimate:estimateTokens(t.text)+B}:void 0;if(t.kind==="tool"){const o=`${t.name}(${t.arguments})${t.output!==void 0?`
4
+ ${t.output}`:""}`;return{kind:"tool",label:`tool \xB7 ${t.tool}${t.output!==void 0?" \u2014 called, and its result":" \u2014 called"}`,role:"tool",ref:{turn:e},text:o,estimate:estimateTokens(o)+B*(t.output!==void 0?2:1)}}return{kind:s,label:et[t.role],role:t.role,ref:{turn:e},text:t.text,estimate:estimateTokens(t.text)+B}}$(E,"E"),y(E,"Z"),g(E,"turnDraft");function J(t){const e=t.turns;let s=e.length;for(;s>0&&e[s-1].kind==="message"&&e[s-1].role!=="assistant";)s--;return e.map((o,n)=>o.kind==="tool"?"tool":o.kind==="reasoning"?"history":o.role==="developer"||o.role==="system"?"context":n>=s&&o.role==="user"?"turn":"history")}$(J,"J"),y(J,"F"),g(J,"turnKinds");function K(t){const e=t.system.map((c,f)=>({kind:"system",label:c.source==="instructions"?"System prompt \xB7 instructions":`System prompt \xB7 ${c.source}`,ref:{system:f},text:c.text,estimate:estimateTokens(c.text)+B})),s=t.tools.map(c=>JSON.stringify({name:c.name,description:c.description,parameters:c.parameters})).join(`
5
+ `),o=t.tools.length?[{kind:"tools",label:`${t.tools.length} tool${t.tools.length===1?"":"s"} offered`,ref:{tools:!0},text:s,estimate:estimateTokens(s)*z}]:[],n=t.answer.format?.schema!==void 0?JSON.stringify(t.answer.format.schema):"",r=n?[{kind:"schema",label:`Answer schema${t.answer.format?.name?` \xB7 ${t.answer.format.name}`:""}`,ref:{schema:!0},text:n,estimate:estimateTokens(n)*z}]:[],h=J(t),u=t.turns.map((c,f)=>E(c,f,h[f])).filter(c=>!!c);for(const c of u){const f=t.turns[c.ref.turn];f.kind==="message"&&f.attachments?.length&&(c.label+=` \xB7 ${f.attachments.join(", ")}`)}return t.provider==="anthropic"?[...o,...e,...r,...u]:[...e,...o,...r,...u]}$(K,"K"),y(K,"U"),g(K,"draftsOf");export function aiContextOf(t,e={}){const s=e.sections!==!1,o=K(t),n=Math.round(o.reduce((i,m)=>i+m.estimate,0)),r=t.usage,h=r?.input!==void 0&&r.input>0,u=h?r.input:n,c=t.settings.some(i=>i.name==="continues response"),f=t.gaps.some(i=>/^The (request was kept to its first|prompt was not kept)/.test(i)),b=h&&(c||f)&&u>n*1.05?u-n:0,l=c?b:0,p=c?0:b,k=n>0?(u-b)/n:0,x=o.map((i,m)=>({i:m,kind:i.kind,label:i.label,...i.role?{role:i.role}:{},ref:i.ref,chars:i.text.length,tokens:Math.round(i.estimate*k),cached:0,sections:!s||i.kind==="tools"?[]:sectionsOf(i.text)}));l&&x.unshift({i:-1,kind:"carried",label:"The conversation it continues",ref:{carried:!0},chars:0,tokens:l,cached:0,sections:[]}),p&&x.push({i:-1,kind:"unkept",label:"The rest of the request \u2014 not kept",ref:{unkept:!0},chars:0,tokens:p,cached:0,sections:[]});const a=u-x.reduce((i,m)=>i+m.tokens,0);a&&x.length&&(x.reduce((i,m)=>m.tokens>i.tokens?m:i).tokens+=a);for(const i of x)i.kind==="tools"&&s&&(i.sections=t.tools.map(m=>({title:m.server?`${m.server} \u203A ${m.tool}`:m.tool,chars:0,tokens:estimateTokens(JSON.stringify({d:m.description,p:m.parameters}))}))),M(i.sections,i.tokens);x.forEach((i,m)=>i.i=m);const d=Math.min(r?.cached??0,u);let v=d;for(const i of x)i.cached=Math.min(i.tokens,v),v-=i.cached;const w=AI_PART_KINDS.map(i=>{const m=x.filter(O=>O.kind===i);return{kind:i,tokens:m.reduce((O,N)=>O+N.tokens,0),cached:m.reduce((O,N)=>O+N.cached,0),parts:m.length}}).filter(i=>i.parts),S=P(t);return{parts:x,byKind:w,input:u,counted:h,cached:d,...r?.written?{written:r.written}:{},estimated:n,output:S,findings:q(t,x,u,d,S)}}$(aiContextOf,"aiContextOf"),y(aiContextOf,"aiContextOf"),g(aiContextOf,"aiContextOf");function P(t){const e=t.answer,s=e.json!==void 0?JSON.stringify(e.json):e.text??e.refusal??"",o=e.toolCalls.map(p=>`${p.name}(${p.arguments})`).join(`
6
+ `),n=estimateTokens(s),r=estimateTokens(o)+e.toolCalls.length*B,h=t.usage,u=h?.output!==void 0,c=u?h.output:Math.round(n+r),f=Math.min(h?.reasoning??0,c),b=c-f,l=n+r>0?Math.round(r/(n+r)*b):0;return{total:c,reasoning:f,answer:b-l,tools:l,counted:u}}$(P,"q"),y(P,"X"),g(P,"outputOf");const A=g(t=>Math.round(t).toLocaleString("en-US"),"fmt"),j=g((t,e)=>`${e>0?Math.round(t/e*100):0}%`,"pct");function q(t,e,s,o,n){const r=[],h=t.answer;if(h.status==="incomplete"||/max_output_tokens|length|max_tokens/.test(h.finish??"")){const a=t.settings.find(d=>/max output|max_tokens|max_completion/.test(d.name));r.push({tone:"bad",text:`It stopped at its output cap${a?` (${a.name} ${a.value})`:""} \u2014 the answer is cut.`})}t.gaps.length&&r.push({tone:"warn",text:"Part of the call was not kept \u2014 the split covers what was."});const u=t.turns.reduce((a,d)=>a+(d.kind==="message"?d.attachments?.length??0:0),0);u&&r.push({tone:"info",text:`${u} image${u===1?"":"s"} or file${u===1?"":"s"} went with its messages: their tokens are counted by the provider but not read from the text, so the split spreads them over the parts.`});const c=t.usage;if(c?.input!==void 0&&s>=1024){if(!o)r.push({tone:"warn",text:`None of its ${A(s)} input tokens came from the prompt cache${c.written?` \u2014 ${A(c.written)} were written to it, for a later call that opens the same way`:""}.`});else if(o<s*.9){const w=e.find(S=>S.cached<S.tokens);w&&r.push({tone:"info",text:`${j(o,s)} cached \u2014 the cache stopped in \xAB${w.label}\xBB: from there on the prompt differed from the last call that opened the same way.`})}const a=e.findIndex(w=>w.kind==="context"),d=a>=0?e.slice(a+1).filter(w=>w.kind==="history"||w.kind==="tool"):[],v=d.reduce((w,S)=>w+S.tokens,0);a>=0&&d.length>=2&&e[a].cached<e[a].tokens&&v>0&&r.push({tone:"info",text:`The context the app put in sits before ${d.length} earlier turns (${A(v)} tokens): when it changes between calls, nothing after it can be read from the cache.`})}const f=e.flatMap(a=>a.sections.filter(d=>d.tag).map(d=>({p:a,x:d}))),b=f.findIndex(({x:a})=>CHANGING_TAGS.has(a.tag)),l=b>=0?f.slice(b+1).filter(({x:a})=>STABLE_TAGS.has(a.tag)):[];if(b>=0&&l.length){const a=f[b].x,d=l.reduce((v,{x:w})=>v+w.tokens,0);r.push({tone:"info",text:`\xAB${a.title}\xBB changes from call to call and comes before ${l.length} section${l.length===1?"":"s"} that should not (\xAB${l[0].x.title}\xBB\u2026, ${A(d)} tokens): put the stable ones first, or they cannot be read from the cache.`})}const p=e.filter(a=>a.kind!=="carried").reduce((a,d)=>!a||d.tokens>a.tokens?d:a,void 0);if(p&&s>2e3&&p.tokens>s*.5){const a=p.sections.reduce((d,v)=>!d||v.tokens>d.tokens?v:d,void 0);r.push({tone:"info",text:`\xAB${p.label}\xBB is ${j(p.tokens,s)} of the input${a&&a.tokens>p.tokens*.4?` \u2014 most of it \xAB${a.title}\xBB (${A(a.tokens)} tokens)`:""}.`})}const k=e.find(a=>a.kind==="tools"),x=h.toolCalls.length;return k&&k.tokens>s*.2&&!x&&!t.turns.some(a=>a.kind==="tool")&&r.push({tone:"info",text:`${t.tools.length} tool definitions are ${j(k.tokens,s)} of the input, and it called none of them.`}),n.total>=200&&n.reasoning>n.total*.7&&r.push({tone:"info",text:`${j(n.reasoning,n.total)} of its output was reasoning (${A(n.reasoning)} tokens).`}),r}$(q,"z"),y(q,"Q"),g(q,"findingsOf");export function aiSplitOf(t){return Object.fromEntries(t.byKind.filter(e=>e.tokens>0).map(e=>[e.kind,e.tokens]))}$(aiSplitOf,"aiSplitOf"),y(aiSplitOf,"aiSplitOf"),g(aiSplitOf,"aiSplitOf");
package/lib/ai-origins.js CHANGED
@@ -1,10 +1,10 @@
1
- "use strict";var It=Object.defineProperty;var v=(t,e)=>It(t,"name",{value:e,configurable:!0});var Mt=Object.defineProperty,c=v((t,e)=>Mt(t,"name",{value:e,configurable:!0}),"a");import{aiContextOf as at}from"./ai-context.js";const ct=8,lt=24,ft=32,Nt=80,ut=400,Tt=200,Ct=1e6,Jt=12;export function normText(t){return(t.includes("\\")?t.replace(/\\[nrt]/g," ").replace(/\\(["\\/])/g,"$1"):t).replace(/\s\s+|[^\S ]/g," ").trim()}v(normText,"normText"),c(normText,"normText");function S(t){const e=t.trim();if(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]"))try{return JSON.stringify(JSON.parse(e))}catch{}return normText(e)}v(S,"I"),c(S,"canonical");const W=ft,G=16777619,qt=(()=>{let t=1;for(let e=1;e<W;e++)t=Math.imul(t,G);return t})(),dt=1<<18,ht=dt-1;function Q(t){let e=0;for(let s=0;s<W;s++)e=Math.imul(e,G)+t.charCodeAt(s)|0;return e}v(Q,"ue"),c(Q,"headHash");class Wt{static{v(this,"Ne")}static{c(this,"PassageIndex")}constructor(){this.by=new Map,this.bits=new Uint32Array(dt>>>5),this.n=0}add(e){const s=Q(e.text),r=this.by.get(s);r?r.push(e):this.by.set(s,[e]),this.bits[(s&ht)>>>5]|=1<<(s&31),this.n++}get size(){return this.n}find(e,s){if(!this.n||e.length<W)return;const r=new Set,n=this.bits;let a=Q(e);for(let u=0;;u++){const h=(n[(a&ht)>>>5]&1<<(a&31))!==0?this.by.get(a):void 0;if(h)for(const w of h)!r.has(w)&&e.startsWith(w.text,u)&&(r.add(w),s(w));if(u+W>=e.length)break;a=Math.imul(a-Math.imul(e.charCodeAt(u),qt)|0,G)+e.charCodeAt(u+W)|0}}}const pt=c(t=>t.replace(/^(?:mcp__)?[A-Za-z0-9-]+(?:_[A-Za-z0-9-]+)*__/,""),"toolName");function C(t,e,s,r=0){if(!(r>Jt)){if(typeof t=="string")e(t,s);else if(Array.isArray(t))for(const n of t)C(n,e,s,r+1);else if(t&&typeof t=="object")for(const[n,a]of Object.entries(t))C(a,e,n,r+1)}}v(C,"T"),c(C,"strings");const V=c(t=>{const e=t.trim();if(!(!e.startsWith("{")&&!e.startsWith("[")))try{return JSON.parse(e)}catch{return}},"parseJson");function gt(t){const e=t.answer,s=[],r=c((n,a)=>{const u=S(n);u.length>=ct&&s.push({key:u,text:normText(n),...a?{what:a}:{}})},"add");e.text!==void 0&&r(e.text),e.json!==void 0&&(e.text===void 0&&r(JSON.stringify(e.json)),C(e.json,(n,a)=>{n.trim().length>=lt&&r(n,a?`its \xAB${a}\xBB`:void 0)}));for(const n of e.toolCalls){const a=n.tool||pt(n.name);r(n.arguments,`its call of ${a}`),C(V(n.arguments),(u,h)=>{u.trim().length>=lt&&r(u,h?`${a}\u2019s \xAB${h}\xBB`:`its call of ${a}`)})}return s}v(gt,"_e"),c(gt,"answerKeys");function wt(t){const e=[],s=new Set,r=c((h,w,x)=>{if(e.length>=Tt||s.has(h))return;s.add(h);const O={text:h,e:t,...w?{what:w}:{},...x?{parent:x}:{}};return e.push(O),O},"push"),n=c((h,w,x,O)=>{const[j,...K]=O;if(j)for(const J of h.split(j)){const N=normText(J);if(N.length<Nt||N===x?.text)continue;const R=r(N,w,x)??x;N.length>ut&&n(J,w,R,K)}},"pieces"),a=c((h,w)=>{const x=normText(h);if(x.length<ft)return;const O=r(x,w);x.length>ut&&n(h,w,O,[/\n\s*\n/,/\n/,/(?<=[.!?:;])\s+/])},"text"),u=t.call.answer;u.json!==void 0?C(u.json,(h,w)=>a(h,w?`its \xAB${w}\xBB`:void 0)):u.text!==void 0&&a(u.text);for(const h of u.toolCalls){const w=h.tool||pt(h.name),x=V(h.arguments);x!==void 0?C(x,(O,j)=>a(O,j?`${w}\u2019s \xAB${j}\xBB`:`its call of ${w}`)):a(h.arguments,`its call of ${w}`)}return e}v(wt,"je"),c(wt,"passagesOf");function mt(t){const e=[];let s=Ct;const r=c(n=>{if(s<=0||!n)return;const a=n.length>s?n.slice(0,s):n;s-=a.length,e.push(a)},"take");for(const n of t.system)r(n.text);for(const n of t.turns)n.kind==="tool"?(r(n.arguments),r(n.output??"")):r(n.text??"");return e}v(mt,"Te"),c(mt,"inputTexts");function _(t,e){const s=e.ref;if("system"in s)return t.system[s.system]?.text??"";if("tools"in s)return t.tools.map(r=>JSON.stringify({name:r.name,description:r.description,parameters:r.parameters})).join(`
2
- `);if("schema"in s)return t.answer.format?.schema!==void 0?JSON.stringify(t.answer.format.schema):"";if("turn"in s){const r=t.turns[s.turn];return r?r.kind==="tool"?`${r.name}(${r.arguments})${r.output!==void 0?`
3
- ${r.output}`:""}`:r.text??"":""}return""}v(_,"K"),c(_,"partText");export const aiPartText=c((t,e)=>_(t,e),"aiPartText"),aiSectionTexts=c((t,e)=>z(t,e,_(t,e)),"aiSectionTexts");function $t(t){const e=V(t);if(e===void 0)return[];const s=e&&typeof e=="object"&&!Array.isArray(e)?e.properties:void 0,r=s&&typeof s=="object"&&!Array.isArray(s)?s:e;return(Array.isArray(r)?r:r&&typeof r=="object"?Object.values(r):[]).map(n=>typeof n=="string"?n:JSON.stringify(n,null,2)??"")}v($t,"Ee"),c($t,"jsonMemberTexts");function z(t,e,s){if(e.kind==="tools")return t.tools.map(n=>JSON.stringify({d:n.description,p:n.parameters}));let r;return e.sections.map((n,a)=>n.at!==void 0&&n.end!==void 0?s.slice(n.at,n.end):(r??=$t(s),r[a]??""))}v(z,"B"),c(z,"sectionTexts");function E(t){const e=new Map;return t.sections.map(s=>{const r=e.get(s.title)??0;return e.set(s.title,r+1),`${s.title}#${r}`})}v(E,"F"),c(E,"titled");function X(t){return t?t.kind==="tool"?`tool
1
+ "use strict";var Mt=Object.defineProperty;var v=(t,e)=>Mt(t,"name",{value:e,configurable:!0});var Tt=Object.defineProperty,y=v((t,e)=>Tt(t,"name",{value:e,configurable:!0}),"v"),Nt=Object.defineProperty,c=y((t,e)=>Nt(t,"name",{value:e,configurable:!0}),"a");import{aiContextOf as ht}from"./ai-context.js";const pt=8,gt=24,wt=32,qt=80,mt=400,Jt=200,Ct=1e6,Wt=12;export function normText(t){return(t.includes("\\")?t.replace(/\\[nrt]/g," ").replace(/\\(["\\/])/g,"$1"):t).replace(/\s\s+|[^\S ]/g," ").trim()}v(normText,"normText"),y(normText,"normText"),c(normText,"normText");function b(t){const e=t.trim();if(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]"))try{return JSON.stringify(JSON.parse(e))}catch{}return normText(e)}v(b,"S"),y(b,"I"),c(b,"canonical");const P=wt,Y=16777619,_t=(()=>{let t=1;for(let e=1;e<P;e++)t=Math.imul(t,Y);return t})(),$t=1<<18,vt=$t-1;function D(t){let e=0;for(let r=0;r<P;r++)e=Math.imul(e,Y)+t.charCodeAt(r)|0;return e}v(D,"Q"),y(D,"ue"),c(D,"headHash");class zt{static{v(this,"Wt")}static{y(this,"Ne")}static{c(this,"PassageIndex")}constructor(){this.by=new Map,this.bits=new Uint32Array($t>>>5),this.n=0}add(e){const r=D(e.text),o=this.by.get(r);o?o.push(e):this.by.set(r,[e]),this.bits[(r&vt)>>>5]|=1<<(r&31),this.n++}get size(){return this.n}find(e,r){if(!this.n||e.length<P)return;const o=new Set,n=this.bits;let i=D(e);for(let u=0;;u++){const h=(n[(i&vt)>>>5]&1<<(i&31))!==0?this.by.get(i):void 0;if(h)for(const w of h)!o.has(w)&&e.startsWith(w.text,u)&&(o.add(w),r(w));if(u+P>=e.length)break;i=Math.imul(i-Math.imul(e.charCodeAt(u),_t)|0,Y)+e.charCodeAt(u+P)|0}}}const yt=c(t=>t.replace(/^(?:mcp__)?[A-Za-z0-9-]+(?:_[A-Za-z0-9-]+)*__/,""),"toolName");function N(t,e,r,o=0){if(!(o>Wt)){if(typeof t=="string")e(t,r);else if(Array.isArray(t))for(const n of t)N(n,e,r,o+1);else if(t&&typeof t=="object")for(const[n,i]of Object.entries(t))N(i,e,n,o+1)}}v(N,"C"),y(N,"T"),c(N,"strings");const tt=c(t=>{const e=t.trim();if(!(!e.startsWith("{")&&!e.startsWith("[")))try{return JSON.parse(e)}catch{return}},"parseJson");function et(t){const e=t.answer,r=[],o=c((n,i)=>{const u=b(n);u.length>=pt&&r.push({key:u,text:normText(n),...i?{what:i}:{}})},"add");e.text!==void 0&&o(e.text),e.json!==void 0&&(e.text===void 0&&o(JSON.stringify(e.json)),N(e.json,(n,i)=>{n.trim().length>=gt&&o(n,i?`its \xAB${i}\xBB`:void 0)}));for(const n of e.toolCalls){const i=n.tool||yt(n.name);o(n.arguments,`its call of ${i}`),N(tt(n.arguments),(u,h)=>{u.trim().length>=gt&&o(u,h?`${i}\u2019s \xAB${h}\xBB`:`its call of ${i}`)})}return r}v(et,"gt"),y(et,"_e"),c(et,"answerKeys");function nt(t){const e=[],r=new Set,o=c((h,w,x)=>{if(e.length>=Jt||r.has(h))return;r.add(h);const A={text:h,e:t,...w?{what:w}:{},...x?{parent:x}:{}};return e.push(A),A},"push"),n=c((h,w,x,A)=>{const[B,...R]=A;if(B)for(const z of h.split(B)){const q=normText(z);if(q.length<qt||q===x?.text)continue;const U=o(q,w,x)??x;q.length>mt&&n(z,w,U,R)}},"pieces"),i=c((h,w)=>{const x=normText(h);if(x.length<wt)return;const A=o(x,w);x.length>mt&&n(h,w,A,[/\n\s*\n/,/\n/,/(?<=[.!?:;])\s+/])},"text"),u=t.call.answer;u.json!==void 0?N(u.json,(h,w)=>i(h,w?`its \xAB${w}\xBB`:void 0)):u.text!==void 0&&i(u.text);for(const h of u.toolCalls){const w=h.tool||yt(h.name),x=tt(h.arguments);x!==void 0?N(x,(A,B)=>i(A,B?`${w}\u2019s \xAB${B}\xBB`:`its call of ${w}`)):i(h.arguments,`its call of ${w}`)}return e}v(nt,"wt"),y(nt,"je"),c(nt,"passagesOf");function st(t){const e=[];let r=Ct;const o=c(n=>{if(r<=0||!n)return;const i=n.length>r?n.slice(0,r):n;r-=i.length,e.push(i)},"take");for(const n of t.system)o(n.text);for(const n of t.turns)n.kind==="tool"?(o(n.arguments),o(n.output??"")):o(n.text??"");return e}v(st,"mt"),y(st,"Te"),c(st,"inputTexts");function C(t,e){const r=e.ref;if("system"in r)return t.system[r.system]?.text??"";if("tools"in r)return t.tools.map(o=>JSON.stringify({name:o.name,description:o.description,parameters:o.parameters})).join(`
2
+ `);if("schema"in r)return t.answer.format?.schema!==void 0?JSON.stringify(t.answer.format.schema):"";if("turn"in r){const o=t.turns[r.turn];return o?o.kind==="tool"?`${o.name}(${o.arguments})${o.output!==void 0?`
3
+ ${o.output}`:""}`:o.text??"":""}return""}v(C,"_"),y(C,"K"),c(C,"partText");export const aiPartText=c((t,e)=>C(t,e),"aiPartText"),aiSectionTexts=c((t,e)=>W(t,e,C(t,e)),"aiSectionTexts");function ot(t){const e=tt(t);if(e===void 0)return[];const r=e&&typeof e=="object"&&!Array.isArray(e)?e.properties:void 0,o=r&&typeof r=="object"&&!Array.isArray(r)?r:e;return(Array.isArray(o)?o:o&&typeof o=="object"?Object.values(o):[]).map(n=>typeof n=="string"?n:JSON.stringify(n,null,2)??"")}v(ot,"$t"),y(ot,"Ee"),c(ot,"jsonMemberTexts");function W(t,e,r){if(e.kind==="tools")return t.tools.map(n=>JSON.stringify({d:n.description,p:n.parameters}));let o;return e.sections.map((n,i)=>n.at!==void 0&&n.end!==void 0?r.slice(n.at,n.end):(o??=ot(r),o[i]??""))}v(W,"z"),y(W,"B"),c(W,"sectionTexts");function _(t){const e=new Map;return t.sections.map(r=>{const o=e.get(r.title)??0;return e.set(r.title,o+1),`${r.title}#${o}`})}v(_,"E"),y(_,"F"),c(_,"titled");function G(t){return t?t.kind==="tool"?`tool
4
4
  ${t.name}
5
- ${S(t.arguments)}
6
- ${S(t.output??"")}`:t.kind==="reasoning"?`reasoning
7
- ${S(t.text??"")}`:`${t.role}
8
- ${S(t.text)}`:""}v(X,"le"),c(X,"turnKey");const _t=new Set(["system","tools","schema","context"]),vt=new Set(["history","tool","turn"]);function Y(t){const e=new Map,s=new Map;for(const r of t){if(!_t.has(r.kind))continue;const n=`${r.kind}:${r.role??""}`,a=e.get(n)??0;e.set(n,a+1),s.set(r,`${n}#${a}`)}return s}v(Y,"pe"),c(Y,"structureKeys");const xt=c(t=>t.toLocaleString("en-US"),"fmt"),D=c(t=>t.k===1?"the call before":`${t.k} calls earlier`,"ago"),P=c(t=>({id:t.row.id,agent:t.row.agent.name,...t.row.step!==void 0?{step:t.row.step}:{},at:t.row.at,service:t.row.service}),"fromOf"),yt={answer:6,"tool-output":6,quoted:5,carried:4,changed:3,unchanged:2,new:1};function kt(t,e){const s=e.filter(n=>n.row.agent.key===t.agent.key),r=[["thread",t.thread?n=>n.thread?.key===t.thread.key:void 0],["run",n=>n.run.key===t.run.key],["flow",t.flowId?n=>n.flowId===t.flowId:void 0],["request",t.requestId?n=>n.requestId===t.requestId:void 0]];for(const[n,a]of r)if(a){for(let u=s.length-1;u>=0;u--)if(a(s[u].row))return{e:s[u],by:n}}}v(kt,"We"),c(kt,"previousOf");export function aiOriginsOf(t,e,s){const r=s.filter(o=>o.row.id!==e.id&&o.row.at<=e.at).sort((o,i)=>o.row.at-i.row.at||o.row.id.localeCompare(i.row.id)),n=r.map((o,i)=>({row:o.row,call:o.call,k:r.length-i})),a=kt(e,n),u={compared:n.length,...a?{previous:{id:a.e.row.id,at:a.e.row.at,by:a.by}}:{},items:[]};if(!n.length)return u;const h=new Map,w=new Wt;for(const o of n){for(const i of gt(o.call)){const d=h.get(i.key);d?d.push({...i,e:o}):h.set(i.key,[{...i,e:o}])}for(const i of wt(o))w.add(i)}const x=new Map,O=new Map,j=c((o,i)=>{const d=`${o.k}
9
- ${i}`;let m=O.get(d);if(m===void 0){let l=x.get(o);l||x.set(o,l=mt(o.call).map(normText)),m=l.some(f=>f.includes(i)),O.set(d,m)}return m},"given"),K=c((o,...i)=>{for(const d of i){if(d===void 0)continue;const m=S(d),l=m.length>=ct?h.get(m):void 0;for(let f=(l?.length??0)-1;f>=0;f--){const y=l[f];if(o||!j(y.e,y.text))return{e:y.e,...y.what?{what:y.what}:{}}}}},"answerOf"),J=c((o,i=!1)=>{if(!w.size)return;const d=new Set;if(w.find(normText(o),f=>d.add(f)),!i)for(const f of d)j(f.e,f.text)&&d.delete(f);if(!d.size)return;const m=new Map;for(const f of d){let y=f.parent;for(;y&&!d.has(y);)y=y.parent;if(y)continue;const I=m.get(f.e)??{e:f.e,n:0,what:new Set};I.n++,f.what&&I.what.add(f.what),m.set(f.e,I)}let l;for(const f of m.values())(!l||f.n>l.n||f.n===l.n&&f.e.k<l.e.k)&&(l=f);return l},"quoteIn"),N=c(o=>({how:"answer",from:P(o.e),said:`the answer of ${o.e.row.agent.name}${o.what?` (${o.what})`:""}, ${D(o.e)}`}),"answered"),R=c(o=>({how:"quoted",from:P(o.e),passages:o.n,said:`quotes ${o.n===1?"a passage":`${o.n} passages`} of ${o.e.row.agent.name}\u2019s answer${o.what.size===1?` (${[...o.what][0]})`:""}, ${D(o.e)}`}),"quoted"),tt=at(t);let U,et=[];if(a){const o=at(a.e.call);U=new Map;for(const[i,d]of Y(o.parts))U.set(d,{part:i,text:_(a.e.call,i)});et=o.parts.filter(i=>vt.has(i.kind)&&"turn"in i.ref).map(i=>X(a.e.call.turns[i.ref.turn]))}const bt=c(o=>{const i=U?.get(o);if(i){if(!i.sections){const d=z(a.e.call,i.part,i.text);i.sections=new Map(E(i.part).map((m,l)=>[m,{text:d[l]??"",canon:S(d[l]??"")}]))}return i.sections}},"prevSections"),St=a?`the previous call of this ${a.by}`:"",B=a?P(a.e):void 0,nt=c((o,i)=>`changed since the previous call \u2014 ${xt(o)} \u2192 ${xt(i)} chars`,"changedSaid"),Ot=Y(tt.parts),ot=[...n].reverse();let rt=0;return tt.parts.forEach((o,i)=>{if(o.kind==="carried"){const p=e.previousResponseId??t.settings.find(g=>g.name==="continues response")?.value,$=p?ot.find(g=>(g.row.responseId??g.call.responseId)===p):void 0;$&&u.items.push({part:i,how:"carried",from:P($),said:`the conversation of ${$.row.agent.name}\u2019s response it continues, ${D($)} \u2014 held by the provider, not sent again`});return}const d=_(t,o),m="turn"in o.ref?t.turns[o.ref.turn]:void 0;let l,f;const y=Ot.get(o);if(a&&y){const p=U.get(y);p?S(p.text)===S(d)?l={part:i,how:"unchanged",from:B,said:`unchanged since ${St}`}:(l={part:i,how:"changed",from:B,said:nt(p.text.length,d.length),chars:{before:p.text.length,after:d.length}},f=bt(y)):l={part:i,how:"new",from:B,said:"new since the previous call"}}else if(a&&vt.has(o.kind)){const p=X(m),$=et.indexOf(p,rt);$>=0?(rt=$+1,l={part:i,how:"carried",from:B,said:"carried from the previous call"}):l={part:i,how:"new",from:B,said:"new since the previous call"}}const I=l&&l.how!=="carried"?l.how:l?"unchanged":void 0;let k;if(m?.kind==="tool"&&m.callId){const p=m.callId,$=ot.find(g=>g.row.callIds?.includes(p)||g.call.answer.toolCalls.some(b=>b.callId===p));if($){const g=$.row.step!==void 0&&$.row.run.key===e.run.key?`called in step ${$.row.step}`:`called by ${$.row.agent.name}, ${D($)}`;k={part:i,how:"tool-output",from:P($),said:`returned by tool ${m.tool} (${g})`}}}const Z=m?.kind==="message"&&m.role==="assistant";if(!k){const p=K(Z,m?.kind==="tool"?m.output:d);p&&(k={part:i,...N(p)})}const F=k?void 0:J(d,Z);F&&(k={part:i,...R(F)}),k&&I&&(k.since=I),k&&l?.chars&&(k.chars=l.chars);const T=k&&(!l||yt[k.how]>=yt[l.how])?k:l;if(T&&f&&T.how==="changed"){const p=new Set(E(o)),$=[...f.keys()].filter(A=>!p.has(A)).map(A=>A.replace(/#\d+$/,"")),g={changed:0,new:0},b=z(t,o,d);E(o).forEach((A,H)=>{const M=f.get(A);M?M.canon!==S(b[H]??"")&&g.changed++:g.new++});const q=[g.changed?`${g.changed} of ${o.sections.length} sections changed`:"",g.new?`${g.new} new`:"",$.length?`${$.length} gone (${$.slice(0,3).map(A=>`\xAB${A}\xBB`).join(", ")}${$.length>3?", \u2026":""})`:""].filter(Boolean);q.length&&(T.said+=`: ${q.join(", ")}`)}if(T&&u.items.push(T),!o.sections.length||T?.how==="answer"||T?.how==="tool-output")return;const At=z(t,o,d),jt=E(o),Bt=!!F;o.sections.forEach((p,$)=>{const g=At[$]??"";if(!g)return;let b;if(f){const L=f.get(jt[$]);L?L.canon===S(g)?b={part:i,section:p.title,how:"unchanged",from:B,said:"unchanged since the previous call"}:b={part:i,section:p.title,how:"changed",from:B,said:nt(L.text.length,g.length),chars:{before:L.text.length,after:g.length}}:b={part:i,section:p.title,how:"new",from:B,said:"new since the previous call"}}const q=p.at!==void 0&&p.title!=="(opening)"?g.indexOf(`
10
- `):-1,A=K(Z,g,q>0?g.slice(q+1):void 0),H=A?void 0:Bt?J(g,Z):void 0,M=A?{part:i,section:p.title,...N(A)}:H?{part:i,section:p.title,...R(H)}:void 0,st=b?b.how:I!=="changed"?I:void 0;M&&st&&(M.since=st),M&&b?.chars&&(M.chars=b.chars);const it=M??b;it&&u.items.push(it)})}),u}v(aiOriginsOf,"aiOriginsOf"),c(aiOriginsOf,"aiOriginsOf");
5
+ ${b(t.arguments)}
6
+ ${b(t.output??"")}`:t.kind==="reasoning"?`reasoning
7
+ ${b(t.text??"")}`:`${t.role}
8
+ ${b(t.text)}`:""}v(G,"X"),y(G,"le"),c(G,"turnKey");const Kt=new Set(["system","tools","schema","context"]),xt=new Set(["history","tool","turn"]);function Q(t){const e=new Map,r=new Map;for(const o of t){if(!Kt.has(o.kind))continue;const n=`${o.kind}:${o.role??""}`,i=e.get(n)??0;e.set(n,i+1),r.set(o,`${n}#${i}`)}return r}v(Q,"Y"),y(Q,"pe"),c(Q,"structureKeys");const kt=c(t=>t.toLocaleString("en-US"),"fmt"),V=c(t=>t.k===1?"the call before":`${t.k} calls earlier`,"ago"),E=c(t=>({id:t.row.id,agent:t.row.agent.name,...t.row.step!==void 0?{step:t.row.step}:{},at:t.row.at,service:t.row.service}),"fromOf"),bt={answer:6,"tool-output":6,quoted:5,carried:4,changed:3,unchanged:2,new:1};function rt(t,e){const r=e.filter(n=>n.row.agent.key===t.agent.key),o=[["thread",t.thread?n=>n.thread?.key===t.thread.key:void 0],["run",n=>n.run.key===t.run.key],["flow",t.flowId?n=>n.flowId===t.flowId:void 0],["request",t.requestId?n=>n.requestId===t.requestId:void 0]];for(const[n,i]of o)if(i){for(let u=r.length-1;u>=0;u--)if(i(r[u].row))return{e:r[u],by:n}}}v(rt,"kt"),y(rt,"We"),c(rt,"previousOf");export function aiOriginsOf(t,e,r){const o=r.filter(s=>s.row.id!==e.id&&s.row.at<=e.at).sort((s,a)=>s.row.at-a.row.at||s.row.id.localeCompare(a.row.id)),n=o.map((s,a)=>({row:s.row,call:s.call,k:o.length-a})),i=rt(e,n),u={compared:n.length,...i?{previous:{id:i.e.row.id,at:i.e.row.at,by:i.by}}:{},items:[]};if(!n.length)return u;const h=new Map,w=new zt;for(const s of n){for(const a of et(s.call)){const d=h.get(a.key);d?d.push({...a,e:s}):h.set(a.key,[{...a,e:s}])}for(const a of nt(s))w.add(a)}const x=new Map,A=new Map,B=c((s,a)=>{const d=`${s.k}
9
+ ${a}`;let m=A.get(d);if(m===void 0){let l=x.get(s);l||x.set(s,l=st(s.call).map(normText)),m=l.some(f=>f.includes(a)),A.set(d,m)}return m},"given"),R=c((s,...a)=>{for(const d of a){if(d===void 0)continue;const m=b(d),l=m.length>=pt?h.get(m):void 0;for(let f=(l?.length??0)-1;f>=0;f--){const k=l[f];if(s||!B(k.e,k.text))return{e:k.e,...k.what?{what:k.what}:{}}}}},"answerOf"),z=c((s,a=!1)=>{if(!w.size)return;const d=new Set;if(w.find(normText(s),f=>d.add(f)),!a)for(const f of d)B(f.e,f.text)&&d.delete(f);if(!d.size)return;const m=new Map;for(const f of d){let k=f.parent;for(;k&&!d.has(k);)k=k.parent;if(k)continue;const M=m.get(f.e)??{e:f.e,n:0,what:new Set};M.n++,f.what&&M.what.add(f.what),m.set(f.e,M)}let l;for(const f of m.values())(!l||f.n>l.n||f.n===l.n&&f.e.k<l.e.k)&&(l=f);return l},"quoteIn"),q=c(s=>({how:"answer",from:E(s.e),said:`the answer of ${s.e.row.agent.name}${s.what?` (${s.what})`:""}, ${V(s.e)}`}),"answered"),U=c(s=>({how:"quoted",from:E(s.e),passages:s.n,said:`quotes ${s.n===1?"a passage":`${s.n} passages`} of ${s.e.row.agent.name}\u2019s answer${s.what.size===1?` (${[...s.what][0]})`:""}, ${V(s.e)}`}),"quoted"),at=ht(t);let Z,it=[];if(i){const s=ht(i.e.call);Z=new Map;for(const[a,d]of Q(s.parts))Z.set(d,{part:a,text:C(i.e.call,a)});it=s.parts.filter(a=>xt.has(a.kind)&&"turn"in a.ref).map(a=>G(i.e.call.turns[a.ref.turn]))}const Ot=c(s=>{const a=Z?.get(s);if(a){if(!a.sections){const d=W(i.e.call,a.part,a.text);a.sections=new Map(_(a.part).map((m,l)=>[m,{text:d[l]??"",canon:b(d[l]??"")}]))}return a.sections}},"prevSections"),St=i?`the previous call of this ${i.by}`:"",I=i?E(i.e):void 0,ct=c((s,a)=>`changed since the previous call \u2014 ${kt(s)} \u2192 ${kt(a)} chars`,"changedSaid"),At=Q(at.parts),lt=[...n].reverse();let ft=0;return at.parts.forEach((s,a)=>{if(s.kind==="carried"){const p=e.previousResponseId??t.settings.find(g=>g.name==="continues response")?.value,$=p?lt.find(g=>(g.row.responseId??g.call.responseId)===p):void 0;$&&u.items.push({part:a,how:"carried",from:E($),said:`the conversation of ${$.row.agent.name}\u2019s response it continues, ${V($)} \u2014 held by the provider, not sent again`});return}const d=C(t,s),m="turn"in s.ref?t.turns[s.ref.turn]:void 0;let l,f;const k=At.get(s);if(i&&k){const p=Z.get(k);p?b(p.text)===b(d)?l={part:a,how:"unchanged",from:I,said:`unchanged since ${St}`}:(l={part:a,how:"changed",from:I,said:ct(p.text.length,d.length),chars:{before:p.text.length,after:d.length}},f=Ot(k)):l={part:a,how:"new",from:I,said:"new since the previous call"}}else if(i&&xt.has(s.kind)){const p=G(m),$=it.indexOf(p,ft);$>=0?(ft=$+1,l={part:a,how:"carried",from:I,said:"carried from the previous call"}):l={part:a,how:"new",from:I,said:"new since the previous call"}}const M=l&&l.how!=="carried"?l.how:l?"unchanged":void 0;let O;if(m?.kind==="tool"&&m.callId){const p=m.callId,$=lt.find(g=>g.row.callIds?.includes(p)||g.call.answer.toolCalls.some(S=>S.callId===p));if($){const g=$.row.step!==void 0&&$.row.run.key===e.run.key?`called in step ${$.row.step}`:`called by ${$.row.agent.name}, ${V($)}`;O={part:a,how:"tool-output",from:E($),said:`returned by tool ${m.tool} (${g})`}}}const F=m?.kind==="message"&&m.role==="assistant";if(!O){const p=R(F,m?.kind==="tool"?m.output:d);p&&(O={part:a,...q(p)})}const X=O?void 0:z(d,F);X&&(O={part:a,...U(X)}),O&&M&&(O.since=M),O&&l?.chars&&(O.chars=l.chars);const J=O&&(!l||bt[O.how]>=bt[l.how])?O:l;if(J&&f&&J.how==="changed"){const p=new Set(_(s)),$=[...f.keys()].filter(j=>!p.has(j)).map(j=>j.replace(/#\d+$/,"")),g={changed:0,new:0},S=W(t,s,d);_(s).forEach((j,H)=>{const T=f.get(j);T?T.canon!==b(S[H]??"")&&g.changed++:g.new++});const K=[g.changed?`${g.changed} of ${s.sections.length} sections changed`:"",g.new?`${g.new} new`:"",$.length?`${$.length} gone (${$.slice(0,3).map(j=>`\xAB${j}\xBB`).join(", ")}${$.length>3?", \u2026":""})`:""].filter(Boolean);K.length&&(J.said+=`: ${K.join(", ")}`)}if(J&&u.items.push(J),!s.sections.length||J?.how==="answer"||J?.how==="tool-output")return;const jt=W(t,s,d),Bt=_(s),It=!!X;s.sections.forEach((p,$)=>{const g=jt[$]??"";if(!g)return;let S;if(f){const L=f.get(Bt[$]);L?L.canon===b(g)?S={part:a,section:p.title,how:"unchanged",from:I,said:"unchanged since the previous call"}:S={part:a,section:p.title,how:"changed",from:I,said:ct(L.text.length,g.length),chars:{before:L.text.length,after:g.length}}:S={part:a,section:p.title,how:"new",from:I,said:"new since the previous call"}}const K=p.at!==void 0&&p.title!=="(opening)"?g.indexOf(`
10
+ `):-1,j=R(F,g,K>0?g.slice(K+1):void 0),H=j?void 0:It?z(g,F):void 0,T=j?{part:a,section:p.title,...q(j)}:H?{part:a,section:p.title,...U(H)}:void 0,ut=S?S.how:M!=="changed"?M:void 0;T&&ut&&(T.since=ut),T&&S?.chars&&(T.chars=S.chars);const dt=T??S;dt&&u.items.push(dt)})}),u}v(aiOriginsOf,"aiOriginsOf"),y(aiOriginsOf,"aiOriginsOf"),c(aiOriginsOf,"aiOriginsOf");
@@ -1,5 +1,5 @@
1
- "use strict";var xe=Object.defineProperty;var A=(e,s)=>xe(e,"name",{value:s,configurable:!0});var ve=Object.defineProperty,$=A((e,s)=>ve(e,"name",{value:s,configurable:!0}),"$");import{aiCacheDiff as le,aiCacheSections as be}from"./ai-cache.js";import{aiCacheMinTokens as Me}from"./ai-cache-facts.js";import{AI_CACHE_VERDICT_LABEL as ye}from"./ai-cache-verdict.js";import{estimateTokens as Q}from"./ai-context.js";export const FOLLOW_MS=1e3,MAX_LEVEL_RUNS=8;const de=200,Be=8,Y=4,Ae=200,y=$(e=>Math.round(e).toLocaleString("en-US"),"fmt"),R=$(e=>`$${Number(e.toFixed(4))}`,"rate"),_=$(e=>`$${e<.01&&e>0?e.toFixed(4):e.toFixed(e<1?3:2)}`,"money"),T=$(e=>Math.round(e*1e6)/1e6,"usd"),G=$(e=>{const s=[...e].sort((r,a)=>r-a);return s.length?s[Math.floor((s.length-1)/2)]:0},"median"),Z=$(e=>e<1e3?`${Math.round(e)} ms`:e<12e4?`${(e/1e3).toFixed(1)} s`:`${Math.round(e/1e3)} s`,"dur"),ue=$((e,s=Ae)=>e.length>s?`${e.slice(0,s-1)}\u2026`:e,"clip"),X=$(e=>e.at+(e.durationMs??0),"endOf"),ee=$((e,s)=>e.at-s.at||+!e.prewarm-+!s.prewarm||e.id.localeCompare(s.id),"byStart"),W=$(e=>e.tokens?.input!==void 0&&!e.failed,"counted"),Se=["tenant","tenant_id","tenantId","business","business_id","businessId","org","org_id","orgId","organization","account","account_id","accountId","customer","customer_id","customerId"],qe=["items","item_count","itemCount","n_items","batch_size","batchSize","rows","count"];export const tenantOf=$(e=>{for(const s of Se)if(e.meta?.[s]?.trim())return e.meta[s].trim()},"tenantOf");const te=$(e=>{for(const s of qe){const r=e.meta?.[s];if(r!==void 0&&/^\d{1,6}$/.test(r.trim()))return Number(r.trim())}},"itemsOf");export function aiTogetherScopeOf(e){if(e.run.from!=="alone")return{by:"run",key:e.run.key};if(e.flowId)return{by:"flow",key:`flow:${e.flowId}`};if(e.requestId)return{by:"request",key:`request:${e.requestId}`}}A(aiTogetherScopeOf,"aiTogetherScopeOf"),$(aiTogetherScopeOf,"aiTogetherScopeOf");function se(e){const s=new Map;for(const a of e){if(a.api==="embeddings")continue;const i=aiTogetherScopeOf(a);if(!i)continue;const l=`${a.agent.key}
2
- ${i.key}`,f=s.get(l);f?f.rows.push(a):s.set(l,{scope:i,rows:[a]})}const r=[];for(const{scope:a,rows:i}of s.values()){i.sort(ee);const l=[];for(const c of i){const u=l[l.length-1];u&&(c.at<u.end||c.at===u.at)?(u.rows.push(c),u.end=Math.max(u.end,X(c))):l.push({rows:[c],at:c.at,end:X(c)})}let f=[];const o=$(()=>{if(f.some(c=>c.rows.length>=2)){const c=f.flatMap(u=>u.rows);r.push({key:`${c[0].agent.key}|${a.key}|${c[0].id}`,scope:a,rows:c,waves:f.map(u=>u.rows)})}f=[]},"flush");for(const c of l){const u=f[f.length-1];u&&c.at-u.end>FOLLOW_MS&&o(),f.push(c)}o()}return r.sort((a,i)=>i.rows[0].at-a.rows[0].at||a.key.localeCompare(i.key))}A(se,"re"),$(se,"groupsOf");function he(e){const s=new Map;for(const r of e){if(r.api==="embeddings"||!r.cache?.marks?.length)continue;const a=aiTogetherScopeOf(r)?.key??`call:${r.id}`,i=s.get(a);i?i.push(r):s.set(a,[r])}return[...s.values()].map(r=>r.sort(ee).find(a=>!a.prewarm&&W(a))??r.find(a=>!a.prewarm)??r[0]).sort(ee)}A(he,"ye"),$(he,"representatives");export function aiTogetherPlan(e,s={}){const r=ne(se(e),s),a=ce(e,s);return{groups:r.flatMap(i=>i.rows.map(l=>l.id)),members:[...new Set(a.flatMap(i=>i.members.map(l=>l.id)))]}}A(aiTogetherPlan,"aiTogetherPlan"),$(aiTogetherPlan,"aiTogetherPlan");function ne(e,s){return s.focus?e.filter(r=>r.rows.some(a=>a.id===s.focus)):s.maxGroups!==void 0?e.slice(0,s.maxGroups):e}A(ne,"ce"),$(ne,"pickGroups");export function aiCalibratedMarks(e){const s=e.cache?.marks??[],r=e.tokens?.input;if(!s.length||r===void 0||e.failed||e.cache?.mode!=="explicit")return s;const a=e.tokens?.cached??0,i=e.tokens?.written??0,l=s.filter(p=>p.bp),f=$((p,m)=>m.reduce((x,w)=>!x||Math.abs(w.t-p)<Math.abs(x.t-p)?w:x,void 0),"nearest"),o=[[0,0]],c=new Set;let u=l;if(a>0){const p=f(a,l);p&&(o.push([p.t,a]),c.add(p),u=l.filter(m=>m.t>p.t))}if(i>0){const p=f(a+i,u);p&&(o.push([p.t,a+i]),c.add(p))}const n=s[s.length-1].t;n>o[o.length-1][0]&&o.push([n,Math.max(r,o[o.length-1][1])]);const d=$(p=>{for(let w=1;w<o.length;w++){const[M,B]=o[w-1],[q,j]=o[w];if(p<=q)return q===M?j:Math.round(B+(p-M)/(q-M)*(j-B))}const[m,x]=o[o.length-1];return Math.round(x+(p-m))},"at");return s.map(p=>({...p,t:d(p.t),...c.has(p)?{exact:!0}:{}}))}A(aiCalibratedMarks,"aiCalibratedMarks"),$(aiCalibratedMarks,"aiCalibratedMarks");function fe(e,s){return e.model?s(e.model,e.tokens?.input??0):void 0}A(fe,"be"),$(fe,"ratesFor");const oe=$((e,s)=>e.writes[s]??e.input,"writeRate");function pe(e,s){const r=e.rows,a=r[0],i=s.texts,l=a.at,f=Math.max(...r.map(X)),o=$(t=>r.reduce((h,g)=>h+(t(g)??0),0),"sum"),c={input:o(t=>t.tokens?.input),read:o(t=>t.tokens?.cached),written:o(t=>t.tokens?.written),plain:o(t=>t.tokens?.input!==void 0?Math.max(0,t.tokens.input-(t.tokens.cached??0)-(t.tokens.written??0)):0),output:o(t=>t.tokens?.output),reasoning:o(t=>t.tokens?.reasoning)},u=r.map(t=>{const h=t.cache?.verdict,g=te(t);return{id:t.id,at:t.at,...t.durationMs!==void 0?{ms:t.durationMs}:{},...t.prewarm?{prewarm:!0}:{},...t.failed?{failed:!0}:{},...t.tokens?.input!==void 0?{input:t.tokens.input}:{},...t.tokens?.cached?{read:t.tokens.cached}:{},...t.tokens?.written?{written:t.tokens.written}:{},...t.tokens?.output!==void 0?{output:t.tokens.output}:{},...t.tokens?.reasoning?{reasoning:t.tokens.reasoning}:{},...h?{verdict:h.kind,...h.race!==void 0?{race:h.race}:{}}:{},...g!==void 0?{items:g}:{}}}),n=r.filter(t=>W(t)&&t.cache?.marks?.length),d=n.map(aiCalibratedMarks),p=new Map,m=new Map;d.forEach((t,h)=>{for(const g of t){const v=p.get(g.h);v?v[v.length-1]!==h&&v.push(h):p.set(g.h,[h]);const I=m.get(g.h)??{ts:[]};I.ts.push(g.t),g.exact&&(I.exact=g.t),m.set(g.h,I)}});const x=$(t=>{const h=m.get(t);return h.exact??G(h.ts)},"one"),w=d.map(t=>t.map(h=>({...h,t:x(h.h)}))),M=new Set;if(n.length){const t=n[0],h=t.tokens?.cached??0,g=Math.max(256,(t.tokens?.input??0)*.03);if(h>0)for(const v of d[0])v.t<=h+g&&M.add(v.h)}const B=new Map;w.forEach((t,h)=>{let g=-1;for(let S=0;S<t.length;S++)(p.get(t[S].h)?.length??0)>=2&&(g=S);let v=0;const I=$(S=>`${p.get(t[S].h).join(",")}${M.has(t[S].h)?"w":""}`,"setOf");for(let S=0;S<=g;S++){const L=t[S];if(S<g&&I(S)===I(S+1))continue;let z=B.get(L.h);z||(z={h:L.h,holders:p.get(L.h),s:L.s,...t[S+1]?{next:t[S+1].s}:{},bp:!1,warm:M.has(L.h),seg:new Map,end:new Map,estimates:m.get(L.h).ts,exact:m.get(L.h).exact!==void 0},B.set(L.h,z)),z.bp||=!!L.bp,z.seg.set(h,Math.max(0,L.t-v)),z.end.set(h,L.t),v=L.t}});const q=[...B.values()].sort((t,h)=>h.holders.length-t.holders.length||G([...t.end.values()])-G([...h.end.values()])).map(t=>{const h=Math.min(...t.estimates),g=Math.max(...t.estimates);return{calls:t.holders.length,ids:t.holders.map(v=>n[v].id),tokens:G([...t.seg.values()]),endsAt:G([...t.end.values()]),...t.exact?{exact:!0}:h!==g?{estimates:[h,g]}:{},endsIn:t.s,...t.next?{partsIn:t.next}:{},breakpoint:t.bp,...t.warm?{warm:!0}:{}}}),j=me(r,n,B,s.ratesOf,e.waves),F={};let P=0;const D=[];for(const t of r){const h=t.cache?.verdict;if(h){F[h.kind]=(F[h.kind]??0)+1,P+=h.lostUsd??0;for(const g of h.costs)g.kind==="duplicate-write"&&D.push({id:t.id,race:!!h.race,...h.against?{against:h.against.id,inFlight:h.against.inFlight}:{},tokens:g.tokens,...g.usd!==void 0?{usd:g.usd}:{},...g.arithmetic?{arithmetic:g.arithmetic}:{},estimate:g.estimate})}}const H=r.find(t=>t.prewarm)?.id,N=$(t=>{const h=t.tokens?.output,g=te(t);return{id:t.id,ms:t.durationMs,...h!==void 0?{output:h}:{},...t.tokens?.reasoning?{reasoning:t.tokens.reasoning}:{},...h!==void 0&&t.durationMs>0?{perSecond:Math.round(h/(t.durationMs/1e3)*10)/10}:{},...g!==void 0?{items:g}:{}}},"timed"),V=r.filter(t=>!t.prewarm&&!t.failed&&t.durationMs!==void 0),J=V.reduce((t,h)=>!t||h.durationMs>t.durationMs?h:t,void 0),k=e.waves.map(t=>t.filter(h=>V.includes(h))).reduce((t,h)=>h.length>t.length?h:t,[]),b=k.length>=2?k.reduce((t,h)=>h.durationMs<t.durationMs?h:t):void 0,U=k.length>=2?k.reduce((t,h)=>h.durationMs>t.durationMs?h:t):void 0,O=V.filter(t=>t.tokens?.output!==void 0&&t.durationMs>0).map(t=>t.tokens.output/(t.durationMs/1e3)),C=a.thread?.key,E={key:e.key,agent:{key:a.agent.key,name:a.agent.name},scope:e.scope,...C?{thread:C}:{},calls:u,waves:e.waves.map(t=>({ids:t.map(h=>h.id),at:t[0].at,ms:Math.max(...t.map(X))-t[0].at})),at:l,end:f,ms:f-l,tokens:c,counted:r.filter(W).length,...j?{cost:j}:{},shared:q,cache:{verdicts:F,lostUsd:T(P),races:D.filter(t=>t.race).length,duplicates:D,...H?{prewarm:H}:{}},time:{...J?{slowest:N(J)}:{},...b&&U?{fastest:N(b),...b.durationMs>0?{spread:Math.round(U.durationMs/b.durationMs*10)/10}:{}}:{},...O.length?{perSecond:[Math.round(Math.min(...O)*10)/10,Math.round(Math.max(...O)*10)/10]}:{},itemsLabelled:r.some(t=>te(t)!==void 0)}};if(i){const t=aiAnswerFields(r.filter(v=>!v.prewarm).map(v=>({json:i.get(v.id)?.answer,visible:De(v)})));t&&(E.answer=t);const h=aiUnquotedSections(r.filter(v=>!v.prewarm).map(v=>({request:i.get(v.id)?.request,answer:i.get(v.id)?.answerText})));h&&(E.unquoted=h);const g=ie(r.filter(v=>!v.prewarm),i);g&&(E.firstDiff=g)}return E}A(pe,"ve"),$(pe,"group");const De=$(e=>e.tokens?.output!==void 0?Math.max(0,e.tokens.output-(e.tokens.reasoning??0)):void 0,"visibleOf");function me(e,s,r,a,i){const l=[],f=[];for(const k of e){if(!W(k)){l.push(k.failed?"failed":"no count");continue}const b=fe(k,a);b?f.push({r:k,rates:b}):l.push("no price")}if(!f.length)return;let o=0,c=0,u=0;const n=new Map;for(const{r:k,rates:b}of f){const U=k.tokens.cached??0,O=k.tokens.written??0,C=Math.max(0,k.tokens.input-U-O),E=b.cacheRead??b.input;o+=U,c+=C;let t=0;const h=Object.entries(k.cache?.writes??{}).filter(g=>typeof g[1]=="number"&&g[1]>0);if(h.length)for(const[g,v]of h){const I=oe(b,g);n.set(I,(n.get(I)??0)+v),t+=v*I}else if(O){const g=oe(b,k.cache?.ttl??"30m");n.set(g,(n.get(g)??0)+O),t+=O*g}u+=(U*E+t+C*b.input)/1e6}const d=f[0].rates,p=f.every(k=>k.rates===d||k.rates.input===d.input&&k.rates.cacheRead===d.cacheRead),m=p?`${y(o)} read \xD7 ${R(d.cacheRead??d.input)} + ${[...n].map(([k,b])=>`${y(b)} written \xD7 ${R(k)}`).join(" + ")||"0 written"} + ${y(c)} plain \xD7 ${R(d.input)}, per million = ${_(u)}`:`the provider's counts at each call's model's rates = ${_(u)}`,x=[];for(const{r:k,rates:b}of f){if(x.some(O=>O.model===k.model))continue;const U=k.cache?.ttl??"30m";x.push({model:k.model,input:b.input,...b.cacheRead!==void 0?{cacheRead:b.cacheRead}:{},...b.writes[U]!==void 0?{write:b.writes[U]}:{},ttl:U,...b.source?{source:b.source}:{},...b.readAt?{readAt:b.readAt}:{},...b.stale?{stale:!0}:{}})}const w=l.length?{calls:l.length,why:[...new Set(l)].join(", ")}:void 0,M={actualUsd:T(u),actual:m,estimate:!0,rates:x,...w?{left:w}:{}},B=new Map(s.map((k,b)=>[k.id,b]));if(!f.every(({r:k})=>B.has(k.id))){const k=f.filter(({r:b})=>!B.has(b.id)).length;return{...M,left:{calls:(w?.calls??0)+k,why:[w?.why,"no prefix marks (kept by a lens before 1.26.11)"].filter(Boolean).join(", ")}}}let q=0,j=0,F=0,P=0,D=0,H=0;const N=new Map;for(const{r:k,rates:b}of f){const U=B.get(k.id),O=b.input,C=b.cacheRead??O,E=Me(k.provider,k.model);let t=0;for(const g of r.values()){const v=g.seg.get(U);if(v===void 0)continue;const I=g.end.get(U);if(t=Math.max(t,I),I<E)P+=v,D+=v*O/1e6;else if(g.warm)F+=v,D+=v*C/1e6;else if(g.holders[0]===U){const S=oe(b,k.cache?.ttl??"30m");q+=v,N.set(S,(N.get(S)??0)+v),D+=v*S/1e6,H+=v*C/1e6}else j+=v,D+=v*C/1e6}const h=Math.max(0,k.tokens.input-t);P+=h,D+=h*O/1e6}const V=!e.some(k=>k.prewarm)&&i.some(k=>k.filter(b=>!b.prewarm).length>=2)&&q>0,J=p?`${F?`${y(F)} already cached, read \xD7 ${R(d.cacheRead??d.input)} + `:""}${[...N].map(([k,b])=>`${y(b)} written once \xD7 ${R(k)}`).join(" + ")||"0 written"} + ${y(j)} read \xD7 ${R(d.cacheRead??d.input)} + ${y(P)} each call's own, plain \xD7 ${R(d.input)}, per million = ${_(D)}`:`one write per shared prefix at each model's rates = ${_(D)}`;return{...M,idealUsd:T(D),ideal:J,gapUsd:T(T(u)-T(D)),...V?{prewarmUsd:T(D+H)}:{}}}A(me,"qe"),$(me,"costOf");const ae=$(e=>Q(JSON.stringify(e)??""),"jsonTokens");export function aiAnswerFields(e){const s=new Map,r=new Map;let a=0,i=0;for(const f of e){const o=f.json;if(!o||typeof o!="object")continue;i++;const c=Math.max(1,ae(o)),u=f.visible!==void 0&&f.visible>0?f.visible/c:1;a+=c*u;const n=Array.isArray(o)?{"[]":o}:o;for(const[p,m]of Object.entries(n))s.set(p,(s.get(p)??0)+(ae(m)+Q(p)+1)*u);const d=$((p,m)=>{if(Array.isArray(p)){const x=p.filter(w=>w&&typeof w=="object"&&!Array.isArray(w));if(x.length>=2){const w=r.get(`${m}[]`)??{rows:0,tokens:0};w.rows+=x.length,w.tokens+=x.reduce((M,B)=>M+ae(B),0)*u,r.set(`${m}[]`,w)}for(const w of p)d(w,`${m}[]`)}else if(p&&typeof p=="object")for(const[x,w]of Object.entries(p))d(w,m?`${m}.${x}`:x)},"walk");d(o,"")}if(!i||a<=0)return;const l=[...r].sort((f,o)=>o[1].tokens-f[1].tokens)[0];return{answers:i,tokens:Math.round(a),fields:[...s].sort((f,o)=>o[1]-f[1]).map(([f,o])=>({field:f,tokens:Math.round(o),share:Math.round(o/a*1e3)/1e3})),...l?{rows:{path:l[0],rows:l[1].rows,tokens:Math.round(l[1].tokens),perRow:Math.round(l[1].tokens/l[1].rows),share:Math.round(l[1].tokens/a*1e3)/1e3}}:{},estimate:!0}}A(aiAnswerFields,"aiAnswerFields"),$(aiAnswerFields,"aiAnswerFields");export function aiRequestSections(e){const s=[];let r=0;return e.blocks.forEach((a,i)=>{const l=be(a.text),f=$((o,c,u)=>{const n=a.text.slice(o,c);n.trim()&&s.push({k:i,block:a.label,title:u,text:n,at:r+o,tokens:Q(n)*(a.weight??1)})},"push");l.length?(l[0].at>0&&f(0,l[0].at,`${a.label} \u203A (opening)`),l.forEach((o,c)=>f(o.at,l[c+1]?.at??a.text.length,`${a.label} \u203A ${o.title}`))):f(0,a.text.length,a.label),r+=a.text.length}),s}A(aiRequestSections,"aiRequestSections"),$(aiRequestSections,"aiRequestSections");const Ue=/^(?:instructions|tools|answer schema)/,$e=$(e=>e.toLowerCase().match(/[\p{L}\p{N}]+/gu)??[],"words");function re(e){const s=new Set;for(let r=0;r+Y<=e.length;r++)s.add(e.slice(r,r+Y).join(" "));return s}A(re,"ue"),$(re,"shinglesOf");export function aiUnquotedSections(e){const s=new Map;let r=0;for(const i of e){if(!i.request||!i.answer)continue;r++;const l=$e(i.answer),f=re(l),o=new Set(l);for(const c of aiRequestSections(i.request)){if(Ue.test(c.block))continue;const u=$e(c.text),n=[...re(u)].some(p=>f.has(p))||u.some(p=>p.length>=6&&/\d/.test(p)&&/\p{L}/u.test(p)&&o.has(p)),d=s.get(c.title)??{tokens:0,calls:0,quoted:0};d.tokens=Math.max(d.tokens,Math.round(c.tokens)),d.calls++,n&&d.quoted++,s.set(c.title,d)}}if(!r)return;const a=[...s].filter(([,i])=>!i.quoted&&i.tokens>=de).sort((i,l)=>l[1].tokens-i[1].tokens).slice(0,Be).map(([i,l])=>({section:i,tokens:l.tokens,calls:l.calls}));return{measure:`a run of ${Y} words, or an id-like word, of the section found in the answer`,untested:!0,answers:r,candidates:a}}A(aiUnquotedSections,"aiUnquotedSections"),$(aiUnquotedSections,"aiUnquotedSections");function ie(e,s){const r=e.filter(c=>s.get(c.id)?.request);if(r.length<2)return;const a=r[0],i=s.get(a.id).request;let l;for(const c of r.slice(1)){const u=le(i,s.get(c.id).request,a.tokens?.input);u.same||(!l||u.chars<l.chars)&&(l={region:u.setting?`settings (${u.setting})`:u.region,...u.line!==void 0?{line:u.line}:{},...u.otherLine!==void 0?{otherLine:u.otherLine}:{},ids:[a.id,c.id],chars:u.chars})}if(!l)return;const{chars:f,...o}=l;return o}A(ie,"le"),$(ie,"firstDiffOf");function ge(e,s){if(e===s)return;let r=0;const a=Math.min(e.length,s.length);for(;r<a&&e.charCodeAt(r)===s.charCodeAt(r);)r++;const i=e.lastIndexOf(`
3
- `,r-1)+1,l=$(f=>{const o=f.indexOf(`
4
- `,i);return ue(f.slice(i,o<0?f.length:o).trim())},"lineOf");return{at:e.slice(0,i).split(`
5
- `).length,text:l(e),other:l(s)}}A(ge,"Oe"),$(ge,"lineDiff");export function aiSectionIdentity(e){if(e.length<2)return;const s=e[0],r=e.map(m=>aiRequestSections(m.request)),a=r.slice(1).map(m=>new Set(m.map(x=>x.text))),i=r[0].reduce((m,x)=>m+x.tokens,0),l=s.input!==void 0&&i>0?s.input/i:1;let f=1/0;for(const m of e.slice(1))f=Math.min(f,le(s.request,m.request).chars);let o=0,c=0,u=0;const n=new Map;for(const m of r[0]){const x=a.every(M=>M.has(m.text)),w=n.get(m.k)??{tokens:0,identical:0};w.tokens+=m.tokens*l,x&&(o+=m.tokens*l,u++,w.identical+=m.tokens*l,m.at+m.text.length<=f&&(c+=m.tokens*l)),n.set(m.k,w)}const d=i*l,p=$((m,x)=>x>0?Math.round(m/x*1e3)/1e3:0,"ratio");return{tokens:Math.round(o),of:Math.round(d),share:p(o,d),afterPrefix:Math.round(Math.max(0,o-c)),sections:u,ofSections:r[0].length,blocks:[...n].map(([m,x])=>{const w=s.request.blocks[m];let M;for(const B of e.slice(1)){const q=B.request.blocks[m],j=q&&q.label===w.label?ge(w.text,q.text):void 0;j&&(!M||j.at<M.at)&&(M={...j,id:B.id})}return{block:w.label,tokens:Math.round(x.tokens),identical:Math.round(x.identical),share:p(x.identical,x.tokens),...M?{line:M}:{}}}).filter(m=>m.tokens>0).sort((m,x)=>x.identical-m.identical||x.tokens-m.tokens)}}A(aiSectionIdentity,"aiSectionIdentity"),$(aiSectionIdentity,"aiSectionIdentity");function ce(e,s){const r=s.focus?e.find(n=>n.id===s.focus):void 0,a=new Set(e.map(n=>n.agent.key));if(s.levels===!1||!r&&a.size!==1)return[];const i=r?.agent.key??[...a][0],l=he(e.filter(n=>n.agent.key===i)),f=$(n=>n.slice(-MAX_LEVEL_RUNS),"newest"),o=[],c=$((n,d)=>{const p=new Map;for(const M of l){const B=d(M);if(!B)continue;const q=p.get(B);q?q.push(M):p.set(B,[M])}const m=[...p].filter(([,M])=>M.length>=2);if(!m.length)return;const x=r?d(r):void 0,w=m.find(([M])=>M===x)??[...m].sort((M,B)=>B[1].length-M[1].length||B[1][B[1].length-1].at-M[1][M[1].length-1].at)[0];o.push({level:n,key:w[0],members:f(w[1]),...m.length>1?{more:m.length-1}:{}})},"keyed");c("thread",n=>n.thread?.key),c("tenant",tenantOf),l.length>=2&&o.push({level:"all",members:f(l)});const u=$((n,d)=>n.members.length===d.members.length&&n.members.every((p,m)=>p.id===d.members[m].id),"same");return o.filter((n,d)=>!o.slice(0,d).some(p=>u(p,n)))}A(ce,"fe"),$(ce,"levelSets");function we(e,s){const r=e.members,a=r.map(aiCalibratedMarks),i=a.slice(1).map(c=>new Set(c.map(u=>u.h)));let l=-1;a[0].forEach((c,u)=>{i.every(n=>n.has(c.h))&&(l=u)});let f;if(l>=0){const c=a[0][l],u=a.map(w=>w.find(M=>M.h===c.h)??c),n=u.filter((w,M)=>W(r[M])),d=(n.length?n:u).map(w=>w.t),p=u.find(w=>w.exact)?.t,m=Math.min(...d),x=Math.max(...d);f={tokens:p??G(d),...p!==void 0?{exact:!0}:m!==x?{estimates:[m,x]}:{},endsIn:c.s,...a[0][l+1]?{partsIn:a[0][l+1].s}:{},breakpoint:u.some(w=>!!w.bp)}}const o={level:e.level,...e.key?{key:e.key}:{},runs:r.length,members:r.map(c=>c.id),...f?{prefix:f}:{},...e.more?{more:e.more}:{}};if(s){const c=r.filter(d=>s.get(d.id)?.request).map(d=>({id:d.id,request:s.get(d.id).request,input:d.tokens?.input})),u=aiSectionIdentity(c);u&&(o.identical=u);const n=ie(r,s);n&&(o.firstDiff=n)}return o}A(we,"Ie"),$(we,"level");export function aiTogether(e,s){const r=se(e),a=ne(r,s).map(o=>pe(o,s)),i=ce(e,s).map(o=>we(o,s.texts)),l=a.filter(o=>o.cost),f=l.filter(o=>o.cost.idealUsd!==void 0);return{groups:a,levels:i,totals:{groups:a.length,calls:a.reduce((o,c)=>o+c.calls.length,0),priced:l.length,actualUsd:T(f.reduce((o,c)=>o+c.cost.actualUsd,0)),idealUsd:T(f.reduce((o,c)=>o+c.cost.idealUsd,0)),gapUsd:T(f.reduce((o,c)=>o+c.cost.gapUsd,0)),races:a.reduce((o,c)=>o+c.cache.races,0),duplicates:a.reduce((o,c)=>o+c.cache.duplicates.length,0)}}}A(aiTogether,"aiTogether"),$(aiTogether,"aiTogether");const K=$(e=>`${Math.round(e*100)}%`,"pct"),ke=$(e=>e[0]===e[1]?y(e[0]):`${y(e[0])}\u2013${y(e[1])}`,"range");export function aiTogetherLines(e){const s=[],r=e.waves.map(n=>n.ids.length===1?e.calls.find(d=>d.id===n.ids[0])?.prewarm?"a prewarm":"1":`${n.ids.length} sent together`).join(", then "),a=e.tokens;s.push(`${e.calls.length} calls of ${e.scope.by} ${e.scope.key.replace(/^(?:run|flow|request):/,"")} in ${e.waves.length} wave${e.waves.length===1?"":"s"} (${r}), ${Z(e.ms)} from the first sent to the last answer`),s.push(`input ${y(a.input)} tokens over the ${e.counted} counted: ${y(a.read)} read from the cache, ${y(a.written)} written to it, ${y(a.plain)} plain; output ${y(a.output)}${a.reasoning?` (${y(a.reasoning)} reasoning)`:""}`);const i=e.cost;if(i){s.push(`input as billed \u2248 ${_(i.actualUsd)}: ${i.actual}`),i.idealUsd!==void 0&&(s.push(`ideal input \u2248 ${_(i.idealUsd)} (estimate \u2014 one write per shared prefix, the rest reads, each call's own tail plain): ${i.ideal}; gap \u2248 ${_(i.gapUsd??0)}`),i.prewarmUsd!==void 0&&s.push(`calls sent together reach that only once one write has finished \u2014 with a prewarm (P\xB7w + N\xB7P\xB7r) \u2248 ${_(i.prewarmUsd)}`)),i.left&&s.push(`left out of these sums: ${i.left.calls} call${i.left.calls===1?"":"s"} (${i.left.why})`);const n=i.rates.map(d=>`${d.model} input ${R(d.input)}, read ${d.cacheRead!==void 0?R(d.cacheRead):"as input"}, write ${d.ttl} ${d.write!==void 0?R(d.write):"as input"} per M \u2014 ${d.source??"no source"}${d.readAt?`, read ${d.readAt}`:""}${d.stale?", STALE":""}`);n.length&&s.push(`rates: ${n.join("; ")}`)}const l=e.calls.filter(n=>n.input!==void 0&&!n.failed).length;e.shared.forEach((n,d)=>{const p=n.estimates?` (by call ${ke(n.estimates)}: estimated)`:n.exact?" (the provider's count)":" (estimated)",m=d?` \u2014 ${n.exact?"":"\u2248 "}${y(n.endsAt)} from the start${p}`:p;s.push(`${n.calls===l?"all":n.calls} of its calls share ${d?"the next ":""}${n.exact?"":"\u2248 "}${y(n.tokens)} tokens, to the end of \xAB${n.endsIn}\xBB${m}${n.warm?"; already in the cache before the group":""}${n.partsIn?`; they part in \xAB${n.partsIn}\xBB`:""} \u2014 ${n.breakpoint?"a breakpoint ends it":"no breakpoint ends it: one belongs there"}`)}),e.firstDiff&&s.push(`where they part, to the line (${e.firstDiff.ids[0]} / ${e.firstDiff.ids[1]}), in \xAB${e.firstDiff.region}\xBB: \xAB${e.firstDiff.line??""}\xBB / \xAB${e.firstDiff.otherLine??""}\xBB`);const f=Object.entries(e.cache.verdicts);f.length&&s.push(`cache verdicts: ${f.sort((n,d)=>d[1]-n[1]).map(([n,d])=>`${ye[n]} \xD7${d}`).join(", ")}${e.cache.lostUsd?` \u2014 \u2248 ${_(e.cache.lostUsd)} lost`:""}${e.cache.prewarm?`; ${e.cache.prewarm} is a prewarm`:""}`);for(const n of e.cache.duplicates)s.push(` ${n.id} wrote the shared prefix again${n.race?` \u2014 a race: ${n.against??"the writer"} was still in flight`:n.against?` after ${n.against} had written it${n.inFlight===!1?" and ended \u2014 not a race":""}`:""}: ${n.arithmetic??y(n.tokens)}${n.usd!==void 0?` = ${_(n.usd)}`:""}${n.estimate?" (estimate)":""}`);const o=e.time;if(o.slowest){const n=o.slowest;s.push(`the slowest call ${n.id}: ${Z(n.ms)}${n.output!==void 0?`, ${y(n.output)} output tokens${n.reasoning?` (${y(n.reasoning)} reasoning)`:""}`:""}${n.perSecond!==void 0?` at ${n.perSecond} tokens a second`:""}${n.items!==void 0?`, ${n.items} items`:""} \u2014 the group waits for it`)}o.fastest&&s.push(`its fan-out's fastest ${o.fastest.id}: ${Z(o.fastest.ms)}${o.fastest.output!==void 0?`, ${y(o.fastest.output)} output tokens`:""}${o.fastest.items!==void 0?`, ${o.fastest.items} items`:""}${o.spread!==void 0?` \u2014 spread ${o.spread}\xD7`:""}${o.perSecond?`; output ${o.perSecond[0]}\u2013${o.perSecond[1]} tokens a second across its calls`:""}`),s.push(o.itemsLabelled?`items per call: ${e.calls.filter(n=>n.items!==void 0).map(n=>`${n.id} ${n.items}`).join(", ")}`:"items per call: the app labels none (metadata.items)");const c=e.answer;c&&(s.push(`the answer by field over ${c.answers} answer${c.answers===1?"":"s"} read (\u2248 ${y(c.tokens)} visible tokens, estimate): ${c.fields.slice(0,8).map(n=>`${n.field} ${K(n.share)} (${y(n.tokens)})`).join(", ")}`),c.rows&&s.push(` the largest repeated row kind ${c.rows.path}: ${y(c.rows.rows)} rows \u2248 ${y(c.rows.perRow)} tokens a row, ${K(c.rows.share)} of the answers`));const u=e.unquoted;return u&&s.push(u.candidates.length?`sections the answers never quote \u2014 candidates only (${u.measure}; untested as a measure), over ${u.answers} answers: ${u.candidates.map(n=>`\xAB${ue(n.section,70)}\xBB \u2248 ${y(n.tokens)} tokens in ${n.calls} call${n.calls===1?"":"s"}`).join("; ")}`:`every context section of ${de}+ tokens is quoted by some answer (${u.measure}; untested as a measure)`),s}A(aiTogetherLines,"aiTogetherLines"),$(aiTogetherLines,"aiTogetherLines");export function aiTogetherLevelLines(e){const s=[],r=e.level==="all"?`all its runs (the newest ${e.runs})`:`the ${e.runs} newest runs of ${e.level} ${e.key}${e.more?` (${e.more} other ${e.level}${e.more===1?"":"s"} of two runs or more)`:""}`;s.push(e.prefix?`${r}, one call each: they share ${e.prefix.exact?`${y(e.prefix.tokens)} tokens (the provider's count)`:`\u2248 ${y(e.prefix.tokens)} tokens (${e.prefix.estimates?`by run ${ke(e.prefix.estimates)}: `:""}estimated)`} to the end of \xAB${e.prefix.endsIn}\xBB${e.prefix.partsIn?`, and part in \xAB${e.prefix.partsIn}\xBB`:""} \u2014 ${e.prefix.breakpoint?"a breakpoint ends it":"no breakpoint ends it: one belongs there"}`:`${r}, one call each: they share no prefix the lens marks \u2014 they part in their first section`),e.firstDiff&&s.push(` first differing line (${e.firstDiff.ids[0]} / ${e.firstDiff.ids[1]}), in \xAB${e.firstDiff.region}\xBB: \xAB${e.firstDiff.line??""}\xBB / \xAB${e.firstDiff.otherLine??""}\xBB`);const a=e.identical;if(a){s.push(` identical in every run, wherever it sits: \u2248 ${y(a.tokens)} of ${y(a.of)} tokens (${K(a.share)}), ${a.sections} of ${a.ofSections} sections${a.afterPrefix?`; \u2248 ${y(a.afterPrefix)} of them after the first difference \u2014 a level a breakpoint reaches only once they are moved before it`:""} (estimate)`);for(const i of a.blocks.filter(l=>l.identical>0).slice(0,4))s.push(` \xAB${i.block}\xBB: ${K(i.share)} identical (\u2248 ${y(i.identical)} of ${y(i.tokens)} tokens)${i.line?`; its first differing line, line ${i.line.at}: \xAB${i.line.text}\xBB / \xAB${i.line.other}\xBB (${i.line.id})`:""}`)}return s}A(aiTogetherLevelLines,"aiTogetherLevelLines"),$(aiTogetherLevelLines,"aiTogetherLevelLines");
1
+ "use strict";var ve=Object.defineProperty;var S=(e,s)=>ve(e,"name",{value:s,configurable:!0});var be=Object.defineProperty,A=S((e,s)=>be(e,"name",{value:s,configurable:!0}),"A"),Me=Object.defineProperty,g=A((e,s)=>Me(e,"name",{value:s,configurable:!0}),"$");import{aiCacheDiff as ge,aiCacheSections as ye}from"./ai-cache.js";import{aiCacheMinTokens as Be}from"./ai-cache-facts.js";import{AI_CACHE_VERDICT_LABEL as Se}from"./ai-cache-verdict.js";import{estimateTokens as ne}from"./ai-context.js";export const FOLLOW_MS=1e3,MAX_LEVEL_RUNS=8;const $e=200,Ae=8,oe=4,qe=200,y=g(e=>Math.round(e).toLocaleString("en-US"),"fmt"),R=g(e=>`$${Number(e.toFixed(4))}`,"rate"),C=g(e=>`$${e<.01&&e>0?e.toFixed(4):e.toFixed(e<1?3:2)}`,"money"),E=g(e=>Math.round(e*1e6)/1e6,"usd"),V=g(e=>{const s=[...e].sort((a,r)=>a-r);return s.length?s[Math.floor((s.length-1)/2)]:0},"median"),re=g(e=>e<1e3?`${Math.round(e)} ms`:e<12e4?`${(e/1e3).toFixed(1)} s`:`${Math.round(e/1e3)} s`,"dur"),we=g((e,s=qe)=>e.length>s?`${e.slice(0,s-1)}\u2026`:e,"clip"),K=g(e=>e.at+(e.durationMs??0),"endOf"),ae=g((e,s)=>e.at-s.at||+!e.prewarm-+!s.prewarm||e.id.localeCompare(s.id),"byStart"),W=g(e=>e.tokens?.input!==void 0&&!e.failed,"counted"),Ue=["tenant","tenant_id","tenantId","business","business_id","businessId","org","org_id","orgId","organization","account","account_id","accountId","customer","customer_id","customerId"],De=["items","item_count","itemCount","n_items","batch_size","batchSize","rows","count"];export const tenantOf=g(e=>{for(const s of Ue)if(e.meta?.[s]?.trim())return e.meta[s].trim()},"tenantOf");const ie=g(e=>{for(const s of De){const a=e.meta?.[s];if(a!==void 0&&/^\d{1,6}$/.test(a.trim()))return Number(a.trim())}},"itemsOf");export function aiTogetherScopeOf(e){if(e.run.from!=="alone")return{by:"run",key:e.run.key};if(e.flowId)return{by:"flow",key:`flow:${e.flowId}`};if(e.requestId)return{by:"request",key:`request:${e.requestId}`}}S(aiTogetherScopeOf,"aiTogetherScopeOf"),A(aiTogetherScopeOf,"aiTogetherScopeOf"),g(aiTogetherScopeOf,"aiTogetherScopeOf");function Q(e){const s=new Map;for(const r of e){if(r.api==="embeddings")continue;const i=aiTogetherScopeOf(r);if(!i)continue;const l=`${r.agent.key}
2
+ ${i.key}`,f=s.get(l);f?f.rows.push(r):s.set(l,{scope:i,rows:[r]})}const a=[];for(const{scope:r,rows:i}of s.values()){i.sort(ae);const l=[];for(const c of i){const u=l[l.length-1];u&&(c.at<u.end||c.at===u.at)?(u.rows.push(c),u.end=Math.max(u.end,K(c))):l.push({rows:[c],at:c.at,end:K(c)})}let f=[];const o=g(()=>{if(f.some(c=>c.rows.length>=2)){const c=f.flatMap(u=>u.rows);a.push({key:`${c[0].agent.key}|${r.key}|${c[0].id}`,scope:r,rows:c,waves:f.map(u=>u.rows)})}f=[]},"flush");for(const c of l){const u=f[f.length-1];u&&c.at-u.end>FOLLOW_MS&&o(),f.push(c)}o()}return a.sort((r,i)=>i.rows[0].at-r.rows[0].at||r.key.localeCompare(i.key))}S(Q,"se"),A(Q,"re"),g(Q,"groupsOf");function ce(e){const s=new Map;for(const a of e){if(a.api==="embeddings"||!a.cache?.marks?.length)continue;const r=aiTogetherScopeOf(a)?.key??`call:${a.id}`,i=s.get(r);i?i.push(a):s.set(r,[a])}return[...s.values()].map(a=>a.sort(ae).find(r=>!r.prewarm&&W(r))??a.find(r=>!r.prewarm)??a[0]).sort(ae)}S(ce,"he"),A(ce,"ye"),g(ce,"representatives");export function aiTogetherPlan(e,s={}){const a=Y(Q(e),s),r=te(e,s);return{groups:a.flatMap(i=>i.rows.map(l=>l.id)),members:[...new Set(r.flatMap(i=>i.members.map(l=>l.id)))]}}S(aiTogetherPlan,"aiTogetherPlan"),A(aiTogetherPlan,"aiTogetherPlan"),g(aiTogetherPlan,"aiTogetherPlan");function Y(e,s){return s.focus?e.filter(a=>a.rows.some(r=>r.id===s.focus)):s.maxGroups!==void 0?e.slice(0,s.maxGroups):e}S(Y,"ne"),A(Y,"ce"),g(Y,"pickGroups");export function aiCalibratedMarks(e){const s=e.cache?.marks??[],a=e.tokens?.input;if(!s.length||a===void 0||e.failed||e.cache?.mode!=="explicit")return s;const r=e.tokens?.cached??0,i=e.tokens?.written??0,l=s.filter(p=>p.bp),f=g((p,m)=>m.reduce((x,w)=>!x||Math.abs(w.t-p)<Math.abs(x.t-p)?w:x,void 0),"nearest"),o=[[0,0]],c=new Set;let u=l;if(r>0){const p=f(r,l);p&&(o.push([p.t,r]),c.add(p),u=l.filter(m=>m.t>p.t))}if(i>0){const p=f(r+i,u);p&&(o.push([p.t,r+i]),c.add(p))}const n=s[s.length-1].t;n>o[o.length-1][0]&&o.push([n,Math.max(a,o[o.length-1][1])]);const d=g(p=>{for(let w=1;w<o.length;w++){const[M,B]=o[w-1],[U,L]=o[w];if(p<=U)return U===M?L:Math.round(B+(p-M)/(U-M)*(L-B))}const[m,x]=o[o.length-1];return Math.round(x+(p-m))},"at");return s.map(p=>({...p,t:d(p.t),...c.has(p)?{exact:!0}:{}}))}S(aiCalibratedMarks,"aiCalibratedMarks"),A(aiCalibratedMarks,"aiCalibratedMarks"),g(aiCalibratedMarks,"aiCalibratedMarks");function le(e,s){return e.model?s(e.model,e.tokens?.input??0):void 0}S(le,"fe"),A(le,"be"),g(le,"ratesFor");const de=g((e,s)=>e.writes[s]??e.input,"writeRate");function ue(e,s){const a=e.rows,r=a[0],i=s.texts,l=r.at,f=Math.max(...a.map(K)),o=g(t=>a.reduce((h,$)=>h+(t($)??0),0),"sum"),c={input:o(t=>t.tokens?.input),read:o(t=>t.tokens?.cached),written:o(t=>t.tokens?.written),plain:o(t=>t.tokens?.input!==void 0?Math.max(0,t.tokens.input-(t.tokens.cached??0)-(t.tokens.written??0)):0),output:o(t=>t.tokens?.output),reasoning:o(t=>t.tokens?.reasoning)},u=a.map(t=>{const h=t.cache?.verdict,$=ie(t);return{id:t.id,at:t.at,...t.durationMs!==void 0?{ms:t.durationMs}:{},...t.prewarm?{prewarm:!0}:{},...t.failed?{failed:!0}:{},...t.tokens?.input!==void 0?{input:t.tokens.input}:{},...t.tokens?.cached?{read:t.tokens.cached}:{},...t.tokens?.written?{written:t.tokens.written}:{},...t.tokens?.output!==void 0?{output:t.tokens.output}:{},...t.tokens?.reasoning?{reasoning:t.tokens.reasoning}:{},...h?{verdict:h.kind,...h.race!==void 0?{race:h.race}:{}}:{},...$!==void 0?{items:$}:{}}}),n=a.filter(t=>W(t)&&t.cache?.marks?.length),d=n.map(aiCalibratedMarks),p=new Map,m=new Map;d.forEach((t,h)=>{for(const $ of t){const v=p.get($.h);v?v[v.length-1]!==h&&v.push(h):p.set($.h,[h]);const j=m.get($.h)??{ts:[]};j.ts.push($.t),$.exact&&(j.exact=$.t),m.set($.h,j)}});const x=g(t=>{const h=m.get(t);return h.exact??V(h.ts)},"one"),w=d.map(t=>t.map(h=>({...h,t:x(h.h)}))),M=new Set;if(n.length){const t=n[0],h=t.tokens?.cached??0,$=Math.max(256,(t.tokens?.input??0)*.03);if(h>0)for(const v of d[0])v.t<=h+$&&M.add(v.h)}const B=new Map;w.forEach((t,h)=>{let $=-1;for(let q=0;q<t.length;q++)(p.get(t[q].h)?.length??0)>=2&&($=q);let v=0;const j=g(q=>`${p.get(t[q].h).join(",")}${M.has(t[q].h)?"w":""}`,"setOf");for(let q=0;q<=$;q++){const T=t[q];if(q<$&&j(q)===j(q+1))continue;let G=B.get(T.h);G||(G={h:T.h,holders:p.get(T.h),s:T.s,...t[q+1]?{next:t[q+1].s}:{},bp:!1,warm:M.has(T.h),seg:new Map,end:new Map,estimates:m.get(T.h).ts,exact:m.get(T.h).exact!==void 0},B.set(T.h,G)),G.bp||=!!T.bp,G.seg.set(h,Math.max(0,T.t-v)),G.end.set(h,T.t),v=T.t}});const U=[...B.values()].sort((t,h)=>h.holders.length-t.holders.length||V([...t.end.values()])-V([...h.end.values()])).map(t=>{const h=Math.min(...t.estimates),$=Math.max(...t.estimates);return{calls:t.holders.length,ids:t.holders.map(v=>n[v].id),tokens:V([...t.seg.values()]),endsAt:V([...t.end.values()]),...t.exact?{exact:!0}:h!==$?{estimates:[h,$]}:{},endsIn:t.s,...t.next?{partsIn:t.next}:{},breakpoint:t.bp,...t.warm?{warm:!0}:{}}}),L=he(a,n,B,s.ratesOf,e.waves),P={};let N=0;const D=[];for(const t of a){const h=t.cache?.verdict;if(h){P[h.kind]=(P[h.kind]??0)+1,N+=h.lostUsd??0;for(const $ of h.costs)$.kind==="duplicate-write"&&D.push({id:t.id,race:!!h.race,...h.against?{against:h.against.id,inFlight:h.against.inFlight}:{},tokens:$.tokens,...$.usd!==void 0?{usd:$.usd}:{},...$.arithmetic?{arithmetic:$.arithmetic}:{},estimate:$.estimate})}}const H=a.find(t=>t.prewarm)?.id,z=g(t=>{const h=t.tokens?.output,$=ie(t);return{id:t.id,ms:t.durationMs,...h!==void 0?{output:h}:{},...t.tokens?.reasoning?{reasoning:t.tokens.reasoning}:{},...h!==void 0&&t.durationMs>0?{perSecond:Math.round(h/(t.durationMs/1e3)*10)/10}:{},...$!==void 0?{items:$}:{}}},"timed"),J=a.filter(t=>!t.prewarm&&!t.failed&&t.durationMs!==void 0),X=J.reduce((t,h)=>!t||h.durationMs>t.durationMs?h:t,void 0),k=e.waves.map(t=>t.filter(h=>J.includes(h))).reduce((t,h)=>h.length>t.length?h:t,[]),b=k.length>=2?k.reduce((t,h)=>h.durationMs<t.durationMs?h:t):void 0,I=k.length>=2?k.reduce((t,h)=>h.durationMs>t.durationMs?h:t):void 0,O=J.filter(t=>t.tokens?.output!==void 0&&t.durationMs>0).map(t=>t.tokens.output/(t.durationMs/1e3)),_=r.thread?.key,F={key:e.key,agent:{key:r.agent.key,name:r.agent.name},scope:e.scope,..._?{thread:_}:{},calls:u,waves:e.waves.map(t=>({ids:t.map(h=>h.id),at:t[0].at,ms:Math.max(...t.map(K))-t[0].at})),at:l,end:f,ms:f-l,tokens:c,counted:a.filter(W).length,...L?{cost:L}:{},shared:U,cache:{verdicts:P,lostUsd:E(N),races:D.filter(t=>t.race).length,duplicates:D,...H?{prewarm:H}:{}},time:{...X?{slowest:z(X)}:{},...b&&I?{fastest:z(b),...b.durationMs>0?{spread:Math.round(I.durationMs/b.durationMs*10)/10}:{}}:{},...O.length?{perSecond:[Math.round(Math.min(...O)*10)/10,Math.round(Math.max(...O)*10)/10]}:{},itemsLabelled:a.some(t=>ie(t)!==void 0)}};if(i){const t=aiAnswerFields(a.filter(v=>!v.prewarm).map(v=>({json:i.get(v.id)?.answer,visible:Ie(v)})));t&&(F.answer=t);const h=aiUnquotedSections(a.filter(v=>!v.prewarm).map(v=>({request:i.get(v.id)?.request,answer:i.get(v.id)?.answerText})));h&&(F.unquoted=h);const $=ee(a.filter(v=>!v.prewarm),i);$&&(F.firstDiff=$)}return F}S(ue,"pe"),A(ue,"ve"),g(ue,"group");const Ie=g(e=>e.tokens?.output!==void 0?Math.max(0,e.tokens.output-(e.tokens.reasoning??0)):void 0,"visibleOf");function he(e,s,a,r,i){const l=[],f=[];for(const k of e){if(!W(k)){l.push(k.failed?"failed":"no count");continue}const b=le(k,r);b?f.push({r:k,rates:b}):l.push("no price")}if(!f.length)return;let o=0,c=0,u=0;const n=new Map;for(const{r:k,rates:b}of f){const I=k.tokens.cached??0,O=k.tokens.written??0,_=Math.max(0,k.tokens.input-I-O),F=b.cacheRead??b.input;o+=I,c+=_;let t=0;const h=Object.entries(k.cache?.writes??{}).filter($=>typeof $[1]=="number"&&$[1]>0);if(h.length)for(const[$,v]of h){const j=de(b,$);n.set(j,(n.get(j)??0)+v),t+=v*j}else if(O){const $=de(b,k.cache?.ttl??"30m");n.set($,(n.get($)??0)+O),t+=O*$}u+=(I*F+t+_*b.input)/1e6}const d=f[0].rates,p=f.every(k=>k.rates===d||k.rates.input===d.input&&k.rates.cacheRead===d.cacheRead),m=p?`${y(o)} read \xD7 ${R(d.cacheRead??d.input)} + ${[...n].map(([k,b])=>`${y(b)} written \xD7 ${R(k)}`).join(" + ")||"0 written"} + ${y(c)} plain \xD7 ${R(d.input)}, per million = ${C(u)}`:`the provider's counts at each call's model's rates = ${C(u)}`,x=[];for(const{r:k,rates:b}of f){if(x.some(O=>O.model===k.model))continue;const I=k.cache?.ttl??"30m";x.push({model:k.model,input:b.input,...b.cacheRead!==void 0?{cacheRead:b.cacheRead}:{},...b.writes[I]!==void 0?{write:b.writes[I]}:{},ttl:I,...b.source?{source:b.source}:{},...b.readAt?{readAt:b.readAt}:{},...b.stale?{stale:!0}:{}})}const w=l.length?{calls:l.length,why:[...new Set(l)].join(", ")}:void 0,M={actualUsd:E(u),actual:m,estimate:!0,rates:x,...w?{left:w}:{}},B=new Map(s.map((k,b)=>[k.id,b]));if(!f.every(({r:k})=>B.has(k.id))){const k=f.filter(({r:b})=>!B.has(b.id)).length;return{...M,left:{calls:(w?.calls??0)+k,why:[w?.why,"no prefix marks (kept by a lens before 1.26.11)"].filter(Boolean).join(", ")}}}let U=0,L=0,P=0,N=0,D=0,H=0;const z=new Map;for(const{r:k,rates:b}of f){const I=B.get(k.id),O=b.input,_=b.cacheRead??O,F=Be(k.provider,k.model);let t=0;for(const $ of a.values()){const v=$.seg.get(I);if(v===void 0)continue;const j=$.end.get(I);if(t=Math.max(t,j),j<F)N+=v,D+=v*O/1e6;else if($.warm)P+=v,D+=v*_/1e6;else if($.holders[0]===I){const q=de(b,k.cache?.ttl??"30m");U+=v,z.set(q,(z.get(q)??0)+v),D+=v*q/1e6,H+=v*_/1e6}else L+=v,D+=v*_/1e6}const h=Math.max(0,k.tokens.input-t);N+=h,D+=h*O/1e6}const J=!e.some(k=>k.prewarm)&&i.some(k=>k.filter(b=>!b.prewarm).length>=2)&&U>0,X=p?`${P?`${y(P)} already cached, read \xD7 ${R(d.cacheRead??d.input)} + `:""}${[...z].map(([k,b])=>`${y(b)} written once \xD7 ${R(k)}`).join(" + ")||"0 written"} + ${y(L)} read \xD7 ${R(d.cacheRead??d.input)} + ${y(N)} each call's own, plain \xD7 ${R(d.input)}, per million = ${C(D)}`:`one write per shared prefix at each model's rates = ${C(D)}`;return{...M,idealUsd:E(D),ideal:X,gapUsd:E(E(u)-E(D)),...J?{prewarmUsd:E(D+H)}:{}}}S(he,"me"),A(he,"qe"),g(he,"costOf");const fe=g(e=>ne(JSON.stringify(e)??""),"jsonTokens");export function aiAnswerFields(e){const s=new Map,a=new Map;let r=0,i=0;for(const f of e){const o=f.json;if(!o||typeof o!="object")continue;i++;const c=Math.max(1,fe(o)),u=f.visible!==void 0&&f.visible>0?f.visible/c:1;r+=c*u;const n=Array.isArray(o)?{"[]":o}:o;for(const[p,m]of Object.entries(n))s.set(p,(s.get(p)??0)+(fe(m)+ne(p)+1)*u);const d=g((p,m)=>{if(Array.isArray(p)){const x=p.filter(w=>w&&typeof w=="object"&&!Array.isArray(w));if(x.length>=2){const w=a.get(`${m}[]`)??{rows:0,tokens:0};w.rows+=x.length,w.tokens+=x.reduce((M,B)=>M+fe(B),0)*u,a.set(`${m}[]`,w)}for(const w of p)d(w,`${m}[]`)}else if(p&&typeof p=="object")for(const[x,w]of Object.entries(p))d(w,m?`${m}.${x}`:x)},"walk");d(o,"")}if(!i||r<=0)return;const l=[...a].sort((f,o)=>o[1].tokens-f[1].tokens)[0];return{answers:i,tokens:Math.round(r),fields:[...s].sort((f,o)=>o[1]-f[1]).map(([f,o])=>({field:f,tokens:Math.round(o),share:Math.round(o/r*1e3)/1e3})),...l?{rows:{path:l[0],rows:l[1].rows,tokens:Math.round(l[1].tokens),perRow:Math.round(l[1].tokens/l[1].rows),share:Math.round(l[1].tokens/r*1e3)/1e3}}:{},estimate:!0}}S(aiAnswerFields,"aiAnswerFields"),A(aiAnswerFields,"aiAnswerFields"),g(aiAnswerFields,"aiAnswerFields");export function aiRequestSections(e){const s=[];let a=0;return e.blocks.forEach((r,i)=>{const l=ye(r.text),f=g((o,c,u)=>{const n=r.text.slice(o,c);n.trim()&&s.push({k:i,block:r.label,title:u,text:n,at:a+o,tokens:ne(n)*(r.weight??1)})},"push");l.length?(l[0].at>0&&f(0,l[0].at,`${r.label} \u203A (opening)`),l.forEach((o,c)=>f(o.at,l[c+1]?.at??r.text.length,`${r.label} \u203A ${o.title}`))):f(0,r.text.length,r.label),a+=r.text.length}),s}S(aiRequestSections,"aiRequestSections"),A(aiRequestSections,"aiRequestSections"),g(aiRequestSections,"aiRequestSections");const Oe=/^(?:instructions|tools|answer schema)/,ke=g(e=>e.toLowerCase().match(/[\p{L}\p{N}]+/gu)??[],"words");function Z(e){const s=new Set;for(let a=0;a+oe<=e.length;a++)s.add(e.slice(a,a+oe).join(" "));return s}S(Z,"re"),A(Z,"ue"),g(Z,"shinglesOf");export function aiUnquotedSections(e){const s=new Map;let a=0;for(const i of e){if(!i.request||!i.answer)continue;a++;const l=ke(i.answer),f=Z(l),o=new Set(l);for(const c of aiRequestSections(i.request)){if(Oe.test(c.block))continue;const u=ke(c.text),n=[...Z(u)].some(p=>f.has(p))||u.some(p=>p.length>=6&&/\d/.test(p)&&/\p{L}/u.test(p)&&o.has(p)),d=s.get(c.title)??{tokens:0,calls:0,quoted:0};d.tokens=Math.max(d.tokens,Math.round(c.tokens)),d.calls++,n&&d.quoted++,s.set(c.title,d)}}if(!a)return;const r=[...s].filter(([,i])=>!i.quoted&&i.tokens>=$e).sort((i,l)=>l[1].tokens-i[1].tokens).slice(0,Ae).map(([i,l])=>({section:i,tokens:l.tokens,calls:l.calls}));return{measure:`a run of ${oe} words, or an id-like word, of the section found in the answer`,untested:!0,answers:a,candidates:r}}S(aiUnquotedSections,"aiUnquotedSections"),A(aiUnquotedSections,"aiUnquotedSections"),g(aiUnquotedSections,"aiUnquotedSections");function ee(e,s){const a=e.filter(c=>s.get(c.id)?.request);if(a.length<2)return;const r=a[0],i=s.get(r.id).request;let l;for(const c of a.slice(1)){const u=ge(i,s.get(c.id).request,r.tokens?.input);u.same||(!l||u.chars<l.chars)&&(l={region:u.setting?`settings (${u.setting})`:u.region,...u.line!==void 0?{line:u.line}:{},...u.otherLine!==void 0?{otherLine:u.otherLine}:{},ids:[r.id,c.id],chars:u.chars})}if(!l)return;const{chars:f,...o}=l;return o}S(ee,"ie"),A(ee,"le"),g(ee,"firstDiffOf");function pe(e,s){if(e===s)return;let a=0;const r=Math.min(e.length,s.length);for(;a<r&&e.charCodeAt(a)===s.charCodeAt(a);)a++;const i=e.lastIndexOf(`
3
+ `,a-1)+1,l=g(f=>{const o=f.indexOf(`
4
+ `,i);return we(f.slice(i,o<0?f.length:o).trim())},"lineOf");return{at:e.slice(0,i).split(`
5
+ `).length,text:l(e),other:l(s)}}S(pe,"ge"),A(pe,"Oe"),g(pe,"lineDiff");export function aiSectionIdentity(e){if(e.length<2)return;const s=e[0],a=e.map(m=>aiRequestSections(m.request)),r=a.slice(1).map(m=>new Set(m.map(x=>x.text))),i=a[0].reduce((m,x)=>m+x.tokens,0),l=s.input!==void 0&&i>0?s.input/i:1;let f=1/0;for(const m of e.slice(1))f=Math.min(f,ge(s.request,m.request).chars);let o=0,c=0,u=0;const n=new Map;for(const m of a[0]){const x=r.every(M=>M.has(m.text)),w=n.get(m.k)??{tokens:0,identical:0};w.tokens+=m.tokens*l,x&&(o+=m.tokens*l,u++,w.identical+=m.tokens*l,m.at+m.text.length<=f&&(c+=m.tokens*l)),n.set(m.k,w)}const d=i*l,p=g((m,x)=>x>0?Math.round(m/x*1e3)/1e3:0,"ratio");return{tokens:Math.round(o),of:Math.round(d),share:p(o,d),afterPrefix:Math.round(Math.max(0,o-c)),sections:u,ofSections:a[0].length,blocks:[...n].map(([m,x])=>{const w=s.request.blocks[m];let M;for(const B of e.slice(1)){const U=B.request.blocks[m],L=U&&U.label===w.label?pe(w.text,U.text):void 0;L&&(!M||L.at<M.at)&&(M={...L,id:B.id})}return{block:w.label,tokens:Math.round(x.tokens),identical:Math.round(x.identical),share:p(x.identical,x.tokens),...M?{line:M}:{}}}).filter(m=>m.tokens>0).sort((m,x)=>x.identical-m.identical||x.tokens-m.tokens)}}S(aiSectionIdentity,"aiSectionIdentity"),A(aiSectionIdentity,"aiSectionIdentity"),g(aiSectionIdentity,"aiSectionIdentity");function te(e,s){const a=s.focus?e.find(n=>n.id===s.focus):void 0,r=new Set(e.map(n=>n.agent.key));if(s.levels===!1||!a&&r.size!==1)return[];const i=a?.agent.key??[...r][0],l=ce(e.filter(n=>n.agent.key===i)),f=g(n=>n.slice(-MAX_LEVEL_RUNS),"newest"),o=[],c=g((n,d)=>{const p=new Map;for(const M of l){const B=d(M);if(!B)continue;const U=p.get(B);U?U.push(M):p.set(B,[M])}const m=[...p].filter(([,M])=>M.length>=2);if(!m.length)return;const x=a?d(a):void 0,w=m.find(([M])=>M===x)??[...m].sort((M,B)=>B[1].length-M[1].length||B[1][B[1].length-1].at-M[1][M[1].length-1].at)[0];o.push({level:n,key:w[0],members:f(w[1]),...m.length>1?{more:m.length-1}:{}})},"keyed");c("thread",n=>n.thread?.key),c("tenant",tenantOf),l.length>=2&&o.push({level:"all",members:f(l)});const u=g((n,d)=>n.members.length===d.members.length&&n.members.every((p,m)=>p.id===d.members[m].id),"same");return o.filter((n,d)=>!o.slice(0,d).some(p=>u(p,n)))}S(te,"ce"),A(te,"fe"),g(te,"levelSets");function me(e,s){const a=e.members,r=a.map(aiCalibratedMarks),i=r.slice(1).map(c=>new Set(c.map(u=>u.h)));let l=-1;r[0].forEach((c,u)=>{i.every(n=>n.has(c.h))&&(l=u)});let f;if(l>=0){const c=r[0][l],u=r.map(w=>w.find(M=>M.h===c.h)??c),n=u.filter((w,M)=>W(a[M])),d=(n.length?n:u).map(w=>w.t),p=u.find(w=>w.exact)?.t,m=Math.min(...d),x=Math.max(...d);f={tokens:p??V(d),...p!==void 0?{exact:!0}:m!==x?{estimates:[m,x]}:{},endsIn:c.s,...r[0][l+1]?{partsIn:r[0][l+1].s}:{},breakpoint:u.some(w=>!!w.bp)}}const o={level:e.level,...e.key?{key:e.key}:{},runs:a.length,members:a.map(c=>c.id),...f?{prefix:f}:{},...e.more?{more:e.more}:{}};if(s){const c=a.filter(d=>s.get(d.id)?.request).map(d=>({id:d.id,request:s.get(d.id).request,input:d.tokens?.input})),u=aiSectionIdentity(c);u&&(o.identical=u);const n=ee(a,s);n&&(o.firstDiff=n)}return o}S(me,"we"),A(me,"Ie"),g(me,"level");export function aiTogether(e,s){const a=Q(e),r=Y(a,s).map(o=>ue(o,s)),i=te(e,s).map(o=>me(o,s.texts)),l=r.filter(o=>o.cost),f=l.filter(o=>o.cost.idealUsd!==void 0);return{groups:r,levels:i,totals:{groups:r.length,calls:r.reduce((o,c)=>o+c.calls.length,0),priced:l.length,actualUsd:E(f.reduce((o,c)=>o+c.cost.actualUsd,0)),idealUsd:E(f.reduce((o,c)=>o+c.cost.idealUsd,0)),gapUsd:E(f.reduce((o,c)=>o+c.cost.gapUsd,0)),races:r.reduce((o,c)=>o+c.cache.races,0),duplicates:r.reduce((o,c)=>o+c.cache.duplicates.length,0)}}}S(aiTogether,"aiTogether"),A(aiTogether,"aiTogether"),g(aiTogether,"aiTogether");const se=g(e=>`${Math.round(e*100)}%`,"pct"),xe=g(e=>e[0]===e[1]?y(e[0]):`${y(e[0])}\u2013${y(e[1])}`,"range");export function aiTogetherLines(e){const s=[],a=e.waves.map(n=>n.ids.length===1?e.calls.find(d=>d.id===n.ids[0])?.prewarm?"a prewarm":"1":`${n.ids.length} sent together`).join(", then "),r=e.tokens;s.push(`${e.calls.length} calls of ${e.scope.by} ${e.scope.key.replace(/^(?:run|flow|request):/,"")} in ${e.waves.length} wave${e.waves.length===1?"":"s"} (${a}), ${re(e.ms)} from the first sent to the last answer`),s.push(`input ${y(r.input)} tokens over the ${e.counted} counted: ${y(r.read)} read from the cache, ${y(r.written)} written to it, ${y(r.plain)} plain; output ${y(r.output)}${r.reasoning?` (${y(r.reasoning)} reasoning)`:""}`);const i=e.cost;if(i){s.push(`input as billed \u2248 ${C(i.actualUsd)}: ${i.actual}`),i.idealUsd!==void 0&&(s.push(`ideal input \u2248 ${C(i.idealUsd)} (estimate \u2014 one write per shared prefix, the rest reads, each call's own tail plain): ${i.ideal}; gap \u2248 ${C(i.gapUsd??0)}`),i.prewarmUsd!==void 0&&s.push(`calls sent together reach that only once one write has finished \u2014 with a prewarm (P\xB7w + N\xB7P\xB7r) \u2248 ${C(i.prewarmUsd)}`)),i.left&&s.push(`left out of these sums: ${i.left.calls} call${i.left.calls===1?"":"s"} (${i.left.why})`);const n=i.rates.map(d=>`${d.model} input ${R(d.input)}, read ${d.cacheRead!==void 0?R(d.cacheRead):"as input"}, write ${d.ttl} ${d.write!==void 0?R(d.write):"as input"} per M \u2014 ${d.source??"no source"}${d.readAt?`, read ${d.readAt}`:""}${d.stale?", STALE":""}`);n.length&&s.push(`rates: ${n.join("; ")}`)}const l=e.calls.filter(n=>n.input!==void 0&&!n.failed).length;e.shared.forEach((n,d)=>{const p=n.estimates?` (by call ${xe(n.estimates)}: estimated)`:n.exact?" (the provider's count)":" (estimated)",m=d?` \u2014 ${n.exact?"":"\u2248 "}${y(n.endsAt)} from the start${p}`:p;s.push(`${n.calls===l?"all":n.calls} of its calls share ${d?"the next ":""}${n.exact?"":"\u2248 "}${y(n.tokens)} tokens, to the end of \xAB${n.endsIn}\xBB${m}${n.warm?"; already in the cache before the group":""}${n.partsIn?`; they part in \xAB${n.partsIn}\xBB`:""} \u2014 ${n.breakpoint?"a breakpoint ends it":"no breakpoint ends it: one belongs there"}`)}),e.firstDiff&&s.push(`where they part, to the line (${e.firstDiff.ids[0]} / ${e.firstDiff.ids[1]}), in \xAB${e.firstDiff.region}\xBB: \xAB${e.firstDiff.line??""}\xBB / \xAB${e.firstDiff.otherLine??""}\xBB`);const f=Object.entries(e.cache.verdicts);f.length&&s.push(`cache verdicts: ${f.sort((n,d)=>d[1]-n[1]).map(([n,d])=>`${Se[n]} \xD7${d}`).join(", ")}${e.cache.lostUsd?` \u2014 \u2248 ${C(e.cache.lostUsd)} lost`:""}${e.cache.prewarm?`; ${e.cache.prewarm} is a prewarm`:""}`);for(const n of e.cache.duplicates)s.push(` ${n.id} wrote the shared prefix again${n.race?` \u2014 a race: ${n.against??"the writer"} was still in flight`:n.against?` after ${n.against} had written it${n.inFlight===!1?" and ended \u2014 not a race":""}`:""}: ${n.arithmetic??y(n.tokens)}${n.usd!==void 0?` = ${C(n.usd)}`:""}${n.estimate?" (estimate)":""}`);const o=e.time;if(o.slowest){const n=o.slowest;s.push(`the slowest call ${n.id}: ${re(n.ms)}${n.output!==void 0?`, ${y(n.output)} output tokens${n.reasoning?` (${y(n.reasoning)} reasoning)`:""}`:""}${n.perSecond!==void 0?` at ${n.perSecond} tokens a second`:""}${n.items!==void 0?`, ${n.items} items`:""} \u2014 the group waits for it`)}o.fastest&&s.push(`its fan-out's fastest ${o.fastest.id}: ${re(o.fastest.ms)}${o.fastest.output!==void 0?`, ${y(o.fastest.output)} output tokens`:""}${o.fastest.items!==void 0?`, ${o.fastest.items} items`:""}${o.spread!==void 0?` \u2014 spread ${o.spread}\xD7`:""}${o.perSecond?`; output ${o.perSecond[0]}\u2013${o.perSecond[1]} tokens a second across its calls`:""}`),s.push(o.itemsLabelled?`items per call: ${e.calls.filter(n=>n.items!==void 0).map(n=>`${n.id} ${n.items}`).join(", ")}`:"items per call: the app labels none (metadata.items)");const c=e.answer;c&&(s.push(`the answer by field over ${c.answers} answer${c.answers===1?"":"s"} read (\u2248 ${y(c.tokens)} visible tokens, estimate): ${c.fields.slice(0,8).map(n=>`${n.field} ${se(n.share)} (${y(n.tokens)})`).join(", ")}`),c.rows&&s.push(` the largest repeated row kind ${c.rows.path}: ${y(c.rows.rows)} rows \u2248 ${y(c.rows.perRow)} tokens a row, ${se(c.rows.share)} of the answers`));const u=e.unquoted;return u&&s.push(u.candidates.length?`sections the answers never quote \u2014 candidates only (${u.measure}; untested as a measure), over ${u.answers} answers: ${u.candidates.map(n=>`\xAB${we(n.section,70)}\xBB \u2248 ${y(n.tokens)} tokens in ${n.calls} call${n.calls===1?"":"s"}`).join("; ")}`:`every context section of ${$e}+ tokens is quoted by some answer (${u.measure}; untested as a measure)`),s}S(aiTogetherLines,"aiTogetherLines"),A(aiTogetherLines,"aiTogetherLines"),g(aiTogetherLines,"aiTogetherLines");export function aiTogetherLevelLines(e){const s=[],a=e.level==="all"?`all its runs (the newest ${e.runs})`:`the ${e.runs} newest runs of ${e.level} ${e.key}${e.more?` (${e.more} other ${e.level}${e.more===1?"":"s"} of two runs or more)`:""}`;s.push(e.prefix?`${a}, one call each: they share ${e.prefix.exact?`${y(e.prefix.tokens)} tokens (the provider's count)`:`\u2248 ${y(e.prefix.tokens)} tokens (${e.prefix.estimates?`by run ${xe(e.prefix.estimates)}: `:""}estimated)`} to the end of \xAB${e.prefix.endsIn}\xBB${e.prefix.partsIn?`, and part in \xAB${e.prefix.partsIn}\xBB`:""} \u2014 ${e.prefix.breakpoint?"a breakpoint ends it":"no breakpoint ends it: one belongs there"}`:`${a}, one call each: they share no prefix the lens marks \u2014 they part in their first section`),e.firstDiff&&s.push(` first differing line (${e.firstDiff.ids[0]} / ${e.firstDiff.ids[1]}), in \xAB${e.firstDiff.region}\xBB: \xAB${e.firstDiff.line??""}\xBB / \xAB${e.firstDiff.otherLine??""}\xBB`);const r=e.identical;if(r){s.push(` identical in every run, wherever it sits: \u2248 ${y(r.tokens)} of ${y(r.of)} tokens (${se(r.share)}), ${r.sections} of ${r.ofSections} sections${r.afterPrefix?`; \u2248 ${y(r.afterPrefix)} of them after the first difference \u2014 a level a breakpoint reaches only once they are moved before it`:""} (estimate)`);for(const i of r.blocks.filter(l=>l.identical>0).slice(0,4))s.push(` \xAB${i.block}\xBB: ${se(i.share)} identical (\u2248 ${y(i.identical)} of ${y(i.tokens)} tokens)${i.line?`; its first differing line, line ${i.line.at}: \xAB${i.line.text}\xBB / \xAB${i.line.other}\xBB (${i.line.id})`:""}`)}return s}S(aiTogetherLevelLines,"aiTogetherLevelLines"),A(aiTogetherLevelLines,"aiTogetherLevelLines"),g(aiTogetherLevelLines,"aiTogetherLevelLines");
@@ -1 +1 @@
1
- "use strict";var T=Object.defineProperty;var i=(e,t)=>T(e,"name",{value:t,configurable:!0});var h=Object.defineProperty,l=i((e,t)=>h(e,"name",{value:t,configurable:!0}),"_");export const DEFAULT_RAW_BYTE_LIMIT=32768,DEFAULT_MAX_STRING_BYTES=4096,DEFAULT_MAX_ARRAY_ITEMS=64,DEFAULT_MAX_DEPTH=12,CHEAP_ENTRY_BYTES=512,NOMINAL_DEEP_BYTES=32,DEEP_REPORT_DEPTH=64,SKELETON_STRING_BYTES=256,MAX_RECORDED_PATHS=20,TRUNCATION_MARKER_KEY="__lensmcpTruncation",TRUNCATED_VALUE_KEY="__lensmcpTruncated";export function estimateJsonBytes(e,t=Number.POSITIVE_INFINITY,r=12){return y(e,t,r,32)}i(estimateJsonBytes,"estimateJsonBytes"),l(estimateJsonBytes,"estimateJsonBytes");export function exceedsJsonByteBudget(e,t,r=12){return y(e,t,r,Number.POSITIVE_INFINITY)>t}i(exceedsJsonByteBudget,"exceedsJsonByteBudget"),l(exceedsJsonByteBudget,"exceedsJsonByteBudget");function y(e,t,r,a){switch(typeof e){case"undefined":case"function":case"symbol":return 0;case"boolean":return 5;case"number":return Number.isFinite(e)?8:4;case"bigint":return 20;case"string":return e.length+2;default:break}if(e===null)return 4;if(r<=0)return a;if(e instanceof Date)return 26;if(Array.isArray(e)){let n=2;for(let s=0;s<e.length;s++)if(n+=y(e[s],t-n,r-1,a)+1,n>t)return n;return n}let u=2;const o=e;for(const n in o){if(!Object.prototype.hasOwnProperty.call(o,n))continue;const s=y(o[n],t-u,r-1,a);if(s!==0&&(u+=n.length+4+s,u>t))return u}return u}i(y,"T"),l(y,"walk");function g(e,t){e.truncatedAnything=!0,e.paths.length<20&&e.paths.push(t||"<root>")}i(g,"A"),l(g,"record");function f(e,t,r){return g(e,r),{[TRUNCATED_VALUE_KEY]:!0,originalBytes:estimateJsonBytes(t,Number.POSITIVE_INFINITY,64)}}i(f,"I"),l(f,"stub");function p(e){if(e===null)return!0;const t=typeof e;return t==="number"||t==="boolean"||t==="string"||t==="bigint"}i(p,"y"),l(p,"isScalar");export function clampValue(e,t,r,a){if(typeof e=="string"){const u=t.budget<=0?256:t.maxStringBytes;if(e.length+2<=u)return t.budget-=e.length+2,e;const o=Math.max(0,u-64);return g(t,a),t.budget-=o,`${e.slice(0,o)}\u2026[lensmcp truncated: ${e.length-o} more chars]`}return e===null||typeof e!="object"?(t.budget-=y(e,Number.POSITIVE_INFINITY,1,32),e):r<=0?f(t,e,a):e instanceof Date?(t.budget-=26,e):Array.isArray(e)?m(e,t,r,a):b(e,t,r,a)}i(clampValue,"clampValue"),l(clampValue,"clampValue");function m(e,t,r,a){const u=[],o=Math.min(e.length,t.maxArrayItems);for(let n=0;n<o&&!(t.budget<=0);n++)u.push(clampValue(e[n],t,r-1,`${a}[${n}]`));return u.length<e.length&&g(t,`${a}[] (+${e.length-u.length} items dropped)`),u}i(m,"f"),l(m,"clampArray");function b(e,t,r,a){const u={};let o;const n=t.budget<=0;for(const s in e){if(!Object.prototype.hasOwnProperty.call(e,s))continue;const c=e[s],I=y(c,512,r-1,Number.POSITIVE_INFINITY);if(I<=512&&(!n||p(c))){u[s]=c,t.budget-=s.length+4+I;continue}(o??=[]).push({key:s,bytes:I})}if(!o)return u;o.sort((s,c)=>s.bytes===c.bytes?0:s.bytes<c.bytes?-1:1);for(const{key:s}of o){const c=a?`${a}.${s}`:s;u[s]=clampValue(e[s],t,r-1,c)}return u}i(b,"m"),l(b,"clampObject");export function boundedClone(e,t={}){const r=t.rawByteLimit??32768,a=t.maxDepth??12;if(r<=0)return{value:void 0,truncated:!1,originalBytes:0,keptBytes:0,paths:[]};if(e==null)return{value:e,truncated:!1,originalBytes:0,keptBytes:0,paths:[]};if(!exceedsJsonByteBudget(e,r,a)){const c=estimateJsonBytes(e,r,a),I={budget:r,maxStringBytes:t.maxStringBytes??4096,maxArrayItems:t.maxArrayItems??64,paths:[],truncatedAnything:!1};return{value:clampValue(e,I,a,""),truncated:!1,originalBytes:c,keptBytes:c,paths:[]}}const u=estimateJsonBytes(e,Number.POSITIVE_INFINITY,64),o={budget:r,maxStringBytes:t.maxStringBytes??4096,maxArrayItems:t.maxArrayItems??64,paths:[],truncatedAnything:!1},n=clampValue(e,o,a,""),s=estimateJsonBytes(n,Number.POSITIVE_INFINITY,a);if(o.truncatedAnything&&n!==null&&typeof n=="object"&&!Array.isArray(n)){const c={truncated:!0,originalBytes:u,keptBytes:s,paths:o.paths};n[TRUNCATION_MARKER_KEY]=c}return{value:n,truncated:o.truncatedAnything,originalBytes:u,keptBytes:s,paths:o.paths}}i(boundedClone,"boundedClone"),l(boundedClone,"boundedClone");
1
+ "use strict";var T=Object.defineProperty;var c=(t,e)=>T(t,"name",{value:e,configurable:!0});var h=Object.defineProperty,l=c((t,e)=>h(t,"name",{value:e,configurable:!0}),"i"),_=Object.defineProperty,y=l((t,e)=>_(t,"name",{value:e,configurable:!0}),"_");export const DEFAULT_RAW_BYTE_LIMIT=32768,DEFAULT_MAX_STRING_BYTES=4096,DEFAULT_MAX_ARRAY_ITEMS=64,DEFAULT_MAX_DEPTH=12,CHEAP_ENTRY_BYTES=512,NOMINAL_DEEP_BYTES=32,DEEP_REPORT_DEPTH=64,SKELETON_STRING_BYTES=256,MAX_RECORDED_PATHS=20,TRUNCATION_MARKER_KEY="__lensmcpTruncation",TRUNCATED_VALUE_KEY="__lensmcpTruncated";export function estimateJsonBytes(t,e=Number.POSITIVE_INFINITY,n=12){return g(t,e,n,32)}c(estimateJsonBytes,"estimateJsonBytes"),l(estimateJsonBytes,"estimateJsonBytes"),y(estimateJsonBytes,"estimateJsonBytes");export function exceedsJsonByteBudget(t,e,n=12){return g(t,e,n,Number.POSITIVE_INFINITY)>e}c(exceedsJsonByteBudget,"exceedsJsonByteBudget"),l(exceedsJsonByteBudget,"exceedsJsonByteBudget"),y(exceedsJsonByteBudget,"exceedsJsonByteBudget");function g(t,e,n,a){switch(typeof t){case"undefined":case"function":case"symbol":return 0;case"boolean":return 5;case"number":return Number.isFinite(t)?8:4;case"bigint":return 20;case"string":return t.length+2;default:break}if(t===null)return 4;if(n<=0)return a;if(t instanceof Date)return 26;if(Array.isArray(t)){let r=2;for(let u=0;u<t.length;u++)if(r+=g(t[u],e-r,n-1,a)+1,r>e)return r;return r}let s=2;const o=t;for(const r in o){if(!Object.prototype.hasOwnProperty.call(o,r))continue;const u=g(o[r],e-s,n-1,a);if(u!==0&&(s+=r.length+4+u,s>e))return s}return s}c(g,"y"),l(g,"T"),y(g,"walk");function f(t,e){t.truncatedAnything=!0,t.paths.length<20&&t.paths.push(e||"<root>")}c(f,"g"),l(f,"A"),y(f,"record");function p(t,e,n){return f(t,n),{[TRUNCATED_VALUE_KEY]:!0,originalBytes:estimateJsonBytes(e,Number.POSITIVE_INFINITY,64)}}c(p,"f"),l(p,"I"),y(p,"stub");function m(t){if(t===null)return!0;const e=typeof t;return e==="number"||e==="boolean"||e==="string"||e==="bigint"}c(m,"p"),l(m,"y"),y(m,"isScalar");export function clampValue(t,e,n,a){if(typeof t=="string"){const s=e.budget<=0?256:e.maxStringBytes;if(t.length+2<=s)return e.budget-=t.length+2,t;const o=Math.max(0,s-64);return f(e,a),e.budget-=o,`${t.slice(0,o)}\u2026[lensmcp truncated: ${t.length-o} more chars]`}return t===null||typeof t!="object"?(e.budget-=g(t,Number.POSITIVE_INFINITY,1,32),t):n<=0?p(e,t,a):t instanceof Date?(e.budget-=26,t):Array.isArray(t)?b(t,e,n,a):d(t,e,n,a)}c(clampValue,"clampValue"),l(clampValue,"clampValue"),y(clampValue,"clampValue");function b(t,e,n,a){const s=[],o=Math.min(t.length,e.maxArrayItems);for(let r=0;r<o&&!(e.budget<=0);r++)s.push(clampValue(t[r],e,n-1,`${a}[${r}]`));return s.length<t.length&&f(e,`${a}[] (+${t.length-s.length} items dropped)`),s}c(b,"m"),l(b,"f"),y(b,"clampArray");function d(t,e,n,a){const s={};let o;const r=e.budget<=0;for(const u in t){if(!Object.prototype.hasOwnProperty.call(t,u))continue;const i=t[u],I=g(i,512,n-1,Number.POSITIVE_INFINITY);if(I<=512&&(!r||m(i))){s[u]=i,e.budget-=u.length+4+I;continue}(o??=[]).push({key:u,bytes:I})}if(!o)return s;o.sort((u,i)=>u.bytes===i.bytes?0:u.bytes<i.bytes?-1:1);for(const{key:u}of o){const i=a?`${a}.${u}`:u;s[u]=clampValue(t[u],e,n-1,i)}return s}c(d,"b"),l(d,"m"),y(d,"clampObject");export function boundedClone(t,e={}){const n=e.rawByteLimit??32768,a=e.maxDepth??12;if(n<=0)return{value:void 0,truncated:!1,originalBytes:0,keptBytes:0,paths:[]};if(t==null)return{value:t,truncated:!1,originalBytes:0,keptBytes:0,paths:[]};if(!exceedsJsonByteBudget(t,n,a)){const i=estimateJsonBytes(t,n,a),I={budget:n,maxStringBytes:e.maxStringBytes??4096,maxArrayItems:e.maxArrayItems??64,paths:[],truncatedAnything:!1};return{value:clampValue(t,I,a,""),truncated:!1,originalBytes:i,keptBytes:i,paths:[]}}const s=estimateJsonBytes(t,Number.POSITIVE_INFINITY,64),o={budget:n,maxStringBytes:e.maxStringBytes??4096,maxArrayItems:e.maxArrayItems??64,paths:[],truncatedAnything:!1},r=clampValue(t,o,a,""),u=estimateJsonBytes(r,Number.POSITIVE_INFINITY,a);if(o.truncatedAnything&&r!==null&&typeof r=="object"&&!Array.isArray(r)){const i={truncated:!0,originalBytes:s,keptBytes:u,paths:o.paths};r[TRUNCATION_MARKER_KEY]=i}return{value:r,truncated:o.truncatedAnything,originalBytes:s,keptBytes:u,paths:o.paths}}c(boundedClone,"boundedClone"),l(boundedClone,"boundedClone"),y(boundedClone,"boundedClone");
@@ -1 +1 @@
1
- "use strict";var c=Object.defineProperty;var t=(e,r)=>c(e,"name",{value:r,configurable:!0});var i=Object.defineProperty,s=t((e,r)=>i(e,"name",{value:r,configurable:!0}),"o");export function capMap(e,r){if(e.size<=r)return 0;let n=0;const o=e.keys();for(;e.size>r;){const a=o.next();if(a.done)break;e.delete(a.value)&&(n+=1)}return n}t(capMap,"capMap"),s(capMap,"capMap");export const MAX_PRODUCER_KEYS=256;
1
+ "use strict";var i=Object.defineProperty;var t=(e,a)=>i(e,"name",{value:a,configurable:!0});var p=Object.defineProperty,o=t((e,a)=>p(e,"name",{value:a,configurable:!0}),"t"),s=Object.defineProperty,u=o((e,a)=>s(e,"name",{value:a,configurable:!0}),"o");export function capMap(e,a){if(e.size<=a)return 0;let r=0;const c=e.keys();for(;e.size>a;){const n=c.next();if(n.done)break;e.delete(n.value)&&(r+=1)}return r}t(capMap,"capMap"),o(capMap,"capMap"),u(capMap,"capMap");export const MAX_PRODUCER_KEYS=256;
@@ -1 +1 @@
1
- "use strict";var y=Object.defineProperty;var r=(e,t)=>y(e,"name",{value:t,configurable:!0});var v=Object.defineProperty,o=r((e,t)=>v(e,"name",{value:t,configurable:!0}),"c");import{renameSync as l,statSync as f,unlinkSync as x}from"node:fs";export function eventMaxBytes(e=process.env){const t=Number(e.LENSMCP_EVENT_MAX_BYTES);return Number.isFinite(t)&&t>0?t:50*1024*1024}r(eventMaxBytes,"eventMaxBytes"),o(eventMaxBytes,"eventMaxBytes");export function eventMaxFiles(e=process.env){const t=Number(e.LENSMCP_EVENT_MAX_FILES);return Number.isFinite(t)&&t>=1&&t<=20?Math.floor(t):5}r(eventMaxFiles,"eventMaxFiles"),o(eventMaxFiles,"eventMaxFiles");const E=1024*1024,a=new Map;export function maybeRotateEventFile(e,t,i){const s=(a.get(e)??0)+t,c=i?.maxBytes??eventMaxBytes(),u=i?.maxFiles??eventMaxFiles(),m=Math.min(E,c);if(s<m){a.set(e,s);return}try{const n=f(e).size;if(a.set(e,0),n<=c)return}catch{a.set(e,s);return}try{x(`${e}.${u}`)}catch{}for(let n=u-1;n>=1;n--)try{l(`${e}.${n}`,`${e}.${n+1}`)}catch{}try{l(e,`${e}.1`)}catch{}}r(maybeRotateEventFile,"maybeRotateEventFile"),o(maybeRotateEventFile,"maybeRotateEventFile");export function resetRotationThrottle(e){e===void 0?a.clear():a.delete(e)}r(resetRotationThrottle,"resetRotationThrottle"),o(resetRotationThrottle,"resetRotationThrottle");
1
+ "use strict";var m=Object.defineProperty;var r=(t,e)=>m(t,"name",{value:e,configurable:!0});var f=Object.defineProperty,o=r((t,e)=>f(t,"name",{value:e,configurable:!0}),"r"),x=Object.defineProperty,s=o((t,e)=>x(t,"name",{value:e,configurable:!0}),"c");import{renameSync as v,statSync as M,unlinkSync as E}from"node:fs";export function eventMaxBytes(t=process.env){const e=Number(t.LENSMCP_EVENT_MAX_BYTES);return Number.isFinite(e)&&e>0?e:50*1024*1024}r(eventMaxBytes,"eventMaxBytes"),o(eventMaxBytes,"eventMaxBytes"),s(eventMaxBytes,"eventMaxBytes");export function eventMaxFiles(t=process.env){const e=Number(t.LENSMCP_EVENT_MAX_FILES);return Number.isFinite(e)&&e>=1&&e<=20?Math.floor(e):5}r(eventMaxFiles,"eventMaxFiles"),o(eventMaxFiles,"eventMaxFiles"),s(eventMaxFiles,"eventMaxFiles");const b=1024*1024,a=new Map;export function maybeRotateEventFile(t,e,c){const i=(a.get(t)??0)+e,l=c?.maxBytes??eventMaxBytes(),u=c?.maxFiles??eventMaxFiles(),y=Math.min(b,l);if(i<y){a.set(t,i);return}try{const n=M(t).size;if(a.set(t,0),n<=l)return}catch{a.set(t,i);return}try{E(`${t}.${u}`)}catch{}for(let n=u-1;n>=1;n--)try{v(`${t}.${n}`,`${t}.${n+1}`)}catch{}try{v(t,`${t}.1`)}catch{}}r(maybeRotateEventFile,"maybeRotateEventFile"),o(maybeRotateEventFile,"maybeRotateEventFile"),s(maybeRotateEventFile,"maybeRotateEventFile");export function resetRotationThrottle(t){t===void 0?a.clear():a.delete(t)}r(resetRotationThrottle,"resetRotationThrottle"),o(resetRotationThrottle,"resetRotationThrottle"),s(resetRotationThrottle,"resetRotationThrottle");
@@ -1 +1 @@
1
- "use strict";var c=Object.defineProperty;var i=(e,a)=>c(e,"name",{value:a,configurable:!0});var p=Object.defineProperty,t=i((e,a)=>p(e,"name",{value:a,configurable:!0}),"s");export const TASK_ARTIFACT_TYPES={"image/png":"png","image/jpeg":"jpg","image/webp":"webp","image/gif":"gif","application/json":"json","text/plain":"txt","text/markdown":"md","text/csv":"csv"},TASK_ARTIFACT_MAX_BYTES=10*1024*1024,TASK_ARTIFACTS_MAX=50,TASK_ARTIFACTS_MAX_BYTES=100*1024*1024,CANVAS_IMAGE_TYPES=Object.keys(TASK_ARTIFACT_TYPES).filter(e=>e.startsWith("image/")),CANVAS_ASSET_ID_PATTERN=/^as-[0-9a-f]{12}$/,isCanvasAssetId=t(e=>typeof e=="string"&&CANVAS_ASSET_ID_PATTERN.test(e),"isCanvasAssetId");export function canvasAnswerAsset(e){if(!e||typeof e!="object"||Array.isArray(e))return;const a=e;return isCanvasAssetId(a.asset)&&typeof a.name=="string"?{asset:a.asset,name:a.name}:void 0}i(canvasAnswerAsset,"canvasAnswerAsset"),t(canvasAnswerAsset,"canvasAnswerAsset");export const isCanvasAttachAsk=t(e=>e.kind==="file"||e.kind==="image","isCanvasAttachAsk"),canvasAskTypes=t(e=>e.kind==="image"?CANVAS_IMAGE_TYPES:Object.keys(TASK_ARTIFACT_TYPES),"canvasAskTypes"),canvasBytesWords=t(e=>e>=1024*1024?`${(e/1024/1024).toFixed(1)} MB`:`${Math.max(1,Math.round(e/1024))} KB`,"canvasBytesWords");const A={"image/png":"PNG","image/jpeg":"JPEG","image/webp":"WebP","image/gif":"GIF","application/json":"JSON","text/plain":"plain text","text/markdown":"Markdown","text/csv":"CSV"};export const canvasTypeWords=t(e=>e.map(a=>A[a]??a).join(", "),"canvasTypeWords");export function canvasUploadRefusal(e,a){if(!isCanvasAttachAsk(e))return`\`${e.qid}\` is not answered with a file: only a \`Field kind="file"\` or \`kind="image"\` is`;const s=a.name.trim();if(!s||s.length>255||/[/\\]/.test(s)||s.includes("\0"))return"The file needs a name of 1 to 255 characters, with no folder in it";const n=a.mediaType.trim().toLowerCase().split(";")[0]?.trim()??"",r=canvasAskTypes(e);if(!r.includes(n)){const o=n?`${A[n]??n}`:"a file of no known type";return e.kind==="image"?`\xAB${s}\xBB is ${o}: this question takes an image \u2014 ${canvasTypeWords(r)} (never SVG: a browser would run it)`:`\xAB${s}\xBB is ${o}: an attachment is ${canvasTypeWords(r)} (never HTML or SVG: a browser would run it)`}if(a.bytes<1)return`\xAB${s}\xBB is empty`;if(a.bytes>TASK_ARTIFACT_MAX_BYTES)return`\xAB${s}\xBB is ${canvasBytesWords(a.bytes)}: an attachment is at most ${canvasBytesWords(TASK_ARTIFACT_MAX_BYTES)}`}i(canvasUploadRefusal,"canvasUploadRefusal"),t(canvasUploadRefusal,"canvasUploadRefusal");export const CANVAS_RENDER_IMAGE_BYTES=760*1024,CANVAS_ASSET_BODY_BYTES=Math.ceil(TASK_ARTIFACT_MAX_BYTES*4/3)+64*1024;
1
+ "use strict";var p=Object.defineProperty;var i=(e,t)=>p(e,"name",{value:t,configurable:!0});var d=Object.defineProperty,o=i((e,t)=>d(e,"name",{value:t,configurable:!0}),"i"),m=Object.defineProperty,s=o((e,t)=>m(e,"name",{value:t,configurable:!0}),"s");export const TASK_ARTIFACT_TYPES={"image/png":"png","image/jpeg":"jpg","image/webp":"webp","image/gif":"gif","application/json":"json","text/plain":"txt","text/markdown":"md","text/csv":"csv"},TASK_ARTIFACT_MAX_BYTES=10*1024*1024,TASK_ARTIFACTS_MAX=50,TASK_ARTIFACTS_MAX_BYTES=100*1024*1024,CANVAS_IMAGE_TYPES=Object.keys(TASK_ARTIFACT_TYPES).filter(e=>e.startsWith("image/")),CANVAS_ASSET_ID_PATTERN=/^as-[0-9a-f]{12}$/,isCanvasAssetId=s(e=>typeof e=="string"&&CANVAS_ASSET_ID_PATTERN.test(e),"isCanvasAssetId");export function canvasAnswerAsset(e){if(!e||typeof e!="object"||Array.isArray(e))return;const t=e;return isCanvasAssetId(t.asset)&&typeof t.name=="string"?{asset:t.asset,name:t.name}:void 0}i(canvasAnswerAsset,"canvasAnswerAsset"),o(canvasAnswerAsset,"canvasAnswerAsset"),s(canvasAnswerAsset,"canvasAnswerAsset");export const isCanvasAttachAsk=s(e=>e.kind==="file"||e.kind==="image","isCanvasAttachAsk"),canvasAskTypes=s(e=>e.kind==="image"?CANVAS_IMAGE_TYPES:Object.keys(TASK_ARTIFACT_TYPES),"canvasAskTypes"),canvasBytesWords=s(e=>e>=1024*1024?`${(e/1024/1024).toFixed(1)} MB`:`${Math.max(1,Math.round(e/1024))} KB`,"canvasBytesWords");const c={"image/png":"PNG","image/jpeg":"JPEG","image/webp":"WebP","image/gif":"GIF","application/json":"JSON","text/plain":"plain text","text/markdown":"Markdown","text/csv":"CSV"};export const canvasTypeWords=s(e=>e.map(t=>c[t]??t).join(", "),"canvasTypeWords");export function canvasUploadRefusal(e,t){if(!isCanvasAttachAsk(e))return`\`${e.qid}\` is not answered with a file: only a \`Field kind="file"\` or \`kind="image"\` is`;const a=t.name.trim();if(!a||a.length>255||/[/\\]/.test(a)||a.includes("\0"))return"The file needs a name of 1 to 255 characters, with no folder in it";const n=t.mediaType.trim().toLowerCase().split(";")[0]?.trim()??"",r=canvasAskTypes(e);if(!r.includes(n)){const A=n?`${c[n]??n}`:"a file of no known type";return e.kind==="image"?`\xAB${a}\xBB is ${A}: this question takes an image \u2014 ${canvasTypeWords(r)} (never SVG: a browser would run it)`:`\xAB${a}\xBB is ${A}: an attachment is ${canvasTypeWords(r)} (never HTML or SVG: a browser would run it)`}if(t.bytes<1)return`\xAB${a}\xBB is empty`;if(t.bytes>TASK_ARTIFACT_MAX_BYTES)return`\xAB${a}\xBB is ${canvasBytesWords(t.bytes)}: an attachment is at most ${canvasBytesWords(TASK_ARTIFACT_MAX_BYTES)}`}i(canvasUploadRefusal,"canvasUploadRefusal"),o(canvasUploadRefusal,"canvasUploadRefusal"),s(canvasUploadRefusal,"canvasUploadRefusal");export const CANVAS_RENDER_IMAGE_BYTES=760*1024,CANVAS_ASSET_BODY_BYTES=Math.ceil(TASK_ARTIFACT_MAX_BYTES*4/3)+64*1024;