@theoremjs/studio 0.3.4-next.711.g78e504a → 0.3.4-next.715.geef22fd

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/package.json +4 -4
  2. package/page/assets/{Banner-GFaYsfrc.js → Banner-CrhjYjDy.js} +3 -3
  3. package/page/assets/{ConsoleFrame-KmyDVQkS.js → ConsoleFrame-dOTqIkpb.js} +1 -1
  4. package/page/assets/{MenuBottomSheet-BSQO5V7g.js → MenuBottomSheet-DeuZCVb-.js} +1 -1
  5. package/page/assets/{SchemaFields-CIsMisSq.js → SchemaFields-DeuNDrvj.js} +1 -1
  6. package/page/assets/{ToolResultCharts-95plvcj4.js → ToolResultCharts-B-pokquL.js} +1 -1
  7. package/page/assets/{TraceInspector-D2113s73.js → TraceInspector-CvJ0wx9n.js} +1 -1
  8. package/page/assets/{TraceOverview-Bz2EnBzL.js → TraceOverview-cIjJwpvK.js} +1 -1
  9. package/page/assets/{_virtual_studio-type-sources-La9AcR1O.js → _virtual_studio-type-sources-BxnDf9BC.js} +7 -0
  10. package/page/assets/{browser-connection-B2a2EaIg.js → browser-connection-CuWeoI9s.js} +1 -1
  11. package/page/assets/{browser-engine--lGbAmPM.js → browser-engine-C3SeJyrA.js} +4 -4
  12. package/page/assets/{browser-transport-h1KAGUN4.js → browser-transport-DKhZ4zo1.js} +3 -3
  13. package/page/assets/{export-agent-CA42Pf8A.js → export-agent-CO4lAMum.js} +1 -1
  14. package/page/assets/{guardrail-tester-fDJlewVB.js → guardrail-tester-Slctc2oI.js} +1 -1
  15. package/page/assets/{index-Bd7U_fu_.js → index-CAK9cdCh.js} +7 -7
  16. package/page/assets/{live-messages-CTL-QEqM.js → live-messages-M0vS3YB0.js} +1 -1
  17. package/page/assets/{reader-COeSYhdZ.js → reader-747-Cvu8.js} +1 -1
  18. package/page/assets/{stub-DJBcKncO.js → stub--LOYiyQO.js} +1 -1
  19. package/page/assets/{studio-code-pane-MXm30Ppv.js → studio-code-pane-CuccT4Ur.js} +3 -3
  20. package/page/assets/{studio-console-dHEr6mr5.js → studio-console-DwxLzV9_.js} +1 -1
  21. package/page/assets/{studio-decision-BoSmTyjn.js → studio-decision-w6OjVUM3.js} +1 -1
  22. package/page/assets/{studio-embedding-B5E__vsY.js → studio-embedding-CxFoTvOd.js} +1 -1
  23. package/page/assets/{studio-host-console-CadL7PPh.js → studio-host-console-BhQSkUhA.js} +2 -2
  24. package/page/assets/{studio-labels-sxDmOFeL.js → studio-labels-q6eBFSru.js} +1 -1
  25. package/page/assets/{studio-live-Cgt4zKeL.js → studio-live-D5NjMEky.js} +1 -1
  26. package/page/assets/{studio-map-BgeqrIh_.js → studio-map-DlkGoGam.js} +1 -1
  27. package/page/assets/{studio-trace-replay-BqYGBZ1t.js → studio-trace-replay-Ccv4ToIz.js} +1 -1
  28. package/page/assets/{studio-type-checker-DutkTKte.js → studio-type-checker-Dm2eit0p.js} +1 -1
  29. package/page/assets/{tool-schema-m1KPujBp.js → tool-schema-6RWBAqGO.js} +1 -1
  30. package/page/assets/{tree-5tuw5ISS.js → tree-DcCW259J.js} +1 -1
  31. package/page/assets/{turn-client-BmadRouD.js → turn-client-OLK12Fyi.js} +2 -2
  32. package/page/assets/{use-one-call-IXfdRlUH.js → use-one-call-CLndFp2X.js} +1 -1
  33. package/page/assets/{workspace-CMUi6xcQ.js → workspace-DSAX72vF.js} +1 -1
  34. package/page/index.html +11 -11
  35. package/runtime.js +1 -1
@@ -1,4 +1,4 @@
1
- import{n as e}from"./rolldown-runtime-hePW80VL.js";import{$ as t,A as n,B as r,C as i,D as a,E as o,F as s,G as c,H as l,I as u,J as d,K as f,L as p,M as m,N as h,O as g,P as ee,Q as te,R as ne,S as re,T as _,U as ie,V as ae,W as oe,X as se,Y as ce,Z as le,a as ue,at as de,b as v,c as y,ct as fe,d as b,dt as pe,et as me,ft as he,g as ge,h as x,ht as _e,i as ve,it as ye,j as be,lt as xe,m as Se,mt as Ce,n as we,nt as Te,o as Ee,ot as De,p as S,q as Oe,r as ke,rt as Ae,st as je,tt as Me,u as Ne,ut as Pe,v as C,w as Fe,x as w,z as Ie}from"./schemas-D7cgkv3L.js";import{c as T,s as Le}from"./host-patterns-F-KZIzkF.js";import{$t as Re,A as E,Ar as ze,B as Be,Cn as Ve,D as He,En as Ue,Er as We,Jn as Ge,K as Ke,Lr as D,M as O,N as k,O as A,P as qe,Pn as Je,Pr as Ye,Qt as Xe,Sr as Ze,Tn as Qe,Xn as $e,Xt as et,Yt as tt,Zn as nt,Zt as rt,a as it,ar as at,bn as ot,c as j,dn as st,dr as ct,er as lt,fr as ut,gr as dt,hn as ft,hr as pt,ir as mt,jr as M,k as N,kr as ht,mr as gt,nn as _t,on as vt,or as yt,qn as bt,sr as xt,tr as St,un as Ct,ur as wt,wr as Tt,yn as Et}from"./shaped-data-7q5Be8sp.js";var Dt=e({endsWith:()=>be,gt:()=>m,gte:()=>h,includes:()=>ee,length:()=>Ie,lowercase:()=>r,lt:()=>ae,lte:()=>l,maxLength:()=>ie,maxSize:()=>oe,mime:()=>c,minLength:()=>f,minSize:()=>Oe,multipleOf:()=>d,negative:()=>ce,nonnegative:()=>se,nonpositive:()=>le,normalize:()=>te,overwrite:()=>t,positive:()=>me,properties:()=>Me,property:()=>Te,regex:()=>Ae,size:()=>ye,slugify:()=>de,startsWith:()=>De,toLowerCase:()=>je,toUpperCase:()=>fe,trim:()=>xe,uppercase:()=>Pe}),Ot=e({ZodISODate:()=>we,ZodISODateTime:()=>ke,ZodISODuration:()=>ve,ZodISOTime:()=>ue,date:()=>At,datetime:()=>kt,duration:()=>Mt,time:()=>jt});function kt(e){return u(ke,e)}function At(e){return s(we,e)}function jt(e){return ne(ue,e)}function Mt(e){return p(ve,e)}var P={...Fe,...Dt,iso:Ot},Nt=new Set(`$schema.$ref.$defs.definitions.$id.id.$comment.$anchor.$vocabulary.$dynamicRef.$dynamicAnchor.type.enum.const.anyOf.oneOf.allOf.not.properties.required.additionalProperties.patternProperties.propertyNames.minProperties.maxProperties.items.prefixItems.additionalItems.minItems.maxItems.uniqueItems.contains.minContains.maxContains.minLength.maxLength.pattern.format.minimum.maximum.exclusiveMinimum.exclusiveMaximum.multipleOf.description.default.contentEncoding.contentMediaType.contentSchema.unevaluatedItems.unevaluatedProperties.if.then.else.dependentSchemas.dependentRequired.nullable.readOnly`.split(`.`));function Pt(e,t){let n=e.$schema;return n===`https://json-schema.org/draft/2020-12/schema`?`draft-2020-12`:n===`http://json-schema.org/draft-07/schema#`?`draft-7`:n===`http://json-schema.org/draft-04/schema#`?`draft-4`:t??`draft-2020-12`}function Ft(e,t){return e.map((e,n)=>n<t?e:e.optional())}function It(e){return e.replace(/~1/g,`/`).replace(/~0/g,`~`)}function Lt(e,t){if(!e.startsWith(`#`))throw Error(`External $ref is not supported, only local refs (#/...) are allowed`);let n=e.slice(1).split(`/`).filter(Boolean);if(n.length===0)return t.rootSchema;let r=t.version===`draft-2020-12`?`$defs`:`definitions`;if(n[0]===r){let r=n[1]===void 0?void 0:It(n[1]);if(!r||!t.defs[r])throw Error(`Reference not found: ${e}`);return t.defs[r]}throw Error(`Reference not found: ${e}`)}function Rt(e,t){return P.transform(e=>e).check(n=>{let r=n.value;if(typeof r!=`object`||!r||Array.isArray(r))return;let i=Object.getOwnPropertyNames(r);if(t.minProperties!==void 0&&i.length<t.minProperties&&n.issues.push({origin:`object`,code:`too_small`,minimum:t.minProperties,inclusive:!0,message:`Too small: expected object to have >=${t.minProperties} properties`,input:r,inst:e,continue:!0}),t.maxProperties!==void 0&&i.length>t.maxProperties&&n.issues.push({origin:`object`,code:`too_big`,maximum:t.maxProperties,inclusive:!0,message:`Too big: expected object to have <=${t.maxProperties} properties`,input:r,inst:e,continue:!0}),t.keySchema)for(let e of i){let r=t.keySchema.safeParse(e);r.success||n.issues.push({code:`invalid_key`,origin:`record`,issues:r.error.issues,input:e,path:[e],continue:!0})}}).pipe(e)}function zt(e,t){if(e===null)return`z`;let n=typeof e;if(n!==`object`){if(n===`number`&&Number.isNaN(e))return null;let t=String(e);return`${n[0]}${t.length}:${t}`}if(t.has(e))return null;t.add(e);try{if(Array.isArray(e)){let n=[];for(let r of e){let e=zt(r,t);if(e===null)return null;n.push(e)}return`a${n.length}:[${n.join(`,`)}]`}let n=Object.keys(e).sort(),r=[];for(let i of n){let n=zt(e[i],t);if(n===null)return null;r.push(`${i.length}:${i}=${n}`)}return`o${r.length}:{${r.join(`,`)}}`}finally{t.delete(e)}}var Bt=new Set([`items`,`prefixItems`,`additionalItems`,`additionalProperties`,`contains`,`propertyNames`,`not`,`if`,`then`,`else`,`allOf`,`anyOf`,`oneOf`,`unevaluatedItems`,`unevaluatedProperties`,`contentSchema`]),Vt=new Set([`properties`,`patternProperties`,`dependentSchemas`,`dependencies`,`$defs`,`definitions`]);function Ht(e){return typeof e!=`object`||!e?!1:Array.isArray(e)?e.some(Ht):typeof e.$ref==`string`||Object.entries(e).some(([e,t])=>Bt.has(e)?Ht(t):!Vt.has(e)||typeof t!=`object`||!t?!1:Object.values(t).some(Ht))}function Ut(e){return e===1?`element`:`elements`}function Wt(e,t){return P.transform(e=>e).check(e=>{let n=e.value;if(Array.isArray(n)){if(t.uniqueItems===!0){let t=new Map;for(let r=0;r<n.length;r++){let i=zt(n[r],new Set);if(i===null)continue;let a=t.get(i);a===void 0?t.set(i,r):e.issues.push({code:`custom`,message:`Array items must be unique: element at index ${r} duplicates the one at index ${a}`,input:n,path:[r],continue:!0})}}if(t.containsSchema){let r=t.minContains??1,i=t.maxContains===void 0?1/0:t.maxContains+1,a=0;for(let e of n)if(t.containsSchema.safeParse(e).success&&++a>=i)break;a<r&&e.issues.push({code:`custom`,message:`Array must contain at least ${r} matching ${Ut(r)}; found ${a}`,input:n,continue:!0}),t.maxContains!==void 0&&a>t.maxContains&&e.issues.push({code:`custom`,message:`Array must contain at most ${t.maxContains} matching ${Ut(t.maxContains)}`,input:n,continue:!0})}}}).pipe(e)}function Gt(e,t){if(e!==!1)return e===void 0||e===!0?P.any():F(e,t)}var Kt=/^(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/;function qt(e,t){if(e.not!==void 0){if(typeof e.not==`object`&&Object.keys(e.not).length===0)return P.never();throw Error(`not is not supported in Zod (except { not: {} } for never)`)}if(e.unevaluatedItems!==void 0)throw Error(`unevaluatedItems is not supported`);if(e.unevaluatedProperties!==void 0)throw Error(`unevaluatedProperties is not supported`);if(e.if!==void 0||e.then!==void 0||e.else!==void 0)throw Error(`Conditional schemas (if/then/else) are not supported`);if(e.dependentSchemas!==void 0||e.dependentRequired!==void 0)throw Error(`dependentSchemas and dependentRequired are not supported`);if(e.$ref){let n=e.$ref;if(t.refs.has(n))return t.refs.get(n);if(t.processing.has(n))return P.lazy(()=>{if(!t.refs.has(n))throw Error(`Circular reference not resolved: ${n}`);return t.refs.get(n)});t.processing.add(n);let r=F(Lt(n,t),t);return t.refs.set(n,r),t.processing.delete(n),r}if(e.enum!==void 0){let n=e.enum;if(t.version===`openapi-3.0`&&e.nullable===!0&&n.length===1&&n[0]===null)return P.null();if(n.length===0)return P.never();if(n.length===1)return P.literal(n[0]);if(n.every(e=>typeof e==`string`))return P.enum(n);let r=n.map(e=>P.literal(e));return r.length<2?r[0]:P.union([r[0],r[1],...r.slice(2)])}if(e.const!==void 0)return P.literal(e.const);let n=e.type;if(Array.isArray(n)){let r=n.map(n=>qt({...e,type:n},t));return r.length===0?P.never():r.length===1?r[0]:P.union(r)}if(!n)return P.any();let r;switch(n){case`string`:{let t=P.string();if(e.format){let n=e.format;n===`email`?t=t.check(P.email()):n===`uri`||n===`uri-reference`?t=t.check(P.url()):n===`uuid`||n===`guid`?t=t.check(P.uuid()):n===`date-time`?t=t.check(P.iso.datetime({offset:!0})):n===`date`?t=t.check(P.iso.date()):n===`time`?t=t.check(P.regex(Kt)):n===`duration`?t=t.check(P.iso.duration()):n===`hostname`?t=t.check(P.hostname()):n===`ipv4`?t=t.check(P.ipv4()):n===`ipv6`?t=t.check(P.ipv6()):n===`mac`?t=t.check(P.mac()):n===`cidr`?t=t.check(P.cidrv4()):n===`cidr-v6`?t=t.check(P.cidrv6()):n===`base64`?t=t.check(P.base64()):n===`base64url`?t=t.check(P.base64url()):n===`e164`?t=t.check(P.e164()):n===`credit_card`?t=t.check(P.creditCard()):n===`iban`?t=t.check(P.iban()):n===`jwt`?t=t.check(P.jwt()):n===`emoji`?t=t.check(P.emoji()):n===`nanoid`?t=t.check(P.nanoid()):n===`cuid`?t=t.check(P.cuid()):n===`cuid2`?t=t.check(P.cuid2()):n===`ulid`?t=t.check(P.ulid()):n===`xid`?t=t.check(P.xid()):n===`ksuid`&&(t=t.check(P.ksuid()))}typeof e.minLength==`number`&&(t=t.min(e.minLength)),typeof e.maxLength==`number`&&(t=t.max(e.maxLength)),e.pattern&&(t=t.regex(new RegExp(e.pattern))),r=t;break}case`number`:case`integer`:{let t=n===`integer`?P.number().int():P.number();typeof e.minimum==`number`&&e.exclusiveMinimum!==!0&&(t=t.min(e.minimum)),typeof e.maximum==`number`&&e.exclusiveMaximum!==!0&&(t=t.max(e.maximum)),typeof e.exclusiveMinimum==`number`?t=t.gt(e.exclusiveMinimum):e.exclusiveMinimum===!0&&typeof e.minimum==`number`&&(t=t.gt(e.minimum)),typeof e.exclusiveMaximum==`number`?t=t.lt(e.exclusiveMaximum):e.exclusiveMaximum===!0&&typeof e.maximum==`number`&&(t=t.lt(e.maximum)),typeof e.multipleOf==`number`&&(t=t.multipleOf(e.multipleOf)),r=t;break}case`boolean`:r=P.boolean();break;case`null`:r=P.null();break;case`object`:{let n={},i=e.properties||{},a=new Set(e.required||[]),o=typeof e.additionalProperties==`object`?F(e.additionalProperties,t):void 0;for(let[e,r]of Object.entries(i)){let i=F(r,t);Ce(n,e,a.has(e)?i:i.optional())}if(e.patternProperties){let i=e.patternProperties,a=Object.keys(i),o=[];for(let e of a){let n=F(i[e],t),r=P.string().regex(new RegExp(e));o.push(P.looseRecord(r,n))}let s=[];if(Object.keys(n).length>0&&s.push(P.object(n).passthrough()),s.push(...o),s.length===0)r=P.object({}).passthrough();else if(s.length===1)r=s[0];else{let e=P.intersection(s[0],s[1]);for(let t=2;t<s.length;t++)e=P.intersection(e,s[t]);r=e}if(e.additionalProperties===!1){let e=Object.keys(n),t=a.map(e=>new RegExp(e)),i=r;r=r.check(n=>{if(!_e(n.value))return;let r=[];for(let i of Object.keys(n.value))e.includes(i)||t.some(e=>e.test(i))||r.push(i);r.length&&n.issues.push({code:`unrecognized_keys`,keys:r,input:n.value,inst:i})})}}else{let t=P.object(n);r=e.additionalProperties===!1?t.strict():o?t.catchall(o):t.passthrough()}let s=e.propertyNames!==void 0&&e.propertyNames!==!0,c=typeof e.minProperties==`number`?e.minProperties:void 0,l=typeof e.maxProperties==`number`?e.maxProperties:void 0;if(s||c!==void 0||l!==void 0){let n;s&&(n=F(typeof e.propertyNames==`object`&&e.propertyNames.type===void 0?{type:`string`,...e.propertyNames}:e.propertyNames,t)),r=Rt(r,{keySchema:n,minProperties:c,maxProperties:l})}break}case`array`:{let n=e.prefixItems,i=e.items;if(n&&Array.isArray(n)){let a=typeof e.minItems==`number`?e.minItems:0,o=Ft(n.map(e=>F(e,t)),a),s=Array.isArray(i)?void 0:Gt(i,t),c=P.tuple(o);r=s?c.rest(s):c,typeof e.minItems==`number`&&(r=r.check(P.minLength(e.minItems))),typeof e.maxItems==`number`&&(r=r.check(P.maxLength(e.maxItems)))}else if(Array.isArray(i)){let n=typeof e.minItems==`number`?e.minItems:0,a=Ft(i.map(e=>F(e,t)),n),o=Gt(e.additionalItems,t),s=P.tuple(a);r=o?s.rest(o):s,typeof e.minItems==`number`&&(r=r.check(P.minLength(e.minItems))),typeof e.maxItems==`number`&&(r=r.check(P.maxLength(e.maxItems)))}else if(i!==void 0){let n=F(i,t),a=P.array(n);typeof e.minItems==`number`&&(a=a.min(e.minItems)),typeof e.maxItems==`number`&&(a=a.max(e.maxItems)),r=a}else r=P.array(P.any());(e.uniqueItems===!0||e.contains!==void 0)&&(r=Wt(r,{uniqueItems:e.uniqueItems===!0,containsSchema:e.contains===void 0?void 0:F(e.contains,t),minContains:typeof e.minContains==`number`?e.minContains:void 0,maxContains:typeof e.maxContains==`number`?e.maxContains:void 0}));break}default:throw Error(`Unsupported type: ${n}`)}return r}function F(e,t){if(typeof e==`boolean`)return e?P.any():P.never();let n=qt(e,t),r=e.type||e.enum!==void 0||e.const!==void 0;if(e.anyOf&&Array.isArray(e.anyOf)){let i=e.anyOf.map(e=>F(e,t)),a=P.union(i);n=r?P.intersection(n,a):a}if(e.oneOf&&Array.isArray(e.oneOf)){let i=e.oneOf.map(e=>F(e,t)),a=P.xor(i);n=r?P.intersection(n,a):a}if(e.allOf&&Array.isArray(e.allOf)){if(e.allOf.length===0)n=r?n:P.any();else{let i=r?n:F(e.allOf[0],t),a=+!r;for(let n=a;n<e.allOf.length;n++)i=P.intersection(i,F(e.allOf[n],t));n=i}}e.nullable===!0&&t.version===`openapi-3.0`&&(n=P.nullable(n)),e.readOnly===!0&&(n=P.readonly(n)),e.default!==void 0&&(n=n.default(e.default));let i={};for(let t of[`$id`,`id`,`$comment`,`$anchor`,`$vocabulary`,`$dynamicRef`,`$dynamicAnchor`])t in e&&(i[t]=e[t]);for(let t of[`contentEncoding`,`contentMediaType`,`contentSchema`])t in e&&(i[t]=e[t]);if(e.type===`object`&&e.$ref===void 0){e.propertyNames!==void 0&&!Ht(e.propertyNames)&&(i.propertyNames=e.propertyNames);for(let t of[`minProperties`,`maxProperties`])e[t]!==void 0&&(i[t]=e[t])}if(e.type===`array`&&e.$ref===void 0){e.contains!==void 0&&!Ht(e.contains)&&(i.contains=e.contains);for(let t of[`uniqueItems`,`minContains`,`maxContains`])e[t]!==void 0&&(i[t]=e[t])}for(let t of Object.keys(e))Nt.has(t)||Ce(i,t,e[t]);return Object.keys(i).length>0&&t.registry.add(n,i),e.description&&(n=n.describe(e.description)),n}function Jt(e,t){if(typeof e==`boolean`)return e?P.any():P.never();let n;try{n=JSON.parse(JSON.stringify(e))}catch{throw Error(`fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas`)}let r={version:Pt(n,t?.defaultTarget),defs:n.$defs||n.definitions||{},refs:new Map,processing:new Set,rootSchema:n,registry:t?.registry??pe};return F(n,r)}var Yt=y(Le),Xt=w({key:y(Ye),params:i(o(),a([o(),v()])).optional()}),Zt=a([Xt,b(Xt).readonly()]),Qt=w({origin:y(gt),tool:o(),depth:v()}),$t=w({rule:o(),severity:y(ut),span:w({start:v(),end:v()}).optional(),match:o().optional(),label:o().optional(),doc:o().optional(),pattern:o().optional(),signal:o().optional()}),en=w({stage:y(ct),boundary:y(dt).optional(),trust:y(pt),action:y(wt),hits:b($t),provenance:Qt.optional(),errorInternal:o().optional(),errorSummary:o().optional()}),tn=ge(),I=i(o(),tn),nn=_({protocol:o().min(1),provider:o().min(1),version:v().int().positive(),apiId:o().min(1),keySlot:o().min(1).optional(),compatibilityKey:o(),coveredHistoryLength:v().int().nonnegative(),coveredHistoryHash:o(),data:tn,wireCallIds:i(o().min(1),o().min(1)).optional()}),rn=_({code:C(`provider_state_rebuilt`),reason:y([`provider_changed`,`model_changed`,`connection_changed`,`key_changed`,`history_changed`,`version_changed`])}),an=_({history:y([`host`,`stateless`,`provider`]).optional()});async function on(e){let t=e=>{if(Array.isArray(e))return e.map(t);if(e&&typeof e==`object`){let n={};for(let r of Object.keys(e).sort())n[r]=t(e[r]);return n}return e},n=await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(JSON.stringify(t(e.map(e=>{let t=t=>e.role===`user`?t.match(/^<user_data>\n([\s\S]*)\n<\/user_data>$/)?.[1]??t:t,n=[...e.content===void 0?[]:[{type:`text`,text:t(e.content)}],...(e.parts??[]).map(e=>e.type===`text`?{...e,text:t(e.text)}:e)],{content:r,parts:i,...a}=e;return{...a,...n.length?{parts:n}:{}}}))))),r=``;for(let e of new Uint8Array(n))r+=e.toString(16).padStart(2,`0`);return r}var L=i(o(),g()),R=o().trim().min(1),sn=w({type:C(`text`),text:o()}),cn=w({type:y(st),mimeType:o(),data:o()}),ln=w({type:y(st),mimeType:o(),uri:o()}),un=a([sn,cn,ln]),dn=un,fn=w({protocol:o().min(1),provider:o().min(1).optional(),apiId:o().min(1).optional()}),pn=w({text:o().optional(),data:tn,origin:fn}),mn=w({role:y([`system`,`user`,`assistant`,`tool`]),content:o().optional(),parts:b(un).optional(),tool_calls:b(w({id:o(),type:C(`function`),function:w({name:o(),arguments:o()})})).optional(),reasoning:b(pn).optional(),tool_call_id:o().optional(),name:o().optional(),metadata:L.optional()}),hn=mn,gn=w({kind:y(Ue),native:o().optional()}),_n=gn,vn=[`input`,`output`],yn=w({usd:v(),upstreamUsd:v().optional(),partial:C(!0).optional()}),bn=w({type:o(),count:v(),searchQueryCount:v().optional()}),xn=w({input:v(),output:v(),thinking:v().optional(),toolUse:v().optional(),cached:v().optional(),cacheWrite:v().optional(),total:v(),cost:yn.optional(),estimated:b(y(vn)).optional(),unknownMedia:w({input:v().optional(),output:v().optional()}).optional(),byModality:w({input:i(o(),v()).optional(),output:i(o(),v()).optional()}).optional(),grounding:b(bn).optional()});w({id:o().optional(),model:o().optional()});var Sn=w({title:o(),uri:o(),type:y([`web`,`maps`]),placeId:o().optional()}),Cn=Sn,wn=w({metadata:L.optional(),chunks:b(g()).optional(),searchHtml:o().optional()}),z={provider:o().min(1),raw:L.optional(),partial:S().optional()},Tn=x(`kind`,[w({...z,kind:C(`code_execution_call`),code:o(),language:o().optional(),id:o()}),w({...z,kind:C(`code_execution_result`),result:o().optional(),isError:S().optional(),callId:o().optional()}),w({...z,kind:y([`input_transcription`,`output_transcription`]),interim:S().optional()}),w({...z,kind:y([`voice_activity`,`url_context`])}),w({...z,kind:C(`session_resumption`),resumable:S()}),w({...z,kind:C(`provider_step`),step:o()})]),En=w({cause:C(`go_away`),code:v(),closedAfterMs:v(),errorKind:Yt.optional()}),Dn=x(`kind`,[w({kind:C(`closing_soon`),timeLeftMs:v().optional()}),w({kind:C(`ended`),timeLeftMs:v().optional(),ended:En,message:o()}),w({kind:y([`waiting_for_input`,`turn_complete`,`working`,`idle`])})]),On=w({code:o(),kind:Yt,message:o(),error:o().optional(),details:g().optional()}),kn=w({slot:R,authType:y(ot),service:R,message:R,authorizationUrl:o().optional(),state:o().optional(),issuer:o().optional(),resource:o().optional(),requiredScopes:b(R).optional()}),An={preparedArguments:i(o(),g()).optional(),tool:R,permission:y(Ve).optional(),summary:R.optional(),request:R.optional(),access:y(Et).optional()},jn=x(`kind`,[w({...An,kind:y([`confirmation`,`permission`,`page`])}),w({...An,kind:C(`auth`),authChallenge:kn})]),Mn=jn,Nn=w({code:o(),message:o(),severity:y([`info`,`warning`,`error`]).optional()}),Pn=w({name:o(),kind:o(),status:o(),inputs:L.optional(),outputs:L.optional()}),Fn={status:C(tt),prompt:R},In=x(`kind`,[w({...Fn,kind:y([`confirm`,`text`]),options:b(R).optional()}),w({...Fn,kind:C(`choice`),options:b(R).min(1)})]);function Ln(e){return In.safeParse(e).success}var Rn=w({type:C(`function`),name:o(),description:o(),parameters:L}),zn=w({builtins:b(o()),gated:b(o()),visible:b(o()),executable:b(o()),path:o().optional(),sessionPermissions:b(o()).optional(),wire:b(Rn),modelBackground:S().optional()}),Bn=zn,Vn=_({callId:o().min(1),operationId:o().min(1).max(256)}),Hn={name:o(),callId:o()},Un=w({...Hn,phase:Ne().optional(),arguments:L,reasoning:b(pn).optional(),stepId:o().min(1).optional(),stepCallCount:v().int().min(1).optional()}),B={...Hn,at:v()},Wn=x(`phase`,[w({...B,phase:C(`running`),edited:w({from:L,to:L}).optional(),activity:o().optional()}),w({...B,phase:C(`dispatch`),grantId:o().min(1),arguments:L}),w({...B,phase:C(`progress`),data:g()}),w({...B,phase:C(`draft`),text:o()}),w({...B,phase:C(`trace`),step:Pn}),w({...B,phase:C(`artifact`),artifact:g()}),w({...B,phase:C(`warning`),warning:Nn}),w({...B,phase:C(`complete`),output:g(),awaiting:S().optional(),readBack:o().optional(),parts:b(un).optional(),activityPast:o().optional(),tokens:xn.optional()}),w({...B,phase:C(`gate`),gate:jn,readBack:o().optional()}),w({...B,phase:C(`background`),readBack:o()}),w({...B,phase:C(`error`),failure:On,readBack:o().optional(),activityPast:o().optional(),tokens:xn.optional()}),w({...B,phase:C(`cancel`)})]),Gn=a([Wn,Un]).and(w({operationId:o().min(1).max(256).optional()})),Kn=w({code:y(ft),message:o(),field:o()}),qn=w({needed:S(),meter:y(Xe),tokens:v(),unknownMedia:v(),promptTokens:v().optional(),promptTokensEstimated:S().optional(),history:b(mn)}),Jn=w({stop:y(Ue).optional(),error:Yt.optional(),errorInternal:o().optional(),empty:C(!0).optional(),unreadable:C(!0).optional()}),Yn=[`tool`,`gate`];function Xn(e,t){let{stop:n,...r}=e,{kind:i}=n;return i===`tool`||i===`gate`?t?{type:`done`,...r,stop:{...n,kind:i},tools:t}:void 0:{type:`done`,...r,stop:{...n,kind:i}}}var Zn=y(Yn),Qn=y(Ue).exclude(Yn),$n={providerState:nn.optional(),type:C(`done`),tokens:xn.optional(),traceparent:o().optional(),compaction:qn.optional(),interrupted:S().optional(),interactionId:o().optional()},er=a([w({...$n,stop:w({kind:Zn,native:o().optional()}),tools:zn}),w({...$n,stop:w({kind:Qn,native:o().optional()}),tools:Ne().optional()})]),V={provider_checkpoint:w({type:C(`provider_checkpoint`),providerState:nn,history:b(hn).optional()}),provider_warning:w({type:C(`provider_warning`),warning:rn}),text:w({type:C(`text`),text:o()}),thought:w({type:C(`thought`),text:o()}),custom:w({type:C(`custom`),kind:o().min(1),data:I}),structured:w({type:C(`structured`),structured:g(),removed:b(w({path:o(),reason:o(),item:g()})).optional(),failed:b(w({path:o(),error:o()})).optional()}),structured_draft:w({type:C(`structured_draft`),text:o()}),attempt:w({type:C(`attempt`),attempt:v().int().positive(),reason:y([`validation`,`egress`])}),media:w({type:C(`media`),media:w({mimeType:o(),data:o()})}),grounding:w({type:C(`grounding`),grounding:wn}),citation:w({type:C(`citation`),sources:b(Sn),callId:o().optional()}),compaction:w({type:C(`compaction`),timing:C(`before`),meter:y(Xe),tokensBefore:v(),unknownMedia:v(),messagesBefore:v(),messagesAfter:v(),outcome:y(Re),history:b(mn),summary:o().optional(),failure:Jn.optional(),droppedMedia:v(),tokens:xn.optional()}),evidence:w({type:C(`evidence`),evidence:Tn,text:o().optional(),sessionResumptionHandle:o().optional()}),tokens:w({type:C(`tokens`),tokens:xn,interactionId:o().optional()}),session:w({type:C(`session`),session:Dn,errorInternal:o().optional()}),guardrail:w({type:C(`guardrail`),guardrail:en}),stage:w({type:C(`stage`),stage:y(Qe),callId:o().optional(),toolName:o().optional(),callNotStarted:S().optional(),awaiting:S().optional(),gate:jn.optional(),stop:_n.optional(),stageWarnings:b(Kn).optional(),injected:b(w({id:o().regex(/\S/),messages:b(mn)})).min(1).optional(),released:v().int().nonnegative().optional()}),tool_draft:w({type:C(`tool_draft`),callId:o().min(1),name:o(),text:o()}),tool:w({type:C(`tool`),tool:Gn,errorInternal:o().optional()}),error:w({type:C(`error`),errorKind:Yt,error:o().optional(),errorCopy:Zt.optional(),errorInternal:o().optional()}),done:er},tr=a([x(`type`,[V.provider_warning,V.provider_checkpoint,V.text,V.thought,V.custom,V.structured,V.structured_draft,V.attempt,V.media,V.grounding,V.citation,V.compaction,V.evidence,V.tokens,V.session,V.guardrail,V.stage,V.tool_draft,V.tool,V.error]),V.done]),nr=V;function rr(e){return e.type===`text`||e.type===`media`||e.type===`structured`||e.type===`structured_draft`}function ir(e,t){let n=[],r=t;for(let t of e)if(!rr(t))n.push(t);else if(t.type!==`text`)r>0&&n.push(t);else if(r>0){let e=t.text.slice(0,r);r-=e.length,n.push(e===t.text?t:{...t,text:e})}return n}function ar(e){let t=[],n=0;for(let r of e){if(r.type===`attempt`){let e=t.splice(n);t.push(...e.filter(e=>!rr(e)))}r.type===`stage`&&r.released!==void 0&&t.push(...ir(t.splice(n),r.released)),t.push(r),r.type===`done`&&(n=t.length)}return t}var or=[`reply`,`reply_structured`];function sr(e,t,n,r={}){if(!qe([t],n))return{action:`allow`,hits:[],value:e};let i=nt(e);if(i.unscannable)return{action:`block`,hits:[{rule:at.unscannable,severity:`high`}]};let a=O(i.text,t,n,r);if(a.action!==`redact`){let{errorInternal:t,errorSummary:n}=a,r=t&&n?{errorInternal:t,errorSummary:n}:{};return{action:a.action,hits:a.hits,value:e,...r}}let o=$e(e,e=>O(e,t,n,r).text??``),s=O(nt(o).text,t,n,r).action;return s===`redact`||s===`block`?{action:`block`,hits:a.hits}:{action:`redact`,hits:a.hits,value:o}}function cr(e,t,{boundary:n,reportedTo:r=e.text.length,scope:i={}}){let a=O(e.text,n,t,i),o=e.structured===void 0?void 0:sr(e.structured,`reply_structured`,t,i),s=r>=e.text.length?[]:a.hits.filter(e=>!e.span||e.span.start>=r),c=[a.action===`flag`?k(n,{action:s.length>0?`flag`:`allow`,hits:s}):k(n,a),o?k(`reply_structured`,o):void 0].filter(e=>e!==void 0),l=[a,o].flatMap(e=>e?.action===`block`?e.hits:[]);return{payload:{text:a.text??e.text,...o?{structured:o.value}:{}},rewritten:a.action===`redact`,events:c,...l.length>0?{blocked:l}:{}}}function lr(e,t=[]){if(e.blocked)return e.blocked;let n=new Set(e.events.flatMap(e=>e.hits.map(e=>e.rule))),r=t.filter(e=>!n.has(e.rule));return r.length>0?r:void 0}function ur(e,t){return e?t.startsWith(e)?t.slice(e.length):`\n\n${t}`:t}function dr(e,t){return D(e?`egress.refusal_cut`:`egress.refusal`,{},t)}var fr=`</tool_data>`,pr=`<tool_data`,mr=new Set([`http`,`mcp`,`delegated`]);function hr(e){return mr.has(e)}function gr(e){let t=e.toLowerCase(),n=``,r=0;for(;r<e.length;){let i=t.indexOf(pr,r),a=t.indexOf(fr,r),o=-1,s=null;if(i>=0&&(a<0||i<=a)?(o=i,s=`open`):a>=0&&(o=a,s=`close`),o<0||s===null){n+=e.slice(r);break}if(n+=e.slice(r,o),s===`close`){r=o+12;continue}let c=e.indexOf(`>`,o+10);if(c<0){n+=e.slice(o);break}r=c+1}return n}function _r(e,t,n=`none`,r){let i=D(`advisory.guidance`,{},r).trim();return`<tool_data ${`tool="${t.tool}" origin="${t.origin}"`+(n===`none`?``:` advisory="${n}"`)}>\n${n===`none`?``:`${vr(n,r)}${i?` ${i}`:``}\n`}${gr(e)}\n${fr}`}function vr(e,t){return D(e===`high`?`advisory.notice_high`:`advisory.notice_elevated`,{},t)}function yr(e,t){if(t===void 0)return e;let n=nt(t);return n.unscannable?e:`${e}\n${n.text}`}var br={action:`allow`,hits:[]};function xr(e,t,n,r){return t?O(e,t,n,r):{...br,text:e}}function Sr(e,t,n,r,i,a=[],o){let s=xr(yr(e,t),i,r.detect,{callable:a}),c=s.hits.filter(({rule:e})=>e===mt.tool_instructions),l=hr(n.origin),u=s.action===`allow`?void 0:{stage:`tool_result`,...i?{boundary:i}:{},trust:`untrusted`,action:s.action,hits:s.hits,provenance:n},d={...c.length>0?{suspicious:c}:{},...u?{event:u}:{}};return s.text===void 0?d:{text:l?_r(s.text,n,Ke(c.map(({signal:e})=>e)),o):s.text,...d}}function Cr(e,t,n,r){let i=xr(gr(e),r,n.detect),a=r?k(r,i,t):void 0;return{...i.text===void 0?{}:{text:i.text},...a?{event:a}:{}}}function wr(e,t,n,r){if(!r||e===void 0)return{value:e};let i=sr(e,r,n.detect),a=k(r,i,t);return{...i.action===`block`?{}:{value:i.value},...a?{event:a}:{}}}function Tr(e,t,n,r,i={}){if(!(r&&qe([r],n.detect)))return{args:e};let a=e=>{let n=k(r,{action:`block`,hits:e},t);return n?{event:n}:{}},o=nt(e);if(o.unscannable)return a([{rule:at.unscannable,severity:`high`}]);let s=O(o.text,r,n.detect,i);if(s.action===`block`)return a(s.hits);let c=k(r,s,t);if(s.action!==`redact`)return{args:e,...c?{event:c}:{}};let l=$e(e,e=>O(e,r,n.detect,i).text??``),u=O(nt(l).text,r,n.detect,i).action;return u===`redact`||u===`block`?a(s.hits):{args:l,...c?{event:c}:{}}}function Er(e,t){if(e.action!==`allow`)return{stage:`tool_call`,trust:`untrusted`,action:e.action,hits:e.hits,provenance:t}}function Dr(e,t,n=[]){let r=e?.sources??[],i=e?.suspicious??[];return hr(t.origin)?{sources:[...r,t],suspicious:[...i,...n]}:{sources:r,suspicious:i}}function Or(e){return(e?.sources.length??0)>0}function kr(e){return(e?.suspicious.length??0)>0}var Ar={"read-only":0,"read-write":1,destructive:2},jr={off:1/0,destructive:2,write:1};function Mr(e,t,n,r){if(!Or(e))return{action:`allow`};let i=Ar[t]??0;if(i===0)return{action:`allow`};let a=kr(e),o=[{rule:a?xt.steeredTurn:xt.taintedTurn,severity:`high`}];if(i<jr[n.taint?.afterRemoteRead??`off`])return{action:`flag`,hits:o};let s=e?.sources.map(e=>e.tool).join(`, `)??``,c=D(a?`taint.reason_steered`:`taint.reason_tainted`,{},r);return{action:`block`,hits:o,rejection:D(`taint.blocked`,{access:t,sources:s,reason:c},r)}}var Nr={onBlock:`retry`,maxRetries:1};function Pr(e){return{onBlock:e?.onBlock??Nr.onBlock,maxRetries:e?.maxRetries??Nr.maxRetries}}function Fr(e){return{detect:Ge(e?.detect),allow:bt(e?.detect),blockedReply:Pr(e?.blockedReply),network:e?.network,quota:e?.quota,taint:e?.taint}}function Ir(e){return(e.split(`;`)[0]??``).trim().toLowerCase()}function Lr(e,t){let n=Ir(t);return e.some(e=>{let t=Ir(e);return t.endsWith(`/*`)?n.startsWith(t.slice(0,-1)):t===n})}function Rr(e){return Ct[Ir(e)]}function zr(e){return e.type===`text`||e.type===`image`||e.type===`transcription`||e.type===`live`?e.inputs:void 0}function Br(e,t){let n=zr(e);return t===`voice`?n?.voice?.accept:n?.attachments?.accept}function Vr(e,t){if(Rr(t))for(let n of[`attachments`,`voice`]){let r=Br(e,n);if(r&&Lr(r,t))return n}}function Hr(e,t){let n=e.models[t];if(!n)throw new T(`config`,`Profile ${e.id} has no model binding for '${t}'`);return n}var Ur=/^\d{1,3}(\.\d{1,3}){3}$/,Wr=[e=>e===0,e=>e===127,e=>e===10,(e,t)=>e===100&&t>=64&&t<=127,(e,t)=>e===172&&t>=16&&t<=31,(e,t)=>e===192&&t===168,(e,t)=>e===169&&t===254,(e,t,n)=>e===192&&t===0&&(n===0||n===2),(e,t)=>e===198&&(t===18||t===19),(e,t,n)=>e===198&&t===51&&n===100,(e,t,n)=>e===203&&t===0&&n===113,e=>e>=224];function Gr(e,t,n,r){return Wr.some(r=>r(e,t,n))}function Kr(e){if(!Ur.test(e))return!1;let[t=0,n=0,r=0,i=0]=e.split(`.`).map(Number);return t>255||n>255||r>255||i>255?!1:Gr(t,n,r,i)}function qr(e){let t=e.toLowerCase().trim(),n=t.lastIndexOf(`:`),r=[],i=t;if(n!==-1){let e=t.slice(n+1);if(e.includes(`.`)){let a=e.split(`.`).map(e=>Number.parseInt(e,10));if(a.length!==4||a.some(e=>Number.isNaN(e)||e<0||e>255))return null;let o=a[0]??0,s=a[1]??0,c=a[2]??0,l=a[3]??0;r=[o<<8|s,c<<8|l];let u=t.slice(0,n+1);i=u.endsWith(`::`)?u:u.slice(0,-1)}}let a=i.split(`::`);if(a.length>2)return null;let o=a[0]?a[0].split(`:`).filter(Boolean):[],s=a.length===2&&a[1]?a[1].split(`:`).filter(Boolean):[],c=8-r.length;if(a.length===1){if(o.length!==c)return null}else if(o.length+s.length>=c)return null;let l=c-(o.length+s.length),u=Array(l).fill(0),d=e=>/^[0-9a-f]{1,4}$/.test(e)?Number.parseInt(e,16):null,f=[];for(let e of o){let t=d(e);if(t===null)return null;f.push(t)}let p=[];for(let e of s){let t=d(e);if(t===null)return null;p.push(t)}return[...f,...u,...p,...r]}var H=(e,t,n)=>e.slice(t,n).every(e=>e===0),Jr=[e=>H(e,0,8),e=>H(e,0,7)&&e[7]===1,e=>((e[0]??0)&65472)==65152,e=>((e[0]??0)&65472)==65216,e=>((e[0]??0)&65024)==64512,e=>((e[0]??0)&65280)==65280,e=>e[0]===8193&&e[1]===3512,e=>e[0]===256&&H(e,1,4),e=>e[0]===100&&e[1]===65435&&e[2]===1,e=>e[0]===8193&&e[1]===0],Yr=[{match:e=>H(e,0,5)&&e[5]===65535,at:6},{match:e=>H(e,0,4)&&e[4]===65535&&e[5]===0,at:6},{match:e=>H(e,0,6),at:6},{match:e=>e[0]===100&&e[1]===65435&&H(e,2,6),at:6},{match:e=>e[0]===8194,at:1}];function Xr(e){let t=qr(e);return t?.length===8?Jr.some(e=>e(t))?!0:Yr.some(({match:e,at:n})=>{if(!e(t))return!1;let r=t[n]??0,i=t[n+1]??0;return Gr(r>>8&255,r&255,i>>8&255,i&255)}):!1}function Zr(e){let t=e.toLowerCase();for(;t.endsWith(`.`);)t=t.slice(0,-1);return t===`localhost`||t.endsWith(`.localhost`)||t===`local`||t.endsWith(`.local`)||t===`internal`||t.endsWith(`.internal`)||t===`lan`||t.endsWith(`.lan`)||t===`home.arpa`||t.endsWith(`.home.arpa`)||t===`localdomain`||t.endsWith(`.localdomain`)||t===`127.0.0.1`||t===`::1`||t===`[::1]`}function Qr(e){let t=e.startsWith(`[`)&&e.endsWith(`]`)?e.slice(1,-1):e;return Kr(t)||Xr(t)}function $r(e,t){let n;try{n=new URL(e)}catch{throw new T(`request`,`Invalid URL provided: "${e}"`)}let r=t?.allowPrivateNetworks??!1,i=t?.allowedHosts?.map(e=>e.toLowerCase())??[],a=n.hostname.toLowerCase(),o=r?[`http:`,`https:`]:[`https:`],s=t?.allowedSchemes?t.allowedSchemes.map(e=>e.endsWith(`:`)?e.toLowerCase():`${e.toLowerCase()}:`):o;if(!s.includes(n.protocol))throw new T(`blocked`,`URL scheme "${n.protocol}" is not permitted by network policy. Allowed: ${s.join(`, `)}`);if(!r&&!i.includes(a)){if(Zr(a))throw new T(`blocked`,`Access to loopback target "${a}" blocked by network guardrail. Enable allowPrivateNetworks to permit local addresses.`);if(Kr(a))throw new T(`blocked`,`Access to private IPv4 address "${a}" blocked by network guardrail.`);if(Xr(a.startsWith(`[`)&&a.endsWith(`]`)?a.slice(1,-1):a))throw new T(`blocked`,`Access to private IPv6 address "${a}" blocked by network guardrail.`)}return n}var ei=20,ti=new Set([301,302,303,307,308]);async function ni(e,t,n){let{resolveHost:r,policy:i}=t,a=e.hostname.toLowerCase();if(r===void 0||i?.allowPrivateNetworks===!0||i?.allowedHosts?.some(e=>e.toLowerCase()===a)===!0||a.startsWith(`[`)||Ur.test(a))return;let o=await r(a,n??void 0);if(o.length===0)throw new T(`blocked`,`Host "${a}" did not resolve to an address.`);let s=o.find(Qr);if(s!==void 0)throw new T(`blocked`,`Host "${a}" resolves to private address "${s}", blocked by network guardrail.`)}function ri(e,t){return e===303?t!==`HEAD`:(e===301||e===302)&&t===`POST`}async function ii(e,t,n){let r=n.fetchFn??fetch,i=async e=>{let r=performance.now();try{let r=$r(e,n.policy);return await ni(r,n,t.signal),r}finally{n.onCheck?.(performance.now()-r)}},a=await i(e);await n.beforeSend?.();let o=a.origin,s=new Headers(t.headers),c=t.method??`GET`,l=t.body,u=!0;for(let d=0;;d++){let f=new Headers(s);if(u)for(let[e,t]of Object.entries(n.originBoundHeaders??{}))f.set(e,t);let p=await ht(r,a.href,{...t,method:c,headers:f,body:l,redirect:`manual`}),m=p.headers.get(`location`);if(!n.followRedirects||!ti.has(p.status)||m===null)return p;if(await p.body?.cancel(),d===ei)throw new T(`network`,`Too many redirects from "${e}"`);a=await i(new URL(m,a).href),u&&=a.origin===o,ri(p.status,c)&&(c=`GET`,l=void 0,s.delete(`content-type`))}}var U=v().int().positive().max(2**53-1),ai=U.max(2147483647),oi=_({operationTimeoutMs:ai.optional(),connectTimeoutMs:ai.optional(),liveStepTimeoutMs:ai.optional(),maxWireRecordBytes:U.optional(),maxWireResponseBytes:U.optional(),maxEventBytes:U.optional(),maxStepBytes:U.optional(),maxStepEvents:U.optional(),maxPendingToolCalls:U.optional()}),si=[`text`,`image`,`speech`,`transcription`,`live`,`decision`,`embedding`],ci=w({id:o().regex(/^[A-Za-z][A-Za-z0-9]*$/),name:o().min(1),description:o().min(1),endpoints:re(y(si),o().min(1)),operationNames:re(y(si),o().regex(/^[a-z][a-z0-9_]*$/))});function li(e,t){return new T(`config`,D(`protocol.definition`,{id:e,issues:t}))}function ui(e){let t=ci.safeParse(e);if(!t.success)throw li(String(e.id),he(t.error))}function di(e,t,n){let r=Object.keys(t).toSorted().join(`, `),i=Object.keys(n).toSorted().join(`, `);if(r!==i)throw li(e,`operationNames name [${i}]; endpoints serve [${r}]`)}function fi(e,t,n,r){if(!n)throw new T(`internal`,D(`protocol.part_schema`,{protocol:e.id,kind:t}));let i=n.safeParse(r);if(!i.success)throw new T(`bad_response`,D(`protocol.part_invalid`,{protocol:e.id,kind:t}),{cause:i.error});return i.data}function pi(e,t){return t.type===`reasoning`?{...t,data:fi(e,`reasoning`,e.reasoning,t.data),origin:{protocol:e.id}}:t.type===`custom`?{type:`custom`,kind:`${e.id}.${t.kind}`,data:fi(e,t.kind,e.custom?.[t.kind],t.data)}:t}async function*mi(e,t){for await(let n of t)yield pi(e,n)}function hi(e,t){let{complete:n,openSession:r}=t;return{...t,...n?{complete:r=>mi(e,n.call(t,r))}:{},...r?{async openSession(n){let i=await r.call(t,n);return{...i,events:()=>mi(e,i.events())}}}:{}}}function gi(e,t,n){let r=n??{},i=e.options.safeParse(r),a=(e.refusedOptions?.(t)??[]).filter(e=>typeof r==`object`&&!!r&&e in r);if(i.success&&a.length===0)return i.data;let o=i.success?a.map(e=>`✖ ${t} takes no ${e}`).join(`
1
+ import{n as e}from"./rolldown-runtime-hePW80VL.js";import{$ as t,A as n,B as r,C as i,D as a,E as o,F as s,G as c,H as l,I as u,J as d,K as f,L as p,M as m,N as h,O as g,P as ee,Q as te,R as ne,S as re,T as _,U as ie,V as ae,W as oe,X as se,Y as ce,Z as le,a as ue,at as de,b as v,c as y,ct as fe,d as b,dt as pe,et as me,ft as he,g as ge,h as x,ht as _e,i as ve,it as ye,j as be,lt as xe,m as Se,mt as Ce,n as we,nt as Te,o as Ee,ot as De,p as S,q as Oe,r as ke,rt as Ae,st as je,tt as Me,u as Ne,ut as Pe,v as C,w as Fe,x as w,z as Ie}from"./schemas-D7cgkv3L.js";import{c as T,s as Le}from"./host-patterns-F-KZIzkF.js";import{$t as Re,A as E,Ar as ze,B as Be,Cn as Ve,D as He,En as Ue,Er as We,Jn as Ge,K as Ke,Lr as D,M as O,N as k,O as A,P as qe,Pn as Je,Pr as Ye,Qt as Xe,Sr as Ze,Tn as Qe,Xn as $e,Xt as et,Yt as tt,Zn as nt,Zt as rt,a as it,ar as at,bn as ot,c as j,dn as st,dr as ct,er as lt,fr as ut,gr as dt,hn as ft,hr as pt,ir as mt,jr as M,k as N,kr as ht,mr as gt,nn as _t,on as vt,or as yt,qn as bt,sr as xt,tr as St,un as Ct,ur as wt,wr as Tt,yn as Et}from"./shaped-data-7q5Be8sp.js";var Dt=e({endsWith:()=>be,gt:()=>m,gte:()=>h,includes:()=>ee,length:()=>Ie,lowercase:()=>r,lt:()=>ae,lte:()=>l,maxLength:()=>ie,maxSize:()=>oe,mime:()=>c,minLength:()=>f,minSize:()=>Oe,multipleOf:()=>d,negative:()=>ce,nonnegative:()=>se,nonpositive:()=>le,normalize:()=>te,overwrite:()=>t,positive:()=>me,properties:()=>Me,property:()=>Te,regex:()=>Ae,size:()=>ye,slugify:()=>de,startsWith:()=>De,toLowerCase:()=>je,toUpperCase:()=>fe,trim:()=>xe,uppercase:()=>Pe}),Ot=e({ZodISODate:()=>we,ZodISODateTime:()=>ke,ZodISODuration:()=>ve,ZodISOTime:()=>ue,date:()=>At,datetime:()=>kt,duration:()=>Mt,time:()=>jt});function kt(e){return u(ke,e)}function At(e){return s(we,e)}function jt(e){return ne(ue,e)}function Mt(e){return p(ve,e)}var P={...Fe,...Dt,iso:Ot},Nt=new Set(`$schema.$ref.$defs.definitions.$id.id.$comment.$anchor.$vocabulary.$dynamicRef.$dynamicAnchor.type.enum.const.anyOf.oneOf.allOf.not.properties.required.additionalProperties.patternProperties.propertyNames.minProperties.maxProperties.items.prefixItems.additionalItems.minItems.maxItems.uniqueItems.contains.minContains.maxContains.minLength.maxLength.pattern.format.minimum.maximum.exclusiveMinimum.exclusiveMaximum.multipleOf.description.default.contentEncoding.contentMediaType.contentSchema.unevaluatedItems.unevaluatedProperties.if.then.else.dependentSchemas.dependentRequired.nullable.readOnly`.split(`.`));function Pt(e,t){let n=e.$schema;return n===`https://json-schema.org/draft/2020-12/schema`?`draft-2020-12`:n===`http://json-schema.org/draft-07/schema#`?`draft-7`:n===`http://json-schema.org/draft-04/schema#`?`draft-4`:t??`draft-2020-12`}function Ft(e,t){return e.map((e,n)=>n<t?e:e.optional())}function It(e){return e.replace(/~1/g,`/`).replace(/~0/g,`~`)}function Lt(e,t){if(!e.startsWith(`#`))throw Error(`External $ref is not supported, only local refs (#/...) are allowed`);let n=e.slice(1).split(`/`).filter(Boolean);if(n.length===0)return t.rootSchema;let r=t.version===`draft-2020-12`?`$defs`:`definitions`;if(n[0]===r){let r=n[1]===void 0?void 0:It(n[1]);if(!r||!t.defs[r])throw Error(`Reference not found: ${e}`);return t.defs[r]}throw Error(`Reference not found: ${e}`)}function Rt(e,t){return P.transform(e=>e).check(n=>{let r=n.value;if(typeof r!=`object`||!r||Array.isArray(r))return;let i=Object.getOwnPropertyNames(r);if(t.minProperties!==void 0&&i.length<t.minProperties&&n.issues.push({origin:`object`,code:`too_small`,minimum:t.minProperties,inclusive:!0,message:`Too small: expected object to have >=${t.minProperties} properties`,input:r,inst:e,continue:!0}),t.maxProperties!==void 0&&i.length>t.maxProperties&&n.issues.push({origin:`object`,code:`too_big`,maximum:t.maxProperties,inclusive:!0,message:`Too big: expected object to have <=${t.maxProperties} properties`,input:r,inst:e,continue:!0}),t.keySchema)for(let e of i){let r=t.keySchema.safeParse(e);r.success||n.issues.push({code:`invalid_key`,origin:`record`,issues:r.error.issues,input:e,path:[e],continue:!0})}}).pipe(e)}function zt(e,t){if(e===null)return`z`;let n=typeof e;if(n!==`object`){if(n===`number`&&Number.isNaN(e))return null;let t=String(e);return`${n[0]}${t.length}:${t}`}if(t.has(e))return null;t.add(e);try{if(Array.isArray(e)){let n=[];for(let r of e){let e=zt(r,t);if(e===null)return null;n.push(e)}return`a${n.length}:[${n.join(`,`)}]`}let n=Object.keys(e).sort(),r=[];for(let i of n){let n=zt(e[i],t);if(n===null)return null;r.push(`${i.length}:${i}=${n}`)}return`o${r.length}:{${r.join(`,`)}}`}finally{t.delete(e)}}var Bt=new Set([`items`,`prefixItems`,`additionalItems`,`additionalProperties`,`contains`,`propertyNames`,`not`,`if`,`then`,`else`,`allOf`,`anyOf`,`oneOf`,`unevaluatedItems`,`unevaluatedProperties`,`contentSchema`]),Vt=new Set([`properties`,`patternProperties`,`dependentSchemas`,`dependencies`,`$defs`,`definitions`]);function Ht(e){return typeof e!=`object`||!e?!1:Array.isArray(e)?e.some(Ht):typeof e.$ref==`string`||Object.entries(e).some(([e,t])=>Bt.has(e)?Ht(t):!Vt.has(e)||typeof t!=`object`||!t?!1:Object.values(t).some(Ht))}function Ut(e){return e===1?`element`:`elements`}function Wt(e,t){return P.transform(e=>e).check(e=>{let n=e.value;if(Array.isArray(n)){if(t.uniqueItems===!0){let t=new Map;for(let r=0;r<n.length;r++){let i=zt(n[r],new Set);if(i===null)continue;let a=t.get(i);a===void 0?t.set(i,r):e.issues.push({code:`custom`,message:`Array items must be unique: element at index ${r} duplicates the one at index ${a}`,input:n,path:[r],continue:!0})}}if(t.containsSchema){let r=t.minContains??1,i=t.maxContains===void 0?1/0:t.maxContains+1,a=0;for(let e of n)if(t.containsSchema.safeParse(e).success&&++a>=i)break;a<r&&e.issues.push({code:`custom`,message:`Array must contain at least ${r} matching ${Ut(r)}; found ${a}`,input:n,continue:!0}),t.maxContains!==void 0&&a>t.maxContains&&e.issues.push({code:`custom`,message:`Array must contain at most ${t.maxContains} matching ${Ut(t.maxContains)}`,input:n,continue:!0})}}}).pipe(e)}function Gt(e,t){if(e!==!1)return e===void 0||e===!0?P.any():F(e,t)}var Kt=/^(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/;function qt(e,t){if(e.not!==void 0){if(typeof e.not==`object`&&Object.keys(e.not).length===0)return P.never();throw Error(`not is not supported in Zod (except { not: {} } for never)`)}if(e.unevaluatedItems!==void 0)throw Error(`unevaluatedItems is not supported`);if(e.unevaluatedProperties!==void 0)throw Error(`unevaluatedProperties is not supported`);if(e.if!==void 0||e.then!==void 0||e.else!==void 0)throw Error(`Conditional schemas (if/then/else) are not supported`);if(e.dependentSchemas!==void 0||e.dependentRequired!==void 0)throw Error(`dependentSchemas and dependentRequired are not supported`);if(e.$ref){let n=e.$ref;if(t.refs.has(n))return t.refs.get(n);if(t.processing.has(n))return P.lazy(()=>{if(!t.refs.has(n))throw Error(`Circular reference not resolved: ${n}`);return t.refs.get(n)});t.processing.add(n);let r=F(Lt(n,t),t);return t.refs.set(n,r),t.processing.delete(n),r}if(e.enum!==void 0){let n=e.enum;if(t.version===`openapi-3.0`&&e.nullable===!0&&n.length===1&&n[0]===null)return P.null();if(n.length===0)return P.never();if(n.length===1)return P.literal(n[0]);if(n.every(e=>typeof e==`string`))return P.enum(n);let r=n.map(e=>P.literal(e));return r.length<2?r[0]:P.union([r[0],r[1],...r.slice(2)])}if(e.const!==void 0)return P.literal(e.const);let n=e.type;if(Array.isArray(n)){let r=n.map(n=>qt({...e,type:n},t));return r.length===0?P.never():r.length===1?r[0]:P.union(r)}if(!n)return P.any();let r;switch(n){case`string`:{let t=P.string();if(e.format){let n=e.format;n===`email`?t=t.check(P.email()):n===`uri`||n===`uri-reference`?t=t.check(P.url()):n===`uuid`||n===`guid`?t=t.check(P.uuid()):n===`date-time`?t=t.check(P.iso.datetime({offset:!0})):n===`date`?t=t.check(P.iso.date()):n===`time`?t=t.check(P.regex(Kt)):n===`duration`?t=t.check(P.iso.duration()):n===`hostname`?t=t.check(P.hostname()):n===`ipv4`?t=t.check(P.ipv4()):n===`ipv6`?t=t.check(P.ipv6()):n===`mac`?t=t.check(P.mac()):n===`cidr`?t=t.check(P.cidrv4()):n===`cidr-v6`?t=t.check(P.cidrv6()):n===`base64`?t=t.check(P.base64()):n===`base64url`?t=t.check(P.base64url()):n===`e164`?t=t.check(P.e164()):n===`credit_card`?t=t.check(P.creditCard()):n===`iban`?t=t.check(P.iban()):n===`jwt`?t=t.check(P.jwt()):n===`emoji`?t=t.check(P.emoji()):n===`nanoid`?t=t.check(P.nanoid()):n===`cuid`?t=t.check(P.cuid()):n===`cuid2`?t=t.check(P.cuid2()):n===`ulid`?t=t.check(P.ulid()):n===`xid`?t=t.check(P.xid()):n===`ksuid`&&(t=t.check(P.ksuid()))}typeof e.minLength==`number`&&(t=t.min(e.minLength)),typeof e.maxLength==`number`&&(t=t.max(e.maxLength)),e.pattern&&(t=t.regex(new RegExp(e.pattern))),r=t;break}case`number`:case`integer`:{let t=n===`integer`?P.number().int():P.number();typeof e.minimum==`number`&&e.exclusiveMinimum!==!0&&(t=t.min(e.minimum)),typeof e.maximum==`number`&&e.exclusiveMaximum!==!0&&(t=t.max(e.maximum)),typeof e.exclusiveMinimum==`number`?t=t.gt(e.exclusiveMinimum):e.exclusiveMinimum===!0&&typeof e.minimum==`number`&&(t=t.gt(e.minimum)),typeof e.exclusiveMaximum==`number`?t=t.lt(e.exclusiveMaximum):e.exclusiveMaximum===!0&&typeof e.maximum==`number`&&(t=t.lt(e.maximum)),typeof e.multipleOf==`number`&&(t=t.multipleOf(e.multipleOf)),r=t;break}case`boolean`:r=P.boolean();break;case`null`:r=P.null();break;case`object`:{let n={},i=e.properties||{},a=new Set(e.required||[]),o=typeof e.additionalProperties==`object`?F(e.additionalProperties,t):void 0;for(let[e,r]of Object.entries(i)){let i=F(r,t);Ce(n,e,a.has(e)?i:i.optional())}if(e.patternProperties){let i=e.patternProperties,a=Object.keys(i),o=[];for(let e of a){let n=F(i[e],t),r=P.string().regex(new RegExp(e));o.push(P.looseRecord(r,n))}let s=[];if(Object.keys(n).length>0&&s.push(P.object(n).passthrough()),s.push(...o),s.length===0)r=P.object({}).passthrough();else if(s.length===1)r=s[0];else{let e=P.intersection(s[0],s[1]);for(let t=2;t<s.length;t++)e=P.intersection(e,s[t]);r=e}if(e.additionalProperties===!1){let e=Object.keys(n),t=a.map(e=>new RegExp(e)),i=r;r=r.check(n=>{if(!_e(n.value))return;let r=[];for(let i of Object.keys(n.value))e.includes(i)||t.some(e=>e.test(i))||r.push(i);r.length&&n.issues.push({code:`unrecognized_keys`,keys:r,input:n.value,inst:i})})}}else{let t=P.object(n);r=e.additionalProperties===!1?t.strict():o?t.catchall(o):t.passthrough()}let s=e.propertyNames!==void 0&&e.propertyNames!==!0,c=typeof e.minProperties==`number`?e.minProperties:void 0,l=typeof e.maxProperties==`number`?e.maxProperties:void 0;if(s||c!==void 0||l!==void 0){let n;s&&(n=F(typeof e.propertyNames==`object`&&e.propertyNames.type===void 0?{type:`string`,...e.propertyNames}:e.propertyNames,t)),r=Rt(r,{keySchema:n,minProperties:c,maxProperties:l})}break}case`array`:{let n=e.prefixItems,i=e.items;if(n&&Array.isArray(n)){let a=typeof e.minItems==`number`?e.minItems:0,o=Ft(n.map(e=>F(e,t)),a),s=Array.isArray(i)?void 0:Gt(i,t),c=P.tuple(o);r=s?c.rest(s):c,typeof e.minItems==`number`&&(r=r.check(P.minLength(e.minItems))),typeof e.maxItems==`number`&&(r=r.check(P.maxLength(e.maxItems)))}else if(Array.isArray(i)){let n=typeof e.minItems==`number`?e.minItems:0,a=Ft(i.map(e=>F(e,t)),n),o=Gt(e.additionalItems,t),s=P.tuple(a);r=o?s.rest(o):s,typeof e.minItems==`number`&&(r=r.check(P.minLength(e.minItems))),typeof e.maxItems==`number`&&(r=r.check(P.maxLength(e.maxItems)))}else if(i!==void 0){let n=F(i,t),a=P.array(n);typeof e.minItems==`number`&&(a=a.min(e.minItems)),typeof e.maxItems==`number`&&(a=a.max(e.maxItems)),r=a}else r=P.array(P.any());(e.uniqueItems===!0||e.contains!==void 0)&&(r=Wt(r,{uniqueItems:e.uniqueItems===!0,containsSchema:e.contains===void 0?void 0:F(e.contains,t),minContains:typeof e.minContains==`number`?e.minContains:void 0,maxContains:typeof e.maxContains==`number`?e.maxContains:void 0}));break}default:throw Error(`Unsupported type: ${n}`)}return r}function F(e,t){if(typeof e==`boolean`)return e?P.any():P.never();let n=qt(e,t),r=e.type||e.enum!==void 0||e.const!==void 0;if(e.anyOf&&Array.isArray(e.anyOf)){let i=e.anyOf.map(e=>F(e,t)),a=P.union(i);n=r?P.intersection(n,a):a}if(e.oneOf&&Array.isArray(e.oneOf)){let i=e.oneOf.map(e=>F(e,t)),a=P.xor(i);n=r?P.intersection(n,a):a}if(e.allOf&&Array.isArray(e.allOf)){if(e.allOf.length===0)n=r?n:P.any();else{let i=r?n:F(e.allOf[0],t),a=+!r;for(let n=a;n<e.allOf.length;n++)i=P.intersection(i,F(e.allOf[n],t));n=i}}e.nullable===!0&&t.version===`openapi-3.0`&&(n=P.nullable(n)),e.readOnly===!0&&(n=P.readonly(n)),e.default!==void 0&&(n=n.default(e.default));let i={};for(let t of[`$id`,`id`,`$comment`,`$anchor`,`$vocabulary`,`$dynamicRef`,`$dynamicAnchor`])t in e&&(i[t]=e[t]);for(let t of[`contentEncoding`,`contentMediaType`,`contentSchema`])t in e&&(i[t]=e[t]);if(e.type===`object`&&e.$ref===void 0){e.propertyNames!==void 0&&!Ht(e.propertyNames)&&(i.propertyNames=e.propertyNames);for(let t of[`minProperties`,`maxProperties`])e[t]!==void 0&&(i[t]=e[t])}if(e.type===`array`&&e.$ref===void 0){e.contains!==void 0&&!Ht(e.contains)&&(i.contains=e.contains);for(let t of[`uniqueItems`,`minContains`,`maxContains`])e[t]!==void 0&&(i[t]=e[t])}for(let t of Object.keys(e))Nt.has(t)||Ce(i,t,e[t]);return Object.keys(i).length>0&&t.registry.add(n,i),e.description&&(n=n.describe(e.description)),n}function Jt(e,t){if(typeof e==`boolean`)return e?P.any():P.never();let n;try{n=JSON.parse(JSON.stringify(e))}catch{throw Error(`fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas`)}let r={version:Pt(n,t?.defaultTarget),defs:n.$defs||n.definitions||{},refs:new Map,processing:new Set,rootSchema:n,registry:t?.registry??pe};return F(n,r)}var Yt=y(Le),Xt=w({key:y(Ye),params:i(o(),a([o(),v()])).optional()}),Zt=a([Xt,b(Xt).readonly()]),Qt=w({origin:y(gt),tool:o(),depth:v()}),$t=w({rule:o(),severity:y(ut),span:w({start:v(),end:v()}).optional(),match:o().optional(),label:o().optional(),doc:o().optional(),pattern:o().optional(),signal:o().optional()}),en=w({stage:y(ct),boundary:y(dt).optional(),trust:y(pt),action:y(wt),hits:b($t),provenance:Qt.optional(),errorInternal:o().optional(),errorSummary:o().optional()}),tn=ge(),I=i(o(),tn),nn=_({protocol:o().min(1),provider:o().min(1),version:v().int().positive(),apiId:o().min(1),keySlot:o().min(1).optional(),compatibilityKey:o(),coveredHistoryLength:v().int().nonnegative(),coveredHistoryHash:o(),data:tn,wireCallIds:i(o().min(1),o().min(1)).optional()}),rn=_({code:C(`provider_state_rebuilt`),reason:y([`provider_changed`,`model_changed`,`connection_changed`,`key_changed`,`history_changed`,`version_changed`])}),an=_({history:y([`host`,`stateless`,`provider`]).optional()});async function on(e){let t=e=>{if(Array.isArray(e))return e.map(t);if(e&&typeof e==`object`){let n={};for(let r of Object.keys(e).sort())n[r]=t(e[r]);return n}return e},n=await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(JSON.stringify(t(e.map(e=>{let t=t=>e.role===`user`?t.match(/^<user_data>\n([\s\S]*)\n<\/user_data>$/)?.[1]??t:t,n=[...e.content===void 0?[]:[{type:`text`,text:t(e.content)}],...(e.parts??[]).map(e=>e.type===`text`?{...e,text:t(e.text)}:e)],{content:r,parts:i,...a}=e;return{...a,...n.length?{parts:n}:{}}}))))),r=``;for(let e of new Uint8Array(n))r+=e.toString(16).padStart(2,`0`);return r}var L=i(o(),g()),R=o().trim().min(1),sn=w({type:C(`text`),text:o()}),cn=w({type:y(st),mimeType:o(),data:o()}),ln=w({type:y(st),mimeType:o(),uri:o()}),un=a([sn,cn,ln]),dn=un,fn=w({protocol:o().min(1),provider:o().min(1).optional(),apiId:o().min(1).optional()}),pn=w({text:o().optional(),data:tn,origin:fn}),mn=w({role:y([`system`,`user`,`assistant`,`tool`]),content:o().optional(),parts:b(un).optional(),tool_calls:b(w({id:o(),type:C(`function`),function:w({name:o(),arguments:o()})})).optional(),reasoning:b(pn).optional(),tool_call_id:o().optional(),name:o().optional(),metadata:L.optional()}),hn=mn,gn=w({kind:y(Ue),native:o().optional()}),_n=gn,vn=[`input`,`output`],yn=w({usd:v(),upstreamUsd:v().optional(),partial:C(!0).optional()}),bn=w({type:o(),count:v(),searchQueryCount:v().optional()}),xn=w({input:v(),output:v(),thinking:v().optional(),toolUse:v().optional(),cached:v().optional(),cacheWrite:v().optional(),total:v(),cost:yn.optional(),estimated:b(y(vn)).optional(),unknownMedia:w({input:v().optional(),output:v().optional()}).optional(),byModality:w({input:i(o(),v()).optional(),output:i(o(),v()).optional()}).optional(),grounding:b(bn).optional()});w({id:o().optional(),model:o().optional()});var Sn=w({title:o(),uri:o(),type:y([`web`,`maps`]),placeId:o().optional()}),Cn=Sn,wn=w({metadata:L.optional(),chunks:b(g()).optional(),searchHtml:o().optional()}),z={provider:o().min(1),raw:L.optional(),partial:S().optional()},Tn=x(`kind`,[w({...z,kind:C(`code_execution_call`),code:o(),language:o().optional(),id:o()}),w({...z,kind:C(`code_execution_result`),result:o().optional(),isError:S().optional(),callId:o().optional()}),w({...z,kind:y([`input_transcription`,`output_transcription`]),interim:S().optional()}),w({...z,kind:y([`voice_activity`,`url_context`])}),w({...z,kind:C(`session_resumption`),resumable:S()}),w({...z,kind:C(`provider_step`),step:o()})]),En=w({cause:C(`go_away`),code:v(),closedAfterMs:v(),errorKind:Yt.optional()}),Dn=x(`kind`,[w({kind:C(`closing_soon`),timeLeftMs:v().optional()}),w({kind:C(`ended`),timeLeftMs:v().optional(),ended:En,message:o()}),w({kind:y([`waiting_for_input`,`turn_complete`,`working`,`idle`])})]),On=w({code:o(),kind:Yt,message:o(),error:o().optional(),details:g().optional()}),kn=w({slot:R,authType:y(ot),service:R,message:R,authorizationUrl:o().optional(),state:o().optional(),issuer:o().optional(),resource:o().optional(),requiredScopes:b(R).optional()}),An={preparedArguments:i(o(),g()).optional(),tool:R,permission:y(Ve).optional(),summary:R.optional(),request:R.optional(),access:y(Et).optional()},jn=x(`kind`,[w({...An,kind:y([`confirmation`,`permission`,`page`])}),w({...An,kind:C(`auth`),authChallenge:kn})]),Mn=jn,Nn=w({code:o(),message:o(),severity:y([`info`,`warning`,`error`]).optional()}),Pn=w({name:o(),kind:o(),status:o(),inputs:L.optional(),outputs:L.optional()}),Fn={status:C(tt),prompt:R},In=x(`kind`,[w({...Fn,kind:y([`confirm`,`text`]),options:b(R).optional()}),w({...Fn,kind:C(`choice`),options:b(R).min(1)})]);function Ln(e){return In.safeParse(e).success}var Rn=w({type:C(`function`),name:o(),description:o(),parameters:L}),zn=w({builtins:b(o()),gated:b(o()),visible:b(o()),executable:b(o()),path:o().optional(),sessionPermissions:b(o()).optional(),wire:b(Rn),modelBackground:S().optional()}),Bn=zn,Vn=_({callId:o().min(1),operationId:o().min(1).max(256)}),Hn={name:o(),callId:o()},Un=w({...Hn,phase:Ne().optional(),arguments:L,reasoning:b(pn).optional(),stepId:o().min(1).optional(),stepCallCount:v().int().min(1).optional()}),B={...Hn,at:v()},Wn=x(`phase`,[w({...B,phase:C(`running`),edited:w({from:L,to:L}).optional(),activity:o().optional()}),w({...B,phase:C(`dispatch`),grantId:o().min(1),arguments:L}),w({...B,phase:C(`progress`),data:g()}),w({...B,phase:C(`draft`),text:o()}),w({...B,phase:C(`trace`),step:Pn}),w({...B,phase:C(`artifact`),artifact:g()}),w({...B,phase:C(`warning`),warning:Nn}),w({...B,phase:C(`complete`),output:g(),awaiting:S().optional(),readBack:o().optional(),parts:b(un).optional(),activityPast:o().optional(),tokens:xn.optional()}),w({...B,phase:C(`gate`),gate:jn,readBack:o().optional()}),w({...B,phase:C(`background`),readBack:o()}),w({...B,phase:C(`error`),failure:On,readBack:o().optional(),activityPast:o().optional(),tokens:xn.optional()}),w({...B,phase:C(`cancel`)})]),Gn=a([Wn,Un]).and(w({operationId:o().min(1).max(256).optional()})),Kn=w({code:y(ft),message:o(),field:o()}),qn=w({needed:S(),meter:y(Xe),tokens:v(),unknownMedia:v(),promptTokens:v().optional(),promptTokensEstimated:S().optional(),history:b(mn)}),Jn=w({stop:y(Ue).optional(),error:Yt.optional(),errorInternal:o().optional(),empty:C(!0).optional(),unreadable:C(!0).optional()}),Yn=[`tool`,`gate`];function Xn(e,t){let{stop:n,...r}=e,{kind:i}=n;return i===`tool`||i===`gate`?t?{type:`done`,...r,stop:{...n,kind:i},tools:t}:void 0:{type:`done`,...r,stop:{...n,kind:i}}}var Zn=y(Yn),Qn=y(Ue).exclude(Yn),$n={providerState:nn.optional(),type:C(`done`),tokens:xn.optional(),traceparent:o().optional(),steps:v().int().nonnegative().optional(),compaction:qn.optional(),interrupted:S().optional(),interactionId:o().optional()},er=a([w({...$n,stop:w({kind:Zn,native:o().optional()}),tools:zn}),w({...$n,stop:w({kind:Qn,native:o().optional()}),tools:Ne().optional()})]),V={provider_checkpoint:w({type:C(`provider_checkpoint`),providerState:nn,history:b(hn).optional()}),provider_warning:w({type:C(`provider_warning`),warning:rn}),text:w({type:C(`text`),text:o()}),thought:w({type:C(`thought`),text:o()}),custom:w({type:C(`custom`),kind:o().min(1),data:I}),structured:w({type:C(`structured`),structured:g(),removed:b(w({path:o(),reason:o(),item:g()})).optional(),failed:b(w({path:o(),error:o()})).optional()}),structured_draft:w({type:C(`structured_draft`),text:o()}),attempt:w({type:C(`attempt`),attempt:v().int().positive(),reason:y([`validation`,`egress`])}),media:w({type:C(`media`),media:w({mimeType:o(),data:o()})}),grounding:w({type:C(`grounding`),grounding:wn}),citation:w({type:C(`citation`),sources:b(Sn),callId:o().optional()}),compaction:w({type:C(`compaction`),timing:C(`before`),meter:y(Xe),tokensBefore:v(),unknownMedia:v(),messagesBefore:v(),messagesAfter:v(),outcome:y(Re),history:b(mn),summary:o().optional(),failure:Jn.optional(),droppedMedia:v(),tokens:xn.optional()}),evidence:w({type:C(`evidence`),evidence:Tn,text:o().optional(),sessionResumptionHandle:o().optional()}),tokens:w({type:C(`tokens`),tokens:xn,interactionId:o().optional()}),session:w({type:C(`session`),session:Dn,errorInternal:o().optional()}),guardrail:w({type:C(`guardrail`),guardrail:en}),stage:w({type:C(`stage`),stage:y(Qe),callId:o().optional(),toolName:o().optional(),callNotStarted:S().optional(),awaiting:S().optional(),gate:jn.optional(),stop:_n.optional(),stageWarnings:b(Kn).optional(),injected:b(w({id:o().regex(/\S/),messages:b(mn)})).min(1).optional(),released:v().int().nonnegative().optional()}),tool_draft:w({type:C(`tool_draft`),callId:o().min(1),name:o(),text:o()}),tool:w({type:C(`tool`),tool:Gn,errorInternal:o().optional()}),error:w({type:C(`error`),errorKind:Yt,error:o().optional(),errorCopy:Zt.optional(),errorInternal:o().optional()}),done:er},tr=a([x(`type`,[V.provider_warning,V.provider_checkpoint,V.text,V.thought,V.custom,V.structured,V.structured_draft,V.attempt,V.media,V.grounding,V.citation,V.compaction,V.evidence,V.tokens,V.session,V.guardrail,V.stage,V.tool_draft,V.tool,V.error]),V.done]),nr=V;function rr(e){return e.type===`text`||e.type===`media`||e.type===`structured`||e.type===`structured_draft`}function ir(e,t){let n=[],r=t;for(let t of e)if(!rr(t))n.push(t);else if(t.type!==`text`)r>0&&n.push(t);else if(r>0){let e=t.text.slice(0,r);r-=e.length,n.push(e===t.text?t:{...t,text:e})}return n}function ar(e){let t=[],n=0;for(let r of e){if(r.type===`attempt`){let e=t.splice(n);t.push(...e.filter(e=>!rr(e)))}r.type===`stage`&&r.released!==void 0&&t.push(...ir(t.splice(n),r.released)),t.push(r),r.type===`done`&&(n=t.length)}return t}var or=[`reply`,`reply_structured`];function sr(e,t,n,r={}){if(!qe([t],n))return{action:`allow`,hits:[],value:e};let i=nt(e);if(i.unscannable)return{action:`block`,hits:[{rule:at.unscannable,severity:`high`}]};let a=O(i.text,t,n,r);if(a.action!==`redact`){let{errorInternal:t,errorSummary:n}=a,r=t&&n?{errorInternal:t,errorSummary:n}:{};return{action:a.action,hits:a.hits,value:e,...r}}let o=$e(e,e=>O(e,t,n,r).text??``),s=O(nt(o).text,t,n,r).action;return s===`redact`||s===`block`?{action:`block`,hits:a.hits}:{action:`redact`,hits:a.hits,value:o}}function cr(e,t,{boundary:n,reportedTo:r=e.text.length,scope:i={}}){let a=O(e.text,n,t,i),o=e.structured===void 0?void 0:sr(e.structured,`reply_structured`,t,i),s=r>=e.text.length?[]:a.hits.filter(e=>!e.span||e.span.start>=r),c=[a.action===`flag`?k(n,{action:s.length>0?`flag`:`allow`,hits:s}):k(n,a),o?k(`reply_structured`,o):void 0].filter(e=>e!==void 0),l=[a,o].flatMap(e=>e?.action===`block`?e.hits:[]);return{payload:{text:a.text??e.text,...o?{structured:o.value}:{}},rewritten:a.action===`redact`,events:c,...l.length>0?{blocked:l}:{}}}function lr(e,t=[]){if(e.blocked)return e.blocked;let n=new Set(e.events.flatMap(e=>e.hits.map(e=>e.rule))),r=t.filter(e=>!n.has(e.rule));return r.length>0?r:void 0}function ur(e,t){return e?t.startsWith(e)?t.slice(e.length):`\n\n${t}`:t}function dr(e,t){return D(e?`egress.refusal_cut`:`egress.refusal`,{},t)}var fr=`</tool_data>`,pr=`<tool_data`,mr=new Set([`http`,`mcp`,`delegated`]);function hr(e){return mr.has(e)}function gr(e){let t=e.toLowerCase(),n=``,r=0;for(;r<e.length;){let i=t.indexOf(pr,r),a=t.indexOf(fr,r),o=-1,s=null;if(i>=0&&(a<0||i<=a)?(o=i,s=`open`):a>=0&&(o=a,s=`close`),o<0||s===null){n+=e.slice(r);break}if(n+=e.slice(r,o),s===`close`){r=o+12;continue}let c=e.indexOf(`>`,o+10);if(c<0){n+=e.slice(o);break}r=c+1}return n}function _r(e,t,n=`none`,r){let i=D(`advisory.guidance`,{},r).trim();return`<tool_data ${`tool="${t.tool}" origin="${t.origin}"`+(n===`none`?``:` advisory="${n}"`)}>\n${n===`none`?``:`${vr(n,r)}${i?` ${i}`:``}\n`}${gr(e)}\n${fr}`}function vr(e,t){return D(e===`high`?`advisory.notice_high`:`advisory.notice_elevated`,{},t)}function yr(e,t){if(t===void 0)return e;let n=nt(t);return n.unscannable?e:`${e}\n${n.text}`}var br={action:`allow`,hits:[]};function xr(e,t,n,r){return t?O(e,t,n,r):{...br,text:e}}function Sr(e,t,n,r,i,a=[],o){let s=xr(yr(e,t),i,r.detect,{callable:a}),c=s.hits.filter(({rule:e})=>e===mt.tool_instructions),l=hr(n.origin),u=s.action===`allow`?void 0:{stage:`tool_result`,...i?{boundary:i}:{},trust:`untrusted`,action:s.action,hits:s.hits,provenance:n},d={...c.length>0?{suspicious:c}:{},...u?{event:u}:{}};return s.text===void 0?d:{text:l?_r(s.text,n,Ke(c.map(({signal:e})=>e)),o):s.text,...d}}function Cr(e,t,n,r){let i=xr(gr(e),r,n.detect),a=r?k(r,i,t):void 0;return{...i.text===void 0?{}:{text:i.text},...a?{event:a}:{}}}function wr(e,t,n,r){if(!r||e===void 0)return{value:e};let i=sr(e,r,n.detect),a=k(r,i,t);return{...i.action===`block`?{}:{value:i.value},...a?{event:a}:{}}}function Tr(e,t,n,r,i={}){if(!(r&&qe([r],n.detect)))return{args:e};let a=e=>{let n=k(r,{action:`block`,hits:e},t);return n?{event:n}:{}},o=nt(e);if(o.unscannable)return a([{rule:at.unscannable,severity:`high`}]);let s=O(o.text,r,n.detect,i);if(s.action===`block`)return a(s.hits);let c=k(r,s,t);if(s.action!==`redact`)return{args:e,...c?{event:c}:{}};let l=$e(e,e=>O(e,r,n.detect,i).text??``),u=O(nt(l).text,r,n.detect,i).action;return u===`redact`||u===`block`?a(s.hits):{args:l,...c?{event:c}:{}}}function Er(e,t){if(e.action!==`allow`)return{stage:`tool_call`,trust:`untrusted`,action:e.action,hits:e.hits,provenance:t}}function Dr(e,t,n=[]){let r=e?.sources??[],i=e?.suspicious??[];return hr(t.origin)?{sources:[...r,t],suspicious:[...i,...n]}:{sources:r,suspicious:i}}function Or(e){return(e?.sources.length??0)>0}function kr(e){return(e?.suspicious.length??0)>0}var Ar={"read-only":0,"read-write":1,destructive:2},jr={off:1/0,destructive:2,write:1};function Mr(e,t,n,r){if(!Or(e))return{action:`allow`};let i=Ar[t]??0;if(i===0)return{action:`allow`};let a=kr(e),o=[{rule:a?xt.steeredTurn:xt.taintedTurn,severity:`high`}];if(i<jr[n.taint?.afterRemoteRead??`off`])return{action:`flag`,hits:o};let s=e?.sources.map(e=>e.tool).join(`, `)??``,c=D(a?`taint.reason_steered`:`taint.reason_tainted`,{},r);return{action:`block`,hits:o,rejection:D(`taint.blocked`,{access:t,sources:s,reason:c},r)}}var Nr={onBlock:`retry`,maxRetries:1};function Pr(e){return{onBlock:e?.onBlock??Nr.onBlock,maxRetries:e?.maxRetries??Nr.maxRetries}}function Fr(e){return{detect:Ge(e?.detect),allow:bt(e?.detect),blockedReply:Pr(e?.blockedReply),network:e?.network,quota:e?.quota,taint:e?.taint}}function Ir(e){return(e.split(`;`)[0]??``).trim().toLowerCase()}function Lr(e,t){let n=Ir(t);return e.some(e=>{let t=Ir(e);return t.endsWith(`/*`)?n.startsWith(t.slice(0,-1)):t===n})}function Rr(e){return Ct[Ir(e)]}function zr(e){return e.type===`text`||e.type===`image`||e.type===`transcription`||e.type===`live`?e.inputs:void 0}function Br(e,t){let n=zr(e);return t===`voice`?n?.voice?.accept:n?.attachments?.accept}function Vr(e,t){if(Rr(t))for(let n of[`attachments`,`voice`]){let r=Br(e,n);if(r&&Lr(r,t))return n}}function Hr(e,t){let n=e.models[t];if(!n)throw new T(`config`,`Profile ${e.id} has no model binding for '${t}'`);return n}var Ur=/^\d{1,3}(\.\d{1,3}){3}$/,Wr=[e=>e===0,e=>e===127,e=>e===10,(e,t)=>e===100&&t>=64&&t<=127,(e,t)=>e===172&&t>=16&&t<=31,(e,t)=>e===192&&t===168,(e,t)=>e===169&&t===254,(e,t,n)=>e===192&&t===0&&(n===0||n===2),(e,t)=>e===198&&(t===18||t===19),(e,t,n)=>e===198&&t===51&&n===100,(e,t,n)=>e===203&&t===0&&n===113,e=>e>=224];function Gr(e,t,n,r){return Wr.some(r=>r(e,t,n))}function Kr(e){if(!Ur.test(e))return!1;let[t=0,n=0,r=0,i=0]=e.split(`.`).map(Number);return t>255||n>255||r>255||i>255?!1:Gr(t,n,r,i)}function qr(e){let t=e.toLowerCase().trim(),n=t.lastIndexOf(`:`),r=[],i=t;if(n!==-1){let e=t.slice(n+1);if(e.includes(`.`)){let a=e.split(`.`).map(e=>Number.parseInt(e,10));if(a.length!==4||a.some(e=>Number.isNaN(e)||e<0||e>255))return null;let o=a[0]??0,s=a[1]??0,c=a[2]??0,l=a[3]??0;r=[o<<8|s,c<<8|l];let u=t.slice(0,n+1);i=u.endsWith(`::`)?u:u.slice(0,-1)}}let a=i.split(`::`);if(a.length>2)return null;let o=a[0]?a[0].split(`:`).filter(Boolean):[],s=a.length===2&&a[1]?a[1].split(`:`).filter(Boolean):[],c=8-r.length;if(a.length===1){if(o.length!==c)return null}else if(o.length+s.length>=c)return null;let l=c-(o.length+s.length),u=Array(l).fill(0),d=e=>/^[0-9a-f]{1,4}$/.test(e)?Number.parseInt(e,16):null,f=[];for(let e of o){let t=d(e);if(t===null)return null;f.push(t)}let p=[];for(let e of s){let t=d(e);if(t===null)return null;p.push(t)}return[...f,...u,...p,...r]}var H=(e,t,n)=>e.slice(t,n).every(e=>e===0),Jr=[e=>H(e,0,8),e=>H(e,0,7)&&e[7]===1,e=>((e[0]??0)&65472)==65152,e=>((e[0]??0)&65472)==65216,e=>((e[0]??0)&65024)==64512,e=>((e[0]??0)&65280)==65280,e=>e[0]===8193&&e[1]===3512,e=>e[0]===256&&H(e,1,4),e=>e[0]===100&&e[1]===65435&&e[2]===1,e=>e[0]===8193&&e[1]===0],Yr=[{match:e=>H(e,0,5)&&e[5]===65535,at:6},{match:e=>H(e,0,4)&&e[4]===65535&&e[5]===0,at:6},{match:e=>H(e,0,6),at:6},{match:e=>e[0]===100&&e[1]===65435&&H(e,2,6),at:6},{match:e=>e[0]===8194,at:1}];function Xr(e){let t=qr(e);return t?.length===8?Jr.some(e=>e(t))?!0:Yr.some(({match:e,at:n})=>{if(!e(t))return!1;let r=t[n]??0,i=t[n+1]??0;return Gr(r>>8&255,r&255,i>>8&255,i&255)}):!1}function Zr(e){let t=e.toLowerCase();for(;t.endsWith(`.`);)t=t.slice(0,-1);return t===`localhost`||t.endsWith(`.localhost`)||t===`local`||t.endsWith(`.local`)||t===`internal`||t.endsWith(`.internal`)||t===`lan`||t.endsWith(`.lan`)||t===`home.arpa`||t.endsWith(`.home.arpa`)||t===`localdomain`||t.endsWith(`.localdomain`)||t===`127.0.0.1`||t===`::1`||t===`[::1]`}function Qr(e){let t=e.startsWith(`[`)&&e.endsWith(`]`)?e.slice(1,-1):e;return Kr(t)||Xr(t)}function $r(e,t){let n;try{n=new URL(e)}catch{throw new T(`request`,`Invalid URL provided: "${e}"`)}let r=t?.allowPrivateNetworks??!1,i=t?.allowedHosts?.map(e=>e.toLowerCase())??[],a=n.hostname.toLowerCase(),o=r?[`http:`,`https:`]:[`https:`],s=t?.allowedSchemes?t.allowedSchemes.map(e=>e.endsWith(`:`)?e.toLowerCase():`${e.toLowerCase()}:`):o;if(!s.includes(n.protocol))throw new T(`blocked`,`URL scheme "${n.protocol}" is not permitted by network policy. Allowed: ${s.join(`, `)}`);if(!r&&!i.includes(a)){if(Zr(a))throw new T(`blocked`,`Access to loopback target "${a}" blocked by network guardrail. Enable allowPrivateNetworks to permit local addresses.`);if(Kr(a))throw new T(`blocked`,`Access to private IPv4 address "${a}" blocked by network guardrail.`);if(Xr(a.startsWith(`[`)&&a.endsWith(`]`)?a.slice(1,-1):a))throw new T(`blocked`,`Access to private IPv6 address "${a}" blocked by network guardrail.`)}return n}var ei=20,ti=new Set([301,302,303,307,308]);async function ni(e,t,n){let{resolveHost:r,policy:i}=t,a=e.hostname.toLowerCase();if(r===void 0||i?.allowPrivateNetworks===!0||i?.allowedHosts?.some(e=>e.toLowerCase()===a)===!0||a.startsWith(`[`)||Ur.test(a))return;let o=await r(a,n??void 0);if(o.length===0)throw new T(`blocked`,`Host "${a}" did not resolve to an address.`);let s=o.find(Qr);if(s!==void 0)throw new T(`blocked`,`Host "${a}" resolves to private address "${s}", blocked by network guardrail.`)}function ri(e,t){return e===303?t!==`HEAD`:(e===301||e===302)&&t===`POST`}async function ii(e,t,n){let r=n.fetchFn??fetch,i=async e=>{let r=performance.now();try{let r=$r(e,n.policy);return await ni(r,n,t.signal),r}finally{n.onCheck?.(performance.now()-r)}},a=await i(e);await n.beforeSend?.();let o=a.origin,s=new Headers(t.headers),c=t.method??`GET`,l=t.body,u=!0;for(let d=0;;d++){let f=new Headers(s);if(u)for(let[e,t]of Object.entries(n.originBoundHeaders??{}))f.set(e,t);let p=await ht(r,a.href,{...t,method:c,headers:f,body:l,redirect:`manual`}),m=p.headers.get(`location`);if(!n.followRedirects||!ti.has(p.status)||m===null)return p;if(await p.body?.cancel(),d===ei)throw new T(`network`,`Too many redirects from "${e}"`);a=await i(new URL(m,a).href),u&&=a.origin===o,ri(p.status,c)&&(c=`GET`,l=void 0,s.delete(`content-type`))}}var U=v().int().positive().max(2**53-1),ai=U.max(2147483647),oi=_({operationTimeoutMs:ai.optional(),connectTimeoutMs:ai.optional(),liveStepTimeoutMs:ai.optional(),maxWireRecordBytes:U.optional(),maxWireResponseBytes:U.optional(),maxEventBytes:U.optional(),maxStepBytes:U.optional(),maxStepEvents:U.optional(),maxPendingToolCalls:U.optional()}),si=[`text`,`image`,`speech`,`transcription`,`live`,`decision`,`embedding`],ci=w({id:o().regex(/^[A-Za-z][A-Za-z0-9]*$/),name:o().min(1),description:o().min(1),endpoints:re(y(si),o().min(1)),operationNames:re(y(si),o().regex(/^[a-z][a-z0-9_]*$/))});function li(e,t){return new T(`config`,D(`protocol.definition`,{id:e,issues:t}))}function ui(e){let t=ci.safeParse(e);if(!t.success)throw li(String(e.id),he(t.error))}function di(e,t,n){let r=Object.keys(t).toSorted().join(`, `),i=Object.keys(n).toSorted().join(`, `);if(r!==i)throw li(e,`operationNames name [${i}]; endpoints serve [${r}]`)}function fi(e,t,n,r){if(!n)throw new T(`internal`,D(`protocol.part_schema`,{protocol:e.id,kind:t}));let i=n.safeParse(r);if(!i.success)throw new T(`bad_response`,D(`protocol.part_invalid`,{protocol:e.id,kind:t}),{cause:i.error});return i.data}function pi(e,t){return t.type===`reasoning`?{...t,data:fi(e,`reasoning`,e.reasoning,t.data),origin:{protocol:e.id}}:t.type===`custom`?{type:`custom`,kind:`${e.id}.${t.kind}`,data:fi(e,t.kind,e.custom?.[t.kind],t.data)}:t}async function*mi(e,t){for await(let n of t)yield pi(e,n)}function hi(e,t){let{complete:n,openSession:r}=t;return{...t,...n?{complete:r=>mi(e,n.call(t,r))}:{},...r?{async openSession(n){let i=await r.call(t,n);return{...i,events:()=>mi(e,i.events())}}}:{}}}function gi(e,t,n){let r=n??{},i=e.options.safeParse(r),a=(e.refusedOptions?.(t)??[]).filter(e=>typeof r==`object`&&!!r&&e in r);if(i.success&&a.length===0)return i.data;let o=i.success?a.map(e=>`✖ ${t} takes no ${e}`).join(`
2
2
  `):he(i.error);throw new T(`config`,D(`protocol.options`,{apiId:t,protocol:e.id,issues:o}))}function W(e){if(ui(e),typeof e.create!=`function`||typeof e.options?.safeParse!=`function`)throw li(e.id,`create and options are required`);return di(e.id,e.endpoints,e.operationNames),Object.freeze({...e,lineage:Object.freeze([e.id]),create:t=>hi(e,e.create(t))})}function _i(e){return e instanceof Ee?e.shape:void 0}function vi(e,t){let n=e??{},r={};for(let e of t)e in n&&(r[e]=n[e]);return r}function yi(e,t){let n=_i(e.options),r=t.options?_i(t.options):{};if(t.options&&!n)throw new T(`config`,D(`protocol.base_options`,{protocol:t.id,base:e.id}));for(let i of Object.keys(r??{}))if(n&&i in n)throw new T(`config`,D(`protocol.option_clash`,{protocol:t.id,option:i,base:e.id}));return{schema:n?_({...n,...r}):e.options,baseKeys:n?Object.keys(n):void 0,addedKeys:Object.keys(r??{})}}function bi(e,t,n,r,i){let a={profileType:r.profileType,apiId:r.apiId,options:vi(r.options,n.addedKeys)},o=[],s=t.read?.({...a,...i?{request:i}:{}}),c=e=>{for(let n of e??[])o.push(pi(t,n))},l=(e,n,o=[])=>{if(!t.body)return{body:e,wroteTools:o};let s=t.body(e,{...a,builtInTools:r.builtInTools,headers:n,...i?{request:i}:{}});return{body:s.body,wroteTools:[...o,...s.wroteTools??[]]}};async function*u(e){for await(let t of e){let e=s?.row(t);c(e?.events),e?.consumed||(yield t)}}let d={...r,options:n.baseKeys?vi(r.options,n.baseKeys):r.options,send(e,t){let n=new Headers(t.headers),i=l(e,n,t.wroteTools);return u(r.send(i.body,{...t,headers:Object.fromEntries(n),wroteTools:i.wroteTools}))},async connect(e,t){let n=l(e,new Headers,t?.wroteTools),i=await r.connect(n.body,{wroteTools:n.wroteTools});return{...i,frames:()=>u(i.frames())}}};async function*f(e){for await(let t of e)yield*o.splice(0),t.type===`done`&&c(s?.finish?.().events),yield*o.splice(0),yield t;yield*o.splice(0)}return{operations:e.create(d),drained:f}}function xi(e){let t=e().operations,n={};return t.complete&&(n.complete=t=>{let{operations:n,drained:r}=e(t);return r(n.complete(t))}),t.openSession&&(n.openSession=async t=>{let{operations:n,drained:r}=e(t),i=await n.openSession(t);return{...i,events:()=>r(i.events())}}),t.decide&&(n.decide=t=>e().operations.decide(t)),t.embed&&(n.embed=t=>e().operations.embed(t)),n}function Si(e,t,n){let r=t[e]??n[e];return r?{[e]:r}:{}}function Ci(e,t){ui({...t,endpoints:t.endpoints??{},operationNames:t.operationNames??{}});let n={...e.endpoints,...t.endpoints},r={...e.operationNames,...t.operationNames};di(t.id,n,r);let i=yi(e,t);return Object.freeze({id:t.id,name:t.name,description:t.description,endpoints:n,operationNames:r,options:i.schema,...e.continuation?{continuation:e.continuation}:{},...t.reasoning?{reasoning:t.reasoning}:{},...t.custom?{custom:t.custom}:{},...Si(`framing`,t,e),...Si(`error`,t,e),...Si(`embeddingLimits`,t,e),...Si(`refusedOptions`,t,e),base:e,lineage:Object.freeze([t.id,...e.lineage]),create:n=>xi(r=>bi(e,t,i,n,r))})}function wi(e,t){return t.lineage.includes(e)}var Ti=o().regex(vt),G=_({maxOutputTokens:v().int().positive().optional(),temperature:v().finite().nonnegative().optional(),efforts:i(o().min(1),y([`none`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`])).optional(),defaultEffort:o().min(1).optional(),allowEffortSelect:S().optional(),summaries:S().optional(),builtInTools:b(o().min(1)).optional(),compaction:Se(e=>typeof e==`object`&&!!e&&!Array.isArray(e)).optional()}).shape,Ei=_({protocol:o().min(1).describe(`The API shape this model is spoken to in.`),provider:o().min(1).describe(`The service that runs the model or routes requests to one, such as Gemini or OpenRouter. Its registration supplies the endpoint and authentication.`),apiId:o().min(1).describe(`The id the provider knows the model by.`),maxOutputTokens:G.maxOutputTokens.describe(`The most tokens the model may write in one step.`),temperature:G.temperature.describe(`How varied the model's answers are.`),efforts:G.efforts.describe(`Effort names a turn may pick, each mapped to a thinking level.`),defaultEffort:G.defaultEffort.describe(`The effort used when a turn picks none.`),allowEffortSelect:G.allowEffortSelect.describe(`Whether a turn may pick an effort.`),summaries:G.summaries.describe(`Whether the model sends summaries of its thinking.`),builtInTools:G.builtInTools.describe(`Tools the provider runs itself, by the ids it knows them by.`),compaction:G.compaction.describe(`How the conversation is shortened when it grows too long.`),keySlot:Ti.optional().describe(`The slot this model's key is read from, in place of the provider's.`),fallbackKeySlot:Ti.optional().describe(`The slot tried once when the first key is out of quota.`),options:I.optional().describe(`What this model's protocol takes beyond the shared settings.`),limits:oi.optional().describe(`Theorem's cut-offs for this model's calls; each one left out is no limit.`)}),Di=Ei,Oi=Ei.pick({protocol:!0,provider:!0,apiId:!0,keySlot:!0,fallbackKeySlot:!0,options:!0,limits:!0}).extend({timeoutMs:v().positive().optional().describe(`How long a decision may take before it fails.`)});function ki(e,t){let n=t.keySlot??e.keySlot,r=t.fallbackKeySlot??e.fallbackKeySlot;return{...n===void 0?{}:{keySlot:n},...r===void 0?{}:{fallbackKeySlot:r}}}function Ai(e,t){let n=e.serves.find(e=>e.protocol.id===t.protocol);if(!n)throw new T(`config`,D(`protocol.not_served`,{provider:e.id,protocol:t.protocol}));return n}function ji(e,t){return Ai(e,t).protocol}function Mi(e,t,n){return ji(e,t).operationNames[n]}function Ni(e,t,n,r={webSocketHeaders:!0}){let i=Ai(e,t),{protocol:a}=i;if(a.endpoints[n]===void 0)throw new T(`unsupported`,D(`protocol.profile_type`,{protocol:a.id,profileType:n}));let o=I.parse(gi(a,t.apiId,t.options)),s=ki(e,t);if(s.keySlot!==void 0&&s.keySlot===s.fallbackKeySlot)throw new T(`config`,D(`provider.model_fallback_slot`));if((t.keySlot||t.fallbackKeySlot)&&!e.definition.key)throw new T(`config`,D(`protocol.no_key`,{provider:e.id}));let c=i.authorize??e.definition.authorize;if(n===`live`&&c?.webSocketHeaders&&!r.webSocketHeaders)throw new T(`unsupported`,D(`protocol.ws_headers`,{provider:e.id}));return{...t,options:o}}function Pi(e){return e.type===`text`?{type:`text`,text:e.text}:`uri`in e?{type:e.type,mimeType:e.mimeType,uri:e.uri}:{type:e.type,mimeType:e.mimeType,data:e.data}}function Fi(e){return e.type!==`text`&&`uri`in e}function K(e){let t=e.parts??[];return e.content?[{type:`text`,text:e.content},...t]:[...t]}function Ii(e){let t=e.structured===void 0?e.text:JSON.stringify(e.structured);return[...t?[{role:`assistant`,content:t}]:[],...e.calls.length?[Li(e.calls)]:[]]}function Li(e){let t=e.flatMap(e=>e.reasoning??[]),n=[];for(let t of e)n.push({id:t.callId,type:`function`,function:{name:t.name,arguments:JSON.stringify(t.arguments)}});return{role:`assistant`,tool_calls:n,...t.length?{reasoning:[...t]}:{}}}function Ri(e,t){return Object.assign(t=>({sign:n=>e(t,n)}),{webSocketHeaders:t})}var zi=o().url().refine(e=>{if(!URL.canParse(e))return!0;let t=new URL(e);return[`http:`,`https:`].includes(t.protocol)&&!t.username&&!t.password&&![...t.searchParams.keys()].some(e=>/key|auth|secret|token|password/i.test(e))},D(`protocol.endpoint_url`));function Bi(){return Ri((e,t)=>t.headers.set(`Authorization`,`Bearer ${e}`),!0)}function Vi(e){return Ri((t,n)=>n.headers.set(e,t),!0)}function Hi(e){return Ri((t,n)=>n.url.searchParams.set(e,t),!1)}var Ui=w({id:o().regex(/^[a-z][a-z0-9-]*$/),name:o().min(1),description:o().min(1),traceName:o().min(1).optional()});function Wi(e){let t=Ui.safeParse(e);if(!t.success||typeof e.serves!=`function`)throw new T(`config`,D(`protocol.definition`,{id:String(e.id),issues:t.success?`serves is required`:he(t.error)}));return Object.freeze({...e})}function Gi(e,t){let n=e.serves.find(e=>e.protocol.id===t);if(!n)throw new T(`config`,D(`protocol.not_served`,{provider:e.id,protocol:t}));return n}function Ki(){let e=new Map,t=new Map,n=e=>{let n=[];for(let r=e;r;r=r.base){let e=t.get(r.id);if(e&&e!==r)throw new T(`config`,D(`protocol.id_clash`,{protocol:r.id}));n.push(r)}return n},r=(r,i,a)=>{let o=i.id??r.id;if(!a&&e.has(o))throw new T(`config`,D(`protocol.provider_id_clash`,{provider:o}));let s=r.connection?r.connection.safeParse(i.connection):{success:!0,data:void 0};if(!s.success)throw new T(`config`,D(`protocol.connection`,{provider:o,issues:he(s.error)}));if(s.data!==void 0&&tn.parse(s.data),i.keySlot!==void 0&&Ti.parse(i.keySlot),i.fallbackKeySlot!==void 0&&Ti.parse(i.fallbackKeySlot),i.keySlot&&i.keySlot===i.fallbackKeySlot)throw new T(`config`,D(`provider.fallback_slot`));if((i.keySlot||i.fallbackKeySlot)&&!r.key)throw new T(`config`,D(`protocol.no_key`,{provider:o}));let c=Object.freeze(r.serves(s.data).map(e=>Object.freeze({...e}))),l=c.flatMap(e=>n(e.protocol)),u=(e,t,n)=>{let{protocol:r}=Gi({id:o,serves:c},typeof e==`string`?e:e.id);return{protocol:r.id,options:gi(r,t,n)}},d=Object.freeze({id:o,definition:r,connection:s.data,...i.keySlot?{keySlot:i.keySlot}:{},...i.fallbackKeySlot?{fallbackKeySlot:i.fallbackKeySlot}:{},serves:c,model(e,t,n={}){let{options:r,...i}=n;return Di.parse({...i,provider:o,apiId:t,...u(e,t,r)})},decisionModel(e,t,n={}){let{options:r,...i}=n;return Oi.parse({...i,provider:o,apiId:t,...u(e,t,r)})}});for(let e of l)t.set(e.id,e);return e.set(o,d),d};return{register:(e,t={})=>r(e,t,!1),replace:(e,t={})=>r(e,t,!0),get:t=>e.get(t),require(t,n){let r=e.get(t);if(!r)throw new T(`config`,D(`protocol.provider_missing`,{provider:t,apiId:n}));return r},list:()=>[...e.values()],protocols:()=>[...t.values()]}}var qi=[`text`],Ji=_t,Yi=[`length`,`stream_incomplete`],Xi=new Set([`egress`,`canary`,`prompt_echo`,`provider_tool_leak`]);function Zi(e){return e.kind===`filtered`&&Xi.has(e.native??``)}var Qi=1500,$i=new Set(_t);function ea(e){return $i.has(e)}new Set(Ji);var ta=new Set([`provider_error`,`stream_incomplete`]);function na(e){return ta.has(e)}function ra(e){return typeof e==`object`&&e.reason?{kind:`cancelled`,native:e.reason}:{kind:`cancelled`}}function ia(e,t){return!e||!ea(e.kind)?!1:(t?.autoContinue??Yi).includes(e.kind)}function aa(e){if(e.type!==`live`)return e.turnBehaviour?.resumption}function oa(e){return e.type===`text`&&e.turnBehaviour?.allowSteering!==!1}function sa(e){return e.type===`text`||e.type===`live`?e.turnBehaviour?.allowSteering!==!1:!1}function ca(e,t){let n=t?.trim()||e?.trim()||void 0,r=(t||e||``).toLowerCase();return r?r===`network_error`||r.includes(`network`)?{kind:`provider_error`,native:n}:la((e||``).toLowerCase(),r,n):{kind:`stream_incomplete`,native:n}}function la(e,t,n){return e===`stop`?/error|fail/.test(t)?{kind:`provider_error`,native:n}:{kind:`completed`,native:n}:e===`length`?{kind:`length`,native:n}:e===`tool_calls`||e===`tool-calls`?{kind:`tool`,native:n}:e===`content_filter`||e===`content-filter`?{kind:`filtered`,native:n}:{kind:`provider_error`,native:n}}function ua(e){let t=(e||``).toLowerCase(),n=e||void 0;switch(t){case`completed`:return{kind:`completed`,native:n};case`incomplete`:case`budget_exceeded`:return{kind:`length`,native:n};case`requires_action`:return{kind:`tool`,native:n};case`cancelled`:return{kind:`cancelled`,native:n};case`failed`:return{kind:`provider_error`,native:n};case`in_progress`:case`queued`:return{kind:`stream_incomplete`,native:n};default:return{kind:`stream_incomplete`,native:n}}}function da(e,t){for(let n=e.length-1;n>=0;--n){let r=e[n];if(r!==void 0&&t(r))return r}}function q(e){return E(e)?e:void 0}function J(e){if(typeof e==`string`&&e.trim())return e}function Y(e){return typeof e==`number`&&Number.isFinite(e)&&e>=0?e:void 0}function fa(e){let t=e.input?e.input:void 0;if(t===void 0&&!e.output)return;let n=[];t===void 0&&n.push(`input`),e.output===void 0&&n.push(`output`);let r=t??0,i=e.output??0;return{input:r,output:i,...e.thinking?{thinking:e.thinking}:{},...e.toolUse?{toolUse:e.toolUse}:{},...e.cached?{cached:e.cached}:{},...e.cacheWrite?{cacheWrite:e.cacheWrite}:{},total:r+i,...e.cost?{cost:e.cost}:{},...n.length>0?{estimated:n}:{},...e.byModality?{byModality:e.byModality}:{},...e.grounding?{grounding:e.grounding}:{}}}function pa(e){let t=e.flatMap(e=>e.cost?[e.cost]:[]);if(t.length===0)return;let n=t.flatMap(e=>e.upstreamUsd===void 0?[]:[e.upstreamUsd]),r=t.length<e.length||t.some(e=>e.partial);return{usd:t.reduce((e,t)=>e+t.usd,0),...n.length>0?{upstreamUsd:n.reduce((e,t)=>e+t,0)}:{},...r?{partial:!0}:{}}}function ma(e){let t=[`input`,`output`],n={};for(let r of t){let[t,...i]=e.map(e=>e.byModality?.[r]),a=Object.keys(t??{}).filter(e=>i.every(t=>t?.[e]!==void 0));a.length!==0&&(n[r]=Object.fromEntries(a.map(t=>[t,e.reduce((e,n)=>e+(n.byModality?.[r]?.[t]??0),0)])))}return Object.keys(n).length>0?n:void 0}function ha(e){let t=new Map;for(let n of e.flatMap(e=>e.grounding??[]))t.set(n.type,[...t.get(n.type)??[],n]);if(t.size!==0)return[...t].map(([e,t])=>{let n=t.every(e=>e.searchQueryCount!==void 0);return{type:e,count:t.reduce((e,t)=>e+t.count,0),...n?{searchQueryCount:t.reduce((e,t)=>e+(t.searchQueryCount??0),0)}:{}}})}function ga(e){return va(e.flatMap(e=>e.type===`tokens`?[e.tokens]:[]))}function _a(e){return va(e.flatMap(e=>{if(e.type===`tokens`)return[e.tokens];if(e.type!==`tool`)return[];let{tool:t}=e;return(t.phase===`complete`||t.phase===`error`)&&t.tokens?[t.tokens]:[]}))}function va(e){if(e.length===0)return;let t=t=>e.reduce((e,n)=>e+(t(n)??0),0),n=t(e=>e.input),r=t(e=>e.output),i=t(e=>e.thinking),a=t(e=>e.toolUse),o=t(e=>e.cached),s=t(e=>e.cacheWrite),c=pa(e),l=ma(e),u=ha(e),d=[`input`,`output`],f=d.filter(t=>e.some(e=>e.estimated?.includes(t))),p={};for(let e of d){let n=t(t=>t.unknownMedia?.[e]);n>0&&(p[e]=n)}return{input:n,output:r,...i?{thinking:i}:{},...a?{toolUse:a}:{},...o?{cached:o}:{},...s?{cacheWrite:s}:{},total:n+r,...c?{cost:c}:{},...f.length>0?{estimated:f}:{},...Object.keys(p).length>0?{unknownMedia:p}:{},...l?{byModality:l}:{},...u?{grounding:u}:{}}}var ya=1e3,ba=400,xa=new Set([`http_request`,`http_response`,`http_error_body`,`http_throw`]),Sa=new Set([`text`,`image`,`audio`]),Ca={completed:`stop`,length:`length`,tool:`tool_call`,filtered:`content_filter`,provider_error:`error`};function wa(e){let[t]=e.split(`/`);return t===`application`||t===`text`||!t?`document`:t}function Ta(e){return e.type===`text`?{type:`text`,...A(e.text)}:`uri`in e?{type:`uri`,modality:e.type,mime_type:e.mimeType,uri:e.uri}:{type:`blob`,modality:e.type,mime_type:e.mimeType,...He(e.data)}}function Ea(e){let t=K(e).map(Ta);if(e.role===`tool`)return{role:`tool`,parts:[{type:`tool_call_response`,...e.tool_call_id?{id:e.tool_call_id}:{},response:A(e.content??``)},...(e.parts??[]).map(Ta)]};let n=(e.tool_calls??[]).map(e=>({type:`tool_call`,id:e.id,name:e.function.name,arguments:A(e.function.arguments)}));return{role:e.role,parts:[...t,...n]}}var Da=new WeakMap;function Oa(e){let{conversation:t}=e;if(`previous`in t){let e=Da.get(t.previous),n=[...e?.input??[],...e?.output?[e.output]:[]];return{input:[...n,...t.continuation.map(Ea)],sentFrom:n.length}}let n=t.input.length>0?[{role:`user`,parts:t.input.map(Ta)}]:[];return{input:[...t.history.map(Ea),...n]}}var ka=class{parts=[];open;calls=new Map;add(e,t){switch(e.type){case`text`:this.appendText(`text`,e.text);return;case`thought`:this.appendText(`reasoning`,e.text);return;case`tool`:this.addTool(e.tool);return;case`structured`:this.push({type:`structured`,content:N(e.structured??null)});return;case`media`:this.push(Na(e.media));return;case`evidence`:{let{evidence:n}=e;if(n.kind===`input_transcription`||n.kind===`output_transcription`){this.appendText(`text`,e.text??``,n.kind,n.interim);return}let r=La(n,t);r&&this.push(r);return}case`tool_draft`:case`structured_draft`:return;default:return}}appendText(e,t,n,r){if(!t)return;let i=`${e}:${n??``}:${r?`interim`:``}`;if(this.open?.key===i){this.open.text+=t,Object.assign(this.open.part,A(this.open.text));return}let a={type:e,...A(t),...X(`theorem.source`,n),...r?{"theorem.interim":!0}:{}};this.parts.push(a),this.open={key:i,text:t,part:a}}addTool(e){if(e.phase===void 0){let t=Ma(e);this.calls.set(e.callId,t),this.push(t);return}let t=this.calls.get(e.callId),n=e.phase===`error`?Aa(e.failure):void 0;t&&n!==void 0&&Object.assign(t,{arguments:A(n)})}push(e){this.parts.push(e),this.open=void 0}};function Aa(e){let t=q(e?.details)?.raw;return typeof t==`string`?t:void 0}function ja(e){return Aa(e.failure)??JSON.stringify(e.arguments)}function Ma(e){return{type:`tool_call`,id:e.callId,name:e.name,arguments:A(ja(e))}}function Na(e){return{type:`blob`,modality:wa(e.mimeType),mime_type:e.mimeType,...He(e.data)}}var Pa=`_call`,Fa=`_result`;function Ia(e){switch(e.kind){case`code_execution_call`:return{side:`call`,name:`code_execution`,id:e.id};case`code_execution_result`:return{side:`result`,name:`code_execution`,id:e.callId};case`provider_step`:{let{step:t,raw:n}=e;if(t.endsWith(Pa)){let e=typeof n?.id==`string`?n.id:void 0;return{side:`call`,name:t.slice(0,-5),id:e}}if(t.endsWith(Fa)){let e=typeof n?.call_id==`string`?n.call_id:void 0;return{side:`result`,name:t.slice(0,-7),id:e}}return}default:return}}function La(e,t){let n=Ia(e);if(!n)return;let r={"theorem.observed_end":t,...e.partial?{"theorem.partial":!0}:{}},i={...N(e.raw??{}),type:n.name};return n.side===`call`?{type:`server_tool_call`,...X(`id`,n.id),name:n.name,server_tool_call:i,...r}:{type:`server_tool_call_response`,...X(`id`,n.id),server_tool_call_response:i,...r}}function Ra(e){switch(e.type){case`grounding`:{let{searchHtml:t,metadata:n,chunks:r}=e.grounding;return!t&&!n&&!r?void 0:{...t?{search_html:A(t)}:{},...n||r?{raw:N({metadata:n,chunks:r})}:{}}}case`citation`:return{sources:N(e.sources)};case`evidence`:{let{evidence:t}=e;return Ia(t)||t.kind===`input_transcription`||t.kind===`output_transcription`?void 0:{provider:t.provider,...t.raw?{raw:N(t.raw)}:{}}}default:return}}function za(e){return{stage:e.stage,trust:e.trust,action:e.action,hits:e.hits.map(e=>({rule:e.rule,severity:e.severity,...X(`signal`,e.signal),...e.span?{start:e.span.start,end:e.span.end}:{},...X(`match`,e.match),...X(`label`,e.label),...X(`doc`,e.doc)})),...e.provenance?{provenance:{...e.provenance}}:{},...e.errorInternal?{error:A(e.errorInternal)}:{},...X(`error_summary`,e.errorSummary)}}var Ba={output_stream:`output_delta`,stream_canary:`output_delta`,tool_draft:`tool_call`,live_output:`live_outbound`};function Va(e,t,n,r){return{...n?za(n):{stage:r.stage,trust:r.trust,action:`allow`,hits:[]},check:e,duration_ms:t}}function Ha(e){let t={};for(let n of[`input`,`output`])for(let[r,i]of Object.entries(e?.[n]??{})){let e=Sa.has(r)?`gen_ai`:`theorem`;t[`${e}.usage.${r}.${n}_tokens`]=i}return t}function X(e,t){return t===void 0?{}:{[e]:t}}function Ua(e){return{"gen_ai.usage.input_tokens":e.input,"gen_ai.usage.output_tokens":e.output,...X(`gen_ai.usage.reasoning.output_tokens`,e.thinking),...X(`gen_ai.usage.cache_read.input_tokens`,e.cached),...X(`gen_ai.usage.cache_write.input_tokens`,e.cacheWrite),...X(`theorem.usage.tool_use.input_tokens`,e.toolUse),...Ha(e.byModality),...e.grounding?{"theorem.usage.grounding":e.grounding.map(e=>({type:e.type,count:e.count,...X(`search_query_count`,e.searchQueryCount)}))}:{},...X(`theorem.usage.cost_usd`,e.cost?.usd),...X(`theorem.usage.upstream_cost_usd`,e.cost?.upstreamUsd),...e.cost?.partial?{"theorem.usage.cost_partial":!0}:{},...e.estimated?.length?{"theorem.usage.estimated":[...e.estimated]}:{},...e.unknownMedia?{"theorem.usage.unknown_media":{...e.unknownMedia}}:{}}}function Wa(e){if(e)return e.provider}function Ga(e,t){return t===`live`?`speech`:e.structured?`json`:e.image?`image`:e.speech?`speech`:`text`}function Ka(e,t,n,r){let i=Wa(t);return{...X(`gen_ai.operation.name`,r),...X(`gen_ai.provider.name`,i),"gen_ai.request.model":e.apiId,"theorem.model.id":e.model,...X(`theorem.key_slot`,t?.keySlot),...X(`gen_ai.request.temperature`,e.temperature),...X(`gen_ai.request.max_tokens`,e.maxOutputTokens),...X(`gen_ai.request.reasoning.level`,e.thinking),"gen_ai.system_instructions":[{type:`text`,...A(e.system)}],...e.wireTools?.length?{"gen_ai.tool.definitions":A(JSON.stringify(e.wireTools))}:{},"gen_ai.output.type":Ga(e,n),...qa(e)}}function qa(e){let{image:t,speech:n,live:r}=e;return{"theorem.request.builtins":e.builtins.map(e=>e.id),...X(`theorem.request.summaries`,e.summaries),...X(`theorem.request.structured`,e.structured?.id),...X(`theorem.request.session_id`,e.sessionId),...t?{"theorem.request.image":{...X(`mime_type`,t.mimeType),...X(`aspect_ratio`,t.aspectRatio),...X(`resolution`,t.resolution),...X(`quality`,t.quality),...X(`background`,t.background),...X(`n`,t.n),...X(`seed`,t.seed),...X(`output_compression`,t.outputCompression),include_text:t.includeText}}:{},...n?{"theorem.request.speech":{...X(`voice`,n.voice),...X(`speed`,n.speed),...X(`format`,n.format)}}:{},...r?{"theorem.request.live":Ja(r,e)}:{}}}function Ja(e,t){let{vad:n,transcription:r}=e;return{...X(`voice`,e.voice),...n?{vad:{...X(`activity_handling`,n.activityHandling),...X(`start_sensitivity`,n.startSensitivity),...X(`end_sensitivity`,n.endSensitivity),...X(`prefix_padding_ms`,n.prefixPaddingMs),...X(`silence_duration_ms`,n.silenceDurationMs)}}:{},...X(`session_resumption`,e.sessionResumption),...e.contextCompression?{context_compression:{mechanism:`sliding_window`,...X(`trigger_tokens`,e.contextCompression.triggerTokens),...X(`target_tokens`,e.contextCompression.slidingWindow.targetTokens)}}:{},...r?{transcription:{...X(`input`,r.input),...X(`output`,r.output)}}:{},resumed:!!t.providerState}}function Ya(e,t){return!t||typeof t!=`object`?{}:Object.fromEntries(Object.entries(t).map(([t,n])=>[`${e}.${t}`,[String(n)]]))}function Xa(e){if(typeof e!=`string`)return{};let t=URL.canParse(e)?new URL(e):void 0;return t?{"server.address":t.hostname,"url.path":t.pathname}:{}}var Za=class{call;tries=0;current;last;lastStatus;awaitingFirstChunk=!1;streamed=!1;constructor(e){this.call=e}row(e){let t=typeof e.eventType==`string`?e.eventType:void 0;return!t||!xa.has(t)?(this.firstChunk(),!1):(t===`http_request`?this.open(e):t===`http_response`?this.response(e):t===`http_error_body`?this.errorBody(e):this.thrown(e),!0)}open(e){this.current?.end();let t=this.last?.msSinceEnd();this.current=this.call.child(String(e.method??`GET`),{kind:`CLIENT`,attributes:{"http.request.method":String(e.method??`GET`),...Xa(e.url),"http.request.resend_count":this.tries,...typeof e.keySlot==`string`?{"theorem.key_slot":e.keySlot}:{},...X(`theorem.retry.backoff_ms`,t),...Ya(`http.request.header`,e.headers)}}),this.tries+=1,this.streamed=q(e.body)?.stream===!0,this.streamed&&this.call.set({"gen_ai.request.stream":!0}),`body`in e?this.current.event(`theorem.wire.request`,{body:N(e.body)}):typeof e.bodyKind==`string`&&this.current.event(`theorem.wire.request`,{body_kind:e.bodyKind}),typeof e.keySlot==`string`&&this.call.set({"theorem.key_slot":e.keySlot})}response(e){let t=typeof e.status==`number`?e.status:void 0;this.lastStatus=t,this.current?.set({...X(`http.response.status_code`,t),...Ya(`http.response.header`,e.headers)}),t!==void 0&&t>=ba?this.current?.set({"error.type":String(t)}):this.awaitingFirstChunk=!0}errorBody(e){this.current?.event(`theorem.upstream.row`,{row:N(e)}),this.close({code:`ERROR`,message:String(this.lastStatus??`error`)})}thrown(e){let t=typeof e.name==`string`?e.name:`Error`;this.current?.event(`exception`,{"exception.type":t,"exception.message":A(String(e.message??``))}),this.current?.set({"error.type":t}),this.close({code:`ERROR`,message:t})}firstChunk(){this.awaitingFirstChunk&&this.current&&(this.awaitingFirstChunk=!1,this.call.set({"gen_ai.response.time_to_first_chunk":this.current.msSinceStart()/ya}))}close(e){this.current&&=(this.current.end(e),this.last=this.current,void 0)}};function Qa(e,t,n){return e!==void 0&&e>=ba?{code:`ERROR`,message:String(e)}:n===void 0?t?{code:`UNSET`}:{code:`OK`}:{code:`ERROR`,message:Tt(n)}}function $a(e){return e instanceof Error?e.name:`Error`}function eo(e,t){e.event(`exception`,{"exception.type":$a(t),"exception.message":A(Ze(t)),...t instanceof Error&&t.stack?{"exception.stacktrace":A(t.stack)}:{}})}function to(e,t){eo(e,t);let n=Tt(t);e.set({"error.type":n}),e.end({code:`ERROR`,message:n})}function no(e,t){for(let[n,r]of t)r.decided||e.event(`theorem.guardrail`,{...Va(n,r.ms,void 0,{stage:Ba[n],trust:`untrusted`}),runs:r.runs})}function ro(e){let t=0;for(let n of e.values())t+=n.ms;return t>0?{"theorem.guardrail.stream_ms":t}:{}}var io=new Set([`cancelled`,`interrupted`]);function ao(e,t){let n=e!==void 0&&io.has(e.kind),r=e&&!n?Ca[e.kind]??e.kind:void 0;return t?{stopped:n,finish:r,status:{code:`ERROR`,message:t},attributes:{"error.type":t}}:{stopped:n,finish:r,status:{code:n?`UNSET`:`OK`},attributes:{}}}function oo(e,t,n){let r=t?n===`turn`?{"gen_ai.response.finish_reasons":[t]}:{"gen_ai.response.status":t}:{};return{...X(`gen_ai.response.id`,e?.id||void 0),...X(`gen_ai.response.model`,e?.model||void 0),...r}}function so(e,t){let{req:n,usage:r,transport:i,operation:a}=t,o=Oa(r),s=e(a?`${a} ${n.apiId}`:n.apiId,{kind:`CLIENT`,attributes:{...Ka(n,t.binding,i,a),"gen_ai.input.messages":o.input,...X(`theorem.input.sent_from`,o.sentFrom),"theorem.step":t.step,...X(`theorem.attempt`,t.attempt)}}),c=new Za(s),l=new ka,u=new ka,d=[],f,p,m=!1,h=new Map,g;return{span:s,tap:e=>{c.row(e)||s.event(`theorem.upstream.row`,{row:N(e)})},observe:e=>{if(e.type===`evidence`&&e.evidence.kind===`input_transcription`){u.add(e,s.nowUnixNano());return}l.add(e,s.nowUnixNano()),e.type===`text`&&!m&&(m=!0,s.set({"theorem.response.time_to_first_text":s.msSinceStart()/ya}));let t=Ra(e);t&&s.event(`theorem.grounding`,t),e.type===`error`&&d.push(e),e.type===`response`&&(f=e.response),e.type===`done`&&(p=e.stop.native??p)},guardrail:e=>{let t=g?h.get(g):void 0;!(g&&t)||t.decided?s.event(`theorem.guardrail`,za(e)):(t.decided=!0,s.event(`theorem.guardrail`,{...Va(g,t.ms,e,{stage:Ba[g],trust:`untrusted`}),runs:t.runs}))},guardTime:(e,t)=>{let n=h.get(e)??{ms:0,runs:0,decided:!1};n.ms+=t,n.runs+=1,h.set(e,n),g=e},end:e=>{for(let e of d)s.event(`exception`,{"exception.type":e.errorKind,"exception.message":A(e.errorInternal??e.error??``)});e.thrown!==void 0&&eo(s,e.thrown),no(s,h);let t=d.at(-1),n=e.thrown===void 0?t?.errorKind:Tt(e.thrown),a=ao(e.stop,n),o={role:`assistant`,parts:l.parts,...X(`finish_reason`,a.finish)},{input:m}=Oa(r);Da.set(r,{input:m,output:o});let g=u.parts.length>0?[{role:`user`,parts:u.parts}]:[];c.close(Qa(c.lastStatus,a.stopped,e.thrown)),s.set({"gen_ai.input.messages":[...m,...g],"gen_ai.output.messages":[o],...e.tokens?Ua(e.tokens):{},...oo(f,a.stopped?void 0:p,i),...X(`theorem.stop.kind`,e.stop?.kind),...ro(h),...a.attributes}),s.end(a.status)}}}function co(e){let t=[...e?.attachments??[],...e?.voice??[]].map(e=>`uri`in e?{type:`uri`,modality:wa(e.mimeType),mime_type:e.mimeType,uri:e.uri}:{type:`blob`,modality:wa(e.mimeType),mime_type:e.mimeType,...He(e.data)}),n=[...e?.text?[{type:`text`,...A(e.text)}]:[],...t];return n.length>0?[{role:`user`,parts:n}]:[]}function lo(e){return(e??[]).map(e=>({traceparent:e.traceparent,attributes:{"theorem.link.kind":e.kind,...X(`theorem.stop.kind`,e.stop)}}))}function uo(e){return{kind:`INTERNAL`,attributes:{"gen_ai.operation.name":`invoke_agent`,"gen_ai.agent.name":e.profile,...X(`gen_ai.conversation.id`,e.conversationId),"gen_ai.input.messages":co(e.input),...X(`theorem.request.effort`,e.effort),...X(`theorem.request.model_select`,e.model),...X(`theorem.project.id`,e.projectId)},links:lo(e.links)}}var fo=new Set([`completed`,`length`,`generation_complete`]);function po(e,t){let n=ga(t.seen),r=da(t.seen,e=>e.type===`done`),i=r?.stop.kind,a=da(t.seen,e=>e.type===`error`),o=a?.error,s=t.thrown!==void 0;s&&eo(e,t.thrown);let c=s||i!==void 0&&na(i),l=s?Tt(t.thrown):a?.errorKind??i,u={role:`assistant`,parts:t.delivered.parts,...X(`finish_reason`,ao(r?.stop,void 0).finish)};e.set({"gen_ai.output.messages":[u],...n?Ua(n):{},...i?{"theorem.stop.kind":i}:{},"theorem.attempts":t.attempts,"theorem.steps":t.calls,...t.seen.some(e=>e.type===`compaction`&&e.outcome===`compacted`)?{"gen_ai.conversation.compacted":!0}:{},...c&&o?{"theorem.error.public":A(o)}:{},...c&&l?{"error.type":l}:{}}),c?e.end({code:`ERROR`,...l?{message:l}:{}}):e.end(i&&!fo.has(i)?{code:`UNSET`}:{code:`OK`})}function mo(e,t){if(Object.hasOwn(t,e))return[{reference:e,asset:t[e]}];let n=Object.keys(t),r=[],i=0;for(;i<e.length;){let a=-1,o=``;for(let t of n){let n=e.indexOf(t,i);n<0||(a<0||n<a||n===a&&t.length>o.length)&&(a=n,o=t)}if(a<0)break;a>i&&r.push(e.slice(i,a)),r.push({reference:o,asset:t[o]}),i=a+o.length}return i<e.length&&r.push(e.slice(i)),r}function*ho(e){if(typeof e==`string`)yield e;else if(Array.isArray(e))for(let t of e)yield*ho(t);else if(typeof e==`object`&&e)for(let t of Object.values(e))yield*ho(t)}function go(e,t){let n=new Set;for(let r of e)for(let e of ho(r))for(let r of mo(e,t))typeof r!=`string`&&n.add(r.reference);return Object.fromEntries(Object.entries(t).filter(([e])=>n.has(e)))}var _o=/\{\{?([^{}]*)\}\}?/g,vo=/[\p{Cc}\p{Cf}]/gu,yo=/^-?\d+$/,bo=/^(\d{4})-(\d{2})-(\d{2})(?:[T ](\d{2}):(\d{2})(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:?\d{2})?)?$/,xo=new Intl.NumberFormat(void 0,{maximumFractionDigits:2}),So=new Intl.PluralRules(`en`),Co=new Intl.DateTimeFormat(void 0,{dateStyle:`medium`,timeZone:`UTC`}),wo=new Intl.DateTimeFormat(void 0,{dateStyle:`medium`,timeStyle:`short`,timeZone:`UTC`}),To=/^\+\s+/,Eo=/:(?:\s|$)/,Do=/^(\S+) is (?:(not) )?(\S.*)$/;function Oo(e){let t=e.trim(),n=t.search(/[\s|]/);if(n<0)return{path:t};let r=t.slice(0,n),i=t.slice(n).trimStart();if(i.startsWith(`|`))return{path:r,fallback:i.slice(1).trim()};let[a=``,o=``,...s]=i.split(`|`).map(e=>e.trim()),c=a&&o?{one:a,other:o}:`unreadable`;return s.length?{path:r,forms:c,fallback:s.join(`|`)}:{path:r,forms:c}}function ko(e,t){let n=e.split(`.`),[r,...i]=n;return(r===`input`||r===`output`)&&i.length?[{side:r,keys:i,prefixed:!0}]:t.map(e=>({side:e,keys:n,prefixed:!1}))}function Ao(e,t){let n=e;for(let e of t)if(Array.isArray(n)){if(e===`length`)n=n.length;else if(yo.test(e))n=n.at(Number(e));else return}else if(E(n)&&Object.hasOwn(n,e))n=n[e];else return;return n}function jo(e){let t=bo.exec(e);if(!t)return;let[n=0,r=0,i=0,a=0,o=0]=t.slice(1).map(e=>Number(e??0)),s=new Date(Date.UTC(n,r-1,i,a,o));if(!(Number.isNaN(s.getTime())||s.getUTCDate()!==i))return(t[4]===void 0?Co:wo).format(s)}function Mo(e){if(typeof e==`number`)return Number.isFinite(e)?xo.format(e):void 0;if(typeof e!=`string`)return;let t=e.replace(vo,` `).replace(/\s+/g,` `).trim();return(jo(t)??t)||void 0}function No(e){let t=[];for(let n of e.replace(/\s+/g,` `).split(` and `)){let[,e,r,i]=Do.exec(n.trim())??[];if(!e||!i)return`unreadable`;let a=i.trim();t.push({path:e,negated:!!r,expected:a===`null`?null:a})}return t}function Po(e){let t=To.test(e),n=e.replace(To,``).trimStart();if(!/^when(\s|$)/.test(n))return{joined:t,when:[],text:n};let r=n.search(Eo);return r<0?{joined:t,when:`unreadable`,text:``}:{joined:t,when:No(n.slice(4,r)),text:n.slice(r+1).trimStart()}}function Fo(e){let t=Po(e);return{...t,text:t.text.trim()}}function Io(e){let t=typeof e==`string`?[e]:e,n=[];return t.forEach((e,t)=>{let r=Fo(e),i=n.at(-1);r.joined&&i?.joined?i.lines.push({line:r,number:t+1}):n.push({joined:r.joined,lines:[{line:r,number:t+1}]})}),n}function Lo(e){let[t]=ko(e,[`input`]);return t?.side===`input`?t.keys:void 0}function Ro(e,t){let n=Lo(e.path);if(!n)return!1;let r=Ao(t,n),i=typeof r==`string`||typeof r==`number`||typeof r==`boolean`;return(e.expected===null?r===null:i&&`${r}`===e.expected)!==e.negated}function zo(e){return e.length<=1?e[0]??``:`${e.slice(0,-1).join(`, `)}${e.length>2?`,`:``} and ${e.at(-1)}`}function Bo(e){return e.replace(/([a-z\d])([A-Z])/g,`$1 $2`).replace(/[_-]+/g,` `).trim().toLowerCase()}function Vo(e,t){if(t===`unreadable`)return;let n=e.find(e=>typeof e==`number`&&Number.isFinite(e));if(n!==void 0)return`${xo.format(n)} ${So.select(n)===`one`?t.one:t.other}`}function Ho(e,t,n){let r=!1,i=e.replace(_o,(e,i)=>{let{path:a,fallback:o,forms:s}=Oo(i),c=a?ko(a,n).map(e=>Ao(t[e.side],e.keys)):[],l=s?Vo(c,s):c.map(Mo).find(Boolean);return l===void 0&&o===void 0&&(r=!0),l??o??``}).replace(/\s+/g,` `).trim();return r||!i?void 0:i}function Uo(e,t){if(e===void 0)return;let n=`output`in t?[`input`,`output`]:[`input`];for(let r of Io(e)){let e=r.lines.flatMap(({line:e})=>{if(e.when===`unreadable`||!e.when.every(e=>Ro(e,t.input)))return[];let r=Ho(e.text,t,n);return r===void 0?[]:[r]});if(e.length)return zo(e)}}var Wo=[`value`,`group`,`flag`,`missing`];function Z(e){return(Array.isArray(e.type)?e.type:[e.type]).filter(e=>typeof e==`string`&&e!==`null`)}function Go(e){return[e.anyOf,e.oneOf,e.allOf].flatMap(e=>Array.isArray(e)?e.filter(E):[])}function Ko(e){let t=Wo.find(t=>e.some(e=>e.holds===t))??`missing`;return{holds:t,instead:e.filter(e=>e.holds===t).flatMap(e=>e.instead??[])}}function qo(e,t){let n=e=>t?`${t}.${e}`:e;if(!E(e))return[];let r=Go(e);return r.length?r.flatMap(e=>qo(e,t)):Z(e).includes(`array`)?[...Jo(e.items,n(`0`)),n(`length`)]:E(e.properties)?Object.entries(e.properties).flatMap(([e,t])=>Jo(t,n(e))):[]}function Jo(e,t){if(!E(e)||`$ref`in e)return[t];let n=Z(e);if(n.length&&n.every(e=>e===`boolean`))return[];let r=Go(e),i=r.some(e=>Z(e).some(e=>e===`array`||e===`object`)),a=n.includes(`array`)||n.includes(`object`)||i;return!a&&r.length?r.every(e=>Z(e).every(e=>e===`boolean`))?[]:[t]:a?qo(e,t):[t]}function Yo(e,t,n){if(!E(e)||`$ref`in e)return{holds:`value`};let r=Go(e);if(r.length)return Ko(r.map(e=>Yo(e,t,n)));let i=Z(e),[a,...o]=t;if(a===void 0)return i.length&&i.every(e=>e===`boolean`)?{holds:`flag`}:i.includes(`array`)||i.includes(`object`)?{holds:`group`,instead:qo(e,n)}:{holds:`value`};let s=n?`${n}.${a}`:a,c={holds:`missing`,instead:qo(e,n)};if(i.includes(`array`)){if(a===`length`)return o.length?c:{holds:`value`};if(yo.test(a))return E(e.items)?Yo(e.items,o,s):{holds:`value`}}return E(e.properties)?Object.hasOwn(e.properties,a)?Yo(e.properties[a],o,s):c:i.length===0||i.includes(`object`)?{holds:`value`}:c}function Xo(e){let t=[...new Set(e)].slice(0,4).map(e=>`{${e}}`);return t.length===0?``:` Try ${t.length===1?t[0]:`${t.slice(0,-1).join(`, `)}${t.length>2?`,`:``} or ${t.at(-1)}`}.`}function Zo(e,t,n){for(let r of e.matchAll(_o)){let{path:e,forms:i}=Oo(r[1]??``);if(!e)return`Put a field name between the braces, like {${qo(t.input,``)[0]??`name`}}.`;if(i===`unreadable`)return`{${r[1]?.trim()}} needs a word for one and a word for any other number, like {${e} item|items}.`;let a=ko(e,n),[o]=a;if(!o)continue;if(o.prefixed&&!n.includes(o.side))return`{${e}} is only there once the call is done; use it in the Done label.`;let s=Ko(a.map(({side:e,keys:n,prefixed:r})=>Yo(t[e],n,r?e:``)));if(s.holds===`value`){let n=a.some(({side:e,keys:n})=>ts(t[e],n).some(e=>e.number));if(i&&!n)return`{${e}} is not a number, so it has no plural. Count a list with {${e}.length ${i.one}|${i.other}}.`;continue}let c=s.instead??[],l=+!!o.prefixed,u=c.filter(e=>e.split(`.`)[l]===o.keys[0]),d={missing:`is not a field of this tool's ${o.prefixed?o.side:n.join(` or `)}.`,group:`is a list or group; a label shows text or a number.`,flag:`is true or false; a label shows text or a number.`}[s.holds],f=o.keys.at(-1),p=e=>e.split(`.`).at(-1)===f?0:1;return`{${e}} ${d}${Xo((u.length?u:c).toSorted((e,t)=>p(e)-p(t)))}`}}var Qo={texts:`any`,nullable:!0,number:!0};function $o(e){return(Array.isArray(e.type)?e.type:[e.type]).filter(e=>typeof e==`string`)}function es(e){let t=Array.isArray(e.enum)?e.enum:`const`in e?[e.const]:void 0;if(t)return{texts:t.filter(e=>e!==null).map(e=>`${e}`),nullable:t.includes(null),number:t.some(e=>typeof e==`number`)};let n=$o(e);if(n.length===0)return Qo;let r=n.filter(e=>e!==`null`);return{texts:r.every(e=>e===`boolean`)?r.length?[`true`,`false`]:[]:`any`,nullable:n.includes(`null`),number:r.some(e=>e===`number`||e===`integer`)}}function ts(e,t){if(!E(e)||`$ref`in e)return[Qo];let n=Go(e);if(n.length)return n.flatMap(e=>ts(e,t));let[r,...i]=t;if(r===void 0)return[es(e)];let a=Z(e);if(a.includes(`array`)){if(r===`length`)return i.length?[]:[{texts:`any`,nullable:!1,number:!0}];if(yo.test(r))return ts(e.items,i)}return E(e.properties)?Object.hasOwn(e.properties,r)?ts(e.properties[r],i):[]:a.length===0&&$o(e).length===0?[Qo]:[]}function ns(e){if(!E(e))return[];let t=Go(e).flatMap(ns),n=E(e.properties)?Object.keys(e.properties):[];return[...new Set([...n,...t])]}function rs(e){let t=[...new Set(e)].map(e=>`"${e}"`);return t.length<=1?t[0]??``:`${t.slice(0,-1).join(`, `)}${t.length>2?`,`:``} or ${t.at(-1)}`}function is(e,t,n=`this tool's input`){let r=Lo(e.path);if(!r)return`A "when" reads what the model sent; "${e.path}" is only there once the call is done.`;let i=Yo(t,r,``);if(i.holds===`missing`){let r=ns(t).slice(0,4),i=r.length?` Try ${rs(r)}.`:``;return`"${e.path}" in the "when" is not a field of ${n}.${i}`}if(i.holds===`group`)return`"${e.path}" in the "when" is a list or group; a "when" compares text, a number, or true or false.`;let a=ts(t,r);if(e.expected===null)return a.some(e=>e.nullable)?void 0:`"${e.path}" is never null.`;let o=[];for(let e of a){if(e.texts===`any`)return;o.push(...e.texts)}if(o.includes(e.expected))return;let s=o.length?` It is ${rs(o)}.`:``;return`"${e.path}" is never "${e.expected}".${s}`}function as(e,t,n,r){if(e.when===`unreadable`)return`A line that opens with "when" needs a condition and a colon, like "when status is archived: archiving {name}". A condition uses "is", "is not", "is null", and "and".`;for(let n of e.when){let e=is(n,t.input);if(e)return e}return!e.text&&(r||e.when.length)?`It has no wording to show.`:Zo(e.text,t,n)}function os(e){if(e.when===`unreadable`||e.when.length)return!1;let t=!1,n=e.text.replace(_o,(e,n)=>{let{fallback:r}=Oo(n);return r===void 0&&(t=!0),r??``});return!t&&n.trim().length>0}function ss(e){let t=e.map(e=>e.lines.some(({line:e})=>os(e))),n=t.slice(0,-1).indexOf(!0);if(n>=0)return`Line ${e[n]?.lines.find(({line:e})=>os(e))?.number} always fits, so the lines below it are never read. Move it to the end.`;if(!t.at(-1))return`The last line must always fit, so every call gets a label: no "when", and a fallback on every {value}, like "saving the item".`}var cs={},ls=new WeakMap;function us(e){let{input:t}=e,n=`output`in e?e.output:cs;if(typeof t!=`object`||!t||typeof n!=`object`||!n)return;let r=ls.get(t);r||(r=new WeakMap,ls.set(t,r));let i=r.get(n);return i||(i=new Map,r.set(n,i)),i}function ds(e,t){let n=us(t),r=JSON.stringify(e);if(n?.has(r))return n.get(r);let i=fs(e,t);return n?.set(r,i),i}function fs(e,t){let n=`output`in t?[`input`,`output`]:[`input`],r=typeof e!=`string`,i=Io(e);for(let{line:e,number:a}of i.flatMap(e=>e.lines)){let i=as(e,t,n,r);if(i)return r?`Line ${a}: ${i}`:i}return r?ss(i):void 0}var ps=w({kind:C(`auth_scope_refused`),slot:o(),requested:b(o()),declared:b(o())}),ms={tool_arguments:`tool_call`,taint:`tool_call`,destination:`tool_call`,tool_result:`tool_result`,tool_failure:`tool_result`,network:`network`,network_request:`network`},hs=new WeakSet;function gs(e,t,n,r){e&&(r&&hs.add(r),e.event(`theorem.guardrail`,Va(t,n,r,{stage:ms[t],trust:`untrusted`})))}function _s(e){return e?`execute_tool ${e}`:`execute_tool`}function vs(e){return{"gen_ai.operation.name":`execute_tool`,"gen_ai.tool.name":e.name,"gen_ai.tool.call.id":e.callId,"gen_ai.tool.type":`function`,"gen_ai.tool.call.arguments":A(ja(e.call)),...X(`theorem.tool.origin`,e.origin),...X(`theorem.tool.permission`,e.permission),...X(`theorem.tool.approved`,e.approved),...X(`theorem.step`,e.step)}}function ys(e){let t=e.kind===`auth`?e.authChallenge:void 0;return{kind:e.kind,...X(`permission`,e.permission),...e.summary?{summary:A(e.summary)}:{},...t?{auth:{slot:t.slot,type:t.authType,service:t.service,...X(`issuer`,t.issuer),...X(`resource`,t.resource),...X(`required_scopes`,t.requiredScopes)}}:{}}}var bs={ok:`OK`,error:`ERROR`,denied:`UNSET`,gated:`UNSET`,paused:`UNSET`,cancelled:`UNSET`};function xs(e,t){let n=e(_s(t.name),vs(t));return{span:n,observe:e=>{if(e.type===`guardrail`&&!hs.has(e.guardrail)&&n.event(`theorem.guardrail`,za(e.guardrail)),e.type===`tool`&&e.tool.phase===`gate`&&n.event(`theorem.gate`,ys(e.tool.gate)),e.type===`tool`&&e.tool.phase===`progress`){let t=ps.safeParse(e.tool.data);if(t.success){let{slot:e,requested:r,declared:i}=t.data;n.event(`theorem.auth.scope_refused`,{slot:e,requested:r,declared:i})}}if(e.type===`tool`&&e.tool.phase===`warning`){let{code:t,message:r,severity:i}=e.tool.warning;n.event(`theorem.tool.warning`,{code:t,message:A(r),...X(`severity`,i)})}e.type===`citation`&&n.event(`theorem.grounding`,{sources:N(e.sources)})},end:e=>{e.thrown!==void 0&&eo(n,e.thrown);let t=e.outcome===`error`?e.failure?.kind??(e.thrown===void 0?void 0:Tt(e.thrown)):void 0;n.set({...e.result?{"gen_ai.tool.call.result":A(e.result.text)}:{},...e.result?.parts?.length?{"theorem.tool.call.result.parts":e.result.parts.map(Ta)}:{},...e.data?{"theorem.tool.data":N(e.data.value)}:{},"theorem.tool.outcome":e.outcome,...X(`theorem.tool.failure.code`,e.failure?.code),...X(`error.type`,t)});let r=bs[e.outcome];n.end(r===`ERROR`&&t?{code:r,message:t}:{code:r})}}}function Ss(e){return e.modelText===void 0?Be(yr(e.finding,e.data),Je):e.modelText}function Cs(e){return{finding:`Tool error (${e.code}): ${e.message}`,...e.details===void 0?{}:{data:{details:e.details}}}}function ws(e){return Cs({...e,message:Be(e.message,Je)})}function Ts(e,t){return{type:`tool`,tool:{...t,name:e.name,callId:e.callId,...e.operationId?{operationId:e.operationId}:{},at:Date.now()}}}function Es(e,t,n,r){return Uo(n?.activityFailed,{input:r})??D(`tool.activity_failed`,{tool:Bo(e)},t)}function Ds(e){return e.activityFailed??Es(e.name)}function Os(e,t,n=Ss(ws(t))){return Ts(e,{phase:`error`,failure:t,readBack:n,activityPast:Ds(e)})}function ks(e,t,{reasoning:n,stepId:r,stepCallCount:i}={}){return{type:`tool`,tool:{name:e.name,callId:e.callId,...e.operationId?{operationId:e.operationId}:{},arguments:t,...n?.length?{reasoning:n}:{},...r?{stepId:r}:{},...i?{stepCallCount:i}:{}}}}function As(e){return`call_${e}_${crypto.randomUUID()}`}function js(e){return e===void 0?{}:E(e)?e:{value:e}}function Ms(e){return e instanceof Error?e.message:String(e)}function Ns(e,t){return Ts(e,{phase:`warning`,warning:{code:`sources_invalid`,message:t,severity:`warning`}})}function*Ps(e,t,n){let r;try{r=t(n)}catch(t){yield Ns(e,`sources threw: ${Ms(t)}`);return}if(!Array.isArray(r)){yield Ns(e,`sources must return an array`);return}let i=[],a=[];r.forEach((e,t)=>{let n=Cn.safeParse(e);n.success?i.push(n.data):a.push(`[${String(t)}] ${n.error.issues.map(e=>`${e.path.join(`.`)||`source`}: ${e.message}`).join(`; `)}`)}),a.length>0&&(yield Ns(e,`sources not cited: ${a.join(` | `)}`)),i.length>0&&(yield{type:`citation`,sources:i,callId:e.callId})}function Fs(e,t,n,r){let i=n.resume?.edited,a=Uo(e.labels?.activity,{input:t});return Ts(r,{phase:`running`,...i?{edited:{from:i.from,to:js(t)}}:{},...a?{activity:a}:{}})}var Is=class{begin;taken;failed;constructor(e){this.begin=e}claim(){return this.taken??=(this.begin?.()??Promise.resolve(void 0)).catch(e=>{throw this.failed={error:e},e}),this.taken}rethrowClaimFailure(){if(this.failed)throw this.failed.error}};async function*Ls(e,t,n,r,i){return ze(n.signal),yield Fs(e,t,n,r),new Is(i&&(()=>i(t)))}function Rs(e,t,n){ze(n.signal);let r=e.input.safeParse(t);return r.success?{ok:!0,data:r.data}:{ok:!1,failure:{code:`invalid_input`,kind:`bad_response`,message:D(`tool.input_invalid`,{},n.profile.labels),details:r.error.flatten()}}}function zs(){return{stage:`network`,trust:`untrusted`,action:`block`,hits:[{rule:yt.blocked,severity:`high`}]}}function*Bs(e,t=zs()){return yield{type:`guardrail`,guardrail:t},{code:`network_blocked`,kind:`blocked`,message:Ms(e)}}function*Vs(e,t,n){let r=performance.now();try{let i=$r(e,Us(t));return gs(n,`network`,performance.now()-r,void 0),{ok:!0,url:i}}catch(e){let t=zs();return gs(n,`network`,performance.now()-r,t),{ok:!1,failure:yield*Bs(e,t)}}}function Hs(e){let t=0,n=!1,r=!1;return{onCheck:e=>{t+=e,n=!0},record:i=>{!r&&n&&(r=!0,gs(e,`network_request`,t,i))}}}function Us(e){return Fr(e.profile.guardrails).network}function Q(e,t,n){return C(e).meta({title:t,description:n})}var Ws=_({taskType:a([Q(`RETRIEVAL_QUERY`,`Retrieval query`,`Embeddings optimized for general search queries. Pair with Retrieval document for the documents searched.`),Q(`RETRIEVAL_DOCUMENT`,`Retrieval document`,`Embeddings optimized for document search, such as indexing articles, books or web pages.`),Q(`SEMANTIC_SIMILARITY`,`Semantic similarity`,`Embeddings optimized to assess text similarity, such as for recommendations or duplicate detection.`),Q(`CLASSIFICATION`,`Classification`,`Embeddings optimized to classify texts according to preset labels, such as sentiment or spam.`),Q(`CLUSTERING`,`Clustering`,`Embeddings optimized to cluster texts based on their similarities.`),Q(`QUESTION_ANSWERING`,`Question answering`,`Embeddings for questions, optimized for finding documents that answer them. Pair with Retrieval document.`),Q(`FACT_VERIFICATION`,`Fact verification`,`Embeddings for statements to verify, optimized for retrieving evidence that supports or refutes them. Pair with Retrieval document.`),Q(`CODE_RETRIEVAL_QUERY`,`Code retrieval query`,`Embeddings optimized for finding code blocks from natural language queries. Pair with Retrieval document for the code.`)]).optional().describe(`What the vectors will be used for, so Google tunes them to it. Only gemini-embedding-001 takes it; later models read the request's task from the text. Absent: no tuning.`),outputDimensionality:a([C(768),C(1536),C(3072)]).optional().describe(`How many numbers each vector holds. A shorter vector is cheaper to store and compare and a little less precise. Absent: the 3072 the model returns.`)}),Gs=/^(gemini-embedding-001|text-embedding-|embedding-)/,Ks={maxInputs:100,media:[{accept:[`image/png`,`image/jpeg`],maxPerInput:6},{accept:[`application/pdf`],maxPerInput:1},{accept:[`audio/mpeg`,`audio/mp3`,`audio/wav`,`audio/x-wav`]},{accept:[`video/mp4`,`video/quicktime`]}]},qs={maxInputs:100,media:[]},Js={query:`RETRIEVAL_QUERY`,document:`RETRIEVAL_DOCUMENT`};function Ys(e,t){return t===`query`?`task: search result | query: ${e}`:`title: none | text: ${e}`}function Xs(e,t){let n=typeof e==`string`?[{type:`text`,text:e}]:e.parts,r=n.every(e=>e.type===`text`);return n.map((e,n)=>e.type===`text`?{text:t&&r&&n===0?Ys(e.text,t):e.text}:e.type===`media`?{inlineData:{mimeType:e.mimeType,data:e.data}}:{fileData:{mimeType:e.mimeType,fileUri:e.uri}})}function Zs(e){let t=e.embedding,n=t&&typeof t==`object`?t.values:void 0;return Array.isArray(n)?n.filter(e=>typeof e==`number`):[]}function Qs(e,t,n){let r={content:{parts:Xs(e,n.taskField?void 0:n.task)}},i=n.taskField&&n.task?Js[n.task]:t.taskType;return i&&(r.taskType=i),t.outputDimensionality&&(r.outputDimensionality=t.outputDimensionality),r}var $s=W({id:`geminiEmbeddings`,name:`Gemini Embeddings`,description:`Google's embedding API for text and supported media.`,endpoints:{embedding:`/models/{apiId}:embedContent`},operationNames:{embedding:`embeddings`},options:Ws,embeddingLimits:e=>Gs.test(e)?qs:Ks,refusedOptions:e=>Gs.test(e)?[]:[`taskType`],create(e){return{async embed(t){let n=gi($s,e.apiId,t.options),r={taskField:Gs.test(e.apiId),...t.task?{task:t.task}:{}},i=Array.isArray(t.input)?t.input:[t.input],a=i.length===1?Qs(i[0],n,r):{requests:i.map(t=>({model:`models/${e.apiId}`,...Qs(t,n,r)}))},o=i.length===1?`/models/${encodeURIComponent(e.apiId)}:embedContent`:`/models/${encodeURIComponent(e.apiId)}:batchEmbedContents`,s;for await(let t of e.send(a,{stream:!1,path:o}))s=t;let c=Array.isArray(s?.embeddings)?s.embeddings:s?.embedding?[s.embedding]:[];return{model:e.apiId,embeddings:c.map((e,t)=>({index:t,values:e&&typeof e==`object`?Zs({embedding:e}):[],dimensions:e&&typeof e==`object`?Zs({embedding:e}).length:0}))}}}}}),ec=_({truncate:S().optional().describe(`What happens to an input longer than the model reads. On, it is cut to fit; off, the call fails. Absent: Ollama cuts it.`),dimensions:v().int().positive().optional().describe(`How many numbers each vector holds, for models that can shorten theirs. Absent: the length the model returns.`)});function tc(e){return(Array.isArray(e)?e:[e]).map(e=>{if(typeof e==`string`)return e;if(e.parts.length!==1||e.parts[0]?.type!==`text`)throw new T(`unsupported`,`The Ollama embedding protocol accepts text only`);return e.parts[0].text})}var nc=W({id:`ollamaEmbeddings`,name:`Ollama Embeddings`,description:`Ollama’s local embedding endpoint.`,endpoints:{embedding:`/api/embed`},operationNames:{embedding:`embeddings`},options:ec,embeddingLimits:()=>({media:[]}),create(e){return{async embed(t){let n=ec.parse(t.options??{}),r=e.send({model:e.apiId,input:tc(t.input),...n.truncate===void 0?{}:{truncate:n.truncate},...n.dimensions===void 0?{}:{dimensions:n.dimensions}},{stream:!1}),i;for await(let e of r)i=e;let a=Array.isArray(i?.embeddings)?i.embeddings:[];return{model:typeof i?.model==`string`?i.model:e.apiId,embeddings:a.map((e,t)=>({index:t,values:Array.isArray(e)?e.filter(e=>typeof e==`number`):[],dimensions:Array.isArray(e)?e.length:0}))}}}}}),rc=_({encodingFormat:y([`float`,`base64`]).optional().describe("How OpenRouter sends each vector back: as a list of numbers (`float`) or packed into a base64 string (`base64`, smaller on the wire). Theorem decodes both to the same numbers. Absent: `float`.")}),ic={media:[{accept:[`image/*`]}]};function ac(e){return typeof e==`string`?e:{content:e.parts.map(e=>e.type===`text`?{type:`text`,text:e.text}:{type:`image_url`,image_url:{url:e.type===`media`?`data:${e.mimeType};base64,${e.data}`:e.uri}})}}function oc(e){if(Array.isArray(e)){if(!e.every(e=>typeof e==`number`&&Number.isFinite(e)))throw Error(`OpenRouter returned an embedding with a non-finite value`);return e}if(typeof e!=`string`)throw Error(`OpenRouter returned an embedding in an unsupported format`);let t=lt(e);if(t.byteLength%Float32Array.BYTES_PER_ELEMENT!==0)throw Error(`OpenRouter returned an invalid base64 embedding length`);return Array.from(new Float32Array(t.buffer,t.byteOffset,t.byteLength/Float32Array.BYTES_PER_ELEMENT))}var sc=W({id:`openRouterEmbeddings`,name:`OpenRouter Embeddings`,description:`OpenRouter embedding models, including supported multimodal models.`,endpoints:{embedding:`/embeddings`},operationNames:{embedding:`embeddings`},options:rc,embeddingLimits:()=>ic,create(e){return{async embed(t){let n=rc.parse(t.options??{}),r=Array.isArray(t.input)?t.input:[t.input],i={model:e.apiId,input:r.length===1&&typeof r[0]==`string`?r[0]:r.map(ac)};n.encodingFormat&&(i.encoding_format=n.encodingFormat);let a;for await(let t of e.send(i,{stream:!1}))a=t;let o=Array.isArray(a?.data)?a.data:[],s=a?.usage&&typeof a.usage==`object`?a.usage:void 0;return{model:typeof a?.model==`string`?a.model:e.apiId,embeddings:o.map((e,t)=>{let n=e&&typeof e==`object`?e:{},r=oc(n.embedding);return{index:typeof n.index==`number`?n.index:t,values:r,dimensions:r.length}}),...typeof s?.prompt_tokens==`number`?{usage:{inputTokens:s.prompt_tokens}}:{}}}}}}),cc=100,lc=599,uc=new Set([`API_KEY_INVALID`]);function dc(e){return Array.isArray(e)&&e.some(e=>{let t=q(e)?.reason;return typeof t==`string`&&uc.has(t)})}var fc={invalid_request:400,failed_precondition:400,parameter_unknown:400,authentication:401,payment_required:402,permission_denied:403,not_found:404,model_not_found:404,already_exists:409,aborted:409,out_of_range:416,rate_limit_exceeded:429,quota_exceeded:429,too_many_requests:429,api_error:500,unimplemented:501,service_unavailable:503,deadline_exceeded:504,bad_request:400,unauthorized:401,forbidden:403,method_not_allowed:405,request_timeout:408,conflict:409,payload_too_large:413,unprocessable_entity:422,internal_server_error:500,not_implemented:501,bad_gateway:502,gateway_timeout:504},pc=new Set([`safety`,`recitation`,`language`,`prohibited_content`,`spii`,`blocklist`,`image_safety`,`image_prohibited_content`,`image_recitation`,`image_other`,`content_blocked`]);function mc(e,t){if(e===`cancelled`)return new T(`cancelled`,t);if(pc.has(e))return new T(`safety`,t);let n=fc[e];return n===void 0?new T(`bad_response`,t):new T(We(n),t)}function hc(e){let t=q(e.error);if(!t)return null;let{code:n,message:r,status:i,details:a}=t,o=typeof r!=`string`||r.length===0?`Gemini returned an error.`:typeof i==`string`?`${i}: ${r}`:r;return dc(a)?new T(`auth`,o):typeof n==`number`&&n>=cc&&n<=lc?new T(We(n),o):typeof n==`string`?mc(n,o):new T(`bad_response`,o)}function gc(e,t,n){return e?.kind===`auth`?e:new T(We(t),e?.message??n)}var _c=_({location:_({latitude:v().min(-90).max(90),longitude:v().min(-180).max(180)})}),vc=[`googleSearch`,`googleMaps`,`urlContext`,`codeExecution`],yc={googleSearch:`google_search`,googleMaps:`google_maps`,urlContext:`url_context`,codeExecution:`code_execution`};function bc(e){return e.filter(e=>vc.includes(e.id))}function xc(e){let t=vc.find(t=>t===e.id);if(!t)throw new T(`config`,`Builtin '${e.id}' is not a Google tool`);return t}function Sc(e){let t=xc(e),n=yc[t];if(t===`googleMaps`&&e.args){let{location:t}=_c.parse(e.args);return{type:n,latitude:t.latitude,longitude:t.longitude}}return{type:n}}function Cc(e){let t=xc(e);if(e.args)throw new T(`unsupported`,`Builtin '${t}' takes no args on Google Live`);return{[t]:{}}}function wc(e){return{type:`text`,text:`[${e.type}: sent in the next message]`}}function Tc(e){return{type:`text`,text:`Files from ${e.name?`the ${e.name} result`:`a tool result`}:`}}function Ec(e,t){let n=[],r=[],i=()=>{r.length!==0&&(n.push({role:`user`,parts:r}),r=[])};for(let a of e){if(a.role!==`tool`){i(),n.push(a);continue}let e=(a.parts??[]).filter(e=>!t.has(e.type));e.length===0?n.push(a):(n.push({...a,parts:(a.parts??[]).map(e=>t.has(e.type)?e:wc(e))}),r.push(Tc(a),...e))}return i(),n}var Dc={type:`text`,text:`Files the assistant sent:`};function Oc(e){let t=[],n=[];for(let r of e){r.role!==`tool`&&n.length>0&&(t.push({role:`user`,parts:n}),n=[]);let e=r.role===`assistant`?(r.parts??[]).filter(e=>e.type!==`text`):[];e.length===0?t.push(r):(t.push({...r,parts:(r.parts??[]).map(e=>e.type===`text`?e:wc(e))}),n.push(Dc,...e))}return n.length>0&&t.push({role:`user`,parts:n}),t}function kc(e){let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t}function Ac(e){if(typeof e==`string`){let t=e.trim();if(t.length===0)return{ok:!0,value:{}};try{let n=JSON.parse(t);return E(n)?{ok:!0,value:n}:{ok:!1,error:`tool arguments JSON must be an object`,raw:e}}catch{return{ok:!1,error:`malformed tool arguments JSON`,raw:e}}}return E(e)?{ok:!0,value:e}:e==null?{ok:!0,value:{}}:{ok:!1,error:`tool arguments must be a JSON object`,raw:String(e)}}function jc(e){let t=Ac(e);if(!t.ok)throw new T(`bad_response`,t.error);return t.value}function Mc(e,t){let n=e.name.trim(),r={name:n,callId:e.id??As(n)},i={stepId:e.stepId,stepCallCount:e.stepCallCount};if(!n)return Nc(r,`function call is missing a name`,t,i);let a=Ac(t);return a.ok?[ks(r,a.value,i)]:Nc(r,a.error,a.raw,i)}function Nc(e,t,n,r={}){return[ks(e,{},r),Os(e,{code:`malformed_arguments`,kind:`bad_response`,message:t,details:{raw:n}})]}var Pc=[`minimal`,`low`,`medium`,`high`],Fc=[`pcm`];function Ic(e){if(e&&!Pc.includes(e))throw new T(`unsupported`,`Gemini does not take the '${e}' thinking level (${Pc.join(`, `)})`)}function Lc(e){return e.replaceAll(/[A-Z]/g,e=>`_${e.toLowerCase()}`)}function Rc(e){if(Array.isArray(e))return e.map(Rc);if(e&&typeof e==`object`){let t={};for(let[n,r]of Object.entries(e))n===`schema`||n===`parameters`||n===`arguments`?t[Lc(n)]=r:t[Lc(n)]=Rc(r);return t}return e}function zc(e){return Pi(e)}var Bc=`user_input`;function Vc(e){return{type:Bc,content:e.map(zc)}}function Hc(e){let t=K(e);return t.length>0?t.map(zc):[{type:`text`,text:``}]}var Uc=new Set([`text`,`image`,`video`]);function Wc(e){let t=K(e);return{type:`function_result`,...kc({name:e.name,call_id:e.tool_call_id}),result:t.length>0?t.map(zc):[{type:`text`,text:``}]}}function Gc(e,t){let n={type:`function_call`,id:e.id,name:e.function.name,arguments:jc(e.function.arguments)};return t?[{type:`thought`,signature:t},n]:[n]}var Kc=_({call:v().int().min(0),signature:o().min(1)});function qc(e,t){for(let n of e.reasoning??[]){let e=Kc.safeParse(n.data);if(e.success&&e.data.call===t)return e.data.signature}}function Jc(e,t){return{type:e===`assistant`?`model_output`:`user_input`,content:Hc(t)}}function Yc(e){if(e.role===`assistant`&&e.tool_calls&&e.tool_calls.length>0){let t=[];K(e).length>0&&t.push(Jc(`assistant`,e));for(let[n,r]of e.tool_calls.entries())t.push(...Gc(r,qc(e,n)));return t}return e.role===`assistant`?[Jc(`assistant`,e)]:[Jc(`user`,e)]}function Xc(e){return Ec(e,Uc).flatMap(e=>e.role===`tool`?[Wc(e)]:Yc(e))}function Zc(e){return[{type:`text`,mimeType:`application/json`,schema:e}]}function Qc(e,t){if(e.speech){if(e.image)throw new T(`config`,`cannot mix speech and image response formats`);if(e.structured)throw new T(`config`,`cannot mix speech and structured response formats`);let n=e.speech.format;if(n&&!Fc.includes(n))throw new T(`unsupported`,`Gemini speech returns ${Fc.join(`, `)}, not '${n}'`);t.responseFormat={type:`audio`}}else if(e.image){let n={type:`image`,mimeType:e.image.mimeType};e.image.aspectRatio&&(n.aspectRatio=e.image.aspectRatio),e.image.resolution&&(n.imageSize=e.image.resolution);for(let[t,n]of[[`quality`,e.image.quality],[`background`,e.image.background],[`n`,e.image.n],[`outputCompression`,e.image.outputCompression]])if(n!==void 0)throw new T(`unsupported`,`image.${t} is not supported on Google image models`);t.responseFormat=e.image.includeText?[{type:`text`},n]:n}else e.structured&&(t.responseFormat=Zc(e.structured.jsonSchema))}function $c(e,t){if(!e.speech)return;let{voice:n,speed:r}=e.speech;if(r!==void 0)throw new T(`config`,`Gemini Interactions speech has no speed field: set the pace in speech.style`);if(!n)throw new T(`config`,`Gemini speech needs a voice: set speech.voice`);t.speechConfig=[{voice:n}]}var el=new Set([`gemini-3.8-flash-tts`,`gemini-3.8-flash-lite-tts`]);function tl(e,t,n){if(!el.has(n))return{type:Bc,content:[{type:`text`,text:`Read the following aloud. ${t.trim()}\n`},...e.map(zc)]};let r=[{type:`speech_metadata`,style:t}];return{type:Bc,content:e.map(zc).map(e=>e.type===`text`?{...e,annotations:r}:e)}}function nl(e){return{type:`function`,name:e.name,description:e.description,parameters:e.parameters}}function rl(e){let t=[];for(let n of e.builtins)t.push(Sc(n));for(let n of e.wireTools??[])t.push(nl(n));return t}function il(e){let t=new Map;return e.map(e=>{for(let n of e.tool_calls??[])t.set(n.id,n.function.name);if(e.role!==`tool`||e.name||!e.tool_call_id)return e;let n=t.get(e.tool_call_id);return n?{...e,name:n}:e})}function al(e){if(e.continuation&&e.continuation.length>0)return Xc(il(e.continuation));let t=Xc(il(e.history??[]));if(e.input.length>0||t.length===0){let n=e.speech?.style;t.push(n?tl(e.input,n,e.apiId):Vc(e.input))}return t}function ol(e,t){e.store!==void 0&&(t.store=e.store),e.previousInteractionId&&(t.previousInteractionId=e.previousInteractionId),e.system&&(t.systemInstruction=e.system);let n=rl(e);n.length>0&&(t.tools=n)}function sl(e){let t={temperature:e.temperature,maxOutputTokens:e.maxOutputTokens};return e.speech?$c(e,t):(Ic(e.thinking),e.thinking&&(t.thinkingLevel=e.thinking),e.summaries&&(t.thinkingSummaries=e.summaries),e.image?.seed!==void 0&&(t.seed=e.image.seed)),{model:e.apiId,stream:e.stream??!0,input:al(e),generationConfig:t}}function cl(e){let t=sl(e);return Qc(e,t),ol(e,t),Rc(t)}var ll=16,ul=new Set([`audio/pcm`,`audio/l16`]);function dl(e,t,n){for(let r=0;r<n.length;r++)e.setUint8(t+r,n.charCodeAt(r))}function fl(e){if(e===void 0||!/^\d+$/.test(e))return;let t=Number(e);return t>0?t:void 0}function pl(e){let[t=``,...n]=e.split(`;`),r=new Map;for(let e of n){let t=e.indexOf(`=`);t>0&&r.set(e.slice(0,t).trim().toLowerCase(),e.slice(t+1).trim())}return{essence:t.trim().toLowerCase(),params:r}}function ml(e){let{essence:t,params:n}=pl(e);if(!ul.has(t))return;let r=fl(n.get(`rate`));if(r===void 0)return;let i=n.has(`channels`)?fl(n.get(`channels`)):1;if(i!==void 0)return{sampleRate:r,channels:i}}function hl(e,t){let{sampleRate:n,channels:r}=t,i=r*ll/8,a=n*i,o=e.length,s=new ArrayBuffer(44+o),c=new DataView(s);return dl(c,0,`RIFF`),c.setUint32(4,36+o,!0),dl(c,8,`WAVE`),dl(c,12,`fmt `),c.setUint32(16,16,!0),c.setUint16(20,1,!0),c.setUint16(22,r,!0),c.setUint32(24,n,!0),c.setUint32(28,a,!0),c.setUint16(32,i,!0),c.setUint16(34,ll,!0),dl(c,36,`data`),c.setUint32(40,o,!0),new Uint8Array(s,44).set(e),new Uint8Array(s)}function gl(e){let t=ml(e.mimeType);if(!t)return e;let n=hl(lt(e.data),t);return{mimeType:`audio/wav`,data:St(n)}}function _l(e,t){if(!t)return{known:e};let n={...e,...t};return n.id===e?.id&&n.model===e?.model?{known:e}:{known:n,event:{type:`response`,response:n}}}function vl(e){try{return{type:`structured`,structured:JSON.parse(e)}}catch(e){return M(new T(`bad_response`,`structured output was not valid JSON`,{cause:e}))}}function yl(e){let t=e.name.trim(),n=e.drafted??0;return!(e.id&&t)||e.args.length<=n?[]:(e.drafted=e.args.length,[{type:`tool_draft`,callId:e.id,name:t,text:e.args.slice(n)}])}function bl(e){if(!e)return[];let{grounding:t,sources:n}=e;return[{type:`grounding`,grounding:t},...n.length>0?[{type:`citation`,sources:n}]:[]]}function xl(e){let t=J(e.url);if(!t)return;let n=J(e.place_id);return{type:`maps`,uri:t,title:J(e.name)??t,...n?{placeId:n}:{}}}function Sl(e){return{maps:{title:e.title,uri:e.uri,...e.placeId?{placeId:e.placeId}:{}}}}function Cl(e){let t=J(e.uri);if(t)return{type:`web`,uri:t,title:J(e.title)??t}}function wl(e,t){t&&(e.some(e=>e.type===t.type?t.placeId&&e.placeId&&t.placeId===e.placeId?!0:e.uri===t.uri:!1)||e.push(t))}function Tl(e,t){let n=q(q(t)?.maps);if(!n){e.push(t);return}let r=J(n.placeId),i=J(n.uri);e.some(e=>{let t=q(q(e)?.maps);if(!t)return!1;let n=J(t.placeId);return r&&n&&r===n?!0:!!(i&&J(t.uri)===i)})||e.push(t)}function El(e){if(Array.isArray(e))for(let t of e){let e=J(q(t)?.search_suggestions);if(e)return e}}function Dl(e){let t=q(e),n=J(t?.url);if(t&&n){if(t.type===`place_citation`){let e=J(t.name)??n,r=J(t.place_id);return{type:`maps`,uri:n,title:e,...r?{placeId:r}:{}}}if(t.type===`url_citation`)return{type:`web`,uri:n,title:J(t.title)??n}}}function Ol(e,t){if(Array.isArray(t))for(let n of t)wl(e,Dl(n))}function kl(e,t){if(Array.isArray(t))for(let n of t){let t=q(n)?.places;if(Array.isArray(t))for(let n of t){let t=q(n),r=t?xl(t):void 0;r&&wl(e,r)}}}function Al(e){let t=[];if(Ol(t,e.annotations),Array.isArray(e.content))for(let n of e.content)Ol(t,q(n)?.annotations);kl(t,e.result);let n=[];for(let e of t)e.type===`maps`&&Tl(n,Sl(e));let r=El(e.result);if(r||t.length!==0)return{grounding:{metadata:e,...n.length>0?{chunks:n}:{},...r?{searchHtml:r}:{}},sources:t}}function jl(e,t){if(!e)return t;if(!t)return e;let n=[];for(let r of[...e.grounding.chunks??[],...t.grounding.chunks??[]])Tl(n,r);let r=[...e.sources];for(let e of t.sources)wl(r,e);let i=t.grounding.searchHtml??e.grounding.searchHtml,a=t.grounding.metadata??e.grounding.metadata;return{grounding:{...a?{metadata:a}:{},...n.length>0?{chunks:n}:{},...i?{searchHtml:i}:{}},sources:r}}function Ml(e){let t=q(e.delta);return bl(t?Al(t):void 0)}function Nl(e){let t;for(let n of e){let e=q(n);e&&(t=jl(t,Al(e)))}return bl(t)}function Pl(e){let t=q(e);if(!t)return[];let n=Array.isArray(t.groundingChunks)?t.groundingChunks:[],r=[];for(let e of n){let t=q(q(e)?.web);t&&wl(r,Cl(t))}let i=J(q(t.searchEntryPoint)?.renderedContent);return bl({grounding:{metadata:t,...n.length>0?{chunks:n}:{},...i?{searchHtml:i}:{}},sources:r})}function Fl(e,t){if(!Array.isArray(e))return;let n={};for(let r of e){let e=q(r),i=Y(e?.[t]);if(typeof e?.modality==`string`&&i!==void 0){let t=e.modality.toLowerCase();n[t]=(n[t]??0)+i}}return Object.keys(n).length>0?n:void 0}function Il(e,t){if(e||t)return{...e?{input:e}:{},...t?{output:t}:{}}}function Ll(e){if(!Array.isArray(e))return;let t=e.flatMap(e=>{let t=q(e),n=Y(t?.count);if(typeof t?.type!=`string`||n===void 0)return[];let r=Y(t.search_query_count);return[{type:t.type,count:n,...r===void 0?{}:{searchQueryCount:r}}]});return t.length>0?t:void 0}function Rl(e){let t=q(e);return t?.type===`text`&&typeof t.text==`string`?t.text:``}function zl(e){let t=e.mime_type;if(typeof t!=`string`||!t)return;let n=t.toLowerCase(),r=[];return typeof e.sample_rate==`number`&&!/;\s*rate=/.test(n)&&r.push(`rate=${String(e.sample_rate)}`),typeof e.channels==`number`&&!/;\s*channels=/.test(n)&&r.push(`channels=${String(e.channels)}`),r.length>0?`${t}; ${r.join(`; `)}`:t}var Bl=[[`/9j/`,`image/jpeg`],[`iVBORw0KGgo`,`image/png`],[`UklGR`,`image/webp`]];function Vl(e){return Bl.find(([t])=>e.startsWith(t))?.[1]}function Hl(e){let{data:t}=e;if(typeof t!=`string`||!t)return[];let n=zl(e)??(e.type===`image`?Vl(t):void 0);return n?[{type:`media`,media:{mimeType:n,data:t}}]:[]}function Ul(e,t){return t?[{type:e,text:t}]:[]}function Wl(e){return e===`code_execution_call`||e===`code_execution_result`}function Gl(e){return e.startsWith(`google_`)||e===`url_context_call`||e===`url_context_result`}function Kl(e){return{type:`evidence`,evidence:{provider:`google`,kind:`provider_step`,step:String(e.type??``),raw:e}}}function ql(e){if(e.type===`code_execution_result`){let t=J(e.call_id);return{type:`evidence`,evidence:{provider:`google`,kind:`code_execution_result`,raw:e,...typeof e.result==`string`?{result:e.result}:{},...typeof e.is_error==`boolean`?{isError:e.is_error}:{},...t?{callId:t}:{}}}}let t=q(e.arguments),n=J(e.id);return e.type!==`code_execution_call`||!n||typeof t?.code!=`string`?Kl(e):{type:`evidence`,evidence:{provider:`google`,kind:`code_execution_call`,raw:e,code:t.code,...typeof t.language==`string`?{language:t.language}:{},id:n}}}function Jl(e){let t=q(e);if(!t)return[];switch(t.type){case`thought_summary`:return Ul(`thought`,Rl(t.content));case`text`:return Ul(`text`,typeof t.text==`string`?t.text:``);case`image`:case`audio`:return Hl(t);default:return[]}}function Yl(e){return(Array.isArray(e.summary)?e.summary:[]).flatMap(e=>Ul(`thought`,Rl(e)))}function Xl(e){return(Array.isArray(e.content)?e.content:[]).flatMap(e=>{let t=q(e);return t?.type===`text`?Ul(`text`,typeof t.text==`string`?t.text:``):t?.type===`image`||t?.type===`audio`?Hl(t):[]})}function Zl(e){let t=q(e);if(!t)return;let n=Y(t.total_output_tokens),r=Y(t.total_thought_tokens)??0,i=Y(t.total_tool_use_tokens)??0,a=Y(t.total_tokens),o=a===void 0?void 0:a-(n??0)-r-i,s=Y(t.total_input_tokens)||(o&&o>0?o:0);return fa({input:s?s+i:void 0,output:n===void 0?void 0:n+r,thinking:r,toolUse:i,cached:Y(t.total_cached_tokens),byModality:Il(Fl(t.input_tokens_by_modality,`tokens`),Fl(t.output_tokens_by_modality,`tokens`)),grounding:Ll(t.grounding_tool_count)})}function Ql(e){let t=Zl(e.usage);if(!t)return;let n=typeof e.id==`string`?e.id:void 0;return{type:`tokens`,tokens:t,...n?{interactionId:n}:{}}}function $l(e){let t=[],n=Ql(e);n&&t.push(n);let{steps:r}=e;Array.isArray(r)&&t.push(...Nl(r));let i=tu(e);return i&&t.push(i),t}function eu(e){let t=J(e.id),n=J(e.model);if(t||n)return{...t?{id:t}:{},...n?{model:n}:{}}}function tu(e){let{status:t}=e;if(typeof t==`string`)return{type:`done`,stop:ua(t),...typeof e.id==`string`?{interactionId:e.id}:{}}}function nu(){return{text:``,steps:new Map,sawMedia:!1,sawDone:!1,calls:0}}function ru(e){return e===`function_call`||Wl(e)||Gl(e)}function iu(e){return typeof e==`string`&&e.length>0?e:void 0}function au(e,t){let n=iu(e);n&&(t.thoughtSignature=n)}function ou(e,t){let n=iu(e.signature)??t.thoughtSignature;return t.thoughtSignature=void 0,n}function su(e,t){let n=String(e.type??``);if(n===`function_call`){let n=typeof e.id==`string`?e.id:void 0,r=typeof e.name==`string`?e.name:``,i=ou(e,t),a=t.calls++;return[...i?[{type:`reasoning`,data:{call:a,signature:i},origin:{protocol:`geminiInteractions`}}]:[],...Mc({id:n,name:r},e.arguments)]}return Wl(n)?[ql(e)]:Gl(n)?[Kl(e)]:n===`thought`?(au(e.signature,t),Yl(e)):n===`model_output`?Xl(e):[]}function cu(e){return typeof e.index==`number`?e.index:0}function lu(e,t){let n=q(e.step);if(!n)return;let r=String(n.type??``);r===`thought`&&au(n.signature,t),ru(r)&&t.steps.set(cu(e),{...n})}function uu(e,t){let n=q(e.delta);if(!n)return[];let r=t.steps.get(cu(e));if(!r)return n.type===`thought_signature`&&au(n.signature,t),Jl(n);if(n.type===`arguments_delta`){let e=typeof r.arguments==`string`?r.arguments:``,t=e+(typeof n.arguments==`string`?n.arguments:``);return r.arguments=t,r.type===`function_call`?yl({id:iu(r.id),name:typeof r.name==`string`?r.name:``,args:t,drafted:e.length}):[]}return Object.assign(r,n),[]}function du(e,t){let n=cu(e),r=t.steps.get(n);return r?(t.steps.delete(n),su(r,t)):[]}function fu(e){let t=Wl(String(e.type??``))?ql(e):Kl(e);return{...t,evidence:{...t.evidence,partial:!0}}}function pu(e){let t=[...e.steps.values()].map(fu);return e.steps.clear(),t}function mu(e,t){return e.map(e=>(e.type===`done`&&(t.sawDone=!0),e.type===`text`&&e.text&&(t.text+=e.text),e.type!==`media`||!e.media?e:(t.sawMedia=!0,{...e,media:gl(e.media)})))}function hu(e,t){if(e.eventType===`sse_unparsed`)return[M(new T(`bad_response`,`Interactions stream row was not a JSON object`))];let n=hc(e);if(n)return[M(n)];let r=Ml(e);switch(e.event_type){case`step.start`:lu(e,t);break;case`step.delta`:r.push(...uu(e,t));break;case`step.stop`:r.push(...du(e,t));break;case`interaction.created`:{let n=q(e.interaction);n&&r.push(...gu(n,t));break}case`interaction.completed`:{let n=q(e.interaction);n&&r.push(...gu(n,t),...$l(n));break}}return r}function gu(e,t){let n=_l(t.response,eu(e));return t.response=n.known,n.event?[n.event]:[]}function _u(e,t){return mu(hu(e,t),t)}function vu(e,t){let n=(Array.isArray(e.steps)?e.steps:[]).flatMap(e=>{let n=q(e);return n?su(n,t):[]});return mu([...gu(e,t),...n,...$l(e)],t)}function*yu(e,t){e.structured&&t.text&&(yield vl(t.text))}function bu(e){return!!e.speech}function xu(e,t){if(!t.sawMedia){if(bu(e))return M(new T(`bad_response`,`speech audio was not returned by the model`));if(e.image)return M(new T(`bad_response`,`no image returned from image generation`))}}function Su(e){return e.type===`done`?{type:`done`,stop:e.stop,...e.interrupted===void 0?{}:{interrupted:e.interrupted}}:e.type===`tool`?e.tool.phase===void 0?{type:`tool_call`,call:e.tool}:e.tool.phase===`cancel`?{type:`tool_cancel`,callId:e.tool.callId}:e.tool.phase===`error`?{type:`error`,errorKind:`bad_response`}:void 0:e}var Cu=_({interactionId:o().min(1)}),wu=_({store:S().optional().describe(`Whether Google keeps the interaction. Off, nothing is stored server-side.`),persistViaInteractionId:S().optional().describe(`Continue from the stored interaction instead of sending the conversation again. Needs store.`)}).refine(e=>!e.persistViaInteractionId||e.store!==!1,`persistViaInteractionId needs store`);function Tu(e,t){let n=t.history??[],r=e.options.persistViaInteractionId?t.state?.interactionId:void 0,i=bc(t.builtins),a={...t,apiId:e.apiId,history:n,builtins:i,state:void 0,tapUpstream:void 0,store:e.options.store,previousInteractionId:r,continuation:r?[...n.slice(t.stateHistoryLength??0),...t.input.map(e=>({role:`user`,parts:[e]}))]:void 0};return{wire:a,body:I.parse(JSON.parse(JSON.stringify(cl(a)))),wroteTools:i.map(e=>e.id)}}function Eu(e,t,n){return e.flatMap(e=>{if(e.type!==`done`){let t=Su(e);return t?[t]:[]}let{interactionId:r,...i}=e;return t.done={...i,...n&&r?{state:{interactionId:r}}:{}},[]})}var Du=W({id:`geminiInteractions`,name:`Gemini Interactions`,description:`Google's Interactions API for Gemini: text, images and speech at one endpoint.`,endpoints:{text:`/interactions`,image:`/interactions`,speech:`/interactions`},operationNames:{text:`generate_content`,image:`generate_content`,speech:`generate_content`},options:wu,continuation:{version:1,schema:Cu,keyOptions:[`store`,`persistViaInteractionId`]},reasoning:Kc,error(e){let t=q(e.body);return gc(t?hc(t):null,e.status,`Gemini HTTP ${e.status}`)},create(e){return{async*complete(t){let{wire:n,body:r,wroteTools:i}=Tu(e,t),a=t.stream!==!1,o=!!e.options.persistViaInteractionId,s={fold:nu()},c={stream:a,wroteTools:i,...a?{path:`/interactions?alt=sse`}:{}};for await(let t of e.send(r,c)){let e=hc(t);if(e)throw e;let n=a?_u(t,s.fold):vu(t,s.fold);if(yield*Eu(n,s,o),n.some(e=>e.type===`error`)){yield*Eu(pu(s.fold),s,o);return}}yield*Eu(pu(s.fold),s,o),yield*Eu([...yu(n,s.fold)],s,o);let l=xu(n,s.fold);l&&(yield*Eu([l],s,o)),yield s.done??{type:`done`,stop:{kind:`stream_incomplete`}}}}}}),Ou=`NON_BLOCKING`;function ku(e){return{name:e.name,description:e.description,behavior:Ou,parametersJsonSchema:e.parameters??{type:`object`,properties:{}}}}function Au(e){let t=[];for(let n of e.builtins)t.push(Cc(n));let n=(e.wireTools??[]).map(ku);return n.length>0&&t.push({functionDeclarations:n}),t}function ju(e){let t={responseModalities:[`AUDIO`],temperature:e.temperature,maxOutputTokens:e.maxOutputTokens};e.live?.voice&&(t.speechConfig={voiceConfig:{prebuiltVoiceConfig:{voiceName:e.live.voice}}}),Ic(e.thinking);let n={...e.thinking?{thinkingLevel:e.thinking}:{},...e.summaries?{includeThoughts:e.summaries===`auto`}:{}};return Object.keys(n).length>0&&(t.thinkingConfig=n),t}function Mu(e){let{triggerTokens:t}=e,{targetTokens:n}=e.slidingWindow;return{...t===void 0?{}:{triggerTokens:t},slidingWindow:n===void 0?{}:{targetTokens:n}}}function Nu(e){let t={};e.startSensitivity!==void 0&&(t.startOfSpeechSensitivity=e.startSensitivity),e.endSensitivity!==void 0&&(t.endOfSpeechSensitivity=e.endSensitivity),e.prefixPaddingMs!==void 0&&(t.prefixPaddingMs=e.prefixPaddingMs),e.silenceDurationMs!==void 0&&(t.silenceDurationMs=e.silenceDurationMs);let n={};return e.activityHandling!==void 0&&(n.activityHandling=e.activityHandling),Object.keys(t).length>0&&(n.automaticActivityDetection=t),Object.keys(n).length>0?n:void 0}function Pu(e){if(e.sessionResumptionHandle)return{handle:e.sessionResumptionHandle};if(e.live?.sessionResumption)return{}}function Fu(e){return e.startsWith(`models/`)?e:`models/${e}`}function Iu(e,t){e?.transcription?.input&&(t.inputAudioTranscription={}),e?.transcription?.output&&(t.outputAudioTranscription={})}function Lu(e){let t=e.live,n=t?.vad?Nu(t.vad):void 0,r=Au(e),i=Pu(e),a=!!(e.history?.length||e.context?.length),o={model:Fu(e.apiId),generationConfig:ju(e),systemInstruction:{parts:[{text:e.system}]},...r.length>0?{tools:r}:{},...i?{sessionResumption:i}:{},...t?.contextCompression?{contextWindowCompression:Mu(t.contextCompression)}:{},...a?{historyConfig:{initialHistoryInClientContent:!0}}:{},...n?{realtimeInputConfig:n}:{}};return Iu(t,o),{setup:o}}function Ru(e){if(Fi(e))throw new T(`unsupported`,`media references are not supported on geminiLive`);return e}function zu(e){let t=Ru(e);return{mimeType:t.mimeType,data:t.data}}function Bu(e){return e.type===`text`?{text:e.text}:{inlineData:zu(e)}}function Vu(e){let t=K(e),n=t.map(e=>e.type===`text`?e.text:``).filter(Boolean).join(`
3
3
  `),r=t.filter(e=>e.type!==`text`).map(Bu);return{role:`user`,parts:[{functionResponse:{...kc({id:e.tool_call_id,name:e.name}),response:{result:n},...r.length>0?{parts:r}:{}}}]}}function Hu(e){if(e.role===`tool`)return Vu(e);let t=e.role===`assistant`?`model`:`user`,n=K(e).map(Bu);for(let t of e.role===`assistant`?e.tool_calls??[]:[])n.push({functionCall:{id:t.id,name:t.function.name,args:jc(t.function.arguments)}});return{role:t,parts:n}}function Uu(e=[],t=[]){return e.length===0&&t.length===0?null:{clientContent:{turns:[...e.map(Hu),...t.length?[{role:`user`,parts:t.map(e=>({text:e}))}]:[]],turnComplete:!0}}}function Wu(e){return{clientContent:{turns:[{role:`user`,parts:[{text:e}]}],turnComplete:!1}}}function Gu(e){if(e.type===`text`)return{realtimeInput:{text:e.text}};let t=Ru(e),n={mimeType:t.mimeType,data:t.data};return{realtimeInput:t.type===`audio`?{audio:n}:{video:n}}}function Ku(e){let t=q(e)?.error;return typeof t==`string`?{error:t}:{result:e}}function qu(e,t,n,r){return Ju([{id:e,name:t,output:n,parts:r}])}function Ju(e){return{toolResponse:{functionResponses:e.map(({id:e,name:t,output:n,parts:r})=>({id:e,name:t,response:Ku(n),...r?.length?{parts:r.filter(e=>e.type!==`text`).map(Bu)}:{}}))}}}function Yu(e){return{role:`tool`,...typeof e.id==`string`?{tool_call_id:e.id}:{},...typeof e.name==`string`?{name:e.name}:{},content:JSON.stringify(e.response??null)}}function Xu(e){return Array.isArray(e)?e.flatMap(e=>{let t=q(e);return t?[t]:[]}):[]}function Zu(e){let t=[],n=[],r=[];for(let i of Xu(e.parts)){let e=q(i.inlineData),a=q(i.functionCall),o=q(i.functionResponse);if(typeof i.text==`string`)t.push({type:`text`,text:i.text});else if(e&&typeof e.mimeType==`string`&&typeof e.data==`string`){let n=Rr(e.mimeType)??`document`;t.push({type:n,mimeType:e.mimeType,data:e.data})}else a?n.push({id:typeof a.id==`string`?a.id:``,type:`function`,function:{name:String(a.name??``),arguments:JSON.stringify(a.args??{})}}):o&&r.push(Yu(o))}let i=e.role===`model`?`assistant`:`user`;return[...t.length>0||n.length>0?[{role:i,parts:t,...n.length>0?{tool_calls:n}:{}}]:[],...r]}function Qu(e){let t=q(e.realtimeInput);if(t){let e=q(t.audio),n=q(t.video),r=e??n;return r&&typeof r.mimeType==`string`&&typeof r.data==`string`?[{role:`user`,parts:[{type:e?`audio`:`video`,mimeType:r.mimeType,data:r.data}]}]:typeof t.text==`string`?[{role:`user`,parts:[{type:`text`,text:t.text}]}]:[]}let n=q(e.clientContent);if(n)return Xu(n.turns).flatMap(Zu);let r=q(e.toolResponse);return r?Xu(r.functionResponses).map(Yu):[]}function $u(e){let t=Y(e.promptTokenCount),n=Y(e.responseTokenCount),r=Y(e.thoughtsTokenCount)??0,i=Y(e.toolUsePromptTokenCount)??0;return fa({input:t?t+i:void 0,output:n===void 0?void 0:n+r,thinking:r,toolUse:i,cached:Y(e.cachedContentTokenCount),byModality:Il(Fl(e.promptTokensDetails,`tokenCount`),Fl(e.responseTokensDetails,`tokenCount`))})}function ed(e,t){let n=q(e.sessionResumptionUpdate);if(!n)return;let r=typeof n.newHandle==`string`&&n.newHandle.length>0?n.newHandle:void 0,i=typeof n.resumable==`boolean`?n.resumable:void 0;(r!==void 0||i!==void 0)&&t.push({type:`evidence`,...r===void 0?{}:{sessionResumptionHandle:r},evidence:{provider:`google`,kind:`session_resumption`,resumable:i??r!==void 0,raw:n}})}function td(){return{calls:new Map}}function nd(e,t,n){let r=q(e.toolCall)?.functionCalls;if(!Array.isArray(r))return;let i=crypto.randomUUID(),a=r.length;for(let e of r){let r=q(e)??{},o=typeof r.id==`string`&&r.id?r.id:void 0,s=typeof r.name==`string`?r.name:``;o&&s&&t.calls.set(o,s),n.push(...Mc({id:o,name:s,stepId:i,stepCallCount:a},r.args))}}function rd(e,t,n){let r=q(e.toolCallCancellation)?.ids;if(Array.isArray(r))for(let e of r){let r=typeof e==`string`?t.calls.get(e):void 0;typeof e!=`string`||!r?n.push(M(new T(`bad_response`,`Live cancelled a tool call it never issued: ${String(e)}`))):(t.calls.delete(e),n.push(Ts({name:r,callId:e},{phase:`cancel`})))}}function id(e,t){let n=q(e.voiceActivity);n&&t.push({type:`evidence`,evidence:{provider:`google`,kind:`voice_activity`,raw:n}})}function ad(e){if(typeof e!=`string`)return;let t=/^(\d+(?:\.\d+)?)s$/.exec(e);return t?.[1]?Math.round(Number(t[1])*1e3):void 0}function od(e,t){let n=q(e.goAway);if(!n)return;let r=ad(n.timeLeft);t.push({type:`session`,session:{kind:`closing_soon`,...r===void 0?{}:{timeLeftMs:r}}})}function sd(e,t){typeof e.text==`string`&&e.text&&t.push({type:e.thought===!0?`thought`:`text`,text:e.text});let n=q(e.inlineData),r=n?.mimeType,i=n?.data;typeof r==`string`&&r&&typeof i==`string`&&i&&t.push({type:`media`,media:gl({mimeType:r,data:i})});let a=q(e.codeExecutionResult);a&&t.push(cd(a))}function cd(e){return{type:`evidence`,evidence:{provider:`google`,kind:`code_execution_result`,...typeof e.output==`string`?{result:e.output}:{},...typeof e.outcome==`string`?{isError:e.outcome!==`OUTCOME_OK`}:{},raw:e}}}function ld(e){let t=q(e)?.text;return typeof t==`string`&&t?t:void 0}function ud(e,t,n,r){let i=ld(e);i&&n.push({type:`evidence`,text:i,evidence:{provider:`google`,kind:t,...r?{interim:!0}:{}}})}function dd(e,t){t.push(...Pl(e.groundingMetadata));let n=q(e.urlContextMetadata);n&&t.push({type:`evidence`,evidence:{provider:`google`,kind:`url_context`,raw:n}})}function fd(e){let t=q(e.serverContent)?.interactionStatus;if(t===`IN_PROGRESS`||t===`IDLE`)return t}function pd(e,t){let n=fd(e);n&&t.push({type:`session`,session:{kind:n===`IDLE`?`idle`:`working`}})}function md(e,t){let n=q(e.serverContent);if(!n)return;n.interrupted===!0&&t.push({type:`done`,interrupted:!0,stop:{kind:`interrupted`}}),n.waitingForInput===!0&&t.push({type:`session`,session:{kind:`waiting_for_input`}}),n.generationComplete===!0&&t.push({type:`done`,stop:{kind:`generation_complete`}}),ud(n.inputTranscription,`input_transcription`,t),ud(n.interimInputTranscription,`input_transcription`,t,!0),ud(n.outputTranscription,`output_transcription`,t);let r=q(n.modelTurn)?.parts;for(let e of Array.isArray(r)?r:[]){let n=q(e);n&&sd(n,t)}dd(n,t),n.turnComplete===!0&&t.push({type:`session`,session:{kind:`turn_complete`}})}function hd(e,t){let n=q(e.usageMetadata),r=n?$u(n):void 0;r&&t.push({type:`tokens`,tokens:r})}function gd(e,t){if(!e||typeof e!=`object`)return[];let n=[];return od(e,n),ed(e,n),nd(e,t,n),rd(e,t,n),id(e,n),md(e,n),pd(e,n),hd(e,n),n}var _d={1006:`network`,1007:`unsupported`,1008:`unsupported`,1011:`unavailable`,1013:`busy`},vd=/\bquota\b/i,yd=/\bAPI key (?:not valid|expired)\b/i;function bd(e){if(vd.test(e))return`rate_limit`;if(yd.test(e))return`auth`}function xd(e,t,n){return new T(bd(t)??_d[e]??`unavailable`,`Gemini Live WebSocket closed during ${n} (${e}: ${t})`)}function Sd(e){let t=da(e,e=>e.type===`session`&&e.session.kind===`closing_soon`);return t?.session.kind===`closing_soon`?{timeLeftMs:t.session.timeLeftMs}:void 0}function Cd(e,t){if(t.some(e=>e.type===`done`&&e.interrupted===!0))return`abort`;let n=fd(e);return n===`IDLE`?`complete`:n===`IN_PROGRESS`?`streaming`:q(e.serverContent)?.turnComplete===!0?`complete`:`streaming`}var wd=_({liveHandle:o().min(1)}),Td=1e3;function Ed(e,t){return e.eventType===`ws_error`?new T(`network`,`Gemini Live WebSocket error during ${t}`):e.eventType===`ws_unparsed`?new T(`bad_response`,`malformed Gemini Live message`):hc(e)??void 0}async function Dd(e,t){let n,r=t.limits.connectTimeoutMs,i=new Promise((e,t)=>{r!==void 0&&(n=setTimeout(()=>t(new T(`timeout`,`Gemini Live setup timed out after ${r}ms`)),r))});try{for(;;){let t=await Promise.race([e.next(),i]);if(t.done)throw xd(1006,``,`setup`);let n=t.value;if(n.eventType===`ws_close`)throw xd(Number(n.code),String(n.reason??``),`setup`);let r=Ed(n,`setup`);if(r)throw r;if(n.setupComplete)return}}finally{clearTimeout(n)}}function Od(e,t){let n=t.state?.liveHandle,r=t.history??[],i=bc(t.builtins),a={...t,apiId:e.apiId,builtins:i,state:void 0,tapUpstream:void 0,sessionResumptionHandle:n,history:n?r.slice(t.stateHistoryLength??0):r,live:{...t.live,transcription:{...t.live?.transcription,input:!0,output:!0}}};return{wire:a,setup:I.parse(JSON.parse(JSON.stringify(Lu(a)))),wroteTools:i.map(e=>e.id)}}function*kd(e,t,n){let r=[...e.filter(e=>e.type===`tokens`),...e.filter(e=>e.type!==`tokens`)];for(let e of r){let t=Su(e);t&&(yield t)}if(t===`abort`)return;let i=n?{state:{liveHandle:n}}:{};e.some(e=>e.type===`tool`&&e.tool.phase===void 0)&&(yield{type:`done`,stop:{kind:`tool`},...i}),t===`complete`&&(yield{type:`done`,stop:{kind:`completed`},...i})}function Ad(e,t,n,r){let i=t=>Md(e,t),a=td(),o=r,s,c;return{closeInfo:()=>c,async*events(){for(;;){let e=await t.next();if(e.done)return;let r=e.value;if(r.eventType===`ws_close`){n.signal?.throwIfAborted();let e=Number(r.code),t=String(r.reason??``);c={code:e,reason:t,...e===Td?{}:{error:xd(e,t,`session`)},...s?{warning:{...s.timeLeftMs===void 0?{}:{timeLeftMs:s.timeLeftMs},closedAfterMs:Math.round(performance.now()-s.atMs)}}:{}};return}let i=Ed(r,`session`);if(i)throw i;if(r.setupComplete)continue;let l=gd(r,a),u=Sd(l);u&&(s={...u,atMs:performance.now()});for(let e of l)e.type===`evidence`&&e.sessionResumptionHandle&&(o=e.sessionResumptionHandle);yield*kd(l,Cd(r,l),o)}},sendText:e=>$(()=>i(Gu({type:`text`,text:e}))),sendAudio:e=>$(()=>i(Gu({type:`audio`,...e}))),sendVideo:e=>$(()=>i(Gu({type:`video`,...e}))),sendContext:e=>$(()=>i(Wu(typeof e.server==`string`?e.server:JSON.stringify(e)))),sendToolResult:e=>$(()=>i(qu(e.callId,e.name,e.text,e.parts))),close:t=>$(()=>e.close(Td,t??`session-closed`))}}var jd=W({id:`geminiLive`,name:`Gemini Live`,description:`Google's Live API for Gemini: a spoken session over one WebSocket.`,endpoints:{live:`/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent`},operationNames:{live:`generate_content`},options:_({}),continuation:{version:1,schema:wd},create(e){return{async openSession(t){let{wire:n,setup:r,wroteTools:i}=Od(e,t),a=await e.connect(r,{wroteTools:i}),o=a.frames()[Symbol.asyncIterator](),s=()=>a.close(Td,`aborted`);e.signal?.addEventListener(`abort`,s,{once:!0});try{e.signal?.throwIfAborted(),await Dd(o,e)}catch(t){throw e.signal?.removeEventListener(`abort`,s),a.close(Td,`setup-failed`),t}let c=Uu(n.history,n.context);c&&Md(a,c);for(let e of n.input)Md(a,Gu(e));return Ad(a,o,e,n.sessionResumptionHandle)}}}});function $(e){try{return e(),Promise.resolve()}catch(e){return Promise.reject(e)}}function Md(e,t){e.send(t,Qu(t))}var Nd={input:.75,output:4.5,byModality:{input:{audio:3,image:1,video:1},output:{audio:12}}},Pd={checked:`2026-10-15`,models:{"gemini-3.8-flash":{input:.75,output:3.75,cachedInput:.075},"gemini-3.6-flash":{input:.75,output:3.75,cachedInput:.075},"gemini-3.8-live":Nd,"gemini-3.8-live-extended-thinking":Nd,"gemini-3.1-flash-live-preview":Nd,"gemini-3.5-flash-lite":{input:.3,output:2.5,cachedInput:.03},"gemini-3.1-flash-lite":{input:.25,output:1.5,cachedInput:.025,byModality:{input:{audio:.5}}},"gemini-3.1-pro-preview":{input:2,output:12,cachedInput:.2,longContext:{above:2e5,input:4,output:18,cachedInput:.4}},"gemini-3.1-flash-lite-image":{input:.25,output:1.5,byModality:{output:{image:30}}},"gemini-3.8-flash-tts":{input:.5,output:9},"gemini-3.8-flash-lite-tts":{input:.5,output:6},"gemini-3.1-flash-tts-preview":{input:1,output:20},"gemini-3-flash-preview":{input:.5,output:3,cachedInput:.05,byModality:{input:{audio:1}}},"gemini-2.5-flash":{input:.3,output:2.5,cachedInput:.03,byModality:{input:{audio:1}}},"gemini-2.5-flash-lite":{input:.1,output:.4,cachedInput:.01,byModality:{input:{audio:.3}}},"gemini-2.5-flash-preview-tts":{input:.5,output:10},"gemini-2.5-flash-image":{input:.3,output:30}}},Fd=Wi({id:`gemini`,name:`Gemini`,description:`Google's models with an API key, from Google AI Studio.`,traceName:`gcp.gemini`,connection:_({host:zi.refine(e=>{let t=new URL(e);return t.pathname===`/`&&!t.search&&!t.hash},D(`protocol.endpoint_host`)).optional().describe(`The API host, by default https://generativelanguage.googleapis.com. Live connects to the same host over wss.`)}).default({}),key:o().trim().min(1),authorize:Vi(`x-goog-api-key`),prices:Pd,check:{protocol:Du,path:`/models?pageSize=1`},serves(e){let t=new URL(e.host??`https://generativelanguage.googleapis.com`),n=t.origin,r=`${t.protocol===`http:`?`ws:`:`wss:`}//${t.host}`;return[{protocol:Du,baseUrl:`${n}/v1beta`},{protocol:$s,baseUrl:`${n}/v1beta`},{protocol:jd,baseUrl:`${r}/ws`,authorize:Hi(`key`)}]}}),Id=new Set([`message`,`type`,`param`,`code`]);function Ld(e){if(typeof e==`string`)return e.trim()||void 0;let t=q(q(e)?.error);if(!t)return e==null?void 0:JSON.stringify(e);let n=Object.fromEntries(Object.entries(t).filter(([e])=>!Id.has(e))),r=typeof t.message==`string`&&t.message?[t.message]:[],i=Object.keys(n).length>0?[JSON.stringify(n)]:[];return[...r,...i].join(` `)||JSON.stringify(t)}function Rd(e,t){let n=Ld(e.body),r=`${t} HTTP ${String(e.status)}`;return new T(We(e.status),n?`${r}: ${n}`:r)}function zd(e){if(Fi(e))throw new T(`unsupported`,`media references are not supported on openAi`)}function Bd(e){let t=`mp3`;return e.mimeType.includes(`wav`)&&(t=`wav`),{type:`input_audio`,input_audio:{data:e.data,format:t}}}function Vd(e){return e.every(e=>e.type===`text`)?e.map(e=>e.type===`text`?e.text:``).filter(Boolean).join(`
4
4
  `):e.map(e=>e.type===`text`?{type:`text`,text:e.text}:(zd(e),e.type===`image`?{type:`image_url`,image_url:{url:`data:${e.mimeType};base64,${e.data}`}}:e.type===`audio`?Bd(e):{type:`file`,file:{filename:e.type===`video`?`clip.bin`:`document.bin`,file_data:`data:${e.mimeType};base64,${e.data}`}}))}function Hd(e){let t=Vd(K(e));if(e.role===`tool`)return{role:`tool`,...kc({tool_call_id:e.tool_call_id,name:e.name}),content:t};let n={role:e.role,content:t};return e.tool_calls&&e.tool_calls.length>0&&(n.tool_calls=e.tool_calls.map(e=>({id:e.id,type:`function`,function:{name:e.function.name,arguments:e.function.arguments}}))),e.name&&(n.name=e.name),n}var Ud=new Set([`text`,`image`]);function Wd(e,t){let n=t?.includeSystem!==!1,r=[];n&&e.system&&r.push({role:`system`,content:e.system});let i=Oc(e.history??[]);for(let e of Ec(i,Ud))r.push(Hd(e));return e.input.length>0&&r.push({role:`user`,content:Vd(e.input)}),r}function Gd(e){if(e&&e.length!==0)return e.map(e=>({type:`function`,function:{name:e.name,description:e.description,parameters:e.parameters}}))}function Kd(e){return e.replace(/[^A-Za-z0-9_-]/g,`_`).slice(0,64)}function qd(e){if(e)return{type:`json_schema`,json_schema:{name:Kd(e.id),strict:!0,schema:e.jsonSchema}}}function Jd(e){let t=Y(e.cost);if(t===void 0)return;let n=Y(q(e.cost_details)?.upstream_inference_cost);return{usd:t,...n===void 0?{}:{upstreamUsd:n}}}function Yd(e,t){let n=Object.entries(t).flatMap(([t,n])=>{let r=Y(e?.[t]);return r===void 0?[]:[[n,r]]});return n.length>0?Object.fromEntries(n):void 0}function Xd(e,t){let n=Yd(e,{audio_tokens:`audio`,video_tokens:`video`}),r=Yd(t,{image_tokens:`image`,audio_tokens:`audio`});if(n||r)return{...n?{input:n}:{},...r?{output:r}:{}}}function Zd(e){let t=q(e);if(!t)return;let n=q(t.prompt_tokens_details)??q(t.input_tokens_details),r=q(t.completion_tokens_details);return fa({input:Y(t.prompt_tokens)??Y(t.input_tokens),output:Y(t.completion_tokens)??Y(t.output_tokens),thinking:Y(r?.reasoning_tokens),cached:Y(n?.cached_tokens),cacheWrite:Y(n?.cache_write_tokens),cost:Jd(t),byModality:Xd(n,r)})}function Qd(e){let t=J(e.id),n=J(e.model);if(t||n)return{...t?{id:t}:{},...n?{model:n}:{}}}function $d(e){return e.flatMap(e=>Su(e)??[])}function ef(e,t){let n=t.stream!==!1,r=Gd(t.wireTools),i=qd(t.structured),a={model:e.apiId,messages:Wd(t),stream:n,...n?{stream_options:{include_usage:!0}}:{},...t.temperature===void 0?{}:{temperature:t.temperature},...t.maxOutputTokens===void 0?{}:{max_tokens:t.maxOutputTokens},...t.thinking?{reasoning_effort:t.thinking}:{},...i?{response_format:i}:{},...r?{tools:r}:{}};return JSON.parse(JSON.stringify(a))}function tf(e,t){let n=q(e.error);if(!n)return;let r=typeof n.code==`number`?n.code:502,i=We(r);throw new T(t.response&&i===`unsupported`?`unavailable`:i,Ld(e)??JSON.stringify(n))}function nf(e,t){let n=(Array.isArray(e.annotations)?e.annotations:[]).flatMap(e=>{let n=q(q(e)?.url_citation);return typeof n?.url!=`string`||t.cited.has(n.url)?[]:(t.cited.add(n.url),[{title:typeof n.title==`string`&&n.title?n.title:n.url,uri:n.url,type:`web`}])});return n.length?[{type:`citation`,sources:n}]:[]}function rf(e,t){for(let[n,r]of(Array.isArray(e.tool_calls)?e.tool_calls:[]).entries()){let e=q(r),i=q(e?.function),a=typeof e?.index==`number`?e.index:n,o=t.calls.get(a)??{name:``,args:``};typeof e?.id==`string`&&e.id&&(o.id=e.id),typeof i?.name==`string`&&(o.name+=i.name),typeof i?.arguments==`string`&&(o.args+=i.arguments),t.calls.set(a,o)}}function af(e,t,n){let r=[],i=e.reasoning??e.reasoning_content;return typeof i==`string`&&i&&n.summaries!==`none`&&r.push({type:`thought`,text:i}),typeof e.content==`string`&&e.content&&(t.text+=e.content,r.push({type:`text`,text:e.content})),r.push(...nf(e,t)),rf(e,t),r}function of(e,t,n,r){tf(e,t);let i=[],a=_l(t.response,Qd(e));t.response=a.known,a.event&&i.push(a.event);let o=t.tokens?void 0:Zd(e.usage);o&&(t.tokens=!0,i.push({type:`tokens`,tokens:o}));for(let a of Array.isArray(e.choices)?e.choices:[]){let e=q(a),o=q(r?e?.delta:e?.message);o&&i.push(...af(o,t,n)),typeof e?.finish_reason==`string`&&(t.finish=e.finish_reason),typeof e?.native_finish_reason==`string`&&(t.native=e.native_finish_reason)}if(r)for(let e of t.calls.values())i.push(...$d(yl(e)));return i}function sf(e,t){let n=[];for(let[t,r]of e.calls)n.push(...$d(Mc({...r,id:r.id??`call_${t}`},r.args)));let r=ca(e.finish,e.native);if(t.structured&&e.text&&r.kind===`completed`){let t=$d([vl(e.text)]);if(n.push(...t),t[0]?.type===`error`)return n}return n.push({type:`done`,stop:r}),n}async function*cf(e,t){let n=t.input.flatMap(e=>e.type===`text`?[e.text]:[]).join(` `).trim();if(!n)throw new T(`request`,`empty text for speech`);let r=t.speech,i={model:e.apiId,input:n,...r?.format?{response_format:r.format}:{},...r?.voice?{voice:r.voice}:{},...r?.speed===void 0?{}:{speed:r.speed},...r?.style?{instructions:r.style}:{}},a;for await(let t of e.send(i,{stream:!1})){let e=_l(a,Qd(t));a=e.known,e.event&&(yield e.event);let n=typeof t.mime_type==`string`?t.mime_type:``,r=typeof t.data==`string`?lt(t.data):new Uint8Array;if(!r.length)throw new T(`bad_response`,`no audio returned from speech`);let i=ml(n);yield{type:`media`,media:i?{mimeType:`audio/wav`,data:St(hl(r,i))}:{mimeType:Ir(n)||`application/octet-stream`,data:t.data}},yield{type:`done`,stop:{kind:`completed`}}}}var lf=W({id:`openAi`,name:`OpenAI Chat Completions`,description:`The Chat Completions shape that OpenAI and most compatible servers speak.`,endpoints:{text:`/chat/completions`,speech:`/audio/speech`},operationNames:{text:`chat`,speech:`generate_content`},options:_({}),error:e=>Rd(e,`Chat Completions`),create(e){return{async*complete(t){if(e.profileType===`speech`){yield*cf(e,t);return}let n=t.stream!==!1,r={text:``,tokens:!1,cited:new Set,calls:new Map};for await(let i of e.send(ef(e,t),{stream:n}))yield*of(i,r,t,n);yield*sf(r,t)}}}}),uf=Wi({id:`local`,name:`Local`,description:`A server that speaks OpenAI's chat API: Ollama, llama.cpp, vLLM, LM Studio.`,traceName:`openai`,connection:_({baseUrl:zi.describe(`Where the server listens, up to and including /v1, e.g. http://localhost:11434/v1.`)}),key:o().trim().min(1).optional(),authorize:Bi(),serves:e=>[{protocol:lf,baseUrl:e.baseUrl},{protocol:nc,baseUrl:e.baseUrl,url:({path:t})=>{let n=new URL(e.baseUrl);return n.pathname=n.pathname.replace(/\/v1\/?$/,``)||`/`,new URL(t.replace(/^\/+/,``),n).toString()}}]}),df=v().int().nonnegative(),ff=w({model:o().min(1),answers:i(o(),g()),usage:w({input_tokens:df,output_tokens:df,cost:v().nonnegative().optional()}).optional().catch(void 0)}),pf=_({images:S().optional().describe(`Let a decision hold images and box questions. TypeSafe calls this experimental, and a request that uses either is refused without it.`),longContext:S().optional().describe(`Raise the context window from 64k tokens to 262k. TypeSafe calls this slower and less accurate.`)}),mf=`TypeSafe-Danger-Zone-Images`,hf=`TypeSafe-Danger-Zone-Long-Context`,gf=W({id:`systemOne`,name:`System One`,description:`TypeSafe's decision API: questions about a state, answered in one call.`,endpoints:{decision:`/systemone`},operationNames:{decision:`decide`},options:pf,create(e){return{async decide(t){let n=Object.values(t.questions).some(({type:e})=>e===`box`),r=n||t.assets&&Object.keys(t.assets).length>0;if(r&&!e.options.images)throw new T(`unsupported`,D(`provider.decision_images_off`));if(n&&/^jev-1\.13(\.|$)/.test(e.apiId))throw new T(`unsupported`,D(`provider.decision_box_model`,{apiId:e.apiId}));let i={};r&&(i[mf]=`true`),e.options.longContext&&(i[hf]=`true`);let a=I.parse({model:e.apiId,state:t.state,questions:t.questions,...t.assets&&Object.keys(t.assets).length?{assets:yf(t.assets)}:{}});return await _f(`systemOne`,e.send(a,{stream:!1,headers:i}))}}}});async function _f(e,t){for await(let n of t){let t=ff.safeParse(n);if(!t.success)throw new T(`bad_response`,D(`protocol.reply_shape`,{protocol:e,issues:he(t.error)}));let{model:r,answers:i,usage:a}=t.data;return{model:r,answers:i,...a?{usage:{inputTokens:a.input_tokens,outputTokens:a.output_tokens,...a.cost===void 0?{}:{costUsd:a.cost}}}:{}}}throw new T(`bad_response`,D(`provider.decision_failed`))}var vf={"image/png":`png`,"image/jpeg":`jpeg`};function yf(e){return Object.fromEntries(Object.entries(e).map(([e,{mimeType:t,data:n}])=>[e,{type:`image`,format:vf[t],data_base64:n}]))}var bf=W({id:`openRouterDecisions`,name:`OpenRouter Decisions`,description:`OpenRouter's decision API: questions about a state, answered in one call.`,endpoints:{decision:`/alpha/decisions`},operationNames:{decision:`decide`},options:_({}),create(e){return{decide(t){let n=t.assets??{},r=I.parse({model:e.apiId,state:xf(t.state,n),questions:Object.fromEntries(Object.entries(t.questions).map(([e,t])=>[e,{...t,instructions:xf(t.instructions,n),...`criteria`in t&&t.criteria!==void 0?{criteria:xf(t.criteria,n)}:{}}]))});return _f(`openRouterDecisions`,e.send(r,{stream:!1}))}}}});function xf(e,t){if(typeof e==`string`){let n=mo(e,t);if(n.every(e=>typeof e==`string`))return e;let r=n.map(e=>typeof e==`string`?e:Sf(e.asset));return r.length===1?r[0]:r}return Array.isArray(e)?e.map(e=>xf(e,t)):typeof e==`object`&&e?Object.fromEntries(Object.entries(e).map(([e,n])=>[e,xf(n,t)])):e}function Sf({mimeType:e,data:t}){return{type:`image_url`,image_url:{url:`data:${e};base64,${t}`}}}var Cf=`openrouter:image_generation`;function wf(e){return(Array.isArray(e.data)?e.data:[]).flatMap(e=>{let t=q(e),n=J(t?.b64_json),r=J(t?.media_type);return n&&r?[{mimeType:r,data:n}]:[]})}function Tf(e){if(typeof e!=`string`)return;let t=/^data:([^;,]+);base64,(.+)$/s.exec(e);if(t?.[1]&&t[2])return{mimeType:t[1],data:t[2]}}function Ef(e){return(Array.isArray(e.images)?e.images:[]).flatMap(e=>{let t=Tf(q(q(e)?.image_url)?.url);return t?[t]:[]})}function Df(e){return e.filter(e=>e.type===`text`).map(e=>e.type===`text`?e.text:``).join(`
@@ -1,3 +1,3 @@
1
- import{C as e,Cn as t,M as n,Wt as r,Xt as i,h as a,j as o,n as s,p as c,t as l,vn as ee,y as te,z as u}from"./tool-schema-m1KPujBp.js";import{An as d,Cn as ne,Hn as re,Nn as f,Pn as ie,Sn as ae,Wn as oe,an as se,br as p,gr as m,pn as h,yn as g}from"./shaped-data-7q5Be8sp.js";import{a as _,r as v}from"./live-ingress-OuSlQ6q7.js";var ce=[{id:`identity`,profilePath:`identity`,role:`root`,optional:!1,editor:`structural`,label:`Identity`,ownsFields:[`profile.id`,`profile.type`]},{id:`models`,profilePath:`models`,role:`spine`,optional:!1,editor:`structural`,label:`Models`,ownsFields:[`profile.defaultModel`,`profile.allowModelSelect`,`profile.maxSteps`,`providerContinuation`]},{id:`modelBinding`,profilePath:`models.*`,role:`branch`,parent:`models`,optional:!1,editor:`structural`,label:`Model binding`},{id:`decision`,profilePath:`decision`,role:`spine`,optional:!1,editor:`structural`,label:`Decision`,ownsFields:[`inputs`]},{id:`image`,profilePath:`image`,role:`spine`,optional:!1,editor:`structural`,label:`Image`},{id:`speech`,profilePath:`speech`,role:`spine`,optional:!1,editor:`structural`,label:`Speech`},{id:`live`,profilePath:`live`,role:`spine`,optional:!1,editor:`structural`,label:`Live`},{id:`tools`,profilePath:`tools`,role:`spine`,optional:!1,editor:`structural`,label:`Tools`},{id:`toolSpec`,profilePath:`tools.allow`,role:`branch`,parent:`tools`,optional:!0,editor:`structural`,label:`Tool`},{id:`inputs`,profilePath:`inputs`,role:`spine`,optional:!1,editor:`structural`,label:`Inputs`},{id:`outputs`,profilePath:`outputs`,role:`spine`,optional:!0,editor:`structural`,label:`Outputs`},{id:`turnBehaviour`,profilePath:`turnBehaviour`,role:`spine`,optional:!0,editor:`structural`,label:`Turn behaviour`},{id:`guardrails`,profilePath:`guardrails`,role:`spine`,optional:!0,editor:`structural`,label:`Guardrails`},{id:`observability`,profilePath:`observability`,role:`spine`,optional:!0,editor:`structural`,label:`Observability`},{id:`labels`,profilePath:`labels`,role:`spine`,optional:!0,editor:`structural`,label:`Labels`}],le={identity:d,inputs:f(`inputs`).filter(e=>e!==`decision`)},y=ce.map(e=>({...e,profileTypes:le[e.id]??f(e.profilePath)}));function ue(e){return y.find(t=>t.id===e)}function de(e){return e.modelBindings.length>1}function fe(e){return e.modelBindings.some(t=>t.provider!==`local`&&!n(e.providers,t).keySlot)}function b(e,t){let r={provider:t.provider,keySlot:t.keySlot||e.models.key,fallbackKeySlot:t.fallbackKeySlot||e.models.fallbackKey},i=n(e.providers,r);return{...i,given:{keySlot:!!i.keySlot&&!r.keySlot,fallbackKeySlot:!!i.fallbackKeySlot&&!r.fallbackKeySlot}}}function pe(e,t){let n=new Set(e.modelBindings.filter(n=>{let r=b(e,n);return r.keySlot===t||r.fallbackKeySlot===t}).map(e=>e.provider));return e.providers.filter(e=>n.has(e.id))}function me(e){let t=e.efforts.map(({alias:e})=>e.trim()).filter(Boolean);return new Set(t).size>1}function he(e){return e.attachmentsAccept.length>0||e.voiceAccept.length>0}var ge=h,x=[{name:`operationTimeoutMs`,label:`Call timeout`,units:`ms`,isTimer:!0},{name:`connectTimeoutMs`,label:`Connect timeout`,units:`ms`,isTimer:!0},{name:`liveStepTimeoutMs`,label:`Live step timeout`,units:`ms`,isTimer:!0},{name:`maxWireRecordBytes`,label:`Wire record`,units:`bytes`,isTimer:!1},{name:`maxWireResponseBytes`,label:`Wire response`,units:`bytes`,isTimer:!1},{name:`maxEventBytes`,label:`Event`,units:`bytes`,isTimer:!1},{name:`maxStepBytes`,label:`Step`,units:`bytes`,isTimer:!1},{name:`maxStepEvents`,label:`Step events`,units:`events`,isTimer:!1},{name:`maxPendingToolCalls`,label:`Tool calls`,units:`calls`,isTimer:!1}],S=2147483647,C={compactMaxTokens:32e3,compactAt:.75,compactKeep:4},w={"continue.instruction":`turnBehaviour`,"canary.bind_note":`guardrails`,"quota.exhausted":`guardrails`,"repair.default_guidance":`outputs`,"egress.default_repair_guidance":`guardrails`,"egress.refusal":`guardrails`};function T(e){return`${e}-${crypto.randomUUID().slice(0,8)}`}function E(e){return{key:T(`model`),modelId:`fast`,protocol:`openRouterOpenAi`,provider:`openrouter`,apiId:``,options:{},timeoutMs:null,efforts:[],defaultEffort:``,allowEffortSelect:!1,summaries:null,maxOutputTokens:null,temperature:null,builtInTools:[],...e}}var D=`Studio stub tool — returns a fixed result.`;function O(e){return{key:T(`tool`),toolName:`my_tool`,toolType:`function`,description:D,category:`studio`,access:g[0],permission:ne[0],loadTier:ae[0],paths:[`*`],inputJson:l,outputJson:s,...e}}function k(e,t,n){return(!e.description.trim()||e.description===D)&&n?{agentKey:t,description:`Asks ${n} and returns its answer.`}:{agentKey:t}}function A(){return{name:``,kind:`words`,pattern:``,flags:``,words:[]}}function j(){return{key:``,label:``,at:p(m,()=>`ignore`),patterns:[A()],hint:``}}function M(){let e=t(void 0);return{canaryBindNote:``,detect:p(ie,t=>({...e.detect[t]})),sources:Object.fromEntries(re.map(e=>[e,{theorem:!0,patterns:[],hint:``}])),own:[],quotaEnabled:!1,quotaPerDay:null,quotaMessage:``,allow:{ungiven_images:{hosts:[],fromTools:!0},ungiven_links:{hosts:[],fromTools:!0}},innocentNames:[],blockedReplyOnBlock:``,blockedReplyMaxRetries:null,egressRepairGuidance:``,egressRefusal:``,allowPrivateNetworks:!1,allowedHosts:[],allowedSchemes:[],taintAfterRemoteRead:``,taintRemoteDestination:``}}function N(){let e=_({});return{writeTo:c,destination:c,sampleRate:e.sampleRate,include:{...e.include},scrub:{sensitive:e.scrub.sensitive,injection:e.scrub.injection,canary:e.scrub.canary},retainForDays:null,rotateAfterMiB:null,resourceJson:``}}function P(e){return e.map(([e,t])=>({key:T(`criterion`),label:e,text:t}))}function F(){return{contract:`guardrails.tool_call.v1`,maxStateBytes:null,questions:[{key:T(`question`),id:`verdict`,type:`choice`,instructions:`Given what the user asked for and what the call would do, should it run?`,criteria:P([[`allow`,`Safe, and what the user asked for.`],[`flag`,`Probably fine, but unusual or sensitive enough for a person to look first.`],[`block`,`Harmful, or clearly beyond what the user asked for.`]])},{key:T(`question`),id:`risk`,type:`score`,instructions:`How much harm would this call do if it were wrong?`,criteria:P([[``,`Low: reversible, and affects only the user.`],[``,`High: hard to undo, or affects other people or money.`]])}],images:[]}}var I=JSON.stringify({context:`The user asked the agent to tidy up old screenshots on their desktop.`,tool_call:{name:`delete_files`,path:`~/Documents`,recursive:!0},outcome:`Would delete 1,284 files, including tax_return_2025.pdf.`},null,2),L=JSON.stringify(`The user asked to tidy screenshots. The proposed call recursively deletes 1,284 files, including a tax return.`),_e=`To clear your desktop, select the screenshots and move them to the Trash. Empty the Trash to delete them for good.(Screen captures save to the desktop by default. You can change where they go in the Screenshot app's Options menu.(Press Command-Shift-5 to record the screen or capture a window. Recordings are saved as movie files next to your screenshots.(Stacks group desktop files by kind, date or tag, so a cluttered desktop folds into a few piles you can open one at a time.(Deleted files stay in the Trash for 30 days. Drag a file out of the Trash to put it back where it was.(When your disk is almost full, open Storage settings and review the largest files. Old downloads and installers are safe to remove.(Offloading unused apps frees space and keeps their documents. Reinstalling an app brings its data back.(Photos you have backed up can be optimised so the originals live in the cloud and smaller copies stay on the device.(Your plan renews on the same date each month. You can see the next charge under Billing, then Upcoming invoices.(To get a refund, open the invoice and choose Request refund. Charges from the last 14 days are refunded in full.(Update your card under Billing, then Payment methods. The new card is used for the next renewal, not for past invoices.(Annual plans cost two months less than paying monthly. Switching mid-term credits the unused months to the new plan.(Invoices are emailed as PDFs and list your company name and tax number. Edit those details before the invoice is issued.(Turn on two-step verification under Security. You will be asked for a code from your authenticator app each time you sign in on a new device.(If you forget your password, choose Forgot password on the sign-in page. The reset link expires after one hour.(Review signed-in devices under Security and sign out any you don't recognise. This ends their sessions immediately.(Passkeys replace your password with your fingerprint or face. Create one under Security, then Passkeys.(To close your account, export your data first. Closing deletes your workspace after a 30-day grace period.(Share a folder by choosing Share, then entering an email address. Viewers can read; editors can change and delete.(Public links work for anyone who has them. Set an expiry date, or turn the link off to stop sharing at once.(Transfer ownership of a folder before you leave a team, or its contents will be archived with your account.(Lisbon has mild, wet winters and warm, dry summers. Expect highs near 28 °C in August.(The best months for the Algarve coast are May, June and September, when the beaches are warm and the crowds are thin.(Trams in Lisbon climb the steep hills of Alfama and Graça. Line 28 is the famous one, and the busiest.(For a crisp pizza base, preheat the oven and the baking tray together at the highest setting for at least thirty minutes.(Rest steak for five minutes after cooking so the juices settle back into the meat instead of running onto the board.`.split(`(`).join(`
1
+ import{C as e,Cn as t,M as n,Wt as r,Xt as i,h as a,j as o,n as s,p as c,t as l,vn as ee,y as te,z as u}from"./tool-schema-6RWBAqGO.js";import{An as d,Cn as ne,Hn as re,Nn as f,Pn as ie,Sn as ae,Wn as oe,an as se,br as p,gr as m,pn as h,yn as g}from"./shaped-data-7q5Be8sp.js";import{a as _,r as v}from"./live-ingress-OuSlQ6q7.js";var ce=[{id:`identity`,profilePath:`identity`,role:`root`,optional:!1,editor:`structural`,label:`Identity`,ownsFields:[`profile.id`,`profile.type`]},{id:`models`,profilePath:`models`,role:`spine`,optional:!1,editor:`structural`,label:`Models`,ownsFields:[`profile.defaultModel`,`profile.allowModelSelect`,`profile.maxSteps`,`providerContinuation`]},{id:`modelBinding`,profilePath:`models.*`,role:`branch`,parent:`models`,optional:!1,editor:`structural`,label:`Model binding`},{id:`decision`,profilePath:`decision`,role:`spine`,optional:!1,editor:`structural`,label:`Decision`,ownsFields:[`inputs`]},{id:`image`,profilePath:`image`,role:`spine`,optional:!1,editor:`structural`,label:`Image`},{id:`speech`,profilePath:`speech`,role:`spine`,optional:!1,editor:`structural`,label:`Speech`},{id:`live`,profilePath:`live`,role:`spine`,optional:!1,editor:`structural`,label:`Live`},{id:`tools`,profilePath:`tools`,role:`spine`,optional:!1,editor:`structural`,label:`Tools`},{id:`toolSpec`,profilePath:`tools.allow`,role:`branch`,parent:`tools`,optional:!0,editor:`structural`,label:`Tool`},{id:`inputs`,profilePath:`inputs`,role:`spine`,optional:!1,editor:`structural`,label:`Inputs`},{id:`outputs`,profilePath:`outputs`,role:`spine`,optional:!0,editor:`structural`,label:`Outputs`},{id:`turnBehaviour`,profilePath:`turnBehaviour`,role:`spine`,optional:!0,editor:`structural`,label:`Turn behaviour`},{id:`guardrails`,profilePath:`guardrails`,role:`spine`,optional:!0,editor:`structural`,label:`Guardrails`},{id:`observability`,profilePath:`observability`,role:`spine`,optional:!0,editor:`structural`,label:`Observability`},{id:`labels`,profilePath:`labels`,role:`spine`,optional:!0,editor:`structural`,label:`Labels`}],le={identity:d,inputs:f(`inputs`).filter(e=>e!==`decision`)},y=ce.map(e=>({...e,profileTypes:le[e.id]??f(e.profilePath)}));function ue(e){return y.find(t=>t.id===e)}function de(e){return e.modelBindings.length>1}function fe(e){return e.modelBindings.some(t=>t.provider!==`local`&&!n(e.providers,t).keySlot)}function b(e,t){let r={provider:t.provider,keySlot:t.keySlot||e.models.key,fallbackKeySlot:t.fallbackKeySlot||e.models.fallbackKey},i=n(e.providers,r);return{...i,given:{keySlot:!!i.keySlot&&!r.keySlot,fallbackKeySlot:!!i.fallbackKeySlot&&!r.fallbackKeySlot}}}function pe(e,t){let n=new Set(e.modelBindings.filter(n=>{let r=b(e,n);return r.keySlot===t||r.fallbackKeySlot===t}).map(e=>e.provider));return e.providers.filter(e=>n.has(e.id))}function me(e){let t=e.efforts.map(({alias:e})=>e.trim()).filter(Boolean);return new Set(t).size>1}function he(e){return e.attachmentsAccept.length>0||e.voiceAccept.length>0}var ge=h,x=[{name:`operationTimeoutMs`,label:`Call timeout`,units:`ms`,isTimer:!0},{name:`connectTimeoutMs`,label:`Connect timeout`,units:`ms`,isTimer:!0},{name:`liveStepTimeoutMs`,label:`Live step timeout`,units:`ms`,isTimer:!0},{name:`maxWireRecordBytes`,label:`Wire record`,units:`bytes`,isTimer:!1},{name:`maxWireResponseBytes`,label:`Wire response`,units:`bytes`,isTimer:!1},{name:`maxEventBytes`,label:`Event`,units:`bytes`,isTimer:!1},{name:`maxStepBytes`,label:`Step`,units:`bytes`,isTimer:!1},{name:`maxStepEvents`,label:`Step events`,units:`events`,isTimer:!1},{name:`maxPendingToolCalls`,label:`Tool calls`,units:`calls`,isTimer:!1}],S=2147483647,C={compactMaxTokens:32e3,compactAt:.75,compactKeep:4},w={"continue.instruction":`turnBehaviour`,"canary.bind_note":`guardrails`,"quota.exhausted":`guardrails`,"repair.default_guidance":`outputs`,"egress.default_repair_guidance":`guardrails`,"egress.refusal":`guardrails`};function T(e){return`${e}-${crypto.randomUUID().slice(0,8)}`}function E(e){return{key:T(`model`),modelId:`fast`,protocol:`openRouterOpenAi`,provider:`openrouter`,apiId:``,options:{},timeoutMs:null,efforts:[],defaultEffort:``,allowEffortSelect:!1,summaries:null,maxOutputTokens:null,temperature:null,builtInTools:[],...e}}var D=`Studio stub tool — returns a fixed result.`;function O(e){return{key:T(`tool`),toolName:`my_tool`,toolType:`function`,description:D,category:`studio`,access:g[0],permission:ne[0],loadTier:ae[0],paths:[`*`],inputJson:l,outputJson:s,...e}}function k(e,t,n){return(!e.description.trim()||e.description===D)&&n?{agentKey:t,description:`Asks ${n} and returns its answer.`}:{agentKey:t}}function A(){return{name:``,kind:`words`,pattern:``,flags:``,words:[]}}function j(){return{key:``,label:``,at:p(m,()=>`ignore`),patterns:[A()],hint:``}}function M(){let e=t(void 0);return{canaryBindNote:``,detect:p(ie,t=>({...e.detect[t]})),sources:Object.fromEntries(re.map(e=>[e,{theorem:!0,patterns:[],hint:``}])),own:[],quotaEnabled:!1,quotaPerDay:null,quotaMessage:``,allow:{ungiven_images:{hosts:[],fromTools:!0},ungiven_links:{hosts:[],fromTools:!0}},innocentNames:[],blockedReplyOnBlock:``,blockedReplyMaxRetries:null,egressRepairGuidance:``,egressRefusal:``,allowPrivateNetworks:!1,allowedHosts:[],allowedSchemes:[],taintAfterRemoteRead:``,taintRemoteDestination:``}}function N(){let e=_({});return{writeTo:c,destination:c,sampleRate:e.sampleRate,include:{...e.include},scrub:{sensitive:e.scrub.sensitive,injection:e.scrub.injection,canary:e.scrub.canary},retainForDays:null,rotateAfterMiB:null,resourceJson:``}}function P(e){return e.map(([e,t])=>({key:T(`criterion`),label:e,text:t}))}function F(){return{contract:`guardrails.tool_call.v1`,maxStateBytes:null,questions:[{key:T(`question`),id:`verdict`,type:`choice`,instructions:`Given what the user asked for and what the call would do, should it run?`,criteria:P([[`allow`,`Safe, and what the user asked for.`],[`flag`,`Probably fine, but unusual or sensitive enough for a person to look first.`],[`block`,`Harmful, or clearly beyond what the user asked for.`]])},{key:T(`question`),id:`risk`,type:`score`,instructions:`How much harm would this call do if it were wrong?`,criteria:P([[``,`Low: reversible, and affects only the user.`],[``,`High: hard to undo, or affects other people or money.`]])}],images:[]}}var I=JSON.stringify({context:`The user asked the agent to tidy up old screenshots on their desktop.`,tool_call:{name:`delete_files`,path:`~/Documents`,recursive:!0},outcome:`Would delete 1,284 files, including tax_return_2025.pdf.`},null,2),L=JSON.stringify(`The user asked to tidy screenshots. The proposed call recursively deletes 1,284 files, including a tax return.`),_e=`To clear your desktop, select the screenshots and move them to the Trash. Empty the Trash to delete them for good.(Screen captures save to the desktop by default. You can change where they go in the Screenshot app's Options menu.(Press Command-Shift-5 to record the screen or capture a window. Recordings are saved as movie files next to your screenshots.(Stacks group desktop files by kind, date or tag, so a cluttered desktop folds into a few piles you can open one at a time.(Deleted files stay in the Trash for 30 days. Drag a file out of the Trash to put it back where it was.(When your disk is almost full, open Storage settings and review the largest files. Old downloads and installers are safe to remove.(Offloading unused apps frees space and keeps their documents. Reinstalling an app brings its data back.(Photos you have backed up can be optimised so the originals live in the cloud and smaller copies stay on the device.(Your plan renews on the same date each month. You can see the next charge under Billing, then Upcoming invoices.(To get a refund, open the invoice and choose Request refund. Charges from the last 14 days are refunded in full.(Update your card under Billing, then Payment methods. The new card is used for the next renewal, not for past invoices.(Annual plans cost two months less than paying monthly. Switching mid-term credits the unused months to the new plan.(Invoices are emailed as PDFs and list your company name and tax number. Edit those details before the invoice is issued.(Turn on two-step verification under Security. You will be asked for a code from your authenticator app each time you sign in on a new device.(If you forget your password, choose Forgot password on the sign-in page. The reset link expires after one hour.(Review signed-in devices under Security and sign out any you don't recognise. This ends their sessions immediately.(Passkeys replace your password with your fingerprint or face. Create one under Security, then Passkeys.(To close your account, export your data first. Closing deletes your workspace after a 30-day grace period.(Share a folder by choosing Share, then entering an email address. Viewers can read; editors can change and delete.(Public links work for anyone who has them. Set an expiry date, or turn the link off to stop sharing at once.(Transfer ownership of a folder before you leave a team, or its contents will be archived with your account.(Lisbon has mild, wet winters and warm, dry summers. Expect highs near 28 °C in August.(The best months for the Algarve coast are May, June and September, when the beaches are warm and the crowds are thin.(Trams in Lisbon climb the steep hills of Alfama and Graça. Line 28 is the famous one, and the busiest.(For a crisp pizza base, preheat the oven and the baking tray together at the highest setting for at least thirty minutes.(Rest steak for five minutes after cooking so the juices settle back into the meat instead of running onto the board.`.split(`(`).join(`
2
2
 
3
3
  `),ve=`How do I delete every screenshot on my desktop?`;function ye(e,t=`choice`){let n=q(`question`,e.decision.questions.map(e=>e.id),e=>`question_${e}`);return{key:T(`question`),id:n,type:t,instructions:``,criteria:B(t)}}function be(e,t,n){let r=t.replace(/\.[^.]*$/,``).toLowerCase().replace(/[^a-z0-9]+/g,`_`).replace(/^_|_$/g,``)||`image`,i=q(r,e.decision.images.map(e=>e.name),e=>`${r}_${e}`);return{key:T(`image`),name:i,...n}}function xe(e){let t=q(`slot`,e.map(e=>e.name),e=>`slot_${String(e)}`);return{key:T(`slot`),name:t,label:``,choices:[R(),R()]}}function Se(){return{key:T(`condition`),name:``,values:[]}}function R(){return{key:T(`choice`),value:``,description:``}}function z(){return{key:T(`criterion`),label:``,text:``}}function B(e){return e===`noul`||e===`box`?[]:P(e===`choice`?[[`yes`,``],[`no`,``]]:[[``,``],[``,``]])}function Ce(){return{identity:{agentId:``,profileType:``,handle:``,system:``,conditions:[]},included:[`observability`,`labels`],models:{defaultModel:``,allowModelSelect:!1,maxSteps:null,key:``},modelBindings:[],providers:[...e],tools:{t2Loader:``,parallel:!1},toolSpecs:[],inputs:{text:!0,attachmentsAccept:[],voiceAccept:[],maxFiles:null,maxBytes:null,maxTurnBytes:null,limitsByMime:{},slots:[],contextFrom:[],contextMaxChars:null},outputs:{mode:`text`,schemaId:``,schemaJson:``,streamMode:``,streamThoughts:!0,validationEnabled:!1,maxRetries:null,itemRules:{},repairGuidance:``},turnBehaviour:{resumeEnabled:!1,allowContinue:[],autoContinue:[],maxContinues:null,continueInstruction:``,allowSteering:i({type:`text`}),atStepLimit:`stop`},guardrails:M(),observability:N(),image:{aspectRatio:``,resolution:``,mimeType:``,quality:``,background:``,n:null,seed:null,outputCompression:null,includeText:!1,references:[]},speech:{voice:``,style:``,speed:null,format:``},live:{ingressAudio:v(`audio`),ingressVideo:v(`video`),ingressText:v(`text`),voice:``,sessionResumption:!1,greeting:``,resumedPrompt:``,resumedAfterMs:null,contextCompression:!1,compressionTriggerTokens:null,compressionTargetTokens:null,transcriptionInput:!1,transcriptionOutput:!1,vadActivityHandling:``,vadStartSensitivity:``,vadEndSensitivity:``,vadPrefixPaddingMs:null,vadSilenceDurationMs:null},decision:F(),labels:{}}}var we=new Set([`guardrails`]);function V(e,t){return e.profileTypes.includes(t)&&!(t===`decision`&&we.has(e.id))}function H(e){let t=e.identity.profileType;if(!t)return[`identity`];let n=new Set(e.included);return y.filter(e=>e.role!==`branch`&&V(e,t)&&(!e.optional||n.has(e.id))).map(e=>e.id)}function U(e,t){let n=e.identity.profileType;return n!==``&&f(t).includes(n)}function Te(e){return U(e,`identity.system`)&&oe(e.guardrails.detect,`canary_leak`)}function Ee(e){let t=e.identity.profileType;return t!==``&&r.includes(t)}function W(e){let t=e.identity.profileType;return t?y.filter(n=>n.role===`spine`&&n.optional&&V(n,t)&&!e.included.includes(n.id)).map(e=>e.id):[]}function De(e){return{...e,attachmentsAccept:e.attachmentsAccept.filter(e=>ee(se,e)),voiceAccept:[]}}function Oe(e){return{...e,text:!1,attachmentsAccept:[],voiceAccept:e.voiceAccept.length?e.voiceAccept:[`audio/*`]}}function ke(e,t,n){let r=e.modelBindings.find(e=>e.key===t);return r?{...e,models:n.modelId!==void 0&&e.models.defaultModel===r.modelId?{...e.models,defaultModel:n.modelId}:e.models,modelBindings:e.modelBindings.map(e=>e.key===t?{...e,...n}:e)}:e}function G(e,t){if(t.some(t=>t.modelId===e))return e;let[n,...r]=t;return n&&!r.length?n.modelId:``}function Ae(e,t){if(!e.modelBindings.find(e=>e.key===t))return e;let n=e.modelBindings.filter(e=>e.key!==t);return{...e,models:{...e.models,defaultModel:G(e.models.defaultModel,n)},modelBindings:n}}function K(e,t){let n=e.identity.profileType,r=n&&n!==`host`?n:`text`,i=e.modelBindings.map(e=>e.modelId),a=te(r,t),o=q(a.modelId,i,e=>`${a.modelId}${e}`);return E({...a,modelId:o})}function je(e){return O({toolName:q(`my_tool`,e.toolSpecs.map(e=>e.toolName),e=>`my_tool_${e}`)})}function q(e,t,n){let r=new Set(t),i=e;for(let e=2;r.has(i);e++)i=n(e);return i}function Me(e,t,n){if(t===`host`)return{...e,identity:{...e.identity,profileType:t}};let r=e.modelBindings.filter(r=>{let i=o(e.providers,t,r),a=e.providers.find(e=>e.id===r.provider);return u(a,t,r.protocol)&&!Fe(n,t,i)}),i={...e,identity:{...e.identity,profileType:t},modelBindings:r},s=r.length?r:[K(i,n?.start)],c=!e.models.key&&fe({...i,modelBindings:s}),l=t===`speech`&&!e.speech.voice.trim()&&s.some(n=>a(o(e.providers,t,n)));return{...i,inputs:t===`image`?De(e.inputs):t===`transcription`?Oe(e.inputs):e.inputs,...l?{speech:{...e.speech,voice:Ne}}:{},models:{...e.models,defaultModel:G(e.models.defaultModel,s),key:c?Ie:e.models.key},modelBindings:s}}var Ne=`Kore`,Pe=[`text`,`image`,`speech`,`transcription`,`live`,`decision`];function Fe(e,t,n){if(!e)return!1;let r=t=>e.models(t,n.definition).some(e=>e.id===n.apiId.trim());return!r(t)&&Pe.some(e=>e!==t&&r(e))}var Ie=`slot_a`;function Le(e,t){return W(e).includes(t)?{...e,included:[...e.included,t]}:e}function Re(e,t){return{...e,included:e.included.filter(e=>e!==t)}}function J(e){return`modelBinding:${e}`}var Y=`toolSpec:`;function X(e){return`${Y}${e}`}function Z(e){return e.startsWith(Y)?e.slice(9):void 0}var Q=`provider:`;function ze(e){return`${Q}${e}`}function Be(e){return e.startsWith(Q)?e.slice(9):void 0}var Ve=new Map(y.map(e=>[e.id,e.label]));function He(e){return Ve.get(e)??e}function Ue(e,t){let[n,r]=t.split(`:`,2);if(n===`modelBinding`&&r!==void 0)return e.modelBindings.some(e=>e.key===r)?{facet:n,key:r}:void 0;let i=Z(t);if(i!==void 0)return e.toolSpecs.some(e=>e.key===i)?{facet:`toolSpec`,key:i}:void 0;let a=H(e);if(r===void 0&&a.includes(t))return{facet:t}}function We(e,t){return t===`models`?e.modelBindings.map(e=>({id:J(e.key),ref:{facet:`modelBinding`,key:e.key},label:e.modelId.trim()||`Unnamed model`,children:[]})):t===`tools`?$(e.toolSpecs):[]}function $(e){return e.map(e=>({id:X(e.key),ref:{facet:`toolSpec`,key:e.key},label:e.toolName.trim()||`Unnamed tool`,children:[]}))}function Ge(e){let t=H(e).filter(e=>e!==`identity`).map(t=>({id:t,ref:{facet:t},label:He(t),children:We(e,t)}));return{id:`identity`,ref:{facet:`identity`},label:e.identity.agentId.trim()||`Unnamed agent`,children:t}}export{B as A,Te as B,H as C,W as D,q as E,j as F,b as G,Me as H,A as I,he as J,me as K,xe as L,be as M,ye as N,Le as O,K as P,R,U as S,Re as T,Ee as U,Ae as V,ke as W,y as X,pe as Y,ue as Z,S as _,Ge as a,E as b,$ as c,ve as d,_e as f,ge as g,x as h,Ue as i,z as j,Se as k,C as l,w as m,Be as n,Z as o,L as p,de as q,ze as r,X as s,J as t,I as u,k as v,T as w,O as x,Ce as y,je as z};
@@ -1,2 +1,2 @@
1
- import{Ht as e,Kn as t,Vn as n}from"./tool-schema-m1KPujBp.js";import{c as r}from"./host-patterns-F-KZIzkF.js";import{Lr as i,M as a,Vn as o}from"./shaped-data-7q5Be8sp.js";import{I as s}from"./reader-COeSYhdZ.js";import{M as c}from"./browser-connection-B2a2EaIg.js";import{r as l}from"./encode-files-DoLGXgup.js";function u(e,t){let n=typeof t==`string`?t.trim():``;if(!n)throw new r(`request`,`A typed credential must be a non-empty string`);if(e===`bearer`)return{type:`bearer`,token:n};if(e===`api_key`)return{type:`api_key`,key:n};throw new r(`request`,`A '${e}' sign-in takes no typed credential; the host's callback saves it`)}function d(e,t){if(!e)throw new r(`request`,`a typed credential answers only a sign-in gate`);return{slot:e.slot,credential:u(e.authType,t)}}function ee(e,t){if(t!==void 0){if(!Number.isFinite(t)||t<=0)throw new r(`config`,`${e} gateTtlMs must be a positive number of milliseconds; got ${t}.`);return t}}function te(e,t,n){return n!==void 0&&t-e>=n}var f=[`approve`,`deny`,`abandon`];function p(e,t=!1){return e.decision===`approve`?{granted:!0,...e.edited?{edited:e.edited}:{},...t?{signIn:t}:{}}:{granted:!1,cause:e.decision===`deny`?`declined`:`abandoned`,...t?{signIn:t}:{}}}function m(e,t,n){return n!==`session_consent`||e.includes(t)?[...e]:[...e,t]}function ne(e,t,n){let{callId:i,decision:a,input:o,secret:s,page:c}=e;if((o!==void 0||s!==void 0||c!==void 0)&&a!==`approve`)throw new r(`request`,`only an approval takes edited input, a secret, or a page answer (call ${i})`);if(a!==`approve`)return{resume:p({decision:a},t.auth!==void 0),input:t.arguments,sessionPermissions:[...n]};let l=s===void 0?void 0:d(t.auth,s);return{resume:{...p(o===void 0?{decision:a}:{decision:a,edited:{from:t.arguments}},t.auth!==void 0),...t.gateKind?{gateKind:t.gateKind}:{}},input:o??t.arguments,sessionPermissions:m(n,t.name,t.permission),...l?{typed:l}:{},...c?{page:c}:{}}}var re={'"':`"`,"\\":`\\`,"/":`/`,b:`\b`,f:`\f`,n:`
2
- `,r:`\r`,t:` `};function h(e,t){let n=``,r=t+1;for(;r<e.length;){let t=e.charAt(r);if(t===`"`)return{text:n,end:r+1};if(t!==`\\`){n+=t,r++;continue}if(r+1>=e.length)break;let i=e.charAt(r+1);if(i===`u`){let t=e.slice(r+2,r+6);if(t.length<4)break;if(/^[0-9a-fA-F]{4}$/.test(t)){n+=String.fromCharCode(Number.parseInt(t,16)),r+=6;continue}}n+=re[i]??i,r+=2}return{text:n}}function g(e,t){let n=t;for(;/\s/.test(e.charAt(n));)n++;return n}function ie(e,t){if(e.charAt(t)===`"`){let n=h(e,t);return n.end===void 0?void 0:_(e,t,n.end)}let n=0;for(let r=t;r<e.length;r++){let i=e.charAt(r);if(i===`"`){let t=h(e,r).end;if(t===void 0)return;r=t-1}else if(i===`{`||i===`[`)n++;else if(i===`}`||i===`]`){if(n===0)return _(e,t,r);if(n--,n===0)return _(e,t,r+1)}else if(i===`,`&&n===0)return _(e,t,r)}}function _(e,t,n){try{return{value:JSON.parse(e.slice(t,n)),end:n}}catch{return}}function v(e){let t={},n=g(e,0);if(e.charAt(n)!==`{`)return t;for(n++;;){if(n=g(e,n),e.charAt(n)===`,`&&(n=g(e,n+1)),e.charAt(n)!==`"`)return t;let r=h(e,n);if(r.end===void 0||(n=g(e,r.end),e.charAt(n)!==`:`)||(n=g(e,n+1),n>=e.length))return t;let i=ie(e,n);if(!i)return e.charAt(n)===`"`&&(t[r.text]=h(e,n).text),t;t[r.text]=i.value,n=i.end}}function y(e,t){if(t.phase===void 0)return{name:t.name,callId:t.callId,...t.operationId?{operationId:t.operationId}:{},arguments:t.arguments,...t.reasoning?{reasoning:t.reasoning}:{},...t.stepId?{stepId:t.stepId}:{},artifacts:[]};if(e===void 0)throw new r(`bad_response`,`Tool event '${t.phase}' for call '${t.callId}' arrived before the call.`);if(e.callId!==t.callId||e.name!==t.name)throw new r(`bad_response`,i(`error.bad_response`));switch(t.phase){case`running`:{let{endedAt:n,outputDraft:r,...i}=e;return{...i,state:t,startedAt:t.at,...t.edited?{edited:t.edited}:{},...t.activity?{activity:t.activity}:{}}}case`complete`:case`error`:return{...b(e),state:t,endedAt:t.at,...t.activityPast?{activityPast:t.activityPast}:{}};case`cancel`:case`gate`:case`background`:return{...b(e),state:t,endedAt:t.at};case`draft`:return{...e,outputDraft:(e.outputDraft??``)+t.text};case`artifact`:return{...e,artifacts:[...e.artifacts,t.artifact]};case`progress`:return se(e,t.data);case`dispatch`:case`trace`:case`warning`:return e}}function b(e){let{outputDraft:t,...n}=e;return n}function x(e,t){return{arguments:{},artifacts:[],...e,name:t.name,callId:t.callId,draft:(e?.draft??``)+t.text}}function S(e,t){if(t.type===`tool_draft`){e.set(t.callId,x(e.get(t.callId),t));return}let{tool:n}=t,r=n.operationId??n.callId;n.phase===void 0&&e.get(n.callId)?.draft!==void 0&&e.delete(n.callId),e.set(r,y(e.get(r),n))}function ae(e){let t=new Map;for(let n of e)(n.type===`tool_draft`||n.type===`tool`)&&S(t,n);return[...t.values()]}function oe(e){if(typeof e!=`object`||!e||!(`agent`in e)||!(`event`in e))return;let{event:n}=e;if(n?.type!==`tool`&&n?.type!==`tool_draft`)return;let r=t.safeParse(n);return r.success?r.data:void 0}function se(e,t){let n=oe(t),r=n&&ce(e.steps??[],n);return r?{...e,steps:r}:e}function ce(e,t){let n=new Map(e.map(e=>[e.operationId??e.callId,e]));if(t.type===`tool`&&t.tool.phase!==void 0){let e=n.get(t.tool.operationId??t.tool.callId);if(e?.callId!==t.tool.callId||e.name!==t.tool.name)return}return S(n,t),[...n.values()]}function le(e){return(e.state?.phase===`gate`?e.state.gate.preparedArguments:void 0)??e.edited?.to??e.arguments}function ue(e,t){return e.type!==`tool`||e.tool.callId!==t?!1:e.tool.phase===`complete`||e.tool.phase===`error`||e.tool.phase===`background`}var de={avif:`image/avif`,gif:`image/gif`,heic:`image/heic`,heif:`image/heif`,jpeg:`image/jpeg`,jpg:`image/jpeg`,png:`image/png`,svg:`image/svg+xml`,webp:`image/webp`,mp4:`video/mp4`,webm:`video/webm`,mov:`video/quicktime`,ogv:`video/ogg`,mp3:`audio/mpeg`,m4a:`audio/mp4`,ogg:`audio/ogg`,wav:`audio/wav`};function fe(e){let t=e.split(`/`).pop()??e,n=t.lastIndexOf(`.`);return n<=0||n===t.length-1?void 0:de[t.slice(n+1).toLowerCase()]}function pe(e){let t=e.trim();if(t.length===0)return;let n;try{n=new URL(t)}catch{return}if(n.protocol!==`http:`&&n.protocol!==`https:`)return;let r=fe(n.pathname);if(r)return{url:n.href,mimeType:r}}var me=/^(.*)\/thumb(\/.+\/([^/]+))\/(\d+)px-\3(?:\.[a-z0-9]+)?$/i;function he(e){let t=new URL(e),n=t.hostname.split(`.`).slice(-2).join(`.`);for(let e of[...t.searchParams.keys()])e.startsWith(`utm_`)&&t.searchParams.delete(e);let r=me.exec(t.pathname);return{key:`${n}${r?`${r[1]}${r[2]}`:t.pathname}${t.search}`,width:r?Number(r[4]):1/0}}function ge(e){let t=new Map,n=[],r=e=>{if(typeof e==`string`){let r=pe(e);if(!r)return;let i=he(r.url),a=t.get(i.key);if(!a){t.set(i.key,{index:n.length,largest:i.width,smallest:i.width}),n.push(r);return}let o=n[a.index];i.width>a.largest?(a.largest=i.width,n[a.index]={...o,url:r.url,previewUrl:o.previewUrl??o.url}):i.width<a.smallest&&(a.smallest=i.width,n[a.index]={...o,previewUrl:r.url})}else if(Array.isArray(e))for(let t of e)r(t);else if(typeof e==`object`&&e)for(let t of Object.values(e))r(t)};return r(e),n}var C=0;function w(e){return e===`user`?`user-${globalThis.crypto.randomUUID()}`:(C+=1,`${e}-${String(C)}`)}function T(e,t){return e?.kind===t}function E(e,t,n,r){let i=e.at(-1);T(i,t)?i.text+=n:e.push({id:w(r),kind:t,text:n})}function D(e,t){let n=e.at(-1),r=n?.kind===`text`||n?.kind===`thought`;e.splice(r?e.length-1:e.length,0,t)}function O(e,t){return e.find(e=>e.kind===`tool`&&e.id===t)}function k(e,t){let n=`tool-${t.operationId??t.callId}`,r=O(e,n),i=y(r?.tool,t);if(r){r.tool=i;return}let a=t.phase===void 0?O(e,`tool-${t.callId}`):void 0;a?.tool.draft===void 0?e.push({id:n,kind:`tool`,tool:i}):(a.id=n,a.tool=i)}function A(e,t){let n=`tool-${t.callId}`,r=O(e,n),i=x(r?.tool,t);r?r.tool=i:e.push({id:n,kind:`tool`,tool:i})}function j(e){return e.findLast(e=>e.kind===`structured`&&e.draft!==void 0)}function M(e,t,n){let r=j(e),i=(r?.draft??``)+t;r?(r.draft=i,r.value=v(i)):e.push({id:w(n),kind:`structured`,value:v(i),draft:i})}function N(e,t,n){let r=j(e);r?(r.value=t,delete r.draft):e.push({id:w(n),kind:`structured`,value:t})}function P(e,t){return e.type===t.type?e.placeId&&t.placeId?e.placeId===t.placeId:e.uri===t.uri:!1}function F(e,t,n){let r=e.find(e=>e.kind===`citation`&&e.callId===t.callId),i=r?[...r.sources]:[];for(let e of t.sources)i.some(t=>P(t,e))||i.push(e);r?r.sources=i:e.push({id:w(n),kind:`citation`,sources:i,...t.callId===void 0?{}:{callId:t.callId}})}function I(e,t,n,r){if(t.phase===`complete`&&t.output!==void 0)for(let i of ge(t.output))r.has(i.url)||(r.add(i.url),e.push({id:w(n),kind:`media`,mimeType:i.mimeType,url:i.url,...i.previewUrl?{previewUrl:i.previewUrl}:{}}))}function L(e,t){return e.messages.flatMap(e=>{if(e.role!==`user`)return[];let n=e.parts??[],r=[e.content??``,...n.map(e=>`text`in e?e.text:``)].join(``).trim();return[...r?[{id:w(t),kind:`user-text`,text:r}]:[],...n.flatMap(e=>`text`in e?[]:[{id:w(t),kind:e.type===`audio`?`user-voice`:`user-attachment`,name:e.mimeType,mimeType:e.mimeType,...`data`in e?{sizeBytes:Math.floor(e.data.length*3/4),data:e.data}:{sizeBytes:0}}])]})}function R(e,t=`user`){let n=[],r=e.text?.trim();r&&n.push({id:w(t),kind:`user-text`,text:r});for(let r of e.attachments??[])n.push({id:w(t),kind:`user-attachment`,name:r.name,mimeType:r.mimeType,sizeBytes:r.sizeBytes,...r.data===void 0?{}:{data:r.data}});for(let r of e.voice??[])n.push({id:w(t),kind:`user-voice`,name:r.name,mimeType:r.mimeType,sizeBytes:r.sizeBytes,...r.data===void 0?{}:{data:r.data}});return n}function _e(e,t){switch(e.type){case`media`:return e.media?{id:w(t),kind:`media`,mimeType:e.media.mimeType,data:e.media.data}:void 0;case`grounding`:return{id:w(t),kind:`grounding`,grounding:e.grounding};case`evidence`:return{id:w(t),kind:`evidence`,evidence:e.evidence};case`error`:return e.error?{id:w(t),kind:`error`,message:e.error}:void 0;case`done`:return{id:w(t),kind:`turn-done`,stop:e.stop,tokens:e.tokens,interactionId:e.interactionId,compaction:e.compaction!==void 0};default:return}}function ve(e,t,n){if(t.phase===`complete`)for(let r of t.parts??[])r.type!==`text`&&e.push({id:w(n),kind:`media`,mimeType:r.mimeType,...`data`in r?{data:r.data}:{url:r.uri}})}function z(e,t={}){let r=t.idPrefix??`turn`,i=t.showThoughts??!0;C=0;let a=[],o=new Set;for(let t of n(e))switch(t.type){case`thought`:i&&t.text&&E(a,`thought`,t.text,r);break;case`text`:t.text&&E(a,`text`,t.text,r);break;case`tool_draft`:A(a,t);break;case`tool`:k(a,t.tool),I(a,t.tool,r,o),ve(a,t.tool,r);break;case`structured_draft`:M(a,t.text,r);break;case`structured`:N(a,t.structured,r);break;case`citation`:F(a,t,r);break;case`guardrail`:D(a,{id:w(r),kind:`guardrail`,guardrail:t.guardrail});break;case`stage`:for(let e of t.injected??[])a.push(...L(e,r));break;default:{let e=_e(t,r);e&&a.push(e)}}return a}function ye(e,t,n={}){return[...R(e,`user`),...z(t,n)]}function be(e){if(!e)return o;let{detect:t,patterns:n}=e;if(!n)return t;let r=Object.fromEntries(Object.entries(n).map(([e,{theorem:t}])=>[e,{theorem:t,matchers:[]}]));return{...t,sources:r}}function xe(e,t){if(e.text===void 0)return e;let n=a(e.text,`user`,be(t));return{...e,text:n.text??e.text}}function B(e,t,n){let r=s(e,t);if(!r.ok)return{ok:!1,issues:r.issues};let i=xe(t,n);return{ok:!0,draft:i,blocks:R(i)}}function V(e,t){if(t)return e.models[t]}function H(e){return!!(e.allowModelSelect&&Object.keys(e.models).length>=2)}function U(e,t){let n=V(e,t);return n?.allowEffortSelect?Object.keys(n.efforts??{}).length>=2:!1}function W(e,t){let n=V(e,t);if(!n?.efforts)return;let r=n.defaultEffort?.trim();return r&&n.efforts[r]?r:Object.keys(n.efforts)[0]}function Se(e){return H(e)?Object.entries(e.models).map(([e,t])=>({id:e,label:t.apiId})):[]}function Ce(e,t){if(!U(e,t))return[];let n=V(e,t);return n?.efforts?Object.entries(n.efforts).map(([e,t])=>({alias:e,level:t})):[]}function G(e){let t=new Set;for(let n of e)if(n.type===`tool`&&n.tool.phase===`complete`)for(let e of c(n.tool.output)??[])t.add(e);return[...t]}function K(t){let n=e(t,e=>e.type===`done`&&e.tools!==void 0);return n?.type===`done`?n.tools:void 0}function we(e){let t=K(e)?.visible??[];return[...new Set([...t,...G(e)])]}function q(e){return e?.streaming?.streamThoughts!==!1}function J(e){return e.defaultModel??Object.keys(e.models)[0]}function Te(e,t,n){let r=t.model!==void 0&&Object.hasOwn(e.models,t.model)&&(n===void 0||t.model!==J(n))?t.model:J(e),i=r===void 0?void 0:e.models[r]?.efforts;return{model:r,effort:r===t.model&&t.effort!==void 0&&i!==void 0&&Object.hasOwn(i,t.effort)&&(n===void 0||t.effort!==W(n,r))?t.effort:W(e,r)}}function Y(e){if(!e.operationId)throw new r(`request`,i(`session.gate_expired`));return e.operationId}function Ee(e,t){return t.selectedModel??J(e)}function X(e,t,n){let r=t.selectedEffort;if(!n||!Object.hasOwn(e.models,n))return r;let i=e.models[n];return i.allowEffortSelect?r??i.defaultEffort:r===W(e,n)?void 0:r}function Z(e,t){let n=Ee(e,t),r=e.allowModelSelect||n!==J(e)?n:void 0,i=X(e,t,n);return{...r?{model:r}:{},...i?{effort:i}:{}}}function De(e,t,n){return{name:n.name,input:n.input,...n.gateKind?{gateKind:n.gateKind}:{},sessionPermissions:n.sessionPermissions??t.sessionPermissions,...t.toolSnapshot?{snapshot:t.toolSnapshot}:{},...t.promotedToolIds.length?{promoted:[...t.promotedToolIds]}:{},...Z(e,t)}}function Q(e){return{...e.conversation?{conversation:e.conversation}:{},...e.turnId?{turnId:e.turnId}:{}}}function Oe(e,t,n,r={}){let i=(r.walkAway?.calls??[]).map(e=>({callId:e.callId,operationId:Y(e)}));return{...Q(r),...Z(e,t),input:n,...i.length?{abandon:i}:{},replay:{sessionPermissions:t.sessionPermissions}}}function ke(e,t,n,r={}){return{...Q(r),gateId:n.gateId,operationId:n.operationId,decision:n.decision,...n.secret===void 0?{}:{secret:n.secret},...n.page===void 0?{}:{page:n.page},replay:De(e,t,{...n,gateKind:n.gateKind??(t.gatedTool?.callId===n.gateId?t.gatedTool.gateKind:void 0)})}}function $(e,t){return B(e.inputs,t,e.guardrails)}function Ae(e,t,n,r=[]){return $(e,{...t.trim()?{text:t}:{},...n.length?{attachments:l(n)}:{},...r.length?{voice:l(r)}:{}})}function je(e,t){return z(t,{showThoughts:q(e.outputs)})}export{ae as C,ee as D,te as E,p as O,le as S,ne as T,B as _,Ae as a,y as b,q as c,K as d,W as f,H as g,Se as h,Y as i,m as k,G as l,Ce as m,Oe as n,$ as o,U as p,je as r,Te as s,ke as t,we as u,ye as v,f as w,ue as x,z as y};
1
+ import{Ht as e,Kn as t,Vn as n}from"./tool-schema-6RWBAqGO.js";import{c as r}from"./host-patterns-F-KZIzkF.js";import{Lr as i,M as a,Vn as o}from"./shaped-data-7q5Be8sp.js";import{I as s}from"./reader-747-Cvu8.js";import{M as c}from"./browser-connection-CuWeoI9s.js";import{r as l}from"./encode-files-DoLGXgup.js";function u(e,t){let n=typeof t==`string`?t.trim():``;if(!n)throw new r(`request`,`A typed credential must be a non-empty string`);if(e===`bearer`)return{type:`bearer`,token:n};if(e===`api_key`)return{type:`api_key`,key:n};throw new r(`request`,`A '${e}' sign-in takes no typed credential; the host's callback saves it`)}function d(e,t){if(!e)throw new r(`request`,`a typed credential answers only a sign-in gate`);return{slot:e.slot,credential:u(e.authType,t)}}function ee(e,t){if(t!==void 0){if(!Number.isFinite(t)||t<=0)throw new r(`config`,`${e} gateTtlMs must be a positive number of milliseconds; got ${t}.`);return t}}function te(e,t,n){return n!==void 0&&t-e>=n}var f=[`approve`,`deny`,`abandon`];function p(e,t=!1){return e.decision===`approve`?{granted:!0,...e.edited?{edited:e.edited}:{},...t?{signIn:t}:{}}:{granted:!1,cause:e.decision===`deny`?`declined`:`abandoned`,...t?{signIn:t}:{}}}function m(e,t,n){return n!==`session_consent`||e.includes(t)?[...e]:[...e,t]}function ne(e,t,n){let{callId:i,decision:a,input:o,secret:s,page:c}=e;if((o!==void 0||s!==void 0||c!==void 0)&&a!==`approve`)throw new r(`request`,`only an approval takes edited input, a secret, or a page answer (call ${i})`);if(a!==`approve`)return{resume:p({decision:a},t.auth!==void 0),input:t.arguments,sessionPermissions:[...n]};let l=s===void 0?void 0:d(t.auth,s);return{resume:{...p(o===void 0?{decision:a}:{decision:a,edited:{from:t.arguments}},t.auth!==void 0),...t.gateKind?{gateKind:t.gateKind}:{}},input:o??t.arguments,sessionPermissions:m(n,t.name,t.permission),...l?{typed:l}:{},...c?{page:c}:{}}}var re={'"':`"`,"\\":`\\`,"/":`/`,b:`\b`,f:`\f`,n:`
2
+ `,r:`\r`,t:` `};function h(e,t){let n=``,r=t+1;for(;r<e.length;){let t=e.charAt(r);if(t===`"`)return{text:n,end:r+1};if(t!==`\\`){n+=t,r++;continue}if(r+1>=e.length)break;let i=e.charAt(r+1);if(i===`u`){let t=e.slice(r+2,r+6);if(t.length<4)break;if(/^[0-9a-fA-F]{4}$/.test(t)){n+=String.fromCharCode(Number.parseInt(t,16)),r+=6;continue}}n+=re[i]??i,r+=2}return{text:n}}function g(e,t){let n=t;for(;/\s/.test(e.charAt(n));)n++;return n}function ie(e,t){if(e.charAt(t)===`"`){let n=h(e,t);return n.end===void 0?void 0:_(e,t,n.end)}let n=0;for(let r=t;r<e.length;r++){let i=e.charAt(r);if(i===`"`){let t=h(e,r).end;if(t===void 0)return;r=t-1}else if(i===`{`||i===`[`)n++;else if(i===`}`||i===`]`){if(n===0)return _(e,t,r);if(n--,n===0)return _(e,t,r+1)}else if(i===`,`&&n===0)return _(e,t,r)}}function _(e,t,n){try{return{value:JSON.parse(e.slice(t,n)),end:n}}catch{return}}function v(e){let t={},n=g(e,0);if(e.charAt(n)!==`{`)return t;for(n++;;){if(n=g(e,n),e.charAt(n)===`,`&&(n=g(e,n+1)),e.charAt(n)!==`"`)return t;let r=h(e,n);if(r.end===void 0||(n=g(e,r.end),e.charAt(n)!==`:`)||(n=g(e,n+1),n>=e.length))return t;let i=ie(e,n);if(!i)return e.charAt(n)===`"`&&(t[r.text]=h(e,n).text),t;t[r.text]=i.value,n=i.end}}function y(e,t){if(t.phase===void 0)return{name:t.name,callId:t.callId,...t.operationId?{operationId:t.operationId}:{},arguments:t.arguments,...t.reasoning?{reasoning:t.reasoning}:{},...t.stepId?{stepId:t.stepId}:{},artifacts:[]};if(e===void 0)throw new r(`bad_response`,`Tool event '${t.phase}' for call '${t.callId}' arrived before the call.`);if(e.callId!==t.callId||e.name!==t.name)throw new r(`bad_response`,i(`error.bad_response`));switch(t.phase){case`running`:{let{endedAt:n,outputDraft:r,...i}=e;return{...i,state:t,startedAt:t.at,...t.edited?{edited:t.edited}:{},...t.activity?{activity:t.activity}:{}}}case`complete`:case`error`:return{...b(e),state:t,endedAt:t.at,...t.activityPast?{activityPast:t.activityPast}:{}};case`cancel`:case`gate`:case`background`:return{...b(e),state:t,endedAt:t.at};case`draft`:return{...e,outputDraft:(e.outputDraft??``)+t.text};case`artifact`:return{...e,artifacts:[...e.artifacts,t.artifact]};case`progress`:return se(e,t.data);case`dispatch`:case`trace`:case`warning`:return e}}function b(e){let{outputDraft:t,...n}=e;return n}function x(e,t){return{arguments:{},artifacts:[],...e,name:t.name,callId:t.callId,draft:(e?.draft??``)+t.text}}function S(e,t){if(t.type===`tool_draft`){e.set(t.callId,x(e.get(t.callId),t));return}let{tool:n}=t,r=n.operationId??n.callId;n.phase===void 0&&e.get(n.callId)?.draft!==void 0&&e.delete(n.callId),e.set(r,y(e.get(r),n))}function ae(e){let t=new Map;for(let n of e)(n.type===`tool_draft`||n.type===`tool`)&&S(t,n);return[...t.values()]}function oe(e){if(typeof e!=`object`||!e||!(`agent`in e)||!(`event`in e))return;let{event:n}=e;if(n?.type!==`tool`&&n?.type!==`tool_draft`)return;let r=t.safeParse(n);return r.success?r.data:void 0}function se(e,t){let n=oe(t),r=n&&ce(e.steps??[],n);return r?{...e,steps:r}:e}function ce(e,t){let n=new Map(e.map(e=>[e.operationId??e.callId,e]));if(t.type===`tool`&&t.tool.phase!==void 0){let e=n.get(t.tool.operationId??t.tool.callId);if(e?.callId!==t.tool.callId||e.name!==t.tool.name)return}return S(n,t),[...n.values()]}function le(e){return(e.state?.phase===`gate`?e.state.gate.preparedArguments:void 0)??e.edited?.to??e.arguments}function ue(e,t){return e.type!==`tool`||e.tool.callId!==t?!1:e.tool.phase===`complete`||e.tool.phase===`error`||e.tool.phase===`background`}var de={avif:`image/avif`,gif:`image/gif`,heic:`image/heic`,heif:`image/heif`,jpeg:`image/jpeg`,jpg:`image/jpeg`,png:`image/png`,svg:`image/svg+xml`,webp:`image/webp`,mp4:`video/mp4`,webm:`video/webm`,mov:`video/quicktime`,ogv:`video/ogg`,mp3:`audio/mpeg`,m4a:`audio/mp4`,ogg:`audio/ogg`,wav:`audio/wav`};function fe(e){let t=e.split(`/`).pop()??e,n=t.lastIndexOf(`.`);return n<=0||n===t.length-1?void 0:de[t.slice(n+1).toLowerCase()]}function pe(e){let t=e.trim();if(t.length===0)return;let n;try{n=new URL(t)}catch{return}if(n.protocol!==`http:`&&n.protocol!==`https:`)return;let r=fe(n.pathname);if(r)return{url:n.href,mimeType:r}}var me=/^(.*)\/thumb(\/.+\/([^/]+))\/(\d+)px-\3(?:\.[a-z0-9]+)?$/i;function he(e){let t=new URL(e),n=t.hostname.split(`.`).slice(-2).join(`.`);for(let e of[...t.searchParams.keys()])e.startsWith(`utm_`)&&t.searchParams.delete(e);let r=me.exec(t.pathname);return{key:`${n}${r?`${r[1]}${r[2]}`:t.pathname}${t.search}`,width:r?Number(r[4]):1/0}}function ge(e){let t=new Map,n=[],r=e=>{if(typeof e==`string`){let r=pe(e);if(!r)return;let i=he(r.url),a=t.get(i.key);if(!a){t.set(i.key,{index:n.length,largest:i.width,smallest:i.width}),n.push(r);return}let o=n[a.index];i.width>a.largest?(a.largest=i.width,n[a.index]={...o,url:r.url,previewUrl:o.previewUrl??o.url}):i.width<a.smallest&&(a.smallest=i.width,n[a.index]={...o,previewUrl:r.url})}else if(Array.isArray(e))for(let t of e)r(t);else if(typeof e==`object`&&e)for(let t of Object.values(e))r(t)};return r(e),n}var C=0;function w(e){return e===`user`?`user-${globalThis.crypto.randomUUID()}`:(C+=1,`${e}-${String(C)}`)}function T(e,t){return e?.kind===t}function E(e,t,n,r){let i=e.at(-1);T(i,t)?i.text+=n:e.push({id:w(r),kind:t,text:n})}function D(e,t){let n=e.at(-1),r=n?.kind===`text`||n?.kind===`thought`;e.splice(r?e.length-1:e.length,0,t)}function O(e,t){return e.find(e=>e.kind===`tool`&&e.id===t)}function k(e,t){let n=`tool-${t.operationId??t.callId}`,r=O(e,n),i=y(r?.tool,t);if(r){r.tool=i;return}let a=t.phase===void 0?O(e,`tool-${t.callId}`):void 0;a?.tool.draft===void 0?e.push({id:n,kind:`tool`,tool:i}):(a.id=n,a.tool=i)}function A(e,t){let n=`tool-${t.callId}`,r=O(e,n),i=x(r?.tool,t);r?r.tool=i:e.push({id:n,kind:`tool`,tool:i})}function j(e){return e.findLast(e=>e.kind===`structured`&&e.draft!==void 0)}function M(e,t,n){let r=j(e),i=(r?.draft??``)+t;r?(r.draft=i,r.value=v(i)):e.push({id:w(n),kind:`structured`,value:v(i),draft:i})}function N(e,t,n){let r=j(e);r?(r.value=t,delete r.draft):e.push({id:w(n),kind:`structured`,value:t})}function P(e,t){return e.type===t.type?e.placeId&&t.placeId?e.placeId===t.placeId:e.uri===t.uri:!1}function F(e,t,n){let r=e.find(e=>e.kind===`citation`&&e.callId===t.callId),i=r?[...r.sources]:[];for(let e of t.sources)i.some(t=>P(t,e))||i.push(e);r?r.sources=i:e.push({id:w(n),kind:`citation`,sources:i,...t.callId===void 0?{}:{callId:t.callId}})}function I(e,t,n,r){if(t.phase===`complete`&&t.output!==void 0)for(let i of ge(t.output))r.has(i.url)||(r.add(i.url),e.push({id:w(n),kind:`media`,mimeType:i.mimeType,url:i.url,...i.previewUrl?{previewUrl:i.previewUrl}:{}}))}function L(e,t){return e.messages.flatMap(e=>{if(e.role!==`user`)return[];let n=e.parts??[],r=[e.content??``,...n.map(e=>`text`in e?e.text:``)].join(``).trim();return[...r?[{id:w(t),kind:`user-text`,text:r}]:[],...n.flatMap(e=>`text`in e?[]:[{id:w(t),kind:e.type===`audio`?`user-voice`:`user-attachment`,name:e.mimeType,mimeType:e.mimeType,...`data`in e?{sizeBytes:Math.floor(e.data.length*3/4),data:e.data}:{sizeBytes:0}}])]})}function R(e,t=`user`){let n=[],r=e.text?.trim();r&&n.push({id:w(t),kind:`user-text`,text:r});for(let r of e.attachments??[])n.push({id:w(t),kind:`user-attachment`,name:r.name,mimeType:r.mimeType,sizeBytes:r.sizeBytes,...r.data===void 0?{}:{data:r.data}});for(let r of e.voice??[])n.push({id:w(t),kind:`user-voice`,name:r.name,mimeType:r.mimeType,sizeBytes:r.sizeBytes,...r.data===void 0?{}:{data:r.data}});return n}function _e(e,t){switch(e.type){case`media`:return e.media?{id:w(t),kind:`media`,mimeType:e.media.mimeType,data:e.media.data}:void 0;case`grounding`:return{id:w(t),kind:`grounding`,grounding:e.grounding};case`evidence`:return{id:w(t),kind:`evidence`,evidence:e.evidence};case`error`:return e.error?{id:w(t),kind:`error`,message:e.error}:void 0;case`done`:return{id:w(t),kind:`turn-done`,stop:e.stop,tokens:e.tokens,interactionId:e.interactionId,compaction:e.compaction!==void 0};default:return}}function ve(e,t,n){if(t.phase===`complete`)for(let r of t.parts??[])r.type!==`text`&&e.push({id:w(n),kind:`media`,mimeType:r.mimeType,...`data`in r?{data:r.data}:{url:r.uri}})}function z(e,t={}){let r=t.idPrefix??`turn`,i=t.showThoughts??!0;C=0;let a=[],o=new Set;for(let t of n(e))switch(t.type){case`thought`:i&&t.text&&E(a,`thought`,t.text,r);break;case`text`:t.text&&E(a,`text`,t.text,r);break;case`tool_draft`:A(a,t);break;case`tool`:k(a,t.tool),I(a,t.tool,r,o),ve(a,t.tool,r);break;case`structured_draft`:M(a,t.text,r);break;case`structured`:N(a,t.structured,r);break;case`citation`:F(a,t,r);break;case`guardrail`:D(a,{id:w(r),kind:`guardrail`,guardrail:t.guardrail});break;case`stage`:for(let e of t.injected??[])a.push(...L(e,r));break;default:{let e=_e(t,r);e&&a.push(e)}}return a}function ye(e,t,n={}){return[...R(e,`user`),...z(t,n)]}function be(e){if(!e)return o;let{detect:t,patterns:n}=e;if(!n)return t;let r=Object.fromEntries(Object.entries(n).map(([e,{theorem:t}])=>[e,{theorem:t,matchers:[]}]));return{...t,sources:r}}function xe(e,t){if(e.text===void 0)return e;let n=a(e.text,`user`,be(t));return{...e,text:n.text??e.text}}function B(e,t,n){let r=s(e,t);if(!r.ok)return{ok:!1,issues:r.issues};let i=xe(t,n);return{ok:!0,draft:i,blocks:R(i)}}function V(e,t){if(t)return e.models[t]}function H(e){return!!(e.allowModelSelect&&Object.keys(e.models).length>=2)}function U(e,t){let n=V(e,t);return n?.allowEffortSelect?Object.keys(n.efforts??{}).length>=2:!1}function W(e,t){let n=V(e,t);if(!n?.efforts)return;let r=n.defaultEffort?.trim();return r&&n.efforts[r]?r:Object.keys(n.efforts)[0]}function Se(e){return H(e)?Object.entries(e.models).map(([e,t])=>({id:e,label:t.apiId})):[]}function Ce(e,t){if(!U(e,t))return[];let n=V(e,t);return n?.efforts?Object.entries(n.efforts).map(([e,t])=>({alias:e,level:t})):[]}function G(e){let t=new Set;for(let n of e)if(n.type===`tool`&&n.tool.phase===`complete`)for(let e of c(n.tool.output)??[])t.add(e);return[...t]}function K(t){let n=e(t,e=>e.type===`done`&&e.tools!==void 0);return n?.type===`done`?n.tools:void 0}function we(t){let n=K(t)?.visible??[],r=e(t,e=>e.type===`done`&&e.steps!==void 0);return{promoted:[...new Set([...n,...G(t)])],stepsTaken:r?.type===`done`?r.steps??0:0}}function q(e){return e?.streaming?.streamThoughts!==!1}function J(e){return e.defaultModel??Object.keys(e.models)[0]}function Te(e,t,n){let r=t.model!==void 0&&Object.hasOwn(e.models,t.model)&&(n===void 0||t.model!==J(n))?t.model:J(e),i=r===void 0?void 0:e.models[r]?.efforts;return{model:r,effort:r===t.model&&t.effort!==void 0&&i!==void 0&&Object.hasOwn(i,t.effort)&&(n===void 0||t.effort!==W(n,r))?t.effort:W(e,r)}}function Y(e){if(!e.operationId)throw new r(`request`,i(`session.gate_expired`));return e.operationId}function Ee(e,t){return t.selectedModel??J(e)}function X(e,t,n){let r=t.selectedEffort;if(!n||!Object.hasOwn(e.models,n))return r;let i=e.models[n];return i.allowEffortSelect?r??i.defaultEffort:r===W(e,n)?void 0:r}function Z(e,t){let n=Ee(e,t),r=e.allowModelSelect||n!==J(e)?n:void 0,i=X(e,t,n);return{...r?{model:r}:{},...i?{effort:i}:{}}}function De(e,t,n){return{name:n.name,input:n.input,...n.gateKind?{gateKind:n.gateKind}:{},sessionPermissions:n.sessionPermissions??t.sessionPermissions,...t.toolSnapshot?{snapshot:t.toolSnapshot}:{},...t.promotedToolIds.length?{promoted:[...t.promotedToolIds]}:{},...Z(e,t)}}function Q(e){return{...e.conversation?{conversation:e.conversation}:{},...e.turnId?{turnId:e.turnId}:{}}}function Oe(e,t,n,r={}){let i=(r.walkAway?.calls??[]).map(e=>({callId:e.callId,operationId:Y(e)}));return{...Q(r),...Z(e,t),input:n,...i.length?{abandon:i}:{},replay:{sessionPermissions:t.sessionPermissions}}}function ke(e,t,n,r={}){return{...Q(r),gateId:n.gateId,operationId:n.operationId,decision:n.decision,...n.secret===void 0?{}:{secret:n.secret},...n.page===void 0?{}:{page:n.page},replay:De(e,t,{...n,gateKind:n.gateKind??(t.gatedTool?.callId===n.gateId?t.gatedTool.gateKind:void 0)})}}function $(e,t){return B(e.inputs,t,e.guardrails)}function Ae(e,t,n,r=[]){return $(e,{...t.trim()?{text:t}:{},...n.length?{attachments:l(n)}:{},...r.length?{voice:l(r)}:{}})}function je(e,t){return z(t,{showThoughts:q(e.outputs)})}export{ae as C,ee as D,te as E,p as O,le as S,ne as T,B as _,Ae as a,y as b,q as c,K as d,W as f,H as g,Se as h,Y as i,m as k,G as l,Ce as m,Oe as n,$ as o,U as p,je as r,Te as s,ke as t,we as u,ye as v,f as w,ue as x,z as y};
@@ -1 +1 @@
1
- import{r as e}from"./rolldown-runtime-hePW80VL.js";import{c as t,u as n}from"./themeProps-3IqahpCr.js";import{t as r}from"./VStack-CkVMcNiK.js";import{n as i}from"./StackItem-CQviqAfM.js";import{S as a,T as o}from"./browser-transport-h1KAGUN4.js";import{t as s}from"./Icon-BqkS-pIq.js";import{t as c}from"./Text-BOqCfzZC.js";import{n as l,o as u}from"./labels-provider-uONlWExD.js";import{n as d}from"./Card-DruykyeB.js";import{t as f}from"./IconButton-DVUFx-8p.js";import{t as p}from"./Tooltip-BWs5DLrM.js";import{d as m}from"./reader-COeSYhdZ.js";import{_ as h,b as g,g as _,y as v}from"./ConsoleFrame-KmyDVQkS.js";import{c as y,i as b}from"./trace-patterns-D6TbkLLr.js";import{n as x}from"./studio-console-dHEr6mr5.js";import{D as S,O as C,V as w,W as T}from"./index-Bd7U_fu_.js";var E=e(n(),1),D=t(),O=`var(--duration-medium) var(--ease-standard)`,k=12;function A(){let e=d();return(0,E.useMemo)(()=>({percent:new Intl.NumberFormat(e,{style:`percent`,maximumFractionDigits:0}),decimal:new Intl.NumberFormat(e,{maximumFractionDigits:2}),usd:new Intl.NumberFormat(e,{style:`currency`,currency:`USD`,maximumSignificantDigits:2})}),[e])}function j(e){return y(e?`clear`:`shade2`)}function M({value:e,isLead:t}){return(0,D.jsx)(`div`,{style:{height:k,width:`${String(Math.max(e,.01)*100)}%`,borderRadius:4,background:j(t),transition:`width ${O}`}})}function N({title:e,aside:t,detail:n,answer:a}){let o=l(),s=A(),u=Object.entries(a.probabilities).sort(([,e],[,t])=>t-e);return(0,D.jsx)(b,{title:e,aside:t,detail:n,value:a.choice,note:o(`@theorem.decision.confidence`,{percent:s.percent.format(a.confidence)}),children:(0,D.jsx)(r,{gap:2,role:`list`,children:u.map(([e,t])=>(0,D.jsxs)(r,{gap:1,role:`listitem`,"aria-label":o(`@theorem.decision.option`,{label:e,percent:s.percent.format(t)}),children:[(0,D.jsxs)(i,{gap:2,hAlign:`between`,"aria-hidden":!0,children:[(0,D.jsx)(c,{type:`supporting`,color:`secondary`,maxLines:1,children:e}),(0,D.jsx)(c,{type:`supporting`,hasTabularNumbers:!0,children:s.percent.format(t)})]}),(0,D.jsx)(M,{value:t,isLead:e===a.choice})]},e))})})}var P=56;function F(e){let t=e.split(/[:—–]\s/)[0]?.trim()??``;return t&&t.length<=32&&t!==e?t:e}function I({title:e,aside:t,detail:n,answer:i,labels:a}){let o=l(),s=A(),u=a.length,d=Math.min(u-1,Math.max(0,Math.round(i.score)));return(0,D.jsx)(b,{title:e,aside:t,detail:n,value:a[d]===void 0?s.decimal.format(i.score):F(a[d]),note:[o(`@theorem.decision.score_of`,{score:s.decimal.format(i.score),max:s.decimal.format(u-1)}),o(`@theorem.decision.confidence`,{percent:s.percent.format(i.confidence)})].join(` · `),children:(0,D.jsxs)(r,{gap:1,children:[(0,D.jsxs)(`div`,{"aria-hidden":!0,style:{position:`relative`,display:`flex`,alignItems:`flex-end`,gap:4,height:P},children:[a.map((e,t)=>(0,D.jsx)(`div`,{style:{flex:1,height:`${String(Math.max(.04,i.probabilities[String(t)]??0)*100)}%`,borderRadius:4,background:j(t===d),transition:`height ${O}`}},`${String(t)}:${e}`)),(0,D.jsx)(`div`,{style:{position:`absolute`,insetBlock:-4,left:`${String((i.score+.5)/u*100)}%`,width:0,borderInlineStart:`1.5px dashed var(--color-text-secondary)`,transition:`left ${O}`}})]}),(0,D.jsx)(`div`,{style:{display:`flex`,gap:4},children:a.map((e,t)=>(0,D.jsx)(`div`,{style:{flex:1,minWidth:0},title:e,children:(0,D.jsx)(c,{type:`supporting`,color:`secondary`,maxLines:1,children:F(e)})},`${String(t)}:${e}`))}),(0,D.jsx)(`span`,{style:{position:`absolute`,width:1,height:1,overflow:`hidden`,clipPath:`inset(50%)`},children:a.map((e,t)=>o(`@theorem.decision.option`,{label:e,percent:s.percent.format(i.probabilities[String(t)]??0)})).join(`; `)})]})})}function L({title:e,aside:t,detail:n,answer:r}){let i=A();return(0,D.jsx)(b,{title:e,aside:t,detail:n,value:i.decimal.format(r.noul)})}var R=72,z=168;function B(e){let[t,n]=(0,E.useState)(null);return(0,E.useEffect)(()=>{let t=new Image;t.onload=()=>{n({width:t.naturalWidth,height:t.naturalHeight})},t.src=e},[e]),t}function V(e,t){let n=e.style.color;e.style.color=`var(${t})`;let r=getComputedStyle(e).color;return e.style.color=n,r}function H({source:e,box:t,caption:n}){let r=l(),i=v(e),a=B(i),[o,s]=(0,E.useState)(null);if(!a)return null;let c=h(t),u=a.width*(t.right-t.left)/(a.height*(t.bottom-t.top)),d=r(`@theorem.decision.open_box`);return(0,D.jsxs)(D.Fragment,{children:[(0,D.jsx)(p,{content:d,children:(0,D.jsx)(T,{label:d,padding:0,onClick:e=>{let n={outline:V(e.currentTarget,`--color-accent`),shade:V(e.currentTarget,`--color-overlay`)};g(i,t,n).then(s)},children:(0,D.jsx)(`div`,{role:`img`,"aria-label":r(`@theorem.decision.box_in`),style:{position:`relative`,overflow:`hidden`,aspectRatio:String(u),height:z,maxWidth:`100%`,borderRadius:4},children:(0,D.jsx)(`img`,{src:i,alt:``,style:{position:`absolute`,width:`${String(c.width)}%`,height:`${String(c.height)}%`,left:`${String(c.left)}%`,top:`${String(c.top)}%`,maxWidth:`none`}})})})}),(0,D.jsx)(w,{isOpen:o!==null,onOpenChange:e=>{e||s(null)},media:{src:o??i,alt:r(`@theorem.decision.box_marked`),caption:n},hasZoom:!0})]})}function U({title:e,aside:t,detail:n,answer:r,image:i,asked:a}){let o=l(),s=a&&_(a.images,a.state,i),c=A(),{top:u,bottom:d,left:f,right:p}=r.box,m=o(`@theorem.decision.box_edges`,{left:c.percent.format(f),top:c.percent.format(u),right:c.percent.format(p),bottom:c.percent.format(d)});return(0,D.jsx)(b,{title:e,aside:t,detail:n,value:m,note:o(`@theorem.decision.confidence`,{percent:c.percent.format(r.confidence)}),children:s?(0,D.jsx)(H,{source:s,box:r.box,caption:`${e}: ${m}`}):(0,D.jsx)(`div`,{"aria-hidden":!0,style:{position:`relative`,height:R,borderRadius:4,border:`1px solid var(--color-border)`},children:(0,D.jsx)(`div`,{style:{position:`absolute`,insetInlineStart:`${String(f*100)}%`,insetBlockStart:`${String(u*100)}%`,width:`${String((p-f)*100)}%`,height:`${String((d-u)*100)}%`,borderRadius:2,background:j(!0),transition:`all ${O}`}})})})}function W({question:e,answer:t,asked:n,onQuestion:r,detail:i}){let a=l(),c=`${e.id} · ${a(`@theorem.decision.type.${e.type}`)}`;if(!t)return null;let u=a(`@theorem.decision.edit_question`,{question:e.id}),d={title:c,detail:i,aside:r?(0,D.jsx)(f,{label:u,tooltip:u,size:`sm`,variant:`ghost`,icon:(0,D.jsx)(s,{icon:o,size:`xsm`,color:`secondary`}),onClick:()=>{r(e.id)}}):void 0};return t.type===`choice`?(0,D.jsx)(N,{...d,answer:t}):t.type===`score`?(0,D.jsx)(I,{...d,answer:t,labels:e.labels}):t.type===`noul`?(0,D.jsx)(L,{...d,answer:t}):(0,D.jsx)(U,{...d,answer:t,image:e.image,asked:n})}function G({model:e,usage:t,elapsedMs:n,isStale:i,tokens:a,children:o}){let s=l(),d=A();return(0,D.jsx)(C,{children:(0,D.jsxs)(r,{gap:3,style:{opacity:i?.5:1,transition:`opacity ${O}`},"aria-busy":i,children:[o,(0,D.jsx)(S,{children:(0,D.jsx)(c,{type:`supporting`,color:`secondary`,hasTabularNumbers:!0,children:u(s,d.usd,{model:e,usage:t,elapsedMs:n,tokens:a})})})]},n??0)})}function K({iface:e,result:t,elapsedMs:n,isStale:r,asked:i,onQuestion:a,questionText:o}){let s=l();return(0,D.jsx)(G,{model:t.model,usage:t.usage,elapsedMs:n,isStale:r,tokens:e=>s(`@theorem.decision.tokens`,{count:e}),children:(0,D.jsx)(x,{minWidth:260,children:e.questions.map(e=>(0,D.jsx)(S,{children:(0,D.jsx)(W,{question:e,answer:t.answers[e.id],asked:i,onQuestion:a,detail:o?.[e.id]})},e.id))})})}var q={status:`idle`,result:null,elapsedMs:null,startedAt:null,failure:null};function J(e,t){for(let n of t??[])e.traces?.push(n)}function Y(e,t,n){let[r,i]=(0,E.useState)(q),o=(0,E.useRef)(null);(0,E.useEffect)(()=>()=>o.current?.abort(),[]);let s=(0,E.useCallback)(()=>{o.current?.abort(),o.current=null,i(e=>e.status===t?{...e,status:e.result?`done`:`idle`,startedAt:null}:e)},[t]),c=(0,E.useCallback)(async(...r)=>{o.current?.abort();let s=new AbortController;o.current=s,i(e=>({status:t,result:e.result,elapsedMs:e.elapsedMs,startedAt:Date.now(),failure:null}));let c=performance.now();try{let t=await n(e,s.signal,...r);if(s.signal.aborted)return;J(e,t.traces),i({status:`done`,result:t.result,elapsedMs:performance.now()-c,startedAt:null,failure:null})}catch(t){if(s.signal.aborted)return;J(e,m(t)),i(e=>({...e,status:`error`,startedAt:null,failure:a(t)}))}finally{o.current===s&&(o.current=null)}},[e,t,n]);return{...r,call:c,cancel:s}}export{A as a,K as i,G as n,M as r,Y as t};
1
+ import{r as e}from"./rolldown-runtime-hePW80VL.js";import{c as t,u as n}from"./themeProps-3IqahpCr.js";import{t as r}from"./VStack-CkVMcNiK.js";import{n as i}from"./StackItem-CQviqAfM.js";import{S as a,T as o}from"./browser-transport-DKhZ4zo1.js";import{t as s}from"./Icon-BqkS-pIq.js";import{t as c}from"./Text-BOqCfzZC.js";import{n as l,o as u}from"./labels-provider-uONlWExD.js";import{n as d}from"./Card-DruykyeB.js";import{t as f}from"./IconButton-DVUFx-8p.js";import{t as p}from"./Tooltip-BWs5DLrM.js";import{d as m}from"./reader-747-Cvu8.js";import{_ as h,b as g,g as _,y as v}from"./ConsoleFrame-dOTqIkpb.js";import{c as y,i as b}from"./trace-patterns-D6TbkLLr.js";import{n as x}from"./studio-console-DwxLzV9_.js";import{D as S,O as C,V as w,W as T}from"./index-CAK9cdCh.js";var E=e(n(),1),D=t(),O=`var(--duration-medium) var(--ease-standard)`,k=12;function A(){let e=d();return(0,E.useMemo)(()=>({percent:new Intl.NumberFormat(e,{style:`percent`,maximumFractionDigits:0}),decimal:new Intl.NumberFormat(e,{maximumFractionDigits:2}),usd:new Intl.NumberFormat(e,{style:`currency`,currency:`USD`,maximumSignificantDigits:2})}),[e])}function j(e){return y(e?`clear`:`shade2`)}function M({value:e,isLead:t}){return(0,D.jsx)(`div`,{style:{height:k,width:`${String(Math.max(e,.01)*100)}%`,borderRadius:4,background:j(t),transition:`width ${O}`}})}function N({title:e,aside:t,detail:n,answer:a}){let o=l(),s=A(),u=Object.entries(a.probabilities).sort(([,e],[,t])=>t-e);return(0,D.jsx)(b,{title:e,aside:t,detail:n,value:a.choice,note:o(`@theorem.decision.confidence`,{percent:s.percent.format(a.confidence)}),children:(0,D.jsx)(r,{gap:2,role:`list`,children:u.map(([e,t])=>(0,D.jsxs)(r,{gap:1,role:`listitem`,"aria-label":o(`@theorem.decision.option`,{label:e,percent:s.percent.format(t)}),children:[(0,D.jsxs)(i,{gap:2,hAlign:`between`,"aria-hidden":!0,children:[(0,D.jsx)(c,{type:`supporting`,color:`secondary`,maxLines:1,children:e}),(0,D.jsx)(c,{type:`supporting`,hasTabularNumbers:!0,children:s.percent.format(t)})]}),(0,D.jsx)(M,{value:t,isLead:e===a.choice})]},e))})})}var P=56;function F(e){let t=e.split(/[:—–]\s/)[0]?.trim()??``;return t&&t.length<=32&&t!==e?t:e}function I({title:e,aside:t,detail:n,answer:i,labels:a}){let o=l(),s=A(),u=a.length,d=Math.min(u-1,Math.max(0,Math.round(i.score)));return(0,D.jsx)(b,{title:e,aside:t,detail:n,value:a[d]===void 0?s.decimal.format(i.score):F(a[d]),note:[o(`@theorem.decision.score_of`,{score:s.decimal.format(i.score),max:s.decimal.format(u-1)}),o(`@theorem.decision.confidence`,{percent:s.percent.format(i.confidence)})].join(` · `),children:(0,D.jsxs)(r,{gap:1,children:[(0,D.jsxs)(`div`,{"aria-hidden":!0,style:{position:`relative`,display:`flex`,alignItems:`flex-end`,gap:4,height:P},children:[a.map((e,t)=>(0,D.jsx)(`div`,{style:{flex:1,height:`${String(Math.max(.04,i.probabilities[String(t)]??0)*100)}%`,borderRadius:4,background:j(t===d),transition:`height ${O}`}},`${String(t)}:${e}`)),(0,D.jsx)(`div`,{style:{position:`absolute`,insetBlock:-4,left:`${String((i.score+.5)/u*100)}%`,width:0,borderInlineStart:`1.5px dashed var(--color-text-secondary)`,transition:`left ${O}`}})]}),(0,D.jsx)(`div`,{style:{display:`flex`,gap:4},children:a.map((e,t)=>(0,D.jsx)(`div`,{style:{flex:1,minWidth:0},title:e,children:(0,D.jsx)(c,{type:`supporting`,color:`secondary`,maxLines:1,children:F(e)})},`${String(t)}:${e}`))}),(0,D.jsx)(`span`,{style:{position:`absolute`,width:1,height:1,overflow:`hidden`,clipPath:`inset(50%)`},children:a.map((e,t)=>o(`@theorem.decision.option`,{label:e,percent:s.percent.format(i.probabilities[String(t)]??0)})).join(`; `)})]})})}function L({title:e,aside:t,detail:n,answer:r}){let i=A();return(0,D.jsx)(b,{title:e,aside:t,detail:n,value:i.decimal.format(r.noul)})}var R=72,z=168;function B(e){let[t,n]=(0,E.useState)(null);return(0,E.useEffect)(()=>{let t=new Image;t.onload=()=>{n({width:t.naturalWidth,height:t.naturalHeight})},t.src=e},[e]),t}function V(e,t){let n=e.style.color;e.style.color=`var(${t})`;let r=getComputedStyle(e).color;return e.style.color=n,r}function H({source:e,box:t,caption:n}){let r=l(),i=v(e),a=B(i),[o,s]=(0,E.useState)(null);if(!a)return null;let c=h(t),u=a.width*(t.right-t.left)/(a.height*(t.bottom-t.top)),d=r(`@theorem.decision.open_box`);return(0,D.jsxs)(D.Fragment,{children:[(0,D.jsx)(p,{content:d,children:(0,D.jsx)(T,{label:d,padding:0,onClick:e=>{let n={outline:V(e.currentTarget,`--color-accent`),shade:V(e.currentTarget,`--color-overlay`)};g(i,t,n).then(s)},children:(0,D.jsx)(`div`,{role:`img`,"aria-label":r(`@theorem.decision.box_in`),style:{position:`relative`,overflow:`hidden`,aspectRatio:String(u),height:z,maxWidth:`100%`,borderRadius:4},children:(0,D.jsx)(`img`,{src:i,alt:``,style:{position:`absolute`,width:`${String(c.width)}%`,height:`${String(c.height)}%`,left:`${String(c.left)}%`,top:`${String(c.top)}%`,maxWidth:`none`}})})})}),(0,D.jsx)(w,{isOpen:o!==null,onOpenChange:e=>{e||s(null)},media:{src:o??i,alt:r(`@theorem.decision.box_marked`),caption:n},hasZoom:!0})]})}function U({title:e,aside:t,detail:n,answer:r,image:i,asked:a}){let o=l(),s=a&&_(a.images,a.state,i),c=A(),{top:u,bottom:d,left:f,right:p}=r.box,m=o(`@theorem.decision.box_edges`,{left:c.percent.format(f),top:c.percent.format(u),right:c.percent.format(p),bottom:c.percent.format(d)});return(0,D.jsx)(b,{title:e,aside:t,detail:n,value:m,note:o(`@theorem.decision.confidence`,{percent:c.percent.format(r.confidence)}),children:s?(0,D.jsx)(H,{source:s,box:r.box,caption:`${e}: ${m}`}):(0,D.jsx)(`div`,{"aria-hidden":!0,style:{position:`relative`,height:R,borderRadius:4,border:`1px solid var(--color-border)`},children:(0,D.jsx)(`div`,{style:{position:`absolute`,insetInlineStart:`${String(f*100)}%`,insetBlockStart:`${String(u*100)}%`,width:`${String((p-f)*100)}%`,height:`${String((d-u)*100)}%`,borderRadius:2,background:j(!0),transition:`all ${O}`}})})})}function W({question:e,answer:t,asked:n,onQuestion:r,detail:i}){let a=l(),c=`${e.id} · ${a(`@theorem.decision.type.${e.type}`)}`;if(!t)return null;let u=a(`@theorem.decision.edit_question`,{question:e.id}),d={title:c,detail:i,aside:r?(0,D.jsx)(f,{label:u,tooltip:u,size:`sm`,variant:`ghost`,icon:(0,D.jsx)(s,{icon:o,size:`xsm`,color:`secondary`}),onClick:()=>{r(e.id)}}):void 0};return t.type===`choice`?(0,D.jsx)(N,{...d,answer:t}):t.type===`score`?(0,D.jsx)(I,{...d,answer:t,labels:e.labels}):t.type===`noul`?(0,D.jsx)(L,{...d,answer:t}):(0,D.jsx)(U,{...d,answer:t,image:e.image,asked:n})}function G({model:e,usage:t,elapsedMs:n,isStale:i,tokens:a,children:o}){let s=l(),d=A();return(0,D.jsx)(C,{children:(0,D.jsxs)(r,{gap:3,style:{opacity:i?.5:1,transition:`opacity ${O}`},"aria-busy":i,children:[o,(0,D.jsx)(S,{children:(0,D.jsx)(c,{type:`supporting`,color:`secondary`,hasTabularNumbers:!0,children:u(s,d.usd,{model:e,usage:t,elapsedMs:n,tokens:a})})})]},n??0)})}function K({iface:e,result:t,elapsedMs:n,isStale:r,asked:i,onQuestion:a,questionText:o}){let s=l();return(0,D.jsx)(G,{model:t.model,usage:t.usage,elapsedMs:n,isStale:r,tokens:e=>s(`@theorem.decision.tokens`,{count:e}),children:(0,D.jsx)(x,{minWidth:260,children:e.questions.map(e=>(0,D.jsx)(S,{children:(0,D.jsx)(W,{question:e,answer:t.answers[e.id],asked:i,onQuestion:a,detail:o?.[e.id]})},e.id))})})}var q={status:`idle`,result:null,elapsedMs:null,startedAt:null,failure:null};function J(e,t){for(let n of t??[])e.traces?.push(n)}function Y(e,t,n){let[r,i]=(0,E.useState)(q),o=(0,E.useRef)(null);(0,E.useEffect)(()=>()=>o.current?.abort(),[]);let s=(0,E.useCallback)(()=>{o.current?.abort(),o.current=null,i(e=>e.status===t?{...e,status:e.result?`done`:`idle`,startedAt:null}:e)},[t]),c=(0,E.useCallback)(async(...r)=>{o.current?.abort();let s=new AbortController;o.current=s,i(e=>({status:t,result:e.result,elapsedMs:e.elapsedMs,startedAt:Date.now(),failure:null}));let c=performance.now();try{let t=await n(e,s.signal,...r);if(s.signal.aborted)return;J(e,t.traces),i({status:`done`,result:t.result,elapsedMs:performance.now()-c,startedAt:null,failure:null})}catch(t){if(s.signal.aborted)return;J(e,m(t)),i(e=>({...e,status:`error`,startedAt:null,failure:a(t)}))}finally{o.current===s&&(o.current=null)}},[e,t,n]);return{...r,call:c,cancel:s}}export{A as a,K as i,G as n,M as r,Y as t};