@theoremjs/studio 0.3.4-next.843.ga3bad83 → 0.3.4-next.847.g6513d7e

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 (44) hide show
  1. package/package.json +4 -4
  2. package/page/assets/{BottomSheet-Cw0lMJjl.js → BottomSheet-vAeXbo6j.js} +1 -1
  3. package/page/assets/{ConsoleFrame-B9JNg4CN.js → ConsoleFrame-1n_sABmX.js} +1 -1
  4. package/page/assets/{DateInput-De9JjeH_.js → DateInput-DpZtfChG.js} +1 -1
  5. package/page/assets/{MenuBottomSheet-DdSmYsNc.js → MenuBottomSheet-B7CP4Lsr.js} +1 -1
  6. package/page/assets/{SchemaFields-DJkTusje.js → SchemaFields-CXD7c72E.js} +1 -1
  7. package/page/assets/{TokenizerBottomSheet-C1L_-KaG.js → TokenizerBottomSheet-Cu3kzKeo.js} +1 -1
  8. package/page/assets/{ToolResultCharts-DZGGNGma.js → ToolResultCharts-DVYs8fEi.js} +1 -1
  9. package/page/assets/{Toolbar-Btx1iaPT.js → Toolbar-CE6Lf31u.js} +1 -1
  10. package/page/assets/{TraceInspector-0pNFF2YZ.js → TraceInspector-BiZXdbiO.js} +1 -1
  11. package/page/assets/{TraceOverview-C05Dq7VT.js → TraceOverview-BGJeBaBA.js} +1 -1
  12. package/page/assets/{browser-connection-BMoCFhYy.js → browser-connection-D0GtrJxN.js} +1 -1
  13. package/page/assets/{browser-engine-BPK0G6Fx.js → browser-engine-BPM5Nk_h.js} +1 -1
  14. package/page/assets/{browser-transport-CGUAMEI8.js → browser-transport-CbYs8r-W.js} +2 -2
  15. package/page/assets/{compile-6eIfaXll.js → compile-CmwVyRsa.js} +1 -1
  16. package/page/assets/{encode-files-MOJXvlW9.js → encode-files-DWBa8FAF.js} +1 -1
  17. package/page/assets/{export-agent-pIAn8z0b.js → export-agent-DMuAKRCy.js} +1 -1
  18. package/page/assets/{guardrail-tester-2dfwTtJS.js → guardrail-tester-BrUjQBZe.js} +1 -1
  19. package/page/assets/{index-DneFNrzM.js → index-D2y4CjDY.js} +10 -10
  20. package/page/assets/{json-code-B1rVZeZr.js → json-code-3X-j_JYu.js} +1 -1
  21. package/page/assets/{live-messages-d9BIeBEz.js → live-messages-Cfo-A3Ia.js} +1 -1
  22. package/page/assets/{prompt-row-BJV0pnrQ.js → prompt-row-Bf15WWbA.js} +1 -1
  23. package/page/assets/{reader-CXHCDEbW.js → reader-CVIM-dZI.js} +1 -1
  24. package/page/assets/{registry-Dv2wwCfg.js → registry-BpOBaSGc.js} +1 -1
  25. package/page/assets/{schema-G8cHvtht.js → schema-V9Rv344d.js} +1 -1
  26. package/page/assets/{shaped-data-OkTOsVE5.js → shaped-data-CjB-teds.js} +1 -1
  27. package/page/assets/{stub-B7dxSuX6.js → stub-CeHLNUXC.js} +1 -1
  28. package/page/assets/{studio-code-pane-Cx_dRvck.js → studio-code-pane-DTq-NEj9.js} +1 -1
  29. package/page/assets/{studio-console-B7L5E-BA.js → studio-console-BFsT1OdM.js} +1 -1
  30. package/page/assets/{studio-decision-BUQutOd_.js → studio-decision-CLgqn34e.js} +1 -1
  31. package/page/assets/{studio-embedding-BhQ4o-kG.js → studio-embedding-6qdjR5xf.js} +1 -1
  32. package/page/assets/{studio-host-console-DSclsJeZ.js → studio-host-console-DJ5Xg7dh.js} +2 -2
  33. package/page/assets/{studio-labels-Bv6qm3lg.js → studio-labels-B-e0Wofl.js} +1 -1
  34. package/page/assets/{studio-live-BrdnB_o5.js → studio-live-COBsd-IC.js} +1 -1
  35. package/page/assets/{studio-map-Cnatnz-_.js → studio-map-BPAftdD5.js} +1 -1
  36. package/page/assets/{studio-trace-replay-VESTHfWb.js → studio-trace-replay-Y4NSmcA3.js} +1 -1
  37. package/page/assets/{tool-schema-Cphc-uXi.js → tool-schema-Cqelak6O.js} +1 -1
  38. package/page/assets/{trace-record-D1fIfCpY.js → trace-record-CchShZYV.js} +1 -1
  39. package/page/assets/{tree-BhFuh9Po.js → tree-DoI5ABlX.js} +1 -1
  40. package/page/assets/{turn-client-DsZejesM.js → turn-client-_TUC5_DY.js} +1 -1
  41. package/page/assets/{types-rNU69aPS.js → types-yrvA7TCg.js} +1 -1
  42. package/page/assets/{use-one-call-DTURPTpy.js → use-one-call-CvLcEx5b.js} +1 -1
  43. package/page/assets/{workspace-DbaMrvjR.js → workspace-BpNR3COy.js} +1 -1
  44. package/page/index.html +16 -16
@@ -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{$n as Re,$t as ze,A as E,Ar as Be,B as Ve,Br as He,Cn as Ue,D as We,En as Ge,Fr as Ke,Ir as qe,Jn as Je,K as Ye,Lr as D,M as O,Mr as Xe,N as k,O as A,On as Ze,Or as Qe,P as $e,Qt as et,Sn as tt,Sr as nt,Ur as j,_r as rt,a as it,an as at,br as ot,c as M,dr as st,en as ct,er as lt,fr as ut,gr as dt,k as N,kn as ft,ln as pt,mn as mt,mt as ht,nn as gt,nr as _t,or as vt,pn as yt,pr as bt,rr as xt,sr as St,tn as Ct,ur as wt,vn as Tt,vr as Et,xr as Dt}from"./shaped-data-OkTOsVE5.js";var Ot=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}),kt=e({ZodISODate:()=>we,ZodISODateTime:()=>ke,ZodISODuration:()=>ve,ZodISOTime:()=>ue,date:()=>jt,datetime:()=>At,duration:()=>Nt,time:()=>Mt});function At(e){return u(ke,e)}function jt(e){return s(we,e)}function Mt(e){return ne(ue,e)}function Nt(e){return p(ve,e)}var P={...Fe,...Ot,iso:kt},Pt=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 Ft(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 It(e,t){return e.map((e,n)=>n<t?e:e.optional())}function Lt(e){return e.replace(/~1/g,`/`).replace(/~0/g,`~`)}function Rt(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:Lt(n[1]);if(!r||!t.defs[r])throw Error(`Reference not found: ${e}`);return t.defs[r]}throw Error(`Reference not found: ${e}`)}function zt(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 Bt(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=Bt(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=Bt(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 Vt=new Set([`items`,`prefixItems`,`additionalItems`,`additionalProperties`,`contains`,`propertyNames`,`not`,`if`,`then`,`else`,`allOf`,`anyOf`,`oneOf`,`unevaluatedItems`,`unevaluatedProperties`,`contentSchema`]),Ht=new Set([`properties`,`patternProperties`,`dependentSchemas`,`dependencies`,`$defs`,`definitions`]);function Ut(e){return typeof e!=`object`||!e?!1:Array.isArray(e)?e.some(Ut):typeof e.$ref==`string`||Object.entries(e).some(([e,t])=>Vt.has(e)?Ut(t):!Ht.has(e)||typeof t!=`object`||!t?!1:Object.values(t).some(Ut))}function Wt(e){return e===1?`element`:`elements`}function Gt(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=Bt(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 ${Wt(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 ${Wt(t.maxContains)}`,input:n,continue:!0})}}}).pipe(e)}function Kt(e,t){if(e!==!1)return e===void 0||e===!0?P.any():F(e,t)}var qt=/^(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/;function Jt(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(Rt(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=>Jt({...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(qt)):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=zt(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=It(n.map(e=>F(e,t)),a),s=Array.isArray(i)?void 0:Kt(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=It(i.map(e=>F(e,t)),n),o=Kt(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=Gt(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=Jt(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&&!Ut(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&&!Ut(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))Pt.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 Yt(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:Ft(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 Xt=y(Le),Zt=w({key:y(He),params:i(o(),a([o(),v()])).optional()}),Qt=a([Zt,b(Zt).readonly()]),$t=w({origin:y(ot),tool:o(),depth:v()}),en=w({rule:o(),severity:y(Et),span:w({start:v(),end:v()}).optional(),match:o().optional(),label:o().optional(),doc:o().optional(),pattern:o().optional(),signal:o().optional()}),tn=w({stage:y(rt),boundary:y(nt).optional(),trust:y(Dt),action:y(dt),hits:b(en),provenance:$t.optional(),errorInternal:o().optional(),errorSummary:o().optional()}),nn=ge(),I=i(o(),nn),rn=_({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:nn,wireCallIds:i(o().min(1),o().min(1)).optional()}),an=_({code:C(`provider_state_rebuilt`),reason:y([`provider_changed`,`model_changed`,`connection_changed`,`key_changed`,`history_changed`,`version_changed`])}),on=_({history:y([`host`,`stateless`,`provider`]).optional()});async function sn(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),cn=w({type:C(`text`),text:o()}),ln=w({type:y(mt),mimeType:o(),data:o()}),un=w({type:y(mt),mimeType:o(),uri:o()}),dn=a([cn,ln,un]),fn=dn,pn=w({protocol:o().min(1),provider:o().min(1).optional(),apiId:o().min(1).optional()}),mn=w({text:o().optional(),data:nn,origin:pn}),hn=w({role:y([`system`,`user`,`assistant`,`tool`]),content:o().optional(),parts:b(dn).optional(),tool_calls:b(w({id:o(),type:C(`function`),function:w({name:o(),arguments:o()})})).optional(),reasoning:b(mn).optional(),tool_call_id:o().optional(),name:o().optional(),metadata:L.optional()}),gn=hn,_n=w({kind:y(ft),native:o().optional()}),vn=_n,yn=[`input`,`output`],bn=w({usd:v(),upstreamUsd:v().optional(),partial:C(!0).optional()}),xn=w({type:o(),count:v(),searchQueryCount:v().optional()}),Sn=w({input:v(),output:v(),thinking:v().optional(),toolUse:v().optional(),cached:v().optional(),cacheWrite:v().optional(),total:v(),cost:bn.optional(),estimated:b(y(yn)).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(xn).optional()});w({id:o().optional(),model:o().optional()});var Cn=w({title:o(),uri:o(),type:y([`web`,`maps`]),placeId:o().optional()}),wn=Cn,Tn=w({metadata:L.optional(),chunks:b(g()).optional(),searchHtml:o().optional()}),z={provider:o().min(1),raw:L.optional(),partial:S().optional()},En=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()})]),Dn=w({cause:C(`go_away`),code:v(),closedAfterMs:v(),errorKind:Xt.optional()}),On=x(`kind`,[w({kind:C(`closing_soon`),timeLeftMs:v().optional()}),w({kind:C(`ended`),timeLeftMs:v().optional(),ended:Dn,message:o()}),w({kind:y([`waiting_for_input`,`turn_complete`,`working`,`idle`])})]),kn=w({code:o(),kind:Xt,message:o(),error:o().optional(),details:g().optional()}),An=w({slot:R,authType:y(Ue),service:R,message:R,authorizationUrl:o().optional(),state:o().optional(),issuer:o().optional(),resource:o().optional(),requiredScopes:b(R).optional()}),jn={preparedArguments:i(o(),g()).optional(),tool:R,permission:y(Ge).optional(),summary:R.optional(),request:R.optional(),access:y(tt).optional()},Mn=x(`kind`,[w({...jn,kind:y([`confirmation`,`permission`,`page`])}),w({...jn,kind:C(`auth`),authChallenge:An})]),Nn=Mn,Pn=w({code:o(),message:o(),severity:y([`info`,`warning`,`error`]).optional()}),Fn=w({name:o(),kind:o(),status:o(),inputs:L.optional(),outputs:L.optional()}),In={status:C(et),prompt:R},Ln=x(`kind`,[w({...In,kind:y([`confirm`,`text`]),options:b(R).optional()}),w({...In,kind:C(`choice`),options:b(R).min(1)})]);function Rn(e){return Ln.safeParse(e).success}var zn=w({type:C(`function`),name:o(),description:o(),parameters:L}),Bn=w({builtins:b(o()),gated:b(o()),visible:b(o()),executable:b(o()),path:o().optional(),sessionPermissions:b(o()).optional(),wire:b(zn),modelBackground:S().optional()}),Vn=Bn,Hn=_({callId:o().min(1),operationId:o().min(1).max(256)}),Un={name:o(),callId:o()},Wn=w({...Un,phase:Ne().optional(),arguments:L,reasoning:b(mn).optional(),stepId:o().min(1).optional(),stepCallCount:v().int().min(1).optional()}),B={...Un,at:v()},Gn=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:Fn}),w({...B,phase:C(`artifact`),artifact:g()}),w({...B,phase:C(`warning`),warning:Pn}),w({...B,phase:C(`complete`),output:g(),awaiting:S().optional(),readBack:o().optional(),parts:b(dn).optional(),activityPast:o().optional(),tokens:Sn.optional()}),w({...B,phase:C(`gate`),gate:Mn,readBack:o().optional()}),w({...B,phase:C(`background`),readBack:o()}),w({...B,phase:C(`error`),failure:kn,readBack:o().optional(),activityPast:o().optional(),tokens:Sn.optional()}),w({...B,phase:C(`cancel`)})]),Kn=a([Gn,Wn]).and(w({operationId:o().min(1).max(256).optional()})),qn=w({code:y(Tt),message:o(),field:o()}),Jn=w({needed:S(),meter:y(Ct),tokens:v(),unknownMedia:v(),promptTokens:v().optional(),promptTokensEstimated:S().optional(),history:b(hn)}),Yn=w({stop:y(ft).optional(),error:Xt.optional(),errorInternal:o().optional(),empty:C(!0).optional(),unreadable:C(!0).optional()}),Xn=[`tool`,`gate`];function Zn(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 Qn=y(Xn),$n=y(ft).exclude(Xn),er={providerState:rn.optional(),type:C(`done`),tokens:Sn.optional(),traceparent:o().optional(),steps:v().int().nonnegative().optional(),compaction:Jn.optional(),interrupted:S().optional(),interactionId:o().optional(),mediaRefused:w({dropped:b(w({mimeType:o(),from:y([`input`,`history`,`tool`])})),said:o()}).optional()},tr=a([w({...er,stop:w({kind:Qn,native:o().optional()}),tools:Bn}),w({...er,stop:w({kind:$n,native:o().optional()}),tools:Ne().optional()})]),V={provider_checkpoint:w({type:C(`provider_checkpoint`),providerState:rn,history:b(gn).optional()}),provider_warning:w({type:C(`provider_warning`),warning:an}),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`])}),late_results:w({type:C(`late_results`),text:o()}),media:w({type:C(`media`),media:w({mimeType:o(),data:o()})}),grounding:w({type:C(`grounding`),grounding:Tn}),citation:w({type:C(`citation`),sources:b(Cn),callId:o().optional()}),compaction:w({type:C(`compaction`),timing:C(`before`),meter:y(Ct),tokensBefore:v(),unknownMedia:v(),messagesBefore:v(),messagesAfter:v(),outcome:y(gt),history:b(hn),summary:o().optional(),failure:Yn.optional(),droppedMedia:v(),tokens:Sn.optional()}),evidence:w({type:C(`evidence`),evidence:En,text:o().optional(),sessionResumptionHandle:o().optional()}),tokens:w({type:C(`tokens`),tokens:Sn,interactionId:o().optional()}),session:w({type:C(`session`),session:On,errorInternal:o().optional()}),guardrail:w({type:C(`guardrail`),guardrail:tn}),stage:w({type:C(`stage`),stage:y(Ze),callId:o().optional(),toolName:o().optional(),callNotStarted:S().optional(),awaiting:S().optional(),gate:Mn.optional(),stop:vn.optional(),stageWarnings:b(qn).optional(),injected:b(w({id:o().regex(/\S/),messages:b(hn)})).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:Kn,errorInternal:o().optional()}),error:w({type:C(`error`),errorKind:Xt,error:o().optional(),errorCopy:Qt.optional(),errorInternal:o().optional()}),done:tr},nr=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.late_results,V.tokens,V.session,V.guardrail,V.stage,V.tool_draft,V.tool,V.error]),V.done]),rr=V;function ir(e){return e.type===`text`||e.type===`media`||e.type===`structured`||e.type===`structured_draft`}function ar(e,t){let n=[],r=t;for(let t of e)if(!ir(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 or(e){let t=[],n=0;for(let r of e){if(r.type===`attempt`){let e=t.splice(n);t.push(...e.filter(e=>!ir(e)))}r.type===`stage`&&r.released!==void 0&&t.push(...ar(t.splice(n),r.released)),t.push(r),r.type===`done`&&(n=t.length)}return t}var sr=[`reply`,`reply_structured`];function cr(e,t,n,r={}){if(!$e([t],n))return{action:`allow`,hits:[],value:e};let i=xt(e);if(i.unscannable)return{action:`block`,hits:[{rule:st.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=_t(e,e=>O(e,t,n,r).text??``),s=O(xt(o).text,t,n,r).action;return s===`redact`||s===`block`?{action:`block`,hits:a.hits}:{action:`redact`,hits:a.hits,value:o}}function lr(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:cr(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 ur(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 dr(e,t){return e?t.startsWith(e)?t.slice(e.length):`\n\n${t}`:t}function fr(e,t){return j(e?`egress.refusal_cut`:`egress.refusal`,{},t)}var 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(ht,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+ht.length;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=j(`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${ht}`}function vr(e,t){return j(e===`high`?`advisory.notice_high`:`advisory.notice_elevated`,{},t)}function yr(e,t){if(t===void 0)return e;let n=xt(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){return hr(t.origin)?e.filter(({rule:e})=>e===wt.injection):[]}function Cr(e,t,n,r,i,a=[],o,s=[]){let c=xr(yr(e,t),i,r.detect,{callable:a}),l=hr(n.origin),u=[...s,...Sr(c.hits,n)],d=c.action===`allow`?void 0:{stage:`tool_result`,...i?{boundary:i}:{},trust:`untrusted`,action:c.action,hits:c.hits,provenance:n},f={...u.length>0?{suspicious:u}:{},...d?{event:d}:{}};return c.text===void 0?f:{text:l?_r(c.text,n,Ye(u.map(({signal:e})=>e)),o):c.text,...f}}function wr(e,t,n,r){let i=xr(gr(e),r,n.detect),a=r?k(r,i,t):void 0,o=i.text===void 0?[]:Sr(i.hits,t);return{...i.text===void 0?{}:{text:i.text},...a?{event:a}:{},...o.length>0?{suspicious:o}:{}}}function Tr(e,t,n,r){if(!r||e===void 0)return{value:e};let i=cr(e,r,n.detect),a=k(r,i,t);return{...i.action===`block`?{}:{value:i.value},...a?{event:a}:{}}}function Er(e,t,n,r,i={}){if(!(r&&$e([r],n.detect)))return{args:e};let a=e=>{let n=k(r,{action:`block`,hits:e},t);return n?{event:n}:{}},o=xt(e);if(o.unscannable)return a([{rule:st.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=_t(e,e=>O(e,r,n.detect,i).text??``),u=O(xt(l).text,r,n.detect,i).action;return u===`redact`||u===`block`?a(s.hits):{args:l,...c?{event:c}:{}}}function Dr(e,t){if(e.action!==`allow`)return{stage:`tool_call`,trust:`untrusted`,action:e.action,hits:e.hits,provenance:t}}function Or(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 kr(e){return(e?.sources.length??0)>0}function Ar(e){return(e?.suspicious.length??0)>0}var jr={"read-only":0,"read-write":1,destructive:2},Mr={off:1/0,destructive:2,write:1};function Nr(e,t,n,r){if(!kr(e))return{action:`allow`};let i=jr[t]??0;if(i===0)return{action:`allow`};let a=Ar(e),o=[{rule:a?bt.steeredTurn:bt.taintedTurn,severity:`high`}];if(i<Mr[n.taint?.afterRemoteRead??`off`])return{action:`flag`,hits:o};let s=e?.sources.map(e=>e.tool).join(`, `)??``,c=j(a?`taint.reason_steered`:`taint.reason_tainted`,{},r);return{action:`block`,hits:o,rejection:j(`taint.blocked`,{access:t,sources:s,reason:c},r)}}var Pr={onBlock:`retry`,maxRetries:1};function Fr(e){return{onBlock:e?.onBlock??Pr.onBlock,maxRetries:e?.maxRetries??Pr.maxRetries}}function Ir(e){return{detect:lt(e?.detect),allow:Re(e?.detect),blockedReply:Fr(e?.blockedReply),network:e?.network,quota:e?.quota,taint:e?.taint}}function Lr(e){return(e.split(`;`)[0]??``).trim().toLowerCase()}function Rr(e,t){let n=Lr(t);return e.some(e=>{let t=Lr(e);return t.endsWith(`/*`)?n.startsWith(t.slice(0,-1)):t===n})}function zr(e){return yt[Lr(e)]}function Br(e){return e.type===`text`||e.type===`image`||e.type===`transcription`||e.type===`live`?e.inputs:void 0}function Vr(e,t){let n=Br(e);return t===`voice`?n?.voice?.accept:n?.attachments?.accept}function Hr(e,t){if(zr(t))for(let n of[`attachments`,`voice`]){let r=Vr(e,n);if(r&&Rr(r,t))return n}}function Ur(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 Wr=/^\d{1,3}(\.\d{1,3}){3}$/,Gr=[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 Kr(e,t,n,r){return Gr.some(r=>r(e,t,n))}function qr(e){if(!Wr.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:Kr(t,n,r,i)}function Jr(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),Yr=[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],Xr=[{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 Zr(e){let t=Jr(e);return t?.length===8?Yr.some(e=>e(t))?!0:Xr.some(({match:e,at:n})=>{if(!e(t))return!1;let r=t[n]??0,i=t[n+1]??0;return Kr(r>>8&255,r&255,i>>8&255,i&255)}):!1}function Qr(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 $r(e){let t=e.startsWith(`[`)&&e.endsWith(`]`)?e.slice(1,-1):e;return qr(t)||Zr(t)}function ei(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(Qr(a))throw new T(`blocked`,`Access to loopback target "${a}" blocked by network guardrail. Enable allowPrivateNetworks to permit local addresses.`);if(qr(a))throw new T(`blocked`,`Access to private IPv4 address "${a}" blocked by network guardrail.`);if(Zr(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 ti=20,ni=new Set([301,302,303,307,308]);async function ri(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(`[`)||Wr.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($r);if(s!==void 0)throw new T(`blocked`,`Host "${a}" resolves to private address "${s}", blocked by network guardrail.`)}function ii(e,t){return e===303?t!==`HEAD`:(e===301||e===302)&&t===`POST`}async function ai(e,t,n){let r=n.fetchFn??fetch,i=async e=>{let r=performance.now();try{let r=ei(e,n.policy);return await ri(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 Ke(r,a.href,{...t,method:c,headers:f,body:l,redirect:`manual`}),m=p.headers.get(`location`);if(!n.followRedirects||!ni.has(p.status)||m===null)return p;if(await p.body?.cancel(),d===ti)throw new T(`network`,`Too many redirects from "${e}"`);a=await i(new URL(m,a).href),u&&=a.origin===o,ii(p.status,c)&&(c=`GET`,l=void 0,s.delete(`content-type`))}}var U=v().int().positive().max(2**53-1),oi=U.max(2147483647),si=_({operationTimeoutMs:oi.optional(),connectTimeoutMs:oi.optional(),liveStepTimeoutMs:oi.optional(),maxWireRecordBytes:U.optional(),maxWireResponseBytes:U.optional(),maxEventBytes:U.optional(),maxStepBytes:U.optional(),maxStepEvents:U.optional(),maxPendingToolCalls:U.optional()}),ci=[`text`,`image`,`speech`,`transcription`,`live`,`decision`,`embedding`],li=w({id:o().regex(/^[A-Za-z][A-Za-z0-9]*$/),name:o().min(1),description:o().min(1),endpoints:re(y(ci),o().min(1)),operationNames:re(y(ci),o().regex(/^[a-z][a-z0-9_]*$/))});function ui(e,t){return new T(`config`,j(`protocol.definition`,{id:e,issues:t}))}function di(e){let t=li.safeParse(e);if(!t.success)throw ui(String(e.id),he(t.error))}function fi(e,t,n){let r=Object.keys(t).toSorted().join(`, `),i=Object.keys(n).toSorted().join(`, `);if(r!==i)throw ui(e,`operationNames name [${i}]; endpoints serve [${r}]`)}function pi(e,t,n,r){if(!n)throw new T(`internal`,j(`protocol.part_schema`,{protocol:e.id,kind:t}));let i=n.safeParse(r);if(!i.success)throw new T(`bad_response`,j(`protocol.part_invalid`,{protocol:e.id,kind:t}),{cause:i.error});return i.data}function mi(e,t){return t.type===`reasoning`?{...t,data:pi(e,`reasoning`,e.reasoning,t.data),origin:{protocol:e.id}}:t.type===`custom`?{type:`custom`,kind:`${e.id}.${t.kind}`,data:pi(e,t.kind,e.custom?.[t.kind],t.data)}:t}async function*hi(e,t){for await(let n of t)yield mi(e,n)}function gi(e,t){let{complete:n,openSession:r}=t;return{...t,...n?{complete:r=>hi(e,n.call(t,r))}:{},...r?{async openSession(n){let i=await r.call(t,n);return{...i,events:()=>hi(e,i.events())}}}:{}}}function _i(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{$n as Re,$t as ze,A as E,Ar as Be,B as Ve,Br as He,Cn as Ue,D as We,En as Ge,Fr as Ke,Ir as qe,Jn as Je,K as Ye,Lr as D,M as O,Mr as Xe,N as k,O as A,On as Ze,Or as Qe,P as $e,Qt as et,Sn as tt,Sr as nt,Ur as j,_r as rt,a as it,an as at,br as ot,c as M,dr as st,en as ct,er as lt,fr as ut,gr as dt,k as N,kn as ft,ln as pt,mn as mt,mt as ht,nn as gt,nr as _t,or as vt,pn as yt,pr as bt,rr as xt,sr as St,tn as Ct,ur as wt,vn as Tt,vr as Et,xr as Dt}from"./shaped-data-CjB-teds.js";var Ot=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}),kt=e({ZodISODate:()=>we,ZodISODateTime:()=>ke,ZodISODuration:()=>ve,ZodISOTime:()=>ue,date:()=>jt,datetime:()=>At,duration:()=>Nt,time:()=>Mt});function At(e){return u(ke,e)}function jt(e){return s(we,e)}function Mt(e){return ne(ue,e)}function Nt(e){return p(ve,e)}var P={...Fe,...Ot,iso:kt},Pt=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 Ft(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 It(e,t){return e.map((e,n)=>n<t?e:e.optional())}function Lt(e){return e.replace(/~1/g,`/`).replace(/~0/g,`~`)}function Rt(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:Lt(n[1]);if(!r||!t.defs[r])throw Error(`Reference not found: ${e}`);return t.defs[r]}throw Error(`Reference not found: ${e}`)}function zt(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 Bt(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=Bt(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=Bt(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 Vt=new Set([`items`,`prefixItems`,`additionalItems`,`additionalProperties`,`contains`,`propertyNames`,`not`,`if`,`then`,`else`,`allOf`,`anyOf`,`oneOf`,`unevaluatedItems`,`unevaluatedProperties`,`contentSchema`]),Ht=new Set([`properties`,`patternProperties`,`dependentSchemas`,`dependencies`,`$defs`,`definitions`]);function Ut(e){return typeof e!=`object`||!e?!1:Array.isArray(e)?e.some(Ut):typeof e.$ref==`string`||Object.entries(e).some(([e,t])=>Vt.has(e)?Ut(t):!Ht.has(e)||typeof t!=`object`||!t?!1:Object.values(t).some(Ut))}function Wt(e){return e===1?`element`:`elements`}function Gt(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=Bt(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 ${Wt(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 ${Wt(t.maxContains)}`,input:n,continue:!0})}}}).pipe(e)}function Kt(e,t){if(e!==!1)return e===void 0||e===!0?P.any():F(e,t)}var qt=/^(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/;function Jt(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(Rt(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=>Jt({...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(qt)):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=zt(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=It(n.map(e=>F(e,t)),a),s=Array.isArray(i)?void 0:Kt(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=It(i.map(e=>F(e,t)),n),o=Kt(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=Gt(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=Jt(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&&!Ut(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&&!Ut(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))Pt.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 Yt(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:Ft(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 Xt=y(Le),Zt=w({key:y(He),params:i(o(),a([o(),v()])).optional()}),Qt=a([Zt,b(Zt).readonly()]),$t=w({origin:y(ot),tool:o(),depth:v()}),en=w({rule:o(),severity:y(Et),span:w({start:v(),end:v()}).optional(),match:o().optional(),label:o().optional(),doc:o().optional(),pattern:o().optional(),signal:o().optional()}),tn=w({stage:y(rt),boundary:y(nt).optional(),trust:y(Dt),action:y(dt),hits:b(en),provenance:$t.optional(),errorInternal:o().optional(),errorSummary:o().optional()}),nn=ge(),I=i(o(),nn),rn=_({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:nn,wireCallIds:i(o().min(1),o().min(1)).optional()}),an=_({code:C(`provider_state_rebuilt`),reason:y([`provider_changed`,`model_changed`,`connection_changed`,`key_changed`,`history_changed`,`version_changed`])}),on=_({history:y([`host`,`stateless`,`provider`]).optional()});async function sn(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),cn=w({type:C(`text`),text:o()}),ln=w({type:y(mt),mimeType:o(),data:o()}),un=w({type:y(mt),mimeType:o(),uri:o()}),dn=a([cn,ln,un]),fn=dn,pn=w({protocol:o().min(1),provider:o().min(1).optional(),apiId:o().min(1).optional()}),mn=w({text:o().optional(),data:nn,origin:pn}),hn=w({role:y([`system`,`user`,`assistant`,`tool`]),content:o().optional(),parts:b(dn).optional(),tool_calls:b(w({id:o(),type:C(`function`),function:w({name:o(),arguments:o()})})).optional(),reasoning:b(mn).optional(),tool_call_id:o().optional(),name:o().optional(),metadata:L.optional()}),gn=hn,_n=w({kind:y(ft),native:o().optional()}),vn=_n,yn=[`input`,`output`],bn=w({usd:v(),upstreamUsd:v().optional(),partial:C(!0).optional()}),xn=w({type:o(),count:v(),searchQueryCount:v().optional()}),Sn=w({input:v(),output:v(),thinking:v().optional(),toolUse:v().optional(),cached:v().optional(),cacheWrite:v().optional(),total:v(),cost:bn.optional(),estimated:b(y(yn)).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(xn).optional()});w({id:o().optional(),model:o().optional()});var Cn=w({title:o(),uri:o(),type:y([`web`,`maps`]),placeId:o().optional()}),wn=Cn,Tn=w({metadata:L.optional(),chunks:b(g()).optional(),searchHtml:o().optional()}),z={provider:o().min(1),raw:L.optional(),partial:S().optional()},En=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()})]),Dn=w({cause:C(`go_away`),code:v(),closedAfterMs:v(),errorKind:Xt.optional()}),On=x(`kind`,[w({kind:C(`closing_soon`),timeLeftMs:v().optional()}),w({kind:C(`ended`),timeLeftMs:v().optional(),ended:Dn,message:o()}),w({kind:y([`waiting_for_input`,`turn_complete`,`working`,`idle`])})]),kn=w({code:o(),kind:Xt,message:o(),error:o().optional(),details:g().optional()}),An=w({slot:R,authType:y(Ue),service:R,message:R,authorizationUrl:o().optional(),state:o().optional(),issuer:o().optional(),resource:o().optional(),requiredScopes:b(R).optional()}),jn={preparedArguments:i(o(),g()).optional(),tool:R,permission:y(Ge).optional(),summary:R.optional(),request:R.optional(),access:y(tt).optional()},Mn=x(`kind`,[w({...jn,kind:y([`confirmation`,`permission`,`page`])}),w({...jn,kind:C(`auth`),authChallenge:An})]),Nn=Mn,Pn=w({code:o(),message:o(),severity:y([`info`,`warning`,`error`]).optional()}),Fn=w({name:o(),kind:o(),status:o(),inputs:L.optional(),outputs:L.optional()}),In={status:C(et),prompt:R},Ln=x(`kind`,[w({...In,kind:y([`confirm`,`text`]),options:b(R).optional()}),w({...In,kind:C(`choice`),options:b(R).min(1)})]);function Rn(e){return Ln.safeParse(e).success}var zn=w({type:C(`function`),name:o(),description:o(),parameters:L}),Bn=w({builtins:b(o()),gated:b(o()),visible:b(o()),executable:b(o()),path:o().optional(),sessionPermissions:b(o()).optional(),wire:b(zn),modelBackground:S().optional()}),Vn=Bn,Hn=_({callId:o().min(1),operationId:o().min(1).max(256)}),Un={name:o(),callId:o()},Wn=w({...Un,phase:Ne().optional(),arguments:L,reasoning:b(mn).optional(),stepId:o().min(1).optional(),stepCallCount:v().int().min(1).optional()}),B={...Un,at:v()},Gn=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:Fn}),w({...B,phase:C(`artifact`),artifact:g()}),w({...B,phase:C(`warning`),warning:Pn}),w({...B,phase:C(`complete`),output:g(),awaiting:S().optional(),readBack:o().optional(),parts:b(dn).optional(),activityPast:o().optional(),tokens:Sn.optional()}),w({...B,phase:C(`gate`),gate:Mn,readBack:o().optional()}),w({...B,phase:C(`background`),readBack:o()}),w({...B,phase:C(`error`),failure:kn,readBack:o().optional(),activityPast:o().optional(),tokens:Sn.optional()}),w({...B,phase:C(`cancel`)})]),Kn=a([Gn,Wn]).and(w({operationId:o().min(1).max(256).optional()})),qn=w({code:y(Tt),message:o(),field:o()}),Jn=w({needed:S(),meter:y(Ct),tokens:v(),unknownMedia:v(),promptTokens:v().optional(),promptTokensEstimated:S().optional(),history:b(hn)}),Yn=w({stop:y(ft).optional(),error:Xt.optional(),errorInternal:o().optional(),empty:C(!0).optional(),unreadable:C(!0).optional()}),Xn=[`tool`,`gate`];function Zn(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 Qn=y(Xn),$n=y(ft).exclude(Xn),er={providerState:rn.optional(),type:C(`done`),tokens:Sn.optional(),traceparent:o().optional(),steps:v().int().nonnegative().optional(),compaction:Jn.optional(),interrupted:S().optional(),interactionId:o().optional(),mediaRefused:w({dropped:b(w({mimeType:o(),from:y([`input`,`history`,`tool`])})),said:o()}).optional()},tr=a([w({...er,stop:w({kind:Qn,native:o().optional()}),tools:Bn}),w({...er,stop:w({kind:$n,native:o().optional()}),tools:Ne().optional()})]),V={provider_checkpoint:w({type:C(`provider_checkpoint`),providerState:rn,history:b(gn).optional()}),provider_warning:w({type:C(`provider_warning`),warning:an}),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`])}),late_results:w({type:C(`late_results`),text:o()}),media:w({type:C(`media`),media:w({mimeType:o(),data:o()})}),grounding:w({type:C(`grounding`),grounding:Tn}),citation:w({type:C(`citation`),sources:b(Cn),callId:o().optional()}),compaction:w({type:C(`compaction`),timing:C(`before`),meter:y(Ct),tokensBefore:v(),unknownMedia:v(),messagesBefore:v(),messagesAfter:v(),outcome:y(gt),history:b(hn),summary:o().optional(),failure:Yn.optional(),droppedMedia:v(),tokens:Sn.optional()}),evidence:w({type:C(`evidence`),evidence:En,text:o().optional(),sessionResumptionHandle:o().optional()}),tokens:w({type:C(`tokens`),tokens:Sn,interactionId:o().optional()}),session:w({type:C(`session`),session:On,errorInternal:o().optional()}),guardrail:w({type:C(`guardrail`),guardrail:tn}),stage:w({type:C(`stage`),stage:y(Ze),callId:o().optional(),toolName:o().optional(),callNotStarted:S().optional(),awaiting:S().optional(),gate:Mn.optional(),stop:vn.optional(),stageWarnings:b(qn).optional(),injected:b(w({id:o().regex(/\S/),messages:b(hn)})).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:Kn,errorInternal:o().optional()}),error:w({type:C(`error`),errorKind:Xt,error:o().optional(),errorCopy:Qt.optional(),errorInternal:o().optional()}),done:tr},nr=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.late_results,V.tokens,V.session,V.guardrail,V.stage,V.tool_draft,V.tool,V.error]),V.done]),rr=V;function ir(e){return e.type===`text`||e.type===`media`||e.type===`structured`||e.type===`structured_draft`}function ar(e,t){let n=[],r=t;for(let t of e)if(!ir(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 or(e){let t=[],n=0;for(let r of e){if(r.type===`attempt`){let e=t.splice(n);t.push(...e.filter(e=>!ir(e)))}r.type===`stage`&&r.released!==void 0&&t.push(...ar(t.splice(n),r.released)),t.push(r),r.type===`done`&&(n=t.length)}return t}var sr=[`reply`,`reply_structured`];function cr(e,t,n,r={}){if(!$e([t],n))return{action:`allow`,hits:[],value:e};let i=xt(e);if(i.unscannable)return{action:`block`,hits:[{rule:st.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=_t(e,e=>O(e,t,n,r).text??``),s=O(xt(o).text,t,n,r).action;return s===`redact`||s===`block`?{action:`block`,hits:a.hits}:{action:`redact`,hits:a.hits,value:o}}function lr(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:cr(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 ur(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 dr(e,t){return e?t.startsWith(e)?t.slice(e.length):`\n\n${t}`:t}function fr(e,t){return j(e?`egress.refusal_cut`:`egress.refusal`,{},t)}var 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(ht,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+ht.length;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=j(`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${ht}`}function vr(e,t){return j(e===`high`?`advisory.notice_high`:`advisory.notice_elevated`,{},t)}function yr(e,t){if(t===void 0)return e;let n=xt(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){return hr(t.origin)?e.filter(({rule:e})=>e===wt.injection):[]}function Cr(e,t,n,r,i,a=[],o,s=[]){let c=xr(yr(e,t),i,r.detect,{callable:a}),l=hr(n.origin),u=[...s,...Sr(c.hits,n)],d=c.action===`allow`?void 0:{stage:`tool_result`,...i?{boundary:i}:{},trust:`untrusted`,action:c.action,hits:c.hits,provenance:n},f={...u.length>0?{suspicious:u}:{},...d?{event:d}:{}};return c.text===void 0?f:{text:l?_r(c.text,n,Ye(u.map(({signal:e})=>e)),o):c.text,...f}}function wr(e,t,n,r){let i=xr(gr(e),r,n.detect),a=r?k(r,i,t):void 0,o=i.text===void 0?[]:Sr(i.hits,t);return{...i.text===void 0?{}:{text:i.text},...a?{event:a}:{},...o.length>0?{suspicious:o}:{}}}function Tr(e,t,n,r){if(!r||e===void 0)return{value:e};let i=cr(e,r,n.detect),a=k(r,i,t);return{...i.action===`block`?{}:{value:i.value},...a?{event:a}:{}}}function Er(e,t,n,r,i={}){if(!(r&&$e([r],n.detect)))return{args:e};let a=e=>{let n=k(r,{action:`block`,hits:e},t);return n?{event:n}:{}},o=xt(e);if(o.unscannable)return a([{rule:st.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=_t(e,e=>O(e,r,n.detect,i).text??``),u=O(xt(l).text,r,n.detect,i).action;return u===`redact`||u===`block`?a(s.hits):{args:l,...c?{event:c}:{}}}function Dr(e,t){if(e.action!==`allow`)return{stage:`tool_call`,trust:`untrusted`,action:e.action,hits:e.hits,provenance:t}}function Or(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 kr(e){return(e?.sources.length??0)>0}function Ar(e){return(e?.suspicious.length??0)>0}var jr={"read-only":0,"read-write":1,destructive:2},Mr={off:1/0,destructive:2,write:1};function Nr(e,t,n,r){if(!kr(e))return{action:`allow`};let i=jr[t]??0;if(i===0)return{action:`allow`};let a=Ar(e),o=[{rule:a?bt.steeredTurn:bt.taintedTurn,severity:`high`}];if(i<Mr[n.taint?.afterRemoteRead??`off`])return{action:`flag`,hits:o};let s=e?.sources.map(e=>e.tool).join(`, `)??``,c=j(a?`taint.reason_steered`:`taint.reason_tainted`,{},r);return{action:`block`,hits:o,rejection:j(`taint.blocked`,{access:t,sources:s,reason:c},r)}}var Pr={onBlock:`retry`,maxRetries:1};function Fr(e){return{onBlock:e?.onBlock??Pr.onBlock,maxRetries:e?.maxRetries??Pr.maxRetries}}function Ir(e){return{detect:lt(e?.detect),allow:Re(e?.detect),blockedReply:Fr(e?.blockedReply),network:e?.network,quota:e?.quota,taint:e?.taint}}function Lr(e){return(e.split(`;`)[0]??``).trim().toLowerCase()}function Rr(e,t){let n=Lr(t);return e.some(e=>{let t=Lr(e);return t.endsWith(`/*`)?n.startsWith(t.slice(0,-1)):t===n})}function zr(e){return yt[Lr(e)]}function Br(e){return e.type===`text`||e.type===`image`||e.type===`transcription`||e.type===`live`?e.inputs:void 0}function Vr(e,t){let n=Br(e);return t===`voice`?n?.voice?.accept:n?.attachments?.accept}function Hr(e,t){if(zr(t))for(let n of[`attachments`,`voice`]){let r=Vr(e,n);if(r&&Rr(r,t))return n}}function Ur(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 Wr=/^\d{1,3}(\.\d{1,3}){3}$/,Gr=[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 Kr(e,t,n,r){return Gr.some(r=>r(e,t,n))}function qr(e){if(!Wr.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:Kr(t,n,r,i)}function Jr(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),Yr=[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],Xr=[{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 Zr(e){let t=Jr(e);return t?.length===8?Yr.some(e=>e(t))?!0:Xr.some(({match:e,at:n})=>{if(!e(t))return!1;let r=t[n]??0,i=t[n+1]??0;return Kr(r>>8&255,r&255,i>>8&255,i&255)}):!1}function Qr(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 $r(e){let t=e.startsWith(`[`)&&e.endsWith(`]`)?e.slice(1,-1):e;return qr(t)||Zr(t)}function ei(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(Qr(a))throw new T(`blocked`,`Access to loopback target "${a}" blocked by network guardrail. Enable allowPrivateNetworks to permit local addresses.`);if(qr(a))throw new T(`blocked`,`Access to private IPv4 address "${a}" blocked by network guardrail.`);if(Zr(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 ti=20,ni=new Set([301,302,303,307,308]);async function ri(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(`[`)||Wr.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($r);if(s!==void 0)throw new T(`blocked`,`Host "${a}" resolves to private address "${s}", blocked by network guardrail.`)}function ii(e,t){return e===303?t!==`HEAD`:(e===301||e===302)&&t===`POST`}async function ai(e,t,n){let r=n.fetchFn??fetch,i=async e=>{let r=performance.now();try{let r=ei(e,n.policy);return await ri(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 Ke(r,a.href,{...t,method:c,headers:f,body:l,redirect:`manual`}),m=p.headers.get(`location`);if(!n.followRedirects||!ni.has(p.status)||m===null)return p;if(await p.body?.cancel(),d===ti)throw new T(`network`,`Too many redirects from "${e}"`);a=await i(new URL(m,a).href),u&&=a.origin===o,ii(p.status,c)&&(c=`GET`,l=void 0,s.delete(`content-type`))}}var U=v().int().positive().max(2**53-1),oi=U.max(2147483647),si=_({operationTimeoutMs:oi.optional(),connectTimeoutMs:oi.optional(),liveStepTimeoutMs:oi.optional(),maxWireRecordBytes:U.optional(),maxWireResponseBytes:U.optional(),maxEventBytes:U.optional(),maxStepBytes:U.optional(),maxStepEvents:U.optional(),maxPendingToolCalls:U.optional()}),ci=[`text`,`image`,`speech`,`transcription`,`live`,`decision`,`embedding`],li=w({id:o().regex(/^[A-Za-z][A-Za-z0-9]*$/),name:o().min(1),description:o().min(1),endpoints:re(y(ci),o().min(1)),operationNames:re(y(ci),o().regex(/^[a-z][a-z0-9_]*$/))});function ui(e,t){return new T(`config`,j(`protocol.definition`,{id:e,issues:t}))}function di(e){let t=li.safeParse(e);if(!t.success)throw ui(String(e.id),he(t.error))}function fi(e,t,n){let r=Object.keys(t).toSorted().join(`, `),i=Object.keys(n).toSorted().join(`, `);if(r!==i)throw ui(e,`operationNames name [${i}]; endpoints serve [${r}]`)}function pi(e,t,n,r){if(!n)throw new T(`internal`,j(`protocol.part_schema`,{protocol:e.id,kind:t}));let i=n.safeParse(r);if(!i.success)throw new T(`bad_response`,j(`protocol.part_invalid`,{protocol:e.id,kind:t}),{cause:i.error});return i.data}function mi(e,t){return t.type===`reasoning`?{...t,data:pi(e,`reasoning`,e.reasoning,t.data),origin:{protocol:e.id}}:t.type===`custom`?{type:`custom`,kind:`${e.id}.${t.kind}`,data:pi(e,t.kind,e.custom?.[t.kind],t.data)}:t}async function*hi(e,t){for await(let n of t)yield mi(e,n)}function gi(e,t){let{complete:n,openSession:r}=t;return{...t,...n?{complete:r=>hi(e,n.call(t,r))}:{},...r?{async openSession(n){let i=await r.call(t,n);return{...i,events:()=>hi(e,i.events())}}}:{}}}function _i(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`,j(`protocol.options`,{apiId:t,protocol:e.id,issues:o}))}function W(e){if(di(e),typeof e.create!=`function`||typeof e.options?.safeParse!=`function`)throw ui(e.id,`create and options are required`);return fi(e.id,e.endpoints,e.operationNames),Object.freeze({...e,lineage:Object.freeze([e.id]),create:t=>gi(e,e.create(t))})}function vi(e){return e instanceof Ee?e.shape:void 0}function yi(e,t){let n=e??{},r={};for(let e of t)e in n&&(r[e]=n[e]);return r}function bi(e,t){let n=vi(e.options),r=t.options?vi(t.options):{};if(t.options&&!n)throw new T(`config`,j(`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`,j(`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 xi(e,t,n,r,i){let a={profileType:r.profileType,apiId:r.apiId,options:yi(r.options,n.addedKeys)},o=[],s=t.read?.({...a,...i?{request:i}:{}}),c=e=>{for(let n of e??[])o.push(mi(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?yi(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 Si(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 Ci(e,t,n){let r=t[e]??n[e];return r?{[e]:r}:{}}function wi(e,t){di({...t,endpoints:t.endpoints??{},operationNames:t.operationNames??{}});let n={...e.endpoints,...t.endpoints},r={...e.operationNames,...t.operationNames};fi(t.id,n,r);let i=bi(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}:{},...Ci(`framing`,t,e),...Ci(`error`,t,e),...Ci(`embeddingLimits`,t,e),...Ci(`refusedOptions`,t,e),base:e,lineage:Object.freeze([t.id,...e.lineage]),create:n=>Si(r=>xi(e,t,i,n,r))})}function Ti(e,t){return t.lineage.includes(e)}var Ei=o().regex(pt),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,Di=_({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:Ei.optional().describe(`The slot this model's key is read from, in place of the provider's.`),fallbackKeySlot:Ei.optional().describe(`The slot tried once when the first key is out of quota, rate limited or busy.`),options:I.optional().describe(`What this model's protocol takes beyond the shared settings.`),limits:si.optional().describe(`Theorem's cut-offs for this model's calls; each one left out is no limit.`)}),Oi=Di,ki=Di.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 Ai(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 ji(e,t){let n=e.serves.find(e=>e.protocol.id===t.protocol);if(!n)throw new T(`config`,j(`protocol.not_served`,{provider:e.id,protocol:t.protocol}));return n}function Mi(e,t){return ji(e,t).protocol}function Ni(e,t,n){return Mi(e,t).operationNames[n]}function Pi(e,t,n,r={webSocketHeaders:!0}){let i=ji(e,t),{protocol:a}=i;if(a.endpoints[n]===void 0)throw new T(`unsupported`,j(`protocol.profile_type`,{protocol:a.id,profileType:n}));let o=I.parse(_i(a,t.apiId,t.options)),s=Ai(e,t);if(s.keySlot!==void 0&&s.keySlot===s.fallbackKeySlot)throw new T(`config`,j(`provider.model_fallback_slot`));if((t.keySlot||t.fallbackKeySlot)&&!e.definition.key)throw new T(`config`,j(`protocol.no_key`,{provider:e.id}));let c=i.authorize??e.definition.authorize;if(n===`live`&&c?.webSocketHeaders&&!r.webSocketHeaders)throw new T(`unsupported`,j(`protocol.ws_headers`,{provider:e.id}));return{...t,options:o}}function Fi(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 Ii(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 Li(e){let t=e.structured===void 0?e.text:JSON.stringify(e.structured);return[...t?[{role:`assistant`,content:t}]:[],...e.calls.length?[Ri(e.calls)]:[]]}function Ri(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 zi(e,t){return Object.assign(t=>({sign:n=>e(t,n)}),{webSocketHeaders:t})}var Bi=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))},j(`protocol.endpoint_url`));function Vi(){return zi((e,t)=>t.headers.set(`Authorization`,`Bearer ${e}`),!0)}function Hi(e){return zi((t,n)=>n.headers.set(e,t),!0)}function Ui(e){return zi((t,n)=>n.url.searchParams.set(e,t),!1)}var Wi=w({id:o().regex(/^[a-z][a-z0-9-]*$/),name:o().min(1),description:o().min(1),traceName:o().min(1).optional()});function Gi(e){let t=Wi.safeParse(e);if(!t.success||typeof e.serves!=`function`)throw new T(`config`,j(`protocol.definition`,{id:String(e.id),issues:t.success?`serves is required`:he(t.error)}));return Object.freeze({...e})}function Ki(e,t){let n=e.serves.find(e=>e.protocol.id===t);if(!n)throw new T(`config`,j(`protocol.not_served`,{provider:e.id,protocol:t}));return n}function qi(){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`,j(`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`,j(`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`,j(`protocol.connection`,{provider:o,issues:he(s.error)}));if(s.data!==void 0&&nn.parse(s.data),i.keySlot!==void 0&&Ei.parse(i.keySlot),i.fallbackKeySlot!==void 0&&Ei.parse(i.fallbackKeySlot),i.keySlot&&i.keySlot===i.fallbackKeySlot)throw new T(`config`,j(`provider.fallback_slot`));if((i.keySlot||i.fallbackKeySlot)&&!r.key)throw new T(`config`,j(`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}=Ki({id:o,serves:c},typeof e==`string`?e:e.id);return{protocol:r.id,options:_i(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 Oi.parse({...i,provider:o,apiId:t,...u(e,t,r)})},decisionModel(e,t,n={}){let{options:r,...i}=n;return ki.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`,j(`protocol.provider_missing`,{provider:t,apiId:n}));return r},list:()=>[...e.values()],protocols:()=>[...t.values()]}}var Ji=[`text`],Yi=at,Xi=[`length`,`stream_incomplete`],Zi=new Set([`egress`,`canary`,`prompt_echo`,`provider_tool_leak`]);function Qi(e){return e.kind===`filtered`&&Zi.has(e.native??``)}var $i=1500,ea=new Set(at);function ta(e){return ea.has(e)}new Set(Yi);var na=new Set([`provider_error`,`stream_incomplete`]);function ra(e){return na.has(e)}function ia(e){return typeof e==`object`&&e.reason?{kind:`cancelled`,native:e.reason}:{kind:`cancelled`}}function aa(e,t){return!e||!ta(e.kind)?!1:(t?.autoContinue??Xi).includes(e.kind)}function oa(e){if(e.type!==`live`)return e.turnBehaviour?.resumption}function sa(e){return e.type===`text`&&e.turnBehaviour?.allowSteering!==!1}function ca(e){return e.type===`text`||e.type===`live`?e.turnBehaviour?.allowSteering!==!1:!1}function la(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}:ua((e||``).toLowerCase(),r,n):{kind:`stream_incomplete`,native:n}}function ua(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 da(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 fa(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 pa(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 ma(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 ha(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 ga(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 _a(e){return ya(e.flatMap(e=>e.type===`tokens`?[e.tokens]:[]))}function va(e){return ya(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 ya(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=ma(e),l=ha(e),u=ga(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 ba=1e3,xa=400,Sa=new Set([`http_request`,`http_response`,`http_error_body`,`http_throw`]),Ca=new Set([`text`,`image`,`audio`]),wa={completed:`stop`,length:`length`,tool:`tool_call`,filtered:`content_filter`,provider_error:`error`};function Ta(e){let[t]=e.split(`/`);return t===`application`||t===`text`||!t?`document`:t}function Ea(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,...We(e.data)}}function Da(e){let t=K(e).map(Ea);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(Ea)]};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 Oa=new WeakMap;function ka(e){let{conversation:t}=e;if(`previous`in t){let e=Oa.get(t.previous),n=[...e?.input??[],...e?.output?[e.output]:[]];return{input:[...n,...t.continuation.map(Da)],sentFrom:n.length}}let n=t.input.length>0?[{role:`user`,parts:t.input.map(Ea)}]:[];return{input:[...t.history.map(Da),...n]}}var Aa=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(Pa(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=Ra(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=Na(e);this.calls.set(e.callId,t),this.push(t);return}let t=this.calls.get(e.callId),n=e.phase===`error`?ja(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 ja(e){let t=q(e?.details)?.raw;return typeof t==`string`?t:void 0}function Ma(e){return ja(e.failure)??JSON.stringify(e.arguments)}function Na(e){return{type:`tool_call`,id:e.callId,name:e.name,arguments:A(Ma(e))}}function Pa(e){return{type:`blob`,modality:Ta(e.mimeType),mime_type:e.mimeType,...We(e.data)}}var Fa=`_call`,Ia=`_result`;function La(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(Fa)){let e=typeof n?.id==`string`?n.id:void 0;return{side:`call`,name:t.slice(0,-5),id:e}}if(t.endsWith(Ia)){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 Ra(e,t){let n=La(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 za(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 La(t)||t.kind===`input_transcription`||t.kind===`output_transcription`?void 0:{provider:t.provider,...t.raw?{raw:N(t.raw)}:{}}}default:return}}function Ba(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 Va={output_stream:`output_delta`,stream_canary:`output_delta`,tool_draft:`tool_call`,live_output:`live_outbound`};function Ha(e,t,n,r){return{...n?Ba(n):{stage:r.stage,trust:r.trust,action:`allow`,hits:[]},check:e,duration_ms:t}}function Ua(e){let t={};for(let n of[`input`,`output`])for(let[r,i]of Object.entries(e?.[n]??{})){let e=Ca.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 Wa(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),...Ua(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 Ga(e){if(e)return e.provider}function Ka(e,t){return t===`live`?`speech`:e.structured?`json`:e.image?`image`:e.speech?`speech`:`text`}function qa(e,t,n,r){let i=Ga(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":Ka(e,n),...Ja(e)}}function Ja(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":Ya(r,e)}:{}}}function Ya(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 Xa(e,t){return!t||typeof t!=`object`?{}:Object.fromEntries(Object.entries(t).map(([t,n])=>[`${e}.${t}`,[String(n)]]))}function Za(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 Qa=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||!Sa.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`),...Za(e.url),"http.request.resend_count":this.tries,...typeof e.keySlot==`string`?{"theorem.key_slot":e.keySlot}:{},...X(`theorem.retry.backoff_ms`,t),...Xa(`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),...Xa(`http.response.header`,e.headers)}),t!==void 0&&t>=xa?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()/ba}))}close(e){this.current&&=(this.current.end(e),this.last=this.current,void 0)}};function $a(e,t,n){return e!==void 0&&e>=xa?{code:`ERROR`,message:String(e)}:n===void 0?t?{code:`UNSET`}:{code:`OK`}:{code:`ERROR`,message:Be(n)}}function eo(e){return e instanceof Error?e.name:`Error`}function to(e,t){e.event(`exception`,{"exception.type":eo(t),"exception.message":A(Qe(t)),...t instanceof Error&&t.stack?{"exception.stacktrace":A(t.stack)}:{}})}function no(e,t){to(e,t);let n=Be(t);e.set({"error.type":n}),e.end({code:`ERROR`,message:n})}function ro(e,t){for(let[n,r]of t)r.decided||e.event(`theorem.guardrail`,{...Ha(n,r.ms,void 0,{stage:Va[n],trust:`untrusted`}),runs:r.runs})}function io(e){let t=0;for(let n of e.values())t+=n.ms;return t>0?{"theorem.guardrail.stream_ms":t}:{}}var ao=new Set([`cancelled`,`interrupted`]);function oo(e,t){let n=e!==void 0&&ao.has(e.kind),r=e&&!n?wa[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 so(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 co(e,t){let{req:n,usage:r,transport:i,operation:a}=t,o=ka(r),s=e(a?`${a} ${n.apiId}`:n.apiId,{kind:`CLIENT`,attributes:{...qa(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 Qa(s),l=new Aa,u=new Aa,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()/ba}));let t=za(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`,Ba(e)):(t.decided=!0,s.event(`theorem.guardrail`,{...Ha(g,t.ms,e,{stage:Va[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&&to(s,e.thrown),ro(s,h);let t=d.at(-1),n=e.thrown===void 0?t?.errorKind:Be(e.thrown),a=oo(e.stop,n),o={role:`assistant`,parts:l.parts,...X(`finish_reason`,a.finish)},{input:m}=ka(r);Oa.set(r,{input:m,output:o});let g=u.parts.length>0?[{role:`user`,parts:u.parts}]:[];c.close($a(c.lastStatus,a.stopped,e.thrown)),s.set({"gen_ai.input.messages":[...m,...g],"gen_ai.output.messages":[o],...e.tokens?Wa(e.tokens):{},...so(f,a.stopped?void 0:p,i),...X(`theorem.stop.kind`,e.stop?.kind),...io(h),...a.attributes}),s.end(a.status)}}}function lo(e){let t=[...e?.attachments??[],...e?.voice??[]].map(e=>`uri`in e?{type:`uri`,modality:Ta(e.mimeType),mime_type:e.mimeType,uri:e.uri}:{type:`blob`,modality:Ta(e.mimeType),mime_type:e.mimeType,...We(e.data)}),n=[...e?.text?[{type:`text`,...A(e.text)}]:[],...t];return n.length>0?[{role:`user`,parts:n}]:[]}function uo(e){return(e??[]).map(e=>({traceparent:e.traceparent,attributes:{"theorem.link.kind":e.kind,...X(`theorem.stop.kind`,e.stop)}}))}function fo(e){return{...X(`gen_ai.conversation.id`,e.conversationId),...X(`theorem.project.id`,e.projectId)}}function po(e){return{...X(`theorem.request.effort`,e.effort),...X(`theorem.request.model_select`,e.model)}}function mo(e){return{kind:`INTERNAL`,attributes:{"gen_ai.operation.name":`invoke_agent`,"gen_ai.agent.name":e.profile,...fo(e),"gen_ai.input.messages":lo(e.input),...po(e)},links:uo(e.links)}}var ho=new Set([`completed`,`length`,`generation_complete`]);function go(e,t){let n=_a(t.seen),r=fa(t.seen,e=>e.type===`done`),i=r?.stop.kind,a=fa(t.seen,e=>e.type===`error`),o=a?.error,s=t.thrown!==void 0;s&&to(e,t.thrown);let c=s||i!==void 0&&ra(i),l=s?Be(t.thrown):a?.errorKind??i,u={role:`assistant`,parts:t.delivered.parts,...X(`finish_reason`,oo(r?.stop,void 0).finish)};e.set({"gen_ai.output.messages":[u],...n?Wa(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&&!ho.has(i)?{code:`UNSET`}:{code:`OK`})}function _o(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*vo(e){if(typeof e==`string`)yield e;else if(Array.isArray(e))for(let t of e)yield*vo(t);else if(typeof e==`object`&&e)for(let t of Object.values(e))yield*vo(t)}function yo(e,t){let n=new Set;for(let r of e)for(let e of vo(r))for(let r of _o(e,t))typeof r!=`string`&&n.add(r.reference);return Object.fromEntries(Object.entries(t).filter(([e])=>n.has(e)))}var bo=/\{\{?([^{}]*)\}\}?/g,xo=/[\p{Cc}\p{Cf}]/gu,So=/^-?\d+$/,Co=/^(\d{4})-(\d{2})-(\d{2})(?:[T ](\d{2}):(\d{2})(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:?\d{2})?)?$/,wo=new Intl.NumberFormat(void 0,{maximumFractionDigits:2}),To=new Intl.PluralRules(`en`),Eo=new Intl.DateTimeFormat(void 0,{dateStyle:`medium`,timeZone:`UTC`}),Do=new Intl.DateTimeFormat(void 0,{dateStyle:`medium`,timeStyle:`short`,timeZone:`UTC`}),Oo=/^\+\s+/,ko=/:(?:\s|$)/,Ao=/^(\S+) is (?:(not) )?(\S.*)$/;function jo(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 Mo(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 No(e,t){let n=e;for(let e of t)if(Array.isArray(n)){if(e===`length`)n=n.length;else if(So.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 Po(e){let t=Co.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?Eo:Do).format(s)}function Fo(e){if(typeof e==`number`)return Number.isFinite(e)?wo.format(e):void 0;if(typeof e!=`string`)return;let t=e.replace(xo,` `).replace(/\s+/g,` `).trim();return(Po(t)??t)||void 0}function Io(e){let t=[];for(let n of e.replace(/\s+/g,` `).split(` and `)){let[,e,r,i]=Ao.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 Lo(e){let t=Oo.test(e),n=e.replace(Oo,``).trimStart();if(!/^when(\s|$)/.test(n))return{joined:t,when:[],text:n};let r=n.search(ko);return r<0?{joined:t,when:`unreadable`,text:``}:{joined:t,when:Io(n.slice(4,r)),text:n.slice(r+1).trimStart()}}function Ro(e){let t=Lo(e);return{...t,text:t.text.trim()}}function zo(e){let t=typeof e==`string`?[e]:e,n=[];return t.forEach((e,t)=>{let r=Ro(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 Bo(e){let[t]=Mo(e,[`input`]);return t?.side===`input`?t.keys:void 0}function Vo(e,t){let n=Bo(e.path);if(!n)return!1;let r=No(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 Ho(e){return e.length<=1?e[0]??``:`${e.slice(0,-1).join(`, `)}${e.length>2?`,`:``} and ${e.at(-1)}`}function Uo(e){return e.replace(/([a-z\d])([A-Z])/g,`$1 $2`).replace(/[_-]+/g,` `).trim().toLowerCase()}function Wo(e,t){if(t===`unreadable`)return;let n=e.find(e=>typeof e==`number`&&Number.isFinite(e));if(n!==void 0)return`${wo.format(n)} ${To.select(n)===`one`?t.one:t.other}`}function Go(e,t,n){let r=!1,i=e.replace(bo,(e,i)=>{let{path:a,fallback:o,forms:s}=jo(i),c=a?Mo(a,n).map(e=>No(t[e.side],e.keys)):[],l=s?Wo(c,s):c.map(Fo).find(Boolean);return l===void 0&&o===void 0&&(r=!0),l??o??``}).replace(/\s+/g,` `).trim();return r||!i?void 0:i}function Ko(e,t){if(e===void 0)return;let n=`output`in t?[`input`,`output`]:[`input`];for(let r of zo(e)){let e=r.lines.flatMap(({line:e})=>{if(e.when===`unreadable`||!e.when.every(e=>Vo(e,t.input)))return[];let r=Go(e.text,t,n);return r===void 0?[]:[r]});if(e.length)return Ho(e)}}var qo=[`value`,`group`,`flag`,`missing`];function Z(e){return(Array.isArray(e.type)?e.type:[e.type]).filter(e=>typeof e==`string`&&e!==`null`)}function Jo(e){return[e.anyOf,e.oneOf,e.allOf].flatMap(e=>Array.isArray(e)?e.filter(E):[])}function Yo(e){let t=qo.find(t=>e.some(e=>e.holds===t))??`missing`;return{holds:t,instead:e.filter(e=>e.holds===t).flatMap(e=>e.instead??[])}}function Xo(e,t){let n=e=>t?`${t}.${e}`:e;if(!E(e))return[];let r=Jo(e);return r.length?r.flatMap(e=>Xo(e,t)):Z(e).includes(`array`)?[...Zo(e.items,n(`0`)),n(`length`)]:E(e.properties)?Object.entries(e.properties).flatMap(([e,t])=>Zo(t,n(e))):[]}function Zo(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=Jo(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?Xo(e,t):[t]}function Qo(e,t,n){if(!E(e)||`$ref`in e)return{holds:`value`};let r=Jo(e);if(r.length)return Yo(r.map(e=>Qo(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:Xo(e,n)}:{holds:`value`};let s=n?`${n}.${a}`:a,c={holds:`missing`,instead:Xo(e,n)};if(i.includes(`array`)){if(a===`length`)return o.length?c:{holds:`value`};if(So.test(a))return E(e.items)?Qo(e.items,o,s):{holds:`value`}}return E(e.properties)?Object.hasOwn(e.properties,a)?Qo(e.properties[a],o,s):c:i.length===0||i.includes(`object`)?{holds:`value`}:c}function $o(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 es(e,t,n){for(let r of e.matchAll(bo)){let{path:e,forms:i}=jo(r[1]??``);if(!e)return`Put a field name between the braces, like {${Xo(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=Mo(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=Yo(a.map(({side:e,keys:n,prefixed:r})=>Qo(t[e],n,r?e:``)));if(s.holds===`value`){let n=a.some(({side:e,keys:n})=>is(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}${$o((u.length?u:c).toSorted((e,t)=>p(e)-p(t)))}`}}var ts={texts:`any`,nullable:!0,number:!0};function ns(e){return(Array.isArray(e.type)?e.type:[e.type]).filter(e=>typeof e==`string`)}function rs(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=ns(e);if(n.length===0)return ts;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 is(e,t){if(!E(e)||`$ref`in e)return[ts];let n=Jo(e);if(n.length)return n.flatMap(e=>is(e,t));let[r,...i]=t;if(r===void 0)return[rs(e)];let a=Z(e);if(a.includes(`array`)){if(r===`length`)return i.length?[]:[{texts:`any`,nullable:!1,number:!0}];if(So.test(r))return is(e.items,i)}return E(e.properties)?Object.hasOwn(e.properties,r)?is(e.properties[r],i):[]:a.length===0&&ns(e).length===0?[ts]:[]}function as(e){if(!E(e))return[];let t=Jo(e).flatMap(as),n=E(e.properties)?Object.keys(e.properties):[];return[...new Set([...n,...t])]}function os(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 ss(e,t,n=`this tool's input`){let r=Bo(e.path);if(!r)return`A "when" reads what the model sent; "${e.path}" is only there once the call is done.`;let i=Qo(t,r,``);if(i.holds===`missing`){let r=as(t).slice(0,4),i=r.length?` Try ${os(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=is(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 ${os(o)}.`:``;return`"${e.path}" is never "${e.expected}".${s}`}function cs(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=ss(n,t.input);if(e)return e}return!e.text&&(r||e.when.length)?`It has no wording to show.`:es(e.text,t,n)}function ls(e){if(e.when===`unreadable`||e.when.length)return!1;let t=!1,n=e.text.replace(bo,(e,n)=>{let{fallback:r}=jo(n);return r===void 0&&(t=!0),r??``});return!t&&n.trim().length>0}function us(e){let t=e.map(e=>e.lines.some(({line:e})=>ls(e))),n=t.slice(0,-1).indexOf(!0);if(n>=0)return`Line ${e[n]?.lines.find(({line:e})=>ls(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 ds={},fs=new WeakMap;function ps(e){let{input:t}=e,n=`output`in e?e.output:ds;if(typeof t!=`object`||!t||typeof n!=`object`||!n)return;let r=fs.get(t);r||(r=new WeakMap,fs.set(t,r));let i=r.get(n);return i||(i=new Map,r.set(n,i)),i}function ms(e,t){let n=ps(t),r=JSON.stringify(e);if(n?.has(r))return n.get(r);let i=hs(e,t);return n?.set(r,i),i}function hs(e,t){let n=`output`in t?[`input`,`output`]:[`input`],r=typeof e!=`string`,i=zo(e);for(let{line:e,number:a}of i.flatMap(e=>e.lines)){let i=cs(e,t,n,r);if(i)return r?`Line ${a}: ${i}`:i}return r?us(i):void 0}var gs=w({kind:C(`auth_scope_refused`),slot:o(),requested:b(o()),declared:b(o())}),_s={tool_arguments:`tool_call`,taint:`tool_call`,destination:`tool_call`,tool_result:`tool_result`,tool_failure:`tool_result`,network:`network`,network_request:`network`},vs=new WeakSet;function ys(e,t,n,r){e&&(r&&vs.add(r),e.event(`theorem.guardrail`,Ha(t,n,r,{stage:_s[t],trust:`untrusted`})))}function bs(e){return e?`execute_tool ${e}`:`execute_tool`}function xs(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(Ma(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 Ss(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 Cs={ok:`OK`,error:`ERROR`,denied:`UNSET`,gated:`UNSET`,paused:`UNSET`,cancelled:`UNSET`};function ws(e,t){let n=e(bs(t.name),xs(t));return{span:n,observe:e=>{if(e.type===`guardrail`&&!vs.has(e.guardrail)&&n.event(`theorem.guardrail`,Ba(e.guardrail)),e.type===`tool`&&e.tool.phase===`gate`&&n.event(`theorem.gate`,Ss(e.tool.gate)),e.type===`tool`&&e.tool.phase===`progress`){let t=gs.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&&to(n,e.thrown);let t=e.outcome===`error`?e.failure?.kind??(e.thrown===void 0?void 0:Be(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(Ea)}:{},...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=Cs[e.outcome];n.end(r===`ERROR`&&t?{code:r,message:t}:{code:r})}}}function Ts(e){return e.modelText===void 0?Ve(yr(e.finding,e.data),Je):e.modelText}var Es=`Tool error (`;function Ds(e){return e.startsWith(Es)}function Os(e){return{finding:`${Es}${e.code}): ${e.message}`,...e.details===void 0?{}:{data:{details:e.details}}}}function ks(e){return Os({...e,message:Ve(e.message,Je)})}function As(e,t){return{type:`tool`,tool:{...t,name:e.name,callId:e.callId,...e.operationId?{operationId:e.operationId}:{},at:Date.now()}}}function js(e,t,n,r){return Ko(n?.activityFailed,{input:r})??j(`tool.activity_failed`,{tool:Uo(e)},t)}function Ms(e){return e.activityFailed??js(e.name)}function Ns(e,t,n=Ts(ks(t))){return As(e,{phase:`error`,failure:t,readBack:n,activityPast:Ms(e)})}function Ps(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 Fs(e){return`call_${e}_${crypto.randomUUID()}`}function Is(e){return e===void 0?{}:E(e)?e:{value:e}}function Ls(e){return e instanceof Error?e.message:String(e)}function Rs(e,t){return As(e,{phase:`warning`,warning:{code:`sources_invalid`,message:t,severity:`warning`}})}function*zs(e,t,n){let r;try{r=t(n)}catch(t){yield Rs(e,`sources threw: ${Ls(t)}`);return}if(!Array.isArray(r)){yield Rs(e,`sources must return an array`);return}let i=[],a=[];r.forEach((e,t)=>{let n=wn.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 Rs(e,`sources not cited: ${a.join(` | `)}`)),i.length>0&&(yield{type:`citation`,sources:i,callId:e.callId})}function Bs(e,t,n,r){let i=n.resume?.edited,a=Ko(e.labels?.activity,{input:t});return As(r,{phase:`running`,...i?{edited:{from:i.from,to:Is(t)}}:{},...a?{activity:a}:{}})}var Vs=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*Hs(e,t,n,r,i){return qe(n.signal),yield Bs(e,t,n,r),new Vs(i&&(()=>i(t)))}function Us(e,t,n){qe(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:j(`tool.input_invalid`,{},n.profile.labels),details:r.error.flatten()}}}function Ws(){return{stage:`network`,trust:`untrusted`,action:`block`,hits:[{rule:ut.blocked,severity:`high`}]}}function*Gs(e,t=Ws()){return yield{type:`guardrail`,guardrail:t},{code:`network_blocked`,kind:`blocked`,message:Ls(e)}}function*Ks(e,t,n){let r=performance.now();try{let i=ei(e,Js(t));return ys(n,`network`,performance.now()-r,void 0),{ok:!0,url:i}}catch(e){let t=Ws();return ys(n,`network`,performance.now()-r,t),{ok:!1,failure:yield*Gs(e,t)}}}function qs(e){let t=0,n=!1,r=!1;return{onCheck:e=>{t+=e,n=!0},record:i=>{!r&&n&&(r=!0,ys(e,`network_request`,t,i))}}}function Js(e){return Ir(e.profile.guardrails).network}function Q(e,t,n){return C(e).meta({title:t,description:n})}var Ys=_({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.`)}),Xs=/^(gemini-embedding-001|text-embedding-|embedding-)/,Zs={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:[]},$s={query:`RETRIEVAL_QUERY`,document:`RETRIEVAL_DOCUMENT`};function ec(e,t){return t===`query`?`task: search result | query: ${e}`:`title: none | text: ${e}`}function tc(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?ec(e.text,t):e.text}:e.type===`media`?{inlineData:{mimeType:e.mimeType,data:e.data}}:{fileData:{mimeType:e.mimeType,fileUri:e.uri}})}function nc(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 rc(e,t,n){let r={content:{parts:tc(e,n.taskField?void 0:n.task)}},i=n.taskField&&n.task?$s[n.task]:t.taskType;return i&&(r.taskType=i),t.outputDimensionality&&(r.outputDimensionality=t.outputDimensionality),r}var ic=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:Ys,embeddingLimits:e=>Xs.test(e)?Qs:Zs,refusedOptions:e=>Xs.test(e)?[]:[`taskType`],create(e){return{async embed(t){let n=_i(ic,e.apiId,t.options),r={taskField:Xs.test(e.apiId),...t.task?{task:t.task}:{}},i=Array.isArray(t.input)?t.input:[t.input],a=i.length===1?rc(i[0],n,r):{requests:i.map(t=>({model:`models/${e.apiId}`,...rc(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`?nc({embedding:e}):[],dimensions:e&&typeof e==`object`?nc({embedding:e}).length:0}))}}}}}),ac=_({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 oc(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 sc=W({id:`ollamaEmbeddings`,name:`Ollama Embeddings`,description:`Ollama’s local embedding endpoint.`,endpoints:{embedding:`/api/embed`},operationNames:{embedding:`embeddings`},options:ac,embeddingLimits:()=>({media:[]}),create(e){return{async embed(t){let n=ac.parse(t.options??{}),r=e.send({model:e.apiId,input:oc(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}))}}}}}),cc=_({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`.")}),lc={media:[{accept:[`image/*`]}]};function uc(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 dc(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=vt(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 fc=W({id:`openRouterEmbeddings`,name:`OpenRouter Embeddings`,description:`OpenRouter embedding models, including supported multimodal models.`,endpoints:{embedding:`/embeddings`},operationNames:{embedding:`embeddings`},options:cc,embeddingLimits:()=>lc,create(e){return{async embed(t){let n=cc.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(uc)};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=dc(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}}:{}}}}}}),pc=100,mc=599,hc=new Set([`API_KEY_INVALID`]);function gc(e){return Array.isArray(e)&&e.some(e=>{let t=q(e)?.reason;return typeof t==`string`&&hc.has(t)})}var _c={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},vc=new Set([`safety`,`recitation`,`language`,`prohibited_content`,`spii`,`blocklist`,`image_safety`,`image_prohibited_content`,`image_recitation`,`image_other`,`content_blocked`]);function yc(e,t){if(e===`cancelled`)return new T(`cancelled`,t);if(vc.has(e))return new T(`safety`,t);let n=_c[e];return n===void 0?new T(`bad_response`,t):new T(Xe(n),t)}function bc(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 gc(a)?new T(`auth`,o):typeof n==`number`&&n>=pc&&n<=mc?new T(Xe(n),o):typeof n==`string`?yc(n,o):new T(`bad_response`,o)}function xc(e,t,n){return e?.kind===`auth`?e:new T(Xe(t),e?.message??n)}var Sc=_({location:_({latitude:v().min(-90).max(90),longitude:v().min(-180).max(180)})}),Cc=[`googleSearch`,`googleMaps`,`urlContext`,`codeExecution`],wc={googleSearch:`google_search`,googleMaps:`google_maps`,urlContext:`url_context`,codeExecution:`code_execution`};function Tc(e){return e.filter(e=>Cc.includes(e.id))}function Ec(e){let t=Cc.find(t=>t===e.id);if(!t)throw new T(`config`,`Builtin '${e.id}' is not a Google tool`);return t}function Dc(e){let t=Ec(e),n=wc[t];if(t===`googleMaps`&&e.args){let{location:t}=Sc.parse(e.args);return{type:n,latitude:t.latitude,longitude:t.longitude}}return{type:n}}function Oc(e){let t=Ec(e);if(e.args)throw new T(`unsupported`,`Builtin '${t}' takes no args on Google Live`);return{[t]:{}}}function kc(e){return{type:`text`,text:`[${e.type}: sent in the next message]`}}function Ac(e){return{type:`text`,text:`Files from ${e.name?`the ${e.name} result`:`a tool result`}:`}}function jc(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:kc(e))}),r.push(Ac(a),...e))}return i(),n}var Mc={type:`text`,text:`Files the assistant sent:`};function Nc(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:kc(e))}),n.push(Mc,...e))}return n.length>0&&t.push({role:`user`,parts:n}),t}function Pc(e){let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t}function Fc(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 Ic(e){let t=Fc(e);if(!t.ok)throw new T(`bad_response`,t.error);return t.value}function Lc(e,t){let n=e.name.trim(),r={name:n,callId:e.id??Fs(n)},i={stepId:e.stepId,stepCallCount:e.stepCallCount};if(!n)return Rc(r,`function call is missing a name`,t,i);let a=Fc(t);return a.ok?[Ps(r,a.value,i)]:Rc(r,a.error,a.raw,i)}function Rc(e,t,n,r={}){return[Ps(e,{},r),Ns(e,{code:`malformed_arguments`,kind:`bad_response`,message:t,details:{raw:n}})]}var zc=[`minimal`,`low`,`medium`,`high`],Bc=[`pcm`];function Vc(e){if(e&&!zc.includes(e))throw new T(`unsupported`,`Gemini does not take the '${e}' thinking level (${zc.join(`, `)})`)}function Hc(e){return e.replaceAll(/[A-Z]/g,e=>`_${e.toLowerCase()}`)}function Uc(e){if(Array.isArray(e))return e.map(Uc);if(e&&typeof e==`object`){let t={};for(let[n,r]of Object.entries(e))n===`schema`||n===`parameters`||n===`arguments`?t[Hc(n)]=r:t[Hc(n)]=Uc(r);return t}return e}function Wc(e){return Fi(e)}var Gc=`user_input`;function Kc(e){return{type:Gc,content:e.map(Wc)}}function qc(e){let t=K(e);return t.length>0?t.map(Wc):[{type:`text`,text:``}]}var Jc=new Set([`text`,`image`,`video`]);function Yc(e){let t=K(e);return{type:`function_result`,...Pc({name:e.name,call_id:e.tool_call_id}),result:t.length>0?t.map(Wc):[{type:`text`,text:``}]}}function Xc(e,t){let n={type:`function_call`,id:e.id,name:e.function.name,arguments:Ic(e.function.arguments)};return t?[{type:`thought`,signature:t},n]:[n]}var Zc=_({call:v().int().min(0),signature:o().min(1)});function Qc(e,t){for(let n of e.reasoning??[]){let e=Zc.safeParse(n.data);if(e.success&&e.data.call===t)return e.data.signature}}function $c(e,t){return{type:e===`assistant`?`model_output`:`user_input`,content:qc(t)}}function el(e){if(e.role===`assistant`&&e.tool_calls&&e.tool_calls.length>0){let t=[];K(e).length>0&&t.push($c(`assistant`,e));for(let[n,r]of e.tool_calls.entries())t.push(...Xc(r,Qc(e,n)));return t}return e.role===`assistant`?[$c(`assistant`,e)]:[$c(`user`,e)]}function tl(e){return jc(e,Jc).flatMap(e=>e.role===`tool`?[Yc(e)]:el(e))}function nl(e){return[{type:`text`,mimeType:`application/json`,schema:e}]}function rl(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&&!Bc.includes(n))throw new T(`unsupported`,`Gemini speech returns ${Bc.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=nl(e.structured.jsonSchema))}function il(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 al=new Set([`gemini-3.8-flash-tts`,`gemini-3.8-flash-lite-tts`]);function ol(e,t,n){if(!al.has(n))return{type:Gc,content:[{type:`text`,text:`Read the following aloud. ${t.trim()}\n`},...e.map(Wc)]};let r=[{type:`speech_metadata`,style:t}];return{type:Gc,content:e.map(Wc).map(e=>e.type===`text`?{...e,annotations:r}:e)}}function sl(e){return{type:`function`,name:e.name,description:e.description,parameters:e.parameters}}function cl(e){let t=[];for(let n of e.builtins)t.push(Dc(n));for(let n of e.wireTools??[])t.push(sl(n));return t}function ll(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 ul(e){if(e.continuation&&e.continuation.length>0)return tl(ll(e.continuation));let t=tl(ll(e.history??[]));if(e.input.length>0||t.length===0){let n=e.speech?.style;t.push(n?ol(e.input,n,e.apiId):Kc(e.input))}return t}function dl(e,t){e.store!==void 0&&(t.store=e.store),e.previousInteractionId&&(t.previousInteractionId=e.previousInteractionId),e.system&&(t.systemInstruction=e.system);let n=cl(e);n.length>0&&(t.tools=n)}function fl(e){let t={temperature:e.temperature,maxOutputTokens:e.maxOutputTokens};return e.speech?il(e,t):(Vc(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:ul(e),generationConfig:t}}function pl(e){let t=fl(e);return rl(e,t),dl(e,t),Uc(t)}var ml=16,hl=new Set([`audio/pcm`,`audio/l16`]);function gl(e,t,n){for(let r=0;r<n.length;r++)e.setUint8(t+r,n.charCodeAt(r))}function _l(e){if(e===void 0||!/^\d+$/.test(e))return;let t=Number(e);return t>0?t:void 0}function vl(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 yl(e){let{essence:t,params:n}=vl(e);if(!hl.has(t))return;let r=_l(n.get(`rate`));if(r===void 0)return;let i=n.has(`channels`)?_l(n.get(`channels`)):1;if(i!==void 0)return{sampleRate:r,channels:i}}function bl(e,t){let{sampleRate:n,channels:r}=t,i=r*ml/8,a=n*i,o=e.length,s=new ArrayBuffer(44+o),c=new DataView(s);return gl(c,0,`RIFF`),c.setUint32(4,36+o,!0),gl(c,8,`WAVE`),gl(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,ml,!0),gl(c,36,`data`),c.setUint32(40,o,!0),new Uint8Array(s,44).set(e),new Uint8Array(s)}function xl(e){let t=yl(e.mimeType);if(!t)return e;let n=bl(vt(e.data),t);return{mimeType:`audio/wav`,data:St(n)}}function Sl(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 Cl(e){try{return{type:`structured`,structured:JSON.parse(e)}}catch(e){return D(new T(`bad_response`,`structured output was not valid JSON`,{cause:e}))}}function wl(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 Tl(e){if(!e)return[];let{grounding:t,sources:n}=e;return[{type:`grounding`,grounding:t},...n.length>0?[{type:`citation`,sources:n}]:[]]}function El(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 Dl(e){return{maps:{title:e.title,uri:e.uri,...e.placeId?{placeId:e.placeId}:{}}}}function Ol(e){let t=J(e.uri);if(t)return{type:`web`,uri:t,title:J(e.title)??t}}function kl(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 Al(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 jl(e){if(Array.isArray(e))for(let t of e){let e=J(q(t)?.search_suggestions);if(e)return e}}function Ml(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 Nl(e,t){if(Array.isArray(t))for(let n of t)kl(e,Ml(n))}function Pl(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?El(t):void 0;r&&kl(e,r)}}}function Fl(e){let t=[];if(Nl(t,e.annotations),Array.isArray(e.content))for(let n of e.content)Nl(t,q(n)?.annotations);Pl(t,e.result);let n=[];for(let e of t)e.type===`maps`&&Al(n,Dl(e));let r=jl(e.result);if(r||t.length!==0)return{grounding:{metadata:e,...n.length>0?{chunks:n}:{},...r?{searchHtml:r}:{}},sources:t}}function Il(e,t){if(!e)return t;if(!t)return e;let n=[];for(let r of[...e.grounding.chunks??[],...t.grounding.chunks??[]])Al(n,r);let r=[...e.sources];for(let e of t.sources)kl(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 Ll(e){let t=q(e.delta);return Tl(t?Fl(t):void 0)}function Rl(e){let t;for(let n of e){let e=q(n);e&&(t=Il(t,Fl(e)))}return Tl(t)}function zl(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&&kl(r,Ol(t))}let i=J(q(t.searchEntryPoint)?.renderedContent);return Tl({grounding:{metadata:t,...n.length>0?{chunks:n}:{},...i?{searchHtml:i}:{}},sources:r})}function Bl(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 Vl(e,t){if(e||t)return{...e?{input:e}:{},...t?{output:t}:{}}}function Hl(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 Ul(e){let t=q(e);return t?.type===`text`&&typeof t.text==`string`?t.text:``}function Wl(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 Gl=[[`/9j/`,`image/jpeg`],[`iVBORw0KGgo`,`image/png`],[`UklGR`,`image/webp`]];function Kl(e){return Gl.find(([t])=>e.startsWith(t))?.[1]}function ql(e){let{data:t}=e;if(typeof t!=`string`||!t)return[];let n=Wl(e)??(e.type===`image`?Kl(t):void 0);return n?[{type:`media`,media:{mimeType:n,data:t}}]:[]}function Jl(e,t){return t?[{type:e,text:t}]:[]}function Yl(e){return e===`code_execution_call`||e===`code_execution_result`}function Xl(e){return e.startsWith(`google_`)||e===`url_context_call`||e===`url_context_result`}function Zl(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`?Zl(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 $l(e){let t=q(e);if(!t)return[];switch(t.type){case`thought_summary`:return Jl(`thought`,Ul(t.content));case`text`:return Jl(`text`,typeof t.text==`string`?t.text:``);case`image`:case`audio`:return ql(t);default:return[]}}function eu(e){return(Array.isArray(e.summary)?e.summary:[]).flatMap(e=>Jl(`thought`,Ul(e)))}function tu(e){return(Array.isArray(e.content)?e.content:[]).flatMap(e=>{let t=q(e);return t?.type===`text`?Jl(`text`,typeof t.text==`string`?t.text:``):t?.type===`image`||t?.type===`audio`?ql(t):[]})}function nu(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 pa({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:Vl(Bl(t.input_tokens_by_modality,`tokens`),Bl(t.output_tokens_by_modality,`tokens`)),grounding:Hl(t.grounding_tool_count)})}function ru(e){let t=nu(e.usage);if(!t)return;let n=typeof e.id==`string`?e.id:void 0;return{type:`tokens`,tokens:t,...n?{interactionId:n}:{}}}function iu(e){let t=[],n=ru(e);n&&t.push(n);let{steps:r}=e;Array.isArray(r)&&t.push(...Rl(r));let i=ou(e);return i&&t.push(i),t}function au(e){let t=J(e.id),n=J(e.model);if(t||n)return{...t?{id:t}:{},...n?{model:n}:{}}}function ou(e){let{status:t}=e;if(typeof t==`string`)return{type:`done`,stop:da(t),...typeof e.id==`string`?{interactionId:e.id}:{}}}function su(){return{text:``,steps:new Map,sawMedia:!1,sawDone:!1,calls:0}}function cu(e){return e===`function_call`||Yl(e)||Xl(e)}function lu(e){return typeof e==`string`&&e.length>0?e:void 0}function uu(e,t){let n=lu(e);n&&(t.thoughtSignature=n)}function du(e,t){let n=lu(e.signature)??t.thoughtSignature;return t.thoughtSignature=void 0,n}function fu(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=du(e,t),a=t.calls++;return[...i?[{type:`reasoning`,data:{call:a,signature:i},origin:{protocol:`geminiInteractions`}}]:[],...Lc({id:n,name:r},e.arguments)]}return Yl(n)?[Ql(e)]:Xl(n)?[Zl(e)]:n===`thought`?(uu(e.signature,t),eu(e)):n===`model_output`?tu(e):[]}function pu(e){return typeof e.index==`number`?e.index:0}function mu(e,t){let n=q(e.step);if(!n)return;let r=String(n.type??``);r===`thought`&&uu(n.signature,t),cu(r)&&t.steps.set(pu(e),{...n})}function hu(e,t){let n=q(e.delta);if(!n)return[];let r=t.steps.get(pu(e));if(!r)return n.type===`thought_signature`&&uu(n.signature,t),$l(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`?wl({id:lu(r.id),name:typeof r.name==`string`?r.name:``,args:t,drafted:e.length}):[]}return Object.assign(r,n),[]}function gu(e,t){let n=pu(e),r=t.steps.get(n);return r?(t.steps.delete(n),fu(r,t)):[]}function _u(e){let t=Yl(String(e.type??``))?Ql(e):Zl(e);return{...t,evidence:{...t.evidence,partial:!0}}}function vu(e){let t=[...e.steps.values()].map(_u);return e.steps.clear(),t}function yu(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:xl(e.media)})))}function bu(e,t){if(e.eventType===`sse_unparsed`)return[D(new T(`bad_response`,`Interactions stream row was not a JSON object`))];let n=bc(e);if(n)return[D(n)];let r=Ll(e);switch(e.event_type){case`step.start`:mu(e,t);break;case`step.delta`:r.push(...hu(e,t));break;case`step.stop`:r.push(...gu(e,t));break;case`interaction.created`:{let n=q(e.interaction);n&&r.push(...xu(n,t));break}case`interaction.completed`:{let n=q(e.interaction);n&&r.push(...xu(n,t),...iu(n));break}}return r}function xu(e,t){let n=Sl(t.response,au(e));return t.response=n.known,n.event?[n.event]:[]}function Su(e,t){return yu(bu(e,t),t)}function Cu(e,t){let n=(Array.isArray(e.steps)?e.steps:[]).flatMap(e=>{let n=q(e);return n?fu(n,t):[]});return yu([...xu(e,t),...n,...iu(e)],t)}function*wu(e,t){e.structured&&t.text&&(yield Cl(t.text))}function Tu(e){return!!e.speech}function Eu(e,t){if(!t.sawMedia){if(Tu(e))return D(new T(`bad_response`,`speech audio was not returned by the model`));if(e.image)return D(new T(`bad_response`,`no image returned from image generation`))}}function Du(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 Ou=_({interactionId:o().min(1)}),ku=_({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 Au(e,t){let n=t.history??[],r=e.options.persistViaInteractionId?t.state?.interactionId:void 0,i=Tc(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(pl(a)))),wroteTools:i.map(e=>e.id)}}function ju(e,t,n){return e.flatMap(e=>{if(e.type!==`done`){let t=Du(e);return t?[t]:[]}let{interactionId:r,...i}=e;return t.done={...i,...n&&r?{state:{interactionId:r}}:{}},[]})}var Mu=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:ku,continuation:{version:1,schema:Ou,keyOptions:[`store`,`persistViaInteractionId`]},reasoning:Zc,error(e){let t=q(e.body);return xc(t?bc(t):null,e.status,`Gemini HTTP ${e.status}`)},create(e){return{async*complete(t){let{wire:n,body:r,wroteTools:i}=Au(e,t),a=t.stream!==!1,o=!!e.options.persistViaInteractionId,s={fold:su()},c={stream:a,wroteTools:i,...a?{path:`/interactions?alt=sse`}:{}};for await(let t of e.send(r,c)){let e=bc(t);if(e)throw e;let n=a?Su(t,s.fold):Cu(t,s.fold);if(yield*ju(n,s,o),n.some(e=>e.type===`error`)){yield*ju(vu(s.fold),s,o);return}}yield*ju(vu(s.fold),s,o),yield*ju([...wu(n,s.fold)],s,o);let l=Eu(n,s.fold);l&&(yield*ju([l],s,o)),yield s.done??{type:`done`,stop:{kind:`stream_incomplete`}}}}}}),Nu=`NON_BLOCKING`;function Pu(e){return{name:e.name,description:e.description,behavior:Nu,parametersJsonSchema:e.parameters??{type:`object`,properties:{}}}}function Fu(e){let t=[];for(let n of e.builtins)t.push(Oc(n));let n=(e.wireTools??[]).map(Pu);return n.length>0&&t.push({functionDeclarations:n}),t}function Iu(e){let t={responseModalities:[`AUDIO`],temperature:e.temperature,maxOutputTokens:e.maxOutputTokens};e.live?.voice&&(t.speechConfig={voiceConfig:{prebuiltVoiceConfig:{voiceName:e.live.voice}}}),Vc(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 Lu(e){let{triggerTokens:t}=e,{targetTokens:n}=e.slidingWindow;return{...t===void 0?{}:{triggerTokens:t},slidingWindow:n===void 0?{}:{targetTokens:n}}}function Ru(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 zu(e){if(e.sessionResumptionHandle)return{handle:e.sessionResumptionHandle};if(e.live?.sessionResumption)return{}}function Bu(e){return e.startsWith(`models/`)?e:`models/${e}`}function Vu(e,t){e?.transcription?.input&&(t.inputAudioTranscription={}),e?.transcription?.output&&(t.outputAudioTranscription={})}function Hu(e){let t=e.live,n=t?.vad?Ru(t.vad):void 0,r=Fu(e),i=zu(e),a=!!(e.history?.length||e.context?.length),o={model:Bu(e.apiId),generationConfig:Iu(e),systemInstruction:{parts:[{text:e.system}]},...r.length>0?{tools:r}:{},...i?{sessionResumption:i}:{},...t?.contextCompression?{contextWindowCompression:Lu(t.contextCompression)}:{},...a?{historyConfig:{initialHistoryInClientContent:!0}}:{},...n?{realtimeInputConfig:n}:{}};return Vu(t,o),{setup:o}}function Uu(e){if(Ii(e))throw new T(`unsupported`,`media references are not supported on geminiLive`);return e}function Wu(e){let t=Uu(e);return{mimeType:t.mimeType,data:t.data}}function Gu(e){return e.type===`text`?{text:e.text}:{inlineData:Wu(e)}}function Ku(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(Gu);return{role:`user`,parts:[{functionResponse:{...Pc({id:e.tool_call_id,name:e.name}),response:{result:n},...r.length>0?{parts:r}:{}}}]}}function qu(e){if(e.role===`tool`)return Ku(e);let t=e.role===`assistant`?`model`:`user`,n=K(e).map(Gu);for(let t of e.role===`assistant`?e.tool_calls??[]:[])n.push({functionCall:{id:t.id,name:t.function.name,args:Ic(t.function.arguments)}});return{role:t,parts:n}}function Ju(e=[],t=[]){return e.length===0&&t.length===0?null:{clientContent:{turns:[...e.map(qu),...t.length?[{role:`user`,parts:t.map(e=>({text:e}))}]:[]],turnComplete:!0}}}function Yu(e){return{clientContent:{turns:[{role:`user`,parts:[{text:e}]}],turnComplete:!1}}}function Xu(e){if(e.type===`text`)return{realtimeInput:{text:e.text}};let t=Uu(e),n={mimeType:t.mimeType,data:t.data};return{realtimeInput:t.type===`audio`?{audio:n}:{video:n}}}function Zu(e){let t=q(e)?.error;return typeof t==`string`?{error:t}:{result:e}}function Qu(e,t,n,r){return $u([{id:e,name:t,output:n,parts:r}])}function $u(e){return{toolResponse:{functionResponses:e.map(({id:e,name:t,output:n,parts:r})=>({id:e,name:t,response:Zu(n),...r?.length?{parts:r.filter(e=>e.type!==`text`).map(Gu)}:{}}))}}}function ed(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 td(e){return Array.isArray(e)?e.flatMap(e=>{let t=q(e);return t?[t]:[]}):[]}function nd(e){let t=[],n=[],r=[];for(let i of td(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=zr(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(ed(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 rd(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 td(n.turns).flatMap(nd);let r=q(e.toolResponse);return r?td(r.functionResponses).map(ed):[]}function id(e){let t=Y(e.promptTokenCount),n=Y(e.responseTokenCount),r=Y(e.thoughtsTokenCount)??0,i=Y(e.toolUsePromptTokenCount)??0;return pa({input:t?t+i:void 0,output:n===void 0?void 0:n+r,thinking:r,toolUse:i,cached:Y(e.cachedContentTokenCount),byModality:Vl(Bl(e.promptTokensDetails,`tokenCount`),Bl(e.responseTokensDetails,`tokenCount`))})}function ad(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 od(){return{calls:new Map}}function sd(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(...Lc({id:o,name:s,stepId:i,stepCallCount:a},r.args))}}function cd(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(D(new T(`bad_response`,`Live cancelled a tool call it never issued: ${String(e)}`))):(t.calls.delete(e),n.push(As({name:r,callId:e},{phase:`cancel`})))}}function ld(e,t){let n=q(e.voiceActivity);n&&t.push({type:`evidence`,evidence:{provider:`google`,kind:`voice_activity`,raw:n}})}function ud(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 dd(e,t){let n=q(e.goAway);if(!n)return;let r=ud(n.timeLeft);t.push({type:`session`,session:{kind:`closing_soon`,...r===void 0?{}:{timeLeftMs:r}}})}function fd(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:xl({mimeType:r,data:i})});let a=q(e.codeExecutionResult);a&&t.push(pd(a))}function pd(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 md(e){let t=q(e)?.text;return typeof t==`string`&&t?t:void 0}function hd(e,t,n,r){let i=md(e);i&&n.push({type:`evidence`,text:i,evidence:{provider:`google`,kind:t,...r?{interim:!0}:{}}})}function gd(e,t){t.push(...zl(e.groundingMetadata));let n=q(e.urlContextMetadata);n&&t.push({type:`evidence`,evidence:{provider:`google`,kind:`url_context`,raw:n}})}function _d(e){let t=q(e.serverContent)?.interactionStatus;if(t===`IN_PROGRESS`||t===`IDLE`)return t}function vd(e,t){let n=_d(e);n&&t.push({type:`session`,session:{kind:n===`IDLE`?`idle`:`working`}})}function yd(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`}}),hd(n.inputTranscription,`input_transcription`,t),hd(n.interimInputTranscription,`input_transcription`,t,!0),hd(n.outputTranscription,`output_transcription`,t);let r=q(n.modelTurn)?.parts;for(let e of Array.isArray(r)?r:[]){let n=q(e);n&&fd(n,t)}gd(n,t),n.turnComplete===!0&&t.push({type:`session`,session:{kind:`turn_complete`}})}function bd(e,t){let n=q(e.usageMetadata),r=n?id(n):void 0;r&&t.push({type:`tokens`,tokens:r})}function xd(e,t){if(!e||typeof e!=`object`)return[];let n=[];return dd(e,n),ad(e,n),sd(e,t,n),cd(e,t,n),ld(e,n),yd(e,n),vd(e,n),bd(e,n),n}var Sd={1006:`network`,1007:`unsupported`,1008:`unsupported`,1011:`unavailable`,1013:`busy`},Cd=/\bquota\b/i,wd=/\bAPI key (?:not valid|expired)\b/i;function Td(e){if(Cd.test(e))return`rate_limit`;if(wd.test(e))return`auth`}function Ed(e,t,n){return new T(Td(t)??Sd[e]??`unavailable`,`Gemini Live WebSocket closed during ${n} (${e}: ${t})`)}function Dd(e){let t=fa(e,e=>e.type===`session`&&e.session.kind===`closing_soon`);return t?.session.kind===`closing_soon`?{timeLeftMs:t.session.timeLeftMs}:void 0}function Od(e){return _d(e)===`IDLE`&&Object.keys(q(e.serverContent)??{}).length===1}function kd(e,t){if(t.some(e=>e.type===`done`&&e.interrupted===!0))return`abort`;let n=_d(e);return n===`IDLE`?`complete`:n===`IN_PROGRESS`?`streaming`:q(e.serverContent)?.turnComplete===!0?`complete`:`streaming`}var Ad=_({liveHandle:o().min(1)}),jd=1e3;function Md(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`):bc(e)??void 0}async function Nd(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 Ed(1006,``,`setup`);let n=t.value;if(n.eventType===`ws_close`)throw Ed(Number(n.code),String(n.reason??``),`setup`);let r=Md(n,`setup`);if(r)throw r;if(n.setupComplete)return}}finally{clearTimeout(n)}}function Pd(e,t){let n=t.state?.liveHandle,r=t.history??[],i=Tc(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(Hu(a)))),wroteTools:i.map(e=>e.id)}}function*Fd(e,t,n){let r=[...e.filter(e=>e.type===`tokens`),...e.filter(e=>e.type!==`tokens`)];for(let e of r){let t=Du(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 Id(e,t,n,r){let i=t=>Rd(e,t),a=od(),o=r,s=!1,c,l;return{closeInfo:()=>l,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??``);l={code:e,reason:t,...e===jd?{}:{error:Ed(e,t,`session`)},...c?{warning:{...c.timeLeftMs===void 0?{}:{timeLeftMs:c.timeLeftMs},closedAfterMs:Math.round(performance.now()-c.atMs)}}:{}};return}let i=Md(r,`session`);if(i)throw i;if(r.setupComplete)continue;let u=xd(r,a),d=Dd(u);d&&(c={...d,atMs:performance.now()});for(let e of u)e.type===`evidence`&&e.sessionResumptionHandle&&(o=e.sessionResumptionHandle);let f=kd(r,u);yield*Fd(u,s&&Od(r)?`streaming`:f,o),f===`complete`?s=!0:r.serverContent&&(s=!1)}},sendText:e=>$(()=>i(Xu({type:`text`,text:e}))),sendAudio:e=>$(()=>i(Xu({type:`audio`,...e}))),sendVideo:e=>$(()=>i(Xu({type:`video`,...e}))),sendContext:e=>$(()=>i(Yu(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(jd,t??`session-closed`))}}var Ld=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:Ad},create(e){return{async openSession(t){let{wire:n,setup:r,wroteTools:i}=Pd(e,t),a=await e.connect(r,{wroteTools:i}),o=a.frames()[Symbol.asyncIterator](),s=()=>a.close(jd,`aborted`);e.signal?.addEventListener(`abort`,s,{once:!0});try{e.signal?.throwIfAborted(),await Nd(o,e)}catch(t){throw e.signal?.removeEventListener(`abort`,s),a.close(jd,`setup-failed`),t}let c=Ju(n.history,n.context);c&&Rd(a,c);for(let e of n.input)Rd(a,Xu(e));return Id(a,o,e,n.sessionResumptionHandle)}}}});function $(e){try{return e(),Promise.resolve()}catch(e){return Promise.reject(e)}}function Rd(e,t){e.send(t,rd(t))}var zd={input:.75,output:4.5,byModality:{input:{audio:3,image:1,video:1},output:{audio:12}}},Bd={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":zd,"gemini-3.8-live-extended-thinking":zd,"gemini-3.1-flash-live-preview":zd,"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}}},Vd=Gi({id:`gemini`,name:`Gemini`,description:`Google's models with an API key, from Google AI Studio.`,traceName:`gcp.gemini`,connection:_({host:Bi.refine(e=>{let t=new URL(e);return t.pathname===`/`&&!t.search&&!t.hash},j(`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:Hi(`x-goog-api-key`),prices:Bd,check:{protocol:Mu,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:Mu,baseUrl:`${n}/v1beta`},{protocol:ic,baseUrl:`${n}/v1beta`},{protocol:Ld,baseUrl:`${r}/ws`,authorize:Ui(`key`)}]}}),Hd=new Set([`message`,`type`,`param`,`code`]);function Ud(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])=>!Hd.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 Wd(e,t){let n=Ud(e.body),r=`${t} HTTP ${String(e.status)}`;return new T(Xe(e.status),n?`${r}: ${n}`:r)}function Gd(e){if(Ii(e))throw new T(`unsupported`,`media references are not supported on openAi`)}function Kd(e){let t=`mp3`;return e.mimeType.includes(`wav`)&&(t=`wav`),{type:`input_audio`,input_audio:{data:e.data,format:t}}}function qd(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}:(Gd(e),e.type===`image`?{type:`image_url`,image_url:{url:`data:${e.mimeType};base64,${e.data}`}}:e.type===`audio`?Kd(e):e.type===`video`?{type:`video_url`,video_url:{url:`data:${e.mimeType};base64,${e.data}`}}:{type:`file`,file:{filename:`document.bin`,file_data:`data:${e.mimeType};base64,${e.data}`}}))}function Jd(e){let t=qd(K(e));if(e.role===`tool`)return{role:`tool`,...Pc({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 Yd=new Set([`text`,`image`]);function Xd(e,t){let n=t?.includeSystem!==!1,r=[];n&&e.system&&r.push({role:`system`,content:e.system});let i=Nc(e.history??[]);for(let e of jc(i,Yd))r.push(Jd(e));return e.input.length>0&&r.push({role:`user`,content:qd(e.input)}),r}function Zd(e){if(e&&e.length!==0)return e.map(e=>({type:`function`,function:{name:e.name,description:e.description,parameters:e.parameters}}))}function Qd(e){return e.replace(/[^A-Za-z0-9_-]/g,`_`).slice(0,64)}function $d(e){if(e)return{type:`json_schema`,json_schema:{name:Qd(e.id),strict:!0,schema:e.jsonSchema}}}function ef(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 tf(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 nf(e,t){let n=tf(e,{audio_tokens:`audio`,video_tokens:`video`}),r=tf(t,{image_tokens:`image`,audio_tokens:`audio`});if(n||r)return{...n?{input:n}:{},...r?{output:r}:{}}}function rf(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 pa({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:ef(t),byModality:nf(n,r)})}function af(e){let t=J(e.id),n=J(e.model);if(t||n)return{...t?{id:t}:{},...n?{model:n}:{}}}function of(e){return e.flatMap(e=>Du(e)??[])}function sf(e,t){let n=t.stream!==!1,r=Zd(t.wireTools),i=$d(t.structured),a={model:e.apiId,messages:Xd(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 cf(e,t){let n=q(e.error);if(!n)return;let r=typeof n.code==`number`?n.code:502,i=Xe(r);throw new T(t.response&&i===`unsupported`?`unavailable`:i,Ud(e)??JSON.stringify(n))}function lf(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 uf(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 df(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(...lf(e,t)),uf(e,t),r}function ff(e,t,n,r){cf(e,t);let i=[],a=Sl(t.response,af(e));t.response=a.known,a.event&&i.push(a.event);let o=t.tokens?void 0:rf(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(...df(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(...of(wl(e)));return i}function pf(e,t){let n=[];for(let[t,r]of e.calls)n.push(...of(Lc({...r,id:r.id??`call_${t}`},r.args)));let r=la(e.finish,e.native);if(t.structured&&e.text&&r.kind===`completed`){let t=of([Cl(e.text)]);if(n.push(...t),t[0]?.type===`error`)return n}return n.push({type:`done`,stop:r}),n}async function*mf(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=Sl(a,af(t));a=e.known,e.event&&(yield e.event);let n=typeof t.mime_type==`string`?t.mime_type:``,r=typeof t.data==`string`?vt(t.data):new Uint8Array;if(!r.length)throw new T(`bad_response`,`no audio returned from speech`);let i=yl(n);yield{type:`media`,media:i?{mimeType:`audio/wav`,data:St(bl(r,i))}:{mimeType:Lr(n)||`application/octet-stream`,data:t.data}},yield{type:`done`,stop:{kind:`completed`}}}}var hf=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=>Wd(e,`Chat Completions`),create(e){return{async*complete(t){if(e.profileType===`speech`){yield*mf(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(sf(e,t),{stream:n}))yield*ff(i,r,t,n);yield*pf(r,t)}}}}),gf=Gi({id:`local`,name:`Local`,description:`A server that speaks OpenAI's chat API: Ollama, llama.cpp, vLLM, LM Studio.`,traceName:`openai`,connection:_({baseUrl:Bi.describe(`Where the server listens, up to and including /v1, e.g. http://localhost:11434/v1.`)}),key:o().trim().min(1).optional(),authorize:Vi(),serves:e=>[{protocol:hf,baseUrl:e.baseUrl},{protocol:sc,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()}}]}),_f=v().int().nonnegative(),vf=w({model:o().min(1),answers:i(o(),g()),usage:w({input_tokens:_f,output_tokens:_f,cost:v().nonnegative().optional()}).optional().catch(void 0)}),yf=_({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.`)}),bf=`TypeSafe-Danger-Zone-Images`,xf=`TypeSafe-Danger-Zone-Long-Context`,Sf=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:yf,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`,j(`provider.decision_images_off`));if(n&&/^jev-1\.13(\.|$)/.test(e.apiId))throw new T(`unsupported`,j(`provider.decision_box_model`,{apiId:e.apiId}));let i={};r&&(i[bf]=`true`),e.options.longContext&&(i[xf]=`true`);let a=I.parse({model:e.apiId,state:t.state,questions:t.questions,...t.assets&&Object.keys(t.assets).length?{assets:Tf(t.assets)}:{}});return await Cf(`systemOne`,e.send(a,{stream:!1,headers:i}))}}}});async function Cf(e,t){for await(let n of t){let t=vf.safeParse(n);if(!t.success)throw new T(`bad_response`,j(`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`,j(`provider.decision_failed`))}var wf={"image/png":`png`,"image/jpeg":`jpeg`};function Tf(e){return Object.fromEntries(Object.entries(e).map(([e,{mimeType:t,data:n}])=>[e,{type:`image`,format:wf[t],data_base64:n}]))}var Ef=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:Df(t.state,n),questions:Object.fromEntries(Object.entries(t.questions).map(([e,t])=>[e,{...t,instructions:Df(t.instructions,n),...`criteria`in t&&t.criteria!==void 0?{criteria:Df(t.criteria,n)}:{}}]))});return Cf(`openRouterDecisions`,e.send(r,{stream:!1}))}}}});function Df(e,t){if(typeof e==`string`){let n=_o(e,t);if(n.every(e=>typeof e==`string`))return e;let r=n.map(e=>typeof e==`string`?e:Of(e.asset));return r.length===1?r[0]:r}return Array.isArray(e)?e.map(e=>Df(e,t)):typeof e==`object`&&e?Object.fromEntries(Object.entries(e).map(([e,n])=>[e,Df(n,t)])):e}function Of({mimeType:e,data:t}){return{type:`image_url`,image_url:{url:`data:${e};base64,${t}`}}}var kf=`openrouter:image_generation`;function Af(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 jf(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 Mf(e){return(Array.isArray(e.images)?e.images:[]).flatMap(e=>{let t=jf(q(q(e)?.image_url)?.url);return t?[t]:[]})}function Nf(e){return e.filter(e=>e.type===`text`).map(e=>e.type===`text`?e.text:``).join(`
@@ -1 +1 @@
1
- import{C as e,H as t,S as n,U as r,Xt as i,ar as a,ir as o,jt as s,nr as c,tr as l,w as u}from"./shaped-data-OkTOsVE5.js";var d=/^data:([^;,]+);base64,/,f=new Map([[`image`,`data`],[`audio`,`data`],[`thought_signature`,`signature`],[`thought`,`signature`],[`function_call`,`signature`],[`reasoning.encrypted`,`data`]]);function p(e){if(typeof(e.mime_type??e.mimeType)==`string`&&typeof e.data==`string`)return`data`;if(typeof e.media_type==`string`&&typeof e.b64_json==`string`)return`b64_json`;let t=typeof e.type==`string`?f.get(e.type):void 0;return t&&typeof e[t]==`string`&&e[t]!==``?t:void 0}var m=`sha256`,h=`text_sha256`;async function g(e){let t=await a(e);return t?{kind:m,hash:t.hash}:{kind:h,hash:await o(e)}}async function _(e){let t=d.exec(e);if(!t)return e;let{kind:n,hash:r}=await g(e.slice(t[0].length));return`data:${t[1]};${n},${r}`}async function v(e){let t=p(e),n,r=await Promise.all(Object.entries(e).map(async([e,r])=>{if(e===t&&typeof r==`string`){let{kind:t,hash:i}=await g(r);return n=t,[e,i]}return[e,await y(r)]})),i=Object.fromEntries(r);return n&&(i.dataKind=n),i}function y(e){return typeof e==`string`?_(e):Array.isArray(e)?Promise.all(e.map(e=>y(e))):e&&typeof e==`object`?v(e):Promise.resolve(e)}function b(e,t){return t.reduce((e,t)=>s(e,t),e)}function x(e,t){return t.some(Boolean)?c(e,e=>b(e,t)):e}async function S(e,t){return x(await y(e),t)}var C=`https://github.com/open-telemetry/semantic-conventions-genai/tree/8ffdf56`,w=`content_sha256`,T=`json_sha256`,E=[`gen_ai.usage.`,`theorem.usage.`],D={"theorem.upstream.row":`upstreamLog`,"theorem.wire.request":`outboundWire`,"theorem.guardrail":`guardrailDecisions`},O=`raw`,k=`match`,A=[`injection`];function j(e,t){return e===!0||e!==!1&&e[t]}function M(e,{scrub:n,detect:a}){let{sensitive:o,injection:s}=n;return i(e,[...o?r(e,l,o,a):[],...j(o,`host`)?t(e,a):[],...s?r(e,A,s,a):[]])}async function N(e,t){let n=await o(e);return t.content[n]=e,t.known.set(e,n),n}function P(e,t){let{[t]:n,...r}=e;return r}async function F(t,r){if(e(t)){let e=b(M(t.$content,r),r.canaries);return{...P(t,`$content`),[w]:await N(e,r)}}if(n(t)){let e=P(t,`$bytes`),n=await a(t.$bytes);return n?{...e,content_sha256:n.hash,bytes:n.bytes}:{...e,invalid_base64:!0,text_sha256:await o(t.$bytes)}}return u(t)?t:await z(t,e=>F(e,r))}function I(e,t){return typeof e==`string`?t(e):Array.isArray(e)?e.map(e=>I(e,t)):e&&typeof e==`object`?Object.fromEntries(Object.entries(e).map(([e,n])=>[e,I(n,t)])):e}function L(e,t){return I(e,e=>{let n=M(e,t),r=t.known.get(n);return r?{[w]:r}:n})}async function R(e,t){if(u(e)){let n=await S(e.$json,t.canaries),r=JSON.stringify(L(n,t)),i=await o(r);return t.content[i]=r,{...P(e,`$json`),[T]:i}}return await z(e,e=>R(e,t))}async function z(e,t){if(Array.isArray(e))return await Promise.all(e.map(t));if(e&&typeof e==`object`){let n=await Promise.all(Object.entries(e).map(async([e,n])=>[e,await t(n)]));return Object.fromEntries(n)}return e}async function B(e,t){let n=await Promise.all(Object.entries(e).map(async([e,n])=>[e,await t(n)]));return Object.fromEntries(n)}async function V(e,t){let n=await Promise.all(e.events.map(async e=>({...e,attributes:await B(e.attributes,t)})));return{...e,attributes:await B(e.attributes,t),events:n}}function H(e,t){return t.usage?e:Object.fromEntries(Object.entries(e).filter(([e])=>!E.some(t=>e.startsWith(t))))}function U(e){return e.map(e=>{if(!e||typeof e!=`object`||Array.isArray(e))return e;let{[k]:t,...n}=e;return n})}function W(e,t){let n=D[e.name];if(n&&!t[n])return;if(e.name===`theorem.grounding`&&!t.evidenceRaw){let{[O]:t,...n}=e.attributes;return{...e,attributes:n}}let{hits:r}=e.attributes;return e.name===`theorem.guardrail`&&!t.guardrailMatchPreview&&Array.isArray(r)?{...e,attributes:{...e.attributes,hits:U(r)}}:e}function G(e,t){return{...e,attributes:H(e.attributes,t),events:e.events.flatMap(e=>W(e,t)??[])}}function K(e){return Object.entries(e).flatMap(([e,t])=>t?[e]:[])}async function q(e){let{policy:t}=e,n={scrub:t.scrub,detect:t.detect,canaries:j(t.scrub.canary,`theorem`)?e.canaries??[]:[],content:{},known:new Map},r=e.spans.map(e=>G(e,t.include)),[i]=r;i&&(i.attributes={...i.attributes,"theorem.record.include":K(t.include),"theorem.record.scrub":K(t.scrub)});let a=await Promise.all(r.map(e=>V(e,e=>F(e,n)))),o=await Promise.all(a.map(e=>V(e,e=>R(e,n))));return{v:3,schemaUrl:C,resource:{...t.resource},...e.metadata?{metadata:e.metadata}:{},spans:o,content:n.content}}function J(e,t){if(Array.isArray(t))return t.map(t=>J(e,t));if(!t||typeof t!=`object`)return t;let n=Object.fromEntries(Object.entries(t).map(([t,n])=>[t,J(e,n)])),{[w]:r,[T]:i,...a}=n,o=typeof r==`string`?e.content[r]:void 0;if(o!==void 0)return Object.keys(a).length===0?o:{...a,content:o};let s=typeof i==`string`?e.content[i]:void 0;if(s===void 0)return n;let c=J(e,JSON.parse(s));return Object.keys(a).length===0?c:c&&typeof c==`object`&&!Array.isArray(c)?{...c,...a}:n}export{J as n,q as t};
1
+ import{C as e,H as t,S as n,U as r,Xt as i,ar as a,ir as o,jt as s,nr as c,tr as l,w as u}from"./shaped-data-CjB-teds.js";var d=/^data:([^;,]+);base64,/,f=new Map([[`image`,`data`],[`audio`,`data`],[`thought_signature`,`signature`],[`thought`,`signature`],[`function_call`,`signature`],[`reasoning.encrypted`,`data`]]);function p(e){if(typeof(e.mime_type??e.mimeType)==`string`&&typeof e.data==`string`)return`data`;if(typeof e.media_type==`string`&&typeof e.b64_json==`string`)return`b64_json`;let t=typeof e.type==`string`?f.get(e.type):void 0;return t&&typeof e[t]==`string`&&e[t]!==``?t:void 0}var m=`sha256`,h=`text_sha256`;async function g(e){let t=await a(e);return t?{kind:m,hash:t.hash}:{kind:h,hash:await o(e)}}async function _(e){let t=d.exec(e);if(!t)return e;let{kind:n,hash:r}=await g(e.slice(t[0].length));return`data:${t[1]};${n},${r}`}async function v(e){let t=p(e),n,r=await Promise.all(Object.entries(e).map(async([e,r])=>{if(e===t&&typeof r==`string`){let{kind:t,hash:i}=await g(r);return n=t,[e,i]}return[e,await y(r)]})),i=Object.fromEntries(r);return n&&(i.dataKind=n),i}function y(e){return typeof e==`string`?_(e):Array.isArray(e)?Promise.all(e.map(e=>y(e))):e&&typeof e==`object`?v(e):Promise.resolve(e)}function b(e,t){return t.reduce((e,t)=>s(e,t),e)}function x(e,t){return t.some(Boolean)?c(e,e=>b(e,t)):e}async function S(e,t){return x(await y(e),t)}var C=`https://github.com/open-telemetry/semantic-conventions-genai/tree/8ffdf56`,w=`content_sha256`,T=`json_sha256`,E=[`gen_ai.usage.`,`theorem.usage.`],D={"theorem.upstream.row":`upstreamLog`,"theorem.wire.request":`outboundWire`,"theorem.guardrail":`guardrailDecisions`},O=`raw`,k=`match`,A=[`injection`];function j(e,t){return e===!0||e!==!1&&e[t]}function M(e,{scrub:n,detect:a}){let{sensitive:o,injection:s}=n;return i(e,[...o?r(e,l,o,a):[],...j(o,`host`)?t(e,a):[],...s?r(e,A,s,a):[]])}async function N(e,t){let n=await o(e);return t.content[n]=e,t.known.set(e,n),n}function P(e,t){let{[t]:n,...r}=e;return r}async function F(t,r){if(e(t)){let e=b(M(t.$content,r),r.canaries);return{...P(t,`$content`),[w]:await N(e,r)}}if(n(t)){let e=P(t,`$bytes`),n=await a(t.$bytes);return n?{...e,content_sha256:n.hash,bytes:n.bytes}:{...e,invalid_base64:!0,text_sha256:await o(t.$bytes)}}return u(t)?t:await z(t,e=>F(e,r))}function I(e,t){return typeof e==`string`?t(e):Array.isArray(e)?e.map(e=>I(e,t)):e&&typeof e==`object`?Object.fromEntries(Object.entries(e).map(([e,n])=>[e,I(n,t)])):e}function L(e,t){return I(e,e=>{let n=M(e,t),r=t.known.get(n);return r?{[w]:r}:n})}async function R(e,t){if(u(e)){let n=await S(e.$json,t.canaries),r=JSON.stringify(L(n,t)),i=await o(r);return t.content[i]=r,{...P(e,`$json`),[T]:i}}return await z(e,e=>R(e,t))}async function z(e,t){if(Array.isArray(e))return await Promise.all(e.map(t));if(e&&typeof e==`object`){let n=await Promise.all(Object.entries(e).map(async([e,n])=>[e,await t(n)]));return Object.fromEntries(n)}return e}async function B(e,t){let n=await Promise.all(Object.entries(e).map(async([e,n])=>[e,await t(n)]));return Object.fromEntries(n)}async function V(e,t){let n=await Promise.all(e.events.map(async e=>({...e,attributes:await B(e.attributes,t)})));return{...e,attributes:await B(e.attributes,t),events:n}}function H(e,t){return t.usage?e:Object.fromEntries(Object.entries(e).filter(([e])=>!E.some(t=>e.startsWith(t))))}function U(e){return e.map(e=>{if(!e||typeof e!=`object`||Array.isArray(e))return e;let{[k]:t,...n}=e;return n})}function W(e,t){let n=D[e.name];if(n&&!t[n])return;if(e.name===`theorem.grounding`&&!t.evidenceRaw){let{[O]:t,...n}=e.attributes;return{...e,attributes:n}}let{hits:r}=e.attributes;return e.name===`theorem.guardrail`&&!t.guardrailMatchPreview&&Array.isArray(r)?{...e,attributes:{...e.attributes,hits:U(r)}}:e}function G(e,t){return{...e,attributes:H(e.attributes,t),events:e.events.flatMap(e=>W(e,t)??[])}}function K(e){return Object.entries(e).flatMap(([e,t])=>t?[e]:[])}async function q(e){let{policy:t}=e,n={scrub:t.scrub,detect:t.detect,canaries:j(t.scrub.canary,`theorem`)?e.canaries??[]:[],content:{},known:new Map},r=e.spans.map(e=>G(e,t.include)),[i]=r;i&&(i.attributes={...i.attributes,"theorem.record.include":K(t.include),"theorem.record.scrub":K(t.scrub)});let a=await Promise.all(r.map(e=>V(e,e=>F(e,n)))),o=await Promise.all(a.map(e=>V(e,e=>R(e,n))));return{v:3,schemaUrl:C,resource:{...t.resource},...e.metadata?{metadata:e.metadata}:{},spans:o,content:n.content}}function J(e,t){if(Array.isArray(t))return t.map(t=>J(e,t));if(!t||typeof t!=`object`)return t;let n=Object.fromEntries(Object.entries(t).map(([t,n])=>[t,J(e,n)])),{[w]:r,[T]:i,...a}=n,o=typeof r==`string`?e.content[r]:void 0;if(o!==void 0)return Object.keys(a).length===0?o:{...a,content:o};let s=typeof i==`string`?e.content[i]:void 0;if(s===void 0)return n;let c=J(e,JSON.parse(s));return Object.keys(a).length===0?c:c&&typeof c==`object`&&!Array.isArray(c)?{...c,...a}:n}export{J as n,q as t};
@@ -1,3 +1,3 @@
1
- import{$t as e,C as t,Cn as n,M as r,On as i,h as a,j as o,n as s,p as c,qt as l,t as ee,y as te,z as u}from"./tool-schema-Cphc-uXi.js";import{En as d,Er as f,Fn as ne,Rn as p,Sn as re,Sr as ie,Tn as ae,Xn as oe,cn as m,gn as h,qn as g,zn as _}from"./shaped-data-OkTOsVE5.js";import{a as se,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:ne,inputs:p(`inputs`).filter(e=>e!==`decision`)},y=ce.map(e=>({...e,profileTypes:le[e.id]??p(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`&&!r(e.providers,t).keySlot)}function b(e,t){let n={provider:t.provider,keySlot:t.keySlot||e.models.key,fallbackKeySlot:t.fallbackKeySlot||e.models.fallbackKey},i=r(e.providers,n);return{...i,given:{keySlot:!!i.keySlot&&!n.keySlot,fallbackKeySlot:!!i.fallbackKeySlot&&!n.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 x=h,S=[{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}],C=2147483647,w={compactMaxTokens:32e3,compactAt:.75,compactKeep:4},T={"continue.instruction":`turnBehaviour`,"canary.bind_note":`guardrails`,"quota.exhausted":`guardrails`,"repair.default_guidance":`outputs`,"egress.default_repair_guidance":`guardrails`,"egress.refusal":`guardrails`};function E(e){return`${e}-${crypto.randomUUID().slice(0,8)}`}function D(e){return{key:E(`model`),modelId:`fast`,protocol:`openRouterOpenAi`,provider:`openrouter`,apiId:``,options:{},timeoutMs:null,efforts:[],defaultEffort:``,allowEffortSelect:!1,summaries:null,maxOutputTokens:null,temperature:null,builtInTools:[],...e}}var O=`Studio stub tool — returns a fixed result.`;function k(e){return{key:E(`tool`),toolName:`my_tool`,toolType:`function`,description:O,category:`studio`,access:re[0],permission:d[0],loadTier:ae[0],paths:[`*`],inputJson:ee,outputJson:s,...e}}function A(e,t,n){return(!e.description.trim()||e.description===O)&&n?{agentKey:t,description:`Asks ${n} and returns its answer.`}:{agentKey:t}}function j(){return{name:``,kind:`words`,pattern:``,flags:``,words:[]}}function M(){return{key:``,label:``,at:f(ie,()=>`ignore`),patterns:[j()],hint:``}}function N(){let e=i(void 0);return{canaryBindNote:``,detect:f(_,t=>({...e.detect[t]})),sources:Object.fromEntries(g.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 P(){let e=se({});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 F(e){return e.map(([e,t])=>({key:E(`criterion`),label:e,text:t}))}function I(){return{contract:`guardrails.tool_call.v1`,maxStateBytes:null,questions:[{key:E(`question`),id:`verdict`,type:`choice`,instructions:`Given what the user asked for and what the call would do, should it run?`,criteria:F([[`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:E(`question`),id:`risk`,type:`score`,instructions:`How much harm would this call do if it were wrong?`,criteria:F([[``,`Low: reversible, and affects only the user.`],[``,`High: hard to undo, or affects other people or money.`]])}],images:[]}}var L=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),R=JSON.stringify(`The user asked to tidy screenshots. The proposed call recursively deletes 1,284 files, including a tax return.`),ge=`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{$t as e,C as t,Cn as n,M as r,On as i,h as a,j as o,n as s,p as c,qt as l,t as ee,y as te,z as u}from"./tool-schema-Cqelak6O.js";import{En as d,Er as f,Fn as ne,Rn as p,Sn as re,Sr as ie,Tn as ae,Xn as oe,cn as m,gn as h,qn as g,zn as _}from"./shaped-data-CjB-teds.js";import{a as se,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:ne,inputs:p(`inputs`).filter(e=>e!==`decision`)},y=ce.map(e=>({...e,profileTypes:le[e.id]??p(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`&&!r(e.providers,t).keySlot)}function b(e,t){let n={provider:t.provider,keySlot:t.keySlot||e.models.key,fallbackKeySlot:t.fallbackKeySlot||e.models.fallbackKey},i=r(e.providers,n);return{...i,given:{keySlot:!!i.keySlot&&!n.keySlot,fallbackKeySlot:!!i.fallbackKeySlot&&!n.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 x=h,S=[{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}],C=2147483647,w={compactMaxTokens:32e3,compactAt:.75,compactKeep:4},T={"continue.instruction":`turnBehaviour`,"canary.bind_note":`guardrails`,"quota.exhausted":`guardrails`,"repair.default_guidance":`outputs`,"egress.default_repair_guidance":`guardrails`,"egress.refusal":`guardrails`};function E(e){return`${e}-${crypto.randomUUID().slice(0,8)}`}function D(e){return{key:E(`model`),modelId:`fast`,protocol:`openRouterOpenAi`,provider:`openrouter`,apiId:``,options:{},timeoutMs:null,efforts:[],defaultEffort:``,allowEffortSelect:!1,summaries:null,maxOutputTokens:null,temperature:null,builtInTools:[],...e}}var O=`Studio stub tool — returns a fixed result.`;function k(e){return{key:E(`tool`),toolName:`my_tool`,toolType:`function`,description:O,category:`studio`,access:re[0],permission:d[0],loadTier:ae[0],paths:[`*`],inputJson:ee,outputJson:s,...e}}function A(e,t,n){return(!e.description.trim()||e.description===O)&&n?{agentKey:t,description:`Asks ${n} and returns its answer.`}:{agentKey:t}}function j(){return{name:``,kind:`words`,pattern:``,flags:``,words:[]}}function M(){return{key:``,label:``,at:f(ie,()=>`ignore`),patterns:[j()],hint:``}}function N(){let e=i(void 0);return{canaryBindNote:``,detect:f(_,t=>({...e.detect[t]})),sources:Object.fromEntries(g.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 P(){let e=se({});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 F(e){return e.map(([e,t])=>({key:E(`criterion`),label:e,text:t}))}function I(){return{contract:`guardrails.tool_call.v1`,maxStateBytes:null,questions:[{key:E(`question`),id:`verdict`,type:`choice`,instructions:`Given what the user asked for and what the call would do, should it run?`,criteria:F([[`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:E(`question`),id:`risk`,type:`score`,instructions:`How much harm would this call do if it were wrong?`,criteria:F([[``,`Low: reversible, and affects only the user.`],[``,`High: hard to undo, or affects other people or money.`]])}],images:[]}}var L=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),R=JSON.stringify(`The user asked to tidy screenshots. The proposed call recursively deletes 1,284 files, including a tax return.`),ge=`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
  `),_e=`How do I delete every screenshot on my desktop?`;function ve(e,t=`choice`){let n=K(`question`,e.decision.questions.map(e=>e.id),e=>`question_${e}`);return{key:E(`question`),id:n,type:t,instructions:``,criteria:z(t)}}function ye(e,t,n){let r=t.replace(/\.[^.]*$/,``).toLowerCase().replace(/[^a-z0-9]+/g,`_`).replace(/^_|_$/g,``)||`image`,i=K(r,e.decision.images.map(e=>e.name),e=>`${r}_${e}`);return{key:E(`image`),name:i,...n}}function be(){return{key:E(`option`),name:``,label:``,isShownInChat:!1,choices:[]}}function xe(e,t){return e.map(e=>t.find(t=>t.value===e)??{key:E(`choice`),value:e,description:``})}function Se(){return{key:E(`criterion`),label:``,text:``}}function z(e){return e===`noul`||e===`box`?[]:F(e===`choice`?[[`yes`,``],[`no`,``]]:[[``,``],[``,``]])}function Ce(){return{identity:{agentId:``,profileType:``,handle:``,system:``,options:[]},included:[`observability`,`labels`],models:{defaultModel:``,allowModelSelect:!1,maxSteps:null,key:``},modelBindings:[],providers:[...t],tools:{t2Loader:``,parallel:!1},toolSpecs:[],inputs:{text:!0,attachmentsAccept:[],voiceAccept:[],maxFiles:null,maxBytes:null,maxTurnBytes:null,limitsByMime:{},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:e({type:`text`}),atStepLimit:`stop`},guardrails:N(),observability:P(),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:I(),labels:{}}}var we=new Set([`guardrails`]);function B(e,t){return e.profileTypes.includes(t)&&!(t===`decision`&&we.has(e.id))}function V(e){let t=e.identity.profileType;if(!t)return[`identity`];let n=new Set(e.included);return y.filter(e=>e.role!==`branch`&&B(e,t)&&(!e.optional||n.has(e.id))).map(e=>e.id)}function H(e,t){let n=e.identity.profileType;return n!==``&&p(t).includes(n)}function Te(e,t,n){if((!n||n.includes(t.key))&&t.loadTier===`T2`&&H(e,`tools.t2Loader`)&&!e.tools.t2Loader.trim())return`No T2 loader is set under Tools, so this tool never loads.`}function Ee(e){return H(e,`identity.system`)&&oe(e.guardrails.detect,`canary_leak`)}function De(e){let t=e.identity.profileType;return t!==``&&l.includes(t)}function U(e){let t=e.identity.profileType;return t?y.filter(n=>n.role===`spine`&&n.optional&&B(n,t)&&!e.included.includes(n.id)).map(e=>e.id):[]}function Oe(e){return{...e,attachmentsAccept:e.attachmentsAccept.filter(e=>n(m,e)),voiceAccept:[]}}function ke(e){return{...e,text:!1,attachmentsAccept:[],voiceAccept:e.voiceAccept.length?e.voiceAccept:[`audio/*`]}}function Ae(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 W(e,t){if(t.some(t=>t.modelId===e))return e;let[n,...r]=t;return n&&!r.length?n.modelId:``}function je(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:W(e.models.defaultModel,n)},modelBindings:n}}function G(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=K(a.modelId,i,e=>`${a.modelId}${e}`);return D({...a,modelId:o})}function Me(e){return k({toolName:K(`my_tool`,e.toolSpecs.map(e=>e.toolName),e=>`my_tool_${e}`)})}function K(e,t,n){let r=new Set(t),i=e;for(let e=2;r.has(i);e++)i=n(e);return i}function Ne(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)&&!Ie(n,t,i)}),i={...e,identity:{...e.identity,profileType:t},modelBindings:r},s=r.length?r:[G(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`?Oe(e.inputs):t===`transcription`?ke(e.inputs):e.inputs,...l?{speech:{...e.speech,voice:Pe}}:{},models:{...e.models,defaultModel:W(e.models.defaultModel,s),key:c?Le:e.models.key},modelBindings:s}}var Pe=`Kore`,Fe=[`text`,`image`,`speech`,`transcription`,`live`,`decision`];function Ie(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)&&Fe.some(e=>e!==t&&r(e))}var Le=`slot_a`;function Re(e,t){return U(e).includes(t)?{...e,included:[...e.included,t]}:e}function ze(e,t){return{...e,included:e.included.filter(e=>e!==t)}}function q(e){return`modelBinding:${e}`}var J=`toolSpec:`;function Y(e){return`${J}${e}`}function X(e){return e.startsWith(J)?e.slice(9):void 0}var Z=`provider:`;function Q(e){return`${Z}${e}`}function Be(e){return e.startsWith(Z)?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=X(t);if(i!==void 0)return e.toolSpecs.some(e=>e.key===i)?{facet:`toolSpec`,key:i}:void 0;let a=V(e);if(r===void 0&&a.includes(t))return{facet:t}}function We(e,t){return t===`models`?e.modelBindings.map(e=>({id:q(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:Y(e.key),ref:{facet:`toolSpec`,key:e.key},label:e.toolName.trim()||`Unnamed tool`,children:[]}))}function Ge(e){let t=V(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{z as A,Ee as B,V as C,U as D,K as E,be as F,b as G,Ne as H,M as I,he as J,me as K,j as L,ye as M,ve as N,Re as O,G as P,Me as R,H as S,ze as T,De as U,je as V,Ae as W,y as X,pe as Y,ue as Z,C as _,Ge as a,D as b,$ as c,_e as d,ge as f,x as g,S as h,Ue as i,Se as j,Te as k,w as l,T as m,Be as n,X as o,R as p,de as q,Q as r,Y as s,q as t,L as u,A as v,E as w,k as x,Ce as y,xe as z};
@@ -1,2 +1,2 @@
1
- import{Gt as e,Qn as t,qn as n}from"./tool-schema-Cphc-uXi.js";import{c as r}from"./host-patterns-F-KZIzkF.js";import{Kn as i,M as a,Ur as o}from"./shaped-data-OkTOsVE5.js";import{I as s}from"./reader-CXHCDEbW.js";import{g as c}from"./schema-G8cHvtht.js";import{r as l}from"./encode-files-MOJXvlW9.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:`
1
+ import{Gt as e,Qn as t,qn as n}from"./tool-schema-Cqelak6O.js";import{c as r}from"./host-patterns-F-KZIzkF.js";import{Kn as i,M as a,Ur as o}from"./shaped-data-CjB-teds.js";import{I as s}from"./reader-CVIM-dZI.js";import{g as c}from"./schema-V9Rv344d.js";import{r as l}from"./encode-files-DWBa8FAF.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
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`,o(`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`late_results`:return{id:w(t),kind:`late-results`,text:e.text};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 i;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`,o(`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{Dn as e}from"./shaped-data-OkTOsVE5.js";var t=/\{\s*private\s*:/g,n=/\n(?:[ \t]*\n)+/,r=/^\s*when\s/;function i(e){let[t,...n]=e;if(t===void 0)return;if(n.length===0&&typeof t==`string`)return t.trim()||void 0;let r=[...e],i=e.at(-1);typeof t==`string`&&(r[0]=t.trimStart()),typeof i==`string`&&(r[r.length-1]=i.trimEnd());let a=r.filter(e=>e!==``),[o,...s]=a;return s.length===0&&typeof o==`string`?o:a}function a(e){let r=[[]],a=e=>{let[t=``,...i]=e.split(n);r.at(-1)?.push(t),r.push(...i.map(e=>[e]))},o=0;for(let n of e.matchAll(t)){if(n.index<o)continue;let t=1,i=n.index+n[0].length;for(;i<e.length&&t>0;i++)e[i]===`{`?t++:e[i]===`}`&&t--;if(a(e.slice(o,n.index)),t>0)return{ok:!1,message:`The {private: section on line ${String(r.length)} has no closing }.`};let s=e.slice(n.index+n[0].length,i-1).trim();if(!s)return{ok:!1,message:`The {private: section on line ${String(r.length)} is empty.`};r.at(-1)?.push({private:s}),o=i}return a(e.slice(o)),{ok:!0,lines:r.flatMap(e=>{let t=i(e.filter(e=>e!==``));return t===void 0?[]:[t]})}}var o=e.filter(e=>e!==`builtin`),s=`Tool type must be ${o.join(`, `).replace(/, ([^,]+)$/,`, or $1`)}.`;export{a as i,s as n,r,o as t};
1
+ import{Dn as e}from"./shaped-data-CjB-teds.js";var t=/\{\s*private\s*:/g,n=/\n(?:[ \t]*\n)+/,r=/^\s*when\s/;function i(e){let[t,...n]=e;if(t===void 0)return;if(n.length===0&&typeof t==`string`)return t.trim()||void 0;let r=[...e],i=e.at(-1);typeof t==`string`&&(r[0]=t.trimStart()),typeof i==`string`&&(r[r.length-1]=i.trimEnd());let a=r.filter(e=>e!==``),[o,...s]=a;return s.length===0&&typeof o==`string`?o:a}function a(e){let r=[[]],a=e=>{let[t=``,...i]=e.split(n);r.at(-1)?.push(t),r.push(...i.map(e=>[e]))},o=0;for(let n of e.matchAll(t)){if(n.index<o)continue;let t=1,i=n.index+n[0].length;for(;i<e.length&&t>0;i++)e[i]===`{`?t++:e[i]===`}`&&t--;if(a(e.slice(o,n.index)),t>0)return{ok:!1,message:`The {private: section on line ${String(r.length)} has no closing }.`};let s=e.slice(n.index+n[0].length,i-1).trim();if(!s)return{ok:!1,message:`The {private: section on line ${String(r.length)} is empty.`};r.at(-1)?.push({private:s}),o=i}return a(e.slice(o)),{ok:!0,lines:r.flatMap(e=>{let t=i(e.filter(e=>e!==``));return t===void 0?[]:[t]})}}var o=e.filter(e=>e!==`builtin`),s=`Tool type must be ${o.join(`, `).replace(/, ([^,]+)$/,`, or $1`)}.`;export{a as i,s as n,r,o as t};