@lensmcp/protocol-types 1.26.12 → 1.26.13
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 +1 -0
- package/index.js +1 -1
- package/lib/accounts.d.ts +60 -0
- package/lib/accounts.js +1 -0
- package/lib/ai-cache-facts.js +1 -1
- package/lib/ai-cache-verdict.js +1 -1
- package/lib/ai-cache.js +3 -3
- package/lib/ai-call-groups.js +2 -2
- package/lib/ai-call-row.js +3 -3
- package/lib/ai-call.js +9 -9
- package/lib/ai-compare.js +3 -3
- package/lib/ai-context.js +6 -6
- package/lib/ai-origins.js +9 -9
- package/lib/ai-together.js +5 -5
- package/lib/bounded-clone.js +1 -1
- package/lib/bounded-map.js +1 -1
- package/lib/bounded-writer.js +1 -1
- package/lib/capture-demand.js +1 -1
- package/lib/dashboard-path.js +1 -1
- package/lib/docker-errors.js +1 -1
- package/lib/docker-jobs.js +1 -1
- package/lib/docker-report.js +2 -2
- package/lib/docker-runs.js +3 -3
- package/lib/error-cause.js +6 -6
- package/lib/error-dismissal.js +1 -1
- package/lib/error-verdict.js +3 -3
- package/lib/event-loop.js +1 -1
- package/lib/expected-failure.js +2 -2
- package/lib/finding-proof.js +1 -1
- package/lib/flood-guard.js +1 -1
- package/lib/goal-design.js +1 -1
- package/lib/host-agents.js +1 -1
- package/lib/lint-coverage.js +1 -1
- package/lib/log-query.js +1 -1
- package/lib/metrics-reset.js +1 -1
- package/lib/overseer-findings.js +1 -1
- package/lib/peers.d.ts +1 -1
- package/lib/peers.js +1 -1
- package/lib/perf-rules.js +1 -1
- package/lib/pod-memory.js +1 -1
- package/lib/producer-health.js +1 -1
- package/lib/remote-instances.js +1 -1
- package/lib/sessions.d.ts +17 -1
- package/lib/sources.js +1 -1
- package/lib/static-checks.js +1 -1
- package/lib/system-report.js +1 -1
- package/lib/team-design.d.ts +113 -3
- 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(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
|
-
`,
|
|
4
|
-
`,i);return
|
|
5
|
-
`).length,text:l(e),other:l(s)}}A(ge,"Oe"),$(ge,"lineDiff");export function aiSectionIdentity(e){if(e.length<2)return;const s=e[0],r=e.map(m=>aiRequestSections(m.request)),a=r.slice(1).map(m=>new Set(m.map(x=>x.text))),i=r[0].reduce((m,x)=>m+x.tokens,0),l=s.input!==void 0&&i>0?s.input/i:1;let f=1/0;for(const m of e.slice(1))f=Math.min(f,le(s.request,m.request).chars);let o=0,c=0,u=0;const n=new Map;for(const m of r[0]){const x=a.every(M=>M.has(m.text)),w=n.get(m.k)??{tokens:0,identical:0};w.tokens+=m.tokens*l,x&&(o+=m.tokens*l,u++,w.identical+=m.tokens*l,m.at+m.text.length<=f&&(c+=m.tokens*l)),n.set(m.k,w)}const d=i*l,p=$((m,x)=>x>0?Math.round(m/x*1e3)/1e3:0,"ratio");return{tokens:Math.round(o),of:Math.round(d),share:p(o,d),afterPrefix:Math.round(Math.max(0,o-c)),sections:u,ofSections:r[0].length,blocks:[...n].map(([m,x])=>{const w=s.request.blocks[m];let M;for(const B of e.slice(1)){const q=B.request.blocks[m],j=q&&q.label===w.label?ge(w.text,q.text):void 0;j&&(!M||j.at<M.at)&&(M={...j,id:B.id})}return{block:w.label,tokens:Math.round(x.tokens),identical:Math.round(x.identical),share:p(x.identical,x.tokens),...M?{line:M}:{}}}).filter(m=>m.tokens>0).sort((m,x)=>x.identical-m.identical||x.tokens-m.tokens)}}A(aiSectionIdentity,"aiSectionIdentity"),$(aiSectionIdentity,"aiSectionIdentity");function ce(e,s){const r=s.focus?e.find(n=>n.id===s.focus):void 0,a=new Set(e.map(n=>n.agent.key));if(s.levels===!1||!r&&a.size!==1)return[];const i=r?.agent.key??[...a][0],l=he(e.filter(n=>n.agent.key===i)),f=$(n=>n.slice(-MAX_LEVEL_RUNS),"newest"),o=[],c=$((n,d)=>{const p=new Map;for(const M of l){const B=d(M);if(!B)continue;const q=p.get(B);q?q.push(M):p.set(B,[M])}const m=[...p].filter(([,M])=>M.length>=2);if(!m.length)return;const x=r?d(r):void 0,w=m.find(([M])=>M===x)??[...m].sort((M,B)=>B[1].length-M[1].length||B[1][B[1].length-1].at-M[1][M[1].length-1].at)[0];o.push({level:n,key:w[0],members:f(w[1]),...m.length>1?{more:m.length-1}:{}})},"keyed");c("thread",n=>n.thread?.key),c("tenant",tenantOf),l.length>=2&&o.push({level:"all",members:f(l)});const u=$((n,d)=>n.members.length===d.members.length&&n.members.every((p,m)=>p.id===d.members[m].id),"same");return o.filter((n,d)=>!o.slice(0,d).some(p=>u(p,n)))}A(ce,"fe"),$(ce,"levelSets");function we(e,s){const r=e.members,a=r.map(aiCalibratedMarks),i=a.slice(1).map(c=>new Set(c.map(u=>u.h)));let l=-1;a[0].forEach((c,u)=>{i.every(n=>n.has(c.h))&&(l=u)});let f;if(l>=0){const c=a[0][l],u=a.map(w=>w.find(M=>M.h===c.h)??c),n=u.filter((w,M)=>W(r[M])),d=(n.length?n:u).map(w=>w.t),p=u.find(w=>w.exact)?.t,m=Math.min(...d),x=Math.max(...d);f={tokens:p??G(d),...p!==void 0?{exact:!0}:m!==x?{estimates:[m,x]}:{},endsIn:c.s,...a[0][l+1]?{partsIn:a[0][l+1].s}:{},breakpoint:u.some(w=>!!w.bp)}}const o={level:e.level,...e.key?{key:e.key}:{},runs:r.length,members:r.map(c=>c.id),...f?{prefix:f}:{},...e.more?{more:e.more}:{}};if(s){const c=r.filter(d=>s.get(d.id)?.request).map(d=>({id:d.id,request:s.get(d.id).request,input:d.tokens?.input})),u=aiSectionIdentity(c);u&&(o.identical=u);const n=ie(r,s);n&&(o.firstDiff=n)}return o}A(we,"Ie"),$(we,"level");export function aiTogether(e,s){const r=se(e),a=ne(r,s).map(o=>pe(o,s)),i=ce(e,s).map(o=>we(o,s.texts)),l=a.filter(o=>o.cost),f=l.filter(o=>o.cost.idealUsd!==void 0);return{groups:a,levels:i,totals:{groups:a.length,calls:a.reduce((o,c)=>o+c.calls.length,0),priced:l.length,actualUsd:T(f.reduce((o,c)=>o+c.cost.actualUsd,0)),idealUsd:T(f.reduce((o,c)=>o+c.cost.idealUsd,0)),gapUsd:T(f.reduce((o,c)=>o+c.cost.gapUsd,0)),races:a.reduce((o,c)=>o+c.cache.races,0),duplicates:a.reduce((o,c)=>o+c.cache.duplicates.length,0)}}}A(aiTogether,"aiTogether"),$(aiTogether,"aiTogether");const K=$(e=>`${Math.round(e*100)}%`,"pct"),ke=$(e=>e[0]===e[1]?y(e[0]):`${y(e[0])}\u2013${y(e[1])}`,"range");export function aiTogetherLines(e){const s=[],r=e.waves.map(n=>n.ids.length===1?e.calls.find(d=>d.id===n.ids[0])?.prewarm?"a prewarm":"1":`${n.ids.length} sent together`).join(", then "),a=e.tokens;s.push(`${e.calls.length} calls of ${e.scope.by} ${e.scope.key.replace(/^(?:run|flow|request):/,"")} in ${e.waves.length} wave${e.waves.length===1?"":"s"} (${r}), ${Z(e.ms)} from the first sent to the last answer`),s.push(`input ${y(a.input)} tokens over the ${e.counted} counted: ${y(a.read)} read from the cache, ${y(a.written)} written to it, ${y(a.plain)} plain; output ${y(a.output)}${a.reasoning?` (${y(a.reasoning)} reasoning)`:""}`);const i=e.cost;if(i){s.push(`input as billed \u2248 ${_(i.actualUsd)}: ${i.actual}`),i.idealUsd!==void 0&&(s.push(`ideal input \u2248 ${_(i.idealUsd)} (estimate \u2014 one write per shared prefix, the rest reads, each call's own tail plain): ${i.ideal}; gap \u2248 ${_(i.gapUsd??0)}`),i.prewarmUsd!==void 0&&s.push(`calls sent together reach that only once one write has finished \u2014 with a prewarm (P\xB7w + N\xB7P\xB7r) \u2248 ${_(i.prewarmUsd)}`)),i.left&&s.push(`left out of these sums: ${i.left.calls} call${i.left.calls===1?"":"s"} (${i.left.why})`);const n=i.rates.map(d=>`${d.model} input ${R(d.input)}, read ${d.cacheRead!==void 0?R(d.cacheRead):"as input"}, write ${d.ttl} ${d.write!==void 0?R(d.write):"as input"} per M \u2014 ${d.source??"no source"}${d.readAt?`, read ${d.readAt}`:""}${d.stale?", STALE":""}`);n.length&&s.push(`rates: ${n.join("; ")}`)}const l=e.calls.filter(n=>n.input!==void 0&&!n.failed).length;e.shared.forEach((n,d)=>{const p=n.estimates?` (by call ${ke(n.estimates)}: estimated)`:n.exact?" (the provider's count)":" (estimated)",m=d?` \u2014 ${n.exact?"":"\u2248 "}${y(n.endsAt)} from the start${p}`:p;s.push(`${n.calls===l?"all":n.calls} of its calls share ${d?"the next ":""}${n.exact?"":"\u2248 "}${y(n.tokens)} tokens, to the end of \xAB${n.endsIn}\xBB${m}${n.warm?"; already in the cache before the group":""}${n.partsIn?`; they part in \xAB${n.partsIn}\xBB`:""} \u2014 ${n.breakpoint?"a breakpoint ends it":"no breakpoint ends it: one belongs there"}`)}),e.firstDiff&&s.push(`where they part, to the line (${e.firstDiff.ids[0]} / ${e.firstDiff.ids[1]}), in \xAB${e.firstDiff.region}\xBB: \xAB${e.firstDiff.line??""}\xBB / \xAB${e.firstDiff.otherLine??""}\xBB`);const f=Object.entries(e.cache.verdicts);f.length&&s.push(`cache verdicts: ${f.sort((n,d)=>d[1]-n[1]).map(([n,d])=>`${ye[n]} \xD7${d}`).join(", ")}${e.cache.lostUsd?` \u2014 \u2248 ${_(e.cache.lostUsd)} lost`:""}${e.cache.prewarm?`; ${e.cache.prewarm} is a prewarm`:""}`);for(const n of e.cache.duplicates)s.push(` ${n.id} wrote the shared prefix again${n.race?` \u2014 a race: ${n.against??"the writer"} was still in flight`:n.against?` after ${n.against} had written it${n.inFlight===!1?" and ended \u2014 not a race":""}`:""}: ${n.arithmetic??y(n.tokens)}${n.usd!==void 0?` = ${_(n.usd)}`:""}${n.estimate?" (estimate)":""}`);const o=e.time;if(o.slowest){const n=o.slowest;s.push(`the slowest call ${n.id}: ${Z(n.ms)}${n.output!==void 0?`, ${y(n.output)} output tokens${n.reasoning?` (${y(n.reasoning)} reasoning)`:""}`:""}${n.perSecond!==void 0?` at ${n.perSecond} tokens a second`:""}${n.items!==void 0?`, ${n.items} items`:""} \u2014 the group waits for it`)}o.fastest&&s.push(`its fan-out's fastest ${o.fastest.id}: ${Z(o.fastest.ms)}${o.fastest.output!==void 0?`, ${y(o.fastest.output)} output tokens`:""}${o.fastest.items!==void 0?`, ${o.fastest.items} items`:""}${o.spread!==void 0?` \u2014 spread ${o.spread}\xD7`:""}${o.perSecond?`; output ${o.perSecond[0]}\u2013${o.perSecond[1]} tokens a second across its calls`:""}`),s.push(o.itemsLabelled?`items per call: ${e.calls.filter(n=>n.items!==void 0).map(n=>`${n.id} ${n.items}`).join(", ")}`:"items per call: the app labels none (metadata.items)");const c=e.answer;c&&(s.push(`the answer by field over ${c.answers} answer${c.answers===1?"":"s"} read (\u2248 ${y(c.tokens)} visible tokens, estimate): ${c.fields.slice(0,8).map(n=>`${n.field} ${K(n.share)} (${y(n.tokens)})`).join(", ")}`),c.rows&&s.push(` the largest repeated row kind ${c.rows.path}: ${y(c.rows.rows)} rows \u2248 ${y(c.rows.perRow)} tokens a row, ${K(c.rows.share)} of the answers`));const u=e.unquoted;return u&&s.push(u.candidates.length?`sections the answers never quote \u2014 candidates only (${u.measure}; untested as a measure), over ${u.answers} answers: ${u.candidates.map(n=>`\xAB${ue(n.section,70)}\xBB \u2248 ${y(n.tokens)} tokens in ${n.calls} call${n.calls===1?"":"s"}`).join("; ")}`:`every context section of ${de}+ tokens is quoted by some answer (${u.measure}; untested as a measure)`),s}A(aiTogetherLines,"aiTogetherLines"),$(aiTogetherLines,"aiTogetherLines");export function aiTogetherLevelLines(e){const s=[],r=e.level==="all"?`all its runs (the newest ${e.runs})`:`the ${e.runs} newest runs of ${e.level} ${e.key}${e.more?` (${e.more} other ${e.level}${e.more===1?"":"s"} of two runs or more)`:""}`;s.push(e.prefix?`${r}, one call each: they share ${e.prefix.exact?`${y(e.prefix.tokens)} tokens (the provider's count)`:`\u2248 ${y(e.prefix.tokens)} tokens (${e.prefix.estimates?`by run ${ke(e.prefix.estimates)}: `:""}estimated)`} to the end of \xAB${e.prefix.endsIn}\xBB${e.prefix.partsIn?`, and part in \xAB${e.prefix.partsIn}\xBB`:""} \u2014 ${e.prefix.breakpoint?"a breakpoint ends it":"no breakpoint ends it: one belongs there"}`:`${r}, one call each: they share no prefix the lens marks \u2014 they part in their first section`),e.firstDiff&&s.push(` first differing line (${e.firstDiff.ids[0]} / ${e.firstDiff.ids[1]}), in \xAB${e.firstDiff.region}\xBB: \xAB${e.firstDiff.line??""}\xBB / \xAB${e.firstDiff.otherLine??""}\xBB`);const a=e.identical;if(a){s.push(` identical in every run, wherever it sits: \u2248 ${y(a.tokens)} of ${y(a.of)} tokens (${K(a.share)}), ${a.sections} of ${a.ofSections} sections${a.afterPrefix?`; \u2248 ${y(a.afterPrefix)} of them after the first difference \u2014 a level a breakpoint reaches only once they are moved before it`:""} (estimate)`);for(const i of a.blocks.filter(l=>l.identical>0).slice(0,4))s.push(` \xAB${i.block}\xBB: ${K(i.share)} identical (\u2248 ${y(i.identical)} of ${y(i.tokens)} tokens)${i.line?`; its first differing line, line ${i.line.at}: \xAB${i.line.text}\xBB / \xAB${i.line.other}\xBB (${i.line.id})`:""}`)}return s}A(aiTogetherLevelLines,"aiTogetherLevelLines"),$(aiTogetherLevelLines,"aiTogetherLevelLines");
|
|
1
|
+
"use strict";var ve=Object.defineProperty;var S=(e,s)=>ve(e,"name",{value:s,configurable:!0});var be=Object.defineProperty,A=S((e,s)=>be(e,"name",{value:s,configurable:!0}),"A"),Me=Object.defineProperty,g=A((e,s)=>Me(e,"name",{value:s,configurable:!0}),"$");import{aiCacheDiff as ge,aiCacheSections as ye}from"./ai-cache.js";import{aiCacheMinTokens as Be}from"./ai-cache-facts.js";import{AI_CACHE_VERDICT_LABEL as Se}from"./ai-cache-verdict.js";import{estimateTokens as ne}from"./ai-context.js";export const FOLLOW_MS=1e3,MAX_LEVEL_RUNS=8;const $e=200,Ae=8,oe=4,qe=200,y=g(e=>Math.round(e).toLocaleString("en-US"),"fmt"),R=g(e=>`$${Number(e.toFixed(4))}`,"rate"),C=g(e=>`$${e<.01&&e>0?e.toFixed(4):e.toFixed(e<1?3:2)}`,"money"),E=g(e=>Math.round(e*1e6)/1e6,"usd"),V=g(e=>{const s=[...e].sort((a,r)=>a-r);return s.length?s[Math.floor((s.length-1)/2)]:0},"median"),re=g(e=>e<1e3?`${Math.round(e)} ms`:e<12e4?`${(e/1e3).toFixed(1)} s`:`${Math.round(e/1e3)} s`,"dur"),we=g((e,s=qe)=>e.length>s?`${e.slice(0,s-1)}\u2026`:e,"clip"),K=g(e=>e.at+(e.durationMs??0),"endOf"),ae=g((e,s)=>e.at-s.at||+!e.prewarm-+!s.prewarm||e.id.localeCompare(s.id),"byStart"),W=g(e=>e.tokens?.input!==void 0&&!e.failed,"counted"),Ue=["tenant","tenant_id","tenantId","business","business_id","businessId","org","org_id","orgId","organization","account","account_id","accountId","customer","customer_id","customerId"],De=["items","item_count","itemCount","n_items","batch_size","batchSize","rows","count"];export const tenantOf=g(e=>{for(const s of Ue)if(e.meta?.[s]?.trim())return e.meta[s].trim()},"tenantOf");const ie=g(e=>{for(const s of De){const a=e.meta?.[s];if(a!==void 0&&/^\d{1,6}$/.test(a.trim()))return Number(a.trim())}},"itemsOf");export function aiTogetherScopeOf(e){if(e.run.from!=="alone")return{by:"run",key:e.run.key};if(e.flowId)return{by:"flow",key:`flow:${e.flowId}`};if(e.requestId)return{by:"request",key:`request:${e.requestId}`}}S(aiTogetherScopeOf,"aiTogetherScopeOf"),A(aiTogetherScopeOf,"aiTogetherScopeOf"),g(aiTogetherScopeOf,"aiTogetherScopeOf");function Q(e){const s=new Map;for(const r of e){if(r.api==="embeddings")continue;const i=aiTogetherScopeOf(r);if(!i)continue;const l=`${r.agent.key}
|
|
2
|
+
${i.key}`,f=s.get(l);f?f.rows.push(r):s.set(l,{scope:i,rows:[r]})}const a=[];for(const{scope:r,rows:i}of s.values()){i.sort(ae);const l=[];for(const c of i){const u=l[l.length-1];u&&(c.at<u.end||c.at===u.at)?(u.rows.push(c),u.end=Math.max(u.end,K(c))):l.push({rows:[c],at:c.at,end:K(c)})}let f=[];const o=g(()=>{if(f.some(c=>c.rows.length>=2)){const c=f.flatMap(u=>u.rows);a.push({key:`${c[0].agent.key}|${r.key}|${c[0].id}`,scope:r,rows:c,waves:f.map(u=>u.rows)})}f=[]},"flush");for(const c of l){const u=f[f.length-1];u&&c.at-u.end>FOLLOW_MS&&o(),f.push(c)}o()}return a.sort((r,i)=>i.rows[0].at-r.rows[0].at||r.key.localeCompare(i.key))}S(Q,"se"),A(Q,"re"),g(Q,"groupsOf");function ce(e){const s=new Map;for(const a of e){if(a.api==="embeddings"||!a.cache?.marks?.length)continue;const r=aiTogetherScopeOf(a)?.key??`call:${a.id}`,i=s.get(r);i?i.push(a):s.set(r,[a])}return[...s.values()].map(a=>a.sort(ae).find(r=>!r.prewarm&&W(r))??a.find(r=>!r.prewarm)??a[0]).sort(ae)}S(ce,"he"),A(ce,"ye"),g(ce,"representatives");export function aiTogetherPlan(e,s={}){const a=Y(Q(e),s),r=te(e,s);return{groups:a.flatMap(i=>i.rows.map(l=>l.id)),members:[...new Set(r.flatMap(i=>i.members.map(l=>l.id)))]}}S(aiTogetherPlan,"aiTogetherPlan"),A(aiTogetherPlan,"aiTogetherPlan"),g(aiTogetherPlan,"aiTogetherPlan");function Y(e,s){return s.focus?e.filter(a=>a.rows.some(r=>r.id===s.focus)):s.maxGroups!==void 0?e.slice(0,s.maxGroups):e}S(Y,"ne"),A(Y,"ce"),g(Y,"pickGroups");export function aiCalibratedMarks(e){const s=e.cache?.marks??[],a=e.tokens?.input;if(!s.length||a===void 0||e.failed||e.cache?.mode!=="explicit")return s;const r=e.tokens?.cached??0,i=e.tokens?.written??0,l=s.filter(p=>p.bp),f=g((p,m)=>m.reduce((x,w)=>!x||Math.abs(w.t-p)<Math.abs(x.t-p)?w:x,void 0),"nearest"),o=[[0,0]],c=new Set;let u=l;if(r>0){const p=f(r,l);p&&(o.push([p.t,r]),c.add(p),u=l.filter(m=>m.t>p.t))}if(i>0){const p=f(r+i,u);p&&(o.push([p.t,r+i]),c.add(p))}const n=s[s.length-1].t;n>o[o.length-1][0]&&o.push([n,Math.max(a,o[o.length-1][1])]);const d=g(p=>{for(let w=1;w<o.length;w++){const[M,B]=o[w-1],[U,L]=o[w];if(p<=U)return U===M?L:Math.round(B+(p-M)/(U-M)*(L-B))}const[m,x]=o[o.length-1];return Math.round(x+(p-m))},"at");return s.map(p=>({...p,t:d(p.t),...c.has(p)?{exact:!0}:{}}))}S(aiCalibratedMarks,"aiCalibratedMarks"),A(aiCalibratedMarks,"aiCalibratedMarks"),g(aiCalibratedMarks,"aiCalibratedMarks");function le(e,s){return e.model?s(e.model,e.tokens?.input??0):void 0}S(le,"fe"),A(le,"be"),g(le,"ratesFor");const de=g((e,s)=>e.writes[s]??e.input,"writeRate");function ue(e,s){const a=e.rows,r=a[0],i=s.texts,l=r.at,f=Math.max(...a.map(K)),o=g(t=>a.reduce((h,$)=>h+(t($)??0),0),"sum"),c={input:o(t=>t.tokens?.input),read:o(t=>t.tokens?.cached),written:o(t=>t.tokens?.written),plain:o(t=>t.tokens?.input!==void 0?Math.max(0,t.tokens.input-(t.tokens.cached??0)-(t.tokens.written??0)):0),output:o(t=>t.tokens?.output),reasoning:o(t=>t.tokens?.reasoning)},u=a.map(t=>{const h=t.cache?.verdict,$=ie(t);return{id:t.id,at:t.at,...t.durationMs!==void 0?{ms:t.durationMs}:{},...t.prewarm?{prewarm:!0}:{},...t.failed?{failed:!0}:{},...t.tokens?.input!==void 0?{input:t.tokens.input}:{},...t.tokens?.cached?{read:t.tokens.cached}:{},...t.tokens?.written?{written:t.tokens.written}:{},...t.tokens?.output!==void 0?{output:t.tokens.output}:{},...t.tokens?.reasoning?{reasoning:t.tokens.reasoning}:{},...h?{verdict:h.kind,...h.race!==void 0?{race:h.race}:{}}:{},...$!==void 0?{items:$}:{}}}),n=a.filter(t=>W(t)&&t.cache?.marks?.length),d=n.map(aiCalibratedMarks),p=new Map,m=new Map;d.forEach((t,h)=>{for(const $ of t){const v=p.get($.h);v?v[v.length-1]!==h&&v.push(h):p.set($.h,[h]);const j=m.get($.h)??{ts:[]};j.ts.push($.t),$.exact&&(j.exact=$.t),m.set($.h,j)}});const x=g(t=>{const h=m.get(t);return h.exact??V(h.ts)},"one"),w=d.map(t=>t.map(h=>({...h,t:x(h.h)}))),M=new Set;if(n.length){const t=n[0],h=t.tokens?.cached??0,$=Math.max(256,(t.tokens?.input??0)*.03);if(h>0)for(const v of d[0])v.t<=h+$&&M.add(v.h)}const B=new Map;w.forEach((t,h)=>{let $=-1;for(let q=0;q<t.length;q++)(p.get(t[q].h)?.length??0)>=2&&($=q);let v=0;const j=g(q=>`${p.get(t[q].h).join(",")}${M.has(t[q].h)?"w":""}`,"setOf");for(let q=0;q<=$;q++){const T=t[q];if(q<$&&j(q)===j(q+1))continue;let G=B.get(T.h);G||(G={h:T.h,holders:p.get(T.h),s:T.s,...t[q+1]?{next:t[q+1].s}:{},bp:!1,warm:M.has(T.h),seg:new Map,end:new Map,estimates:m.get(T.h).ts,exact:m.get(T.h).exact!==void 0},B.set(T.h,G)),G.bp||=!!T.bp,G.seg.set(h,Math.max(0,T.t-v)),G.end.set(h,T.t),v=T.t}});const U=[...B.values()].sort((t,h)=>h.holders.length-t.holders.length||V([...t.end.values()])-V([...h.end.values()])).map(t=>{const h=Math.min(...t.estimates),$=Math.max(...t.estimates);return{calls:t.holders.length,ids:t.holders.map(v=>n[v].id),tokens:V([...t.seg.values()]),endsAt:V([...t.end.values()]),...t.exact?{exact:!0}:h!==$?{estimates:[h,$]}:{},endsIn:t.s,...t.next?{partsIn:t.next}:{},breakpoint:t.bp,...t.warm?{warm:!0}:{}}}),L=he(a,n,B,s.ratesOf,e.waves),P={};let N=0;const D=[];for(const t of a){const h=t.cache?.verdict;if(h){P[h.kind]=(P[h.kind]??0)+1,N+=h.lostUsd??0;for(const $ of h.costs)$.kind==="duplicate-write"&&D.push({id:t.id,race:!!h.race,...h.against?{against:h.against.id,inFlight:h.against.inFlight}:{},tokens:$.tokens,...$.usd!==void 0?{usd:$.usd}:{},...$.arithmetic?{arithmetic:$.arithmetic}:{},estimate:$.estimate})}}const H=a.find(t=>t.prewarm)?.id,z=g(t=>{const h=t.tokens?.output,$=ie(t);return{id:t.id,ms:t.durationMs,...h!==void 0?{output:h}:{},...t.tokens?.reasoning?{reasoning:t.tokens.reasoning}:{},...h!==void 0&&t.durationMs>0?{perSecond:Math.round(h/(t.durationMs/1e3)*10)/10}:{},...$!==void 0?{items:$}:{}}},"timed"),J=a.filter(t=>!t.prewarm&&!t.failed&&t.durationMs!==void 0),X=J.reduce((t,h)=>!t||h.durationMs>t.durationMs?h:t,void 0),k=e.waves.map(t=>t.filter(h=>J.includes(h))).reduce((t,h)=>h.length>t.length?h:t,[]),b=k.length>=2?k.reduce((t,h)=>h.durationMs<t.durationMs?h:t):void 0,I=k.length>=2?k.reduce((t,h)=>h.durationMs>t.durationMs?h:t):void 0,O=J.filter(t=>t.tokens?.output!==void 0&&t.durationMs>0).map(t=>t.tokens.output/(t.durationMs/1e3)),_=r.thread?.key,F={key:e.key,agent:{key:r.agent.key,name:r.agent.name},scope:e.scope,..._?{thread:_}:{},calls:u,waves:e.waves.map(t=>({ids:t.map(h=>h.id),at:t[0].at,ms:Math.max(...t.map(K))-t[0].at})),at:l,end:f,ms:f-l,tokens:c,counted:a.filter(W).length,...L?{cost:L}:{},shared:U,cache:{verdicts:P,lostUsd:E(N),races:D.filter(t=>t.race).length,duplicates:D,...H?{prewarm:H}:{}},time:{...X?{slowest:z(X)}:{},...b&&I?{fastest:z(b),...b.durationMs>0?{spread:Math.round(I.durationMs/b.durationMs*10)/10}:{}}:{},...O.length?{perSecond:[Math.round(Math.min(...O)*10)/10,Math.round(Math.max(...O)*10)/10]}:{},itemsLabelled:a.some(t=>ie(t)!==void 0)}};if(i){const t=aiAnswerFields(a.filter(v=>!v.prewarm).map(v=>({json:i.get(v.id)?.answer,visible:Ie(v)})));t&&(F.answer=t);const h=aiUnquotedSections(a.filter(v=>!v.prewarm).map(v=>({request:i.get(v.id)?.request,answer:i.get(v.id)?.answerText})));h&&(F.unquoted=h);const $=ee(a.filter(v=>!v.prewarm),i);$&&(F.firstDiff=$)}return F}S(ue,"pe"),A(ue,"ve"),g(ue,"group");const Ie=g(e=>e.tokens?.output!==void 0?Math.max(0,e.tokens.output-(e.tokens.reasoning??0)):void 0,"visibleOf");function he(e,s,a,r,i){const l=[],f=[];for(const k of e){if(!W(k)){l.push(k.failed?"failed":"no count");continue}const b=le(k,r);b?f.push({r:k,rates:b}):l.push("no price")}if(!f.length)return;let o=0,c=0,u=0;const n=new Map;for(const{r:k,rates:b}of f){const I=k.tokens.cached??0,O=k.tokens.written??0,_=Math.max(0,k.tokens.input-I-O),F=b.cacheRead??b.input;o+=I,c+=_;let t=0;const h=Object.entries(k.cache?.writes??{}).filter($=>typeof $[1]=="number"&&$[1]>0);if(h.length)for(const[$,v]of h){const j=de(b,$);n.set(j,(n.get(j)??0)+v),t+=v*j}else if(O){const $=de(b,k.cache?.ttl??"30m");n.set($,(n.get($)??0)+O),t+=O*$}u+=(I*F+t+_*b.input)/1e6}const d=f[0].rates,p=f.every(k=>k.rates===d||k.rates.input===d.input&&k.rates.cacheRead===d.cacheRead),m=p?`${y(o)} read \xD7 ${R(d.cacheRead??d.input)} + ${[...n].map(([k,b])=>`${y(b)} written \xD7 ${R(k)}`).join(" + ")||"0 written"} + ${y(c)} plain \xD7 ${R(d.input)}, per million = ${C(u)}`:`the provider's counts at each call's model's rates = ${C(u)}`,x=[];for(const{r:k,rates:b}of f){if(x.some(O=>O.model===k.model))continue;const I=k.cache?.ttl??"30m";x.push({model:k.model,input:b.input,...b.cacheRead!==void 0?{cacheRead:b.cacheRead}:{},...b.writes[I]!==void 0?{write:b.writes[I]}:{},ttl:I,...b.source?{source:b.source}:{},...b.readAt?{readAt:b.readAt}:{},...b.stale?{stale:!0}:{}})}const w=l.length?{calls:l.length,why:[...new Set(l)].join(", ")}:void 0,M={actualUsd:E(u),actual:m,estimate:!0,rates:x,...w?{left:w}:{}},B=new Map(s.map((k,b)=>[k.id,b]));if(!f.every(({r:k})=>B.has(k.id))){const k=f.filter(({r:b})=>!B.has(b.id)).length;return{...M,left:{calls:(w?.calls??0)+k,why:[w?.why,"no prefix marks (kept by a lens before 1.26.11)"].filter(Boolean).join(", ")}}}let U=0,L=0,P=0,N=0,D=0,H=0;const z=new Map;for(const{r:k,rates:b}of f){const I=B.get(k.id),O=b.input,_=b.cacheRead??O,F=Be(k.provider,k.model);let t=0;for(const $ of a.values()){const v=$.seg.get(I);if(v===void 0)continue;const j=$.end.get(I);if(t=Math.max(t,j),j<F)N+=v,D+=v*O/1e6;else if($.warm)P+=v,D+=v*_/1e6;else if($.holders[0]===I){const q=de(b,k.cache?.ttl??"30m");U+=v,z.set(q,(z.get(q)??0)+v),D+=v*q/1e6,H+=v*_/1e6}else L+=v,D+=v*_/1e6}const h=Math.max(0,k.tokens.input-t);N+=h,D+=h*O/1e6}const J=!e.some(k=>k.prewarm)&&i.some(k=>k.filter(b=>!b.prewarm).length>=2)&&U>0,X=p?`${P?`${y(P)} already cached, read \xD7 ${R(d.cacheRead??d.input)} + `:""}${[...z].map(([k,b])=>`${y(b)} written once \xD7 ${R(k)}`).join(" + ")||"0 written"} + ${y(L)} read \xD7 ${R(d.cacheRead??d.input)} + ${y(N)} each call's own, plain \xD7 ${R(d.input)}, per million = ${C(D)}`:`one write per shared prefix at each model's rates = ${C(D)}`;return{...M,idealUsd:E(D),ideal:X,gapUsd:E(E(u)-E(D)),...J?{prewarmUsd:E(D+H)}:{}}}S(he,"me"),A(he,"qe"),g(he,"costOf");const fe=g(e=>ne(JSON.stringify(e)??""),"jsonTokens");export function aiAnswerFields(e){const s=new Map,a=new Map;let r=0,i=0;for(const f of e){const o=f.json;if(!o||typeof o!="object")continue;i++;const c=Math.max(1,fe(o)),u=f.visible!==void 0&&f.visible>0?f.visible/c:1;r+=c*u;const n=Array.isArray(o)?{"[]":o}:o;for(const[p,m]of Object.entries(n))s.set(p,(s.get(p)??0)+(fe(m)+ne(p)+1)*u);const d=g((p,m)=>{if(Array.isArray(p)){const x=p.filter(w=>w&&typeof w=="object"&&!Array.isArray(w));if(x.length>=2){const w=a.get(`${m}[]`)??{rows:0,tokens:0};w.rows+=x.length,w.tokens+=x.reduce((M,B)=>M+fe(B),0)*u,a.set(`${m}[]`,w)}for(const w of p)d(w,`${m}[]`)}else if(p&&typeof p=="object")for(const[x,w]of Object.entries(p))d(w,m?`${m}.${x}`:x)},"walk");d(o,"")}if(!i||r<=0)return;const l=[...a].sort((f,o)=>o[1].tokens-f[1].tokens)[0];return{answers:i,tokens:Math.round(r),fields:[...s].sort((f,o)=>o[1]-f[1]).map(([f,o])=>({field:f,tokens:Math.round(o),share:Math.round(o/r*1e3)/1e3})),...l?{rows:{path:l[0],rows:l[1].rows,tokens:Math.round(l[1].tokens),perRow:Math.round(l[1].tokens/l[1].rows),share:Math.round(l[1].tokens/r*1e3)/1e3}}:{},estimate:!0}}S(aiAnswerFields,"aiAnswerFields"),A(aiAnswerFields,"aiAnswerFields"),g(aiAnswerFields,"aiAnswerFields");export function aiRequestSections(e){const s=[];let a=0;return e.blocks.forEach((r,i)=>{const l=ye(r.text),f=g((o,c,u)=>{const n=r.text.slice(o,c);n.trim()&&s.push({k:i,block:r.label,title:u,text:n,at:a+o,tokens:ne(n)*(r.weight??1)})},"push");l.length?(l[0].at>0&&f(0,l[0].at,`${r.label} \u203A (opening)`),l.forEach((o,c)=>f(o.at,l[c+1]?.at??r.text.length,`${r.label} \u203A ${o.title}`))):f(0,r.text.length,r.label),a+=r.text.length}),s}S(aiRequestSections,"aiRequestSections"),A(aiRequestSections,"aiRequestSections"),g(aiRequestSections,"aiRequestSections");const Oe=/^(?:instructions|tools|answer schema)/,ke=g(e=>e.toLowerCase().match(/[\p{L}\p{N}]+/gu)??[],"words");function Z(e){const s=new Set;for(let a=0;a+oe<=e.length;a++)s.add(e.slice(a,a+oe).join(" "));return s}S(Z,"re"),A(Z,"ue"),g(Z,"shinglesOf");export function aiUnquotedSections(e){const s=new Map;let a=0;for(const i of e){if(!i.request||!i.answer)continue;a++;const l=ke(i.answer),f=Z(l),o=new Set(l);for(const c of aiRequestSections(i.request)){if(Oe.test(c.block))continue;const u=ke(c.text),n=[...Z(u)].some(p=>f.has(p))||u.some(p=>p.length>=6&&/\d/.test(p)&&/\p{L}/u.test(p)&&o.has(p)),d=s.get(c.title)??{tokens:0,calls:0,quoted:0};d.tokens=Math.max(d.tokens,Math.round(c.tokens)),d.calls++,n&&d.quoted++,s.set(c.title,d)}}if(!a)return;const r=[...s].filter(([,i])=>!i.quoted&&i.tokens>=$e).sort((i,l)=>l[1].tokens-i[1].tokens).slice(0,Ae).map(([i,l])=>({section:i,tokens:l.tokens,calls:l.calls}));return{measure:`a run of ${oe} words, or an id-like word, of the section found in the answer`,untested:!0,answers:a,candidates:r}}S(aiUnquotedSections,"aiUnquotedSections"),A(aiUnquotedSections,"aiUnquotedSections"),g(aiUnquotedSections,"aiUnquotedSections");function ee(e,s){const a=e.filter(c=>s.get(c.id)?.request);if(a.length<2)return;const r=a[0],i=s.get(r.id).request;let l;for(const c of a.slice(1)){const u=ge(i,s.get(c.id).request,r.tokens?.input);u.same||(!l||u.chars<l.chars)&&(l={region:u.setting?`settings (${u.setting})`:u.region,...u.line!==void 0?{line:u.line}:{},...u.otherLine!==void 0?{otherLine:u.otherLine}:{},ids:[r.id,c.id],chars:u.chars})}if(!l)return;const{chars:f,...o}=l;return o}S(ee,"ie"),A(ee,"le"),g(ee,"firstDiffOf");function pe(e,s){if(e===s)return;let a=0;const r=Math.min(e.length,s.length);for(;a<r&&e.charCodeAt(a)===s.charCodeAt(a);)a++;const i=e.lastIndexOf(`
|
|
3
|
+
`,a-1)+1,l=g(f=>{const o=f.indexOf(`
|
|
4
|
+
`,i);return we(f.slice(i,o<0?f.length:o).trim())},"lineOf");return{at:e.slice(0,i).split(`
|
|
5
|
+
`).length,text:l(e),other:l(s)}}S(pe,"ge"),A(pe,"Oe"),g(pe,"lineDiff");export function aiSectionIdentity(e){if(e.length<2)return;const s=e[0],a=e.map(m=>aiRequestSections(m.request)),r=a.slice(1).map(m=>new Set(m.map(x=>x.text))),i=a[0].reduce((m,x)=>m+x.tokens,0),l=s.input!==void 0&&i>0?s.input/i:1;let f=1/0;for(const m of e.slice(1))f=Math.min(f,ge(s.request,m.request).chars);let o=0,c=0,u=0;const n=new Map;for(const m of a[0]){const x=r.every(M=>M.has(m.text)),w=n.get(m.k)??{tokens:0,identical:0};w.tokens+=m.tokens*l,x&&(o+=m.tokens*l,u++,w.identical+=m.tokens*l,m.at+m.text.length<=f&&(c+=m.tokens*l)),n.set(m.k,w)}const d=i*l,p=g((m,x)=>x>0?Math.round(m/x*1e3)/1e3:0,"ratio");return{tokens:Math.round(o),of:Math.round(d),share:p(o,d),afterPrefix:Math.round(Math.max(0,o-c)),sections:u,ofSections:a[0].length,blocks:[...n].map(([m,x])=>{const w=s.request.blocks[m];let M;for(const B of e.slice(1)){const U=B.request.blocks[m],L=U&&U.label===w.label?pe(w.text,U.text):void 0;L&&(!M||L.at<M.at)&&(M={...L,id:B.id})}return{block:w.label,tokens:Math.round(x.tokens),identical:Math.round(x.identical),share:p(x.identical,x.tokens),...M?{line:M}:{}}}).filter(m=>m.tokens>0).sort((m,x)=>x.identical-m.identical||x.tokens-m.tokens)}}S(aiSectionIdentity,"aiSectionIdentity"),A(aiSectionIdentity,"aiSectionIdentity"),g(aiSectionIdentity,"aiSectionIdentity");function te(e,s){const a=s.focus?e.find(n=>n.id===s.focus):void 0,r=new Set(e.map(n=>n.agent.key));if(s.levels===!1||!a&&r.size!==1)return[];const i=a?.agent.key??[...r][0],l=ce(e.filter(n=>n.agent.key===i)),f=g(n=>n.slice(-MAX_LEVEL_RUNS),"newest"),o=[],c=g((n,d)=>{const p=new Map;for(const M of l){const B=d(M);if(!B)continue;const U=p.get(B);U?U.push(M):p.set(B,[M])}const m=[...p].filter(([,M])=>M.length>=2);if(!m.length)return;const x=a?d(a):void 0,w=m.find(([M])=>M===x)??[...m].sort((M,B)=>B[1].length-M[1].length||B[1][B[1].length-1].at-M[1][M[1].length-1].at)[0];o.push({level:n,key:w[0],members:f(w[1]),...m.length>1?{more:m.length-1}:{}})},"keyed");c("thread",n=>n.thread?.key),c("tenant",tenantOf),l.length>=2&&o.push({level:"all",members:f(l)});const u=g((n,d)=>n.members.length===d.members.length&&n.members.every((p,m)=>p.id===d.members[m].id),"same");return o.filter((n,d)=>!o.slice(0,d).some(p=>u(p,n)))}S(te,"ce"),A(te,"fe"),g(te,"levelSets");function me(e,s){const a=e.members,r=a.map(aiCalibratedMarks),i=r.slice(1).map(c=>new Set(c.map(u=>u.h)));let l=-1;r[0].forEach((c,u)=>{i.every(n=>n.has(c.h))&&(l=u)});let f;if(l>=0){const c=r[0][l],u=r.map(w=>w.find(M=>M.h===c.h)??c),n=u.filter((w,M)=>W(a[M])),d=(n.length?n:u).map(w=>w.t),p=u.find(w=>w.exact)?.t,m=Math.min(...d),x=Math.max(...d);f={tokens:p??V(d),...p!==void 0?{exact:!0}:m!==x?{estimates:[m,x]}:{},endsIn:c.s,...r[0][l+1]?{partsIn:r[0][l+1].s}:{},breakpoint:u.some(w=>!!w.bp)}}const o={level:e.level,...e.key?{key:e.key}:{},runs:a.length,members:a.map(c=>c.id),...f?{prefix:f}:{},...e.more?{more:e.more}:{}};if(s){const c=a.filter(d=>s.get(d.id)?.request).map(d=>({id:d.id,request:s.get(d.id).request,input:d.tokens?.input})),u=aiSectionIdentity(c);u&&(o.identical=u);const n=ee(a,s);n&&(o.firstDiff=n)}return o}S(me,"we"),A(me,"Ie"),g(me,"level");export function aiTogether(e,s){const a=Q(e),r=Y(a,s).map(o=>ue(o,s)),i=te(e,s).map(o=>me(o,s.texts)),l=r.filter(o=>o.cost),f=l.filter(o=>o.cost.idealUsd!==void 0);return{groups:r,levels:i,totals:{groups:r.length,calls:r.reduce((o,c)=>o+c.calls.length,0),priced:l.length,actualUsd:E(f.reduce((o,c)=>o+c.cost.actualUsd,0)),idealUsd:E(f.reduce((o,c)=>o+c.cost.idealUsd,0)),gapUsd:E(f.reduce((o,c)=>o+c.cost.gapUsd,0)),races:r.reduce((o,c)=>o+c.cache.races,0),duplicates:r.reduce((o,c)=>o+c.cache.duplicates.length,0)}}}S(aiTogether,"aiTogether"),A(aiTogether,"aiTogether"),g(aiTogether,"aiTogether");const se=g(e=>`${Math.round(e*100)}%`,"pct"),xe=g(e=>e[0]===e[1]?y(e[0]):`${y(e[0])}\u2013${y(e[1])}`,"range");export function aiTogetherLines(e){const s=[],a=e.waves.map(n=>n.ids.length===1?e.calls.find(d=>d.id===n.ids[0])?.prewarm?"a prewarm":"1":`${n.ids.length} sent together`).join(", then "),r=e.tokens;s.push(`${e.calls.length} calls of ${e.scope.by} ${e.scope.key.replace(/^(?:run|flow|request):/,"")} in ${e.waves.length} wave${e.waves.length===1?"":"s"} (${a}), ${re(e.ms)} from the first sent to the last answer`),s.push(`input ${y(r.input)} tokens over the ${e.counted} counted: ${y(r.read)} read from the cache, ${y(r.written)} written to it, ${y(r.plain)} plain; output ${y(r.output)}${r.reasoning?` (${y(r.reasoning)} reasoning)`:""}`);const i=e.cost;if(i){s.push(`input as billed \u2248 ${C(i.actualUsd)}: ${i.actual}`),i.idealUsd!==void 0&&(s.push(`ideal input \u2248 ${C(i.idealUsd)} (estimate \u2014 one write per shared prefix, the rest reads, each call's own tail plain): ${i.ideal}; gap \u2248 ${C(i.gapUsd??0)}`),i.prewarmUsd!==void 0&&s.push(`calls sent together reach that only once one write has finished \u2014 with a prewarm (P\xB7w + N\xB7P\xB7r) \u2248 ${C(i.prewarmUsd)}`)),i.left&&s.push(`left out of these sums: ${i.left.calls} call${i.left.calls===1?"":"s"} (${i.left.why})`);const n=i.rates.map(d=>`${d.model} input ${R(d.input)}, read ${d.cacheRead!==void 0?R(d.cacheRead):"as input"}, write ${d.ttl} ${d.write!==void 0?R(d.write):"as input"} per M \u2014 ${d.source??"no source"}${d.readAt?`, read ${d.readAt}`:""}${d.stale?", STALE":""}`);n.length&&s.push(`rates: ${n.join("; ")}`)}const l=e.calls.filter(n=>n.input!==void 0&&!n.failed).length;e.shared.forEach((n,d)=>{const p=n.estimates?` (by call ${xe(n.estimates)}: estimated)`:n.exact?" (the provider's count)":" (estimated)",m=d?` \u2014 ${n.exact?"":"\u2248 "}${y(n.endsAt)} from the start${p}`:p;s.push(`${n.calls===l?"all":n.calls} of its calls share ${d?"the next ":""}${n.exact?"":"\u2248 "}${y(n.tokens)} tokens, to the end of \xAB${n.endsIn}\xBB${m}${n.warm?"; already in the cache before the group":""}${n.partsIn?`; they part in \xAB${n.partsIn}\xBB`:""} \u2014 ${n.breakpoint?"a breakpoint ends it":"no breakpoint ends it: one belongs there"}`)}),e.firstDiff&&s.push(`where they part, to the line (${e.firstDiff.ids[0]} / ${e.firstDiff.ids[1]}), in \xAB${e.firstDiff.region}\xBB: \xAB${e.firstDiff.line??""}\xBB / \xAB${e.firstDiff.otherLine??""}\xBB`);const f=Object.entries(e.cache.verdicts);f.length&&s.push(`cache verdicts: ${f.sort((n,d)=>d[1]-n[1]).map(([n,d])=>`${Se[n]} \xD7${d}`).join(", ")}${e.cache.lostUsd?` \u2014 \u2248 ${C(e.cache.lostUsd)} lost`:""}${e.cache.prewarm?`; ${e.cache.prewarm} is a prewarm`:""}`);for(const n of e.cache.duplicates)s.push(` ${n.id} wrote the shared prefix again${n.race?` \u2014 a race: ${n.against??"the writer"} was still in flight`:n.against?` after ${n.against} had written it${n.inFlight===!1?" and ended \u2014 not a race":""}`:""}: ${n.arithmetic??y(n.tokens)}${n.usd!==void 0?` = ${C(n.usd)}`:""}${n.estimate?" (estimate)":""}`);const o=e.time;if(o.slowest){const n=o.slowest;s.push(`the slowest call ${n.id}: ${re(n.ms)}${n.output!==void 0?`, ${y(n.output)} output tokens${n.reasoning?` (${y(n.reasoning)} reasoning)`:""}`:""}${n.perSecond!==void 0?` at ${n.perSecond} tokens a second`:""}${n.items!==void 0?`, ${n.items} items`:""} \u2014 the group waits for it`)}o.fastest&&s.push(`its fan-out's fastest ${o.fastest.id}: ${re(o.fastest.ms)}${o.fastest.output!==void 0?`, ${y(o.fastest.output)} output tokens`:""}${o.fastest.items!==void 0?`, ${o.fastest.items} items`:""}${o.spread!==void 0?` \u2014 spread ${o.spread}\xD7`:""}${o.perSecond?`; output ${o.perSecond[0]}\u2013${o.perSecond[1]} tokens a second across its calls`:""}`),s.push(o.itemsLabelled?`items per call: ${e.calls.filter(n=>n.items!==void 0).map(n=>`${n.id} ${n.items}`).join(", ")}`:"items per call: the app labels none (metadata.items)");const c=e.answer;c&&(s.push(`the answer by field over ${c.answers} answer${c.answers===1?"":"s"} read (\u2248 ${y(c.tokens)} visible tokens, estimate): ${c.fields.slice(0,8).map(n=>`${n.field} ${se(n.share)} (${y(n.tokens)})`).join(", ")}`),c.rows&&s.push(` the largest repeated row kind ${c.rows.path}: ${y(c.rows.rows)} rows \u2248 ${y(c.rows.perRow)} tokens a row, ${se(c.rows.share)} of the answers`));const u=e.unquoted;return u&&s.push(u.candidates.length?`sections the answers never quote \u2014 candidates only (${u.measure}; untested as a measure), over ${u.answers} answers: ${u.candidates.map(n=>`\xAB${we(n.section,70)}\xBB \u2248 ${y(n.tokens)} tokens in ${n.calls} call${n.calls===1?"":"s"}`).join("; ")}`:`every context section of ${$e}+ tokens is quoted by some answer (${u.measure}; untested as a measure)`),s}S(aiTogetherLines,"aiTogetherLines"),A(aiTogetherLines,"aiTogetherLines"),g(aiTogetherLines,"aiTogetherLines");export function aiTogetherLevelLines(e){const s=[],a=e.level==="all"?`all its runs (the newest ${e.runs})`:`the ${e.runs} newest runs of ${e.level} ${e.key}${e.more?` (${e.more} other ${e.level}${e.more===1?"":"s"} of two runs or more)`:""}`;s.push(e.prefix?`${a}, one call each: they share ${e.prefix.exact?`${y(e.prefix.tokens)} tokens (the provider's count)`:`\u2248 ${y(e.prefix.tokens)} tokens (${e.prefix.estimates?`by run ${xe(e.prefix.estimates)}: `:""}estimated)`} to the end of \xAB${e.prefix.endsIn}\xBB${e.prefix.partsIn?`, and part in \xAB${e.prefix.partsIn}\xBB`:""} \u2014 ${e.prefix.breakpoint?"a breakpoint ends it":"no breakpoint ends it: one belongs there"}`:`${a}, one call each: they share no prefix the lens marks \u2014 they part in their first section`),e.firstDiff&&s.push(` first differing line (${e.firstDiff.ids[0]} / ${e.firstDiff.ids[1]}), in \xAB${e.firstDiff.region}\xBB: \xAB${e.firstDiff.line??""}\xBB / \xAB${e.firstDiff.otherLine??""}\xBB`);const r=e.identical;if(r){s.push(` identical in every run, wherever it sits: \u2248 ${y(r.tokens)} of ${y(r.of)} tokens (${se(r.share)}), ${r.sections} of ${r.ofSections} sections${r.afterPrefix?`; \u2248 ${y(r.afterPrefix)} of them after the first difference \u2014 a level a breakpoint reaches only once they are moved before it`:""} (estimate)`);for(const i of r.blocks.filter(l=>l.identical>0).slice(0,4))s.push(` \xAB${i.block}\xBB: ${se(i.share)} identical (\u2248 ${y(i.identical)} of ${y(i.tokens)} tokens)${i.line?`; its first differing line, line ${i.line.at}: \xAB${i.line.text}\xBB / \xAB${i.line.other}\xBB (${i.line.id})`:""}`)}return s}S(aiTogetherLevelLines,"aiTogetherLevelLines"),A(aiTogetherLevelLines,"aiTogetherLevelLines"),g(aiTogetherLevelLines,"aiTogetherLevelLines");
|
package/lib/bounded-clone.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var T=Object.defineProperty;var
|
|
1
|
+
"use strict";var T=Object.defineProperty;var c=(t,e)=>T(t,"name",{value:e,configurable:!0});var h=Object.defineProperty,l=c((t,e)=>h(t,"name",{value:e,configurable:!0}),"i"),_=Object.defineProperty,y=l((t,e)=>_(t,"name",{value:e,configurable:!0}),"_");export const DEFAULT_RAW_BYTE_LIMIT=32768,DEFAULT_MAX_STRING_BYTES=4096,DEFAULT_MAX_ARRAY_ITEMS=64,DEFAULT_MAX_DEPTH=12,CHEAP_ENTRY_BYTES=512,NOMINAL_DEEP_BYTES=32,DEEP_REPORT_DEPTH=64,SKELETON_STRING_BYTES=256,MAX_RECORDED_PATHS=20,TRUNCATION_MARKER_KEY="__lensmcpTruncation",TRUNCATED_VALUE_KEY="__lensmcpTruncated";export function estimateJsonBytes(t,e=Number.POSITIVE_INFINITY,n=12){return g(t,e,n,32)}c(estimateJsonBytes,"estimateJsonBytes"),l(estimateJsonBytes,"estimateJsonBytes"),y(estimateJsonBytes,"estimateJsonBytes");export function exceedsJsonByteBudget(t,e,n=12){return g(t,e,n,Number.POSITIVE_INFINITY)>e}c(exceedsJsonByteBudget,"exceedsJsonByteBudget"),l(exceedsJsonByteBudget,"exceedsJsonByteBudget"),y(exceedsJsonByteBudget,"exceedsJsonByteBudget");function g(t,e,n,a){switch(typeof t){case"undefined":case"function":case"symbol":return 0;case"boolean":return 5;case"number":return Number.isFinite(t)?8:4;case"bigint":return 20;case"string":return t.length+2;default:break}if(t===null)return 4;if(n<=0)return a;if(t instanceof Date)return 26;if(Array.isArray(t)){let r=2;for(let u=0;u<t.length;u++)if(r+=g(t[u],e-r,n-1,a)+1,r>e)return r;return r}let s=2;const o=t;for(const r in o){if(!Object.prototype.hasOwnProperty.call(o,r))continue;const u=g(o[r],e-s,n-1,a);if(u!==0&&(s+=r.length+4+u,s>e))return s}return s}c(g,"y"),l(g,"T"),y(g,"walk");function f(t,e){t.truncatedAnything=!0,t.paths.length<20&&t.paths.push(e||"<root>")}c(f,"g"),l(f,"A"),y(f,"record");function p(t,e,n){return f(t,n),{[TRUNCATED_VALUE_KEY]:!0,originalBytes:estimateJsonBytes(e,Number.POSITIVE_INFINITY,64)}}c(p,"f"),l(p,"I"),y(p,"stub");function m(t){if(t===null)return!0;const e=typeof t;return e==="number"||e==="boolean"||e==="string"||e==="bigint"}c(m,"p"),l(m,"y"),y(m,"isScalar");export function clampValue(t,e,n,a){if(typeof t=="string"){const s=e.budget<=0?256:e.maxStringBytes;if(t.length+2<=s)return e.budget-=t.length+2,t;const o=Math.max(0,s-64);return f(e,a),e.budget-=o,`${t.slice(0,o)}\u2026[lensmcp truncated: ${t.length-o} more chars]`}return t===null||typeof t!="object"?(e.budget-=g(t,Number.POSITIVE_INFINITY,1,32),t):n<=0?p(e,t,a):t instanceof Date?(e.budget-=26,t):Array.isArray(t)?b(t,e,n,a):d(t,e,n,a)}c(clampValue,"clampValue"),l(clampValue,"clampValue"),y(clampValue,"clampValue");function b(t,e,n,a){const s=[],o=Math.min(t.length,e.maxArrayItems);for(let r=0;r<o&&!(e.budget<=0);r++)s.push(clampValue(t[r],e,n-1,`${a}[${r}]`));return s.length<t.length&&f(e,`${a}[] (+${t.length-s.length} items dropped)`),s}c(b,"m"),l(b,"f"),y(b,"clampArray");function d(t,e,n,a){const s={};let o;const r=e.budget<=0;for(const u in t){if(!Object.prototype.hasOwnProperty.call(t,u))continue;const i=t[u],I=g(i,512,n-1,Number.POSITIVE_INFINITY);if(I<=512&&(!r||m(i))){s[u]=i,e.budget-=u.length+4+I;continue}(o??=[]).push({key:u,bytes:I})}if(!o)return s;o.sort((u,i)=>u.bytes===i.bytes?0:u.bytes<i.bytes?-1:1);for(const{key:u}of o){const i=a?`${a}.${u}`:u;s[u]=clampValue(t[u],e,n-1,i)}return s}c(d,"b"),l(d,"m"),y(d,"clampObject");export function boundedClone(t,e={}){const n=e.rawByteLimit??32768,a=e.maxDepth??12;if(n<=0)return{value:void 0,truncated:!1,originalBytes:0,keptBytes:0,paths:[]};if(t==null)return{value:t,truncated:!1,originalBytes:0,keptBytes:0,paths:[]};if(!exceedsJsonByteBudget(t,n,a)){const i=estimateJsonBytes(t,n,a),I={budget:n,maxStringBytes:e.maxStringBytes??4096,maxArrayItems:e.maxArrayItems??64,paths:[],truncatedAnything:!1};return{value:clampValue(t,I,a,""),truncated:!1,originalBytes:i,keptBytes:i,paths:[]}}const s=estimateJsonBytes(t,Number.POSITIVE_INFINITY,64),o={budget:n,maxStringBytes:e.maxStringBytes??4096,maxArrayItems:e.maxArrayItems??64,paths:[],truncatedAnything:!1},r=clampValue(t,o,a,""),u=estimateJsonBytes(r,Number.POSITIVE_INFINITY,a);if(o.truncatedAnything&&r!==null&&typeof r=="object"&&!Array.isArray(r)){const i={truncated:!0,originalBytes:s,keptBytes:u,paths:o.paths};r[TRUNCATION_MARKER_KEY]=i}return{value:r,truncated:o.truncatedAnything,originalBytes:s,keptBytes:u,paths:o.paths}}c(boundedClone,"boundedClone"),l(boundedClone,"boundedClone"),y(boundedClone,"boundedClone");
|
package/lib/bounded-map.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var i=Object.defineProperty;var t=(e,a)=>i(e,"name",{value:a,configurable:!0});var p=Object.defineProperty,o=t((e,a)=>p(e,"name",{value:a,configurable:!0}),"t"),s=Object.defineProperty,u=o((e,a)=>s(e,"name",{value:a,configurable:!0}),"o");export function capMap(e,a){if(e.size<=a)return 0;let r=0;const c=e.keys();for(;e.size>a;){const n=c.next();if(n.done)break;e.delete(n.value)&&(r+=1)}return r}t(capMap,"capMap"),o(capMap,"capMap"),u(capMap,"capMap");export const MAX_PRODUCER_KEYS=256;
|
package/lib/bounded-writer.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var m=Object.defineProperty;var r=(t,e)=>m(t,"name",{value:e,configurable:!0});var f=Object.defineProperty,o=r((t,e)=>f(t,"name",{value:e,configurable:!0}),"r"),x=Object.defineProperty,s=o((t,e)=>x(t,"name",{value:e,configurable:!0}),"c");import{renameSync as v,statSync as M,unlinkSync as E}from"node:fs";export function eventMaxBytes(t=process.env){const e=Number(t.LENSMCP_EVENT_MAX_BYTES);return Number.isFinite(e)&&e>0?e:50*1024*1024}r(eventMaxBytes,"eventMaxBytes"),o(eventMaxBytes,"eventMaxBytes"),s(eventMaxBytes,"eventMaxBytes");export function eventMaxFiles(t=process.env){const e=Number(t.LENSMCP_EVENT_MAX_FILES);return Number.isFinite(e)&&e>=1&&e<=20?Math.floor(e):5}r(eventMaxFiles,"eventMaxFiles"),o(eventMaxFiles,"eventMaxFiles"),s(eventMaxFiles,"eventMaxFiles");const b=1024*1024,a=new Map;export function maybeRotateEventFile(t,e,c){const i=(a.get(t)??0)+e,l=c?.maxBytes??eventMaxBytes(),u=c?.maxFiles??eventMaxFiles(),y=Math.min(b,l);if(i<y){a.set(t,i);return}try{const n=M(t).size;if(a.set(t,0),n<=l)return}catch{a.set(t,i);return}try{E(`${t}.${u}`)}catch{}for(let n=u-1;n>=1;n--)try{v(`${t}.${n}`,`${t}.${n+1}`)}catch{}try{v(t,`${t}.1`)}catch{}}r(maybeRotateEventFile,"maybeRotateEventFile"),o(maybeRotateEventFile,"maybeRotateEventFile"),s(maybeRotateEventFile,"maybeRotateEventFile");export function resetRotationThrottle(t){t===void 0?a.clear():a.delete(t)}r(resetRotationThrottle,"resetRotationThrottle"),o(resetRotationThrottle,"resetRotationThrottle"),s(resetRotationThrottle,"resetRotationThrottle");
|
package/lib/capture-demand.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var s=Object.defineProperty;var a=(r,e)=>s(r,"name",{value:e,configurable:!0});var p=Object.defineProperty,c=a((r,e)=>p(r,"name",{value:e,configurable:!0}),"o"),u=Object.defineProperty,E=c((r,e)=>u(r,"name",{value:e,configurable:!0}),"s");export const CAPTURE_REQUEST_FILENAME="capture-request.json",CAPTURE_PRESENCE_FILENAME="capture-runner.json";export function appMatchesPage(r,e){const t=r.trim().toLowerCase();if(!t)return!1;if(e.project&&e.project.toLowerCase()===t)return!0;const o=e.url.toLowerCase();if(o===t||o.replace(/\/+$/,"")===t.replace(/\/+$/,""))return!0;try{const n=new URL(e.url);return/^\d+$/.test(t)?n.port===t:n.origin.toLowerCase()===t.replace(/\/+$/,"")}catch{return!1}}a(appMatchesPage,"appMatchesPage"),c(appMatchesPage,"appMatchesPage"),E(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 d=Object.defineProperty;var t=(e,n)=>d(e,"name",{value:n,configurable:!0});var a=Object.defineProperty,c=t((e,n)=>a(e,"name",{value:n,configurable:!0}),"c"),g=Object.defineProperty,o=c((e,n)=>g(e,"name",{value:n,configurable:!0}),"t");const p={"~":"~~","/":"~s","\\":"~b","\0":"~0"},l={"~":"~",s:"/",b:"\\",0:"\0",d:"."},m=/%2f|%5c|%2e|%00/i;export function encodeSegment(e){return e==="."||e===".."?e.replace(/\./g,"~d"):encodeURIComponent(e.replace(/[~/\\\0]/g,n=>p[n])).replace(/%3A/g,":").replace(/%40/g,"@")}t(encodeSegment,"encodeSegment"),c(encodeSegment,"encodeSegment"),o(encodeSegment,"encodeSegment");export function decodeSegment(e){let n;try{n=decodeURIComponent(e)}catch{n=e}return m.test(e)?n:n.replace(/~([~sb0d])/g,(u,r)=>l[r])}t(decodeSegment,"decodeSegment"),c(decodeSegment,"decodeSegment"),o(decodeSegment,"decodeSegment");
|
package/lib/docker-errors.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var O=Object.defineProperty;var m=(e,o)=>O(e,"name",{value:o,configurable:!0});var B=Object.defineProperty,b=m((e,o)=>B(e,"name",{value:o,configurable:!0}),"m"),I=Object.defineProperty,c=b((e,o)=>I(e,"name",{value:o,configurable:!0}),"c");import{CONTAINER_OOM as k,DOCKER_ENGINE_LOST as g,DOCKER_RUN_FIELD as N}from"./docker-jobs.js";import{joinId as E}from"./error-cause.js";const _=200,f=50,$=c(e=>typeof e=="object"&&e!==null&&!Array.isArray(e),"isObj"),h=c(e=>{if(typeof e!="string")return;const o=e.trim();return o?o.slice(0,_):void 0},"name"),p=c(e=>typeof e=="number"&&Number.isFinite(e)&&e>0?e:void 0,"someMb"),C=c(e=>typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0,"anyMb"),w=c(e=>Object.fromEntries(Object.entries(e).filter(([,o])=>o!==void 0)),"defined"),D=c(e=>{if(!$(e))return;const o=h(e.peer);if(!o)return;const n=h(e.name);return n?{peer:o,name:n}:{peer:o}},"hostOf"),M=c(e=>e.name??e.peer,"hostWord");export function readDockerError(e){if($(e)){if(e.kind===k)return w({kind:k,run:h(e.run),job:h(e.job),service:h(e.service),container:h(e.container),seen:e.seen==="event"||e.seen==="inspect"?e.seen:void 0,limitMb:p(e.limitMb),peakMb:p(e.peakMb),budgetMb:p(e.budgetMb),context:h(e.context),host:D(e.host)});if(e.kind===g){const o=new Map;for(const r of Array.isArray(e.runs)?e.runs:[]){const i=$(r)?h(r.run):h(r),t=$(r)?h(r.job):void 0;i&&!o.has(i)&&o.size<f&&o.set(i,{run:i,...t?{job:t}:{}})}const n=Array.isArray(e.killed)?[...new Set(e.killed.map(h).filter(r=>!!r))].slice(0,f):[];return w({kind:g,context:h(e.context),runs:[...o.values()],why:h(e.why),vmTotalMb:p(e.vmTotalMb),vmAvailableMb:C(e.vmAvailableMb),killed:n.length?n:void 0,host:D(e.host)})}}}m(readDockerError,"readDockerError"),b(readDockerError,"readDockerError"),c(readDockerError,"readDockerError");export function dockerErrorRuns(e){return e.kind===k?e.run?[e.run]:[]:e.runs.map(o=>o.run)}m(dockerErrorRuns,"dockerErrorRuns"),b(dockerErrorRuns,"dockerErrorRuns"),c(dockerErrorRuns,"dockerErrorRuns");export function dockerRunOfEvent(e){return $(e)?h(e[N]):void 0}m(dockerRunOfEvent,"dockerRunOfEvent"),b(dockerRunOfEvent,"dockerRunOfEvent"),c(dockerRunOfEvent,"dockerRunOfEvent");export const CONTAINER_OOM_ERROR="ContainerOOMKilled",DOCKER_ENGINE_LOST_ERROR="DockerEngineLost";const L=256,a=c(e=>`${Math.round(e)} MiB`,"mib");function x(e){const o=`${e.service??"a container"} ran out of memory in ${e.job??"a Docker job"}`,n=`${e.service?`\xAB${e.service}\xBB`:"A container"} ran out of memory and was killed, in ${e.job?`the Docker job \xAB${e.job}\xBB`:"a Docker job"}${e.host?` on the worker \xAB${M(e.host)}\xBB`:""}`,r=e.job?`\`${e.budgetMb!==void 0&&e.service?`jobs.${e.job}.budget.services.${e.service}`:`jobs.${e.job}.budget`}\` in lensmcp.json`:"its job's budget in lensmcp.json \u2192 jobs",{limitMb:i,peakMb:t,budgetMb:s}=e;let l;if(i!==void 0&&s!==void 0){const d=Math.round(i)-Math.round(s);l=d>0?`It was killed at its ${a(i)} limit \u2014 ${a(d)} over the ${a(s)} it declares. Raise ${r} to what it takes (more than ${a(i)}), and the container's memory limit with it.`:d===0?`It was killed at its ${a(i)} limit, which is all it declares. Raise ${r} to what it takes, and the container's memory limit with it.`:`It was killed at its ${a(i)} limit, ${a(-d)} under the ${a(s)} it declares. Raise the container's memory limit to its budget (${r}) \u2014 and both, if it takes more.`}else if(i!==void 0)l=`It was killed at its ${a(i)} limit. Raise the limit, and ${r}, to what it takes.`;else if(t!==void 0&&s!==void 0){const d=Math.round(t)-Math.round(s);l=d>0?`It held ${a(t)} at its peak \u2014 ${a(d)} over the ${a(s)} it declares. Raise ${r} to what it takes, so the queue lets the job in only when Docker's VM has that much.`:`It held ${a(t)} at its peak, within the ${a(s)} it declares (${r}): it was killed at a lower limit of its own, or when Docker's VM ran out. Check its memory limit in the compose file, and what else the VM held.`}else t!==void 0?l=`It held ${a(t)} at its peak. Check ${r} against that, and the container's memory limit.`:s!==void 0?l=`Its peak was not sampled. It declares ${a(s)}: raise ${r} to what it takes, and the container's memory limit with it.`:l=`Raise ${r} to what the service takes, and the container's memory limit with it.`;const u=[i!==void 0?`killed at its ${a(i)} limit`:"killed for memory",t!==void 0?`peak ${a(t)}`:void 0,s!==void 0?`budget ${a(s)}`:void 0,e.run?`run ${e.run}`:void 0,e.seen==="inspect"?"found by the inspect at the run's end":void 0,e.host?`on the worker ${M(e.host)}`:void 0,e.context?`Docker context ${e.context}`:void 0];return{cause:{id:E("cause",[CONTAINER_OOM_ERROR,e.job,e.service]),errorName:CONTAINER_OOM_ERROR,message:o},title:`${CONTAINER_OOM_ERROR}: ${o}`,headline:n,hint:l,facts:u.filter(Boolean).join(" \xB7 "),where:e.job?`Docker job ${e.job}`:"Docker"}}m(x,"y"),b(x,"A"),c(x,"oomWords");function y(e){const o=e.host?` on the worker ${M(e.host)}`:"",n=`Docker stopped answering${e.context?` (context ${e.context})`:""}${o}`,r=[...new Set(e.runs.map(v=>v.job).filter(v=>!!v))],i=e.runs.length,t=e.host?`Docker on the worker \xAB${M(e.host)}\xBB`:"Docker",s=i===0?`${t} stopped answering while LensMCP ran work in it`:i===1?`${t} stopped answering while ${r[0]?`the job \xAB${r[0]}\xBB`:"a job"} ran: its containers went with it`:`${t} stopped answering while ${i} runs were in it${r.length?` (${r.map(v=>`\xAB${v}\xBB`).join(", ")})`:""}: their containers went with it`,{vmTotalMb:l,vmAvailableMb:u}=e,d=u===void 0?void 0:`${a(u)} free${l!==void 0?` of ${a(l)}`:""}`,j=u===void 0?"If nobody stopped it, its VM most likely ran out of memory: compare the jobs' budgets in lensmcp.json with what Docker's VM has.":u<=L?`Its VM had ${d} when it was last read: it most likely ran out of memory. Let less in at once (the jobs' budgets in lensmcp.json decide), or give Docker's VM more.`:`Its VM had ${d} when it was last read, so memory is not the likely reason: was Docker stopped or restarted?`,A=[i?`${i} run${i===1?"":"s"} lost: ${e.runs.map(v=>`${v.job??"a job"} (run ${v.run})`).join(", ")}`:void 0,e.why,d?`VM ${d}`:void 0,e.killed?.length?`killed for memory before it went: ${e.killed.join(", ")}`:void 0];return{cause:{id:E("cause",e.host?[DOCKER_ENGINE_LOST_ERROR,e.context,e.host.peer]:[DOCKER_ENGINE_LOST_ERROR,e.context]),errorName:DOCKER_ENGINE_LOST_ERROR,message:n},title:`${DOCKER_ENGINE_LOST_ERROR}: ${n}`,headline:s,hint:`Start Docker again${o} and run ${i>1?"the jobs":"the job"} again: a run lost with the engine has no result. ${j}`,facts:A.filter(Boolean).join(" \xB7 "),where:`${e.context?`Docker context ${e.context}`:"Docker"}${o}`}}m(y,"E"),b(y,"I"),c(y,"engineWords");export function dockerErrorWords(e){return e.kind===k?x(e):y(e)}m(dockerErrorWords,"dockerErrorWords"),b(dockerErrorWords,"dockerErrorWords"),c(dockerErrorWords,"dockerErrorWords");export function mergeDockerError(e,o){if(e.kind===k){if(o.kind!==k)return e;const t=Math.max(e.peakMb??0,o.peakMb??0);return w({...o,...e,seen:e.seen==="event"||o.seen==="event"?"event":e.seen??o.seen,peakMb:t>0?t:void 0})}const n=e;if(o.kind===k)return o.service&&!n.killed?.includes(o.service)?{...n,killed:[...n.killed??[],o.service].slice(0,f)}:e;const r=new Map(n.runs.map(t=>[t.run,t]));for(const t of o.runs)(!r.has(t.run)||!r.get(t.run).job&&t.job)&&r.set(t.run,t);const i=[...new Set([...n.killed??[],...o.killed??[]])];return w({...o,...n,runs:[...r.values()].slice(0,f),vmAvailableMb:n.vmAvailableMb!==void 0&&o.vmAvailableMb!==void 0?Math.min(n.vmAvailableMb,o.vmAvailableMb):n.vmAvailableMb??o.vmAvailableMb,killed:i.length?i:void 0})}m(mergeDockerError,"mergeDockerError"),b(mergeDockerError,"mergeDockerError"),c(mergeDockerError,"mergeDockerError");export const DOCKER_ENGINE_LOSS_SAME_MS=6e4;const R=2e3,S=200;export class DockerErrorLedger{static{m(this,"DockerErrorLedger")}static{b(this,"DockerErrorLedger")}static{c(this,"DockerErrorLedger")}constructor(){this.kills=new Map,this.losses=new Map,this.lostRuns=new Map}account(o,n,r){if(o.kind===g){const l=o.host?`${o.host.peer}\0${o.context??""}`:o.context??"",u=this.losses.get(l),d=u&&Math.abs(r-u.at)<=DOCKER_ENGINE_LOSS_SAME_MS?u.told:void 0;d||this.remember(this.losses,l,{told:n,at:r},S);for(const j of o.runs)this.remember(this.lostRuns,j.run,d??n,R);return d}const i=o.seen!=="inspect",t=o.run&&o.container?`${o.run}\0${o.container}`:o.run&&o.service?`${o.run}\0\0${o.service}`:void 0,s=t?this.kills.get(t):void 0;if(!s){const l=!i&&o.run?this.lostRuns.get(o.run):void 0;if(l)return l;t&&this.remember(this.kills,t,{told:n,live:i?1:0},R);return}if(!i)return s.told;if(s.live===0)return s.live=1,s.told;s.live+=1,s.told=n}remember(o,n,r,i){o.delete(n),o.set(n,r),o.size>i&&o.delete(o.keys().next().value)}}
|
package/lib/docker-jobs.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var R=Object.defineProperty;var i=(e,s)=>R(e,"name",{value:s,configurable:!0});var w=Object.defineProperty,n=i((e,s)=>w(e,"name",{value:s,configurable:!0}),"s");export const DOCKER_LABELS={run:"com.lensmcp.run",home:"com.lensmcp.home",job:"com.lensmcp.job",probe:"com.lensmcp.probe"},LENS_JOB_KINDS=["compose","testcontainers","playwright"];export function neverShipped(e){const s=(e.split("/").at(-1)??"").toLowerCase();return s===".env"||s===".env.local"||/^\.env\..+\.local$/.test(s)}i(neverShipped,"neverShipped"),n(neverShipped,"neverShipped");export const jobInputFiles=n(e=>[...new Set(e.inputs?.files??[])].sort(),"jobInputFiles"),jobMintedFiles=n(e=>[...new Set(e.inputs?.minted??[])].sort(),"jobMintedFiles"),DEFAULT_LINK_LOSS_MINUTES=15,jobProblemText=n(e=>e.job===void 0?e.problem:`jobs.${e.job}: ${e.problem}`,"jobProblemText");const M=["kind","lane","prepare","command","cleanup","report","artifacts","inputs","timeoutMinutes","retryable","onLinkLoss","nx","budget"],$={compose:[...M,"compose"],testcontainers:M,playwright:[...M,"stack"]},L={compose:["services","buildMb","hostMb"],testcontainers:["vmMb","hostMb"],playwright:["hostMb","vmMb"]},_=/^[A-Za-z0-9][A-Za-z0-9._-]{0,62}$/,N=/^[A-Za-z0-9][A-Za-z0-9._-]*$/,k=1024*1024,f=360,b=100,x=4e3,l=n(e=>typeof e=="object"&&e!==null&&!Array.isArray(e),"isObj"),E=n(e=>typeof e=="number"&&Number.isInteger(e)&&e>=1&&e<=k,"isMb"),I=n(e=>e.map(s=>`"${s}"`).join(", "),"quoted");export function linkLossProblem(e){if(e==="cancel")return;const s=l(e)&&Object.keys(e).length===1?e.continueMinutes:void 0;if(!(typeof s=="number"&&Number.isInteger(s)&&s>=1&&s<=f))return`onLinkLoss is "cancel" or { "continueMinutes": 1 to ${f} }`}i(linkLossProblem,"linkLossProblem"),n(linkLossProblem,"linkLossProblem");export function linkLossMinutes(e,s,t=e.timeoutMinutes){const o=s??e.onLinkLoss??{continueMinutes:DEFAULT_LINK_LOSS_MINUTES};return o==="cancel"?0:Math.min(o.continueMinutes,Math.ceil(t??f))}i(linkLossMinutes,"linkLossMinutes"),n(linkLossMinutes,"linkLossMinutes");function v(e){return typeof e!="string"||!e||e.length>500||/[\0\\]/.test(e)||e.startsWith("/")||e.startsWith("~")||/^[A-Za-z]:/.test(e)?!1:!e.split("/").includes("..")}i(v,"y"),n(v,"inTree");function y(e){return Array.isArray(e)&&e.length>=1&&e.length<=b&&e.every(s=>typeof s=="string"&&s.length<=x)&&e[0]!==""}i(y,"k"),n(y,"isArgv");function m(e,s,t,o){const c=Object.keys(e).filter(a=>!s.includes(a));c.length&&o.push(`${t?`${t} has`:"has"} ${c.length===1?"an unknown key":"unknown keys"} ${I(c)}`)}i(m,"m"),n(m,"unknownKeys");function S(e,s,t){e!==void 0&&(!Array.isArray(e)||e.length>b||!e.every(v))&&t.push(`${s} is a list of paths inside the checkout`)}i(S,"$"),n(S,"paths");function j(e,s,t){if(e===void 0)return[];if(!Array.isArray(e)||e.length>b||!e.every(v))return t.push(`${s} is a list of paths inside the checkout`),[];for(const o of e){const c=o.split("/");c.some(a=>a===""||a===".")?t.push(`${s} names ${JSON.stringify(o)}: a file is written as git names it \u2014 a/b.json, with no ./, no // and no trailing /`):c.some(a=>a.toLowerCase()===".git")&&t.push(`${s} names ${JSON.stringify(o)}, which is inside git's own folder`)}return e}i(j,"N"),n(j,"inputPaths");function A(e){if(!l(e))return["is not an object"];const s=e.kind;if(!LENS_JOB_KINDS.includes(s))return[`kind is ${LENS_JOB_KINDS.slice(0,-1).join(", ")} or ${LENS_JOB_KINDS.at(-1)}`];const t=[];m(e,$[s],"",t),e.lane!==void 0&&e.lane!=="light"&&e.lane!=="heavy"&&t.push("lane is light or heavy"),y(e.command)||t.push("command is a program and its arguments, as a list of strings \u2014 not a shell line"),e.cleanup!==void 0&&!y(e.cleanup)&&t.push("cleanup is a program and its arguments, as a list of strings"),e.prepare!==void 0&&!(Array.isArray(e.prepare)&&e.prepare.length<=b&&e.prepare.every(y))&&t.push("prepare is a list of steps, each a program and its arguments"),e.report!==void 0&&!["jest","vitest","playwright"].includes(e.report)&&t.push("report is jest, vitest or playwright"),S(e.artifacts,"artifacts",t),e.timeoutMinutes!==void 0&&!(typeof e.timeoutMinutes=="number"&&e.timeoutMinutes>0&&e.timeoutMinutes<=f)&&t.push(`timeoutMinutes is execution minutes, up to ${f}`),e.retryable!==void 0&&typeof e.retryable!="boolean"&&t.push("retryable is true or false");const o=e.onLinkLoss,c=o===void 0?void 0:linkLossProblem(o);c?t.push(c):l(o)&&typeof e.timeoutMinutes=="number"&&o.continueMinutes>e.timeoutMinutes&&t.push(`onLinkLoss.continueMinutes is past timeoutMinutes (${e.timeoutMinutes}): a run goes on through a dropped link no longer than it may run`),e.nx!==void 0&&!(typeof e.nx=="string"&&/^\S+:[^\s:]+$/.test(e.nx))&&t.push("nx is <project>:<target>");const a=e.inputs;if(a!==void 0)if(!l(a))t.push("inputs is an object of files, minted and secrets");else{m(a,["files","minted","secrets"],"inputs",t);const r=j(a.files,"inputs.files",t),d=j(a.minted,"inputs.minted",t);for(const h of r)neverShipped(h)&&t.push(`inputs.files names ${h}, which is never shipped to another Mac \u2014 declare it in inputs.minted, and make it in a prepare step`);const u=[...new Set(r.filter(h=>d.includes(h)))];u.length&&t.push(`inputs names ${u.join(", ")} in files and in minted: a file is shipped by hash, or made per run on the host that runs it \u2014 not both`);const g=a.secrets;g!==void 0&&!(Array.isArray(g)&&g.length<=b&&g.every(h=>typeof h=="string"&&/^[A-Za-z_][A-Za-z0-9_]*$/.test(h)))&&t.push("inputs.secrets is a list of variable names, never values")}const p=e.budget;if(!l(p))t.push("has no budget: the memory it declares is what it is admitted by");else{m(p,L[s],"budget",t);for(const r of["buildMb","hostMb","vmMb"])L[s].includes(r)&&p[r]!==void 0&&!E(p[r])&&t.push(`budget.${r} is MiB, a whole number from 1 to ${k}`);if(s==="testcontainers"&&(p.vmMb===void 0||p.hostMb===void 0)&&t.push("budget needs vmMb (its containers, in Docker's VM) and hostMb (the test runner, on the host)"),s==="playwright"&&p.vmMb===void 0&&p.hostMb===void 0&&t.push("budget needs hostMb or vmMb: where its browsers run"),s==="compose"){const r=p.services;if(!l(r)||!Object.keys(r).length)t.push("budget.services is each service's expected peak, MiB, by its name in the compose files");else for(const[d,u]of Object.entries(r))N.test(d)?E(u)||t.push(`budget.services.${d} is MiB, a whole number from 1 to ${k}`):t.push(`budget.services has "${d}", which is no service name`)}}if(s==="compose"){const r=e.compose;if(!l(r))t.push("compose is an object of files and edge");else{m(r,["files","edge"],"compose",t);const d=r.files;(!Array.isArray(d)||!d.length||d.length>b||!d.every(v))&&t.push("compose.files is the compose files, as paths inside the checkout");const u=r.edge;u!==void 0&&(!l(u)||typeof u.service!="string"||!N.test(u.service)||!Number.isInteger(u.port)||u.port<1||u.port>65535?t.push('compose.edge is the service and the container port its URL reaches: { "service": "edge", "port": 8443 }'):(m(u,["service","port"],"compose.edge",t),l(p)&&l(p.services)&&!Object.hasOwn(p.services,u.service)&&t.push(`${u.service} has no budget`)))}}return s==="playwright"&&e.stack!==void 0&&!(typeof e.stack=="string"&&_.test(e.stack))&&t.push("stack is the name of a compose job of this file"),t}i(A,"j"),n(A,"jobProblems");export function readLensJobs(e){const s={jobs:{},problems:[]};if(e===void 0)return s;if(!l(e))return s.problems.push({problem:"jobs is an object of jobs by name"}),s;for(const[t,o]of Object.entries(e)){if(!_.test(t)){s.problems.push({job:t,problem:"a job's name is letters, digits, dots, dashes and underscores \u2014 63 at most, the first a letter or a digit"});continue}const c=A(o);c.length?s.problems.push(...c.map(a=>({job:t,problem:a}))):s.jobs[t]=o}for(const[t,o]of Object.entries(s.jobs))o.kind!=="playwright"||o.stack===void 0||s.jobs[o.stack]?.kind!=="compose"&&(s.problems.push({job:t,problem:`stack names "${o.stack}", which is no compose job of this file that may run`}),delete s.jobs[t]);return s}i(readLensJobs,"readLensJobs"),n(readLensJobs,"readLensJobs");const O=n(e=>Object.values(e).reduce((s,t)=>s+t,0),"sum");export function jobVmNeedMb(e,s={}){if(e.kind==="compose")return Math.max(e.budget.buildMb??0,O(e.budget.services));if(e.kind==="testcontainers")return e.budget.vmMb;const t=e.budget.vmMb??0,o=e.stack===void 0?void 0:s[e.stack];return o?.kind==="compose"?Math.max(o.budget.buildMb??0,O(o.budget.services)+t):t}i(jobVmNeedMb,"jobVmNeedMb"),n(jobVmNeedMb,"jobVmNeedMb");export function jobHostNeedMb(e,s={}){const t=e.budget.hostMb??0,o=e.kind==="playwright"&&e.stack!==void 0?s[e.stack]:void 0;return t+(o?.kind==="compose"?o.budget.hostMb??0:0)}i(jobHostNeedMb,"jobHostNeedMb"),n(jobHostNeedMb,"jobHostNeedMb");export function jobLane(e){return e.lane?e.lane:e.kind==="compose"||e.kind==="playwright"&&e.stack!==void 0?"heavy":"light"}i(jobLane,"jobLane"),n(jobLane,"jobLane");export function unbudgetedServices(e,s){return[...new Set(s)].filter(t=>!Object.hasOwn(e.budget.services,t)).sort()}i(unbudgetedServices,"unbudgetedServices"),n(unbudgetedServices,"unbudgetedServices");export const RUN_ID_PATTERN=/^[A-Za-z0-9][A-Za-z0-9_-]{7,79}$/;export function runShortId(e){const s=e.toLowerCase().replace(/^[a-z]+_/,"").replace(/[^a-z0-9]/g,"").slice(0,8);return s.length===8?s:void 0}i(runShortId,"runShortId"),n(runShortId,"runShortId");export const composeProjectOf=n(e=>`lensmcp-${e}`,"composeProjectOf"),DOCKER_RUN_ENV={id:"LENSMCP_RUN_ID",origin:"LENSMCP_RUN_ORIGIN",artifacts:"LENSMCP_RUN_ARTIFACTS",labels:"LENSMCP_RUN_LABELS",override:"LENSMCP_COMPOSE_OVERRIDE",project:"COMPOSE_PROJECT_NAME"};export function dockerRunLabels(e){return{[DOCKER_LABELS.run]:e.id,[DOCKER_LABELS.home]:e.home,[DOCKER_LABELS.job]:e.job}}i(dockerRunLabels,"dockerRunLabels"),n(dockerRunLabels,"dockerRunLabels");export const runLabelsEnv=n(e=>JSON.stringify(e),"runLabelsEnv");export function jobRunScope(e){return e.kind==="compose"||e.kind==="playwright"&&e.stack!==void 0?"stack":jobVmNeedMb(e)>0?"containers":"none"}i(jobRunScope,"jobRunScope"),n(jobRunScope,"jobRunScope");export const RYUK_DISABLED_ENV="TESTCONTAINERS_RYUK_DISABLED",RYUK_LABEL="org.testcontainers.ryuk";export function ryukWarning(e,s){const t=s[RYUK_DISABLED_ENV];if(!(e.kind!=="testcontainers"||t===void 0||t.trim().toLowerCase()!=="true"))return`${RYUK_DISABLED_ENV}=${t.trim()} is set in the job's environment: testcontainers' own reaper (Ryuk) is off, so a container the suite leaves is removed only where it carries the run's labels \u2014 hand ${DOCKER_RUN_ENV.labels} to every container it starts. One that does not carry them stays in Docker's VM: LensMCP never removes it, and nothing else does.`}i(ryukWarning,"ryukWarning"),n(ryukWarning,"ryukWarning");export const MAX_RUN_ROUTE_SEC=14400,DOCKER_RUN_ENDS=["passed","failed","cancelled","timeout","errored","lost"],dockerRunEnded=n(e=>DOCKER_RUN_ENDS.includes(e),"dockerRunEnded"),MAX_RUN_STRANGERS=20,MAX_RUN_KILLS=100,CONTAINER_OOM="container-oom",DOCKER_ENGINE_LOST="docker-engine-lost",DOCKER_RUN_FIELD="dockerRun";
|
|
1
|
+
"use strict";var w=Object.defineProperty;var i=(e,s)=>w(e,"name",{value:s,configurable:!0});var $=Object.defineProperty,r=i((e,s)=>$(e,"name",{value:s,configurable:!0}),"i"),x=Object.defineProperty,n=r((e,s)=>x(e,"name",{value:s,configurable:!0}),"s");export const DOCKER_LABELS={run:"com.lensmcp.run",home:"com.lensmcp.home",job:"com.lensmcp.job",probe:"com.lensmcp.probe"},LENS_JOB_KINDS=["compose","testcontainers","playwright"];export function neverShipped(e){const s=(e.split("/").at(-1)??"").toLowerCase();return s===".env"||s===".env.local"||/^\.env\..+\.local$/.test(s)}i(neverShipped,"neverShipped"),r(neverShipped,"neverShipped"),n(neverShipped,"neverShipped");export const jobInputFiles=n(e=>[...new Set(e.inputs?.files??[])].sort(),"jobInputFiles"),jobMintedFiles=n(e=>[...new Set(e.inputs?.minted??[])].sort(),"jobMintedFiles"),DEFAULT_LINK_LOSS_MINUTES=15,jobProblemText=n(e=>e.job===void 0?e.problem:`jobs.${e.job}: ${e.problem}`,"jobProblemText");const j=["kind","lane","prepare","command","cleanup","report","artifacts","inputs","timeoutMinutes","retryable","onLinkLoss","nx","budget"],I={compose:[...j,"compose"],testcontainers:j,playwright:[...j,"stack"]},S={compose:["services","buildMb","hostMb"],testcontainers:["vmMb","hostMb"],playwright:["hostMb","vmMb"]},E=/^[A-Za-z0-9][A-Za-z0-9._-]{0,62}$/,R=/^[A-Za-z0-9][A-Za-z0-9._-]*$/,L=1024*1024,g=360,f=100,C=4e3,l=n(e=>typeof e=="object"&&e!==null&&!Array.isArray(e),"isObj"),A=n(e=>typeof e=="number"&&Number.isInteger(e)&&e>=1&&e<=L,"isMb"),P=n(e=>e.map(s=>`"${s}"`).join(", "),"quoted");export function linkLossProblem(e){if(e==="cancel")return;const s=l(e)&&Object.keys(e).length===1?e.continueMinutes:void 0;if(!(typeof s=="number"&&Number.isInteger(s)&&s>=1&&s<=g))return`onLinkLoss is "cancel" or { "continueMinutes": 1 to ${g} }`}i(linkLossProblem,"linkLossProblem"),r(linkLossProblem,"linkLossProblem"),n(linkLossProblem,"linkLossProblem");export function linkLossMinutes(e,s,t=e.timeoutMinutes){const o=s??e.onLinkLoss??{continueMinutes:DEFAULT_LINK_LOSS_MINUTES};return o==="cancel"?0:Math.min(o.continueMinutes,Math.ceil(t??g))}i(linkLossMinutes,"linkLossMinutes"),r(linkLossMinutes,"linkLossMinutes"),n(linkLossMinutes,"linkLossMinutes");function v(e){return typeof e!="string"||!e||e.length>500||/[\0\\]/.test(e)||e.startsWith("/")||e.startsWith("~")||/^[A-Za-z]:/.test(e)?!1:!e.split("/").includes("..")}i(v,"v"),r(v,"y"),n(v,"inTree");function y(e){return Array.isArray(e)&&e.length>=1&&e.length<=f&&e.every(s=>typeof s=="string"&&s.length<=C)&&e[0]!==""}i(y,"y"),r(y,"k"),n(y,"isArgv");function m(e,s,t,o){const p=Object.keys(e).filter(u=>!s.includes(u));p.length&&o.push(`${t?`${t} has`:"has"} ${p.length===1?"an unknown key":"unknown keys"} ${P(p)}`)}i(m,"m"),r(m,"m"),n(m,"unknownKeys");function _(e,s,t){e!==void 0&&(!Array.isArray(e)||e.length>f||!e.every(v))&&t.push(`${s} is a list of paths inside the checkout`)}i(_,"S"),r(_,"$"),n(_,"paths");function k(e,s,t){if(e===void 0)return[];if(!Array.isArray(e)||e.length>f||!e.every(v))return t.push(`${s} is a list of paths inside the checkout`),[];for(const o of e){const p=o.split("/");p.some(u=>u===""||u===".")?t.push(`${s} names ${JSON.stringify(o)}: a file is written as git names it \u2014 a/b.json, with no ./, no // and no trailing /`):p.some(u=>u.toLowerCase()===".git")&&t.push(`${s} names ${JSON.stringify(o)}, which is inside git's own folder`)}return e}i(k,"j"),r(k,"N"),n(k,"inputPaths");function N(e){if(!l(e))return["is not an object"];const s=e.kind;if(!LENS_JOB_KINDS.includes(s))return[`kind is ${LENS_JOB_KINDS.slice(0,-1).join(", ")} or ${LENS_JOB_KINDS.at(-1)}`];const t=[];m(e,I[s],"",t),e.lane!==void 0&&e.lane!=="light"&&e.lane!=="heavy"&&t.push("lane is light or heavy"),y(e.command)||t.push("command is a program and its arguments, as a list of strings \u2014 not a shell line"),e.cleanup!==void 0&&!y(e.cleanup)&&t.push("cleanup is a program and its arguments, as a list of strings"),e.prepare!==void 0&&!(Array.isArray(e.prepare)&&e.prepare.length<=f&&e.prepare.every(y))&&t.push("prepare is a list of steps, each a program and its arguments"),e.report!==void 0&&!["jest","vitest","playwright"].includes(e.report)&&t.push("report is jest, vitest or playwright"),_(e.artifacts,"artifacts",t),e.timeoutMinutes!==void 0&&!(typeof e.timeoutMinutes=="number"&&e.timeoutMinutes>0&&e.timeoutMinutes<=g)&&t.push(`timeoutMinutes is execution minutes, up to ${g}`),e.retryable!==void 0&&typeof e.retryable!="boolean"&&t.push("retryable is true or false");const o=e.onLinkLoss,p=o===void 0?void 0:linkLossProblem(o);p?t.push(p):l(o)&&typeof e.timeoutMinutes=="number"&&o.continueMinutes>e.timeoutMinutes&&t.push(`onLinkLoss.continueMinutes is past timeoutMinutes (${e.timeoutMinutes}): a run goes on through a dropped link no longer than it may run`),e.nx!==void 0&&!(typeof e.nx=="string"&&/^\S+:[^\s:]+$/.test(e.nx))&&t.push("nx is <project>:<target>");const u=e.inputs;if(u!==void 0)if(!l(u))t.push("inputs is an object of files, minted and secrets");else{m(u,["files","minted","secrets"],"inputs",t);const a=k(u.files,"inputs.files",t),b=k(u.minted,"inputs.minted",t);for(const h of a)neverShipped(h)&&t.push(`inputs.files names ${h}, which is never shipped to another Mac \u2014 declare it in inputs.minted, and make it in a prepare step`);const c=[...new Set(a.filter(h=>b.includes(h)))];c.length&&t.push(`inputs names ${c.join(", ")} in files and in minted: a file is shipped by hash, or made per run on the host that runs it \u2014 not both`);const M=u.secrets;M!==void 0&&!(Array.isArray(M)&&M.length<=f&&M.every(h=>typeof h=="string"&&/^[A-Za-z_][A-Za-z0-9_]*$/.test(h)))&&t.push("inputs.secrets is a list of variable names, never values")}const d=e.budget;if(!l(d))t.push("has no budget: the memory it declares is what it is admitted by");else{m(d,S[s],"budget",t);for(const a of["buildMb","hostMb","vmMb"])S[s].includes(a)&&d[a]!==void 0&&!A(d[a])&&t.push(`budget.${a} is MiB, a whole number from 1 to ${L}`);if(s==="testcontainers"&&(d.vmMb===void 0||d.hostMb===void 0)&&t.push("budget needs vmMb (its containers, in Docker's VM) and hostMb (the test runner, on the host)"),s==="playwright"&&d.vmMb===void 0&&d.hostMb===void 0&&t.push("budget needs hostMb or vmMb: where its browsers run"),s==="compose"){const a=d.services;if(!l(a)||!Object.keys(a).length)t.push("budget.services is each service's expected peak, MiB, by its name in the compose files");else for(const[b,c]of Object.entries(a))R.test(b)?A(c)||t.push(`budget.services.${b} is MiB, a whole number from 1 to ${L}`):t.push(`budget.services has "${b}", which is no service name`)}}if(s==="compose"){const a=e.compose;if(!l(a))t.push("compose is an object of files and edge");else{m(a,["files","edge"],"compose",t);const b=a.files;(!Array.isArray(b)||!b.length||b.length>f||!b.every(v))&&t.push("compose.files is the compose files, as paths inside the checkout");const c=a.edge;c!==void 0&&(!l(c)||typeof c.service!="string"||!R.test(c.service)||!Number.isInteger(c.port)||c.port<1||c.port>65535?t.push('compose.edge is the service and the container port its URL reaches: { "service": "edge", "port": 8443 }'):(m(c,["service","port"],"compose.edge",t),l(d)&&l(d.services)&&!Object.hasOwn(d.services,c.service)&&t.push(`${c.service} has no budget`)))}}return s==="playwright"&&e.stack!==void 0&&!(typeof e.stack=="string"&&E.test(e.stack))&&t.push("stack is the name of a compose job of this file"),t}i(N,"A"),r(N,"j"),n(N,"jobProblems");export function readLensJobs(e){const s={jobs:{},problems:[]};if(e===void 0)return s;if(!l(e))return s.problems.push({problem:"jobs is an object of jobs by name"}),s;for(const[t,o]of Object.entries(e)){if(!E.test(t)){s.problems.push({job:t,problem:"a job's name is letters, digits, dots, dashes and underscores \u2014 63 at most, the first a letter or a digit"});continue}const p=N(o);p.length?s.problems.push(...p.map(u=>({job:t,problem:u}))):s.jobs[t]=o}for(const[t,o]of Object.entries(s.jobs))o.kind!=="playwright"||o.stack===void 0||s.jobs[o.stack]?.kind!=="compose"&&(s.problems.push({job:t,problem:`stack names "${o.stack}", which is no compose job of this file that may run`}),delete s.jobs[t]);return s}i(readLensJobs,"readLensJobs"),r(readLensJobs,"readLensJobs"),n(readLensJobs,"readLensJobs");const O=n(e=>Object.values(e).reduce((s,t)=>s+t,0),"sum");export function jobVmNeedMb(e,s={}){if(e.kind==="compose")return Math.max(e.budget.buildMb??0,O(e.budget.services));if(e.kind==="testcontainers")return e.budget.vmMb;const t=e.budget.vmMb??0,o=e.stack===void 0?void 0:s[e.stack];return o?.kind==="compose"?Math.max(o.budget.buildMb??0,O(o.budget.services)+t):t}i(jobVmNeedMb,"jobVmNeedMb"),r(jobVmNeedMb,"jobVmNeedMb"),n(jobVmNeedMb,"jobVmNeedMb");export function jobHostNeedMb(e,s={}){const t=e.budget.hostMb??0,o=e.kind==="playwright"&&e.stack!==void 0?s[e.stack]:void 0;return t+(o?.kind==="compose"?o.budget.hostMb??0:0)}i(jobHostNeedMb,"jobHostNeedMb"),r(jobHostNeedMb,"jobHostNeedMb"),n(jobHostNeedMb,"jobHostNeedMb");export function jobLane(e){return e.lane?e.lane:e.kind==="compose"||e.kind==="playwright"&&e.stack!==void 0?"heavy":"light"}i(jobLane,"jobLane"),r(jobLane,"jobLane"),n(jobLane,"jobLane");export function unbudgetedServices(e,s){return[...new Set(s)].filter(t=>!Object.hasOwn(e.budget.services,t)).sort()}i(unbudgetedServices,"unbudgetedServices"),r(unbudgetedServices,"unbudgetedServices"),n(unbudgetedServices,"unbudgetedServices");export const RUN_ID_PATTERN=/^[A-Za-z0-9][A-Za-z0-9_-]{7,79}$/;export function runShortId(e){const s=e.toLowerCase().replace(/^[a-z]+_/,"").replace(/[^a-z0-9]/g,"").slice(0,8);return s.length===8?s:void 0}i(runShortId,"runShortId"),r(runShortId,"runShortId"),n(runShortId,"runShortId");export const composeProjectOf=n(e=>`lensmcp-${e}`,"composeProjectOf"),DOCKER_RUN_ENV={id:"LENSMCP_RUN_ID",origin:"LENSMCP_RUN_ORIGIN",artifacts:"LENSMCP_RUN_ARTIFACTS",labels:"LENSMCP_RUN_LABELS",override:"LENSMCP_COMPOSE_OVERRIDE",project:"COMPOSE_PROJECT_NAME"};export function dockerRunLabels(e){return{[DOCKER_LABELS.run]:e.id,[DOCKER_LABELS.home]:e.home,[DOCKER_LABELS.job]:e.job}}i(dockerRunLabels,"dockerRunLabels"),r(dockerRunLabels,"dockerRunLabels"),n(dockerRunLabels,"dockerRunLabels");export const runLabelsEnv=n(e=>JSON.stringify(e),"runLabelsEnv");export function jobRunScope(e){return e.kind==="compose"||e.kind==="playwright"&&e.stack!==void 0?"stack":jobVmNeedMb(e)>0?"containers":"none"}i(jobRunScope,"jobRunScope"),r(jobRunScope,"jobRunScope"),n(jobRunScope,"jobRunScope");export const RYUK_DISABLED_ENV="TESTCONTAINERS_RYUK_DISABLED",RYUK_LABEL="org.testcontainers.ryuk";export function ryukWarning(e,s){const t=s[RYUK_DISABLED_ENV];if(!(e.kind!=="testcontainers"||t===void 0||t.trim().toLowerCase()!=="true"))return`${RYUK_DISABLED_ENV}=${t.trim()} is set in the job's environment: testcontainers' own reaper (Ryuk) is off, so a container the suite leaves is removed only where it carries the run's labels \u2014 hand ${DOCKER_RUN_ENV.labels} to every container it starts. One that does not carry them stays in Docker's VM: LensMCP never removes it, and nothing else does.`}i(ryukWarning,"ryukWarning"),r(ryukWarning,"ryukWarning"),n(ryukWarning,"ryukWarning");export const MAX_RUN_ROUTE_SEC=14400,DOCKER_RUN_ENDS=["passed","failed","cancelled","timeout","errored","lost"],dockerRunEnded=n(e=>DOCKER_RUN_ENDS.includes(e),"dockerRunEnded"),MAX_RUN_STRANGERS=20,MAX_RUN_KILLS=100,CONTAINER_OOM="container-oom",DOCKER_ENGINE_LOST="docker-engine-lost",DOCKER_RUN_FIELD="dockerRun";
|
package/lib/docker-report.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
`)}
|
|
1
|
+
"use strict";var w=Object.defineProperty;var c=(e,t)=>w(e,"name",{value:t,configurable:!0});var k=Object.defineProperty,p=c((e,t)=>k(e,"name",{value:t,configurable:!0}),"h"),x=Object.defineProperty,u=p((e,t)=>x(e,"name",{value:t,configurable:!0}),"u");import{DOCKER_RUN_ENV as f,dockerRunEnded as j,RYUK_DISABLED_ENV as A}from"./docker-jobs.js";export function runUnlabeledWords(e){if(e.scope!=="containers")return[];const t=[],o=`hand ${f.labels} to each container it starts \u2014 a JSON object of labels: .withLabels(JSON.parse(process.env.${f.labels} ?? '{}'))`,i=e.startedAt!==void 0&&e.watch?.inspected!==void 0&&!e.engineLost&&!(e.services??[]).length;i&&t.push(`LensMCP saw no container with the run's labels while it ran: it watched none and removed none. If the job starts containers, ${o}.`);const a=e.strangers;if(a?.containers.length){const n=a.containers.length+(a.more??0),h=(e.warnings??[]).some(l=>l.startsWith(A));t.push(`${n} container${n===1?"":"s"} without the run's labels came up while it ran and ${n===1?"is":"are"} still there: ${a.containers.join(", ")}${a.more?` and ${a.more} more`:""}. LensMCP cannot tell whether this run started ${n===1?"it":"them"} \u2014 Docker does not say who starts a container \u2014 and ${n===1?"does not remove it":"removes none of them"}: only what carries the run's labels is the run's. `+(h?"testcontainers' own reaper is off, so nothing else removes what a suite left either.":"Where testcontainers' own reaper is on, it removes what a suite left.")+(i?"":` If the job started ${n===1?"it":"them"}, ${o}.`))}return t}c(runUnlabeledWords,"runUnlabeledWords"),p(runUnlabeledWords,"runUnlabeledWords"),u(runUnlabeledWords,"runUnlabeledWords");export function dockerRunReport(e,t=Date.now()){const o=j(e.state),i=(e.services??[]).map(l=>{const s=l.budgetMb===void 0?0:l.peakMb-l.budgetMb;return{...l,...s>0?{overMb:s}:{},...l.peakMb>0?{}:{unsampled:!0}}}).sort((l,s)=>(s.overMb??0)-(l.overMb??0)||s.peakMb-l.peakMb||l.name.localeCompare(s.name)),a=i.filter(l=>l.budgetMb!==void 0),n=e.startedAt===void 0?void 0:Math.max(0,(e.endedAt??t)-e.startedAt),h=runUnlabeledWords(e);return{run:{id:e.id,job:e.job,kind:e.kind,state:e.state,ended:o,scope:e.scope??"stack",project:e.project,root:e.root,...e.context?{context:e.context}:{},...e.stage?{stage:e.stage}:{},...e.note?{note:e.note}:{},...e.url?{url:e.url}:{},...e.origin?{origin:e.origin}:{},...e.urlNote?{urlNote:e.urlNote}:{},createdAt:e.createdAt,...e.startedAt!==void 0?{startedAt:e.startedAt}:{},...e.endedAt!==void 0?{endedAt:e.endedAt}:{},...n!==void 0?{ranMs:n}:{},...e.exit?{exit:e.exit}:{}},services:i,totals:{lastMb:i.reduce((l,s)=>l+s.lastMb,0),...a.length?{budgetMb:a.reduce((l,s)=>l+(s.budgetMb??0),0)}:{}},kills:e.kills??[],...e.killsMore?{killsMore:e.killsMore}:{},...e.engineLost?{engineLost:e.engineLost}:{},...e.vm?{vm:e.vm}:{},...e.cleanup?{cleanup:e.cleanup}:{},...e.warnings?.length?{warnings:e.warnings}:{},...h.length?{unlabeled:h}:{},...e.watch?{watch:e.watch}:{},files:{...e.files.samples?{samples:e.files.samples}:{},...e.files.events?{events:e.files.events}:{},log:e.files.log,artifacts:e.files.artifacts}}}c(dockerRunReport,"dockerRunReport"),p(dockerRunReport,"dockerRunReport"),u(dockerRunReport,"dockerRunReport");const d=u(e=>new Date(e).toISOString().replace(/\.\d{3}Z$/,"Z"),"when"),M=u(e=>{const t=Math.round(e/1e3);if(t<60)return`${t} s`;const o=Math.floor(t/60);return o<60?`${o} min${t%60?` ${t%60} s`:""}`:`${Math.floor(o/60)} h${o%60?` ${o%60} min`:""}`},"lasted"),$=u((e,t,o)=>`${e} ${e===1?t:o}`,"plural");export{d as dockerTime,M as dockerLasted};function g(e){const t=e.exit?e.exit.signal?`its command was ended by ${e.exit.signal}`:`its command exited ${e.exit.code}`:void 0,o=[e.ranMs!==void 0?`${e.ended?"ran":"running for"} ${M(e.ranMs)}`:void 0,e.startedAt!==void 0?`started ${d(e.startedAt)}`:`created ${d(e.createdAt)}`,e.endedAt!==void 0?`ended ${d(e.endedAt)}`:void 0].filter(Boolean).join(", ");return`${{starting:"starting: nothing of the job has run yet",preparing:"preparing: its prepare steps run",running:"running",cleaning:`cleaning up${t?`: ${t}`:""}`,passed:`passed${t?`: ${t}`:""}`,failed:`failed${t?`: ${t}`:""}`,cancelled:"cancelled",timeout:"timed out",errored:"errored",lost:`lost: its runner died, so nobody knows how it would have ended${t?` (${t})`:""}`}[e.state]} \xB7 ${o}`}c(g,"v"),p(g,"w"),u(g,"stateText");function v(e){const t=e[0].map((o,i)=>Math.max(...e.map(a=>(a[i]??"").length)));return e.map(o=>o.map((i,a)=>a===0?i.padEnd(t[a]):a===o.length-1?i:i.padStart(t[a])).join(" ").trimEnd())}c(v,"f"),p(v,"k"),u(v,"table");export function dockerRunReportText(e){const{run:t,vm:o,watch:i,cleanup:a}=e,n=[`Docker run ${t.id} \u2014 job \xAB${t.job}\xBB (${t.kind}), ${t.project?`Compose project ${t.project}`:t.scope==="none"?"nothing in Docker":"no Compose project: its containers by the run's labels"}`,` ${g(t)}`,` in ${t.root}${t.context?` \xB7 Docker context ${t.context}`:""}`];t.stage&&n.push(` stage: ${t.stage}`),t.note&&n.push(` ${t.note}`);for(const s of e.warnings??[])n.push(` ! ${s}`);t.url?n.push(` URL: ${t.url}`):t.urlNote&&n.push(` no URL: ${t.urlNote}`),n.push("");const h=i?.samples?`${$(i.samples,"sample","samples")}${i.sampledAt!==void 0?`, the last at ${d(i.sampledAt)}`:""}`:"no sample was taken";if(n.push(t.scope==="none"?"Memory: the job declares nothing in Docker's VM \u2014 its commands were given no labels, and Docker was not asked about it.":`Memory by service, MiB \u2014 ${h}`),e.services.length){const s=u(r=>r===void 0?"\u2013":String(r),"figure"),b=u(r=>[r.overMb!==void 0?`OVER its budget by ${r.overMb}`:void 0,r.oomKilled?"killed for memory":void 0,r.exitCode!==void 0?`exit ${r.exitCode}`:void 0,r.unsampled?"never sampled":void 0].filter(Boolean).join(" \xB7 "),"remark");n.push(...v([["service","now","peak","budget","limit",""],...e.services.map(r=>[r.name,r.unsampled?"\u2013":String(r.lastMb),r.unsampled?"\u2013":String(r.peakMb),s(r.budgetMb),s(r.limitMb),b(r)]),["all",String(e.totals.lastMb),"",s(e.totals.budgetMb),"",""]]).map(r=>` ${r}`));const m=e.services.filter(r=>r.overMb!==void 0);m.length&&n.push(` ${$(m.length,"service","services")} over what ${m.length===1?"it declares":"they declare"}: raise \`jobs.${t.job}.budget.services\` in lensmcp.json to what ${m.length===1?"it takes":"they take"} \u2014 the queue lets the job in by these figures.`)}else t.scope!=="none"&&n.push(" No container of the run was seen.");n.push("");const l=e.kills.length+(e.killsMore??0);n.push(l?`Killed for memory: ${l}`:"Killed for memory: none");for(const s of e.kills){const b=[s.limitMb!==void 0?`at its ${s.limitMb} MiB limit`:"no limit of its own: the VM ran out, or it was not read",s.peakMb!==void 0?`peak ${s.peakMb} MiB`:"never sampled",s.budgetMb!==void 0?`budget ${s.budgetMb} MiB`:void 0,s.seen==="event"?"seen live":"found by the inspect: the live stream did not tell it"].filter(Boolean).join(" \xB7 ");n.push(` ${d(s.at)} ${s.service}${s.name?` (${s.name})`:""} ${b}`)}if(e.killsMore&&n.push(` \u2026 and ${e.killsMore} more, not listed`),e.engineLost){const s=e.engineLost;n.push(""),n.push(`Docker stopped answering at ${d(s.at)} \u2014 ${s.why}`),s.backAt!==void 0&&n.push(` it answered again at ${d(s.backAt)}`),s.killed?.length&&n.push(` found killed for memory once it was gone: ${s.killed.join(", ")} \u2014 they went with the engine`)}o&&(n.push(""),n.push(`Docker's VM: ${o.totalMb} MiB \xB7 ${o.read==="estimate"?"about ":""}${o.availableAtAdmissionMb} MiB free when the run was let in (${o.read==="estimate"?"an estimate: its own figure could not be read":"the VM's own figure"})`+(o.minAvailableMb!==void 0?` \xB7 lowest ${o.minAvailableMb} MiB while it ran`:" \xB7 not read while it ran")+(o.lastAvailableMb!==void 0?` \xB7 ${o.lastAvailableMb} MiB at the last read${o.sampledAt!==void 0?` (${d(o.sampledAt)})`:""}`:""))),n.push(""),a?a.done?n.push(`Cleanup: by ${a.by==="project"?"the project's own end (LensMCP looked, and found nothing)":a.by} at ${d(a.at)} \u2014 nothing of the run is left`):n.push(`Cleanup: OWED (${a.by}, ${d(a.at)}) \u2014 ${a.why??"something that carries the run's labels is left"}${a.left?.length?` \u2014 left: ${a.left.join(", ")}`:""}`):n.push(t.ended?"Cleanup: not recorded \u2014 its guard, or the sweep, has it":"Cleanup: not yet \u2014 the run has not ended"),a?.unlabeled?.length&&n.push(` in its Compose project without the run's labels, never removed: ${a.unlabeled.join(", ")}`);for(const s of e.unlabeled??[])n.push(` ${s}`);if(i?.notes?.length||i?.streamRestarts){n.push(""),n.push("What the watcher could not do:"),i.streamRestarts&&n.push(` the live stream ended ${$(i.streamRestarts,"time","times")} while Docker answered, and was started again`);for(const s of i.notes??[])n.push(` ${s}`)}return n.push(""),n.push(`Files: ${[e.files.samples?`samples ${e.files.samples}`:void 0,e.files.events?`events ${e.files.events}`:void 0,`log ${e.files.log}`].filter(Boolean).join(" \xB7 ")}`),n.join(`
|
|
2
|
+
`)}c(dockerRunReportText,"dockerRunReportText"),p(dockerRunReportText,"dockerRunReportText"),u(dockerRunReportText,"dockerRunReportText");
|
package/lib/docker-runs.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
`);const o=e.ended?` \xB7 ${v(e.ended,"ended one is","ended ones are")} kept${
|
|
3
|
-
`)}u(dockerRunsText,"dockerRunsText"),i(dockerRunsText,"dockerRunsText");export const BLOCK_MAX_SERVICES=8,BLOCK_MAX_KILLS=5;const
|
|
1
|
+
"use strict";var w=Object.defineProperty;var u=(n,e)=>w(n,"name",{value:e,configurable:!0});var A=Object.defineProperty,a=u((n,e)=>A(n,"name",{value:e,configurable:!0}),"u"),M=Object.defineProperty,i=a((n,e)=>M(n,"name",{value:e,configurable:!0}),"l");import{dockerLasted as $,dockerRunReport as x,dockerTime as h}from"./docker-report.js";export function dockerRunStanding(n){return n.run.ended?n.cleanup?.done===!0?"ended":"owed":"up"}u(dockerRunStanding,"dockerRunStanding"),a(dockerRunStanding,"dockerRunStanding"),i(dockerRunStanding,"dockerRunStanding");export function dockerRunsList(n,e={}){const o=e.now??Date.now(),r=n.map(k=>{const c=x(k,o),g=dockerRunStanding(c);return{...c,standing:g,...g==="up"&&e.runnerGone?.(k)?{runnerGone:!0}:{}}}),d=i(k=>r.filter(c=>c.standing===k).sort((c,g)=>(g.run.endedAt??g.run.startedAt??g.run.createdAt)-(c.run.endedAt??c.run.startedAt??c.run.createdAt)||c.run.id.localeCompare(g.run.id)),"of"),t=d("up"),l=d("owed"),s=d("ended"),p=e.all?s.slice(0,e.endedMax??s.length):[];return{counts:{up:t.length,owed:l.length,ended:s.length},all:e.all===!0,...e.all&&p.length<s.length?{endedMore:s.length-p.length}:{},runs:[...t,...l,...p]}}u(dockerRunsList,"dockerRunsList"),a(dockerRunsList,"dockerRunsList"),i(dockerRunsList,"dockerRunsList");const L={starting:"starting",preparing:"preparing",running:"running",cleaning:"cleaning up",passed:"passed",failed:"failed",cancelled:"cancelled",timeout:"timed out",errored:"errored",lost:"lost"};export const dockerStateWord=i(n=>L[n],"dockerStateWord");export function dockerRunSince(n){const{run:e}=n;return e.ended?e.endedAt??e.startedAt??e.createdAt:e.startedAt??e.createdAt}u(dockerRunSince,"dockerRunSince"),a(dockerRunSince,"dockerRunSince"),i(dockerRunSince,"dockerRunSince");export function dockerRunHolds(n){if(n.services.some(e=>!e.unsampled))return n.totals.budgetMb===void 0?`${n.totals.lastMb} MiB`:`${n.totals.lastMb} of ${n.totals.budgetMb} MiB`}u(dockerRunHolds,"dockerRunHolds"),a(dockerRunHolds,"dockerRunHolds"),i(dockerRunHolds,"dockerRunHolds");export const RUNNER_GONE="its runner is gone: nothing runs it any more \u2014 its guard, or the sweep, writes its end and takes its stack down";export function dockerRunRemarks(n){const e=[];n.runnerGone&&!n.run.ended&&e.push(RUNNER_GONE);const o=n.services.filter(l=>l.overMb!==void 0);o.length&&e.push(`OVER its budget: ${o.map(l=>`${l.name} by ${l.overMb} MiB`).join(", ")}`);const r=n.kills.length+(n.killsMore??0),d=[...new Set(n.kills.map(l=>l.service))];r&&e.push(`killed for memory: ${r}${d.length?` (${d.join(", ")})`:""}`),n.engineLost&&e.push(`Docker stopped answering at ${h(n.engineLost.at)}${n.engineLost.backAt!==void 0?`, and answered again at ${h(n.engineLost.backAt)}`:""}`);const{cleanup:t}=n;return n.run.ended&&!t?e.push("cleanup OWED: none is recorded \u2014 its guard, or the sweep, has it"):t&&!t.done&&e.push(`cleanup OWED: ${t.why??"something that carries the run's labels is left"}${t.left?.length?` \u2014 left: ${t.left.join(", ")}`:""}`),t?.unlabeled?.length&&e.push(`in its Compose project without the run's labels, never removed: ${t.unlabeled.join(", ")}`),e}u(dockerRunRemarks,"dockerRunRemarks"),a(dockerRunRemarks,"dockerRunRemarks"),i(dockerRunRemarks,"dockerRunRemarks");function R(n){const{run:e}=n,o=dockerRunSince(n),r=e.ended?`ended ${h(o)}${e.ranMs!==void 0?` after ${$(e.ranMs)}`:""}`:e.startedAt!==void 0?`for ${$(e.ranMs??0)}, since ${h(o)}`:`since ${h(o)}`,d=n.standing==="up"?dockerRunHolds(n):void 0,t=[[e.job,`${dockerStateWord(e.state)}${n.standing==="owed"?", cleanup OWED":n.runnerGone?", its runner GONE":""}`,r,...d?[`holds ${d}`]:[],e.id].join(" ")];e.stage&&!e.ended&&t.push(` stage: ${e.stage}`),e.url?t.push(` URL: ${e.url}`):e.urlNote&&!e.ended&&t.push(` no URL: ${e.urlNote}`),e.note&&t.push(` ${e.note}`);for(const l of dockerRunRemarks(n))t.push(` ${l}`);return t}u(R,"$"),a(R,"R"),i(R,"runLines");const v=i((n,e,o)=>`${n} ${n===1?e:o}`,"plural");export function dockerRunsText(n){const{counts:e}=n;if(!(e.up+e.owed+e.ended))return["This home's registry holds no Docker run.","A job is declared in the checkout's lensmcp.json \u2192 jobs, and started with `lensmcp docker run <job>`."].join(`
|
|
2
|
+
`);const o=e.ended?` \xB7 ${v(e.ended,"ended one is","ended ones are")} kept${n.all?"":" (--all lists them)"}`:"",r=[`Docker runs of this home \u2014 ${e.up} up, ${e.owed?`${v(e.owed,"owes","owe")} a cleanup`:"none owes a cleanup"}${o}`];n.runs.length||r.push(" Nothing of this home is in Docker now.");for(const d of n.runs)r.push(...R(d).map(t=>` ${t}`));return n.endedMore&&r.push(` \u2026 and ${n.endedMore} more ended, not listed`),e.owed&&r.push("","A cleanup that is owed is taken by the run's guard, then by the sweep: `lensmcp docker sweep --dry-run` says what one would take down."),r.join(`
|
|
3
|
+
`)}u(dockerRunsText,"dockerRunsText"),a(dockerRunsText,"dockerRunsText"),i(dockerRunsText,"dockerRunsText");export const BLOCK_MAX_SERVICES=8,BLOCK_MAX_KILLS=5;const j=8,b=300,m=i(n=>n.length>b?`${n.slice(0,b-1)}\u2026`:n,"cut"),f=i(n=>n?.length?n.slice(0,j).map(e=>e.slice(0,120)):void 0,"names");export function dockerRunBlock(n){const{run:e,cleanup:o,engineLost:r}=n,d=n.services.slice(0,BLOCK_MAX_SERVICES),t=n.kills.slice(0,BLOCK_MAX_KILLS),l=n.kills.length-t.length+(n.killsMore??0),s=f(o?.left),p=f(o?.unlabeled),k=f(r?.killed);return{run:e.id,job:e.job,kind:e.kind,state:e.state,standing:dockerRunStanding(n),...n.runnerGone&&!e.ended?{runnerGone:!0}:{},project:e.project,...e.context?{context:e.context}:{},...e.stage?{stage:e.stage}:{},...e.url?{url:e.url}:{},...e.urlNote?{urlNote:m(e.urlNote)}:{},...e.note?{note:m(e.note)}:{},...e.startedAt!==void 0?{startedAt:e.startedAt}:{},...e.endedAt!==void 0?{endedAt:e.endedAt}:{},...e.ranMs!==void 0?{ranMs:e.ranMs}:{},...e.exit?{exit:e.exit}:{},...n.vm?{vm:n.vm}:{},services:d,...n.services.length>d.length?{servicesMore:n.services.length-d.length}:{},totals:n.totals,kills:t.map(c=>({...c,container:c.container.slice(0,12)})),...l?{killsMore:l}:{},...r?{engineLost:{at:r.at,why:m(r.why),...r.backAt!==void 0?{backAt:r.backAt}:{},...k?{killed:k}:{}}}:{},...o?{cleanup:{by:o.by,at:o.at,done:o.done,...s?{left:s}:{},...p?{unlabeled:p}:{},...o.why?{why:m(o.why)}:{}}}:{}}}u(dockerRunBlock,"dockerRunBlock"),a(dockerRunBlock,"dockerRunBlock"),i(dockerRunBlock,"dockerRunBlock");export function dockerRunBlockLess(n){if(n.services&&n.services.length>1)return{...n,services:n.services.slice(0,-1),servicesMore:(n.servicesMore??0)+1};if(n.kills&&n.kills.length>1)return{...n,kills:n.kills.slice(0,-1),killsMore:(n.killsMore??0)+1}}u(dockerRunBlockLess,"dockerRunBlockLess"),a(dockerRunBlockLess,"dockerRunBlockLess"),i(dockerRunBlockLess,"dockerRunBlockLess");export const PAGE_MAX_ROWS=50;const y=["queued","running"];export function dockerRemoteStanding(n){return n.state==="lost"?"lost":y.includes(n.state)?"up":"ended"}u(dockerRemoteStanding,"dockerRemoteStanding"),a(dockerRemoteStanding,"dockerRemoteStanding"),i(dockerRemoteStanding,"dockerRemoteStanding");export function dockerRemoteRunsList(n,e={}){const o=i(s=>s.completedAt??s.startedAt??s.queuedAt,"since"),r=[...n].sort((s,p)=>o(p)-o(s)||s.run.localeCompare(p.run)),d=r.filter(s=>dockerRemoteStanding(s)==="up"),t=r.filter(s=>dockerRemoteStanding(s)!=="up"),l=t.slice(0,e.endedMax??t.length);return{counts:{up:d.length,lost:t.filter(s=>s.state==="lost").length,ended:t.filter(s=>s.state!=="lost").length},runs:[...d,...l],...l.length<t.length?{endedMore:t.length-l.length}:{}}}u(dockerRemoteRunsList,"dockerRemoteRunsList"),a(dockerRemoteRunsList,"dockerRemoteRunsList"),i(dockerRemoteRunsList,"dockerRemoteRunsList");
|
package/lib/error-cause.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
`)[0].replace(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi,"<id>").replace(/\b[0-9A-HJKMNP-TV-Z]{26}\b/g,"<id>").replace(/0x[0-9a-f]+/gi,"<hex>").replace(/\b[0-9a-f]{12,}\b/gi,"<id>").replace(/\d+/g,"#").trim().slice(0,140):""}s(foldMessage,"foldMessage"),
|
|
3
|
-
`)}s(readableErrorMessage,"readableErrorMessage"),
|
|
4
|
-
`)[0].trim());return t?{name:t[1],message:t[2].trim()}:void 0}s(h,"u"),
|
|
5
|
-
`)){const
|
|
6
|
-
`)[0].trim();const
|
|
1
|
+
"use strict";var g=Object.defineProperty;var s=(e,t)=>g(e,"name",{value:t,configurable:!0});var y=Object.defineProperty,c=s((e,t)=>y(e,"name",{value:t,configurable:!0}),"s"),E=Object.defineProperty,a=c((e,t)=>E(e,"name",{value:t,configurable:!0}),"n");export function joinId(e,t){const i=a(n=>n.replace(/%/g,"%25").replace(/:/g,"%3A"),"esc");return[e,...t.map(n=>i(n===void 0?"":String(n)))].join(":")}s(joinId,"joinId"),c(joinId,"joinId"),a(joinId,"joinId");export function foldMessage(e){return e?e.split(`
|
|
2
|
+
`)[0].replace(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi,"<id>").replace(/\b[0-9A-HJKMNP-TV-Z]{26}\b/g,"<id>").replace(/0x[0-9a-f]+/gi,"<hex>").replace(/\b[0-9a-f]{12,}\b/gi,"<id>").replace(/\d+/g,"#").trim().slice(0,140):""}s(foldMessage,"foldMessage"),c(foldMessage,"foldMessage"),a(foldMessage,"foldMessage");const x=a(e=>!!e&&typeof e=="object"&&typeof e.message=="string","isValidationIssue"),v=a(e=>Array.isArray(e)&&e.length?e.map(String).join("."):"(root)","issuePath"),p=3;export function readableErrorMessage(e){const t=e?.trim()??"",i=t.indexOf("["),n=t.slice(0,Math.max(i,0));if(i<0||!/^(?:[A-Za-z_$][\w$]*:\s*)?$/.test(n))return e;let d;try{d=JSON.parse(t.slice(i))}catch{return e}if(!Array.isArray(d)||!d.length||!d.every(x))return e;const o=d.map(m=>`${v(m.path)}: ${m.message}`),r=o.length===1?"1 issue":`${o.length} issues`,h=o.length>p?` (+${o.length-p} more)`:"";return[`${n}Validation failed (${r}): ${o.slice(0,p).join("; ")}${h}`,...o.map(m=>` ${m}`)].join(`
|
|
3
|
+
`)}s(readableErrorMessage,"readableErrorMessage"),c(readableErrorMessage,"readableErrorMessage"),a(readableErrorMessage,"readableErrorMessage");const w=/^(?:Uncaught\s+(?:\(in promise\)\s+)?)?((?:[A-Za-z_$][\w$]*)?(?:Error|Exception|Failure|Fault|Rejection))(?:\s*\[[^\]]*\])?:\s*(.+)$/;function l(e){const t=w.exec((e??"").split(`
|
|
4
|
+
`)[0].trim());return t?{name:t[1],message:t[2].trim()}:void 0}s(l,"h"),c(l,"u"),a(l,"named");export function appFrameOf(e){for(const t of(e??"").split(`
|
|
5
|
+
`)){const i=/^\s*at\s+(.+)$/.exec(t);if(!i||/node_modules|node:internal|node:async_hooks|\(native\)|<anonymous>|\(internal\//.test(i[1]))continue;const n=/\(?([^()\s]+?):(\d+)(?::\d+)?\)?$/.exec(i[1].trim());return n?`${n[1].replace(/^.*?\/(?=(?:src|apps|libs)\/)/,"")}:${n[2]}`:i[1].trim()}}s(appFrameOf,"appFrameOf"),c(appFrameOf,"appFrameOf"),a(appFrameOf,"appFrameOf");export function errorCause(e){const t=readableErrorMessage(e.message),i=l(e.stack),n=l(t),d=l(e.title),o=e.name?.trim()||i?.name||n?.name||d?.name;if(!o)return;let r=(t!==e.message?t:void 0)??(i&&i.name===o?i.message:void 0)??t??d?.message??e.title??"";const h=l(r);h&&h.name===o&&(r=h.message),r=r.split(`
|
|
6
|
+
`)[0].trim();const m=appFrameOf(e.stack),f=b.has(errorHeadline({name:o,message:r})?.id??"");return{id:joinId("cause",[o,foldMessage(r),f?void 0:m]),errorName:o,message:r,...m?{frame:m}:{}}}s(errorCause,"errorCause"),c(errorCause,"errorCause"),a(errorCause,"errorCause");const b=new Set(["missing-column","missing-table","connection-refused","out-of-memory"]);export function causeIdWithoutFrame(e){return joinId("cause",[e.errorName,foldMessage(e.message),void 0])}s(causeIdWithoutFrame,"causeIdWithoutFrame"),c(causeIdWithoutFrame,"causeIdWithoutFrame"),a(causeIdWithoutFrame,"causeIdWithoutFrame");const u=a(e=>e?` (\xAB${e}\xBB)`:"","q");export const ERROR_HEADLINES=[{id:"missing-column",match:a(e=>/column "?([\w.]+)"?(?: of relation "?[\w.]+"?)? does not exist|Unknown column '([^']+)'|ER_BAD_FIELD_ERROR/i.exec(e),"match"),say:a(e=>({headline:`The code expects a database column${u(e===!0?void 0:e[1]??e[2])} the database doesn't have`,hint:"Run the migrations, or add the migration the entity change needs."}),"say")},{id:"missing-table",match:a(e=>/relation "?([\w.]+)"? does not exist|Table '([^']+)' doesn't exist|ER_NO_SUCH_TABLE/i.exec(e),"match"),say:a(e=>({headline:`The code expects a database table${u(e===!0?void 0:e[1]??e[2])} the database doesn't have`,hint:"Run the migrations against this database."}),"say")},{id:"unique-violation",match:a((e,t)=>/duplicate key value violates unique constraint "?([\w.]+)"?|Duplicate entry '[^']*' for key '([^']+)'|ER_DUP_ENTRY/i.exec(e)||t.code==="23505","match"),say:a(e=>({headline:`A row with the same unique value already exists${u(e===!0?void 0:e[1]??e[2])}`,hint:"The code inserts a duplicate: look up the existing row first, or upsert."}),"say")},{id:"foreign-key-violation",match:a((e,t)=>/violates foreign key constraint "?([\w.]+)"?|a foreign key constraint fails|ER_NO_REFERENCED_ROW|ER_ROW_IS_REFERENCED/i.exec(e)||t.code==="23503","match"),say:a(e=>({headline:`A row points at a row that doesn't exist, or a row still in use was deleted${u(e===!0?void 0:e[1])}`,hint:"Create the referenced row first, or delete the rows that point at it."}),"say")},{id:"connection-refused",match:a((e,t)=>/ECONNREFUSED|connection refused|connect ECONNREFUSED/i.exec(e)||t.code==="ECONNREFUSED","match"),say:a(()=>({headline:"A service the code connects to is not running, or not listening where the code looks",hint:"Start it (database, cache, broker or API), or fix its host and port."}),"say")},{id:"out-of-memory",match:a((e,t)=>/heap out of memory|JavaScript heap|out of memory|ENOMEM|Allocation failed/i.exec(e)||t.code==="ENOMEM","match"),say:a(()=>({headline:"The process ran out of memory",hint:"Something holds or loads too much at once \u2014 look for an unbounded list, cache or query."}),"say")},{id:"jwt-expired",match:a((e,t)=>/jwt expired|token expired/i.exec(e)||t.name==="TokenExpiredError","match"),say:a(()=>({headline:"A sign-in token expired",hint:"Sign in again; if it keeps happening, the client is not refreshing its token."}),"say")},{id:"jwt-invalid",match:a((e,t)=>/jwt malformed|invalid signature|invalid token|jwt must be provided|jwt audience invalid|jwt issuer invalid/i.exec(e)||t.name==="JsonWebTokenError","match"),say:a(()=>({headline:"A sign-in token is not valid here",hint:"Its signature, audience or issuer does not match what this service expects."}),"say")},{id:"timeout",match:a((e,t)=>/ETIMEDOUT|ESOCKETTIMEDOUT|timed? ?out|timeout exceeded|statement timeout|canceling statement due to|Query read timeout/i.exec(e)||t.name==="TimeoutError"||t.code==="ETIMEDOUT","match"),say:a(()=>({headline:"Something took too long and was cut off",hint:"A slow query, a busy dependency or a lock \u2014 open the failing step to see which."}),"say")},{id:"unauthorized",match:a((e,t)=>t.status===401||t.name==="UnauthorizedException"||/^Unauthorized$/i.test(e.trim()),"match"),say:a(()=>({headline:"The request was not signed in (401)",hint:"It came without a valid session or token."}),"say")},{id:"forbidden",match:a((e,t)=>t.status===403||t.name==="ForbiddenException"||/^Forbidden(?: resource)?$/i.test(e.trim()),"match"),say:a(()=>({headline:"The signed-in user is not allowed to do this (403)",hint:"A role or permission check refused it."}),"say")}];export function errorHeadline(e){const t=[e.code,e.message].filter(Boolean).join(" ");for(const i of ERROR_HEADLINES){const n=i.match(t,e);if(n)return{id:i.id,...i.say(n)}}}s(errorHeadline,"errorHeadline"),c(errorHeadline,"errorHeadline"),a(errorHeadline,"errorHeadline");
|
package/lib/error-dismissal.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var E=Object.defineProperty;var s=(e,r)=>E(e,"name",{value:r,configurable:!0});var m=Object.defineProperty,c=s((e,r)=>m(e,"name",{value:r,configurable:!0}),"s"),p=Object.defineProperty,l=c((e,r)=>p(e,"name",{value:r,configurable:!0}),"s");export const ERROR_DISMISSED="error-dismissed",ERROR_RESTORED="error-restored",LENS_EVENT_SOURCE="lens",MAX_DISMISSAL_EVENT_IDS=200;const y=2048;export const MAX_DISMISSAL_REASON_CHARS=500;const b=300,I=new Set(["dashboard","cli","agent"]);export function readErrorDismissal(e){if(e.source!==LENS_EVENT_SOURCE||!e.raw||typeof e.raw!="object")return;const r=e.raw,i=r.groupId;if(typeof i!="string"||i.length===0||i.length>2048)return;if(r.kind===ERROR_RESTORED)return{kind:ERROR_RESTORED,groupId:i};if(r.kind!==ERROR_DISMISSED)return;const n=r.until;if(typeof n!="number"||!Number.isFinite(n))return;const f=Array.isArray(r.eventIds)?r.eventIds.filter(t=>typeof t=="string"&&t.length>0).slice(0,200):[],o=I.has(r.by)?r.by:void 0,a=l((t,S)=>typeof t=="string"&&t.trim()?t.trim().slice(0,S):void 0,"text"),d=a(r.reason,500),u=a(r.title,300);return{kind:ERROR_DISMISSED,groupId:i,until:Math.min(n,e.timestamp),eventIds:f,...o?{by:o}:{},...d?{reason:d}:{},...u?{title:u}:{}}}s(readErrorDismissal,"readErrorDismissal"),c(readErrorDismissal,"readErrorDismissal"),l(readErrorDismissal,"readErrorDismissal");
|