@lensmcp/protocol-types 1.26.9 → 1.26.11

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.
@@ -0,0 +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(`
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");
@@ -0,0 +1,374 @@
1
+ import type { AiCallRow } from './ai-call-row.js';
2
+ import { type AiCacheMark, type AiCacheRequest } from './ai-cache.js';
3
+ import { type AiCacheTtl } from './ai-cache-facts.js';
4
+ import { type AiCacheRatesOf, type AiCacheVerdictKind } from './ai-cache-verdict.js';
5
+ /**
6
+ * The calls of one agent reviewed together (foodguard-301 C), by arithmetic — no model. The waste was never inside one
7
+ * call: it was between calls in flight at the same moment, between the products of one business, and between the
8
+ * answer's size and the stage's time.
9
+ *
10
+ * **A group** is the calls of one agent in one run — else one flow, else one request — whose times overlap: sent while
11
+ * another was still in flight, chained (a wave). Waves sent within {@link FOLLOW_MS} of each other are one group — a
12
+ * prewarm and the calls it warmed, a fan-out and the merge that waited for it — when one of them holds at least two
13
+ * calls. A tool loop's steps, one after another, are no group: nothing in it ran together.
14
+ *
15
+ * For a group:
16
+ * - **its input cost against the ideal** (the issue's § 2.2): over the prefixes its calls share (the cache marks A keeps,
17
+ * set on the provider's count at the breakpoints it says it read and wrote), one write and the rest reads —
18
+ * `P·w + (N−1)·P·r`, or with a prewarm `P·w + N·P·r` — what was already in the cache before it read by all, each call's
19
+ * own tail at the plain rate; the gap in dollars and the arithmetic, an estimate: the positions are;
20
+ * - **the levels its calls share** and where each ends and they part — where a breakpoint belongs;
21
+ * - **its cache verdicts** (B): the duplicate writes, the races, what they cost;
22
+ * - **its time**: the slowest call, its output tokens and tokens a second; the spread of its fan-out; items per call
23
+ * where the app labels them;
24
+ * - with the kept texts: **the answer's tokens by schema field** (and the largest repeated row kind's share), **sections
25
+ * the answers never quote** (candidates — a text-overlap stand-in, untested as a measure), and the first differing line.
26
+ *
27
+ * Across groups, **the levels of an agent's runs**: what one call of each run shares across the runs of one thread, of
28
+ * one tenant (the app's `metadata.tenant` / `business` / `org`…), and of all of them — the prefix (to the mark), and,
29
+ * with the texts, the sections identical anywhere in every run (a block that is mostly the same behind a first line that
30
+ * is not), and the first line where they differ.
31
+ *
32
+ * Pure: on the AI call index's rows (with their marks and B's verdicts), the server's prices, and the requests and
33
+ * answers the server read off the kept exchanges.
34
+ */
35
+ /** A wave sent within this long after the one before it ended is the same group: a prewarm's calls, a merge. */
36
+ export declare const FOLLOW_MS = 1000;
37
+ /** The runs a level across runs is read over, at most — the newest. */
38
+ export declare const MAX_LEVEL_RUNS = 8;
39
+ /** What an index row carries that the groups need. */
40
+ export type AiTogetherRow = Pick<AiCallRow, 'id' | 'at' | 'durationMs' | 'agent' | 'run' | 'thread' | 'flowId' | 'requestId' | 'meta' | 'model' | 'provider' | 'api' | 'tokens' | 'cache' | 'prewarm' | 'failed'>;
41
+ /** What the server read off a call's kept exchange: its request as its cache reads it, its answer. */
42
+ export interface AiTogetherText {
43
+ request?: AiCacheRequest;
44
+ /** The structured answer, parsed. */
45
+ answer?: unknown;
46
+ /** The answer's text — what is searched for quotes. */
47
+ answerText?: string;
48
+ }
49
+ export interface AiTogetherScope {
50
+ /** What holds the group: the app's run (or one its calls chained), else the flow, else the request. */
51
+ by: 'run' | 'flow' | 'request';
52
+ key: string;
53
+ }
54
+ export interface AiTogetherCall {
55
+ id: string;
56
+ at: number;
57
+ ms?: number;
58
+ prewarm?: true;
59
+ failed?: true;
60
+ input?: number;
61
+ read?: number;
62
+ written?: number;
63
+ output?: number;
64
+ reasoning?: number;
65
+ verdict?: AiCacheVerdictKind;
66
+ race?: boolean;
67
+ /** The app's label for how many items it was given (`metadata.items`…). */
68
+ items?: number;
69
+ }
70
+ /** A prefix the group's calls share, from the end of the one before it: one level, where one breakpoint belongs. */
71
+ export interface AiTogetherShared {
72
+ /** The calls that share it (a prewarm among them). */
73
+ calls: number;
74
+ ids: string[];
75
+ /** Its tokens past the level before. */
76
+ tokens: number;
77
+ /** The tokens before its end: where its breakpoint goes — the provider's count where a call's count placed a breakpoint there (`exact`), else the median of its calls' estimates (`estimates`: the lowest and the highest). */
78
+ endsAt: number;
79
+ exact?: true;
80
+ estimates?: [number, number];
81
+ /** The region it ends with, and the one where its calls part. */
82
+ endsIn: string;
83
+ partsIn?: string;
84
+ /** A breakpoint ends it in the requests. */
85
+ breakpoint: boolean;
86
+ /** Its first call read it from the cache: it was there before the group. */
87
+ warm?: true;
88
+ }
89
+ export interface AiTogetherRates {
90
+ model: string;
91
+ input: number;
92
+ cacheRead?: number;
93
+ /** The write rate of the lifetime the writer asked for. */
94
+ write?: number;
95
+ ttl: AiCacheTtl;
96
+ source?: string;
97
+ readAt?: string;
98
+ stale?: true;
99
+ }
100
+ export interface AiTogetherCost {
101
+ /** At the provider's counts and the lens's rates: reads, writes by lifetime, plain input. */
102
+ actualUsd: number;
103
+ actual: string;
104
+ /** One write per shared prefix, the rest reads, what was warm read by all, each call's tail plain — none without marks. */
105
+ idealUsd?: number;
106
+ ideal?: string;
107
+ /** Calls sent together reach the ideal only once one write has finished: a prewarm adds a read for its writer (`P·w + N·P·r`). */
108
+ prewarmUsd?: number;
109
+ gapUsd?: number;
110
+ /** The prefixes' positions are the lens's estimate — set on the provider's count where it says where a breakpoint is. */
111
+ estimate: true;
112
+ /** Calls of the group not in these sums, and why. */
113
+ left?: {
114
+ calls: number;
115
+ why: string;
116
+ };
117
+ rates: AiTogetherRates[];
118
+ }
119
+ export interface AiTogetherDuplicate {
120
+ id: string;
121
+ race: boolean;
122
+ against?: string;
123
+ inFlight?: boolean;
124
+ tokens: number;
125
+ usd?: number;
126
+ arithmetic?: string;
127
+ estimate: boolean;
128
+ }
129
+ export interface AiTogetherTimed {
130
+ id: string;
131
+ ms: number;
132
+ output?: number;
133
+ reasoning?: number;
134
+ /** Output tokens a second. */
135
+ perSecond?: number;
136
+ items?: number;
137
+ }
138
+ export interface AiTogetherAnswer {
139
+ /** Answers read as JSON. */
140
+ answers: number;
141
+ /** The answers' visible tokens (output − reasoning where counted; else estimated) — what the fields share. */
142
+ tokens: number;
143
+ fields: Array<{
144
+ field: string;
145
+ tokens: number;
146
+ share: number;
147
+ }>;
148
+ /** The largest repeated row kind: its path (`hazards[]`), rows, tokens a row, share of the answers. */
149
+ rows?: {
150
+ path: string;
151
+ rows: number;
152
+ tokens: number;
153
+ perRow: number;
154
+ share: number;
155
+ };
156
+ estimate: true;
157
+ }
158
+ export interface AiTogetherUnquoted {
159
+ /** What it rests on: a run of words of a section found in an answer — a stand-in for "the answer used it". */
160
+ measure: string;
161
+ untested: true;
162
+ answers: number;
163
+ candidates: Array<{
164
+ section: string;
165
+ tokens: number;
166
+ calls: number;
167
+ }>;
168
+ }
169
+ export interface AiTogetherDiff {
170
+ region: string;
171
+ line?: string;
172
+ otherLine?: string;
173
+ ids: [string, string];
174
+ }
175
+ export interface AiTogetherGroup {
176
+ key: string;
177
+ agent: {
178
+ key: string;
179
+ name: string;
180
+ };
181
+ scope: AiTogetherScope;
182
+ thread?: string;
183
+ calls: AiTogetherCall[];
184
+ /** The calls sent together, wave by wave. */
185
+ waves: Array<{
186
+ ids: string[];
187
+ at: number;
188
+ ms: number;
189
+ }>;
190
+ at: number;
191
+ end: number;
192
+ /** From the first sent to the last answer. */
193
+ ms: number;
194
+ tokens: {
195
+ input: number;
196
+ read: number;
197
+ written: number;
198
+ plain: number;
199
+ output: number;
200
+ reasoning: number;
201
+ };
202
+ /** Calls whose count the provider gave. */
203
+ counted: number;
204
+ cost?: AiTogetherCost;
205
+ /** The prefixes its calls share, outermost first. */
206
+ shared: AiTogetherShared[];
207
+ cache: {
208
+ verdicts: Partial<Record<AiCacheVerdictKind, number>>;
209
+ lostUsd: number;
210
+ races: number;
211
+ duplicates: AiTogetherDuplicate[];
212
+ prewarm?: string;
213
+ };
214
+ time: {
215
+ slowest?: AiTogetherTimed;
216
+ /** The fastest of its widest wave — the fan-out. */
217
+ fastest?: AiTogetherTimed;
218
+ /** Slowest over fastest, in the fan-out. */
219
+ spread?: number;
220
+ perSecond?: [number, number];
221
+ /** The app labels how many items each call was given. */
222
+ itemsLabelled: boolean;
223
+ };
224
+ answer?: AiTogetherAnswer;
225
+ unquoted?: AiTogetherUnquoted;
226
+ /** Where its calls part, to the line — with the texts. */
227
+ firstDiff?: AiTogetherDiff;
228
+ }
229
+ /** The sections identical, whole, in every member, wherever they sit — with the texts. */
230
+ export interface AiTogetherIdentity {
231
+ /** Of the first member's input (estimated, scaled to its count). */
232
+ tokens: number;
233
+ of: number;
234
+ share: number;
235
+ /** Of those, the tokens after the prefix every member shares: no breakpoint reaches them where they are. */
236
+ afterPrefix: number;
237
+ sections: number;
238
+ ofSections: number;
239
+ /** Block by block, the most identical first: its tokens, the identical ones, and its first line that differs. */
240
+ blocks: Array<{
241
+ block: string;
242
+ tokens: number;
243
+ identical: number;
244
+ share: number;
245
+ line?: {
246
+ at: number;
247
+ text: string;
248
+ other: string;
249
+ id: string;
250
+ };
251
+ }>;
252
+ }
253
+ export interface AiTogetherLevel {
254
+ level: 'thread' | 'tenant' | 'all';
255
+ /** The thread's key, the tenant's value. */
256
+ key?: string;
257
+ /** Runs it is over (one call of each), and those calls, oldest first. */
258
+ runs: number;
259
+ members: string[];
260
+ /**
261
+ * The prefix every member shares, to the mark — none when they part at once: its tokens, the provider's count where a
262
+ * member's count placed a breakpoint there (`exact`), else the median of the members' estimates (`estimates`).
263
+ */
264
+ prefix?: {
265
+ tokens: number;
266
+ exact?: true;
267
+ estimates?: [number, number];
268
+ endsIn: string;
269
+ partsIn?: string;
270
+ breakpoint: boolean;
271
+ };
272
+ identical?: AiTogetherIdentity;
273
+ firstDiff?: AiTogetherDiff;
274
+ /** Other threads or tenants of two runs or more, not shown. */
275
+ more?: number;
276
+ }
277
+ export interface AiTogether {
278
+ /** Newest first. */
279
+ groups: AiTogetherGroup[];
280
+ levels: AiTogetherLevel[];
281
+ totals: {
282
+ groups: number;
283
+ calls: number;
284
+ priced: number;
285
+ actualUsd: number;
286
+ idealUsd: number;
287
+ gapUsd: number;
288
+ races: number;
289
+ duplicates: number;
290
+ };
291
+ }
292
+ export interface AiTogetherOptions {
293
+ ratesOf: AiCacheRatesOf;
294
+ texts?: ReadonlyMap<string, AiTogetherText>;
295
+ /** The group this call is in, alone — and the levels of its thread and tenant. */
296
+ focus?: string;
297
+ /** Groups computed, newest first. */
298
+ maxGroups?: number;
299
+ /** The levels across an agent's runs (default: when the rows are one agent's, or a focus names one). */
300
+ levels?: boolean;
301
+ }
302
+ /** The app's tenant label on a call: `metadata.tenant`, `business`, `org`, `account`, `customer`. */
303
+ export declare const tenantOf: (r: Pick<AiCallRow, "meta">) => string | undefined;
304
+ /** What holds a call's group: its run when the app named it (or its calls chained), else its flow, else its request. */
305
+ export declare function aiTogetherScopeOf(r: Pick<AiCallRow, 'run' | 'flowId' | 'requestId'>): AiTogetherScope | undefined;
306
+ /**
307
+ * The calls whose kept texts the computation reads, for the server to read them: the groups' calls (the focus's
308
+ * group, else the newest `maxGroups`), and one call of each of the newest runs of the levels.
309
+ */
310
+ export declare function aiTogetherPlan(rows: readonly AiTogetherRow[], opts?: {
311
+ focus?: string;
312
+ maxGroups?: number;
313
+ levels?: boolean;
314
+ }): {
315
+ groups: string[];
316
+ members: string[];
317
+ };
318
+ /**
319
+ * A call's marks, their positions set on the provider's count where it says where a breakpoint is: in explicit mode
320
+ * what a call read ends at a breakpoint, and what it read and wrote at another — between those, scaled.
321
+ */
322
+ export declare function aiCalibratedMarks(r: Pick<AiCallRow, 'cache' | 'tokens' | 'failed'>): AiCalibratedMark[];
323
+ /** A mark set on the provider's count: `exact` where the count says a breakpoint is there. */
324
+ export type AiCalibratedMark = AiCacheMark & {
325
+ exact?: true;
326
+ };
327
+ /**
328
+ * The answers' tokens by top-level field, and the largest repeated row kind — an array of objects, at any depth — with
329
+ * its rows, tokens a row and share: estimated from the JSON, scaled to each answer's visible tokens where counted.
330
+ * `undefined` when no answer was read as JSON.
331
+ */
332
+ export declare function aiAnswerFields(answers: ReadonlyArray<{
333
+ json: unknown;
334
+ visible?: number | undefined;
335
+ }>): AiTogetherAnswer | undefined;
336
+ export interface AiRequestSection {
337
+ /** The block it is in: its index in the provider's order, and its label. */
338
+ k: number;
339
+ block: string;
340
+ title: string;
341
+ text: string;
342
+ /** Where it starts: characters of the blocks before it, in the provider's order. */
343
+ at: number;
344
+ /** Estimated. */
345
+ tokens: number;
346
+ }
347
+ /** A request's blocks cut at their sections (`--- TITLE ---`, headings, tags) — the text before the first is its own. */
348
+ export declare function aiRequestSections(req: AiCacheRequest): AiRequestSection[];
349
+ /**
350
+ * The context sections no answer quotes — a run of {@link SHINGLE} words of the section, or an id-like word of it (a
351
+ * letter and a digit, six characters or more), found in the answer of a call it was in. Candidates, never a verdict:
352
+ * the stand-in is untested as a measure (the issue counted it by hand over three runs). `undefined` without answers.
353
+ */
354
+ export declare function aiUnquotedSections(calls: ReadonlyArray<{
355
+ request?: AiCacheRequest | undefined;
356
+ answer?: string | undefined;
357
+ }>): AiTogetherUnquoted | undefined;
358
+ /**
359
+ * The sections identical, whole, in every member's request, wherever they sit — the first member's, by block, with the
360
+ * first line where each block differs; `afterPrefix` the identical tokens past the prefix all of them share (no
361
+ * breakpoint reaches them until they are moved before the first difference). Tokens estimated, scaled to the first
362
+ * member's count where it was counted.
363
+ */
364
+ export declare function aiSectionIdentity(members: ReadonlyArray<{
365
+ id: string;
366
+ request: AiCacheRequest;
367
+ input?: number | undefined;
368
+ }>): AiTogetherIdentity | undefined;
369
+ /** The rows' groups (newest first), the levels across one agent's runs, and the totals over the groups. */
370
+ export declare function aiTogether(rows: readonly AiTogetherRow[], opts: AiTogetherOptions): AiTogether;
371
+ /** A group as lines a person or a model reads: what it cost against the ideal, its levels, its verdicts, its time, its answer. */
372
+ export declare function aiTogetherLines(g: AiTogetherGroup): string[];
373
+ /** A level across runs as lines. */
374
+ export declare function aiTogetherLevelLines(l: AiTogetherLevel): string[];
@@ -0,0 +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");
@@ -181,6 +181,8 @@ export interface DashLint {
181
181
  errors: number;
182
182
  warnings: number;
183
183
  };
184
+ /** The files that hold a finding, both severities — absent from a lens before it said. */
185
+ files?: number;
184
186
  /** The same under the filters. */
185
187
  matched: {
186
188
  errors: number;
@@ -0,0 +1,109 @@
1
+ import type { CheckAnswer, TypecheckFinding } from './static-checks.js';
2
+ /** Checks › Types: `GET /api/typecheck` (type errors grouped and filtered, the checkers, the projects) and `GET /api/typecheck/coverage` (the kept verdicts, no wait). */
3
+ export type DashTypecheckGroupBy = 'file' | 'code' | 'project';
4
+ export declare const DASH_TYPECHECK_GROUP_BY: readonly DashTypecheckGroupBy[];
5
+ export interface DashTypecheckQuery {
6
+ by: DashTypecheckGroupBy;
7
+ /** Only the errors of this project (the one owning the file, else the checker's). */
8
+ project?: string;
9
+ /** `TS2322`. */
10
+ code?: string;
11
+ /** Words in the code, message, file or project. */
12
+ q?: string;
13
+ }
14
+ export interface DashTypecheckFinding {
15
+ /** The event that first reported it. */
16
+ id: string;
17
+ /** `TS2322`; `TS?` when the checker named none. */
18
+ code: string;
19
+ message: string;
20
+ /** Relative to the workspace when it is inside it. */
21
+ file?: string;
22
+ line?: number;
23
+ column?: number;
24
+ project: string;
25
+ /** The checkers (by project) that report it now. */
26
+ programs: string[];
27
+ /** Its newest report. */
28
+ at: number;
29
+ }
30
+ export interface DashTypecheckGroup {
31
+ /** The file, the code or the project. */
32
+ key: string;
33
+ count: number;
34
+ projects: string[];
35
+ projectCount: number;
36
+ files: number;
37
+ codes: number;
38
+ lastSeenAt: number;
39
+ findings: DashTypecheckFinding[];
40
+ more: number;
41
+ }
42
+ export type DashTypecheckRunState = 'running' | 'clean' | 'failing' | 'error';
43
+ /** One checker that reports into the lens (`<tool>:<project>`), as its last run left it. */
44
+ export interface DashTypecheckRun {
45
+ id: string;
46
+ tool: string;
47
+ project?: string;
48
+ state: DashTypecheckRunState;
49
+ /** Its newest report, and its first. */
50
+ at: number;
51
+ firstAt: number;
52
+ durationMs?: number;
53
+ errors: number;
54
+ warnings?: number;
55
+ /** Why it gave no verdict. */
56
+ error?: string;
57
+ }
58
+ /** A project of the workspace, the errors held in its files and the checkers of its own. */
59
+ export interface DashTypecheckProject {
60
+ name: string;
61
+ root: string;
62
+ service?: true;
63
+ errors: number;
64
+ /** The checkers that report under its name; none: its files are checked only through the programs that hold them. */
65
+ checkers: string[];
66
+ }
67
+ export interface DashTypecheckFacet {
68
+ name: string;
69
+ errors: number;
70
+ }
71
+ export interface DashTypecheck {
72
+ at: number;
73
+ /** False when this lens does not serve `typecheck://`. */
74
+ served: boolean;
75
+ status: 'unknown' | 'clean' | 'failing';
76
+ /** `none`: no checker has ever reported here — unchecked, not passing. */
77
+ producer: 'none' | 'connected';
78
+ detail?: string;
79
+ /** The newest report is older than the producers' staleness bound. */
80
+ stale?: boolean;
81
+ lastRunAt?: number;
82
+ totals: {
83
+ errors: number;
84
+ files: number;
85
+ projects: number;
86
+ };
87
+ /** The errors under the filters. */
88
+ matched: number;
89
+ query: DashTypecheckQuery;
90
+ groups: DashTypecheckGroup[];
91
+ moreGroups: number;
92
+ runs: DashTypecheckRun[];
93
+ projects: DashTypecheckProject[];
94
+ moreProjects: number;
95
+ facets: {
96
+ projects: DashTypecheckFacet[];
97
+ codes: DashTypecheckFacet[];
98
+ };
99
+ }
100
+ /** The kept verdicts' answer for every program, one finding long — or why there is none (no tsgo, no program). */
101
+ export type DashTypecheckCoverage = {
102
+ at: number;
103
+ available: true;
104
+ answer: CheckAnswer<TypecheckFinding>;
105
+ } | {
106
+ at: number;
107
+ available: false;
108
+ why: string;
109
+ };
@@ -0,0 +1 @@
1
+ "use strict";export const DASH_TYPECHECK_GROUP_BY=["file","code","project"];
@@ -18,6 +18,7 @@ import type { DesignStage } from './goal-design.js';
18
18
  import type { DashExternalBefore, DashSqlBefore } from './metrics-reset.js';
19
19
  import type { ExpectedFailureMatch } from './expected-failure.js';
20
20
  import type { ErrorJudgement, ErrorVerdict } from './error-verdict.js';
21
+ import type { FindingRiskClass, FindingSaving } from './finding-proof.js';
21
22
  /** Bumped only on a breaking change to the stream framing itself. */
22
23
  export declare const DASHBOARD_PROTOCOL = 1;
23
24
  /** The swimlane a flow event belongs to (mirrors `FlowArea` in `@lensmcp/core`'s flow-shape). */
@@ -2862,6 +2863,16 @@ export interface DashAiFinding {
2862
2863
  /** How to roll it out safely, and back. */
2863
2864
  deploy?: string;
2864
2865
  verify: string;
2866
+ /**
2867
+ * What the model reads after the change — the class decides the proof it owes (foodguard-301 §4, `finding-proof.ts`).
2868
+ * Asked of the AI agent review's findings; absent on an older review, or when the model named none or one not in the
2869
+ * list: such a finding is shown unclassified, never dropped.
2870
+ */
2871
+ riskClass?: FindingRiskClass;
2872
+ /** What must be shown before the change ships, for its class, made concrete for it (which spec, which calls, how many runs a side). */
2873
+ proofOwed?: string;
2874
+ /** What it saves, with the arithmetic behind it — an estimate unless the evidence held calls from before and after the change. */
2875
+ saving?: FindingSaving;
2865
2876
  }
2866
2877
  /** What a thing costs the app, measured by the lens before any model is asked; `low` holds every finding at low. */
2867
2878
  export interface DashAiImpact {