@lensmcp/protocol-types 1.26.23 → 1.26.24

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 CHANGED
@@ -14,6 +14,7 @@ export * from './lib/bounded-map.js';
14
14
  export * from './lib/flood-guard.js';
15
15
  export * from './lib/dashboard.js';
16
16
  export * from './lib/dashboard-path.js';
17
+ export * from './lib/lens-hosts.js';
17
18
  export * from './lib/dashboard-lint.js';
18
19
  export * from './lib/dashboard-typecheck.js';
19
20
  export * from './lib/lint-coverage.js';
@@ -85,3 +86,7 @@ export { PROOF_ACTIONS, NOT_RUN_KINDS } from './lib/team-delivery.js';
85
86
  export type { NotRunKind } from './lib/team-delivery.js';
86
87
  export * from './lib/canvas.js';
87
88
  export * from './lib/canvas-catalog.js';
89
+ export * from './lib/canvas-frame-policy.js';
90
+ export * from './lib/canvas-attachments.js';
91
+ export * from './lib/canvas-editing.js';
92
+ export * from './lib/canvas-hub.js';
package/index.js CHANGED
@@ -1 +1 @@
1
- "use strict";export*from"./lib/schema-version.js";export*from"./lib/source-location.js";export*from"./lib/context.js";export*from"./lib/event.js";export*from"./lib/node.js";export*from"./lib/edge.js";export*from"./lib/attributes.js";export*from"./lib/producer-health.js";export*from"./lib/resources.js";export*from"./lib/tokens.js";export*from"./lib/capture-demand.js";export*from"./lib/bounded-clone.js";export*from"./lib/bounded-map.js";export*from"./lib/flood-guard.js";export*from"./lib/dashboard.js";export*from"./lib/dashboard-path.js";export*from"./lib/dashboard-lint.js";export*from"./lib/dashboard-typecheck.js";export*from"./lib/lint-coverage.js";export*from"./lib/lint-ignores.js";export*from"./lib/static-checks.js";export*from"./lib/log-query.js";export*from"./lib/error-dismissal.js";export*from"./lib/expected-failure.js";export*from"./lib/error-verdict.js";export*from"./lib/finding-proof.js";export*from"./lib/error-cause.js";export*from"./lib/metrics-reset.js";export*from"./lib/ai-content.js";export*from"./lib/http-exchange.js";export*from"./lib/ai-call.js";export*from"./lib/ai-call-row.js";export*from"./lib/ai-call-groups.js";export*from"./lib/ai-context.js";export*from"./lib/ai-cache-facts.js";export*from"./lib/ai-cache.js";export*from"./lib/ai-cache-verdict.js";export*from"./lib/ai-together.js";export*from"./lib/ai-origins.js";export*from"./lib/ai-playground.js";export*from"./lib/ai-compare.js";export*from"./lib/pod-memory.js";export*from"./lib/perf-rules.js";export*from"./lib/sources.js";export*from"./lib/page-visit.js";export*from"./lib/replay.js";export*from"./lib/event-loop.js";export*from"./lib/workspace-actions.js";export*from"./lib/docker-jobs.js";export*from"./lib/docker-report.js";export*from"./lib/docker-runs.js";export*from"./lib/docker-errors.js";export*from"./lib/peers.js";export*from"./lib/hosts.js";export*from"./lib/cluster-hosts.js";export*from"./lib/dashboard-updates.js";export*from"./lib/accounts.js";export*from"./lib/host-agents.js";export*from"./lib/remote-instances.js";export*from"./lib/team.js";export*from"./lib/sessions.js";export*from"./lib/conversations.js";export*from"./lib/backlog.js";export*from"./lib/team-review-changes.js";export*from"./lib/goal-outcome.js";export*from"./lib/role-fidelity.js";export*from"./lib/goal-retro.js";export*from"./lib/follow-ups.js";export*from"./lib/changes.js";export*from"./lib/main-mirror.js";export*from"./lib/team-design.js";export*from"./lib/team-library.js";export*from"./lib/team-skills.js";export*from"./lib/system-report.js";export*from"./lib/overseer-findings.js";export*from"./lib/overseer-rounds.js";export*from"./lib/goal-design.js";export*from"./lib/overseer-messages.js";export*from"./lib/team-roadmap.js";export*from"./lib/team-prompts.js";export{PROOF_ACTIONS,NOT_RUN_KINDS}from"./lib/team-delivery.js";export*from"./lib/canvas.js";export*from"./lib/canvas-catalog.js";
1
+ "use strict";export*from"./lib/schema-version.js";export*from"./lib/source-location.js";export*from"./lib/context.js";export*from"./lib/event.js";export*from"./lib/node.js";export*from"./lib/edge.js";export*from"./lib/attributes.js";export*from"./lib/producer-health.js";export*from"./lib/resources.js";export*from"./lib/tokens.js";export*from"./lib/capture-demand.js";export*from"./lib/bounded-clone.js";export*from"./lib/bounded-map.js";export*from"./lib/flood-guard.js";export*from"./lib/dashboard.js";export*from"./lib/dashboard-path.js";export*from"./lib/lens-hosts.js";export*from"./lib/dashboard-lint.js";export*from"./lib/dashboard-typecheck.js";export*from"./lib/lint-coverage.js";export*from"./lib/lint-ignores.js";export*from"./lib/static-checks.js";export*from"./lib/log-query.js";export*from"./lib/error-dismissal.js";export*from"./lib/expected-failure.js";export*from"./lib/error-verdict.js";export*from"./lib/finding-proof.js";export*from"./lib/error-cause.js";export*from"./lib/metrics-reset.js";export*from"./lib/ai-content.js";export*from"./lib/http-exchange.js";export*from"./lib/ai-call.js";export*from"./lib/ai-call-row.js";export*from"./lib/ai-call-groups.js";export*from"./lib/ai-context.js";export*from"./lib/ai-cache-facts.js";export*from"./lib/ai-cache.js";export*from"./lib/ai-cache-verdict.js";export*from"./lib/ai-together.js";export*from"./lib/ai-origins.js";export*from"./lib/ai-playground.js";export*from"./lib/ai-compare.js";export*from"./lib/pod-memory.js";export*from"./lib/perf-rules.js";export*from"./lib/sources.js";export*from"./lib/page-visit.js";export*from"./lib/replay.js";export*from"./lib/event-loop.js";export*from"./lib/workspace-actions.js";export*from"./lib/docker-jobs.js";export*from"./lib/docker-report.js";export*from"./lib/docker-runs.js";export*from"./lib/docker-errors.js";export*from"./lib/peers.js";export*from"./lib/hosts.js";export*from"./lib/cluster-hosts.js";export*from"./lib/dashboard-updates.js";export*from"./lib/accounts.js";export*from"./lib/host-agents.js";export*from"./lib/remote-instances.js";export*from"./lib/team.js";export*from"./lib/sessions.js";export*from"./lib/conversations.js";export*from"./lib/backlog.js";export*from"./lib/team-review-changes.js";export*from"./lib/goal-outcome.js";export*from"./lib/role-fidelity.js";export*from"./lib/goal-retro.js";export*from"./lib/follow-ups.js";export*from"./lib/changes.js";export*from"./lib/main-mirror.js";export*from"./lib/team-design.js";export*from"./lib/team-library.js";export*from"./lib/team-skills.js";export*from"./lib/system-report.js";export*from"./lib/overseer-findings.js";export*from"./lib/overseer-rounds.js";export*from"./lib/goal-design.js";export*from"./lib/overseer-messages.js";export*from"./lib/team-roadmap.js";export*from"./lib/team-prompts.js";export{PROOF_ACTIONS,NOT_RUN_KINDS}from"./lib/team-delivery.js";export*from"./lib/canvas.js";export*from"./lib/canvas-catalog.js";export*from"./lib/canvas-frame-policy.js";export*from"./lib/canvas-attachments.js";export*from"./lib/canvas-editing.js";export*from"./lib/canvas-hub.js";
@@ -103,7 +103,7 @@ export interface AiCacheRates {
103
103
  }
104
104
  export type AiCacheRatesOf = (model: string, inputTokens: number) => AiCacheRates | undefined;
105
105
  /** The rows the verdicts need — what an index row carries. */
106
- type Row = Pick<AiCallRow, 'id' | 'at' | 'durationMs' | 'agent' | 'model' | 'provider' | 'tokens' | 'cache' | 'prewarm' | 'failed' | 'api'>;
106
+ type Row = Pick<AiCallRow, 'id' | 'at' | 'durationMs' | 'agent' | 'model' | 'provider' | 'tokens' | 'cache' | 'prewarm' | 'failed' | 'api' | 'noUsage'>;
107
107
  /**
108
108
  * Every row's verdict, by id — rows with no cache (an embedding) have none. `now` decides which writes may still be
109
109
  * read (their lifetime has not run out).
@@ -1 +1 @@
1
- "use strict";var Ct=Object.defineProperty;var F=(e,o)=>Ct(e,"name",{value:o,configurable:!0});var Ut=Object.defineProperty,k=F((e,o)=>Ut(e,"name",{value:o,configurable:!0}),"w");import{AI_CACHE_TTL_MS as et,AI_GUIDANCE_SOURCES as kt,aiCacheMinTokens as It,aiGuidanceAge as Dt}from"./ai-cache-facts.js";export const AI_CACHE_VERDICT_LABEL={read:"read","first-writer":"first writer","duplicate-write":"duplicate write","broken-prefix":"broken prefix",cold:"cold","write-nothing-read":"write nothing read","no-cache":"no cache",unknown:"unknown"};const b=k(e=>Math.round(e).toLocaleString("en-US"),"fmt"),ot=k(e=>`$${e<.01&&e>0?e.toFixed(4):e.toFixed(2)}`,"money"),R=k(e=>`$${Number(e.toFixed(4))}`,"rate"),_=k(e=>Math.round(e*1e6)/1e6,"usd"),V=k(e=>e<1e3?`${Math.round(e)} ms`:e<12e4?`${(e/1e3).toFixed(1)} s`:e<72e5?`${Math.round(e/6e4)} min`:`${(e/36e5).toFixed(1)} h`,"dur"),Et=k(e=>e.tokens?.input!==void 0&&e.cache!==void 0&&!e.failed,"counted");export function aiCacheVerdicts(e,o,g=Date.now()){const h=new Map,l=new Map;for(const d of e){if(!d.cache)continue;const i=l.get(d.agent.key);i?i.push(d):l.set(d.agent.key,[d])}for(const d of l.values()){d.sort((i,s)=>i.at-s.at||i.id.localeCompare(s.id));for(const[i,s]of $t(d,o,g))h.set(i,s)}return h}F(aiCacheVerdicts,"aiCacheVerdicts"),k(aiCacheVerdicts,"aiCacheVerdicts");function gt(e,o){const g=e==="anthropic"?kt.anthropicCaching:kt.openaiCaching;return{source:g.url,readAt:g.readAt,...Dt(g.readAt,o).stale?{stale:!0}:{}}}F(gt,"It"),k(gt,"factsOf");function $t(e,o,g){const h=[],l=new Map,d=new Map;e.forEach((i,s)=>{const n=i.cache,$=i.at,x=i.durationMs!==void 0?i.at+i.durationMs:void 0,I=et[n.ttl],a={row:i,start:$,...x!==void 0?{end:x}:{},ttlMs:I,wrote:[]};h.push(a);const r=n.marks??[],w=r.filter(t=>t.bp),A=i.tokens?.input??0,m=i.tokens?.cached??0,f=i.tokens?.written??0,v=Et(i),c=i.model?o(i.model,A):void 0,J=gt(i.provider,g),K={...c?{price:{...c.source?{source:c.source}:{},...c.readAt?{readAt:c.readAt}:{},...c.stale?{stale:!0}:{}}}:{},facts:J},Z=k(()=>{for(const t of r){const u=d.get(t.h);u?u.push(s):d.set(t.h,[s])}},"remember"),tt=k((t,u)=>{const p=l.get(t);p?p.push({i:s,how:u}):l.set(t,[{i:s,how:u}])},"hold"),Q=It(i.provider,i.model);if(!v){if(!i.failed)for(const t of w)tt(t.h,"unknown");Z(),a.verdict=it(n,A,Q,K)??{kind:"unknown",said:i.failed?"It failed \u2014 the provider counted nothing for it.":"Its token count was not kept (the answer was cut by the capture): no verdict.",costs:[],basis:K},i.prewarm&&(a.verdict.prewarm=!0);return}const O=it(n,A,Q,K);if(O){const t=st(a,h,d,s);if(t&&t.tokens>=Q&&c){const u=c.cacheRead??c.input,p=t.tokens*(c.input-u)/1e6;O.costs.push({kind:"no-cache",tokens:t.tokens,usd:_(p),arithmetic:`${b(t.tokens)} \xD7 (${R(c.input)} \u2212 ${R(u)})/M`,estimate:!0}),O.lostUsd=_(p),O.said+=` It shares \u2248 ${b(t.tokens)} tokens with ${t.id} (${V($-h[t.i].start)} before): read from a cache, they would cost \u2248 ${ot(p)} less.`}i.prewarm&&(O.prewarm=!0),a.verdict=O,Z();return}const z=Math.max(256,A*.03),xt=k((t,u)=>u.reduce((p,B)=>!p||Math.abs(B.t-t)<Math.abs(p.t-t)?B:p,void 0),"nearest");let S=-1;if(m>0){const t=xt(m,w.length?w:r);t&&Math.abs(t.t-m)<=Math.max(z,m*.15)&&(a.readBp={h:t.h,t:t.t,s:t.s},S=w.indexOf(t))}w.forEach((t,u)=>(u<=S||S<0&&t.t<=m+z)&&tt(t.h,"read"));const at=w.filter((t,u)=>S>=0?u>S:t.t>m+z),vt=S>=0?w[S].t:m;let D=f>0?at.filter(t=>t.t<=vt+f+Math.max(z,f*.15)):[];if(f>0&&!D.length){const t=at[0]??w[w.length-1];D=t?[t]:[]}const nt=D.map((t,u)=>Math.max(1,t.t-(u?D[u-1].t:Math.max(m,w.filter(p=>p.t<t.t).pop()?.t??0)))),Bt=nt.reduce((t,u)=>t+u,0);D.forEach((t,u)=>{const p=D.length===1?f:Math.round(nt[u]/Bt*f),B=n.breakpoints.find(U=>Math.abs(U.tokens-t.t)<=1)?.ttl??n.ttl,N=et[B],T=(l.get(t.h)??[]).filter(U=>U.i<s),W=T.filter(U=>$-h[U.i].start<=N);if(W.length){const U=k(M=>h[M.i].end!==void 0&&h[M.i].end<=$,"done"),q=k(M=>M[M.length-1],"last"),ft=W.filter(M=>M.how==="wrote"),pt=W.filter(M=>M.how==="unknown"),wt=q(ft.filter(U))??q(pt.filter(U)),mt=q(ft.filter(M=>!U(M)))??q(pt.filter(M=>!U(M))),bt=wt??mt??q(W),At=!wt&&!!mt,yt=W.filter(M=>M.how==="read").length;a.wrote.push({h:t.h,s:t.s,tokens:p,estimate:D.length>1,ttl:B,status:"duplicate",against:bt,race:At,readFirst:yt})}else T.length?a.wrote.push({h:t.h,s:t.s,tokens:p,estimate:D.length>1,ttl:B,status:"cold",against:T[T.length-1],idleMs:$-h[T[T.length-1].i].start}):a.wrote.push({h:t.h,s:t.s,tokens:p,estimate:D.length>1,ttl:B,status:"first"});tt(t.h,"wrote")});const y=st(a,h,d,s);Z();const L=c?c.cacheRead??c.input:void 0,dt=c?Y(c,n.writes,n.ttl):void 0,H=[];let X,ct;if(y){const t=w.filter(B=>B.t<=y.tokens+1&&y.hashes.has(B.h)).reduce((B,N)=>Math.max(B,N.t),0),u=Math.max(m,t),p=y.tokens-u;if(y.tokens>=Q&&p>z){X={region:y.next??"(the end of the prompt)",tokens:y.tokens,id:h[y.i].row.id},ct=h[y.i];const B=m+f>=y.tokens-z,N=c?B?dt-L:c.input-L:void 0;H.push({kind:"broken-prefix",tokens:p,estimate:!0,...N!==void 0?{usd:_(p*N/1e6),arithmetic:`${b(p)} \xD7 (${R(B?dt:c.input)} \u2212 ${R(L)})/M`}:{}})}}for(const t of a.wrote){if(t.status==="first")continue;const u=c?Y(c,n.writes,t.ttl):void 0;H.push({kind:t.status==="duplicate"?"duplicate-write":"cold",tokens:t.tokens,estimate:t.estimate,...c?{usd:_(t.tokens*(u-L)/1e6),arithmetic:`${b(t.tokens)} \xD7 (${R(u)} \u2212 ${R(L)})/M`}:{}})}const C=[];a.wrote.some(t=>t.status==="duplicate")&&C.push("duplicate-write"),X&&C.push("broken-prefix"),a.wrote.some(t=>t.status==="cold")&&C.push("cold"),a.wrote.some(t=>t.status==="first")&&C.push("first-writer"),m>0&&C.push("read"),C.length||C.push("no-cache");const j=a.wrote.find(t=>t.status==="duplicate"),P=a.wrote.find(t=>t.status==="cold"),ht=j?.against??P?.against,E=ht?h[ht.i]:ct,ut=H.some(t=>t.usd!==void 0)?_(H.reduce((t,u)=>t+(u.usd??0),0)):void 0,lt=c&&m>0?_(m*(c.input-L)/1e6):void 0,Mt=C[0];a.verdict={kind:Mt,...C.length>1?{also:C.slice(1)}:{},said:"",costs:H,...ut!==void 0?{lostUsd:ut}:{},...lt!==void 0?{savedUsd:lt}:{},...j||P||a.wrote[0]||a.readBp?{prefix:(j??P??a.wrote[0])?.h??a.readBp.h}:{},read:m,written:f,...E?{against:{id:E.row.id,at:E.start,...E.end!==void 0?{ended:E.end}:{},inFlight:E.end===void 0||E.end>$,gapMs:$-E.start,...E.row.prewarm?{prewarm:!0}:{}}}:{},...j?{race:!!j.race,...j.readFirst?{readBefore:j.readFirst}:{}}:{},...X?{brokeAt:X}:{},...P?.idleMs!==void 0?{idleMs:P.idleMs}:{},...i.prewarm?{prewarm:!0}:{},basis:K}});for(const i of h){const s=i.verdict;if(!i.wrote.length){s.said=rt(i,s);continue}const n=new Set,$=new Set;let x=!1;const I=[];for(const a of i.wrote){const r=et[a.ttl],w=(l.get(a.h)??[]).filter(f=>h[f.i].start>i.start&&h[f.i].start-i.start<=r),A=w.filter(f=>f.how==="read"),m=w.filter(f=>f.how==="unknown");for(const f of A)n.add(f.i);for(const f of m)$.add(f.i);i.start+r>g?x=!0:!A.length&&!m.length&&I.push(a)}for(const a of n)$.delete(a);if(n.size&&(s.readBy=n.size),$.size&&(s.maybeReadBy=$.size),x&&(s.open=!0),I.length){const a=i.row,r=a.model?o(a.model,a.tokens?.input??0):void 0;let w=s.costs.find(v=>v.kind==="broken-prefix")?.tokens??0;for(const v of I){if(v.status!=="first")continue;const c=Math.max(0,v.tokens-w);if(w=0,!c)continue;const J=r?Y(r,a.cache.writes,v.ttl):void 0;s.costs.push({kind:"write-nothing-read",tokens:c,estimate:v.estimate||c!==v.tokens,...r?{usd:_(c*(J-r.input)/1e6),arithmetic:`${b(c)} \xD7 (${R(J)} \u2212 ${R(r.input)})/M`}:{}})}r&&(s.lostUsd=_(s.costs.reduce((v,c)=>v+(c.usd??0),0)));const A=[s.kind,...s.also??[]],m=A.findIndex(v=>v!=="duplicate-write"&&v!=="broken-prefix"&&v!=="cold");A.splice(m<0?A.length:m,0,"write-nothing-read"),s.kind=A[0];const f=A.slice(1);f.length?s.also=f:delete s.also}s.said=rt(i,s)}return new Map(h.map(i=>[i.row.id,i.verdict]))}F($t,"Ut"),k($t,"judgeAgent");function Y(e,o,g){const h=Object.entries(o??{}).filter(d=>typeof d[1]=="number"&&d[1]>0);if(h.length>1){const d=h.reduce((i,[,s])=>i+s,0);return h.reduce((i,[s,n])=>i+(e.writes[s]??e.input)*n,0)/d}const l=h[0]?.[0]??g;return e.writes[l]??e.input}F(Y,"et"),k(Y,"writeRate");function it(e,o,g,h){const l=k(d=>({kind:"no-cache",said:d,costs:[],basis:h}),"no");if(e.mode==="explicit"&&!e.breakpoints.length)return l("Explicit mode with no breakpoint: it read and wrote nothing.");if(e.mode==="none")return l("No `cache_control`: Anthropic cached nothing of it.");if(o>0&&o<g)return l(`${b(o)} input tokens \u2014 under the ${b(g)}-token minimum: nothing is cached.`)}F(it,"pt"),k(it,"structural");function st(e,o,g,h){const l=e.row.cache?.marks??[];let d;for(let s=0;s<l.length;s++){const n=g.get(l[s].h);if(n)for(let $=n.length-1;$>=0;$--){const x=n[$];if(!(x>=h)){if(e.start-o[x].start>e.ttlMs)break;d={i:x,at:s};break}}}if(!d)return;const i=o[d.i];return{i:d.i,id:i.row.id,tokens:l[d.at].t,...l[d.at+1]?{next:l[d.at+1].s}:{},hashes:new Set((i.row.cache?.marks??[]).map(s=>s.h))}}F(st,"wt"),k(st,"sharedWith");const G=k(e=>e.split(" \u203A ")[0],"block");function rt(e,o){if(o.said)return o.said;const g=e.row,h=g.cache,l=g.tokens?.input??0,d=o.read??0,i=o.written??0,s=h.ttl,n=[],$=o.prewarm?"A prewarm (it answers nothing): it ":"It ";n.push(`${$}read ${b(d)} of its ${b(l)} input tokens from the cache${i?` and wrote ${b(i)}`:""} (${h.mode} mode, ${s}).`);const x=e.wrote.find(r=>r.status==="duplicate");if(x&&o.against){const r=o.against,w=o.readBefore?` ${b(o.readBefore)} call${o.readBefore===1?"":"s"} sent before this one read it.`:"";n.push(o.race?`Duplicate write \u2014 a race: ${r.id}${x.against?.how==="unknown"?" (its count was not kept: it may have)":""} wrote the same prefix (to the end of \xAB${G(x.s)}\xBB) and was still in flight when this one was sent, ${V(r.gapMs)} after it.${w}`:x.against?.how==="read"?`Duplicate write: ${r.id} had read the same prefix (to the end of \xAB${G(x.s)}\xBB) ${V(r.gapMs)} before \u2014 the entry was there, and this call did not read it.`:`Duplicate write: ${r.id}${r.prewarm?" (a prewarm)":""}${x.against?.how==="unknown"?" (its count was not kept: it may have)":""} wrote the same prefix (to the end of \xAB${G(x.s)}\xBB) ${V(r.gapMs)} before${r.ended!==void 0&&r.ended<=e.start?` and had ended ${V(e.start-r.ended)} before this one was sent \u2014 not a race: the write had finished and this call did not read it`:""}.${w}`)}o.brokeAt&&n.push(`Broken prefix: it shares \u2248 ${b(o.brokeAt.tokens)} tokens with ${o.brokeAt.id}, then they part in \xAB${o.brokeAt.region}\xBB \u2014 no breakpoint ends where they part, so it read only ${b(d)}.`);const I=e.wrote.find(r=>r.status==="cold");I&&o.idleMs!==void 0&&n.push(`Cold: the same prefix (to the end of \xAB${G(I.s)}\xBB) was last used ${V(o.idleMs)} before \u2014 past its ${I.ttl} lifetime.`);const a=e.wrote.filter(r=>r.status==="first");return a.length&&n.push(`First writer of the prefix to the end of \xAB${a.map(r=>G(r.s)).join("\xBB, \xAB")}\xBB.`),e.wrote.length&&(o.kind==="write-nothing-read"||o.also?.includes("write-nothing-read")?n.push("No later call of its agent read what it wrote inside its lifetime."):o.readBy?n.push(`${b(o.readBy)} later call${o.readBy===1?"":"s"} read what it wrote.`):o.maybeReadBy?n.push(`${b(o.maybeReadBy)} later call${o.maybeReadBy===1?"":"s"} may have read it (their counts were not kept).`):o.open&&n.push("Its lifetime has not run out: a later call may still read it.")),!e.wrote.length&&d>0&&!o.brokeAt&&n.push(`Read${e.readBp?` to the end of \xAB${G(e.readBp.s)}\xBB`:""}.`),o.lostUsd!==void 0&&o.lostUsd>0&&n.push(`\u2248 ${ot(o.lostUsd)} lost: ${o.costs.filter(r=>r.arithmetic).map(r=>`${r.arithmetic}${r.estimate?" (estimate)":""}`).join(" + ")}.`),o.savedUsd&&n.push(`Its reads saved \u2248 ${ot(o.savedUsd)} against plain input.`),n.join(" ")}F(rt,"kt"),k(rt,"said");
1
+ "use strict";var Ct=Object.defineProperty;var F=(e,o)=>Ct(e,"name",{value:o,configurable:!0});var It=Object.defineProperty,k=F((e,o)=>It(e,"name",{value:o,configurable:!0}),"w");import{AI_CACHE_TTL_MS as et,AI_GUIDANCE_SOURCES as kt,aiCacheMinTokens as Ut,aiGuidanceAge as Dt}from"./ai-cache-facts.js";export const AI_CACHE_VERDICT_LABEL={read:"read","first-writer":"first writer","duplicate-write":"duplicate write","broken-prefix":"broken prefix",cold:"cold","write-nothing-read":"write nothing read","no-cache":"no cache",unknown:"unknown"};const b=k(e=>Math.round(e).toLocaleString("en-US"),"fmt"),ot=k(e=>`$${e<.01&&e>0?e.toFixed(4):e.toFixed(2)}`,"money"),R=k(e=>`$${Number(e.toFixed(4))}`,"rate"),_=k(e=>Math.round(e*1e6)/1e6,"usd"),V=k(e=>e<1e3?`${Math.round(e)} ms`:e<12e4?`${(e/1e3).toFixed(1)} s`:e<72e5?`${Math.round(e/6e4)} min`:`${(e/36e5).toFixed(1)} h`,"dur"),Et=k(e=>e.tokens?.input!==void 0&&e.cache!==void 0&&!e.failed,"counted");export function aiCacheVerdicts(e,o,g=Date.now()){const h=new Map,l=new Map;for(const d of e){if(!d.cache)continue;const i=l.get(d.agent.key);i?i.push(d):l.set(d.agent.key,[d])}for(const d of l.values()){d.sort((i,s)=>i.at-s.at||i.id.localeCompare(s.id));for(const[i,s]of $t(d,o,g))h.set(i,s)}return h}F(aiCacheVerdicts,"aiCacheVerdicts"),k(aiCacheVerdicts,"aiCacheVerdicts");function gt(e,o){const g=e==="anthropic"?kt.anthropicCaching:kt.openaiCaching;return{source:g.url,readAt:g.readAt,...Dt(g.readAt,o).stale?{stale:!0}:{}}}F(gt,"Ut"),k(gt,"factsOf");function $t(e,o,g){const h=[],l=new Map,d=new Map;e.forEach((i,s)=>{const n=i.cache,$=i.at,x=i.durationMs!==void 0?i.at+i.durationMs:void 0,U=et[n.ttl],a={row:i,start:$,...x!==void 0?{end:x}:{},ttlMs:U,wrote:[]};h.push(a);const r=n.marks??[],w=r.filter(t=>t.bp),A=i.tokens?.input??0,m=i.tokens?.cached??0,f=i.tokens?.written??0,v=Et(i),c=i.model?o(i.model,A):void 0,J=gt(i.provider,g),K={...c?{price:{...c.source?{source:c.source}:{},...c.readAt?{readAt:c.readAt}:{},...c.stale?{stale:!0}:{}}}:{},facts:J},Z=k(()=>{for(const t of r){const u=d.get(t.h);u?u.push(s):d.set(t.h,[s])}},"remember"),tt=k((t,u)=>{const p=l.get(t);p?p.push({i:s,how:u}):l.set(t,[{i:s,how:u}])},"hold"),Q=Ut(i.provider,i.model);if(!v){if(!i.failed)for(const t of w)tt(t.h,"unknown");Z(),a.verdict=it(n,A,Q,K)??{kind:"unknown",said:i.failed?"It failed \u2014 the provider counted nothing for it.":i.noUsage?`${i.noUsage.said} No verdict.`:"Its token count was not kept (the answer was cut by the capture): no verdict.",costs:[],basis:K},i.prewarm&&(a.verdict.prewarm=!0);return}const O=it(n,A,Q,K);if(O){const t=st(a,h,d,s);if(t&&t.tokens>=Q&&c){const u=c.cacheRead??c.input,p=t.tokens*(c.input-u)/1e6;O.costs.push({kind:"no-cache",tokens:t.tokens,usd:_(p),arithmetic:`${b(t.tokens)} \xD7 (${R(c.input)} \u2212 ${R(u)})/M`,estimate:!0}),O.lostUsd=_(p),O.said+=` It shares \u2248 ${b(t.tokens)} tokens with ${t.id} (${V($-h[t.i].start)} before): read from a cache, they would cost \u2248 ${ot(p)} less.`}i.prewarm&&(O.prewarm=!0),a.verdict=O,Z();return}const N=Math.max(256,A*.03),xt=k((t,u)=>u.reduce((p,B)=>!p||Math.abs(B.t-t)<Math.abs(p.t-t)?B:p,void 0),"nearest");let S=-1;if(m>0){const t=xt(m,w.length?w:r);t&&Math.abs(t.t-m)<=Math.max(N,m*.15)&&(a.readBp={h:t.h,t:t.t,s:t.s},S=w.indexOf(t))}w.forEach((t,u)=>(u<=S||S<0&&t.t<=m+N)&&tt(t.h,"read"));const at=w.filter((t,u)=>S>=0?u>S:t.t>m+N),vt=S>=0?w[S].t:m;let D=f>0?at.filter(t=>t.t<=vt+f+Math.max(N,f*.15)):[];if(f>0&&!D.length){const t=at[0]??w[w.length-1];D=t?[t]:[]}const nt=D.map((t,u)=>Math.max(1,t.t-(u?D[u-1].t:Math.max(m,w.filter(p=>p.t<t.t).pop()?.t??0)))),Bt=nt.reduce((t,u)=>t+u,0);D.forEach((t,u)=>{const p=D.length===1?f:Math.round(nt[u]/Bt*f),B=n.breakpoints.find(I=>Math.abs(I.tokens-t.t)<=1)?.ttl??n.ttl,L=et[B],T=(l.get(t.h)??[]).filter(I=>I.i<s),W=T.filter(I=>$-h[I.i].start<=L);if(W.length){const I=k(M=>h[M.i].end!==void 0&&h[M.i].end<=$,"done"),q=k(M=>M[M.length-1],"last"),ft=W.filter(M=>M.how==="wrote"),pt=W.filter(M=>M.how==="unknown"),wt=q(ft.filter(I))??q(pt.filter(I)),mt=q(ft.filter(M=>!I(M)))??q(pt.filter(M=>!I(M))),bt=wt??mt??q(W),At=!wt&&!!mt,yt=W.filter(M=>M.how==="read").length;a.wrote.push({h:t.h,s:t.s,tokens:p,estimate:D.length>1,ttl:B,status:"duplicate",against:bt,race:At,readFirst:yt})}else T.length?a.wrote.push({h:t.h,s:t.s,tokens:p,estimate:D.length>1,ttl:B,status:"cold",against:T[T.length-1],idleMs:$-h[T[T.length-1].i].start}):a.wrote.push({h:t.h,s:t.s,tokens:p,estimate:D.length>1,ttl:B,status:"first"});tt(t.h,"wrote")});const y=st(a,h,d,s);Z();const z=c?c.cacheRead??c.input:void 0,dt=c?Y(c,n.writes,n.ttl):void 0,H=[];let X,ct;if(y){const t=w.filter(B=>B.t<=y.tokens+1&&y.hashes.has(B.h)).reduce((B,L)=>Math.max(B,L.t),0),u=Math.max(m,t),p=y.tokens-u;if(y.tokens>=Q&&p>N){X={region:y.next??"(the end of the prompt)",tokens:y.tokens,id:h[y.i].row.id},ct=h[y.i];const B=m+f>=y.tokens-N,L=c?B?dt-z:c.input-z:void 0;H.push({kind:"broken-prefix",tokens:p,estimate:!0,...L!==void 0?{usd:_(p*L/1e6),arithmetic:`${b(p)} \xD7 (${R(B?dt:c.input)} \u2212 ${R(z)})/M`}:{}})}}for(const t of a.wrote){if(t.status==="first")continue;const u=c?Y(c,n.writes,t.ttl):void 0;H.push({kind:t.status==="duplicate"?"duplicate-write":"cold",tokens:t.tokens,estimate:t.estimate,...c?{usd:_(t.tokens*(u-z)/1e6),arithmetic:`${b(t.tokens)} \xD7 (${R(u)} \u2212 ${R(z)})/M`}:{}})}const C=[];a.wrote.some(t=>t.status==="duplicate")&&C.push("duplicate-write"),X&&C.push("broken-prefix"),a.wrote.some(t=>t.status==="cold")&&C.push("cold"),a.wrote.some(t=>t.status==="first")&&C.push("first-writer"),m>0&&C.push("read"),C.length||C.push("no-cache");const j=a.wrote.find(t=>t.status==="duplicate"),P=a.wrote.find(t=>t.status==="cold"),ht=j?.against??P?.against,E=ht?h[ht.i]:ct,ut=H.some(t=>t.usd!==void 0)?_(H.reduce((t,u)=>t+(u.usd??0),0)):void 0,lt=c&&m>0?_(m*(c.input-z)/1e6):void 0,Mt=C[0];a.verdict={kind:Mt,...C.length>1?{also:C.slice(1)}:{},said:"",costs:H,...ut!==void 0?{lostUsd:ut}:{},...lt!==void 0?{savedUsd:lt}:{},...j||P||a.wrote[0]||a.readBp?{prefix:(j??P??a.wrote[0])?.h??a.readBp.h}:{},read:m,written:f,...E?{against:{id:E.row.id,at:E.start,...E.end!==void 0?{ended:E.end}:{},inFlight:E.end===void 0||E.end>$,gapMs:$-E.start,...E.row.prewarm?{prewarm:!0}:{}}}:{},...j?{race:!!j.race,...j.readFirst?{readBefore:j.readFirst}:{}}:{},...X?{brokeAt:X}:{},...P?.idleMs!==void 0?{idleMs:P.idleMs}:{},...i.prewarm?{prewarm:!0}:{},basis:K}});for(const i of h){const s=i.verdict;if(!i.wrote.length){s.said=rt(i,s);continue}const n=new Set,$=new Set;let x=!1;const U=[];for(const a of i.wrote){const r=et[a.ttl],w=(l.get(a.h)??[]).filter(f=>h[f.i].start>i.start&&h[f.i].start-i.start<=r),A=w.filter(f=>f.how==="read"),m=w.filter(f=>f.how==="unknown");for(const f of A)n.add(f.i);for(const f of m)$.add(f.i);i.start+r>g?x=!0:!A.length&&!m.length&&U.push(a)}for(const a of n)$.delete(a);if(n.size&&(s.readBy=n.size),$.size&&(s.maybeReadBy=$.size),x&&(s.open=!0),U.length){const a=i.row,r=a.model?o(a.model,a.tokens?.input??0):void 0;let w=s.costs.find(v=>v.kind==="broken-prefix")?.tokens??0;for(const v of U){if(v.status!=="first")continue;const c=Math.max(0,v.tokens-w);if(w=0,!c)continue;const J=r?Y(r,a.cache.writes,v.ttl):void 0;s.costs.push({kind:"write-nothing-read",tokens:c,estimate:v.estimate||c!==v.tokens,...r?{usd:_(c*(J-r.input)/1e6),arithmetic:`${b(c)} \xD7 (${R(J)} \u2212 ${R(r.input)})/M`}:{}})}r&&(s.lostUsd=_(s.costs.reduce((v,c)=>v+(c.usd??0),0)));const A=[s.kind,...s.also??[]],m=A.findIndex(v=>v!=="duplicate-write"&&v!=="broken-prefix"&&v!=="cold");A.splice(m<0?A.length:m,0,"write-nothing-read"),s.kind=A[0];const f=A.slice(1);f.length?s.also=f:delete s.also}s.said=rt(i,s)}return new Map(h.map(i=>[i.row.id,i.verdict]))}F($t,"It"),k($t,"judgeAgent");function Y(e,o,g){const h=Object.entries(o??{}).filter(d=>typeof d[1]=="number"&&d[1]>0);if(h.length>1){const d=h.reduce((i,[,s])=>i+s,0);return h.reduce((i,[s,n])=>i+(e.writes[s]??e.input)*n,0)/d}const l=h[0]?.[0]??g;return e.writes[l]??e.input}F(Y,"et"),k(Y,"writeRate");function it(e,o,g,h){const l=k(d=>({kind:"no-cache",said:d,costs:[],basis:h}),"no");if(e.mode==="explicit"&&!e.breakpoints.length)return l("Explicit mode with no breakpoint: it read and wrote nothing.");if(e.mode==="none")return l("No `cache_control`: Anthropic cached nothing of it.");if(o>0&&o<g)return l(`${b(o)} input tokens \u2014 under the ${b(g)}-token minimum: nothing is cached.`)}F(it,"pt"),k(it,"structural");function st(e,o,g,h){const l=e.row.cache?.marks??[];let d;for(let s=0;s<l.length;s++){const n=g.get(l[s].h);if(n)for(let $=n.length-1;$>=0;$--){const x=n[$];if(!(x>=h)){if(e.start-o[x].start>e.ttlMs)break;d={i:x,at:s};break}}}if(!d)return;const i=o[d.i];return{i:d.i,id:i.row.id,tokens:l[d.at].t,...l[d.at+1]?{next:l[d.at+1].s}:{},hashes:new Set((i.row.cache?.marks??[]).map(s=>s.h))}}F(st,"wt"),k(st,"sharedWith");const G=k(e=>e.split(" \u203A ")[0],"block");function rt(e,o){if(o.said)return o.said;const g=e.row,h=g.cache,l=g.tokens?.input??0,d=o.read??0,i=o.written??0,s=h.ttl,n=[],$=o.prewarm?"A prewarm (it answers nothing): it ":"It ";n.push(`${$}read ${b(d)} of its ${b(l)} input tokens from the cache${i?` and wrote ${b(i)}`:""} (${h.mode} mode, ${s}).`);const x=e.wrote.find(r=>r.status==="duplicate");if(x&&o.against){const r=o.against,w=o.readBefore?` ${b(o.readBefore)} call${o.readBefore===1?"":"s"} sent before this one read it.`:"";n.push(o.race?`Duplicate write \u2014 a race: ${r.id}${x.against?.how==="unknown"?" (its count was not kept: it may have)":""} wrote the same prefix (to the end of \xAB${G(x.s)}\xBB) and was still in flight when this one was sent, ${V(r.gapMs)} after it.${w}`:x.against?.how==="read"?`Duplicate write: ${r.id} had read the same prefix (to the end of \xAB${G(x.s)}\xBB) ${V(r.gapMs)} before \u2014 the entry was there, and this call did not read it.`:`Duplicate write: ${r.id}${r.prewarm?" (a prewarm)":""}${x.against?.how==="unknown"?" (its count was not kept: it may have)":""} wrote the same prefix (to the end of \xAB${G(x.s)}\xBB) ${V(r.gapMs)} before${r.ended!==void 0&&r.ended<=e.start?` and had ended ${V(e.start-r.ended)} before this one was sent \u2014 not a race: the write had finished and this call did not read it`:""}.${w}`)}o.brokeAt&&n.push(`Broken prefix: it shares \u2248 ${b(o.brokeAt.tokens)} tokens with ${o.brokeAt.id}, then they part in \xAB${o.brokeAt.region}\xBB \u2014 no breakpoint ends where they part, so it read only ${b(d)}.`);const U=e.wrote.find(r=>r.status==="cold");U&&o.idleMs!==void 0&&n.push(`Cold: the same prefix (to the end of \xAB${G(U.s)}\xBB) was last used ${V(o.idleMs)} before \u2014 past its ${U.ttl} lifetime.`);const a=e.wrote.filter(r=>r.status==="first");return a.length&&n.push(`First writer of the prefix to the end of \xAB${a.map(r=>G(r.s)).join("\xBB, \xAB")}\xBB.`),e.wrote.length&&(o.kind==="write-nothing-read"||o.also?.includes("write-nothing-read")?n.push("No later call of its agent read what it wrote inside its lifetime."):o.readBy?n.push(`${b(o.readBy)} later call${o.readBy===1?"":"s"} read what it wrote.`):o.maybeReadBy?n.push(`${b(o.maybeReadBy)} later call${o.maybeReadBy===1?"":"s"} may have read it (their counts were not kept).`):o.open&&n.push("Its lifetime has not run out: a later call may still read it.")),!e.wrote.length&&d>0&&!o.brokeAt&&n.push(`Read${e.readBp?` to the end of \xAB${G(e.readBp.s)}\xBB`:""}.`),o.lostUsd!==void 0&&o.lostUsd>0&&n.push(`\u2248 ${ot(o.lostUsd)} lost: ${o.costs.filter(r=>r.arithmetic).map(r=>`${r.arithmetic}${r.estimate?" (estimate)":""}`).join(" + ")}.`),o.savedUsd&&n.push(`Its reads saved \u2248 ${ot(o.savedUsd)} against plain input.`),n.join(" ")}F(rt,"kt"),k(rt,"said");
@@ -32,6 +32,15 @@ export interface AiNamed {
32
32
  name: string;
33
33
  from: AiNameSource;
34
34
  }
35
+ /**
36
+ * Why a kept call has no token counts (foodguard-302): `failed`, the provider counted nothing for it; `cut`, the
37
+ * capture did not keep the end of its answer, where the counts come; `not-kept`, its answer was not kept (an AI
38
+ * provider's bodies only when asked for); `not-sent`, its answer was kept whole and carried none. `said`: in words.
39
+ */
40
+ export interface AiNoUsage {
41
+ why: 'failed' | 'cut' | 'not-kept' | 'not-sent';
42
+ said: string;
43
+ }
35
44
  export interface AiCallRow {
36
45
  /** The exchange's id (`hx_…`): the call's page is `/ai/calls/<id>`. */
37
46
  id: string;
@@ -99,6 +108,8 @@ export interface AiCallRow {
99
108
  meta?: Record<string, string>;
100
109
  /** A body was cut by the capture: some of the call is not readable. */
101
110
  cut?: true;
111
+ /** Why it has no token counts, when it has none ({@link AiNoUsage}): what a reader says instead of a cost or a cache verdict. */
112
+ noUsage?: AiNoUsage;
102
113
  /** What it was last given and what it answered, a line each — only where content may be shown. */
103
114
  asked?: string;
104
115
  said?: string;
@@ -1,3 +1,3 @@
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(`
1
+ "use strict";var B=Object.defineProperty;var m=(t,o)=>B(t,"name",{value:o,configurable:!0});var T=Object.defineProperty,c=m((t,o)=>T(t,"name",{value:o,configurable:!0}),"d");import{aiCallOf as z}from"./ai-call.js";import{aiContextOf as q,aiSplitOf as E}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 K=160,A="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=K)=>{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
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");
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"),U=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 _(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(_,"B"),c(_,"metaOf");function N(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??A} ${o.api==="embeddings"?"embeddings":o.model??o.api}`,"service")}m(N,"E"),c(N,"agentOf");function R(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(R,"x"),c(R,"actionOf");function L(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(L,"z"),c(L,"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,"A"),c(v,"saidLine");function S(t,o){if(o)return{why:"failed",said:"It failed \u2014 the provider counted nothing for it."};const e=t.gaps.find(a=>/^The (answer|stream)\b/.test(a)||/of the stream’s events were kept/.test(a));return e&&/was not kept|only each event’s name/.test(e)?{why:"not-kept",said:e}:e?{why:"cut",said:`Its token counts were not kept: ${e}`}:{why:"not-sent",said:"Its answer was kept whole, and the provider counted no tokens in it."}}m(S,"q"),c(S,"noUsageOf");export function aiCallRow(t,o){const e=z(t);if(!e||!t.ai)return;const a=_(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?{}:E(q(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(),b=h(a,"parent_run","parentRun","parent")??g(t,"x-lensmcp-parent")?.trim(),x=R(t,e,a),$=U(a.round),O=U(a.attempt),I=n.get("continues response"),C=[...e.turns].reverse().map(L).find(Boolean),M=e.answer.status==="failed"||!!e.answer.error||(t.status??0)>=400||!!t.error,j=p&&Object.keys(p).length?void 0:S(e,M);return{id:t.id,at:t.startedAt,...t.durationMs!==void 0?{durationMs:t.durationMs}:{},...t.status!==void 0?{status:t.status}:{},...M?{failed:!0}:{},service:t.service??A,...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:N(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"}}:{},...b?{parent:`run:${b}`}:{},...$!==void 0?{round:$}:{},...O!==void 0?{attempt:O}:{},...x?{action:x}:{},...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}:{},...I?{previousResponseId:I}:{},...Object.keys(a).length?{meta:a}:{},...e.gaps.some(d=>/kept to its first|cut/.test(d))?{cut:!0}:{},...j?{noUsage:j}:{},...o.content&&C?{asked:C}:{},...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.js CHANGED
@@ -1,19 +1,19 @@
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(`
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(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(`
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
- `);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(`
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($(o.replace(/_call$/,""),D(r),{callId:e(r.call_id)??e(r.id)}))}i.length&&(n.text=i.join(`
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(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(`
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 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(`
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
- `)),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");
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");
@@ -0,0 +1,80 @@
1
+ import type { CanvasActor, CanvasAsk } from './canvas.js';
2
+ /**
3
+ * Attachments in answers (planning/canvas §10 «Attachments in answers», issues canvas-11): a `Field kind="file"|"image"`
4
+ * is answered with a file the person picks in the DASHBOARD's own control, drawn over the frame like every answer control
5
+ * — the frame never sees the file. The upload is kept in the canvas's `assets/` beside its store, with TaskArtifact's
6
+ * types and caps (one table for both, here: the coordination store's artifacts read it too); the answer references it
7
+ * — `{ asset, name }` — and `canvas_get`/`canvas_wait` hand an agent the asset's path.
8
+ */
9
+ /**
10
+ * The types a task's artifact and a canvas attachment may have, and the extension its file is kept under. Nothing a
11
+ * browser runs: never HTML, never SVG.
12
+ */
13
+ export declare const TASK_ARTIFACT_TYPES: Readonly<Record<string, string>>;
14
+ /** One artifact's file, at most. */
15
+ export declare const TASK_ARTIFACT_MAX_BYTES: number;
16
+ /** A task's artifacts, and a canvas's attachments: at most this many… */
17
+ export declare const TASK_ARTIFACTS_MAX = 50;
18
+ /** …and this many bytes together. */
19
+ export declare const TASK_ARTIFACTS_MAX_BYTES: number;
20
+ /** The raster images an `image` field takes (and the html export keeps written in). */
21
+ export declare const CANVAS_IMAGE_TYPES: readonly string[];
22
+ /** `as-` and 12 hex: checked before any path is built from it. */
23
+ export declare const CANVAS_ASSET_ID_PATTERN: RegExp;
24
+ export declare const isCanvasAssetId: (id: unknown) => id is string;
25
+ /** An attachment, as the store keeps it: its bytes are the file `assets/<canvas>/<id>.<ext>`. */
26
+ export interface CanvasAsset {
27
+ id: string;
28
+ canvas: string;
29
+ /** The question it was uploaded for. */
30
+ qid: string;
31
+ /** The file's name as the person picked it (never a path). */
32
+ name: string;
33
+ mediaType: string;
34
+ bytes: number;
35
+ sha256: string;
36
+ by: CanvasActor;
37
+ at: number;
38
+ }
39
+ /** What a file or image answer holds: the asset, and the name the person sees. */
40
+ export interface CanvasAssetRef {
41
+ asset: string;
42
+ name: string;
43
+ }
44
+ /** The asset an answer's value references, if it is a file or image answer's `{ asset, name }`. */
45
+ export declare function canvasAnswerAsset(value: unknown): CanvasAssetRef | undefined;
46
+ /** Whether a question is answered with a file (`Field kind="file"|"image"`). */
47
+ export declare const isCanvasAttachAsk: (ask: Pick<CanvasAsk, "kind">) => boolean;
48
+ /** The types a question takes: an image field, raster images; a file field, any attachment type. */
49
+ export declare const canvasAskTypes: (ask: Pick<CanvasAsk, "kind">) => readonly string[];
50
+ /** A file's size as the person reads it: `184 KB`, `2.4 MB`. */
51
+ export declare const canvasBytesWords: (n: number) => string;
52
+ export declare const canvasTypeWords: (types: readonly string[]) => string;
53
+ /**
54
+ * Why a file may not be uploaded for `ask`, in words — or undefined. The upload route and the dashboard's control say
55
+ * the same (the store checks the bytes themselves again: their first bytes must be the type named).
56
+ */
57
+ export declare function canvasUploadRefusal(ask: Pick<CanvasAsk, 'kind' | 'qid'>, file: {
58
+ name: string;
59
+ mediaType: string;
60
+ bytes: number;
61
+ }): string | undefined;
62
+ /** `POST /api/canvases/<id>/assets` — the person's file for a question, its bytes base64. */
63
+ export interface DashCanvasAssetInput {
64
+ qid: string;
65
+ name: string;
66
+ mediaType: string;
67
+ /** The bytes, base64 (≤ 10 MB of file). */
68
+ data: string;
69
+ requestId?: string;
70
+ }
71
+ export interface DashCanvasAssetResult {
72
+ asset: CanvasAsset;
73
+ }
74
+ /**
75
+ * An image answer is written into a headless render — its picture and its html export — up to this many bytes, as a
76
+ * `data:` image (the html keeps an image of at most 1 MB of `data:` text); past it, the card names the file.
77
+ */
78
+ export declare const CANVAS_RENDER_IMAGE_BYTES: number;
79
+ /** The most a JSON upload's body takes: 10 MB of file as base64 (4/3), and the rest of the request. */
80
+ export declare const CANVAS_ASSET_BODY_BYTES: number;
@@ -0,0 +1 @@
1
+ "use strict";var c=Object.defineProperty;var i=(e,a)=>c(e,"name",{value:a,configurable:!0});var p=Object.defineProperty,t=i((e,a)=>p(e,"name",{value:a,configurable:!0}),"s");export const TASK_ARTIFACT_TYPES={"image/png":"png","image/jpeg":"jpg","image/webp":"webp","image/gif":"gif","application/json":"json","text/plain":"txt","text/markdown":"md","text/csv":"csv"},TASK_ARTIFACT_MAX_BYTES=10*1024*1024,TASK_ARTIFACTS_MAX=50,TASK_ARTIFACTS_MAX_BYTES=100*1024*1024,CANVAS_IMAGE_TYPES=Object.keys(TASK_ARTIFACT_TYPES).filter(e=>e.startsWith("image/")),CANVAS_ASSET_ID_PATTERN=/^as-[0-9a-f]{12}$/,isCanvasAssetId=t(e=>typeof e=="string"&&CANVAS_ASSET_ID_PATTERN.test(e),"isCanvasAssetId");export function canvasAnswerAsset(e){if(!e||typeof e!="object"||Array.isArray(e))return;const a=e;return isCanvasAssetId(a.asset)&&typeof a.name=="string"?{asset:a.asset,name:a.name}:void 0}i(canvasAnswerAsset,"canvasAnswerAsset"),t(canvasAnswerAsset,"canvasAnswerAsset");export const isCanvasAttachAsk=t(e=>e.kind==="file"||e.kind==="image","isCanvasAttachAsk"),canvasAskTypes=t(e=>e.kind==="image"?CANVAS_IMAGE_TYPES:Object.keys(TASK_ARTIFACT_TYPES),"canvasAskTypes"),canvasBytesWords=t(e=>e>=1024*1024?`${(e/1024/1024).toFixed(1)} MB`:`${Math.max(1,Math.round(e/1024))} KB`,"canvasBytesWords");const A={"image/png":"PNG","image/jpeg":"JPEG","image/webp":"WebP","image/gif":"GIF","application/json":"JSON","text/plain":"plain text","text/markdown":"Markdown","text/csv":"CSV"};export const canvasTypeWords=t(e=>e.map(a=>A[a]??a).join(", "),"canvasTypeWords");export function canvasUploadRefusal(e,a){if(!isCanvasAttachAsk(e))return`\`${e.qid}\` is not answered with a file: only a \`Field kind="file"\` or \`kind="image"\` is`;const s=a.name.trim();if(!s||s.length>255||/[/\\]/.test(s)||s.includes("\0"))return"The file needs a name of 1 to 255 characters, with no folder in it";const n=a.mediaType.trim().toLowerCase().split(";")[0]?.trim()??"",r=canvasAskTypes(e);if(!r.includes(n)){const o=n?`${A[n]??n}`:"a file of no known type";return e.kind==="image"?`\xAB${s}\xBB is ${o}: this question takes an image \u2014 ${canvasTypeWords(r)} (never SVG: a browser would run it)`:`\xAB${s}\xBB is ${o}: an attachment is ${canvasTypeWords(r)} (never HTML or SVG: a browser would run it)`}if(a.bytes<1)return`\xAB${s}\xBB is empty`;if(a.bytes>TASK_ARTIFACT_MAX_BYTES)return`\xAB${s}\xBB is ${canvasBytesWords(a.bytes)}: an attachment is at most ${canvasBytesWords(TASK_ARTIFACT_MAX_BYTES)}`}i(canvasUploadRefusal,"canvasUploadRefusal"),t(canvasUploadRefusal,"canvasUploadRefusal");export const CANVAS_RENDER_IMAGE_BYTES=760*1024,CANVAS_ASSET_BODY_BYTES=Math.ceil(TASK_ARTIFACT_MAX_BYTES*4/3)+64*1024;
@@ -4,9 +4,10 @@
4
4
  </Tabs>`},{name:"Tab",group:"layout",describe:"One tab of a `Tabs`.",props:{title:{type:"string",required:!0,describe:"The tab\u2019s label."}},children:"blocks",parent:"Tabs",example:'<Tab title="After">\u2026</Tab>'},{name:"Columns",group:"layout",describe:"Children side by side (stacked on a narrow screen).",props:{count:{type:"number",describe:"How many columns (2\u20134, default: one per child)."}},children:"blocks",example:`<Columns>
5
5
  <Stat label="p95" value="120 ms" />
6
6
  <Stat label="Errors" value={3} />
7
- </Columns>`},{name:"Badge",group:"layout",describe:"A small label.",props:{tone:{type:"enum",values:n,describe:"Its color."}},children:"text",example:'<Badge tone="success">shipped</Badge>'},{name:"Stat",group:"data",describe:"One number with a label.",props:{label:{type:"string",required:!0,describe:"What it counts."},value:{type:"any",describe:"The value (or `source`)."},source:{type:"source",describe:"Where the value is: a JSON Pointer into the data (`/totals/cost`) or a get."},unit:{type:"string",describe:"Shown after the value."},delta:{type:"any",describe:"A change to show beside it (`+12%`, or a number)."},tone:{type:"enum",values:n,describe:"Its color."}},children:"none",example:'<Stat label="Monthly cost" source="/totals/cost" unit="USD" />'},{name:"Chart",group:"data",describe:"A chart of rows: bar, line, area, stacked, pie, scatter.",props:{type:{type:"enum",values:CANVAS_CHART_TYPES,required:!0,describe:"Which chart."},data:{type:"rows",describe:"Inline rows (or `source`)."},source:{type:"source",describe:"Where the rows are: a JSON Pointer to an array of objects."},x:{type:"string",required:!0,describe:"The key each row\u2019s x (or slice, for pie) is under."},y:{type:"strings",required:!0,describe:"The numeric key(s) to draw: one series each."},title:{type:"string",describe:"A heading."},unit:{type:"string",describe:"The values\u2019 unit."},height:{type:"number",describe:"Pixels (default 260)."}},children:"none",example:'<Chart type="bar" source="/costs/monthly" x="month" y={["cost"]} unit="USD" />'},{name:"Table",group:"data",describe:"Rows as a sortable table (virtualised past 500 rows).",props:{data:{type:"rows",describe:"Inline rows (or `source`)."},source:{type:"source",describe:"A JSON Pointer to an array of objects."},columns:{type:"columns",describe:"Which keys, in order (default: the first row\u2019s)."},title:{type:"string",describe:"A heading."}},children:"none",example:'<Table source="/checks" columns={["name","state","ms"]} />'},{name:"Timeline",group:"data",describe:"Dated events in order.",props:{data:{type:"rows",describe:"Inline events (or `source`): objects with a date and a title."},source:{type:"source",describe:"A JSON Pointer to an array of objects."},date:{type:"string",describe:"The key of each event\u2019s date (default `date`)."},label:{type:"string",describe:"The key of each event\u2019s title (default `title`)."}},children:"none",example:'<Timeline source="/milestones" />'},{name:"TaskRef",group:"reference",describe:"A link to a task.",props:{id:{type:"string",required:!0,literal:!0,describe:"The task id."}},children:"text",example:'<TaskRef id="6f1c\u2026" />'},{name:"GoalRef",group:"reference",describe:"A link to a goal.",props:{id:{type:"string",required:!0,literal:!0,describe:"The goal id."}},children:"text",example:'<GoalRef id="g-42" />'},{name:"CanvasRef",group:"reference",describe:"A link to another canvas.",props:{id:{type:"string",required:!0,literal:!0,describe:"The canvas id (`cv-\u2026`)."}},children:"text",example:'<CanvasRef id="cv-0123456789abcdef" />'},{name:"FileRef",group:"reference",describe:"A link to a file of the project (opened on the Changes page).",props:{path:{type:"string",required:!0,literal:!0,describe:"Repository-relative path."},line:{type:"number",literal:!0,describe:"A line to open at."}},children:"text",example:'<FileRef path="libs/core/src/index.ts" line={12} />'},{name:"Options",group:"decision",describe:"A decision between options, each an `Option` with its own text; the person picks one.",props:{qid:{type:"string",required:!0,describe:"The decision\u2019s id: what the answer is keyed by."},title:{type:"string",required:!0,describe:"The question the options answer."},blocking:{type:"boolean",describe:"Its task needs the answer: it waits flagged in Team \u203A Inbox \u203A Canvases until the person answers."},inbox:{type:"boolean",describe:"Also ask it in Team \u203A Inbox \u203A Canvases."}},children:"Option",interactive:!0,example:`<Options qid="store" title="Where do canvases live?">
7
+ </Columns>`},{name:"Badge",group:"layout",describe:"A small label.",props:{tone:{type:"enum",values:n,describe:"Its color."}},children:"text",example:'<Badge tone="success">shipped</Badge>'},{name:"Stat",group:"data",describe:"One number with a label.",props:{label:{type:"string",required:!0,describe:"What it counts."},value:{type:"any",describe:"The value (or `source`)."},source:{type:"source",describe:"Where the value is: a JSON Pointer into the data (`/totals/cost`) or a get."},unit:{type:"string",describe:"Shown after the value."},delta:{type:"any",describe:"A change to show beside it (`+12%`, or a number)."},tone:{type:"enum",values:n,describe:"Its color."}},children:"none",example:'<Stat label="Monthly cost" source="/totals/cost" unit="USD" />'},{name:"Chart",group:"data",describe:"A chart of rows: bar, line, area, stacked, pie, scatter.",props:{type:{type:"enum",values:CANVAS_CHART_TYPES,required:!0,describe:"Which chart."},data:{type:"rows",describe:"Inline rows (or `source`)."},source:{type:"source",describe:"Where the rows are: a JSON Pointer to an array of objects."},x:{type:"string",required:!0,describe:"The key each row\u2019s x (or slice, for pie) is under."},y:{type:"strings",required:!0,describe:"The numeric key(s) to draw: one series each."},title:{type:"string",describe:"A heading."},unit:{type:"string",describe:"The values\u2019 unit."},height:{type:"number",describe:"Pixels (default 260)."}},children:"none",example:'<Chart type="bar" source="/costs/monthly" x="month" y={["cost"]} unit="USD" />'},{name:"Table",group:"data",describe:"Rows as a sortable table (virtualised past 500 rows).",props:{data:{type:"rows",describe:"Inline rows (or `source`)."},source:{type:"source",describe:"A JSON Pointer to an array of objects."},columns:{type:"columns",describe:"Which keys, in order (default: the first row\u2019s)."},title:{type:"string",describe:"A heading."}},children:"none",example:'<Table source="/checks" columns={["name","state","ms"]} />'},{name:"Timeline",group:"data",describe:"Dated events in order.",props:{data:{type:"rows",describe:"Inline events (or `source`): objects with a date and a title."},source:{type:"source",describe:"A JSON Pointer to an array of objects."},date:{type:"string",describe:"The key of each event\u2019s date (default `date`)."},label:{type:"string",describe:"The key of each event\u2019s title (default `title`)."}},children:"none",example:'<Timeline source="/milestones" />'},{name:"TaskRef",group:"reference",describe:"A link to a task.",props:{id:{type:"string",required:!0,literal:!0,describe:"The task id."}},children:"text",example:'<TaskRef id="6f1c\u2026" />'},{name:"GoalRef",group:"reference",describe:"A link to a goal.",props:{id:{type:"string",required:!0,literal:!0,describe:"The goal id."}},children:"text",example:'<GoalRef id="g-42" />'},{name:"CanvasRef",group:"reference",describe:"A link to another canvas.",props:{id:{type:"string",required:!0,literal:!0,describe:"The canvas id (`cv-\u2026`)."}},children:"text",example:'<CanvasRef id="cv-0123456789abcdef" />'},{name:"FileRef",group:"reference",describe:"A link to a file of the project (opened on the Changes page).",props:{path:{type:"string",required:!0,literal:!0,describe:"Repository-relative path."},line:{type:"number",literal:!0,describe:"A line to open at."}},children:"text",example:'<FileRef path="libs/core/src/index.ts" line={12} />'},{name:"Options",group:"decision",describe:"A decision between options, each an `Option` with its own text; the person picks one.",props:{qid:{type:"string",required:!0,describe:"The decision\u2019s id: what the answer is keyed by."},title:{type:"string",required:!0,describe:"The question the options answer."},blocking:{type:"boolean",describe:"Its linked task waits for the answer: no one claims it until it is answered, and its next holder reads the answer. Asked in Team \u203A Inbox like `inbox`, flagged."},inbox:{type:"boolean",describe:"Also ask it in Team \u203A Inbox: it goes to the linked goal's manager first, then the person (no manager on the team, the manager escalates it, its session ends, or 30 minutes pass)."}},children:"Option",interactive:!0,example:`<Options qid="store" title="Where do canvases live?">
8
8
  <Option id="sqlite" title="One SQLite database" recommended>\u2026</Option>
9
9
  <Option id="files" title="Files per canvas">\u2026</Option>
10
- </Options>`},{name:"Option",group:"decision",describe:"One option of an `Options`: its body is the argument for it.",props:{id:{type:"string",required:!0,describe:"The option\u2019s id (the answer\u2019s value)."},title:{type:"string",required:!0,describe:"Its name."},recommended:{type:"boolean",describe:"The one you recommend."}},children:"blocks",parent:"Options",interactive:!0,example:'<Option id="sqlite" title="One SQLite database" recommended>Transactions, one writer \u2026</Option>'},{name:"Question",group:"interactive",describe:"A question the person answers in the document.",props:{qid:{type:"string",required:!0,describe:"Its id: what the answer is keyed by. Letters, digits, `-`, `_`."},kind:{type:"enum",values:["choice","multi","text","number","confirm","approve"],required:!0,describe:"choice (one option), multi (any), text, number, confirm (yes/no), approve (approve / ask for changes)."},title:{type:"string",required:!0,describe:"The question, as the control shows it."},detail:{type:"string",describe:"A line of context under it."},options:{type:"options",describe:'For choice and multi: `[{id, label, detail?}]` or `["A", "B"]`.'},recommended:{type:"string",describe:"The option id you recommend."},blocking:{type:"boolean",describe:"Its task needs the answer: it waits flagged in Team \u203A Inbox \u203A Canvases until the person answers."},inbox:{type:"boolean",describe:"Also ask it in Team \u203A Inbox \u203A Canvases."},required:{type:"boolean",describe:"An answer is needed."},min:{type:"number",describe:"For number: the least."},max:{type:"number",describe:"For number: the most."},placeholder:{type:"string",describe:"For text and number."}},children:"none",interactive:!0,example:'<Question qid="db" kind="choice" title="Which database?" options={["Postgres", "SQLite"]} recommended="sqlite" />'},{name:"Checklist",group:"interactive",describe:"Items the person ticks; each item is its own answer (`qid/itemId`).",props:{qid:{type:"string",required:!0,describe:"Its id."},title:{type:"string",required:!0,describe:"What the list is for."},items:{type:"options",required:!0,describe:'`[{id, label}]` or `["Lint", "Tests"]`.'}},children:"none",interactive:!0,example:'<Checklist qid="release" title="Before release" items={["Changelog", "Docs", "Smoke test"]} />'},{name:"Field",group:"interactive",describe:"One value the person fills in.",props:{qid:{type:"string",required:!0,describe:"Its id."},label:{type:"string",required:!0,describe:"What to fill in."},kind:{type:"enum",values:["text","number","date","file","image"],required:!0,describe:"text, number, date, file or image."},placeholder:{type:"string",describe:"A hint inside it."},required:{type:"boolean",describe:"An answer is needed."},min:{type:"number",describe:"For number."},max:{type:"number",describe:"For number."}},children:"none",interactive:!0,example:'<Field qid="deadline" label="Ship by" kind="date" />'},{name:"When",group:"interactive",describe:"Shows its content (follow-up text and questions) once a question is answered so.",props:{qid:{type:"string",required:!0,describe:"The question it follows."},is:{type:"strings",required:!0,describe:'The option id(s) \u2014 or "yes"/"no" for a confirm \u2014 that show it.'}},children:"blocks",interactive:!0,example:`<When qid="db" is="postgres">
10
+ </Options>`},{name:"Option",group:"decision",describe:"One option of an `Options`: its body is the argument for it.",props:{id:{type:"string",required:!0,describe:"The option\u2019s id (the answer\u2019s value)."},title:{type:"string",required:!0,describe:"Its name."},recommended:{type:"boolean",describe:"The one you recommend."}},children:"blocks",parent:"Options",interactive:!0,example:'<Option id="sqlite" title="One SQLite database" recommended>Transactions, one writer \u2026</Option>'},{name:"Question",group:"interactive",describe:"A question the person answers in the document.",props:{qid:{type:"string",required:!0,describe:"Its id: what the answer is keyed by. Letters, digits, `-`, `_`."},kind:{type:"enum",values:["choice","multi","text","number","confirm","approve"],required:!0,describe:"choice (one option), multi (any), text, number, confirm (yes/no), approve (approve / ask for changes)."},title:{type:"string",required:!0,describe:"The question, as the control shows it."},detail:{type:"string",describe:"A line of context under it."},options:{type:"options",describe:'For choice and multi: `[{id, label, detail?}]` or `["A", "B"]`.'},recommended:{type:"string",describe:"The option id you recommend."},blocking:{type:"boolean",describe:"Its linked task waits for the answer: no one claims it until it is answered, and its next holder reads the answer. Asked in Team \u203A Inbox like `inbox`, flagged."},inbox:{type:"boolean",describe:"Also ask it in Team \u203A Inbox: it goes to the linked goal's manager first, then the person (no manager on the team, the manager escalates it, its session ends, or 30 minutes pass)."},required:{type:"boolean",describe:"An answer is needed."},min:{type:"number",describe:"For number: the least."},max:{type:"number",describe:"For number: the most."},placeholder:{type:"string",describe:"For text and number."}},children:"none",interactive:!0,example:'<Question qid="db" kind="choice" title="Which database?" options={["Postgres", "SQLite"]} recommended="sqlite" />'},{name:"Checklist",group:"interactive",describe:"Items the person ticks; each item is its own answer (`qid/itemId`).",props:{qid:{type:"string",required:!0,describe:"Its id."},title:{type:"string",required:!0,describe:"What the list is for."},items:{type:"options",required:!0,describe:'`[{id, label}]` or `["Lint", "Tests"]`.'}},children:"none",interactive:!0,example:'<Checklist qid="release" title="Before release" items={["Changelog", "Docs", "Smoke test"]} />'},{name:"Field",group:"interactive",describe:"One value the person fills in \u2014 or a file or image they attach, in the dashboard's own picker (the frame never sees it). The answer is `{ asset, name }`; canvas_get and canvas_wait name its `file.path`.",props:{qid:{type:"string",required:!0,describe:"Its id."},label:{type:"string",required:!0,describe:"What to fill in."},kind:{type:"enum",values:["text","number","date","file","image"],required:!0,describe:"text, number, date, file (PNG, JPEG, WebP, GIF, JSON, plain text, Markdown, CSV; at most 10 MB) or image (PNG, JPEG, WebP, GIF)."},placeholder:{type:"string",describe:"A hint inside it."},required:{type:"boolean",describe:"An answer is needed."},min:{type:"number",describe:"For number."},max:{type:"number",describe:"For number."}},children:"none",interactive:!0,example:`<Field qid="deadline" label="Ship by" kind="date" />
11
+ <Field qid="screenshot" label="A screenshot of the error" kind="image" />`},{name:"When",group:"interactive",describe:"Shows its content (follow-up text and questions) once a question is answered so.",props:{qid:{type:"string",required:!0,describe:"The question it follows."},is:{type:"strings",required:!0,describe:'The option id(s) \u2014 or "yes"/"no" for a confirm \u2014 that show it.'}},children:"blocks",interactive:!0,example:`<When qid="db" is="postgres">
11
12
  <Question qid="pg-host" kind="text" title="Which host?" />
12
13
  </When>`}],CANVAS_COMPONENT_NAMES=CANVAS_COMPONENTS.map(e=>e.name),canvasComponent=s(e=>CANVAS_COMPONENTS.find(t=>t.name===e),"canvasComponent"),CANVAS_FENCES=["mermaid","diff"];export function canvasComponentSchema(e){const t=Object.entries(e.props).map(([a,i])=>`${a}${i.required?"*":""}: ${i.type==="enum"?(i.values??[]).join("|"):i.type}`);return`${e.name} { ${t.join(", ")} }${e.children==="none"?"":` children: ${e.children}`}`}r(canvasComponentSchema,"canvasComponentSchema"),s(canvasComponentSchema,"canvasComponentSchema");export function canvasOptionId(e){const t=e.normalize("NFKD").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,63);return/^[a-z]/.test(t)?t:`o-${t||"x"}`.slice(0,63)}r(canvasOptionId,"canvasOptionId"),s(canvasOptionId,"canvasOptionId");export const CANVAS_INTERNAL_COMPONENTS=["CanvasBlock","CanvasMermaid","CanvasDiffBlock"];