@theoremjs/studio 0.3.4-next.823.ga9dd146 → 0.3.4-next.827.gdc3858d

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 (46) hide show
  1. package/package.json +4 -4
  2. package/page/assets/{BottomSheet-CDgXiVuF.js → BottomSheet-D8l5EiVw.js} +1 -1
  3. package/page/assets/{ConsoleFrame-CPNRVDBo.js → ConsoleFrame-DIqBRQ6h.js} +1 -1
  4. package/page/assets/{DateInput-Cjk4hML1.js → DateInput-D8jgunEH.js} +1 -1
  5. package/page/assets/{MenuBottomSheet-Bj_mKrh6.js → MenuBottomSheet-DuECEDvN.js} +1 -1
  6. package/page/assets/{SchemaFields-CkL-vai_.js → SchemaFields-wBQPYJp7.js} +1 -1
  7. package/page/assets/{TokenizerBottomSheet-DcYu74xd.js → TokenizerBottomSheet-BQ-YVdrH.js} +1 -1
  8. package/page/assets/{ToolResultCharts-CYIijshR.js → ToolResultCharts-mvzwp85f.js} +1 -1
  9. package/page/assets/{Toolbar-DpOR5fTo.js → Toolbar-Dph7K0gF.js} +1 -1
  10. package/page/assets/{TraceInspector-B003cC1O.js → TraceInspector-2hKk5NX-.js} +1 -1
  11. package/page/assets/{TraceOverview-CRlar-s2.js → TraceOverview-D45HL0Hf.js} +1 -1
  12. package/page/assets/{browser-connection-DgdBd76s.js → browser-connection-qRFid-Dw.js} +1 -1
  13. package/page/assets/{browser-engine-CeSJcH28.js → browser-engine-CeycUzUW.js} +1 -1
  14. package/page/assets/{browser-transport-D2Mx-Qnc.js → browser-transport-CsUtc1Pe.js} +2 -2
  15. package/page/assets/{compile-DBxEJqBO.js → compile-DYCFhHk9.js} +1 -1
  16. package/page/assets/egress-automata-CiZ3Vt9G.js +1 -0
  17. package/page/assets/{encode-files-C19H5oqI.js → encode-files-BRs8C-bs.js} +1 -1
  18. package/page/assets/{export-agent-CqbkC1Ia.js → export-agent-B4IKwOzc.js} +1 -1
  19. package/page/assets/{guardrail-tester-CAdmVyuo.js → guardrail-tester-DRs_NH1q.js} +1 -1
  20. package/page/assets/{index-DRUuSFSA.js → index-BA2jTPWc.js} +10 -10
  21. package/page/assets/{json-code-DLvskcGp.js → json-code-luSNXvne.js} +1 -1
  22. package/page/assets/{live-messages-A9Tq-ju5.js → live-messages-BqywxVCH.js} +1 -1
  23. package/page/assets/{prompt-row-deJ96dq5.js → prompt-row-DrJDr0LV.js} +1 -1
  24. package/page/assets/{reader-DeQkPn6F.js → reader-BBrTYWFM.js} +1 -1
  25. package/page/assets/{registry-CaitOCn7.js → registry-CWNE3rO6.js} +1 -1
  26. package/page/assets/{schema-C46sNlNM.js → schema-BgiRaskO.js} +1 -1
  27. package/page/assets/{shaped-data-CK3-VEaY.js → shaped-data-QPeAmaJ4.js} +1 -1
  28. package/page/assets/{stub-BMOs6lLs.js → stub-xIKEDapD.js} +1 -1
  29. package/page/assets/{studio-code-pane-BlBOcJ5N.js → studio-code-pane-s5yRjP4Z.js} +1 -1
  30. package/page/assets/{studio-console-C0iQI2gx.js → studio-console-7f4F4Hkd.js} +1 -1
  31. package/page/assets/{studio-decision-BpJEfYeU.js → studio-decision-T4qrTzYI.js} +1 -1
  32. package/page/assets/{studio-embedding-Bd4IQNg8.js → studio-embedding-ImGGpwTU.js} +1 -1
  33. package/page/assets/{studio-host-console-CBpKmTKc.js → studio-host-console-BI14iMuJ.js} +2 -2
  34. package/page/assets/{studio-labels-DXI0kCJG.js → studio-labels-OQ5Vc2LV.js} +1 -1
  35. package/page/assets/{studio-live-BcW5Imw6.js → studio-live-BPbdXowP.js} +1 -1
  36. package/page/assets/{studio-map-2u2Sz-vZ.js → studio-map-CmgnDmVT.js} +1 -1
  37. package/page/assets/{studio-trace-replay-BYe5YpFb.js → studio-trace-replay-9DFss6XN.js} +1 -1
  38. package/page/assets/{tool-schema-Sm_QLU6x.js → tool-schema-BMdqCPG0.js} +1 -1
  39. package/page/assets/{trace-record-CX7Fvi-y.js → trace-record-zDKImdlA.js} +1 -1
  40. package/page/assets/{tree-C7Zz83Uw.js → tree-BRzl4J61.js} +1 -1
  41. package/page/assets/{turn-client-oo4BR2Jy.js → turn-client-u43fclzs.js} +1 -1
  42. package/page/assets/{types-BRkR8qiH.js → types-5TSKtfT6.js} +1 -1
  43. package/page/assets/{use-one-call-DqVLm9Oz.js → use-one-call-UKtYn9P2.js} +1 -1
  44. package/page/assets/{workspace-Bq99kF6X.js → workspace-B0zHlpWt.js} +1 -1
  45. package/page/index.html +16 -16
  46. package/page/assets/egress-automata-CpTxDNty.js +0 -1
@@ -1,4 +1,4 @@
1
- import{n as e}from"./rolldown-runtime-hePW80VL.js";import{$ as t,A as n,B as r,C as i,D as a,E as o,F as s,G as c,H as l,I as u,J as d,K as f,L as p,M as m,N as h,O as g,P as ee,Q as te,R as ne,S as re,T as _,U as ie,V as ae,W as oe,X as se,Y as ce,Z as le,a as ue,at as de,b as v,c as y,ct as fe,d as b,dt as pe,et as me,ft as he,g as ge,h as x,ht as _e,i as ve,it as ye,j as be,lt as xe,m as Se,mt as Ce,n as we,nt as Te,o as Ee,ot as De,p as S,q as Oe,r as ke,rt as Ae,st as je,tt as Me,u as Ne,ut as Pe,v as C,w as Fe,x as w,z as Ie}from"./schemas-D7cgkv3L.js";import{c as T,s as Le}from"./host-patterns-F-KZIzkF.js";import{$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-CK3-VEaY.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,n,r,i,a=[],o){let s=xr(yr(e,t),i,r.detect,{callable:a}),c=s.hits.filter(({rule:e})=>e===wt.tool_instructions),l=hr(n.origin),u=s.action===`allow`?void 0:{stage:`tool_result`,...i?{boundary:i}:{},trust:`untrusted`,action:s.action,hits:s.hits,provenance:n},d={...c.length>0?{suspicious:c}:{},...u?{event:u}:{}};return s.text===void 0?d:{text:l?_r(s.text,n,Ye(c.map(({signal:e})=>e)),o):s.text,...d}}function Cr(e,t,n,r){let i=xr(gr(e),r,n.detect),a=r?k(r,i,t):void 0;return{...i.text===void 0?{}:{text:i.text},...a?{event:a}:{}}}function wr(e,t,n,r){if(!r||e===void 0)return{value:e};let i=cr(e,r,n.detect),a=k(r,i,t);return{...i.action===`block`?{}:{value:i.value},...a?{event:a}:{}}}function Tr(e,t,n,r,i={}){if(!(r&&$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 Er(e,t){if(e.action!==`allow`)return{stage:`tool_call`,trust:`untrusted`,action:e.action,hits:e.hits,provenance:t}}function Dr(e,t,n=[]){let r=e?.sources??[],i=e?.suspicious??[];return hr(t.origin)?{sources:[...r,t],suspicious:[...i,...n]}:{sources:r,suspicious:i}}function Or(e){return(e?.sources.length??0)>0}function kr(e){return(e?.suspicious.length??0)>0}var Ar={"read-only":0,"read-write":1,destructive:2},jr={off:1/0,destructive:2,write:1};function Mr(e,t,n,r){if(!Or(e))return{action:`allow`};let i=Ar[t]??0;if(i===0)return{action:`allow`};let a=kr(e),o=[{rule:a?bt.steeredTurn:bt.taintedTurn,severity:`high`}];if(i<jr[n.taint?.afterRemoteRead??`off`])return{action:`flag`,hits:o};let s=e?.sources.map(e=>e.tool).join(`, `)??``,c=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 Nr={onBlock:`retry`,maxRetries:1};function Pr(e){return{onBlock:e?.onBlock??Nr.onBlock,maxRetries:e?.maxRetries??Nr.maxRetries}}function Fr(e){return{detect:lt(e?.detect),allow:Re(e?.detect),blockedReply:Pr(e?.blockedReply),network:e?.network,quota:e?.quota,taint:e?.taint}}function Ir(e){return(e.split(`;`)[0]??``).trim().toLowerCase()}function Lr(e,t){let n=Ir(t);return e.some(e=>{let t=Ir(e);return t.endsWith(`/*`)?n.startsWith(t.slice(0,-1)):t===n})}function Rr(e){return yt[Ir(e)]}function zr(e){return e.type===`text`||e.type===`image`||e.type===`transcription`||e.type===`live`?e.inputs:void 0}function Br(e,t){let n=zr(e);return t===`voice`?n?.voice?.accept:n?.attachments?.accept}function Vr(e,t){if(Rr(t))for(let n of[`attachments`,`voice`]){let r=Br(e,n);if(r&&Lr(r,t))return n}}function Hr(e,t){let n=e.models[t];if(!n)throw new T(`config`,`Profile ${e.id} has no model binding for '${t}'`);return n}var Ur=/^\d{1,3}(\.\d{1,3}){3}$/,Wr=[e=>e===0,e=>e===127,e=>e===10,(e,t)=>e===100&&t>=64&&t<=127,(e,t)=>e===172&&t>=16&&t<=31,(e,t)=>e===192&&t===168,(e,t)=>e===169&&t===254,(e,t,n)=>e===192&&t===0&&(n===0||n===2),(e,t)=>e===198&&(t===18||t===19),(e,t,n)=>e===198&&t===51&&n===100,(e,t,n)=>e===203&&t===0&&n===113,e=>e>=224];function Gr(e,t,n,r){return Wr.some(r=>r(e,t,n))}function Kr(e){if(!Ur.test(e))return!1;let[t=0,n=0,r=0,i=0]=e.split(`.`).map(Number);return t>255||n>255||r>255||i>255?!1:Gr(t,n,r,i)}function qr(e){let t=e.toLowerCase().trim(),n=t.lastIndexOf(`:`),r=[],i=t;if(n!==-1){let e=t.slice(n+1);if(e.includes(`.`)){let a=e.split(`.`).map(e=>Number.parseInt(e,10));if(a.length!==4||a.some(e=>Number.isNaN(e)||e<0||e>255))return null;let o=a[0]??0,s=a[1]??0,c=a[2]??0,l=a[3]??0;r=[o<<8|s,c<<8|l];let u=t.slice(0,n+1);i=u.endsWith(`::`)?u:u.slice(0,-1)}}let a=i.split(`::`);if(a.length>2)return null;let o=a[0]?a[0].split(`:`).filter(Boolean):[],s=a.length===2&&a[1]?a[1].split(`:`).filter(Boolean):[],c=8-r.length;if(a.length===1){if(o.length!==c)return null}else if(o.length+s.length>=c)return null;let l=c-(o.length+s.length),u=Array(l).fill(0),d=e=>/^[0-9a-f]{1,4}$/.test(e)?Number.parseInt(e,16):null,f=[];for(let e of o){let t=d(e);if(t===null)return null;f.push(t)}let p=[];for(let e of s){let t=d(e);if(t===null)return null;p.push(t)}return[...f,...u,...p,...r]}var H=(e,t,n)=>e.slice(t,n).every(e=>e===0),Jr=[e=>H(e,0,8),e=>H(e,0,7)&&e[7]===1,e=>((e[0]??0)&65472)==65152,e=>((e[0]??0)&65472)==65216,e=>((e[0]??0)&65024)==64512,e=>((e[0]??0)&65280)==65280,e=>e[0]===8193&&e[1]===3512,e=>e[0]===256&&H(e,1,4),e=>e[0]===100&&e[1]===65435&&e[2]===1,e=>e[0]===8193&&e[1]===0],Yr=[{match:e=>H(e,0,5)&&e[5]===65535,at:6},{match:e=>H(e,0,4)&&e[4]===65535&&e[5]===0,at:6},{match:e=>H(e,0,6),at:6},{match:e=>e[0]===100&&e[1]===65435&&H(e,2,6),at:6},{match:e=>e[0]===8194,at:1}];function Xr(e){let t=qr(e);return t?.length===8?Jr.some(e=>e(t))?!0:Yr.some(({match:e,at:n})=>{if(!e(t))return!1;let r=t[n]??0,i=t[n+1]??0;return Gr(r>>8&255,r&255,i>>8&255,i&255)}):!1}function Zr(e){let t=e.toLowerCase();for(;t.endsWith(`.`);)t=t.slice(0,-1);return t===`localhost`||t.endsWith(`.localhost`)||t===`local`||t.endsWith(`.local`)||t===`internal`||t.endsWith(`.internal`)||t===`lan`||t.endsWith(`.lan`)||t===`home.arpa`||t.endsWith(`.home.arpa`)||t===`localdomain`||t.endsWith(`.localdomain`)||t===`127.0.0.1`||t===`::1`||t===`[::1]`}function Qr(e){let t=e.startsWith(`[`)&&e.endsWith(`]`)?e.slice(1,-1):e;return Kr(t)||Xr(t)}function $r(e,t){let n;try{n=new URL(e)}catch{throw new T(`request`,`Invalid URL provided: "${e}"`)}let r=t?.allowPrivateNetworks??!1,i=t?.allowedHosts?.map(e=>e.toLowerCase())??[],a=n.hostname.toLowerCase(),o=r?[`http:`,`https:`]:[`https:`],s=t?.allowedSchemes?t.allowedSchemes.map(e=>e.endsWith(`:`)?e.toLowerCase():`${e.toLowerCase()}:`):o;if(!s.includes(n.protocol))throw new T(`blocked`,`URL scheme "${n.protocol}" is not permitted by network policy. Allowed: ${s.join(`, `)}`);if(!r&&!i.includes(a)){if(Zr(a))throw new T(`blocked`,`Access to loopback target "${a}" blocked by network guardrail. Enable allowPrivateNetworks to permit local addresses.`);if(Kr(a))throw new T(`blocked`,`Access to private IPv4 address "${a}" blocked by network guardrail.`);if(Xr(a.startsWith(`[`)&&a.endsWith(`]`)?a.slice(1,-1):a))throw new T(`blocked`,`Access to private IPv6 address "${a}" blocked by network guardrail.`)}return n}var ei=20,ti=new Set([301,302,303,307,308]);async function ni(e,t,n){let{resolveHost:r,policy:i}=t,a=e.hostname.toLowerCase();if(r===void 0||i?.allowPrivateNetworks===!0||i?.allowedHosts?.some(e=>e.toLowerCase()===a)===!0||a.startsWith(`[`)||Ur.test(a))return;let o=await r(a,n??void 0);if(o.length===0)throw new T(`blocked`,`Host "${a}" did not resolve to an address.`);let s=o.find(Qr);if(s!==void 0)throw new T(`blocked`,`Host "${a}" resolves to private address "${s}", blocked by network guardrail.`)}function ri(e,t){return e===303?t!==`HEAD`:(e===301||e===302)&&t===`POST`}async function ii(e,t,n){let r=n.fetchFn??fetch,i=async e=>{let r=performance.now();try{let r=$r(e,n.policy);return await ni(r,n,t.signal),r}finally{n.onCheck?.(performance.now()-r)}},a=await i(e);await n.beforeSend?.();let o=a.origin,s=new Headers(t.headers),c=t.method??`GET`,l=t.body,u=!0;for(let d=0;;d++){let f=new Headers(s);if(u)for(let[e,t]of Object.entries(n.originBoundHeaders??{}))f.set(e,t);let p=await Ke(r,a.href,{...t,method:c,headers:f,body:l,redirect:`manual`}),m=p.headers.get(`location`);if(!n.followRedirects||!ti.has(p.status)||m===null)return p;if(await p.body?.cancel(),d===ei)throw new T(`network`,`Too many redirects from "${e}"`);a=await i(new URL(m,a).href),u&&=a.origin===o,ri(p.status,c)&&(c=`GET`,l=void 0,s.delete(`content-type`))}}var U=v().int().positive().max(2**53-1),ai=U.max(2147483647),oi=_({operationTimeoutMs:ai.optional(),connectTimeoutMs:ai.optional(),liveStepTimeoutMs:ai.optional(),maxWireRecordBytes:U.optional(),maxWireResponseBytes:U.optional(),maxEventBytes:U.optional(),maxStepBytes:U.optional(),maxStepEvents:U.optional(),maxPendingToolCalls:U.optional()}),si=[`text`,`image`,`speech`,`transcription`,`live`,`decision`,`embedding`],ci=w({id:o().regex(/^[A-Za-z][A-Za-z0-9]*$/),name:o().min(1),description:o().min(1),endpoints:re(y(si),o().min(1)),operationNames:re(y(si),o().regex(/^[a-z][a-z0-9_]*$/))});function li(e,t){return new T(`config`,j(`protocol.definition`,{id:e,issues:t}))}function ui(e){let t=ci.safeParse(e);if(!t.success)throw li(String(e.id),he(t.error))}function di(e,t,n){let r=Object.keys(t).toSorted().join(`, `),i=Object.keys(n).toSorted().join(`, `);if(r!==i)throw li(e,`operationNames name [${i}]; endpoints serve [${r}]`)}function fi(e,t,n,r){if(!n)throw new T(`internal`,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 pi(e,t){return t.type===`reasoning`?{...t,data:fi(e,`reasoning`,e.reasoning,t.data),origin:{protocol:e.id}}:t.type===`custom`?{type:`custom`,kind:`${e.id}.${t.kind}`,data:fi(e,t.kind,e.custom?.[t.kind],t.data)}:t}async function*mi(e,t){for await(let n of t)yield pi(e,n)}function hi(e,t){let{complete:n,openSession:r}=t;return{...t,...n?{complete:r=>mi(e,n.call(t,r))}:{},...r?{async openSession(n){let i=await r.call(t,n);return{...i,events:()=>mi(e,i.events())}}}:{}}}function gi(e,t,n){let r=n??{},i=e.options.safeParse(r),a=(e.refusedOptions?.(t)??[]).filter(e=>typeof r==`object`&&!!r&&e in r);if(i.success&&a.length===0)return i.data;let o=i.success?a.map(e=>`✖ ${t} takes no ${e}`).join(`
1
+ import{n as e}from"./rolldown-runtime-hePW80VL.js";import{$ as t,A as n,B as r,C as i,D as a,E as o,F as s,G as c,H as l,I as u,J as d,K as f,L as p,M as m,N as h,O as g,P as ee,Q as te,R as ne,S as re,T as _,U as ie,V as ae,W as oe,X as se,Y as ce,Z as le,a as ue,at as de,b as v,c as y,ct as fe,d as b,dt as pe,et as me,ft as he,g as ge,h as x,ht as _e,i as ve,it as ye,j as be,lt as xe,m as Se,mt as Ce,n as we,nt as Te,o as Ee,ot as De,p as S,q as Oe,r as ke,rt as Ae,st as je,tt as Me,u as Ne,ut as Pe,v as C,w as Fe,x as w,z as Ie}from"./schemas-D7cgkv3L.js";import{c as T,s as Le}from"./host-patterns-F-KZIzkF.js";import{$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-QPeAmaJ4.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,n,r,i,a=[],o){let s=xr(yr(e,t),i,r.detect,{callable:a}),c=s.hits.filter(({rule:e})=>e===wt.tool_instructions),l=hr(n.origin),u=s.action===`allow`?void 0:{stage:`tool_result`,...i?{boundary:i}:{},trust:`untrusted`,action:s.action,hits:s.hits,provenance:n},d={...c.length>0?{suspicious:c}:{},...u?{event:u}:{}};return s.text===void 0?d:{text:l?_r(s.text,n,Ye(c.map(({signal:e})=>e)),o):s.text,...d}}function Cr(e,t,n,r){let i=xr(gr(e),r,n.detect),a=r?k(r,i,t):void 0;return{...i.text===void 0?{}:{text:i.text},...a?{event:a}:{}}}function wr(e,t,n,r){if(!r||e===void 0)return{value:e};let i=cr(e,r,n.detect),a=k(r,i,t);return{...i.action===`block`?{}:{value:i.value},...a?{event:a}:{}}}function Tr(e,t,n,r,i={}){if(!(r&&$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 Er(e,t){if(e.action!==`allow`)return{stage:`tool_call`,trust:`untrusted`,action:e.action,hits:e.hits,provenance:t}}function Dr(e,t,n=[]){let r=e?.sources??[],i=e?.suspicious??[];return hr(t.origin)?{sources:[...r,t],suspicious:[...i,...n]}:{sources:r,suspicious:i}}function Or(e){return(e?.sources.length??0)>0}function kr(e){return(e?.suspicious.length??0)>0}var Ar={"read-only":0,"read-write":1,destructive:2},jr={off:1/0,destructive:2,write:1};function Mr(e,t,n,r){if(!Or(e))return{action:`allow`};let i=Ar[t]??0;if(i===0)return{action:`allow`};let a=kr(e),o=[{rule:a?bt.steeredTurn:bt.taintedTurn,severity:`high`}];if(i<jr[n.taint?.afterRemoteRead??`off`])return{action:`flag`,hits:o};let s=e?.sources.map(e=>e.tool).join(`, `)??``,c=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 Nr={onBlock:`retry`,maxRetries:1};function Pr(e){return{onBlock:e?.onBlock??Nr.onBlock,maxRetries:e?.maxRetries??Nr.maxRetries}}function Fr(e){return{detect:lt(e?.detect),allow:Re(e?.detect),blockedReply:Pr(e?.blockedReply),network:e?.network,quota:e?.quota,taint:e?.taint}}function Ir(e){return(e.split(`;`)[0]??``).trim().toLowerCase()}function Lr(e,t){let n=Ir(t);return e.some(e=>{let t=Ir(e);return t.endsWith(`/*`)?n.startsWith(t.slice(0,-1)):t===n})}function Rr(e){return yt[Ir(e)]}function zr(e){return e.type===`text`||e.type===`image`||e.type===`transcription`||e.type===`live`?e.inputs:void 0}function Br(e,t){let n=zr(e);return t===`voice`?n?.voice?.accept:n?.attachments?.accept}function Vr(e,t){if(Rr(t))for(let n of[`attachments`,`voice`]){let r=Br(e,n);if(r&&Lr(r,t))return n}}function Hr(e,t){let n=e.models[t];if(!n)throw new T(`config`,`Profile ${e.id} has no model binding for '${t}'`);return n}var Ur=/^\d{1,3}(\.\d{1,3}){3}$/,Wr=[e=>e===0,e=>e===127,e=>e===10,(e,t)=>e===100&&t>=64&&t<=127,(e,t)=>e===172&&t>=16&&t<=31,(e,t)=>e===192&&t===168,(e,t)=>e===169&&t===254,(e,t,n)=>e===192&&t===0&&(n===0||n===2),(e,t)=>e===198&&(t===18||t===19),(e,t,n)=>e===198&&t===51&&n===100,(e,t,n)=>e===203&&t===0&&n===113,e=>e>=224];function Gr(e,t,n,r){return Wr.some(r=>r(e,t,n))}function Kr(e){if(!Ur.test(e))return!1;let[t=0,n=0,r=0,i=0]=e.split(`.`).map(Number);return t>255||n>255||r>255||i>255?!1:Gr(t,n,r,i)}function qr(e){let t=e.toLowerCase().trim(),n=t.lastIndexOf(`:`),r=[],i=t;if(n!==-1){let e=t.slice(n+1);if(e.includes(`.`)){let a=e.split(`.`).map(e=>Number.parseInt(e,10));if(a.length!==4||a.some(e=>Number.isNaN(e)||e<0||e>255))return null;let o=a[0]??0,s=a[1]??0,c=a[2]??0,l=a[3]??0;r=[o<<8|s,c<<8|l];let u=t.slice(0,n+1);i=u.endsWith(`::`)?u:u.slice(0,-1)}}let a=i.split(`::`);if(a.length>2)return null;let o=a[0]?a[0].split(`:`).filter(Boolean):[],s=a.length===2&&a[1]?a[1].split(`:`).filter(Boolean):[],c=8-r.length;if(a.length===1){if(o.length!==c)return null}else if(o.length+s.length>=c)return null;let l=c-(o.length+s.length),u=Array(l).fill(0),d=e=>/^[0-9a-f]{1,4}$/.test(e)?Number.parseInt(e,16):null,f=[];for(let e of o){let t=d(e);if(t===null)return null;f.push(t)}let p=[];for(let e of s){let t=d(e);if(t===null)return null;p.push(t)}return[...f,...u,...p,...r]}var H=(e,t,n)=>e.slice(t,n).every(e=>e===0),Jr=[e=>H(e,0,8),e=>H(e,0,7)&&e[7]===1,e=>((e[0]??0)&65472)==65152,e=>((e[0]??0)&65472)==65216,e=>((e[0]??0)&65024)==64512,e=>((e[0]??0)&65280)==65280,e=>e[0]===8193&&e[1]===3512,e=>e[0]===256&&H(e,1,4),e=>e[0]===100&&e[1]===65435&&e[2]===1,e=>e[0]===8193&&e[1]===0],Yr=[{match:e=>H(e,0,5)&&e[5]===65535,at:6},{match:e=>H(e,0,4)&&e[4]===65535&&e[5]===0,at:6},{match:e=>H(e,0,6),at:6},{match:e=>e[0]===100&&e[1]===65435&&H(e,2,6),at:6},{match:e=>e[0]===8194,at:1}];function Xr(e){let t=qr(e);return t?.length===8?Jr.some(e=>e(t))?!0:Yr.some(({match:e,at:n})=>{if(!e(t))return!1;let r=t[n]??0,i=t[n+1]??0;return Gr(r>>8&255,r&255,i>>8&255,i&255)}):!1}function Zr(e){let t=e.toLowerCase();for(;t.endsWith(`.`);)t=t.slice(0,-1);return t===`localhost`||t.endsWith(`.localhost`)||t===`local`||t.endsWith(`.local`)||t===`internal`||t.endsWith(`.internal`)||t===`lan`||t.endsWith(`.lan`)||t===`home.arpa`||t.endsWith(`.home.arpa`)||t===`localdomain`||t.endsWith(`.localdomain`)||t===`127.0.0.1`||t===`::1`||t===`[::1]`}function Qr(e){let t=e.startsWith(`[`)&&e.endsWith(`]`)?e.slice(1,-1):e;return Kr(t)||Xr(t)}function $r(e,t){let n;try{n=new URL(e)}catch{throw new T(`request`,`Invalid URL provided: "${e}"`)}let r=t?.allowPrivateNetworks??!1,i=t?.allowedHosts?.map(e=>e.toLowerCase())??[],a=n.hostname.toLowerCase(),o=r?[`http:`,`https:`]:[`https:`],s=t?.allowedSchemes?t.allowedSchemes.map(e=>e.endsWith(`:`)?e.toLowerCase():`${e.toLowerCase()}:`):o;if(!s.includes(n.protocol))throw new T(`blocked`,`URL scheme "${n.protocol}" is not permitted by network policy. Allowed: ${s.join(`, `)}`);if(!r&&!i.includes(a)){if(Zr(a))throw new T(`blocked`,`Access to loopback target "${a}" blocked by network guardrail. Enable allowPrivateNetworks to permit local addresses.`);if(Kr(a))throw new T(`blocked`,`Access to private IPv4 address "${a}" blocked by network guardrail.`);if(Xr(a.startsWith(`[`)&&a.endsWith(`]`)?a.slice(1,-1):a))throw new T(`blocked`,`Access to private IPv6 address "${a}" blocked by network guardrail.`)}return n}var ei=20,ti=new Set([301,302,303,307,308]);async function ni(e,t,n){let{resolveHost:r,policy:i}=t,a=e.hostname.toLowerCase();if(r===void 0||i?.allowPrivateNetworks===!0||i?.allowedHosts?.some(e=>e.toLowerCase()===a)===!0||a.startsWith(`[`)||Ur.test(a))return;let o=await r(a,n??void 0);if(o.length===0)throw new T(`blocked`,`Host "${a}" did not resolve to an address.`);let s=o.find(Qr);if(s!==void 0)throw new T(`blocked`,`Host "${a}" resolves to private address "${s}", blocked by network guardrail.`)}function ri(e,t){return e===303?t!==`HEAD`:(e===301||e===302)&&t===`POST`}async function ii(e,t,n){let r=n.fetchFn??fetch,i=async e=>{let r=performance.now();try{let r=$r(e,n.policy);return await ni(r,n,t.signal),r}finally{n.onCheck?.(performance.now()-r)}},a=await i(e);await n.beforeSend?.();let o=a.origin,s=new Headers(t.headers),c=t.method??`GET`,l=t.body,u=!0;for(let d=0;;d++){let f=new Headers(s);if(u)for(let[e,t]of Object.entries(n.originBoundHeaders??{}))f.set(e,t);let p=await Ke(r,a.href,{...t,method:c,headers:f,body:l,redirect:`manual`}),m=p.headers.get(`location`);if(!n.followRedirects||!ti.has(p.status)||m===null)return p;if(await p.body?.cancel(),d===ei)throw new T(`network`,`Too many redirects from "${e}"`);a=await i(new URL(m,a).href),u&&=a.origin===o,ri(p.status,c)&&(c=`GET`,l=void 0,s.delete(`content-type`))}}var U=v().int().positive().max(2**53-1),ai=U.max(2147483647),oi=_({operationTimeoutMs:ai.optional(),connectTimeoutMs:ai.optional(),liveStepTimeoutMs:ai.optional(),maxWireRecordBytes:U.optional(),maxWireResponseBytes:U.optional(),maxEventBytes:U.optional(),maxStepBytes:U.optional(),maxStepEvents:U.optional(),maxPendingToolCalls:U.optional()}),si=[`text`,`image`,`speech`,`transcription`,`live`,`decision`,`embedding`],ci=w({id:o().regex(/^[A-Za-z][A-Za-z0-9]*$/),name:o().min(1),description:o().min(1),endpoints:re(y(si),o().min(1)),operationNames:re(y(si),o().regex(/^[a-z][a-z0-9_]*$/))});function li(e,t){return new T(`config`,j(`protocol.definition`,{id:e,issues:t}))}function ui(e){let t=ci.safeParse(e);if(!t.success)throw li(String(e.id),he(t.error))}function di(e,t,n){let r=Object.keys(t).toSorted().join(`, `),i=Object.keys(n).toSorted().join(`, `);if(r!==i)throw li(e,`operationNames name [${i}]; endpoints serve [${r}]`)}function fi(e,t,n,r){if(!n)throw new T(`internal`,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 pi(e,t){return t.type===`reasoning`?{...t,data:fi(e,`reasoning`,e.reasoning,t.data),origin:{protocol:e.id}}:t.type===`custom`?{type:`custom`,kind:`${e.id}.${t.kind}`,data:fi(e,t.kind,e.custom?.[t.kind],t.data)}:t}async function*mi(e,t){for await(let n of t)yield pi(e,n)}function hi(e,t){let{complete:n,openSession:r}=t;return{...t,...n?{complete:r=>mi(e,n.call(t,r))}:{},...r?{async openSession(n){let i=await r.call(t,n);return{...i,events:()=>mi(e,i.events())}}}:{}}}function gi(e,t,n){let r=n??{},i=e.options.safeParse(r),a=(e.refusedOptions?.(t)??[]).filter(e=>typeof r==`object`&&!!r&&e in r);if(i.success&&a.length===0)return i.data;let o=i.success?a.map(e=>`✖ ${t} takes no ${e}`).join(`
2
2
  `):he(i.error);throw new T(`config`,j(`protocol.options`,{apiId:t,protocol:e.id,issues:o}))}function W(e){if(ui(e),typeof e.create!=`function`||typeof e.options?.safeParse!=`function`)throw li(e.id,`create and options are required`);return di(e.id,e.endpoints,e.operationNames),Object.freeze({...e,lineage:Object.freeze([e.id]),create:t=>hi(e,e.create(t))})}function _i(e){return e instanceof Ee?e.shape:void 0}function vi(e,t){let n=e??{},r={};for(let e of t)e in n&&(r[e]=n[e]);return r}function yi(e,t){let n=_i(e.options),r=t.options?_i(t.options):{};if(t.options&&!n)throw new T(`config`,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 bi(e,t,n,r,i){let a={profileType:r.profileType,apiId:r.apiId,options:vi(r.options,n.addedKeys)},o=[],s=t.read?.({...a,...i?{request:i}:{}}),c=e=>{for(let n of e??[])o.push(pi(t,n))},l=(e,n,o=[])=>{if(!t.body)return{body:e,wroteTools:o};let s=t.body(e,{...a,builtInTools:r.builtInTools,headers:n,...i?{request:i}:{}});return{body:s.body,wroteTools:[...o,...s.wroteTools??[]]}};async function*u(e){for await(let t of e){let e=s?.row(t);c(e?.events),e?.consumed||(yield t)}}let d={...r,options:n.baseKeys?vi(r.options,n.baseKeys):r.options,send(e,t){let n=new Headers(t.headers),i=l(e,n,t.wroteTools);return u(r.send(i.body,{...t,headers:Object.fromEntries(n),wroteTools:i.wroteTools}))},async connect(e,t){let n=l(e,new Headers,t?.wroteTools),i=await r.connect(n.body,{wroteTools:n.wroteTools});return{...i,frames:()=>u(i.frames())}}};async function*f(e){for await(let t of e)yield*o.splice(0),t.type===`done`&&c(s?.finish?.().events),yield*o.splice(0),yield t;yield*o.splice(0)}return{operations:e.create(d),drained:f}}function xi(e){let t=e().operations,n={};return t.complete&&(n.complete=t=>{let{operations:n,drained:r}=e(t);return r(n.complete(t))}),t.openSession&&(n.openSession=async t=>{let{operations:n,drained:r}=e(t),i=await n.openSession(t);return{...i,events:()=>r(i.events())}}),t.decide&&(n.decide=t=>e().operations.decide(t)),t.embed&&(n.embed=t=>e().operations.embed(t)),n}function Si(e,t,n){let r=t[e]??n[e];return r?{[e]:r}:{}}function Ci(e,t){ui({...t,endpoints:t.endpoints??{},operationNames:t.operationNames??{}});let n={...e.endpoints,...t.endpoints},r={...e.operationNames,...t.operationNames};di(t.id,n,r);let i=yi(e,t);return Object.freeze({id:t.id,name:t.name,description:t.description,endpoints:n,operationNames:r,options:i.schema,...e.continuation?{continuation:e.continuation}:{},...t.reasoning?{reasoning:t.reasoning}:{},...t.custom?{custom:t.custom}:{},...Si(`framing`,t,e),...Si(`error`,t,e),...Si(`embeddingLimits`,t,e),...Si(`refusedOptions`,t,e),base:e,lineage:Object.freeze([t.id,...e.lineage]),create:n=>xi(r=>bi(e,t,i,n,r))})}function wi(e,t){return t.lineage.includes(e)}var Ti=o().regex(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,Ei=_({protocol:o().min(1).describe(`The API shape this model is spoken to in.`),provider:o().min(1).describe(`The service that runs the model or routes requests to one, such as Gemini or OpenRouter. Its registration supplies the endpoint and authentication.`),apiId:o().min(1).describe(`The id the provider knows the model by.`),maxOutputTokens:G.maxOutputTokens.describe(`The most tokens the model may write in one step.`),temperature:G.temperature.describe(`How varied the model's answers are.`),efforts:G.efforts.describe(`Effort names a turn may pick, each mapped to a thinking level.`),defaultEffort:G.defaultEffort.describe(`The effort used when a turn picks none.`),allowEffortSelect:G.allowEffortSelect.describe(`Whether a turn may pick an effort.`),summaries:G.summaries.describe(`Whether the model sends summaries of its thinking.`),builtInTools:G.builtInTools.describe(`Tools the provider runs itself, by the ids it knows them by.`),compaction:G.compaction.describe(`How the conversation is shortened when it grows too long.`),keySlot:Ti.optional().describe(`The slot this model's key is read from, in place of the provider's.`),fallbackKeySlot:Ti.optional().describe(`The slot tried once when the first key is out of quota, rate limited or busy.`),options:I.optional().describe(`What this model's protocol takes beyond the shared settings.`),limits:oi.optional().describe(`Theorem's cut-offs for this model's calls; each one left out is no limit.`)}),Di=Ei,Oi=Ei.pick({protocol:!0,provider:!0,apiId:!0,keySlot:!0,fallbackKeySlot:!0,options:!0,limits:!0}).extend({timeoutMs:v().positive().optional().describe(`How long a decision may take before it fails.`)});function ki(e,t){let n=t.keySlot??e.keySlot,r=t.fallbackKeySlot??e.fallbackKeySlot;return{...n===void 0?{}:{keySlot:n},...r===void 0?{}:{fallbackKeySlot:r}}}function Ai(e,t){let n=e.serves.find(e=>e.protocol.id===t.protocol);if(!n)throw new T(`config`,j(`protocol.not_served`,{provider:e.id,protocol:t.protocol}));return n}function ji(e,t){return Ai(e,t).protocol}function Mi(e,t,n){return ji(e,t).operationNames[n]}function Ni(e,t,n,r={webSocketHeaders:!0}){let i=Ai(e,t),{protocol:a}=i;if(a.endpoints[n]===void 0)throw new T(`unsupported`,j(`protocol.profile_type`,{protocol:a.id,profileType:n}));let o=I.parse(gi(a,t.apiId,t.options)),s=ki(e,t);if(s.keySlot!==void 0&&s.keySlot===s.fallbackKeySlot)throw new T(`config`,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 Pi(e){return e.type===`text`?{type:`text`,text:e.text}:`uri`in e?{type:e.type,mimeType:e.mimeType,uri:e.uri}:{type:e.type,mimeType:e.mimeType,data:e.data}}function Fi(e){return e.type!==`text`&&`uri`in e}function K(e){let t=e.parts??[];return e.content?[{type:`text`,text:e.content},...t]:[...t]}function Ii(e){let t=e.structured===void 0?e.text:JSON.stringify(e.structured);return[...t?[{role:`assistant`,content:t}]:[],...e.calls.length?[Li(e.calls)]:[]]}function Li(e){let t=e.flatMap(e=>e.reasoning??[]),n=[];for(let t of e)n.push({id:t.callId,type:`function`,function:{name:t.name,arguments:JSON.stringify(t.arguments)}});return{role:`assistant`,tool_calls:n,...t.length?{reasoning:[...t]}:{}}}function Ri(e,t){return Object.assign(t=>({sign:n=>e(t,n)}),{webSocketHeaders:t})}var zi=o().url().refine(e=>{if(!URL.canParse(e))return!0;let t=new URL(e);return[`http:`,`https:`].includes(t.protocol)&&!t.username&&!t.password&&![...t.searchParams.keys()].some(e=>/key|auth|secret|token|password/i.test(e))},j(`protocol.endpoint_url`));function Bi(){return Ri((e,t)=>t.headers.set(`Authorization`,`Bearer ${e}`),!0)}function Vi(e){return Ri((t,n)=>n.headers.set(e,t),!0)}function Hi(e){return Ri((t,n)=>n.url.searchParams.set(e,t),!1)}var Ui=w({id:o().regex(/^[a-z][a-z0-9-]*$/),name:o().min(1),description:o().min(1),traceName:o().min(1).optional()});function Wi(e){let t=Ui.safeParse(e);if(!t.success||typeof e.serves!=`function`)throw new T(`config`,j(`protocol.definition`,{id:String(e.id),issues:t.success?`serves is required`:he(t.error)}));return Object.freeze({...e})}function Gi(e,t){let n=e.serves.find(e=>e.protocol.id===t);if(!n)throw new T(`config`,j(`protocol.not_served`,{provider:e.id,protocol:t}));return n}function Ki(){let e=new Map,t=new Map,n=e=>{let n=[];for(let r=e;r;r=r.base){let e=t.get(r.id);if(e&&e!==r)throw new T(`config`,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&&Ti.parse(i.keySlot),i.fallbackKeySlot!==void 0&&Ti.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}=Gi({id:o,serves:c},typeof e==`string`?e:e.id);return{protocol:r.id,options:gi(r,t,n)}},d=Object.freeze({id:o,definition:r,connection:s.data,...i.keySlot?{keySlot:i.keySlot}:{},...i.fallbackKeySlot?{fallbackKeySlot:i.fallbackKeySlot}:{},serves:c,model(e,t,n={}){let{options:r,...i}=n;return Di.parse({...i,provider:o,apiId:t,...u(e,t,r)})},decisionModel(e,t,n={}){let{options:r,...i}=n;return Oi.parse({...i,provider:o,apiId:t,...u(e,t,r)})}});for(let e of l)t.set(e.id,e);return e.set(o,d),d};return{register:(e,t={})=>r(e,t,!1),replace:(e,t={})=>r(e,t,!0),get:t=>e.get(t),require(t,n){let r=e.get(t);if(!r)throw new T(`config`,j(`protocol.provider_missing`,{provider:t,apiId:n}));return r},list:()=>[...e.values()],protocols:()=>[...t.values()]}}var qi=[`text`],Ji=at,Yi=[`length`,`stream_incomplete`],Xi=new Set([`egress`,`canary`,`prompt_echo`,`provider_tool_leak`]);function Zi(e){return e.kind===`filtered`&&Xi.has(e.native??``)}var Qi=1500,$i=new Set(at);function ea(e){return $i.has(e)}new Set(Ji);var ta=new Set([`provider_error`,`stream_incomplete`]);function na(e){return ta.has(e)}function ra(e){return typeof e==`object`&&e.reason?{kind:`cancelled`,native:e.reason}:{kind:`cancelled`}}function ia(e,t){return!e||!ea(e.kind)?!1:(t?.autoContinue??Yi).includes(e.kind)}function aa(e){if(e.type!==`live`)return e.turnBehaviour?.resumption}function oa(e){return e.type===`text`&&e.turnBehaviour?.allowSteering!==!1}function sa(e){return e.type===`text`||e.type===`live`?e.turnBehaviour?.allowSteering!==!1:!1}function ca(e,t){let n=t?.trim()||e?.trim()||void 0,r=(t||e||``).toLowerCase();return r?r===`network_error`||r.includes(`network`)?{kind:`provider_error`,native:n}:la((e||``).toLowerCase(),r,n):{kind:`stream_incomplete`,native:n}}function la(e,t,n){return e===`stop`?/error|fail/.test(t)?{kind:`provider_error`,native:n}:{kind:`completed`,native:n}:e===`length`?{kind:`length`,native:n}:e===`tool_calls`||e===`tool-calls`?{kind:`tool`,native:n}:e===`content_filter`||e===`content-filter`?{kind:`filtered`,native:n}:{kind:`provider_error`,native:n}}function ua(e){let t=(e||``).toLowerCase(),n=e||void 0;switch(t){case`completed`:return{kind:`completed`,native:n};case`incomplete`:case`budget_exceeded`:return{kind:`length`,native:n};case`requires_action`:return{kind:`tool`,native:n};case`cancelled`:return{kind:`cancelled`,native:n};case`failed`:return{kind:`provider_error`,native:n};case`in_progress`:case`queued`:return{kind:`stream_incomplete`,native:n};default:return{kind:`stream_incomplete`,native:n}}}function da(e,t){for(let n=e.length-1;n>=0;--n){let r=e[n];if(r!==void 0&&t(r))return r}}function q(e){return E(e)?e:void 0}function J(e){if(typeof e==`string`&&e.trim())return e}function Y(e){return typeof e==`number`&&Number.isFinite(e)&&e>=0?e:void 0}function fa(e){let t=e.input?e.input:void 0;if(t===void 0&&!e.output)return;let n=[];t===void 0&&n.push(`input`),e.output===void 0&&n.push(`output`);let r=t??0,i=e.output??0;return{input:r,output:i,...e.thinking?{thinking:e.thinking}:{},...e.toolUse?{toolUse:e.toolUse}:{},...e.cached?{cached:e.cached}:{},...e.cacheWrite?{cacheWrite:e.cacheWrite}:{},total:r+i,...e.cost?{cost:e.cost}:{},...n.length>0?{estimated:n}:{},...e.byModality?{byModality:e.byModality}:{},...e.grounding?{grounding:e.grounding}:{}}}function pa(e){let t=e.flatMap(e=>e.cost?[e.cost]:[]);if(t.length===0)return;let n=t.flatMap(e=>e.upstreamUsd===void 0?[]:[e.upstreamUsd]),r=t.length<e.length||t.some(e=>e.partial);return{usd:t.reduce((e,t)=>e+t.usd,0),...n.length>0?{upstreamUsd:n.reduce((e,t)=>e+t,0)}:{},...r?{partial:!0}:{}}}function ma(e){let t=[`input`,`output`],n={};for(let r of t){let[t,...i]=e.map(e=>e.byModality?.[r]),a=Object.keys(t??{}).filter(e=>i.every(t=>t?.[e]!==void 0));a.length!==0&&(n[r]=Object.fromEntries(a.map(t=>[t,e.reduce((e,n)=>e+(n.byModality?.[r]?.[t]??0),0)])))}return Object.keys(n).length>0?n:void 0}function ha(e){let t=new Map;for(let n of e.flatMap(e=>e.grounding??[]))t.set(n.type,[...t.get(n.type)??[],n]);if(t.size!==0)return[...t].map(([e,t])=>{let n=t.every(e=>e.searchQueryCount!==void 0);return{type:e,count:t.reduce((e,t)=>e+t.count,0),...n?{searchQueryCount:t.reduce((e,t)=>e+(t.searchQueryCount??0),0)}:{}}})}function ga(e){return va(e.flatMap(e=>e.type===`tokens`?[e.tokens]:[]))}function _a(e){return va(e.flatMap(e=>{if(e.type===`tokens`)return[e.tokens];if(e.type!==`tool`)return[];let{tool:t}=e;return(t.phase===`complete`||t.phase===`error`)&&t.tokens?[t.tokens]:[]}))}function va(e){if(e.length===0)return;let t=t=>e.reduce((e,n)=>e+(t(n)??0),0),n=t(e=>e.input),r=t(e=>e.output),i=t(e=>e.thinking),a=t(e=>e.toolUse),o=t(e=>e.cached),s=t(e=>e.cacheWrite),c=pa(e),l=ma(e),u=ha(e),d=[`input`,`output`],f=d.filter(t=>e.some(e=>e.estimated?.includes(t))),p={};for(let e of d){let n=t(t=>t.unknownMedia?.[e]);n>0&&(p[e]=n)}return{input:n,output:r,...i?{thinking:i}:{},...a?{toolUse:a}:{},...o?{cached:o}:{},...s?{cacheWrite:s}:{},total:n+r,...c?{cost:c}:{},...f.length>0?{estimated:f}:{},...Object.keys(p).length>0?{unknownMedia:p}:{},...l?{byModality:l}:{},...u?{grounding:u}:{}}}var ya=1e3,ba=400,xa=new Set([`http_request`,`http_response`,`http_error_body`,`http_throw`]),Sa=new Set([`text`,`image`,`audio`]),Ca={completed:`stop`,length:`length`,tool:`tool_call`,filtered:`content_filter`,provider_error:`error`};function wa(e){let[t]=e.split(`/`);return t===`application`||t===`text`||!t?`document`:t}function Ta(e){return e.type===`text`?{type:`text`,...A(e.text)}:`uri`in e?{type:`uri`,modality:e.type,mime_type:e.mimeType,uri:e.uri}:{type:`blob`,modality:e.type,mime_type:e.mimeType,...We(e.data)}}function Ea(e){let t=K(e).map(Ta);if(e.role===`tool`)return{role:`tool`,parts:[{type:`tool_call_response`,...e.tool_call_id?{id:e.tool_call_id}:{},response:A(e.content??``)},...(e.parts??[]).map(Ta)]};let n=(e.tool_calls??[]).map(e=>({type:`tool_call`,id:e.id,name:e.function.name,arguments:A(e.function.arguments)}));return{role:e.role,parts:[...t,...n]}}var Da=new WeakMap;function Oa(e){let{conversation:t}=e;if(`previous`in t){let e=Da.get(t.previous),n=[...e?.input??[],...e?.output?[e.output]:[]];return{input:[...n,...t.continuation.map(Ea)],sentFrom:n.length}}let n=t.input.length>0?[{role:`user`,parts:t.input.map(Ta)}]:[];return{input:[...t.history.map(Ea),...n]}}var ka=class{parts=[];open;calls=new Map;add(e,t){switch(e.type){case`text`:this.appendText(`text`,e.text);return;case`thought`:this.appendText(`reasoning`,e.text);return;case`tool`:this.addTool(e.tool);return;case`structured`:this.push({type:`structured`,content:N(e.structured??null)});return;case`media`:this.push(Na(e.media));return;case`evidence`:{let{evidence:n}=e;if(n.kind===`input_transcription`||n.kind===`output_transcription`){this.appendText(`text`,e.text??``,n.kind,n.interim);return}let r=La(n,t);r&&this.push(r);return}case`tool_draft`:case`structured_draft`:return;default:return}}appendText(e,t,n,r){if(!t)return;let i=`${e}:${n??``}:${r?`interim`:``}`;if(this.open?.key===i){this.open.text+=t,Object.assign(this.open.part,A(this.open.text));return}let a={type:e,...A(t),...X(`theorem.source`,n),...r?{"theorem.interim":!0}:{}};this.parts.push(a),this.open={key:i,text:t,part:a}}addTool(e){if(e.phase===void 0){let t=Ma(e);this.calls.set(e.callId,t),this.push(t);return}let t=this.calls.get(e.callId),n=e.phase===`error`?Aa(e.failure):void 0;t&&n!==void 0&&Object.assign(t,{arguments:A(n)})}push(e){this.parts.push(e),this.open=void 0}};function Aa(e){let t=q(e?.details)?.raw;return typeof t==`string`?t:void 0}function ja(e){return Aa(e.failure)??JSON.stringify(e.arguments)}function Ma(e){return{type:`tool_call`,id:e.callId,name:e.name,arguments:A(ja(e))}}function Na(e){return{type:`blob`,modality:wa(e.mimeType),mime_type:e.mimeType,...We(e.data)}}var Pa=`_call`,Fa=`_result`;function Ia(e){switch(e.kind){case`code_execution_call`:return{side:`call`,name:`code_execution`,id:e.id};case`code_execution_result`:return{side:`result`,name:`code_execution`,id:e.callId};case`provider_step`:{let{step:t,raw:n}=e;if(t.endsWith(Pa)){let e=typeof n?.id==`string`?n.id:void 0;return{side:`call`,name:t.slice(0,-5),id:e}}if(t.endsWith(Fa)){let e=typeof n?.call_id==`string`?n.call_id:void 0;return{side:`result`,name:t.slice(0,-7),id:e}}return}default:return}}function La(e,t){let n=Ia(e);if(!n)return;let r={"theorem.observed_end":t,...e.partial?{"theorem.partial":!0}:{}},i={...N(e.raw??{}),type:n.name};return n.side===`call`?{type:`server_tool_call`,...X(`id`,n.id),name:n.name,server_tool_call:i,...r}:{type:`server_tool_call_response`,...X(`id`,n.id),server_tool_call_response:i,...r}}function Ra(e){switch(e.type){case`grounding`:{let{searchHtml:t,metadata:n,chunks:r}=e.grounding;return!t&&!n&&!r?void 0:{...t?{search_html:A(t)}:{},...n||r?{raw:N({metadata:n,chunks:r})}:{}}}case`citation`:return{sources:N(e.sources)};case`evidence`:{let{evidence:t}=e;return Ia(t)||t.kind===`input_transcription`||t.kind===`output_transcription`?void 0:{provider:t.provider,...t.raw?{raw:N(t.raw)}:{}}}default:return}}function za(e){return{stage:e.stage,trust:e.trust,action:e.action,hits:e.hits.map(e=>({rule:e.rule,severity:e.severity,...X(`signal`,e.signal),...e.span?{start:e.span.start,end:e.span.end}:{},...X(`match`,e.match),...X(`label`,e.label),...X(`doc`,e.doc)})),...e.provenance?{provenance:{...e.provenance}}:{},...e.errorInternal?{error:A(e.errorInternal)}:{},...X(`error_summary`,e.errorSummary)}}var Ba={output_stream:`output_delta`,stream_canary:`output_delta`,tool_draft:`tool_call`,live_output:`live_outbound`};function Va(e,t,n,r){return{...n?za(n):{stage:r.stage,trust:r.trust,action:`allow`,hits:[]},check:e,duration_ms:t}}function Ha(e){let t={};for(let n of[`input`,`output`])for(let[r,i]of Object.entries(e?.[n]??{})){let e=Sa.has(r)?`gen_ai`:`theorem`;t[`${e}.usage.${r}.${n}_tokens`]=i}return t}function X(e,t){return t===void 0?{}:{[e]:t}}function Ua(e){return{"gen_ai.usage.input_tokens":e.input,"gen_ai.usage.output_tokens":e.output,...X(`gen_ai.usage.reasoning.output_tokens`,e.thinking),...X(`gen_ai.usage.cache_read.input_tokens`,e.cached),...X(`gen_ai.usage.cache_write.input_tokens`,e.cacheWrite),...X(`theorem.usage.tool_use.input_tokens`,e.toolUse),...Ha(e.byModality),...e.grounding?{"theorem.usage.grounding":e.grounding.map(e=>({type:e.type,count:e.count,...X(`search_query_count`,e.searchQueryCount)}))}:{},...X(`theorem.usage.cost_usd`,e.cost?.usd),...X(`theorem.usage.upstream_cost_usd`,e.cost?.upstreamUsd),...e.cost?.partial?{"theorem.usage.cost_partial":!0}:{},...e.estimated?.length?{"theorem.usage.estimated":[...e.estimated]}:{},...e.unknownMedia?{"theorem.usage.unknown_media":{...e.unknownMedia}}:{}}}function Wa(e){if(e)return e.provider}function Ga(e,t){return t===`live`?`speech`:e.structured?`json`:e.image?`image`:e.speech?`speech`:`text`}function Ka(e,t,n,r){let i=Wa(t);return{...X(`gen_ai.operation.name`,r),...X(`gen_ai.provider.name`,i),"gen_ai.request.model":e.apiId,"theorem.model.id":e.model,...X(`theorem.key_slot`,t?.keySlot),...X(`gen_ai.request.temperature`,e.temperature),...X(`gen_ai.request.max_tokens`,e.maxOutputTokens),...X(`gen_ai.request.reasoning.level`,e.thinking),"gen_ai.system_instructions":[{type:`text`,...A(e.system)}],...e.wireTools?.length?{"gen_ai.tool.definitions":A(JSON.stringify(e.wireTools))}:{},"gen_ai.output.type":Ga(e,n),...qa(e)}}function qa(e){let{image:t,speech:n,live:r}=e;return{"theorem.request.builtins":e.builtins.map(e=>e.id),...X(`theorem.request.summaries`,e.summaries),...X(`theorem.request.structured`,e.structured?.id),...X(`theorem.request.session_id`,e.sessionId),...t?{"theorem.request.image":{...X(`mime_type`,t.mimeType),...X(`aspect_ratio`,t.aspectRatio),...X(`resolution`,t.resolution),...X(`quality`,t.quality),...X(`background`,t.background),...X(`n`,t.n),...X(`seed`,t.seed),...X(`output_compression`,t.outputCompression),include_text:t.includeText}}:{},...n?{"theorem.request.speech":{...X(`voice`,n.voice),...X(`speed`,n.speed),...X(`format`,n.format)}}:{},...r?{"theorem.request.live":Ja(r,e)}:{}}}function Ja(e,t){let{vad:n,transcription:r}=e;return{...X(`voice`,e.voice),...n?{vad:{...X(`activity_handling`,n.activityHandling),...X(`start_sensitivity`,n.startSensitivity),...X(`end_sensitivity`,n.endSensitivity),...X(`prefix_padding_ms`,n.prefixPaddingMs),...X(`silence_duration_ms`,n.silenceDurationMs)}}:{},...X(`session_resumption`,e.sessionResumption),...e.contextCompression?{context_compression:{mechanism:`sliding_window`,...X(`trigger_tokens`,e.contextCompression.triggerTokens),...X(`target_tokens`,e.contextCompression.slidingWindow.targetTokens)}}:{},...r?{transcription:{...X(`input`,r.input),...X(`output`,r.output)}}:{},resumed:!!t.providerState}}function Ya(e,t){return!t||typeof t!=`object`?{}:Object.fromEntries(Object.entries(t).map(([t,n])=>[`${e}.${t}`,[String(n)]]))}function Xa(e){if(typeof e!=`string`)return{};let t=URL.canParse(e)?new URL(e):void 0;return t?{"server.address":t.hostname,"url.path":t.pathname}:{}}var Za=class{call;tries=0;current;last;lastStatus;awaitingFirstChunk=!1;streamed=!1;constructor(e){this.call=e}row(e){let t=typeof e.eventType==`string`?e.eventType:void 0;return!t||!xa.has(t)?(this.firstChunk(),!1):(t===`http_request`?this.open(e):t===`http_response`?this.response(e):t===`http_error_body`?this.errorBody(e):this.thrown(e),!0)}open(e){this.current?.end();let t=this.last?.msSinceEnd();this.current=this.call.child(String(e.method??`GET`),{kind:`CLIENT`,attributes:{"http.request.method":String(e.method??`GET`),...Xa(e.url),"http.request.resend_count":this.tries,...typeof e.keySlot==`string`?{"theorem.key_slot":e.keySlot}:{},...X(`theorem.retry.backoff_ms`,t),...Ya(`http.request.header`,e.headers)}}),this.tries+=1,this.streamed=q(e.body)?.stream===!0,this.streamed&&this.call.set({"gen_ai.request.stream":!0}),`body`in e?this.current.event(`theorem.wire.request`,{body:N(e.body)}):typeof e.bodyKind==`string`&&this.current.event(`theorem.wire.request`,{body_kind:e.bodyKind}),typeof e.keySlot==`string`&&this.call.set({"theorem.key_slot":e.keySlot})}response(e){let t=typeof e.status==`number`?e.status:void 0;this.lastStatus=t,this.current?.set({...X(`http.response.status_code`,t),...Ya(`http.response.header`,e.headers)}),t!==void 0&&t>=ba?this.current?.set({"error.type":String(t)}):this.awaitingFirstChunk=!0}errorBody(e){this.current?.event(`theorem.upstream.row`,{row:N(e)}),this.close({code:`ERROR`,message:String(this.lastStatus??`error`)})}thrown(e){let t=typeof e.name==`string`?e.name:`Error`;this.current?.event(`exception`,{"exception.type":t,"exception.message":A(String(e.message??``))}),this.current?.set({"error.type":t}),this.close({code:`ERROR`,message:t})}firstChunk(){this.awaitingFirstChunk&&this.current&&(this.awaitingFirstChunk=!1,this.call.set({"gen_ai.response.time_to_first_chunk":this.current.msSinceStart()/ya}))}close(e){this.current&&=(this.current.end(e),this.last=this.current,void 0)}};function Qa(e,t,n){return e!==void 0&&e>=ba?{code:`ERROR`,message:String(e)}:n===void 0?t?{code:`UNSET`}:{code:`OK`}:{code:`ERROR`,message:Be(n)}}function $a(e){return e instanceof Error?e.name:`Error`}function eo(e,t){e.event(`exception`,{"exception.type":$a(t),"exception.message":A(Qe(t)),...t instanceof Error&&t.stack?{"exception.stacktrace":A(t.stack)}:{}})}function to(e,t){eo(e,t);let n=Be(t);e.set({"error.type":n}),e.end({code:`ERROR`,message:n})}function no(e,t){for(let[n,r]of t)r.decided||e.event(`theorem.guardrail`,{...Va(n,r.ms,void 0,{stage:Ba[n],trust:`untrusted`}),runs:r.runs})}function ro(e){let t=0;for(let n of e.values())t+=n.ms;return t>0?{"theorem.guardrail.stream_ms":t}:{}}var io=new Set([`cancelled`,`interrupted`]);function ao(e,t){let n=e!==void 0&&io.has(e.kind),r=e&&!n?Ca[e.kind]??e.kind:void 0;return t?{stopped:n,finish:r,status:{code:`ERROR`,message:t},attributes:{"error.type":t}}:{stopped:n,finish:r,status:{code:n?`UNSET`:`OK`},attributes:{}}}function oo(e,t,n){let r=t?n===`turn`?{"gen_ai.response.finish_reasons":[t]}:{"gen_ai.response.status":t}:{};return{...X(`gen_ai.response.id`,e?.id||void 0),...X(`gen_ai.response.model`,e?.model||void 0),...r}}function so(e,t){let{req:n,usage:r,transport:i,operation:a}=t,o=Oa(r),s=e(a?`${a} ${n.apiId}`:n.apiId,{kind:`CLIENT`,attributes:{...Ka(n,t.binding,i,a),"gen_ai.input.messages":o.input,...X(`theorem.input.sent_from`,o.sentFrom),"theorem.step":t.step,...X(`theorem.attempt`,t.attempt)}}),c=new Za(s),l=new ka,u=new ka,d=[],f,p,m=!1,h=new Map,g;return{span:s,tap:e=>{c.row(e)||s.event(`theorem.upstream.row`,{row:N(e)})},observe:e=>{if(e.type===`evidence`&&e.evidence.kind===`input_transcription`){u.add(e,s.nowUnixNano());return}l.add(e,s.nowUnixNano()),e.type===`text`&&!m&&(m=!0,s.set({"theorem.response.time_to_first_text":s.msSinceStart()/ya}));let t=Ra(e);t&&s.event(`theorem.grounding`,t),e.type===`error`&&d.push(e),e.type===`response`&&(f=e.response),e.type===`done`&&(p=e.stop.native??p)},guardrail:e=>{let t=g?h.get(g):void 0;!(g&&t)||t.decided?s.event(`theorem.guardrail`,za(e)):(t.decided=!0,s.event(`theorem.guardrail`,{...Va(g,t.ms,e,{stage:Ba[g],trust:`untrusted`}),runs:t.runs}))},guardTime:(e,t)=>{let n=h.get(e)??{ms:0,runs:0,decided:!1};n.ms+=t,n.runs+=1,h.set(e,n),g=e},end:e=>{for(let e of d)s.event(`exception`,{"exception.type":e.errorKind,"exception.message":A(e.errorInternal??e.error??``)});e.thrown!==void 0&&eo(s,e.thrown),no(s,h);let t=d.at(-1),n=e.thrown===void 0?t?.errorKind:Be(e.thrown),a=ao(e.stop,n),o={role:`assistant`,parts:l.parts,...X(`finish_reason`,a.finish)},{input:m}=Oa(r);Da.set(r,{input:m,output:o});let g=u.parts.length>0?[{role:`user`,parts:u.parts}]:[];c.close(Qa(c.lastStatus,a.stopped,e.thrown)),s.set({"gen_ai.input.messages":[...m,...g],"gen_ai.output.messages":[o],...e.tokens?Ua(e.tokens):{},...oo(f,a.stopped?void 0:p,i),...X(`theorem.stop.kind`,e.stop?.kind),...ro(h),...a.attributes}),s.end(a.status)}}}function co(e){let t=[...e?.attachments??[],...e?.voice??[]].map(e=>`uri`in e?{type:`uri`,modality:wa(e.mimeType),mime_type:e.mimeType,uri:e.uri}:{type:`blob`,modality:wa(e.mimeType),mime_type:e.mimeType,...We(e.data)}),n=[...e?.text?[{type:`text`,...A(e.text)}]:[],...t];return n.length>0?[{role:`user`,parts:n}]:[]}function lo(e){return(e??[]).map(e=>({traceparent:e.traceparent,attributes:{"theorem.link.kind":e.kind,...X(`theorem.stop.kind`,e.stop)}}))}function uo(e){return{...X(`gen_ai.conversation.id`,e.conversationId),...X(`theorem.project.id`,e.projectId)}}function fo(e){return{...X(`theorem.request.effort`,e.effort),...X(`theorem.request.model_select`,e.model)}}function po(e){return{kind:`INTERNAL`,attributes:{"gen_ai.operation.name":`invoke_agent`,"gen_ai.agent.name":e.profile,...uo(e),"gen_ai.input.messages":co(e.input),...fo(e)},links:lo(e.links)}}var mo=new Set([`completed`,`length`,`generation_complete`]);function ho(e,t){let n=ga(t.seen),r=da(t.seen,e=>e.type===`done`),i=r?.stop.kind,a=da(t.seen,e=>e.type===`error`),o=a?.error,s=t.thrown!==void 0;s&&eo(e,t.thrown);let c=s||i!==void 0&&na(i),l=s?Be(t.thrown):a?.errorKind??i,u={role:`assistant`,parts:t.delivered.parts,...X(`finish_reason`,ao(r?.stop,void 0).finish)};e.set({"gen_ai.output.messages":[u],...n?Ua(n):{},...i?{"theorem.stop.kind":i}:{},"theorem.attempts":t.attempts,"theorem.steps":t.calls,...t.seen.some(e=>e.type===`compaction`&&e.outcome===`compacted`)?{"gen_ai.conversation.compacted":!0}:{},...c&&o?{"theorem.error.public":A(o)}:{},...c&&l?{"error.type":l}:{}}),c?e.end({code:`ERROR`,...l?{message:l}:{}}):e.end(i&&!mo.has(i)?{code:`UNSET`}:{code:`OK`})}function go(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*_o(e){if(typeof e==`string`)yield e;else if(Array.isArray(e))for(let t of e)yield*_o(t);else if(typeof e==`object`&&e)for(let t of Object.values(e))yield*_o(t)}function vo(e,t){let n=new Set;for(let r of e)for(let e of _o(r))for(let r of go(e,t))typeof r!=`string`&&n.add(r.reference);return Object.fromEntries(Object.entries(t).filter(([e])=>n.has(e)))}var yo=/\{\{?([^{}]*)\}\}?/g,bo=/[\p{Cc}\p{Cf}]/gu,xo=/^-?\d+$/,So=/^(\d{4})-(\d{2})-(\d{2})(?:[T ](\d{2}):(\d{2})(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:?\d{2})?)?$/,Co=new Intl.NumberFormat(void 0,{maximumFractionDigits:2}),wo=new Intl.PluralRules(`en`),To=new Intl.DateTimeFormat(void 0,{dateStyle:`medium`,timeZone:`UTC`}),Eo=new Intl.DateTimeFormat(void 0,{dateStyle:`medium`,timeStyle:`short`,timeZone:`UTC`}),Do=/^\+\s+/,Oo=/:(?:\s|$)/,ko=/^(\S+) is (?:(not) )?(\S.*)$/;function Ao(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 jo(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 Mo(e,t){let n=e;for(let e of t)if(Array.isArray(n)){if(e===`length`)n=n.length;else if(xo.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 No(e){let t=So.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?To:Eo).format(s)}function Po(e){if(typeof e==`number`)return Number.isFinite(e)?Co.format(e):void 0;if(typeof e!=`string`)return;let t=e.replace(bo,` `).replace(/\s+/g,` `).trim();return(No(t)??t)||void 0}function Fo(e){let t=[];for(let n of e.replace(/\s+/g,` `).split(` and `)){let[,e,r,i]=ko.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 Io(e){let t=Do.test(e),n=e.replace(Do,``).trimStart();if(!/^when(\s|$)/.test(n))return{joined:t,when:[],text:n};let r=n.search(Oo);return r<0?{joined:t,when:`unreadable`,text:``}:{joined:t,when:Fo(n.slice(4,r)),text:n.slice(r+1).trimStart()}}function Lo(e){let t=Io(e);return{...t,text:t.text.trim()}}function Ro(e){let t=typeof e==`string`?[e]:e,n=[];return t.forEach((e,t)=>{let r=Lo(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 zo(e){let[t]=jo(e,[`input`]);return t?.side===`input`?t.keys:void 0}function Bo(e,t){let n=zo(e.path);if(!n)return!1;let r=Mo(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 Vo(e){return e.length<=1?e[0]??``:`${e.slice(0,-1).join(`, `)}${e.length>2?`,`:``} and ${e.at(-1)}`}function Ho(e){return e.replace(/([a-z\d])([A-Z])/g,`$1 $2`).replace(/[_-]+/g,` `).trim().toLowerCase()}function Uo(e,t){if(t===`unreadable`)return;let n=e.find(e=>typeof e==`number`&&Number.isFinite(e));if(n!==void 0)return`${Co.format(n)} ${wo.select(n)===`one`?t.one:t.other}`}function Wo(e,t,n){let r=!1,i=e.replace(yo,(e,i)=>{let{path:a,fallback:o,forms:s}=Ao(i),c=a?jo(a,n).map(e=>Mo(t[e.side],e.keys)):[],l=s?Uo(c,s):c.map(Po).find(Boolean);return l===void 0&&o===void 0&&(r=!0),l??o??``}).replace(/\s+/g,` `).trim();return r||!i?void 0:i}function Go(e,t){if(e===void 0)return;let n=`output`in t?[`input`,`output`]:[`input`];for(let r of Ro(e)){let e=r.lines.flatMap(({line:e})=>{if(e.when===`unreadable`||!e.when.every(e=>Bo(e,t.input)))return[];let r=Wo(e.text,t,n);return r===void 0?[]:[r]});if(e.length)return Vo(e)}}var Ko=[`value`,`group`,`flag`,`missing`];function Z(e){return(Array.isArray(e.type)?e.type:[e.type]).filter(e=>typeof e==`string`&&e!==`null`)}function qo(e){return[e.anyOf,e.oneOf,e.allOf].flatMap(e=>Array.isArray(e)?e.filter(E):[])}function Jo(e){let t=Ko.find(t=>e.some(e=>e.holds===t))??`missing`;return{holds:t,instead:e.filter(e=>e.holds===t).flatMap(e=>e.instead??[])}}function Yo(e,t){let n=e=>t?`${t}.${e}`:e;if(!E(e))return[];let r=qo(e);return r.length?r.flatMap(e=>Yo(e,t)):Z(e).includes(`array`)?[...Xo(e.items,n(`0`)),n(`length`)]:E(e.properties)?Object.entries(e.properties).flatMap(([e,t])=>Xo(t,n(e))):[]}function Xo(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=qo(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?Yo(e,t):[t]}function Zo(e,t,n){if(!E(e)||`$ref`in e)return{holds:`value`};let r=qo(e);if(r.length)return Jo(r.map(e=>Zo(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:Yo(e,n)}:{holds:`value`};let s=n?`${n}.${a}`:a,c={holds:`missing`,instead:Yo(e,n)};if(i.includes(`array`)){if(a===`length`)return o.length?c:{holds:`value`};if(xo.test(a))return E(e.items)?Zo(e.items,o,s):{holds:`value`}}return E(e.properties)?Object.hasOwn(e.properties,a)?Zo(e.properties[a],o,s):c:i.length===0||i.includes(`object`)?{holds:`value`}:c}function Qo(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 $o(e,t,n){for(let r of e.matchAll(yo)){let{path:e,forms:i}=Ao(r[1]??``);if(!e)return`Put a field name between the braces, like {${Yo(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=jo(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=Jo(a.map(({side:e,keys:n,prefixed:r})=>Zo(t[e],n,r?e:``)));if(s.holds===`value`){let n=a.some(({side:e,keys:n})=>rs(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}${Qo((u.length?u:c).toSorted((e,t)=>p(e)-p(t)))}`}}var es={texts:`any`,nullable:!0,number:!0};function ts(e){return(Array.isArray(e.type)?e.type:[e.type]).filter(e=>typeof e==`string`)}function ns(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=ts(e);if(n.length===0)return es;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 rs(e,t){if(!E(e)||`$ref`in e)return[es];let n=qo(e);if(n.length)return n.flatMap(e=>rs(e,t));let[r,...i]=t;if(r===void 0)return[ns(e)];let a=Z(e);if(a.includes(`array`)){if(r===`length`)return i.length?[]:[{texts:`any`,nullable:!1,number:!0}];if(xo.test(r))return rs(e.items,i)}return E(e.properties)?Object.hasOwn(e.properties,r)?rs(e.properties[r],i):[]:a.length===0&&ts(e).length===0?[es]:[]}function is(e){if(!E(e))return[];let t=qo(e).flatMap(is),n=E(e.properties)?Object.keys(e.properties):[];return[...new Set([...n,...t])]}function as(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 os(e,t,n=`this tool's input`){let r=zo(e.path);if(!r)return`A "when" reads what the model sent; "${e.path}" is only there once the call is done.`;let i=Zo(t,r,``);if(i.holds===`missing`){let r=is(t).slice(0,4),i=r.length?` Try ${as(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=rs(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 ${as(o)}.`:``;return`"${e.path}" is never "${e.expected}".${s}`}function ss(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=os(n,t.input);if(e)return e}return!e.text&&(r||e.when.length)?`It has no wording to show.`:$o(e.text,t,n)}function cs(e){if(e.when===`unreadable`||e.when.length)return!1;let t=!1,n=e.text.replace(yo,(e,n)=>{let{fallback:r}=Ao(n);return r===void 0&&(t=!0),r??``});return!t&&n.trim().length>0}function ls(e){let t=e.map(e=>e.lines.some(({line:e})=>cs(e))),n=t.slice(0,-1).indexOf(!0);if(n>=0)return`Line ${e[n]?.lines.find(({line:e})=>cs(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 us={},ds=new WeakMap;function fs(e){let{input:t}=e,n=`output`in e?e.output:us;if(typeof t!=`object`||!t||typeof n!=`object`||!n)return;let r=ds.get(t);r||(r=new WeakMap,ds.set(t,r));let i=r.get(n);return i||(i=new Map,r.set(n,i)),i}function ps(e,t){let n=fs(t),r=JSON.stringify(e);if(n?.has(r))return n.get(r);let i=ms(e,t);return n?.set(r,i),i}function ms(e,t){let n=`output`in t?[`input`,`output`]:[`input`],r=typeof e!=`string`,i=Ro(e);for(let{line:e,number:a}of i.flatMap(e=>e.lines)){let i=ss(e,t,n,r);if(i)return r?`Line ${a}: ${i}`:i}return r?ls(i):void 0}var hs=w({kind:C(`auth_scope_refused`),slot:o(),requested:b(o()),declared:b(o())}),gs={tool_arguments:`tool_call`,taint:`tool_call`,destination:`tool_call`,tool_result:`tool_result`,tool_failure:`tool_result`,network:`network`,network_request:`network`},_s=new WeakSet;function vs(e,t,n,r){e&&(r&&_s.add(r),e.event(`theorem.guardrail`,Va(t,n,r,{stage:gs[t],trust:`untrusted`})))}function ys(e){return e?`execute_tool ${e}`:`execute_tool`}function bs(e){return{"gen_ai.operation.name":`execute_tool`,"gen_ai.tool.name":e.name,"gen_ai.tool.call.id":e.callId,"gen_ai.tool.type":`function`,"gen_ai.tool.call.arguments":A(ja(e.call)),...X(`theorem.tool.origin`,e.origin),...X(`theorem.tool.permission`,e.permission),...X(`theorem.tool.approved`,e.approved),...X(`theorem.step`,e.step)}}function xs(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 Ss={ok:`OK`,error:`ERROR`,denied:`UNSET`,gated:`UNSET`,paused:`UNSET`,cancelled:`UNSET`};function Cs(e,t){let n=e(ys(t.name),bs(t));return{span:n,observe:e=>{if(e.type===`guardrail`&&!_s.has(e.guardrail)&&n.event(`theorem.guardrail`,za(e.guardrail)),e.type===`tool`&&e.tool.phase===`gate`&&n.event(`theorem.gate`,xs(e.tool.gate)),e.type===`tool`&&e.tool.phase===`progress`){let t=hs.safeParse(e.tool.data);if(t.success){let{slot:e,requested:r,declared:i}=t.data;n.event(`theorem.auth.scope_refused`,{slot:e,requested:r,declared:i})}}if(e.type===`tool`&&e.tool.phase===`warning`){let{code:t,message:r,severity:i}=e.tool.warning;n.event(`theorem.tool.warning`,{code:t,message:A(r),...X(`severity`,i)})}e.type===`citation`&&n.event(`theorem.grounding`,{sources:N(e.sources)})},end:e=>{e.thrown!==void 0&&eo(n,e.thrown);let t=e.outcome===`error`?e.failure?.kind??(e.thrown===void 0?void 0: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(Ta)}:{},...e.data?{"theorem.tool.data":N(e.data.value)}:{},"theorem.tool.outcome":e.outcome,...X(`theorem.tool.failure.code`,e.failure?.code),...X(`error.type`,t)});let r=Ss[e.outcome];n.end(r===`ERROR`&&t?{code:r,message:t}:{code:r})}}}function ws(e){return e.modelText===void 0?Ve(yr(e.finding,e.data),Je):e.modelText}var Ts=`Tool error (`;function Es(e){return e.startsWith(Ts)}function Ds(e){return{finding:`${Ts}${e.code}): ${e.message}`,...e.details===void 0?{}:{data:{details:e.details}}}}function Os(e){return Ds({...e,message:Ve(e.message,Je)})}function ks(e,t){return{type:`tool`,tool:{...t,name:e.name,callId:e.callId,...e.operationId?{operationId:e.operationId}:{},at:Date.now()}}}function As(e,t,n,r){return Go(n?.activityFailed,{input:r})??j(`tool.activity_failed`,{tool:Ho(e)},t)}function js(e){return e.activityFailed??As(e.name)}function Ms(e,t,n=ws(Os(t))){return ks(e,{phase:`error`,failure:t,readBack:n,activityPast:js(e)})}function Ns(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 Ps(e){return`call_${e}_${crypto.randomUUID()}`}function Fs(e){return e===void 0?{}:E(e)?e:{value:e}}function Is(e){return e instanceof Error?e.message:String(e)}function Ls(e,t){return ks(e,{phase:`warning`,warning:{code:`sources_invalid`,message:t,severity:`warning`}})}function*Rs(e,t,n){let r;try{r=t(n)}catch(t){yield Ls(e,`sources threw: ${Is(t)}`);return}if(!Array.isArray(r)){yield Ls(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 Ls(e,`sources not cited: ${a.join(` | `)}`)),i.length>0&&(yield{type:`citation`,sources:i,callId:e.callId})}function zs(e,t,n,r){let i=n.resume?.edited,a=Go(e.labels?.activity,{input:t});return ks(r,{phase:`running`,...i?{edited:{from:i.from,to:Fs(t)}}:{},...a?{activity:a}:{}})}var Bs=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*Vs(e,t,n,r,i){return qe(n.signal),yield zs(e,t,n,r),new Bs(i&&(()=>i(t)))}function Hs(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 Us(){return{stage:`network`,trust:`untrusted`,action:`block`,hits:[{rule:ut.blocked,severity:`high`}]}}function*Ws(e,t=Us()){return yield{type:`guardrail`,guardrail:t},{code:`network_blocked`,kind:`blocked`,message:Is(e)}}function*Gs(e,t,n){let r=performance.now();try{let i=$r(e,qs(t));return vs(n,`network`,performance.now()-r,void 0),{ok:!0,url:i}}catch(e){let t=Us();return vs(n,`network`,performance.now()-r,t),{ok:!1,failure:yield*Ws(e,t)}}}function Ks(e){let t=0,n=!1,r=!1;return{onCheck:e=>{t+=e,n=!0},record:i=>{!r&&n&&(r=!0,vs(e,`network_request`,t,i))}}}function qs(e){return Fr(e.profile.guardrails).network}function Q(e,t,n){return C(e).meta({title:t,description:n})}var Js=_({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.`)}),Ys=/^(gemini-embedding-001|text-embedding-|embedding-)/,Xs={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`]}]},Zs={maxInputs:100,media:[]},Qs={query:`RETRIEVAL_QUERY`,document:`RETRIEVAL_DOCUMENT`};function $s(e,t){return t===`query`?`task: search result | query: ${e}`:`title: none | text: ${e}`}function ec(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?$s(e.text,t):e.text}:e.type===`media`?{inlineData:{mimeType:e.mimeType,data:e.data}}:{fileData:{mimeType:e.mimeType,fileUri:e.uri}})}function tc(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 nc(e,t,n){let r={content:{parts:ec(e,n.taskField?void 0:n.task)}},i=n.taskField&&n.task?Qs[n.task]:t.taskType;return i&&(r.taskType=i),t.outputDimensionality&&(r.outputDimensionality=t.outputDimensionality),r}var rc=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:Js,embeddingLimits:e=>Ys.test(e)?Zs:Xs,refusedOptions:e=>Ys.test(e)?[]:[`taskType`],create(e){return{async embed(t){let n=gi(rc,e.apiId,t.options),r={taskField:Ys.test(e.apiId),...t.task?{task:t.task}:{}},i=Array.isArray(t.input)?t.input:[t.input],a=i.length===1?nc(i[0],n,r):{requests:i.map(t=>({model:`models/${e.apiId}`,...nc(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`?tc({embedding:e}):[],dimensions:e&&typeof e==`object`?tc({embedding:e}).length:0}))}}}}}),ic=_({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 ac(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 oc=W({id:`ollamaEmbeddings`,name:`Ollama Embeddings`,description:`Ollama’s local embedding endpoint.`,endpoints:{embedding:`/api/embed`},operationNames:{embedding:`embeddings`},options:ic,embeddingLimits:()=>({media:[]}),create(e){return{async embed(t){let n=ic.parse(t.options??{}),r=e.send({model:e.apiId,input:ac(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}))}}}}}),sc=_({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`.")}),cc={media:[{accept:[`image/*`]}]};function lc(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 uc(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 dc=W({id:`openRouterEmbeddings`,name:`OpenRouter Embeddings`,description:`OpenRouter embedding models, including supported multimodal models.`,endpoints:{embedding:`/embeddings`},operationNames:{embedding:`embeddings`},options:sc,embeddingLimits:()=>cc,create(e){return{async embed(t){let n=sc.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(lc)};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=uc(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}}:{}}}}}}),fc=100,pc=599,mc=new Set([`API_KEY_INVALID`]);function hc(e){return Array.isArray(e)&&e.some(e=>{let t=q(e)?.reason;return typeof t==`string`&&mc.has(t)})}var gc={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},_c=new Set([`safety`,`recitation`,`language`,`prohibited_content`,`spii`,`blocklist`,`image_safety`,`image_prohibited_content`,`image_recitation`,`image_other`,`content_blocked`]);function vc(e,t){if(e===`cancelled`)return new T(`cancelled`,t);if(_c.has(e))return new T(`safety`,t);let n=gc[e];return n===void 0?new T(`bad_response`,t):new T(Xe(n),t)}function yc(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 hc(a)?new T(`auth`,o):typeof n==`number`&&n>=fc&&n<=pc?new T(Xe(n),o):typeof n==`string`?vc(n,o):new T(`bad_response`,o)}function bc(e,t,n){return e?.kind===`auth`?e:new T(Xe(t),e?.message??n)}var xc=_({location:_({latitude:v().min(-90).max(90),longitude:v().min(-180).max(180)})}),Sc=[`googleSearch`,`googleMaps`,`urlContext`,`codeExecution`],Cc={googleSearch:`google_search`,googleMaps:`google_maps`,urlContext:`url_context`,codeExecution:`code_execution`};function wc(e){return e.filter(e=>Sc.includes(e.id))}function Tc(e){let t=Sc.find(t=>t===e.id);if(!t)throw new T(`config`,`Builtin '${e.id}' is not a Google tool`);return t}function Ec(e){let t=Tc(e),n=Cc[t];if(t===`googleMaps`&&e.args){let{location:t}=xc.parse(e.args);return{type:n,latitude:t.latitude,longitude:t.longitude}}return{type:n}}function Dc(e){let t=Tc(e);if(e.args)throw new T(`unsupported`,`Builtin '${t}' takes no args on Google Live`);return{[t]:{}}}function Oc(e){return{type:`text`,text:`[${e.type}: sent in the next message]`}}function kc(e){return{type:`text`,text:`Files from ${e.name?`the ${e.name} result`:`a tool result`}:`}}function Ac(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:Oc(e))}),r.push(kc(a),...e))}return i(),n}var jc={type:`text`,text:`Files the assistant sent:`};function Mc(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:Oc(e))}),n.push(jc,...e))}return n.length>0&&t.push({role:`user`,parts:n}),t}function Nc(e){let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t}function Pc(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 Fc(e){let t=Pc(e);if(!t.ok)throw new T(`bad_response`,t.error);return t.value}function Ic(e,t){let n=e.name.trim(),r={name:n,callId:e.id??Ps(n)},i={stepId:e.stepId,stepCallCount:e.stepCallCount};if(!n)return Lc(r,`function call is missing a name`,t,i);let a=Pc(t);return a.ok?[Ns(r,a.value,i)]:Lc(r,a.error,a.raw,i)}function Lc(e,t,n,r={}){return[Ns(e,{},r),Ms(e,{code:`malformed_arguments`,kind:`bad_response`,message:t,details:{raw:n}})]}var Rc=[`minimal`,`low`,`medium`,`high`],zc=[`pcm`];function Bc(e){if(e&&!Rc.includes(e))throw new T(`unsupported`,`Gemini does not take the '${e}' thinking level (${Rc.join(`, `)})`)}function Vc(e){return e.replaceAll(/[A-Z]/g,e=>`_${e.toLowerCase()}`)}function Hc(e){if(Array.isArray(e))return e.map(Hc);if(e&&typeof e==`object`){let t={};for(let[n,r]of Object.entries(e))n===`schema`||n===`parameters`||n===`arguments`?t[Vc(n)]=r:t[Vc(n)]=Hc(r);return t}return e}function Uc(e){return Pi(e)}var Wc=`user_input`;function Gc(e){return{type:Wc,content:e.map(Uc)}}function Kc(e){let t=K(e);return t.length>0?t.map(Uc):[{type:`text`,text:``}]}var qc=new Set([`text`,`image`,`video`]);function Jc(e){let t=K(e);return{type:`function_result`,...Nc({name:e.name,call_id:e.tool_call_id}),result:t.length>0?t.map(Uc):[{type:`text`,text:``}]}}function Yc(e,t){let n={type:`function_call`,id:e.id,name:e.function.name,arguments:Fc(e.function.arguments)};return t?[{type:`thought`,signature:t},n]:[n]}var Xc=_({call:v().int().min(0),signature:o().min(1)});function Zc(e,t){for(let n of e.reasoning??[]){let e=Xc.safeParse(n.data);if(e.success&&e.data.call===t)return e.data.signature}}function Qc(e,t){return{type:e===`assistant`?`model_output`:`user_input`,content:Kc(t)}}function $c(e){if(e.role===`assistant`&&e.tool_calls&&e.tool_calls.length>0){let t=[];K(e).length>0&&t.push(Qc(`assistant`,e));for(let[n,r]of e.tool_calls.entries())t.push(...Yc(r,Zc(e,n)));return t}return e.role===`assistant`?[Qc(`assistant`,e)]:[Qc(`user`,e)]}function el(e){return Ac(e,qc).flatMap(e=>e.role===`tool`?[Jc(e)]:$c(e))}function tl(e){return[{type:`text`,mimeType:`application/json`,schema:e}]}function nl(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&&!zc.includes(n))throw new T(`unsupported`,`Gemini speech returns ${zc.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=tl(e.structured.jsonSchema))}function rl(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 il=new Set([`gemini-3.8-flash-tts`,`gemini-3.8-flash-lite-tts`]);function al(e,t,n){if(!il.has(n))return{type:Wc,content:[{type:`text`,text:`Read the following aloud. ${t.trim()}\n`},...e.map(Uc)]};let r=[{type:`speech_metadata`,style:t}];return{type:Wc,content:e.map(Uc).map(e=>e.type===`text`?{...e,annotations:r}:e)}}function ol(e){return{type:`function`,name:e.name,description:e.description,parameters:e.parameters}}function sl(e){let t=[];for(let n of e.builtins)t.push(Ec(n));for(let n of e.wireTools??[])t.push(ol(n));return t}function cl(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 ll(e){if(e.continuation&&e.continuation.length>0)return el(cl(e.continuation));let t=el(cl(e.history??[]));if(e.input.length>0||t.length===0){let n=e.speech?.style;t.push(n?al(e.input,n,e.apiId):Gc(e.input))}return t}function ul(e,t){e.store!==void 0&&(t.store=e.store),e.previousInteractionId&&(t.previousInteractionId=e.previousInteractionId),e.system&&(t.systemInstruction=e.system);let n=sl(e);n.length>0&&(t.tools=n)}function dl(e){let t={temperature:e.temperature,maxOutputTokens:e.maxOutputTokens};return e.speech?rl(e,t):(Bc(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:ll(e),generationConfig:t}}function fl(e){let t=dl(e);return nl(e,t),ul(e,t),Hc(t)}var pl=16,ml=new Set([`audio/pcm`,`audio/l16`]);function hl(e,t,n){for(let r=0;r<n.length;r++)e.setUint8(t+r,n.charCodeAt(r))}function gl(e){if(e===void 0||!/^\d+$/.test(e))return;let t=Number(e);return t>0?t:void 0}function _l(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 vl(e){let{essence:t,params:n}=_l(e);if(!ml.has(t))return;let r=gl(n.get(`rate`));if(r===void 0)return;let i=n.has(`channels`)?gl(n.get(`channels`)):1;if(i!==void 0)return{sampleRate:r,channels:i}}function yl(e,t){let{sampleRate:n,channels:r}=t,i=r*pl/8,a=n*i,o=e.length,s=new ArrayBuffer(44+o),c=new DataView(s);return hl(c,0,`RIFF`),c.setUint32(4,36+o,!0),hl(c,8,`WAVE`),hl(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,pl,!0),hl(c,36,`data`),c.setUint32(40,o,!0),new Uint8Array(s,44).set(e),new Uint8Array(s)}function bl(e){let t=vl(e.mimeType);if(!t)return e;let n=yl(vt(e.data),t);return{mimeType:`audio/wav`,data:St(n)}}function xl(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 Sl(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 Cl(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 wl(e){if(!e)return[];let{grounding:t,sources:n}=e;return[{type:`grounding`,grounding:t},...n.length>0?[{type:`citation`,sources:n}]:[]]}function Tl(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 El(e){return{maps:{title:e.title,uri:e.uri,...e.placeId?{placeId:e.placeId}:{}}}}function Dl(e){let t=J(e.uri);if(t)return{type:`web`,uri:t,title:J(e.title)??t}}function Ol(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 kl(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 Al(e){if(Array.isArray(e))for(let t of e){let e=J(q(t)?.search_suggestions);if(e)return e}}function jl(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 Ml(e,t){if(Array.isArray(t))for(let n of t)Ol(e,jl(n))}function Nl(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?Tl(t):void 0;r&&Ol(e,r)}}}function Pl(e){let t=[];if(Ml(t,e.annotations),Array.isArray(e.content))for(let n of e.content)Ml(t,q(n)?.annotations);Nl(t,e.result);let n=[];for(let e of t)e.type===`maps`&&kl(n,El(e));let r=Al(e.result);if(r||t.length!==0)return{grounding:{metadata:e,...n.length>0?{chunks:n}:{},...r?{searchHtml:r}:{}},sources:t}}function Fl(e,t){if(!e)return t;if(!t)return e;let n=[];for(let r of[...e.grounding.chunks??[],...t.grounding.chunks??[]])kl(n,r);let r=[...e.sources];for(let e of t.sources)Ol(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 Il(e){let t=q(e.delta);return wl(t?Pl(t):void 0)}function Ll(e){let t;for(let n of e){let e=q(n);e&&(t=Fl(t,Pl(e)))}return wl(t)}function Rl(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&&Ol(r,Dl(t))}let i=J(q(t.searchEntryPoint)?.renderedContent);return wl({grounding:{metadata:t,...n.length>0?{chunks:n}:{},...i?{searchHtml:i}:{}},sources:r})}function zl(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 Bl(e,t){if(e||t)return{...e?{input:e}:{},...t?{output:t}:{}}}function Vl(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 Hl(e){let t=q(e);return t?.type===`text`&&typeof t.text==`string`?t.text:``}function Ul(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 Wl=[[`/9j/`,`image/jpeg`],[`iVBORw0KGgo`,`image/png`],[`UklGR`,`image/webp`]];function Gl(e){return Wl.find(([t])=>e.startsWith(t))?.[1]}function Kl(e){let{data:t}=e;if(typeof t!=`string`||!t)return[];let n=Ul(e)??(e.type===`image`?Gl(t):void 0);return n?[{type:`media`,media:{mimeType:n,data:t}}]:[]}function ql(e,t){return t?[{type:e,text:t}]:[]}function Jl(e){return e===`code_execution_call`||e===`code_execution_result`}function Yl(e){return e.startsWith(`google_`)||e===`url_context_call`||e===`url_context_result`}function Xl(e){return{type:`evidence`,evidence:{provider:`google`,kind:`provider_step`,step:String(e.type??``),raw:e}}}function Zl(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`?Xl(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 Ql(e){let t=q(e);if(!t)return[];switch(t.type){case`thought_summary`:return ql(`thought`,Hl(t.content));case`text`:return ql(`text`,typeof t.text==`string`?t.text:``);case`image`:case`audio`:return Kl(t);default:return[]}}function $l(e){return(Array.isArray(e.summary)?e.summary:[]).flatMap(e=>ql(`thought`,Hl(e)))}function eu(e){return(Array.isArray(e.content)?e.content:[]).flatMap(e=>{let t=q(e);return t?.type===`text`?ql(`text`,typeof t.text==`string`?t.text:``):t?.type===`image`||t?.type===`audio`?Kl(t):[]})}function tu(e){let t=q(e);if(!t)return;let n=Y(t.total_output_tokens),r=Y(t.total_thought_tokens)??0,i=Y(t.total_tool_use_tokens)??0,a=Y(t.total_tokens),o=a===void 0?void 0:a-(n??0)-r-i,s=Y(t.total_input_tokens)||(o&&o>0?o:0);return fa({input:s?s+i:void 0,output:n===void 0?void 0:n+r,thinking:r,toolUse:i,cached:Y(t.total_cached_tokens),byModality:Bl(zl(t.input_tokens_by_modality,`tokens`),zl(t.output_tokens_by_modality,`tokens`)),grounding:Vl(t.grounding_tool_count)})}function nu(e){let t=tu(e.usage);if(!t)return;let n=typeof e.id==`string`?e.id:void 0;return{type:`tokens`,tokens:t,...n?{interactionId:n}:{}}}function ru(e){let t=[],n=nu(e);n&&t.push(n);let{steps:r}=e;Array.isArray(r)&&t.push(...Ll(r));let i=au(e);return i&&t.push(i),t}function iu(e){let t=J(e.id),n=J(e.model);if(t||n)return{...t?{id:t}:{},...n?{model:n}:{}}}function au(e){let{status:t}=e;if(typeof t==`string`)return{type:`done`,stop:ua(t),...typeof e.id==`string`?{interactionId:e.id}:{}}}function ou(){return{text:``,steps:new Map,sawMedia:!1,sawDone:!1,calls:0}}function su(e){return e===`function_call`||Jl(e)||Yl(e)}function cu(e){return typeof e==`string`&&e.length>0?e:void 0}function lu(e,t){let n=cu(e);n&&(t.thoughtSignature=n)}function uu(e,t){let n=cu(e.signature)??t.thoughtSignature;return t.thoughtSignature=void 0,n}function du(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=uu(e,t),a=t.calls++;return[...i?[{type:`reasoning`,data:{call:a,signature:i},origin:{protocol:`geminiInteractions`}}]:[],...Ic({id:n,name:r},e.arguments)]}return Jl(n)?[Zl(e)]:Yl(n)?[Xl(e)]:n===`thought`?(lu(e.signature,t),$l(e)):n===`model_output`?eu(e):[]}function fu(e){return typeof e.index==`number`?e.index:0}function pu(e,t){let n=q(e.step);if(!n)return;let r=String(n.type??``);r===`thought`&&lu(n.signature,t),su(r)&&t.steps.set(fu(e),{...n})}function mu(e,t){let n=q(e.delta);if(!n)return[];let r=t.steps.get(fu(e));if(!r)return n.type===`thought_signature`&&lu(n.signature,t),Ql(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`?Cl({id:cu(r.id),name:typeof r.name==`string`?r.name:``,args:t,drafted:e.length}):[]}return Object.assign(r,n),[]}function hu(e,t){let n=fu(e),r=t.steps.get(n);return r?(t.steps.delete(n),du(r,t)):[]}function gu(e){let t=Jl(String(e.type??``))?Zl(e):Xl(e);return{...t,evidence:{...t.evidence,partial:!0}}}function _u(e){let t=[...e.steps.values()].map(gu);return e.steps.clear(),t}function vu(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:bl(e.media)})))}function yu(e,t){if(e.eventType===`sse_unparsed`)return[D(new T(`bad_response`,`Interactions stream row was not a JSON object`))];let n=yc(e);if(n)return[D(n)];let r=Il(e);switch(e.event_type){case`step.start`:pu(e,t);break;case`step.delta`:r.push(...mu(e,t));break;case`step.stop`:r.push(...hu(e,t));break;case`interaction.created`:{let n=q(e.interaction);n&&r.push(...bu(n,t));break}case`interaction.completed`:{let n=q(e.interaction);n&&r.push(...bu(n,t),...ru(n));break}}return r}function bu(e,t){let n=xl(t.response,iu(e));return t.response=n.known,n.event?[n.event]:[]}function xu(e,t){return vu(yu(e,t),t)}function Su(e,t){let n=(Array.isArray(e.steps)?e.steps:[]).flatMap(e=>{let n=q(e);return n?du(n,t):[]});return vu([...bu(e,t),...n,...ru(e)],t)}function*Cu(e,t){e.structured&&t.text&&(yield Sl(t.text))}function wu(e){return!!e.speech}function Tu(e,t){if(!t.sawMedia){if(wu(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 Eu(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 Du=_({interactionId:o().min(1)}),Ou=_({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 ku(e,t){let n=t.history??[],r=e.options.persistViaInteractionId?t.state?.interactionId:void 0,i=wc(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(fl(a)))),wroteTools:i.map(e=>e.id)}}function Au(e,t,n){return e.flatMap(e=>{if(e.type!==`done`){let t=Eu(e);return t?[t]:[]}let{interactionId:r,...i}=e;return t.done={...i,...n&&r?{state:{interactionId:r}}:{}},[]})}var ju=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:Ou,continuation:{version:1,schema:Du,keyOptions:[`store`,`persistViaInteractionId`]},reasoning:Xc,error(e){let t=q(e.body);return bc(t?yc(t):null,e.status,`Gemini HTTP ${e.status}`)},create(e){return{async*complete(t){let{wire:n,body:r,wroteTools:i}=ku(e,t),a=t.stream!==!1,o=!!e.options.persistViaInteractionId,s={fold:ou()},c={stream:a,wroteTools:i,...a?{path:`/interactions?alt=sse`}:{}};for await(let t of e.send(r,c)){let e=yc(t);if(e)throw e;let n=a?xu(t,s.fold):Su(t,s.fold);if(yield*Au(n,s,o),n.some(e=>e.type===`error`)){yield*Au(_u(s.fold),s,o);return}}yield*Au(_u(s.fold),s,o),yield*Au([...Cu(n,s.fold)],s,o);let l=Tu(n,s.fold);l&&(yield*Au([l],s,o)),yield s.done??{type:`done`,stop:{kind:`stream_incomplete`}}}}}}),Mu=`NON_BLOCKING`;function Nu(e){return{name:e.name,description:e.description,behavior:Mu,parametersJsonSchema:e.parameters??{type:`object`,properties:{}}}}function Pu(e){let t=[];for(let n of e.builtins)t.push(Dc(n));let n=(e.wireTools??[]).map(Nu);return n.length>0&&t.push({functionDeclarations:n}),t}function Fu(e){let t={responseModalities:[`AUDIO`],temperature:e.temperature,maxOutputTokens:e.maxOutputTokens};e.live?.voice&&(t.speechConfig={voiceConfig:{prebuiltVoiceConfig:{voiceName:e.live.voice}}}),Bc(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 Iu(e){let{triggerTokens:t}=e,{targetTokens:n}=e.slidingWindow;return{...t===void 0?{}:{triggerTokens:t},slidingWindow:n===void 0?{}:{targetTokens:n}}}function Lu(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 Ru(e){if(e.sessionResumptionHandle)return{handle:e.sessionResumptionHandle};if(e.live?.sessionResumption)return{}}function zu(e){return e.startsWith(`models/`)?e:`models/${e}`}function Bu(e,t){e?.transcription?.input&&(t.inputAudioTranscription={}),e?.transcription?.output&&(t.outputAudioTranscription={})}function Vu(e){let t=e.live,n=t?.vad?Lu(t.vad):void 0,r=Pu(e),i=Ru(e),a=!!(e.history?.length||e.context?.length),o={model:zu(e.apiId),generationConfig:Fu(e),systemInstruction:{parts:[{text:e.system}]},...r.length>0?{tools:r}:{},...i?{sessionResumption:i}:{},...t?.contextCompression?{contextWindowCompression:Iu(t.contextCompression)}:{},...a?{historyConfig:{initialHistoryInClientContent:!0}}:{},...n?{realtimeInputConfig:n}:{}};return Bu(t,o),{setup:o}}function Hu(e){if(Fi(e))throw new T(`unsupported`,`media references are not supported on geminiLive`);return e}function Uu(e){let t=Hu(e);return{mimeType:t.mimeType,data:t.data}}function Wu(e){return e.type===`text`?{text:e.text}:{inlineData:Uu(e)}}function Gu(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(Wu);return{role:`user`,parts:[{functionResponse:{...Nc({id:e.tool_call_id,name:e.name}),response:{result:n},...r.length>0?{parts:r}:{}}}]}}function Ku(e){if(e.role===`tool`)return Gu(e);let t=e.role===`assistant`?`model`:`user`,n=K(e).map(Wu);for(let t of e.role===`assistant`?e.tool_calls??[]:[])n.push({functionCall:{id:t.id,name:t.function.name,args:Fc(t.function.arguments)}});return{role:t,parts:n}}function qu(e=[],t=[]){return e.length===0&&t.length===0?null:{clientContent:{turns:[...e.map(Ku),...t.length?[{role:`user`,parts:t.map(e=>({text:e}))}]:[]],turnComplete:!0}}}function Ju(e){return{clientContent:{turns:[{role:`user`,parts:[{text:e}]}],turnComplete:!1}}}function Yu(e){if(e.type===`text`)return{realtimeInput:{text:e.text}};let t=Hu(e),n={mimeType:t.mimeType,data:t.data};return{realtimeInput:t.type===`audio`?{audio:n}:{video:n}}}function Xu(e){let t=q(e)?.error;return typeof t==`string`?{error:t}:{result:e}}function Zu(e,t,n,r){return Qu([{id:e,name:t,output:n,parts:r}])}function Qu(e){return{toolResponse:{functionResponses:e.map(({id:e,name:t,output:n,parts:r})=>({id:e,name:t,response:Xu(n),...r?.length?{parts:r.filter(e=>e.type!==`text`).map(Wu)}:{}}))}}}function $u(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 ed(e){return Array.isArray(e)?e.flatMap(e=>{let t=q(e);return t?[t]:[]}):[]}function td(e){let t=[],n=[],r=[];for(let i of ed(e.parts)){let e=q(i.inlineData),a=q(i.functionCall),o=q(i.functionResponse);if(typeof i.text==`string`)t.push({type:`text`,text:i.text});else if(e&&typeof e.mimeType==`string`&&typeof e.data==`string`){let n=Rr(e.mimeType)??`document`;t.push({type:n,mimeType:e.mimeType,data:e.data})}else a?n.push({id:typeof a.id==`string`?a.id:``,type:`function`,function:{name:String(a.name??``),arguments:JSON.stringify(a.args??{})}}):o&&r.push($u(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 nd(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 ed(n.turns).flatMap(td);let r=q(e.toolResponse);return r?ed(r.functionResponses).map($u):[]}function rd(e){let t=Y(e.promptTokenCount),n=Y(e.responseTokenCount),r=Y(e.thoughtsTokenCount)??0,i=Y(e.toolUsePromptTokenCount)??0;return fa({input:t?t+i:void 0,output:n===void 0?void 0:n+r,thinking:r,toolUse:i,cached:Y(e.cachedContentTokenCount),byModality:Bl(zl(e.promptTokensDetails,`tokenCount`),zl(e.responseTokensDetails,`tokenCount`))})}function id(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 ad(){return{calls:new Map}}function od(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(...Ic({id:o,name:s,stepId:i,stepCallCount:a},r.args))}}function sd(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(ks({name:r,callId:e},{phase:`cancel`})))}}function cd(e,t){let n=q(e.voiceActivity);n&&t.push({type:`evidence`,evidence:{provider:`google`,kind:`voice_activity`,raw:n}})}function ld(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 ud(e,t){let n=q(e.goAway);if(!n)return;let r=ld(n.timeLeft);t.push({type:`session`,session:{kind:`closing_soon`,...r===void 0?{}:{timeLeftMs:r}}})}function dd(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:bl({mimeType:r,data:i})});let a=q(e.codeExecutionResult);a&&t.push(fd(a))}function fd(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 pd(e){let t=q(e)?.text;return typeof t==`string`&&t?t:void 0}function md(e,t,n,r){let i=pd(e);i&&n.push({type:`evidence`,text:i,evidence:{provider:`google`,kind:t,...r?{interim:!0}:{}}})}function hd(e,t){t.push(...Rl(e.groundingMetadata));let n=q(e.urlContextMetadata);n&&t.push({type:`evidence`,evidence:{provider:`google`,kind:`url_context`,raw:n}})}function gd(e){let t=q(e.serverContent)?.interactionStatus;if(t===`IN_PROGRESS`||t===`IDLE`)return t}function _d(e,t){let n=gd(e);n&&t.push({type:`session`,session:{kind:n===`IDLE`?`idle`:`working`}})}function vd(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`}}),md(n.inputTranscription,`input_transcription`,t),md(n.interimInputTranscription,`input_transcription`,t,!0),md(n.outputTranscription,`output_transcription`,t);let r=q(n.modelTurn)?.parts;for(let e of Array.isArray(r)?r:[]){let n=q(e);n&&dd(n,t)}hd(n,t),n.turnComplete===!0&&t.push({type:`session`,session:{kind:`turn_complete`}})}function yd(e,t){let n=q(e.usageMetadata),r=n?rd(n):void 0;r&&t.push({type:`tokens`,tokens:r})}function bd(e,t){if(!e||typeof e!=`object`)return[];let n=[];return ud(e,n),id(e,n),od(e,t,n),sd(e,t,n),cd(e,n),vd(e,n),_d(e,n),yd(e,n),n}var xd={1006:`network`,1007:`unsupported`,1008:`unsupported`,1011:`unavailable`,1013:`busy`},Sd=/\bquota\b/i,Cd=/\bAPI key (?:not valid|expired)\b/i;function wd(e){if(Sd.test(e))return`rate_limit`;if(Cd.test(e))return`auth`}function Td(e,t,n){return new T(wd(t)??xd[e]??`unavailable`,`Gemini Live WebSocket closed during ${n} (${e}: ${t})`)}function Ed(e){let t=da(e,e=>e.type===`session`&&e.session.kind===`closing_soon`);return t?.session.kind===`closing_soon`?{timeLeftMs:t.session.timeLeftMs}:void 0}function Dd(e){return gd(e)===`IDLE`&&Object.keys(q(e.serverContent)??{}).length===1}function Od(e,t){if(t.some(e=>e.type===`done`&&e.interrupted===!0))return`abort`;let n=gd(e);return n===`IDLE`?`complete`:n===`IN_PROGRESS`?`streaming`:q(e.serverContent)?.turnComplete===!0?`complete`:`streaming`}var kd=_({liveHandle:o().min(1)}),Ad=1e3;function jd(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`):yc(e)??void 0}async function Md(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 Td(1006,``,`setup`);let n=t.value;if(n.eventType===`ws_close`)throw Td(Number(n.code),String(n.reason??``),`setup`);let r=jd(n,`setup`);if(r)throw r;if(n.setupComplete)return}}finally{clearTimeout(n)}}function Nd(e,t){let n=t.state?.liveHandle,r=t.history??[],i=wc(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(Vu(a)))),wroteTools:i.map(e=>e.id)}}function*Pd(e,t,n){let r=[...e.filter(e=>e.type===`tokens`),...e.filter(e=>e.type!==`tokens`)];for(let e of r){let t=Eu(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 Fd(e,t,n,r){let i=t=>Rd(e,t),a=ad(),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===Ad?{}:{error:Td(e,t,`session`)},...c?{warning:{...c.timeLeftMs===void 0?{}:{timeLeftMs:c.timeLeftMs},closedAfterMs:Math.round(performance.now()-c.atMs)}}:{}};return}let i=jd(r,`session`);if(i)throw i;if(r.setupComplete)continue;let u=bd(r,a),d=Ed(u);d&&(c={...d,atMs:performance.now()});for(let e of u)e.type===`evidence`&&e.sessionResumptionHandle&&(o=e.sessionResumptionHandle);let f=Od(r,u);yield*Pd(u,s&&Dd(r)?`streaming`:f,o),f===`complete`?s=!0:r.serverContent&&(s=!1)}},sendText:e=>Ld(()=>i(Yu({type:`text`,text:e}))),sendAudio:e=>Ld(()=>i(Yu({type:`audio`,...e}))),sendVideo:e=>Ld(()=>i(Yu({type:`video`,...e}))),sendContext:e=>Ld(()=>i(Ju(typeof e.server==`string`?e.server:JSON.stringify(e)))),sendToolResult:e=>Ld(()=>i(Zu(e.callId,e.name,e.text,e.parts))),close:t=>Ld(()=>e.close(Ad,t??`session-closed`))}}var Id=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:kd},create(e){return{async openSession(t){let{wire:n,setup:r,wroteTools:i}=Nd(e,t),a=await e.connect(r,{wroteTools:i}),o=a.frames()[Symbol.asyncIterator](),s=()=>a.close(Ad,`aborted`);e.signal?.addEventListener(`abort`,s,{once:!0});try{e.signal?.throwIfAborted(),await Md(o,e)}catch(t){throw e.signal?.removeEventListener(`abort`,s),a.close(Ad,`setup-failed`),t}let c=qu(n.history,n.context);c&&Rd(a,c);for(let e of n.input)Rd(a,Yu(e));return Fd(a,o,e,n.sessionResumptionHandle)}}}});function Ld(e){try{return e(),Promise.resolve()}catch(e){return Promise.reject(e)}}function Rd(e,t){e.send(t,nd(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=Wi({id:`gemini`,name:`Gemini`,description:`Google's models with an API key, from Google AI Studio.`,traceName:`gcp.gemini`,connection:_({host:zi.refine(e=>{let t=new URL(e);return t.pathname===`/`&&!t.search&&!t.hash},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:Vi(`x-goog-api-key`),prices:Bd,check:{protocol:ju,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:ju,baseUrl:`${n}/v1beta`},{protocol:rc,baseUrl:`${n}/v1beta`},{protocol:Id,baseUrl:`${r}/ws`,authorize:Hi(`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(Fi(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`,...Nc({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=Mc(e.history??[]);for(let e of Ac(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 fa({input:Y(t.prompt_tokens)??Y(t.input_tokens),output:Y(t.completion_tokens)??Y(t.output_tokens),thinking:Y(r?.reasoning_tokens),cached:Y(n?.cached_tokens),cacheWrite:Y(n?.cache_write_tokens),cost: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=>Eu(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=xl(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(Cl(e)));return i}function pf(e,t){let n=[];for(let[t,r]of e.calls)n.push(...of(Ic({...r,id:r.id??`call_${t}`},r.args)));let r=ca(e.finish,e.native);if(t.structured&&e.text&&r.kind===`completed`){let t=of([Sl(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=xl(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=vl(n);yield{type:`media`,media:i?{mimeType:`audio/wav`,data:St(yl(r,i))}:{mimeType:Ir(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=Wi({id:`local`,name:`Local`,description:`A server that speaks OpenAI's chat API: Ollama, llama.cpp, vLLM, LM Studio.`,traceName:`openai`,connection:_({baseUrl:zi.describe(`Where the server listens, up to and including /v1, e.g. http://localhost:11434/v1.`)}),key:o().trim().min(1).optional(),authorize:Bi(),serves:e=>[{protocol:hf,baseUrl:e.baseUrl},{protocol:oc,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=go(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-CK3-VEaY.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`,`tool_instructions`];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-QPeAmaJ4.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`,`tool_instructions`];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-Sm_QLU6x.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-CK3-VEaY.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-BMdqCPG0.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-QPeAmaJ4.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-Sm_QLU6x.js";import{c as r}from"./host-patterns-F-KZIzkF.js";import{Kn as i,M as a,Ur as o}from"./shaped-data-CK3-VEaY.js";import{I as s}from"./reader-DeQkPn6F.js";import{g as c}from"./schema-C46sNlNM.js";import{r as l}from"./encode-files-C19H5oqI.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-BMdqCPG0.js";import{c as r}from"./host-patterns-F-KZIzkF.js";import{Kn as i,M as a,Ur as o}from"./shaped-data-QPeAmaJ4.js";import{I as s}from"./reader-BBrTYWFM.js";import{g as c}from"./schema-BgiRaskO.js";import{r as l}from"./encode-files-BRs8C-bs.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-CK3-VEaY.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-QPeAmaJ4.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};