@theoremjs/studio 0.3.5-next.943.g77aa4ba → 0.3.5-next.945.g127cfdd
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/{BottomSheet-QaKqG4jF.js → BottomSheet-CGCeV0j1.js} +1 -1
- package/page/assets/{ConsoleFrame-cb9_ArXw.js → ConsoleFrame-D2GshrNG.js} +1 -1
- package/page/assets/{ContextMenu-BnbiZucy.js → ContextMenu-DBz-JG4k.js} +2 -2
- package/page/assets/{DateInput-stobICzZ.js → DateInput-D4P1qXs4.js} +1 -1
- package/page/assets/{DropdownMenu-BzGltiAm.js → DropdownMenu-L_jMBqTm.js} +2 -2
- package/page/assets/{Link-BtTmEbdB.js → Link-8shHw31C.js} +1 -1
- package/page/assets/{MenuBottomSheet-B9NN63O3.js → MenuBottomSheet-CpgKx3Gn.js} +1 -1
- package/page/assets/{PowerSearchBottomSheet-BOV5GdgP.js → PowerSearchBottomSheet-DpeYUQEs.js} +1 -1
- package/page/assets/{RankedBars-1VZsRbhd.js → RankedBars-BiLmrqKa.js} +1 -1
- package/page/assets/{SchemaFields-Dyitt-M1.js → SchemaFields-CFmjkJ6M.js} +1 -1
- package/page/assets/{ShapedData-BBnTz3mS.js → ShapedData-DwKqBicC.js} +1 -1
- package/page/assets/{TokenizerBottomSheet-BoLsFTK4.js → TokenizerBottomSheet-CqNod-xJ.js} +1 -1
- package/page/assets/{ToolResultCharts-CguMnOa6.js → ToolResultCharts-B8nqKU-p.js} +1 -1
- package/page/assets/{Toolbar-CgDahCAm.js → Toolbar-JItJGIdz.js} +1 -1
- package/page/assets/{TraceInspector-DQDlkN8V.js → TraceInspector-CR2p0Rsk.js} +2 -2
- package/page/assets/{TraceOverview-DJ83CvfS.js → TraceOverview-4URknKAx.js} +1 -1
- package/page/assets/{_virtual_studio-type-sources-G_oCq5-0.js → _virtual_studio-type-sources-D6OCf7oS.js} +6 -1
- package/page/assets/{browser-connection-kb6TLu6Q.js → browser-connection-WnnSpy0l.js} +1 -1
- package/page/assets/{browser-engine-D8Rivwgl.js → browser-engine-B3DypGiU.js} +1 -1
- package/page/assets/{browser-transport-CMhiaeC7.js → browser-transport-B4Kwu8zD.js} +2 -2
- package/page/assets/{compile-DCNCvXa1.js → compile-8yHA7cmn.js} +1 -1
- package/page/assets/{export-agent-ALLh0kKl.js → export-agent-DnBVyBSA.js} +1 -1
- package/page/assets/{getRadiusAndStrokeWidthFromDot-BvXM31yx.js → getRadiusAndStrokeWidthFromDot-BWoQYgPp.js} +1 -1
- package/page/assets/{guardrail-health-D7-D9qD4.js → guardrail-health-Bx0iZLTr.js} +1 -1
- package/page/assets/{guardrail-tester-BuLSv10M.js → guardrail-tester-BQJ57eVF.js} +1 -1
- package/page/assets/{index-Betmdih_.js → index-yC5X4xkW.js} +9 -9
- package/page/assets/{json-code-DHq_KoDO.js → json-code-DvTbV1HF.js} +1 -1
- package/page/assets/{live-messages-BHvZ8weQ.js → live-messages-BrQhgNiV.js} +1 -1
- package/page/assets/{prompt-row-C9JPS5tx.js → prompt-row-D6KsHzGX.js} +1 -1
- package/page/assets/{reader-CXFUEtiT.js → reader--ohfEAKk.js} +1 -1
- package/page/assets/{registry-DYcSwTjI.js → registry-DTX5GVdX.js} +1 -1
- package/page/assets/{schema-TcexWxQ5.js → schema-DXPRQZid.js} +1 -1
- package/page/assets/{studio-code-pane-CDOgmTL7.js → studio-code-pane-DqwItrQC.js} +3 -3
- package/page/assets/{studio-console-BRjSBukh.js → studio-console-C3fb3uvx.js} +1 -1
- package/page/assets/{studio-decision-DppsKqW1.js → studio-decision-DU0xJ_yF.js} +1 -1
- package/page/assets/{studio-embedding-B8u6gSzU.js → studio-embedding-BWRXx7j3.js} +1 -1
- package/page/assets/{studio-host-console-tH9YxROO.js → studio-host-console-BcxYCUod.js} +2 -2
- package/page/assets/{studio-live-BDv02GUw.js → studio-live-V8VdBf-b.js} +1 -1
- package/page/assets/{studio-map-DpnUD0nn.js → studio-map-DUsPuSdw.js} +1 -1
- package/page/assets/{studio-media-BpPswiCJ.js → studio-media-DrQcx2gs.js} +1 -1
- package/page/assets/{studio-trace-replay-Ub7bAl25.js → studio-trace-replay-CiPB4pLJ.js} +1 -1
- package/page/assets/{studio-type-checker-DoIvUMKB.js → studio-type-checker-DE8zvwkv.js} +1 -1
- package/page/assets/{turn-client-DbELNcFw.js → turn-client-Cef0JadZ.js} +1 -1
- package/page/assets/{use-one-call-WBouz5ih.js → use-one-call-BzjYM1tg.js} +1 -1
- package/page/assets/{useDismissSearchOnTouchDrag-CqBTrJGJ.js → useDismissSearchOnTouchDrag-CJF2iaqF.js} +1 -1
- package/page/index.html +13 -13
- package/ui/lib/studio-page.d.ts +5 -0
- package/ui/lib/studio-page.js +17 -11
- package/ui/profile-editor.js +11 -11
|
@@ -1 +1 @@
|
|
|
1
|
-
import{E as e,d as t,x as n}from"./schemas-D7cgkv3L.js";import{H as r}from"./tool-schema-Cw0KPTnQ.js";import{$t as i,Ba as a,Cn as o,Da as s,Fi as c,Oa as l,Oi as u,Pi as ee,Qt as te,Sn as d,Ti as ne,Tn as f,Wa as re,Xa as ie,Y as ae,Zi as oe,ao as se,ba as ce,bn as le,ea as ue,fa as p,lo as m,na as de,nn as fe,ta as pe,uo as me,wi as h,xn as g,zi as _,zt as he}from"./shaped-data-gYhn8vze.js";import{c as v}from"./host-patterns-F-KZIzkF.js";import{D as ge,S as _e,g as y,k as ve,v as ye,w as be}from"./schema-TcexWxQ5.js";import{a as xe,n as Se}from"./live-ingress-OuSlQ6q7.js";var Ce=2,we=4,Te=3,Ee=/(^|,)(\s*)("?)(?:([=@])|([+-])(?![0-9."]))/gm,De=/^[A-Za-z0-9+/]*={0,2}$/,Oe=new Set([`text/csv`,`text/plain`,`text/markdown`]);function b(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 ke(e,t){if(t.limitsByMime){let n=f(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 x(e){return`uri`in e}function Ae(e){if(e.type===`speech`)throw new v(`request`,`Profile ${e.id} (speech) does not accept media input`);if(e.type===`live`)throw new v(`request`,`Profile ${e.id} (live) does not accept turn attachment input`);if(e.type===`host`||e.type===`decision`||e.type===`embedding`)throw new v(`request`,`Profile ${e.id} (${e.type}) does not accept turn input`);let t=b(e.inputs??{});if(!t)throw new v(`config`,`Profile ${e.id} must set maxFiles, maxBytes, and maxTurnBytes`);return t}function je(e){let t=0;return e.endsWith(`==`)?t=Ce:e.endsWith(`=`)&&(t=1),Math.floor(e.length*Te/we)-t}function Me(e){try{return new TextDecoder(`utf-8`,{fatal:!0}).decode(e)}catch{return new TextDecoder(`latin1`).decode(e)}}function Ne(e){return e.replace(Ee,(e,...t)=>{let[n,r,i,a,o]=t;return`${n}${r}${i}'${a??``}${o??``}`})}function Pe(e,t,n){let r=Me(t);return e===`text/csv`&&(r=Ne(r)),new TextEncoder().encode(n.read(r))}function S(e,t){return t?{...e,fileName:t}:e}function C(e,t,n){return t.filter(t=>!g(e,t.mimeType)).map(e=>S({code:`mime_not_allowed`,params:{mimeType:e.mimeType,channel:n}},e.name))}function Fe(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=ke(i.mimeType,t);i.sizeBytes>e&&n.push(S({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 Ie(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(...C(e.attachments,t,`attachment`)),e.voice&&r.push(...C(e.voice,n,`voice`)),e.limits?[...r,...Fe([...t,...n],e.limits)]:[...r,{code:`limits_unconfigured`}])}var Le={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 Re(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:Le[e.code],params:t}}function ze(e,t){let n=Re(e);return m(n.key,n.params,t)}function w(e){return new v(`input`,`attachments refused: ${e.map(e=>e.code).join(`, `)}`,{copy:e.map(Re)})}function T(e){if(!De.test(e))throw new v(`request`,`attachment data must be base64`);return je(e)}function E(e){let t={mimeType:e.mimeType,name:e.name};return x(e)||(t.sizeBytes=T(e.data)),t}function Be(e,t,n){if(!Ve(t,n))return;let r=Ae(e),i=Ie({attachments:d(e,`attachments`),voice:d(e,`voice`),limits:r},(t??[]).map(E),(n??[]).map(E));if(i.length>0)throw w(i)}function D(e,t){if(x(e))return e;let{mimeType:n,data:r}=e;if(!Oe.has(f(n)))return e;let i=Pe(n,s(r),t);return{...e,data:l(i)}}function Ve(e,t){return(e?.length??0)>0||(t?.length??0)>0}function He(e,t,n,r){return Be(e,t,n),{attachments:t?.length?t.map(e=>D(e,r.attachment)):t,voice:n?.length?n.map(e=>D(e,r.voice)):n}}function O(e){let t=Object.keys(e);return t.length===1?t[0]:void 0}function k(e){return e==null}function A(e){return k(e)||typeof e!=`object`||Array.isArray(e)?null:e}function j(e){let t=A(e);return!t||t.type!==void 0&&t.type!==`object`?null:t}function M(e){let t=e.required;return Array.isArray(t)?t.filter(e=>typeof e==`string`):[]}function N(e){let t=e.properties;return A(t)??{}}function Ue(e,t){return e?`${e}.${t}`:t}function P(e,t){t.push({path:e,error:`required field '${e}' is missing`})}async function We(e,t,n,r,i,a){if(!n)return;let o;try{o=await n(t,r)}catch(e){a.push(e),o={isValid:!1}}o.isValid||i.push({path:e,error:o.error||o.finding||`Validation failed for '${e}'`})}async function Ge(e){let{path:t,propSchema:n,child:r,isRequired:i,fields:a,options:o,failures:s,crashes:c}=e;if(k(r)){i&&P(t,s);return}await We(t,r,a?.[t],o,s,c);let l=j(n),u=l?A(r):null;l&&u&&await F(l,u,t,a,o,s,c)}async function F(e,t,n,r,i,a,o){let s=N(e),c=new Set(M(e)),l=new Set([...Object.keys(s),...c]),u=A(t);for(let e of l)await Ge({path:Ue(n,e),propSchema:s[e],child:u?.[e],isRequired:c.has(e),fields:r,options:i,failures:a,crashes:o})}async function Ke(e,t,n,r,i=[]){let a=j(e);if(!a)throw new v(`config`,`structured validation requires a JSON Schema object root`);let o=[];if(!A(t)){for(let e of M(a))P(e,o);return o}return await F(a,t,``,n,r,o,i),o}function qe(e,t){let n=e;for(let e of t.split(`.`)){let t=j(n);if(!t)return!1;let r=N(t);if(!Object.hasOwn(r,e)&&!M(t).includes(e))return!1;n=r[e]}return!0}function Je(e){return e.map(e=>e.error).join(`; `)}function I(e,t){let n=e;for(let e of t.split(`.`))n=A(n)?.[e];return n}function L(e,t,n){let[r,...i]=t.split(`.`),a=A(e)??{};return r===void 0?e:{...a,[r]:i.length?L(a[r],i.join(`.`),n):n}}async function Ye(e,t,n,r=[]){let i=[];for(let[a,o]of Object.entries(t??{})){let t=I(e,a);if(Array.isArray(t))for(let[e,s]of t.entries()){let t;try{t=await o.check(s,n)}catch(e){r.push(e),t={isValid:!1}}t.isValid||i.push({path:a,index:e,item:s,reason:t.error||t.finding||`Validation failed for '${a}'`,onFail:o.onFail})}}return i}function R(e,t){let n=e;for(let e of t.split(`.`)){let t=j(n);if(!t)return;n=N(t)[e]}let r=A(n);if(r?.type===`array`)return A(r.items)??void 0}function Xe(e,t,n,r){if(!n.provider?.trim()||!n.apiId?.trim())throw new v(`config`,m(`provider.binding_identity`))}function Ze(e){B(e.id,e.models),Y(e.id,e.observability),zt(e.id,e.inputs);for(let[t,n]of Object.entries(e.models))H(e.id,t,n);return{type:`embedding`,id:e.id,identity:{handle:e.identity.handle},models:e.models,defaultModel:V(e.id,e),allowModelSelect:e.allowModelSelect,inputs:e.inputs,guardrails:e.guardrails,observability:e.observability,labels:e.labels}}function Qe(e){B(e.id,e.models),q(e.id,e.guardrails),Y(e.id,e.observability);for(let[t,n]of Object.entries(e.models))H(e.id,t,n);if(`text`in e.inputs&&e.inputs.text!==!1)throw new v(`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},...W(e),providerContinuation:void 0,maxSteps:void 0,inputs:{...e.inputs,text:!1},guardrails:e.guardrails,observability:e.observability,labels:e.labels}}function z(e,t,n,r){let i=r.safeParse(n);if(!i.success)throw new v(`config`,`Profile ${e} model '${t}': ${i.error.issues.map(e=>`${ae(e.path)}: ${e.message}`).join(`; `)}`)}function $e(e,t,n){if(z(e,t,n,i),Xe(e,t,n,`decision`),`retry`in n)throw new v(`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 v(`config`,`Profile ${e} model '${t}' timeoutMs must be > 0`)}function et(e){let t=e.models?O(e.models):void 0;if(!t)throw new v(`config`,`Profile ${e.id}: type 'decision' must declare exactly one model`);$e(e.id,t,e.models[t])}function tt(e){if(e.inputs.state!==`json`)throw new v(`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 v(`config`,`Profile ${e.id}: decision inputs.maxStateBytes must be a positive integer`);if(!e.decision.contract.trim())throw new v(`config`,`Profile ${e.id}: decision.contract must be non-empty`)}function nt(e){return et(e),tt(e),Y(e.id,e.observability),{...e,identity:{handle:e.identity.handle}}}function rt(e){return e===void 0?{}:{parallel:e}}function it(e){return at(e.id,e.tools),Y(e.id,e.observability),{type:`host`,id:e.id,tools:{allow:e.tools.allow,...rt(e.tools.parallel)},guardrails:e.guardrails,observability:e.observability,labels:e.labels}}function at(e,t){if(!Array.isArray(t.allow))throw new v(`config`,`Profile ${e}: type 'host' must set tools.allow`)}function B(e,t){if(Object.keys(t).length===0)throw new v(`config`,`Profile ${e} must declare at least one model`)}function V(e,t){let n=t.defaultModel??O(t.models);if(!n)throw new v(`config`,`Profile ${e} must set defaultModel when more than one model is declared`);if(!t.models[n])throw new v(`config`,`Profile ${e} defaultModel '${n}' is not declared`);return n}function H(e,t,n){U(e,t,n),z(e,t,n,fe),U(e,t,n)}function U(e,t,n){let r=n.efforts;if(!r||Object.keys(r).length===0){if(n.defaultEffort||n.allowEffortSelect)throw new v(`config`,`Profile ${e} model '${t}': defaultEffort and allowEffortSelect require efforts`);return}for(let[n,i]of Object.entries(r))if(!_.includes(i))throw new v(`config`,`Profile ${e} model '${t}' effort '${n}': '${i}' is not a thinking level (${_.join(`, `)})`);let i=Object.keys(r),a=n.defaultEffort??(i.length===1?i[0]:void 0);if(!a)throw new v(`config`,`Profile ${e} model '${t}' must set defaultEffort when more than one effort is declared`);if(!r[a])throw new v(`config`,`Profile ${e} model '${t}' defaultEffort '${a}' is not declared`);if(n.allowEffortSelect&&i.length<2)throw new v(`config`,`Profile ${e} model '${t}' allowEffortSelect requires at least two efforts`)}function W(e){return{providerContinuation:e.providerContinuation?ce.parse(e.providerContinuation):{},models:e.models,defaultModel:V(e.id,e),allowModelSelect:e.allowModelSelect,maxSteps:e.maxSteps}}function G(e,t,n){if(n?.length){for(let r of n)if(!he(r))throw new v(`config`,`Profile ${e}: turnBehaviour.resumption.${t} may only include ContinueStopKind (${ne.join(` | `)}); got '${r}'`)}}function ot(e,t){t&&(G(e,`allowContinue`,t.allowContinue),G(e,`autoContinue`,t.autoContinue))}function K(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function st(e,t){let n=[e];for(let e of t)n=n.flatMap(t=>K(t)?e===`*`?Object.values(t):[t[e]]:[]);return n}var ct=Object.entries(ee).filter(([,e])=>e.required===!0).map(([e,t])=>[e,t.profileTypes]).sort(([e],[t])=>e.split(`.`).length-t.split(`.`).length);function lt(e){if(!K(e))throw new v(`config`,`Profile definition must be an object`);let t=typeof e.id==`string`&&e.id.trim()?e.id:void 0;if(!t)throw new v(`config`,`Profile definition must set id`);if(!c.find(t=>t===e.type))throw new v(`config`,`Profile ${t}: type must be one of ${c.join(`, `)}`)}function ut(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 v(`config`,`Profile ${e.id.slice(0,64)}: ${t} must be at most ${i} characters`)}function dt(e){let{id:t,type:n}=e,r=e;for(let[e,i]of ct){if(i&&!i.includes(n))continue;let a=pe(e),o=st(r,a.slice(0,-1)),s=a[a.length-1];if(o.some(e=>{if(!K(e))return!1;let t=e[s];return t==null||t===``}))throw new v(`config`,`Profile ${t}: type '${n}' must set ${a.join(`.`)}`)}}function ft(e){let{id:t,type:n}=e;if(n!==`live`&&de(`inputs`).includes(n)&&e.inputs==null)throw new v(`config`,`Profile ${t}: type '${n}' must set inputs`)}function pt(e){let[t]=ue(e);if(!t)return;let{offValue:n,reason:r}=t.scope,i=n===void 0?``:` (other than ${n})`;throw new v(`config`,`Profile ${e.id}: type '${e.type}' must not set ${t.path}${i} — ${r}`)}function mt(e,t){let n=t.turnBehaviour;ot(e,n?.resumption)}function ht(e,t){let n=t=>new v(`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 q(e,t){let n=t=>new v(`config`,`Profile ${e}: ${t}`),r=Object.keys(t??{}).find(e=>!J.includes(e));if(r!==void 0)throw n(`guardrails.${r} is not a setting; it takes ${J.join(`, `)}`);_t(t?.blockedReply,n)}var J=[`quota`,`detect`,`blockedReply`,`network`,`taint`],gt=[`onBlock`,`maxRetries`];function _t(e,t){if(e===void 0)return;let n=Object.keys(e).find(e=>!gt.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&&!a.includes(r))throw t(`guardrails.blockedReply.onBlock must be one of ${a.join(`, `)}`);if(i!==void 0&&(!Number.isInteger(i)||i<0))throw t(`guardrails.blockedReply.maxRetries must be a non-negative integer`)}function vt(e){let t=e.guardrails?.detect,n=e.type===`host`?p(`guardrails.detect`,t,re):p(`guardrails.detect`,t);if(n!==void 0)throw new v(`config`,`Profile ${e.id}: ${n}`)}function Y(e,t){try{let n=xe(t);if(!Number.isFinite(n.retainForDays))throw new v(`config`,`Profile ${e}: observability.retainForDays must be a finite number`);if(n.rotateAfterMiB<=0||!Number.isFinite(n.rotateAfterMiB))throw new v(`config`,`Profile ${e}: observability.rotateAfterMiB must be a positive number`)}catch(t){if(t instanceof v&&t.message.startsWith(`Profile `))throw t;let n=t instanceof Error?t.message:String(t);throw new v(ie(t),`Profile ${e}: ${n}`,{cause:t})}}function yt(e){if(e.type===`host`||e.type===`decision`||e.type===`speech`||e.type===`transcription`||e.type===`embedding`)return;let{options:t,system:n}=e.identity,r=n??``;_e(r,`Profile ${e.id} identity.system`);let i=be(r,t,e.inputs?.options);if(i)throw new v(`config`,`Profile ${e.id} identity.system: ${i}`)}function X(e){let t=bt(e),[n]=oe(e);if(n)throw new v(`config`,`Profile ${e.id}: ${n.path} ${n.message}`);return t}function bt(e){lt(e);for(let t of[`key`,`fallbackKey`,`protocol`,`provider`])if(t in e)throw new v(`config`,m(`provider.profile_configuration`,{profile:e.id,field:t}));pt(e),ft(e),dt(e),ut(e),e.labels&&me(e.labels,`Profile ${e.id}`);for(let t of se)if(e.labels?.[t]!==void 0)throw new v(`config`,`Profile ${e.id}: labels '${t}' is a host line, which a profile cannot change; set it with overrideLabels`);if(yt(e),vt(e),e.type===`host`)return it(e);if(e.type===`decision`)return nt(e);if(e.type===`embedding`)return Ze(e);if(e.type===`transcription`)return Qe(e);B(e.id,e.models),mt(e.id,e),q(e.id,e.guardrails),e.type===`text`&&ht(e.id,e.outputs?.validation),Y(e.id,e.observability);for(let[t,n]of Object.entries(e.models))H(e.id,t,n);let t=e.type===`speech`?{handle:e.identity.handle}:{handle:e.identity.handle,options:e.identity.options,system:e.identity.system},n=e.guardrails,r=e.observability,i=e.labels,a=W(e),o;switch(e.type){case`text`:o={type:`text`,id:e.id,identity:t,...a,tools:e.tools,inputs: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:e.inputs,outputs:e.outputs,turnBehaviour:e.turnBehaviour,guardrails:n,observability:r,labels:i},Et(o.id,o.inputs.attachments?.accept),Tt(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,tools:{allow:e.tools.allow,...rt(e.tools.parallel)},turnBehaviour:e.turnBehaviour,guardrails:n,observability:r,labels:i},Se(o),Ot(o.id,o.live.contextCompression),Dt(o);break;default:throw new v(`config`,`Unknown profile type '${String(e)}'`)}return Ct(o),xt(o),St(o),o}function xt(e){let{maxSteps:t}=e;if(!(t===void 0||Number.isInteger(t)&&t>0))throw new v(`config`,`Profile ${e.id}: maxSteps must be a whole number of 1 or more; leave it out for the default of 20`)}function St(e){if(e.type===`text`&&e.turnBehaviour?.atStepLimit===`answer`&&e.maxSteps===1)throw new v(`config`,`Profile ${e.id}: turnBehaviour.atStepLimit 'answer' with maxSteps 1 leaves no step that can call a tool`)}function Ct(e){if(e.type===`live`)return;let t=e.outputs?.structured;if(!t||typeof t==`string`)return;let n=ve(e,t.by);if(!n)throw new v(`config`,`Profile ${e.id}: outputs.structured.by '${t.by}' is not one of the profile's options`);let r=ge(n),i=Object.keys(t.map).filter(e=>!r.includes(e));if(i.length)throw new v(`config`,`Profile ${e.id}: outputs.structured.map maps ${i.join(`, `)}, not a choice of option '${t.by}'`)}var wt={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 Tt(e,t){for(let[n,{ok:r,rule:i}]of Object.entries(wt)){let a=t[n];if(a!==void 0&&!r(a))throw new v(`config`,`Profile ${e}: image.${n} must be ${i}`)}t.references?.forEach((t,n)=>{let r=`Profile ${e}: image.references[${n}]`;if(le(t.mimeType)!==`image`)throw new v(`config`,`${r} must be an image, not '${t.mimeType}'`);if(!(x(t)?t.uri:t.data))throw new v(`config`,`${r} needs its bytes or its uri`)})}function Et(e,t){let n=t?.filter(e=>!g(u,e));if(n?.length)throw new v(`config`,`Profile ${e}: an image profile's attachments take images, video, and PDF only, not ${n.join(`, `)}`)}function Dt(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 v(`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 v(`config`,`${i}.resumed.prompt must be a prompt`);let{afterMs:a}=n;if(a!==void 0&&!(Number.isFinite(a)&&a>=0))throw new v(`config`,`${i}.resumed.afterMs must be 0 or more milliseconds`);if(!r)throw new v(`config`,`${i}.resumed needs live.sessionResumption: without it no call resumes`)}function Ot(e,t){if(!t)return;let n=`Profile ${e} live.contextCompression`,r=t.triggerTokens,i=t.slidingWindow.targetTokens;if(Z(`${n}.triggerTokens`,r),Z(`${n}.slidingWindow.targetTokens`,i),r!==void 0&&i!==void 0&&i>=r)throw new v(`config`,`${n}: slidingWindow.targetTokens must be below triggerTokens`)}function Z(e,t){if(!(t===void 0||Number.isInteger(t)&&t>0))throw new v(`config`,`${e} must be a whole number above 0`)}function kt(e,t,n,r){let i=`Profile ${t.id} model ${n} compaction`;if(At(i,r),jt(i,r),r.profile===void 0){if(t.type!==`text`||t.inputs.text===!1)throw new v(`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 v(`config`,`${i}: compaction profile '${r.profile}' must be registered before '${t.id}'`);if(a.type!==`text`||a.inputs.text===!1)throw new v(`config`,`${i}: compaction profile '${r.profile}' must be a text profile that takes text`)}function At(e,t){if(t.maxTokens<=0)throw new v(`config`,`${e}: maxTokens must be > 0`);if(t.compactAt<=0||t.compactAt>=1)throw new v(`config`,`${e}: compactAt must be in (0, 1)`)}function jt(e,t){if(t.previousExchanges<0)throw new v(`config`,`${e}: previousExchanges must be >= 0`);if(t.previousExchanges<1&&t.previousExchanges>=t.compactAt)throw new v(`config`,`${e}: previousExchanges as fraction (${t.previousExchanges}) must be < compactAt (${t.compactAt})`);if(t.previousExchanges>1&&!Number.isInteger(t.previousExchanges))throw new v(`config`,`${e}: previousExchanges >= 1 must be an integer`)}function Mt(e,t){for(let n of y(t))if(e.get(n)?.type===`builtin`)throw new v(`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 Nt(e,t){let n=ye(t)?.t2Loader;if(n){if(!y(t).includes(n))throw new v(`config`,`Profile ${t.id} tools.t2Loader '${n}' must also be listed in tools.allow`);if(e.get(n)?.type!==`function`)throw new v(`config`,`Profile ${t.id} tools.t2Loader '${n}' must be a registered type: 'function' tool`)}}function*Pt(e){for(let[t,n]of Object.entries(e.models))for(let e of n.builtInTools??[])yield{modelId:t,id:e}}function Ft(e,t){for(let{modelId:n,id:r}of Pt(t))if(e.get(r)?.type!==`builtin`)throw new v(`config`,`Profile ${t.id} model '${n}' lists '${r}' in builtInTools — not a registered builtin`)}function Q(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 It(e,t){return t?.type===`text`?Q(t).flatMap(t=>{let n=e.find(t);return n?[n.jsonSchema]:[]}):[]}function Lt(e,t){let n=Q(t).map(n=>{let r=e.find(n);if(!r)throw new v(`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 v(`config`,`Profile ${t.id}: outputs.validation checks a structured reply, so it needs outputs.structured`);let o=a.filter(e=>!n.some(t=>R(t.jsonSchema,e)));if(o.length)throw new v(`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=>qe(t.jsonSchema,e)));if(s.length)throw new v(`config`,`Profile ${t.id}: outputs.validation.fields has ${s.join(`, `)}, which no structured schema reaches through object properties`)}function Rt(e){let t=o(e)?.context;if(!t)return;let n=h;if(t.from.length===0||t.from.some(e=>!n.includes(e)))throw new v(`config`,`Profile ${e.id}: inputs.context.from must list ${h.join(` or `)}`);if(!(Number.isInteger(t.maxChars)&&t.maxChars>0))throw new v(`config`,`Profile ${e.id}: inputs.context.maxChars must be a positive integer`)}function zt(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 v(`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 v(`config`,`Profile ${e}: inputs.${t} must be a positive integer`)}function Bt(e,t,n){let r=new Map,i=i=>{let a=X(i),s=n&&a.type!==`host`?{...a,models:Object.fromEntries(Object.entries(a.models).map(([e,t])=>[e,te(n.require(t.provider,t.apiId),t,a.type)]))}:a;if(Mt(e,s),Nt(e,s),s.type!==`host`&&s.type!==`decision`&&s.type!==`embedding`){Ft(e,s),zt(s.id,o(s)),Rt(s),Lt(t,s);for(let[e,t]of Object.entries(s.models))t.compaction&&kt(r,s,e,t.compaction)}r.set(s.id,s)};return{register:i,registerMany(e){for(let t of e)i(t)},get(e){let t=r.get(e);if(!t)throw new v(`config`,`Unknown profile '${e}'`);return t},find:e=>r.get(e),has:e=>r.has(e),list:()=>[...r.values()],clear:()=>r.clear()}}function Vt(e){let t=e?.trim()??``;if(t.startsWith(`AIza`))return`gemini`;if(t.startsWith(`sk-or-`))return`openrouter`}function Ht(e){let t;try{t=new URL(e.baseUrl)}catch{throw new v(`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 v(`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 v(`blocked`,`Local requests must stay on the configured origin.`))}}var Ut=n({data:t(n({id:e().min(1)}))});async function Wt(e,t){let n=Ht(e);if(!n?.fetch)throw new v(`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 v(`network`,`Local model list returned HTTP ${r.status}.`);let i=Ut.safeParse(await r.json());if(!i.success)throw new v(`request`,`The endpoint returned an invalid model list.`);return[...new Set(i.data.data.map(e=>e.id))]}var Gt=`https://openrouter.ai/api/v1/models`,Kt=`https://openrouter.ai/api/v1/embeddings/models`,qt=[{id:`gemini-embedding-2-preview`,label:`Gemini Embeddings 2 (preview)`},{id:`gemini-embedding-001`,label:`Gemini Embedding 001`}],Jt=[{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)`}],Yt={text:`text`,image:`image`,speech:`speech`,transcription:`transcription`,live:void 0,embedding:void 0},Xt=n({data:t(n({id:e().min(1),name:e().optional(),architecture:n({output_modalities:t(e()).optional()}).optional()}))}),Zt=n({data:t(n({id:e().min(1),name:e().optional()}))}),Qt=n({models:t(n({name:e().min(1),displayName:e().optional(),supportedGenerationMethods:t(e()).optional()})).optional(),nextPageToken:e().optional()}),$t=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 v(`auth`,`${e} refused the key.`);if(!r.ok)throw new v(`network`,`${e} model list returned HTTP ${r.status}.`);return await r.json()}async function en(e,t,n,r){let i=n?.trim();if(t===`embedding`&&!i)return[...e===`openrouter`?Jt:qt];if(e===`openrouter`)return await tn(t,i,r);if(!i)throw new v(`auth`,`Choose a key to list Gemini models.`);return await rn(t,i,r)}async function tn(e,t,n){let r={signal:n,headers:{Accept:`application/json`,...t?{Authorization:[`Bearer`,t].join(` `)}:{}}};if(e===`embedding`){let e=Zt.safeParse(await $(`OpenRouter`,Kt,r));if(!e.success)throw new v(`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=Yt[e];if(!i)return[];let a=Xt.safeParse(await $(`OpenRouter`,`${Gt}?output_modalities=${i}`,r));if(!a.success)throw new v(`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 nn={live:`bidiGenerateContent`,embedding:`embedContent`};async function rn(e,t,n){let i=nn[e]??`generateContent`,a=[],o;for(let e=0;e<$t;e++){let e=new URL(r);e.searchParams.set(`pageSize`,`1000`),o&&e.searchParams.set(`pageToken`,o);let s=Qt.safeParse(await $(`Google`,e.href,{signal:n,headers:{Accept:`application/json`,"x-goog-api-key":t}}));if(!s.success)throw new v(`bad_response`,`Google returned an invalid model list.`);for(let e of s.data.models??[]){if(!e.supportedGenerationMethods?.includes(i))continue;let t=e.name.replace(/^models\//,``);a.push({id:t,label:e.displayName??t})}if(o=s.data.nextPageToken,!o)break}return a}function an(e){return[...new Set([e.key,e.fallbackKey,...Object.values(e.models??{}).flatMap(e=>[e.keySlot,e.fallbackKeySlot])].filter(e=>!!e))]}function on(e,t){return Object.fromEntries(e.map(e=>[e,Object.hasOwn(t,e)?t[e]:void 0]))}export{He as C,b as S,ze as _,an as a,T as b,X as c,Ke as d,Je as f,O as g,L as h,Ht as i,It as l,I as m,Wt as n,on as o,R as p,en as r,Bt as s,Vt as t,Ye as u,Ie as v,x,w as y};
|
|
1
|
+
import{E as e,d as t,x as n}from"./schemas-D7cgkv3L.js";import{H as r}from"./tool-schema-Cw0KPTnQ.js";import{$t as i,Ba as a,Cn as o,Da as s,Fi as c,Oa as l,Oi as u,Pi as ee,Qt as te,Sn as d,Ti as ne,Tn as f,Wa as re,Xa as ie,Y as ae,Zi as oe,ao as se,ba as ce,bn as le,ea as ue,fa as p,lo as m,na as de,nn as fe,ta as pe,uo as me,wi as h,xn as g,zi as _,zt as he}from"./shaped-data-gYhn8vze.js";import{c as v}from"./host-patterns-F-KZIzkF.js";import{D as ge,S as _e,g as y,k as ve,v as ye,w as be}from"./schema-DXPRQZid.js";import{a as xe,n as Se}from"./live-ingress-OuSlQ6q7.js";var Ce=2,we=4,Te=3,Ee=/(^|,)(\s*)("?)(?:([=@])|([+-])(?![0-9."]))/gm,De=/^[A-Za-z0-9+/]*={0,2}$/,Oe=new Set([`text/csv`,`text/plain`,`text/markdown`]);function b(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 ke(e,t){if(t.limitsByMime){let n=f(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 x(e){return`uri`in e}function Ae(e){if(e.type===`speech`)throw new v(`request`,`Profile ${e.id} (speech) does not accept media input`);if(e.type===`live`)throw new v(`request`,`Profile ${e.id} (live) does not accept turn attachment input`);if(e.type===`host`||e.type===`decision`||e.type===`embedding`)throw new v(`request`,`Profile ${e.id} (${e.type}) does not accept turn input`);let t=b(e.inputs??{});if(!t)throw new v(`config`,`Profile ${e.id} must set maxFiles, maxBytes, and maxTurnBytes`);return t}function je(e){let t=0;return e.endsWith(`==`)?t=Ce:e.endsWith(`=`)&&(t=1),Math.floor(e.length*Te/we)-t}function Me(e){try{return new TextDecoder(`utf-8`,{fatal:!0}).decode(e)}catch{return new TextDecoder(`latin1`).decode(e)}}function Ne(e){return e.replace(Ee,(e,...t)=>{let[n,r,i,a,o]=t;return`${n}${r}${i}'${a??``}${o??``}`})}function Pe(e,t,n){let r=Me(t);return e===`text/csv`&&(r=Ne(r)),new TextEncoder().encode(n.read(r))}function S(e,t){return t?{...e,fileName:t}:e}function C(e,t,n){return t.filter(t=>!g(e,t.mimeType)).map(e=>S({code:`mime_not_allowed`,params:{mimeType:e.mimeType,channel:n}},e.name))}function Fe(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=ke(i.mimeType,t);i.sizeBytes>e&&n.push(S({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 Ie(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(...C(e.attachments,t,`attachment`)),e.voice&&r.push(...C(e.voice,n,`voice`)),e.limits?[...r,...Fe([...t,...n],e.limits)]:[...r,{code:`limits_unconfigured`}])}var Le={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 Re(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:Le[e.code],params:t}}function ze(e,t){let n=Re(e);return m(n.key,n.params,t)}function w(e){return new v(`input`,`attachments refused: ${e.map(e=>e.code).join(`, `)}`,{copy:e.map(Re)})}function T(e){if(!De.test(e))throw new v(`request`,`attachment data must be base64`);return je(e)}function E(e){let t={mimeType:e.mimeType,name:e.name};return x(e)||(t.sizeBytes=T(e.data)),t}function Be(e,t,n){if(!Ve(t,n))return;let r=Ae(e),i=Ie({attachments:d(e,`attachments`),voice:d(e,`voice`),limits:r},(t??[]).map(E),(n??[]).map(E));if(i.length>0)throw w(i)}function D(e,t){if(x(e))return e;let{mimeType:n,data:r}=e;if(!Oe.has(f(n)))return e;let i=Pe(n,s(r),t);return{...e,data:l(i)}}function Ve(e,t){return(e?.length??0)>0||(t?.length??0)>0}function He(e,t,n,r){return Be(e,t,n),{attachments:t?.length?t.map(e=>D(e,r.attachment)):t,voice:n?.length?n.map(e=>D(e,r.voice)):n}}function O(e){let t=Object.keys(e);return t.length===1?t[0]:void 0}function k(e){return e==null}function A(e){return k(e)||typeof e!=`object`||Array.isArray(e)?null:e}function j(e){let t=A(e);return!t||t.type!==void 0&&t.type!==`object`?null:t}function M(e){let t=e.required;return Array.isArray(t)?t.filter(e=>typeof e==`string`):[]}function N(e){let t=e.properties;return A(t)??{}}function Ue(e,t){return e?`${e}.${t}`:t}function P(e,t){t.push({path:e,error:`required field '${e}' is missing`})}async function We(e,t,n,r,i,a){if(!n)return;let o;try{o=await n(t,r)}catch(e){a.push(e),o={isValid:!1}}o.isValid||i.push({path:e,error:o.error||o.finding||`Validation failed for '${e}'`})}async function Ge(e){let{path:t,propSchema:n,child:r,isRequired:i,fields:a,options:o,failures:s,crashes:c}=e;if(k(r)){i&&P(t,s);return}await We(t,r,a?.[t],o,s,c);let l=j(n),u=l?A(r):null;l&&u&&await F(l,u,t,a,o,s,c)}async function F(e,t,n,r,i,a,o){let s=N(e),c=new Set(M(e)),l=new Set([...Object.keys(s),...c]),u=A(t);for(let e of l)await Ge({path:Ue(n,e),propSchema:s[e],child:u?.[e],isRequired:c.has(e),fields:r,options:i,failures:a,crashes:o})}async function Ke(e,t,n,r,i=[]){let a=j(e);if(!a)throw new v(`config`,`structured validation requires a JSON Schema object root`);let o=[];if(!A(t)){for(let e of M(a))P(e,o);return o}return await F(a,t,``,n,r,o,i),o}function qe(e,t){let n=e;for(let e of t.split(`.`)){let t=j(n);if(!t)return!1;let r=N(t);if(!Object.hasOwn(r,e)&&!M(t).includes(e))return!1;n=r[e]}return!0}function Je(e){return e.map(e=>e.error).join(`; `)}function I(e,t){let n=e;for(let e of t.split(`.`))n=A(n)?.[e];return n}function L(e,t,n){let[r,...i]=t.split(`.`),a=A(e)??{};return r===void 0?e:{...a,[r]:i.length?L(a[r],i.join(`.`),n):n}}async function Ye(e,t,n,r=[]){let i=[];for(let[a,o]of Object.entries(t??{})){let t=I(e,a);if(Array.isArray(t))for(let[e,s]of t.entries()){let t;try{t=await o.check(s,n)}catch(e){r.push(e),t={isValid:!1}}t.isValid||i.push({path:a,index:e,item:s,reason:t.error||t.finding||`Validation failed for '${a}'`,onFail:o.onFail})}}return i}function R(e,t){let n=e;for(let e of t.split(`.`)){let t=j(n);if(!t)return;n=N(t)[e]}let r=A(n);if(r?.type===`array`)return A(r.items)??void 0}function Xe(e,t,n,r){if(!n.provider?.trim()||!n.apiId?.trim())throw new v(`config`,m(`provider.binding_identity`))}function Ze(e){B(e.id,e.models),Y(e.id,e.observability),zt(e.id,e.inputs);for(let[t,n]of Object.entries(e.models))H(e.id,t,n);return{type:`embedding`,id:e.id,identity:{handle:e.identity.handle},models:e.models,defaultModel:V(e.id,e),allowModelSelect:e.allowModelSelect,inputs:e.inputs,guardrails:e.guardrails,observability:e.observability,labels:e.labels}}function Qe(e){B(e.id,e.models),q(e.id,e.guardrails),Y(e.id,e.observability);for(let[t,n]of Object.entries(e.models))H(e.id,t,n);if(`text`in e.inputs&&e.inputs.text!==!1)throw new v(`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},...W(e),providerContinuation:void 0,maxSteps:void 0,inputs:{...e.inputs,text:!1},guardrails:e.guardrails,observability:e.observability,labels:e.labels}}function z(e,t,n,r){let i=r.safeParse(n);if(!i.success)throw new v(`config`,`Profile ${e} model '${t}': ${i.error.issues.map(e=>`${ae(e.path)}: ${e.message}`).join(`; `)}`)}function $e(e,t,n){if(z(e,t,n,i),Xe(e,t,n,`decision`),`retry`in n)throw new v(`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 v(`config`,`Profile ${e} model '${t}' timeoutMs must be > 0`)}function et(e){let t=e.models?O(e.models):void 0;if(!t)throw new v(`config`,`Profile ${e.id}: type 'decision' must declare exactly one model`);$e(e.id,t,e.models[t])}function tt(e){if(e.inputs.state!==`json`)throw new v(`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 v(`config`,`Profile ${e.id}: decision inputs.maxStateBytes must be a positive integer`);if(!e.decision.contract.trim())throw new v(`config`,`Profile ${e.id}: decision.contract must be non-empty`)}function nt(e){return et(e),tt(e),Y(e.id,e.observability),{...e,identity:{handle:e.identity.handle}}}function rt(e){return e===void 0?{}:{parallel:e}}function it(e){return at(e.id,e.tools),Y(e.id,e.observability),{type:`host`,id:e.id,tools:{allow:e.tools.allow,...rt(e.tools.parallel)},guardrails:e.guardrails,observability:e.observability,labels:e.labels}}function at(e,t){if(!Array.isArray(t.allow))throw new v(`config`,`Profile ${e}: type 'host' must set tools.allow`)}function B(e,t){if(Object.keys(t).length===0)throw new v(`config`,`Profile ${e} must declare at least one model`)}function V(e,t){let n=t.defaultModel??O(t.models);if(!n)throw new v(`config`,`Profile ${e} must set defaultModel when more than one model is declared`);if(!t.models[n])throw new v(`config`,`Profile ${e} defaultModel '${n}' is not declared`);return n}function H(e,t,n){U(e,t,n),z(e,t,n,fe),U(e,t,n)}function U(e,t,n){let r=n.efforts;if(!r||Object.keys(r).length===0){if(n.defaultEffort||n.allowEffortSelect)throw new v(`config`,`Profile ${e} model '${t}': defaultEffort and allowEffortSelect require efforts`);return}for(let[n,i]of Object.entries(r))if(!_.includes(i))throw new v(`config`,`Profile ${e} model '${t}' effort '${n}': '${i}' is not a thinking level (${_.join(`, `)})`);let i=Object.keys(r),a=n.defaultEffort??(i.length===1?i[0]:void 0);if(!a)throw new v(`config`,`Profile ${e} model '${t}' must set defaultEffort when more than one effort is declared`);if(!r[a])throw new v(`config`,`Profile ${e} model '${t}' defaultEffort '${a}' is not declared`);if(n.allowEffortSelect&&i.length<2)throw new v(`config`,`Profile ${e} model '${t}' allowEffortSelect requires at least two efforts`)}function W(e){return{providerContinuation:e.providerContinuation?ce.parse(e.providerContinuation):{},models:e.models,defaultModel:V(e.id,e),allowModelSelect:e.allowModelSelect,maxSteps:e.maxSteps}}function G(e,t,n){if(n?.length){for(let r of n)if(!he(r))throw new v(`config`,`Profile ${e}: turnBehaviour.resumption.${t} may only include ContinueStopKind (${ne.join(` | `)}); got '${r}'`)}}function ot(e,t){t&&(G(e,`allowContinue`,t.allowContinue),G(e,`autoContinue`,t.autoContinue))}function K(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function st(e,t){let n=[e];for(let e of t)n=n.flatMap(t=>K(t)?e===`*`?Object.values(t):[t[e]]:[]);return n}var ct=Object.entries(ee).filter(([,e])=>e.required===!0).map(([e,t])=>[e,t.profileTypes]).sort(([e],[t])=>e.split(`.`).length-t.split(`.`).length);function lt(e){if(!K(e))throw new v(`config`,`Profile definition must be an object`);let t=typeof e.id==`string`&&e.id.trim()?e.id:void 0;if(!t)throw new v(`config`,`Profile definition must set id`);if(!c.find(t=>t===e.type))throw new v(`config`,`Profile ${t}: type must be one of ${c.join(`, `)}`)}function ut(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 v(`config`,`Profile ${e.id.slice(0,64)}: ${t} must be at most ${i} characters`)}function dt(e){let{id:t,type:n}=e,r=e;for(let[e,i]of ct){if(i&&!i.includes(n))continue;let a=pe(e),o=st(r,a.slice(0,-1)),s=a[a.length-1];if(o.some(e=>{if(!K(e))return!1;let t=e[s];return t==null||t===``}))throw new v(`config`,`Profile ${t}: type '${n}' must set ${a.join(`.`)}`)}}function ft(e){let{id:t,type:n}=e;if(n!==`live`&&de(`inputs`).includes(n)&&e.inputs==null)throw new v(`config`,`Profile ${t}: type '${n}' must set inputs`)}function pt(e){let[t]=ue(e);if(!t)return;let{offValue:n,reason:r}=t.scope,i=n===void 0?``:` (other than ${n})`;throw new v(`config`,`Profile ${e.id}: type '${e.type}' must not set ${t.path}${i} — ${r}`)}function mt(e,t){let n=t.turnBehaviour;ot(e,n?.resumption)}function ht(e,t){let n=t=>new v(`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 q(e,t){let n=t=>new v(`config`,`Profile ${e}: ${t}`),r=Object.keys(t??{}).find(e=>!J.includes(e));if(r!==void 0)throw n(`guardrails.${r} is not a setting; it takes ${J.join(`, `)}`);_t(t?.blockedReply,n)}var J=[`quota`,`detect`,`blockedReply`,`network`,`taint`],gt=[`onBlock`,`maxRetries`];function _t(e,t){if(e===void 0)return;let n=Object.keys(e).find(e=>!gt.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&&!a.includes(r))throw t(`guardrails.blockedReply.onBlock must be one of ${a.join(`, `)}`);if(i!==void 0&&(!Number.isInteger(i)||i<0))throw t(`guardrails.blockedReply.maxRetries must be a non-negative integer`)}function vt(e){let t=e.guardrails?.detect,n=e.type===`host`?p(`guardrails.detect`,t,re):p(`guardrails.detect`,t);if(n!==void 0)throw new v(`config`,`Profile ${e.id}: ${n}`)}function Y(e,t){try{let n=xe(t);if(!Number.isFinite(n.retainForDays))throw new v(`config`,`Profile ${e}: observability.retainForDays must be a finite number`);if(n.rotateAfterMiB<=0||!Number.isFinite(n.rotateAfterMiB))throw new v(`config`,`Profile ${e}: observability.rotateAfterMiB must be a positive number`)}catch(t){if(t instanceof v&&t.message.startsWith(`Profile `))throw t;let n=t instanceof Error?t.message:String(t);throw new v(ie(t),`Profile ${e}: ${n}`,{cause:t})}}function yt(e){if(e.type===`host`||e.type===`decision`||e.type===`speech`||e.type===`transcription`||e.type===`embedding`)return;let{options:t,system:n}=e.identity,r=n??``;_e(r,`Profile ${e.id} identity.system`);let i=be(r,t,e.inputs?.options);if(i)throw new v(`config`,`Profile ${e.id} identity.system: ${i}`)}function X(e){let t=bt(e),[n]=oe(e);if(n)throw new v(`config`,`Profile ${e.id}: ${n.path} ${n.message}`);return t}function bt(e){lt(e);for(let t of[`key`,`fallbackKey`,`protocol`,`provider`])if(t in e)throw new v(`config`,m(`provider.profile_configuration`,{profile:e.id,field:t}));pt(e),ft(e),dt(e),ut(e),e.labels&&me(e.labels,`Profile ${e.id}`);for(let t of se)if(e.labels?.[t]!==void 0)throw new v(`config`,`Profile ${e.id}: labels '${t}' is a host line, which a profile cannot change; set it with overrideLabels`);if(yt(e),vt(e),e.type===`host`)return it(e);if(e.type===`decision`)return nt(e);if(e.type===`embedding`)return Ze(e);if(e.type===`transcription`)return Qe(e);B(e.id,e.models),mt(e.id,e),q(e.id,e.guardrails),e.type===`text`&&ht(e.id,e.outputs?.validation),Y(e.id,e.observability);for(let[t,n]of Object.entries(e.models))H(e.id,t,n);let t=e.type===`speech`?{handle:e.identity.handle}:{handle:e.identity.handle,options:e.identity.options,system:e.identity.system},n=e.guardrails,r=e.observability,i=e.labels,a=W(e),o;switch(e.type){case`text`:o={type:`text`,id:e.id,identity:t,...a,tools:e.tools,inputs: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:e.inputs,outputs:e.outputs,turnBehaviour:e.turnBehaviour,guardrails:n,observability:r,labels:i},Et(o.id,o.inputs.attachments?.accept),Tt(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,tools:{allow:e.tools.allow,...rt(e.tools.parallel)},turnBehaviour:e.turnBehaviour,guardrails:n,observability:r,labels:i},Se(o),Ot(o.id,o.live.contextCompression),Dt(o);break;default:throw new v(`config`,`Unknown profile type '${String(e)}'`)}return Ct(o),xt(o),St(o),o}function xt(e){let{maxSteps:t}=e;if(!(t===void 0||Number.isInteger(t)&&t>0))throw new v(`config`,`Profile ${e.id}: maxSteps must be a whole number of 1 or more; leave it out for the default of 20`)}function St(e){if(e.type===`text`&&e.turnBehaviour?.atStepLimit===`answer`&&e.maxSteps===1)throw new v(`config`,`Profile ${e.id}: turnBehaviour.atStepLimit 'answer' with maxSteps 1 leaves no step that can call a tool`)}function Ct(e){if(e.type===`live`)return;let t=e.outputs?.structured;if(!t||typeof t==`string`)return;let n=ve(e,t.by);if(!n)throw new v(`config`,`Profile ${e.id}: outputs.structured.by '${t.by}' is not one of the profile's options`);let r=ge(n),i=Object.keys(t.map).filter(e=>!r.includes(e));if(i.length)throw new v(`config`,`Profile ${e.id}: outputs.structured.map maps ${i.join(`, `)}, not a choice of option '${t.by}'`)}var wt={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 Tt(e,t){for(let[n,{ok:r,rule:i}]of Object.entries(wt)){let a=t[n];if(a!==void 0&&!r(a))throw new v(`config`,`Profile ${e}: image.${n} must be ${i}`)}t.references?.forEach((t,n)=>{let r=`Profile ${e}: image.references[${n}]`;if(le(t.mimeType)!==`image`)throw new v(`config`,`${r} must be an image, not '${t.mimeType}'`);if(!(x(t)?t.uri:t.data))throw new v(`config`,`${r} needs its bytes or its uri`)})}function Et(e,t){let n=t?.filter(e=>!g(u,e));if(n?.length)throw new v(`config`,`Profile ${e}: an image profile's attachments take images, video, and PDF only, not ${n.join(`, `)}`)}function Dt(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 v(`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 v(`config`,`${i}.resumed.prompt must be a prompt`);let{afterMs:a}=n;if(a!==void 0&&!(Number.isFinite(a)&&a>=0))throw new v(`config`,`${i}.resumed.afterMs must be 0 or more milliseconds`);if(!r)throw new v(`config`,`${i}.resumed needs live.sessionResumption: without it no call resumes`)}function Ot(e,t){if(!t)return;let n=`Profile ${e} live.contextCompression`,r=t.triggerTokens,i=t.slidingWindow.targetTokens;if(Z(`${n}.triggerTokens`,r),Z(`${n}.slidingWindow.targetTokens`,i),r!==void 0&&i!==void 0&&i>=r)throw new v(`config`,`${n}: slidingWindow.targetTokens must be below triggerTokens`)}function Z(e,t){if(!(t===void 0||Number.isInteger(t)&&t>0))throw new v(`config`,`${e} must be a whole number above 0`)}function kt(e,t,n,r){let i=`Profile ${t.id} model ${n} compaction`;if(At(i,r),jt(i,r),r.profile===void 0){if(t.type!==`text`||t.inputs.text===!1)throw new v(`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 v(`config`,`${i}: compaction profile '${r.profile}' must be registered before '${t.id}'`);if(a.type!==`text`||a.inputs.text===!1)throw new v(`config`,`${i}: compaction profile '${r.profile}' must be a text profile that takes text`)}function At(e,t){if(t.maxTokens<=0)throw new v(`config`,`${e}: maxTokens must be > 0`);if(t.compactAt<=0||t.compactAt>=1)throw new v(`config`,`${e}: compactAt must be in (0, 1)`)}function jt(e,t){if(t.previousExchanges<0)throw new v(`config`,`${e}: previousExchanges must be >= 0`);if(t.previousExchanges<1&&t.previousExchanges>=t.compactAt)throw new v(`config`,`${e}: previousExchanges as fraction (${t.previousExchanges}) must be < compactAt (${t.compactAt})`);if(t.previousExchanges>1&&!Number.isInteger(t.previousExchanges))throw new v(`config`,`${e}: previousExchanges >= 1 must be an integer`)}function Mt(e,t){for(let n of y(t))if(e.get(n)?.type===`builtin`)throw new v(`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 Nt(e,t){let n=ye(t)?.t2Loader;if(n){if(!y(t).includes(n))throw new v(`config`,`Profile ${t.id} tools.t2Loader '${n}' must also be listed in tools.allow`);if(e.get(n)?.type!==`function`)throw new v(`config`,`Profile ${t.id} tools.t2Loader '${n}' must be a registered type: 'function' tool`)}}function*Pt(e){for(let[t,n]of Object.entries(e.models))for(let e of n.builtInTools??[])yield{modelId:t,id:e}}function Ft(e,t){for(let{modelId:n,id:r}of Pt(t))if(e.get(r)?.type!==`builtin`)throw new v(`config`,`Profile ${t.id} model '${n}' lists '${r}' in builtInTools — not a registered builtin`)}function Q(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 It(e,t){return t?.type===`text`?Q(t).flatMap(t=>{let n=e.find(t);return n?[n.jsonSchema]:[]}):[]}function Lt(e,t){let n=Q(t).map(n=>{let r=e.find(n);if(!r)throw new v(`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 v(`config`,`Profile ${t.id}: outputs.validation checks a structured reply, so it needs outputs.structured`);let o=a.filter(e=>!n.some(t=>R(t.jsonSchema,e)));if(o.length)throw new v(`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=>qe(t.jsonSchema,e)));if(s.length)throw new v(`config`,`Profile ${t.id}: outputs.validation.fields has ${s.join(`, `)}, which no structured schema reaches through object properties`)}function Rt(e){let t=o(e)?.context;if(!t)return;let n=h;if(t.from.length===0||t.from.some(e=>!n.includes(e)))throw new v(`config`,`Profile ${e.id}: inputs.context.from must list ${h.join(` or `)}`);if(!(Number.isInteger(t.maxChars)&&t.maxChars>0))throw new v(`config`,`Profile ${e.id}: inputs.context.maxChars must be a positive integer`)}function zt(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 v(`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 v(`config`,`Profile ${e}: inputs.${t} must be a positive integer`)}function Bt(e,t,n){let r=new Map,i=i=>{let a=X(i),s=n&&a.type!==`host`?{...a,models:Object.fromEntries(Object.entries(a.models).map(([e,t])=>[e,te(n.require(t.provider,t.apiId),t,a.type)]))}:a;if(Mt(e,s),Nt(e,s),s.type!==`host`&&s.type!==`decision`&&s.type!==`embedding`){Ft(e,s),zt(s.id,o(s)),Rt(s),Lt(t,s);for(let[e,t]of Object.entries(s.models))t.compaction&&kt(r,s,e,t.compaction)}r.set(s.id,s)};return{register:i,registerMany(e){for(let t of e)i(t)},get(e){let t=r.get(e);if(!t)throw new v(`config`,`Unknown profile '${e}'`);return t},find:e=>r.get(e),has:e=>r.has(e),list:()=>[...r.values()],clear:()=>r.clear()}}function Vt(e){let t=e?.trim()??``;if(t.startsWith(`AIza`))return`gemini`;if(t.startsWith(`sk-or-`))return`openrouter`}function Ht(e){let t;try{t=new URL(e.baseUrl)}catch{throw new v(`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 v(`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 v(`blocked`,`Local requests must stay on the configured origin.`))}}var Ut=n({data:t(n({id:e().min(1)}))});async function Wt(e,t){let n=Ht(e);if(!n?.fetch)throw new v(`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 v(`network`,`Local model list returned HTTP ${r.status}.`);let i=Ut.safeParse(await r.json());if(!i.success)throw new v(`request`,`The endpoint returned an invalid model list.`);return[...new Set(i.data.data.map(e=>e.id))]}var Gt=`https://openrouter.ai/api/v1/models`,Kt=`https://openrouter.ai/api/v1/embeddings/models`,qt=[{id:`gemini-embedding-2-preview`,label:`Gemini Embeddings 2 (preview)`},{id:`gemini-embedding-001`,label:`Gemini Embedding 001`}],Jt=[{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)`}],Yt={text:`text`,image:`image`,speech:`speech`,transcription:`transcription`,live:void 0,embedding:void 0},Xt=n({data:t(n({id:e().min(1),name:e().optional(),architecture:n({output_modalities:t(e()).optional()}).optional()}))}),Zt=n({data:t(n({id:e().min(1),name:e().optional()}))}),Qt=n({models:t(n({name:e().min(1),displayName:e().optional(),supportedGenerationMethods:t(e()).optional()})).optional(),nextPageToken:e().optional()}),$t=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 v(`auth`,`${e} refused the key.`);if(!r.ok)throw new v(`network`,`${e} model list returned HTTP ${r.status}.`);return await r.json()}async function en(e,t,n,r){let i=n?.trim();if(t===`embedding`&&!i)return[...e===`openrouter`?Jt:qt];if(e===`openrouter`)return await tn(t,i,r);if(!i)throw new v(`auth`,`Choose a key to list Gemini models.`);return await rn(t,i,r)}async function tn(e,t,n){let r={signal:n,headers:{Accept:`application/json`,...t?{Authorization:[`Bearer`,t].join(` `)}:{}}};if(e===`embedding`){let e=Zt.safeParse(await $(`OpenRouter`,Kt,r));if(!e.success)throw new v(`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=Yt[e];if(!i)return[];let a=Xt.safeParse(await $(`OpenRouter`,`${Gt}?output_modalities=${i}`,r));if(!a.success)throw new v(`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 nn={live:`bidiGenerateContent`,embedding:`embedContent`};async function rn(e,t,n){let i=nn[e]??`generateContent`,a=[],o;for(let e=0;e<$t;e++){let e=new URL(r);e.searchParams.set(`pageSize`,`1000`),o&&e.searchParams.set(`pageToken`,o);let s=Qt.safeParse(await $(`Google`,e.href,{signal:n,headers:{Accept:`application/json`,"x-goog-api-key":t}}));if(!s.success)throw new v(`bad_response`,`Google returned an invalid model list.`);for(let e of s.data.models??[]){if(!e.supportedGenerationMethods?.includes(i))continue;let t=e.name.replace(/^models\//,``);a.push({id:t,label:e.displayName??t})}if(o=s.data.nextPageToken,!o)break}return a}function an(e){return[...new Set([e.key,e.fallbackKey,...Object.values(e.models??{}).flatMap(e=>[e.keySlot,e.fallbackKeySlot])].filter(e=>!!e))]}function on(e,t){return Object.fromEntries(e.map(e=>[e,Object.hasOwn(t,e)?t[e]:void 0]))}export{He as C,b as S,ze as _,an as a,T as b,X as c,Ke as d,Je as f,O as g,L as h,Ht as i,It as l,I as m,Wt as n,on as o,R as p,en as r,Bt as s,Vt as t,Ye as u,Ie as v,x,w as y};
|
|
@@ -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{A as m,C as h,L as g,p as _,v}from"./tool-schema-Cw0KPTnQ.js";import{$ as y,$a as b,$n as x,An as S,Ar as C,At as w,B as T,Bn as E,Br as ee,Bt as D,Ca as te,Cn as ne,Cr as O,Ct as re,Da as k,Dn as ie,Dr as ae,Dt as oe,En as A,Er as se,Et as ce,F as le,Fn as ue,Fr as j,G as de,Gr as fe,Gt as pe,H as me,Hi as he,Hn as ge,Hr as _e,Ht as ve,I as M,In as ye,Ir as be,J as xe,Ja as Se,Jr as Ce,Jt as we,K as Te,Ki as Ee,Kr as De,Kt as Oe,L as ke,Ln as Ae,Lr as je,Ma as Me,Mn as Ne,Mr as Pe,Mt as N,N as Fe,Na as Ie,Ni as Le,Nn as Re,Nr as ze,Nt as P,Oa as F,On as Be,Or as I,Ot as Ve,P as He,Pn as Ue,Pr as We,Pt as Ge,Q as Ke,Qa as qe,R as Je,Rn as Ye,Rt as Xe,Sa as L,Sr as Ze,St as Qe,Tr as $e,Tt as et,U as tt,Un as nt,Ur as rt,V as it,Va as at,Vi as ot,Vn as st,W as ct,Wi as lt,Wn as ut,Wr as dt,Wt as ft,X as pt,Xa as R,Xn as mt,Xt as ht,Y as gt,Ya as _t,Yn as vt,Yr as yt,Yt as bt,Z as xt,Za as St,Zt as Ct,_i as wt,_r as Tt,_t as Et,an as Dt,bi as Ot,bn as kt,br as At,bt as jt,cr as Mt,di as Nt,dt as Pt,et as Ft,fi as It,fn as Lt,gi as Rt,gn as zt,gr as Bt,gt as Vt,ha as Ht,hn as z,hr as Ut,in as Wt,io as Gt,ir as Kt,ja as qt,jn as Jt,jr as Yt,jt as Xt,ka as Zt,kn as Qt,kr as $t,kt as en,lo as B,lr as tn,lt as nn,mn as rn,mr as an,mt as on,na as sn,no as V,nr as cn,nt as ln,on as un,or as dn,pn as fn,pt as pn,q as H,qa as mn,qr as hn,rn as gn,ro as U,rr as _n,rt as vn,sn as yn,st as bn,tn as xn,to as Sn,tr as Cn,tt as wn,ui as Tn,va as En,vi as Dn,vr as On,vt as kn,wa as An,wi as jn,wn as Mn,wr as Nn,wt as Pn,xa as Fn,xt as In,ya as Ln,yi as Rn,yn as zn,yt as Bn,z as Vn,zn as Hn,zr as Un}from"./shaped-data-gYhn8vze.js";import{c as W,t as Wn}from"./host-patterns-F-KZIzkF.js";import{$ as Gn,A as Kn,B as qn,G as Jn,H as Yn,J as Xn,K as Zn,L as Qn,N as $n,O as er,P as tr,Q as nr,R as rr,U as ir,V as ar,W as or,X as sr,Y as cr,Z as lr,a as ur,at as dr,ct as fr,et as pr,i as mr,it as hr,l as gr,lt as G,m as _r,n as vr,nt as yr,o as br,ot as xr,q as Sr,r as Cr,rt as wr,st as Tr,tt as Er,z as Dr}from"./reader
|
|
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{A as m,C as h,L as g,p as _,v}from"./tool-schema-Cw0KPTnQ.js";import{$ as y,$a as b,$n as x,An as S,Ar as C,At as w,B as T,Bn as E,Br as ee,Bt as D,Ca as te,Cn as ne,Cr as O,Ct as re,Da as k,Dn as ie,Dr as ae,Dt as oe,En as A,Er as se,Et as ce,F as le,Fn as ue,Fr as j,G as de,Gr as fe,Gt as pe,H as me,Hi as he,Hn as ge,Hr as _e,Ht as ve,I as M,In as ye,Ir as be,J as xe,Ja as Se,Jr as Ce,Jt as we,K as Te,Ki as Ee,Kr as De,Kt as Oe,L as ke,Ln as Ae,Lr as je,Ma as Me,Mn as Ne,Mr as Pe,Mt as N,N as Fe,Na as Ie,Ni as Le,Nn as Re,Nr as ze,Nt as P,Oa as F,On as Be,Or as I,Ot as Ve,P as He,Pn as Ue,Pr as We,Pt as Ge,Q as Ke,Qa as qe,R as Je,Rn as Ye,Rt as Xe,Sa as L,Sr as Ze,St as Qe,Tr as $e,Tt as et,U as tt,Un as nt,Ur as rt,V as it,Va as at,Vi as ot,Vn as st,W as ct,Wi as lt,Wn as ut,Wr as dt,Wt as ft,X as pt,Xa as R,Xn as mt,Xt as ht,Y as gt,Ya as _t,Yn as vt,Yr as yt,Yt as bt,Z as xt,Za as St,Zt as Ct,_i as wt,_r as Tt,_t as Et,an as Dt,bi as Ot,bn as kt,br as At,bt as jt,cr as Mt,di as Nt,dt as Pt,et as Ft,fi as It,fn as Lt,gi as Rt,gn as zt,gr as Bt,gt as Vt,ha as Ht,hn as z,hr as Ut,in as Wt,io as Gt,ir as Kt,ja as qt,jn as Jt,jr as Yt,jt as Xt,ka as Zt,kn as Qt,kr as $t,kt as en,lo as B,lr as tn,lt as nn,mn as rn,mr as an,mt as on,na as sn,no as V,nr as cn,nt as ln,on as un,or as dn,pn as fn,pt as pn,q as H,qa as mn,qr as hn,rn as gn,ro as U,rr as _n,rt as vn,sn as yn,st as bn,tn as xn,to as Sn,tr as Cn,tt as wn,ui as Tn,va as En,vi as Dn,vr as On,vt as kn,wa as An,wi as jn,wn as Mn,wr as Nn,wt as Pn,xa as Fn,xt as In,ya as Ln,yi as Rn,yn as zn,yt as Bn,z as Vn,zn as Hn,zr as Un}from"./shaped-data-gYhn8vze.js";import{c as W,t as Wn}from"./host-patterns-F-KZIzkF.js";import{$ as Gn,A as Kn,B as qn,G as Jn,H as Yn,J as Xn,K as Zn,L as Qn,N as $n,O as er,P as tr,Q as nr,R as rr,U as ir,V as ar,W as or,X as sr,Y as cr,Z as lr,a as ur,at as dr,ct as fr,et as pr,i as mr,it as hr,l as gr,lt as G,m as _r,n as vr,nt as yr,o as br,ot as xr,q as Sr,r as Cr,rt as wr,st as Tr,tt as Er,z as Dr}from"./reader--ohfEAKk.js";import{a as Or,b as kr,c as Ar,d as jr,f as Mr,g as Nr,h as Pr,m as Fr,p as Ir,u as Lr,y as Rr}from"./browser-connection-WnnSpy0l.js";import{A as zr,E as Br,_ as Vr,a as Hr,b as Ur,f as Wr,g as Gr,h as Kr,j as qr,l as Jr,m as Yr,p as Xr,r as Zr,s as Qr,t as $r,v as ei,x as ti,y as ni}from"./schema-DXPRQZid.js";import{a as ri,t as ii}from"./live-ingress-OuSlQ6q7.js";import{t as ai}from"./trace-record-DK92KCo0.js";import{_ as oi,a as si,c as ci,d as li,f as ui,g as di,h as fi,i as pi,l as mi,m as hi,o as gi,p as _i,r as vi,s as yi,u as bi,v as xi,y as Si}from"./registry-DTX5GVdX.js";import{D as Ci,E as wi,O as Ti,S as Ei,a as Di,b as Oi,d as ki,f as Ai,k as ji,l as Mi,u as Ni,v as Pi}from"./turn-client-Cef0JadZ.js";import{n as Fi,t as Ii}from"./live-messages-BrQhgNiV.js";import{n as Li,r as Ri}from"./lent-keys-C32ems-I.js";import{Ct as zi,St as Bi,_t as Vi,ft as Hi,gt as Ui,ht as Wi,lt as Gi,mt as Ki,pt as qi,ut as Ji,wt as Yi,xt as Xi}from"./index-yC5X4xkW.js";function Zi(){return{given:new Set,remote:new Map}}var Qi=/[\p{L}\p{N}_.+-]/u,$i=/[\p{L}\p{N}_-]/u,ea=/(?:https?:\/\/|www\.)[^\s'"<>)\]]+/gi,ta=/\b[A-Z]{2}\d{2}[A-Z0-9]{10,30}\b/g,na=/[/?#]/;function ra(e,t){let n=t;for(;n<e.length;){let t=String.fromCodePoint(e.codePointAt(n)??0);if(!$i.test(t))break;n+=t.length}return n}function ia(e,t){let n=ra(e,t);if(n===t)return-1;let r=1;for(;e.charAt(n)===`.`;){let t=ra(e,n+1);if(t===n+1)break;n=t,r+=1}return r>1?n:-1}function aa(e){let t=e.length;for(;t>0&&(e.charAt(t-1)===`.`||e.charAt(t-1)===`,`);)--t;return e.slice(0,t)}function oa(e){let t=[],n=e.indexOf(`@`);for(;n>=0;){let r=n;for(;r>0&&Qi.test(e.charAt(r-1));)--r;let i=r<n?ia(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 sa(e){let t=e.replace(/^https?:\/\//i,``),n=t.search(na),r=n<0?t:t.slice(0,n);return aa(r.slice(r.lastIndexOf(`@`)+1).replace(/:\d*$/,``).toLowerCase()).replace(/^www\./,``)}function ca(e){let t=oa(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(ea)]){let t=sa(e[0]);t&&a.push({key:`host:${t}`,start:e.index,end:e.index+e[0].length})}for(let e of[...i.matchAll(ta)])a.push({key:`account:${e[0].toLowerCase()}`,start:e.index,end:e.index+e[0].length});return a}function la(e){let t=e.trimStart().charAt(0);if(t===`{`||t===`[`)try{return JSON.parse(e)}catch{return}}var ua=32;function da(e,t,n=0){if(!(n>ua)){if(typeof e==`string`){let r=la(e);r===void 0?t(e):da(r,t,n+1)}else if(Array.isArray(e))for(let r of e)da(r,t,n+1);else if(e&&typeof e==`object`)for(let r of Object.values(e))da(r,t,n+1)}}function fa(e,t=!1){let n=new Set;return da(e,e=>{let r=e.trim(),i=ca(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 pa(e,t){for(let n of fa(t))e.given.add(n)}function ma(e,t,n){for(let r of t)r.role===`assistant`||r.role===`tool`||n.has(r)||Ze(r)||pa(e,An(r).text)}function ha(e,t,n){pa(e,t.system),n.has(t.input)||pa(e,An(t.input).text),ma(e,t.history??[],n)}function ga(e,t,n){if(!Ne(n.origin)){pa(e,[t.finding,t.data]);return}let r=la(t.finding),i=new Set([...r===void 0?fa(t.finding):fa(r,!0),...fa(t.data,!0)]);for(let t of i)e.remote.has(t)||e.remote.set(t,n.tool)}function _a(e,t,n){let r=t.lastIndexOf(`
|
|
3
3
|
`),i=r<0?void 0:la(t.slice(r+1));ga(e,i===void 0?{finding:t}:{finding:t.slice(0,r),data:i},n)}function va(e,t,n,r){if(!e||e.remote.size===0)return{verdict:{action:`allow`}};let i=[...fa(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:Ie.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:B(`taint.destination_blocked`,s,r)}}:{verdict:{action:`flag`,hits:o},...c===`confirm`?{confirm:B(`taint.destination_confirm`,s,r)}:{}}}var ya={image:`thought.omitted_image`,link:`thought.omitted_link`,instructions:`thought.omitted_instructions`},ba={rule:qt.ungiven_images,severity:`high`},xa={rule:qt.ungiven_links,severity:`high`},Sa={rule:qt.marker_leak,severity:`high`},Ca={rule:qt.prompt_leak,severity:`high`};function wa(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 Ta(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 Ea=8,Da=16;function Oa(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=cn({canary:l,labels:o}),d=e=>({...e,...a?{given:a}:{}});function f(e,t){let n=B(ya[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?dr({detect:s,allow:{ungiven_images:t.images??{},ungiven_links:t.links??{}},skipImages:c,...a?{given:a}:{},...u?{note:u}:{}}):void 0,g=n?be(n):void 0,_=0,v=0,E(e)}function E(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=yt(e,_);i=Ce(e.slice(t),r,l).length>0,_=e.length}return t||n||i}function D(e){let i=[];if(t.images)for(let n of On(e,d(t.images)))i.push({...n,kind:`image`,hit:ba});if(t.links)for(let n of At(e,d(t.links),c))i.push({...n,kind:`link`,hit:xa});if(t.markers){let t=[new RegExp(Mt.source,`gi`),...u?[tn(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:Sa})}}if(n)for(let[t,r]of Pe(e,n))i.push({start:t,end:r,kind:`instructions`,hit:Zt});if(r)for(let[t,n]of Ce(e,r,l))i.push({start:t,end:n,kind:`instructions`,hit:Ca});return i}function te(e){return b.find(t=>t.start<e&&e<t.end)}function ne(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=ae;;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||yt(a.text,a.held)>0)return a}}function re(){let e=O();if(!e)return[];let t=[];if(n)for(let[r,i]of Pe(e.text,n))t.push([r,i,Zt]);if(r)for(let[n,i]of Ce(e.text,r,l))t.push([n,i,Ca]);let i=[];for(let[n,r,a]of t){if(r<=e.held)continue;let t=wa(e,n),o=wa(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 k(){return Ta([...D(p+m),...re()])}function ie(){return k().filter(({end:e})=>e>p.length)}function oe(e,t=!1){let n=te(e);return n?t?n.end:n.start:e}function A(e){let t=ie(),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(oe(e)),S=i?.has(a.rule)??!1;let o=S?n.length:Math.max(l,oe(t,!0)),d=f(r,p+c),m=p.length+c.length;if(s.push({start:m,end:m+d.length,raw:ne(l,o)}),c+=d,w.set(a.rule,a),l=o,S)break}return y=void 0,a&&!S&&(u(oe(a.start)),y=p.length+c.length),u(n.length),b=s,m=c,x=0,o.length>0}function se(){let e=k()[0],t=e?Math.max(0,oe(e.start)-p.length):0,n=m.slice(0,t),r=f(e?.kind??`instructions`,p+n),i=p.length+t,a=ne(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 ce(){let e=p+m;return y===void 0?e:e.slice(0,y)}function le(){for(let e=0;e<Ea&&!(C>=Da);e++){let e=new Set(b.map(e=>e.start));if(!A(!1)){if(y===void 0)break;return}if(S||(b.some(t=>!e.has(t.start))&&C++,!T(ce())))return}se()}function ue(){let e=p.length+m.length,t=h?h.holdFrom():e,i=n?j(n):e,a=r?p.length+hn(m,r,l):e,o=Math.min(t,i,a,fe()??e,y??e);return oe(o<p.length?o:p.length+dt(m,o-p.length))}function j(e){let t=Math.max(p.length,x),n=Math.max(0,t-I),r=n+We(de(n),e);if(r<t&&t>p.length){let t=Math.max(0,p.length-I);r=t+We(de(t),e)}return x=Math.min(r,p.length+m.length-I),Math.max(p.length,r)}function de(e){return e<p.length?p.slice(e)+m:m.slice(e-p.length)}function fe(){let e=O();if(!e)return;let t=e.text.slice(e.held),i=n?Yt(t,n,e.text.slice(0,e.held)):t.length,a=r?hn(t,r,l):t.length;return wa(e,e.held+Math.min(i,a))}function pe(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||E(e)||re().length>0)&&le(),S))return pe(``);let t=Math.max(0,ue()-p.length),n=m.slice(0,t);return p+=n,m=m.slice(t),pe(n)},flush(){if(!S){for(let e=0;e<Ea&&!S&&A(!0);e++);!S&&m&&(D(p+m).length>0||re().length>0)&&se()}let e=m,t=p+m;p=n||r?ee(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),pe(e)},carryOut:()=>p}}function ka(...e){let t=e.filter(e=>e!==void 0);return t.length===0?{}:{found:{action:t.reduce((e,t)=>x(e,t.action),`allow`),hits:[...new Map(t.flatMap(({hits:e})=>e).map(e=>[e.rule,e])).values()]}}}function Aa(e,t,n,r){let i=()=>hr(`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,...ka(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()],...ka(n,r?.found,u.found)}},carryOut:()=>e?.carryOut()??``}}var ja={canary_leak:Zt,prompt_leak:Ca,marker_leak:Sa,ungiven_images:ba,ungiven_links:xa},Ma=[`marker_leak`,`ungiven_images`,`ungiven_links`];function Na(e,t){let{canary:n,privateSystem:r}=e,i=n?be(n):void 0,a=``,o=new Set;return{read(e){let n=yt(a+e,a.length);a+=e;let s=[];i?.push(e)&&s.push(Zt),r&&Ce(a.slice(n),r,t).length>0&&s.push(Ca);let c=s.filter(e=>!o.has(e.rule));for(let e of c)o.add(e.rule);return c},reset(){i=n?be(n):void 0,a=``,o=new Set}}}function Pa(e,t,n,r){let i=Na(n,r),a=new Map(Object.entries(ja).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)=>x(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 Fa(e,t,n){let{detect:r}=e,i=Ma.filter(e=>Ia(r,e)),a=Ra(r,t,Ia),o=Ra(r,t,(e,t)=>e[t].thought===`flag`),s=i.length>0||za(a)||za(o),c=mt(e,t);(s||ut([`thought`],r,c))&&await xr();let l=s?Oa({omit:La(e),...a,...Ba(r),...Va(t),...n?{carry:n}:{}}):void 0;return Aa(l&&Pa(l,r,o,t.canary),r,c,i)}function Ia(e,t){return e[t].thought===`redact`||e[t].thought===`block`}function La({detect:e,allow:t}){return{...Ia(e,`marker_leak`)?{markers:!0}:{},...Ia(e,`ungiven_images`)?{images:t.ungiven_images}:{},...Ia(e,`ungiven_links`)?{links:t.ungiven_links}:{},imagesRead:e.ungiven_images.thought!==`ignore`}}function Ra(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 za(e){return e.canary!==void 0||e.privateSystem!==void 0}function Ba(e){let t=new Set(Object.entries(ja).filter(([t])=>e[t].thought===`block`).map(([,e])=>e.rule));return t.size>0?{ends:t}:{}}function Va({canary:e,givenUrls:t,labels:n}){return{...e?{planted:e}:{},...t?{given:t}:{},...n?{labels:n}:{}}}var Ha={rule:`live.untranscribed-audio`,severity:`high`};async function Ua(e,t,n,r,i){let a=A(e.guardrails),o={stage:`live_outbound`,trust:`untrusted`,profileId:e.id,...vt(a.detect,{canary:t,privateSystem:n}),...e.labels?{labels:e.labels}:{},...r?{givenUrls:r}:{},...i?{ownTools:i}:{}},s=await Fa(a,o);return{policy:a,context:o,gate:await Er(a,o,`live_reply`),held:[],releasedTo:0,withholdVisible:!1,...s?{thoughts:s}:{}}}function Wa(e){let t=e.gate?.carryOut();e.gate=yr(e.policy,e.context,`live_reply`,t),e.held=[],e.releasedTo=0,e.withholdVisible=!1,e.promptLeaks=void 0}function Ga(e,t,n=[]){let r=Tr(`live_outbound`,`untrusted`,t,`block`);return{action:`withhold`,error:new W(`safety`,e),events:[...n,...r?[r]:[]]}}function Ka(e){return e.accumulated().length-e.unreleased().length}function qa(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 Ja(e,t,n,r){if(!n.blocked){let i=n.found&&nt(`live_reply`,n.found);i&&r.push(fr(i)),qa(e,t,Ka(t),r);return}let i=n.hits.filter(Kt);i.length>0&&(e.promptLeaks=i),e.withholdVisible=!0;let a=n.boundary?void 0:Tr(`live_outbound`,`untrusted`,n.hits,`block`);a&&r.push(a)}function Ya(e,t,n){e.withholdVisible||e.held.length===0||Ja(e,t,t.flush(),n)}function Xa(e,t,n,r){let i=t.accumulated().length;e.held.push({event:n,start:i,end:r?i:1/0})}function Za(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 Qa(e,t,n,r){let i=n.text??``;if(!i)return;let a=t.accumulated().length;Za(e,a+i.length),e.held.push({event:n,start:a,end:a+i.length});let o=t.process(i);e.withholdVisible||Ja(e,t,o,r)}function $a(e,t){let n=[],{gate:r}=e;if(!r){let{thoughts:n}=e;return ro(n?t.flatMap(e=>e.type===`thought`?eo(n.push(e.text),e):[e]):t)}let i=!1;for(let a of t){if(je(a)){i||=!!a.text,Qa(e,r,a,n);continue}if(a.type===`media`){Xa(e,r,a,i),e.withholdVisible||qa(e,r,Ka(r),n);continue}Ya(e,r,n),to(a)&&no(e,r,n);let t=a.type===`tool`?void 0:_n(a,e.context,e.policy.detect,`live_reply`);if(t?.stop)return Ga(dn(t.hits),t.hits,n);if(t){let e=nt(`live_reply`,{action:`flag`,hits:t.hits});e&&n.push(fr(e))}a.type===`thought`&&e.thoughts?n.push(...eo(e.thoughts.push(a.text),a)):n.push(a)}return ro(n)}function eo({text:e,hits:t,found:n},r){let i=n&&nt(`thought`,n),a=Tr(`thought`,`untrusted`,t,`redact`);return[...i?[fr(i)]:[],...a?[a]:[],...e?[{...r,text:e}]:[]]}function to(e){return e.type===`done`&&e.stop?.kind===`generation_complete`}function no(e,t,n){let r=t.accumulated().length;e.withholdVisible||r===0||Ka(t)<r||qa(e,t,r,n,!0)}function ro(e){return e.length===0?{action:`idle`}:{action:`emit`,events:e}}function io(e,t,n){let{detect:r,blockedReply:i}=e.policy,a=Ae({text:t.accumulated()},r,{boundary:`live_reply`,...e.withholdVisible?{reportedTo:Ka(t)}:{},scope:mt(e.policy,e.context)}),o=t.accumulated().slice(0,e.releasedTo),s=E(a,e.promptLeaks),c=s&&s!==a.blocked?Tr(`live_outbound`,`untrusted`,s,`block`):void 0,l=[...n,...a.events.map(fr),...c?[c]:[]];if(s){if(i.onBlock===`refuse`){let t=Ye(o,e.context.labels);return{action:`emit`,events:[...l,{type:`text`,text:t}],refused:!0}}return{action:`withhold`,error:new W(`safety`,Cn.egress),events:l}}if(a.rewritten){let e=Hn(o,a.payload.text);return{action:`emit`,events:[...l,{type:`text`,text:e}]}}return qa(e,t,t.accumulated().length,l,!0),ro(l)}function ao(e,t){if(e.held.length===0)return t;let n=Tr(`live_outbound`,`untrusted`,[Ha],`block`);return n?[...t,n]:t}function oo(e,t){let n=[];return Ya(e,t,n),t.accumulated()?io(e,t,n):ro(ao(e,n))}function so(e){let t=e.thoughts?eo(e.thoughts.flush(),{type:`thought`,text:``}):[];if(!e.gate)return ro(t);let n=oo(e,e.gate);return Wa(e),t.length===0?n:n.action===`idle`?{action:`emit`,events:t}:{...n,events:[...t,...n.events??[]]}}function co(e){e.thoughts?.flush(),Wa(e)}var lo=[1e3,2e3,4e3,8e3],uo=5e3,fo=lo.length,po=1e3,mo=new Set([408,429,500,502,503,504,529]),ho=(e,t)=>new Promise((n,r)=>{if(t?.aborted){r(go(t));return}let i=setTimeout(()=>{t?.removeEventListener(`abort`,a),n()},e);function a(){clearTimeout(i),r(go(t))}t?.addEventListener(`abort`,a,{once:!0})});function go(e){return e.reason??new DOMException(`The operation was aborted.`,`AbortError`)}function _o(e){return mo.has(e)}function vo(e){let t=b(e);return t instanceof W&&t.kind===`network`}function yo(e){return lo[Math.min(e,lo.length-1)]}function bo(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*po:Date.parse(r)-t}if(!(i===void 0||Number.isNaN(i)||i<0))return i}function xo(e,t=ho,n=()=>1/0){return async(r,i)=>{let a=0;for(let o=0;;o++){let s=Math.min(uo-a,n()),c;try{let t=await e(r,i);if(!_o(t.status)||(c=bo(t.headers)??yo(o),c>s||o>=fo))return t;await t.body?.cancel()}catch(e){if(c=yo(o),!vo(e)||c>s||o>=fo)throw e}await t(c,i?.signal),a+=c}}}var So=`[DONE]`;function Co(e){if(e&&typeof e==`object`&&!Array.isArray(e))return e}function wo(e,t){let n=e.startsWith(`data:`)?e.slice(5).replace(/^ /,``):e,r={};if(t&&(r.sseEvent=t),n===So)return r.eventType=`sse_done`,r;try{let e=JSON.parse(n),t=Co(e);return t?{...t,...r}:(r.eventType=`sse_unparsed`,r.data=e,r)}catch{return r.eventType=`sse_unparsed`,r.data=n,r}}function To(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(wo(i.join(`
|
|
4
4
|
`),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*Eo(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=To(r);r=o.rest;for(let e of o.payloads)yield e}}finally{i||t.cancel().catch(()=>void 0),t.releaseLock()}}var Do=/key|auth|cookie|secret|token/i;function Oo(e,t){return Do.test(e)?`[redacted]`:t}function ko(e){let t={};for(let[n,r]of new Headers(e).entries())t[n]=Oo(n,r);return t}function Ao(e){return e instanceof Error?{eventType:`http_throw`,name:e.name,message:e.message}:{eventType:`http_throw`,name:`Error`,message:String(e)}}function jo(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 Mo(e,t=fetch,n){return e?async(r,i)=>{e({eventType:`http_request`,method:i?.method??`GET`,url:String(r),headers:ko(i?.headers),...n?{keySlot:n}:{},...jo(i?.body)});try{let n=await t(r,i);return e({eventType:`http_response`,status:n.status,headers:ko(n.headers)}),n.ok||e({eventType:`http_error_body`,body:await n.clone().text()}),n}catch(t){throw e(Ao(t)),t}}:t}function No(e=fetch){return(t,n)=>Sn(e,t,n)}var Po=`key_fallback`,Fo=1e6;function Io(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 Lo(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 Ro(e,t,n){let r=Io(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)+Lo(n.input-a,i.input,i.byModality?.input,n.byModality?.input)+Lo(n.output,i.output,i.byModality?.output,n.byModality?.output))/Fo,estimated:!0}}function zo(e){return(t,n)=>{if([...n.headers.keys()].length)throw new W(`unsupported`,B(`protocol.ws_headers`,{provider:e}));return Promise.resolve(new WebSocket(t,n.protocols))}}var Bo=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789`,Vo=248;function Ho(){let e=``;for(;e.length<24;)for(let t of crypto.getRandomValues(new Uint8Array(24-e.length)))t<Vo&&(e+=Bo[t%62]);return e}function Uo(e){return Ct(e.provider,e.binding)}var Wo=new WeakMap;function Go(e,t){return e&&Object.hasOwn(e,t)?e[t]:void 0}async function Ko(e,t,n,r){let i=n?Go(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 qo(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 W(`auth`,i===void 0?B(`provider.credential_missing`,{slot:t??``}):B(`protocol.key_invalid`,{slot:t??``,provider:e.id}));return a.data}async function Jo(e,t,n){let r=t.authorize??e.provider.definition.authorize;if(!r)return;let i=e.provider.definition.key?await Ko(e.provider,e.vault,n,{apiId:e.binding.apiId,...e.signal?{signal:e.signal}:{}}):void 0,a=qo(e.provider,n,i);if(a===void 0)return;e.onKey?.(n,a);let o=`${t.protocol.id}\u0000${n??``}`,s=Wo.get(e.provider)??new Map;Wo.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 Yo(e){let t=e.length;for(;e[t-1]===`/`;)t--;return e.slice(0,t)}function Xo(e,t,n,r){return e.url?new URL(e.url({path:t,apiId:n,stream:r})):new URL(Yo(e.baseUrl)+(t.startsWith(`/`)?t:`/${t}`))}async function*Zo(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:F(t),...r?{id:r}:{}}}else if(!t)yield await e.json();else if(e.body)for await(let t of Eo(e.body)){if(t.eventType===`sse_done`)return;yield t}}function Qo(e){let t=e.split(/\r?\n/).filter(e=>e.startsWith(`data:`)).map(e=>e.slice(5).trim()).join(`
|
|
5
5
|
`);for(let n of t?[e,t]:[e])try{return JSON.parse(n)}catch{}return e}async function $o(e,t,n){let r=Qo(await n.text()),i=e.error?.({status:n.status,body:r,headers:n.headers})??new W(qe(n.status),B(`protocol.http`,{provider:t,status:n.status}));return Object.assign(i,{status:n.status})}function es(e){return e.builtins.map(e=>e.id)}function ts(e,t,n=[]){let r=t.find(e=>!n.includes(e));if(r!==void 0)throw new W(`unsupported`,B(`protocol.builtin_unwritten`,{protocol:e.id,tool:r}))}async function ns(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 rs(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 is(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 ns(e.data);t.trim()&&s(rs(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:L.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 as(e,t,n,r={sent:!1},i=[]){let a=Uo(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 W(`unsupported`,B(`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){ts(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:Xo(a,u(c.path),s,c.stream),headers:d,protocols:[],body:JSON.stringify(n)};await(await Jo(e,a,t))?.sign(f);let p=xo(Mo(e.tapUpstream&&(t=>e.tapUpstream?.(t)),No(e.fetch??fetch),t),e.wait??ho,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 $o(o,e.provider.id,m);for await(let e of(o.framing??Zo)(m,c.stream))l(e),yield e},async connect(n,c){ts(o,i,c?.wroteTools);let d={transport:`ws`,url:Xo(a,u(void 0),s,!0),headers:new Headers(a.headers),protocols:[]};await(await Jo(e,a,t))?.sign(d);let f=e.openWebSocket??zo(e.provider.id);r.sent=!0;let p=is(await f(d.url.toString(),{headers:d.headers,protocols:d.protocols}),l);return p.send(n),p}}}function os(e,t){return e instanceof W&&e.kind===t}async function*ss(e,t){let{keySlot:n,fallbackKeySlot:r}=xn(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((os(t,`rate_limit`)||os(t,`busy`))&&r&&i!==r&&cs(e,r))e.tapUpstream?.({eventType:Po,from:i??null,keySlot:r,errorKind:t.kind,error:t.message}),i=r,a=!0;else if(os(t,`auth`)&&!o){o=!0;let t=Uo(e);Wo.get(e.provider)?.get(`${t.protocol.id}\u0000${i??``}`)?.signer.invalidate?.()}else throw t}}}function cs(e,t){let n=Go(e.vault,t);return typeof n==`string`?n.trim()!==``:typeof n==`function`||typeof n==`object`&&!!n}function ls(e){if(!(e instanceof W)||e.kind===`cancelled`||e.kind===`config`)throw e;return{type:`error`,errorKind:e.kind,errorInternal:Se(e),...e.copy?{errorCopy:e.copy}:{}}}function us(e){if(e.state===void 0)return e;if(!e.history?.length)throw new W(`request`,B(`protocol.history_needed`));let{state:t,stateHistoryLength:n,...r}=e;return r}function ds(e){let t=new Map,n=e=>{let n=t.get(e);if(n)return n;let r=Ho();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=Ro(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 fs(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=Ro(n,t.model,{input:r,output:i,total:r+i});return a?{...t,usage:{...t.usage,costUsd:a.usd,estimated:!0}}:t}function ps(e){return Uo(e).protocol}function ms(e,t,n){let r=t[n];if(!r)throw new W(`unsupported`,B(`protocol.no_operation`,{protocol:e.id,operation:n}));let i=r;return((...e)=>i.apply(t,e))}async function hs(e,t,n){let r=ps(e);for await(let i of ss(e,i=>(async function*(){let a=r.create(as(e,i,[]));yield await ms(r,a,t)(n)})()))return i;throw new W(`internal`,B(`provider.decision_failed`))}function gs(e){let t=ps(e);return{async*complete(n){let{finish:r}=ds(e),i=[],a={sent:!1},o=ss(e,(r,o)=>{a.sent=!1;let s=t.create(as(e,r,i,a,es(n)));return ms(t,s,`complete`)(o?us(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 ls(e);return}for(let e of i.splice(0))yield{type:`raw`,row:e}},async openSession(n){let{finish:r,wireOf:i}=ds(e),a=[],o;for await(let r of ss(e,(r,i)=>(async function*(){let o=t.create(as(e,r,a,void 0,es(n)));yield await ms(t,o,`openSession`)(i?us(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=>fs(e,await hs(e,`decide`,t)),embed:t=>hs(e,`embed`,t)}}function _s(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 vs(e,t){return t!==void 0&&e>t}var ys=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=_s(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 W(`timeout`,B(`error.timeout`))),V(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 W(`timeout`,B(`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 W(`bad_response`,B(`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 W(`timeout`,B(`error.timeout`))),V(this.signal)}value(e){this.checkDeadline();let t=new TextEncoder().encode(JSON.stringify(e)).byteLength;this.checkDeadline(),this.stepBytes+=t,this.stepEvents++,(vs(t,this.limits.maxEventBytes)||vs(this.stepBytes,this.limits.maxStepBytes)||vs(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),vs(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)=>{V(this.signal);let r=await e(t,n);this.signal.aborted&&(r.close(),V(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(vs(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=_s(r?[this.signal,r]:[this.signal]),a=i.signal;V(a);let o=await e(t,{...n,signal:a}).catch(e=>{throw i.dispose(),e});if(V(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 bs(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{V(a);let t=await s.read();if(V(a),t.done){e.close(),a.removeEventListener(`abort`,u),i.dispose(),s.releaseLock();return}c+=t.value.byteLength,this.wireBytes+=t.value.byteLength,(vs(c,this.limits.maxWireResponseBytes)||vs(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})}}},bs=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++,vs(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)}},xs=a({name:r().min(1),callId:r().min(1),wireCallId:r().min(1).optional(),arguments:t(r(),L),stepId:r().min(1).optional(),stepCallCount:o().int().min(1).optional()}),Ss=It.extend({type:f(`reasoning`)}),Cs=new Set([`text`,`thought`,`structured`,`media`,`grounding`,`citation`,`evidence`,`tokens`,`session`,`tool_draft`,`error`,`custom`]);function ws(e){let t=Rn.parse(e);if(t.kind===`gate`)throw new W(`bad_response`,B(`provider.kernel_gate`));return t}function Ts(e){if(!z(e)||typeof e.type!=`string`)throw new W(`bad_response`,B(`provider.event_invalid`));if(Cs.has(e.type))return wt.parse(e);switch(e.type){case`tool_call`:return{type:`tool_call`,call:xs.parse(e.call)};case`tool_cancel`:return{type:`tool_cancel`,callId:r().min(1).parse(e.callId)};case`reasoning`:return Ss.parse(e);case`raw`:return{type:`raw`,row:Fn.parse(e.row)};case`done`:return{type:`done`,stop:ws(e.stop),interrupted:d().optional().parse(e.interrupted),state:e.state};case`response`:if(!z(e.response))throw new W(`bad_response`,B(`provider.response_identity`));return{type:`response`,response:a({id:r().optional(),model:r().optional()}).parse(e.response)};default:throw new W(`bad_response`,B(`provider.event_type`,{type:e.type}))}}async function Es(e,t){if(V(t),!t)return await e();let n=()=>{},r=new Promise((e,r)=>{n=()=>{try{V(t)}catch(e){r(e)}},t.addEventListener(`abort`,n,{once:!0}),t.aborted&&n()});try{return await Promise.race([Promise.resolve().then(()=>(V(t),e())),r])}finally{t.removeEventListener(`abort`,n)}}function Ds(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 Os(e,t){let n=t(e instanceof Error?e.message:String(e));if(e instanceof DOMException)return new DOMException(n,e.name);if(St(e))return new DOMException(n,`AbortError`);let r=e instanceof Error&&e.cause!==void 0?{cause:Os(e.cause,t)}:{},i=e instanceof W?new W(e.kind,n,{copy:Ds(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 ks(e,t){try{return await e()}catch(e){throw Os(e,t)}}async function*As(e,t,n,r=!1){r||n.resumeOperation();let i;try{for(i=e()[Symbol.asyncIterator]();;){let e=i,a=await Es(()=>e.next(),n.signal);if(a.done)break;let o=Ts(a.value);r&&(o.type!==`session`||o.session.kind===`working`)&&n.startLiveStep(),n.event(o),o.type===`error`?yield{...o,...o.errorCopy?{errorCopy:Ds(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 Os(e,t)}finally{n.close(),i?.return&&Promise.resolve(i.return()).catch(()=>void 0)}}var js=/^(?:authorization|proxy-authorization|cookie|set-cookie|api[_-]?key|x-goog-api-key|secret|token|access[_-]?token|refresh[_-]?token|password)$/i;function Ms(e,t,n,r,i){let a=Object.freeze(yn.parse({...t.limits,...r.limits})),o=new ys(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)),js.test(e)&&typeof t==`string`?`[redacted]`:l(t)])):e},u=e=>String(l(e)),d=xn(e,t).keySlot,f=gs({provider:e,binding:t,profileType:n,limits:a,signal:o.signal,fetch:o.fetch(r.fetch??globalThis.fetch),openWebSocket:o.socket(r.openWebSocket??zo(e.id)),...r.vault?{vault:r.vault}:{},...r.wait?{wait:r.wait}:{},timeLeft:()=>o.timeLeft(),...i.tapUpstream?{tapUpstream:e=>i.tapUpstream?.(Fn.parse(l(e)))}:{},onKey(e,t){d=e,c(t)}});o.stopTimer();let p=async e=>{try{o.resumeOperation();let t=await Es(()=>ks(e,u),o.signal);return o.value(t),t}finally{o.close()}};return{keySlot:()=>d,complete:e=>As(()=>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 Es(()=>ks(()=>f.openSession({...e,signal:o.signal}),u),o.signal).catch(e=>{throw o.close(),e}).finally(()=>o.stopTimer());return{events:()=>As(()=>t.events(),u,o,!0),closeInfo:()=>{let e=t.closeInfo?.();return e&&{...e,...e.error?{error:Os(e.error,u)}:{}}},sendText:e=>(o.startLiveStep(),ks(()=>t.sendText(e),u)),sendAudio:e=>ks(()=>t.sendAudio(e),u),sendVideo:e=>ks(()=>t.sendVideo(e),u),sendContext:e=>ks(()=>t.sendContext(e),u),sendToolResult:e=>(o.startLiveStep(),ks(()=>t.sendToolResult(e),u)),close:e=>(o.stopTimer(),ks(()=>t.close(e),u).finally(()=>o.dispose()))}}}}function Ns(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 Ps(e,t,n){if(e?.history===`stateless`&&(t||n?.length))throw new W(`request`,B(`provider.stateless_history`))}async function Fs(e,t,n,r,i={}){if(!n)return{};let a=Ln.parse(n),o=Wt(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===Ns(e,t,o)?a.keySlot===xn(e,t).keySlot?(i.history===`provider`?r.length>0:a.coveredHistoryLength>r.length||a.coveredHistoryHash!==await En(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 Is(e,t,n,r,i,a={}){if(r===void 0)return;let o=Wt(e,t),s=o.continuation;if(!s)throw new W(`bad_response`,B(`provider.continuation_contract`));return{protocol:o.id,provider:e.id,version:s.version,apiId:t.apiId,...n?{keySlot:n}:{},compatibilityKey:Ns(e,t,o),coveredHistoryLength:i.length,coveredHistoryHash:await En(i),data:L.parse(s.schema.parse(r)),...Object.keys(a).length?{wireCallIds:a}:{}}}function Ls(e,t){return e?.map(e=>{if(!e.reasoning)return e;let{reasoning:n,...r}=e,i=n.filter(e=>Dt(e.origin.protocol,t));return i.length?{...r,reasoning:i}:r})}function Rs(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 zs(e,t,n){let{providerState:r,tapUpstream:i,history:a,...o}=e,s=Rs(Ls(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*Vs(e,t){let n={},r,i=!1,a=[],o=[],s=``,c,l=e[Symbol.asyncIterator](),u=!1;try{for(;;){let e=await Es(()=>l.next(),t);if(e.done){u=!0;break}V(t);let d=e.value;if(r)throw new W(`bad_response`,B(`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 W(`bad_response`,B(`provider.duplicate_call`));d.call.wireCallId&&(n[d.call.callId]=d.call.wireCallId),a.push(Bs(d.call));continue;case`tool_cancel`:throw new W(`bad_response`,B(`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 Hs(e,t,n,r,i,a={},o=[]){let s=Wt(e,t),c=i;return{async*complete(l){let u=c===i&&a.history===`provider`,d=await Fs(e,t,c,u?o:l.history??[],u?a:{});d.warning&&(c=void 0,yield{type:`provider_warning`,warning:d.warning});let f=Ms(e,t,n,r,l),{terminal:p,failed:m,pending:h,reasoning:g,text:_,structured:v,wireCallIds:y}=yield*Vs(f.complete(zs(l,s,d)),l.signal);if(V(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 Is(e,t,f.keySlot(),p.state,[...b,...ht({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 Us=new Map;function Ws(e){return typeof e==`object`&&!!e&&`write`in e&&typeof e.write==`function`}function Gs(e,t){let n=e.trim();if(!n)throw new W(`config`,`registerTraceDestination requires a non-empty id`);if(!Ws(t))throw new W(`config`,`Trace destination '${n}' must be a TraceSink`);Us.set(n,t)}function Ks(e){return Us.get(e)}function qs(e){let t=Ks(e);if(!t)throw new W(`config`,`Trace destination '${e}' is not registered`);return t}async function Js(e,t,n){try{await e.write(await t,{retainForDays:n.retainForDays,rotateAfterMiB:n.rotateAfterMiB})}catch(t){try{e.onError?.(t)}catch{}}}function Ys(e,t,n,r){return Js(e,ai({spans:t,policy:n,...r?{metadata:r}:{}}),n)}function Xs(){return{write:()=>Promise.resolve()}}function Zs(e,t){return!t&&!e.onError?e:{write:(t,n)=>e.write(t,n),onError:e.onError??t}}var Qs=2**32;function $s(e,t){let n=e.spans[0]?.traceId??``;return Number.parseInt(n.slice(-8),16)/Qs<t}function ec(e,t){return t>=1?e:t<=0?Xs():{write:async(n,r)=>{$s(n,t)&&await e.write(n,r)},onError:e.onError}}function tc(e,t){return e===void 0||e===!1?Xs():Zs(typeof e==`string`?qs(e):e,t.onWriteError)}function nc(e){let t={...ri(e.observability),detect:A(e.guardrails).detect};return e.override?{policy:t,sink:Zs(e.override,t.onWriteError)}:t.record?{policy:t,sink:ec(tc(t.writeTo,t),t.sampleRate)}:{policy:t,sink:Xs()}}async function rc({name:e,attributes:t,traceparent:n,links:r,metadata:i,writer:a},o){let s=Lt(e,{kind:`CLIENT`,attributes:t,links:ce(r),...n?{traceparent:n}:{}}),{sink:c,policy:l}=nc(a);try{let e=await o(s.root);return s.root.end({code:`OK`}),e}catch(e){throw kn(s.root,e),e}finally{await Ys(c,s.collect(),l,i)}}var ic={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`},ac={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`},K=class extends W{code;status;constructor(e,t,n,r){super(ic[e],t,r),this.code=e,this.status=n}};function oc(e,t){let n=e.profiles.get(t);if(n.type!==`decision`)throw new W(`request`,`runDecision requires profile.type 'decision' (got '${n.type}' for ${n.id})`);return n}function sc(e){let t=Nr(e.models),n=t?e.models[t]:void 0;if(!t||!n)throw new W(`config`,`Profile ${e.id}: type 'decision' must declare exactly one model`);return[t,n]}function q(e,t,n=0,r=1){if(typeof e!=`number`||!Number.isFinite(e)||e<n||e>r)throw new K(`malformed_response`,`${t} is outside its valid range`);return e}function cc(e,t,n){if(!z(e)||Object.keys(e).length!==t.length||t.some(t=>!Object.hasOwn(e,t)))throw new K(`malformed_response`,`${n} does not match declared labels`);let r=Object.create(null);for(let i of t)r[i]=q(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 K(`malformed_response`,`${n} must sum to one`);return r}function lc(e,t){if(!z(e))throw new K(`malformed_response`,`${t} is invalid`);let n={top:q(e.top,`${t}.top`),bottom:q(e.bottom,`${t}.bottom`),left:q(e.left,`${t}.left`),right:q(e.right,`${t}.right`)};if(n.left>=n.right||n.top>=n.bottom)throw new K(`malformed_response`,`${t} has an edge out of order`);return n}function uc(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 K(`malformed_response`,`${n} is invalid`);return e}function dc(e,t){if(!z(e)||Object.keys(e).length!==Object.keys(t).length)throw new K(`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 K(`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 K(`malformed_response`,`Decision provider returned an undeclared choice for '${r}'`);n[r]={type:`choice`,choice:t.choice,confidence:q(t.confidence,`${r}.confidence`),probabilities:cc(t.probabilities,e,`${r}.probabilities`)}}else if(i.type===`noul`)n[r]={type:`noul`,noul:q(t.noul,`${r}.noul`)};else if(i.type===`box`)n[r]={type:`box`,box:lc(t.box,`${r}.box`),confidence:q(t.confidence,`${r}.confidence`)};else{let e=i.criteria.map((e,t)=>String(t));n[r]={type:`score`,score:q(t.score,`${r}.score`,0,Math.max(0,e.length-1)),confidence:q(t.confidence,`${r}.confidence`),legend:uc(t.legend,e,`${r}.legend`),probabilities:cc(t.probabilities,e,`${r}.probabilities`)}}}return n}function fc(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 pc(e,t){if(!z(t)||!e.trim()||!bc(t.instructions))throw new K(`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 K(`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(bc))throw new K(`invalid_request`,`Decision ${t.type} '${e}' must declare criteria`)}function mc(e,t){if(V(e.signal),e.model!==void 0)throw new K(`invalid_request`,`Decision requests do not select a model; the profile runs its one model`);if(e.state===null||!fc(e.state))throw new K(`invalid_request`,`Decision state must be non-null JSON`);let n;try{n=JSON.stringify(e.state)}catch{throw new K(`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 K(`invalid_request`,`Decision state exceeds ${t.inputs.maxStateBytes} bytes`);if(!z(e.questions)||!fc(e.questions)||Object.keys(e.questions).length===0)throw new K(`invalid_request`,`Decision request must declare at least one question`);for(let[t,n]of Object.entries(e.questions))pc(t,n);e.assets!==void 0&&yc(e.assets);for(let[t,n]of Object.entries(e.questions))gc(t,n,e.state,e.assets)}function hc(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 gc(e,t,n,r){if(!z(t)||t.image===void 0)return;let i=t.image,a=typeof i==`string`&&!r?.[i]?hc(n,i):i;if(t.type!==`box`||typeof a!=`string`||r?.[a]===void 0)throw new K(`invalid_request`,`Decision question '${e}' has an image that is neither a held image nor a state field holding one`)}function _c(e,t){if(e.type!==`box`||e.image===void 0)return e;let{image:n,instructions:r}=e,i=B(`decision.box_image`,{image:t?.[n]?n:`\`${n}\``});return{type:`box`,instructions:typeof r==`string`?`${r} ${i}`:[r,i]}}var vc=/^[A-Za-z0-9+/]+={0,2}$/;function yc(e){if(!z(e)||Object.keys(e).length===0)throw new K(`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||!vc.test(n.data))throw new K(`invalid_request`,`Decision asset '${t}' must be PNG or JPEG bytes as padded base64`)}function bc(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 xc(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 K(`disclosure_blocked`,`Decision disclosure was blocked`)}function Sc(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,...Pn(r),"gen_ai.request.model":n.apiId,"theorem.model.id":t,"theorem.decision.contract":e.decision.contract,"theorem.decision.state":rn(r.state),"theorem.decision.questions":rn(r.questions),...i?{"theorem.decision.assets":rn(Object.fromEntries(Object.entries(i).map(([e,{mimeType:t,data:n}])=>[e,{mimeType:t,bytes:n.length}])))}:{}}}function Cc(e,t){e.set({"gen_ai.response.model":t.model,"theorem.decision.answers":rn(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 wc(e){if(e instanceof K)return e;let t=R(e);return new K(t===`auth`&&z(e)&&e.status===403?`permission`:ac[t],e instanceof W?e.message:B(`provider.decision_failed`),z(e)&&typeof e.status==`number`?e.status:void 0,{cause:e})}function Tc(e){let t=Object.fromEntries(Object.entries(e.questions).map(([t,n])=>[t,_c(n,e.assets)])),n=e.assets?Vt([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 Ec(e,t,[n,r],i,a,o){V(i.signal);let s=e.providers.require(r.provider,r.apiId);await xc(t,n,r.provider,i,a.assets),V(i.signal);try{let e=await Ms(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 K(`malformed_response`,B(`provider.decision_model_missing`));return{...e,answers:dc(e.answers,i.questions)}}catch(e){throw i.signal?.aborted?new K(`cancelled`,B(`provider.decision_ended`)):wc(e)}}async function Dc(e,t,n){let r=oc(e,t.profile);mc(t,r);let i=sc(r),[a,o]=i,s=Tc(t),c=e.providers.get(o.provider),l=c&&gn(c,o,`decision`);return await rc({name:l?`${l} ${o.apiId}`:o.apiId,attributes:Sc(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 Ec(e,r,i,t,s,n);return Cc(a,o),o})}function Oc(e,t){let n=e.profiles.get(t);if(n.type!==`embedding`)throw new W(`request`,`runEmbedding requires profile.type 'embedding' (got '${n.type}' for ${t})`);return n}function kc(e,t){let n=t??e.defaultModel;if(t&&!e.allowModelSelect)throw new W(`request`,`Profile ${e.id} does not allow model selection`);let r=e.models[n];if(!r)throw new W(`request`,`Unknown model '${n}' for ${e.id}`);return[n,r]}var Ac=[`query`,`document`];function jc(e){if(e!==void 0&&!Ac.includes(e))throw new W(`request`,`Embedding task must be 'query' or 'document'`)}function Mc(e){return Array.isArray(e)?e:[e]}function Nc(e){return typeof e==`string`?[{type:`text`,text:e}]:e&&Array.isArray(e.parts)?e.parts:[]}function Pc(e,t,n,r){let i=Sr(e.inputs,r);if(i.maxInputs!==void 0&&n.length>i.maxInputs)throw new W(`request`,`Model '${t}' of ${e.id} takes at most ${i.maxInputs} inputs per request`);let a=[];for(let t of n){let n=Nc(t);if(n.length===0)throw new W(`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 W(`unsupported`,`Profile ${e.id} does not accept text embedding input`)}else r.push(t.type===`media`?{mimeType:t.mimeType,sizeBytes:kr(t.data)}:{mimeType:t.mimeType});a.push(r)}let o=Zn(i,a);if(o.length>0)throw Rr(o)}function Fc(e,t){if(!e.model.trim()||e.embeddings.length!==t)throw new W(`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 W(`bad_response`,`Embedding provider returned invalid vector metadata`);if(e.values.some(e=>!Number.isFinite(e)))throw new W(`bad_response`,`Embedding provider returned a non-finite vector value`);return e});return{...e,embeddings:n}}async function Ic(e,t,n={}){V(t.signal);let r=Oc(e,t.profile),[i,a]=kc(r,t.model),o=Mc(t.input);jc(t.task);let s=e.providers.require(a.provider,a.apiId);Pc(r,i,o,Wt(s,a).embeddingLimits?.(a.apiId));let c=Ms(s,a,`embedding`,n,{...t.signal?{signal:t.signal}:{}}),l=gn(s,a,`embedding`);return await rc({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,...Pn(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()=>Fc(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 J(e,t,n={}){let{span:r,...i}=n,a={type:`hook_failed`,hook:e,...i,errorKind:R(t),errorInternal:Se(t)};return r?.event(`theorem.hook_failed`,{hook:e,...i.stage?{stage:i.stage}:{},error_kind:a.errorKind,reason:a.errorInternal??``}),a}function Lc(e,t,n=!1){let r=n?`tool.execution_uncertain`:`tool.hook_failed`;return{code:`hook_failed`,kind:R(e),message:B(r,{},t)}}function Rc(e){let t=[];return{report(n,r){let i=e();if(!i?.ended){J(n,r,{span:i});return}let a=(e,n={},r)=>{t.push({name:e,timeUnixNano:r??i.nowUnixNano(),attributes:n})};J(n,r,{span:{...i,event:a}})},into(e){return e[0]?.events.push(...t.splice(0)),e}}}function zc(e,t,n,r,i){let a=e.profiles.get(t);if(a.type===`host`)return Bc(e,r);if(a.type===`decision`||a.type===`live`||a.type===`embedding`)throw new W(`unsupported`,B(`provider.turn_profile`));let o=a.models[n??a.defaultModel];if(!o)throw new W(`config`,B(`provider.model_binding_missing`));Ps(a.providerContinuation,i?.providerState,i?.input?.history);let{compaction:s,...c}=o;return{complete:Hs(e.providers.require(o.provider,o.apiId),structuredClone(c),a.type,r,i?.providerState,a.providerContinuation,i?.input?.history).complete,forProfile:(t,n,i)=>zc(e,t,n,r,i)}}function Bc(e,t){return{complete(){throw new W(`unsupported`,B(`provider.host_model`))},forProfile:(n,r,i)=>zc(e,n,r,t,i)}}function Vc(e,t,n,r){return`forProfile`in e&&typeof e.forProfile==`function`?e.forProfile(t,n,r):e}function Hc(e){let t,n=Rc(()=>t?.root);return{open:(n,r)=>(t=Lt(n,{...r?{attributes:r}:{},traceparent:e.traceparent}),t.root),hookFailed:(e,t)=>n.report(e,t),end:()=>{if(t)return e.write(n.into(t.collect()))}}}function Uc(){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(bt(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 Wc(){return Promise.resolve(Uc())}function Gc(e){return e.meter??`history`}function Kc(e){let t=[];for(let n=0;n<e.length;n++)e[n].role===`user`&&!O(e[n])&&t.push(n);return t}async function qc(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 Wc()).messages(t)}async function Jc(e){let t=Gc(e.spec);if(t===`history`)return{meter:t,...await qc(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 Yc(e,t){return e>t.compactAt*t.maxTokens}async function Xc(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 Yc(e.tokens,t)}async function Zc(e,t){if(e.length===0)return{toCompact:[],toRetain:[]};if(t.previousExchanges===0)return{toCompact:[...e],toRetain:[]};let n=Kc(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 Wc(),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 Qc(e){return e.metadata?.compactionSummary===!0}function $c(e){return{type:`text`,text:e}}function el(e,t){let n=t.labels,r=new Map,i=0,a=e=>(e??[]).filter(e=>e.type===`text`||zn(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:[$c(B(`compaction.tool_result`,{tool:i??``,result:a},n))]}),e.length>0&&o.push({role:`user`,parts:[$c(B(`compaction.tool_files`,{tool:i??``},n)),...e]});continue}let i=(t.tool_calls??[]).map(e=>$c(B(`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 tl(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(Qc),...e.toRetain]}:{...i,outcome:`deferred`,failure:t.failure,history:[...e.toCompact,...e.toRetain]}}var nl={[Me.unscannable]:`egress.hint_unscannable`,[Me.providerToolLeak]:`egress.hint_provider_tool_leak`},rl=[qt.canary_leak],il=3,al=120,ol=`detect.`;function sl(e,t,n){let r=nl[e.rule];if(r)return B(r,{},n);let i=e.rule.startsWith(ol)?e.rule.slice(7):e.rule;if(Ht(i))return t.hints?.[i]??B(`detect.hint.${i}`,{},n);let a=t.host?.find(({id:e})=>e===i),o=a?.label??e.label??i;return a?.hint??B(`detect.hint.own`,{label:o},n)}function cl(e){let t=e.flatMap(({rule:e,match:t})=>t&&!rl.includes(e)?[t]:[]);return[...new Set(t)].slice(0,il).map(e=>JSON.stringify(e.length>al?e.slice(0,al):e))}function ll(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=sl(e[0],t,n),i=cl(e);return i.length>0?B(`egress.rejection_found`,{hint:r,matches:i.join(`, `)},n):r});return B(`egress.rejection`,{found:i.join(`
|