@theoremjs/studio 0.3.4-next.757.gde44a4d → 0.3.4-next.759.g46e0e27
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/compile.d.ts +3 -3
- package/compile.js +70 -101
- package/cookbooks/catalog.js +14 -28
- package/draft.d.ts +24 -28
- package/draft.js +11 -12
- package/guardrail-probe.js +1 -30
- package/mod.d.ts +2 -2
- package/mod.js +2 -2
- package/package.json +4 -4
- package/page/assets/{ConsoleFrame-D309UtSL.js → ConsoleFrame-IP80BbVy.js} +1 -1
- package/page/assets/{MenuBottomSheet-CVBLnUiO.js → MenuBottomSheet-B90IZU5_.js} +1 -1
- package/page/assets/{SchemaFields-muOTQM8x.js → SchemaFields-BBCNN0DQ.js} +1 -1
- package/page/assets/{ToolResultCharts-Bhesjbc4.js → ToolResultCharts-BA5C4s_d.js} +1 -1
- package/page/assets/{Toolbar-t4I6MDV_.js → Toolbar-cLeL30W1.js} +1 -1
- package/page/assets/{TraceInspector-BqEGN_46.js → TraceInspector-6xElMxMt.js} +1 -1
- package/page/assets/{TraceOverview-DLEqvRF2.js → TraceOverview-BgjbNvh5.js} +1 -1
- package/page/assets/{_virtual_studio-type-sources-Cc4WAdgD.js → _virtual_studio-type-sources-_88V0ngH.js} +37 -44
- package/page/assets/browser-connection-C1_PJcSQ.js +1 -0
- package/page/assets/browser-engine-VzmlJFEv.js +16 -0
- package/page/assets/browser-transport-JN5LOARG.js +45 -0
- package/page/assets/compile-BJuLB_as.js +2 -0
- package/page/assets/{encode-files-CeZxxjYd.js → encode-files-CCet4LKE.js} +1 -1
- package/page/assets/{export-agent-CYZqQ4ll.js → export-agent-BzdhT7lw.js} +8 -8
- package/page/assets/{guardrail-tester-D-_i4Zuj.js → guardrail-tester-M-A7EKhq.js} +1 -1
- package/page/assets/index-BHZr7HfC.js +149 -0
- package/page/assets/index-BYDlXF8Q.css +1 -0
- package/page/assets/live-messages-tG47aB12.js +1 -0
- package/page/assets/{prompt-row-CIxkqX9Q.js → prompt-row-BUe2Ni0Y.js} +2 -2
- package/page/assets/reader-SzTjS7rw.js +5 -0
- package/page/assets/{registry-DP0ArymS.js → registry-BrmnEhgs.js} +1 -1
- package/page/assets/schema-BztznKB7.js +3 -0
- package/page/assets/{shaped-data-DCfLI4gb.js → shaped-data-D15FDUcH.js} +3 -3
- package/page/assets/{stub-REBz-ZC7.js → stub-CJG-5zBe.js} +1 -1
- package/page/assets/studio-code-pane-k8fWxZOU.js +10 -0
- package/page/assets/{studio-console-DHgwXKne.js → studio-console-BANFk07G.js} +1 -1
- package/page/assets/{studio-decision-B_EdxnvG.js → studio-decision-DFj8AA2c.js} +1 -1
- package/page/assets/{studio-embedding-mZIx4qHD.js → studio-embedding-CZy7UHg8.js} +1 -1
- package/page/assets/{studio-host-console-BmB0sSsX.js → studio-host-console-CRxuC6E-.js} +2 -2
- package/page/assets/{studio-labels-BRouZt4M.js → studio-labels-3Sq86Mzp.js} +1 -1
- package/page/assets/studio-live-BcOCiV63.js +5 -0
- package/page/assets/{studio-map-8aIk_pdY.js → studio-map-CCtcfniD.js} +1 -1
- package/page/assets/{studio-trace-replay-BaF2UAqT.js → studio-trace-replay-C5t6OfXY.js} +1 -1
- package/page/assets/{studio-type-checker-JZuu4iVI.js → studio-type-checker-o2Q6t4mP.js} +1 -1
- package/page/assets/{tool-schema-BwaPiLtT.js → tool-schema-D26IAEC3.js} +1 -1
- package/page/assets/trace-record-jocyYEPa.js +1 -0
- package/page/assets/tree-B0fXPCwG.js +3 -0
- package/page/assets/{turn-client-B3jV7UKH.js → turn-client-eM8VIbMd.js} +1 -1
- package/page/assets/{types-BDx4pnrt.js → types-CfC3vRXO.js} +1 -1
- package/page/assets/{use-one-call-BKLi6fk_.js → use-one-call-Drfw4kwV.js} +1 -1
- package/page/assets/{workspace-B6d08n7C.js → workspace-BlOYHATA.js} +1 -1
- package/page/index.html +17 -17
- package/prompt-doc.d.ts +1 -1
- package/prompt-doc.js +2 -2
- package/read-source.js +26 -39
- package/section-notes.d.ts +1 -2
- package/section-notes.js +1 -2
- package/system-markup.d.ts +1 -1
- package/system-markup.js +1 -1
- package/ui/lib/export-agent.js +9 -26
- package/ui/lib/studio-page.d.ts +9 -16
- package/ui/lib/studio-page.js +28 -38
- package/ui/profile-editor.js +46 -93
- package/ui/prompt-editor.d.ts +1 -1
- package/ui/prompt-editor.js +11 -11
- package/ui/prompt-line-node.d.ts +5 -5
- package/ui/prompt-line-node.js +9 -9
- package/ui/prompt-row.d.ts +3 -3
- package/ui/prompt-row.js +3 -3
- package/ui/studio-compare.d.ts +4 -2
- package/ui/studio-compare.js +6 -5
- package/ui/studio-live.d.ts +1 -1
- package/ui/studio-live.js +2 -2
- package/ui/studio-runner.d.ts +4 -3
- package/ui/studio-runner.js +9 -9
- package/ui/studio-screen.js +5 -2
- package/ui/studio.css +3 -3
- package/page/assets/browser-connection-159CdeHX.js +0 -1
- package/page/assets/browser-engine-Fi7MROTb.js +0 -16
- package/page/assets/browser-transport-C_sHZVPa.js +0 -45
- package/page/assets/compile-iB2CAmRL.js +0 -2
- package/page/assets/index-DakRjE8R.css +0 -1
- package/page/assets/index-DuTrjzLN.js +0 -149
- package/page/assets/live-messages-D-SPyR3e.js +0 -1
- package/page/assets/reader-DtOL_I1x.js +0 -5
- package/page/assets/schema-Cv4HAfBT.js +0 -3
- package/page/assets/studio-code-pane-DEBuOivy.js +0 -10
- package/page/assets/studio-live-Cy09vyLv.js +0 -5
- package/page/assets/trace-record--uEnDt_D.js +0 -1
- package/page/assets/tree-CL4ETBd5.js +0 -3
- package/slot-values.d.ts +0 -2
- package/slot-values.js +0 -22
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{C as e,E as t,O as n,b as r,c as i,d as a,h as o,v as s,x as c}from"./schemas-D7cgkv3L.js";import{Jn as l,Vn as u,Zn as d,tr as f}from"./tool-schema-BwaPiLtT.js";import{C as p,M as m,O as h,j as g}from"./reader-DtOL_I1x.js";import{n as _}from"./trace-schema--4IGmLeE.js";import{w as v}from"./turn-client-B3jV7UKH.js";var y=c({type:s(`open`),history:a(d).optional(),slots:e(t(),t()).optional(),context:n().optional(),stated:h.optional(),model:t().optional(),effort:t().optional(),resume:c({providerState:f,awayMs:r().nonnegative()}).optional(),host:e(t(),n()).optional()}),b=o(`type`,[c({type:s(`audio`),data:t()}),c({type:s(`video`),data:t(),mimeType:t()}),c({type:s(`text`),text:t()}),c({type:s(`context`),context:n()}),c({type:s(`executeTool`),callId:t().min(1),operationId:t().min(1).max(256),decision:i(v).optional(),input:n().optional(),secret:t().optional(),output:n().optional(),grantId:t().min(1).optional(),unanswered:s(!0).optional()})]),x={ready:c({type:s(`ready`),profile:t().optional(),sessionId:t().optional()}),events:c({type:s(`events`),events:a(n())}),trace:c({type:s(`trace`),record:_}),error:c({type:s(`error`)}).and(p),executeToolResult:o(`status`,[c({type:s(`executeToolResult`),callId:t().min(1),operationId:t().min(1).max(256),status:s(`dispatched`),grantId:t().min(1),arguments:e(t(),n())}),c({type:s(`executeToolResult`),callId:t(),status:s(`settled`),operationId:t().min(1).max(256)}),c({type:s(`executeToolResult`),callId:t(),status:s(`gated`),operationId:t().min(1).max(256),gate:l}),c({type:s(`executeToolResult`),callId:t(),status:s(`refused`),operationId:t().min(1).max(256),body:p})])};function S(e){let t=g(x,e);return t.type===`events`?{type:`events`,events:t.events.map(e=>m(u,e))}:t}export{y as n,S as r,b 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{$n as v,Cn as y,En as b,Hn as x,Kn as S,Tn as C,U as ee,Vn as w,X as T,Xn as E,Zn as D,ar as O,bn as k,en as te,or as ne,pn as re,qt as ie,s as ae,sr as oe,tn as se,wn as ce,xn as A}from"./tool-schema-BwaPiLtT.js";import{c as j}from"./host-patterns-F-KZIzkF.js";import{$ as le,Ar as ue,At as de,Br as fe,Bt as pe,Dr as me,Et as he,F as ge,Fr as _e,Ft as ve,G as ye,Gt as be,Hr as M,Ht as xe,I as Se,Ir as Ce,It as we,Jt as Te,Kt as Ee,L as De,Lr as Oe,Lt as ke,N as Ae,Ot as je,P as Me,R as Ne,Tr as Pe,Ut as Fe,V as Ie,Vt as Le,Wn as Re,Wt as ze,Yn as Be,Yt as Ve,Z as He,_n as Ue,an as We,at as Ge,bn as Ke,cr as qe,dn as Je,dt as Ye,fn as Xe,in as Ze,it as Qe,j as $e,jr as et,kn as tt,mr as nt,nt as rt,pr as it,pt as at,qt as ot,rn as st,rt as ct,sr as lt,tn as ut,tt as dt,un as ft,vt as N,wn as pt,wt as mt,xn as ht,xr as gt,yn as _t,zn as vt,zr as yt,zt as bt}from"./shaped-data-DCfLI4gb.js";import{S as xt,_ as St,b as Ct,x as wt}from"./browser-connection-159CdeHX.js";import{A as Tt,C as Et,E as Dt,M as Ot,N as kt,O as At,P as jt,S as Mt,g as Nt,h as Pt,x as Ft}from"./schema-Cv4HAfBT.js";import{a as It}from"./live-ingress-OuSlQ6q7.js";import{n as Lt,t as Rt}from"./trace-schema--4IGmLeE.js";import{n as zt}from"./stub-REBz-ZC7.js";function Bt(e){return{type:`guardrail`,guardrail:e}}function Vt(e,t,n,r=`redact`,i){if(n.length!==0)return Bt({stage:e,trust:t,action:r,hits:n,...i?{provenance:i}:{}})}function Ht(e,t){return e.type===`guardrail`?{...e,guardrail:qe(e.guardrail,t)}:e}var P=65536;function F(e){let t=e.classStarts.length,n=new Uint16Array(P);for(let r=0;r<t;r++)n.fill(r,e.classStarts[r],e.classStarts[r+1]??P);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 Ut,I,Wt;async function Gt(){if(Ut)return;let{FORWARD_AUTOMATON:t,REVERSED_AUTOMATON:n}=await e(async()=>{let{FORWARD_AUTOMATON:e,REVERSED_AUTOMATON:t}=await import(`./egress-automata-SiHQTP1i.js`);return{FORWARD_AUTOMATON:e,REVERSED_AUTOMATON:t}},[]);Ut={forward:t,reversed:n}}function Kt(){if(!Ut)throw Error(`A stream was opened before loadEgressAutomata() finished.`);return Ut}var L;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 Jt(e){if(!L){L=new Map;for(let e=0;e<P;e++){let t=qt(e),n=L.get(t);n?n.push(e):L.set(t,[e])}}return L.get(qt(e))??[e]}function Yt(e){let t=[0];for(let n of e)t.at(-1)!==n&&t.push(n),n+1<P&&t.push(n+1);return t}var Xt=new Map;function Zt(e){let t=Xt.get(e);if(t)return t;let n=Array.from({length:e.length},(t,n)=>Jt(e.charCodeAt(n))),r=Yt([...new Set(n.flat())].sort((e,t)=>e-t)),i=e=>r.indexOf(e),a=F({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 Xt.set(e,a),a}function Qt(e){let t=JSON.stringify(e),n=Xt.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=Yt(r),a=r.map(e=>[i.indexOf(e)]),o=[],s=F({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 Xt.set(t,s),s}function $t(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 en(e,t){e.text+=t,e.fresh+=t}function tn(e){return e.text.length-e.fresh.length}function R(e,t){let n=tn(e);return t>=n?e.fresh.charCodeAt(t-n):e.text.charCodeAt(t)}function nn(e,t,n=e.text.length){let r=tn(e);return t>=r?e.fresh.slice(t-r,n-r):e.text.slice(t,n)}function rn(e){let t={text:``,fresh:``,rawAt:e=>e,update(){t.text=e.text,t.fresh=e.fresh}};return t}function an(e,t){let n={text:``,fresh:``,rawAt:e.rawAt,update(){n.fresh=``,en(n,t(nn(e,n.text.length)))}};return n}var on=/\w/,sn=Math.max(...Le.map(e=>e.length));function cn(e){return e.length<=sn+1&&/^[A-Za-z]*$/.test(e)}function ln(e){let t=0,n,r=!1,i=[],a=(e,t,n)=>{en(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(R(e,t)),o=on.test(i);o&&!r&&(n=``),r=o,o?n===void 0?a(i,t,1):n+=i:(n!==void 0&&a(be(n),t-n.length,n.length),n=void 0,a(i,t,1))}n!==void 0&&!cn(n)&&(a(n,t-n.length,n.length),n=void 0)}};return o}function un(e){let t={text:``,fresh:``,from:[],rawAt:n=>n<t.from.length?t.from[n]:e(),update(){}};return t}function z(e,t,n){en(e,t);for(let r=0;r<t.length;r++)e.from.push(n)}var dn=55296,fn=56319,pn=/[A-Za-z]/,mn=56320,hn=57343;function gn(e){let t=0,n=``,r=[],i=``,a=[],o=!1,s=-1,c=un(()=>Math.min(t,r[0]??t,a[0]??t,s<0?t:s));function l(e,t){s>=0&&(pn.test(e)||z(c,`\\`,s),s=-1),e===`\\`?s=t:z(c,e,t)}function u(e,t){if(Ee(e)&&(o||i)){i+=e;for(let n=0;n<e.length;n++)a.push(t)}else{if(i){if(!pn.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=pn.test(e)&&e.length===1}}function d(){let e=0;for(;e<n.length;){let t=n.charCodeAt(e),i=t>=dn&&t<=fn;if(i&&e+1>=n.length)break;let a=n.charCodeAt(e+1),o=i&&a>=mn&&a<=hn?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=R(e,t),o=a>=dn&&a<=fn;if(o&&t+1>=i)break;let s=R(e,t+1),c=o&&s>=mn&&s<=hn?2:1,l=ot(nn(e,t,t+c));n+=l;for(let e=0;e<l.length;e++)r.push(t);t+=c}d()},c}var _n=/[0-9A-Fa-f]/;function vn(e){let t=0,n=-1,r=un(()=>n<0?t:n);r.update=()=>{r.fresh=``;let a=e.text.length;for(;t<a;){let a=String.fromCharCode(R(e,t));if(n<0){a===`%`?n=t:(z(r,a,t),t++);continue}let o=(t-n)%3;if(o===0?a===`%`:_n.test(a))t++;else{i(t-o);for(let n=t-o;n<t;n++)z(r,String.fromCharCode(R(e,n)),n)}}};function i(t){t>n&&z(r,xe(nn(e,n,t)),n),n=-1}return r}var yn=new Set([`injection`,`base64`,`hex`,`spaced`,`pipe`]),bn=new Map(pe.map(({pattern:e,hit:t})=>[e,t])),xn=new Map(rt.flatMap(({pattern:e,hit:t})=>t?[[e,t]]:[]));function B(e){return{rule:it(e),severity:`high`,detector:e}}var Sn=B(`injection`),Cn=B(`marker_leak`),wn=B(`tool_leak`);function Tn({kind:e,group:t}){if(yn.has(e))return Sn;switch(e){case`sensitive`:case`card`:return t===void 0?void 0:B(t);case`boundary`:return Cn;case`image`:return B(`ungiven_images`);default:return B(`ungiven_links`)}}function En(e,t,n){if(e===`card`)return{hit:ct};if(e===`image`||e===`link`){let r=(e===`image`?Qe:Ge).indexOf(t),i=n[e][r];return`find`in i?{find:i.find}:{hit:i.test}}let r=bn.get(t)??xn.get(t);return r?{hit:r}:{}}function Dn(e,{given:t,allow:n,skipImages:r}){let i=e=>({...e,...t?{given:t}:{}}),a={image:Ye(i(n?.ungiven_images)),link:at(i(n?.ungiven_links),r??e.includes(`ungiven_images`))},o=[];return le.forEach((t,n)=>{let r=Tn(t);r?.detector&&e.includes(r.detector)&&o.push({...r,id:n,regex:Ve(t.pattern),...En(t.kind,t.pattern,a)})}),o}function On(){let e=[];return le.forEach(({kind:t,pattern:n},r)=>{if(t!==`injection`)return;let i=bn.get(n);e.push({...Sn,id:r,regex:Ve(n),...i?{hit:i}:{}})}),e}function kn(){return Te.map((e,t)=>({...Sn,id:t,regex:new RegExp(e.source,e.flags)}))}function An(e,t,n){let r=$t(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),C=[...new Set(S)].filter(e=>e>=0),ee=n.flatMap((e,t)=>S[t]<0?[]:[t]),w=new Int32Array(t.has.length).fill(-1);function T(){let{text:n,fresh:h}=e,g=tn(e),{classOf:_,has:v,edges:ee,final:T,pattern:E}=t;for(;p<n.length;p++){let e=_[p>=g?h.charCodeAt(p-g):n.charCodeAt(p)];f++;let t=0,D=(e,n)=>{if(d[e]===f){let t=u[e];n<c[t]&&(c[t]=n)}else d[e]=f,u[e]=t,s[t]=e,c[t]=n,t++,T[e]&&(m[i[E[e]]]=1)};for(let t=0;t<l;t++){let n=ee[a[t]],r=o[t];for(let t=0;t<n.length;t+=2)v[n[t+1]][e]&&D(n[t],r)}let O=r[e];for(let e=0;e<O.length;e++){let t=O[e],n=i[E[t]],r=S[n],a=r<0?-1:w[r],o=a<0?p:a;D(t,o),y[n]&&(x[n]=p,b[n]<0&&(b[n]=o))}for(let t of C)v[t][e]?w[t]<0&&(w[t]=p):w[t]=-1;[a,s]=[s,a],[o,c]=[c,o],l=t}}function E(){let n=e.text.length;_.fill(n),v.fill(0);let r=n;for(let e=0;e<l;e++){let n=a[e],s=i[t.pattern[n]],c=o[e];c<_[s]&&(_[s]=c),t.final[n]&&(v[s]=1),c<r&&(r=c)}for(let e of ee){let t=w[S[e]];t<0||(t<_[e]&&(_[e]=t),t<r&&(r=t))}return r}function D(t,r){let i=b[t],a=g[t];if(i<0||i>=r){g[t]=r;return}let{find:o,rule:s,severity:c,detector:l}=n[t],u=o?.(e.text,a,r);if(u===void 0)g[t]=r,b[t]=x[t]>=r?r:-1;else return g[t]=Math.max(a,u)+1,{rule:s,severity:c,start:e.rawAt(u),detector:l}}let O={text:``,lower:``},k=()=>(O.text!==e.text&&(O={text:e.text,lower:e.text.toLowerCase()}),O.lower);function te(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,k)))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 ne(){for(let e=0;e<n.length;e++){let t=_[e];if(t<=g[e])continue;let r=n[e].find?D(e,t):te(e,t);if(r)return r}}return{run(t){T();let n=E();for(let e=ne();e;e=ne())t.push(e);return e.rawAt(n)}}}var jn=new WeakMap;function Mn(e){let t=jn.get(e);return t||(t=F(e),jn.set(e,t)),t}function Nn(e={}){let t={text:``,fresh:``},n=rn(t),r=[n],i=(e,t,n)=>(r.includes(e)||r.push(e),An(e,t,n)),a=[],o=e.detect??[],s=Dn(o,e);if(s.length>0&&(I??=F(Kt().forward),a.push(i(n,I,s))),o.includes(`injection`)){I??=F(Kt().forward),Wt??=F(Kt().reversed);let e=gn(t),r=On();a.push(i(n,Wt,kn()),i(ln(n),I,r),i(e,I,r),i(ln(e),I,r),i(an(n,ze),I,r),i(an(n,e=>Fe(e)??e),I,r),i(vn(t),I,r))}if(o.includes(`marker_leak`)&&e.note){let t=dt(e.note);a.push(i(n,Zt(e.note),[{...Cn,id:0,regex:t}]))}if(o.includes(`tool_leak`)&&e.tools){let t=ye(e.tools),r=t.map(({regex:e},t)=>({...wn,id:t,regex:e}));t.length>0&&a.push(i(n,Qt(t.map(({literal:e})=>e)),r))}for(let{detector:t,compiled:r,matchers:o}of e.own??[]){let e=o.map(({regex:e},n)=>({...B(t),id:n,regex:new RegExp(e.source,e.flags)}));a.push(i(n,Mn(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 Pn(e,t,n={},r=[]){let i=Se(e,t).filter(e=>!(Ne(e)||r.includes(e))),a=De(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=Nn({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=ge(p,c,e,t,{detectors:o,scope:n});return m=m.filter(({start:e})=>e>=r+l.taken),l}}}function Fn(e){let{context:t}=e,n=e.detect,r=n?Pn(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(-N),_=u,v=0,y=u,b=0,x=0,S=s?he(s):void 0;S?.push(u);function C(e){let n=[];if(S?.push(e)&&n.push([a,lt]),c){let r=_.length;_+=e;let i=bt(_,r);_=_.slice(i),v+=i;let[a]=He(_,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 ee(e){let t=l?C(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-N),i=r+mt(y.slice(r-b),e);i<n&&n>t&&(y=g+h,b=t-g.length,i=b+mt(y,e)),x=Math.min(i,u.length+p.length-N);let a=Math.max(b,Math.max(t,x)-N);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+ke(i,e,t)-u.length-m)}function O(e){let t=ee(e);if(t)return{blocked:!0,...t};let i=e===void 0,a=i?p.length:Math.min(w(),r?.holdFrom()??p.length),o=Math.max(0,a-m);if(!(n&&r))return T({blocked:!1,emit:k(o)});let s=r.take(m,m+o,i);return s.action===`block`||s.action===`redact`&&!n.rewrite?{blocked:!0,hits:s.hits,boundary:n.boundary}:(k(s.taken),T({blocked:!1,emit:s.text??``,...s.action===`allow`?{}:{found:{action:s.action,hits:s.hits}}}))}function k(e){let t=h.slice(0,e);return h=h.slice(e),m+=t.length,l&&(g=(g+t).slice(-N)),t}return{process(e){return e?(p+=e,h+=e,l&&(y+=e),O(e)):{blocked:!1,emit:``}},flush:()=>O(),accumulated:()=>p,unreleased:()=>h,drainUnreleased:()=>k(h.length),carryOut:()=>l?de(u+p,s,c):``}}function V(e,t,n){return Me(t,e.detect,n)}async function In(e,t,n,r){return V(e,[n],t)?(await Gt(),Ln(e,t,n,r)):null}function Ln(e,t,n,r){return V(e,[n],t)?Fn({context:t,detect:{matrix:e.detect,boundary:n,rewrite:n===`reply`,scope:Ie(e,t)},...r?{carry:r}:{}}):null}async function Rn(e,t,n,r){return V(e,[n],r??t)?(await Gt(),Fn({context:t,detect:{matrix:e.detect,boundary:n,rewrite:!1,scope:r??Ie(e,t)}})):null}var zn=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}},Bn=[`user`,`slots`,`repair`,`attachment`,`voice`,`history`,`system`];function Vn(e,t){return e&&Object.fromEntries(Object.entries(e).map(([e,n])=>[e,t.read(n)]))}var Hn={client:`untrusted`,server:`assembled`};function Un(e){return typeof e==`string`?e:JSON.stringify(e)}function Wn(e,t){let n=[],r=!1;if(!e)return{context:e,events:n,blocked:r};let i={};for(let a of Ze){let o=e[a];if(o===void 0)continue;let s=t();i[a]=s.read(Un(o));let c=s.found(),l=Ae(`context`,c);l&&n.push({...l,trust:Hn[a]}),r||=c.action===`block`}return{context:i,events:n,blocked:r}}var Gn=/^[A-Za-z0-9._-]+$/;function Kn(e){let t=e?.trim();return t&&Gn.test(t)?t:void 0}function qn(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 Jn(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 Yn(e,t){let n=t?`: ${t}`:``;return new j(`input`,`guardrails.detect blocked the request at ${e}${n}`,{copy:{key:`detect.blocked`}})}function Xn(e,t){let{detect:n}=b(t.guardrails),r=Pe(Bn,e=>$e(e,n)),i=e.input??{},a=i.text===void 0?void 0:r.user.read(i.text),o=e.system===void 0?void 0:kt(e.system,`TurnRequest.system`,e=>r.system.read(e)),s=Vn(i.slots,r.slots),c=Wn(i.context,()=>$e(`context`,n)),l=qn(i.repair,r.repair),u=i.history?Jn(i.history,r.history):void 0,{attachments:d,voice:f}=i.attachments?.length||i.voice?.length?xt(t,i.attachments,i.voice,r):i,p=[],m;for(let e of Bn){let t=r[e].found(),n=Ae(e,t);n&&p.push(Bt(n)),t.action===`block`&&(m??=Yn(e,t.errorInternal))}return p.push(...c.events.map(Bt)),c.blocked&&(m??=Yn(`context`)),{request:{...e,system:o,projectId:Kn(e.projectId),input:{...i,text:a,slots:s,...c.context?{context:c.context}:{},repair:l,history:u,attachments:d,voice:f}},events:p,...m?{refusal:m}:{}}}function Zn(e,t){let{request:n,refusal:r}=Xn(e,t);if(r)throw r;return n}function Qn(e,t){return[...new Set([...t.filter(t=>A(e,t)),...e.filter(e=>A(t,e))])]}function $n(e,t){let n=e.attachments?t?Qn(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 er(e){let t=C(e[0]??``);return t===`application/pdf`?`PDF`:t.split(`/`)[0]??t}function tr(e,t){let n=wt(e),r=St({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=>A(t.accept,e.mimeType)).length>t.max&&r.push({code:`too_many_of_kind`,params:{maxFiles:t.max,kind:er(t.accept)}})}let i=new Set;return r.filter(e=>{let t=JSON.stringify(e);return!i.has(t)&&(i.add(t),!0)})}var nr=`final_answer`;function rr(e){return e.structured!==null&&e.tools.wire.length>0}function ir(e,t,n){let{structured:r}=t;if(!r||!rr(t))return e;let i={type:`function`,name:nr,description:M(`structured.answer_tool`,{},n),parameters:r.jsonSchema};return{...e,structured:null,wireTools:[...e.wireTools??[],i]}}function ar(e,t){return e.get(t)||{name:t,missing:!0}}function or(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 sr(e,t){return[...Ft(t),...or(t)].map(t=>ar(e,t))}function cr(e,t){if(Array.isArray(e)){for(let n of e)cr(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),cr(r,t);for(let e of Object.values(r))cr(e,t)}function lr(e,t){let n=sr(e,t);if(n.length===0)return;let r=new Set;for(let e of n)`inputSchema`in e&&cr(e.inputSchema,r);return{names:n.map(({name:e})=>e),params:[...r]}}function ur(e){return!e||e.length===0?[]:e.slice(-4)}function dr(e,t){if(e.length===0)return``;let n=e.map(e=>`${e.role===`user`?`User`:`Assistant`}: ${e.content}`);return`${M(`repair.history_heading`,{count:e.length},t)}\n${n.join(`
|
|
2
|
-
`)}\n\n`}function fr(e){let{profile:t,repair:n,history:r}=e,i=n.guidance||M(`repair.default_guidance`,{},t.labels),a=dr(ur(r),t.labels),o=`${M(`repair.prompt_header`,{},t.labels)}\n\n`;return o+=`${M(`repair.prompt_intro`,{},t.labels)}\n\n`,o+=`${M(`repair.section_previous_output`,{},t.labels)}\n\`\`\`\n${n.previousOutput.trim()}\n\`\`\`\n\n`,o+=`${M(`repair.section_validator_rejection`,{},t.labels)}\n${n.rejection.trim()}\n\n`,i.trim()&&(o+=`${M(`repair.section_repair_guidance`,{},t.labels)}\n${i.trim()}\n\n`),a&&(o+=a),o+=`${M(`repair.section_instructions`,{},t.labels)}\n`,o+=M(`repair.prompt_instructions`,{},t.labels),o}function pr(e,t){let n=[];return t&&n.push(`structured`),e.type===`image`&&n.push(`image`),e.type===`speech`&&n.push(`speech`),n}function mr(e,t){let n=pr(e,t);if(!(n.length<=1))throw new j(`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 hr(e,t){if(e.type!==`speech`){if(t.speech)throw new j(`request`,`Profile ${e.id} (${e.type}) takes no speech settings — only a speech profile speaks`)}else if(t.system)throw new j(`config`,`Profile ${e.id} (speech) takes no system prompt — the input text is the transcript`)}function gr(e,t){if(e.type===`transcription`){if(t.system)throw new j(`config`,`Profile ${e.id} (transcription) takes no system prompt — the input is the clip`);if(!t.input?.voice?.length)throw new j(`request`,`Profile ${e.id} (transcription) requires a voice clip`)}}function _r(e,t){return e.type===`speech`?{...e.speech,...vr(t.speech)}:void 0}function vr(e){return Object.fromEntries(Object.entries(e??{}).filter(([,e])=>e!==void 0))}function yr(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 br(e){let t=k(e);if(!t)throw new j(`input`,`MIME '${e}' is not a supported media input type`);return t}function xr(e){return e.map(e=>{let t=br(e.mimeType),n=C(e.mimeType),r=n===`image/jpg`?`image/jpeg`:n;return Ct(e)?{type:t,mimeType:r,uri:e.uri}:{type:t,mimeType:r,data:e.data}})}function Sr(e,t){let{text:n,repair:r,history:i}=t.input??{};if(e.type===`speech`&&!n?.trim())throw new j(`request`,`Profile ${e.id} (speech) requires text input`);if(y(e)?.text===!1&&n)throw new j(`request`,`Profile ${e.id} does not accept text input`);let a=r?fr({profile:e,repair:r,history:i}):wr(e,t)??n;if(e.type===`speech`)return a?{type:`text`,text:a}:null;let o=[...Cr(t),...a?[we(a)]:[]];return o.length>0?{type:`text`,text:o.join(`
|
|
3
|
-
|
|
4
|
-
`)}:null}function Cr(e){let t=e.input?.context??{};return[...Ze].reverse().filter(e=>t[e]!==void 0).map(e=>ve(e,Un(t[e])))}function wr(e,t){if(t.continueFrom&&ie.includes(e.type)){if(t.input?.text)throw new j(`request`,`Profile ${e.id}: a continueFrom turn takes no input.text — its user message is the continue instruction`);return M(`continue.instruction`,{},e.labels)}}function Tr(e){return e.type===`image`&&e.image.references?xr(e.image.references):[]}function Er(e,t){let n=t.input?.attachments??[],r=t.input?.voice??[];return[...Tr(e),...xr(n),...xr(r)]}function Dr(e,t){let n=[],r=Sr(e,t);return r&&n.push(r),n.push(...Er(e,t)),n}function Or(e,t){let n=t.input?.slots;if(!n)return;let r=y(e)?.slots??{};for(let[t,i]of Object.entries(n)){let n=Object.hasOwn(r,t)?r[t]:void 0;if(!n)throw new j(`request`,`Profile ${e.id} has no slot '${t}'`);let a=Nt(n);if(!a.includes(i))throw new j(`request`,`Profile ${e.id}: slot '${t}' takes ${a.join(`, `)}, not '${i}'`)}}function kr(e,t){let n=t.input?.context;if(!n)return;let r=y(e)?.context;for(let[t,i]of Object.entries(n))if(i!==void 0){if(!Ze.includes(t)||!r?.from.some(e=>e===t))throw new j(`request`,`Profile ${e.id} takes no context from '${t}'`);if(Un(i).length>r.maxChars)throw new j(`request`,`Profile ${e.id}: context from '${t}' is over inputs.context.maxChars (${String(r.maxChars)})`)}}var Ar=/\{([A-Za-z_][\w-]*)\}/g;function jr(e,t,n,r){let i=y(e)?.slots;return i?t.replace(Ar,(t,a)=>{if(!Object.hasOwn(i,a))return t;let o=n&&Object.hasOwn(n,a)?n[a]:void 0;if(o===void 0)throw new j(`request`,`Profile ${e.id}: ${r} uses slot '${a}', and the request chose no value for it`);return o}):t}function Mr(e,t,n){if(e.type===`speech`||e.type===`transcription`)return[];let r=e.identity.system;if(!r)return[];let i=Tt(e.id,e.identity.conditions,n,t);return At(r,i,n=>jr(e,n,t,`identity.system`))}function Nr(e,t){let n=Mr(e,t.input?.slots,t);return{pieces:Ot([...n.map(({pieces:e})=>e),t.system===void 0?[]:jt(t.system)]),lines:n.map(({line:e})=>e)}}function Pr(e){return e.type!==`host`&&e.type!==`decision`&&e.type!==`embedding`}function Fr(e,t){if(Pr(e))return e;throw e.type===`host`?new j(`request`,`Profile ${e.id}: type 'host' never runs a model — ${t} is not supported; execute tools with invokeTool`):e.type===`embedding`?new j(`request`,`Profile ${e.id}: type 'embedding' runs through runEmbedding — ${t} is not supported`):new j(`request`,`Profile ${e.id}: type 'decision' runs through runDecision — ${t} is not supported`)}function Ir(e,t){if(t){if(!e.allowModelSelect)throw new j(`request`,`Profile ${e.id} does not allow model selection`);if(!e.models[t])throw new j(`request`,`Unknown model '${t}' for ${e.id}`);return t}return e.defaultModel}function Lr(e,t,n,r){let i=t.efforts;if(!i||Object.keys(i).length===0){if(r)throw new j(`request`,`Profile ${e.id} model '${n}' has no selectable efforts`);return}let a=Object.keys(i);if(r){if(!t.allowEffortSelect)throw new j(`request`,`Profile ${e.id} model '${n}' does not allow effort selection`);let a=i[r];if(!a)throw new j(`request`,`Unknown effort '${r}' for ${e.id} model '${n}'`);return a}return i[t.defaultEffort??a[0]]}function Rr(e){if(e.summaries===!0)return`auto`;if(e.summaries===!1)return`none`}function zr(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 Br(e){return e.type===`live`||e.outputs?.streaming?.mode!==`buffered`}function Vr(e,t){return e.type===`live`?`live`:`turn`}function Hr(e,t){if(!t.continueFrom)return;if(e.type===`live`)throw new j(`request`,`Profile ${e.id}: type 'live' uses live.sessionResumption, not turnBehaviour.resumption/continueFrom`);let n=se(e)?.maxContinues;if(n===void 0)return;let r=t.continuation;if(r===void 0)throw new j(`request`,`Profile ${e.id}: continueFrom requires TurnRequest.continuation when turnBehaviour.resumption.maxContinues is set`);if(r<1)throw new j(`request`,`Profile ${e.id}: continuation must be >= 1`);if(r>n)throw new j(`request`,`Profile ${e.id}: continuation ${r} exceeds turnBehaviour.resumption.maxContinues (${n})`)}function Ur(e,t){return V(b(t),[`live_reply`])?{...e,transcription:{...e?.transcription,output:!0}}:e}function Wr(e){let{detect:t}=b(e.guardrails);return e.type!==`speech`&&e.type!==`transcription`&&Be(t,`canary_leak`)?je():``}function Gr(e,t,n,r){if(!r)return;let i={};for(let[a,o]of Object.entries(r)){if(!n.builtInTools?.includes(a))throw new j(`request`,`Profile ${e.id}: builtInArgs names '${a}', which model '${t}' does not list in builtInTools`);i[a]=o}return i}function Kr(e,t,n){let r=Fr(e.profiles.get(t.profile),`resolveTurn`);Or(r,t),kr(r,t);let i=Zn(t,r),a=i.input??{};Hr(r,i);let o=n??Ir(r,i.model),s=ce(r,o),c=Dt(e.tools,r,i,o),l=c.builtins,u=zr(r,a.slots);if(mr(r,u),u&&c.wire.some(e=>e.name===`final_answer`))throw new j(`config`,`Profile ${r.id}: a structured turn answers through '${nr}', so no tool of its own may take that name`);hr(r,i),gr(r,i);let d=Gr(r,o,s,i.builtInArgs),f=Vr(r,s),p=e.providers.get(s.provider),m=p&&re(p,s,r.type),h=Nr(r,i);return{profile:r,generation:{model:o,apiId:s.apiId,transport:f,...m?{operationName:m}:{},stream:Br(r),thinking:Lr(r,s,o,i.effort),summaries:Rr(s),maxOutputTokens:s.maxOutputTokens,temperature:s.temperature,builtins:l,builtInArgs:d,sessionId:i.sessionId,tools:c,sessionPermissions:i.sessionPermissions,execution:i.execution,pageExecution:i.pageExecution,history:a.history,maxSteps:r.maxSteps??20,structured:u?{id:u,jsonSchema:e.schemas.get(u).jsonSchema}:null,image:yr(r),speech:_r(r,i),live:r.type===`live`?Ur(r.live,r.guardrails):void 0,input:Dr(r,i),canary:Wr(r),resolvedSystem:h.pieces,systemLines:h.lines,host:i.host}}}function qr(e){return e.type===`image`?e.image:null}function Jr(e,t){let n=Fr(t,`projectProfile`),{identity:r}=n,i=y(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:sr(e,n),inputs:i,outputs:a,image:qr(n),speech:n.type===`speech`?n.speech:null,live:n.type===`live`?n.live:null}}function Yr(e,t){return Jr(e.tools,e.profiles.get(t))}var Xr=[`audio/webm;codecs=opus`,`audio/webm`,`audio/mp4`,`audio/wav`,`audio/mpeg`];function Zr(e){return e.join(`,`)}function Qr(e){let t=e?.attachments?.accept,n=e?.voice?.accept;return{text:e?.text!==!1,attachments:t?.length?{accept:t,acceptAttr:Zr(t)}:null,voice:n?.length?{accept:n}:null,maxFiles:e?.maxFiles,maxBytes:e?.maxBytes,maxTurnBytes:e?.maxTurnBytes,limitsByMime:e?.limitsByMime,slots:Pt(e?.slots),context:e?.context}}function $r(e){return{text:e.text,attachments:e.attachments?{accept:e.attachments.accept}:void 0,voice:e.voice?{accept:e.voice.accept}:void 0,maxFiles:e.maxFiles,maxBytes:e.maxBytes,maxTurnBytes:e.maxTurnBytes,limitsByMime:e.limitsByMime,slots:e.slots,context:e.context}}function ei(e,t){let n=e=>(e??[]).map(({name:e,mimeType:t,sizeBytes:n})=>({name:e,mimeType:t,sizeBytes:n})),r=St({attachments:e.attachments?.accept,voice:e.voice?.accept,limits:wt($r(e))},n(t.attachments),n(t.voice));return{ok:r.length===0,issues:r}}function ti(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(Xr.filter(t=>A(e,t)))??e.find(n):r(Xr)}var ni=_({protocol:r(),provider:r(),apiId:r(),options:t(r(),u()).optional(),keySlot:r().optional(),fallbackKeySlot:r().optional(),efforts:t(r(),c(ht)).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(st),meter:c(ut).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()}),ri=_({structured:n([r(),_({by:r(),map:t(r(),r()),fallback:r()}),f()]).optional(),streaming:_({mode:c(Ke).optional(),streamThoughts:m().optional()}).optional()}),ii=_(Pe(gt,()=>c(Re))),ai=_(Pe(vt,()=>ii)),oi=_({id:r(),label:r(),actions:ii,names:l(r()),find:m()}),si=_({hosts:l(r()),fromTools:m()}),ci=_({quota:_({perDay:s()}).optional(),detect:ai,patterns:a(c(vt),_({theorem:m(),names:l(r())})).optional(),host:l(oi).optional(),allow:_({ungiven_images:si,ungiven_links:si}),blockedReply:_({onBlock:c(nt),maxRetries:s()})}),li=n([m(),_({theorem:m(),host:m()})]),ui=_({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:li,injection:li,canary:li}),resource:Rt,retainForDays:s(),rotateAfterMiB:s(),hasOnWriteError:m()}),H=_({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(),slots:t(r(),_({label:r().optional(),choices:l(_({value:r(),description:r().optional()}))})).optional(),context:_({from:l(c(Ze)),maxChars:s()}).optional()}),di=_({allowContinue:l(c(We)).optional(),autoContinue:l(c(We)).optional(),maxContinues:s().optional()}),fi=_({resumption:di.optional()}),pi=_({allow:l(r()),page:l(r()),t2Loader:r().optional(),parallel:m().optional()}),U={providerContinuation:_({history:c([`host`,`stateless`,`provider`]).optional()}).optional(),id:r(),models:t(r(),ni),defaultModel:r(),allowModelSelect:m().optional(),maxSteps:s().optional(),labels:a(c(yt),r()),guardrails:ci.optional(),observability:ui.optional()},mi=n([r(),o({private:r().min(1)})]),hi=n([r(),l(n([r(),l(mi).readonly()])).min(1).readonly()]),gi=_({handle:r(),conditions:t(r(),l(r()).readonly()).readonly().optional(),system:hi.optional()}),W=d(`type`,[_({...U,type:g(`text`),identity:gi,outputs:ri.optional(),inputs:H,tools:pi,turnBehaviour:_({resumption:di.optional(),allowSteering:m().optional(),atStepLimit:c(_t).optional()}).optional(),canStop:g(!0),allowSteering:m()}),_({...U,type:g(`image`),identity:gi,outputs:ri.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:H,tools:pi,turnBehaviour:fi.optional(),canStop:g(!0)}),_({...U,type:g(`transcription`),identity:_({handle:r()}),maxSteps:h().optional(),outputs:ri.optional(),inputs:H,canStop:g(!0)}),_({...U,type:g(`speech`),identity:_({handle:r()}),outputs:ri.optional(),speech:_({voice:r().optional(),style:r().optional(),speed:s().optional(),format:c(Ue).optional()}),inputs:H,turnBehaviour:fi.optional(),canStop:g(!0)}),_({...U,type:g(`live`),identity:gi,inputs:H.pick({slots:!0,context:!0}).optional(),live:_({ingress:_({audio:m().optional(),video:m().optional(),text:m().optional()}).optional(),voice:r().optional(),vad:_({activityHandling:c(ft).optional(),startSensitivity:c(Xe).optional(),endSensitivity:c(Je).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:pi.pick({allow:!0,page:!0}),turnBehaviour:_({allowSteering:m().optional()}).optional()})]);function _i(e){let t=b(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:vi(t.allow.ungiven_images),ungiven_links:vi(t.allow.ungiven_links)},blockedReply:t.blockedReply}}function vi(e){return{hosts:[...e.hosts??[]],fromTools:e.fromTools??!0}}function yi(e){return e===void 0||e===!1||typeof e==`string`?e:`custom`}function bi(e){if(!e)return;let t=It(e);return{record:t.record,writeTo:yi(t.writeTo),sampleRate:t.sampleRate,include:t.include,scrub:t.scrub,resource:t.resource,retainForDays:t.retainForDays,rotateAfterMiB:t.rotateAfterMiB,hasOnWriteError:!!t.onWriteError}}function xi(e){let{greeting:t,resumed:n,...r}=e??{};return r}function Si(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=Et(t),r=Mt(t);return{allow:[...Ft(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 Ci({allow:e,page:t}){return{allow:e,page:t}}function wi(e,t){let n=Qr(e.inputs),r=t?.identity??{handle:e.handle},i=t?_i(t.guardrails):void 0,a=t?bi(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:fe(t?.labels)};switch(e.type){case`text`:return W.parse({...s,type:`text`,inputs:n,tools:Si(e,t),turnBehaviour:t?.type===`text`?t.turnBehaviour:void 0,canStop:!0,allowSteering:!t||te(t)});case`image`:return W.parse({...s,type:`image`,image:e.image??{},inputs:n,tools:Si(e,t),turnBehaviour:t?.type===`image`?t.turnBehaviour:void 0,canStop:!0});case`speech`:return W.parse({...s,type:`speech`,speech:e.speech??{},inputs:n,turnBehaviour:t?.type===`speech`?t.turnBehaviour:void 0,canStop:!0});case`transcription`:return W.parse({...s,type:`transcription`,inputs:n,canStop:!0});case`live`:return W.parse({...s,type:`live`,live:xi(e.live),...e.inputs?{inputs:{slots:n.slots,context:n.context}}:{},tools:Ci(Si(e,t))});default:return e.type}}function Ti(e,t){let n=Fr(e,`interfaceFromProfile`);return wi(Jr(t,n),n)}function Ei(e){return p(t=>E.safeParse(e(t)).success)}var Di=[`running`,`gate`,`background`,`complete`,`error`,`cancel`],Oi=p(e=>{let t=E.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 Di.some(e=>e===n)}),ki=t(r(),i()),Ai=_({operationId:r().optional(),name:r(),callId:r(),arguments:ki,draft:r().optional(),reasoning:l(S).optional(),stepId:r().optional(),edited:_({from:ki,to:ki}).optional(),activity:r().optional(),activityPast:r().optional(),outputDraft:r().optional(),state:Oi.optional(),startedAt:s().optional(),endedAt:s().optional(),artifacts:l(i()),get steps(){return l(Ai).optional()}}),ji=_({kind:c(tt),native:r().optional()}),G={id:r()},K=d(`kind`,[_({...G,kind:g(`user-text`),text:r()}),_({...G,kind:c([`user-attachment`,`user-voice`]),name:r(),mimeType:r(),sizeBytes:s(),data:r().optional()}),_({...G,kind:g(`thought`),text:r()}),_({...G,kind:g(`text`),text:r()}),_({...G,kind:g(`tool`),tool:Ai}),_({...G,kind:g(`structured`),value:i(),draft:r().optional()}),_({...G,kind:g(`media`),mimeType:r(),data:r().optional(),url:r().optional(),previewUrl:r().optional()}),_({...G,kind:g(`grounding`),grounding:Ei(e=>({type:`grounding`,grounding:e}))}),_({...G,kind:g(`citation`),sources:Ei(e=>({type:`citation`,sources:e})),callId:r().optional()}),_({...G,kind:g(`evidence`),evidence:Ei(e=>({type:`evidence`,evidence:e}))}),_({...G,kind:g(`guardrail`),guardrail:oe}),_({...G,kind:g(`late-results`),text:r()}),_({...G,kind:g(`error`),message:r()}),_({...G,kind:g(`turn-done`),stop:ji.optional(),tokens:Ei(e=>({type:`tokens`,tokens:e})).optional(),interactionId:r().optional(),compaction:m().optional(),workedMs:s().optional(),endedAt:s().optional()})]),Mi=_({type:r()});function Ni(e,t){return Object.hasOwn(e,t)}function Pi(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=>Pi(e,n)).join(` | `)}]`}).join(`; `)}function Fi(e){return Pi(e.issues,[])}function Ii(e,t){return new j(`bad_response`,`${e} failed its wire check: ${Fi(t)}`)}function q(e,t,n){let r=e.safeParse(t);if(!r.success)throw Ii(n,r.error);return r.data}function Li(e){return{type:`malformed`,error:new j(`bad_response`,e,{copy:{key:`session.part_skipped`}})}}function Ri(e,t){let n=Mi.safeParse(t);if(!n.success)return Li(`a line without a kind failed its wire check: ${Fi(n.error)}`);let{type:r}=n.data;if(!Ni(e,r))return{type:`unsupported`,received:r,raw:t};let i=e[r].safeParse(t);return i.success?i.data:Li(`a '${r}' line failed its wire check: ${Fi(i.error)}`)}function zi(e){try{return{value:JSON.parse(e)}}catch(e){if(e instanceof SyntaxError)return;throw e}}function Bi(e,t){let n=zi(t);return n?Ri(e,n.value):Li(`a line is not JSON`)}function Vi(e){let t=zi(e);if(!t)throw new j(`bad_response`,`a line is not JSON`);return t.value}var Hi=_({name:r(),mimeType:r(),data:r()}),Ui=_({slots:t(r(),r()).optional(),context:i().optional(),text:r().optional(),attachments:l(Hi).optional(),voice:l(Hi).optional()}),Wi=_({gateKind:c(pt).optional(),sessionPermissions:l(r()).optional(),name:r().optional(),input:i().optional(),snapshot:v.optional(),promoted:l(r()).optional(),model:r().optional(),effort:r().optional()}),J=r().trim().min(1),Gi=_({path:r().optional(),conditions:t(r(),r()).optional()}),Ki=Gi;_({input:Ui,conversation:r().min(1).optional(),model:r().optional(),effort:r().optional(),stated:Gi.optional(),turnId:J.optional(),abandon:l(x).min(1).optional(),replay:Wi.pick({sessionPermissions:!0}).optional(),transcript:l(K).optional()});var qi=[`approve`,`deny`],Ji=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:Ji.optional(),conversation:r().min(1).optional(),turnId:J.optional(),replay:Wi.optional()}),_({turnId:J,id:J,inject:l(D).min(1)}),_({turnId:J});var Yi=_({type:g(`conversation`),ref:r().min(1),posted:g(!0).optional()}),Xi={...w,conversation:Yi},Zi=_({transcript:l(K),paused:_({events:l(E),blocks:l(K)}).optional(),notify:_({retryMs:s().optional()}).optional()});_({conversation:r().min(1)}),o({});var Qi={changed:_({type:g(`changed`)})};_({conversation:r().min(1),at:s().int().min(-1)}),_({blocks:l(K)});var $i=_({conversation:r().min(1),view:Zi}),ea=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 ta(e){return e instanceof ea}function na(e){return e?.trim()||void 0}var ra=_({error:r().optional(),errorKind:ne.optional(),errorCopy:O.optional(),errorInternal:r().optional()}),ia=ra;function aa(e,t){let n=na(e.error),r=na(e.errorInternal);return new ea(e.errorKind??t,n,r&&r!==n?r:void 0,e.errorCopy)}function oa(e){return!ta(e)||e.copy===void 0?!1:(Array.isArray(e.copy)?e.copy:[e.copy]).some(e=>e.key===`session.conversation_unknown`)}function sa(e,t){let n=Bi(e,t);if(n.type===`error`)throw aa(ra.parse(n),`internal`);return n}function ca(e,t,n){let r=e.split(`
|
|
5
|
-
`),i=r.pop()??``;for(let e of r)e.trim()&&n(sa(t,e));return i}async function la(e,t,n,r){if(!e.body)throw new j(`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(;;){_e(r);let{done:e,value:s}=await i.read();if(e)break;o=ca(o+a.decode(s,{stream:!0}),t,n)}let e=o.trim();e&&n(sa(t,e))}finally{r?.removeEventListener(`abort`,s)}}async function ua(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 da(e,t){let n=await e.text(),r;try{r=JSON.parse(n),t?.(r)}catch{return aa({errorInternal:`HTTP ${String(e.status)}`},et(e.status))}let i=ra.safeParse(r);return i.success?aa({...i.data,errorInternal:i.data.errorInternal??`HTTP ${String(e.status)}`},et(e.status)):new j(`bad_response`,`HTTP ${String(e.status)} error body failed its wire check`)}async function fa(e,t,n){let r=n.fetch??globalThis.fetch.bind(globalThis);try{return await r(e,{...t,headers:await ua(n),credentials:n.credentials??`same-origin`})}catch(e){throw ue(e)?e:new j(`network`,me(e),{cause:e})}}async function pa(e,t,n,r,i={}){await la(await ma(e,t,i),n,r,i.signal)}async function ma(e,t,n){let r=await fa(e,{method:`POST`,body:JSON.stringify(t),signal:n.signal},n);if(!r.ok)throw await da(r);return r}async function ha(e,t,n={}){await ma(e,t,n)}async function Y(e,t,n={}){let r=await fa(e,{...t.body===void 0?{method:`GET`}:{method:`POST`,body:JSON.stringify(t.body)},signal:t.signal},n);if(!r.ok)throw await da(r,t.failed);return Vi(await r.text())}async function ga(e,t,n={}){let{signal:r,...i}=n;return q(Zi,await Y(e,{body:t,signal:r},i),`the conversation`)}async function _a(e,t,n,r){let{signal:i,...a}=n;return q($i,await Y(e,{body:t,signal:i},a),r)}function va(e,t,n={}){return _a(e,t,n,`the rewound conversation`)}function ya(e,t,n={}){return _a(e,t,n,`the started conversation`)}function ba(e){let t=e.length;for(;t>0&&e[t-1]===`/`;)--t;return e.slice(0,t)}var xa=_({interface:W});function Sa(e={}){let t=ba(e.endpoint??`/api/theorem`);return{async describe(n){let r=await fa(t,{method:`GET`,signal:n},e);if(!r.ok)throw await da(r);return q(xa,Vi(await r.text()),`the profile description`).interface},turn:({replay:n,...r},i,a)=>pa(`${t}/turn`,r,Xi,i,{...e,signal:a}),invoke:({replay:n,...r},i,a)=>pa(`${t}/invoke`,r,Xi,i,{...e,signal:a}),conversation:(n,r)=>ga(`${t}/conversation`,n,{...e,signal:r}),notify:(n,r)=>pa(`${t}/notify`,{},Qi,e=>{e.type===`changed`&&n()},{...e,signal:r}),rewind:(n,r)=>va(`${t}/rewind`,n,{...e,signal:r}),pageResult:(n,r)=>ha(`${t}/page-result`,n,{...e,signal:r}),steer:n=>ha(`${t}/steer`,n,e),stop:n=>ha(`${t}/stop`,n,e)}}function Ca(e,t){if(typeof e==`string`)return e;let n=Array.isArray(e)?e:Object.keys(e);return n.length?Ca(n[0],t):t}function wa(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)=>Ca(e,String(t))):[],...t.type===`box`&&t.image!==void 0?{image:t.image}:{}}))}function Ta(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:wa(t),...n&&Object.keys(n).length>0?{images:n}:{},...e.observability?{observability:{record:It(e.observability).record}}:{}}}function Ea(e,t){let n=Object.keys(t??{}).find(t=>e&&Object.hasOwn(e,t));if(n!==void 0)throw new j(`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 X=s().min(0).max(1),Da=t(r(),X),Oa=d(`type`,[_({type:g(`choice`),choice:r(),confidence:X,probabilities:Da}),_({type:g(`noul`),noul:X}),_({type:g(`box`),box:_({top:X,bottom:X,left:X,right:X}),confidence:X}),_({type:g(`score`),score:s().nonnegative(),confidence:X,legend:t(r(),r().min(1)),probabilities:Da})]),ka=_({id:r(),type:c([`choice`,`noul`,`score`,`box`]),labels:l(r()),image:r().optional()}),Aa=_({result:_({model:r().min(1),questions:l(ka).optional(),answers:t(r(),Oa),usage:_({inputTokens:s().int().nonnegative(),outputTokens:s().int().nonnegative(),costUsd:s().nonnegative().optional()}).optional()}),traces:l(Lt).optional()}),ja=new WeakMap;function Ma(e,t){return t.length>0&&typeof e==`object`&&e&&ja.set(e,t),e}function Na(e){return typeof e==`object`&&!!e&&ja.get(e)||[]}var Pa=_({traces:l(Lt)});async function Fa(e,t,n,r,i){let a=[],o=e=>{let t=Pa.safeParse(e);t.success&&(a=t.data.traces)};try{return i(await Y(e,{body:t,signal:n,failed:o},r))}catch(e){throw Ma(e,a)}}function Ia(e,t,n,r={}){return Fa(e,t,n,r,La)}function La(e){return q(Aa,e,`the decision`)}var Ra=_({interface:_({type:g(`decision`),identity:_({handle:r()}),contract:r(),maxStateBytes:s().optional(),questions:l(ka),build:_({input:t(r(),i()).optional()}).optional(),images:t(r(),_({mimeType:c([`image/png`,`image/jpeg`]),data:r()})).optional(),observability:_({record:m()}).optional()})});function za(e={}){let t=(e.endpoint??`/api/decision`).replace(/\/$/,``);return{async describe(n){return q(Ra,await Y(t,{signal:n},e),`the decision description`).interface},decide:(n,r,i,a)=>Ia(`${t}/decide`,{state:n,...i?{assets:i}:{},...a===void 0?{}:{input:a}},r,e)}}function Ba(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Z(e,t){let n=e[t];return typeof n==`string`&&n.trim()?n.trim():void 0}function Q(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 Va(e){let t=new Set;return e.filter(e=>!t.has(e.uri)&&(t.add(e.uri),!0))}function Ha(e){let t=[...e.matchAll(/\[([^\]]+)\]\((https?:\/\/[^)\s]+)\)/g)].flatMap(e=>Q(e[1]??``,e[2]??``)??[]),n=[...e.matchAll(/https?:\/\/[^\s"'<>\]]+/g)].flatMap(e=>{let t=(e[0]??``).replace(/[),.;:]+$/,``);return Q(t,t)??[]});return Va([...t,...n])}function Ua(e){if(Array.isArray(e))return e;if(!Ba(e))return[];for(let t of[`items`,`results`,`search_results`,`models`,`datasets`]){let n=e[t];if(Array.isArray(n))return n}return[]}function Wa(e,t){return Va(e.flatMap(e=>Ba(e)?t(e)??[]:[]))}function Ga(e,t){let n=t===`dataset`?`https://huggingface.co/datasets/`:`https://huggingface.co/`;return Wa(Ua(e),e=>{let t=Z(e,`id`)??Z(e,`modelId`);return t?Q(t,`${n}${t}`):void 0})}function Ka(e){return Wa(Ua(e),e=>{let t=Z(e,`html_url`),n=Z(e,`full_name`)??Z(e,`name`);return t?Q(n??t,t):void 0})}function qa(e){let t=e,n;do n=t,t=t.replace(/<[^>]+>/g,``);while(t!==n);return t.replace(/\s+/g,` `).trim()}function Ja(e){if(typeof e!=`string`)return Ha(JSON.stringify(e));let t=[...e.matchAll(/<entry\b[\s\S]*?<\/entry>/g)];return t.length===0?Ha(e):Va(t.flatMap(e=>{let t=/<id>(https?:\/\/[^<]+)<\/id>/.exec(e[0]??``)?.[1],n=/<title>([\s\S]*?)<\/title>/.exec(e[0]??``)?.[1];return t?Q(qa(n??t),t)??[]:[]}))}function $(e){if(typeof e==`string`)return Ha(e);if(Array.isArray(e)||Ba(e)){let t=Wa(Ua(e),e=>{let t=Z(e,`html_url`)??Z(e,`url`)??Z(e,`source_url`)??Z(e,`contentUrl`),n=Z(e,`title`)??Z(e,`name`)??t;return t?Q(n??t,t):void 0});return t.length>0?t:Ha(JSON.stringify(e))}return[]}var Ya={search_models:e=>Ga(e,`model`),search_datasets:e=>Ga(e,`dataset`),search_github:Ka,list_arxiv:Ja,search_web:$,read_pages:$,read_model_card:$,read_dataset_card:$,read_readme:$,find_library:$,read_library_docs:$,ask_repo_docs:$};function Xa(e){return Ya[e]}function Za(e,t){let n=Xa(e);return n?{...t,sources:n}:t}function Qa(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:ae(t.inputSchema),output:ae(t.outputSchema)};if(t.type===`http`){e.register(Za(t.name,{...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(Za(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??zt(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 $a(e,t,n){e.registerMany([...ee,...T]);for(let r of t)Qa(e,r,n)}function eo(e,t,n,r,i){if($a(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 to(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 no(e){if(e.type!==`error`&&e.type!==`session`&&e.type!==`tool`||e.errorInternal===void 0)return e;let{errorInternal:t,...n}=e;return n}function ro(e){if(e.type!==`compaction`||e.failure?.errorInternal===void 0)return e;let{errorInternal:t,...n}=e.failure;return{...e,failure:n}}function io(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 ao(e){if(e.type!==`done`||e.mediaRefused===void 0)return e;let{mediaRefused:t,...n}=e;return n}function oo(e){if(e.type!==`evidence`||!e.evidence?.raw)return e;let{raw:t,...n}=e.evidence;return{...e,evidence:n}}function so(e,t){let n=t?.reader===`builder`?to(e):ao(ro(io(no(e))));return t?.includeEvidenceRaw||(n=oo(n)),n=Ht(n,!1),n}function co(e,t){return e.map(e=>so(e,t))}function lo(e,t,n){let{error:r=``,errorKind:i,errorCopy:a}=so(Oe(Ce(e),t),n);return{error:r,errorKind:i,...a?{errorCopy:a}:{}}}var uo={reader:`builder`};function fo(e){return e.mode===`demo`?{reader:`visitor`}:uo}export{Xn as $,Fi as A,jr as B,ia as C,pa as D,ha as E,ti as F,rr as G,Dr as H,ei as I,$n as J,ir as K,Ir as L,Ri as M,K as N,Ki as O,Ti as P,Zn as Q,Yr as R,aa as S,oa as T,lr as U,kr as V,nr as W,Wn as X,Yn as Y,Jn as Z,Sa as _,co as a,Pn as at,va as b,za as c,Vt as ct,Na as d,zn as et,Ia as f,ea as g,Xi as h,so as i,V as it,Bi as j,q as k,Ea as l,Bt as lt,Ma as m,fo as n,In as nt,eo as o,Nn as ot,Fa as p,tr as q,lo as r,Ln as rt,$a as s,Gt as st,uo as t,Rn as tt,Ta as u,Ht as ut,ga as v,ta as w,ya as x,Y as y,Kr as z};
|
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
import{A as e,D as t,E as n,O as r,T as i,b as a,c as o,d as s,f as c,x as l}from"./schemas-D7cgkv3L.js";import{Dt as u,Gn as d,Gt as f,Tt as ee,Un as te,qn as ne,wt as re}from"./tool-schema-BwaPiLtT.js";import{c as p}from"./host-patterns-F-KZIzkF.js";import{A as m}from"./shaped-data-DCfLI4gb.js";var h=`
|
|
2
|
-
|
|
3
|
-
`;function g(e){if(typeof e==`string`)return;if(typeof e!=`object`||!e||Array.isArray(e))return`must be a string or { private: string }`;let t=Object.keys(e);if(t.length!==1||t[0]!==`private`)return`must have exactly one key, private`;let n=e.private;if(typeof n!=`string`)return`must be a string`;if(n===``)return`must not be empty`}function _(e,t){if(typeof e!=`string`){if(!Array.isArray(e))return`${t} must be a string or an array of parts`;if(e.length===0)return`${t} must not be an empty array`;for(let[n,r]of e.entries()){let e=g(r);if(e)return`${t}[${n}]${typeof r==`object`&&r&&`private`in r?`.private`:``} ${e}`}}}function v(e,t){let n=_(e,t);if(n)throw new p(`config`,n)}function ie(e,t,n){return v(e,t),typeof e==`string`?n(e):e.map(e=>typeof e==`string`?n(e):{private:n(e.private)})}function ae(e){if(typeof e==`string`)return[{text:e,private:!0}];let t=e.some(e=>typeof e!=`string`);return e.map(e=>typeof e==`string`?{text:e,private:!t}:{text:e.private,private:!0})}function y(e){let t=[];for(let n of e)n.some(e=>e.text)&&(t.length>0&&t.push({text:h,private:!0}),t.push(...n));return t}function oe(e){return e.map(e=>e.text).join(``)}function se(e){let t=[],n=``;for(let r of e)r.private?n+=r.text:(n.trim()&&t.push(n),n=``);return n.trim()&&t.push(n),{text:oe(e),private:t}}function ce(e,t){return se(y([e,...t.map(e=>e?[{text:e,private:!0}]:[])]))}var le=/^[A-Za-z_][\w-]*$/,ue=/^\S+$/;function b(e){return typeof e==`string`?[[e]]:e.map(e=>typeof e==`string`?[e]:e)}function x(e){return typeof e==`string`?e:e.private}function S(e){return u(e[0]===void 0?``:x(e[0]))}function de(e,t){let n={};for(let[r,i]of Object.entries({...e,...t}))n[r]={type:`string`,enum:[...i]};return{type:`object`,properties:n}}function fe(e,t){for(let[n,r]of Object.entries(e??{})){if(!le.test(n))return`Condition "${n}" needs a plain name.`;if(n===`input`||n===`output`)return`Condition "${n}" is a reserved name.`;if(Object.hasOwn(t,n))return`"${n}" is both a condition and a slot.`;if(r.length===0)return`Condition "${n}" lists no values.`;let e=r.find(e=>!ue.test(e)||e===`null`);if(e!==void 0)return`Condition "${n}" can't take the value "${e}".`}}function C(e,t){if(e.length===0)return`It has no wording to send.`;let n=S(e);if(n.joined)return`A prompt line can't start with "+"; every line that fits is sent.`;if(n.when===`unreadable`)return`A line that opens with "when" needs a condition and a colon, like "when path is web: …".`;for(let e of n.when){if(e.path.includes(`.`))return`"${e.path}" isn't one condition or slot.`;if(e.expected===null)return`A condition always has a value, so "is null" never fits.`;let n=ee(e,t,`this profile’s conditions or slots`);if(n)return n}if(n.when.length>0&&!n.text&&e.length===1)return`It has no wording to send.`}function w(e,t,n){let r=fe(t,n);if(r)return r;let i=de(t,n);for(let[t,n]of b(e).entries()){let e=C(n,i);if(e)return`Line ${t+1}: ${e}`}}function T(e,t,n,r){let i=n.conditions??{};if(t===void 0){if(n.conditions)throw new p(`request`,`Profile ${e} declares no conditions`);return{...r}}if(Object.hasOwn(i,`path`))throw new p(`request`,`Profile ${e}: the turn's own path states path`);for(let n of Object.keys(i))if(!Object.hasOwn(t,n))throw new p(`request`,`Profile ${e} has no condition '${n}'`);let a={...r};for(let[r,o]of Object.entries(t)){let t=r===`path`?n.path:i[r];if(t===void 0)throw new p(`request`,`Profile ${e}: the turn left condition '${r}' unset`);if(!o.includes(t))throw new p(`request`,`Profile ${e}: '${t}' is no value of condition '${r}'`);a[r]=t}return a}function E(e,t){return e.when!==`unreadable`&&e.when.every(e=>re(e,t))}function D(e,t,n){let r=b(e),i=r.flat().some(e=>typeof e!=`string`),a=[];for(let[e,o]of r.entries()){let r=S(o);if(!E(r,t))continue;let s=[];for(let[e,t]of o.entries()){let a=n(e===0?r.text:x(t));a&&s.push({text:a,private:typeof t!=`string`||!i})}a.push({line:e+1,pieces:s})}return a}function O(e,t){if(typeof e!=`string`){if(!Array.isArray(e))throw new p(`config`,`${t} must be a string or an array of lines`);if(e.length===0)throw new p(`config`,`${t} must not be an empty array`);for(let[n,r]of e.entries())if(typeof r!=`string`){if(!Array.isArray(r))throw new p(`config`,`${t}[${n}] must be a string or a list of parts; put { private } inside the list`);v(r,`${t}[${n}]`)}}}function k(e,t){let n=e?.path;if(n)for(let e of t){let t=e.paths?.find(e=>e!==`*`&&!n.includes(e));if(t!==void 0)return`Tool ${e.name} lists path "${t}", which is not one of ${n.join(`, `)}.`}}function A(e,t){let n=e.get(t);return n!==void 0&&n.type!==`builtin`}function j(e,t){return!e||e.includes(`*`)?!0:t?e.includes(t):!1}function M(e,t){return t.filter(n=>{let r=e.get(n);return r?.type!==`builtin`||!(r.conflictsWith??[]).some(e=>t.includes(e))})}function N(e){return`tools`in e?e.tools.allow:[]}function P(e){return e.type===`text`||e.type===`image`?e.tools:void 0}function F(e){return`tools`in e?e.tools.parallel:void 0}function I(e,t,n){return N(t).filter(r=>{let i=e.get(r);return!i||i.type===`builtin`?!1:t.type===`host`||j(i.paths,n.path)})}function L(e,t,n,r){let i=t.models[r];return i?(i.builtInTools??[]).filter(t=>{let r=e.get(t);return r?.type===`builtin`&&j(r.paths,n.path)}):[]}function R(e,t,n){let r=e.get(t);if(r&&r.type!==`builtin`)return{type:`function`,name:r.name,description:r.description,parameters:n&&r.askInputSchema||r.inputSchema}}function z(e,t,n){let r=[];for(let i of t){let t=R(e,i,n);t&&r.push(t)}return r}function B(e,t,n){if(t.visible.includes(n))return;t.visible.push(n);let r=R(e,n,t.modelBackground);r&&!t.wire.some(e=>e.name===n)&&t.wire.push(r)}function V(e,t,n){if(t.builtins.includes(n))return;let r=e.get(n);if(r?.type!==`builtin`)return;let i=r.conflictsWith??[];t.builtins=t.builtins.filter(t=>{if(i.includes(t))return!1;let r=e.get(t);return!(r?.type===`builtin`&&r.conflictsWith?.includes(n))}),t.builtins.push(n)}function pe(e,t,n){return t.type===`live`||t.type===`host`?[...n]:n.filter(t=>e.get(t)?.loadTier===`T0`)}function me(e,t,n){return M(e,n.filter(n=>{let r=e.get(n);return r?.type===`builtin`&&(t.type===`live`||r.loadTier===`T0`)}))}function he(e,t){if(t.type!==`text`&&t.type!==`image`&&t.type!==`live`)return;let n=N(t).flatMap(t=>e.get(t)??[]),r=k(t.identity.conditions,n);if(r)throw new p(`config`,`Profile ${t.id}: ${r}`)}function ge(e,t){let n=P(t)?.t2Loader,r=n===void 0?void 0:e.get(n);if(r&&r.type!==`builtin`&&(r.background??`never`)!==`never`)throw new p(`config`,`Profile ${t.id}: tools.t2Loader '${r.name}' sets background, and a loader cannot detach`)}function H(e,t,n,r){he(e,t),ge(e,t);let i=I(e,t,n),a=t.type===`host`||t.type===`decision`||t.type===`embedding`||r===void 0?[]:L(e,t,n,r),o=[...i,...a],s=me(e,t,o),c=pe(e,t,o),l=c.filter(t=>A(e,t)),u=n.background!==void 0;return{builtins:s,gated:o,visible:c,executable:l,path:n.path,sessionPermissions:n.sessionPermissions,wire:z(e,c,u),...u?{modelBackground:u}:{}}}async function _e(e,t,n,r){let i=H(e,t,n,r);return await U(e,i,t,n),i}function ve(e){return{builtins:[...e.builtins],gated:[...e.gated],visible:[...e.visible],executable:[...e.executable],path:e.path,sessionPermissions:e.sessionPermissions?[...e.sessionPermissions]:void 0,wire:e.wire.map(e=>({...e,parameters:structuredClone(e.parameters)})),...e.modelBackground?{modelBackground:e.modelBackground}:{}}}async function U(e,t,n,r){let i=P(n)?.t1Policy;if(!i)return;let a;try{a=await i({profile:n,input:r.input,path:r.path,sessionPermissions:r.sessionPermissions,gated:t.gated,host:r.host})}catch(e){let t=e instanceof Error?e.message:String(e);throw new p(`config`,`Profile '${n.id}' tools.t1Policy rejected: ${t}`,{cause:e})}if(!Array.isArray(a))throw new p(`config`,`Profile '${n.id}' tools.t1Policy must return ToolId[]`);W(e,t,a)}function W(e,t,n=[]){for(let r of n){if(!t.gated.includes(r))continue;let n=e.get(r);n?.loadTier===`T2`&&(n.type===`builtin`?V(e,t,r):B(e,t,r))}t.executable=t.visible.filter(t=>A(e,t))}var ye=new Set([`__proto__`,`constructor`,`prototype`]);function be(e){if(!m(e))return;let{loaded:t}=e;if(Array.isArray(t)&&t.every(e=>typeof e==`string`))return t}function xe(e,t,n,r){if(r.type===`live`||r.type===`host`)return{promoted:[]};let i=[];for(let a of n){if(typeof a!=`string`||ye.has(a))return{promoted:[],failure:{code:`invalid_output`,kind:`bad_response`,message:`tools.t2Loader loaded ids must be plain strings`}};let n=Se(e,a,r);if(`failure`in n)return{promoted:[],failure:n.failure};let{tool:o}=n;j(o.paths,t.path)&&t.gated.includes(a)&&i.push(a)}let a=[];for(let n of i)B(e,t,n),a.push(n);return t.executable=t.visible.filter(t=>A(e,t)),{promoted:a}}function G(e){return{failure:{code:`invalid_output`,kind:`bad_response`,message:e}}}function Se(e,t,n){if(!N(n).includes(t))return G(`tools.t2Loader attempted to promote tool '${t}' outside profile allow`);let r=e.get(t);return r?r.type===`builtin`?G(`tools.t2Loader attempted to promote builtin '${t}' — only custom tools may be promoted`):r.loadTier===`T2`?{tool:r}:G(`tools.t2Loader attempted to promote tool '${t}' with loadTier '${r.loadTier}' — only T2 tools may be promoted`):G(`tools.t2Loader attempted to promote unknown tool '${t}'`)}function K(e){return Array.isArray(e)?[...e]:e.choices.map(e=>e.value)}function Ce(e){return Array.isArray(e)?{choices:e.map(e=>({value:e}))}:{...e.label!==void 0&&e.label!==``?{label:e.label}:{},choices:e.choices.map(e=>({value:e.value,...e.description!==void 0&&e.description!==``?{description:e.description}:{}}))}}function q(e){if(e)return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,Ce(t)]))}function we(e){return e?.slots?{...e,slots:q(e.slots)}:e}var Te=class extends Error{failure;constructor(e){super(e.message),this.failure=e}},Ee=new Set([`text`,`image`,`speech`]),De=n().regex(/\S/),J=i({mimeType:n(),data:c(),name:n().optional()}),Oe=i({mimeType:n(),uri:n(),name:n().optional()}),ke=i({voice:n().optional(),style:n().optional(),speed:a().positive().optional()});function Ae(e){return i(Object.fromEntries(Object.entries(e).map(([e,t])=>{let n=K(t);return[e,o(n).optional()]})))}var je=new Set([`text`,`attachments`,`voice`,`slots`,`speech`]);function Me(e,t){if(!e.hostFields)return{sent:t};let n={...t},r={};for(let t of Object.keys(e.hostFields))n[t]!==void 0&&(r[t]=n[t]);let{text:i,attachments:a,voice:o,slots:s,speech:c}=t;return{sent:{text:i,...a?{attachments:a}:{},...o?{voice:o}:{},...s?{slots:s}:{},...c?{speech:c}:{}},hostInput:r}}function Ne(e,n){let{inputs:r}=e,a={text:De};r?.attachments&&(a.attachments=s(t([J,Oe])).optional()),r?.voice&&(a.voice=s(J).optional()),r?.slots&&(a.slots=Ae(r.slots).optional()),e.type===`speech`&&(a.speech=ke.optional());for(let e of n?.hostOnly??[]){if(!a[e])throw new p(`config`,`Tool '${n?.name}' keeps '${e}' for the host, which its profile does not take`);delete a[e]}for(let[e,t]of Object.entries(n?.fieldText??{})){let r=a[e];if(!r)throw new p(`config`,`Tool '${n?.name}' describes '${e}', which its profile does not take`);a[e]=r.describe(t)}for(let[e,t]of Object.entries(n?.hostFields??{})){if(je.has(e))throw new p(`config`,`Tool '${n?.name}' declares the host field '${e}', which is a field of every agent tool`);a[e]=t}return i(a)}var Y=l({text:n().optional(),structured:r().optional(),removed:s(l({path:n(),reason:n(),item:r()})).optional(),parts:s(te).optional(),sources:s(ne).optional()});function Pe(e){return e.type===`speech`||(e.type===`text`||e.type===`image`)&&e.inputs.text!==!1}function Fe(e){return e.type===`builtin`?!1:e.permission!==`auto`||`auth`in e&&e.auth!==void 0&&(e.auth.onUnauthenticated??`gate`)===`gate`}function X(e,t){if(!Ee.has(e.type))return`it is a ${e.type} profile; an agent tool runs a text, image, or speech profile`;if(!Pe(e))return`it does not take text`;for(let n of N(e)){let e=t(n);if(!e)return`its tool '${n}' is not registered; register it first`;if(Fe(e))return`its tool '${n}' can stop on a gate; give it permission 'auto' and no sign-in`}}function Ie(e,t,n){let r=`Agent tool "${e.name}"`,i=e.maxCallsPerTurn;if(i!==void 0&&!(Number.isInteger(i)&&i>0))throw new p(`config`,`${r}: maxCallsPerTurn must be a whole number above 0`);let a=t(e.profile);if(!a)throw new p(`config`,`${r}: profile '${e.profile}' must be registered before the tool`);let o=X(a,n);if(o)throw new p(`config`,`${r} can't run '${e.profile}': ${o}`);return a}function Z(e){if(!e)return`delegated`;let t=`models`in e&&Object.values(e.models).some(e=>(e.builtInTools?.length??0)>0);return N(e).length===0&&!t?`local`:`delegated`}function Le(e){let t=d(e),n=t.flatMap(e=>e.type===`text`?[e.text]:[]).join(``),r=f(t,e=>e.type===`structured`),i=r?.structured,a=t.flatMap(e=>e.type===`media`?[{type:e.media.mimeType.startsWith(`audio/`)?`audio`:`image`,mimeType:e.media.mimeType,data:e.media.data}]:[]),o=t.flatMap(e=>e.type===`citation`?e.sources:[]);return{...i===void 0?{text:n}:{structured:i},...r?.removed?.length?{removed:r.removed}:{},...a.length>0?{parts:a}:{},...o.length>0?{sources:o}:{}}}function Re(e,t,n){return{...e,type:`agent`,input:t,output:Y,sources:e=>e.sources??[],...n}}function ze(e,t,n){if(!e||typeof e!=`object`||Array.isArray(e))return n.push(`${t}: schema must be an object`),!1;let r=typeof e.type==`string`||Array.isArray(e.type),i=e.anyOf!==void 0||e.oneOf!==void 0;if(!r&&!i){if(t!==`$`)return!0;n.push(`${t}: missing type or combinator`)}return e.type===`array`&&e.items===void 0&&n.push(`${t}: array schema must define items`),!0}function Be(e,t,n,r){let i=Array.isArray(t)?t:[];for(let t of i)typeof t==`string`&&!Object.hasOwn(e,t)&&r.push(`${n}: required key '${t}' missing from properties`);for(let[t,i]of Object.entries(e))i&&typeof i==`object`&&Q(i,`${n}.properties.${t}`,r)}function Q(e,t,n){if(!ze(e,t,n))return;let r=e.properties;r&&typeof r==`object`&&!Array.isArray(r)&&Be(r,e.required,t,n),e.items&&typeof e.items==`object`&&!Array.isArray(e.items)&&Q(e.items,`${t}.items`,n);for(let r of[`anyOf`,`oneOf`]){let i=e[r];Array.isArray(i)&&i.forEach((e,i)=>{e&&typeof e==`object`&&Q(e,`${t}.${r}[${i}]`,n)})}}function Ve(e,t){let n=[];if(Q(e,`$`,n),n.length>0)throw new p(`config`,`Invalid tool ${t} schema: ${n.join(`; `)}`)}function He(t,n=`output`){let r=e(t,{target:`draft-7`,io:n});return delete r.$schema,r.type||=`object`,r}function $(e){if(typeof e!=`object`||!e)return e;if(Array.isArray(e))return e.map($);let t={};for(let n of Object.keys(e))n!==`__proto__`&&n!==`constructor`&&n!==`prototype`&&(t[n]=$(e[n]));return t}function Ue(e){let t=/^[a-z][a-z0-9+.-]*:\/\/[^/?#]*/i.exec(e)?.[0];if(!t||/[{}]/.test(t))throw new p(`config`,`Endpoint "${e}" must start with a fixed scheme and host; placeholders belong in the path or query`)}export{T as A,P as C,O as D,H as E,y as M,ie as N,D as O,ae as P,F as S,W as T,ve as _,Te as a,_e as b,Z as c,Ie as d,Re as f,K as g,q as h,Ve as i,ce as j,w as k,Y as l,we as m,He as n,X as o,Me as p,$ as r,Ne as s,Ue as t,Le as u,U as v,xe as w,N as x,be as y};
|
|
@@ -1,10 +0,0 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/studio-monaco-xfyfezQS.js","assets/editor.api-Cd3ViPQa.js","assets/preload-helper-DpV6A1kQ.js","assets/editor-DjpsE8to.css","assets/studio-monaco-CbKf90i6.css","assets/register-CDgivxvX.js","assets/studio-type-checker-JZuu4iVI.js"])))=>i.map(i=>d[i]);
|
|
2
|
-
import{r as e}from"./rolldown-runtime-hePW80VL.js";import{c as t,u as n}from"./themeProps-3IqahpCr.js";import{t as r}from"./preload-helper-DpV6A1kQ.js";import{D as i,Jt as a,T as o,Yt as s,k as c}from"./tool-schema-BwaPiLtT.js";import{c as l}from"./host-patterns-F-KZIzkF.js";import{$n as u,Nn as d,Tr as f,in as p,xr as m,zn as h}from"./shaped-data-DCfLI4gb.js";import{X as g,b as ee,g as _,h as v,m as te,w as y,x as b,y as x}from"./tree-CL4ETBd5.js";import{r as S}from"./live-ingress-OuSlQ6q7.js";import{t as ne}from"./registry-DP0ArymS.js";import{i as C,n as re,r as ie,t as ae}from"./types-BDx4pnrt.js";import{n as oe}from"./stub-REBz-ZC7.js";import{I as w,M as se,k as ce,r as le}from"./workspace-B6d08n7C.js";import{E as ue,Tt as de}from"./index-DuTrjzLN.js";var T=class extends Error{line;column;constructor(e,t,n){super(e),this.line=t,this.column=n}},fe=class{text;of;i=0;line=1;column=1;constructor(e,t=`profile`){this.text=e,this.of=t}get done(){return this.i>=this.text.length}pos(){return{line:this.line,column:this.column}}fail(e){throw new T(e,this.line,this.column)}peek(e=0){return this.text[this.i+e]??``}bump(){let e=this.text[this.i]??``;return this.i+=1,e===`
|
|
3
|
-
`?(this.line+=1,this.column=1):this.column+=1,e}skip(){for(;;){let e=this.peek();if(e===` `||e===` `||e===`
|
|
4
|
-
`||e===`\r`||e===``)this.bump();else if(e===`/`&&this.peek(1)===`/`)for(;!this.done&&this.peek()!==`
|
|
5
|
-
`;)this.bump();else if(e===`/`&&this.peek(1)===`*`){for(this.bump(),this.bump();!this.done&&(this.peek()!==`*`||this.peek(1)!==`/`);)this.bump();this.done&&this.fail(`This comment never closes.`),this.bump(),this.bump()}else return}}starts(e){return this.skip(),this.text.startsWith(e,this.i)}eat(e){if(!this.starts(e))return!1;for(let t=0;t<e.length;t+=1)this.bump();return!0}expect(e){this.eat(e)||this.fail(`Expected '${e}'.`)}ident(){this.skip();let e=this.peek();if(!/^[A-Za-z_$]/.test(e))return;let t=``;for(;/^[A-Za-z0-9_$]/.test(this.peek());)t+=this.bump();return t}expectIdent(){let e=this.ident();return e===void 0&&this.fail(`Expected a name.`),e}peekIdent(){return this.skip(),/^[A-Za-z_$][A-Za-z0-9_$]*/.exec(this.text.slice(this.i))?.[0]}rest(){return this.skip(),this.text.slice(this.i)}};function E(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function D(e){e.skip();let t=e.peek();t!==`'`&&t!==`"`&&e.fail(`Expected a string.`),e.bump();let n=``;for(;!e.done&&e.peek()!==t;){let t=e.bump();if(t!==`\\`){n+=t;continue}let r=e.bump(),i={n:`
|
|
6
|
-
`,r:`\r`,t:` `,"\\":`\\`,"'":`'`,'"':`"`};if(r in i)n+=i[r];else if(r===`u`){let t=``;for(let n=0;n<4;n+=1)t+=e.bump();n+=String.fromCharCode(Number.parseInt(t,16))}else n+=r}return e.peek()!==t&&e.fail(`This string never closes.`),e.bump(),n}function pe(e){e.skip();let t=e.pos(),n=``;for(e.peek()===`-`&&(n+=e.bump());/^[0-9.eE+-]/.test(e.peek())&&n.length<64;)n+=e.bump();let r=Number(n);if(!Number.isFinite(r))throw new T(`'${n}' is not a number.`,t.line,t.column);return r}function me(e,t,n,r){let i=0;for(;!e.done;){if(r()&&i===0)return;let a=e.peek();a===`'`||a===`"`?D(e):(a!==``&&t.includes(a)?i+=1:a!==``&&n.includes(a)&&--i,e.bump())}}function he(e){me(e,`<([{`,`>)]}`,()=>(e.skip(),e.peek()===`;`||e.peek()===`
|
|
7
|
-
`))}function ge(e){me(e,`{([`,`})]`,()=>e.peek()===`;`),e.peek()===`;`&&e.bump()}function _e(e,t,n){e.expect(`{`);let r={};for(;!e.eat(`}`);){e.eat(`...`)&&e.fail(`This file doesn't use spreads.`);let i=e.pos(),a;if(a=e.peek()===`'`||e.peek()===`"`?D(e):e.expectIdent(),a===`__proto__`)throw new T(`'__proto__' sets what an object inherits, not a setting.`,i.line,i.column);if(Object.hasOwn(r,a))throw new T(`'${a}' is set twice.`,i.line,i.column);let o=t?`${t}.${a}`:a;n.push({path:o,line:i.line,column:i.column}),e.expect(`:`),r[a]=P(e,o,n),e.eat(`,`),e.done&&e.fail(`This object never closes.`)}return r}function ve(e,t,n){e.expect(`[`);let r=[],i=0;for(;!e.eat(`]`);){e.eat(`...`)&&e.fail(`This file doesn't use spreads.`),e.skip();let a=e.pos(),o=t?`${t}.${String(i)}`:String(i);n.push({path:o,line:a.line,column:a.column}),r.push(P(e,o,n)),i+=1,e.eat(`,`),e.done&&e.fail(`This array never closes.`)}return r}function ye(e,t,n){let[r]=t;return e!==`z.fromJSONSchema`&&n.fail(`The studio reads a schema as JSON Schema: z.fromJSONSchema({ ... }), not '${e}'.`),E(r)||n.fail(`z.fromJSONSchema() needs a schema.`),r}function O(e){return E(e)&&e.kind===`member`}function be(e,t){return{kind:`member`,object:e,name:t}}function k(e){if(typeof e.object==`string`)return`${e.object}.${e.name}`;if(O(e.object)){let t=k(e.object);return t?`${t}.${e.name}`:void 0}}function A(e,t,n){let r=e[0];return E(r)||t.fail(n),r}function xe(e,t){try{ne({...e,name:I(e.name)})}catch(e){if(!(e instanceof l))throw e;let n=t.filter(t=>RegExp(`\\b${t.path}\\b`).test(e.message)).sort((e,t)=>t.path.length-e.path.length)[0]??t[0]??{line:1,column:1};throw new T(e.message,n.line,n.column)}}function Se(e,t,n){let r=A(e,t,`registerTool() needs the tool object.`),i=r.type,a=typeof i==`string`&&ae.includes(i);if(i!==void 0&&!a){let e=n.findLast(e=>e.path===`type`)??t.pos();throw new T(re,e.line,e.column)}return xe(r,n),{kind:`registerTool`,tool:r}}function Ce(e,t,n,r){if(n.of===`provider`){if(e!==`registerProvider`)return n.fail(`'${e}' isn't part of a provider's code.`);let[r,i={}]=t;return typeof r!=`string`&&n.fail(`registerProvider() needs the definition it registers from.`),(!E(i)||t.length>2)&&n.fail(`registerProvider() takes the definition and its settings.`),{kind:`provider`,definition:r,spec:i}}return e===`compileDetect`?A(t,n,`compileDetect() needs the detect object.`):e===`defineProfile`?A(t,n,`defineProfile() needs the profile object.`):e===`registerTool`?Se(t,n,r):e===`registerStructured`?{kind:`registerStructured`,args:t}:e===`registerProfile`||e===`registerProvider`?{kind:e}:n.fail(`'${e}' isn't part of this file.`)}function we(e,t,n){return(typeof t!=`string`||e.some(e=>typeof e!=`string`))&&n.fail(`.join() here joins lines of one string.`),e.join(t)}function Te(e,t,n){if(e.name===`join`&&Array.isArray(e.object))return we(e.object,t[0],n);if(e.name===`resolve`&&e.object===`Promise`)return t[0];let r=k(e);return r?.startsWith(`z.`)?ye(r,t,n):n.fail(`This call isn't part of this file.`)}function Ee(e,t,n,r){return typeof e==`string`?Ce(e,t,n,r):(O(e)||n.fail(`This call isn't part of this file.`),Te(e,t,n))}function De(e){return/^(async\s*)?\(\s*\)\s*=>/.test(e.rest())}function Oe(e,t,n){return e.peekIdent()===`async`&&e.expectIdent(),e.expect(`(`),e.eat(`)`)||e.fail(`A handler here takes no arguments. It returns a fixed value.`),e.expect(`=>`),P(e,t,n)}var j=class{name;constructor(e){this.name=e}};function M(e){return e instanceof j?e.name:e}function N(e,t,n){return De(e)?Oe(e,t,n):Ae(ke(e,t,n),e,t,n)}function ke(e,t,n){e.skip();let r=e.peek();if(r===`'`||r===`"`)return D(e);if(r==="`"&&e.fail(`This file doesn't use template strings.`),r===`-`||/^[0-9]/.test(r))return pe(e);if(r===`{`)return _e(e,t,n);if(r===`[`)return ve(e,t,n);if(r===`(`){e.bump();let r=N(e,t,n);return e.expect(`)`),r}let i=e.ident();return i===`true`?!0:i===`false`?!1:i===`null`?null:(i===void 0&&e.fail(`Expected a value.`),new j(i))}function P(e,t,n){e.skip();let r=e.pos(),i=N(e,t,n);if(!(i instanceof j))return i;if(i.name!==`undefined`)throw new T(`'${i.name}' is set somewhere else. Write its value here.`,r.line,r.column)}function Ae(e,t,n,r){let i=e;for(;;)if(t.eat(`.`)){let e=t.expectIdent();i=be(M(i),e)}else if(t.eat(`(`)){let e=r.length,a=[];for(;!t.eat(`)`);)a.push(M(N(t,n,r))),t.eat(`,`),t.done&&t.fail(`This call never closes.`);i=Ee(M(i),a,t,r.slice(e))}else return O(i)&&t.fail(`This file doesn't stop on a property.`),i}function je(e,t){e.expectIdent();let n=e.expectIdent();e.expect(`=`);let r=N(e,``,t.spans);(e.eat(`satisfies`)||e.eat(`as`))&&he(e),e.eat(`;`),e.of===`provider`?e.fail(`A provider's code is its registerProvider() call and nothing else.`):n===`profile`?(E(r)||e.fail(`profile has to be the defineProfile() object.`),t.profile&&e.fail(`This file defines two profiles.`),t.profile=r):n===`questions`?(E(r)||e.fail(`questions has to be an object.`),t.questions=r):n===`images`&&(E(r)||e.fail(`images has to be an object.`),t.images=r)}function Me(e,t){let n=N(e,``,t.spans);if(e.eat(`;`),E(n)){if(n.kind===`provider`&&typeof n.definition==`string`&&E(n.spec))t.provider&&e.fail(`This code registers two providers.`),t.provider={definition:n.definition,spec:n.spec};else if(n.kind===`registerTool`){let r=n.tool;E(r)||e.fail(`registerTool() needs the tool object.`),t.tools.push(r)}else if(n.kind===`registerStructured`){let[r,i]=Array.isArray(n.args)?n.args:[];(typeof r!=`string`||!E(i))&&e.fail(`registerStructured() needs an id and a spec.`),t.structures.push({id:r,spec:i})}}}function F(e,t=`profile`){let n=new fe(e,t),r={tools:[],structures:[],spans:[]};for(n.skip();!n.done;n.skip())n.peekIdent()===`import`?(n.expectIdent(),ge(n)):(n.peekIdent()===`export`&&n.expectIdent(),n.peekIdent()===`const`?je(n,r):Me(n,r));return t===`provider`?r.provider||n.fail(`This code needs registerProvider().`):r.profile||n.fail(`This file needs defineProfile().`),r}function I(e,t=``){return typeof e==`string`?e:t}function L(e){return typeof e==`number`?e:null}function R(e,t){if(e===void 0)return``;if(typeof e==`string`)return e;if(!Array.isArray(e))throw new T(t,1,1);return e.map(e=>{if(typeof e==`string`)return e;if(Array.isArray(e))return R(e,t);if(E(e)&&typeof e.private==`string`)return`{private: ${e.private}}`;throw new T(t,1,1)}).join(``)}function Ne(e){let t=`The system prompt has to be text.`,n=(Array.isArray(e)?e:[e]).map(n=>{if(Array.isArray(e)&&typeof n!=`string`&&!Array.isArray(n))throw new T(t,1,1);return R(n,t)});for(let e of n){let t=C(e);if(ie.test(e)&&t.ok&&t.lines.length>1)throw new T(`A "when" line in the system prompt can't hold a blank line.`,1,1)}return n.join(`
|
|
8
|
-
|
|
9
|
-
`)}function Pe(e,t){if(e===void 0)return[];let n=`Conditions have to be lists of values.`;if(!E(e))throw new T(n,1,1);return Object.entries(e).map(([e,r])=>{if(!Array.isArray(r))throw new T(n,1,1);return{key:t.find(t=>t.name===e)?.key??y(`condition`),name:e,values:r.map(e=>I(e))}})}function z(e){return e===void 0?``:JSON.stringify(e,null,2)}function Fe(e,t){return w(e)===w(t)}function B(e){return E(e)?JSON.stringify(e,null,2):JSON.stringify(e)}function V(e){return Array.isArray(e)?e.map(e=>{if(!E(e)||typeof e.name!=`string`)throw new T(`A pattern needs a name.`,1,1);return Array.isArray(e.words)?{name:e.name,kind:`words`,pattern:``,flags:``,words:e.words.filter(e=>typeof e==`string`)}:{name:e.name,kind:`pattern`,pattern:I(e.pattern),flags:I(e.flags),words:[]}}):[]}function H(e){return E(e)?e:void 0}function U(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`):[]}function W(e){return Array.isArray(e)?U(e):void 0}function G(e){return I(e)||void 0}function K(e){return Array.isArray(e)?U(e).join(`
|
|
10
|
-
`)||void 0:G(e)}function q(e,t,n){return E(e)?t(e):n}function Ie(e,t,n){if(!E(n))return;if(Array.isArray(n.names)){e.innocentNames=U(n.names);return}if(!(t in e.allow))return;let r=e.allow[t];r.hosts=U(n.hosts),r.fromTools=n.fromTools!==!1}function Le(e,t,n){let r=e.sources[t];r&&(n.theorem===!1&&(r.theorem=!1),r.patterns=V(n.patterns),r.hint=I(n.hint)),Ie(e,t,n.allow)}function Re(e,t){let n=f(m,()=>`ignore`);return E(t.at)&&Object.assign(n,t.at),{key:e,label:I(t.label),at:n,patterns:V(t.patterns),hint:I(t.hint)}}function ze(e){let t=x().guardrails;if(!E(e))return t;let n=u(e.detect),r={detect:f(h,e=>({...n[e]})),sources:structuredClone(t.sources),allow:structuredClone(t.allow),innocentNames:[...t.innocentNames]},i=[],a=new Set(h);for(let[t,n]of Object.entries(H(e.detect)??{}))E(n)&&(a.has(t)?Le(r,t,n):i.push(Re(t,n)));let o=H(e.quota),s=H(e.blockedReply),c=H(e.network),l=H(e.taint);return{...t,...r,own:i,quotaEnabled:o!==void 0,quotaPerDay:L(o?.perDay),blockedReplyOnBlock:I(s?.onBlock),blockedReplyMaxRetries:L(s?.maxRetries),allowPrivateNetworks:c?.allowPrivateNetworks===!0,allowedHosts:U(c?.allowedHosts),allowedSchemes:U(c?.allowedSchemes),taintAfterRemoteRead:I(l?.afterRemoteRead),taintRemoteDestination:I(l?.remoteDestination)}}var Be={"continue.instruction":(e,t)=>{e.turnBehaviour.continueInstruction=t},"canary.bind_note":(e,t)=>{e.guardrails.canaryBindNote=t},"quota.exhausted":(e,t)=>{e.guardrails.quotaMessage=t},"repair.default_guidance":(e,t)=>{e.outputs.repairGuidance=t},"egress.default_repair_guidance":(e,t)=>{e.guardrails.egressRepairGuidance=t},"egress.refusal":(e,t)=>{e.guardrails.egressRefusal=t}};function Ve(e,t){if(!E(t))return;let n={};for(let[r,i]of Object.entries(t)){if(typeof i!=`string`)continue;let t=Be[r];t?t(e,i):te[r]||(n[r]=i)}e.labels=n}function He(e){if(E(e))return Object.fromEntries(v.map(({name:t})=>[t,L(e[t])]))}function Ue(e,t,n,r,i){let a=n??ee({modelId:e});if(!E(t))return{...a,modelId:e};let o=E(t.efforts)?Object.entries(t.efforts).map(([e,t])=>({alias:e,level:t})):[],s=E(t.compaction)?t.compaction:void 0,c=I(s?.profile),l=L(t.timeoutMs);return{...a,modelId:e,protocol:I(t.protocol,a.protocol),provider:I(t.provider,a.provider),apiId:I(t.apiId),options:H(t.options)??{},timeoutMs:l,limits:He(t.limits),efforts:o,defaultEffort:I(t.defaultEffort),allowEffortSelect:t.allowEffortSelect===!0,summaries:typeof t.summaries==`boolean`?t.summaries:null,maxOutputTokens:L(t.maxOutputTokens),temperature:typeof t.temperature==`number`?t.temperature:null,builtInTools:Array.isArray(t.builtInTools)?t.builtInTools.filter(e=>typeof e==`string`):[],keySlot:I(t.keySlot),fallbackKeySlot:I(t.fallbackKeySlot),compactTiming:I(s?.timing),compactMaxTokens:L(s?.maxTokens),compactAt:typeof s?.compactAt==`number`?s.compactAt:void 0,compactKeep:L(s?.previousExchanges),compactMeter:I(s?.meter),compactWith:c?We(c,r,`models.${e}.compaction.profile`,i):``}}function We(e,t,n,r){return t?t(e)??Y(r,n,`'${e}' is not an agent here, so it can't write this model's summaries.`):``}function Ge(e,t){let n=t.output;if(e===`function`&&E(t.handler)&&E(n)&&!Fe(t.handler,oe(n)))return z(t.handler)}function Ke(e){let t=H(e.mapping)??{};return{endpoint:G(e.endpoint),method:G(e.method),headersJson:E(e.headers)?z(e.headers):void 0,pathParams:W(t.pathParams),queryParams:W(t.queryParams),bodyParam:G(t.bodyParam),serverUrl:G(e.serverUrl),mcpToolName:G(e.mcpToolName),maxResponseBytes:L(e.maxResponseBytes),sessionIdleMs:L(H(e.session)?.idleMs),sessionMax:L(H(e.session)?.max)}}function qe(e){let t=H(e.auth)??{};return{authType:I(t.type),authSlot:G(t.slot),authService:G(t.service),authHeaderName:G(t.headerName),authHeaderPrefix:typeof t.headerPrefix==`string`?t.headerPrefix:void 0,authQueryParam:G(t.queryParam),authUnauthenticated:I(t.onUnauthenticated),authScopes:W(t.scopes),authClientId:G(t.clientId),authRedirectUri:G(t.redirectUri)}}function Je(e,t,n){let r=t??b(),i=I(e.type,r.toolType),a=H(e.labels)??{},o=I(e.profile),s=e.answeredBy===`page`;return{...r,key:t?.key??y(`tool`),toolName:I(e.name,r.toolName),toolType:i,description:I(e.description),category:I(e.category,`studio`),access:I(e.access,r.access),permission:I(e.permission,r.permission),loadTier:I(e.loadTier,r.loadTier),paths:W(e.paths)??[`*`],inputJson:e.input===void 0?r.inputJson:B(e.input),outputJson:e.output===void 0?r.outputJson:B(e.output),activity:K(a.activity),activityPast:K(a.activityPast),activityFailed:K(a.activityFailed),request:K(a.request),stubOutputJson:s?t?.stubOutputJson:Ge(i,e),answeredBy:s?`page`:void 0,after:e.after===!0||void 0,background:e.background,...Ke(e),agentKey:o?n?.(o):void 0,maxCallsPerTurn:L(e.maxCallsPerTurn),...qe(e)}}function Ye(e,t){let n=new Map(t.map(e=>[e.id,e]));return Object.entries(e).map(([e,t])=>{let r=n.get(e),i=E(t)?t:{},a=I(i.type,`choice`),o=i.criteria,s=Array.isArray(o)?o.map((e,t)=>({key:r?.criteria[t]?.key??y(`criterion`),label:``,text:I(e)})):E(o)?Object.entries(o).map(([e,t],n)=>({key:r?.criteria[n]?.key??y(`criterion`),label:e,text:I(t)})):[];return{key:r?.key??y(`question`),id:e,type:a,instructions:I(i.instructions),criteria:s,...a===`box`&&I(i.image)?{image:I(i.image)}:{}}})}function Xe(e){if(!Array.isArray(e))return[];let t=[];for(let n of e)if(E(n)){if(typeof n.uri==`string`){let e=I(n.name);t.push({key:y(`reference`),uri:n.uri,...e?{name:e}:{}})}else typeof n.data==`string`&&t.push({key:y(`reference`),name:I(n.name),mimeType:I(n.mimeType),data:n.data})}return t}function Ze(e,t){return e?g.filter(n=>!n.optional||n.role===`branch`||!n.profileTypes.includes(e)?!1:n.profilePath in t).map(e=>e.id):x().included}function Qe(e,t,n,r){let i=[],a=new Set;for(let o of e){let e=Je(o,t.get(I(o.name)),n);if(e.toolName&&a.has(e.toolName)){let t=r.filter(e=>e.path===`name`)[i.length]??{line:1,column:1};throw new T(`'${e.toolName}' is registered twice.`,t.line,t.column)}e.toolName&&a.add(e.toolName),i.push(e)}return i}function $e(e,t,n){if(t===void 0)return[];let r=n.findLast(e=>e.path===`tools.allow`)??{line:1,column:1};if(!Array.isArray(t))throw new T(`tools.allow has to be a list of tool names.`,r.line,r.column);let i=new Map(e.map(e=>[e.toolName,e])),a=[],o=new Set;for(let[e,s]of t.entries()){let t=n.find(t=>t.path===`tools.allow.${String(e)}`)??r;if(typeof s!=`string`||s.trim()===``)throw new T(`tools.allow names tools.`,t.line,t.column);if(o.has(s))throw new T(`'${s}' is listed twice in tools.allow.`,t.line,t.column);o.add(s);let c=i.get(s);if(!c)throw new T(`'${s}' is in tools.allow, and this file has no registerTool for it.`,t.line,t.column);a.push(c)}return a}function et(e,t,n){let r=H(t.identity)??{};return{...e,agentId:I(t.id),profileType:n,handle:I(r.handle),system:Ne(r.system),conditions:Pe(r.conditions,e.conditions)}}function tt(e){return{...E(e.providerContinuation)&&(e.providerContinuation.history===`provider`||e.providerContinuation.history===`stateless`)?{providerHistory:e.providerContinuation.history}:{},defaultModel:I(e.defaultModel),allowModelSelect:e.allowModelSelect===!0,maxSteps:L(e.maxSteps),key:I(e.key),fallbackKey:I(e.fallbackKey)}}function nt(e){return p.includes(e)}function rt(e){return Object.fromEntries(Object.entries(H(e)??{}).filter(e=>typeof e[1]==`number`))}function it(e,t){let n=new Map(t.map(e=>[e.name,e]));return Object.entries(H(e)??{}).map(([e,t])=>{let r=n.get(e),i=H(t),a=(Array.isArray(t)?t:Array.isArray(i?.choices)?i.choices:[]).map((e,t)=>{let n=H(e);return{key:r?.choices[t]?.key??y(`choice`),value:I(n?n.value:e),description:I(n?.description)}});return{key:r?.key??y(`slot`),name:e,label:I(i?.label),choices:a}})}function at(e,t){let n=H(e.context);return{text:e.text!==!1,attachmentsAccept:U(H(e.attachments)?.accept),voiceAccept:U(H(e.voice)?.accept),maxFiles:L(e.maxFiles),maxBytes:L(e.maxBytes),maxTurnBytes:L(e.maxTurnBytes),limitsByMime:rt(e.limitsByMime),slots:it(e.slots,t.slots),contextFrom:U(n?.from).filter(nt),contextMaxChars:L(n?.maxChars)}}function ot(e){return Object.fromEntries(Object.entries(e??{}).map(([e,t])=>[e,H(t)?.onFail===`fix`?`fix`:`drop`]))}function st(e,t){let n=H(e?.structured),r=n?t.find(({id:e})=>e===I(n.fallback)):t[0],i=r?.id??I(e?.structured),a=Object.entries(H(n?.map)??{}).map(([e,n])=>({choice:e,schemaId:I(n),schemaJson:z(t.find(e=>e.id===n)?.spec.jsonSchema)})),o=H(e?.streaming),s=H(e?.validation);return{mode:i?`structured`:`text`,schemaId:i,schemaJson:z(r?.spec.jsonSchema),...n?{bySlot:{slot:I(n.by),shapes:a}}:{},streamMode:I(o?.mode),streamThoughts:o?.streamThoughts!==!1,validationEnabled:s!==void 0,maxRetries:L(s?.maxRetries),itemRules:ot(H(s?.items)),repairGuidance:``}}function ct(e){let t=H(e.resumption),n=Array.isArray(t?.allowContinue)?t.allowContinue:[...a],r=Array.isArray(t?.autoContinue)?t.autoContinue:[...s];return{resumeEnabled:n.length>0||r.length>0,allowContinue:n,autoContinue:r,maxContinues:L(t?.maxContinues),continueInstruction:``,allowSteering:e.allowSteering!==!1,atStepLimit:e.atStepLimit===`answer`?`answer`:`stop`}}function lt(e){let t=x().observability,n=typeof e.writeTo==`string`&&e.writeTo?e.writeTo:t.destination;return{...t,writeTo:e.writeTo!==!1&&n,destination:n,sampleRate:typeof e.sampleRate==`number`?e.sampleRate:t.sampleRate,include:{...t.include,...H(e.include)},scrub:{...t.scrub,...H(e.scrub)},retainForDays:L(e.retainForDays),rotateAfterMiB:L(e.rotateAfterMiB),resourceJson:z(e.resource)}}function ut(e){return{aspectRatio:I(e.aspectRatio),resolution:I(e.resolution),mimeType:I(e.mimeType),quality:I(e.quality),background:I(e.background),n:L(e.n),seed:L(e.seed),outputCompression:L(e.outputCompression),includeText:e.includeText===!0,references:Xe(e.references)}}function dt(e){return{voice:I(e.voice),style:I(e.style),speed:L(e.speed),format:I(e.format)}}function J(e,t){let n=e[t];return typeof n==`boolean`?n:S(t)}function ft(e){let t=H(e.ingress)??{},n=H(e.vad)??{},r=H(e.contextCompression),i=H(r?.slidingWindow),a=H(e.transcription);return{ingressAudio:J(t,`audio`),ingressVideo:J(t,`video`),ingressText:J(t,`text`),voice:I(e.voice),sessionResumption:e.sessionResumption===!0,greeting:I(e.greeting),resumedPrompt:I(H(e.resumed)?.prompt),resumedAfterMs:L(H(e.resumed)?.afterMs),contextCompression:r!==void 0,compressionTriggerTokens:L(r?.triggerTokens),compressionTargetTokens:L(i?.targetTokens),transcriptionInput:a?.input===!0,transcriptionOutput:a?.output===!0,vadActivityHandling:I(n.activityHandling),vadStartSensitivity:I(n.startSensitivity),vadEndSensitivity:I(n.endSensitivity),vadPrefixPaddingMs:L(n.prefixPaddingMs),vadSilenceDurationMs:L(n.silenceDurationMs)}}function pt(e,t,n){let r=L(H(t.profile?.inputs)?.maxStateBytes);return{contract:I(e.contract),maxStateBytes:r,questions:t.questions?Ye(t.questions,n.questions):[],images:t.images?mt(t.images,n.images):[]}}function mt(e,t){let n=new Map(t.map(e=>[e.name,e]));return Object.entries(e).map(([e,t])=>{let r=e.replace(/^<|>$/g,``),i=E(t)?t:{};return{key:n.get(r)?.key??y(`image`),name:r,mimeType:I(i.mimeType),data:I(i.data)}})}function ht(e){let t=I(e.type);if(t&&!_.includes(t))throw new T(`'${t}' is not a profile type.`,1,1);return t}function gt(e,t){let[n]=d(e);n&&Y(t,n.path,`${n.path} ${n.message}`)}function _t(e,t,n){let r=e.profile??{},i=ht(r);gt(r,e.spans);let a=new Map(t.modelBindings.map(e=>[e.modelId,e])),o=new Map(t.toolSpecs.map(e=>[e.toolName,e])),s=H(r.tools)??{},c=H(r.inputs),l=H(r.outputs),u={...t,identity:et(t.identity,r,i),included:Ze(i,r),models:tt(r),modelBindings:Object.entries(H(r.models)??{}).map(([t,r])=>Ue(t,r,a.get(t),n,e.spans)),tools:{t2Loader:I(s.t2Loader),parallel:s.parallel===!0},toolSpecs:[],inputs:c&&i!==`decision`?at(c,t.inputs):t.inputs,outputs:l||e.structures.length?st(l,e.structures):t.outputs,turnBehaviour:q(r.turnBehaviour,ct,t.turnBehaviour),guardrails:q(r.guardrails,ze,t.guardrails),observability:q(r.observability,lt,t.observability),image:q(r.image,ut,t.image),speech:q(r.speech,dt,t.speech),live:q(r.live,ft,t.live),decision:q(r.decision,n=>pt(n,e,t.decision),t.decision),labels:{}},d=Qe(e.tools,o,n,e.spans),f=$e(d,s.allow,e.spans);u.toolSpecs=f;let p=new Set(f.map(e=>e.toolName));return u.tools.t2Loader&&!p.has(u.tools.t2Loader)&&(u.tools={...u.tools,t2Loader:``}),Ve(u,r.labels),{draft:u,registered:d}}function vt(e,t,n){try{let r=F(e),{draft:i,registered:a}=_t(r,t,n);return{ok:!0,draft:i,spans:r.spans,registered:a}}catch(e){if(e instanceof T)return{ok:!1,errors:[{message:e.message,line:e.line,column:e.column}]};throw e}}function Y(e,t,n){let r=e.findLast(e=>e.path===t)??{line:1,column:1};throw new T(n,r.line,r.column)}var yt=new Set([`id`,`connection`,`keySlot`,`fallbackKeySlot`]);function bt(e,t,n){let{spec:r}=e;for(let e of Object.keys(r))yt.has(e)||Y(n,e,`'${e}' isn't a provider setting the studio holds.`);r.id!==t.id&&Y(n,`id`,`The id stays '${t.id}': models and code name the provider by it.`);let a=i(e.definition);if(!a){let t=c().flatMap(e=>o(e)??[]).join(`, `);Y(n,``,`'${e.definition}' isn't one of the kernel's providers: ${t}.`)}let s=r.connection===void 0?{}:xt(r.connection,n),l=Object.keys(s).length===0&&t.connection===void 0,u={id:t.id,definition:a,...l?{}:{connection:s}};for(let e of[`keySlot`,`fallbackKeySlot`]){let t=r[e];t!==void 0&&(typeof t!=`string`&&Y(n,e,`${e} names a key slot.`),u[e]=t)}return u}function xt(e,t){let n=`connection holds text settings here.`,r={};E(e)||Y(t,`connection`,n);for(let[i,a]of Object.entries(e))typeof a!=`string`&&Y(t,`connection`,n),r[i]=a;return r}function St(e,t){try{let n=F(e,`provider`);if(!n.provider)throw new T(`This code needs registerProvider().`,1,1);return{ok:!0,provider:bt(n.provider,t,n.spans),spans:n.spans}}catch(e){if(e instanceof T)return{ok:!1,errors:[{message:e.message,line:e.line,column:e.column}]};throw e}}var X=e(n(),1),Z=t(),Ct=300,wt=2e3;function Tt({editor:e,monaco:t,spans:n,errors:r},i){let a=e?.getModel();t&&a&&t.editor.setModelMarkers(a,`studio`,[...r.map(e=>$(t,e.line,e.column,e.message)),...Et(t,n,i)])}function Q({text:e,hold:t,isReadOnly:n=!1,issues:i,onApply:a}){let o=(0,X.useRef)(null),s=(0,X.useRef)(a),c=(0,X.useRef)(e),l=(0,X.useRef)(n);l.current=n;let u=(0,X.useRef)(i),d=(0,X.useRef)({spans:[],errors:[],setting:!1,dirty:!1});return s.current=a,c.current=e,u.current=i,(0,X.useEffect)(()=>{let e=o.current;if(!e)return;let t={disposed:!1},n,i,a=0,f,p=!1,m=!1,h=()=>{a+=1,i&&clearTimeout(i),i=void 0,f?.stop(),f=void 0,p=!1,m=!1},g=t=>e.contains(t)?!0:t instanceof Element&&!!t.closest(`.suggest-widget, .parameter-hints-widget, .monaco-hover, .monaco-menu-container, .context-view`),ee=()=>!!document.querySelector(`.suggest-widget.visible, .parameter-hints-widget.visible`),_,v=()=>{Tt(d.current,u.current)};return(async()=>{let o=await r(()=>import(`./studio-monaco-xfyfezQS.js`),__vite__mapDeps([0,1,2,3,4]));await r(()=>import(`./register-CDgivxvX.js`),__vite__mapDeps([5,2,1,3]));let u=(await r(async()=>{let{default:e}=await import(`./editor.worker-6GY8RhDc.js`);return{default:e}},[])).default;if(self.MonacoEnvironment={getWorker(){return new u}},t.disposed||!e.isConnected)return;let te=document.documentElement.dataset.theme===`dark`||globalThis.matchMedia(`(prefers-color-scheme: dark)`).matches,y=o.Uri.parse(`file:///agent.ts`);o.editor.getModel(y)?.dispose();let b=o.editor.createModel(c.current,`typescript`,y),x=o.editor.create(e,{model:b,readOnly:l.current,language:`typescript`,theme:te?`vs-dark`:`vs`,minimap:{enabled:!1},fontSize:13,wordWrap:`on`,wrappingIndent:`indent`,scrollBeyondLastLine:!1,automaticLayout:!0,fixedOverflowWidgets:!0,tabSize:2,padding:{top:12},quickSuggestions:{other:!0,comments:!1,strings:!0},suggestOnTriggerCharacters:!0,acceptSuggestionOnEnter:`on`,tabCompletion:`on`,wordBasedSuggestions:`currentDocument`,parameterHints:{enabled:!0},suggest:{preview:!0,showIcons:!0}});d.current.editor=x,d.current.monaco=o;let S=()=>{i&&clearTimeout(i),i=setTimeout(()=>{t.disposed||(ee()?S():h())},wt)},ne=()=>{if(f){m&&S();return}if(p)return;let e=a,n=()=>t.disposed||e!==a;p=!0,r(async()=>{let{openTypeChecker:e}=await import(`./studio-type-checker-JZuu4iVI.js`);return{openTypeChecker:e}},__vite__mapDeps([6,2])).then(({openTypeChecker:r})=>{if(n())return;let i=r(o,x,()=>{t.disposed||e!==a||(m=!0,S())});n()?i.stop():f=i}).catch(()=>{}).finally(()=>{e===a&&(p=!1)})};x.onKeyDown(e=>{let t=e.browserEvent;t.metaKey||t.ctrlKey||t.altKey||m&&S()});let C=e=>{let t=e.target;t instanceof Node&&!g(t)&&h()};document.addEventListener(`pointerdown`,C,!0),_=()=>{document.removeEventListener(`pointerdown`,C,!0)},x.onDidBlurEditorText(()=>{queueMicrotask(()=>{if(t.disposed||x.hasTextFocus())return;let e=document.activeElement;e&&g(e)||h()})}),x.onDidChangeModelContent(()=>{if(d.current.setting)return;ne();let e=x.getValue();d.current.dirty=e!==c.current,n&&clearTimeout(n),n=setTimeout(()=>{let t=s.current(e);d.current.spans=t.spans,d.current.errors=t.errors,v()},Ct)}),v()})(),()=>{t.disposed=!0,_?.(),h(),n&&clearTimeout(n);let e=d.current.editor?.getModel();d.current.editor?.dispose(),e?.dispose(),d.current.editor=void 0}},[]),(0,X.useEffect)(()=>{let{editor:n}=d.current;n&&!t&&(d.current.dirty&&n.getValue()!==e||(n.getValue()===e||(d.current.setting=!0,n.setValue(e),d.current.setting=!1),d.current.dirty=!1))},[e,t]),(0,X.useEffect)(()=>{d.current.editor?.updateOptions({readOnly:n})},[n]),(0,X.useEffect)(()=>{Tt(d.current,i)},[i]),(0,Z.jsx)(`div`,{ref:o,className:`studio-fill`})}function $(e,t,n,r){return{startLineNumber:t,startColumn:n,endLineNumber:t,endColumn:n+1,message:r,severity:e.MarkerSeverity.Error}}function Et(e,t,n){return n.flatMap(n=>{let r=n.field?`${n.nodeId}.${n.field}`:n.nodeId,i=t.find(e=>e.path===r)??(n.field?t.find(e=>e.path===n.field):void 0);return i?[$(e,i.line,i.column,n.message)]:[]})}function Dt({source:e,blocked:t,issues:n,state:r}){let i=(0,X.useRef)(e);e&&(i.current=e);let a=(0,X.useCallback)(e=>{let t=le(r.workspace,r.focus);if(!t)return{errors:[{message:`No agent is open.`,line:1,column:1}],spans:[]};let n=vt(e,{...t,toolSpecs:r.workspace.toolSpecs},e=>r.workspace.agents.find(t=>t.identity.agentId.trim()===e)?.key);return n.ok?(r.update(e=>ce(e,r.focus,n.draft,n.registered)),{errors:[],spans:n.spans}):{errors:n.errors,spans:[]}},[r]);return i.current?(0,Z.jsx)(`div`,{className:`studio-fill`,children:(0,Z.jsx)(Q,{text:e??i.current,hold:e==null,issues:n,onApply:a})}):(0,Z.jsx)(ue,{title:`No code yet`,description:`${t??``} to generate the TypeScript.`})}function Ot({provider:e,issues:t,state:n,isEditable:r}){let i=(0,X.useCallback)(t=>{let r=n.workspace.providers.find(t=>t.id===e.id);if(!r)return{errors:[{message:`No provider is open.`,line:1,column:1}],spans:[]};let i=St(t,r);return i.ok?(n.update(e=>se(e,i.provider)),{errors:[],spans:i.spans}):{errors:i.errors,spans:[]}},[n,e.id]);return(0,Z.jsx)(`div`,{className:`studio-fill`,children:(0,Z.jsx)(Q,{text:de(e),hold:!1,isReadOnly:!r||o(e.definition)===void 0,issues:t,onApply:i},e.id)})}export{Dt as CodeBody,Ot as ProviderCode};
|
|
@@ -1,5 +0,0 @@
|
|
|
1
|
-
import{r as e}from"./rolldown-runtime-hePW80VL.js";import{c as t,u as n}from"./themeProps-3IqahpCr.js";import{a as r,i}from"./useAnnounceRenderedText-aqUr1P16.js";import{t as a}from"./VStack-CkVMcNiK.js";import{n as o,t as s}from"./StackItem-CQviqAfM.js";import{S as c,h as l,s as u,t as d,v as f}from"./browser-transport-C_sHZVPa.js";import{t as p}from"./Icon-3c9WmPTH.js";import{a as m,c as h,l as g,p as _,u as v}from"./SidePanel-Bp_RI52Y.js";import{t as y}from"./Text-B74VhVA7.js";import{a as b,n as x,t as S}from"./labels-provider-Dc-AJqPH.js";import{n as C,t as w}from"./IconButton-BeI1pXEZ.js";import{t as T}from"./Dialog-DUNBjHOI.js";import{t as E}from"./createReactComponent-CZwsv6DD.js";import{n as ee,t as D}from"./Center-CgO0c-qo.js";import{_ as O,g as k,h as A,m as j,n as M,r as N,t as P}from"./studio-labels-BRouZt4M.js";import{c as F}from"./host-patterns-F-KZIzkF.js";import{Dr as I,Hr as L,ar as te,or as ne}from"./shaped-data-DCfLI4gb.js";import{S as R,g as re,r as ie,t as z}from"./reader-DtOL_I1x.js";import{i as B}from"./live-ingress-OuSlQ6q7.js";import{i as ae,y as oe}from"./turn-client-B3jV7UKH.js";import{r as se,t as ce}from"./live-messages-D-SPyR3e.js";import{t as le}from"./EmptyState-C_uF9Wyj.js";import"./use-second-ticker-DhbZ0Soz.js";import{t as ue}from"./Toolbar-t4I6MDV_.js";import{A as de,Ht as fe,I as pe,Pt as me,S as he,T as ge,Ut as _e,V,Vt as ve,_ as ye,c as be,it as xe,j as Se,nn as Ce,pt as we}from"./index-DuTrjzLN.js";var Te=E(`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`}]]),Ee=E(`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`}]]),De=E(`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`}]]),H=E(`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`}]]),Oe=E(`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`}]]),ke=E(`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`}]]),U=E(`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 Ae(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 je(e){return!(e.isMuted||!e.socketOpen||e.modelPlaying&&e.rms<e.bargeInRmsWhileSpeaking)}function Me(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 Ne(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 W=new Set;async function Pe(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&&!W.has(n)&&(W.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 Fe(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 Ie=`mic-capture-processor`;function Le(){return new URL(`data:text/javascript;base64,LyoqCiAqIEF1ZGlvV29ya2xldCBwcm9jZXNzb3IgdGhhdCBmb3J3YXJkcyBtb25vIG1pYyBmcmFtZXMgdG8gdGhlIG1haW4gdGhyZWFkLgogKiBQbGFpbiBKUzogaXQgcnVucyBpbiB0aGUgQXVkaW9Xb3JrbGV0R2xvYmFsU2NvcGUgYXMgaXRzIG93biBtb2R1bGUsIGxvYWRlZAogKiBieSBVUkwgKHNlZSBgLi4vbWljLWNhcHR1cmUudHNgKSwgc28gaXQgaW1wb3J0cyBub3RoaW5nIGFuZCBzaGlwcyBhcyBpcy4KICovCnJlZ2lzdGVyUHJvY2Vzc29yKAogICdtaWMtY2FwdHVyZS1wcm9jZXNzb3InLAogIGNsYXNzIE1pY0NhcHR1cmVQcm9jZXNzb3IgZXh0ZW5kcyBBdWRpb1dvcmtsZXRQcm9jZXNzb3IgewogICAgcHJvY2VzcyhpbnB1dHMpIHsKICAgICAgY29uc3QgY2hhbm5lbCA9IGlucHV0c1swXVswXTsKICAgICAgY29uc3QgY29weSA9IG5ldyBGbG9hdDMyQXJyYXkoY2hhbm5lbCk7CiAgICAgIHRoaXMucG9ydC5wb3N0TWVzc2FnZShjb3B5LCBbY29weS5idWZmZXJdKTsKICAgICAgcmV0dXJuIHRydWU7CiAgICB9CiAgfSwKKTsK`,``+import.meta.url)}function Re(e,t,n=16e3){if(t===n)return ze(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]=G(i>0?n/i:0),o++,s=t}return a}function ze(e){let t=new Int16Array(e.length);for(let n=0;n<e.length;n++)t[n]=G(e[n]??0);return t}function G(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 K(e){return JSON.stringify(e)}function Ve(){return{toolCalls:[],mediaChunks:[],cancelledToolIds:new Set}}var He=.05,Ue=[500,1e3,2e3,4e3,8e3];function q(e){return e instanceof Error?e:new F(`internal`,I(e),{cause:e})}function J(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=ve(e.inputFloat32),n=e.hasPlaybackNodes||e.status===`speaking`;return je({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 F(`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{slots:e,stated:t,model:n,effort:r,openMessage:i}=this.options;return{type:`open`,...this.history.length?{history:structuredClone(this.history)}:{},...e?{slots: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 F(`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 F(`timeout`,`live connect timed out`))},2e4),this.ws.onmessage=e=>{this.enqueueServerMessage(e.data)},this.ws.onclose=()=>{this.opening?this.failOpen(new F(`network`,`live socket closed before ready`)):this.handleDrop()},this.ws.onerror=()=>{!this.opening&&this.providerState&&!this.sessionOver?this.handleDrop():this.failOpen(new F(`network`,`live socket error`))}}catch(e){this.failOpen(new F(`internal`,I(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=Fe(e);this.failSession(new F(t?`auth`:`internal`,I(e),{cause:e,copy:{key:t?`voice.permission`:`voice.unavailable`}}))}finally{this.micActivating=!1}}}sendMicFrame(e,t){let n=Re(e,t,16e3),r=ne(new Uint8Array(n.buffer)),i=this.ws;i?.readyState===WebSocket.OPEN&&i.send(K({type:`audio`,data:r}))}reportMicVolume(e){this.isMuted||this.options.onVolumeLevel?.(fe(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(Le()),!0),this.micWorklet=new AudioWorkletNode(this.audioContext,Ie),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(()=>Pe({executeToolOnRelay:e=>this.executeToolOnRelay(e),pageTools:this.options.pageTools,onGate:this.options.onGate,name:e.name,toolArgs:e.arguments,callId:e.id,operationId:ae(e)})).catch(e=>{this.options.onError?.(q(e))});this.scheduleMediaChunks(t.mediaChunks)}enqueueServerMessage(e){this.inboundChain=this.inboundChain.then(async()=>{if(typeof e!=`string`)return;let t=se(e);t.type===`unsupported`||t.type===`malformed`?this.options.onTurnEvent?.(t):await this.processServerEnvelope(t)}).catch(e=>{this.options.onError?.(q(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(R(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?.(R(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`:Ne(e.tool,t);break;case`done`:this.handleDoneTurnEvent(e)}}handleEvidenceTurnEvent(e){let t=Me(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?.(q(e))})}executeToolOnRelay(e){let t=this.ws;if(!t||t.readyState!==WebSocket.OPEN)throw new F(`request`,`live session is not connected`);let n=ce.safeParse({...e,type:`executeTool`});if(!n.success||n.data.type!==`executeTool`)throw new F(`request`,L(`error.request`));let r=n.data;if(this.pendingExecuteResults.has(r.operationId))throw new F(`request`,L(`session.gate_expired`));return new Promise((e,n)=>{this.pendingExecuteResults.set(r.operationId,{callId:r.callId,resolve:e,reject:n});try{t.send(K(r))}catch(e){this.pendingExecuteResults.delete(r.operationId),n(q(e))}})}async enqueueAudioChunk(e,t){if(this.audioContext)try{if(this.ensurePlaybackBus(),!this.playbackBus)return;let n=te(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?.(q(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(K({type:`text`,text:e}))}setSlots(e){JSON.stringify(e)!==JSON.stringify(this.options.slots)&&(this.options={...this.options,slots: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(K({type:`context`,context:this.context})))}sendVideo(e,t=`image/jpeg`){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(K({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(),J(this.playbackBus),this.playbackBus=null,this.playbackAnalyser=null,this.playbackMeterBuffer=null,this.micWorklet&&=(this.micWorklet.port.onmessage=null,J(this.micWorklet),null),J(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}}},Y=e(n(),1);function X(){return{turns:[],interimUser:``,interimAgent:``,working:!1}}function Je(e,t){return t.length===0?e:[...e,[...t]]}function Ye(e,t){return e?t?t.startsWith(e)||e.startsWith(t)?t.length>=e.length?t:e:Z(e,t):e:t}function Z(e,t){return e?t?!e.endsWith(` `)&&!t.startsWith(` `)&&!/^\s/.test(t)&&!/^[\s.,!?;:]/.test(t)?`${e} ${t}`:`${e}${t}`:e:t}function Xe(e){return`${String(Date.now())}-${String(e.turns.length)}`}function Ze(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:Z(s.text,t)};else{let n=i?.forceNew?t:Ye(c,t);o.push({id:Xe(e),role:a,text:n})}return{...e,turns:o,interimUser:n?``:e.interimUser,interimAgent:n?e.interimAgent:``}}function Qe(e){return e.type===`thought`||e.type===`tool`||e.type===`citation`}function $e(e,t){return e.findIndex(e=>e.role===`work`&&e.events.some(e=>e.type===`tool`&&e.tool.callId===t))}function et(e,t){if(t.type===`tool`&&t.tool.phase!==void 0)return t.tool.phase===`gate`?-1:$e(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 tt(e,t){if(t.type===`done`)return e.working?{...e,working:!1}:e;if(!Qe(t))return e;let n=et(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:Xe(e),role:`work`,events:[t]},{...e,turns:r,working:!0}}function nt(e){return e.role===`work`?oe(e.events,{idPrefix:e.id}):[{id:e.id,kind:e.role===`user`?`user-text`:`text`,text:e.text}]}var rt=24;function it(e,t){let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];)n+=1;return n}function at(e,t){let n=e.trim();return it(n,t.trim())>=Math.min(n.length,rt)}function ot(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`&&at(t.text,e.text))})}function st(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=>ot(e).flatMap(nt)).filter(e=>e.length>0);return{blocks:a.flat(),callStarts:a.slice(1).map(e=>e[0].id)}}function ct({working:e,interimAgent:t}){return t!==``||e}function lt(e){return!e.interimUser&&!e.interimAgent?e:{...e,interimUser:``,interimAgent:``}}function ut(e,t){let n=Object.keys(t??{}).sort().join(`
|
|
2
|
-
`),r=e?.join(`
|
|
3
|
-
`);(0,Y.useEffect)(()=>{r!==void 0&&me(r?r.split(`
|
|
4
|
-
`):[],n?n.split(`
|
|
5
|
-
`):[])},[r,n])}var dt=.62,ft=400;function pt(e){return navigator.mediaDevices.getUserMedia({video:{facingMode:{ideal:e},width:{ideal:640},height:{ideal:480}},audio:!1})}function mt(e,t){let n=t?.facingMode??`user`;return pt(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 F(`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`,dt).split(`,`)[1];t&&e(t)};return r.play().then(()=>{o||s||(o=setInterval(l,ft))}),{video:r,facingMode:()=>c.facing,flip:async()=>{if(s)return c.facing;let e=c.facing===`user`?`environment`:`user`,t=await pt(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 ht(e){let t=(0,Y.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,Y.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,Y.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=>Ze(e,n,!0,!1,{forceNew:!0})))},[e]),handleToggleVideo:(0,Y.useCallback)(async()=>{if(e.clientRef.current&&e.sessionActive&&e.videoAvailable){if(e.isVideoOn)e.stopVideo();else try{let t=await mt(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,Y.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,Y.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,Y.useCallback)(async()=>{t(),await n()},[n,t])}}function gt(e){return new re(e.kind,e.error,e.message)}function Q(e){e.gateCallId===void 0&&e.clearActiveTool()}function _t(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(gt(e.failure)),Q(t)):t.setActiveTool(e.name)}function vt(e,t){e.type===`done`?(t.clearInterim(),Q(t)):e.type===`tool`&&_t(e.tool,t)}function yt(e){let[t,n]=(0,Y.useState)(`disconnected`),[r,i]=(0,Y.useState)(null),a=(0,Y.useRef)({input:0,output:0}),o=(0,Y.useCallback)(e=>{let t=a.current;t.input=typeof e==`function`?e(t.input):e},[]),s=(0,Y.useCallback)(e=>{let t=a.current;t.output=typeof e==`function`?e(t.output):e},[]),[l,u]=(0,Y.useState)(!1),[d,f]=(0,Y.useState)(!1),[p,m]=(0,Y.useState)(null),[h,g]=(0,Y.useState)(X),[_,v]=(0,Y.useState)(null),[y,b]=(0,Y.useState)(null),[x,S]=(0,Y.useState)(``),[C,w]=(0,Y.useState)(!1),[T,E]=(0,Y.useState)([]),[ee,D]=(0,Y.useState)(!1),[O,k]=(0,Y.useState)(null),[A,j]=(0,Y.useState)(`user`),M=(0,Y.useRef)(null),N=(0,Y.useRef)(h),P=(0,Y.useRef)(l),F=(0,Y.useRef)(T),I=(0,Y.useRef)(t);return N.current=h,P.current=l,F.current=T,I.current=t,(0,Y.useEffect)(()=>{C&&D(!0)},[C]),{status:t,setStatus:n,connectPhase:r,setConnectPhase:i,levelsRef:a,setInputLevel:o,setOutputLevel:s,isMuted:l,setIsMuted:u,isVideoOn:d,setIsVideoOn:f,activeTool:p,setActiveTool:m,captions:h,setCaptions:g,failure:_,reportFailure:(0,Y.useCallback)(t=>{v(c(t,e))},[e]),clearFailure:(0,Y.useCallback)(()=>{v(null)},[]),sessionEnded:y,reportSessionEnded:(0,Y.useCallback)(e=>{b(e.message)},[]),clearSessionEnded:(0,Y.useCallback)(()=>{b(null)},[]),textDraft:x,setTextDraft:S,sessionActive:C,setSessionActive:w,sessionPermissions:T,setSessionPermissions:E,everConnected:ee,videoPreview:O,setVideoPreview:k,videoFacingMode:A,setVideoFacingMode:j,videoCaptureRef:M,captionsRef:N,isMutedRef:P,sessionPermissionsRef:F,statusRef:I,resetCaptions:(0,Y.useCallback)(()=>{g(X())},[]),stopVideo:(0,Y.useCallback)(()=>{M.current&&=(M.current.stop(),null),k(null),j(`user`),f(!1)},[])}}function bt(e){let[t,n]=(0,Y.useState)(null),r=(0,Y.useRef)(t);r.current=t;let i=(0,Y.useRef)(null),a=(0,Y.useRef)(null),o=(0,Y.useCallback)(e=>{i.current?.(e),i.current=null,a.current=null,n(null)},[]);return{gatePrompt:t,gatePromptRef:r,handleLiveTurnEvent:(0,Y.useCallback)(t=>{e.setCaptions(e=>tt(e,t)),vt(t,{gateCallId:r.current?.callId,withdrawGate:()=>{o(`withdrawn`)},clearInterim:()=>{e.setCaptions(e=>lt(e))},clearActiveTool:()=>{e.setActiveTool(null)},reportFailure:e.reportFailure,setActiveTool:e.setActiveTool})},[e,o]),waitForGateDecision:(0,Y.useCallback)(e=>new Promise((t,r)=>{n(e),i.current=t,a.current=r}),[]),resolveGateDecision:(0,Y.useCallback)(e=>{o(e)},[o]),cancelGateDecision:(0,Y.useCallback)(()=>{a.current?.(new F(`cancelled`,`live session ended with a gate open`)),i.current=null,a.current=null,n(null)},[])}}function xt(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 St(e,t,n,r){r.setCaptions(r=>Ze(r,e,t,n?.interim))}async function Ct(e,t){let n=await t.waitForGateDecision(e);if(n===`withdrawn`)return`withdrawn`;let r=O({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 wt(e){let t=(0,Y.useRef)(null),n=(0,Y.useRef)(e);return n.current=e,{clientRef:t,ensureClient:(0,Y.useCallback)(e=>{if(t.current)return t.current;let r=n.current,i=new qe({...e,slots:r.slots,stated:r.stated,model:r.model,effort:r.effort,context:r.context,voiceIngress:r.voiceAvailable,onConnectPhase:e=>{r.setConnectPhase(e)},onStatusChange:e=>{xt(e,n.current)},onTranscript:(e,t,r)=>{St(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=>Ct(e,n.current)});return t.current=i,i},[]),clearClient:(0,Y.useCallback)(()=>{t.current&&=(t.current.disconnect(),null)},[])}}function Tt(e,t,n,r){let[i,a]=(0,Y.useState)(!1),[o,s]=(0,Y.useState)(!1),c=(0,Y.useRef)(!1),l=(0,Y.useCallback)(t=>{c.current=t.video&&r,a(!0),s(!1),e.startSession()},[e,r]);(0,Y.useEffect)(()=>{n&&c.current&&(c.current=!1,e.handleToggleVideo())},[e,n]);let u=(0,Y.useCallback)(()=>{c.current=!1,e.teardownSession(),s(!0)},[e]),[d,f]=(0,Y.useState)([]),p=(0,Y.useCallback)(async()=>{let n=t.current.turns;f(e=>Je(e,n)),s(!1),await e.handleRestart()},[e,t]),m=(0,Y.useRef)(e.teardownSession);return m.current=e.teardownSession,(0,Y.useEffect)(()=>()=>{m.current()},[]),{callStarted:i,ended:o,pastCalls:d,startCall:l,handleEnd:u,handleRestart:p}}function Et(e,t,n={}){let r=yt(e.labels),i=bt({setCaptions:r.setCaptions,setActiveTool:r.setActiveTool,reportFailure:r.reportFailure}),a=(0,Y.useRef)(t);a.current=t;let o=B(e.live.ingress,`audio`),s=B(e.live.ingress,`video`),c=B(e.live.ingress,`text`),l=(0,Y.useMemo)(()=>Ae({status:r.status,connectPhase:r.connectPhase,toolName:r.activeTool,isMuted:r.isMuted,voiceEnabled:o}),[r.activeTool,r.connectPhase,r.isMuted,r.status,o]),u=(0,Y.useMemo)(f,[]),{clientRef:d,ensureClient:p,clearClient:m}=wt({slots:n.slots,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,setActiveTool:r.setActiveTool,setSessionPermissions:r.setSessionPermissions,setVideoPreview:r.setVideoPreview,setVideoFacingMode:r.setVideoFacingMode,setIsVideoOn:r.setIsVideoOn}),h=ht({clientRef:d,videoCaptureRef:r.videoCaptureRef,connectionRef:a,statusRef:r.statusRef,isMutedRef:r.isMutedRef,sessionPermissionsRef:r.sessionPermissionsRef,ensureClient:p,clearClient:m,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,ended:_,pastCalls:v,startCall:y,handleEnd:b,handleRestart:x}=Tt(h,r.captionsRef,r.sessionActive,s),S=JSON.stringify(n.context);(0,Y.useEffect)(()=>{d.current?.setContext(S===void 0?void 0:JSON.parse(S))},[d,S]);let C=JSON.stringify(n.slots);(0,Y.useEffect)(()=>{d.current?.setSlots(C===void 0?void 0:JSON.parse(C))},[d,C]);let w=JSON.stringify(n.stated);return(0,Y.useEffect)(()=>{d.current?.setStated(w===void 0?void 0:JSON.parse(w))},[d,w]),ut(e.tools.page,n.pageTools),{handle:e.identity.handle,traces:u,callStarted:g,pastCalls:v,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||_||r.failure!==null),gatePrompt:i.gatePrompt,setTextDraft:r.setTextDraft,handleEnd:b,startCall:y,handleRestart:x,handleSendText:h.handleSendText,handleToggleMic:h.handleToggleMic,handleFlipCamera:h.handleFlipCamera,handleToggleVideo:h.handleToggleVideo,resolveGateDecision:i.resolveGateDecision}}var $=t();function Dt(e){return(0,$.jsx)(S,{children:(0,$.jsx)(Ot,{...e})})}function Ot({handle:e,captions:t,pastCalls:n,draftText:r,onDraftTextChange:i,onSubmit:o,isDisabled:c,showComposer:l=!0,leading:u}){let d=x(),f=d(`@theorem.agent.handle`,{handle:e}),{blocks:h,callStarts:g}=st(n,t),_=d(`@theorem.live.new_session`),v=Object.fromEntries(g.map(e=>[e,_])),y=l?(0,$.jsx)(xe,{handle:e,draftText:r,onDraftTextChange:i,onSubmit:o,isDisabled:c}):null;return(0,$.jsxs)(a,{height:`100%`,children:[u,(0,$.jsx)(s,{size:`fill`,children:h.length>0?(0,$.jsx)(m,{label:d(`@theorem.panel.captions.name`),children:(0,$.jsx)(pe,{blocks:h,dividers:v,handle:f,streaming:ct(t)})}):(0,$.jsx)(a,{height:`100%`,vAlign:`center`,padding:4,children:(0,$.jsx)(le,{icon:(0,$.jsx)(p,{icon:Oe,size:`lg`,color:`secondary`}),title:d(`@theorem.panel.captions.empty.title`),description:d(`@theorem.panel.captions.empty.description`),isCompact:!0})})}),y]})}var kt=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 F(`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 d(),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 F(`auth`,`Fill the vault slot this model names.`);let[c]=this.queued.splice(0,1);if(typeof c!=`string`)throw new F(`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`,...ie(t,e.profile.labels,z)}),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:z});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 At(e,t){let n,r=t.execution?void 0:e=>n??=e.browserExecution();return{createSocket:()=>new kt(e,t,r)}}var jt=720,Mt=320;function Nt({theme:e,mode:t,labels:n,...r}){return(0,$.jsx)(u,{theme:e,mode:t,children:(0,$.jsx)(S,{labels:n,children:(0,$.jsx)(Pt,{...r})})})}function Pt({iface:e,connection:t,trace:n,...o}){let s=x(),c=Et(e,t,o),l=(0,Y.useRef)(null),u=Se(e,c.traces,n),d=_(l,!0),f={name:s(`@theorem.panel.captions.name`),show:s(`@theorem.panel.captions.show`),hide:s(`@theorem.panel.captions.hide`),resize:s(`@theorem.panel.captions.resize`)},m=(0,$.jsx)(v,{labels:f,icon:(0,$.jsx)(p,{icon:Ce}),panelId:d.id,open:d.open,onToggle:d.toggle});return c.callStarted?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(de,{inspector:u,children:(0,$.jsx)(r,{ref:l,height:`fill`,header:(0,$.jsx)(g,{children:u.toggle}),content:(0,$.jsx)(i,{padding:0,children:(0,$.jsx)(r,{height:`fill`,end:(0,$.jsx)(h,{id:d.id,labels:f,resizable:d.resizable,open:d.open,children:(0,$.jsx)(zt,{model:c})}),content:(0,$.jsx)(i,{padding:0,children:(0,$.jsx)(a,{height:`100%`,padding:3,children:(0,$.jsx)(It,{model:c,captionsToggle:m})})})})})})}),(0,$.jsx)(Wt,{prompt:c.gatePrompt,agent:s(`@theorem.agent.handle`,{handle:c.handle}),onResolve:c.resolveGateDecision})]}):(0,$.jsx)(de,{inspector:u,children:(0,$.jsx)(r,{ref:l,height:`fill`,header:(0,$.jsx)(g,{children:u.toggle}),content:(0,$.jsx)(i,{padding:0,children:(0,$.jsx)(Ft,{model:c})})})})}function Ft({model:e}){let t=x();return(0,$.jsx)(a,{minHeight:`100%`,vAlign:`center`,gap:8,paddingInline:3,children:(0,$.jsx)(D,{axis:`horizontal`,width:`100%`,children:(0,$.jsxs)(a,{width:`100%`,maxWidth:he,gap:8,children:[(0,$.jsxs)(a,{gap:1,children:[(0,$.jsx)(y,{type:`large`,as:`h2`,children:t(`@theorem.agent.handle`,{handle:e.handle})}),(0,$.jsx)(y,{type:`display-2`,as:`h1`,children:t(`@theorem.live.greeting`)})]}),(0,$.jsxs)(o,{gap:2,wrap:`wrap`,children:[(0,$.jsx)(C,{label:t(e.voiceAvailable?`@theorem.live.start_voice_call`:`@theorem.live.start_call`),variant:`primary`,icon:(0,$.jsx)(p,{icon:H}),onClick:()=>e.startCall({video:!1})}),e.videoAvailable?(0,$.jsx)(C,{label:t(`@theorem.live.start_video_call`),variant:`secondary`,icon:(0,$.jsx)(p,{icon:U}),onClick:()=>e.startCall({video:!0})}):null]})]})})})}function It({model:e,captionsToggle:t}){let n=x(),r=Lt();return(0,$.jsx)(a,{ref:r,height:`100%`,hAlign:`center`,children:(0,$.jsxs)(a,{width:`100%`,maxWidth:jt,height:`100%`,gap:3,children:[(0,$.jsxs)(a,{gap:.5,children:[(0,$.jsx)(y,{type:`label`,color:`secondary`,children:n(`@theorem.agent.handle`,{handle:e.handle})}),(0,$.jsx)(y,{size:`sm`,color:`secondary`,children:b(n,e.liveState,e.activeTool)})]}),e.failure?(0,$.jsx)(ge,{status:`error`,role:`alert`,title:e.failure.error}):null,e.sessionEnded?(0,$.jsx)(ge,{status:`info`,role:`status`,title:e.sessionEnded}):null,(0,$.jsx)(s,{size:`fill`,children:(0,$.jsx)(a,{height:`100%`,vAlign:`end`,children:(0,$.jsx)(a,{width:`100%`,height:Mt,style:{color:`var(--color-icon-primary)`},"aria-hidden":`true`,children:(0,$.jsx)(we,{status:e.status,levelsRef:e.levelsRef,toolActive:e.toolActive,variant:`hero`})})})}),(0,$.jsx)(Rt,{model:e,captionsToggle:t})]})})}function Lt(){let e=(0,Y.useRef)(null);return(0,Y.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 Rt({model:e,captionsToggle:t}){let n=x(),r=!e.sessionActive,i=[];return e.voiceAvailable&&i.push((0,$.jsx)(V,{label:n(`@theorem.live.microphone`),tooltip:n(e.isMuted?`@theorem.live.unmute`:`@theorem.live.mute`),isIconOnly:!0,isPressed:!e.isMuted,isDisabled:r,icon:(0,$.jsx)(p,{icon:ee}),pressedIcon:(0,$.jsx)(p,{icon:Ee}),onPressedChange:e.handleToggleMic},`mic`)),e.videoAvailable&&(i.push((0,$.jsx)(V,{label:n(`@theorem.live.camera`),tooltip:n(e.isVideoOn?`@theorem.live.camera_off`:`@theorem.live.camera_on`),isIconOnly:!0,isPressed:e.isVideoOn,isDisabled:r,icon:(0,$.jsx)(p,{icon:U}),pressedIcon:(0,$.jsx)(p,{icon:ke}),onPressedChange:()=>{e.handleToggleVideo()}},`video`)),e.isVideoOn&&i.push((0,$.jsx)(w,{label:n(`@theorem.live.flip_camera`),tooltip:n(`@theorem.live.flip_camera`),variant:`ghost`,isDisabled:r,icon:(0,$.jsx)(p,{icon:Te}),onClick:()=>{e.handleFlipCamera()}},`flip`))),i.push((0,$.jsx)(Y.Fragment,{children:t},`captions`),e.canRestart?(0,$.jsx)(w,{label:n(`@theorem.live.start_call`),tooltip:n(`@theorem.live.start_call`),variant:`primary`,icon:(0,$.jsx)(p,{icon:H}),onClick:()=>{e.handleRestart()}},`call`):(0,$.jsx)(w,{label:n(`@theorem.live.end_call`),tooltip:n(`@theorem.live.end_call`),variant:`destructive`,isDisabled:r,icon:(0,$.jsx)(p,{icon:De}),onClick:e.handleEnd},`call`)),(0,$.jsx)(ue,{label:n(`@theorem.live.controls`),dividers:[`top`],centerContent:(0,$.jsx)(o,{gap:2,vAlign:`center`,children:i})})}function zt({model:e}){return(0,$.jsx)(Dt,{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)(Bt,{video:e.videoPreview,facingMode:e.videoFacingMode}):null})}function Bt({video:e,facingMode:t}){let n=x(),r=(0,Y.useRef)(null);return(0,Y.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,Y.useEffect)(()=>{e.style.transform=t===`user`?`scaleX(-1)`:``},[e,t]),(0,$.jsx)(j,{ratio:4/3,fit:`cover`,children:(0,$.jsx)(`div`,{ref:r,"aria-label":n(`@theorem.live.camera_preview`),role:`img`})})}var Vt=4,Ht=432,Ut={background:`transparent`,boxShadow:`none`};function Wt({prompt:e,agent:t,onResolve:n}){return(0,$.jsx)(T,{isOpen:e!==null,purpose:`required`,width:Ht,padding:Vt,style:Ut,onOpenChange:e=>{e||n({action:`deny`})},children:e?e.gate.kind===`auth`?(0,$.jsx)(N,{gate:e.gate,toolName:e.gate.tool,onAuthenticated:e=>{n({action:`auth`,secret:e})}}):(0,$.jsx)(M,{gate:e.gate,toolName:e.gate.tool,agent:t,input:e.input,onDecision:e=>{n({action:e})}}):null})}function Gt({runtime:e,...t}){let{payload:n}=t;return(0,$.jsx)(qt,{...t,connect:()=>e?At(n,e):A(n)})}function Kt({endpoint:e,...t}){let{actingAs:n}=be();return(0,$.jsx)(qt,{...t,connect:()=>({createSocket:()=>new WebSocket(ye(e,n))})})}function qt({payload:e,note:t,connect:n,trace:r,slots:i,stated:a,context:o}){let s=(0,Y.useMemo)(()=>l(e),[e]),c=(0,Y.useMemo)(()=>k(e),[e]);return s.type===`live`?(0,$.jsx)(Nt,{labels:P,iface:s,connection:()=>(t(),n()),trace:r,slots:i,stated:a,context:o,pageTools:c}):null}export{Kt as ProjectLive,Gt as StudioLive};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{C as e,H as t,S as n,U as r,Xt as i,er as a,ir as o,jt as s,rr as c,tr as l,w as u}from"./shaped-data-DCfLI4gb.js";var d=/^data:([^;,]+);base64,/;function f(e){if(typeof(e.mime_type??e.mimeType)==`string`&&typeof e.data==`string`)return`data`;if(typeof e.media_type==`string`&&typeof e.b64_json==`string`)return`b64_json`}var p=`sha256`,m=`text_sha256`;async function h(e){let t=await o(e);return t?{kind:p,hash:t.hash}:{kind:m,hash:await c(e)}}async function g(e){let t=d.exec(e);if(!t)return e;let{kind:n,hash:r}=await h(e.slice(t[0].length));return`data:${t[1]};${n},${r}`}async function _(e){let t=f(e),n,r=await Promise.all(Object.entries(e).map(async([e,r])=>{if(e===t&&typeof r==`string`){let{kind:t,hash:i}=await h(r);return n=t,[e,i]}return[e,await v(r)]})),i=Object.fromEntries(r);return n&&(i.dataKind=n),i}function v(e){return typeof e==`string`?g(e):Array.isArray(e)?Promise.all(e.map(e=>v(e))):e&&typeof e==`object`?_(e):Promise.resolve(e)}function y(e,t){return t.reduce((e,t)=>s(e,t),e)}function b(e,t){return t.some(Boolean)?l(e,e=>y(e,t)):e}async function x(e,t){return b(await v(e),t)}var S=`https://github.com/open-telemetry/semantic-conventions-genai/tree/8ffdf56`,C=`content_sha256`,w=`json_sha256`,T=[`gen_ai.usage.`,`theorem.usage.`],E={"theorem.upstream.row":`upstreamLog`,"theorem.wire.request":`outboundWire`,"theorem.guardrail":`guardrailDecisions`},D=`raw`,O=`match`,k=[`injection`,`tool_instructions`];function A(e,t){return e===!0||e!==!1&&e[t]}function j(e,{scrub:n,detect:o}){let{sensitive:s,injection:c}=n;return i(e,[...s?r(e,a,s,o):[],...A(s,`host`)?t(e,o):[],...c?r(e,k,c,o):[]])}async function M(e,t){let n=await c(e);return t.content[n]=e,t.known.set(e,n),n}function N(e,t){let{[t]:n,...r}=e;return r}async function P(t,r){if(e(t)){let e=y(j(t.$content,r),r.canaries);return{...N(t,`$content`),[C]:await M(e,r)}}if(n(t)){let e=N(t,`$bytes`),n=await o(t.$bytes);return n?{...e,content_sha256:n.hash,bytes:n.bytes}:{...e,invalid_base64:!0,text_sha256:await c(t.$bytes)}}return u(t)?t:await R(t,e=>P(e,r))}function F(e,t){return typeof e==`string`?t(e):Array.isArray(e)?e.map(e=>F(e,t)):e&&typeof e==`object`?Object.fromEntries(Object.entries(e).map(([e,n])=>[e,F(n,t)])):e}function I(e,t){return F(e,e=>{let n=j(e,t),r=t.known.get(n);return r?{[C]:r}:n})}async function L(e,t){if(u(e)){let n=await x(e.$json,t.canaries),r=JSON.stringify(I(n,t)),i=await c(r);return t.content[i]=r,{...N(e,`$json`),[w]:i}}return await R(e,e=>L(e,t))}async function R(e,t){if(Array.isArray(e))return await Promise.all(e.map(t));if(e&&typeof e==`object`){let n=await Promise.all(Object.entries(e).map(async([e,n])=>[e,await t(n)]));return Object.fromEntries(n)}return e}async function z(e,t){let n=await Promise.all(Object.entries(e).map(async([e,n])=>[e,await t(n)]));return Object.fromEntries(n)}async function B(e,t){let n=await Promise.all(e.events.map(async e=>({...e,attributes:await z(e.attributes,t)})));return{...e,attributes:await z(e.attributes,t),events:n}}function V(e,t){return t.usage?e:Object.fromEntries(Object.entries(e).filter(([e])=>!T.some(t=>e.startsWith(t))))}function H(e){return e.map(e=>{if(!e||typeof e!=`object`||Array.isArray(e))return e;let{[O]:t,...n}=e;return n})}function U(e,t){let n=E[e.name];if(n&&!t[n])return;if(e.name===`theorem.grounding`&&!t.evidenceRaw){let{[D]:t,...n}=e.attributes;return{...e,attributes:n}}let{hits:r}=e.attributes;return e.name===`theorem.guardrail`&&!t.guardrailMatchPreview&&Array.isArray(r)?{...e,attributes:{...e.attributes,hits:H(r)}}:e}function W(e,t){return{...e,attributes:V(e.attributes,t),events:e.events.flatMap(e=>U(e,t)??[])}}function G(e){return Object.entries(e).flatMap(([e,t])=>t?[e]:[])}async function K(e){let{policy:t}=e,n={scrub:t.scrub,detect:t.detect,canaries:A(t.scrub.canary,`theorem`)?e.canaries??[]:[],content:{},known:new Map},r=e.spans.map(e=>W(e,t.include)),[i]=r;i&&(i.attributes={...i.attributes,"theorem.record.include":G(t.include),"theorem.record.scrub":G(t.scrub)});let a=await Promise.all(r.map(e=>B(e,e=>P(e,n)))),o=await Promise.all(a.map(e=>B(e,e=>L(e,n))));return{v:3,schemaUrl:S,resource:{...t.resource},...e.metadata?{metadata:e.metadata}:{},spans:o,content:n.content}}function q(e,t){if(Array.isArray(t))return t.map(t=>q(e,t));if(!t||typeof t!=`object`)return t;let n=Object.fromEntries(Object.entries(t).map(([t,n])=>[t,q(e,n)])),{[C]:r,[w]:i,...a}=n,o=typeof r==`string`?e.content[r]:void 0;if(o!==void 0)return Object.keys(a).length===0?o:{...a,content:o};let s=typeof i==`string`?e.content[i]:void 0;if(s===void 0)return n;let c=q(e,JSON.parse(s));return Object.keys(a).length===0?c:c&&typeof c==`object`&&!Array.isArray(c)?{...c,...a}:n}export{q as n,K as t};
|
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
import{$t as e,C as t,En as n,M as r,h as i,j as a,n as o,p as s,qt as c,t as l,xn as ee,y as u,z as d}from"./tool-schema-BwaPiLtT.js";import{En as f,Fn as te,Rn as p,Sn as ne,Tn as re,Tr as m,Yn as ie,cn as ae,gn as h,qn as g,xr as _,zn as v}from"./shaped-data-DCfLI4gb.js";import{a as oe,r as y}from"./live-ingress-OuSlQ6q7.js";var se=[{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`}],ce={identity:te,inputs:p(`inputs`).filter(e=>e!==`decision`)},b=se.map(e=>({...e,profileTypes:ce[e.id]??p(e.profilePath)}));function le(e){return b.find(t=>t.id===e)}function ue(e){return e.modelBindings.length>1}function de(e){return e.modelBindings.some(t=>t.provider!==`local`&&!r(e.providers,t).keySlot)}function x(e,t){let n={provider:t.provider,keySlot:t.keySlot||e.models.key,fallbackKeySlot:t.fallbackKeySlot||e.models.fallbackKey},i=r(e.providers,n);return{...i,given:{keySlot:!!i.keySlot&&!n.keySlot,fallbackKeySlot:!!i.fallbackKeySlot&&!n.fallbackKeySlot}}}function fe(e,t){let n=new Set(e.modelBindings.filter(n=>{let r=x(e,n);return r.keySlot===t||r.fallbackKeySlot===t}).map(e=>e.provider));return e.providers.filter(e=>n.has(e.id))}function pe(e){let t=e.efforts.map(({alias:e})=>e.trim()).filter(Boolean);return new Set(t).size>1}function me(e){return e.attachmentsAccept.length>0||e.voiceAccept.length>0}var he=h,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:ne[0],permission:f[0],loadTier:re[0],paths:[`*`],inputJson:l,outputJson:o,...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:m(_,()=>`ignore`),patterns:[j()],hint:``}}function N(){let e=n(void 0);return{canaryBindNote:``,detect:m(v,t=>({...e.detect[t]})),sources:Object.fromEntries(g.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=oe({});return{writeTo:s,destination:s,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(e){let t=q(`slot`,e.map(e=>e.name),e=>`slot_${String(e)}`);return{key:E(`slot`),name:t,label:``,choices:[z(),z()]}}function xe(){return{key:E(`condition`),name:``,values:[]}}function z(){return{key:E(`choice`),value:``,description:``}}function Se(){return{key:E(`criterion`),label:``,text:``}}function B(e){return e===`noul`||e===`box`?[]:F(e===`choice`?[[`yes`,``],[`no`,``]]:[[``,``],[``,``]])}function Ce(){return{identity:{agentId:``,profileType:``,handle:``,system:``,conditions:[]},included:[`observability`,`labels`],models:{defaultModel:``,allowModelSelect:!1,maxSteps:null,key:``},modelBindings:[],providers:[...t],tools:{t2Loader:``,parallel:!1},toolSpecs:[],inputs:{text:!0,attachmentsAccept:[],voiceAccept:[],maxFiles:null,maxBytes:null,maxTurnBytes:null,limitsByMime:{},slots:[],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:e({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:y(`audio`),ingressVideo:y(`video`),ingressText:y(`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 we=new Set([`guardrails`]);function V(e,t){return e.profileTypes.includes(t)&&!(t===`decision`&&we.has(e.id))}function H(e){let t=e.identity.profileType;if(!t)return[`identity`];let n=new Set(e.included);return b.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!==``&&p(t).includes(n)}function Te(e){return U(e,`identity.system`)&&ie(e.guardrails.detect,`canary_leak`)}function Ee(e){let t=e.identity.profileType;return t!==``&&c.includes(t)}function W(e){let t=e.identity.profileType;return t?b.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=>ee(ae,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=u(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,n){if(t===`host`)return{...e,identity:{...e.identity,profileType:t}};let r=e.modelBindings.filter(r=>{let i=a(e.providers,t,r),o=e.providers.find(e=>e.id===r.provider);return d(o,t,r.protocol)&&!Fe(n,t,i)}),o={...e,identity:{...e.identity,profileType:t},modelBindings:r},s=r.length?r:[K(o,n?.start)],c=!e.models.key&&de({...o,modelBindings:s}),l=t===`speech`&&!e.speech.voice.trim()&&s.some(n=>i(a(e.providers,t,n)));return{...o,inputs:t===`image`?De(e.inputs):t===`transcription`?Oe(e.inputs):e.inputs,...l?{speech:{...e.speech,voice:Ne}}:{},models:{...e.models,defaultModel:G(e.models.defaultModel,s),key:c?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(b.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,M as F,x as G,Me as H,j as I,me as J,pe as K,be as L,ye as M,ve as N,Le as O,K as P,z as R,U as S,Re as T,Ee as U,Ae as V,ke as W,b as X,fe as Y,le as Z,C as _,Ge as a,D as b,$ as c,_e as d,ge as f,he as g,S as h,Ue as i,Se as j,xe as k,w as l,T as m,Be as n,Z as o,R as p,ue as q,ze as r,X as s,J as t,L as u,A as v,E as w,k as x,Ce as y,je as z};
|
package/slot-values.d.ts
DELETED
package/slot-values.js
DELETED
|
@@ -1,22 +0,0 @@
|
|
|
1
|
-
/** The values a slot's declaration lists, or undefined when it lists none a page could pick. */
|
|
2
|
-
export function choiceValues(decl) {
|
|
3
|
-
if (Array.isArray(decl) &&
|
|
4
|
-
decl.length > 0 &&
|
|
5
|
-
decl.every((value) => typeof value === 'string' && value.trim() !== '')) {
|
|
6
|
-
return decl;
|
|
7
|
-
}
|
|
8
|
-
const choices = isRecord(decl) ? decl.choices : undefined;
|
|
9
|
-
if (!Array.isArray(choices) || choices.length === 0)
|
|
10
|
-
return undefined;
|
|
11
|
-
const values = [];
|
|
12
|
-
for (const choice of choices) {
|
|
13
|
-
if (!isRecord(choice) || typeof choice.value !== 'string' || choice.value.trim() === '') {
|
|
14
|
-
return undefined;
|
|
15
|
-
}
|
|
16
|
-
values.push(choice.value);
|
|
17
|
-
}
|
|
18
|
-
return values;
|
|
19
|
-
}
|
|
20
|
-
function isRecord(value) {
|
|
21
|
-
return typeof value === 'object' && value !== null;
|
|
22
|
-
}
|