@lensmcp/protocol-types 1.26.10 → 1.26.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/index.d.ts +6 -0
  2. package/index.js +1 -1
  3. package/lib/ai-cache-facts.d.ts +69 -0
  4. package/lib/ai-cache-facts.js +1 -0
  5. package/lib/ai-cache-verdict.d.ts +112 -0
  6. package/lib/ai-cache-verdict.js +1 -0
  7. package/lib/ai-cache.d.ts +133 -0
  8. package/lib/ai-cache.js +4 -0
  9. package/lib/ai-call-groups.d.ts +2 -0
  10. package/lib/ai-call-groups.js +2 -2
  11. package/lib/ai-call-row.d.ts +44 -0
  12. package/lib/ai-call-row.js +3 -3
  13. package/lib/ai-call.d.ts +6 -0
  14. package/lib/ai-call.js +9 -9
  15. package/lib/ai-compare.d.ts +298 -0
  16. package/lib/ai-compare.js +4 -0
  17. package/lib/ai-context.js +6 -6
  18. package/lib/ai-origins.js +9 -9
  19. package/lib/ai-together.d.ts +374 -0
  20. package/lib/ai-together.js +5 -0
  21. package/lib/bounded-clone.js +1 -1
  22. package/lib/bounded-map.js +1 -1
  23. package/lib/bounded-writer.js +1 -1
  24. package/lib/capture-demand.js +1 -1
  25. package/lib/dashboard-path.js +1 -1
  26. package/lib/dashboard.d.ts +11 -0
  27. package/lib/docker-errors.js +1 -1
  28. package/lib/docker-jobs.js +1 -1
  29. package/lib/docker-report.js +2 -2
  30. package/lib/docker-runs.js +3 -3
  31. package/lib/error-cause.js +6 -6
  32. package/lib/error-dismissal.js +1 -1
  33. package/lib/error-verdict.js +3 -3
  34. package/lib/event-loop.js +1 -1
  35. package/lib/expected-failure.js +2 -2
  36. package/lib/finding-proof.d.ts +35 -0
  37. package/lib/finding-proof.js +1 -0
  38. package/lib/flood-guard.js +1 -1
  39. package/lib/goal-design.js +1 -1
  40. package/lib/host-agents.js +1 -1
  41. package/lib/lint-coverage.js +1 -1
  42. package/lib/log-query.js +1 -1
  43. package/lib/metrics-reset.js +1 -1
  44. package/lib/overseer-findings.js +1 -1
  45. package/lib/peers.js +1 -1
  46. package/lib/perf-rules.js +1 -1
  47. package/lib/pod-memory.js +1 -1
  48. package/lib/producer-health.js +1 -1
  49. package/lib/remote-instances.js +1 -1
  50. package/lib/sources.js +1 -1
  51. package/lib/static-checks.js +1 -1
  52. package/lib/system-report.js +1 -1
  53. package/lib/team.js +1 -1
  54. package/package.json +1 -1
@@ -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 L=Object.defineProperty;var m=(t,o)=>L(t,"name",{value:o,configurable:!0});var S=Object.defineProperty,c=m((t,o)=>S(t,"name",{value:o,configurable:!0}),"d");import{aiCallOf as B}from"./ai-call.js";import{aiContextOf as T,aiSplitOf as z}from"./ai-context.js";export function aiCallCacheOf(t){return{mode:t.mode,...t.modeSaid?{modeSaid:!0}:{},ttl:t.ttl,...t.ttlSaid?{ttlSaid:!0}:{},...t.key?{key:!0}:{},breakpoints:t.breakpoints.map(o=>({at:o.at,tokens:o.tokens,...o.ttl?{ttl:o.ttl}:{},...o.implicit?{implicit:!0}:{}})),...t.writes?{writes:{...t.writes}}:{},...t.marks.length?{marks:t.marks}:{}}}m(aiCallCacheOf,"aiCallCacheOf"),c(aiCallCacheOf,"aiCallCacheOf");export function aiRowOut(t){if(!t.cache?.marks)return t;const{marks:o,...e}=t.cache;return{...t,cache:e}}m(aiRowOut,"aiRowOut"),c(aiRowOut,"aiRowOut");export const EMPTY_AI_NAMES={version:1,names:{},merge:{}};export function aiModelUses(t,o){const e=o.toLowerCase(),a=new Map;for(const n of t){if(n.host.toLowerCase()!==e)continue;const s=n.model??"unknown";let r=a.get(s);r||(r={use:{model:s,calls:0,failed:0,unmetered:0,input:0,cached:0,output:0,costUsd:0,priced:0,agents:0,first:n.at,last:n.at},agents:new Set},a.set(s,r));const i=r.use;n.prewarm?i.prewarms=(i.prewarms??0)+1:i.calls+=1,n.failed&&(i.failed+=1),n.tokens?(i.input+=n.tokens.input??0,i.cached+=n.tokens.cached??0,i.output+=n.tokens.output??0):i.unmetered+=1,n.costUsd!==void 0&&(i.costUsd+=n.costUsd,i.priced+=1),r.agents.add(n.agent.key),i.first=Math.min(i.first,n.at),i.last=Math.max(i.last,n.at)}return[...a.values()].map(({use:n,agents:s})=>({...n,agents:s.size})).sort((n,s)=>s.calls-n.calls||s.last-n.last)}m(aiModelUses,"aiModelUses"),c(aiModelUses,"aiModelUses");export function aiAgentUses(t,o){const e=o?.toLowerCase(),a=new Map;for(const n of t){if(e!==void 0&&n.host.toLowerCase()!==e)continue;let s=a.get(n.agent.key);s||(s={use:{key:n.agent.key,name:n.agent.name,from:n.agent.from,calls:0,runs:0,failed:0,input:0,cached:0,written:0,output:0,costUsd:0,priced:0,split:{},models:[],last:n.at},runs:new Set,models:new Map},a.set(n.agent.key,s));const r=s.use;n.prewarm?r.prewarms=(r.prewarms??0)+1:(r.calls+=1,s.runs.add(n.run.key)),n.failed&&(r.failed+=1),r.input+=n.tokens?.input??0,r.cached+=n.tokens?.cached??0,r.written+=n.tokens?.written??0,r.output+=n.tokens?.output??0,n.costUsd!==void 0&&(r.costUsd+=n.costUsd,r.priced+=1);for(const[i,u]of Object.entries(n.split??{}))r.split[i]=(r.split[i]??0)+u;n.model&&s.models.set(n.model,(s.models.get(n.model)??0)+1),r.last=Math.max(r.last,n.at)}return[...a.values()].map(({use:n,runs:s,models:r})=>({...n,runs:s.size,models:[...r].sort((i,u)=>u[1]-i[1]).map(([i])=>i)})).sort((n,s)=>s.input-n.input||s.calls-n.calls)}m(aiAgentUses,"aiAgentUses"),c(aiAgentUses,"aiAgentUses");export const MAX_TOOLS=40,MAX_THREAD_CALLS=300,MAX_META=24;const E=160,M="unknown service";export const aiKeyOf=c((t,o)=>`${t}:${o.normalize("NFKD").toLowerCase().replace(/[^a-z0-9:.]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80)||"unnamed"}`,"aiKeyOf");export function humanName(t){const o=t.trim();if(/[A-Z]/.test(o)||/ /.test(o))return o;const e=o.replace(/[-_.]+/g," ").trim();return e?e[0].toUpperCase()+e.slice(1):o}m(humanName,"humanName"),c(humanName,"humanName");const f=c((t,o=E)=>{if(!t)return;const e=t.replace(/\s+/g," ").trim();if(e)return e.length>o?`${e.slice(0,o-1)}\u2026`:e},"line");export function promptTitle(t){const o=t.split(`
2
+ `).map(n=>n.trim()).find(Boolean)??"",e=/^#{1,6}\s+(.+)$/.exec(o);if(e){const n=e[1].split(/\s+[—–]\s+|\s+-\s+|:\s/)[0].replace(/[*_`]/g,"").trim();return n?n.slice(0,60):void 0}const a=/^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(a){const n=a[1].trim().split(/\s+/);if(n.length>6||/^(?:going|about|given|now|here|responsible|able|allowed|expected|tasked|asked|helping|working|being|not)$/i.test(n[0]))return;const s=n.join(" ");return s[0].toUpperCase()+s.slice(1)}}m(promptTitle,"promptTitle"),c(promptTitle,"promptTitle");export function promptOpening(t){const o=t.split(`
3
+ `).map(a=>a.trim()).find(Boolean);if(!o)return;const e=o.replace(/^[#>*\s-]+/,"").split(/\s+/).filter(Boolean);if(!(e.length<3))return e.length>7?`${e.slice(0,7).join(" ")} \u2026`:e.join(" ")}m(promptOpening,"promptOpening"),c(promptOpening,"promptOpening");export function actionName(t){const o=t.split("::")[0],e=/^(?:[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(a=>a.split(".").filter(n=>!e.test(n)).join(".")).filter((a,n,s)=>a||n<s.length-1).join(":").slice(0,120)}m(actionName,"actionName"),c(actionName,"actionName");const g=c((t,o)=>{const e=t.request.headers.find(([a])=>a.toLowerCase()===o)?.[1];if(e===void 0||!o.startsWith("x-lensmcp-")||!e.includes("%"))return e;try{return decodeURIComponent(e)}catch{return e}},"header"),A=c(t=>t!==void 0&&/^\d{1,6}$/.test(t.trim())?Number(t.trim()):void 0,"intOf"),h=c((t,...o)=>{for(const e of o)if(t[e]?.trim())return t[e].trim()},"first");function j(t){const o={};for(const e of t.settings)if(e.name.startsWith("metadata.")){if(Object.keys(o).length>=MAX_META)break;o[e.name.slice(9)]=e.value.slice(0,200)}return o}m(j,"T"),c(j,"metaOf");function U(t,o,e){const a=c((p,k)=>({key:aiKeyOf("agent",p),name:humanName(p),from:k}),"named"),n=h(e,"agent","agent_name","agentName","assistant");if(n)return a(n,"metadata");const s=g(t,"x-lensmcp-agent");if(s?.trim())return a(s.trim(),"header");const r=o.system.map(p=>promptTitle(p.text)).find(Boolean);if(r)return a(r,"prompt");const i=o.answer.format?.name;if(i)return a(i,"schema");const u=[...o.tools,...o.answer.toolCalls].map(p=>p.server).find(Boolean);if(u)return a(u,"tools");const l=o.system.map(p=>promptOpening(p.text)).find(Boolean);return l?{key:aiKeyOf("agent",`prompt ${l.replace(/ …$/,"")}`),name:l,from:"prompt"}:a(`${t.service??M} ${o.api==="embeddings"?"embeddings":o.model??o.api}`,"service")}m(U,"B"),c(U,"agentOf");function _(t,o,e){const a=c((r,i)=>({key:aiKeyOf("action",r),name:r,from:i}),"named"),n=h(e,"act","action","task","step","operation");if(n&&actionName(n))return a(actionName(n),"metadata");const s=g(t,"x-lensmcp-action");if(s?.trim())return a(actionName(s.trim()),"header");if(o.answer.format?.name)return a(o.answer.format.name,"schema")}m(_,"E"),c(_,"actionOf");function N(t){if(t.kind==="message")return f(t.text);if(t.kind==="tool")return f(t.output!==void 0?`${t.tool} \u2192 ${t.output}`:`${t.tool}(${t.arguments})`)}m(N,"x"),c(N,"turnLine");function v(t){const o=t.answer;return o.error?f(`error: ${o.error}`):o.refusal?f(`refused: ${o.refusal}`):o.toolCalls.length?f(o.toolCalls.map(e=>`${e.tool}(${e.arguments})`).join(" \xB7 ")):t.embedding?`${t.embedding.vectors??t.embedding.count} vector${(t.embedding.vectors??t.embedding.count)===1?"":"s"}${t.embedding.dimensions?` \xD7 ${t.embedding.dimensions}`:""}`:f(o.text)}m(v,"_"),c(v,"saidLine");export function aiCallRow(t,o){const e=B(t);if(!e||!t.ai)return;const a=j(e),n=new Map(e.settings.map(d=>[d.name,d.value])),s=h(a,"run","run_id","runId"),r=g(t,"x-lensmcp-run")?.trim(),i=e.turns.filter(d=>d.kind==="tool").filter(d=>d.output!==void 0&&d.callId).map(d=>d.callId),u=e.answer.toolCalls.map(d=>d.callId).filter(d=>!!d),l=e.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=e.shape==="embedding"||l?.input===void 0?{}:z(T(e,{sections:!1})),w=h(a,"thread","thread_id","threadId","conversation","conversation_id","conversationId","case","case_id","caseId"),y=g(t,"x-lensmcp-thread")?.trim(),x=h(a,"parent_run","parentRun","parent")??g(t,"x-lensmcp-parent")?.trim(),b=_(t,e,a),$=A(a.round),O=A(a.attempt),C=n.get("continues response"),I=[...e.turns].reverse().map(N).find(Boolean),R=e.answer.status==="failed"||!!e.answer.error||(t.status??0)>=400||!!t.error;return{id:t.id,at:t.startedAt,...t.durationMs!==void 0?{durationMs:t.durationMs}:{},...t.status!==void 0?{status:t.status}:{},...R?{failed:!0}:{},service:t.service??M,...t.flowId?{flowId:t.flowId}:{},...t.requestId?{requestId:t.requestId}:{},provider:t.ai.provider,host:t.host,api:e.api,shape:e.shape,...e.model?{model:e.model}:{},...t.response.stream?{streamed:!0}:{},...p&&Object.keys(p).length?{tokens:p}:{},...Object.keys(k).length?{split:k}:{},...e.cache?.prewarm?{prewarm:!0}:{},...e.cache?{cache:aiCallCacheOf(e.cache)}:{},agent:U(t,e,a),run:s?{key:`run:${s}`,from:"metadata"}:r?{key:`run:${r}`,from:"header"}:{key:`run:${t.id}`,from:"alone"},...w?{thread:{key:`thread:${w}`,name:w,from:"metadata"}}:y?{thread:{key:`thread:${y}`,name:y,from:"header"}}:{},...x?{parent:`run:${x}`}:{},...$!==void 0?{round:$}:{},...O!==void 0?{attempt:O}:{},...b?{action:b}:{},...e.answer.format?.name?{schema:e.answer.format.name}:{},...e.tools.length?{tools:e.tools.slice(0,MAX_TOOLS).map(d=>d.name)}:{},...e.answer.toolCalls.length?{called:e.answer.toolCalls.map(d=>d.name)}:{},...u.length?{callIds:u}:{},...i.length?{answers:i}:{},...e.responseId?{responseId:e.responseId}:{},...C?{previousResponseId:C}:{},...Object.keys(a).length?{meta:a}:{},...e.gaps.some(d=>/kept to its first|cut/.test(d))?{cut:!0}:{},...o.content&&I?{asked:I}:{},...o.content&&v(e)?{said:v(e)}:{}}}m(aiCallRow,"aiCallRow"),c(aiCallRow,"aiCallRow");export function linkAiRuns(t){const o=[...t].sort((s,r)=>s.at-r.at||s.id.localeCompare(r.id)),e=new Map,a=new Map;for(const s of o){if(s.run.from==="alone"){const r=s.previousResponseId?e.get(s.previousResponseId):void 0,i=r?void 0:s.answers?.map(l=>a.get(l)).find(Boolean),u=r??i;if(u){const l=r?"chain":"tools";s.run={key:u.run.key,from:u.run.from==="alone"||u.run.from===l?l:u.run.from},u.run.from==="alone"&&(u.run={key:u.run.key,from:l})}}s.responseId&&e.set(s.responseId,s);for(const r of s.callIds??[])a.set(r,s)}const n=new Map;for(const s of o){const r=(n.get(s.run.key)??0)+1;n.set(s.run.key,r),s.step=r}return t}m(linkAiRuns,"linkAiRuns"),c(linkAiRuns,"linkAiRuns");export function mergedKey(t,o){let e=o;for(let a=0;a<8&&t.merge[e]&&t.merge[e]!==o;a++)e=t.merge[e];return e}m(mergedKey,"mergedKey"),c(mergedKey,"mergedKey");export function applyAiNames(t,o){if(!Object.keys(o.names).length&&!Object.keys(o.merge).length)return t;const e=new Map;for(const n of t)e.has(n.agent.key)||e.set(n.agent.key,n.agent),n.action&&!e.has(n.action.key)&&e.set(n.action.key,n.action);const a=c(n=>{const s=mergedKey(o,n.key),r=o.names[s];if(r)return{key:s,name:r,from:"renamed"};if(s===n.key)return n;const i=e.get(s);return{key:s,name:i?.name??humanName(s.replace(/^[a-z]+:/,"")),from:i?.from??n.from}},"resolve");for(const n of t)n.agent=a(n.agent),n.action&&(n.action=a(n.action));return t}m(applyAiNames,"applyAiNames"),c(applyAiNames,"applyAiNames");export function aiNamesOf(t){const o=t&&typeof t=="object"?t:{},e=c(a=>{const n={};if(a&&typeof a=="object"&&!Array.isArray(a))for(const[s,r]of Object.entries(a))/^(agent|action):/.test(s)&&typeof r=="string"&&r.trim()&&(n[s]=r.trim().slice(0,120));return n},"pick");return{version:1,names:e(o.names),merge:e(o.merge)}}m(aiNamesOf,"aiNamesOf"),c(aiNamesOf,"aiNamesOf");
package/lib/ai-call.d.ts CHANGED
@@ -1,4 +1,6 @@
1
1
  import type { HttpExchange } from './http-exchange.js';
2
+ import { type AiCache } from './ai-cache.js';
3
+ import type { AiCacheTtl } from './ai-cache-facts.js';
2
4
  /**
3
5
  * An AI provider's call read for a person (Data › External APIs › Request & response): what the model was told — its
4
6
  * system prompt, the context the app put in, the conversation so far with each tool call and what it returned, the
@@ -32,6 +34,8 @@ export interface AiCall {
32
34
  tools: AiTool[];
33
35
  answer: AiAnswer;
34
36
  usage?: AiUsage;
37
+ /** Its prompt cache as the provider reports it: mode, breakpoints, lifetime, a prewarm, reads and writes ({@link aiCacheOf}). */
38
+ cache?: AiCache;
35
39
  embedding?: {
36
40
  inputs: string[];
37
41
  count: number;
@@ -110,6 +114,8 @@ export interface AiUsage {
110
114
  cached?: number;
111
115
  /** Written to the provider's prompt cache by this call — read at a discount by a later call that opens the same way. */
112
116
  written?: number;
117
+ /** The writes by lifetime, where the provider split them (OpenAI `ttl_30m_tokens` / `ttl_12h_tokens`, Anthropic `ephemeral_5m` / `ephemeral_1h`). */
118
+ writes?: Partial<Record<AiCacheTtl, number>>;
113
119
  output?: number;
114
120
  reasoning?: number;
115
121
  total?: number;
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 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 ne=Object.defineProperty;var v=(t,s)=>ne(t,"name",{value:s,configurable:!0});var re=Object.defineProperty,f=v((t,s)=>re(t,"name",{value:s,configurable:!0}),"d");import{aiCacheOf as ae}from"./ai-cache.js";const b=f(t=>!!t&&typeof t=="object"&&!Array.isArray(t),"isObj"),e=f(t=>typeof t=="string"?t:void 0,"str"),y=f(t=>typeof t=="number"&&Number.isFinite(t)?t:void 0,"num"),k=f(t=>Array.isArray(t)?t:[],"arr"),u=f(t=>b(t)?t:{},"obj"),A=f(t=>typeof t=="string"?t:t===void 0?"":JSON.stringify(t),"json");function q(t){const s={};for(const[n,i]of t)typeof i=="number"&&Number.isFinite(i)&&i>0&&(s[n]=i);return Object.keys(s).length?{writes:s}:{}}v(q,"J"),f(q,"writesOf");function E(t,s){const n=y(s.cache_write_tokens)??y(t.cache_write_tokens),i=u(s.cache_write_tokens_details??t.cache_write_tokens_details);return{...n?{written:n}:{},...q([["30m",i.ttl_30m_tokens],["12h",i.ttl_12h_tokens]])}}v(E,"K"),f(E,"openaiWrites");const Z=f(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,i=!1,a=!1,r=!1;const o=t.length,l=f(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(i){r?r=!1:d==="\\"?r=!0:d==='"'&&(i=!1,a?s[s.length-1].state="colon":l(m+1));continue}if(d===" "||d===`
2
+ `||d==="\r"||d===" ")continue;const _=s[s.length-1];if(d==='"'){i=!0,a=!!_&&_.c==="{"&&_.state==="key";continue}if(d==="{"||d==="["){s.push({c:d,state:d==="{"?"key":"value"}),n=m+1;continue}if(d==="}"||d==="]"){s.pop(),l(m+1);continue}if(d===":"){_&&(_.state="value");continue}if(d===","){_&&(_.state=_.c==="{"?"key":"value");continue}let h=m;for(;h<o&&!`,}]
3
+ \r `.includes(t[h]);)h++;if(h>=o)break;l(h),m=h-1}const c=s.map(m=>m.c==="{"?"}":"]").reverse().join("");if(i&&!a)for(let m=0;m<=6;m++)try{return{value:JSON.parse(`${t.slice(0,o-m)}${CUT_MARK}"${c}`),cut:!0}}catch{}if(n)try{return{value:JSON.parse(`${t.slice(0,n)}${c}`),cut:!0}}catch{return}}v(parseJsonPrefix,"parseJsonPrefix"),f(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"),f(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"),f(splitToolName,"splitToolName");const $=f((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 Capture \u203A AI calls, for the calls made after.`);return}if(t.omitted||t.text===void 0)return;const i=parseJsonPrefix(t.text);if(i)return(i.cut||t.truncated)&&n.push(`The ${s} was kept to its first ${Z(t.kept)} of ${Z(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}).`),i.value}v(M,"N"),f(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,"E"),f(J,"eventJson");function O(t){if(typeof t=="string")return{text:t,attachments:[]};const s=[],n=[];for(const i of k(t)){if(typeof i=="string"){s.push(i);continue}const a=u(i),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(u(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 U(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(O,"I"),f(O,"contentOf");const N=f(t=>typeof t=="string"?t:Array.isArray(t)&&O(t).text||A(t),"outputOf");function I(t,s){const n=[];for(const[a,r]of s){let o=t;for(const c of a.split("."))o=u(o)[c];if(o==null)continue;const l=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:l})}const i=u(t.metadata);for(const[a,r]of Object.entries(i))n.push({name:`metadata.${a}`,value:typeof r=="string"?r:JSON.stringify(r)});return n}v(I,"O"),f(I,"settingsOf");function C(t,s,n,i){const a=s?t.byCallId.get(s):void 0;if(a){a.output=n,i&&(a.error=i);return}t.call.turns.push({kind:"tool",...$("(an earlier call)","",{callId:s,output:n,error:i})})}v(C,"T"),f(C,"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"),f(j,"addCall");const ie=[["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"],["prompt_cache_options.mode","prompt cache mode"],["prompt_cache_options.ttl","prompt cache ttl"],["prompt_cache_options.prewarm","prompt cache prewarm"],["prompt_cache_retention","prompt cache retention"]],D=f(t=>A(Object.fromEntries(Object.entries(t).filter(([s])=>s!=="type"&&s!=="id"&&s!=="status"))),"builtInCall");function H(t,s){const n=e(s.type)??(s.role?"message":"");if(n==="message"){const i=e(s.role)??"user",{text:a,attachments:r}=O(s.content);i==="system"?t.call.system.push({source:"system message",text:a}):t.call.turns.push({kind:"message",role:i,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")C(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 i=k(s.tools).map(a=>e(u(a).name)).filter(Boolean);j(t,$("list_tools","",{server:e(s.server_label),output:i.join(", ")}))}else if(n==="reasoning"){const i=k(s.summary).map(a=>e(u(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(U,"Z"),k(U,"R"),_(U,"responsesItem");function W(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(W,"D"),k(W,"W"),_(W,"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",...i?{text:i}:{}})}else n&&j(t,$(n.replace(/_call$/,""),D(s),{callId:e(s.call_id)??e(s.id)}))}v(H,"D"),f(H,"responsesItem");function R(t){return k(t.tools).map(s=>{const n=u(s),i=e(n.type)??"function";if(i==="mcp"){const r=e(n.server_label)??"mcp",o=k(n.allowed_tools).map(l=>e(l)).filter(Boolean);return{name:r,server:r,tool:o.length?o.join(", "):"every tool",type:i,...e(n.server_description)??e(n.server_url)?{description:e(n.server_description)??e(n.server_url)}:{},called:0}}const a=e(n.name)??i;return{name:a,...splitToolName(a),type:i,...e(n.description)?{description:e(n.description)}:{},...n.parameters!==void 0?{parameters:n.parameters}:{},...typeof n.strict=="boolean"?{strict:n.strict}:{},called:0}})}v(R,"Q"),f(R,"responsesTools");function K(t,s){const n=t.call.answer;e(s.status)&&(n.status=e(s.status));const i=e(u(s.incomplete_details).reason);i&&(n.finish=i);const a=u(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)),z(t,k(s.output).map(u));const r=u(s.usage);Object.keys(r).length&&(t.call.usage={...y(r.input_tokens)!==void 0?{input:y(r.input_tokens)}:{},...y(u(r.input_tokens_details).cached_tokens)!==void 0?{cached:y(u(r.input_tokens_details).cached_tokens)}:{},...E(r,u(r.input_tokens_details)),...y(r.output_tokens)!==void 0?{output:y(r.output_tokens)}:{},...y(u(r.output_tokens_details).reasoning_tokens)!==void 0?{reasoning:y(u(r.output_tokens_details).reasoning_tokens)}:{},...y(r.total_tokens)!==void 0?{total:y(r.total_tokens)}:{}})}v(K,"L"),f(K,"responsesAnswer");function z(t,s){const n=t.call.answer,i=[],a=[];for(const r of s){const o=e(r.type);if(o==="message")for(const l of k(r.content).map(u))e(l.refusal)?n.refusal=e(l.refusal):e(l.text)!==void 0&&i.push(e(l.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 l=k(r.summary).map(c=>e(u(c).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
+ `);l&&a.push(l)}else o&&o!=="mcp_list_tools"&&n.toolCalls.push($(o.replace(/_call$/,""),D(r),{callId:e(r.call_id)??e(r.id)}))}i.length&&(n.text=i.join(`
10
10
 
11
11
  `)),a.length&&(n.reasoning=a.join(`
12
12
 
13
- `))}v(E,"E"),k(E,"G"),_(E,"responsesOutput");function Z(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(Z,"H"),k(Z,"Z"),_(Z,"responsesStream");function D(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)&&U(t,i);a.tools=W(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=>Z(t,i,l))}v(D,"R"),k(D,"D"),_(D,"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,"L"),_(z,"chatCalls");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=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(K,"z"),k(K,"P"),_(K,"chatAnswer");function F(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}}))};K(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(F,"G"),k(F,"V"),_(F,"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=>K(t,s),s=>F(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(z,"F"),f(z,"responsesOutput");function G(t,s,n){let i,a=0;const r=new Map,o=new Set,l=new Map,c=new Map,m=new Map;for(const _ of s){const h=J(_);if(!h)continue;h.cut&&a++;const p=h.v,g=e(p.type)??_.event,w=y(p.output_index)??0;if(g==="response.completed"||g==="response.incomplete"||g==="response.failed"){if(!h.cut&&b(p.response))i=p.response;else if(b(p.response)){const x=p.response;e(x.status)&&(t.call.answer.status=e(x.status))}}else if(g==="response.created"||g==="response.in_progress"){const x=u(p.response);e(x.model)&&(t.call.model??=e(x.model)),e(x.id)&&(t.call.responseId??=e(x.id))}else g==="response.output_item.added"||g==="response.output_item.done"?b(p.item)&&(!o.has(w)||!h.cut)&&(r.set(w,{...r.get(w)??{},...p.item}),g.endsWith(".done")&&!h.cut&&o.add(w)):g==="response.output_text.delta"||g==="response.refusal.delta"?l.set(w,(l.get(w)??"")+(e(p.delta)??"")):g==="response.output_text.done"&&!h.cut&&e(p.text)!==void 0?l.set(w,e(p.text)):g==="response.function_call_arguments.delta"||g==="response.custom_tool_call_input.delta"||g==="response.mcp_call_arguments.delta"?c.set(w,(c.get(w)??"")+(e(p.delta)??"")):(g==="response.function_call_arguments.done"||g==="response.mcp_call_arguments.done")&&!h.cut&&e(p.arguments)!==void 0?c.set(w,e(p.arguments)):g==="response.reasoning_summary_text.delta"?m.set(w,(m.get(w)??"")+(e(p.delta)??"")):(g==="error"||g==="response.error")&&(t.call.answer.error=e(p.message)??e(u(p.error).message)??"the stream reported an error")}if(i){K(t,i);return}const d=[...r.entries()].sort(([_],[h])=>_-h).map(([_,h])=>{if(o.has(_))return h;const p=e(h.type);return p==="message"&&l.has(_)?{...h,content:[{type:"output_text",text:l.get(_)}]}:(p==="function_call"||p==="mcp_call")&&c.has(_)?{...h,arguments:c.get(_)}:p==="custom_tool_call"&&c.has(_)?{...h,input:c.get(_)}:p==="reasoning"&&m.has(_)?{...h,summary:[{type:"summary_text",text:m.get(_)}]}:h});for(const[_,h]of l)r.has(_)||d.push({type:"message",content:[{type:"output_text",text:h}]});z(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(G,"V"),f(G,"responsesStream");function Q(t,s,n,i){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 l of k(r))b(l)&&H(t,l);a.tools=R(s),a.settings=I(s,ie);const o=u(u(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,i,l=>K(t,l),l=>G(t,l,i))}v(Q,"X"),f(Q,"responsesCall");const le=[["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 L(t){const s=k(t.tool_calls).map(u).map(i=>{const a=u(i.function);return $(e(a.name)??e(u(i.custom).name)??"?",e(a.arguments)??e(u(i.custom).input)??"",{callId:e(i.id)})}),n=u(t.function_call);return e(n.name)&&s.push($(e(n.name),e(n.arguments)??"",{})),s}v(L,"P"),f(L,"chatCalls");function P(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 i=u(k(s.choices)[0]),a=u(i.message),r=O(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(...L(a)),e(i.finish_reason)&&(n.finish=e(i.finish_reason)),n.status=n.finish?"completed":n.status??"unknown";const l=u(s.error);e(l.message)&&(n.error=e(l.message));const c=u(s.usage);Object.keys(c).length&&(t.call.usage={...y(c.prompt_tokens)!==void 0?{input:y(c.prompt_tokens)}:{},...y(u(c.prompt_tokens_details).cached_tokens)!==void 0?{cached:y(u(c.prompt_tokens_details).cached_tokens)}:{},...E(c,u(c.prompt_tokens_details)),...y(c.completion_tokens)!==void 0?{output:y(c.completion_tokens)}:{},...y(u(c.completion_tokens_details).reasoning_tokens)!==void 0?{reasoning:y(u(c.completion_tokens_details).reasoning_tokens)}:{},...y(c.total_tokens)!==void 0?{total:y(c.total_tokens)}:{}})}v(P,"U"),f(P,"chatAnswer");function V(t,s,n){let i="",a="",r="",o,l,c,m,d=0;const _=new Map;for(const p of s){const g=J(p);if(!g)continue;g.cut&&d++,c??=e(g.v.model),m??=e(g.v.id),b(g.v.usage)&&(l=g.v.usage),b(g.v.error)&&(t.call.answer.error=e(g.v.error.message)??"the stream reported an error");const w=u(k(g.v.choices)[0]),x=u(w.delta);i+=e(x.content)??"",a+=e(x.reasoning_content)??e(x.reasoning)??"",r+=e(x.refusal)??"";for(const S of k(x.tool_calls).map(u)){const U=y(S.index)??0,B=_.get(U)??{name:"",args:""},W=u(S.function);e(S.id)&&(B.id=e(S.id)),B.name+=e(W.name)??"",B.args+=e(W.arguments)??"",_.set(U,B)}e(w.finish_reason)&&(o=e(w.finish_reason))}const h={content:i,...a?{reasoning_content:a}:{},...r?{refusal:r}:{},tool_calls:[..._.entries()].sort(([p],[g])=>p-g).map(([,p])=>({id:p.id,function:{name:p.name,arguments:p.args}}))};P(t,{...c?{model:c}:{},...m?{id:m}:{},choices:[{message:h,...o?{finish_reason:o}:{}}],...l?{usage:l}:{}}),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(V,"ee"),f(V,"chatStream");function X(t,s,n,i){const a=t.call;e(s.model)&&(a.model=e(s.model));for(const o of k(s.messages).map(u)){const l=e(o.role)??"user",{text:c,attachments:m}=O(o.content);if(l==="system")a.system.push({source:"system message",text:c});else if(l==="tool")C(t,e(o.tool_call_id),c);else if(l==="function")C(t,void 0,c);else{(c||m.length||l!=="assistant")&&a.turns.push({kind:"message",role:l,text:c,...m.length?{attachments:m}:{}});for(const d of L(o))j(t,d)}}a.tools=[...k(s.tools).map(u),...k(s.functions).map(o=>({type:"function",function:o}))].map(o=>{const l=u(o.function),c=e(o.type)??"function",m=e(l.name)??e(u(o.custom).name)??c;return{name:m,...splitToolName(m),type:c,...e(l.description)??e(u(o.custom).description)?{description:e(l.description)??e(u(o.custom).description)}:{},...l.parameters!==void 0?{parameters:l.parameters}:{},...typeof l.strict=="boolean"?{strict:l.strict}:{},called:0}}),a.settings=I(s,le);const r=u(s.response_format);if(e(r.type)&&r.type!=="text"){const o=u(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,i,o=>P(t,o),o=>V(t,o,i))}v(X,"te"),f(X,"chatCall");const ce=[["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"],["cache_control.type","cache control"],["cache_control.ttl","cache ttl"]];function Y(t,s,n){if(typeof n=="string"){t.call.turns.push({kind:"message",role:s,text:n});return}const i=[],a=[],r=f(()=>{(i.length||a.length)&&t.call.turns.push({kind:"message",role:s,text:i.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 L(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]}:{}}),i.length=0,a.length=0},"flush");for(const o of k(n).map(u)){const l=e(o.type)??"";l==="text"?i.push(e(o.text)??""):l==="tool_use"||l==="server_tool_use"||l==="mcp_tool_use"?(r(),j(t,$(e(o.name)??"?",A(o.input),{callId:e(o.id),server:e(o.server_name)}))):l==="tool_result"||l==="mcp_tool_result"||/_tool_result$/.test(l)?(r(),C(t,e(o.tool_use_id),N(o.content),o.is_error===!0?"the tool reported an error":void 0)):l==="thinking"||l==="redacted_thinking"?(r(),t.call.turns.push({kind:"reasoning",...e(o.thinking)?{text:e(o.thinking)}:{}})):a.push(l==="image"?"image":l==="document"?`document ${e(o.title)??""}`.trim():l)}r()}v(Y,"se"),f(Y,"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 i=[],a=[];for(const l of k(s.content).map(u)){const c=e(l.type);c==="text"?i.push(e(l.text)??""):c==="tool_use"||c==="server_tool_use"||c==="mcp_tool_use"?n.toolCalls.push($(e(l.name)??"?",A(l.input),{callId:e(l.id),server:e(l.server_name)})):c==="thinking"&&a.push(e(l.thinking)??"")}i.length&&(n.text=i.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(L,"L"),k(L,"U"),_(L,"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)}L(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=>L(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 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"?D(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=u(s.error);e(r.message)&&(n.error=e(r.message));const o=u(s.usage);if(Object.keys(o).length){const l=y(o.input_tokens),c=y(o.cache_read_input_tokens),m=y(o.output_tokens);t.call.usage={...l!==void 0?{input:l+(c??0)+(y(o.cache_creation_input_tokens)??0)}:{},...c!==void 0?{cached:c}:{},...y(o.cache_creation_input_tokens)?{written:y(o.cache_creation_input_tokens)}:{},...q([["5m",u(o.cache_creation).ephemeral_5m_input_tokens],["1h",u(o.cache_creation).ephemeral_1h_input_tokens]]),...m!==void 0?{output:m}:{}}}}v(F,"W"),f(F,"anthropicAnswer");function ee(t,s,n){let i={};const a=new Map,r=new Map;let o={},l=0;for(const c of s){const m=J(c);if(!m)continue;m.cut&&l++;const d=m.v,_=e(d.type)??c.event,h=y(d.index)??0;if(_==="message_start")i=u(d.message),o={...u(i.usage)};else if(_==="content_block_start")a.set(h,{...u(d.content_block)});else if(_==="content_block_delta"){const p=u(d.delta),g=a.get(h)??{};e(p.text)!==void 0&&(g.text=(e(g.text)??"")+e(p.text)),e(p.thinking)!==void 0&&(g.thinking=(e(g.thinking)??"")+e(p.thinking)),e(p.partial_json)!==void 0&&r.set(h,(r.get(h)??"")+e(p.partial_json)),a.set(h,g)}else _==="message_delta"?(i={...i,...u(d.delta)},o={...o,...u(d.usage)}):_==="error"&&(t.call.answer.error=e(u(d.error).message)??"the stream reported an error")}for(const[c,m]of r){const d=a.get(c);d&&(d.input=parseJsonPrefix(m)?.value??m)}F(t,{...i,content:[...a.entries()].sort(([c],[m])=>c-m).map(([,c])=>c),usage:o}),l&&n.push(`${l} of the stream\u2019s events were kept to their first 4 KB \u2014 the answer was joined from what was kept of them.`)}v(ee,"oe"),f(ee,"anthropicStream");function te(t,s,n,i){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(u))e(o.text)&&a.system.push({source:"system",text:e(o.text)});for(const o of k(s.messages).map(u))Y(t,e(o.role)??"user",o.content);a.tools=[...k(s.tools).map(u).map(o=>{const l=e(o.name)??e(o.type)??"tool";return{name:l,...splitToolName(l),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(u).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=I(s,ce),T(t,n,i,o=>F(t,o),o=>ee(t,o,i))}v(te,"re"),f(te,"anthropicCall");function se(t,s,n,i){const a=t.call;e(s.model)&&(a.model=e(s.model));const r=s.input,o=typeof r=="string"?[r]:k(r),l=o.slice(0,200).map(p=>typeof p=="string"?p:typeof p=="number"?`token ${p}`:Array.isArray(p)?`${p.length} tokens`:A(p)),c=o.length>0&&o.every(p=>typeof p=="number");a.embedding={inputs:c?[`${o.length} tokens`]:l,count:c?1:o.length,...y(s.dimensions)!==void 0?{dimensions:y(s.dimensions)}:{}},a.settings=I(s,[["dimensions","dimensions"],["encoding_format","encoding"],["user","user"]]);const m=u(M(n.response.body,"answer",[])),d=k(m.data);if(d.length){a.embedding.vectors=d.length;const p=u(d[0]).embedding;Array.isArray(p)&&a.embedding.dimensions===void 0&&(a.embedding.dimensions=p.length)}const _=u(m.usage);y(_.prompt_tokens)!==void 0&&(a.usage={input:y(_.prompt_tokens),...y(_.total_tokens)!==void 0?{total:y(_.total_tokens)}:{}}),a.answer.status=n.status!==void 0&&n.status<400?"completed":"failed";const h=u(m.error);e(h.message)&&(a.answer.error=e(h.message))}v(se,"ae"),f(se,"embeddingsCall");function T(t,s,n,i,a){const r=s.response.stream;if(r){if(r.events.length&&r.events.every(l=>l.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 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)?i(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,"M"),f(T,"answerOf");function oe(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(oe,"ie"),f(oe,"shapeOf");export function aiCallOf(t){if(!t.ai)return;const s=aiApiOf(t.path);if(!s)return;const n=[],i={call:{provider:t.ai.provider,api:s,shape:"prompt",settings:[],system:[],turns:[],tools:[],answer:{toolCalls:[]},gaps:n},byCallId:new Map},a=u(M(t.request.body,"request",n));s==="responses"?Q(i,a,t,n):s==="chat"?X(i,a,t,n):s==="messages"?te(i,a,t,n):se(i,a,t,n);const r=i.call;if(r.answer.text!==void 0&&(r.answer.format?/json/.test(r.answer.format.type):/^\s*[{[]/.test(r.answer.text))){const c=parseJsonPrefix(r.answer.text);c&&(b(c.value)||Array.isArray(c.value))&&(r.answer.json=c.value)}!r.answer.finish&&r.answer.toolCalls.length&&(r.answer.finish="tool calls");const o=new Map;for(const c of r.turns)c.kind==="tool"&&o.set(c.name,(o.get(c.name)??0)+1);for(const c of r.answer.toolCalls)o.set(c.name,(o.get(c.name)??0)+1);for(const c of r.tools)c.called=o.get(c.name)??0;r.shape=oe(r);const l=ae(s,a,r.usage);l&&(r.cache=l);for(const c of r.system)c.text.endsWith(CUT_MARK)&&(c.cut=!0);return r}v(aiCallOf,"aiCallOf"),f(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"),f(prettyJson,"prettyJson");
@@ -0,0 +1,298 @@
1
+ import type { AiApi } from './ai-call.js';
2
+ import type { AiCallRow } from './ai-call-row.js';
3
+ import { type AiCacheMode } from './ai-cache.js';
4
+ import type { AiCacheTtl } from './ai-cache-facts.js';
5
+ import type { AiCacheRates } from './ai-cache-verdict.js';
6
+ /**
7
+ * Two sets of one agent's calls side by side (foodguard-301 E) — two runs, flows or time windows: «before» and «after».
8
+ * By arithmetic on what the lens kept, no model:
9
+ *
10
+ * - **the requests, diffed by bytes and by section.** The calls of one repetition of each side (its run or flow with
11
+ * the most calls) are matched — a prewarm to a prewarm; then by action (and the app's `part` / `group` label): one
12
+ * call each, by label; several, by the order they were sent; when the counts differ, by the longest prefix their
13
+ * requests share. A pair's requests are joined — each message's blocks as one text, in the order the provider reads
14
+ * them — and set side by side: the same bytes (the proof the «same bytes» risk class owes: «the new request, joined,
15
+ * is the old request byte for byte»), or the first character and UTF-8 byte where they part, the section it is in
16
+ * and each line there; the settings the model gets (the model, effort, format, temperature…) that differ; and each
17
+ * section's tokens on either side (estimated from the text, scaled to the provider's count);
18
+ * - **cost, time and output side by side**, per repetition: input as plain, read and written, output and its reasoning
19
+ * share, dollars from the price table (its source and read date), the stage's wall time and its slowest call;
20
+ * - **a noise floor** where a side holds more than one repetition: each measure's min–max and its dispersion (the
21
+ * standard deviation, and that over the mean), and a verdict per measure — `within` the floor or `beyond` it. One
22
+ * repetition a side has none, and says so: seven runs of one request proposed 11 to 23 changes (the issue's lesson);
23
+ * without a range, one run reads as a regression;
24
+ * - **a warning when the sides ran at different provider speeds**: the median output tokens a second differ by more
25
+ * than {@link AI_SPEED_SKEW} — then their times are not comparable.
26
+ *
27
+ * Every figure says what it rests on: `measured` (the provider's counts, the clock; dollars are those counts at the
28
+ * price table's rates) or `estimate` (tokens read from the text).
29
+ *
30
+ * Pure: run on the rows of the AI calls index and the request bodies of the calls it pairs ({@link aiCompareNeeds}
31
+ * names them), with the server's prices.
32
+ */
33
+ export type AiFigureBasis = 'measured' | 'estimate';
34
+ /** What one repetition of a side is: the calls of one run (`run.key`), or of one flow (`flowId`). */
35
+ export type AiCompareUnit = 'run' | 'flow';
36
+ /** A model's prices for a comparison, USD per million tokens: its cache rates and its output rate. */
37
+ export interface AiCompareRates extends AiCacheRates {
38
+ output: number;
39
+ }
40
+ export type AiCompareRatesOf = (model: string, inputTokens: number) => AiCompareRates | undefined;
41
+ /** The rows a comparison needs — what an index row carries. */
42
+ export type AiCompareRow = Pick<AiCallRow, 'id' | 'at' | 'durationMs' | 'api' | 'model' | 'tokens' | 'prewarm' | 'failed' | 'run' | 'flowId' | 'action' | 'meta' | 'cache'>;
43
+ export interface AiCompareSideIn {
44
+ /** «before», «after» — what the side is called. */
45
+ name: string;
46
+ /** How it was chosen, in words: «runs run:a, run:b», «17.11 08:00–09:00». */
47
+ said?: string;
48
+ rows: readonly AiCompareRow[];
49
+ unit: AiCompareUnit;
50
+ }
51
+ /** A request body as the caller read it — or why it could not. */
52
+ export type AiCompareRequest = {
53
+ body: unknown;
54
+ } | {
55
+ why: string;
56
+ };
57
+ export interface AiCompareInput {
58
+ a: AiCompareSideIn;
59
+ b: AiCompareSideIn;
60
+ ratesOf: AiCompareRatesOf;
61
+ /** The request bodies of the calls {@link aiCompareNeeds} names, by id: without them, the calls are matched by position and not diffed. */
62
+ requests?: ReadonlyMap<string, AiCompareRequest>;
63
+ }
64
+ export type AiCompareTokens = {
65
+ input: number;
66
+ /** Neither read from the cache nor written to it. */
67
+ plain: number;
68
+ read: number;
69
+ written: number;
70
+ writes?: Partial<Record<AiCacheTtl, number>>;
71
+ output: number;
72
+ reasoning: number;
73
+ };
74
+ export type AiCompareUsd = {
75
+ plain: number;
76
+ read: number;
77
+ written: number;
78
+ input: number;
79
+ output: number;
80
+ total: number;
81
+ };
82
+ /** One repetition of a side: a run's (or a flow's) calls, summed. */
83
+ export type AiCompareRun = {
84
+ key: string;
85
+ at: number;
86
+ /** Calls — a prewarm apart (`prewarms`): it writes the cache and answers nothing; its tokens are in the figures. */
87
+ calls: number;
88
+ prewarms: number;
89
+ failed: number;
90
+ /** Calls the provider's count was not kept for (a failed call, an answer the capture cut): in no token or dollar figure. */
91
+ uncounted: number;
92
+ tokens: AiCompareTokens;
93
+ /** Of the output, the reasoning's share (0–1). */
94
+ reasoningShare?: number;
95
+ /** Over its counted calls whose model has a price — `unpriced` of them had none. */
96
+ usd?: AiCompareUsd;
97
+ unpriced?: number;
98
+ /** From its first call's start to its last call's end — a prewarm included: the stage waits for it. */
99
+ wallMs?: number;
100
+ slowest?: {
101
+ id: string;
102
+ ms: number;
103
+ output?: number;
104
+ tokPerSec?: number;
105
+ };
106
+ /** The median of its calls' output tokens a second — over those that wrote at least {@link AI_SPEED_MIN_OUTPUT}. */
107
+ tokPerSec?: number;
108
+ };
109
+ export type AiComparePrice = {
110
+ model: string;
111
+ input: number;
112
+ output: number;
113
+ cacheRead?: number;
114
+ writes: Partial<Record<AiCacheTtl, number>>;
115
+ source?: string;
116
+ readAt?: string;
117
+ stale?: true;
118
+ };
119
+ export type AiCompareSide = {
120
+ name: string;
121
+ said?: string;
122
+ unit: AiCompareUnit;
123
+ /** Its repetitions, the earliest first (at most {@link AI_COMPARE_MAX_RUNS} listed; `moreRuns` beyond). */
124
+ runs: AiCompareRun[];
125
+ moreRuns?: number;
126
+ /** Its repetitions in all — what its noise floor is over. */
127
+ runCount: number;
128
+ /** The repetition whose requests were diffed: the one with the most calls, the earliest of those. */
129
+ diffed?: string;
130
+ models: string[];
131
+ /** The rates its dollars are at, by model — each with the page it was read from and the day. */
132
+ prices: AiComparePrice[];
133
+ /** Its calls' speeds, output tokens a second (calls that wrote at least {@link AI_SPEED_MIN_OUTPUT}): the median, and the range. */
134
+ speed?: {
135
+ median: number;
136
+ min: number;
137
+ max: number;
138
+ calls: number;
139
+ };
140
+ /** Its diffed repetition's prewarm: whether each answering call's request starts with the prewarm's, joined. */
141
+ prewarm?: {
142
+ id: string;
143
+ prefixOf: number;
144
+ of: number;
145
+ };
146
+ };
147
+ export type AiCompareMeasureKey = 'calls' | 'input' | 'plain' | 'read' | 'written' | 'output' | 'reasoningShare' | 'plainUsd' | 'readUsd' | 'writtenUsd' | 'inputUsd' | 'outputUsd' | 'totalUsd' | 'wallMs' | 'slowestMs' | 'tokPerSec';
148
+ export type AiCompareUnitOf = 'calls' | 'tokens' | 'share' | 'usd' | 'ms' | 'tok/s';
149
+ /** A measure's spread over a side's repetitions — its noise floor. */
150
+ export type AiCompareSpread = {
151
+ runs: number;
152
+ min: number;
153
+ max: number;
154
+ mean: number;
155
+ /** The sample standard deviation, and that over the mean. */
156
+ sd: number;
157
+ cv?: number;
158
+ };
159
+ export type AiCompareValue = {
160
+ /** The single repetition's value, or the mean over the side's repetitions. */
161
+ value?: number;
162
+ spread?: AiCompareSpread;
163
+ /** Over some of the side's calls only: the provider's count of the rest was not kept. */
164
+ partial?: true;
165
+ };
166
+ export type AiCompareNoise = 'within' | 'beyond' | 'none';
167
+ export type AiCompareMeasure = {
168
+ key: AiCompareMeasureKey;
169
+ label: string;
170
+ unit: AiCompareUnitOf;
171
+ basis: AiFigureBasis;
172
+ a: AiCompareValue;
173
+ b: AiCompareValue;
174
+ /** b − a, and that over a. */
175
+ delta?: number;
176
+ change?: number;
177
+ /** `none`: one repetition a side, no noise floor. */
178
+ noise: AiCompareNoise;
179
+ /** The sides ran at different provider speeds: this time is not comparable. */
180
+ speedSkew?: true;
181
+ said: string;
182
+ };
183
+ export type AiCompareMatch = 'label' | 'position' | 'prefix';
184
+ export type AiCompareSection = {
185
+ /** «user › Hazards, one per line…» — a section of a message, or the message whole. */
186
+ title: string;
187
+ a?: number;
188
+ b?: number;
189
+ delta: number;
190
+ state: 'changed' | 'only-a' | 'only-b';
191
+ };
192
+ export type AiComparePair = {
193
+ a?: string;
194
+ b?: string;
195
+ /** «ccp_determinator · 2 of 3», «prewarm». */
196
+ label: string;
197
+ /** A prewarm's pair: not in whether the answering calls' requests are the same bytes. */
198
+ prewarm?: true;
199
+ /** How the two were matched — none when one side has no call for it. */
200
+ match?: AiCompareMatch;
201
+ /** The joined requests are the same bytes and the model gets the same settings — undefined when a request was not read. */
202
+ same?: boolean;
203
+ /** Why the requests were not diffed. */
204
+ unread?: string;
205
+ /** The settings the model gets that differ (the model, effort, the answer's format, temperature…). */
206
+ settings?: string[];
207
+ /** Where the joined texts part: the character and UTF-8 byte, the section, the tokens before it (estimated), each side's line there. */
208
+ diff?: {
209
+ char: number;
210
+ byte: number;
211
+ region: string;
212
+ tokensBefore: number;
213
+ basis: 'estimate';
214
+ line?: string;
215
+ otherLine?: string;
216
+ };
217
+ /** How each side cut its request: blocks, breakpoints and cache mode — the same text cut otherwise is the same bytes. */
218
+ cut?: {
219
+ blocks: [number, number];
220
+ breakpoints: [number, number];
221
+ mode: [AiCacheMode, AiCacheMode];
222
+ };
223
+ /** The sections whose text differs, in the request's order, with their tokens (estimated, scaled to the provider's count). */
224
+ sections?: {
225
+ basis: 'estimate';
226
+ changed: AiCompareSection[];
227
+ more?: number;
228
+ same: number;
229
+ sameTokens: number;
230
+ };
231
+ /** The two calls' own figures (measured). */
232
+ input?: [number | null, number | null];
233
+ inputUsd?: [number | null, number | null];
234
+ output?: [number | null, number | null];
235
+ ms?: [number | null, number | null];
236
+ };
237
+ export type AiCompareRequests = {
238
+ /** How the calls were matched, in words. */
239
+ how: string;
240
+ pairs: AiComparePair[];
241
+ /** Every answering call of each diffed repetition has its match and the same bytes — undefined when a request was not read. */
242
+ identical?: boolean;
243
+ said: string;
244
+ };
245
+ export type AiCompareSpeed = {
246
+ a?: number;
247
+ b?: number;
248
+ /** The share the faster is above the slower. */
249
+ apart?: number;
250
+ /** Beyond {@link AI_SPEED_SKEW}: time is not comparable. */
251
+ differs: boolean;
252
+ threshold: number;
253
+ said: string;
254
+ };
255
+ export type AiComparison = {
256
+ a: AiCompareSide;
257
+ b: AiCompareSide;
258
+ measures: AiCompareMeasure[];
259
+ speed: AiCompareSpeed;
260
+ requests: AiCompareRequests;
261
+ /** The noise floor in a line: «one run a side: no noise floor», or each side's repetitions. */
262
+ noise: string;
263
+ warnings: string[];
264
+ /** What the figures do not cover. */
265
+ notVerified: string[];
266
+ };
267
+ /**
268
+ * Speeds this far apart (the faster over the slower) are different provider speeds. FoodGuard's same requests took
269
+ * 337 and 388 s in one morning — 15 % apart, the noise of one session — and 444 to 460 s that evening, 14 to 36 % slower
270
+ * (foodguard-301 § 4); a side's median over its calls is steadier than one call (38 to 60 tok/s in one run).
271
+ */
272
+ export declare const AI_SPEED_SKEW = 0.15;
273
+ /**
274
+ * A call's speed counts when it wrote at least this many tokens: its time is mostly writing. At ~50 tok/s that is 20 s
275
+ * or more, so the wait for the first token (a second or two on a 60k-token prompt) is under a tenth of it.
276
+ */
277
+ export declare const AI_SPEED_MIN_OUTPUT = 1000;
278
+ /** A diffed repetition's calls, at most — the earliest. */
279
+ export declare const AI_COMPARE_MAX_CALLS = 24;
280
+ /** A side's repetitions listed, at most — the floor is over all of them. */
281
+ export declare const AI_COMPARE_MAX_RUNS = 20;
282
+ /** A pair's changed sections listed, at most. */
283
+ export declare const AI_COMPARE_MAX_SECTIONS = 30;
284
+ /** The request joined: each message's blocks as one text, in the provider's order — and the settings the model gets. */
285
+ export declare function aiJoinedRequest(api: AiApi, body: unknown): {
286
+ settings: Record<string, string>;
287
+ segments: Array<{
288
+ label: string;
289
+ text: string;
290
+ }>;
291
+ } | undefined;
292
+ /**
293
+ * The calls whose request bodies the comparison diffs: the diffed repetition of each side (its run or flow with the most
294
+ * calls), at most {@link AI_COMPARE_MAX_CALLS} each — the earliest.
295
+ */
296
+ export declare function aiCompareNeeds(a: AiCompareSideIn, b: AiCompareSideIn): string[];
297
+ /** The two sets side by side — see the file's comment. */
298
+ export declare function aiCompare(input: AiCompareInput): AiComparison;