@theoremjs/studio 0.3.4-next.727.g8a08b91 → 0.3.4-next.729.g096feb6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +4 -4
- package/page/assets/{Banner-BLNhepw5.js → Banner-DdKVQVIA.js} +3 -3
- package/page/assets/{ConsoleFrame-CPxgSITW.js → ConsoleFrame-CXVxrOXS.js} +1 -1
- package/page/assets/{MenuBottomSheet-DkcUfuBE.js → MenuBottomSheet-C3gi7El9.js} +1 -1
- package/page/assets/{SchemaFields-DuwdKRO9.js → SchemaFields-bnMsWJjR.js} +1 -1
- package/page/assets/{ToolResultCharts-CkvTtwJ1.js → ToolResultCharts-Bn2FEUbS.js} +1 -1
- package/page/assets/{TraceInspector-DKh6_uCU.js → TraceInspector-Bj_ZXTQQ.js} +1 -1
- package/page/assets/{TraceOverview-1CQk-7B8.js → TraceOverview-DpjrzPHw.js} +1 -1
- package/page/assets/{browser-connection-DMLe-0pv.js → browser-connection-IC3QKsFq.js} +1 -1
- package/page/assets/{browser-engine-CU1JMUMz.js → browser-engine-Bavv76-3.js} +1 -1
- package/page/assets/{browser-transport-BCwSLVJv.js → browser-transport-BRjXq2Qp.js} +3 -3
- package/page/assets/{export-agent-C43TTkhk.js → export-agent-DWKNTptV.js} +1 -1
- package/page/assets/{guardrail-tester-0xHqNTIG.js → guardrail-tester-5IMes5w-.js} +1 -1
- package/page/assets/{index-DxaSpTtM.js → index-CCj0zkrC.js} +7 -7
- package/page/assets/{live-messages-eYYz6aFz.js → live-messages-ConwEl7T.js} +1 -1
- package/page/assets/{reader-DAdKx3ZF.js → reader-Ql1nrrAA.js} +1 -1
- package/page/assets/{stub-4NoUUWes.js → stub-U8WThytR.js} +1 -1
- package/page/assets/{studio-code-pane-CnNaDzrN.js → studio-code-pane-CFOmHAPp.js} +1 -1
- package/page/assets/{studio-console-BD3mlhyS.js → studio-console-C0F2FDl3.js} +1 -1
- package/page/assets/{studio-decision-jCaBdiGS.js → studio-decision-Cityn64u.js} +1 -1
- package/page/assets/{studio-embedding-DD4c70Np.js → studio-embedding-S9ZH-InI.js} +1 -1
- package/page/assets/{studio-host-console-BdXfPdWD.js → studio-host-console-CcGeithp.js} +2 -2
- package/page/assets/{studio-labels-B1CPAbnq.js → studio-labels-DwBTrktF.js} +1 -1
- package/page/assets/{studio-live-SbPBqNbn.js → studio-live-BhwFs5I4.js} +1 -1
- package/page/assets/{studio-map-Bajn32Xo.js → studio-map-BAXmd4eb.js} +1 -1
- package/page/assets/{studio-trace-replay-D78AB4Zj.js → studio-trace-replay-Wc4f_9El.js} +1 -1
- package/page/assets/{tool-schema-C7lMQU0w.js → tool-schema-BHHcOFff.js} +1 -1
- package/page/assets/{tree-BpAzPK_j.js → tree-DveW6zCH.js} +1 -1
- package/page/assets/{turn-client-CMgd-m7p.js → turn-client-D36i6KKG.js} +1 -1
- package/page/assets/{use-one-call-DS5qaoqY.js → use-one-call-CJYjKc3D.js} +1 -1
- package/page/assets/{workspace-CUvoWPwb.js → workspace-BmMSRE4E.js} +1 -1
- package/page/index.html +11 -11
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import{n as e}from"./rolldown-runtime-hePW80VL.js";import{$ as t,A as n,B as r,C as i,D as a,E as o,F as s,G as c,H as l,I as u,J as d,K as f,L as p,M as m,N as h,O as g,P as ee,Q as te,R as ne,S as re,T as _,U as ie,V as ae,W as oe,X as se,Y as ce,Z as le,a as ue,at as de,b as v,c as y,ct as fe,d as b,dt as pe,et as me,ft as he,g as ge,h as x,ht as _e,i as ve,it as ye,j as be,lt as xe,m as Se,mt as Ce,n as we,nt as Te,o as Ee,ot as De,p as S,q as Oe,r as ke,rt as Ae,st as je,tt as Me,u as Ne,ut as Pe,v as C,w as Fe,x as w,z as Ie}from"./schemas-D7cgkv3L.js";import{c as T,s as Le}from"./host-patterns-F-KZIzkF.js";import{$t as Re,A as E,Ar as ze,B as Be,Cn as Ve,D as He,En as Ue,Er as We,Jn as Ge,K as Ke,Lr as D,M as O,N as k,O as A,P as qe,Pn as Je,Pr as Ye,Qt as Xe,Sr as Ze,Tn as Qe,Xn as $e,Xt as et,Yt as tt,Zn as nt,Zt as rt,a as it,ar as at,bn as ot,c as j,dn as st,dr as ct,er as lt,fr as ut,gr as dt,hn as ft,hr as pt,ir as mt,jr as M,k as N,kr as ht,mr as gt,nn as _t,on as vt,or as yt,qn as bt,sr as xt,tr as St,un as Ct,ur as wt,wr as Tt,yn as Et}from"./shaped-data-BRffby3g.js";var Dt=e({endsWith:()=>be,gt:()=>m,gte:()=>h,includes:()=>ee,length:()=>Ie,lowercase:()=>r,lt:()=>ae,lte:()=>l,maxLength:()=>ie,maxSize:()=>oe,mime:()=>c,minLength:()=>f,minSize:()=>Oe,multipleOf:()=>d,negative:()=>ce,nonnegative:()=>se,nonpositive:()=>le,normalize:()=>te,overwrite:()=>t,positive:()=>me,properties:()=>Me,property:()=>Te,regex:()=>Ae,size:()=>ye,slugify:()=>de,startsWith:()=>De,toLowerCase:()=>je,toUpperCase:()=>fe,trim:()=>xe,uppercase:()=>Pe}),Ot=e({ZodISODate:()=>we,ZodISODateTime:()=>ke,ZodISODuration:()=>ve,ZodISOTime:()=>ue,date:()=>At,datetime:()=>kt,duration:()=>Mt,time:()=>jt});function kt(e){return u(ke,e)}function At(e){return s(we,e)}function jt(e){return ne(ue,e)}function Mt(e){return p(ve,e)}var P={...Fe,...Dt,iso:Ot},Nt=new Set(`$schema.$ref.$defs.definitions.$id.id.$comment.$anchor.$vocabulary.$dynamicRef.$dynamicAnchor.type.enum.const.anyOf.oneOf.allOf.not.properties.required.additionalProperties.patternProperties.propertyNames.minProperties.maxProperties.items.prefixItems.additionalItems.minItems.maxItems.uniqueItems.contains.minContains.maxContains.minLength.maxLength.pattern.format.minimum.maximum.exclusiveMinimum.exclusiveMaximum.multipleOf.description.default.contentEncoding.contentMediaType.contentSchema.unevaluatedItems.unevaluatedProperties.if.then.else.dependentSchemas.dependentRequired.nullable.readOnly`.split(`.`));function Pt(e,t){let n=e.$schema;return n===`https://json-schema.org/draft/2020-12/schema`?`draft-2020-12`:n===`http://json-schema.org/draft-07/schema#`?`draft-7`:n===`http://json-schema.org/draft-04/schema#`?`draft-4`:t??`draft-2020-12`}function Ft(e,t){return e.map((e,n)=>n<t?e:e.optional())}function It(e){return e.replace(/~1/g,`/`).replace(/~0/g,`~`)}function Lt(e,t){if(!e.startsWith(`#`))throw Error(`External $ref is not supported, only local refs (#/...) are allowed`);let n=e.slice(1).split(`/`).filter(Boolean);if(n.length===0)return t.rootSchema;let r=t.version===`draft-2020-12`?`$defs`:`definitions`;if(n[0]===r){let r=n[1]===void 0?void 0:It(n[1]);if(!r||!t.defs[r])throw Error(`Reference not found: ${e}`);return t.defs[r]}throw Error(`Reference not found: ${e}`)}function Rt(e,t){return P.transform(e=>e).check(n=>{let r=n.value;if(typeof r!=`object`||!r||Array.isArray(r))return;let i=Object.getOwnPropertyNames(r);if(t.minProperties!==void 0&&i.length<t.minProperties&&n.issues.push({origin:`object`,code:`too_small`,minimum:t.minProperties,inclusive:!0,message:`Too small: expected object to have >=${t.minProperties} properties`,input:r,inst:e,continue:!0}),t.maxProperties!==void 0&&i.length>t.maxProperties&&n.issues.push({origin:`object`,code:`too_big`,maximum:t.maxProperties,inclusive:!0,message:`Too big: expected object to have <=${t.maxProperties} properties`,input:r,inst:e,continue:!0}),t.keySchema)for(let e of i){let r=t.keySchema.safeParse(e);r.success||n.issues.push({code:`invalid_key`,origin:`record`,issues:r.error.issues,input:e,path:[e],continue:!0})}}).pipe(e)}function zt(e,t){if(e===null)return`z`;let n=typeof e;if(n!==`object`){if(n===`number`&&Number.isNaN(e))return null;let t=String(e);return`${n[0]}${t.length}:${t}`}if(t.has(e))return null;t.add(e);try{if(Array.isArray(e)){let n=[];for(let r of e){let e=zt(r,t);if(e===null)return null;n.push(e)}return`a${n.length}:[${n.join(`,`)}]`}let n=Object.keys(e).sort(),r=[];for(let i of n){let n=zt(e[i],t);if(n===null)return null;r.push(`${i.length}:${i}=${n}`)}return`o${r.length}:{${r.join(`,`)}}`}finally{t.delete(e)}}var Bt=new Set([`items`,`prefixItems`,`additionalItems`,`additionalProperties`,`contains`,`propertyNames`,`not`,`if`,`then`,`else`,`allOf`,`anyOf`,`oneOf`,`unevaluatedItems`,`unevaluatedProperties`,`contentSchema`]),Vt=new Set([`properties`,`patternProperties`,`dependentSchemas`,`dependencies`,`$defs`,`definitions`]);function Ht(e){return typeof e!=`object`||!e?!1:Array.isArray(e)?e.some(Ht):typeof e.$ref==`string`||Object.entries(e).some(([e,t])=>Bt.has(e)?Ht(t):!Vt.has(e)||typeof t!=`object`||!t?!1:Object.values(t).some(Ht))}function Ut(e){return e===1?`element`:`elements`}function Wt(e,t){return P.transform(e=>e).check(e=>{let n=e.value;if(Array.isArray(n)){if(t.uniqueItems===!0){let t=new Map;for(let r=0;r<n.length;r++){let i=zt(n[r],new Set);if(i===null)continue;let a=t.get(i);a===void 0?t.set(i,r):e.issues.push({code:`custom`,message:`Array items must be unique: element at index ${r} duplicates the one at index ${a}`,input:n,path:[r],continue:!0})}}if(t.containsSchema){let r=t.minContains??1,i=t.maxContains===void 0?1/0:t.maxContains+1,a=0;for(let e of n)if(t.containsSchema.safeParse(e).success&&++a>=i)break;a<r&&e.issues.push({code:`custom`,message:`Array must contain at least ${r} matching ${Ut(r)}; found ${a}`,input:n,continue:!0}),t.maxContains!==void 0&&a>t.maxContains&&e.issues.push({code:`custom`,message:`Array must contain at most ${t.maxContains} matching ${Ut(t.maxContains)}`,input:n,continue:!0})}}}).pipe(e)}function Gt(e,t){if(e!==!1)return e===void 0||e===!0?P.any():F(e,t)}var Kt=/^(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/;function qt(e,t){if(e.not!==void 0){if(typeof e.not==`object`&&Object.keys(e.not).length===0)return P.never();throw Error(`not is not supported in Zod (except { not: {} } for never)`)}if(e.unevaluatedItems!==void 0)throw Error(`unevaluatedItems is not supported`);if(e.unevaluatedProperties!==void 0)throw Error(`unevaluatedProperties is not supported`);if(e.if!==void 0||e.then!==void 0||e.else!==void 0)throw Error(`Conditional schemas (if/then/else) are not supported`);if(e.dependentSchemas!==void 0||e.dependentRequired!==void 0)throw Error(`dependentSchemas and dependentRequired are not supported`);if(e.$ref){let n=e.$ref;if(t.refs.has(n))return t.refs.get(n);if(t.processing.has(n))return P.lazy(()=>{if(!t.refs.has(n))throw Error(`Circular reference not resolved: ${n}`);return t.refs.get(n)});t.processing.add(n);let r=F(Lt(n,t),t);return t.refs.set(n,r),t.processing.delete(n),r}if(e.enum!==void 0){let n=e.enum;if(t.version===`openapi-3.0`&&e.nullable===!0&&n.length===1&&n[0]===null)return P.null();if(n.length===0)return P.never();if(n.length===1)return P.literal(n[0]);if(n.every(e=>typeof e==`string`))return P.enum(n);let r=n.map(e=>P.literal(e));return r.length<2?r[0]:P.union([r[0],r[1],...r.slice(2)])}if(e.const!==void 0)return P.literal(e.const);let n=e.type;if(Array.isArray(n)){let r=n.map(n=>qt({...e,type:n},t));return r.length===0?P.never():r.length===1?r[0]:P.union(r)}if(!n)return P.any();let r;switch(n){case`string`:{let t=P.string();if(e.format){let n=e.format;n===`email`?t=t.check(P.email()):n===`uri`||n===`uri-reference`?t=t.check(P.url()):n===`uuid`||n===`guid`?t=t.check(P.uuid()):n===`date-time`?t=t.check(P.iso.datetime({offset:!0})):n===`date`?t=t.check(P.iso.date()):n===`time`?t=t.check(P.regex(Kt)):n===`duration`?t=t.check(P.iso.duration()):n===`hostname`?t=t.check(P.hostname()):n===`ipv4`?t=t.check(P.ipv4()):n===`ipv6`?t=t.check(P.ipv6()):n===`mac`?t=t.check(P.mac()):n===`cidr`?t=t.check(P.cidrv4()):n===`cidr-v6`?t=t.check(P.cidrv6()):n===`base64`?t=t.check(P.base64()):n===`base64url`?t=t.check(P.base64url()):n===`e164`?t=t.check(P.e164()):n===`credit_card`?t=t.check(P.creditCard()):n===`iban`?t=t.check(P.iban()):n===`jwt`?t=t.check(P.jwt()):n===`emoji`?t=t.check(P.emoji()):n===`nanoid`?t=t.check(P.nanoid()):n===`cuid`?t=t.check(P.cuid()):n===`cuid2`?t=t.check(P.cuid2()):n===`ulid`?t=t.check(P.ulid()):n===`xid`?t=t.check(P.xid()):n===`ksuid`&&(t=t.check(P.ksuid()))}typeof e.minLength==`number`&&(t=t.min(e.minLength)),typeof e.maxLength==`number`&&(t=t.max(e.maxLength)),e.pattern&&(t=t.regex(new RegExp(e.pattern))),r=t;break}case`number`:case`integer`:{let t=n===`integer`?P.number().int():P.number();typeof e.minimum==`number`&&e.exclusiveMinimum!==!0&&(t=t.min(e.minimum)),typeof e.maximum==`number`&&e.exclusiveMaximum!==!0&&(t=t.max(e.maximum)),typeof e.exclusiveMinimum==`number`?t=t.gt(e.exclusiveMinimum):e.exclusiveMinimum===!0&&typeof e.minimum==`number`&&(t=t.gt(e.minimum)),typeof e.exclusiveMaximum==`number`?t=t.lt(e.exclusiveMaximum):e.exclusiveMaximum===!0&&typeof e.maximum==`number`&&(t=t.lt(e.maximum)),typeof e.multipleOf==`number`&&(t=t.multipleOf(e.multipleOf)),r=t;break}case`boolean`:r=P.boolean();break;case`null`:r=P.null();break;case`object`:{let n={},i=e.properties||{},a=new Set(e.required||[]),o=typeof e.additionalProperties==`object`?F(e.additionalProperties,t):void 0;for(let[e,r]of Object.entries(i)){let i=F(r,t);Ce(n,e,a.has(e)?i:i.optional())}if(e.patternProperties){let i=e.patternProperties,a=Object.keys(i),o=[];for(let e of a){let n=F(i[e],t),r=P.string().regex(new RegExp(e));o.push(P.looseRecord(r,n))}let s=[];if(Object.keys(n).length>0&&s.push(P.object(n).passthrough()),s.push(...o),s.length===0)r=P.object({}).passthrough();else if(s.length===1)r=s[0];else{let e=P.intersection(s[0],s[1]);for(let t=2;t<s.length;t++)e=P.intersection(e,s[t]);r=e}if(e.additionalProperties===!1){let e=Object.keys(n),t=a.map(e=>new RegExp(e)),i=r;r=r.check(n=>{if(!_e(n.value))return;let r=[];for(let i of Object.keys(n.value))e.includes(i)||t.some(e=>e.test(i))||r.push(i);r.length&&n.issues.push({code:`unrecognized_keys`,keys:r,input:n.value,inst:i})})}}else{let t=P.object(n);r=e.additionalProperties===!1?t.strict():o?t.catchall(o):t.passthrough()}let s=e.propertyNames!==void 0&&e.propertyNames!==!0,c=typeof e.minProperties==`number`?e.minProperties:void 0,l=typeof e.maxProperties==`number`?e.maxProperties:void 0;if(s||c!==void 0||l!==void 0){let n;s&&(n=F(typeof e.propertyNames==`object`&&e.propertyNames.type===void 0?{type:`string`,...e.propertyNames}:e.propertyNames,t)),r=Rt(r,{keySchema:n,minProperties:c,maxProperties:l})}break}case`array`:{let n=e.prefixItems,i=e.items;if(n&&Array.isArray(n)){let a=typeof e.minItems==`number`?e.minItems:0,o=Ft(n.map(e=>F(e,t)),a),s=Array.isArray(i)?void 0:Gt(i,t),c=P.tuple(o);r=s?c.rest(s):c,typeof e.minItems==`number`&&(r=r.check(P.minLength(e.minItems))),typeof e.maxItems==`number`&&(r=r.check(P.maxLength(e.maxItems)))}else if(Array.isArray(i)){let n=typeof e.minItems==`number`?e.minItems:0,a=Ft(i.map(e=>F(e,t)),n),o=Gt(e.additionalItems,t),s=P.tuple(a);r=o?s.rest(o):s,typeof e.minItems==`number`&&(r=r.check(P.minLength(e.minItems))),typeof e.maxItems==`number`&&(r=r.check(P.maxLength(e.maxItems)))}else if(i!==void 0){let n=F(i,t),a=P.array(n);typeof e.minItems==`number`&&(a=a.min(e.minItems)),typeof e.maxItems==`number`&&(a=a.max(e.maxItems)),r=a}else r=P.array(P.any());(e.uniqueItems===!0||e.contains!==void 0)&&(r=Wt(r,{uniqueItems:e.uniqueItems===!0,containsSchema:e.contains===void 0?void 0:F(e.contains,t),minContains:typeof e.minContains==`number`?e.minContains:void 0,maxContains:typeof e.maxContains==`number`?e.maxContains:void 0}));break}default:throw Error(`Unsupported type: ${n}`)}return r}function F(e,t){if(typeof e==`boolean`)return e?P.any():P.never();let n=qt(e,t),r=e.type||e.enum!==void 0||e.const!==void 0;if(e.anyOf&&Array.isArray(e.anyOf)){let i=e.anyOf.map(e=>F(e,t)),a=P.union(i);n=r?P.intersection(n,a):a}if(e.oneOf&&Array.isArray(e.oneOf)){let i=e.oneOf.map(e=>F(e,t)),a=P.xor(i);n=r?P.intersection(n,a):a}if(e.allOf&&Array.isArray(e.allOf)){if(e.allOf.length===0)n=r?n:P.any();else{let i=r?n:F(e.allOf[0],t),a=+!r;for(let n=a;n<e.allOf.length;n++)i=P.intersection(i,F(e.allOf[n],t));n=i}}e.nullable===!0&&t.version===`openapi-3.0`&&(n=P.nullable(n)),e.readOnly===!0&&(n=P.readonly(n)),e.default!==void 0&&(n=n.default(e.default));let i={};for(let t of[`$id`,`id`,`$comment`,`$anchor`,`$vocabulary`,`$dynamicRef`,`$dynamicAnchor`])t in e&&(i[t]=e[t]);for(let t of[`contentEncoding`,`contentMediaType`,`contentSchema`])t in e&&(i[t]=e[t]);if(e.type===`object`&&e.$ref===void 0){e.propertyNames!==void 0&&!Ht(e.propertyNames)&&(i.propertyNames=e.propertyNames);for(let t of[`minProperties`,`maxProperties`])e[t]!==void 0&&(i[t]=e[t])}if(e.type===`array`&&e.$ref===void 0){e.contains!==void 0&&!Ht(e.contains)&&(i.contains=e.contains);for(let t of[`uniqueItems`,`minContains`,`maxContains`])e[t]!==void 0&&(i[t]=e[t])}for(let t of Object.keys(e))Nt.has(t)||Ce(i,t,e[t]);return Object.keys(i).length>0&&t.registry.add(n,i),e.description&&(n=n.describe(e.description)),n}function Jt(e,t){if(typeof e==`boolean`)return e?P.any():P.never();let n;try{n=JSON.parse(JSON.stringify(e))}catch{throw Error(`fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas`)}let r={version:Pt(n,t?.defaultTarget),defs:n.$defs||n.definitions||{},refs:new Map,processing:new Set,rootSchema:n,registry:t?.registry??pe};return F(n,r)}var Yt=y(Le),Xt=w({key:y(Ye),params:i(o(),a([o(),v()])).optional()}),Zt=a([Xt,b(Xt).readonly()]),Qt=w({origin:y(gt),tool:o(),depth:v()}),$t=w({rule:o(),severity:y(ut),span:w({start:v(),end:v()}).optional(),match:o().optional(),label:o().optional(),doc:o().optional(),pattern:o().optional(),signal:o().optional()}),en=w({stage:y(ct),boundary:y(dt).optional(),trust:y(pt),action:y(wt),hits:b($t),provenance:Qt.optional(),errorInternal:o().optional(),errorSummary:o().optional()}),tn=ge(),I=i(o(),tn),nn=_({protocol:o().min(1),provider:o().min(1),version:v().int().positive(),apiId:o().min(1),keySlot:o().min(1).optional(),compatibilityKey:o(),coveredHistoryLength:v().int().nonnegative(),coveredHistoryHash:o(),data:tn,wireCallIds:i(o().min(1),o().min(1)).optional()}),rn=_({code:C(`provider_state_rebuilt`),reason:y([`provider_changed`,`model_changed`,`connection_changed`,`key_changed`,`history_changed`,`version_changed`])}),an=_({history:y([`host`,`stateless`,`provider`]).optional()});async function on(e){let t=e=>{if(Array.isArray(e))return e.map(t);if(e&&typeof e==`object`){let n={};for(let r of Object.keys(e).sort())n[r]=t(e[r]);return n}return e},n=await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(JSON.stringify(t(e.map(e=>{let t=t=>e.role===`user`?t.match(/^<user_data>\n([\s\S]*)\n<\/user_data>$/)?.[1]??t:t,n=[...e.content===void 0?[]:[{type:`text`,text:t(e.content)}],...(e.parts??[]).map(e=>e.type===`text`?{...e,text:t(e.text)}:e)],{content:r,parts:i,...a}=e;return{...a,...n.length?{parts:n}:{}}}))))),r=``;for(let e of new Uint8Array(n))r+=e.toString(16).padStart(2,`0`);return r}var L=i(o(),g()),R=o().trim().min(1),sn=w({type:C(`text`),text:o()}),cn=w({type:y(st),mimeType:o(),data:o()}),ln=w({type:y(st),mimeType:o(),uri:o()}),un=a([sn,cn,ln]),dn=un,fn=w({protocol:o().min(1),provider:o().min(1).optional(),apiId:o().min(1).optional()}),pn=w({text:o().optional(),data:tn,origin:fn}),mn=w({role:y([`system`,`user`,`assistant`,`tool`]),content:o().optional(),parts:b(un).optional(),tool_calls:b(w({id:o(),type:C(`function`),function:w({name:o(),arguments:o()})})).optional(),reasoning:b(pn).optional(),tool_call_id:o().optional(),name:o().optional(),metadata:L.optional()}),hn=mn,gn=w({kind:y(Ue),native:o().optional()}),_n=gn,vn=[`input`,`output`],yn=w({usd:v(),upstreamUsd:v().optional(),partial:C(!0).optional()}),bn=w({type:o(),count:v(),searchQueryCount:v().optional()}),xn=w({input:v(),output:v(),thinking:v().optional(),toolUse:v().optional(),cached:v().optional(),cacheWrite:v().optional(),total:v(),cost:yn.optional(),estimated:b(y(vn)).optional(),unknownMedia:w({input:v().optional(),output:v().optional()}).optional(),byModality:w({input:i(o(),v()).optional(),output:i(o(),v()).optional()}).optional(),grounding:b(bn).optional()});w({id:o().optional(),model:o().optional()});var Sn=w({title:o(),uri:o(),type:y([`web`,`maps`]),placeId:o().optional()}),Cn=Sn,wn=w({metadata:L.optional(),chunks:b(g()).optional(),searchHtml:o().optional()}),z={provider:o().min(1),raw:L.optional(),partial:S().optional()},Tn=x(`kind`,[w({...z,kind:C(`code_execution_call`),code:o(),language:o().optional(),id:o()}),w({...z,kind:C(`code_execution_result`),result:o().optional(),isError:S().optional(),callId:o().optional()}),w({...z,kind:y([`input_transcription`,`output_transcription`]),interim:S().optional()}),w({...z,kind:y([`voice_activity`,`url_context`])}),w({...z,kind:C(`session_resumption`),resumable:S()}),w({...z,kind:C(`provider_step`),step:o()})]),En=w({cause:C(`go_away`),code:v(),closedAfterMs:v(),errorKind:Yt.optional()}),Dn=x(`kind`,[w({kind:C(`closing_soon`),timeLeftMs:v().optional()}),w({kind:C(`ended`),timeLeftMs:v().optional(),ended:En,message:o()}),w({kind:y([`waiting_for_input`,`turn_complete`,`working`,`idle`])})]),On=w({code:o(),kind:Yt,message:o(),error:o().optional(),details:g().optional()}),kn=w({slot:R,authType:y(ot),service:R,message:R,authorizationUrl:o().optional(),state:o().optional(),issuer:o().optional(),resource:o().optional(),requiredScopes:b(R).optional()}),An={preparedArguments:i(o(),g()).optional(),tool:R,permission:y(Ve).optional(),summary:R.optional(),request:R.optional(),access:y(Et).optional()},jn=x(`kind`,[w({...An,kind:y([`confirmation`,`permission`,`page`])}),w({...An,kind:C(`auth`),authChallenge:kn})]),Mn=jn,Nn=w({code:o(),message:o(),severity:y([`info`,`warning`,`error`]).optional()}),Pn=w({name:o(),kind:o(),status:o(),inputs:L.optional(),outputs:L.optional()}),Fn={status:C(tt),prompt:R},In=x(`kind`,[w({...Fn,kind:y([`confirm`,`text`]),options:b(R).optional()}),w({...Fn,kind:C(`choice`),options:b(R).min(1)})]);function Ln(e){return In.safeParse(e).success}var Rn=w({type:C(`function`),name:o(),description:o(),parameters:L}),zn=w({builtins:b(o()),gated:b(o()),visible:b(o()),executable:b(o()),path:o().optional(),sessionPermissions:b(o()).optional(),wire:b(Rn),modelBackground:S().optional()}),Bn=zn,Vn=_({callId:o().min(1),operationId:o().min(1).max(256)}),Hn={name:o(),callId:o()},Un=w({...Hn,phase:Ne().optional(),arguments:L,reasoning:b(pn).optional(),stepId:o().min(1).optional(),stepCallCount:v().int().min(1).optional()}),B={...Hn,at:v()},Wn=x(`phase`,[w({...B,phase:C(`running`),edited:w({from:L,to:L}).optional(),activity:o().optional()}),w({...B,phase:C(`dispatch`),grantId:o().min(1),arguments:L}),w({...B,phase:C(`progress`),data:g()}),w({...B,phase:C(`draft`),text:o()}),w({...B,phase:C(`trace`),step:Pn}),w({...B,phase:C(`artifact`),artifact:g()}),w({...B,phase:C(`warning`),warning:Nn}),w({...B,phase:C(`complete`),output:g(),awaiting:S().optional(),readBack:o().optional(),parts:b(un).optional(),activityPast:o().optional(),tokens:xn.optional()}),w({...B,phase:C(`gate`),gate:jn,readBack:o().optional()}),w({...B,phase:C(`background`),readBack:o()}),w({...B,phase:C(`error`),failure:On,readBack:o().optional(),activityPast:o().optional(),tokens:xn.optional()}),w({...B,phase:C(`cancel`)})]),Gn=a([Wn,Un]).and(w({operationId:o().min(1).max(256).optional()})),Kn=w({code:y(ft),message:o(),field:o()}),qn=w({needed:S(),meter:y(Xe),tokens:v(),unknownMedia:v(),promptTokens:v().optional(),promptTokensEstimated:S().optional(),history:b(mn)}),Jn=w({stop:y(Ue).optional(),error:Yt.optional(),errorInternal:o().optional(),empty:C(!0).optional(),unreadable:C(!0).optional()}),Yn=[`tool`,`gate`];function Xn(e,t){let{stop:n,...r}=e,{kind:i}=n;return i===`tool`||i===`gate`?t?{type:`done`,...r,stop:{...n,kind:i},tools:t}:void 0:{type:`done`,...r,stop:{...n,kind:i}}}var Zn=y(Yn),Qn=y(Ue).exclude(Yn),$n={providerState:nn.optional(),type:C(`done`),tokens:xn.optional(),traceparent:o().optional(),steps:v().int().nonnegative().optional(),compaction:qn.optional(),interrupted:S().optional(),interactionId:o().optional()},er=a([w({...$n,stop:w({kind:Zn,native:o().optional()}),tools:zn}),w({...$n,stop:w({kind:Qn,native:o().optional()}),tools:Ne().optional()})]),V={provider_checkpoint:w({type:C(`provider_checkpoint`),providerState:nn,history:b(hn).optional()}),provider_warning:w({type:C(`provider_warning`),warning:rn}),text:w({type:C(`text`),text:o()}),thought:w({type:C(`thought`),text:o()}),custom:w({type:C(`custom`),kind:o().min(1),data:I}),structured:w({type:C(`structured`),structured:g(),removed:b(w({path:o(),reason:o(),item:g()})).optional(),failed:b(w({path:o(),error:o()})).optional()}),structured_draft:w({type:C(`structured_draft`),text:o()}),attempt:w({type:C(`attempt`),attempt:v().int().positive(),reason:y([`validation`,`egress`])}),media:w({type:C(`media`),media:w({mimeType:o(),data:o()})}),grounding:w({type:C(`grounding`),grounding:wn}),citation:w({type:C(`citation`),sources:b(Sn),callId:o().optional()}),compaction:w({type:C(`compaction`),timing:C(`before`),meter:y(Xe),tokensBefore:v(),unknownMedia:v(),messagesBefore:v(),messagesAfter:v(),outcome:y(Re),history:b(mn),summary:o().optional(),failure:Jn.optional(),droppedMedia:v(),tokens:xn.optional()}),evidence:w({type:C(`evidence`),evidence:Tn,text:o().optional(),sessionResumptionHandle:o().optional()}),tokens:w({type:C(`tokens`),tokens:xn,interactionId:o().optional()}),session:w({type:C(`session`),session:Dn,errorInternal:o().optional()}),guardrail:w({type:C(`guardrail`),guardrail:en}),stage:w({type:C(`stage`),stage:y(Qe),callId:o().optional(),toolName:o().optional(),callNotStarted:S().optional(),awaiting:S().optional(),gate:jn.optional(),stop:_n.optional(),stageWarnings:b(Kn).optional(),injected:b(w({id:o().regex(/\S/),messages:b(mn)})).min(1).optional(),released:v().int().nonnegative().optional()}),tool_draft:w({type:C(`tool_draft`),callId:o().min(1),name:o(),text:o()}),tool:w({type:C(`tool`),tool:Gn,errorInternal:o().optional()}),error:w({type:C(`error`),errorKind:Yt,error:o().optional(),errorCopy:Zt.optional(),errorInternal:o().optional()}),done:er},tr=a([x(`type`,[V.provider_warning,V.provider_checkpoint,V.text,V.thought,V.custom,V.structured,V.structured_draft,V.attempt,V.media,V.grounding,V.citation,V.compaction,V.evidence,V.tokens,V.session,V.guardrail,V.stage,V.tool_draft,V.tool,V.error]),V.done]),nr=V;function rr(e){return e.type===`text`||e.type===`media`||e.type===`structured`||e.type===`structured_draft`}function ir(e,t){let n=[],r=t;for(let t of e)if(!rr(t))n.push(t);else if(t.type!==`text`)r>0&&n.push(t);else if(r>0){let e=t.text.slice(0,r);r-=e.length,n.push(e===t.text?t:{...t,text:e})}return n}function ar(e){let t=[],n=0;for(let r of e){if(r.type===`attempt`){let e=t.splice(n);t.push(...e.filter(e=>!rr(e)))}r.type===`stage`&&r.released!==void 0&&t.push(...ir(t.splice(n),r.released)),t.push(r),r.type===`done`&&(n=t.length)}return t}var or=[`reply`,`reply_structured`];function sr(e,t,n,r={}){if(!qe([t],n))return{action:`allow`,hits:[],value:e};let i=nt(e);if(i.unscannable)return{action:`block`,hits:[{rule:at.unscannable,severity:`high`}]};let a=O(i.text,t,n,r);if(a.action!==`redact`){let{errorInternal:t,errorSummary:n}=a,r=t&&n?{errorInternal:t,errorSummary:n}:{};return{action:a.action,hits:a.hits,value:e,...r}}let o=$e(e,e=>O(e,t,n,r).text??``),s=O(nt(o).text,t,n,r).action;return s===`redact`||s===`block`?{action:`block`,hits:a.hits}:{action:`redact`,hits:a.hits,value:o}}function cr(e,t,{boundary:n,reportedTo:r=e.text.length,scope:i={}}){let a=O(e.text,n,t,i),o=e.structured===void 0?void 0:sr(e.structured,`reply_structured`,t,i),s=r>=e.text.length?[]:a.hits.filter(e=>!e.span||e.span.start>=r),c=[a.action===`flag`?k(n,{action:s.length>0?`flag`:`allow`,hits:s}):k(n,a),o?k(`reply_structured`,o):void 0].filter(e=>e!==void 0),l=[a,o].flatMap(e=>e?.action===`block`?e.hits:[]);return{payload:{text:a.text??e.text,...o?{structured:o.value}:{}},rewritten:a.action===`redact`,events:c,...l.length>0?{blocked:l}:{}}}function lr(e,t=[]){if(e.blocked)return e.blocked;let n=new Set(e.events.flatMap(e=>e.hits.map(e=>e.rule))),r=t.filter(e=>!n.has(e.rule));return r.length>0?r:void 0}function ur(e,t){return e?t.startsWith(e)?t.slice(e.length):`\n\n${t}`:t}function dr(e,t){return D(e?`egress.refusal_cut`:`egress.refusal`,{},t)}var fr=`</tool_data>`,pr=`<tool_data`,mr=new Set([`http`,`mcp`,`delegated`]);function hr(e){return mr.has(e)}function gr(e){let t=e.toLowerCase(),n=``,r=0;for(;r<e.length;){let i=t.indexOf(pr,r),a=t.indexOf(fr,r),o=-1,s=null;if(i>=0&&(a<0||i<=a)?(o=i,s=`open`):a>=0&&(o=a,s=`close`),o<0||s===null){n+=e.slice(r);break}if(n+=e.slice(r,o),s===`close`){r=o+12;continue}let c=e.indexOf(`>`,o+10);if(c<0){n+=e.slice(o);break}r=c+1}return n}function _r(e,t,n=`none`,r){let i=D(`advisory.guidance`,{},r).trim();return`<tool_data ${`tool="${t.tool}" origin="${t.origin}"`+(n===`none`?``:` advisory="${n}"`)}>\n${n===`none`?``:`${vr(n,r)}${i?` ${i}`:``}\n`}${gr(e)}\n${fr}`}function vr(e,t){return D(e===`high`?`advisory.notice_high`:`advisory.notice_elevated`,{},t)}function yr(e,t){if(t===void 0)return e;let n=nt(t);return n.unscannable?e:`${e}\n${n.text}`}var br={action:`allow`,hits:[]};function xr(e,t,n,r){return t?O(e,t,n,r):{...br,text:e}}function Sr(e,t,n,r,i,a=[],o){let s=xr(yr(e,t),i,r.detect,{callable:a}),c=s.hits.filter(({rule:e})=>e===mt.tool_instructions),l=hr(n.origin),u=s.action===`allow`?void 0:{stage:`tool_result`,...i?{boundary:i}:{},trust:`untrusted`,action:s.action,hits:s.hits,provenance:n},d={...c.length>0?{suspicious:c}:{},...u?{event:u}:{}};return s.text===void 0?d:{text:l?_r(s.text,n,Ke(c.map(({signal:e})=>e)),o):s.text,...d}}function Cr(e,t,n,r){let i=xr(gr(e),r,n.detect),a=r?k(r,i,t):void 0;return{...i.text===void 0?{}:{text:i.text},...a?{event:a}:{}}}function wr(e,t,n,r){if(!r||e===void 0)return{value:e};let i=sr(e,r,n.detect),a=k(r,i,t);return{...i.action===`block`?{}:{value:i.value},...a?{event:a}:{}}}function Tr(e,t,n,r,i={}){if(!(r&&qe([r],n.detect)))return{args:e};let a=e=>{let n=k(r,{action:`block`,hits:e},t);return n?{event:n}:{}},o=nt(e);if(o.unscannable)return a([{rule:at.unscannable,severity:`high`}]);let s=O(o.text,r,n.detect,i);if(s.action===`block`)return a(s.hits);let c=k(r,s,t);if(s.action!==`redact`)return{args:e,...c?{event:c}:{}};let l=$e(e,e=>O(e,r,n.detect,i).text??``),u=O(nt(l).text,r,n.detect,i).action;return u===`redact`||u===`block`?a(s.hits):{args:l,...c?{event:c}:{}}}function Er(e,t){if(e.action!==`allow`)return{stage:`tool_call`,trust:`untrusted`,action:e.action,hits:e.hits,provenance:t}}function Dr(e,t,n=[]){let r=e?.sources??[],i=e?.suspicious??[];return hr(t.origin)?{sources:[...r,t],suspicious:[...i,...n]}:{sources:r,suspicious:i}}function Or(e){return(e?.sources.length??0)>0}function kr(e){return(e?.suspicious.length??0)>0}var Ar={"read-only":0,"read-write":1,destructive:2},jr={off:1/0,destructive:2,write:1};function Mr(e,t,n,r){if(!Or(e))return{action:`allow`};let i=Ar[t]??0;if(i===0)return{action:`allow`};let a=kr(e),o=[{rule:a?xt.steeredTurn:xt.taintedTurn,severity:`high`}];if(i<jr[n.taint?.afterRemoteRead??`off`])return{action:`flag`,hits:o};let s=e?.sources.map(e=>e.tool).join(`, `)??``,c=D(a?`taint.reason_steered`:`taint.reason_tainted`,{},r);return{action:`block`,hits:o,rejection:D(`taint.blocked`,{access:t,sources:s,reason:c},r)}}var Nr={onBlock:`retry`,maxRetries:1};function Pr(e){return{onBlock:e?.onBlock??Nr.onBlock,maxRetries:e?.maxRetries??Nr.maxRetries}}function Fr(e){return{detect:Ge(e?.detect),allow:bt(e?.detect),blockedReply:Pr(e?.blockedReply),network:e?.network,quota:e?.quota,taint:e?.taint}}function Ir(e){return(e.split(`;`)[0]??``).trim().toLowerCase()}function Lr(e,t){let n=Ir(t);return e.some(e=>{let t=Ir(e);return t.endsWith(`/*`)?n.startsWith(t.slice(0,-1)):t===n})}function Rr(e){return Ct[Ir(e)]}function zr(e){return e.type===`text`||e.type===`image`||e.type===`transcription`||e.type===`live`?e.inputs:void 0}function Br(e,t){let n=zr(e);return t===`voice`?n?.voice?.accept:n?.attachments?.accept}function Vr(e,t){if(Rr(t))for(let n of[`attachments`,`voice`]){let r=Br(e,n);if(r&&Lr(r,t))return n}}function Hr(e,t){let n=e.models[t];if(!n)throw new T(`config`,`Profile ${e.id} has no model binding for '${t}'`);return n}var Ur=/^\d{1,3}(\.\d{1,3}){3}$/,Wr=[e=>e===0,e=>e===127,e=>e===10,(e,t)=>e===100&&t>=64&&t<=127,(e,t)=>e===172&&t>=16&&t<=31,(e,t)=>e===192&&t===168,(e,t)=>e===169&&t===254,(e,t,n)=>e===192&&t===0&&(n===0||n===2),(e,t)=>e===198&&(t===18||t===19),(e,t,n)=>e===198&&t===51&&n===100,(e,t,n)=>e===203&&t===0&&n===113,e=>e>=224];function Gr(e,t,n,r){return Wr.some(r=>r(e,t,n))}function Kr(e){if(!Ur.test(e))return!1;let[t=0,n=0,r=0,i=0]=e.split(`.`).map(Number);return t>255||n>255||r>255||i>255?!1:Gr(t,n,r,i)}function qr(e){let t=e.toLowerCase().trim(),n=t.lastIndexOf(`:`),r=[],i=t;if(n!==-1){let e=t.slice(n+1);if(e.includes(`.`)){let a=e.split(`.`).map(e=>Number.parseInt(e,10));if(a.length!==4||a.some(e=>Number.isNaN(e)||e<0||e>255))return null;let o=a[0]??0,s=a[1]??0,c=a[2]??0,l=a[3]??0;r=[o<<8|s,c<<8|l];let u=t.slice(0,n+1);i=u.endsWith(`::`)?u:u.slice(0,-1)}}let a=i.split(`::`);if(a.length>2)return null;let o=a[0]?a[0].split(`:`).filter(Boolean):[],s=a.length===2&&a[1]?a[1].split(`:`).filter(Boolean):[],c=8-r.length;if(a.length===1){if(o.length!==c)return null}else if(o.length+s.length>=c)return null;let l=c-(o.length+s.length),u=Array(l).fill(0),d=e=>/^[0-9a-f]{1,4}$/.test(e)?Number.parseInt(e,16):null,f=[];for(let e of o){let t=d(e);if(t===null)return null;f.push(t)}let p=[];for(let e of s){let t=d(e);if(t===null)return null;p.push(t)}return[...f,...u,...p,...r]}var H=(e,t,n)=>e.slice(t,n).every(e=>e===0),Jr=[e=>H(e,0,8),e=>H(e,0,7)&&e[7]===1,e=>((e[0]??0)&65472)==65152,e=>((e[0]??0)&65472)==65216,e=>((e[0]??0)&65024)==64512,e=>((e[0]??0)&65280)==65280,e=>e[0]===8193&&e[1]===3512,e=>e[0]===256&&H(e,1,4),e=>e[0]===100&&e[1]===65435&&e[2]===1,e=>e[0]===8193&&e[1]===0],Yr=[{match:e=>H(e,0,5)&&e[5]===65535,at:6},{match:e=>H(e,0,4)&&e[4]===65535&&e[5]===0,at:6},{match:e=>H(e,0,6),at:6},{match:e=>e[0]===100&&e[1]===65435&&H(e,2,6),at:6},{match:e=>e[0]===8194,at:1}];function Xr(e){let t=qr(e);return t?.length===8?Jr.some(e=>e(t))?!0:Yr.some(({match:e,at:n})=>{if(!e(t))return!1;let r=t[n]??0,i=t[n+1]??0;return Gr(r>>8&255,r&255,i>>8&255,i&255)}):!1}function Zr(e){let t=e.toLowerCase();for(;t.endsWith(`.`);)t=t.slice(0,-1);return t===`localhost`||t.endsWith(`.localhost`)||t===`local`||t.endsWith(`.local`)||t===`internal`||t.endsWith(`.internal`)||t===`lan`||t.endsWith(`.lan`)||t===`home.arpa`||t.endsWith(`.home.arpa`)||t===`localdomain`||t.endsWith(`.localdomain`)||t===`127.0.0.1`||t===`::1`||t===`[::1]`}function Qr(e){let t=e.startsWith(`[`)&&e.endsWith(`]`)?e.slice(1,-1):e;return Kr(t)||Xr(t)}function $r(e,t){let n;try{n=new URL(e)}catch{throw new T(`request`,`Invalid URL provided: "${e}"`)}let r=t?.allowPrivateNetworks??!1,i=t?.allowedHosts?.map(e=>e.toLowerCase())??[],a=n.hostname.toLowerCase(),o=r?[`http:`,`https:`]:[`https:`],s=t?.allowedSchemes?t.allowedSchemes.map(e=>e.endsWith(`:`)?e.toLowerCase():`${e.toLowerCase()}:`):o;if(!s.includes(n.protocol))throw new T(`blocked`,`URL scheme "${n.protocol}" is not permitted by network policy. Allowed: ${s.join(`, `)}`);if(!r&&!i.includes(a)){if(Zr(a))throw new T(`blocked`,`Access to loopback target "${a}" blocked by network guardrail. Enable allowPrivateNetworks to permit local addresses.`);if(Kr(a))throw new T(`blocked`,`Access to private IPv4 address "${a}" blocked by network guardrail.`);if(Xr(a.startsWith(`[`)&&a.endsWith(`]`)?a.slice(1,-1):a))throw new T(`blocked`,`Access to private IPv6 address "${a}" blocked by network guardrail.`)}return n}var ei=20,ti=new Set([301,302,303,307,308]);async function ni(e,t,n){let{resolveHost:r,policy:i}=t,a=e.hostname.toLowerCase();if(r===void 0||i?.allowPrivateNetworks===!0||i?.allowedHosts?.some(e=>e.toLowerCase()===a)===!0||a.startsWith(`[`)||Ur.test(a))return;let o=await r(a,n??void 0);if(o.length===0)throw new T(`blocked`,`Host "${a}" did not resolve to an address.`);let s=o.find(Qr);if(s!==void 0)throw new T(`blocked`,`Host "${a}" resolves to private address "${s}", blocked by network guardrail.`)}function ri(e,t){return e===303?t!==`HEAD`:(e===301||e===302)&&t===`POST`}async function ii(e,t,n){let r=n.fetchFn??fetch,i=async e=>{let r=performance.now();try{let r=$r(e,n.policy);return await ni(r,n,t.signal),r}finally{n.onCheck?.(performance.now()-r)}},a=await i(e);await n.beforeSend?.();let o=a.origin,s=new Headers(t.headers),c=t.method??`GET`,l=t.body,u=!0;for(let d=0;;d++){let f=new Headers(s);if(u)for(let[e,t]of Object.entries(n.originBoundHeaders??{}))f.set(e,t);let p=await ht(r,a.href,{...t,method:c,headers:f,body:l,redirect:`manual`}),m=p.headers.get(`location`);if(!n.followRedirects||!ti.has(p.status)||m===null)return p;if(await p.body?.cancel(),d===ei)throw new T(`network`,`Too many redirects from "${e}"`);a=await i(new URL(m,a).href),u&&=a.origin===o,ri(p.status,c)&&(c=`GET`,l=void 0,s.delete(`content-type`))}}var U=v().int().positive().max(2**53-1),ai=U.max(2147483647),oi=_({operationTimeoutMs:ai.optional(),connectTimeoutMs:ai.optional(),liveStepTimeoutMs:ai.optional(),maxWireRecordBytes:U.optional(),maxWireResponseBytes:U.optional(),maxEventBytes:U.optional(),maxStepBytes:U.optional(),maxStepEvents:U.optional(),maxPendingToolCalls:U.optional()}),si=[`text`,`image`,`speech`,`transcription`,`live`,`decision`,`embedding`],ci=w({id:o().regex(/^[A-Za-z][A-Za-z0-9]*$/),name:o().min(1),description:o().min(1),endpoints:re(y(si),o().min(1)),operationNames:re(y(si),o().regex(/^[a-z][a-z0-9_]*$/))});function li(e,t){return new T(`config`,D(`protocol.definition`,{id:e,issues:t}))}function ui(e){let t=ci.safeParse(e);if(!t.success)throw li(String(e.id),he(t.error))}function di(e,t,n){let r=Object.keys(t).toSorted().join(`, `),i=Object.keys(n).toSorted().join(`, `);if(r!==i)throw li(e,`operationNames name [${i}]; endpoints serve [${r}]`)}function fi(e,t,n,r){if(!n)throw new T(`internal`,D(`protocol.part_schema`,{protocol:e.id,kind:t}));let i=n.safeParse(r);if(!i.success)throw new T(`bad_response`,D(`protocol.part_invalid`,{protocol:e.id,kind:t}),{cause:i.error});return i.data}function pi(e,t){return t.type===`reasoning`?{...t,data:fi(e,`reasoning`,e.reasoning,t.data),origin:{protocol:e.id}}:t.type===`custom`?{type:`custom`,kind:`${e.id}.${t.kind}`,data:fi(e,t.kind,e.custom?.[t.kind],t.data)}:t}async function*mi(e,t){for await(let n of t)yield pi(e,n)}function hi(e,t){let{complete:n,openSession:r}=t;return{...t,...n?{complete:r=>mi(e,n.call(t,r))}:{},...r?{async openSession(n){let i=await r.call(t,n);return{...i,events:()=>mi(e,i.events())}}}:{}}}function gi(e,t,n){let r=n??{},i=e.options.safeParse(r),a=(e.refusedOptions?.(t)??[]).filter(e=>typeof r==`object`&&!!r&&e in r);if(i.success&&a.length===0)return i.data;let o=i.success?a.map(e=>`✖ ${t} takes no ${e}`).join(`
|
|
2
2
|
`):he(i.error);throw new T(`config`,D(`protocol.options`,{apiId:t,protocol:e.id,issues:o}))}function W(e){if(ui(e),typeof e.create!=`function`||typeof e.options?.safeParse!=`function`)throw li(e.id,`create and options are required`);return di(e.id,e.endpoints,e.operationNames),Object.freeze({...e,lineage:Object.freeze([e.id]),create:t=>hi(e,e.create(t))})}function _i(e){return e instanceof Ee?e.shape:void 0}function vi(e,t){let n=e??{},r={};for(let e of t)e in n&&(r[e]=n[e]);return r}function yi(e,t){let n=_i(e.options),r=t.options?_i(t.options):{};if(t.options&&!n)throw new T(`config`,D(`protocol.base_options`,{protocol:t.id,base:e.id}));for(let i of Object.keys(r??{}))if(n&&i in n)throw new T(`config`,D(`protocol.option_clash`,{protocol:t.id,option:i,base:e.id}));return{schema:n?_({...n,...r}):e.options,baseKeys:n?Object.keys(n):void 0,addedKeys:Object.keys(r??{})}}function bi(e,t,n,r,i){let a={profileType:r.profileType,apiId:r.apiId,options:vi(r.options,n.addedKeys)},o=[],s=t.read?.({...a,...i?{request:i}:{}}),c=e=>{for(let n of e??[])o.push(pi(t,n))},l=(e,n,o=[])=>{if(!t.body)return{body:e,wroteTools:o};let s=t.body(e,{...a,builtInTools:r.builtInTools,headers:n,...i?{request:i}:{}});return{body:s.body,wroteTools:[...o,...s.wroteTools??[]]}};async function*u(e){for await(let t of e){let e=s?.row(t);c(e?.events),e?.consumed||(yield t)}}let d={...r,options:n.baseKeys?vi(r.options,n.baseKeys):r.options,send(e,t){let n=new Headers(t.headers),i=l(e,n,t.wroteTools);return u(r.send(i.body,{...t,headers:Object.fromEntries(n),wroteTools:i.wroteTools}))},async connect(e,t){let n=l(e,new Headers,t?.wroteTools),i=await r.connect(n.body,{wroteTools:n.wroteTools});return{...i,frames:()=>u(i.frames())}}};async function*f(e){for await(let t of e)yield*o.splice(0),t.type===`done`&&c(s?.finish?.().events),yield*o.splice(0),yield t;yield*o.splice(0)}return{operations:e.create(d),drained:f}}function xi(e){let t=e().operations,n={};return t.complete&&(n.complete=t=>{let{operations:n,drained:r}=e(t);return r(n.complete(t))}),t.openSession&&(n.openSession=async t=>{let{operations:n,drained:r}=e(t),i=await n.openSession(t);return{...i,events:()=>r(i.events())}}),t.decide&&(n.decide=t=>e().operations.decide(t)),t.embed&&(n.embed=t=>e().operations.embed(t)),n}function Si(e,t,n){let r=t[e]??n[e];return r?{[e]:r}:{}}function Ci(e,t){ui({...t,endpoints:t.endpoints??{},operationNames:t.operationNames??{}});let n={...e.endpoints,...t.endpoints},r={...e.operationNames,...t.operationNames};di(t.id,n,r);let i=yi(e,t);return Object.freeze({id:t.id,name:t.name,description:t.description,endpoints:n,operationNames:r,options:i.schema,...e.continuation?{continuation:e.continuation}:{},...t.reasoning?{reasoning:t.reasoning}:{},...t.custom?{custom:t.custom}:{},...Si(`framing`,t,e),...Si(`error`,t,e),...Si(`embeddingLimits`,t,e),...Si(`refusedOptions`,t,e),base:e,lineage:Object.freeze([t.id,...e.lineage]),create:n=>xi(r=>bi(e,t,i,n,r))})}function wi(e,t){return t.lineage.includes(e)}var Ti=o().regex(vt),G=_({maxOutputTokens:v().int().positive().optional(),temperature:v().finite().nonnegative().optional(),efforts:i(o().min(1),y([`none`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`])).optional(),defaultEffort:o().min(1).optional(),allowEffortSelect:S().optional(),summaries:S().optional(),builtInTools:b(o().min(1)).optional(),compaction:Se(e=>typeof e==`object`&&!!e&&!Array.isArray(e)).optional()}).shape,Ei=_({protocol:o().min(1).describe(`The API shape this model is spoken to in.`),provider:o().min(1).describe(`The service that runs the model or routes requests to one, such as Gemini or OpenRouter. Its registration supplies the endpoint and authentication.`),apiId:o().min(1).describe(`The id the provider knows the model by.`),maxOutputTokens:G.maxOutputTokens.describe(`The most tokens the model may write in one step.`),temperature:G.temperature.describe(`How varied the model's answers are.`),efforts:G.efforts.describe(`Effort names a turn may pick, each mapped to a thinking level.`),defaultEffort:G.defaultEffort.describe(`The effort used when a turn picks none.`),allowEffortSelect:G.allowEffortSelect.describe(`Whether a turn may pick an effort.`),summaries:G.summaries.describe(`Whether the model sends summaries of its thinking.`),builtInTools:G.builtInTools.describe(`Tools the provider runs itself, by the ids it knows them by.`),compaction:G.compaction.describe(`How the conversation is shortened when it grows too long.`),keySlot:Ti.optional().describe(`The slot this model's key is read from, in place of the provider's.`),fallbackKeySlot:Ti.optional().describe(`The slot tried once when the first key is out of quota.`),options:I.optional().describe(`What this model's protocol takes beyond the shared settings.`),limits:oi.optional().describe(`Theorem's cut-offs for this model's calls; each one left out is no limit.`)}),Di=Ei,Oi=Ei.pick({protocol:!0,provider:!0,apiId:!0,keySlot:!0,fallbackKeySlot:!0,options:!0,limits:!0}).extend({timeoutMs:v().positive().optional().describe(`How long a decision may take before it fails.`)});function ki(e,t){let n=t.keySlot??e.keySlot,r=t.fallbackKeySlot??e.fallbackKeySlot;return{...n===void 0?{}:{keySlot:n},...r===void 0?{}:{fallbackKeySlot:r}}}function Ai(e,t){let n=e.serves.find(e=>e.protocol.id===t.protocol);if(!n)throw new T(`config`,D(`protocol.not_served`,{provider:e.id,protocol:t.protocol}));return n}function ji(e,t){return Ai(e,t).protocol}function Mi(e,t,n){return ji(e,t).operationNames[n]}function Ni(e,t,n,r={webSocketHeaders:!0}){let i=Ai(e,t),{protocol:a}=i;if(a.endpoints[n]===void 0)throw new T(`unsupported`,D(`protocol.profile_type`,{protocol:a.id,profileType:n}));let o=I.parse(gi(a,t.apiId,t.options)),s=ki(e,t);if(s.keySlot!==void 0&&s.keySlot===s.fallbackKeySlot)throw new T(`config`,D(`provider.model_fallback_slot`));if((t.keySlot||t.fallbackKeySlot)&&!e.definition.key)throw new T(`config`,D(`protocol.no_key`,{provider:e.id}));let c=i.authorize??e.definition.authorize;if(n===`live`&&c?.webSocketHeaders&&!r.webSocketHeaders)throw new T(`unsupported`,D(`protocol.ws_headers`,{provider:e.id}));return{...t,options:o}}function Pi(e){return e.type===`text`?{type:`text`,text:e.text}:`uri`in e?{type:e.type,mimeType:e.mimeType,uri:e.uri}:{type:e.type,mimeType:e.mimeType,data:e.data}}function Fi(e){return e.type!==`text`&&`uri`in e}function K(e){let t=e.parts??[];return e.content?[{type:`text`,text:e.content},...t]:[...t]}function Ii(e){let t=e.structured===void 0?e.text:JSON.stringify(e.structured);return[...t?[{role:`assistant`,content:t}]:[],...e.calls.length?[Li(e.calls)]:[]]}function Li(e){let t=e.flatMap(e=>e.reasoning??[]),n=[];for(let t of e)n.push({id:t.callId,type:`function`,function:{name:t.name,arguments:JSON.stringify(t.arguments)}});return{role:`assistant`,tool_calls:n,...t.length?{reasoning:[...t]}:{}}}function Ri(e,t){return Object.assign(t=>({sign:n=>e(t,n)}),{webSocketHeaders:t})}var zi=o().url().refine(e=>{if(!URL.canParse(e))return!0;let t=new URL(e);return[`http:`,`https:`].includes(t.protocol)&&!t.username&&!t.password&&![...t.searchParams.keys()].some(e=>/key|auth|secret|token|password/i.test(e))},D(`protocol.endpoint_url`));function Bi(){return Ri((e,t)=>t.headers.set(`Authorization`,`Bearer ${e}`),!0)}function Vi(e){return Ri((t,n)=>n.headers.set(e,t),!0)}function Hi(e){return Ri((t,n)=>n.url.searchParams.set(e,t),!1)}var Ui=w({id:o().regex(/^[a-z][a-z0-9-]*$/),name:o().min(1),description:o().min(1),traceName:o().min(1).optional()});function Wi(e){let t=Ui.safeParse(e);if(!t.success||typeof e.serves!=`function`)throw new T(`config`,D(`protocol.definition`,{id:String(e.id),issues:t.success?`serves is required`:he(t.error)}));return Object.freeze({...e})}function Gi(e,t){let n=e.serves.find(e=>e.protocol.id===t);if(!n)throw new T(`config`,D(`protocol.not_served`,{provider:e.id,protocol:t}));return n}function Ki(){let e=new Map,t=new Map,n=e=>{let n=[];for(let r=e;r;r=r.base){let e=t.get(r.id);if(e&&e!==r)throw new T(`config`,D(`protocol.id_clash`,{protocol:r.id}));n.push(r)}return n},r=(r,i,a)=>{let o=i.id??r.id;if(!a&&e.has(o))throw new T(`config`,D(`protocol.provider_id_clash`,{provider:o}));let s=r.connection?r.connection.safeParse(i.connection):{success:!0,data:void 0};if(!s.success)throw new T(`config`,D(`protocol.connection`,{provider:o,issues:he(s.error)}));if(s.data!==void 0&&tn.parse(s.data),i.keySlot!==void 0&&Ti.parse(i.keySlot),i.fallbackKeySlot!==void 0&&Ti.parse(i.fallbackKeySlot),i.keySlot&&i.keySlot===i.fallbackKeySlot)throw new T(`config`,D(`provider.fallback_slot`));if((i.keySlot||i.fallbackKeySlot)&&!r.key)throw new T(`config`,D(`protocol.no_key`,{provider:o}));let c=Object.freeze(r.serves(s.data).map(e=>Object.freeze({...e}))),l=c.flatMap(e=>n(e.protocol)),u=(e,t,n)=>{let{protocol:r}=Gi({id:o,serves:c},typeof e==`string`?e:e.id);return{protocol:r.id,options:gi(r,t,n)}},d=Object.freeze({id:o,definition:r,connection:s.data,...i.keySlot?{keySlot:i.keySlot}:{},...i.fallbackKeySlot?{fallbackKeySlot:i.fallbackKeySlot}:{},serves:c,model(e,t,n={}){let{options:r,...i}=n;return Di.parse({...i,provider:o,apiId:t,...u(e,t,r)})},decisionModel(e,t,n={}){let{options:r,...i}=n;return Oi.parse({...i,provider:o,apiId:t,...u(e,t,r)})}});for(let e of l)t.set(e.id,e);return e.set(o,d),d};return{register:(e,t={})=>r(e,t,!1),replace:(e,t={})=>r(e,t,!0),get:t=>e.get(t),require(t,n){let r=e.get(t);if(!r)throw new T(`config`,D(`protocol.provider_missing`,{provider:t,apiId:n}));return r},list:()=>[...e.values()],protocols:()=>[...t.values()]}}var qi=[`text`],Ji=_t,Yi=[`length`,`stream_incomplete`],Xi=new Set([`egress`,`canary`,`prompt_echo`,`provider_tool_leak`]);function Zi(e){return e.kind===`filtered`&&Xi.has(e.native??``)}var Qi=1500,$i=new Set(_t);function ea(e){return $i.has(e)}new Set(Ji);var ta=new Set([`provider_error`,`stream_incomplete`]);function na(e){return ta.has(e)}function ra(e){return typeof e==`object`&&e.reason?{kind:`cancelled`,native:e.reason}:{kind:`cancelled`}}function ia(e,t){return!e||!ea(e.kind)?!1:(t?.autoContinue??Yi).includes(e.kind)}function aa(e){if(e.type!==`live`)return e.turnBehaviour?.resumption}function oa(e){return e.type===`text`&&e.turnBehaviour?.allowSteering!==!1}function sa(e){return e.type===`text`||e.type===`live`?e.turnBehaviour?.allowSteering!==!1:!1}function ca(e,t){let n=t?.trim()||e?.trim()||void 0,r=(t||e||``).toLowerCase();return r?r===`network_error`||r.includes(`network`)?{kind:`provider_error`,native:n}:la((e||``).toLowerCase(),r,n):{kind:`stream_incomplete`,native:n}}function la(e,t,n){return e===`stop`?/error|fail/.test(t)?{kind:`provider_error`,native:n}:{kind:`completed`,native:n}:e===`length`?{kind:`length`,native:n}:e===`tool_calls`||e===`tool-calls`?{kind:`tool`,native:n}:e===`content_filter`||e===`content-filter`?{kind:`filtered`,native:n}:{kind:`provider_error`,native:n}}function ua(e){let t=(e||``).toLowerCase(),n=e||void 0;switch(t){case`completed`:return{kind:`completed`,native:n};case`incomplete`:case`budget_exceeded`:return{kind:`length`,native:n};case`requires_action`:return{kind:`tool`,native:n};case`cancelled`:return{kind:`cancelled`,native:n};case`failed`:return{kind:`provider_error`,native:n};case`in_progress`:case`queued`:return{kind:`stream_incomplete`,native:n};default:return{kind:`stream_incomplete`,native:n}}}function da(e,t){for(let n=e.length-1;n>=0;--n){let r=e[n];if(r!==void 0&&t(r))return r}}function q(e){return E(e)?e:void 0}function J(e){if(typeof e==`string`&&e.trim())return e}function Y(e){return typeof e==`number`&&Number.isFinite(e)&&e>=0?e:void 0}function fa(e){let t=e.input?e.input:void 0;if(t===void 0&&!e.output)return;let n=[];t===void 0&&n.push(`input`),e.output===void 0&&n.push(`output`);let r=t??0,i=e.output??0;return{input:r,output:i,...e.thinking?{thinking:e.thinking}:{},...e.toolUse?{toolUse:e.toolUse}:{},...e.cached?{cached:e.cached}:{},...e.cacheWrite?{cacheWrite:e.cacheWrite}:{},total:r+i,...e.cost?{cost:e.cost}:{},...n.length>0?{estimated:n}:{},...e.byModality?{byModality:e.byModality}:{},...e.grounding?{grounding:e.grounding}:{}}}function pa(e){let t=e.flatMap(e=>e.cost?[e.cost]:[]);if(t.length===0)return;let n=t.flatMap(e=>e.upstreamUsd===void 0?[]:[e.upstreamUsd]),r=t.length<e.length||t.some(e=>e.partial);return{usd:t.reduce((e,t)=>e+t.usd,0),...n.length>0?{upstreamUsd:n.reduce((e,t)=>e+t,0)}:{},...r?{partial:!0}:{}}}function ma(e){let t=[`input`,`output`],n={};for(let r of t){let[t,...i]=e.map(e=>e.byModality?.[r]),a=Object.keys(t??{}).filter(e=>i.every(t=>t?.[e]!==void 0));a.length!==0&&(n[r]=Object.fromEntries(a.map(t=>[t,e.reduce((e,n)=>e+(n.byModality?.[r]?.[t]??0),0)])))}return Object.keys(n).length>0?n:void 0}function ha(e){let t=new Map;for(let n of e.flatMap(e=>e.grounding??[]))t.set(n.type,[...t.get(n.type)??[],n]);if(t.size!==0)return[...t].map(([e,t])=>{let n=t.every(e=>e.searchQueryCount!==void 0);return{type:e,count:t.reduce((e,t)=>e+t.count,0),...n?{searchQueryCount:t.reduce((e,t)=>e+(t.searchQueryCount??0),0)}:{}}})}function ga(e){return va(e.flatMap(e=>e.type===`tokens`?[e.tokens]:[]))}function _a(e){return va(e.flatMap(e=>{if(e.type===`tokens`)return[e.tokens];if(e.type!==`tool`)return[];let{tool:t}=e;return(t.phase===`complete`||t.phase===`error`)&&t.tokens?[t.tokens]:[]}))}function va(e){if(e.length===0)return;let t=t=>e.reduce((e,n)=>e+(t(n)??0),0),n=t(e=>e.input),r=t(e=>e.output),i=t(e=>e.thinking),a=t(e=>e.toolUse),o=t(e=>e.cached),s=t(e=>e.cacheWrite),c=pa(e),l=ma(e),u=ha(e),d=[`input`,`output`],f=d.filter(t=>e.some(e=>e.estimated?.includes(t))),p={};for(let e of d){let n=t(t=>t.unknownMedia?.[e]);n>0&&(p[e]=n)}return{input:n,output:r,...i?{thinking:i}:{},...a?{toolUse:a}:{},...o?{cached:o}:{},...s?{cacheWrite:s}:{},total:n+r,...c?{cost:c}:{},...f.length>0?{estimated:f}:{},...Object.keys(p).length>0?{unknownMedia:p}:{},...l?{byModality:l}:{},...u?{grounding:u}:{}}}var ya=1e3,ba=400,xa=new Set([`http_request`,`http_response`,`http_error_body`,`http_throw`]),Sa=new Set([`text`,`image`,`audio`]),Ca={completed:`stop`,length:`length`,tool:`tool_call`,filtered:`content_filter`,provider_error:`error`};function wa(e){let[t]=e.split(`/`);return t===`application`||t===`text`||!t?`document`:t}function Ta(e){return e.type===`text`?{type:`text`,...A(e.text)}:`uri`in e?{type:`uri`,modality:e.type,mime_type:e.mimeType,uri:e.uri}:{type:`blob`,modality:e.type,mime_type:e.mimeType,...He(e.data)}}function Ea(e){let t=K(e).map(Ta);if(e.role===`tool`)return{role:`tool`,parts:[{type:`tool_call_response`,...e.tool_call_id?{id:e.tool_call_id}:{},response:A(e.content??``)},...(e.parts??[]).map(Ta)]};let n=(e.tool_calls??[]).map(e=>({type:`tool_call`,id:e.id,name:e.function.name,arguments:A(e.function.arguments)}));return{role:e.role,parts:[...t,...n]}}var Da=new WeakMap;function Oa(e){let{conversation:t}=e;if(`previous`in t){let e=Da.get(t.previous),n=[...e?.input??[],...e?.output?[e.output]:[]];return{input:[...n,...t.continuation.map(Ea)],sentFrom:n.length}}let n=t.input.length>0?[{role:`user`,parts:t.input.map(Ta)}]:[];return{input:[...t.history.map(Ea),...n]}}var ka=class{parts=[];open;calls=new Map;add(e,t){switch(e.type){case`text`:this.appendText(`text`,e.text);return;case`thought`:this.appendText(`reasoning`,e.text);return;case`tool`:this.addTool(e.tool);return;case`structured`:this.push({type:`structured`,content:N(e.structured??null)});return;case`media`:this.push(Na(e.media));return;case`evidence`:{let{evidence:n}=e;if(n.kind===`input_transcription`||n.kind===`output_transcription`){this.appendText(`text`,e.text??``,n.kind,n.interim);return}let r=La(n,t);r&&this.push(r);return}case`tool_draft`:case`structured_draft`:return;default:return}}appendText(e,t,n,r){if(!t)return;let i=`${e}:${n??``}:${r?`interim`:``}`;if(this.open?.key===i){this.open.text+=t,Object.assign(this.open.part,A(this.open.text));return}let a={type:e,...A(t),...X(`theorem.source`,n),...r?{"theorem.interim":!0}:{}};this.parts.push(a),this.open={key:i,text:t,part:a}}addTool(e){if(e.phase===void 0){let t=Ma(e);this.calls.set(e.callId,t),this.push(t);return}let t=this.calls.get(e.callId),n=e.phase===`error`?Aa(e.failure):void 0;t&&n!==void 0&&Object.assign(t,{arguments:A(n)})}push(e){this.parts.push(e),this.open=void 0}};function Aa(e){let t=q(e?.details)?.raw;return typeof t==`string`?t:void 0}function ja(e){return Aa(e.failure)??JSON.stringify(e.arguments)}function Ma(e){return{type:`tool_call`,id:e.callId,name:e.name,arguments:A(ja(e))}}function Na(e){return{type:`blob`,modality:wa(e.mimeType),mime_type:e.mimeType,...He(e.data)}}var Pa=`_call`,Fa=`_result`;function Ia(e){switch(e.kind){case`code_execution_call`:return{side:`call`,name:`code_execution`,id:e.id};case`code_execution_result`:return{side:`result`,name:`code_execution`,id:e.callId};case`provider_step`:{let{step:t,raw:n}=e;if(t.endsWith(Pa)){let e=typeof n?.id==`string`?n.id:void 0;return{side:`call`,name:t.slice(0,-5),id:e}}if(t.endsWith(Fa)){let e=typeof n?.call_id==`string`?n.call_id:void 0;return{side:`result`,name:t.slice(0,-7),id:e}}return}default:return}}function La(e,t){let n=Ia(e);if(!n)return;let r={"theorem.observed_end":t,...e.partial?{"theorem.partial":!0}:{}},i={...N(e.raw??{}),type:n.name};return n.side===`call`?{type:`server_tool_call`,...X(`id`,n.id),name:n.name,server_tool_call:i,...r}:{type:`server_tool_call_response`,...X(`id`,n.id),server_tool_call_response:i,...r}}function Ra(e){switch(e.type){case`grounding`:{let{searchHtml:t,metadata:n,chunks:r}=e.grounding;return!t&&!n&&!r?void 0:{...t?{search_html:A(t)}:{},...n||r?{raw:N({metadata:n,chunks:r})}:{}}}case`citation`:return{sources:N(e.sources)};case`evidence`:{let{evidence:t}=e;return Ia(t)||t.kind===`input_transcription`||t.kind===`output_transcription`?void 0:{provider:t.provider,...t.raw?{raw:N(t.raw)}:{}}}default:return}}function za(e){return{stage:e.stage,trust:e.trust,action:e.action,hits:e.hits.map(e=>({rule:e.rule,severity:e.severity,...X(`signal`,e.signal),...e.span?{start:e.span.start,end:e.span.end}:{},...X(`match`,e.match),...X(`label`,e.label),...X(`doc`,e.doc)})),...e.provenance?{provenance:{...e.provenance}}:{},...e.errorInternal?{error:A(e.errorInternal)}:{},...X(`error_summary`,e.errorSummary)}}var Ba={output_stream:`output_delta`,stream_canary:`output_delta`,tool_draft:`tool_call`,live_output:`live_outbound`};function Va(e,t,n,r){return{...n?za(n):{stage:r.stage,trust:r.trust,action:`allow`,hits:[]},check:e,duration_ms:t}}function Ha(e){let t={};for(let n of[`input`,`output`])for(let[r,i]of Object.entries(e?.[n]??{})){let e=Sa.has(r)?`gen_ai`:`theorem`;t[`${e}.usage.${r}.${n}_tokens`]=i}return t}function X(e,t){return t===void 0?{}:{[e]:t}}function Ua(e){return{"gen_ai.usage.input_tokens":e.input,"gen_ai.usage.output_tokens":e.output,...X(`gen_ai.usage.reasoning.output_tokens`,e.thinking),...X(`gen_ai.usage.cache_read.input_tokens`,e.cached),...X(`gen_ai.usage.cache_write.input_tokens`,e.cacheWrite),...X(`theorem.usage.tool_use.input_tokens`,e.toolUse),...Ha(e.byModality),...e.grounding?{"theorem.usage.grounding":e.grounding.map(e=>({type:e.type,count:e.count,...X(`search_query_count`,e.searchQueryCount)}))}:{},...X(`theorem.usage.cost_usd`,e.cost?.usd),...X(`theorem.usage.upstream_cost_usd`,e.cost?.upstreamUsd),...e.cost?.partial?{"theorem.usage.cost_partial":!0}:{},...e.estimated?.length?{"theorem.usage.estimated":[...e.estimated]}:{},...e.unknownMedia?{"theorem.usage.unknown_media":{...e.unknownMedia}}:{}}}function Wa(e){if(e)return e.provider}function Ga(e,t){return t===`live`?`speech`:e.structured?`json`:e.image?`image`:e.speech?`speech`:`text`}function Ka(e,t,n,r){let i=Wa(t);return{...X(`gen_ai.operation.name`,r),...X(`gen_ai.provider.name`,i),"gen_ai.request.model":e.apiId,"theorem.model.id":e.model,...X(`theorem.key_slot`,t?.keySlot),...X(`gen_ai.request.temperature`,e.temperature),...X(`gen_ai.request.max_tokens`,e.maxOutputTokens),...X(`gen_ai.request.reasoning.level`,e.thinking),"gen_ai.system_instructions":[{type:`text`,...A(e.system)}],...e.wireTools?.length?{"gen_ai.tool.definitions":A(JSON.stringify(e.wireTools))}:{},"gen_ai.output.type":Ga(e,n),...qa(e)}}function qa(e){let{image:t,speech:n,live:r}=e;return{"theorem.request.builtins":e.builtins.map(e=>e.id),...X(`theorem.request.summaries`,e.summaries),...X(`theorem.request.structured`,e.structured?.id),...X(`theorem.request.session_id`,e.sessionId),...t?{"theorem.request.image":{...X(`mime_type`,t.mimeType),...X(`aspect_ratio`,t.aspectRatio),...X(`resolution`,t.resolution),...X(`quality`,t.quality),...X(`background`,t.background),...X(`n`,t.n),...X(`seed`,t.seed),...X(`output_compression`,t.outputCompression),include_text:t.includeText}}:{},...n?{"theorem.request.speech":{...X(`voice`,n.voice),...X(`speed`,n.speed),...X(`format`,n.format)}}:{},...r?{"theorem.request.live":Ja(r,e)}:{}}}function Ja(e,t){let{vad:n,transcription:r}=e;return{...X(`voice`,e.voice),...n?{vad:{...X(`activity_handling`,n.activityHandling),...X(`start_sensitivity`,n.startSensitivity),...X(`end_sensitivity`,n.endSensitivity),...X(`prefix_padding_ms`,n.prefixPaddingMs),...X(`silence_duration_ms`,n.silenceDurationMs)}}:{},...X(`session_resumption`,e.sessionResumption),...e.contextCompression?{context_compression:{mechanism:`sliding_window`,...X(`trigger_tokens`,e.contextCompression.triggerTokens),...X(`target_tokens`,e.contextCompression.slidingWindow.targetTokens)}}:{},...r?{transcription:{...X(`input`,r.input),...X(`output`,r.output)}}:{},resumed:!!t.providerState}}function Ya(e,t){return!t||typeof t!=`object`?{}:Object.fromEntries(Object.entries(t).map(([t,n])=>[`${e}.${t}`,[String(n)]]))}function Xa(e){if(typeof e!=`string`)return{};let t=URL.canParse(e)?new URL(e):void 0;return t?{"server.address":t.hostname,"url.path":t.pathname}:{}}var Za=class{call;tries=0;current;last;lastStatus;awaitingFirstChunk=!1;streamed=!1;constructor(e){this.call=e}row(e){let t=typeof e.eventType==`string`?e.eventType:void 0;return!t||!xa.has(t)?(this.firstChunk(),!1):(t===`http_request`?this.open(e):t===`http_response`?this.response(e):t===`http_error_body`?this.errorBody(e):this.thrown(e),!0)}open(e){this.current?.end();let t=this.last?.msSinceEnd();this.current=this.call.child(String(e.method??`GET`),{kind:`CLIENT`,attributes:{"http.request.method":String(e.method??`GET`),...Xa(e.url),"http.request.resend_count":this.tries,...typeof e.keySlot==`string`?{"theorem.key_slot":e.keySlot}:{},...X(`theorem.retry.backoff_ms`,t),...Ya(`http.request.header`,e.headers)}}),this.tries+=1,this.streamed=q(e.body)?.stream===!0,this.streamed&&this.call.set({"gen_ai.request.stream":!0}),`body`in e?this.current.event(`theorem.wire.request`,{body:N(e.body)}):typeof e.bodyKind==`string`&&this.current.event(`theorem.wire.request`,{body_kind:e.bodyKind}),typeof e.keySlot==`string`&&this.call.set({"theorem.key_slot":e.keySlot})}response(e){let t=typeof e.status==`number`?e.status:void 0;this.lastStatus=t,this.current?.set({...X(`http.response.status_code`,t),...Ya(`http.response.header`,e.headers)}),t!==void 0&&t>=ba?this.current?.set({"error.type":String(t)}):this.awaitingFirstChunk=!0}errorBody(e){this.current?.event(`theorem.upstream.row`,{row:N(e)}),this.close({code:`ERROR`,message:String(this.lastStatus??`error`)})}thrown(e){let t=typeof e.name==`string`?e.name:`Error`;this.current?.event(`exception`,{"exception.type":t,"exception.message":A(String(e.message??``))}),this.current?.set({"error.type":t}),this.close({code:`ERROR`,message:t})}firstChunk(){this.awaitingFirstChunk&&this.current&&(this.awaitingFirstChunk=!1,this.call.set({"gen_ai.response.time_to_first_chunk":this.current.msSinceStart()/ya}))}close(e){this.current&&=(this.current.end(e),this.last=this.current,void 0)}};function Qa(e,t,n){return e!==void 0&&e>=ba?{code:`ERROR`,message:String(e)}:n===void 0?t?{code:`UNSET`}:{code:`OK`}:{code:`ERROR`,message:Tt(n)}}function $a(e){return e instanceof Error?e.name:`Error`}function eo(e,t){e.event(`exception`,{"exception.type":$a(t),"exception.message":A(Ze(t)),...t instanceof Error&&t.stack?{"exception.stacktrace":A(t.stack)}:{}})}function to(e,t){eo(e,t);let n=Tt(t);e.set({"error.type":n}),e.end({code:`ERROR`,message:n})}function no(e,t){for(let[n,r]of t)r.decided||e.event(`theorem.guardrail`,{...Va(n,r.ms,void 0,{stage:Ba[n],trust:`untrusted`}),runs:r.runs})}function ro(e){let t=0;for(let n of e.values())t+=n.ms;return t>0?{"theorem.guardrail.stream_ms":t}:{}}var io=new Set([`cancelled`,`interrupted`]);function ao(e,t){let n=e!==void 0&&io.has(e.kind),r=e&&!n?Ca[e.kind]??e.kind:void 0;return t?{stopped:n,finish:r,status:{code:`ERROR`,message:t},attributes:{"error.type":t}}:{stopped:n,finish:r,status:{code:n?`UNSET`:`OK`},attributes:{}}}function oo(e,t,n){let r=t?n===`turn`?{"gen_ai.response.finish_reasons":[t]}:{"gen_ai.response.status":t}:{};return{...X(`gen_ai.response.id`,e?.id||void 0),...X(`gen_ai.response.model`,e?.model||void 0),...r}}function so(e,t){let{req:n,usage:r,transport:i,operation:a}=t,o=Oa(r),s=e(a?`${a} ${n.apiId}`:n.apiId,{kind:`CLIENT`,attributes:{...Ka(n,t.binding,i,a),"gen_ai.input.messages":o.input,...X(`theorem.input.sent_from`,o.sentFrom),"theorem.step":t.step,...X(`theorem.attempt`,t.attempt)}}),c=new Za(s),l=new ka,u=new ka,d=[],f,p,m=!1,h=new Map,g;return{span:s,tap:e=>{c.row(e)||s.event(`theorem.upstream.row`,{row:N(e)})},observe:e=>{if(e.type===`evidence`&&e.evidence.kind===`input_transcription`){u.add(e,s.nowUnixNano());return}l.add(e,s.nowUnixNano()),e.type===`text`&&!m&&(m=!0,s.set({"theorem.response.time_to_first_text":s.msSinceStart()/ya}));let t=Ra(e);t&&s.event(`theorem.grounding`,t),e.type===`error`&&d.push(e),e.type===`response`&&(f=e.response),e.type===`done`&&(p=e.stop.native??p)},guardrail:e=>{let t=g?h.get(g):void 0;!(g&&t)||t.decided?s.event(`theorem.guardrail`,za(e)):(t.decided=!0,s.event(`theorem.guardrail`,{...Va(g,t.ms,e,{stage:Ba[g],trust:`untrusted`}),runs:t.runs}))},guardTime:(e,t)=>{let n=h.get(e)??{ms:0,runs:0,decided:!1};n.ms+=t,n.runs+=1,h.set(e,n),g=e},end:e=>{for(let e of d)s.event(`exception`,{"exception.type":e.errorKind,"exception.message":A(e.errorInternal??e.error??``)});e.thrown!==void 0&&eo(s,e.thrown),no(s,h);let t=d.at(-1),n=e.thrown===void 0?t?.errorKind:Tt(e.thrown),a=ao(e.stop,n),o={role:`assistant`,parts:l.parts,...X(`finish_reason`,a.finish)},{input:m}=Oa(r);Da.set(r,{input:m,output:o});let g=u.parts.length>0?[{role:`user`,parts:u.parts}]:[];c.close(Qa(c.lastStatus,a.stopped,e.thrown)),s.set({"gen_ai.input.messages":[...m,...g],"gen_ai.output.messages":[o],...e.tokens?Ua(e.tokens):{},...oo(f,a.stopped?void 0:p,i),...X(`theorem.stop.kind`,e.stop?.kind),...ro(h),...a.attributes}),s.end(a.status)}}}function co(e){let t=[...e?.attachments??[],...e?.voice??[]].map(e=>`uri`in e?{type:`uri`,modality:wa(e.mimeType),mime_type:e.mimeType,uri:e.uri}:{type:`blob`,modality:wa(e.mimeType),mime_type:e.mimeType,...He(e.data)}),n=[...e?.text?[{type:`text`,...A(e.text)}]:[],...t];return n.length>0?[{role:`user`,parts:n}]:[]}function lo(e){return(e??[]).map(e=>({traceparent:e.traceparent,attributes:{"theorem.link.kind":e.kind,...X(`theorem.stop.kind`,e.stop)}}))}function uo(e){return{...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?Tt(t.thrown):a?.errorKind??i,u={role:`assistant`,parts:t.delivered.parts,...X(`finish_reason`,ao(r?.stop,void 0).finish)};e.set({"gen_ai.output.messages":[u],...n?Ua(n):{},...i?{"theorem.stop.kind":i}:{},"theorem.attempts":t.attempts,"theorem.steps":t.calls,...t.seen.some(e=>e.type===`compaction`&&e.outcome===`compacted`)?{"gen_ai.conversation.compacted":!0}:{},...c&&o?{"theorem.error.public":A(o)}:{},...c&&l?{"error.type":l}:{}}),c?e.end({code:`ERROR`,...l?{message:l}:{}}):e.end(i&&!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:Tt(e.thrown)):void 0;n.set({...e.result?{"gen_ai.tool.call.result":A(e.result.text)}:{},...e.result?.parts?.length?{"theorem.tool.call.result.parts":e.result.parts.map(Ta)}:{},...e.data?{"theorem.tool.data":N(e.data.value)}:{},"theorem.tool.outcome":e.outcome,...X(`theorem.tool.failure.code`,e.failure?.code),...X(`error.type`,t)});let r=Ss[e.outcome];n.end(r===`ERROR`&&t?{code:r,message:t}:{code:r})}}}function ws(e){return e.modelText===void 0?Be(yr(e.finding,e.data),Je):e.modelText}function Ts(e){return{finding:`Tool error (${e.code}): ${e.message}`,...e.details===void 0?{}:{data:{details:e.details}}}}function Es(e){return Ts({...e,message:Be(e.message,Je)})}function Ds(e,t){return{type:`tool`,tool:{...t,name:e.name,callId:e.callId,...e.operationId?{operationId:e.operationId}:{},at:Date.now()}}}function Os(e,t,n,r){return Go(n?.activityFailed,{input:r})??D(`tool.activity_failed`,{tool:Ho(e)},t)}function ks(e){return e.activityFailed??Os(e.name)}function As(e,t,n=ws(Es(t))){return Ds(e,{phase:`error`,failure:t,readBack:n,activityPast:ks(e)})}function js(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 Ms(e){return`call_${e}_${crypto.randomUUID()}`}function Ns(e){return e===void 0?{}:E(e)?e:{value:e}}function Ps(e){return e instanceof Error?e.message:String(e)}function Fs(e,t){return Ds(e,{phase:`warning`,warning:{code:`sources_invalid`,message:t,severity:`warning`}})}function*Is(e,t,n){let r;try{r=t(n)}catch(t){yield Fs(e,`sources threw: ${Ps(t)}`);return}if(!Array.isArray(r)){yield Fs(e,`sources must return an array`);return}let i=[],a=[];r.forEach((e,t)=>{let n=Cn.safeParse(e);n.success?i.push(n.data):a.push(`[${String(t)}] ${n.error.issues.map(e=>`${e.path.join(`.`)||`source`}: ${e.message}`).join(`; `)}`)}),a.length>0&&(yield Fs(e,`sources not cited: ${a.join(` | `)}`)),i.length>0&&(yield{type:`citation`,sources:i,callId:e.callId})}function Ls(e,t,n,r){let i=n.resume?.edited,a=Go(e.labels?.activity,{input:t});return Ds(r,{phase:`running`,...i?{edited:{from:i.from,to:Ns(t)}}:{},...a?{activity:a}:{}})}var Rs=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*zs(e,t,n,r,i){return ze(n.signal),yield Ls(e,t,n,r),new Rs(i&&(()=>i(t)))}function Bs(e,t,n){ze(n.signal);let r=e.input.safeParse(t);return r.success?{ok:!0,data:r.data}:{ok:!1,failure:{code:`invalid_input`,kind:`bad_response`,message:D(`tool.input_invalid`,{},n.profile.labels),details:r.error.flatten()}}}function Vs(){return{stage:`network`,trust:`untrusted`,action:`block`,hits:[{rule:yt.blocked,severity:`high`}]}}function*Hs(e,t=Vs()){return yield{type:`guardrail`,guardrail:t},{code:`network_blocked`,kind:`blocked`,message:Ps(e)}}function*Us(e,t,n){let r=performance.now();try{let i=$r(e,Gs(t));return vs(n,`network`,performance.now()-r,void 0),{ok:!0,url:i}}catch(e){let t=Vs();return vs(n,`network`,performance.now()-r,t),{ok:!1,failure:yield*Hs(e,t)}}}function Ws(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 Gs(e){return Fr(e.profile.guardrails).network}function Q(e,t,n){return C(e).meta({title:t,description:n})}var Ks=_({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.`)}),qs=/^(gemini-embedding-001|text-embedding-|embedding-)/,Js={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`]}]},Ys={maxInputs:100,media:[]},Xs={query:`RETRIEVAL_QUERY`,document:`RETRIEVAL_DOCUMENT`};function Zs(e,t){return t===`query`?`task: search result | query: ${e}`:`title: none | text: ${e}`}function Qs(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?Zs(e.text,t):e.text}:e.type===`media`?{inlineData:{mimeType:e.mimeType,data:e.data}}:{fileData:{mimeType:e.mimeType,fileUri:e.uri}})}function $s(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 ec(e,t,n){let r={content:{parts:Qs(e,n.taskField?void 0:n.task)}},i=n.taskField&&n.task?Xs[n.task]:t.taskType;return i&&(r.taskType=i),t.outputDimensionality&&(r.outputDimensionality=t.outputDimensionality),r}var tc=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:Ks,embeddingLimits:e=>qs.test(e)?Ys:Js,refusedOptions:e=>qs.test(e)?[]:[`taskType`],create(e){return{async embed(t){let n=gi(tc,e.apiId,t.options),r={taskField:qs.test(e.apiId),...t.task?{task:t.task}:{}},i=Array.isArray(t.input)?t.input:[t.input],a=i.length===1?ec(i[0],n,r):{requests:i.map(t=>({model:`models/${e.apiId}`,...ec(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`?$s({embedding:e}):[],dimensions:e&&typeof e==`object`?$s({embedding:e}).length:0}))}}}}}),nc=_({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 rc(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 ic=W({id:`ollamaEmbeddings`,name:`Ollama Embeddings`,description:`Ollama’s local embedding endpoint.`,endpoints:{embedding:`/api/embed`},operationNames:{embedding:`embeddings`},options:nc,embeddingLimits:()=>({media:[]}),create(e){return{async embed(t){let n=nc.parse(t.options??{}),r=e.send({model:e.apiId,input:rc(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}))}}}}}),ac=_({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`.")}),oc={media:[{accept:[`image/*`]}]};function sc(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 cc(e){if(Array.isArray(e)){if(!e.every(e=>typeof e==`number`&&Number.isFinite(e)))throw Error(`OpenRouter returned an embedding with a non-finite value`);return e}if(typeof e!=`string`)throw Error(`OpenRouter returned an embedding in an unsupported format`);let t=lt(e);if(t.byteLength%Float32Array.BYTES_PER_ELEMENT!==0)throw Error(`OpenRouter returned an invalid base64 embedding length`);return Array.from(new Float32Array(t.buffer,t.byteOffset,t.byteLength/Float32Array.BYTES_PER_ELEMENT))}var lc=W({id:`openRouterEmbeddings`,name:`OpenRouter Embeddings`,description:`OpenRouter embedding models, including supported multimodal models.`,endpoints:{embedding:`/embeddings`},operationNames:{embedding:`embeddings`},options:ac,embeddingLimits:()=>oc,create(e){return{async embed(t){let n=ac.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(sc)};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=cc(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}}:{}}}}}}),uc=100,dc=599,fc=new Set([`API_KEY_INVALID`]);function pc(e){return Array.isArray(e)&&e.some(e=>{let t=q(e)?.reason;return typeof t==`string`&&fc.has(t)})}var mc={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},hc=new Set([`safety`,`recitation`,`language`,`prohibited_content`,`spii`,`blocklist`,`image_safety`,`image_prohibited_content`,`image_recitation`,`image_other`,`content_blocked`]);function gc(e,t){if(e===`cancelled`)return new T(`cancelled`,t);if(hc.has(e))return new T(`safety`,t);let n=mc[e];return n===void 0?new T(`bad_response`,t):new T(We(n),t)}function _c(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 pc(a)?new T(`auth`,o):typeof n==`number`&&n>=uc&&n<=dc?new T(We(n),o):typeof n==`string`?gc(n,o):new T(`bad_response`,o)}function vc(e,t,n){return e?.kind===`auth`?e:new T(We(t),e?.message??n)}var yc=_({location:_({latitude:v().min(-90).max(90),longitude:v().min(-180).max(180)})}),bc=[`googleSearch`,`googleMaps`,`urlContext`,`codeExecution`],xc={googleSearch:`google_search`,googleMaps:`google_maps`,urlContext:`url_context`,codeExecution:`code_execution`};function Sc(e){return e.filter(e=>bc.includes(e.id))}function Cc(e){let t=bc.find(t=>t===e.id);if(!t)throw new T(`config`,`Builtin '${e.id}' is not a Google tool`);return t}function wc(e){let t=Cc(e),n=xc[t];if(t===`googleMaps`&&e.args){let{location:t}=yc.parse(e.args);return{type:n,latitude:t.latitude,longitude:t.longitude}}return{type:n}}function Tc(e){let t=Cc(e);if(e.args)throw new T(`unsupported`,`Builtin '${t}' takes no args on Google Live`);return{[t]:{}}}function Ec(e){return{type:`text`,text:`[${e.type}: sent in the next message]`}}function Dc(e){return{type:`text`,text:`Files from ${e.name?`the ${e.name} result`:`a tool result`}:`}}function Oc(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:Ec(e))}),r.push(Dc(a),...e))}return i(),n}var kc={type:`text`,text:`Files the assistant sent:`};function Ac(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:Ec(e))}),n.push(kc,...e))}return n.length>0&&t.push({role:`user`,parts:n}),t}function jc(e){let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t}function Mc(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 Nc(e){let t=Mc(e);if(!t.ok)throw new T(`bad_response`,t.error);return t.value}function Pc(e,t){let n=e.name.trim(),r={name:n,callId:e.id??Ms(n)},i={stepId:e.stepId,stepCallCount:e.stepCallCount};if(!n)return Fc(r,`function call is missing a name`,t,i);let a=Mc(t);return a.ok?[js(r,a.value,i)]:Fc(r,a.error,a.raw,i)}function Fc(e,t,n,r={}){return[js(e,{},r),As(e,{code:`malformed_arguments`,kind:`bad_response`,message:t,details:{raw:n}})]}var Ic=[`minimal`,`low`,`medium`,`high`],Lc=[`pcm`];function Rc(e){if(e&&!Ic.includes(e))throw new T(`unsupported`,`Gemini does not take the '${e}' thinking level (${Ic.join(`, `)})`)}function zc(e){return e.replaceAll(/[A-Z]/g,e=>`_${e.toLowerCase()}`)}function Bc(e){if(Array.isArray(e))return e.map(Bc);if(e&&typeof e==`object`){let t={};for(let[n,r]of Object.entries(e))n===`schema`||n===`parameters`||n===`arguments`?t[zc(n)]=r:t[zc(n)]=Bc(r);return t}return e}function Vc(e){return Pi(e)}var Hc=`user_input`;function Uc(e){return{type:Hc,content:e.map(Vc)}}function Wc(e){let t=K(e);return t.length>0?t.map(Vc):[{type:`text`,text:``}]}var Gc=new Set([`text`,`image`,`video`]);function Kc(e){let t=K(e);return{type:`function_result`,...jc({name:e.name,call_id:e.tool_call_id}),result:t.length>0?t.map(Vc):[{type:`text`,text:``}]}}function qc(e,t){let n={type:`function_call`,id:e.id,name:e.function.name,arguments:Nc(e.function.arguments)};return t?[{type:`thought`,signature:t},n]:[n]}var Jc=_({call:v().int().min(0),signature:o().min(1)});function Yc(e,t){for(let n of e.reasoning??[]){let e=Jc.safeParse(n.data);if(e.success&&e.data.call===t)return e.data.signature}}function Xc(e,t){return{type:e===`assistant`?`model_output`:`user_input`,content:Wc(t)}}function Zc(e){if(e.role===`assistant`&&e.tool_calls&&e.tool_calls.length>0){let t=[];K(e).length>0&&t.push(Xc(`assistant`,e));for(let[n,r]of e.tool_calls.entries())t.push(...qc(r,Yc(e,n)));return t}return e.role===`assistant`?[Xc(`assistant`,e)]:[Xc(`user`,e)]}function Qc(e){return Oc(e,Gc).flatMap(e=>e.role===`tool`?[Kc(e)]:Zc(e))}function $c(e){return[{type:`text`,mimeType:`application/json`,schema:e}]}function el(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&&!Lc.includes(n))throw new T(`unsupported`,`Gemini speech returns ${Lc.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=$c(e.structured.jsonSchema))}function tl(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 nl=new Set([`gemini-3.8-flash-tts`,`gemini-3.8-flash-lite-tts`]);function rl(e,t,n){if(!nl.has(n))return{type:Hc,content:[{type:`text`,text:`Read the following aloud. ${t.trim()}\n`},...e.map(Vc)]};let r=[{type:`speech_metadata`,style:t}];return{type:Hc,content:e.map(Vc).map(e=>e.type===`text`?{...e,annotations:r}:e)}}function il(e){return{type:`function`,name:e.name,description:e.description,parameters:e.parameters}}function al(e){let t=[];for(let n of e.builtins)t.push(wc(n));for(let n of e.wireTools??[])t.push(il(n));return t}function ol(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 sl(e){if(e.continuation&&e.continuation.length>0)return Qc(ol(e.continuation));let t=Qc(ol(e.history??[]));if(e.input.length>0||t.length===0){let n=e.speech?.style;t.push(n?rl(e.input,n,e.apiId):Uc(e.input))}return t}function cl(e,t){e.store!==void 0&&(t.store=e.store),e.previousInteractionId&&(t.previousInteractionId=e.previousInteractionId),e.system&&(t.systemInstruction=e.system);let n=al(e);n.length>0&&(t.tools=n)}function ll(e){let t={temperature:e.temperature,maxOutputTokens:e.maxOutputTokens};return e.speech?tl(e,t):(Rc(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:sl(e),generationConfig:t}}function ul(e){let t=ll(e);return el(e,t),cl(e,t),Bc(t)}var dl=16,fl=new Set([`audio/pcm`,`audio/l16`]);function pl(e,t,n){for(let r=0;r<n.length;r++)e.setUint8(t+r,n.charCodeAt(r))}function ml(e){if(e===void 0||!/^\d+$/.test(e))return;let t=Number(e);return t>0?t:void 0}function hl(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 gl(e){let{essence:t,params:n}=hl(e);if(!fl.has(t))return;let r=ml(n.get(`rate`));if(r===void 0)return;let i=n.has(`channels`)?ml(n.get(`channels`)):1;if(i!==void 0)return{sampleRate:r,channels:i}}function _l(e,t){let{sampleRate:n,channels:r}=t,i=r*dl/8,a=n*i,o=e.length,s=new ArrayBuffer(44+o),c=new DataView(s);return pl(c,0,`RIFF`),c.setUint32(4,36+o,!0),pl(c,8,`WAVE`),pl(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,dl,!0),pl(c,36,`data`),c.setUint32(40,o,!0),new Uint8Array(s,44).set(e),new Uint8Array(s)}function vl(e){let t=gl(e.mimeType);if(!t)return e;let n=_l(lt(e.data),t);return{mimeType:`audio/wav`,data:St(n)}}function yl(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 bl(e){try{return{type:`structured`,structured:JSON.parse(e)}}catch(e){return M(new T(`bad_response`,`structured output was not valid JSON`,{cause:e}))}}function xl(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 Sl(e){if(!e)return[];let{grounding:t,sources:n}=e;return[{type:`grounding`,grounding:t},...n.length>0?[{type:`citation`,sources:n}]:[]]}function Cl(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 wl(e){return{maps:{title:e.title,uri:e.uri,...e.placeId?{placeId:e.placeId}:{}}}}function Tl(e){let t=J(e.uri);if(t)return{type:`web`,uri:t,title:J(e.title)??t}}function El(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 Dl(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 Ol(e){if(Array.isArray(e))for(let t of e){let e=J(q(t)?.search_suggestions);if(e)return e}}function kl(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 Al(e,t){if(Array.isArray(t))for(let n of t)El(e,kl(n))}function jl(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?Cl(t):void 0;r&&El(e,r)}}}function Ml(e){let t=[];if(Al(t,e.annotations),Array.isArray(e.content))for(let n of e.content)Al(t,q(n)?.annotations);jl(t,e.result);let n=[];for(let e of t)e.type===`maps`&&Dl(n,wl(e));let r=Ol(e.result);if(r||t.length!==0)return{grounding:{metadata:e,...n.length>0?{chunks:n}:{},...r?{searchHtml:r}:{}},sources:t}}function Nl(e,t){if(!e)return t;if(!t)return e;let n=[];for(let r of[...e.grounding.chunks??[],...t.grounding.chunks??[]])Dl(n,r);let r=[...e.sources];for(let e of t.sources)El(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 Pl(e){let t=q(e.delta);return Sl(t?Ml(t):void 0)}function Fl(e){let t;for(let n of e){let e=q(n);e&&(t=Nl(t,Ml(e)))}return Sl(t)}function Il(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&&El(r,Tl(t))}let i=J(q(t.searchEntryPoint)?.renderedContent);return Sl({grounding:{metadata:t,...n.length>0?{chunks:n}:{},...i?{searchHtml:i}:{}},sources:r})}function Ll(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 Rl(e,t){if(e||t)return{...e?{input:e}:{},...t?{output:t}:{}}}function zl(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 Bl(e){let t=q(e);return t?.type===`text`&&typeof t.text==`string`?t.text:``}function Vl(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 Hl=[[`/9j/`,`image/jpeg`],[`iVBORw0KGgo`,`image/png`],[`UklGR`,`image/webp`]];function Ul(e){return Hl.find(([t])=>e.startsWith(t))?.[1]}function Wl(e){let{data:t}=e;if(typeof t!=`string`||!t)return[];let n=Vl(e)??(e.type===`image`?Ul(t):void 0);return n?[{type:`media`,media:{mimeType:n,data:t}}]:[]}function Gl(e,t){return t?[{type:e,text:t}]:[]}function Kl(e){return e===`code_execution_call`||e===`code_execution_result`}function ql(e){return e.startsWith(`google_`)||e===`url_context_call`||e===`url_context_result`}function Jl(e){return{type:`evidence`,evidence:{provider:`google`,kind:`provider_step`,step:String(e.type??``),raw:e}}}function Yl(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`?Jl(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 Xl(e){let t=q(e);if(!t)return[];switch(t.type){case`thought_summary`:return Gl(`thought`,Bl(t.content));case`text`:return Gl(`text`,typeof t.text==`string`?t.text:``);case`image`:case`audio`:return Wl(t);default:return[]}}function Zl(e){return(Array.isArray(e.summary)?e.summary:[]).flatMap(e=>Gl(`thought`,Bl(e)))}function Ql(e){return(Array.isArray(e.content)?e.content:[]).flatMap(e=>{let t=q(e);return t?.type===`text`?Gl(`text`,typeof t.text==`string`?t.text:``):t?.type===`image`||t?.type===`audio`?Wl(t):[]})}function $l(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:Rl(Ll(t.input_tokens_by_modality,`tokens`),Ll(t.output_tokens_by_modality,`tokens`)),grounding:zl(t.grounding_tool_count)})}function eu(e){let t=$l(e.usage);if(!t)return;let n=typeof e.id==`string`?e.id:void 0;return{type:`tokens`,tokens:t,...n?{interactionId:n}:{}}}function tu(e){let t=[],n=eu(e);n&&t.push(n);let{steps:r}=e;Array.isArray(r)&&t.push(...Fl(r));let i=ru(e);return i&&t.push(i),t}function nu(e){let t=J(e.id),n=J(e.model);if(t||n)return{...t?{id:t}:{},...n?{model:n}:{}}}function ru(e){let{status:t}=e;if(typeof t==`string`)return{type:`done`,stop:ua(t),...typeof e.id==`string`?{interactionId:e.id}:{}}}function iu(){return{text:``,steps:new Map,sawMedia:!1,sawDone:!1,calls:0}}function au(e){return e===`function_call`||Kl(e)||ql(e)}function ou(e){return typeof e==`string`&&e.length>0?e:void 0}function su(e,t){let n=ou(e);n&&(t.thoughtSignature=n)}function cu(e,t){let n=ou(e.signature)??t.thoughtSignature;return t.thoughtSignature=void 0,n}function lu(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=cu(e,t),a=t.calls++;return[...i?[{type:`reasoning`,data:{call:a,signature:i},origin:{protocol:`geminiInteractions`}}]:[],...Pc({id:n,name:r},e.arguments)]}return Kl(n)?[Yl(e)]:ql(n)?[Jl(e)]:n===`thought`?(su(e.signature,t),Zl(e)):n===`model_output`?Ql(e):[]}function uu(e){return typeof e.index==`number`?e.index:0}function du(e,t){let n=q(e.step);if(!n)return;let r=String(n.type??``);r===`thought`&&su(n.signature,t),au(r)&&t.steps.set(uu(e),{...n})}function fu(e,t){let n=q(e.delta);if(!n)return[];let r=t.steps.get(uu(e));if(!r)return n.type===`thought_signature`&&su(n.signature,t),Xl(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`?xl({id:ou(r.id),name:typeof r.name==`string`?r.name:``,args:t,drafted:e.length}):[]}return Object.assign(r,n),[]}function pu(e,t){let n=uu(e),r=t.steps.get(n);return r?(t.steps.delete(n),lu(r,t)):[]}function mu(e){let t=Kl(String(e.type??``))?Yl(e):Jl(e);return{...t,evidence:{...t.evidence,partial:!0}}}function hu(e){let t=[...e.steps.values()].map(mu);return e.steps.clear(),t}function gu(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:vl(e.media)})))}function _u(e,t){if(e.eventType===`sse_unparsed`)return[M(new T(`bad_response`,`Interactions stream row was not a JSON object`))];let n=_c(e);if(n)return[M(n)];let r=Pl(e);switch(e.event_type){case`step.start`:du(e,t);break;case`step.delta`:r.push(...fu(e,t));break;case`step.stop`:r.push(...pu(e,t));break;case`interaction.created`:{let n=q(e.interaction);n&&r.push(...vu(n,t));break}case`interaction.completed`:{let n=q(e.interaction);n&&r.push(...vu(n,t),...tu(n));break}}return r}function vu(e,t){let n=yl(t.response,nu(e));return t.response=n.known,n.event?[n.event]:[]}function yu(e,t){return gu(_u(e,t),t)}function bu(e,t){let n=(Array.isArray(e.steps)?e.steps:[]).flatMap(e=>{let n=q(e);return n?lu(n,t):[]});return gu([...vu(e,t),...n,...tu(e)],t)}function*xu(e,t){e.structured&&t.text&&(yield bl(t.text))}function Su(e){return!!e.speech}function Cu(e,t){if(!t.sawMedia){if(Su(e))return M(new T(`bad_response`,`speech audio was not returned by the model`));if(e.image)return M(new T(`bad_response`,`no image returned from image generation`))}}function wu(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 Tu=_({interactionId:o().min(1)}),Eu=_({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 Du(e,t){let n=t.history??[],r=e.options.persistViaInteractionId?t.state?.interactionId:void 0,i=Sc(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(ul(a)))),wroteTools:i.map(e=>e.id)}}function Ou(e,t,n){return e.flatMap(e=>{if(e.type!==`done`){let t=wu(e);return t?[t]:[]}let{interactionId:r,...i}=e;return t.done={...i,...n&&r?{state:{interactionId:r}}:{}},[]})}var ku=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:Eu,continuation:{version:1,schema:Tu,keyOptions:[`store`,`persistViaInteractionId`]},reasoning:Jc,error(e){let t=q(e.body);return vc(t?_c(t):null,e.status,`Gemini HTTP ${e.status}`)},create(e){return{async*complete(t){let{wire:n,body:r,wroteTools:i}=Du(e,t),a=t.stream!==!1,o=!!e.options.persistViaInteractionId,s={fold:iu()},c={stream:a,wroteTools:i,...a?{path:`/interactions?alt=sse`}:{}};for await(let t of e.send(r,c)){let e=_c(t);if(e)throw e;let n=a?yu(t,s.fold):bu(t,s.fold);if(yield*Ou(n,s,o),n.some(e=>e.type===`error`)){yield*Ou(hu(s.fold),s,o);return}}yield*Ou(hu(s.fold),s,o),yield*Ou([...xu(n,s.fold)],s,o);let l=Cu(n,s.fold);l&&(yield*Ou([l],s,o)),yield s.done??{type:`done`,stop:{kind:`stream_incomplete`}}}}}}),Au=`NON_BLOCKING`;function ju(e){return{name:e.name,description:e.description,behavior:Au,parametersJsonSchema:e.parameters??{type:`object`,properties:{}}}}function Mu(e){let t=[];for(let n of e.builtins)t.push(Tc(n));let n=(e.wireTools??[]).map(ju);return n.length>0&&t.push({functionDeclarations:n}),t}function Nu(e){let t={responseModalities:[`AUDIO`],temperature:e.temperature,maxOutputTokens:e.maxOutputTokens};e.live?.voice&&(t.speechConfig={voiceConfig:{prebuiltVoiceConfig:{voiceName:e.live.voice}}}),Rc(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 Pu(e){let{triggerTokens:t}=e,{targetTokens:n}=e.slidingWindow;return{...t===void 0?{}:{triggerTokens:t},slidingWindow:n===void 0?{}:{targetTokens:n}}}function Fu(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 Iu(e){if(e.sessionResumptionHandle)return{handle:e.sessionResumptionHandle};if(e.live?.sessionResumption)return{}}function Lu(e){return e.startsWith(`models/`)?e:`models/${e}`}function Ru(e,t){e?.transcription?.input&&(t.inputAudioTranscription={}),e?.transcription?.output&&(t.outputAudioTranscription={})}function zu(e){let t=e.live,n=t?.vad?Fu(t.vad):void 0,r=Mu(e),i=Iu(e),a=!!(e.history?.length||e.context?.length),o={model:Lu(e.apiId),generationConfig:Nu(e),systemInstruction:{parts:[{text:e.system}]},...r.length>0?{tools:r}:{},...i?{sessionResumption:i}:{},...t?.contextCompression?{contextWindowCompression:Pu(t.contextCompression)}:{},...a?{historyConfig:{initialHistoryInClientContent:!0}}:{},...n?{realtimeInputConfig:n}:{}};return Ru(t,o),{setup:o}}function Bu(e){if(Fi(e))throw new T(`unsupported`,`media references are not supported on geminiLive`);return e}function Vu(e){let t=Bu(e);return{mimeType:t.mimeType,data:t.data}}function Hu(e){return e.type===`text`?{text:e.text}:{inlineData:Vu(e)}}function Uu(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(Hu);return{role:`user`,parts:[{functionResponse:{...jc({id:e.tool_call_id,name:e.name}),response:{result:n},...r.length>0?{parts:r}:{}}}]}}function Wu(e){if(e.role===`tool`)return Uu(e);let t=e.role===`assistant`?`model`:`user`,n=K(e).map(Hu);for(let t of e.role===`assistant`?e.tool_calls??[]:[])n.push({functionCall:{id:t.id,name:t.function.name,args:Nc(t.function.arguments)}});return{role:t,parts:n}}function Gu(e=[],t=[]){return e.length===0&&t.length===0?null:{clientContent:{turns:[...e.map(Wu),...t.length?[{role:`user`,parts:t.map(e=>({text:e}))}]:[]],turnComplete:!0}}}function Ku(e){return{clientContent:{turns:[{role:`user`,parts:[{text:e}]}],turnComplete:!1}}}function qu(e){if(e.type===`text`)return{realtimeInput:{text:e.text}};let t=Bu(e),n={mimeType:t.mimeType,data:t.data};return{realtimeInput:t.type===`audio`?{audio:n}:{video:n}}}function Ju(e){let t=q(e)?.error;return typeof t==`string`?{error:t}:{result:e}}function Yu(e,t,n,r){return Xu([{id:e,name:t,output:n,parts:r}])}function Xu(e){return{toolResponse:{functionResponses:e.map(({id:e,name:t,output:n,parts:r})=>({id:e,name:t,response:Ju(n),...r?.length?{parts:r.filter(e=>e.type!==`text`).map(Hu)}:{}}))}}}function Zu(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 Qu(e){return Array.isArray(e)?e.flatMap(e=>{let t=q(e);return t?[t]:[]}):[]}function $u(e){let t=[],n=[],r=[];for(let i of Qu(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(Zu(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 ed(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 Qu(n.turns).flatMap($u);let r=q(e.toolResponse);return r?Qu(r.functionResponses).map(Zu):[]}function td(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:Rl(Ll(e.promptTokensDetails,`tokenCount`),Ll(e.responseTokensDetails,`tokenCount`))})}function nd(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 rd(){return{calls:new Map}}function id(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(...Pc({id:o,name:s,stepId:i,stepCallCount:a},r.args))}}function ad(e,t,n){let r=q(e.toolCallCancellation)?.ids;if(Array.isArray(r))for(let e of r){let r=typeof e==`string`?t.calls.get(e):void 0;typeof e!=`string`||!r?n.push(M(new T(`bad_response`,`Live cancelled a tool call it never issued: ${String(e)}`))):(t.calls.delete(e),n.push(Ds({name:r,callId:e},{phase:`cancel`})))}}function od(e,t){let n=q(e.voiceActivity);n&&t.push({type:`evidence`,evidence:{provider:`google`,kind:`voice_activity`,raw:n}})}function sd(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 cd(e,t){let n=q(e.goAway);if(!n)return;let r=sd(n.timeLeft);t.push({type:`session`,session:{kind:`closing_soon`,...r===void 0?{}:{timeLeftMs:r}}})}function ld(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:vl({mimeType:r,data:i})});let a=q(e.codeExecutionResult);a&&t.push(ud(a))}function ud(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 dd(e){let t=q(e)?.text;return typeof t==`string`&&t?t:void 0}function fd(e,t,n,r){let i=dd(e);i&&n.push({type:`evidence`,text:i,evidence:{provider:`google`,kind:t,...r?{interim:!0}:{}}})}function pd(e,t){t.push(...Il(e.groundingMetadata));let n=q(e.urlContextMetadata);n&&t.push({type:`evidence`,evidence:{provider:`google`,kind:`url_context`,raw:n}})}function md(e){let t=q(e.serverContent)?.interactionStatus;if(t===`IN_PROGRESS`||t===`IDLE`)return t}function hd(e,t){let n=md(e);n&&t.push({type:`session`,session:{kind:n===`IDLE`?`idle`:`working`}})}function gd(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`}}),fd(n.inputTranscription,`input_transcription`,t),fd(n.interimInputTranscription,`input_transcription`,t,!0),fd(n.outputTranscription,`output_transcription`,t);let r=q(n.modelTurn)?.parts;for(let e of Array.isArray(r)?r:[]){let n=q(e);n&&ld(n,t)}pd(n,t),n.turnComplete===!0&&t.push({type:`session`,session:{kind:`turn_complete`}})}function _d(e,t){let n=q(e.usageMetadata),r=n?td(n):void 0;r&&t.push({type:`tokens`,tokens:r})}function vd(e,t){if(!e||typeof e!=`object`)return[];let n=[];return cd(e,n),nd(e,n),id(e,t,n),ad(e,t,n),od(e,n),gd(e,n),hd(e,n),_d(e,n),n}var yd={1006:`network`,1007:`unsupported`,1008:`unsupported`,1011:`unavailable`,1013:`busy`},bd=/\bquota\b/i,xd=/\bAPI key (?:not valid|expired)\b/i;function Sd(e){if(bd.test(e))return`rate_limit`;if(xd.test(e))return`auth`}function Cd(e,t,n){return new T(Sd(t)??yd[e]??`unavailable`,`Gemini Live WebSocket closed during ${n} (${e}: ${t})`)}function wd(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 Td(e,t){if(t.some(e=>e.type===`done`&&e.interrupted===!0))return`abort`;let n=md(e);return n===`IDLE`?`complete`:n===`IN_PROGRESS`?`streaming`:q(e.serverContent)?.turnComplete===!0?`complete`:`streaming`}var Ed=_({liveHandle:o().min(1)}),Dd=1e3;function Od(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`):_c(e)??void 0}async function kd(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 Cd(1006,``,`setup`);let n=t.value;if(n.eventType===`ws_close`)throw Cd(Number(n.code),String(n.reason??``),`setup`);let r=Od(n,`setup`);if(r)throw r;if(n.setupComplete)return}}finally{clearTimeout(n)}}function Ad(e,t){let n=t.state?.liveHandle,r=t.history??[],i=Sc(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(zu(a)))),wroteTools:i.map(e=>e.id)}}function*jd(e,t,n){let r=[...e.filter(e=>e.type===`tokens`),...e.filter(e=>e.type!==`tokens`)];for(let e of r){let t=wu(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 Md(e,t,n,r){let i=t=>Pd(e,t),a=rd(),o=r,s,c;return{closeInfo:()=>c,async*events(){for(;;){let e=await t.next();if(e.done)return;let r=e.value;if(r.eventType===`ws_close`){n.signal?.throwIfAborted();let e=Number(r.code),t=String(r.reason??``);c={code:e,reason:t,...e===Dd?{}:{error:Cd(e,t,`session`)},...s?{warning:{...s.timeLeftMs===void 0?{}:{timeLeftMs:s.timeLeftMs},closedAfterMs:Math.round(performance.now()-s.atMs)}}:{}};return}let i=Od(r,`session`);if(i)throw i;if(r.setupComplete)continue;let l=vd(r,a),u=wd(l);u&&(s={...u,atMs:performance.now()});for(let e of l)e.type===`evidence`&&e.sessionResumptionHandle&&(o=e.sessionResumptionHandle);yield*jd(l,Td(r,l),o)}},sendText:e=>$(()=>i(qu({type:`text`,text:e}))),sendAudio:e=>$(()=>i(qu({type:`audio`,...e}))),sendVideo:e=>$(()=>i(qu({type:`video`,...e}))),sendContext:e=>$(()=>i(Ku(typeof e.server==`string`?e.server:JSON.stringify(e)))),sendToolResult:e=>$(()=>i(Yu(e.callId,e.name,e.text,e.parts))),close:t=>$(()=>e.close(Dd,t??`session-closed`))}}var Nd=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:Ed},create(e){return{async openSession(t){let{wire:n,setup:r,wroteTools:i}=Ad(e,t),a=await e.connect(r,{wroteTools:i}),o=a.frames()[Symbol.asyncIterator](),s=()=>a.close(Dd,`aborted`);e.signal?.addEventListener(`abort`,s,{once:!0});try{e.signal?.throwIfAborted(),await kd(o,e)}catch(t){throw e.signal?.removeEventListener(`abort`,s),a.close(Dd,`setup-failed`),t}let c=Gu(n.history,n.context);c&&Pd(a,c);for(let e of n.input)Pd(a,qu(e));return Md(a,o,e,n.sessionResumptionHandle)}}}});function $(e){try{return e(),Promise.resolve()}catch(e){return Promise.reject(e)}}function Pd(e,t){e.send(t,ed(t))}var Fd={input:.75,output:4.5,byModality:{input:{audio:3,image:1,video:1},output:{audio:12}}},Id={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":Fd,"gemini-3.8-live-extended-thinking":Fd,"gemini-3.1-flash-live-preview":Fd,"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}}},Ld=Wi({id:`gemini`,name:`Gemini`,description:`Google's models with an API key, from Google AI Studio.`,traceName:`gcp.gemini`,connection:_({host:zi.refine(e=>{let t=new URL(e);return t.pathname===`/`&&!t.search&&!t.hash},D(`protocol.endpoint_host`)).optional().describe(`The API host, by default https://generativelanguage.googleapis.com. Live connects to the same host over wss.`)}).default({}),key:o().trim().min(1),authorize:Vi(`x-goog-api-key`),prices:Id,check:{protocol:ku,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:ku,baseUrl:`${n}/v1beta`},{protocol:tc,baseUrl:`${n}/v1beta`},{protocol:Nd,baseUrl:`${r}/ws`,authorize:Hi(`key`)}]}}),Rd=new Set([`message`,`type`,`param`,`code`]);function zd(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])=>!Rd.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 Bd(e,t){let n=zd(e.body),r=`${t} HTTP ${String(e.status)}`;return new T(We(e.status),n?`${r}: ${n}`:r)}function Vd(e){if(Fi(e))throw new T(`unsupported`,`media references are not supported on openAi`)}function Hd(e){let t=`mp3`;return e.mimeType.includes(`wav`)&&(t=`wav`),{type:`input_audio`,input_audio:{data:e.data,format:t}}}function Ud(e){return e.every(e=>e.type===`text`)?e.map(e=>e.type===`text`?e.text:``).filter(Boolean).join(`
|
|
4
|
-
`):e.map(e=>e.type===`text`?{type:`text`,text:e.text}:(Vd(e),e.type===`image`?{type:`image_url`,image_url:{url:`data:${e.mimeType};base64,${e.data}`}}:e.type===`audio`?Hd(e):{type:`file`,file:{filename
|
|
4
|
+
`):e.map(e=>e.type===`text`?{type:`text`,text:e.text}:(Vd(e),e.type===`image`?{type:`image_url`,image_url:{url:`data:${e.mimeType};base64,${e.data}`}}:e.type===`audio`?Hd(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 Wd(e){let t=Ud(K(e));if(e.role===`tool`)return{role:`tool`,...jc({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 Gd=new Set([`text`,`image`]);function Kd(e,t){let n=t?.includeSystem!==!1,r=[];n&&e.system&&r.push({role:`system`,content:e.system});let i=Ac(e.history??[]);for(let e of Oc(i,Gd))r.push(Wd(e));return e.input.length>0&&r.push({role:`user`,content:Ud(e.input)}),r}function qd(e){if(e&&e.length!==0)return e.map(e=>({type:`function`,function:{name:e.name,description:e.description,parameters:e.parameters}}))}function Jd(e){return e.replace(/[^A-Za-z0-9_-]/g,`_`).slice(0,64)}function Yd(e){if(e)return{type:`json_schema`,json_schema:{name:Jd(e.id),strict:!0,schema:e.jsonSchema}}}function Xd(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 Zd(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 Qd(e,t){let n=Zd(e,{audio_tokens:`audio`,video_tokens:`video`}),r=Zd(t,{image_tokens:`image`,audio_tokens:`audio`});if(n||r)return{...n?{input:n}:{},...r?{output:r}:{}}}function $d(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:Xd(t),byModality:Qd(n,r)})}function ef(e){let t=J(e.id),n=J(e.model);if(t||n)return{...t?{id:t}:{},...n?{model:n}:{}}}function tf(e){return e.flatMap(e=>wu(e)??[])}function nf(e,t){let n=t.stream!==!1,r=qd(t.wireTools),i=Yd(t.structured),a={model:e.apiId,messages:Kd(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 rf(e,t){let n=q(e.error);if(!n)return;let r=typeof n.code==`number`?n.code:502,i=We(r);throw new T(t.response&&i===`unsupported`?`unavailable`:i,zd(e)??JSON.stringify(n))}function af(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 of(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 sf(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(...af(e,t)),of(e,t),r}function cf(e,t,n,r){rf(e,t);let i=[],a=yl(t.response,ef(e));t.response=a.known,a.event&&i.push(a.event);let o=t.tokens?void 0:$d(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(...sf(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(...tf(xl(e)));return i}function lf(e,t){let n=[];for(let[t,r]of e.calls)n.push(...tf(Pc({...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=tf([bl(e.text)]);if(n.push(...t),t[0]?.type===`error`)return n}return n.push({type:`done`,stop:r}),n}async function*uf(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=yl(a,ef(t));a=e.known,e.event&&(yield e.event);let n=typeof t.mime_type==`string`?t.mime_type:``,r=typeof t.data==`string`?lt(t.data):new Uint8Array;if(!r.length)throw new T(`bad_response`,`no audio returned from speech`);let i=gl(n);yield{type:`media`,media:i?{mimeType:`audio/wav`,data:St(_l(r,i))}:{mimeType:Ir(n)||`application/octet-stream`,data:t.data}},yield{type:`done`,stop:{kind:`completed`}}}}var df=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=>Bd(e,`Chat Completions`),create(e){return{async*complete(t){if(e.profileType===`speech`){yield*uf(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(nf(e,t),{stream:n}))yield*cf(i,r,t,n);yield*lf(r,t)}}}}),ff=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:df,baseUrl:e.baseUrl},{protocol:ic,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()}}]}),pf=v().int().nonnegative(),mf=w({model:o().min(1),answers:i(o(),g()),usage:w({input_tokens:pf,output_tokens:pf,cost:v().nonnegative().optional()}).optional().catch(void 0)}),hf=_({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.`)}),gf=`TypeSafe-Danger-Zone-Images`,_f=`TypeSafe-Danger-Zone-Long-Context`,vf=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:hf,create(e){return{async decide(t){let n=Object.values(t.questions).some(({type:e})=>e===`box`),r=n||t.assets&&Object.keys(t.assets).length>0;if(r&&!e.options.images)throw new T(`unsupported`,D(`provider.decision_images_off`));if(n&&/^jev-1\.13(\.|$)/.test(e.apiId))throw new T(`unsupported`,D(`provider.decision_box_model`,{apiId:e.apiId}));let i={};r&&(i[gf]=`true`),e.options.longContext&&(i[_f]=`true`);let a=I.parse({model:e.apiId,state:t.state,questions:t.questions,...t.assets&&Object.keys(t.assets).length?{assets:xf(t.assets)}:{}});return await yf(`systemOne`,e.send(a,{stream:!1,headers:i}))}}}});async function yf(e,t){for await(let n of t){let t=mf.safeParse(n);if(!t.success)throw new T(`bad_response`,D(`protocol.reply_shape`,{protocol:e,issues:he(t.error)}));let{model:r,answers:i,usage:a}=t.data;return{model:r,answers:i,...a?{usage:{inputTokens:a.input_tokens,outputTokens:a.output_tokens,...a.cost===void 0?{}:{costUsd:a.cost}}}:{}}}throw new T(`bad_response`,D(`provider.decision_failed`))}var bf={"image/png":`png`,"image/jpeg":`jpeg`};function xf(e){return Object.fromEntries(Object.entries(e).map(([e,{mimeType:t,data:n}])=>[e,{type:`image`,format:bf[t],data_base64:n}]))}var Sf=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:Cf(t.state,n),questions:Object.fromEntries(Object.entries(t.questions).map(([e,t])=>[e,{...t,instructions:Cf(t.instructions,n),...`criteria`in t&&t.criteria!==void 0?{criteria:Cf(t.criteria,n)}:{}}]))});return yf(`openRouterDecisions`,e.send(r,{stream:!1}))}}}});function Cf(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:wf(e.asset));return r.length===1?r[0]:r}return Array.isArray(e)?e.map(e=>Cf(e,t)):typeof e==`object`&&e?Object.fromEntries(Object.entries(e).map(([e,n])=>[e,Cf(n,t)])):e}function wf({mimeType:e,data:t}){return{type:`image_url`,image_url:{url:`data:${e};base64,${t}`}}}var Tf=`openrouter:image_generation`;function Ef(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 Df(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 Of(e){return(Array.isArray(e.images)?e.images:[]).flatMap(e=>{let t=Df(q(q(e)?.image_url)?.url);return t?[t]:[]})}function kf(e){return e.filter(e=>e.type===`text`).map(e=>e.type===`text`?e.text:``).join(`
|
|
5
5
|
`).trim()}function Af(e){let t=e.toLowerCase().replace(/^image\//,``);return t===`jpg`?`jpeg`:t===`png`||t===`jpeg`||t===`webp`?t:`png`}var jf=/^https?:\/\//i;function Mf(e){return{type:`image_url`,image_url:{url:Fi(e)?e.uri:`data:${e.mimeType};base64,${e.data}`}}}function Nf(e){let t=[];for(let n of e)if(n.type!==`text`){if(n.type!==`image`)throw new T(`unsupported`,`${n.mimeType} input is not supported on /images, which takes image references only`);if(Fi(n)&&!jf.test(n.uri))throw new T(`unsupported`,`only http(s) media references are supported on /images`);t.push(Mf(n))}return t}function Pf(e,t){t.aspectRatio&&(e.aspect_ratio=t.aspectRatio),t.resolution&&(e.resolution=t.resolution),t.mimeType&&(e.output_format=Af(t.mimeType)),t.quality&&(e.quality=t.quality),t.background&&(e.background=t.background),t.n!==void 0&&(e.n=t.n),t.seed!==void 0&&(e.seed=t.seed),t.outputCompression!==void 0&&(e.output_compression=t.outputCompression)}function Ff(e){if(!e.image)throw Error(`buildImagesPayload requires req.image`);let t={model:e.apiId,prompt:kf(e.input)};Pf(t,e.image);let n=Nf(e.input);return n.length>0&&(t.input_references=n),e.stream===!1&&(t.stream=!1),t}function If(e){let t={};e.mimeType&&(t.output_format=Af(e.mimeType)),e.aspectRatio&&(t.aspect_ratio=e.aspectRatio),e.resolution&&(t.resolution=e.resolution),e.quality&&(t.quality=e.quality),e.background&&(t.background=e.background),e.outputCompression!==void 0&&(t.output_compression=e.outputCompression);for(let[t,n]of[[`n`,e.n],[`seed`,e.seed]])if(n!==void 0)throw new T(`unsupported`,`image.${t} is not supported with image.includeText`);return t}function Lf(e){return JSON.parse(JSON.stringify(e))}function Rf(e){let t=$d(e.usage);return t?[{type:`tokens`,tokens:t}]:[]}function zf(){return new T(`bad_response`,`no image returned from image generation`)}async function*Bf(e,t){let n=Lf(Ff({...t,apiId:e.apiId}));for await(let t of e.send(n,{stream:!1})){let e=Ef(t);if(!e.length)throw zf();for(let t of e)yield{type:`media`,media:t};yield*Rf(t),yield{type:`done`,stop:{kind:`completed`}}}}async function*Vf(e,t,n){let r=Lf({model:e.apiId,stream:!1,provider:{require_parameters:!0},messages:Kd(t),temperature:t.temperature,max_tokens:t.maxOutputTokens,...t.thinking?{reasoning:{effort:t.thinking}}:{},tools:[{type:Tf,parameters:If(n)}]});for await(let t of e.send(r,{stream:!1,path:`/chat/completions`})){let e=q(Array.isArray(t.choices)?t.choices[0]:void 0),n=q(e?.message),r=J(n?.content);r&&(yield{type:`text`,text:r});let i=n?Of(n):[];if(!i.length)throw zf();for(let e of i)yield{type:`media`,media:e};yield*Rf(t),yield{type:`done`,stop:ca(typeof e?.finish_reason==`string`?e.finish_reason:void 0,typeof e?.native_finish_reason==`string`?e.native_finish_reason:void 0)}}}var Hf=W({id:`openRouterImages`,name:`OpenRouter Images`,description:`OpenRouter's image generation, with or without text beside the picture.`,endpoints:{image:`/images`},operationNames:{image:`generate_content`},options:_({}),create(e){return{complete(t){let n=t.image;if(!n)throw new T(`request`,`missing image response format`);if(!kf(t.input))throw new T(`request`,`empty text for image generation`);return n.includeText?Vf(e,t,n):Bf(e,t)}}}});function Uf(e,t){let n=``;for(let r of Array.isArray(e.choices)?e.choices:[]){if(!E(r))continue;let e=E(r.delta)?r.delta:E(r.message)?r.message:void 0;if(e){typeof e.reasoning==`string`?n+=e.reasoning:typeof e.reasoning_content==`string`&&(n+=e.reasoning_content);for(let n of Array.isArray(e.reasoning_details)?e.reasoning_details:[]){let e=I.parse(n),r=JSON.stringify([e.index??e.id??t.size,e.type]),i=t.get(r),a={...i,...e};for(let t of[`text`,`summary`,`data`])i&&typeof i[t]==`string`&&typeof e[t]==`string`&&(a[t]=i[t]+e[t]);t.set(r,a)}}}return n}var Wf=_({mode:y(et).describe("What is cached: the whole request (`automatic`) or the system instruction only (`system`)."),ttl:y(rt).optional().describe(`How long the cache is kept. Absent: the upstream default.`)}).describe(`Prompt caching, for models that support it.`),Gf=_({only:b(o()).optional().describe("Upstream endpoints to allow, by slug, such as `gmicloud/fp8`."),order:b(o()).optional().describe(`Upstream endpoints to try first, in order.`),ignore:b(o()).optional().describe(`Upstream endpoints to skip.`),allow_fallbacks:S().optional().describe(`Whether another upstream may answer when the listed ones cannot.`),require_parameters:S().optional().describe(`Whether every upstream must support every supplied parameter. Unset: on.`),data_collection:y([`allow`,`deny`]).optional().describe(`Whether an upstream that may store and train on data can answer.`),zdr:S().optional().describe(`Use only endpoints with zero data retention.`),enforce_distillable_text:S().optional().describe(`Use only models whose authors allow text distillation.`),quantizations:b(o()).optional().describe("Quantization levels to allow, such as `fp8`."),sort:a([o(),_({by:o(),partition:o().optional()})]).optional().describe("What to order upstreams by: `price`, `throughput` or `latency`."),preferred_min_throughput:a([v(),I]).optional().describe(`Tokens per second below which an upstream is tried later.`),preferred_max_latency:a([v(),I]).optional().describe(`Seconds above which an upstream is tried later.`),max_price:_({prompt:v().optional().describe(`The most to pay per million input tokens.`),completion:v().optional().describe(`The most to pay per million output tokens.`),request:v().optional().describe(`The most to pay per request.`),image:v().optional().describe(`The most to pay per image.`)}).optional().describe(`The prices above which an upstream is refused.`)}).describe(`Which upstreams OpenRouter may route to. Absent: its own choice.`),Kf=_({details:b(I),content:o().optional()});function qf(e){return e.ttl?{type:`ephemeral`,ttl:e.ttl}:{type:`ephemeral`}}function Jf(e){let t=q(e)?.tool_calls;return Array.isArray(t)?t.map(e=>String(q(e)?.id)):[]}function Yf(e,t){for(let n of e){let e=Jf(n);if(n.role!==`assistant`||!e.length)continue;let r=(t.find(t=>t.role===`assistant`&&JSON.stringify((t.tool_calls??[]).map(e=>e.id))===JSON.stringify(e))?.reasoning??[]).map(e=>Kf.safeParse(e.data)).find(e=>e.success);r?.success&&(n.reasoning_details=r.data.details,r.data.content&&(n.reasoning=r.data.content))}}function Xf(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`):[]}function Zf(e){let t=e=>[e?.citations,q(e?.providerMetadata)?.citations,q(e?.provider_metadata)?.citations],n=q(e.openrouter),r=Array.isArray(e.choices)?e.choices.map(q):[];return[...t(e),...t(n),...t(q(n?.providerMetadata)),...t(q(n?.provider_metadata)),...r.flatMap(e=>[...t(q(e?.message)),...t(q(e?.delta))])].flatMap(Xf)}function Qf(e){let t=Array.isArray(e.choices)?e.choices.map(q):[];return[e.annotations,q(e.openrouter)?.annotations,...t.flatMap(e=>[q(e?.message)?.annotations,q(e?.delta)?.annotations])].flatMap(e=>Array.isArray(e)?e:[]).filter(e=>q(e)?.type!==`url_citation`)}function $f(e){return(Array.isArray(e.choices)?e.choices:[]).map(e=>q(q(e)?.delta)?.thinking).filter(e=>typeof e==`string`).join(``)}var ep=Ci(df,{id:`openRouterOpenAi`,name:`OpenRouter Chat Completions`,description:`Chat Completions with OpenRouter's caching, routing, web search, citations and reasoning.`,options:_({cache:Wf.optional(),provider:Gf.optional()}),reasoning:Kf,body(e,t){if(t.profileType!==`text`)return{body:e};let n={...e,provider:{require_parameters:!0,...t.options.provider}};n.reasoning_effort!==void 0&&(n.reasoning={effort:n.reasoning_effort},delete n.reasoning_effort);let r=Array.isArray(n.messages)?n.messages:[],i=t.options.cache;i?.mode===`automatic`&&(n.cache_control=qf(i)),i?.mode===`system`&&r[0]?.role===`system`&&(r[0]={...r[0],content:[{type:`text`,text:r[0].content??``,cache_control:qf(i)}]}),Yf(r,t.request?.history??[]),t.request?.sessionId&&(n.session_id=t.request.sessionId);let a=t.builtInTools.includes(`webSearch`);return a&&(n.web_search_options={}),{body:{...n,messages:r},wroteTools:a?[`webSearch`]:[]}},read(e){let t=new Map,n=new Set,r=new Set,i=``;return{row(a){i+=Uf(a,t);let o=[],s=$f(a);s&&e.request?.summaries!==`none`&&o.push({type:`thought`,text:s});let c=Zf(a).filter(e=>!n.has(e)&&n.add(e)).map(e=>({title:e,uri:e,type:`web`}));c.length&&o.push({type:`citation`,sources:c});let l=Qf(a).filter(e=>{let t=JSON.stringify(e);return!r.has(t)&&r.add(t)});return l.length&&o.push({type:`evidence`,evidence:{provider:`openrouter`,kind:`provider_step`,step:`annotations`,raw:{annotations:l}}}),{events:o}},finish(){return!t.size&&!i?{}:{events:[{type:`reasoning`,data:{details:[...t.values()],...i?{content:i}:{}}}]}}}}}),tp=_({provider:_({zdr:S().optional().describe(`Use only endpoints with zero data retention.`),data_collection:y([`allow`,`deny`]).optional().describe(`Whether an upstream that may store and train on data can answer.`)}).optional().describe(`Which upstreams OpenRouter may route to. Absent: its own choice.`)}),np={"audio/wav":`wav`,"audio/x-wav":`wav`,"audio/wave":`wav`,"audio/mpeg":`mp3`,"audio/mp3":`mp3`,"audio/mp4":`m4a`,"audio/m4a":`m4a`,"audio/x-m4a":`m4a`,"audio/aac":`aac`,"audio/ogg":`ogg`,"audio/opus":`ogg`,"audio/flac":`flac`,"audio/webm":`webm`};function rp(e){let t=e.input.filter(e=>e.type===`audio`),[n]=t;if(t.length!==1||!n||!(`data`in n)||n.data===void 0)throw new T(`request`,`a transcription takes exactly one inline clip`);let r=np[n.mimeType];if(!r)throw new T(`request`,`OpenRouter cannot transcribe ${n.mimeType} audio`);return{data:n.data,format:r}}async function*ip(e,t){let n=tp.parse(e.options??{}),r={model:e.apiId,input_audio:rp(t),...n.provider?{provider:n.provider}:{}};for await(let t of e.send(r,{stream:!1})){if(typeof t.text!=`string`)throw new T(`bad_response`,`no text returned from transcription`);let e=ef(t);e&&(yield{type:`response`,response:e});let n=$d(t.usage);n&&(yield{type:`tokens`,tokens:n}),t.text&&(yield{type:`text`,text:t.text}),yield{type:`done`,stop:{kind:`completed`}}}}var ap=W({id:`openRouterTranscriptions`,name:`OpenRouter Transcriptions`,description:`OpenRouter speech-to-text models: a voice clip in, what was said out.`,endpoints:{transcription:`/audio/transcriptions`},operationNames:{transcription:`transcribe`},options:tp,async*framing(e){let t=e.headers.get(`x-generation-id`)?.trim();yield{...await e.json(),...t?{id:t}:{}}},create(e){return{complete:t=>ip(e,t)}}}),op=Wi({id:`openrouter`,name:`OpenRouter`,description:`Many labs' models behind one key.`,connection:_({baseUrl:zi.optional().describe(`The API, by default https://openrouter.ai/api/v1.`),decisionUrl:zi.optional().describe(`The decision API, by default https://openrouter.ai/api/alpha/decisions.`),siteUrl:o().trim().min(1).optional().describe(`Sent as HTTP-Referer, for OpenRouter rankings.`),siteName:o().trim().min(1).optional().describe(`Sent as X-Title, for OpenRouter rankings.`)}).default({}),key:o().trim().min(1),authorize:Bi(),check:{protocol:ep,path:`/key`},serves(e){let t=e.baseUrl??`https://openrouter.ai/api/v1`,n={};e.siteUrl&&(n[`HTTP-Referer`]=e.siteUrl),e.siteName&&(n[`X-Title`]=e.siteName);let r=e.decisionUrl??`https://openrouter.ai/api/alpha/decisions`;return[{protocol:ep,baseUrl:t,headers:n},{protocol:lc,baseUrl:t,headers:n},{protocol:Hf,baseUrl:t,headers:n},{protocol:ap,baseUrl:t,headers:n},{protocol:Sf,baseUrl:r,url:()=>r,headers:n}]}}),sp=Wi({id:`typesafe`,name:`TypeSafe`,description:`System One decisions, at TypeSafe's own API.`,connection:_({baseUrl:zi.optional().describe(`The API, by default https://api.typesafe.ai/v1.`)}).default({}),key:o().trim().min(1),authorize:Bi(),prices:{checked:`2026-10-19`,models:{"jev-*":{input:.042,output:0}}},check:{protocol:vf,path:`/models`},serves:e=>[{protocol:vf,baseUrl:e.baseUrl??`https://api.typesafe.ai/v1`}]}),cp=`https://generativelanguage.googleapis.com/v1beta/models`,lp=`Zephyr.Puck.Charon.Kore.Fenrir.Leda.Orus.Aoede.Callirrhoe.Autonoe.Enceladus.Iapetus.Umbriel.Algieba.Despina.Erinome.Algenib.Rasalgethi.Laomedeia.Achernar.Alnilam.Schedar.Gacrux.Pulcherrima.Achird.Zubenelgenubi.Vindemiatrix.Sadachbia.Sadaltager.Sulafat`.split(`.`),up=[`minimal`,`low`,`medium`,`high`],dp=[`pcm`],fp=[`1:1`,`3:2`,`2:3`,`3:4`,`4:3`,`4:5`,`5:4`,`9:16`,`16:9`,`21:9`],pp=[`1K`,`2K`,`4K`],mp=[`image/png`,`image/jpeg`],hp=[{type:`builtin`,name:`googleSearch`,description:`Google Search grounding`,category:`grounding`,access:`read-only`,paths:[`*`],loadTier:`T0`,permission:`auto`},{type:`builtin`,name:`googleMaps`,description:`Google Maps grounding`,category:`grounding`,access:`read-only`,paths:[`*`],loadTier:`T0`,permission:`auto`,conflictsWith:[`googleSearch`,`urlContext`]},{type:`builtin`,name:`urlContext`,description:`Fetch URL context`,category:`grounding`,access:`read-only`,paths:[`*`],loadTier:`T0`,permission:`auto`},{type:`builtin`,name:`codeExecution`,description:`Google code execution`,category:`grounding`,access:`read-only`,paths:[`*`],loadTier:`T0`,permission:`auto`}],gp=[{type:`builtin`,name:`webSearch`,description:`OpenRouter web search`,category:`grounding`,access:`read-only`,paths:[`*`],loadTier:`T0`,permission:`auto`}],_p=`local`;function vp(e,t){return!t&&e===`local`}function yp(e=`http://localhost:11434`){return`${e.replace(/\/$/,``)}/v1`}var bp=[{id:`gemini`,definition:`gemini`},{id:`openrouter`,definition:`openrouter`},{id:_p,definition:`local`,connection:{baseUrl:yp()}},{id:`typesafe`,definition:`typesafe`}],xp={gemini:{provider:Ld,factory:`geminiProvider`},openrouter:{provider:op,factory:`openRouterProvider`},local:{provider:ff,factory:`localProvider`},typesafe:{provider:sp,factory:`typesafeProvider`}};function Sp(e){return e===void 0?void 0:xp[e]?.provider}function Cp(){return Object.keys(xp)}function wp(e){return Object.keys(xp).find(t=>xp[t]?.factory===e)}function Tp(e){return xp[e]?.factory}function Ep(e,t){return e.find(e=>e.id===t)?.definition}function Dp(e){return{id:e.id,...e.connection===void 0?{}:{connection:e.connection},...e.keySlot===void 0?{}:{keySlot:e.keySlot},...e.fallbackKeySlot===void 0?{}:{fallbackKeySlot:e.fallbackKeySlot}}}function Op(e,t,n=Sp(t.definition),r=`register`){if(!n)throw Error(`The studio does not hold the provider definition '${t.definition}'.`);return e[r](n,Dp(t))}function kp(e){let t=Sp(e);if(!t)return;if(!t.connection)return[];let r=n(t.connection,{io:`input`});return Object.entries(r.properties??{}).map(([e,t])=>({name:e,required:r.required?.includes(e)??!1,url:t.format===`uri`,...t.description?{description:t.description}:{}}))}function Ap(e){let t=Sp(e);return t===void 0||t.key!==void 0}function jp(e){let t=[];e.id.trim()||t.push({field:`id`,message:`Provider id is required.`});let n=Sp(e.definition),r=e.connection??{},i=n?.connection?.safeParse(r);for(let e of i?.error?.issues??[]){if(e.code===`unrecognized_keys`){for(let n of e.keys)t.push({field:`connection.${n}`,message:`This provider takes no '${n}'.`});continue}let n=e.path[0];if(typeof n!=`string`){t.push({message:e.message});continue}let i=n in r?e.message:`${n} is required.`;t.push({field:`connection.${n}`,message:i})}for(let n of[`keySlot`,`fallbackKeySlot`]){let r=e[n];r!==void 0&&!Ti.safeParse(r).success&&t.push({field:n,message:`A key slot is 1 to 32 letters, digits, hyphens, or underscores.`})}return e.keySlot&&e.keySlot===e.fallbackKeySlot&&t.push({field:`fallbackKeySlot`,message:D(`provider.fallback_slot`)}),(e.keySlot||e.fallbackKeySlot)&&n&&!n.key&&t.push({field:`keySlot`,message:D(`protocol.no_key`,{provider:e.id})}),t}function Mp(e,t){return ki(e.find(e=>e.id===t.provider)??{},{...t.keySlot?{keySlot:t.keySlot}:{},...t.fallbackKeySlot?{fallbackKeySlot:t.fallbackKeySlot}:{}})}function Np(e,t){let n=Sp(e.definition);if(!n)return;let r;try{r=Op(Ki(),e,n)}catch{return[]}return r.serves.map(e=>e.protocol).filter(e=>t===void 0||e.endpoints[t]!==void 0)}function Pp(e,t,n){if(!e)return!1;let r=Np(e,t);return r===void 0?!0:n===void 0?r.length>0:r.some(e=>e.id===n)}function Fp(e,t,n){if(!Ip(t))throw Error(`Cannot create a model route without a profile type.`);return{profileType:t,protocol:n.protocol,provider:n.provider,definition:Ep(e,n.provider),apiId:n.apiId,decision:t===`decision`}}function Ip(e){return[`text`,`image`,`speech`,`transcription`,`live`,`decision`,`embedding`].includes(e)}function Lp(e,t){let r=Rp(n(e.options,{io:`input`,unrepresentable:`any`}),``,!0),i=t?e.refusedOptions?.(t.apiId.trim())??[]:[];return r.filter(e=>{let n=e.path.split(`.`)[0]??e.path;return!i.includes(n)||t?.options[n]!==void 0})}function Rp(e,t,n){return Object.entries(e.properties??{}).flatMap(([r,i])=>{let a=t?`${t}.${r}`:r,o=n&&(e.required?.includes(r)??!1);if(i.type===`object`&&i.properties)return Rp(i,a,o);let s={path:a,label:zp(r),required:o,...i.description?{description:i.description}:{}},c=i.anyOf?.filter(e=>typeof e.const==`string`||typeof e.const==`number`),l=c?.map(e=>e.const);if(i.enum?.every(e=>typeof e==`string`))return[{...s,kind:`choice`,choices:i.enum.map(e=>({value:e}))}];if(l&&l.length===i.anyOf?.length&&l.length>0){let e=l.every(e=>typeof e==`number`);if(e||l.every(e=>typeof e==`string`))return[{...s,kind:`choice`,choices:(c??[]).map(e=>({value:String(e.const),...e.title?{label:e.title}:{},...e.description?{description:e.description}:{}})),...e?{choiceType:`number`}:{}}]}return i.type===`boolean`?[{...s,kind:`boolean`}]:i.type===`array`&&i.items?.type===`string`?[{...s,kind:`names`}]:i.type===`string`?[{...s,kind:`text`}]:i.type===`number`||i.type===`integer`?[{...s,kind:`number`}]:[]})}function zp(e){let t=e.replace(/([a-z0-9])([A-Z])/g,`$1 $2`).replace(/_/g,` `).toLowerCase();return t.charAt(0).toUpperCase()+t.slice(1)}function Bp(e,t){return t.split(`.`).reduce((e,t)=>e&&typeof e==`object`&&!Array.isArray(e)?e[t]:void 0,e)}function Vp(e,t,n){let[r=``,...i]=t.split(`.`),{[r]:a,...o}=e,s=i.length?Vp(a&&typeof a==`object`&&!Array.isArray(a)?a:{},i.join(`.`),n):n;return s===void 0||typeof s==`object`&&s&&!Array.isArray(s)&&!Object.keys(s).length?o:{...o,[r]:s}}var Hp=`studio`,Up={"observability.writeTo":Hp};function Wp(e){return Object.entries(Up).reduce((e,[t,n])=>Gp(e,t.split(`.`),n),e)}function Gp(e,[t,...n],r){if(t===void 0||!Object.hasOwn(e,t))return e;let i=e[t];if(!n.length)return i===r?Object.fromEntries(Object.entries(e).filter(([e])=>e!==t)):e;if(typeof i!=`object`||!i||Array.isArray(i))return e;let a=Gp(i,n,r);return a===i?e:Object.fromEntries(Object.entries(e).flatMap(([e,n])=>e===t?Object.keys(a).length?[[e,a]]:[]:[[e,n]]))}var Kp=new Set(hp.map(e=>e.name));function qp(e){return e.protocol===ku.id||e.protocol===Nd.id}function Jp(e){return e.protocol===ep.id||e.protocol===Hf.id}function Yp(e){return Kp.has(e)}function Xp(e,t,n){return n.mode===`demo`?n.keys.runs(e,t?.definition):Pp(t,e)}var Zp={text:`fast`,image:`image`,speech:`voice`,transcription:`transcription`,live:`live`,decision:`decision`,embedding:`embedding`};function Qp(e,t){let n=t?.(e)??{...$p(e===`decision`?`typesafe`:`gemini`,e),apiId:``};return{modelId:Zp[e],...n}}function $p(e,t){let n=bp.find(t=>t.id===e),r=n&&Np(n,t)?.[0];if(!r)throw Error(`The studio provider '${e}' serves no ${t} agents.`);return{protocol:r.id,provider:e}}function em(e,t){return t.mode===`demo`?t.keys.violation(e):t.mode===`local`&&e.provider!==`local`?{field:`provider`,message:`Local runs require local models. Switch the model provider to Local.`}:null}var tm=5,nm=100,rm=120;function im(e){let t=Array.isArray(e.type)?e.type.find(e=>e!==`null`):e.type;return t===`string`||t===`number`||t===`integer`||t===`boolean`||t===`array`?t:t===`object`||j(e.properties)?`object`:Array.isArray(e.enum)?`string`:`unknown`}function am(e){return j(e.items)?e.items:void 0}function om(e){let t=e?.enum;return Array.isArray(t)&&t.length>0&&t.every(e=>typeof e==`string`)?t:void 0}function sm(e,t){let n=e[t];return typeof n==`number`&&Number.isFinite(n)?n:void 0}function cm(e,t){let n=sm(e,`minimum`),r=sm(e,`maximum`);return t&&n!==void 0&&r!==void 0&&r>n&&r-n<=nm?{kind:`range`,min:n,max:r}:{kind:`number`,isInteger:t,...n===void 0?{}:{min:n},...r===void 0?{}:{max:r}}}function lm(e){if(e.format===`date`)return{kind:`date`};let t=sm(e,`maxLength`);return{kind:`text`,isLong:t!==void 0&&t>rm,type:e.format===`email`?`email`:`text`}}function um(e){let t=am(e),n=om(t);if(n)return{kind:`choices`,options:n};let r=t?im(t):`unknown`;return r===`string`||r===`number`||r===`integer`?{kind:`words`}:t&&r===`object`?{kind:`rows`,item:t}:{kind:`json`}}function dm(e){let t=om(e);if(t)return{kind:`choice`,options:t,isMenu:t.length>tm};switch(im(e)){case`boolean`:return{kind:`switch`};case`number`:return cm(e,!1);case`integer`:return cm(e,!0);case`string`:return lm(e);case`array`:return um(e);case`object`:return j(e.properties)?{kind:`group`,schema:e}:{kind:`json`};default:return{kind:`json`}}}function fm(e){return new Set(Array.isArray(e.required)?e.required.filter(e=>typeof e==`string`):[])}function pm(e){let t=j(e.properties)?e.properties:{},n=fm(e);return Object.entries(t).flatMap(([e,t])=>j(t)?[{key:e,label:typeof t.title==`string`&&t.title?t.title:it(e),...typeof t.description==`string`&&t.description?{description:t.description}:{},isRequired:n.has(e),control:dm(t)}]:[])}function mm(e){if(Array.isArray(e.examples)&&e.examples.length)return{value:e.examples[0]};if(`default`in e)return{value:e.default};if(`const`in e)return{value:e.const};if(Array.isArray(e.enum)&&e.enum.length)return{value:e.enum[0]}}function hm(e){let t=mm(e);if(t)return t.value;switch(im(e)){case`number`:case`integer`:return sm(e,`minimum`)??1;case`boolean`:return!0;case`array`:return[];case`object`:return gm(e);case`string`:case`unknown`:return`example`}}function gm(e){let t=j(e.properties)?e.properties:{},n=new Set(fm(e)),r={};for(let[e,i]of Object.entries(t))j(i)&&(n.has(e)?r[e]=hm(i):Array.isArray(i.examples)&&i.examples.length&&(r[e]=i.examples[0]));return r}function _m(e){return gm(e)}function vm(e,t,n){let r={...e};return n===void 0||n===``?delete r[t]:r[t]=n,r}function ym(e,t,n=``){return j(t)?pm(e).flatMap(e=>{let r=t[e.key],i=n?`${n} › ${e.label}`:e.label;return r==null||r===``?e.isRequired?[i]:[]:e.control.kind===`group`?ym(e.control.schema,r,i):[]}):[]}var bm=`{
|
|
6
6
|
"type": "object",
|
|
7
7
|
"properties": {
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{C as e,Kt as t,M as n,Qt as r,Tn as i,bn as a,h as o,j as s,n as c,p as l,t as u,y as d,z as ee}from"./tool-schema-
|
|
1
|
+
import{C as e,Kt as t,M as n,Qt as r,Tn as i,bn as a,h as o,j as s,n as c,p as l,t as u,y as d,z as ee}from"./tool-schema-BHHcOFff.js";import{An as te,Cn as ne,Hn as re,Nn as f,Pn as ie,Sn as ae,Wn as oe,an as se,br as p,gr as m,pn as h,yn as g}from"./shaped-data-BRffby3g.js";import{a as _,r as v}from"./live-ingress-OuSlQ6q7.js";var ce=[{id:`identity`,profilePath:`identity`,role:`root`,optional:!1,editor:`structural`,label:`Identity`,ownsFields:[`profile.id`,`profile.type`]},{id:`models`,profilePath:`models`,role:`spine`,optional:!1,editor:`structural`,label:`Models`,ownsFields:[`profile.defaultModel`,`profile.allowModelSelect`,`profile.maxSteps`,`providerContinuation`]},{id:`modelBinding`,profilePath:`models.*`,role:`branch`,parent:`models`,optional:!1,editor:`structural`,label:`Model binding`},{id:`decision`,profilePath:`decision`,role:`spine`,optional:!1,editor:`structural`,label:`Decision`,ownsFields:[`inputs`]},{id:`image`,profilePath:`image`,role:`spine`,optional:!1,editor:`structural`,label:`Image`},{id:`speech`,profilePath:`speech`,role:`spine`,optional:!1,editor:`structural`,label:`Speech`},{id:`live`,profilePath:`live`,role:`spine`,optional:!1,editor:`structural`,label:`Live`},{id:`tools`,profilePath:`tools`,role:`spine`,optional:!1,editor:`structural`,label:`Tools`},{id:`toolSpec`,profilePath:`tools.allow`,role:`branch`,parent:`tools`,optional:!0,editor:`structural`,label:`Tool`},{id:`inputs`,profilePath:`inputs`,role:`spine`,optional:!1,editor:`structural`,label:`Inputs`},{id:`outputs`,profilePath:`outputs`,role:`spine`,optional:!0,editor:`structural`,label:`Outputs`},{id:`turnBehaviour`,profilePath:`turnBehaviour`,role:`spine`,optional:!0,editor:`structural`,label:`Turn behaviour`},{id:`guardrails`,profilePath:`guardrails`,role:`spine`,optional:!0,editor:`structural`,label:`Guardrails`},{id:`observability`,profilePath:`observability`,role:`spine`,optional:!0,editor:`structural`,label:`Observability`},{id:`labels`,profilePath:`labels`,role:`spine`,optional:!0,editor:`structural`,label:`Labels`}],le={identity:te,inputs:f(`inputs`).filter(e=>e!==`decision`)},y=ce.map(e=>({...e,profileTypes:le[e.id]??f(e.profilePath)}));function ue(e){return y.find(t=>t.id===e)}function de(e){return e.modelBindings.length>1}function fe(e){return e.modelBindings.some(t=>t.provider!==`local`&&!n(e.providers,t).keySlot)}function b(e,t){let r={provider:t.provider,keySlot:t.keySlot||e.models.key,fallbackKeySlot:t.fallbackKeySlot||e.models.fallbackKey},i=n(e.providers,r);return{...i,given:{keySlot:!!i.keySlot&&!r.keySlot,fallbackKeySlot:!!i.fallbackKeySlot&&!r.fallbackKeySlot}}}function pe(e,t){let n=new Set(e.modelBindings.filter(n=>{let r=b(e,n);return r.keySlot===t||r.fallbackKeySlot===t}).map(e=>e.provider));return e.providers.filter(e=>n.has(e.id))}function me(e){let t=e.efforts.map(({alias:e})=>e.trim()).filter(Boolean);return new Set(t).size>1}function he(e){return e.attachmentsAccept.length>0||e.voiceAccept.length>0}var ge=h,x=[{name:`operationTimeoutMs`,label:`Call timeout`,units:`ms`,isTimer:!0},{name:`connectTimeoutMs`,label:`Connect timeout`,units:`ms`,isTimer:!0},{name:`liveStepTimeoutMs`,label:`Live step timeout`,units:`ms`,isTimer:!0},{name:`maxWireRecordBytes`,label:`Wire record`,units:`bytes`,isTimer:!1},{name:`maxWireResponseBytes`,label:`Wire response`,units:`bytes`,isTimer:!1},{name:`maxEventBytes`,label:`Event`,units:`bytes`,isTimer:!1},{name:`maxStepBytes`,label:`Step`,units:`bytes`,isTimer:!1},{name:`maxStepEvents`,label:`Step events`,units:`events`,isTimer:!1},{name:`maxPendingToolCalls`,label:`Tool calls`,units:`calls`,isTimer:!1}],S=2147483647,C={compactMaxTokens:32e3,compactAt:.75,compactKeep:4},w={"continue.instruction":`turnBehaviour`,"canary.bind_note":`guardrails`,"quota.exhausted":`guardrails`,"repair.default_guidance":`outputs`,"egress.default_repair_guidance":`guardrails`,"egress.refusal":`guardrails`};function T(e){return`${e}-${crypto.randomUUID().slice(0,8)}`}function E(e){return{key:T(`model`),modelId:`fast`,protocol:`openRouterOpenAi`,provider:`openrouter`,apiId:``,options:{},timeoutMs:null,efforts:[],defaultEffort:``,allowEffortSelect:!1,summaries:null,maxOutputTokens:null,temperature:null,builtInTools:[],...e}}var D=`Studio stub tool — returns a fixed result.`;function O(e){return{key:T(`tool`),toolName:`my_tool`,toolType:`function`,description:D,category:`studio`,access:g[0],permission:ne[0],loadTier:ae[0],paths:[`*`],inputJson:u,outputJson:c,...e}}function k(e,t,n){return(!e.description.trim()||e.description===D)&&n?{agentKey:t,description:`Asks ${n} and returns its answer.`}:{agentKey:t}}function A(){return{name:``,kind:`words`,pattern:``,flags:``,words:[]}}function j(){return{key:``,label:``,at:p(m,()=>`ignore`),patterns:[A()],hint:``}}function M(){let e=i(void 0);return{canaryBindNote:``,detect:p(ie,t=>({...e.detect[t]})),sources:Object.fromEntries(re.map(e=>[e,{theorem:!0,patterns:[],hint:``}])),own:[],quotaEnabled:!1,quotaPerDay:null,quotaMessage:``,allow:{ungiven_images:{hosts:[],fromTools:!0},ungiven_links:{hosts:[],fromTools:!0}},innocentNames:[],blockedReplyOnBlock:``,blockedReplyMaxRetries:null,egressRepairGuidance:``,egressRefusal:``,allowPrivateNetworks:!1,allowedHosts:[],allowedSchemes:[],taintAfterRemoteRead:``,taintRemoteDestination:``}}function N(){let e=_({});return{writeTo:l,destination:l,sampleRate:e.sampleRate,include:{...e.include},scrub:{sensitive:e.scrub.sensitive,injection:e.scrub.injection,canary:e.scrub.canary},retainForDays:null,rotateAfterMiB:null,resourceJson:``}}function P(e){return e.map(([e,t])=>({key:T(`criterion`),label:e,text:t}))}function F(){return{contract:`guardrails.tool_call.v1`,maxStateBytes:null,questions:[{key:T(`question`),id:`verdict`,type:`choice`,instructions:`Given what the user asked for and what the call would do, should it run?`,criteria:P([[`allow`,`Safe, and what the user asked for.`],[`flag`,`Probably fine, but unusual or sensitive enough for a person to look first.`],[`block`,`Harmful, or clearly beyond what the user asked for.`]])},{key:T(`question`),id:`risk`,type:`score`,instructions:`How much harm would this call do if it were wrong?`,criteria:P([[``,`Low: reversible, and affects only the user.`],[``,`High: hard to undo, or affects other people or money.`]])}],images:[]}}var I=JSON.stringify({context:`The user asked the agent to tidy up old screenshots on their desktop.`,tool_call:{name:`delete_files`,path:`~/Documents`,recursive:!0},outcome:`Would delete 1,284 files, including tax_return_2025.pdf.`},null,2),L=JSON.stringify(`The user asked to tidy screenshots. The proposed call recursively deletes 1,284 files, including a tax return.`),_e=`To clear your desktop, select the screenshots and move them to the Trash. Empty the Trash to delete them for good.(Screen captures save to the desktop by default. You can change where they go in the Screenshot app's Options menu.(Press Command-Shift-5 to record the screen or capture a window. Recordings are saved as movie files next to your screenshots.(Stacks group desktop files by kind, date or tag, so a cluttered desktop folds into a few piles you can open one at a time.(Deleted files stay in the Trash for 30 days. Drag a file out of the Trash to put it back where it was.(When your disk is almost full, open Storage settings and review the largest files. Old downloads and installers are safe to remove.(Offloading unused apps frees space and keeps their documents. Reinstalling an app brings its data back.(Photos you have backed up can be optimised so the originals live in the cloud and smaller copies stay on the device.(Your plan renews on the same date each month. You can see the next charge under Billing, then Upcoming invoices.(To get a refund, open the invoice and choose Request refund. Charges from the last 14 days are refunded in full.(Update your card under Billing, then Payment methods. The new card is used for the next renewal, not for past invoices.(Annual plans cost two months less than paying monthly. Switching mid-term credits the unused months to the new plan.(Invoices are emailed as PDFs and list your company name and tax number. Edit those details before the invoice is issued.(Turn on two-step verification under Security. You will be asked for a code from your authenticator app each time you sign in on a new device.(If you forget your password, choose Forgot password on the sign-in page. The reset link expires after one hour.(Review signed-in devices under Security and sign out any you don't recognise. This ends their sessions immediately.(Passkeys replace your password with your fingerprint or face. Create one under Security, then Passkeys.(To close your account, export your data first. Closing deletes your workspace after a 30-day grace period.(Share a folder by choosing Share, then entering an email address. Viewers can read; editors can change and delete.(Public links work for anyone who has them. Set an expiry date, or turn the link off to stop sharing at once.(Transfer ownership of a folder before you leave a team, or its contents will be archived with your account.(Lisbon has mild, wet winters and warm, dry summers. Expect highs near 28 °C in August.(The best months for the Algarve coast are May, June and September, when the beaches are warm and the crowds are thin.(Trams in Lisbon climb the steep hills of Alfama and Graça. Line 28 is the famous one, and the busiest.(For a crisp pizza base, preheat the oven and the baking tray together at the highest setting for at least thirty minutes.(Rest steak for five minutes after cooking so the juices settle back into the meat instead of running onto the board.`.split(`(`).join(`
|
|
2
2
|
|
|
3
3
|
`),ve=`How do I delete every screenshot on my desktop?`;function ye(e,t=`choice`){let n=q(`question`,e.decision.questions.map(e=>e.id),e=>`question_${e}`);return{key:T(`question`),id:n,type:t,instructions:``,criteria:B(t)}}function be(e,t,n){let r=t.replace(/\.[^.]*$/,``).toLowerCase().replace(/[^a-z0-9]+/g,`_`).replace(/^_|_$/g,``)||`image`,i=q(r,e.decision.images.map(e=>e.name),e=>`${r}_${e}`);return{key:T(`image`),name:i,...n}}function xe(e){let t=q(`slot`,e.map(e=>e.name),e=>`slot_${String(e)}`);return{key:T(`slot`),name:t,label:``,choices:[z(),z()]}}function R(){return{key:T(`condition`),name:``,values:[]}}function z(){return{key:T(`choice`),value:``,description:``}}function Se(){return{key:T(`criterion`),label:``,text:``}}function B(e){return e===`noul`||e===`box`?[]:P(e===`choice`?[[`yes`,``],[`no`,``]]:[[``,``],[``,``]])}function Ce(){return{identity:{agentId:``,profileType:``,handle:``,system:``,conditions:[]},included:[`observability`,`labels`],models:{defaultModel:``,allowModelSelect:!1,maxSteps:null,key:``},modelBindings:[],providers:[...e],tools:{t2Loader:``,parallel:!1},toolSpecs:[],inputs:{text:!0,attachmentsAccept:[],voiceAccept:[],maxFiles:null,maxBytes:null,maxTurnBytes:null,limitsByMime:{},slots:[],contextFrom:[],contextMaxChars:null},outputs:{mode:`text`,schemaId:``,schemaJson:``,streamMode:``,streamThoughts:!0,validationEnabled:!1,maxRetries:null,itemRules:{},repairGuidance:``},turnBehaviour:{resumeEnabled:!1,allowContinue:[],autoContinue:[],maxContinues:null,continueInstruction:``,allowSteering:r({type:`text`}),atStepLimit:`stop`},guardrails:M(),observability:N(),image:{aspectRatio:``,resolution:``,mimeType:``,quality:``,background:``,n:null,seed:null,outputCompression:null,includeText:!1,references:[]},speech:{voice:``,style:``,speed:null,format:``},live:{ingressAudio:v(`audio`),ingressVideo:v(`video`),ingressText:v(`text`),voice:``,sessionResumption:!1,greeting:``,resumedPrompt:``,resumedAfterMs:null,contextCompression:!1,compressionTriggerTokens:null,compressionTargetTokens:null,transcriptionInput:!1,transcriptionOutput:!1,vadActivityHandling:``,vadStartSensitivity:``,vadEndSensitivity:``,vadPrefixPaddingMs:null,vadSilenceDurationMs:null},decision:F(),labels:{}}}var we=new Set([`guardrails`]);function V(e,t){return e.profileTypes.includes(t)&&!(t===`decision`&&we.has(e.id))}function H(e){let t=e.identity.profileType;if(!t)return[`identity`];let n=new Set(e.included);return y.filter(e=>e.role!==`branch`&&V(e,t)&&(!e.optional||n.has(e.id))).map(e=>e.id)}function U(e,t){let n=e.identity.profileType;return n!==``&&f(t).includes(n)}function Te(e){return U(e,`identity.system`)&&oe(e.guardrails.detect,`canary_leak`)}function Ee(e){let n=e.identity.profileType;return n!==``&&t.includes(n)}function W(e){let t=e.identity.profileType;return t?y.filter(n=>n.role===`spine`&&n.optional&&V(n,t)&&!e.included.includes(n.id)).map(e=>e.id):[]}function De(e){return{...e,attachmentsAccept:e.attachmentsAccept.filter(e=>a(se,e)),voiceAccept:[]}}function Oe(e){return{...e,text:!1,attachmentsAccept:[],voiceAccept:e.voiceAccept.length?e.voiceAccept:[`audio/*`]}}function ke(e,t,n){let r=e.modelBindings.find(e=>e.key===t);return r?{...e,models:n.modelId!==void 0&&e.models.defaultModel===r.modelId?{...e.models,defaultModel:n.modelId}:e.models,modelBindings:e.modelBindings.map(e=>e.key===t?{...e,...n}:e)}:e}function G(e,t){if(t.some(t=>t.modelId===e))return e;let[n,...r]=t;return n&&!r.length?n.modelId:``}function Ae(e,t){if(!e.modelBindings.find(e=>e.key===t))return e;let n=e.modelBindings.filter(e=>e.key!==t);return{...e,models:{...e.models,defaultModel:G(e.models.defaultModel,n)},modelBindings:n}}function K(e,t){let n=e.identity.profileType,r=n&&n!==`host`?n:`text`,i=e.modelBindings.map(e=>e.modelId),a=d(r,t),o=q(a.modelId,i,e=>`${a.modelId}${e}`);return E({...a,modelId:o})}function je(e){return O({toolName:q(`my_tool`,e.toolSpecs.map(e=>e.toolName),e=>`my_tool_${e}`)})}function q(e,t,n){let r=new Set(t),i=e;for(let e=2;r.has(i);e++)i=n(e);return i}function Me(e,t,n){if(t===`host`)return{...e,identity:{...e.identity,profileType:t}};let r=e.modelBindings.filter(r=>{let i=s(e.providers,t,r),a=e.providers.find(e=>e.id===r.provider);return ee(a,t,r.protocol)&&!Fe(n,t,i)}),i={...e,identity:{...e.identity,profileType:t},modelBindings:r},a=r.length?r:[K(i,n?.start)],c=!e.models.key&&fe({...i,modelBindings:a}),l=t===`speech`&&!e.speech.voice.trim()&&a.some(n=>o(s(e.providers,t,n)));return{...i,inputs:t===`image`?De(e.inputs):t===`transcription`?Oe(e.inputs):e.inputs,...l?{speech:{...e.speech,voice:Ne}}:{},models:{...e.models,defaultModel:G(e.models.defaultModel,a),key:c?Ie:e.models.key},modelBindings:a}}var Ne=`Kore`,Pe=[`text`,`image`,`speech`,`transcription`,`live`,`decision`];function Fe(e,t,n){if(!e)return!1;let r=t=>e.models(t,n.definition).some(e=>e.id===n.apiId.trim());return!r(t)&&Pe.some(e=>e!==t&&r(e))}var Ie=`slot_a`;function Le(e,t){return W(e).includes(t)?{...e,included:[...e.included,t]}:e}function Re(e,t){return{...e,included:e.included.filter(e=>e!==t)}}function J(e){return`modelBinding:${e}`}var Y=`toolSpec:`;function X(e){return`${Y}${e}`}function Z(e){return e.startsWith(Y)?e.slice(9):void 0}var Q=`provider:`;function ze(e){return`${Q}${e}`}function Be(e){return e.startsWith(Q)?e.slice(9):void 0}var Ve=new Map(y.map(e=>[e.id,e.label]));function He(e){return Ve.get(e)??e}function Ue(e,t){let[n,r]=t.split(`:`,2);if(n===`modelBinding`&&r!==void 0)return e.modelBindings.some(e=>e.key===r)?{facet:n,key:r}:void 0;let i=Z(t);if(i!==void 0)return e.toolSpecs.some(e=>e.key===i)?{facet:`toolSpec`,key:i}:void 0;let a=H(e);if(r===void 0&&a.includes(t))return{facet:t}}function We(e,t){return t===`models`?e.modelBindings.map(e=>({id:J(e.key),ref:{facet:`modelBinding`,key:e.key},label:e.modelId.trim()||`Unnamed model`,children:[]})):t===`tools`?$(e.toolSpecs):[]}function $(e){return e.map(e=>({id:X(e.key),ref:{facet:`toolSpec`,key:e.key},label:e.toolName.trim()||`Unnamed tool`,children:[]}))}function Ge(e){let t=H(e).filter(e=>e!==`identity`).map(t=>({id:t,ref:{facet:t},label:He(t),children:We(e,t)}));return{id:`identity`,ref:{facet:`identity`},label:e.identity.agentId.trim()||`Unnamed agent`,children:t}}export{B as A,Te as B,H as C,W as D,q as E,j as F,b as G,Me as H,A as I,he as J,me as K,xe as L,be as M,ye as N,Le as O,K as P,z as R,U as S,Re as T,Ee as U,Ae as V,ke as W,y as X,pe as Y,ue as Z,S as _,Ge as a,E as b,$ as c,ve as d,_e as f,ge as g,x as h,Ue as i,Se as j,R as k,C as l,w as m,Be as n,Z as o,L as p,de as q,ze as r,X as s,J as t,I as u,k as v,T as w,O as x,Ce as y,je as z};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{Jn as e,Un as t,Wt as n}from"./tool-schema-
|
|
1
|
+
import{Jn as e,Un as t,Wt as n}from"./tool-schema-BHHcOFff.js";import{c as r}from"./host-patterns-F-KZIzkF.js";import{Lr as i,M as a,Vn as o}from"./shaped-data-BRffby3g.js";import{I as s}from"./reader-Ql1nrrAA.js";import{M as c}from"./browser-connection-IC3QKsFq.js";import{r as l}from"./encode-files-BF1rsZES.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`,i(`error.bad_response`));switch(t.phase){case`running`:{let{endedAt:n,outputDraft:r,...i}=e;return{...i,state:t,startedAt:t.at,...t.edited?{edited:t.edited}:{},...t.activity?{activity:t.activity}:{}}}case`complete`:case`error`:return{...b(e),state:t,endedAt:t.at,...t.activityPast?{activityPast:t.activityPast}:{}};case`cancel`:case`gate`:case`background`:return{...b(e),state:t,endedAt:t.at};case`draft`:return{...e,outputDraft:(e.outputDraft??``)+t.text};case`artifact`:return{...e,artifacts:[...e.artifacts,t.artifact]};case`progress`:return se(e,t.data);case`dispatch`:case`trace`:case`warning`:return e}}function b(e){let{outputDraft:t,...n}=e;return n}function x(e,t){return{arguments:{},artifacts:[],...e,name:t.name,callId:t.callId,draft:(e?.draft??``)+t.text}}function S(e,t){if(t.type===`tool_draft`){e.set(t.callId,x(e.get(t.callId),t));return}let{tool:n}=t,r=n.operationId??n.callId;n.phase===void 0&&e.get(n.callId)?.draft!==void 0&&e.delete(n.callId),e.set(r,y(e.get(r),n))}function ae(e){let t=new Map;for(let n of e)(n.type===`tool_draft`||n.type===`tool`)&&S(t,n);return[...t.values()]}function oe(t){if(typeof t!=`object`||!t||!(`agent`in t)||!(`event`in t))return;let{event:n}=t;if(n?.type!==`tool`&&n?.type!==`tool_draft`)return;let r=e.safeParse(n);return r.success?r.data:void 0}function se(e,t){let n=oe(t),r=n&&ce(e.steps??[],n);return r?{...e,steps:r}:e}function ce(e,t){let n=new Map(e.map(e=>[e.operationId??e.callId,e]));if(t.type===`tool`&&t.tool.phase!==void 0){let e=n.get(t.tool.operationId??t.tool.callId);if(e?.callId!==t.tool.callId||e.name!==t.tool.name)return}return S(n,t),[...n.values()]}function le(e){return(e.state?.phase===`gate`?e.state.gate.preparedArguments:void 0)??e.edited?.to??e.arguments}function ue(e,t){return e.type!==`tool`||e.tool.callId!==t?!1:e.tool.phase===`complete`||e.tool.phase===`error`||e.tool.phase===`background`}var de={avif:`image/avif`,gif:`image/gif`,heic:`image/heic`,heif:`image/heif`,jpeg:`image/jpeg`,jpg:`image/jpeg`,png:`image/png`,svg:`image/svg+xml`,webp:`image/webp`,mp4:`video/mp4`,webm:`video/webm`,mov:`video/quicktime`,ogv:`video/ogg`,mp3:`audio/mpeg`,m4a:`audio/mp4`,ogg:`audio/ogg`,wav:`audio/wav`};function fe(e){let t=e.split(`/`).pop()??e,n=t.lastIndexOf(`.`);return n<=0||n===t.length-1?void 0:de[t.slice(n+1).toLowerCase()]}function pe(e){let t=e.trim();if(t.length===0)return;let n;try{n=new URL(t)}catch{return}if(n.protocol!==`http:`&&n.protocol!==`https:`)return;let r=fe(n.pathname);if(r)return{url:n.href,mimeType:r}}var me=/^(.*)\/thumb(\/.+\/([^/]+))\/(\d+)px-\3(?:\.[a-z0-9]+)?$/i;function he(e){let t=new URL(e),n=t.hostname.split(`.`).slice(-2).join(`.`);for(let e of[...t.searchParams.keys()])e.startsWith(`utm_`)&&t.searchParams.delete(e);let r=me.exec(t.pathname);return{key:`${n}${r?`${r[1]}${r[2]}`:t.pathname}${t.search}`,width:r?Number(r[4]):1/0}}function ge(e){let t=new Map,n=[],r=e=>{if(typeof e==`string`){let r=pe(e);if(!r)return;let i=he(r.url),a=t.get(i.key);if(!a){t.set(i.key,{index:n.length,largest:i.width,smallest:i.width}),n.push(r);return}let o=n[a.index];i.width>a.largest?(a.largest=i.width,n[a.index]={...o,url:r.url,previewUrl:o.previewUrl??o.url}):i.width<a.smallest&&(a.smallest=i.width,n[a.index]={...o,previewUrl:r.url})}else if(Array.isArray(e))for(let t of e)r(t);else if(typeof e==`object`&&e)for(let t of Object.values(e))r(t)};return r(e),n}var C=0;function w(e){return e===`user`?`user-${globalThis.crypto.randomUUID()}`:(C+=1,`${e}-${String(C)}`)}function T(e,t){return e?.kind===t}function E(e,t,n,r){let i=e.at(-1);T(i,t)?i.text+=n:e.push({id:w(r),kind:t,text:n})}function D(e,t){let n=e.at(-1),r=n?.kind===`text`||n?.kind===`thought`;e.splice(r?e.length-1:e.length,0,t)}function O(e,t){return e.find(e=>e.kind===`tool`&&e.id===t)}function k(e,t){let n=`tool-${t.operationId??t.callId}`,r=O(e,n),i=y(r?.tool,t);if(r){r.tool=i;return}let a=t.phase===void 0?O(e,`tool-${t.callId}`):void 0;a?.tool.draft===void 0?e.push({id:n,kind:`tool`,tool:i}):(a.id=n,a.tool=i)}function A(e,t){let n=`tool-${t.callId}`,r=O(e,n),i=x(r?.tool,t);r?r.tool=i:e.push({id:n,kind:`tool`,tool:i})}function j(e){return e.findLast(e=>e.kind===`structured`&&e.draft!==void 0)}function M(e,t,n){let r=j(e),i=(r?.draft??``)+t;r?(r.draft=i,r.value=v(i)):e.push({id:w(n),kind:`structured`,value:v(i),draft:i})}function N(e,t,n){let r=j(e);r?(r.value=t,delete r.draft):e.push({id:w(n),kind:`structured`,value:t})}function P(e,t){return e.type===t.type?e.placeId&&t.placeId?e.placeId===t.placeId:e.uri===t.uri:!1}function F(e,t,n){let r=e.find(e=>e.kind===`citation`&&e.callId===t.callId),i=r?[...r.sources]:[];for(let e of t.sources)i.some(t=>P(t,e))||i.push(e);r?r.sources=i:e.push({id:w(n),kind:`citation`,sources:i,...t.callId===void 0?{}:{callId:t.callId}})}function I(e,t,n,r){if(t.phase===`complete`&&t.output!==void 0)for(let i of ge(t.output))r.has(i.url)||(r.add(i.url),e.push({id:w(n),kind:`media`,mimeType:i.mimeType,url:i.url,...i.previewUrl?{previewUrl:i.previewUrl}:{}}))}function L(e,t){return e.messages.flatMap(e=>{if(e.role!==`user`)return[];let n=e.parts??[],r=[e.content??``,...n.map(e=>`text`in e?e.text:``)].join(``).trim();return[...r?[{id:w(t),kind:`user-text`,text:r}]:[],...n.flatMap(e=>`text`in e?[]:[{id:w(t),kind:e.type===`audio`?`user-voice`:`user-attachment`,name:e.mimeType,mimeType:e.mimeType,...`data`in e?{sizeBytes:Math.floor(e.data.length*3/4),data:e.data}:{sizeBytes:0}}])]})}function R(e,t=`user`){let n=[],r=e.text?.trim();r&&n.push({id:w(t),kind:`user-text`,text:r});for(let r of e.attachments??[])n.push({id:w(t),kind:`user-attachment`,name:r.name,mimeType:r.mimeType,sizeBytes:r.sizeBytes,...r.data===void 0?{}:{data:r.data}});for(let r of e.voice??[])n.push({id:w(t),kind:`user-voice`,name:r.name,mimeType:r.mimeType,sizeBytes:r.sizeBytes,...r.data===void 0?{}:{data:r.data}});return n}function _e(e,t){switch(e.type){case`media`:return e.media?{id:w(t),kind:`media`,mimeType:e.media.mimeType,data:e.media.data}:void 0;case`grounding`:return{id:w(t),kind:`grounding`,grounding:e.grounding};case`evidence`:return{id:w(t),kind:`evidence`,evidence:e.evidence};case`error`:return e.error?{id:w(t),kind:`error`,message:e.error}:void 0;case`done`:return{id:w(t),kind:`turn-done`,stop:e.stop,tokens:e.tokens,interactionId:e.interactionId,compaction:e.compaction!==void 0};default:return}}function ve(e,t,n){if(t.phase===`complete`)for(let r of t.parts??[])r.type!==`text`&&e.push({id:w(n),kind:`media`,mimeType:r.mimeType,...`data`in r?{data:r.data}:{url:r.uri}})}function z(e,n={}){let r=n.idPrefix??`turn`,i=n.showThoughts??!0;C=0;let a=[],o=new Set;for(let n of t(e))switch(n.type){case`thought`:i&&n.text&&E(a,`thought`,n.text,r);break;case`text`:n.text&&E(a,`text`,n.text,r);break;case`tool_draft`:A(a,n);break;case`tool`:k(a,n.tool),I(a,n.tool,r,o),ve(a,n.tool,r);break;case`structured_draft`:M(a,n.text,r);break;case`structured`:N(a,n.structured,r);break;case`citation`:F(a,n,r);break;case`guardrail`:D(a,{id:w(r),kind:`guardrail`,guardrail:n.guardrail});break;case`stage`:for(let e of n.injected??[])a.push(...L(e,r));break;default:{let e=_e(n,r);e&&a.push(e)}}return a}function ye(e,t,n={}){return[...R(e,`user`),...z(t,n)]}function be(e){if(!e)return o;let{detect:t,patterns:n}=e;if(!n)return t;let r=Object.fromEntries(Object.entries(n).map(([e,{theorem:t}])=>[e,{theorem:t,matchers:[]}]));return{...t,sources:r}}function xe(e,t){if(e.text===void 0)return e;let n=a(e.text,`user`,be(t));return{...e,text:n.text??e.text}}function B(e,t,n){let r=s(e,t);if(!r.ok)return{ok:!1,issues:r.issues};let i=xe(t,n);return{ok:!0,draft:i,blocks:R(i)}}function V(e,t){if(t)return e.models[t]}function H(e){return!!(e.allowModelSelect&&Object.keys(e.models).length>=2)}function U(e,t){let n=V(e,t);return n?.allowEffortSelect?Object.keys(n.efforts??{}).length>=2:!1}function W(e,t){let n=V(e,t);if(!n?.efforts)return;let r=n.defaultEffort?.trim();return r&&n.efforts[r]?r:Object.keys(n.efforts)[0]}function Se(e){return H(e)?Object.entries(e.models).map(([e,t])=>({id:e,label:t.apiId})):[]}function Ce(e,t){if(!U(e,t))return[];let n=V(e,t);return n?.efforts?Object.entries(n.efforts).map(([e,t])=>({alias:e,level:t})):[]}function G(e){let t=new Set;for(let n of e)if(n.type===`tool`&&n.tool.phase===`complete`)for(let e of c(n.tool.output)??[])t.add(e);return[...t]}function K(e){let t=n(e,e=>e.type===`done`&&e.tools!==void 0);return t?.type===`done`?t.tools:void 0}function we(e){let t=K(e)?.visible??[],r=n(e,e=>e.type===`done`&&e.steps!==void 0);return{promoted:[...new Set([...t,...G(e)])],stepsTaken:r?.type===`done`?r.steps??0:0}}function q(e){return e?.streaming?.streamThoughts!==!1}function J(e){return e.defaultModel??Object.keys(e.models)[0]}function Te(e,t,n){let r=t.model!==void 0&&Object.hasOwn(e.models,t.model)&&(n===void 0||t.model!==J(n))?t.model:J(e),i=r===void 0?void 0:e.models[r]?.efforts;return{model:r,effort:r===t.model&&t.effort!==void 0&&i!==void 0&&Object.hasOwn(i,t.effort)&&(n===void 0||t.effort!==W(n,r))?t.effort:W(e,r)}}function Y(e){if(!e.operationId)throw new r(`request`,i(`session.gate_expired`));return e.operationId}function Ee(e,t){return t.selectedModel??J(e)}function X(e,t,n){let r=t.selectedEffort;if(!n||!Object.hasOwn(e.models,n))return r;let i=e.models[n];return i.allowEffortSelect?r??i.defaultEffort:r===W(e,n)?void 0:r}function Z(e,t){let n=Ee(e,t),r=e.allowModelSelect||n!==J(e)?n:void 0,i=X(e,t,n);return{...r?{model:r}:{},...i?{effort:i}:{}}}function De(e,t,n){return{name:n.name,input:n.input,...n.gateKind?{gateKind:n.gateKind}:{},sessionPermissions:n.sessionPermissions??t.sessionPermissions,...t.toolSnapshot?{snapshot:t.toolSnapshot}:{},...t.promotedToolIds.length?{promoted:[...t.promotedToolIds]}:{},...Z(e,t)}}function Q(e){return{...e.conversation?{conversation:e.conversation}:{},...e.turnId?{turnId:e.turnId}:{}}}function Oe(e,t,n,r={}){let i=(r.walkAway?.calls??[]).map(e=>({callId:e.callId,operationId:Y(e)}));return{...Q(r),...Z(e,t),input:n,...i.length?{abandon:i}:{},replay:{sessionPermissions:t.sessionPermissions}}}function ke(e,t,n,r={}){return{...Q(r),gateId:n.gateId,operationId:n.operationId,decision:n.decision,...n.secret===void 0?{}:{secret:n.secret},...n.page===void 0?{}:{page:n.page},replay:De(e,t,{...n,gateKind:n.gateKind??(t.gatedTool?.callId===n.gateId?t.gatedTool.gateKind:void 0)})}}function $(e,t){return B(e.inputs,t,e.guardrails)}function Ae(e,t,n,r=[]){return $(e,{...t.trim()?{text:t}:{},...n.length?{attachments:l(n)}:{},...r.length?{voice:l(r)}:{}})}function je(e,t){return z(t,{showThoughts:q(e.outputs)})}export{ae as C,ee as D,te as E,p as O,le as S,ne as T,B as _,Ae as a,y as b,q as c,K as d,W as f,H as g,Se as h,Y as i,m as k,G as l,Ce as m,Oe as n,$ as o,U as p,je as r,Te as s,ke as t,we as u,ye as v,f as w,ue as x,z as y};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{r as e}from"./rolldown-runtime-hePW80VL.js";import{c as t,u as n}from"./themeProps-3IqahpCr.js";import{t as r}from"./VStack-CkVMcNiK.js";import{n as i}from"./StackItem-CQviqAfM.js";import{S as a,T as o}from"./browser-transport-
|
|
1
|
+
import{r as e}from"./rolldown-runtime-hePW80VL.js";import{c as t,u as n}from"./themeProps-3IqahpCr.js";import{t as r}from"./VStack-CkVMcNiK.js";import{n as i}from"./StackItem-CQviqAfM.js";import{S as a,T as o}from"./browser-transport-BRjXq2Qp.js";import{t as s}from"./Icon-BqkS-pIq.js";import{t as c}from"./Text-BOqCfzZC.js";import{n as l,o as u}from"./labels-provider-uONlWExD.js";import{n as d}from"./Card-DruykyeB.js";import{t as f}from"./IconButton-DVUFx-8p.js";import{t as p}from"./Tooltip-BWs5DLrM.js";import{d as m}from"./reader-Ql1nrrAA.js";import{_ as h,b as g,g as _,y as v}from"./ConsoleFrame-CXVxrOXS.js";import{c as y,i as b}from"./trace-patterns-D6TbkLLr.js";import{n as x}from"./studio-console-C0F2FDl3.js";import{D as S,O as C,V as w,W as T}from"./index-CCj0zkrC.js";var E=e(n(),1),D=t(),O=`var(--duration-medium) var(--ease-standard)`,k=12;function A(){let e=d();return(0,E.useMemo)(()=>({percent:new Intl.NumberFormat(e,{style:`percent`,maximumFractionDigits:0}),decimal:new Intl.NumberFormat(e,{maximumFractionDigits:2}),usd:new Intl.NumberFormat(e,{style:`currency`,currency:`USD`,maximumSignificantDigits:2})}),[e])}function j(e){return y(e?`clear`:`shade2`)}function M({value:e,isLead:t}){return(0,D.jsx)(`div`,{style:{height:k,width:`${String(Math.max(e,.01)*100)}%`,borderRadius:4,background:j(t),transition:`width ${O}`}})}function N({title:e,aside:t,detail:n,answer:a}){let o=l(),s=A(),u=Object.entries(a.probabilities).sort(([,e],[,t])=>t-e);return(0,D.jsx)(b,{title:e,aside:t,detail:n,value:a.choice,note:o(`@theorem.decision.confidence`,{percent:s.percent.format(a.confidence)}),children:(0,D.jsx)(r,{gap:2,role:`list`,children:u.map(([e,t])=>(0,D.jsxs)(r,{gap:1,role:`listitem`,"aria-label":o(`@theorem.decision.option`,{label:e,percent:s.percent.format(t)}),children:[(0,D.jsxs)(i,{gap:2,hAlign:`between`,"aria-hidden":!0,children:[(0,D.jsx)(c,{type:`supporting`,color:`secondary`,maxLines:1,children:e}),(0,D.jsx)(c,{type:`supporting`,hasTabularNumbers:!0,children:s.percent.format(t)})]}),(0,D.jsx)(M,{value:t,isLead:e===a.choice})]},e))})})}var P=56;function F(e){let t=e.split(/[:—–]\s/)[0]?.trim()??``;return t&&t.length<=32&&t!==e?t:e}function I({title:e,aside:t,detail:n,answer:i,labels:a}){let o=l(),s=A(),u=a.length,d=Math.min(u-1,Math.max(0,Math.round(i.score)));return(0,D.jsx)(b,{title:e,aside:t,detail:n,value:a[d]===void 0?s.decimal.format(i.score):F(a[d]),note:[o(`@theorem.decision.score_of`,{score:s.decimal.format(i.score),max:s.decimal.format(u-1)}),o(`@theorem.decision.confidence`,{percent:s.percent.format(i.confidence)})].join(` · `),children:(0,D.jsxs)(r,{gap:1,children:[(0,D.jsxs)(`div`,{"aria-hidden":!0,style:{position:`relative`,display:`flex`,alignItems:`flex-end`,gap:4,height:P},children:[a.map((e,t)=>(0,D.jsx)(`div`,{style:{flex:1,height:`${String(Math.max(.04,i.probabilities[String(t)]??0)*100)}%`,borderRadius:4,background:j(t===d),transition:`height ${O}`}},`${String(t)}:${e}`)),(0,D.jsx)(`div`,{style:{position:`absolute`,insetBlock:-4,left:`${String((i.score+.5)/u*100)}%`,width:0,borderInlineStart:`1.5px dashed var(--color-text-secondary)`,transition:`left ${O}`}})]}),(0,D.jsx)(`div`,{style:{display:`flex`,gap:4},children:a.map((e,t)=>(0,D.jsx)(`div`,{style:{flex:1,minWidth:0},title:e,children:(0,D.jsx)(c,{type:`supporting`,color:`secondary`,maxLines:1,children:F(e)})},`${String(t)}:${e}`))}),(0,D.jsx)(`span`,{style:{position:`absolute`,width:1,height:1,overflow:`hidden`,clipPath:`inset(50%)`},children:a.map((e,t)=>o(`@theorem.decision.option`,{label:e,percent:s.percent.format(i.probabilities[String(t)]??0)})).join(`; `)})]})})}function L({title:e,aside:t,detail:n,answer:r}){let i=A();return(0,D.jsx)(b,{title:e,aside:t,detail:n,value:i.decimal.format(r.noul)})}var R=72,z=168;function B(e){let[t,n]=(0,E.useState)(null);return(0,E.useEffect)(()=>{let t=new Image;t.onload=()=>{n({width:t.naturalWidth,height:t.naturalHeight})},t.src=e},[e]),t}function V(e,t){let n=e.style.color;e.style.color=`var(${t})`;let r=getComputedStyle(e).color;return e.style.color=n,r}function H({source:e,box:t,caption:n}){let r=l(),i=v(e),a=B(i),[o,s]=(0,E.useState)(null);if(!a)return null;let c=h(t),u=a.width*(t.right-t.left)/(a.height*(t.bottom-t.top)),d=r(`@theorem.decision.open_box`);return(0,D.jsxs)(D.Fragment,{children:[(0,D.jsx)(p,{content:d,children:(0,D.jsx)(T,{label:d,padding:0,onClick:e=>{let n={outline:V(e.currentTarget,`--color-accent`),shade:V(e.currentTarget,`--color-overlay`)};g(i,t,n).then(s)},children:(0,D.jsx)(`div`,{role:`img`,"aria-label":r(`@theorem.decision.box_in`),style:{position:`relative`,overflow:`hidden`,aspectRatio:String(u),height:z,maxWidth:`100%`,borderRadius:4},children:(0,D.jsx)(`img`,{src:i,alt:``,style:{position:`absolute`,width:`${String(c.width)}%`,height:`${String(c.height)}%`,left:`${String(c.left)}%`,top:`${String(c.top)}%`,maxWidth:`none`}})})})}),(0,D.jsx)(w,{isOpen:o!==null,onOpenChange:e=>{e||s(null)},media:{src:o??i,alt:r(`@theorem.decision.box_marked`),caption:n},hasZoom:!0})]})}function U({title:e,aside:t,detail:n,answer:r,image:i,asked:a}){let o=l(),s=a&&_(a.images,a.state,i),c=A(),{top:u,bottom:d,left:f,right:p}=r.box,m=o(`@theorem.decision.box_edges`,{left:c.percent.format(f),top:c.percent.format(u),right:c.percent.format(p),bottom:c.percent.format(d)});return(0,D.jsx)(b,{title:e,aside:t,detail:n,value:m,note:o(`@theorem.decision.confidence`,{percent:c.percent.format(r.confidence)}),children:s?(0,D.jsx)(H,{source:s,box:r.box,caption:`${e}: ${m}`}):(0,D.jsx)(`div`,{"aria-hidden":!0,style:{position:`relative`,height:R,borderRadius:4,border:`1px solid var(--color-border)`},children:(0,D.jsx)(`div`,{style:{position:`absolute`,insetInlineStart:`${String(f*100)}%`,insetBlockStart:`${String(u*100)}%`,width:`${String((p-f)*100)}%`,height:`${String((d-u)*100)}%`,borderRadius:2,background:j(!0),transition:`all ${O}`}})})})}function W({question:e,answer:t,asked:n,onQuestion:r,detail:i}){let a=l(),c=`${e.id} · ${a(`@theorem.decision.type.${e.type}`)}`;if(!t)return null;let u=a(`@theorem.decision.edit_question`,{question:e.id}),d={title:c,detail:i,aside:r?(0,D.jsx)(f,{label:u,tooltip:u,size:`sm`,variant:`ghost`,icon:(0,D.jsx)(s,{icon:o,size:`xsm`,color:`secondary`}),onClick:()=>{r(e.id)}}):void 0};return t.type===`choice`?(0,D.jsx)(N,{...d,answer:t}):t.type===`score`?(0,D.jsx)(I,{...d,answer:t,labels:e.labels}):t.type===`noul`?(0,D.jsx)(L,{...d,answer:t}):(0,D.jsx)(U,{...d,answer:t,image:e.image,asked:n})}function G({model:e,usage:t,elapsedMs:n,isStale:i,tokens:a,children:o}){let s=l(),d=A();return(0,D.jsx)(C,{children:(0,D.jsxs)(r,{gap:3,style:{opacity:i?.5:1,transition:`opacity ${O}`},"aria-busy":i,children:[o,(0,D.jsx)(S,{children:(0,D.jsx)(c,{type:`supporting`,color:`secondary`,hasTabularNumbers:!0,children:u(s,d.usd,{model:e,usage:t,elapsedMs:n,tokens:a})})})]},n??0)})}function K({iface:e,result:t,elapsedMs:n,isStale:r,asked:i,onQuestion:a,questionText:o}){let s=l();return(0,D.jsx)(G,{model:t.model,usage:t.usage,elapsedMs:n,isStale:r,tokens:e=>s(`@theorem.decision.tokens`,{count:e}),children:(0,D.jsx)(x,{minWidth:260,children:e.questions.map(e=>(0,D.jsx)(S,{children:(0,D.jsx)(W,{question:e,answer:t.answers[e.id],asked:i,onQuestion:a,detail:o?.[e.id]})},e.id))})})}var q={status:`idle`,result:null,elapsedMs:null,startedAt:null,failure:null};function J(e,t){for(let n of t??[])e.traces?.push(n)}function Y(e,t,n){let[r,i]=(0,E.useState)(q),o=(0,E.useRef)(null);(0,E.useEffect)(()=>()=>o.current?.abort(),[]);let s=(0,E.useCallback)(()=>{o.current?.abort(),o.current=null,i(e=>e.status===t?{...e,status:e.result?`done`:`idle`,startedAt:null}:e)},[t]),c=(0,E.useCallback)(async(...r)=>{o.current?.abort();let s=new AbortController;o.current=s,i(e=>({status:t,result:e.result,elapsedMs:e.elapsedMs,startedAt:Date.now(),failure:null}));let c=performance.now();try{let t=await n(e,s.signal,...r);if(s.signal.aborted)return;J(e,t.traces),i({status:`done`,result:t.result,elapsedMs:performance.now()-c,startedAt:null,failure:null})}catch(t){if(s.signal.aborted)return;J(e,m(t)),i(e=>({...e,status:`error`,startedAt:null,failure:a(t)}))}finally{o.current===s&&(o.current=null)}},[e,t,n]);return{...r,call:c,cancel:s}}export{A as a,K as i,G as n,M as r,Y as t};
|