@theoremjs/studio 0.3.4-next.403.g5de27f3 → 0.3.4-next.407.gd93ec2c
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/browser-engine.d.ts +1 -1
- package/browser-engine.js +1 -1
- package/browser-transport.d.ts +12 -0
- package/browser-transport.js +26 -7
- package/browser.d.ts +1 -1
- package/browser.js +1 -1
- package/mod.d.ts +2 -1
- package/mod.js +2 -1
- package/package.json +4 -4
- package/page/assets/{Banner-CLcFr8r9.js → Banner-B1Vat7i_.js} +2 -2
- package/page/assets/{ContextMenu-CArbXxnu.js → ContextMenu-BreVLY9J.js} +2 -2
- package/page/assets/{ToolResultCharts-DG0GfEe-.js → ToolResultCharts-BV2tbzow.js} +1 -1
- package/page/assets/{TraceInspector-DlcrrHNa.js → TraceInspector-B8NufbVX.js} +1 -1
- package/page/assets/{TraceOverview-BRgK49q4.js → TraceOverview-DoQOfiAe.js} +2 -2
- package/page/assets/{browser-engine-yDBh7tWN.js → browser-engine-BvsLwtiv.js} +6 -6
- package/page/assets/browser-transport-DxpDmXGb.js +47 -0
- package/page/assets/{export-agent-DuPZHGrj.js → export-agent-D2Vo-OSL.js} +3 -3
- package/page/assets/{guardrail-tester-xtRSrTXh.js → guardrail-tester-CuqamClw.js} +2 -2
- package/page/assets/{index-BVTCzZhh.js → index-C3mDKoGG.js} +69 -69
- package/page/assets/{live-messages-CaI0Oqem.js → live-messages-BZGmMo_v.js} +1 -1
- package/page/assets/{reader-CaGeZoFz.js → reader-paEmSrWc.js} +4 -4
- package/page/assets/{studio-code-pane-_XzNjN6P.js → studio-code-pane-B9bG0xzf.js} +1 -1
- package/page/assets/{studio-console-Da8ZVuKx.js → studio-console-1qIWsDtV.js} +3 -3
- package/page/assets/studio-decision-BdJR3HSN.js +1 -0
- package/page/assets/{studio-embedding-BaWl7liT.js → studio-embedding-CFzitRLj.js} +1 -1
- package/page/assets/studio-host-console-BzpDE2TK.js +2 -0
- package/page/assets/{studio-live-ON74y8sM.js → studio-live-BucphGSr.js} +2 -2
- package/page/assets/{studio-map-W8XbAypV.js → studio-map-BfUMbnZK.js} +1 -1
- package/page/assets/studio-trace-replay-C5cBxYG_.js +2 -0
- package/page/assets/turn-client-BZUECwPn.js +2 -0
- package/page/assets/{use-one-call-BD3tlw64.js → use-one-call-BVmuHLSm.js} +1 -1
- package/page/index.html +6 -6
- package/replay.d.ts +97 -0
- package/replay.js +387 -0
- package/server/draft-handler.js +2 -1
- package/transport.d.ts +5 -1
- package/transport.js +7 -2
- package/ui/inspector-context.d.ts +1 -1
- package/ui/lib/send-when-ready.d.ts +7 -0
- package/ui/lib/send-when-ready.js +14 -0
- package/ui/studio-connection.d.ts +1 -1
- package/ui/studio-runner.d.ts +4 -1
- package/ui/studio-runner.js +3 -2
- package/ui/studio-screen.js +111 -11
- package/ui/studio-trace-replay.d.ts +23 -0
- package/ui/studio-trace-replay.js +216 -0
- package/page/assets/browser-transport-B0GPqGzb.js +0 -47
- package/page/assets/studio-decision-CHaFsz_1.js +0 -1
- package/page/assets/studio-host-console-BuPmNkLs.js +0 -2
- package/page/assets/turn-client-BBi2anJM.js +0 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
import{E as e,g as t,l as n,o as r,p as i,v as a,w as o,x as s,y as c}from"./schemas-BQ9Jydzb.js";import{Fn as l,On as u,Rn as d,xr as f}from"./tool-schema-CgpwKFX7.js";import{A as p,
|
|
1
|
+
import{E as e,g as t,l as n,o as r,p as i,v as a,w as o,x as s,y as c}from"./schemas-BQ9Jydzb.js";import{Fn as l,On as u,Rn as d,xr as f}from"./tool-schema-CgpwKFX7.js";import{A as p,C as m,j as h}from"./reader-paEmSrWc.js";import{n as g}from"./trace-schema-9CdEyG6Q.js";import{C as _}from"./turn-client-BZUECwPn.js";var v=c({type:t(`open`),history:n(d).optional(),slots:s(o(),o()).optional(),context:e().optional(),resume:c({providerState:f,awayMs:a().nonnegative()}).optional(),host:s(o(),e()).optional()}),y=i(`type`,[c({type:t(`audio`),data:o()}),c({type:t(`video`),data:o(),mimeType:o()}),c({type:t(`text`),text:o()}),c({type:t(`context`),context:e()}),c({type:t(`executeTool`),callId:o().min(1),operationId:o().min(1).max(256),decision:r(_).optional(),input:e().optional(),secret:o().optional(),output:e().optional(),grantId:o().min(1).optional(),unanswered:t(!0).optional()})]),b={ready:c({type:t(`ready`),profile:o().optional(),sessionId:o().optional()}),events:c({type:t(`events`),events:n(e())}),trace:c({type:t(`trace`),record:g}),error:c({type:t(`error`)}).and(m),executeToolResult:i(`status`,[c({type:t(`executeToolResult`),callId:o().min(1),operationId:o().min(1).max(256),status:t(`dispatched`),grantId:o().min(1),arguments:s(o(),e())}),c({type:t(`executeToolResult`),callId:o(),status:t(`settled`),operationId:o().min(1).max(256)}),c({type:t(`executeToolResult`),callId:o(),status:t(`gated`),operationId:o().min(1).max(256),gate:l}),c({type:t(`executeToolResult`),callId:o(),status:t(`refused`),operationId:o().min(1).max(256),body:m})])};function x(e){let t=p(b,e);return t.type===`events`?{type:`events`,events:t.events.map(e=>h(u,e))}:t}export{v as n,x as r,y as t};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import{t as e}from"./preload-helper-DpV6A1kQ.js";import{C as t,E as n,O as r,T as i,b as a,d as o,f as s,g as c,l,m as u,o as d,p as f,s as p,u as m,v as h,w as g,x as _,y as v}from"./schemas-BQ9Jydzb.js";import{$n as y,An as b,Ar as x,Bn as S,Br as ee,Dr as C,Er as w,Fr as T,G as E,Gn as D,Hn as O,Ht as k,Jn as te,Kt as ne,Ln as re,Lr as ie,Lt as ae,Mn as oe,Mr as se,Nn as ce,On as le,Pn as ue,Qt as de,Rn as fe,Sr as pe,Tr as me,Un as he,Vr as ge,Wn as A,Xn as _e,Yn as ve,Zn as ye,Zt as be,_r as xe,cn as Se,dn as j,dr as Ce,en as we,er as Te,fn as Ee,gr as De,ir as Oe,kn as ke,ln as M,mn as Ae,nr as je,pn as Me,qt as Ne,rr as Pe,s as Fe,sr as Ie,tr as Le,un as Re,vr as ze,vt as Be,zr as Ve,zt as He}from"./tool-schema-CgpwKFX7.js";import{c as N}from"./host-patterns-C9RMP16Q.js";import{An as Ue,B as We,Bt as Ge,En as Ke,Et as qe,F as Je,Gt as Ye,Ht as Xe,I as Ze,It as Qe,Lt as $e,M as et,Mn as P,Mt as tt,N as nt,Nn as rt,O as it,On as at,P as ot,Pt as st,Q as ct,Qt as lt,Rt as ut,Sn as dt,St as ft,Ut as pt,Vt as mt,W as ht,Wt as gt,X as _t,bt as vt,et as yt,fn as bt,ft as xt,gn as St,it as Ct,j as wt,jt as Tt,k as Et,mn as Dt,mt as F,nn as Ot,nt as kt,pn as At,qt as jt,rn as Mt,rt as Nt,tt as Pt,ut as Ft,wn as It,wt as Lt,xn as Rt,zt}from"./shaped-data-0GUF7Al3.js";import{a as Bt,n as Vt}from"./live-ingress-lDUGPwth.js";import{n as Ht,t as Ut}from"./trace-schema-9CdEyG6Q.js";import{n as Wt}from"./stub-DpBSP8Ld.js";function I(e){return{type:`guardrail`,guardrail:e}}function Gt(e,t,n,r=`redact`,i){if(n.length!==0)return I({stage:e,trust:t,action:r,hits:n,...i?{provenance:i}:{}})}function Kt(e,t){return e.type===`guardrail`?{...e,guardrail:St(e.guardrail,t)}:e}var qt=65536;function L(e){let t=e.classStarts.length,n=new Uint16Array(qt);for(let r=0;r<t;r++)n.fill(r,e.classStarts[r],e.classStarts[r+1]??qt);let r=e.charsets.map(e=>{let n=new Uint8Array(t);for(let t of e)n[t]=1;return n}),i=e.nodes.length,a=new Int32Array(i),o=new Uint8Array(i),s=[];return e.nodes.forEach((e,t)=>{a[t]=e[0],o[t]=e[1],s.push(Int32Array.from(e.slice(2)))}),{classOf:n,has:r,pattern:a,final:o,edges:s,initials:e.initials,leads:e.leads,size:i}}var Jt,R,Yt;async function Xt(){if(Jt)return;let{FORWARD_AUTOMATON:t,REVERSED_AUTOMATON:n}=await e(async()=>{let{FORWARD_AUTOMATON:e,REVERSED_AUTOMATON:t}=await import(`./egress-automata-B5ZGE1mT.js`);return{FORWARD_AUTOMATON:e,REVERSED_AUTOMATON:t}},[]);Jt={forward:t,reversed:n}}function Zt(){if(!Jt)throw Error(`A stream was opened before loadEgressAutomata() finished.`);return Jt}var z;function Qt(e){let t=String.fromCharCode(e).toUpperCase();if(t.length!==1)return e;let n=t.charCodeAt(0);return e>=128&&n<128?e:n}function $t(e){if(!z){z=new Map;for(let e=0;e<qt;e++){let t=Qt(e),n=z.get(t);n?n.push(e):z.set(t,[e])}}return z.get(Qt(e))??[e]}function en(e){let t=[0];for(let n of e)t.at(-1)!==n&&t.push(n),n+1<qt&&t.push(n+1);return t}var B=new Map;function tn(e){let t=B.get(e);if(t)return t;let n=Array.from({length:e.length},(t,n)=>$t(e.charCodeAt(n))),r=en([...new Set(n.flat())].sort((e,t)=>e-t)),i=e=>r.indexOf(e),a=L({classStarts:r,charsets:n.map(e=>e.map(i)),initials:[0],leads:[-1],nodes:[...n.map((e,t)=>[0,0,t+1,t]),[0,1]]});return B.set(e,a),a}function nn(e){let t=JSON.stringify(e),n=B.get(t);if(n)return n;let r=[...new Set(e.flatMap(e=>Array.from(e,e=>e.charCodeAt(0))))];r.sort((e,t)=>e-t);let i=en(r),a=r.map(e=>[i.indexOf(e)]),o=[],s=L({classStarts:i,charsets:a,initials:e.map((e,t)=>{let n=o.length;for(let n=0;n<e.length;n++)o.push([t,0,o.length+1,r.indexOf(e.charCodeAt(n))]);return o.push([t,1]),n}),leads:e.map(()=>-1),nodes:o});return B.set(t,s),s}function rn(e,t){let n=e.has[0]?.length??0,r=Array.from({length:n},()=>[]);for(let i of t){let t=e.edges[e.initials[i]];for(let i=0;i<t.length;i+=2){let a=e.has[t[i+1]];for(let e=0;e<n;e++)a[e]&&r[e]?.push(t[i])}}return r.map(e=>Int32Array.from(e))}function an(e,t){e.text+=t,e.fresh+=t}function on(e){return e.text.length-e.fresh.length}function V(e,t){let n=on(e);return t>=n?e.fresh.charCodeAt(t-n):e.text.charCodeAt(t)}function sn(e,t,n=e.text.length){let r=on(e);return t>=r?e.fresh.slice(t-r,n-r):e.text.slice(t,n)}function cn(e){let t={text:``,fresh:``,rawAt:e=>e,update(){t.text=e.text,t.fresh=e.fresh}};return t}function ln(e,t){let n={text:``,fresh:``,rawAt:e.rawAt,update(){n.fresh=``,an(n,t(sn(e,n.text.length)))}};return n}var un=/\w/,dn=Math.max(...ut.map(e=>e.length));function fn(e){return e.length<=dn+1&&/^[A-Za-z]*$/.test(e)}function pn(e){let t=0,n,r=!1,i=[],a=(e,t,n)=>{an(o,e);for(let r=0;r<e.length;r++)i.push(t+Math.min(r,n-1))},o={text:``,fresh:``,rawAt:r=>e.rawAt(r<i.length?i[r]:t-(n?.length??0)),update(){o.fresh=``;for(let i=e.text.length;t<i;t++){let i=String.fromCharCode(V(e,t)),o=un.test(i);o&&!r&&(n=``),r=o,o?n===void 0?a(i,t,1):n+=i:(n!==void 0&&a(Xe(n),t-n.length,n.length),n=void 0,a(i,t,1))}n!==void 0&&!fn(n)&&(a(n,t-n.length,n.length),n=void 0)}};return o}function mn(e){let t={text:``,fresh:``,from:[],rawAt:n=>n<t.from.length?t.from[n]:e(),update(){}};return t}function H(e,t,n){an(e,t);for(let r=0;r<t.length;r++)e.from.push(n)}var hn=55296,gn=56319,_n=/[A-Za-z]/,vn=56320,yn=57343;function bn(e){let t=0,n=``,r=[],i=``,a=[],o=!1,s=-1,c=mn(()=>Math.min(t,r[0]??t,a[0]??t,s<0?t:s));function l(e,t){s>=0&&(_n.test(e)||H(c,`\\`,s),s=-1),e===`\\`?s=t:H(c,e,t)}function u(e,t){if(pt(e)&&(o||i)){i+=e;for(let n=0;n<e.length;n++)a.push(t)}else{if(i){if(!_n.test(e))for(let e=0;e<i.length;e++)l(i[e],a[e]);i=``,a=[]}for(let n=0;n<e.length;n++)l(e[n],t);o=_n.test(e)&&e.length===1}}function d(){let e=0;for(;e<n.length;){let t=n.charCodeAt(e),i=t>=hn&&t<=gn;if(i&&e+1>=n.length)break;let a=n.charCodeAt(e+1),o=i&&a>=vn&&a<=yn?2:1;u(n.slice(e,e+o),r[e]),e+=o}n=n.slice(e),r=r.slice(e)}return c.update=()=>{c.fresh=``;let i=e.text.length;for(;t<i;){let a=V(e,t),o=a>=hn&&a<=gn;if(o&&t+1>=i)break;let s=V(e,t+1),c=o&&s>=vn&&s<=yn?2:1,l=gt(sn(e,t,t+c));n+=l;for(let e=0;e<l.length;e++)r.push(t);t+=c}d()},c}var xn=/[0-9A-Fa-f]/;function Sn(e){let t=0,n=-1,r=mn(()=>n<0?t:n);r.update=()=>{r.fresh=``;let a=e.text.length;for(;t<a;){let a=String.fromCharCode(V(e,t));if(n<0){a===`%`?n=t:(H(r,a,t),t++);continue}let o=(t-n)%3;if(o===0?a===`%`:xn.test(a))t++;else{i(t-o);for(let n=t-o;n<t;n++)H(r,String.fromCharCode(V(e,n)),n)}}};function i(t){t>n&&H(r,zt(sn(e,n,t)),n),n=-1}return r}var Cn=new Set([`injection`,`base64`,`hex`,`spaced`,`pipe`]),wn=new Map($e.map(({pattern:e,hit:t})=>[e,t])),Tn=new Map(Pt.flatMap(({pattern:e,hit:t})=>t?[[e,t]]:[]));function U(e){return{rule:Rt(e),severity:`high`,detector:e}}var En=U(`injection`),Dn=U(`marker_leak`),On=U(`tool_leak`);function kn({kind:e,group:t}){if(Cn.has(e))return En;switch(e){case`sensitive`:case`card`:return t===void 0?void 0:U(t);case`boundary`:return Dn;case`image`:return U(`ungiven_images`);default:return U(`ungiven_links`)}}function An(e,t,n){if(e===`card`)return{hit:kt};if(e===`image`||e===`link`){let r=(e===`image`?Nt:Ct).indexOf(t),i=n[e][r];return`find`in i?{find:i.find}:{hit:i.test}}let r=wn.get(t)??Tn.get(t);return r?{hit:r}:{}}function jn(e,{given:t,allow:n,skipImages:r}){let i=e=>({...e,...t?{given:t}:{}}),a={image:Ft(i(n?.ungiven_images)),link:xt(i(n?.ungiven_links),r??e.includes(`ungiven_images`))},o=[];return ct.forEach((t,n)=>{let r=kn(t);r?.detector&&e.includes(r.detector)&&o.push({...r,id:n,regex:new RegExp(t.pattern.source,t.pattern.flags),...An(t.kind,t.pattern,a)})}),o}function Mn(){let e=[];return ct.forEach(({kind:t,pattern:n},r)=>{if(t!==`injection`)return;let i=wn.get(n);e.push({...En,id:r,regex:new RegExp(n.source,n.flags),...i?{hit:i}:{}})}),e}function Nn(){return Ye.map((e,t)=>({...En,id:t,regex:new RegExp(e.source,e.flags)}))}function Pn(e,t,n){let r=rn(t,n.map(e=>e.id)),i=new Int32Array(t.initials.length).fill(-1);n.forEach((e,t)=>{i[e.id]=t});let a=new Int32Array(t.size),o=new Int32Array(t.size),s=new Int32Array(t.size),c=new Int32Array(t.size),l=0,u=new Int32Array(t.size),d=new Int32Array(t.size),f=0,p=0,m=new Uint8Array(n.length),h=new Uint8Array(n.length),g=new Int32Array(n.length),_=new Int32Array(n.length),v=new Uint8Array(n.length),y=Uint8Array.from(n,e=>+!!e.find),b=new Int32Array(n.length).fill(-1),x=new Int32Array(n.length).fill(-1),S=Int32Array.from(n,e=>t.leads[e.id]??-1),ee=[...new Set(S)].filter(e=>e>=0),C=n.flatMap((e,t)=>S[t]<0?[]:[t]),w=new Int32Array(t.has.length).fill(-1);function T(){let{text:n,fresh:h}=e,g=on(e),{classOf:_,has:v,edges:C,final:T,pattern:E}=t;for(;p<n.length;p++){let e=_[p>=g?h.charCodeAt(p-g):n.charCodeAt(p)];f++;let t=0,D=(e,n)=>{if(d[e]===f){let t=u[e];n<c[t]&&(c[t]=n)}else d[e]=f,u[e]=t,s[t]=e,c[t]=n,t++,T[e]&&(m[i[E[e]]]=1)};for(let t=0;t<l;t++){let n=C[a[t]],r=o[t];for(let t=0;t<n.length;t+=2)v[n[t+1]][e]&&D(n[t],r)}let O=r[e];for(let e=0;e<O.length;e++){let t=O[e],n=i[E[t]],r=S[n],a=r<0?-1:w[r],o=a<0?p:a;D(t,o),y[n]&&(x[n]=p,b[n]<0&&(b[n]=o))}for(let t of ee)v[t][e]?w[t]<0&&(w[t]=p):w[t]=-1;[a,s]=[s,a],[o,c]=[c,o],l=t}}function E(){let n=e.text.length;_.fill(n),v.fill(0);let r=n;for(let e=0;e<l;e++){let n=a[e],s=i[t.pattern[n]],c=o[e];c<_[s]&&(_[s]=c),t.final[n]&&(v[s]=1),c<r&&(r=c)}for(let e of C){let t=w[S[e]];t<0||(t<_[e]&&(_[e]=t),t<r&&(r=t))}return r}function D(t,r){let i=b[t],a=g[t];if(i<0||i>=r){g[t]=r;return}let{find:o,rule:s,severity:c,detector:l}=n[t],u=o?.(e.text,a,r);if(u===void 0)g[t]=r,b[t]=x[t]>=r?r:-1;else return g[t]=Math.max(a,u)+1,{rule:s,severity:c,start:e.rawAt(u),detector:l}}function O(t,r){if(!m[t]&&!h[t]){g[t]=r;return}m[t]=0;let i=e.text,{regex:a,hit:o,rule:s,severity:c,detector:l}=n[t];for(a.lastIndex=g[t];;){let n=a.exec(i);if(!n||n.index>=r){g[t]=r,h[t]=n||v[t]?1:0;return}let[u]=n;if(u&&(!o||o(u,i,n.index)))return g[t]=a.lastIndex,h[t]=1,{rule:s,severity:c,start:e.rawAt(n.index),detector:l};u||a.lastIndex++,g[t]=a.lastIndex}}function k(){for(let e=0;e<n.length;e++){let t=_[e];if(t<=g[e])continue;let r=n[e].find?D(e,t):O(e,t);if(r)return r}}return{run(t){T();let n=E();for(let e=k();e;e=k())t.push(e);return e.rawAt(n)}}}var Fn=new WeakMap;function In(e){let t=Fn.get(e);return t||(t=L(e),Fn.set(e,t)),t}function Ln(e={}){let t={text:``,fresh:``},n=cn(t),r=[n],i=(e,t,n)=>(r.includes(e)||r.push(e),Pn(e,t,n)),a=[],o=e.detect??[],s=jn(o,e);if(s.length>0&&(R??=L(Zt().forward),a.push(i(n,R,s))),o.includes(`injection`)){R??=L(Zt().forward),Yt??=L(Zt().reversed);let e=bn(t),r=Mn();a.push(i(n,Yt,Nn()),i(pn(n),R,r),i(e,R,r),i(pn(e),R,r),i(ln(n,mt),R,r),i(ln(n,e=>Ge(e)??e),R,r),i(Sn(t),R,r))}if(o.includes(`marker_leak`)&&e.note){let t=yt(e.note);a.push(i(n,tn(e.note),[{...Dn,id:0,regex:t}]))}if(o.includes(`tool_leak`)&&e.tools){let t=ht(e.tools),r=t.map(({regex:e},t)=>({...On,id:t,regex:e}));t.length>0&&a.push(i(n,nn(t.map(({literal:e})=>e)),r))}for(let{detector:t,compiled:r,matchers:o}of e.own??[]){let e=o.map(({regex:e},n)=>({...U(t),id:n,regex:new RegExp(e.source,e.flags)}));a.push(i(n,In(r.automaton),e))}let c=0;return{push(e){t.text+=e,t.fresh=e;for(let e of r)e.update();let n=[],i=t.text.length;for(let e of a)i=Math.min(i,e.run(n));return c=i,n},holdFrom:()=>c}}function Rn(e,t,n={},r=[]){let i=ot(e,t).filter(e=>!(Ze(e)||r.includes(e))),a=Je(e,t);if(i.length===0&&a.length===0)return;let o=[...i,...a.map(({id:e})=>e)],s=t.sources??{},c=[...i.map(e=>({detector:e,...s[e]})),...a.map(({id:e,matchers:t,compiled:n})=>({detector:e,matchers:t,compiled:n}))],l=c.some(({matchers:e,compiled:t})=>e?.length&&!t),u=Ln({detect:i.filter(e=>s[e]?.theorem!==!1),own:c.flatMap(({detector:e,compiled:t,matchers:n=[]})=>t?[{detector:e,compiled:t,matchers:n}]:[]),skipImages:t.ungiven_images[e]!==`ignore`,...n.allow?{allow:n.allow}:{},...n.givenUrls?{given:n.givenUrls}:{},...n.note?{note:n.note}:{},...n.ownTools?{tools:n.ownTools}:{}}),d=a.some(({find:e})=>e),f=e===`live_reply`?96:256,p=``,m=[];return{push(e){p+=e;for(let{start:t,detector:n}of u.push(e))n&&m.push({start:t,detector:n})},holdFrom(){if(l)return 0;let e=u.holdFrom();return d?Math.min(e,Math.max(0,p.length-f)):e},take(r,i,a=!1){let s=m.filter(({start:e})=>e<i);if(s.length===0&&!a&&!d)return{action:`allow`,text:p.slice(r,i),hits:[],taken:i-r};let c={from:r,to:i,settled:s.map(({detector:e})=>e)},l=nt(p,c,e,t,{detectors:o,scope:n});return m=m.filter(({start:e})=>e>=r+l.taken),l}}}function zn(e){let{context:t}=e,n=e.detect,r=n?Rn(n.boundary,n.matrix,n.scope):void 0,i=e=>n?n.matrix[e][n.boundary]:`block`,a=i(`canary_leak`),o=i(`prompt_leak`),s=t.canaryGiven||a===`ignore`?void 0:t.canary,c=o===`ignore`?void 0:t.privateSystem,l=s!==void 0||c!==void 0,u=l?e.carry??``:``,d=[],f=new Set,p=``,m=0,h=``,g=u.slice(-F),_=u,v=0,y=u,b=0,x=0,S=s?ft(s):void 0;S?.push(u);function ee(e){let n=[];if(S?.push(e)&&n.push([a,Dt]),c){let r=_.length;_+=e;let i=Qe(_,r);_=_.slice(i),v+=i;let[a]=_t(_,c,t.canary);a&&n.push([o,a])}for(let[e,t]of n)e!==`flag`||f.has(t.rule)||(f.add(t.rule),d.push(t));return n.filter(([e])=>e!==`flag`).map(([,e])=>e)}function C(e){let t=l?ee(e??``):[];return e&&r?.push(e),t.length===0?null:{hits:t,...n?{boundary:n.boundary}:{}}}function w(){let e=s&&a!==`flag`?E(s):h.length,n=c&&o!==`flag`?D(c,t.canary):h.length;return m+Math.min(e,n)}function T(e){if(d.length===0)return e;let t=[...d,...e.found?.hits??[]];return d=[],{...e,found:{action:e.found?.action??`flag`,hits:t}}}function E(e){let t=u.length+m,n=Math.max(t,x),r=Math.max(b,n-F),i=r+vt(y.slice(r-b),e);i<n&&n>t&&(y=g+h,b=t-g.length,i=b+vt(y,e)),x=Math.min(i,u.length+p.length-F);let a=Math.max(b,Math.max(t,x)-F);return y=y.slice(a-b),b=a,Math.max(0,i-t)}function D(e,t){let n=m===0?u:``,r=u.length+m-n.length,[i,a]=v>=r?[_,v]:[n+h,r];return Math.max(0,a+st(i,e,t)-u.length-m)}function O(e){let t=C(e);if(t)return{blocked:!0,...t};let i=e===void 0,a=i?p.length:Math.min(w(),r?.holdFrom()??p.length),o=Math.max(0,a-m);if(!(n&&r))return T({blocked:!1,emit:k(o)});let s=r.take(m,m+o,i);return s.action===`block`||s.action===`redact`&&!n.rewrite?{blocked:!0,hits:s.hits,boundary:n.boundary}:(k(s.taken),T({blocked:!1,emit:s.text??``,...s.action===`allow`?{}:{found:{action:s.action,hits:s.hits}}}))}function k(e){let t=h.slice(0,e);return h=h.slice(e),m+=t.length,l&&(g=(g+t).slice(-F)),t}return{process(e){return e?(p+=e,h+=e,l&&(y+=e),O(e)):{blocked:!1,emit:``}},flush:()=>O(),accumulated:()=>p,unreleased:()=>h,drainUnreleased:()=>k(h.length),carryOut:()=>l?qe(u+p,s,c):``}}function W(e,t,n){return et(t,e.detect,n)}async function Bn(e,t,n,r){return W(e,[n],t)?(await Xt(),Vn(e,t,n,r)):null}function Vn(e,t,n,r){return W(e,[n],t)?zn({context:t,detect:{matrix:e.detect,boundary:n,rewrite:n===`reply`,scope:We(e,t)},...r?{carry:r}:{}}):null}async function Hn(e,t,n,r){return W(e,[n],r??t)?(await Xt(),zn({context:t,detect:{matrix:e.detect,boundary:n,rewrite:!1,scope:r??We(e,t)}})):null}var Un=class{open;gate;constructor(e){this.open=e}async read(e){if(this.gate===void 0&&(this.gate=await this.open()),this.gate===`stopped`)return``;if(!this.gate)return e;let t=this.gate.process(e);return t.blocked?(this.gate=`stopped`,``):t.emit}end(){if(!this.gate||this.gate===`stopped`)return``;let e=this.gate.flush();return e.blocked?``:e.emit}},Wn=2,Gn=4,Kn=3,qn=/(^|,)(\s*)("?)(?:([=@])|([+-])(?![0-9."]))/gm,Jn=/^[A-Za-z0-9+/]*={0,2}$/,Yn=new Set([`text/csv`,`text/plain`,`text/markdown`]);function Xn(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 Zn(e,t){if(t.limitsByMime){let n=Me(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 G(e){return`uri`in e}function Qn(e){if(e.type===`speech`)throw new N(`request`,`Profile ${e.id} (speech) does not accept media input`);if(e.type===`live`)throw new N(`request`,`Profile ${e.id} (live) does not accept turn attachment input`);if(e.type===`host`||e.type===`decision`||e.type===`embedding`)throw new N(`request`,`Profile ${e.id} (${e.type}) does not accept turn input`);let t=Xn(e.inputs??{});if(!t)throw new N(`config`,`Profile ${e.id} must set maxFiles, maxBytes, and maxTurnBytes`);return t}function $n(e){let t=0;return e.endsWith(`==`)?t=Wn:e.endsWith(`=`)&&(t=1),Math.floor(e.length*Kn/Gn)-t}function er(e){try{return new TextDecoder(`utf-8`,{fatal:!0}).decode(e)}catch{return new TextDecoder(`latin1`).decode(e)}}function tr(e){return e.replace(qn,(e,...t)=>{let[n,r,i,a,o]=t;return`${n}${r}${i}'${a??``}${o??``}`})}function nr(e,t,n){let r=er(t);return e===`text/csv`&&(r=tr(r)),new TextEncoder().encode(n.read(r))}function rr(e,t){return t?{...e,fileName:t}:e}function ir(e,t,n){return t.filter(t=>!M(e,t.mimeType)).map(e=>rr({code:`mime_not_allowed`,params:{mimeType:e.mimeType,channel:n}},e.name))}function ar(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=Zn(i.mimeType,t);i.sizeBytes>e&&n.push(rr({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 or(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(...ir(e.attachments,t,`attachment`)),e.voice&&r.push(...ir(e.voice,n,`voice`)),e.limits?[...r,...ar([...t,...n],e.limits)]:[...r,{code:`limits_unconfigured`}])}var sr={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 cr(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:sr[e.code],params:t}}function lr(e,t){let n=cr(e);return P(n.key,n.params,t)}function ur(e){return new N(`input`,`attachments refused: ${e.map(e=>e.code).join(`, `)}`,{copy:e.map(cr)})}function dr(e){if(!Jn.test(e))throw new N(`request`,`attachment data must be base64`);return $n(e)}function fr(e){let t={mimeType:e.mimeType,name:e.name};return G(e)||(t.sizeBytes=dr(e.data)),t}function pr(e,t,n){if(!hr(t,n))return;let r=Qn(e),i=or({attachments:Re(e,`attachments`),voice:Re(e,`voice`),limits:r},(t??[]).map(fr),(n??[]).map(fr));if(i.length>0)throw ur(i)}function mr(e,t){if(G(e))return e;let{mimeType:n,data:r}=e;if(!Yn.has(Me(n)))return e;let i=nr(n,bt(r),t);return{...e,data:At(i)}}function hr(e,t){return(e?.length??0)>0||(t?.length??0)>0}function gr(e,t,n,r){return pr(e,t,n),{attachments:t?.length?t.map(e=>mr(e,r.attachment)):t,voice:n?.length?n.map(e=>mr(e,r.voice)):n}}var _r=`
|
|
2
2
|
|
|
3
|
-
`;function vr(e){if(typeof e==`string`)return;if(typeof e!=`object`||!e||Array.isArray(e))return`must be a string or { private: string }`;let t=Object.keys(e);if(t.length!==1||t[0]!==`private`)return`must have exactly one key, private`;let n=e.private;if(typeof n!=`string`)return`must be a string`;if(n===``)return`must not be empty`}function yr(e,t){if(typeof e!=`string`){if(!Array.isArray(e))return`${t} must be a string or an array of parts`;if(e.length===0)return`${t} must not be an empty array`;for(let[n,r]of e.entries()){let e=vr(r);if(e)return`${t}[${n}]${typeof r==`object`&&r&&`private`in r?`.private`:``} ${e}`}}}function br(e,t){let n=yr(e,t);if(n)throw new N(`config`,n)}function xr(e,t,n){return br(e,t),typeof e==`string`?n(e):e.map(e=>typeof e==`string`?n(e):{private:n(e.private)})}function Sr(e){if(typeof e==`string`)return[{text:e,private:!0}];let t=e.some(e=>typeof e!=`string`);return e.map(e=>typeof e==`string`?{text:e,private:!t}:{text:e.private,private:!0})}function Cr(e){let t=[];for(let n of e)n.some(e=>e.text)&&(t.length>0&&t.push({text:_r,private:!0}),t.push(...n));return t}function wr(e){return e.map(e=>e.text).join(``)}function Tr(e){let t=[],n=``;for(let r of e)r.private?n+=r.text:(n.trim()&&t.push(n),n=``);return n.trim()&&t.push(n),{text:wr(e),private:t}}function Er(e,t){return Tr(Cr([e,...t.map(e=>e?[{text:e,private:!0}]:[])]))}var Dr=[`user`,`slots`,`repair`,`attachment`,`voice`,`history`,`system`];function Or(e,t){return e&&Object.fromEntries(Object.entries(e).map(([e,n])=>[e,t.read(n)]))}var kr={client:`untrusted`,server:`assembled`};function Ar(e){return typeof e==`string`?e:JSON.stringify(e)}function jr(e,t){let n=[],r=!1;if(!e)return{context:e,events:n,blocked:r};let i={};for(let a of A){let o=e[a];if(o===void 0)continue;let s=t();i[a]=s.read(Ar(o));let c=s.found(),l=wt(`context`,c);l&&n.push({...l,trust:kr[a]}),r||=c.action===`block`}return{context:i,events:n,blocked:r}}var Mr=/^[A-Za-z0-9._-]+$/;function Nr(e){let t=e?.trim();return t&&Mr.test(t)?t:void 0}function Pr(e,t){if(!e)return e;let n=e.guidance?t.read(e.guidance):void 0;return{previousOutput:t.read(e.previousOutput),rejection:t.read(e.rejection),...n?{guidance:n}:{}}}function Fr(e,t){return e.map(e=>{let n=e.content===void 0?void 0:t.read(e.content),r=e.parts?.map(e=>e.type===`text`?{...e,text:t.read(e.text)}:e);return{role:e.role,...n===void 0?{}:{content:n},...r?{parts:r}:{},...e.tool_calls?{tool_calls:e.tool_calls}:{},...e.tool_call_id?{tool_call_id:e.tool_call_id}:{},...e.name?{name:e.name}:{},...e.metadata?{metadata:e.metadata}:{},...e.reasoning?{reasoning:e.reasoning}:{}}})}function Ir(e){return new N(`input`,`guardrails.detect blocked the request at ${e}`,{copy:{key:`detect.blocked`}})}function Lr(e,t){let{detect:n}=Ae(t.guardrails),r=Ke(Dr,e=>Et(e,n)),i=e.input??{},a=i.text===void 0?void 0:r.user.read(i.text),o=e.system===void 0?void 0:xr(e.system,`TurnRequest.system`,e=>r.system.read(e)),s=Or(i.slots,r.slots),c=jr(i.context,()=>Et(`context`,n)),l=Pr(i.repair,r.repair),u=i.history?Fr(i.history,r.history):void 0,{attachments:d,voice:f}=i.attachments?.length||i.voice?.length?gr(t,i.attachments,i.voice,r):i,p=[],m;for(let e of Dr){let t=r[e].found(),n=wt(e,t);n&&p.push(I(n)),t.action===`block`&&(m??=Ir(e))}return p.push(...c.events.map(I)),c.blocked&&(m??=Ir(`context`)),{request:{...e,system:o,projectId:Nr(e.projectId),input:{...i,text:a,slots:s,...c.context?{context:c.context}:{},repair:l,history:u,attachments:d,voice:f}},events:p,...m?{refusal:m}:{}}}function Rr(e,t){let{request:n,refusal:r}=Lr(e,t);if(r)throw r;return n}function zr(e){let t=Object.keys(e);return t.length===1?t[0]:void 0}function Br(e,t){return[...new Set([...t.filter(t=>M(e,t)),...e.filter(e=>M(t,e))])]}function Vr(e,t){let n=e.attachments?t?Br(e.attachments.accept,t.media.flatMap(e=>e.accept)):[...e.attachments.accept]:[],r=(t?.media??[]).flatMap(e=>e.maxPerInput===void 0?[]:[{accept:[...e.accept],max:e.maxPerInput}]);return{text:e.text!==!1,...n.length>0?{attachments:{accept:n}}:{},...e.maxFiles===void 0?{}:{maxFiles:e.maxFiles},...e.maxBytes===void 0?{}:{maxBytes:e.maxBytes},...e.maxTurnBytes===void 0?{}:{maxTurnBytes:e.maxTurnBytes},...e.limitsByMime===void 0?{}:{limitsByMime:{...e.limitsByMime}},...t?.maxInputs===void 0?{}:{maxInputs:t.maxInputs},...r.length>0?{perInput:r}:{}}}function Hr(e){let t=Me(e[0]??``);return t===`application/pdf`?`PDF`:t.split(`/`)[0]??t}function Ur(e,t){let n=Xn(e),r=or({attachments:e.attachments?.accept,...n?{limits:{...n,maxFiles:2**53-1}}:{}},t.flat(),[]);if(n)for(let i of t){i.length>n.maxFiles&&r.push({code:`too_many_files`,params:{maxFiles:n.maxFiles}});for(let t of e.perInput??[])i.filter(e=>M(t.accept,e.mimeType)).length>t.max&&r.push({code:`too_many_of_kind`,params:{maxFiles:t.max,kind:Hr(t.accept)}})}let i=new Set;return r.filter(e=>{let t=JSON.stringify(e);return!i.has(t)&&(i.add(t),!0)})}function Wr(e,t){let n=e.get(t);return n!==void 0&&n.type!==`builtin`}function Gr(e,t){return!e||e.includes(`*`)?!0:t?e.includes(t):!1}function Kr(e,t){return t.filter(n=>{let r=e.get(n);return r?.type!==`builtin`||!(r.conflictsWith??[]).some(e=>t.includes(e))})}function K(e){return`tools`in e?e.tools.allow:[]}function
|
|
4
|
-
`)}\n\n`}function
|
|
3
|
+
`;function vr(e){if(typeof e==`string`)return;if(typeof e!=`object`||!e||Array.isArray(e))return`must be a string or { private: string }`;let t=Object.keys(e);if(t.length!==1||t[0]!==`private`)return`must have exactly one key, private`;let n=e.private;if(typeof n!=`string`)return`must be a string`;if(n===``)return`must not be empty`}function yr(e,t){if(typeof e!=`string`){if(!Array.isArray(e))return`${t} must be a string or an array of parts`;if(e.length===0)return`${t} must not be an empty array`;for(let[n,r]of e.entries()){let e=vr(r);if(e)return`${t}[${n}]${typeof r==`object`&&r&&`private`in r?`.private`:``} ${e}`}}}function br(e,t){let n=yr(e,t);if(n)throw new N(`config`,n)}function xr(e,t,n){return br(e,t),typeof e==`string`?n(e):e.map(e=>typeof e==`string`?n(e):{private:n(e.private)})}function Sr(e){if(typeof e==`string`)return[{text:e,private:!0}];let t=e.some(e=>typeof e!=`string`);return e.map(e=>typeof e==`string`?{text:e,private:!t}:{text:e.private,private:!0})}function Cr(e){let t=[];for(let n of e)n.some(e=>e.text)&&(t.length>0&&t.push({text:_r,private:!0}),t.push(...n));return t}function wr(e){return e.map(e=>e.text).join(``)}function Tr(e){let t=[],n=``;for(let r of e)r.private?n+=r.text:(n.trim()&&t.push(n),n=``);return n.trim()&&t.push(n),{text:wr(e),private:t}}function Er(e,t){return Tr(Cr([e,...t.map(e=>e?[{text:e,private:!0}]:[])]))}var Dr=[`user`,`slots`,`repair`,`attachment`,`voice`,`history`,`system`];function Or(e,t){return e&&Object.fromEntries(Object.entries(e).map(([e,n])=>[e,t.read(n)]))}var kr={client:`untrusted`,server:`assembled`};function Ar(e){return typeof e==`string`?e:JSON.stringify(e)}function jr(e,t){let n=[],r=!1;if(!e)return{context:e,events:n,blocked:r};let i={};for(let a of A){let o=e[a];if(o===void 0)continue;let s=t();i[a]=s.read(Ar(o));let c=s.found(),l=wt(`context`,c);l&&n.push({...l,trust:kr[a]}),r||=c.action===`block`}return{context:i,events:n,blocked:r}}var Mr=/^[A-Za-z0-9._-]+$/;function Nr(e){let t=e?.trim();return t&&Mr.test(t)?t:void 0}function Pr(e,t){if(!e)return e;let n=e.guidance?t.read(e.guidance):void 0;return{previousOutput:t.read(e.previousOutput),rejection:t.read(e.rejection),...n?{guidance:n}:{}}}function Fr(e,t){return e.map(e=>{let n=e.content===void 0?void 0:t.read(e.content),r=e.parts?.map(e=>e.type===`text`?{...e,text:t.read(e.text)}:e);return{role:e.role,...n===void 0?{}:{content:n},...r?{parts:r}:{},...e.tool_calls?{tool_calls:e.tool_calls}:{},...e.tool_call_id?{tool_call_id:e.tool_call_id}:{},...e.name?{name:e.name}:{},...e.metadata?{metadata:e.metadata}:{},...e.reasoning?{reasoning:e.reasoning}:{}}})}function Ir(e){return new N(`input`,`guardrails.detect blocked the request at ${e}`,{copy:{key:`detect.blocked`}})}function Lr(e,t){let{detect:n}=Ae(t.guardrails),r=Ke(Dr,e=>Et(e,n)),i=e.input??{},a=i.text===void 0?void 0:r.user.read(i.text),o=e.system===void 0?void 0:xr(e.system,`TurnRequest.system`,e=>r.system.read(e)),s=Or(i.slots,r.slots),c=jr(i.context,()=>Et(`context`,n)),l=Pr(i.repair,r.repair),u=i.history?Fr(i.history,r.history):void 0,{attachments:d,voice:f}=i.attachments?.length||i.voice?.length?gr(t,i.attachments,i.voice,r):i,p=[],m;for(let e of Dr){let t=r[e].found(),n=wt(e,t);n&&p.push(I(n)),t.action===`block`&&(m??=Ir(e))}return p.push(...c.events.map(I)),c.blocked&&(m??=Ir(`context`)),{request:{...e,system:o,projectId:Nr(e.projectId),input:{...i,text:a,slots:s,...c.context?{context:c.context}:{},repair:l,history:u,attachments:d,voice:f}},events:p,...m?{refusal:m}:{}}}function Rr(e,t){let{request:n,refusal:r}=Lr(e,t);if(r)throw r;return n}function zr(e){let t=Object.keys(e);return t.length===1?t[0]:void 0}function Br(e,t){return[...new Set([...t.filter(t=>M(e,t)),...e.filter(e=>M(t,e))])]}function Vr(e,t){let n=e.attachments?t?Br(e.attachments.accept,t.media.flatMap(e=>e.accept)):[...e.attachments.accept]:[],r=(t?.media??[]).flatMap(e=>e.maxPerInput===void 0?[]:[{accept:[...e.accept],max:e.maxPerInput}]);return{text:e.text!==!1,...n.length>0?{attachments:{accept:n}}:{},...e.maxFiles===void 0?{}:{maxFiles:e.maxFiles},...e.maxBytes===void 0?{}:{maxBytes:e.maxBytes},...e.maxTurnBytes===void 0?{}:{maxTurnBytes:e.maxTurnBytes},...e.limitsByMime===void 0?{}:{limitsByMime:{...e.limitsByMime}},...t?.maxInputs===void 0?{}:{maxInputs:t.maxInputs},...r.length>0?{perInput:r}:{}}}function Hr(e){let t=Me(e[0]??``);return t===`application/pdf`?`PDF`:t.split(`/`)[0]??t}function Ur(e,t){let n=Xn(e),r=or({attachments:e.attachments?.accept,...n?{limits:{...n,maxFiles:2**53-1}}:{}},t.flat(),[]);if(n)for(let i of t){i.length>n.maxFiles&&r.push({code:`too_many_files`,params:{maxFiles:n.maxFiles}});for(let t of e.perInput??[])i.filter(e=>M(t.accept,e.mimeType)).length>t.max&&r.push({code:`too_many_of_kind`,params:{maxFiles:t.max,kind:Hr(t.accept)}})}let i=new Set;return r.filter(e=>{let t=JSON.stringify(e);return!i.has(t)&&(i.add(t),!0)})}function Wr(e,t){let n=e.get(t);return n!==void 0&&n.type!==`builtin`}function Gr(e,t){return!e||e.includes(`*`)?!0:t?e.includes(t):!1}function Kr(e,t){return t.filter(n=>{let r=e.get(n);return r?.type!==`builtin`||!(r.conflictsWith??[]).some(e=>t.includes(e))})}function K(e){return`tools`in e?e.tools.allow:[]}function qr(e){return e.type===`text`||e.type===`image`?e.tools:void 0}function Jr(e){return`tools`in e?e.tools.parallel:void 0}function Yr(e,t,n){return K(t).filter(r=>{let i=e.get(r);return!i||i.type===`builtin`?!1:t.type===`host`||Gr(i.paths,n.path)})}function Xr(e,t,n,r){let i=t.models[r];return i?(i.builtInTools??[]).filter(t=>{let r=e.get(t);return r?.type===`builtin`&&Gr(r.paths,n.path)}):[]}function Zr(e,t){let n=e.get(t);if(n&&n.type!==`builtin`)return{type:`function`,name:n.name,description:n.description,parameters:n.inputSchema}}function Qr(e,t){let n=[];for(let r of t){let t=Zr(e,r);t&&n.push(t)}return n}function $r(e,t,n){if(t.visible.includes(n))return;t.visible.push(n);let r=Zr(e,n);r&&!t.wire.some(e=>e.name===n)&&t.wire.push(r)}function ei(e,t,n){if(t.builtins.includes(n))return;let r=e.get(n);if(r?.type!==`builtin`)return;let i=r.conflictsWith??[];t.builtins=t.builtins.filter(t=>{if(i.includes(t))return!1;let r=e.get(t);return!(r?.type===`builtin`&&r.conflictsWith?.includes(n))}),t.builtins.push(n)}function ti(e,t,n){return t.type===`live`||t.type===`host`?[...n]:n.filter(t=>e.get(t)?.loadTier===`T0`)}function ni(e,t,n){return Kr(e,n.filter(n=>{let r=e.get(n);return r?.type===`builtin`&&(t.type===`live`||r.loadTier===`T0`)}))}function ri(e,t,n,r){let i=Yr(e,t,n),a=t.type===`host`||t.type===`decision`||t.type===`embedding`||r===void 0?[]:Xr(e,t,n,r),o=[...i,...a],s=ni(e,t,o),c=ti(e,t,o);return{builtins:s,gated:o,visible:c,executable:c.filter(t=>Wr(e,t)),path:n.path,sessionPermissions:n.sessionPermissions,wire:Qr(e,c)}}async function ii(e,t,n,r){let i=ri(e,t,n,r);return await oi(e,i,t,n),i}function ai(e){return{builtins:[...e.builtins],gated:[...e.gated],visible:[...e.visible],executable:[...e.executable],path:e.path,sessionPermissions:e.sessionPermissions?[...e.sessionPermissions]:void 0,wire:e.wire.map(e=>({...e,parameters:structuredClone(e.parameters)}))}}async function oi(e,t,n,r){let i=qr(n)?.t1Policy;if(!i)return;let a;try{a=await i({profile:n,input:r.input,path:r.path,sessionPermissions:r.sessionPermissions,gated:t.gated,host:r.host})}catch(e){let t=e instanceof Error?e.message:String(e);throw new N(`config`,`Profile '${n.id}' tools.t1Policy rejected: ${t}`,{cause:e})}if(!Array.isArray(a))throw new N(`config`,`Profile '${n.id}' tools.t1Policy must return ToolId[]`);for(let n of a){if(!t.gated.includes(n))continue;let r=e.get(n);r?.loadTier===`T2`&&(r.type===`builtin`?ei(e,t,n):$r(e,t,n))}t.executable=t.visible.filter(t=>Wr(e,t))}var si=new Set([`__proto__`,`constructor`,`prototype`]);function ci(e){if(!it(e))return;let{loaded:t}=e;if(Array.isArray(t)&&t.every(e=>typeof e==`string`))return t}function li(e,t,n,r){if(r.type===`live`||r.type===`host`)return{promoted:[]};let i=[];for(let a of n){if(typeof a!=`string`||si.has(a))return{promoted:[],failure:{code:`invalid_output`,kind:`bad_response`,message:`tools.t2Loader loaded ids must be plain strings`}};let n=di(e,a,r);if(`failure`in n)return{promoted:[],failure:n.failure};let{tool:o}=n;Gr(o.paths,t.path)&&t.gated.includes(a)&&i.push(a)}let a=[];for(let n of i)$r(e,t,n),a.push(n);return t.executable=t.visible.filter(t=>Wr(e,t)),{promoted:a}}function ui(e){return{failure:{code:`invalid_output`,kind:`bad_response`,message:e}}}function di(e,t,n){if(!K(n).includes(t))return ui(`tools.t2Loader attempted to promote tool '${t}' outside profile allow`);let r=e.get(t);return r?r.type===`builtin`?ui(`tools.t2Loader attempted to promote builtin '${t}' — only custom tools may be promoted`):r.loadTier===`T2`?{tool:r}:ui(`tools.t2Loader attempted to promote tool '${t}' with loadTier '${r.loadTier}' — only T2 tools may be promoted`):ui(`tools.t2Loader attempted to promote unknown tool '${t}'`)}function fi(e,t){return e.get(t)||{name:t,missing:!0}}function pi(e){let t=new Set;if(e.type===`host`||e.type===`decision`||e.type===`embedding`)return[];for(let n of Object.values(e.models))for(let e of n.builtInTools??[])t.add(e);return[...t]}function mi(e,t){return[...K(t),...pi(t)].map(t=>fi(e,t))}function hi(e,t){if(Array.isArray(e)){for(let n of e)hi(n,t);return}if(typeof e!=`object`||!e)return;let{properties:n,...r}=e;if(typeof n==`object`&&n)for(let[e,r]of Object.entries(n))t.add(e),hi(r,t);for(let e of Object.values(r))hi(e,t)}function gi(e,t){let n=mi(e,t);if(n.length===0)return;let r=new Set;for(let e of n)`inputSchema`in e&&hi(e.inputSchema,r);return{names:n.map(({name:e})=>e),params:[...r]}}function _i(e){return!e||e.length===0?[]:e.slice(-4)}function vi(e,t){if(e.length===0)return``;let n=e.map(e=>`${e.role===`user`?`User`:`Assistant`}: ${e.content}`);return`${P(`repair.history_heading`,{count:e.length},t)}\n${n.join(`
|
|
4
|
+
`)}\n\n`}function yi(e){let{profile:t,repair:n,history:r}=e,i=n.guidance||P(`repair.default_guidance`,{},t.labels),a=vi(_i(r),t.labels),o=`${P(`repair.prompt_header`,{},t.labels)}\n\n`;return o+=`${P(`repair.prompt_intro`,{},t.labels)}\n\n`,o+=`${P(`repair.section_previous_output`,{},t.labels)}\n\`\`\`\n${n.previousOutput.trim()}\n\`\`\`\n\n`,o+=`${P(`repair.section_validator_rejection`,{},t.labels)}\n${n.rejection.trim()}\n\n`,i.trim()&&(o+=`${P(`repair.section_repair_guidance`,{},t.labels)}\n${i.trim()}\n\n`),a&&(o+=a),o+=`${P(`repair.section_instructions`,{},t.labels)}\n`,o+=P(`repair.prompt_instructions`,{},t.labels),o}function bi(e,t){let n=[];return t&&n.push(`structured`),e.type===`image`&&n.push(`image`),e.type===`speech`&&n.push(`speech`),n}function xi(e,t){let n=bi(e,t);if(!(n.length<=1))throw new N(`config`,`Profile ${e.id} declares multiple output wire formats (${n.join(`, `)}). Only one of a structured JSON schema (outputs.structured), image, or speech may be active.`)}function Si(e,t){if(e.type!==`speech`){if(t.speech)throw new N(`request`,`Profile ${e.id} (${e.type}) takes no speech settings — only a speech profile speaks`)}else if(t.system)throw new N(`config`,`Profile ${e.id} (speech) takes no system prompt — the input text is the transcript`)}function Ci(e,t){return e.type===`speech`?{...e.speech,...wi(t.speech)}:void 0}function wi(e){return Object.fromEntries(Object.entries(e??{}).filter(([,e])=>e!==void 0))}function Ti(e){if(e.type!==`image`)return null;let t=e.image;return{type:`image`,mimeType:t.mimeType,aspectRatio:t.aspectRatio,resolution:t.resolution,quality:t.quality,background:t.background,n:t.n,seed:t.seed,outputCompression:t.outputCompression,includeText:t.includeText===!0}}function Ei(e){let t=Se(e);if(!t)throw new N(`input`,`MIME '${e}' is not a supported media input type`);return t}function Di(e){return e.map(e=>{let t=Ei(e.mimeType),n=Me(e.mimeType),r=n===`image/jpg`?`image/jpeg`:n;return G(e)?{type:t,mimeType:r,uri:e.uri}:{type:t,mimeType:r,data:e.data}})}function Oi(e,t){let{text:n,repair:r,history:i}=t.input??{};if(e.type===`speech`&&!n?.trim())throw new N(`request`,`Profile ${e.id} (speech) requires text input`);if(j(e)?.text===!1&&n)throw new N(`request`,`Profile ${e.id} does not accept text input`);let a=r?yi({profile:e,repair:r,history:i}):Ai(e,t)??n;if(e.type===`speech`)return a?{type:`text`,text:a}:null;let o=[...ki(t),...a?[tt(a)]:[]];return o.length>0?{type:`text`,text:o.join(`
|
|
5
5
|
|
|
6
|
-
`)}:null}function Oi(e){let t=e.input?.context??{};return[...A].reverse().filter(e=>t[e]!==void 0).map(e=>Tt(e,Ar(t[e])))}function ki(e,t){if(t.continueFrom&&He.includes(e.type)){if(t.input?.text)throw new N(`request`,`Profile ${e.id}: a continueFrom turn takes no input.text — its user message is the continue instruction`);return P(`continue.instruction`,{},e.labels)}}function Ai(e){return e.type===`image`&&e.image.references?Ei(e.image.references):[]}function ji(e,t){let n=t.input?.attachments??[],r=t.input?.voice??[];return[...Ai(e),...Ei(n),...Ei(r)]}function Mi(e,t){let n=[],r=Di(e,t);return r&&n.push(r),n.push(...ji(e,t)),n}function Ni(e,t){let n=t.input?.slots;if(!n)return;let r=j(e)?.slots??{};for(let[t,i]of Object.entries(n)){let n=Object.hasOwn(r,t)?r[t]:void 0;if(!n)throw new N(`request`,`Profile ${e.id} has no slot '${t}'`);if(!n.includes(i))throw new N(`request`,`Profile ${e.id}: slot '${t}' takes ${n.join(`, `)}, not '${i}'`)}}function Pi(e,t){let n=t.input?.context;if(!n)return;let r=j(e)?.context;for(let[t,i]of Object.entries(n))if(i!==void 0){if(!A.includes(t)||!r?.from.some(e=>e===t))throw new N(`request`,`Profile ${e.id} takes no context from '${t}'`);if(Ar(i).length>r.maxChars)throw new N(`request`,`Profile ${e.id}: context from '${t}' is over inputs.context.maxChars (${String(r.maxChars)})`)}}var Fi=/\{([A-Za-z_][\w-]*)\}/g;function Ii(e,t,n,r){let i=j(e)?.slots;return i?t.replace(Fi,(t,a)=>{if(!Object.hasOwn(i,a))return t;let o=n&&Object.hasOwn(n,a)?n[a]:void 0;if(o===void 0)throw new N(`request`,`Profile ${e.id}: ${r} uses slot '${a}', and the request chose no value for it`);return o}):t}function Li(e,t){let{handle:n}=e.identity,r=e.type===`speech`?void 0:e.identity.systemByRole;return t&&r&&Object.hasOwn(r,t)?t:n}function Ri(e,t,n){if(e.type===`speech`)return[];let{systemByRole:r,system:i}=e.identity,a=r?.[t]||i||``;return a?Sr(xr(a,`Profile ${e.id} identity.system`,t=>Ii(e,t,n,`identity.system`))):[]}function zi(e,t){return Cr([Ri(e,Li(e,t.input?.role),t.input?.slots),t.system===void 0?[]:Sr(t.system)])}function Bi(e){return e.type!==`host`&&e.type!==`decision`&&e.type!==`embedding`}function Vi(e,t){if(Bi(e))return e;throw e.type===`host`?new N(`request`,`Profile ${e.id}: type 'host' never runs a model — ${t} is not supported; execute tools with invokeTool`):e.type===`embedding`?new N(`request`,`Profile ${e.id}: type 'embedding' runs through runEmbedding — ${t} is not supported`):new N(`request`,`Profile ${e.id}: type 'decision' runs through runDecision — ${t} is not supported`)}function Hi(e,t){if(t){if(!e.allowModelSelect)throw new N(`request`,`Profile ${e.id} does not allow model selection`);if(!e.models[t])throw new N(`request`,`Unknown model '${t}' for ${e.id}`);return t}return e.defaultModel}function Ui(e,t,n,r){let i=t.efforts;if(!i||Object.keys(i).length===0){if(r)throw new N(`request`,`Profile ${e.id} model '${n}' has no selectable efforts`);return}let a=Object.keys(i);if(r){if(!t.allowEffortSelect)throw new N(`request`,`Profile ${e.id} model '${n}' does not allow effort selection`);let a=i[r];if(!a)throw new N(`request`,`Unknown effort '${r}' for ${e.id} model '${n}'`);return a}return i[t.defaultEffort??a[0]]}function Wi(e){if(e.summaries===!0)return`auto`;if(e.summaries===!1)return`none`}function Gi(e,t){if(e.type===`live`)return null;let n=e.outputs?.structured;if(!n)return null;if(typeof n==`string`)return n;let r=t?.[n.by];if(r){let e=n.map[r];if(e)return e}return n.fallback}function Ki(e){return e.type===`live`||e.outputs?.streaming?.mode!==`buffered`}function qi(e,t){return e.type===`live`?`live`:`turn`}function Ji(e,t){if(!t.continueFrom)return;if(e.type===`live`)throw new N(`request`,`Profile ${e.id}: type 'live' uses live.sessionResumption, not turnBehaviour.resumption/continueFrom`);let n=Ne(e)?.maxContinues;if(n===void 0)return;let r=t.continuation;if(r===void 0)throw new N(`request`,`Profile ${e.id}: continueFrom requires TurnRequest.continuation when turnBehaviour.resumption.maxContinues is set`);if(r<1)throw new N(`request`,`Profile ${e.id}: continuation must be >= 1`);if(r>n)throw new N(`request`,`Profile ${e.id}: continuation ${r} exceeds turnBehaviour.resumption.maxContinues (${n})`)}function Yi(e,t){return W(Ae(t),[`live_reply`])?{...e,transcription:{...e?.transcription,output:!0}}:e}function Xi(e){let{detect:t}=Ae(e.guardrails);return e.type!==`speech`&&Mt(t,`canary_leak`)?Lt():``}function Zi(e,t,n,r){if(!r)return;let i={};for(let[a,o]of Object.entries(r)){if(!n.builtInTools?.includes(a))throw new N(`request`,`Profile ${e.id}: builtInArgs names '${a}', which model '${t}' does not list in builtInTools`);i[a]=o}return i}function Qi(e,t,n){let r=Vi(e.profiles.get(t.profile),`resolveTurn`);Ni(r,t),Pi(r,t);let i=Rr(t,r),a=i.input??{};Ji(r,i);let o=n??Hi(r,i.model),s=Ee(r,o),c=ni(e.tools,r,i,o),l=c.builtins,u=Gi(r,a.slots);bi(r,u),xi(r,i);let d=Zi(r,o,s,i.builtInArgs),f=qi(r,s);return{profile:r,generation:{model:o,apiId:s.apiId,transport:f,stream:Ki(r),thinking:Ui(r,s,o,i.effort),summaries:Wi(s),maxOutputTokens:s.maxOutputTokens,temperature:s.temperature,builtins:l,builtInArgs:d,sessionId:i.sessionId,tools:c,sessionPermissions:i.sessionPermissions,execution:i.execution,pageExecution:i.pageExecution,history:a.history,maxSteps:r.maxSteps??20,structured:u?{id:u,jsonSchema:e.schemas.get(u).jsonSchema}:null,image:wi(r),speech:Si(r,i),live:r.type===`live`?Yi(r.live,r.guardrails):void 0,input:Mi(r,i),canary:Xi(r),resolvedSystem:zi(r,i),host:i.host}}}function $i(e){return e.type===`image`?e.image:null}function ea(e,t){let n=Vi(t,`projectProfile`),{identity:r}=n,i=j(n)??null,a=n.type===`live`?null:n.outputs??null;return{id:n.id,type:n.type,handle:r.handle,models:n.models,defaultModel:n.defaultModel,allowModelSelect:n.allowModelSelect,maxSteps:n.maxSteps,tools:pi(e,n),inputs:i,outputs:a,image:$i(n),speech:n.type===`speech`?n.speech:null,live:n.type===`live`?n.live:null}}function ta(e,t){return ea(e.tools,e.profiles.get(t))}function na(e){return e==null}function J(e){return na(e)||typeof e!=`object`||Array.isArray(e)?null:e}function ra(e){let t=J(e);return!t||t.type!==void 0&&t.type!==`object`?null:t}function ia(e){let t=e.required;return Array.isArray(t)?t.filter(e=>typeof e==`string`):[]}function aa(e){let t=e.properties;return J(t)??{}}function oa(e,t){return e?`${e}.${t}`:t}function sa(e,t){t.push({path:e,error:`required field '${e}' is missing`})}async function ca(e,t,n,r,i){if(!n)return;let a=await n(t,r);a.isValid||i.push({path:e,error:a.error||a.finding||`Validation failed for '${e}'`})}async function la(e){let{path:t,propSchema:n,child:r,isRequired:i,fields:a,slots:o,failures:s}=e;if(na(r)){i&&sa(t,s);return}await ca(t,r,a?.[t],o,s);let c=ra(n),l=c?J(r):null;c&&l&&await ua(c,l,t,a,o,s)}async function ua(e,t,n,r,i,a){let o=aa(e),s=new Set(ia(e)),c=new Set([...Object.keys(o),...s]),l=J(t);for(let e of c)await la({path:oa(n,e),propSchema:o[e],child:l?.[e],isRequired:s.has(e),fields:r,slots:i,failures:a})}async function da(e,t,n,r){let i=ra(e);if(!i)throw new N(`config`,`structured validation requires a JSON Schema object root`);let a=[];if(!J(t)){for(let e of ia(i))sa(e,a);return a}return await ua(i,t,``,n,r,a),a}function fa(e,t){let n=e;for(let e of t.split(`.`)){let t=ra(n);if(!t)return!1;let r=aa(t);if(!Object.hasOwn(r,e)&&!ia(t).includes(e))return!1;n=r[e]}return!0}function pa(e){return e.map(e=>e.error).join(`; `)}function ma(e,t){let n=e;for(let e of t.split(`.`))n=J(n)?.[e];return n}function ha(e,t,n){let[r,...i]=t.split(`.`),a=J(e)??{};return r===void 0?e:{...a,[r]:i.length?ha(a[r],i.join(`.`),n):n}}async function ga(e,t,n){let r=[];for(let[i,a]of Object.entries(t??{})){let t=ma(e,i);if(Array.isArray(t))for(let[e,o]of t.entries()){let t=await a.check(o,n);t.isValid||r.push({path:i,index:e,item:o,reason:t.error||t.finding||`Validation failed for '${i}'`,onFail:a.onFail})}}return r}function _a(e,t){let n=e;for(let e of t.split(`.`)){let t=ra(n);if(!t)return;n=aa(t)[e]}let r=J(n);if(r?.type===`array`)return J(r.items)??void 0}var va=class extends Error{failure;constructor(e){super(e.message),this.failure=e}},ya=new Set([`text`,`image`,`speech`]),ba=g().regex(/\S/),xa=t({mimeType:g(),data:m(),name:g().optional()}),Sa=t({mimeType:g(),uri:g(),name:g().optional()}),Ca=t({voice:g().optional(),style:g().optional(),speed:h().positive().optional()});function wa(e){return t(Object.fromEntries(Object.entries(e).map(([e,t])=>[e,d(t).optional()])))}var Ta=new Set([`text`,`attachments`,`voice`,`slots`,`speech`]);function Ea(e,t){if(!e.hostFields)return{sent:t};let n={...t},r={};for(let t of Object.keys(e.hostFields))n[t]!==void 0&&(r[t]=n[t]);let{text:i,attachments:a,voice:o,slots:s,speech:c}=t;return{sent:{text:i,...a?{attachments:a}:{},...o?{voice:o}:{},...s?{slots:s}:{},...c?{speech:c}:{}},hostInput:r}}function Da(e,n){let{inputs:r}=e,a={text:ba};r?.attachments&&(a.attachments=l(i([xa,Sa])).optional()),r?.voice&&(a.voice=l(xa).optional()),r?.slots&&(a.slots=wa(r.slots).optional()),e.type===`speech`&&(a.speech=Ca.optional());for(let e of n?.hostOnly??[]){if(!a[e])throw new N(`config`,`Tool '${n?.name}' keeps '${e}' for the host, which its profile does not take`);delete a[e]}for(let[e,t]of Object.entries(n?.fieldText??{})){let r=a[e];if(!r)throw new N(`config`,`Tool '${n?.name}' describes '${e}', which its profile does not take`);a[e]=r.describe(t)}for(let[e,t]of Object.entries(n?.hostFields??{})){if(Ta.has(e))throw new N(`config`,`Tool '${n?.name}' declares the host field '${e}', which is a field of every agent tool`);a[e]=t}return t(a)}var Oa=v({text:g().optional(),structured:n().optional(),removed:l(v({path:g(),reason:g(),item:n()})).optional(),parts:l(b).optional(),sources:l(ue).optional()});function ka(e){return e.type===`speech`||(e.type===`text`||e.type===`image`)&&e.inputs.text!==!1}function Aa(e){return e.type===`builtin`?!1:e.permission!==`auto`||`auth`in e&&e.auth!==void 0&&(e.auth.onUnauthenticated??`gate`)===`gate`}function ja(e,t){if(!ya.has(e.type))return`it is a ${e.type} profile; an agent tool runs a text, image, or speech profile`;if(!ka(e))return`it does not take text`;for(let n of K(e)){let e=t(n);if(!e)return`its tool '${n}' is not registered; register it first`;if(Aa(e))return`its tool '${n}' can stop on a gate; give it permission 'auto' and no sign-in`}}function Ma(e,t,n){let r=`Agent tool "${e.name}"`,i=e.maxCallsPerTurn;if(i!==void 0&&!(Number.isInteger(i)&&i>0))throw new N(`config`,`${r}: maxCallsPerTurn must be a whole number above 0`);let a=t(e.profile);if(!a)throw new N(`config`,`${r}: profile '${e.profile}' must be registered before the tool`);let o=ja(a,n);if(o)throw new N(`config`,`${r} can't run '${e.profile}': ${o}`);return a}function Na(e){if(!e)return`delegated`;let t=`models`in e&&Object.values(e.models).some(e=>(e.builtInTools?.length??0)>0);return K(e).length===0&&!t?`local`:`delegated`}function Pa(e){let t=oe(e),n=t.flatMap(e=>e.type===`text`?[e.text]:[]).join(``),r=ae(t,e=>e.type===`structured`),i=r?.structured,a=t.flatMap(e=>e.type===`media`?[{type:e.media.mimeType.startsWith(`audio/`)?`audio`:`image`,mimeType:e.media.mimeType,data:e.media.data}]:[]),o=t.flatMap(e=>e.type===`citation`?e.sources:[]);return{...i===void 0?{text:n}:{structured:i},...r?.removed?.length?{removed:r.removed}:{},...a.length>0?{parts:a}:{},...o.length>0?{sources:o}:{}}}function Fa(e,t,n){return{...e,type:`agent`,input:t,output:Oa,sources:e=>e.sources??[],...n}}var Ia=256,La=18e5,Ra=/^[\x21-\x7E]{1,256}$/;function za(e=Date.now){let t=new Map,n=new Map;return{get(n){let r=t.get(n);if(r&&(t.delete(n),!(e()-r.usedAt>La)))return t.set(n,{...r,usedAt:e()}),{id:r.id,protocolVersion:r.protocolVersion}},open(r,i){let a=n.get(r);if(a)return a;let o=i().then(n=>{t.delete(r),t.set(r,{...n,usedAt:e()});for(let e of t.keys()){if(t.size<=Ia)break;t.delete(e)}return n}).finally(()=>n.delete(r));return n.set(r,o),o},drop(e,n){t.get(e)?.id===n&&t.delete(e)},clear(){t.clear(),n.clear()}}}function Ba(e){return e!==null&&Ra.test(e)}async function Va(e,t){let n=JSON.stringify([e,Object.entries(t).map(([e,t])=>[e.toLowerCase(),t]).sort(([e],[t])=>e<t?-1:+(e>t))]),r=await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(n));return[...new Uint8Array(r)].map(e=>e.toString(16).padStart(2,`0`)).join(``)}function Ha(e,t,n){if(!e||typeof e!=`object`||Array.isArray(e))return n.push(`${t}: schema must be an object`),!1;let r=typeof e.type==`string`||Array.isArray(e.type),i=e.anyOf!==void 0||e.oneOf!==void 0;if(!r&&!i){if(t!==`$`)return!0;n.push(`${t}: missing type or combinator`)}return e.type===`array`&&e.items===void 0&&n.push(`${t}: array schema must define items`),!0}function Ua(e,t,n,r){let i=Array.isArray(t)?t:[];for(let t of i)typeof t==`string`&&!Object.hasOwn(e,t)&&r.push(`${n}: required key '${t}' missing from properties`);for(let[t,i]of Object.entries(e))i&&typeof i==`object`&&Wa(i,`${n}.properties.${t}`,r)}function Wa(e,t,n){if(!Ha(e,t,n))return;let r=e.properties;r&&typeof r==`object`&&!Array.isArray(r)&&Ua(r,e.required,t,n),e.items&&typeof e.items==`object`&&!Array.isArray(e.items)&&Wa(e.items,`${t}.items`,n);for(let r of[`anyOf`,`oneOf`]){let i=e[r];Array.isArray(i)&&i.forEach((e,i)=>{e&&typeof e==`object`&&Wa(e,`${t}.${r}[${i}]`,n)})}}function Ga(e,t){let n=[];if(Wa(e,`$`,n),n.length>0)throw new N(`config`,`Invalid tool ${t} schema: ${n.join(`; `)}`)}function Ka(e,t=`output`){let n=r(e,{target:`draft-7`,io:t});return delete n.$schema,n.type||=`object`,n}function qa(e){if(typeof e!=`object`||!e)return e;if(Array.isArray(e))return e.map(qa);let t={};for(let n of Object.keys(e))n!==`__proto__`&&n!==`constructor`&&n!==`prototype`&&(t[n]=qa(e[n]));return t}function Ja(e){let t=/^[a-z][a-z0-9+.-]*:\/\/[^/?#]*/i.exec(e)?.[0];if(!t||/[{}]/.test(t))throw new N(`config`,`Endpoint "${e}" must start with a fixed scheme and host; placeholders belong in the path or query`)}var Ya=class{value;constructor(e){this.value=e}};function Xa(e){return new Ya(e)}function Za(e){return(t,n)=>{let{page:r}=n;if(r&&`output`in r)return Xa(r.output);let{labels:i}=n.profile;throw r?.timedOut?Error(P(`tool.page_timed_out`,{},i)):Error(P(`tool.page_no_answer`,{tool:e},i))}}function Qa(e){let t=Ka(e.input,`input`);Ga(t,`input`);let n=Ka(e.output,`output`);Ga(n,`output`);let r={activity:{input:t},activityPast:{input:t,output:n},activityFailed:{input:t},request:{input:t}};for(let t of[`activity`,`activityPast`,`activityFailed`,`request`]){let n=e.labels?.[t],i=n?Be(n,r[t]):void 0;if(i)throw new N(`config`,`Tool "${e.name}" ${t} label: ${i}`)}return{inputSchema:t,outputSchema:n}}function $a(e,t){if(t&&(typeof t.service!=`string`||!t.service.trim()))throw new N(`config`,`Tool "${e}" signs in with slot "${t.slot}" but names no service`)}function eo(e,t,n=[]){if(t?.queryParam===void 0)return;let r=t.queryParam.trim()?t.type===`api_key`?t.headerName!==void 0||t.headerPrefix!==void 0?`is set with headerName or headerPrefix; the key goes in one place`:n.includes(t.queryParam)?`"${t.queryParam}" is also one of mapping.queryParams`:void 0:`is set on a '${t.type}' sign-in; only an API key goes in the URL`:`is blank`;if(r)throw new N(`config`,`Tool "${e}" auth.queryParam ${r}`)}function to(e,t){if(t!==void 0&&!(Number.isInteger(t.requests)&&t.requests>0&&Number.isFinite(t.windowMs)&&t.windowMs>0))throw new N(`config`,`Tool "${e}" limit needs a whole number of requests above 0 and a window above 0 ms`)}function no(e,t){if(!(t===void 0||Number.isFinite(t)&&t>0))throw new N(`config`,`Tool "${e}" timeoutMs needs a finite number of ms above 0`)}function ro(e){return Ja(e.endpoint),$a(e.name,e.auth),eo(e.name,e.auth,e.mapping?.queryParams),to(e.name,e.limit),no(e.name,e.timeoutMs),{...e,type:`http`,...Qa(e)}}function io(e){return $a(e.name,e.auth),eo(e.name,e.auth),{...e,type:`mcp`,...Qa(e)}}function ao(e){$a(e.name,e.auth),eo(e.name,e.auth);let t=e.answeredBy===`page`?Za(e.name):e.handler;if(typeof t!=`function`)throw new N(`config`,`Tool '${e.name}' needs a handler, or answeredBy: 'page'`);return{...e,handler:t,type:`function`,...Qa(e)}}function oo(e,t,n){if(e.type===`builtin`)return e;if(e.type===`agent`){let r=Ma(e,t,n),i=j(r),a=Da({type:r.type,...i?{inputs:i}:{}},e);return Fa(e,a,Qa({...e,input:a,output:Oa}))}return e.type===`http`?ro(e):e.type===`mcp`?io(e):ao(e)}function so(e=()=>void 0){let t=new Map,n=za(),r=e=>t.get(e),i=n=>{let i=oo(n,e,r);return t.set(i.name,i),i};return{register:i,registerMany:e=>e.map(e=>i(e)),get:r,require(e){let t=r(e);if(!t)throw new N(`config`,`Tool '${e}' is not registered`);return t},has:e=>t.has(e),list:()=>[...t.values()],findProfile:e,reset:()=>{t.clear(),n.clear()},mcpSessions:n}}function co(e,t,n,r){if(!n.provider?.trim()||!n.apiId?.trim())throw new N(`config`,P(`provider.binding_identity`))}function lo(e){yo(e.id,e.models),Vo(e.id,e.observability),ls(e.id,e.inputs);for(let[t,n]of Object.entries(e.models))xo(e.id,t,n);return{type:`embedding`,id:e.id,identity:{handle:e.identity.handle},models:e.models,defaultModel:bo(e.id,e),allowModelSelect:e.allowModelSelect,inputs:e.inputs,guardrails:e.guardrails,observability:e.observability,labels:e.labels}}function uo(e,t,n,r){let i=r.safeParse(n);if(!i.success)throw new N(`config`,`Profile ${e} model '${t}': ${i.error.issues.map(e=>`${e.path.join(`.`)}: ${e.message}`).join(`; `)}`)}function fo(e,t,n){if(uo(e,t,n,de),co(e,t,n,`decision`),`retry`in n)throw new N(`config`,`Profile ${e} model '${t}': decision retry configuration is unsupported; POSTs are never retried`);if(n.timeoutMs!==void 0&&(!Number.isFinite(n.timeoutMs)||n.timeoutMs<=0))throw new N(`config`,`Profile ${e} model '${t}' timeoutMs must be > 0`)}function po(e){let t=e.models?zr(e.models):void 0;if(!t)throw new N(`config`,`Profile ${e.id}: type 'decision' must declare exactly one model`);fo(e.id,t,e.models[t])}function mo(e){if(e.inputs.state!==`json`)throw new N(`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 N(`config`,`Profile ${e.id}: decision inputs.maxStateBytes must be a positive integer`);if(!e.decision.contract.trim())throw new N(`config`,`Profile ${e.id}: decision.contract must be non-empty`)}function ho(e){return po(e),mo(e),Vo(e.id,e.observability),{...e,identity:{handle:e.identity.handle}}}function go(e){return e===void 0?{}:{parallel:e}}function _o(e){return vo(e.id,e.tools),Vo(e.id,e.observability),{type:`host`,id:e.id,tools:{allow:e.tools.allow,...go(e.tools.parallel)},guardrails:e.guardrails,observability:e.observability,labels:e.labels}}function vo(e,t){if(!Array.isArray(t.allow))throw new N(`config`,`Profile ${e}: type 'host' must set tools.allow`)}function yo(e,t){if(Object.keys(t).length===0)throw new N(`config`,`Profile ${e} must declare at least one model`)}function bo(e,t){let n=t.defaultModel??zr(t.models);if(!n)throw new N(`config`,`Profile ${e} must set defaultModel when more than one model is declared`);if(!t.models[n])throw new N(`config`,`Profile ${e} defaultModel '${n}' is not declared`);return n}function xo(e,t,n){So(e,t,n),uo(e,t,n,we),So(e,t,n)}function So(e,t,n){let r=n.efforts;if(!r||Object.keys(r).length===0){if(n.defaultEffort||n.allowEffortSelect)throw new N(`config`,`Profile ${e} model '${t}': defaultEffort and allowEffortSelect require efforts`);return}for(let[n,i]of Object.entries(r))if(!Oe.includes(i))throw new N(`config`,`Profile ${e} model '${t}' effort '${n}': '${i}' is not a thinking level (${Oe.join(`, `)})`);let i=Object.keys(r),a=n.defaultEffort??(i.length===1?i[0]:void 0);if(!a)throw new N(`config`,`Profile ${e} model '${t}' must set defaultEffort when more than one effort is declared`);if(!r[a])throw new N(`config`,`Profile ${e} model '${t}' defaultEffort '${a}' is not declared`);if(n.allowEffortSelect&&i.length<2)throw new N(`config`,`Profile ${e} model '${t}' allowEffortSelect requires at least two efforts`)}function Co(e){return{providerContinuation:e.providerContinuation?pe.parse(e.providerContinuation):{},models:e.models,defaultModel:bo(e.id,e),allowModelSelect:e.allowModelSelect,maxSteps:e.maxSteps}}function wo(e,t,n){if(n?.length){for(let r of n)if(!k(r))throw new N(`config`,`Profile ${e}: turnBehaviour.resumption.${t} may only include ContinueStopKind (length | stream_incomplete | provider_error); got '${r}'`)}}function To(e,t){t&&(wo(e,`allowContinue`,t.allowContinue),wo(e,`autoContinue`,t.autoContinue))}function Eo(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Do(e,t){let n=[e];for(let e of t)n=n.flatMap(t=>Eo(t)?e===`*`?Object.values(t):[t[e]]:[]);return n}var Oo=Object.entries(y).filter(([,e])=>e.required===!0).map(([e,t])=>[e,t.profileTypes]).sort(([e],[t])=>e.split(`.`).length-t.split(`.`).length);function ko(e){if(!Eo(e))throw new N(`config`,`Profile definition must be an object`);let t=typeof e.id==`string`&&e.id.trim()?e.id:void 0;if(!t)throw new N(`config`,`Profile definition must set id`);if(!Te.find(t=>t===e.type))throw new N(`config`,`Profile ${t}: type must be one of ${Te.join(`, `)}`)}function Ao(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 N(`config`,`Profile ${e.id.slice(0,64)}: ${t} must be at most ${i} characters`)}function jo(e){let{id:t,type:n}=e,r=e;for(let[e,i]of Oo){if(i&&!i.includes(n))continue;let a=xe(e),o=Do(r,a.slice(0,-1)),s=a[a.length-1];if(o.some(e=>{if(!Eo(e))return!1;let t=e[s];return t==null||t===``}))throw new N(`config`,`Profile ${t}: type '${n}' must set ${a.join(`.`)}`)}}function Mo(e){let{id:t,type:n}=e;if(n!==`live`&&ze(`inputs`).includes(n)&&e.inputs==null)throw new N(`config`,`Profile ${t}: type '${n}' must set inputs`)}function No(e){let[t]=De(e);if(!t)return;let{offValue:n,reason:r}=t.scope,i=n===void 0?``:` (other than ${n})`;throw new N(`config`,`Profile ${e.id}: type '${e.type}' must not set ${t.path}${i} — ${r}`)}function Po(e,t){let n=t.turnBehaviour;To(e,n?.resumption)}function Fo(e,t){let n=t=>new N(`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 Io(e,t){let n=t=>new N(`config`,`Profile ${e}: ${t}`),r=Object.keys(t??{}).find(e=>!Lo.includes(e));if(r!==void 0)throw n(`guardrails.${r} is not a setting; it takes ${Lo.join(`, `)}`);zo(t?.blockedReply,n)}var Lo=[`quota`,`detect`,`blockedReply`,`network`,`taint`],Ro=[`onBlock`,`maxRetries`];function zo(e,t){if(e===void 0)return;let n=Object.keys(e).find(e=>!Ro.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&&!x.includes(r))throw t(`guardrails.blockedReply.onBlock must be one of ${x.join(`, `)}`);if(i!==void 0&&(!Number.isInteger(i)||i<0))throw t(`guardrails.blockedReply.maxRetries must be a non-negative integer`)}function Bo(e){let t=e.guardrails?.detect,n=e.type===`host`?Ot(`guardrails.detect`,t,It):Ot(`guardrails.detect`,t);if(n!==void 0)throw new N(`config`,`Profile ${e.id}: ${n}`)}function Vo(e,t){try{let n=Bt(t);if(!Number.isFinite(n.retainForDays))throw new N(`config`,`Profile ${e}: observability.retainForDays must be a finite number`);if(n.rotateAfterMiB<=0||!Number.isFinite(n.rotateAfterMiB))throw new N(`config`,`Profile ${e}: observability.rotateAfterMiB must be a positive number`)}catch(t){if(t instanceof N&&t.message.startsWith(`Profile `))throw t;let n=t instanceof Error?t.message:String(t);throw new N(`config`,`Profile ${e}: ${n}`)}}function Ho(e){if(e.type===`host`||e.type===`decision`||e.type===`speech`||e.type===`embedding`)return;let{system:t,systemByRole:n}=e.identity;t!==void 0&&br(t,`Profile ${e.id} identity.system`);for(let[t,r]of Object.entries(n??{}))br(r,`Profile ${e.id} identity.systemByRole.${t}`)}function Uo(e){ko(e);for(let t of[`key`,`fallbackKey`,`protocol`,`provider`])if(t in e)throw new N(`config`,P(`provider.profile_configuration`,{profile:e.id,field:t}));if(No(e),Mo(e),jo(e),Ao(e),e.labels&&rt(e.labels,`Profile ${e.id}`),Ho(e),Bo(e),e.type===`host`)return _o(e);if(e.type===`decision`)return ho(e);if(e.type===`embedding`)return lo(e);yo(e.id,e.models),Po(e.id,e),Io(e.id,e.guardrails),e.type===`text`&&Fo(e.id,e.outputs?.validation),Vo(e.id,e.observability);for(let[t,n]of Object.entries(e.models))xo(e.id,t,n);let t=e.type===`speech`?{handle:e.identity.handle}:{handle:e.identity.handle,system:e.identity.system,systemByRole:e.identity.systemByRole},n=e.guardrails,r=e.observability,i=e.labels,a=Co(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},Yo(o.id,o.inputs.attachments?.accept),Jo(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,...go(e.tools.parallel)},turnBehaviour:e.turnBehaviour,guardrails:n,observability:r,labels:i},Vt(o),Zo(o.id,o.live.contextCompression),Xo(o);break;default:throw new N(`config`,`Unknown profile type '${String(e)}'`)}return Ko(o),Wo(o),Go(o),o}function Wo(e){let{maxSteps:t}=e;if(!(t===void 0||Number.isInteger(t)&&t>0))throw new N(`config`,`Profile ${e.id}: maxSteps must be a whole number of 1 or more; leave it out for the default of 20`)}function Go(e){if(e.type===`text`&&e.turnBehaviour?.atStepLimit===`answer`&&e.maxSteps===1)throw new N(`config`,`Profile ${e.id}: turnBehaviour.atStepLimit 'answer' with maxSteps 1 leaves no step that can call a tool`)}function Ko(e){if(e.type===`live`)return;let t=e.outputs?.structured;if(!t||typeof t==`string`)return;let n=j(e)?.slots?.[t.by];if(!n)throw new N(`config`,`Profile ${e.id}: outputs.structured.by '${t.by}' is not a slot in inputs.slots`);let r=Object.keys(t.map).filter(e=>!n.includes(e));if(r.length)throw new N(`config`,`Profile ${e.id}: outputs.structured.map maps ${r.join(`, `)}, not a choice of slot '${t.by}'`)}var qo={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 Jo(e,t){for(let[n,{ok:r,rule:i}]of Object.entries(qo)){let a=t[n];if(a!==void 0&&!r(a))throw new N(`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 N(`config`,`${r} must be an image, not '${t.mimeType}'`);if(!(G(t)?t.uri:t.data))throw new N(`config`,`${r} needs its bytes or its uri`)})}function Yo(e,t){let n=t?.filter(e=>!M(te,e));if(n?.length)throw new N(`config`,`Profile ${e}: an image profile's attachments take images, video, and PDF only, not ${n.join(`, `)}`)}function Xo(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 N(`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 N(`config`,`${i}.resumed.prompt must be a prompt`);let{afterMs:a}=n;if(a!==void 0&&!(Number.isFinite(a)&&a>=0))throw new N(`config`,`${i}.resumed.afterMs must be 0 or more milliseconds`);if(!r)throw new N(`config`,`${i}.resumed needs live.sessionResumption: without it no call resumes`)}function Zo(e,t){if(!t)return;let n=`Profile ${e} live.contextCompression`,r=t.triggerTokens,i=t.slidingWindow.targetTokens;if(Qo(`${n}.triggerTokens`,r),Qo(`${n}.slidingWindow.targetTokens`,i),r!==void 0&&i!==void 0&&i>=r)throw new N(`config`,`${n}: slidingWindow.targetTokens must be below triggerTokens`)}function Qo(e,t){if(!(t===void 0||Number.isInteger(t)&&t>0))throw new N(`config`,`${e} must be a whole number above 0`)}function $o(e,t,n,r){let i=`Profile ${t.id} model ${n} compaction`;if(es(i,r),ts(i,r),r.meter!=null&&r.meter!==`history`&&r.meter!==`input`)throw new N(`config`,`${i}: meter must be 'history' or 'input'`);if(r.profile===void 0){if(t.type!==`text`||t.inputs.text===!1)throw new N(`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 N(`config`,`${i}: compaction profile '${r.profile}' must be registered before '${t.id}'`);if(a.type!==`text`||a.inputs.text===!1)throw new N(`config`,`${i}: compaction profile '${r.profile}' must be a text profile that takes text`)}function es(e,t){if(t.maxTokens<=0)throw new N(`config`,`${e}: maxTokens must be > 0`);if(t.compactAt<=0||t.compactAt>=1)throw new N(`config`,`${e}: compactAt must be in (0, 1)`)}function ts(e,t){if(t.previousExchanges<0)throw new N(`config`,`${e}: previousExchanges must be >= 0`);if(t.previousExchanges<1&&t.previousExchanges>=t.compactAt)throw new N(`config`,`${e}: previousExchanges as fraction (${t.previousExchanges}) must be < compactAt (${t.compactAt})`);if(t.previousExchanges>1&&!Number.isInteger(t.previousExchanges))throw new N(`config`,`${e}: previousExchanges >= 1 must be an integer`)}function ns(e,t){for(let n of K(t))if(e.get(n)?.type===`builtin`)throw new N(`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 rs(e,t){let n=q(t)?.t2Loader;if(n){if(!K(t).includes(n))throw new N(`config`,`Profile ${t.id} tools.t2Loader '${n}' must also be listed in tools.allow`);if(e.get(n)?.type!==`function`)throw new N(`config`,`Profile ${t.id} tools.t2Loader '${n}' must be a registered type: 'function' tool`)}}function*is(e){for(let[t,n]of Object.entries(e.models))for(let e of n.builtInTools??[])yield{modelId:t,id:e}}function as(e,t){for(let{modelId:n,id:r}of is(t))if(e.get(r)?.type!==`builtin`)throw new N(`config`,`Profile ${t.id} model '${n}' lists '${r}' in builtInTools — not a registered builtin`)}function os(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 ss(e,t){let n=os(t).map(n=>{let r=e.find(n);if(!r)throw new N(`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 N(`config`,`Profile ${t.id}: outputs.validation checks a structured reply, so it needs outputs.structured`);let o=a.filter(e=>!n.some(t=>_a(t.jsonSchema,e)));if(o.length)throw new N(`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=>fa(t.jsonSchema,e)));if(s.length)throw new N(`config`,`Profile ${t.id}: outputs.validation.fields has ${s.join(`, `)}, which no structured schema reaches through object properties`)}function cs(e){let t=j(e)?.context;if(!t)return;let n=A;if(t.from.length===0||t.from.some(e=>!n.includes(e)))throw new N(`config`,`Profile ${e.id}: inputs.context.from must list ${A.join(` or `)}`);if(!(Number.isInteger(t.maxChars)&&t.maxChars>0))throw new N(`config`,`Profile ${e.id}: inputs.context.maxChars must be a positive integer`)}function ls(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 N(`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 N(`config`,`Profile ${e}: inputs.${t} must be a positive integer`)}function us(e,t,n){let r=new Map,i=i=>{let a=Uo(i),o=n&&a.type!==`host`?{...a,models:Object.fromEntries(Object.entries(a.models).map(([e,t])=>[e,be(n.require(t.provider,t.apiId),t,a.type)]))}:a;if(ns(e,o),rs(e,o),o.type!==`host`&&o.type!==`decision`&&o.type!==`embedding`){as(e,o),ls(o.id,j(o)),cs(o),ss(t,o);for(let[e,t]of Object.entries(o.models))t.compaction&&$o(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 N(`config`,`Unknown profile '${e}'`);return t},find:e=>r.get(e),has:e=>r.has(e),list:()=>[...r.values()],clear:()=>r.clear()}}var ds=`https://generativelanguage.googleapis.com/v1beta/models`;function fs(e){let t=e?.trim()??``;if(t.startsWith(`AIza`))return`gemini`;if(t.startsWith(`sk-or-`))return`openrouter`}function ps(e){let t;try{t=new URL(e.baseUrl)}catch{throw new N(`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 N(`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 N(`blocked`,`Local requests must stay on the configured origin.`))}}var ms=v({data:l(v({id:g().min(1)}))});async function hs(e,t){let n=ps(e);if(!n?.fetch)throw new N(`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 N(`network`,`Local model list returned HTTP ${r.status}.`);let i=ms.safeParse(await r.json());if(!i.success)throw new N(`request`,`The endpoint returned an invalid model list.`);return[...new Set(i.data.data.map(e=>e.id))]}var gs=`https://openrouter.ai/api/v1/models`,_s=`https://openrouter.ai/api/v1/embeddings/models`,vs=[{id:`gemini-embedding-2-preview`,label:`Gemini Embeddings 2 (preview)`},{id:`gemini-embedding-001`,label:`Gemini Embedding 001`}],ys=[{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)`}],bs={text:`text`,image:`image`,speech:`speech`,live:void 0,embedding:void 0},xs=v({data:l(v({id:g().min(1),name:g().optional(),architecture:v({output_modalities:l(g()).optional()}).optional()}))}),Ss=v({data:l(v({id:g().min(1),name:g().optional()}))}),Cs=v({models:l(v({name:g().min(1),displayName:g().optional(),supportedGenerationMethods:l(g()).optional()})).optional(),nextPageToken:g().optional()}),ws=5;async function Ts(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 N(`auth`,`${e} refused the key.`);if(!r.ok)throw new N(`network`,`${e} model list returned HTTP ${r.status}.`);return await r.json()}async function Es(e,t,n,r){let i=n?.trim();if(t===`embedding`&&!i)return[...e===`openrouter`?ys:vs];if(e===`openrouter`)return await Ds(t,i,r);if(!i)throw new N(`auth`,`Choose a key to list Gemini models.`);return await ks(t,i,r)}async function Ds(e,t,n){let r={signal:n,headers:{Accept:`application/json`,...t?{Authorization:[`Bearer`,t].join(` `)}:{}}};if(e===`embedding`){let e=Ss.safeParse(await Ts(`OpenRouter`,_s,r));if(!e.success)throw new N(`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=bs[e];if(!i)return[];let a=xs.safeParse(await Ts(`OpenRouter`,`${gs}?output_modalities=${i}`,r));if(!a.success)throw new N(`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 Os={live:`bidiGenerateContent`,embedding:`embedContent`};async function ks(e,t,n){let r=Os[e]??`generateContent`,i=[],a;for(let e=0;e<ws;e++){let e=new URL(ds);e.searchParams.set(`pageSize`,`1000`),a&&e.searchParams.set(`pageToken`,a);let o=Cs.safeParse(await Ts(`Google`,e.href,{signal:n,headers:{Accept:`application/json`,"x-goog-api-key":t}}));if(!o.success)throw new N(`bad_response`,`Google returned an invalid model list.`);for(let e of o.data.models??[]){if(!e.supportedGenerationMethods?.includes(r))continue;let t=e.name.replace(/^models\//,``);i.push({id:t,label:e.displayName??t})}if(a=o.data.nextPageToken,!a)break}return i}function As(e){return[...new Set([e.key,e.fallbackKey,...Object.values(e.models??{}).flatMap(e=>[e.keySlot,e.fallbackKeySlot])].filter(e=>!!e))]}function js(e,t){return Object.fromEntries(e.map(e=>[e,Object.hasOwn(t,e)?t[e]:void 0]))}var Ms=[`audio/webm;codecs=opus`,`audio/webm`,`audio/mp4`,`audio/wav`,`audio/mpeg`];function Ns(e){return e.join(`,`)}function Ps(e){let t=e?.attachments?.accept,n=e?.voice?.accept;return{text:e?.text!==!1,attachments:t?.length?{accept:t,acceptAttr:Ns(t)}:null,voice:n?.length?{accept:n}:null,maxFiles:e?.maxFiles,maxBytes:e?.maxBytes,maxTurnBytes:e?.maxTurnBytes,limitsByMime:e?.limitsByMime,slots:e?.slots,context:e?.context}}function Fs(e){return{text:e.text,attachments:e.attachments?{accept:e.attachments.accept}:void 0,voice:e.voice?{accept:e.voice.accept}:void 0,maxFiles:e.maxFiles,maxBytes:e.maxBytes,maxTurnBytes:e.maxTurnBytes,limitsByMime:e.limitsByMime,slots:e.slots,context:e.context}}function Is(e,t){let n=e=>(e??[]).map(({name:e,mimeType:t,sizeBytes:n})=>({name:e,mimeType:t,sizeBytes:n})),r=or({attachments:e.attachments?.accept,voice:e.voice?.accept,limits:Xn(Fs(e))},n(t.attachments),n(t.voice));return{ok:r.length===0,issues:r}}function Ls(e){let t=globalThis.MediaRecorder;if(t===void 0)return;let n=e=>t.isTypeSupported(e),r=e=>e.find(n);return e?.length?r(Ms.filter(t=>M(e,t)))??e.find(n):r(Ms)}var Rs=v({protocol:g(),provider:g(),apiId:g(),options:_(g(),u()).optional(),keySlot:g().optional(),fallbackKeySlot:g().optional(),efforts:_(g(),d(Oe)).optional(),defaultEffort:g().optional(),allowEffortSelect:o().optional(),summaries:o().optional(),maxOutputTokens:h().optional(),temperature:h().optional(),builtInTools:l(g()).optional(),compaction:v({maxTokens:h(),compactAt:h(),previousExchanges:h(),profile:g().optional(),timing:d(he),meter:d(O).optional()}).optional()}),zs=v({structured:i([g(),v({by:g(),map:_(g(),g()),fallback:g()}),p()]).optional(),streaming:v({mode:d(Pe).optional(),streamThoughts:o().optional()}).optional()}),Bs=v(Ke(dt,()=>d(lt))),Vs=v(Ke(jt,()=>Bs)),Hs=v({id:g(),label:g(),actions:Bs,names:l(g()),find:o()}),Us=v({hosts:l(g()),fromTools:o()}),Ws=v({quota:v({perDay:h()}).optional(),detect:Vs,patterns:a(d(jt),v({theorem:o(),names:l(g())})).optional(),host:l(Hs).optional(),allow:v({ungiven_images:Us,ungiven_links:Us}),blockedReply:v({onBlock:d(x),maxRetries:h()})}),Gs=i([o(),v({theorem:o(),host:o()})]),Ks=v({record:o(),writeTo:i([c(!1),g()]).optional(),sampleRate:h(),include:v({upstreamLog:o(),outboundWire:o(),evidenceRaw:o(),usage:o(),guardrailDecisions:o(),guardrailMatchPreview:o()}),scrub:v({sensitive:Gs,injection:Gs,canary:Gs}),resource:Ut,retainForDays:h(),rotateAfterMiB:h(),hasOnWriteError:o()}),qs=v({text:o(),attachments:v({accept:l(g()),acceptAttr:g()}).nullable(),voice:v({accept:l(g())}).nullable(),maxFiles:h().optional(),maxBytes:h().optional(),maxTurnBytes:h().optional(),limitsByMime:_(g(),h()).optional(),slots:_(g(),l(g())).optional(),context:v({from:l(d(A)),maxChars:h()}).optional()}),Js=v({allowContinue:l(d(D)).optional(),autoContinue:l(d(D)).optional(),maxContinues:h().optional()}),Ys=v({resumption:Js.optional()}),Xs=v({allow:l(g()),page:l(g()),t2Loader:g().optional(),parallel:o().optional()}),Zs={providerContinuation:v({history:d([`host`,`stateless`,`provider`]).optional()}).optional(),id:g(),models:_(g(),Rs),defaultModel:g(),allowModelSelect:o().optional(),maxSteps:h().optional(),labels:a(d(at),g()),guardrails:Ws.optional(),observability:Ks.optional()},Qs=i([g(),l(i([g(),t({private:g().min(1)})])).min(1).readonly()]),$s=v({handle:g(),system:Qs.optional(),systemByRole:_(g(),Qs).optional()}),Y=f(`type`,[v({...Zs,type:c(`text`),identity:$s,outputs:zs.optional(),inputs:qs,tools:Xs,turnBehaviour:v({resumption:Js.optional(),allowSteering:o().optional(),atStepLimit:d(je).optional()}).optional(),canStop:c(!0),allowSteering:o()}),v({...Zs,type:c(`image`),identity:$s,outputs:zs.optional(),image:v({aspectRatio:g().optional(),resolution:g().optional(),mimeType:g().optional(),quality:g().optional(),background:g().optional(),n:h().int().min(1).optional(),seed:h().int().optional(),outputCompression:h().int().min(0).max(100).optional(),references:l(i([v({mimeType:g(),data:g(),name:g().optional()}),v({mimeType:g(),uri:g(),name:g().optional()})])).optional(),includeText:o().optional()}),inputs:qs,tools:Xs,turnBehaviour:Ys.optional(),canStop:c(!0)}),v({...Zs,type:c(`speech`),identity:v({handle:g()}),outputs:zs.optional(),speech:v({voice:g().optional(),style:g().optional(),speed:h().optional(),format:d(Le).optional()}),inputs:qs,turnBehaviour:Ys.optional(),canStop:c(!0)}),v({...Zs,type:c(`live`),identity:$s,inputs:qs.pick({slots:!0,context:!0}).optional(),live:v({ingress:v({audio:o().optional(),video:o().optional(),text:o().optional()}).optional(),voice:g().optional(),vad:v({activityHandling:d(ve).optional(),startSensitivity:d(ye).optional(),endSensitivity:d(_e).optional(),prefixPaddingMs:h().optional(),silenceDurationMs:h().optional()}).optional(),sessionResumption:o().optional(),contextCompression:v({triggerTokens:h().optional(),slidingWindow:v({targetTokens:h().optional()})}).optional(),transcription:v({input:o().optional(),output:o().optional()}).optional()}),tools:Xs.pick({allow:!0,page:!0}),turnBehaviour:v({allowSteering:o().optional()}).optional()})]);function ec(e){let t=Ae(e),{sources:n,host:r,...i}=t.detect;return{quota:t.quota,detect:i,...n?{patterns:Object.fromEntries(Object.entries(n).map(([e,{theorem:t,matchers:n}])=>[e,{theorem:t,names:n.map(({name:e})=>e)}]))}:{},...r?{host:r.map(({id:e,label:t,actions:n,matchers:r,find:i})=>({id:e,label:t,actions:n,names:r.map(({name:e})=>e),find:!!i}))}:{},allow:{ungiven_images:tc(t.allow.ungiven_images),ungiven_links:tc(t.allow.ungiven_links)},blockedReply:t.blockedReply}}function tc(e){return{hosts:[...e.hosts??[]],fromTools:e.fromTools??!0}}function nc(e){return e===void 0||e===!1||typeof e==`string`?e:`custom`}function rc(e){if(!e)return;let t=Bt(e);return{record:t.record,writeTo:nc(t.writeTo),sampleRate:t.sampleRate,include:t.include,scrub:t.scrub,resource:t.resource,retainForDays:t.retainForDays,rotateAfterMiB:t.rotateAfterMiB,hasOnWriteError:!!t.onWriteError}}function ic(e){let{greeting:t,resumed:n,...r}=e??{};return r}function ac(e,t){let n=e.tools.filter(e=>`type`in e&&e.type===`function`&&e.answeredBy===`page`).map(e=>e.name);if(t){let e=q(t),r=qr(t);return{allow:[...K(t)],page:n,...e?.t2Loader?{t2Loader:e.t2Loader}:{},...r===void 0?{}:{parallel:r}}}return{allow:e.tools.filter(e=>!(`type`in e&&e.type===`builtin`)).map(e=>e.name),page:n}}function oc({allow:e,page:t}){return{allow:e,page:t}}function sc(e,t){let n=Ps(e.inputs),r=t?.identity??{handle:e.handle},i=t?ec(t.guardrails):void 0,a=t?rc(t.observability):void 0,o=e.outputs??void 0,s={id:e.id,identity:r,models:e.models,defaultModel:e.defaultModel,allowModelSelect:e.allowModelSelect,maxSteps:e.maxSteps,providerContinuation:e.providerContinuation,outputs:o,guardrails:i,observability:a,labels:Ue(t?.labels)};switch(e.type){case`text`:return Y.parse({...s,type:`text`,inputs:n,tools:ac(e,t),turnBehaviour:t?.type===`text`?t.turnBehaviour:void 0,canStop:!0,allowSteering:!t||ne(t)});case`image`:return Y.parse({...s,type:`image`,image:e.image??{},inputs:n,tools:ac(e,t),turnBehaviour:t?.type===`image`?t.turnBehaviour:void 0,canStop:!0});case`speech`:return Y.parse({...s,type:`speech`,speech:e.speech??{},inputs:n,turnBehaviour:t?.type===`speech`?t.turnBehaviour:void 0,canStop:!0});case`live`:return Y.parse({...s,type:`live`,live:ic(e.live),...e.inputs?{inputs:{slots:n.slots,context:n.context}}:{},tools:oc(ac(e,t))});default:return e.type}}function cc(e,t){let n=Vi(e,`interfaceFromProfile`);return sc(ea(t,n),n)}function lc(e){return s(t=>re.safeParse(e(t)).success)}var uc=[`running`,`gate`,`complete`,`error`,`cancel`],dc=s(e=>{let t=re.safeParse({type:`tool`,tool:e});if(!t.success||t.data.type!==`tool`||!(`phase`in t.data.tool))return!1;let{phase:n}=t.data.tool;return uc.some(e=>e===n)}),fc=_(g(),n()),pc=v({operationId:g().optional(),name:g(),callId:g(),arguments:fc,draft:g().optional(),reasoning:l(ce).optional(),stepId:g().optional(),edited:v({from:fc,to:fc}).optional(),activity:g().optional(),activityPast:g().optional(),outputDraft:g().optional(),state:dc.optional(),startedAt:h().optional(),endedAt:h().optional(),artifacts:l(n())}),mc=v({kind:d(Ce),native:g().optional()}),X={id:g()},hc=f(`kind`,[v({...X,kind:c(`user-text`),text:g()}),v({...X,kind:d([`user-attachment`,`user-voice`]),name:g(),mimeType:g(),sizeBytes:h(),data:g().optional()}),v({...X,kind:c(`thought`),text:g()}),v({...X,kind:c(`text`),text:g()}),v({...X,kind:c(`tool`),tool:pc}),v({...X,kind:c(`structured`),value:n(),draft:g().optional()}),v({...X,kind:c(`media`),mimeType:g(),data:g().optional(),url:g().optional(),previewUrl:g().optional()}),v({...X,kind:c(`grounding`),grounding:lc(e=>({type:`grounding`,grounding:e}))}),v({...X,kind:c(`citation`),sources:lc(e=>({type:`citation`,sources:e})),callId:g().optional()}),v({...X,kind:c(`evidence`),evidence:lc(e=>({type:`evidence`,evidence:e}))}),v({...X,kind:c(`guardrail`),guardrail:C}),v({...X,kind:c(`error`),message:g()}),v({...X,kind:c(`turn-done`),stop:mc.optional(),tokens:lc(e=>({type:`tokens`,tokens:e})).optional(),interactionId:g().optional(),compaction:o().optional(),workedMs:h().optional(),endedAt:h().optional()})]),gc=v({type:g()});function _c(e,t){return Object.hasOwn(e,t)}function vc(e,t){return e.map(e=>{let n=[...t,...e.path],r=`${n.map(String).join(`.`)||`(root)`} ${e.code}`;return e.code!==`invalid_union`||e.errors.length===0?r:`${r} [${e.errors.map(e=>vc(e,n)).join(` | `)}]`}).join(`; `)}function yc(e){return vc(e.issues,[])}function bc(e,t){return new N(`bad_response`,`${e} failed its wire check: ${yc(t)}`)}function Z(e,t,n){let r=e.safeParse(t);if(!r.success)throw bc(n,r.error);return r.data}function xc(e){return{type:`malformed`,error:new N(`bad_response`,e,{copy:{key:`session.part_skipped`}})}}function Sc(e,t){let n=gc.safeParse(t);if(!n.success)return xc(`a line without a kind failed its wire check: ${yc(n.error)}`);let{type:r}=n.data;if(!_c(e,r))return{type:`unsupported`,received:r,raw:t};let i=e[r].safeParse(t);return i.success?i.data:xc(`a '${r}' line failed its wire check: ${yc(i.error)}`)}function Cc(e){try{return{value:JSON.parse(e)}}catch(e){if(e instanceof SyntaxError)return;throw e}}function wc(e,t){let n=Cc(t);return n?Sc(e,n.value):xc(`a line is not JSON`)}function Tc(e){let t=Cc(e);if(!t)throw new N(`bad_response`,`a line is not JSON`);return t.value}var Ec=v({name:g(),mimeType:g(),data:g()}),Dc=v({slots:_(g(),g()).optional(),context:n().optional(),text:g().optional(),attachments:l(Ec).optional(),voice:l(Ec).optional()}),Oc=v({gateKind:d(Ie).optional(),sessionPermissions:l(g()).optional(),name:g().optional(),input:n().optional(),snapshot:S.optional(),promoted:l(g()).optional(),model:g().optional(),effort:g().optional()}),kc=g().trim().min(1);v({input:Dc,conversation:g().min(1).optional(),model:g().optional(),effort:g().optional(),turnId:kc.optional(),abandon:l(ke).min(1).optional(),replay:Oc.pick({sessionPermissions:!0}).optional(),transcript:l(hc).optional()});var Ac=[`approve`,`deny`],jc=i([t({unanswered:c(!0)}),t({output:n()}).refine(e=>`output`in e).transform(e=>({output:e.output}))]);v({gateId:g().min(1),operationId:g().min(1).max(256),decision:d(Ac),input:n().optional(),secret:g().optional(),page:jc.optional(),conversation:g().min(1).optional(),turnId:kc.optional(),replay:Oc.optional()}),v({turnId:kc,id:kc,inject:l(fe).min(1)});var Mc=v({type:c(`conversation`),ref:g().min(1),posted:c(!0).optional()}),Nc={...le,conversation:Mc},Pc=v({transcript:l(hc),paused:v({events:l(re),blocks:l(hc)}).optional()});v({conversation:g().min(1)}),v({conversation:g().min(1),at:h().int().min(-1)});var Fc=v({conversation:g().min(1),view:Pc}),Ic=class extends Error{kind;publicMessage;internalMessage;copy;constructor(e,t,n,r){super(n??t??e),this.name=`TheoremStreamError`,this.kind=e,t&&(this.publicMessage=t),n&&(this.internalMessage=n),r&&(this.copy=r)}};function Lc(e){return e instanceof Ic}function Rc(e){return e?.trim()||void 0}var zc=v({error:g().optional(),errorKind:w.optional(),errorCopy:me.optional(),errorInternal:g().optional()}),Bc=zc;function Vc(e,t){let n=Rc(e.error),r=Rc(e.errorInternal);return new Ic(e.errorKind??t,n,r&&r!==n?r:void 0,e.errorCopy)}function Hc(e){return!Lc(e)||e.copy===void 0?!1:(Array.isArray(e.copy)?e.copy:[e.copy]).some(e=>e.key===`session.conversation_unknown`)}function Uc(e,t){let n=wc(e,t);if(n.type===`error`)throw Vc(zc.parse(n),`internal`);return n}function Wc(e,t,n){let r=e.split(`
|
|
7
|
-
`),i=r.pop()??``;for(let e of r)e.trim()&&n(Uc(t,e));return i}async function Gc(e,t,n,r){if(!e.body)throw new N(`bad_response`,`stream reply has no body`);let i=e.body.getReader(),a=new TextDecoder,o=``,s=()=>{i.cancel()};r?.addEventListener(`abort`,s,{once:!0});try{for(;;){Ve(r);let{done:e,value:s}=await i.read();if(e)break;o=Wc(o+a.decode(s,{stream:!0}),t,n)}let e=o.trim();e&&n(Uc(t,e))}finally{r?.removeEventListener(`abort`,s)}}async function Kc(e){let t=typeof e.headers==`function`?await e.headers():e.headers,n=new Headers(t);return n.set(`content-type`,`application/json`),n}async function qc(e,t){let n=await e.text(),r;try{r=JSON.parse(n),t?.(r)}catch{return Vc({errorInternal:`HTTP ${String(e.status)}`},ie(e.status))}let i=zc.safeParse(r);return i.success?Vc({...i.data,errorInternal:i.data.errorInternal??`HTTP ${String(e.status)}`},ie(e.status)):new N(`bad_response`,`HTTP ${String(e.status)} error body failed its wire check`)}async function Jc(e,t,n){let r=n.fetch??globalThis.fetch.bind(globalThis);try{return await r(e,{...t,headers:await Kc(n),credentials:n.credentials??`same-origin`})}catch(e){throw T(e)?e:new N(`network`,se(e),{cause:e})}}async function Yc(e,t,n,r,i={}){await Gc(await Xc(e,t,i),n,r,i.signal)}async function Xc(e,t,n){let r=await Jc(e,{method:`POST`,body:JSON.stringify(t),signal:n.signal},n);if(!r.ok)throw await qc(r);return r}async function Zc(e,t,n={}){await Xc(e,t,n)}async function Q(e,t,n={}){let r=await Jc(e,{...t.body===void 0?{method:`GET`}:{method:`POST`,body:JSON.stringify(t.body)},signal:t.signal},n);if(!r.ok)throw await qc(r,t.failed);return Tc(await r.text())}async function Qc(e,t,n={}){let{signal:r,...i}=n;return Z(Pc,await Q(e,{body:t,signal:r},i),`the conversation`)}async function $c(e,t,n
|
|
6
|
+
`)}:null}function ki(e){let t=e.input?.context??{};return[...A].reverse().filter(e=>t[e]!==void 0).map(e=>Tt(e,Ar(t[e])))}function Ai(e,t){if(t.continueFrom&&He.includes(e.type)){if(t.input?.text)throw new N(`request`,`Profile ${e.id}: a continueFrom turn takes no input.text — its user message is the continue instruction`);return P(`continue.instruction`,{},e.labels)}}function ji(e){return e.type===`image`&&e.image.references?Di(e.image.references):[]}function Mi(e,t){let n=t.input?.attachments??[],r=t.input?.voice??[];return[...ji(e),...Di(n),...Di(r)]}function Ni(e,t){let n=[],r=Oi(e,t);return r&&n.push(r),n.push(...Mi(e,t)),n}function Pi(e,t){let n=t.input?.slots;if(!n)return;let r=j(e)?.slots??{};for(let[t,i]of Object.entries(n)){let n=Object.hasOwn(r,t)?r[t]:void 0;if(!n)throw new N(`request`,`Profile ${e.id} has no slot '${t}'`);if(!n.includes(i))throw new N(`request`,`Profile ${e.id}: slot '${t}' takes ${n.join(`, `)}, not '${i}'`)}}function Fi(e,t){let n=t.input?.context;if(!n)return;let r=j(e)?.context;for(let[t,i]of Object.entries(n))if(i!==void 0){if(!A.includes(t)||!r?.from.some(e=>e===t))throw new N(`request`,`Profile ${e.id} takes no context from '${t}'`);if(Ar(i).length>r.maxChars)throw new N(`request`,`Profile ${e.id}: context from '${t}' is over inputs.context.maxChars (${String(r.maxChars)})`)}}var Ii=/\{([A-Za-z_][\w-]*)\}/g;function Li(e,t,n,r){let i=j(e)?.slots;return i?t.replace(Ii,(t,a)=>{if(!Object.hasOwn(i,a))return t;let o=n&&Object.hasOwn(n,a)?n[a]:void 0;if(o===void 0)throw new N(`request`,`Profile ${e.id}: ${r} uses slot '${a}', and the request chose no value for it`);return o}):t}function Ri(e,t){let{handle:n}=e.identity,r=e.type===`speech`?void 0:e.identity.systemByRole;return t&&r&&Object.hasOwn(r,t)?t:n}function zi(e,t,n){if(e.type===`speech`)return[];let{systemByRole:r,system:i}=e.identity,a=r?.[t]||i||``;return a?Sr(xr(a,`Profile ${e.id} identity.system`,t=>Li(e,t,n,`identity.system`))):[]}function Bi(e,t){return Cr([zi(e,Ri(e,t.input?.role),t.input?.slots),t.system===void 0?[]:Sr(t.system)])}function Vi(e){return e.type!==`host`&&e.type!==`decision`&&e.type!==`embedding`}function Hi(e,t){if(Vi(e))return e;throw e.type===`host`?new N(`request`,`Profile ${e.id}: type 'host' never runs a model — ${t} is not supported; execute tools with invokeTool`):e.type===`embedding`?new N(`request`,`Profile ${e.id}: type 'embedding' runs through runEmbedding — ${t} is not supported`):new N(`request`,`Profile ${e.id}: type 'decision' runs through runDecision — ${t} is not supported`)}function Ui(e,t){if(t){if(!e.allowModelSelect)throw new N(`request`,`Profile ${e.id} does not allow model selection`);if(!e.models[t])throw new N(`request`,`Unknown model '${t}' for ${e.id}`);return t}return e.defaultModel}function Wi(e,t,n,r){let i=t.efforts;if(!i||Object.keys(i).length===0){if(r)throw new N(`request`,`Profile ${e.id} model '${n}' has no selectable efforts`);return}let a=Object.keys(i);if(r){if(!t.allowEffortSelect)throw new N(`request`,`Profile ${e.id} model '${n}' does not allow effort selection`);let a=i[r];if(!a)throw new N(`request`,`Unknown effort '${r}' for ${e.id} model '${n}'`);return a}return i[t.defaultEffort??a[0]]}function Gi(e){if(e.summaries===!0)return`auto`;if(e.summaries===!1)return`none`}function Ki(e,t){if(e.type===`live`)return null;let n=e.outputs?.structured;if(!n)return null;if(typeof n==`string`)return n;let r=t?.[n.by];if(r){let e=n.map[r];if(e)return e}return n.fallback}function qi(e){return e.type===`live`||e.outputs?.streaming?.mode!==`buffered`}function Ji(e,t){return e.type===`live`?`live`:`turn`}function Yi(e,t){if(!t.continueFrom)return;if(e.type===`live`)throw new N(`request`,`Profile ${e.id}: type 'live' uses live.sessionResumption, not turnBehaviour.resumption/continueFrom`);let n=Ne(e)?.maxContinues;if(n===void 0)return;let r=t.continuation;if(r===void 0)throw new N(`request`,`Profile ${e.id}: continueFrom requires TurnRequest.continuation when turnBehaviour.resumption.maxContinues is set`);if(r<1)throw new N(`request`,`Profile ${e.id}: continuation must be >= 1`);if(r>n)throw new N(`request`,`Profile ${e.id}: continuation ${r} exceeds turnBehaviour.resumption.maxContinues (${n})`)}function Xi(e,t){return W(Ae(t),[`live_reply`])?{...e,transcription:{...e?.transcription,output:!0}}:e}function Zi(e){let{detect:t}=Ae(e.guardrails);return e.type!==`speech`&&Mt(t,`canary_leak`)?Lt():``}function Qi(e,t,n,r){if(!r)return;let i={};for(let[a,o]of Object.entries(r)){if(!n.builtInTools?.includes(a))throw new N(`request`,`Profile ${e.id}: builtInArgs names '${a}', which model '${t}' does not list in builtInTools`);i[a]=o}return i}function $i(e,t,n){let r=Hi(e.profiles.get(t.profile),`resolveTurn`);Pi(r,t),Fi(r,t);let i=Rr(t,r),a=i.input??{};Yi(r,i);let o=n??Ui(r,i.model),s=Ee(r,o),c=ri(e.tools,r,i,o),l=c.builtins,u=Ki(r,a.slots);xi(r,u),Si(r,i);let d=Qi(r,o,s,i.builtInArgs),f=Ji(r,s);return{profile:r,generation:{model:o,apiId:s.apiId,transport:f,stream:qi(r),thinking:Wi(r,s,o,i.effort),summaries:Gi(s),maxOutputTokens:s.maxOutputTokens,temperature:s.temperature,builtins:l,builtInArgs:d,sessionId:i.sessionId,tools:c,sessionPermissions:i.sessionPermissions,execution:i.execution,pageExecution:i.pageExecution,history:a.history,maxSteps:r.maxSteps??20,structured:u?{id:u,jsonSchema:e.schemas.get(u).jsonSchema}:null,image:Ti(r),speech:Ci(r,i),live:r.type===`live`?Xi(r.live,r.guardrails):void 0,input:Ni(r,i),canary:Zi(r),resolvedSystem:Bi(r,i),host:i.host}}}function ea(e){return e.type===`image`?e.image:null}function ta(e,t){let n=Hi(t,`projectProfile`),{identity:r}=n,i=j(n)??null,a=n.type===`live`?null:n.outputs??null;return{id:n.id,type:n.type,handle:r.handle,models:n.models,defaultModel:n.defaultModel,allowModelSelect:n.allowModelSelect,maxSteps:n.maxSteps,tools:mi(e,n),inputs:i,outputs:a,image:ea(n),speech:n.type===`speech`?n.speech:null,live:n.type===`live`?n.live:null}}function na(e,t){return ta(e.tools,e.profiles.get(t))}function ra(e){return e==null}function q(e){return ra(e)||typeof e!=`object`||Array.isArray(e)?null:e}function ia(e){let t=q(e);return!t||t.type!==void 0&&t.type!==`object`?null:t}function aa(e){let t=e.required;return Array.isArray(t)?t.filter(e=>typeof e==`string`):[]}function oa(e){let t=e.properties;return q(t)??{}}function sa(e,t){return e?`${e}.${t}`:t}function ca(e,t){t.push({path:e,error:`required field '${e}' is missing`})}async function la(e,t,n,r,i){if(!n)return;let a=await n(t,r);a.isValid||i.push({path:e,error:a.error||a.finding||`Validation failed for '${e}'`})}async function ua(e){let{path:t,propSchema:n,child:r,isRequired:i,fields:a,slots:o,failures:s}=e;if(ra(r)){i&&ca(t,s);return}await la(t,r,a?.[t],o,s);let c=ia(n),l=c?q(r):null;c&&l&&await da(c,l,t,a,o,s)}async function da(e,t,n,r,i,a){let o=oa(e),s=new Set(aa(e)),c=new Set([...Object.keys(o),...s]),l=q(t);for(let e of c)await ua({path:sa(n,e),propSchema:o[e],child:l?.[e],isRequired:s.has(e),fields:r,slots:i,failures:a})}async function fa(e,t,n,r){let i=ia(e);if(!i)throw new N(`config`,`structured validation requires a JSON Schema object root`);let a=[];if(!q(t)){for(let e of aa(i))ca(e,a);return a}return await da(i,t,``,n,r,a),a}function pa(e,t){let n=e;for(let e of t.split(`.`)){let t=ia(n);if(!t)return!1;let r=oa(t);if(!Object.hasOwn(r,e)&&!aa(t).includes(e))return!1;n=r[e]}return!0}function ma(e){return e.map(e=>e.error).join(`; `)}function ha(e,t){let n=e;for(let e of t.split(`.`))n=q(n)?.[e];return n}function ga(e,t,n){let[r,...i]=t.split(`.`),a=q(e)??{};return r===void 0?e:{...a,[r]:i.length?ga(a[r],i.join(`.`),n):n}}async function _a(e,t,n){let r=[];for(let[i,a]of Object.entries(t??{})){let t=ha(e,i);if(Array.isArray(t))for(let[e,o]of t.entries()){let t=await a.check(o,n);t.isValid||r.push({path:i,index:e,item:o,reason:t.error||t.finding||`Validation failed for '${i}'`,onFail:a.onFail})}}return r}function va(e,t){let n=e;for(let e of t.split(`.`)){let t=ia(n);if(!t)return;n=oa(t)[e]}let r=q(n);if(r?.type===`array`)return q(r.items)??void 0}var ya=class extends Error{failure;constructor(e){super(e.message),this.failure=e}},ba=new Set([`text`,`image`,`speech`]),xa=g().regex(/\S/),Sa=t({mimeType:g(),data:m(),name:g().optional()}),Ca=t({mimeType:g(),uri:g(),name:g().optional()}),wa=t({voice:g().optional(),style:g().optional(),speed:h().positive().optional()});function Ta(e){return t(Object.fromEntries(Object.entries(e).map(([e,t])=>[e,d(t).optional()])))}var Ea=new Set([`text`,`attachments`,`voice`,`slots`,`speech`]);function Da(e,t){if(!e.hostFields)return{sent:t};let n={...t},r={};for(let t of Object.keys(e.hostFields))n[t]!==void 0&&(r[t]=n[t]);let{text:i,attachments:a,voice:o,slots:s,speech:c}=t;return{sent:{text:i,...a?{attachments:a}:{},...o?{voice:o}:{},...s?{slots:s}:{},...c?{speech:c}:{}},hostInput:r}}function Oa(e,n){let{inputs:r}=e,a={text:xa};r?.attachments&&(a.attachments=l(i([Sa,Ca])).optional()),r?.voice&&(a.voice=l(Sa).optional()),r?.slots&&(a.slots=Ta(r.slots).optional()),e.type===`speech`&&(a.speech=wa.optional());for(let e of n?.hostOnly??[]){if(!a[e])throw new N(`config`,`Tool '${n?.name}' keeps '${e}' for the host, which its profile does not take`);delete a[e]}for(let[e,t]of Object.entries(n?.fieldText??{})){let r=a[e];if(!r)throw new N(`config`,`Tool '${n?.name}' describes '${e}', which its profile does not take`);a[e]=r.describe(t)}for(let[e,t]of Object.entries(n?.hostFields??{})){if(Ea.has(e))throw new N(`config`,`Tool '${n?.name}' declares the host field '${e}', which is a field of every agent tool`);a[e]=t}return t(a)}var ka=v({text:g().optional(),structured:n().optional(),removed:l(v({path:g(),reason:g(),item:n()})).optional(),parts:l(b).optional(),sources:l(ue).optional()});function Aa(e){return e.type===`speech`||(e.type===`text`||e.type===`image`)&&e.inputs.text!==!1}function ja(e){return e.type===`builtin`?!1:e.permission!==`auto`||`auth`in e&&e.auth!==void 0&&(e.auth.onUnauthenticated??`gate`)===`gate`}function Ma(e,t){if(!ba.has(e.type))return`it is a ${e.type} profile; an agent tool runs a text, image, or speech profile`;if(!Aa(e))return`it does not take text`;for(let n of K(e)){let e=t(n);if(!e)return`its tool '${n}' is not registered; register it first`;if(ja(e))return`its tool '${n}' can stop on a gate; give it permission 'auto' and no sign-in`}}function Na(e,t,n){let r=`Agent tool "${e.name}"`,i=e.maxCallsPerTurn;if(i!==void 0&&!(Number.isInteger(i)&&i>0))throw new N(`config`,`${r}: maxCallsPerTurn must be a whole number above 0`);let a=t(e.profile);if(!a)throw new N(`config`,`${r}: profile '${e.profile}' must be registered before the tool`);let o=Ma(a,n);if(o)throw new N(`config`,`${r} can't run '${e.profile}': ${o}`);return a}function Pa(e){if(!e)return`delegated`;let t=`models`in e&&Object.values(e.models).some(e=>(e.builtInTools?.length??0)>0);return K(e).length===0&&!t?`local`:`delegated`}function Fa(e){let t=oe(e),n=t.flatMap(e=>e.type===`text`?[e.text]:[]).join(``),r=ae(t,e=>e.type===`structured`),i=r?.structured,a=t.flatMap(e=>e.type===`media`?[{type:e.media.mimeType.startsWith(`audio/`)?`audio`:`image`,mimeType:e.media.mimeType,data:e.media.data}]:[]),o=t.flatMap(e=>e.type===`citation`?e.sources:[]);return{...i===void 0?{text:n}:{structured:i},...r?.removed?.length?{removed:r.removed}:{},...a.length>0?{parts:a}:{},...o.length>0?{sources:o}:{}}}function Ia(e,t,n){return{...e,type:`agent`,input:t,output:ka,sources:e=>e.sources??[],...n}}var La=256,Ra=18e5,za=/^[\x21-\x7E]{1,256}$/;function Ba(e=Date.now){let t=new Map,n=new Map;return{get(n){let r=t.get(n);if(r&&(t.delete(n),!(e()-r.usedAt>Ra)))return t.set(n,{...r,usedAt:e()}),{id:r.id,protocolVersion:r.protocolVersion}},open(r,i){let a=n.get(r);if(a)return a;let o=i().then(n=>{t.delete(r),t.set(r,{...n,usedAt:e()});for(let e of t.keys()){if(t.size<=La)break;t.delete(e)}return n}).finally(()=>n.delete(r));return n.set(r,o),o},drop(e,n){t.get(e)?.id===n&&t.delete(e)},clear(){t.clear(),n.clear()}}}function Va(e){return e!==null&&za.test(e)}async function Ha(e,t){let n=JSON.stringify([e,Object.entries(t).map(([e,t])=>[e.toLowerCase(),t]).sort(([e],[t])=>e<t?-1:+(e>t))]),r=await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(n));return[...new Uint8Array(r)].map(e=>e.toString(16).padStart(2,`0`)).join(``)}function Ua(e,t,n){if(!e||typeof e!=`object`||Array.isArray(e))return n.push(`${t}: schema must be an object`),!1;let r=typeof e.type==`string`||Array.isArray(e.type),i=e.anyOf!==void 0||e.oneOf!==void 0;if(!r&&!i){if(t!==`$`)return!0;n.push(`${t}: missing type or combinator`)}return e.type===`array`&&e.items===void 0&&n.push(`${t}: array schema must define items`),!0}function Wa(e,t,n,r){let i=Array.isArray(t)?t:[];for(let t of i)typeof t==`string`&&!Object.hasOwn(e,t)&&r.push(`${n}: required key '${t}' missing from properties`);for(let[t,i]of Object.entries(e))i&&typeof i==`object`&&Ga(i,`${n}.properties.${t}`,r)}function Ga(e,t,n){if(!Ua(e,t,n))return;let r=e.properties;r&&typeof r==`object`&&!Array.isArray(r)&&Wa(r,e.required,t,n),e.items&&typeof e.items==`object`&&!Array.isArray(e.items)&&Ga(e.items,`${t}.items`,n);for(let r of[`anyOf`,`oneOf`]){let i=e[r];Array.isArray(i)&&i.forEach((e,i)=>{e&&typeof e==`object`&&Ga(e,`${t}.${r}[${i}]`,n)})}}function Ka(e,t){let n=[];if(Ga(e,`$`,n),n.length>0)throw new N(`config`,`Invalid tool ${t} schema: ${n.join(`; `)}`)}function qa(e,t=`output`){let n=r(e,{target:`draft-7`,io:t});return delete n.$schema,n.type||=`object`,n}function Ja(e){if(typeof e!=`object`||!e)return e;if(Array.isArray(e))return e.map(Ja);let t={};for(let n of Object.keys(e))n!==`__proto__`&&n!==`constructor`&&n!==`prototype`&&(t[n]=Ja(e[n]));return t}function Ya(e){let t=/^[a-z][a-z0-9+.-]*:\/\/[^/?#]*/i.exec(e)?.[0];if(!t||/[{}]/.test(t))throw new N(`config`,`Endpoint "${e}" must start with a fixed scheme and host; placeholders belong in the path or query`)}var Xa=class{value;constructor(e){this.value=e}};function Za(e){return new Xa(e)}function Qa(e){return(t,n)=>{let{page:r}=n;if(r&&`output`in r)return Za(r.output);let{labels:i}=n.profile;throw r?.timedOut?Error(P(`tool.page_timed_out`,{},i)):Error(P(`tool.page_no_answer`,{tool:e},i))}}function $a(e){let t=qa(e.input,`input`);Ka(t,`input`);let n=qa(e.output,`output`);Ka(n,`output`);let r={activity:{input:t},activityPast:{input:t,output:n},activityFailed:{input:t},request:{input:t}};for(let t of[`activity`,`activityPast`,`activityFailed`,`request`]){let n=e.labels?.[t],i=n?Be(n,r[t]):void 0;if(i)throw new N(`config`,`Tool "${e.name}" ${t} label: ${i}`)}return{inputSchema:t,outputSchema:n}}function eo(e,t){if(t&&(typeof t.service!=`string`||!t.service.trim()))throw new N(`config`,`Tool "${e}" signs in with slot "${t.slot}" but names no service`)}function to(e,t,n=[]){if(t?.queryParam===void 0)return;let r=t.queryParam.trim()?t.type===`api_key`?t.headerName!==void 0||t.headerPrefix!==void 0?`is set with headerName or headerPrefix; the key goes in one place`:n.includes(t.queryParam)?`"${t.queryParam}" is also one of mapping.queryParams`:void 0:`is set on a '${t.type}' sign-in; only an API key goes in the URL`:`is blank`;if(r)throw new N(`config`,`Tool "${e}" auth.queryParam ${r}`)}function no(e,t){if(t!==void 0&&!(Number.isInteger(t.requests)&&t.requests>0&&Number.isFinite(t.windowMs)&&t.windowMs>0))throw new N(`config`,`Tool "${e}" limit needs a whole number of requests above 0 and a window above 0 ms`)}function ro(e,t){if(!(t===void 0||Number.isFinite(t)&&t>0))throw new N(`config`,`Tool "${e}" timeoutMs needs a finite number of ms above 0`)}function io(e){return Ya(e.endpoint),eo(e.name,e.auth),to(e.name,e.auth,e.mapping?.queryParams),no(e.name,e.limit),ro(e.name,e.timeoutMs),{...e,type:`http`,...$a(e)}}function ao(e){return eo(e.name,e.auth),to(e.name,e.auth),{...e,type:`mcp`,...$a(e)}}function oo(e){eo(e.name,e.auth),to(e.name,e.auth);let t=e.answeredBy===`page`?Qa(e.name):e.handler;if(typeof t!=`function`)throw new N(`config`,`Tool '${e.name}' needs a handler, or answeredBy: 'page'`);return{...e,handler:t,type:`function`,...$a(e)}}function so(e,t,n){if(e.type===`builtin`)return e;if(e.type===`agent`){let r=Na(e,t,n),i=j(r),a=Oa({type:r.type,...i?{inputs:i}:{}},e);return Ia(e,a,$a({...e,input:a,output:ka}))}return e.type===`http`?io(e):e.type===`mcp`?ao(e):oo(e)}function co(e=()=>void 0){let t=new Map,n=Ba(),r=e=>t.get(e),i=n=>{let i=so(n,e,r);return t.set(i.name,i),i};return{register:i,registerMany:e=>e.map(e=>i(e)),get:r,require(e){let t=r(e);if(!t)throw new N(`config`,`Tool '${e}' is not registered`);return t},has:e=>t.has(e),list:()=>[...t.values()],findProfile:e,reset:()=>{t.clear(),n.clear()},mcpSessions:n}}function lo(e,t,n,r){if(!n.provider?.trim()||!n.apiId?.trim())throw new N(`config`,P(`provider.binding_identity`))}function uo(e){bo(e.id,e.models),Ho(e.id,e.observability),us(e.id,e.inputs);for(let[t,n]of Object.entries(e.models))So(e.id,t,n);return{type:`embedding`,id:e.id,identity:{handle:e.identity.handle},models:e.models,defaultModel:xo(e.id,e),allowModelSelect:e.allowModelSelect,inputs:e.inputs,guardrails:e.guardrails,observability:e.observability,labels:e.labels}}function fo(e,t,n,r){let i=r.safeParse(n);if(!i.success)throw new N(`config`,`Profile ${e} model '${t}': ${i.error.issues.map(e=>`${e.path.join(`.`)}: ${e.message}`).join(`; `)}`)}function po(e,t,n){if(fo(e,t,n,de),lo(e,t,n,`decision`),`retry`in n)throw new N(`config`,`Profile ${e} model '${t}': decision retry configuration is unsupported; POSTs are never retried`);if(n.timeoutMs!==void 0&&(!Number.isFinite(n.timeoutMs)||n.timeoutMs<=0))throw new N(`config`,`Profile ${e} model '${t}' timeoutMs must be > 0`)}function mo(e){let t=e.models?zr(e.models):void 0;if(!t)throw new N(`config`,`Profile ${e.id}: type 'decision' must declare exactly one model`);po(e.id,t,e.models[t])}function ho(e){if(e.inputs.state!==`json`)throw new N(`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 N(`config`,`Profile ${e.id}: decision inputs.maxStateBytes must be a positive integer`);if(!e.decision.contract.trim())throw new N(`config`,`Profile ${e.id}: decision.contract must be non-empty`)}function go(e){return mo(e),ho(e),Ho(e.id,e.observability),{...e,identity:{handle:e.identity.handle}}}function _o(e){return e===void 0?{}:{parallel:e}}function vo(e){return yo(e.id,e.tools),Ho(e.id,e.observability),{type:`host`,id:e.id,tools:{allow:e.tools.allow,..._o(e.tools.parallel)},guardrails:e.guardrails,observability:e.observability,labels:e.labels}}function yo(e,t){if(!Array.isArray(t.allow))throw new N(`config`,`Profile ${e}: type 'host' must set tools.allow`)}function bo(e,t){if(Object.keys(t).length===0)throw new N(`config`,`Profile ${e} must declare at least one model`)}function xo(e,t){let n=t.defaultModel??zr(t.models);if(!n)throw new N(`config`,`Profile ${e} must set defaultModel when more than one model is declared`);if(!t.models[n])throw new N(`config`,`Profile ${e} defaultModel '${n}' is not declared`);return n}function So(e,t,n){Co(e,t,n),fo(e,t,n,we),Co(e,t,n)}function Co(e,t,n){let r=n.efforts;if(!r||Object.keys(r).length===0){if(n.defaultEffort||n.allowEffortSelect)throw new N(`config`,`Profile ${e} model '${t}': defaultEffort and allowEffortSelect require efforts`);return}for(let[n,i]of Object.entries(r))if(!Oe.includes(i))throw new N(`config`,`Profile ${e} model '${t}' effort '${n}': '${i}' is not a thinking level (${Oe.join(`, `)})`);let i=Object.keys(r),a=n.defaultEffort??(i.length===1?i[0]:void 0);if(!a)throw new N(`config`,`Profile ${e} model '${t}' must set defaultEffort when more than one effort is declared`);if(!r[a])throw new N(`config`,`Profile ${e} model '${t}' defaultEffort '${a}' is not declared`);if(n.allowEffortSelect&&i.length<2)throw new N(`config`,`Profile ${e} model '${t}' allowEffortSelect requires at least two efforts`)}function wo(e){return{providerContinuation:e.providerContinuation?pe.parse(e.providerContinuation):{},models:e.models,defaultModel:xo(e.id,e),allowModelSelect:e.allowModelSelect,maxSteps:e.maxSteps}}function To(e,t,n){if(n?.length){for(let r of n)if(!k(r))throw new N(`config`,`Profile ${e}: turnBehaviour.resumption.${t} may only include ContinueStopKind (length | stream_incomplete | provider_error); got '${r}'`)}}function Eo(e,t){t&&(To(e,`allowContinue`,t.allowContinue),To(e,`autoContinue`,t.autoContinue))}function Do(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Oo(e,t){let n=[e];for(let e of t)n=n.flatMap(t=>Do(t)?e===`*`?Object.values(t):[t[e]]:[]);return n}var ko=Object.entries(y).filter(([,e])=>e.required===!0).map(([e,t])=>[e,t.profileTypes]).sort(([e],[t])=>e.split(`.`).length-t.split(`.`).length);function Ao(e){if(!Do(e))throw new N(`config`,`Profile definition must be an object`);let t=typeof e.id==`string`&&e.id.trim()?e.id:void 0;if(!t)throw new N(`config`,`Profile definition must set id`);if(!Te.find(t=>t===e.type))throw new N(`config`,`Profile ${t}: type must be one of ${Te.join(`, `)}`)}function jo(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 N(`config`,`Profile ${e.id.slice(0,64)}: ${t} must be at most ${i} characters`)}function Mo(e){let{id:t,type:n}=e,r=e;for(let[e,i]of ko){if(i&&!i.includes(n))continue;let a=xe(e),o=Oo(r,a.slice(0,-1)),s=a[a.length-1];if(o.some(e=>{if(!Do(e))return!1;let t=e[s];return t==null||t===``}))throw new N(`config`,`Profile ${t}: type '${n}' must set ${a.join(`.`)}`)}}function No(e){let{id:t,type:n}=e;if(n!==`live`&&ze(`inputs`).includes(n)&&e.inputs==null)throw new N(`config`,`Profile ${t}: type '${n}' must set inputs`)}function Po(e){let[t]=De(e);if(!t)return;let{offValue:n,reason:r}=t.scope,i=n===void 0?``:` (other than ${n})`;throw new N(`config`,`Profile ${e.id}: type '${e.type}' must not set ${t.path}${i} — ${r}`)}function Fo(e,t){let n=t.turnBehaviour;Eo(e,n?.resumption)}function Io(e,t){let n=t=>new N(`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 Lo(e,t){let n=t=>new N(`config`,`Profile ${e}: ${t}`),r=Object.keys(t??{}).find(e=>!Ro.includes(e));if(r!==void 0)throw n(`guardrails.${r} is not a setting; it takes ${Ro.join(`, `)}`);Bo(t?.blockedReply,n)}var Ro=[`quota`,`detect`,`blockedReply`,`network`,`taint`],zo=[`onBlock`,`maxRetries`];function Bo(e,t){if(e===void 0)return;let n=Object.keys(e).find(e=>!zo.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&&!x.includes(r))throw t(`guardrails.blockedReply.onBlock must be one of ${x.join(`, `)}`);if(i!==void 0&&(!Number.isInteger(i)||i<0))throw t(`guardrails.blockedReply.maxRetries must be a non-negative integer`)}function Vo(e){let t=e.guardrails?.detect,n=e.type===`host`?Ot(`guardrails.detect`,t,It):Ot(`guardrails.detect`,t);if(n!==void 0)throw new N(`config`,`Profile ${e.id}: ${n}`)}function Ho(e,t){try{let n=Bt(t);if(!Number.isFinite(n.retainForDays))throw new N(`config`,`Profile ${e}: observability.retainForDays must be a finite number`);if(n.rotateAfterMiB<=0||!Number.isFinite(n.rotateAfterMiB))throw new N(`config`,`Profile ${e}: observability.rotateAfterMiB must be a positive number`)}catch(t){if(t instanceof N&&t.message.startsWith(`Profile `))throw t;let n=t instanceof Error?t.message:String(t);throw new N(`config`,`Profile ${e}: ${n}`)}}function Uo(e){if(e.type===`host`||e.type===`decision`||e.type===`speech`||e.type===`embedding`)return;let{system:t,systemByRole:n}=e.identity;t!==void 0&&br(t,`Profile ${e.id} identity.system`);for(let[t,r]of Object.entries(n??{}))br(r,`Profile ${e.id} identity.systemByRole.${t}`)}function Wo(e){Ao(e);for(let t of[`key`,`fallbackKey`,`protocol`,`provider`])if(t in e)throw new N(`config`,P(`provider.profile_configuration`,{profile:e.id,field:t}));if(Po(e),No(e),Mo(e),jo(e),e.labels&&rt(e.labels,`Profile ${e.id}`),Uo(e),Vo(e),e.type===`host`)return vo(e);if(e.type===`decision`)return go(e);if(e.type===`embedding`)return uo(e);bo(e.id,e.models),Fo(e.id,e),Lo(e.id,e.guardrails),e.type===`text`&&Io(e.id,e.outputs?.validation),Ho(e.id,e.observability);for(let[t,n]of Object.entries(e.models))So(e.id,t,n);let t=e.type===`speech`?{handle:e.identity.handle}:{handle:e.identity.handle,system:e.identity.system,systemByRole:e.identity.systemByRole},n=e.guardrails,r=e.observability,i=e.labels,a=wo(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},Xo(o.id,o.inputs.attachments?.accept),Yo(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,..._o(e.tools.parallel)},turnBehaviour:e.turnBehaviour,guardrails:n,observability:r,labels:i},Vt(o),Qo(o.id,o.live.contextCompression),Zo(o);break;default:throw new N(`config`,`Unknown profile type '${String(e)}'`)}return qo(o),Go(o),Ko(o),o}function Go(e){let{maxSteps:t}=e;if(!(t===void 0||Number.isInteger(t)&&t>0))throw new N(`config`,`Profile ${e.id}: maxSteps must be a whole number of 1 or more; leave it out for the default of 20`)}function Ko(e){if(e.type===`text`&&e.turnBehaviour?.atStepLimit===`answer`&&e.maxSteps===1)throw new N(`config`,`Profile ${e.id}: turnBehaviour.atStepLimit 'answer' with maxSteps 1 leaves no step that can call a tool`)}function qo(e){if(e.type===`live`)return;let t=e.outputs?.structured;if(!t||typeof t==`string`)return;let n=j(e)?.slots?.[t.by];if(!n)throw new N(`config`,`Profile ${e.id}: outputs.structured.by '${t.by}' is not a slot in inputs.slots`);let r=Object.keys(t.map).filter(e=>!n.includes(e));if(r.length)throw new N(`config`,`Profile ${e.id}: outputs.structured.map maps ${r.join(`, `)}, not a choice of slot '${t.by}'`)}var Jo={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 Yo(e,t){for(let[n,{ok:r,rule:i}]of Object.entries(Jo)){let a=t[n];if(a!==void 0&&!r(a))throw new N(`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 N(`config`,`${r} must be an image, not '${t.mimeType}'`);if(!(G(t)?t.uri:t.data))throw new N(`config`,`${r} needs its bytes or its uri`)})}function Xo(e,t){let n=t?.filter(e=>!M(te,e));if(n?.length)throw new N(`config`,`Profile ${e}: an image profile's attachments take images, video, and PDF only, not ${n.join(`, `)}`)}function Zo(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 N(`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 N(`config`,`${i}.resumed.prompt must be a prompt`);let{afterMs:a}=n;if(a!==void 0&&!(Number.isFinite(a)&&a>=0))throw new N(`config`,`${i}.resumed.afterMs must be 0 or more milliseconds`);if(!r)throw new N(`config`,`${i}.resumed needs live.sessionResumption: without it no call resumes`)}function Qo(e,t){if(!t)return;let n=`Profile ${e} live.contextCompression`,r=t.triggerTokens,i=t.slidingWindow.targetTokens;if($o(`${n}.triggerTokens`,r),$o(`${n}.slidingWindow.targetTokens`,i),r!==void 0&&i!==void 0&&i>=r)throw new N(`config`,`${n}: slidingWindow.targetTokens must be below triggerTokens`)}function $o(e,t){if(!(t===void 0||Number.isInteger(t)&&t>0))throw new N(`config`,`${e} must be a whole number above 0`)}function es(e,t,n,r){let i=`Profile ${t.id} model ${n} compaction`;if(ts(i,r),ns(i,r),r.meter!=null&&r.meter!==`history`&&r.meter!==`input`)throw new N(`config`,`${i}: meter must be 'history' or 'input'`);if(r.profile===void 0){if(t.type!==`text`||t.inputs.text===!1)throw new N(`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 N(`config`,`${i}: compaction profile '${r.profile}' must be registered before '${t.id}'`);if(a.type!==`text`||a.inputs.text===!1)throw new N(`config`,`${i}: compaction profile '${r.profile}' must be a text profile that takes text`)}function ts(e,t){if(t.maxTokens<=0)throw new N(`config`,`${e}: maxTokens must be > 0`);if(t.compactAt<=0||t.compactAt>=1)throw new N(`config`,`${e}: compactAt must be in (0, 1)`)}function ns(e,t){if(t.previousExchanges<0)throw new N(`config`,`${e}: previousExchanges must be >= 0`);if(t.previousExchanges<1&&t.previousExchanges>=t.compactAt)throw new N(`config`,`${e}: previousExchanges as fraction (${t.previousExchanges}) must be < compactAt (${t.compactAt})`);if(t.previousExchanges>1&&!Number.isInteger(t.previousExchanges))throw new N(`config`,`${e}: previousExchanges >= 1 must be an integer`)}function rs(e,t){for(let n of K(t))if(e.get(n)?.type===`builtin`)throw new N(`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 is(e,t){let n=qr(t)?.t2Loader;if(n){if(!K(t).includes(n))throw new N(`config`,`Profile ${t.id} tools.t2Loader '${n}' must also be listed in tools.allow`);if(e.get(n)?.type!==`function`)throw new N(`config`,`Profile ${t.id} tools.t2Loader '${n}' must be a registered type: 'function' tool`)}}function*as(e){for(let[t,n]of Object.entries(e.models))for(let e of n.builtInTools??[])yield{modelId:t,id:e}}function os(e,t){for(let{modelId:n,id:r}of as(t))if(e.get(r)?.type!==`builtin`)throw new N(`config`,`Profile ${t.id} model '${n}' lists '${r}' in builtInTools — not a registered builtin`)}function ss(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 cs(e,t){let n=ss(t).map(n=>{let r=e.find(n);if(!r)throw new N(`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 N(`config`,`Profile ${t.id}: outputs.validation checks a structured reply, so it needs outputs.structured`);let o=a.filter(e=>!n.some(t=>va(t.jsonSchema,e)));if(o.length)throw new N(`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=>pa(t.jsonSchema,e)));if(s.length)throw new N(`config`,`Profile ${t.id}: outputs.validation.fields has ${s.join(`, `)}, which no structured schema reaches through object properties`)}function ls(e){let t=j(e)?.context;if(!t)return;let n=A;if(t.from.length===0||t.from.some(e=>!n.includes(e)))throw new N(`config`,`Profile ${e.id}: inputs.context.from must list ${A.join(` or `)}`);if(!(Number.isInteger(t.maxChars)&&t.maxChars>0))throw new N(`config`,`Profile ${e.id}: inputs.context.maxChars must be a positive integer`)}function us(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 N(`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 N(`config`,`Profile ${e}: inputs.${t} must be a positive integer`)}function ds(e,t,n){let r=new Map,i=i=>{let a=Wo(i),o=n&&a.type!==`host`?{...a,models:Object.fromEntries(Object.entries(a.models).map(([e,t])=>[e,be(n.require(t.provider,t.apiId),t,a.type)]))}:a;if(rs(e,o),is(e,o),o.type!==`host`&&o.type!==`decision`&&o.type!==`embedding`){os(e,o),us(o.id,j(o)),ls(o),cs(t,o);for(let[e,t]of Object.entries(o.models))t.compaction&&es(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 N(`config`,`Unknown profile '${e}'`);return t},find:e=>r.get(e),has:e=>r.has(e),list:()=>[...r.values()],clear:()=>r.clear()}}var fs=`https://generativelanguage.googleapis.com/v1beta/models`;function ps(e){let t=e?.trim()??``;if(t.startsWith(`AIza`))return`gemini`;if(t.startsWith(`sk-or-`))return`openrouter`}function ms(e){let t;try{t=new URL(e.baseUrl)}catch{throw new N(`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 N(`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 N(`blocked`,`Local requests must stay on the configured origin.`))}}var hs=v({data:l(v({id:g().min(1)}))});async function gs(e,t){let n=ms(e);if(!n?.fetch)throw new N(`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 N(`network`,`Local model list returned HTTP ${r.status}.`);let i=hs.safeParse(await r.json());if(!i.success)throw new N(`request`,`The endpoint returned an invalid model list.`);return[...new Set(i.data.data.map(e=>e.id))]}var _s=`https://openrouter.ai/api/v1/models`,vs=`https://openrouter.ai/api/v1/embeddings/models`,ys=[{id:`gemini-embedding-2-preview`,label:`Gemini Embeddings 2 (preview)`},{id:`gemini-embedding-001`,label:`Gemini Embedding 001`}],bs=[{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)`}],xs={text:`text`,image:`image`,speech:`speech`,live:void 0,embedding:void 0},Ss=v({data:l(v({id:g().min(1),name:g().optional(),architecture:v({output_modalities:l(g()).optional()}).optional()}))}),Cs=v({data:l(v({id:g().min(1),name:g().optional()}))}),ws=v({models:l(v({name:g().min(1),displayName:g().optional(),supportedGenerationMethods:l(g()).optional()})).optional(),nextPageToken:g().optional()}),Ts=5;async function Es(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 N(`auth`,`${e} refused the key.`);if(!r.ok)throw new N(`network`,`${e} model list returned HTTP ${r.status}.`);return await r.json()}async function Ds(e,t,n,r){let i=n?.trim();if(t===`embedding`&&!i)return[...e===`openrouter`?bs:ys];if(e===`openrouter`)return await Os(t,i,r);if(!i)throw new N(`auth`,`Choose a key to list Gemini models.`);return await As(t,i,r)}async function Os(e,t,n){let r={signal:n,headers:{Accept:`application/json`,...t?{Authorization:[`Bearer`,t].join(` `)}:{}}};if(e===`embedding`){let e=Cs.safeParse(await Es(`OpenRouter`,vs,r));if(!e.success)throw new N(`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=xs[e];if(!i)return[];let a=Ss.safeParse(await Es(`OpenRouter`,`${_s}?output_modalities=${i}`,r));if(!a.success)throw new N(`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 ks={live:`bidiGenerateContent`,embedding:`embedContent`};async function As(e,t,n){let r=ks[e]??`generateContent`,i=[],a;for(let e=0;e<Ts;e++){let e=new URL(fs);e.searchParams.set(`pageSize`,`1000`),a&&e.searchParams.set(`pageToken`,a);let o=ws.safeParse(await Es(`Google`,e.href,{signal:n,headers:{Accept:`application/json`,"x-goog-api-key":t}}));if(!o.success)throw new N(`bad_response`,`Google returned an invalid model list.`);for(let e of o.data.models??[]){if(!e.supportedGenerationMethods?.includes(r))continue;let t=e.name.replace(/^models\//,``);i.push({id:t,label:e.displayName??t})}if(a=o.data.nextPageToken,!a)break}return i}function js(e){return[...new Set([e.key,e.fallbackKey,...Object.values(e.models??{}).flatMap(e=>[e.keySlot,e.fallbackKeySlot])].filter(e=>!!e))]}function Ms(e,t){return Object.fromEntries(e.map(e=>[e,Object.hasOwn(t,e)?t[e]:void 0]))}var Ns=[`audio/webm;codecs=opus`,`audio/webm`,`audio/mp4`,`audio/wav`,`audio/mpeg`];function Ps(e){return e.join(`,`)}function Fs(e){let t=e?.attachments?.accept,n=e?.voice?.accept;return{text:e?.text!==!1,attachments:t?.length?{accept:t,acceptAttr:Ps(t)}:null,voice:n?.length?{accept:n}:null,maxFiles:e?.maxFiles,maxBytes:e?.maxBytes,maxTurnBytes:e?.maxTurnBytes,limitsByMime:e?.limitsByMime,slots:e?.slots,context:e?.context}}function Is(e){return{text:e.text,attachments:e.attachments?{accept:e.attachments.accept}:void 0,voice:e.voice?{accept:e.voice.accept}:void 0,maxFiles:e.maxFiles,maxBytes:e.maxBytes,maxTurnBytes:e.maxTurnBytes,limitsByMime:e.limitsByMime,slots:e.slots,context:e.context}}function Ls(e,t){let n=e=>(e??[]).map(({name:e,mimeType:t,sizeBytes:n})=>({name:e,mimeType:t,sizeBytes:n})),r=or({attachments:e.attachments?.accept,voice:e.voice?.accept,limits:Xn(Is(e))},n(t.attachments),n(t.voice));return{ok:r.length===0,issues:r}}function Rs(e){let t=globalThis.MediaRecorder;if(t===void 0)return;let n=e=>t.isTypeSupported(e),r=e=>e.find(n);return e?.length?r(Ns.filter(t=>M(e,t)))??e.find(n):r(Ns)}var zs=v({protocol:g(),provider:g(),apiId:g(),options:_(g(),u()).optional(),keySlot:g().optional(),fallbackKeySlot:g().optional(),efforts:_(g(),d(Oe)).optional(),defaultEffort:g().optional(),allowEffortSelect:o().optional(),summaries:o().optional(),maxOutputTokens:h().optional(),temperature:h().optional(),builtInTools:l(g()).optional(),compaction:v({maxTokens:h(),compactAt:h(),previousExchanges:h(),profile:g().optional(),timing:d(he),meter:d(O).optional()}).optional()}),Bs=v({structured:i([g(),v({by:g(),map:_(g(),g()),fallback:g()}),p()]).optional(),streaming:v({mode:d(Pe).optional(),streamThoughts:o().optional()}).optional()}),Vs=v(Ke(dt,()=>d(lt))),Hs=v(Ke(jt,()=>Vs)),Us=v({id:g(),label:g(),actions:Vs,names:l(g()),find:o()}),Ws=v({hosts:l(g()),fromTools:o()}),Gs=v({quota:v({perDay:h()}).optional(),detect:Hs,patterns:a(d(jt),v({theorem:o(),names:l(g())})).optional(),host:l(Us).optional(),allow:v({ungiven_images:Ws,ungiven_links:Ws}),blockedReply:v({onBlock:d(x),maxRetries:h()})}),Ks=i([o(),v({theorem:o(),host:o()})]),qs=v({record:o(),writeTo:i([c(!1),g()]).optional(),sampleRate:h(),include:v({upstreamLog:o(),outboundWire:o(),evidenceRaw:o(),usage:o(),guardrailDecisions:o(),guardrailMatchPreview:o()}),scrub:v({sensitive:Ks,injection:Ks,canary:Ks}),resource:Ut,retainForDays:h(),rotateAfterMiB:h(),hasOnWriteError:o()}),Js=v({text:o(),attachments:v({accept:l(g()),acceptAttr:g()}).nullable(),voice:v({accept:l(g())}).nullable(),maxFiles:h().optional(),maxBytes:h().optional(),maxTurnBytes:h().optional(),limitsByMime:_(g(),h()).optional(),slots:_(g(),l(g())).optional(),context:v({from:l(d(A)),maxChars:h()}).optional()}),Ys=v({allowContinue:l(d(D)).optional(),autoContinue:l(d(D)).optional(),maxContinues:h().optional()}),Xs=v({resumption:Ys.optional()}),Zs=v({allow:l(g()),page:l(g()),t2Loader:g().optional(),parallel:o().optional()}),Qs={providerContinuation:v({history:d([`host`,`stateless`,`provider`]).optional()}).optional(),id:g(),models:_(g(),zs),defaultModel:g(),allowModelSelect:o().optional(),maxSteps:h().optional(),labels:a(d(at),g()),guardrails:Gs.optional(),observability:qs.optional()},$s=i([g(),l(i([g(),t({private:g().min(1)})])).min(1).readonly()]),ec=v({handle:g(),system:$s.optional(),systemByRole:_(g(),$s).optional()}),J=f(`type`,[v({...Qs,type:c(`text`),identity:ec,outputs:Bs.optional(),inputs:Js,tools:Zs,turnBehaviour:v({resumption:Ys.optional(),allowSteering:o().optional(),atStepLimit:d(je).optional()}).optional(),canStop:c(!0),allowSteering:o()}),v({...Qs,type:c(`image`),identity:ec,outputs:Bs.optional(),image:v({aspectRatio:g().optional(),resolution:g().optional(),mimeType:g().optional(),quality:g().optional(),background:g().optional(),n:h().int().min(1).optional(),seed:h().int().optional(),outputCompression:h().int().min(0).max(100).optional(),references:l(i([v({mimeType:g(),data:g(),name:g().optional()}),v({mimeType:g(),uri:g(),name:g().optional()})])).optional(),includeText:o().optional()}),inputs:Js,tools:Zs,turnBehaviour:Xs.optional(),canStop:c(!0)}),v({...Qs,type:c(`speech`),identity:v({handle:g()}),outputs:Bs.optional(),speech:v({voice:g().optional(),style:g().optional(),speed:h().optional(),format:d(Le).optional()}),inputs:Js,turnBehaviour:Xs.optional(),canStop:c(!0)}),v({...Qs,type:c(`live`),identity:ec,inputs:Js.pick({slots:!0,context:!0}).optional(),live:v({ingress:v({audio:o().optional(),video:o().optional(),text:o().optional()}).optional(),voice:g().optional(),vad:v({activityHandling:d(ve).optional(),startSensitivity:d(ye).optional(),endSensitivity:d(_e).optional(),prefixPaddingMs:h().optional(),silenceDurationMs:h().optional()}).optional(),sessionResumption:o().optional(),contextCompression:v({triggerTokens:h().optional(),slidingWindow:v({targetTokens:h().optional()})}).optional(),transcription:v({input:o().optional(),output:o().optional()}).optional()}),tools:Zs.pick({allow:!0,page:!0}),turnBehaviour:v({allowSteering:o().optional()}).optional()})]);function tc(e){let t=Ae(e),{sources:n,host:r,...i}=t.detect;return{quota:t.quota,detect:i,...n?{patterns:Object.fromEntries(Object.entries(n).map(([e,{theorem:t,matchers:n}])=>[e,{theorem:t,names:n.map(({name:e})=>e)}]))}:{},...r?{host:r.map(({id:e,label:t,actions:n,matchers:r,find:i})=>({id:e,label:t,actions:n,names:r.map(({name:e})=>e),find:!!i}))}:{},allow:{ungiven_images:nc(t.allow.ungiven_images),ungiven_links:nc(t.allow.ungiven_links)},blockedReply:t.blockedReply}}function nc(e){return{hosts:[...e.hosts??[]],fromTools:e.fromTools??!0}}function rc(e){return e===void 0||e===!1||typeof e==`string`?e:`custom`}function ic(e){if(!e)return;let t=Bt(e);return{record:t.record,writeTo:rc(t.writeTo),sampleRate:t.sampleRate,include:t.include,scrub:t.scrub,resource:t.resource,retainForDays:t.retainForDays,rotateAfterMiB:t.rotateAfterMiB,hasOnWriteError:!!t.onWriteError}}function ac(e){let{greeting:t,resumed:n,...r}=e??{};return r}function oc(e,t){let n=e.tools.filter(e=>`type`in e&&e.type===`function`&&e.answeredBy===`page`).map(e=>e.name);if(t){let e=qr(t),r=Jr(t);return{allow:[...K(t)],page:n,...e?.t2Loader?{t2Loader:e.t2Loader}:{},...r===void 0?{}:{parallel:r}}}return{allow:e.tools.filter(e=>!(`type`in e&&e.type===`builtin`)).map(e=>e.name),page:n}}function sc({allow:e,page:t}){return{allow:e,page:t}}function cc(e,t){let n=Fs(e.inputs),r=t?.identity??{handle:e.handle},i=t?tc(t.guardrails):void 0,a=t?ic(t.observability):void 0,o=e.outputs??void 0,s={id:e.id,identity:r,models:e.models,defaultModel:e.defaultModel,allowModelSelect:e.allowModelSelect,maxSteps:e.maxSteps,providerContinuation:e.providerContinuation,outputs:o,guardrails:i,observability:a,labels:Ue(t?.labels)};switch(e.type){case`text`:return J.parse({...s,type:`text`,inputs:n,tools:oc(e,t),turnBehaviour:t?.type===`text`?t.turnBehaviour:void 0,canStop:!0,allowSteering:!t||ne(t)});case`image`:return J.parse({...s,type:`image`,image:e.image??{},inputs:n,tools:oc(e,t),turnBehaviour:t?.type===`image`?t.turnBehaviour:void 0,canStop:!0});case`speech`:return J.parse({...s,type:`speech`,speech:e.speech??{},inputs:n,turnBehaviour:t?.type===`speech`?t.turnBehaviour:void 0,canStop:!0});case`live`:return J.parse({...s,type:`live`,live:ac(e.live),...e.inputs?{inputs:{slots:n.slots,context:n.context}}:{},tools:sc(oc(e,t))});default:return e.type}}function lc(e,t){let n=Hi(e,`interfaceFromProfile`);return cc(ta(t,n),n)}function uc(e){return s(t=>re.safeParse(e(t)).success)}var dc=[`running`,`gate`,`complete`,`error`,`cancel`],fc=s(e=>{let t=re.safeParse({type:`tool`,tool:e});if(!t.success||t.data.type!==`tool`||!(`phase`in t.data.tool))return!1;let{phase:n}=t.data.tool;return dc.some(e=>e===n)}),pc=_(g(),n()),mc=v({operationId:g().optional(),name:g(),callId:g(),arguments:pc,draft:g().optional(),reasoning:l(ce).optional(),stepId:g().optional(),edited:v({from:pc,to:pc}).optional(),activity:g().optional(),activityPast:g().optional(),outputDraft:g().optional(),state:fc.optional(),startedAt:h().optional(),endedAt:h().optional(),artifacts:l(n())}),hc=v({kind:d(Ce),native:g().optional()}),Y={id:g()},X=f(`kind`,[v({...Y,kind:c(`user-text`),text:g()}),v({...Y,kind:d([`user-attachment`,`user-voice`]),name:g(),mimeType:g(),sizeBytes:h(),data:g().optional()}),v({...Y,kind:c(`thought`),text:g()}),v({...Y,kind:c(`text`),text:g()}),v({...Y,kind:c(`tool`),tool:mc}),v({...Y,kind:c(`structured`),value:n(),draft:g().optional()}),v({...Y,kind:c(`media`),mimeType:g(),data:g().optional(),url:g().optional(),previewUrl:g().optional()}),v({...Y,kind:c(`grounding`),grounding:uc(e=>({type:`grounding`,grounding:e}))}),v({...Y,kind:c(`citation`),sources:uc(e=>({type:`citation`,sources:e})),callId:g().optional()}),v({...Y,kind:c(`evidence`),evidence:uc(e=>({type:`evidence`,evidence:e}))}),v({...Y,kind:c(`guardrail`),guardrail:C}),v({...Y,kind:c(`error`),message:g()}),v({...Y,kind:c(`turn-done`),stop:hc.optional(),tokens:uc(e=>({type:`tokens`,tokens:e})).optional(),interactionId:g().optional(),compaction:o().optional(),workedMs:h().optional(),endedAt:h().optional()})]),gc=v({type:g()});function _c(e,t){return Object.hasOwn(e,t)}function vc(e,t){return e.map(e=>{let n=[...t,...e.path],r=`${n.map(String).join(`.`)||`(root)`} ${e.code}`;return e.code!==`invalid_union`||e.errors.length===0?r:`${r} [${e.errors.map(e=>vc(e,n)).join(` | `)}]`}).join(`; `)}function yc(e){return vc(e.issues,[])}function bc(e,t){return new N(`bad_response`,`${e} failed its wire check: ${yc(t)}`)}function Z(e,t,n){let r=e.safeParse(t);if(!r.success)throw bc(n,r.error);return r.data}function xc(e){return{type:`malformed`,error:new N(`bad_response`,e,{copy:{key:`session.part_skipped`}})}}function Sc(e,t){let n=gc.safeParse(t);if(!n.success)return xc(`a line without a kind failed its wire check: ${yc(n.error)}`);let{type:r}=n.data;if(!_c(e,r))return{type:`unsupported`,received:r,raw:t};let i=e[r].safeParse(t);return i.success?i.data:xc(`a '${r}' line failed its wire check: ${yc(i.error)}`)}function Cc(e){try{return{value:JSON.parse(e)}}catch(e){if(e instanceof SyntaxError)return;throw e}}function wc(e,t){let n=Cc(t);return n?Sc(e,n.value):xc(`a line is not JSON`)}function Tc(e){let t=Cc(e);if(!t)throw new N(`bad_response`,`a line is not JSON`);return t.value}var Ec=v({name:g(),mimeType:g(),data:g()}),Dc=v({slots:_(g(),g()).optional(),context:n().optional(),text:g().optional(),attachments:l(Ec).optional(),voice:l(Ec).optional()}),Oc=v({gateKind:d(Ie).optional(),sessionPermissions:l(g()).optional(),name:g().optional(),input:n().optional(),snapshot:S.optional(),promoted:l(g()).optional(),model:g().optional(),effort:g().optional()}),kc=g().trim().min(1);v({input:Dc,conversation:g().min(1).optional(),model:g().optional(),effort:g().optional(),turnId:kc.optional(),abandon:l(ke).min(1).optional(),replay:Oc.pick({sessionPermissions:!0}).optional(),transcript:l(X).optional()});var Ac=[`approve`,`deny`],jc=i([t({unanswered:c(!0)}),t({output:n()}).refine(e=>`output`in e).transform(e=>({output:e.output}))]);v({gateId:g().min(1),operationId:g().min(1).max(256),decision:d(Ac),input:n().optional(),secret:g().optional(),page:jc.optional(),conversation:g().min(1).optional(),turnId:kc.optional(),replay:Oc.optional()}),v({turnId:kc,id:kc,inject:l(fe).min(1)});var Mc=v({type:c(`conversation`),ref:g().min(1),posted:c(!0).optional()}),Nc={...le,conversation:Mc},Pc=v({transcript:l(X),paused:v({events:l(re),blocks:l(X)}).optional()});v({conversation:g().min(1)}),v({conversation:g().min(1),at:h().int().min(-1)}),v({blocks:l(X)});var Fc=v({conversation:g().min(1),view:Pc}),Ic=class extends Error{kind;publicMessage;internalMessage;copy;constructor(e,t,n,r){super(n??t??e),this.name=`TheoremStreamError`,this.kind=e,t&&(this.publicMessage=t),n&&(this.internalMessage=n),r&&(this.copy=r)}};function Lc(e){return e instanceof Ic}function Rc(e){return e?.trim()||void 0}var zc=v({error:g().optional(),errorKind:w.optional(),errorCopy:me.optional(),errorInternal:g().optional()}),Bc=zc;function Vc(e,t){let n=Rc(e.error),r=Rc(e.errorInternal);return new Ic(e.errorKind??t,n,r&&r!==n?r:void 0,e.errorCopy)}function Hc(e){return!Lc(e)||e.copy===void 0?!1:(Array.isArray(e.copy)?e.copy:[e.copy]).some(e=>e.key===`session.conversation_unknown`)}function Uc(e,t){let n=wc(e,t);if(n.type===`error`)throw Vc(zc.parse(n),`internal`);return n}function Wc(e,t,n){let r=e.split(`
|
|
7
|
+
`),i=r.pop()??``;for(let e of r)e.trim()&&n(Uc(t,e));return i}async function Gc(e,t,n,r){if(!e.body)throw new N(`bad_response`,`stream reply has no body`);let i=e.body.getReader(),a=new TextDecoder,o=``,s=()=>{i.cancel()};r?.addEventListener(`abort`,s,{once:!0});try{for(;;){Ve(r);let{done:e,value:s}=await i.read();if(e)break;o=Wc(o+a.decode(s,{stream:!0}),t,n)}let e=o.trim();e&&n(Uc(t,e))}finally{r?.removeEventListener(`abort`,s)}}async function Kc(e){let t=typeof e.headers==`function`?await e.headers():e.headers,n=new Headers(t);return n.set(`content-type`,`application/json`),n}async function qc(e,t){let n=await e.text(),r;try{r=JSON.parse(n),t?.(r)}catch{return Vc({errorInternal:`HTTP ${String(e.status)}`},ie(e.status))}let i=zc.safeParse(r);return i.success?Vc({...i.data,errorInternal:i.data.errorInternal??`HTTP ${String(e.status)}`},ie(e.status)):new N(`bad_response`,`HTTP ${String(e.status)} error body failed its wire check`)}async function Jc(e,t,n){let r=n.fetch??globalThis.fetch.bind(globalThis);try{return await r(e,{...t,headers:await Kc(n),credentials:n.credentials??`same-origin`})}catch(e){throw T(e)?e:new N(`network`,se(e),{cause:e})}}async function Yc(e,t,n,r,i={}){await Gc(await Xc(e,t,i),n,r,i.signal)}async function Xc(e,t,n){let r=await Jc(e,{method:`POST`,body:JSON.stringify(t),signal:n.signal},n);if(!r.ok)throw await qc(r);return r}async function Zc(e,t,n={}){await Xc(e,t,n)}async function Q(e,t,n={}){let r=await Jc(e,{...t.body===void 0?{method:`GET`}:{method:`POST`,body:JSON.stringify(t.body)},signal:t.signal},n);if(!r.ok)throw await qc(r,t.failed);return Tc(await r.text())}async function Qc(e,t,n={}){let{signal:r,...i}=n;return Z(Pc,await Q(e,{body:t,signal:r},i),`the conversation`)}async function $c(e,t,n,r){let{signal:i,...a}=n;return Z(Fc,await Q(e,{body:t,signal:i},a),r)}function el(e,t,n={}){return $c(e,t,n,`the rewound conversation`)}function tl(e,t,n={}){return $c(e,t,n,`the started conversation`)}function nl(e){let t=e.length;for(;t>0&&e[t-1]===`/`;)--t;return e.slice(0,t)}var rl=v({interface:J});function il(e={}){let t=nl(e.endpoint??`/api/theorem`);return{async describe(n){let r=await Jc(t,{method:`GET`,signal:n},e);if(!r.ok)throw await qc(r);return Z(rl,Tc(await r.text()),`the profile description`).interface},turn:({replay:n,...r},i,a)=>Yc(`${t}/turn`,r,Nc,i,{...e,signal:a}),invoke:({replay:n,...r},i,a)=>Yc(`${t}/invoke`,r,Nc,i,{...e,signal:a}),conversation:(n,r)=>Qc(`${t}/conversation`,n,{...e,signal:r}),rewind:(n,r)=>el(`${t}/rewind`,n,{...e,signal:r}),pageResult:(n,r)=>Zc(`${t}/page-result`,n,{...e,signal:r}),steer:n=>Zc(`${t}/steer`,n,e)}}function al(e,t){if(typeof e==`string`)return e;let n=Array.isArray(e)?e:Object.keys(e);return n.length?al(n[0],t):t}function ol(e){return e===void 0?{}:{field:e}}function sl(e){if(typeof e==`string`)return/\x60([^\x60\s]+)\x60/.exec(e)?.[1];let t=Array.isArray(e)?e:Object.values(e);for(let e of t){let t=sl(e);if(t!==void 0)return t}}function cl(e,t,n){return{type:`decision`,identity:{handle:e.identity.handle},contract:e.decision.contract,...e.inputs.maxStateBytes===void 0?{}:{maxStateBytes:e.inputs.maxStateBytes},questions:Object.entries(t).map(([e,t])=>({id:e,type:t.type,labels:t.type===`choice`?Object.keys(t.criteria):t.type===`score`?t.criteria.map((e,t)=>al(e,String(t))):[],...t.type===`box`?ol(t.image??sl(t.instructions)):{}})),...n&&Object.keys(n).length>0?{images:n}:{},...e.observability?{observability:{record:Bt(e.observability).record}}:{}}}function ll(e,t){let n=Object.keys(t??{}).find(t=>e&&Object.hasOwn(e,t));if(n!==void 0)throw new N(`request`,`the image ${n} is the host's, so the page's needs another name`);let r={...e,...t};return Object.keys(r).length>0?r:void 0}var $=h().min(0).max(1),ul=_(g(),$).refine(e=>Math.abs(Object.values(e).reduce((e,t)=>e+t,0)-1)<=.001),dl=f(`type`,[v({type:c(`choice`),choice:g(),confidence:$,probabilities:ul}),v({type:c(`noul`),noul:$}),v({type:c(`box`),box:v({top:$,bottom:$,left:$,right:$}),confidence:$}),v({type:c(`score`),score:h().nonnegative(),confidence:$,legend:_(g(),g().min(1)),probabilities:ul})]),fl=v({result:v({model:g().min(1),answers:_(g(),dl),usage:v({inputTokens:h().int().nonnegative(),outputTokens:h().int().nonnegative(),costUsd:h().nonnegative().optional()}).optional()}),traces:l(Ht).optional()}),pl=new WeakMap;function ml(e,t){return t.length>0&&typeof e==`object`&&e&&pl.set(e,t),e}function hl(e){return typeof e==`object`&&!!e&&pl.get(e)||[]}var gl=v({traces:l(Ht)});async function _l(e,t,n,r,i){let a=[],o=e=>{let t=gl.safeParse(e);t.success&&(a=t.data.traces)};try{return i(await Q(e,{body:t,signal:n,failed:o},r))}catch(e){throw ml(e,a)}}function vl(e,t,n,r={}){return _l(e,t,n,r,yl)}function yl(e){return Z(fl,e,`the decision`)}var bl=v({interface:v({type:c(`decision`),identity:v({handle:g()}),contract:g(),maxStateBytes:h().optional(),questions:l(v({id:g(),type:d([`choice`,`noul`,`score`,`box`]),labels:l(g()),field:g().optional()})),images:_(g(),v({mimeType:d([`image/png`,`image/jpeg`]),data:g()})).optional(),observability:v({record:o()}).optional()})});function xl(e={}){let t=(e.endpoint??`/api/decision`).replace(/\/$/,``);return{async describe(n){return Z(bl,await Q(t,{signal:n},e),`the decision description`).interface},decide:(n,r,i)=>vl(`${t}/decide`,{state:n,...i?{assets:i}:{}},r,e)}}function Sl(e,t,n={}){let r={name:t.name,description:t.description,category:t.category,access:t.access,paths:t.paths,loadTier:t.loadTier,permission:t.permission,...t.labels?{labels:t.labels}:{}};if(t.type===`agent`){e.register({...r,type:`agent`,profile:t.profile,...t.maxCallsPerTurn===void 0?{}:{maxCallsPerTurn:t.maxCallsPerTurn}});return}let i={...r,input:Fe(t.inputSchema),output:Fe(t.outputSchema)};if(t.type===`http`){e.register({...i,type:`http`,endpoint:t.endpoint,method:t.method,headers:t.headers,mapping:t.mapping,auth:t.auth});return}if(t.type===`mcp`){e.register({...i,type:`mcp`,serverUrl:t.serverUrl,mcpToolName:t.mcpToolName,headers:t.headers,auth:t.auth});return}if(t.answeredBy===`page`){e.register({...i,type:`function`,answeredBy:`page`});return}let a=t.stubResponse||!Object.hasOwn(n,t.name)?void 0:n[t.name],o=t.stubResponse??Wt(t.outputSchema);e.register({...i,type:`function`,handler:a?e=>{try{return Promise.resolve(a(e))}catch(e){return Promise.reject(e instanceof Error?e:Error(String(e)))}}:()=>Promise.resolve(o)})}function Cl(e,t,n){e.registerMany(E);for(let r of t)Sl(e,r,n)}function wl(e,t,n,r,i){return Cl(e.tools,n,i),r&&t.type!==`live`&&e.schemas.register(r.id,r.spec),e.profiles.register(t),t}function Tl(e){if(e.type===`error`&&e.errorInternal!==void 0){let{errorInternal:t,...n}=e;return{...n,error:t}}if(e.type===`session`&&e.session.kind===`ended`&&e.errorInternal!==void 0){let{errorInternal:t,...n}=e;return{...n,session:{...e.session,message:t}}}if(e.type===`tool`&&e.tool.phase===`error`&&e.tool.failure.error!==void 0){let{failure:t}=e.tool;return{...e,tool:{...e.tool,failure:{...t,error:t.message}}}}return e}function El(e){if(e.type!==`error`&&e.type!==`session`&&e.type!==`tool`||e.errorInternal===void 0)return e;let{errorInternal:t,...n}=e;return n}function Dl(e){if(e.type!==`guardrail`||!e.guardrail?.errorInternal)return e;let{errorInternal:t,...n}=e.guardrail;return{...e,guardrail:n}}function Ol(e){if(e.type!==`evidence`||!e.evidence?.raw)return e;let{raw:t,...n}=e.evidence;return{...e,evidence:n}}function kl(e,t){let n=t?.reader===`builder`?Tl(e):Dl(El(e));return t?.includeEvidenceRaw||(n=Ol(n)),n=Kt(n,!1),n}function Al(e,t){return e.map(e=>kl(e,t))}function jl(e,t,n){let{error:r=``,errorKind:i,errorCopy:a}=kl(ge(ee(e),t),n);return{error:r,errorKind:i,...a?{errorCopy:a}:{}}}var Ml={reader:`builder`};function Nl(e){return e.mode===`demo`?{reader:`visitor`}:Ml}export{Ma as $,wc as A,jr as At,js as B,Hn as Bt,Bc as C,Jr as Ct,Yc as D,Vr as Dt,Zc as E,Ur as Et,Ls as F,yr as Ft,Xa as G,Ln as Gt,ds as H,Vn as Ht,ps as I,lr as It,Ja as J,I as Jt,Ya as K,Xt as Kt,gs as L,ur as Lt,X as M,Rr as Mt,lc as N,Lr as Nt,Z as O,zr as Ot,Rs as P,Er as Pt,ya as Q,Ds as R,dr as Rt,Vc as S,K as St,Hc as T,li as Tt,Wo as U,W as Ut,Ms as V,Bn as Vt,co as W,Rn as Wt,Va as X,Ba as Y,Kt as Yt,Ha as Z,il as _,gi as _t,Al as a,_a as at,el as b,ci as bt,xl as c,va as ct,hl as d,Ui as dt,Oa as et,vl as f,na as ft,Ic as g,Ni as gt,Nc as h,Fi as ht,kl as i,Da as it,Sc as j,Fr as jt,yc as k,Ir as kt,ll as l,ha as lt,ml as m,Li as mt,Nl as n,ka as nt,wl as o,fa as ot,_l as p,$i as pt,qa as q,Gt as qt,jl as r,Fa as rt,Cl as s,ma as st,Ml as t,Pa as tt,cl as u,ga as ut,Qc as v,ai as vt,Lc as w,qr as wt,tl as x,ii as xt,Q as y,oi as yt,ms as z,Un as zt};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/studio-monaco-xfyfezQS.js","assets/editor.api-Cd3ViPQa.js","assets/preload-helper-DpV6A1kQ.js","assets/editor-DjpsE8to.css","assets/studio-monaco-CbKf90i6.css","assets/register-CDgivxvX.js","assets/studio-type-checker-Cm6RZxV3.js"])))=>i.map(i=>d[i]);
|
|
2
|
-
import{r as e}from"./rolldown-runtime-hePW80VL.js";import{c as t,u as n}from"./themeProps-3IqahpCr.js";import{t as r}from"./preload-helper-DpV6A1kQ.js";import{Bt as i,D as a,T as o,Vt as s,Wn as c,k as l,pr as u}from"./tool-schema-CgpwKFX7.js";import{En as d,Sn as f,qt as p}from"./shaped-data-0GUF7Al3.js";import{S as m,U as h,_ as g,h as _,m as v,v as y,y as b}from"./tree-BxX70aqA.js";import{r as x}from"./live-ingress-lDUGPwth.js";import{n as S,t as C}from"./types-BoECJ8mE.js";import{n as w}from"./stub-DpBSP8Ld.js";import{F as T,M as E,k as ee,r as te}from"./workspace-Bc---F49.js";import{t as ne}from"./PaneState-C8jetBGI.js";import{
|
|
2
|
+
import{r as e}from"./rolldown-runtime-hePW80VL.js";import{c as t,u as n}from"./themeProps-3IqahpCr.js";import{t as r}from"./preload-helper-DpV6A1kQ.js";import{Bt as i,D as a,T as o,Vt as s,Wn as c,k as l,pr as u}from"./tool-schema-CgpwKFX7.js";import{En as d,Sn as f,qt as p}from"./shaped-data-0GUF7Al3.js";import{S as m,U as h,_ as g,h as _,m as v,v as y,y as b}from"./tree-BxX70aqA.js";import{r as x}from"./live-ingress-lDUGPwth.js";import{n as S,t as C}from"./types-BoECJ8mE.js";import{n as w}from"./stub-DpBSP8Ld.js";import{F as T,M as E,k as ee,r as te}from"./workspace-Bc---F49.js";import{t as ne}from"./PaneState-C8jetBGI.js";import{J as re}from"./index-C3mDKoGG.js";var D=class extends Error{line;column;constructor(e,t,n){super(e),this.line=t,this.column=n}},ie=class{text;of;i=0;line=1;column=1;constructor(e,t=`profile`){this.text=e,this.of=t}get done(){return this.i>=this.text.length}pos(){return{line:this.line,column:this.column}}fail(e){throw new D(e,this.line,this.column)}peek(e=0){return this.text[this.i+e]??``}bump(){let e=this.text[this.i]??``;return this.i+=1,e===`
|
|
3
3
|
`?(this.line+=1,this.column=1):this.column+=1,e}skip(){for(;;){let e=this.peek();if(e===` `||e===` `||e===`
|
|
4
4
|
`||e===`\r`||e===``)this.bump();else if(e===`/`&&this.peek(1)===`/`)for(;!this.done&&this.peek()!==`
|
|
5
5
|
`;)this.bump();else if(e===`/`&&this.peek(1)===`*`){for(this.bump(),this.bump();!this.done&&(this.peek()!==`*`||this.peek(1)!==`/`);)this.bump();this.done&&this.fail(`This comment never closes.`),this.bump(),this.bump()}else return}}starts(e){return this.skip(),this.text.startsWith(e,this.i)}eat(e){if(!this.starts(e))return!1;for(let t=0;t<e.length;t+=1)this.bump();return!0}expect(e){this.eat(e)||this.fail(`Expected '${e}'.`)}ident(){this.skip();let e=this.peek();if(!/^[A-Za-z_$]/.test(e))return;let t=``;for(;/^[A-Za-z0-9_$]/.test(this.peek());)t+=this.bump();return t}expectIdent(){let e=this.ident();return e===void 0&&this.fail(`Expected a name.`),e}peekIdent(){return this.skip(),/^[A-Za-z_$][A-Za-z0-9_$]*/.exec(this.text.slice(this.i))?.[0]}rest(){return this.skip(),this.text.slice(this.i)}};function O(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function k(e){e.skip();let t=e.peek();t!==`'`&&t!==`"`&&e.fail(`Expected a string.`),e.bump();let n=``;for(;!e.done&&e.peek()!==t;){let t=e.bump();if(t!==`\\`){n+=t;continue}let r=e.bump(),i={n:`
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{r as e}from"./rolldown-runtime-hePW80VL.js";import{c as t,u as n}from"./themeProps-3IqahpCr.js";import{l as r,n as i,t as a,u as o}from"./SegmentedControlItem-BLuJOusN.js";import{t as s}from"./VStack-CkVMcNiK.js";import{n as c,t as l}from"./StackItem-CQviqAfM.js";import{
|
|
2
|
-
`).length,t),n)}var U=(0,E.createContext)({images:{},onImages:()=>{}});function we({value:e,label:t,isLabelHidden:n}){let r=v(),{images:i,onImages:a}=(0,E.useContext)(U),{read:o,status:s}=V(),[f,p]=(0,E.useState)(!1),m=Object.hasOwn(i,e)?k(i[e]):void 0;return(0,B.jsxs)(c,{gap:2,vAlign:`center`,children:[(0,B.jsx)(
|
|
3
|
-
`))),[o]=(0,E.useState)(()=>typeof e==`string`&&Object.hasOwn(i,e));if(o&&typeof e==`string`)return(0,B.jsx)(we,{value:e,label:n,isLabelHidden:r});if(typeof e==`boolean`)return(0,B.jsx)(
|
|
1
|
+
import{r as e}from"./rolldown-runtime-hePW80VL.js";import{c as t,u as n}from"./themeProps-3IqahpCr.js";import{l as r,n as i,t as a,u as o}from"./SegmentedControlItem-BLuJOusN.js";import{t as s}from"./VStack-CkVMcNiK.js";import{n as c,t as l}from"./StackItem-CQviqAfM.js";import{d as u,l as d}from"./browser-transport-DxpDmXGb.js";import{d as f,g as p}from"./fieldParts-Cs6Amprh.js";import{r as m,t as ee}from"./IconButton-CG5klqF1.js";import{a as h,g as te,i as ne,l as g,s as re,u as ie}from"./SidePanel-OYp0bLNO.js";import{t as _}from"./Text-BsiAsowd.js";import{n as v}from"./labels-provider-BqgbdxdT.js";import{n as ae,t as y}from"./Card-Ghe4ozhC.js";import{n as b}from"./ScrollableArea-C8AVuqnt.js";import{i as x}from"./Banner-B1Vat7i_.js";import{a as oe}from"./arrive-DvbqpeRS.js";import{t as se}from"./Center-nHS1JSux.js";import{a as S,o as ce}from"./shaped-data-0GUF7Al3.js";import{n as C}from"./trace-patterns-CS99kExN.js";import{D as le,T as ue,b as w,c as de,jt as fe,v as pe,y as T}from"./index-C3mDKoGG.js";var E=e(n(),1),me=new Set([`image/png`,`image/jpeg`]),D=`image/png,image/jpeg`;function he(e,t){let n=e.replace(/\.[^.]*$/,``).toLowerCase().replace(/[^a-z0-9]+/g,`_`).replace(/^_+|_+$/g,``)||`image`,r=`<${n}>`;for(let e=2;t.includes(r);e+=1)r=`<${n}_${String(e)}>`;return r}async function O(e){if(!me.has(e.type))return null;let t=new Uint8Array(await e.arrayBuffer()),n=``;for(let e=0;e<t.length;e+=32768)n+=String.fromCharCode(...t.subarray(e,e+32768));return{mimeType:e.type,data:btoa(n)}}function k(e){return`data:${e.mimeType};base64,${e.data}`}function A(e,t){return typeof e==`string`?e===t:Array.isArray(e)?e.some(e=>A(e,t)):typeof e==`object`&&e?Object.values(e).some(e=>A(e,t)):!1}function j(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>A(t,e)))}function M(e,t,n){let r=he(e,[...Object.keys(t),...n.map(e=>`<${e}>`)]);return{key:r.slice(1,-1),reference:r}}function N(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:void 0}function P(e,t){let{images:n,state:r}=t;for(let[i,a]of e){let{key:e,reference:o}=M(i.name,{...t.host,...n},Object.keys(r));n={...n,[o]:a},r={...r,[e]:o}}return{images:n,state:r}}function F(e,t){let n=e;for(let e of t.split(`.`)){if(typeof n!=`object`||!n)return;n=Array.isArray(n)?n[Number(e)]:n[e]}return n}function I(e,t,n){let r=Object.keys(e),i=n===void 0||n in e?n:F(t,n);return e[(typeof i==`string`&&i in e?i:void 0)??r.find(e=>A(t,e))??r[0]??``]}function L(e,t,n){return{x:e.left*t,y:e.top*n,width:(e.right-e.left)*t,height:(e.bottom-e.top)*n,line:Math.max(2,Math.round(Math.min(t,n)/200))}}var R=.45;async function ge(e,t,n){let r=new Image;r.src=e,await r.decode();let i=document.createElement(`canvas`);i.width=r.naturalWidth,i.height=r.naturalHeight;let a=i.getContext(`2d`);if(!a)return e;let o=L(t,i.width,i.height);return a.drawImage(r,0,0),a.fillStyle=n.shade,a.globalAlpha=R,a.beginPath(),a.rect(0,0,i.width,i.height),a.rect(o.x,o.y,o.width,o.height),a.fill(`evenodd`),a.globalAlpha=1,a.strokeStyle=n.outline,a.lineWidth=o.line,a.strokeRect(o.x,o.y,o.width,o.height),i.toDataURL(`image/png`)}function _e(e){let t=e.right-e.left,n=e.bottom-e.top;return{width:100/t,height:100/n,left:-e.left/t*100,top:-e.top/n*100}}function ve(e){return e.every(e=>typeof e==`string`)}function z(e){return e==null||typeof e==`string`?``:typeof e==`number`?0:typeof e==`boolean`?!1:Array.isArray(e)?[]:Object.fromEntries(Object.entries(e).map(([e,t])=>[e,z(t)]))}function ye(e){let t=e[0];if(typeof t!=`object`||!t||Array.isArray(t))return null;let n=Object.keys(t);return n.length===0||n.length>4||!e.every(e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&Object.keys(e).join()===n.join()&&Object.values(e).every(e=>typeof e!=`object`||!e))?null:n.map(t=>{let n=e.map(e=>String(e[t]??``).length),r=Math.max(t.length,...n);return{key:t,weight:Math.min(4,Math.max(1,Math.round(r/10)))}})}var B=t();function be(e){return e===null?[]:Array.isArray(e)?e:[e]}function V(){let e=v(),[t,n]=(0,E.useState)(null);return{read:async e=>{n(null);let t=[];for(let r of be(e)){let e=await O(r);e?t.push([r,e]):n(r.name)}return t},status:t===null?void 0:{type:`error`,message:e(`@theorem.decision.image_bad`,{file:t})}}}function xe({onImages:e}){let t=v(),{read:n,status:r}=V();return(0,B.jsx)(T,{label:t(`@theorem.decision.add_image`),isLabelHidden:!0,mode:`dropzone`,isMultiple:!0,accept:D,value:null,placeholder:t(`@theorem.decision.add_image_hint`),status:r,statusVariant:`detached`,onChange:t=>{n(t).then(t=>{t.length>0&&e(t)})}})}var Se={search:()=>[],bootstrap:()=>[]},Ce=48;function H(e,t,n){return Math.min(Math.max(e.split(`
|
|
2
|
+
`).length,t),n)}var U=(0,E.createContext)({images:{},onImages:()=>{}});function we({value:e,label:t,isLabelHidden:n}){let r=v(),{images:i,onImages:a}=(0,E.useContext)(U),{read:o,status:s}=V(),[f,p]=(0,E.useState)(!1),m=Object.hasOwn(i,e)?k(i[e]):void 0;return(0,B.jsxs)(c,{gap:2,vAlign:`center`,children:[(0,B.jsx)(u,{src:m,alt:t,label:e,onClick:m?()=>p(!0):void 0}),m?(0,B.jsx)(d,{isOpen:f,onOpenChange:p,media:{src:m,alt:t,caption:e},hasZoom:!0}):null,(0,B.jsx)(l,{size:`fill`,children:(0,B.jsx)(T,{label:t,isLabelHidden:n,accept:D,value:null,placeholder:r(`@theorem.decision.replace_image`),status:s,statusVariant:`detached`,onChange:t=>{o(t).then(([t])=>{t&&a({...i,[e]:t[1]})})}})})]})}function W({value:e,onChange:t,label:n,isLabelHidden:r}){let{images:i}=(0,E.useContext)(U),[a]=(0,E.useState)(()=>typeof e==`string`&&(e.length>Ce||e.includes(`
|
|
3
|
+
`))),[o]=(0,E.useState)(()=>typeof e==`string`&&Object.hasOwn(i,e));if(o&&typeof e==`string`)return(0,B.jsx)(we,{value:e,label:n,isLabelHidden:r});if(typeof e==`boolean`)return(0,B.jsx)(pe,{label:n,value:e,onChange:t});if(typeof e==`number`)return(0,B.jsx)(le,{label:n,isLabelHidden:r,size:`sm`,value:e,isWheelEnabled:!1,onChange:t});if(e===null)return(0,B.jsx)(b,{label:n,isLabelHidden:r,size:`sm`,value:``,placeholder:`null`,isDisabled:!0,onChange:()=>{}});let s=String(e);return a?(0,B.jsx)(w,{label:n,isLabelHidden:r,size:`sm`,rows:H(s,2,12),value:s,onChange:t}):(0,B.jsx)(b,{label:n,isLabelHidden:r,size:`sm`,value:s,onChange:t})}function G({label:e,isRequired:t,description:n,children:r}){let i=(0,E.useId)();return(0,B.jsxs)(s,{gap:2,role:`group`,"aria-labelledby":i,children:[(0,B.jsx)(f,{label:e,inputID:``,labelID:i,isGroupLabel:!0,isRequired:t,description:n}),r]})}function K({children:e,...t}){return(0,B.jsx)(G,{...t,children:(0,B.jsx)(`div`,{style:{paddingInlineStart:12,borderInlineStart:`1px solid var(--color-border)`},children:e})})}function q({field:e,onAdd:t}){let n=v();return(0,B.jsx)(c,{children:(0,B.jsx)(m,{label:n(`@theorem.decision.add_item`,{field:e}),size:`sm`,variant:`ghost`,icon:(0,B.jsx)(fe,{size:14}),onClick:t})})}function J({index:e,onRemove:t}){let n=v();return(0,B.jsx)(ee,{label:n(`@theorem.decision.remove_item`,{item:n(`@theorem.data.item`,{index:String(e+1)})}),size:`sm`,variant:`ghost`,icon:(0,B.jsx)(p,{size:14}),onClick:t})}function Y({value:e,onChange:t}){return(0,B.jsx)(s,{gap:3,children:Object.entries(e).map(([n,r])=>(0,B.jsx)(X,{label:S(n),value:r,onChange:r=>t({...e,[n]:r})},n))})}function Te({value:e,onChange:t,label:n}){let r=v(),i=oe(e);if(ve(e))return(0,B.jsx)(ue,{label:n,size:`sm`,value:e.map((e,t)=>({id:`${String(t)}:${e}`,label:e})),searchSource:Se,hasCreate:!0,debounceMs:0,placeholder:r(`@theorem.decision.add_value`),onChange:e=>t(e.map(e=>e.label))});let a=ye(e),o=(0,B.jsx)(q,{field:n,onAdd:()=>t([...e,z(e.at(-1))])}),u=n=>(0,B.jsx)(J,{index:n,onRemove:()=>{i.drop(n),t(e.filter((e,t)=>t!==n))}});if(a){let r={display:`grid`,gap:8,alignItems:`start`,gridTemplateColumns:`${a.map(e=>`minmax(0, ${String(e.weight)}fr)`).join(` `)} auto`},s=e;return(0,B.jsxs)(G,{label:n,children:[(0,B.jsxs)(`div`,{style:r,"aria-hidden":!0,children:[a.map(e=>(0,B.jsx)(_,{type:`supporting`,color:`secondary`,maxLines:1,children:S(e.key)},e.key)),(0,B.jsx)(`span`,{style:{width:28}})]}),i.rows.map(({index:e,key:n})=>{let i=s[e];return(0,B.jsxs)(`div`,{style:r,children:[a.map(n=>(0,B.jsx)(W,{label:`${S(n.key)} ${String(e+1)}`,isLabelHidden:!0,value:i[n.key]??null,onChange:r=>t(s.map((t,i)=>i===e?{...t,[n.key]:r}:t))},n.key)),u(e)]},n)}),o]})}return(0,B.jsx)(K,{label:n,children:(0,B.jsxs)(s,{gap:3,children:[i.rows.map(({item:n,index:i,key:a})=>{let o=r(`@theorem.data.item`,{index:String(i+1)}),s=n=>t(e.map((e,t)=>t===i?n:e));return(0,B.jsxs)(c,{gap:2,vAlign:`start`,children:[(0,B.jsx)(l,{size:`fill`,children:ce(n)?(0,B.jsx)(W,{label:o,isLabelHidden:!0,value:n,onChange:s}):(0,B.jsx)(X,{label:o,value:n,onChange:s})}),u(i)]},a)}),o]})})}function X({value:e,onChange:t,label:n}){return Array.isArray(e)?(0,B.jsx)(Te,{label:n,value:e,onChange:t}):typeof e==`object`&&e?(0,B.jsx)(K,{label:n,children:(0,B.jsx)(Y,{value:e,onChange:t})}):(0,B.jsx)(W,{label:n,value:e,onChange:t})}function Ee({value:e,onChange:t,label:n}){return typeof e==`object`&&e&&!Array.isArray(e)?(0,B.jsx)(Y,{value:e,onChange:t}):(0,B.jsx)(X,{label:n,value:e,onChange:t})}var De={"--theorem-console-card":`var(--color-background-muted)`},Z=`(width < 768px)`,Q=(0,E.createContext)(!0);function $(){return(0,E.useSyncExternalStore)(e=>{let t=globalThis.matchMedia(Z);return t.addEventListener(`change`,e),()=>{t.removeEventListener(`change`,e)}},()=>globalThis.matchMedia(Z).matches,()=>!1)}function Oe({flush:e,wide:t,maxWidth:n,children:r}){return(0,B.jsx)(s,{height:`100%`,paddingInline:3,style:e?De:void 0,children:(0,B.jsx)(y,{variant:`transparent`,height:`100%`,padding:0,style:e?{overflowY:`auto`}:{...re,overflowY:`auto`},children:(0,B.jsx)(se,{axis:`horizontal`,width:`100%`,minHeight:`100%`,children:(0,B.jsx)(s,{width:`100%`,maxWidth:t?void 0:n,gap:3,padding:4,children:r})})})})}function ke({inspector:e,maxWidth:t,flush:n=!1,columns:i=!1,requestLabel:a,className:s,style:c,children:l}){let u=(0,E.useRef)(null);return(0,B.jsx)(x,{inspector:e,children:(0,B.jsx)(o,{ref:u,height:`fill`,className:s,style:c,header:e.toggle?(0,B.jsx)(ie,{children:e.toggle}):void 0,content:(0,B.jsx)(r,{padding:0,isScrollable:!1,children:(0,B.jsx)(Ae,{layoutRef:u,flush:n,columns:i,maxWidth:t,requestLabel:a,children:l})})})})}function Ae({layoutRef:e,flush:t,columns:n,maxWidth:r,requestLabel:i,children:a}){let o=$(),s=E.Children.toArray(a).length,c=n&&s>1;return c&&!o?(0,B.jsx)(je,{requestLabel:i,basisWidth:e.current?.clientWidth??0,children:a}):(0,B.jsx)(Oe,{flush:t,wide:c,maxWidth:r,children:a})}function je({requestLabel:e=`Request`,basisWidth:t,children:n}){let i=v(),a=(0,E.useRef)(null),s=te({defaultSize:t>0?Math.round(t*.4):`40%`,minSize:280,maxSize:`70%`,containerRef:a}),[c,l]=E.Children.toArray(n),u={name:e,show:e,hide:e,resize:i(`@theorem.panel.resize`,{name:e})};return(0,B.jsx)(Q,{value:!1,children:(0,B.jsx)(o,{ref:a,height:`fill`,start:(0,B.jsx)(g,{side:`start`,className:`theorem-console-request`,labels:u,resizable:s,open:!0,children:(0,B.jsx)(h,{label:e,children:c})}),content:(0,B.jsx)(r,{padding:0,isScrollable:!1,children:(0,B.jsx)(ne,{inset:`beside`,className:`theorem-console-response`,children:l})})})})}function Me({children:e}){return(0,B.jsx)(y,{variant:`muted`,padding:0,className:`theorem-console-card`,style:C,children:(0,B.jsx)(Q,{value:!1,children:e})})}function Ne({label:e,fill:t=!1,children:n}){return(0,E.use)(Q)?(0,B.jsx)(y,{variant:`muted`,padding:t?0:4,className:`theorem-console-card`,style:C,children:t?n:(0,B.jsx)(s,{height:`100%`,gap:3,children:n})}):t?n:(0,B.jsx)(h,{label:e,padding:4,children:n})}function Pe(e){return t=>{t.key===`Enter`&&(t.metaKey||t.ctrlKey)&&(t.preventDefault(),e())}}function Fe({title:e,view:t,hasFields:n,onView:r,onRun:o,children:l}){let u=v(),d=(0,E.use)(Q),f=(0,B.jsxs)(s,{gap:3,padding:d?void 0:4,onKeyDown:Pe(o),children:[(0,B.jsxs)(c,{gap:2,hAlign:`between`,vAlign:`center`,children:[(0,B.jsx)(_,{type:`supporting`,color:`secondary`,as:`h3`,children:e}),(0,B.jsxs)(i,{label:u(`@theorem.decision.view`),size:`sm`,value:t,onChange:e=>{r(e===`json`?`json`:`fields`)},children:[(0,B.jsx)(a,{value:`fields`,label:u(`@theorem.decision.fields`),isDisabled:!n}),(0,B.jsx)(a,{value:`json`,label:u(`@theorem.data.json`)})]})]}),l]});return d?(0,B.jsx)(y,{variant:`muted`,padding:4,className:`theorem-console-card`,style:C,children:f}):f}var Ie={"--font-family-body":`var(--font-family-code)`};function Le({label:e,text:t,isInvalid:n,onChange:r}){return(0,B.jsx)(w,{label:e,isLabelHidden:!0,value:t,onChange:r,rows:H(t,8,24),hasSpellCheck:!1,status:n?{type:`error`}:void 0,controlStyle:Ie})}function Re({note:e,isReady:t,isRunning:n,runLabel:r,runningLabel:i,stopLabel:a,onRun:o,onStop:s}){return(0,B.jsxs)(c,{gap:3,hAlign:`between`,vAlign:`center`,children:[(0,B.jsx)(_,{type:`supporting`,color:`secondary`,style:t?void 0:{color:`var(--color-error)`},hasTabularNumbers:!0,children:e}),(0,B.jsxs)(c,{gap:2,vAlign:`center`,children:[n?(0,B.jsx)(m,{label:a,variant:`ghost`,onClick:s}):null,(0,B.jsx)(m,{label:n?i:r,variant:`primary`,isLoading:n,isDisabled:!t,onClick:o})]})]})}function ze(){let e=ae();return(0,E.useMemo)(()=>{let t=new Intl.NumberFormat(e,{style:`unit`,unit:`byte`,unitDisplay:`narrow`}),n=new Intl.NumberFormat(e,{style:`unit`,unit:`kilobyte`,unitDisplay:`narrow`,maximumFractionDigits:1});return e=>e<1024?t.format(e):n.format(e/1024)},[e])}function Be({payload:e,runtime:t=null,traces:n,onActivity:r},i,a){return(0,E.useMemo)(()=>{let o=t?a(e,t,{traces:n}):i(e,{traces:n});return r?de(o,r):o},[e,t,n,r,i,a])}export{N as C,j as S,I as _,Fe as a,k as b,ze as c,G as d,J as f,xe as g,H as h,Le as i,q as l,U as m,ke as n,Ne as o,Ee as p,Me as r,Re as s,Be as t,K as u,_e as v,ge as x,P as y};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{r as e}from"./rolldown-runtime-hePW80VL.js";import{c as t,u as n}from"./themeProps-3IqahpCr.js";import{c as r,m as i,n as a,s as o}from"./browser-transport-DxpDmXGb.js";import{n as s,t as c}from"./labels-provider-BqgbdxdT.js";import{a as l,t as u}from"./Banner-B1Vat7i_.js";import{c as d}from"./reader-paEmSrWc.js";import{p as f,u as p}from"./tree-BxX70aqA.js";import{n as m,t as h}from"./PaneState-C8jetBGI.js";import{C as g,S as _,a as v,c as y,g as b,i as x,m as S,n as C,o as w,p as T,s as E,t as D,y as O}from"./studio-console-1qIWsDtV.js";import{i as k,t as A}from"./use-one-call-BVmuHLSm.js";import{d as j,nt as M,tt as N}from"./index-C3mDKoGG.js";var P=(e,t,n,r)=>e.decide(n,t,r);function F(e){let{iface:t,describeFailure:n}=r(e),{call:i,...a}=A(e,`deciding`,P);return{iface:t,describeFailure:n,...a,decide:i}}var I=e(n(),1),L=t();function R(e,t){let n;try{n=JSON.parse(e)}catch{return{ok:!1,reason:`invalid_json`}}if(n===null)return{ok:!1,reason:`null_state`,state:n};let r=new TextEncoder().encode(JSON.stringify(n)).byteLength;return t!==void 0&&r>t?{ok:!1,reason:`too_large`,bytes:r,state:n}:{ok:!0,state:n,bytes:r}}function z(e,t,n,r){return t.ok?n===void 0?null:e(`@theorem.decision.state_size`,{size:r(t.bytes),limit:r(n)}):t.reason===`too_large`?e(`@theorem.decision.too_large`,{limit:r(n??0)}):e(t.reason===`invalid_json`?`@theorem.decision.invalid_json`:`@theorem.decision.null_state`)}function B(e){return e.failure||e.result?`settled`:e.status===`deciding`?`waiting`:`idle`}function V(e,t){let[n,r]=(0,I.useState)(e),i=R(n,t),[a,o]=(0,I.useState)(()=>i.state===void 0?`json`:`fields`);return{text:n,setText:r,check:i,shown:i.state===void 0?`json`:a,setView:o}}function H({form:e,iface:t,images:n,onImages:r,note:i,isRunning:a,onRun:o,onStop:c}){let l=s(),{text:u,setText:d,check:f,shown:p,setView:m}=e,h=t.questions.some(e=>e.type===`box`)||Object.keys(n).length>0,_=p===`fields`?f.state:void 0,y=g(_);return(0,L.jsxs)(v,{title:l(`@theorem.decision.state`),view:p,hasFields:f.state!==void 0,onView:m,onRun:o,children:[_===void 0?(0,L.jsx)(x,{label:l(`@theorem.decision.state`),text:u,isInvalid:!f.ok,onChange:d}):(0,L.jsx)(S,{value:{images:n,onImages:r},children:(0,L.jsx)(T,{label:l(`@theorem.decision.state`),value:_,onChange:e=>{d(JSON.stringify(e,null,2))}})}),h&&y?(0,L.jsx)(b,{onImages:e=>{let i=O(e,{images:n,host:t.images,state:y});r(i.images),d(JSON.stringify(i.state,null,2))}}):null,(0,L.jsx)(E,{note:i,isReady:f.ok,isRunning:a,runLabel:l(`@theorem.decision.decide`),runningLabel:l(`@theorem.decision.deciding`),stopLabel:l(`@theorem.decision.stop`),onRun:o,onStop:c})]})}function U({iface:e,decision:t,asked:n,onQuestion:r,questionText:i}){let a=s(),o=t.status===`deciding`;return(0,L.jsxs)(L.Fragment,{children:[t.failure?(0,L.jsx)(u,{status:`error`,role:`alert`,title:t.failure.error}):null,o&&!t.result?(0,L.jsx)(m,{label:a(`@theorem.decision.deciding`),since:t.startedAt}):null,t.result?(0,L.jsx)(k,{iface:e,result:t.result,asked:n,onQuestion:r,questionText:i,elapsedMs:t.elapsedMs,isStale:o}):null]})}function W(e,t,n,r,i){if(t===`idle`)return null;if(!e)return i;let a=t===`waiting`;return(0,L.jsx)(w,{label:n.answers,fill:a,children:a?(0,L.jsx)(m,{label:n.deciding,since:r}):i})}function G({transport:e,iface:t,decision:n,defaultState:r=`{}`,defaultImages:i,onQuestion:a,questionText:o,maxWidth:c=`960px`,trace:u,flush:d,columns:f=!1,className:p,style:m}){let h=s(),g=y(),v=V(r,t.maxStateBytes),{check:b}=v,[x,S]=(0,I.useState)(i??{}),[w,T]=(0,I.useState)(),E=l(t,e.traces,u);return(0,L.jsxs)(C,{inspector:E,maxWidth:c,flush:d,columns:f,requestLabel:h(`@theorem.decision.state`),className:p,style:m,children:[(0,L.jsx)(H,{form:v,iface:t,images:x,onImages:S,note:z(h,b,t.maxStateBytes,g),isRunning:n.status===`deciding`,onRun:()=>{if(!b.ok)return;let e=_(x,b.state);T({images:{...t.images,...e},state:b.state}),n.decide(b.state,Object.keys(e).length>0?e:void 0)},onStop:n.cancel}),W(f,B(n),{answers:h(`@theorem.decision.answers`),deciding:h(`@theorem.decision.deciding`)},n.startedAt,(0,L.jsx)(U,{iface:t,decision:n,asked:w,onQuestion:a,questionText:o}))]})}function K(e){let t=s(),n=F(e.transport);return n.describeFailure?(0,L.jsx)(h,{title:n.describeFailure.error}):n.iface?(0,L.jsx)(G,{...e,iface:n.iface,decision:n}):(0,L.jsx)(m,{label:t(`@theorem.chat.loading`)})}function q({endpoint:e,http:t,transport:n,theme:r,mode:i,labels:a,...s}){let l=(0,I.useRef)(t);l.current=t;let u=(0,I.useMemo)(()=>n??d({...l.current,endpoint:e}),[n,e]);return(0,L.jsx)(o,{theme:r,mode:i,children:(0,L.jsx)(c,{labels:a,children:(0,L.jsx)(K,{...s,transport:u})})})}var J;function Y(e){if(e.agentId===`pantry.jev`)return J??=M(),{defaultState:N,defaultImages:{...(0,I.use)(J)}};let{profile:t}=e;return{defaultState:(t.type===`decision`?Object.values(t.models)[0]:void 0)?.apiId.startsWith(`respan/`)?f:p}}function X(e){return typeof e==`string`?e:Array.isArray(e)?e.map(X).join(` `):Object.entries(e).map(([e,t])=>`${e}: ${X(t)}`).join(` `)}function Z(e){let t=D(e,i,a);return(0,L.jsx)(Q,{...e,transport:t})}function Q({payload:e,transport:t,trace:n,flush:r,columns:i,className:a}){let{open:o}=(0,I.useContext)(j),s=Y(e),{questions:c}=e,l=(0,I.useMemo)(()=>c&&Object.fromEntries(Object.entries(c).map(([e,t])=>[e,X(t.instructions)])),[c]);return(0,L.jsx)(q,{transport:t,...s,trace:n,flush:r,columns:i,className:a,onQuestion:o,questionText:l})}export{Q as DecisionView,Z as StudioDecision};
|