@lensmcp/protocol-types 1.26.9 → 1.26.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/index.d.ts +7 -0
- package/index.js +1 -1
- package/lib/ai-cache-facts.d.ts +69 -0
- package/lib/ai-cache-facts.js +1 -0
- package/lib/ai-cache-verdict.d.ts +112 -0
- package/lib/ai-cache-verdict.js +1 -0
- package/lib/ai-cache.d.ts +133 -0
- package/lib/ai-cache.js +4 -0
- package/lib/ai-call-groups.d.ts +2 -0
- package/lib/ai-call-groups.js +2 -2
- package/lib/ai-call-row.d.ts +44 -0
- package/lib/ai-call-row.js +3 -3
- package/lib/ai-call.d.ts +6 -0
- package/lib/ai-call.js +9 -9
- package/lib/ai-compare.d.ts +298 -0
- package/lib/ai-compare.js +4 -0
- package/lib/ai-together.d.ts +374 -0
- package/lib/ai-together.js +5 -0
- package/lib/dashboard-lint.d.ts +2 -0
- package/lib/dashboard-typecheck.d.ts +109 -0
- package/lib/dashboard-typecheck.js +1 -0
- package/lib/dashboard.d.ts +11 -0
- package/lib/finding-proof.d.ts +35 -0
- package/lib/finding-proof.js +1 -0
- package/package.json +1 -1
package/lib/ai-call-row.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
`).map(
|
|
3
|
-
`).map(
|
|
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
|
|
2
|
-
`||d==="\r"||d===" ")continue;const
|
|
3
|
-
\r `.includes(t[
|
|
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(
|
|
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",...
|
|
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
|
-
`);
|
|
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(
|
|
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]}:{}}),
|
|
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(s.stop_reason)&&(n.finish=e(s.stop_reason)),n.status=s.type==="error"?"failed":n.finish?"completed":n.status??"unknown";const r=
|
|
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;
|