@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,3 +1,3 @@
|
|
|
1
|
-
import{A as e,D as t,E as n,O as r,T as i,b as a,c as o,d as s,f as c,x as l}from"./schemas-D7cgkv3L.js";import{Ct as u,Et as ee,Gn as te,H as ne,Sn as d,Un as re,Vn as ie,Wt as ae,Yt as oe,bn as f,cn as se,dn as ce,er as le,ln as ue,wn as p,wt as de,xn as fe,yn as pe}from"./tool-schema-
|
|
1
|
+
import{A as e,D as t,E as n,O as r,T as i,b as a,c as o,d as s,f as c,x as l}from"./schemas-D7cgkv3L.js";import{Ct as u,Et as ee,Gn as te,H as ne,Sn as d,Un as re,Vn as ie,Wt as ae,Yt as oe,bn as f,cn as se,dn as ce,er as le,ln as ue,wn as p,wt as de,xn as fe,yn as pe}from"./tool-schema-BHHcOFff.js";import{c as m}from"./host-patterns-F-KZIzkF.js";import{A as me,Lr as h,Mn as he,Nn as ge,Nr as _e,Rr as ve,Un as ye,an as be,er as xe,fn as Se,jn as Ce,lr as g,pn as we,tn as _,tr as Te,vn as v,vr as Ee,wr as De}from"./shaped-data-BRffby3g.js";import{a as Oe,n as ke}from"./live-ingress-OuSlQ6q7.js";var Ae=2,je=4,Me=3,Ne=/(^|,)(\s*)("?)(?:([=@])|([+-])(?![0-9."]))/gm,Pe=/^[A-Za-z0-9+/]*={0,2}$/,Fe=new Set([`text/csv`,`text/plain`,`text/markdown`]);function y(e){let{maxFiles:t,maxBytes:n,maxTurnBytes:r,limitsByMime:i}=e;if(t&&n&&r)return{maxFiles:t,maxBytes:n,maxTurnBytes:r,limitsByMime:i}}function Ie(e,t){if(t.limitsByMime){let n=p(e);if(t.limitsByMime[n])return t.limitsByMime[n];let[r]=n.split(`/`),i=`${r}/*`;if(t.limitsByMime[i])return t.limitsByMime[i]}return t.maxBytes}function b(e){return`uri`in e}function Le(e){if(e.type===`speech`)throw new m(`request`,`Profile ${e.id} (speech) does not accept media input`);if(e.type===`live`)throw new m(`request`,`Profile ${e.id} (live) does not accept turn attachment input`);if(e.type===`host`||e.type===`decision`||e.type===`embedding`)throw new m(`request`,`Profile ${e.id} (${e.type}) does not accept turn input`);let t=y(e.inputs??{});if(!t)throw new m(`config`,`Profile ${e.id} must set maxFiles, maxBytes, and maxTurnBytes`);return t}function Re(e){let t=0;return e.endsWith(`==`)?t=Ae:e.endsWith(`=`)&&(t=1),Math.floor(e.length*Me/je)-t}function ze(e){try{return new TextDecoder(`utf-8`,{fatal:!0}).decode(e)}catch{return new TextDecoder(`latin1`).decode(e)}}function Be(e){return e.replace(Ne,(e,...t)=>{let[n,r,i,a,o]=t;return`${n}${r}${i}'${a??``}${o??``}`})}function Ve(e,t,n){let r=ze(t);return e===`text/csv`&&(r=Be(r)),new TextEncoder().encode(n.read(r))}function x(e,t){return t?{...e,fileName:t}:e}function S(e,t,n){return t.filter(t=>!f(e,t.mimeType)).map(e=>x({code:`mime_not_allowed`,params:{mimeType:e.mimeType,channel:n}},e.name))}function He(e,t){let n=[];e.length>t.maxFiles&&n.push({code:`too_many_files`,params:{maxFiles:t.maxFiles}});let r=0;for(let i of e){if(i.sizeBytes===void 0)continue;let e=Ie(i.mimeType,t);i.sizeBytes>e&&n.push(x({code:`file_too_large`,params:{maxBytes:e}},i.name)),r+=i.sizeBytes}return r>t.maxTurnBytes&&n.push({code:`turn_too_large`,params:{maxTurnBytes:t.maxTurnBytes}}),n}function C(e,t,n){let r=[];return t.length>0&&!e.attachments&&r.push({code:`attachments_not_accepted`,params:{channel:`attachment`}}),n.length>0&&!e.voice&&r.push({code:`voice_not_accepted`,params:{channel:`voice`}}),r.length>0||t.length===0&&n.length===0?r:(e.attachments&&r.push(...S(e.attachments,t,`attachment`)),e.voice&&r.push(...S(e.voice,n,`voice`)),e.limits?[...r,...He([...t,...n],e.limits)]:[...r,{code:`limits_unconfigured`}])}var Ue={mime_not_allowed:`attachments.mime_not_allowed`,too_many_files:`attachments.too_many_files`,too_many_of_kind:`attachments.too_many_of_kind`,file_too_large:`attachments.file_too_large`,turn_too_large:`attachments.turn_too_large`,attachments_not_accepted:`attachments.not_accepted`,voice_not_accepted:`attachments.not_accepted`,limits_unconfigured:`attachments.limits_unconfigured`};function w(e){let t={};for(let[n,r]of Object.entries(e.params??{}))r!==void 0&&(t[n]=r);return e.fileName!==void 0&&(t.fileName=e.fileName),{key:Ue[e.code],params:t}}function We(e,t){let n=w(e);return h(n.key,n.params,t)}function Ge(e){return new m(`input`,`attachments refused: ${e.map(e=>e.code).join(`, `)}`,{copy:e.map(w)})}function Ke(e){if(!Pe.test(e))throw new m(`request`,`attachment data must be base64`);return Re(e)}function qe(e){let t={mimeType:e.mimeType,name:e.name};return b(e)||(t.sizeBytes=Ke(e.data)),t}function Je(e,t,n){if(!Xe(t,n))return;let r=Le(e),i=C({attachments:fe(e,`attachments`),voice:fe(e,`voice`),limits:r},(t??[]).map(qe),(n??[]).map(qe));if(i.length>0)throw Ge(i)}function Ye(e,t){if(b(e))return e;let{mimeType:n,data:r}=e;if(!Fe.has(p(n)))return e;let i=Ve(n,xe(r),t);return{...e,data:Te(i)}}function Xe(e,t){return(e?.length??0)>0||(t?.length??0)>0}function Ze(e,t,n,r){return Je(e,t,n),{attachments:t?.length?t.map(e=>Ye(e,r.attachment)):t,voice:n?.length?n.map(e=>Ye(e,r.voice)):n}}var Qe=`
|
|
2
2
|
|
|
3
3
|
`;function $e(e){if(typeof e==`string`)return;if(typeof e!=`object`||!e||Array.isArray(e))return`must be a string or { private: string }`;let t=Object.keys(e);if(t.length!==1||t[0]!==`private`)return`must have exactly one key, private`;let n=e.private;if(typeof n!=`string`)return`must be a string`;if(n===``)return`must not be empty`}function et(e,t){if(typeof e!=`string`){if(!Array.isArray(e))return`${t} must be a string or an array of parts`;if(e.length===0)return`${t} must not be an empty array`;for(let[n,r]of e.entries()){let e=$e(r);if(e)return`${t}[${n}]${typeof r==`object`&&r&&`private`in r?`.private`:``} ${e}`}}}function tt(e,t){let n=et(e,t);if(n)throw new m(`config`,n)}function nt(e,t,n){return tt(e,t),typeof e==`string`?n(e):e.map(e=>typeof e==`string`?n(e):{private:n(e.private)})}function rt(e){if(typeof e==`string`)return[{text:e,private:!0}];let t=e.some(e=>typeof e!=`string`);return e.map(e=>typeof e==`string`?{text:e,private:!t}:{text:e.private,private:!0})}function it(e){let t=[];for(let n of e)n.some(e=>e.text)&&(t.length>0&&t.push({text:Qe,private:!0}),t.push(...n));return t}function at(e){return e.map(e=>e.text).join(``)}function ot(e){let t=[],n=``;for(let r of e)r.private?n+=r.text:(n.trim()&&t.push(n),n=``);return n.trim()&&t.push(n),{text:at(e),private:t}}function st(e,t){return ot(it([e,...t.map(e=>e?[{text:e,private:!0}]:[])]))}function T(e){let t=Object.keys(e);return t.length===1?t[0]:void 0}var ct=/^[A-Za-z_][\w-]*$/,lt=/^\S+$/;function ut(e){return typeof e==`string`?[[e]]:e.map(e=>typeof e==`string`?[e]:e)}function dt(e){return typeof e==`string`?e:e.private}function E(e){return ee(e[0]===void 0?``:dt(e[0]))}function ft(e,t){let n={};for(let[r,i]of Object.entries({...e,...t}))n[r]={type:`string`,enum:[...i]};return{type:`object`,properties:n}}function pt(e,t){for(let[n,r]of Object.entries(e??{})){if(!ct.test(n))return`Condition "${n}" needs a plain name.`;if(n===`input`||n===`output`)return`Condition "${n}" is a reserved name.`;if(Object.hasOwn(t,n))return`"${n}" is both a condition and a slot.`;if(r.length===0)return`Condition "${n}" lists no values.`;let e=r.find(e=>!lt.test(e)||e===`null`);if(e!==void 0)return`Condition "${n}" can't take the value "${e}".`}}function mt(e,t){if(e.length===0)return`It has no wording to send.`;let n=E(e);if(n.joined)return`A prompt line can't start with "+"; every line that fits is sent.`;if(n.when===`unreadable`)return`A line that opens with "when" needs a condition and a colon, like "when path is web: …".`;for(let e of n.when){if(e.path.includes(`.`))return`"${e.path}" isn't one condition or slot.`;if(e.expected===null)return`A condition always has a value, so "is null" never fits.`;let n=de(e,t,`this profile’s conditions or slots`);if(n)return n}if(n.when.length>0&&!n.text&&e.length===1)return`It has no wording to send.`}function D(e,t,n){let r=pt(t,n);if(r)return r;let i=ft(t,n);for(let[t,n]of ut(e).entries()){let e=mt(n,i);if(e)return`Line ${t+1}: ${e}`}}function ht(e,t,n,r){let i=n.conditions??{};if(t===void 0){if(n.conditions)throw new m(`request`,`Profile ${e} declares no conditions`);return{...r}}if(Object.hasOwn(i,`path`))throw new m(`request`,`Profile ${e}: the turn's own path states path`);for(let n of Object.keys(i))if(!Object.hasOwn(t,n))throw new m(`request`,`Profile ${e} has no condition '${n}'`);let a={...r};for(let[r,o]of Object.entries(t)){let t=r===`path`?n.path:i[r];if(t===void 0)throw new m(`request`,`Profile ${e}: the turn left condition '${r}' unset`);if(!o.includes(t))throw new m(`request`,`Profile ${e}: '${t}' is no value of condition '${r}'`);a[r]=t}return a}function gt(e,t){return e.when!==`unreadable`&&e.when.every(e=>u(e,t))}function _t(e,t,n){let r=ut(e),i=r.flat().some(e=>typeof e!=`string`),a=[];for(let[e,o]of r.entries()){let r=E(o);if(!gt(r,t))continue;let s=[];for(let[e,t]of o.entries()){let a=n(e===0?r.text:dt(t));a&&s.push({text:a,private:typeof t!=`string`||!i})}a.push({line:e+1,pieces:s})}return a}function vt(e,t){if(typeof e!=`string`){if(!Array.isArray(e))throw new m(`config`,`${t} must be a string or an array of lines`);if(e.length===0)throw new m(`config`,`${t} must not be an empty array`);for(let[n,r]of e.entries())if(typeof r!=`string`){if(!Array.isArray(r))throw new m(`config`,`${t}[${n}] must be a string or a list of parts; put { private } inside the list`);tt(r,`${t}[${n}]`)}}}function yt(e,t){let n=e?.path;if(n)for(let e of t){let t=e.paths?.find(e=>e!==`*`&&!n.includes(e));if(t!==void 0)return`Tool ${e.name} lists path "${t}", which is not one of ${n.join(`, `)}.`}}function O(e,t){let n=e.get(t);return n!==void 0&&n.type!==`builtin`}function k(e,t){return!e||e.includes(`*`)?!0:t?e.includes(t):!1}function bt(e,t){return t.filter(n=>{let r=e.get(n);return r?.type!==`builtin`||!(r.conflictsWith??[]).some(e=>t.includes(e))})}function A(e){return`tools`in e?e.tools.allow:[]}function j(e){return e.type===`text`||e.type===`image`?e.tools:void 0}function xt(e){return`tools`in e?e.tools.parallel:void 0}function St(e,t,n){return A(t).filter(r=>{let i=e.get(r);return!i||i.type===`builtin`?!1:t.type===`host`||k(i.paths,n.path)})}function Ct(e,t,n,r){let i=t.models[r];return i?(i.builtInTools??[]).filter(t=>{let r=e.get(t);return r?.type===`builtin`&&k(r.paths,n.path)}):[]}function M(e,t,n){let r=e.get(t);if(r&&r.type!==`builtin`)return{type:`function`,name:r.name,description:r.description,parameters:n&&r.askInputSchema||r.inputSchema}}function wt(e,t,n){let r=[];for(let i of t){let t=M(e,i,n);t&&r.push(t)}return r}function N(e,t,n){if(t.visible.includes(n))return;t.visible.push(n);let r=M(e,n,t.modelBackground);r&&!t.wire.some(e=>e.name===n)&&t.wire.push(r)}function Tt(e,t,n){if(t.builtins.includes(n))return;let r=e.get(n);if(r?.type!==`builtin`)return;let i=r.conflictsWith??[];t.builtins=t.builtins.filter(t=>{if(i.includes(t))return!1;let r=e.get(t);return!(r?.type===`builtin`&&r.conflictsWith?.includes(n))}),t.builtins.push(n)}function Et(e,t,n){return t.type===`live`||t.type===`host`?[...n]:n.filter(t=>e.get(t)?.loadTier===`T0`)}function Dt(e,t,n){return bt(e,n.filter(n=>{let r=e.get(n);return r?.type===`builtin`&&(t.type===`live`||r.loadTier===`T0`)}))}function Ot(e,t){if(t.type!==`text`&&t.type!==`image`&&t.type!==`live`)return;let n=A(t).flatMap(t=>e.get(t)??[]),r=yt(t.identity.conditions,n);if(r)throw new m(`config`,`Profile ${t.id}: ${r}`)}function kt(e,t){let n=j(t)?.t2Loader,r=n===void 0?void 0:e.get(n);if(r&&r.type!==`builtin`&&(r.background??`never`)!==`never`)throw new m(`config`,`Profile ${t.id}: tools.t2Loader '${r.name}' sets background, and a loader cannot detach`)}function P(e,t,n,r){Ot(e,t),kt(e,t);let i=St(e,t,n),a=t.type===`host`||t.type===`decision`||t.type===`embedding`||r===void 0?[]:Ct(e,t,n,r),o=[...i,...a],s=Dt(e,t,o),c=Et(e,t,o),l=c.filter(t=>O(e,t)),u=n.background!==void 0;return{builtins:s,gated:o,visible:c,executable:l,path:n.path,sessionPermissions:n.sessionPermissions,wire:wt(e,c,u),...u?{modelBackground:u}:{}}}async function At(e,t,n,r){let i=P(e,t,n,r);return await F(e,i,t,n),i}function jt(e){return{builtins:[...e.builtins],gated:[...e.gated],visible:[...e.visible],executable:[...e.executable],path:e.path,sessionPermissions:e.sessionPermissions?[...e.sessionPermissions]:void 0,wire:e.wire.map(e=>({...e,parameters:structuredClone(e.parameters)})),...e.modelBackground?{modelBackground:e.modelBackground}:{}}}async function F(e,t,n,r){let i=j(n)?.t1Policy;if(!i)return;let a;try{a=await i({profile:n,input:r.input,path:r.path,sessionPermissions:r.sessionPermissions,gated:t.gated,host:r.host})}catch(e){let t=e instanceof Error?e.message:String(e);throw new m(`config`,`Profile '${n.id}' tools.t1Policy rejected: ${t}`,{cause:e})}if(!Array.isArray(a))throw new m(`config`,`Profile '${n.id}' tools.t1Policy must return ToolId[]`);I(e,t,a)}function I(e,t,n=[]){for(let r of n){if(!t.gated.includes(r))continue;let n=e.get(r);n?.loadTier===`T2`&&(n.type===`builtin`?Tt(e,t,r):N(e,t,r))}t.executable=t.visible.filter(t=>O(e,t))}var Mt=new Set([`__proto__`,`constructor`,`prototype`]);function Nt(e){if(!me(e))return;let{loaded:t}=e;if(Array.isArray(t)&&t.every(e=>typeof e==`string`))return t}function Pt(e,t,n,r){if(r.type===`live`||r.type===`host`)return{promoted:[]};let i=[];for(let a of n){if(typeof a!=`string`||Mt.has(a))return{promoted:[],failure:{code:`invalid_output`,kind:`bad_response`,message:`tools.t2Loader loaded ids must be plain strings`}};let n=Ft(e,a,r);if(`failure`in n)return{promoted:[],failure:n.failure};let{tool:o}=n;k(o.paths,t.path)&&t.gated.includes(a)&&i.push(a)}let a=[];for(let n of i)N(e,t,n),a.push(n);return t.executable=t.visible.filter(t=>O(e,t)),{promoted:a}}function L(e){return{failure:{code:`invalid_output`,kind:`bad_response`,message:e}}}function Ft(e,t,n){if(!A(n).includes(t))return L(`tools.t2Loader attempted to promote tool '${t}' outside profile allow`);let r=e.get(t);return r?r.type===`builtin`?L(`tools.t2Loader attempted to promote builtin '${t}' — only custom tools may be promoted`):r.loadTier===`T2`?{tool:r}:L(`tools.t2Loader attempted to promote tool '${t}' with loadTier '${r.loadTier}' — only T2 tools may be promoted`):L(`tools.t2Loader attempted to promote unknown tool '${t}'`)}function R(e){return Array.isArray(e)?[...e]:e.choices.map(e=>e.value)}function It(e){return Array.isArray(e)?{choices:e.map(e=>({value:e}))}:{...e.label!==void 0&&e.label!==``?{label:e.label}:{},choices:e.choices.map(e=>({value:e.value,...e.description!==void 0&&e.description!==``?{description:e.description}:{}}))}}function z(e){if(e)return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,It(t)]))}function B(e){return e?.slots?{...e,slots:z(e.slots)}:e}function V(e){return e==null}function H(e){return V(e)||typeof e!=`object`||Array.isArray(e)?null:e}function U(e){let t=H(e);return!t||t.type!==void 0&&t.type!==`object`?null:t}function W(e){let t=e.required;return Array.isArray(t)?t.filter(e=>typeof e==`string`):[]}function G(e){let t=e.properties;return H(t)??{}}function Lt(e,t){return e?`${e}.${t}`:t}function Rt(e,t){t.push({path:e,error:`required field '${e}' is missing`})}async function zt(e,t,n,r,i){if(!n)return;let a=await n(t,r);a.isValid||i.push({path:e,error:a.error||a.finding||`Validation failed for '${e}'`})}async function Bt(e){let{path:t,propSchema:n,child:r,isRequired:i,fields:a,slots:o,failures:s}=e;if(V(r)){i&&Rt(t,s);return}await zt(t,r,a?.[t],o,s);let c=U(n),l=c?H(r):null;c&&l&&await Vt(c,l,t,a,o,s)}async function Vt(e,t,n,r,i,a){let o=G(e),s=new Set(W(e)),c=new Set([...Object.keys(o),...s]),l=H(t);for(let e of c)await Bt({path:Lt(n,e),propSchema:o[e],child:l?.[e],isRequired:s.has(e),fields:r,slots:i,failures:a})}async function Ht(e,t,n,r){let i=U(e);if(!i)throw new m(`config`,`structured validation requires a JSON Schema object root`);let a=[];if(!H(t)){for(let e of W(i))Rt(e,a);return a}return await Vt(i,t,``,n,r,a),a}function Ut(e,t){let n=e;for(let e of t.split(`.`)){let t=U(n);if(!t)return!1;let r=G(t);if(!Object.hasOwn(r,e)&&!W(t).includes(e))return!1;n=r[e]}return!0}function Wt(e){return e.map(e=>e.error).join(`; `)}function Gt(e,t){let n=e;for(let e of t.split(`.`))n=H(n)?.[e];return n}function Kt(e,t,n){let[r,...i]=t.split(`.`),a=H(e)??{};return r===void 0?e:{...a,[r]:i.length?Kt(a[r],i.join(`.`),n):n}}async function qt(e,t,n){let r=[];for(let[i,a]of Object.entries(t??{})){let t=Gt(e,i);if(Array.isArray(t))for(let[e,o]of t.entries()){let t=await a.check(o,n);t.isValid||r.push({path:i,index:e,item:o,reason:t.error||t.finding||`Validation failed for '${i}'`,onFail:a.onFail})}}return r}function Jt(e,t){let n=e;for(let e of t.split(`.`)){let t=U(n);if(!t)return;n=G(t)[e]}let r=H(n);if(r?.type===`array`)return H(r.items)??void 0}var Yt=class extends Error{failure;constructor(e){super(e.message),this.failure=e}},Xt=new Set([`text`,`image`,`speech`]),Zt=n().regex(/\S/),Qt=i({mimeType:n(),data:c(),name:n().optional()}),$t=i({mimeType:n(),uri:n(),name:n().optional()}),en=i({voice:n().optional(),style:n().optional(),speed:a().positive().optional()});function tn(e){return i(Object.fromEntries(Object.entries(e).map(([e,t])=>{let n=R(t);return[e,o(n).optional()]})))}var nn=new Set([`text`,`attachments`,`voice`,`slots`,`speech`]);function rn(e,t){if(!e.hostFields)return{sent:t};let n={...t},r={};for(let t of Object.keys(e.hostFields))n[t]!==void 0&&(r[t]=n[t]);let{text:i,attachments:a,voice:o,slots:s,speech:c}=t;return{sent:{text:i,...a?{attachments:a}:{},...o?{voice:o}:{},...s?{slots:s}:{},...c?{speech:c}:{}},hostInput:r}}function an(e,n){let{inputs:r}=e,a={text:Zt};r?.attachments&&(a.attachments=s(t([Qt,$t])).optional()),r?.voice&&(a.voice=s(Qt).optional()),r?.slots&&(a.slots=tn(r.slots).optional()),e.type===`speech`&&(a.speech=en.optional());for(let e of n?.hostOnly??[]){if(!a[e])throw new m(`config`,`Tool '${n?.name}' keeps '${e}' for the host, which its profile does not take`);delete a[e]}for(let[e,t]of Object.entries(n?.fieldText??{})){let r=a[e];if(!r)throw new m(`config`,`Tool '${n?.name}' describes '${e}', which its profile does not take`);a[e]=r.describe(t)}for(let[e,t]of Object.entries(n?.hostFields??{})){if(nn.has(e))throw new m(`config`,`Tool '${n?.name}' declares the host field '${e}', which is a field of every agent tool`);a[e]=t}return i(a)}var on=l({text:n().optional(),structured:r().optional(),removed:s(l({path:n(),reason:n(),item:r()})).optional(),parts:s(ie).optional(),sources:s(te).optional()});function sn(e){return e.type===`speech`||(e.type===`text`||e.type===`image`)&&e.inputs.text!==!1}function cn(e){return e.type===`builtin`?!1:e.permission!==`auto`||`auth`in e&&e.auth!==void 0&&(e.auth.onUnauthenticated??`gate`)===`gate`}function ln(e,t){if(!Xt.has(e.type))return`it is a ${e.type} profile; an agent tool runs a text, image, or speech profile`;if(!sn(e))return`it does not take text`;for(let n of A(e)){let e=t(n);if(!e)return`its tool '${n}' is not registered; register it first`;if(cn(e))return`its tool '${n}' can stop on a gate; give it permission 'auto' and no sign-in`}}function un(e,t,n){let r=`Agent tool "${e.name}"`,i=e.maxCallsPerTurn;if(i!==void 0&&!(Number.isInteger(i)&&i>0))throw new m(`config`,`${r}: maxCallsPerTurn must be a whole number above 0`);let a=t(e.profile);if(!a)throw new m(`config`,`${r}: profile '${e.profile}' must be registered before the tool`);let o=ln(a,n);if(o)throw new m(`config`,`${r} can't run '${e.profile}': ${o}`);return a}function dn(e){if(!e)return`delegated`;let t=`models`in e&&Object.values(e.models).some(e=>(e.builtInTools?.length??0)>0);return A(e).length===0&&!t?`local`:`delegated`}function fn(e){let t=re(e),n=t.flatMap(e=>e.type===`text`?[e.text]:[]).join(``),r=ae(t,e=>e.type===`structured`),i=r?.structured,a=t.flatMap(e=>e.type===`media`?[{type:e.media.mimeType.startsWith(`audio/`)?`audio`:`image`,mimeType:e.media.mimeType,data:e.media.data}]:[]),o=t.flatMap(e=>e.type===`citation`?e.sources:[]);return{...i===void 0?{text:n}:{structured:i},...r?.removed?.length?{removed:r.removed}:{},...a.length>0?{parts:a}:{},...o.length>0?{sources:o}:{}}}function pn(e,t,n){return{...e,type:`agent`,input:t,output:on,sources:e=>e.sources??[],...n}}function mn(e,t,n){if(!e||typeof e!=`object`||Array.isArray(e))return n.push(`${t}: schema must be an object`),!1;let r=typeof e.type==`string`||Array.isArray(e.type),i=e.anyOf!==void 0||e.oneOf!==void 0;if(!r&&!i){if(t!==`$`)return!0;n.push(`${t}: missing type or combinator`)}return e.type===`array`&&e.items===void 0&&n.push(`${t}: array schema must define items`),!0}function hn(e,t,n,r){let i=Array.isArray(t)?t:[];for(let t of i)typeof t==`string`&&!Object.hasOwn(e,t)&&r.push(`${n}: required key '${t}' missing from properties`);for(let[t,i]of Object.entries(e))i&&typeof i==`object`&&K(i,`${n}.properties.${t}`,r)}function K(e,t,n){if(!mn(e,t,n))return;let r=e.properties;r&&typeof r==`object`&&!Array.isArray(r)&&hn(r,e.required,t,n),e.items&&typeof e.items==`object`&&!Array.isArray(e.items)&&K(e.items,`${t}.items`,n);for(let r of[`anyOf`,`oneOf`]){let i=e[r];Array.isArray(i)&&i.forEach((e,i)=>{e&&typeof e==`object`&&K(e,`${t}.${r}[${i}]`,n)})}}function gn(e,t){let n=[];if(K(e,`$`,n),n.length>0)throw new m(`config`,`Invalid tool ${t} schema: ${n.join(`; `)}`)}function _n(t,n=`output`){let r=e(t,{target:`draft-7`,io:n});return delete r.$schema,r.type||=`object`,r}function q(e){if(typeof e!=`object`||!e)return e;if(Array.isArray(e))return e.map(q);let t={};for(let n of Object.keys(e))n!==`__proto__`&&n!==`constructor`&&n!==`prototype`&&(t[n]=q(e[n]));return t}function vn(e){let t=/^[a-z][a-z0-9+.-]*:\/\/[^/?#]*/i.exec(e)?.[0];if(!t||/[{}]/.test(t))throw new m(`config`,`Endpoint "${e}" must start with a fixed scheme and host; placeholders belong in the path or query`)}function yn(e,t,n,r){if(!n.provider?.trim()||!n.apiId?.trim())throw new m(`config`,h(`provider.binding_identity`))}function bn(e){J(e.id,e.models),Q(e.id,e.observability),hr(e.id,e.inputs);for(let[t,n]of Object.entries(e.models))Y(e.id,t,n);return{type:`embedding`,id:e.id,identity:{handle:e.identity.handle},models:e.models,defaultModel:An(e.id,e),allowModelSelect:e.allowModelSelect,inputs:e.inputs,guardrails:e.guardrails,observability:e.observability,labels:e.labels}}function xn(e){J(e.id,e.models),Z(e.id,e.guardrails),Q(e.id,e.observability);for(let[t,n]of Object.entries(e.models))Y(e.id,t,n);if(`text`in e.inputs&&e.inputs.text!==!1)throw new m(`config`,`Profile ${e.id}: a transcription takes a voice clip, so inputs.text must be false`);return{type:`transcription`,id:e.id,identity:{handle:e.identity.handle},...Mn(e),providerContinuation:void 0,maxSteps:void 0,inputs:{...e.inputs,text:!1},guardrails:e.guardrails,observability:e.observability,labels:e.labels}}function Sn(e,t,n,r){let i=r.safeParse(n);if(!i.success)throw new m(`config`,`Profile ${e} model '${t}': ${i.error.issues.map(e=>`${e.path.join(`.`)}: ${e.message}`).join(`; `)}`)}function Cn(e,t,n){if(Sn(e,t,n,ue),yn(e,t,n,`decision`),`retry`in n)throw new m(`config`,`Profile ${e} model '${t}': a decision binding takes no retry; a decision retries only a transient failure, by the kernel's rule`);if(n.timeoutMs!==void 0&&(!Number.isFinite(n.timeoutMs)||n.timeoutMs<=0))throw new m(`config`,`Profile ${e} model '${t}' timeoutMs must be > 0`)}function wn(e){let t=e.models?T(e.models):void 0;if(!t)throw new m(`config`,`Profile ${e.id}: type 'decision' must declare exactly one model`);Cn(e.id,t,e.models[t])}function Tn(e){if(e.inputs.state!==`json`)throw new m(`config`,`Profile ${e.id}: decision inputs.state must be 'json'`);let t=e.inputs.maxStateBytes;if(t!==void 0&&!(Number.isInteger(t)&&t>0))throw new m(`config`,`Profile ${e.id}: decision inputs.maxStateBytes must be a positive integer`);if(!e.decision.contract.trim())throw new m(`config`,`Profile ${e.id}: decision.contract must be non-empty`)}function En(e){return wn(e),Tn(e),Q(e.id,e.observability),{...e,identity:{handle:e.identity.handle}}}function Dn(e){return e===void 0?{}:{parallel:e}}function On(e){return kn(e.id,e.tools),Q(e.id,e.observability),{type:`host`,id:e.id,tools:{allow:e.tools.allow,...Dn(e.tools.parallel)},guardrails:e.guardrails,observability:e.observability,labels:e.labels}}function kn(e,t){if(!Array.isArray(t.allow))throw new m(`config`,`Profile ${e}: type 'host' must set tools.allow`)}function J(e,t){if(Object.keys(t).length===0)throw new m(`config`,`Profile ${e} must declare at least one model`)}function An(e,t){let n=t.defaultModel??T(t.models);if(!n)throw new m(`config`,`Profile ${e} must set defaultModel when more than one model is declared`);if(!t.models[n])throw new m(`config`,`Profile ${e} defaultModel '${n}' is not declared`);return n}function Y(e,t,n){jn(e,t,n),Sn(e,t,n,ce),jn(e,t,n)}function jn(e,t,n){let r=n.efforts;if(!r||Object.keys(r).length===0){if(n.defaultEffort||n.allowEffortSelect)throw new m(`config`,`Profile ${e} model '${t}': defaultEffort and allowEffortSelect require efforts`);return}for(let[n,i]of Object.entries(r))if(!v.includes(i))throw new m(`config`,`Profile ${e} model '${t}' effort '${n}': '${i}' is not a thinking level (${v.join(`, `)})`);let i=Object.keys(r),a=n.defaultEffort??(i.length===1?i[0]:void 0);if(!a)throw new m(`config`,`Profile ${e} model '${t}' must set defaultEffort when more than one effort is declared`);if(!r[a])throw new m(`config`,`Profile ${e} model '${t}' defaultEffort '${a}' is not declared`);if(n.allowEffortSelect&&i.length<2)throw new m(`config`,`Profile ${e} model '${t}' allowEffortSelect requires at least two efforts`)}function Mn(e){return{providerContinuation:e.providerContinuation?le.parse(e.providerContinuation):{},models:e.models,defaultModel:An(e.id,e),allowModelSelect:e.allowModelSelect,maxSteps:e.maxSteps}}function Nn(e,t,n){if(n?.length){for(let r of n)if(!oe(r))throw new m(`config`,`Profile ${e}: turnBehaviour.resumption.${t} may only include ContinueStopKind (length | stream_incomplete | provider_error); got '${r}'`)}}function Pn(e,t){t&&(Nn(e,`allowContinue`,t.allowContinue),Nn(e,`autoContinue`,t.autoContinue))}function X(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Fn(e,t){let n=[e];for(let e of t)n=n.flatMap(t=>X(t)?e===`*`?Object.values(t):[t[e]]:[]);return n}var In=Object.entries(Se).filter(([,e])=>e.required===!0).map(([e,t])=>[e,t.profileTypes]).sort(([e],[t])=>e.split(`.`).length-t.split(`.`).length);function Ln(e){if(!X(e))throw new m(`config`,`Profile definition must be an object`);let t=typeof e.id==`string`&&e.id.trim()?e.id:void 0;if(!t)throw new m(`config`,`Profile definition must set id`);if(!we.find(t=>t===e.type))throw new m(`config`,`Profile ${t}: type must be one of ${we.join(`, `)}`)}function Rn(e){let t=e.identity?.handle,n=[[`id`,e.id,64],[`identity.handle`,typeof t==`string`?t:``,32]];for(let[t,r,i]of n)if(!(Array.from(r).length<=i))throw new m(`config`,`Profile ${e.id.slice(0,64)}: ${t} must be at most ${i} characters`)}function zn(e){let{id:t,type:n}=e,r=e;for(let[e,i]of In){if(i&&!i.includes(n))continue;let a=he(e),o=Fn(r,a.slice(0,-1)),s=a[a.length-1];if(o.some(e=>{if(!X(e))return!1;let t=e[s];return t==null||t===``}))throw new m(`config`,`Profile ${t}: type '${n}' must set ${a.join(`.`)}`)}}function Bn(e){let{id:t,type:n}=e;if(n!==`live`&&ge(`inputs`).includes(n)&&e.inputs==null)throw new m(`config`,`Profile ${t}: type '${n}' must set inputs`)}function Vn(e){let[t]=Ce(e);if(!t)return;let{offValue:n,reason:r}=t.scope,i=n===void 0?``:` (other than ${n})`;throw new m(`config`,`Profile ${e.id}: type '${e.type}' must not set ${t.path}${i} — ${r}`)}function Hn(e,t){let n=t.turnBehaviour;Pn(e,n?.resumption)}function Un(e,t){let n=t=>new m(`config`,`Profile ${e}: ${t}`),r=t?.maxRetries;if(r!==void 0&&(!Number.isInteger(r)||r<0))throw n(`outputs.validation.maxRetries must be a non-negative integer`)}function Z(e,t){let n=t=>new m(`config`,`Profile ${e}: ${t}`),r=Object.keys(t??{}).find(e=>!Wn.includes(e));if(r!==void 0)throw n(`guardrails.${r} is not a setting; it takes ${Wn.join(`, `)}`);Kn(t?.blockedReply,n)}var Wn=[`quota`,`detect`,`blockedReply`,`network`,`taint`],Gn=[`onBlock`,`maxRetries`];function Kn(e,t){if(e===void 0)return;let n=Object.keys(e).find(e=>!Gn.includes(e));if(n!==void 0)throw t(`guardrails.blockedReply.${n} is not a setting; it takes onBlock and maxRetries`);let{onBlock:r,maxRetries:i}=e;if(r!==void 0&&!g.includes(r))throw t(`guardrails.blockedReply.onBlock must be one of ${g.join(`, `)}`);if(i!==void 0&&(!Number.isInteger(i)||i<0))throw t(`guardrails.blockedReply.maxRetries must be a non-negative integer`)}function qn(e){let t=e.guardrails?.detect,n=e.type===`host`?ye(`guardrails.detect`,t,Ee):ye(`guardrails.detect`,t);if(n!==void 0)throw new m(`config`,`Profile ${e.id}: ${n}`)}function Q(e,t){try{let n=Oe(t);if(!Number.isFinite(n.retainForDays))throw new m(`config`,`Profile ${e}: observability.retainForDays must be a finite number`);if(n.rotateAfterMiB<=0||!Number.isFinite(n.rotateAfterMiB))throw new m(`config`,`Profile ${e}: observability.rotateAfterMiB must be a positive number`)}catch(t){if(t instanceof m&&t.message.startsWith(`Profile `))throw t;let n=t instanceof Error?t.message:String(t);throw new m(De(t),`Profile ${e}: ${n}`,{cause:t})}}function Jn(e){if(e.type===`host`||e.type===`decision`||e.type===`speech`||e.type===`transcription`||e.type===`embedding`)return;let{conditions:t,system:n}=e.identity,r={};for(let[t,n]of Object.entries(B(e.inputs)?.slots??{}))r[t]=R(n);let i=n??``;vt(i,`Profile ${e.id} identity.system`);let a=D(i,t,r);if(a)throw new m(`config`,`Profile ${e.id} identity.system: ${a}`)}function Yn(e){Ln(e);for(let t of[`key`,`fallbackKey`,`protocol`,`provider`])if(t in e)throw new m(`config`,h(`provider.profile_configuration`,{profile:e.id,field:t}));Vn(e),Bn(e),zn(e),Rn(e),e.labels&&ve(e.labels,`Profile ${e.id}`);for(let t of _e)if(e.labels?.[t]!==void 0)throw new m(`config`,`Profile ${e.id}: labels '${t}' is a host line, which a profile cannot change; set it with overrideLabels`);if(Jn(e),qn(e),e.type===`host`)return On(e);if(e.type===`decision`)return En(e);if(e.type===`embedding`)return bn(e);if(e.type===`transcription`)return xn(e);J(e.id,e.models),Hn(e.id,e),Z(e.id,e.guardrails),e.type===`text`&&Un(e.id,e.outputs?.validation),Q(e.id,e.observability);for(let[t,n]of Object.entries(e.models))Y(e.id,t,n);let t=e.type===`speech`?{handle:e.identity.handle}:{handle:e.identity.handle,conditions:e.identity.conditions,system:e.identity.system},n=e.guardrails,r=e.observability,i=e.labels,a=Mn(e),o;switch(e.type){case`text`:o={type:`text`,id:e.id,identity:t,...a,tools:e.tools,inputs:B(e.inputs),outputs:e.outputs,turnBehaviour:e.turnBehaviour,guardrails:n,observability:r,labels:i};break;case`image`:o={type:`image`,id:e.id,identity:t,...a,image:e.image,tools:e.tools,inputs:B(e.inputs),outputs:e.outputs,turnBehaviour:e.turnBehaviour,guardrails:n,observability:r,labels:i},tr(o.id,o.inputs.attachments?.accept),er(o.id,o.image);break;case`speech`:o={type:`speech`,id:e.id,identity:t,...a,speech:e.speech,outputs:e.outputs,turnBehaviour:e.turnBehaviour,guardrails:n,observability:r,labels:i};break;case`live`:o={type:`live`,id:e.id,identity:t,...a,live:e.live,inputs:e.inputs?B(e.inputs):e.inputs,tools:{allow:e.tools.allow,...Dn(e.tools.parallel)},turnBehaviour:e.turnBehaviour,guardrails:n,observability:r,labels:i},ke(o),rr(o.id,o.live.contextCompression),nr(o);break;default:throw new m(`config`,`Unknown profile type '${String(e)}'`)}return Qn(o),Xn(o),Zn(o),o}function Xn(e){let{maxSteps:t}=e;if(!(t===void 0||Number.isInteger(t)&&t>0))throw new m(`config`,`Profile ${e.id}: maxSteps must be a whole number of 1 or more; leave it out for the default of 20`)}function Zn(e){if(e.type===`text`&&e.turnBehaviour?.atStepLimit===`answer`&&e.maxSteps===1)throw new m(`config`,`Profile ${e.id}: turnBehaviour.atStepLimit 'answer' with maxSteps 1 leaves no step that can call a tool`)}function Qn(e){if(e.type===`live`)return;let t=e.outputs?.structured;if(!t||typeof t==`string`)return;let n=d(e)?.slots?.[t.by];if(!n)throw new m(`config`,`Profile ${e.id}: outputs.structured.by '${t.by}' is not a slot in inputs.slots`);let r=R(n),i=Object.keys(t.map).filter(e=>!r.includes(e));if(i.length)throw new m(`config`,`Profile ${e.id}: outputs.structured.map maps ${i.join(`, `)}, not a choice of slot '${t.by}'`)}var $n={n:{ok:e=>Number.isInteger(e)&&e>=1,rule:`a whole number of 1 or more`},seed:{ok:Number.isInteger,rule:`a whole number`},outputCompression:{ok:e=>Number.isInteger(e)&&e>=0&&e<=100,rule:`a whole number from 0 to 100`}};function er(e,t){for(let[n,{ok:r,rule:i}]of Object.entries($n)){let a=t[n];if(a!==void 0&&!r(a))throw new m(`config`,`Profile ${e}: image.${n} must be ${i}`)}t.references?.forEach((t,n)=>{let r=`Profile ${e}: image.references[${n}]`;if(pe(t.mimeType)!==`image`)throw new m(`config`,`${r} must be an image, not '${t.mimeType}'`);if(!(b(t)?t.uri:t.data))throw new m(`config`,`${r} needs its bytes or its uri`)})}function tr(e,t){let n=t?.filter(e=>!f(be,e));if(n?.length)throw new m(`config`,`Profile ${e}: an image profile's attachments take images, video, and PDF only, not ${n.join(`, `)}`)}function nr(e){let{greeting:t,resumed:n,sessionResumption:r}=e.live,i=`Profile ${e.id} live`;if(t!==void 0&&(typeof t!=`string`||!t.trim()))throw new m(`config`,`${i}.greeting must be a prompt; leave it out to wait`);if(!n)return;if(typeof n.prompt!=`string`||!n.prompt.trim())throw new m(`config`,`${i}.resumed.prompt must be a prompt`);let{afterMs:a}=n;if(a!==void 0&&!(Number.isFinite(a)&&a>=0))throw new m(`config`,`${i}.resumed.afterMs must be 0 or more milliseconds`);if(!r)throw new m(`config`,`${i}.resumed needs live.sessionResumption: without it no call resumes`)}function rr(e,t){if(!t)return;let n=`Profile ${e} live.contextCompression`,r=t.triggerTokens,i=t.slidingWindow.targetTokens;if(ir(`${n}.triggerTokens`,r),ir(`${n}.slidingWindow.targetTokens`,i),r!==void 0&&i!==void 0&&i>=r)throw new m(`config`,`${n}: slidingWindow.targetTokens must be below triggerTokens`)}function ir(e,t){if(!(t===void 0||Number.isInteger(t)&&t>0))throw new m(`config`,`${e} must be a whole number above 0`)}function ar(e,t,n,r){let i=`Profile ${t.id} model ${n} compaction`;if(or(i,r),sr(i,r),r.meter!=null&&r.meter!==`history`&&r.meter!==`input`)throw new m(`config`,`${i}: meter must be 'history' or 'input'`);if(r.profile===void 0){if(t.type!==`text`||t.inputs.text===!1)throw new m(`config`,`${i}: a profile that compacts itself must be a text profile that takes text`);return}let a=e.get(r.profile);if(!a)throw new m(`config`,`${i}: compaction profile '${r.profile}' must be registered before '${t.id}'`);if(a.type!==`text`||a.inputs.text===!1)throw new m(`config`,`${i}: compaction profile '${r.profile}' must be a text profile that takes text`)}function or(e,t){if(t.maxTokens<=0)throw new m(`config`,`${e}: maxTokens must be > 0`);if(t.compactAt<=0||t.compactAt>=1)throw new m(`config`,`${e}: compactAt must be in (0, 1)`)}function sr(e,t){if(t.previousExchanges<0)throw new m(`config`,`${e}: previousExchanges must be >= 0`);if(t.previousExchanges<1&&t.previousExchanges>=t.compactAt)throw new m(`config`,`${e}: previousExchanges as fraction (${t.previousExchanges}) must be < compactAt (${t.compactAt})`);if(t.previousExchanges>1&&!Number.isInteger(t.previousExchanges))throw new m(`config`,`${e}: previousExchanges >= 1 must be an integer`)}function cr(e,t){for(let n of A(t))if(e.get(n)?.type===`builtin`)throw new m(`config`,t.type===`host`?`Profile ${t.id} lists builtin '${n}' in tools.allow — type 'host' never runs a model`:`Profile ${t.id} lists builtin '${n}' in tools.allow — declare it on models.*.builtInTools instead`)}function lr(e,t){let n=j(t)?.t2Loader;if(n){if(!A(t).includes(n))throw new m(`config`,`Profile ${t.id} tools.t2Loader '${n}' must also be listed in tools.allow`);if(e.get(n)?.type!==`function`)throw new m(`config`,`Profile ${t.id} tools.t2Loader '${n}' must be a registered type: 'function' tool`)}}function*ur(e){for(let[t,n]of Object.entries(e.models))for(let e of n.builtInTools??[])yield{modelId:t,id:e}}function dr(e,t){for(let{modelId:n,id:r}of ur(t))if(e.get(r)?.type!==`builtin`)throw new m(`config`,`Profile ${t.id} model '${n}' lists '${r}' in builtInTools — not a registered builtin`)}function fr(e){let t=e.type===`text`?e.outputs?.structured:void 0;return t?typeof t==`string`?[t]:[...new Set([...Object.values(t.map),t.fallback])]:[]}function pr(e,t){let n=fr(t).map(n=>{let r=e.find(n);if(!r)throw new m(`config`,`Profile ${t.id}: outputs.structured names '${n}', which is not a registered schema; register it before the profile`);return r}),r=t.type===`text`?t.outputs?.validation:void 0,i=Object.keys(r?.fields??{}),a=Object.keys(r?.items??{});if(!i.length&&!a.length)return;if(!n.length)throw new m(`config`,`Profile ${t.id}: outputs.validation checks a structured reply, so it needs outputs.structured`);let o=a.filter(e=>!n.some(t=>Jt(t.jsonSchema,e)));if(o.length)throw new m(`config`,`Profile ${t.id}: outputs.validation.items has ${o.join(`, `)}, which no structured schema reaches as a list with an items schema`);let s=i.filter(e=>!n.some(t=>Ut(t.jsonSchema,e)));if(s.length)throw new m(`config`,`Profile ${t.id}: outputs.validation.fields has ${s.join(`, `)}, which no structured schema reaches through object properties`)}function mr(e){let t=d(e)?.context;if(!t)return;let n=_;if(t.from.length===0||t.from.some(e=>!n.includes(e)))throw new m(`config`,`Profile ${e.id}: inputs.context.from must list ${_.join(` or `)}`);if(!(Number.isInteger(t.maxChars)&&t.maxChars>0))throw new m(`config`,`Profile ${e.id}: inputs.context.maxChars must be a positive integer`)}function hr(e,t){if(!t)return;let{attachments:n,voice:r,maxFiles:i,maxBytes:a,maxTurnBytes:o,limitsByMime:s}=t,c={maxFiles:i,maxBytes:a,maxTurnBytes:o};if((n||r)&&Object.values(c).some(e=>e===void 0))throw new m(`config`,`Profile ${e} must set maxFiles, maxBytes, and maxTurnBytes`);for(let[e,t]of Object.entries(s??{}))c[`limitsByMime['${e}']`]=t;for(let[t,n]of Object.entries(c))if(n!==void 0&&!(Number.isInteger(n)&&n>0))throw new m(`config`,`Profile ${e}: inputs.${t} must be a positive integer`)}function gr(e,t,n){let r=new Map,i=i=>{let a=Yn(i),o=n&&a.type!==`host`?{...a,models:Object.fromEntries(Object.entries(a.models).map(([e,t])=>[e,se(n.require(t.provider,t.apiId),t,a.type)]))}:a;if(cr(e,o),lr(e,o),o.type!==`host`&&o.type!==`decision`&&o.type!==`embedding`){dr(e,o),hr(o.id,d(o)),mr(o),pr(t,o);for(let[e,t]of Object.entries(o.models))t.compaction&&ar(r,o,e,t.compaction)}r.set(o.id,o)};return{register:i,registerMany(e){for(let t of e)i(t)},get(e){let t=r.get(e);if(!t)throw new m(`config`,`Unknown profile '${e}'`);return t},find:e=>r.get(e),has:e=>r.has(e),list:()=>[...r.values()],clear:()=>r.clear()}}function _r(e){let t=e?.trim()??``;if(t.startsWith(`AIza`))return`gemini`;if(t.startsWith(`sk-or-`))return`openrouter`}function vr(e){let t;try{t=new URL(e.baseUrl)}catch{throw new m(`config`,`Enter a valid localhost URL.`)}if(![`http:`,`https:`].includes(t.protocol)||![`localhost`,`127.0.0.1`,`[::1]`].includes(t.hostname)||t.username||t.password||t.search||t.hash)throw new m(`config`,`Use a localhost URL without credentials, query parameters or a fragment.`);return{baseUrl:t.href.replace(/\/$/,``),fetch:(e,n)=>new URL(e instanceof Request?e.url:String(e)).origin===t.origin?fetch(e,{...n,redirect:`error`,credentials:`omit`}):Promise.reject(new m(`blocked`,`Local requests must stay on the configured origin.`))}}var yr=l({data:s(l({id:n().min(1)}))});async function br(e,t){let n=vr(e);if(!n?.fetch)throw new m(`config`,`Enter a local endpoint.`);let r=await n.fetch(`${n.baseUrl}/v1/models`,{signal:t,headers:{Accept:`application/json`}});if(!r.ok)throw new m(`network`,`Local model list returned HTTP ${r.status}.`);let i=yr.safeParse(await r.json());if(!i.success)throw new m(`request`,`The endpoint returned an invalid model list.`);return[...new Set(i.data.data.map(e=>e.id))]}var xr=`https://openrouter.ai/api/v1/models`,Sr=`https://openrouter.ai/api/v1/embeddings/models`,Cr=[{id:`gemini-embedding-2-preview`,label:`Gemini Embeddings 2 (preview)`},{id:`gemini-embedding-001`,label:`Gemini Embedding 001`}],wr=[{id:`liquid/lfm-2.5-embedding-350m:free`,label:`Liquid LFM 2.5 Embedding 350M (free)`},{id:`nvidia/nemotron-3-embed-1b:free`,label:`NVIDIA Nemotron 3 Embed 1B (free)`},{id:`nvidia/llama-nemotron-embed-vl-1b-v2:free`,label:`NVIDIA Llama Nemotron Embed VL 1B v2 (free)`}],Tr={text:`text`,image:`image`,speech:`speech`,transcription:`transcription`,live:void 0,embedding:void 0},Er=l({data:s(l({id:n().min(1),name:n().optional(),architecture:l({output_modalities:s(n()).optional()}).optional()}))}),Dr=l({data:s(l({id:n().min(1),name:n().optional()}))}),Or=l({models:s(l({name:n().min(1),displayName:n().optional(),supportedGenerationMethods:s(n()).optional()})).optional(),nextPageToken:n().optional()}),kr=5;async function $(e,t,n){let r=await fetch(t,{...n,redirect:`error`,credentials:`omit`});if(r.status===400||r.status===401||r.status===403)throw new m(`auth`,`${e} refused the key.`);if(!r.ok)throw new m(`network`,`${e} model list returned HTTP ${r.status}.`);return await r.json()}async function Ar(e,t,n,r){let i=n?.trim();if(t===`embedding`&&!i)return[...e===`openrouter`?wr:Cr];if(e===`openrouter`)return await jr(t,i,r);if(!i)throw new m(`auth`,`Choose a key to list Gemini models.`);return await Nr(t,i,r)}async function jr(e,t,n){let r={signal:n,headers:{Accept:`application/json`,...t?{Authorization:[`Bearer`,t].join(` `)}:{}}};if(e===`embedding`){let e=Dr.safeParse(await $(`OpenRouter`,Sr,r));if(!e.success)throw new m(`bad_response`,`OpenRouter returned an invalid embedding model list.`);return e.data.data.map(e=>({id:e.id,label:e.name??e.id}))}let i=Tr[e];if(!i)return[];let a=Er.safeParse(await $(`OpenRouter`,`${xr}?output_modalities=${i}`,r));if(!a.success)throw new m(`bad_response`,`OpenRouter returned an invalid model list.`);return a.data.data.filter(e=>e.architecture?.output_modalities?.includes(i)??!0).map(e=>({id:e.id,label:e.name??e.id}))}var Mr={live:`bidiGenerateContent`,embedding:`embedContent`};async function Nr(e,t,n){let r=Mr[e]??`generateContent`,i=[],a;for(let e=0;e<kr;e++){let e=new URL(ne);e.searchParams.set(`pageSize`,`1000`),a&&e.searchParams.set(`pageToken`,a);let o=Or.safeParse(await $(`Google`,e.href,{signal:n,headers:{Accept:`application/json`,"x-goog-api-key":t}}));if(!o.success)throw new m(`bad_response`,`Google returned an invalid model list.`);for(let e of o.data.models??[]){if(!e.supportedGenerationMethods?.includes(r))continue;let t=e.name.replace(/^models\//,``);i.push({id:t,label:e.displayName??t})}if(a=o.data.nextPageToken,!a)break}return i}function Pr(e){return[...new Set([e.key,e.fallbackKey,...Object.values(e.models??{}).flatMap(e=>[e.keySlot,e.fallbackKeySlot])].filter(e=>!!e))]}function Fr(e,t){return Object.fromEntries(e.map(e=>[e,Object.hasOwn(t,e)?t[e]:void 0]))}export{y as $,jt as A,_t as B,Ht as C,Kt as D,Gt as E,xt as F,it as G,ht as H,j as I,We as J,nt as K,Pt as L,Nt as M,At as N,z as O,A as P,b as Q,I as R,qt as S,Jt as T,T as U,D as V,st as W,Ge as X,C as Y,Ke as Z,on as _,Pr as a,pn as b,Yn as c,q as d,Ze as et,gn as f,dn as g,an as h,vr as i,F as j,R as k,vn as l,ln as m,br as n,Fr as o,Yt as p,rt as q,Ar as r,gr as s,_r as t,_n as u,fn as v,Wt as w,rn as x,un as y,P as z};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/compile-egress-C3etX-3o.js","assets/rolldown-runtime-hePW80VL.js","assets/host-patterns-F-KZIzkF.js"])))=>i.map(i=>d[i]);
|
|
2
|
-
import{t as e}from"./preload-helper-DpV6A1kQ.js";import{C as t,D as n,E as r,O as i,T as a,b as o,c as s,d as c,g as l,h as u,p as d,v as f,x as p}from"./schemas-D7cgkv3L.js";import{$n as m,A as h,An as g,At as _,Bt as v,C as y,Cn as b,Dn as x,Dt as S,En as C,Fn as w,Ft as T,Gt as ee,Hn as E,Ht as D,In as te,It as O,Jn as ne,L as re,Ln as k,Lt as A,Mn as ie,Mt as j,Nn as ae,Nt as oe,On as se,Ot as ce,Pn as le,Pt as ue,Qn as de,Qt as fe,Rn as pe,Rt as me,Sn as he,Tn as M,Tt as ge,Un as _e,Ut as ve,Vt as ye,Wn as be,Wt as N,Xn as xe,Xt as Se,Yn as P,Zn as Ce,_n as we,_t as Te,an as Ee,at as De,bt as Oe,ct as ke,dt as Ae,en as je,et as Me,fn as Ne,ft as F,gn as Pe,gt as Fe,hn as Ie,ht as Le,in as Re,it as ze,jn as Be,jt as Ve,kn as He,kt as Ue,lt as We,mn as Ge,mt as I,nn as Ke,nr as qe,nt as Je,on as Ye,ot as Xe,p as Ze,pn as Qe,pt as $e,qn as et,rt as L,sn as tt,st as nt,tn as rt,tr as it,tt as at,un as ot,ut as st,v as ct,vn as lt,vt as ut,xt as dt,yt as ft,zt as pt}from"./tool-schema-C7lMQU0w.js";import{c as R,t as mt}from"./host-patterns-F-KZIzkF.js";import{A as z,Ar as B,At as ht,Cn as gt,Cr as _t,Ct as vt,Dr as yt,Dt as bt,E as xt,Er as St,Et as Ct,Ft as wt,It as Tt,J as Et,Kn as Dt,Lr as V,M as Ot,Mr as kt,Mt as At,N as jt,Nn as Mt,Nt,O as Pt,P as Ft,Pt as It,Q as Lt,Sr as Rt,St as zt,Tr as Bt,V as Vt,W as Ht,X as Ut,Xn as Wt,Y as Gt,Zn as Kt,_t as qt,ar as Jt,bn as Yt,bt as Xt,ct as Zt,er as Qt,et as $t,ft as en,gt as tn,ht as nn,ir as rn,j as an,jr as H,jt as on,k as U,kr as sn,kt as cn,lt as ln,mt as un,nr as dn,ot as fn,pr as pn,q as mn,sr as hn,st as gn,tn as _n,tr as vn,tt as yn,ut as bn,vt as xn,wr as W,wt as Sn,xn as Cn,xr as wn,xt as Tn,yt as En,z as Dn}from"./shaped-data-BRffby3g.js";import{$ as On,A as kn,B as An,Ct as jn,Dt as G,Et as Mn,G as Nn,H as Pn,J as Fn,K as In,N as Ln,O as Rn,Ot as K,P as zn,Q as Bn,R as Vn,St as Hn,Tt as Un,U as Wn,V as Gn,W as Kn,X as qn,Y as Jn,Z as Yn,_t as Xn,a as Zn,at as Qn,bt as $n,ct as er,dt as tr,et as nr,ft as rr,gt as ir,ht as ar,i as or,it as sr,l as cr,lt as lr,m as ur,mt as dr,n as fr,nt as pr,o as mr,ot as hr,pt as gr,q as _r,r as vr,rt as yr,st as br,tt as xr,ut as Sr,vt as Cr,wt as wr,xt as Tr,yt as Er,z as Dr}from"./reader-DAdKx3ZF.js";import{A as Or,C as kr,D as Ar,E as jr,F as Mr,I as Nr,L as Pr,M as Fr,N as Ir,P as Lr,R as Rr,S as zr,T as Br,U as Vr,W as Hr,X as Ur,Z as Wr,a as Gr,c as Kr,d as qr,g as Jr,j as Yr,l as Xr,m as Zr,p as Qr,v as $r,w as ei,x as ti}from"./browser-connection-DMLe-0pv.js";import{a as ni,t as ri}from"./live-ingress-OuSlQ6q7.js";import{t as ii}from"./trace-record-Doo6lYDI.js";import{n as ai,r as oi,t as si}from"./crypto-DjhcOJmp.js";import{D as ci,E as li,O as ui,T as di,_ as fi,c as pi,d as mi,i as hi,l as gi,u as _i,x as vi,y as yi}from"./turn-client-CMgd-m7p.js";import{n as bi,t as xi}from"./live-messages-eYYz6aFz.js";import{n as Si,r as Ci}from"./lent-keys-C32ems-I.js";import{Ct as wi,Dt as Ti,St as Ei,bt as Di,gt as Oi,ht as ki,vt as Ai,xt as ji,yt as Mi}from"./index-DxaSpTtM.js";function Ni(){return{given:new Set,remote:new Map}}var Pi=/[\p{L}\p{N}_.+-]/u,Fi=/[\p{L}\p{N}_-]/u,Ii=/(?:https?:\/\/|www\.)[^\s'"<>)\]]+/gi,Li=/\b[A-Z]{2}\d{2}[A-Z0-9]{10,30}\b/g,Ri=/[/?#]/;function zi(e,t){let n=t;for(;n<e.length;){let t=String.fromCodePoint(e.codePointAt(n)??0);if(!Fi.test(t))break;n+=t.length}return n}function Bi(e,t){let n=zi(e,t);if(n===t)return-1;let r=1;for(;e.charAt(n)===`.`;){let t=zi(e,n+1);if(t===n+1)break;n=t,r+=1}return r>1?n:-1}function Vi(e){let t=e.length;for(;t>0&&(e.charAt(t-1)===`.`||e.charAt(t-1)===`,`);)--t;return e.slice(0,t)}function Hi(e){let t=[],n=e.indexOf(`@`);for(;n>=0;){let r=n;for(;r>0&&Pi.test(e.charAt(r-1));)--r;let i=r<n?Bi(e,n+1):-1;i>=0?(t.push({key:`email:${e.slice(r,i).toLowerCase()}`,start:r,end:i}),n=e.indexOf(`@`,i)):n=e.indexOf(`@`,n+1)}return t}function Ui(e){let t=e.replace(/^https?:\/\//i,``),n=t.search(Ri),r=n<0?t:t.slice(0,n);return Vi(r.slice(r.lastIndexOf(`@`)+1).replace(/:\d*$/,``).toLowerCase()).replace(/^www\./,``)}function Wi(e){let t=Hi(e),n=[],r=0;for(let{start:i,end:a}of t)n.push(e.slice(r,i),` `.repeat(a-i)),r=a;n.push(e.slice(r));let i=n.join(``),a=[...t];for(let e of[...i.matchAll(Ii)]){let t=Ui(e[0]);t&&a.push({key:`host:${t}`,start:e.index,end:e.index+e[0].length})}for(let e of[...i.matchAll(Li)])a.push({key:`account:${e[0].toLowerCase()}`,start:e.index,end:e.index+e[0].length});return a}function Gi(e){let t=e.trimStart().charAt(0);if(t===`{`||t===`[`)try{return JSON.parse(e)}catch{return}}var Ki=32;function qi(e,t,n=0){if(!(n>Ki)){if(typeof e==`string`){let r=Gi(e);r===void 0?t(e):qi(r,t,n+1)}else if(Array.isArray(e))for(let r of e)qi(r,t,n+1);else if(e&&typeof e==`object`)for(let r of Object.values(e))qi(r,t,n+1)}}function Ji(e,t=!1){let n=new Set;return qi(e,e=>{let r=e.trim(),i=Wi(r),[a]=i,o=i.length===1&&a?.start===0&&a.end===r.length;if(!(t&&o))for(let{key:e}of i)n.add(e)}),n}function Yi(e,t){for(let n of Ji(t))e.given.add(n)}function Xi(e,t,n){for(let r of t)r.role===`assistant`||r.role===`tool`||n.has(r)||Yi(e,Kt(r).text)}function Zi(e,t,n){Yi(e,t.system),n.has(t.input)||Yi(e,Kt(t.input).text),Xi(e,t.history??[],n)}function Qi(e,t,n){if(!Be(n.origin)){Yi(e,[t.finding,t.data]);return}let r=Gi(t.finding),i=new Set([...r===void 0?Ji(t.finding):Ji(r,!0),...Ji(t.data,!0)]);for(let t of i)e.remote.has(t)||e.remote.set(t,n.tool)}function $i(e,t,n,r){if(!e||e.remote.size===0)return{verdict:{action:`allow`}};let i=[...Ji(t)].filter(t=>e.remote.has(t)&&!e.given.has(t));if(i.length===0)return{verdict:{action:`allow`}};let a=i.map(e=>e.slice(e.indexOf(`:`)+1)),o=a.map(e=>({rule:hn.remoteDestination,severity:`high`,match:e})),s={destination:a.join(`, `),sources:[...new Set(i.map(t=>e.remote.get(t)??``))].join(`, `)},c=n.taint?.remoteDestination??`off`;return c===`block`?{verdict:{action:`block`,hits:o,rejection:V(`taint.destination_blocked`,s,r)}}:{verdict:{action:`flag`,hits:o},...c===`confirm`?{confirm:V(`taint.destination_confirm`,s,r)}:{}}}var ea={image:`thought.omitted_image`,link:`thought.omitted_link`,instructions:`thought.omitted_instructions`},ta={rule:rn.ungiven_images,severity:`high`},na={rule:rn.ungiven_links,severity:`high`},ra={rule:rn.marker_leak,severity:`high`},ia={rule:rn.prompt_leak,severity:`high`};function aa(e,t,n=!1){let r=e.pieces[0];for(let i of e.pieces){if(i.raw>t||n&&i.raw===t&&t>0)break;r=i}return r?r.mark?n?r.mark.end:r.mark.start:r.shown+t-r.raw:t}function oa(e){let t=[];for(let n of[...e].sort((e,t)=>e.start-t.start)){let e=t.at(-1);e&&n.start<e.end?e.end=Math.max(e.end,n.end):t.push({...n})}return t}var sa=8,ca=16;function la(e){let{omit:t={},canary:n,privateSystem:r,ends:i,given:a,labels:o}=e,s=[...t.markers?[`marker_leak`]:[],...t.images?[`ungiven_images`]:[],...t.links?[`ungiven_links`]:[]],c=t.imagesRead??t.images!==void 0,l=n??e.planted,u=Et({canary:l,labels:o}),d=e=>({...e,...a?{given:a}:{}});function f(e,t){let n=V(ea[e],{},o);return/\s$/.test(t)?n.trimStart():n}let p=n||r?e.carry??``:``,m=``,h,g,_=0,v=0,y,b=[],x=0,S=!1,C=0,w=new Map;function T(e){return h=s.length>0?wr({detect:s,allow:{ungiven_images:t.images??{},ungiven_links:t.links??{}},skipImages:c,...a?{given:a}:{},...u?{note:u}:{}}):void 0,g=n?vt(n):void 0,_=0,v=0,ee(e)}function ee(e){v+=e.length;let t=(h?.push(e).length??0)>0,n=g?.push(e)??!1,i=!1;if(r){let e=(p+m).slice(0,v),t=Tt(e,_);i=wt(e.slice(t),r,l).length>0,_=e.length}return t||n||i}function E(e){let i=[];if(t.images)for(let n of bn(e,d(t.images)))i.push({...n,kind:`image`,hit:ta});if(t.links)for(let n of en(e,d(t.links),c))i.push({...n,kind:`link`,hit:na});if(t.markers){let t=[new RegExp($t.source,`gi`),...u?[yn(u)]:[]];for(let n of t.flatMap(t=>[...e.matchAll(t)])){let e=n.index;i.push({start:e,end:e+n[0].length,kind:`instructions`,hit:ra})}}if(n)for(let[t,r]of En(e,n))i.push({start:t,end:r,kind:`instructions`,hit:dn});if(r)for(let[t,n]of wt(e,r,l))i.push({start:t,end:n,kind:`instructions`,hit:ia});return i}function D(e){return b.find(t=>t.start<e&&e<t.end)}function te(e,t){let n=p+m,r=``,i=e;for(let a of b)a.end<=e||a.start>=t||(r+=n.slice(i,a.start)+a.raw,i=a.end);return r+n.slice(i,t)}function O(){let e=p+m;for(let t=un;;t*=2){let n=p.length,i=0;for(let e=b.length-1;n>0&&i<t;){let r=b[e];if(r&&r.end>n)e--;else if(r&&r.end===n)i+=r.raw.length,n=r.start,e--;else{let e=Math.max(r?.end??0,n-(t-i));i+=n-e,n=e}}if(b=b.filter(e=>e.end>n),b.length===0)return;let a={text:``,held:0,pieces:[]},o=n;for(let t of[...b,void 0]){let n=t?t.start:e.length;if(n>o&&a.pieces.push({raw:a.text.length,shown:o}),o<=p.length&&p.length<=n&&(a.held=a.text.length+p.length-o),a.text+=e.slice(o,n),!t)break;a.pieces.push({raw:a.text.length,shown:t.start,mark:t}),a.text+=t.raw,o=t.end}if(!r||n===0||Tt(a.text,a.held)>0)return a}}function ne(){let e=O();if(!e)return[];let t=[];if(n)for(let[r,i]of En(e.text,n))t.push([r,i,dn]);if(r)for(let[n,i]of wt(e.text,r,l))t.push([n,i,ia]);let i=[];for(let[n,r,a]of t){if(r<=e.held)continue;let t=aa(e,n),o=aa(e,r,!0),s=!1;for(let e=Math.max(t,p.length);e<o&&!s;e++)s=!b.some(t=>t.start<=e&&e<t.end);s&&i.push({start:t,end:o,kind:`instructions`,hit:a})}return i}function re(){return oa([...E(p+m),...ne()])}function k(){return re().filter(({end:e})=>e>p.length)}function A(e,t=!1){let n=D(e);return n?t?n.end:n.start:e}function ie(e){let t=k(),n=p+m,r=t.at(-1),a=!e&&r!==void 0&&r.end>=n.length?r:void 0,o=a?t.slice(0,-1):t,s=b.filter(e=>e.end<=p.length),c=``,l=p.length,u=e=>{let t=p.length+c.length-l;for(let n of b)n.start>=l&&n.end<=e&&s.push({...n,start:n.start+t,end:n.end+t});c+=n.slice(l,Math.max(l,e)),l=Math.max(l,e)};for(let{start:e,end:t,kind:r,hit:a}of o){u(A(e)),S=i?.has(a.rule)??!1;let o=S?n.length:Math.max(l,A(t,!0)),d=f(r,p+c),m=p.length+c.length;if(s.push({start:m,end:m+d.length,raw:te(l,o)}),c+=d,w.set(a.rule,a),l=o,S)break}return y=void 0,a&&!S&&(u(A(a.start)),y=p.length+c.length),u(n.length),b=s,m=c,x=0,o.length>0}function j(){let e=re()[0],t=e?Math.max(0,A(e.start)-p.length):0,n=m.slice(0,t),r=f(e?.kind??`instructions`,p+n),i=p.length+t,a=te(i,p.length+m.length);b=b.filter(e=>e.end<=i),b.push({start:i,end:i+r.length,raw:a}),m=n+r,x=0,e&&w.set(e.hit.rule,e.hit),y=void 0,S=!0}function ae(){let e=p+m;return y===void 0?e:e.slice(0,y)}function oe(){for(let e=0;e<sa&&!(C>=ca);e++){let e=new Set(b.map(e=>e.start));if(!ie(!1)){if(y===void 0)break;return}if(S||(b.some(t=>!e.has(t.start))&&C++,!T(ae())))return}j()}function se(){let e=p.length+m.length,t=h?h.holdFrom():e,i=n?ce(n):e,a=r?p.length+It(m,r,l):e,o=Math.min(t,i,a,ue()??e,y??e);return A(o<p.length?o:p.length+on(m,o-p.length))}function ce(e){let t=Math.max(p.length,x),n=Math.max(0,t-nn),r=n+Tn(le(n),e);if(r<t&&t>p.length){let t=Math.max(0,p.length-nn);r=t+Tn(le(t),e)}return x=Math.min(r,p.length+m.length-nn),Math.max(p.length,r)}function le(e){return e<p.length?p.slice(e)+m:m.slice(e-p.length)}function ue(){let e=O();if(!e)return;let t=e.text.slice(e.held),i=n?xn(t,n,e.text.slice(0,e.held)):t.length,a=r?It(t,r,l):t.length;return aa(e,e.held+Math.min(i,a))}function de(e){let t={text:e,hits:[...w.values()]};return w=new Map,t}return T(p),{push(e){if(S||!e||(m+=e,(y!==void 0||ee(e)||ne().length>0)&&oe(),S))return de(``);let t=Math.max(0,se()-p.length),n=m.slice(0,t);return p+=n,m=m.slice(t),de(n)},flush(){if(!S){for(let e=0;e<sa&&!S&&ie(!0);e++);!S&&m&&(E(p+m).length>0||ne().length>0)&&j()}let e=m,t=p+m;p=n||r?bt(t,n,r):``;let i=p.length-t.length;return b=b.filter(e=>e.start+i>=0).map(e=>({...e,start:e.start+i,end:e.end+i})),m=``,x=0,y=void 0,S=!1,C=0,T(p),de(e)},carryOut:()=>p}}function ua(...e){let t=e.filter(e=>e!==void 0);return t.length===0?{}:{found:{action:t.reduce((e,t)=>Ht(e,t.action),`allow`),hits:[...new Map(t.flatMap(({hits:e})=>e).map(e=>[e.rule,e])).values()]}}}function da(e,t,n,r){let i=()=>jn(`thought`,t,n,r),a=i();if(!a)return e;let o=0,s=0,c=!1;function l(e){if(c||!a)return{text:``};let t=e?o:Math.max(s,a.holdFrom()),{action:n,text:r=``,hits:i,taken:l}=a.take(s,t,e);return c=n===`block`,s+=l,{text:r,...n===`allow`?{}:{found:{action:n,hits:i}}}}return{push(t){o+=t.length,a?.push(t);let{text:n,found:r}=l(!1),i=e?e.push(n):{text:n,hits:[]};return{text:i.text,hits:i.hits,...ua(r,i.found)}},flush(){let{text:t,found:n}=l(!0),r=e?.push(t),u=e?e.flush():{text:t,hits:[]};return a=i(),o=0,s=0,c=!1,{text:(r?.text??``)+u.text,hits:[...new Map([...r?.hits??[],...u.hits].map(e=>[e.rule,e])).values()],...ua(n,r?.found,u.found)}},carryOut:()=>e?.carryOut()??``}}var fa={canary_leak:dn,prompt_leak:ia,marker_leak:ra,ungiven_images:ta,ungiven_links:na},pa=[`marker_leak`,`ungiven_images`,`ungiven_links`];function ma(e,t){let{canary:n,privateSystem:r}=e,i=n?vt(n):void 0,a=``,o=new Set;return{read(e){let n=Tt(a+e,a.length);a+=e;let s=[];i?.push(e)&&s.push(dn),r&&wt(a.slice(n),r,t).length>0&&s.push(ia);let c=s.filter(e=>!o.has(e.rule));for(let e of c)o.add(e.rule);return c},reset(){i=n?vt(n):void 0,a=``,o=new Set}}}function ha(e,t,n,r){let i=ma(n,r),a=new Map(Object.entries(fa).map(([e,n])=>[n.rule,t[e].thought]));function o(e,t){let n=[...t,...e.hits.filter(e=>a.has(e.rule))];if(n.length===0)return e;let r=n.reduce((e,t)=>Ht(e,a.get(t.rule)??`ignore`),e.found?.action??`allow`);return{text:e.text,hits:e.hits.filter(e=>!a.has(e.rule)),found:{action:r,hits:[...e.found?.hits??[],...n]}}}return{push:t=>o(e.push(t),i.read(t)),flush(){return i.reset(),o(e.flush(),[])},carryOut:()=>e.carryOut()}}async function ga(e,t,n){let{detect:r}=e,i=pa.filter(e=>_a(r,e)),a=ya(r,t,_a),o=ya(r,t,(e,t)=>e[t].thought===`flag`),s=i.length>0||ba(a)||ba(o),c=Vt(e,t);(s||Ft([`thought`],r,c))&&await Un();let l=s?la({omit:va(e),...a,...xa(r),...Sa(t),...n?{carry:n}:{}}):void 0;return da(l&&ha(l,r,o,t.canary),r,c,i)}function _a(e,t){return e[t].thought===`redact`||e[t].thought===`block`}function va({detect:e,allow:t}){return{..._a(e,`marker_leak`)?{markers:!0}:{},..._a(e,`ungiven_images`)?{images:t.ungiven_images}:{},..._a(e,`ungiven_links`)?{links:t.ungiven_links}:{},imagesRead:e.ungiven_images.thought!==`ignore`}}function ya(e,t,n){let r=n(e,`canary_leak`)&&!t.canaryGiven&&t.canary,i=n(e,`prompt_leak`)&&t.privateSystem;return{...r?{canary:r}:{},...i?{privateSystem:i}:{}}}function ba(e){return e.canary!==void 0||e.privateSystem!==void 0}function xa(e){let t=new Set(Object.entries(fa).filter(([t])=>e[t].thought===`block`).map(([,e])=>e.rule));return t.size>0?{ends:t}:{}}function Sa({canary:e,givenUrls:t,labels:n}){return{...e?{planted:e}:{},...t?{given:t}:{},...n?{labels:n}:{}}}var Ca={rule:`live.untranscribed-audio`,severity:`high`};async function wa(e,t,n,r,i){let a=M(e.guardrails),o={stage:`live_outbound`,trust:`untrusted`,profileId:e.id,...Dn(a.detect,{canary:t,privateSystem:n}),...e.labels?{labels:e.labels}:{},...r?{givenUrls:r}:{},...i?{ownTools:i}:{}},s=await ga(a,o);return{policy:a,context:o,gate:await $n(a,o,`live_reply`),held:[],releasedTo:0,withholdVisible:!1,...s?{thoughts:s}:{}}}function Ta(e){let t=e.gate?.carryOut();e.gate=Tr(e.policy,e.context,`live_reply`,t),e.held=[],e.releasedTo=0,e.withholdVisible=!1,e.promptLeaks=void 0}function Ea(e,t,n=[]){let r=Mn(`live_outbound`,`untrusted`,t,`block`);return{action:`withhold`,error:new R(`safety`,e),events:[...n,...r?[r]:[]]}}function Da(e){return e.accumulated().length-e.unreleased().length}function Oa(e,t,n,r,i=!1){let a=t.accumulated();for(let t=e.held[0];t!==void 0;t=e.held[0]){let{event:o}=t;if(o.type!==`media`){let i=Math.max(t.start,e.releasedTo),s=Math.min(t.end,n);s>i&&(r.push({...o,text:a.slice(i,s)}),e.releasedTo=s)}if(t.end>n&&!(i&&o.type===`media`))return;o.type===`media`&&r.push(o),e.held.shift()}}function ka(e,t,n,r){if(!n.blocked){let i=n.found&&jt(`live_reply`,n.found);i&&r.push(G(i)),Oa(e,t,Da(t),r);return}let i=n.hits.filter(Ut);i.length>0&&(e.promptLeaks=i),e.withholdVisible=!0;let a=n.boundary?void 0:Mn(`live_outbound`,`untrusted`,n.hits,`block`);a&&r.push(a)}function Aa(e,t,n){e.withholdVisible||e.held.length===0||ka(e,t,t.flush(),n)}function ja(e,t,n,r){let i=t.accumulated().length;e.held.push({event:n,start:i,end:r?i:1/0})}function Ma(e,t){for(let n=e.held.length-1;n>=0;--n){let r=e.held[n];if(r===void 0||r.end!==1/0)return;r.end=t}}function Na(e,t,n,r){let i=n.text??``;if(!i)return;let a=t.accumulated().length;Ma(e,a+i.length),e.held.push({event:n,start:a,end:a+i.length});let o=t.process(i);e.withholdVisible||ka(e,t,o,r)}function Pa(e,t){let n=[],{gate:r}=e;if(!r){let{thoughts:n}=e;return Ra(n?t.flatMap(e=>e.type===`thought`?Fa(n.push(e.text),e):[e]):t)}let i=!1;for(let a of t){if(Sn(a)){i||=!!a.text,Na(e,r,a,n);continue}if(a.type===`media`){ja(e,r,a,i),e.withholdVisible||Oa(e,r,Da(r),n);continue}Aa(e,r,n),Ia(a)&&La(e,r,n);let t=a.type===`tool`?void 0:Gt(a,e.context,e.policy.detect,`live_reply`);if(t?.stop)return Ea(Lt(t.hits),t.hits,n);if(t){let e=jt(`live_reply`,{action:`flag`,hits:t.hits});e&&n.push(G(e))}a.type===`thought`&&e.thoughts?n.push(...Fa(e.thoughts.push(a.text),a)):n.push(a)}return Ra(n)}function Fa({text:e,hits:t,found:n},r){let i=n&&jt(`thought`,n),a=Mn(`thought`,`untrusted`,t,`redact`);return[...i?[G(i)]:[],...a?[a]:[],...e?[{...r,text:e}]:[]]}function Ia(e){return e.type===`done`&&e.stop?.kind===`generation_complete`}function La(e,t,n){let r=t.accumulated().length;e.withholdVisible||r===0||Da(t)<r||Oa(e,t,r,n,!0)}function Ra(e){return e.length===0?{action:`idle`}:{action:`emit`,events:e}}function za(e,t,n){let{detect:r,blockedReply:i}=e.policy,a=w({text:t.accumulated()},r,{boundary:`live_reply`,...e.withholdVisible?{reportedTo:Da(t)}:{},scope:Vt(e.policy,e.context)}),o=t.accumulated().slice(0,e.releasedTo),s=pe(a,e.promptLeaks),c=s&&s!==a.blocked?Mn(`live_outbound`,`untrusted`,s,`block`):void 0,l=[...n,...a.events.map(G),...c?[c]:[]];if(s){if(i.onBlock===`refuse`){let t=te(o,e.context.labels);return{action:`emit`,events:[...l,{type:`text`,text:t}]}}return{action:`withhold`,error:new R(`safety`,mn.egress),events:l}}if(a.rewritten){let e=k(o,a.payload.text);return{action:`emit`,events:[...l,{type:`text`,text:e}]}}return Oa(e,t,t.accumulated().length,l,!0),Ra(l)}function Ba(e,t){if(e.held.length===0)return t;let n=Mn(`live_outbound`,`untrusted`,[Ca],`block`);return n?[...t,n]:t}function Va(e,t){let n=[];return Aa(e,t,n),t.accumulated()?za(e,t,n):Ra(Ba(e,n))}function Ha(e){let t=e.thoughts?Fa(e.thoughts.flush(),{type:`thought`,text:``}):[];if(!e.gate)return Ra(t);let n=Va(e,e.gate);return Ta(e),t.length===0?n:n.action===`idle`?{action:`emit`,events:t}:{...n,events:[...t,...n.events??[]]}}function Ua(e){e.thoughts?.flush(),Ta(e)}var Wa=[1e3,2e3,4e3,8e3],Ga=5e3,Ka=Wa.length,qa=1e3,Ja=new Set([408,429,500,502,503,504,529]),Ya=(e,t)=>new Promise((n,r)=>{if(t?.aborted){r(Xa(t));return}let i=setTimeout(()=>{t?.removeEventListener(`abort`,a),n()},e);function a(){clearTimeout(i),r(Xa(t))}t?.addEventListener(`abort`,a,{once:!0})});function Xa(e){return e.reason??new DOMException(`The operation was aborted.`,`AbortError`)}function Za(e){return Ja.has(e)}function Qa(e){let t=yt(e);return t instanceof R&&t.kind===`network`}function $a(e){return Wa[Math.min(e,Wa.length-1)]}function eo(e,t=Date.now()){let n=e.get(`retry-after-ms`),r=e.get(`retry-after`),i;if(n!==null&&n.trim()!==``&&Number.isFinite(Number(n)))i=Number(n);else if(r!==null&&r.trim()!==``){let e=Number(r);i=Number.isFinite(e)?e*qa:Date.parse(r)-t}if(!(i===void 0||Number.isNaN(i)||i<0))return i}function to(e,t=Ya,n=()=>1/0){return async(r,i)=>{let a=0;for(let o=0;;o++){let s=Math.min(Ga-a,n()),c;try{let t=await e(r,i);if(!Za(t.status)||(c=eo(t.headers)??$a(o),c>s||o>=Ka))return t;await t.body?.cancel()}catch(e){if(c=$a(o),!Qa(e)||c>s||o>=Ka)throw e}await t(c,i?.signal),a+=c}}}var no=`[DONE]`;function ro(e){if(e&&typeof e==`object`&&!Array.isArray(e))return e}function io(e,t){let n=e.startsWith(`data:`)?e.slice(5).replace(/^ /,``):e,r={};if(t&&(r.sseEvent=t),n===no)return r.eventType=`sse_done`,r;try{let e=JSON.parse(n),t=ro(e);return t?{...t,...r}:(r.eventType=`sse_unparsed`,r.data=e,r)}catch{return r.eventType=`sse_unparsed`,r.data=n,r}}function ao(e,t=``){let n=[],r=t,i=[],a=!1,o=0,s=/\r\n|\r|\n/g,c=0;for(let t=s.exec(e);t&&(t[0]!==`\r`||t.index!==e.length-1);t=s.exec(e)){let s=e.slice(c,t.index);if(c=t.index+t[0].length,!s)a&&n.push(io(i.join(`
|
|
2
|
+
import{t as e}from"./preload-helper-DpV6A1kQ.js";import{C as t,D as n,E as r,O as i,T as a,b as o,c as s,d as c,g as l,h as u,p as d,v as f,x as p}from"./schemas-D7cgkv3L.js";import{$n as m,A as h,An as g,At as _,Bt as v,C as y,Cn as b,Dn as x,Dt as S,En as C,Fn as w,Ft as T,Gt as ee,Hn as E,Ht as D,In as te,It as O,Jn as ne,L as re,Ln as k,Lt as A,Mn as ie,Mt as j,Nn as ae,Nt as oe,On as se,Ot as ce,Pn as le,Pt as ue,Qn as de,Qt as fe,Rn as pe,Rt as me,Sn as he,Tn as M,Tt as ge,Un as _e,Ut as ve,Vt as ye,Wn as be,Wt as N,Xn as xe,Xt as Se,Yn as P,Zn as Ce,_n as we,_t as Te,an as Ee,at as De,bt as Oe,ct as ke,dt as Ae,en as je,et as Me,fn as Ne,ft as F,gn as Pe,gt as Fe,hn as Ie,ht as Le,in as Re,it as ze,jn as Be,jt as Ve,kn as He,kt as Ue,lt as We,mn as Ge,mt as I,nn as Ke,nr as qe,nt as Je,on as Ye,ot as Xe,p as Ze,pn as Qe,pt as $e,qn as et,rt as L,sn as tt,st as nt,tn as rt,tr as it,tt as at,un as ot,ut as st,v as ct,vn as lt,vt as ut,xt as dt,yt as ft,zt as pt}from"./tool-schema-BHHcOFff.js";import{c as R,t as mt}from"./host-patterns-F-KZIzkF.js";import{A as z,Ar as B,At as ht,Cn as gt,Cr as _t,Ct as vt,Dr as yt,Dt as bt,E as xt,Er as St,Et as Ct,Ft as wt,It as Tt,J as Et,Kn as Dt,Lr as V,M as Ot,Mr as kt,Mt as At,N as jt,Nn as Mt,Nt,O as Pt,P as Ft,Pt as It,Q as Lt,Sr as Rt,St as zt,Tr as Bt,V as Vt,W as Ht,X as Ut,Xn as Wt,Y as Gt,Zn as Kt,_t as qt,ar as Jt,bn as Yt,bt as Xt,ct as Zt,er as Qt,et as $t,ft as en,gt as tn,ht as nn,ir as rn,j as an,jr as H,jt as on,k as U,kr as sn,kt as cn,lt as ln,mt as un,nr as dn,ot as fn,pr as pn,q as mn,sr as hn,st as gn,tn as _n,tr as vn,tt as yn,ut as bn,vt as xn,wr as W,wt as Sn,xn as Cn,xr as wn,xt as Tn,yt as En,z as Dn}from"./shaped-data-BRffby3g.js";import{$ as On,A as kn,B as An,Ct as jn,Dt as G,Et as Mn,G as Nn,H as Pn,J as Fn,K as In,N as Ln,O as Rn,Ot as K,P as zn,Q as Bn,R as Vn,St as Hn,Tt as Un,U as Wn,V as Gn,W as Kn,X as qn,Y as Jn,Z as Yn,_t as Xn,a as Zn,at as Qn,bt as $n,ct as er,dt as tr,et as nr,ft as rr,gt as ir,ht as ar,i as or,it as sr,l as cr,lt as lr,m as ur,mt as dr,n as fr,nt as pr,o as mr,ot as hr,pt as gr,q as _r,r as vr,rt as yr,st as br,tt as xr,ut as Sr,vt as Cr,wt as wr,xt as Tr,yt as Er,z as Dr}from"./reader-Ql1nrrAA.js";import{A as Or,C as kr,D as Ar,E as jr,F as Mr,I as Nr,L as Pr,M as Fr,N as Ir,P as Lr,R as Rr,S as zr,T as Br,U as Vr,W as Hr,X as Ur,Z as Wr,a as Gr,c as Kr,d as qr,g as Jr,j as Yr,l as Xr,m as Zr,p as Qr,v as $r,w as ei,x as ti}from"./browser-connection-IC3QKsFq.js";import{a as ni,t as ri}from"./live-ingress-OuSlQ6q7.js";import{t as ii}from"./trace-record-Doo6lYDI.js";import{n as ai,r as oi,t as si}from"./crypto-DjhcOJmp.js";import{D as ci,E as li,O as ui,T as di,_ as fi,c as pi,d as mi,i as hi,l as gi,u as _i,x as vi,y as yi}from"./turn-client-D36i6KKG.js";import{n as bi,t as xi}from"./live-messages-ConwEl7T.js";import{n as Si,r as Ci}from"./lent-keys-C32ems-I.js";import{Ct as wi,Dt as Ti,St as Ei,bt as Di,gt as Oi,ht as ki,vt as Ai,xt as ji,yt as Mi}from"./index-CCj0zkrC.js";function Ni(){return{given:new Set,remote:new Map}}var Pi=/[\p{L}\p{N}_.+-]/u,Fi=/[\p{L}\p{N}_-]/u,Ii=/(?:https?:\/\/|www\.)[^\s'"<>)\]]+/gi,Li=/\b[A-Z]{2}\d{2}[A-Z0-9]{10,30}\b/g,Ri=/[/?#]/;function zi(e,t){let n=t;for(;n<e.length;){let t=String.fromCodePoint(e.codePointAt(n)??0);if(!Fi.test(t))break;n+=t.length}return n}function Bi(e,t){let n=zi(e,t);if(n===t)return-1;let r=1;for(;e.charAt(n)===`.`;){let t=zi(e,n+1);if(t===n+1)break;n=t,r+=1}return r>1?n:-1}function Vi(e){let t=e.length;for(;t>0&&(e.charAt(t-1)===`.`||e.charAt(t-1)===`,`);)--t;return e.slice(0,t)}function Hi(e){let t=[],n=e.indexOf(`@`);for(;n>=0;){let r=n;for(;r>0&&Pi.test(e.charAt(r-1));)--r;let i=r<n?Bi(e,n+1):-1;i>=0?(t.push({key:`email:${e.slice(r,i).toLowerCase()}`,start:r,end:i}),n=e.indexOf(`@`,i)):n=e.indexOf(`@`,n+1)}return t}function Ui(e){let t=e.replace(/^https?:\/\//i,``),n=t.search(Ri),r=n<0?t:t.slice(0,n);return Vi(r.slice(r.lastIndexOf(`@`)+1).replace(/:\d*$/,``).toLowerCase()).replace(/^www\./,``)}function Wi(e){let t=Hi(e),n=[],r=0;for(let{start:i,end:a}of t)n.push(e.slice(r,i),` `.repeat(a-i)),r=a;n.push(e.slice(r));let i=n.join(``),a=[...t];for(let e of[...i.matchAll(Ii)]){let t=Ui(e[0]);t&&a.push({key:`host:${t}`,start:e.index,end:e.index+e[0].length})}for(let e of[...i.matchAll(Li)])a.push({key:`account:${e[0].toLowerCase()}`,start:e.index,end:e.index+e[0].length});return a}function Gi(e){let t=e.trimStart().charAt(0);if(t===`{`||t===`[`)try{return JSON.parse(e)}catch{return}}var Ki=32;function qi(e,t,n=0){if(!(n>Ki)){if(typeof e==`string`){let r=Gi(e);r===void 0?t(e):qi(r,t,n+1)}else if(Array.isArray(e))for(let r of e)qi(r,t,n+1);else if(e&&typeof e==`object`)for(let r of Object.values(e))qi(r,t,n+1)}}function Ji(e,t=!1){let n=new Set;return qi(e,e=>{let r=e.trim(),i=Wi(r),[a]=i,o=i.length===1&&a?.start===0&&a.end===r.length;if(!(t&&o))for(let{key:e}of i)n.add(e)}),n}function Yi(e,t){for(let n of Ji(t))e.given.add(n)}function Xi(e,t,n){for(let r of t)r.role===`assistant`||r.role===`tool`||n.has(r)||Yi(e,Kt(r).text)}function Zi(e,t,n){Yi(e,t.system),n.has(t.input)||Yi(e,Kt(t.input).text),Xi(e,t.history??[],n)}function Qi(e,t,n){if(!Be(n.origin)){Yi(e,[t.finding,t.data]);return}let r=Gi(t.finding),i=new Set([...r===void 0?Ji(t.finding):Ji(r,!0),...Ji(t.data,!0)]);for(let t of i)e.remote.has(t)||e.remote.set(t,n.tool)}function $i(e,t,n,r){if(!e||e.remote.size===0)return{verdict:{action:`allow`}};let i=[...Ji(t)].filter(t=>e.remote.has(t)&&!e.given.has(t));if(i.length===0)return{verdict:{action:`allow`}};let a=i.map(e=>e.slice(e.indexOf(`:`)+1)),o=a.map(e=>({rule:hn.remoteDestination,severity:`high`,match:e})),s={destination:a.join(`, `),sources:[...new Set(i.map(t=>e.remote.get(t)??``))].join(`, `)},c=n.taint?.remoteDestination??`off`;return c===`block`?{verdict:{action:`block`,hits:o,rejection:V(`taint.destination_blocked`,s,r)}}:{verdict:{action:`flag`,hits:o},...c===`confirm`?{confirm:V(`taint.destination_confirm`,s,r)}:{}}}var ea={image:`thought.omitted_image`,link:`thought.omitted_link`,instructions:`thought.omitted_instructions`},ta={rule:rn.ungiven_images,severity:`high`},na={rule:rn.ungiven_links,severity:`high`},ra={rule:rn.marker_leak,severity:`high`},ia={rule:rn.prompt_leak,severity:`high`};function aa(e,t,n=!1){let r=e.pieces[0];for(let i of e.pieces){if(i.raw>t||n&&i.raw===t&&t>0)break;r=i}return r?r.mark?n?r.mark.end:r.mark.start:r.shown+t-r.raw:t}function oa(e){let t=[];for(let n of[...e].sort((e,t)=>e.start-t.start)){let e=t.at(-1);e&&n.start<e.end?e.end=Math.max(e.end,n.end):t.push({...n})}return t}var sa=8,ca=16;function la(e){let{omit:t={},canary:n,privateSystem:r,ends:i,given:a,labels:o}=e,s=[...t.markers?[`marker_leak`]:[],...t.images?[`ungiven_images`]:[],...t.links?[`ungiven_links`]:[]],c=t.imagesRead??t.images!==void 0,l=n??e.planted,u=Et({canary:l,labels:o}),d=e=>({...e,...a?{given:a}:{}});function f(e,t){let n=V(ea[e],{},o);return/\s$/.test(t)?n.trimStart():n}let p=n||r?e.carry??``:``,m=``,h,g,_=0,v=0,y,b=[],x=0,S=!1,C=0,w=new Map;function T(e){return h=s.length>0?wr({detect:s,allow:{ungiven_images:t.images??{},ungiven_links:t.links??{}},skipImages:c,...a?{given:a}:{},...u?{note:u}:{}}):void 0,g=n?vt(n):void 0,_=0,v=0,ee(e)}function ee(e){v+=e.length;let t=(h?.push(e).length??0)>0,n=g?.push(e)??!1,i=!1;if(r){let e=(p+m).slice(0,v),t=Tt(e,_);i=wt(e.slice(t),r,l).length>0,_=e.length}return t||n||i}function E(e){let i=[];if(t.images)for(let n of bn(e,d(t.images)))i.push({...n,kind:`image`,hit:ta});if(t.links)for(let n of en(e,d(t.links),c))i.push({...n,kind:`link`,hit:na});if(t.markers){let t=[new RegExp($t.source,`gi`),...u?[yn(u)]:[]];for(let n of t.flatMap(t=>[...e.matchAll(t)])){let e=n.index;i.push({start:e,end:e+n[0].length,kind:`instructions`,hit:ra})}}if(n)for(let[t,r]of En(e,n))i.push({start:t,end:r,kind:`instructions`,hit:dn});if(r)for(let[t,n]of wt(e,r,l))i.push({start:t,end:n,kind:`instructions`,hit:ia});return i}function D(e){return b.find(t=>t.start<e&&e<t.end)}function te(e,t){let n=p+m,r=``,i=e;for(let a of b)a.end<=e||a.start>=t||(r+=n.slice(i,a.start)+a.raw,i=a.end);return r+n.slice(i,t)}function O(){let e=p+m;for(let t=un;;t*=2){let n=p.length,i=0;for(let e=b.length-1;n>0&&i<t;){let r=b[e];if(r&&r.end>n)e--;else if(r&&r.end===n)i+=r.raw.length,n=r.start,e--;else{let e=Math.max(r?.end??0,n-(t-i));i+=n-e,n=e}}if(b=b.filter(e=>e.end>n),b.length===0)return;let a={text:``,held:0,pieces:[]},o=n;for(let t of[...b,void 0]){let n=t?t.start:e.length;if(n>o&&a.pieces.push({raw:a.text.length,shown:o}),o<=p.length&&p.length<=n&&(a.held=a.text.length+p.length-o),a.text+=e.slice(o,n),!t)break;a.pieces.push({raw:a.text.length,shown:t.start,mark:t}),a.text+=t.raw,o=t.end}if(!r||n===0||Tt(a.text,a.held)>0)return a}}function ne(){let e=O();if(!e)return[];let t=[];if(n)for(let[r,i]of En(e.text,n))t.push([r,i,dn]);if(r)for(let[n,i]of wt(e.text,r,l))t.push([n,i,ia]);let i=[];for(let[n,r,a]of t){if(r<=e.held)continue;let t=aa(e,n),o=aa(e,r,!0),s=!1;for(let e=Math.max(t,p.length);e<o&&!s;e++)s=!b.some(t=>t.start<=e&&e<t.end);s&&i.push({start:t,end:o,kind:`instructions`,hit:a})}return i}function re(){return oa([...E(p+m),...ne()])}function k(){return re().filter(({end:e})=>e>p.length)}function A(e,t=!1){let n=D(e);return n?t?n.end:n.start:e}function ie(e){let t=k(),n=p+m,r=t.at(-1),a=!e&&r!==void 0&&r.end>=n.length?r:void 0,o=a?t.slice(0,-1):t,s=b.filter(e=>e.end<=p.length),c=``,l=p.length,u=e=>{let t=p.length+c.length-l;for(let n of b)n.start>=l&&n.end<=e&&s.push({...n,start:n.start+t,end:n.end+t});c+=n.slice(l,Math.max(l,e)),l=Math.max(l,e)};for(let{start:e,end:t,kind:r,hit:a}of o){u(A(e)),S=i?.has(a.rule)??!1;let o=S?n.length:Math.max(l,A(t,!0)),d=f(r,p+c),m=p.length+c.length;if(s.push({start:m,end:m+d.length,raw:te(l,o)}),c+=d,w.set(a.rule,a),l=o,S)break}return y=void 0,a&&!S&&(u(A(a.start)),y=p.length+c.length),u(n.length),b=s,m=c,x=0,o.length>0}function j(){let e=re()[0],t=e?Math.max(0,A(e.start)-p.length):0,n=m.slice(0,t),r=f(e?.kind??`instructions`,p+n),i=p.length+t,a=te(i,p.length+m.length);b=b.filter(e=>e.end<=i),b.push({start:i,end:i+r.length,raw:a}),m=n+r,x=0,e&&w.set(e.hit.rule,e.hit),y=void 0,S=!0}function ae(){let e=p+m;return y===void 0?e:e.slice(0,y)}function oe(){for(let e=0;e<sa&&!(C>=ca);e++){let e=new Set(b.map(e=>e.start));if(!ie(!1)){if(y===void 0)break;return}if(S||(b.some(t=>!e.has(t.start))&&C++,!T(ae())))return}j()}function se(){let e=p.length+m.length,t=h?h.holdFrom():e,i=n?ce(n):e,a=r?p.length+It(m,r,l):e,o=Math.min(t,i,a,ue()??e,y??e);return A(o<p.length?o:p.length+on(m,o-p.length))}function ce(e){let t=Math.max(p.length,x),n=Math.max(0,t-nn),r=n+Tn(le(n),e);if(r<t&&t>p.length){let t=Math.max(0,p.length-nn);r=t+Tn(le(t),e)}return x=Math.min(r,p.length+m.length-nn),Math.max(p.length,r)}function le(e){return e<p.length?p.slice(e)+m:m.slice(e-p.length)}function ue(){let e=O();if(!e)return;let t=e.text.slice(e.held),i=n?xn(t,n,e.text.slice(0,e.held)):t.length,a=r?It(t,r,l):t.length;return aa(e,e.held+Math.min(i,a))}function de(e){let t={text:e,hits:[...w.values()]};return w=new Map,t}return T(p),{push(e){if(S||!e||(m+=e,(y!==void 0||ee(e)||ne().length>0)&&oe(),S))return de(``);let t=Math.max(0,se()-p.length),n=m.slice(0,t);return p+=n,m=m.slice(t),de(n)},flush(){if(!S){for(let e=0;e<sa&&!S&&ie(!0);e++);!S&&m&&(E(p+m).length>0||ne().length>0)&&j()}let e=m,t=p+m;p=n||r?bt(t,n,r):``;let i=p.length-t.length;return b=b.filter(e=>e.start+i>=0).map(e=>({...e,start:e.start+i,end:e.end+i})),m=``,x=0,y=void 0,S=!1,C=0,T(p),de(e)},carryOut:()=>p}}function ua(...e){let t=e.filter(e=>e!==void 0);return t.length===0?{}:{found:{action:t.reduce((e,t)=>Ht(e,t.action),`allow`),hits:[...new Map(t.flatMap(({hits:e})=>e).map(e=>[e.rule,e])).values()]}}}function da(e,t,n,r){let i=()=>jn(`thought`,t,n,r),a=i();if(!a)return e;let o=0,s=0,c=!1;function l(e){if(c||!a)return{text:``};let t=e?o:Math.max(s,a.holdFrom()),{action:n,text:r=``,hits:i,taken:l}=a.take(s,t,e);return c=n===`block`,s+=l,{text:r,...n===`allow`?{}:{found:{action:n,hits:i}}}}return{push(t){o+=t.length,a?.push(t);let{text:n,found:r}=l(!1),i=e?e.push(n):{text:n,hits:[]};return{text:i.text,hits:i.hits,...ua(r,i.found)}},flush(){let{text:t,found:n}=l(!0),r=e?.push(t),u=e?e.flush():{text:t,hits:[]};return a=i(),o=0,s=0,c=!1,{text:(r?.text??``)+u.text,hits:[...new Map([...r?.hits??[],...u.hits].map(e=>[e.rule,e])).values()],...ua(n,r?.found,u.found)}},carryOut:()=>e?.carryOut()??``}}var fa={canary_leak:dn,prompt_leak:ia,marker_leak:ra,ungiven_images:ta,ungiven_links:na},pa=[`marker_leak`,`ungiven_images`,`ungiven_links`];function ma(e,t){let{canary:n,privateSystem:r}=e,i=n?vt(n):void 0,a=``,o=new Set;return{read(e){let n=Tt(a+e,a.length);a+=e;let s=[];i?.push(e)&&s.push(dn),r&&wt(a.slice(n),r,t).length>0&&s.push(ia);let c=s.filter(e=>!o.has(e.rule));for(let e of c)o.add(e.rule);return c},reset(){i=n?vt(n):void 0,a=``,o=new Set}}}function ha(e,t,n,r){let i=ma(n,r),a=new Map(Object.entries(fa).map(([e,n])=>[n.rule,t[e].thought]));function o(e,t){let n=[...t,...e.hits.filter(e=>a.has(e.rule))];if(n.length===0)return e;let r=n.reduce((e,t)=>Ht(e,a.get(t.rule)??`ignore`),e.found?.action??`allow`);return{text:e.text,hits:e.hits.filter(e=>!a.has(e.rule)),found:{action:r,hits:[...e.found?.hits??[],...n]}}}return{push:t=>o(e.push(t),i.read(t)),flush(){return i.reset(),o(e.flush(),[])},carryOut:()=>e.carryOut()}}async function ga(e,t,n){let{detect:r}=e,i=pa.filter(e=>_a(r,e)),a=ya(r,t,_a),o=ya(r,t,(e,t)=>e[t].thought===`flag`),s=i.length>0||ba(a)||ba(o),c=Vt(e,t);(s||Ft([`thought`],r,c))&&await Un();let l=s?la({omit:va(e),...a,...xa(r),...Sa(t),...n?{carry:n}:{}}):void 0;return da(l&&ha(l,r,o,t.canary),r,c,i)}function _a(e,t){return e[t].thought===`redact`||e[t].thought===`block`}function va({detect:e,allow:t}){return{..._a(e,`marker_leak`)?{markers:!0}:{},..._a(e,`ungiven_images`)?{images:t.ungiven_images}:{},..._a(e,`ungiven_links`)?{links:t.ungiven_links}:{},imagesRead:e.ungiven_images.thought!==`ignore`}}function ya(e,t,n){let r=n(e,`canary_leak`)&&!t.canaryGiven&&t.canary,i=n(e,`prompt_leak`)&&t.privateSystem;return{...r?{canary:r}:{},...i?{privateSystem:i}:{}}}function ba(e){return e.canary!==void 0||e.privateSystem!==void 0}function xa(e){let t=new Set(Object.entries(fa).filter(([t])=>e[t].thought===`block`).map(([,e])=>e.rule));return t.size>0?{ends:t}:{}}function Sa({canary:e,givenUrls:t,labels:n}){return{...e?{planted:e}:{},...t?{given:t}:{},...n?{labels:n}:{}}}var Ca={rule:`live.untranscribed-audio`,severity:`high`};async function wa(e,t,n,r,i){let a=M(e.guardrails),o={stage:`live_outbound`,trust:`untrusted`,profileId:e.id,...Dn(a.detect,{canary:t,privateSystem:n}),...e.labels?{labels:e.labels}:{},...r?{givenUrls:r}:{},...i?{ownTools:i}:{}},s=await ga(a,o);return{policy:a,context:o,gate:await $n(a,o,`live_reply`),held:[],releasedTo:0,withholdVisible:!1,...s?{thoughts:s}:{}}}function Ta(e){let t=e.gate?.carryOut();e.gate=Tr(e.policy,e.context,`live_reply`,t),e.held=[],e.releasedTo=0,e.withholdVisible=!1,e.promptLeaks=void 0}function Ea(e,t,n=[]){let r=Mn(`live_outbound`,`untrusted`,t,`block`);return{action:`withhold`,error:new R(`safety`,e),events:[...n,...r?[r]:[]]}}function Da(e){return e.accumulated().length-e.unreleased().length}function Oa(e,t,n,r,i=!1){let a=t.accumulated();for(let t=e.held[0];t!==void 0;t=e.held[0]){let{event:o}=t;if(o.type!==`media`){let i=Math.max(t.start,e.releasedTo),s=Math.min(t.end,n);s>i&&(r.push({...o,text:a.slice(i,s)}),e.releasedTo=s)}if(t.end>n&&!(i&&o.type===`media`))return;o.type===`media`&&r.push(o),e.held.shift()}}function ka(e,t,n,r){if(!n.blocked){let i=n.found&&jt(`live_reply`,n.found);i&&r.push(G(i)),Oa(e,t,Da(t),r);return}let i=n.hits.filter(Ut);i.length>0&&(e.promptLeaks=i),e.withholdVisible=!0;let a=n.boundary?void 0:Mn(`live_outbound`,`untrusted`,n.hits,`block`);a&&r.push(a)}function Aa(e,t,n){e.withholdVisible||e.held.length===0||ka(e,t,t.flush(),n)}function ja(e,t,n,r){let i=t.accumulated().length;e.held.push({event:n,start:i,end:r?i:1/0})}function Ma(e,t){for(let n=e.held.length-1;n>=0;--n){let r=e.held[n];if(r===void 0||r.end!==1/0)return;r.end=t}}function Na(e,t,n,r){let i=n.text??``;if(!i)return;let a=t.accumulated().length;Ma(e,a+i.length),e.held.push({event:n,start:a,end:a+i.length});let o=t.process(i);e.withholdVisible||ka(e,t,o,r)}function Pa(e,t){let n=[],{gate:r}=e;if(!r){let{thoughts:n}=e;return Ra(n?t.flatMap(e=>e.type===`thought`?Fa(n.push(e.text),e):[e]):t)}let i=!1;for(let a of t){if(Sn(a)){i||=!!a.text,Na(e,r,a,n);continue}if(a.type===`media`){ja(e,r,a,i),e.withholdVisible||Oa(e,r,Da(r),n);continue}Aa(e,r,n),Ia(a)&&La(e,r,n);let t=a.type===`tool`?void 0:Gt(a,e.context,e.policy.detect,`live_reply`);if(t?.stop)return Ea(Lt(t.hits),t.hits,n);if(t){let e=jt(`live_reply`,{action:`flag`,hits:t.hits});e&&n.push(G(e))}a.type===`thought`&&e.thoughts?n.push(...Fa(e.thoughts.push(a.text),a)):n.push(a)}return Ra(n)}function Fa({text:e,hits:t,found:n},r){let i=n&&jt(`thought`,n),a=Mn(`thought`,`untrusted`,t,`redact`);return[...i?[G(i)]:[],...a?[a]:[],...e?[{...r,text:e}]:[]]}function Ia(e){return e.type===`done`&&e.stop?.kind===`generation_complete`}function La(e,t,n){let r=t.accumulated().length;e.withholdVisible||r===0||Da(t)<r||Oa(e,t,r,n,!0)}function Ra(e){return e.length===0?{action:`idle`}:{action:`emit`,events:e}}function za(e,t,n){let{detect:r,blockedReply:i}=e.policy,a=w({text:t.accumulated()},r,{boundary:`live_reply`,...e.withholdVisible?{reportedTo:Da(t)}:{},scope:Vt(e.policy,e.context)}),o=t.accumulated().slice(0,e.releasedTo),s=pe(a,e.promptLeaks),c=s&&s!==a.blocked?Mn(`live_outbound`,`untrusted`,s,`block`):void 0,l=[...n,...a.events.map(G),...c?[c]:[]];if(s){if(i.onBlock===`refuse`){let t=te(o,e.context.labels);return{action:`emit`,events:[...l,{type:`text`,text:t}]}}return{action:`withhold`,error:new R(`safety`,mn.egress),events:l}}if(a.rewritten){let e=k(o,a.payload.text);return{action:`emit`,events:[...l,{type:`text`,text:e}]}}return Oa(e,t,t.accumulated().length,l,!0),Ra(l)}function Ba(e,t){if(e.held.length===0)return t;let n=Mn(`live_outbound`,`untrusted`,[Ca],`block`);return n?[...t,n]:t}function Va(e,t){let n=[];return Aa(e,t,n),t.accumulated()?za(e,t,n):Ra(Ba(e,n))}function Ha(e){let t=e.thoughts?Fa(e.thoughts.flush(),{type:`thought`,text:``}):[];if(!e.gate)return Ra(t);let n=Va(e,e.gate);return Ta(e),t.length===0?n:n.action===`idle`?{action:`emit`,events:t}:{...n,events:[...t,...n.events??[]]}}function Ua(e){e.thoughts?.flush(),Ta(e)}var Wa=[1e3,2e3,4e3,8e3],Ga=5e3,Ka=Wa.length,qa=1e3,Ja=new Set([408,429,500,502,503,504,529]),Ya=(e,t)=>new Promise((n,r)=>{if(t?.aborted){r(Xa(t));return}let i=setTimeout(()=>{t?.removeEventListener(`abort`,a),n()},e);function a(){clearTimeout(i),r(Xa(t))}t?.addEventListener(`abort`,a,{once:!0})});function Xa(e){return e.reason??new DOMException(`The operation was aborted.`,`AbortError`)}function Za(e){return Ja.has(e)}function Qa(e){let t=yt(e);return t instanceof R&&t.kind===`network`}function $a(e){return Wa[Math.min(e,Wa.length-1)]}function eo(e,t=Date.now()){let n=e.get(`retry-after-ms`),r=e.get(`retry-after`),i;if(n!==null&&n.trim()!==``&&Number.isFinite(Number(n)))i=Number(n);else if(r!==null&&r.trim()!==``){let e=Number(r);i=Number.isFinite(e)?e*qa:Date.parse(r)-t}if(!(i===void 0||Number.isNaN(i)||i<0))return i}function to(e,t=Ya,n=()=>1/0){return async(r,i)=>{let a=0;for(let o=0;;o++){let s=Math.min(Ga-a,n()),c;try{let t=await e(r,i);if(!Za(t.status)||(c=eo(t.headers)??$a(o),c>s||o>=Ka))return t;await t.body?.cancel()}catch(e){if(c=$a(o),!Qa(e)||c>s||o>=Ka)throw e}await t(c,i?.signal),a+=c}}}var no=`[DONE]`;function ro(e){if(e&&typeof e==`object`&&!Array.isArray(e))return e}function io(e,t){let n=e.startsWith(`data:`)?e.slice(5).replace(/^ /,``):e,r={};if(t&&(r.sseEvent=t),n===no)return r.eventType=`sse_done`,r;try{let e=JSON.parse(n),t=ro(e);return t?{...t,...r}:(r.eventType=`sse_unparsed`,r.data=e,r)}catch{return r.eventType=`sse_unparsed`,r.data=n,r}}function ao(e,t=``){let n=[],r=t,i=[],a=!1,o=0,s=/\r\n|\r|\n/g,c=0;for(let t=s.exec(e);t&&(t[0]!==`\r`||t.index!==e.length-1);t=s.exec(e)){let s=e.slice(c,t.index);if(c=t.index+t[0].length,!s)a&&n.push(io(i.join(`
|
|
3
3
|
`),r)),r=``,i=[],a=!1,o=c;else if(!s.startsWith(`:`)){let e=s.indexOf(`:`),t=e<0?s:s.slice(0,e),n=e<0?``:s.slice(e+1).replace(/^ /,``);t===`event`&&(r=n),t===`data`&&(i.push(n),a=!0)}}return{rest:e.slice(o),payloads:n,pendingEvent:``}}async function*oo(e){let t=e.getReader(),n=new TextDecoder,r=``,i=!1;try{for(;;){let{done:e,value:a}=await t.read();if(e){i=!0;break}r+=n.decode(a,{stream:!0});let o=ao(r);r=o.rest;for(let e of o.payloads)yield e}}finally{i||t.cancel().catch(()=>void 0),t.releaseLock()}}var so=/key|auth|cookie|secret|token/i;function co(e,t){return so.test(e)?`[redacted]`:t}function lo(e){let t={};for(let[n,r]of new Headers(e).entries())t[n]=co(n,r);return t}function uo(e){return e instanceof Error?{eventType:`http_throw`,name:e.name,message:e.message}:{eventType:`http_throw`,name:`Error`,message:String(e)}}function fo(e){if(e==null)return{};if(typeof e!=`string`)return{bodyKind:e.constructor.name};try{return{body:JSON.parse(e)}}catch{return{body:e}}}function po(e,t=fetch,n){return e?async(r,i)=>{e({eventType:`http_request`,method:i?.method??`GET`,url:String(r),headers:lo(i?.headers),...n?{keySlot:n}:{},...fo(i?.body)});try{let n=await t(r,i);return e({eventType:`http_response`,status:n.status,headers:lo(n.headers)}),n.ok||e({eventType:`http_error_body`,body:await n.clone().text()}),n}catch(t){throw e(uo(t)),t}}:t}function mo(e=fetch){return(t,n)=>sn(e,t,n)}var ho=`key_fallback`,go=1e6;function _o(e,t){let n=e.models[t];if(n)return n;let r;for(let[n,i]of Object.entries(e.models))n.endsWith(`*`)&&t.startsWith(n.slice(0,-1))&&n.length-1>(r?.prefix.length??-1)&&(r={prefix:n.slice(0,-1),price:i});return r?.price}function vo(e,t,n,r){let i=e,a=0;for(let[e,t]of Object.entries(n??{})){let n=Math.min(r?.[e]??0,i);a+=n*t,i-=n}return a+i*t}function yo(e,t,n){let r=_o(e,t);if(!r)return;let i=r.longContext&&n.input>r.longContext.above?r.longContext:r,a=Math.min(n.cached??0,n.input);return{usd:(a*(i.cachedInput??i.input)+vo(n.input-a,i.input,i.byModality?.input,n.byModality?.input)+vo(n.output,i.output,i.byModality?.output,n.byModality?.output))/go,estimated:!0}}function bo(e){return(t,n)=>{if([...n.headers.keys()].length)throw new R(`unsupported`,V(`protocol.ws_headers`,{provider:e}));return Promise.resolve(new WebSocket(t,n.protocols))}}var xo=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789`,So=248;function Co(){let e=``;for(;e.length<24;)for(let t of crypto.getRandomValues(new Uint8Array(24-e.length)))t<So&&(e+=xo[t%62]);return e}function wo(e){return tt(e.provider,e.binding)}var To=new WeakMap;function Eo(e,t){return e&&Object.hasOwn(e,t)?e[t]:void 0}async function Do(e,t,n,r){let i=n?Eo(t,n):void 0;return typeof i==`function`?await i({providerId:e.id,...r.apiId===void 0?{}:{apiId:r.apiId},keySlot:n,...r.signal?{signal:r.signal}:{}}):i}function Oo(e,t,n){let r=e.definition.key;if(!r)return;let i=typeof n==`string`?n.trim()||void 0:n,a=r.safeParse(i);if(!a.success||t&&i===void 0)throw new R(`auth`,i===void 0?V(`provider.credential_missing`,{slot:t??``}):V(`protocol.key_invalid`,{slot:t??``,provider:e.id}));return a.data}async function ko(e,t,n){let r=t.authorize??e.provider.definition.authorize;if(!r)return;let i=e.provider.definition.key?await Do(e.provider,e.vault,n,{apiId:e.binding.apiId,...e.signal?{signal:e.signal}:{}}):void 0,a=Oo(e.provider,n,i);if(a===void 0)return;e.onKey?.(n,a);let o=`${t.protocol.id}\u0000${n??``}`,s=To.get(e.provider)??new Map;To.set(e.provider,s);let c=s.get(o);if(c&&JSON.stringify(c.key)===JSON.stringify(a))return c.signer;let l=r(a);return s.set(o,{key:a,signer:l}),l}function Ao(e,t,n,r){return e.url?new URL(e.url({path:t,apiId:n,stream:r})):new URL(e.baseUrl.replace(/\/+$/,``)+(t.startsWith(`/`)?t:`/${t}`))}async function*jo(e,t){let n=e.headers.get(`content-type`)??``;if(!t&&!/json/i.test(n)){let t=new Uint8Array(await e.arrayBuffer()),r=e.headers.get(`x-generation-id`)?.trim();yield{eventType:`http_body`,mime_type:n,data:vn(t),...r?{id:r}:{}}}else if(!t)yield await e.json();else if(e.body)for await(let t of oo(e.body)){if(t.eventType===`sse_done`)return;yield t}}function Mo(e){let t=e.split(/\r?\n/).filter(e=>e.startsWith(`data:`)).map(e=>e.slice(5).trim()).join(`
|
|
4
4
|
`);for(let n of t?[e,t]:[e])try{return JSON.parse(n)}catch{}return e}async function No(e,t,n){let r=Mo(await n.text()),i=e.error?.({status:n.status,body:r,headers:n.headers})??new R(St(n.status),V(`protocol.http`,{provider:t,status:n.status}));return Object.assign(i,{status:n.status})}function Po(e){return e.builtins.map(e=>e.id)}function Fo(e,t,n=[]){let r=t.find(e=>!n.includes(e));if(r!==void 0)throw new R(`unsupported`,V(`protocol.builtin_unwritten`,{protocol:e.id,tool:r}))}async function Io(e){return typeof e==`string`?e:e instanceof ArrayBuffer?new TextDecoder().decode(e):typeof Blob<`u`&&e instanceof Blob?await e.text():String(e)}function Lo(e){try{let t=JSON.parse(e);if(t&&typeof t==`object`&&!Array.isArray(t))return t}catch{}return{eventType:`ws_unparsed`,data:e}}function Ro(e,t){let n=[],r=[],i,a=!1,o=Promise.resolve(),s=e=>{t(e),n.push(e),i?.()},c=e=>{o=o.then(e)};return e.addEventListener(`open`,()=>{for(let t of r.splice(0))e.send(t)}),e.addEventListener(`message`,e=>c(async()=>{let t=await Io(e.data);t.trim()&&s(Lo(t))})),e.addEventListener(`error`,()=>c(()=>s({eventType:`ws_error`}))),e.addEventListener(`close`,e=>c(()=>{let{code:t,reason:n}=e;s({eventType:`ws_close`,code:t,reason:n}),a=!0})),{send(n,i){t({eventType:`ws_send`,body:n,...i?.length?{input:qe.parse(i)}:{}});let a=JSON.stringify(n);e.readyState===WebSocket.CONNECTING?r.push(a):e.send(a)},async*frames(){for(;;){let e=n.shift();if(e)yield e;else if(a)return;else await new Promise(e=>i=e)}},close(t,n){(e.readyState===WebSocket.CONNECTING||e.readyState===WebSocket.OPEN)&&e.close(t,n)}}}function zo(e,t,n,r={sent:!1},i=[]){let a=wo(e),{protocol:o}=a,{apiId:s}=e.binding,c=(`builtInTools`in e.binding?e.binding.builtInTools:void 0)??[],l=t=>{e.tapUpstream?.(t),e.rawRows&&n.push(t)},u=t=>{let n=t??o.endpoints[e.profileType];if(n===void 0)throw new R(`unsupported`,V(`protocol.profile_type`,{protocol:o.id,profileType:e.profileType}));return n};return{profileType:e.profileType,apiId:s,options:e.binding.options??{},builtInTools:c,limits:e.limits??e.binding.limits??{},...e.signal?{signal:e.signal}:{},tapUpstream:l,async*send(n,c){Fo(o,i,c.wroteTools);let d=new Headers({"content-type":`application/json`});c.stream&&d.set(`accept`,`text/event-stream`);for(let[e,t]of Object.entries(a.headers??{}))d.set(e,t);for(let[e,t]of Object.entries(c.headers??{}))d.set(e,t);let f={transport:`http`,url:Ao(a,u(c.path),s,c.stream),headers:d,protocols:[],body:JSON.stringify(n)};await(await ko(e,a,t))?.sign(f);let p=to(po(e.tapUpstream&&(t=>e.tapUpstream?.(t)),mo(e.fetch??fetch),t),e.wait??Ya,e.timeLeft);r.sent=!0;let m=await p(f.url,{method:`POST`,headers:f.headers,body:f.body??null,...e.signal?{signal:e.signal}:{}});if(!m.ok)throw await No(o,e.provider.id,m);for await(let e of(o.framing??jo)(m,c.stream))l(e),yield e},async connect(n,c){Fo(o,i,c?.wroteTools);let d={transport:`ws`,url:Ao(a,u(void 0),s,!0),headers:new Headers(a.headers),protocols:[]};await(await ko(e,a,t))?.sign(d);let f=e.openWebSocket??bo(e.provider.id);r.sent=!0;let p=Ro(await f(d.url.toString(),{headers:d.headers,protocols:d.protocols}),l);return p.send(n),p}}}function Bo(e,t){return e instanceof R&&e.kind===t}async function*Vo(e,t){let{keySlot:n,fallbackKeySlot:r}=ot(e.provider,e.binding),i=n,a=!1,o=!1;for(;;){let n=!1;try{for await(let e of t(i,a))n=!0,yield e;return}catch(t){if(n)throw t;if((Bo(t,`rate_limit`)||Bo(t,`busy`))&&r&&i!==r&&Ho(e,r))e.tapUpstream?.({eventType:ho,from:i??null,keySlot:r,errorKind:t.kind,error:t.message}),i=r,a=!0;else if(Bo(t,`auth`)&&!o){o=!0;let t=wo(e);To.get(e.provider)?.get(`${t.protocol.id}\u0000${i??``}`)?.signer.invalidate?.()}else throw t}}}function Ho(e,t){let n=Eo(e.vault,t);return typeof n==`string`?n.trim()!==``:typeof n==`function`||typeof n==`object`&&!!n}function Uo(e){if(!(e instanceof R)||e.kind===`cancelled`||e.kind===`config`)throw e;return{type:`error`,errorKind:e.kind,errorInternal:Rt(e),...e.copy?{errorCopy:e.copy}:{}}}function Wo(e){if(e.state===void 0)return e;if(!e.history?.length)throw new R(`request`,V(`protocol.history_needed`));let{state:t,stateHistoryLength:n,...r}=e;return r}function Go(e){let t=new Map,n=e=>{let n=t.get(e);if(n)return n;let r=Co();return t.set(e,r),r},r=e.provider.definition.prices;return{finish:t=>{switch(t.type){case`tool_call`:return{...t,call:{...t.call,callId:n(t.call.callId),wireCallId:t.call.callId}};case`tool_cancel`:case`tool_draft`:return{...t,callId:n(t.callId)};case`reasoning`:return{...t,origin:{protocol:t.origin?.protocol??e.binding.protocol,provider:e.provider.id,apiId:e.binding.apiId}};case`tokens`:{if(t.tokens.cost||!r)return t;let n=yo(r,e.binding.apiId,t.tokens);return n?{...t,tokens:{...t.tokens,cost:n}}:t}default:return t}},wireOf:e=>{for(let[n,r]of t)if(r===e)return n;return e}}}function Ko(e,t){let n=e.provider.definition.prices;if(!t.usage||t.usage.costUsd!==void 0||!n)return t;let{inputTokens:r,outputTokens:i}=t.usage,a=yo(n,t.model,{input:r,output:i,total:r+i});return a?{...t,usage:{...t.usage,costUsd:a.usd,estimated:!0}}:t}function qo(e){return wo(e).protocol}function Jo(e,t,n){let r=t[n];if(!r)throw new R(`unsupported`,V(`protocol.no_operation`,{protocol:e.id,operation:n}));let i=r;return((...e)=>i.apply(t,e))}async function Yo(e,t,n){let r=qo(e);for await(let i of Vo(e,i=>(async function*(){let a=r.create(zo(e,i,[]));yield await Jo(r,a,t)(n)})()))return i;throw new R(`internal`,V(`provider.decision_failed`))}function Xo(e){let t=qo(e);return{async*complete(n){let{finish:r}=Go(e),i=[],a={sent:!1},o=Vo(e,(r,o)=>{a.sent=!1;let s=t.create(zo(e,r,i,a,Po(n)));return Jo(t,s,`complete`)(o?Wo(n):n)});try{for await(let e of o){for(let e of i.splice(0))yield{type:`raw`,row:e};yield r(e)}}catch(e){for(let e of i.splice(0))yield{type:`raw`,row:e};if(!a.sent)throw e;yield Uo(e);return}for(let e of i.splice(0))yield{type:`raw`,row:e}},async openSession(n){let{finish:r,wireOf:i}=Go(e),a=[],o;for await(let r of Vo(e,(r,i)=>(async function*(){let o=t.create(zo(e,r,a,void 0,Po(n)));yield await Jo(t,o,`openSession`)(i?Wo(n):n)})()))o=r;let s=o;return{...s,sendToolResult:e=>s.sendToolResult({...e,callId:i(e.callId)}),async*events(){for await(let e of s.events()){for(let e of a.splice(0))yield{type:`raw`,row:e};yield r(e)}}}},decide:async t=>Ko(e,await Yo(e,`decide`,t)),embed:t=>Yo(e,`embed`,t)}}function Zo(e){let t=new AbortController,n=[],r=()=>{for(let e of n.splice(0))e()};for(let i of e){let e=()=>{t.abort(i.reason),r()};if(i.aborted){e();break}i.addEventListener(`abort`,e,{once:!0}),n.push(()=>i.removeEventListener(`abort`,e))}return{signal:t.signal,dispose:r}}function Qo(e,t){return t!==void 0&&e>t}var $o=class{limits;controller=new AbortController;signal;timer;timerDeadline;wireBytes=0;stepBytes=0;stepEvents=0;calls=new Set;deadline;releaseSignal;constructor(e,t,n=e.operationTimeoutMs){this.limits=e;let r=Zo(t?[t,this.controller.signal]:[this.controller.signal]);this.signal=r.signal,this.releaseSignal=r.dispose,n!==void 0&&(this.startTimer(n),this.deadline=performance.now()+n)}resumeOperation(){if(this.deadline===void 0)return;let e=this.deadline-performance.now();e<=0&&(this.controller.abort(new R(`timeout`,V(`error.timeout`))),B(this.signal)),this.startTimer(e)}timeLeft(){let e=this.timerDeadline??this.deadline;return e===void 0?1/0:e-performance.now()}startTimer(e){this.stopTimer(),this.timerDeadline=performance.now()+e,this.timer=setTimeout(()=>this.controller.abort(new R(`timeout`,V(`error.timeout`))),e)}stopTimer(){this.timer!==void 0&&clearTimeout(this.timer),this.timer=void 0,this.timerDeadline=void 0}close(){this.controller.abort(),this.dispose()}dispose(){this.stopTimer(),this.releaseSignal()}startLiveStep(){let e=this.limits.liveStepTimeoutMs;this.timer===void 0&&e!==void 0&&this.startTimer(e)}fail(){let e=new R(`bad_response`,V(`provider.budget_exhausted`),{copy:{key:`provider.budget_exhausted`}});throw this.controller.abort(e),e}checkDeadline(){this.timerDeadline!==void 0&&performance.now()>=this.timerDeadline&&this.controller.abort(new R(`timeout`,V(`error.timeout`))),B(this.signal)}value(e){this.checkDeadline();let t=new TextEncoder().encode(JSON.stringify(e)).byteLength;this.checkDeadline(),this.stepBytes+=t,this.stepEvents++,(Qo(t,this.limits.maxEventBytes)||Qo(this.stepBytes,this.limits.maxStepBytes)||Qo(this.stepEvents,this.limits.maxStepEvents))&&this.fail()}event(e){this.value(e),e.type===`tool_call`&&this.calls.add(e.call.callId),e.type===`tool_cancel`&&this.calls.delete(e.callId),Qo(this.calls.size,this.limits.maxPendingToolCalls)&&this.fail()}resetStep(){this.stepBytes=0,this.stepEvents=0,this.calls.clear(),this.wireBytes=0,this.stopTimer()}socket(e){return async(t,n)=>{B(this.signal);let r=await e(t,n);this.signal.aborted&&(r.close(),B(this.signal));let i=()=>r.close();return this.signal.addEventListener(`abort`,i,{once:!0}),r.addEventListener(`close`,()=>this.signal.removeEventListener(`abort`,i),{once:!0}),r.addEventListener(`message`,e=>{let t=e.data;if(Qo(typeof t==`string`?new TextEncoder().encode(t).byteLength:t instanceof Blob?t.size:t instanceof ArrayBuffer||ArrayBuffer.isView(t)?t.byteLength:0,this.limits.maxWireRecordBytes)){e.stopImmediatePropagation();try{this.fail()}catch{r.close(1009,`response limit`)}}}),r}}fetch(e){return async(t,n)=>{let r=n?.signal??(t instanceof Request?t.signal:void 0),i=Zo(r?[this.signal,r]:[this.signal]),a=i.signal;B(a);let o=await e(t,{...n,signal:a}).catch(e=>{throw i.dispose(),e});if(B(a),!o.body)return i.dispose(),o;let s=o.body.getReader(),c=0,l=this.limits.maxWireRecordBytes!==void 0&&o.headers.get(`content-type`)?.includes(`text/event-stream`)?new es(this):void 0,u=()=>{s.cancel(a.reason).catch(()=>void 0)};a.addEventListener(`abort`,u,{once:!0});let d=new ReadableStream({pull:async e=>{try{B(a);let t=await s.read();if(B(a),t.done){e.close(),a.removeEventListener(`abort`,u),i.dispose(),s.releaseLock();return}c+=t.value.byteLength,this.wireBytes+=t.value.byteLength,(Qo(c,this.limits.maxWireResponseBytes)||Qo(this.wireBytes,this.limits.maxWireResponseBytes))&&this.fail(),l?.accept(t.value),e.enqueue(t.value)}catch(t){e.error(t),a.removeEventListener(`abort`,u),i.dispose(),s.cancel(t).catch(()=>void 0)}},cancel:e=>(a.removeEventListener(`abort`,u),i.dispose(),s.cancel(e))});return new Response(d,{status:o.status,statusText:o.statusText,headers:o.headers})}}},es=class{budget;recordBytes=0;lineBytes=0;previousCR=!1;emptyCR=!1;constructor(e){this.budget=e}accept(e){for(let t of e)this.emptyCR&&t!==10&&(this.recordBytes=0,this.emptyCR=!1),this.recordBytes++,Qo(this.recordBytes,this.budget.limits.maxWireRecordBytes)&&this.budget.fail(),this.emptyCR?(this.recordBytes=0,this.emptyCR=!1,this.previousCR=!1):t===10&&this.previousCR?this.previousCR=!1:(t===10||t===13?(this.lineBytes===0&&(t===13?this.emptyCR=!0:this.recordBytes=0),this.lineBytes=0):this.lineBytes++,this.previousCR=t===13)}},ts=a({name:r().min(1),callId:r().min(1),wireCallId:r().min(1).optional(),arguments:t(r(),qe),stepId:r().min(1).optional(),stepCallCount:o().int().min(1).optional()}),ns=be.extend({type:f(`reasoning`)}),rs=new Set([`text`,`thought`,`structured`,`media`,`grounding`,`citation`,`evidence`,`tokens`,`session`,`tool_draft`,`error`,`custom`]);function is(e){let t=xe.parse(e);if(t.kind===`gate`)throw new R(`bad_response`,V(`provider.kernel_gate`));return t}function as(e){if(!z(e)||typeof e.type!=`string`)throw new R(`bad_response`,V(`provider.event_invalid`));if(rs.has(e.type))return ne.parse(e);switch(e.type){case`tool_call`:return{type:`tool_call`,call:ts.parse(e.call)};case`tool_cancel`:return{type:`tool_cancel`,callId:r().min(1).parse(e.callId)};case`reasoning`:return ns.parse(e);case`raw`:return{type:`raw`,row:it.parse(e.row)};case`done`:return{type:`done`,stop:is(e.stop),interrupted:d().optional().parse(e.interrupted),state:e.state};case`response`:if(!z(e.response))throw new R(`bad_response`,V(`provider.response_identity`));return{type:`response`,response:a({id:r().optional(),model:r().optional()}).parse(e.response)};default:throw new R(`bad_response`,V(`provider.event_type`,{type:e.type}))}}async function os(e,t){if(B(t),!t)return await e();let n=()=>{},r=new Promise((e,r)=>{n=()=>{try{B(t)}catch(e){r(e)}},t.addEventListener(`abort`,n,{once:!0}),t.aborted&&n()});try{return await Promise.race([Promise.resolve().then(()=>(B(t),e())),r])}finally{t.removeEventListener(`abort`,n)}}function ss(e,t){if(!e)return;let n=e=>({...e,...e.params?{params:Object.fromEntries(Object.entries(e.params).map(([e,n])=>[e,typeof n==`string`?t(n):n]))}:{}});return`key`in e?n(e):e.map(n)}function cs(e,t){let n=t(e instanceof Error?e.message:String(e));if(e instanceof DOMException)return new DOMException(n,e.name);if(Bt(e))return new DOMException(n,`AbortError`);let r=e instanceof Error&&e.cause!==void 0?{cause:cs(e.cause,t)}:{},i=e instanceof R?new R(e.kind,n,{copy:ss(e.copy,t),...r}):e instanceof TypeError?TypeError(n,r):Error(n,r);return z(e)&&typeof e.status==`number`&&Object.assign(i,{status:e.status}),i}async function ls(e,t){try{return await e()}catch(e){throw cs(e,t)}}async function*us(e,t,n,r=!1){r||n.resumeOperation();let i;try{for(i=e()[Symbol.asyncIterator]();;){let e=i,a=await os(()=>e.next(),n.signal);if(a.done)break;let o=as(a.value);r&&(o.type!==`session`||o.session.kind===`working`)&&n.startLiveStep(),n.event(o),o.type===`error`?yield{...o,...o.errorCopy?{errorCopy:ss(o.errorCopy,t)}:{},...o.errorInternal?{errorInternal:t(o.errorInternal)}:{},...o.error?{error:t(o.error)}:{}}:yield o,r&&o.type===`done`&&n.resetStep()}}catch(e){throw cs(e,t)}finally{n.close(),i?.return&&Promise.resolve(i.return()).catch(()=>void 0)}}var ds=/^(?:authorization|proxy-authorization|cookie|set-cookie|api[_-]?key|x-goog-api-key|secret|token|access[_-]?token|refresh[_-]?token|password)$/i;function fs(e,t,n,r,i){let a=Object.freeze(Pe.parse({...t.limits,...r.limits})),o=new $o(a,i.signal,i.timeoutMs??(i.liveConnection?a.connectTimeoutMs:a.operationTimeoutMs)),s=new Set,c=e=>{if(typeof e==`string`)s.add(e);else if(e&&typeof e==`object`)for(let t of Object.values(e))c(t)},l=e=>{if(typeof e==`string`){let t=e;for(let e of s)e&&(e.length>=4||t===e)&&(t=t.split(e).join(`[redacted]`));return t}return Array.isArray(e)?e.map(l):e&&typeof e==`object`?Object.fromEntries(Object.entries(e).map(([e,t])=>[String(l(e)),ds.test(e)&&typeof t==`string`?`[redacted]`:l(t)])):e},u=e=>String(l(e)),d=ot(e,t).keySlot,f=Xo({provider:e,binding:t,profileType:n,limits:a,signal:o.signal,fetch:o.fetch(r.fetch??globalThis.fetch),openWebSocket:o.socket(r.openWebSocket??bo(e.id)),...r.vault?{vault:r.vault}:{},...r.wait?{wait:r.wait}:{},timeLeft:()=>o.timeLeft(),...i.tapUpstream?{tapUpstream:e=>i.tapUpstream?.(it.parse(l(e)))}:{},onKey(e,t){d=e,c(t)}});o.stopTimer();let p=async e=>{try{o.resumeOperation();let t=await os(()=>ls(e,u),o.signal);return o.value(t),t}finally{o.close()}};return{keySlot:()=>d,complete:e=>us(()=>f.complete({...e,signal:o.signal}),u,o),decide:e=>p(()=>f.decide({...e,signal:o.signal})),embed:e=>p(()=>f.embed({...e,signal:o.signal})),async openSession(e){o.resumeOperation();let t=await os(()=>ls(()=>f.openSession({...e,signal:o.signal}),u),o.signal).catch(e=>{throw o.close(),e}).finally(()=>o.stopTimer());return{events:()=>us(()=>t.events(),u,o,!0),closeInfo:()=>{let e=t.closeInfo?.();return e&&{...e,...e.error?{error:cs(e.error,u)}:{}}},sendText:e=>(o.startLiveStep(),ls(()=>t.sendText(e),u)),sendAudio:e=>ls(()=>t.sendAudio(e),u),sendVideo:e=>ls(()=>t.sendVideo(e),u),sendContext:e=>ls(()=>t.sendContext(e),u),sendToolResult:e=>(o.startLiveStep(),ls(()=>t.sendToolResult(e),u)),close:e=>(o.stopTimer(),ls(()=>t.close(e),u).finally(()=>o.dispose()))}}}}function ps(e,t,n){let r=t.options??{},i=[...n.continuation?.keyOptions??[]].sort().map(e=>[e,r[e]??null]);return JSON.stringify({connection:e.connection??null,options:i})}function ms(e,t,n){if(e?.history===`stateless`&&(t||n?.length))throw new R(`request`,V(`provider.stateless_history`))}async function hs(e,t,n,r,i={}){if(!n)return{};let a=m.parse(n),o=Qe(e,t),s=o.continuation,c;return a.protocol!==o.id||a.provider!==e.id?c=`provider_changed`:a.apiId===t.apiId?!s||a.version!==s.version?c=`version_changed`:a.compatibilityKey===ps(e,t,o)?a.keySlot===ot(e,t).keySlot?(i.history===`provider`?r.length>0:a.coveredHistoryLength>r.length||a.coveredHistoryHash!==await de(r.slice(0,a.coveredHistoryLength)))&&(c=`history_changed`):c=`key_changed`:c=`connection_changed`:c=`model_changed`,c?{warning:{code:`provider_state_rebuilt`,reason:c}}:{state:s?.schema.parse(a.data),covered:i.history===`provider`?0:a.coveredHistoryLength,...a.wireCallIds?{wireCallIds:a.wireCallIds}:{}}}async function gs(e,t,n,r,i,a={}){if(r===void 0)return;let o=Qe(e,t),s=o.continuation;if(!s)throw new R(`bad_response`,V(`provider.continuation_contract`));return{protocol:o.id,provider:e.id,version:s.version,apiId:t.apiId,...n?{keySlot:n}:{},compatibilityKey:ps(e,t,o),coveredHistoryLength:i.length,coveredHistoryHash:await de(i),data:qe.parse(s.schema.parse(r)),...Object.keys(a).length?{wireCallIds:a}:{}}}function _s(e,t){return e?.map(e=>{if(!e.reasoning)return e;let{reasoning:n,...r}=e,i=n.filter(e=>Ge(e.origin.protocol,t));return i.length?{...r,reasoning:i}:r})}function vs(e,t){if(!e||!t)return e;let n=e=>t[e]??e;return e.map(e=>({...e,...e.tool_calls?{tool_calls:e.tool_calls.map(e=>({...e,id:n(e.id)}))}:{},...e.tool_call_id?{tool_call_id:n(e.tool_call_id)}:{}}))}function ys(e,t,n){let{providerState:r,tapUpstream:i,history:a,...o}=e,s=vs(_s(a,t),n.wireCallIds);return{...o,...s?{history:s}:{},...n.state===void 0?{}:{state:n.state,stateHistoryLength:n.covered}}}function bs(e){let{wireCallId:t,...n}=e;return n}async function*xs(e,t){let n={},r,i=!1,a=[],o=[],s=``,c,l=e[Symbol.asyncIterator](),u=!1;try{for(;;){let e=await os(()=>l.next(),t);if(e.done){u=!0;break}B(t);let d=e.value;if(r)throw new R(`bad_response`,V(`provider.events_after_completion`));switch(d.type){case`raw`:continue;case`text`:s+=d.text;break;case`structured`:c=d.structured;break;case`reasoning`:{let{type:e,...t}=d;o.push(t);break}case`tool_call`:if(a.some(e=>e.callId===d.call.callId))throw new R(`bad_response`,V(`provider.duplicate_call`));d.call.wireCallId&&(n[d.call.callId]=d.call.wireCallId),a.push(bs(d.call));continue;case`tool_cancel`:throw new R(`bad_response`,V(`provider.tool_cancel_live`));case`error`:i=!0;break;case`done`:r=d;continue}yield d}}finally{!u&&l.return&&Promise.resolve(l.return()).catch(()=>void 0)}return{terminal:r,failed:i,pending:a,reasoning:o,text:s,...c===void 0?{}:{structured:c},wireCallIds:n}}function Ss(e,t,n,r,i,a={},o=[]){let s=Qe(e,t),c=i;return{async*complete(l){let u=c===i&&a.history===`provider`,d=await hs(e,t,c,u?o:l.history??[],u?a:{});d.warning&&(c=void 0,yield{type:`provider_warning`,warning:d.warning});let f=fs(e,t,n,r,l),{terminal:p,failed:m,pending:h,reasoning:g,text:_,structured:v,wireCallIds:y}=yield*xs(f.complete(ys(l,s,d)),l.signal);if(B(l.signal),!p){yield{type:`done`,stop:{kind:m?`provider_error`:`stream_incomplete`}};return}if(m||p.interrupted||p.stop.kind!==`tool`&&p.stop.kind!==`completed`){yield{type:`done`,stop:p.stop};return}let b=[...l.history??[]];l.input.length&&b.push(l.input.every(e=>e.type===`text`)?{role:`user`,content:l.input.map(e=>e.type===`text`?e.text:``).join(``)}:{role:`user`,parts:l.input});let x=await gs(e,t,f.keySlot(),p.state,[...b,...Ye({text:_,structured:v,calls:h.map((e,t)=>t===0?{...e,reasoning:g}:e)})],{...d.wireCallIds,...y});c=x;for(let e of h)yield{type:`tool`,tool:e};yield{type:`done`,stop:p.stop,providerState:x}}}}var Cs=new Map;function ws(e){return typeof e==`object`&&!!e&&`write`in e&&typeof e.write==`function`}function Ts(e,t){let n=e.trim();if(!n)throw new R(`config`,`registerTraceDestination requires a non-empty id`);if(!ws(t))throw new R(`config`,`Trace destination '${n}' must be a TraceSink`);Cs.set(n,t)}function Es(e){return Cs.get(e)}function Ds(e){let t=Es(e);if(!t)throw new R(`config`,`Trace destination '${e}' is not registered`);return t}async function Os(e,t,n){try{await e.write(await t,{retainForDays:n.retainForDays,rotateAfterMiB:n.rotateAfterMiB})}catch(t){try{e.onError?.(t)}catch{}}}function ks(e,t,n,r){return Os(e,ii({spans:t,policy:n,...r?{metadata:r}:{}}),n)}function As(){return{write:()=>Promise.resolve()}}function js(e,t){return!t&&!e.onError?e:{write:(t,n)=>e.write(t,n),onError:e.onError??t}}var Ms=2**32;function Ns(e,t){let n=e.spans[0]?.traceId??``;return Number.parseInt(n.slice(-8),16)/Ms<t}function Ps(e,t){return t>=1?e:t<=0?As():{write:async(n,r)=>{Ns(n,t)&&await e.write(n,r)},onError:e.onError}}function Fs(e,t){return e===void 0||e===!1?As():js(typeof e==`string`?Ds(e):e,t.onWriteError)}function Is(e){let t={...ni(e.observability),detect:M(e.guardrails).detect};return e.override?{policy:t,sink:js(e.override,t.onWriteError)}:t.record?{policy:t,sink:Ps(Fs(t.writeTo,t),t.sampleRate)}:{policy:t,sink:As()}}async function Ls({name:e,attributes:t,traceparent:n,links:r,metadata:i,writer:a},o){let s=xt(e,{kind:`CLIENT`,attributes:t,links:A(r),...n?{traceparent:n}:{}}),{sink:c,policy:l}=Is(a);try{let e=await o(s.root);return s.root.end({code:`OK`}),e}catch(e){throw Ue(s.root,e),e}finally{await ks(c,s.collect(),l,i)}}var Rs={invalid_config:`config`,invalid_request:`request`,conflict:`conflict`,not_found:`not_found`,invalid_input:`input`,not_allowed:`action`,authentication:`auth`,permission:`auth`,rate_limited:`rate_limit`,busy:`busy`,unsupported:`unsupported`,unavailable:`unavailable`,network:`network`,timeout:`timeout`,cancelled:`cancelled`,malformed_response:`bad_response`,refused:`safety`,blocked:`blocked`,disclosure_blocked:`blocked`,declined:`declined`,failed:`failed`,internal:`internal`},zs={config:`invalid_config`,request:`invalid_request`,conflict:`conflict`,not_found:`not_found`,input:`invalid_input`,action:`not_allowed`,auth:`authentication`,rate_limit:`rate_limited`,busy:`busy`,unsupported:`unsupported`,unavailable:`unavailable`,bad_response:`malformed_response`,network:`network`,timeout:`timeout`,safety:`refused`,blocked:`blocked`,declined:`declined`,failed:`failed`,cancelled:`cancelled`,internal:`internal`},q=class extends R{code;status;constructor(e,t,n,r){super(Rs[e],t,r),this.code=e,this.status=n}};function Bs(e,t){let n=e.profiles.get(t);if(n.type!==`decision`)throw new R(`request`,`runDecision requires profile.type 'decision' (got '${n.type}' for ${n.id})`);return n}function Vs(e){let t=Vr(e.models),n=t?e.models[t]:void 0;if(!t||!n)throw new R(`config`,`Profile ${e.id}: type 'decision' must declare exactly one model`);return[t,n]}function J(e,t,n=0,r=1){if(typeof e!=`number`||!Number.isFinite(e)||e<n||e>r)throw new q(`malformed_response`,`${t} is outside its valid range`);return e}function Hs(e,t,n){if(!z(e)||Object.keys(e).length!==t.length||t.some(t=>!Object.hasOwn(e,t)))throw new q(`malformed_response`,`${n} does not match declared labels`);let r=Object.create(null);for(let i of t)r[i]=J(e[i],`${n}.${i}`);let i=Object.values(r).reduce((e,t)=>e+t,0);if(Math.abs(i-1)>.005*t.length+1e-9)throw new q(`malformed_response`,`${n} must sum to one`);return r}function Us(e,t){if(!z(e))throw new q(`malformed_response`,`${t} is invalid`);let n={top:J(e.top,`${t}.top`),bottom:J(e.bottom,`${t}.bottom`),left:J(e.left,`${t}.left`),right:J(e.right,`${t}.right`)};if(n.left>=n.right||n.top>=n.bottom)throw new q(`malformed_response`,`${t} has an edge out of order`);return n}function Ws(e,t,n){if(!z(e)||Object.keys(e).length!==t.length||t.some(t=>!Object.hasOwn(e,t))||Object.values(e).some(e=>typeof e!=`string`||!e.trim()))throw new q(`malformed_response`,`${n} is invalid`);return e}function Gs(e,t){if(!z(e)||Object.keys(e).length!==Object.keys(t).length)throw new q(`malformed_response`,`Decision provider returned an incomplete answer set`);let n=Object.create(null);for(let[r,i]of Object.entries(t)){let t=e[r];if(!z(t)||t.type!==i.type)throw new q(`malformed_response`,`Decision provider returned an invalid answer for '${r}'`);if(i.type===`choice`){let e=Object.keys(i.criteria);if(typeof t.choice!=`string`||!e.includes(t.choice))throw new q(`malformed_response`,`Decision provider returned an undeclared choice for '${r}'`);n[r]={type:`choice`,choice:t.choice,confidence:J(t.confidence,`${r}.confidence`),probabilities:Hs(t.probabilities,e,`${r}.probabilities`)}}else if(i.type===`noul`)n[r]={type:`noul`,noul:J(t.noul,`${r}.noul`)};else if(i.type===`box`)n[r]={type:`box`,box:Us(t.box,`${r}.box`),confidence:J(t.confidence,`${r}.confidence`)};else{let e=i.criteria.map((e,t)=>String(t));n[r]={type:`score`,score:J(t.score,`${r}.score`,0,Math.max(0,e.length-1)),confidence:J(t.confidence,`${r}.confidence`),legend:Ws(t.legend,e,`${r}.legend`),probabilities:Hs(t.probabilities,e,`${r}.probabilities`)}}}return n}function Ks(e){let t=new Set,n=[{value:e}];for(;n.length;){let e=n.pop();if(!e)break;let r=e.value;if(e.exit){t.delete(r);continue}if(r===null||typeof r==`string`||typeof r==`boolean`)continue;if(typeof r==`number`){if(!Number.isFinite(r))return!1;continue}if(typeof r!=`object`||t.has(r)||!Array.isArray(r)&&Object.getPrototypeOf(r)!==Object.prototype&&Object.getPrototypeOf(r)!==null||Object.getOwnPropertySymbols(r).length)return!1;t.add(r),n.push({value:r,exit:!0});let i=Array.isArray(r)?Array.from(r):Object.values(r);for(let e of i)n.push({value:e})}return!0}function qs(e,t){if(!z(t)||!e.trim()||!ec(t.instructions))throw new q(`invalid_request`,`Decision question '${e}' must include instructions`);if((t.type===`noul`||t.type===`box`)&&t.criteria===void 0)return;if(typeof t.type!=`string`||![`choice`,`noul`,`score`].includes(t.type)||(t.type===`score`?!Array.isArray(t.criteria):!z(t.criteria)))throw new q(`invalid_request`,`Decision question '${e}' has invalid criteria`);let n=Array.isArray(t.criteria)?t.criteria:Object.values(t.criteria);if(!n.length||!n.every(ec))throw new q(`invalid_request`,`Decision ${t.type} '${e}' must declare criteria`)}function Js(e,t){if(B(e.signal),e.model!==void 0)throw new q(`invalid_request`,`Decision requests do not select a model; the profile runs its one model`);if(e.state===null||!Ks(e.state))throw new q(`invalid_request`,`Decision state must be non-null JSON`);let n;try{n=JSON.stringify(e.state)}catch{throw new q(`invalid_request`,`Decision state cannot be serialized as JSON`)}let r=new TextEncoder().encode(n).byteLength;if(t.inputs.maxStateBytes!==void 0&&r>t.inputs.maxStateBytes)throw new q(`invalid_request`,`Decision state exceeds ${t.inputs.maxStateBytes} bytes`);if(!z(e.questions)||!Ks(e.questions)||Object.keys(e.questions).length===0)throw new q(`invalid_request`,`Decision request must declare at least one question`);for(let[t,n]of Object.entries(e.questions))qs(t,n);e.assets!==void 0&&$s(e.assets);for(let[t,n]of Object.entries(e.questions))Xs(t,n,e.state,e.assets)}function Ys(e,t){let n=e;for(let e of t.split(`.`)){if(!z(n)&&!Array.isArray(n))return;n=Array.isArray(n)?n[Number(e)]:n[e]}return n}function Xs(e,t,n,r){if(!z(t)||t.image===void 0)return;let i=t.image,a=typeof i==`string`&&!r?.[i]?Ys(n,i):i;if(t.type!==`box`||typeof a!=`string`||r?.[a]===void 0)throw new q(`invalid_request`,`Decision question '${e}' has an image that is neither a held image nor a state field holding one`)}function Zs(e,t){if(e.type!==`box`||e.image===void 0)return e;let{image:n,instructions:r}=e,i=V(`decision.box_image`,{image:t?.[n]?n:`\`${n}\``});return{type:`box`,instructions:typeof r==`string`?`${r} ${i}`:[r,i]}}var Qs=/^[A-Za-z0-9+/]+={0,2}$/;function $s(e){if(!z(e)||Object.keys(e).length===0)throw new q(`invalid_request`,`Decision assets must name at least one image`);for(let[t,n]of Object.entries(e))if(!t.trim()||!z(n)||n.mimeType!==`image/png`&&n.mimeType!==`image/jpeg`||typeof n.data!=`string`||n.data.length%4!=0||!Qs.test(n.data))throw new q(`invalid_request`,`Decision asset '${t}' must be PNG or JPEG bytes as padded base64`)}function ec(e){let t=[e];for(;t.length;){let e=t.pop();if(typeof e==`string`){if(!e.trim())return!1;continue}if(!z(e)&&!Array.isArray(e))return!1;let n=Object.values(e);if(!n.length)return!1;for(let e of n)t.push(e)}return!0}async function tc(e,t,n,r,i){if((await e.guardrails?.disclosure?.enforce(r.state,{destination:n,profileId:e.id,model:t,questionIds:Object.keys(r.questions),...i?{assets:i}:{}}))?.action===`block`)throw new q(`disclosure_blocked`,`Decision disclosure was blocked`)}function nc(e,t,n,r,i,a){return{...a?{"gen_ai.operation.name":a}:{},"gen_ai.provider.name":n.provider,"gen_ai.agent.name":e.id,...T(r),"gen_ai.request.model":n.apiId,"theorem.model.id":t,"theorem.decision.contract":e.decision.contract,"theorem.decision.state":U(r.state),"theorem.decision.questions":U(r.questions),...i?{"theorem.decision.assets":U(Object.fromEntries(Object.entries(i).map(([e,{mimeType:t,data:n}])=>[e,{mimeType:t,bytes:n.length}])))}:{}}}function rc(e,t){e.set({"gen_ai.response.model":t.model,"theorem.decision.answers":U(t.answers),...t.usage?{"gen_ai.usage.input_tokens":t.usage.inputTokens,"gen_ai.usage.output_tokens":t.usage.outputTokens,...t.usage.costUsd===void 0?{}:{"theorem.usage.cost_usd":t.usage.costUsd}}:{}})}function ic(e){if(e instanceof q)return e;let t=W(e);return new q(t===`auth`&&z(e)&&e.status===403?`permission`:zs[t],e instanceof R?e.message:V(`provider.decision_failed`),z(e)&&typeof e.status==`number`?e.status:void 0,{cause:e})}function ac(e){let t=Object.fromEntries(Object.entries(e.questions).map(([t,n])=>[t,Zs(n,e.assets)])),n=e.assets?S([e.state,...Object.values(t).flatMap(e=>[e.instructions,`criteria`in e?e.criteria:void 0])],e.assets):{};return{state:e.state,questions:t,...Object.keys(n).length?{assets:n}:{}}}async function oc(e,t,[n,r],i,a,o){B(i.signal);let s=e.providers.require(r.provider,r.apiId);await tc(t,n,r.provider,i,a.assets),B(i.signal);try{let e=await fs(s,r,`decision`,o,{...i.signal?{signal:i.signal}:{},...r.timeoutMs?{timeoutMs:r.timeoutMs}:{}}).decide({apiId:r.apiId,...a});if(typeof e.model!=`string`||!e.model.trim())throw new q(`malformed_response`,V(`provider.decision_model_missing`));return{...e,answers:Gs(e.answers,i.questions)}}catch(e){throw i.signal?.aborted?new q(`cancelled`,V(`provider.decision_ended`)):ic(e)}}async function sc(e,t,n){let r=Bs(e,t.profile);Js(t,r);let i=Vs(r),[a,o]=i,s=ac(t),c=e.providers.get(o.provider),l=c&&Ne(c,o,`decision`);return await Ls({name:l?`${l} ${o.apiId}`:o.apiId,attributes:nc(r,a,o,t,s.assets,l),traceparent:t.traceparent,links:t.links,metadata:t.metadata,writer:{override:n.sink,observability:r.observability,guardrails:r.guardrails}},async a=>{let o=await oc(e,r,i,t,s,n);return rc(a,o),o})}function cc(e,t){let n=e.profiles.get(t);if(n.type!==`embedding`)throw new R(`request`,`runEmbedding requires profile.type 'embedding' (got '${n.type}' for ${t})`);return n}function lc(e,t){let n=t??e.defaultModel;if(t&&!e.allowModelSelect)throw new R(`request`,`Profile ${e.id} does not allow model selection`);let r=e.models[n];if(!r)throw new R(`request`,`Unknown model '${n}' for ${e.id}`);return[n,r]}var uc=[`query`,`document`];function dc(e){if(e!==void 0&&!uc.includes(e))throw new R(`request`,`Embedding task must be 'query' or 'document'`)}function fc(e){return Array.isArray(e)?e:[e]}function pc(e){return typeof e==`string`?[{type:`text`,text:e}]:e&&Array.isArray(e.parts)?e.parts:[]}function mc(e,t,n,r){let i=rr(e.inputs,r);if(i.maxInputs!==void 0&&n.length>i.maxInputs)throw new R(`request`,`Model '${t}' of ${e.id} takes at most ${i.maxInputs} inputs per request`);let a=[];for(let t of n){let n=pc(t);if(n.length===0)throw new R(`request`,`Profile ${e.id} received an empty embedding input`);let r=[];for(let t of n)if(t.type===`text`){if(!i.text)throw new R(`unsupported`,`Profile ${e.id} does not accept text embedding input`)}else r.push(t.type===`media`?{mimeType:t.mimeType,sizeBytes:Wr(t.data)}:{mimeType:t.mimeType});a.push(r)}let o=tr(i,a);if(o.length>0)throw Ur(o)}function hc(e,t){if(!e.model.trim()||e.embeddings.length!==t)throw new R(`bad_response`,`Embedding provider returned an invalid vector count`);let n=e.embeddings.map((e,t)=>{if(e.index!==t||e.dimensions!==e.values.length||e.dimensions===0)throw new R(`bad_response`,`Embedding provider returned invalid vector metadata`);if(e.values.some(e=>!Number.isFinite(e)))throw new R(`bad_response`,`Embedding provider returned a non-finite vector value`);return e});return{...e,embeddings:n}}async function gc(e,t,n={}){B(t.signal);let r=cc(e,t.profile),[i,a]=lc(r,t.model),o=fc(t.input);dc(t.task);let s=e.providers.require(a.provider,a.apiId);mc(r,i,o,Qe(s,a).embeddingLimits?.(a.apiId));let c=fs(s,a,`embedding`,n,{...t.signal?{signal:t.signal}:{}}),l=Ne(s,a,`embedding`);return await Ls({name:l?`${l} ${a.apiId}`:a.apiId,attributes:{...l?{"gen_ai.operation.name":l}:{},"gen_ai.provider.name":a.provider,"gen_ai.agent.name":r.id,...T(t),"gen_ai.request.model":a.apiId,"theorem.model.id":i,"theorem.embedding.inputs":o.length,...t.task?{"theorem.embedding.task":t.task}:{}},traceparent:t.traceparent,links:t.links,metadata:t.metadata,writer:{override:n.sink,observability:r.observability,guardrails:r.guardrails}},async()=>hc(await c.embed({apiId:a.apiId,input:t.input,...t.task?{task:t.task}:{},...a.options?{options:a.options}:{},...t.signal?{signal:t.signal}:{}}),o.length))}function _c(e,t,n,r,i){let a=e.profiles.get(t);if(a.type===`host`)return vc(e,r);if(a.type===`decision`||a.type===`live`||a.type===`embedding`)throw new R(`unsupported`,V(`provider.turn_profile`));let o=a.models[n??a.defaultModel];if(!o)throw new R(`config`,V(`provider.model_binding_missing`));return ms(a.providerContinuation,i?.providerState,i?.input?.history),{complete:Ss(e.providers.require(o.provider,o.apiId),structuredClone(o),a.type,r,i?.providerState,a.providerContinuation,i?.input?.history).complete,forProfile:(t,n,i)=>_c(e,t,n,r,i)}}function vc(e,t){return{complete(){throw new R(`unsupported`,V(`provider.host_model`))},forProfile:(n,r,i)=>_c(e,n,r,t,i)}}function yc(e,t,n,r){return`forProfile`in e&&typeof e.forProfile==`function`?e.forProfile(t,n,r):e}function bc(e){let t;return{open:(n,r)=>(t=xt(n,{...r?{attributes:r}:{},traceparent:e.traceparent}),t.root),end:()=>{if(t)return e.write(t.collect())}}}function xc(){let e=e=>Math.ceil(e.length/4),t=t=>{let n={tokens:0,unknownMedia:0};for(let r of t)r.type===`text`?n.tokens+=e(r.text):n.unknownMedia+=1;return n};return{text:e,parts:t,messages:n=>{let r={tokens:0,unknownMedia:0};for(let i of n){let n=t(Ee(i));r.tokens+=n.tokens,r.unknownMedia+=n.unknownMedia;for(let t of i.tool_calls??[])r.tokens+=e(t.function.name)+e(t.function.arguments)}return r}}}function Sc(){return Promise.resolve(xc())}function Cc(e){return e.meter??`history`}function wc(e){let t=[];for(let n=0;n<e.length;n++)e[n].role===`user`&&t.push(n);return t}async function Tc(e){if(e?.historyTokens!=null)return{tokens:e.historyTokens,unknownMedia:0};let t=e?.history??[];return t.length===0?{tokens:0,unknownMedia:0}:await(await Sc()).messages(t)}async function Ec(e){let t=Cc(e.spec);if(t===`history`)return{meter:t,...await Tc(e.input)};if(e.prompt&&e.prompt.input>0)return{meter:t,tokens:e.prompt.input,unknownMedia:e.prompt.unknownMedia?.input??0};let n=e.input?.inputTokens;if(!(n==null||n<=0))return{meter:t,tokens:n,unknownMedia:0}}function Dc(e,t){return e>t.compactAt*t.maxTokens}async function Oc(e,t){if(t.trigger){let n={tokens:e.tokens,maxTokens:t.maxTokens,compactAt:t.compactAt,meter:e.meter,unknownMedia:e.unknownMedia};return await t.trigger(n)}return Dc(e.tokens,t)}async function kc(e,t){if(e.length===0)return{toCompact:[],toRetain:[]};if(t.previousExchanges===0)return{toCompact:[...e],toRetain:[]};let n=wc(e);if(n.length===0)return{toCompact:[...e],toRetain:[]};let r;if(t.previousExchanges>=1){let e=Math.min(t.previousExchanges,n.length);r=n[n.length-e]}else{let i=t.previousExchanges*t.maxTokens,a=await Sc(),o=0;r=e.length;for(let t=n.length-1;t>=0;t--){let s=n[t],c=t<n.length-1?n[t+1]:e.length,l=e.slice(s,c),u=a.messages(l).tokens;if(o+u>i)break;o+=u,r=s}}return r<=0?{toCompact:[],toRetain:[...e]}:{toCompact:e.slice(0,r),toRetain:e.slice(r)}}function Ac(e){return e.metadata?.compactionSummary===!0}function jc(e){return{type:`text`,text:e}}function Mc(e,t){let n=t.labels,r=new Map,i=0,a=e=>(e??[]).filter(e=>e.type===`text`||lt(t,e.mimeType)?!0:(i+=1,!1)),o=[];for(let t of e){for(let e of t.tool_calls??[])r.set(e.id,e.function.name);let e=a(t.parts);if(t.role===`tool`){let i=t.name??(t.tool_call_id?r.get(t.tool_call_id):void 0),a=t.content??``;o.push({role:`assistant`,parts:[jc(V(`compaction.tool_result`,{tool:i??``,result:a},n))]}),e.length>0&&o.push({role:`user`,parts:[jc(V(`compaction.tool_files`,{tool:i??``},n)),...e]});continue}let i=(t.tool_calls??[]).map(e=>jc(V(`compaction.tool_call`,{tool:e.function.name,arguments:e.function.arguments},n))),s=[...e,...i];(t.content||s.length!==0)&&o.push({role:t.role,...t.content?{content:t.content}:{},...s.length>0?{parts:s}:{},...t.name?{name:t.name}:{}})}return{history:o,droppedMedia:i}}function Nc(e,t,n,r){let i={toCompact:e.toCompact,droppedMedia:t.droppedMedia,...t.tokens?{tokens:t.tokens}:{}};if(`summary`in t){let n={role:`assistant`,content:t.summary,metadata:{compactionSummary:!0}};return{...i,outcome:`compacted`,summary:t.summary,history:[n,...e.toRetain]}}return n>r.maxTokens?{...i,outcome:`dropped`,failure:t.failure,history:[...e.toCompact.filter(Ac),...e.toRetain]}:{...i,outcome:`deferred`,failure:t.failure,history:[...e.toCompact,...e.toRetain]}}var Pc={[Jt.unscannable]:`egress.hint_unscannable`,[Jt.providerToolLeak]:`egress.hint_provider_tool_leak`},Fc=[rn.canary_leak],Ic=3,Lc=120,Rc=`detect.`;function zc(e,t,n){let r=Pc[e.rule];if(r)return V(r,{},n);let i=e.rule.startsWith(Rc)?e.rule.slice(7):e.rule;if(Dt(i))return t.hints?.[i]??V(`detect.hint.${i}`,{},n);let a=t.host?.find(({id:e})=>e===i),o=a?.label??e.label??i;return a?.hint??V(`detect.hint.own`,{label:o},n)}function Bc(e){let t=e.flatMap(({rule:e,match:t})=>t&&!Fc.includes(e)?[t]:[]);return[...new Set(t)].slice(0,Ic).map(e=>JSON.stringify(e.length>Lc?e.slice(0,Lc):e))}function Vc(e,t,n){let r=new Map;for(let t of e)r.set(t.rule,[...r.get(t.rule)??[],t]);let i=[...r.values()].map(e=>{let r=zc(e[0],t,n),i=Bc(e);return i.length>0?V(`egress.rejection_found`,{hint:r,matches:i.join(`, `)},n):r});return V(`egress.rejection`,{found:i.join(`
|
|
5
5
|
`)},n)}function Hc(e){if(e.type!==`transcription`&&e.type!==`live`&&e.type!==`host`&&e.type!==`decision`&&e.type!==`embedding`)return e.outputs}var Uc=[`inject`,`abort`,`deny`,`confirm`,`mutate`,`labelFailed`,`waitFor`],Wc=Object.freeze({pre_turn:Object.freeze([`inject`,`abort`]),pre_tool:Object.freeze([`abort`,`deny`,`confirm`,`mutate`,`waitFor`]),post_tool:Object.freeze([`inject`,`abort`,`deny`,`mutate`,`labelFailed`]),before_end:Object.freeze([`inject`,`abort`]),post_turn:Object.freeze([])}),Gc=new Set([...Uc,`injectId`,`released`]);function Kc(e,t){return Wc[e].includes(t)}function Y(e,t,n,r){e.push({code:t,field:n,message:r})}function qc(e,t){if(!z(e)){Y(t,`inject_invalid_messages`,`inject`,`inject entry must be an object`);return}if(e.role===`tool`){Y(t,`inject_invalid_messages`,`inject`,`inject messages with role "tool" are rejected`);return}if(e.role!==`user`&&e.role!==`assistant`&&e.role!==`system`){Y(t,`inject_invalid_messages`,`inject`,`inject role not allowed: ${String(e.role)}`);return}let n={role:e.role};if(e.content!==void 0){if(typeof e.content!=`string`){Y(t,`inject_invalid_messages`,`inject`,`inject content must be a string when present`);return}n.content=e.content}if(e.parts!==void 0){if(!Array.isArray(e.parts)){Y(t,`inject_invalid_messages`,`inject`,`inject parts must be an array when present`);return}n.parts=e.parts}if(e.tool_calls!==void 0){if(!Array.isArray(e.tool_calls)){Y(t,`inject_invalid_messages`,`inject`,`inject tool_calls must be an array when present`);return}n.tool_calls=e.tool_calls}if(e.name!==void 0){if(typeof e.name!=`string`){Y(t,`inject_invalid_messages`,`inject`,`inject name must be a string`);return}n.name=e.name}if(e.metadata!==void 0){if(!z(e.metadata)){Y(t,`inject_invalid_messages`,`inject`,`inject metadata must be a plain object`);return}n.metadata={...e.metadata}}return e.tool_call_id!==void 0&&Y(t,`inject_invalid_messages`,`inject`,`inject tool_call_id is rejected (not a tool-role message)`),n}function Jc(e,t){if(!Array.isArray(e)){Y(t,`inject_invalid_messages`,`inject`,`inject must be an array of history messages`);return}let n=[];for(let r of e){let e=qc(r,t);e&&n.push(e)}return n.length>0?n:void 0}function Yc(e,t){if(e!==void 0){if(typeof e==`number`&&Number.isInteger(e)&&e>=0)return e;Y(t,`inject_released_invalid`,`released`,`released must be a whole number of characters, 0 or more; ignored`)}}function Xc(e,t){let n=Jc(e.inject,t);if(!n)return;let r=Yc(e.released,t),i={messages:n,...r===void 0?{}:{released:r}};if(e.injectId===void 0)return i;if(typeof e.injectId==`string`&&e.injectId.trim())return{id:e.injectId,...i};Y(t,`inject_id_invalid`,`injectId`,`injectId must be a non-empty string; inject refused`)}function Zc(e,t,n){if(!(`inject`in e)||e.inject===void 0){e.injectId!==void 0&&Y(n.warnings,`inject_id_invalid`,`injectId`,`injectId without inject ignored`),e.released!==void 0&&Y(n.warnings,`inject_released_invalid`,`released`,`released without inject ignored`);return}let{stage:r,injectAllowed:i,injectWouldExceedMaxSteps:a}=t;if(!Kc(r,`inject`))Y(n.warnings,`affordance_not_allowed`,`inject`,`inject is not allowed at stage ${r}`);else if(!i)Y(n.warnings,`inject_not_allowed`,`inject`,`inject gate is closed for this profile/session`);else if(a)Y(n.warnings,`inject_rejected_max_steps`,`inject`,`inject rejected: another model step would exceed maxSteps`);else{let t=Xc(e,n.warnings);t&&(n.inject=t)}}function Qc(e,t,n){if(`abort`in e&&e.abort!==void 0){if(!Kc(t,`abort`))Y(n.warnings,`affordance_not_allowed`,`abort`,`abort is not allowed at post_turn`);else if(e.abort===!0)n.abort=!0;else if(z(e.abort)){let t=typeof e.abort.reason==`string`&&e.abort.reason.trim()?e.abort.reason.trim():void 0;n.abort=!t||{reason:t}}else e.abort!==!1&&Y(n.warnings,`abort_invalid`,`abort`,`abort must be boolean or { reason?: string }`)}}function $c(e,t,n){`deny`in e&&e.deny!==void 0&&(Kc(t,`deny`)?z(e.deny)?n.deny={code:typeof e.deny.code==`string`&&e.deny.code.trim()?e.deny.code.trim():`not_authorized`,message:typeof e.deny.message==`string`&&e.deny.message.trim()?e.deny.message.trim():`Tool execution not authorized`}:Y(n.warnings,`deny_invalid`,`deny`,`deny must be an object`):Y(n.warnings,`affordance_not_allowed`,`deny`,`deny is not allowed at stage ${t}`))}function el(e,t,n){`labelFailed`in e&&e.labelFailed!==void 0&&(Kc(t,`labelFailed`)?e.labelFailed===!0?n.labelFailed=!0:e.labelFailed!==!1&&Y(n.warnings,`label_failed_invalid`,`labelFailed`,`labelFailed must be true`):Y(n.warnings,`affordance_not_allowed`,`labelFailed`,`labelFailed is not allowed at stage ${t}`))}function tl(e,t,n){if(`confirm`in e&&e.confirm!==void 0){if(!Kc(t,`confirm`))Y(n.warnings,`affordance_not_allowed`,`confirm`,`confirm is not allowed at stage ${t}`);else if(e.confirm===!0)n.confirm={};else if(z(e.confirm)){let t=typeof e.confirm.summary==`string`&&e.confirm.summary.trim()?e.confirm.summary.trim():void 0;n.confirm=t?{summary:t}:{}}else Y(n.warnings,`confirm_invalid`,`confirm`,`confirm must be true or { summary?: string }`)}}function nl(e,t,n){`waitFor`in e&&e.waitFor!==void 0&&(Kc(t,`waitFor`)?!Array.isArray(e.waitFor)||!e.waitFor.every(e=>typeof e==`string`&&e.trim()!==``)?Y(n.warnings,`wait_for_invalid`,`waitFor`,`waitFor must be an array of call ids`):e.waitFor.length>0&&(n.waitFor=[...new Set(e.waitFor)]):Y(n.warnings,`affordance_not_allowed`,`waitFor`,`waitFor is not allowed at stage ${t}`))}var rl={pre_tool:`input`,post_tool:`output`};function il(e){return e in rl?rl[e]:void 0}function al(e,t,n){let{stage:r}=t;if(!(`mutate`in e)||e.mutate===void 0)return;if(!Kc(r,`mutate`)){Y(n.warnings,`affordance_not_allowed`,`mutate`,`mutate is not allowed at stage ${r}`);return}let i=il(r);i?!z(e.mutate)||e.mutate[i]===void 0?Y(n.warnings,`mutate_invalid`,`mutate`,`mutate must be { ${i}: unknown } at stage ${r}`):t.mutable===!1?Y(n.warnings,`mutate_invalid`,`mutate`,`there is no ${i} to replace at this ${r} fire`):n.mutate=i===`input`?{input:e.mutate.input}:{output:e.mutate.output}:Y(n.warnings,`mutate_invalid`,`mutate`,`no mutate subject is defined at stage ${r}`)}function ol(e){let t=[],n={warnings:t},{stage:r,result:i}=e;if(i==null)return n;if(!z(i))return Y(t,`result_invalid`,`result`,`StageResult must be a plain object`),n;for(let e of Object.keys(i))Gc.has(e)||Y(t,`unknown_field`,e,`unknown StageResult field "${e}" ignored`);return Zc(i,e,n),Qc(i,r,n),$c(i,r,n),tl(i,r,n),al(i,e,n),el(i,r,n),nl(i,r,n),n.deny&&n.confirm&&(Y(t,`confirm_invalid`,`confirm`,`confirm ignored because deny is set`),delete n.confirm),n}function sl(e,t){let n={type:`stage`,stage:e};return t&&(t.callId!==void 0&&(n.callId=t.callId),t.toolName!==void 0&&(n.toolName=t.toolName),t.callNotStarted!==void 0&&(n.callNotStarted=t.callNotStarted),t.awaiting!==void 0&&(n.awaiting=t.awaiting),t.gate!==void 0&&(n.gate=t.gate),t.stop!==void 0&&(n.stop=t.stop),t.injected!==void 0&&(n.injected=t.injected),t.released!==void 0&&(n.released=t.released)),n}function cl(e){return e.flatMap(e=>e.messages)}function ll(e,t,n){let r=t.flatMap(e=>e.id===void 0?[]:[{id:e.id,messages:e.messages}]);if(r.length!==0||n?.released!==void 0)return sl(e,{...n,...r.length>0?{injected:r}:{}})}function ul(e,t){return t===void 0||t<=0?!1:e>=t}function dl(e,t){return t===`inject`?e.inject.length>0:!!e[t]}function fl(e){let t={warnings:e.flatMap(e=>e.warnings),inject:[]};for(let n of e)n.abort!==void 0&&(t.abort=n.abort),n.deny&&(t.deny=n.deny),n.confirm&&(t.confirm=n.confirm),n.mutate&&(t.mutate=n.mutate),n.labelFailed&&(t.labelFailed=!0),n.waitFor&&(t.waitFor=[...new Set([...t.waitFor??[],...n.waitFor])]),n.inject&&t.inject.push(n.inject);return t.deny&&t.confirm&&(Y(t.warnings,`confirm_invalid`,`confirm`,`confirm ignored because deny is set`),delete t.confirm),t}async function pl(e,t,n,r){let i=[];for(let a of e){let e;try{e=await a({...t})}catch(e){throw B(r),e}B(r),i.push(ol({...n,result:e}))}return i}async function*ml(e){let{stage:t,step:n,history:r,handlers:i,guardrails:a,injectAllowed:o,injectWouldExceedMaxSteps:s,mutable:c,host:l,signal:u,span:d,...f}=e;if(B(u),yield sl(t,{callId:f.callId,toolName:f.tool,callNotStarted:f.callNotStarted,awaiting:f.awaiting,gate:f.gate,stop:f.stop}),i.length===0)return d?.event(`theorem.stage`,{stage:t,affordance:[]}),{warnings:[],inject:[]};let p={stage:t,step:n,history:r,host:l,...f},m=d?.msSinceStart(),h=fl(await pl(i,p,{stage:t,injectAllowed:o,injectWouldExceedMaxSteps:s,mutable:c},u));if(d?.event(`theorem.stage`,{stage:t,...m===void 0?{}:{hook_ms:d.msSinceStart()-m},affordance:Uc.filter(e=>dl(h,e)),...h.warnings.length>0?{warnings:h.warnings.map(e=>e.code)}:{}}),h.warnings.length>0&&(yield{...sl(t,{callId:f.callId,toolName:f.tool}),stageWarnings:h.warnings}),h.inject.length===0)return h;let g=an(`injected`,M(a).detect),_=h.inject.map(e=>({...e,messages:ar(e.messages,g)})),v=g.found(),y=jt(`injected`,v);if(y&&(d?.event(`theorem.guardrail`,Ve(y)),yield G(y)),v.action===`block`)throw gr(`injected`);return{...h,inject:_}}function hl(e,t,n){if(e.currentHistory.push(...t),n!==void 0)for(let r of t)typeof r.content==`string`&&e.replyMessages.push({message:r,at:n})}function gl(e){let t=e.flatMap(e=>e.released===void 0?[]:[e.released]);return t.length>0?Math.min(...t):void 0}function _l(e,t){let n=[...e],r=t;for(let e=n.length-1;e>=0&&r>0;--e){let t=n[e];if(t?.type!==`text`)continue;let i=Math.max(0,t.text.length-r);r-=t.text.length-i,i===0?n.splice(e,1):n[e]={...t,text:t.text.slice(0,i)}}return n}function vl(e,t){if(t===void 0||t>=e.replyText.length)return;let n=e.replyText.length-t;e.replyText=e.replyText.slice(0,t),e.released=e.released.slice(0,Math.max(0,e.released.length-n)),e.attemptEvents=_l(e.attemptEvents,n);let r=[];for(let{message:n,at:i}of e.replyMessages){let a=typeof n.content==`string`?n.content:``,o=a.slice(0,Math.max(0,t-i)),s=e.currentHistory.indexOf(n);if(!(s<0)){if(o){let t=o===a?n:{...n,content:o};e.currentHistory[s]=t,r.push({message:t,at:i})}else e.currentHistory.splice(s,1)}}return e.replyMessages=r,t}function*yl(e,t,n,r){let i=cl(n);if(i.length===0)return 0;let a=vl(e,gl(n));e.currentHistory.push(...i);let o=ll(t,n,{...r,...a===void 0?{}:{released:a}});return o&&(e.allEmittedEvents.push(o),yield o),i.length}async function*bl(e){let{profile:t,generation:n,state:r,onStage:i,host:a,reply:o,replyAt:s,...c}=e;B(c.signal);let l=ml({...c,...o?{reply:o}:{},history:r.currentHistory,handlers:i?[i]:[],guardrails:t.guardrails,injectAllowed:fe(t),host:a??n.host,span:r.trace.root}),u=await l.next();for(;!u.done;)r.allEmittedEvents.push(u.value),yield u.value,u=await l.next();let d=u.value;return o&&cl(d.inject).length>0&&hl(r,o,s),{abort:d.abort,injectCount:yield*yl(r,c.stage,d.inject),warnings:d.warnings}}function xl(e,t){t.allEmittedEvents.push(e),t.attemptEvents.push(e)}function Sl(e,t){if(t.length===0)return;let n=t.every(e=>e.type===`text`);e.currentHistory.push(n?{role:`user`,content:t.map(e=>e.type===`text`?e.text:``).join(``)}:{role:`user`,parts:[...t]})}function Cl(e){let{profile:t,generation:n}=e,r=br(e.tools,t),i={tools:e.tools,trace:e.trace,currentHistory:[...n.history??[]],turnStart:n.history?.length??0,stepCount:0,resumes:0,toolResults:[],allEmittedEvents:e.allEmittedEvents??[],attemptEvents:[],released:``,replyText:``,replyMessages:[],givenUrls:ln(),destinations:Ni(),canaryGiven:!1,canaryScanned:new WeakSet,...r?{ownTools:r}:{},...e.agents?{agents:e.agents}:{},...e.background?{background:e.background}:{}};return t.type===`text`&&(Sl(i,n.input),n.input=[]),i}function wl(e){return e.turnOnly?e.currentHistory.slice(e.turnStart):e.currentHistory}function Tl(e){return e.turnOnly===!0&&e.turnStart>0}function El(e,t,n={}){return t.map(t=>{if(e.get(t)?.type!==`builtin`)throw new R(`config`,`Builtin '${t}' is not registered`);let r=n[t];return r?{id:t,args:r}:{id:t}})}function Dl(e,t,n){return{model:t.model,apiId:t.apiId,stream:t.stream,thinking:t.thinking,summaries:t.summaries,maxOutputTokens:t.maxOutputTokens,temperature:t.temperature,builtins:El(e,t.builtins,t.builtInArgs),sessionId:t.sessionId,system:n,input:t.input,history:t.history,wireTools:t.tools.wire,structured:t.structured,image:t.image,speech:t.speech,live:t.live}}function Ol(){let e=()=>void 0;return{promise:new Promise(t=>{e=t}),resolve:e}}function kl(e,t,n){let r=new Set,i=new Map(e.map(e=>[e,Ol()])),a=new Map,o=new Map,s=new Map,c=n=>t?[]:e.slice(0,e.indexOf(n));for(let t of e){let e=c(t);e.length>0&&a.set(t,new Map(e.map(e=>[e,`after`])))}let l=(e,t,n=new Set)=>{if(e===t)return[t];if(!(n.has(e)||r.has(e))){n.add(e);for(let r of a.get(e)?.keys()??[]){let i=l(r,t,n);if(i)return[e,...i]}}},u=(e,t)=>{o.get(e)?.(t),o.delete(e),s.get(e)?.(),s.delete(e);for(let[t,n]of a.get(e)??[])n===`asked`&&a.get(e)?.delete(t)},d=e=>i.get(e)?.promise??Promise.resolve();return{start:async e=>{await Promise.all(c(e).map(d)),B(n)},settle:e=>{r.add(e),a.delete(e),i.get(e)?.resolve()},wait:(e,t)=>{let c=t.filter(e=>!i.has(e));if(c.length>0)return Promise.resolve({ok:!1,reason:`unknown`,callIds:c});let f=t.filter(e=>!r.has(e));if(f.length===0)return Promise.resolve({ok:!0});let p=a.get(e)??new Map;a.set(e,p);for(let e of f)p.set(e,`asked`);let m=f.flatMap(t=>{let n=l(t,e);return n?[{id:t,path:n}]:[]});if(m.length>0){for(let{path:t}of m)for(let[n,r]of t.entries()){let i=t[n+1];i!==void 0&&r!==e&&a.get(r)?.get(i)===`asked`&&u(r,{ok:!1,reason:`cycle`,callIds:[i]})}return u(e,{ok:!1,reason:`cycle`,callIds:m.map(({id:e})=>e)}),Promise.resolve({ok:!1,reason:`cycle`,callIds:m.map(({id:e})=>e)})}let h=Ol();o.set(e,h.resolve),Promise.all(f.map(d)).then(()=>u(e,{ok:!0}));let g=new Promise((t,r)=>{if(!n)return;let i=()=>r(n.reason);n.addEventListener(`abort`,i,{once:!0}),s.set(e,()=>n.removeEventListener(`abort`,i))});return g.catch(()=>{}),Promise.race([h.promise,g])}}}async function*Al(e,t,n){try{return await e.start(t),yield*n()}finally{e.settle(t)}}async function*jl(e){let t=e.map(()=>void 0),n=new Map,r=(e,t)=>{let r=t.next().then(t=>({index:e,next:t}));r.catch(()=>{}),n.set(e,r)};e.forEach((e,t)=>{e&&r(t,e)});try{for(;n.size>0;){let{index:i,next:a}=await Promise.race(n.values());n.delete(i);let o=e[i];a.done||!o?a.done&&(t[i]=a.value):(yield a.value,r(i,o))}}finally{for(let t of n.keys())e[t]?.return(void 0).catch(()=>{})}return t}var Ml=class{outcome;constructor(e){this.outcome=e}},Nl=class{reply;constructor(e){this.reply=e}},Pl=Symbol(`fired`),Fl=Symbol(`cut`),Il=class{at;turnSignal;controller=new AbortController;firing=Ol();timer;ended=!1;forward=()=>this.controller.abort();constructor(e,t){this.at=e,this.turnSignal=t,t?.aborted&&this.forward(),t?.addEventListener(`abort`,this.forward,{once:!0})}get signal(){return this.controller.signal}get fired(){return this.firing.promise}claimed(){this.ended||(this.at===`claim`?this.firing.resolve(Pl):this.timer=setTimeout(()=>this.firing.resolve(Pl),this.at.afterMs))}bodyEnded=()=>{this.ended=!0,clearTimeout(this.timer)};abort(){this.controller.abort()}release(){this.bodyEnded(),this.turnSignal?.removeEventListener(`abort`,this.forward)}};function Ll(e,t,n,r){let{name:i,callId:a,operationId:o}=e,s=Fe(n),c=L({name:i,callId:a,...o?{operationId:o}:{}},n),l=r?{...c,tool:{...c.tool,tokens:r}}:c;return Bn.parse(Jn({event:l,effects:t,replay:{modelResult:s,failure:n}}))}function Rl(e){return nr(e.kind===`auth`?`auth`:`internal`,`The tool asked for a ${e.kind} gate after it was sent, so its effects are unknown`)}var zl=class{coordinator;operation;accepted;signal;trigger;claim;committed=!1;writeFailed=!1;terminal;stopped;spent;cut=Ol();graceTimer;constructor(e,t,n,r,i){this.coordinator=e,this.operation=t,this.accepted=n,this.signal=r,this.trigger=i}async beginBody(e){B(this.signal);let t={...this.operation,invocation:{accepted:this.accepted,preparedInput:Jn(e)}},n=await this.coordinator.begin(t);if(n.kind===`settled`)throw new Ml(n.outcome);if(n.kind===`background`)throw new Nl(n.reply);if(n.kind===`running`||n.kind===`uncertain`)throw _r(n.kind);if(n.kind!==`acquired`||typeof n.claimToken!=`string`||!n.claimToken)throw Fn(`The tool coordinator's begin returned no claim`);return this.claim={...t,claimToken:n.claimToken},B(this.signal),this.trigger?.claimed(),this.claim}spend(e){this.spent=e}observe(e){if(e.type!==`tool`)return!0;if(e.tool.phase===`complete`||e.tool.phase===`error`)return this.terminal={...e,tool:e.tool},this.trigger?.bodyEnded(),!1;if(this.claim&&e.tool.phase===`gate`)throw Rl(e.tool.gate);return!0}async finish(e){if(e.gated){if(this.claim)throw Rl(e.gated);return{settlement:e}}if(!this.terminal)throw Fn(`The tool run ended with no terminal event`);let{modelResult:t,outputRaw:n,failure:r,awaiting:i,denied:a,callNotStarted:o,aborted:s,pendingInject:c}=e,l=this.claim?r?`unknown`:`completed`:`not_started`,u={event:this.terminal,effects:l,replay:{modelResult:t,outputRaw:n,failure:r,awaiting:i,denied:a,callNotStarted:o,aborted:s,pendingInject:c}},d=Bn.parse(Jn(u)),f=this.withinLimit(d);return await this.save(f),{terminal:f.event,settlement:f===d?e:f.replay}}async save(e){this.writeFailed=!0,this.claim?await this.coordinator.settle(this.claim,e):await this.coordinator.settleNotStarted(this.operation,e),this.committed=!0}base(){let{toolId:e,callId:t,operationId:n}=this.operation;return{name:e,callId:t,operationId:n}}async detach(e,t,n){let{claim:r,coordinator:i,trigger:a}=this;if(!r||!i.detach||!a)throw Fn(`The tool detached with no claim`);let o=e.reply(),s=Ol(),c={...this.call(),stop:(e,t)=>this.stop(e,t),done:s.promise};try{await i.detach(r,o),B(this.signal),e.support.service.detached(c)}catch(e){throw this.writeFailed=!this.signal?.aborted,a.abort(),e}return a.release(),this.goOn(e,t,n).finally(()=>s.resolve()),o}call(){let{operationId:e,callId:t,toolId:n}=this.operation;return{operationId:e,callId:t,toolId:n}}stop(e,t){this.committed||(this.stopped??=e===void 0?{}:{reason:e},this.trigger?.abort(),t?.graceMs!==void 0&&this.graceTimer===void 0&&(this.graceTimer=setTimeout(()=>this.cut.resolve(Fl),t.graceMs)))}async goOn(e,t,n){let{service:r,project:i}=e.support,a=async e=>{try{await r.event(i(e),this.call())}catch{}};try{await this.drain(t,n,a)}catch{}finally{clearTimeout(this.graceTimer),await this.close().catch(()=>{}),await Promise.resolve(e.trace.end()).catch(()=>{})}}async drain(e,t,n){let r=t;try{for(;;){let t=await Promise.race([r,this.cut.promise]);if(t===Fl)return e.return({}).catch(()=>{}),await this.settleStopped(n);if(t.done)return await this.settleAfterReply(t.value,n);this.observe(t.value)&&await n(t.value),r=e.next()}}catch(e){throw this.writeFailed||await this.settleStopped(n),e}}async settleAfterReply(e,t){if(this.stopped)return this.settleStopped(t);if(e.awaiting)return this.settleFailed({code:`awaiting_after_reply`,kind:`internal`,message:`The tool asked to wait for a result after its turn ended`},t);let{pendingInject:n,aborted:r,...i}=e,{terminal:a}=await this.finish(i);a&&await t(a)}async settleStopped(e){let t=this.stopped?.reason;t!==void 0&&await this.settleFailed({code:t,kind:`cancelled`,message:`The tool call was stopped: ${t}`},e)}async settleFailed(e,t){let n=Ll(this.base(),`unknown`,e,this.spent);await this.save(n),await t(n.event)}withinLimit(e){let t=this.coordinator.maxOutcomeBytes;if(t===void 0)return e;let n=new TextEncoder().encode(JSON.stringify(e)).byteLength;if(n<=t)return e;let{name:r}=e.event.tool,i={code:`result_too_large`,kind:`bad_response`,message:`The result of ${r} is ${n} bytes, more than the ${t} bytes kept for one tool result`,details:{bytes:n,maxOutcomeBytes:t}};return Ll(e.event.tool,e.effects,i)}replay(e){let t=Bn.parse(Jn(e.outcome));return this.assertOwn(t,`outcome`),this.committed=!0,t}replayReply(e){let t=On.parse(Jn(e));return this.assertOwn(t,`reply`),this.committed=!0,t}assertOwn(e,t){let{operationId:n,callId:r,toolId:i}=this.operation,{tool:a}=e.event;if(a.operationId!==n||a.callId!==r||a.name!==i)throw Fn(`The tool coordinator's saved ${t} is another operation's`)}failure(e){return!this.claim||this.committed?e:nr(W(e),`The tool was sent and did not settle, so its effects are unknown`,e)}async close(){this.claim&&!this.committed&&await this.coordinator.markUncertain(this.claim,this.writeFailed?`settlement_write_failed`:`execution_interrupted`)}};async function Bl(e,t,n){if(!n)throw Fn(`A settled tool operation has no replay check`);if(t instanceof Nl){let r=e.replayReply(t.reply);return await n(),r}let r=e.replay(t);return await n(r),r}function Vl(e){if(e?.kind===`background`)return new Nl(e.reply);if(e?.kind===`settled`)return new Ml(e.outcome)}async function*Hl(e,t,n,r,i,a,o){if(!e)return yield*i(void 0,{signal:r});let s=it.parse(Jn(n)),c={...t,invocationHash:await Yn(s)},l=o?new Il(o.at,r):void 0,u=l?l.signal:r,d=new zl(e,c,s,u,l);B(r);let f=await e.lookup(c);if(B(r),f?.kind===`running`||f?.kind===`uncertain`)throw _r(f.kind);let p=Vl(f);if(p){let e=await Bl(d,p,a);return B(r),yield e.event,e.replay}let m=i(e=>d.beginBody(e),{signal:u,spent:e=>d.spend(e),...l?{bodyEnded:l.bodyEnded}:{}}),h=!1;try{let e=m.next();for(;;){let t=await(l?Promise.race([e,l.fired]):e);if(t===Pl){if(!o)throw Fn(`The tool detached with no plan`);let t=await d.detach(o,m,e);return h=!0,yield t.event,{...t.replay}}if(t.done){let{terminal:e,settlement:n}=await d.finish(t.value);return e&&(yield e),n}d.observe(t.value)&&(yield t.value),e=m.next()}}catch(e){if(e instanceof Ml||e instanceof Nl){let t=await Bl(d,e,a);return yield t.event,t.replay}throw d.failure(e)}finally{if(!h){l?.release();try{await d.close()}finally{await m.return({}),await o?.trace.end()}}}}function*Ul(e,t){t.kind===`progress`?yield I(e,{phase:`progress`,data:t.data}):t.kind===`draft`?yield I(e,{phase:`draft`,text:t.text}):t.kind===`trace`?yield I(e,{phase:`trace`,step:t.step}):t.kind===`artifact`?yield I(e,{phase:`artifact`,artifact:t.artifact}):t.kind===`warning`&&(yield I(e,{phase:`warning`,warning:t.warning}))}var Wl=class{base;checks;drafts;constructor(e,t){this.base=e,this.checks=t,t?.drafts&&(this.drafts=new Cr(()=>Gl(t)))}async*show(e){if(e.kind===`draft`)yield*this.draft(e.text);else if(!(e.kind===`progress`&&(yield*this.progressStops(e.data)))){if(e.kind===`artifact`){let t=yield*this.shown(e.artifact);t.shown&&(yield*Ul(this.base,{...e,artifact:t.value}))}else if(e.kind===`trace`){let t=yield*this.shown(e.step);t.shown&&(yield*Ul(this.base,{...e,step:t.value}))}else yield*Ul(this.base,e)}}*end(){let e=this.drafts?.end();e&&(yield I(this.base,{phase:`draft`,text:e}))}async*draft(e){let t=await this.drafts?.read(e);t&&(yield I(this.base,{phase:`draft`,text:t}))}*shown(e){let t=this.checks;if(!t)return{shown:!0,value:e};let n=x(e,t.provenance,t.policy,t.shown);return n.event&&(yield{type:`guardrail`,guardrail:n.event}),`value`in n?{shown:!0,value:n.value}:{shown:!1}}*progressStops(e){let t=this.checks;if(!t)return!1;let{event:n,text:r}=He(``,e,t.provenance,t.policy,t.boundary,t.callableTools);return r!==void 0&&(n===void 0||n.action===`flag`)?!1:(n&&(yield{type:`guardrail`,guardrail:n}),!0)}};function Gl(e){return Er(e.policy,{stage:`tool_result`,trust:`untrusted`,profileId:e.profileId,provenance:e.provenance},e.boundary,{callable:e.callableTools})}var Kl=new Set([`image/png`,`image/jpeg`,`image/gif`,`image/webp`]);async function ql(e,t=1/0){let n=Number(e.headers.get(`content-length`));if(Number.isFinite(n)&&n>t){await e.body?.cancel().catch(()=>{});return}if(!e.body)return new Uint8Array(await e.arrayBuffer());let r=e.body.getReader(),i=[],a=0;for(;;){let{done:e,value:n}=await r.read();if(e)break;if(a+=n.byteLength,a>t){await r.cancel().catch(()=>{});return}i.push(n)}let o=new Uint8Array(a),s=0;for(let e of i)o.set(e,s),s+=e.byteLength;return o}function Jl(e,t){if(t===void 0)return e.signal;let n=AbortSignal.timeout(t);return e.signal?AbortSignal.any([e.signal,n]):n}async function Yl(e,t,n){let r=Jl(t,n.timeoutMs),i=await we(e,{method:`GET`,headers:{Accept:`image/*`},signal:r},{policy:Le(t),followRedirects:!0,resolveHost:t.resolveHost});if(!i.ok)throw Error(`HTTP ${i.status}`);let a=(i.headers.get(`content-type`)??``).split(`;`)[0]?.trim().toLowerCase();if(!a||!Kl.has(a))throw await i.body?.cancel().catch(()=>{}),Error(`not a png, jpeg, gif or webp image (${a||`no type`})`);let o=await ql(i,n.bytes);if(!o)throw Error(`larger than ${n.bytes} bytes`);return{type:`image`,mimeType:a,data:vn(o)}}function Xl(e){if(typeof e!=`string`)return{reason:`an address that is not text`};try{if(new URL(e).protocol===`https:`)return{url:e}}catch{}return{reason:`${e.slice(0,80)}: not an absolute https address`}}async function Zl(e,t,n,r={}){let i=[],a=[];try{for(let n of new Set(e(t))){let e=Xl(n);`url`in e?a.push(e.url):i.push(e.reason)}}catch(e){return{parts:[],urls:[],warning:Ql([`the images hook threw: ${String(e)}`])}}let o=a.slice(0,r.count),s=await Promise.allSettled(o.map(e=>Yl(e,n,r))),c=r.totalBytes??1/0,l=[],u=[],d=0;return s.forEach((e,t)=>{let n=o[t];if(e.status===`rejected`){let t=e.reason instanceof Error?e.reason.message:String(e.reason);i.push(`${new URL(n).hostname}: ${t}`);return}let r=`data`in e.value?e.value.data.length:0;d+r>c?i.push(`${new URL(n).hostname}: past the ${c} byte total`):(d+=r,l.push(e.value),u.push(n))}),{parts:l,urls:u,...i.length?{warning:Ql(i)}:{}}}function Ql(e){return{code:`images_unfetched`,severity:`warning`,message:`Some pictures the tool named were left out. ${e.join(`; `)}`}}function $l(e){return typeof e?.granted==`boolean`}function eu(e){return e?.granted===!0}function tu(e){return e?.granted===!1}function nu(e,t){return t?t.includes(`*`)||t.includes(e):!1}function ru(e,t){let n=ge(e.labels?.request,{input:t});return{access:e.access,...n?{request:n}:{}}}function iu(e,t,n,r,i){return t===`auto`||(t===`always_confirm`?r?.granted===!0:nu(e,n))?null:{kind:`permission`,tool:e,permission:t,...i}}function au(e,t,n){return we(e,t,{policy:n.network,followRedirects:!1,resolveHost:n.resolveHost,...n.fetchFn?{fetchFn:n.fetchFn}:{}})}function ou(e,t){if(typeof e!=`string`)throw Error(`OAuth ${t} is missing`);let n;try{n=new URL(e)}catch{throw Error(`OAuth ${t} "${e}" is not a URL`)}if(n.protocol!==`https:`||n.hash)throw Error(`OAuth ${t} "${e}" must be an https URL without a fragment`);return n}var su=/^[\x20\x21\x23-\x5B\x5D-\x7E]*$/;async function cu(e){let t;try{t=await e.json()}catch{return``}if(!z(t))return``;let{error:n,error_description:r}=t;return typeof n!=`string`||!su.test(n)?``:typeof r==`string`&&su.test(r)?`: ${n} (${r})`:`: ${n}`}function lu(e,t){let n=e=>{throw Error(`Token response from ${t} ${e}`)};if(!z(e))return n(`is not a JSON object`);let r=e;(typeof r.access_token!=`string`||r.access_token.length===0)&&n(`has no access_token`),(typeof r.token_type!=`string`||r.token_type.toLowerCase()!==`bearer`)&&n(`has token_type "${String(r.token_type)}", not Bearer`);let i=r.expires_in;i!==void 0&&(typeof i!=`number`||!Number.isFinite(i)||i<0)&&n(`has an expires_in that is not a number of seconds`);for(let e of[`refresh_token`,`scope`])r[e]!==void 0&&typeof r[e]!=`string`&&n(`has a ${e} that is not a string`);return r}function uu(e){return e===void 0?[]:e.split(` `).filter(e=>e.length>0)}function du(e,t,n){if(t.length===0)return;let r=uu(e).flatMap(e=>t.includes(e)?[]:e.split(`,`).filter(e=>!t.includes(e)));if(r.length>0)throw Error(`Token response from ${n} grants scopes that were not asked for: ${r.join(`, `)}`)}async function fu(e,t,n,r,i){let{clientSecret:a,...o}=t,s=new URLSearchParams({...n,client_id:t.clientId,...a===void 0?{}:{client_secret:a},resource:t.resource}),c=await au(t.tokenEndpoint,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`,Accept:`application/json`},body:s.toString()},e);if(!c.ok)throw Error(`${i?`Token refresh failed`:`Token exchange failed`} at ${t.tokenEndpoint} (HTTP ${c.status})${await cu(c)}`);let l=lu(await c.json(),t.tokenEndpoint);return du(l.scope,r,t.tokenEndpoint),{tokens:l,credential:{type:`oauth2`,...o,accessToken:l.access_token,refreshToken:l.refresh_token??i?.refreshToken,expiresAt:l.expires_in===void 0?void 0:Date.now()+l.expires_in*1e3,scope:l.scope??i?.scope??(r.length>0?r.join(` `):void 0)}}}function pu(e){return ou(e.tokenEndpoint,`token_endpoint`),ou(e.resource,`resource`),fu(e,{issuer:e.issuer,resource:e.resource,tokenEndpoint:e.tokenEndpoint,clientId:e.clientId,...e.clientSecret===void 0?{}:{clientSecret:e.clientSecret}},{grant_type:`refresh_token`,refresh_token:e.refreshToken,...e.scope?{scope:e.scope}:{}},uu(e.scope),{refreshToken:e.refreshToken,scope:e.scope})}function mu(e,t){let n;try{n=new URL(e)}catch{return!1}if(n.origin!==t.origin)return!1;let r=n.pathname.replace(/\/$/,``);return t.pathname===r||t.pathname.startsWith(`${r}/`)||r===``}var hu={now:Date.now,wait:Ya},gu=new WeakMap;function _u(e){let t=gu.get(e);if(t)return t;let n={places:[],heldUntil:0,waiting:new Set};return gu.set(e,n),n}function vu(e,t,n){e.places=e.places.filter(e=>e.opensAt>n);let r=e.places.length<t.requests?n:Math.min(...e.places.map(e=>e.opensAt));return Math.max(r,e.heldUntil)}async function yu(e,t,n,r){let i=new AbortController,a=()=>i.abort();e.waiting.add(a);try{await r.wait(t,n?AbortSignal.any([n,i.signal]):i.signal)}catch(e){if(n?.aborted||!i.signal.aborted)throw e}finally{e.waiting.delete(a)}}async function bu(e,t,n,r=hu){let i=_u(e),a=r.now()+Ga;for(;;){let e=r.now(),o=vu(i,t,e);if(o<=e){let e={opensAt:1/0};return i.places.push(e),{answered:n=>{let a=r.now();e.opensAt=a+t.windowMs;let o=n?.status===429?eo(n.headers,a):void 0;o!==void 0&&(i.heldUntil=Math.max(i.heldUntil,a+o));for(let e of i.waiting)e()}}}if(o>a&&o!==1/0)return{full:!0,limit:t,opensInMs:o-e};if(e>=a)return{full:!0,limit:t,opensInMs:void 0};await yu(i,Math.min(o,a)-e,n,r)}}async function xu(e,t){try{let n=await t;return e?.answered(n),n}catch(t){throw e?.answered(),t}}function Su(e){return{handlers:[],profile:e.profile,step:e.turn?.step??1,history:()=>[],injectAllowed:!1,host:e.host,signal:e.signal}}function Cu(e){let t=eu(e),n=t&&e?.gateKind!==`permission`&&e?.gateKind!==`auth`;return{confirmed:n,approvedAsIs:n&&e?.edited===void 0,approved:t&&e?.gateKind!==`auth`}}function wu(e,t){return{ok:!1,kind:`failed`,failure:{code:`invalid_input`,kind:`bad_response`,message:V(`tool.input_invalid_after_mutate`,{},t.profile.labels),details:e.flatten()}}}async function*Tu(e){let{tool:t,ctx:n,base:r,stages:i}=e,{input:a,names:o}=Dr(t,e.input),s=n.resume?[]:An(o,r.callId,i?.stepCalls),c,{confirmed:l,approved:u,approvedAsIs:d}=Cu(n.resume);if(t.preTool&&!d&&(c=await t.preTool(a,n)??void 0),!i&&c===void 0&&s.length===0)return{ok:!0,input:a};let f=yield*Eu({stages:i??Su(n),toolName:t.name,callId:r.callId,input:a,toolPreTool:c,details:ru(t,a),confirmed:l,approved:u});if(!f.ok){if(f.kind!==`gated`)return f;if(`input`in f){let e=f.input,r=t.input.safeParse(qr(e));if(!r.success)return wu(r.error,n);f.gate={...f.gate,...ru(t,r.data),preparedArguments:it.parse(Jn(qr(e)))}}return yield sl(`pre_tool`,{callId:r.callId,toolName:t.name,callNotStarted:!0,gate:f.gate}),yield I(r,{phase:`gate`,gate:f.gate}),f}let p=f.mutated?t.input.safeParse(qr(f.input)):void 0;if(p&&!p.success)return wu(p.error,n);let m=await Du(i,r.callId,t.name,[...f.waitFor??[],...s],n.profile.labels);return m?{ok:!1,kind:`failed`,failure:m}:{ok:!0,input:p?p.data:f.input}}async function*Eu(e){let{stages:t,toolName:n,callId:r,input:i,toolPreTool:a,details:o,confirmed:s,approved:c}=e,l=yield*ml({stage:`pre_tool`,step:t.step,history:t.history(),handlers:[...a===void 0?[]:[()=>a],...t.handlers],guardrails:t.profile.guardrails,injectAllowed:!1,host:t.host,signal:t.signal,span:t.span,callId:r,tool:n,input:i,...c?{approved:!0}:{},...t.stepCalls?{stepCalls:t.stepCalls}:{}});if(l.abort)return{ok:!1,kind:`aborted`,aborted:l.abort};if(l.deny)return{ok:!1,kind:`failed`,failure:{...l.deny,kind:`blocked`},denied:!0};if(l.confirm&&!s)return{ok:!1,kind:`gated`,gate:{kind:`confirmation`,tool:n,...l.confirm.summary?{summary:l.confirm.summary}:{},...o},...l.mutate&&`input`in l.mutate?{input:l.mutate.input}:{}};let u=l.waitFor?{waitFor:l.waitFor}:{};return l.mutate&&`input`in l.mutate?{ok:!0,input:l.mutate.input,mutated:!0,...u}:{ok:!0,input:i,mutated:!1,...u}}async function Du(e,t,n,r,i){if(r.length===0)return;let a=e?.wait?await e.wait(t,r):{ok:!1,reason:`unknown`,callIds:[...r]};if(!a.ok)return{code:a.reason===`unknown`?`wait_unknown`:`wait_cycle`,kind:`request`,message:V(a.reason===`unknown`?`tool.wait_unknown`:`tool.wait_cycle`,{tool:n,calls:a.callIds.join(`, `)},i)}}async function*Ou(e){let{stages:t,toolName:n,callId:r,mutable:i,...a}=e;t.bodyEnded?.();let o=yield*ml({...a,stage:`post_tool`,step:t.step,history:t.history(),handlers:t.handlers,guardrails:t.profile.guardrails,injectAllowed:t.injectAllowed,injectWouldExceedMaxSteps:t.injectWouldExceedMaxSteps,mutable:i,host:t.host,signal:t.signal,span:t.span,callId:r,tool:n});return{...o.abort===void 0?{}:{abort:o.abort},...o.deny?{deny:o.deny}:{},...o.mutate&&`output`in o.mutate?{mutate:o.mutate}:{},...o.labelFailed?{labelFailed:!0}:{},inject:o.inject}}async function*ku(e){yield sl(`pre_tool`,{callId:e.callId,toolName:e.toolName,callNotStarted:!0,gate:e.gate});let t=e.gate.kind===`auth`?V(`sign_in.pending`,{service:e.gate.authChallenge.service},e.labels):void 0;return yield I(e.base,{phase:`gate`,gate:e.gate,...t?{readBack:t}:{}}),t}function Au(e,t){if(!t)return e;let n=new URL(e);return n.searchParams.set(t.name,t.value),n}function ju(e,t,n){let r=e.headerName??n.headerName,i=e.headerPrefix??n.headerPrefix;return{[r]:`${i}${t}`}}function Mu(e,t,n,r){return{kind:`auth`,tool:e,authChallenge:{slot:t.slot,authType:t.type,service:t.service,message:n,issuer:r?.issuer??t.preResolved?.issuer,resource:r?.resource??t.preResolved?.resource,requiredScopes:t.scopes}}}function Nu(e,t,n,r,i){return r===`gate`?{headers:{},unauthenticated:!0,gate:Mu(e,t,n,i)}:r===`fail`?{headers:{},unauthenticated:!0,failureMessage:n}:{headers:{},unauthenticated:!0,modelMessage:n}}function Pu(e,t){let n=t.type===`bearer`?t.token:t.key;if(e.queryParam!==void 0)return{headers:{},query:{name:e.queryParam,value:n}};if(t.type===`bearer`)return{headers:ju(e,n,{headerName:`Authorization`,headerPrefix:`Bearer `})};let r=t.headerName??e.headerName??`Authorization`,i=t.headerPrefix??e.headerPrefix??``;return{headers:{[r]:`${i}${n}`}}}function Fu(e,t){if(e.type!==`bearer`&&e.type!==`api_key`)return;let n=e.type===`bearer`?e.token:e.key;return{...Pu(t,e),secret:n}}var Iu=new Map;function Lu(e,t,n,r){let i=`${e.tokenEndpoint}\n${t}`,a=Iu.get(i);if(a)return a;let o=pu({refreshToken:t,tokenEndpoint:e.tokenEndpoint,clientId:e.clientId,resource:e.resource,scope:e.scope,issuer:e.issuer,...r===void 0?{}:{clientSecret:r},...n}).then(e=>e.credential);Iu.set(i,o);let s=()=>Iu.delete(i);return o.then(s,s),o}async function*Ru(e,t,n,r,i,a,o){let s=t.slot,c={issuer:n.issuer,resource:n.resource};if(typeof n.resource!=`string`||n.resource.length===0)return Nu(e,t,`OAuth credential for '${e}' (slot: '${s}') does not name the resource it was issued for.`,o,c);let l=n,u=n.expiresAt!==void 0&&n.expiresAt<=Date.now()+3e4;if(u&&n.refreshToken){try{l=await Lu(n,n.refreshToken,{network:Le(i),resolveHost:i.resolveHost},await r.clientSecret?.(n.clientId))}catch(n){return yield{...I(a,{phase:`progress`,data:{kind:`auth_token_refresh_failed`,slot:s}}),errorInternal:De(n)},Nu(e,t,`Failed to refresh OAuth token for '${e}' (slot: '${s}').`,o,c)}await r.set(s,l),yield I(a,{phase:`progress`,data:{kind:`auth_token_refreshed`,slot:s}})}else if(u)return Nu(e,t,`OAuth token expired for '${e}' (slot: '${s}') and no refresh token is available.`,o,c);return{headers:ju(t,l.accessToken,{headerName:`Authorization`,headerPrefix:`Bearer `}),secret:l.accessToken,audience:n.resource}}async function*zu(e,t,n,r){if(!t)return{headers:{}};let i=n.credentials,a=i?await i.get(t.slot):void 0,o=t.onUnauthenticated??`gate`;return!i||!a?Nu(e,t,`Authentication required for '${e}' (auth slot: '${t.slot}').`,o):Fu(a,t)||(a.type===`oauth2`?yield*Ru(e,t,a,i,n,r,o):{headers:{}})}function Bu(e,t){if(t===`.`||t===`..`)throw Error(`Path parameter "${e}" cannot be "${t}"`);return encodeURIComponent(t)}function Vu(e,t,n,r){Xr(e);let i=e,a=r?.pathParams??[];for(let e of a){let t=n[e];t!==void 0&&(i=i.replaceAll(`{${e}}`,Bu(e,String(t))))}let o=i.match(/\{([a-zA-Z0-9_-]+)\}/);if(o)throw Error(`Missing required path parameter "${o[1]}" for endpoint "${e}"`);let s=new URL(i),c=r?.queryParams??[];for(let e of c){let t=n[e];t!==void 0&&s.searchParams.set(e,String(t))}if(t===`GET`)return{url:s.toString()};if(r?.bodyParam)return{url:s.toString(),body:JSON.stringify(n[r.bodyParam])};let l={},u=new Set([...a,...c]);for(let[e,t]of Object.entries(n))u.has(e)||(l[e]=t);return{url:s.toString(),body:JSON.stringify(l)}}function Hu(e,t,n){if(e.includes(`application/json`)&&t.trim().length>0)try{return JSON.parse(t)}catch{return t}return t.trim().length===0&&n===204?null:t}function Uu(e,t){let n=e.safeParse(t);if(!n.success&&typeof t==`string`&&t.trim().length>0)try{let r=JSON.parse(t),i=e.safeParse(r);i.success&&(n=i)}catch{}return n}function Wu(e){return{finding:typeof e==`string`?e:JSON.stringify(e)}}function Gu(e,t){return t?.length?{...e,parts:t}:e}function X(e,t){return{kind:`failed`,failure:e,callNotStarted:t}}async function*Ku(e){let t=yield*Tu(e);return t.ok?t:t.kind===`aborted`?{kind:`aborted`,aborted:t.aborted}:t.kind===`gated`?{kind:`gated`,gate:t.gate}:{...X(t.failure,!0),...t.denied?{denied:!0}:{}}}function qu(e,t,n){let r=Ae(e,t,n);if(!r.ok)return{ok:!1,outcome:X(r.failure,!0)};let i=iu(e.name,e.permission,n.sessionPermissions,n.resume,ru(e,r.data));return i?{ok:!1,outcome:{kind:`gated`,gate:i}}:{ok:!0,input:r.data}}function Ju(e,t=!1){if(e.unauthenticated){if(e.gate)return{kind:`gated`,gate:e.gate};if(e.modelMessage)return{kind:`ok`,modelResult:{finding:e.modelMessage},outputRaw:{unauthenticated:!0,message:e.modelMessage}};if(e.failureMessage===void 0)throw Error(`An unauthenticated call carries a gate, a model message or a failure`);return X({code:`not_authorized`,kind:`auth`,message:e.failureMessage},!t)}}function Yu(e){return e.status===401||e.status===403?{status:e.status,challenge:e.headers.get(`www-authenticate`)}:void 0}var Xu=/^[\x21\x23-\x5B\x5D-\x7E]+$/;function Zu(e){let t=t=>e?.match(RegExp(`(?:^|[\\s,])${t}="([^"]*)"`,`i`))?.[1],n=(t(`scope`)??``).split(` `).filter(e=>Xu.test(e)),r=t(`error`);return r===void 0?{scopes:n}:{error:r,scopes:n}}function Qu(e){return e.status===401||Zu(e.challenge).error===`insufficient_scope`}function*$u(e,t,n,r,i){let a=e.auth;if(!a||!t||!n)return;let o=a.onUnauthenticated??`gate`;if(t.status===401){let t=`The credential for '${e.name}' (slot: '${a.slot}') was refused.`;return Ju(Nu(e.name,a,t,o),!0)}let s=Zu(t.challenge);if(s.error!==`insufficient_scope`)return;let c=a.scopes??[],l=s.scopes;if(l.length>0&&l.every(e=>c.includes(e))){let t=`'${e.name}' needs scopes its credential (slot: '${a.slot}') does not carry.`;return Ju(Nu(e.name,a,t,o),!0)}let u={kind:`auth_scope_refused`,slot:a.slot,requested:l,declared:c};return yield I(i,{phase:`progress`,data:u}),X({code:`out_of_scope`,kind:`auth`,message:V(`sign_in.out_of_scope`,{service:a.service},r.profile.labels)},!1)}async function*ed(e){let t=yield*zu(e.tool.name,e.tool.auth,e.ctx,e.base),n=Ju(t);if(n)return n;let r=yield*Ku({tool:e.tool,input:e.input,ctx:e.ctx,base:e.base,stages:e.stages});return`ok`in r?{ok:!0,input:r.input,authHeaders:t.headers??{},...t.query?{query:t.query}:{},...t.secret?{secret:t.secret}:{},...t.audience?{audience:t.audience}:{}}:r}var td={network:`network_error`,cancelled:`cancelled`,timeout:`timeout`};function*nd(e,t){if(W(e)===`blocked`){let n=nt();return t.record(n),X(yield*Xe(e,n),!1)}let n=W(e);return X({code:td[n]??`request_failed`,kind:n,message:De(e)},!1)}var rd=`[omitted - credential]`,id=2e3;async function*ad(e,t=1/0){let n=Number(e.headers.get(`content-length`));if(Number.isFinite(n)&&n>t)return await e.body?.cancel().catch(()=>{}),!1;if(!e.body)return yield await e.text(),!0;let r=e.body.getReader(),i=new TextDecoder,a=0;for(;;){let{done:e,value:n}=await r.read();if(e)break;if(a+=n.byteLength,a>t)return await r.cancel().catch(()=>{}),!1;let o=i.decode(n,{stream:!0});o&&(yield o)}let o=i.decode();return o&&(yield o),!0}async function od(e,t){let n=ad(e,t),r=``;for(;;){let e=await n.next();if(e.done)return e.value?r:void 0;r+=e.value}}async function*sd(e,t,n,r){let i=ad(e,r),a=n?n.length-1:0,o=``,s=``;for(;;){let e=await i.next();if(e.done)return e.value?(s&&(yield*t.show({kind:`draft`,text:s})),yield*t.end(),o):void 0;o+=e.value,s=n?ud(s+e.value,n):s+e.value;let r=s.length-a;r<=0||(yield*t.show({kind:`draft`,text:s.slice(0,r)}),s=s.slice(r))}}function cd(e){return e.length>id?`${e.slice(0,id)}…`:e}function ld(e,t){return{code:`response_too_large`,kind:`bad_response`,message:`Response from ${e} is larger than ${t} bytes`}}function ud(e,t){return e.replaceAll(t,rd)}function dd(e,t){return Wt(e,e=>ud(e,t))}function fd(e,t){return{...e,message:ud(e.message,t),...e.details===void 0?{}:{details:dd(e.details,t)}}}function pd(e,t){if(!t)return e;if(e.kind===`ok`){let n=dd(e.outputRaw,t);return{kind:`ok`,outputRaw:n,modelResult:Gu(Wu(n),e.modelResult.parts)}}return e.kind===`failed`?{...e,failure:fd(e.failure,t)}:e}function md(e,t){if(e&&!mu(e,t))return`The OAuth token for "${e}" cannot be sent to "${t.origin}${t.pathname}"`}async function*hd(e,t,n){let r=md(e.audience,t);return r?X({code:`credential_audience_mismatch`,kind:`config`,message:r},!0):pd(yield*n(Au(t,e.query)),e.secret)}async function*gd(e,t,n,r,i,a,o){let s=qu(e,t,n);if(!s.ok)return s.outcome;let c=s.input,l=yield*ed({tool:e,input:c,ctx:n,base:r,stages:i});if(!(`ok`in l))return l;c=l.input;let u;try{u=Vu(e.endpoint,e.method,c,e.mapping)}catch(e){return X({code:`invalid_input`,kind:`bad_response`,message:De(e)},!0)}let d=yield*ze(u.url,n,i?.span);if(!d.ok)return X(d.failure,!0);let f=yield*Me(e,c,n,r,a);return yield*hd(l,d.url,t=>yd(e,t,u.body,l,n,r,i?.span,o,f))}function _d(e){if(!e.ok)return!1;let t=e.headers.get(`content-type`)??``;return t===``||t.startsWith(`text/`)||/[/+]json\b/.test(t)}async function*vd(e,t,n,r){return!t||!_d(e)?await od(e,r):yield*sd(e,t,n,r)}async function*yd(e,t,n,{authHeaders:r,secret:i},a,o,s,c,l){let u=We(s),d={Accept:`application/json`};e.method!==`GET`&&(d[`Content-Type`]=`application/json`);let f;try{let s=e.limit?await bu(e,e.limit,a.signal):void 0;if(s&&`full`in s)return X(Pd(e,s),!1);f=e.timeoutMs===void 0?void 0:AbortSignal.timeout(e.timeoutMs);let p=f&&a.signal?AbortSignal.any([a.signal,f]):f??a.signal,m=await xu(s,we(t.href,{method:e.method,headers:d,body:n,signal:p},{policy:Le(a),followRedirects:!0,...e.access===`read-only`?{fetchFn:to(fetch)}:{},originBoundHeaders:{...e.headers,...r},resolveHost:a.resolveHost,onCheck:u.onCheck,beforeSend:async()=>{await l.claim()}})),h=yield*vd(m,c,i,e.maxResponseBytes);if(h===void 0)return X(ld(t.hostname,e.maxResponseBytes),!1);if(!m.ok)return(yield*$u(e,Yu(m),i!==void 0,a,o))||X({code:`http_${m.status}`,kind:Fd(m.status),message:`HTTP ${m.status} from ${t.hostname}: ${cd(h)}`},!1);let g=Hu(m.headers.get(`content-type`)??``,h,m.status),_=Uu(e.output,g);return _.success?{kind:`ok`,modelResult:Wu(_.data),outputRaw:_.data}:X({code:`invalid_output`,kind:`bad_response`,message:`HTTP response did not match tool output schema`,details:_.error.flatten()},!1)}catch(n){return l.rethrowClaimFailure(),e.timeoutMs!==void 0&&f?.aborted&&!a.signal?.aborted?X(bd(t.hostname,e.timeoutMs),!1):yield*nd(n,u)}finally{u.record()}}function bd(e,t){return{code:`timeout`,kind:`timeout`,message:`${e} did not answer within ${t} ms`}}var xd=[`2026-07-28`,`2025-11-25`,`2025-06-18`,`2025-03-26`];function Sd(e){return{"io.modelcontextprotocol/protocolVersion":e,"io.modelcontextprotocol/clientCapabilities":{}}}function Cd(e){let t=e.trim();if(t.startsWith(`{`))return JSON.parse(t);let n=[];for(let t of e.split(`
|