@lensmcp/protocol-types 1.25.37 → 1.25.39

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.
@@ -1,2 +1,2 @@
1
- "use strict";var m=Object.defineProperty;var i=(e,t)=>m(e,"name",{value:t,configurable:!0});var d=Object.defineProperty,l=i((e,t)=>d(e,"name",{value:t,configurable:!0}),"i"),p=Object.defineProperty,u=l((e,t)=>p(e,"name",{value:t,configurable:!0}),"i");export function aiTotalsOf(e){const t={calls:e.length,runs:new Set(e.map(a=>a.run.key)).size,failed:0,input:0,cached:0,written:0,output:0,split:{},costUsd:0,priced:0,first:1/0,last:0,models:[]},r=new Map;for(const a of e){a.failed&&t.failed++,t.input+=a.tokens?.input??0,t.cached+=a.tokens?.cached??0,t.written+=a.tokens?.written??0,t.output+=a.tokens?.output??0;for(const[n,o]of Object.entries(a.split??{}))t.split[n]=(t.split[n]??0)+o;a.costUsd!==void 0&&(t.costUsd+=a.costUsd,t.priced++),t.first=Math.min(t.first,a.at),t.last=Math.max(t.last,a.at),a.model&&r.set(a.model,(r.get(a.model)??0)+1)}return t.models=[...r].sort((a,n)=>n[1]-a[1]).map(([a])=>a),e.length||(t.first=0),t}i(aiTotalsOf,"aiTotalsOf"),l(aiTotalsOf,"aiTotalsOf"),u(aiTotalsOf,"aiTotalsOf");export function aiRunsOf(e,t=!1){const r=new Map;for(const a of e){const n=r.get(a.run.key);n?n.push(a):r.set(a.run.key,[a])}return[...r.entries()].map(([a,n])=>{n.sort((s,c)=>(s.step??0)-(c.step??0)||s.at-c.at);const o=aiTotalsOf(n);return{key:a,from:n[0].run.from,calls:n,at:o.first,last:o.last,totals:o}}).sort((a,n)=>t?a.at-n.at:n.last-a.last)}i(aiRunsOf,"aiRunsOf"),l(aiRunsOf,"aiRunsOf"),u(aiRunsOf,"aiRunsOf");const k="(none)";function f(e,t){if(t==="agent")return e.agent;if(t==="action")return e.action??{key:"action:",name:"(no action)"};if(t==="run")return{key:e.run.key,name:e.agent.name};if(t==="thread")return e.thread?{key:e.thread.key,name:`thread ${e.thread.name}`}:{key:"thread:",name:"(no thread)"};if(t==="flow")return e.flowId?{key:`flow:${e.flowId}`,name:e.flowId}:e.requestId?{key:`request:${e.requestId}`,name:`request ${e.requestId}`}:{key:"flow:",name:"(no flow)"};if(t==="model")return{key:`model:${e.model??""}`,name:e.model??"(unknown model)"};if(t==="service")return{key:`service:${e.service}`,name:e.service};const r=t.slice(5),a=e.meta?.[r];return{key:`${t}=${a??""}`,name:a??k}}i(f,"f"),l(f,"m"),u(f,"keyOf");export function groupAiCalls(e,t,r){const a=new Map;for(const o of e){const s=f(o,t),c=a.get(s.key);c?c.rows.push(o):a.set(s.key,{...s,rows:[o]})}const n=t==="agent"||t==="action";return[...a.values()].map(o=>({key:o.key,name:o.name,...o.from?{from:o.from}:{},nameable:n&&/^(agent|action):./.test(o.key),merged:r?Object.entries(r.merge).filter(([,s])=>s===o.key).map(([s])=>s).sort():[],runs:aiRunsOf(o.rows,t==="flow"),totals:aiTotalsOf(o.rows)})).sort((o,s)=>s.totals.last-o.totals.last||o.name.localeCompare(s.name))}i(groupAiCalls,"groupAiCalls"),l(groupAiCalls,"groupAiCalls"),u(groupAiCalls,"groupAiCalls");export function matchesAi(e,t){const r=t.toLowerCase().split(/\s+/).filter(Boolean);if(!r.length)return!0;const a=[e.id,e.agent.name,e.action?.name,e.model,e.service,e.flowId,e.requestId,e.schema,e.asked,e.said,...e.called??[],...Object.entries(e.meta??{}).map(([n,o])=>`${n}:${o}`)].filter(Boolean).join(`
2
- `).toLowerCase();return r.every(n=>a.includes(n))}i(matchesAi,"matchesAi"),l(matchesAi,"matchesAi"),u(matchesAi,"matchesAi");
1
+ "use strict";var u=Object.defineProperty;var i=(t,e)=>u(t,"name",{value:e,configurable:!0});var m=Object.defineProperty,c=i((t,e)=>m(t,"name",{value:e,configurable:!0}),"i");export function aiTotalsOf(t){const e={calls:t.length,runs:new Set(t.map(a=>a.run.key)).size,failed:0,input:0,cached:0,written:0,output:0,split:{},costUsd:0,priced:0,first:1/0,last:0,models:[]},o=new Map;for(const a of t){a.failed&&e.failed++,e.input+=a.tokens?.input??0,e.cached+=a.tokens?.cached??0,e.written+=a.tokens?.written??0,e.output+=a.tokens?.output??0;for(const[s,n]of Object.entries(a.split??{}))e.split[s]=(e.split[s]??0)+n;a.costUsd!==void 0&&(e.costUsd+=a.costUsd,e.priced++),e.first=Math.min(e.first,a.at),e.last=Math.max(e.last,a.at),a.model&&o.set(a.model,(o.get(a.model)??0)+1)}return e.models=[...o].sort((a,s)=>s[1]-a[1]).map(([a])=>a),t.length||(e.first=0),e}i(aiTotalsOf,"aiTotalsOf"),c(aiTotalsOf,"aiTotalsOf");export function aiRunsOf(t,e=!1){const o=new Map;for(const a of t){const s=o.get(a.run.key);s?s.push(a):o.set(a.run.key,[a])}return[...o.entries()].map(([a,s])=>{s.sort((r,l)=>(r.step??0)-(l.step??0)||r.at-l.at);const n=aiTotalsOf(s);return{key:a,from:s[0].run.from,calls:s,at:n.first,last:n.last,totals:n}}).sort((a,s)=>e?a.at-s.at:s.last-a.last)}i(aiRunsOf,"aiRunsOf"),c(aiRunsOf,"aiRunsOf");const d="(none)";function f(t,e){if(e==="agent")return t.agent;if(e==="action")return t.action??{key:"action:",name:"(no action)"};if(e==="run")return{key:t.run.key,name:t.agent.name};if(e==="thread")return t.thread?{key:t.thread.key,name:`thread ${t.thread.name}`}:{key:"thread:",name:"(no thread)"};if(e==="flow")return t.flowId?{key:`flow:${t.flowId}`,name:t.flowId}:t.requestId?{key:`request:${t.requestId}`,name:`request ${t.requestId}`}:{key:"flow:",name:"(no flow)"};if(e==="model")return{key:`model:${t.model??""}`,name:t.model??"(unknown model)"};if(e==="service")return{key:`service:${t.service}`,name:t.service};const o=e.slice(5),a=t.meta?.[o];return{key:`${e}=${a??""}`,name:a??d}}i(f,"m"),c(f,"keyOf");export function groupAiCalls(t,e,o){const a=new Map;for(const n of t){const r=f(n,e),l=a.get(r.key);l?l.rows.push(n):a.set(r.key,{...r,rows:[n]})}const s=e==="agent"||e==="action";return[...a.values()].map(n=>({key:n.key,name:n.name,...n.from?{from:n.from}:{},nameable:s&&/^(agent|action):./.test(n.key),merged:o?Object.entries(o.merge).filter(([,r])=>r===n.key).map(([r])=>r).sort():[],runs:aiRunsOf(n.rows,e==="flow"),totals:aiTotalsOf(n.rows)})).sort((n,r)=>r.totals.last-n.totals.last||n.name.localeCompare(r.name))}i(groupAiCalls,"groupAiCalls"),c(groupAiCalls,"groupAiCalls");export function matchesAi(t,e){const o=e.toLowerCase().split(/\s+/).filter(Boolean);if(!o.length)return!0;const a=[t.id,t.agent.name,t.action?.name,t.model,t.service,t.flowId,t.requestId,t.schema,t.asked,t.said,...t.called??[],...Object.entries(t.meta??{}).map(([s,n])=>`${s}:${n}`)].filter(Boolean).join(`
2
+ `).toLowerCase();return o.every(s=>a.includes(s))}i(matchesAi,"matchesAi"),c(matchesAi,"matchesAi");
@@ -1,3 +1,3 @@
1
- "use strict";var B=Object.defineProperty;var u=(e,o)=>B(e,"name",{value:o,configurable:!0});var S=Object.defineProperty,p=u((e,o)=>S(e,"name",{value:o,configurable:!0}),"u"),T=Object.defineProperty,l=p((e,o)=>T(e,"name",{value:o,configurable:!0}),"d");import{aiCallOf as z}from"./ai-call.js";import{aiContextOf as E,aiSplitOf as K}from"./ai-context.js";export const EMPTY_AI_NAMES={version:1,names:{},merge:{}};export function aiModelUses(e,o){const n=o.toLowerCase(),r=new Map;for(const t of e){if(t.host.toLowerCase()!==n)continue;const s=t.model??"unknown";let a=r.get(s);a||(a={use:{model:s,calls:0,failed:0,unmetered:0,input:0,cached:0,output:0,costUsd:0,priced:0,agents:0,first:t.at,last:t.at},agents:new Set},r.set(s,a));const i=a.use;i.calls+=1,t.failed&&(i.failed+=1),t.tokens?(i.input+=t.tokens.input??0,i.cached+=t.tokens.cached??0,i.output+=t.tokens.output??0):i.unmetered+=1,t.costUsd!==void 0&&(i.costUsd+=t.costUsd,i.priced+=1),a.agents.add(t.agent.key),i.first=Math.min(i.first,t.at),i.last=Math.max(i.last,t.at)}return[...r.values()].map(({use:t,agents:s})=>({...t,agents:s.size})).sort((t,s)=>s.calls-t.calls||s.last-t.last)}u(aiModelUses,"aiModelUses"),p(aiModelUses,"aiModelUses"),l(aiModelUses,"aiModelUses");export function aiAgentUses(e,o){const n=o?.toLowerCase(),r=new Map;for(const t of e){if(n!==void 0&&t.host.toLowerCase()!==n)continue;let s=r.get(t.agent.key);s||(s={use:{key:t.agent.key,name:t.agent.name,from:t.agent.from,calls:0,runs:0,failed:0,input:0,cached:0,written:0,output:0,costUsd:0,priced:0,split:{},models:[],last:t.at},runs:new Set,models:new Map},r.set(t.agent.key,s));const a=s.use;a.calls+=1,s.runs.add(t.run.key),t.failed&&(a.failed+=1),a.input+=t.tokens?.input??0,a.cached+=t.tokens?.cached??0,a.written+=t.tokens?.written??0,a.output+=t.tokens?.output??0,t.costUsd!==void 0&&(a.costUsd+=t.costUsd,a.priced+=1);for(const[i,d]of Object.entries(t.split??{}))a.split[i]=(a.split[i]??0)+d;t.model&&s.models.set(t.model,(s.models.get(t.model)??0)+1),a.last=Math.max(a.last,t.at)}return[...r.values()].map(({use:t,runs:s,models:a})=>({...t,runs:s.size,models:[...a].sort((i,d)=>d[1]-i[1]).map(([i])=>i)})).sort((t,s)=>s.input-t.input||s.calls-t.calls)}u(aiAgentUses,"aiAgentUses"),p(aiAgentUses,"aiAgentUses"),l(aiAgentUses,"aiAgentUses");export const MAX_TOOLS=40,MAX_THREAD_CALLS=300,MAX_META=24;const q=160,_="unknown service";export const aiKeyOf=l((e,o)=>`${e}:${o.normalize("NFKD").toLowerCase().replace(/[^a-z0-9:.]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80)||"unnamed"}`,"aiKeyOf");export function humanName(e){const o=e.trim();if(/[A-Z]/.test(o)||/ /.test(o))return o;const n=o.replace(/[-_.]+/g," ").trim();return n?n[0].toUpperCase()+n.slice(1):o}u(humanName,"humanName"),p(humanName,"humanName"),l(humanName,"humanName");const g=l((e,o=q)=>{if(!e)return;const n=e.replace(/\s+/g," ").trim();if(n)return n.length>o?`${n.slice(0,o-1)}\u2026`:n},"line");export function promptTitle(e){const o=e.split(`
2
- `).map(t=>t.trim()).find(Boolean)??"",n=/^#{1,6}\s+(.+)$/.exec(o);if(n){const t=n[1].split(/\s+[—–]\s+|\s+-\s+|:\s/)[0].replace(/[*_`]/g,"").trim();return t?t.slice(0,60):void 0}const r=/^you are (?:an? |the )?(.+?)(?:[.,;:!]|\s+(?:who|that|which|for|in|on|whose|with|and|following|using|working|based|at|to)\b|$)/i.exec(o);if(r){const t=r[1].trim().split(/\s+/);if(t.length>6||/^(?:going|about|given|now|here|responsible|able|allowed|expected|tasked|asked|helping|working|being|not)$/i.test(t[0]))return;const s=t.join(" ");return s[0].toUpperCase()+s.slice(1)}}u(promptTitle,"promptTitle"),p(promptTitle,"promptTitle"),l(promptTitle,"promptTitle");export function promptOpening(e){const o=e.split(`
3
- `).map(r=>r.trim()).find(Boolean);if(!o)return;const n=o.replace(/^[#>*\s-]+/,"").split(/\s+/).filter(Boolean);if(!(n.length<3))return n.length>7?`${n.slice(0,7).join(" ")} \u2026`:n.join(" ")}u(promptOpening,"promptOpening"),p(promptOpening,"promptOpening"),l(promptOpening,"promptOpening");export function actionName(e){const o=e.split("::")[0],n=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|[0-9a-f]{8,}|\d{4,})$/i;return o.split(":").map(r=>r.split(".").filter(t=>!n.test(t)).join(".")).filter((r,t,s)=>r||t<s.length-1).join(":").slice(0,120)}u(actionName,"actionName"),p(actionName,"actionName"),l(actionName,"actionName");const h=l((e,o)=>{const n=e.request.headers.find(([r])=>r.toLowerCase()===o)?.[1];if(n===void 0||!o.startsWith("x-lensmcp-")||!n.includes("%"))return n;try{return decodeURIComponent(n)}catch{return n}},"header"),R=l(e=>e!==void 0&&/^\d{1,6}$/.test(e.trim())?Number(e.trim()):void 0,"intOf"),k=l((e,...o)=>{for(const n of o)if(e[n]?.trim())return e[n].trim()},"first");function x(e){const o={};for(const n of e.settings)if(n.name.startsWith("metadata.")){if(Object.keys(o).length>=MAX_META)break;o[n.name.slice(9)]=n.value.slice(0,200)}return o}u(x,"j"),p(x,"S"),l(x,"metaOf");function $(e,o,n){const r=l((f,w)=>({key:aiKeyOf("agent",f),name:humanName(f),from:w}),"named"),t=k(n,"agent","agent_name","agentName","assistant");if(t)return r(t,"metadata");const s=h(e,"x-lensmcp-agent");if(s?.trim())return r(s.trim(),"header");const a=o.system.map(f=>promptTitle(f.text)).find(Boolean);if(a)return r(a,"prompt");const i=o.answer.format?.name;if(i)return r(i,"schema");const d=[...o.tools,...o.answer.toolCalls].map(f=>f.server).find(Boolean);if(d)return r(d,"tools");const c=o.system.map(f=>promptOpening(f.text)).find(Boolean);return c?{key:aiKeyOf("agent",`prompt ${c.replace(/ …$/,"")}`),name:c,from:"prompt"}:r(`${e.service??_} ${o.api==="embeddings"?"embeddings":o.model??o.api}`,"service")}u($,"U"),p($,"B"),l($,"agentOf");function O(e,o,n){const r=l((a,i)=>({key:aiKeyOf("action",a),name:a,from:i}),"named"),t=k(n,"act","action","task","step","operation");if(t&&actionName(t))return r(actionName(t),"metadata");const s=h(e,"x-lensmcp-action");if(s?.trim())return r(actionName(s.trim()),"header");if(o.answer.format?.name)return r(o.answer.format.name,"schema")}u(O,"_"),p(O,"E"),l(O,"actionOf");function I(e){if(e.kind==="message")return g(e.text);if(e.kind==="tool")return g(e.output!==void 0?`${e.tool} \u2192 ${e.output}`:`${e.tool}(${e.arguments})`)}u(I,"N"),p(I,"z"),l(I,"turnLine");function y(e){const o=e.answer;return o.error?g(`error: ${o.error}`):o.refusal?g(`refused: ${o.refusal}`):o.toolCalls.length?g(o.toolCalls.map(n=>`${n.tool}(${n.arguments})`).join(" \xB7 ")):e.embedding?`${e.embedding.vectors??e.embedding.count} vector${(e.embedding.vectors??e.embedding.count)===1?"":"s"}${e.embedding.dimensions?` \xD7 ${e.embedding.dimensions}`:""}`:g(o.text)}u(y,"v"),p(y,"A"),l(y,"saidLine");export function aiCallRow(e,o){const n=z(e);if(!n||!e.ai)return;const r=x(n),t=new Map(n.settings.map(m=>[m.name,m.value])),s=k(r,"run","run_id","runId"),a=h(e,"x-lensmcp-run")?.trim(),i=n.turns.filter(m=>m.kind==="tool").filter(m=>m.output!==void 0&&m.callId).map(m=>m.callId),d=n.answer.toolCalls.map(m=>m.callId).filter(m=>!!m),c=n.usage,f=c?{...c.input!==void 0?{input:c.input}:{},...c.cached?{cached:c.cached}:{},...c.written?{written:c.written}:{},...c.output!==void 0?{output:c.output}:{},...c.reasoning?{reasoning:c.reasoning}:{}}:void 0,w=n.shape==="embedding"||c?.input===void 0?{}:K(E(n,{sections:!1})),v=k(r,"thread","thread_id","threadId","conversation","conversation_id","conversationId","case","case_id","caseId"),b=h(e,"x-lensmcp-thread")?.trim(),M=k(r,"parent_run","parentRun","parent")??h(e,"x-lensmcp-parent")?.trim(),A=O(e,n,r),C=R(r.round),j=R(r.attempt),U=t.get("continues response"),N=[...n.turns].reverse().map(I).find(Boolean),L=n.answer.status==="failed"||!!n.answer.error||(e.status??0)>=400||!!e.error;return{id:e.id,at:e.startedAt,...e.durationMs!==void 0?{durationMs:e.durationMs}:{},...e.status!==void 0?{status:e.status}:{},...L?{failed:!0}:{},service:e.service??_,...e.flowId?{flowId:e.flowId}:{},...e.requestId?{requestId:e.requestId}:{},provider:e.ai.provider,host:e.host,api:n.api,shape:n.shape,...n.model?{model:n.model}:{},...e.response.stream?{streamed:!0}:{},...f&&Object.keys(f).length?{tokens:f}:{},...Object.keys(w).length?{split:w}:{},agent:$(e,n,r),run:s?{key:`run:${s}`,from:"metadata"}:a?{key:`run:${a}`,from:"header"}:{key:`run:${e.id}`,from:"alone"},...v?{thread:{key:`thread:${v}`,name:v,from:"metadata"}}:b?{thread:{key:`thread:${b}`,name:b,from:"header"}}:{},...M?{parent:`run:${M}`}:{},...C!==void 0?{round:C}:{},...j!==void 0?{attempt:j}:{},...A?{action:A}:{},...n.answer.format?.name?{schema:n.answer.format.name}:{},...n.tools.length?{tools:n.tools.slice(0,MAX_TOOLS).map(m=>m.name)}:{},...n.answer.toolCalls.length?{called:n.answer.toolCalls.map(m=>m.name)}:{},...d.length?{callIds:d}:{},...i.length?{answers:i}:{},...n.responseId?{responseId:n.responseId}:{},...U?{previousResponseId:U}:{},...Object.keys(r).length?{meta:r}:{},...n.gaps.some(m=>/kept to its first|cut/.test(m))?{cut:!0}:{},...o.content&&N?{asked:N}:{},...o.content&&y(n)?{said:y(n)}:{}}}u(aiCallRow,"aiCallRow"),p(aiCallRow,"aiCallRow"),l(aiCallRow,"aiCallRow");export function linkAiRuns(e){const o=[...e].sort((s,a)=>s.at-a.at||s.id.localeCompare(a.id)),n=new Map,r=new Map;for(const s of o){if(s.run.from==="alone"){const a=s.previousResponseId?n.get(s.previousResponseId):void 0,i=a?void 0:s.answers?.map(c=>r.get(c)).find(Boolean),d=a??i;if(d){const c=a?"chain":"tools";s.run={key:d.run.key,from:d.run.from==="alone"||d.run.from===c?c:d.run.from},d.run.from==="alone"&&(d.run={key:d.run.key,from:c})}}s.responseId&&n.set(s.responseId,s);for(const a of s.callIds??[])r.set(a,s)}const t=new Map;for(const s of o){const a=(t.get(s.run.key)??0)+1;t.set(s.run.key,a),s.step=a}return e}u(linkAiRuns,"linkAiRuns"),p(linkAiRuns,"linkAiRuns"),l(linkAiRuns,"linkAiRuns");export function mergedKey(e,o){let n=o;for(let r=0;r<8&&e.merge[n]&&e.merge[n]!==o;r++)n=e.merge[n];return n}u(mergedKey,"mergedKey"),p(mergedKey,"mergedKey"),l(mergedKey,"mergedKey");export function applyAiNames(e,o){if(!Object.keys(o.names).length&&!Object.keys(o.merge).length)return e;const n=new Map;for(const t of e)n.has(t.agent.key)||n.set(t.agent.key,t.agent),t.action&&!n.has(t.action.key)&&n.set(t.action.key,t.action);const r=l(t=>{const s=mergedKey(o,t.key),a=o.names[s];if(a)return{key:s,name:a,from:"renamed"};if(s===t.key)return t;const i=n.get(s);return{key:s,name:i?.name??humanName(s.replace(/^[a-z]+:/,"")),from:i?.from??t.from}},"resolve");for(const t of e)t.agent=r(t.agent),t.action&&(t.action=r(t.action));return e}u(applyAiNames,"applyAiNames"),p(applyAiNames,"applyAiNames"),l(applyAiNames,"applyAiNames");export function aiNamesOf(e){const o=e&&typeof e=="object"?e:{},n=l(r=>{const t={};if(r&&typeof r=="object"&&!Array.isArray(r))for(const[s,a]of Object.entries(r))/^(agent|action):/.test(s)&&typeof a=="string"&&a.trim()&&(t[s]=a.trim().slice(0,120));return t},"pick");return{version:1,names:n(o.names),merge:n(o.merge)}}u(aiNamesOf,"aiNamesOf"),p(aiNamesOf,"aiNamesOf"),l(aiNamesOf,"aiNamesOf");
1
+ "use strict";var R=Object.defineProperty;var u=(e,s)=>R(e,"name",{value:s,configurable:!0});var B=Object.defineProperty,c=u((e,s)=>B(e,"name",{value:s,configurable:!0}),"d");import{aiCallOf as S}from"./ai-call.js";import{aiContextOf as T,aiSplitOf as z}from"./ai-context.js";export const EMPTY_AI_NAMES={version:1,names:{},merge:{}};export function aiModelUses(e,s){const n=s.toLowerCase(),r=new Map;for(const t of e){if(t.host.toLowerCase()!==n)continue;const o=t.model??"unknown";let a=r.get(o);a||(a={use:{model:o,calls:0,failed:0,unmetered:0,input:0,cached:0,output:0,costUsd:0,priced:0,agents:0,first:t.at,last:t.at},agents:new Set},r.set(o,a));const i=a.use;i.calls+=1,t.failed&&(i.failed+=1),t.tokens?(i.input+=t.tokens.input??0,i.cached+=t.tokens.cached??0,i.output+=t.tokens.output??0):i.unmetered+=1,t.costUsd!==void 0&&(i.costUsd+=t.costUsd,i.priced+=1),a.agents.add(t.agent.key),i.first=Math.min(i.first,t.at),i.last=Math.max(i.last,t.at)}return[...r.values()].map(({use:t,agents:o})=>({...t,agents:o.size})).sort((t,o)=>o.calls-t.calls||o.last-t.last)}u(aiModelUses,"aiModelUses"),c(aiModelUses,"aiModelUses");export function aiAgentUses(e,s){const n=s?.toLowerCase(),r=new Map;for(const t of e){if(n!==void 0&&t.host.toLowerCase()!==n)continue;let o=r.get(t.agent.key);o||(o={use:{key:t.agent.key,name:t.agent.name,from:t.agent.from,calls:0,runs:0,failed:0,input:0,cached:0,written:0,output:0,costUsd:0,priced:0,split:{},models:[],last:t.at},runs:new Set,models:new Map},r.set(t.agent.key,o));const a=o.use;a.calls+=1,o.runs.add(t.run.key),t.failed&&(a.failed+=1),a.input+=t.tokens?.input??0,a.cached+=t.tokens?.cached??0,a.written+=t.tokens?.written??0,a.output+=t.tokens?.output??0,t.costUsd!==void 0&&(a.costUsd+=t.costUsd,a.priced+=1);for(const[i,m]of Object.entries(t.split??{}))a.split[i]=(a.split[i]??0)+m;t.model&&o.models.set(t.model,(o.models.get(t.model)??0)+1),a.last=Math.max(a.last,t.at)}return[...r.values()].map(({use:t,runs:o,models:a})=>({...t,runs:o.size,models:[...a].sort((i,m)=>m[1]-i[1]).map(([i])=>i)})).sort((t,o)=>o.input-t.input||o.calls-t.calls)}u(aiAgentUses,"aiAgentUses"),c(aiAgentUses,"aiAgentUses");export const MAX_TOOLS=40,MAX_THREAD_CALLS=300,MAX_META=24;const E=160,C="unknown service";export const aiKeyOf=c((e,s)=>`${e}:${s.normalize("NFKD").toLowerCase().replace(/[^a-z0-9:.]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80)||"unnamed"}`,"aiKeyOf");export function humanName(e){const s=e.trim();if(/[A-Z]/.test(s)||/ /.test(s))return s;const n=s.replace(/[-_.]+/g," ").trim();return n?n[0].toUpperCase()+n.slice(1):s}u(humanName,"humanName"),c(humanName,"humanName");const f=c((e,s=E)=>{if(!e)return;const n=e.replace(/\s+/g," ").trim();if(n)return n.length>s?`${n.slice(0,s-1)}\u2026`:n},"line");export function promptTitle(e){const s=e.split(`
2
+ `).map(t=>t.trim()).find(Boolean)??"",n=/^#{1,6}\s+(.+)$/.exec(s);if(n){const t=n[1].split(/\s+[—–]\s+|\s+-\s+|:\s/)[0].replace(/[*_`]/g,"").trim();return t?t.slice(0,60):void 0}const r=/^you are (?:an? |the )?(.+?)(?:[.,;:!]|\s+(?:who|that|which|for|in|on|whose|with|and|following|using|working|based|at|to)\b|$)/i.exec(s);if(r){const t=r[1].trim().split(/\s+/);if(t.length>6||/^(?:going|about|given|now|here|responsible|able|allowed|expected|tasked|asked|helping|working|being|not)$/i.test(t[0]))return;const o=t.join(" ");return o[0].toUpperCase()+o.slice(1)}}u(promptTitle,"promptTitle"),c(promptTitle,"promptTitle");export function promptOpening(e){const s=e.split(`
3
+ `).map(r=>r.trim()).find(Boolean);if(!s)return;const n=s.replace(/^[#>*\s-]+/,"").split(/\s+/).filter(Boolean);if(!(n.length<3))return n.length>7?`${n.slice(0,7).join(" ")} \u2026`:n.join(" ")}u(promptOpening,"promptOpening"),c(promptOpening,"promptOpening");export function actionName(e){const s=e.split("::")[0],n=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|[0-9a-f]{8,}|\d{4,})$/i;return s.split(":").map(r=>r.split(".").filter(t=>!n.test(t)).join(".")).filter((r,t,o)=>r||t<o.length-1).join(":").slice(0,120)}u(actionName,"actionName"),c(actionName,"actionName");const g=c((e,s)=>{const n=e.request.headers.find(([r])=>r.toLowerCase()===s)?.[1];if(n===void 0||!s.startsWith("x-lensmcp-")||!n.includes("%"))return n;try{return decodeURIComponent(n)}catch{return n}},"header"),A=c(e=>e!==void 0&&/^\d{1,6}$/.test(e.trim())?Number(e.trim()):void 0,"intOf"),h=c((e,...s)=>{for(const n of s)if(e[n]?.trim())return e[n].trim()},"first");function j(e){const s={};for(const n of e.settings)if(n.name.startsWith("metadata.")){if(Object.keys(s).length>=MAX_META)break;s[n.name.slice(9)]=n.value.slice(0,200)}return s}u(j,"S"),c(j,"metaOf");function U(e,s,n){const r=c((p,k)=>({key:aiKeyOf("agent",p),name:humanName(p),from:k}),"named"),t=h(n,"agent","agent_name","agentName","assistant");if(t)return r(t,"metadata");const o=g(e,"x-lensmcp-agent");if(o?.trim())return r(o.trim(),"header");const a=s.system.map(p=>promptTitle(p.text)).find(Boolean);if(a)return r(a,"prompt");const i=s.answer.format?.name;if(i)return r(i,"schema");const m=[...s.tools,...s.answer.toolCalls].map(p=>p.server).find(Boolean);if(m)return r(m,"tools");const l=s.system.map(p=>promptOpening(p.text)).find(Boolean);return l?{key:aiKeyOf("agent",`prompt ${l.replace(/ …$/,"")}`),name:l,from:"prompt"}:r(`${e.service??C} ${s.api==="embeddings"?"embeddings":s.model??s.api}`,"service")}u(U,"B"),c(U,"agentOf");function _(e,s,n){const r=c((a,i)=>({key:aiKeyOf("action",a),name:a,from:i}),"named"),t=h(n,"act","action","task","step","operation");if(t&&actionName(t))return r(actionName(t),"metadata");const o=g(e,"x-lensmcp-action");if(o?.trim())return r(actionName(o.trim()),"header");if(s.answer.format?.name)return r(s.answer.format.name,"schema")}u(_,"E"),c(_,"actionOf");function N(e){if(e.kind==="message")return f(e.text);if(e.kind==="tool")return f(e.output!==void 0?`${e.tool} \u2192 ${e.output}`:`${e.tool}(${e.arguments})`)}u(N,"z"),c(N,"turnLine");function v(e){const s=e.answer;return s.error?f(`error: ${s.error}`):s.refusal?f(`refused: ${s.refusal}`):s.toolCalls.length?f(s.toolCalls.map(n=>`${n.tool}(${n.arguments})`).join(" \xB7 ")):e.embedding?`${e.embedding.vectors??e.embedding.count} vector${(e.embedding.vectors??e.embedding.count)===1?"":"s"}${e.embedding.dimensions?` \xD7 ${e.embedding.dimensions}`:""}`:f(s.text)}u(v,"A"),c(v,"saidLine");export function aiCallRow(e,s){const n=S(e);if(!n||!e.ai)return;const r=j(n),t=new Map(n.settings.map(d=>[d.name,d.value])),o=h(r,"run","run_id","runId"),a=g(e,"x-lensmcp-run")?.trim(),i=n.turns.filter(d=>d.kind==="tool").filter(d=>d.output!==void 0&&d.callId).map(d=>d.callId),m=n.answer.toolCalls.map(d=>d.callId).filter(d=>!!d),l=n.usage,p=l?{...l.input!==void 0?{input:l.input}:{},...l.cached?{cached:l.cached}:{},...l.written?{written:l.written}:{},...l.output!==void 0?{output:l.output}:{},...l.reasoning?{reasoning:l.reasoning}:{}}:void 0,k=n.shape==="embedding"||l?.input===void 0?{}:z(T(n,{sections:!1})),w=h(r,"thread","thread_id","threadId","conversation","conversation_id","conversationId","case","case_id","caseId"),y=g(e,"x-lensmcp-thread")?.trim(),$=h(r,"parent_run","parentRun","parent")??g(e,"x-lensmcp-parent")?.trim(),x=_(e,n,r),b=A(r.round),I=A(r.attempt),O=t.get("continues response"),M=[...n.turns].reverse().map(N).find(Boolean),L=n.answer.status==="failed"||!!n.answer.error||(e.status??0)>=400||!!e.error;return{id:e.id,at:e.startedAt,...e.durationMs!==void 0?{durationMs:e.durationMs}:{},...e.status!==void 0?{status:e.status}:{},...L?{failed:!0}:{},service:e.service??C,...e.flowId?{flowId:e.flowId}:{},...e.requestId?{requestId:e.requestId}:{},provider:e.ai.provider,host:e.host,api:n.api,shape:n.shape,...n.model?{model:n.model}:{},...e.response.stream?{streamed:!0}:{},...p&&Object.keys(p).length?{tokens:p}:{},...Object.keys(k).length?{split:k}:{},agent:U(e,n,r),run:o?{key:`run:${o}`,from:"metadata"}:a?{key:`run:${a}`,from:"header"}:{key:`run:${e.id}`,from:"alone"},...w?{thread:{key:`thread:${w}`,name:w,from:"metadata"}}:y?{thread:{key:`thread:${y}`,name:y,from:"header"}}:{},...$?{parent:`run:${$}`}:{},...b!==void 0?{round:b}:{},...I!==void 0?{attempt:I}:{},...x?{action:x}:{},...n.answer.format?.name?{schema:n.answer.format.name}:{},...n.tools.length?{tools:n.tools.slice(0,MAX_TOOLS).map(d=>d.name)}:{},...n.answer.toolCalls.length?{called:n.answer.toolCalls.map(d=>d.name)}:{},...m.length?{callIds:m}:{},...i.length?{answers:i}:{},...n.responseId?{responseId:n.responseId}:{},...O?{previousResponseId:O}:{},...Object.keys(r).length?{meta:r}:{},...n.gaps.some(d=>/kept to its first|cut/.test(d))?{cut:!0}:{},...s.content&&M?{asked:M}:{},...s.content&&v(n)?{said:v(n)}:{}}}u(aiCallRow,"aiCallRow"),c(aiCallRow,"aiCallRow");export function linkAiRuns(e){const s=[...e].sort((o,a)=>o.at-a.at||o.id.localeCompare(a.id)),n=new Map,r=new Map;for(const o of s){if(o.run.from==="alone"){const a=o.previousResponseId?n.get(o.previousResponseId):void 0,i=a?void 0:o.answers?.map(l=>r.get(l)).find(Boolean),m=a??i;if(m){const l=a?"chain":"tools";o.run={key:m.run.key,from:m.run.from==="alone"||m.run.from===l?l:m.run.from},m.run.from==="alone"&&(m.run={key:m.run.key,from:l})}}o.responseId&&n.set(o.responseId,o);for(const a of o.callIds??[])r.set(a,o)}const t=new Map;for(const o of s){const a=(t.get(o.run.key)??0)+1;t.set(o.run.key,a),o.step=a}return e}u(linkAiRuns,"linkAiRuns"),c(linkAiRuns,"linkAiRuns");export function mergedKey(e,s){let n=s;for(let r=0;r<8&&e.merge[n]&&e.merge[n]!==s;r++)n=e.merge[n];return n}u(mergedKey,"mergedKey"),c(mergedKey,"mergedKey");export function applyAiNames(e,s){if(!Object.keys(s.names).length&&!Object.keys(s.merge).length)return e;const n=new Map;for(const t of e)n.has(t.agent.key)||n.set(t.agent.key,t.agent),t.action&&!n.has(t.action.key)&&n.set(t.action.key,t.action);const r=c(t=>{const o=mergedKey(s,t.key),a=s.names[o];if(a)return{key:o,name:a,from:"renamed"};if(o===t.key)return t;const i=n.get(o);return{key:o,name:i?.name??humanName(o.replace(/^[a-z]+:/,"")),from:i?.from??t.from}},"resolve");for(const t of e)t.agent=r(t.agent),t.action&&(t.action=r(t.action));return e}u(applyAiNames,"applyAiNames"),c(applyAiNames,"applyAiNames");export function aiNamesOf(e){const s=e&&typeof e=="object"?e:{},n=c(r=>{const t={};if(r&&typeof r=="object"&&!Array.isArray(r))for(const[o,a]of Object.entries(r))/^(agent|action):/.test(o)&&typeof a=="string"&&a.trim()&&(t[o]=a.trim().slice(0,120));return t},"pick");return{version:1,names:n(s.names),merge:n(s.merge)}}u(aiNamesOf,"aiNamesOf"),c(aiNamesOf,"aiNamesOf");
package/lib/ai-call.js CHANGED
@@ -1,19 +1,19 @@
1
- "use strict";var se=Object.defineProperty;var v=(t,o)=>se(t,"name",{value:o,configurable:!0});var ne=Object.defineProperty,k=v((t,o)=>ne(t,"name",{value:o,configurable:!0}),"v"),re=Object.defineProperty,_=k((t,o)=>re(t,"name",{value:o,configurable:!0}),"d");const $=_(t=>!!t&&typeof t=="object"&&!Array.isArray(t),"isObj"),e=_(t=>typeof t=="string"?t:void 0,"str"),h=_(t=>typeof t=="number"&&Number.isFinite(t)?t:void 0,"num"),w=_(t=>Array.isArray(t)?t:[],"arr"),c=_(t=>$(t)?t:{},"obj"),O=_(t=>typeof t=="string"?t:t===void 0?"":JSON.stringify(t),"json"),te=_(t=>t>=1024*1024?`${(t/1024/1024).toFixed(1)} MB`:`${Math.round(t/1024)} KB`,"kb");export const CUT_MARK="\u2026";export function parseJsonPrefix(t){try{return{value:JSON.parse(t),cut:!1}}catch{}const o=[];let n=0,l=!1,a=!1,r=!1;const s=t.length,i=_(m=>{const d=o[o.length-1];d&&(d.state="after"),n=m},"ended");for(let m=0;m<s;m++){const d=t[m];if(l){r?r=!1:d==="\\"?r=!0:d==='"'&&(l=!1,a?o[o.length-1].state="colon":i(m+1));continue}if(d===" "||d===`
2
- `||d==="\r"||d===" ")continue;const f=o[o.length-1];if(d==='"'){l=!0,a=!!f&&f.c==="{"&&f.state==="key";continue}if(d==="{"||d==="["){o.push({c:d,state:d==="{"?"key":"value"}),n=m+1;continue}if(d==="}"||d==="]"){o.pop(),i(m+1);continue}if(d===":"){f&&(f.state="value");continue}if(d===","){f&&(f.state=f.c==="{"?"key":"value");continue}let g=m;for(;g<s&&!`,}]
3
- \r `.includes(t[g]);)g++;if(g>=s)break;i(g),m=g-1}const u=o.map(m=>m.c==="{"?"}":"]").reverse().join("");if(l&&!a)for(let m=0;m<=6;m++)try{return{value:JSON.parse(`${t.slice(0,s-m)}${CUT_MARK}"${u}`),cut:!0}}catch{}if(n)try{return{value:JSON.parse(`${t.slice(0,n)}${u}`),cut:!0}}catch{return}}v(parseJsonPrefix,"parseJsonPrefix"),k(parseJsonPrefix,"parseJsonPrefix"),_(parseJsonPrefix,"parseJsonPrefix");export function aiApiOf(t){const o=t.split("?")[0].replace(/\/+$/,"");if(/\/responses$/.test(o))return"responses";if(/\/chat\/completions$/.test(o))return"chat";if(/\/embeddings$/.test(o))return"embeddings";if(/\/messages$/.test(o))return"messages"}v(aiApiOf,"aiApiOf"),k(aiApiOf,"aiApiOf"),_(aiApiOf,"aiApiOf");export function splitToolName(t,o){if(o)return{server:o,tool:t};const n=/^(?:mcp__)?([A-Za-z0-9-]+(?:_[A-Za-z0-9-]+)*)__(.+)$/.exec(t);return n?{server:n[1],tool:n[2]}:{tool:t}}v(splitToolName,"splitToolName"),k(splitToolName,"splitToolName"),_(splitToolName,"splitToolName");const A=_((t,o,n={})=>({...n.callId?{callId:n.callId}:{},name:t,...splitToolName(t,n.server),arguments:o,...n.output!==void 0?{output:n.output}:{},...n.error?{error:n.error}:{}}),"toolCall");function J(t,o,n){if(!t)return;if(t.omitted==="ai"){n.push(`The ${o==="request"?"prompt":"answer"} was not kept \u2014 an AI provider\u2019s bodies are kept only when asked for: Settings \u203A Features \u203A Capture \u203A AI calls, for the calls made after.`);return}if(t.omitted||t.text===void 0)return;const l=parseJsonPrefix(t.text);if(l)return(l.cut||t.truncated)&&n.push(`The ${o} was kept to its first ${te(t.kept)} of ${te(t.size)} \u2014 read as far as it goes; what follows is not shown (the ${o==="request"?"end of the conversation":"rest of the answer"}, marked ${CUT_MARK}).`),l.value}v(J,"M"),k(J,"E"),_(J,"readBody");function M(t){if(t.data===void 0||t.data==="[DONE]")return;const o=parseJsonPrefix(t.data);return o&&$(o.value)?{v:o.value,cut:o.cut}:void 0}v(M,"J"),k(M,"M"),_(M,"eventJson");function I(t){if(typeof t=="string")return{text:t,attachments:[]};const o=[],n=[];for(const l of w(t)){if(typeof l=="string"){o.push(l);continue}const a=c(l),r=e(a.type)??"",s=e(a.text)??e(a.refusal);s!==void 0?o.push(s):/image/.test(r)?n.push(e(a.detail)?`image (${e(a.detail)})`:"image"):/file|document/.test(r)?n.push(`file ${e(a.filename)??e(c(a.source).media_type)??e(a.file_id)??""}`.trim()):/audio/.test(r)?n.push("audio"):r&&n.push(r)}return{text:o.join(`
1
+ "use strict";var se=Object.defineProperty;var v=(t,s)=>se(t,"name",{value:s,configurable:!0});var oe=Object.defineProperty,_=v((t,s)=>oe(t,"name",{value:s,configurable:!0}),"d");const b=_(t=>!!t&&typeof t=="object"&&!Array.isArray(t),"isObj"),e=_(t=>typeof t=="string"?t:void 0,"str"),h=_(t=>typeof t=="number"&&Number.isFinite(t)?t:void 0,"num"),k=_(t=>Array.isArray(t)?t:[],"arr"),c=_(t=>b(t)?t:{},"obj"),A=_(t=>typeof t=="string"?t:t===void 0?"":JSON.stringify(t),"json"),U=_(t=>t>=1024*1024?`${(t/1024/1024).toFixed(1)} MB`:`${Math.round(t/1024)} KB`,"kb");export const CUT_MARK="\u2026";export function parseJsonPrefix(t){try{return{value:JSON.parse(t),cut:!1}}catch{}const s=[];let n=0,l=!1,a=!1,r=!1;const o=t.length,i=_(m=>{const d=s[s.length-1];d&&(d.state="after"),n=m},"ended");for(let m=0;m<o;m++){const d=t[m];if(l){r?r=!1:d==="\\"?r=!0:d==='"'&&(l=!1,a?s[s.length-1].state="colon":i(m+1));continue}if(d===" "||d===`
2
+ `||d==="\r"||d===" ")continue;const f=s[s.length-1];if(d==='"'){l=!0,a=!!f&&f.c==="{"&&f.state==="key";continue}if(d==="{"||d==="["){s.push({c:d,state:d==="{"?"key":"value"}),n=m+1;continue}if(d==="}"||d==="]"){s.pop(),i(m+1);continue}if(d===":"){f&&(f.state="value");continue}if(d===","){f&&(f.state=f.c==="{"?"key":"value");continue}let g=m;for(;g<o&&!`,}]
3
+ \r `.includes(t[g]);)g++;if(g>=o)break;i(g),m=g-1}const u=s.map(m=>m.c==="{"?"}":"]").reverse().join("");if(l&&!a)for(let m=0;m<=6;m++)try{return{value:JSON.parse(`${t.slice(0,o-m)}${CUT_MARK}"${u}`),cut:!0}}catch{}if(n)try{return{value:JSON.parse(`${t.slice(0,n)}${u}`),cut:!0}}catch{return}}v(parseJsonPrefix,"parseJsonPrefix"),_(parseJsonPrefix,"parseJsonPrefix");export function aiApiOf(t){const s=t.split("?")[0].replace(/\/+$/,"");if(/\/responses$/.test(s))return"responses";if(/\/chat\/completions$/.test(s))return"chat";if(/\/embeddings$/.test(s))return"embeddings";if(/\/messages$/.test(s))return"messages"}v(aiApiOf,"aiApiOf"),_(aiApiOf,"aiApiOf");export function splitToolName(t,s){if(s)return{server:s,tool:t};const n=/^(?:mcp__)?([A-Za-z0-9-]+(?:_[A-Za-z0-9-]+)*)__(.+)$/.exec(t);return n?{server:n[1],tool:n[2]}:{tool:t}}v(splitToolName,"splitToolName"),_(splitToolName,"splitToolName");const $=_((t,s,n={})=>({...n.callId?{callId:n.callId}:{},name:t,...splitToolName(t,n.server),arguments:s,...n.output!==void 0?{output:n.output}:{},...n.error?{error:n.error}:{}}),"toolCall");function M(t,s,n){if(!t)return;if(t.omitted==="ai"){n.push(`The ${s==="request"?"prompt":"answer"} was not kept \u2014 an AI provider\u2019s bodies are kept only when asked for: Settings \u203A Features \u203A Capture \u203A AI calls, for the calls made after.`);return}if(t.omitted||t.text===void 0)return;const l=parseJsonPrefix(t.text);if(l)return(l.cut||t.truncated)&&n.push(`The ${s} was kept to its first ${U(t.kept)} of ${U(t.size)} \u2014 read as far as it goes; what follows is not shown (the ${s==="request"?"end of the conversation":"rest of the answer"}, marked ${CUT_MARK}).`),l.value}v(M,"E"),_(M,"readBody");function J(t){if(t.data===void 0||t.data==="[DONE]")return;const s=parseJsonPrefix(t.data);return s&&b(s.value)?{v:s.value,cut:s.cut}:void 0}v(J,"M"),_(J,"eventJson");function I(t){if(typeof t=="string")return{text:t,attachments:[]};const s=[],n=[];for(const l of k(t)){if(typeof l=="string"){s.push(l);continue}const a=c(l),r=e(a.type)??"",o=e(a.text)??e(a.refusal);o!==void 0?s.push(o):/image/.test(r)?n.push(e(a.detail)?`image (${e(a.detail)})`:"image"):/file|document/.test(r)?n.push(`file ${e(a.filename)??e(c(a.source).media_type)??e(a.file_id)??""}`.trim()):/audio/.test(r)?n.push("audio"):r&&n.push(r)}return{text:s.join(`
4
4
 
5
- `),attachments:n}}v(I,"I"),k(I,"I"),_(I,"contentOf");const q=_(t=>typeof t=="string"?t:Array.isArray(t)&&I(t).text||O(t),"outputOf");function C(t,o){const n=[];for(const[a,r]of o){let s=t;for(const u of a.split("."))s=c(s)[u];if(s==null)continue;const i=typeof s=="string"?s:typeof s=="number"||typeof s=="boolean"?String(s):$(s)&&e(s.name)?`${e(s.type)??"tool"} ${e(s.name)}`:$(s)&&e(s.type)?e(s.type):JSON.stringify(s);n.push({name:r,value:i})}const l=c(t.metadata);for(const[a,r]of Object.entries(l))n.push({name:`metadata.${a}`,value:typeof r=="string"?r:JSON.stringify(r)});return n}v(C,"C"),k(C,"O"),_(C,"settingsOf");function S(t,o,n,l){const a=o?t.byCallId.get(o):void 0;if(a){a.output=n,l&&(a.error=l);return}t.call.turns.push({kind:"tool",...A("(an earlier call)","",{callId:o,output:n,error:l})})}v(S,"O"),k(S,"T"),_(S,"addOutput");function j(t,o){const n={kind:"tool",...o};t.call.turns.push(n),o.callId&&t.byCallId.set(o.callId,n)}v(j,"j"),k(j,"S"),_(j,"addCall");const ae=[["reasoning.effort","reasoning effort"],["reasoning.summary","reasoning summary"],["max_output_tokens","max output tokens"],["temperature","temperature"],["top_p","top_p"],["tool_choice","tool choice"],["parallel_tool_calls","parallel tool calls"],["text.verbosity","verbosity"],["truncation","truncation"],["previous_response_id","continues response"],["store","store"],["service_tier","service tier"],["stream","stream"],["prompt_cache_key","prompt cache key"],["user","user"],["safety_identifier","safety identifier"]],oe=_(t=>O(Object.fromEntries(Object.entries(t).filter(([o])=>o!=="type"&&o!=="id"&&o!=="status"))),"builtInCall");function L(t,o){const n=e(o.type)??(o.role?"message":"");if(n==="message"){const l=e(o.role)??"user",{text:a,attachments:r}=I(o.content);l==="system"?t.call.system.push({source:"system message",text:a}):t.call.turns.push({kind:"message",role:l,text:a,...r.length?{attachments:r}:{}})}else if(n==="function_call"||n==="custom_tool_call")j(t,A(e(o.name)??"?",e(o.arguments)??O(o.input),{callId:e(o.call_id)}));else if(n==="function_call_output"||n==="custom_tool_call_output"||n==="computer_call_output"||n==="local_shell_call_output")S(t,e(o.call_id),q(o.output));else if(n==="mcp_call")j(t,A(e(o.name)??"?",e(o.arguments)??"",{callId:e(o.id),server:e(o.server_label),...o.output!==void 0&&o.output!==null?{output:q(o.output)}:{},error:e(o.error)}));else if(n==="mcp_list_tools"){const l=w(o.tools).map(a=>e(c(a).name)).filter(Boolean);j(t,A("list_tools","",{server:e(o.server_label),output:l.join(", ")}))}else if(n==="reasoning"){const l=w(o.summary).map(a=>e(c(a).text)).filter(Boolean).join(`
5
+ `),attachments:n}}v(I,"I"),_(I,"contentOf");const N=_(t=>typeof t=="string"?t:Array.isArray(t)&&I(t).text||A(t),"outputOf");function C(t,s){const n=[];for(const[a,r]of s){let o=t;for(const u of a.split("."))o=c(o)[u];if(o==null)continue;const i=typeof o=="string"?o:typeof o=="number"||typeof o=="boolean"?String(o):b(o)&&e(o.name)?`${e(o.type)??"tool"} ${e(o.name)}`:b(o)&&e(o.type)?e(o.type):JSON.stringify(o);n.push({name:r,value:i})}const l=c(t.metadata);for(const[a,r]of Object.entries(l))n.push({name:`metadata.${a}`,value:typeof r=="string"?r:JSON.stringify(r)});return n}v(C,"O"),_(C,"settingsOf");function O(t,s,n,l){const a=s?t.byCallId.get(s):void 0;if(a){a.output=n,l&&(a.error=l);return}t.call.turns.push({kind:"tool",...$("(an earlier call)","",{callId:s,output:n,error:l})})}v(O,"T"),_(O,"addOutput");function j(t,s){const n={kind:"tool",...s};t.call.turns.push(n),s.callId&&t.byCallId.set(s.callId,n)}v(j,"S"),_(j,"addCall");const ne=[["reasoning.effort","reasoning effort"],["reasoning.summary","reasoning summary"],["max_output_tokens","max output tokens"],["temperature","temperature"],["top_p","top_p"],["tool_choice","tool choice"],["parallel_tool_calls","parallel tool calls"],["text.verbosity","verbosity"],["truncation","truncation"],["previous_response_id","continues response"],["store","store"],["service_tier","service tier"],["stream","stream"],["prompt_cache_key","prompt cache key"],["user","user"],["safety_identifier","safety identifier"]],W=_(t=>A(Object.fromEntries(Object.entries(t).filter(([s])=>s!=="type"&&s!=="id"&&s!=="status"))),"builtInCall");function Z(t,s){const n=e(s.type)??(s.role?"message":"");if(n==="message"){const l=e(s.role)??"user",{text:a,attachments:r}=I(s.content);l==="system"?t.call.system.push({source:"system message",text:a}):t.call.turns.push({kind:"message",role:l,text:a,...r.length?{attachments:r}:{}})}else if(n==="function_call"||n==="custom_tool_call")j(t,$(e(s.name)??"?",e(s.arguments)??A(s.input),{callId:e(s.call_id)}));else if(n==="function_call_output"||n==="custom_tool_call_output"||n==="computer_call_output"||n==="local_shell_call_output")O(t,e(s.call_id),N(s.output));else if(n==="mcp_call")j(t,$(e(s.name)??"?",e(s.arguments)??"",{callId:e(s.id),server:e(s.server_label),...s.output!==void 0&&s.output!==null?{output:N(s.output)}:{},error:e(s.error)}));else if(n==="mcp_list_tools"){const l=k(s.tools).map(a=>e(c(a).name)).filter(Boolean);j(t,$("list_tools","",{server:e(s.server_label),output:l.join(", ")}))}else if(n==="reasoning"){const l=k(s.summary).map(a=>e(c(a).text)).filter(Boolean).join(`
6
6
 
7
- `);t.call.turns.push({kind:"reasoning",...l?{text:l}:{}})}else n&&j(t,A(n.replace(/_call$/,""),oe(o),{callId:e(o.call_id)??e(o.id)}))}v(L,"Z"),k(L,"R"),_(L,"responsesItem");function U(t){return w(t.tools).map(o=>{const n=c(o),l=e(n.type)??"function";if(l==="mcp"){const r=e(n.server_label)??"mcp",s=w(n.allowed_tools).map(i=>e(i)).filter(Boolean);return{name:r,server:r,tool:s.length?s.join(", "):"every tool",type:l,...e(n.server_description)??e(n.server_url)?{description:e(n.server_description)??e(n.server_url)}:{},called:0}}const a=e(n.name)??l;return{name:a,...splitToolName(a),type:l,...e(n.description)?{description:e(n.description)}:{},...n.parameters!==void 0?{parameters:n.parameters}:{},...typeof n.strict=="boolean"?{strict:n.strict}:{},called:0}})}v(U,"D"),k(U,"W"),_(U,"responsesTools");function P(t,o){const n=t.call.answer;e(o.status)&&(n.status=e(o.status));const l=e(c(o.incomplete_details).reason);l&&(n.finish=l);const a=c(o.error);e(a.message)&&(n.error=e(a.message)),e(o.model)&&(t.call.model??=e(o.model)),e(o.id)&&(t.call.responseId=e(o.id)),E(t,w(o.output).map(c));const r=c(o.usage);Object.keys(r).length&&(t.call.usage={...h(r.input_tokens)!==void 0?{input:h(r.input_tokens)}:{},...h(c(r.input_tokens_details).cached_tokens)!==void 0?{cached:h(c(r.input_tokens_details).cached_tokens)}:{},...h(c(r.input_tokens_details).cache_write_tokens)?{written:h(c(r.input_tokens_details).cache_write_tokens)}:{},...h(r.output_tokens)!==void 0?{output:h(r.output_tokens)}:{},...h(c(r.output_tokens_details).reasoning_tokens)!==void 0?{reasoning:h(c(r.output_tokens_details).reasoning_tokens)}:{},...h(r.total_tokens)!==void 0?{total:h(r.total_tokens)}:{}})}v(P,"q"),k(P,"z"),_(P,"responsesAnswer");function E(t,o){const n=t.call.answer,l=[],a=[];for(const r of o){const s=e(r.type);if(s==="message")for(const i of w(r.content).map(c))e(i.refusal)?n.refusal=e(i.refusal):e(i.text)!==void 0&&l.push(e(i.text));else if(s==="function_call"||s==="custom_tool_call")n.toolCalls.push(A(e(r.name)??"?",e(r.arguments)??O(r.input),{callId:e(r.call_id)}));else if(s==="mcp_call")n.toolCalls.push(A(e(r.name)??"?",e(r.arguments)??"",{callId:e(r.id),server:e(r.server_label),...r.output!==void 0&&r.output!==null?{output:q(r.output)}:{},error:e(r.error)}));else if(s==="reasoning"){const i=w(r.summary).map(u=>e(c(u).text)).filter(Boolean).join(`
7
+ `);t.call.turns.push({kind:"reasoning",...l?{text:l}:{}})}else n&&j(t,$(n.replace(/_call$/,""),W(s),{callId:e(s.call_id)??e(s.id)}))}v(Z,"R"),_(Z,"responsesItem");function D(t){return k(t.tools).map(s=>{const n=c(s),l=e(n.type)??"function";if(l==="mcp"){const r=e(n.server_label)??"mcp",o=k(n.allowed_tools).map(i=>e(i)).filter(Boolean);return{name:r,server:r,tool:o.length?o.join(", "):"every tool",type:l,...e(n.server_description)??e(n.server_url)?{description:e(n.server_description)??e(n.server_url)}:{},called:0}}const a=e(n.name)??l;return{name:a,...splitToolName(a),type:l,...e(n.description)?{description:e(n.description)}:{},...n.parameters!==void 0?{parameters:n.parameters}:{},...typeof n.strict=="boolean"?{strict:n.strict}:{},called:0}})}v(D,"W"),_(D,"responsesTools");function q(t,s){const n=t.call.answer;e(s.status)&&(n.status=e(s.status));const l=e(c(s.incomplete_details).reason);l&&(n.finish=l);const a=c(s.error);e(a.message)&&(n.error=e(a.message)),e(s.model)&&(t.call.model??=e(s.model)),e(s.id)&&(t.call.responseId=e(s.id)),E(t,k(s.output).map(c));const r=c(s.usage);Object.keys(r).length&&(t.call.usage={...h(r.input_tokens)!==void 0?{input:h(r.input_tokens)}:{},...h(c(r.input_tokens_details).cached_tokens)!==void 0?{cached:h(c(r.input_tokens_details).cached_tokens)}:{},...h(c(r.input_tokens_details).cache_write_tokens)?{written:h(c(r.input_tokens_details).cache_write_tokens)}:{},...h(r.output_tokens)!==void 0?{output:h(r.output_tokens)}:{},...h(c(r.output_tokens_details).reasoning_tokens)!==void 0?{reasoning:h(c(r.output_tokens_details).reasoning_tokens)}:{},...h(r.total_tokens)!==void 0?{total:h(r.total_tokens)}:{}})}v(q,"z"),_(q,"responsesAnswer");function E(t,s){const n=t.call.answer,l=[],a=[];for(const r of s){const o=e(r.type);if(o==="message")for(const i of k(r.content).map(c))e(i.refusal)?n.refusal=e(i.refusal):e(i.text)!==void 0&&l.push(e(i.text));else if(o==="function_call"||o==="custom_tool_call")n.toolCalls.push($(e(r.name)??"?",e(r.arguments)??A(r.input),{callId:e(r.call_id)}));else if(o==="mcp_call")n.toolCalls.push($(e(r.name)??"?",e(r.arguments)??"",{callId:e(r.id),server:e(r.server_label),...r.output!==void 0&&r.output!==null?{output:N(r.output)}:{},error:e(r.error)}));else if(o==="reasoning"){const i=k(r.summary).map(u=>e(c(u).text)).filter(Boolean).join(`
8
8
 
9
- `);i&&a.push(i)}else s&&s!=="mcp_list_tools"&&n.toolCalls.push(A(s.replace(/_call$/,""),oe(r),{callId:e(r.call_id)??e(r.id)}))}l.length&&(n.text=l.join(`
9
+ `);i&&a.push(i)}else o&&o!=="mcp_list_tools"&&n.toolCalls.push($(o.replace(/_call$/,""),W(r),{callId:e(r.call_id)??e(r.id)}))}l.length&&(n.text=l.join(`
10
10
 
11
11
  `)),a.length&&(n.reasoning=a.join(`
12
12
 
13
- `))}v(E,"E"),k(E,"F"),_(E,"responsesOutput");function W(t,o,n){let l,a=0;const r=new Map,s=new Set,i=new Map,u=new Map,m=new Map;for(const f of o){const g=M(f);if(!g)continue;g.cut&&a++;const p=g.v,y=e(p.type)??f.event,x=h(p.output_index)??0;if(y==="response.completed"||y==="response.incomplete"||y==="response.failed"){if(!g.cut&&$(p.response))l=p.response;else if($(p.response)){const b=p.response;e(b.status)&&(t.call.answer.status=e(b.status))}}else if(y==="response.created"||y==="response.in_progress"){const b=c(p.response);e(b.model)&&(t.call.model??=e(b.model)),e(b.id)&&(t.call.responseId??=e(b.id))}else y==="response.output_item.added"||y==="response.output_item.done"?$(p.item)&&(!s.has(x)||!g.cut)&&(r.set(x,{...r.get(x)??{},...p.item}),y.endsWith(".done")&&!g.cut&&s.add(x)):y==="response.output_text.delta"||y==="response.refusal.delta"?i.set(x,(i.get(x)??"")+(e(p.delta)??"")):y==="response.output_text.done"&&!g.cut&&e(p.text)!==void 0?i.set(x,e(p.text)):y==="response.function_call_arguments.delta"||y==="response.custom_tool_call_input.delta"||y==="response.mcp_call_arguments.delta"?u.set(x,(u.get(x)??"")+(e(p.delta)??"")):(y==="response.function_call_arguments.done"||y==="response.mcp_call_arguments.done")&&!g.cut&&e(p.arguments)!==void 0?u.set(x,e(p.arguments)):y==="response.reasoning_summary_text.delta"?m.set(x,(m.get(x)??"")+(e(p.delta)??"")):(y==="error"||y==="response.error")&&(t.call.answer.error=e(p.message)??e(c(p.error).message)??"the stream reported an error")}if(l){P(t,l);return}const d=[...r.entries()].sort(([f],[g])=>f-g).map(([f,g])=>{if(s.has(f))return g;const p=e(g.type);return p==="message"&&i.has(f)?{...g,content:[{type:"output_text",text:i.get(f)}]}:(p==="function_call"||p==="mcp_call")&&u.has(f)?{...g,arguments:u.get(f)}:p==="custom_tool_call"&&u.has(f)?{...g,input:u.get(f)}:p==="reasoning"&&m.has(f)?{...g,summary:[{type:"summary_text",text:m.get(f)}]}:g});for(const[f,g]of i)r.has(f)||d.push({type:"message",content:[{type:"output_text",text:g}]});E(t,d),t.call.answer.status||(t.call.answer.status=d.length?"completed":"unknown"),a&&n.push(`${a} of the stream\u2019s events were kept to their first 4 KB, so the answer was rebuilt from its pieces${t.call.usage?"":" \u2014 its token counts came in the last event, which was cut"}.`)}v(W,"H"),k(W,"Z"),_(W,"responsesStream");function Z(t,o,n,l){const a=t.call;e(o.model)&&(a.model=e(o.model)),e(o.instructions)&&a.system.push({source:"instructions",text:e(o.instructions)});const r=o.input;if(typeof r=="string")a.turns.push({kind:"message",role:"user",text:r});else for(const i of w(r))$(i)&&L(t,i);a.tools=U(o),a.settings=C(o,ae);const s=c(c(o.text).format);e(s.type)&&s.type!=="text"&&(a.answer.format={type:e(s.type),...e(s.name)?{name:e(s.name)}:{},...s.schema!==void 0?{schema:s.schema}:{},...typeof s.strict=="boolean"?{strict:s.strict}:{}}),B(t,n,l,i=>P(t,i),i=>W(t,i,l))}v(Z,"R"),k(Z,"D"),_(Z,"responsesCall");const ie=[["reasoning_effort","reasoning effort"],["max_completion_tokens","max completion tokens"],["max_tokens","max tokens"],["temperature","temperature"],["top_p","top_p"],["tool_choice","tool choice"],["parallel_tool_calls","parallel tool calls"],["n","n"],["seed","seed"],["stop","stop"],["presence_penalty","presence penalty"],["frequency_penalty","frequency penalty"],["verbosity","verbosity"],["store","store"],["service_tier","service tier"],["stream","stream"],["user","user"]];function z(t){const o=w(t.tool_calls).map(c).map(l=>{const a=c(l.function);return A(e(a.name)??e(c(l.custom).name)??"?",e(a.arguments)??e(c(l.custom).input)??"",{callId:e(l.id)})}),n=c(t.function_call);return e(n.name)&&o.push(A(e(n.name),e(n.arguments)??"",{})),o}v(z,"K"),k(z,"G"),_(z,"chatCalls");function F(t,o){const n=t.call.answer;e(o.model)&&(t.call.model??=e(o.model)),e(o.id)&&(t.call.responseId??=e(o.id));const l=c(w(o.choices)[0]),a=c(l.message),r=I(a.content).text;r&&(n.text=r),e(a.refusal)&&(n.refusal=e(a.refusal));const s=e(a.reasoning_content)??e(a.reasoning);s&&(n.reasoning=s),n.toolCalls.push(...z(a)),e(l.finish_reason)&&(n.finish=e(l.finish_reason)),n.status=n.finish?"completed":n.status??"unknown";const i=c(o.error);e(i.message)&&(n.error=e(i.message));const u=c(o.usage);Object.keys(u).length&&(t.call.usage={...h(u.prompt_tokens)!==void 0?{input:h(u.prompt_tokens)}:{},...h(c(u.prompt_tokens_details).cached_tokens)!==void 0?{cached:h(c(u.prompt_tokens_details).cached_tokens)}:{},...h(c(u.prompt_tokens_details).cache_write_tokens)?{written:h(c(u.prompt_tokens_details).cache_write_tokens)}:{},...h(u.completion_tokens)!==void 0?{output:h(u.completion_tokens)}:{},...h(c(u.completion_tokens_details).reasoning_tokens)!==void 0?{reasoning:h(c(u.completion_tokens_details).reasoning_tokens)}:{},...h(u.total_tokens)!==void 0?{total:h(u.total_tokens)}:{}})}v(F,"z"),k(F,"L"),_(F,"chatAnswer");function D(t,o,n){let l="",a="",r="",s,i,u,m,d=0;const f=new Map;for(const p of o){const y=M(p);if(!y)continue;y.cut&&d++,u??=e(y.v.model),m??=e(y.v.id),$(y.v.usage)&&(i=y.v.usage),$(y.v.error)&&(t.call.answer.error=e(y.v.error.message)??"the stream reported an error");const x=c(w(y.v.choices)[0]),b=c(x.delta);l+=e(b.content)??"",a+=e(b.reasoning_content)??e(b.reasoning)??"",r+=e(b.refusal)??"";for(const N of w(b.tool_calls).map(c)){const Y=h(N.index)??0,T=f.get(Y)??{name:"",args:""},ee=c(N.function);e(N.id)&&(T.id=e(N.id)),T.name+=e(ee.name)??"",T.args+=e(ee.arguments)??"",f.set(Y,T)}e(x.finish_reason)&&(s=e(x.finish_reason))}const g={content:l,...a?{reasoning_content:a}:{},...r?{refusal:r}:{},tool_calls:[...f.entries()].sort(([p],[y])=>p-y).map(([,p])=>({id:p.id,function:{name:p.name,arguments:p.args}}))};F(t,{...u?{model:u}:{},...m?{id:m}:{},choices:[{message:g,...s?{finish_reason:s}:{}}],...i?{usage:i}:{}}),d&&n.push(`${d} of the stream\u2019s chunks were kept to their first 4 KB \u2014 the answer was joined from what was kept of them.`)}v(D,"G"),k(D,"V"),_(D,"chatStream");function R(t,o,n,l){const a=t.call;e(o.model)&&(a.model=e(o.model));for(const s of w(o.messages).map(c)){const i=e(s.role)??"user",{text:u,attachments:m}=I(s.content);if(i==="system")a.system.push({source:"system message",text:u});else if(i==="tool")S(t,e(s.tool_call_id),u);else if(i==="function")S(t,void 0,u);else{(u||m.length||i!=="assistant")&&a.turns.push({kind:"message",role:i,text:u,...m.length?{attachments:m}:{}});for(const d of z(s))j(t,d)}}a.tools=[...w(o.tools).map(c),...w(o.functions).map(s=>({type:"function",function:s}))].map(s=>{const i=c(s.function),u=e(s.type)??"function",m=e(i.name)??e(c(s.custom).name)??u;return{name:m,...splitToolName(m),type:u,...e(i.description)??e(c(s.custom).description)?{description:e(i.description)??e(c(s.custom).description)}:{},...i.parameters!==void 0?{parameters:i.parameters}:{},...typeof i.strict=="boolean"?{strict:i.strict}:{},called:0}}),a.settings=C(o,ie);const r=c(o.response_format);if(e(r.type)&&r.type!=="text"){const s=c(r.json_schema);a.answer.format={type:e(r.type),...e(s.name)?{name:e(s.name)}:{},...s.schema!==void 0?{schema:s.schema}:{},...typeof s.strict=="boolean"?{strict:s.strict}:{}}}B(t,n,l,s=>F(t,s),s=>D(t,s,l))}v(R,"Q"),k(R,"X"),_(R,"chatCall");const le=[["max_tokens","max tokens"],["thinking.budget_tokens","thinking budget"],["temperature","temperature"],["top_p","top_p"],["top_k","top_k"],["tool_choice","tool choice"],["stop_sequences","stop sequences"],["stream","stream"],["metadata.user_id","user"]];function G(t,o,n){if(typeof n=="string"){t.call.turns.push({kind:"message",role:o,text:n});return}const l=[],a=[],r=_(()=>{(l.length||a.length)&&t.call.turns.push({kind:"message",role:o,text:l.join(`
13
+ `))}v(E,"F"),_(E,"responsesOutput");function H(t,s,n){let l,a=0;const r=new Map,o=new Set,i=new Map,u=new Map,m=new Map;for(const f of s){const g=J(f);if(!g)continue;g.cut&&a++;const p=g.v,y=e(p.type)??f.event,w=h(p.output_index)??0;if(y==="response.completed"||y==="response.incomplete"||y==="response.failed"){if(!g.cut&&b(p.response))l=p.response;else if(b(p.response)){const x=p.response;e(x.status)&&(t.call.answer.status=e(x.status))}}else if(y==="response.created"||y==="response.in_progress"){const x=c(p.response);e(x.model)&&(t.call.model??=e(x.model)),e(x.id)&&(t.call.responseId??=e(x.id))}else y==="response.output_item.added"||y==="response.output_item.done"?b(p.item)&&(!o.has(w)||!g.cut)&&(r.set(w,{...r.get(w)??{},...p.item}),y.endsWith(".done")&&!g.cut&&o.add(w)):y==="response.output_text.delta"||y==="response.refusal.delta"?i.set(w,(i.get(w)??"")+(e(p.delta)??"")):y==="response.output_text.done"&&!g.cut&&e(p.text)!==void 0?i.set(w,e(p.text)):y==="response.function_call_arguments.delta"||y==="response.custom_tool_call_input.delta"||y==="response.mcp_call_arguments.delta"?u.set(w,(u.get(w)??"")+(e(p.delta)??"")):(y==="response.function_call_arguments.done"||y==="response.mcp_call_arguments.done")&&!g.cut&&e(p.arguments)!==void 0?u.set(w,e(p.arguments)):y==="response.reasoning_summary_text.delta"?m.set(w,(m.get(w)??"")+(e(p.delta)??"")):(y==="error"||y==="response.error")&&(t.call.answer.error=e(p.message)??e(c(p.error).message)??"the stream reported an error")}if(l){q(t,l);return}const d=[...r.entries()].sort(([f],[g])=>f-g).map(([f,g])=>{if(o.has(f))return g;const p=e(g.type);return p==="message"&&i.has(f)?{...g,content:[{type:"output_text",text:i.get(f)}]}:(p==="function_call"||p==="mcp_call")&&u.has(f)?{...g,arguments:u.get(f)}:p==="custom_tool_call"&&u.has(f)?{...g,input:u.get(f)}:p==="reasoning"&&m.has(f)?{...g,summary:[{type:"summary_text",text:m.get(f)}]}:g});for(const[f,g]of i)r.has(f)||d.push({type:"message",content:[{type:"output_text",text:g}]});E(t,d),t.call.answer.status||(t.call.answer.status=d.length?"completed":"unknown"),a&&n.push(`${a} of the stream\u2019s events were kept to their first 4 KB, so the answer was rebuilt from its pieces${t.call.usage?"":" \u2014 its token counts came in the last event, which was cut"}.`)}v(H,"Z"),_(H,"responsesStream");function R(t,s,n,l){const a=t.call;e(s.model)&&(a.model=e(s.model)),e(s.instructions)&&a.system.push({source:"instructions",text:e(s.instructions)});const r=s.input;if(typeof r=="string")a.turns.push({kind:"message",role:"user",text:r});else for(const i of k(r))b(i)&&Z(t,i);a.tools=D(s),a.settings=C(s,ne);const o=c(c(s.text).format);e(o.type)&&o.type!=="text"&&(a.answer.format={type:e(o.type),...e(o.name)?{name:e(o.name)}:{},...o.schema!==void 0?{schema:o.schema}:{},...typeof o.strict=="boolean"?{strict:o.strict}:{}}),T(t,n,l,i=>q(t,i),i=>H(t,i,l))}v(R,"D"),_(R,"responsesCall");const re=[["reasoning_effort","reasoning effort"],["max_completion_tokens","max completion tokens"],["max_tokens","max tokens"],["temperature","temperature"],["top_p","top_p"],["tool_choice","tool choice"],["parallel_tool_calls","parallel tool calls"],["n","n"],["seed","seed"],["stop","stop"],["presence_penalty","presence penalty"],["frequency_penalty","frequency penalty"],["verbosity","verbosity"],["store","store"],["service_tier","service tier"],["stream","stream"],["user","user"]];function K(t){const s=k(t.tool_calls).map(c).map(l=>{const a=c(l.function);return $(e(a.name)??e(c(l.custom).name)??"?",e(a.arguments)??e(c(l.custom).input)??"",{callId:e(l.id)})}),n=c(t.function_call);return e(n.name)&&s.push($(e(n.name),e(n.arguments)??"",{})),s}v(K,"G"),_(K,"chatCalls");function z(t,s){const n=t.call.answer;e(s.model)&&(t.call.model??=e(s.model)),e(s.id)&&(t.call.responseId??=e(s.id));const l=c(k(s.choices)[0]),a=c(l.message),r=I(a.content).text;r&&(n.text=r),e(a.refusal)&&(n.refusal=e(a.refusal));const o=e(a.reasoning_content)??e(a.reasoning);o&&(n.reasoning=o),n.toolCalls.push(...K(a)),e(l.finish_reason)&&(n.finish=e(l.finish_reason)),n.status=n.finish?"completed":n.status??"unknown";const i=c(s.error);e(i.message)&&(n.error=e(i.message));const u=c(s.usage);Object.keys(u).length&&(t.call.usage={...h(u.prompt_tokens)!==void 0?{input:h(u.prompt_tokens)}:{},...h(c(u.prompt_tokens_details).cached_tokens)!==void 0?{cached:h(c(u.prompt_tokens_details).cached_tokens)}:{},...h(c(u.prompt_tokens_details).cache_write_tokens)?{written:h(c(u.prompt_tokens_details).cache_write_tokens)}:{},...h(u.completion_tokens)!==void 0?{output:h(u.completion_tokens)}:{},...h(c(u.completion_tokens_details).reasoning_tokens)!==void 0?{reasoning:h(c(u.completion_tokens_details).reasoning_tokens)}:{},...h(u.total_tokens)!==void 0?{total:h(u.total_tokens)}:{}})}v(z,"L"),_(z,"chatAnswer");function G(t,s,n){let l="",a="",r="",o,i,u,m,d=0;const f=new Map;for(const p of s){const y=J(p);if(!y)continue;y.cut&&d++,u??=e(y.v.model),m??=e(y.v.id),b(y.v.usage)&&(i=y.v.usage),b(y.v.error)&&(t.call.answer.error=e(y.v.error.message)??"the stream reported an error");const w=c(k(y.v.choices)[0]),x=c(w.delta);l+=e(x.content)??"",a+=e(x.reasoning_content)??e(x.reasoning)??"",r+=e(x.refusal)??"";for(const S of k(x.tool_calls).map(c)){const L=h(S.index)??0,B=f.get(L)??{name:"",args:""},P=c(S.function);e(S.id)&&(B.id=e(S.id)),B.name+=e(P.name)??"",B.args+=e(P.arguments)??"",f.set(L,B)}e(w.finish_reason)&&(o=e(w.finish_reason))}const g={content:l,...a?{reasoning_content:a}:{},...r?{refusal:r}:{},tool_calls:[...f.entries()].sort(([p],[y])=>p-y).map(([,p])=>({id:p.id,function:{name:p.name,arguments:p.args}}))};z(t,{...u?{model:u}:{},...m?{id:m}:{},choices:[{message:g,...o?{finish_reason:o}:{}}],...i?{usage:i}:{}}),d&&n.push(`${d} of the stream\u2019s chunks were kept to their first 4 KB \u2014 the answer was joined from what was kept of them.`)}v(G,"V"),_(G,"chatStream");function Q(t,s,n,l){const a=t.call;e(s.model)&&(a.model=e(s.model));for(const o of k(s.messages).map(c)){const i=e(o.role)??"user",{text:u,attachments:m}=I(o.content);if(i==="system")a.system.push({source:"system message",text:u});else if(i==="tool")O(t,e(o.tool_call_id),u);else if(i==="function")O(t,void 0,u);else{(u||m.length||i!=="assistant")&&a.turns.push({kind:"message",role:i,text:u,...m.length?{attachments:m}:{}});for(const d of K(o))j(t,d)}}a.tools=[...k(s.tools).map(c),...k(s.functions).map(o=>({type:"function",function:o}))].map(o=>{const i=c(o.function),u=e(o.type)??"function",m=e(i.name)??e(c(o.custom).name)??u;return{name:m,...splitToolName(m),type:u,...e(i.description)??e(c(o.custom).description)?{description:e(i.description)??e(c(o.custom).description)}:{},...i.parameters!==void 0?{parameters:i.parameters}:{},...typeof i.strict=="boolean"?{strict:i.strict}:{},called:0}}),a.settings=C(s,re);const r=c(s.response_format);if(e(r.type)&&r.type!=="text"){const o=c(r.json_schema);a.answer.format={type:e(r.type),...e(o.name)?{name:e(o.name)}:{},...o.schema!==void 0?{schema:o.schema}:{},...typeof o.strict=="boolean"?{strict:o.strict}:{}}}T(t,n,l,o=>z(t,o),o=>G(t,o,l))}v(Q,"X"),_(Q,"chatCall");const ae=[["max_tokens","max tokens"],["thinking.budget_tokens","thinking budget"],["temperature","temperature"],["top_p","top_p"],["top_k","top_k"],["tool_choice","tool choice"],["stop_sequences","stop sequences"],["stream","stream"],["metadata.user_id","user"]];function V(t,s,n){if(typeof n=="string"){t.call.turns.push({kind:"message",role:s,text:n});return}const l=[],a=[],r=_(()=>{(l.length||a.length)&&t.call.turns.push({kind:"message",role:s,text:l.join(`
14
14
 
15
- `),...a.length?{attachments:[...a]}:{}}),l.length=0,a.length=0},"flush");for(const s of w(n).map(c)){const i=e(s.type)??"";i==="text"?l.push(e(s.text)??""):i==="tool_use"||i==="server_tool_use"||i==="mcp_tool_use"?(r(),j(t,A(e(s.name)??"?",O(s.input),{callId:e(s.id),server:e(s.server_name)}))):i==="tool_result"||i==="mcp_tool_result"||/_tool_result$/.test(i)?(r(),S(t,e(s.tool_use_id),q(s.content),s.is_error===!0?"the tool reported an error":void 0)):i==="thinking"||i==="redacted_thinking"?(r(),t.call.turns.push({kind:"reasoning",...e(s.thinking)?{text:e(s.thinking)}:{}})):a.push(i==="image"?"image":i==="document"?`document ${e(s.title)??""}`.trim():i)}r()}v(G,"V"),k(G,"ee"),_(G,"anthropicBlocks");function K(t,o){const n=t.call.answer;e(o.model)&&(t.call.model??=e(o.model)),e(o.id)&&(t.call.responseId??=e(o.id));const l=[],a=[];for(const i of w(o.content).map(c)){const u=e(i.type);u==="text"?l.push(e(i.text)??""):u==="tool_use"||u==="server_tool_use"||u==="mcp_tool_use"?n.toolCalls.push(A(e(i.name)??"?",O(i.input),{callId:e(i.id),server:e(i.server_name)})):u==="thinking"&&a.push(e(i.thinking)??"")}l.length&&(n.text=l.join(`
15
+ `),...a.length?{attachments:[...a]}:{}}),l.length=0,a.length=0},"flush");for(const o of k(n).map(c)){const i=e(o.type)??"";i==="text"?l.push(e(o.text)??""):i==="tool_use"||i==="server_tool_use"||i==="mcp_tool_use"?(r(),j(t,$(e(o.name)??"?",A(o.input),{callId:e(o.id),server:e(o.server_name)}))):i==="tool_result"||i==="mcp_tool_result"||/_tool_result$/.test(i)?(r(),O(t,e(o.tool_use_id),N(o.content),o.is_error===!0?"the tool reported an error":void 0)):i==="thinking"||i==="redacted_thinking"?(r(),t.call.turns.push({kind:"reasoning",...e(o.thinking)?{text:e(o.thinking)}:{}})):a.push(i==="image"?"image":i==="document"?`document ${e(o.title)??""}`.trim():i)}r()}v(V,"ee"),_(V,"anthropicBlocks");function F(t,s){const n=t.call.answer;e(s.model)&&(t.call.model??=e(s.model)),e(s.id)&&(t.call.responseId??=e(s.id));const l=[],a=[];for(const i of k(s.content).map(c)){const u=e(i.type);u==="text"?l.push(e(i.text)??""):u==="tool_use"||u==="server_tool_use"||u==="mcp_tool_use"?n.toolCalls.push($(e(i.name)??"?",A(i.input),{callId:e(i.id),server:e(i.server_name)})):u==="thinking"&&a.push(e(i.thinking)??"")}l.length&&(n.text=l.join(`
16
16
 
17
17
  `)),a.length&&(n.reasoning=a.join(`
18
18
 
19
- `)),e(o.stop_reason)&&(n.finish=e(o.stop_reason)),n.status=o.type==="error"?"failed":n.finish?"completed":n.status??"unknown";const r=c(o.error);e(r.message)&&(n.error=e(r.message));const s=c(o.usage);if(Object.keys(s).length){const i=h(s.input_tokens),u=h(s.cache_read_input_tokens),m=h(s.output_tokens);t.call.usage={...i!==void 0?{input:i+(u??0)+(h(s.cache_creation_input_tokens)??0)}:{},...u!==void 0?{cached:u}:{},...h(s.cache_creation_input_tokens)?{written:h(s.cache_creation_input_tokens)}:{},...m!==void 0?{output:m}:{}}}}v(K,"F"),k(K,"P"),_(K,"anthropicAnswer");function H(t,o,n){let l={};const a=new Map,r=new Map;let s={},i=0;for(const u of o){const m=M(u);if(!m)continue;m.cut&&i++;const d=m.v,f=e(d.type)??u.event,g=h(d.index)??0;if(f==="message_start")l=c(d.message),s={...c(l.usage)};else if(f==="content_block_start")a.set(g,{...c(d.content_block)});else if(f==="content_block_delta"){const p=c(d.delta),y=a.get(g)??{};e(p.text)!==void 0&&(y.text=(e(y.text)??"")+e(p.text)),e(p.thinking)!==void 0&&(y.thinking=(e(y.thinking)??"")+e(p.thinking)),e(p.partial_json)!==void 0&&r.set(g,(r.get(g)??"")+e(p.partial_json)),a.set(g,y)}else f==="message_delta"?(l={...l,...c(d.delta)},s={...s,...c(d.usage)}):f==="error"&&(t.call.answer.error=e(c(d.error).message)??"the stream reported an error")}for(const[u,m]of r){const d=a.get(u);d&&(d.input=parseJsonPrefix(m)?.value??m)}K(t,{...l,content:[...a.entries()].sort(([u],[m])=>u-m).map(([,u])=>u),usage:s}),i&&n.push(`${i} of the stream\u2019s events were kept to their first 4 KB \u2014 the answer was joined from what was kept of them.`)}v(H,"X"),k(H,"te"),_(H,"anthropicStream");function V(t,o,n,l){const a=t.call;e(o.model)&&(a.model=e(o.model));const r=o.system;if(typeof r=="string"&&r)a.system.push({source:"system",text:r});else for(const s of w(r).map(c))e(s.text)&&a.system.push({source:"system",text:e(s.text)});for(const s of w(o.messages).map(c))G(t,e(s.role)??"user",s.content);a.tools=[...w(o.tools).map(c).map(s=>{const i=e(s.name)??e(s.type)??"tool";return{name:i,...splitToolName(i),type:e(s.type)??"custom",...e(s.description)?{description:e(s.description)}:{},...s.input_schema!==void 0?{parameters:s.input_schema}:{},called:0}}),...w(o.mcp_servers).map(c).map(s=>({name:e(s.name)??"mcp",server:e(s.name)??"mcp",tool:"every tool",type:"mcp",...e(s.url)?{description:e(s.url)}:{},called:0}))],a.settings=C(o,le),B(t,n,l,s=>K(t,s),s=>H(t,s,l))}v(V,"Y"),k(V,"ne"),_(V,"anthropicCall");function X(t,o,n,l){const a=t.call;e(o.model)&&(a.model=e(o.model));const r=o.input,s=typeof r=="string"?[r]:w(r),i=s.slice(0,200).map(p=>typeof p=="string"?p:typeof p=="number"?`token ${p}`:Array.isArray(p)?`${p.length} tokens`:O(p)),u=s.length>0&&s.every(p=>typeof p=="number");a.embedding={inputs:u?[`${s.length} tokens`]:i,count:u?1:s.length,...h(o.dimensions)!==void 0?{dimensions:h(o.dimensions)}:{}},a.settings=C(o,[["dimensions","dimensions"],["encoding_format","encoding"],["user","user"]]);const m=c(J(n.response.body,"answer",[])),d=w(m.data);if(d.length){a.embedding.vectors=d.length;const p=c(d[0]).embedding;Array.isArray(p)&&a.embedding.dimensions===void 0&&(a.embedding.dimensions=p.length)}const f=c(m.usage);h(f.prompt_tokens)!==void 0&&(a.usage={input:h(f.prompt_tokens),...h(f.total_tokens)!==void 0?{total:h(f.total_tokens)}:{}}),a.answer.status=n.status!==void 0&&n.status<400?"completed":"failed";const g=c(m.error);e(g.message)&&(a.answer.error=e(g.message))}v(X,"ee"),k(X,"se"),_(X,"embeddingsCall");function B(t,o,n,l,a){const r=o.response.stream;if(r){if(r.events.length&&r.events.every(i=>i.data===void 0)){n.push("The answer streamed, and only each event\u2019s name, time and size were kept \u2014 an AI provider\u2019s bodies are kept only when asked for: Settings \u203A Features \u203A Capture \u203A AI calls.");return}a(r.events),r.cut&&n.push(`The stream was cut after ${r.events.length.toLocaleString("en-US")} of its ${r.total.toLocaleString("en-US")} events \u2014 what came after is not shown.`);return}const s=J(o.response.body,"answer",n);$(s)?l(s):o.error&&(t.call.answer.error=o.error),t.call.answer.status||(t.call.answer.status=o.error||(o.status??0)>=400?"failed":"unknown")}v(B,"T"),k(B,"N"),_(B,"answerOf");function Q(t){return t.api==="embeddings"?"embedding":t.answer.format&&/json/.test(t.answer.format.type)?"decision":t.tools.length||t.answer.toolCalls.length||t.turns.some(o=>o.kind==="tool")?"tools":t.turns.filter(o=>o.kind==="message"&&(o.role==="user"||o.role==="assistant")).length>1?"chat":"prompt"}v(Q,"te"),k(Q,"oe"),_(Q,"shapeOf");export function aiCallOf(t){if(!t.ai)return;const o=aiApiOf(t.path);if(!o)return;const n=[],l={call:{provider:t.ai.provider,api:o,shape:"prompt",settings:[],system:[],turns:[],tools:[],answer:{toolCalls:[]},gaps:n},byCallId:new Map},a=c(J(t.request.body,"request",n));o==="responses"?Z(l,a,t,n):o==="chat"?R(l,a,t,n):o==="messages"?V(l,a,t,n):X(l,a,t,n);const r=l.call;if(r.answer.text!==void 0&&(r.answer.format?/json/.test(r.answer.format.type):/^\s*[{[]/.test(r.answer.text))){const i=parseJsonPrefix(r.answer.text);i&&($(i.value)||Array.isArray(i.value))&&(r.answer.json=i.value)}!r.answer.finish&&r.answer.toolCalls.length&&(r.answer.finish="tool calls");const s=new Map;for(const i of r.turns)i.kind==="tool"&&s.set(i.name,(s.get(i.name)??0)+1);for(const i of r.answer.toolCalls)s.set(i.name,(s.get(i.name)??0)+1);for(const i of r.tools)i.called=s.get(i.name)??0;r.shape=Q(r);for(const i of r.system)i.text.endsWith(CUT_MARK)&&(i.cut=!0);return r}v(aiCallOf,"aiCallOf"),k(aiCallOf,"aiCallOf"),_(aiCallOf,"aiCallOf");export const SHAPE_LABEL={prompt:"Single prompt",chat:"Conversation",tools:"Tool calling",decision:"Structured decision",embedding:"Embedding"};export function prettyJson(t){const o=t.trim()?parseJsonPrefix(t):void 0;return o&&($(o.value)||Array.isArray(o.value))?{value:o.value,text:t}:{text:t}}v(prettyJson,"prettyJson"),k(prettyJson,"prettyJson"),_(prettyJson,"prettyJson");
19
+ `)),e(s.stop_reason)&&(n.finish=e(s.stop_reason)),n.status=s.type==="error"?"failed":n.finish?"completed":n.status??"unknown";const r=c(s.error);e(r.message)&&(n.error=e(r.message));const o=c(s.usage);if(Object.keys(o).length){const i=h(o.input_tokens),u=h(o.cache_read_input_tokens),m=h(o.output_tokens);t.call.usage={...i!==void 0?{input:i+(u??0)+(h(o.cache_creation_input_tokens)??0)}:{},...u!==void 0?{cached:u}:{},...h(o.cache_creation_input_tokens)?{written:h(o.cache_creation_input_tokens)}:{},...m!==void 0?{output:m}:{}}}}v(F,"P"),_(F,"anthropicAnswer");function X(t,s,n){let l={};const a=new Map,r=new Map;let o={},i=0;for(const u of s){const m=J(u);if(!m)continue;m.cut&&i++;const d=m.v,f=e(d.type)??u.event,g=h(d.index)??0;if(f==="message_start")l=c(d.message),o={...c(l.usage)};else if(f==="content_block_start")a.set(g,{...c(d.content_block)});else if(f==="content_block_delta"){const p=c(d.delta),y=a.get(g)??{};e(p.text)!==void 0&&(y.text=(e(y.text)??"")+e(p.text)),e(p.thinking)!==void 0&&(y.thinking=(e(y.thinking)??"")+e(p.thinking)),e(p.partial_json)!==void 0&&r.set(g,(r.get(g)??"")+e(p.partial_json)),a.set(g,y)}else f==="message_delta"?(l={...l,...c(d.delta)},o={...o,...c(d.usage)}):f==="error"&&(t.call.answer.error=e(c(d.error).message)??"the stream reported an error")}for(const[u,m]of r){const d=a.get(u);d&&(d.input=parseJsonPrefix(m)?.value??m)}F(t,{...l,content:[...a.entries()].sort(([u],[m])=>u-m).map(([,u])=>u),usage:o}),i&&n.push(`${i} of the stream\u2019s events were kept to their first 4 KB \u2014 the answer was joined from what was kept of them.`)}v(X,"te"),_(X,"anthropicStream");function Y(t,s,n,l){const a=t.call;e(s.model)&&(a.model=e(s.model));const r=s.system;if(typeof r=="string"&&r)a.system.push({source:"system",text:r});else for(const o of k(r).map(c))e(o.text)&&a.system.push({source:"system",text:e(o.text)});for(const o of k(s.messages).map(c))V(t,e(o.role)??"user",o.content);a.tools=[...k(s.tools).map(c).map(o=>{const i=e(o.name)??e(o.type)??"tool";return{name:i,...splitToolName(i),type:e(o.type)??"custom",...e(o.description)?{description:e(o.description)}:{},...o.input_schema!==void 0?{parameters:o.input_schema}:{},called:0}}),...k(s.mcp_servers).map(c).map(o=>({name:e(o.name)??"mcp",server:e(o.name)??"mcp",tool:"every tool",type:"mcp",...e(o.url)?{description:e(o.url)}:{},called:0}))],a.settings=C(s,ae),T(t,n,l,o=>F(t,o),o=>X(t,o,l))}v(Y,"ne"),_(Y,"anthropicCall");function ee(t,s,n,l){const a=t.call;e(s.model)&&(a.model=e(s.model));const r=s.input,o=typeof r=="string"?[r]:k(r),i=o.slice(0,200).map(p=>typeof p=="string"?p:typeof p=="number"?`token ${p}`:Array.isArray(p)?`${p.length} tokens`:A(p)),u=o.length>0&&o.every(p=>typeof p=="number");a.embedding={inputs:u?[`${o.length} tokens`]:i,count:u?1:o.length,...h(s.dimensions)!==void 0?{dimensions:h(s.dimensions)}:{}},a.settings=C(s,[["dimensions","dimensions"],["encoding_format","encoding"],["user","user"]]);const m=c(M(n.response.body,"answer",[])),d=k(m.data);if(d.length){a.embedding.vectors=d.length;const p=c(d[0]).embedding;Array.isArray(p)&&a.embedding.dimensions===void 0&&(a.embedding.dimensions=p.length)}const f=c(m.usage);h(f.prompt_tokens)!==void 0&&(a.usage={input:h(f.prompt_tokens),...h(f.total_tokens)!==void 0?{total:h(f.total_tokens)}:{}}),a.answer.status=n.status!==void 0&&n.status<400?"completed":"failed";const g=c(m.error);e(g.message)&&(a.answer.error=e(g.message))}v(ee,"se"),_(ee,"embeddingsCall");function T(t,s,n,l,a){const r=s.response.stream;if(r){if(r.events.length&&r.events.every(i=>i.data===void 0)){n.push("The answer streamed, and only each event\u2019s name, time and size were kept \u2014 an AI provider\u2019s bodies are kept only when asked for: Settings \u203A Features \u203A Capture \u203A AI calls.");return}a(r.events),r.cut&&n.push(`The stream was cut after ${r.events.length.toLocaleString("en-US")} of its ${r.total.toLocaleString("en-US")} events \u2014 what came after is not shown.`);return}const o=M(s.response.body,"answer",n);b(o)?l(o):s.error&&(t.call.answer.error=s.error),t.call.answer.status||(t.call.answer.status=s.error||(s.status??0)>=400?"failed":"unknown")}v(T,"N"),_(T,"answerOf");function te(t){return t.api==="embeddings"?"embedding":t.answer.format&&/json/.test(t.answer.format.type)?"decision":t.tools.length||t.answer.toolCalls.length||t.turns.some(s=>s.kind==="tool")?"tools":t.turns.filter(s=>s.kind==="message"&&(s.role==="user"||s.role==="assistant")).length>1?"chat":"prompt"}v(te,"oe"),_(te,"shapeOf");export function aiCallOf(t){if(!t.ai)return;const s=aiApiOf(t.path);if(!s)return;const n=[],l={call:{provider:t.ai.provider,api:s,shape:"prompt",settings:[],system:[],turns:[],tools:[],answer:{toolCalls:[]},gaps:n},byCallId:new Map},a=c(M(t.request.body,"request",n));s==="responses"?R(l,a,t,n):s==="chat"?Q(l,a,t,n):s==="messages"?Y(l,a,t,n):ee(l,a,t,n);const r=l.call;if(r.answer.text!==void 0&&(r.answer.format?/json/.test(r.answer.format.type):/^\s*[{[]/.test(r.answer.text))){const i=parseJsonPrefix(r.answer.text);i&&(b(i.value)||Array.isArray(i.value))&&(r.answer.json=i.value)}!r.answer.finish&&r.answer.toolCalls.length&&(r.answer.finish="tool calls");const o=new Map;for(const i of r.turns)i.kind==="tool"&&o.set(i.name,(o.get(i.name)??0)+1);for(const i of r.answer.toolCalls)o.set(i.name,(o.get(i.name)??0)+1);for(const i of r.tools)i.called=o.get(i.name)??0;r.shape=te(r);for(const i of r.system)i.text.endsWith(CUT_MARK)&&(i.cut=!0);return r}v(aiCallOf,"aiCallOf"),_(aiCallOf,"aiCallOf");export const SHAPE_LABEL={prompt:"Single prompt",chat:"Conversation",tools:"Tool calling",decision:"Structured decision",embedding:"Embedding"};export function prettyJson(t){const s=t.trim()?parseJsonPrefix(t):void 0;return s&&(b(s.value)||Array.isArray(s.value))?{value:s.value,text:t}:{text:t}}v(prettyJson,"prettyJson"),_(prettyJson,"prettyJson");
package/lib/ai-context.js CHANGED
@@ -1,6 +1,6 @@
1
- "use strict";var G=Object.defineProperty;var $=(t,e)=>G(t,"name",{value:e,configurable:!0});var R=Object.defineProperty,y=$((t,e)=>R(t,"name",{value:e,configurable:!0}),"$"),W=Object.defineProperty,g=y((t,e)=>W(t,"name",{value:e,configurable:!0}),"g");export const AI_PART_KINDS=["system","tools","schema","context","history","tool","turn","carried","unkept"],AI_PART_LABEL={system:"System prompt",tools:"Tool definitions",schema:"Answer schema",context:"Context",history:"Earlier turns",tool:"Tool calls & results",turn:"This turn",carried:"Held by the provider",unkept:"Not kept"},AI_PART_SAID={system:"The instructions every call of this agent starts with",tools:"The tools it was offered, as defined \u2014 sent with every call, called or not",schema:"The JSON schema its answer had to fit",context:"What the app put in beside the conversation (developer messages)",history:"The conversation before this turn \u2014 what was said, and answered",tool:"The tools it called earlier in this run, what it sent them and what came back",turn:"What this call asks \u2014 the latest message",carried:"The conversation of the response it continues (previous_response_id): counted by the provider, not in this request",unkept:"The end of the request, which the capture did not keep (a lens before 1.25.32 kept its first 64 KB): counted by the provider, not known here"};const Z=/[\p{L}\p{M}]/u,D=/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u,U=/(\s*)([A-Za-z]+|[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]+|[\p{L}\p{M}]+|[0-9]+|[^\s\p{L}\p{M}0-9]+)|(\s+)/gu,B=4,z=.7;export function estimateTokens(t){let e=0;for(const s of t.matchAll(U)){const o=s[1],n=s[2];if(s[3]!==void 0){/\n| {2,}/.test(s[3])&&(e+=1);continue}if(o&&/\n| {2,}/.test(o)&&(e+=1),!n)continue;const r=n.charCodeAt(0);r>=65&&r<=90||r>=97&&r<=122?e+=1+(n.length>8?(n.length-8)/4:0):r>=48&&r<=57?e+=Math.ceil(n.length/3):D.test(n)?e+=[...n].length*.9:Z.test(n)?e+=[...n].length*.66:e+=n.length*.75}return e}$(estimateTokens,"estimateTokens"),y(estimateTokens,"estimateTokens"),g(estimateTokens,"estimateTokens");const F=/^[ \t]*-{3,}[ \t]*(.+?)[ \t]*-{3,}[ \t]*$/gm,Q=/^(#{1,4})[ \t]+(.+?)[ \t]*#*[ \t]*$/gm,I=60;function C(t,e){const s=[],o=t.slice(0,e[0].at);return o.trim().length>40&&s.push({title:"(opening)",chars:o.length,tokens:0,at:0,end:e[0].at}),e.forEach((n,r)=>{const h=r+1<e.length?e[r+1].at:t.length;s.push({title:n.title.slice(0,120),chars:h-n.at,tokens:0,at:n.at,end:h})}),s}$(C,"C"),y(C,"P"),g(C,"cutAt");function T(t){const e=t.trim();if(!e.startsWith("{")&&!e.startsWith("["))return[];let s;try{s=JSON.parse(e)}catch{return[]}const o=s&&typeof s=="object"&&!Array.isArray(s)?s.properties:void 0,n=o&&typeof o=="object"&&!Array.isArray(o)?o:s,r=Array.isArray(n)?n.map((h,u)=>[`[${u}]`,h]):n&&typeof n=="object"?Object.entries(n):[];return r.length<2?[]:r.slice(0,I).map(([h,u])=>{const c=JSON.stringify(u,null,2)??"";return{title:h,chars:c.length,tokens:estimateTokens(c)}})}$(T,"M"),y(T,"M"),g(T,"jsonSections");export function sectionsOf(t){const e=taggedSections(t);return e.length?e:_(t)}$(sectionsOf,"sectionsOf"),y(sectionsOf,"sectionsOf"),g(sectionsOf,"sectionsOf");function _(t){if(t.length<200)return[];let e=g((o,n,r=()=>!0)=>[...t.matchAll(o)].filter(r).map(h=>({at:h.index,title:n(h)})),"pick")(F,o=>o[1]);if(e.length<2){const o=[...t.matchAll(Q)],n=[1,2,3,4].find(r=>o.filter(h=>h[1].length===r).length>=2);e=n?o.filter(r=>r[1].length===n).map(r=>({at:r.index,title:r[2]})):[]}if(e.length<2)return T(t);const s=C(t,e.slice(0,I));for(const o of s){const n=t.slice(o.at,o.end);o.tokens=estimateTokens(n);const r=n.indexOf(`
2
- `),h=r>0?T(n.slice(r+1)):[];h.length&&(o.children=h)}return s}$(_,"j"),y(_,"N"),g(_,"plainSections");export const STABLE_TAGS=new Set(["instructions","rules","output","examples"]),CHANGING_TAGS=new Set(["memory","status","data","task"]);const X=/<([a-z][a-z0-9_-]{0,40})((?:\s+[A-Za-z_][\w.:-]*\s*=\s*(?:"[^"]*"|'[^']*'))*)\s*>/g,V=/([A-Za-z_][\w.:-]*)\s*=\s*(?:"([^"]*)"|'([^']*)')/g,Y=g(t=>t.replace(/&quot;/g,'"').replace(/&apos;/g,"'").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&"),"unescape");function H(t){const e={};for(const s of t.matchAll(V))e[s[1]]=Y(s[2]??s[3]??"");return e}$(H,"H"),y(H,"q"),g(H,"attrsOf");function L(t,e,s,o){const n=`<${e}`,r=`</${e}>`;let h=1,u=s;for(;u<o;){const c=t.indexOf(r,u);if(c<0||c>=o)return-1;let f=t.indexOf(n,u);for(;f>=0&&f<c&&!/[\s>]/.test(t[f+n.length]??"");)f=t.indexOf(n,f+1);if(f>=0&&f<c){h++,u=f+n.length;continue}if(--h===0)return c;u=c+r.length}return-1}$(L,"L"),y(L,"z"),g(L,"closeOf");const tt=g((t,e)=>{for(let s=e-1;s>=0;s--){const o=t[s];if(o===`
3
- `)return!0;if(o!==" "&&o!==" ")return!1}return!0},"atLineStart");export function taggedSections(t,e=0,s=t.length,o=0){const n=[],r=new RegExp(X.source,"g");let h=e;for(;h<s&&n.length<I;){r.lastIndex=h;const l=r.exec(t);if(!l||l.index>=s)break;const p=l[1],k=l.index+l[0].length,x=tt(t,l.index)?L(t,p,k,s):-1;if(x<0){h=k;continue}const a=x+p.length+3,d=H(l[2]??""),v={title:p,tag:p,...Object.keys(d).length?{attrs:d}:{},chars:a-l.index,tokens:estimateTokens(t.slice(l.index,a)),at:l.index,end:a};if(o<1){const w=taggedSections(t,k,x,o+1).filter(i=>i.tag),S=w.length?w:_(t.slice(k,x)).map(i=>i.at===void 0?i:{...i,at:i.at+k,end:i.end+k});S.length&&(v.children=S)}n.push(v),h=a}if(!n.length)return[];const u=[];let c=e;const f=g((l,p)=>{const k=t.slice(l,p);k.trim().length>20&&u.push({title:"(untagged)",chars:p-l,tokens:estimateTokens(k),at:l,end:p})},"gap");for(const l of n)f(c,l.at),u.push(l),c=l.end;f(c,s);const b=new Map;for(const l of u){if(!l.tag)continue;const p=l.attrs?.id?`${l.tag} \xB7 ${l.attrs.id}`:l.tag,k=(b.get(p)??0)+1;b.set(p,k),l.title=k>1?`${p} #${k}`:p}return u}$(taggedSections,"taggedSections"),y(taggedSections,"taggedSections"),g(taggedSections,"taggedSections");function M(t,e){const s=t.reduce((o,n)=>o+n.tokens,0);for(const o of t)o.tokens=s>0?Math.round(o.tokens/s*e):0,o.children&&M(o.children,o.tokens)}$(M,"N"),y(M,"I"),g(M,"scaleSections");const et={user:"user",assistant:"assistant",developer:"Context \xB7 developer message",system:"system message"};function E(t,e,s){if(t.kind==="reasoning")return t.text?{kind:"history",label:"reasoning \xB7 sent back",role:"assistant",ref:{turn:e},text:t.text,estimate:estimateTokens(t.text)+B}:void 0;if(t.kind==="tool"){const o=`${t.name}(${t.arguments})${t.output!==void 0?`
4
- ${t.output}`:""}`;return{kind:"tool",label:`tool \xB7 ${t.tool}${t.output!==void 0?" \u2014 called, and its result":" \u2014 called"}`,role:"tool",ref:{turn:e},text:o,estimate:estimateTokens(o)+B*(t.output!==void 0?2:1)}}return{kind:s,label:et[t.role],role:t.role,ref:{turn:e},text:t.text,estimate:estimateTokens(t.text)+B}}$(E,"E"),y(E,"Z"),g(E,"turnDraft");function J(t){const e=t.turns;let s=e.length;for(;s>0&&e[s-1].kind==="message"&&e[s-1].role!=="assistant";)s--;return e.map((o,n)=>o.kind==="tool"?"tool":o.kind==="reasoning"?"history":o.role==="developer"||o.role==="system"?"context":n>=s&&o.role==="user"?"turn":"history")}$(J,"J"),y(J,"F"),g(J,"turnKinds");function K(t){const e=t.system.map((c,f)=>({kind:"system",label:c.source==="instructions"?"System prompt \xB7 instructions":`System prompt \xB7 ${c.source}`,ref:{system:f},text:c.text,estimate:estimateTokens(c.text)+B})),s=t.tools.map(c=>JSON.stringify({name:c.name,description:c.description,parameters:c.parameters})).join(`
5
- `),o=t.tools.length?[{kind:"tools",label:`${t.tools.length} tool${t.tools.length===1?"":"s"} offered`,ref:{tools:!0},text:s,estimate:estimateTokens(s)*z}]:[],n=t.answer.format?.schema!==void 0?JSON.stringify(t.answer.format.schema):"",r=n?[{kind:"schema",label:`Answer schema${t.answer.format?.name?` \xB7 ${t.answer.format.name}`:""}`,ref:{schema:!0},text:n,estimate:estimateTokens(n)*z}]:[],h=J(t),u=t.turns.map((c,f)=>E(c,f,h[f])).filter(c=>!!c);for(const c of u){const f=t.turns[c.ref.turn];f.kind==="message"&&f.attachments?.length&&(c.label+=` \xB7 ${f.attachments.join(", ")}`)}return t.provider==="anthropic"?[...o,...e,...r,...u]:[...e,...o,...r,...u]}$(K,"K"),y(K,"U"),g(K,"draftsOf");export function aiContextOf(t,e={}){const s=e.sections!==!1,o=K(t),n=Math.round(o.reduce((i,m)=>i+m.estimate,0)),r=t.usage,h=r?.input!==void 0&&r.input>0,u=h?r.input:n,c=t.settings.some(i=>i.name==="continues response"),f=t.gaps.some(i=>/^The (request was kept to its first|prompt was not kept)/.test(i)),b=h&&(c||f)&&u>n*1.05?u-n:0,l=c?b:0,p=c?0:b,k=n>0?(u-b)/n:0,x=o.map((i,m)=>({i:m,kind:i.kind,label:i.label,...i.role?{role:i.role}:{},ref:i.ref,chars:i.text.length,tokens:Math.round(i.estimate*k),cached:0,sections:!s||i.kind==="tools"?[]:sectionsOf(i.text)}));l&&x.unshift({i:-1,kind:"carried",label:"The conversation it continues",ref:{carried:!0},chars:0,tokens:l,cached:0,sections:[]}),p&&x.push({i:-1,kind:"unkept",label:"The rest of the request \u2014 not kept",ref:{unkept:!0},chars:0,tokens:p,cached:0,sections:[]});const a=u-x.reduce((i,m)=>i+m.tokens,0);a&&x.length&&(x.reduce((i,m)=>m.tokens>i.tokens?m:i).tokens+=a);for(const i of x)i.kind==="tools"&&s&&(i.sections=t.tools.map(m=>({title:m.server?`${m.server} \u203A ${m.tool}`:m.tool,chars:0,tokens:estimateTokens(JSON.stringify({d:m.description,p:m.parameters}))}))),M(i.sections,i.tokens);x.forEach((i,m)=>i.i=m);const d=Math.min(r?.cached??0,u);let v=d;for(const i of x)i.cached=Math.min(i.tokens,v),v-=i.cached;const w=AI_PART_KINDS.map(i=>{const m=x.filter(O=>O.kind===i);return{kind:i,tokens:m.reduce((O,N)=>O+N.tokens,0),cached:m.reduce((O,N)=>O+N.cached,0),parts:m.length}}).filter(i=>i.parts),S=P(t);return{parts:x,byKind:w,input:u,counted:h,cached:d,...r?.written?{written:r.written}:{},estimated:n,output:S,findings:q(t,x,u,d,S)}}$(aiContextOf,"aiContextOf"),y(aiContextOf,"aiContextOf"),g(aiContextOf,"aiContextOf");function P(t){const e=t.answer,s=e.json!==void 0?JSON.stringify(e.json):e.text??e.refusal??"",o=e.toolCalls.map(p=>`${p.name}(${p.arguments})`).join(`
6
- `),n=estimateTokens(s),r=estimateTokens(o)+e.toolCalls.length*B,h=t.usage,u=h?.output!==void 0,c=u?h.output:Math.round(n+r),f=Math.min(h?.reasoning??0,c),b=c-f,l=n+r>0?Math.round(r/(n+r)*b):0;return{total:c,reasoning:f,answer:b-l,tools:l,counted:u}}$(P,"q"),y(P,"X"),g(P,"outputOf");const A=g(t=>Math.round(t).toLocaleString("en-US"),"fmt"),j=g((t,e)=>`${e>0?Math.round(t/e*100):0}%`,"pct");function q(t,e,s,o,n){const r=[],h=t.answer;if(h.status==="incomplete"||/max_output_tokens|length|max_tokens/.test(h.finish??"")){const a=t.settings.find(d=>/max output|max_tokens|max_completion/.test(d.name));r.push({tone:"bad",text:`It stopped at its output cap${a?` (${a.name} ${a.value})`:""} \u2014 the answer is cut.`})}t.gaps.length&&r.push({tone:"warn",text:"Part of the call was not kept \u2014 the split covers what was."});const u=t.turns.reduce((a,d)=>a+(d.kind==="message"?d.attachments?.length??0:0),0);u&&r.push({tone:"info",text:`${u} image${u===1?"":"s"} or file${u===1?"":"s"} went with its messages: their tokens are counted by the provider but not read from the text, so the split spreads them over the parts.`});const c=t.usage;if(c?.input!==void 0&&s>=1024){if(!o)r.push({tone:"warn",text:`None of its ${A(s)} input tokens came from the prompt cache${c.written?` \u2014 ${A(c.written)} were written to it, for a later call that opens the same way`:""}.`});else if(o<s*.9){const w=e.find(S=>S.cached<S.tokens);w&&r.push({tone:"info",text:`${j(o,s)} cached \u2014 the cache stopped in \xAB${w.label}\xBB: from there on the prompt differed from the last call that opened the same way.`})}const a=e.findIndex(w=>w.kind==="context"),d=a>=0?e.slice(a+1).filter(w=>w.kind==="history"||w.kind==="tool"):[],v=d.reduce((w,S)=>w+S.tokens,0);a>=0&&d.length>=2&&e[a].cached<e[a].tokens&&v>0&&r.push({tone:"info",text:`The context the app put in sits before ${d.length} earlier turns (${A(v)} tokens): when it changes between calls, nothing after it can be read from the cache.`})}const f=e.flatMap(a=>a.sections.filter(d=>d.tag).map(d=>({p:a,x:d}))),b=f.findIndex(({x:a})=>CHANGING_TAGS.has(a.tag)),l=b>=0?f.slice(b+1).filter(({x:a})=>STABLE_TAGS.has(a.tag)):[];if(b>=0&&l.length){const a=f[b].x,d=l.reduce((v,{x:w})=>v+w.tokens,0);r.push({tone:"info",text:`\xAB${a.title}\xBB changes from call to call and comes before ${l.length} section${l.length===1?"":"s"} that should not (\xAB${l[0].x.title}\xBB\u2026, ${A(d)} tokens): put the stable ones first, or they cannot be read from the cache.`})}const p=e.filter(a=>a.kind!=="carried").reduce((a,d)=>!a||d.tokens>a.tokens?d:a,void 0);if(p&&s>2e3&&p.tokens>s*.5){const a=p.sections.reduce((d,v)=>!d||v.tokens>d.tokens?v:d,void 0);r.push({tone:"info",text:`\xAB${p.label}\xBB is ${j(p.tokens,s)} of the input${a&&a.tokens>p.tokens*.4?` \u2014 most of it \xAB${a.title}\xBB (${A(a.tokens)} tokens)`:""}.`})}const k=e.find(a=>a.kind==="tools"),x=h.toolCalls.length;return k&&k.tokens>s*.2&&!x&&!t.turns.some(a=>a.kind==="tool")&&r.push({tone:"info",text:`${t.tools.length} tool definitions are ${j(k.tokens,s)} of the input, and it called none of them.`}),n.total>=200&&n.reasoning>n.total*.7&&r.push({tone:"info",text:`${j(n.reasoning,n.total)} of its output was reasoning (${A(n.reasoning)} tokens).`}),r}$(q,"z"),y(q,"Q"),g(q,"findingsOf");export function aiSplitOf(t){return Object.fromEntries(t.byKind.filter(e=>e.tokens>0).map(e=>[e.kind,e.tokens]))}$(aiSplitOf,"aiSplitOf"),y(aiSplitOf,"aiSplitOf"),g(aiSplitOf,"aiSplitOf");
1
+ "use strict";var P=Object.defineProperty;var $=(t,e)=>P(t,"name",{value:e,configurable:!0});var G=Object.defineProperty,g=$((t,e)=>G(t,"name",{value:e,configurable:!0}),"g");export const AI_PART_KINDS=["system","tools","schema","context","history","tool","turn","carried","unkept"],AI_PART_LABEL={system:"System prompt",tools:"Tool definitions",schema:"Answer schema",context:"Context",history:"Earlier turns",tool:"Tool calls & results",turn:"This turn",carried:"Held by the provider",unkept:"Not kept"},AI_PART_SAID={system:"The instructions every call of this agent starts with",tools:"The tools it was offered, as defined \u2014 sent with every call, called or not",schema:"The JSON schema its answer had to fit",context:"What the app put in beside the conversation (developer messages)",history:"The conversation before this turn \u2014 what was said, and answered",tool:"The tools it called earlier in this run, what it sent them and what came back",turn:"What this call asks \u2014 the latest message",carried:"The conversation of the response it continues (previous_response_id): counted by the provider, not in this request",unkept:"The end of the request, which the capture did not keep (a lens before 1.25.32 kept its first 64 KB): counted by the provider, not known here"};const R=/[\p{L}\p{M}]/u,W=/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u,D=/(\s*)([A-Za-z]+|[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]+|[\p{L}\p{M}]+|[0-9]+|[^\s\p{L}\p{M}0-9]+)|(\s+)/gu,B=4,I=.7;export function estimateTokens(t){let e=0;for(const o of t.matchAll(D)){const s=o[1],n=o[2];if(o[3]!==void 0){/\n| {2,}/.test(o[3])&&(e+=1);continue}if(s&&/\n| {2,}/.test(s)&&(e+=1),!n)continue;const r=n.charCodeAt(0);r>=65&&r<=90||r>=97&&r<=122?e+=1+(n.length>8?(n.length-8)/4:0):r>=48&&r<=57?e+=Math.ceil(n.length/3):W.test(n)?e+=[...n].length*.9:R.test(n)?e+=[...n].length*.66:e+=n.length*.75}return e}$(estimateTokens,"estimateTokens"),g(estimateTokens,"estimateTokens");const Z=/^[ \t]*-{3,}[ \t]*(.+?)[ \t]*-{3,}[ \t]*$/gm,U=/^(#{1,4})[ \t]+(.+?)[ \t]*#*[ \t]*$/gm,_=60;function C(t,e){const o=[],s=t.slice(0,e[0].at);return s.trim().length>40&&o.push({title:"(opening)",chars:s.length,tokens:0,at:0,end:e[0].at}),e.forEach((n,r)=>{const h=r+1<e.length?e[r+1].at:t.length;o.push({title:n.title.slice(0,120),chars:h-n.at,tokens:0,at:n.at,end:h})}),o}$(C,"P"),g(C,"cutAt");function M(t){const e=t.trim();if(!e.startsWith("{")&&!e.startsWith("["))return[];let o;try{o=JSON.parse(e)}catch{return[]}const s=o&&typeof o=="object"&&!Array.isArray(o)?o.properties:void 0,n=s&&typeof s=="object"&&!Array.isArray(s)?s:o,r=Array.isArray(n)?n.map((h,u)=>[`[${u}]`,h]):n&&typeof n=="object"?Object.entries(n):[];return r.length<2?[]:r.slice(0,_).map(([h,u])=>{const c=JSON.stringify(u,null,2)??"";return{title:h,chars:c.length,tokens:estimateTokens(c)}})}$(M,"M"),g(M,"jsonSections");export function sectionsOf(t){const e=taggedSections(t);return e.length?e:j(t)}$(sectionsOf,"sectionsOf"),g(sectionsOf,"sectionsOf");function j(t){if(t.length<200)return[];let e=g((s,n,r=()=>!0)=>[...t.matchAll(s)].filter(r).map(h=>({at:h.index,title:n(h)})),"pick")(Z,s=>s[1]);if(e.length<2){const s=[...t.matchAll(U)],n=[1,2,3,4].find(r=>s.filter(h=>h[1].length===r).length>=2);e=n?s.filter(r=>r[1].length===n).map(r=>({at:r.index,title:r[2]})):[]}if(e.length<2)return M(t);const o=C(t,e.slice(0,_));for(const s of o){const n=t.slice(s.at,s.end);s.tokens=estimateTokens(n);const r=n.indexOf(`
2
+ `),h=r>0?M(n.slice(r+1)):[];h.length&&(s.children=h)}return o}$(j,"N"),g(j,"plainSections");export const STABLE_TAGS=new Set(["instructions","rules","output","examples"]),CHANGING_TAGS=new Set(["memory","status","data","task"]);const F=/<([a-z][a-z0-9_-]{0,40})((?:\s+[A-Za-z_][\w.:-]*\s*=\s*(?:"[^"]*"|'[^']*'))*)\s*>/g,Q=/([A-Za-z_][\w.:-]*)\s*=\s*(?:"([^"]*)"|'([^']*)')/g,X=g(t=>t.replace(/&quot;/g,'"').replace(/&apos;/g,"'").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&"),"unescape");function H(t){const e={};for(const o of t.matchAll(Q))e[o[1]]=X(o[2]??o[3]??"");return e}$(H,"q"),g(H,"attrsOf");function L(t,e,o,s){const n=`<${e}`,r=`</${e}>`;let h=1,u=o;for(;u<s;){const c=t.indexOf(r,u);if(c<0||c>=s)return-1;let f=t.indexOf(n,u);for(;f>=0&&f<c&&!/[\s>]/.test(t[f+n.length]??"");)f=t.indexOf(n,f+1);if(f>=0&&f<c){h++,u=f+n.length;continue}if(--h===0)return c;u=c+r.length}return-1}$(L,"z"),g(L,"closeOf");const V=g((t,e)=>{for(let o=e-1;o>=0;o--){const s=t[o];if(s===`
3
+ `)return!0;if(s!==" "&&s!==" ")return!1}return!0},"atLineStart");export function taggedSections(t,e=0,o=t.length,s=0){const n=[],r=new RegExp(F.source,"g");let h=e;for(;h<o&&n.length<_;){r.lastIndex=h;const l=r.exec(t);if(!l||l.index>=o)break;const p=l[1],k=l.index+l[0].length,x=V(t,l.index)?L(t,p,k,o):-1;if(x<0){h=k;continue}const i=x+p.length+3,d=H(l[2]??""),b={title:p,tag:p,...Object.keys(d).length?{attrs:d}:{},chars:i-l.index,tokens:estimateTokens(t.slice(l.index,i)),at:l.index,end:i};if(s<1){const w=taggedSections(t,k,x,s+1).filter(a=>a.tag),v=w.length?w:j(t.slice(k,x)).map(a=>a.at===void 0?a:{...a,at:a.at+k,end:a.end+k});v.length&&(b.children=v)}n.push(b),h=i}if(!n.length)return[];const u=[];let c=e;const f=g((l,p)=>{const k=t.slice(l,p);k.trim().length>20&&u.push({title:"(untagged)",chars:p-l,tokens:estimateTokens(k),at:l,end:p})},"gap");for(const l of n)f(c,l.at),u.push(l),c=l.end;f(c,o);const y=new Map;for(const l of u){if(!l.tag)continue;const p=l.attrs?.id?`${l.tag} \xB7 ${l.attrs.id}`:l.tag,k=(y.get(p)??0)+1;y.set(p,k),l.title=k>1?`${p} #${k}`:p}return u}$(taggedSections,"taggedSections"),g(taggedSections,"taggedSections");function N(t,e){const o=t.reduce((s,n)=>s+n.tokens,0);for(const s of t)s.tokens=o>0?Math.round(s.tokens/o*e):0,s.children&&N(s.children,s.tokens)}$(N,"I"),g(N,"scaleSections");const Y={user:"user",assistant:"assistant",developer:"Context \xB7 developer message",system:"system message"};function E(t,e,o){if(t.kind==="reasoning")return t.text?{kind:"history",label:"reasoning \xB7 sent back",role:"assistant",ref:{turn:e},text:t.text,estimate:estimateTokens(t.text)+B}:void 0;if(t.kind==="tool"){const s=`${t.name}(${t.arguments})${t.output!==void 0?`
4
+ ${t.output}`:""}`;return{kind:"tool",label:`tool \xB7 ${t.tool}${t.output!==void 0?" \u2014 called, and its result":" \u2014 called"}`,role:"tool",ref:{turn:e},text:s,estimate:estimateTokens(s)+B*(t.output!==void 0?2:1)}}return{kind:o,label:Y[t.role],role:t.role,ref:{turn:e},text:t.text,estimate:estimateTokens(t.text)+B}}$(E,"Z"),g(E,"turnDraft");function J(t){const e=t.turns;let o=e.length;for(;o>0&&e[o-1].kind==="message"&&e[o-1].role!=="assistant";)o--;return e.map((s,n)=>s.kind==="tool"?"tool":s.kind==="reasoning"?"history":s.role==="developer"||s.role==="system"?"context":n>=o&&s.role==="user"?"turn":"history")}$(J,"F"),g(J,"turnKinds");function K(t){const e=t.system.map((c,f)=>({kind:"system",label:c.source==="instructions"?"System prompt \xB7 instructions":`System prompt \xB7 ${c.source}`,ref:{system:f},text:c.text,estimate:estimateTokens(c.text)+B})),o=t.tools.map(c=>JSON.stringify({name:c.name,description:c.description,parameters:c.parameters})).join(`
5
+ `),s=t.tools.length?[{kind:"tools",label:`${t.tools.length} tool${t.tools.length===1?"":"s"} offered`,ref:{tools:!0},text:o,estimate:estimateTokens(o)*I}]:[],n=t.answer.format?.schema!==void 0?JSON.stringify(t.answer.format.schema):"",r=n?[{kind:"schema",label:`Answer schema${t.answer.format?.name?` \xB7 ${t.answer.format.name}`:""}`,ref:{schema:!0},text:n,estimate:estimateTokens(n)*I}]:[],h=J(t),u=t.turns.map((c,f)=>E(c,f,h[f])).filter(c=>!!c);for(const c of u){const f=t.turns[c.ref.turn];f.kind==="message"&&f.attachments?.length&&(c.label+=` \xB7 ${f.attachments.join(", ")}`)}return t.provider==="anthropic"?[...s,...e,...r,...u]:[...e,...s,...r,...u]}$(K,"U"),g(K,"draftsOf");export function aiContextOf(t,e={}){const o=e.sections!==!1,s=K(t),n=Math.round(s.reduce((a,m)=>a+m.estimate,0)),r=t.usage,h=r?.input!==void 0&&r.input>0,u=h?r.input:n,c=t.settings.some(a=>a.name==="continues response"),f=t.gaps.some(a=>/^The (request was kept to its first|prompt was not kept)/.test(a)),y=h&&(c||f)&&u>n*1.05?u-n:0,l=c?y:0,p=c?0:y,k=n>0?(u-y)/n:0,x=s.map((a,m)=>({i:m,kind:a.kind,label:a.label,...a.role?{role:a.role}:{},ref:a.ref,chars:a.text.length,tokens:Math.round(a.estimate*k),cached:0,sections:!o||a.kind==="tools"?[]:sectionsOf(a.text)}));l&&x.unshift({i:-1,kind:"carried",label:"The conversation it continues",ref:{carried:!0},chars:0,tokens:l,cached:0,sections:[]}),p&&x.push({i:-1,kind:"unkept",label:"The rest of the request \u2014 not kept",ref:{unkept:!0},chars:0,tokens:p,cached:0,sections:[]});const i=u-x.reduce((a,m)=>a+m.tokens,0);i&&x.length&&(x.reduce((a,m)=>m.tokens>a.tokens?m:a).tokens+=i);for(const a of x)a.kind==="tools"&&o&&(a.sections=t.tools.map(m=>({title:m.server?`${m.server} \u203A ${m.tool}`:m.tool,chars:0,tokens:estimateTokens(JSON.stringify({d:m.description,p:m.parameters}))}))),N(a.sections,a.tokens);x.forEach((a,m)=>a.i=m);const d=Math.min(r?.cached??0,u);let b=d;for(const a of x)a.cached=Math.min(a.tokens,b),b-=a.cached;const w=AI_PART_KINDS.map(a=>{const m=x.filter(A=>A.kind===a);return{kind:a,tokens:m.reduce((A,T)=>A+T.tokens,0),cached:m.reduce((A,T)=>A+T.cached,0),parts:m.length}}).filter(a=>a.parts),v=q(t);return{parts:x,byKind:w,input:u,counted:h,cached:d,...r?.written?{written:r.written}:{},estimated:n,output:v,findings:z(t,x,u,d,v)}}$(aiContextOf,"aiContextOf"),g(aiContextOf,"aiContextOf");function q(t){const e=t.answer,o=e.json!==void 0?JSON.stringify(e.json):e.text??e.refusal??"",s=e.toolCalls.map(p=>`${p.name}(${p.arguments})`).join(`
6
+ `),n=estimateTokens(o),r=estimateTokens(s)+e.toolCalls.length*B,h=t.usage,u=h?.output!==void 0,c=u?h.output:Math.round(n+r),f=Math.min(h?.reasoning??0,c),y=c-f,l=n+r>0?Math.round(r/(n+r)*y):0;return{total:c,reasoning:f,answer:y-l,tools:l,counted:u}}$(q,"X"),g(q,"outputOf");const S=g(t=>Math.round(t).toLocaleString("en-US"),"fmt"),O=g((t,e)=>`${e>0?Math.round(t/e*100):0}%`,"pct");function z(t,e,o,s,n){const r=[],h=t.answer;if(h.status==="incomplete"||/max_output_tokens|length|max_tokens/.test(h.finish??"")){const i=t.settings.find(d=>/max output|max_tokens|max_completion/.test(d.name));r.push({tone:"bad",text:`It stopped at its output cap${i?` (${i.name} ${i.value})`:""} \u2014 the answer is cut.`})}t.gaps.length&&r.push({tone:"warn",text:"Part of the call was not kept \u2014 the split covers what was."});const u=t.turns.reduce((i,d)=>i+(d.kind==="message"?d.attachments?.length??0:0),0);u&&r.push({tone:"info",text:`${u} image${u===1?"":"s"} or file${u===1?"":"s"} went with its messages: their tokens are counted by the provider but not read from the text, so the split spreads them over the parts.`});const c=t.usage;if(c?.input!==void 0&&o>=1024){if(!s)r.push({tone:"warn",text:`None of its ${S(o)} input tokens came from the prompt cache${c.written?` \u2014 ${S(c.written)} were written to it, for a later call that opens the same way`:""}.`});else if(s<o*.9){const w=e.find(v=>v.cached<v.tokens);w&&r.push({tone:"info",text:`${O(s,o)} cached \u2014 the cache stopped in \xAB${w.label}\xBB: from there on the prompt differed from the last call that opened the same way.`})}const i=e.findIndex(w=>w.kind==="context"),d=i>=0?e.slice(i+1).filter(w=>w.kind==="history"||w.kind==="tool"):[],b=d.reduce((w,v)=>w+v.tokens,0);i>=0&&d.length>=2&&e[i].cached<e[i].tokens&&b>0&&r.push({tone:"info",text:`The context the app put in sits before ${d.length} earlier turns (${S(b)} tokens): when it changes between calls, nothing after it can be read from the cache.`})}const f=e.flatMap(i=>i.sections.filter(d=>d.tag).map(d=>({p:i,x:d}))),y=f.findIndex(({x:i})=>CHANGING_TAGS.has(i.tag)),l=y>=0?f.slice(y+1).filter(({x:i})=>STABLE_TAGS.has(i.tag)):[];if(y>=0&&l.length){const i=f[y].x,d=l.reduce((b,{x:w})=>b+w.tokens,0);r.push({tone:"info",text:`\xAB${i.title}\xBB changes from call to call and comes before ${l.length} section${l.length===1?"":"s"} that should not (\xAB${l[0].x.title}\xBB\u2026, ${S(d)} tokens): put the stable ones first, or they cannot be read from the cache.`})}const p=e.filter(i=>i.kind!=="carried").reduce((i,d)=>!i||d.tokens>i.tokens?d:i,void 0);if(p&&o>2e3&&p.tokens>o*.5){const i=p.sections.reduce((d,b)=>!d||b.tokens>d.tokens?b:d,void 0);r.push({tone:"info",text:`\xAB${p.label}\xBB is ${O(p.tokens,o)} of the input${i&&i.tokens>p.tokens*.4?` \u2014 most of it \xAB${i.title}\xBB (${S(i.tokens)} tokens)`:""}.`})}const k=e.find(i=>i.kind==="tools"),x=h.toolCalls.length;return k&&k.tokens>o*.2&&!x&&!t.turns.some(i=>i.kind==="tool")&&r.push({tone:"info",text:`${t.tools.length} tool definitions are ${O(k.tokens,o)} of the input, and it called none of them.`}),n.total>=200&&n.reasoning>n.total*.7&&r.push({tone:"info",text:`${O(n.reasoning,n.total)} of its output was reasoning (${S(n.reasoning)} tokens).`}),r}$(z,"Q"),g(z,"findingsOf");export function aiSplitOf(t){return Object.fromEntries(t.byKind.filter(e=>e.tokens>0).map(e=>[e.kind,e.tokens]))}$(aiSplitOf,"aiSplitOf"),g(aiSplitOf,"aiSplitOf");
package/lib/ai-origins.js CHANGED
@@ -1,10 +1,10 @@
1
- "use strict";var Mt=Object.defineProperty;var v=(t,e)=>Mt(t,"name",{value:e,configurable:!0});var Tt=Object.defineProperty,y=v((t,e)=>Tt(t,"name",{value:e,configurable:!0}),"v"),Nt=Object.defineProperty,c=y((t,e)=>Nt(t,"name",{value:e,configurable:!0}),"a");import{aiContextOf as ht}from"./ai-context.js";const pt=8,gt=24,wt=32,qt=80,mt=400,Jt=200,Ct=1e6,Wt=12;export function normText(t){return(t.includes("\\")?t.replace(/\\[nrt]/g," ").replace(/\\(["\\/])/g,"$1"):t).replace(/\s\s+|[^\S ]/g," ").trim()}v(normText,"normText"),y(normText,"normText"),c(normText,"normText");function b(t){const e=t.trim();if(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]"))try{return JSON.stringify(JSON.parse(e))}catch{}return normText(e)}v(b,"S"),y(b,"I"),c(b,"canonical");const P=wt,Y=16777619,_t=(()=>{let t=1;for(let e=1;e<P;e++)t=Math.imul(t,Y);return t})(),$t=1<<18,vt=$t-1;function D(t){let e=0;for(let r=0;r<P;r++)e=Math.imul(e,Y)+t.charCodeAt(r)|0;return e}v(D,"Q"),y(D,"ue"),c(D,"headHash");class zt{static{v(this,"Wt")}static{y(this,"Ne")}static{c(this,"PassageIndex")}constructor(){this.by=new Map,this.bits=new Uint32Array($t>>>5),this.n=0}add(e){const r=D(e.text),o=this.by.get(r);o?o.push(e):this.by.set(r,[e]),this.bits[(r&vt)>>>5]|=1<<(r&31),this.n++}get size(){return this.n}find(e,r){if(!this.n||e.length<P)return;const o=new Set,n=this.bits;let i=D(e);for(let u=0;;u++){const h=(n[(i&vt)>>>5]&1<<(i&31))!==0?this.by.get(i):void 0;if(h)for(const w of h)!o.has(w)&&e.startsWith(w.text,u)&&(o.add(w),r(w));if(u+P>=e.length)break;i=Math.imul(i-Math.imul(e.charCodeAt(u),_t)|0,Y)+e.charCodeAt(u+P)|0}}}const yt=c(t=>t.replace(/^(?:mcp__)?[A-Za-z0-9-]+(?:_[A-Za-z0-9-]+)*__/,""),"toolName");function N(t,e,r,o=0){if(!(o>Wt)){if(typeof t=="string")e(t,r);else if(Array.isArray(t))for(const n of t)N(n,e,r,o+1);else if(t&&typeof t=="object")for(const[n,i]of Object.entries(t))N(i,e,n,o+1)}}v(N,"C"),y(N,"T"),c(N,"strings");const tt=c(t=>{const e=t.trim();if(!(!e.startsWith("{")&&!e.startsWith("[")))try{return JSON.parse(e)}catch{return}},"parseJson");function et(t){const e=t.answer,r=[],o=c((n,i)=>{const u=b(n);u.length>=pt&&r.push({key:u,text:normText(n),...i?{what:i}:{}})},"add");e.text!==void 0&&o(e.text),e.json!==void 0&&(e.text===void 0&&o(JSON.stringify(e.json)),N(e.json,(n,i)=>{n.trim().length>=gt&&o(n,i?`its \xAB${i}\xBB`:void 0)}));for(const n of e.toolCalls){const i=n.tool||yt(n.name);o(n.arguments,`its call of ${i}`),N(tt(n.arguments),(u,h)=>{u.trim().length>=gt&&o(u,h?`${i}\u2019s \xAB${h}\xBB`:`its call of ${i}`)})}return r}v(et,"gt"),y(et,"_e"),c(et,"answerKeys");function nt(t){const e=[],r=new Set,o=c((h,w,x)=>{if(e.length>=Jt||r.has(h))return;r.add(h);const A={text:h,e:t,...w?{what:w}:{},...x?{parent:x}:{}};return e.push(A),A},"push"),n=c((h,w,x,A)=>{const[B,...R]=A;if(B)for(const z of h.split(B)){const q=normText(z);if(q.length<qt||q===x?.text)continue;const U=o(q,w,x)??x;q.length>mt&&n(z,w,U,R)}},"pieces"),i=c((h,w)=>{const x=normText(h);if(x.length<wt)return;const A=o(x,w);x.length>mt&&n(h,w,A,[/\n\s*\n/,/\n/,/(?<=[.!?:;])\s+/])},"text"),u=t.call.answer;u.json!==void 0?N(u.json,(h,w)=>i(h,w?`its \xAB${w}\xBB`:void 0)):u.text!==void 0&&i(u.text);for(const h of u.toolCalls){const w=h.tool||yt(h.name),x=tt(h.arguments);x!==void 0?N(x,(A,B)=>i(A,B?`${w}\u2019s \xAB${B}\xBB`:`its call of ${w}`)):i(h.arguments,`its call of ${w}`)}return e}v(nt,"wt"),y(nt,"je"),c(nt,"passagesOf");function st(t){const e=[];let r=Ct;const o=c(n=>{if(r<=0||!n)return;const i=n.length>r?n.slice(0,r):n;r-=i.length,e.push(i)},"take");for(const n of t.system)o(n.text);for(const n of t.turns)n.kind==="tool"?(o(n.arguments),o(n.output??"")):o(n.text??"");return e}v(st,"mt"),y(st,"Te"),c(st,"inputTexts");function C(t,e){const r=e.ref;if("system"in r)return t.system[r.system]?.text??"";if("tools"in r)return t.tools.map(o=>JSON.stringify({name:o.name,description:o.description,parameters:o.parameters})).join(`
2
- `);if("schema"in r)return t.answer.format?.schema!==void 0?JSON.stringify(t.answer.format.schema):"";if("turn"in r){const o=t.turns[r.turn];return o?o.kind==="tool"?`${o.name}(${o.arguments})${o.output!==void 0?`
3
- ${o.output}`:""}`:o.text??"":""}return""}v(C,"_"),y(C,"K"),c(C,"partText");export const aiPartText=c((t,e)=>C(t,e),"aiPartText"),aiSectionTexts=c((t,e)=>W(t,e,C(t,e)),"aiSectionTexts");function ot(t){const e=tt(t);if(e===void 0)return[];const r=e&&typeof e=="object"&&!Array.isArray(e)?e.properties:void 0,o=r&&typeof r=="object"&&!Array.isArray(r)?r:e;return(Array.isArray(o)?o:o&&typeof o=="object"?Object.values(o):[]).map(n=>typeof n=="string"?n:JSON.stringify(n,null,2)??"")}v(ot,"$t"),y(ot,"Ee"),c(ot,"jsonMemberTexts");function W(t,e,r){if(e.kind==="tools")return t.tools.map(n=>JSON.stringify({d:n.description,p:n.parameters}));let o;return e.sections.map((n,i)=>n.at!==void 0&&n.end!==void 0?r.slice(n.at,n.end):(o??=ot(r),o[i]??""))}v(W,"z"),y(W,"B"),c(W,"sectionTexts");function _(t){const e=new Map;return t.sections.map(r=>{const o=e.get(r.title)??0;return e.set(r.title,o+1),`${r.title}#${o}`})}v(_,"E"),y(_,"F"),c(_,"titled");function G(t){return t?t.kind==="tool"?`tool
1
+ "use strict";var It=Object.defineProperty;var v=(t,e)=>It(t,"name",{value:e,configurable:!0});var Mt=Object.defineProperty,c=v((t,e)=>Mt(t,"name",{value:e,configurable:!0}),"a");import{aiContextOf as at}from"./ai-context.js";const ct=8,lt=24,ft=32,Nt=80,ut=400,Tt=200,Ct=1e6,Jt=12;export function normText(t){return(t.includes("\\")?t.replace(/\\[nrt]/g," ").replace(/\\(["\\/])/g,"$1"):t).replace(/\s\s+|[^\S ]/g," ").trim()}v(normText,"normText"),c(normText,"normText");function S(t){const e=t.trim();if(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]"))try{return JSON.stringify(JSON.parse(e))}catch{}return normText(e)}v(S,"I"),c(S,"canonical");const W=ft,G=16777619,qt=(()=>{let t=1;for(let e=1;e<W;e++)t=Math.imul(t,G);return t})(),dt=1<<18,ht=dt-1;function Q(t){let e=0;for(let s=0;s<W;s++)e=Math.imul(e,G)+t.charCodeAt(s)|0;return e}v(Q,"ue"),c(Q,"headHash");class Wt{static{v(this,"Ne")}static{c(this,"PassageIndex")}constructor(){this.by=new Map,this.bits=new Uint32Array(dt>>>5),this.n=0}add(e){const s=Q(e.text),r=this.by.get(s);r?r.push(e):this.by.set(s,[e]),this.bits[(s&ht)>>>5]|=1<<(s&31),this.n++}get size(){return this.n}find(e,s){if(!this.n||e.length<W)return;const r=new Set,n=this.bits;let a=Q(e);for(let u=0;;u++){const h=(n[(a&ht)>>>5]&1<<(a&31))!==0?this.by.get(a):void 0;if(h)for(const w of h)!r.has(w)&&e.startsWith(w.text,u)&&(r.add(w),s(w));if(u+W>=e.length)break;a=Math.imul(a-Math.imul(e.charCodeAt(u),qt)|0,G)+e.charCodeAt(u+W)|0}}}const pt=c(t=>t.replace(/^(?:mcp__)?[A-Za-z0-9-]+(?:_[A-Za-z0-9-]+)*__/,""),"toolName");function C(t,e,s,r=0){if(!(r>Jt)){if(typeof t=="string")e(t,s);else if(Array.isArray(t))for(const n of t)C(n,e,s,r+1);else if(t&&typeof t=="object")for(const[n,a]of Object.entries(t))C(a,e,n,r+1)}}v(C,"T"),c(C,"strings");const V=c(t=>{const e=t.trim();if(!(!e.startsWith("{")&&!e.startsWith("[")))try{return JSON.parse(e)}catch{return}},"parseJson");function gt(t){const e=t.answer,s=[],r=c((n,a)=>{const u=S(n);u.length>=ct&&s.push({key:u,text:normText(n),...a?{what:a}:{}})},"add");e.text!==void 0&&r(e.text),e.json!==void 0&&(e.text===void 0&&r(JSON.stringify(e.json)),C(e.json,(n,a)=>{n.trim().length>=lt&&r(n,a?`its \xAB${a}\xBB`:void 0)}));for(const n of e.toolCalls){const a=n.tool||pt(n.name);r(n.arguments,`its call of ${a}`),C(V(n.arguments),(u,h)=>{u.trim().length>=lt&&r(u,h?`${a}\u2019s \xAB${h}\xBB`:`its call of ${a}`)})}return s}v(gt,"_e"),c(gt,"answerKeys");function wt(t){const e=[],s=new Set,r=c((h,w,x)=>{if(e.length>=Tt||s.has(h))return;s.add(h);const O={text:h,e:t,...w?{what:w}:{},...x?{parent:x}:{}};return e.push(O),O},"push"),n=c((h,w,x,O)=>{const[j,...K]=O;if(j)for(const J of h.split(j)){const N=normText(J);if(N.length<Nt||N===x?.text)continue;const R=r(N,w,x)??x;N.length>ut&&n(J,w,R,K)}},"pieces"),a=c((h,w)=>{const x=normText(h);if(x.length<ft)return;const O=r(x,w);x.length>ut&&n(h,w,O,[/\n\s*\n/,/\n/,/(?<=[.!?:;])\s+/])},"text"),u=t.call.answer;u.json!==void 0?C(u.json,(h,w)=>a(h,w?`its \xAB${w}\xBB`:void 0)):u.text!==void 0&&a(u.text);for(const h of u.toolCalls){const w=h.tool||pt(h.name),x=V(h.arguments);x!==void 0?C(x,(O,j)=>a(O,j?`${w}\u2019s \xAB${j}\xBB`:`its call of ${w}`)):a(h.arguments,`its call of ${w}`)}return e}v(wt,"je"),c(wt,"passagesOf");function mt(t){const e=[];let s=Ct;const r=c(n=>{if(s<=0||!n)return;const a=n.length>s?n.slice(0,s):n;s-=a.length,e.push(a)},"take");for(const n of t.system)r(n.text);for(const n of t.turns)n.kind==="tool"?(r(n.arguments),r(n.output??"")):r(n.text??"");return e}v(mt,"Te"),c(mt,"inputTexts");function _(t,e){const s=e.ref;if("system"in s)return t.system[s.system]?.text??"";if("tools"in s)return t.tools.map(r=>JSON.stringify({name:r.name,description:r.description,parameters:r.parameters})).join(`
2
+ `);if("schema"in s)return t.answer.format?.schema!==void 0?JSON.stringify(t.answer.format.schema):"";if("turn"in s){const r=t.turns[s.turn];return r?r.kind==="tool"?`${r.name}(${r.arguments})${r.output!==void 0?`
3
+ ${r.output}`:""}`:r.text??"":""}return""}v(_,"K"),c(_,"partText");export const aiPartText=c((t,e)=>_(t,e),"aiPartText"),aiSectionTexts=c((t,e)=>z(t,e,_(t,e)),"aiSectionTexts");function $t(t){const e=V(t);if(e===void 0)return[];const s=e&&typeof e=="object"&&!Array.isArray(e)?e.properties:void 0,r=s&&typeof s=="object"&&!Array.isArray(s)?s:e;return(Array.isArray(r)?r:r&&typeof r=="object"?Object.values(r):[]).map(n=>typeof n=="string"?n:JSON.stringify(n,null,2)??"")}v($t,"Ee"),c($t,"jsonMemberTexts");function z(t,e,s){if(e.kind==="tools")return t.tools.map(n=>JSON.stringify({d:n.description,p:n.parameters}));let r;return e.sections.map((n,a)=>n.at!==void 0&&n.end!==void 0?s.slice(n.at,n.end):(r??=$t(s),r[a]??""))}v(z,"B"),c(z,"sectionTexts");function E(t){const e=new Map;return t.sections.map(s=>{const r=e.get(s.title)??0;return e.set(s.title,r+1),`${s.title}#${r}`})}v(E,"F"),c(E,"titled");function X(t){return t?t.kind==="tool"?`tool
4
4
  ${t.name}
5
- ${b(t.arguments)}
6
- ${b(t.output??"")}`:t.kind==="reasoning"?`reasoning
7
- ${b(t.text??"")}`:`${t.role}
8
- ${b(t.text)}`:""}v(G,"X"),y(G,"le"),c(G,"turnKey");const Kt=new Set(["system","tools","schema","context"]),xt=new Set(["history","tool","turn"]);function Q(t){const e=new Map,r=new Map;for(const o of t){if(!Kt.has(o.kind))continue;const n=`${o.kind}:${o.role??""}`,i=e.get(n)??0;e.set(n,i+1),r.set(o,`${n}#${i}`)}return r}v(Q,"Y"),y(Q,"pe"),c(Q,"structureKeys");const kt=c(t=>t.toLocaleString("en-US"),"fmt"),V=c(t=>t.k===1?"the call before":`${t.k} calls earlier`,"ago"),E=c(t=>({id:t.row.id,agent:t.row.agent.name,...t.row.step!==void 0?{step:t.row.step}:{},at:t.row.at,service:t.row.service}),"fromOf"),bt={answer:6,"tool-output":6,quoted:5,carried:4,changed:3,unchanged:2,new:1};function rt(t,e){const r=e.filter(n=>n.row.agent.key===t.agent.key),o=[["thread",t.thread?n=>n.thread?.key===t.thread.key:void 0],["run",n=>n.run.key===t.run.key],["flow",t.flowId?n=>n.flowId===t.flowId:void 0],["request",t.requestId?n=>n.requestId===t.requestId:void 0]];for(const[n,i]of o)if(i){for(let u=r.length-1;u>=0;u--)if(i(r[u].row))return{e:r[u],by:n}}}v(rt,"kt"),y(rt,"We"),c(rt,"previousOf");export function aiOriginsOf(t,e,r){const o=r.filter(s=>s.row.id!==e.id&&s.row.at<=e.at).sort((s,a)=>s.row.at-a.row.at||s.row.id.localeCompare(a.row.id)),n=o.map((s,a)=>({row:s.row,call:s.call,k:o.length-a})),i=rt(e,n),u={compared:n.length,...i?{previous:{id:i.e.row.id,at:i.e.row.at,by:i.by}}:{},items:[]};if(!n.length)return u;const h=new Map,w=new zt;for(const s of n){for(const a of et(s.call)){const d=h.get(a.key);d?d.push({...a,e:s}):h.set(a.key,[{...a,e:s}])}for(const a of nt(s))w.add(a)}const x=new Map,A=new Map,B=c((s,a)=>{const d=`${s.k}
9
- ${a}`;let m=A.get(d);if(m===void 0){let l=x.get(s);l||x.set(s,l=st(s.call).map(normText)),m=l.some(f=>f.includes(a)),A.set(d,m)}return m},"given"),R=c((s,...a)=>{for(const d of a){if(d===void 0)continue;const m=b(d),l=m.length>=pt?h.get(m):void 0;for(let f=(l?.length??0)-1;f>=0;f--){const k=l[f];if(s||!B(k.e,k.text))return{e:k.e,...k.what?{what:k.what}:{}}}}},"answerOf"),z=c((s,a=!1)=>{if(!w.size)return;const d=new Set;if(w.find(normText(s),f=>d.add(f)),!a)for(const f of d)B(f.e,f.text)&&d.delete(f);if(!d.size)return;const m=new Map;for(const f of d){let k=f.parent;for(;k&&!d.has(k);)k=k.parent;if(k)continue;const M=m.get(f.e)??{e:f.e,n:0,what:new Set};M.n++,f.what&&M.what.add(f.what),m.set(f.e,M)}let l;for(const f of m.values())(!l||f.n>l.n||f.n===l.n&&f.e.k<l.e.k)&&(l=f);return l},"quoteIn"),q=c(s=>({how:"answer",from:E(s.e),said:`the answer of ${s.e.row.agent.name}${s.what?` (${s.what})`:""}, ${V(s.e)}`}),"answered"),U=c(s=>({how:"quoted",from:E(s.e),passages:s.n,said:`quotes ${s.n===1?"a passage":`${s.n} passages`} of ${s.e.row.agent.name}\u2019s answer${s.what.size===1?` (${[...s.what][0]})`:""}, ${V(s.e)}`}),"quoted"),at=ht(t);let Z,it=[];if(i){const s=ht(i.e.call);Z=new Map;for(const[a,d]of Q(s.parts))Z.set(d,{part:a,text:C(i.e.call,a)});it=s.parts.filter(a=>xt.has(a.kind)&&"turn"in a.ref).map(a=>G(i.e.call.turns[a.ref.turn]))}const Ot=c(s=>{const a=Z?.get(s);if(a){if(!a.sections){const d=W(i.e.call,a.part,a.text);a.sections=new Map(_(a.part).map((m,l)=>[m,{text:d[l]??"",canon:b(d[l]??"")}]))}return a.sections}},"prevSections"),St=i?`the previous call of this ${i.by}`:"",I=i?E(i.e):void 0,ct=c((s,a)=>`changed since the previous call \u2014 ${kt(s)} \u2192 ${kt(a)} chars`,"changedSaid"),At=Q(at.parts),lt=[...n].reverse();let ft=0;return at.parts.forEach((s,a)=>{if(s.kind==="carried"){const p=e.previousResponseId??t.settings.find(g=>g.name==="continues response")?.value,$=p?lt.find(g=>(g.row.responseId??g.call.responseId)===p):void 0;$&&u.items.push({part:a,how:"carried",from:E($),said:`the conversation of ${$.row.agent.name}\u2019s response it continues, ${V($)} \u2014 held by the provider, not sent again`});return}const d=C(t,s),m="turn"in s.ref?t.turns[s.ref.turn]:void 0;let l,f;const k=At.get(s);if(i&&k){const p=Z.get(k);p?b(p.text)===b(d)?l={part:a,how:"unchanged",from:I,said:`unchanged since ${St}`}:(l={part:a,how:"changed",from:I,said:ct(p.text.length,d.length),chars:{before:p.text.length,after:d.length}},f=Ot(k)):l={part:a,how:"new",from:I,said:"new since the previous call"}}else if(i&&xt.has(s.kind)){const p=G(m),$=it.indexOf(p,ft);$>=0?(ft=$+1,l={part:a,how:"carried",from:I,said:"carried from the previous call"}):l={part:a,how:"new",from:I,said:"new since the previous call"}}const M=l&&l.how!=="carried"?l.how:l?"unchanged":void 0;let O;if(m?.kind==="tool"&&m.callId){const p=m.callId,$=lt.find(g=>g.row.callIds?.includes(p)||g.call.answer.toolCalls.some(S=>S.callId===p));if($){const g=$.row.step!==void 0&&$.row.run.key===e.run.key?`called in step ${$.row.step}`:`called by ${$.row.agent.name}, ${V($)}`;O={part:a,how:"tool-output",from:E($),said:`returned by tool ${m.tool} (${g})`}}}const F=m?.kind==="message"&&m.role==="assistant";if(!O){const p=R(F,m?.kind==="tool"?m.output:d);p&&(O={part:a,...q(p)})}const X=O?void 0:z(d,F);X&&(O={part:a,...U(X)}),O&&M&&(O.since=M),O&&l?.chars&&(O.chars=l.chars);const J=O&&(!l||bt[O.how]>=bt[l.how])?O:l;if(J&&f&&J.how==="changed"){const p=new Set(_(s)),$=[...f.keys()].filter(j=>!p.has(j)).map(j=>j.replace(/#\d+$/,"")),g={changed:0,new:0},S=W(t,s,d);_(s).forEach((j,H)=>{const T=f.get(j);T?T.canon!==b(S[H]??"")&&g.changed++:g.new++});const K=[g.changed?`${g.changed} of ${s.sections.length} sections changed`:"",g.new?`${g.new} new`:"",$.length?`${$.length} gone (${$.slice(0,3).map(j=>`\xAB${j}\xBB`).join(", ")}${$.length>3?", \u2026":""})`:""].filter(Boolean);K.length&&(J.said+=`: ${K.join(", ")}`)}if(J&&u.items.push(J),!s.sections.length||J?.how==="answer"||J?.how==="tool-output")return;const jt=W(t,s,d),Bt=_(s),It=!!X;s.sections.forEach((p,$)=>{const g=jt[$]??"";if(!g)return;let S;if(f){const L=f.get(Bt[$]);L?L.canon===b(g)?S={part:a,section:p.title,how:"unchanged",from:I,said:"unchanged since the previous call"}:S={part:a,section:p.title,how:"changed",from:I,said:ct(L.text.length,g.length),chars:{before:L.text.length,after:g.length}}:S={part:a,section:p.title,how:"new",from:I,said:"new since the previous call"}}const K=p.at!==void 0&&p.title!=="(opening)"?g.indexOf(`
10
- `):-1,j=R(F,g,K>0?g.slice(K+1):void 0),H=j?void 0:It?z(g,F):void 0,T=j?{part:a,section:p.title,...q(j)}:H?{part:a,section:p.title,...U(H)}:void 0,ut=S?S.how:M!=="changed"?M:void 0;T&&ut&&(T.since=ut),T&&S?.chars&&(T.chars=S.chars);const dt=T??S;dt&&u.items.push(dt)})}),u}v(aiOriginsOf,"aiOriginsOf"),y(aiOriginsOf,"aiOriginsOf"),c(aiOriginsOf,"aiOriginsOf");
5
+ ${S(t.arguments)}
6
+ ${S(t.output??"")}`:t.kind==="reasoning"?`reasoning
7
+ ${S(t.text??"")}`:`${t.role}
8
+ ${S(t.text)}`:""}v(X,"le"),c(X,"turnKey");const _t=new Set(["system","tools","schema","context"]),vt=new Set(["history","tool","turn"]);function Y(t){const e=new Map,s=new Map;for(const r of t){if(!_t.has(r.kind))continue;const n=`${r.kind}:${r.role??""}`,a=e.get(n)??0;e.set(n,a+1),s.set(r,`${n}#${a}`)}return s}v(Y,"pe"),c(Y,"structureKeys");const xt=c(t=>t.toLocaleString("en-US"),"fmt"),D=c(t=>t.k===1?"the call before":`${t.k} calls earlier`,"ago"),P=c(t=>({id:t.row.id,agent:t.row.agent.name,...t.row.step!==void 0?{step:t.row.step}:{},at:t.row.at,service:t.row.service}),"fromOf"),yt={answer:6,"tool-output":6,quoted:5,carried:4,changed:3,unchanged:2,new:1};function kt(t,e){const s=e.filter(n=>n.row.agent.key===t.agent.key),r=[["thread",t.thread?n=>n.thread?.key===t.thread.key:void 0],["run",n=>n.run.key===t.run.key],["flow",t.flowId?n=>n.flowId===t.flowId:void 0],["request",t.requestId?n=>n.requestId===t.requestId:void 0]];for(const[n,a]of r)if(a){for(let u=s.length-1;u>=0;u--)if(a(s[u].row))return{e:s[u],by:n}}}v(kt,"We"),c(kt,"previousOf");export function aiOriginsOf(t,e,s){const r=s.filter(o=>o.row.id!==e.id&&o.row.at<=e.at).sort((o,i)=>o.row.at-i.row.at||o.row.id.localeCompare(i.row.id)),n=r.map((o,i)=>({row:o.row,call:o.call,k:r.length-i})),a=kt(e,n),u={compared:n.length,...a?{previous:{id:a.e.row.id,at:a.e.row.at,by:a.by}}:{},items:[]};if(!n.length)return u;const h=new Map,w=new Wt;for(const o of n){for(const i of gt(o.call)){const d=h.get(i.key);d?d.push({...i,e:o}):h.set(i.key,[{...i,e:o}])}for(const i of wt(o))w.add(i)}const x=new Map,O=new Map,j=c((o,i)=>{const d=`${o.k}
9
+ ${i}`;let m=O.get(d);if(m===void 0){let l=x.get(o);l||x.set(o,l=mt(o.call).map(normText)),m=l.some(f=>f.includes(i)),O.set(d,m)}return m},"given"),K=c((o,...i)=>{for(const d of i){if(d===void 0)continue;const m=S(d),l=m.length>=ct?h.get(m):void 0;for(let f=(l?.length??0)-1;f>=0;f--){const y=l[f];if(o||!j(y.e,y.text))return{e:y.e,...y.what?{what:y.what}:{}}}}},"answerOf"),J=c((o,i=!1)=>{if(!w.size)return;const d=new Set;if(w.find(normText(o),f=>d.add(f)),!i)for(const f of d)j(f.e,f.text)&&d.delete(f);if(!d.size)return;const m=new Map;for(const f of d){let y=f.parent;for(;y&&!d.has(y);)y=y.parent;if(y)continue;const I=m.get(f.e)??{e:f.e,n:0,what:new Set};I.n++,f.what&&I.what.add(f.what),m.set(f.e,I)}let l;for(const f of m.values())(!l||f.n>l.n||f.n===l.n&&f.e.k<l.e.k)&&(l=f);return l},"quoteIn"),N=c(o=>({how:"answer",from:P(o.e),said:`the answer of ${o.e.row.agent.name}${o.what?` (${o.what})`:""}, ${D(o.e)}`}),"answered"),R=c(o=>({how:"quoted",from:P(o.e),passages:o.n,said:`quotes ${o.n===1?"a passage":`${o.n} passages`} of ${o.e.row.agent.name}\u2019s answer${o.what.size===1?` (${[...o.what][0]})`:""}, ${D(o.e)}`}),"quoted"),tt=at(t);let U,et=[];if(a){const o=at(a.e.call);U=new Map;for(const[i,d]of Y(o.parts))U.set(d,{part:i,text:_(a.e.call,i)});et=o.parts.filter(i=>vt.has(i.kind)&&"turn"in i.ref).map(i=>X(a.e.call.turns[i.ref.turn]))}const bt=c(o=>{const i=U?.get(o);if(i){if(!i.sections){const d=z(a.e.call,i.part,i.text);i.sections=new Map(E(i.part).map((m,l)=>[m,{text:d[l]??"",canon:S(d[l]??"")}]))}return i.sections}},"prevSections"),St=a?`the previous call of this ${a.by}`:"",B=a?P(a.e):void 0,nt=c((o,i)=>`changed since the previous call \u2014 ${xt(o)} \u2192 ${xt(i)} chars`,"changedSaid"),Ot=Y(tt.parts),ot=[...n].reverse();let rt=0;return tt.parts.forEach((o,i)=>{if(o.kind==="carried"){const p=e.previousResponseId??t.settings.find(g=>g.name==="continues response")?.value,$=p?ot.find(g=>(g.row.responseId??g.call.responseId)===p):void 0;$&&u.items.push({part:i,how:"carried",from:P($),said:`the conversation of ${$.row.agent.name}\u2019s response it continues, ${D($)} \u2014 held by the provider, not sent again`});return}const d=_(t,o),m="turn"in o.ref?t.turns[o.ref.turn]:void 0;let l,f;const y=Ot.get(o);if(a&&y){const p=U.get(y);p?S(p.text)===S(d)?l={part:i,how:"unchanged",from:B,said:`unchanged since ${St}`}:(l={part:i,how:"changed",from:B,said:nt(p.text.length,d.length),chars:{before:p.text.length,after:d.length}},f=bt(y)):l={part:i,how:"new",from:B,said:"new since the previous call"}}else if(a&&vt.has(o.kind)){const p=X(m),$=et.indexOf(p,rt);$>=0?(rt=$+1,l={part:i,how:"carried",from:B,said:"carried from the previous call"}):l={part:i,how:"new",from:B,said:"new since the previous call"}}const I=l&&l.how!=="carried"?l.how:l?"unchanged":void 0;let k;if(m?.kind==="tool"&&m.callId){const p=m.callId,$=ot.find(g=>g.row.callIds?.includes(p)||g.call.answer.toolCalls.some(b=>b.callId===p));if($){const g=$.row.step!==void 0&&$.row.run.key===e.run.key?`called in step ${$.row.step}`:`called by ${$.row.agent.name}, ${D($)}`;k={part:i,how:"tool-output",from:P($),said:`returned by tool ${m.tool} (${g})`}}}const Z=m?.kind==="message"&&m.role==="assistant";if(!k){const p=K(Z,m?.kind==="tool"?m.output:d);p&&(k={part:i,...N(p)})}const F=k?void 0:J(d,Z);F&&(k={part:i,...R(F)}),k&&I&&(k.since=I),k&&l?.chars&&(k.chars=l.chars);const T=k&&(!l||yt[k.how]>=yt[l.how])?k:l;if(T&&f&&T.how==="changed"){const p=new Set(E(o)),$=[...f.keys()].filter(A=>!p.has(A)).map(A=>A.replace(/#\d+$/,"")),g={changed:0,new:0},b=z(t,o,d);E(o).forEach((A,H)=>{const M=f.get(A);M?M.canon!==S(b[H]??"")&&g.changed++:g.new++});const q=[g.changed?`${g.changed} of ${o.sections.length} sections changed`:"",g.new?`${g.new} new`:"",$.length?`${$.length} gone (${$.slice(0,3).map(A=>`\xAB${A}\xBB`).join(", ")}${$.length>3?", \u2026":""})`:""].filter(Boolean);q.length&&(T.said+=`: ${q.join(", ")}`)}if(T&&u.items.push(T),!o.sections.length||T?.how==="answer"||T?.how==="tool-output")return;const At=z(t,o,d),jt=E(o),Bt=!!F;o.sections.forEach((p,$)=>{const g=At[$]??"";if(!g)return;let b;if(f){const L=f.get(jt[$]);L?L.canon===S(g)?b={part:i,section:p.title,how:"unchanged",from:B,said:"unchanged since the previous call"}:b={part:i,section:p.title,how:"changed",from:B,said:nt(L.text.length,g.length),chars:{before:L.text.length,after:g.length}}:b={part:i,section:p.title,how:"new",from:B,said:"new since the previous call"}}const q=p.at!==void 0&&p.title!=="(opening)"?g.indexOf(`
10
+ `):-1,A=K(Z,g,q>0?g.slice(q+1):void 0),H=A?void 0:Bt?J(g,Z):void 0,M=A?{part:i,section:p.title,...N(A)}:H?{part:i,section:p.title,...R(H)}:void 0,st=b?b.how:I!=="changed"?I:void 0;M&&st&&(M.since=st),M&&b?.chars&&(M.chars=b.chars);const it=M??b;it&&u.items.push(it)})}),u}v(aiOriginsOf,"aiOriginsOf"),c(aiOriginsOf,"aiOriginsOf");
@@ -1 +1 @@
1
- "use strict";var T=Object.defineProperty;var c=(t,e)=>T(t,"name",{value:e,configurable:!0});var h=Object.defineProperty,l=c((t,e)=>h(t,"name",{value:e,configurable:!0}),"i"),_=Object.defineProperty,y=l((t,e)=>_(t,"name",{value:e,configurable:!0}),"_");export const DEFAULT_RAW_BYTE_LIMIT=32768,DEFAULT_MAX_STRING_BYTES=4096,DEFAULT_MAX_ARRAY_ITEMS=64,DEFAULT_MAX_DEPTH=12,CHEAP_ENTRY_BYTES=512,NOMINAL_DEEP_BYTES=32,DEEP_REPORT_DEPTH=64,SKELETON_STRING_BYTES=256,MAX_RECORDED_PATHS=20,TRUNCATION_MARKER_KEY="__lensmcpTruncation",TRUNCATED_VALUE_KEY="__lensmcpTruncated";export function estimateJsonBytes(t,e=Number.POSITIVE_INFINITY,n=12){return g(t,e,n,32)}c(estimateJsonBytes,"estimateJsonBytes"),l(estimateJsonBytes,"estimateJsonBytes"),y(estimateJsonBytes,"estimateJsonBytes");export function exceedsJsonByteBudget(t,e,n=12){return g(t,e,n,Number.POSITIVE_INFINITY)>e}c(exceedsJsonByteBudget,"exceedsJsonByteBudget"),l(exceedsJsonByteBudget,"exceedsJsonByteBudget"),y(exceedsJsonByteBudget,"exceedsJsonByteBudget");function g(t,e,n,a){switch(typeof t){case"undefined":case"function":case"symbol":return 0;case"boolean":return 5;case"number":return Number.isFinite(t)?8:4;case"bigint":return 20;case"string":return t.length+2;default:break}if(t===null)return 4;if(n<=0)return a;if(t instanceof Date)return 26;if(Array.isArray(t)){let r=2;for(let u=0;u<t.length;u++)if(r+=g(t[u],e-r,n-1,a)+1,r>e)return r;return r}let s=2;const o=t;for(const r in o){if(!Object.prototype.hasOwnProperty.call(o,r))continue;const u=g(o[r],e-s,n-1,a);if(u!==0&&(s+=r.length+4+u,s>e))return s}return s}c(g,"y"),l(g,"T"),y(g,"walk");function f(t,e){t.truncatedAnything=!0,t.paths.length<20&&t.paths.push(e||"<root>")}c(f,"g"),l(f,"A"),y(f,"record");function p(t,e,n){return f(t,n),{[TRUNCATED_VALUE_KEY]:!0,originalBytes:estimateJsonBytes(e,Number.POSITIVE_INFINITY,64)}}c(p,"f"),l(p,"I"),y(p,"stub");function m(t){if(t===null)return!0;const e=typeof t;return e==="number"||e==="boolean"||e==="string"||e==="bigint"}c(m,"p"),l(m,"y"),y(m,"isScalar");export function clampValue(t,e,n,a){if(typeof t=="string"){const s=e.budget<=0?256:e.maxStringBytes;if(t.length+2<=s)return e.budget-=t.length+2,t;const o=Math.max(0,s-64);return f(e,a),e.budget-=o,`${t.slice(0,o)}\u2026[lensmcp truncated: ${t.length-o} more chars]`}return t===null||typeof t!="object"?(e.budget-=g(t,Number.POSITIVE_INFINITY,1,32),t):n<=0?p(e,t,a):t instanceof Date?(e.budget-=26,t):Array.isArray(t)?b(t,e,n,a):d(t,e,n,a)}c(clampValue,"clampValue"),l(clampValue,"clampValue"),y(clampValue,"clampValue");function b(t,e,n,a){const s=[],o=Math.min(t.length,e.maxArrayItems);for(let r=0;r<o&&!(e.budget<=0);r++)s.push(clampValue(t[r],e,n-1,`${a}[${r}]`));return s.length<t.length&&f(e,`${a}[] (+${t.length-s.length} items dropped)`),s}c(b,"m"),l(b,"f"),y(b,"clampArray");function d(t,e,n,a){const s={};let o;const r=e.budget<=0;for(const u in t){if(!Object.prototype.hasOwnProperty.call(t,u))continue;const i=t[u],I=g(i,512,n-1,Number.POSITIVE_INFINITY);if(I<=512&&(!r||m(i))){s[u]=i,e.budget-=u.length+4+I;continue}(o??=[]).push({key:u,bytes:I})}if(!o)return s;o.sort((u,i)=>u.bytes===i.bytes?0:u.bytes<i.bytes?-1:1);for(const{key:u}of o){const i=a?`${a}.${u}`:u;s[u]=clampValue(t[u],e,n-1,i)}return s}c(d,"b"),l(d,"m"),y(d,"clampObject");export function boundedClone(t,e={}){const n=e.rawByteLimit??32768,a=e.maxDepth??12;if(n<=0)return{value:void 0,truncated:!1,originalBytes:0,keptBytes:0,paths:[]};if(t==null)return{value:t,truncated:!1,originalBytes:0,keptBytes:0,paths:[]};if(!exceedsJsonByteBudget(t,n,a)){const i=estimateJsonBytes(t,n,a),I={budget:n,maxStringBytes:e.maxStringBytes??4096,maxArrayItems:e.maxArrayItems??64,paths:[],truncatedAnything:!1};return{value:clampValue(t,I,a,""),truncated:!1,originalBytes:i,keptBytes:i,paths:[]}}const s=estimateJsonBytes(t,Number.POSITIVE_INFINITY,64),o={budget:n,maxStringBytes:e.maxStringBytes??4096,maxArrayItems:e.maxArrayItems??64,paths:[],truncatedAnything:!1},r=clampValue(t,o,a,""),u=estimateJsonBytes(r,Number.POSITIVE_INFINITY,a);if(o.truncatedAnything&&r!==null&&typeof r=="object"&&!Array.isArray(r)){const i={truncated:!0,originalBytes:s,keptBytes:u,paths:o.paths};r[TRUNCATION_MARKER_KEY]=i}return{value:r,truncated:o.truncatedAnything,originalBytes:s,keptBytes:u,paths:o.paths}}c(boundedClone,"boundedClone"),l(boundedClone,"boundedClone"),y(boundedClone,"boundedClone");
1
+ "use strict";var T=Object.defineProperty;var i=(e,t)=>T(e,"name",{value:t,configurable:!0});var h=Object.defineProperty,l=i((e,t)=>h(e,"name",{value:t,configurable:!0}),"_");export const DEFAULT_RAW_BYTE_LIMIT=32768,DEFAULT_MAX_STRING_BYTES=4096,DEFAULT_MAX_ARRAY_ITEMS=64,DEFAULT_MAX_DEPTH=12,CHEAP_ENTRY_BYTES=512,NOMINAL_DEEP_BYTES=32,DEEP_REPORT_DEPTH=64,SKELETON_STRING_BYTES=256,MAX_RECORDED_PATHS=20,TRUNCATION_MARKER_KEY="__lensmcpTruncation",TRUNCATED_VALUE_KEY="__lensmcpTruncated";export function estimateJsonBytes(e,t=Number.POSITIVE_INFINITY,r=12){return y(e,t,r,32)}i(estimateJsonBytes,"estimateJsonBytes"),l(estimateJsonBytes,"estimateJsonBytes");export function exceedsJsonByteBudget(e,t,r=12){return y(e,t,r,Number.POSITIVE_INFINITY)>t}i(exceedsJsonByteBudget,"exceedsJsonByteBudget"),l(exceedsJsonByteBudget,"exceedsJsonByteBudget");function y(e,t,r,a){switch(typeof e){case"undefined":case"function":case"symbol":return 0;case"boolean":return 5;case"number":return Number.isFinite(e)?8:4;case"bigint":return 20;case"string":return e.length+2;default:break}if(e===null)return 4;if(r<=0)return a;if(e instanceof Date)return 26;if(Array.isArray(e)){let n=2;for(let s=0;s<e.length;s++)if(n+=y(e[s],t-n,r-1,a)+1,n>t)return n;return n}let u=2;const o=e;for(const n in o){if(!Object.prototype.hasOwnProperty.call(o,n))continue;const s=y(o[n],t-u,r-1,a);if(s!==0&&(u+=n.length+4+s,u>t))return u}return u}i(y,"T"),l(y,"walk");function g(e,t){e.truncatedAnything=!0,e.paths.length<20&&e.paths.push(t||"<root>")}i(g,"A"),l(g,"record");function f(e,t,r){return g(e,r),{[TRUNCATED_VALUE_KEY]:!0,originalBytes:estimateJsonBytes(t,Number.POSITIVE_INFINITY,64)}}i(f,"I"),l(f,"stub");function p(e){if(e===null)return!0;const t=typeof e;return t==="number"||t==="boolean"||t==="string"||t==="bigint"}i(p,"y"),l(p,"isScalar");export function clampValue(e,t,r,a){if(typeof e=="string"){const u=t.budget<=0?256:t.maxStringBytes;if(e.length+2<=u)return t.budget-=e.length+2,e;const o=Math.max(0,u-64);return g(t,a),t.budget-=o,`${e.slice(0,o)}\u2026[lensmcp truncated: ${e.length-o} more chars]`}return e===null||typeof e!="object"?(t.budget-=y(e,Number.POSITIVE_INFINITY,1,32),e):r<=0?f(t,e,a):e instanceof Date?(t.budget-=26,e):Array.isArray(e)?m(e,t,r,a):b(e,t,r,a)}i(clampValue,"clampValue"),l(clampValue,"clampValue");function m(e,t,r,a){const u=[],o=Math.min(e.length,t.maxArrayItems);for(let n=0;n<o&&!(t.budget<=0);n++)u.push(clampValue(e[n],t,r-1,`${a}[${n}]`));return u.length<e.length&&g(t,`${a}[] (+${e.length-u.length} items dropped)`),u}i(m,"f"),l(m,"clampArray");function b(e,t,r,a){const u={};let o;const n=t.budget<=0;for(const s in e){if(!Object.prototype.hasOwnProperty.call(e,s))continue;const c=e[s],I=y(c,512,r-1,Number.POSITIVE_INFINITY);if(I<=512&&(!n||p(c))){u[s]=c,t.budget-=s.length+4+I;continue}(o??=[]).push({key:s,bytes:I})}if(!o)return u;o.sort((s,c)=>s.bytes===c.bytes?0:s.bytes<c.bytes?-1:1);for(const{key:s}of o){const c=a?`${a}.${s}`:s;u[s]=clampValue(e[s],t,r-1,c)}return u}i(b,"m"),l(b,"clampObject");export function boundedClone(e,t={}){const r=t.rawByteLimit??32768,a=t.maxDepth??12;if(r<=0)return{value:void 0,truncated:!1,originalBytes:0,keptBytes:0,paths:[]};if(e==null)return{value:e,truncated:!1,originalBytes:0,keptBytes:0,paths:[]};if(!exceedsJsonByteBudget(e,r,a)){const c=estimateJsonBytes(e,r,a),I={budget:r,maxStringBytes:t.maxStringBytes??4096,maxArrayItems:t.maxArrayItems??64,paths:[],truncatedAnything:!1};return{value:clampValue(e,I,a,""),truncated:!1,originalBytes:c,keptBytes:c,paths:[]}}const u=estimateJsonBytes(e,Number.POSITIVE_INFINITY,64),o={budget:r,maxStringBytes:t.maxStringBytes??4096,maxArrayItems:t.maxArrayItems??64,paths:[],truncatedAnything:!1},n=clampValue(e,o,a,""),s=estimateJsonBytes(n,Number.POSITIVE_INFINITY,a);if(o.truncatedAnything&&n!==null&&typeof n=="object"&&!Array.isArray(n)){const c={truncated:!0,originalBytes:u,keptBytes:s,paths:o.paths};n[TRUNCATION_MARKER_KEY]=c}return{value:n,truncated:o.truncatedAnything,originalBytes:u,keptBytes:s,paths:o.paths}}i(boundedClone,"boundedClone"),l(boundedClone,"boundedClone");
@@ -1 +1 @@
1
- "use strict";var i=Object.defineProperty;var t=(e,a)=>i(e,"name",{value:a,configurable:!0});var p=Object.defineProperty,o=t((e,a)=>p(e,"name",{value:a,configurable:!0}),"t"),s=Object.defineProperty,u=o((e,a)=>s(e,"name",{value:a,configurable:!0}),"o");export function capMap(e,a){if(e.size<=a)return 0;let r=0;const c=e.keys();for(;e.size>a;){const n=c.next();if(n.done)break;e.delete(n.value)&&(r+=1)}return r}t(capMap,"capMap"),o(capMap,"capMap"),u(capMap,"capMap");export const MAX_PRODUCER_KEYS=256;
1
+ "use strict";var c=Object.defineProperty;var t=(e,r)=>c(e,"name",{value:r,configurable:!0});var i=Object.defineProperty,s=t((e,r)=>i(e,"name",{value:r,configurable:!0}),"o");export function capMap(e,r){if(e.size<=r)return 0;let n=0;const o=e.keys();for(;e.size>r;){const a=o.next();if(a.done)break;e.delete(a.value)&&(n+=1)}return n}t(capMap,"capMap"),s(capMap,"capMap");export const MAX_PRODUCER_KEYS=256;
@@ -1 +1 @@
1
- "use strict";var m=Object.defineProperty;var r=(t,e)=>m(t,"name",{value:e,configurable:!0});var f=Object.defineProperty,o=r((t,e)=>f(t,"name",{value:e,configurable:!0}),"r"),x=Object.defineProperty,s=o((t,e)=>x(t,"name",{value:e,configurable:!0}),"c");import{renameSync as v,statSync as M,unlinkSync as E}from"node:fs";export function eventMaxBytes(t=process.env){const e=Number(t.LENSMCP_EVENT_MAX_BYTES);return Number.isFinite(e)&&e>0?e:50*1024*1024}r(eventMaxBytes,"eventMaxBytes"),o(eventMaxBytes,"eventMaxBytes"),s(eventMaxBytes,"eventMaxBytes");export function eventMaxFiles(t=process.env){const e=Number(t.LENSMCP_EVENT_MAX_FILES);return Number.isFinite(e)&&e>=1&&e<=20?Math.floor(e):5}r(eventMaxFiles,"eventMaxFiles"),o(eventMaxFiles,"eventMaxFiles"),s(eventMaxFiles,"eventMaxFiles");const b=1024*1024,a=new Map;export function maybeRotateEventFile(t,e,c){const i=(a.get(t)??0)+e,l=c?.maxBytes??eventMaxBytes(),u=c?.maxFiles??eventMaxFiles(),y=Math.min(b,l);if(i<y){a.set(t,i);return}try{const n=M(t).size;if(a.set(t,0),n<=l)return}catch{a.set(t,i);return}try{E(`${t}.${u}`)}catch{}for(let n=u-1;n>=1;n--)try{v(`${t}.${n}`,`${t}.${n+1}`)}catch{}try{v(t,`${t}.1`)}catch{}}r(maybeRotateEventFile,"maybeRotateEventFile"),o(maybeRotateEventFile,"maybeRotateEventFile"),s(maybeRotateEventFile,"maybeRotateEventFile");export function resetRotationThrottle(t){t===void 0?a.clear():a.delete(t)}r(resetRotationThrottle,"resetRotationThrottle"),o(resetRotationThrottle,"resetRotationThrottle"),s(resetRotationThrottle,"resetRotationThrottle");
1
+ "use strict";var y=Object.defineProperty;var r=(e,t)=>y(e,"name",{value:t,configurable:!0});var v=Object.defineProperty,o=r((e,t)=>v(e,"name",{value:t,configurable:!0}),"c");import{renameSync as l,statSync as f,unlinkSync as x}from"node:fs";export function eventMaxBytes(e=process.env){const t=Number(e.LENSMCP_EVENT_MAX_BYTES);return Number.isFinite(t)&&t>0?t:50*1024*1024}r(eventMaxBytes,"eventMaxBytes"),o(eventMaxBytes,"eventMaxBytes");export function eventMaxFiles(e=process.env){const t=Number(e.LENSMCP_EVENT_MAX_FILES);return Number.isFinite(t)&&t>=1&&t<=20?Math.floor(t):5}r(eventMaxFiles,"eventMaxFiles"),o(eventMaxFiles,"eventMaxFiles");const E=1024*1024,a=new Map;export function maybeRotateEventFile(e,t,i){const s=(a.get(e)??0)+t,c=i?.maxBytes??eventMaxBytes(),u=i?.maxFiles??eventMaxFiles(),m=Math.min(E,c);if(s<m){a.set(e,s);return}try{const n=f(e).size;if(a.set(e,0),n<=c)return}catch{a.set(e,s);return}try{x(`${e}.${u}`)}catch{}for(let n=u-1;n>=1;n--)try{l(`${e}.${n}`,`${e}.${n+1}`)}catch{}try{l(e,`${e}.1`)}catch{}}r(maybeRotateEventFile,"maybeRotateEventFile"),o(maybeRotateEventFile,"maybeRotateEventFile");export function resetRotationThrottle(e){e===void 0?a.clear():a.delete(e)}r(resetRotationThrottle,"resetRotationThrottle"),o(resetRotationThrottle,"resetRotationThrottle");
@@ -1 +1 @@
1
- "use strict";var 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";
1
+ "use strict";var c=Object.defineProperty;var o=(t,e)=>c(t,"name",{value:e,configurable:!0});var s=Object.defineProperty,u=o((t,e)=>s(t,"name",{value:e,configurable:!0}),"s");export const CAPTURE_REQUEST_FILENAME="capture-request.json",CAPTURE_PRESENCE_FILENAME="capture-runner.json";export function appMatchesPage(t,e){const r=t.trim().toLowerCase();if(!r)return!1;if(e.project&&e.project.toLowerCase()===r)return!0;const n=e.url.toLowerCase();if(n===r||n.replace(/\/+$/,"")===r.replace(/\/+$/,""))return!0;try{const a=new URL(e.url);return/^\d+$/.test(r)?a.port===r:a.origin.toLowerCase()===r.replace(/\/+$/,"")}catch{return!1}}o(appMatchesPage,"appMatchesPage"),u(appMatchesPage,"appMatchesPage");export const CAPTURE_RULES_FILENAME="capture-rules.json";
@@ -1 +1 @@
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");
1
+ "use strict";var f=Object.defineProperty;var s=(t,r)=>f(t,"name",{value:r,configurable:!0});var E=Object.defineProperty,S=s((t,r)=>E(t,"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 g=2048;export const MAX_DISMISSAL_REASON_CHARS=500;const m=300,I=new Set(["dashboard","cli","agent"]);export function readErrorDismissal(t){if(t.source!==LENS_EVENT_SOURCE||!t.raw||typeof t.raw!="object")return;const r=t.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 c=Array.isArray(r.eventIds)?r.eventIds.filter(e=>typeof e=="string"&&e.length>0).slice(0,200):[],o=I.has(r.by)?r.by:void 0,a=S((e,l)=>typeof e=="string"&&e.trim()?e.trim().slice(0,l):void 0,"text"),d=a(r.reason,500),u=a(r.title,300);return{kind:ERROR_DISMISSED,groupId:i,until:Math.min(n,t.timestamp),eventIds:c,...o?{by:o}:{},...d?{reason:d}:{},...u?{title:u}:{}}}s(readErrorDismissal,"readErrorDismissal"),S(readErrorDismissal,"readErrorDismissal");
package/lib/event-loop.js CHANGED
@@ -1 +1 @@
1
- "use strict";var s=Object.defineProperty;var r=(e,t)=>s(e,"name",{value:t,configurable:!0});var u=Object.defineProperty,o=r((e,t)=>u(e,"name",{value:t,configurable:!0}),"r"),c=Object.defineProperty,i=o((e,t)=>c(e,"name",{value:t,configurable:!0}),"e");export const LOOP_STARTUP_MS=6e4;export function loopStartedAt(e){if(!e.startsWith("node:"))return;const t=Number(e.slice(e.lastIndexOf(":")+1));return Number.isFinite(t)&&t>0?t:void 0}r(loopStartedAt,"loopStartedAt"),o(loopStartedAt,"loopStartedAt"),i(loopStartedAt,"loopStartedAt");export function loopPhaseAt(e,t){const n=loopStartedAt(e);if(n===void 0)return;const a=Math.max(0,Math.round(t-n));return{phase:a<6e4?"startup":"running",sinceStartMs:a}}r(loopPhaseAt,"loopPhaseAt"),o(loopPhaseAt,"loopPhaseAt"),i(loopPhaseAt,"loopPhaseAt");
1
+ "use strict";var a=Object.defineProperty;var r=(t,e)=>a(t,"name",{value:e,configurable:!0});var i=Object.defineProperty,s=r((t,e)=>i(t,"name",{value:e,configurable:!0}),"e");export const LOOP_STARTUP_MS=6e4;export function loopStartedAt(t){if(!t.startsWith("node:"))return;const e=Number(t.slice(t.lastIndexOf(":")+1));return Number.isFinite(e)&&e>0?e:void 0}r(loopStartedAt,"loopStartedAt"),s(loopStartedAt,"loopStartedAt");export function loopPhaseAt(t,e){const n=loopStartedAt(t);if(n===void 0)return;const o=Math.max(0,Math.round(e-n));return{phase:o<6e4?"startup":"running",sinceStartMs:o}}r(loopPhaseAt,"loopPhaseAt"),s(loopPhaseAt,"loopPhaseAt");
@@ -1 +1 @@
1
- "use strict";var S=Object.defineProperty;var i=(t,s)=>S(t,"name",{value:s,configurable:!0});var A=Object.defineProperty,f=i((t,s)=>A(t,"name",{value:s,configurable:!0}),"i"),k=Object.defineProperty,u=f((t,s)=>k(t,"name",{value:s,configurable:!0}),"o");function l(){const t=typeof process<"u"?process.env?.LENSMCP_EVENT_MAX_EPS:void 0;if(t===void 0||t==="")return;if(t==="off")return"off";const s=Number(t);if(Number.isFinite(s))return s<=0?"off":s}i(l,"d"),f(l,"S"),u(l,"envPerSec");export function createEventFloodGuard(t){const s=t?.envOverride===!1?void 0:l();if(s==="off")return{admit:u(()=>({ok:!0,suppressed:0}),"admit")};const c=s??t?.perSec??5,d=Math.max(1,t?.burst??Math.max(30,c*4)),p=t?.maxKeys??2048,n=new Map,v=u(o=>{for(const[r,e]of n)o-e.lastSeenAt>6e4&&n.delete(r);if(n.size>p){const r=[...n.entries()].sort((e,a)=>e[1].lastSeenAt-a[1].lastSeenAt);for(let e=0;e<r.length>>1;e++)n.delete(r[e][0])}},"evictStale");return{admit(o){const r=Date.now();let e=n.get(o);e||(n.size>=p&&v(r),e={tokens:d,lastRefillAt:r,suppressed:0,lastSeenAt:r},n.set(o,e)),e.lastSeenAt=r;const a=r-e.lastRefillAt;if(a>0&&(e.tokens=Math.min(d,e.tokens+a/1e3*c),e.lastRefillAt=r),e.tokens>=1){e.tokens-=1;const m=e.suppressed;return e.suppressed=0,{ok:!0,suppressed:m}}return e.suppressed+=1,{ok:!1,suppressed:0}}}}i(createEventFloodGuard,"createEventFloodGuard"),f(createEventFloodGuard,"createEventFloodGuard"),u(createEventFloodGuard,"createEventFloodGuard");
1
+ "use strict";var S=Object.defineProperty;var i=(t,n)=>S(t,"name",{value:n,configurable:!0});var m=Object.defineProperty,u=i((t,n)=>m(t,"name",{value:n,configurable:!0}),"o");function d(){const t=typeof process<"u"?process.env?.LENSMCP_EVENT_MAX_EPS:void 0;if(t===void 0||t==="")return;if(t==="off")return"off";const n=Number(t);if(Number.isFinite(n))return n<=0?"off":n}i(d,"S"),u(d,"envPerSec");export function createEventFloodGuard(t){const n=t?.envOverride===!1?void 0:d();if(n==="off")return{admit:u(()=>({ok:!0,suppressed:0}),"admit")};const l=n??t?.perSec??5,f=Math.max(1,t?.burst??Math.max(30,l*4)),c=t?.maxKeys??2048,r=new Map,p=u(o=>{for(const[s,e]of r)o-e.lastSeenAt>6e4&&r.delete(s);if(r.size>c){const s=[...r.entries()].sort((e,a)=>e[1].lastSeenAt-a[1].lastSeenAt);for(let e=0;e<s.length>>1;e++)r.delete(s[e][0])}},"evictStale");return{admit(o){const s=Date.now();let e=r.get(o);e||(r.size>=c&&p(s),e={tokens:f,lastRefillAt:s,suppressed:0,lastSeenAt:s},r.set(o,e)),e.lastSeenAt=s;const a=s-e.lastRefillAt;if(a>0&&(e.tokens=Math.min(f,e.tokens+a/1e3*l),e.lastRefillAt=s),e.tokens>=1){e.tokens-=1;const v=e.suppressed;return e.suppressed=0,{ok:!0,suppressed:v}}return e.suppressed+=1,{ok:!1,suppressed:0}}}}i(createEventFloodGuard,"createEventFloodGuard"),u(createEventFloodGuard,"createEventFloodGuard");
package/lib/log-query.js CHANGED
@@ -1 +1 @@
1
- "use strict";var L=Object.defineProperty;var a=(e,t)=>L(e,"name",{value:t,configurable:!0});var d=Object.defineProperty,c=a((e,t)=>d(e,"name",{value:t,configurable:!0}),"a"),h=Object.defineProperty,u=c((e,t)=>h(e,"name",{value:t,configurable:!0}),"c");const p={level:"level",severity:"level",service:"service",svc:"service",src:"service",source:"service",flow:"flow",trace:"trace",request:"trace",category:"category",cat:"category",ms:"ms"},C={warn:"warning",err:"error"},k=/(-?)(?:([A-Za-z]+):)?(?:"([^"]*)"|(\S+))/g;export function parseLogQuery(e){const t=[],r=[];for(const s of e.matchAll(k)){const[o,n,g,y,w]=s,i=(y??w??"").trim(),l=g?p[g.toLowerCase()]:void 0;if(l&&i){const m=l==="level"?C[i.toLowerCase()]??i.toLowerCase():i;t.push({key:l,value:m,negate:n==="-"})}else o.trim()&&r.push(o.trim())}return{tokens:t,text:r.join(" ")}}a(parseLogQuery,"parseLogQuery"),c(parseLogQuery,"parseLogQuery"),u(parseLogQuery,"parseLogQuery");export function formatLogQuery(e){const t=u(r=>/\s/.test(r)?`"${r}"`:r,"quote");return[...e.tokens.map(r=>`${r.negate?"-":""}${r.key}:${t(r.value)}`),e.text].filter(Boolean).join(" ")}a(formatLogQuery,"formatLogQuery"),c(formatLogQuery,"formatLogQuery"),u(formatLogQuery,"formatLogQuery");function v(e,t){if(e===void 0)return!1;const r=/^(>=|<=|>|<|=)?\s*(\d+(?:\.\d+)?)$/.exec(t);if(!r)return!1;const s=Number(r[2]);switch(r[1]){case">":return e>s;case"<":return e<s;case"<=":return e<=s;case"=":return e===s;default:return e>=s}}a(v,"v"),c(v,"h"),u(v,"msMatches");function f(e,t){const r=t.value.toLowerCase();switch(t.key){case"level":return e.severity.toLowerCase()===r;case"service":return e.source.toLowerCase()===r;case"flow":return!!e.flowId&&e.flowId.toLowerCase().startsWith(r);case"trace":return!!e.requestId&&e.requestId.toLowerCase().startsWith(r);case"category":return e.category.toLowerCase()===r;case"ms":return v(e.durationMs,t.value)}}a(f,"l"),c(f,"i"),u(f,"tokenMatches");export function matchesLogQuery(e,t,r){const s=new Map;for(const o of t.tokens){if(o.negate){if(f(e,o))return!1;continue}const n=s.get(o.key);n?n.push(o):s.set(o.key,[o])}for(const o of s.values())if(!o.some(n=>f(e,n)))return!1;if(t.text){const o=`${e.title} ${e.message??""} ${e.source} ${e.flowId??""}`;return r?r(o):o.toLowerCase().includes(t.text.toLowerCase())}return!0}a(matchesLogQuery,"matchesLogQuery"),c(matchesLogQuery,"matchesLogQuery"),u(matchesLogQuery,"matchesLogQuery");
1
+ "use strict";var m=Object.defineProperty;var a=(e,r)=>m(e,"name",{value:r,configurable:!0});var L=Object.defineProperty,c=a((e,r)=>L(e,"name",{value:r,configurable:!0}),"c");const d={level:"level",severity:"level",service:"service",svc:"service",src:"service",source:"service",flow:"flow",trace:"trace",request:"trace",category:"category",cat:"category",ms:"ms"},h={warn:"warning",err:"error"},p=/(-?)(?:([A-Za-z]+):)?(?:"([^"]*)"|(\S+))/g;export function parseLogQuery(e){const r=[],t=[];for(const s of e.matchAll(p)){const[o,n,f,w,g]=s,u=(w??g??"").trim(),i=f?d[f.toLowerCase()]:void 0;if(i&&u){const y=i==="level"?h[u.toLowerCase()]??u.toLowerCase():u;r.push({key:i,value:y,negate:n==="-"})}else o.trim()&&t.push(o.trim())}return{tokens:r,text:t.join(" ")}}a(parseLogQuery,"parseLogQuery"),c(parseLogQuery,"parseLogQuery");export function formatLogQuery(e){const r=c(t=>/\s/.test(t)?`"${t}"`:t,"quote");return[...e.tokens.map(t=>`${t.negate?"-":""}${t.key}:${r(t.value)}`),e.text].filter(Boolean).join(" ")}a(formatLogQuery,"formatLogQuery"),c(formatLogQuery,"formatLogQuery");function v(e,r){if(e===void 0)return!1;const t=/^(>=|<=|>|<|=)?\s*(\d+(?:\.\d+)?)$/.exec(r);if(!t)return!1;const s=Number(t[2]);switch(t[1]){case">":return e>s;case"<":return e<s;case"<=":return e<=s;case"=":return e===s;default:return e>=s}}a(v,"h"),c(v,"msMatches");function l(e,r){const t=r.value.toLowerCase();switch(r.key){case"level":return e.severity.toLowerCase()===t;case"service":return e.source.toLowerCase()===t;case"flow":return!!e.flowId&&e.flowId.toLowerCase().startsWith(t);case"trace":return!!e.requestId&&e.requestId.toLowerCase().startsWith(t);case"category":return e.category.toLowerCase()===t;case"ms":return v(e.durationMs,r.value)}}a(l,"i"),c(l,"tokenMatches");export function matchesLogQuery(e,r,t){const s=new Map;for(const o of r.tokens){if(o.negate){if(l(e,o))return!1;continue}const n=s.get(o.key);n?n.push(o):s.set(o.key,[o])}for(const o of s.values())if(!o.some(n=>l(e,n)))return!1;if(r.text){const o=`${e.title} ${e.message??""} ${e.source} ${e.flowId??""}`;return t?t(o):o.toLowerCase().includes(r.text.toLowerCase())}return!0}a(matchesLogQuery,"matchesLogQuery"),c(matchesLogQuery,"matchesLogQuery");
package/lib/perf-rules.js CHANGED
@@ -1 +1 @@
1
- "use strict";var c=Object.defineProperty;var a=(r,e)=>c(r,"name",{value:e,configurable:!0});var l=Object.defineProperty,o=a((r,e)=>l(r,"name",{value:e,configurable:!0}),"o"),f=Object.defineProperty,p=o((r,e)=>f(r,"name",{value:e,configurable:!0}),"o");export const PERF_RULE_IDS=["bundle/heavy-barrel-import","pod/heap-budget","pod/retained-generation"],PERF_RULE_EVENT_KINDS=["perf-rule-finding","perf-rule-retracted","perf-rule-scan"],PERF_RULES_DOC="https://github.com/kiwiapps-ltd/lensmcp/blob/main/docs/lensmcp/concepts/memory-and-build-cost.mdx",PERF_RULE_DOCS={"bundle/heavy-barrel-import":`${PERF_RULES_DOC}#bundleheavy-barrel-import`,"pod/heap-budget":`${PERF_RULES_DOC}#podheap-budget`,"pod/retained-generation":`${PERF_RULES_DOC}#podretained-generation`};export function perfRuleFingerprint(r,e,n){return`perf-rule:${r}:${e}:${n}`}a(perfRuleFingerprint,"perfRuleFingerprint"),o(perfRuleFingerprint,"perfRuleFingerprint"),p(perfRuleFingerprint,"perfRuleFingerprint");export function perfRuleScanFingerprint(r,e){return`perf-rule-scan:${r}:${e}`}a(perfRuleScanFingerprint,"perfRuleScanFingerprint"),o(perfRuleScanFingerprint,"perfRuleScanFingerprint"),p(perfRuleScanFingerprint,"perfRuleScanFingerprint");const s=/^[a-z][a-z0-9-]*\/[a-z0-9][a-z0-9-]*$/,d=12,y=4e3,t=p((r,e=y)=>typeof r=="string"&&r.length>0&&r.length<=e,"isText");export function asPerfRuleRaw(r){if(!r||typeof r!="object")return;const e=r;if(!PERF_RULE_EVENT_KINDS.includes(e.kind)||typeof e.rule!="string"||!s.test(e.rule)||!t(e.project,512))return;if(e.kind==="perf-rule-scan"){const i=e.open;return!Array.isArray(i)||i.length>256||!i.every(u=>t(u,512))?void 0:r}if(!t(e.subject,512))return;if(e.kind==="perf-rule-retracted")return r;if(e.severity!=="warning"&&e.severity!=="error"||!t(e.title)||!t(e.summary)||!t(e.verify)||!t(e.docs,1024))return;const n=e.fix;if(!(!Array.isArray(n)||n.length===0||n.length>d||!n.every(i=>t(i)))&&!(!e.evidence||typeof e.evidence!="object"||Array.isArray(e.evidence))&&!(!e.cost||typeof e.cost!="object"||Array.isArray(e.cost)))return r}a(asPerfRuleRaw,"asPerfRuleRaw"),o(asPerfRuleRaw,"asPerfRuleRaw"),p(asPerfRuleRaw,"asPerfRuleRaw");
1
+ "use strict";var u=Object.defineProperty;var o=(r,e)=>u(r,"name",{value:e,configurable:!0});var c=Object.defineProperty,a=o((r,e)=>c(r,"name",{value:e,configurable:!0}),"o");export const PERF_RULE_IDS=["bundle/heavy-barrel-import","pod/heap-budget","pod/retained-generation"],PERF_RULE_EVENT_KINDS=["perf-rule-finding","perf-rule-retracted","perf-rule-scan"],PERF_RULES_DOC="https://github.com/kiwiapps-ltd/lensmcp/blob/main/docs/lensmcp/concepts/memory-and-build-cost.mdx",PERF_RULE_DOCS={"bundle/heavy-barrel-import":`${PERF_RULES_DOC}#bundleheavy-barrel-import`,"pod/heap-budget":`${PERF_RULES_DOC}#podheap-budget`,"pod/retained-generation":`${PERF_RULES_DOC}#podretained-generation`};export function perfRuleFingerprint(r,e,n){return`perf-rule:${r}:${e}:${n}`}o(perfRuleFingerprint,"perfRuleFingerprint"),a(perfRuleFingerprint,"perfRuleFingerprint");export function perfRuleScanFingerprint(r,e){return`perf-rule-scan:${r}:${e}`}o(perfRuleScanFingerprint,"perfRuleScanFingerprint"),a(perfRuleScanFingerprint,"perfRuleScanFingerprint");const s=/^[a-z][a-z0-9-]*\/[a-z0-9][a-z0-9-]*$/,l=12,f=4e3,t=a((r,e=f)=>typeof r=="string"&&r.length>0&&r.length<=e,"isText");export function asPerfRuleRaw(r){if(!r||typeof r!="object")return;const e=r;if(!PERF_RULE_EVENT_KINDS.includes(e.kind)||typeof e.rule!="string"||!s.test(e.rule)||!t(e.project,512))return;if(e.kind==="perf-rule-scan"){const i=e.open;return!Array.isArray(i)||i.length>256||!i.every(p=>t(p,512))?void 0:r}if(!t(e.subject,512))return;if(e.kind==="perf-rule-retracted")return r;if(e.severity!=="warning"&&e.severity!=="error"||!t(e.title)||!t(e.summary)||!t(e.verify)||!t(e.docs,1024))return;const n=e.fix;if(!(!Array.isArray(n)||n.length===0||n.length>l||!n.every(i=>t(i)))&&!(!e.evidence||typeof e.evidence!="object"||Array.isArray(e.evidence))&&!(!e.cost||typeof e.cost!="object"||Array.isArray(e.cost)))return r}o(asPerfRuleRaw,"asPerfRuleRaw"),a(asPerfRuleRaw,"asPerfRuleRaw");
package/lib/pod-memory.js CHANGED
@@ -1 +1 @@
1
- "use strict";var n=Object.defineProperty;var o=(r,e)=>n(r,"name",{value:e,configurable:!0});var d=Object.defineProperty,t=o((r,e)=>d(r,"name",{value:e,configurable:!0}),"r"),m=Object.defineProperty,i=t((r,e)=>m(r,"name",{value:e,configurable:!0}),"r");export const POD_MEMORY_KINDS=["pod-memory","pod-memory-retained","pod-memory-released","pod-memory-exited"];export function asPodMemoryRaw(r){if(!r||typeof r!="object")return;const e=r;if(POD_MEMORY_KINDS.includes(e.kind)&&!(typeof e.project!="string"||!e.project)&&!(typeof e.pod!="number"||typeof e.pid!="number")&&!(e.kind==="pod-memory"&&(typeof e.live!="number"||!Number.isFinite(e.live)))&&!((e.kind==="pod-memory-retained"||e.kind==="pod-memory-released")&&typeof e.gen!="number"))return r}o(asPodMemoryRaw,"asPodMemoryRaw"),t(asPodMemoryRaw,"asPodMemoryRaw"),i(asPodMemoryRaw,"asPodMemoryRaw");
1
+ "use strict";var t=Object.defineProperty;var r=(o,e)=>t(o,"name",{value:e,configurable:!0});var d=Object.defineProperty,m=r((o,e)=>d(o,"name",{value:e,configurable:!0}),"r");export const POD_MEMORY_KINDS=["pod-memory","pod-memory-retained","pod-memory-released","pod-memory-exited"];export function asPodMemoryRaw(o){if(!o||typeof o!="object")return;const e=o;if(POD_MEMORY_KINDS.includes(e.kind)&&!(typeof e.project!="string"||!e.project)&&!(typeof e.pod!="number"||typeof e.pid!="number")&&!(e.kind==="pod-memory"&&(typeof e.live!="number"||!Number.isFinite(e.live)))&&!((e.kind==="pod-memory-retained"||e.kind==="pod-memory-released")&&typeof e.gen!="number"))return o}r(asPodMemoryRaw,"asPodMemoryRaw"),m(asPodMemoryRaw,"asPodMemoryRaw");
@@ -1 +1 @@
1
- "use strict";var R=Object.defineProperty;var i=(e,o)=>R(e,"name",{value:o,configurable:!0});var $=Object.defineProperty,d=i((e,o)=>$(e,"name",{value:o,configurable:!0}),"i"),b=Object.defineProperty,m=d((e,o)=>b(e,"name",{value:o,configurable:!0}),"u");import{z as r}from"zod";export const ProducerStateSchema=r.enum(["none","connected"]),ProducerRunStatusSchema=r.enum(["running","clean","failing","error"]),ProducerReportSchema=r.object({id:r.string(),tool:r.string(),project:r.string().optional(),firstReportedAt:r.number().int().nonnegative(),lastReportedAt:r.number().int().nonnegative(),lastRunStatus:ProducerRunStatusSchema,lastRunDurationMs:r.number().int().nonnegative().optional(),errorCount:r.number().int().nonnegative(),warningCount:r.number().int().nonnegative().optional(),error:r.string().optional()}),ProducerHealthSchema=r.object({producer:ProducerStateSchema,producers:r.array(ProducerReportSchema),lastReportedAt:r.number().int().nonnegative().optional(),ageMs:r.number().int().nonnegative().optional(),stale:r.boolean(),detail:r.string()}),PRODUCER_STALE_AFTER_MS=10*6e4;export function summariseProducers(e){const o=e.now??Date.now(),t=[...e.producers].sort((n,h)=>h.lastReportedAt-n.lastReportedAt);if(t.length===0)return{producer:"none",producers:[],stale:!1,detail:`No ${e.domain} producer has ever reported into this session \u2014 this is NOT a clean result, nothing is watching. ${e.noProducerHint}`};const l=t[0].lastReportedAt,u=Math.max(0,o-l),p=u>PRODUCER_STALE_AFTER_MS,g=t.filter(n=>n.lastRunStatus==="failing"),s=t.filter(n=>n.lastRunStatus==="error"),a=[`${t.length} ${e.domain} producer${t.length===1?"":"s"} reporting (${t.map(n=>n.id).join(", ")}); newest report ${c(u)}.`];return s.length>0&&a.push(`${s.length} produced NO verdict (the tool itself failed): ${s.map(n=>`${n.id} \u2014 ${n.error??"unknown error"}`).join("; ")}.`),g.length>0&&a.push(`${g.length} reporting errors.`),p&&a.push(`Older than ${Math.round(PRODUCER_STALE_AFTER_MS/6e4)}m \u2014 the verdict may predate the current source.`),{producer:"connected",producers:t,lastReportedAt:l,ageMs:u,stale:p,detail:a.join(" ")}}i(summariseProducers,"summariseProducers"),d(summariseProducers,"summariseProducers"),m(summariseProducers,"summariseProducers");function c(e){return e<1e3?"just now":e<6e4?`${Math.round(e/1e3)}s ago`:e<36e5?`${Math.round(e/6e4)}m ago`:`${Math.round(e/36e5)}h ago`}i(c,"g"),d(c,"g"),m(c,"describeAge");
1
+ "use strict";var m=Object.defineProperty;var i=(t,o)=>m(t,"name",{value:o,configurable:!0});var R=Object.defineProperty,p=i((t,o)=>R(t,"name",{value:o,configurable:!0}),"u");import{z as e}from"zod";export const ProducerStateSchema=e.enum(["none","connected"]),ProducerRunStatusSchema=e.enum(["running","clean","failing","error"]),ProducerReportSchema=e.object({id:e.string(),tool:e.string(),project:e.string().optional(),firstReportedAt:e.number().int().nonnegative(),lastReportedAt:e.number().int().nonnegative(),lastRunStatus:ProducerRunStatusSchema,lastRunDurationMs:e.number().int().nonnegative().optional(),errorCount:e.number().int().nonnegative(),warningCount:e.number().int().nonnegative().optional(),error:e.string().optional()}),ProducerHealthSchema=e.object({producer:ProducerStateSchema,producers:e.array(ProducerReportSchema),lastReportedAt:e.number().int().nonnegative().optional(),ageMs:e.number().int().nonnegative().optional(),stale:e.boolean(),detail:e.string()}),PRODUCER_STALE_AFTER_MS=10*6e4;export function summariseProducers(t){const o=t.now??Date.now(),n=[...t.producers].sort((r,h)=>h.lastReportedAt-r.lastReportedAt);if(n.length===0)return{producer:"none",producers:[],stale:!1,detail:`No ${t.domain} producer has ever reported into this session \u2014 this is NOT a clean result, nothing is watching. ${t.noProducerHint}`};const d=n[0].lastReportedAt,u=Math.max(0,o-d),l=u>PRODUCER_STALE_AFTER_MS,c=n.filter(r=>r.lastRunStatus==="failing"),s=n.filter(r=>r.lastRunStatus==="error"),a=[`${n.length} ${t.domain} producer${n.length===1?"":"s"} reporting (${n.map(r=>r.id).join(", ")}); newest report ${g(u)}.`];return s.length>0&&a.push(`${s.length} produced NO verdict (the tool itself failed): ${s.map(r=>`${r.id} \u2014 ${r.error??"unknown error"}`).join("; ")}.`),c.length>0&&a.push(`${c.length} reporting errors.`),l&&a.push(`Older than ${Math.round(PRODUCER_STALE_AFTER_MS/6e4)}m \u2014 the verdict may predate the current source.`),{producer:"connected",producers:n,lastReportedAt:d,ageMs:u,stale:l,detail:a.join(" ")}}i(summariseProducers,"summariseProducers"),p(summariseProducers,"summariseProducers");function g(t){return t<1e3?"just now":t<6e4?`${Math.round(t/1e3)}s ago`:t<36e5?`${Math.round(t/6e4)}m ago`:`${Math.round(t/36e5)}h ago`}i(g,"g"),p(g,"describeAge");
package/lib/sources.js CHANGED
@@ -1 +1 @@
1
- "use strict";var U=Object.defineProperty;var u=(e,r)=>U(e,"name",{value:r,configurable:!0});var v=Object.defineProperty,c=u((e,r)=>v(e,"name",{value:r,configurable:!0}),"a"),I=Object.defineProperty,n=c((e,r)=>I(e,"name",{value:r,configurable:!0}),"r");export const SOURCE_KINDS=["queue","loop","store","traffic"],SOURCE_KINDS_READ=["queue","loop","store","traffic"],sourceWireSchema=n(e=>`lensmcp.${e}/v1`,"sourceWireSchema"),QUEUE_WIRE_SCHEMA="lensmcp.queue/v1",LOOP_WIRE_SCHEMA="lensmcp.loop/v1",STORE_WIRE_SCHEMA="lensmcp.store/v1",TRAFFIC_WIRE_SCHEMA="lensmcp.traffic/v1",SOURCE_SNAPSHOT_FIELD={queue:"snapshot",loop:"loop",store:"store",traffic:"traffic"},URI_SOURCES="process://sources",SOURCE_PROVENANCE="reported",QUEUE_OLDEST_WAIT_RULE="queue/oldest-wait",QUEUE_STALLED_RULE="queue/stalled",LOOP_OVERDUE_RULE="loop/overdue",LOOP_FAILING_RULE="loop/failing",LOOP_IDLE_RULE="loop/idle-while-fed",STORE_QUOTA_RULE="store/near-quota",STORE_ERRORS_RULE="store/errors",STORE_ORPHANS_RULE="store/orphans",TRAFFIC_FAILURES_RULE="traffic/failures",TRAFFIC_LATENCY_RULE="traffic/latency",TRAFFIC_RATE_LIMITED_RULE="traffic/rate-limited",SOURCE_RULES=[QUEUE_OLDEST_WAIT_RULE,QUEUE_STALLED_RULE,LOOP_OVERDUE_RULE,LOOP_FAILING_RULE,LOOP_IDLE_RULE,STORE_QUOTA_RULE,STORE_ERRORS_RULE,STORE_ORPHANS_RULE,TRAFFIC_FAILURES_RULE,TRAFFIC_LATENCY_RULE,TRAFFIC_RATE_LIMITED_RULE],SOURCE_EVENT_KINDS=["source-poll","source-declaration","source-event"],CUSTOM_EVENT_SOURCE="custom",QUEUE_EVENTS=["enqueued","admitted","completed","failed","parked"],LOOP_EVENTS=["run-start","run-end"],LOOP_OUTCOMES=["ok","failed","skipped"],STORE_EVENTS=["write","delete","error"],TRAFFIC_EVENTS=["inbound","outbound"],TRAFFIC_OUTCOMES=["ok","failed","rate-limited"],SOURCE_PUSH_EVENTS={queue:QUEUE_EVENTS,loop:LOOP_EVENTS,store:STORE_EVENTS,traffic:TRAFFIC_EVENTS},SOURCE_PUSH_OUTCOMES={queue:[],loop:LOOP_OUTCOMES,store:[],traffic:TRAFFIC_OUTCOMES},SOURCE_POLL_STATES=["current","unreachable","refused","malformed","not-running"],SOURCE_STATES=[...SOURCE_POLL_STATES,"stale","never-polled"],SOURCE_DEFAULT_INTERVAL_SEC=10,SOURCE_MIN_INTERVAL_SEC=2,QUEUE_DEFAULT_OLDEST_WAIT_MIN=10,QUEUE_DEFAULT_STALLED_MIN=15,LOOP_DEFAULT_IDLE_MIN=10,LOOP_OVERDUE_INTERVALS=2,LOOP_FAILING_RUNS=3,SOURCE_FULL_REPORT_MS=6e4,SOURCE_HISTORY_POINTS=60,SOURCE_RUNS_KEPT=30,SOURCE_PUSHED_KEPT=20,STORE_DEFAULT_QUOTA_PCT=90,STORE_DEFAULT_ERROR_RATE_PCT=5,STORE_DEFAULT_ORPHAN_MIN=60,TRAFFIC_DEFAULT_FAILURE_PCT=5,TRAFFIC_DEFAULT_P95_MS=2e3,TRAFFIC_DEFAULT_RATE_LIMITED=1,TRAFFIC_MIN_MESSAGES=10,TRAFFIC_PUSH_WINDOW_MS=10*6e4,TRAFFIC_PUSH_CHANNELS=50,TRAFFIC_PUSH_EVENTS_PER_CHANNEL=1e3,SOURCE_MAX_GROUPS=500,SOURCE_MAX_BYTES=256*1024,SOURCE_STALE_PERIODS=3,SOURCE_STALE_MIN_MS=3e4;export function sourceStaleAfterMs(e){return Math.max(SOURCE_STALE_MIN_MS,SOURCE_STALE_PERIODS*Math.max(0,e))}u(sourceStaleAfterMs,"sourceStaleAfterMs"),c(sourceStaleAfterMs,"sourceStaleAfterMs"),n(sourceStaleAfterMs,"sourceStaleAfterMs");const i=n(e=>typeof e=="object"&&e!==null&&!Array.isArray(e),"isObj"),t=n(e=>typeof e=="number"&&Number.isInteger(e)&&e>=0,"isCount"),E=n(e=>typeof e=="number"&&Number.isFinite(e)&&e>0,"isTime"),a=n((e,r)=>typeof e=="string"&&e.length>0&&e.length<=r,"isStr"),L=n(e=>e===void 0||typeof e=="number"&&e>0,"isMin");function _(e){if(!SOURCE_KINDS_READ.includes(e.sourceKind)||typeof e.path!="string"&&!(e.path===void 0&&(e.sourceKind==="traffic"||e.sourceKind==="loop"))||!a(e.name,200)||typeof e.intervalSec!="number"||e.feeds!==void 0&&!a(e.feeds,200))return!1;const r=e.thresholds;if(!i(r))return!1;for(const o of["stalledMin","idleMin","oldestWaitMin","quotaPct","errorRatePct","orphanMin","failurePct","p95Ms","rateLimited"])if(!L(r[o]))return!1;return e.sourceKind!=="queue"||typeof r.oldestWaitMin=="number"}u(_,"_"),c(_,"l"),n(_,"asDecl");const d=n(e=>e===null||typeof e=="string","isIsoOrNull"),l=n(e=>e===void 0||t(e),"isOptCount");function f(e){if(!i(e)||typeof e.at!="string"||!E(e.receivedAt)||!E(e.intervalSec)||!d(e.lastRunAt)||e.nextRunAt!==void 0&&!d(e.nextRunAt))return!1;for(const r of["lastDurationMs","lastItems","runsInWindow","itemsInWindow","failuresInWindow","windowSec"])if(!l(e[r]))return!1;return e.lastOutcome!==void 0&&!LOOP_OUTCOMES.includes(e.lastOutcome)?!1:e.lastError===void 0||typeof e.lastError=="string"}u(f,"d"),c(f,"_"),n(f,"asLoopSnapshot");const T=n(e=>e===void 0||i(e)&&Object.values(e).every(r=>typeof r=="string"),"isLabels");function S(e){if(!i(e)||typeof e.at!="string"||!E(e.receivedAt)||!t(e.objects)||!t(e.bytes)||e.quotaBytes!==void 0&&e.quotaBytes!==null&&!t(e.quotaBytes))return!1;for(const s of["opsInWindow","writesInWindow","deletesInWindow","errorsInWindow","windowSec"])if(!l(e[s]))return!1;if(e.lastWriteAt!==void 0&&!d(e.lastWriteAt)||e.lastError!==void 0&&typeof e.lastError!="string")return!1;const r=e.truncated;if(r!==void 0&&!(i(r)&&t(r.groups)))return!1;const o=e.groups;return o===void 0?!0:Array.isArray(o)&&o.length<=SOURCE_MAX_GROUPS&&o.every(s=>i(s)&&a(s.group,1e3)&&t(s.objects)&&t(s.bytes)&&T(s.labels))}u(S,"S"),c(S,"S"),n(S,"asStoreSnapshot");function R(e){if(!i(e)||typeof e.at!="string"||!E(e.receivedAt)||!Array.isArray(e.channels)||!l(e.windowSec))return!1;const r=e.truncated;return r!==void 0&&!(i(r)&&t(r.channels))?!1:e.channels.length<=SOURCE_MAX_GROUPS&&e.channels.every(o=>{if(!i(o)||!a(o.channel,1e3)||!T(o.labels)||o.direction!==void 0&&o.direction!=="inbound"&&o.direction!=="outbound"||o.counterpart!==void 0&&!a(o.counterpart,200))return!1;for(const s of["messagesInWindow","failuresInWindow","rateLimitedInWindow"])if(!l(o[s]))return!1;return o.p95Ms!==void 0&&!(typeof o.p95Ms=="number"&&Number.isFinite(o.p95Ms)&&o.p95Ms>=0)||o.lastAt!==void 0&&!d(o.lastAt)?!1:o.lastError===void 0||typeof o.lastError=="string"})}u(R,"p"),c(R,"R"),n(R,"asTrafficSnapshot");function p(e){return i(e)&&a(e.digest,100)&&typeof e.at=="string"&&E(e.receivedAt)}u(p,"R"),c(p,"A"),n(p,"asSame");function A(e){if(!i(e)||!a(e.group,1e3)||!t(e.pending))return!1;for(const s of["inFlight","failed","completedInWindow"])if(e[s]!==void 0&&!t(e[s]))return!1;const r=e.oldestPendingAt;if(r!=null&&typeof r!="string")return!1;const o=e.labels;return o===void 0||i(o)&&Object.values(o).every(s=>typeof s=="string")}u(A,"A"),c(A,"O"),n(A,"asGroup");function O(e){if(!i(e)||typeof e.at!="string"||!E(e.receivedAt)||!Array.isArray(e.groups))return!1;const r=e.totals;if(!i(r)||!t(r.groups)||!t(r.pending)||!t(r.inFlight)||!t(r.failed))return!1;const o=e.truncated;return o!==void 0&&!(i(o)&&t(o.groups))?!1:e.groups.length<=SOURCE_MAX_GROUPS&&e.groups.every(A)}u(O,"O"),c(O,"T"),n(O,"asSnapshot");export function asSourcePollRaw(e){if(!i(e)||e.kind!=="source-poll"||!a(e.project,200)||!_(e)||!SOURCE_POLL_STATES.includes(e.state)||!E(e.polledAt)||!E(e.reportEveryMs)||e.path===void 0)return;const r=SOURCE_SNAPSHOT_FIELD[e.sourceKind];for(const s of Object.values(SOURCE_SNAPSHOT_FIELD))if(s!==r&&e[s]!==void 0)return;const o={snapshot:O,loop:f,store:S,traffic:R}[r];if(!(e[r]!==void 0&&!o(e[r]))&&!(e.same!==void 0&&(!p(e.same)||e[r]!==void 0))&&!(e.state==="current"&&e[r]===void 0&&e.same===void 0))return e}u(asSourcePollRaw,"asSourcePollRaw"),c(asSourcePollRaw,"asSourcePollRaw"),n(asSourcePollRaw,"asSourcePollRaw");export function asSourceEventRaw(e){if(!i(e)||e.kind!=="source-event"||!a(e.project,200)||!a(e.name,200))return;const r=e.sourceKind;if(SOURCE_KINDS_READ.includes(r)&&SOURCE_PUSH_EVENTS[r].includes(e.event)&&!(e.item!==void 0&&!a(e.item,200)||e.group!==void 0&&!a(e.group,200))&&!(!l(e.items)||!l(e.durationMs)||!l(e.bytes))&&!(e.outcome!==void 0&&!SOURCE_PUSH_OUTCOMES[r].includes(e.outcome))){for(const o of["object","channel","counterpart","correlation"])if(e[o]!==void 0&&!a(e[o],200))return;if(!(e.error!==void 0&&typeof e.error!="string"))return e}}u(asSourceEventRaw,"asSourceEventRaw"),c(asSourceEventRaw,"asSourceEventRaw"),n(asSourceEventRaw,"asSourceEventRaw");export function asSourceDeclarationRaw(e){if(!(!i(e)||e.kind!=="source-declaration"||!a(e.project,200))&&!(!Array.isArray(e.sources)||!e.sources.every(r=>i(r)&&_(r)))&&!(!Array.isArray(e.problems)||!e.problems.every(r=>typeof r=="string")))return e}u(asSourceDeclarationRaw,"asSourceDeclarationRaw"),c(asSourceDeclarationRaw,"asSourceDeclarationRaw"),n(asSourceDeclarationRaw,"asSourceDeclarationRaw");
1
+ "use strict";var T=Object.defineProperty;var a=(t,r)=>T(t,"name",{value:r,configurable:!0});var U=Object.defineProperty,e=a((t,r)=>U(t,"name",{value:r,configurable:!0}),"r");export const SOURCE_KINDS=["queue","loop","store","traffic"],SOURCE_KINDS_READ=["queue","loop","store","traffic"],sourceWireSchema=e(t=>`lensmcp.${t}/v1`,"sourceWireSchema"),QUEUE_WIRE_SCHEMA="lensmcp.queue/v1",LOOP_WIRE_SCHEMA="lensmcp.loop/v1",STORE_WIRE_SCHEMA="lensmcp.store/v1",TRAFFIC_WIRE_SCHEMA="lensmcp.traffic/v1",SOURCE_SNAPSHOT_FIELD={queue:"snapshot",loop:"loop",store:"store",traffic:"traffic"},URI_SOURCES="process://sources",SOURCE_PROVENANCE="reported",QUEUE_OLDEST_WAIT_RULE="queue/oldest-wait",QUEUE_STALLED_RULE="queue/stalled",LOOP_OVERDUE_RULE="loop/overdue",LOOP_FAILING_RULE="loop/failing",LOOP_IDLE_RULE="loop/idle-while-fed",STORE_QUOTA_RULE="store/near-quota",STORE_ERRORS_RULE="store/errors",STORE_ORPHANS_RULE="store/orphans",TRAFFIC_FAILURES_RULE="traffic/failures",TRAFFIC_LATENCY_RULE="traffic/latency",TRAFFIC_RATE_LIMITED_RULE="traffic/rate-limited",SOURCE_RULES=[QUEUE_OLDEST_WAIT_RULE,QUEUE_STALLED_RULE,LOOP_OVERDUE_RULE,LOOP_FAILING_RULE,LOOP_IDLE_RULE,STORE_QUOTA_RULE,STORE_ERRORS_RULE,STORE_ORPHANS_RULE,TRAFFIC_FAILURES_RULE,TRAFFIC_LATENCY_RULE,TRAFFIC_RATE_LIMITED_RULE],SOURCE_EVENT_KINDS=["source-poll","source-declaration","source-event"],CUSTOM_EVENT_SOURCE="custom",QUEUE_EVENTS=["enqueued","admitted","completed","failed","parked"],LOOP_EVENTS=["run-start","run-end"],LOOP_OUTCOMES=["ok","failed","skipped"],STORE_EVENTS=["write","delete","error"],TRAFFIC_EVENTS=["inbound","outbound"],TRAFFIC_OUTCOMES=["ok","failed","rate-limited"],SOURCE_PUSH_EVENTS={queue:QUEUE_EVENTS,loop:LOOP_EVENTS,store:STORE_EVENTS,traffic:TRAFFIC_EVENTS},SOURCE_PUSH_OUTCOMES={queue:[],loop:LOOP_OUTCOMES,store:[],traffic:TRAFFIC_OUTCOMES},SOURCE_POLL_STATES=["current","unreachable","refused","malformed","not-running"],SOURCE_STATES=[...SOURCE_POLL_STATES,"stale","never-polled"],SOURCE_DEFAULT_INTERVAL_SEC=10,SOURCE_MIN_INTERVAL_SEC=2,QUEUE_DEFAULT_OLDEST_WAIT_MIN=10,QUEUE_DEFAULT_STALLED_MIN=15,LOOP_DEFAULT_IDLE_MIN=10,LOOP_OVERDUE_INTERVALS=2,LOOP_FAILING_RUNS=3,SOURCE_FULL_REPORT_MS=6e4,SOURCE_HISTORY_POINTS=60,SOURCE_RUNS_KEPT=30,SOURCE_PUSHED_KEPT=20,STORE_DEFAULT_QUOTA_PCT=90,STORE_DEFAULT_ERROR_RATE_PCT=5,STORE_DEFAULT_ORPHAN_MIN=60,TRAFFIC_DEFAULT_FAILURE_PCT=5,TRAFFIC_DEFAULT_P95_MS=2e3,TRAFFIC_DEFAULT_RATE_LIMITED=1,TRAFFIC_MIN_MESSAGES=10,TRAFFIC_PUSH_WINDOW_MS=10*6e4,TRAFFIC_PUSH_CHANNELS=50,TRAFFIC_PUSH_EVENTS_PER_CHANNEL=1e3,SOURCE_MAX_GROUPS=500,SOURCE_MAX_BYTES=256*1024,SOURCE_STALE_PERIODS=3,SOURCE_STALE_MIN_MS=3e4;export function sourceStaleAfterMs(t){return Math.max(SOURCE_STALE_MIN_MS,SOURCE_STALE_PERIODS*Math.max(0,t))}a(sourceStaleAfterMs,"sourceStaleAfterMs"),e(sourceStaleAfterMs,"sourceStaleAfterMs");const n=e(t=>typeof t=="object"&&t!==null&&!Array.isArray(t),"isObj"),s=e(t=>typeof t=="number"&&Number.isInteger(t)&&t>=0,"isCount"),E=e(t=>typeof t=="number"&&Number.isFinite(t)&&t>0,"isTime"),u=e((t,r)=>typeof t=="string"&&t.length>0&&t.length<=r,"isStr"),v=e(t=>t===void 0||typeof t=="number"&&t>0,"isMin");function _(t){if(!SOURCE_KINDS_READ.includes(t.sourceKind)||typeof t.path!="string"&&!(t.path===void 0&&(t.sourceKind==="traffic"||t.sourceKind==="loop"))||!u(t.name,200)||typeof t.intervalSec!="number"||t.feeds!==void 0&&!u(t.feeds,200))return!1;const r=t.thresholds;if(!n(r))return!1;for(const o of["stalledMin","idleMin","oldestWaitMin","quotaPct","errorRatePct","orphanMin","failurePct","p95Ms","rateLimited"])if(!v(r[o]))return!1;return t.sourceKind!=="queue"||typeof r.oldestWaitMin=="number"}a(_,"l"),e(_,"asDecl");const l=e(t=>t===null||typeof t=="string","isIsoOrNull"),c=e(t=>t===void 0||s(t),"isOptCount");function d(t){if(!n(t)||typeof t.at!="string"||!E(t.receivedAt)||!E(t.intervalSec)||!l(t.lastRunAt)||t.nextRunAt!==void 0&&!l(t.nextRunAt))return!1;for(const r of["lastDurationMs","lastItems","runsInWindow","itemsInWindow","failuresInWindow","windowSec"])if(!c(t[r]))return!1;return t.lastOutcome!==void 0&&!LOOP_OUTCOMES.includes(t.lastOutcome)?!1:t.lastError===void 0||typeof t.lastError=="string"}a(d,"_"),e(d,"asLoopSnapshot");const f=e(t=>t===void 0||n(t)&&Object.values(t).every(r=>typeof r=="string"),"isLabels");function S(t){if(!n(t)||typeof t.at!="string"||!E(t.receivedAt)||!s(t.objects)||!s(t.bytes)||t.quotaBytes!==void 0&&t.quotaBytes!==null&&!s(t.quotaBytes))return!1;for(const i of["opsInWindow","writesInWindow","deletesInWindow","errorsInWindow","windowSec"])if(!c(t[i]))return!1;if(t.lastWriteAt!==void 0&&!l(t.lastWriteAt)||t.lastError!==void 0&&typeof t.lastError!="string")return!1;const r=t.truncated;if(r!==void 0&&!(n(r)&&s(r.groups)))return!1;const o=t.groups;return o===void 0?!0:Array.isArray(o)&&o.length<=SOURCE_MAX_GROUPS&&o.every(i=>n(i)&&u(i.group,1e3)&&s(i.objects)&&s(i.bytes)&&f(i.labels))}a(S,"S"),e(S,"asStoreSnapshot");function p(t){if(!n(t)||typeof t.at!="string"||!E(t.receivedAt)||!Array.isArray(t.channels)||!c(t.windowSec))return!1;const r=t.truncated;return r!==void 0&&!(n(r)&&s(r.channels))?!1:t.channels.length<=SOURCE_MAX_GROUPS&&t.channels.every(o=>{if(!n(o)||!u(o.channel,1e3)||!f(o.labels)||o.direction!==void 0&&o.direction!=="inbound"&&o.direction!=="outbound"||o.counterpart!==void 0&&!u(o.counterpart,200))return!1;for(const i of["messagesInWindow","failuresInWindow","rateLimitedInWindow"])if(!c(o[i]))return!1;return o.p95Ms!==void 0&&!(typeof o.p95Ms=="number"&&Number.isFinite(o.p95Ms)&&o.p95Ms>=0)||o.lastAt!==void 0&&!l(o.lastAt)?!1:o.lastError===void 0||typeof o.lastError=="string"})}a(p,"R"),e(p,"asTrafficSnapshot");function R(t){return n(t)&&u(t.digest,100)&&typeof t.at=="string"&&E(t.receivedAt)}a(R,"A"),e(R,"asSame");function A(t){if(!n(t)||!u(t.group,1e3)||!s(t.pending))return!1;for(const i of["inFlight","failed","completedInWindow"])if(t[i]!==void 0&&!s(t[i]))return!1;const r=t.oldestPendingAt;if(r!=null&&typeof r!="string")return!1;const o=t.labels;return o===void 0||n(o)&&Object.values(o).every(i=>typeof i=="string")}a(A,"O"),e(A,"asGroup");function O(t){if(!n(t)||typeof t.at!="string"||!E(t.receivedAt)||!Array.isArray(t.groups))return!1;const r=t.totals;if(!n(r)||!s(r.groups)||!s(r.pending)||!s(r.inFlight)||!s(r.failed))return!1;const o=t.truncated;return o!==void 0&&!(n(o)&&s(o.groups))?!1:t.groups.length<=SOURCE_MAX_GROUPS&&t.groups.every(A)}a(O,"T"),e(O,"asSnapshot");export function asSourcePollRaw(t){if(!n(t)||t.kind!=="source-poll"||!u(t.project,200)||!_(t)||!SOURCE_POLL_STATES.includes(t.state)||!E(t.polledAt)||!E(t.reportEveryMs)||t.path===void 0)return;const r=SOURCE_SNAPSHOT_FIELD[t.sourceKind];for(const i of Object.values(SOURCE_SNAPSHOT_FIELD))if(i!==r&&t[i]!==void 0)return;const o={snapshot:O,loop:d,store:S,traffic:p}[r];if(!(t[r]!==void 0&&!o(t[r]))&&!(t.same!==void 0&&(!R(t.same)||t[r]!==void 0))&&!(t.state==="current"&&t[r]===void 0&&t.same===void 0))return t}a(asSourcePollRaw,"asSourcePollRaw"),e(asSourcePollRaw,"asSourcePollRaw");export function asSourceEventRaw(t){if(!n(t)||t.kind!=="source-event"||!u(t.project,200)||!u(t.name,200))return;const r=t.sourceKind;if(SOURCE_KINDS_READ.includes(r)&&SOURCE_PUSH_EVENTS[r].includes(t.event)&&!(t.item!==void 0&&!u(t.item,200)||t.group!==void 0&&!u(t.group,200))&&!(!c(t.items)||!c(t.durationMs)||!c(t.bytes))&&!(t.outcome!==void 0&&!SOURCE_PUSH_OUTCOMES[r].includes(t.outcome))){for(const o of["object","channel","counterpart","correlation"])if(t[o]!==void 0&&!u(t[o],200))return;if(!(t.error!==void 0&&typeof t.error!="string"))return t}}a(asSourceEventRaw,"asSourceEventRaw"),e(asSourceEventRaw,"asSourceEventRaw");export function asSourceDeclarationRaw(t){if(!(!n(t)||t.kind!=="source-declaration"||!u(t.project,200))&&!(!Array.isArray(t.sources)||!t.sources.every(r=>n(r)&&_(r)))&&!(!Array.isArray(t.problems)||!t.problems.every(r=>typeof r=="string")))return t}a(asSourceDeclarationRaw,"asSourceDeclarationRaw"),e(asSourceDeclarationRaw,"asSourceDeclarationRaw");
@@ -141,6 +141,8 @@ export interface DashTeamMember {
141
141
  /** The model and reasoning effort its file names for its agents (the manager spawns them with these) — none: the spawner's. */
142
142
  model?: string;
143
143
  effort?: string;
144
+ /** The client its file names for its launched agents (`codex` | `claude`) — none: the spawner's. */
145
+ client?: 'codex' | 'claude';
144
146
  /** The repository's own rules for it, as tagged sections — empty when it has none. */
145
147
  rules: string;
146
148
  /** `default`: no file — LensMCP's default (built on its library role); `file`: the repository's file; `design`: a file an accepted team design wrote. */
@@ -205,6 +207,8 @@ export interface DashTeamMemberEdit {
205
207
  /** The model (at most 80 characters) and effort (at most 40) its agents run on, in their client's words — empty or left out: none. */
206
208
  model?: string;
207
209
  effort?: string;
210
+ /** The client its launched agents run on — left out: none (the spawner's). */
211
+ client?: 'codex' | 'claude';
208
212
  /** Tools added to the base's (one the base has, named again, takes this when). */
209
213
  tools?: DashTeamRoleTool[];
210
214
  /** Skills added to the base's. */
package/lib/team.d.ts CHANGED
@@ -8,7 +8,7 @@
8
8
  * What kind of work a task is: it names the role that takes it. `goal`: what a manager breaks into the others' tasks;
9
9
  * `marketing`: telling people about the product (launch posts, release notes, landing and store copy).
10
10
  */
11
- export declare const DASH_TEAM_KINDS: readonly ["goal", "build", "bug", "review", "test", "docs", "marketing", "research", "chore"];
11
+ export declare const DASH_TEAM_KINDS: readonly ["goal", "build", "bug", "review", "test", "qa", "docs", "marketing", "research", "chore"];
12
12
  export type DashTeamKind = (typeof DASH_TEAM_KINDS)[number];
13
13
  export type DashTeamTaskState = 'open' | 'claimed' | 'recovery' | 'completed' | 'cancelled';
14
14
  export type DashTeamOutcome = 'done' | 'approved' | 'changes-requested' | 'passed' | 'failed' | 'wontfix';
@@ -66,6 +66,52 @@ export interface DashTeamTask {
66
66
  completedHead?: string | null;
67
67
  paths?: string[];
68
68
  tags?: string[];
69
+ /** A review's items, whole (the drawer): each point it checks and its verdict (planning/team/06-team-operations.md OP-D3). */
70
+ items?: DashTeamReviewItem[];
71
+ /** A review's items as counts (the board). */
72
+ itemStats?: {
73
+ total: number;
74
+ pass: number;
75
+ fail: number;
76
+ open: number;
77
+ };
78
+ /** What its holder's tool calls did in its newest claim, as the hooks saw them (the drawer). */
79
+ work?: DashTeamTaskWork;
80
+ }
81
+ /** One claim's work, from its holder's hooks: the files edited, commits, the checks and the whole suites run, workspace actions. */
82
+ export interface DashTeamTaskWork {
83
+ sessionId: string;
84
+ at: number;
85
+ edits: number;
86
+ edited: string[];
87
+ outside?: string[];
88
+ commits?: number;
89
+ checks?: string[];
90
+ suites?: string[];
91
+ actions?: number;
92
+ }
93
+ /**
94
+ * «Are they doing the right things» (planning/team/06-team-operations.md O5): what a task's record and its holder's tool
95
+ * calls raise — a review or QA run that edited, a test author that ran a whole suite, edits outside the task's paths, a
96
+ * change completed with no commit or no check, a QA pass naming no run, a claim with no line in ten minutes, a holder
97
+ * whose process ended. Hints, never verdicts.
98
+ */
99
+ export type DashTeamConductKind = 'checker-edited' | 'whole-suite' | 'outside-paths' | 'no-commit' | 'unchecked' | 'qa-unrun' | 'quiet-claim' | 'host-gone';
100
+ export interface DashTeamFlag {
101
+ kind: DashTeamConductKind;
102
+ severity: 'info' | 'warn';
103
+ taskId: string;
104
+ /** The agent it is about: the task's holder. */
105
+ sessionId?: string;
106
+ text: string;
107
+ }
108
+ /** One point a review checks: from the work's «Done means», its tests, a review before it that sent it back, or the reviewer. */
109
+ export interface DashTeamReviewItem {
110
+ id: string;
111
+ text: string;
112
+ from: 'done-means' | 'tests' | 'recheck' | 'reviewer';
113
+ verdict?: 'pass' | 'fail' | 'n/a';
114
+ note?: string;
69
115
  }
70
116
  /** A task named in another's chain: its parent, its children, a blocker. */
71
117
  export interface DashTeamTaskRef {
@@ -81,6 +127,25 @@ export interface DashTeamTaskRef {
81
127
  export interface DashTeamTreeNode extends DashTeamTaskRef {
82
128
  children: DashTeamTreeNode[];
83
129
  }
130
+ /**
131
+ * The OS process agents run in (planning/team/06-team-operations.md OP-D2): a Claude Code or Codex CLI — the person's
132
+ * terminal or a launch. An in-process subagent has no process of its own: it runs in its parent's host. One process,
133
+ * not a reused pid: the pid with the time it started.
134
+ */
135
+ export interface DashTeamHost {
136
+ /** `<pid>@<startedAt>`. */
137
+ key: string;
138
+ pid: number;
139
+ /** The client binary: `claude`, `codex`, or another's name. */
140
+ bin: string;
141
+ startedAt: number;
142
+ /** It runs now — the same binary, started then. Undefined: it could not be checked (no `ps`). */
143
+ alive?: boolean;
144
+ /** Its resident memory in MB, while it runs. */
145
+ rssMb?: number;
146
+ }
147
+ /** Why a session ended: closed by itself or the person, its CLI's SessionEnd, a subagent that stopped, its host process gone, a join never used, quiet past the lease with no host to vouch for it. */
148
+ export type DashTeamClosedReason = 'closed' | 'session-end' | 'stopped' | 'host-gone' | 'unused' | 'lost';
84
149
  /** One coordination session: an agent on the team (a role), or one outside it (no role). */
85
150
  export interface DashTeamSession {
86
151
  id: string;
@@ -89,16 +154,29 @@ export interface DashTeamSession {
89
154
  role?: string;
90
155
  /** Who it reports to: `user`, or a session id. */
91
156
  manager?: string;
157
+ /** The launch that started it (`agent_spawn`), when a manager launched it. */
158
+ launch?: string;
92
159
  /** Waiting for work (agent_wait). */
93
160
  listening?: boolean;
94
161
  objective?: string;
95
162
  step?: string;
96
- /** `stale`: active, but not heard from within its lease. */
97
- presence: 'active' | 'stale' | 'closed';
163
+ /**
164
+ * `active`: heard from within its lease. `idle`: not heard from within it, but its host process runs — a session at
165
+ * the prompt, waiting for the person. `stale`: not heard from within it and no host to vouch for it — lost; LensMCP
166
+ * closes it an hour after its lease. `closed`: ended (closedReason says how).
167
+ */
168
+ presence: 'active' | 'idle' | 'stale' | 'closed';
169
+ /** The process it runs in — a key of the board's `hosts`. None: unknown (an older LensMCP's session, or no `ps`). */
170
+ host?: string;
171
+ /** The session it is a subagent of: it runs inside that session's process. */
172
+ parent?: string;
173
+ closedReason?: DashTeamClosedReason;
98
174
  worktreeId: string;
99
175
  createdAt: number;
100
176
  lastSeenAt: number;
101
177
  expiresAt: number;
178
+ /** Direct messages to it it has not read — an agent reads its messages with agent_sync. None: it read them all. */
179
+ unread?: number;
102
180
  }
103
181
  /** A checkout of the repository, as an agent's lens last saw it. */
104
182
  export interface DashTeamWorktree {
@@ -127,6 +205,8 @@ export interface DashTeamRole {
127
205
  /** The model and reasoning effort its role file asks for — the manager spawns its agents with them (planning/team/03). */
128
206
  model?: string;
129
207
  effort?: string;
208
+ /** The client its role file asks its launched agents to run on — none: the spawner's (planning/team/05). */
209
+ client?: DashTeamLaunchClient;
130
210
  /** Claimable now (blocked ones not counted). */
131
211
  open: number;
132
212
  claimed: number;
@@ -155,11 +235,15 @@ export interface DashTeamBoard {
155
235
  revision: number;
156
236
  observedAt: number;
157
237
  sessions: DashTeamSession[];
238
+ /** The processes the board's sessions run in — running ones first. */
239
+ hosts: DashTeamHost[];
158
240
  worktrees: DashTeamWorktree[];
159
241
  /** Live tasks first, then finished ones, newest first. */
160
242
  tasks: DashTeamTask[];
161
243
  notes: DashTeamNote[];
162
244
  roles: DashTeamRole[];
245
+ /** What the board's tasks raise about the agents that hold or held them. */
246
+ flags?: DashTeamFlag[];
163
247
  /** More sessions or tasks than the board carries. */
164
248
  truncated: boolean;
165
249
  }
@@ -210,6 +294,30 @@ export interface DashTeamMessage {
210
294
  kind: 'message' | 'note';
211
295
  to?: string;
212
296
  }
297
+ /** A message by or to one agent, and whether its recipient read it. */
298
+ export interface DashTeamAgentMessage {
299
+ id: string;
300
+ seq: number;
301
+ /** A session id, or `user`: the person (this page, the operator CLI). */
302
+ from: string;
303
+ /** The session it is to; none: to every agent. */
304
+ to?: string;
305
+ kind: 'message' | 'note';
306
+ /** Cut past a few thousand characters. */
307
+ body: string;
308
+ createdAt: number;
309
+ /** Its recipient fetched it (agent_sync). */
310
+ read: boolean;
311
+ /** Its recipient acknowledged it. */
312
+ acked: boolean;
313
+ }
314
+ /** `GET /api/team/messages?session=` — the agent's newest direct messages, by it and to it, and the notes it sent; newest last. */
315
+ export interface DashTeamAgentMessages {
316
+ sessionId: string;
317
+ messages: DashTeamAgentMessage[];
318
+ /** Direct messages to it it has not read — all of them, not only those listed. */
319
+ unread: number;
320
+ }
213
321
  /**
214
322
  * What an agent's OWN transcript says (planning/team/03-agent-transcripts.md) — the Codex rollout or the Claude Code
215
323
  * transcript its coordination session is linked to: by its hooks' native key, or by the `agent_join` answer that names
@@ -410,7 +518,7 @@ export interface DashTeamReviewDelegation {
410
518
  }
411
519
  /** What the run says about the process — a hint for the person reviewing it, never a verdict. */
412
520
  export interface DashTeamReviewFlag {
413
- kind: 'self-review' | 'manager-did-work' | 'same-model' | 'role-model-mismatch' | 'unjoined-agent' | 'long-wait' | 'silent-claim' | 'rework' | 'no-evidence' | 'recovery' | 'open-under-closed' | 'serial' | 'idle-agent';
521
+ kind: 'self-review' | 'manager-did-work' | 'same-model' | 'role-model-mismatch' | 'unjoined-agent' | 'long-wait' | 'silent-claim' | 'rework' | 'no-evidence' | 'recovery' | 'open-under-closed' | 'serial' | 'idle-agent' | DashTeamConductKind;
414
522
  severity: 'info' | 'warn';
415
523
  text: string;
416
524
  taskId?: string;
@@ -483,3 +591,42 @@ export interface DashTeamReview {
483
591
  tasks?: number;
484
592
  };
485
593
  }
594
+ /** The clients LensMCP launches headless: Codex (`codex exec`) and Claude Code (`claude -p`). */
595
+ export type DashTeamLaunchClient = 'codex' | 'claude';
596
+ /** An agent a manager launched (`agent_spawn`): what it runs, where, and how it is doing. */
597
+ export interface DashTeamLaunch {
598
+ id: string;
599
+ role: string;
600
+ client: DashTeamLaunchClient;
601
+ model?: string;
602
+ effort?: string;
603
+ /** The session that launched it (a manager), and the goal and task it was launched for. */
604
+ by: string;
605
+ goalId?: string;
606
+ taskId?: string;
607
+ /** The checkout it works in — its goal's worktree — and that worktree's branch. */
608
+ worktree: string;
609
+ branch?: string;
610
+ pid: number;
611
+ /** `running` until it exits; `stopped` by the person or its deadline; `failed`: it could not start. */
612
+ state: 'running' | 'exited' | 'stopped' | 'failed';
613
+ startedAt: number;
614
+ /** When it is stopped if still running. */
615
+ deadline: number;
616
+ endedAt?: number;
617
+ exitCode?: number;
618
+ /** Its coordination session once it joined (its hooks name the launch), and its client's thread or session id. */
619
+ sessionId?: string;
620
+ threadId?: string;
621
+ /** The newest lines of its output, readable — what it said before it joined, or why it ended. */
622
+ tail?: string[];
623
+ }
624
+ /** `GET /api/team/launches` — the repository's launched agents, newest first, and whether launching is on. */
625
+ export interface DashTeamLaunchesAnswer {
626
+ /** Features › Team launches agents. */
627
+ enabled: boolean;
628
+ /** The most launches running at once (Features), and how many run now. */
629
+ max: number;
630
+ running: number;
631
+ launches: DashTeamLaunch[];
632
+ }
package/lib/team.js CHANGED
@@ -1 +1 @@
1
- "use strict";export const DASH_TEAM_KINDS=["goal","build","bug","review","test","docs","marketing","research","chore"],DASH_TEAM_LINK_KINDS=["task","flow","error","suggestion","ai-call","review","page","route","commit","branch","worktree","file"];
1
+ "use strict";export const DASH_TEAM_KINDS=["goal","build","bug","review","test","qa","docs","marketing","research","chore"],DASH_TEAM_LINK_KINDS=["task","flow","error","suggestion","ai-call","review","page","route","commit","branch","worktree","file"];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lensmcp/protocol-types",
3
- "version": "1.25.37",
3
+ "version": "1.25.39",
4
4
  "type": "module",
5
5
  "main": "./index.js",
6
6
  "module": "./index.js",