@lensmcp/protocol-types 1.26.33 → 1.26.34
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/index.d.ts +3 -0
- package/index.js +1 -1
- package/lib/account-drain.js +1 -1
- package/lib/ai-cache-facts.js +1 -1
- package/lib/ai-cache-verdict.js +1 -1
- package/lib/ai-cache.js +3 -3
- package/lib/ai-call-groups.js +2 -2
- package/lib/ai-call-row.js +3 -3
- package/lib/ai-call.js +9 -9
- package/lib/ai-compare.js +3 -3
- package/lib/ai-context.js +6 -6
- package/lib/ai-origins.js +9 -9
- package/lib/ai-together.js +5 -5
- package/lib/bounded-clone.js +1 -1
- package/lib/bounded-map.js +1 -1
- package/lib/bounded-writer.js +1 -1
- package/lib/canvas-attachments.js +1 -1
- package/lib/canvas-catalog.js +3 -3
- package/lib/canvas-chat.js +2 -2
- package/lib/canvas-editing.js +4 -4
- package/lib/canvas-frame-policy.js +1 -1
- package/lib/canvas-hub.js +1 -1
- package/lib/canvas.js +1 -1
- package/lib/capture-demand.js +1 -1
- package/lib/dashboard-path.js +1 -1
- package/lib/delivery-status.d.ts +197 -0
- package/lib/delivery-status.js +1 -0
- package/lib/docker-errors.js +1 -1
- package/lib/docker-jobs.js +1 -1
- package/lib/docker-report.js +2 -2
- package/lib/docker-runs.js +3 -3
- package/lib/error-cause.js +6 -6
- package/lib/error-dismissal.js +1 -1
- package/lib/error-verdict.js +3 -3
- package/lib/event-loop.js +1 -1
- package/lib/expected-failure.js +2 -2
- package/lib/finding-proof.js +1 -1
- package/lib/flood-guard.js +1 -1
- package/lib/goal-design.js +1 -1
- package/lib/goal-number.d.ts +20 -0
- package/lib/goal-number.js +1 -0
- package/lib/host-agents.js +1 -1
- package/lib/lens-hosts.js +1 -1
- package/lib/lint-coverage.js +1 -1
- package/lib/lint-ignores.js +2 -2
- package/lib/log-query.js +1 -1
- package/lib/metrics-reset.js +1 -1
- package/lib/overseer-findings.js +1 -1
- package/lib/peers.d.ts +2 -2
- package/lib/peers.js +1 -1
- package/lib/perf-rules.js +1 -1
- package/lib/pod-memory.js +1 -1
- package/lib/producer-health.js +1 -1
- package/lib/pull-requests.d.ts +161 -0
- package/lib/pull-requests.js +1 -0
- package/lib/remote-instances.js +1 -1
- package/lib/sources.js +1 -1
- package/lib/static-checks.js +1 -1
- package/lib/system-report.js +1 -1
- package/lib/team-roadmap.d.ts +2 -0
- package/lib/team.d.ts +64 -0
- package/lib/team.js +1 -1
- package/package.json +1 -1
package/lib/ai-together.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
"use strict";var
|
|
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
|
-
`,
|
|
4
|
-
`,i);return
|
|
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
|
+
"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");
|
package/lib/bounded-clone.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var T=Object.defineProperty;var
|
|
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");
|
package/lib/bounded-map.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
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;
|
package/lib/bounded-writer.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
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 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
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;
|
package/lib/canvas-catalog.js
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var o=Object.defineProperty;var r=(e,t)=>o(e,"name",{value:t,configurable:!0});var d=Object.defineProperty,s=r((e,t)=>d(e,"name",{value:t,configurable:!0}),"i");const n=["neutral","info","success","warning","danger"];export const CANVAS_CHART_TYPES=["bar","line","area","stacked","pie","scatter"],CANVAS_CALLOUT_TYPES=["note","info","tip","warning","danger","success"],CANVAS_COMPONENTS=[{name:"Callout",group:"layout",describe:"A highlighted note.",props:{type:{type:"enum",values:CANVAS_CALLOUT_TYPES,describe:"How it reads: note (default), info, tip, warning, danger, success."},title:{type:"string",describe:"A short heading."}},children:"blocks",example:'<Callout type="warning" title="Before you merge">The migration locks `orders` for about 2 s.</Callout>'},{name:"Details",group:"layout",describe:"A section the person opens.",props:{summary:{type:"string",required:!0,describe:"What the closed section says."},open:{type:"boolean",describe:"Open at first."}},children:"blocks",example:'<Details summary="How it was measured">Three runs on the dev Mac \u2026</Details>'},{name:"Tabs",group:"layout",describe:"Tabs; each child is a `Tab`.",props:{},children:"Tab",example:`<Tabs>
|
|
2
2
|
<Tab title="Before">\u2026</Tab>
|
|
3
3
|
<Tab title="After">\u2026</Tab>
|
|
4
4
|
</Tabs>`},{name:"Tab",group:"layout",describe:"One tab of a `Tabs`.",props:{title:{type:"string",required:!0,describe:"The tab\u2019s label."}},children:"blocks",parent:"Tabs",example:'<Tab title="After">\u2026</Tab>'},{name:"Columns",group:"layout",describe:"Children side by side (stacked on a narrow screen).",props:{count:{type:"number",describe:"How many columns (2\u20134, default: one per child)."}},children:"blocks",example:`<Columns>
|
|
5
5
|
<Stat label="p95" value="120 ms" />
|
|
6
6
|
<Stat label="Errors" value={3} />
|
|
7
|
-
</Columns>`},{name:"Badge",group:"layout",describe:"A small label.",props:{tone:{type:"enum",values:
|
|
7
|
+
</Columns>`},{name:"Badge",group:"layout",describe:"A small label.",props:{tone:{type:"enum",values:n,describe:"Its color."}},children:"text",example:'<Badge tone="success">shipped</Badge>'},{name:"Stat",group:"data",describe:"One number with a label.",props:{label:{type:"string",required:!0,describe:"What it counts."},value:{type:"any",describe:"The value (or `source`)."},source:{type:"source",describe:"Where the value is: a JSON Pointer into the data (`/totals/cost`) or a get."},unit:{type:"string",describe:"Shown after the value."},delta:{type:"any",describe:"A change to show beside it (`+12%`, or a number)."},tone:{type:"enum",values:n,describe:"Its color."}},children:"none",example:'<Stat label="Monthly cost" source="/totals/cost" unit="USD" />'},{name:"Chart",group:"data",describe:"A chart of rows: bar, line, area, stacked, pie, scatter.",props:{type:{type:"enum",values:CANVAS_CHART_TYPES,required:!0,describe:"Which chart."},data:{type:"rows",describe:"Inline rows (or `source`)."},source:{type:"source",describe:"Where the rows are: a JSON Pointer to an array of objects."},x:{type:"string",required:!0,describe:"The key each row\u2019s x (or slice, for pie) is under."},y:{type:"strings",required:!0,describe:"The numeric key(s) to draw: one series each."},title:{type:"string",describe:"A heading."},unit:{type:"string",describe:"The values\u2019 unit."},height:{type:"number",describe:"Pixels (default 260)."}},children:"none",example:'<Chart type="bar" source="/costs/monthly" x="month" y={["cost"]} unit="USD" />'},{name:"Table",group:"data",describe:"Rows as a sortable table (virtualised past 500 rows).",props:{data:{type:"rows",describe:"Inline rows (or `source`)."},source:{type:"source",describe:"A JSON Pointer to an array of objects."},columns:{type:"columns",describe:"Which keys, in order (default: the first row\u2019s)."},title:{type:"string",describe:"A heading."}},children:"none",example:'<Table source="/checks" columns={["name","state","ms"]} />'},{name:"Timeline",group:"data",describe:"Dated events in order.",props:{data:{type:"rows",describe:"Inline events (or `source`): objects with a date and a title."},source:{type:"source",describe:"A JSON Pointer to an array of objects."},date:{type:"string",describe:"The key of each event\u2019s date (default `date`)."},label:{type:"string",describe:"The key of each event\u2019s title (default `title`)."}},children:"none",example:'<Timeline source="/milestones" />'},{name:"TaskRef",group:"reference",describe:"A link to a task.",props:{id:{type:"string",required:!0,literal:!0,describe:"The task id."}},children:"text",example:'<TaskRef id="6f1c\u2026" />'},{name:"GoalRef",group:"reference",describe:"A link to a goal.",props:{id:{type:"string",required:!0,literal:!0,describe:"The goal id."}},children:"text",example:'<GoalRef id="g-42" />'},{name:"CanvasRef",group:"reference",describe:"A link to another canvas.",props:{id:{type:"string",required:!0,literal:!0,describe:"The canvas id (`cv-\u2026`)."}},children:"text",example:'<CanvasRef id="cv-0123456789abcdef" />'},{name:"FileRef",group:"reference",describe:"A link to a file of the project (opened on the Changes page).",props:{path:{type:"string",required:!0,literal:!0,describe:"Repository-relative path."},line:{type:"number",literal:!0,describe:"A line to open at."}},children:"text",example:'<FileRef path="libs/core/src/index.ts" line={12} />'},{name:"Options",group:"decision",describe:"A decision between options, each an `Option` with its own text; the person picks one.",props:{qid:{type:"string",required:!0,describe:"The decision\u2019s id: what the answer is keyed by."},title:{type:"string",required:!0,describe:"The question the options answer."},blocking:{type:"boolean",describe:"Its linked task waits for the answer: no one claims it until it is answered, and its next holder reads the answer. Asked in Team \u203A Inbox like `inbox`, flagged."},inbox:{type:"boolean",describe:"Also ask it in Team \u203A Inbox: it goes to the linked goal's manager first, then the person (no manager on the team, the manager escalates it, its session ends, or 30 minutes pass)."}},children:"Option",interactive:!0,example:`<Options qid="store" title="Where do canvases live?">
|
|
8
8
|
<Option id="sqlite" title="One SQLite database" recommended>\u2026</Option>
|
|
9
9
|
<Option id="files" title="Files per canvas">\u2026</Option>
|
|
10
10
|
</Options>`},{name:"Option",group:"decision",describe:"One option of an `Options`: its body is the argument for it.",props:{id:{type:"string",required:!0,describe:"The option\u2019s id (the answer\u2019s value)."},title:{type:"string",required:!0,describe:"Its name."},recommended:{type:"boolean",describe:"The one you recommend."}},children:"blocks",parent:"Options",interactive:!0,example:'<Option id="sqlite" title="One SQLite database" recommended>Transactions, one writer \u2026</Option>'},{name:"Question",group:"interactive",describe:"A question the person answers in the document.",props:{qid:{type:"string",required:!0,describe:"Its id: what the answer is keyed by. Letters, digits, `-`, `_`."},kind:{type:"enum",values:["choice","multi","text","number","confirm","approve"],required:!0,describe:"choice (one option), multi (any), text, number, confirm (yes/no), approve (approve / ask for changes)."},title:{type:"string",required:!0,describe:"The question, as the control shows it."},detail:{type:"string",describe:"A line of context under it."},options:{type:"options",describe:'For choice and multi: `[{id, label, detail?}]` or `["A", "B"]`.'},recommended:{type:"string",describe:"The option id you recommend."},blocking:{type:"boolean",describe:"Its linked task waits for the answer: no one claims it until it is answered, and its next holder reads the answer. Asked in Team \u203A Inbox like `inbox`, flagged."},inbox:{type:"boolean",describe:"Also ask it in Team \u203A Inbox: it goes to the linked goal's manager first, then the person (no manager on the team, the manager escalates it, its session ends, or 30 minutes pass)."},required:{type:"boolean",describe:"An answer is needed."},min:{type:"number",describe:"For number: the least."},max:{type:"number",describe:"For number: the most."},placeholder:{type:"string",describe:"For text and number."}},children:"none",interactive:!0,example:'<Question qid="db" kind="choice" title="Which database?" options={["Postgres", "SQLite"]} recommended="sqlite" />'},{name:"Checklist",group:"interactive",describe:"Items the person ticks; each item is its own answer (`qid/itemId`).",props:{qid:{type:"string",required:!0,describe:"Its id."},title:{type:"string",required:!0,describe:"What the list is for."},items:{type:"options",required:!0,describe:'`[{id, label}]` or `["Lint", "Tests"]`.'}},children:"none",interactive:!0,example:'<Checklist qid="release" title="Before release" items={["Changelog", "Docs", "Smoke test"]} />'},{name:"Field",group:"interactive",describe:"One value the person fills in \u2014 or a file or image they attach, in the dashboard's own picker (the frame never sees it). The answer is `{ asset, name }`; canvas_get and canvas_wait name its `file.path`.",props:{qid:{type:"string",required:!0,describe:"Its id."},label:{type:"string",required:!0,describe:"What to fill in."},kind:{type:"enum",values:["text","number","date","file","image"],required:!0,describe:"text, number, date, file (PNG, JPEG, WebP, GIF, JSON, plain text, Markdown, CSV; at most 10 MB) or image (PNG, JPEG, WebP, GIF)."},placeholder:{type:"string",describe:"A hint inside it."},required:{type:"boolean",describe:"An answer is needed."},min:{type:"number",describe:"For number."},max:{type:"number",describe:"For number."}},children:"none",interactive:!0,example:`<Field qid="deadline" label="Ship by" kind="date" />
|
|
11
11
|
<Field qid="screenshot" label="A screenshot of the error" kind="image" />`},{name:"When",group:"interactive",describe:"Shows its content (follow-up text and questions) once a question is answered so.",props:{qid:{type:"string",required:!0,describe:"The question it follows."},is:{type:"strings",required:!0,describe:'The option id(s) \u2014 or "yes"/"no" for a confirm \u2014 that show it.'}},children:"blocks",interactive:!0,example:`<When qid="db" is="postgres">
|
|
12
12
|
<Question qid="pg-host" kind="text" title="Which host?" />
|
|
13
|
-
</When>`}],CANVAS_COMPONENT_NAMES=CANVAS_COMPONENTS.map(e=>e.name),canvasComponent=
|
|
13
|
+
</When>`}],CANVAS_COMPONENT_NAMES=CANVAS_COMPONENTS.map(e=>e.name),canvasComponent=s(e=>CANVAS_COMPONENTS.find(t=>t.name===e),"canvasComponent"),CANVAS_FENCES=["mermaid","diff"];export function canvasComponentSchema(e){const t=Object.entries(e.props).map(([a,i])=>`${a}${i.required?"*":""}: ${i.type==="enum"?(i.values??[]).join("|"):i.type}`);return`${e.name} { ${t.join(", ")} }${e.children==="none"?"":` children: ${e.children}`}`}r(canvasComponentSchema,"canvasComponentSchema"),s(canvasComponentSchema,"canvasComponentSchema");export function canvasOptionId(e){const t=e.normalize("NFKD").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,63);return/^[a-z]/.test(t)?t:`o-${t||"x"}`.slice(0,63)}r(canvasOptionId,"canvasOptionId"),s(canvasOptionId,"canvasOptionId");export const CANVAS_INTERNAL_COMPONENTS=["CanvasBlock","CanvasMermaid","CanvasDiffBlock"];
|
package/lib/canvas-chat.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
`)}
|
|
1
|
+
"use strict";var r=Object.defineProperty;var a=(t,e)=>r(t,"name",{value:e,configurable:!0});var o=Object.defineProperty,n=a((t,e)=>o(t,"name",{value:e,configurable:!0}),"a");export const CANVAS_CHAT_ENGINES=["model","agent"],CANVAS_CHAT_STATES=["idle","working","stopped","failed"],CANVAS_CHAT_ROW_KINDS=["person","reply","step","version","edit","error","engine"],CANVAS_CHAT_EFFORTS=["low","medium","high","xhigh","max"],isCanvasChatEffort=n(t=>typeof t=="string"&&CANVAS_CHAT_EFFORTS.includes(t),"isCanvasChatEffort");export function canvasChatEfforts(t,e){return t==="model"?e?.provider==="openai"?CANVAS_CHAT_EFFORTS.slice(0,3):CANVAS_CHAT_EFFORTS:e?.client==="codex"?CANVAS_CHAT_EFFORTS.slice(0,4):CANVAS_CHAT_EFFORTS}a(canvasChatEfforts,"canvasChatEfforts"),n(canvasChatEfforts,"canvasChatEfforts");export function canvasChatEffortFor(t,e){const s=e?.effort;if(!isCanvasChatEffort(s))return;const i=canvasChatEfforts(t,e);return i.includes(s)?s:i[i.length-1]}a(canvasChatEffortFor,"canvasChatEffortFor"),n(canvasChatEffortFor,"canvasChatEffortFor");export const CANVAS_CHAT_LIMITS={textChars:8e3,rows:500,title:120},CANVAS_AUTHOR_ROLE="canvas-author",CANVAS_AUTHOR_IDLE_MINUTES=15;export function canvasAuthorText(t){const e=JSON.stringify(t.chat);return["# Your role: canvas author (LensMCP)","",`You write a canvas with a person, in a chat (${t.chat}). Read it with \`canvas_chat { chat: ${e} }\`, change the canvas with \`canvas_write\` (\`chat: ${e}\` on the first, which makes it), say what you did with \`canvas_chat { chat: ${e}, say }\` \u2014 short \u2014 and wait for the next message with \`canvas_wait { on: ["chat"], chat: ${e}, since }\`. Do not change the repository. Stop after ${CANVAS_AUTHOR_IDLE_MINUTES} idle minutes; the person's next message starts you again with the chat so far.`,"",t.canvas?`- The canvas is ${t.canvas}: read it first (\`canvas_get { id: ${JSON.stringify(t.canvas)}, include: ["mdx", "data", "shape"] }\`), then write \`canvas_write { id: ${JSON.stringify(t.canvas)}, chat: ${e}, ifVersion, note }\`.`:`- There is no canvas yet: your first \`canvas_write { chat: ${e}, mdx, data, note }\` makes it and binds it to the chat; write the next versions with its \`id\`.`,"- Read skill://lensmcp-canvas/SKILL.md before you write: the components, the data and its shape, and what the checker refuses.","- What to do is in the person's messages (`kind: \"person\"`). An `edit` row is a version the person saved themselves: read it before you write, and build on it, never over it. Other rows are the chat's record.","- Read the repository and the lens as the canvas needs; change nothing in the repository \u2014 no edits, no commits, no branches. What you make is the canvas.",`- One message, one answer: the version(s) it asks for, one short \`say\`, then \`canvas_wait\` with the \`seq\` you read. Back with nothing new: wait again \u2014 once ${CANVAS_AUTHOR_IDLE_MINUTES} minutes passed with nothing, end.`].join(`
|
|
2
|
+
`)}a(canvasAuthorText,"canvasAuthorText"),n(canvasAuthorText,"canvasAuthorText");export function canvasAuthorStart(t){return`The person wrote to you in the canvas chat ${t.chat}: read it with canvas_chat { chat: ${JSON.stringify(t.chat)} } and answer its newest messages, as your role says. (LensMCP launch ${t.launchId}.)`}a(canvasAuthorStart,"canvasAuthorStart"),n(canvasAuthorStart,"canvasAuthorStart");
|
package/lib/canvas-editing.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var d=Object.defineProperty;var l=(e,n)=>d(e,"name",{value:n,configurable:!0});var
|
|
2
|
-
`).length,
|
|
3
|
-
`)}else if(/end of JSON input/i.test(
|
|
4
|
-
`);s=t.length,
|
|
1
|
+
"use strict";var d=Object.defineProperty;var l=(e,n)=>d(e,"name",{value:n,configurable:!0});var u=Object.defineProperty,p=l((e,n)=>u(e,"name",{value:n,configurable:!0}),"c");export function parseCanvasJsonText(e,n){try{return{ok:!0,value:JSON.parse(e)}}catch(r){const a=r instanceof Error?r.message:String(r),i=/\(line (\d+) column (\d+)\)/.exec(a),c=/position (\d+)/.exec(a);let s,o;if(i)s=Number(i[1]),o=Number(i[2]);else if(c){const t=e.slice(0,Number(c[1]));s=t.split(`
|
|
2
|
+
`).length,o=t.length-t.lastIndexOf(`
|
|
3
|
+
`)}else if(/end of JSON input/i.test(a)){const t=e.split(`
|
|
4
|
+
`);s=t.length,o=(t[t.length-1]?.length??0)+1}const m=a.replace(/^SyntaxError:\s*/,"").replace(/\s*\(line \d+ column \d+\)/,"").replace(/,? ?"[^"]{40,}"? is not valid JSON/," is not valid JSON");return{ok:!1,problem:{code:"json",severity:"error",part:n,message:`The ${n} is not JSON: ${m}`,hint:n==="data"?"Data is one JSON value: quote keys and strings, no trailing commas, no comments.":"A shape is a JSON object: quote keys and strings, no trailing commas, no comments.",...s!==void 0?{line:s}:{},...o!==void 0?{column:o}:{}}}}}l(parseCanvasJsonText,"parseCanvasJsonText"),p(parseCanvasJsonText,"parseCanvasJsonText");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var e=Object.defineProperty;var n=(s,t)=>e(s,"name",{value:t,configurable:!0});var a=Object.defineProperty,o=n((s,t)=>a(s,"name",{value:t,configurable:!0}),"n");export const CANVAS_FRAME_FILE=/^(?:(?:media|chunks)\/)?[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)*\.(html|js|css|woff2|woff|map|svg)$/,CANVAS_FRAME_TYPES={html:"text/html; charset=utf-8",js:"application/javascript; charset=utf-8",css:"text/css; charset=utf-8",woff2:"font/woff2",woff:"font/woff",map:"application/json",svg:"image/svg+xml"},CANVAS_FRAME_ANCESTORS="http://localhost:* http://127.0.0.1:* https://lensmcp.localhost:* https://*.lensmcp.localhost:* https://lensmcp.local:*";export function canvasFrameCsp(s,t=CANVAS_FRAME_ANCESTORS){return["default-src 'none'",`script-src ${s} 'unsafe-eval'`,`style-src ${s} 'unsafe-inline'`,`font-src ${s}`,"img-src data: blob:","connect-src 'none'","frame-src 'none'","form-action 'none'","base-uri 'none'","object-src 'none'","worker-src 'none'","manifest-src 'none'",`frame-ancestors ${t}`].join("; ")}n(canvasFrameCsp,"canvasFrameCsp"),o(canvasFrameCsp,"canvasFrameCsp");
|
package/lib/canvas-hub.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var r=Object.defineProperty;var a=(e,t)=>r(e,"name",{value:t,configurable:!0});var s=Object.defineProperty,n=a((e,t)=>s(e,"name",{value:t,configurable:!0}),"t");export const CANVAS_HUB_API="/hub/v1",CANVAS_HUB_ROLES=["read","answer","write","admin"];export function canvasHubRoleAtLeast(e,t){return e?CANVAS_HUB_ROLES.indexOf(e)>=CANVAS_HUB_ROLES.indexOf(t):!1}a(canvasHubRoleAtLeast,"canvasHubRoleAtLeast"),n(canvasHubRoleAtLeast,"canvasHubRoleAtLeast");export const isCanvasHubRole=n(e=>typeof e=="string"&&CANVAS_HUB_ROLES.includes(e),"isCanvasHubRole");
|
package/lib/canvas.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var m=Object.defineProperty;var r=(e,t)=>m(e,"name",{value:t,configurable:!0});var p=Object.defineProperty,o=r((e,t)=>p(e,"name",{value:t,configurable:!0}),"o");import{z as a}from"zod";import{TASK_ARTIFACT_MAX_BYTES as A,TASK_ARTIFACTS_MAX as h,TASK_ARTIFACTS_MAX_BYTES as d}from"./canvas-attachments.js";export const CANVAS_FORMAT=1,CANVAS_FRAME_PROTOCOL=1,CANVAS_FRAME_RUNTIME="frame-v1",CANVAS_FRAME_PATH="/v1",CANVAS_FRAME_HOST="lensmcp.canvas.localhost",CANVAS_ID_PATTERN=/^cv-[0-9a-f]{16}$/,CANVAS_PROJECT_ID_PATTERN=/^pr-[0-9a-f]{16}$/,CANVAS_QID_PATTERN=/^[a-z][a-z0-9_-]{0,63}$/i,isCanvasId=o(e=>typeof e=="string"&&CANVAS_ID_PATTERN.test(e),"isCanvasId"),CANVAS_TAG_PATTERN=/^[a-z0-9][a-z0-9-]{0,31}$/,CANVAS_TAG_LIMITS={count:8,chars:32},CANVAS_DESIGN_TAG="design";export function canvasTags(e){if(!Array.isArray(e))return{why:"`tags` is a list of short labels"};const t=[];for(const n of e){if(typeof n!="string")return{why:"`tags` is a list of short labels"};const s=n.trim().replace(/^#+/,"").toLowerCase().replace(/[\s_]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"");if(s){if(!CANVAS_TAG_PATTERN.test(s))return{why:`\xAB${n.slice(0,40)}\xBB is not a label: lower-case letters, digits and -, at most ${CANVAS_TAG_LIMITS.chars} characters`};t.includes(s)||t.push(s)}}return t.length>CANVAS_TAG_LIMITS.count?{why:`a canvas has at most ${CANVAS_TAG_LIMITS.count} labels; got ${t.length}`}:{tags:t}}r(canvasTags,"canvasTags"),o(canvasTags,"canvasTags");export function authoredCanvasTags(e,t=[]){const n=canvasTags(e);if("why"in n)return n;const s=t.includes(CANVAS_DESIGN_TAG);if(!s&&n.tags.includes(CANVAS_DESIGN_TAG))return{why:`\xAB${CANVAS_DESIGN_TAG}\xBB is LensMCP's own label \u2014 the canvas a goal's design is drawn as; pick another`};const i=s&&!n.tags.includes(CANVAS_DESIGN_TAG)?[CANVAS_DESIGN_TAG,...n.tags]:n.tags;return i.length>CANVAS_TAG_LIMITS.count?{why:`a canvas has at most ${CANVAS_TAG_LIMITS.count} labels; got ${i.length}`}:{tags:i}}r(authoredCanvasTags,"authoredCanvasTags"),o(authoredCanvasTags,"authoredCanvasTags");export const CANVAS_LIMITS={mdxBytes:256*1024,mdxWholeBytes:64*1024,dataBytes:2*1024*1024,answerBytes:16*1024,questions:500,assets:h,assetBytes:d,assetFileBytes:A,canvasBytes:256*1024*1024,projectBytes:2*1024*1024*1024,titleChars:200,noteChars:2e3,commentChars:8e3,frameMessageBytes:256*1024,snapshotPartChars:96*1024,snapshotParts:96,depth:64,ops:1e3,checkpointEvery:50,checkpointsKept:20,waitDefaultMs:45e3,waitMaxMs:9e5},CANVAS_KINDS=["doc","decision","plan","review","report","dashboard","qa","template"],CANVAS_TEMPLATE_NAMES=["decision-record","plan-review","weekly-report","goal-dashboard","qa-report"],CANVAS_QUESTION_KINDS=["choice","multi","text","number","confirm","approve"],CANVAS_FIELD_KINDS=["text","number","date","file","image"],CANVAS_INTERACTIVE=["Question","Checklist","Field","Options"];export function canvasAnswerKeys(e){return e.kind==="checklist"?(e.items??[]).map(t=>`${e.qid}/${t.id}`):e.kind==="multi"?(e.options??[]).map(t=>`${e.qid}/${t.id}`):[e.qid]}r(canvasAnswerKeys,"canvasAnswerKeys"),o(canvasAnswerKeys,"canvasAnswerKeys");export const canvasQidOf=o(e=>e.split("/")[0]??e,"canvasQidOf"),CANVAS_SHAPE_KEYS=["type","properties","required","items","enum","minimum","maximum","minItems","maxItems","format","additionalProperties","description","derived","$schema","title"],CANVAS_DATA_OPS=["set","remove","move","copy","append"],CANVAS_HEALTH_STATES=["checked","good","broken","unverified"],CANVAS_ANSWER_VIAS=["document","rail","inbox","cli","api","host"],CANVAS_LEDGER_PARTS=["version","data","answer","got","grant","share","archive","delete","comment","health","meta","asset"],CANVAS_OUTSIDE={timeoutMs:1e4,maxBytes:2*1024*1024,redirects:5,perCanvasPerMinute:30,perOriginPerMinute:60,keptPerCanvas:20,keptBytesPerCanvas:8*1024*1024};export function canvasGrantWords(e){return`This canvas could send what it reads to ${e}, or anywhere.`}r(canvasGrantWords,"canvasGrantWords"),o(canvasGrantWords,"canvasGrantWords");export function canvasGrantPrompt(e){return{title:`Let this canvas read ${e}?`,lines:[canvasGrantWords(e),"A site a canvas may read is also a way out: the addresses its versions ask for can carry what its author knows, each read tells the site you opened the canvas, and the site can pass any of it on.","The dashboard fetches it, never the canvas: only the exact URLs a version declares, public addresses only, GET, no cookies, 10 s and 2 MB at most. Revoke it here at any time; the ledger records both."],act:`Approve ${e}`}}r(canvasGrantPrompt,"canvasGrantPrompt"),o(canvasGrantPrompt,"canvasGrantPrompt");export const CANVAS_BROKER_METHODS=["ui/initialize","ui/notifications/size-changed","ui/open-link","canvas/heartbeat","canvas/slots","canvas/focus","canvas/get","canvas/rendered","canvas/problem","canvas/health","canvas/data-changed","canvas/answers-changed","canvas/selection","canvas/copy","canvas/download","canvas/open-ref","canvas/slot-sizes","canvas/theme","canvas/escape","canvas/snapshot-asked","canvas/snapshot","canvas/print"],CANVAS_APP_MIME="text/html;profile=mcp-app",CANVAS_APP_URI_TEMPLATE="ui://canvas/{id}",canvasAppUri=o(e=>`ui://canvas/${e}`,"canvasAppUri"),CANVAS_APP_VIEW_URI="ui://canvas/view",CANVAS_ANSWER_TOOL="canvas_answer",CANVAS_APP_PROTOCOL=1;export function canvasConfirmedAnswers(e){const t=new Map;for(const s of e){if(!s.confirmed)continue;const i=t.get(s.key);(!i||s.seq>i.seq)&&t.set(s.key,s)}const n={};for(const[s,i]of t)i.state==="current"&&(n[s]=i.value);return n}r(canvasConfirmedAnswers,"canvasConfirmedAnswers"),o(canvasConfirmedAnswers,"canvasConfirmedAnswers");export function canvasFrameInit(e){const t=e.detail;return{protocol:CANVAS_FRAME_PROTOCOL,theme:e.theme,tokens:e.tokens,canvas:t.canvas.id,version:t.shown,code:e.code,compiler:e.compiler,contract:t.version.contract,bindings:t.version.bindings,data:t.data,marks:t.marks,answers:canvasConfirmedAnswers(t.answers),got:{},...e.anchor?{anchor:e.anchor}:{},fallback:e.fallback,dir:"auto"}}r(canvasFrameInit,"canvasFrameInit"),o(canvasFrameInit,"canvasFrameInit");const c=a.number(),v=a.object({qid:a.string().max(64),x:c,y:c,width:c.min(0).max(1e4),height:c.min(0).max(1e4),visible:a.boolean()}),l=a.object({message:a.string().max(4e3),block:a.string().max(200).optional(),line:a.number().int().min(0).max(1e6).optional(),column:a.number().int().min(0).max(1e5).optional(),component:a.string().max(100).optional()});export const CANVAS_FRAME_PARAMS={"ui/initialize":a.looseObject({protocol:a.number().int()}),"ui/notifications/size-changed":a.object({height:c.min(0).max(1e6),width:c.min(0).max(1e5).optional()}),"ui/open-link":a.object({url:a.string().max(4e3)}),"canvas/heartbeat":a.object({t:c}),"canvas/slots":a.object({slots:a.array(v).max(CANVAS_LIMITS.questions)}),"canvas/focus":a.object({qid:a.string().max(64)}),"canvas/get":a.object({uri:a.string().max(2e3)}),"canvas/rendered":a.object({ms:c.min(0),blocks:a.number().int().min(0),errors:a.number().int().min(0)}),"canvas/problem":a.object({errors:a.array(l).max(200)}),"canvas/health":a.object({ok:a.boolean(),errors:a.array(l).max(200)}),"canvas/selection":a.object({text:a.string().max(8e3),block:a.string().max(200).optional(),lines:a.tuple([a.number().int(),a.number().int()]).optional()}),"canvas/copy":a.object({text:a.string().max(1024*1024)}),"canvas/download":a.object({name:a.string().max(200),type:a.enum(["csv","json","png","txt","md"]),text:a.string().max(4*1024*1024)}),"canvas/open-ref":a.object({kind:a.enum(["task","goal","file","canvas"]),id:a.string().max(2e3),line:a.number().int().optional()}),"canvas/escape":a.object({}),"canvas/snapshot":a.object({n:a.number().int().min(0),part:a.number().int().min(0).max(CANVAS_LIMITS.snapshotParts-1),parts:a.number().int().min(1).max(CANVAS_LIMITS.snapshotParts),html:a.string().max(CANVAS_LIMITS.snapshotPartChars),dir:a.enum(["ltr","rtl","auto"]).optional()}),"canvas/print":a.object({})};export function canvasSlotHeight(e){if(e.component==="Options"&&e.kind==="choice")return 26+40*Math.ceil(Math.max(1,e.options?.length??0)/2);const t=40+(e.detail?20:0),n=44;switch(e.kind){case"choice":case"multi":return t+36*Math.max(1,e.options?.length??0)+n;case"checklist":return t+32*Math.max(1,e.items?.length??0);case"confirm":return t+n;case"approve":return t+72+n;case"text":return t+84+n;default:return t+40+n}}r(canvasSlotHeight,"canvasSlotHeight"),o(canvasSlotHeight,"canvasSlotHeight");export function canvasOptionLabel(e){return e.replace(/\s*[::]+\s*$/u,"")||e}r(canvasOptionLabel,"canvasOptionLabel"),o(canvasOptionLabel,"canvasOptionLabel");
|
package/lib/capture-demand.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var c=Object.defineProperty;var o=(t,e)=>c(t,"name",{value:e,configurable:!0});var s=Object.defineProperty,u=o((t,e)=>s(t,"name",{value:e,configurable:!0}),"s");export const CAPTURE_REQUEST_FILENAME="capture-request.json",CAPTURE_PRESENCE_FILENAME="capture-runner.json";export function appMatchesPage(t,e){const r=t.trim().toLowerCase();if(!r)return!1;if(e.project&&e.project.toLowerCase()===r)return!0;const n=e.url.toLowerCase();if(n===r||n.replace(/\/+$/,"")===r.replace(/\/+$/,""))return!0;try{const a=new URL(e.url);return/^\d+$/.test(r)?a.port===r:a.origin.toLowerCase()===r.replace(/\/+$/,"")}catch{return!1}}o(appMatchesPage,"appMatchesPage"),u(appMatchesPage,"appMatchesPage");export const CAPTURE_RULES_FILENAME="capture-rules.json";
|
package/lib/dashboard-path.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var o=Object.defineProperty;var c=(e,t)=>o(e,"name",{value:t,configurable:!0});var d=Object.defineProperty,n=c((e,t)=>d(e,"name",{value:t,configurable:!0}),"t");const a={"~":"~~","/":"~s","\\":"~b","\0":"~0"},p={"~":"~",s:"/",b:"\\",0:"\0",d:"."},g=/%2f|%5c|%2e|%00/i;export function encodeSegment(e){return e==="."||e===".."?e.replace(/\./g,"~d"):encodeURIComponent(e.replace(/[~/\\\0]/g,t=>a[t])).replace(/%3A/g,":").replace(/%40/g,"@")}c(encodeSegment,"encodeSegment"),n(encodeSegment,"encodeSegment");export function decodeSegment(e){let t;try{t=decodeURIComponent(e)}catch{t=e}return g.test(e)?t:t.replace(/~([~sb0d])/g,(l,r)=>p[r])}c(decodeSegment,"decodeSegment"),n(decodeSegment,"decodeSegment");
|