@theoremjs/studio 0.3.5-next.901.g4c6ea22 → 0.3.5-next.902.g334d23a
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-DrGIeIK_.js → BottomSheet-DoQyCSv5.js} +1 -1
- package/page/assets/{ConsoleFrame-DsOjQpUH.js → ConsoleFrame-6pxwtmj7.js} +1 -1
- package/page/assets/{DateInput-DgnVu-kI.js → DateInput-B9iV939o.js} +1 -1
- package/page/assets/{MenuBottomSheet-GY06yd5H.js → MenuBottomSheet-Kk5gIkzY.js} +1 -1
- package/page/assets/{RankedBars-B8U3kxSK.js → RankedBars-HSq4wPeA.js} +1 -1
- package/page/assets/{SchemaFields-Cis8JWaR.js → SchemaFields-DhHzB3cY.js} +1 -1
- package/page/assets/{TokenizerBottomSheet-CTvjd7HX.js → TokenizerBottomSheet-CMErW59w.js} +1 -1
- package/page/assets/{ToolResultCharts-Bd3n9LnX.js → ToolResultCharts-BmoE9xfE.js} +1 -1
- package/page/assets/{Toolbar-C1ayeE9N.js → Toolbar-R7By0ClV.js} +1 -1
- package/page/assets/{TraceInspector-3xdQ4UqS.js → TraceInspector-B2-q3kdh.js} +1 -1
- package/page/assets/{TraceOverview-BBndmpzt.js → TraceOverview-DFi4TFKx.js} +1 -1
- package/page/assets/{_virtual_studio-type-sources-iVMrMuhc.js → _virtual_studio-type-sources-DndWNIpu.js} +8 -2
- package/page/assets/{browser-connection-D_lN2asL.js → browser-connection-BSNet_H3.js} +1 -1
- package/page/assets/{browser-engine-BsrddSgm.js → browser-engine-HY1MiOBw.js} +1 -1
- package/page/assets/{browser-transport-DEmPOpCh.js → browser-transport-CqE21ewt.js} +2 -2
- package/page/assets/{compile-sDVAeWRn.js → compile-DTDHCKfi.js} +1 -1
- package/page/assets/{encode-files-kIrEhKfy.js → encode-files-DPDNany5.js} +1 -1
- package/page/assets/{export-agent-Cm5TCs3D.js → export-agent-OANxVkvE.js} +1 -1
- package/page/assets/{getRadiusAndStrokeWidthFromDot-B-uqMFL9.js → getRadiusAndStrokeWidthFromDot-CFpiLWPo.js} +1 -1
- package/page/assets/{guardrail-health-BsoV3UoN.js → guardrail-health-CwTKl0zG.js} +1 -1
- package/page/assets/{guardrail-tester-CSf6QKJ4.js → guardrail-tester-CKlDr0k_.js} +1 -1
- package/page/assets/{index-DeS-oJXP.js → index-OCKUpKmV.js} +10 -10
- package/page/assets/{json-code-BmmHJCk3.js → json-code-D2OkfSza.js} +1 -1
- package/page/assets/{labels-provider-BTXBWLwp.js → labels-provider-26qkmR1c.js} +1 -1
- package/page/assets/{live-messages-fu3eH91T.js → live-messages-Df38_7Lx.js} +1 -1
- package/page/assets/{prompt-row-BBs4REOD.js → prompt-row-DjQm0bw2.js} +1 -1
- package/page/assets/{reader-DZ_YIRM1.js → reader-CR8x2duE.js} +4 -4
- package/page/assets/{registry-CTpu-bdw.js → registry-yn0Ipf-_.js} +1 -1
- package/page/assets/{schema-5LN5ovk9.js → schema-CvmO11hb.js} +1 -1
- package/page/assets/{shaped-data-BPVQeZF7.js → shaped-data-D9qzQU2m.js} +3 -3
- package/page/assets/{stub-BwR5uljZ.js → stub-D6-YFRxO.js} +1 -1
- package/page/assets/{studio-code-pane-B8Fl2VY6.js → studio-code-pane-C_AN-d0W.js} +3 -3
- package/page/assets/{studio-console-DaC0GewJ.js → studio-console-BjDwiYxB.js} +1 -1
- package/page/assets/{studio-decision-DyTHR1MJ.js → studio-decision-NFrI5pe7.js} +1 -1
- package/page/assets/{studio-embedding-DNszq0Hd.js → studio-embedding-lf-ItxLq.js} +1 -1
- package/page/assets/{studio-host-console-CjTWhYKN.js → studio-host-console-BPaTXrnv.js} +2 -2
- package/page/assets/{studio-labels-CeaN-Nln.js → studio-labels-B_l5mKbZ.js} +1 -1
- package/page/assets/{studio-live-BTFzHMaj.js → studio-live-Babh_n6b.js} +1 -1
- package/page/assets/{studio-map-DvZVYO9k.js → studio-map-Ddk7GO_i.js} +1 -1
- package/page/assets/{studio-trace-replay-BDcSfoDI.js → studio-trace-replay-CAW03Aol.js} +1 -1
- package/page/assets/{studio-type-checker-esCrDSll.js → studio-type-checker-CDfrrQ9W.js} +1 -1
- package/page/assets/{tool-schema-kC7sCJbX.js → tool-schema-lNJyGpcM.js} +1 -1
- package/page/assets/{trace-record-BrtFWrPa.js → trace-record-CmhXXllR.js} +1 -1
- package/page/assets/{tree-iTFAG9HK.js → tree-DxJnvWmh.js} +1 -1
- package/page/assets/{turn-client-Ijnv3PVz.js → turn-client-BfkK4BN-.js} +1 -1
- package/page/assets/{types-BONQrLx-.js → types-YRukYg-4.js} +1 -1
- package/page/assets/{use-one-call-02vj6oku.js → use-one-call-KOcgOvF7.js} +1 -1
- package/page/assets/{workspace-Dri6_R-8.js → workspace-LbPd2mMU.js} +1 -1
- package/page/index.html +17 -17
|
@@ -1 +1 @@
|
|
|
1
|
-
import{E as e,d as t,x as n}from"./schemas-D7cgkv3L.js";import{H as r}from"./tool-schema-kC7sCJbX.js";import{At as i,Bi as a,Fa as o,Ii as s,Ja as c,Ta as l,Ti as u,Ut as ee,Vi as te,Wa as ne,Wt as re,Ya as ie,Zi as d,aa as ae,bi as oe,di as f,dn as se,fa as ce,fi as le,fn as p,gn as m,hi as ue,ka as de,mn as h,pa as fe,pn as g,qt as pe,xi as _,zi as me}from"./shaped-data-BPVQeZF7.js";import{c as v}from"./host-patterns-F-KZIzkF.js";import{A as he,C as ge,O as _e,T as ve,_ as y,y as ye}from"./schema-5LN5ovk9.js";import{a as be,n as xe}from"./live-ingress-OuSlQ6q7.js";var Se=2,Ce=4,we=3,Te=/(^|,)(\s*)("?)(?:([=@])|([+-])(?![0-9."]))/gm,Ee=/^[A-Za-z0-9+/]*={0,2}$/,De=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 Oe(e,t){if(t.limitsByMime){let n=m(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 ke(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 Ae(e){let t=0;return e.endsWith(`==`)?t=Se:e.endsWith(`=`)&&(t=1),Math.floor(e.length*we/Ce)-t}function je(e){try{return new TextDecoder(`utf-8`,{fatal:!0}).decode(e)}catch{return new TextDecoder(`latin1`).decode(e)}}function Me(e){return e.replace(Te,(e,...t)=>{let[n,r,i,a,o]=t;return`${n}${r}${i}'${a??``}${o??``}`})}function Ne(e,t,n){let r=je(t);return e===`text/csv`&&(r=Me(r)),new TextEncoder().encode(n.read(r))}function S(e,t){return t?{...e,fileName:t}:e}function Pe(e,t,n){return t.filter(t=>!p(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=Oe(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(...Pe(e.attachments,t,`attachment`)),e.voice&&r.push(...Pe(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 C(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 Re(e,t){let n=C(e);return c(n.key,n.params,t)}function w(e){return new v(`input`,`attachments refused: ${e.map(e=>e.code).join(`, `)}`,{copy:e.map(C)})}function T(e){if(!Ee.test(e))throw new v(`request`,`attachment data must be base64`);return Ae(e)}function E(e){let t={mimeType:e.mimeType,name:e.name};return x(e)||(t.sizeBytes=T(e.data)),t}function ze(e,t,n){if(!Be(t,n))return;let r=ke(e),i=Ie({attachments:g(e,`attachments`),voice:g(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(!De.has(m(n)))return e;let i=Ne(n,ce(r),t);return{...e,data:fe(i)}}function Be(e,t){return(e?.length??0)>0||(t?.length??0)>0}function Ve(e,t,n,r){return ze(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 He(e,t){return e?`${e}.${t}`:t}function P(e,t){t.push({path:e,error:`required field '${e}' is missing`})}async function Ue(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 We(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 Ue(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 We({path:He(n,e),propSchema:s[e],child:u?.[e],isRequired:c.has(e),fields:r,options:i,failures:a,crashes:o})}async function Ge(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 Ke(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 qe(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 Je(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 Ye(e,t,n,r){if(!n.provider?.trim()||!n.apiId?.trim())throw new v(`config`,c(`provider.binding_identity`))}function Xe(e){B(e.id,e.models),Y(e.id,e.observability),Q(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 Ze(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 Qe(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=>`${e.path.join(`.`)}: ${e.message}`).join(`; `)}`)}function $e(e,t,n){if(Qe(e,t,n,re),Ye(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 z(e){return e===void 0?{}:{parallel:e}}function rt(e){return it(e.id,e.tools),Y(e.id,e.observability),{type:`host`,id:e.id,tools:{allow:e.tools.allow,...z(e.tools.parallel)},guardrails:e.guardrails,observability:e.observability,labels:e.labels}}function it(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),Qe(e,t,n,pe),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(!u.includes(i))throw new v(`config`,`Profile ${e} model '${t}' effort '${n}': '${i}' is not a thinking level (${u.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?ae.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(!i(r))throw new v(`config`,`Profile ${e}: turnBehaviour.resumption.${t} may only include ContinueStopKind (${le.join(` | `)}); got '${r}'`)}}function at(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 ot(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 st=Object.entries(oe).filter(([,e])=>e.required===!0).map(([e,t])=>[e,t.profileTypes]).sort(([e],[t])=>e.split(`.`).length-t.split(`.`).length);function ct(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(!_.find(t=>t===e.type))throw new v(`config`,`Profile ${t}: type must be one of ${_.join(`, `)}`)}function lt(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 ut(e){let{id:t,type:n}=e,r=e;for(let[e,i]of st){if(i&&!i.includes(n))continue;let o=a(e),s=ot(r,o.slice(0,-1)),c=o[o.length-1];if(s.some(e=>{if(!K(e))return!1;let t=e[c];return t==null||t===``}))throw new v(`config`,`Profile ${t}: type '${n}' must set ${o.join(`.`)}`)}}function dt(e){let{id:t,type:n}=e;if(n!==`live`&&te(`inputs`).includes(n)&&e.inputs==null)throw new v(`config`,`Profile ${t}: type '${n}' must set inputs`)}function ft(e){let[t]=me(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 pt(e,t){let n=t.turnBehaviour;at(e,n?.resumption)}function mt(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(`, `)}`);gt(t?.blockedReply,n)}var J=[`quota`,`detect`,`blockedReply`,`network`,`taint`],ht=[`onBlock`,`maxRetries`];function gt(e,t){if(e===void 0)return;let n=Object.keys(e).find(e=>!ht.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&&!l.includes(r))throw t(`guardrails.blockedReply.onBlock must be one of ${l.join(`, `)}`);if(i!==void 0&&(!Number.isInteger(i)||i<0))throw t(`guardrails.blockedReply.maxRetries must be a non-negative integer`)}function _t(e){let t=e.guardrails?.detect,n=e.type===`host`?d(`guardrails.detect`,t,de):d(`guardrails.detect`,t);if(n!==void 0)throw new v(`config`,`Profile ${e.id}: ${n}`)}function Y(e,t){try{let n=be(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(o(t),`Profile ${e}: ${n}`,{cause:t})}}function vt(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??``;ge(r,`Profile ${e.id} identity.system`);let i=ve(r,t,e.inputs?.options);if(i)throw new v(`config`,`Profile ${e.id} identity.system: ${i}`)}function X(e){let t=yt(e),[n]=s(e);if(n)throw new v(`config`,`Profile ${e.id}: ${n.path} ${n.message}`);return t}function yt(e){ct(e);for(let t of[`key`,`fallbackKey`,`protocol`,`provider`])if(t in e)throw new v(`config`,c(`provider.profile_configuration`,{profile:e.id,field:t}));ft(e),dt(e),ut(e),lt(e),e.labels&&ie(e.labels,`Profile ${e.id}`);for(let t of ne)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(vt(e),_t(e),e.type===`host`)return rt(e);if(e.type===`decision`)return nt(e);if(e.type===`embedding`)return Xe(e);if(e.type===`transcription`)return Ze(e);B(e.id,e.models),pt(e.id,e),q(e.id,e.guardrails),e.type===`text`&&mt(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},Tt(o.id,o.inputs.attachments?.accept),wt(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,...z(e.tools.parallel)},turnBehaviour:e.turnBehaviour,guardrails:n,observability:r,labels:i},xe(o),Dt(o.id,o.live.contextCompression),Et(o);break;default:throw new v(`config`,`Unknown profile type '${String(e)}'`)}return St(o),bt(o),xt(o),o}function bt(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 xt(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 St(e){if(e.type===`live`)return;let t=e.outputs?.structured;if(!t||typeof t==`string`)return;let n=he(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=_e(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 Ct={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 wt(e,t){for(let[n,{ok:r,rule:i}]of Object.entries(Ct)){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(se(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 Tt(e,t){let n=t?.filter(e=>!p(ue,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 Et(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 Dt(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 Ot(e,t,n,r){let i=`Profile ${t.id} model ${n} compaction`;if(kt(i,r),At(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 kt(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 At(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 jt(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 Mt(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*Nt(e){for(let[t,n]of Object.entries(e.models))for(let e of n.builtInTools??[])yield{modelId:t,id:e}}function Pt(e,t){for(let{modelId:n,id:r}of Nt(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 Ft(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){let n=Ft(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=>Ke(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 Lt(e){let t=h(e)?.context;if(!t)return;let n=f;if(t.from.length===0||t.from.some(e=>!n.includes(e)))throw new v(`config`,`Profile ${e.id}: inputs.context.from must list ${f.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 Q(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 Rt(e,t,n){let r=new Map,i=i=>{let a=X(i),o=n&&a.type!==`host`?{...a,models:Object.fromEntries(Object.entries(a.models).map(([e,t])=>[e,ee(n.require(t.provider,t.apiId),t,a.type)]))}:a;if(jt(e,o),Mt(e,o),o.type!==`host`&&o.type!==`decision`&&o.type!==`embedding`){Pt(e,o),Q(o.id,h(o)),Lt(o),It(t,o);for(let[e,t]of Object.entries(o.models))t.compaction&&Ot(r,o,e,t.compaction)}r.set(o.id,o)};return{register:i,registerMany(e){for(let t of e)i(t)},get(e){let t=r.get(e);if(!t)throw new v(`config`,`Unknown profile '${e}'`);return t},find:e=>r.get(e),has:e=>r.has(e),list:()=>[...r.values()],clear:()=>r.clear()}}function zt(e){let t=e?.trim()??``;if(t.startsWith(`AIza`))return`gemini`;if(t.startsWith(`sk-or-`))return`openrouter`}function Bt(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 Vt=n({data:t(n({id:e().min(1)}))});async function Ht(e,t){let n=Bt(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=Vt.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 Ut=`https://openrouter.ai/api/v1/models`,Wt=`https://openrouter.ai/api/v1/embeddings/models`,Gt=[{id:`gemini-embedding-2-preview`,label:`Gemini Embeddings 2 (preview)`},{id:`gemini-embedding-001`,label:`Gemini Embedding 001`}],Kt=[{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)`}],qt={text:`text`,image:`image`,speech:`speech`,transcription:`transcription`,live:void 0,embedding:void 0},Jt=n({data:t(n({id:e().min(1),name:e().optional(),architecture:n({output_modalities:t(e()).optional()}).optional()}))}),Yt=n({data:t(n({id:e().min(1),name:e().optional()}))}),Xt=n({models:t(n({name:e().min(1),displayName:e().optional(),supportedGenerationMethods:t(e()).optional()})).optional(),nextPageToken:e().optional()}),Zt=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 Qt(e,t,n,r){let i=n?.trim();if(t===`embedding`&&!i)return[...e===`openrouter`?Kt:Gt];if(e===`openrouter`)return await $t(t,i,r);if(!i)throw new v(`auth`,`Choose a key to list Gemini models.`);return await tn(t,i,r)}async function $t(e,t,n){let r={signal:n,headers:{Accept:`application/json`,...t?{Authorization:[`Bearer`,t].join(` `)}:{}}};if(e===`embedding`){let e=Yt.safeParse(await $(`OpenRouter`,Wt,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=qt[e];if(!i)return[];let a=Jt.safeParse(await $(`OpenRouter`,`${Ut}?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 en={live:`bidiGenerateContent`,embedding:`embedContent`};async function tn(e,t,n){let i=en[e]??`generateContent`,a=[],o;for(let e=0;e<Zt;e++){let e=new URL(r);e.searchParams.set(`pageSize`,`1000`),o&&e.searchParams.set(`pageToken`,o);let s=Xt.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 nn(e){return[...new Set([e.key,e.fallbackKey,...Object.values(e.models??{}).flatMap(e=>[e.keySlot,e.fallbackKeySlot])].filter(e=>!!e))]}function rn(e,t){return Object.fromEntries(e.map(e=>[e,Object.hasOwn(t,e)?t[e]:void 0]))}export{Ve as S,Ie as _,nn as a,x as b,X as c,qe as d,R as f,Re as g,O as h,Bt as i,Je as l,L as m,Ht as n,rn as o,I as p,Qt as r,Rt as s,zt as t,Ge as u,w as v,b as x,T as y};
|
|
1
|
+
import{E as e,d as t,x as n}from"./schemas-D7cgkv3L.js";import{H as r}from"./tool-schema-lNJyGpcM.js";import{At as i,Bi as a,Fa as o,Ii as s,Ja as c,Ta as l,Ti as u,Ut as ee,Vi as te,Wa as ne,Wt as re,Ya as ie,Zi as d,aa as ae,bi as oe,di as f,dn as se,fa as ce,fi as le,fn as p,gn as m,hi as ue,ka as de,mn as h,pa as fe,pn as g,qt as pe,xi as _,zi as me}from"./shaped-data-D9qzQU2m.js";import{c as v}from"./host-patterns-F-KZIzkF.js";import{A as he,C as ge,O as _e,T as ve,_ as y,y as ye}from"./schema-CvmO11hb.js";import{a as be,n as xe}from"./live-ingress-OuSlQ6q7.js";var Se=2,Ce=4,we=3,Te=/(^|,)(\s*)("?)(?:([=@])|([+-])(?![0-9."]))/gm,Ee=/^[A-Za-z0-9+/]*={0,2}$/,De=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 Oe(e,t){if(t.limitsByMime){let n=m(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 ke(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 Ae(e){let t=0;return e.endsWith(`==`)?t=Se:e.endsWith(`=`)&&(t=1),Math.floor(e.length*we/Ce)-t}function je(e){try{return new TextDecoder(`utf-8`,{fatal:!0}).decode(e)}catch{return new TextDecoder(`latin1`).decode(e)}}function Me(e){return e.replace(Te,(e,...t)=>{let[n,r,i,a,o]=t;return`${n}${r}${i}'${a??``}${o??``}`})}function Ne(e,t,n){let r=je(t);return e===`text/csv`&&(r=Me(r)),new TextEncoder().encode(n.read(r))}function S(e,t){return t?{...e,fileName:t}:e}function Pe(e,t,n){return t.filter(t=>!p(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=Oe(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(...Pe(e.attachments,t,`attachment`)),e.voice&&r.push(...Pe(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 C(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 Re(e,t){let n=C(e);return c(n.key,n.params,t)}function w(e){return new v(`input`,`attachments refused: ${e.map(e=>e.code).join(`, `)}`,{copy:e.map(C)})}function T(e){if(!Ee.test(e))throw new v(`request`,`attachment data must be base64`);return Ae(e)}function E(e){let t={mimeType:e.mimeType,name:e.name};return x(e)||(t.sizeBytes=T(e.data)),t}function ze(e,t,n){if(!Be(t,n))return;let r=ke(e),i=Ie({attachments:g(e,`attachments`),voice:g(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(!De.has(m(n)))return e;let i=Ne(n,ce(r),t);return{...e,data:fe(i)}}function Be(e,t){return(e?.length??0)>0||(t?.length??0)>0}function Ve(e,t,n,r){return ze(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 He(e,t){return e?`${e}.${t}`:t}function P(e,t){t.push({path:e,error:`required field '${e}' is missing`})}async function Ue(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 We(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 Ue(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 We({path:He(n,e),propSchema:s[e],child:u?.[e],isRequired:c.has(e),fields:r,options:i,failures:a,crashes:o})}async function Ge(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 Ke(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 qe(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 Je(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 Ye(e,t,n,r){if(!n.provider?.trim()||!n.apiId?.trim())throw new v(`config`,c(`provider.binding_identity`))}function Xe(e){B(e.id,e.models),Y(e.id,e.observability),Q(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 Ze(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 Qe(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=>`${e.path.join(`.`)}: ${e.message}`).join(`; `)}`)}function $e(e,t,n){if(Qe(e,t,n,re),Ye(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 z(e){return e===void 0?{}:{parallel:e}}function rt(e){return it(e.id,e.tools),Y(e.id,e.observability),{type:`host`,id:e.id,tools:{allow:e.tools.allow,...z(e.tools.parallel)},guardrails:e.guardrails,observability:e.observability,labels:e.labels}}function it(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),Qe(e,t,n,pe),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(!u.includes(i))throw new v(`config`,`Profile ${e} model '${t}' effort '${n}': '${i}' is not a thinking level (${u.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?ae.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(!i(r))throw new v(`config`,`Profile ${e}: turnBehaviour.resumption.${t} may only include ContinueStopKind (${le.join(` | `)}); got '${r}'`)}}function at(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 ot(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 st=Object.entries(oe).filter(([,e])=>e.required===!0).map(([e,t])=>[e,t.profileTypes]).sort(([e],[t])=>e.split(`.`).length-t.split(`.`).length);function ct(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(!_.find(t=>t===e.type))throw new v(`config`,`Profile ${t}: type must be one of ${_.join(`, `)}`)}function lt(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 ut(e){let{id:t,type:n}=e,r=e;for(let[e,i]of st){if(i&&!i.includes(n))continue;let o=a(e),s=ot(r,o.slice(0,-1)),c=o[o.length-1];if(s.some(e=>{if(!K(e))return!1;let t=e[c];return t==null||t===``}))throw new v(`config`,`Profile ${t}: type '${n}' must set ${o.join(`.`)}`)}}function dt(e){let{id:t,type:n}=e;if(n!==`live`&&te(`inputs`).includes(n)&&e.inputs==null)throw new v(`config`,`Profile ${t}: type '${n}' must set inputs`)}function ft(e){let[t]=me(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 pt(e,t){let n=t.turnBehaviour;at(e,n?.resumption)}function mt(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(`, `)}`);gt(t?.blockedReply,n)}var J=[`quota`,`detect`,`blockedReply`,`network`,`taint`],ht=[`onBlock`,`maxRetries`];function gt(e,t){if(e===void 0)return;let n=Object.keys(e).find(e=>!ht.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&&!l.includes(r))throw t(`guardrails.blockedReply.onBlock must be one of ${l.join(`, `)}`);if(i!==void 0&&(!Number.isInteger(i)||i<0))throw t(`guardrails.blockedReply.maxRetries must be a non-negative integer`)}function _t(e){let t=e.guardrails?.detect,n=e.type===`host`?d(`guardrails.detect`,t,de):d(`guardrails.detect`,t);if(n!==void 0)throw new v(`config`,`Profile ${e.id}: ${n}`)}function Y(e,t){try{let n=be(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(o(t),`Profile ${e}: ${n}`,{cause:t})}}function vt(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??``;ge(r,`Profile ${e.id} identity.system`);let i=ve(r,t,e.inputs?.options);if(i)throw new v(`config`,`Profile ${e.id} identity.system: ${i}`)}function X(e){let t=yt(e),[n]=s(e);if(n)throw new v(`config`,`Profile ${e.id}: ${n.path} ${n.message}`);return t}function yt(e){ct(e);for(let t of[`key`,`fallbackKey`,`protocol`,`provider`])if(t in e)throw new v(`config`,c(`provider.profile_configuration`,{profile:e.id,field:t}));ft(e),dt(e),ut(e),lt(e),e.labels&&ie(e.labels,`Profile ${e.id}`);for(let t of ne)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(vt(e),_t(e),e.type===`host`)return rt(e);if(e.type===`decision`)return nt(e);if(e.type===`embedding`)return Xe(e);if(e.type===`transcription`)return Ze(e);B(e.id,e.models),pt(e.id,e),q(e.id,e.guardrails),e.type===`text`&&mt(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},Tt(o.id,o.inputs.attachments?.accept),wt(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,...z(e.tools.parallel)},turnBehaviour:e.turnBehaviour,guardrails:n,observability:r,labels:i},xe(o),Dt(o.id,o.live.contextCompression),Et(o);break;default:throw new v(`config`,`Unknown profile type '${String(e)}'`)}return St(o),bt(o),xt(o),o}function bt(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 xt(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 St(e){if(e.type===`live`)return;let t=e.outputs?.structured;if(!t||typeof t==`string`)return;let n=he(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=_e(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 Ct={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 wt(e,t){for(let[n,{ok:r,rule:i}]of Object.entries(Ct)){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(se(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 Tt(e,t){let n=t?.filter(e=>!p(ue,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 Et(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 Dt(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 Ot(e,t,n,r){let i=`Profile ${t.id} model ${n} compaction`;if(kt(i,r),At(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 kt(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 At(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 jt(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 Mt(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*Nt(e){for(let[t,n]of Object.entries(e.models))for(let e of n.builtInTools??[])yield{modelId:t,id:e}}function Pt(e,t){for(let{modelId:n,id:r}of Nt(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 Ft(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){let n=Ft(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=>Ke(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 Lt(e){let t=h(e)?.context;if(!t)return;let n=f;if(t.from.length===0||t.from.some(e=>!n.includes(e)))throw new v(`config`,`Profile ${e.id}: inputs.context.from must list ${f.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 Q(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 Rt(e,t,n){let r=new Map,i=i=>{let a=X(i),o=n&&a.type!==`host`?{...a,models:Object.fromEntries(Object.entries(a.models).map(([e,t])=>[e,ee(n.require(t.provider,t.apiId),t,a.type)]))}:a;if(jt(e,o),Mt(e,o),o.type!==`host`&&o.type!==`decision`&&o.type!==`embedding`){Pt(e,o),Q(o.id,h(o)),Lt(o),It(t,o);for(let[e,t]of Object.entries(o.models))t.compaction&&Ot(r,o,e,t.compaction)}r.set(o.id,o)};return{register:i,registerMany(e){for(let t of e)i(t)},get(e){let t=r.get(e);if(!t)throw new v(`config`,`Unknown profile '${e}'`);return t},find:e=>r.get(e),has:e=>r.has(e),list:()=>[...r.values()],clear:()=>r.clear()}}function zt(e){let t=e?.trim()??``;if(t.startsWith(`AIza`))return`gemini`;if(t.startsWith(`sk-or-`))return`openrouter`}function Bt(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 Vt=n({data:t(n({id:e().min(1)}))});async function Ht(e,t){let n=Bt(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=Vt.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 Ut=`https://openrouter.ai/api/v1/models`,Wt=`https://openrouter.ai/api/v1/embeddings/models`,Gt=[{id:`gemini-embedding-2-preview`,label:`Gemini Embeddings 2 (preview)`},{id:`gemini-embedding-001`,label:`Gemini Embedding 001`}],Kt=[{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)`}],qt={text:`text`,image:`image`,speech:`speech`,transcription:`transcription`,live:void 0,embedding:void 0},Jt=n({data:t(n({id:e().min(1),name:e().optional(),architecture:n({output_modalities:t(e()).optional()}).optional()}))}),Yt=n({data:t(n({id:e().min(1),name:e().optional()}))}),Xt=n({models:t(n({name:e().min(1),displayName:e().optional(),supportedGenerationMethods:t(e()).optional()})).optional(),nextPageToken:e().optional()}),Zt=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 Qt(e,t,n,r){let i=n?.trim();if(t===`embedding`&&!i)return[...e===`openrouter`?Kt:Gt];if(e===`openrouter`)return await $t(t,i,r);if(!i)throw new v(`auth`,`Choose a key to list Gemini models.`);return await tn(t,i,r)}async function $t(e,t,n){let r={signal:n,headers:{Accept:`application/json`,...t?{Authorization:[`Bearer`,t].join(` `)}:{}}};if(e===`embedding`){let e=Yt.safeParse(await $(`OpenRouter`,Wt,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=qt[e];if(!i)return[];let a=Jt.safeParse(await $(`OpenRouter`,`${Ut}?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 en={live:`bidiGenerateContent`,embedding:`embedContent`};async function tn(e,t,n){let i=en[e]??`generateContent`,a=[],o;for(let e=0;e<Zt;e++){let e=new URL(r);e.searchParams.set(`pageSize`,`1000`),o&&e.searchParams.set(`pageToken`,o);let s=Xt.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 nn(e){return[...new Set([e.key,e.fallbackKey,...Object.values(e.models??{}).flatMap(e=>[e.keySlot,e.fallbackKeySlot])].filter(e=>!!e))]}function rn(e,t){return Object.fromEntries(e.map(e=>[e,Object.hasOwn(t,e)?t[e]:void 0]))}export{Ve as S,Ie as _,nn as a,x as b,X as c,qe as d,R as f,Re as g,O as h,Bt as i,Je as l,L as m,Ht as n,rn as o,I as p,Qt as r,Rt as s,zt as t,Ge as u,w as v,b as x,T 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-
|
|
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-lNJyGpcM.js";import{$ as y,$n as b,$r as x,Ai as S,An as C,Ar as w,B as T,Ba as ee,Bn as E,Bt as D,Cn as te,Cr as ne,Ct as O,Di as k,Dn as re,Dr as ie,Ea as ae,En as oe,F as se,Fa as A,Fn as ce,Fr as le,Ft as ue,G as j,H as de,Ha as M,Ht as fe,I as N,Ia as P,Ir as pe,It as me,J as he,Ja as F,Jn as ge,Jt as _e,K as ve,Kn as ye,Kt as be,L as xe,La as Se,Lr as Ce,Lt as we,Ma as I,Mn as Te,Mr as Ee,N as De,Na as Oe,Nn as ke,Nr as Ae,Nt as je,Oi as Me,On as Ne,Or as Pe,P as Fe,Pa as Ie,Pn as L,Pr as Le,Q as Re,Qr as R,Qt as ze,R as z,Ra as Be,Sn as Ve,Sr as He,St as Ue,Tn as We,Tr as Ge,Tt as Ke,U as qe,Ua as Je,V as Ye,Va as B,Vi as Xe,Vn as Ze,Vt as Qe,W as $e,Wn as et,X as tt,Xt as nt,Y as rt,Yn as it,Yt as at,Z as ot,Zn as st,Zt as ct,_a as lt,_n as V,_r as ut,_t as dt,ai as ft,an as pt,ar as mt,at as ht,bn as gt,br as _t,bt as vt,ca as yt,cr as bt,ct as xt,di as St,dr as Ct,dt as wt,ea as Tt,ei as Et,er as Dt,et as Ot,fa as kt,ft as At,ga as jt,gr as Mt,gt as Nt,hn as Pt,hr as Ft,ht as It,ia as Lt,ii as Rt,in as zt,jn as Bt,jr as Vt,jt as Ht,kn as Ut,kt as Wt,la as Gt,lr as Kt,lt as qt,ma as Jt,mn as Yt,mr as Xt,mt as Zt,oa as Qt,oi as $t,on as H,or as en,pa as tn,pr as nn,pt as rn,q as U,qn as an,ra as on,ri as sn,rn as cn,sa as ln,si as un,sn as dn,sr as fn,st as pn,tt as mn,un as hn,ut as gn,va as _n,vn,vr as yn,vt as bn,wn as xn,wr as Sn,wt as Cn,xn as wn,xr as Tn,xt as En,yn as Dn,yr as On,yt as kn,z as An,zt as jn}from"./shaped-data-D9qzQU2m.js";import{c as W,t as Mn}from"./host-patterns-F-KZIzkF.js";import{$ as Nn,A as Pn,B as Fn,G as In,H as Ln,J as Rn,K as zn,L as Bn,N as Vn,O as Hn,P as Un,Q as Wn,R as Gn,U as Kn,V as qn,W as Jn,X as Yn,Y as Xn,Z as Zn,a as Qn,at as $n,ct as er,et as tr,i as nr,it as rr,l as ir,lt as G,m as ar,n as or,nt as sr,o as cr,ot as lr,q as ur,r as dr,rt as fr,st as pr,tt as mr,z as hr}from"./reader-CR8x2duE.js";import{a as gr,c as _r,d as vr,f as yr,h as br,l as xr,m as Sr,p as Cr,u as wr,v as Tr,y as Er}from"./browser-connection-BSNet_H3.js";import{D as Dr,M as Or,S as kr,_ as Ar,a as jr,b as Mr,c as Nr,g as Pr,h as Fr,j as Ir,m as Lr,o as Rr,p as zr,r as Br,t as Vr,u as Hr,v as Ur,x as Wr,y as Gr}from"./schema-CvmO11hb.js";import{a as Kr,t as qr}from"./live-ingress-OuSlQ6q7.js";import{t as Jr}from"./trace-record-CmhXXllR.js";import{_ as Yr,a as Xr,c as Zr,d as Qr,f as $r,g as ei,h as ti,i as ni,l as ri,m as ii,o as ai,p as oi,r as si,s as ci,u as li,v as ui,y as di}from"./registry-yn0Ipf-_.js";import{D as fi,E as pi,O as mi,T as hi,_ as gi,c as _i,d as vi,i as yi,l as bi,u as xi,x as Si,y as Ci}from"./turn-client-BfkK4BN-.js";import{n as wi,t as Ti}from"./live-messages-Df38_7Lx.js";import{n as Ei,r as Di}from"./lent-keys-C32ems-I.js";import{Bt as Oi,Ft as ki,Gt as Ai,It as ji,Kt as Mi,Lt as Ni,Mt as Pi,Nt as Fi,Rt as Ii,Wt as Li,qt as Ri,zt as zi}from"./index-OCKUpKmV.js";function Bi(){return{given:new Set,remote:new Map}}var Vi=/[\p{L}\p{N}_.+-]/u,Hi=/[\p{L}\p{N}_-]/u,Ui=/(?:https?:\/\/|www\.)[^\s'"<>)\]]+/gi,Wi=/\b[A-Z]{2}\d{2}[A-Z0-9]{10,30}\b/g,Gi=/[/?#]/;function Ki(e,t){let n=t;for(;n<e.length;){let t=String.fromCodePoint(e.codePointAt(n)??0);if(!Hi.test(t))break;n+=t.length}return n}function qi(e,t){let n=Ki(e,t);if(n===t)return-1;let r=1;for(;e.charAt(n)===`.`;){let t=Ki(e,n+1);if(t===n+1)break;n=t,r+=1}return r>1?n:-1}function Ji(e){let t=e.length;for(;t>0&&(e.charAt(t-1)===`.`||e.charAt(t-1)===`,`);)--t;return e.slice(0,t)}function Yi(e){let t=[],n=e.indexOf(`@`);for(;n>=0;){let r=n;for(;r>0&&Vi.test(e.charAt(r-1));)--r;let i=r<n?qi(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 Xi(e){let t=e.replace(/^https?:\/\//i,``),n=t.search(Gi),r=n<0?t:t.slice(0,n);return Ji(r.slice(r.lastIndexOf(`@`)+1).replace(/:\d*$/,``).toLowerCase()).replace(/^www\./,``)}function Zi(e){let t=Yi(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(Ui)]){let t=Xi(e[0]);t&&a.push({key:`host:${t}`,start:e.index,end:e.index+e[0].length})}for(let e of[...i.matchAll(Wi)])a.push({key:`account:${e[0].toLowerCase()}`,start:e.index,end:e.index+e[0].length});return a}function Qi(e){let t=e.trimStart().charAt(0);if(t===`{`||t===`[`)try{return JSON.parse(e)}catch{return}}var $i=32;function ea(e,t,n=0){if(!(n>$i)){if(typeof e==`string`){let r=Qi(e);r===void 0?t(e):ea(r,t,n+1)}else if(Array.isArray(e))for(let r of e)ea(r,t,n+1);else if(e&&typeof e==`object`)for(let r of Object.values(e))ea(r,t,n+1)}}function ta(e,t=!1){let n=new Set;return ea(e,e=>{let r=e.trim(),i=Zi(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 na(e,t){for(let n of ta(t))e.given.add(n)}function ra(e,t,n){for(let r of t)r.role===`assistant`||r.role===`tool`||n.has(r)||nn(r)||na(e,Gt(r).text)}function ia(e,t,n){na(e,t.system),n.has(t.input)||na(e,Gt(t.input).text),ra(e,t.history??[],n)}function aa(e,t,n){if(!te(n.origin)){na(e,[t.finding,t.data]);return}let r=Qi(t.finding),i=new Set([...r===void 0?ta(t.finding):ta(r,!0),...ta(t.data,!0)]);for(let t of i)e.remote.has(t)||e.remote.set(t,n.tool)}function oa(e,t,n){let r=t.lastIndexOf(`
|
|
3
3
|
`),i=r<0?void 0:Qi(t.slice(r+1));aa(e,i===void 0?{finding:t}:{finding:t.slice(0,r),data:i},n)}function sa(e,t,n,r){if(!e||e.remote.size===0)return{verdict:{action:`allow`}};let i=[...ta(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:_n.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:F(`taint.destination_blocked`,s,r)}}:{verdict:{action:`flag`,hits:o},...c===`confirm`?{confirm:F(`taint.destination_confirm`,s,r)}:{}}}var ca={image:`thought.omitted_image`,link:`thought.omitted_link`,instructions:`thought.omitted_instructions`},la={rule:jt.ungiven_images,severity:`high`},ua={rule:jt.ungiven_links,severity:`high`},da={rule:jt.marker_leak,severity:`high`},fa={rule:jt.prompt_leak,severity:`high`};function pa(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 ma(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 ha=8,ga=16;function _a(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=an({canary:l,labels:o}),d=e=>({...e,...a?{given:a}:{}});function f(e,t){let n=F(ca[e],{},o);return/\s$/.test(t)?n.trimStart():n}let p=n||r?e.carry??``:``,m=``,h,g,_=0,v=0,y,x=[],S=0,C=!1,w=0,T=new Map;function ee(e){return h=s.length>0?$n({detect:s,allow:{ungiven_images:t.images??{},ungiven_links:t.links??{}},skipImages:c,...a?{given:a}:{},...u?{note:u}:{}}):void 0,g=n?Sn(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=Ce(e,_);i=pe(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 Kt(e,d(t.images)))i.push({...n,kind:`image`,hit:la});if(t.links)for(let n of Ct(e,d(t.links),c))i.push({...n,kind:`link`,hit:ua});if(t.markers){let t=[new RegExp(b.source,`gi`),...u?[Dt(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:da})}}if(n)for(let[t,r]of _t(e,n))i.push({start:t,end:r,kind:`instructions`,hit:Jt});if(r)for(let[t,n]of pe(e,r,l))i.push({start:t,end:n,kind:`instructions`,hit:fa});return i}function te(e){return x.find(t=>t.start<e&&e<t.end)}function ne(e,t){let n=p+m,r=``,i=e;for(let a of x)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=Ft;;t*=2){let n=p.length,i=0;for(let e=x.length-1;n>0&&i<t;){let r=x[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(x=x.filter(e=>e.end>n),x.length===0)return;let a={text:``,held:0,pieces:[]},o=n;for(let t of[...x,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||Ce(a.text,a.held)>0)return a}}function k(){let e=O();if(!e)return[];let t=[];if(n)for(let[r,i]of _t(e.text,n))t.push([r,i,Jt]);if(r)for(let[n,i]of pe(e.text,r,l))t.push([n,i,fa]);let i=[];for(let[n,r,a]of t){if(r<=e.held)continue;let t=pa(e,n),o=pa(e,r,!0),s=!1;for(let e=Math.max(t,p.length);e<o&&!s;e++)s=!x.some(t=>t.start<=e&&e<t.end);s&&i.push({start:t,end:o,kind:`instructions`,hit:a})}return i}function re(){return ma([...D(p+m),...k()])}function ie(){return re().filter(({end:e})=>e>p.length)}function ae(e,t=!1){let n=te(e);return n?t?n.end:n.start:e}function oe(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=x.filter(e=>e.end<=p.length),c=``,l=p.length,u=e=>{let t=p.length+c.length-l;for(let n of x)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(ae(e)),C=i?.has(a.rule)??!1;let o=C?n.length:Math.max(l,ae(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,T.set(a.rule,a),l=o,C)break}return y=void 0,a&&!C&&(u(ae(a.start)),y=p.length+c.length),u(n.length),x=s,m=c,S=0,o.length>0}function se(){let e=re()[0],t=e?Math.max(0,ae(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);x=x.filter(e=>e.end<=i),x.push({start:i,end:i+r.length,raw:a}),m=n+r,S=0,e&&T.set(e.hit.rule,e.hit),y=void 0,C=!0}function A(){let e=p+m;return y===void 0?e:e.slice(0,y)}function ce(){for(let e=0;e<ha&&!(w>=ga);e++){let e=new Set(x.map(e=>e.start));if(!oe(!1)){if(y===void 0)break;return}if(C||(x.some(t=>!e.has(t.start))&&w++,!ee(A())))return}se()}function ue(){let e=p.length+m.length,t=h?h.holdFrom():e,i=n?j(n):e,a=r?p.length+le(m,r,l):e,o=Math.min(t,i,a,M()??e,y??e);return ae(o<p.length?o:p.length+Ee(m,o-p.length))}function j(e){let t=Math.max(p.length,S),n=Math.max(0,t-Mt),r=n+He(de(n),e);if(r<t&&t>p.length){let t=Math.max(0,p.length-Mt);r=t+He(de(t),e)}return S=Math.min(r,p.length+m.length-Mt),Math.max(p.length,r)}function de(e){return e<p.length?p.slice(e)+m:m.slice(e-p.length)}function M(){let e=O();if(!e)return;let t=e.text.slice(e.held),i=n?On(t,n,e.text.slice(0,e.held)):t.length,a=r?le(t,r,l):t.length;return pa(e,e.held+Math.min(i,a))}function fe(e){let t={text:e,hits:[...T.values()]};return T=new Map,t}return ee(p),{push(e){if(C||!e||(m+=e,(y!==void 0||E(e)||k().length>0)&&ce(),C))return fe(``);let t=Math.max(0,ue()-p.length),n=m.slice(0,t);return p+=n,m=m.slice(t),fe(n)},flush(){if(!C){for(let e=0;e<ha&&!C&&oe(!0);e++);!C&&m&&(D(p+m).length>0||k().length>0)&&se()}let e=m,t=p+m;p=n||r?Pe(t,n,r):``;let i=p.length-t.length;return x=x.filter(e=>e.start+i>=0).map(e=>({...e,start:e.start+i,end:e.end+i})),m=``,S=0,y=void 0,C=!1,w=0,ee(p),fe(e)},carryOut:()=>p}}function va(...e){let t=e.filter(e=>e!==void 0);return t.length===0?{}:{found:{action:t.reduce((e,t)=>et(e,t.action),`allow`),hits:[...new Map(t.flatMap(({hits:e})=>e).map(e=>[e.rule,e])).values()]}}}function ya(e,t,n,r){let i=()=>rr(`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,...va(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()],...va(n,r?.found,u.found)}},carryOut:()=>e?.carryOut()??``}}var ba={canary_leak:Jt,prompt_leak:fa,marker_leak:da,ungiven_images:la,ungiven_links:ua},xa=[`marker_leak`,`ungiven_images`,`ungiven_links`];function Sa(e,t){let{canary:n,privateSystem:r}=e,i=n?Sn(n):void 0,a=``,o=new Set;return{read(e){let n=Ce(a+e,a.length);a+=e;let s=[];i?.push(e)&&s.push(Jt),r&&pe(a.slice(n),r,t).length>0&&s.push(fa);let c=s.filter(e=>!o.has(e.rule));for(let e of c)o.add(e.rule);return c},reset(){i=n?Sn(n):void 0,a=``,o=new Set}}}function Ca(e,t,n,r){let i=Sa(n,r),a=new Map(Object.entries(ba).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)=>et(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 wa(e,t,n){let{detect:r}=e,i=xa.filter(e=>Ta(r,e)),a=Da(r,t,Ta),o=Da(r,t,(e,t)=>e[t].thought===`flag`),s=i.length>0||Oa(a)||Oa(o),c=Ze(e,t);(s||ce([`thought`],r,c))&&await lr();let l=s?_a({omit:Ea(e),...a,...ka(r),...Aa(t),...n?{carry:n}:{}}):void 0;return ya(l&&Ca(l,r,o,t.canary),r,c,i)}function Ta(e,t){return e[t].thought===`redact`||e[t].thought===`block`}function Ea({detect:e,allow:t}){return{...Ta(e,`marker_leak`)?{markers:!0}:{},...Ta(e,`ungiven_images`)?{images:t.ungiven_images}:{},...Ta(e,`ungiven_links`)?{links:t.ungiven_links}:{},imagesRead:e.ungiven_images.thought!==`ignore`}}function Da(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 Oa(e){return e.canary!==void 0||e.privateSystem!==void 0}function ka(e){let t=new Set(Object.entries(ba).filter(([t])=>e[t].thought===`block`).map(([,e])=>e.rule));return t.size>0?{ends:t}:{}}function Aa({canary:e,givenUrls:t,labels:n}){return{...e?{planted:e}:{},...t?{given:t}:{},...n?{labels:n}:{}}}var ja={rule:`live.untranscribed-audio`,severity:`high`};async function Ma(e,t,n,r,i){let a=V(e.guardrails),o={stage:`live_outbound`,trust:`untrusted`,profileId:e.id,...E(a.detect,{canary:t,privateSystem:n}),...e.labels?{labels:e.labels}:{},...r?{givenUrls:r}:{},...i?{ownTools:i}:{}},s=await wa(a,o);return{policy:a,context:o,gate:await mr(a,o,`live_reply`),held:[],releasedTo:0,withholdVisible:!1,...s?{thoughts:s}:{}}}function Na(e){let t=e.gate?.carryOut();e.gate=sr(e.policy,e.context,`live_reply`,t),e.held=[],e.releasedTo=0,e.withholdVisible=!1,e.promptLeaks=void 0}function Pa(e,t,n=[]){let r=pr(`live_outbound`,`untrusted`,t,`block`);return{action:`withhold`,error:new W(`safety`,e),events:[...n,...r?[r]:[]]}}function Fa(e){return e.accumulated().length-e.unreleased().length}function Ia(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 La(e,t,n,r){if(!n.blocked){let i=n.found&&L(`live_reply`,n.found);i&&r.push(er(i)),Ia(e,t,Fa(t),r);return}let i=n.hits.filter(it);i.length>0&&(e.promptLeaks=i),e.withholdVisible=!0;let a=n.boundary?void 0:pr(`live_outbound`,`untrusted`,n.hits,`block`);a&&r.push(a)}function Ra(e,t,n){e.withholdVisible||e.held.length===0||La(e,t,t.flush(),n)}function za(e,t,n,r){let i=t.accumulated().length;e.held.push({event:n,start:i,end:r?i:1/0})}function Ba(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 Va(e,t,n,r){let i=n.text??``;if(!i)return;let a=t.accumulated().length;Ba(e,a+i.length),e.held.push({event:n,start:a,end:a+i.length});let o=t.process(i);e.withholdVisible||La(e,t,o,r)}function Ha(e,t){let n=[],{gate:r}=e;if(!r){let{thoughts:n}=e;return Ka(n?t.flatMap(e=>e.type===`thought`?Ua(n.push(e.text),e):[e]):t)}let i=!1;for(let a of t){if(Ge(a)){i||=!!a.text,Va(e,r,a,n);continue}if(a.type===`media`){za(e,r,a,i),e.withholdVisible||Ia(e,r,Fa(r),n);continue}Ra(e,r,n),Wa(a)&&Ga(e,r,n);let t=a.type===`tool`?void 0:ge(a,e.context,e.policy.detect,`live_reply`);if(t?.stop)return Pa(st(t.hits),t.hits,n);if(t){let e=L(`live_reply`,{action:`flag`,hits:t.hits});e&&n.push(er(e))}a.type===`thought`&&e.thoughts?n.push(...Ua(e.thoughts.push(a.text),a)):n.push(a)}return Ka(n)}function Ua({text:e,hits:t,found:n},r){let i=n&&L(`thought`,n),a=pr(`thought`,`untrusted`,t,`redact`);return[...i?[er(i)]:[],...a?[a]:[],...e?[{...r,text:e}]:[]]}function Wa(e){return e.type===`done`&&e.stop?.kind===`generation_complete`}function Ga(e,t,n){let r=t.accumulated().length;e.withholdVisible||r===0||Fa(t)<r||Ia(e,t,r,n,!0)}function Ka(e){return e.length===0?{action:`idle`}:{action:`emit`,events:e}}function qa(e,t,n){let{detect:r,blockedReply:i}=e.policy,a=Ne({text:t.accumulated()},r,{boundary:`live_reply`,...e.withholdVisible?{reportedTo:Fa(t)}:{},scope:Ze(e.policy,e.context)}),o=t.accumulated().slice(0,e.releasedTo),s=Bt(a,e.promptLeaks),c=s&&s!==a.blocked?pr(`live_outbound`,`untrusted`,s,`block`):void 0,l=[...n,...a.events.map(er),...c?[c]:[]];if(s){if(i.onBlock===`refuse`){let t=Ut(o,e.context.labels);return{action:`emit`,events:[...l,{type:`text`,text:t}],refused:!0}}return{action:`withhold`,error:new W(`safety`,ye.egress),events:l}}if(a.rewritten){let e=C(o,a.payload.text);return{action:`emit`,events:[...l,{type:`text`,text:e}]}}return Ia(e,t,t.accumulated().length,l,!0),Ka(l)}function Ja(e,t){if(e.held.length===0)return t;let n=pr(`live_outbound`,`untrusted`,[ja],`block`);return n?[...t,n]:t}function Ya(e,t){let n=[];return Ra(e,t,n),t.accumulated()?qa(e,t,n):Ka(Ja(e,n))}function Xa(e){let t=e.thoughts?Ua(e.thoughts.flush(),{type:`thought`,text:``}):[];if(!e.gate)return Ka(t);let n=Ya(e,e.gate);return Na(e),t.length===0?n:n.action===`idle`?{action:`emit`,events:t}:{...n,events:[...t,...n.events??[]]}}function Za(e){e.thoughts?.flush(),Na(e)}var Qa=[1e3,2e3,4e3,8e3],$a=5e3,eo=Qa.length,to=1e3,no=new Set([408,429,500,502,503,504,529]),ro=(e,t)=>new Promise((n,r)=>{if(t?.aborted){r(io(t));return}let i=setTimeout(()=>{t?.removeEventListener(`abort`,a),n()},e);function a(){clearTimeout(i),r(io(t))}t?.addEventListener(`abort`,a,{once:!0})});function io(e){return e.reason??new DOMException(`The operation was aborted.`,`AbortError`)}function ao(e){return no.has(e)}function oo(e){let t=Be(e);return t instanceof W&&t.kind===`network`}function so(e){return Qa[Math.min(e,Qa.length-1)]}function co(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*to:Date.parse(r)-t}if(!(i===void 0||Number.isNaN(i)||i<0))return i}function lo(e,t=ro,n=()=>1/0){return async(r,i)=>{let a=0;for(let o=0;;o++){let s=Math.min($a-a,n()),c;try{let t=await e(r,i);if(!ao(t.status)||(c=co(t.headers)??so(o),c>s||o>=eo))return t;await t.body?.cancel()}catch(e){if(c=so(o),!oo(e)||c>s||o>=eo)throw e}await t(c,i?.signal),a+=c}}}var uo=`[DONE]`;function fo(e){if(e&&typeof e==`object`&&!Array.isArray(e))return e}function po(e,t){let n=e.startsWith(`data:`)?e.slice(5).replace(/^ /,``):e,r={};if(t&&(r.sseEvent=t),n===uo)return r.eventType=`sse_done`,r;try{let e=JSON.parse(n),t=fo(e);return t?{...t,...r}:(r.eventType=`sse_unparsed`,r.data=e,r)}catch{return r.eventType=`sse_unparsed`,r.data=n,r}}function mo(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(po(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*ho(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=mo(r);r=o.rest;for(let e of o.payloads)yield e}}finally{i||t.cancel().catch(()=>void 0),t.releaseLock()}}var go=/key|auth|cookie|secret|token/i;function _o(e,t){return go.test(e)?`[redacted]`:t}function vo(e){let t={};for(let[n,r]of new Headers(e).entries())t[n]=_o(n,r);return t}function yo(e){return e instanceof Error?{eventType:`http_throw`,name:e.name,message:e.message}:{eventType:`http_throw`,name:`Error`,message:String(e)}}function bo(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 xo(e,t=fetch,n){return e?async(r,i)=>{e({eventType:`http_request`,method:i?.method??`GET`,url:String(r),headers:vo(i?.headers),...n?{keySlot:n}:{},...bo(i?.body)});try{let n=await t(r,i);return e({eventType:`http_response`,status:n.status,headers:vo(n.headers)}),n.ok||e({eventType:`http_error_body`,body:await n.clone().text()}),n}catch(t){throw e(yo(t)),t}}:t}function So(e=fetch){return(t,n)=>ee(e,t,n)}var Co=`key_fallback`,wo=1e6;function To(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 Eo(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 Do(e,t,n){let r=To(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)+Eo(n.input-a,i.input,i.byModality?.input,n.byModality?.input)+Eo(n.output,i.output,i.byModality?.output,n.byModality?.output))/wo,estimated:!0}}function Oo(e){return(t,n)=>{if([...n.headers.keys()].length)throw new W(`unsupported`,F(`protocol.ws_headers`,{provider:e}));return Promise.resolve(new WebSocket(t,n.protocols))}}var ko=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789`,Ao=248;function jo(){let e=``;for(;e.length<24;)for(let t of crypto.getRandomValues(new Uint8Array(24-e.length)))t<Ao&&(e+=ko[t%62]);return e}function Mo(e){return fe(e.provider,e.binding)}var No=new WeakMap;function Po(e,t){return e&&Object.hasOwn(e,t)?e[t]:void 0}async function Fo(e,t,n,r){let i=n?Po(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 Io(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?F(`provider.credential_missing`,{slot:t??``}):F(`protocol.key_invalid`,{slot:t??``,provider:e.id}));return a.data}async function Lo(e,t,n){let r=t.authorize??e.provider.definition.authorize;if(!r)return;let i=e.provider.definition.key?await Fo(e.provider,e.vault,n,{apiId:e.binding.apiId,...e.signal?{signal:e.signal}:{}}):void 0,a=Io(e.provider,n,i);if(a===void 0)return;e.onKey?.(n,a);let o=`${t.protocol.id}\u0000${n??``}`,s=No.get(e.provider)??new Map;No.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 Ro(e){let t=e.length;for(;e[t-1]===`/`;)t--;return e.slice(0,t)}function zo(e,t,n,r){return e.url?new URL(e.url({path:t,apiId:n,stream:r})):new URL(Ro(e.baseUrl)+(t.startsWith(`/`)?t:`/${t}`))}async function*Bo(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:tn(t),...r?{id:r}:{}}}else if(!t)yield await e.json();else if(e.body)for await(let t of ho(e.body)){if(t.eventType===`sse_done`)return;yield t}}function Vo(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 Ho(e,t,n){let r=Vo(await n.text()),i=e.error?.({status:n.status,body:r,headers:n.headers})??new W(Se(n.status),F(`protocol.http`,{provider:t,status:n.status}));return Object.assign(i,{status:n.status})}function Uo(e){return e.builtins.map(e=>e.id)}function Wo(e,t,n=[]){let r=t.find(e=>!n.includes(e));if(r!==void 0)throw new W(`unsupported`,F(`protocol.builtin_unwritten`,{protocol:e.id,tool:r}))}async function Go(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 Ko(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 qo(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 Go(e.data);t.trim()&&s(Ko(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:ln.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 Jo(e,t,n,r={sent:!1},i=[]){let a=Mo(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`,F(`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){Wo(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:zo(a,u(c.path),s,c.stream),headers:d,protocols:[],body:JSON.stringify(n)};await(await Lo(e,a,t))?.sign(f);let p=lo(xo(e.tapUpstream&&(t=>e.tapUpstream?.(t)),So(e.fetch??fetch),t),e.wait??ro,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 Ho(o,e.provider.id,m);for await(let e of(o.framing??Bo)(m,c.stream))l(e),yield e},async connect(n,c){Wo(o,i,c?.wroteTools);let d={transport:`ws`,url:zo(a,u(void 0),s,!0),headers:new Headers(a.headers),protocols:[]};await(await Lo(e,a,t))?.sign(d);let f=e.openWebSocket??Oo(e.provider.id);r.sent=!0;let p=qo(await f(d.url.toString(),{headers:d.headers,protocols:d.protocols}),l);return p.send(n),p}}}function Yo(e,t){return e instanceof W&&e.kind===t}async function*Xo(e,t){let{keySlot:n,fallbackKeySlot:r}=be(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((Yo(t,`rate_limit`)||Yo(t,`busy`))&&r&&i!==r&&Zo(e,r))e.tapUpstream?.({eventType:Co,from:i??null,keySlot:r,errorKind:t.kind,error:t.message}),i=r,a=!0;else if(Yo(t,`auth`)&&!o){o=!0;let t=Mo(e);No.get(e.provider)?.get(`${t.protocol.id}\u0000${i??``}`)?.signer.invalidate?.()}else throw t}}}function Zo(e,t){let n=Po(e.vault,t);return typeof n==`string`?n.trim()!==``:typeof n==`function`||typeof n==`object`&&!!n}function Qo(e){if(!(e instanceof W)||e.kind===`cancelled`||e.kind===`config`)throw e;return{type:`error`,errorKind:e.kind,errorInternal:Oe(e),...e.copy?{errorCopy:e.copy}:{}}}function $o(e){if(e.state===void 0)return e;if(!e.history?.length)throw new W(`request`,F(`protocol.history_needed`));let{state:t,stateHistoryLength:n,...r}=e;return r}function es(e){let t=new Map,n=e=>{let n=t.get(e);if(n)return n;let r=jo();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=Do(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 ts(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=Do(n,t.model,{input:r,output:i,total:r+i});return a?{...t,usage:{...t.usage,costUsd:a.usd,estimated:!0}}:t}function ns(e){return Mo(e).protocol}function rs(e,t,n){let r=t[n];if(!r)throw new W(`unsupported`,F(`protocol.no_operation`,{protocol:e.id,operation:n}));let i=r;return((...e)=>i.apply(t,e))}async function is(e,t,n){let r=ns(e);for await(let i of Xo(e,i=>(async function*(){let a=r.create(Jo(e,i,[]));yield await rs(r,a,t)(n)})()))return i;throw new W(`internal`,F(`provider.decision_failed`))}function as(e){let t=ns(e);return{async*complete(n){let{finish:r}=es(e),i=[],a={sent:!1},o=Xo(e,(r,o)=>{a.sent=!1;let s=t.create(Jo(e,r,i,a,Uo(n)));return rs(t,s,`complete`)(o?$o(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 Qo(e);return}for(let e of i.splice(0))yield{type:`raw`,row:e}},async openSession(n){let{finish:r,wireOf:i}=es(e),a=[],o;for await(let r of Xo(e,(r,i)=>(async function*(){let o=t.create(Jo(e,r,a,void 0,Uo(n)));yield await rs(t,o,`openSession`)(i?$o(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=>ts(e,await is(e,`decide`,t)),embed:t=>is(e,`embed`,t)}}function os(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 ss(e,t){return t!==void 0&&e>t}var cs=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=os(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`,F(`error.timeout`))),B(this.signal)),this.startTimer(e)}timeLeft(){let e=this.timerDeadline??this.deadline;return e===void 0?1/0:e-performance.now()}startTimer(e){this.stopTimer(),this.timerDeadline=performance.now()+e,this.timer=setTimeout(()=>this.controller.abort(new W(`timeout`,F(`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`,F(`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`,F(`error.timeout`))),B(this.signal)}value(e){this.checkDeadline();let t=new TextEncoder().encode(JSON.stringify(e)).byteLength;this.checkDeadline(),this.stepBytes+=t,this.stepEvents++,(ss(t,this.limits.maxEventBytes)||ss(this.stepBytes,this.limits.maxStepBytes)||ss(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),ss(this.calls.size,this.limits.maxPendingToolCalls)&&this.fail()}resetStep(){this.stepBytes=0,this.stepEvents=0,this.calls.clear(),this.wireBytes=0,this.stopTimer()}socket(e){return async(t,n)=>{B(this.signal);let r=await e(t,n);this.signal.aborted&&(r.close(),B(this.signal));let i=()=>r.close();return this.signal.addEventListener(`abort`,i,{once:!0}),r.addEventListener(`close`,()=>this.signal.removeEventListener(`abort`,i),{once:!0}),r.addEventListener(`message`,e=>{let t=e.data;if(ss(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=os(r?[this.signal,r]:[this.signal]),a=i.signal;B(a);let o=await e(t,{...n,signal:a}).catch(e=>{throw i.dispose(),e});if(B(a),!o.body)return i.dispose(),o;let s=o.body.getReader(),c=0,l=this.limits.maxWireRecordBytes!==void 0&&o.headers.get(`content-type`)?.includes(`text/event-stream`)?new ls(this):void 0,u=()=>{s.cancel(a.reason).catch(()=>void 0)};a.addEventListener(`abort`,u,{once:!0});let d=new ReadableStream({pull:async e=>{try{B(a);let t=await s.read();if(B(a),t.done){e.close(),a.removeEventListener(`abort`,u),i.dispose(),s.releaseLock();return}c+=t.value.byteLength,this.wireBytes+=t.value.byteLength,(ss(c,this.limits.maxWireResponseBytes)||ss(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})}}},ls=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++,ss(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)}},us=a({name:r().min(1),callId:r().min(1),wireCallId:r().min(1).optional(),arguments:t(r(),ln),stepId:r().min(1).optional(),stepCallCount:o().int().min(1).optional()}),ds=Et.extend({type:f(`reasoning`)}),fs=new Set([`text`,`thought`,`structured`,`media`,`grounding`,`citation`,`evidence`,`tokens`,`session`,`tool_draft`,`error`,`custom`]);function ps(e){let t=$t.parse(e);if(t.kind===`gate`)throw new W(`bad_response`,F(`provider.kernel_gate`));return t}function ms(e){if(!H(e)||typeof e.type!=`string`)throw new W(`bad_response`,F(`provider.event_invalid`));if(fs.has(e.type))return Rt.parse(e);switch(e.type){case`tool_call`:return{type:`tool_call`,call:us.parse(e.call)};case`tool_cancel`:return{type:`tool_cancel`,callId:r().min(1).parse(e.callId)};case`reasoning`:return ds.parse(e);case`raw`:return{type:`raw`,row:Qt.parse(e.row)};case`done`:return{type:`done`,stop:ps(e.stop),interrupted:d().optional().parse(e.interrupted),state:e.state};case`response`:if(!H(e.response))throw new W(`bad_response`,F(`provider.response_identity`));return{type:`response`,response:a({id:r().optional(),model:r().optional()}).parse(e.response)};default:throw new W(`bad_response`,F(`provider.event_type`,{type:e.type}))}}async function hs(e,t){if(B(t),!t)return await e();let n=()=>{},r=new Promise((e,r)=>{n=()=>{try{B(t)}catch(e){r(e)}},t.addEventListener(`abort`,n,{once:!0}),t.aborted&&n()});try{return await Promise.race([Promise.resolve().then(()=>(B(t),e())),r])}finally{t.removeEventListener(`abort`,n)}}function gs(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 _s(e,t){let n=t(e instanceof Error?e.message:String(e));if(e instanceof DOMException)return new DOMException(n,e.name);if(P(e))return new DOMException(n,`AbortError`);let r=e instanceof Error&&e.cause!==void 0?{cause:_s(e.cause,t)}:{},i=e instanceof W?new W(e.kind,n,{copy:gs(e.copy,t),...r}):e instanceof TypeError?TypeError(n,r):Error(n,r);return H(e)&&typeof e.status==`number`&&Object.assign(i,{status:e.status}),i}async function vs(e,t){try{return await e()}catch(e){throw _s(e,t)}}async function*ys(e,t,n,r=!1){r||n.resumeOperation();let i;try{for(i=e()[Symbol.asyncIterator]();;){let e=i,a=await hs(()=>e.next(),n.signal);if(a.done)break;let o=ms(a.value);r&&(o.type!==`session`||o.session.kind===`working`)&&n.startLiveStep(),n.event(o),o.type===`error`?yield{...o,...o.errorCopy?{errorCopy:gs(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 _s(e,t)}finally{n.close(),i?.return&&Promise.resolve(i.return()).catch(()=>void 0)}}var bs=/^(?:authorization|proxy-authorization|cookie|set-cookie|api[_-]?key|x-goog-api-key|secret|token|access[_-]?token|refresh[_-]?token|password)$/i;function xs(e,t,n,r,i){let a=Object.freeze(ze.parse({...t.limits,...r.limits})),o=new cs(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)),bs.test(e)&&typeof t==`string`?`[redacted]`:l(t)])):e},u=e=>String(l(e)),d=be(e,t).keySlot,f=as({provider:e,binding:t,profileType:n,limits:a,signal:o.signal,fetch:o.fetch(r.fetch??globalThis.fetch),openWebSocket:o.socket(r.openWebSocket??Oo(e.id)),...r.vault?{vault:r.vault}:{},...r.wait?{wait:r.wait}:{},timeLeft:()=>o.timeLeft(),...i.tapUpstream?{tapUpstream:e=>i.tapUpstream?.(Qt.parse(l(e)))}:{},onKey(e,t){d=e,c(t)}});o.stopTimer();let p=async e=>{try{o.resumeOperation();let t=await hs(()=>vs(e,u),o.signal);return o.value(t),t}finally{o.close()}};return{keySlot:()=>d,complete:e=>ys(()=>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 hs(()=>vs(()=>f.openSession({...e,signal:o.signal}),u),o.signal).catch(e=>{throw o.close(),e}).finally(()=>o.stopTimer());return{events:()=>ys(()=>t.events(),u,o,!0),closeInfo:()=>{let e=t.closeInfo?.();return e&&{...e,...e.error?{error:_s(e.error,u)}:{}}},sendText:e=>(o.startLiveStep(),vs(()=>t.sendText(e),u)),sendAudio:e=>vs(()=>t.sendAudio(e),u),sendVideo:e=>vs(()=>t.sendVideo(e),u),sendContext:e=>vs(()=>t.sendContext(e),u),sendToolResult:e=>(o.startLiveStep(),vs(()=>t.sendToolResult(e),u)),close:e=>(o.stopTimer(),vs(()=>t.close(e),u).finally(()=>o.dispose()))}}}}function Ss(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 Cs(e,t,n){if(e?.history===`stateless`&&(t||n?.length))throw new W(`request`,F(`provider.stateless_history`))}async function ws(e,t,n,r,i={}){if(!n)return{};let a=Lt.parse(n),o=at(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===Ss(e,t,o)?a.keySlot===be(e,t).keySlot?(i.history===`provider`?r.length>0:a.coveredHistoryLength>r.length||a.coveredHistoryHash!==await on(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 Ts(e,t,n,r,i,a={}){if(r===void 0)return;let o=at(e,t),s=o.continuation;if(!s)throw new W(`bad_response`,F(`provider.continuation_contract`));return{protocol:o.id,provider:e.id,version:s.version,apiId:t.apiId,...n?{keySlot:n}:{},compatibilityKey:Ss(e,t,o),coveredHistoryLength:i.length,coveredHistoryHash:await on(i),data:ln.parse(s.schema.parse(r)),...Object.keys(a).length?{wireCallIds:a}:{}}}function Es(e,t){return e?.map(e=>{if(!e.reasoning)return e;let{reasoning:n,...r}=e,i=n.filter(e=>nt(e.origin.protocol,t));return i.length?{...r,reasoning:i}:r})}function Ds(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 Os(e,t,n){let{providerState:r,tapUpstream:i,history:a,...o}=e,s=Ds(Es(a,t),n.wireCallIds);return{...o,...s?{history:s}:{},...n.state===void 0?{}:{state:n.state,stateHistoryLength:n.covered}}}function ks(e){let{wireCallId:t,...n}=e;return n}async function*As(e,t){let n={},r,i=!1,a=[],o=[],s=``,c,l=e[Symbol.asyncIterator](),u=!1;try{for(;;){let e=await hs(()=>l.next(),t);if(e.done){u=!0;break}B(t);let d=e.value;if(r)throw new W(`bad_response`,F(`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`,F(`provider.duplicate_call`));d.call.wireCallId&&(n[d.call.callId]=d.call.wireCallId),a.push(ks(d.call));continue;case`tool_cancel`:throw new W(`bad_response`,F(`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 js(e,t,n,r,i,a={},o=[]){let s=at(e,t),c=i;return{async*complete(l){let u=c===i&&a.history===`provider`,d=await ws(e,t,c,u?o:l.history??[],u?a:{});d.warning&&(c=void 0,yield{type:`provider_warning`,warning:d.warning});let f=xs(e,t,n,r,l),{terminal:p,failed:m,pending:h,reasoning:g,text:_,structured:v,wireCallIds:y}=yield*As(f.complete(Os(l,s,d)),l.signal);if(B(l.signal),!p){yield{type:`done`,stop:{kind:m?`provider_error`:`stream_incomplete`}};return}if(m||p.interrupted||p.stop.kind!==`tool`&&p.stop.kind!==`completed`){yield{type:`done`,stop:p.stop};return}let b=[...l.history??[]];l.input.length&&b.push(l.input.every(e=>e.type===`text`)?{role:`user`,content:l.input.map(e=>e.type===`text`?e.text:``).join(``)}:{role:`user`,parts:l.input});let x=await Ts(e,t,f.keySlot(),p.state,[...b,...Qe({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 Ms=new Map;function Ns(e){return typeof e==`object`&&!!e&&`write`in e&&typeof e.write==`function`}function Ps(e,t){let n=e.trim();if(!n)throw new W(`config`,`registerTraceDestination requires a non-empty id`);if(!Ns(t))throw new W(`config`,`Trace destination '${n}' must be a TraceSink`);Ms.set(n,t)}function Fs(e){return Ms.get(e)}function Is(e){let t=Fs(e);if(!t)throw new W(`config`,`Trace destination '${e}' is not registered`);return t}async function Ls(e,t,n){try{await e.write(await t,{retainForDays:n.retainForDays,rotateAfterMiB:n.rotateAfterMiB})}catch(t){try{e.onError?.(t)}catch{}}}function Rs(e,t,n,r){return Ls(e,Jr({spans:t,policy:n,...r?{metadata:r}:{}}),n)}function zs(){return{write:()=>Promise.resolve()}}function Bs(e,t){return!t&&!e.onError?e:{write:(t,n)=>e.write(t,n),onError:e.onError??t}}var Vs=2**32;function Hs(e,t){let n=e.spans[0]?.traceId??``;return Number.parseInt(n.slice(-8),16)/Vs<t}function Us(e,t){return t>=1?e:t<=0?zs():{write:async(n,r)=>{Hs(n,t)&&await e.write(n,r)},onError:e.onError}}function Ws(e,t){return e===void 0||e===!1?zs():Bs(typeof e==`string`?Is(e):e,t.onWriteError)}function Gs(e){let t={...Kr(e.observability),detect:V(e.guardrails).detect};return e.override?{policy:t,sink:Bs(e.override,t.onWriteError)}:t.record?{policy:t,sink:Us(Ws(t.writeTo,t),t.sampleRate)}:{policy:t,sink:zs()}}async function Ks({name:e,attributes:t,traceparent:n,links:r,metadata:i,writer:a},o){let s=cn(e,{kind:`CLIENT`,attributes:t,links:dt(r),...n?{traceparent:n}:{}}),{sink:c,policy:l}=Gs(a);try{let e=await o(s.root);return s.root.end({code:`OK`}),e}catch(e){throw qt(s.root,e),e}finally{await Rs(c,s.collect(),l,i)}}var qs={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`},Js={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(qs[e],t,r),this.code=e,this.status=n}};function Ys(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 Xs(e){let t=br(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 Zs(e,t,n){if(!H(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 Qs(e,t){if(!H(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 $s(e,t,n){if(!H(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 ec(e,t){if(!H(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(!H(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:Zs(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:Qs(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:$s(t.legend,e,`${r}.legend`),probabilities:Zs(t.probabilities,e,`${r}.probabilities`)}}}return n}function tc(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 nc(e,t){if(!H(t)||!e.trim()||!lc(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):!H(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(lc))throw new K(`invalid_request`,`Decision ${t.type} '${e}' must declare criteria`)}function rc(e,t){if(B(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||!tc(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(!H(e.questions)||!tc(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))nc(t,n);e.assets!==void 0&&cc(e.assets);for(let[t,n]of Object.entries(e.questions))ac(t,n,e.state,e.assets)}function ic(e,t){let n=e;for(let e of t.split(`.`)){if(!H(n)&&!Array.isArray(n))return;n=Array.isArray(n)?n[Number(e)]:n[e]}return n}function ac(e,t,n,r){if(!H(t)||t.image===void 0)return;let i=t.image,a=typeof i==`string`&&!r?.[i]?ic(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 oc(e,t){if(e.type!==`box`||e.image===void 0)return e;let{image:n,instructions:r}=e,i=F(`decision.box_image`,{image:t?.[n]?n:`\`${n}\``});return{type:`box`,instructions:typeof r==`string`?`${r} ${i}`:[r,i]}}var sc=/^[A-Za-z0-9+/]+={0,2}$/;function cc(e){if(!H(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()||!H(n)||n.mimeType!==`image/png`&&n.mimeType!==`image/jpeg`||typeof n.data!=`string`||n.data.length%4!=0||!sc.test(n.data))throw new K(`invalid_request`,`Decision asset '${t}' must be PNG or JPEG bytes as padded base64`)}function lc(e){let t=[e];for(;t.length;){let e=t.pop();if(typeof e==`string`){if(!e.trim())return!1;continue}if(!H(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 uc(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 dc(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,...It(r),"gen_ai.request.model":n.apiId,"theorem.model.id":t,"theorem.decision.contract":e.decision.contract,"theorem.decision.state":pt(r.state),"theorem.decision.questions":pt(r.questions),...i?{"theorem.decision.assets":pt(Object.fromEntries(Object.entries(i).map(([e,{mimeType:t,data:n}])=>[e,{mimeType:t,bytes:n.length}])))}:{}}}function fc(e,t){e.set({"gen_ai.response.model":t.model,"theorem.decision.answers":pt(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 pc(e){if(e instanceof K)return e;let t=A(e);return new K(t===`auth`&&H(e)&&e.status===403?`permission`:Js[t],e instanceof W?e.message:F(`provider.decision_failed`),H(e)&&typeof e.status==`number`?e.status:void 0,{cause:e})}function mc(e){let t=Object.fromEntries(Object.entries(e.questions).map(([t,n])=>[t,oc(n,e.assets)])),n=e.assets?pn([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 hc(e,t,[n,r],i,a,o){B(i.signal);let s=e.providers.require(r.provider,r.apiId);await uc(t,n,r.provider,i,a.assets),B(i.signal);try{let e=await xs(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`,F(`provider.decision_model_missing`));return{...e,answers:ec(e.answers,i.questions)}}catch(e){throw i.signal?.aborted?new K(`cancelled`,F(`provider.decision_ended`)):pc(e)}}async function gc(e,t,n){let r=Ys(e,t.profile);rc(t,r);let i=Xs(r),[a,o]=i,s=mc(t),c=e.providers.get(o.provider),l=c&&_e(c,o,`decision`);return await Ks({name:l?`${l} ${o.apiId}`:o.apiId,attributes:dc(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 hc(e,r,i,t,s,n);return fc(a,o),o})}function _c(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 vc(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 yc=[`query`,`document`];function bc(e){if(e!==void 0&&!yc.includes(e))throw new W(`request`,`Embedding task must be 'query' or 'document'`)}function xc(e){return Array.isArray(e)?e:[e]}function Sc(e){return typeof e==`string`?[{type:`text`,text:e}]:e&&Array.isArray(e.parts)?e.parts:[]}function Cc(e,t,n,r){let i=ur(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=Sc(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:Er(t.data)}:{mimeType:t.mimeType});a.push(r)}let o=zn(i,a);if(o.length>0)throw Tr(o)}function wc(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 Tc(e,t,n={}){B(t.signal);let r=_c(e,t.profile),[i,a]=vc(r,t.model),o=xc(t.input);bc(t.task);let s=e.providers.require(a.provider,a.apiId);Cc(r,i,o,at(s,a).embeddingLimits?.(a.apiId));let c=xs(s,a,`embedding`,n,{...t.signal?{signal:t.signal}:{}}),l=_e(s,a,`embedding`);return await Ks({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,...It(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()=>wc(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:A(t),errorInternal:Oe(t)};return r?.event(`theorem.hook_failed`,{hook:e,...i.stage?{stage:i.stage}:{},error_kind:a.errorKind,reason:a.errorInternal??``}),a}function Ec(e,t,n=!1){let r=n?`tool.execution_uncertain`:`tool.hook_failed`;return{code:`hook_failed`,kind:A(e),message:F(r,{},t)}}function Dc(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 Oc(e,t,n,r,i){let a=e.profiles.get(t);if(a.type===`host`)return kc(e,r);if(a.type===`decision`||a.type===`live`||a.type===`embedding`)throw new W(`unsupported`,F(`provider.turn_profile`));let o=a.models[n??a.defaultModel];if(!o)throw new W(`config`,F(`provider.model_binding_missing`));Cs(a.providerContinuation,i?.providerState,i?.input?.history);let{compaction:s,...c}=o;return{complete:js(e.providers.require(o.provider,o.apiId),structuredClone(c),a.type,r,i?.providerState,a.providerContinuation,i?.input?.history).complete,forProfile:(t,n,i)=>Oc(e,t,n,r,i)}}function kc(e,t){return{complete(){throw new W(`unsupported`,F(`provider.host_model`))},forProfile:(n,r,i)=>Oc(e,n,r,t,i)}}function Ac(e,t,n,r){return`forProfile`in e&&typeof e.forProfile==`function`?e.forProfile(t,n,r):e}function jc(e){let t,n=Dc(()=>t?.root);return{open:(n,r)=>(t=cn(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 Mc(){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(D(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 Nc(){return Promise.resolve(Mc())}function Pc(e){return e.meter??`history`}function Fc(e){let t=[];for(let n=0;n<e.length;n++)e[n].role===`user`&&t.push(n);return t}async function Ic(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 Nc()).messages(t)}async function Lc(e){let t=Pc(e.spec);if(t===`history`)return{meter:t,...await Ic(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 Rc(e,t){return e>t.compactAt*t.maxTokens}async function zc(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 Rc(e.tokens,t)}async function Bc(e,t){if(e.length===0)return{toCompact:[],toRetain:[]};if(t.previousExchanges===0)return{toCompact:[...e],toRetain:[]};let n=Fc(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 Nc(),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 Vc(e){return e.metadata?.compactionSummary===!0}function Hc(e){return{type:`text`,text:e}}function Uc(e,t){let n=t.labels,r=new Map,i=0,a=e=>(e??[]).filter(e=>e.type===`text`||hn(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:[Hc(F(`compaction.tool_result`,{tool:i??``,result:a},n))]}),e.length>0&&o.push({role:`user`,parts:[Hc(F(`compaction.tool_files`,{tool:i??``},n)),...e]});continue}let i=(t.tool_calls??[]).map(e=>Hc(F(`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 Wc(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(Vc),...e.toRetain]}:{...i,outcome:`deferred`,failure:t.failure,history:[...e.toCompact,...e.toRetain]}}var Gc={[lt.unscannable]:`egress.hint_unscannable`,[lt.providerToolLeak]:`egress.hint_provider_tool_leak`},Kc=[jt.canary_leak],qc=3,Jc=120,Yc=`detect.`;function Xc(e,t,n){let r=Gc[e.rule];if(r)return F(r,{},n);let i=e.rule.startsWith(Yc)?e.rule.slice(7):e.rule;if(Tt(i))return t.hints?.[i]??F(`detect.hint.${i}`,{},n);let a=t.host?.find(({id:e})=>e===i),o=a?.label??e.label??i;return a?.hint??F(`detect.hint.own`,{label:o},n)}function Zc(e){let t=e.flatMap(({rule:e,match:t})=>t&&!Kc.includes(e)?[t]:[]);return[...new Set(t)].slice(0,qc).map(e=>JSON.stringify(e.length>Jc?e.slice(0,Jc):e))}function Qc(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=Xc(e[0],t,n),i=Zc(e);return i.length>0?F(`egress.rejection_found`,{hint:r,matches:i.join(`, `)},n):r});return F(`egress.rejection`,{found:i.join(`
|