@lensmcp/protocol-types 1.26.31 → 1.26.32
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/index.d.ts +1 -0
- package/index.js +1 -1
- package/lib/account-drain.d.ts +82 -0
- package/lib/account-drain.js +1 -0
- package/lib/ai-cache-facts.js +1 -1
- package/lib/ai-cache-verdict.js +1 -1
- package/lib/ai-cache.js +3 -3
- package/lib/ai-call-groups.js +2 -2
- package/lib/ai-call-row.js +3 -3
- package/lib/ai-call.js +9 -9
- package/lib/ai-compare.js +3 -3
- package/lib/ai-context.js +6 -6
- package/lib/ai-origins.js +9 -9
- package/lib/ai-together.js +5 -5
- package/lib/bounded-clone.js +1 -1
- package/lib/bounded-map.js +1 -1
- package/lib/bounded-writer.js +1 -1
- package/lib/canvas-attachments.js +1 -1
- package/lib/canvas-catalog.js +3 -3
- package/lib/canvas-chat.js +2 -2
- package/lib/canvas-editing.js +4 -4
- package/lib/canvas-frame-policy.js +1 -1
- package/lib/canvas-hub.js +1 -1
- package/lib/canvas.js +1 -1
- package/lib/capture-demand.js +1 -1
- package/lib/dashboard-path.js +1 -1
- package/lib/docker-errors.js +1 -1
- package/lib/docker-jobs.js +1 -1
- package/lib/docker-report.js +2 -2
- package/lib/docker-runs.js +3 -3
- package/lib/error-cause.js +6 -6
- package/lib/error-dismissal.js +1 -1
- package/lib/error-verdict.js +3 -3
- package/lib/event-loop.js +1 -1
- package/lib/expected-failure.js +2 -2
- package/lib/finding-proof.js +1 -1
- package/lib/flood-guard.js +1 -1
- package/lib/goal-design.js +1 -1
- package/lib/host-agents.js +1 -1
- package/lib/lens-hosts.js +1 -1
- package/lib/lint-coverage.js +1 -1
- package/lib/lint-ignores.js +2 -2
- package/lib/log-query.js +1 -1
- package/lib/metrics-reset.js +1 -1
- package/lib/overseer-findings.js +1 -1
- package/lib/peers.js +1 -1
- package/lib/perf-rules.js +1 -1
- package/lib/pod-memory.js +1 -1
- package/lib/producer-health.js +1 -1
- package/lib/remote-instances.js +1 -1
- package/lib/sources.js +1 -1
- package/lib/static-checks.js +1 -1
- package/lib/system-report.js +1 -1
- package/lib/team.d.ts +33 -1
- package/lib/team.js +1 -1
- package/package.json +1 -1
package/lib/ai-call.js
CHANGED
|
@@ -1,19 +1,19 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
`||d==="\r"||d===" ")continue;const h=
|
|
3
|
-
\r `.includes(
|
|
1
|
+
"use strict";var nt=Object.defineProperty;var v=(t,e)=>nt(t,"name",{value:e,configurable:!0});var rt=Object.defineProperty,f=v((t,e)=>rt(t,"name",{value:e,configurable:!0}),"d");import{aiCacheOf as at}from"./ai-cache.js";const b=f(t=>!!t&&typeof t=="object"&&!Array.isArray(t),"isObj"),s=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 z(t){const e={};for(const[n,i]of t)typeof i=="number"&&Number.isFinite(i)&&i>0&&(e[n]=i);return Object.keys(e).length?{writes:e}:{}}v(z,"K"),f(z,"writesOf");function E(t,e){const n=y(e.cache_write_tokens)??y(t.cache_write_tokens),i=u(e.cache_write_tokens_details??t.cache_write_tokens_details);return{...n?{written:n}:{},...z([["30m",i.ttl_30m_tokens],["12h",i.ttl_12h_tokens]])}}v(E,"z"),f(E,"openaiWrites");const I=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 e=[];let n=0,i=!1,a=!1,r=!1;const o=t.length,l=f(m=>{const d=e[e.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?e[e.length-1].state="colon":l(m+1));continue}if(d===" "||d===`
|
|
2
|
+
`||d==="\r"||d===" ")continue;const h=e[e.length-1];if(d==='"'){i=!0,a=!!h&&h.c==="{"&&h.state==="key";continue}if(d==="{"||d==="["){e.push({c:d,state:d==="{"?"key":"value"}),n=m+1;continue}if(d==="}"||d==="]"){e.pop(),l(m+1);continue}if(d===":"){h&&(h.state="value");continue}if(d===","){h&&(h.state=h.c==="{"?"key":"value");continue}let _=m;for(;_<o&&!`,}]
|
|
3
|
+
\r `.includes(t[_]);)_++;if(_>=o)break;l(_),m=_-1}const c=e.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 e=t.split("?")[0].replace(/\/+$/,"");if(/\/responses$/.test(e))return"responses";if(/\/chat\/completions$/.test(e))return"chat";if(/\/embeddings$/.test(e))return"embeddings";if(/\/messages$/.test(e))return"messages"}v(aiApiOf,"aiApiOf"),f(aiApiOf,"aiApiOf");export function splitToolName(t,e){if(e)return{server:e,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,e,n={})=>({...n.callId?{callId:n.callId}:{},name:t,...splitToolName(t,n.server),arguments:e,...n.output!==void 0?{output:n.output}:{},...n.error?{error:n.error}:{}}),"toolCall"),it=300*1e3,lt=f(t=>`${Math.floor(t/6e4)} min ${Math.round(t%6e4/1e3)} s`,"minutes");function T(t,e,n,i){if(!t)return;if(t.omitted==="ai"){n.push(`The ${e==="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 a=parseJsonPrefix(t.text);if(!a)return;const r=`read as far as it goes; what follows is not shown (the ${e==="request"?"end of the conversation":"rest of the answer"}, marked ${CUT_MARK}).`;if(t.cut==="time")n.push(`The ${e} was cut by the capture after its first ${I(t.kept)}: its read ran out of time (5 minutes from the answer\u2019s first byte, 30 for an AI call kept whole) \u2014 ${r}`);else if(t.cut==="broken")n.push(`The ${e} was cut after its first ${I(t.kept)}: the caller or the network ended it before its end \u2014 ${r}`);else if(a.cut&&!t.truncated){const o=e==="answer"&&i!==void 0&&i>it?` \u2014 its first byte came ${lt(i)} after the call, past the 5 minutes a capture before 2026-11-22 read an answer for, counted from the call\u2019s start`:"";n.push(`The ${e} was cut by the capture after its first ${I(t.kept)}${o} \u2014 ${r}`)}else(a.cut||t.truncated)&&n.push(`The ${e} was kept to its first ${I(t.kept)} of ${I(t.size)} \u2014 ${r}`);return a.value}v(T,"M"),f(T,"readBody");function J(t){if(t.data===void 0||t.data==="[DONE]")return;const e=parseJsonPrefix(t.data);return e&&b(e.value)?{v:e.value,cut:e.cut}:void 0}v(J,"E"),f(J,"eventJson");function O(t){if(typeof t=="string")return{text:t,attachments:[]};const e=[],n=[];for(const i of k(t)){if(typeof i=="string"){e.push(i);continue}const a=u(i),r=s(a.type)??"",o=s(a.text)??s(a.refusal);o!==void 0?e.push(o):/image/.test(r)?n.push(s(a.detail)?`image (${s(a.detail)})`:"image"):/file|document/.test(r)?n.push(`file ${s(a.filename)??s(u(a.source).media_type)??s(a.file_id)??""}`.trim()):/audio/.test(r)?n.push("audio"):r&&n.push(r)}return{text:e.join(`
|
|
4
4
|
|
|
5
|
-
`),attachments:n}}v(
|
|
5
|
+
`),attachments:n}}v(O,"O"),f(O,"contentOf");const N=f(t=>typeof t=="string"?t:Array.isArray(t)&&O(t).text||A(t),"outputOf");function C(t,e){const n=[];for(const[a,r]of e){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)&&s(o.name)?`${s(o.type)??"tool"} ${s(o.name)}`:b(o)&&s(o.type)?s(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(C,"T"),f(C,"settingsOf");function S(t,e,n,i){const a=e?t.byCallId.get(e):void 0;if(a){a.output=n,i&&(a.error=i);return}t.call.turns.push({kind:"tool",...$("(an earlier call)","",{callId:e,output:n,error:i})})}v(S,"B"),f(S,"addOutput");function j(t,e){const n={kind:"tool",...e};t.call.turns.push(n),e.callId&&t.byCallId.set(e.callId,n)}v(j,"S"),f(j,"addCall");const ct=[["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(([e])=>e!=="type"&&e!=="id"&&e!=="status"))),"builtInCall");function H(t,e){const n=s(e.type)??(e.role?"message":"");if(n==="message"){const i=s(e.role)??"user",{text:a,attachments:r}=O(e.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,$(s(e.name)??"?",s(e.arguments)??A(e.input),{callId:s(e.call_id)}));else if(n==="function_call_output"||n==="custom_tool_call_output"||n==="computer_call_output"||n==="local_shell_call_output")S(t,s(e.call_id),N(e.output));else if(n==="mcp_call")j(t,$(s(e.name)??"?",s(e.arguments)??"",{callId:s(e.id),server:s(e.server_label),...e.output!==void 0&&e.output!==null?{output:N(e.output)}:{},error:s(e.error)}));else if(n==="mcp_list_tools"){const i=k(e.tools).map(a=>s(u(a).name)).filter(Boolean);j(t,$("list_tools","",{server:s(e.server_label),output:i.join(", ")}))}else if(n==="reasoning"){const i=k(e.summary).map(a=>s(u(a).text)).filter(Boolean).join(`
|
|
6
6
|
|
|
7
|
-
`);
|
|
7
|
+
`);t.call.turns.push({kind:"reasoning",...i?{text:i}:{}})}else n&&j(t,$(n.replace(/_call$/,""),D(e),{callId:s(e.call_id)??s(e.id)}))}v(H,"V"),f(H,"responsesItem");function R(t){return k(t.tools).map(e=>{const n=u(e),i=s(n.type)??"function";if(i==="mcp"){const r=s(n.server_label)??"mcp",o=k(n.allowed_tools).map(l=>s(l)).filter(Boolean);return{name:r,server:r,tool:o.length?o.join(", "):"every tool",type:i,...s(n.server_description)??s(n.server_url)?{description:s(n.server_description)??s(n.server_url)}:{},called:0}}const a=s(n.name)??i;return{name:a,...splitToolName(a),type:i,...s(n.description)?{description:s(n.description)}:{},...n.parameters!==void 0?{parameters:n.parameters}:{},...typeof n.strict=="boolean"?{strict:n.strict}:{},called:0}})}v(R,"X"),f(R,"responsesTools");function K(t,e){const n=t.call.answer;s(e.status)&&(n.status=s(e.status));const i=s(u(e.incomplete_details).reason);i&&(n.finish=i);const a=u(e.error);s(a.message)&&(n.error=s(a.message)),s(e.model)&&(t.call.model??=s(e.model)),s(e.id)&&(t.call.responseId=s(e.id)),L(t,k(e.output).map(u));const r=u(e.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,"G"),f(K,"responsesAnswer");function L(t,e){const n=t.call.answer,i=[],a=[];for(const r of e){const o=s(r.type);if(o==="message")for(const l of k(r.content).map(u))s(l.refusal)?n.refusal=s(l.refusal):s(l.text)!==void 0&&i.push(s(l.text));else if(o==="function_call"||o==="custom_tool_call")n.toolCalls.push($(s(r.name)??"?",s(r.arguments)??A(r.input),{callId:s(r.call_id)}));else if(o==="mcp_call")n.toolCalls.push($(s(r.name)??"?",s(r.arguments)??"",{callId:s(r.id),server:s(r.server_label),...r.output!==void 0&&r.output!==null?{output:N(r.output)}:{},error:s(r.error)}));else if(o==="reasoning"){const l=k(r.summary).map(c=>s(u(c).text)).filter(Boolean).join(`
|
|
8
8
|
|
|
9
|
-
`);l&&a.push(l)}else o&&o!=="mcp_list_tools"&&n.toolCalls.push(
|
|
9
|
+
`);l&&a.push(l)}else o&&o!=="mcp_list_tools"&&n.toolCalls.push($(o.replace(/_call$/,""),D(r),{callId:s(r.call_id)??s(r.id)}))}i.length&&(n.text=i.join(`
|
|
10
10
|
|
|
11
11
|
`)),a.length&&(n.reasoning=a.join(`
|
|
12
12
|
|
|
13
|
-
`))}v(
|
|
13
|
+
`))}v(L,"D"),f(L,"responsesOutput");function G(t,e,n){let i,a=0;const r=new Map,o=new Set,l=new Map,c=new Map,m=new Map;for(const h of e){const _=J(h);if(!_)continue;_.cut&&a++;const p=_.v,g=s(p.type)??h.event,w=y(p.output_index)??0;if(g==="response.completed"||g==="response.incomplete"||g==="response.failed"){if(!_.cut&&b(p.response))i=p.response;else if(b(p.response)){const x=p.response;s(x.status)&&(t.call.answer.status=s(x.status))}}else if(g==="response.created"||g==="response.in_progress"){const x=u(p.response);s(x.model)&&(t.call.model??=s(x.model)),s(x.id)&&(t.call.responseId??=s(x.id))}else g==="response.output_item.added"||g==="response.output_item.done"?b(p.item)&&(!o.has(w)||!_.cut)&&(r.set(w,{...r.get(w)??{},...p.item}),g.endsWith(".done")&&!_.cut&&o.add(w)):g==="response.output_text.delta"||g==="response.refusal.delta"?l.set(w,(l.get(w)??"")+(s(p.delta)??"")):g==="response.output_text.done"&&!_.cut&&s(p.text)!==void 0?l.set(w,s(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)??"")+(s(p.delta)??"")):(g==="response.function_call_arguments.done"||g==="response.mcp_call_arguments.done")&&!_.cut&&s(p.arguments)!==void 0?c.set(w,s(p.arguments)):g==="response.reasoning_summary_text.delta"?m.set(w,(m.get(w)??"")+(s(p.delta)??"")):(g==="error"||g==="response.error")&&(t.call.answer.error=s(p.message)??s(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(h))return _;const p=s(_.type);return p==="message"&&l.has(h)?{..._,content:[{type:"output_text",text:l.get(h)}]}:(p==="function_call"||p==="mcp_call")&&c.has(h)?{..._,arguments:c.get(h)}:p==="custom_tool_call"&&c.has(h)?{..._,input:c.get(h)}:p==="reasoning"&&m.has(h)?{..._,summary:[{type:"summary_text",text:m.get(h)}]}:_});for(const[h,_]of l)r.has(h)||d.push({type:"message",content:[{type:"output_text",text:_}]});L(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,"Y"),f(G,"responsesStream");function Q(t,e,n,i){const a=t.call;s(e.model)&&(a.model=s(e.model)),s(e.instructions)&&a.system.push({source:"instructions",text:s(e.instructions)});const r=e.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(e),a.settings=C(e,ct);const o=u(u(e.text).format);s(o.type)&&o.type!=="text"&&(a.answer.format={type:s(o.type),...s(o.name)?{name:s(o.name)}:{},...o.schema!==void 0?{schema:o.schema}:{},...typeof o.strict=="boolean"?{strict:o.strict}:{}}),q(t,n,i,l=>K(t,l),l=>G(t,l,i))}v(Q,"ee"),f(Q,"responsesCall");const ut=[["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 P(t){const e=k(t.tool_calls).map(u).map(i=>{const a=u(i.function);return $(s(a.name)??s(u(i.custom).name)??"?",s(a.arguments)??s(u(i.custom).input)??"",{callId:s(i.id)})}),n=u(t.function_call);return s(n.name)&&e.push($(s(n.name),s(n.arguments)??"",{})),e}v(P,"F"),f(P,"chatCalls");function F(t,e){const n=t.call.answer;s(e.model)&&(t.call.model??=s(e.model)),s(e.id)&&(t.call.responseId??=s(e.id));const i=u(k(e.choices)[0]),a=u(i.message),r=O(a.content).text;r&&(n.text=r),s(a.refusal)&&(n.refusal=s(a.refusal));const o=s(a.reasoning_content)??s(a.reasoning);o&&(n.reasoning=o),n.toolCalls.push(...P(a)),s(i.finish_reason)&&(n.finish=s(i.finish_reason)),n.status=n.finish?"completed":n.status??"unknown";const l=u(e.error);s(l.message)&&(n.error=s(l.message));const c=u(e.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(F,"P"),f(F,"chatAnswer");function V(t,e,n){let i="",a="",r="",o,l,c,m,d=0;const h=new Map;for(const p of e){const g=J(p);if(!g)continue;g.cut&&d++,c??=s(g.v.model),m??=s(g.v.id),b(g.v.usage)&&(l=g.v.usage),b(g.v.error)&&(t.call.answer.error=s(g.v.error.message)??"the stream reported an error");const w=u(k(g.v.choices)[0]),x=u(w.delta);i+=s(x.content)??"",a+=s(x.reasoning_content)??s(x.reasoning)??"",r+=s(x.refusal)??"";for(const B of k(x.tool_calls).map(u)){const W=y(B.index)??0,M=h.get(W)??{name:"",args:""},Z=u(B.function);s(B.id)&&(M.id=s(B.id)),M.name+=s(Z.name)??"",M.args+=s(Z.arguments)??"",h.set(W,M)}s(w.finish_reason)&&(o=s(w.finish_reason))}const _={content:i,...a?{reasoning_content:a}:{},...r?{refusal:r}:{},tool_calls:[...h.entries()].sort(([p],[g])=>p-g).map(([,p])=>({id:p.id,function:{name:p.name,arguments:p.args}}))};F(t,{...c?{model:c}:{},...m?{id:m}:{},choices:[{message:_,...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,"ne"),f(V,"chatStream");function X(t,e,n,i){const a=t.call;s(e.model)&&(a.model=s(e.model));for(const o of k(e.messages).map(u)){const l=s(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")S(t,s(o.tool_call_id),c);else if(l==="function")S(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 P(o))j(t,d)}}a.tools=[...k(e.tools).map(u),...k(e.functions).map(o=>({type:"function",function:o}))].map(o=>{const l=u(o.function),c=s(o.type)??"function",m=s(l.name)??s(u(o.custom).name)??c;return{name:m,...splitToolName(m),type:c,...s(l.description)??s(u(o.custom).description)?{description:s(l.description)??s(u(o.custom).description)}:{},...l.parameters!==void 0?{parameters:l.parameters}:{},...typeof l.strict=="boolean"?{strict:l.strict}:{},called:0}}),a.settings=C(e,ut);const r=u(e.response_format);if(s(r.type)&&r.type!=="text"){const o=u(r.json_schema);a.answer.format={type:s(r.type),...s(o.name)?{name:s(o.name)}:{},...o.schema!==void 0?{schema:o.schema}:{},...typeof o.strict=="boolean"?{strict:o.strict}:{}}}q(t,n,i,o=>F(t,o),o=>V(t,o,i))}v(X,"se"),f(X,"chatCall");const pt=[["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,e,n){if(typeof n=="string"){t.call.turns.push({kind:"message",role:e,text:n});return}const i=[],a=[],r=f(()=>{(i.length||a.length)&&t.call.turns.push({kind:"message",role:e,text:i.join(`
|
|
14
14
|
|
|
15
|
-
`),...a.length?{attachments:[...a]}:{}}),i.length=0,a.length=0},"flush");for(const o of
|
|
15
|
+
`),...a.length?{attachments:[...a]}:{}}),i.length=0,a.length=0},"flush");for(const o of k(n).map(u)){const l=s(o.type)??"";l==="text"?i.push(s(o.text)??""):l==="tool_use"||l==="server_tool_use"||l==="mcp_tool_use"?(r(),j(t,$(s(o.name)??"?",A(o.input),{callId:s(o.id),server:s(o.server_name)}))):l==="tool_result"||l==="mcp_tool_result"||/_tool_result$/.test(l)?(r(),S(t,s(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",...s(o.thinking)?{text:s(o.thinking)}:{}})):a.push(l==="image"?"image":l==="document"?`document ${s(o.title)??""}`.trim():l)}r()}v(Y,"re"),f(Y,"anthropicBlocks");function U(t,e){const n=t.call.answer;s(e.model)&&(t.call.model??=s(e.model)),s(e.id)&&(t.call.responseId??=s(e.id));const i=[],a=[];for(const l of k(e.content).map(u)){const c=s(l.type);c==="text"?i.push(s(l.text)??""):c==="tool_use"||c==="server_tool_use"||c==="mcp_tool_use"?n.toolCalls.push($(s(l.name)??"?",A(l.input),{callId:s(l.id),server:s(l.server_name)})):c==="thinking"&&a.push(s(l.thinking)??"")}i.length&&(n.text=i.join(`
|
|
16
16
|
|
|
17
17
|
`)),a.length&&(n.reasoning=a.join(`
|
|
18
18
|
|
|
19
|
-
`)),s(
|
|
19
|
+
`)),s(e.stop_reason)&&(n.finish=s(e.stop_reason)),n.status=e.type==="error"?"failed":n.finish?"completed":n.status??"unknown";const r=u(e.error);s(r.message)&&(n.error=s(r.message));const o=u(e.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)}:{},...z([["5m",u(o.cache_creation).ephemeral_5m_input_tokens],["1h",u(o.cache_creation).ephemeral_1h_input_tokens]]),...m!==void 0?{output:m}:{}}}}v(U,"R"),f(U,"anthropicAnswer");function tt(t,e,n){let i={};const a=new Map,r=new Map;let o={},l=0;for(const c of e){const m=J(c);if(!m)continue;m.cut&&l++;const d=m.v,h=s(d.type)??c.event,_=y(d.index)??0;if(h==="message_start")i=u(d.message),o={...u(i.usage)};else if(h==="content_block_start")a.set(_,{...u(d.content_block)});else if(h==="content_block_delta"){const p=u(d.delta),g=a.get(_)??{};s(p.text)!==void 0&&(g.text=(s(g.text)??"")+s(p.text)),s(p.thinking)!==void 0&&(g.thinking=(s(g.thinking)??"")+s(p.thinking)),s(p.partial_json)!==void 0&&r.set(_,(r.get(_)??"")+s(p.partial_json)),a.set(_,g)}else h==="message_delta"?(i={...i,...u(d.delta)},o={...o,...u(d.usage)}):h==="error"&&(t.call.answer.error=s(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)}U(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(tt,"ae"),f(tt,"anthropicStream");function et(t,e,n,i){const a=t.call;s(e.model)&&(a.model=s(e.model));const r=e.system;if(typeof r=="string"&&r)a.system.push({source:"system",text:r});else for(const o of k(r).map(u))s(o.text)&&a.system.push({source:"system",text:s(o.text)});for(const o of k(e.messages).map(u))Y(t,s(o.role)??"user",o.content);a.tools=[...k(e.tools).map(u).map(o=>{const l=s(o.name)??s(o.type)??"tool";return{name:l,...splitToolName(l),type:s(o.type)??"custom",...s(o.description)?{description:s(o.description)}:{},...o.input_schema!==void 0?{parameters:o.input_schema}:{},called:0}}),...k(e.mcp_servers).map(u).map(o=>({name:s(o.name)??"mcp",server:s(o.name)??"mcp",tool:"every tool",type:"mcp",...s(o.url)?{description:s(o.url)}:{},called:0}))],a.settings=C(e,pt),q(t,n,i,o=>U(t,o),o=>tt(t,o,i))}v(et,"ie"),f(et,"anthropicCall");function st(t,e,n,i){const a=t.call;s(e.model)&&(a.model=s(e.model));const r=e.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(e.dimensions)!==void 0?{dimensions:y(e.dimensions)}:{}},a.settings=C(e,[["dimensions","dimensions"],["encoding_format","encoding"],["user","user"]]);const m=u(T(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 h=u(m.usage);y(h.prompt_tokens)!==void 0&&(a.usage={input:y(h.prompt_tokens),...y(h.total_tokens)!==void 0?{total:y(h.total_tokens)}:{}}),a.answer.status=n.status!==void 0&&n.status<400?"completed":"failed";const _=u(m.error);s(_.message)&&(a.answer.error=s(_.message))}v(st,"le"),f(st,"embeddingsCall");function q(t,e,n,i,a){const r=e.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}if(a(r.events),r.cut){const l=r.cutBy==="time"?": its read ran out of time (5 minutes from the first byte, 30 for an AI call kept whole)":r.cutBy==="broken"?": the caller or the network ended it":r.cutBy==="size"?": past what a stream keeps":"";n.push(`The stream was cut after ${r.events.length.toLocaleString("en-US")} of its ${r.total.toLocaleString("en-US")} events${l} \u2014 what came after is not shown.`)}return}const o=T(e.response.body,"answer",n,e.ttfbMs);b(o)?i(o):e.error&&(t.call.answer.error=e.error),t.call.answer.status||(t.call.answer.status=e.error||(e.status??0)>=400?"failed":"unknown")}v(q,"N"),f(q,"answerOf");function ot(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(e=>e.kind==="tool")?"tools":t.turns.filter(e=>e.kind==="message"&&(e.role==="user"||e.role==="assistant")).length>1?"chat":"prompt"}v(ot,"ce"),f(ot,"shapeOf");export function aiCallOf(t){if(!t.ai)return;const e=aiApiOf(t.path);if(!e)return;const n=[],i={call:{provider:t.ai.provider,api:e,shape:"prompt",settings:[],system:[],turns:[],tools:[],answer:{toolCalls:[]},gaps:n},byCallId:new Map},a=u(T(t.request.body,"request",n));e==="responses"?Q(i,a,t,n):e==="chat"?X(i,a,t,n):e==="messages"?et(i,a,t,n):st(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=ot(r);const l=at(e,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 e=t.trim()?parseJsonPrefix(t):void 0;return e&&(b(e.value)||Array.isArray(e.value))?{value:e.value,text:t}:{text:t}}v(prettyJson,"prettyJson"),f(prettyJson,"prettyJson");
|
package/lib/ai-compare.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var ke=Object.defineProperty;var k=(e,t)=>ke(e,"name",{value:t,configurable:!0});var ve=Object.defineProperty,r=k((e,t)=>ve(e,"name",{value:t,configurable:!0}),"r");import{aiCacheRequestOf as xe,aiCacheSections as ae}from"./ai-cache.js";import{estimateTokens as ye}from"./ai-context.js";export const AI_SPEED_SKEW=.15,AI_SPEED_MIN_OUTPUT=1e3,AI_COMPARE_MAX_CALLS=24,AI_COMPARE_MAX_RUNS=20,AI_COMPARE_MAX_SECTIONS=30;const ie=200,V=r(e=>Math.round(e).toLocaleString("en-US"),"fmt"),C=r(e=>Math.round(e*1e6)/1e6,"usd"),Me=r(e=>{const t=Math.abs(e);return`$${t===0?"0":t<.001?Number(e.toPrecision(2)).toString():t<.01?e.toFixed(4):e.toFixed(3)}`},"money"),Oe=r(e=>e>=9?`\xD7${Math.round(e+1).toLocaleString("en-US")}`:`${e>0?"+":e<0?"\u2212":""}${Math.abs(Math.round(e*100))}%`,"pct"),je=r(e=>e<1e3?`${Math.round(e)} ms`:`${(e/1e3).toFixed(e<1e4?1:0)} s`,"secs"),J=r(e=>Math.round(e*1e3)/1e3,"round3");function G(e,t){return t==="usd"?Me(e):t==="ms"?je(e):t==="share"?`${Math.round(e*100)}%`:t==="tok/s"?`${e.toFixed(1)} tok/s`:V(e)}k(G,"G"),r(G,"show");const Se=r((e,t)=>e.at-t.at||e.id.localeCompare(t.id),"byTime"),Ae=r(e=>e.tokens?.input!==void 0,"counted");function H(e){const t=new Map;for(const n of e.rows){const s=e.unit==="flow"?n.flowId??"(no flow)":n.run.key,a=t.get(s);a?a.push(n):t.set(s,[n])}return[...t].map(([n,s])=>({key:n,rows:s.sort(Se)})).sort((n,s)=>n.rows[0].at-s.rows[0].at||n.key.localeCompare(s.key))}k(H,"H"),r(H,"repetitionsOf");function D(e){let t;const n=r(s=>s.rows.filter(a=>!a.prewarm).length,"answering");for(const s of e)(!t||n(s)>n(t))&&(t=s);return t}k(D,"V"),r(D,"diffedOf");function Q(e){const t=e.tokens?.written??0;if(!t)return{};const n=e.cache?.writes,s=n?Object.values(n).reduce((c,u)=>c+(u??0),0):0;if(n&&s>=t)return{...n};const a=e.cache?.ttl??"30m";return{...n??{},[a]:(n?.[a]??0)+t-s}}k(Q,"ee"),r(Q,"writesOf");function Z(e,t){const n=e.tokens;if(!n||n.input===void 0||!e.model)return;const s=t(e.model,n.input);if(!s)return;const a=n.cached??0,c=n.written??0,u=Math.max(0,n.input-a-c);let d=0;for(const[b,O]of Object.entries(Q(e)))d+=O*(s.writes[b]??s.input);const l={plain:u*s.input/1e6,read:a*(s.cacheRead??s.input)/1e6,written:d/1e6,output:(n.output??0)*s.output/1e6},i=l.plain+l.read+l.written;return{...l,input:i,total:i+l.output}}k(Z,"te"),r(Z,"callUsd");const _e=r(e=>({plain:C(e.plain),read:C(e.read),written:C(e.written),input:C(e.input),output:C(e.output),total:C(e.total)}),"usdOut"),re=r(e=>!e.prewarm&&e.durationMs&&e.durationMs>0&&(e.tokens?.output??0)>=AI_SPEED_MIN_OUTPUT?e.tokens.output/e.durationMs*1e3:void 0,"speedOf"),le=r(e=>{if(!e.length)return;const t=[...e].sort((s,a)=>s-a),n=Math.floor(t.length/2);return t.length%2?t[n]:(t[n-1]+t[n])/2},"median");function ee(e,t,n){const s={input:0,plain:0,read:0,written:0,output:0,reasoning:0},a={};let c,u=0,d=0;for(const m of t){if(!Ae(m)){d++;continue}const w=m.tokens;s.input+=w.input,s.read+=w.cached??0,s.written+=w.written??0,s.plain+=Math.max(0,w.input-(w.cached??0)-(w.written??0)),s.output+=w.output??0,s.reasoning+=w.reasoning??0;for(const[h,f]of Object.entries(Q(m)))a[h]=(a[h]??0)+f;const $=Z(m,n);if(!$){u++;continue}c=c?{plain:c.plain+$.plain,read:c.read+$.read,written:c.written+$.written,input:c.input+$.input,output:c.output+$.output,total:c.total+$.total}:$}Object.keys(a).length&&(s.writes=a);const l=t.filter(m=>m.durationMs!==void 0),i=t.filter(m=>!m.prewarm),b=i.filter(m=>m.durationMs!==void 0).reduce((m,w)=>!m||w.durationMs>m.durationMs?w:m,void 0),O=b?.durationMs&&b.tokens?.output!==void 0?b.tokens.output/b.durationMs*1e3:void 0,x=le(i.map(re).filter(m=>m!==void 0));return{key:e,at:t[0].at,calls:i.length,prewarms:t.length-i.length,failed:t.filter(m=>m.failed).length,uncounted:d,tokens:s,...s.output?{reasoningShare:J(s.reasoning/s.output)}:{},...c?{usd:_e(c)}:{},...u?{unpriced:u}:{},...l.length?{wallMs:Math.max(...l.map(m=>m.at+m.durationMs))-t[0].at}:{},...b?{slowest:{id:b.id,ms:b.durationMs,...b.tokens?.output!==void 0?{output:b.tokens.output}:{},...O!==void 0?{tokPerSec:Math.round(O*10)/10}:{}}}:{},...x!==void 0?{tokPerSec:Math.round(x*10)/10}:{}}}k(ee,"oe"),r(ee,"runOf");const Be=[{key:"calls",label:"calls (a prewarm apart)",unit:"calls",of:r(e=>e.calls,"of")},{key:"input",label:"input tokens",unit:"tokens",of:r(e=>e.tokens.input,"of"),counts:!0},{key:"plain",label:"input, plain (neither read nor written)",unit:"tokens",of:r(e=>e.tokens.plain,"of"),counts:!0},{key:"read",label:"input, read from the cache",unit:"tokens",of:r(e=>e.tokens.read,"of"),counts:!0},{key:"written",label:"input, written to the cache",unit:"tokens",of:r(e=>e.tokens.written,"of"),counts:!0},{key:"output",label:"output tokens",unit:"tokens",of:r(e=>e.tokens.output,"of"),counts:!0},{key:"reasoningShare",label:"reasoning share of the output",unit:"share",of:r(e=>e.reasoningShare,"of"),counts:!0},{key:"plainUsd",label:"input $, plain",unit:"usd",of:r(e=>e.usd?.plain,"of"),counts:!0},{key:"readUsd",label:"input $, read",unit:"usd",of:r(e=>e.usd?.read,"of"),counts:!0},{key:"writtenUsd",label:"input $, written",unit:"usd",of:r(e=>e.usd?.written,"of"),counts:!0},{key:"inputUsd",label:"input $",unit:"usd",of:r(e=>e.usd?.input,"of"),counts:!0},{key:"outputUsd",label:"output $",unit:"usd",of:r(e=>e.usd?.output,"of"),counts:!0},{key:"totalUsd",label:"total $",unit:"usd",of:r(e=>e.usd?.total,"of"),counts:!0},{key:"wallMs",label:"the stage\u2019s wall time",unit:"ms",of:r(e=>e.wallMs,"of")},{key:"slowestMs",label:"its slowest call",unit:"ms",of:r(e=>e.slowest?.ms,"of")},{key:"tokPerSec",label:"provider speed (median output tokens a second)",unit:"tok/s",of:r(e=>e.tokPerSec,"of")}];function te(e,t){const n=e.map(t.of).filter(u=>typeof u=="number"&&Number.isFinite(u)),s=t.counts&&e.some(u=>u.uncounted>0||t.unit==="usd"&&(u.unpriced??0)>0);if(!n.length)return s?{partial:!0}:{};const a=n.reduce((u,d)=>u+d,0)/n.length,c={value:t.unit==="usd"?C(a):t.unit==="share"?J(a):Math.round(a*10)/10,...s?{partial:!0}:{}};if(n.length>=2){const u=Math.sqrt(n.reduce((l,i)=>l+(i-a)**2,0)/(n.length-1)),d=r(l=>t.unit==="usd"?C(l):t.unit==="share"?J(l):Math.round(l*10)/10,"r");c.spread={runs:n.length,min:d(Math.min(...n)),max:d(Math.max(...n)),mean:d(a),sd:d(u),...a?{cv:J(u/Math.abs(a))}:{}}}return c}k(te,"ae"),r(te,"valueOf");function ue(e,t){if(!e.spread&&!t.spread)return"none";if(e.spread&&t.spread)return e.spread.max<t.spread.min||t.spread.max<e.spread.min?"beyond":"within";const n=e.spread??t.spread,s=e.spread?t.value:e.value;return s===void 0?"none":s<n.min||s>n.max?"beyond":"within"}k(ue,"Me"),r(ue,"noiseOf");function de(e,t,n,s,a,c){const u=te(s,e),d=te(a,e),l=ue(u,d),i=u.value!==void 0&&d.value!==void 0?d.value-u.value:void 0,b=i!==void 0&&u.value?J(i/u.value):void 0,O=e.unit==="ms",x=r((h,f)=>f.value===void 0?`${h.name} \u2014`:`${h.name} ${G(f.value,e.unit)}${f.spread?` (${G(f.spread.min,e.unit)}\u2013${G(f.spread.max,e.unit)} over ${f.spread.runs})`:""}`,"side"),m=l==="none"?u.value===void 0||d.value===void 0?"nothing to compare":"one run a side: no noise floor":l==="beyond"?"beyond noise":"within noise",w=u.partial||d.partial?` \u2014 over the counted calls only (${[u.partial?t.name:"",d.partial?n.name:""].filter(Boolean).join(", ")})`:"",$=`${e.label}: ${x(t,u)} \u2192 ${x(n,d)}${b!==void 0&&i?` (${Oe(b)})`:""} \u2014 ${m}${w}`+(O&&c?" \u2014 the sides ran at different provider speeds: time is not comparable":"");return{key:e.key,label:e.label,unit:e.unit,basis:"measured",a:u,b:d,...i!==void 0?{delta:e.unit==="usd"?C(i):e.unit==="share"?J(i):Math.round(i*10)/10}:{},...b!==void 0?{change:b}:{},noise:l,...O&&c?{speedSkew:!0}:{},said:$}}k(de,"xe"),r(de,"measureOf");const qe=["temperature","top_p","top_k","max_output_tokens","max_tokens","max_completion_tokens","seed","stop","stop_sequences","tool_choice","frequency_penalty","presence_penalty","truncation","n"],Ne=new Set(["prompt_cache_key"]),Ce=/^(.*) · block (\d+) of \d+$/;export function aiJoinedRequest(e,t){const n=ne(e,t);return n?{settings:n.settings,segments:n.segments}:void 0}k(aiJoinedRequest,"aiJoinedRequest"),r(aiJoinedRequest,"aiJoinedRequest");function ne(e,t){const n=xe(e,t);if(!n)return;const s=[];for(const d of n.blocks){const l=Ce.exec(d.label),i=l?l[1]:d.label,b=s[s.length-1];l&&Number(l[2])>1&&b?.label===i?b.text+=d.text:s.push({label:i,text:d.text})}const a={},c=JSON.parse(n.settings);for(const[d,l]of Object.entries(c))!Ne.has(d)&&l!==void 0&&(a[d]=JSON.stringify(l));const u=t;for(const d of qe)u[d]!==void 0&&(a[d]=JSON.stringify(u[d]));return{settings:a,segments:s,flat:s.map(d=>`\0${d.label}${d.text}`).join(""),chars:s.reduce((d,l)=>d+l.text.length,0),blocks:n.blocks.length,breakpoints:n.blocks.filter(d=>d.bp).length,mode:n.mode}}k(ne,"ie"),r(ne,"joinedOf");function ce(e,t){let n=0;for(let s=0;s<t;s++){const a=e.charCodeAt(s);a<128?n+=1:a<2048?n+=2:a>=55296&&a<=56319&&s+1<t?(n+=4,s++):n+=3}return n}k(ce,"ve"),r(ce,"utf8");const he=r((e,t)=>{const n=e.lastIndexOf(`
|
|
2
2
|
`,t-1)+1,s=e.indexOf(`
|
|
3
|
-
`,t),a=e.slice(n,s<0?e.length:s).trim();return a?a.length>
|
|
4
|
-
${t??""}`,name:t?`${n} \xB7 ${t}`:n}}k(de,"me"),v(de,"Ne"),r(de,"labelOf");function ce(e,t,n){const s=[],a=e.filter(i=>i.prewarm),c=t.filter(i=>i.prewarm);for(let i=0;i<Math.max(a.length,c.length);i++)s.push({...a[i]?{a:a[i]}:{},...c[i]?{b:c[i]}:{},label:Math.max(a.length,c.length)>1?`prewarm \xB7 ${i+1}`:"prewarm",prewarm:!0,...a[i]&&c[i]?{match:"position"}:{}});const u=new Map,d=r((i,b)=>{const j=de(i);let y=u.get(j.key);y||u.set(j.key,y={name:j.name,a:[],b:[]}),y[b].push(i)},"put");for(const i of e)i.prewarm||d(i,"a");for(const i of t)i.prewarm||d(i,"b");const l=u.size>1;for(const i of u.values()){const b=Math.max(i.a.length,i.b.length),j=r(p=>b>1?`${i.name} \xB7 ${p+1} of ${b}`:i.name,"name");if(i.a.length===i.b.length||i.a.some(p=>!n(p.id))||i.b.some(p=>!n(p.id))){for(let p=0;p<b;p++){const f=i.a[p],M=i.b[p];s.push({...f?{a:f}:{},...M?{b:M}:{},label:j(p),...f&&M?{match:b===1&&l?"label":"position"}:{}})}continue}const y=[];for(let p=0;p<i.a.length;p++)for(let f=0;f<i.b.length;f++){const M=n(i.a[p].id),C=n(i.b[f].id),q=JSON.stringify(M.settings)===JSON.stringify(C.settings)?we(M.flat,C.flat):0;y.push({i:p,j:f,n:q,rest:M.flat.length+C.flat.length-2*q})}y.sort((p,f)=>f.n-p.n||p.rest-f.rest||p.i-f.i||p.j-f.j);const m=new Set,w=new Set,$=[];for(const p of y)m.has(p.i)||w.has(p.j)||(m.add(p.i),w.add(p.j),$.push({i:p.i,j:p.j}));i.a.forEach((p,f)=>!m.has(f)&&$.push({i:f})),i.b.forEach((p,f)=>!w.has(f)&&$.push({j:f})),$.sort((p,f)=>(p.i??1/0)-(f.i??1/0)||(p.j??1/0)-(f.j??1/0)),$.forEach((p,f)=>{const M=p.i!==void 0?i.a[p.i]:void 0,C=p.j!==void 0?i.b[p.j]:void 0;s.push({...M?{a:M}:{},...C?{b:C}:{},label:j(f),...M&&C?{match:"prefix"}:{}})})}return s}k(ce,"ge"),v(ce,"Ce"),r(ce,"matchCalls");export function aiCompareNeeds(e,t){return[e,t].flatMap(n=>(D(K(n))?.rows??[]).slice(0,AI_COMPARE_MAX_CALLS).map(s=>s.id))}k(aiCompareNeeds,"aiCompareNeeds"),v(aiCompareNeeds,"aiCompareNeeds"),r(aiCompareNeeds,"aiCompareNeeds");function pe(e,t){const n=new Map;for(const s of e){if(!s.model||n.has(s.model))continue;const a=t(s.model,s.tokens?.input??0);a&&n.set(s.model,{model:s.model,input:a.input,output:a.output,...a.cacheRead!==void 0?{cacheRead:a.cacheRead}:{},writes:{...a.writes},...a.source?{source:a.source}:{},...a.readAt?{readAt:a.readAt}:{},...a.stale?{stale:!0}:{}})}return[...n.values()]}k(pe,"be"),v(pe,"Ee"),r(pe,"pricesOf");function ae(e,t,n,s){const a=e.rows.map(ge).filter(l=>l!==void 0),c=be(a),u=[...new Set(e.rows.map(l=>l.model).filter(l=>!!l))],d=D(t);return{name:e.name,...e.said?{said:e.said}:{},unit:e.unit,runs:n.slice(0,AI_COMPARE_MAX_RUNS),...n.length>AI_COMPARE_MAX_RUNS?{moreRuns:n.length-AI_COMPARE_MAX_RUNS}:{},runCount:n.length,...d?{diffed:d.key}:{},models:u,prices:pe(e.rows,s),...c!==void 0?{speed:{median:Math.round(c*10)/10,min:Math.round(Math.min(...a)*10)/10,max:Math.round(Math.max(...a)*10)/10,calls:a.length}}:{}}}k(ae,"oe"),v(ae,"de"),r(ae,"sideOf");function he(e,t){const n=e.speed?.median,s=t.speed?.median,a={threshold:AI_SPEED_SKEW,...n!==void 0?{a:n}:{},...s!==void 0?{b:s}:{}};if(n===void 0||s===void 0){const l=[n===void 0?e.name:"",s===void 0?t.name:""].filter(Boolean).join(" and ");return{...a,differs:!1,said:`No speed for ${l}: no call wrote ${Q(AI_SPEED_MIN_OUTPUT)} output tokens or more \u2014 whether the sides ran at one provider speed is not known.`}}const c=J(Math.max(n,s)/Math.min(n,s)-1),u=c>AI_SPEED_SKEW,d=`${e.name} ${n.toFixed(1)} tok/s (${e.speed.min}\u2013${e.speed.max} over ${e.speed.calls} call${e.speed.calls===1?"":"s"}), ${t.name} ${s.toFixed(1)} tok/s (${t.speed.min}\u2013${t.speed.max} over ${t.speed.calls})`;return{...a,apart:c,differs:u,said:u?`The sides ran at different provider speeds: ${d} \u2014 ${Math.round(c*100)}% apart, beyond the ${Math.round(AI_SPEED_SKEW*100)}% two runs of the same requests differ by in one session. Their times are not comparable: measure the two side by side, in one session.`:`One provider speed: ${d} \u2014 ${Math.round(c*100)}% apart, within ${Math.round(AI_SPEED_SKEW*100)}%.`}}k(he,"$e"),v(he,"qe"),r(he,"speedOfSides");export function aiCompare(e){const{a:t,b:n,ratesOf:s}=e,a=K(t),c=K(n),u=a.map(o=>te(o.key,o.rows,s)),d=c.map(o=>te(o.key,o.rows,s)),l=ae(t,a,u,s),i=ae(n,c,d,s),b=he(l,i),j=Ce.map(o=>re(o,l,i,u,d,b.differs)),y=new Map,m=new Map,w=new Map([...t.rows,...n.rows].map(o=>[o.id,o])),$=r(o=>{if(y.has(o))return y.get(o);const x=e.requests?.get(o),S=w.get(o);let A;if(!x)m.set(o,"its request was not read");else if("why"in x)m.set(o,x.why);else if(S){try{A=se(S.api,x.body)}catch{A=void 0}A||m.set(o,"its request is not one the lens can read (an embedding, or not an object)")}return y.set(o,A),A},"joined"),p=D(a),f=D(c),M=(p?.rows??[]).slice(0,AI_COMPARE_MAX_CALLS),C=(f?.rows??[]).slice(0,AI_COMPARE_MAX_CALLS),q=new Re,V=r(o=>{const x=o?ee(o,s):void 0;return x?E(x.input):void 0},"usdOf"),Y=ce(M,C,$).map(o=>{const x={...o.a?{a:o.a.id}:{},...o.b?{b:o.b.id}:{},label:o.label,...o.prewarm?{prewarm:!0}:{},...o.match?{match:o.match}:{},input:[o.a?.tokens?.input??null,o.b?.tokens?.input??null],inputUsd:[V(o.a)??null,V(o.b)??null],output:[o.a?.tokens?.output??null,o.b?.tokens?.output??null],ms:[o.a?.durationMs??null,o.b?.durationMs??null]};if(!o.a||!o.b)return x;const S=$(o.a.id),A=$(o.b.id);return!S||!A?{...x,unread:[S?"":`${t.name}: ${m.get(o.a.id)}`,A?"":`${n.name}: ${m.get(o.b.id)}`].filter(Boolean).join("; ")}:{...x,...ue(S,A,[o.a.tokens?.input,o.b.tokens?.input],q)}});for(const[o,x]of[[l,M],[i,C]]){const S=x.find(B=>B.prewarm),A=S?$(S.id):void 0;if(!S||!A)continue;const X=x.filter(B=>!B.prewarm).map(B=>$(B.id)).filter(B=>!!B);o.prewarm={id:S.id,prefixOf:X.filter(B=>JSON.stringify(B.settings)===JSON.stringify(A.settings)&&B.flat.startsWith(A.flat)).length,of:X.length}}const O=Y.filter(o=>!o.prewarm),G=O.some(o=>o.a&&o.b&&o.same===void 0),T=O.filter(o=>!o.a||!o.b),P=O.filter(o=>o.same===!1),I=P.length||T.length?!1:G?void 0:O.length?!0:void 0,h=O.filter(o=>o.same&&o.cut&&(o.cut.blocks[0]!==o.cut.blocks[1]||o.cut.breakpoints[0]!==o.cut.breakpoints[1]||o.cut.mode[0]!==o.cut.mode[1])),g=P.find(o=>o.diff||o.settings),_=I===!0?`The ${i.name} requests, joined, are the ${l.name} requests byte for byte: ${O.length} call${O.length===1?"":"s"}, the same bytes and settings${h.length?` \u2014 ${h.length} cut otherwise (blocks ${h[0].cut.blocks.join(" \u2192 ")}, breakpoints ${h[0].cut.breakpoints.join(" \u2192 ")}, ${h[0].cut.mode.join(" \u2192 ")}): what the cache sees changed, what the model reads did not`:""}.`:I===!1?`Not the same bytes: ${P.length} of ${O.length} pair${O.length===1?"":"s"} differ${T.length?`, ${T.length} call${T.length===1?"":"s"} on one side only`:""}`+(g?.settings?` \u2014 settings ${g.settings.join(", ")}`:"")+(g?.diff?` \u2014 the first, \xAB${g.label}\xBB, parts at \xAB${g.diff.region}\xBB (character ${Q(g.diff.char)}, byte ${Q(g.diff.byte)}): \xAB${g.diff.line??""}\xBB vs \xAB${g.diff.otherLine??""}\xBB`:"")+".":O.length?`Not every request was read (${O.filter(o=>o.unread).length} pair${O.filter(o=>o.unread).length===1?"":"s"}): whether the requests are the same bytes is not known.`:"No answering call on either side to diff.",F=`The ${l.name} ${t.unit} ${p?.key??"\u2014"} and the ${i.name} ${n.unit} ${f?.key??"\u2014"} (each side's ${t.unit===n.unit?t.unit:"repetition"} with the most calls, the earliest of those) are set call by call: a prewarm to a prewarm; then by action (and the app\u2019s part label) \u2014 one call each, by label; several, by the order they were sent; counts that differ, by the longest prefix their joined requests share.`+((p?.rows.length??0)>AI_COMPARE_MAX_CALLS||(f?.rows.length??0)>AI_COMPARE_MAX_CALLS?` The first ${AI_COMPARE_MAX_CALLS} calls of each.`:""),H=a.length<2&&c.length<2?"One run a side: no noise floor \u2014 a difference may be the model\u2019s own spread (seven runs of one request proposed 11 to 23 changes). Compare several runs a side.":`Noise floor: ${l.name} over ${a.length} ${t.unit}${a.length===1?"":"s"}, ${i.name} over ${c.length}${a.length===2||c.length===2?" \u2014 a floor of two runs is thin":""}. A measure is beyond noise when its ranges do not overlap, or a single run falls outside the other side\u2019s range.`,R=[];b.differs&&R.push(b.said);for(const[o,x]of[[l,u],[i,d]]){const S=x.reduce((N,z)=>N+z.uncounted,0),A=x.reduce((N,z)=>N+z.calls+z.prewarms,0);S&&R.push(`${o.name}: ${S} of ${A} calls kept no usage (a failed call, an answer the capture cut) \u2014 its tokens and dollars are over the ${A-S} counted.`);const X=x.reduce((N,z)=>N+(z.unpriced??0),0);X&&R.push(`${o.name}: ${X} counted call${X===1?"":"s"} with no price \u2014 in its tokens, not its dollars.`);const B=o.prices.filter(N=>N.stale);B.length&&R.push(`${o.name}: the price of ${B.map(N=>N.model).join(", ")} is stale (read ${B.map(N=>N.readAt??"?").join(", ")}): read the provider's page again.`),o.prewarm&&o.prewarm.prefixOf<o.prewarm.of&&R.push(`${o.name}: ${o.prewarm.of-o.prewarm.prefixOf} of ${o.prewarm.of} answering calls do not start with the prewarm's request \u2014 it warmed a prefix they do not share.`)}const U=l.models.join(", "),L=i.models.join(", ");U&&L&&U!==L&&R.push(`The sides called other models (${l.name}: ${U}; ${i.name}: ${L}).`);const ke=["Section tokens and the tokens before a difference are estimated from the text, scaled to the provider\u2019s count.",`Dollars are the provider\u2019s counts at the price table\u2019s rates (${[...l.prices,...i.prices].map(o=>`${o.model}: ${o.source??"no source"}${o.readAt?`, read ${o.readAt}`:""}`).filter((o,x,S)=>S.indexOf(o)===x).join("; ")||"no price"}) \u2014 not the provider\u2019s bill.`,"A call\u2019s speed is its output over its whole time, the wait for the first token included.",...m.size?[`${m.size} request${m.size===1?"":"s"} not diffed: ${[...new Set(m.values())].join("; ")}.`]:[]];return{a:l,b:i,measures:j,speed:b,requests:{how:F,pairs:Y,...I!==void 0?{identical:I}:{},said:_},noise:H,warnings:R,notVerified:ke}}k(aiCompare,"aiCompare"),v(aiCompare,"aiCompare"),r(aiCompare,"aiCompare");
|
|
3
|
+
`,t),a=e.slice(n,s<0?e.length:s).trim();return a?a.length>ie?`${a.slice(0,ie-1)}\u2026`:a:"(an empty line)"},"lineAt"),pe=r((e,t)=>{const n=Math.min(e.length,t.length);let s=0;for(;s<n&&e.charCodeAt(s)===t.charCodeAt(s);)s++;return s},"commonPrefix");function se(e,t){const n=ae(e.text),s=[],a=r((c,u,d)=>{const l=`${e.label} \u203A ${c}`,i=(t.get(l)??0)+1;t.set(l,i),s.push({title:i>1?`${l} #${i}`:l,text:e.text.slice(u,d)})},"push");if(!n.length){const c=(t.get(e.label)??0)+1;return t.set(e.label,c),[{title:c>1?`${e.label} #${c}`:e.label,text:e.text}]}return n[0].at>0&&e.text.slice(0,n[0].at).trim()&&a("(opening)",0,n[0].at),n.forEach((c,u)=>a(c.title,c.at,u+1<n.length?n[u+1].at:e.text.length)),s}k(se,"ue"),r(se,"sectionsOf");class Ee{static{k(this,"_e")}static{r(this,"Estimates")}constructor(){this.memo=new Map}of(t){let n=this.memo.get(t);return n===void 0&&(n=ye(t),this.memo.set(t,n)),n}}function fe(e,t,n,s){const a=[...new Set([...Object.keys(e.settings),...Object.keys(t.settings)])].filter(p=>e.settings[p]!==t.settings[p]);let c=0,u,d;const l=r(()=>d??=e.segments.map(p=>p.text).join(""),"joinedX");for(let p=0;p<Math.max(e.segments.length,t.segments.length)&&!u;p++){const g=e.segments[p],A=t.segments[p];if(g&&A&&g.label===A.label&&g.text===A.text){c+=g.text.length;continue}const I=g&&A&&g.label===A.label?pe(g.text,A.text):0,Y=g?[...ae(g.text)].reverse().find(z=>z.at<=I):void 0,U=g?g.label!==A?.label?`${g.label}${A?` (the other has \xAB${A.label}\xBB here)`:" (the other request has ended)"}`:Y?`${g.label} \u203A ${Y.title}`:g.label:`the end of the first request (the other goes on with \xAB${A.label}\xBB)`,P=c+I;u={char:P,byte:ce(l(),P),region:U,tokensBefore:n[0]!==void 0&&e.chars>0?Math.round(P/e.chars*n[0]):Math.round(s.of(l().slice(0,P))),basis:"estimate",...g?{line:he(g.text,Math.min(I,Math.max(0,g.text.length-1)))}:{},...A?{otherLine:he(A.text,Math.min(I,Math.max(0,A.text.length-1)))}:{}}}const i={blocks:[e.blocks,t.blocks],breakpoints:[e.breakpoints,t.breakpoints],mode:[e.mode,t.mode]},b=!u&&!a.length,O=new Map,x=new Map,m=e.segments.flatMap(p=>se(p,O)),w=t.segments.flatMap(p=>se(p,x)),$=m.reduce((p,g)=>p+s.of(g.text),0),h=w.reduce((p,g)=>p+s.of(g.text),0),[f,y]=n,q=f!==void 0&&y!==void 0&&$+h>0?(f+y)/($+h):f!==void 0&&$>0?f/$:y!==void 0&&h>0?y/h:1,_=r(p=>Math.round(s.of(p)*q),"tok"),K=new Map(w.map(p=>[p.title,p.text])),W=new Set(m.map(p=>p.title)),M=[];let X=0,R=0,E=0;const T=r(p=>{for(;E<w.length&&w[E].title!==p;){const g=w[E++];W.has(g.title)||M.push({title:g.title,b:_(g.text),delta:_(g.text),state:"only-b"})}E<w.length&&E++},"onlyY");for(const p of m){const g=K.get(p.title);if(g===void 0){M.push({title:p.title,a:_(p.text),delta:-_(p.text),state:"only-a"});continue}T(p.title),g===p.text?(X++,R+=_(p.text)):M.push({title:p.title,a:_(p.text),b:_(g),delta:_(g)-_(p.text),state:"changed"})}return T(void 0),{same:b,...a.length?{settings:a}:{},...u?{diff:u}:{},cut:i,sections:{basis:"estimate",changed:M.slice(0,AI_COMPARE_MAX_SECTIONS),...M.length>AI_COMPARE_MAX_SECTIONS?{more:M.length-AI_COMPARE_MAX_SECTIONS}:{},same:X,sameTokens:R}}}k(fe,"Ae"),r(fe,"diffOf");function me(e){const t=e.meta?.part??e.meta?.group??e.meta?.label,n=e.action?.name??"call";return{key:`${e.action?.key??""}
|
|
4
|
+
${t??""}`,name:t?`${n} \xB7 ${t}`:n}}k(me,"Ne"),r(me,"labelOf");function ge(e,t,n){const s=[],a=e.filter(i=>i.prewarm),c=t.filter(i=>i.prewarm);for(let i=0;i<Math.max(a.length,c.length);i++)s.push({...a[i]?{a:a[i]}:{},...c[i]?{b:c[i]}:{},label:Math.max(a.length,c.length)>1?`prewarm \xB7 ${i+1}`:"prewarm",prewarm:!0,...a[i]&&c[i]?{match:"position"}:{}});const u=new Map,d=r((i,b)=>{const O=me(i);let x=u.get(O.key);x||u.set(O.key,x={name:O.name,a:[],b:[]}),x[b].push(i)},"put");for(const i of e)i.prewarm||d(i,"a");for(const i of t)i.prewarm||d(i,"b");const l=u.size>1;for(const i of u.values()){const b=Math.max(i.a.length,i.b.length),O=r(h=>b>1?`${i.name} \xB7 ${h+1} of ${b}`:i.name,"name");if(i.a.length===i.b.length||i.a.some(h=>!n(h.id))||i.b.some(h=>!n(h.id))){for(let h=0;h<b;h++){const f=i.a[h],y=i.b[h];s.push({...f?{a:f}:{},...y?{b:y}:{},label:O(h),...f&&y?{match:b===1&&l?"label":"position"}:{}})}continue}const x=[];for(let h=0;h<i.a.length;h++)for(let f=0;f<i.b.length;f++){const y=n(i.a[h].id),q=n(i.b[f].id),_=JSON.stringify(y.settings)===JSON.stringify(q.settings)?pe(y.flat,q.flat):0;x.push({i:h,j:f,n:_,rest:y.flat.length+q.flat.length-2*_})}x.sort((h,f)=>f.n-h.n||h.rest-f.rest||h.i-f.i||h.j-f.j);const m=new Set,w=new Set,$=[];for(const h of x)m.has(h.i)||w.has(h.j)||(m.add(h.i),w.add(h.j),$.push({i:h.i,j:h.j}));i.a.forEach((h,f)=>!m.has(f)&&$.push({i:f})),i.b.forEach((h,f)=>!w.has(f)&&$.push({j:f})),$.sort((h,f)=>(h.i??1/0)-(f.i??1/0)||(h.j??1/0)-(f.j??1/0)),$.forEach((h,f)=>{const y=h.i!==void 0?i.a[h.i]:void 0,q=h.j!==void 0?i.b[h.j]:void 0;s.push({...y?{a:y}:{},...q?{b:q}:{},label:O(f),...y&&q?{match:"prefix"}:{}})})}return s}k(ge,"Ce"),r(ge,"matchCalls");export function aiCompareNeeds(e,t){return[e,t].flatMap(n=>(D(H(n))?.rows??[]).slice(0,AI_COMPARE_MAX_CALLS).map(s=>s.id))}k(aiCompareNeeds,"aiCompareNeeds"),r(aiCompareNeeds,"aiCompareNeeds");function be(e,t){const n=new Map;for(const s of e){if(!s.model||n.has(s.model))continue;const a=t(s.model,s.tokens?.input??0);a&&n.set(s.model,{model:s.model,input:a.input,output:a.output,...a.cacheRead!==void 0?{cacheRead:a.cacheRead}:{},writes:{...a.writes},...a.source?{source:a.source}:{},...a.readAt?{readAt:a.readAt}:{},...a.stale?{stale:!0}:{}})}return[...n.values()]}k(be,"Ee"),r(be,"pricesOf");function oe(e,t,n,s){const a=e.rows.map(re).filter(l=>l!==void 0),c=le(a),u=[...new Set(e.rows.map(l=>l.model).filter(l=>!!l))],d=D(t);return{name:e.name,...e.said?{said:e.said}:{},unit:e.unit,runs:n.slice(0,AI_COMPARE_MAX_RUNS),...n.length>AI_COMPARE_MAX_RUNS?{moreRuns:n.length-AI_COMPARE_MAX_RUNS}:{},runCount:n.length,...d?{diffed:d.key}:{},models:u,prices:be(e.rows,s),...c!==void 0?{speed:{median:Math.round(c*10)/10,min:Math.round(Math.min(...a)*10)/10,max:Math.round(Math.max(...a)*10)/10,calls:a.length}}:{}}}k(oe,"de"),r(oe,"sideOf");function $e(e,t){const n=e.speed?.median,s=t.speed?.median,a={threshold:AI_SPEED_SKEW,...n!==void 0?{a:n}:{},...s!==void 0?{b:s}:{}};if(n===void 0||s===void 0){const l=[n===void 0?e.name:"",s===void 0?t.name:""].filter(Boolean).join(" and ");return{...a,differs:!1,said:`No speed for ${l}: no call wrote ${V(AI_SPEED_MIN_OUTPUT)} output tokens or more \u2014 whether the sides ran at one provider speed is not known.`}}const c=J(Math.max(n,s)/Math.min(n,s)-1),u=c>AI_SPEED_SKEW,d=`${e.name} ${n.toFixed(1)} tok/s (${e.speed.min}\u2013${e.speed.max} over ${e.speed.calls} call${e.speed.calls===1?"":"s"}), ${t.name} ${s.toFixed(1)} tok/s (${t.speed.min}\u2013${t.speed.max} over ${t.speed.calls})`;return{...a,apart:c,differs:u,said:u?`The sides ran at different provider speeds: ${d} \u2014 ${Math.round(c*100)}% apart, beyond the ${Math.round(AI_SPEED_SKEW*100)}% two runs of the same requests differ by in one session. Their times are not comparable: measure the two side by side, in one session.`:`One provider speed: ${d} \u2014 ${Math.round(c*100)}% apart, within ${Math.round(AI_SPEED_SKEW*100)}%.`}}k($e,"qe"),r($e,"speedOfSides");export function aiCompare(e){const{a:t,b:n,ratesOf:s}=e,a=H(t),c=H(n),u=a.map(o=>ee(o.key,o.rows,s)),d=c.map(o=>ee(o.key,o.rows,s)),l=oe(t,a,u,s),i=oe(n,c,d,s),b=$e(l,i),O=Be.map(o=>de(o,l,i,u,d,b.differs)),x=new Map,m=new Map,w=new Map([...t.rows,...n.rows].map(o=>[o.id,o])),$=r(o=>{if(x.has(o))return x.get(o);const v=e.requests?.get(o),j=w.get(o);let S;if(!v)m.set(o,"its request was not read");else if("why"in v)m.set(o,v.why);else if(j){try{S=ne(j.api,v.body)}catch{S=void 0}S||m.set(o,"its request is not one the lens can read (an embedding, or not an object)")}return x.set(o,S),S},"joined"),h=D(a),f=D(c),y=(h?.rows??[]).slice(0,AI_COMPARE_MAX_CALLS),q=(f?.rows??[]).slice(0,AI_COMPARE_MAX_CALLS),_=new Ee,K=r(o=>{const v=o?Z(o,s):void 0;return v?C(v.input):void 0},"usdOf"),W=ge(y,q,$).map(o=>{const v={...o.a?{a:o.a.id}:{},...o.b?{b:o.b.id}:{},label:o.label,...o.prewarm?{prewarm:!0}:{},...o.match?{match:o.match}:{},input:[o.a?.tokens?.input??null,o.b?.tokens?.input??null],inputUsd:[K(o.a)??null,K(o.b)??null],output:[o.a?.tokens?.output??null,o.b?.tokens?.output??null],ms:[o.a?.durationMs??null,o.b?.durationMs??null]};if(!o.a||!o.b)return v;const j=$(o.a.id),S=$(o.b.id);return!j||!S?{...v,unread:[j?"":`${t.name}: ${m.get(o.a.id)}`,S?"":`${n.name}: ${m.get(o.b.id)}`].filter(Boolean).join("; ")}:{...v,...fe(j,S,[o.a.tokens?.input,o.b.tokens?.input],_)}});for(const[o,v]of[[l,y],[i,q]]){const j=v.find(B=>B.prewarm),S=j?$(j.id):void 0;if(!j||!S)continue;const F=v.filter(B=>!B.prewarm).map(B=>$(B.id)).filter(B=>!!B);o.prewarm={id:j.id,prefixOf:F.filter(B=>JSON.stringify(B.settings)===JSON.stringify(S.settings)&&B.flat.startsWith(S.flat)).length,of:F.length}}const M=W.filter(o=>!o.prewarm),X=M.some(o=>o.a&&o.b&&o.same===void 0),R=M.filter(o=>!o.a||!o.b),E=M.filter(o=>o.same===!1),T=E.length||R.length?!1:X?void 0:M.length?!0:void 0,p=M.filter(o=>o.same&&o.cut&&(o.cut.blocks[0]!==o.cut.blocks[1]||o.cut.breakpoints[0]!==o.cut.breakpoints[1]||o.cut.mode[0]!==o.cut.mode[1])),g=E.find(o=>o.diff||o.settings),A=T===!0?`The ${i.name} requests, joined, are the ${l.name} requests byte for byte: ${M.length} call${M.length===1?"":"s"}, the same bytes and settings${p.length?` \u2014 ${p.length} cut otherwise (blocks ${p[0].cut.blocks.join(" \u2192 ")}, breakpoints ${p[0].cut.breakpoints.join(" \u2192 ")}, ${p[0].cut.mode.join(" \u2192 ")}): what the cache sees changed, what the model reads did not`:""}.`:T===!1?`Not the same bytes: ${E.length} of ${M.length} pair${M.length===1?"":"s"} differ${R.length?`, ${R.length} call${R.length===1?"":"s"} on one side only`:""}`+(g?.settings?` \u2014 settings ${g.settings.join(", ")}`:"")+(g?.diff?` \u2014 the first, \xAB${g.label}\xBB, parts at \xAB${g.diff.region}\xBB (character ${V(g.diff.char)}, byte ${V(g.diff.byte)}): \xAB${g.diff.line??""}\xBB vs \xAB${g.diff.otherLine??""}\xBB`:"")+".":M.length?`Not every request was read (${M.filter(o=>o.unread).length} pair${M.filter(o=>o.unread).length===1?"":"s"}): whether the requests are the same bytes is not known.`:"No answering call on either side to diff.",I=`The ${l.name} ${t.unit} ${h?.key??"\u2014"} and the ${i.name} ${n.unit} ${f?.key??"\u2014"} (each side's ${t.unit===n.unit?t.unit:"repetition"} with the most calls, the earliest of those) are set call by call: a prewarm to a prewarm; then by action (and the app\u2019s part label) \u2014 one call each, by label; several, by the order they were sent; counts that differ, by the longest prefix their joined requests share.`+((h?.rows.length??0)>AI_COMPARE_MAX_CALLS||(f?.rows.length??0)>AI_COMPARE_MAX_CALLS?` The first ${AI_COMPARE_MAX_CALLS} calls of each.`:""),Y=a.length<2&&c.length<2?"One run a side: no noise floor \u2014 a difference may be the model\u2019s own spread (seven runs of one request proposed 11 to 23 changes). Compare several runs a side.":`Noise floor: ${l.name} over ${a.length} ${t.unit}${a.length===1?"":"s"}, ${i.name} over ${c.length}${a.length===2||c.length===2?" \u2014 a floor of two runs is thin":""}. A measure is beyond noise when its ranges do not overlap, or a single run falls outside the other side\u2019s range.`,U=[];b.differs&&U.push(b.said);for(const[o,v]of[[l,u],[i,d]]){const j=v.reduce((N,L)=>N+L.uncounted,0),S=v.reduce((N,L)=>N+L.calls+L.prewarms,0);j&&U.push(`${o.name}: ${j} of ${S} calls kept no usage (a failed call, an answer the capture cut) \u2014 its tokens and dollars are over the ${S-j} counted.`);const F=v.reduce((N,L)=>N+(L.unpriced??0),0);F&&U.push(`${o.name}: ${F} counted call${F===1?"":"s"} with no price \u2014 in its tokens, not its dollars.`);const B=o.prices.filter(N=>N.stale);B.length&&U.push(`${o.name}: the price of ${B.map(N=>N.model).join(", ")} is stale (read ${B.map(N=>N.readAt??"?").join(", ")}): read the provider's page again.`),o.prewarm&&o.prewarm.prefixOf<o.prewarm.of&&U.push(`${o.name}: ${o.prewarm.of-o.prewarm.prefixOf} of ${o.prewarm.of} answering calls do not start with the prewarm's request \u2014 it warmed a prefix they do not share.`)}const P=l.models.join(", "),z=i.models.join(", ");P&&z&&P!==z&&U.push(`The sides called other models (${l.name}: ${P}; ${i.name}: ${z}).`);const we=["Section tokens and the tokens before a difference are estimated from the text, scaled to the provider\u2019s count.",`Dollars are the provider\u2019s counts at the price table\u2019s rates (${[...l.prices,...i.prices].map(o=>`${o.model}: ${o.source??"no source"}${o.readAt?`, read ${o.readAt}`:""}`).filter((o,v,j)=>j.indexOf(o)===v).join("; ")||"no price"}) \u2014 not the provider\u2019s bill.`,"A call\u2019s speed is its output over its whole time, the wait for the first token included.",...m.size?[`${m.size} request${m.size===1?"":"s"} not diffed: ${[...new Set(m.values())].join("; ")}.`]:[]];return{a:l,b:i,measures:O,speed:b,requests:{how:I,pairs:W,...T!==void 0?{identical:T}:{},said:A},noise:Y,warnings:U,notVerified:we}}k(aiCompare,"aiCompare"),r(aiCompare,"aiCompare");
|
package/lib/ai-context.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
`),h=r>0?
|
|
3
|
-
`)return!0;if(
|
|
4
|
-
${t.output}`:""}`;return{kind:"tool",label:`tool \xB7 ${t.tool}${t.output!==void 0?" \u2014 called, and its result":" \u2014 called"}`,role:"tool",ref:{turn:e},text:
|
|
5
|
-
`),
|
|
6
|
-
`),n=estimateTokens(
|
|
1
|
+
"use strict";var P=Object.defineProperty;var $=(t,e)=>P(t,"name",{value:e,configurable:!0});var G=Object.defineProperty,g=$((t,e)=>G(t,"name",{value:e,configurable:!0}),"g");export const AI_PART_KINDS=["system","tools","schema","context","history","tool","turn","carried","unkept"],AI_PART_LABEL={system:"System prompt",tools:"Tool definitions",schema:"Answer schema",context:"Context",history:"Earlier turns",tool:"Tool calls & results",turn:"This turn",carried:"Held by the provider",unkept:"Not kept"},AI_PART_SAID={system:"The instructions every call of this agent starts with",tools:"The tools it was offered, as defined \u2014 sent with every call, called or not",schema:"The JSON schema its answer had to fit",context:"What the app put in beside the conversation (developer messages)",history:"The conversation before this turn \u2014 what was said, and answered",tool:"The tools it called earlier in this run, what it sent them and what came back",turn:"What this call asks \u2014 the latest message",carried:"The conversation of the response it continues (previous_response_id): counted by the provider, not in this request",unkept:"The end of the request, which the capture did not keep (a lens before 1.25.32 kept its first 64 KB): counted by the provider, not known here"};const R=/[\p{L}\p{M}]/u,W=/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u,D=/(\s*)([A-Za-z]+|[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]+|[\p{L}\p{M}]+|[0-9]+|[^\s\p{L}\p{M}0-9]+)|(\s+)/gu,B=4,I=.7;export function estimateTokens(t){let e=0;for(const o of t.matchAll(D)){const s=o[1],n=o[2];if(o[3]!==void 0){/\n| {2,}/.test(o[3])&&(e+=1);continue}if(s&&/\n| {2,}/.test(s)&&(e+=1),!n)continue;const r=n.charCodeAt(0);r>=65&&r<=90||r>=97&&r<=122?e+=1+(n.length>8?(n.length-8)/4:0):r>=48&&r<=57?e+=Math.ceil(n.length/3):W.test(n)?e+=[...n].length*.9:R.test(n)?e+=[...n].length*.66:e+=n.length*.75}return e}$(estimateTokens,"estimateTokens"),g(estimateTokens,"estimateTokens");const Z=/^[ \t]*-{3,}[ \t]*(.+?)[ \t]*-{3,}[ \t]*$/gm,U=/^(#{1,4})[ \t]+(.+?)[ \t]*#*[ \t]*$/gm,_=60;function C(t,e){const o=[],s=t.slice(0,e[0].at);return s.trim().length>40&&o.push({title:"(opening)",chars:s.length,tokens:0,at:0,end:e[0].at}),e.forEach((n,r)=>{const h=r+1<e.length?e[r+1].at:t.length;o.push({title:n.title.slice(0,120),chars:h-n.at,tokens:0,at:n.at,end:h})}),o}$(C,"P"),g(C,"cutAt");function M(t){const e=t.trim();if(!e.startsWith("{")&&!e.startsWith("["))return[];let o;try{o=JSON.parse(e)}catch{return[]}const s=o&&typeof o=="object"&&!Array.isArray(o)?o.properties:void 0,n=s&&typeof s=="object"&&!Array.isArray(s)?s:o,r=Array.isArray(n)?n.map((h,u)=>[`[${u}]`,h]):n&&typeof n=="object"?Object.entries(n):[];return r.length<2?[]:r.slice(0,_).map(([h,u])=>{const c=JSON.stringify(u,null,2)??"";return{title:h,chars:c.length,tokens:estimateTokens(c)}})}$(M,"M"),g(M,"jsonSections");export function sectionsOf(t){const e=taggedSections(t);return e.length?e:j(t)}$(sectionsOf,"sectionsOf"),g(sectionsOf,"sectionsOf");function j(t){if(t.length<200)return[];let e=g((s,n,r=()=>!0)=>[...t.matchAll(s)].filter(r).map(h=>({at:h.index,title:n(h)})),"pick")(Z,s=>s[1]);if(e.length<2){const s=[...t.matchAll(U)],n=[1,2,3,4].find(r=>s.filter(h=>h[1].length===r).length>=2);e=n?s.filter(r=>r[1].length===n).map(r=>({at:r.index,title:r[2]})):[]}if(e.length<2)return M(t);const o=C(t,e.slice(0,_));for(const s of o){const n=t.slice(s.at,s.end);s.tokens=estimateTokens(n);const r=n.indexOf(`
|
|
2
|
+
`),h=r>0?M(n.slice(r+1)):[];h.length&&(s.children=h)}return o}$(j,"N"),g(j,"plainSections");export const STABLE_TAGS=new Set(["instructions","rules","output","examples"]),CHANGING_TAGS=new Set(["memory","status","data","task"]);const F=/<([a-z][a-z0-9_-]{0,40})((?:\s+[A-Za-z_][\w.:-]*\s*=\s*(?:"[^"]*"|'[^']*'))*)\s*>/g,Q=/([A-Za-z_][\w.:-]*)\s*=\s*(?:"([^"]*)"|'([^']*)')/g,X=g(t=>t.replace(/"/g,'"').replace(/'/g,"'").replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&"),"unescape");function H(t){const e={};for(const o of t.matchAll(Q))e[o[1]]=X(o[2]??o[3]??"");return e}$(H,"q"),g(H,"attrsOf");function L(t,e,o,s){const n=`<${e}`,r=`</${e}>`;let h=1,u=o;for(;u<s;){const c=t.indexOf(r,u);if(c<0||c>=s)return-1;let f=t.indexOf(n,u);for(;f>=0&&f<c&&!/[\s>]/.test(t[f+n.length]??"");)f=t.indexOf(n,f+1);if(f>=0&&f<c){h++,u=f+n.length;continue}if(--h===0)return c;u=c+r.length}return-1}$(L,"z"),g(L,"closeOf");const V=g((t,e)=>{for(let o=e-1;o>=0;o--){const s=t[o];if(s===`
|
|
3
|
+
`)return!0;if(s!==" "&&s!==" ")return!1}return!0},"atLineStart");export function taggedSections(t,e=0,o=t.length,s=0){const n=[],r=new RegExp(F.source,"g");let h=e;for(;h<o&&n.length<_;){r.lastIndex=h;const l=r.exec(t);if(!l||l.index>=o)break;const p=l[1],k=l.index+l[0].length,x=V(t,l.index)?L(t,p,k,o):-1;if(x<0){h=k;continue}const i=x+p.length+3,d=H(l[2]??""),b={title:p,tag:p,...Object.keys(d).length?{attrs:d}:{},chars:i-l.index,tokens:estimateTokens(t.slice(l.index,i)),at:l.index,end:i};if(s<1){const w=taggedSections(t,k,x,s+1).filter(a=>a.tag),v=w.length?w:j(t.slice(k,x)).map(a=>a.at===void 0?a:{...a,at:a.at+k,end:a.end+k});v.length&&(b.children=v)}n.push(b),h=i}if(!n.length)return[];const u=[];let c=e;const f=g((l,p)=>{const k=t.slice(l,p);k.trim().length>20&&u.push({title:"(untagged)",chars:p-l,tokens:estimateTokens(k),at:l,end:p})},"gap");for(const l of n)f(c,l.at),u.push(l),c=l.end;f(c,o);const y=new Map;for(const l of u){if(!l.tag)continue;const p=l.attrs?.id?`${l.tag} \xB7 ${l.attrs.id}`:l.tag,k=(y.get(p)??0)+1;y.set(p,k),l.title=k>1?`${p} #${k}`:p}return u}$(taggedSections,"taggedSections"),g(taggedSections,"taggedSections");function N(t,e){const o=t.reduce((s,n)=>s+n.tokens,0);for(const s of t)s.tokens=o>0?Math.round(s.tokens/o*e):0,s.children&&N(s.children,s.tokens)}$(N,"I"),g(N,"scaleSections");const Y={user:"user",assistant:"assistant",developer:"Context \xB7 developer message",system:"system message"};function E(t,e,o){if(t.kind==="reasoning")return t.text?{kind:"history",label:"reasoning \xB7 sent back",role:"assistant",ref:{turn:e},text:t.text,estimate:estimateTokens(t.text)+B}:void 0;if(t.kind==="tool"){const s=`${t.name}(${t.arguments})${t.output!==void 0?`
|
|
4
|
+
${t.output}`:""}`;return{kind:"tool",label:`tool \xB7 ${t.tool}${t.output!==void 0?" \u2014 called, and its result":" \u2014 called"}`,role:"tool",ref:{turn:e},text:s,estimate:estimateTokens(s)+B*(t.output!==void 0?2:1)}}return{kind:o,label:Y[t.role],role:t.role,ref:{turn:e},text:t.text,estimate:estimateTokens(t.text)+B}}$(E,"Z"),g(E,"turnDraft");function J(t){const e=t.turns;let o=e.length;for(;o>0&&e[o-1].kind==="message"&&e[o-1].role!=="assistant";)o--;return e.map((s,n)=>s.kind==="tool"?"tool":s.kind==="reasoning"?"history":s.role==="developer"||s.role==="system"?"context":n>=o&&s.role==="user"?"turn":"history")}$(J,"F"),g(J,"turnKinds");function K(t){const e=t.system.map((c,f)=>({kind:"system",label:c.source==="instructions"?"System prompt \xB7 instructions":`System prompt \xB7 ${c.source}`,ref:{system:f},text:c.text,estimate:estimateTokens(c.text)+B})),o=t.tools.map(c=>JSON.stringify({name:c.name,description:c.description,parameters:c.parameters})).join(`
|
|
5
|
+
`),s=t.tools.length?[{kind:"tools",label:`${t.tools.length} tool${t.tools.length===1?"":"s"} offered`,ref:{tools:!0},text:o,estimate:estimateTokens(o)*I}]:[],n=t.answer.format?.schema!==void 0?JSON.stringify(t.answer.format.schema):"",r=n?[{kind:"schema",label:`Answer schema${t.answer.format?.name?` \xB7 ${t.answer.format.name}`:""}`,ref:{schema:!0},text:n,estimate:estimateTokens(n)*I}]:[],h=J(t),u=t.turns.map((c,f)=>E(c,f,h[f])).filter(c=>!!c);for(const c of u){const f=t.turns[c.ref.turn];f.kind==="message"&&f.attachments?.length&&(c.label+=` \xB7 ${f.attachments.join(", ")}`)}return t.provider==="anthropic"?[...s,...e,...r,...u]:[...e,...s,...r,...u]}$(K,"U"),g(K,"draftsOf");export function aiContextOf(t,e={}){const o=e.sections!==!1,s=K(t),n=Math.round(s.reduce((a,m)=>a+m.estimate,0)),r=t.usage,h=r?.input!==void 0&&r.input>0,u=h?r.input:n,c=t.settings.some(a=>a.name==="continues response"),f=t.gaps.some(a=>/^The (request was kept to its first|prompt was not kept)/.test(a)),y=h&&(c||f)&&u>n*1.05?u-n:0,l=c?y:0,p=c?0:y,k=n>0?(u-y)/n:0,x=s.map((a,m)=>({i:m,kind:a.kind,label:a.label,...a.role?{role:a.role}:{},ref:a.ref,chars:a.text.length,tokens:Math.round(a.estimate*k),cached:0,sections:!o||a.kind==="tools"?[]:sectionsOf(a.text)}));l&&x.unshift({i:-1,kind:"carried",label:"The conversation it continues",ref:{carried:!0},chars:0,tokens:l,cached:0,sections:[]}),p&&x.push({i:-1,kind:"unkept",label:"The rest of the request \u2014 not kept",ref:{unkept:!0},chars:0,tokens:p,cached:0,sections:[]});const i=u-x.reduce((a,m)=>a+m.tokens,0);i&&x.length&&(x.reduce((a,m)=>m.tokens>a.tokens?m:a).tokens+=i);for(const a of x)a.kind==="tools"&&o&&(a.sections=t.tools.map(m=>({title:m.server?`${m.server} \u203A ${m.tool}`:m.tool,chars:0,tokens:estimateTokens(JSON.stringify({d:m.description,p:m.parameters}))}))),N(a.sections,a.tokens);x.forEach((a,m)=>a.i=m);const d=Math.min(r?.cached??0,u);let b=d;for(const a of x)a.cached=Math.min(a.tokens,b),b-=a.cached;const w=AI_PART_KINDS.map(a=>{const m=x.filter(A=>A.kind===a);return{kind:a,tokens:m.reduce((A,T)=>A+T.tokens,0),cached:m.reduce((A,T)=>A+T.cached,0),parts:m.length}}).filter(a=>a.parts),v=q(t);return{parts:x,byKind:w,input:u,counted:h,cached:d,...r?.written?{written:r.written}:{},estimated:n,output:v,findings:z(t,x,u,d,v)}}$(aiContextOf,"aiContextOf"),g(aiContextOf,"aiContextOf");function q(t){const e=t.answer,o=e.json!==void 0?JSON.stringify(e.json):e.text??e.refusal??"",s=e.toolCalls.map(p=>`${p.name}(${p.arguments})`).join(`
|
|
6
|
+
`),n=estimateTokens(o),r=estimateTokens(s)+e.toolCalls.length*B,h=t.usage,u=h?.output!==void 0,c=u?h.output:Math.round(n+r),f=Math.min(h?.reasoning??0,c),y=c-f,l=n+r>0?Math.round(r/(n+r)*y):0;return{total:c,reasoning:f,answer:y-l,tools:l,counted:u}}$(q,"X"),g(q,"outputOf");const S=g(t=>Math.round(t).toLocaleString("en-US"),"fmt"),O=g((t,e)=>`${e>0?Math.round(t/e*100):0}%`,"pct");function z(t,e,o,s,n){const r=[],h=t.answer;if(h.status==="incomplete"||/max_output_tokens|length|max_tokens/.test(h.finish??"")){const i=t.settings.find(d=>/max output|max_tokens|max_completion/.test(d.name));r.push({tone:"bad",text:`It stopped at its output cap${i?` (${i.name} ${i.value})`:""} \u2014 the answer is cut.`})}t.gaps.length&&r.push({tone:"warn",text:"Part of the call was not kept \u2014 the split covers what was."});const u=t.turns.reduce((i,d)=>i+(d.kind==="message"?d.attachments?.length??0:0),0);u&&r.push({tone:"info",text:`${u} image${u===1?"":"s"} or file${u===1?"":"s"} went with its messages: their tokens are counted by the provider but not read from the text, so the split spreads them over the parts.`});const c=t.usage;if(c?.input!==void 0&&o>=1024){if(!s)r.push({tone:"warn",text:`None of its ${S(o)} input tokens came from the prompt cache${c.written?` \u2014 ${S(c.written)} were written to it, for a later call that opens the same way`:""}.`});else if(s<o*.9){const w=e.find(v=>v.cached<v.tokens);w&&r.push({tone:"info",text:`${O(s,o)} cached \u2014 the cache stopped in \xAB${w.label}\xBB: from there on the prompt differed from the last call that opened the same way.`})}const i=e.findIndex(w=>w.kind==="context"),d=i>=0?e.slice(i+1).filter(w=>w.kind==="history"||w.kind==="tool"):[],b=d.reduce((w,v)=>w+v.tokens,0);i>=0&&d.length>=2&&e[i].cached<e[i].tokens&&b>0&&r.push({tone:"info",text:`The context the app put in sits before ${d.length} earlier turns (${S(b)} tokens): when it changes between calls, nothing after it can be read from the cache.`})}const f=e.flatMap(i=>i.sections.filter(d=>d.tag).map(d=>({p:i,x:d}))),y=f.findIndex(({x:i})=>CHANGING_TAGS.has(i.tag)),l=y>=0?f.slice(y+1).filter(({x:i})=>STABLE_TAGS.has(i.tag)):[];if(y>=0&&l.length){const i=f[y].x,d=l.reduce((b,{x:w})=>b+w.tokens,0);r.push({tone:"info",text:`\xAB${i.title}\xBB changes from call to call and comes before ${l.length} section${l.length===1?"":"s"} that should not (\xAB${l[0].x.title}\xBB\u2026, ${S(d)} tokens): put the stable ones first, or they cannot be read from the cache.`})}const p=e.filter(i=>i.kind!=="carried").reduce((i,d)=>!i||d.tokens>i.tokens?d:i,void 0);if(p&&o>2e3&&p.tokens>o*.5){const i=p.sections.reduce((d,b)=>!d||b.tokens>d.tokens?b:d,void 0);r.push({tone:"info",text:`\xAB${p.label}\xBB is ${O(p.tokens,o)} of the input${i&&i.tokens>p.tokens*.4?` \u2014 most of it \xAB${i.title}\xBB (${S(i.tokens)} tokens)`:""}.`})}const k=e.find(i=>i.kind==="tools"),x=h.toolCalls.length;return k&&k.tokens>o*.2&&!x&&!t.turns.some(i=>i.kind==="tool")&&r.push({tone:"info",text:`${t.tools.length} tool definitions are ${O(k.tokens,o)} of the input, and it called none of them.`}),n.total>=200&&n.reasoning>n.total*.7&&r.push({tone:"info",text:`${O(n.reasoning,n.total)} of its output was reasoning (${S(n.reasoning)} tokens).`}),r}$(z,"Q"),g(z,"findingsOf");export function aiSplitOf(t){return Object.fromEntries(t.byKind.filter(e=>e.tokens>0).map(e=>[e.kind,e.tokens]))}$(aiSplitOf,"aiSplitOf"),g(aiSplitOf,"aiSplitOf");
|
package/lib/ai-origins.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
`);if("schema"in
|
|
3
|
-
${
|
|
1
|
+
"use strict";var It=Object.defineProperty;var v=(t,e)=>It(t,"name",{value:e,configurable:!0});var Mt=Object.defineProperty,c=v((t,e)=>Mt(t,"name",{value:e,configurable:!0}),"a");import{aiContextOf as at}from"./ai-context.js";const ct=8,lt=24,ft=32,Nt=80,ut=400,Tt=200,Ct=1e6,Jt=12;export function normText(t){return(t.includes("\\")?t.replace(/\\[nrt]/g," ").replace(/\\(["\\/])/g,"$1"):t).replace(/\s\s+|[^\S ]/g," ").trim()}v(normText,"normText"),c(normText,"normText");function S(t){const e=t.trim();if(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]"))try{return JSON.stringify(JSON.parse(e))}catch{}return normText(e)}v(S,"I"),c(S,"canonical");const W=ft,G=16777619,qt=(()=>{let t=1;for(let e=1;e<W;e++)t=Math.imul(t,G);return t})(),dt=1<<18,ht=dt-1;function Q(t){let e=0;for(let s=0;s<W;s++)e=Math.imul(e,G)+t.charCodeAt(s)|0;return e}v(Q,"ue"),c(Q,"headHash");class Wt{static{v(this,"Ne")}static{c(this,"PassageIndex")}constructor(){this.by=new Map,this.bits=new Uint32Array(dt>>>5),this.n=0}add(e){const s=Q(e.text),r=this.by.get(s);r?r.push(e):this.by.set(s,[e]),this.bits[(s&ht)>>>5]|=1<<(s&31),this.n++}get size(){return this.n}find(e,s){if(!this.n||e.length<W)return;const r=new Set,n=this.bits;let a=Q(e);for(let u=0;;u++){const h=(n[(a&ht)>>>5]&1<<(a&31))!==0?this.by.get(a):void 0;if(h)for(const w of h)!r.has(w)&&e.startsWith(w.text,u)&&(r.add(w),s(w));if(u+W>=e.length)break;a=Math.imul(a-Math.imul(e.charCodeAt(u),qt)|0,G)+e.charCodeAt(u+W)|0}}}const pt=c(t=>t.replace(/^(?:mcp__)?[A-Za-z0-9-]+(?:_[A-Za-z0-9-]+)*__/,""),"toolName");function C(t,e,s,r=0){if(!(r>Jt)){if(typeof t=="string")e(t,s);else if(Array.isArray(t))for(const n of t)C(n,e,s,r+1);else if(t&&typeof t=="object")for(const[n,a]of Object.entries(t))C(a,e,n,r+1)}}v(C,"T"),c(C,"strings");const V=c(t=>{const e=t.trim();if(!(!e.startsWith("{")&&!e.startsWith("[")))try{return JSON.parse(e)}catch{return}},"parseJson");function gt(t){const e=t.answer,s=[],r=c((n,a)=>{const u=S(n);u.length>=ct&&s.push({key:u,text:normText(n),...a?{what:a}:{}})},"add");e.text!==void 0&&r(e.text),e.json!==void 0&&(e.text===void 0&&r(JSON.stringify(e.json)),C(e.json,(n,a)=>{n.trim().length>=lt&&r(n,a?`its \xAB${a}\xBB`:void 0)}));for(const n of e.toolCalls){const a=n.tool||pt(n.name);r(n.arguments,`its call of ${a}`),C(V(n.arguments),(u,h)=>{u.trim().length>=lt&&r(u,h?`${a}\u2019s \xAB${h}\xBB`:`its call of ${a}`)})}return s}v(gt,"_e"),c(gt,"answerKeys");function wt(t){const e=[],s=new Set,r=c((h,w,x)=>{if(e.length>=Tt||s.has(h))return;s.add(h);const O={text:h,e:t,...w?{what:w}:{},...x?{parent:x}:{}};return e.push(O),O},"push"),n=c((h,w,x,O)=>{const[j,...K]=O;if(j)for(const J of h.split(j)){const N=normText(J);if(N.length<Nt||N===x?.text)continue;const R=r(N,w,x)??x;N.length>ut&&n(J,w,R,K)}},"pieces"),a=c((h,w)=>{const x=normText(h);if(x.length<ft)return;const O=r(x,w);x.length>ut&&n(h,w,O,[/\n\s*\n/,/\n/,/(?<=[.!?:;])\s+/])},"text"),u=t.call.answer;u.json!==void 0?C(u.json,(h,w)=>a(h,w?`its \xAB${w}\xBB`:void 0)):u.text!==void 0&&a(u.text);for(const h of u.toolCalls){const w=h.tool||pt(h.name),x=V(h.arguments);x!==void 0?C(x,(O,j)=>a(O,j?`${w}\u2019s \xAB${j}\xBB`:`its call of ${w}`)):a(h.arguments,`its call of ${w}`)}return e}v(wt,"je"),c(wt,"passagesOf");function mt(t){const e=[];let s=Ct;const r=c(n=>{if(s<=0||!n)return;const a=n.length>s?n.slice(0,s):n;s-=a.length,e.push(a)},"take");for(const n of t.system)r(n.text);for(const n of t.turns)n.kind==="tool"?(r(n.arguments),r(n.output??"")):r(n.text??"");return e}v(mt,"Te"),c(mt,"inputTexts");function _(t,e){const s=e.ref;if("system"in s)return t.system[s.system]?.text??"";if("tools"in s)return t.tools.map(r=>JSON.stringify({name:r.name,description:r.description,parameters:r.parameters})).join(`
|
|
2
|
+
`);if("schema"in s)return t.answer.format?.schema!==void 0?JSON.stringify(t.answer.format.schema):"";if("turn"in s){const r=t.turns[s.turn];return r?r.kind==="tool"?`${r.name}(${r.arguments})${r.output!==void 0?`
|
|
3
|
+
${r.output}`:""}`:r.text??"":""}return""}v(_,"K"),c(_,"partText");export const aiPartText=c((t,e)=>_(t,e),"aiPartText"),aiSectionTexts=c((t,e)=>z(t,e,_(t,e)),"aiSectionTexts");function $t(t){const e=V(t);if(e===void 0)return[];const s=e&&typeof e=="object"&&!Array.isArray(e)?e.properties:void 0,r=s&&typeof s=="object"&&!Array.isArray(s)?s:e;return(Array.isArray(r)?r:r&&typeof r=="object"?Object.values(r):[]).map(n=>typeof n=="string"?n:JSON.stringify(n,null,2)??"")}v($t,"Ee"),c($t,"jsonMemberTexts");function z(t,e,s){if(e.kind==="tools")return t.tools.map(n=>JSON.stringify({d:n.description,p:n.parameters}));let r;return e.sections.map((n,a)=>n.at!==void 0&&n.end!==void 0?s.slice(n.at,n.end):(r??=$t(s),r[a]??""))}v(z,"B"),c(z,"sectionTexts");function E(t){const e=new Map;return t.sections.map(s=>{const r=e.get(s.title)??0;return e.set(s.title,r+1),`${s.title}#${r}`})}v(E,"F"),c(E,"titled");function X(t){return t?t.kind==="tool"?`tool
|
|
4
4
|
${t.name}
|
|
5
|
-
${
|
|
6
|
-
${
|
|
7
|
-
${
|
|
8
|
-
${
|
|
9
|
-
${
|
|
10
|
-
`):-1,
|
|
5
|
+
${S(t.arguments)}
|
|
6
|
+
${S(t.output??"")}`:t.kind==="reasoning"?`reasoning
|
|
7
|
+
${S(t.text??"")}`:`${t.role}
|
|
8
|
+
${S(t.text)}`:""}v(X,"le"),c(X,"turnKey");const _t=new Set(["system","tools","schema","context"]),vt=new Set(["history","tool","turn"]);function Y(t){const e=new Map,s=new Map;for(const r of t){if(!_t.has(r.kind))continue;const n=`${r.kind}:${r.role??""}`,a=e.get(n)??0;e.set(n,a+1),s.set(r,`${n}#${a}`)}return s}v(Y,"pe"),c(Y,"structureKeys");const xt=c(t=>t.toLocaleString("en-US"),"fmt"),D=c(t=>t.k===1?"the call before":`${t.k} calls earlier`,"ago"),P=c(t=>({id:t.row.id,agent:t.row.agent.name,...t.row.step!==void 0?{step:t.row.step}:{},at:t.row.at,service:t.row.service}),"fromOf"),yt={answer:6,"tool-output":6,quoted:5,carried:4,changed:3,unchanged:2,new:1};function kt(t,e){const s=e.filter(n=>n.row.agent.key===t.agent.key),r=[["thread",t.thread?n=>n.thread?.key===t.thread.key:void 0],["run",n=>n.run.key===t.run.key],["flow",t.flowId?n=>n.flowId===t.flowId:void 0],["request",t.requestId?n=>n.requestId===t.requestId:void 0]];for(const[n,a]of r)if(a){for(let u=s.length-1;u>=0;u--)if(a(s[u].row))return{e:s[u],by:n}}}v(kt,"We"),c(kt,"previousOf");export function aiOriginsOf(t,e,s){const r=s.filter(o=>o.row.id!==e.id&&o.row.at<=e.at).sort((o,i)=>o.row.at-i.row.at||o.row.id.localeCompare(i.row.id)),n=r.map((o,i)=>({row:o.row,call:o.call,k:r.length-i})),a=kt(e,n),u={compared:n.length,...a?{previous:{id:a.e.row.id,at:a.e.row.at,by:a.by}}:{},items:[]};if(!n.length)return u;const h=new Map,w=new Wt;for(const o of n){for(const i of gt(o.call)){const d=h.get(i.key);d?d.push({...i,e:o}):h.set(i.key,[{...i,e:o}])}for(const i of wt(o))w.add(i)}const x=new Map,O=new Map,j=c((o,i)=>{const d=`${o.k}
|
|
9
|
+
${i}`;let m=O.get(d);if(m===void 0){let l=x.get(o);l||x.set(o,l=mt(o.call).map(normText)),m=l.some(f=>f.includes(i)),O.set(d,m)}return m},"given"),K=c((o,...i)=>{for(const d of i){if(d===void 0)continue;const m=S(d),l=m.length>=ct?h.get(m):void 0;for(let f=(l?.length??0)-1;f>=0;f--){const y=l[f];if(o||!j(y.e,y.text))return{e:y.e,...y.what?{what:y.what}:{}}}}},"answerOf"),J=c((o,i=!1)=>{if(!w.size)return;const d=new Set;if(w.find(normText(o),f=>d.add(f)),!i)for(const f of d)j(f.e,f.text)&&d.delete(f);if(!d.size)return;const m=new Map;for(const f of d){let y=f.parent;for(;y&&!d.has(y);)y=y.parent;if(y)continue;const I=m.get(f.e)??{e:f.e,n:0,what:new Set};I.n++,f.what&&I.what.add(f.what),m.set(f.e,I)}let l;for(const f of m.values())(!l||f.n>l.n||f.n===l.n&&f.e.k<l.e.k)&&(l=f);return l},"quoteIn"),N=c(o=>({how:"answer",from:P(o.e),said:`the answer of ${o.e.row.agent.name}${o.what?` (${o.what})`:""}, ${D(o.e)}`}),"answered"),R=c(o=>({how:"quoted",from:P(o.e),passages:o.n,said:`quotes ${o.n===1?"a passage":`${o.n} passages`} of ${o.e.row.agent.name}\u2019s answer${o.what.size===1?` (${[...o.what][0]})`:""}, ${D(o.e)}`}),"quoted"),tt=at(t);let U,et=[];if(a){const o=at(a.e.call);U=new Map;for(const[i,d]of Y(o.parts))U.set(d,{part:i,text:_(a.e.call,i)});et=o.parts.filter(i=>vt.has(i.kind)&&"turn"in i.ref).map(i=>X(a.e.call.turns[i.ref.turn]))}const bt=c(o=>{const i=U?.get(o);if(i){if(!i.sections){const d=z(a.e.call,i.part,i.text);i.sections=new Map(E(i.part).map((m,l)=>[m,{text:d[l]??"",canon:S(d[l]??"")}]))}return i.sections}},"prevSections"),St=a?`the previous call of this ${a.by}`:"",B=a?P(a.e):void 0,nt=c((o,i)=>`changed since the previous call \u2014 ${xt(o)} \u2192 ${xt(i)} chars`,"changedSaid"),Ot=Y(tt.parts),ot=[...n].reverse();let rt=0;return tt.parts.forEach((o,i)=>{if(o.kind==="carried"){const p=e.previousResponseId??t.settings.find(g=>g.name==="continues response")?.value,$=p?ot.find(g=>(g.row.responseId??g.call.responseId)===p):void 0;$&&u.items.push({part:i,how:"carried",from:P($),said:`the conversation of ${$.row.agent.name}\u2019s response it continues, ${D($)} \u2014 held by the provider, not sent again`});return}const d=_(t,o),m="turn"in o.ref?t.turns[o.ref.turn]:void 0;let l,f;const y=Ot.get(o);if(a&&y){const p=U.get(y);p?S(p.text)===S(d)?l={part:i,how:"unchanged",from:B,said:`unchanged since ${St}`}:(l={part:i,how:"changed",from:B,said:nt(p.text.length,d.length),chars:{before:p.text.length,after:d.length}},f=bt(y)):l={part:i,how:"new",from:B,said:"new since the previous call"}}else if(a&&vt.has(o.kind)){const p=X(m),$=et.indexOf(p,rt);$>=0?(rt=$+1,l={part:i,how:"carried",from:B,said:"carried from the previous call"}):l={part:i,how:"new",from:B,said:"new since the previous call"}}const I=l&&l.how!=="carried"?l.how:l?"unchanged":void 0;let k;if(m?.kind==="tool"&&m.callId){const p=m.callId,$=ot.find(g=>g.row.callIds?.includes(p)||g.call.answer.toolCalls.some(b=>b.callId===p));if($){const g=$.row.step!==void 0&&$.row.run.key===e.run.key?`called in step ${$.row.step}`:`called by ${$.row.agent.name}, ${D($)}`;k={part:i,how:"tool-output",from:P($),said:`returned by tool ${m.tool} (${g})`}}}const Z=m?.kind==="message"&&m.role==="assistant";if(!k){const p=K(Z,m?.kind==="tool"?m.output:d);p&&(k={part:i,...N(p)})}const F=k?void 0:J(d,Z);F&&(k={part:i,...R(F)}),k&&I&&(k.since=I),k&&l?.chars&&(k.chars=l.chars);const T=k&&(!l||yt[k.how]>=yt[l.how])?k:l;if(T&&f&&T.how==="changed"){const p=new Set(E(o)),$=[...f.keys()].filter(A=>!p.has(A)).map(A=>A.replace(/#\d+$/,"")),g={changed:0,new:0},b=z(t,o,d);E(o).forEach((A,H)=>{const M=f.get(A);M?M.canon!==S(b[H]??"")&&g.changed++:g.new++});const q=[g.changed?`${g.changed} of ${o.sections.length} sections changed`:"",g.new?`${g.new} new`:"",$.length?`${$.length} gone (${$.slice(0,3).map(A=>`\xAB${A}\xBB`).join(", ")}${$.length>3?", \u2026":""})`:""].filter(Boolean);q.length&&(T.said+=`: ${q.join(", ")}`)}if(T&&u.items.push(T),!o.sections.length||T?.how==="answer"||T?.how==="tool-output")return;const At=z(t,o,d),jt=E(o),Bt=!!F;o.sections.forEach((p,$)=>{const g=At[$]??"";if(!g)return;let b;if(f){const L=f.get(jt[$]);L?L.canon===S(g)?b={part:i,section:p.title,how:"unchanged",from:B,said:"unchanged since the previous call"}:b={part:i,section:p.title,how:"changed",from:B,said:nt(L.text.length,g.length),chars:{before:L.text.length,after:g.length}}:b={part:i,section:p.title,how:"new",from:B,said:"new since the previous call"}}const q=p.at!==void 0&&p.title!=="(opening)"?g.indexOf(`
|
|
10
|
+
`):-1,A=K(Z,g,q>0?g.slice(q+1):void 0),H=A?void 0:Bt?J(g,Z):void 0,M=A?{part:i,section:p.title,...N(A)}:H?{part:i,section:p.title,...R(H)}:void 0,st=b?b.how:I!=="changed"?I:void 0;M&&st&&(M.since=st),M&&b?.chars&&(M.chars=b.chars);const it=M??b;it&&u.items.push(it)})}),u}v(aiOriginsOf,"aiOriginsOf"),c(aiOriginsOf,"aiOriginsOf");
|