@theoremjs/studio 0.3.5-next.906.g6f050f4 → 0.3.5-next.911.g193d75c
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/browser-connection.d.ts +1 -2
- package/package.json +4 -4
- package/page/assets/{BottomSheet-v4keekfB.js → BottomSheet-gvxs6HLX.js} +1 -1
- package/page/assets/{ConsoleFrame-CHnnxxNA.js → ConsoleFrame-DjKftiM3.js} +1 -1
- package/page/assets/{DateInput-CYFXY_3W.js → DateInput-BpXRJu6W.js} +1 -1
- package/page/assets/{MenuBottomSheet-BR8JYBqn.js → MenuBottomSheet-C-aSCSIv.js} +1 -1
- package/page/assets/{PowerSearchBottomSheet-DSkpQQys.js → PowerSearchBottomSheet-CadUl0hQ.js} +1 -1
- package/page/assets/{RankedBars-C_arZO1h.js → RankedBars-BqvXkuhw.js} +1 -1
- package/page/assets/{SchemaFields-DvOp5_M3.js → SchemaFields-BA_tTlTT.js} +1 -1
- package/page/assets/{TokenizerBottomSheet-DjiTJgA9.js → TokenizerBottomSheet-BVgCEcFv.js} +1 -1
- package/page/assets/{ToolResultCharts-t1kqy-J6.js → ToolResultCharts-Ju_2APDe.js} +1 -1
- package/page/assets/{Toolbar-CkD1V_z_.js → Toolbar-Bodaemo6.js} +1 -1
- package/page/assets/{TraceInspector-CGGxz_g-.js → TraceInspector-CCjkzWyI.js} +2 -2
- package/page/assets/TraceOverview-BtC8GQVd.js +57 -0
- package/page/assets/{_virtual_studio-type-sources-CuPTbB69.js → _virtual_studio-type-sources-CdnMqL-n.js} +115 -66
- package/page/assets/browser-connection-8HG8E7-I.js +1 -0
- package/page/assets/browser-engine-nrFEmQVr.js +16 -0
- package/page/assets/{browser-transport-Dq9itWDy.js → browser-transport-C4b9Cns1.js} +2 -2
- package/page/assets/compile--gO-Z1FH.js +4 -0
- package/page/assets/{encode-files-Dc2wHsb6.js → encode-files-7UPrYBrF.js} +1 -1
- package/page/assets/{export-agent-Y0Y8mdbB.js → export-agent-CJU4yuZq.js} +1 -1
- package/page/assets/{getRadiusAndStrokeWidthFromDot-bzD-VA8b.js → getRadiusAndStrokeWidthFromDot-Ecj-jR5D.js} +1 -1
- package/page/assets/{guardrail-health-BGyQi_jA.js → guardrail-health-DFvepe74.js} +2 -2
- package/page/assets/{guardrail-tester-DbR85sml.js → guardrail-tester-D0nvciLt.js} +1 -1
- package/page/assets/{index-Cfhzi3KD.js → index-DdfSX5Od.js} +18 -18
- package/page/assets/{json-code-D2imJbsd.js → json-code-ChVouP8g.js} +1 -1
- package/page/assets/{labels-provider-CTjEbRdu.js → labels-provider-BO_XYaPQ.js} +1 -1
- package/page/assets/{live-messages-Bp_b714P.js → live-messages-BrXwocbM.js} +1 -1
- package/page/assets/{prompt-row-eETPWTfK.js → prompt-row-D7xmJLxc.js} +1 -1
- package/page/assets/reader-CfENH3jS.js +5 -0
- package/page/assets/registry-BOVP_lQO.js +1 -0
- package/page/assets/{schema-D4bn5YDU.js → schema-dtr41Lr7.js} +2 -2
- package/page/assets/shaped-data-9kDvR1de.js +25 -0
- package/page/assets/{stub-CZ_Xswg8.js → stub-B275bXj-.js} +1 -1
- package/page/assets/{studio-code-pane-lxwvQgJE.js → studio-code-pane-epOb7YCi.js} +3 -3
- package/page/assets/{studio-console-BNOXf-xr.js → studio-console-KObtCJyc.js} +1 -1
- package/page/assets/{studio-decision-C9oxa1xo.js → studio-decision-CJWMloET.js} +1 -1
- package/page/assets/{studio-embedding-D8rA6MOH.js → studio-embedding-CGKFrG_-.js} +1 -1
- package/page/assets/{studio-host-console-XPl__wj7.js → studio-host-console-C5oeUj4u.js} +2 -2
- package/page/assets/studio-labels-EVPkcfTG.js +3 -0
- package/page/assets/{studio-live-B3gN-hIU.js → studio-live-B6Iy_esj.js} +1 -1
- package/page/assets/{studio-map-Cf2DHvn2.js → studio-map-DnuXEuzm.js} +1 -1
- package/page/assets/{studio-trace-replay-BCOqVguH.js → studio-trace-replay-Dxc3ePxC.js} +1 -1
- package/page/assets/{studio-type-checker-BWW15y7M.js → studio-type-checker-Cg2BuLET.js} +1 -1
- package/page/assets/{tool-schema-BMNs-MyH.js → tool-schema-D6i-fwc5.js} +1 -1
- package/page/assets/{trace-record-CS_K7b8l.js → trace-record-DFHRIoSR.js} +1 -1
- package/page/assets/tree-DXvClIpQ.js +3 -0
- package/page/assets/{turn-client-8TS8z-jZ.js → turn-client-Cl1P1QP9.js} +2 -2
- package/page/assets/types-Bl2lxigr.js +1 -0
- package/page/assets/{use-one-call-Ch9fKeMJ.js → use-one-call-BKua0dRg.js} +1 -1
- package/page/assets/{useDismissSearchOnTouchDrag-DJ9Di3hZ.js → useDismissSearchOnTouchDrag-lH0YZH1H.js} +1 -1
- package/page/assets/{workspace-CCtOtOGD.js → workspace-BpEiFb5f.js} +1 -1
- package/page/index.html +17 -17
- package/page/assets/TraceOverview-C3RFiWfu.js +0 -57
- package/page/assets/browser-connection-UWxIyv6u.js +0 -1
- package/page/assets/browser-engine-Ds0-ThtZ.js +0 -16
- package/page/assets/compile-NWqVUG3a.js +0 -4
- package/page/assets/reader-C8mnJAB6.js +0 -5
- package/page/assets/registry-DJBxNVIO.js +0 -1
- package/page/assets/shaped-data-yrTrXPh4.js +0 -25
- package/page/assets/studio-labels-CUJQgb-k.js +0 -3
- package/page/assets/tree-D6WoHLJe.js +0 -3
- package/page/assets/types-D9SHTHld.js +0 -1
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{r as e}from"./rolldown-runtime-hePW80VL.js";import{d as t,l as n,r,u as i}from"./themeProps-Bo2jNkIC.js";import{t as a}from"./mergeProps-ptS-gIMz.js";import{t as o}from"./Icon-Cd9sDRzY.js";import{t as s}from"./Text-Cq4yqBpQ.js";import{t as c}from"./Button-Bwkht0RI.js";import{t as l}from"./Token-CGIAH1hn.js";import{w as u}from"./browser-transport-C4b9Cns1.js";import{t as d}from"./CodeBlock-QRlV-wmv.js";import{t as f}from"./createReactComponent-DVEyVJ-p.js";import{n as p}from"./useAdaptivePresentation-D53OuCPm.js";import{Ja as ee,Vt as te,Wa as ne,a as m,hn as h,ro as g}from"./shaped-data-9kDvR1de.js";import{k as _}from"./turn-client-Cl1P1QP9.js";import{n as v}from"./stub-B275bXj-.js";import{t as y}from"./Badge-BUFlIXVD.js";import{n as b,t as x}from"./labels-provider-BO_XYaPQ.js";import{t as S}from"./HStack-B00ufja5.js";import{t as re}from"./VStack-D1ZLA9g3.js";import{t as ie}from"./Card-C6l0Ne1A.js";import{n as C}from"./CollapsibleGroup-483UEs5v.js";import{t as w}from"./TextInput-DwHcdc-E.js";var T=f(`outline`,`flame`,`Flame`,[[`path`,{d:`M12 10.941c2.333 -3.308 .167 -7.823 -1 -8.941c0 3.395 -2.235 5.299 -3.667 6.706c-1.43 1.408 -2.333 3.294 -2.333 5.588c0 3.704 3.134 6.706 7 6.706c3.866 0 7 -3.002 7 -6.706c0 -1.712 -1.232 -4.403 -2.333 -5.588c-2.084 3.353 -3.257 3.353 -4.667 2.235`,key:`svg-0`}]]),E=[`cancelled`,`interrupted`,`length`,`filtered`,`provider_error`,`stream_incomplete`,`step_limit`,`answer_missing`],D=new Set(E);function O(e){return D.has(e)}function k(e,t,n){if(!e||!O(e.kind)||te(e)||t.some(e=>e.kind===`error`))return;let r=`stop.${e.kind}`;return g(r,{},n)}function A(e,t){let n=(n,r)=>{let i=new Set;return a=>{if(n(a),a.type!==`tool`||a.tool.phase!==`dispatch`)return;let{tool:o}=a;if(!e.pageResult||!o.operationId||r?.aborted)return;let s=JSON.stringify([o.operationId,o.grantId]);if(i.has(s))return;i.add(s);let c=t&&Object.hasOwn(t,o.name)?t[o.name]:void 0,l={callId:o.callId,operationId:o.operationId,grantId:o.grantId};Promise.resolve().then(async()=>{if(r?.aborted)return;let t=c?await Promise.resolve().then(()=>c(o.arguments,l)).catch(()=>({unanswered:!0})):{unanswered:!0};await e.pageResult?.({...l,page:t},r)}).catch(e=>{r?.aborted||n({type:`error`,errorKind:ne(e),error:ee(e)})})}},r=(e,t)=>{let r=n(e,t);return t=>t.type===`conversation`?e(t):r(t)};return`call`in e?{...e,describe:e.describe.bind(e),invoke:(t,r,i)=>e.invoke(t,n(r,i),i),call:(t,r,i)=>e.call(t,n(r,i),i)}:{...e,describe:e.describe.bind(e),invoke:(t,n,i)=>e.invoke(t,r(n,i),i),turn:(t,n,i)=>e.turn(t,r(n,i),i),steer:e.steer.bind(e),stop:e.stop.bind(e),conversation:e.conversation.bind(e),rewind:e.rewind.bind(e)}}function j(e){if(e.resolution.action===`deny`)return{decision:`deny`};let{resolution:t}=e;return{decision:`approve`,...t.action===`auth`&&t.secret!==void 0?{secret:t.secret}:{},...t.action===`page`?{page:t.page}:{},sessionPermissions:_(e.sessionPermissions,e.toolName,e.gate.permission)}}var M=`theorem.oauth_complete`;function N(e,t){if(e.source!==t.popup||e.origin!==t.origin)return!1;let n=e.data;return h(n)&&n.type===M&&n.slot===t.slot}function P(e){return{openMessage:{type:`draft`,profile:e.profile,customTools:e.customTools}}}function F(e){let t={};for(let n of e.customTools){if(n.type!==`function`||n.answeredBy!==`page`)continue;let e=n.stubResponse??v(n.outputSchema);t[n.name]=()=>({output:e})}return t}var I=n(),L={container:{kVAEAm:`x1n2onr6`,kzqmXN:`xh8yej3`,kVQacm:`x7giv3`,kAzted:`x2lwn1j`,kmuXW:`x2lah0s`,$$css:!0},ellipse:{kaIpWk:`x16rqkct`,$$css:!0}},R={ratio:e=>[{kOBAk4:e==null?e:`x10y9f9r`,$$css:!0},{"--x-aspectRatio":e??void 0}]};function z({ratio:e,shape:t=`rectangle`,fit:n,children:o,xstyle:s,className:c,style:l,ref:u,...d}){return(0,I.jsx)(`div`,{ref:u,...a(r(`aspect-ratio`,{shape:t}),i(L.container,R.ratio(e),t===`ellipse`&&L.ellipse,s),c,l),...d,children:(0,I.jsx)(`div`,{"data-astryx-aspect-ratio-override":n,...{0:{className:`x10l6tqk x13vifvy x1o0tod xh8yej3 x5yr21d`},8:{className:`x10l6tqk x13vifvy x1o0tod xh8yej3 x5yr21d x78zum5 x6s0dn4 xl56j7k`},4:{className:`x10l6tqk x13vifvy x1o0tod xh8yej3 x5yr21d xyz6fim x1m6kvgq`},12:{className:`x10l6tqk x13vifvy x1o0tod xh8yej3 x5yr21d x78zum5 x6s0dn4 xl56j7k xyz6fim x1m6kvgq`},2:{className:`x10l6tqk x13vifvy x1o0tod xh8yej3 x5yr21d x492jj3`},10:{className:`x10l6tqk x13vifvy x1o0tod xh8yej3 x5yr21d x78zum5 x6s0dn4 xl56j7k x492jj3`},6:{className:`x10l6tqk x13vifvy x1o0tod xh8yej3 x5yr21d xyz6fim x1m6kvgq x492jj3`},14:{className:`x10l6tqk x13vifvy x1o0tod xh8yej3 x5yr21d x78zum5 x6s0dn4 xl56j7k xyz6fim x1m6kvgq x492jj3`},1:{className:`x10l6tqk x13vifvy x1o0tod xh8yej3 x5yr21d x16lv2iq`},9:{className:`x10l6tqk x13vifvy x1o0tod xh8yej3 x5yr21d x78zum5 x6s0dn4 xl56j7k x16lv2iq`},5:{className:`x10l6tqk x13vifvy x1o0tod xh8yej3 x5yr21d xyz6fim x1m6kvgq x16lv2iq`},13:{className:`x10l6tqk x13vifvy x1o0tod xh8yej3 x5yr21d x78zum5 x6s0dn4 xl56j7k xyz6fim x1m6kvgq x16lv2iq`},3:{className:`x10l6tqk x13vifvy x1o0tod xh8yej3 x5yr21d x16lv2iq`},11:{className:`x10l6tqk x13vifvy x1o0tod xh8yej3 x5yr21d x78zum5 x6s0dn4 xl56j7k x16lv2iq`},7:{className:`x10l6tqk x13vifvy x1o0tod xh8yej3 x5yr21d xyz6fim x1m6kvgq x16lv2iq`},15:{className:`x10l6tqk x13vifvy x1o0tod xh8yej3 x5yr21d x78zum5 x6s0dn4 xl56j7k xyz6fim x1m6kvgq x16lv2iq`}}[(n===`center`)<<3|(n===`cover`||n===`contain`)<<2|(n===`cover`)<<1|n===`contain`],children:o})})}z.displayName=`AspectRatio`;function B(e,t){if(!e)return t;let n=e.total+t.total;return!e.cost&&!t.cost?{total:n}:{total:n,cost:{usd:(e.cost?.usd??0)+(t.cost?.usd??0),...!e.cost||!t.cost||e.cost.partial||t.cost.partial?{partial:!0}:{}}}}var V={citation:`last`};function H(e,t){if(!t)return[...e];let n=[],r=[],i=[];for(let a of e){let e=t[a.kind];e===`first`?n.push(a):e===`last`?i.push(a):r.push(a)}return[...n,...r,...i]}var U=new Set(E),W=new Set([`user-text`,`user-attachment`,`user-voice`]);function G(e){return W.has(e.kind)}function K(e){return e.kind===`turn-done`}function ae(e,t){e?.kind===`user`?t.stop&&U.has(t.stop.kind)&&(e.stop=t.stop):e&&(t.workedMs!==void 0&&(e.workedMs=t.workedMs,e.endedAt=t.endedAt),t.tokens&&(e.usage=B(e.usage,t.tokens)),t.stop&&(e.stop=t.stop))}function q(e,t){return!e||e.kind!==(t?`user`:`assistant`)?!1:!(e.kind===`user`&&e.stop)}function J(e,t){let n=[];for(let r of e){if(r.kind===`turn-done`&&ae(n.at(-1),r),K(r))continue;let e=G(r),i=n.at(-1);i&&q(i,e)&&!t?.has(r.id)?i.blocks.push(r):n.push({kind:e?`user`:`assistant`,key:r.id,blocks:[r]})}return n}function oe(e){return e.filter(e=>e.kind===`text`).map(e=>e.text).filter(Boolean).join(`
|
|
2
|
+
|
|
3
|
+
`)}function se(e){let t=e.elapsedMs===void 0?{}:{elapsedMs:e.elapsedMs};return e.streaming?{phase:`working`,...t}:e.elapsedMs!==void 0&&e.elapsedMs>0?{phase:`worked`,elapsedMs:e.elapsedMs}:e.hasTrace?{phase:`worked`}:null}function ce(e){return e.kind===`tool`&&e.tool.state?.phase===`gate`}function le(e){for(let t=e.length-1;t>=0;--t)if(e[t]?.kind===`tool`)return t;return-1}function ue(e,t,n,r){t.hasTools&&t.index<t.lastToolIndex?e.text.trim()&&n.push({kind:`narration`,id:e.id,text:e.text}):r.push(e)}function de(e,t,n,r){e.kind===`thought`?e.text.trim()&&n.push({kind:`reasoning`,id:e.id,text:e.text}):e.kind===`tool`?n.push({kind:`tool`,id:e.id,block:e}):e.kind===`text`?ue(e,t,n,r):r.push(e)}function fe(e,t){let n=e.filter(e=>!K(e)),r=n.find(ce),i=r?[r]:[],a=n.filter(e=>e!==r),o=le(a),s=o>=0,c=[],l=[];for(let[e,t]of a.entries())de(t,{hasTools:s,index:e,lastToolIndex:o},c,l);return{trace:c,gatedTools:i,body:H(l,t?.bodyKindPlacement??V),hasTrace:c.length>0}}function pe(e){let t=e.at(-1);return t?.kind===`user`?t:void 0}function Y(e,t){let n=e[t-1];return n?.kind===`user`?X(n):e[t]?.key??String(t)}function X(e){return`${e.key}:reply`}function me(e,t,n){let r=e[t+1];return r?.kind===`assistant`&&r.endedAt!==void 0&&r.workedMs!==void 0?r.endedAt-r.workedMs:n(e[t]?.key??``)}function he(e){let t=Y(e.groups,e.index),n=e.streaming&&e.index===e.groups.length-1,r=e.groups[e.index];if(!n)return r?.kind===`assistant`&&r.workedMs!==void 0?{key:t,live:n,workedMs:r.workedMs,endedAt:r.endedAt}:{key:t,live:n};let i=e.groups[e.index-1],a=i?.kind===`user`?e.spans.get(i.key):void 0;return!i||!a?{key:t,live:n}:{key:t,live:n,startedAt:e.timeOf(i.key)+a.pausedMs}}function ge(e){let t=e.state?.phase;return t===`cancel`?m(e.name):(t===`complete`||t===`error`?e.activityPast:e.activity)??m(e.name)}var Z=e(t(),1);function _e(e,t,n,r){let i=t.request??e(`@theorem.gate.approval.use_tool`,{tool:m(n).toLowerCase()});return r?e(`@theorem.gate.approval.title`,{agent:r,request:i}):e(`@theorem.gate.approval.title_no_agent`,{request:i})}var ve={outline:`none`};function ye(e){return typeof e==`string`?e:e==null?``:JSON.stringify(e,null,2)}function Q(e){return(0,I.jsx)(ie,{variant:`bubble`,elevation:`med`,maxWidth:400,children:(0,I.jsxs)(re,{gap:3,children:[(0,I.jsxs)(S,{justify:`between`,align:`start`,gap:3,children:[(0,I.jsx)(s,{type:`large`,weight:`semibold`,tabIndex:-1,"data-autofocus":!0,style:ve,children:e.heading}),e.tag]}),e.children]})})}var be={"read-only":p,"read-write":u,destructive:T};function $({access:e}){let t=b();return(0,I.jsxs)(S,{gap:1,align:`center`,children:[(0,I.jsx)(o,{icon:be[e],size:`sm`,color:e===`destructive`?`error`:`secondary`}),(0,I.jsx)(s,{type:`supporting`,textWrap:`nowrap`,children:t(`@theorem.tool.access.${e}`)})]})}function xe(e){return(0,I.jsx)(x,{children:(0,I.jsx)(Se,{...e})})}function Se({gate:e,toolName:t,agent:n,input:r,decided:i=null,onDecision:a}){let o=b(),l=ye(e.preparedArguments??r);return(0,I.jsxs)(Q,{heading:_e(o,e,t,n),tag:e.access?(0,I.jsx)($,{access:e.access}):null,children:[e.summary?(0,I.jsx)(s,{color:`secondary`,children:e.summary}):null,l?(0,I.jsx)(C,{defaultIsOpen:!1,trigger:(0,I.jsx)(s,{type:`supporting`,children:o(`@theorem.gate.approval.input`)}),children:(0,I.jsx)(d,{code:l,language:`json`,size:`sm`})}):null,(0,I.jsxs)(S,{gap:2,justify:`end`,children:[(0,I.jsx)(c,{label:o(`@theorem.gate.approval.deny`),variant:`ghost`,isLoading:i===`deny`,isDisabled:i===`allow`,onClick:()=>a?.(`deny`)}),(0,I.jsx)(c,{label:o(`@theorem.gate.approval.approve`),variant:`primary`,isLoading:i===`allow`,isDisabled:i===`deny`,onClick:()=>a?.(`allow`)})]})]})}function Ce({challenge:e}){let t=b();return(0,I.jsxs)(I.Fragment,{children:[(0,I.jsx)(s,{color:`secondary`,children:e.message}),e.resource?(0,I.jsx)(s,{type:`supporting`,color:`secondary`,children:t(`@theorem.gate.auth.resource`,{resource:e.resource})}):null,e.requiredScopes?.length?(0,I.jsx)(S,{gap:1,wrap:`wrap`,children:e.requiredScopes.map(e=>(0,I.jsx)(l,{label:e,size:`sm`},e))}):null]})}function we(e){return(0,I.jsx)(x,{children:(0,I.jsx)(Ee,{...e})})}function Te(e,t){let[n,r]=(0,Z.useState)(null);return(0,Z.useEffect)(()=>{if(!n)return;function i(i){n&&N(i,{popup:n,slot:e,origin:globalThis.location.origin})&&(r(null),t())}return globalThis.addEventListener(`message`,i),()=>globalThis.removeEventListener(`message`,i)},[n,e,t]),e=>r(globalThis.open(e,`_blank`,`width=600,height=700`))}function Ee({gate:e,toolName:t,onAuthenticated:n,submitted:r=!1}){let i=b(),a=e.authChallenge,{authType:o,slot:c}=a,[l,u]=(0,Z.useState)(``),d=Te(c,(0,Z.useCallback)(()=>n?.(),[n]));function f(){let e=l.trim();e&&(u(``),n?.(e))}return(0,I.jsxs)(Q,{heading:i(`@theorem.gate.auth.title`,{tool:m(t).toLowerCase()}),tag:(0,I.jsx)(s,{type:`supporting`,textWrap:`nowrap`,children:i(`@theorem.gate.tag.${o}`)}),children:[(0,I.jsx)(Ce,{challenge:a}),(0,I.jsx)(De,{authType:o,authUrl:a.authorizationUrl,slot:c,secret:l,submitted:r,onSecretChange:u,onSubmit:f,onOpenSignIn:d})]})}function De(e){let t=b();if(e.submitted)return(0,I.jsx)(y,{variant:`success`,label:t(`@theorem.gate.auth.provided`,{slot:e.slot})});if(e.authType===`oauth2`)return e.authUrl?(0,I.jsx)(S,{justify:`end`,children:(0,I.jsx)(c,{label:t(`@theorem.gate.auth.authorize`),variant:`primary`,onClick:()=>{e.authUrl&&e.onOpenSignIn(e.authUrl)}})}):(0,I.jsx)(s,{color:`secondary`,children:t(`@theorem.gate.auth.no_oauth`)});let n=t(e.authType===`api_key`?`@theorem.gate.auth.api_key`:`@theorem.gate.auth.bearer`),r=t(`@theorem.gate.auth.secret_note`).trim();return(0,I.jsxs)(S,{gap:2,align:`end`,children:[(0,I.jsx)(w,{type:`password`,label:n,...r?{description:r}:{},value:e.secret,placeholder:t(`@theorem.gate.auth.secret_placeholder`,{slot:e.slot}),autoComplete:`off`,onChange:e.onSecretChange,onEnter:e.onSubmit,width:`100%`}),(0,I.jsx)(c,{label:t(`@theorem.gate.auth.submit`),variant:`primary`,isDisabled:!e.secret.trim(),onClick:e.onSubmit})]})}var Oe={en:{"@theorem.gate.auth.secret_note":`Used for this call only. theorem doesn't store it.`,"@astryx.chat.status.sending":`sending`,"@astryx.chat.status.sent":`sent`,"@astryx.chat.status.delivered":`delivered`,"@astryx.chat.status.read":`read`}};export{j as _,he as a,T as b,pe as c,Y as d,ge as f,F as g,P as h,oe as i,X as l,z as m,xe as n,fe as o,se as p,we as r,J as s,Oe as t,me as u,A as v,k as y};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{r as e}from"./rolldown-runtime-hePW80VL.js";import{d as t,l as n}from"./themeProps-Bo2jNkIC.js";import{n as r,t as i}from"./LayoutContent-BWpUj2Iy.js";import{t as a}from"./Icon-Cd9sDRzY.js";import{a as o,c as s,l as c,p as l,u}from"./SidePanel-DcAhRInK.js";import{t as d}from"./Text-Cq4yqBpQ.js";import{t as f}from"./Button-Bwkht0RI.js";import{b as p,g as m,p as h,s as g,t as _}from"./browser-transport-Dq9itWDy.js";import{t as v}from"./createReactComponent-DVEyVJ-p.js";import{t as y}from"./Center-CPu_uP6i.js";import{_ as b,g as x,h as S,m as C,n as w,r as T,t as ee}from"./studio-labels-CUJQgb-k.js";import{t as E}from"./IconMicrophone-BT77cilC.js";import{Ba as D,ba as O,to as k,ya as A}from"./shaped-data-yrTrXPh4.js";import{c as j}from"./host-patterns-F-KZIzkF.js";import{S as M,g as N,r as P,t as F}from"./reader-C8mnJAB6.js";import{i as I}from"./live-ingress-OuSlQ6q7.js";import{i as te,y as ne}from"./turn-client-8TS8z-jZ.js";import{r as re,t as ie}from"./live-messages-Bp_b714P.js";import{t as ae}from"./EmptyState-DW-8doL9.js";import"./use-second-ticker-Dd57a-0O.js";import{a as oe,n as L,t as R}from"./labels-provider-CTjEbRdu.js";import{t as z}from"./HStack-B00ufja5.js";import{t as B}from"./IconButton-BenRR-zK.js";import{t as V}from"./VStack-D1ZLA9g3.js";import{t as se}from"./StackItem-nWHq5y--.js";import{t as ce}from"./Toolbar-CkD1V_z_.js";import{t as le}from"./Dialog-tyH-Jv5A.js";import{Gt as ue,H as de,Kt as fe,L as pe,M as me,Rt as he,S as ge,St as _e,T as H,b as ve,j as U,pt as ye,qt as be,tn as xe,u as Se}from"./index-Cfhzi3KD.js";var Ce=v(`outline`,`arrows-diagonal-minimize-2`,`ArrowsDiagonalMinimize2`,[[`path`,{d:`M18 10h-4v-4`,key:`svg-0`}],[`path`,{d:`M20 4l-6 6`,key:`svg-1`}],[`path`,{d:`M6 14h4v4`,key:`svg-2`}],[`path`,{d:`M10 14l-6 6`,key:`svg-3`}]]),we=v(`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`}]]),Te=v(`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`}]]),Ee=v(`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`}]]),W=v(`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`}]]),De=v(`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`}]]),Oe=v(`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`}]]),G=v(`outline`,`video`,`Video`,[[`path`,{d:`M15 10l4.553 -2.276a1 1 0 0 1 1.447 .894v6.764a1 1 0 0 1 -1.447 .894l-4.553 -2.276v-4`,key:`svg-0`}],[`path`,{d:`M3 8a2 2 0 0 1 2 -2h8a2 2 0 0 1 2 2v8a2 2 0 0 1 -2 2h-8a2 2 0 0 1 -2 -2l0 -8`,key:`svg-1`}]]);function ke(e){return e.status===`reconnecting`?`reconnecting`:e.toolName?`calling_tool`:e.connectPhase===`socket`?`connecting`:e.connectPhase===`microphone`?`requesting_mic`:e.status===`speaking`?`speaking`:e.status===`listening`||e.status===`ready`?e.voiceEnabled===!1?`connected`:e.isMuted?`muted`:`listening`:e.status===`connecting`?`connecting`:e.status===`error`?`error`:`ended`}function Ae(e){return!(e.isMuted||!e.socketOpen||e.modelPlaying&&e.rms<e.bargeInRmsWhileSpeaking)}function je(e){let{evidence:t,text:n}=e;return!n||t.kind!==`input_transcription`&&t.kind!==`output_transcription`?null:{text:n,isUser:t.kind===`input_transcription`,interim:t.interim===!0}}function Me(e,t){if(e.phase===void 0){t.toolCalls.push({id:e.callId,name:e.name,arguments:e.arguments,...e.operationId?{operationId:e.operationId}:{}});return}if(e.phase===`cancel`){t.cancelledToolIds.add(e.callId);return}if(e.phase!==`error`)return;let n=t.toolCalls.findIndex(t=>t.id===e.callId);n!==-1&&t.toolCalls.splice(n,1)}var K=new Set;async function Ne(e){let{executeToolOnRelay:t,name:n,toolArgs:r,callId:i,operationId:a}=e,o=e.pageTools&&Object.hasOwn(e.pageTools,n)?e.pageTools[n]:void 0,s=await t({callId:i,operationId:a}),c=new Set;for(;s.status!==`settled`;){if(s.status===`dispatched`){if(c.has(s.grantId))return;c.add(s.grantId);let e=s.grantId,r=s.arguments;!o&&!K.has(n)&&(K.add(n),console.warn(`Theorem: page tool '${n}' has no handler in pageTools; the agent gets no answer.`));let l=o?await Promise.resolve().then(()=>o(r,{callId:i,operationId:a})).catch(()=>void 0):void 0;s=await t({callId:i,operationId:a,grantId:e,...l?{output:l.output}:{unanswered:!0}});continue}let{gate:l}=s,u=l.kind===`page`||!e.onGate?{decision:`deny`}:await e.onGate({callId:i,toolName:n,input:l.preparedArguments??r,gate:l});if(u===`withdrawn`)return;if(u.decision===`deny`){await t({callId:i,operationId:a,decision:`deny`});return}s=await t({callId:i,decision:`approve`,operationId:a,...u.secret===void 0?{}:{secret:u.secret}})}}function Pe(e){if(!(e instanceof Error))return!1;let t=`name`in e&&typeof e.name==`string`?e.name:``;return t===`NotAllowedError`||t===`PermissionDeniedError`||/permission|not allowed|denied/i.test(e.message)}var Fe=`mic-capture-processor`;function Ie(){return new URL(`data:text/javascript;base64,LyoqCiAqIEF1ZGlvV29ya2xldCBwcm9jZXNzb3IgdGhhdCBmb3J3YXJkcyBtb25vIG1pYyBmcmFtZXMgdG8gdGhlIG1haW4gdGhyZWFkLgogKiBQbGFpbiBKUzogaXQgcnVucyBpbiB0aGUgQXVkaW9Xb3JrbGV0R2xvYmFsU2NvcGUgYXMgaXRzIG93biBtb2R1bGUsIGxvYWRlZAogKiBieSBVUkwgKHNlZSBgLi4vbWljLWNhcHR1cmUudHNgKSwgc28gaXQgaW1wb3J0cyBub3RoaW5nIGFuZCBzaGlwcyBhcyBpcy4KICovCnJlZ2lzdGVyUHJvY2Vzc29yKAogICdtaWMtY2FwdHVyZS1wcm9jZXNzb3InLAogIGNsYXNzIE1pY0NhcHR1cmVQcm9jZXNzb3IgZXh0ZW5kcyBBdWRpb1dvcmtsZXRQcm9jZXNzb3IgewogICAgcHJvY2VzcyhpbnB1dHMpIHsKICAgICAgY29uc3QgY2hhbm5lbCA9IGlucHV0c1swXVswXTsKICAgICAgY29uc3QgY29weSA9IG5ldyBGbG9hdDMyQXJyYXkoY2hhbm5lbCk7CiAgICAgIHRoaXMucG9ydC5wb3N0TWVzc2FnZShjb3B5LCBbY29weS5idWZmZXJdKTsKICAgICAgcmV0dXJuIHRydWU7CiAgICB9CiAgfSwKKTsK`,``+import.meta.url)}function Le(e,t,n=16e3){if(t===n)return Re(e);let r=t/n,i=Math.round(e.length/r),a=new Int16Array(i),o=0,s=0;for(;o<a.length;){let t=Math.round((o+1)*r),n=0,i=0;for(let r=s;r<t&&r<e.length;r++)n+=e[r]??0,i++;a[o]=q(i>0?n/i:0),o++,s=t}return a}function Re(e){let t=new Int16Array(e.length);for(let n=0;n<e.length;n++)t[n]=q(e[n]??0);return t}function q(e){let t=Math.max(-1,Math.min(1,e));return t<0?t*32768:t*32767}function ze(e){let t=new DataView(e.buffer,e.byteOffset,e.byteLength),n=new Float32Array(e.byteLength/2);for(let e=0;e<n.length;e++){let r=t.getInt16(e*2,!0);n[e]=r/(r<0?32768:32767)}return n}function J(e){return JSON.stringify(e)}function Be(){return{toolCalls:[],mediaChunks:[],cancelledToolIds:new Set}}var Ve=.05,He=[500,1e3,2e3,4e3,8e3];function Y(e){return e instanceof Error?e:new j(`internal`,D(e),{cause:e})}function X(e){if(e&&typeof e.disconnect==`function`)try{e.disconnect()}catch{}}function Ue(e){if(e&&typeof e.getTracks==`function`)for(let t of e.getTracks())t.stop()}function We(e){let t=ue(e.inputFloat32),n=e.hasPlaybackNodes||e.status===`speaking`;return Ae({isMuted:e.isMuted,socketOpen:e.wsOpen,modelPlaying:n,rms:t,bargeInRmsWhileSpeaking:Ve})}function Ge(e,t){return e===`listening`&&t?`working`:e===`working`&&!t?`listening`:null}var Ke=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 j(`network`,`live session closed before call ${e} settled`));if(this.pendingExecuteResults.clear(),this.ws){this.ws.onopen=null,this.ws.onmessage=null,this.ws.onclose=null,this.ws.onerror=null;try{this.ws.close()}catch{}this.ws=null}}clearReconnect(){this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=null,this.reconnectTries=0,this.droppedAt=void 0}teardownConnection(){this.clearConnectTimeout(),this.micActivating=!1,this.setConnectPhase(null),this.detachWebSocket(),this.cleanupAudio()}failSession(e){this.status!==`error`&&this.status!==`disconnected`&&(this.clearReconnect(),this.teardownConnection(),this.options.onError?.(e),this.setStatus(`error`))}createSocket(e){return this.options.createSocket?.()??new WebSocket(e)}connect(){let e=this.lostAt;return this.clearReconnect(),this.lostAt=void 0,e===void 0?(this.providerState=void 0,this.history=[]):this.droppedAt=e,this.open(`connecting`)}startOver(){return this.status!==`connecting`||!this.providerState?!1:(this.providerState=void 0,this.droppedAt=void 0,this.open(`connecting`),!0)}openMessage(){let{options:e,stated:t,model:n,effort:r,openMessage:i}=this.options;return{type:`open`,...this.history.length?{history:structuredClone(this.history)}:{},...e?{options:e}:{},...t?{stated:t}:{},...n?{model:n}:{},...r?{effort:r}:{},...this.context===void 0?{}:{context:this.context},...this.providerState?{resume:{providerState:this.providerState,awayMs:this.droppedAt===void 0?0:Date.now()-this.droppedAt}}:{},...i?{host:i}:{}}}handleDrop(){!this.providerState||this.sessionOver?(this.teardownConnection(),this.setStatus(`disconnected`)):(this.droppedAt??=Date.now(),this.teardownConnection(),this.setStatus(`reconnecting`),this.scheduleReconnect())}scheduleReconnect(){let e=He[this.reconnectTries];if(e===void 0){let e=this.droppedAt;this.failSession(new j(`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 j(`timeout`,`live connect timed out`))},2e4),this.ws.onmessage=e=>{this.enqueueServerMessage(e.data)},this.ws.onclose=()=>{this.opening?this.failOpen(new j(`network`,`live socket closed before ready`)):this.handleDrop()},this.ws.onerror=()=>{!this.opening&&this.providerState&&!this.sessionOver?this.handleDrop():this.failOpen(new j(`network`,`live socket error`))}}catch(e){this.failOpen(new j(`internal`,D(e),{cause:e}))}}async ensureAudioContext(){if(!this.audioContext||this.audioContext.state===`closed`){let e=globalThis.AudioContext;this.audioContext=new e,this.audioContext.state===`suspended`&&await this.audioContext.resume()}}async activateMicrophone(){if(!this.micActivating&&this.opening){this.micActivating=!0,this.status===`connecting`&&this.setConnectPhase(`microphone`);try{await this.ensureAudioContext(),this.micStream=await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}}),await this.setupMicrophonePipeline(),this.becomeReady()}catch(e){let t=Pe(e);this.failSession(new j(t?`auth`:`internal`,D(e),{cause:e,copy:{key:t?`voice.permission`:`voice.unavailable`}}))}finally{this.micActivating=!1}}}sendMicFrame(e,t){let n=Le(e,t,16e3),r=O(new Uint8Array(n.buffer)),i=this.ws;i?.readyState===WebSocket.OPEN&&i.send(J({type:`audio`,data:r}))}reportMicVolume(e){this.isMuted||this.options.onVolumeLevel?.(fe(e),!0)}forwardMicBuffer(e){if(this.reportMicVolume(e),We({isMuted:this.isMuted,wsOpen:this.ws?.readyState===WebSocket.OPEN,hasPlaybackNodes:this.playbackNodes.length>0,status:this.status,inputFloat32:e})){let t=this.audioContext?this.audioContext.sampleRate:48e3;this.sendMicFrame(e,t)}}async setupMicrophonePipeline(){if(!this.micStream||!this.audioContext)return;this.micSource=this.audioContext.createMediaStreamSource(this.micStream);let e=this.audioContext.createGain();e.gain.value=0,this.micWorkletModuleLoaded||=(await this.audioContext.audioWorklet.addModule(Ie()),!0),this.micWorklet=new AudioWorkletNode(this.audioContext,Fe),this.micWorklet.port.onmessage=e=>{let t=new Float32Array(e.data);this.forwardMicBuffer(t)},this.micSource.connect(this.micWorklet),this.micWorklet.connect(e),e.connect(this.audioContext.destination)}ensurePlaybackBus(){this.audioContext&&!this.playbackBus&&(this.playbackBus=this.audioContext.createGain(),this.playbackAnalyser=this.audioContext.createAnalyser(),this.playbackAnalyser.fftSize=512,this.playbackAnalyser.smoothingTimeConstant=.35,this.playbackBus.connect(this.playbackAnalyser),this.playbackAnalyser.connect(this.audioContext.destination),this.playbackMeterBuffer=new Uint8Array(this.playbackAnalyser.fftSize))}stopPlaybackMeter(){this.playbackMeterFrame&&=(cancelAnimationFrame(this.playbackMeterFrame),0),this.options.onVolumeLevel?.(0,!1)}startPlaybackMeter(){if(this.playbackMeterFrame)return;let e=()=>{this.playbackNodes.length===0||!this.playbackAnalyser||!this.playbackMeterBuffer?this.stopPlaybackMeter():(this.playbackAnalyser.getByteTimeDomainData(this.playbackMeterBuffer),this.options.onVolumeLevel?.(be(this.playbackMeterBuffer),!1),this.playbackMeterFrame=requestAnimationFrame(e))};this.playbackMeterFrame=requestAnimationFrame(e)}async processServerEnvelope(e){if(await this.tryHandleControlEnvelope(e)||e.type!==`events`)return;let t=this.collectInboundTurn(e.events),n=t.toolCalls.filter(e=>!t.cancelledToolIds.has(e.id));for(let e of n)this.toolChain=this.toolChain.then(()=>Ne({executeToolOnRelay:e=>this.executeToolOnRelay(e),pageTools:this.options.pageTools,onGate:this.options.onGate,name:e.name,toolArgs:e.arguments,callId:e.id,operationId:te(e)})).catch(e=>{this.options.onError?.(Y(e))});this.scheduleMediaChunks(t.mediaChunks)}enqueueServerMessage(e){this.inboundChain=this.inboundChain.then(async()=>{if(typeof e!=`string`)return;let t=re(e);t.type===`unsupported`||t.type===`malformed`?this.options.onTurnEvent?.(t):await this.processServerEnvelope(t)}).catch(e=>{this.options.onError?.(Y(e))})}async handleReadyEnvelope(e){this.options.onSessionReady?.({sessionId:e.sessionId,profile:e.profile}),this.options.voiceIngress===!1?this.becomeReady():await this.activateMicrophone()}becomeReady(){this.clearReconnect(),this.setConnectPhase(null),this.setStatus(`listening`),this.flushContext()}handleExecuteToolResultEnvelope(e){let t=this.pendingExecuteResults.get(e.operationId);t&&t.callId===e.callId&&(this.pendingExecuteResults.delete(e.operationId),e.status===`refused`?t.reject(M(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?.(M(e,`unavailable`)),this.setStatus(`error`)),!0)}collectInboundTurn(e){let t=Be();for(let n of e)this.processTurnEvent(n,t);return t}processTurnEvent(e,t){switch(e.type===`provider_checkpoint`&&e.history&&(this.history=structuredClone(e.history)),(e.type===`provider_checkpoint`||e.type===`done`)&&e.providerState&&(this.providerState=e.providerState),e.type===`provider_warning`&&(this.providerState=void 0),this.options.onTurnEvent?.(e),e.type){case`evidence`:this.handleEvidenceTurnEvent(e);break;case`session`:this.handleSessionTurnEvent(e);break;case`media`:this.collectMediaTurnEvent(e,t);break;case`tool`:Me(e.tool,t);break;case`done`:this.handleDoneTurnEvent(e)}}handleEvidenceTurnEvent(e){let t=je(e);t&&this.options.onTranscript?.(t.text,t.isUser,{interim:t.interim})}handleSessionTurnEvent(e){if(this.notifySessionLifecycle(e.session))return;this.serverWorking=e.session.kind===`working`;let t=Ge(this.status,this.serverWorking);t&&this.setStatus(t)}notifySessionLifecycle(e){return e.kind===`closing_soon`?(this.options.onSessionClosing?.(e.timeLeftMs),!0):e.kind===`ended`?this.providerState?(this.handleDrop(),!0):(this.sessionOver=!0,this.options.onSessionEnded?.(e),!0):!1}restingStatus(){return this.serverWorking?`working`:`listening`}collectMediaTurnEvent(e,t){e.media.data&&(this.setStatus(`speaking`),t.mediaChunks.push({data:e.media.data,mimeType:e.media.mimeType}))}handleDoneTurnEvent(e){e.interrupted&&this.cancelPlayback(),e.stop.kind!==`generation_complete`&&(this.serverWorking=!1,this.setStatus(`listening`))}scheduleMediaChunks(e){if(e.length===0)return;let t=this.audioEpoch;for(let n of e)this.audioChain=this.audioChain.then(async()=>{t===this.audioEpoch&&await this.enqueueAudioChunk(n.data,n.mimeType)}).catch(e=>{this.options.onError?.(Y(e))})}executeToolOnRelay(e){let t=this.ws;if(!t||t.readyState!==WebSocket.OPEN)throw new j(`request`,`live session is not connected`);let n=ie.safeParse({...e,type:`executeTool`});if(!n.success||n.data.type!==`executeTool`)throw new j(`request`,k(`error.request`));let r=n.data;if(this.pendingExecuteResults.has(r.operationId))throw new j(`request`,k(`session.gate_expired`));return new Promise((e,n)=>{this.pendingExecuteResults.set(r.operationId,{callId:r.callId,resolve:e,reject:n});try{t.send(J(r))}catch(e){this.pendingExecuteResults.delete(r.operationId),n(Y(e))}})}async enqueueAudioChunk(e,t){if(this.audioContext)try{if(this.ensurePlaybackBus(),!this.playbackBus)return;let n=A(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=ze(n);r=this.audioContext.createBuffer(1,e.length,24e3),r.getChannelData(0).set(e)}let i=this.audioContext.createBufferSource();i.buffer=r,i.connect(this.playbackBus);let a=this.audioContext.currentTime,o=Math.max(a,this.nextPlaybackTime);i.start(o),this.nextPlaybackTime=o+r.duration,this.playbackNodes.push(i),this.startPlaybackMeter(),i.onended=()=>{let e=this.playbackNodes.indexOf(i);e!==-1&&this.playbackNodes.splice(e,1),this.playbackNodes.length===0&&(this.stopPlaybackMeter(),this.status===`speaking`&&this.setStatus(this.restingStatus()))}}catch(e){this.options.onError?.(Y(e))}}cancelPlayback(){this.audioEpoch+=1,this.audioChain=Promise.resolve();for(let e of this.playbackNodes)try{e.stop(),e.disconnect()}catch{}this.playbackNodes=[],this.stopPlaybackMeter(),this.audioContext&&(this.nextPlaybackTime=this.audioContext.currentTime)}toggleMute(){return this.isMuted=!this.isMuted,this.isMuted}sendText(e){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(J({type:`text`,text:e}))}setOptions(e){JSON.stringify(e)!==JSON.stringify(this.options.options)&&(this.options={...this.options,options:e},this.takeUpAgain())}setStated(e){JSON.stringify(e)!==JSON.stringify(this.options.stated)&&(this.options={...this.options,stated:e},this.takeUpAgain())}takeUpAgain(){this.providerState&&!this.opening&&this.ws?.readyState===WebSocket.OPEN&&this.handleDrop()}setContext(e){this.context=e,this.flushContext()}flushContext(){if(this.opening||this.ws?.readyState!==WebSocket.OPEN)return;let e=JSON.stringify(this.context);e!==this.sentContext&&(this.sentContext=e,this.ws.send(J({type:`context`,context:this.context})))}sendVideo(e,t=`image/jpeg`){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(J({type:`video`,data:e,mimeType:t}))}disconnect(){this.clearReconnect(),this.lostAt=void 0,this.providerState=void 0,this.teardownConnection(),this.setStatus(`disconnected`)}cleanupAudio(){if(this.cancelPlayback(),this.stopPlaybackMeter(),X(this.playbackBus),this.playbackBus=null,this.playbackAnalyser=null,this.playbackMeterBuffer=null,this.micWorklet&&=(this.micWorklet.port.onmessage=null,X(this.micWorklet),null),X(this.micSource),this.micSource=null,Ue(this.micStream),this.micStream=null,this.audioContext&&this.audioContext.state!==`closed`){try{this.audioContext.close()}catch{}this.audioContext=null,this.micWorkletModuleLoaded=!1}}},Z=e(t(),1);function qe(){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:Xe(e,t):e:t}function Xe(e,t){return e?t?!e.endsWith(` `)&&!t.startsWith(` `)&&!/^\s/.test(t)&&!/^[\s.,!?;:]/.test(t)?`${e} ${t}`:`${e}${t}`:e:t}function Ze(e){return`${String(Date.now())}-${String(e.turns.length)}`}function Qe(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:Xe(s.text,t)};else{let n=i?.forceNew?t:Ye(c,t);o.push({id:Ze(e),role:a,text:n})}return{...e,turns:o,interimUser:n?``:e.interimUser,interimAgent:n?e.interimAgent:``}}function $e(e){return e.type===`thought`||e.type===`tool`||e.type===`citation`}function et(e,t){return e.findIndex(e=>e.role===`work`&&e.events.some(e=>e.type===`tool`&&e.tool.callId===t))}function tt(e,t){if(t.type===`tool`&&t.tool.phase!==void 0)return t.tool.phase===`gate`?-1:et(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 nt(e,t){if(t.type===`done`)return e.working?{...e,working:!1}:e;if(!$e(t))return e;let n=tt(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:Ze(e),role:`work`,events:[t]},{...e,turns:r,working:!0}}function rt(e){return e.role===`work`?ne(e.events,{idPrefix:e.id}):[{id:e.id,kind:e.role===`user`?`user-text`:`text`,text:e.text}]}var it=24;function at(e,t){let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];)n+=1;return n}function ot(e,t){let n=e.trim();return at(n,t.trim())>=Math.min(n.length,it)}function st(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`&&ot(t.text,e.text))})}function ct(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=>st(e).flatMap(rt)).filter(e=>e.length>0);return{blocks:a.flat(),callStarts:a.slice(1).map(e=>e[0].id)}}function lt({working:e,interimAgent:t}){return t!==``||e}function ut(e){return!e.interimUser&&!e.interimAgent?e:{...e,interimUser:``,interimAgent:``}}function dt(e,t){let n=Object.keys(t??{}).sort().join(`
|
|
1
|
+
import{r as e}from"./rolldown-runtime-hePW80VL.js";import{d as t,l as n}from"./themeProps-Bo2jNkIC.js";import{n as r,t as i}from"./LayoutContent-BWpUj2Iy.js";import{t as a}from"./Icon-Cd9sDRzY.js";import{a as o,c as s,l as c,p as l,u}from"./SidePanel-DcAhRInK.js";import{t as d}from"./Text-Cq4yqBpQ.js";import{t as f}from"./Button-Bwkht0RI.js";import{b as p,g as m,p as h,s as g,t as _}from"./browser-transport-C4b9Cns1.js";import{t as v}from"./createReactComponent-DVEyVJ-p.js";import{t as y}from"./Center-CPu_uP6i.js";import{_ as b,g as x,h as S,m as C,n as w,r as T,t as ee}from"./studio-labels-EVPkcfTG.js";import{t as E}from"./IconMicrophone-BT77cilC.js";import{Ha as D,Sa as O,ro as k,xa as A}from"./shaped-data-9kDvR1de.js";import{c as j}from"./host-patterns-F-KZIzkF.js";import{S as M,g as N,r as P,t as F}from"./reader-CfENH3jS.js";import{i as I}from"./live-ingress-OuSlQ6q7.js";import{i as te,y as ne}from"./turn-client-Cl1P1QP9.js";import{r as re,t as ie}from"./live-messages-BrXwocbM.js";import{t as ae}from"./EmptyState-DW-8doL9.js";import"./use-second-ticker-Dd57a-0O.js";import{a as oe,n as L,t as R}from"./labels-provider-BO_XYaPQ.js";import{t as z}from"./HStack-B00ufja5.js";import{t as B}from"./IconButton-BenRR-zK.js";import{t as V}from"./VStack-D1ZLA9g3.js";import{t as se}from"./StackItem-nWHq5y--.js";import{t as ce}from"./Toolbar-Bodaemo6.js";import{t as le}from"./Dialog-tyH-Jv5A.js";import{Gt as ue,H as de,Kt as fe,L as pe,M as me,Rt as he,S as ge,St as _e,T as H,b as ve,j as U,pt as ye,qt as be,tn as xe,u as Se}from"./index-DdfSX5Od.js";var Ce=v(`outline`,`arrows-diagonal-minimize-2`,`ArrowsDiagonalMinimize2`,[[`path`,{d:`M18 10h-4v-4`,key:`svg-0`}],[`path`,{d:`M20 4l-6 6`,key:`svg-1`}],[`path`,{d:`M6 14h4v4`,key:`svg-2`}],[`path`,{d:`M10 14l-6 6`,key:`svg-3`}]]),we=v(`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`}]]),Te=v(`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`}]]),Ee=v(`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`}]]),W=v(`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`}]]),De=v(`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`}]]),Oe=v(`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`}]]),G=v(`outline`,`video`,`Video`,[[`path`,{d:`M15 10l4.553 -2.276a1 1 0 0 1 1.447 .894v6.764a1 1 0 0 1 -1.447 .894l-4.553 -2.276v-4`,key:`svg-0`}],[`path`,{d:`M3 8a2 2 0 0 1 2 -2h8a2 2 0 0 1 2 2v8a2 2 0 0 1 -2 2h-8a2 2 0 0 1 -2 -2l0 -8`,key:`svg-1`}]]);function ke(e){return e.status===`reconnecting`?`reconnecting`:e.toolName?`calling_tool`:e.connectPhase===`socket`?`connecting`:e.connectPhase===`microphone`?`requesting_mic`:e.status===`speaking`?`speaking`:e.status===`listening`||e.status===`ready`?e.voiceEnabled===!1?`connected`:e.isMuted?`muted`:`listening`:e.status===`connecting`?`connecting`:e.status===`error`?`error`:`ended`}function Ae(e){return!(e.isMuted||!e.socketOpen||e.modelPlaying&&e.rms<e.bargeInRmsWhileSpeaking)}function je(e){let{evidence:t,text:n}=e;return!n||t.kind!==`input_transcription`&&t.kind!==`output_transcription`?null:{text:n,isUser:t.kind===`input_transcription`,interim:t.interim===!0}}function Me(e,t){if(e.phase===void 0){t.toolCalls.push({id:e.callId,name:e.name,arguments:e.arguments,...e.operationId?{operationId:e.operationId}:{}});return}if(e.phase===`cancel`){t.cancelledToolIds.add(e.callId);return}if(e.phase!==`error`)return;let n=t.toolCalls.findIndex(t=>t.id===e.callId);n!==-1&&t.toolCalls.splice(n,1)}var K=new Set;async function Ne(e){let{executeToolOnRelay:t,name:n,toolArgs:r,callId:i,operationId:a}=e,o=e.pageTools&&Object.hasOwn(e.pageTools,n)?e.pageTools[n]:void 0,s=await t({callId:i,operationId:a}),c=new Set;for(;s.status!==`settled`;){if(s.status===`dispatched`){if(c.has(s.grantId))return;c.add(s.grantId);let e=s.grantId,r=s.arguments;!o&&!K.has(n)&&(K.add(n),console.warn(`Theorem: page tool '${n}' has no handler in pageTools; the agent gets no answer.`));let l=o?await Promise.resolve().then(()=>o(r,{callId:i,operationId:a})).catch(()=>void 0):void 0;s=await t({callId:i,operationId:a,grantId:e,...l?{output:l.output}:{unanswered:!0}});continue}let{gate:l}=s,u=l.kind===`page`||!e.onGate?{decision:`deny`}:await e.onGate({callId:i,toolName:n,input:l.preparedArguments??r,gate:l});if(u===`withdrawn`)return;if(u.decision===`deny`){await t({callId:i,operationId:a,decision:`deny`});return}s=await t({callId:i,decision:`approve`,operationId:a,...u.secret===void 0?{}:{secret:u.secret}})}}function Pe(e){if(!(e instanceof Error))return!1;let t=`name`in e&&typeof e.name==`string`?e.name:``;return t===`NotAllowedError`||t===`PermissionDeniedError`||/permission|not allowed|denied/i.test(e.message)}var Fe=`mic-capture-processor`;function Ie(){return new URL(`data:text/javascript;base64,LyoqCiAqIEF1ZGlvV29ya2xldCBwcm9jZXNzb3IgdGhhdCBmb3J3YXJkcyBtb25vIG1pYyBmcmFtZXMgdG8gdGhlIG1haW4gdGhyZWFkLgogKiBQbGFpbiBKUzogaXQgcnVucyBpbiB0aGUgQXVkaW9Xb3JrbGV0R2xvYmFsU2NvcGUgYXMgaXRzIG93biBtb2R1bGUsIGxvYWRlZAogKiBieSBVUkwgKHNlZSBgLi4vbWljLWNhcHR1cmUudHNgKSwgc28gaXQgaW1wb3J0cyBub3RoaW5nIGFuZCBzaGlwcyBhcyBpcy4KICovCnJlZ2lzdGVyUHJvY2Vzc29yKAogICdtaWMtY2FwdHVyZS1wcm9jZXNzb3InLAogIGNsYXNzIE1pY0NhcHR1cmVQcm9jZXNzb3IgZXh0ZW5kcyBBdWRpb1dvcmtsZXRQcm9jZXNzb3IgewogICAgcHJvY2VzcyhpbnB1dHMpIHsKICAgICAgY29uc3QgY2hhbm5lbCA9IGlucHV0c1swXVswXTsKICAgICAgY29uc3QgY29weSA9IG5ldyBGbG9hdDMyQXJyYXkoY2hhbm5lbCk7CiAgICAgIHRoaXMucG9ydC5wb3N0TWVzc2FnZShjb3B5LCBbY29weS5idWZmZXJdKTsKICAgICAgcmV0dXJuIHRydWU7CiAgICB9CiAgfSwKKTsK`,``+import.meta.url)}function Le(e,t,n=16e3){if(t===n)return Re(e);let r=t/n,i=Math.round(e.length/r),a=new Int16Array(i),o=0,s=0;for(;o<a.length;){let t=Math.round((o+1)*r),n=0,i=0;for(let r=s;r<t&&r<e.length;r++)n+=e[r]??0,i++;a[o]=q(i>0?n/i:0),o++,s=t}return a}function Re(e){let t=new Int16Array(e.length);for(let n=0;n<e.length;n++)t[n]=q(e[n]??0);return t}function q(e){let t=Math.max(-1,Math.min(1,e));return t<0?t*32768:t*32767}function ze(e){let t=new DataView(e.buffer,e.byteOffset,e.byteLength),n=new Float32Array(e.byteLength/2);for(let e=0;e<n.length;e++){let r=t.getInt16(e*2,!0);n[e]=r/(r<0?32768:32767)}return n}function J(e){return JSON.stringify(e)}function Be(){return{toolCalls:[],mediaChunks:[],cancelledToolIds:new Set}}var Ve=.05,He=[500,1e3,2e3,4e3,8e3];function Y(e){return e instanceof Error?e:new j(`internal`,D(e),{cause:e})}function X(e){if(e&&typeof e.disconnect==`function`)try{e.disconnect()}catch{}}function Ue(e){if(e&&typeof e.getTracks==`function`)for(let t of e.getTracks())t.stop()}function We(e){let t=ue(e.inputFloat32),n=e.hasPlaybackNodes||e.status===`speaking`;return Ae({isMuted:e.isMuted,socketOpen:e.wsOpen,modelPlaying:n,rms:t,bargeInRmsWhileSpeaking:Ve})}function Ge(e,t){return e===`listening`&&t?`working`:e===`working`&&!t?`listening`:null}var Ke=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 j(`network`,`live session closed before call ${e} settled`));if(this.pendingExecuteResults.clear(),this.ws){this.ws.onopen=null,this.ws.onmessage=null,this.ws.onclose=null,this.ws.onerror=null;try{this.ws.close()}catch{}this.ws=null}}clearReconnect(){this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=null,this.reconnectTries=0,this.droppedAt=void 0}teardownConnection(){this.clearConnectTimeout(),this.micActivating=!1,this.setConnectPhase(null),this.detachWebSocket(),this.cleanupAudio()}failSession(e){this.status!==`error`&&this.status!==`disconnected`&&(this.clearReconnect(),this.teardownConnection(),this.options.onError?.(e),this.setStatus(`error`))}createSocket(e){return this.options.createSocket?.()??new WebSocket(e)}connect(){let e=this.lostAt;return this.clearReconnect(),this.lostAt=void 0,e===void 0?(this.providerState=void 0,this.history=[]):this.droppedAt=e,this.open(`connecting`)}startOver(){return this.status!==`connecting`||!this.providerState?!1:(this.providerState=void 0,this.droppedAt=void 0,this.open(`connecting`),!0)}openMessage(){let{options:e,stated:t,model:n,effort:r,openMessage:i}=this.options;return{type:`open`,...this.history.length?{history:structuredClone(this.history)}:{},...e?{options:e}:{},...t?{stated:t}:{},...n?{model:n}:{},...r?{effort:r}:{},...this.context===void 0?{}:{context:this.context},...this.providerState?{resume:{providerState:this.providerState,awayMs:this.droppedAt===void 0?0:Date.now()-this.droppedAt}}:{},...i?{host:i}:{}}}handleDrop(){!this.providerState||this.sessionOver?(this.teardownConnection(),this.setStatus(`disconnected`)):(this.droppedAt??=Date.now(),this.teardownConnection(),this.setStatus(`reconnecting`),this.scheduleReconnect())}scheduleReconnect(){let e=He[this.reconnectTries];if(e===void 0){let e=this.droppedAt;this.failSession(new j(`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 j(`timeout`,`live connect timed out`))},2e4),this.ws.onmessage=e=>{this.enqueueServerMessage(e.data)},this.ws.onclose=()=>{this.opening?this.failOpen(new j(`network`,`live socket closed before ready`)):this.handleDrop()},this.ws.onerror=()=>{!this.opening&&this.providerState&&!this.sessionOver?this.handleDrop():this.failOpen(new j(`network`,`live socket error`))}}catch(e){this.failOpen(new j(`internal`,D(e),{cause:e}))}}async ensureAudioContext(){if(!this.audioContext||this.audioContext.state===`closed`){let e=globalThis.AudioContext;this.audioContext=new e,this.audioContext.state===`suspended`&&await this.audioContext.resume()}}async activateMicrophone(){if(!this.micActivating&&this.opening){this.micActivating=!0,this.status===`connecting`&&this.setConnectPhase(`microphone`);try{await this.ensureAudioContext(),this.micStream=await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}}),await this.setupMicrophonePipeline(),this.becomeReady()}catch(e){let t=Pe(e);this.failSession(new j(t?`auth`:`internal`,D(e),{cause:e,copy:{key:t?`voice.permission`:`voice.unavailable`}}))}finally{this.micActivating=!1}}}sendMicFrame(e,t){let n=Le(e,t,16e3),r=O(new Uint8Array(n.buffer)),i=this.ws;i?.readyState===WebSocket.OPEN&&i.send(J({type:`audio`,data:r}))}reportMicVolume(e){this.isMuted||this.options.onVolumeLevel?.(fe(e),!0)}forwardMicBuffer(e){if(this.reportMicVolume(e),We({isMuted:this.isMuted,wsOpen:this.ws?.readyState===WebSocket.OPEN,hasPlaybackNodes:this.playbackNodes.length>0,status:this.status,inputFloat32:e})){let t=this.audioContext?this.audioContext.sampleRate:48e3;this.sendMicFrame(e,t)}}async setupMicrophonePipeline(){if(!this.micStream||!this.audioContext)return;this.micSource=this.audioContext.createMediaStreamSource(this.micStream);let e=this.audioContext.createGain();e.gain.value=0,this.micWorkletModuleLoaded||=(await this.audioContext.audioWorklet.addModule(Ie()),!0),this.micWorklet=new AudioWorkletNode(this.audioContext,Fe),this.micWorklet.port.onmessage=e=>{let t=new Float32Array(e.data);this.forwardMicBuffer(t)},this.micSource.connect(this.micWorklet),this.micWorklet.connect(e),e.connect(this.audioContext.destination)}ensurePlaybackBus(){this.audioContext&&!this.playbackBus&&(this.playbackBus=this.audioContext.createGain(),this.playbackAnalyser=this.audioContext.createAnalyser(),this.playbackAnalyser.fftSize=512,this.playbackAnalyser.smoothingTimeConstant=.35,this.playbackBus.connect(this.playbackAnalyser),this.playbackAnalyser.connect(this.audioContext.destination),this.playbackMeterBuffer=new Uint8Array(this.playbackAnalyser.fftSize))}stopPlaybackMeter(){this.playbackMeterFrame&&=(cancelAnimationFrame(this.playbackMeterFrame),0),this.options.onVolumeLevel?.(0,!1)}startPlaybackMeter(){if(this.playbackMeterFrame)return;let e=()=>{this.playbackNodes.length===0||!this.playbackAnalyser||!this.playbackMeterBuffer?this.stopPlaybackMeter():(this.playbackAnalyser.getByteTimeDomainData(this.playbackMeterBuffer),this.options.onVolumeLevel?.(be(this.playbackMeterBuffer),!1),this.playbackMeterFrame=requestAnimationFrame(e))};this.playbackMeterFrame=requestAnimationFrame(e)}async processServerEnvelope(e){if(await this.tryHandleControlEnvelope(e)||e.type!==`events`)return;let t=this.collectInboundTurn(e.events),n=t.toolCalls.filter(e=>!t.cancelledToolIds.has(e.id));for(let e of n)this.toolChain=this.toolChain.then(()=>Ne({executeToolOnRelay:e=>this.executeToolOnRelay(e),pageTools:this.options.pageTools,onGate:this.options.onGate,name:e.name,toolArgs:e.arguments,callId:e.id,operationId:te(e)})).catch(e=>{this.options.onError?.(Y(e))});this.scheduleMediaChunks(t.mediaChunks)}enqueueServerMessage(e){this.inboundChain=this.inboundChain.then(async()=>{if(typeof e!=`string`)return;let t=re(e);t.type===`unsupported`||t.type===`malformed`?this.options.onTurnEvent?.(t):await this.processServerEnvelope(t)}).catch(e=>{this.options.onError?.(Y(e))})}async handleReadyEnvelope(e){this.options.onSessionReady?.({sessionId:e.sessionId,profile:e.profile}),this.options.voiceIngress===!1?this.becomeReady():await this.activateMicrophone()}becomeReady(){this.clearReconnect(),this.setConnectPhase(null),this.setStatus(`listening`),this.flushContext()}handleExecuteToolResultEnvelope(e){let t=this.pendingExecuteResults.get(e.operationId);t&&t.callId===e.callId&&(this.pendingExecuteResults.delete(e.operationId),e.status===`refused`?t.reject(M(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?.(M(e,`unavailable`)),this.setStatus(`error`)),!0)}collectInboundTurn(e){let t=Be();for(let n of e)this.processTurnEvent(n,t);return t}processTurnEvent(e,t){switch(e.type===`provider_checkpoint`&&e.history&&(this.history=structuredClone(e.history)),(e.type===`provider_checkpoint`||e.type===`done`)&&e.providerState&&(this.providerState=e.providerState),e.type===`provider_warning`&&(this.providerState=void 0),this.options.onTurnEvent?.(e),e.type){case`evidence`:this.handleEvidenceTurnEvent(e);break;case`session`:this.handleSessionTurnEvent(e);break;case`media`:this.collectMediaTurnEvent(e,t);break;case`tool`:Me(e.tool,t);break;case`done`:this.handleDoneTurnEvent(e)}}handleEvidenceTurnEvent(e){let t=je(e);t&&this.options.onTranscript?.(t.text,t.isUser,{interim:t.interim})}handleSessionTurnEvent(e){if(this.notifySessionLifecycle(e.session))return;this.serverWorking=e.session.kind===`working`;let t=Ge(this.status,this.serverWorking);t&&this.setStatus(t)}notifySessionLifecycle(e){return e.kind===`closing_soon`?(this.options.onSessionClosing?.(e.timeLeftMs),!0):e.kind===`ended`?this.providerState?(this.handleDrop(),!0):(this.sessionOver=!0,this.options.onSessionEnded?.(e),!0):!1}restingStatus(){return this.serverWorking?`working`:`listening`}collectMediaTurnEvent(e,t){e.media.data&&(this.setStatus(`speaking`),t.mediaChunks.push({data:e.media.data,mimeType:e.media.mimeType}))}handleDoneTurnEvent(e){e.interrupted&&this.cancelPlayback(),e.stop.kind!==`generation_complete`&&(this.serverWorking=!1,this.setStatus(`listening`))}scheduleMediaChunks(e){if(e.length===0)return;let t=this.audioEpoch;for(let n of e)this.audioChain=this.audioChain.then(async()=>{t===this.audioEpoch&&await this.enqueueAudioChunk(n.data,n.mimeType)}).catch(e=>{this.options.onError?.(Y(e))})}executeToolOnRelay(e){let t=this.ws;if(!t||t.readyState!==WebSocket.OPEN)throw new j(`request`,`live session is not connected`);let n=ie.safeParse({...e,type:`executeTool`});if(!n.success||n.data.type!==`executeTool`)throw new j(`request`,k(`error.request`));let r=n.data;if(this.pendingExecuteResults.has(r.operationId))throw new j(`request`,k(`session.gate_expired`));return new Promise((e,n)=>{this.pendingExecuteResults.set(r.operationId,{callId:r.callId,resolve:e,reject:n});try{t.send(J(r))}catch(e){this.pendingExecuteResults.delete(r.operationId),n(Y(e))}})}async enqueueAudioChunk(e,t){if(this.audioContext)try{if(this.ensurePlaybackBus(),!this.playbackBus)return;let n=A(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=ze(n);r=this.audioContext.createBuffer(1,e.length,24e3),r.getChannelData(0).set(e)}let i=this.audioContext.createBufferSource();i.buffer=r,i.connect(this.playbackBus);let a=this.audioContext.currentTime,o=Math.max(a,this.nextPlaybackTime);i.start(o),this.nextPlaybackTime=o+r.duration,this.playbackNodes.push(i),this.startPlaybackMeter(),i.onended=()=>{let e=this.playbackNodes.indexOf(i);e!==-1&&this.playbackNodes.splice(e,1),this.playbackNodes.length===0&&(this.stopPlaybackMeter(),this.status===`speaking`&&this.setStatus(this.restingStatus()))}}catch(e){this.options.onError?.(Y(e))}}cancelPlayback(){this.audioEpoch+=1,this.audioChain=Promise.resolve();for(let e of this.playbackNodes)try{e.stop(),e.disconnect()}catch{}this.playbackNodes=[],this.stopPlaybackMeter(),this.audioContext&&(this.nextPlaybackTime=this.audioContext.currentTime)}toggleMute(){return this.isMuted=!this.isMuted,this.isMuted}sendText(e){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(J({type:`text`,text:e}))}setOptions(e){JSON.stringify(e)!==JSON.stringify(this.options.options)&&(this.options={...this.options,options:e},this.takeUpAgain())}setStated(e){JSON.stringify(e)!==JSON.stringify(this.options.stated)&&(this.options={...this.options,stated:e},this.takeUpAgain())}takeUpAgain(){this.providerState&&!this.opening&&this.ws?.readyState===WebSocket.OPEN&&this.handleDrop()}setContext(e){this.context=e,this.flushContext()}flushContext(){if(this.opening||this.ws?.readyState!==WebSocket.OPEN)return;let e=JSON.stringify(this.context);e!==this.sentContext&&(this.sentContext=e,this.ws.send(J({type:`context`,context:this.context})))}sendVideo(e,t=`image/jpeg`){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(J({type:`video`,data:e,mimeType:t}))}disconnect(){this.clearReconnect(),this.lostAt=void 0,this.providerState=void 0,this.teardownConnection(),this.setStatus(`disconnected`)}cleanupAudio(){if(this.cancelPlayback(),this.stopPlaybackMeter(),X(this.playbackBus),this.playbackBus=null,this.playbackAnalyser=null,this.playbackMeterBuffer=null,this.micWorklet&&=(this.micWorklet.port.onmessage=null,X(this.micWorklet),null),X(this.micSource),this.micSource=null,Ue(this.micStream),this.micStream=null,this.audioContext&&this.audioContext.state!==`closed`){try{this.audioContext.close()}catch{}this.audioContext=null,this.micWorkletModuleLoaded=!1}}},Z=e(t(),1);function qe(){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:Xe(e,t):e:t}function Xe(e,t){return e?t?!e.endsWith(` `)&&!t.startsWith(` `)&&!/^\s/.test(t)&&!/^[\s.,!?;:]/.test(t)?`${e} ${t}`:`${e}${t}`:e:t}function Ze(e){return`${String(Date.now())}-${String(e.turns.length)}`}function Qe(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:Xe(s.text,t)};else{let n=i?.forceNew?t:Ye(c,t);o.push({id:Ze(e),role:a,text:n})}return{...e,turns:o,interimUser:n?``:e.interimUser,interimAgent:n?e.interimAgent:``}}function $e(e){return e.type===`thought`||e.type===`tool`||e.type===`citation`}function et(e,t){return e.findIndex(e=>e.role===`work`&&e.events.some(e=>e.type===`tool`&&e.tool.callId===t))}function tt(e,t){if(t.type===`tool`&&t.tool.phase!==void 0)return t.tool.phase===`gate`?-1:et(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 nt(e,t){if(t.type===`done`)return e.working?{...e,working:!1}:e;if(!$e(t))return e;let n=tt(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:Ze(e),role:`work`,events:[t]},{...e,turns:r,working:!0}}function rt(e){return e.role===`work`?ne(e.events,{idPrefix:e.id}):[{id:e.id,kind:e.role===`user`?`user-text`:`text`,text:e.text}]}var it=24;function at(e,t){let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];)n+=1;return n}function ot(e,t){let n=e.trim();return at(n,t.trim())>=Math.min(n.length,it)}function st(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`&&ot(t.text,e.text))})}function ct(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=>st(e).flatMap(rt)).filter(e=>e.length>0);return{blocks:a.flat(),callStarts:a.slice(1).map(e=>e[0].id)}}function lt({working:e,interimAgent:t}){return t!==``||e}function ut(e){return!e.interimUser&&!e.interimAgent?e:{...e,interimUser:``,interimAgent:``}}function dt(e,t){let n=Object.keys(t??{}).sort().join(`
|
|
2
2
|
`),r=e?.join(`
|
|
3
3
|
`);(0,Z.useEffect)(()=>{r!==void 0&&he(r?r.split(`
|
|
4
4
|
`):[],n?n.split(`
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{r as e}from"./rolldown-runtime-hePW80VL.js";import{d as t,l as n}from"./themeProps-Bo2jNkIC.js";import{t as r}from"./Icon-Cd9sDRzY.js";import{t as i}from"./IconX-Cx51PGNB.js";import{t as a}from"./Text-Cq4yqBpQ.js";import{t as o}from"./Button-Bwkht0RI.js";import{t as s}from"./createReactComponent-DVEyVJ-p.js";import{t as c}from"./ScrollableArea-DgswAvfJ.js";import{a as l,n as u,o as d}from"./type-icons-DgazEJTc.js";import{n as f,r as p}from"./useAdaptivePresentation-D53OuCPm.js";import{n as m,t as h}from"./Center-CPu_uP6i.js";import{t as g}from"./IconSearch-BN1R3FIx.js";import{r as _,s as v,t as y}from"./tree-D6WoHLJe.js";import{F as b,i as x}from"./workspace-CCtOtOGD.js";import{i as S,n as C,r as w,t as T}from"./map-token-BcCSmfJy.js";import{i as E,n as D,o as O}from"./studio-session-ClF2iNCX.js";import{t as k}from"./EmptyState-DW-8doL9.js";import{t as A}from"./IconButton-BenRR-zK.js";import{t as j}from"./TextInput-DwHcdc-E.js";import{Et as M,an as N,ct as P,n as F,wt as I,y as L}from"./index-Cfhzi3KD.js";var R=s(`outline`,`arrows-maximize`,`ArrowsMaximize`,[[`path`,{d:`M16 4l4 0l0 4`,key:`svg-0`}],[`path`,{d:`M14 10l6 -6`,key:`svg-1`}],[`path`,{d:`M8 20l-4 0l0 -4`,key:`svg-2`}],[`path`,{d:`M4 20l6 -6`,key:`svg-3`}],[`path`,{d:`M16 20l4 0l0 -4`,key:`svg-4`}],[`path`,{d:`M14 14l6 6`,key:`svg-5`}],[`path`,{d:`M8 4l-4 0l0 4`,key:`svg-6`}],[`path`,{d:`M4 4l6 6`,key:`svg-7`}]]),z=s(`outline`,`arrows-minimize`,`ArrowsMinimize`,[[`path`,{d:`M5 9l4 0l0 -4`,key:`svg-0`}],[`path`,{d:`M3 3l6 6`,key:`svg-1`}],[`path`,{d:`M5 15l4 0l0 4`,key:`svg-2`}],[`path`,{d:`M3 21l6 -6`,key:`svg-3`}],[`path`,{d:`M19 9l-4 0l0 -4`,key:`svg-4`}],[`path`,{d:`M15 9l6 -6`,key:`svg-5`}],[`path`,{d:`M19 15l-4 0l0 4`,key:`svg-6`}],[`path`,{d:`M15 15l6 6`,key:`svg-7`}]]),B=s(`outline`,`focus-2`,`Focus2`,[[`path`,{d:`M11.5 12a.5 .5 0 1 0 1 0a.5 .5 0 1 0 -1 0`,fill:`currentColor`,key:`svg-0`}],[`path`,{d:`M5 12a7 7 0 1 0 14 0a7 7 0 1 0 -14 0`,key:`svg-1`}],[`path`,{d:`M12 3l0 2`,key:`svg-2`}],[`path`,{d:`M3 12l2 0`,key:`svg-3`}],[`path`,{d:`M12 19l0 2`,key:`svg-4`}],[`path`,{d:`M19 12l2 0`,key:`svg-5`}]]),V=s(`outline`,`layout-grid`,`LayoutGrid`,[[`path`,{d:`M4 5a1 1 0 0 1 1 -1h4a1 1 0 0 1 1 1v4a1 1 0 0 1 -1 1h-4a1 1 0 0 1 -1 -1l0 -4`,key:`svg-0`}],[`path`,{d:`M14 5a1 1 0 0 1 1 -1h4a1 1 0 0 1 1 1v4a1 1 0 0 1 -1 1h-4a1 1 0 0 1 -1 -1l0 -4`,key:`svg-1`}],[`path`,{d:`M4 15a1 1 0 0 1 1 -1h4a1 1 0 0 1 1 1v4a1 1 0 0 1 -1 1h-4a1 1 0 0 1 -1 -1l0 -4`,key:`svg-2`}],[`path`,{d:`M14 15a1 1 0 0 1 1 -1h4a1 1 0 0 1 1 1v4a1 1 0 0 1 -1 1h-4a1 1 0 0 1 -1 -1l0 -4`,key:`svg-3`}]]);function H(e,t,n){let r=e=>{let r=t.flatMap(({from:t,to:n})=>t===e.id?[n]:n===e.id?[t]:[]).flatMap(e=>n.get(e)??[]);return r.length===0?1/0:r.reduce((e,t)=>e+t,0)/r.length},i=new Map(e.map(e=>[e.id,r(e)])),a=e=>i.get(e.id)??1/0;return[...e].sort((e,t)=>a(e)===a(t)?0:a(e)-a(t))}function U(e,t,n){return t===`models`?e.modelBindings.map(e=>e.modelId.trim()||`Unnamed model`).join(`, `):t===`tools`?String(e.tools.allow.filter(e=>n.has(e)).length):t===`outputs`?e.outputs.mode:``}function W(e,t=[]){let n=[],r=new Map(e.agents.map(e=>[e.key,x(e.key)])),i=new Map(e.toolSpecs.map(e=>[e.key,v(e.key)])),a=b(e),o=e.agents.map((e,t)=>{let{agentId:n,profileType:r,handle:o}=e.identity,s=r||`text`;return{id:x(e.key),kind:`agent`,label:n.trim()||`Unnamed agent`,note:o?`${s} · ${o}`:s,opens:x(e.key),type:s,rows:(a.agents[t]?.children??[]).map(t=>({id:t.id,label:t.label,note:U(e,t.ref.facet,i),opens:t.id,type:t.ref.facet}))}}),s=new Set(o.flatMap(e=>e.rows??[]).map(e=>e.id)),c=(e,t)=>{let n=x(e,t);return s.has(n)?n:x(e)},l=new Map,u=new Map(e.providers.map(e=>[e.id,e.definition])),d=new Map;for(let t of e.agents){let e=c(t.key,`models`);for(let i of t.modelBindings){let a=`model:${i.provider}:${i.apiId}:${i.modelId}`,o=_(i.provider);l.has(o)||l.set(o,{id:o,kind:`provider`,label:i.provider,note:``,opens:u.has(i.provider)?o:x(t.key,y(i.key))});let s=x(t.key,y(i.key)),c=d.get(a);c?c.holds?.push(s):(d.set(a,{id:a,kind:`model`,label:i.modelId.trim()||`Unnamed model`,note:i.apiId,opens:s,holds:[s]}),n.push({from:o,to:a,kind:`serves`})),n.some(t=>t.from===a&&t.to===e)||n.push({from:a,to:e,kind:`runs`});let f=i.compactWith?r.get(i.compactWith):void 0,p=n.some(t=>t.kind===`summarised`&&t.from===e);f&&f!==x(t.key)&&!p&&n.push({from:e,to:f,kind:`summarised`})}for(let e of t.tools.allow){let r=i.get(e);r&&n.push({from:c(t.key,`tools`),to:r,kind:`allows`})}}let f=e.toolSpecs.map(e=>{let t=v(e.key),i=e.toolType===`agent`?r.get(e.agentKey??``):r.get(e.stageAgentKey??``);return i&&n.push({from:t,to:i,kind:`asks`}),{id:t,kind:`tool`,label:e.toolName.trim()||`Unnamed tool`,note:e.description,opens:t,type:e.toolType}}),p=t.map(t=>{let{setting:i,facet:a}=t,o=`shared:${i.file}:${i.name}`,s=t.agents.filter(e=>r.has(e)),l=i.tools.flatMap(t=>{let n=e.toolSpecs.find(e=>e.toolName===t);return n?[v(n.key)]:[]});for(let e of s)n.push({from:o,to:a?c(e,a):x(e),kind:`sets`});for(let e of l)n.push({from:o,to:e,kind:`sets`});return{id:o,kind:`shared`,label:i.label,note:`${i.name} · ${i.file}:${String(i.line)}`,opens:M(t)??l[0],type:a}}),m=new Map(o.flatMap((e,t)=>[e.id,...(e.rows??[]).map(e=>e.id)].map(e=>[e,t])));for(let e of d.values())[...d.values()].some(t=>t!==e&&t.label===e.label)&&e.note&&(e.long=`${e.label} · ${e.note}`);let h=H([...d.values()],n,m),g=new Map(h.map((e,t)=>[e.id,t])),S=(...e)=>e.filter(e=>e.nodes.length>0);return{columns:[S({label:`Providers`,nodes:H([...l.values()],n,g)}),S({label:`Shared settings`,nodes:H(p,n,m)},{label:`Models`,nodes:h}),S({label:`Profiles`,nodes:o}),S({label:`Tools`,nodes:H(f,n,m)})].filter(e=>e.length>0),links:n}}function G(e){let t=e.columns.flat().flatMap(e=>e.nodes);return new Map(t.flatMap(e=>[e.id,...(e.rows??[]).map(e=>e.id)].map(t=>[t,e])))}function K(e){let t=G(e);return e.links.flatMap(e=>{let n=t.get(e.from)?.id,r=t.get(e.to)?.id;return n!==void 0&&r!==void 0?[{link:e,from:n,to:r}]:[]})}function ee(e,t){let n=t.trim().toLowerCase();return n===``?[]:e.columns.flat().flatMap(e=>e.nodes).filter(e=>[e.label,e.long??``,e.note].some(e=>e.toLowerCase().includes(n))).map(e=>e.id)}function te(e,t){let n=typeof t==`string`?[t]:t,r=K(e),i=(e,t)=>{let i=new Set(n),a=[...n];for(let n=a.pop();n!==void 0;n=a.pop())for(let o of r)o[e]!==n||i.has(o[t])||(i.add(o[t]),a.push(o[t]));return i},a=new Set([...i(`to`,`from`),...i(`from`,`to`)]),o=e.columns.map(e=>e.map(e=>({...e,nodes:e.nodes.filter(e=>a.has(e.id))})).filter(e=>e.nodes.length>0)).filter(e=>e.length>0),s=new Set(r.filter(({from:e,to:t})=>a.has(e)&&a.has(t)).map(({link:e})=>e));return{columns:o,links:e.links.filter(e=>s.has(e))}}function ne(e,t){let n=new Set([t]),r=new Set,i=(i,a)=>{let o=new Set,s=[t];for(let t=s.pop();t!==void 0;t=s.pop())for(let c of e)(c[i]===t||c.link[i]===t)&&(r.add(c.link),n.add(c.link.from).add(c.link.to).add(c.from).add(c.to),!o.has(c[a])&&(o.add(c[a]),s.push(c[a])))};return i(`to`,`from`),i(`from`,`to`),{ids:n,lines:r}}var re={serves:[`Serves`,`Served by`],sets:[`Sets`,`Set by`],runs:[`Runs`,`Runs on`],allows:[`Allows`,`Allowed by`],asks:[`Asks`,`Asked by`],summarised:[`Summarised by`,`Summarises for`]};function ie(e,t){let n=G(e),r=new Map;for(let{link:i,from:a,to:o}of K(e)){if(a!==t&&o!==t)continue;let e=re[i.kind][a===t?0:1],s=n.get(a===t?o:a)?.label;s!==void 0&&r.set(e,[...r.get(e)??[],s])}return[...r].map(([e,t])=>`${e} ${t.join(`, `)}.`).join(` `)}function ae(e){return e.kind===`tool`||e.kind===`shared`?2:1}var oe=24,q=8,J=16;function se(e,t,n){let r=new Map,i=(e,t)=>`${e}:${String(t)}`;return K(e).flatMap(({link:e})=>{let[a,o]=[t(e.from),t(e.to)];if(a===void 0||o===void 0||Math.abs(a-o)<n)return[];let s=a<o?1:-1;for(let t of[i(e.from,s),i(e.to,-s)])r.set(t,(r.get(t)??0)+1);return[{link:e,way:s}]}).map(({link:e,way:t})=>{let[n,a]=[i(e.from,t),i(e.to,-t)],o=(r.get(n)??0)>=(r.get(a)??0);return{link:e,way:t,leaves:o,hub:o?n:a}})}function ce(e,t,n={}){let{node:r,card:i,columnGap:a,rowGap:o,heading:s,groupGap:c,padding:l,lineGap:u}=t,{moved:d={},widths:f={},detail:p=!1}=n,m=new Map;e.columns.forEach((e,t)=>{for(let n of e)for(let e of n.nodes)if(!Object.hasOwn(d,e.id))for(let n of[e.id,...(e.rows??[]).map(e=>e.id)])m.set(n,t)});let h=t=>{let n={},a=[],u=[],m=new Map,h=0,g=0;return e.columns.forEach((e,_)=>{let v=t[_]??l,y=l;e.forEach((e,t)=>{t>0&&(y+=c),a.push({label:e.label,x:v,y}),u.push({id:`heading:${_}:${t}`,x:v,y,width:r.width,height:s}),y+=s;for(let t of e.nodes){let e=p?t.rows??[]:[],a=e.length>0||t.note!==``,s=p&&(e.length>0||ae(t)===1)?i.head:r.height,c=p&&!a?i.row:s,l=e.length>0?i.head+e.length*i.row+i.foot:c,_=Math.min(f[t.id]??r.width,r.width),b=Object.hasOwn(d,t.id)?d[t.id]:void 0,x=b?{x:Math.max(b.x,0),y:Math.max(b.y,0)}:{x:v,y};n[t.id]={...x,height:l},u.push({id:t.id,...x,width:_,height:l});let S={left:x.x,right:x.x+_,y:x.y+(p?i.row:c)/2};m.set(t.id,S);for(let[e,n]of(t.rows??[]).entries())m.set(n.id,p?{...S,y:x.y+i.head+e*i.row+i.row/2}:S);h=Math.max(h,x.x+r.width),g=Math.max(g,x.y+l),y+=l+o}y-=o})}),{nodes:n,headings:a,boxes:u,ports:m,right:h,bottom:g}},g=(e,t,n)=>{let{way:i,leaves:a}=e,o={x:i>0?t.right+u:t.left-u,y:t.y},s={x:i>0?n.left-u:n.right+u,y:n.y},c=i>0?Math.max(t.left+r.width,t.right)+u:o.x,l=i>0?s.x:Math.max(n.left+r.width,n.right)+u,d=a?l:c,f=a?-i:i;return{start:o,end:s,side:d,into:f,room:Math.abs(l-c),strip:`${String(d)}:${String(f)}`}},_=t=>{let n=new Map(se(e,e=>t.get(e)?.left,r.width).map(e=>[e.link,e])),i=new Map;for(let e of n.values()){let n=t.get(e.link.from),r=t.get(e.link.to);if(!n||!r||n.y===r.y)continue;let{strip:a}=g(e,n,r),o=i.get(a)??new Map,s=e.leaves?e.link.to:e.link.from,c=o.get(e.hub)??{y:e.leaves?n.y:r.y,joins:[],beside:s};c.joins.push(e.leaves?r.y:n.y),i.set(a,o.set(e.hub,c))}let a=new Map,o=new Map;for(let[e,t]of i){let n=e=>e.reduce((e,t)=>e+t,0)/e.length,r=[...t.values()],i=n(r.flatMap(e=>e.joins))>=n(r.map(e=>e.y)),s=[];for(let[n,r]of[...t].sort(([,e],[,t])=>i?e.y-t.y:t.y-e.y)){let t=Math.min(r.y,...r.joins)-q,i=Math.max(r.y,...r.joins)+q,o=s.findIndex(e=>e.every(e=>i<e.low||t>e.high)),c=o<0?s.length:o;s[c]=[...s[c]??[],{low:t,high:i}],a.set(`${e}:${n}`,c)}let[c]=r;c&&o.set(e,{count:s.length,beside:c.beside,into:Number(e.split(`:`)[1])})}return{spans:n,rails:a,held:o}},v=e.columns.map((e,t)=>l+t*(r.width+a)),y=e.columns.map(()=>0);for(let{count:e,beside:t,into:n}of _(h(v).ports).held.values()){let r=m.get(t);if(r===void 0)continue;let i=n>0?r:r-1;i>=0&&i<y.length&&(y[i]=(y[i]??0)+e+1)}let b=[l];for(let[e,t]of y.entries())b.push((b[e]??l)+r.width+Math.max(a,t*J));let x=h(b),{nodes:C,headings:T,boxes:E,ports:D}=x,{right:O,bottom:k}=x,{spans:A,rails:j}=_(D),M=a/2,N=Math.max(o/2,u),P=[],F=new Map,I=Math.max(a,...y.map(e=>e*J)),L=K(e).flatMap(({link:e,from:t,to:n})=>{let i=D.get(e.from),o=D.get(e.to);if(!i||!o)return[];let s=E.filter(e=>e.id!==t&&e.id!==n);if(Math.abs(i.left-o.left)<r.width){let r=i.right+u,a=o.right+u,c=s.filter(e=>e.y<Math.max(i.y,o.y)&&e.y+e.height>Math.min(i.y,o.y)&&e.x<Math.max(r,a)+M&&e.x+e.width>Math.min(i.left,o.left)),l=Math.max(r,a,...c.map(e=>e.x+e.width))+M;return O=Math.max(O,l),[{link:e,from:t,to:n,d:w({x:r,y:i.y},{x:a,y:o.y},l).d}]}let c=A.get(e);if(!c)return[];let{way:l,leaves:d,hub:f}=c,{start:p,end:m,side:h,into:_,room:v,strip:y}=g(c,i,o),b=h+_*Math.min((1+(j.get(`${y}:${f}`)??0))*J,Math.max(v-J,0)),x=v<32?w(p,m):S(p,m,b,q),C=(e,t)=>t>e.y-N&&t<e.y+e.height+N,T=Math.abs(m.x-p.x)<I+a?[]:s.filter(e=>Array.from({length:23},(e,t)=>x.at((t+1)/oe)).some(t=>t.x>e.x&&t.x<e.x+e.width&&C(e,t.y)));if(T.length===0)return[{link:e,from:t,to:n,d:x.d}];let[L,R]=[Math.min(p.x,m.x),Math.max(p.x,m.x)],z=e=>{let t=[...T];for(;;){let n=e<0?Math.min(...t.map(e=>e.y))-N:Math.max(...t.map(e=>e.y+e.height))+N,r=[...s,...P].filter(e=>!t.includes(e)&&e.x<R&&e.x+e.width>L&&C(e,n));if(r.length===0)return n;t.push(...r)}},B=e=>Math.abs(i.y-e)+Math.abs(o.y-e),V=`${f}:${y}`,H=F.get(V)??(()=>{let[e,t]=[z(-1),z(1)],n=e>=0&&B(e)<=B(t)?e:t;return P.push({id:``,x:L,y:n-q+N,width:R-L,height:2*(q-N)}),F.set(V,n),n})();k=Math.max(k,H);let U=d?p.x+l*J:b,W=d?b:m.x-l*J,G={x:(U+W)/2,y:H};return[{link:e,from:t,to:n,d:S(p,G,U,q).d+S(G,m,W,q).d.replace(/^M \S+ \S+/,``)}]});return{width:Math.max((b[Math.max(e.columns.length-1,0)]??l)+r.width,O)+l,height:Math.max(k,l)+l,nodes:C,headings:T,lines:L}}var Y=e(t(),1),le={tokens:{},detail:{},expanded:!1},X=e=>e===void 0?`${D}.map`:`${D}.map.project:${e}`;function ue(e){if(!E(e))return{};let t={};for(let[n,r]of Object.entries(e))E(r)&&typeof r.x==`number`&&typeof r.y==`number`&&(t[n]={x:r.x,y:r.y});return t}function de(e){try{let t=JSON.parse(O()?.getItem(X(e))??`null`);return E(t)?{tokens:ue(t.tokens),detail:ue(t.detail),expanded:t.expanded===!0,...typeof t.family==`string`?{family:t.family}:{}}:le}catch{return le}}function fe(e,t){let{tokens:n,detail:r,expanded:i,family:a}=t;Object.keys(n).length===0&&Object.keys(r).length===0&&!i&&a===void 0?O()?.removeItem(X(e)):O()?.setItem(X(e),JSON.stringify(t))}function pe(e){for(let t=e.parentElement;t;t=t.parentElement){let{overflowX:e,overflowY:n}=getComputedStyle(t);if(/auto|scroll/.test(`${e} ${n}`))return t}}function me(e,t){let n=e.getBoundingClientRect(),r=t.getBoundingClientRect();return{left:n.left-r.left+t.scrollLeft,top:n.top-r.top+t.scrollTop}}var he=(e,t)=>Math.min(Math.max(e,0),Math.max(t,0));function ge(e,t){let n=0,r=120,i=()=>{--r;let a=pe(e);if(a&&a.scrollWidth>a.clientWidth){let e=t(a),n=he(e.left,a.scrollWidth-a.clientWidth),r=he(e.top,a.scrollHeight-a.clientHeight);if(a.scrollTo({left:n,top:r,behavior:`instant`}),Math.abs(a.scrollLeft-n)<1&&Math.abs(a.scrollTop-r)<1)return}r>0&&(n=requestAnimationFrame(i))};return i(),()=>{cancelAnimationFrame(n)}}var _e=e=>e.button===0&&e.pointerType!==`touch`;function ve(e,t,n){let{pointerId:r,clientX:i,clientY:a}=e,o=e=>{e.pointerId===r&&t(e.clientX-i,e.clientY-a)},s=e=>{e.pointerId===r&&(globalThis.removeEventListener(`pointermove`,o),globalThis.removeEventListener(`pointerup`,s),globalThis.removeEventListener(`pointercancel`,s),n(e.type===`pointerup`))};globalThis.addEventListener(`pointermove`,o),globalThis.addEventListener(`pointerup`,s),globalThis.addEventListener(`pointercancel`,s)}function ye(e){let[t,n]=(0,Y.useState)(!1);return{panning:t,pan:t=>{if(!_e(t)||t.target.closest(e))return;let r=pe(t.currentTarget);if(!r)return;let{scrollLeft:i,scrollTop:a}=r;n(!0),ve(t,(e,t)=>{r.scrollTo({left:i-e,top:a-t,behavior:`instant`})},()=>{n(!1)})}}}var Z=n(),be={node:{width:240,height:24},card:{head:60,row:28,foot:4},columnGap:96,rowGap:6,heading:24,groupGap:16,padding:24,lineGap:8},xe={...be,node:{width:240,height:84}},Se=28;function Ce(e){return e.length>Se?`${e.slice(0,27)}…`:e}function we({kind:e,type:t,note:n}){return(e===`agent`?l(t):void 0)||(e===`tool`?d(t??``):e===`model`?L(n)??F.modelBinding:e===`provider`?N:e===`shared`&&t&&Object.hasOwn(F,t)?F[t]:e===`agent`?u.text:p)}function Te(e){return Object.hasOwn(F,e)?F[e]:p}function Q(e,t){return e.kind===`agent`?t===e.id||t.startsWith(`${e.id}/`):e.kind===`model`?e.holds?.includes(t)??!1:e.kind===`tool`&&t===e.id}var Ee=4,De=24,Oe={ArrowLeft:{x:-1,y:0},ArrowRight:{x:1,y:0},ArrowUp:{x:0,y:-1},ArrowDown:{x:0,y:1}};function ke(e){let t=I()?.name,[n,r]=(0,Y.useState)(()=>de(t)),i=e=>{r(e),fe(t,e)},{expanded:a}=n,o=e.columns.flat().some(e=>e.nodes.some(e=>e.id===n.family))?n.family:void 0,s=(0,Y.useMemo)(()=>o===void 0?e:te(e,o),[e,o]),[c,l]=(0,Y.useState)({}),u=a?`detail`:`tokens`;return{expanded:a,family:o,map:s,moved:o===void 0?n[u]:c,put(e,t){o===void 0?t?i({...n,[u]:e}):r({...n,[u]:e}):l(e)},showFamily(e){l({});let{tokens:t,detail:r}=n;i({tokens:t,detail:r,expanded:a,...e===void 0?{}:{family:e}})},expand(){i({...n,expanded:!a})}}}function Ae(e,t,n){let r=(0,Y.useRef)(!1),[i,a]=(0,Y.useState)();return{dragging:i,draggable:i=>({onPointerDown:o=>{r.current=!1;let s=e.nodes[i];if(!s||!_e(o))return;let c;ve(o,(e,r)=>{!c&&Math.hypot(e,r)<Ee||(c||a(i),c={...t,[i]:{x:Math.max(s.x+e,0),y:Math.max(s.y+r,0)}},n(c,!1))},e=>{c&&(r.current=e,globalThis.setTimeout(()=>{r.current=!1},0),a(void 0),n(c,!0))})},onClickCapture:e=>{r.current&&(r.current=!1,e.stopPropagation(),e.preventDefault())},onKeyDown:r=>{let a=r.altKey?Oe[r.key]:void 0,o=e.nodes[i];if(!a||!o)return;r.preventDefault();let s=Math.max(o.x+a.x*De,0),c=Math.max(o.y+a.y*De,0);n({...t,[i]:{x:s,y:c}},!0)}})}}function je(e){let[t,n]=(0,Y.useState)(),[r,i]=(0,Y.useMemo)(()=>{if(t===void 0)return[new Set,new Set];let{ids:n,lines:r}=ne(e.lines,t);return[n,r]},[e,t]);return{lit:t,on:r,onLines:i,lights:e=>({onPointerEnter:()=>{n(e)},onPointerLeave:()=>{n(void 0)},onFocus:()=>{n(e)},onBlur:()=>{n(void 0)}})}}function Me(e,t,n){let r=(0,Y.useRef)(n.place);r.current=n.place;let{sizes:i}=n;(0,Y.useEffect)(()=>{let n=e.current;if(!n)return;let a=r.current,o=t===void 0?a:void 0;return ge(n,e=>{let{left:t,top:r}=me(n,e);return o===void 0?{left:t,top:r}:{left:t+o.x+i.node.width/2-e.clientWidth/2,top:r+o.y+o.height/2-e.clientHeight/2}})},[e,t,i])}function Ne(e,t,n){let{family:r,expanded:i,isMoved:a,showFamily:o,expand:s,tidy:c}=n,l=[];e&&e.id!==r&&l.push({label:`Show only its family`,icon:B,onClick:()=>{o(e.id)}});let u=e?.opens;u!==void 0&&l.push({label:`Open`,icon:m,onClick:()=>{t(u)}}),e&&l.push({type:`divider`});let d={label:`Show everything`,icon:f,onClick:()=>{o(void 0)}};return[...l,...r===void 0?[]:[d],{label:i?`Collapse`:`Expand`,icon:i?z:R,onClick:s},{label:`Tidy`,icon:V,isDisabled:!a,onClick:c}]}function Pe({actions:e,query:t,onQuery:n,onClose:a}){let{family:s,expanded:c,isMoved:l,showFamily:u,expand:d,tidy:p}=e;return(0,Z.jsxs)(`div`,{className:`studio-map-tools`,children:[(0,Z.jsx)(j,{label:`Search the map`,isLabelHidden:!0,size:`sm`,width:200,placeholder:`Search`,startIcon:g,hasClear:!0,value:t,onChange:n}),s!==void 0&&(0,Z.jsx)(o,{label:`Show everything`,variant:`ghost`,size:`sm`,icon:(0,Z.jsx)(r,{icon:f,size:`sm`}),onClick:()=>{u(void 0)}}),l&&(0,Z.jsx)(o,{label:`Tidy`,variant:`ghost`,size:`sm`,icon:(0,Z.jsx)(r,{icon:V,size:`sm`}),onClick:p}),(0,Z.jsx)(A,{label:c?`Collapse`:`Expand`,variant:`ghost`,size:`sm`,icon:(0,Z.jsx)(r,{icon:c?z:R,size:`sm`}),tooltip:c?`Show each node as a token`:`Show sections and descriptions`,onClick:d}),(0,Z.jsx)(A,{label:`Close map`,variant:`ghost`,size:`sm`,icon:(0,Z.jsx)(r,{icon:i,size:`sm`}),tooltip:`Close the map`,onClick:a})]})}function $({node:e,on:t,isFound:n,isDragging:r}){let i=t.has(e.id)||(e.rows??[]).some(e=>t.has(e.id));return{"data-map-node":e.id,"data-on":i?``:void 0,"data-found":n?``:void 0,"data-dragging":r?``:void 0}}function Fe(e){let{node:t,place:n,joins:r,selected:i,onOpen:a,lights:o,drag:s}=e,{opens:c}=t,l=Q(t,i);return(0,Z.jsx)(T,{id:t.id,label:Ce(t.long??t.label),icon:we(t),x:n.x,y:n.y+n.height/2,color:l?`blue`:void 0,description:[t.note,r].filter(Boolean).join(`. `)||void 0,onOpen:c===void 0?void 0:()=>{a(c)},title:(t.long??t.label).length>Se?t.long??t.label:void 0,"aria-current":l?`true`:void 0,...$(e),...o(t.id),...s})}function Ie(e){let{node:t,place:n,joins:i,selected:o,on:s,onOpen:c,lights:l,drag:u}=e,{opens:d}=t,f=t.rows??[],p={left:n.x,top:n.y,height:n.height},m=(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`span`,{className:`studio-map-name`,children:[(0,Z.jsx)(r,{icon:we(t),size:`sm`}),(0,Z.jsx)(a,{type:`supporting`,color:`inherit`,weight:`medium`,maxLines:1,hasTruncateTooltip:!1,children:t.label})]}),t.note&&(0,Z.jsx)(a,{type:`supporting`,maxLines:f.length>0?1:ae(t),hasTruncateTooltip:!1,className:`studio-map-note`,children:t.note})]}),h={type:`button`,title:t.note||void 0,"aria-description":i||void 0,disabled:d===void 0,onClick:()=>{d!==void 0&&c(d)},...l(t.id)};return f.length===0?(0,Z.jsx)(`button`,{...h,...u,...$(e),className:`studio-map-node`,"data-map-token":t.id,style:p,"aria-current":Q(t,o)?`true`:void 0,children:m}):(0,Z.jsxs)(`div`,{className:`studio-map-card`,"data-map-token":t.id,style:p,"data-open":Q(t,o)?``:void 0,...$(e),...u,children:[(0,Z.jsx)(`button`,{...h,className:`studio-map-head`,"aria-current":o===t.id?`true`:void 0,children:m}),f.map(e=>(0,Z.jsxs)(`button`,{type:`button`,className:`studio-map-row`,"aria-current":o===e.id?`true`:void 0,"data-on":s.has(e.id)?``:void 0,onClick:()=>{c(e.opens)},...l(e.id),children:[(0,Z.jsx)(r,{icon:Te(e.type),size:`sm`}),(0,Z.jsx)(a,{type:`supporting`,color:`inherit`,weight:`medium`,maxLines:1,hasTruncateTooltip:!1,children:e.label}),e.note&&(0,Z.jsx)(a,{type:`supporting`,maxLines:1,justify:`end`,hasTruncateTooltip:!1,className:`studio-map-row-note`,children:e.note})]},e.id))]})}function Le({workspace:e,shared:t,selected:n,onOpen:i,onClose:o}){let{expanded:s,family:l,map:u,moved:d,put:f,showFamily:p,expand:m}=ke((0,Y.useMemo)(()=>W(e,t),[e,t])),[_,v]=(0,Y.useState)(``),y=(0,Y.useMemo)(()=>ee(u,_),[u,_]),b=(0,Y.useMemo)(()=>_.trim()===``?u:te(u,y),[u,_,y]),x=_.trim()!==``&&y.length===0,S=(0,Y.useRef)(null),w=s?xe:be,T=(0,Y.useMemo)(()=>({map:b,expanded:s}),[b,s]),E=C(S,T),D=(0,Y.useMemo)(()=>ce(b,w,{moved:d,widths:E,detail:s}),[b,w,s,d,E]),O=b.columns.flat().flatMap(e=>e.nodes),A=O.find(e=>Q(e,n))?.id;Me(S,l,{place:A===void 0?void 0:D.nodes[A],sizes:w});let{dragging:j,draggable:M}=Ae(D,d,f),{panning:N,pan:F}=ye(`[data-map-node]`),{lit:I,on:L,onLines:R,lights:z}=je(D),B={family:l,expanded:s,isMoved:O.some(e=>Object.hasOwn(d,e.id)),showFamily:p,expand:m,tidy:()=>{f({},!0)}},[V,H]=(0,Y.useState)(),U=Ne(O.find(e=>e.id===V),i,B),G=s?Ie:Fe,K=e=>R.has(e.link)?2:+(e.from===A||e.to===A),ne=[...D.lines].sort((e,t)=>K(e)-K(t));return(0,Z.jsxs)(`div`,{className:`studio-map-frame`,role:`none`,onKeyDown:e=>{e.key===`Escape`&&l!==void 0&&(e.target.closest(`[role="menu"]`)||(e.stopPropagation(),p(void 0)))},children:[(0,Z.jsx)(c,{className:`studio-map-scroll`,axis:`both`,role:`region`,label:`Map`,height:`100%`,overscroll:`allow`,children:(0,Z.jsx)(P,{items:U,label:`Map actions`,"data-map-field":``,children:(0,Z.jsxs)(`div`,{ref:S,className:`studio-map`,"data-lit":I===void 0||j!==void 0?void 0:``,"data-panning":N?``:void 0,onPointerDown:F,onContextMenuCapture:e=>{H(e.target.closest(`[data-map-node]`)?.dataset.mapNode)},style:{"--map-width":`${String(D.width)}px`,"--map-height":`${String(D.height)}px`,"--map-slot":`${String(w.node.width)}px`,"--map-line":`${String(w.card.row)}px`},children:[(0,Z.jsx)(`svg`,{className:`studio-map-lines`,width:D.width,height:D.height,"aria-hidden":`true`,children:ne.map(({link:e,from:t,to:n,d:r})=>(0,Z.jsx)(`path`,{className:`map-line`,d:r,"data-kind":e.kind,"data-on":R.has(e)?``:void 0,"data-open":t===A||n===A?``:void 0},`${e.kind}:${e.from}:${e.to}`))}),D.headings.map(({label:e,x:t,y:n})=>(0,Z.jsx)(`div`,{className:`studio-map-heading`,style:{left:t,top:n},children:(0,Z.jsx)(a,{type:`supporting`,color:`secondary`,weight:`semibold`,children:e})},e)),O.map(e=>{let t=D.nodes[e.id];return t&&(0,Z.jsx)(G,{node:e,place:t,joins:ie(b,e.id),selected:n,on:L,isFound:y.includes(e.id),isDragging:j===e.id,onOpen:i,lights:z,drag:M(e.id)},e.id)})]})})}),x&&(0,Z.jsx)(h,{className:`studio-map-nothing`,children:(0,Z.jsx)(k,{headingLevel:2,icon:(0,Z.jsx)(r,{icon:g,size:`lg`}),title:`Nothing matches`})}),(0,Z.jsx)(Pe,{actions:B,query:_,onQuery:v,onClose:o})]})}export{Le as StudioMap};
|
|
1
|
+
import{r as e}from"./rolldown-runtime-hePW80VL.js";import{d as t,l as n}from"./themeProps-Bo2jNkIC.js";import{t as r}from"./Icon-Cd9sDRzY.js";import{t as i}from"./IconX-Cx51PGNB.js";import{t as a}from"./Text-Cq4yqBpQ.js";import{t as o}from"./Button-Bwkht0RI.js";import{t as s}from"./createReactComponent-DVEyVJ-p.js";import{t as c}from"./ScrollableArea-DgswAvfJ.js";import{a as l,n as u,o as d}from"./type-icons-DgazEJTc.js";import{n as f,r as p}from"./useAdaptivePresentation-D53OuCPm.js";import{n as m,t as h}from"./Center-CPu_uP6i.js";import{t as g}from"./IconSearch-BN1R3FIx.js";import{r as _,s as v,t as y}from"./tree-DXvClIpQ.js";import{F as b,i as x}from"./workspace-BpEiFb5f.js";import{i as S,n as C,r as w,t as T}from"./map-token-BcCSmfJy.js";import{i as E,n as D,o as O}from"./studio-session-ClF2iNCX.js";import{t as k}from"./EmptyState-DW-8doL9.js";import{t as A}from"./IconButton-BenRR-zK.js";import{t as j}from"./TextInput-DwHcdc-E.js";import{Et as M,an as N,ct as P,n as F,wt as I,y as L}from"./index-DdfSX5Od.js";var R=s(`outline`,`arrows-maximize`,`ArrowsMaximize`,[[`path`,{d:`M16 4l4 0l0 4`,key:`svg-0`}],[`path`,{d:`M14 10l6 -6`,key:`svg-1`}],[`path`,{d:`M8 20l-4 0l0 -4`,key:`svg-2`}],[`path`,{d:`M4 20l6 -6`,key:`svg-3`}],[`path`,{d:`M16 20l4 0l0 -4`,key:`svg-4`}],[`path`,{d:`M14 14l6 6`,key:`svg-5`}],[`path`,{d:`M8 4l-4 0l0 4`,key:`svg-6`}],[`path`,{d:`M4 4l6 6`,key:`svg-7`}]]),z=s(`outline`,`arrows-minimize`,`ArrowsMinimize`,[[`path`,{d:`M5 9l4 0l0 -4`,key:`svg-0`}],[`path`,{d:`M3 3l6 6`,key:`svg-1`}],[`path`,{d:`M5 15l4 0l0 4`,key:`svg-2`}],[`path`,{d:`M3 21l6 -6`,key:`svg-3`}],[`path`,{d:`M19 9l-4 0l0 -4`,key:`svg-4`}],[`path`,{d:`M15 9l6 -6`,key:`svg-5`}],[`path`,{d:`M19 15l-4 0l0 4`,key:`svg-6`}],[`path`,{d:`M15 15l6 6`,key:`svg-7`}]]),B=s(`outline`,`focus-2`,`Focus2`,[[`path`,{d:`M11.5 12a.5 .5 0 1 0 1 0a.5 .5 0 1 0 -1 0`,fill:`currentColor`,key:`svg-0`}],[`path`,{d:`M5 12a7 7 0 1 0 14 0a7 7 0 1 0 -14 0`,key:`svg-1`}],[`path`,{d:`M12 3l0 2`,key:`svg-2`}],[`path`,{d:`M3 12l2 0`,key:`svg-3`}],[`path`,{d:`M12 19l0 2`,key:`svg-4`}],[`path`,{d:`M19 12l2 0`,key:`svg-5`}]]),V=s(`outline`,`layout-grid`,`LayoutGrid`,[[`path`,{d:`M4 5a1 1 0 0 1 1 -1h4a1 1 0 0 1 1 1v4a1 1 0 0 1 -1 1h-4a1 1 0 0 1 -1 -1l0 -4`,key:`svg-0`}],[`path`,{d:`M14 5a1 1 0 0 1 1 -1h4a1 1 0 0 1 1 1v4a1 1 0 0 1 -1 1h-4a1 1 0 0 1 -1 -1l0 -4`,key:`svg-1`}],[`path`,{d:`M4 15a1 1 0 0 1 1 -1h4a1 1 0 0 1 1 1v4a1 1 0 0 1 -1 1h-4a1 1 0 0 1 -1 -1l0 -4`,key:`svg-2`}],[`path`,{d:`M14 15a1 1 0 0 1 1 -1h4a1 1 0 0 1 1 1v4a1 1 0 0 1 -1 1h-4a1 1 0 0 1 -1 -1l0 -4`,key:`svg-3`}]]);function H(e,t,n){let r=e=>{let r=t.flatMap(({from:t,to:n})=>t===e.id?[n]:n===e.id?[t]:[]).flatMap(e=>n.get(e)??[]);return r.length===0?1/0:r.reduce((e,t)=>e+t,0)/r.length},i=new Map(e.map(e=>[e.id,r(e)])),a=e=>i.get(e.id)??1/0;return[...e].sort((e,t)=>a(e)===a(t)?0:a(e)-a(t))}function U(e,t,n){return t===`models`?e.modelBindings.map(e=>e.modelId.trim()||`Unnamed model`).join(`, `):t===`tools`?String(e.tools.allow.filter(e=>n.has(e)).length):t===`outputs`?e.outputs.mode:``}function W(e,t=[]){let n=[],r=new Map(e.agents.map(e=>[e.key,x(e.key)])),i=new Map(e.toolSpecs.map(e=>[e.key,v(e.key)])),a=b(e),o=e.agents.map((e,t)=>{let{agentId:n,profileType:r,handle:o}=e.identity,s=r||`text`;return{id:x(e.key),kind:`agent`,label:n.trim()||`Unnamed agent`,note:o?`${s} · ${o}`:s,opens:x(e.key),type:s,rows:(a.agents[t]?.children??[]).map(t=>({id:t.id,label:t.label,note:U(e,t.ref.facet,i),opens:t.id,type:t.ref.facet}))}}),s=new Set(o.flatMap(e=>e.rows??[]).map(e=>e.id)),c=(e,t)=>{let n=x(e,t);return s.has(n)?n:x(e)},l=new Map,u=new Map(e.providers.map(e=>[e.id,e.definition])),d=new Map;for(let t of e.agents){let e=c(t.key,`models`);for(let i of t.modelBindings){let a=`model:${i.provider}:${i.apiId}:${i.modelId}`,o=_(i.provider);l.has(o)||l.set(o,{id:o,kind:`provider`,label:i.provider,note:``,opens:u.has(i.provider)?o:x(t.key,y(i.key))});let s=x(t.key,y(i.key)),c=d.get(a);c?c.holds?.push(s):(d.set(a,{id:a,kind:`model`,label:i.modelId.trim()||`Unnamed model`,note:i.apiId,opens:s,holds:[s]}),n.push({from:o,to:a,kind:`serves`})),n.some(t=>t.from===a&&t.to===e)||n.push({from:a,to:e,kind:`runs`});let f=i.compactWith?r.get(i.compactWith):void 0,p=n.some(t=>t.kind===`summarised`&&t.from===e);f&&f!==x(t.key)&&!p&&n.push({from:e,to:f,kind:`summarised`})}for(let e of t.tools.allow){let r=i.get(e);r&&n.push({from:c(t.key,`tools`),to:r,kind:`allows`})}}let f=e.toolSpecs.map(e=>{let t=v(e.key),i=e.toolType===`agent`?r.get(e.agentKey??``):r.get(e.stageAgentKey??``);return i&&n.push({from:t,to:i,kind:`asks`}),{id:t,kind:`tool`,label:e.toolName.trim()||`Unnamed tool`,note:e.description,opens:t,type:e.toolType}}),p=t.map(t=>{let{setting:i,facet:a}=t,o=`shared:${i.file}:${i.name}`,s=t.agents.filter(e=>r.has(e)),l=i.tools.flatMap(t=>{let n=e.toolSpecs.find(e=>e.toolName===t);return n?[v(n.key)]:[]});for(let e of s)n.push({from:o,to:a?c(e,a):x(e),kind:`sets`});for(let e of l)n.push({from:o,to:e,kind:`sets`});return{id:o,kind:`shared`,label:i.label,note:`${i.name} · ${i.file}:${String(i.line)}`,opens:M(t)??l[0],type:a}}),m=new Map(o.flatMap((e,t)=>[e.id,...(e.rows??[]).map(e=>e.id)].map(e=>[e,t])));for(let e of d.values())[...d.values()].some(t=>t!==e&&t.label===e.label)&&e.note&&(e.long=`${e.label} · ${e.note}`);let h=H([...d.values()],n,m),g=new Map(h.map((e,t)=>[e.id,t])),S=(...e)=>e.filter(e=>e.nodes.length>0);return{columns:[S({label:`Providers`,nodes:H([...l.values()],n,g)}),S({label:`Shared settings`,nodes:H(p,n,m)},{label:`Models`,nodes:h}),S({label:`Profiles`,nodes:o}),S({label:`Tools`,nodes:H(f,n,m)})].filter(e=>e.length>0),links:n}}function G(e){let t=e.columns.flat().flatMap(e=>e.nodes);return new Map(t.flatMap(e=>[e.id,...(e.rows??[]).map(e=>e.id)].map(t=>[t,e])))}function K(e){let t=G(e);return e.links.flatMap(e=>{let n=t.get(e.from)?.id,r=t.get(e.to)?.id;return n!==void 0&&r!==void 0?[{link:e,from:n,to:r}]:[]})}function ee(e,t){let n=t.trim().toLowerCase();return n===``?[]:e.columns.flat().flatMap(e=>e.nodes).filter(e=>[e.label,e.long??``,e.note].some(e=>e.toLowerCase().includes(n))).map(e=>e.id)}function te(e,t){let n=typeof t==`string`?[t]:t,r=K(e),i=(e,t)=>{let i=new Set(n),a=[...n];for(let n=a.pop();n!==void 0;n=a.pop())for(let o of r)o[e]!==n||i.has(o[t])||(i.add(o[t]),a.push(o[t]));return i},a=new Set([...i(`to`,`from`),...i(`from`,`to`)]),o=e.columns.map(e=>e.map(e=>({...e,nodes:e.nodes.filter(e=>a.has(e.id))})).filter(e=>e.nodes.length>0)).filter(e=>e.length>0),s=new Set(r.filter(({from:e,to:t})=>a.has(e)&&a.has(t)).map(({link:e})=>e));return{columns:o,links:e.links.filter(e=>s.has(e))}}function ne(e,t){let n=new Set([t]),r=new Set,i=(i,a)=>{let o=new Set,s=[t];for(let t=s.pop();t!==void 0;t=s.pop())for(let c of e)(c[i]===t||c.link[i]===t)&&(r.add(c.link),n.add(c.link.from).add(c.link.to).add(c.from).add(c.to),!o.has(c[a])&&(o.add(c[a]),s.push(c[a])))};return i(`to`,`from`),i(`from`,`to`),{ids:n,lines:r}}var re={serves:[`Serves`,`Served by`],sets:[`Sets`,`Set by`],runs:[`Runs`,`Runs on`],allows:[`Allows`,`Allowed by`],asks:[`Asks`,`Asked by`],summarised:[`Summarised by`,`Summarises for`]};function ie(e,t){let n=G(e),r=new Map;for(let{link:i,from:a,to:o}of K(e)){if(a!==t&&o!==t)continue;let e=re[i.kind][a===t?0:1],s=n.get(a===t?o:a)?.label;s!==void 0&&r.set(e,[...r.get(e)??[],s])}return[...r].map(([e,t])=>`${e} ${t.join(`, `)}.`).join(` `)}function ae(e){return e.kind===`tool`||e.kind===`shared`?2:1}var oe=24,q=8,J=16;function se(e,t,n){let r=new Map,i=(e,t)=>`${e}:${String(t)}`;return K(e).flatMap(({link:e})=>{let[a,o]=[t(e.from),t(e.to)];if(a===void 0||o===void 0||Math.abs(a-o)<n)return[];let s=a<o?1:-1;for(let t of[i(e.from,s),i(e.to,-s)])r.set(t,(r.get(t)??0)+1);return[{link:e,way:s}]}).map(({link:e,way:t})=>{let[n,a]=[i(e.from,t),i(e.to,-t)],o=(r.get(n)??0)>=(r.get(a)??0);return{link:e,way:t,leaves:o,hub:o?n:a}})}function ce(e,t,n={}){let{node:r,card:i,columnGap:a,rowGap:o,heading:s,groupGap:c,padding:l,lineGap:u}=t,{moved:d={},widths:f={},detail:p=!1}=n,m=new Map;e.columns.forEach((e,t)=>{for(let n of e)for(let e of n.nodes)if(!Object.hasOwn(d,e.id))for(let n of[e.id,...(e.rows??[]).map(e=>e.id)])m.set(n,t)});let h=t=>{let n={},a=[],u=[],m=new Map,h=0,g=0;return e.columns.forEach((e,_)=>{let v=t[_]??l,y=l;e.forEach((e,t)=>{t>0&&(y+=c),a.push({label:e.label,x:v,y}),u.push({id:`heading:${_}:${t}`,x:v,y,width:r.width,height:s}),y+=s;for(let t of e.nodes){let e=p?t.rows??[]:[],a=e.length>0||t.note!==``,s=p&&(e.length>0||ae(t)===1)?i.head:r.height,c=p&&!a?i.row:s,l=e.length>0?i.head+e.length*i.row+i.foot:c,_=Math.min(f[t.id]??r.width,r.width),b=Object.hasOwn(d,t.id)?d[t.id]:void 0,x=b?{x:Math.max(b.x,0),y:Math.max(b.y,0)}:{x:v,y};n[t.id]={...x,height:l},u.push({id:t.id,...x,width:_,height:l});let S={left:x.x,right:x.x+_,y:x.y+(p?i.row:c)/2};m.set(t.id,S);for(let[e,n]of(t.rows??[]).entries())m.set(n.id,p?{...S,y:x.y+i.head+e*i.row+i.row/2}:S);h=Math.max(h,x.x+r.width),g=Math.max(g,x.y+l),y+=l+o}y-=o})}),{nodes:n,headings:a,boxes:u,ports:m,right:h,bottom:g}},g=(e,t,n)=>{let{way:i,leaves:a}=e,o={x:i>0?t.right+u:t.left-u,y:t.y},s={x:i>0?n.left-u:n.right+u,y:n.y},c=i>0?Math.max(t.left+r.width,t.right)+u:o.x,l=i>0?s.x:Math.max(n.left+r.width,n.right)+u,d=a?l:c,f=a?-i:i;return{start:o,end:s,side:d,into:f,room:Math.abs(l-c),strip:`${String(d)}:${String(f)}`}},_=t=>{let n=new Map(se(e,e=>t.get(e)?.left,r.width).map(e=>[e.link,e])),i=new Map;for(let e of n.values()){let n=t.get(e.link.from),r=t.get(e.link.to);if(!n||!r||n.y===r.y)continue;let{strip:a}=g(e,n,r),o=i.get(a)??new Map,s=e.leaves?e.link.to:e.link.from,c=o.get(e.hub)??{y:e.leaves?n.y:r.y,joins:[],beside:s};c.joins.push(e.leaves?r.y:n.y),i.set(a,o.set(e.hub,c))}let a=new Map,o=new Map;for(let[e,t]of i){let n=e=>e.reduce((e,t)=>e+t,0)/e.length,r=[...t.values()],i=n(r.flatMap(e=>e.joins))>=n(r.map(e=>e.y)),s=[];for(let[n,r]of[...t].sort(([,e],[,t])=>i?e.y-t.y:t.y-e.y)){let t=Math.min(r.y,...r.joins)-q,i=Math.max(r.y,...r.joins)+q,o=s.findIndex(e=>e.every(e=>i<e.low||t>e.high)),c=o<0?s.length:o;s[c]=[...s[c]??[],{low:t,high:i}],a.set(`${e}:${n}`,c)}let[c]=r;c&&o.set(e,{count:s.length,beside:c.beside,into:Number(e.split(`:`)[1])})}return{spans:n,rails:a,held:o}},v=e.columns.map((e,t)=>l+t*(r.width+a)),y=e.columns.map(()=>0);for(let{count:e,beside:t,into:n}of _(h(v).ports).held.values()){let r=m.get(t);if(r===void 0)continue;let i=n>0?r:r-1;i>=0&&i<y.length&&(y[i]=(y[i]??0)+e+1)}let b=[l];for(let[e,t]of y.entries())b.push((b[e]??l)+r.width+Math.max(a,t*J));let x=h(b),{nodes:C,headings:T,boxes:E,ports:D}=x,{right:O,bottom:k}=x,{spans:A,rails:j}=_(D),M=a/2,N=Math.max(o/2,u),P=[],F=new Map,I=Math.max(a,...y.map(e=>e*J)),L=K(e).flatMap(({link:e,from:t,to:n})=>{let i=D.get(e.from),o=D.get(e.to);if(!i||!o)return[];let s=E.filter(e=>e.id!==t&&e.id!==n);if(Math.abs(i.left-o.left)<r.width){let r=i.right+u,a=o.right+u,c=s.filter(e=>e.y<Math.max(i.y,o.y)&&e.y+e.height>Math.min(i.y,o.y)&&e.x<Math.max(r,a)+M&&e.x+e.width>Math.min(i.left,o.left)),l=Math.max(r,a,...c.map(e=>e.x+e.width))+M;return O=Math.max(O,l),[{link:e,from:t,to:n,d:w({x:r,y:i.y},{x:a,y:o.y},l).d}]}let c=A.get(e);if(!c)return[];let{way:l,leaves:d,hub:f}=c,{start:p,end:m,side:h,into:_,room:v,strip:y}=g(c,i,o),b=h+_*Math.min((1+(j.get(`${y}:${f}`)??0))*J,Math.max(v-J,0)),x=v<32?w(p,m):S(p,m,b,q),C=(e,t)=>t>e.y-N&&t<e.y+e.height+N,T=Math.abs(m.x-p.x)<I+a?[]:s.filter(e=>Array.from({length:23},(e,t)=>x.at((t+1)/oe)).some(t=>t.x>e.x&&t.x<e.x+e.width&&C(e,t.y)));if(T.length===0)return[{link:e,from:t,to:n,d:x.d}];let[L,R]=[Math.min(p.x,m.x),Math.max(p.x,m.x)],z=e=>{let t=[...T];for(;;){let n=e<0?Math.min(...t.map(e=>e.y))-N:Math.max(...t.map(e=>e.y+e.height))+N,r=[...s,...P].filter(e=>!t.includes(e)&&e.x<R&&e.x+e.width>L&&C(e,n));if(r.length===0)return n;t.push(...r)}},B=e=>Math.abs(i.y-e)+Math.abs(o.y-e),V=`${f}:${y}`,H=F.get(V)??(()=>{let[e,t]=[z(-1),z(1)],n=e>=0&&B(e)<=B(t)?e:t;return P.push({id:``,x:L,y:n-q+N,width:R-L,height:2*(q-N)}),F.set(V,n),n})();k=Math.max(k,H);let U=d?p.x+l*J:b,W=d?b:m.x-l*J,G={x:(U+W)/2,y:H};return[{link:e,from:t,to:n,d:S(p,G,U,q).d+S(G,m,W,q).d.replace(/^M \S+ \S+/,``)}]});return{width:Math.max((b[Math.max(e.columns.length-1,0)]??l)+r.width,O)+l,height:Math.max(k,l)+l,nodes:C,headings:T,lines:L}}var Y=e(t(),1),le={tokens:{},detail:{},expanded:!1},X=e=>e===void 0?`${D}.map`:`${D}.map.project:${e}`;function ue(e){if(!E(e))return{};let t={};for(let[n,r]of Object.entries(e))E(r)&&typeof r.x==`number`&&typeof r.y==`number`&&(t[n]={x:r.x,y:r.y});return t}function de(e){try{let t=JSON.parse(O()?.getItem(X(e))??`null`);return E(t)?{tokens:ue(t.tokens),detail:ue(t.detail),expanded:t.expanded===!0,...typeof t.family==`string`?{family:t.family}:{}}:le}catch{return le}}function fe(e,t){let{tokens:n,detail:r,expanded:i,family:a}=t;Object.keys(n).length===0&&Object.keys(r).length===0&&!i&&a===void 0?O()?.removeItem(X(e)):O()?.setItem(X(e),JSON.stringify(t))}function pe(e){for(let t=e.parentElement;t;t=t.parentElement){let{overflowX:e,overflowY:n}=getComputedStyle(t);if(/auto|scroll/.test(`${e} ${n}`))return t}}function me(e,t){let n=e.getBoundingClientRect(),r=t.getBoundingClientRect();return{left:n.left-r.left+t.scrollLeft,top:n.top-r.top+t.scrollTop}}var he=(e,t)=>Math.min(Math.max(e,0),Math.max(t,0));function ge(e,t){let n=0,r=120,i=()=>{--r;let a=pe(e);if(a&&a.scrollWidth>a.clientWidth){let e=t(a),n=he(e.left,a.scrollWidth-a.clientWidth),r=he(e.top,a.scrollHeight-a.clientHeight);if(a.scrollTo({left:n,top:r,behavior:`instant`}),Math.abs(a.scrollLeft-n)<1&&Math.abs(a.scrollTop-r)<1)return}r>0&&(n=requestAnimationFrame(i))};return i(),()=>{cancelAnimationFrame(n)}}var _e=e=>e.button===0&&e.pointerType!==`touch`;function ve(e,t,n){let{pointerId:r,clientX:i,clientY:a}=e,o=e=>{e.pointerId===r&&t(e.clientX-i,e.clientY-a)},s=e=>{e.pointerId===r&&(globalThis.removeEventListener(`pointermove`,o),globalThis.removeEventListener(`pointerup`,s),globalThis.removeEventListener(`pointercancel`,s),n(e.type===`pointerup`))};globalThis.addEventListener(`pointermove`,o),globalThis.addEventListener(`pointerup`,s),globalThis.addEventListener(`pointercancel`,s)}function ye(e){let[t,n]=(0,Y.useState)(!1);return{panning:t,pan:t=>{if(!_e(t)||t.target.closest(e))return;let r=pe(t.currentTarget);if(!r)return;let{scrollLeft:i,scrollTop:a}=r;n(!0),ve(t,(e,t)=>{r.scrollTo({left:i-e,top:a-t,behavior:`instant`})},()=>{n(!1)})}}}var Z=n(),be={node:{width:240,height:24},card:{head:60,row:28,foot:4},columnGap:96,rowGap:6,heading:24,groupGap:16,padding:24,lineGap:8},xe={...be,node:{width:240,height:84}},Se=28;function Ce(e){return e.length>Se?`${e.slice(0,27)}…`:e}function we({kind:e,type:t,note:n}){return(e===`agent`?l(t):void 0)||(e===`tool`?d(t??``):e===`model`?L(n)??F.modelBinding:e===`provider`?N:e===`shared`&&t&&Object.hasOwn(F,t)?F[t]:e===`agent`?u.text:p)}function Te(e){return Object.hasOwn(F,e)?F[e]:p}function Q(e,t){return e.kind===`agent`?t===e.id||t.startsWith(`${e.id}/`):e.kind===`model`?e.holds?.includes(t)??!1:e.kind===`tool`&&t===e.id}var Ee=4,De=24,Oe={ArrowLeft:{x:-1,y:0},ArrowRight:{x:1,y:0},ArrowUp:{x:0,y:-1},ArrowDown:{x:0,y:1}};function ke(e){let t=I()?.name,[n,r]=(0,Y.useState)(()=>de(t)),i=e=>{r(e),fe(t,e)},{expanded:a}=n,o=e.columns.flat().some(e=>e.nodes.some(e=>e.id===n.family))?n.family:void 0,s=(0,Y.useMemo)(()=>o===void 0?e:te(e,o),[e,o]),[c,l]=(0,Y.useState)({}),u=a?`detail`:`tokens`;return{expanded:a,family:o,map:s,moved:o===void 0?n[u]:c,put(e,t){o===void 0?t?i({...n,[u]:e}):r({...n,[u]:e}):l(e)},showFamily(e){l({});let{tokens:t,detail:r}=n;i({tokens:t,detail:r,expanded:a,...e===void 0?{}:{family:e}})},expand(){i({...n,expanded:!a})}}}function Ae(e,t,n){let r=(0,Y.useRef)(!1),[i,a]=(0,Y.useState)();return{dragging:i,draggable:i=>({onPointerDown:o=>{r.current=!1;let s=e.nodes[i];if(!s||!_e(o))return;let c;ve(o,(e,r)=>{!c&&Math.hypot(e,r)<Ee||(c||a(i),c={...t,[i]:{x:Math.max(s.x+e,0),y:Math.max(s.y+r,0)}},n(c,!1))},e=>{c&&(r.current=e,globalThis.setTimeout(()=>{r.current=!1},0),a(void 0),n(c,!0))})},onClickCapture:e=>{r.current&&(r.current=!1,e.stopPropagation(),e.preventDefault())},onKeyDown:r=>{let a=r.altKey?Oe[r.key]:void 0,o=e.nodes[i];if(!a||!o)return;r.preventDefault();let s=Math.max(o.x+a.x*De,0),c=Math.max(o.y+a.y*De,0);n({...t,[i]:{x:s,y:c}},!0)}})}}function je(e){let[t,n]=(0,Y.useState)(),[r,i]=(0,Y.useMemo)(()=>{if(t===void 0)return[new Set,new Set];let{ids:n,lines:r}=ne(e.lines,t);return[n,r]},[e,t]);return{lit:t,on:r,onLines:i,lights:e=>({onPointerEnter:()=>{n(e)},onPointerLeave:()=>{n(void 0)},onFocus:()=>{n(e)},onBlur:()=>{n(void 0)}})}}function Me(e,t,n){let r=(0,Y.useRef)(n.place);r.current=n.place;let{sizes:i}=n;(0,Y.useEffect)(()=>{let n=e.current;if(!n)return;let a=r.current,o=t===void 0?a:void 0;return ge(n,e=>{let{left:t,top:r}=me(n,e);return o===void 0?{left:t,top:r}:{left:t+o.x+i.node.width/2-e.clientWidth/2,top:r+o.y+o.height/2-e.clientHeight/2}})},[e,t,i])}function Ne(e,t,n){let{family:r,expanded:i,isMoved:a,showFamily:o,expand:s,tidy:c}=n,l=[];e&&e.id!==r&&l.push({label:`Show only its family`,icon:B,onClick:()=>{o(e.id)}});let u=e?.opens;u!==void 0&&l.push({label:`Open`,icon:m,onClick:()=>{t(u)}}),e&&l.push({type:`divider`});let d={label:`Show everything`,icon:f,onClick:()=>{o(void 0)}};return[...l,...r===void 0?[]:[d],{label:i?`Collapse`:`Expand`,icon:i?z:R,onClick:s},{label:`Tidy`,icon:V,isDisabled:!a,onClick:c}]}function Pe({actions:e,query:t,onQuery:n,onClose:a}){let{family:s,expanded:c,isMoved:l,showFamily:u,expand:d,tidy:p}=e;return(0,Z.jsxs)(`div`,{className:`studio-map-tools`,children:[(0,Z.jsx)(j,{label:`Search the map`,isLabelHidden:!0,size:`sm`,width:200,placeholder:`Search`,startIcon:g,hasClear:!0,value:t,onChange:n}),s!==void 0&&(0,Z.jsx)(o,{label:`Show everything`,variant:`ghost`,size:`sm`,icon:(0,Z.jsx)(r,{icon:f,size:`sm`}),onClick:()=>{u(void 0)}}),l&&(0,Z.jsx)(o,{label:`Tidy`,variant:`ghost`,size:`sm`,icon:(0,Z.jsx)(r,{icon:V,size:`sm`}),onClick:p}),(0,Z.jsx)(A,{label:c?`Collapse`:`Expand`,variant:`ghost`,size:`sm`,icon:(0,Z.jsx)(r,{icon:c?z:R,size:`sm`}),tooltip:c?`Show each node as a token`:`Show sections and descriptions`,onClick:d}),(0,Z.jsx)(A,{label:`Close map`,variant:`ghost`,size:`sm`,icon:(0,Z.jsx)(r,{icon:i,size:`sm`}),tooltip:`Close the map`,onClick:a})]})}function $({node:e,on:t,isFound:n,isDragging:r}){let i=t.has(e.id)||(e.rows??[]).some(e=>t.has(e.id));return{"data-map-node":e.id,"data-on":i?``:void 0,"data-found":n?``:void 0,"data-dragging":r?``:void 0}}function Fe(e){let{node:t,place:n,joins:r,selected:i,onOpen:a,lights:o,drag:s}=e,{opens:c}=t,l=Q(t,i);return(0,Z.jsx)(T,{id:t.id,label:Ce(t.long??t.label),icon:we(t),x:n.x,y:n.y+n.height/2,color:l?`blue`:void 0,description:[t.note,r].filter(Boolean).join(`. `)||void 0,onOpen:c===void 0?void 0:()=>{a(c)},title:(t.long??t.label).length>Se?t.long??t.label:void 0,"aria-current":l?`true`:void 0,...$(e),...o(t.id),...s})}function Ie(e){let{node:t,place:n,joins:i,selected:o,on:s,onOpen:c,lights:l,drag:u}=e,{opens:d}=t,f=t.rows??[],p={left:n.x,top:n.y,height:n.height},m=(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`span`,{className:`studio-map-name`,children:[(0,Z.jsx)(r,{icon:we(t),size:`sm`}),(0,Z.jsx)(a,{type:`supporting`,color:`inherit`,weight:`medium`,maxLines:1,hasTruncateTooltip:!1,children:t.label})]}),t.note&&(0,Z.jsx)(a,{type:`supporting`,maxLines:f.length>0?1:ae(t),hasTruncateTooltip:!1,className:`studio-map-note`,children:t.note})]}),h={type:`button`,title:t.note||void 0,"aria-description":i||void 0,disabled:d===void 0,onClick:()=>{d!==void 0&&c(d)},...l(t.id)};return f.length===0?(0,Z.jsx)(`button`,{...h,...u,...$(e),className:`studio-map-node`,"data-map-token":t.id,style:p,"aria-current":Q(t,o)?`true`:void 0,children:m}):(0,Z.jsxs)(`div`,{className:`studio-map-card`,"data-map-token":t.id,style:p,"data-open":Q(t,o)?``:void 0,...$(e),...u,children:[(0,Z.jsx)(`button`,{...h,className:`studio-map-head`,"aria-current":o===t.id?`true`:void 0,children:m}),f.map(e=>(0,Z.jsxs)(`button`,{type:`button`,className:`studio-map-row`,"aria-current":o===e.id?`true`:void 0,"data-on":s.has(e.id)?``:void 0,onClick:()=>{c(e.opens)},...l(e.id),children:[(0,Z.jsx)(r,{icon:Te(e.type),size:`sm`}),(0,Z.jsx)(a,{type:`supporting`,color:`inherit`,weight:`medium`,maxLines:1,hasTruncateTooltip:!1,children:e.label}),e.note&&(0,Z.jsx)(a,{type:`supporting`,maxLines:1,justify:`end`,hasTruncateTooltip:!1,className:`studio-map-row-note`,children:e.note})]},e.id))]})}function Le({workspace:e,shared:t,selected:n,onOpen:i,onClose:o}){let{expanded:s,family:l,map:u,moved:d,put:f,showFamily:p,expand:m}=ke((0,Y.useMemo)(()=>W(e,t),[e,t])),[_,v]=(0,Y.useState)(``),y=(0,Y.useMemo)(()=>ee(u,_),[u,_]),b=(0,Y.useMemo)(()=>_.trim()===``?u:te(u,y),[u,_,y]),x=_.trim()!==``&&y.length===0,S=(0,Y.useRef)(null),w=s?xe:be,T=(0,Y.useMemo)(()=>({map:b,expanded:s}),[b,s]),E=C(S,T),D=(0,Y.useMemo)(()=>ce(b,w,{moved:d,widths:E,detail:s}),[b,w,s,d,E]),O=b.columns.flat().flatMap(e=>e.nodes),A=O.find(e=>Q(e,n))?.id;Me(S,l,{place:A===void 0?void 0:D.nodes[A],sizes:w});let{dragging:j,draggable:M}=Ae(D,d,f),{panning:N,pan:F}=ye(`[data-map-node]`),{lit:I,on:L,onLines:R,lights:z}=je(D),B={family:l,expanded:s,isMoved:O.some(e=>Object.hasOwn(d,e.id)),showFamily:p,expand:m,tidy:()=>{f({},!0)}},[V,H]=(0,Y.useState)(),U=Ne(O.find(e=>e.id===V),i,B),G=s?Ie:Fe,K=e=>R.has(e.link)?2:+(e.from===A||e.to===A),ne=[...D.lines].sort((e,t)=>K(e)-K(t));return(0,Z.jsxs)(`div`,{className:`studio-map-frame`,role:`none`,onKeyDown:e=>{e.key===`Escape`&&l!==void 0&&(e.target.closest(`[role="menu"]`)||(e.stopPropagation(),p(void 0)))},children:[(0,Z.jsx)(c,{className:`studio-map-scroll`,axis:`both`,role:`region`,label:`Map`,height:`100%`,overscroll:`allow`,children:(0,Z.jsx)(P,{items:U,label:`Map actions`,"data-map-field":``,children:(0,Z.jsxs)(`div`,{ref:S,className:`studio-map`,"data-lit":I===void 0||j!==void 0?void 0:``,"data-panning":N?``:void 0,onPointerDown:F,onContextMenuCapture:e=>{H(e.target.closest(`[data-map-node]`)?.dataset.mapNode)},style:{"--map-width":`${String(D.width)}px`,"--map-height":`${String(D.height)}px`,"--map-slot":`${String(w.node.width)}px`,"--map-line":`${String(w.card.row)}px`},children:[(0,Z.jsx)(`svg`,{className:`studio-map-lines`,width:D.width,height:D.height,"aria-hidden":`true`,children:ne.map(({link:e,from:t,to:n,d:r})=>(0,Z.jsx)(`path`,{className:`map-line`,d:r,"data-kind":e.kind,"data-on":R.has(e)?``:void 0,"data-open":t===A||n===A?``:void 0},`${e.kind}:${e.from}:${e.to}`))}),D.headings.map(({label:e,x:t,y:n})=>(0,Z.jsx)(`div`,{className:`studio-map-heading`,style:{left:t,top:n},children:(0,Z.jsx)(a,{type:`supporting`,color:`secondary`,weight:`semibold`,children:e})},e)),O.map(e=>{let t=D.nodes[e.id];return t&&(0,Z.jsx)(G,{node:e,place:t,joins:ie(b,e.id),selected:n,on:L,isFound:y.includes(e.id),isDragging:j===e.id,onOpen:i,lights:z,drag:M(e.id)},e.id)})]})})}),x&&(0,Z.jsx)(h,{className:`studio-map-nothing`,children:(0,Z.jsx)(k,{headingLevel:2,icon:(0,Z.jsx)(r,{icon:g,size:`lg`}),title:`Nothing matches`})}),(0,Z.jsx)(Pe,{actions:B,query:_,onQuery:v,onClose:o})]})}export{Le as StudioMap};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{r as e}from"./rolldown-runtime-hePW80VL.js";import{d as t,l as n}from"./themeProps-Bo2jNkIC.js";import{t as r}from"./Icon-Cd9sDRzY.js";import{t as i}from"./IconX-Cx51PGNB.js";import{t as a}from"./Text-Cq4yqBpQ.js";import{t as o}from"./Button-Bwkht0RI.js";import{_ as s,a as c,f as l,g as u,o as d,p as f,s as p}from"./browser-transport-
|
|
1
|
+
import{r as e}from"./rolldown-runtime-hePW80VL.js";import{d as t,l as n}from"./themeProps-Bo2jNkIC.js";import{t as r}from"./Icon-Cd9sDRzY.js";import{t as i}from"./IconX-Cx51PGNB.js";import{t as a}from"./Text-Cq4yqBpQ.js";import{t as o}from"./Button-Bwkht0RI.js";import{_ as s,a as c,f as l,g as u,o as d,p as f,s as p}from"./browser-transport-C4b9Cns1.js";import{i as m,r as h}from"./row-keys-0Bn7ZyYy.js";import{g,t as _}from"./studio-labels-EVPkcfTG.js";import{t as v}from"./IconHistory-DdcWdeRG.js";import{dn as y}from"./shaped-data-9kDvR1de.js";import{c as b}from"./host-patterns-F-KZIzkF.js";import{n as x}from"./trace-record-DFHRIoSR.js";import{n as S}from"./trace-schema--4IGmLeE.js";import{v as C}from"./turn-client-Cl1P1QP9.js";import{n as w,t as T}from"./labels-provider-BO_XYaPQ.js";import{t as E}from"./HStack-B00ufja5.js";import{t as D}from"./IconButton-BenRR-zK.js";import{t as O}from"./VStack-D1ZLA9g3.js";import{t as k}from"./StackItem-nWHq5y--.js";import{a as A,i as j,o as M,t as N}from"./ConsoleFrame-DjKftiM3.js";import{Ct as ee,H as te,L as ne,M as re,N as ie,P as ae,T as P,en as oe,s as F,u as se,w as ce,wt as le}from"./index-DdfSX5Od.js";var I=e=>typeof e==`object`&&!!e&&!Array.isArray(e),L=(e,t)=>e.attributes[t],R=(e,t)=>{let n=L(e,t);return typeof n==`string`?n:void 0};function z(e,t,n){let r=L(t,n);return r===void 0?void 0:x(e,r)}function B(e,t,n){let r=z(e,t,n);return r===void 0?``:typeof r==`string`?r:JSON.stringify(r)}function V(e,t,n){let r=z(e,t,n);return Array.isArray(r)?r.filter(I):[]}var H=e=>Array.isArray(e.parts)?e.parts.filter(I):[],U=e=>BigInt(String(e.startTimeUnixNano)),W=(e,t)=>{let n=U(e)-U(t);return n===0n?0:n<0n?-1:1};function G(e){let t=e.endTimeUnixNano;if(!t)return;let n=U(e),r=BigInt(String(t));if(r<=n)return;let i=Number(n/1000000n),a=Number(r/1000000n);if(!(!Number.isFinite(i)||!Number.isFinite(a)||a<=i))return{startedAt:i,endedAt:a}}function ue(e){let t=G(e);if(t)return{workedMs:t.endedAt-t.startedAt,endedAt:t.endedAt}}function de(e,t){let n=ue(t);if(!n)return e;let r=e.findLastIndex(e=>e.kind===`turn-done`);return r<0?e:e.map((e,t)=>t===r?{...e,...n}:e)}var fe=e=>`content_sha256`in e||`json_sha256`in e;function K(e){let t=e.arguments;if(I(t))return t;if(typeof t!=`string`)return{};try{let e=JSON.parse(t);return I(e)?e:{}}catch{return{}}}function q(e){if(typeof e.content==`string`){if(e.type===`reasoning`)return{type:`thought`,text:e.content};if(e.type===`text`)return{type:`text`,text:e.content}}}function pe(e){let t=[],n=[],r=!1;for(let i of e){let e=H(i),a=e.some(e=>e.type===`text`);for(let i of e){let e=q(i);fe(i)?r=!0:e?t.push(e):i.type===`structured`&&!a?t.push({type:`text`,text:JSON.stringify(i.content)}):i.type===`tool_call`&&typeof i.name==`string`?(n.push(i.name),t.push({type:`tool`,tool:{name:i.name,callId:typeof i.id==`string`?i.id:`replay-${String(n.length)}`,arguments:K(i)}})):(i.type===`blob`||i.type===`uri`)&&(r=!0)}}return{events:t,calls:n,missing:r}}function me(e,t){for(let n=e;n;n=t.get(n.parentSpanId??``)){let e=R(n,`gen_ai.agent.name`);if(R(n,`gen_ai.operation.name`)===`invoke_agent`&&e)return e}return``}var J=e=>R(e,`gen_ai.operation.name`);function he(e){let t=new Map(e.spans.map(e=>[e.spanId,e]));return e.spans.filter(e=>J(e)===`chat`).toSorted(W).map(n=>{let r=pe(V(e,n,`gen_ai.output.messages`)),i=R(n,`theorem.stop.kind`)??`completed`;return{agent:me(n,t),...r,events:[...r.events,{type:`done`,stop:{kind:i}}]}})}function ge(e){return e.spans.filter(e=>J(e)===`execute_tool`).toSorted(W).map(t=>({name:R(t,`gen_ai.tool.name`)??``,result:B(e,t,`gen_ai.tool.call.result`),failed:R(t,`theorem.tool.outcome`)===`error`}))}function Y(e,t){let n=V(e,t,`gen_ai.input.messages`).findLast(e=>e.role===`user`),r=n?H(n):[];return{text:r.flatMap(e=>e.type===`text`&&typeof e.content==`string`?[e.content]:[]).join(`
|
|
2
2
|
`),attachments:r.filter(e=>e.type===`blob`||e.type===`uri`).length}}function _e(e,t){let n=[];for(let r of t.events??[]){if(r.name!==`theorem.grounding`)continue;let i=r.attributes.sources;if(i===void 0)continue;let a=x(e,i);if(!Array.isArray(a))continue;let o=[];for(let e of a)I(e)&&typeof e.title==`string`&&typeof e.uri==`string`&&o.push({title:e.title,uri:e.uri,type:e.type===`maps`?`maps`:`web`,...typeof e.placeId==`string`?{placeId:e.placeId}:{}});if(o.length){let e=R(t,`gen_ai.tool.call.id`);n.push({type:`citation`,sources:o,...e?{callId:e}:{}})}}return n}function ve(e,t){let n=e.spans.filter(e=>J(e)===`execute_tool`).toSorted(W),r=new Set,i=(e,t)=>{let i=n.find(t=>R(t,`gen_ai.tool.call.id`)===e)??n.find(e=>!r.has(e)&&R(e,`gen_ai.tool.name`)===t);return i&&r.add(i),i},a=[];for(let n of V(e,t,`gen_ai.output.messages`))for(let t of H(n)){let n=q(t);if(n)a.push(n);else if(t.type===`structured`&&t.content!==void 0)a.push({type:`structured`,structured:t.content});else if(t.type===`tool_call`&&typeof t.name==`string`){let n=typeof t.id==`string`?t.id:`call-${String(a.length)}`;a.push(...ye(e,t.name,n,K(t),i))}}let o=B(e,t,`theorem.error.public`);t.status.code===`ERROR`&&a.push({type:`error`,errorKind:`internal`,error:o||t.status.message});let s=R(t,`theorem.stop.kind`)??`completed`;return a.push({type:`done`,stop:{kind:s}}),a}function ye(e,t,n,r,i){let a=i(n,t),o={type:`tool`,tool:{name:t,callId:n,arguments:r}};if(!a)return[o];let s=G(a),c=s?.startedAt??Number(U(a)/1000000n),l=s?.endedAt??c,u=B(e,a,`gen_ai.tool.call.result`),d=R(a,`theorem.tool.outcome`)===`error`?{phase:`error`,failure:{code:R(a,`theorem.tool.failure.code`)??`failed`,kind:`internal`,message:u},readBack:u}:{phase:`complete`,output:be(e,a,u),readBack:u};return[o,{type:`tool`,tool:{name:t,callId:n,phase:`running`,at:c}},{type:`tool`,tool:{name:t,callId:n,at:l,...d}},..._e(e,a)]}function be(e,t,n){return`theorem.tool.data`in t.attributes?z(e,t,`theorem.tool.data`):xe(n)}function xe(e){try{return JSON.parse(e)}catch{return e}}var Se=(e,t)=>`${e}:${t}`;function Ce(e,t){if(!t.events.some(e=>e.name===`theorem.compaction`))return!1;let n=Y(e,t);return!n.text&&n.attachments===0}function we(e){let t=new Map,n=new Map,r=(e,t)=>{for(let r of e.spans)n.set(Se(r.traceId,r.spanId),t);t.script.records.push(e)};return e.forEach((e,i)=>{let a=y(e);if(!a||J(a)!==`invoke_agent`||Ce(e,a))return;let o=he(e),s=ge(e),c=a.parentSpanId?n.get(Se(a.traceId,a.parentSpanId)):void 0;if(c){c.turn.calls.push(...o),c.turn.results.push(...s),r(e,c);return}let l=R(a,`gen_ai.agent.name`)??``,u=R(a,`gen_ai.conversation.id`),d=`${l}\u0000${u??``}`,f=t.get(d);f||(f={agent:l,...u===void 0?{}:{conversation:u},turns:[],records:[],recordedAt:Number(U(a)/1000000n)},t.set(d,f));let p=Y(e,a),m={...p,calls:o,results:s,blocks:de(C({text:p.text},ve(e,a),{idPrefix:`recorded-${String(i)}`}),a)};f.turns.push(m),r(e,{turn:m,script:f})}),[...t.values()]}function Te(e){if(e.failed)throw Error(e.result);let t=xe(e.result);return I(t)?t:{result:t}}var Ee=e=>{let t=e%100,n=t>=11&&t<=13?`th`:{1:`st`,2:`nd`,3:`rd`}[e%10]??`th`;return`${String(e)}${n}`};function De(e,t,n){if(!e)return`The profile asked the model a ${Ee(t+1)} time this turn; the recording answered ${String(t)}.`;if(e.missing)return`The recording does not hold all of this reply.`;let r=new Set((n.wireTools??[]).map(e=>e.name)),i=e.calls.find(e=>!r.has(e));return i&&`The recording calls ${i}, which the profile no longer offers.`}function Oe(e,t,n){let r=0,i=new Map,a=new Map,o=t=>{let n=a.get(t);if(!n){n=new Map;for(let r of e.turns[t]?.results??[])n.set(r.name,[...n.get(r.name)??[],r]);a.set(t,n)}return n},s=t=>({async*complete(a){let o=e.turns[r]?.calls.filter(e=>e.agent===t)??[],s=`${String(r)} ${t}`,c=i.get(s)??0;i.set(s,c+1);let l=De(o[c],o.length,a);if(l)throw n({turn:r,agent:t,call:c+1,reason:l}),new b(`request`,`Replay stopped: ${l}`);yield*o[c]?.events??[]}}),c=e=>()=>{let t=o(r).get(e)?.shift();if(!t){let t=`The recording has no further result for ${e}.`;throw n({turn:r,tool:e,reason:t}),new b(`request`,`Replay stopped: ${t}`)}return Te(t)},l=new Set(e.turns.flatMap(e=>e.results.map(e=>e.name)));return{provider:n=>s(n.id===t?e.agent:n.id),toolHandlers:Object.fromEntries([...l].map(e=>[e,c(e)])),startTurn:e=>{r=e}}}function ke(e){return e.map(e=>{if(e.type===`agent`)return e;let{name:t,description:n,category:r,access:i,permission:a,loadTier:o,paths:s}=e;return{type:`function`,name:t,description:n,category:r,access:i,permission:a,loadTier:o,paths:s,inputSchema:e.inputSchema,outputSchema:e.outputSchema,...e.labels?{labels:e.labels}:{},...e.background?{background:e.background}:{}}})}function Ae(e){return{...e,customTools:ke(e.customTools),...e.dependencies?{dependencies:e.dependencies.map(e=>({...e,customTools:ke(e.customTools)}))}:{}}}function je(e){return e.turns.flatMap(e=>e.blocks)}function Me(e,t){let n=S.safeParse(e);if(n.success)return n.data;let r=I(e)?e.v:void 0,i=typeof r==`number`&&r!==3?`This trace is version ${String(r)}${t}; the studio reads version 3.`:`This file is not a Theorem trace${t}.`;throw new b(`request`,i)}function Ne(e){let t=Array.isArray(e)?e:[e];return t.map((e,n)=>Me(e,t.length>1?` (record ${String(n+1)})`:``))}function Pe(e){try{return Ne(JSON.parse(e))}catch(e){if(e instanceof b)throw e}let t=e.split(`
|
|
3
3
|
`).map((e,t)=>({line:e,at:t+1})).filter(({line:e})=>e.trim());if(t.length<2)throw new b(`request`,`This file is not JSON.`);return t.map(({line:e,at:t})=>{let n;try{n=JSON.parse(e)}catch{throw new b(`request`,`Line ${String(t)} of this file is not JSON.`)}return Me(n,` (line ${String(t)})`)})}var X=e(t(),1),Z=n();function Fe(e,t,n){return t?d(e,t,{conversationKey:F(),blocks:n}):l(e,n)}var Q=e=>`turn ${String(e+1)}`;function $({iface:e,feed:t,trace:n,card:r,conversation:i}){let a=re(e,t,n);return(0,Z.jsxs)(N,{inspector:a,maxWidth:`960px`,requestLabel:`Trace`,children:[r,i]})}function Ie({iface:e,blocks:t,banner:n,chat:r}){let i=w();return(0,Z.jsxs)(A,{label:`Conversation`,children:[n,(0,Z.jsx)(ne,{blocks:t,handle:i(`@theorem.agent.handle`,{handle:e.identity.handle}),labels:e.labels,streaming:r?.streaming,delivery:r?.delivery,answering:r?.answering,onToolDecision:r&&((e,t)=>{r.handleToolDecision(e,t)}),onAuthenticated:r&&((e,t)=>{r.handleAuthenticated(e,t)})})]})}function Le({onImport:e}){let[t,n]=(0,X.useState)(),[r,i]=(0,X.useState)(!1);return(0,Z.jsxs)(O,{gap:2,children:[(0,Z.jsx)(ae,{label:`Trace file`,isLabelHidden:!0,mode:`dropzone`,accept:`application/json,.json,.jsonl`,isLoading:r,placeholder:`Drop a trace (.json or .jsonl) or choose a file`,value:null,changeAction:async t=>{let r=Array.isArray(t)?t[0]:t;if(r){i(!0);try{let t=Pe(await r.text());e({name:r.name,records:t}),n(void 0)}catch(e){n(e instanceof Error?e.message:String(e))}finally{i(!1)}}},onChange:()=>void 0}),t?(0,Z.jsx)(P,{status:`error`,title:t}):null]})}var Re=e=>e.recordedAt===void 0?void 0:new Intl.DateTimeFormat(void 0,{dateStyle:`medium`,timeStyle:`short`}).format(e.recordedAt);function ze({shown:e,onShown:t}){return(0,Z.jsx)(te,{label:`Replayed`,tooltip:e===`replayed`?`Recorded`:`Replayed`,size:`sm`,isIconOnly:!0,icon:(0,Z.jsx)(r,{icon:v,size:`sm`}),pressedIcon:(0,Z.jsx)(r,{icon:oe,size:`sm`}),isPressed:e===`replayed`,onPressedChange:e=>{t(e?`replayed`:`recorded`)}})}function Be({controls:e}){let{script:t,payload:n}=e,o=t.turns.length,s=[t.agent||`No agent`,`${String(o)} ${o===1?`turn`:`turns`}`,Re(t)];return(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(E,{gap:2,vAlign:`center`,children:[(0,Z.jsx)(k,{size:`fill`,children:(0,Z.jsxs)(O,{gap:0,children:[(0,Z.jsx)(a,{type:`label`,maxLines:1,children:e.opened.name}),(0,Z.jsx)(a,{type:`supporting`,color:`secondary`,maxLines:1,children:s.filter(Boolean).join(` · `)})]})}),(0,Z.jsx)(D,{label:`Clear trace`,variant:`ghost`,size:`sm`,icon:(0,Z.jsx)(r,{icon:i,size:`sm`}),isDisabled:e.isRunning,onClick:e.onClear})]}),e.count>1?(0,Z.jsxs)(E,{gap:1,vAlign:`center`,children:[(0,Z.jsx)(D,{label:`Previous conversation`,variant:`ghost`,size:`sm`,icon:(0,Z.jsx)(r,{icon:m,size:`sm`}),isDisabled:e.isRunning||e.picked===0,onClick:()=>{e.onPick(e.picked-1)}}),(0,Z.jsxs)(a,{type:`supporting`,children:[`Conversation `,String(e.picked+1),` of `,String(e.count)]}),(0,Z.jsx)(D,{label:`Next conversation`,variant:`ghost`,size:`sm`,icon:(0,Z.jsx)(r,{icon:h,size:`sm`}),isDisabled:e.isRunning||e.picked===e.count-1,onClick:()=>{e.onPick(e.picked+1)}})]}):null,t.agent&&t.agent!==n.profile.id?(0,Z.jsx)(P,{status:`info`,title:`Recorded with ${t.agent}; a replay runs through ${n.profile.id}.`}):null,o===0?(0,Z.jsx)(P,{status:`info`,title:`This trace holds no conversation to replay.`}):null,(0,Z.jsx)(ie,{label:`Live tools`,description:`Run the profile's tools instead of answering them from the recording.`,value:e.liveTools,onChange:e.onLiveTools})]})}var Ve=()=>void 0;function He({onImport:e,controls:t}){let n=t?.onReplay??Ve;return(0,Z.jsxs)(j,{title:`Trace`,onRun:n,actions:t?.shown?(0,Z.jsx)(ze,{shown:t.shown,onShown:t.onShown}):null,children:[(0,Z.jsx)(Le,{onImport:e}),t?(0,Z.jsx)(Be,{controls:t}):null,(0,Z.jsx)(M,{note:t?`Answers each model call from the recording, so it needs no keys.`:null,isReady:(t?.script.turns.length??0)>0,isRunning:t?.isRunning??!1,runLabel:t?.shown?`Replay again`:`Replay`,runningLabel:`Replaying`,stopLabel:`Stop`,onRun:n,onStop:t?.onStop??Ve})]})}function Ue({status:e,turns:t,onContinue:n,onLive:r}){let[i,a]=(0,X.useState)(!1),[s,c]=(0,X.useState)(),l=e=>(0,Z.jsx)(o,{label:`Continue live`,variant:`secondary`,size:`sm`,isLoading:i,onClick:async()=>{a(!0),c(void 0);try{await r(e)}catch(e){c(e instanceof Error?e.message:String(e)),a(!1)}}}),u=(()=>{switch(e.kind){case`running`:return(0,Z.jsx)(P,{status:`info`,title:`Replaying ${Q(e.turn)} of ${String(t)}`});case`waiting`:return(0,Z.jsx)(P,{status:`info`,title:`${Q(e.turn-1)} waits on you`,description:`Answer it in the conversation, then continue the replay.`,endContent:(0,Z.jsx)(o,{label:`Continue replay`,variant:`secondary`,size:`sm`,onClick:()=>{n(e.turn)}})});case`missing`:return(0,Z.jsx)(P,{status:`warning`,title:`Replay stopped before ${Q(e.turn)}`,description:`It was sent with files, and a trace never holds a file's bytes. Continue live to send it again with yours.`,endContent:l(e.turn)});case`diverged`:{let t=e.divergence,n=`tool`in t?`the ${t.tool} tool`:`${t.agent}'s model call ${String(t.call)}`;return(0,Z.jsx)(P,{status:`warning`,title:`Replay stopped at ${Q(t.turn)}, ${n}`,description:t.reason,endContent:l(t.turn)})}case`stopped`:return(0,Z.jsx)(P,{status:`info`,title:`Replay stopped at ${Q(e.turn)}`,description:`You stopped it. Continue live to go on from here with the profile's model.`,endContent:l(e.turn)});case`failed`:return(0,Z.jsx)(P,{status:`error`,title:`Replay stopped at ${Q(e.turn)}`,description:e.message,endContent:l(e.turn)});case`done`:return(0,Z.jsx)(P,{status:`success`,title:`Replayed ${String(t)} ${t===1?`turn`:`turns`}`,description:`Every model call this profile made was one the recording answered.`})}})();return(0,Z.jsxs)(O,{gap:1,children:[u,s?(0,Z.jsx)(P,{status:`error`,title:s}):null]})}function We({payload:e,iface:t,trace:n,card:r,records:i,script:a,shown:o,liveTools:l,runtime:d,onLive:f}){let p=le(),{actingAs:m}=se(),h=(0,X.useRef)(void 0),[_,v]=(0,X.useState)({kind:`running`,turn:0}),[y]=(0,X.useState)(u),b=(0,X.useMemo)(()=>s(i),[i]),x=(0,X.useMemo)(()=>Oe(a,e.profile.id,e=>{h.current??=e}),[a,e.profile.id]),S=(0,X.useMemo)(()=>c(l?e:Ae(e),{mode:`byok`,provider:x.provider,...l?{}:{toolHandlers:x.toolHandlers}},{conversationKey:F(),traces:y}),[e,x,l,y]),C=(0,X.useMemo)(()=>l?g(e):void 0,[l,e]),w=ce({transport:S,iface:t,pageTools:C}),{sendText:T,handleStop:E}=w,D=(0,X.useRef)(w.phase);D.current=w.phase;let[O,k]=(0,X.useState)(0),A=(0,X.useRef)(!1),j=(0,X.useRef)(E);j.current=E,(0,X.useEffect)(()=>()=>j.current(),[]),(0,X.useEffect)(()=>{let e=!1,t=async()=>{for(;!e&&D.current===`streaming`;)await new Promise(e=>requestAnimationFrame(e))};return(async()=>{for(let n=O;n<a.turns.length;n+=1){if(await t(),e||A.current)return;if(D.current===`gated`)return x.startTurn(n-1),v({kind:`waiting`,turn:n});let{text:r,attachments:i}=a.turns[n];if(i>0)return v({kind:`missing`,turn:n});x.startTurn(n),v({kind:`running`,turn:n});try{let t=await T(r);if(e||A.current)return;if(h.current)return v({kind:`diverged`,divergence:h.current});t||--n}catch(e){let t=e instanceof Error?e.message:String(e);return v({kind:`failed`,turn:n,message:t})}}v({kind:`done`})})(),()=>{e=!0}},[O,x,a,T]);let M=async t=>{let n=a.turns.slice(0,t).flatMap(e=>e.blocks);f({...p?await ee(p,e.agentId,n,m):await Fe(e,d,n),text:a.turns[t]?.text??``})},N=o===`replayed`;return(0,Z.jsx)($,{iface:t,feed:N?y:b,trace:n,card:r({isRunning:_.kind===`running`,onStop:()=>{A.current=!0,E(),v(e=>e.kind===`running`?{kind:`stopped`,turn:e.turn}:e)}}),conversation:(0,Z.jsx)(Ie,{iface:t,blocks:N?[...w.blocks,...w.streamBlocks]:je(a),chat:N?w:void 0,banner:N?(0,Z.jsx)(Ue,{status:_,turns:a.turns.length,onContinue:k,onLive:M}):void 0})})}function Ge(e){return(0,Z.jsx)(p,{children:(0,Z.jsx)(T,{labels:_,children:(0,Z.jsx)(Je,{...e})})})}var Ke={agent:``,turns:[],records:[]};function qe(e,t,n){if(t.length<=1||!n)return e;let r=new Set(t.flatMap(e=>e.records)),i=new Set(n.records);return e.filter(e=>i.has(e)||!r.has(e))}function Je({payload:e,trace:t,runtime:n,onLive:r,opened:i,onOpened:a,onClear:o}){let c=(0,X.useMemo)(()=>f(e),[e]),l=(0,X.useMemo)(()=>i?we(i.records):[],[i]),[u,d]=(0,X.useState)(),p=u&&u.of===i?u.index:0,m=i?l[p]??Ke:void 0,h=(0,X.useMemo)(()=>qe(i?.records??[],l,m),[i,l,m]),g=(0,X.useMemo)(()=>s(h),[h]),[_,v]=(0,X.useState)(),[y,b]=(0,X.useState)(!1),x=_&&_.of===m&&_.agent===e.profile.id?_:void 0,S=x?.attempt??0,C=x?.shown??`recorded`,w=e=>{x&&v({...x,shown:e})},T=()=>{m&&v({of:m,agent:e.profile.id,attempt:S+1,shown:`replayed`})};if(c.type===`live`)return null;if(!i||!m)return(0,Z.jsx)($,{iface:c,feed:g,trace:t,card:(0,Z.jsx)(He,{onImport:a}),conversation:null});let E=({isRunning:t,onStop:n})=>(0,Z.jsx)(He,{onImport:a,controls:{opened:i,script:m,picked:p,count:l.length,onPick:e=>{d({of:i,index:e})},payload:e,shown:S>0?C:null,onShown:w,liveTools:y,onLiveTools:e=>{b(e),S>0&&T()},isRunning:t,onReplay:T,onStop:n,onClear:o}});return S===0?(0,Z.jsx)($,{iface:c,feed:g,trace:t,card:E({isRunning:!1,onStop:()=>void 0}),conversation:(0,Z.jsx)(Ie,{iface:c,blocks:je(m)})}):(0,Z.jsx)(We,{payload:e,iface:c,trace:t,card:E,records:h,script:m,shown:C,liveTools:y,runtime:n,onLive:r},S)}export{Ge as TraceReplay};
|
|
@@ -20,4 +20,4 @@ interface URL {
|
|
|
20
20
|
href: string;
|
|
21
21
|
}
|
|
22
22
|
declare function fetch(input: string | URL | Request, init?: RequestInit): Promise<Response>;
|
|
23
|
-
`;function n(n,c,l){let u=!1,d=()=>u,f=[],p=e=>(u?e.dispose():f.push(e),e);return m(),{stop(){if(!d()){u=!0;for(let e of f)e.dispose();f.length=0}}};async function m(){let[{default:f},{typeSources:m}]=await Promise.all([e(()=>import(`./studio-ts.worker-BXtW3z-O.js`),[]),e(()=>import(`./_virtual_studio-type-sources-
|
|
23
|
+
`;function n(n,c,l){let u=!1,d=()=>u,f=[],p=e=>(u?e.dispose():f.push(e),e);return m(),{stop(){if(!d()){u=!0;for(let e of f)e.dispose();f.length=0}}};async function m(){let[{default:f},{typeSources:m}]=await Promise.all([e(()=>import(`./studio-ts.worker-BXtW3z-O.js`),[]),e(()=>import(`./_virtual_studio-type-sources-CdnMqL-n.js`),[])]),h=c.getModel();if(u||!h)return;let g={"lib.host.d.ts":t,...m},_={};for(let[e,t]of Object.entries(g))_[e]={content:t,version:1};let v=p(n.editor.createWebWorker({worker:Promise.resolve(new f).then(e=>(e.postMessage(`ignore`),e.postMessage({compilerOptions:{allowNonTsExtensions:!0,target:7,lib:[`es2022`,`host`],module:99,moduleResolution:100,strict:!0,noEmit:!0,skipLibCheck:!0,allowImportingTsExtensions:!0,paths:{"@theoremjs/agents":[`file:///node_modules/@theoremjs/agents/mod.d.ts`],"@theoremjs/agents/guardrails/compile":[`file:///node_modules/@theoremjs/agents/src/guardrails/compile-egress.d.ts`],zod:[`file:///node_modules/zod/index.d.ts`]}},extraLibs:_,inlayHintsOptions:{}}),e)),keepIdleModels:!0}));if(d())return;let y=()=>v.withSyncedResources([h.uri]),{languages:b}=n;p(b.registerCompletionItemProvider(`typescript`,{triggerCharacters:[`.`],provideCompletionItems:(e,t)=>r(b,y,e,t),resolveCompletionItem:e=>i(b,y,e)})),p(b.registerHoverProvider(`typescript`,{provideHover:(e,t)=>a(y,e,t)})),p(b.registerSignatureHelpProvider(`typescript`,{signatureHelpTriggerCharacters:[`(`,`,`],provideSignatureHelp:(e,t)=>o(y,e,t)})),p(b.registerDefinitionProvider(`typescript`,{provideDefinition:(e,t)=>s(n,g,p,y,e,t)})),!d()&&(c.hasTextFocus()&&c.trigger(`studio`,`editor.action.triggerSuggest`,{}),l())}}async function r(e,t,n,r){try{let i=n.getWordUntilPosition(r),a=n.getOffsetAt(r),o=await(await t()).getCompletionsAtPosition(n.uri.toString(),a);return o?{suggestions:o.entries.map(t=>{let o=t.replacementSpan?l(n,t.replacementSpan):{startLineNumber:r.lineNumber,startColumn:i.startColumn,endLineNumber:r.lineNumber,endColumn:i.endColumn};return{uri:n.uri,position:r,offset:a,label:t.name,insertText:t.name,sortText:t.sortText,kind:p(e,t.kind),range:o,tags:t.kindModifiers?.includes(`deprecated`)===!0?[e.CompletionItemTag.Deprecated]:[]}})}:void 0}catch{return}}async function i(e,t,n){let r=n;if(!r.uri||!r.position||r.offset===void 0)return n;try{let i=await(await t()).getCompletionEntryDetails(r.uri.toString(),r.offset,n.label);return i?{...n,detail:u(i.displayParts),documentation:{value:d(i)},kind:p(e,i.kind)}:n}catch{return n}}async function a(e,t,n){try{let r=await(await e()).getQuickInfoAtPosition(t.uri.toString(),t.getOffsetAt(n));if(!r)return;let i=d(r);return{range:l(t,r.textSpan),contents:[{value:`\`\`\`typescript\n${u(r.displayParts)}\n\`\`\``},...i?[{value:i}]:[]]}}catch{return}}async function o(e,t,n){try{let r=await(await e()).getSignatureHelpItems(t.uri.toString(),t.getOffsetAt(n),{triggerReason:{kind:`invoked`}});return r?{value:{activeSignature:r.selectedItemIndex,activeParameter:r.argumentIndex,signatures:r.items.map(e=>{let t=u(e.prefixDisplayParts),n=e.parameters.map((n,r)=>{let i=u(n.displayParts);return t+=i,r<e.parameters.length-1&&(t+=u(e.separatorDisplayParts)),{label:i,documentation:{value:u(n.documentation)}}});return t+=u(e.suffixDisplayParts),{label:t,parameters:n,documentation:{value:u(e.documentation)}}})},dispose(){}}:void 0}catch{return}}async function s(e,t,n,r,i,a){try{let o=await(await r()).getDefinitionAtPosition(i.uri.toString(),i.getOffsetAt(a));if(!o)return;let s=[];for(let r of o){let i=c(e,t,n,r.fileName);i&&s.push({uri:i.uri,range:l(i,r.textSpan)})}return s}catch{return}}function c(e,t,n,r){let i;try{i=e.Uri.parse(r)}catch{return}let a=e.editor.getModel(i);if(a)return a;if(r in t)return n(e.editor.createModel(t[r],`typescript`,i))}function l(e,t){let n=e.getPositionAt(t.start),r=e.getPositionAt(t.start+t.length);return{startLineNumber:n.lineNumber,startColumn:n.column,endLineNumber:r.lineNumber,endColumn:r.column}}function u(e){return e?.map(e=>e.text).join(``)??``}function d(e){let t=u(e.documentation);for(let n of e.tags??[]){let e=typeof n.text==`string`?n.text:u(n.text);t+=`\n\n*@${n.name}*${e?` — ${e}`:``}`}return t}var f=new Map([[`keyword`,`Keyword`],[`primitive type`,`Keyword`],[`var`,`Variable`],[`local var`,`Variable`],[`const`,`Variable`],[`let`,`Variable`],[`property`,`Field`],[`getter`,`Field`],[`setter`,`Field`],[`function`,`Function`],[`method`,`Function`],[`constructor`,`Function`],[`call`,`Function`],[`construct`,`Function`],[`index`,`Function`],[`enum`,`Enum`],[`module`,`Module`],[`class`,`Class`],[`interface`,`Interface`]]);function p(e,t){return e.CompletionItemKind[f.get(t)??`Property`]}export{n as openTypeChecker};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{n as e}from"./rolldown-runtime-hePW80VL.js";import{$ as t,A as n,B as r,F as i,G as a,H as o,I as s,J as c,K as l,L as ee,M as te,N as ne,P as re,Q as ie,R as ae,U as oe,V as se,W as ce,X as le,Y as ue,Z as de,a as u,at as fe,ct as pe,dt as me,et as he,ht as ge,i as d,it as _e,j as ve,lt as ye,mt as f,n as p,nt as be,ot as xe,q as Se,r as m,rt as Ce,st as we,tt as Te,ut as Ee,w as De,z as Oe}from"./schemas-D7cgkv3L.js";import{$t as ke,A as Ae,C as je,D as Me,Gt as Ne,Qt as Pe,S as Fe,T as Ie,a as Le,c as h,j as Re,k as ze,to as g,w as Be}from"./shaped-data-yrTrXPh4.js";var Ve=e({endsWith:()=>ve,gt:()=>te,gte:()=>ne,includes:()=>re,length:()=>Oe,lowercase:()=>r,lt:()=>se,lte:()=>o,maxLength:()=>oe,maxSize:()=>ce,mime:()=>a,minLength:()=>l,minSize:()=>Se,multipleOf:()=>c,negative:()=>ue,nonnegative:()=>le,nonpositive:()=>de,normalize:()=>ie,overwrite:()=>t,positive:()=>he,properties:()=>Te,property:()=>be,regex:()=>Ce,size:()=>_e,slugify:()=>fe,startsWith:()=>xe,toLowerCase:()=>we,toUpperCase:()=>pe,trim:()=>ye,uppercase:()=>Ee}),He=e({ZodISODate:()=>p,ZodISODateTime:()=>m,ZodISODuration:()=>d,ZodISOTime:()=>u,date:()=>We,datetime:()=>Ue,duration:()=>Ke,time:()=>Ge});function Ue(e){return s(m,e)}function We(e){return i(p,e)}function Ge(e){return ae(u,e)}function Ke(e){return ee(d,e)}var _={...De,...Ve,iso:He},qe=new Set(`$schema.$ref.$defs.definitions.$id.id.$comment.$anchor.$vocabulary.$dynamicRef.$dynamicAnchor.type.enum.const.anyOf.oneOf.allOf.not.properties.required.additionalProperties.patternProperties.propertyNames.minProperties.maxProperties.items.prefixItems.additionalItems.minItems.maxItems.uniqueItems.contains.minContains.maxContains.minLength.maxLength.pattern.format.minimum.maximum.exclusiveMinimum.exclusiveMaximum.multipleOf.description.default.contentEncoding.contentMediaType.contentSchema.unevaluatedItems.unevaluatedProperties.if.then.else.dependentSchemas.dependentRequired.nullable.readOnly`.split(`.`));function Je(e,t){let n=e.$schema;return n===`https://json-schema.org/draft/2020-12/schema`?`draft-2020-12`:n===`http://json-schema.org/draft-07/schema#`?`draft-7`:n===`http://json-schema.org/draft-04/schema#`?`draft-4`:t??`draft-2020-12`}function v(e,t){return e.map((e,n)=>n<t?e:e.optional())}function Ye(e){return e.replace(/~1/g,`/`).replace(/~0/g,`~`)}function Xe(e,t){if(!e.startsWith(`#`))throw Error(`External $ref is not supported, only local refs (#/...) are allowed`);let n=e.slice(1).split(`/`).filter(Boolean);if(n.length===0)return t.rootSchema;let r=t.version===`draft-2020-12`?`$defs`:`definitions`;if(n[0]===r){let r=n[1]===void 0?void 0:Ye(n[1]);if(!r||!t.defs[r])throw Error(`Reference not found: ${e}`);return t.defs[r]}throw Error(`Reference not found: ${e}`)}function Ze(e,t){return _.transform(e=>e).check(n=>{let r=n.value;if(typeof r!=`object`||!r||Array.isArray(r))return;let i=Object.getOwnPropertyNames(r);if(t.minProperties!==void 0&&i.length<t.minProperties&&n.issues.push({origin:`object`,code:`too_small`,minimum:t.minProperties,inclusive:!0,message:`Too small: expected object to have >=${t.minProperties} properties`,input:r,inst:e,continue:!0}),t.maxProperties!==void 0&&i.length>t.maxProperties&&n.issues.push({origin:`object`,code:`too_big`,maximum:t.maxProperties,inclusive:!0,message:`Too big: expected object to have <=${t.maxProperties} properties`,input:r,inst:e,continue:!0}),t.keySchema)for(let e of i){let r=t.keySchema.safeParse(e);r.success||n.issues.push({code:`invalid_key`,origin:`record`,issues:r.error.issues,input:e,path:[e],continue:!0})}}).pipe(e)}function y(e,t){if(e===null)return`z`;let n=typeof e;if(n!==`object`){if(n===`number`&&Number.isNaN(e))return null;let t=String(e);return`${n[0]}${t.length}:${t}`}if(t.has(e))return null;t.add(e);try{if(Array.isArray(e)){let n=[];for(let r of e){let e=y(r,t);if(e===null)return null;n.push(e)}return`a${n.length}:[${n.join(`,`)}]`}let n=Object.keys(e).sort(),r=[];for(let i of n){let n=y(e[i],t);if(n===null)return null;r.push(`${i.length}:${i}=${n}`)}return`o${r.length}:{${r.join(`,`)}}`}finally{t.delete(e)}}var Qe=new Set([`items`,`prefixItems`,`additionalItems`,`additionalProperties`,`contains`,`propertyNames`,`not`,`if`,`then`,`else`,`allOf`,`anyOf`,`oneOf`,`unevaluatedItems`,`unevaluatedProperties`,`contentSchema`]),$e=new Set([`properties`,`patternProperties`,`dependentSchemas`,`dependencies`,`$defs`,`definitions`]);function b(e){return typeof e!=`object`||!e?!1:Array.isArray(e)?e.some(b):typeof e.$ref==`string`||Object.entries(e).some(([e,t])=>Qe.has(e)?b(t):!$e.has(e)||typeof t!=`object`||!t?!1:Object.values(t).some(b))}function x(e){return e===1?`element`:`elements`}function et(e,t){return _.transform(e=>e).check(e=>{let n=e.value;if(Array.isArray(n)){if(t.uniqueItems===!0){let t=new Map;for(let r=0;r<n.length;r++){let i=y(n[r],new Set);if(i===null)continue;let a=t.get(i);a===void 0?t.set(i,r):e.issues.push({code:`custom`,message:`Array items must be unique: element at index ${r} duplicates the one at index ${a}`,input:n,path:[r],continue:!0})}}if(t.containsSchema){let r=t.minContains??1,i=t.maxContains===void 0?1/0:t.maxContains+1,a=0;for(let e of n)if(t.containsSchema.safeParse(e).success&&++a>=i)break;a<r&&e.issues.push({code:`custom`,message:`Array must contain at least ${r} matching ${x(r)}; found ${a}`,input:n,continue:!0}),t.maxContains!==void 0&&a>t.maxContains&&e.issues.push({code:`custom`,message:`Array must contain at most ${t.maxContains} matching ${x(t.maxContains)}`,input:n,continue:!0})}}}).pipe(e)}function S(e,t){if(e!==!1)return e===void 0||e===!0?_.any():w(e,t)}var tt=/^(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/;function C(e,t){if(e.not!==void 0){if(typeof e.not==`object`&&Object.keys(e.not).length===0)return _.never();throw Error(`not is not supported in Zod (except { not: {} } for never)`)}if(e.unevaluatedItems!==void 0)throw Error(`unevaluatedItems is not supported`);if(e.unevaluatedProperties!==void 0)throw Error(`unevaluatedProperties is not supported`);if(e.if!==void 0||e.then!==void 0||e.else!==void 0)throw Error(`Conditional schemas (if/then/else) are not supported`);if(e.dependentSchemas!==void 0||e.dependentRequired!==void 0)throw Error(`dependentSchemas and dependentRequired are not supported`);if(e.$ref){let n=e.$ref;if(t.refs.has(n))return t.refs.get(n);if(t.processing.has(n))return _.lazy(()=>{if(!t.refs.has(n))throw Error(`Circular reference not resolved: ${n}`);return t.refs.get(n)});t.processing.add(n);let r=w(Xe(n,t),t);return t.refs.set(n,r),t.processing.delete(n),r}if(e.enum!==void 0){let n=e.enum;if(t.version===`openapi-3.0`&&e.nullable===!0&&n.length===1&&n[0]===null)return _.null();if(n.length===0)return _.never();if(n.length===1)return _.literal(n[0]);if(n.every(e=>typeof e==`string`))return _.enum(n);let r=n.map(e=>_.literal(e));return r.length<2?r[0]:_.union([r[0],r[1],...r.slice(2)])}if(e.const!==void 0)return _.literal(e.const);let n=e.type;if(Array.isArray(n)){let r=n.map(n=>C({...e,type:n},t));return r.length===0?_.never():r.length===1?r[0]:_.union(r)}if(!n)return _.any();let r;switch(n){case`string`:{let t=_.string();if(e.format){let n=e.format;n===`email`?t=t.check(_.email()):n===`uri`||n===`uri-reference`?t=t.check(_.url()):n===`uuid`||n===`guid`?t=t.check(_.uuid()):n===`date-time`?t=t.check(_.iso.datetime({offset:!0})):n===`date`?t=t.check(_.iso.date()):n===`time`?t=t.check(_.regex(tt)):n===`duration`?t=t.check(_.iso.duration()):n===`hostname`?t=t.check(_.hostname()):n===`ipv4`?t=t.check(_.ipv4()):n===`ipv6`?t=t.check(_.ipv6()):n===`mac`?t=t.check(_.mac()):n===`cidr`?t=t.check(_.cidrv4()):n===`cidr-v6`?t=t.check(_.cidrv6()):n===`base64`?t=t.check(_.base64()):n===`base64url`?t=t.check(_.base64url()):n===`e164`?t=t.check(_.e164()):n===`credit_card`?t=t.check(_.creditCard()):n===`iban`?t=t.check(_.iban()):n===`jwt`?t=t.check(_.jwt()):n===`emoji`?t=t.check(_.emoji()):n===`nanoid`?t=t.check(_.nanoid()):n===`cuid`?t=t.check(_.cuid()):n===`cuid2`?t=t.check(_.cuid2()):n===`ulid`?t=t.check(_.ulid()):n===`xid`?t=t.check(_.xid()):n===`ksuid`&&(t=t.check(_.ksuid()))}typeof e.minLength==`number`&&(t=t.min(e.minLength)),typeof e.maxLength==`number`&&(t=t.max(e.maxLength)),e.pattern&&(t=t.regex(new RegExp(e.pattern))),r=t;break}case`number`:case`integer`:{let t=n===`integer`?_.number().int():_.number();typeof e.minimum==`number`&&e.exclusiveMinimum!==!0&&(t=t.min(e.minimum)),typeof e.maximum==`number`&&e.exclusiveMaximum!==!0&&(t=t.max(e.maximum)),typeof e.exclusiveMinimum==`number`?t=t.gt(e.exclusiveMinimum):e.exclusiveMinimum===!0&&typeof e.minimum==`number`&&(t=t.gt(e.minimum)),typeof e.exclusiveMaximum==`number`?t=t.lt(e.exclusiveMaximum):e.exclusiveMaximum===!0&&typeof e.maximum==`number`&&(t=t.lt(e.maximum)),typeof e.multipleOf==`number`&&(t=t.multipleOf(e.multipleOf)),r=t;break}case`boolean`:r=_.boolean();break;case`null`:r=_.null();break;case`object`:{let n={},i=e.properties||{},a=new Set(e.required||[]),o=typeof e.additionalProperties==`object`?w(e.additionalProperties,t):void 0;for(let[e,r]of Object.entries(i)){let i=w(r,t);f(n,e,a.has(e)?i:i.optional())}if(e.patternProperties){let i=e.patternProperties,a=Object.keys(i),o=[];for(let e of a){let n=w(i[e],t),r=_.string().regex(new RegExp(e));o.push(_.looseRecord(r,n))}let s=[];if(Object.keys(n).length>0&&s.push(_.object(n).passthrough()),s.push(...o),s.length===0)r=_.object({}).passthrough();else if(s.length===1)r=s[0];else{let e=_.intersection(s[0],s[1]);for(let t=2;t<s.length;t++)e=_.intersection(e,s[t]);r=e}if(e.additionalProperties===!1){let e=Object.keys(n),t=a.map(e=>new RegExp(e)),i=r;r=r.check(n=>{if(!ge(n.value))return;let r=[];for(let i of Object.keys(n.value))e.includes(i)||t.some(e=>e.test(i))||r.push(i);r.length&&n.issues.push({code:`unrecognized_keys`,keys:r,input:n.value,inst:i})})}}else{let t=_.object(n);r=e.additionalProperties===!1?t.strict():o?t.catchall(o):t.passthrough()}let s=e.propertyNames!==void 0&&e.propertyNames!==!0,c=typeof e.minProperties==`number`?e.minProperties:void 0,l=typeof e.maxProperties==`number`?e.maxProperties:void 0;if(s||c!==void 0||l!==void 0){let n;s&&(n=w(typeof e.propertyNames==`object`&&e.propertyNames.type===void 0?{type:`string`,...e.propertyNames}:e.propertyNames,t)),r=Ze(r,{keySchema:n,minProperties:c,maxProperties:l})}break}case`array`:{let n=e.prefixItems,i=e.items;if(n&&Array.isArray(n)){let a=typeof e.minItems==`number`?e.minItems:0,o=v(n.map(e=>w(e,t)),a),s=Array.isArray(i)?void 0:S(i,t),c=_.tuple(o);r=s?c.rest(s):c,typeof e.minItems==`number`&&(r=r.check(_.minLength(e.minItems))),typeof e.maxItems==`number`&&(r=r.check(_.maxLength(e.maxItems)))}else if(Array.isArray(i)){let n=typeof e.minItems==`number`?e.minItems:0,a=v(i.map(e=>w(e,t)),n),o=S(e.additionalItems,t),s=_.tuple(a);r=o?s.rest(o):s,typeof e.minItems==`number`&&(r=r.check(_.minLength(e.minItems))),typeof e.maxItems==`number`&&(r=r.check(_.maxLength(e.maxItems)))}else if(i!==void 0){let n=w(i,t),a=_.array(n);typeof e.minItems==`number`&&(a=a.min(e.minItems)),typeof e.maxItems==`number`&&(a=a.max(e.maxItems)),r=a}else r=_.array(_.any());(e.uniqueItems===!0||e.contains!==void 0)&&(r=et(r,{uniqueItems:e.uniqueItems===!0,containsSchema:e.contains===void 0?void 0:w(e.contains,t),minContains:typeof e.minContains==`number`?e.minContains:void 0,maxContains:typeof e.maxContains==`number`?e.maxContains:void 0}));break}default:throw Error(`Unsupported type: ${n}`)}return r}function w(e,t){if(typeof e==`boolean`)return e?_.any():_.never();let n=C(e,t),r=e.type||e.enum!==void 0||e.const!==void 0;if(e.anyOf&&Array.isArray(e.anyOf)){let i=e.anyOf.map(e=>w(e,t)),a=_.union(i);n=r?_.intersection(n,a):a}if(e.oneOf&&Array.isArray(e.oneOf)){let i=e.oneOf.map(e=>w(e,t)),a=_.xor(i);n=r?_.intersection(n,a):a}if(e.allOf&&Array.isArray(e.allOf)){if(e.allOf.length===0)n=r?n:_.any();else{let i=r?n:w(e.allOf[0],t),a=+!r;for(let n=a;n<e.allOf.length;n++)i=_.intersection(i,w(e.allOf[n],t));n=i}}e.nullable===!0&&t.version===`openapi-3.0`&&(n=_.nullable(n)),e.readOnly===!0&&(n=_.readonly(n)),e.default!==void 0&&(n=n.default(e.default));let i={};for(let t of[`$id`,`id`,`$comment`,`$anchor`,`$vocabulary`,`$dynamicRef`,`$dynamicAnchor`])t in e&&(i[t]=e[t]);for(let t of[`contentEncoding`,`contentMediaType`,`contentSchema`])t in e&&(i[t]=e[t]);if(e.type===`object`&&e.$ref===void 0){e.propertyNames!==void 0&&!b(e.propertyNames)&&(i.propertyNames=e.propertyNames);for(let t of[`minProperties`,`maxProperties`])e[t]!==void 0&&(i[t]=e[t])}if(e.type===`array`&&e.$ref===void 0){e.contains!==void 0&&!b(e.contains)&&(i.contains=e.contains);for(let t of[`uniqueItems`,`minContains`,`maxContains`])e[t]!==void 0&&(i[t]=e[t])}for(let t of Object.keys(e))qe.has(t)||f(i,t,e[t]);return Object.keys(i).length>0&&t.registry.add(n,i),e.description&&(n=n.describe(e.description)),n}function nt(e,t){if(typeof e==`boolean`)return e?_.any():_.never();let n;try{n=JSON.parse(JSON.stringify(e))}catch{throw Error(`fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas`)}let r={version:Je(n,t?.defaultTarget),defs:n.$defs||n.definitions||{},refs:new Map,processing:new Set,rootSchema:n,registry:t?.registry??me};return w(n,r)}var rt=`https://generativelanguage.googleapis.com/v1beta/models`,it=`Zephyr.Puck.Charon.Kore.Fenrir.Leda.Orus.Aoede.Callirrhoe.Autonoe.Enceladus.Iapetus.Umbriel.Algieba.Despina.Erinome.Algenib.Rasalgethi.Laomedeia.Achernar.Alnilam.Schedar.Gacrux.Pulcherrima.Achird.Zubenelgenubi.Vindemiatrix.Sadachbia.Sadaltager.Sulafat`.split(`.`),at=[`minimal`,`low`,`medium`,`high`],ot=[`pcm`],st=[`1:1`,`3:2`,`2:3`,`3:4`,`4:3`,`4:5`,`5:4`,`9:16`,`16:9`,`21:9`],ct=[`1K`,`2K`,`4K`],lt=[`image/png`,`image/jpeg`],T=[{type:`builtin`,name:`googleSearch`,description:`Google Search grounding`,category:`grounding`,access:`read-only`,paths:[`*`],loadTier:`T0`,permission:`auto`},{type:`builtin`,name:`googleMaps`,description:`Google Maps grounding`,category:`grounding`,access:`read-only`,paths:[`*`],loadTier:`T0`,permission:`auto`,conflictsWith:[`googleSearch`,`urlContext`]},{type:`builtin`,name:`urlContext`,description:`Fetch URL context`,category:`grounding`,access:`read-only`,paths:[`*`],loadTier:`T0`,permission:`auto`},{type:`builtin`,name:`codeExecution`,description:`Google code execution`,category:`grounding`,access:`read-only`,paths:[`*`],loadTier:`T0`,permission:`auto`}],ut=[{type:`builtin`,name:`webSearch`,description:`OpenRouter web search`,category:`grounding`,access:`read-only`,paths:[`*`],loadTier:`T0`,permission:`auto`}],E=`local`;function dt(e,t){return!t&&e===`local`}function D(e=`http://localhost:11434`){return`${e.replace(/\/$/,``)}/v1`}var O=[{id:`gemini`,definition:`gemini`},{id:`openrouter`,definition:`openrouter`},{id:E,definition:`local`,connection:{baseUrl:D()}},{id:`typesafe`,definition:`typesafe`}],k={gemini:{provider:ze,factory:`geminiProvider`},openrouter:{provider:je,factory:`openRouterProvider`},local:{provider:Me,factory:`localProvider`},typesafe:{provider:Fe,factory:`typesafeProvider`}};function A(e){return e===void 0?void 0:k[e]?.provider}function ft(){return Object.keys(k)}function pt(e){return Object.keys(k).find(t=>k[t]?.factory===e)}function mt(e){return k[e]?.factory}function j(e,t){return e.find(e=>e.id===t)?.definition}function ht(e){return{id:e.id,...e.connection===void 0?{}:{connection:e.connection},...e.keySlot===void 0?{}:{keySlot:e.keySlot},...e.fallbackKeySlot===void 0?{}:{fallbackKeySlot:e.fallbackKeySlot}}}function M(e,t,n=A(t.definition),r=`register`){if(!n)throw Error(`The studio does not hold the provider definition '${t.definition}'.`);return e[r](n,ht(t))}function gt(e){let t=A(e);if(!t)return;if(!t.connection)return[];let r=n(t.connection,{io:`input`});return Object.entries(r.properties??{}).map(([e,t])=>({name:e,required:r.required?.includes(e)??!1,url:t.format===`uri`,...t.description?{description:t.description}:{}}))}function _t(e){let t=A(e);return t===void 0||t.key!==void 0}function N(e){let t=[];e.id.trim()||t.push({field:`id`,message:`Provider id is required.`});let n=A(e.definition),r=e.connection??{},i=n?.connection?.safeParse(r);for(let e of i?.error?.issues??[]){if(e.code===`unrecognized_keys`){for(let n of e.keys)t.push({field:`connection.${n}`,message:`This provider takes no '${n}'.`});continue}let n=e.path[0];if(typeof n!=`string`){t.push({message:e.message});continue}let i=n in r?e.message:`${n} is required.`;t.push({field:`connection.${n}`,message:i})}for(let n of[`keySlot`,`fallbackKeySlot`]){let r=e[n];r!==void 0&&!Pe.safeParse(r).success&&t.push({field:n,message:`A key slot is 1 to 32 letters, digits, hyphens, or underscores.`})}return e.keySlot&&e.keySlot===e.fallbackKeySlot&&t.push({field:`fallbackKeySlot`,message:g(`provider.fallback_slot`)}),(e.keySlot||e.fallbackKeySlot)&&n&&!n.key&&t.push({field:`keySlot`,message:g(`protocol.no_key`,{provider:e.id})}),t}function vt(e,t){let n=e.find(e=>e.id===t.provider)??{};return ke(n,{...t.keySlot?{keySlot:t.keySlot}:{},...t.fallbackKeySlot?{fallbackKeySlot:t.fallbackKeySlot}:{}})}function P(e,t){let n=A(e.definition);if(!n)return;let r;try{r=M(Ne(),e,n)}catch{return[]}return r.serves.map(e=>e.protocol).filter(e=>t===void 0||e.endpoints[t]!==void 0)}function F(e,t,n){if(!e)return!1;let r=P(e,t);return r===void 0?!0:n===void 0?r.length>0:r.some(e=>e.id===n)}function yt(e,t,n){if(!bt(t))throw Error(`Cannot create a model route without a profile type.`);return{profileType:t,protocol:n.protocol,provider:n.provider,definition:j(e,n.provider),apiId:n.apiId,decision:t===`decision`}}function bt(e){return[`text`,`image`,`speech`,`transcription`,`live`,`decision`,`embedding`].includes(e)}function xt(e,t){let r=I(n(e.options,{io:`input`,unrepresentable:`any`}),``,!0),i=t?e.refusedOptions?.(t.apiId.trim())??[]:[];return r.filter(e=>{let n=e.path.split(`.`)[0]??e.path;return!i.includes(n)||t?.options[n]!==void 0})}function I(e,t,n){return Object.entries(e.properties??{}).flatMap(([r,i])=>{let a=t?`${t}.${r}`:r,o=n&&(e.required?.includes(r)??!1);if(i.type===`object`&&i.properties)return I(i,a,o);let s={path:a,label:St(r),required:o,...i.description?{description:i.description}:{}},c=i.anyOf?.filter(e=>typeof e.const==`string`||typeof e.const==`number`),l=c?.map(e=>e.const);if(i.enum?.every(e=>typeof e==`string`))return[{...s,kind:`choice`,choices:i.enum.map(e=>({value:e}))}];if(l&&l.length===i.anyOf?.length&&l.length>0){let e=l.every(e=>typeof e==`number`);if(e||l.every(e=>typeof e==`string`))return[{...s,kind:`choice`,choices:(c??[]).map(e=>({value:String(e.const),...e.title?{label:e.title}:{},...e.description?{description:e.description}:{}})),...e?{choiceType:`number`}:{}}]}return i.type===`boolean`?[{...s,kind:`boolean`}]:i.type===`array`&&i.items?.type===`string`?[{...s,kind:`names`}]:i.type===`string`?[{...s,kind:`text`}]:i.type===`number`||i.type===`integer`?[{...s,kind:`number`}]:[]})}function St(e){let t=e.replace(/([a-z0-9])([A-Z])/g,`$1 $2`).replace(/_/g,` `).toLowerCase();return t.charAt(0).toUpperCase()+t.slice(1)}function Ct(e,t){return t.split(`.`).reduce((e,t)=>e&&typeof e==`object`&&!Array.isArray(e)?e[t]:void 0,e)}function L(e,t,n){let[r=``,...i]=t.split(`.`),{[r]:a,...o}=e,s=i.length?L(a&&typeof a==`object`&&!Array.isArray(a)?a:{},i.join(`.`),n):n;return s===void 0||typeof s==`object`&&s&&!Array.isArray(s)&&!Object.keys(s).length?o:{...o,[r]:s}}var R=`studio`,wt={"observability.writeTo":R};function Tt(e){return Object.entries(wt).reduce((e,[t,n])=>z(e,t.split(`.`),n),e)}function z(e,[t,...n],r){if(t===void 0||!Object.hasOwn(e,t))return e;let i=e[t];if(!n.length)return i===r?Object.fromEntries(Object.entries(e).filter(([e])=>e!==t)):e;if(typeof i!=`object`||!i||Array.isArray(i))return e;let a=z(i,n,r);return a===i?e:Object.fromEntries(Object.entries(e).flatMap(([e,n])=>e===t?Object.keys(a).length?[[e,a]]:[]:[[e,n]]))}var Et=new Set(T.map(e=>e.name));function Dt(e){return e.protocol===Re.id||e.protocol===Ae.id}function Ot(e){return e.protocol===Be.id||e.protocol===Ie.id}function kt(e){return Et.has(e)}function At(e,t,n){return n.mode===`demo`?n.keys.runs(e,t?.definition):F(t,e)}var jt={text:`fast`,image:`image`,speech:`voice`,transcription:`transcription`,live:`live`,decision:`decision`,embedding:`embedding`};function Mt(e,t){let n=t?.(e)??{...B(e===`decision`?`typesafe`:`gemini`,e),apiId:``};return{modelId:jt[e],...n}}function B(e,t){let n=O.find(t=>t.id===e),r=n&&P(n,t)?.[0];if(!r)throw Error(`The studio provider '${e}' serves no ${t} agents.`);return{protocol:r.id,provider:e}}function Nt(e,t){return t.mode===`demo`?t.keys.violation(e):t.mode===`local`&&e.provider!==`local`?{field:`provider`,message:`Local runs require local models. Switch the model provider to Local.`}:null}var Pt=5,Ft=100,It=120;function V(e){let t=Array.isArray(e.type)?e.type.find(e=>e!==`null`):e.type;return t===`string`||t===`number`||t===`integer`||t===`boolean`||t===`array`?t:t===`object`||h(e.properties)?`object`:Array.isArray(e.enum)?`string`:`unknown`}function Lt(e){return h(e.items)?e.items:void 0}function H(e){let t=e?.enum;return Array.isArray(t)&&t.length>0&&t.every(e=>typeof e==`string`)?t:void 0}function U(e,t){let n=e[t];return typeof n==`number`&&Number.isFinite(n)?n:void 0}function W(e,t){let n=U(e,`minimum`),r=U(e,`maximum`);return t&&n!==void 0&&r!==void 0&&r>n&&r-n<=Ft?{kind:`range`,min:n,max:r}:{kind:`number`,isInteger:t,...n===void 0?{}:{min:n},...r===void 0?{}:{max:r}}}function Rt(e){if(e.format===`date`)return{kind:`date`};let t=U(e,`maxLength`);return{kind:`text`,isLong:t!==void 0&&t>It,type:e.format===`email`?`email`:`text`}}function zt(e){let t=Lt(e),n=H(t);if(n)return{kind:`choices`,options:n};let r=t?V(t):`unknown`;return r===`string`||r===`number`||r===`integer`?{kind:`words`}:t&&r===`object`?{kind:`rows`,item:t}:{kind:`json`}}function Bt(e){let t=H(e);if(t)return{kind:`choice`,options:t,isMenu:t.length>Pt};switch(V(e)){case`boolean`:return{kind:`switch`};case`number`:return W(e,!1);case`integer`:return W(e,!0);case`string`:return Rt(e);case`array`:return zt(e);case`object`:return h(e.properties)?{kind:`group`,schema:e}:{kind:`json`};default:return{kind:`json`}}}function G(e){return new Set(Array.isArray(e.required)?e.required.filter(e=>typeof e==`string`):[])}function K(e){let t=h(e.properties)?e.properties:{},n=G(e);return Object.entries(t).flatMap(([e,t])=>h(t)?[{key:e,label:typeof t.title==`string`&&t.title?t.title:Le(e),...typeof t.description==`string`&&t.description?{description:t.description}:{},isRequired:n.has(e),control:Bt(t)}]:[])}function Vt(e){if(Array.isArray(e.examples)&&e.examples.length)return{value:e.examples[0]};if(`default`in e)return{value:e.default};if(`const`in e)return{value:e.const};if(Array.isArray(e.enum)&&e.enum.length)return{value:e.enum[0]}}function Ht(e){let t=Vt(e);if(t)return t.value;switch(V(e)){case`number`:case`integer`:return U(e,`minimum`)??1;case`boolean`:return!0;case`array`:return[];case`object`:return q(e);case`string`:case`unknown`:return`example`}}function q(e){let t=h(e.properties)?e.properties:{},n=new Set(G(e)),r={};for(let[e,i]of Object.entries(t))h(i)&&(n.has(e)?r[e]=Ht(i):Array.isArray(i.examples)&&i.examples.length&&(r[e]=i.examples[0]));return r}function Ut(e){return q(e)}function Wt(e,t,n){let r={...e};return n===void 0||n===``?delete r[t]:r[t]=n,r}function J(e,t,n=``){return h(t)?K(e).flatMap(e=>{let r=t[e.key],i=n?`${n} › ${e.label}`:e.label;return r==null||r===``?e.isRequired?[i]:[]:e.control.kind===`group`?J(e.control.schema,r,i):[]}):[]}var Gt=`{
|
|
1
|
+
import{n as e}from"./rolldown-runtime-hePW80VL.js";import{$ as t,A as n,B as r,F as i,G as a,H as o,I as s,J as c,K as l,L as ee,M as te,N as ne,P as re,Q as ie,R as ae,U as oe,V as se,W as ce,X as le,Y as ue,Z as de,a as u,at as fe,ct as pe,dt as me,et as he,ht as ge,i as d,it as _e,j as ve,lt as ye,mt as f,n as p,nt as be,ot as xe,q as Se,r as m,rt as Ce,st as we,tt as Te,ut as Ee,w as De,z as Oe}from"./schemas-D7cgkv3L.js";import{A as ke,C as Ae,D as je,S as Me,T as Ne,a as Pe,c as h,en as Fe,j as Ie,k as Le,qt as Re,ro as g,tn as ze,w as Be}from"./shaped-data-9kDvR1de.js";var Ve=e({endsWith:()=>ve,gt:()=>te,gte:()=>ne,includes:()=>re,length:()=>Oe,lowercase:()=>r,lt:()=>se,lte:()=>o,maxLength:()=>oe,maxSize:()=>ce,mime:()=>a,minLength:()=>l,minSize:()=>Se,multipleOf:()=>c,negative:()=>ue,nonnegative:()=>le,nonpositive:()=>de,normalize:()=>ie,overwrite:()=>t,positive:()=>he,properties:()=>Te,property:()=>be,regex:()=>Ce,size:()=>_e,slugify:()=>fe,startsWith:()=>xe,toLowerCase:()=>we,toUpperCase:()=>pe,trim:()=>ye,uppercase:()=>Ee}),He=e({ZodISODate:()=>p,ZodISODateTime:()=>m,ZodISODuration:()=>d,ZodISOTime:()=>u,date:()=>We,datetime:()=>Ue,duration:()=>Ke,time:()=>Ge});function Ue(e){return s(m,e)}function We(e){return i(p,e)}function Ge(e){return ae(u,e)}function Ke(e){return ee(d,e)}var _={...De,...Ve,iso:He},qe=new Set(`$schema.$ref.$defs.definitions.$id.id.$comment.$anchor.$vocabulary.$dynamicRef.$dynamicAnchor.type.enum.const.anyOf.oneOf.allOf.not.properties.required.additionalProperties.patternProperties.propertyNames.minProperties.maxProperties.items.prefixItems.additionalItems.minItems.maxItems.uniqueItems.contains.minContains.maxContains.minLength.maxLength.pattern.format.minimum.maximum.exclusiveMinimum.exclusiveMaximum.multipleOf.description.default.contentEncoding.contentMediaType.contentSchema.unevaluatedItems.unevaluatedProperties.if.then.else.dependentSchemas.dependentRequired.nullable.readOnly`.split(`.`));function Je(e,t){let n=e.$schema;return n===`https://json-schema.org/draft/2020-12/schema`?`draft-2020-12`:n===`http://json-schema.org/draft-07/schema#`?`draft-7`:n===`http://json-schema.org/draft-04/schema#`?`draft-4`:t??`draft-2020-12`}function v(e,t){return e.map((e,n)=>n<t?e:e.optional())}function Ye(e){return e.replace(/~1/g,`/`).replace(/~0/g,`~`)}function Xe(e,t){if(!e.startsWith(`#`))throw Error(`External $ref is not supported, only local refs (#/...) are allowed`);let n=e.slice(1).split(`/`).filter(Boolean);if(n.length===0)return t.rootSchema;let r=t.version===`draft-2020-12`?`$defs`:`definitions`;if(n[0]===r){let r=n[1]===void 0?void 0:Ye(n[1]);if(!r||!t.defs[r])throw Error(`Reference not found: ${e}`);return t.defs[r]}throw Error(`Reference not found: ${e}`)}function Ze(e,t){return _.transform(e=>e).check(n=>{let r=n.value;if(typeof r!=`object`||!r||Array.isArray(r))return;let i=Object.getOwnPropertyNames(r);if(t.minProperties!==void 0&&i.length<t.minProperties&&n.issues.push({origin:`object`,code:`too_small`,minimum:t.minProperties,inclusive:!0,message:`Too small: expected object to have >=${t.minProperties} properties`,input:r,inst:e,continue:!0}),t.maxProperties!==void 0&&i.length>t.maxProperties&&n.issues.push({origin:`object`,code:`too_big`,maximum:t.maxProperties,inclusive:!0,message:`Too big: expected object to have <=${t.maxProperties} properties`,input:r,inst:e,continue:!0}),t.keySchema)for(let e of i){let r=t.keySchema.safeParse(e);r.success||n.issues.push({code:`invalid_key`,origin:`record`,issues:r.error.issues,input:e,path:[e],continue:!0})}}).pipe(e)}function y(e,t){if(e===null)return`z`;let n=typeof e;if(n!==`object`){if(n===`number`&&Number.isNaN(e))return null;let t=String(e);return`${n[0]}${t.length}:${t}`}if(t.has(e))return null;t.add(e);try{if(Array.isArray(e)){let n=[];for(let r of e){let e=y(r,t);if(e===null)return null;n.push(e)}return`a${n.length}:[${n.join(`,`)}]`}let n=Object.keys(e).sort(),r=[];for(let i of n){let n=y(e[i],t);if(n===null)return null;r.push(`${i.length}:${i}=${n}`)}return`o${r.length}:{${r.join(`,`)}}`}finally{t.delete(e)}}var Qe=new Set([`items`,`prefixItems`,`additionalItems`,`additionalProperties`,`contains`,`propertyNames`,`not`,`if`,`then`,`else`,`allOf`,`anyOf`,`oneOf`,`unevaluatedItems`,`unevaluatedProperties`,`contentSchema`]),$e=new Set([`properties`,`patternProperties`,`dependentSchemas`,`dependencies`,`$defs`,`definitions`]);function b(e){return typeof e!=`object`||!e?!1:Array.isArray(e)?e.some(b):typeof e.$ref==`string`||Object.entries(e).some(([e,t])=>Qe.has(e)?b(t):!$e.has(e)||typeof t!=`object`||!t?!1:Object.values(t).some(b))}function x(e){return e===1?`element`:`elements`}function et(e,t){return _.transform(e=>e).check(e=>{let n=e.value;if(Array.isArray(n)){if(t.uniqueItems===!0){let t=new Map;for(let r=0;r<n.length;r++){let i=y(n[r],new Set);if(i===null)continue;let a=t.get(i);a===void 0?t.set(i,r):e.issues.push({code:`custom`,message:`Array items must be unique: element at index ${r} duplicates the one at index ${a}`,input:n,path:[r],continue:!0})}}if(t.containsSchema){let r=t.minContains??1,i=t.maxContains===void 0?1/0:t.maxContains+1,a=0;for(let e of n)if(t.containsSchema.safeParse(e).success&&++a>=i)break;a<r&&e.issues.push({code:`custom`,message:`Array must contain at least ${r} matching ${x(r)}; found ${a}`,input:n,continue:!0}),t.maxContains!==void 0&&a>t.maxContains&&e.issues.push({code:`custom`,message:`Array must contain at most ${t.maxContains} matching ${x(t.maxContains)}`,input:n,continue:!0})}}}).pipe(e)}function S(e,t){if(e!==!1)return e===void 0||e===!0?_.any():w(e,t)}var tt=/^(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/;function C(e,t){if(e.not!==void 0){if(typeof e.not==`object`&&Object.keys(e.not).length===0)return _.never();throw Error(`not is not supported in Zod (except { not: {} } for never)`)}if(e.unevaluatedItems!==void 0)throw Error(`unevaluatedItems is not supported`);if(e.unevaluatedProperties!==void 0)throw Error(`unevaluatedProperties is not supported`);if(e.if!==void 0||e.then!==void 0||e.else!==void 0)throw Error(`Conditional schemas (if/then/else) are not supported`);if(e.dependentSchemas!==void 0||e.dependentRequired!==void 0)throw Error(`dependentSchemas and dependentRequired are not supported`);if(e.$ref){let n=e.$ref;if(t.refs.has(n))return t.refs.get(n);if(t.processing.has(n))return _.lazy(()=>{if(!t.refs.has(n))throw Error(`Circular reference not resolved: ${n}`);return t.refs.get(n)});t.processing.add(n);let r=w(Xe(n,t),t);return t.refs.set(n,r),t.processing.delete(n),r}if(e.enum!==void 0){let n=e.enum;if(t.version===`openapi-3.0`&&e.nullable===!0&&n.length===1&&n[0]===null)return _.null();if(n.length===0)return _.never();if(n.length===1)return _.literal(n[0]);if(n.every(e=>typeof e==`string`))return _.enum(n);let r=n.map(e=>_.literal(e));return r.length<2?r[0]:_.union([r[0],r[1],...r.slice(2)])}if(e.const!==void 0)return _.literal(e.const);let n=e.type;if(Array.isArray(n)){let r=n.map(n=>C({...e,type:n},t));return r.length===0?_.never():r.length===1?r[0]:_.union(r)}if(!n)return _.any();let r;switch(n){case`string`:{let t=_.string();if(e.format){let n=e.format;n===`email`?t=t.check(_.email()):n===`uri`||n===`uri-reference`?t=t.check(_.url()):n===`uuid`||n===`guid`?t=t.check(_.uuid()):n===`date-time`?t=t.check(_.iso.datetime({offset:!0})):n===`date`?t=t.check(_.iso.date()):n===`time`?t=t.check(_.regex(tt)):n===`duration`?t=t.check(_.iso.duration()):n===`hostname`?t=t.check(_.hostname()):n===`ipv4`?t=t.check(_.ipv4()):n===`ipv6`?t=t.check(_.ipv6()):n===`mac`?t=t.check(_.mac()):n===`cidr`?t=t.check(_.cidrv4()):n===`cidr-v6`?t=t.check(_.cidrv6()):n===`base64`?t=t.check(_.base64()):n===`base64url`?t=t.check(_.base64url()):n===`e164`?t=t.check(_.e164()):n===`credit_card`?t=t.check(_.creditCard()):n===`iban`?t=t.check(_.iban()):n===`jwt`?t=t.check(_.jwt()):n===`emoji`?t=t.check(_.emoji()):n===`nanoid`?t=t.check(_.nanoid()):n===`cuid`?t=t.check(_.cuid()):n===`cuid2`?t=t.check(_.cuid2()):n===`ulid`?t=t.check(_.ulid()):n===`xid`?t=t.check(_.xid()):n===`ksuid`&&(t=t.check(_.ksuid()))}typeof e.minLength==`number`&&(t=t.min(e.minLength)),typeof e.maxLength==`number`&&(t=t.max(e.maxLength)),e.pattern&&(t=t.regex(new RegExp(e.pattern))),r=t;break}case`number`:case`integer`:{let t=n===`integer`?_.number().int():_.number();typeof e.minimum==`number`&&e.exclusiveMinimum!==!0&&(t=t.min(e.minimum)),typeof e.maximum==`number`&&e.exclusiveMaximum!==!0&&(t=t.max(e.maximum)),typeof e.exclusiveMinimum==`number`?t=t.gt(e.exclusiveMinimum):e.exclusiveMinimum===!0&&typeof e.minimum==`number`&&(t=t.gt(e.minimum)),typeof e.exclusiveMaximum==`number`?t=t.lt(e.exclusiveMaximum):e.exclusiveMaximum===!0&&typeof e.maximum==`number`&&(t=t.lt(e.maximum)),typeof e.multipleOf==`number`&&(t=t.multipleOf(e.multipleOf)),r=t;break}case`boolean`:r=_.boolean();break;case`null`:r=_.null();break;case`object`:{let n={},i=e.properties||{},a=new Set(e.required||[]),o=typeof e.additionalProperties==`object`?w(e.additionalProperties,t):void 0;for(let[e,r]of Object.entries(i)){let i=w(r,t);f(n,e,a.has(e)?i:i.optional())}if(e.patternProperties){let i=e.patternProperties,a=Object.keys(i),o=[];for(let e of a){let n=w(i[e],t),r=_.string().regex(new RegExp(e));o.push(_.looseRecord(r,n))}let s=[];if(Object.keys(n).length>0&&s.push(_.object(n).passthrough()),s.push(...o),s.length===0)r=_.object({}).passthrough();else if(s.length===1)r=s[0];else{let e=_.intersection(s[0],s[1]);for(let t=2;t<s.length;t++)e=_.intersection(e,s[t]);r=e}if(e.additionalProperties===!1){let e=Object.keys(n),t=a.map(e=>new RegExp(e)),i=r;r=r.check(n=>{if(!ge(n.value))return;let r=[];for(let i of Object.keys(n.value))e.includes(i)||t.some(e=>e.test(i))||r.push(i);r.length&&n.issues.push({code:`unrecognized_keys`,keys:r,input:n.value,inst:i})})}}else{let t=_.object(n);r=e.additionalProperties===!1?t.strict():o?t.catchall(o):t.passthrough()}let s=e.propertyNames!==void 0&&e.propertyNames!==!0,c=typeof e.minProperties==`number`?e.minProperties:void 0,l=typeof e.maxProperties==`number`?e.maxProperties:void 0;if(s||c!==void 0||l!==void 0){let n;s&&(n=w(typeof e.propertyNames==`object`&&e.propertyNames.type===void 0?{type:`string`,...e.propertyNames}:e.propertyNames,t)),r=Ze(r,{keySchema:n,minProperties:c,maxProperties:l})}break}case`array`:{let n=e.prefixItems,i=e.items;if(n&&Array.isArray(n)){let a=typeof e.minItems==`number`?e.minItems:0,o=v(n.map(e=>w(e,t)),a),s=Array.isArray(i)?void 0:S(i,t),c=_.tuple(o);r=s?c.rest(s):c,typeof e.minItems==`number`&&(r=r.check(_.minLength(e.minItems))),typeof e.maxItems==`number`&&(r=r.check(_.maxLength(e.maxItems)))}else if(Array.isArray(i)){let n=typeof e.minItems==`number`?e.minItems:0,a=v(i.map(e=>w(e,t)),n),o=S(e.additionalItems,t),s=_.tuple(a);r=o?s.rest(o):s,typeof e.minItems==`number`&&(r=r.check(_.minLength(e.minItems))),typeof e.maxItems==`number`&&(r=r.check(_.maxLength(e.maxItems)))}else if(i!==void 0){let n=w(i,t),a=_.array(n);typeof e.minItems==`number`&&(a=a.min(e.minItems)),typeof e.maxItems==`number`&&(a=a.max(e.maxItems)),r=a}else r=_.array(_.any());(e.uniqueItems===!0||e.contains!==void 0)&&(r=et(r,{uniqueItems:e.uniqueItems===!0,containsSchema:e.contains===void 0?void 0:w(e.contains,t),minContains:typeof e.minContains==`number`?e.minContains:void 0,maxContains:typeof e.maxContains==`number`?e.maxContains:void 0}));break}default:throw Error(`Unsupported type: ${n}`)}return r}function w(e,t){if(typeof e==`boolean`)return e?_.any():_.never();let n=C(e,t),r=e.type||e.enum!==void 0||e.const!==void 0;if(e.anyOf&&Array.isArray(e.anyOf)){let i=e.anyOf.map(e=>w(e,t)),a=_.union(i);n=r?_.intersection(n,a):a}if(e.oneOf&&Array.isArray(e.oneOf)){let i=e.oneOf.map(e=>w(e,t)),a=_.xor(i);n=r?_.intersection(n,a):a}if(e.allOf&&Array.isArray(e.allOf)){if(e.allOf.length===0)n=r?n:_.any();else{let i=r?n:w(e.allOf[0],t),a=+!r;for(let n=a;n<e.allOf.length;n++)i=_.intersection(i,w(e.allOf[n],t));n=i}}e.nullable===!0&&t.version===`openapi-3.0`&&(n=_.nullable(n)),e.readOnly===!0&&(n=_.readonly(n)),e.default!==void 0&&(n=n.default(e.default));let i={};for(let t of[`$id`,`id`,`$comment`,`$anchor`,`$vocabulary`,`$dynamicRef`,`$dynamicAnchor`])t in e&&(i[t]=e[t]);for(let t of[`contentEncoding`,`contentMediaType`,`contentSchema`])t in e&&(i[t]=e[t]);if(e.type===`object`&&e.$ref===void 0){e.propertyNames!==void 0&&!b(e.propertyNames)&&(i.propertyNames=e.propertyNames);for(let t of[`minProperties`,`maxProperties`])e[t]!==void 0&&(i[t]=e[t])}if(e.type===`array`&&e.$ref===void 0){e.contains!==void 0&&!b(e.contains)&&(i.contains=e.contains);for(let t of[`uniqueItems`,`minContains`,`maxContains`])e[t]!==void 0&&(i[t]=e[t])}for(let t of Object.keys(e))qe.has(t)||f(i,t,e[t]);return Object.keys(i).length>0&&t.registry.add(n,i),e.description&&(n=n.describe(e.description)),n}function nt(e,t){if(typeof e==`boolean`)return e?_.any():_.never();let n;try{n=JSON.parse(JSON.stringify(e))}catch{throw Error(`fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas`)}let r={version:Je(n,t?.defaultTarget),defs:n.$defs||n.definitions||{},refs:new Map,processing:new Set,rootSchema:n,registry:t?.registry??me};return w(n,r)}var rt=`https://generativelanguage.googleapis.com/v1beta/models`,it=`Zephyr.Puck.Charon.Kore.Fenrir.Leda.Orus.Aoede.Callirrhoe.Autonoe.Enceladus.Iapetus.Umbriel.Algieba.Despina.Erinome.Algenib.Rasalgethi.Laomedeia.Achernar.Alnilam.Schedar.Gacrux.Pulcherrima.Achird.Zubenelgenubi.Vindemiatrix.Sadachbia.Sadaltager.Sulafat`.split(`.`),at=[`minimal`,`low`,`medium`,`high`],ot=[`pcm`],st=[`1:1`,`3:2`,`2:3`,`3:4`,`4:3`,`4:5`,`5:4`,`9:16`,`16:9`,`21:9`],ct=[`1K`,`2K`,`4K`],lt=[`image/png`,`image/jpeg`],T=[{type:`builtin`,name:`googleSearch`,description:`Google Search grounding`,category:`grounding`,access:`read-only`,paths:[`*`],loadTier:`T0`,permission:`auto`},{type:`builtin`,name:`googleMaps`,description:`Google Maps grounding`,category:`grounding`,access:`read-only`,paths:[`*`],loadTier:`T0`,permission:`auto`,conflictsWith:[`googleSearch`,`urlContext`]},{type:`builtin`,name:`urlContext`,description:`Fetch URL context`,category:`grounding`,access:`read-only`,paths:[`*`],loadTier:`T0`,permission:`auto`},{type:`builtin`,name:`codeExecution`,description:`Google code execution`,category:`grounding`,access:`read-only`,paths:[`*`],loadTier:`T0`,permission:`auto`}],ut=[{type:`builtin`,name:`webSearch`,description:`OpenRouter web search`,category:`grounding`,access:`read-only`,paths:[`*`],loadTier:`T0`,permission:`auto`}],E=`local`;function dt(e,t){return!t&&e===`local`}function D(e=`http://localhost:11434`){return`${e.replace(/\/$/,``)}/v1`}var O=[{id:`gemini`,definition:`gemini`},{id:`openrouter`,definition:`openrouter`},{id:E,definition:`local`,connection:{baseUrl:D()}},{id:`typesafe`,definition:`typesafe`}],k={gemini:{provider:Le,factory:`geminiProvider`},openrouter:{provider:Ae,factory:`openRouterProvider`},local:{provider:je,factory:`localProvider`},typesafe:{provider:Me,factory:`typesafeProvider`}};function A(e){return e===void 0?void 0:k[e]?.provider}function ft(){return Object.keys(k)}function pt(e){return Object.keys(k).find(t=>k[t]?.factory===e)}function mt(e){return k[e]?.factory}function j(e,t){return e.find(e=>e.id===t)?.definition}function ht(e){return{id:e.id,...e.connection===void 0?{}:{connection:e.connection},...e.keySlot===void 0?{}:{keySlot:e.keySlot},...e.fallbackKeySlot===void 0?{}:{fallbackKeySlot:e.fallbackKeySlot}}}function M(e,t,n=A(t.definition),r=`register`){if(!n)throw Error(`The studio does not hold the provider definition '${t.definition}'.`);return e[r](n,ht(t))}function gt(e){let t=A(e);if(!t)return;if(!t.connection)return[];let r=n(t.connection,{io:`input`});return Object.entries(r.properties??{}).map(([e,t])=>({name:e,required:r.required?.includes(e)??!1,url:t.format===`uri`,...t.description?{description:t.description}:{}}))}function _t(e){let t=A(e);return t===void 0||t.key!==void 0}function N(e){let t=[];e.id.trim()||t.push({field:`id`,message:`Provider id is required.`});let n=A(e.definition),r=e.connection??{},i=n?.connection?.safeParse(r);for(let e of i?.error?.issues??[]){if(e.code===`unrecognized_keys`){for(let n of e.keys)t.push({field:`connection.${n}`,message:`This provider takes no '${n}'.`});continue}let n=e.path[0];if(typeof n!=`string`){t.push({message:e.message});continue}let i=n in r?e.message:`${n} is required.`;t.push({field:`connection.${n}`,message:i})}for(let n of[`keySlot`,`fallbackKeySlot`]){let r=e[n];r!==void 0&&!Fe.safeParse(r).success&&t.push({field:n,message:`A key slot is 1 to 32 letters, digits, hyphens, or underscores.`})}return e.keySlot&&e.keySlot===e.fallbackKeySlot&&t.push({field:`fallbackKeySlot`,message:g(`provider.fallback_slot`)}),(e.keySlot||e.fallbackKeySlot)&&n&&!n.key&&t.push({field:`keySlot`,message:g(`protocol.no_key`,{provider:e.id})}),t}function vt(e,t){let n=e.find(e=>e.id===t.provider)??{};return ze(n,{...t.keySlot?{keySlot:t.keySlot}:{},...t.fallbackKeySlot?{fallbackKeySlot:t.fallbackKeySlot}:{}})}function P(e,t){let n=A(e.definition);if(!n)return;let r;try{r=M(Re(),e,n)}catch{return[]}return r.serves.map(e=>e.protocol).filter(e=>t===void 0||e.endpoints[t]!==void 0)}function F(e,t,n){if(!e)return!1;let r=P(e,t);return r===void 0?!0:n===void 0?r.length>0:r.some(e=>e.id===n)}function yt(e,t,n){if(!bt(t))throw Error(`Cannot create a model route without a profile type.`);return{profileType:t,protocol:n.protocol,provider:n.provider,definition:j(e,n.provider),apiId:n.apiId,decision:t===`decision`}}function bt(e){return[`text`,`image`,`speech`,`transcription`,`live`,`decision`,`embedding`].includes(e)}function xt(e,t){let r=I(n(e.options,{io:`input`,unrepresentable:`any`}),``,!0),i=t?e.refusedOptions?.(t.apiId.trim())??[]:[];return r.filter(e=>{let n=e.path.split(`.`)[0]??e.path;return!i.includes(n)||t?.options[n]!==void 0})}function I(e,t,n){return Object.entries(e.properties??{}).flatMap(([r,i])=>{let a=t?`${t}.${r}`:r,o=n&&(e.required?.includes(r)??!1);if(i.type===`object`&&i.properties)return I(i,a,o);let s={path:a,label:St(r),required:o,...i.description?{description:i.description}:{}},c=i.anyOf?.filter(e=>typeof e.const==`string`||typeof e.const==`number`),l=c?.map(e=>e.const);if(i.enum?.every(e=>typeof e==`string`))return[{...s,kind:`choice`,choices:i.enum.map(e=>({value:e}))}];if(l&&l.length===i.anyOf?.length&&l.length>0){let e=l.every(e=>typeof e==`number`);if(e||l.every(e=>typeof e==`string`))return[{...s,kind:`choice`,choices:(c??[]).map(e=>({value:String(e.const),...e.title?{label:e.title}:{},...e.description?{description:e.description}:{}})),...e?{choiceType:`number`}:{}}]}return i.type===`boolean`?[{...s,kind:`boolean`}]:i.type===`array`&&i.items?.type===`string`?[{...s,kind:`names`}]:i.type===`string`?[{...s,kind:`text`}]:i.type===`number`||i.type===`integer`?[{...s,kind:`number`}]:[]})}function St(e){let t=e.replace(/([a-z0-9])([A-Z])/g,`$1 $2`).replace(/_/g,` `).toLowerCase();return t.charAt(0).toUpperCase()+t.slice(1)}function Ct(e,t){return t.split(`.`).reduce((e,t)=>e&&typeof e==`object`&&!Array.isArray(e)?e[t]:void 0,e)}function L(e,t,n){let[r=``,...i]=t.split(`.`),{[r]:a,...o}=e,s=i.length?L(a&&typeof a==`object`&&!Array.isArray(a)?a:{},i.join(`.`),n):n;return s===void 0||typeof s==`object`&&s&&!Array.isArray(s)&&!Object.keys(s).length?o:{...o,[r]:s}}var R=`studio`,wt={"observability.writeTo":R};function Tt(e){return Object.entries(wt).reduce((e,[t,n])=>z(e,t.split(`.`),n),e)}function z(e,[t,...n],r){if(t===void 0||!Object.hasOwn(e,t))return e;let i=e[t];if(!n.length)return i===r?Object.fromEntries(Object.entries(e).filter(([e])=>e!==t)):e;if(typeof i!=`object`||!i||Array.isArray(i))return e;let a=z(i,n,r);return a===i?e:Object.fromEntries(Object.entries(e).flatMap(([e,n])=>e===t?Object.keys(a).length?[[e,a]]:[]:[[e,n]]))}var Et=new Set(T.map(e=>e.name));function Dt(e){return e.protocol===Ie.id||e.protocol===ke.id}function Ot(e){return e.protocol===Be.id||e.protocol===Ne.id}function kt(e){return Et.has(e)}function At(e,t,n){return n.mode===`demo`?n.keys.runs(e,t?.definition):F(t,e)}var jt={text:`fast`,image:`image`,speech:`voice`,transcription:`transcription`,live:`live`,decision:`decision`,embedding:`embedding`};function Mt(e,t){let n=t?.(e)??{...B(e===`decision`?`typesafe`:`gemini`,e),apiId:``};return{modelId:jt[e],...n}}function B(e,t){let n=O.find(t=>t.id===e),r=n&&P(n,t)?.[0];if(!r)throw Error(`The studio provider '${e}' serves no ${t} agents.`);return{protocol:r.id,provider:e}}function Nt(e,t){return t.mode===`demo`?t.keys.violation(e):t.mode===`local`&&e.provider!==`local`?{field:`provider`,message:`Local runs require local models. Switch the model provider to Local.`}:null}var Pt=5,Ft=100,It=120;function V(e){let t=Array.isArray(e.type)?e.type.find(e=>e!==`null`):e.type;return t===`string`||t===`number`||t===`integer`||t===`boolean`||t===`array`?t:t===`object`||h(e.properties)?`object`:Array.isArray(e.enum)?`string`:`unknown`}function Lt(e){return h(e.items)?e.items:void 0}function H(e){let t=e?.enum;return Array.isArray(t)&&t.length>0&&t.every(e=>typeof e==`string`)?t:void 0}function U(e,t){let n=e[t];return typeof n==`number`&&Number.isFinite(n)?n:void 0}function W(e,t){let n=U(e,`minimum`),r=U(e,`maximum`);return t&&n!==void 0&&r!==void 0&&r>n&&r-n<=Ft?{kind:`range`,min:n,max:r}:{kind:`number`,isInteger:t,...n===void 0?{}:{min:n},...r===void 0?{}:{max:r}}}function Rt(e){if(e.format===`date`)return{kind:`date`};let t=U(e,`maxLength`);return{kind:`text`,isLong:t!==void 0&&t>It,type:e.format===`email`?`email`:`text`}}function zt(e){let t=Lt(e),n=H(t);if(n)return{kind:`choices`,options:n};let r=t?V(t):`unknown`;return r===`string`||r===`number`||r===`integer`?{kind:`words`}:t&&r===`object`?{kind:`rows`,item:t}:{kind:`json`}}function Bt(e){let t=H(e);if(t)return{kind:`choice`,options:t,isMenu:t.length>Pt};switch(V(e)){case`boolean`:return{kind:`switch`};case`number`:return W(e,!1);case`integer`:return W(e,!0);case`string`:return Rt(e);case`array`:return zt(e);case`object`:return h(e.properties)?{kind:`group`,schema:e}:{kind:`json`};default:return{kind:`json`}}}function G(e){return new Set(Array.isArray(e.required)?e.required.filter(e=>typeof e==`string`):[])}function K(e){let t=h(e.properties)?e.properties:{},n=G(e);return Object.entries(t).flatMap(([e,t])=>h(t)?[{key:e,label:typeof t.title==`string`&&t.title?t.title:Pe(e),...typeof t.description==`string`&&t.description?{description:t.description}:{},isRequired:n.has(e),control:Bt(t)}]:[])}function Vt(e){if(Array.isArray(e.examples)&&e.examples.length)return{value:e.examples[0]};if(`default`in e)return{value:e.default};if(`const`in e)return{value:e.const};if(Array.isArray(e.enum)&&e.enum.length)return{value:e.enum[0]}}function Ht(e){let t=Vt(e);if(t)return t.value;switch(V(e)){case`number`:case`integer`:return U(e,`minimum`)??1;case`boolean`:return!0;case`array`:return[];case`object`:return q(e);case`string`:case`unknown`:return`example`}}function q(e){let t=h(e.properties)?e.properties:{},n=new Set(G(e)),r={};for(let[e,i]of Object.entries(t))h(i)&&(n.has(e)?r[e]=Ht(i):Array.isArray(i.examples)&&i.examples.length&&(r[e]=i.examples[0]));return r}function Ut(e){return q(e)}function Wt(e,t,n){let r={...e};return n===void 0||n===``?delete r[t]:r[t]=n,r}function J(e,t,n=``){return h(t)?K(e).flatMap(e=>{let r=t[e.key],i=n?`${n} › ${e.label}`:e.label;return r==null||r===``?e.isRequired?[i]:[]:e.control.kind===`group`?J(e.control.schema,r,i):[]}):[]}var Gt=`{
|
|
2
2
|
"type": "object",
|
|
3
3
|
"properties": {
|
|
4
4
|
"query": { "type": "string" }
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Qn as e,Rr as t,Zn as n,_a as r,ba as i,cn as a,da as o,ln as s,ri as c,un as l,ya as u}from"./shaped-data-9kDvR1de.js";var d=/^data:([^;,]+);base64,/,f=new Map([[`image`,`data`],[`audio`,`data`],[`thought_signature`,`signature`],[`thought`,`signature`],[`function_call`,`signature`],[`reasoning.encrypted`,`data`]]);function p(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`;let t=typeof e.type==`string`?f.get(e.type):void 0;return t&&typeof e[t]==`string`&&e[t]!==``?t:void 0}var m=`sha256`,h=`text_sha256`;async function g(e){let t=await i(e);return t?{kind:m,hash:t.hash}:{kind:h,hash:await u(e)}}async function _(e){let t=d.exec(e);if(!t)return e;let{kind:n,hash:r}=await g(e.slice(t[0].length));return`data:${t[1]};${n},${r}`}async function v(e){let t=p(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 g(r);return n=t,[e,i]}return[e,await y(r)]})),i=Object.fromEntries(r);return n&&(i.dataKind=n),i}function y(e){return typeof e==`string`?_(e):Array.isArray(e)?Promise.all(e.map(e=>y(e))):e&&typeof e==`object`?v(e):Promise.resolve(e)}function b(e,n){return n.reduce((e,n)=>t(e,n),e)}function x(e,t){return t.some(Boolean)?r(e,e=>b(e,t)):e}async function S(e,t){return x(await y(e),t)}var C=`https://github.com/open-telemetry/semantic-conventions-genai/tree/8ffdf56`,w=`content_sha256`,T=`json_sha256`,E=[`gen_ai.usage.`,`theorem.usage.`],D={"theorem.upstream.row":`upstreamLog`,"theorem.wire.request":`outboundWire`,"theorem.guardrail":`guardrailDecisions`},O=`raw`,k=`match`,A=[`injection`];function j(e,t){return e===!0||e!==!1&&e[t]}function M(t,{scrub:r,detect:i}){let{sensitive:a,injection:s}=r;return c(t,[...a?e(t,o,a,i):[],...j(a,`host`)?n(t,i):[],...s?e(t,A,s,i):[]])}async function N(e,t){let n=await u(e);return t.content[n]=e,t.known.set(e,n),n}function P(e,t){let{[t]:n,...r}=e;return r}async function F(e,t){if(s(e)){let n=b(M(e.$content,t),t.canaries);return{...P(e,`$content`),[w]:await N(n,t)}}if(a(e)){let t=P(e,`$bytes`),n=await i(e.$bytes);return n?{...t,content_sha256:n.hash,bytes:n.bytes}:{...t,invalid_base64:!0,text_sha256:await u(e.$bytes)}}return l(e)?e:await z(e,e=>F(e,t))}function I(e,t){return typeof e==`string`?t(e):Array.isArray(e)?e.map(e=>I(e,t)):e&&typeof e==`object`?Object.fromEntries(Object.entries(e).map(([e,n])=>[e,I(n,t)])):e}function L(e,t){return I(e,e=>{let n=M(e,t),r=t.known.get(n);return r?{[w]:r}:n})}async function R(e,t){if(l(e)){let n=await S(e.$json,t.canaries),r=JSON.stringify(L(n,t)),i=await u(r);return t.content[i]=r,{...P(e,`$json`),[T]:i}}return await z(e,e=>R(e,t))}async function z(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 B(e,t){let n=await Promise.all(Object.entries(e).map(async([e,n])=>[e,await t(n)]));return Object.fromEntries(n)}async function V(e,t){let n=await Promise.all(e.events.map(async e=>({...e,attributes:await B(e.attributes,t)})));return{...e,attributes:await B(e.attributes,t),events:n}}function H(e,t){return t.usage?e:Object.fromEntries(Object.entries(e).filter(([e])=>!E.some(t=>e.startsWith(t))))}function U(e){return e.map(e=>{if(!e||typeof e!=`object`||Array.isArray(e))return e;let{[k]:t,...n}=e;return n})}function W(e,t){let n=D[e.name];if(n&&!t[n])return;if(e.name===`theorem.grounding`&&!t.evidenceRaw){let{[O]: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:U(r)}}:e}function G(e,t){return{...e,attributes:H(e.attributes,t),events:e.events.flatMap(e=>W(e,t)??[])}}function K(e){return Object.entries(e).flatMap(([e,t])=>t?[e]:[])}async function q(e){let{policy:t}=e,n={scrub:t.scrub,detect:t.detect,canaries:j(t.scrub.canary,`theorem`)?e.canaries??[]:[],content:{},known:new Map},r=e.spans.map(e=>G(e,t.include)),[i]=r;i&&(i.attributes={...i.attributes,"theorem.record.include":K(t.include),"theorem.record.scrub":K(t.scrub)});let a=await Promise.all(r.map(e=>V(e,e=>F(e,n)))),o=await Promise.all(a.map(e=>V(e,e=>R(e,n))));return{v:3,schemaUrl:C,resource:{...t.resource},...e.metadata?{metadata:e.metadata}:{},spans:o,content:n.content}}function J(e,t){if(Array.isArray(t))return t.map(t=>J(e,t));if(!t||typeof t!=`object`)return t;let n=Object.fromEntries(Object.entries(t).map(([t,n])=>[t,J(e,n)])),{[w]:r,[T]: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=J(e,JSON.parse(s));return Object.keys(a).length===0?c:c&&typeof c==`object`&&!Array.isArray(c)?{...c,...a}:n}export{J as n,q as t};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{C as e,M as t,h as n,j as r,n as i,p as a,t as o,y as s,z as ee}from"./tool-schema-D6i-fwc5.js";import{Ai as c,Ba as l,En as te,Fi as u,Ft as d,Ht as ne,Ia as re,Ri as ie,Xi as f,Zi as ae,aa as oe,qi as se,sa as p,wi as m,xn as h,zi as g}from"./shaped-data-9kDvR1de.js";import{a as ce,r as _}from"./live-ingress-OuSlQ6q7.js";var le=[{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`}],ue={identity:se,inputs:f(`inputs`).filter(e=>e!==`decision`)},v=le.map(e=>({...e,profileTypes:ue[e.id]??f(e.profilePath)}));function de(e){return v.find(t=>t.id===e)}function fe(e){return e.modelBindings.length>1}function pe(e){return e.modelBindings.some(n=>n.provider!==`local`&&!t(e.providers,n).keySlot)}function y(e,n){let r={provider:n.provider,keySlot:n.keySlot||e.models.key,fallbackKeySlot:n.fallbackKeySlot||e.models.fallbackKey},i=t(e.providers,r);return{...i,given:{keySlot:!!i.keySlot&&!r.keySlot,fallbackKeySlot:!!i.fallbackKeySlot&&!r.fallbackKeySlot}}}function me(e,t){let n=new Set(e.modelBindings.filter(n=>{let r=y(e,n);return r.keySlot===t||r.fallbackKeySlot===t}).map(e=>e.provider));return e.providers.filter(e=>n.has(e.id))}function he(e){let t=e.efforts.map(({alias:e})=>e.trim()).filter(Boolean);return new Set(t).size>1}function b(e){return e.attachmentsAccept.length>0||e.voiceAccept.length>0}var x=c,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:u[0],permission:g[0],loadTier:ie[0],paths:[`*`],inputJson:o,outputJson:i,...e}}function A(e,t,n){return(!e.description.trim()||e.description===O)&&n?{agentKey:t,description:`Asks ${n} and returns its answer.`}:{agentKey:t}}function j(){return{name:``,kind:`words`,pattern:``,flags:``,words:[]}}function M(){return{key:``,label:``,at:l(re,()=>`ignore`),patterns:[j()],hint:``}}function N(){let e=te(void 0);return{canaryBindNote:``,detect:l(ae,t=>({...e.detect[t]})),sources:Object.fromEntries(oe.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=ce({});return{writeTo:a,destination:a,sampleRate:e.sampleRate,include:{...e.include},scrub:{sensitive:e.scrub.sensitive,injection:e.scrub.injection,canary:e.scrub.canary},retainForDays:null,rotateAfterMiB:null,resourceJson:``}}function F(e){return e.map(([e,t])=>({key:E(`criterion`),label:e,text:t}))}function I(){return{contract:`guardrails.tool_call.v1`,maxStateBytes:null,questions:[{key:E(`question`),id:`verdict`,type:`choice`,instructions:`Given what the user asked for and what the call would do, should it run?`,criteria:F([[`allow`,`Safe, and what the user asked for.`],[`flag`,`Probably fine, but unusual or sensitive enough for a person to look first.`],[`block`,`Harmful, or clearly beyond what the user asked for.`]])},{key:E(`question`),id:`risk`,type:`score`,instructions:`How much harm would this call do if it were wrong?`,criteria:F([[``,`Low: reversible, and affects only the user.`],[``,`High: hard to undo, or affects other people or money.`]])}],images:[]}}var L=JSON.stringify({context:`The user asked the agent to tidy up old screenshots on their desktop.`,tool_call:{name:`delete_files`,path:`~/Documents`,recursive:!0},outcome:`Would delete 1,284 files, including tax_return_2025.pdf.`},null,2),R=JSON.stringify(`The user asked to tidy screenshots. The proposed call recursively deletes 1,284 files, including a tax return.`),ge=`To clear your desktop, select the screenshots and move them to the Trash. Empty the Trash to delete them for good.(Screen captures save to the desktop by default. You can change where they go in the Screenshot app's Options menu.(Press Command-Shift-5 to record the screen or capture a window. Recordings are saved as movie files next to your screenshots.(Stacks group desktop files by kind, date or tag, so a cluttered desktop folds into a few piles you can open one at a time.(Deleted files stay in the Trash for 30 days. Drag a file out of the Trash to put it back where it was.(When your disk is almost full, open Storage settings and review the largest files. Old downloads and installers are safe to remove.(Offloading unused apps frees space and keeps their documents. Reinstalling an app brings its data back.(Photos you have backed up can be optimised so the originals live in the cloud and smaller copies stay on the device.(Your plan renews on the same date each month. You can see the next charge under Billing, then Upcoming invoices.(To get a refund, open the invoice and choose Request refund. Charges from the last 14 days are refunded in full.(Update your card under Billing, then Payment methods. The new card is used for the next renewal, not for past invoices.(Annual plans cost two months less than paying monthly. Switching mid-term credits the unused months to the new plan.(Invoices are emailed as PDFs and list your company name and tax number. Edit those details before the invoice is issued.(Turn on two-step verification under Security. You will be asked for a code from your authenticator app each time you sign in on a new device.(If you forget your password, choose Forgot password on the sign-in page. The reset link expires after one hour.(Review signed-in devices under Security and sign out any you don't recognise. This ends their sessions immediately.(Passkeys replace your password with your fingerprint or face. Create one under Security, then Passkeys.(To close your account, export your data first. Closing deletes your workspace after a 30-day grace period.(Share a folder by choosing Share, then entering an email address. Viewers can read; editors can change and delete.(Public links work for anyone who has them. Set an expiry date, or turn the link off to stop sharing at once.(Transfer ownership of a folder before you leave a team, or its contents will be archived with your account.(Lisbon has mild, wet winters and warm, dry summers. Expect highs near 28 °C in August.(The best months for the Algarve coast are May, June and September, when the beaches are warm and the crowds are thin.(Trams in Lisbon climb the steep hills of Alfama and Graça. Line 28 is the famous one, and the busiest.(For a crisp pizza base, preheat the oven and the baking tray together at the highest setting for at least thirty minutes.(Rest steak for five minutes after cooking so the juices settle back into the meat instead of running onto the board.`.split(`(`).join(`
|
|
2
|
+
|
|
3
|
+
`),_e=`How do I delete every screenshot on my desktop?`;function ve(e,t=`choice`){let n=K(`question`,e.decision.questions.map(e=>e.id),e=>`question_${e}`);return{key:E(`question`),id:n,type:t,instructions:``,criteria:z(t)}}function ye(e,t,n){let r=t.replace(/\.[^.]*$/,``).toLowerCase().replace(/[^a-z0-9]+/g,`_`).replace(/^_|_$/g,``)||`image`,i=K(r,e.decision.images.map(e=>e.name),e=>`${r}_${e}`);return{key:E(`image`),name:i,...n}}function be(){return{key:E(`option`),name:``,label:``,isShownInChat:!1,choices:[]}}function xe(e,t){return e.map(e=>t.find(t=>t.value===e)??{key:E(`choice`),value:e,description:``})}function Se(){return{key:E(`criterion`),label:``,text:``}}function z(e){return e===`noul`||e===`box`?[]:F(e===`choice`?[[`yes`,``],[`no`,``]]:[[``,``],[``,``]])}function Ce(){return{identity:{agentId:``,profileType:``,handle:``,system:``,options:[]},included:[`observability`,`labels`],models:{defaultModel:``,allowModelSelect:!1,maxSteps:null,key:``},modelBindings:[],providers:[...e],tools:{t2Loader:``,parallel:!1},toolSpecs:[],inputs:{text:!0,attachmentsAccept:[],voiceAccept:[],maxFiles:null,maxBytes:null,maxTurnBytes:null,limitsByMime:{},contextFrom:[],contextMaxChars:null},outputs:{mode:`text`,schemaId:``,schemaJson:``,streamMode:``,streamThoughts:!0,validationEnabled:!1,maxRetries:null,itemRules:{},repairGuidance:``},turnBehaviour:{resumeEnabled:!1,allowContinue:[],autoContinue:[],maxContinues:null,continueInstruction:``,allowSteering:ne({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:_(`audio`),ingressVideo:_(`video`),ingressText:_(`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 B(e,t){return e.profileTypes.includes(t)&&!(t===`decision`&&we.has(e.id))}function V(e){let t=e.identity.profileType;if(!t)return[`identity`];let n=new Set(e.included);return v.filter(e=>e.role!==`branch`&&B(e,t)&&(!e.optional||n.has(e.id))).map(e=>e.id)}function H(e,t){let n=e.identity.profileType;return n!==``&&f(t).includes(n)}function Te(e,t,n){if((!n||n.includes(t.key))&&t.loadTier===`T2`&&H(e,`tools.t2Loader`)&&!e.tools.t2Loader.trim())return`No T2 loader is set under Tools, so this tool never loads.`}function Ee(e){return H(e,`identity.system`)&&p(e.guardrails.detect,`canary_leak`)}function De(e){let t=e.identity.profileType;return t!==``&&d.includes(t)}function U(e){let t=e.identity.profileType;return t?v.filter(n=>n.role===`spine`&&n.optional&&B(n,t)&&!e.included.includes(n.id)).map(e=>e.id):[]}function Oe(e){return{...e,attachmentsAccept:e.attachmentsAccept.filter(e=>h(m,e)),voiceAccept:[]}}function ke(e){return{...e,text:!1,attachmentsAccept:[],voiceAccept:e.voiceAccept.length?e.voiceAccept:[`audio/*`]}}function Ae(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 W(e,t){if(t.some(t=>t.modelId===e))return e;let[n,...r]=t;return n&&!r.length?n.modelId:``}function je(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:W(e.models.defaultModel,n)},modelBindings:n}}function G(e,t){let n=e.identity.profileType,r=n&&n!==`host`?n:`text`,i=e.modelBindings.map(e=>e.modelId),a=s(r,t),o=K(a.modelId,i,e=>`${a.modelId}${e}`);return D({...a,modelId:o})}function Me(e){return k({toolName:K(`my_tool`,e.toolSpecs.map(e=>e.toolName),e=>`my_tool_${e}`)})}function K(e,t,n){let r=new Set(t),i=e;for(let e=2;r.has(i);e++)i=n(e);return i}function Ne(e,t,i){if(t===`host`)return{...e,identity:{...e.identity,profileType:t}};let a=e.modelBindings.filter(n=>{let a=r(e.providers,t,n),o=e.providers.find(e=>e.id===n.provider);return ee(o,t,n.protocol)&&!Ie(i,t,a)}),o={...e,identity:{...e.identity,profileType:t},modelBindings:a},s=a.length?a:[G(o,i?.start)],c=!e.models.key&&pe({...o,modelBindings:s}),l=t===`speech`&&!e.speech.voice.trim()&&s.some(i=>n(r(e.providers,t,i)));return{...o,inputs:t===`image`?Oe(e.inputs):t===`transcription`?ke(e.inputs):e.inputs,...l?{speech:{...e.speech,voice:Pe}}:{},models:{...e.models,defaultModel:W(e.models.defaultModel,s),key:c?Le:e.models.key},modelBindings:s}}var Pe=`Kore`,Fe=[`text`,`image`,`speech`,`transcription`,`live`,`decision`];function Ie(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)&&Fe.some(e=>e!==t&&r(e))}var Le=`slot_a`;function Re(e,t){return U(e).includes(t)?{...e,included:[...e.included,t]}:e}function ze(e,t){return{...e,included:e.included.filter(e=>e!==t)}}function q(e){return`modelBinding:${e}`}var J=`toolSpec:`;function Y(e){return`${J}${e}`}function X(e){return e.startsWith(J)?e.slice(9):void 0}var Z=`provider:`;function Be(e){return`${Z}${e}`}function Ve(e){return e.startsWith(Z)?e.slice(9):void 0}var He=new Map(v.map(e=>[e.id,e.label]));function Q(e){return He.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=X(t);if(i!==void 0)return e.toolSpecs.some(e=>e.key===i)?{facet:`toolSpec`,key:i}:void 0;let a=V(e);if(r===void 0&&a.includes(t))return{facet:t}}function We(e,t){return t===`models`?e.modelBindings.map(e=>({id:q(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:Y(e.key),ref:{facet:`toolSpec`,key:e.key},label:e.toolName.trim()||`Unnamed tool`,children:[]}))}function Ge(e){let t=V(e).filter(e=>e!==`identity`).map(t=>({id:t,ref:{facet:t},label:Q(t),children:We(e,t)}));return{id:`identity`,ref:{facet:`identity`},label:e.identity.agentId.trim()||`Unnamed agent`,children:t}}export{z as A,Ee as B,V as C,U as D,K as E,be as F,y as G,Ne as H,M as I,b as J,he as K,j as L,ye as M,ve as N,Re as O,G as P,Me as R,H as S,ze as T,De as U,je as V,Ae as W,v as X,me as Y,de as Z,C as _,Ge as a,D as b,$ as c,_e as d,ge as f,x as g,S as h,Ue as i,Se as j,Te as k,w as l,T as m,Ve as n,X as o,R as p,fe as q,Be as r,Y as s,q as t,L as u,A as v,E as w,k as x,Ce as y,xe as z};
|