@theoremjs/studio 0.3.5-next.935.ga3dc485 → 0.3.5-next.938.g3cbd0dd
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/README.md +1 -1
- package/package.json +4 -4
- package/page/assets/{BottomSheet-BeZNOmva.js → BottomSheet-C4IynZSF.js} +1 -1
- package/page/assets/{ConsoleFrame-Durgrfa8.js → ConsoleFrame-fT5eTIHi.js} +1 -1
- package/page/assets/{ContextMenu-CdZPGyrH.js → ContextMenu-5-xTYWew.js} +2 -2
- package/page/assets/{DateInput-DxxKNbFy.js → DateInput-DoxJGEFL.js} +1 -1
- package/page/assets/{DropdownMenu-CLdHjD_O.js → DropdownMenu-Brkhbsgi.js} +2 -2
- package/page/assets/{Link-B8qtW9Me.js → Link-C6YV8yBY.js} +1 -1
- package/page/assets/{MenuBottomSheet-BJz5pzDE.js → MenuBottomSheet-BQgpj4zr.js} +1 -1
- package/page/assets/{PowerSearchBottomSheet-xO313kak.js → PowerSearchBottomSheet-BIEnT9kr.js} +1 -1
- package/page/assets/{RankedBars-D0yn-ri0.js → RankedBars-DxIPIvjl.js} +1 -1
- package/page/assets/{SchemaFields-Dvwzr5ZO.js → SchemaFields-BBe7AHAM.js} +1 -1
- package/page/assets/{ShapedData-DYRlNRy_.js → ShapedData-DcyAIdQK.js} +1 -1
- package/page/assets/{TokenizerBottomSheet-DhPibEHt.js → TokenizerBottomSheet-DiazU3cR.js} +1 -1
- package/page/assets/{ToolResultCharts-BGJbKsDT.js → ToolResultCharts-fYLeN6h2.js} +1 -1
- package/page/assets/{Toolbar-DVp0Jb7c.js → Toolbar-Co1lZr-l.js} +1 -1
- package/page/assets/{TraceInspector-Cs8SNp3b.js → TraceInspector-CqKt_0Ay.js} +2 -2
- package/page/assets/{TraceOverview-BN5UDJe8.js → TraceOverview-BKCnwphT.js} +3 -3
- package/page/assets/{_virtual_studio-type-sources-ekRa45Mf.js → _virtual_studio-type-sources-mjgBn2Oq.js} +195 -27
- package/page/assets/browser-connection-ByVN8zLj.js +1 -0
- package/page/assets/browser-engine-ClJkq-b5.js +16 -0
- package/page/assets/{browser-transport-rFxtbMn0.js → browser-transport-hq68oIIM.js} +2 -2
- package/page/assets/{compile-C4Q50p5E.js → compile-Dpm_0jBP.js} +2 -2
- package/page/assets/encode-files-B1-I_sQm.js +1 -0
- package/page/assets/{export-agent-CEB-vrfl.js → export-agent-lA4vWLXq.js} +1 -1
- package/page/assets/{getRadiusAndStrokeWidthFromDot-Ck-kRNvB.js → getRadiusAndStrokeWidthFromDot-D7jsnIKG.js} +1 -1
- package/page/assets/{guardrail-health-DMd_p8rH.js → guardrail-health-DoN89cxF.js} +2 -2
- package/page/assets/{guardrail-tester-DAis9Gsd.js → guardrail-tester-DTYzL09j.js} +1 -1
- package/page/assets/{index-C6pyNvXU.js → index-BHyh3u0-.js} +15 -15
- package/page/assets/{json-code-DqpAF4hg.js → json-code-DDOdfslU.js} +1 -1
- package/page/assets/{labels-provider-BOmB5WmP.js → labels-provider-zFTJcXMk.js} +1 -1
- package/page/assets/{live-messages-DekE0UkG.js → live-messages-DUty9gDM.js} +1 -1
- package/page/assets/{prompt-row-BHTY1SfP.js → prompt-row-BoUaTcay.js} +1 -1
- package/page/assets/reader-Q_pKlgc5.js +5 -0
- package/page/assets/registry-CNgPNMqQ.js +1 -0
- package/page/assets/{schema-Do4wX6Sr.js → schema-CW04nV6r.js} +1 -1
- package/page/assets/{shaped-data-BxDmEUJe.js → shaped-data-C_l29gBe.js} +1 -1
- package/page/assets/{stub-CUHiDLLw.js → stub-CXebNVt9.js} +1 -1
- package/page/assets/{studio-code-pane-i0bu-gwb.js → studio-code-pane-CQ3u-Y3E.js} +3 -3
- package/page/assets/{studio-console-Cn5vtx-w.js → studio-console-CvuPC2gg.js} +1 -1
- package/page/assets/{studio-decision-CwWJLFnm.js → studio-decision-Be5svhXz.js} +1 -1
- package/page/assets/{studio-embedding-Dya8zKKM.js → studio-embedding-DFhGtyXw.js} +1 -1
- package/page/assets/{studio-host-console-BbnDPTbG.js → studio-host-console-UhiWfVOB.js} +2 -2
- package/page/assets/studio-live-DYP4Sci4.js +5 -0
- package/page/assets/{studio-map-Bqv8T8BY.js → studio-map-B0m0nQ6C.js} +1 -1
- package/page/assets/{studio-media-C6h3z2kJ.js → studio-media-BwvH-T_Q.js} +1 -1
- package/page/assets/{studio-trace-replay-B-WZNREk.js → studio-trace-replay-DOlV93ID.js} +1 -1
- package/page/assets/{studio-type-checker-2_B50AHd.js → studio-type-checker-Bnec_0A5.js} +1 -1
- package/page/assets/{tool-schema-CnrGGkcr.js → tool-schema-D2XhgIQV.js} +1 -1
- package/page/assets/{trace-record-CRYVqBZW.js → trace-record-D_urrJog.js} +1 -1
- package/page/assets/tree-b43adynw.js +3 -0
- package/page/assets/{turn-client-C_-rA6KF.js → turn-client-C8_eHuOA.js} +2 -2
- package/page/assets/types-BWEkmZ2G.js +1 -0
- package/page/assets/{use-one-call-By1S3qBT.js → use-one-call-_HnXCw32.js} +1 -1
- package/page/assets/{useDismissSearchOnTouchDrag-L_mBp0Dm.js → useDismissSearchOnTouchDrag-CWXS22k8.js} +1 -1
- package/page/assets/{workspace-ChRm7M3S.js → workspace-DT3XVg2T.js} +1 -1
- package/page/index.html +21 -21
- package/page/assets/browser-connection-BWOEEs03.js +0 -1
- package/page/assets/browser-engine-BxtG9nJ-.js +0 -16
- package/page/assets/encode-files-MPtLTYyk.js +0 -1
- package/page/assets/reader-BZ-mDuss.js +0 -5
- package/page/assets/registry-CqweoU_Q.js +0 -1
- package/page/assets/studio-live-uS2TgNK2.js +0 -5
- package/page/assets/tree-CZVr90dg.js +0 -3
- package/page/assets/types-DfwVnkMI.js +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{Da as e,Ea as t}from"./shaped-data-BxDmEUJe.js";function n(e){return e.map(e=>({name:e.name,mimeType:e.type||`application/octet-stream`,sizeBytes:e.size}))}function r(e){let n=[];for(let r of e){if(typeof r.data!=`string`||r.data.length===0)continue;let e=t(r.data),i=e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength);n.push(new File([i],r.name,{type:r.mimeType||`application/octet-stream`}))}return n}async function i(t){let n=[];for(let r of t)n.push({name:r.name,mimeType:r.type||`application/octet-stream`,data:e(new Uint8Array(await r.arrayBuffer()))});return n}function a(e,t,n){let r=0,i=0;return e.map(e=>{if(e.kind===`user-attachment`){let n=t?.[r]?.data;return r+=1,n===void 0?e:{...e,data:n}}if(e.kind===`user-voice`){let t=n?.[i]?.data;return i+=1,t===void 0?e:{...e,data:t}}return e})}export{r as i,i as n,n as r,a as t};
|
|
@@ -1,5 +0,0 @@
|
|
|
1
|
-
import{t as e}from"./preload-helper-DpV6A1kQ.js";import{C as t,D as n,E as r,O as i,S as a,T as o,b as s,c,d as l,g as u,h as d,l as f,m as p,p as m,u as h,v as g,x as _}from"./schemas-D7cgkv3L.js";import{U as v,X as y,s as b}from"./tool-schema-CnrGGkcr.js";import{$r as x,Ai as S,Br as ee,Ci as te,Cn as C,En as w,Fa as T,Ft as E,Ga as D,Gn as ne,Gr as O,Hi as re,Ia as ie,Ii as ae,Ir as oe,Jn as se,Ki as ce,Kn as le,Kr as ue,Li as de,Na as fe,Ni as pe,Oa as me,Or as k,Pa as he,Pr as ge,Qr as _e,Ri as ve,Rr as ye,Si as be,Ti as xe,Tn as Se,Un as Ce,Ut as we,Va as Te,Vn as Ee,Wn as De,Wt as Oe,Xa as ke,Xn as Ae,Xr as je,Yr as Me,Za as Ne,Zr as Pe,_i as Fe,ai as Ie,ao as Le,ar as Re,bi as ze,bn as Be,ci as Ve,co as A,dr as He,ei as Ue,er as We,fa as Ge,fi as Ke,fr as qe,ft as Je,ht as Ye,ii as Xe,ji as Ze,ka as Qe,ki as $e,lr as et,na as tt,ni as nt,no as rt,oo as it,pr as at,qa as ot,qn as st,qr as ct,ri as lt,rn as ut,ro as dt,sa as ft,si as pt,sr as mt,ti as ht,to as gt,ur as _t,vi as vt,wi as yt,wn as bt,xn as j,xr as xt,yr as St,za as Ct,zi as wt}from"./shaped-data-BxDmEUJe.js";import{c as M}from"./host-patterns-F-KZIzkF.js";import{C as Tt,S as Et,v as Dt,x as Ot}from"./browser-connection-BWOEEs03.js";import{A as kt,C as At,E as jt,M as Mt,N as Nt,P as Pt,T as Ft,_ as It,g as Lt,v as Rt,x as zt}from"./schema-Do4wX6Sr.js";import{a as Bt}from"./live-ingress-OuSlQ6q7.js";import{n as Vt,t as Ht}from"./trace-schema--4IGmLeE.js";import{n as Ut}from"./stub-CUHiDLLw.js";function Wt(e){return{type:`guardrail`,guardrail:e}}function Gt(e,t,n,r=`redact`,i){if(n.length!==0)return Wt({stage:e,trust:t,action:r,hits:n,...i?{provenance:i}:{}})}function Kt(e,t){return e.type===`guardrail`?{...e,guardrail:Qe(e.guardrail,t)}:e}var qt=65536;function N(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,P,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-CFjB39wS.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 F;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(!F){F=new Map;for(let e=0;e<qt;e++){let t=Qt(e),n=F.get(t);n?n.push(e):F.set(t,[e])}}return F.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 tn=new Map;function nn(e){let t=tn.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=N({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 tn.set(e,a),a}function rn(e){let t=JSON.stringify(e),n=tn.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=N({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 tn.set(t,s),s}function an(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 on(e,t){e.text+=t,e.fresh+=t}function sn(e){return e.text.length-e.fresh.length}function I(e,t){let n=sn(e);return t>=n?e.fresh.charCodeAt(t-n):e.text.charCodeAt(t)}function cn(e,t,n=e.text.length){let r=sn(e);return t>=r?e.fresh.slice(t-r,n-r):e.text.slice(t,n)}function ln(e){let t={text:``,fresh:``,rawAt:e=>e,update(){t.text=e.text,t.fresh=e.fresh}};return t}function un(e,t){let n={text:``,fresh:``,rawAt:e.rawAt,update(){n.fresh=``,on(n,t(cn(e,n.text.length)))}};return n}var dn=/\w/,fn=Math.max(...Pe.map(e=>e.length));function pn(e){return e.length<=fn+1&&/^[A-Za-z]*$/.test(e)}function mn(e){let t=0,n,r=!1,i=[],a=(e,t,n)=>{on(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(I(e,t)),o=dn.test(i);o&&!r&&(n=``),r=o,o?n===void 0?a(i,t,1):n+=i:(n!==void 0&&a(ht(n),t-n.length,n.length),n=void 0,a(i,t,1))}n!==void 0&&!pn(n)&&(a(n,t-n.length,n.length),n=void 0)}};return o}function hn(e){let t={text:``,fresh:``,from:[],rawAt:n=>n<t.from.length?t.from[n]:e(),update(){}};return t}function L(e,t,n){on(e,t);for(let r=0;r<t.length;r++)e.from.push(n)}var gn=55296,_n=56319,vn=/[A-Za-z]/,yn=56320,bn=57343;function xn(e){let t=0,n=``,r=[],i=``,a=[],o=!1,s=-1,c=hn(()=>Math.min(t,r[0]??t,a[0]??t,s<0?t:s));function l(e,t){s>=0&&(vn.test(e)||L(c,`\\`,s),s=-1),e===`\\`?s=t:L(c,e,t)}function u(e,t){if(nt(e)&&(o||i)){i+=e;for(let n=0;n<e.length;n++)a.push(t)}else{if(i){if(!vn.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=vn.test(e)&&e.length===1}}function d(){let e=0;for(;e<n.length;){let t=n.charCodeAt(e),i=t>=gn&&t<=_n;if(i&&e+1>=n.length)break;let a=n.charCodeAt(e+1),o=i&&a>=yn&&a<=bn?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=I(e,t),o=a>=gn&&a<=_n;if(o&&t+1>=i)break;let s=I(e,t+1),c=o&&s>=yn&&s<=bn?2:1,l=lt(cn(e,t,t+c));n+=l;for(let e=0;e<l.length;e++)r.push(t);t+=c}d()},c}var Sn=/[0-9A-Fa-f]/;function Cn(e){let t=0,n=-1,r=hn(()=>n<0?t:n);r.update=()=>{r.fresh=``;let a=e.text.length;for(;t<a;){let a=String.fromCharCode(I(e,t));if(n<0){a===`%`?n=t:(L(r,a,t),t++);continue}let o=(t-n)%3;if(o===0?a===`%`:Sn.test(a))t++;else{i(t-o);for(let n=t-o;n<t;n++)L(r,String.fromCharCode(I(e,n)),n)}}};function i(t){t>n&&L(r,_e(cn(e,n,t)),n),n=-1}return r}var wn=new Set([`injection`,`base64`,`hex`,`spaced`,`pipe`]),Tn=new Map(je.map(({pattern:e,hit:t})=>[e,t])),En=new Map(_t.flatMap(({pattern:e,hit:t})=>t?[[e,t]]:[]));function R(e){return{rule:fe(e),severity:`high`,detector:e}}var Dn=R(`injection`),On=R(`marker_leak`),kn=R(`tool_leak`);function An({kind:e,group:t}){if(wn.has(e))return Dn;switch(e){case`sensitive`:case`card`:return t===void 0?void 0:R(t);case`boundary`:return On;case`image`:return R(`ungiven_images`);default:return R(`ungiven_links`)}}function jn(e,t,n){if(e===`card`)return{hit:He};if(e===`image`||e===`link`){let r=(e===`image`?qe:at).indexOf(t),i=n[e][r];return`find`in i?{find:i.find}:{hit:i.test}}let r=Tn.get(t)??En.get(t);return r?{hit:r}:{}}function Mn(e,{given:t,allow:n,skipImages:r}){let i=e=>({...e,...t?{given:t}:{}}),a={image:St(i(n?.ungiven_images)),link:xt(i(n?.ungiven_links),r??e.includes(`ungiven_images`))},o=[];return mt.forEach((t,n)=>{let r=An(t);r?.detector&&e.includes(r.detector)&&o.push({...r,id:n,regex:Ie(t.pattern),...jn(t.kind,t.pattern,a)})}),o}function Nn(){let e=[];return mt.forEach(({kind:t,pattern:n},r)=>{if(t!==`injection`)return;let i=Tn.get(n);e.push({...Dn,id:r,regex:Ie(n),...i?{hit:i}:{}})}),e}function Pn(){return Xe.map((e,t)=>({...Dn,id:t,regex:new RegExp(e.source,e.flags)}))}function Fn(e,t,n){let r=an(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),te=n.flatMap((e,t)=>S[t]<0?[]:[t]),C=new Int32Array(t.has.length).fill(-1);function w(){let{text:n,fresh:h}=e,g=sn(e),{classOf:_,has:v,edges:te,final:w,pattern:T}=t;for(;p<n.length;p++){let e=_[p>=g?h.charCodeAt(p-g):n.charCodeAt(p)];f++;let t=0,E=(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++,w[e]&&(m[i[T[e]]]=1)};for(let t=0;t<l;t++){let n=te[a[t]],r=o[t];for(let t=0;t<n.length;t+=2)v[n[t+1]][e]&&E(n[t],r)}let D=r[e];for(let e=0;e<D.length;e++){let t=D[e],n=i[T[t]],r=S[n],a=r<0?-1:C[r],o=a<0?p:a;E(t,o),y[n]&&(x[n]=p,b[n]<0&&(b[n]=o))}for(let t of ee)v[t][e]?C[t]<0&&(C[t]=p):C[t]=-1;[a,s]=[s,a],[o,c]=[c,o],l=t}}function T(){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 te){let t=C[S[e]];t<0||(t<_[e]&&(_[e]=t),t<r&&(r=t))}return r}function E(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}}let D={text:``,lower:``},ne=()=>(D.text!==e.text&&(D={text:e.text,lower:e.text.toLowerCase()}),D.lower);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,ne)))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 re(){for(let e=0;e<n.length;e++){let t=_[e];if(t<=g[e])continue;let r=n[e].find?E(e,t):O(e,t);if(r)return r}}return{run(t){w();let n=T();for(let e=re();e;e=re())t.push(e);return e.rawAt(n)}}}var In=new WeakMap;function Ln(e){let t=In.get(e);return t||(t=N(e),In.set(e,t)),t}function Rn(e={}){let t={text:``,fresh:``},n=ln(t),r=[n],i=(e,t,n)=>(r.includes(e)||r.push(e),Fn(e,t,n)),a=[],o=e.detect??[],s=Mn(o,e);if(s.length>0&&(P??=N(Zt().forward),a.push(i(n,P,s))),o.includes(`injection`)){P??=N(Zt().forward),Yt??=N(Zt().reversed);let e=xn(t),r=Nn();a.push(i(n,Yt,Pn()),i(mn(n),P,r),i(e,P,r),i(mn(e),P,r),i(un(n,Ue),P,r),i(un(n,e=>x(e)??e),P,r),i(Cn(t),P,r))}if(o.includes(`marker_leak`)&&e.note){let t=et(e.note);a.push(i(n,nn(e.note),[{...On,id:0,regex:t}]))}if(o.includes(`tool_leak`)&&e.tools){let t=We(e.tools),r=t.map(({regex:e},t)=>({...kn,id:t,regex:e}));t.length>0&&a.push(i(n,rn(t.map(({literal:e})=>e)),r))}for(let{detector:t,compiled:r,matchers:o}of e.own??[]){let e=o.map(({regex:e},n)=>({...R(t),id:n,regex:new RegExp(e.source,e.flags)}));a.push(i(n,Ln(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 zn(e,t,n={},r=[]){let i=le(e,t).filter(e=>!(se(e)||r.includes(e))),a=st(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=Rn({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=ne(p,c,e,t,{detectors:o,scope:n});return m=m.filter(({start:e})=>e>=r+l.taken),l}}}function Bn(e){let{context:t}=e,n=e.detect,r=n?zn(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(-k),_=u,v=0,y=u,b=0,x=0,S=s?oe(s):void 0;S?.push(u);function te(e){let n=[];if(S?.push(e)&&n.push([a,me]),c){let r=_.length;_+=e;let i=Me(_,r);_=_.slice(i),v+=i;let[a]=Re(_,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?te(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-k),i=r+ge(y.slice(r-b),e);i<n&&n>t&&(y=g+h,b=t-g.length,i=b+ge(y,e)),x=Math.min(i,u.length+p.length-k);let a=Math.max(b,Math.max(t,x)-k);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+ct(i,e,t)-u.length-m)}function ne(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:O(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}:(O(s.taken),T({blocked:!1,emit:s.text??``,...s.action===`allow`?{}:{found:{action:s.action,hits:s.hits}}}))}function O(e){let t=h.slice(0,e);return h=h.slice(e),m+=t.length,l&&(g=(g+t).slice(-k)),t}return{process(e){return e?(p+=e,h+=e,l&&(y+=e),ne(e)):{blocked:!1,emit:``}},flush:()=>ne(),accumulated:()=>p,unreleased:()=>h,drainUnreleased:()=>O(h.length),carryOut:()=>l?ee(u+p,s,c):``}}function z(e,t,n){return De(t,e.detect,n)}async function Vn(e,t,n,r){return z(e,[n],t)?(await Xt(),Hn(e,t,n,r)):null}function Hn(e,t,n,r){return z(e,[n],t)?Bn({context:t,detect:{matrix:e.detect,boundary:n,rewrite:n===`reply`,scope:Ae(e,t)},...r?{carry:r}:{}}):null}async function Un(e,t,n,r){return z(e,[n],r??t)?(await Xt(),Bn({context:t,detect:{matrix:e.detect,boundary:n,rewrite:!1,scope:r??Ae(e,t)}})):null}var Wn=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}},Gn=[`user`,`options`,`repair`,`attachment`,`voice`,`history`,`system`];function Kn(e,t){return e&&Object.fromEntries(Object.entries(e).map(([e,n])=>[e,t.read(n)]))}var qn={client:`untrusted`,server:`assembled`};function Jn(e){return typeof e==`string`?e:JSON.stringify(e)}function Yn(e,t){let n=[],r=!1;if(!e)return{context:e,events:n,blocked:r};let i={};for(let a of yt){let o=e[a];if(o===void 0)continue;let s=t();i[a]=s.read(Jn(o));let c=s.found(),l=Ce(`context`,c);l&&n.push({...l,trust:qn[a]}),r||=c.action===`block`}return{context:i,events:n,blocked:r}}var Xn=/^[A-Za-z0-9._-]+$/,Zn=/^[A-Za-z0-9._:-]{1,32}$/;function Qn(e){if(e===void 0||Zn.test(e))return e;throw new M(`request`,`input.messageId must be 1 to 32 letters, digits, ".", "_", ":" or "-"`)}function $n(e){let t=e?.trim();return t&&Xn.test(t)?t:void 0}function er(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 tr(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 nr(e,t){let n=t?`: ${t}`:``;return new M(`input`,`guardrails.detect blocked the request at ${e}${n}`,{copy:{key:`detect.blocked`}})}function rr(e,t){let{detect:n}=w(t.guardrails),r=D(Gn,e=>Ee(e,n)),i=e.input??{},a=Qn(i.messageId),o=i.text===void 0?void 0:r.user.read(i.text),s=e.system===void 0?void 0:Nt(e.system,`TurnRequest.system`,e=>r.system.read(e)),c=Kn(i.options,r.options),l=Yn(i.context,()=>Ee(`context`,n)),u=er(i.repair,r.repair),d=i.history?tr(i.history,r.history):void 0,{attachments:f,voice:p}=i.attachments?.length||i.voice?.length?Tt(t,i.attachments,i.voice,r):i,m=[],h;for(let e of Gn){let t=r[e].found(),n=Ce(e,t);n&&m.push(Wt(n)),t.action===`block`&&(h??=nr(e,t.errorInternal))}return m.push(...l.events.map(Wt)),l.blocked&&(h??=nr(`context`)),{request:{...e,system:s,projectId:$n(e.projectId),input:{...i,text:o,...a===void 0?{}:{messageId:a},options:c,...l.context?{context:l.context}:{},repair:u,history:d,attachments:f,voice:p}},events:m,...h?{refusal:h}:{}}}function ir(e,t){let{request:n,refusal:r}=rr(e,t);if(r)throw r;return n}function ar(e,t){return[...new Set([...t.filter(t=>j(e,t)),...e.filter(e=>j(t,e))])]}function or(e,t){let n=e.attachments?t?ar(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 sr(e){let t=Se(e[0]??``);return t===`application/pdf`?`PDF`:t.split(`/`)[0]??t}function cr(e,t){let n=Et(e),r=Dt({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=>j(t.accept,e.mimeType)).length>t.max&&r.push({code:`too_many_of_kind`,params:{maxFiles:t.max,kind:sr(t.accept)}})}let i=new Set;return r.filter(e=>{let t=JSON.stringify(e);return!i.has(t)&&(i.add(t),!0)})}var lr=`final_answer`;function ur(e){return e.structured!==null&&e.tools.wire.length>0}function dr(e,t,n){let{structured:r}=t;if(!r||!ur(t))return e;let i={type:`function`,name:lr,description:A(`structured.answer_tool`,{},n),parameters:r.jsonSchema};return{...e,structured:null,wireTools:[...e.wireTools??[],i]}}function fr(e,t){return e.get(t)||{name:t,missing:!0}}function pr(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 mr(e,t){return[...Lt(t),...pr(t)].map(t=>fr(e,t))}function hr(e,t){if(Array.isArray(e)){for(let n of e)hr(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),hr(r,t);for(let e of Object.values(r))hr(e,t)}function gr(e,t){let n=mr(e,t);if(n.length===0)return;let r=new Set;for(let e of n)`inputSchema`in e&&hr(Je(e.inputSchema),r);return{names:n.map(({name:e})=>e),params:[...r]}}function _r(e){return!e||e.length===0?[]:e.slice(-4)}function vr(e,t){if(e.length===0)return``;let n=e.map(e=>`${e.role===`user`?`User`:`Assistant`}: ${e.content}`);return`${A(`repair.history_heading`,{count:e.length},t)}\n${n.join(`
|
|
2
|
-
`)}\n\n`}function yr(e){let{profile:t,repair:n,history:r}=e,i=n.guidance||A(`repair.default_guidance`,{},t.labels),a=vr(_r(r),t.labels),o=`${A(`repair.prompt_header`,{},t.labels)}\n\n`;return o+=`${A(`repair.prompt_intro`,{},t.labels)}\n\n`,o+=`${A(`repair.section_previous_output`,{},t.labels)}\n\`\`\`\n${n.previousOutput.trim()}\n\`\`\`\n\n`,o+=`${A(`repair.section_validator_rejection`,{},t.labels)}\n${n.rejection.trim()}\n\n`,i.trim()&&(o+=`${A(`repair.section_repair_guidance`,{},t.labels)}\n${i.trim()}\n\n`),a&&(o+=a),o+=`${A(`repair.section_instructions`,{},t.labels)}\n`,o+=A(`repair.prompt_instructions`,{},t.labels),o}function br(e,t){let n=[];return t&&n.push(`structured`),e.type===`image`&&n.push(`image`),e.type===`speech`&&n.push(`speech`),n}function xr(e,t){let n=br(e,t);if(!(n.length<=1))throw new M(`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 Sr(e,t){if(e.type!==`speech`){if(t.speech)throw new M(`request`,`Profile ${e.id} (${e.type}) takes no speech settings — only a speech profile speaks`)}else if(t.system)throw new M(`config`,`Profile ${e.id} (speech) takes no system prompt — the input text is the transcript`)}function Cr(e,t){if(e.type===`transcription`){if(t.system)throw new M(`config`,`Profile ${e.id} (transcription) takes no system prompt — the input is the clip`);if(!t.input?.voice?.length)throw new M(`request`,`Profile ${e.id} (transcription) requires a voice clip`)}}function wr(e,t){return e.type===`speech`?{...e.speech,...Tr(t.speech)}:void 0}function Tr(e){return Object.fromEntries(Object.entries(e??{}).filter(([,e])=>e!==void 0))}function Er(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 Dr(e){let t=Be(e);if(!t)throw new M(`input`,`MIME '${e}' is not a supported media input type`);return t}function Or(e){return e.map(e=>{let t=Dr(e.mimeType),n=Se(e.mimeType),r=n===`image/jpg`?`image/jpeg`:n;return Ot(e)?{type:t,mimeType:r,uri:e.uri}:{type:t,mimeType:r,data:e.data}})}function kr(e,t){let{text:n,repair:r,history:i}=t.input??{};if(e.type===`speech`&&!n?.trim())throw new M(`request`,`Profile ${e.id} (speech) requires text input`);if(C(e)?.text===!1&&n)throw new M(`request`,`Profile ${e.id} does not accept text input`);let a=r?yr({profile:e,repair:r,history:i}):jr(e,t)??n;if(e.type===`speech`)return a?{type:`text`,text:a}:null;let o=[...Ar(t),...a?[ue(a,t.input?.messageId)]:[]];return o.length>0?{type:`text`,text:o.join(`
|
|
3
|
-
|
|
4
|
-
`)}:null}function Ar(e){let t=e.input?.context??{};return[...yt].reverse().filter(e=>t[e]!==void 0).map(e=>O(e,Jn(t[e])))}function jr(e,t){if(t.continueFrom&&E.includes(e.type)){if(t.input?.text)throw new M(`request`,`Profile ${e.id}: a continueFrom turn takes no input.text — its user message is the continue instruction`);return A(`continue.instruction`,{},e.labels)}}function Mr(e){return e.type===`image`&&e.image.references?Or(e.image.references):[]}function Nr(e,t){let n=t.input?.attachments??[],r=t.input?.voice??[];return[...Mr(e),...Or(n),...Or(r)]}function Pr(e,t){let n=[],r=kr(e,t);return r&&n.push(r),n.push(...Nr(e,t)),n}function Fr(e,t){let n=t.input?.context;if(!n)return;let r=C(e)?.context;for(let[t,i]of Object.entries(n))if(i!==void 0){if(!yt.includes(t)||!r?.from.some(e=>e===t))throw new M(`request`,`Profile ${e.id} takes no context from '${t}'`);if(Jn(i).length>r.maxChars)throw new M(`request`,`Profile ${e.id}: context from '${t}' is over inputs.context.maxChars (${String(r.maxChars)})`)}}function Ir(e,t){if(e.type===`speech`||e.type===`transcription`)return[];let n=e.identity.system;if(!n)return[];let r=kt(e,t);return At(n,r,t=>jt(e,t,r))}function Lr(e,t){let n=Ir(e,t);return{pieces:Mt([...n.map(({pieces:e})=>e),t.system===void 0?[]:Pt(t.system)]),lines:n.map(({line:e})=>e)}}function Rr(e){return e.type!==`host`&&e.type!==`decision`&&e.type!==`embedding`}function zr(e,t){if(Rr(e))return e;throw e.type===`host`?new M(`request`,`Profile ${e.id}: type 'host' never runs a model — ${t} is not supported; execute tools with invokeTool`):e.type===`embedding`?new M(`request`,`Profile ${e.id}: type 'embedding' runs through runEmbedding — ${t} is not supported`):new M(`request`,`Profile ${e.id}: type 'decision' runs through runDecision — ${t} is not supported`)}function Br(e,t){if(t){if(!e.allowModelSelect)throw new M(`request`,`Profile ${e.id} does not allow model selection`);if(!e.models[t])throw new M(`request`,`Unknown model '${t}' for ${e.id}`);return t}return e.defaultModel}function Vr(e,t,n,r){let i=t.efforts;if(!i||Object.keys(i).length===0){if(r)throw new M(`request`,`Profile ${e.id} model '${n}' has no selectable efforts`);return}let a=Object.keys(i);if(r){if(!t.allowEffortSelect)throw new M(`request`,`Profile ${e.id} model '${n}' does not allow effort selection`);let a=i[r];if(!a)throw new M(`request`,`Unknown effort '${r}' for ${e.id} model '${n}'`);return a}return i[t.defaultEffort??a[0]]}function Hr(e){if(e.summaries===!0)return`auto`;if(e.summaries===!1)return`none`}function Ur(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 Wr(e){return e.type===`live`||e.outputs?.streaming?.mode!==`buffered`}function Gr(e,t){return e.type===`live`?`live`:`turn`}function Kr(e,t){if(!t.continueFrom)return;if(e.type===`live`)throw new M(`request`,`Profile ${e.id}: type 'live' uses live.sessionResumption, not turnBehaviour.resumption/continueFrom`);let n=Oe(e)?.maxContinues;if(n===void 0)return;let r=t.continuation;if(r===void 0)throw new M(`request`,`Profile ${e.id}: continueFrom requires TurnRequest.continuation when turnBehaviour.resumption.maxContinues is set`);if(r<1)throw new M(`request`,`Profile ${e.id}: continuation must be >= 1`);if(r>n)throw new M(`request`,`Profile ${e.id}: continuation ${r} exceeds turnBehaviour.resumption.maxContinues (${n})`)}function qr(e,t){return z(w(t),[`live_reply`])?{...e,transcription:{...e?.transcription,output:!0}}:e}function Jr(e){let{detect:t}=w(e.guardrails);return e.type!==`speech`&&e.type!==`transcription`&&Ge(t,`canary_leak`)?ye():``}function Yr(e,t,n,r){if(!r)return;let i={};for(let[a,o]of Object.entries(r)){if(!n.builtInTools?.includes(a))throw new M(`request`,`Profile ${e.id}: builtInArgs names '${a}', which model '${t}' does not list in builtInTools`);i[a]=o}return i}function Xr(e,t,n){let r=zr(e.profiles.get(t.profile),`resolveTurn`);Ft(r,t),Fr(r,t);let i=ir(t,r),a=i.input??{};Kr(r,i);let o=n??Br(r,i.model),s=bt(r,o),c=zt(e.tools,r,i,o),l=c.builtins,u=Ur(r,kt(r,i));if(xr(r,u),u&&c.wire.some(e=>e.name===`final_answer`))throw new M(`config`,`Profile ${r.id}: a structured turn answers through '${lr}', so no tool of its own may take that name`);Sr(r,i),Cr(r,i);let d=Yr(r,o,s,i.builtInArgs),f=Gr(r,s),p=e.providers.get(s.provider),m=p&&ut(p,s,r.type),h=Lr(r,i);return{profile:r,generation:{model:o,apiId:s.apiId,transport:f,...m?{operationName:m}:{},stream:Wr(r),thinking:Vr(r,s,o,i.effort),summaries:Hr(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:Ye(e.schemas.get(u).jsonSchema)}:null,image:Er(r),speech:wr(r,i),live:r.type===`live`?qr(r.live,r.guardrails):void 0,input:Pr(r,i),canary:Jr(r),resolvedSystem:h.pieces,systemLines:h.lines,host:i.host}}}function Zr(e){return e.type===`image`?e.image:null}function Qr(e,t){let n=zr(t,`projectProfile`),{identity:r}=n,i=C(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:mr(e,n),inputs:i,outputs:a,image:Zr(n),speech:n.type===`speech`?n.speech:null,live:n.type===`live`?n.live:null}}function $r(e,t){return Qr(e.tools,e.profiles.get(t))}var ei=[`audio/webm;codecs=opus`,`audio/webm`,`audio/mp4`,`audio/wav`,`audio/mpeg`];function ti(e){return e.join(`,`)}function ni(e){let t=e?.attachments?.accept,n=e?.voice?.accept;return{text:e?.text!==!1,attachments:t?.length?{accept:t,acceptAttr:ti(t)}:null,voice:n?.length?{accept:n}:null,maxFiles:e?.maxFiles,maxBytes:e?.maxBytes,maxTurnBytes:e?.maxTurnBytes,limitsByMime:e?.limitsByMime,options:e?.options,context:e?.context}}function ri(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,options:e.options,context:e.context}}function ii(e,t){let n=e=>(e??[]).map(({name:e,mimeType:t,sizeBytes:n})=>({name:e,mimeType:t,sizeBytes:n})),r=Dt({attachments:e.attachments?.accept,voice:e.voice?.accept,limits:Et(ri(e))},n(t.attachments),n(t.voice));return{ok:r.length===0,issues:r}}function ai(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(ei.filter(t=>j(e,t)))??e.find(n):r(ei)}var oi=_({protocol:r(),provider:r(),apiId:r(),options:t(r(),u()).optional(),keySlot:r().optional(),fallbackKeySlot:r().optional(),efforts:t(r(),c(wt)).optional(),defaultEffort:r().optional(),allowEffortSelect:m().optional(),summaries:m().optional(),maxOutputTokens:s().optional(),temperature:s().optional(),builtInTools:l(r()).optional(),compaction:_({maxTokens:s(),compactAt:s(),previousExchanges:s(),profile:r().optional(),timing:c(te),meter:c(be).optional()}).optional(),limits:_({operationTimeoutMs:s().optional(),connectTimeoutMs:s().optional(),liveStepTimeoutMs:s().optional(),maxWireRecordBytes:s().optional(),maxWireResponseBytes:s().optional(),maxEventBytes:s().optional(),maxStepBytes:s().optional(),maxStepEvents:s().optional(),maxPendingToolCalls:s().optional()}).optional()}),si=_({structured:n([r(),_({by:r(),map:t(r(),r()),fallback:r()}),f()]).optional(),streaming:_({mode:c(ve).optional(),streamThoughts:m().optional()}).optional()}),ci=_(D(Te,()=>c(ft))),li=_(D(tt,()=>ci)),ui=_({id:r(),label:r(),actions:ci,names:l(r()),find:m()}),di=_({hosts:l(r()),fromTools:m()}),fi=_({quota:_({perDay:s()}).optional(),detect:li,patterns:a(c(tt),_({theorem:m(),names:l(r())})).optional(),host:l(ui).optional(),allow:_({ungiven_images:di,ungiven_links:di}),blockedReply:_({onBlock:c(Ct),maxRetries:s()})}),pi=n([m(),_({theorem:m(),host:m()})]),mi=_({record:m(),writeTo:n([g(!1),r()]).optional(),sampleRate:s(),include:_({upstreamLog:m(),outboundWire:m(),evidenceRaw:m(),usage:m(),guardrailDecisions:m(),guardrailMatchPreview:m()}),scrub:_({sensitive:pi,injection:pi,canary:pi}),resource:Ht,retainForDays:s(),rotateAfterMiB:s(),hasOnWriteError:m()}),hi=t(r(),_({label:r().optional(),choices:l(_({value:r(),description:r().optional()}))})),B=_({text:m(),attachments:_({accept:l(r()),acceptAttr:r()}).nullable(),voice:_({accept:l(r())}).nullable(),maxFiles:s().optional(),maxBytes:s().optional(),maxTurnBytes:s().optional(),limitsByMime:t(r(),s()).optional(),options:hi.optional(),context:_({from:l(c(yt)),maxChars:s()}).optional()}),gi=_({allowContinue:l(c(xe)).optional(),autoContinue:l(c(xe)).optional(),maxContinues:s().optional()}),_i=_({resumption:gi.optional()}),vi=_({allow:l(r()),page:l(r()),t2Loader:r().optional(),parallel:m().optional()}),V={providerContinuation:_({history:c([`host`,`stateless`,`provider`]).optional()}).optional(),id:r(),models:t(r(),oi),defaultModel:r(),allowModelSelect:m().optional(),maxSteps:s().optional(),labels:a(c(Le),r()),guardrails:fi.optional(),observability:mi.optional()},yi=n([r(),o({private:r().min(1)})]),bi=n([r(),l(n([r(),l(yi).readonly()])).min(1).readonly()]),xi=_({handle:r(),options:hi.optional(),system:bi.optional()}),H=d(`type`,[_({...V,type:g(`text`),identity:xi,outputs:si.optional(),inputs:B,tools:vi,turnBehaviour:_({resumption:gi.optional(),allowSteering:m().optional(),atStepLimit:c(de).optional()}).optional(),canStop:g(!0),allowSteering:m()}),_({...V,type:g(`image`),identity:xi,outputs:si.optional(),image:_({aspectRatio:r().optional(),resolution:r().optional(),mimeType:r().optional(),quality:r().optional(),background:r().optional(),n:s().int().min(1).optional(),seed:s().int().optional(),outputCompression:s().int().min(0).max(100).optional(),references:l(n([_({mimeType:r(),data:r(),name:r().optional()}),_({mimeType:r(),uri:r(),name:r().optional()})])).optional(),includeText:m().optional()}),inputs:B,tools:vi,turnBehaviour:_i.optional(),canStop:g(!0)}),_({...V,type:g(`transcription`),identity:_({handle:r()}),maxSteps:h().optional(),outputs:si.optional(),inputs:B,canStop:g(!0)}),_({...V,type:g(`speech`),identity:_({handle:r()}),outputs:si.optional(),speech:_({voice:r().optional(),style:r().optional(),speed:s().optional(),format:c(ae).optional()}),inputs:B,turnBehaviour:_i.optional(),canStop:g(!0)}),_({...V,type:g(`live`),identity:xi,inputs:B.pick({options:!0,context:!0}).optional(),live:_({ingress:_({audio:m().optional(),video:m().optional(),text:m().optional()}).optional(),voice:r().optional(),vad:_({activityHandling:c($e).optional(),startSensitivity:c(Ze).optional(),endSensitivity:c(S).optional(),prefixPaddingMs:s().optional(),silenceDurationMs:s().optional()}).optional(),sessionResumption:m().optional(),contextCompression:_({triggerTokens:s().optional(),slidingWindow:_({targetTokens:s().optional()})}).optional(),transcription:_({input:m().optional(),output:m().optional()}).optional()}),tools:vi.pick({allow:!0,page:!0}),turnBehaviour:_({allowSteering:m().optional()}).optional()})]);function Si(e){let t=w(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:Ci(t.allow.ungiven_images),ungiven_links:Ci(t.allow.ungiven_links)},blockedReply:t.blockedReply}}function Ci(e){return{hosts:[...e.hosts??[]],fromTools:e.fromTools??!0}}function wi(e){return e===void 0||e===!1||typeof e==`string`?e:`custom`}function Ti(e){if(!e)return;let t=Bt(e);return{record:t.record,writeTo:wi(t.writeTo),sampleRate:t.sampleRate,include:t.include,scrub:t.scrub,resource:t.resource,retainForDays:t.retainForDays,rotateAfterMiB:t.rotateAfterMiB,hasOnWriteError:!!t.onWriteError}}function Ei(e){let{greeting:t,resumed:n,...r}=e??{};return r}function Di(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=Rt(t),r=It(t);return{allow:[...Lt(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 Oi({allow:e,page:t}){return{allow:e,page:t}}function ki(e,t){let n=ni(e.inputs),r=t?.identity??{handle:e.handle},i=t?Si(t.guardrails):void 0,a=t?Ti(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:it(t?.labels)};switch(e.type){case`text`:return H.parse({...s,type:`text`,inputs:n,tools:Di(e,t),turnBehaviour:t?.type===`text`?t.turnBehaviour:void 0,canStop:!0,allowSteering:!t||we(t)});case`image`:return H.parse({...s,type:`image`,image:e.image??{},inputs:n,tools:Di(e,t),turnBehaviour:t?.type===`image`?t.turnBehaviour:void 0,canStop:!0});case`speech`:return H.parse({...s,type:`speech`,speech:e.speech??{},inputs:n,turnBehaviour:t?.type===`speech`?t.turnBehaviour:void 0,canStop:!0});case`transcription`:return H.parse({...s,type:`transcription`,inputs:n,canStop:!0});case`live`:return H.parse({...s,type:`live`,live:Ei(e.live),...e.inputs?{inputs:{options:n.options,context:n.context}}:{},tools:Oi(Di(e,t))});default:return e.type}}function Ai(e,t){let n=zr(e,`interfaceFromProfile`);return ki(Qr(t,n),n)}function ji(e){return p(t=>Fe.safeParse(e(t)).success)}var Mi=[`running`,`gate`,`background`,`complete`,`error`,`cancel`],Ni=p(e=>{let t=Fe.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 Mi.some(e=>e===n)}),Pi=t(r(),i()),Fi=_({operationId:r().optional(),name:r(),callId:r(),arguments:Pi,draft:r().optional(),reasoning:l(Ke).optional(),stepId:r().optional(),edited:_({from:Pi,to:Pi}).optional(),activity:r().optional(),activityPast:r().optional(),outputDraft:r().optional(),state:Ni.optional(),startedAt:s().optional(),endedAt:s().optional(),get steps(){return l(Fi).optional()}}),Ii=_({kind:c(ce),native:r().optional()}),U={id:r()},W=d(`kind`,[_({...U,kind:g(`user-text`),text:r()}),_({...U,kind:c([`user-attachment`,`user-voice`]),name:r(),mimeType:r(),sizeBytes:s(),data:r().optional()}),_({...U,kind:g(`thought`),text:r()}),_({...U,kind:g(`text`),text:r()}),_({...U,kind:g(`tool`),tool:Fi}),_({...U,kind:g(`structured`),value:i(),draft:r().optional()}),_({...U,kind:g(`media`),mimeType:r(),data:r().optional(),uri:r().optional(),type:c(pe).optional(),fromTool:g(!0).optional(),sent:g(!0).optional()}),_({...U,kind:g(`grounding`),grounding:ji(e=>({type:`grounding`,grounding:e}))}),_({...U,kind:g(`citation`),sources:ji(e=>({type:`citation`,sources:e})),callId:r().optional()}),_({...U,kind:g(`evidence`),evidence:ji(e=>({type:`evidence`,evidence:e}))}),_({...U,kind:g(`guardrail`),guardrail:ie}),_({...U,kind:g(`late-results`),text:r(),operationIds:l(r()),inReply:m()}),_({...U,kind:g(`error`),message:r()}),_({...U,kind:g(`turn-done`),stop:Ii.optional(),tokens:ji(e=>({type:`tokens`,tokens:e})).optional(),interactionId:r().optional(),compaction:m().optional(),workedMs:s().optional(),endedAt:s().optional()})]),Li=_({type:r()});function Ri(e,t){return Object.hasOwn(e,t)}function zi(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=>zi(e,n)).join(` | `)}]`}).join(`; `)}function Bi(e){return zi(e.issues,[])}function Vi(e,t){return new M(`bad_response`,`${e} failed its wire check: ${Bi(t)}`)}function G(e,t,n){let r=e.safeParse(t);if(!r.success)throw Vi(n,r.error);return r.data}function Hi(e){return{type:`malformed`,error:new M(`bad_response`,e,{copy:{key:`session.part_skipped`}})}}function Ui(e,t){let n=Li.safeParse(t);if(!n.success)return Hi(`a line without a kind failed its wire check: ${Bi(n.error)}`);let{type:r}=n.data;if(!Ri(e,r))return{type:`unsupported`,received:r,raw:t};let i=e[r].safeParse(t);return i.success?i.data:Hi(`a '${r}' line failed its wire check: ${Bi(i.error)}`)}function Wi(e){try{return{value:JSON.parse(e)}}catch(e){if(e instanceof SyntaxError)return;throw e}}function Gi(e,t){let n=Wi(t);return n?Ui(e,n.value):Hi(`a line is not JSON`)}function Ki(e){let t=Wi(e);if(!t)throw new M(`bad_response`,`a line is not JSON`);return t.value}var qi=_({name:r(),mimeType:r(),data:r()}),Ji=_({options:t(r(),r()).optional(),context:i().optional(),text:r().optional(),attachments:l(qi).optional(),voice:l(qi).optional()}),Yi=_({gateKind:c(re).optional(),sessionPermissions:l(r()).optional(),name:r().optional(),input:i().optional(),snapshot:ze.optional(),promoted:l(r()).optional(),model:r().optional(),effort:r().optional()}),K=r().trim().min(1),Xi=_({path:r().optional(),options:t(r(),r()).optional()}),Zi=Xi;_({input:Ji,conversation:r().min(1).optional(),model:r().optional(),effort:r().optional(),stated:Xi.optional(),turnId:K.optional(),abandon:l(Ve).min(1).optional(),replay:Yi.pick({sessionPermissions:!0}).optional(),transcript:l(W).optional()});var Qi=[`approve`,`deny`],$i=n([o({unanswered:g(!0)}),o({output:i()}).refine(e=>`output`in e).transform(e=>({output:e.output}))]);_({gateId:r().min(1),operationId:r().min(1).max(256),decision:c(Qi),input:i().optional(),secret:r().optional(),page:$i.optional(),conversation:r().min(1).optional(),turnId:K.optional(),replay:Yi.optional()}),_({turnId:K,id:K,inject:l(vt).min(1)}),_({turnId:K});var ea=_({type:g(`conversation`),ref:r().min(1),posted:g(!0).optional()}),ta={...pt,conversation:ea},na=_({transcript:l(W),paused:_({events:l(Fe),blocks:l(W)}).optional(),notify:_({retryMs:s().optional()}).optional(),wake:g(!0).optional()});_({conversation:r().min(1)}),_({conversation:r().min(1),input:Ji.pick({options:!0,context:!0}).optional(),model:r().optional(),effort:r().optional(),turnId:K.optional()}),o({});var ra={changed:_({type:g(`changed`)})};_({conversation:r().min(1),at:s().int().min(-1)}),_({blocks:l(W)});var ia=_({conversation:r().min(1),view:na}),aa=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 oa(e){return e instanceof aa}function sa(e){return e?.trim()||void 0}var ca=_({error:r().optional(),errorKind:T.optional(),errorCopy:he.optional(),errorInternal:r().optional()}),la=ca;function ua(e,t){let n=sa(e.error),r=sa(e.errorInternal);return new aa(e.errorKind??t,n,r&&r!==n?r:void 0,e.errorCopy)}function da(e){return!oa(e)||e.copy===void 0?!1:(Array.isArray(e.copy)?e.copy:[e.copy]).some(e=>e.key===`session.conversation_unknown`)}function fa(e,t){let n=Gi(e,t);if(n.type===`error`)throw ua(ca.parse(n),`internal`);return n}function pa(e,t,n){let r=e.split(`
|
|
5
|
-
`),i=r.pop()??``;for(let e of r)e.trim()&&n(fa(t,e));return i}async function ma(e,t,n,r){if(!e.body)throw new M(`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(;;){gt(r);let{done:e,value:s}=await i.read();if(e)break;o=pa(o+a.decode(s,{stream:!0}),t,n)}let e=o.trim();e&&n(fa(t,e))}finally{r?.removeEventListener(`abort`,s)}}async function ha(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 ga(e,t){let n=await e.text(),r;try{r=JSON.parse(n),t?.(r)}catch{return ua({errorInternal:`HTTP ${String(e.status)}`},Ne(e.status))}let i=ca.safeParse(r);return i.success?ua({...i.data,errorInternal:i.data.errorInternal??`HTTP ${String(e.status)}`},Ne(e.status)):new M(`bad_response`,`HTTP ${String(e.status)} error body failed its wire check`)}async function _a(e,t,n){let r=n.fetch??globalThis.fetch.bind(globalThis);try{return await r(e,{...t,headers:await ha(n),credentials:n.credentials??`same-origin`})}catch(e){throw ke(e)?e:new M(`network`,ot(e),{cause:e})}}async function q(e,t,n,r,i={}){await ma(await va(e,t,i),n,r,i.signal)}async function va(e,t,n){let r=await _a(e,{method:`POST`,body:JSON.stringify(t),signal:n.signal},n);if(!r.ok)throw await ga(r);return r}async function ya(e,t,n={}){await va(e,t,n)}async function J(e,t,n={}){let r=await _a(e,{...t.body===void 0?{method:`GET`}:{method:`POST`,body:JSON.stringify(t.body)},signal:t.signal},n);if(!r.ok)throw await ga(r,t.failed);return Ki(await r.text())}async function ba(e,t,n={}){let{signal:r,...i}=n;return G(na,await J(e,{body:t,signal:r},i),`the conversation`)}async function xa(e,t,n,r){let{signal:i,...a}=n;return G(ia,await J(e,{body:t,signal:i},a),r)}function Sa(e,t,n={}){return xa(e,t,n,`the rewound conversation`)}function Ca(e,t,n={}){return xa(e,t,n,`the started conversation`)}function wa(e){let t=e.length;for(;t>0&&e[t-1]===`/`;)--t;return e.slice(0,t)}var Ta=_({interface:H});function Ea(e={}){let t=wa(e.endpoint??`/api/theorem`);return{async describe(n){let r=await _a(t,{method:`GET`,signal:n},e);if(!r.ok)throw await ga(r);return G(Ta,Ki(await r.text()),`the profile description`).interface},turn:({replay:n,...r},i,a)=>q(`${t}/turn`,r,ta,i,{...e,signal:a}),invoke:({replay:n,...r},i,a)=>q(`${t}/invoke`,r,ta,i,{...e,signal:a}),conversation:(n,r)=>ba(`${t}/conversation`,n,{...e,signal:r}),wake:(n,r,i)=>q(`${t}/wake`,n,ta,r,{...e,signal:i}),notify:(n,r)=>q(`${t}/notify`,{},ra,e=>{e.type===`changed`&&n()},{...e,signal:r}),rewind:(n,r)=>Sa(`${t}/rewind`,n,{...e,signal:r}),pageResult:(n,r)=>ya(`${t}/page-result`,n,{...e,signal:r}),steer:n=>ya(`${t}/steer`,n,e),stop:n=>ya(`${t}/stop`,n,e)}}function Da(e,t){if(typeof e==`string`)return e;let n=Array.isArray(e)?e:Object.keys(e);return n.length?Da(n[0],t):t}function Oa(e){return Object.entries(e).map(([e,t])=>({id:e,type:t.type,labels:t.type===`choice`?Object.keys(t.criteria):t.type===`score`?t.criteria.map((e,t)=>Da(e,String(t))):[],...t.type===`box`&&t.image!==void 0?{image:t.image}:{}}))}function ka(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:Oa(t),...n&&Object.keys(n).length>0?{images:n}:{},...e.observability?{observability:{record:Bt(e.observability).record}}:{}}}function Aa(e,t){let n=Object.keys(t??{}).find(t=>e&&Object.hasOwn(e,t));if(n!==void 0)throw new M(`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 Y=s().min(0).max(1),ja=t(r(),Y),Ma=d(`type`,[_({type:g(`choice`),choice:r(),confidence:Y,probabilities:ja}),_({type:g(`noul`),noul:Y}),_({type:g(`box`),box:_({top:Y,bottom:Y,left:Y,right:Y}),confidence:Y}),_({type:g(`score`),score:s().nonnegative(),confidence:Y,legend:t(r(),r().min(1)),probabilities:ja})]),Na=_({id:r(),type:c([`choice`,`noul`,`score`,`box`]),labels:l(r()),image:r().optional()}),Pa=_({result:_({model:r().min(1),questions:l(Na).optional(),answers:t(r(),Ma),usage:_({inputTokens:s().int().nonnegative(),outputTokens:s().int().nonnegative(),costUsd:s().nonnegative().optional()}).optional()}),traces:l(Vt).optional()}),Fa=new WeakMap;function Ia(e,t){return t.length>0&&typeof e==`object`&&e&&Fa.set(e,t),e}function La(e){return typeof e==`object`&&!!e&&Fa.get(e)||[]}var Ra=_({traces:l(Vt)});async function za(e,t,n,r,i){let a=[],o=e=>{let t=Ra.safeParse(e);t.success&&(a=t.data.traces)};try{return i(await J(e,{body:t,signal:n,failed:o},r))}catch(e){throw Ia(e,a)}}function Ba(e,t,n,r={}){return za(e,t,n,r,Va)}function Va(e){return G(Pa,e,`the decision`)}var Ha=_({interface:_({type:g(`decision`),identity:_({handle:r()}),contract:r(),maxStateBytes:s().optional(),questions:l(Na),build:_({input:t(r(),i()).optional()}).optional(),images:t(r(),_({mimeType:c([`image/png`,`image/jpeg`]),data:r()})).optional(),observability:_({record:m()}).optional()})});function Ua(e={}){let t=(e.endpoint??`/api/decision`).replace(/\/$/,``);return{async describe(n){return G(Ha,await J(t,{signal:n},e),`the decision description`).interface},decide:(n,r,i,a)=>Ba(`${t}/decide`,{state:n,...i?{assets:i}:{},...a===void 0?{}:{input:a}},r,e)}}function Wa(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ga(e,t){let n=e;for(let e of t){if(!Wa(n))return;n=n[e]}return typeof n==`string`&&n?n:void 0}function Ka(...e){return t=>{let n=Ga(t,e);return n?[{url:n,sent:!0}]:[]}}var qa={random_dog_image:Ka(`message`),wikipedia_summary:Ka(`originalimage`,`source`),get_pokemon:Ka(`sprites`,`other`,`official-artwork`,`front_default`)};function Ja(e){return qa[e]}function Ya(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function X(e,t){let n=e[t];return typeof n==`string`&&n.trim()?n.trim():void 0}function Z(e,t){if(!URL.canParse(t))return;let n=new URL(t);if(n.protocol===`http:`||n.protocol===`https:`)return{title:e.trim()||n.hostname.replace(/^www\./,``),uri:n.href,type:`web`}}function Xa(e){let t=new Set;return e.filter(e=>!t.has(e.uri)&&(t.add(e.uri),!0))}function Za(e){let t=[...e.matchAll(/\[([^\]]+)\]\((https?:\/\/[^)\s]+)\)/g)].flatMap(e=>Z(e[1]??``,e[2]??``)??[]),n=[...e.matchAll(/https?:\/\/[^\s"'<>\]]+/g)].flatMap(e=>{let t=(e[0]??``).replace(/[),.;:]+$/,``);return Z(t,t)??[]});return Xa([...t,...n])}function Qa(e){if(Array.isArray(e))return e;if(!Ya(e))return[];for(let t of[`items`,`results`,`search_results`,`models`,`datasets`]){let n=e[t];if(Array.isArray(n))return n}return[]}function $a(e,t){return Xa(e.flatMap(e=>Ya(e)?t(e)??[]:[]))}function eo(e,t){let n=t===`dataset`?`https://huggingface.co/datasets/`:`https://huggingface.co/`;return $a(Qa(e),e=>{let t=X(e,`id`)??X(e,`modelId`);return t?Z(t,`${n}${t}`):void 0})}function to(e){return $a(Qa(e),e=>{let t=X(e,`html_url`),n=X(e,`full_name`)??X(e,`name`);return t?Z(n??t,t):void 0})}function no(e){let t=e,n;do n=t,t=t.replace(/<[^>]+>/g,``);while(t!==n);return t.replace(/\s+/g,` `).trim()}function ro(e){if(typeof e!=`string`)return Za(JSON.stringify(e));let t=[...e.matchAll(/<entry\b[\s\S]*?<\/entry>/g)];return t.length===0?Za(e):Xa(t.flatMap(e=>{let t=/<id>(https?:\/\/[^<]+)<\/id>/.exec(e[0]??``)?.[1],n=/<title>([\s\S]*?)<\/title>/.exec(e[0]??``)?.[1];return t?Z(no(n??t),t)??[]:[]}))}function Q(e){if(typeof e==`string`)return Za(e);if(Array.isArray(e)||Ya(e)){let t=$a(Qa(e),e=>{let t=X(e,`html_url`)??X(e,`url`)??X(e,`source_url`)??X(e,`contentUrl`),n=X(e,`title`)??X(e,`name`)??t;return t?Z(n??t,t):void 0});return t.length>0?t:Za(JSON.stringify(e))}return[]}var io={search_models:e=>eo(e,`model`),search_datasets:e=>eo(e,`dataset`),search_github:to,list_arxiv:ro,search_web:Q,read_pages:Q,read_model_card:Q,read_dataset_card:Q,read_readme:Q,find_library:Q,read_library_docs:Q,ask_repo_docs:Q};function ao(e){return io[e]}function oo(e,t){let n=ao(e);return n?{...t,sources:n}:t}function so(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}:{},...t.after?{after:!0}:{},...t.background?{background:t.background}:{}};if(t.type===`agent`){e.register({...r,type:`agent`,profile:t.profile,...t.maxCallsPerTurn===void 0?{}:{maxCallsPerTurn:t.maxCallsPerTurn}});return}let i={...r,input:b(t.inputSchema),output:b(t.outputSchema)};if(t.type===`http`){let n=Ja(t.name);e.register(oo(t.name,{...n?{media:n}:{},...i,type:`http`,endpoint:t.endpoint,method:t.method,headers:t.headers,mapping:t.mapping,auth:t.auth,maxResponseBytes:t.maxResponseBytes}));return}if(t.type===`mcp`){e.register(oo(t.name,{...i,type:`mcp`,serverUrl:t.serverUrl,mcpToolName:t.mcpToolName,headers:t.headers,auth:t.auth,maxResponseBytes:t.maxResponseBytes,session:t.session}));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??Ut(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 co(e,t,n){e.registerMany([...v,...y]);for(let r of t)so(e,r,n)}function lo(e,t,n,r,i){if(co(e.tools,n,i),r&&t.type!==`live`)for(let{id:t,spec:n}of[r,...r.also??[]])e.schemas.register(t,n);return e.profiles.register(t),t}function uo(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 fo(e){if(e.type!==`error`&&e.type!==`session`&&e.type!==`tool`&&e.type!==`hook_failed`||e.errorInternal===void 0)return e;let{errorInternal:t,...n}=e;return n}function po(e){if(e.type!==`compaction`||e.failure?.errorInternal===void 0)return e;let{errorInternal:t,...n}=e.failure;return{...e,failure:n}}function mo(e){if(e.type!==`guardrail`||!(e.guardrail?.errorInternal||e.guardrail?.errorSummary))return e;let{errorInternal:t,errorSummary:n,...r}=e.guardrail;return{...e,guardrail:r}}function ho(e){if(e.type!==`done`||e.mediaRefused===void 0)return e;let{mediaRefused:t,...n}=e;return n}function go(e){if(e.type!==`evidence`||!e.evidence?.raw)return e;let{raw:t,...n}=e.evidence;return{...e,evidence:n}}function _o(e,t){if(e.type!==`tool`||e.tool.phase!==`progress`)return e;let{data:n}=e.tool;if(typeof n!=`object`||!n||!(`agent`in n)||!(`event`in n))return e;let r=$(n.event,t);return{...e,tool:{...e.tool,data:{...n,event:r}}}}function $(e,t){let n=_o(e,t),r=t?.reader===`builder`?uo(n):ho(po(mo(fo(n))));return t?.includeEvidenceRaw||(r=go(r)),r=Kt(r,!1),r}function vo(e,t){return e.map(e=>$(e,t))}function yo(e,t,n){let{error:r=``,errorKind:i,errorCopy:a}=$(dt(rt(e),t),n);return{error:r,errorKind:i,...a?{errorCopy:a}:{}}}var bo={reader:`builder`};function xo(e){return e.mode===`demo`?{reader:`visitor`}:bo}export{Wn as $,Bi as A,Fr as B,la as C,q as D,ya as E,ai as F,dr as G,gr as H,ii as I,nr as J,cr as K,Br as L,Ui as M,W as N,Zi as O,Ai as P,rr as Q,$r as R,ua as S,da as T,lr as U,Pr as V,ur as W,tr as X,Yn as Y,ir as Z,Ea as _,vo as a,Rn as at,Sa as b,Ua as c,Wt as ct,La as d,Un as et,Ba as f,aa as g,ta as h,$ as i,zn as it,Gi as j,G as k,Aa as l,Kt as lt,Ia as m,xo as n,Hn as nt,lo as o,Xt as ot,za as p,or as q,yo as r,z as rt,co as s,Gt as st,bo as t,Vn as tt,ka as u,ba as v,oa as w,Ca as x,J as y,Xr as z};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{D as e,E as t,T as n,b as r,c as i,d as a,h as o,o as s,p as c,pt as l,s as ee,t as u,v as d}from"./schemas-D7cgkv3L.js";import{Cn as te,Fa as f,La as ne,Q as re,Ra as ie,Zi as p,ba as ae,co as m,hi as h,it as g,li as oe,q as se,si as _,ut as v,vi as y,xa as b}from"./shaped-data-BxDmEUJe.js";import{c as x}from"./host-patterns-F-KZIzkF.js";import{c as ce,d as le,i as S,n as C,o as ue,t as w,u as de}from"./schema-Do4wX6Sr.js";var fe=n({accepted:ae,preparedInput:b});function T(e){return new x(`internal`,e)}function E(e,t,n){return new x(e,t,{copy:{key:`tool.execution_uncertain`},cause:n})}function D(e){return E(`conflict`,`The tool operation is ${e}, so it does not run again until the host settles it`)}async function O(e){let t=e=>Array.isArray(e)?e.map(t):e&&typeof e==`object`?Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0).sort(([e],[t])=>e<t?-1:+(e>t)).map(([e,n])=>[e,t(n)])):e,n=b.parse(t(P(e))),r=await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(JSON.stringify(n)));return Array.from(new Uint8Array(r),e=>e.toString(16).padStart(2,`0`)).join(``)}var k=_.tool.transform((e,t)=>e.tool.phase===`complete`||e.tool.phase===`error`?{...e,tool:e.tool}:(t.addIssue({code:`custom`}),l)),A=n({finding:t(),data:b.optional(),parts:a(oe).optional(),media:a(h).optional(),hidden:d(!0).optional(),modelText:t().optional(),provenance:ie.optional(),suspicious:a(ne).optional()}),j=_.tool.transform((e,t)=>e.tool.phase===`background`?{...e,tool:e.tool}:(t.addIssue({code:`custom`}),l)),M=n({event:j,replay:n({modelResult:A})}),N=n({event:k,effects:i([`not_started`,`completed`,`unknown`]),replay:n({modelResult:A.optional(),outputRaw:b.optional(),failure:n({code:t(),kind:f,message:t(),error:t().optional(),details:b.optional()}).optional(),awaiting:c().optional(),denied:d(!0).optional(),callNotStarted:c().optional(),aborted:e([c(),n({reason:t().optional()})]).optional(),pendingInject:a(n({id:t().optional(),messages:a(y),released:r().int().nonnegative().optional()})).optional(),ended:d(!0).optional()})});function P(e){let t=new Set,n=e=>{if(!e||typeof e!=`object`)return e;if(t.has(e))throw T(`Tool operation value has a cycle`);let r=Object.getPrototypeOf(e);if(!Array.isArray(e)&&r!==Object.prototype&&r!==null)throw T(`Tool operation value holds an object that is not plain data`);if(Object.hasOwn(e,`__proto__`))throw T(`Tool operation value has an own __proto__ key`);t.add(e);try{if(Array.isArray(e))return e.map(n);let t=Object.entries(Object.getOwnPropertyDescriptors(e)),r=t.find(([,e])=>e.get||e.set);if(r)throw T(`Tool operation value has a getter or setter at '${r[0]}'`);return Object.fromEntries(t.filter(([,e])=>e.enumerable&&e.value!==void 0).map(([e,t])=>[e,n(t.value)]))}finally{t.delete(e)}};return b.parse(n(e))}var F=e([i([`always`,`ask`,`never`]),n({afterMs:r().finite().nonnegative()})]),I=`background`;function L(){return c().optional().describe(m(`tool.background_field`))}function R(e,t){if(e?.background!==`ask`||typeof t!=`object`||!t)return{input:t,asked:!1};let{[I]:n,...r}=t;return{input:r,asked:n===!0}}function z(e,t){let{background:n}=e;if(n!==void 0&&n!==`never`)return n===`always`?`claim`:n===`ask`?R(e,t).asked?`claim`:void 0:n}function B(e,t){return e.type===`agent`?t?.takesSteers(e)?void 0:`steering_off`:`not_agent`}function V(e){let{tool:t,support:n,base:r,labels:i}=e;if(!t||t.type===`builtin`||!n)return;let a=z(t,e.input);if(a===void 0)return;let o=B(t,e.agents);return{at:a,support:n,...o?{refuseSteers:o}:{},trace:n.openTrace(r.callId),reply:()=>{let e={finding:m(`tool.background_started`,{tool:t.name},i)},n=re(e),a=se(r,{phase:`background`,readBack:n});return M.parse(P({event:a,replay:{modelResult:e}}))}}}function pe(e,t){if(e&&!t?.detach)throw new x(`config`,`A request with a background service needs a coordinator with detach`)}function me(e){let{name:t,background:n}=e;if(n!==void 0&&n!==`never`){if(e.answeredBy===`page`)throw new x(`config`,`Tool '${t}' sets background, which a tool answered by the page cannot`);if(!F.safeParse(n).success)throw new x(`config`,typeof n==`object`?`Tool '${t}' sets background.afterMs, which must be a time in milliseconds`:`Tool '${t}' sets background to ${JSON.stringify(n)}; it takes 'always', 'ask', 'never' or { afterMs }`)}}var he=/^[\x21-\x7E]{1,256}$/;function H(e=Date.now){let t=new Map,n=new Map,r=({tool:e,max:n})=>{if(n===void 0)return;let r=[...t.values()].filter(t=>t.tool===e).length;for(let[i,a]of t){if(r<=n)break;a.tool===e&&(t.delete(i),r--)}};return{get(n,i){let a=t.get(n);if(a&&(t.delete(n),!(i.idleMs!==void 0&&e()-a.usedAt>i.idleMs)))return t.set(n,{...a,usedAt:e(),tool:i.tool}),r(i),{id:a.id,protocolVersion:a.protocolVersion}},open(i,a,o){let s=n.get(i);if(s)return s;let c=o().then(n=>(t.delete(i),t.set(i,{...n,usedAt:e(),tool:a.tool}),r(a),n)).finally(()=>n.delete(i));return n.set(i,c),c},drop(e,n){t.get(e)?.id===n&&t.delete(e)},clear(){t.clear(),n.clear()}}}function ge(e){return e!==null&&he.test(e)}async function _e(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(``)}var U=`after`;function ve(){return a(t()).optional().describe(m(`tool.after_field`))}function W(t,n,r,i){let a=n=>{if(n instanceof s){if(r in n.shape)throw new x(`config`,`Tool '${t}' sets ${r}, and its input already has a field of that name`);return n.safeExtend({[r]:i()})}if(n instanceof u){let e=n.options.map(a);return o(n.def.discriminator,e)}if(n instanceof ee)return e(n.options.map(a));throw new x(`config`,`Tool '${t}' sets ${r}, which needs an object input or a union of objects`)};return a(n)}function G(e,t){return W(e,t,U,ve)}function ye(e,t){if(!e.after||typeof t!=`object`||!t)return{input:t,names:[]};let{[U]:n,...r}=t;return{input:r,names:n??[]}}function be(e,t,n){return n?e.flatMap(e=>{let r=n.filter(n=>n.tool===e&&n.callId!==t).map(e=>e.callId);return r.length>0?r:[e]}):[]}var K=class{value;constructor(e){this.value=e}};function xe(e){return new K(e)}function Se(e){return(t,n)=>{let{page:r}=n;if(r&&`output`in r)return xe(r.output);let{labels:i}=n.profile;throw r?.timedOut?Error(m(`tool.page_timed_out`,{},i)):Error(m(`tool.page_no_answer`,{tool:e},i))}}var q=new WeakMap;function J(e,t){let n=q.get(e);n||(n=new WeakMap,q.set(e,n));let r=n.get(t);if(!r){let i=C(e,`input`);S(i,`input`);let a=C(t,`output`);S(a,`output`),r={inputSchema:i,outputSchema:a},n.set(t,r)}return r}function Y(e){let{inputSchema:t,outputSchema:n}=J(e.input,e.output);v(t,`Tool "${e.name}" input`,`input`),v(n,`Tool "${e.name}" output`,`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?g(n,r[t]):void 0;if(i)throw new x(`config`,`Tool "${e.name}" ${t} label: ${i}`)}return{inputSchema:structuredClone(t),outputSchema:structuredClone(n)}}function Ce(e,t){if(t&&(typeof t.service!=`string`||!t.service.trim()))throw new x(`config`,`Tool "${e}" signs in with slot "${t.slot}" but names no service`)}function X(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 x(`config`,`Tool "${e}" auth.queryParam ${r}`)}function we(e,t){if(t!==void 0&&!(Number.isInteger(t.requests)&&t.requests>0&&Number.isFinite(t.windowMs)&&t.windowMs>0))throw new x(`config`,`Tool "${e}" limit needs a whole number of requests above 0 and a window above 0 ms`)}function Z(e,t){if(!(t===void 0||Number.isFinite(t)&&t>0))throw new x(`config`,`Tool "${e}" timeoutMs needs a finite number of ms above 0`)}function Q(e,t,n){if(!(n===void 0||Number.isInteger(n)&&n>0))throw new x(`config`,`Tool "${e}" ${t} needs a whole number above 0`)}function Te(e){Q(e.name,`maxResponseBytes`,e.maxResponseBytes);let t=e.imageLimits;t&&(Q(e.name,`imageLimits.count`,t.count),Q(e.name,`imageLimits.bytes`,t.bytes),Q(e.name,`imageLimits.totalBytes`,t.totalBytes),Z(e.name,t.timeoutMs))}function $(e){if(e.type!==`builtin`&&me({name:e.name,...e.background===void 0?{}:{background:e.background},...e.answeredBy?{answeredBy:e.answeredBy}:{}}),e.type===`builtin`||e.type===`agent`)return;Ce(e.name,e.auth),e.type===`http`?(e.endpoint?.trim()&&w(e.endpoint),X(e.name,e.auth,e.mapping?.queryParams),we(e.name,e.limit),Z(e.name,e.timeoutMs)):X(e.name,e.auth),(e.type===`http`||e.type===`mcp`)&&Te(e),e.type===`mcp`&&(Q(e.name,`session.idleMs`,e.session?.idleMs),Q(e.name,`session.max`,e.session?.max));let[t]=p(e);if(t)throw new x(`config`,`Tool "${e.name}" ${t.path} ${t.message}`)}function Ee(e){return w(e.endpoint),{...e,type:`http`,...Y(e)}}function De(e){return{...e,type:`mcp`,...Y(e)}}function Oe(e){let t=e.answeredBy===`page`?Se(e.name):e.handler;if(typeof t!=`function`)throw new x(`config`,`Tool '${e.name}' needs a handler, or answeredBy: 'page'`);return{...e,handler:t,type:`function`,...Y(e)}}function ke(e){if(e.type===`builtin`||e.background!==`ask`)return e;let t=e.input,n=W(e.name,t,`background`,L);return{...e,askInputSchema:J(n,e.output).inputSchema}}function Ae(e,t,n){return $(e),ke(je(e,t,n))}function je(e,t,n){if(e.type===`builtin`)return e;if(e.type===`agent`){let r=de(e,t,n),i=te(r),a=ue({type:r.type,...i?{inputs:i}:{}},e),o=e.after?G(e.name,a):a,s=Y({...e,input:o,output:ce});return le(e,o,s)}let r=e.after?{...e,input:G(e.name,e.input)}:e;return r.type===`http`?Ee(r):r.type===`mcp`?De(r):Oe(r)}function Me(e=()=>void 0,t=()=>[]){let n=new Map,r=H(),i=e=>n.get(e),a=t=>{let r=Ae(t,e,i);return n.set(r.name,r),r};return{register:a,registerMany:e=>e.map(e=>a(e)),get:i,require(e){let t=i(e);if(!t)throw new x(`config`,`Tool '${e}' is not registered`);return t},has:e=>n.has(e),list:()=>[...n.values()],findProfile:e,structuredReplies:t,reset:()=>{n.clear(),r.clear()},mcpSessions:r}}export{N as _,be as a,_e as c,R as d,D as f,O as g,fe as h,ye as i,pe as l,P as m,Me as n,H as o,T as p,K as r,ge as s,$ as t,V as u,M as v,E as y};
|
|
@@ -1,5 +0,0 @@
|
|
|
1
|
-
import{r as e}from"./rolldown-runtime-hePW80VL.js";import{d as t,l as n}from"./themeProps-Bo2jNkIC.js";import{n as r,t as i}from"./LayoutContent-BWpUj2Iy.js";import{t as a}from"./Icon-Cd9sDRzY.js";import{a as o,c as s,l as c,p as l,u}from"./SidePanel-DcAhRInK.js";import{t as d}from"./Text-Cq4yqBpQ.js";import{t as f}from"./Button-Bwkht0RI.js";import{b as p,g as m,p as h,t as g}from"./browser-transport-rFxtbMn0.js";import{t as _}from"./createReactComponent-DVEyVJ-p.js";import{t as v}from"./Center-CPu_uP6i.js";import{g as y,h as b,m as x,n as S,o as C,r as w,s as T,t as ee,u as E}from"./studio-media-C6h3z2kJ.js";import{t as D}from"./IconMicrophone-BT77cilC.js";import{Da as O,Ea as k,co as A,qa as j}from"./shaped-data-BxDmEUJe.js";import{c as M}from"./host-patterns-F-KZIzkF.js";import{S as N,g as P,r as F,t as I}from"./reader-BZ-mDuss.js";import{i as L}from"./live-ingress-OuSlQ6q7.js";import{a as te,b as ne}from"./turn-client-C_-rA6KF.js";import{r as re,t as ie}from"./live-messages-DekE0UkG.js";import{t as ae}from"./EmptyState-DW-8doL9.js";import"./use-second-ticker-Dd57a-0O.js";import{c as oe}from"./ShapedData-DYRlNRy_.js";import{a as se,n as R,t as ce}from"./labels-provider-BOmB5WmP.js";import{t as z}from"./HStack-B00ufja5.js";import{t as B}from"./IconButton-BenRR-zK.js";import{t as V}from"./VStack-D1ZLA9g3.js";import{t as H}from"./StackItem-nWHq5y--.js";import{t as le}from"./Toolbar-DVp0Jb7c.js";import{t as U}from"./ToggleButton-DS8nQhRT.js";import{t as ue}from"./Dialog-tyH-Jv5A.js";import{C as de,E as W,K as fe,M as G,N as pe,Ot as me,S as he,b as ge,bt as _e,dt as ve,u as ye,vt as be,yt as xe}from"./index-C6pyNvXU.js";var Se=_(`outline`,`arrows-diagonal-minimize-2`,`ArrowsDiagonalMinimize2`,[[`path`,{d:`M18 10h-4v-4`,key:`svg-0`}],[`path`,{d:`M20 4l-6 6`,key:`svg-1`}],[`path`,{d:`M6 14h4v4`,key:`svg-2`}],[`path`,{d:`M10 14l-6 6`,key:`svg-3`}]]),Ce=_(`outline`,`camera-rotate`,`CameraRotate`,[[`path`,{d:`M5 7h1a2 2 0 0 0 2 -2a1 1 0 0 1 1 -1h6a1 1 0 0 1 1 1a2 2 0 0 0 2 2h1a2 2 0 0 1 2 2v9a2 2 0 0 1 -2 2h-14a2 2 0 0 1 -2 -2v-9a2 2 0 0 1 2 -2`,key:`svg-0`}],[`path`,{d:`M11.245 15.904a3 3 0 0 0 3.755 -2.904m-2.25 -2.905a3 3 0 0 0 -3.75 2.905`,key:`svg-1`}],[`path`,{d:`M14 13h2v2`,key:`svg-2`}],[`path`,{d:`M10 13h-2v-2`,key:`svg-3`}]]),we=_(`outline`,`microphone-off`,`MicrophoneOff`,[[`path`,{d:`M3 3l18 18`,key:`svg-0`}],[`path`,{d:`M9 5a3 3 0 0 1 6 0v5a3 3 0 0 1 -.13 .874m-2 2a3 3 0 0 1 -3.87 -2.872v-1`,key:`svg-1`}],[`path`,{d:`M5 10a7 7 0 0 0 10.846 5.85m2 -2a6.967 6.967 0 0 0 1.152 -3.85`,key:`svg-2`}],[`path`,{d:`M8 21l8 0`,key:`svg-3`}],[`path`,{d:`M12 17l0 4`,key:`svg-4`}]]),Te=_(`outline`,`phone-off`,`PhoneOff`,[[`path`,{d:`M3 21l18 -18`,key:`svg-0`}],[`path`,{d:`M5.831 14.161a15.946 15.946 0 0 1 -2.831 -8.161a2 2 0 0 1 2 -2h4l2 5l-2.5 1.5c.108 .22 .223 .435 .345 .645m1.751 2.277c.843 .84 1.822 1.544 2.904 2.078l1.5 -2.5l5 2v4a2 2 0 0 1 -2 2a15.963 15.963 0 0 1 -10.344 -4.657`,key:`svg-1`}]]),K=_(`outline`,`phone`,`Phone`,[[`path`,{d:`M5 4h4l2 5l-2.5 1.5a11 11 0 0 0 5 5l1.5 -2.5l5 2v4a2 2 0 0 1 -2 2a16 16 0 0 1 -15 -15a2 2 0 0 1 2 -2`,key:`svg-0`}]]),Ee=_(`outline`,`subtitles`,`Subtitles`,[[`path`,{d:`M18 5a3 3 0 0 1 3 3v8a3 3 0 0 1 -3 3h-12a3 3 0 0 1 -3 -3v-8a3 3 0 0 1 3 -3l12 0`,key:`svg-0`}],[`path`,{d:`M7 15h5`,key:`svg-1`}],[`path`,{d:`M15 15h2`,key:`svg-2`}],[`path`,{d:`M17 12h-3`,key:`svg-3`}],[`path`,{d:`M11 12h-1`,key:`svg-4`}]]),De=_(`outline`,`video-off`,`VideoOff`,[[`path`,{d:`M3 3l18 18`,key:`svg-0`}],[`path`,{d:`M15 11v-1l4.553 -2.276a1 1 0 0 1 1.447 .894v6.764a1 1 0 0 1 -.675 .946`,key:`svg-1`}],[`path`,{d:`M10 6h3a2 2 0 0 1 2 2v3m0 4v1a2 2 0 0 1 -2 2h-8a2 2 0 0 1 -2 -2v-8a2 2 0 0 1 2 -2h1`,key:`svg-2`}]]),Oe=_(`outline`,`video`,`Video`,[[`path`,{d:`M15 10l4.553 -2.276a1 1 0 0 1 1.447 .894v6.764a1 1 0 0 1 -1.447 .894l-4.553 -2.276v-4`,key:`svg-0`}],[`path`,{d:`M3 8a2 2 0 0 1 2 -2h8a2 2 0 0 1 2 2v8a2 2 0 0 1 -2 2h-8a2 2 0 0 1 -2 -2l0 -8`,key:`svg-1`}]]);function ke(e){return e.status===`reconnecting`?`reconnecting`:e.toolName?`calling_tool`:e.connectPhase===`socket`?`connecting`:e.connectPhase===`microphone`?`requesting_mic`:e.status===`speaking`?`speaking`:e.status===`listening`||e.status===`ready`?e.voiceEnabled===!1?`connected`:e.isMuted?`muted`:`listening`:e.status===`connecting`?`connecting`:e.status===`error`?`error`:`ended`}function Ae(e){return!(e.isMuted||!e.socketOpen||e.modelPlaying&&e.rms<e.bargeInRmsWhileSpeaking)}function je(e){let{evidence:t,text:n}=e;return!n||t.kind!==`input_transcription`&&t.kind!==`output_transcription`?null:{text:n,isUser:t.kind===`input_transcription`,interim:t.interim===!0}}function Me(e,t){if(e.phase===void 0){t.toolCalls.push({id:e.callId,name:e.name,arguments:e.arguments,...e.operationId?{operationId:e.operationId}:{}});return}if(e.phase===`cancel`){t.cancelledToolIds.add(e.callId);return}if(e.phase!==`error`)return;let n=t.toolCalls.findIndex(t=>t.id===e.callId);n!==-1&&t.toolCalls.splice(n,1)}var q=new Set;async function Ne(e){let{executeToolOnRelay:t,name:n,toolArgs:r,callId:i,operationId:a}=e,o=e.pageTools&&Object.hasOwn(e.pageTools,n)?e.pageTools[n]:void 0,s=await t({callId:i,operationId:a}),c=new Set;for(;s.status!==`settled`;){if(s.status===`dispatched`){if(c.has(s.grantId))return;c.add(s.grantId);let e=s.grantId,r=s.arguments;!o&&!q.has(n)&&(q.add(n),console.warn(`Theorem: page tool '${n}' has no handler in pageTools; the agent gets no answer.`));let l=o?await Promise.resolve().then(()=>o(r,{callId:i,operationId:a})).catch(()=>void 0):void 0;s=await t({callId:i,operationId:a,grantId:e,...l?{output:l.output}:{unanswered:!0}});continue}let{gate:l}=s,u=l.kind===`page`||!e.onGate?{decision:`deny`}:await e.onGate({callId:i,toolName:n,input:l.preparedArguments??r,gate:l});if(u===`withdrawn`)return;if(u.decision===`deny`){await t({callId:i,operationId:a,decision:`deny`});return}s=await t({callId:i,decision:`approve`,operationId:a,...u.secret===void 0?{}:{secret:u.secret}})}}function Pe(e){if(!(e instanceof Error))return!1;let t=`name`in e&&typeof e.name==`string`?e.name:``;return t===`NotAllowedError`||t===`PermissionDeniedError`||/permission|not allowed|denied/i.test(e.message)}var Fe=`mic-capture-processor`;function Ie(){return new URL(`data:text/javascript;base64,LyoqCiAqIEF1ZGlvV29ya2xldCBwcm9jZXNzb3IgdGhhdCBmb3J3YXJkcyBtb25vIG1pYyBmcmFtZXMgdG8gdGhlIG1haW4gdGhyZWFkLgogKiBQbGFpbiBKUzogaXQgcnVucyBpbiB0aGUgQXVkaW9Xb3JrbGV0R2xvYmFsU2NvcGUgYXMgaXRzIG93biBtb2R1bGUsIGxvYWRlZAogKiBieSBVUkwgKHNlZSBgLi4vbWljLWNhcHR1cmUudHNgKSwgc28gaXQgaW1wb3J0cyBub3RoaW5nIGFuZCBzaGlwcyBhcyBpcy4KICovCnJlZ2lzdGVyUHJvY2Vzc29yKAogICdtaWMtY2FwdHVyZS1wcm9jZXNzb3InLAogIGNsYXNzIE1pY0NhcHR1cmVQcm9jZXNzb3IgZXh0ZW5kcyBBdWRpb1dvcmtsZXRQcm9jZXNzb3IgewogICAgcHJvY2VzcyhpbnB1dHMpIHsKICAgICAgY29uc3QgY2hhbm5lbCA9IGlucHV0c1swXVswXTsKICAgICAgY29uc3QgY29weSA9IG5ldyBGbG9hdDMyQXJyYXkoY2hhbm5lbCk7CiAgICAgIHRoaXMucG9ydC5wb3N0TWVzc2FnZShjb3B5LCBbY29weS5idWZmZXJdKTsKICAgICAgcmV0dXJuIHRydWU7CiAgICB9CiAgfSwKKTsK`,``+import.meta.url)}function Le(e,t,n=16e3){if(t===n)return Re(e);let r=t/n,i=Math.round(e.length/r),a=new Int16Array(i),o=0,s=0;for(;o<a.length;){let t=Math.round((o+1)*r),n=0,i=0;for(let r=s;r<t&&r<e.length;r++)n+=e[r]??0,i++;a[o]=ze(i>0?n/i:0),o++,s=t}return a}function Re(e){let t=new Int16Array(e.length);for(let n=0;n<e.length;n++)t[n]=ze(e[n]??0);return t}function ze(e){let t=Math.max(-1,Math.min(1,e));return t<0?t*32768:t*32767}function Be(e){let t=new DataView(e.buffer,e.byteOffset,e.byteLength),n=new Float32Array(e.byteLength/2);for(let e=0;e<n.length;e++){let r=t.getInt16(e*2,!0);n[e]=r/(r<0?32768:32767)}return n}function J(e){return JSON.stringify(e)}function Ve(){return{toolCalls:[],mediaChunks:[],cancelledToolIds:new Set}}var He=.05,Ue=[500,1e3,2e3,4e3,8e3];function Y(e){return e instanceof Error?e:new M(`internal`,j(e),{cause:e})}function X(e){if(e&&typeof e.disconnect==`function`)try{e.disconnect()}catch{}}function We(e){if(e&&typeof e.getTracks==`function`)for(let t of e.getTracks())t.stop()}function Ge(e){let t=be(e.inputFloat32),n=e.hasPlaybackNodes||e.status===`speaking`;return Ae({isMuted:e.isMuted,socketOpen:e.wsOpen,modelPlaying:n,rms:t,bargeInRmsWhileSpeaking:He})}function Ke(e,t){return e===`listening`&&t?`working`:e===`working`&&!t?`listening`:null}var qe=class{ws=null;audioContext=null;micStream=null;micSource=null;micWorklet=null;micWorkletModuleLoaded=!1;playbackNodes=[];playbackBus=null;playbackAnalyser=null;playbackMeterFrame=0;playbackMeterBuffer=null;nextPlaybackTime=0;status=`disconnected`;serverWorking=!1;micActivating=!1;connectTimeout=null;isMuted=!1;options;inboundChain=Promise.resolve();audioChain=Promise.resolve();toolChain=Promise.resolve();audioEpoch=0;pendingExecuteResults=new Map;context;sentContext;history=[];providerState;sessionOver=!1;droppedAt;lostAt;reconnectTries=0;reconnectTimer=null;constructor(e){this.options=e,this.context=e.context}setStatus(e){this.status=e,(e===`listening`||e===`disconnected`||e===`error`)&&this.clearConnectTimeout(),this.options.onStatusChange?.(e)}get opening(){return this.status===`connecting`||this.status===`reconnecting`}setConnectPhase(e){this.options.onConnectPhase?.(e)}clearConnectTimeout(){this.connectTimeout&&=(clearTimeout(this.connectTimeout),null)}detachWebSocket(){for(let[e,t]of this.pendingExecuteResults)t.reject(new M(`network`,`live session closed before call ${e} settled`));if(this.pendingExecuteResults.clear(),this.ws){this.ws.onopen=null,this.ws.onmessage=null,this.ws.onclose=null,this.ws.onerror=null;try{this.ws.close()}catch{}this.ws=null}}clearReconnect(){this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=null,this.reconnectTries=0,this.droppedAt=void 0}teardownConnection(){this.clearConnectTimeout(),this.micActivating=!1,this.setConnectPhase(null),this.detachWebSocket(),this.cleanupAudio()}failSession(e){this.status!==`error`&&this.status!==`disconnected`&&(this.clearReconnect(),this.teardownConnection(),this.options.onError?.(e),this.setStatus(`error`))}createSocket(e){return this.options.createSocket?.()??new WebSocket(e)}connect(){let e=this.lostAt;return this.clearReconnect(),this.lostAt=void 0,e===void 0?(this.providerState=void 0,this.history=[]):this.droppedAt=e,this.open(`connecting`)}startOver(){return this.status!==`connecting`||!this.providerState?!1:(this.providerState=void 0,this.droppedAt=void 0,this.open(`connecting`),!0)}openMessage(){let{options:e,stated:t,model:n,effort:r,openMessage:i}=this.options;return{type:`open`,...this.history.length?{history:structuredClone(this.history)}:{},...e?{options:e}:{},...t?{stated:t}:{},...n?{model:n}:{},...r?{effort:r}:{},...this.context===void 0?{}:{context:this.context},...this.providerState?{resume:{providerState:this.providerState,awayMs:this.droppedAt===void 0?0:Date.now()-this.droppedAt}}:{},...i?{host:i}:{}}}handleDrop(){!this.providerState||this.sessionOver?(this.teardownConnection(),this.setStatus(`disconnected`)):(this.droppedAt??=Date.now(),this.teardownConnection(),this.setStatus(`reconnecting`),this.scheduleReconnect())}scheduleReconnect(){let e=Ue[this.reconnectTries];if(e===void 0){let e=this.droppedAt;this.failSession(new M(`network`,`live call dropped and could not reconnect`)),this.lostAt=e}else this.reconnectTries+=1,this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.open(`reconnecting`)},e)}failOpen(e){this.status===`reconnecting`?(this.teardownConnection(),this.scheduleReconnect()):this.startOver()||this.failSession(e)}async open(e){this.teardownConnection(),this.sessionOver=!1,this.setStatus(e),e===`connecting`&&this.setConnectPhase(`socket`);try{let e=globalThis.AudioContext;this.audioContext=new e,this.audioContext.state===`suspended`&&await this.audioContext.resume();let t=globalThis.location.protocol===`https:`?`wss:`:`ws:`,n=this.options.profile?`?profile=${encodeURIComponent(this.options.profile)}`:``,r=`${t}//${globalThis.location.host}/api/live/relay${n}`,i=this.options.relayUrl||r;this.ws=this.createSocket(i),this.ws.binaryType=`arraybuffer`,this.ws.onopen=()=>{let e=this.openMessage();this.sentContext=JSON.stringify(e.context),this.ws?.send(JSON.stringify(e))},this.connectTimeout=setTimeout(()=>{this.opening&&this.failOpen(new M(`timeout`,`live connect timed out`))},2e4),this.ws.onmessage=e=>{this.enqueueServerMessage(e.data)},this.ws.onclose=()=>{this.opening?this.failOpen(new M(`network`,`live socket closed before ready`)):this.handleDrop()},this.ws.onerror=()=>{!this.opening&&this.providerState&&!this.sessionOver?this.handleDrop():this.failOpen(new M(`network`,`live socket error`))}}catch(e){this.failOpen(new M(`internal`,j(e),{cause:e}))}}async ensureAudioContext(){if(!this.audioContext||this.audioContext.state===`closed`){let e=globalThis.AudioContext;this.audioContext=new e,this.audioContext.state===`suspended`&&await this.audioContext.resume()}}async activateMicrophone(){if(!this.micActivating&&this.opening){this.micActivating=!0,this.status===`connecting`&&this.setConnectPhase(`microphone`);try{await this.ensureAudioContext(),this.micStream=await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}}),await this.setupMicrophonePipeline(),this.becomeReady()}catch(e){let t=Pe(e);this.failSession(new M(t?`auth`:`internal`,j(e),{cause:e,copy:{key:t?`voice.permission`:`voice.unavailable`}}))}finally{this.micActivating=!1}}}sendMicFrame(e,t){let n=Le(e,t,16e3),r=O(new Uint8Array(n.buffer)),i=this.ws;i?.readyState===WebSocket.OPEN&&i.send(J({type:`audio`,data:r}))}reportMicVolume(e){this.isMuted||this.options.onVolumeLevel?.(xe(e),!0)}forwardMicBuffer(e){if(this.reportMicVolume(e),Ge({isMuted:this.isMuted,wsOpen:this.ws?.readyState===WebSocket.OPEN,hasPlaybackNodes:this.playbackNodes.length>0,status:this.status,inputFloat32:e})){let t=this.audioContext?this.audioContext.sampleRate:48e3;this.sendMicFrame(e,t)}}async setupMicrophonePipeline(){if(!this.micStream||!this.audioContext)return;this.micSource=this.audioContext.createMediaStreamSource(this.micStream);let e=this.audioContext.createGain();e.gain.value=0,this.micWorkletModuleLoaded||=(await this.audioContext.audioWorklet.addModule(Ie()),!0),this.micWorklet=new AudioWorkletNode(this.audioContext,Fe),this.micWorklet.port.onmessage=e=>{let t=new Float32Array(e.data);this.forwardMicBuffer(t)},this.micSource.connect(this.micWorklet),this.micWorklet.connect(e),e.connect(this.audioContext.destination)}ensurePlaybackBus(){this.audioContext&&!this.playbackBus&&(this.playbackBus=this.audioContext.createGain(),this.playbackAnalyser=this.audioContext.createAnalyser(),this.playbackAnalyser.fftSize=512,this.playbackAnalyser.smoothingTimeConstant=.35,this.playbackBus.connect(this.playbackAnalyser),this.playbackAnalyser.connect(this.audioContext.destination),this.playbackMeterBuffer=new Uint8Array(this.playbackAnalyser.fftSize))}stopPlaybackMeter(){this.playbackMeterFrame&&=(cancelAnimationFrame(this.playbackMeterFrame),0),this.options.onVolumeLevel?.(0,!1)}startPlaybackMeter(){if(this.playbackMeterFrame)return;let e=()=>{this.playbackNodes.length===0||!this.playbackAnalyser||!this.playbackMeterBuffer?this.stopPlaybackMeter():(this.playbackAnalyser.getByteTimeDomainData(this.playbackMeterBuffer),this.options.onVolumeLevel?.(_e(this.playbackMeterBuffer),!1),this.playbackMeterFrame=requestAnimationFrame(e))};this.playbackMeterFrame=requestAnimationFrame(e)}async processServerEnvelope(e){if(await this.tryHandleControlEnvelope(e)||e.type!==`events`)return;let t=this.collectInboundTurn(e.events),n=t.toolCalls.filter(e=>!t.cancelledToolIds.has(e.id));for(let e of n)this.toolChain=this.toolChain.then(()=>Ne({executeToolOnRelay:e=>this.executeToolOnRelay(e),pageTools:this.options.pageTools,onGate:this.options.onGate,name:e.name,toolArgs:e.arguments,callId:e.id,operationId:te(e)})).catch(e=>{this.options.onError?.(Y(e))});this.scheduleMediaChunks(t.mediaChunks)}enqueueServerMessage(e){this.inboundChain=this.inboundChain.then(async()=>{if(typeof e!=`string`)return;let t=re(e);t.type===`unsupported`||t.type===`malformed`?this.options.onTurnEvent?.(t):await this.processServerEnvelope(t)}).catch(e=>{this.options.onError?.(Y(e))})}async handleReadyEnvelope(e){this.options.onSessionReady?.({sessionId:e.sessionId,profile:e.profile}),this.options.voiceIngress===!1?this.becomeReady():await this.activateMicrophone()}becomeReady(){this.clearReconnect(),this.setConnectPhase(null),this.setStatus(`listening`),this.flushContext()}handleExecuteToolResultEnvelope(e){let t=this.pendingExecuteResults.get(e.operationId);t&&t.callId===e.callId&&(this.pendingExecuteResults.delete(e.operationId),e.status===`refused`?t.reject(N(e.body,`request`)):e.status===`dispatched`?t.resolve({status:`dispatched`,grantId:e.grantId,arguments:e.arguments}):e.status===`gated`?t.resolve({status:`gated`,gate:e.gate}):t.resolve({status:`settled`}))}async tryHandleControlEnvelope(e){return e.type===`ready`?(await this.handleReadyEnvelope(e),!0):e.type===`executeToolResult`?(this.handleExecuteToolResultEnvelope(e),!0):e.type===`trace`?(this.options.onTrace?.(e.record),!0):e.type===`error`&&(this.startOver()||(this.sessionOver=!0,this.options.onError?.(N(e,`unavailable`)),this.setStatus(`error`)),!0)}collectInboundTurn(e){let t=Ve();for(let n of e)this.processTurnEvent(n,t);return t}processTurnEvent(e,t){switch(e.type===`provider_checkpoint`&&e.history&&(this.history=structuredClone(e.history)),(e.type===`provider_checkpoint`||e.type===`done`)&&e.providerState&&(this.providerState=e.providerState),e.type===`provider_warning`&&(this.providerState=void 0),this.options.onTurnEvent?.(e),e.type){case`evidence`:this.handleEvidenceTurnEvent(e);break;case`session`:this.handleSessionTurnEvent(e);break;case`media`:this.collectMediaTurnEvent(e,t);break;case`tool`:Me(e.tool,t);break;case`done`:this.handleDoneTurnEvent(e)}}handleEvidenceTurnEvent(e){let t=je(e);t&&this.options.onTranscript?.(t.text,t.isUser,{interim:t.interim})}handleSessionTurnEvent(e){if(this.notifySessionLifecycle(e.session))return;this.serverWorking=e.session.kind===`working`;let t=Ke(this.status,this.serverWorking);t&&this.setStatus(t)}notifySessionLifecycle(e){return e.kind===`closing_soon`?(this.options.onSessionClosing?.(e.timeLeftMs),!0):e.kind===`ended`?this.providerState?(this.handleDrop(),!0):(this.sessionOver=!0,this.options.onSessionEnded?.(e),!0):!1}restingStatus(){return this.serverWorking?`working`:`listening`}collectMediaTurnEvent(e,t){e.media.data&&(this.setStatus(`speaking`),t.mediaChunks.push({data:e.media.data,mimeType:e.media.mimeType}))}handleDoneTurnEvent(e){e.interrupted&&this.cancelPlayback(),e.stop.kind!==`generation_complete`&&(this.serverWorking=!1,this.setStatus(`listening`))}scheduleMediaChunks(e){if(e.length===0)return;let t=this.audioEpoch;for(let n of e)this.audioChain=this.audioChain.then(async()=>{t===this.audioEpoch&&await this.enqueueAudioChunk(n.data,n.mimeType)}).catch(e=>{this.options.onError?.(Y(e))})}executeToolOnRelay(e){let t=this.ws;if(!t||t.readyState!==WebSocket.OPEN)throw new M(`request`,`live session is not connected`);let n=ie.safeParse({...e,type:`executeTool`});if(!n.success||n.data.type!==`executeTool`)throw new M(`request`,A(`error.request`));let r=n.data;if(this.pendingExecuteResults.has(r.operationId))throw new M(`request`,A(`session.gate_expired`));return new Promise((e,n)=>{this.pendingExecuteResults.set(r.operationId,{callId:r.callId,resolve:e,reject:n});try{t.send(J(r))}catch(e){this.pendingExecuteResults.delete(r.operationId),n(Y(e))}})}async enqueueAudioChunk(e,t){if(this.audioContext)try{if(this.ensurePlaybackBus(),!this.playbackBus)return;let n=k(e),r;if(t?.includes(`wav`)){let e=n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength);r=await this.audioContext.decodeAudioData(e)}else{let e=Be(n);r=this.audioContext.createBuffer(1,e.length,24e3),r.getChannelData(0).set(e)}let i=this.audioContext.createBufferSource();i.buffer=r,i.connect(this.playbackBus);let a=this.audioContext.currentTime,o=Math.max(a,this.nextPlaybackTime);i.start(o),this.nextPlaybackTime=o+r.duration,this.playbackNodes.push(i),this.startPlaybackMeter(),i.onended=()=>{let e=this.playbackNodes.indexOf(i);e!==-1&&this.playbackNodes.splice(e,1),this.playbackNodes.length===0&&(this.stopPlaybackMeter(),this.status===`speaking`&&this.setStatus(this.restingStatus()))}}catch(e){this.options.onError?.(Y(e))}}cancelPlayback(){this.audioEpoch+=1,this.audioChain=Promise.resolve();for(let e of this.playbackNodes)try{e.stop(),e.disconnect()}catch{}this.playbackNodes=[],this.stopPlaybackMeter(),this.audioContext&&(this.nextPlaybackTime=this.audioContext.currentTime)}toggleMute(){return this.isMuted=!this.isMuted,this.isMuted}sendText(e){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(J({type:`text`,text:e}))}setOptions(e){JSON.stringify(e)!==JSON.stringify(this.options.options)&&(this.options={...this.options,options:e},this.takeUpAgain())}setStated(e){JSON.stringify(e)!==JSON.stringify(this.options.stated)&&(this.options={...this.options,stated:e},this.takeUpAgain())}takeUpAgain(){this.providerState&&!this.opening&&this.ws?.readyState===WebSocket.OPEN&&this.handleDrop()}setContext(e){this.context=e,this.flushContext()}flushContext(){if(this.opening||this.ws?.readyState!==WebSocket.OPEN)return;let e=JSON.stringify(this.context);e!==this.sentContext&&(this.sentContext=e,this.ws.send(J({type:`context`,context:this.context})))}sendVideo(e,t=`image/jpeg`){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(J({type:`video`,data:e,mimeType:t}))}disconnect(){this.clearReconnect(),this.lostAt=void 0,this.providerState=void 0,this.teardownConnection(),this.setStatus(`disconnected`)}cleanupAudio(){if(this.cancelPlayback(),this.stopPlaybackMeter(),X(this.playbackBus),this.playbackBus=null,this.playbackAnalyser=null,this.playbackMeterBuffer=null,this.micWorklet&&=(this.micWorklet.port.onmessage=null,X(this.micWorklet),null),X(this.micSource),this.micSource=null,We(this.micStream),this.micStream=null,this.audioContext&&this.audioContext.state!==`closed`){try{this.audioContext.close()}catch{}this.audioContext=null,this.micWorkletModuleLoaded=!1}}},Z=e(t(),1);function Je(){return{turns:[],interimUser:``,interimAgent:``,working:!1}}function Ye(e,t){return t.length===0?e:[...e,[...t]]}function Xe(e,t){return e?t?t.startsWith(e)||e.startsWith(t)?t.length>=e.length?t:e:Ze(e,t):e:t}function Ze(e,t){return e?t?!e.endsWith(` `)&&!t.startsWith(` `)&&!/^\s/.test(t)&&!/^[\s.,!?;:]/.test(t)?`${e} ${t}`:`${e}${t}`:e:t}function Qe(e){return`${String(Date.now())}-${String(e.turns.length)}`}function $e(e,t,n,r,i){if(!t)return e;if(r)return n?{...e,interimUser:t}:{...e,interimAgent:t};let a=n?`user`:`agent`,o=[...e.turns],s=o.at(-1),c=n?e.interimUser:e.interimAgent;if(!i?.forceNew&&s?.role===a)o[o.length-1]={...s,text:Ze(s.text,t)};else{let n=i?.forceNew?t:Xe(c,t);o.push({id:Qe(e),role:a,text:n})}return{...e,turns:o,interimUser:n?``:e.interimUser,interimAgent:n?e.interimAgent:``}}function et(e){return e.type===`thought`||e.type===`tool`||e.type===`citation`}function tt(e,t){return e.findIndex(e=>e.role===`work`&&e.events.some(e=>e.type===`tool`&&e.tool.callId===t))}function nt(e,t){if(t.type===`tool`&&t.tool.phase!==void 0)return t.tool.phase===`gate`?-1:tt(e,t.tool.callId);let n=e.at(-1)?.role===`work`;return t.type===`thought`&&!(n?t.text:t.text.trim())?-1:n?e.length-1:e.length}function rt(e,t){if(t.type===`done`)return e.working?{...e,working:!1}:e;if(!et(t))return e;let n=nt(e.turns,t);if(n===-1)return e;let r=[...e.turns],i=r[n];return r[n]=i?.role===`work`?{...i,events:[...i.events,t]}:{id:Qe(e),role:`work`,events:[t]},{...e,turns:r,working:!0}}function it(e){return e.role===`work`?ne(e.events,{idPrefix:e.id}):[{id:e.id,kind:e.role===`user`?`user-text`:`text`,text:e.text}]}var at=24;function ot(e,t){let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];)n+=1;return n}function st(e,t){let n=e.trim();return ot(n,t.trim())>=Math.min(n.length,at)}function ct(e){return e.filter((t,n)=>{if(t.role!==`agent`)return!0;let r=e.slice(n+1),i=r.findIndex(e=>e.role===`user`);return!(i===-1?r:r.slice(0,i)).some(e=>e.role===`agent`&&st(t.text,e.text))})}function lt(e,{turns:t,interimUser:n,interimAgent:r}){let i=[...t];n&&i.push({id:`interim-user`,role:`user`,text:n}),r&&i.push({id:`interim-agent`,role:`agent`,text:r});let a=[...e.map((e,t)=>e.map(e=>({...e,id:`${String(t)}:${e.id}`}))),i].map(e=>ct(e).flatMap(it)).filter(e=>e.length>0);return{blocks:a.flat(),callStarts:a.slice(1).map(e=>e[0].id)}}function ut({working:e,interimAgent:t}){return t!==``||e}function dt(e){return!e.interimUser&&!e.interimAgent?e:{...e,interimUser:``,interimAgent:``}}function ft(e,t){let n=Object.keys(t??{}).sort().join(`
|
|
2
|
-
`),r=e?.join(`
|
|
3
|
-
`);(0,Z.useEffect)(()=>{r!==void 0&&ve(r?r.split(`
|
|
4
|
-
`):[],n?n.split(`
|
|
5
|
-
`):[])},[r,n])}var pt=.62,mt=400;function ht(e){return navigator.mediaDevices.getUserMedia({video:{facingMode:{ideal:e},width:{ideal:640},height:{ideal:480}},audio:!1})}function gt(e,t){let n=t?.facingMode??`user`;return ht(n).then(t=>{let r=document.createElement(`video`);r.srcObject=t,r.muted=!0,r.playsInline=!0,r.setAttribute(`playsinline`,``);let i=document.createElement(`canvas`),a=i.getContext(`2d`);if(!a){for(let e of t.getTracks())e.stop();throw new M(`unsupported`,`no 2d canvas for live video`)}let o=null,s=!1,c={stream:t,facing:n},l=()=>{if(s||r.videoWidth===0)return;i.width=r.videoWidth,i.height=r.videoHeight,a.drawImage(r,0,0);let t=i.toDataURL(`image/jpeg`,pt).split(`,`)[1];t&&e(t)};return r.play().then(()=>{o||s||(o=setInterval(l,mt))}),{video:r,facingMode:()=>c.facing,flip:async()=>{if(s)return c.facing;let e=c.facing===`user`?`environment`:`user`,t=await ht(e);for(let e of c.stream.getTracks())e.stop();return c={stream:t,facing:e},r.srcObject=t,await r.play(),e},stop:()=>{s=!0,o&&clearInterval(o),o=null,r.srcObject=null;for(let e of c.stream.getTracks())e.stop()}}})}function _t(e){let t=(0,Z.useCallback)(()=>{e.cancelGateDecision(),e.clearClient(),e.stopVideo(),e.setIsMuted(!1),e.isMutedRef.current=!1,e.setSessionActive(!1),e.setSessionPermissions([]),e.sessionPermissionsRef.current=[],e.statusRef.current=`disconnected`,e.setStatus(`disconnected`),e.setConnectPhase(null),e.setInputLevel(0),e.setOutputLevel(0)},[e]),n=(0,Z.useCallback)(async()=>{e.clearFailure(),e.resetCaptions();try{let t=e.ensureClient(await e.connectionRef.current());(e.statusRef.current===`disconnected`||e.statusRef.current===`error`)&&await t.connect()}catch(t){e.reportFailure(t)}},[e]);return{teardownSession:t,startSession:n,handleSendText:(0,Z.useCallback)(t=>{let n=(typeof t==`string`?t:e.textDraft).trim();n&&e.clientRef.current&&e.sessionActive&&e.textAvailable&&(e.clientRef.current.sendText(n),e.setTextDraft(``),e.setCaptions(e=>$e(e,n,!0,!1,{forceNew:!0})))},[e]),handleToggleVideo:(0,Z.useCallback)(async()=>{if(e.clientRef.current&&e.sessionActive&&e.videoAvailable){if(e.isVideoOn)e.stopVideo();else try{let t=await gt(t=>{e.clientRef.current?.sendVideo(t)});e.videoCaptureRef.current=t,e.setVideoPreview(t.video),e.setVideoFacingMode(t.facingMode()),e.setIsVideoOn(!0)}catch(t){e.reportFailure(t),e.stopVideo()}}},[e]),handleFlipCamera:(0,Z.useCallback)(async()=>{let t=e.videoCaptureRef.current;if(t&&e.sessionActive&&e.isVideoOn)try{let n=await t.flip();e.setVideoFacingMode(n),e.setVideoPreview(t.video)}catch(t){e.reportFailure(t)}},[e]),handleToggleMic:(0,Z.useCallback)(()=>{if(!e.clientRef.current||!e.sessionActive||!e.voiceAvailable)return;let t=e.clientRef.current.toggleMute();e.isMutedRef.current=t,e.setIsMuted(t)},[e]),handleRestart:(0,Z.useCallback)(async()=>{t(),await n()},[n,t])}}function vt(e,t){return t.activity===void 0&&e?.name===t.name?e:t}function yt(e){return new P(e.kind,e.error,e.message)}function Q(e){e.gateCallId===void 0&&e.clearActiveTool()}function bt(e,t){e.phase===`cancel`&&e.callId===t.gateCallId?(t.withdrawGate(),t.clearActiveTool()):e.phase===`cancel`||e.phase===`complete`?Q(t):e.phase===`error`?(t.reportFailure(yt(e.failure)),Q(t)):t.setActiveTool(e.phase===`running`&&e.activity?{name:e.name,activity:e.activity}:{name:e.name})}function xt(e,t){e.type===`done`?(t.clearInterim(),Q(t)):e.type===`tool`&&bt(e.tool,t)}function St(e){let[t,n]=(0,Z.useState)(`disconnected`),[r,i]=(0,Z.useState)(null),a=(0,Z.useRef)({input:0,output:0}),o=(0,Z.useCallback)(e=>{let t=a.current;t.input=typeof e==`function`?e(t.input):e},[]),s=(0,Z.useCallback)(e=>{let t=a.current;t.output=typeof e==`function`?e(t.output):e},[]),[c,l]=(0,Z.useState)(!1),[u,d]=(0,Z.useState)(!1),[f,m]=(0,Z.useState)(null),[h,g]=(0,Z.useState)(Je),[_,v]=(0,Z.useState)(null),[y,b]=(0,Z.useState)(null),[x,S]=(0,Z.useState)(``),[C,w]=(0,Z.useState)(!1),[T,ee]=(0,Z.useState)([]),[E,D]=(0,Z.useState)(!1),[O,k]=(0,Z.useState)(null),[A,j]=(0,Z.useState)(`user`),M=(0,Z.useRef)(null),N=(0,Z.useRef)(h),P=(0,Z.useRef)(c),F=(0,Z.useRef)(T),I=(0,Z.useRef)(t);return N.current=h,P.current=c,F.current=T,I.current=t,(0,Z.useEffect)(()=>{C&&D(!0)},[C]),{status:t,setStatus:n,connectPhase:r,setConnectPhase:i,levelsRef:a,setInputLevel:o,setOutputLevel:s,isMuted:c,setIsMuted:l,isVideoOn:u,setIsVideoOn:d,activeTool:f,setActiveTool:m,captions:h,setCaptions:g,failure:_,reportFailure:(0,Z.useCallback)(t=>{v(p(t,e))},[e]),clearFailure:(0,Z.useCallback)(()=>{v(null)},[]),sessionEnded:y,reportSessionEnded:(0,Z.useCallback)(e=>{b(e.message)},[]),clearSessionEnded:(0,Z.useCallback)(()=>{b(null)},[]),textDraft:x,setTextDraft:S,sessionActive:C,setSessionActive:w,sessionPermissions:T,setSessionPermissions:ee,everConnected:E,videoPreview:O,setVideoPreview:k,videoFacingMode:A,setVideoFacingMode:j,videoCaptureRef:M,captionsRef:N,isMutedRef:P,sessionPermissionsRef:F,statusRef:I,resetCaptions:(0,Z.useCallback)(()=>{g(Je())},[]),stopVideo:(0,Z.useCallback)(()=>{M.current&&=(M.current.stop(),null),k(null),j(`user`),d(!1)},[])}}function Ct(e){let[t,n]=(0,Z.useState)(null),r=(0,Z.useRef)(t);r.current=t;let i=(0,Z.useRef)(null),a=(0,Z.useRef)(null),o=(0,Z.useCallback)(e=>{i.current?.(e),i.current=null,a.current=null,n(null)},[]);return{gatePrompt:t,gatePromptRef:r,handleLiveTurnEvent:(0,Z.useCallback)(t=>{e.setCaptions(e=>rt(e,t)),xt(t,{gateCallId:r.current?.callId,withdrawGate:()=>{o(`withdrawn`)},clearInterim:()=>{e.setCaptions(e=>dt(e))},clearActiveTool:()=>{e.setActiveTool(null)},reportFailure:e.reportFailure,setActiveTool:t=>{e.setActiveTool(e=>vt(e,t))}})},[e,o]),waitForGateDecision:(0,Z.useCallback)(e=>new Promise((t,r)=>{n(e),i.current=t,a.current=r}),[]),resolveGateDecision:(0,Z.useCallback)(e=>{o(e)},[o]),cancelGateDecision:(0,Z.useCallback)(()=>{a.current?.(new M(`cancelled`,`live session ended with a gate open`)),i.current=null,a.current=null,n(null)},[])}}function wt(e,t){t.setStatus(e),e===`listening`||e===`ready`?(t.setSessionActive(!0),t.clearFailure(),t.clearSessionEnded()):(e===`disconnected`||e===`error`)&&(t.setSessionActive(!1),t.videoCaptureRef.current&&(t.videoCaptureRef.current.stop(),t.videoCaptureRef.current=null),t.setVideoPreview(null),t.setVideoFacingMode(`user`),t.setIsVideoOn(!1))}function Tt(e,t,n,r){r.setCaptions(r=>$e(r,e,t,n?.interim))}async function Et(e,t){let n=await t.waitForGateDecision(e);if(n===`withdrawn`)return`withdrawn`;let r=y({toolName:e.toolName,gate:e.gate,sessionPermissions:t.sessionPermissionsRef.current,resolution:n});return r.decision===`approve`&&(t.sessionPermissionsRef.current=r.sessionPermissions,t.setSessionPermissions(r.sessionPermissions)),r}function Dt(e){let t=(0,Z.useRef)(null),n=(0,Z.useRef)(e);return n.current=e,{clientRef:t,ensureClient:(0,Z.useCallback)(e=>{if(t.current)return t.current;let r=n.current,i=new qe({...e,options:r.options,stated:r.stated,model:r.model,effort:r.effort,context:r.context,voiceIngress:r.voiceAvailable,onConnectPhase:e=>{r.setConnectPhase(e)},onStatusChange:e=>{wt(e,n.current)},onTranscript:(e,t,r)=>{Tt(e,t,r,n.current)},onTurnEvent:e=>{e.type!==`unsupported`&&(e.type===`malformed`?n.current.reportFailure(e.error):(e.type===`tool`&&e.tool.phase===void 0&&n.current.clearFailure(),n.current.handleLiveTurnEvent(e)))},onTrace:e=>{n.current.traces.push(e)},onVolumeLevel:(e,t)=>{let r=n.current;t?r.setInputLevel(r.isMutedRef.current?0:e):r.setOutputLevel(e)},onError:e=>{n.current.reportFailure(e)},onSessionEnded:e=>{n.current.reportSessionEnded(e)},get pageTools(){return n.current.pageTools},onGate:e=>Et(e,n.current)});return t.current=i,i},[]),clearClient:(0,Z.useCallback)(()=>{t.current&&=(t.current.disconnect(),null)},[])}}function Ot(e,t,n,r){let[i,a]=(0,Z.useState)(!1),[o,s]=(0,Z.useState)(!1),[c,l]=(0,Z.useState)(null),u=(0,Z.useRef)(!1),d=(0,Z.useCallback)(t=>{u.current=t.video&&r,a(!0),s(!1),e.startSession()},[e,r]);(0,Z.useEffect)(()=>{n&&l(e=>e??Date.now())},[n]),(0,Z.useEffect)(()=>{n&&u.current&&(u.current=!1,e.handleToggleVideo())},[e,n]);let f=(0,Z.useCallback)(()=>{u.current=!1,e.teardownSession(),s(!0),l(null)},[e]),[p,m]=(0,Z.useState)([]),h=(0,Z.useCallback)(async()=>{let n=t.current.turns;m(e=>Ye(e,n)),s(!1),l(null),await e.handleRestart()},[e,t]),g=(0,Z.useRef)(e.teardownSession);return g.current=e.teardownSession,(0,Z.useEffect)(()=>()=>{g.current()},[]),{callStarted:i,connectedAt:c,ended:o,pastCalls:p,startCall:d,handleEnd:f,handleRestart:h}}function kt({iface:e,connection:t,...n}){let r=St(e.labels),i=Ct({setCaptions:r.setCaptions,setActiveTool:r.setActiveTool,reportFailure:r.reportFailure}),a=(0,Z.useRef)(t);a.current=t;let o=L(e.live.ingress,`audio`),s=L(e.live.ingress,`video`),c=L(e.live.ingress,`text`),l=(0,Z.useMemo)(()=>ke({status:r.status,connectPhase:r.connectPhase,toolName:r.activeTool?.name??null,isMuted:r.isMuted,voiceEnabled:o}),[r.activeTool,r.connectPhase,r.isMuted,r.status,o]),u=(0,Z.useMemo)(m,[]),{clientRef:d,ensureClient:f,clearClient:p}=Dt({options:n.options,stated:n.stated,model:n.model,effort:n.effort,context:n.context,pageTools:n.pageTools,voiceAvailable:o,traces:u,handleLiveTurnEvent:i.handleLiveTurnEvent,waitForGateDecision:i.waitForGateDecision,gatePromptRef:i.gatePromptRef,isMutedRef:r.isMutedRef,sessionPermissionsRef:r.sessionPermissionsRef,videoCaptureRef:r.videoCaptureRef,setConnectPhase:r.setConnectPhase,setStatus:r.setStatus,setSessionActive:r.setSessionActive,reportFailure:r.reportFailure,clearFailure:r.clearFailure,reportSessionEnded:r.reportSessionEnded,clearSessionEnded:r.clearSessionEnded,setCaptions:r.setCaptions,setInputLevel:r.setInputLevel,setOutputLevel:r.setOutputLevel,setSessionPermissions:r.setSessionPermissions,setVideoPreview:r.setVideoPreview,setVideoFacingMode:r.setVideoFacingMode,setIsVideoOn:r.setIsVideoOn}),h=_t({clientRef:d,videoCaptureRef:r.videoCaptureRef,connectionRef:a,statusRef:r.statusRef,isMutedRef:r.isMutedRef,sessionPermissionsRef:r.sessionPermissionsRef,ensureClient:f,clearClient:p,cancelGateDecision:i.cancelGateDecision,stopVideo:r.stopVideo,resetCaptions:r.resetCaptions,sessionActive:r.sessionActive,textAvailable:c,videoAvailable:s,voiceAvailable:o,isVideoOn:r.isVideoOn,textDraft:r.textDraft,setTextDraft:r.setTextDraft,setCaptions:r.setCaptions,reportFailure:r.reportFailure,clearFailure:r.clearFailure,setIsMuted:r.setIsMuted,setSessionActive:r.setSessionActive,setSessionPermissions:r.setSessionPermissions,setStatus:r.setStatus,setConnectPhase:r.setConnectPhase,setInputLevel:r.setInputLevel,setOutputLevel:r.setOutputLevel,setVideoPreview:r.setVideoPreview,setVideoFacingMode:r.setVideoFacingMode,setIsVideoOn:r.setIsVideoOn}),{callStarted:g,connectedAt:_,ended:v,pastCalls:y,startCall:b,handleEnd:x,handleRestart:S}=Ot(h,r.captionsRef,r.sessionActive,s),C=JSON.stringify(n.context);(0,Z.useEffect)(()=>{d.current?.setContext(C===void 0?void 0:JSON.parse(C))},[d,C]);let w=JSON.stringify(n.options);(0,Z.useEffect)(()=>{d.current?.setOptions(w===void 0?void 0:JSON.parse(w))},[d,w]);let T=JSON.stringify(n.stated);return(0,Z.useEffect)(()=>{d.current?.setStated(T===void 0?void 0:JSON.parse(T))},[d,T]),ft(e.tools.page,n.pageTools),{iface:e,handle:e.identity.handle,traces:u,callStarted:g,connectedAt:_,pastCalls:y,captions:r.captions,failure:r.failure,sessionEnded:r.sessionEnded,levelsRef:r.levelsRef,isMuted:r.isMuted,isVideoOn:r.isVideoOn,sessionActive:r.sessionActive,liveState:l,activeTool:r.activeTool,status:r.status,textAvailable:c,textDraft:r.textDraft,toolActive:r.activeTool!==null||i.gatePrompt!==null,videoAvailable:s,videoFacingMode:r.videoFacingMode,videoPreview:r.videoPreview,voiceAvailable:o,canRestart:!r.sessionActive&&r.status!==`connecting`&&(r.everConnected||v||r.failure!==null),gatePrompt:i.gatePrompt,setTextDraft:r.setTextDraft,handleEnd:x,startCall:b,handleRestart:S,handleSendText:h.handleSendText,handleToggleMic:h.handleToggleMic,handleFlipCamera:h.handleFlipCamera,handleToggleVideo:h.handleToggleVideo,resolveGateDecision:i.resolveGateDecision}}var $=n();function At(e){return(0,$.jsx)(ce,{children:(0,$.jsx)(jt,{...e})})}function jt({handle:e,captions:t,pastCalls:n,draftText:r,onDraftTextChange:i,onSubmit:s,isDisabled:c,showComposer:l=!0,leading:u}){let d=R(),f=d(`@theorem.agent.handle`,{handle:e}),{blocks:p,callStarts:m}=lt(n,t),h=d(`@theorem.live.new_session`),g=Object.fromEntries(m.map(e=>[e,h])),_=l?(0,$.jsx)(fe,{handle:e,draftText:r,onDraftTextChange:i,onSubmit:s,isDisabled:c}):null;return(0,$.jsxs)(V,{height:`100%`,children:[u,(0,$.jsx)(H,{size:`fill`,children:p.length>0?(0,$.jsx)(o,{label:d(`@theorem.panel.captions.name`),children:(0,$.jsx)(w,{blocks:p,dividers:g,handle:f,streaming:ut(t)})}):(0,$.jsx)(V,{height:`100%`,vAlign:`center`,padding:4,children:(0,$.jsx)(ae,{icon:(0,$.jsx)(a,{icon:Ee,size:`lg`,color:`secondary`}),title:d(`@theorem.panel.captions.empty.title`),description:d(`@theorem.panel.captions.empty.description`),isCompact:!0})})}),_]})}var Mt=class{readyState=0;binaryType=`arraybuffer`;onopen=null;onmessage=null;onclose=null;onerror=null;outbound=new EventTarget;closeSession;queued=[];listening=!1;constructor(e,t,n){queueMicrotask(()=>{this.open(e,t,n)})}send(e){if(this.readyState!==1)throw new M(`network`,`Live connection is closed`);this.listening?this.outbound.dispatchEvent(new MessageEvent(`message`,{data:e})):this.queued.push(e)}close(){this.readyState!==3&&(this.readyState=3,this.queued=[],this.outbound.dispatchEvent(new Event(`close`)),this.closeSession?.(),this.emit(`onclose`,new CloseEvent(`close`)))}emit(e,t){let n=this[e];n?.(t)}async open(e,t,n){if(this.readyState===3)return;this.readyState=1,this.emit(`onopen`,new Event(`open`));let r;try{let i=await g(),a=n?.(i);r=i.studioTraces.route(e=>this.receive({type:`trace`,record:e}));let{scope:o,profile:s}=await i.studioScope(e.profile,e.customTools,e.structured,t);if(!t.providers?.vault)throw new M(`auth`,`Fill the vault slot this model names.`);let[c]=this.queued.splice(0,1);if(typeof c!=`string`)throw new M(`request`,`A live call must open with its open message`);let l=await o.runSession({...await(a?(await a.boundary).prepareLiveOpen(i.parseLiveOpenMessage(c)):Promise.resolve(i.liveSessionOpen(i.parseLiveOpenMessage(c)))),profile:s.id,metadata:r.metadata,signal:t.signal,execution:t.execution??a?.execution,pageExecution:t.pageExecution??a?.pageExecution,background:t.background??a?.background},{vault:t.providers.vault,fetch:t.providers.fetch,wait:t.providers.wait,openWebSocket:t.providers.openWebSocket});if(this.closeSession=()=>l.close(`client disconnected`),this.readyState!==1){await this.closeSession(),r.close();return}await this.attach(i.attachStudioLiveSession,l,s.id,r,s.labels,a?{pageResult:a.pageResult,beforeEvent:async e=>{(e.type===`done`||e.type===`provider_checkpoint`)&&e.providerState&&await(await a.boundary).recordCheckpoint(e.providerState)}}:{})}catch(t){r?.close(),this.receive({type:`error`,...F(t,e.profile.labels,I)}),this.close()}}async attach(e,t,n,r,i,a={}){let o=e({send:e=>{typeof e==`string`&&this.receive(JSON.parse(e))},close:()=>this.close(),addEventListener:this.outbound.addEventListener.bind(this.outbound)},t,n,crypto.randomUUID(),r,i,{...a,clientEvents:I});this.closeSession=void 0,this.listening=!0;for(let e of this.queued.splice(0))this.outbound.dispatchEvent(new MessageEvent(`message`,{data:e}));await o}receive(e){this.readyState===1&&this.emit(`onmessage`,new MessageEvent(`message`,{data:JSON.stringify(e)}))}};function Nt(e,t){let n,r=t.execution?void 0:e=>n??=e.browserExecution();return{createSocket:()=>new Mt(e,t,r)}}var Pt={borderRadius:`var(--radius-chat, var(--radius-container))`};function Ft({call:e}){let t=R(),n=e.gatePrompt,r=e.resolveGateDecision,i=t(`@theorem.agent.handle`,{handle:e.handle});return(0,$.jsx)(ue,{isOpen:n!==null,purpose:`required`,width:400,padding:0,style:Pt,onOpenChange:e=>{e||r({action:`deny`})},children:n?n.gate.kind===`auth`?(0,$.jsx)(T,{gate:n.gate,toolName:n.gate.tool,onAuthenticated:e=>{r({action:`auth`,secret:e})}}):(0,$.jsx)(C,{gate:n.gate,toolName:n.gate.tool,agent:i,input:n.input,onDecision:e=>{r({action:e})}}):null})}function It({video:e,facingMode:t}){let n=R(),r=(0,Z.useRef)(null);return(0,Z.useEffect)(()=>{let t=r.current;if(t)return Object.assign(e.style,{width:`100%`,height:`100%`,objectFit:`cover`,display:`block`}),t.replaceChildren(e),()=>{e.parentElement===t&&t.removeChild(e)}},[e]),(0,Z.useEffect)(()=>{e.style.transform=t===`user`?`scaleX(-1)`:``},[e,t]),(0,$.jsx)(E,{ratio:4/3,fit:`cover`,children:(0,$.jsx)(`div`,{ref:r,"aria-label":n(`@theorem.live.camera_preview`),role:`img`})})}var Lt=720,Rt=320;function zt({theme:e,mode:t,labels:n,media:r,resolveMedia:i,...a}){return(0,$.jsx)(de,{theme:e,mode:t,labels:n,detectCodeLanguage:void 0,media:r,resolveMedia:i,children:(0,$.jsx)(Bt,{...a})})}function Bt({call:e,trace:t,onMinimize:n}){let o=R(),d=(0,Z.useRef)(null),f=pe(e.iface,e.traces,t),p=l(d,!0),m={name:o(`@theorem.panel.captions.name`),show:o(`@theorem.panel.captions.show`),hide:o(`@theorem.panel.captions.hide`),resize:o(`@theorem.panel.captions.resize`)},h=(0,$.jsx)(u,{labels:m,icon:(0,$.jsx)(a,{icon:me}),panelId:p.id,open:p.open,onToggle:p.toggle});return e.callStarted?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(G,{inspector:f,children:(0,$.jsx)(r,{ref:d,height:`fill`,header:(0,$.jsx)(c,{children:f.toggle}),content:(0,$.jsx)(i,{padding:0,children:(0,$.jsx)(r,{height:`fill`,end:(0,$.jsx)(s,{id:p.id,labels:m,resizable:p.resizable,open:p.open,children:(0,$.jsx)(qt,{call:e})}),content:(0,$.jsx)(i,{padding:0,children:(0,$.jsx)(V,{height:`100%`,padding:3,children:(0,$.jsx)(Ht,{call:e,captionsToggle:h,onMinimize:n})})})})})})}),(0,$.jsx)(Ft,{call:e})]}):(0,$.jsx)(G,{inspector:f,children:(0,$.jsx)(r,{ref:d,height:`fill`,header:(0,$.jsx)(c,{children:f.toggle}),content:(0,$.jsx)(i,{padding:0,children:(0,$.jsx)(Vt,{call:e})})})})}function Vt({call:e}){let t=R();return(0,$.jsx)(V,{minHeight:`100%`,vAlign:`center`,gap:8,paddingInline:3,children:(0,$.jsx)(v,{axis:`horizontal`,width:`100%`,children:(0,$.jsxs)(V,{width:`100%`,maxWidth:he,gap:8,children:[(0,$.jsxs)(V,{gap:1,children:[(0,$.jsx)(d,{type:`large`,as:`h2`,children:t(`@theorem.agent.handle`,{handle:e.handle})}),(0,$.jsx)(d,{type:`display-2`,as:`h1`,children:t(`@theorem.live.greeting`)})]}),(0,$.jsxs)(z,{gap:2,wrap:`wrap`,children:[(0,$.jsx)(f,{label:t(e.voiceAvailable?`@theorem.live.start_voice_call`:`@theorem.live.start_call`),variant:`primary`,icon:(0,$.jsx)(a,{icon:K}),onClick:()=>e.startCall({video:!1})}),e.videoAvailable?(0,$.jsx)(f,{label:t(`@theorem.live.start_video_call`),variant:`secondary`,icon:(0,$.jsx)(a,{icon:Oe}),onClick:()=>e.startCall({video:!0})}):null]})]})})})}function Ht({call:e,captionsToggle:t,onMinimize:n}){let r=R(),i=Ut();return(0,$.jsx)(V,{ref:i,height:`100%`,hAlign:`center`,children:(0,$.jsxs)(V,{width:`100%`,maxWidth:Lt,height:`100%`,gap:3,children:[(0,$.jsxs)(V,{gap:.5,children:[(0,$.jsx)(d,{type:`label`,color:`secondary`,children:r(`@theorem.agent.handle`,{handle:e.handle})}),(0,$.jsx)(d,{size:`sm`,color:`secondary`,children:se(r,e.liveState,e.activeTool)})]}),e.failure?(0,$.jsx)(W,{status:`error`,role:`alert`,title:e.failure.error}):null,e.sessionEnded?(0,$.jsx)(W,{status:`info`,role:`status`,title:e.sessionEnded}):null,(0,$.jsx)(H,{size:`fill`,children:(0,$.jsx)(V,{height:`100%`,vAlign:`end`,children:(0,$.jsx)(V,{width:`100%`,height:Rt,style:{color:`var(--color-icon-primary)`},"aria-hidden":`true`,children:(0,$.jsx)(oe,{status:e.status,levelsRef:e.levelsRef,toolActive:e.toolActive,variant:`hero`})})})}),(0,$.jsx)(Wt,{call:e,captionsToggle:t,onMinimize:n})]})})}function Ut(){let e=(0,Z.useRef)(null);return(0,Z.useLayoutEffect)(()=>{let t=e.current;if(!t||globalThis.matchMedia?.(`(prefers-reduced-motion: reduce)`).matches)return;let n=getComputedStyle(t),r=Number.parseFloat(n.getPropertyValue(`--duration-medium`))||410;t.animate([{opacity:0,transform:`translateY(8px)`},{opacity:1,transform:`none`}],{duration:r,easing:n.getPropertyValue(`--ease-standard`).trim()||`ease-out`})},[]),e}function Wt({call:e,captionsToggle:t,onMinimize:n}){let r=R(),i=!e.sessionActive,o=[];return e.voiceAvailable&&o.push((0,$.jsx)(U,{label:r(`@theorem.live.microphone`),tooltip:r(e.isMuted?`@theorem.live.unmute`:`@theorem.live.mute`),isIconOnly:!0,isPressed:!e.isMuted,isDisabled:i,icon:(0,$.jsx)(a,{icon:D}),pressedIcon:(0,$.jsx)(a,{icon:we}),onPressedChange:e.handleToggleMic},`mic`)),e.videoAvailable&&o.push((0,$.jsx)(Gt,{call:e},`video`)),n&&o.push((0,$.jsx)(B,{label:r(`@theorem.live.minimize`),tooltip:r(`@theorem.live.minimize`),variant:`ghost`,icon:(0,$.jsx)(a,{icon:Se}),onClick:n},`minimize`)),o.push((0,$.jsx)(Z.Fragment,{children:t},`captions`),(0,$.jsx)(Kt,{call:e},`call`)),(0,$.jsx)(le,{label:r(`@theorem.live.controls`),dividers:[`top`],centerContent:(0,$.jsx)(z,{gap:2,vAlign:`center`,children:o})})}function Gt({call:e}){let t=R(),n=!e.sessionActive;return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(U,{label:t(`@theorem.live.camera`),tooltip:t(e.isVideoOn?`@theorem.live.camera_off`:`@theorem.live.camera_on`),isIconOnly:!0,isPressed:e.isVideoOn,isDisabled:n,icon:(0,$.jsx)(a,{icon:Oe}),pressedIcon:(0,$.jsx)(a,{icon:De}),onPressedChange:()=>{e.handleToggleVideo()}}),e.isVideoOn?(0,$.jsx)(B,{label:t(`@theorem.live.flip_camera`),tooltip:t(`@theorem.live.flip_camera`),variant:`ghost`,isDisabled:n,icon:(0,$.jsx)(a,{icon:Ce}),onClick:()=>{e.handleFlipCamera()}}):null]})}function Kt({call:e}){let t=R();return e.canRestart?(0,$.jsx)(B,{label:t(`@theorem.live.start_call`),tooltip:t(`@theorem.live.start_call`),variant:`primary`,icon:(0,$.jsx)(a,{icon:K}),onClick:()=>{e.handleRestart()}}):(0,$.jsx)(B,{label:t(`@theorem.live.end_call`),tooltip:t(`@theorem.live.end_call`),variant:`destructive`,isDisabled:!e.sessionActive,icon:(0,$.jsx)(a,{icon:Te}),onClick:e.handleEnd})}function qt({call:e}){return(0,$.jsx)(At,{handle:e.handle,captions:e.captions,pastCalls:e.pastCalls,draftText:e.textDraft,onDraftTextChange:e.setTextDraft,onSubmit:e.handleSendText,isDisabled:!e.sessionActive,showComposer:e.textAvailable,leading:e.videoPreview?(0,$.jsx)(It,{video:e.videoPreview,facingMode:e.videoFacingMode}):null})}function Jt({runtime:e,...t}){let{payload:n}=t;return(0,$.jsx)(Xt,{...t,connect:()=>e?Nt(n,e):x(n)})}function Yt({endpoint:e,...t}){let{actingAs:n}=ye();return(0,$.jsx)(Xt,{...t,connect:()=>({createSocket:()=>new WebSocket(ge(e,n))})})}function Xt({payload:e,note:t,connect:n,trace:r,options:i,stated:a,context:o}){let s=(0,Z.useMemo)(()=>h(e),[e]),c=(0,Z.useMemo)(()=>b(e),[e]);return s.type===`live`?(0,$.jsx)(Zt,{iface:s,connection:()=>(t(),n()),trace:r,options:i,stated:a,context:o,pageTools:c}):null}function Zt({trace:e,...t}){let n=kt(t);return(0,$.jsx)(zt,{labels:S,call:n,trace:e,media:`all`,resolveMedia:ee})}export{Yt as ProjectLive,Jt as StudioLive};
|
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
import{C as e,M as t,h as n,j as r,n as i,p as a,t as o,y as s,z as c}from"./tool-schema-CnrGGkcr.js";import{Bi as l,En as u,Fi as d,Ft as f,Ga as p,Ht as ee,Oi as te,Qi as ne,Ui as re,Va as ie,Wi as ae,fa as oe,na as se,ta as m,ua as h,xn as g}from"./shaped-data-BxDmEUJe.js";import{a as _,r as v}from"./live-ingress-OuSlQ6q7.js";var ce=[{id:`identity`,profilePath:`identity`,role:`root`,optional:!1,editor:`structural`,label:`Identity`,ownsFields:[`profile.id`,`profile.type`]},{id:`models`,profilePath:`models`,role:`spine`,optional:!1,editor:`structural`,label:`Models`,ownsFields:[`profile.defaultModel`,`profile.allowModelSelect`,`profile.maxSteps`,`providerContinuation`]},{id:`modelBinding`,profilePath:`models.*`,role:`branch`,parent:`models`,optional:!1,editor:`structural`,label:`Model binding`},{id:`decision`,profilePath:`decision`,role:`spine`,optional:!1,editor:`structural`,label:`Decision`,ownsFields:[`inputs`]},{id:`image`,profilePath:`image`,role:`spine`,optional:!1,editor:`structural`,label:`Image`},{id:`speech`,profilePath:`speech`,role:`spine`,optional:!1,editor:`structural`,label:`Speech`},{id:`live`,profilePath:`live`,role:`spine`,optional:!1,editor:`structural`,label:`Live`},{id:`tools`,profilePath:`tools`,role:`spine`,optional:!1,editor:`structural`,label:`Tools`},{id:`toolSpec`,profilePath:`tools.allow`,role:`branch`,parent:`tools`,optional:!0,editor:`structural`,label:`Tool`},{id:`inputs`,profilePath:`inputs`,role:`spine`,optional:!1,editor:`structural`,label:`Inputs`},{id:`outputs`,profilePath:`outputs`,role:`spine`,optional:!0,editor:`structural`,label:`Outputs`},{id:`turnBehaviour`,profilePath:`turnBehaviour`,role:`spine`,optional:!0,editor:`structural`,label:`Turn behaviour`},{id:`guardrails`,profilePath:`guardrails`,role:`spine`,optional:!0,editor:`structural`,label:`Guardrails`},{id:`observability`,profilePath:`observability`,role:`spine`,optional:!0,editor:`structural`,label:`Observability`},{id:`labels`,profilePath:`labels`,role:`spine`,optional:!0,editor:`structural`,label:`Labels`}],le={identity:ne,inputs:m(`inputs`).filter(e=>e!==`decision`)},y=ce.map(e=>({...e,profileTypes:le[e.id]??m(e.profilePath)}));function ue(e){return y.find(t=>t.id===e)}function de(e){return e.modelBindings.length>1}function fe(e){return e.modelBindings.some(n=>n.provider!==`local`&&!t(e.providers,n).keySlot)}function b(e,n){let r={provider:n.provider,keySlot:n.keySlot||e.models.key,fallbackKeySlot:n.fallbackKeySlot||e.models.fallbackKey},i=t(e.providers,r);return{...i,given:{keySlot:!!i.keySlot&&!r.keySlot,fallbackKeySlot:!!i.fallbackKeySlot&&!r.fallbackKeySlot}}}function pe(e,t){let n=new Set(e.modelBindings.filter(n=>{let r=b(e,n);return r.keySlot===t||r.fallbackKeySlot===t}).map(e=>e.provider));return e.providers.filter(e=>n.has(e.id))}function me(e){let t=e.efforts.map(({alias:e})=>e.trim()).filter(Boolean);return new Set(t).size>1}function he(e){return e.attachmentsAccept.length>0||e.voiceAccept.length>0}var x=d,S=[{name:`operationTimeoutMs`,label:`Call timeout`,units:`ms`,isTimer:!0},{name:`connectTimeoutMs`,label:`Connect timeout`,units:`ms`,isTimer:!0},{name:`liveStepTimeoutMs`,label:`Live step timeout`,units:`ms`,isTimer:!0},{name:`maxWireRecordBytes`,label:`Wire record`,units:`bytes`,isTimer:!1},{name:`maxWireResponseBytes`,label:`Wire response`,units:`bytes`,isTimer:!1},{name:`maxEventBytes`,label:`Event`,units:`bytes`,isTimer:!1},{name:`maxStepBytes`,label:`Step`,units:`bytes`,isTimer:!1},{name:`maxStepEvents`,label:`Step events`,units:`events`,isTimer:!1},{name:`maxPendingToolCalls`,label:`Tool calls`,units:`calls`,isTimer:!1}],C=2147483647,w={compactMaxTokens:32e3,compactAt:.75,compactKeep:4},T={"continue.instruction":`turnBehaviour`,"canary.bind_note":`guardrails`,"quota.exhausted":`guardrails`,"repair.default_guidance":`outputs`,"egress.default_repair_guidance":`guardrails`,"egress.refusal":`guardrails`};function E(e){return`${e}-${crypto.randomUUID().slice(0,8)}`}function D(e){return{key:E(`model`),modelId:`fast`,protocol:`openRouterOpenAi`,provider:`openrouter`,apiId:``,options:{},timeoutMs:null,efforts:[],defaultEffort:``,allowEffortSelect:!1,summaries:null,maxOutputTokens:null,temperature:null,builtInTools:[],...e}}var O=`Studio stub tool — returns a fixed result.`;function k(e){return{key:E(`tool`),toolName:`my_tool`,toolType:`function`,description:O,category:`studio`,access:l[0],permission:ae[0],loadTier:re[0],paths:[`*`],inputJson:o,outputJson:i,...e}}function A(e,t,n){return(!e.description.trim()||e.description===O)&&n?{agentKey:t,description:`Asks ${n} and returns its answer.`}:{agentKey:t}}function j(){return{name:``,kind:`words`,pattern:``,flags:``,words:[]}}function M(){return{key:``,label:``,at:p(ie,()=>`ignore`),patterns:[j()],hint:``}}function N(){let e=u(void 0);return{canaryBindNote:``,detect:p(se,t=>({...e.detect[t]})),sources:Object.fromEntries(h.map(e=>[e,{theorem:!0,patterns:[],hint:``}])),own:[],quotaEnabled:!1,quotaPerDay:null,quotaMessage:``,allow:{ungiven_images:{hosts:[],fromTools:!0},ungiven_links:{hosts:[],fromTools:!0}},innocentNames:[],blockedReplyOnBlock:``,blockedReplyMaxRetries:null,egressRepairGuidance:``,egressRefusal:``,allowPrivateNetworks:!1,allowedHosts:[],allowedSchemes:[],taintAfterRemoteRead:``,taintRemoteDestination:``}}function P(){let e=_({});return{writeTo:a,destination:a,sampleRate:e.sampleRate,include:{...e.include},scrub:{sensitive:e.scrub.sensitive,injection:e.scrub.injection,canary:e.scrub.canary},retainForDays:null,rotateAfterMiB:null,resourceJson:``}}function F(e){return e.map(([e,t])=>({key:E(`criterion`),label:e,text:t}))}function I(){return{contract:`guardrails.tool_call.v1`,maxStateBytes:null,questions:[{key:E(`question`),id:`verdict`,type:`choice`,instructions:`Given what the user asked for and what the call would do, should it run?`,criteria:F([[`allow`,`Safe, and what the user asked for.`],[`flag`,`Probably fine, but unusual or sensitive enough for a person to look first.`],[`block`,`Harmful, or clearly beyond what the user asked for.`]])},{key:E(`question`),id:`risk`,type:`score`,instructions:`How much harm would this call do if it were wrong?`,criteria:F([[``,`Low: reversible, and affects only the user.`],[``,`High: hard to undo, or affects other people or money.`]])}],images:[]}}var L=JSON.stringify({context:`The user asked the agent to tidy up old screenshots on their desktop.`,tool_call:{name:`delete_files`,path:`~/Documents`,recursive:!0},outcome:`Would delete 1,284 files, including tax_return_2025.pdf.`},null,2),R=JSON.stringify(`The user asked to tidy screenshots. The proposed call recursively deletes 1,284 files, including a tax return.`),ge=`To clear your desktop, select the screenshots and move them to the Trash. Empty the Trash to delete them for good.(Screen captures save to the desktop by default. You can change where they go in the Screenshot app's Options menu.(Press Command-Shift-5 to record the screen or capture a window. Recordings are saved as movie files next to your screenshots.(Stacks group desktop files by kind, date or tag, so a cluttered desktop folds into a few piles you can open one at a time.(Deleted files stay in the Trash for 30 days. Drag a file out of the Trash to put it back where it was.(When your disk is almost full, open Storage settings and review the largest files. Old downloads and installers are safe to remove.(Offloading unused apps frees space and keeps their documents. Reinstalling an app brings its data back.(Photos you have backed up can be optimised so the originals live in the cloud and smaller copies stay on the device.(Your plan renews on the same date each month. You can see the next charge under Billing, then Upcoming invoices.(To get a refund, open the invoice and choose Request refund. Charges from the last 14 days are refunded in full.(Update your card under Billing, then Payment methods. The new card is used for the next renewal, not for past invoices.(Annual plans cost two months less than paying monthly. Switching mid-term credits the unused months to the new plan.(Invoices are emailed as PDFs and list your company name and tax number. Edit those details before the invoice is issued.(Turn on two-step verification under Security. You will be asked for a code from your authenticator app each time you sign in on a new device.(If you forget your password, choose Forgot password on the sign-in page. The reset link expires after one hour.(Review signed-in devices under Security and sign out any you don't recognise. This ends their sessions immediately.(Passkeys replace your password with your fingerprint or face. Create one under Security, then Passkeys.(To close your account, export your data first. Closing deletes your workspace after a 30-day grace period.(Share a folder by choosing Share, then entering an email address. Viewers can read; editors can change and delete.(Public links work for anyone who has them. Set an expiry date, or turn the link off to stop sharing at once.(Transfer ownership of a folder before you leave a team, or its contents will be archived with your account.(Lisbon has mild, wet winters and warm, dry summers. Expect highs near 28 °C in August.(The best months for the Algarve coast are May, June and September, when the beaches are warm and the crowds are thin.(Trams in Lisbon climb the steep hills of Alfama and Graça. Line 28 is the famous one, and the busiest.(For a crisp pizza base, preheat the oven and the baking tray together at the highest setting for at least thirty minutes.(Rest steak for five minutes after cooking so the juices settle back into the meat instead of running onto the board.`.split(`(`).join(`
|
|
2
|
-
|
|
3
|
-
`),_e=`How do I delete every screenshot on my desktop?`;function ve(e,t=`choice`){let n=q(`question`,e.decision.questions.map(e=>e.id),e=>`question_${e}`);return{key:E(`question`),id:n,type:t,instructions:``,criteria:B(t)}}function ye(e,t,n){let r=t.replace(/\.[^.]*$/,``).toLowerCase().replace(/[^a-z0-9]+/g,`_`).replace(/^_|_$/g,``)||`image`,i=q(r,e.decision.images.map(e=>e.name),e=>`${r}_${e}`);return{key:E(`image`),name:i,...n}}function be(){return{key:E(`option`),name:``,label:``,isShownInChat:!1,choices:[]}}function xe(e,t){return e.map(e=>t.find(t=>t.value===e)??{key:E(`choice`),value:e,description:``})}function z(){return{key:E(`criterion`),label:``,text:``}}function B(e){return e===`noul`||e===`box`?[]:F(e===`choice`?[[`yes`,``],[`no`,``]]:[[``,``],[``,``]])}function Se(){return{identity:{agentId:``,profileType:``,handle:``,system:``,options:[]},included:[`observability`,`labels`],models:{defaultModel:``,allowModelSelect:!1,maxSteps:null,key:``},modelBindings:[],providers:[...e],tools:{t2Loader:``,parallel:!1},toolSpecs:[],inputs:{text:!0,attachmentsAccept:[],voiceAccept:[],maxFiles:null,maxBytes:null,maxTurnBytes:null,limitsByMime:{},contextFrom:[],contextMaxChars:null},outputs:{mode:`text`,schemaId:``,schemaJson:``,streamMode:``,streamThoughts:!0,validationEnabled:!1,maxRetries:null,itemRules:{},repairGuidance:``},turnBehaviour:{resumeEnabled:!1,allowContinue:[],autoContinue:[],maxContinues:null,continueInstruction:``,allowSteering:ee({type:`text`}),atStepLimit:`stop`},guardrails:N(),observability:P(),image:{aspectRatio:``,resolution:``,mimeType:``,quality:``,background:``,n:null,seed:null,outputCompression:null,includeText:!1,references:[]},speech:{voice:``,style:``,speed:null,format:``},live:{ingressAudio:v(`audio`),ingressVideo:v(`video`),ingressText:v(`text`),voice:``,sessionResumption:!1,greeting:``,resumedPrompt:``,resumedAfterMs:null,contextCompression:!1,compressionTriggerTokens:null,compressionTargetTokens:null,transcriptionInput:!1,transcriptionOutput:!1,vadActivityHandling:``,vadStartSensitivity:``,vadEndSensitivity:``,vadPrefixPaddingMs:null,vadSilenceDurationMs:null},decision:I(),labels:{}}}var Ce=new Set([`guardrails`]);function V(e,t){return e.profileTypes.includes(t)&&!(t===`decision`&&Ce.has(e.id))}function H(e){let t=e.identity.profileType;if(!t)return[`identity`];let n=new Set(e.included);return y.filter(e=>e.role!==`branch`&&V(e,t)&&(!e.optional||n.has(e.id))).map(e=>e.id)}function U(e,t){let n=e.identity.profileType;return n!==``&&m(t).includes(n)}function we(e,t,n){if((!n||n.includes(t.key))&&t.loadTier===`T2`&&U(e,`tools.t2Loader`)&&!e.tools.t2Loader.trim())return`No T2 loader is set under Tools, so this tool never loads.`}function Te(e){return U(e,`identity.system`)&&oe(e.guardrails.detect,`canary_leak`)}function Ee(e){let t=e.identity.profileType;return t!==``&&f.includes(t)}function W(e){let t=e.identity.profileType;return t?y.filter(n=>n.role===`spine`&&n.optional&&V(n,t)&&!e.included.includes(n.id)).map(e=>e.id):[]}function De(e){return{...e,attachmentsAccept:e.attachmentsAccept.filter(e=>g(te,e)),voiceAccept:[]}}function Oe(e){return{...e,text:!1,attachmentsAccept:[],voiceAccept:e.voiceAccept.length?e.voiceAccept:[`audio/*`]}}function ke(e,t,n){let r=e.modelBindings.find(e=>e.key===t);return r?{...e,models:n.modelId!==void 0&&e.models.defaultModel===r.modelId?{...e.models,defaultModel:n.modelId}:e.models,modelBindings:e.modelBindings.map(e=>e.key===t?{...e,...n}:e)}:e}function G(e,t){if(t.some(t=>t.modelId===e))return e;let[n,...r]=t;return n&&!r.length?n.modelId:``}function Ae(e,t){if(!e.modelBindings.find(e=>e.key===t))return e;let n=e.modelBindings.filter(e=>e.key!==t);return{...e,models:{...e.models,defaultModel:G(e.models.defaultModel,n)},modelBindings:n}}function K(e,t){let n=e.identity.profileType,r=n&&n!==`host`?n:`text`,i=e.modelBindings.map(e=>e.modelId),a=s(r,t),o=q(a.modelId,i,e=>`${a.modelId}${e}`);return D({...a,modelId:o})}function je(e){return k({toolName:q(`my_tool`,e.toolSpecs.map(e=>e.toolName),e=>`my_tool_${e}`)})}function q(e,t,n){let r=new Set(t),i=e;for(let e=2;r.has(i);e++)i=n(e);return i}function Me(e,t,i){if(t===`host`)return{...e,identity:{...e.identity,profileType:t}};let a=e.modelBindings.filter(n=>{let a=r(e.providers,t,n),o=e.providers.find(e=>e.id===n.provider);return c(o,t,n.protocol)&&!Fe(i,t,a)}),o={...e,identity:{...e.identity,profileType:t},modelBindings:a},s=a.length?a:[K(o,i?.start)],l=!e.models.key&&fe({...o,modelBindings:s}),u=t===`speech`&&!e.speech.voice.trim()&&s.some(i=>n(r(e.providers,t,i)));return{...o,inputs:t===`image`?De(e.inputs):t===`transcription`?Oe(e.inputs):e.inputs,...u?{speech:{...e.speech,voice:Ne}}:{},models:{...e.models,defaultModel:G(e.models.defaultModel,s),key:l?Ie:e.models.key},modelBindings:s}}var Ne=`Kore`,Pe=[`text`,`image`,`speech`,`transcription`,`live`,`decision`];function Fe(e,t,n){if(!e)return!1;let r=t=>e.models(t,n.definition).some(e=>e.id===n.apiId.trim());return!r(t)&&Pe.some(e=>e!==t&&r(e))}var Ie=`slot_a`;function Le(e,t){return W(e).includes(t)?{...e,included:[...e.included,t]}:e}function Re(e,t){return{...e,included:e.included.filter(e=>e!==t)}}function J(e){return`modelBinding:${e}`}var Y=`toolSpec:`;function X(e){return`${Y}${e}`}function Z(e){return e.startsWith(Y)?e.slice(9):void 0}var Q=`provider:`;function ze(e){return`${Q}${e}`}function Be(e){return e.startsWith(Q)?e.slice(9):void 0}var Ve=new Map(y.map(e=>[e.id,e.label]));function He(e){return Ve.get(e)??e}function Ue(e,t){let[n,r]=t.split(`:`,2);if(n===`modelBinding`&&r!==void 0)return e.modelBindings.some(e=>e.key===r)?{facet:n,key:r}:void 0;let i=Z(t);if(i!==void 0)return e.toolSpecs.some(e=>e.key===i)?{facet:`toolSpec`,key:i}:void 0;let a=H(e);if(r===void 0&&a.includes(t))return{facet:t}}function We(e,t){return t===`models`?e.modelBindings.map(e=>({id:J(e.key),ref:{facet:`modelBinding`,key:e.key},label:e.modelId.trim()||`Unnamed model`,children:[]})):t===`tools`?$(e.toolSpecs):[]}function $(e){return e.map(e=>({id:X(e.key),ref:{facet:`toolSpec`,key:e.key},label:e.toolName.trim()||`Unnamed tool`,children:[]}))}function Ge(e){let t=H(e).filter(e=>e!==`identity`).map(t=>({id:t,ref:{facet:t},label:He(t),children:We(e,t)}));return{id:`identity`,ref:{facet:`identity`},label:e.identity.agentId.trim()||`Unnamed agent`,children:t}}export{B as A,Te as B,H as C,W as D,q as E,be as F,b as G,Me as H,M as I,he as J,me as K,j as L,ye as M,ve as N,Le as O,K as P,je as R,U as S,Re as T,Ee as U,Ae as V,ke as W,y as X,pe as Y,ue as Z,C as _,Ge as a,D as b,$ as c,_e as d,ge as f,x as g,S as h,Ue as i,z as j,we as k,w as l,T as m,Be as n,Z as o,R as p,de as q,ze as r,X as s,J as t,L as u,A as v,E as w,k as x,Se as y,xe as z};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{Gi as e}from"./shaped-data-BxDmEUJe.js";var t=e.filter(e=>e!==`builtin`),n=`Tool type must be ${t.join(`, `).replace(/, ([^,]+)$/,`, or $1`)}.`;export{n,t};
|