@datalayer/agent-runtimes 1.5.80 → 1.5.81

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.
@@ -0,0 +1,32 @@
1
+ import{a5 as B,fT as Gs,r as s,j as t,fU as Ys,fV as qs,ch as Jn,B as h,H as xt,T as z,v as J,cN as qt,eN as nn,fW as se,cH as bt,y as Js,fX as Qs,fY as Zs,em as Xs,fZ as eo,a_ as to,f_ as no,f$ as so,g0 as oo,g1 as ao,g2 as io,g3 as ro,ee as ls,ec as lo,ef as sn,g4 as co,g5 as uo,g6 as fo,g7 as po,g8 as cs,g9 as ds,ga as mo,L as go,gb as ho,dq as Jt,I as us,bp as st,D as fs,gc as Qn,gd as xo,ge as bo,dm as vo,bh as So,gf as yo,gg as wo,gh as Co,gi as jo,gj as ko,gk as To,a0 as Qt,gl as Ro,gm as Io,gn as Eo,go as Ao,gp as Po,gq as Uo,gr as $o,gs as Mo,gt as Oo,gu as Lo,gv as Fo,gw as zo,gx as _o,gy as No,gz as Bo,gA as Vo,gB as Ho,gC as Do,gD as Wo,gE as Ko,gF as ot,gG as Go,gH as Yo,gI as qo,gJ as Jo,gK as Zn,gL as Qo,gM as Ne,gN as Zo,gO as Xo,bi as vt,gP as ea,gQ as ta,gR as Xn,gS as na,gT as sa,gU as oa,gV as aa,eV as ia,gW as Zt,gX as Ae,gY as ra,gZ as la,g_ as ca,g$ as es,h0 as da,h1 as ts,h2 as ua,h3 as fa,h4 as pa,h5 as ma,h6 as ga,h7 as ha,h8 as xa,h9 as ba,ha as va,hb as Sa,hc as St,hd as ya,he as wa,hf as Ca,hg as ja,hh as ka,hi as ns,hj as Ta,hk as Ra,hl as Ia,hm as on,hn as Ea,ho as Aa,eD as Xt,hp as Pa,hq as Ua}from"../datalayer-app-main.js";import{S as $a,E as Ma,a as Oa}from"./SignInIcon-B9ZNyM4_.js";import{F as La,a as Fa,b as za}from"./LinkedInGreyIcon-BoWXE-HS.js";import{K as _a}from"./KebabHorizontalIcon-DD3W5tPT.js";function ps(){const n=B(Gs);return s.useMemo(()=>n.map(o=>o.value),[n])}const en={github:{name:"github",oauth2CallbackServerRoute:"jupyter_iam/oauth2/callback",oauth2CallbackUIRoute:"/iam/oauth2/github/callback"},google:{name:"google",oauth2CallbackServerRoute:"jupyter_iam/oauth2/callback",oauth2CallbackUIRoute:"/iam/oauth2/google/callback"},linkedin:{name:"linkedin",oauth2CallbackServerRoute:"jupyter_iam/oauth2/callback",oauth2CallbackUIRoute:"/iam/oauth2/linkedin/callback"}},ss=()=>{if(typeof document>"u")return"";const n=document.getElementById("datalayer-config-data");if(!n?.textContent)return"";try{const o=JSON.parse(n.textContent);return String(o?.iamUrl||"").replace(/\/$/,"")}catch{return""}},Na=(n,o="Unable to start social sign-in.")=>{if(n instanceof Error&&n.message)return n.message;if(typeof n=="string"&&n.trim())return n;if(n&&typeof n=="object"&&"message"in n){const r=n.message;if(typeof r=="string"&&r.trim())return r}return o},Ba=eo`
2
+ .signin-input-theme-scope input:-webkit-autofill,
3
+ .signin-input-theme-scope input:-webkit-autofill:hover,
4
+ .signin-input-theme-scope input:-webkit-autofill:focus,
5
+ .signin-input-theme-scope input:-webkit-autofill:active,
6
+ .signin-input-theme-scope input:-webkit-autofill:disabled,
7
+ .signin-input-theme-scope textarea:-webkit-autofill,
8
+ .signin-input-theme-scope textarea:-webkit-autofill:hover,
9
+ .signin-input-theme-scope textarea:-webkit-autofill:focus,
10
+ .signin-input-theme-scope textarea:-webkit-autofill:active,
11
+ .signin-input-theme-scope textarea:-webkit-autofill:disabled {
12
+ -webkit-text-fill-color: var(--fgColor-default) !important;
13
+ caret-color: var(--fgColor-default) !important;
14
+ -webkit-box-shadow: 0 0 0 1000px var(--bgColor-default) inset !important;
15
+ box-shadow: 0 0 0 1000px var(--bgColor-default) inset !important;
16
+ background-color: var(--bgColor-default) !important;
17
+ transition: background-color 9999s ease-in-out 0s !important;
18
+ }
19
+
20
+ .signin-input-theme-scope input:disabled,
21
+ .signin-input-theme-scope textarea:disabled {
22
+ -webkit-text-fill-color: var(--fgColor-muted) !important;
23
+ -webkit-box-shadow: 0 0 0 1000px var(--bgColor-default) inset !important;
24
+ box-shadow: 0 0 0 1000px var(--bgColor-default) inset !important;
25
+ background-color: var(--bgColor-default) !important;
26
+ opacity: 1 !important;
27
+ }
28
+ `,Va=({onSignIn:n,onApiKeySignIn:o,loginUrl:r,name:i,title:d="Datalayer OTEL",description:p="Sign in to access the observability dashboard.",icon:v,leadingIcon:c=t.jsx(Xs,{size:24}),github:f=!1,google:x=!1,linkedin:y=!1,apiKey:u=!1,signUp:ue=!0,socialSignInNavigationTarget:O,asDoc:w=!1,fillHeight:k=!0,hideHero:_=!1,calloutTitle:xe,calloutDescription:A,passwordToggleLabel:yt="Sign in with a password",signUpTitle:wt="Don't have an account?",signUpDescription:an="Create a free Datalayer account with your email address.",signUpLabel:be="Sign up with email",signUpHref:Ct="https://datalayer.ai/signup",onSignUp:Q,forgotPasswordHref:fe="/password",forgotPasswordLabel:at="Forgot password?",showForgotPassword:oe=!0,socialButtonMarginTop:Pe=3,actionButtonMaxWidth:te=320})=>{const ve=w&&!_,C=i??(w&&d==="Datalayer OTEL"?"Datalayer Sign In":d),it=v??(w?t.jsx($a,{size:24}):c),Se=s.useMemo(()=>{if(r)return r;const m=ss();return m?`${m}/api/iam/v1/login`:"/api/iam/v1/login"},[r]),[Z,jt]=s.useState(""),[L,kt]=s.useState(""),[ye,Tt]=s.useState(!1),[Ue,Rt]=s.useState(!1),[P,$e]=s.useState(!1),[X,Be]=s.useState(!1),[Me,Ve]=s.useState(null),[K,It]=s.useState(null),[ae,Et]=s.useState(""),[He,At]=s.useState(null),[we,ee]=s.useState(null),{enqueueToast:Ce}=Ys(),[je,ke]=s.useState(!1),[pe,De]=s.useState(""),me=s.useRef(null),We=s.useCallback(m=>qs()?Jn.URLExt.join(Jn.PageConfig.getBaseUrl(),m.oauth2CallbackServerRoute):`${window.location.protocol}//${window.location.hostname}${window.location.port?`:${window.location.port}`:""}${m.oauth2CallbackUIRoute}`,[]),ie=s.useMemo(()=>{if(typeof window>"u")return"/";const m=`${window.location.pathname}${window.location.search}${window.location.hash}`;return m.startsWith("/")?m:"/"},[]),I=s.useCallback(async m=>{if(!X){ee(null),Ve(m.name),Be(!0);try{const U=ss(),V=new URLSearchParams({provider:m.name,callback_uri:We(m)}),H=O===void 0?void 0:String(O||"").trim(),Ge=H===void 0?ie&&ie!=="/"?ie:void 0:H&&H.startsWith("/")&&!H.startsWith("//")?H:void 0;Ge&&V.set("post_auth_redirect",Ge);const E=`${U||""}/api/iam/v1/oauth2/authz/url?${V.toString()}`,$=await fetch(E),j=await $.json(),ce=j?.autorization_url;if(!$.ok||!ce)throw new Error(j?.message||"Unable to start social sign-in.");window.location.assign(ce)}catch(U){const V=Na(U);ee(V),Ce(V,{variant:"error"}),Ve(null),Be(!1)}}},[We,ie,Ce,X,O]);s.useEffect(()=>{je&&me.current?.focus()},[je]);const re=s.useCallback(()=>{ke(!1),De("")},[]),Te=s.useCallback(()=>{!pe.trim()||!o||(o(pe.trim()),re())},[pe,o,re]),le=s.useCallback(()=>{if(Q){Q();return}window.location.assign(Ct)},[Q,Ct]),rt=s.useCallback(()=>{if(fe){if(fe.startsWith("http://")||fe.startsWith("https://")){window.open(fe,"_blank","noopener,noreferrer");return}window.location.assign(fe)}},[fe]),Oe=s.useCallback(async()=>{if(!(w||!Z||!L||P)){$e(!0),ee(null);try{const m=await fetch(Se,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({handle:Z,password:L})});if(!m.ok)throw new Error(`HTTP ${m.status}`);const U=await m.json();if(U.success&&U.token){const V=String(U?.user?.id||U?.user?.uid||"").trim();if(!!U?.user?.mfaUrl&&V){It(V),At(U.token),ee(null);return}n&&n(U.token,Z)}else ee(U.message||"Invalid username or password.")}catch(m){ee(m instanceof Error?m.message:String(m))}finally{$e(!1)}}},[w,Z,L,P,Se,n]),Le=s.useCallback(async()=>{if(!(w||P||!K||!ae.trim()||!He)){$e(!0),ee(null);try{const m=new URL(Se,window.location.origin),U=m.pathname.endsWith("/api/iam/v1/login")?m.href.replace(/\/api\/iam\/v1\/login$/,""):`${m.origin}`,V=await fetch(`${U}/api/iam/v1/users/${K}/mfa/validate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({userUid:K,code:ae.trim()})}),H=await V.json();if(!V.ok||!H?.success)throw new Error(H?.message||"Failed to validate your MFA code.");n&&n(He,Z)}catch(m){const U=m instanceof Error?m.message:String(m);ee(U),Ce(U,{variant:"error"})}finally{$e(!1)}}},[w,Ce,Z,P,Se,ae,He,K,n]),G=s.useCallback(m=>{m.key==="Enter"&&(K?Le():Oe())},[K,Oe,Le]),Ke=X||P||w;return t.jsxs(h,{className:"signin-input-theme-scope",display:"flex",alignItems:_||ve||!k?"flex-start":"center",justifyContent:"center",minHeight:_||ve||!k?"auto":"100vh",bg:_?"transparent":"canvas.default",color:"fg.default",py:_?0:ve?2:4,children:[t.jsx(Ba,{}),t.jsxs(h,{width:"100%",maxWidth:440,p:0,children:[!_&&t.jsxs(t.Fragment,{children:[t.jsxs(h,{display:"flex",alignItems:"center",gap:2,mb:ve?2:3,justifyContent:"center",children:[it,t.jsx(xt,{sx:{fontSize:3},children:C})]}),t.jsx(z,{as:"p",sx:{fontSize:1,color:"fg.muted",mb:ve?2:3,textAlign:"center"},children:p})]}),(xe||A)&&t.jsxs(h,{mb:3,textAlign:"center",children:[xe&&t.jsx(xt,{as:"h3",sx:{fontSize:2,mb:1},children:xe}),A&&t.jsx(z,{sx:{color:"fg.muted",fontSize:1},children:A})]}),!K&&(f||x||y)&&t.jsxs(t.Fragment,{children:[f&&t.jsx(J,{block:!0,size:"large",leadingVisual:Me==="github"?()=>t.jsx(qt,{size:"small"}):La,disabled:Ke,onClick:()=>I(en.github),sx:{mt:Pe,maxWidth:te,mx:"auto"},children:"Sign in with GitHub"}),x&&t.jsx(J,{block:!0,size:"large",leadingVisual:Me==="google"?()=>t.jsx(qt,{size:"small"}):Fa,disabled:Ke,onClick:()=>I(en.google),sx:{mt:Pe,maxWidth:te,mx:"auto"},children:"Sign in with Google"}),y&&t.jsx(J,{block:!0,size:"large",leadingVisual:Me==="linkedin"?()=>t.jsx(qt,{size:"small"}):za,disabled:Ke,onClick:()=>I(en.linkedin),sx:{mt:Pe,maxWidth:te,mx:"auto"},children:"Sign in with LinkedIn"})]}),!K&&!ye&&t.jsx(h,{mt:3,display:"flex",justifyContent:"center",children:t.jsx(J,{leadingVisual:nn,size:"large",block:!0,disabled:w||P||X,onClick:()=>Tt(!0),sx:{maxWidth:te,mx:"auto"},children:yt})}),!K&&ye&&t.jsxs(h,{mt:4,children:[t.jsxs(se,{required:!0,sx:{mb:3},children:[t.jsx(se.Label,{children:"Username"}),t.jsx(bt,{autoFocus:!0,block:!0,placeholder:"Your username",value:Z,disabled:P||w,onChange:m=>jt(m.target.value),onKeyDown:G})]}),t.jsxs(se,{required:!0,sx:{mb:3},children:[t.jsx(se.Label,{children:"Password"}),t.jsx(bt,{block:!0,placeholder:"Your password",type:Ue?"text":"password",value:L,disabled:P||w,onChange:m=>kt(m.target.value),onKeyDown:G,trailingAction:t.jsx(bt.Action,{onClick:()=>Rt(!Ue),disabled:P||w,icon:Ue?Ma:Oa,"aria-label":Ue?"Hide password":"Show password",sx:{color:"var(--fgColor-muted)"}})})]}),t.jsxs(h,{display:"flex",alignItems:"center",justifyContent:"space-between",mt:3,children:[t.jsx(J,{variant:"primary",disabled:P||w||!Z||!L,onClick:Oe,children:P?"Signing in…":"Sign In"}),oe&&t.jsx(Js,{as:"button",sx:{fontSize:1,cursor:w?"not-allowed":"pointer",background:"none",border:"none",opacity:w?.6:1},onClick:()=>{w||P||rt()},children:at})]})]}),K&&t.jsxs(t.Fragment,{children:[t.jsxs(se,{required:!0,sx:{mb:3,mt:2},children:[t.jsx(se.Label,{children:"MFA Code"}),t.jsx(bt,{autoFocus:!0,block:!0,placeholder:"Your MFA code",value:ae,disabled:P||w,onChange:m=>Et(m.target.value),onKeyDown:G})]}),t.jsx(J,{variant:"primary",block:!0,disabled:P||w||!ae.trim(),onClick:Le,sx:{maxWidth:te,mx:"auto"},children:P?"Validating…":"Validate MFA Code"})]}),we&&t.jsx(z,{sx:{color:"danger.fg",fontSize:1,mt:3,display:"block"},children:we}),ue&&t.jsxs(h,{mt:4,pt:4,textAlign:"center",borderTop:"1px solid",borderColor:"border.muted",children:[t.jsx(xt,{as:"h3",sx:{fontSize:2,mb:2},children:wt}),t.jsx(z,{as:"p",sx:{color:"fg.muted",fontSize:1,mb:3},children:an}),t.jsx(h,{display:"flex",justifyContent:"center",children:t.jsx(J,{variant:"primary",size:"large",leadingVisual:Qs,disabled:w||P,onClick:le,children:be})})]}),u&&o&&t.jsxs(t.Fragment,{children:[t.jsxs(h,{display:"flex",alignItems:"center",gap:2,my:3,children:[t.jsx(h,{flex:1,height:"1px",bg:"border.default"}),t.jsx(z,{sx:{fontSize:0,color:"fg.muted"},children:"or"}),t.jsx(h,{flex:1,height:"1px",bg:"border.default"})]}),t.jsx(J,{block:!0,leadingVisual:nn,disabled:w||P||X,onClick:()=>ke(!0),sx:{maxWidth:te,mx:"auto"},children:"Sign in with an API Key"}),je&&t.jsx(h,{role:"dialog","aria-modal":"true","aria-labelledby":"signin-api-key-title",onKeyDown:m=>{m.key==="Escape"&&re()},onClick:re,position:"fixed",inset:0,zIndex:200,p:3,bg:"canvas.backdrop",display:"flex",alignItems:"center",justifyContent:"center",children:t.jsxs(h,{as:"form",onClick:m=>m.stopPropagation(),onSubmit:m=>{m.preventDefault(),Te()},width:"min(560px, 100%)",p:3,borderRadius:2,border:"1px solid",borderColor:"border.default",bg:"canvas.overlay",color:"fg.default",boxShadow:"shadow.large",children:[t.jsx(xt,{id:"signin-api-key-title",sx:{fontSize:2,mb:2},children:"Enter your API Key"}),t.jsxs(se,{required:!0,children:[t.jsx(se.Label,{children:"API Key"}),t.jsx(Zs,{block:!0,required:!0,autoFocus:!0,placeholder:"Paste your API key here",value:pe,onInput:m=>De(m.currentTarget.value),ref:me})]}),t.jsxs(h,{mt:3,display:"flex",justifyContent:"flex-end",gap:2,children:[t.jsx(J,{type:"button",onClick:re,children:"Cancel"}),t.jsx(J,{type:"submit",variant:"primary",disabled:!pe.trim(),children:"Authenticate"})]})]})})]})]})]})};function Ha(n){const{agentId:o,instructions:r,model:i,frontendTools:d,inference:p,subagents:v,sharing:c,onSubagentEvent:f,modeEffect:x}=n;return{type:"browser-vercel-ai",endpoint:"",agentId:o,enableConfigQuery:!1,options:{instructions:r,model:i,frontendTools:d,inference:p,subagents:v,sharing:c,onSubagentEvent:f,modeEffect:x}}}const os=to((n,o)=>({pending:void 0,suggest:(r,i)=>{const d=r.trim();d&&n({pending:{text:d,submit:i?.submit??!1,nonce:(o().pending?.nonce??0)+1}})},consume:()=>n({pending:void 0})})),Da=({state:n})=>no[n];class Wa extends Error{constructor(o,r){super(r),this.status=o,this.name="RuntimeRefusal"}status}function Ka({baseUrl:n,getAccessToken:o,fetch:r}){const i=n.replace(/\/+$/,""),d=(f={})=>{const x=o();return{...f,...x?{Authorization:`Bearer ${x}`}:{}}},p=async f=>{throw new Wa(f.status,ao(f.status,f.statusText,await io(f)))};return{json:async(f,x="GET",y)=>{const u=await r(`${i}${f}`,{method:x,headers:d({Accept:"application/json",...y===void 0?{}:{"Content-Type":"application/json"}}),...y===void 0?{}:{body:JSON.stringify(y)}});return u.ok?await u.json():p(u)},stream:async(f,x,{onEvent:y,signal:u},ue="POST")=>{const O=await r(`${i}${f}`,{method:ue,headers:d({"Content-Type":"application/json",Accept:"text/event-stream"}),body:JSON.stringify(x),signal:u});if(!O.ok)return p(O);await ro(O,y)},refused:p,headers:d,root:i,fetcher:r}}const W=n=>`/api/v1/apps/sessions/${encodeURIComponent(n)}`;function Ga(n){const{json:o,stream:r,fetcher:i,headers:d,refused:p,root:v}=Ka(n);return{serverUrl:v,accessToken:()=>n.getAccessToken(),start:(c,f)=>r("/api/v1/apps/sessions",{agent:c.agent,...c.deploymentUid?{deployment_uid:c.deploymentUid}:{},...c.appUid?{app_uid:c.appUid}:{},...c.version?{version:c.version}:{},...c.session?{session:c.session}:{},opener:c.opener},f),message:(c,f,x)=>r(`${W(c)}/messages`,{text:f},x),changeSettings:(c,f,x)=>r(`${W(c)}/settings`,{values:f},x,"PUT"),resume:(c,f,x)=>r(`${W(c)}/resume`,{agent:f},x),stop:c=>o(`${W(c)}/stop`,"POST"),end:c=>o(`${W(c)}/end`,"POST"),describe:c=>o(W(c)),described:async c=>oo(await o(W(c))),list:(c={})=>{const f=new URLSearchParams;for(const[y,u]of Object.entries(c))u!==""&&u!==void 0&&u!==!1&&f.set(y,String(u));const x=f.toString();return o(`/api/v1/apps/sessions${x?`?${x}`:""}`)},swap:(c,f)=>o(`${W(c)}/agent`,"POST",{agent:f}),clone:(c,f={})=>o(`${W(c)}/clone`,"POST",{up_to_turn:f.upToTurn??null,agent:f.agent??null,title:f.title??""}),exportFile:async(c,f="")=>{const x=await i(`${v}${W(c)}/export${f?`?format=${encodeURIComponent(f)}`:""}`,{method:"GET",headers:d()});return x.ok?x.text():p(x)},importFile:async(c,f={})=>{const x=new URLSearchParams;f.agent&&x.set("agent",f.agent),f.format&&x.set("format",f.format);const y=x.toString(),u=await i(`${v}/api/v1/apps/sessions/import${y?`?${y}`:""}`,{method:"POST",headers:d({"Content-Type":"application/x-ndjson"}),body:c});return u.ok?await u.json():p(u)},rename:(c,f)=>o(`${W(c)}/title`,"PUT",{title:f}),archive:(c,f)=>o(`${W(c)}/archived`,"PUT",{archived:f}),messages:async c=>so((await o(`${W(c)}/messages`)).messages)}}function Ya({agentName:n,sandboxStillRuns:o=!1,temporary:r=!0,onSignedIn:i,onSignUp:d}){const{configuration:p}=ls(),v=s.useCallback(c=>{lo.getState().checkIAMToken(c),i?.()},[i]);return t.jsx(h,{height:"100%",minHeight:0,overflowY:"auto",bg:"canvas.default",px:4,py:4,children:t.jsxs(h,{maxWidth:440,mx:"auto",children:[t.jsxs(h,{display:"flex",alignItems:"center",justifyContent:"center",gap:2,color:"attention.fg",mb:2,children:[t.jsx(nn,{size:20}),t.jsx(z,{sx:{fontSize:2,fontWeight:"semibold",color:"fg.default"},children:r?"This demo runs on a shared key":"Your key has expired"})]}),t.jsxs(z,{as:"p",sx:{fontSize:1,color:"fg.muted",textAlign:"center",mb:3},children:[r?`${n??"The agent"} has used the time this key allows. Sign in to point your own agent at it, use your own data, and drop the time limit.`:`${n??"The agent"} stopped because your session ran out.`,o?" Your notebook is still running in this page.":""]}),t.jsx(Va,{hideHero:!0,fillHeight:!1,calloutTitle:"Sign in to keep going",github:!0,google:!0,linkedin:!0,socialSignInNavigationTarget:typeof window>"u"?void 0:`${window.location.pathname}${window.location.search}`,loginUrl:p?.iamUrl?`${p.iamUrl}/api/iam/v1/login`:void 0,onSignIn:v,onSignUp:d})]})})}const qa="https://r1.datalayer.run";function Ja(n=!0){const{configuration:o}=ls(),r=sn(c=>c.token),i=o?.aiInferenceUrl||qa,d=co(i,n&&!r),p=r||d.token,v=s.useMemo(()=>({inferenceUrl:i,token:p||void 0}),[i,p]);return{inference:v,needsSignIn:uo(v),anonymous:d,inferenceUrl:i}}const Qa={name:"general-purpose",description:"A capable generalist for a task none of the specialists covers: research, reasoning, drafting, checking.",instructions:"You are a capable general-purpose assistant. Carry out the task you are given completely and report the result plainly, saying what you could not do."};function as(n){const o=n?.subagents;if(!o)return[];const r=(o.subagents??[]).map(i=>{const d=i.ref?fo(i.ref):void 0;return{name:i.name,description:i.description||d?.description||i.name,instructions:i.instructions??d?.systemPrompt,model:i.model??d?.model??o.defaultModel,icon:d?.icon}});return o.includeGeneralPurpose?[...r,Qa]:r}function Za(n){return n.replace(/^datalayer_/,"").replace(/_lexical$/,"")}function Xa(n){const o=Za(n);return/^executeCodeIn(Notebook|Document)$/.test(o)||/^(read|list)[A-Z]/.test(o)}function ei(n,o){return n.filter(r=>o?.has(r.name)||Xa(r.name))}function ti(n,o){const r=i=>o&&i.value.id===`${o}-tools`?0:i.value.id==="notebook-tools"?1:2;return n.map((i,d)=>({entry:i,index:d,rank:r(i)})).sort((i,d)=>i.rank-d.rank||i.index-d.index).map(i=>i.entry)}function ni(n,o,r){if(!r||!n.endsWith("-tools"))return!1;const i=n.slice(0,-6);return o.has(i)&&i!==r}const si={type:"object",properties:{}};function oi(n,o){const r=new Set(n.toolset);return n.commands.filter(i=>r.has(i.name)).map(i=>({name:i.name,description:i.description,parameters:i.parameters??si,location:"frontend",handler:async d=>{if(!o)throw new Error(`${i.name}: the ${n.plugin??n.id} plugin is not mounted on this page.`);const p=Object.keys(d??{}).length>0?d:void 0,v=await o.executeCommand(i.command,p);return v===void 0?{ok:!0,command:i.command,argument:p}:v}}))}function ms(n,o){return n.flatMap(r=>oi(r,o))}function ai(){const n=po(),o=ps();return s.useMemo(()=>ms(o,n),[o,n])}function ii(n){const o=n?.app_instance;if(!o||typeof o!="object")return"";const r=o.deployment_uid;return typeof r=="string"?r.trim():""}function ri(n,o,r){return n||!o?n:{id:r,messages:[]}}function li(n){const o=(new URLSearchParams(n).get("session")??"").trim();if(!o)return"";if(!/^[A-Za-z0-9_-]{8,128}$/.test(o))throw new Error(`?session=${o} names no session: a session uid is 8 to 128 letters, digits, hyphens or underscores.`);return o}function ci({facts:n}){if(!n)return null;const o=mo(n);return t.jsxs(h,{display:"inline-flex",alignItems:"center",gap:2,"data-session-state":n.state,children:[t.jsx(go,{size:"small",variant:n.state==="open"?"accent":n.state==="paused"?"attention":"secondary",children:ho(n)}),o?t.jsx(z,{sx:{fontSize:0,color:"fg.muted"},"data-session-lineage":"",children:o}):null]})}function di({facts:n,turn:o,context:r}){const i=B(cs),d=ds(i,n,"turn");return!n||d.length===0||o<1?null:t.jsx(h,{display:"inline-flex",gap:1,"data-turn-actions":o,children:d.map(p=>t.jsx(J,{size:"small",variant:"invisible","data-turn-action":p.id,onClick:()=>{Promise.resolve(p.run(n,{...r,atTurn:o})).catch(v=>r.say(String(v.message??v)))},children:p.label},p.id))})}function ui({uid:n,describe:o,context:r}){const i=B(cs),[d,p]=s.useState(void 0),[v,c]=s.useState(!1),[f,x]=s.useState(""),[y,u]=s.useState(void 0),ue={...r,show:r.show??u,say:k=>{x(k),r.say(k)}},O=s.useCallback(k=>{c(k),k&&n&&o(n).then(p,()=>p(void 0))},[o,n]);if(!n||i.length===0)return null;const w=ds(i,d);return t.jsxs(t.Fragment,{children:[t.jsxs(Jt,{open:v,onOpenChange:O,children:[t.jsx(Jt.Anchor,{children:t.jsx(us,{icon:_a,"aria-label":"Session actions",variant:"invisible",size:"small","data-testid":"session-actions"})}),t.jsx(Jt.Overlay,{width:"small",children:t.jsxs(st,{children:[w.length===0?t.jsx(st.Item,{disabled:!0,children:d?"Nothing applies to this session now.":"Reading the session…"}):w.map(k=>t.jsx(st.Item,{"data-session-action":k.id,onSelect:()=>{d&&Promise.resolve(k.run(d,ue)).catch(_=>ue.say(String(_.message??_)))},children:k.label},k.id)),f?t.jsxs(t.Fragment,{children:[t.jsx(st.Divider,{}),t.jsx(st.Item,{disabled:!0,"data-testid":"session-actions-said",children:f})]}):null]})})]}),y?t.jsx(fs,{title:y.title,onClose:()=>u(void 0),width:"large",children:t.jsx(h,{"data-session-panel":"",children:y.render()})}):null]})}const is={confirm:"Switch",cancel:"Keep it"};function fi({question:n,onPick:o}){const[r,i]=s.useState(n.options[0]?.id??""),[d,p]=s.useState("");s.useEffect(()=>{let c=!0;if(!n.says||!r){p("");return}return n.says(r).then(f=>c&&p(f),()=>c&&p("")),()=>{c=!1}},[r,n]);const v=n.options.find(c=>c.id===r);return t.jsx(fs,{title:n.title,onClose:()=>o(void 0),width:"medium",footerButtons:[{buttonType:"default",content:is.cancel,onClick:()=>o(void 0)},{buttonType:"primary",content:is.confirm,disabled:!r,onClick:()=>o(r||void 0)}],children:t.jsxs(h,{display:"grid",gap:3,"data-session-choose":"",children:[t.jsxs(se,{children:[t.jsx(se.Label,{children:n.title}),t.jsx(Qn,{value:r,onChange:c=>i(c.target.value),block:!0,children:n.options.map(c=>t.jsx(Qn.Option,{value:c.id,children:c.label},c.id))})]}),v?.description?t.jsx(z,{sx:{fontSize:1,color:"fg.muted"},children:v.description}):null,d?t.jsx(z,{as:"p",sx:{m:0,fontSize:1,fontStyle:"italic"},"data-session-choose-says":"",children:d}):null]})})}const pi="var(--theme-accent)";function gs({face:n,size:o}){return typeof n=="string"?t.jsx(xo,{emoji:n,size:o,label:""}):t.jsx(t.Fragment,{children:n})}function mi({face:n,size:o,state:r}){const i=r==="thinking"||r==="working",d=r==="paused";return t.jsxs(h,{as:"span","aria-hidden":!0,"data-presence":r,position:"relative",display:"inline-flex",alignItems:"center",justifyContent:"center",width:o+8,height:o+8,flexShrink:0,fontSize:o,lineHeight:1,children:[t.jsx(h,{as:"span",position:"absolute",inset:0,borderRadius:"50%",boxShadow:d?"none":`0 0 0 2px ${pi}`,border:d?"2px dashed":"none",borderColor:"border.default",opacity:i||r==="waiting"||d?.9:0,transition:"opacity var(--theme-motion-status, 0ms) var(--theme-motion-easing, ease)",animation:i?"loopPresenceBreath 1.8s ease-in-out infinite":"none",reducedMotion:{animation:"none"},sx:{"@keyframes loopPresenceBreath":{"0%, 100%":{transform:"scale(0.92)",opacity:.35},"50%":{transform:"scale(1.06)",opacity:.9}}}}),t.jsx(h,{as:"span",display:"inline-flex",opacity:d?.55:1,filter:d?"grayscale(0.6)":"none",transition:"opacity var(--theme-motion-status, 0ms) var(--theme-motion-easing, ease)",children:t.jsx(gs,{face:n,size:o})})]})}function gi({state:n}){return t.jsx(z,{role:"status","aria-live":"polite","data-presence-line":n,sx:{fontSize:0,color:n==="waiting"?"fg.default":"fg.muted",fontWeight:n==="waiting"?"semibold":"normal",whiteSpace:"nowrap",flexShrink:0},children:Da({state:n})})}const hi=on(void 0),xi=on(""),bi=on({}),de="",vi=1400,rs=parseInt(Pa["--loop-face-large"],10);function ki({workspace:n}){const o=bo(),r=vo(),i=s.useRef(null),d=s.useRef(void 0),{setViewControls:p}=n,v=s.useRef(n.setThread);v.current=n.setThread;const c=s.useCallback(()=>{const e=i.current?.thread();return e&&v.current?.(e),e},[]),[f,x]=s.useState(null),y=So(),u=y.getConfig(yo),ue=u?.placeholder||o.placeholder,O=u?.defaultSurface??"notebook",w=y.getConfig(wo),[k,_]=s.useState(de),xe=s.useRef(!1),A=B(Co),yt=B(jo),wt=B(ko),be=B(To)[0]?.value,Q=Qt(be?.promptStance??hi)??be?.prompt,fe=B(Ro),at=Io(fe[0]?.value),oe=s.useRef(at);oe.current=at;const Pe=s.useRef(""),te=B(Eo),ve=s.useMemo(()=>Ao(()=>te.reduce((e,a)=>({...e,...a.value.extras.value}),{})),[te]),C=Qt(te.length>0?ve:bi),it=s.useRef(new Set),Se=Po(Ea,n),Z=!Se.allowed,jt=Z?Se.reason??"Chat is unavailable for this sandbox":void 0,[L,kt]=s.useState(!1),[ye,Tt]=s.useState(!1),[Ue,Rt]=s.useState(!1),[P,$e]=s.useState({open:!1,pendingApproval:!1}),X=Uo(L,P,u?.presence?.paused===!0),Be=u?.presence?.onPresence;s.useEffect(()=>{Be?.(X),oe.current?.setPresence(X)},[Be,X]);const Me=s.useRef(u?.presence?.onSaying);Me.current=u?.presence?.onSaying;const Ve=s.useRef({answering:!1}),K=s.useCallback(e=>{i.current=e,Tt(!!e)},[]),It=s.useCallback(e=>{const{open:a,pendingApproval:l}=$o(e);$e(Ee=>Ee.open===a&&Ee.pendingApproval===l?Ee:{open:a,pendingApproval:l});const b={saying:Oo(e),answering:Mo(e)},g=Ve.current;(g.saying?.id!==b.saying?.id||g.saying?.text!==b.saying?.text||g.answering!==b.answering)&&(Ve.current=b,Me.current?.(b));const q=oe.current;if(!q)return;q.items(e);const F=new Set(["complete","completed","done","error","failed","cancelled","canceled","rejected","denied","stopped"]),ne={insertcell:"adding a cell",updatecell:"editing a cell",runcell:"running a cell",deletecells:"removing cells",readallcells:"reading the notebook",readcell:"reading a cell",executecode:"running code",insertblock:"adding a block",updateblock:"editing a block",runblock:"running a block",readdocument:"reading the document"};let S;for(let Ee=e.length-1;Ee>=0;Ee-=1){const ht=e[Ee];if(typeof ht.toolName=="string"&&ht.toolCallId){F.has(String(ht.status).toLowerCase())||(S=ht);break}}if(!S){q.activity(void 0);return}const Ie=S.toolName.toLowerCase().replace(/^datalayer_/,"").replace(/_lexical$/,"").replace(/[^a-z]/g,""),Ks=ne[Ie]??`using ${S.toolName}`;q.activity(`${Pe.current||"The agent"} is ${Ks}…`)},[]),ae=s.useRef(C);ae.current=C;const Et=s.useCallback(e=>{Rs(e),oe.current?.usage(e),ae.current.onUsage?.(e)},[]),He=s.useCallback(e=>{kt(e),e||oe.current?.end("done")},[]),At=s.useCallback(e=>{const a=oe.current;if(!a)return;let l=-1;for(let g=e.length-1;g>=0;g-=1)if(e[g].role==="user"){l=g;break}const b=e.slice(l+1).filter(g=>g.role==="assistant").map(Lo).filter(g=>g.trim().length>0).join(`
29
+
30
+ `);a.assistant(b)},[]),we=s.useRef([]),ee=s.useRef(!1),Ce=s.useRef(void 0),je=s.useRef(void 0),ke=s.useRef(void 0),pe=B(Fo),De=s.useRef(pe);De.current=pe;const me=s.useCallback((e,a)=>{if(je.current)return je.current;const l=ke.current;ke.current=void 0;const b=zo(De.current.map(F=>F.value),l?{...a??{},voice:l}:a),g=b?.loop;if(ee.current&&g?.files&&g.files.length>0){const F=Ce.current;if(!F)return"A file is given to an application running on a runtime: run it on Datalayer or on your machine to give it one.";let ne;try{ne=g.files.map(S=>({file:No(String(S.name??"")),base64:_o(String(S.data_url??""))}))}catch(S){return S instanceof Error?S.message:String(S)}F.execute(Bo(ne)).then(S=>{if(!S.success){x(`The files could not be put in the sandbox: ${S.error??"it failed"}.`);return}me(`${e}
31
+
32
+ ${Vo(ne.map(Ie=>Ie.file))}`,{...b,loop:Object.fromEntries(Object.entries(g).filter(([Ie])=>Ie!=="files"))})});return}oe.current?.begin(e,c());const q=i.current?.send;if(!q){we.current.push([e,b]);return}q(e,b)},[c]);s.useEffect(()=>{p(ye?{busy:L,stop:i.current?.stop,newChat:i.current?.newChat,send:me}:null)},[L,ye,p,me]),s.useEffect(()=>()=>p(null),[p]),s.useEffect(()=>n.prompts.subscribe(me),[n.prompts,me]),s.useEffect(()=>{if(!ye||we.current.length===0)return;const e=we.current.splice(0,we.current.length);for(const[a,l]of e)c(),i.current?.send(a,l)},[ye,c]);const We=s.useRef(!1),ie=s.useCallback(async e=>{x(null);const a=await Ho(ae.current,e);if(a){a.sent?Xe(""):x(a.refused);return}We.current||(We.current=!0,w?.firstPromptHook?.());const l=await n.submit(e);if(!l.handled){x(l.reason??null);return}Xe(""),l.result?.content&&x(l.result.content)},[n,w?.firstPromptHook]),I=s.useMemo(()=>A.find(e=>e.value.surfaceId===k)?.value,[A,k]),re=s.useCallback(e=>{xe.current=!0,_(e)},[]);s.useEffect(()=>Do(re),[re]),s.useEffect(()=>{Wo(A.map(e=>e.value.surfaceId))},[A]),s.useEffect(()=>{Ko(k&&k!==de?k:Ua)},[k]);const Te=s.useMemo(()=>O===de||O==="none"?void 0:A.find(e=>e.value.surfaceId===O),[A,O]);s.useEffect(()=>{xe.current||!Te||ot(Te.value,n)&&_(O)},[Te,n,O]);const[le,rt]=s.useState(null),Oe=s.useRef(null),Le=u?.fullScreenTopOffset??0,{fullScreen:G,usingApi:Ke,toggle:m,topOffsetPx:U}=Go(Oe,{forceOverlay:!!Le,topOffset:Le}),[V,H]=s.useState(!1),Ge=s.useRef(!1);s.useEffect(()=>{!L||Ge.current||G||(Ge.current=!0,H(!0))},[L,G]),s.useEffect(()=>{G&&H(!1)},[G]),s.useEffect(()=>{I&&!ot(I,n)&&(rt(I.surfaceId),_(de))},[I,n]);const lt=s.useMemo(()=>{if(le)return A.find(e=>e.value.surfaceId===le)?.value;if(!xe.current&&k===de)return Te?.value},[A,le,k,Te]);s.useEffect(()=>{if(!le||k!==de)return;const e=A.find(a=>a.value.surfaceId===le);e&&ot(e.value,n)&&(rt(null),_(le))},[A,k,le,n]);const E=n.agentId?.trim()||"default",$=Yo(n.sandbox.target??"local");ee.current=$;const j=qo(),ce=Qt(j?.selected??xi),R=j?.members.find(e=>e.id===ce),rn=B(Jo)[0]?.value,Pt=rn?.specId,M=Zn(R?.specId??E)??(Pt?Zn(Pt):void 0),Ye=R?void 0:rn,ln=$&&!R?Ia(Pt,M):void 0;Pe.current=R?.name??M?.name??E;const cn=B(Qo),dn=C.hiddenOpeners,un=C.hideOpeners,Ut=C.openers,$t=s.useMemo(()=>{if(un)return[];const e=new Set(dn??[]),a=S=>e.size===0?S:S.filter(Ie=>!e.has(Ie.text));if(Ut)return a(Ut);const l=cn.flatMap(S=>S.value.suggestions);if(l.length>0)return a(l);const b=a(M?.suggestions??[]),g=a(j?.team.suggestions??[]);if(g.length===0)return b;const q=new Set(g.map(S=>S.text)),F=j?.team.name??"Team",ne=R?.name??M?.name??E;return[...g.map(S=>({...S,group:F})),...b.filter(S=>!q.has(S.text)).map(S=>({...S,group:ne}))]},[cn,j,M,R,E,dn,un,Ut]),ct=s.useMemo(()=>$t.map(e=>({title:e.summary??e.text,message:e.message??e.text,group:e.group})),[$t]),Mt=Ne(M?.icon),Y=u?.presence,hs=Ne(j?.team.icon),fn=B(Zo),dt=s.useMemo(()=>{const e=[],a=new Map,l=new Set,b=new Set(A.map(g=>g.value.surfaceId));for(const g of ti(fn,I?.surfaceId)){if(ni(g.value.id,b,I?.surfaceId))continue;let q;try{q=g.value.tools(n)}catch(F){console.warn(`[loop] frontend tools from '${g.plugin}' failed:`,F);continue}for(const F of q){const ne=a.get(F.name);if(ne){console.warn(`[loop] frontend tool '${F.name}' from '${g.plugin}' is shadowed by the one from '${ne}'.`);continue}a.set(F.name,g.plugin),e.push(F),g.value.chatView&&l.add(F.name)}}for(const g of C.frontendTools??[])a.has(g.name)||(a.set(g.name,"chat-extras"),e.push(g),l.add(g.name));return I?e:ei(e,l)},[fn,n.surfaceId,n.agentId,C.frontendTools,I?.surfaceId,A]),Ot=ai(),qe=s.useMemo(()=>{if(Ot.length===0)return dt;const e=new Set(dt.map(a=>a.name));return[...dt,...Ot.filter(a=>!e.has(a.name))]},[dt,Ot]),pn=ps(),Lt=C.agentToolBundles,xs=s.useMemo(()=>{const e=C.frontendTools??[];if(!Lt?.length)return C.frontendTools;const a=ms(pn.filter(b=>Lt.includes(b.id)),y),l=new Set(e.map(b=>b.name));return[...e,...a.filter(b=>!l.has(b.name))]},[C.frontendTools,Lt,pn,y]);Ce.current=$&&qe.some(e=>e.name===Xo)?y.getOutput(vt)?.sandbox:void 0;const T=ea(n.sandbox,n.serverUrl),Je=s.useMemo(()=>Ga({baseUrl:T??"",getAccessToken:()=>d.current,fetch:(e,a)=>fetch(e,a)}),[T]),mn=B(ta),bs=s.useMemo(()=>mn.filter(e=>e.value.composer).map(e=>({name:e.value.name,description:e.value.description})),[mn]),vs=s.useMemo(()=>{if(!j||!R)return as(M).map(l=>({name:l.name,description:l.description,icon:Ne(l.icon)}));const e=j.members.map(l=>({name:l.name,description:l.description,emoji:l.emoji,icon:Ne(l.icon),disabled:l.id===R.id,disabledReason:l.id===R.id?`You are already talking to ${l.name}`:void 0})),a=Xn(j.team,R.id).filter(l=>!j.members.some(b=>b.name===l.name)).map(l=>({name:l.name,description:l.description,icon:Ne(l.icon)}));return[...e,...a]},[j,R,M]),{inference:gn,anonymous:Ss}=Ja($),ys=sn(e=>e.user),Ft=$&&Ss.status==="expired",hn=!ys,Qe=na();je.current=Qe.disabled?Qe.disableReason||"This conversation is closed here.":void 0;const zt=T===void 0?sa(n.sandbox,o):void 0,Ze=Z||Ft||!!ln||!!zt||Qe.disabled,xn=Ft?hn?o.demoKeyExpired:o.keyExpired:ln??zt??jt??(Qe.disabled?Qe.disableReason:void 0),[_t,Xe]=s.useState(""),[bn]=oa(),et=s.useMemo(()=>u?.voice?aa(u.voice,bn):void 0,[u?.voice,bn]),[ws,Cs]=s.useState(!1),[js,vn]=s.useState(),ut=js??Ye?.model??M?.model??n.model??"",Fe=ia(),Sn=s.useRef(Fe),yn=s.useRef(ce),wn=s.useRef(Fe);wn.current=Fe,s.useEffect(()=>{yn.current!==ce&&(yn.current=ce,Sn.current=wn.current,vn(void 0))},[ce]);const ks=Fe&&Fe!==Sn.current?Fe:null,[Ts,Rs]=s.useState(),Is=ks??Ts??null,Es=Zt(Ae.inpromptMenu),Cn=Zt(Ae.promptAction),jn=Zt(Ae.chatHeader),As=s.useMemo(()=>j?.members.map(e=>({id:e.id,name:e.name,description:e.description,icon:Ne(e.icon)}))??[],[j]),Re=os(e=>e.pending),[kn,Ps]=s.useState(0);s.useEffect(()=>ra(()=>Ps(e=>e+1)),[]),s.useEffect(()=>{Re&&(Xe(Re.text),os.getState().consume(),Re.submit&&ie(Re.text))},[Re]);const Tn=y.getConfig(vt)?.datalayerCreatePayload,D=!!(Ye?.createPayload?.app_spec||Tn?.app_spec),Nt=ii(Tn),Us=sn(e=>e.token),Bt=y.getConfig(vt)?.datalayerVisitors,$s=la(Bt),Ms=y.getConfig(vt)?.embedToken,ge=Bt?$s.token:Ms||Us;d.current=ge||void 0;const Os=s.useMemo(()=>ca(u?.voice,ge||void 0),[u?.voice,ge]),he=!!(Nt||Bt);if(he&&!D)throw new Error("A deployment’s page runs its application: its host gave no app_spec.");const[Rn]=s.useState(es),[Vt,Ls]=s.useMemo(()=>{try{return[li(typeof window>"u"?"":window.location.search),""]}catch(e){return["",e instanceof Error?e.message:String(e)]}},[]),[In,Fs]=s.useState(void 0),N=s.useMemo(()=>In??ri(u?.thread??(Vt&&D?{id:Vt,messages:[],fromRuntime:!0}:void 0),Nt,Rn),[In,u?.thread,Vt,D,Nt,Rn]),[ze,En]=s.useState(null),zs=!!(N?.fromRuntime&&ze?.given!==N.id);s.useEffect(()=>{if(!N?.fromRuntime||!D||!T)return;let e=!0;return(async()=>{let a="";for(let l=0;l<4&&e;l+=1)try{const b=await da({agentBaseUrl:T,agentId:E,uid:N.id,token:ge});e&&En({given:N.id,thread:{...N,fromRuntime:!1,messages:b}});return}catch(b){a=b instanceof Error?b.message:String(b),await new Promise(g=>setTimeout(g,1500))}e&&En({given:N.id,thread:{id:es(),messages:[],onStarted:N.onStarted},said:ts.notOpened(a)})})(),()=>{e=!1}},[N?.id,N?.fromRuntime,D,T,E,ge]);const Ht=N?.fromRuntime?ze?.given===N.id?ze.thread:void 0:N,ft=n.thread||Ht?.id||"",[An,Pn]=s.useState(void 0),[_s,Un]=s.useState(0);s.useEffect(()=>{if(!D||!T||!ft||L)return;let e=!0;return Je.described(ft).then(a=>e&&Pn(a),()=>e&&Pn(void 0)),()=>{e=!1}},[D,T,ft,L,_s,Je]);const[$n,Mn]=s.useState(Ls),[On,Ln]=s.useState(null),Dt=s.useRef(null),Wt=s.useRef(null),Fn=s.useRef(null),zn=s.useMemo(()=>({client:Je,say:e=>{Mn(e),Un(a=>a+1)},openThread:e=>{Fs({id:e,messages:[],fromRuntime:!0}),Un(a=>a+1)},download:(e,a,l)=>{const b=URL.createObjectURL(new Blob([a],{type:l})),g=document.createElement("a");g.href=b,g.download=e,g.click(),URL.revokeObjectURL(b)},choose:e=>new Promise(a=>{Dt.current=a,Ln(e)}),pickFile:e=>new Promise(a=>{const l=Fn.current;if(!l){a(void 0);return}Wt.current=a,l.accept=e,l.value="",l.click()})}),[Je]),Kt=s.useMemo(()=>$?Ha({agentId:R?.specId??E,instructions:ua(M,Ye?.instructions),model:ut||void 0,inference:gn,frontendTools:qe,subagents:j&&R?Xn(j.team,R.id):as(M),sharing:j?.sharing,onSubagentEvent:e=>Aa.getState().appendSubagentEvent(e),modeEffect:Ye?.modeEffect}):T!==void 0?{type:"ag-ui",endpoint:D?`${T}/api/v1/apps/agents/${encodeURIComponent(E)}/ag-ui/`:`${T}/api/v1/ag-ui/${E}/`,...D&&ge?{authToken:ge}:{},...D?{uiSocket:`${T.replace(/^http/,"ws")}/api/v1/apps/ui`,uiFiles:`${T}/api/v1/apps/agents/${encodeURIComponent(E)}/files`,appSessions:`${T}/api/v1/apps/sessions`,...he?{ownRoutesOnly:!0}:{}}:{},agentId:E,configEndpoint:`${T}/api/v1/configure`,enableConfigQuery:!0}:void 0,[E,$,gn,R,qe,j,M,Ye,ut,T,D,ge,he]),pt=fa(!$,Kt?.type==="ag-ui"?Kt.configEndpoint:void 0,void 0,E),tt=pa(),mt=ma(E),[_n,Gt]=s.useState(void 0),[Ns,Bs]=s.useState(void 0);s.useEffect(()=>{if($||T===void 0)return;const e=ga(T,E,he);if(!e){Gt([]);return}let a=!1;return fetch(e).then(l=>l.ok?l.json():null).then(l=>{a||(Gt(l?ha(l):[]),Bs(l?xa(l):void 0))}).catch(()=>{a||Gt([])}),()=>{a=!0}},[T,E,$,he]);const Vs=s.useMemo(()=>ba(_n,()=>Object.values(va).filter(e=>e.available&&Sa(e)).map(e=>({id:e.id,name:e.name,provider:e.provider}))),[_n]),Nn=s.useMemo(()=>{const e=pt.data?.builtinTools??[],a=new Set(e.map(l=>l.name));return{runtime:e,frontend:qe.filter(l=>!a.has(l.name)).map(l=>({id:l.name,name:l.name}))}},[pt.data?.builtinTools,qe]),Bn=s.useMemo(()=>new Set((tt.data?.skills??[]).filter(e=>e.status==="enabled"||e.status==="loaded").map(e=>e.id)),[tt.data]),Hs=s.useCallback(async e=>{if(he)throw new Error("A deployment’s chat does not switch its runtime’s model.");vn(e),!($||T===void 0)&&await fetch(`${T}/api/v1/configure/inference/provider`,{method:"PUT",headers:{"content-type":"application/json"},body:JSON.stringify({model:e})}).catch(()=>{})},[T,$,he]),Vn=u?.promptPlacement==="bottom-chat",Ds=u?.promptPlacement==="floating",_e=u?.promptPlacement==="top",nt=u?.hidePrompt===!0||C.hidePrompt===!0,Ws={onSend:()=>{ie(_t)},input:_t,setInput:Xe,focusTrigger:Re||kn?(Re?.nonce??0)+kn:void 0,placement:Ds||Q==="floating"||Q==="floating-top"||Q==="floating-bottom"?"floating":"docked",floatingAnchor:Q==="floating-top"?"top":"bottom",isLoading:L,onStop:()=>n.viewControls.stop?.(),placeholder:xn??C.sendInstead?.says??ue,typingSuggestions:$t.map(e=>e.text),suggestions:ct,disableInputPrompt:Ze,connectionConfirmed:!Ze,interim:ws,padding:_e||Q==="floating-top"||Q==="floating-bottom"||Q==="docked-top"?2:3,promptVariant:"lexical",autoFocus:u?.autoFocusPrompt??!0,mentionableAgents:vs,promptCommands:bs,headerContent:Es.length>0?t.jsx(St,{slot:Ae.inpromptMenu,props:{workspace:n}}):void 0,footerExtras:Cn.length>0||et&&et.input!=="off"?t.jsxs(t.Fragment,{children:[Cn.length>0?t.jsx(St,{slot:Ae.promptAction,props:{workspace:n}}):null,et&&et.input!=="off"?t.jsx(ya,{voice:et,input:_t,setInput:Xe,disabled:Ze,speaking:Ue,onStopSpeaking:()=>i.current?.stopSpeaking?.(),playbackLevel:()=>i.current?.voiceLevel?.()??0,running:L,onStopRun:()=>(i.current?.interrupt??i.current?.stop)?.(),onInterrupted:()=>i.current?.markInterrupted(),onInterimChange:Cs,answers:!!(u?.voice?.output&&u.voice.output!=="off"&&u.voice.speechUrl),onSpoken:e=>{ke.current=e},send:(e,a)=>{ke.current=a,ie(e)}}):null]}):void 0,showAgentsMenu:!Y,showInlineAgentsMenu:!1,agents:As,selectedAgentId:ce,onSelectAgent:e=>j?.select(e),showTokenUsage:C.showTokenUsage??u?.showTokenUsage??!0,showContextRing:!0,agentUsage:Is??void 0,showModelSelector:!Y&&!he,models:Vs,decisions:Ns,selectedModel:ut,onModelSelect:e=>{Hs(e)},showToolsMenu:!Y,availableTools:Nn.runtime,availableFrontendTools:Nn.frontend,mcpServers:pt.data?.mcpServers??[],mcpStatusData:C.mcpStatusData??void 0,showSkillsMenu:!Y,skills:tt.data?.skills??[],skillsLoading:tt.isLoading,enabledSkills:Bn,onToggleSkill:e=>Bn.has(e)?mt.disableSkill(e):mt.enableSkill(e),onToggleAllSkills:(e,a)=>e.forEach(l=>a?mt.enableSkill(l):mt.disableSkill(l)),codemodeEnabled:C.codemodeEnabled??!1,onToggleCodemode:C.onToggleCodemode,isA2AProtocol:!1,hasConfigData:!!pt.data,hasSkillsData:!!tt.data},Hn=yt[0]?.value.Component,Yt=wt[0]?.value.Component,Dn=!u?.hideHeader&&!!Yt,gt=Hn?t.jsx(Hn,{workspace:n,composer:Ws}):null,Wn=A.length>0&&u?.showSurfaceSelector!==!1?t.jsx(Si,{surfaces:A.map(e=>e.value),active:I?.surfaceId??lt?.surfaceId??de,onChange:re,workspace:n}):null,Kn=t.jsxs(t.Fragment,{children:[A.map(e=>{const a=e.value,l=I?.surfaceId===a.surfaceId;return l||it.current.has(a.surfaceId)||ot(a,n)?(it.current.add(a.surfaceId),t.jsx(h,{sx:l?{flex:"1 1 0",minWidth:0,minHeight:0}:{position:"absolute",inset:0,visibility:"hidden",pointerEvents:"none",zIndex:-1},children:t.jsx(wa,{load:a.load,props:{surfaceId:a.surfaceId,workspace:n},fallback:t.jsxs(tn,{children:["Loading ",a.title,"…"]}),errorFallback:g=>t.jsxs(tn,{children:[a.title," failed to load: ",g.message]})})},a.surfaceId)):null}),!I&&lt?t.jsx(h,{flex:"1 1 0",minWidth:0,minHeight:0,children:t.jsxs(tn,{children:["Starting ",lt.title,"…"]})}):null]}),Gn=t.jsx(t.Fragment,{children:t.jsxs(h,{flex:_e&&I?"0 0 34%":"1 1 0",maxWidth:_e&&I?460:void 0,minWidth:0,minHeight:0,display:"flex",flexDirection:"column",borderLeft:I?"1px solid":void 0,borderColor:"border.default",position:"relative",children:[C.errorBanner?t.jsx(h,{flexShrink:0,px:3,py:2,fontSize:1,borderBottom:"1px solid",bg:C.errorBanner.variant==="warning"?"attention.subtle":"danger.subtle",color:C.errorBanner.variant==="warning"?"attention.fg":"danger.fg",borderColor:C.errorBanner.variant==="warning"?"attention.muted":"danger.muted",children:C.errorBanner.message}):null,ze?.said&&ze.given===N?.id?t.jsx(z,{as:"p",role:"status",sx:{m:0,px:3,py:2,fontSize:1,color:"fg.muted"},children:ze.said}):null,$n?t.jsxs(h,{display:"flex",alignItems:"baseline",gap:2,px:3,py:2,fontSize:1,color:"fg.muted",role:"status","data-session-said":"",children:[t.jsx(z,{sx:{flex:1},children:$n}),t.jsx(J,{size:"small",variant:"invisible",onClick:()=>Mn(""),children:"Dismiss"})]}):null,On?t.jsx(fi,{question:On,onPick:e=>{Ln(null),Dt.current?.(e),Dt.current=null}}):null,t.jsx("input",{ref:Fn,type:"file",hidden:!0,"data-session-file":"",onChange:async e=>{const a=e.target.files?.[0],l=a?await a.text():void 0;Wt.current?.(l),Wt.current=null}}),t.jsx(h,{flex:"1 1 auto",minHeight:0,display:"flex",children:zs?t.jsx(z,{as:"p",role:"status",sx:{m:0,p:3,fontSize:1,color:"fg.muted"},children:ts.opening}):t.jsx(Ca,{themeVariant:u?.themeVariant,themeOverrides:u?.themeOverrides,colorMode:u?.colorMode,thread:Ht,voice:Os,disabled:Ze,disableReason:xn,protocol:Kt,frontendTools:$?void 0:xs,initialModel:ut||void 0,title:Y?.name??R?.name??M?.name??E,description:Y?.welcome??M?.description,brandIcon:Y?.face?t.jsx(mi,{face:Y.face,size:20,state:X}):t.jsx(Mt,{size:20}),headerContent:Y&&!zt?t.jsx(gi,{state:X}):void 0,emptyState:{icon:Y?.face?t.jsx("span",{"aria-hidden":!0,style:{fontSize:rs,lineHeight:1},children:t.jsx(gs,{face:Y.face,size:rs})}):t.jsx(Mt,{size:48}),title:Y?.name??R?.name??M?.name??E,...j&&R?{sections:[{group:j.team.name,icon:t.jsx(hs,{size:48}),title:j.team.name,subtitle:j.team.description},{group:R.name,icon:t.jsx(Mt,{size:32}),title:R.name,subtitle:M?.description}]}:null},suggestions:_e||be||u?.suggestionLabels===!1?[]:ct,showHeader:Dn,headerButtons:{showNewChat:u?.headerButtons?.newChat??!1,showClear:u?.headerButtons?.clear??!1},renderHeader:Yt?e=>t.jsx(Yt,{workspace:n,header:n.chatViewModes?{...e,chatViewMode:n.chatViewModes.value,onChatViewModeChange:n.chatViewModes.onChange,offeredViewModes:n.chatViewModes.offered}:e}):void 0,showInformation:!0,headerActions:t.jsxs(h,{display:"inline-flex",alignItems:"center",gap:2,children:[n.chatHeaderActions,D&&T?t.jsxs(t.Fragment,{children:[t.jsx(ci,{facts:An}),t.jsx(ui,{uid:ft||void 0,describe:e=>Je.described(e),context:zn})]}):null,jn.length>0?t.jsx(St,{slot:Ae.chatHeader,props:{workspace:n}}):null,t.jsx(us,{icon:G?ja:ka,"aria-label":G?"Exit full screen":"Enter full screen",variant:"invisible",size:"small",onClick:()=>{H(!1),m()},sx:V?{"@keyframes dla-fullscreen-hint":{"0%, 100%":{opacity:1},"50%":{opacity:.4}},"&&":{bg:`color-mix(in srgb, ${r.primary} 16%, transparent)`,boxShadow:`inset 0 0 0 1.5px ${r.primary}`,animation:`dla-fullscreen-hint ${vi}ms ease-in-out infinite`},"@media (prefers-reduced-motion: reduce)":{"&&":{animation:"none"}}}:void 0})]}),showInput:!1,onSendReady:K,notebookToolSurfacesId:I?void 0:n.surfaceId,showTurnFooter:C.showTokenUsage??u?.showTokenUsage??!0,onContextSnapshot:Et,onLoadingChange:He,renderMessageFooter:D&&T?(e,a)=>e.role==="user"?t.jsx(di,{facts:An,turn:a.turn,context:zn}):null:void 0,onSpeakingChange:Rt,onItemsChange:At,onDisplayItemsChange:It,enableStreaming:!0},Ht?.id)}),!Dn&&jn.length>0?t.jsx(h,{hidden:!0,children:t.jsx(St,{slot:Ae.chatHeader,props:{workspace:n}})}):null,Vn&&!nt?gt:null]})}),Yn=u?.suggestionLabels!==!1&&ct.length>0?t.jsx(h,{"aria-label":o.suggestedPrompts,display:"flex",flexWrap:"wrap",gap:2,px:2,pb:"6px",children:ct.map(e=>t.jsx(h,{as:"button",type:"button",title:e.message,disabled:L||Ze,onClick:()=>{ie(e.message)},appearance:"none",font:"inherit",fontSize:0,fontWeight:"semibold",lineHeight:1.25,px:"10px",py:"5px",width:ns,flex:`0 0 ${ns}px`,borderRadius:"999px",border:"1px solid",bg:"canvas.subtle",whiteSpace:"nowrap",sx:{borderColor:"border.default",color:"fg.default",cursor:"pointer","&:hover:not(:disabled)":{borderColor:"accent.fg",color:"accent.fg"},"&:disabled":{opacity:.5,cursor:"default"}},children:t.jsx(Ta,{title:e.title,maxWidth:"100%",sx:{minWidth:0},children:e.title})},e.title))}):null,qn=f?t.jsx(h,{flex:"0 0 auto",px:3,py:2,borderTop:"1px solid",borderColor:"border.default",bg:"canvas.subtle",fontSize:1,maxHeight:"40%",overflowY:"auto",children:f}):null;return t.jsxs(h,{ref:Oe,sx:{height:"100%",minHeight:0,display:"flex",flexDirection:"column",position:"relative",...G?{bg:"canvas.default"}:null,...G&&!Ke.current?{position:"fixed",top:U,right:0,bottom:0,left:0,height:"auto",zIndex:1e3}:null},children:[be?t.jsx(be.Component,{workspace:n,editors:Kn,hasEditor:!!I,transcript:Gn,prompt:nt?null:gt,chips:nt?null:Yn,picker:Wn,transient:qn}):t.jsxs(t.Fragment,{children:[_e&&!nt?t.jsxs(h,{flex:"0 0 auto",borderBottom:"1px solid",borderColor:"border.default",children:[gt,Yn]}):null,Wn,t.jsxs(h,{flex:"1 1 auto",minHeight:0,display:"flex",position:"relative",children:[Kn,Gn]}),qn,Vn||nt||_e?null:gt]}),Ft?t.jsx(h,{position:"absolute",inset:0,zIndex:5,bg:"canvas.default",display:"flex",flexDirection:"column",minHeight:0,children:t.jsx(Ya,{agentName:R?.name??M?.name,sandboxStillRuns:$,temporary:hn,onSignedIn:()=>Ra.getState().clear()})}):null]})}function Si({surfaces:n,active:o,onChange:r,workspace:i}){const d=[...n].sort((p,v)=>(p.order??100)-(v.order??100));return t.jsxs(h,{flex:"0 0 auto",display:"flex",alignItems:"center",gap:2,px:3,py:2,borderBottom:"1px solid",borderColor:"border.default",children:[t.jsx(z,{sx:{fontSize:0,color:"fg.muted"},children:"Beside the chat"}),t.jsxs(Xt,{"aria-label":"Editor beside the chat",size:"small",children:[t.jsx(Xt.Button,{selected:o===de,onClick:()=>r(de),children:"Chat"}),d.map(p=>{const v=ot(p,i),c=v?void 0:p.unavailableReason?.(i)??"Not available right now";return t.jsx(Xt.Button,{selected:o===p.surfaceId,"aria-disabled":!v,title:c??p.title,leadingIcon:p.icon,onClick:()=>{v&&r(p.surfaceId)},children:p.title},p.surfaceId)})]})]})}function tn({children:n}){return t.jsx(h,{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"fg.muted",fontSize:1,px:3,textAlign:"center",children:n})}export{ki as default};
@@ -3853,8 +3853,8 @@ ${lo}`;let Iu=MODULES.get(Ru);return Iu||(Iu=(async()=>{const Pu=await $u(Au,{cr
3853
3853
  ${Mu}`:ju,inputs:Mu,clear:Ou?[]:[DRAFT.path],loop:Lu()}:{refused:"Nothing to send: write a message first."}}}}const text=(Au,lo,$u)=>({id:Au,component:"Text",text:{path:lo},...$u?{variant:$u}:{}}),button=(Au,lo,$u,Ru=!1)=>[{id:Au,component:"Button",child:`${Au}-label`,...Ru?{variant:"primary"}:{},action:{event:{name:$u}}},{id:`${Au}-label`,component:"Text",text:lo}];function settingsForm(Au){const lo=pageOf(Au);return lo?pageForm(Au,lo):Au.interface.settings&&settingFields(Au.interface.settings).length?[{id:"settings",component:"Form",schema:Au.interface.settings,...Au.interface.settingsUi?{ui:Au.interface.settingsUi}:{},values:{path:"/inputs"}}]:[]}function pageForm(Au,lo){const $u=Au.interface.settings,Ru={...lo.inputs,type:"object",properties:{...$u?.properties,...lo.inputs.properties},required:[...$u?.required??[],...lo.inputs.required??[]]},Iu={...Au.interface.settingsUi,...lo.inputsUi},Pu=lo.outputs.flatMap(Ou=>[...Ou.title?[{id:`output-${Ou.name}-title`,component:"Text",text:Ou.title,variant:"h4"}]:[],{...Ou.props,id:`output-${Ou.name}`,component:Ou.component,[pageOutputShows(Ou.component,Au.interface.customComponents)??"text"]:{path:outputPath(Ou.name)}}]);return[{id:"inputs",component:"Form",schema:Ru,...Object.keys(Iu).length>0?{ui:Iu}:{},values:{path:"/inputs"}},...lo.live?[]:button("run-page","Run",PAGE_ACTION,!0),...Pu]}function defaultAppSurface(Au){const lo=appKindPaths(Au).inputs?settingsForm(Au):[],$u=[];switch(Au.kind){case"chat":$u.push(text("question","/question","h3"),text("answer","/answer"),text("status","/status","caption"),...lo);break;case"widget":if(pageOf(Au)){$u.push(...lo);break}$u.push(...lo,{id:"actions",component:"Row",children:["run","stop"]},...button("run","Run","run",!0),...button("stop","Stop","stop"),text("status","/status","caption"),text("output","/output"));break;case"worker":$u.push(text("goal","/goal","h3"),text("status","/status","caption"),text("activity","/activity","caption"),text("report","/report"));break}const Ru=new Set($u.flatMap(Iu=>[...Array.isArray(Iu.children)?Iu.children:[],Iu.child].filter(Pu=>typeof Pu=="string")));return[{id:"root",component:"Column",children:$u.map(Iu=>Iu.id).filter(Iu=>!Ru.has(Iu))},...$u]}function appPageMessages(Au,lo){const $u=surfaceComponents(Au);return[{version:"v0.9",createSurface:{surfaceId:APP_PAGE_SURFACE_ID,catalogId:lo}},{version:"v0.9",updateComponents:{surfaceId:APP_PAGE_SURFACE_ID,components:$u.length>0?$u:defaultAppSurface(Au)}},{version:"v0.9",updateDataModel:{surfaceId:APP_PAGE_SURFACE_ID,path:"/",value:appPageInitialData(Au)}}]}const LOOP_PAGE="loop.page";function streamEvents(Au){const lo=[];for(const $u of Au.split(`
3854
3854
 
3855
3855
  `)){const Ru=$u.split(`
3856
- `).filter(Iu=>Iu.startsWith("data:")).map(Iu=>Iu.slice(5).trim()).join("");if(Ru)try{lo.push(JSON.parse(Ru))}catch{}}return lo}function pageTurnOf(Au){let lo=null;for(const $u of streamEvents(Au)){if($u.type==="RUN_ERROR")return{refused:String($u.message??"Its page could not run.")};if($u.type==="CUSTOM"&&$u.name===LOOP_PAGE){const Ru=$u.value??{};lo={outputs:Ru.outputs??{},inputs:Ru.inputs??{}}}}return lo??{refused:"Its page showed nothing: its code answered no outputs."}}const base=Au=>`${Au.serverUrl.replace(/\/+$/,"")}/api/v1/apps/sessions`;async function posted(Au,lo,$u){const Ru=await(Au.fetcher??fetch)(lo,{method:"POST",headers:{"content-type":"application/json",...Au.token?{Authorization:`Bearer ${Au.token}`}:{}},body:JSON.stringify($u)});if(!Ru.ok){let Iu="";try{const Pu=await Ru.json();Iu=typeof Pu.detail=="string"?Pu.detail:""}catch{}throw new Error(Iu||`Its page was refused (${Ru.status}).`)}return Ru.text()}async function openPageSession(Au){const lo=await posted(Au,base(Au),{agent:Au.agentId});for(const $u of streamEvents(lo))if($u.type==="CUSTOM"&&$u.name==="loop.session"){const Ru=$u.value?.uid;if(typeof Ru=="string"&&Ru)return Ru}throw new Error("The runtime opened no session for its page.")}async function runPageIn(Au,lo,$u){try{const Ru=await posted(Au,`${base(Au)}/${encodeURIComponent(lo)}/page`,{inputs:$u});return pageTurnOf(Ru)}catch(Ru){return{refused:Ru instanceof Error?Ru.message:String(Ru)}}}function outputsData(Au){return Object.fromEntries(Object.entries(Au).map(([lo,$u])=>[`/outputs/${lo}`,$u]))}const PAGE_RUN_DELAY_MS=300,NO_TURN$6=signal$2({id:0,status:"idle"}),NO_CONVERSATION$2=signal$2([]);function componentsOnPage(Au){const lo=new Set;for(const $u of Au){const Ru=$u.updateComponents;for(const Iu of Ru?.components??[])lo.add(String(Iu.component))}return[...lo]}function blocksMissing(Au,lo){const $u=new Set(lo),Ru=Au.filter(Iu=>!$u.has(Iu));return Ru.length===0?null:`This page places ${Ru.join(", ")}, which no enabled plugin contributes: ${Ru.length===1?"it is":"they are"} drawn once the plugin that contributes ${Ru.length===1?"it":"them"} is on.`}function AppPage({app:Au,workspace:lo}){const $u=useContributions(LoopChatTurn),Ru=useSignalValue$1($u[0]?.value.turn??NO_TURN$6),Iu=useSignalValue$1($u[0]?.value.conversation??NO_CONVERSATION$2),Pu=reactExports.useMemo(()=>appPageMessages(Au,SURFACE_CATALOG_ID),[Au]),Ou=useContributions(LoopCanvasBlock),Mu=[...new Set(Ou.map(yd=>yd.value.id))].sort(),Du=Mu.join(","),Lu=useOwnComponents(),Bu=reactExports.useMemo(()=>{const yd=blocksMissing(componentsOnPage(Pu),Mu);if(yd)return{problem:yd};try{return{catalog:catalogOfBlocks(Mu,Lu)}}catch(wd){return{problem:wd instanceof Error?wd.message:String(wd)}}},[Pu,Du,Lu]),[ju,Fu]=reactExports.useState(null),zu=pageOf(Au),[Uu,Hu]=reactExports.useState({}),Vu=reactExports.useMemo(()=>({...appPageData(Au,Ru,Iu),...outputsData(Uu)}),[Au,Ru,Iu,Uu]),Gu=useIAMStore(yd=>yd.token)??"",Wu=useChatWords(),Ku=agentServerOf(lo.sandbox,lo.serverUrl),Ju=reactExports.useRef(null);Ju.current=Ku===void 0?null:{serverUrl:Ku,agentId:lo.agentId||Au.id,token:Gu||void 0};const Yu=reactExports.useRef("");Yu.current=Ku===void 0?noRuntimeSaid(lo.sandbox,Wu):"";const Xu=reactExports.useRef(null),ed=reactExports.useRef(!1),td=reactExports.useRef(null),nd=reactExports.useRef(""),od=reactExports.useRef(!0),sd=reactExports.useCallback(yd=>{td.current=yd,!ed.current&&(ed.current=!0,(async()=>{for(;td.current&&od.current;){const wd=td.current;td.current=null;const Ad=Ju.current;if(!Ad){Fu(Yu.current);continue}try{Xu.current??=openPageSession(Ad);const md=await runPageIn(Ad,await Xu.current,wd);if(!od.current)break;"refused"in md?Fu(md.refused):(Fu(null),Hu(md.outputs))}catch(md){Xu.current=null,od.current&&Fu(md instanceof Error?md.message:String(md))}}ed.current=!1})())},[]),ad=reactExports.useRef(null);reactExports.useEffect(()=>(od.current=!0,()=>{od.current=!1,ad.current?.()}),[]);const pd=reactExports.useCallback(yd=>{if(!zu?.live)return;ad.current?.();let wd;const Ad=dd=>{const bd=pageInputsOf(Au,dd),ld=JSON.stringify(bd);ld!==nd.current&&(clearTimeout(wd),wd=setTimeout(()=>{nd.current=ld,sd(bd)},PAGE_RUN_DELAY_MS))},md=yd.dataModel.subscribe("/inputs",Ad);Ad(md.value),ad.current=()=>{clearTimeout(wd),md.unsubscribe()}},[Au,zu?.live,sd]),gd=reactExports.useRef(lo);gd.current=lo;const Sd=reactExports.useRef(""),_d=reactExports.useCallback((yd,wd)=>{const Ad=appPageAction(Au,{name:yd.name,context:yd.context??{}},dd=>wd?.dataModel.get(dd),Sd.current),md=gd.current.viewControls;if("refused"in Ad){Fu(Ad.refused);return}if(Fu(null),"runPage"in Ad)sd(Ad.runPage);else if("stop"in Ad)md.stop?.();else if("newChat"in Ad)md.newChat?.();else{if(md.send){const dd=md.send(Ad.send,{loop:Ad.loop});if(dd){Fu(dd);return}}else if(Ad.loop.files){Fu("The conversation is not ready for a file yet: try again.");return}else gd.current.prompts.submit(Ad.send);Sd.current=Ad.inputs;for(const dd of Ad.clear)wd?.dataModel.set(dd,"")}},[Au,sd]);return jsxRuntimeExports.jsx(Box,{"data-testid":"app-page",height:"100%",minHeight:0,overflow:"auto",p:3,children:"problem"in Bu?jsxRuntimeExports.jsx(Box,{role:"status",color:"fg.muted",fontSize:1,children:Bu.problem}):jsxRuntimeExports.jsx(InlineSurface,{messages:Pu,data:Vu,onAction:_d,validationError:ju,catalog:Bu.catalog,...zu?{onSurface:pd}:{}},Du)})}const APP_PAGE_PLUGIN_NAME="@datalayer/loop-plugin-app-page";function defineAppPagePlugin(Au){function lo({workspace:Ru}){return jsxRuntimeExports.jsx(AppPage,{app:Au,workspace:Ru})}return{name:`${APP_PAGE_PLUGIN_NAME}-${Au.id}`,displayName:`${Au.name}: its page`,description:`The page of ${Au.name}, drawn beside its conversation.`,octicon:"browser",emoji:Au.emoji||void 0,contributes:[contribution(LoopEditorView,{surfaceId:APP_PAGE_SURFACE,title:Au.name,icon:BrowserIcon,order:-10,load:async()=>({default:lo})},{id:APP_PAGE_SURFACE,order:-10})]}}const APP_HOST_PAGE_VIEW="app-page";function defineAppHostPagePlugin(Au,lo){function $u({workspace:Iu}){return jsxRuntimeExports.jsx(lo,{app:Au,workspace:Iu})}return{name:`${APP_PAGE_PLUGIN_NAME}-${Au.id}`,displayName:`${Au.name}: its page`,description:`The page of ${Au.name}, drawn by its host.`,octicon:"browser",emoji:Au.emoji||void 0,contributes:[contribution(LoopViewType,{viewType:APP_HOST_PAGE_VIEW,title:Au.name,icon:BrowserIcon,order:-10,load:async()=>({default:$u})},{id:APP_HOST_PAGE_VIEW,order:-10})]}}const canvasBlocksPluginName=Au=>`@datalayer/loop-plugin-ui-${Au}`;function uiPluginBlocks(Au){return{name:canvasBlocksPluginName(Au.id),displayName:Au.name,description:`The blocks of ${Au.name} on the Canvas: ${Au.components.map(lo=>lo.name).join(", ")}.`,octicon:"apps",contributes:Au.components.map(lo=>contribution(LoopCanvasBlock,{id:lo.id,ui:Au.id,component:lo},{id:lo.id}))}}const CANVAS_BLOCK_PLUGINS=listUI().filter(Au=>Au.components.length>0).map(uiPluginBlocks),MANAGER_PLUGIN_NAME="@datalayer/reactor-manager",MANAGER_ACTIONS_SLOT="manager-actions",ManagerPluginSource=defineContributionPoint("manager.pluginSource");function usePluginRows(Au,lo){const $u=useReactorPlatform(),Ru=reactExports.useSyncExternalStore($u.subscribe,()=>$u.getRevision());return reactExports.useMemo(()=>$u.listPlugins().filter(Iu=>!lo.has(Iu)).map(Iu=>{const Pu=$u.getManifest(Iu);return{name:Iu,displayName:Pu?.displayName??Iu,description:Pu?.description,emoji:Pu?.emoji,version:Pu?.version,enabled:$u.isEnabled(Iu),disabledBy:Pu?.disabledBy,changeable:!Au.has(Iu),details:[{label:"Delivered by",values:Pu?.extension?[Pu.extension]:[]},{label:"Contributes to",values:Pu?.contributesTo??[]},{label:"Offers contribution points",values:Pu?.contributionPoints??[]},{label:"Requires backend plugins",values:Pu?.requiredBackendPlugins??[]},{label:"Uses if available",values:Pu?.optionalBackendPlugins??[]},{label:"Activates on",values:Pu?.activationEvents??[]}]}}),[$u,Ru,Au,lo])}function pluginMatches(Au,lo){if(!lo)return!0;const $u=lo.trim().toLowerCase();return[Au.name,Au.displayName,Au.description??""].join(" ").toLowerCase().includes($u)}const PluginHoverContext=reactExports.createContext(null);function usePluginHoverControl(){const[Au,lo]=reactExports.useState(null),$u=reactExports.useRef(void 0);return reactExports.useEffect(()=>()=>clearTimeout($u.current),[]),reactExports.useMemo(()=>({openName:Au,show:Ru=>{clearTimeout($u.current),lo(Ru)},hide:()=>{clearTimeout($u.current),$u.current=setTimeout(()=>lo(null),200)}}),[Au])}function useHoverControl(){const Au=reactExports.useContext(PluginHoverContext),lo=usePluginHoverControl();return Au??lo}function PluginDetails({row:Au}){const lo=(Au.details??[]).filter($u=>$u.values.length>0);return jsxRuntimeExports.jsxs(Box,{sx:{p:3,maxWidth:360,display:"grid",gap:2},children:[jsxRuntimeExports.jsxs(Box,{sx:{display:"flex",alignItems:"center",gap:2},children:[Au.emoji?jsxRuntimeExports.jsx(Text$3,{"aria-hidden":!0,children:Au.emoji}):null,jsxRuntimeExports.jsx(Text$3,{sx:{fontWeight:"semibold"},children:Au.displayName}),Au.version?jsxRuntimeExports.jsxs(Text$3,{sx:{fontSize:0,color:"fg.muted"},children:["v",Au.version]}):null]}),jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:"fg.muted",wordBreak:"break-all"},children:Au.name}),Au.description?jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0},children:Au.description}):null,lo.map($u=>jsxRuntimeExports.jsxs(Box,{sx:{display:"grid",gap:1},children:[jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,fontWeight:"semibold"},children:$u.label}),$u.values.map(Ru=>jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:"fg.muted",wordBreak:"break-all"},children:Ru},Ru))]},$u.label)),Au.disabledBy==="dependency"?jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:"attention.fg"},children:"Off because something it depends on is off. It comes back when that does."}):null,Au.changeable?null:jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:"attention.fg"},children:"This one cannot be switched off."})]})}const OVERLAY_TAKES_NO_FOCUS={preventFocusOnOpen:!0,sx:{pointerEvents:"none"},returnFocusRef:{current:null}};function PluginRowView({row:Au,size:lo,onToggle:$u}){const Ru=`plugin-name-${Au.name.replace(/[^a-zA-Z0-9]+/g,"-")}`,Iu=useHoverControl(),Pu=Iu.openName===Au.name,Ou=()=>Iu.show(Au.name),Mu=()=>Iu.hide();return jsxRuntimeExports.jsx(AnchoredOverlay,{open:Pu,onOpen:Ou,onClose:Mu,focusZoneSettings:{disabled:!0},focusTrapSettings:{disabled:!0},overlayProps:OVERLAY_TAKES_NO_FOCUS,side:"outside-right",renderAnchor:Du=>jsxRuntimeExports.jsxs(Box,{...Du,onMouseEnter:Ou,onMouseLeave:Mu,onFocus:Ou,onBlur:Mu,sx:{display:"flex",alignItems:"flex-start",gap:2,py:2,borderBottom:"1px solid",borderColor:"border.muted"},children:[jsxRuntimeExports.jsxs(Box,{sx:{minWidth:0,flex:1},children:[jsxRuntimeExports.jsxs(Box,{sx:{display:"flex",alignItems:"center",gap:1},children:[Au.emoji?jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:1},"aria-hidden":!0,children:Au.emoji}):null,jsxRuntimeExports.jsx(Text$3,{id:Ru,sx:{fontSize:1,fontWeight:"semibold",minWidth:0},children:jsxRuntimeExports.jsx(Truncate,{title:Au.name,maxWidth:"100%",inline:!0,children:Au.displayName})})]}),Au.description?jsxRuntimeExports.jsx(Text$3,{sx:{display:"block",fontSize:0,color:"fg.muted"},children:jsxRuntimeExports.jsx(Truncate,{title:Au.description,maxWidth:"100%",inline:!0,children:Au.description})}):null]}),jsxRuntimeExports.jsx(ToggleSwitch,{size:lo,checked:Au.enabled,disabled:!Au.changeable||Au.disabledBy==="dependency","aria-labelledby":Ru,onClick:()=>{Au.changeable&&Au.disabledBy!=="dependency"&&$u(Au.name,!Au.enabled)}})]}),children:jsxRuntimeExports.jsx(PluginDetails,{row:Au})})}function PluginList({plugins:Au,query:lo="",switchSize:$u="small",onToggle:Ru,emptyMessage:Iu}){const Pu=reactExports.useMemo(()=>Au.filter(Ou=>pluginMatches(Ou,lo)),[Au,lo]);return Pu.length===0?jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:"fg.muted"},children:Iu??`No plugin matches “${lo}”.`}):jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:Pu.map(Ou=>jsxRuntimeExports.jsx(PluginRowView,{row:Ou,size:$u,onToggle:Ru},Ou.name))})}function PluginsManagerView({protectedPlugins:Au,hiddenPlugins:lo,switchSize:$u,width:Ru,...Iu}){const Pu=useReactorPlatform(),Ou=Pu.getConfig(MANAGER_PLUGIN_NAME)??{},Mu=reactExports.useMemo(()=>new Set(Au??Ou.protected??[MANAGER_PLUGIN_NAME]),[Au,Ou.protected]),Du=reactExports.useMemo(()=>new Set(lo??Ou.hidden??[]),[lo,Ou.hidden]),Lu=usePluginHoverControl(),Bu=usePluginRows(Mu,Du),[ju,Fu]=reactExports.useState(""),zu=$u??Ou.switchSize??"small",Uu=useContributions(ManagerPluginSource),Hu=reactExports.useMemo(()=>[...Uu].map(Vu=>Vu.value).sort((Vu,Gu)=>(Vu.order??100)-(Gu.order??100)),[Uu]);return jsxRuntimeExports.jsx(PluginHoverContext.Provider,{value:Lu,children:jsxRuntimeExports.jsxs(Box,{sx:{display:"flex",flexDirection:"column",gap:3,width:Ru??Ou.width??"100%",maxWidth:"100%",minWidth:0},children:[jsxRuntimeExports.jsx(ReactorSlot,{slot:MANAGER_ACTIONS_SLOT,props:Iu}),jsxRuntimeExports.jsxs(Box,{children:[jsxRuntimeExports.jsx(Text$3,{as:"h2",sx:{fontSize:1,fontWeight:"semibold",display:"block",mb:2},children:Ou.title??"Plugins"}),jsxRuntimeExports.jsx(TextInput$1,{leadingVisual:SearchIcon,value:ju,onChange:Vu=>Fu(Vu.target.value),"aria-label":"Filter plugins",placeholder:"Filter…",block:!0,size:"small"})]}),jsxRuntimeExports.jsx(Box,{children:jsxRuntimeExports.jsx(PluginList,{plugins:Bu,query:ju,switchSize:zu,onToggle:(Vu,Gu)=>Gu?Pu.enable(Vu):Pu.disable(Vu)})}),Hu.map(Vu=>jsxRuntimeExports.jsxs(Box,{children:[jsxRuntimeExports.jsx(Text$3,{as:"h3",sx:{fontSize:1,fontWeight:"semibold",display:"block",mb:2},children:Vu.title}),jsxRuntimeExports.jsx(Vu.Component,{query:ju,switchSize:zu})]},Vu.title))]})})}const PLUGINS_PANEL_PLUGIN_NAME="@datalayer/loop-plugin-plugins-panel",SIDEBAR_WIDTH=420,REACTOR_GRAPH_PLUGIN_NAME="@datalayer/reactor-graph",PluginsPanelPlugin={name:PLUGINS_PANEL_PLUGIN_NAME,displayName:"Plugins panel",description:"Switch plugins on and off while the workspace runs.",octicon:"plug",emoji:"🔌",build:()=>({components:[{id:"plugins-panel",slot:LoopSlots.sidebar,order:900,Component:({workspace:Au})=>jsxRuntimeExports.jsx(PluginsManagerView,{protectedPlugins:[PLUGINS_PANEL_PLUGIN_NAME],hiddenPlugins:[REACTOR_GRAPH_PLUGIN_NAME],width:SIDEBAR_WIDTH,workspace:Au})}]})};function ViewSwitcher({views:Au,workspace:lo,compact:$u=!1}){return Au.length<2?null:jsxRuntimeExports.jsx(Box,{role:"tablist","aria-label":"Workspace views",display:"inline-flex",alignItems:"center",bg:"neutral.muted",borderRadius:"6px",p:"2px",gap:"1px",children:Au.map(Ru=>{const Iu=Ru.value,Pu=canOpenView(Iu,lo),Ou=lo.activeViewType===Iu.viewType,Mu=Iu.icon,Du=Pu?Iu.title:`${Iu.title} — ${Iu.unavailableReason?.(lo)??"unavailable"}`;return jsxRuntimeExports.jsx(Tooltip,{text:Du,direction:"n",children:jsxRuntimeExports.jsxs(Box,{as:"button",role:"tab","aria-selected":Ou,"aria-disabled":!Pu,onClick:()=>Pu&&lo.setActiveViewType(Iu.viewType),display:"inline-flex",alignItems:"center",gap:1,border:"none",borderRadius:"5px",px:2,py:"4px",fontSize:0,cursor:Pu?"pointer":"not-allowed",opacity:Pu?1:.5,bg:Ou?"canvas.default":"transparent",color:Ou?"fg.default":"fg.muted",boxShadow:Ou?"shadow.small":"none",children:[Mu?jsxRuntimeExports.jsx(Mu,{size:14}):null,$u&&Mu?null:Iu.title]})},Iu.viewType)})})}const paneOpenKeyframes=Au=>Au==="left"?"loopPaneOpenLeft":"loopPaneOpenRight",paneOpenAnimation=Au=>`${paneOpenKeyframes(Au)} var(--theme-motion-pane, 0ms) var(--theme-motion-easing, ease) both`;function paneOpening(Au){const lo="12px";return{animation:paneOpenAnimation(Au),[`@keyframes ${paneOpenKeyframes(Au)}`]:{from:{opacity:0,transform:`translateX(${lo})`},to:{opacity:1,transform:"none"}},"@media (prefers-reduced-motion: reduce)":{animation:"none"}}}function railItemsOf(Au){return Au.map(lo=>({id:lo.id,label:lo.rail?.label??lo.id,icon:lo.rail?.icon??SidebarExpandIcon}))}function railChoiceAfter(Au,lo){return Au===lo?null:lo}const RAIL_WIDTH=48;function SidebarRail({components:Au,props:lo,width:$u}){const Ru=railItemsOf(Au),[Iu,Pu]=reactExports.useState(Ru[0]?.id??null),Ou=Ru.some(Mu=>Mu.id===Iu)?Iu:null;return jsxRuntimeExports.jsxs(Box,{as:"aside","data-loop-rail-sidebar":"",flex:"0 0 auto",display:"flex",minHeight:0,children:[jsxRuntimeExports.jsx(Box,{"data-loop-rail-panel":Ou??void 0,display:Ou?"block":"none",width:`${$u}px`,minWidth:0,borderLeft:"var(--theme-hairline, 1px) solid",borderColor:"border.default",overflowY:"auto",px:3,py:3,children:Au.map(Mu=>{const{Component:Du}=Mu,Lu=Mu.id===Ou;return jsxRuntimeExports.jsx(Box,{id:`loop-rail-panel-${Mu.id}`,role:"region","aria-label":railItemsOf([Mu])[0].label,hidden:!Lu,sx:Lu?paneOpening("right"):void 0,children:jsxRuntimeExports.jsx(Du,{...lo})},Mu.id)})}),jsxRuntimeExports.jsx(Box,{as:"nav","aria-label":"Panels",width:`${RAIL_WIDTH}px`,flex:`0 0 ${RAIL_WIDTH}px`,display:"flex",flexDirection:"column",alignItems:"center",gap:1,py:2,borderLeft:"var(--theme-hairline, 1px) solid",borderColor:"border.default",children:Ru.map(Mu=>{const Du=Mu.icon,Lu=Mu.id===Ou;return jsxRuntimeExports.jsx(Box,{as:"button",type:"button","data-loop-rail-item":Mu.id,"aria-label":Mu.label,title:Mu.label,"aria-pressed":Lu,"aria-controls":`loop-rail-panel-${Mu.id}`,onClick:()=>Pu(railChoiceAfter(Ou,Mu.id)),width:32,height:32,display:"inline-flex",alignItems:"center",justifyContent:"center",p:0,border:"none",borderRadius:2,cursor:"pointer",color:Lu?"fg.default":"fg.muted",bg:Lu?"neutral.muted":"transparent",hover:{color:"fg.default",bg:"neutral.subtle"},focusVisible:{outline:"2px solid",outlineColor:"var(--focus-outlineColor, #0969da)",outlineOffset:"1px"},children:jsxRuntimeExports.jsx(Du,{size:16})},Mu.id)})})]})}function buildLoopReactor(Au){return buildReactorFromPlugins(Au)}function LoopWorkspace(Au){const{serverUrl:lo,agentId:$u,conversationId:Ru,model:Iu,sandbox:Pu={state:"idle"},extensions:Ou=[],reactor:Mu,manageReactor:Du=!0,initialViewType:Lu,onSend:Bu,layout:ju="page",showViewSelector:Fu=!0,showHeader:zu=!0,chatHeaderActions:Uu,chatViewModes:Hu,headerActions:Vu,headerContainer:Gu,sidebarRail:Wu=!1}=Au,Ku=reactExports.useMemo(()=>Mu??buildLoopReactor(Ou),[Mu]);return useReactor(Ku,{autoStart:Du}),jsxRuntimeExports.jsx(WorkspaceBody,{serverUrl:lo,agentId:$u,conversationId:Ru,model:Iu,initialSandbox:Pu,initialViewType:Lu,onSend:Bu,layout:ju,showViewSelector:Fu,showHeader:zu,chatHeaderActions:Uu,chatViewModes:Hu,headerActions:Vu,headerContainer:Gu,sidebarRail:Wu})}function WorkspaceBody({serverUrl:Au,agentId:lo,conversationId:$u,model:Ru,initialSandbox:Iu,initialViewType:Pu,onSend:Ou,layout:Mu="page",showViewSelector:Du=!0,showHeader:Lu=!0,chatHeaderActions:Bu,chatViewModes:ju,headerActions:Fu,headerContainer:zu,sidebarRail:Uu=!1}){const[Hu,Vu]=reactExports.useState(lo),Gu=reactExports.useRef(loopSurfaceId($u??`session-${Date.now().toString(36)}`));reactExports.useEffect(()=>{Vu(lo)},[lo]);const[Wu,Ku]=reactExports.useState(void 0),Ju=reactExports.useCallback(ld=>{Ku(ud=>ud===ld?ud:ld)},[]),[Yu,Xu]=reactExports.useState(Pu??""),[ed,td]=reactExports.useState(Iu),[nd]=reactExports.useState(createPromptChannel),[od,sd]=reactExports.useState({}),ad=reactExports.useCallback(ld=>{sd(ld??{})},[]),pd=useContributions(LoopViewType),gd=useContributions(LoopCommand),Sd=useSlotComponents(LoopSlots.sidebar),_d=reactExports.useRef(gd),yd=reactExports.useRef(null),wd=Mu==="panel",Ad=reactExports.useCallback(async ld=>{const ud=parseCommand(ld);if(!ud)return Ou?.(ld,yd.current),nd.submit(ld)||Ou?{handled:!0}:{handled:!1,reason:"Nothing is listening for prompts in this view yet."};const hd=_d.current.find(Ed=>Ed.value.name===ud.name||(Ed.value.aliases??[]).includes(ud.name));if(!hd)return{handled:!1,command:ud.name,reason:`Unknown command: /${ud.name}. Type /help to see what there is.`};const vd=await hd.value.run({workspace:yd.current,argv:ud.argv});return vd?.prompt&&(Ou?.(vd.prompt,yd.current),nd.submit(vd.prompt)),{handled:!0,command:ud.name,result:vd??void 0}},[Ou,nd]),md=reactExports.useMemo(()=>({serverUrl:Au,agentId:Hu,surfaceId:Gu.current,setAgentId:Vu,conversationId:$u,thread:Wu,setThread:Ju,model:Ru,sandbox:ed,setSandbox:td,activeViewType:Yu,setActiveViewType:Xu,prompts:nd,submit:Ad,viewControls:od,setViewControls:ad,chatHeaderActions:Bu,chatViewModes:ju}),[Au,Hu,$u,Wu,Ru,ed,Yu,nd,Ad,od,ad,Bu,ju]);yd.current=md,_d.current=gd;const dd=reactExports.useMemo(()=>Yu||(pd.find(ud=>canOpenView(ud.value,md))?.value.viewType??""),[Yu,pd,md]);useReactorEvent(dd?onView(dd):void 0);const bd=jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[Fu,jsxRuntimeExports.jsx(ReactorSlot,{slot:LoopSlots.header,props:{workspace:md}}),Du?jsxRuntimeExports.jsx(ViewSwitcher,{views:pd,workspace:md,compact:wd}):null]});return jsxRuntimeExports.jsxs(Box,{"data-loop-workspace":"",display:"flex",flexDirection:"column",height:"100%",minHeight:0,position:"relative",bg:"canvas.default",color:"fg.default",children:[Lu&&zu?reactDomExports.createPortal(jsxRuntimeExports.jsx(Box,{display:"flex",alignItems:"center",flexWrap:"wrap",gap:2,children:bd}),zu):null,Lu&&zu===void 0?jsxRuntimeExports.jsx(Box,{as:"header",display:"flex",alignItems:"center",justifyContent:wd?"flex-start":"space-between",flexWrap:"wrap",gap:2,px:wd?2:3,py:2,borderBottom:"1px solid",borderColor:"border.default",flex:"0 0 auto",children:bd}):null,jsxRuntimeExports.jsxs(Box,{flex:"1 1 auto",minHeight:0,display:"flex",children:[jsxRuntimeExports.jsx(Box,{flex:"1 1 auto",minWidth:0,minHeight:0,position:"relative",children:jsxRuntimeExports.jsx(ReactorViewHost,{point:LoopViewType,active:dd,props:{viewType:dd,workspace:md},fallback:jsxRuntimeExports.jsx(Centered,{children:"Loading…"}),empty:jsxRuntimeExports.jsx(Centered,{children:"No view is available yet."}),errorFallback:ld=>jsxRuntimeExports.jsxs(Centered,{children:["This view failed to load: ",ld.message]})})}),Sd.length>0&&Uu&&!wd?jsxRuntimeExports.jsx(SidebarRail,{components:Sd,props:{workspace:md},width:SIDEBAR_WIDTH}):Sd.length>0?jsxRuntimeExports.jsx(Box,{as:"aside",flex:"0 0 auto",width:wd?"100%":`${SIDEBAR_WIDTH}px`,minWidth:0,borderLeft:wd?"none":"1px solid",borderTop:wd?"1px solid":"none",borderColor:"border.default",bg:"canvas.subtle",overflowY:"auto",px:3,py:3,children:jsxRuntimeExports.jsx(ReactorSlot,{slot:LoopSlots.sidebar,props:{workspace:md}})}):null]}),jsxRuntimeExports.jsxs(Box,{flex:"0 0 auto",children:[jsxRuntimeExports.jsx(ReactorSlot,{slot:LoopSlots.footer,props:{workspace:md}}),jsxRuntimeExports.jsx(ReactorSlot,{slot:LoopSlots.status,props:{workspace:md}})]}),jsxRuntimeExports.jsx(ReactorSlot,{slot:LoopSlots.root,props:{workspace:md}})]})}function Centered({children:Au}){return jsxRuntimeExports.jsx(Box,{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"fg.muted",fontSize:1,px:3,textAlign:"center",children:Au})}function resolveTopOffset(Au){if(typeof Au=="number")return Au;if(!Au||typeof document>"u")return 0;const lo=document.querySelector(Au);return lo?Math.max(0,Math.round(lo.getBoundingClientRect().bottom)):0}function fullScreenNode(Au){return Au?.closest("[data-loop-fullscreen-root]")??Au?.closest("[data-loop-workspace]")??Au}function useWorkspaceFullScreen(Au,lo={}){const{forceOverlay:$u=!1,paintOverlay:Ru=!1,topOffset:Iu=0}=lo,[Pu,Ou]=reactExports.useState(!1),Mu=reactExports.useRef(!1);reactExports.useEffect(()=>{const ju=()=>{if(!Mu.current)return;const Fu=!!document.fullscreenElement&&!!Au.current&&document.fullscreenElement.contains(Au.current);Ou(Fu),Fu||(Mu.current=!1)};return document.addEventListener("fullscreenchange",ju),()=>document.removeEventListener("fullscreenchange",ju)},[Au]);const Du=reactExports.useCallback(()=>{const ju=fullScreenNode(Au.current);if(Pu){Mu.current&&document.fullscreenElement?document.exitFullscreen():Ou(!1);return}if($u||Ru||!ju?.requestFullscreen){Ou(!0);return}Mu.current=!0,ju.requestFullscreen().then(()=>Ou(!0),()=>{Mu.current=!1,Ou(!0)})},[Au,Pu,$u,Ru]),[Lu,Bu]=reactExports.useState(0);return reactExports.useEffect(()=>{if(!Pu||Mu.current){Bu(0);return}const ju=()=>Bu(resolveTopOffset(Iu));return ju(),window.addEventListener("resize",ju),()=>window.removeEventListener("resize",ju)},[Pu,Iu]),reactExports.useEffect(()=>{if(!Ru||!Pu||Mu.current)return;const ju=fullScreenNode(Au.current);if(!ju)return;const Fu=ju.getAttribute("style");return ju.style.position="fixed",ju.style.top=`${Lu}px`,ju.style.right="0",ju.style.bottom="0",ju.style.left="0",ju.style.height="auto",ju.style.zIndex="1000",()=>{Fu===null?ju.removeAttribute("style"):ju.setAttribute("style",Fu)}},[Ru,Pu,Au,Lu]),reactExports.useEffect(()=>{if(!Pu||Mu.current)return;const ju=Fu=>{Fu.key==="Escape"&&!Fu.defaultPrevented&&Ou(!1)};return window.addEventListener("keydown",ju),()=>window.removeEventListener("keydown",ju)},[Pu]),{fullScreen:Pu,usingApi:Mu,toggle:Du,topOffsetPx:Lu}}function messageText(Au){const lo=Au.content;return typeof lo=="string"?lo:lo.map($u=>typeof $u=="string"?$u:$u.text??"").join("")}const isToolCall=Au=>Au.type==="tool-call";function conversationOf(Au){const lo=[];for(const $u of Au){if(isToolCall($u)){lo.push({role:"tool",name:$u.toolName,args:$u.args??{},...$u.result===void 0?{}:{result:$u.result}});continue}if($u.role!=="user"&&$u.role!=="assistant")continue;const Ru=messageText($u);Ru.trim()&&lo.push({role:$u.role,text:Ru})}return lo}const sameConversation=(Au,lo)=>Au.length===lo.length&&Au.every(($u,Ru)=>JSON.stringify($u)===JSON.stringify(lo[Ru])),IDLE={id:0,status:"idle"};function createTurnFeed(){const Au=signal$2(IDLE),lo=signal$2([]),$u=signal$2("idle");return{turn:Au,conversation:lo,presence:$u,setPresence:Ru=>{$u.value!==Ru&&($u.value=Ru)},items:Ru=>{const Iu=conversationOf(Ru);sameConversation(lo.value,Iu)||(lo.value=Iu)},begin:(Ru,Iu)=>{Au.value={id:Au.value.id+1,user:Ru,...Iu?{thread:Iu}:{},status:"thinking",usage:Au.value.usage}},assistant:Ru=>{const Iu=Au.value;Iu.status==="idle"||Iu.assistant===Ru||(Au.value={...Iu,assistant:Ru,status:Iu.status==="done"||Iu.status==="error"?Iu.status:Ru?"streaming":Iu.status})},usage:Ru=>{const Iu=Au.value;Iu.usage!==Ru&&(Au.value={...Iu,usage:Ru})},activity:Ru=>{const Iu=Au.value;Iu.status==="idle"||Iu.activity===Ru||(Au.value={...Iu,activity:Ru})},end:(Ru="done")=>{const Iu=Au.value;Iu.status!=="idle"&&(Au.value={...Iu,status:Ru,activity:void 0})}}}const TURN_WRITERS=Symbol.for("loop.chat.turn.writers");function feedWriters(Au){return{[TURN_WRITERS]:Au}}function turnWritersOf(Au){return Au?.[TURN_WRITERS]}const sessionFileName=Au=>`${Au.uid}.session.jsonl`,SESSION_ACTION_WORDS={switchAgent:"Switch agent…",switchTitle:Au=>`Switch ${Au} to`,noPicker:"Switching the agent needs a picker this page has not: use `loop sessions swap`.",noAgents:"No other agent of the catalogue runs on a harness.",cloneFromHere:"Clone from here",cloned:(Au,lo)=>`Cloned from turn ${Au} as ${lo}: opened here, the source untouched.`,export:"Export",exported:(Au,lo,$u)=>`Exported ${Au} turn${Au===1?"":"s"}, ${lo} redaction${lo===1?"":"s"} → ${$u}.`,import:"Import…",noFilePicker:"Importing a session needs a file picker this page has not: use `loop sessions import`.",imported:(Au,lo,$u)=>`Imported as ${Au} (${lo} turn${lo===1?"":"s"}, ${$u} redaction${$u===1?"":"s"}): opened here.`,resume:"Resume",resumed:Au=>`Resumed ${Au}.`};function agentChoices(Au){const lo=listAgentspecs();return listHarnesses().filter($u=>$u.id!=="custom"&&$u.enabled).flatMap($u=>{const Ru=lo.find(Iu=>Iu.harness===$u.id);return!Ru||Ru.id===Au.agent?[]:[{id:Ru.id,label:`${Ru.name} (${$u.name})`,description:$u.description}]})}const spokenAs=(Au,lo)=>(lo?listHarnesses().find(Ru=>Ru.id===lo):void 0)?.name??(lo||Au);function swapSentence(Au,lo){const $u=spokenAs(Au.agent,Au.harness),Ru=lo.label.replace(/\s*\(.*\)$/,"");return`This conversation was with ${$u} until turn ${Au.turns}; from here it is with ${Ru}. What was said stays.`}const idle=Au=>Au.state==="open"&&Au.turn==="idle";function redactionsOf(Au){const lo=Au.split(`
3857
- `)[0]??"";try{return Number(JSON.parse(lo).redactions??0)||0}catch{return 0}}const SWITCH_AGENT={id:"switch-agent",label:SESSION_ACTION_WORDS.switchAgent,order:10,when:idle,run:async(Au,lo)=>{if(!lo.choose){lo.say(SESSION_ACTION_WORDS.noPicker);return}const $u=agentChoices(Au);if($u.length===0){lo.say(SESSION_ACTION_WORDS.noAgents);return}const Ru=await lo.choose({title:SESSION_ACTION_WORDS.switchTitle(Au.agent),options:$u,says:async Pu=>{const Ou=$u.find(Mu=>Mu.id===Pu);return Ou?swapSentence(Au,Ou):""}});if(!Ru)return;const Iu=await lo.client.swap(Au.uid,Ru);lo.say(String(Iu.said??`Swapped to ${Ru}.`))}},CLONE_FROM_HERE={id:"clone-from-here",label:SESSION_ACTION_WORDS.cloneFromHere,order:20,placement:"both",when:Au=>Au.turns>0,run:async(Au,lo)=>{const $u=lo.atTurn??Au.turns,Ru=await lo.client.clone(Au.uid,{upToTurn:$u}),Iu=String(Ru.uid??"");if(!Iu)throw new Error(`The runtime cloned session ${Au.uid} and named no new session.`);lo.say(SESSION_ACTION_WORDS.cloned($u,Iu)),lo.openThread?.(Iu)}},EXPORT={id:"export",label:SESSION_ACTION_WORDS.export,order:30,when:Au=>Au.turns>0,run:async(Au,lo)=>{const $u=await lo.client.exportFile(Au.uid),Ru=sessionFileName(Au);lo.download?.(Ru,$u,"application/x-ndjson"),lo.say(SESSION_ACTION_WORDS.exported(Au.turns,redactionsOf($u),Ru))}},IMPORT={id:"import",label:SESSION_ACTION_WORDS.import,order:35,when:()=>!0,run:async(Au,lo)=>{if(!lo.pickFile){lo.say(SESSION_ACTION_WORDS.noFilePicker);return}const $u=await lo.pickFile(".jsonl,application/x-ndjson");if(!$u)return;const Ru=await lo.client.importFile($u),Iu=String(Ru.uid??"");if(!Iu)throw new Error("The runtime imported the file and named no session.");lo.say(SESSION_ACTION_WORDS.imported(Iu,Number(Ru.turns??0)||0,Number(Ru.redactions??0)||0)),lo.openThread?.(Iu)}},RESUME={id:"resume",label:SESSION_ACTION_WORDS.resume,order:40,divider:!0,when:Au=>Au.state==="paused",run:async(Au,lo)=>{await lo.client.resume(Au.uid,Au.agent,{onEvent:()=>{}}),lo.say(SESSION_ACTION_WORDS.resumed(Au.uid)),lo.openThread?.(Au.uid)}},CHAT_SESSION_ACTIONS=[SWITCH_AGENT,CLONE_FROM_HERE,EXPORT,IMPORT,RESUME];function agentAction(Au,lo){const{prompt:$u,...Ru}=lo;return{...Ru,type:"button",group:"agent",onClick:()=>Au.workspace.prompts.submit($u)}}const CHAT_PLUGIN_NAME="@datalayer/loop-plugin-chat",ChatPlugin={name:CHAT_PLUGIN_NAME,config:{placeholder:"",defaultSurface:"notebook",showSurfaceSelector:!0,hideHeader:!1,headerButtons:{newChat:!1,clear:!1},hidePrompt:!1,promptPlacement:"bottom",autoFocusPrompt:!0,suggestionLabels:!0,fullScreenTopOffset:0},displayName:"Chat",description:"The conversation, the prompt, and the point editors plug into.",octicon:"comment-discussion",emoji:"💬",contributionPoints:[LoopAgentGate,LoopFrontendTool,LoopChatComposer,LoopChatHeader,LoopChatSuggestion,LoopChatExtras,LoopChatTurn],build:Au=>{const lo=createTurnFeed();return Au.contribute(LoopChatTurn,{id:"chat-turn",turn:lo.turn,conversation:lo.conversation,presence:lo.presence,...feedWriters(lo)},{id:"chat-turn"}),{}},contributes:[...CHAT_SESSION_ACTIONS.map(Au=>contribution(LoopSessionAction,Au,{id:Au.id,order:Au.order})),contribution(LoopViewType,{viewType:"chat",title:"Chat",icon:CommentDiscussionIcon,order:0,load:()=>__vitePreload(()=>import("./chunks/ChatView-LzqHHAEe.js"),[],import.meta.url)},{id:"chat",order:0}),contribution(LoopCommand,{name:"chat",description:"Show the conversation",group:"Session",keybinding:"Mod+Alt+K",run:async({workspace:Au})=>{Au.setActiveViewType("chat")}},{id:"chat"}),contribution(LoopNotebookToolbarItem,{items:Au=>[agentAction(Au,{key:"loop-compact",ariaLabel:"Compact this notebook",title:"Ask @NotebookCompactor to shorten it without changing results",icon:FoldIcon,order:200,prompt:"@NotebookCompactor compact this notebook without changing what it computes."}),agentAction(Au,{key:"loop-reproduce",ariaLabel:"Check reproducibility",title:"Ask @NotebookReproducer to run it on a fresh sandbox",icon:SyncIcon,order:201,prompt:"@NotebookReproducer run this notebook top to bottom on a fresh sandbox and report what does not reproduce."})]},{id:"agent-actions",order:200}),contribution(LoopDocumentToolbarItem,{items:Au=>[agentAction(Au,{key:"loop-summarise",ariaLabel:"Summarise this document",title:"Ask the agent for a summary of what this document says",icon:SparkleFillIcon,order:200,prompt:"Summarise this document in a short paragraph."})]},{id:"agent-actions",order:200})]};function WorkspaceFullScreenAction(){const Au=reactExports.useRef(null),$u=useReactorPlatform().getConfig(CHAT_PLUGIN_NAME)?.fullScreenTopOffset??0,{fullScreen:Ru,toggle:Iu}=useWorkspaceFullScreen(Au,{paintOverlay:!!$u,topOffset:$u});return jsxRuntimeExports.jsx(IconButton,{ref:Au,icon:Ru?ScreenNormalIcon:ScreenFullIcon,"aria-label":Ru?"Exit full screen":"Enter full screen",variant:"invisible",size:"small",sx:{order:2},onClick:Iu})}const THEME_PLUGIN_NAME="@datalayer/primer-theme",TOGGLE_COLOR_MODE_COMMAND="theme.toggleColorMode",ThemePlugin={name:THEME_PLUGIN_NAME,displayName:"Theme",description:"Keeps Primer portals in the application’s color mode, and toggles it.",octicon:"sun",emoji:"🌗",commands:[{id:TOGGLE_COLOR_MODE_COMMAND,name:"Toggle the color mode",description:"Switch between light and dark",emoji:"🌗",category:"Appearance",keybinding:"Mod+Alt+C",execute:()=>{const Au=useThemeStore.getState(),lo=Au.colorMode==="auto"?typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light":Au.colorMode;Au.setColorMode(lo==="dark"?"light":"dark")}}],register:()=>{if(typeof document>"u")return;setupPrimerPortals(useThemeStore.getState().colorMode);const Au=useThemeStore.subscribe((Ru,Iu)=>{Ru.colorMode!==Iu.colorMode&&setupPrimerPortals(Ru.colorMode)}),lo=window.matchMedia("(prefers-color-scheme: dark)"),$u=()=>{useThemeStore.getState().colorMode==="auto"&&setupPrimerPortals("auto")};return lo.addEventListener("change",$u),()=>{Au(),lo.removeEventListener("change",$u)}}},pageLayoutPanelOpen=signal$2(!1),pageLayoutSheet=signal$2("page"),pageLayoutActivity=signal$2(void 0);function openPagePanel(){pageLayoutPanelOpen.value=!0}const PAGE_SHEET_WIDTH=920,PAGE_PANEL_WIDTH=400,PAGE_SIZE_FORMATS={letter:{width:816,height:1056},a4:{width:794,height:1123}};function resolvePageSize(Au,lo=PAGE_SHEET_WIDTH){const $u=Au?.format&&Au.format!=="free"?PAGE_SIZE_FORMATS[Au.format]:void 0;return{width:Au?.width??$u?.width??lo,height:Au?.height??$u?.height}}const CANVAS_PX=[2,3,4];function ActivityLine({label:Au}){return jsxRuntimeExports.jsxs(Box$1,{"data-page-activity":"",role:"status",sx:{position:"sticky",top:0,zIndex:2,alignSelf:"flex-start",display:"inline-flex",alignItems:"center",gap:2,px:2,py:"4px",borderRadius:"999px",border:"1px solid",borderColor:"accent.muted",bg:"accent.subtle",color:"accent.fg",fontSize:0,fontWeight:"semibold",whiteSpace:"nowrap",boxShadow:"0 4px 12px -6px rgba(0,0,0,0.3)"},children:[jsxRuntimeExports.jsx(Box$1,{as:"span","aria-hidden":"true",sx:{width:7,height:7,borderRadius:"50%",bg:"accent.fg",animation:"page-activity-dot 1.1s ease-in-out infinite","@keyframes page-activity-dot":{"0%, 100%":{opacity:1},"50%":{opacity:.3}}}}),jsxRuntimeExports.jsx(Text$3,{children:Au})]})}function panelOpening(Au){const lo=Au==="left"?"pagePanelOpenLeft":"pagePanelOpenRight";return{animation:`${lo} var(--theme-motion-pane, 0ms) var(--theme-motion-easing, ease) both`,[`@keyframes ${lo}`]:{from:{opacity:0,transform:`translateX(${Au==="left"?"-12px":"12px"})`},to:{opacity:1,transform:"none"}},"@media (prefers-reduced-motion: reduce)":{animation:"none"}}}function PageLayout({page:Au,hasPage:lo=Au!=null,panel:$u,band:Ru,chips:Iu,picker:Pu,transient:Ou,activity:Mu,bandMode:Du="docked",panelMode:Lu="docked",panelSide:Bu="right",sheetWidth:ju=PAGE_SHEET_WIDTH,pageSize:Fu,panelWidth:zu=PAGE_PANEL_WIDTH}){const Uu=Du==="panel",Hu=Ru!=null,{width:Vu,height:Gu}=resolvePageSize(Fu,ju),Ku=useSignalValue$1(pageLayoutPanelOpen)||Uu&&Hu,Ju=useSignalValue$1(pageLayoutActivity),Yu=Mu??Ju,Xu=lo?"page":"panel";return reactExports.useEffect(()=>{pageLayoutSheet.value=Xu},[Xu]),jsxRuntimeExports.jsxs(Box$1,{"data-page-layout":"",sx:{position:"relative",flex:"1 1 auto",minHeight:0,display:"flex",flexDirection:"column"},children:[Pu,jsxRuntimeExports.jsxs(Box$1,{sx:{flex:"1 1 auto",minHeight:0,display:"flex",bg:"canvas.inset"},children:[jsxRuntimeExports.jsxs(Box$1,{sx:{flex:"1 1 auto",minWidth:0,minHeight:0,display:"flex",flexDirection:"column"},children:[Ru&&Du==="docked"?jsxRuntimeExports.jsx(Box$1,{"data-page-band":"","data-page-prompt-dock":"",sx:{flex:"0 0 auto",display:"flex",justifyContent:"center",px:CANVAS_PX,bg:"canvas.subtle",borderBottom:"1px solid",borderColor:"border.default"},children:jsxRuntimeExports.jsx(Box$1,{sx:{width:"100%",maxWidth:Vu,minWidth:0},children:Ru})}):null,jsxRuntimeExports.jsxs(Box$1,{"data-page-canvas":"",sx:{flex:"1 1 auto",minWidth:0,minHeight:0,overflowY:lo?"auto":"hidden",overflowX:"hidden",display:"flex",flexDirection:"column",alignItems:"center",pt:3,pb:6,px:CANVAS_PX},children:[Ru&&Iu&&!Uu?jsxRuntimeExports.jsx(Box$1,{sx:{width:"100%",maxWidth:Vu,mb:3,display:"flex",justifyContent:"center","& > *":{justifyContent:"center"}},children:Iu}):null,Yu?jsxRuntimeExports.jsx(Box$1,{sx:{width:"100%",maxWidth:Vu,display:"flex",justifyContent:"flex-end",mb:2},children:jsxRuntimeExports.jsx(ActivityLine,{label:Yu})}):null,jsxRuntimeExports.jsx(Sheet,{"data-page-sheet":"",sx:{width:"100%",maxWidth:Vu,flex:lo?"1 0 auto":"1 1 auto",px:lo?[3,4,"56px"]:[2,3,4],py:lo?[3,4,4]:2,position:"relative",display:"flex",minHeight:lo?Gu??480:0,"& > *":{flex:"1 1 auto",minWidth:0}},children:lo?Au:$u}),lo||!Au?null:jsxRuntimeExports.jsx(Box$1,{"aria-hidden":"true",sx:{position:"absolute",inset:0,visibility:"hidden",pointerEvents:"none",zIndex:-1,display:"flex"},children:Au})]})]}),!lo||!$u?null:jsxRuntimeExports.jsxs(Box$1,{"data-page-panel":Ku?"":void 0,"data-page-panel-mode":Lu,"aria-hidden":Ku?void 0:"true",sx:{minWidth:0,minHeight:0,display:"flex",flexDirection:"column",bg:"canvas.default",borderColor:"border.default",...Ku?Lu==="docked"?{flex:`0 0 ${zu}px`,maxWidth:"45%",order:Bu==="left"?-1:void 0,[Bu==="left"?"borderRight":"borderLeft"]:"1px solid",zIndex:1}:Lu==="overlay"?{position:"absolute",top:0,bottom:0,[Bu]:0,width:zu,maxWidth:"85%",[Bu==="left"?"borderRight":"borderLeft"]:"1px solid",boxShadow:"shadow.large",zIndex:5}:{position:"absolute",[Bu]:16,bottom:16,width:zu,maxWidth:"calc(100% - 32px)",height:"min(70%, 560px)",border:"1px solid",borderRadius:2,boxShadow:"shadow.large",overflow:"hidden",zIndex:5}:{position:"absolute",inset:0,visibility:"hidden",pointerEvents:"none",overflow:"visible"}},children:[jsxRuntimeExports.jsx(Box$1,{sx:{flex:"1 1 auto",minHeight:0,display:"flex",flexDirection:"column","& > *":{flex:"1 1 auto",minHeight:0},...Ku?panelOpening(Bu):null},children:$u}),Hu&&Du!=="docked"?jsxRuntimeExports.jsxs(Box$1,{"data-page-panel-band":Uu?"":void 0,sx:Uu?{flex:"0 0 auto",borderTop:"1px solid",borderColor:"border.default",visibility:"visible",pointerEvents:"auto","& > *":{justifyContent:"center"}}:{position:"absolute",inset:0,visibility:"visible",pointerEvents:"none","& > *":{pointerEvents:"auto"}},children:[Uu?Iu:null,Ru]}):null]})]}),Ou]})}function PagePanelToggle({panelName:Au="panel",icon:lo=SidebarExpandIcon,sx:$u}){const Ru=useSignalValue$1(pageLayoutPanelOpen);return useSignalValue$1(pageLayoutSheet)==="panel"?null:jsxRuntimeExports.jsx(IconButton,{icon:lo,size:"small",variant:Ru?"default":"invisible","aria-label":Ru?`Hide the ${Au}`:`Show the ${Au}`,"aria-pressed":Ru,onClick:()=>{Ru?pageLayoutPanelOpen.value=!1:openPagePanel()},sx:{color:Ru?"accent.fg":"fg.muted",...$u}})}const INPUT_PROMPT_PLUGIN_NAME="@datalayer/loop-plugin-input-prompt",LazyComposerView=reactExports.lazy(()=>__vitePreload(()=>import("./chunks/ComposerView-B-gxvk_X.js"),[],import.meta.url));function ComposerView(Au){return jsxRuntimeExports.jsx(reactExports.Suspense,{fallback:null,children:jsxRuntimeExports.jsx(LazyComposerView,{...Au})})}const InputPromptPlugin={name:INPUT_PROMPT_PLUGIN_NAME,config:{},displayName:"Input Prompt",description:"The composer under (or over) the conversation.",octicon:"pencil",emoji:"✏️",contributionPoints:[LoopPromptPanel],contributes:[contribution(LoopChatComposer,{id:"input-prompt",Component:ComposerView},{id:"input-prompt"})]},AGENT_ICONS={agent:ForwardRef$2,beaker:BeakerIcon,bell:BellIcon,book:BookIcon,briefcase:BriefcaseIcon,browser:BrowserIcon,bug:BugIcon,clock:ClockIcon,code:CodeIcon,"comment-discussion":CommentDiscussionIcon,cpu:CpuIcon,"credit-card":CreditCardIcon,database:DatabaseIcon,file:FileIcon,checklist:ChecklistIcon,"code-review":CodeReviewIcon,fold:FoldIcon,"git-branch":GitBranchIcon,globe:GlobeIcon,graph:GraphIcon,heart:HeartIcon,"issue-opened":IssueOpenedIcon,lightbulb:LightBulbIcon,"light-bulb":LightBulbIcon,"list-unordered":ListUnorderedIcon,mail:MailIcon,megaphone:MegaphoneIcon,"mortar-board":MortarBoardIcon,note:NoteIcon,organization:OrganizationIcon,package:PackageIcon,pencil:PencilIcon,people:PeopleIcon,play:PlayIcon,pulse:PulseIcon,rss:RssIcon,search:SearchIcon,"share-2":ShareAndroidIcon,shield:ShieldIcon,"shield-check":ShieldCheckIcon,sliders:SlidersIcon,sun:SunIcon,sync:SyncIcon,table:TableIcon,tag:TagIcon,tasklist:TasklistIcon,telescope:TelescopeIcon,tools:ToolsIcon,"trending-up":GraphIcon,rocket:RocketIcon,zap:ZapIcon};function agentIcon(Au){return(Au?AGENT_ICONS[Au]:void 0)??ForwardRef$2}function useOptionalSandboxService(){return useReactorPlatform().getOutput(AGENTS_PLUGIN_NAME)?.sandbox}function useSandboxService(){const Au=useOptionalSandboxService();if(!Au)throw new Error(`The code sandbox plugin (${AGENTS_PLUGIN_NAME}) is not mounted. A view that needs a sandbox must declare it as a dependency.`);return Au}function SandboxStatusBridge({workspace:Au}){const lo=useOptionalSandboxService(),$u=useSignalValue$1(lo?.snapshot??IDLE_SANDBOX_SNAPSHOT_SIGNAL),Ru=useSignalValue$1(lo?.target??IDLE_SANDBOX_TARGET_SIGNAL),{setSandbox:Iu,agentId:Pu}=Au;return reactExports.useEffect(()=>lo?.connect(Pu),[lo,Pu]),reactExports.useEffect(()=>{lo&&Iu({...$u,target:Ru})},[lo,$u,Ru,Iu]),null}const DatalayerAgentBridge=reactExports.lazy(async()=>({default:(await __vitePreload(()=>import("./chunks/DatalayerAgentBridge-BNuZDTPn.js"),[],import.meta.url)).DatalayerAgentBridge}));function DatalayerAgentMount(){return jsxRuntimeExports.jsx(reactExports.Suspense,{fallback:null,children:jsxRuntimeExports.jsx(DatalayerAgentBridge,{})})}const CREATING_STATUSES=new Set(["creating","starting","launching","connecting","pending","resuming"]);function isCreatingAgent(Au){return!Au.isReady&&!Au.agentId&&CREATING_STATUSES.has((Au.status||"").toLowerCase())}const MAX_AGENT_NAME_LENGTH=32,toSandboxStatusUrl=Au=>{const lo=String(Au||"").trim();if(lo)try{const $u=new URL(lo);return $u.pathname=`${$u.pathname.replace(/\/$/,"")}/api`,$u.toString()}catch{const $u=lo.replace(/\/$/,"");return $u.endsWith("/api")?$u:`${$u}/api`}},OVERLAY_WIDTH=360,AgentSummary=({summary:Au,title:lo="Active Agent"})=>{const[$u,Ru]=reactExports.useState(!1),[Iu,Pu]=reactExports.useState(!1),Ou=reactExports.useRef(null),Mu=reactExports.useRef(null),Du=()=>{Mu.current!==null&&(window.clearTimeout(Mu.current),Mu.current=null)},Lu=()=>{Du();const Ju=Ou.current?.getBoundingClientRect();Pu(!!(Ju&&Ju.left+OVERLAY_WIDTH>window.innerWidth)),Ru(!0)},Bu=()=>{Du(),Mu.current=window.setTimeout(()=>{Ru(!1),Mu.current=null},300)};reactExports.useEffect(()=>()=>{Du()},[]);const ju=Au?.baseUrl?(()=>{const Ju=Au.baseUrl.replace(/\/$/,"");return Ju.endsWith("/api/v1")?Ju:`${Ju}/api/v1`})():void 0,Fu=ju?`${ju}/runtime/status`:void 0,zu=toSandboxStatusUrl(Au?.sandboxBaseUrl);if(!Au)return null;const Uu=isCreatingAgent(Au),Hu=!!Au.error,Vu=!!Au.agentId||Uu,Gu=strip(Au.agentName,MAX_AGENT_NAME_LENGTH),Wu=`${Au.agentName} · ${Au.location}`,Ku=`${Gu} · ${Au.location}`;return jsxRuntimeExports.jsxs(Box,{ref:Ou,position:"relative",onMouseEnter:Lu,onMouseLeave:Bu,children:[jsxRuntimeExports.jsxs(Box,{as:"button",type:"button",title:Wu,px:2,py:"6px",maxWidth:280,minWidth:0,border:"1px solid",borderColor:Hu?"danger.emphasis":"border.default",borderRadius:2,bg:Hu?"danger.subtle":"canvas.default",color:Hu?"danger.fg":"fg.default",fontSize:0,cursor:"default",display:"flex",alignItems:"center",gap:1,children:[Uu&&jsxRuntimeExports.jsx(StyledSpinner,{size:"small",sx:{width:12,height:12}}),Hu&&jsxRuntimeExports.jsx("span",{"aria-hidden":!0,children:"⚠"}),jsxRuntimeExports.jsx(Box,{as:"span",display:"block",minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",children:Ku})]}),$u&&jsxRuntimeExports.jsxs(Box,{position:"absolute",top:"calc(100% + 8px)",width:OVERLAY_WIDTH,p:2,border:"1px solid",borderColor:"border.default",borderRadius:2,bg:"canvas.overlay",boxShadow:"shadow.large",zIndex:120,fontSize:0,color:"fg.default",right:Iu?0:void 0,left:Iu?void 0:0,children:[jsxRuntimeExports.jsx(Box,{mb:1,fontWeight:600,children:lo}),jsxRuntimeExports.jsxs(Box,{color:"fg.muted",children:["Name: ",Au.agentName]}),jsxRuntimeExports.jsxs(Box,{color:"fg.muted",children:["Location: ",Au.location]}),jsxRuntimeExports.jsxs(Box,{color:"fg.muted",children:["Spec: ",Au.specId||"—"]}),jsxRuntimeExports.jsxs(Box,{color:"fg.muted",children:["Harness: ",Au.harness||"—"]}),jsxRuntimeExports.jsxs(Box,{color:"fg.muted",children:["Variant: ",Au.variant||"—"]}),jsxRuntimeExports.jsxs(Box,{color:"fg.muted",children:["Status: ",Uu?"creating":Au.status||"—"]}),jsxRuntimeExports.jsxs(Box,{color:"fg.muted",wordBreak:"break-all",children:["Agent base URL: ",Au.baseUrl||"—"]}),jsxRuntimeExports.jsxs(Box,{color:"fg.muted",wordBreak:"break-all",children:["Code sandbox base URL:"," ",Au.sandboxBaseUrl?jsxRuntimeExports.jsx(Box,{as:"a",href:Au.sandboxBaseUrl,target:"_blank",rel:"noopener noreferrer",color:"accent.fg",textDecoration:"underline",children:Au.sandboxBaseUrl}):"—"]}),jsxRuntimeExports.jsxs(Box,{color:"fg.muted",wordBreak:"break-all",display:"flex",alignItems:"center",gap:1,children:["Agent ID:"," ",Au.agentId?Au.agentId:Uu?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(StyledSpinner,{size:"small",sx:{width:12,height:12}}),"Creating…"]}):"—"]}),jsxRuntimeExports.jsxs(Box,{color:"fg.muted",wordBreak:"break-all",children:["Agent status:"," ",Vu&&Fu?jsxRuntimeExports.jsx(Box,{as:"a",href:Fu,target:"_blank",rel:"noopener noreferrer",color:"accent.fg",textDecoration:"underline",children:Fu}):"n/a"]}),jsxRuntimeExports.jsxs(Box,{color:"fg.muted",wordBreak:"break-all",children:["Code sandbox status:"," ",zu?jsxRuntimeExports.jsx(Box,{as:"a",href:zu,target:"_blank",rel:"noopener noreferrer",color:"accent.fg",textDecoration:"underline",children:zu}):"n/a"]}),Hu&&jsxRuntimeExports.jsxs(Box,{mt:1,p:1,border:"1px solid",borderColor:"danger.muted",borderRadius:2,bg:"danger.subtle",color:"danger.fg",wordBreak:"break-word",children:["Error: ",Au.error]})]})]})},insideJupyterLab=()=>loadJupyterConfig().insideJupyterLab;function collect(Au,lo){const $u=Au?.header?.msg_type,Ru=Au?.content??{};$u==="stream"?(lo.stdout.push(String(Ru.text??"")),lo.outputs.push({output_type:"stream",text:Ru.text})):$u==="execute_result"||$u==="display_data"?lo.outputs.push({output_type:$u,data:Ru.data}):$u==="error"&&(lo.error=`${Ru.ename??"Error"}: ${Ru.evalue??""}`,lo.outputs.push({output_type:"error",ename:Ru.ename,evalue:Ru.evalue,traceback:Ru.traceback}))}function browserSource(){let Au;return{variant:"pyodide",acquire:async()=>{const{createLiteServiceManager:lo,jupyterReactStore:$u,loadJupyterConfig:Ru}=await __vitePreload(async()=>{const{createLiteServiceManager:Pu,jupyterReactStore:Ou,loadJupyterConfig:Mu}=await import("./chunks/index-BOGJMsUN.js").then(Du=>Du.r);return{createLiteServiceManager:Pu,jupyterReactStore:Ou,loadJupyterConfig:Mu}},[],import.meta.url);Au=Au??{baseUrl:libExports$5.PageConfig.getOption("baseUrl"),wsUrl:libExports$5.PageConfig.getOption("wsUrl")},Ru({lite:!0});const Iu=await lo();return $u.getState().setServiceManager(Iu),Iu},release:()=>{Au&&(libExports$5.PageConfig.setOption("baseUrl",Au.baseUrl),libExports$5.PageConfig.setOption("wsUrl",Au.wsUrl),Au=void 0)},owned:!0}}function createBrowserSandboxService(Au=browserSource()){const lo=signal$2(null),$u=signal$2("idle"),Ru=signal$2(null),Iu=computed$1(()=>({state:$u.value,variant:Au.variant,kernelId:lo.value?.kernel_id})),Pu=computed$1(()=>$u.value==="running");let Ou=null,Mu=null,Du=null,Lu=null;async function Bu(){if(Mu)return;$u.value="starting",Ou=await Au.acquire();const ju=await Ou.sessions.startNew({name:"loop",path:"loop.ipynb",type:"notebook",kernel:{name:"python"}});Du=ju.kernel,Mu=ju.kernel,lo.value={variant:Au.variant,sandbox_running:!0,kernel_id:Mu?.id,kernel_name:"python"},$u.value="running"}return{kind:"browser",snapshot:Iu,status:lo,ready:Pu,lastExecution:Ru,serverUrl:"",getServiceManager:()=>Ou,getKernelConnection:()=>Du,report(ju){lo.value=ju},setState(ju){$u.value=ju},connect(){return Lu=Lu??Bu().catch(ju=>{throw $u.value="error",lo.value=null,Lu=null,ju}),()=>{Mu?.shutdown?.(),Mu=null,Du=null,Ou=Au.owned?null:Ou,Au.release?.(),Lu=null,$u.value="idle",lo.value=null}},async execute(ju){const Fu=Date.now();try{if(await(Lu??Bu()),!Mu)throw new Error("The browser kernel did not start");const zu={outputs:[],stdout:[],error:""},Uu=Mu.requestExecute({code:ju});Uu.onIOPub=Vu=>collect(Vu,zu),await Uu.done;const Hu={code:ju,success:!zu.error,stdout:zu.stdout.join(""),error:zu.error||void 0,outputs:zu.outputs,startedAt:Fu,finishedAt:Date.now()};return Ru.value=Hu,Hu}catch(zu){const Uu={code:ju,success:!1,error:zu instanceof Error?zu.message:String(zu),startedAt:Fu,finishedAt:Date.now()};return Ru.value=Uu,Uu}}}}function summarize(Au,lo){if(!Au)return{state:lo};const $u=Au.variant==="jupyter-server"||Au.variant==="datalayer";return{state:!!Au.sandbox_running||$u&&!!Au.jupyter_connected?"running":lo==="running"?"idle":lo,variant:Au.variant,kernelId:Au.kernel_id,jupyterUrl:Au.jupyter_url,jupyterToken:Au.jupyter_token,agentBaseUrl:Au.agent_base_url}}const RECONNECT_BASE_MS=1e3,RECONNECT_MAX_MS=3e4;function createServerSandboxService(Au){const lo=signal$2(null),$u=signal$2("idle"),Ru=signal$2(void 0),Iu=signal$2(null),Pu=computed$1(()=>({...summarize(lo.value,$u.value),errorReason:$u.value==="error"?Ru.value:void 0})),Ou=computed$1(()=>Pu.value.state==="running");return{kind:"server",connect(Mu){if(typeof WebSocket>"u")return()=>{};let Du=null,Lu=null,Bu=0,ju=!1;const Fu=()=>{if(ju)return;const zu=Au.replace(/^http/,"ws"),Uu=Mu?`?agent_id=${encodeURIComponent(Mu)}`:"";Du=new WebSocket(`${zu}/api/v1/configure/sandbox/ws${Uu}`),Du.onopen=()=>{Bu=0},Du.onmessage=Hu=>{try{lo.value=JSON.parse(String(Hu.data))}catch{}},Du.onclose=()=>{if(ju)return;lo.value=null,Bu+=1;const Hu=Math.min(RECONNECT_BASE_MS*2**(Bu-1),RECONNECT_MAX_MS);Lu=setTimeout(Fu,Hu)}};return Fu(),()=>{ju=!0,Lu&&clearTimeout(Lu),Du?.close(),Du=null}},snapshot:Pu,status:lo,ready:Ou,lastExecution:Iu,serverUrl:Au,report(Mu){lo.value=Mu},setState(Mu,Du){$u.value=Mu,Ru.value=Mu==="error"?Du:void 0},async execute(Mu){const Du=Date.now();try{const Lu=await fetch(`${Au}/api/v1/sandbox/execute`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({code:Mu})}),Bu=Lu.ok?await Lu.json():null,ju={code:Mu,success:Lu.ok&&!Bu?.error,stdout:Bu?.stdout,stderr:Bu?.stderr,error:Lu.ok?Bu?.error:`Execution failed: ${Lu.status}`,outputs:Bu?.outputs,startedAt:Du,finishedAt:Date.now()};return Iu.value=ju,ju}catch(Lu){const Bu={code:Mu,success:!1,error:Lu instanceof Error?Lu.message:String(Lu),startedAt:Du,finishedAt:Date.now()};return Iu.value=Bu,Bu}}}}const ANONYMOUS_JUPYTER_URL="https://prod1.datalayer.run/api/jupyter-server",ANONYMOUS_JUPYTER_TOKEN="60c1661cc408f978c309d04157af55c9588ff9557c9380e4fb50785750703da6",SANDBOX_TARGETS=["browser","local","jupyter","datalayer"];function heldTargetReason(Au,lo){if(Au==="local"&&!lo&&!insideJupyterLab())return"Not offered on the web for now: a local agent and the Jupyter server it starts run beside JupyterLab, not in a page."}const TARGET_SPECS={browser:{label:"Browser",hint:"Python in this page (Pyodide), with the agent loop running here too. Only the model is asked over the network.",hasAgent:!0,noAgentReason:""},local:{label:"Local",hint:"A local agent, with the Jupyter server it starts beside itself.",hasAgent:!0,noAgentReason:"",configure:{variant:"jupyter-server",jupyter_url:"",jupyter_token:""}},jupyter:{label:"Jupyter",hint:"A named Jupyter server: the anonymous one on prod1.datalayer.run.",hasAgent:!1,noAgentReason:"No agent on an anonymous Jupyter server",configure:{variant:"jupyter-server",jupyter_url:ANONYMOUS_JUPYTER_URL,jupyter_token:ANONYMOUS_JUPYTER_TOKEN}},datalayer:{label:"Datalayer",hint:"A Datalayer runtime running the agent this workspace asks for.",hasAgent:!0,noAgentReason:""}};function targetHasAgent(Au){return TARGET_SPECS[Au]?.hasAgent??!1}function targetRunsAgentInPage(Au){return Au==="browser"}function createSwitchableSandboxService({serverUrl:Au,initialTarget:lo="local",kernelSource:$u,localAgent:Ru,blueprint:Iu}){const Pu=signal$2(lo),Ou=createServerSandboxService(Au),Mu=createBrowserSandboxService($u??browserSource()),Du=computed$1(()=>Pu.value==="browser"?Mu:Ou);let Lu=null,Bu;const ju=computed$1(()=>Du.value.snapshot.value),Fu=computed$1(()=>Du.value.status.value),zu=computed$1(()=>Du.value.ready.value),Uu=computed$1(()=>Du.value.lastExecution.value);async function Hu(Wu){if(Wu==="local"){const ed=Iu?.()??Ru?.createPayload;ed&&await Vu(ed)}const Ku=TARGET_SPECS[Wu]?.configure;if(!Ku)return;const Ju=TARGET_SPECS[Wu].label;let Yu;try{Yu=await fetch(`${Au}/api/v1/agents/sandbox/configure`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(Ku)})}catch(ed){throw new Error(`${Ju} needs an agent-runtimes server at ${Au}, and nothing answered there. Start one and try again. (${ed instanceof Error?ed.message:String(ed)})`,{cause:ed})}if(!Yu.ok)throw new Error(`The server could not switch to ${Ju} (${Yu.status} ${Yu.statusText}). `+await detail(Yu));const Xu=await fetch(`${Au}/api/v1/agents/sandbox/restart`,{method:"POST"});if(!Xu.ok)throw new Error(`The server could not start ${Ju} (${Xu.status} ${Xu.statusText}). `+await detail(Xu))}function Vu(Wu){return ensureServerAgent(Au,Bu,Wu)}function Gu(){if(Lu?.(),Pu.peek()==="datalayer"){Lu=null,Ou.setState("starting");return}Lu=Du.peek().connect(Bu)}return{get kind(){return Pu.peek()==="browser"?"browser":"server"},target:Pu,snapshot:ju,status:Fu,ready:zu,lastExecution:Uu,serverUrl:Au,getServiceManager:()=>Pu.peek()==="browser"?Mu.getServiceManager():null,getKernelConnection:()=>Pu.peek()==="browser"?Mu.getKernelConnection():null,report(Wu){Du.peek().report(Wu)},setState(Wu,Ku){Du.peek().setState(Wu,Ku)},execute(Wu){return Du.peek().execute(Wu)},connect(Wu){Bu=Wu;const Ku=Pu.peek()==="local"&&Wu?Iu?.()??Ru?.createPayload:void 0;if(!Ku)return Gu(),()=>{Lu?.(),Lu=null};let Ju=!1;return Ou.setState("starting"),Vu(Ku).then(()=>{Ju||Gu()},Yu=>{Ju||(Ou.setState("error"),console.error("[loop] Local agent could not be started:",Yu))}),()=>{Ju=!0,Lu?.(),Lu=null}},async setTarget(Wu){const Ku=Pu.peek();if(Wu===Ku)return;const Ju=heldTargetReason(Wu,Au);if(Ju)throw new Error(Ju);Lu?.(),Lu=null;try{await Hu(Wu)}catch(Yu){throw Gu(),Yu}Pu.value=Wu,Gu()}}}async function ensureServerAgent(Au,lo,$u){const Ru=lo?.trim();if(!Ru)throw new Error("Local needs an agent id before its runtime can start.");let Iu;try{Iu=await fetch(`${Au}/api/v1/agents/${encodeURIComponent(Ru)}`)}catch(Ou){throw new Error(`Local needs an agent-runtimes server at ${Au}, and nothing answered there. Start one and try again. (${Ou instanceof Error?Ou.message:String(Ou)})`,{cause:Ou})}if(Iu.ok){await ensureServerSandbox(Au,Ru);return}if(Iu.status!==404)throw new Error(`The server could not inspect local agent ${Ru} (${Iu.status} ${Iu.statusText}). `+await detail(Iu));const Pu=await fetch(`${Au}/api/v1/agents`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({transport:"ag-ui",sandbox_variant:"jupyter-server",...$u,name:Ru})});if(!Pu.ok&&Pu.status!==409)throw new Error(`The server could not launch local agent ${Ru} (${Pu.status} ${Pu.statusText}). `+await detail(Pu));Pu.status===409&&await ensureServerSandbox(Au,Ru)}async function ensureServerSandbox(Au,lo){const $u=await fetch(`${Au}/api/v1/agents/${encodeURIComponent(lo)}/sandbox/ensure`,{method:"POST"});if(!$u.ok)throw new Error(`The server could not start a sandbox for local agent ${lo} (${$u.status} ${$u.statusText}). `+await detail($u))}async function detail(Au){try{const lo=await Au.json();return typeof lo.detail=="string"?lo.detail:""}catch{return""}}function useOptionalTeamSelection(){return useReactorPlatform().getOutput(AGENTS_PLUGIN_NAME)?.team}const NO_TARGET={value:void 0,peek:()=>{}},NO_MEMBER={value:void 0,peek:()=>{}};function AgentSummaryPanel({workspace:Au}){const lo=useSandboxService(),$u=useSignalValue$1(lo?.target??NO_TARGET),Ru=useOptionalTeamSelection(),Iu=useSignalValue$1(Ru?.active??NO_MEMBER);if(!lo)return null;const Pu=Au.sandbox,Ou=Iu?.specId||Au.agentId,Mu=AGENTSPECS$1[Ou],Du={agentName:Iu?.name||Mu?.name||Au.agentId,location:$u?TARGET_SPECS[$u].label:"—",specId:Ou,harness:Mu?.harness,variant:Pu.variant,status:Pu.state,baseUrl:Pu.agentBaseUrl||Au.serverUrl,sandboxBaseUrl:Pu.jupyterUrl,agentId:Au.agentId,isReady:Pu.state==="running"};return jsxRuntimeExports.jsx(AgentSummary,{summary:Du})}const RING=14,STROKE=2.5,RADIUS=(RING-STROKE)/2,CIRCUMFERENCE=2*Math.PI*RADIUS,DEFAULT_WARN_AT=.25,DEFAULT_DANGER_AT=.1,DEFAULT_PULSE_AT=.05,PULSE_MS=1200;function format(Au){const lo=Math.max(0,Math.ceil(Au/1e3)),$u=Math.floor(lo/60),Ru=lo%60;return`${$u}:${String(Ru).padStart(2,"0")}`}function AnonymousKeyTimer({expiresAt:Au,grantedMs:lo,label:$u="Trial key",warnAt:Ru=DEFAULT_WARN_AT,dangerAt:Iu=DEFAULT_DANGER_AT,pulseAt:Pu=DEFAULT_PULSE_AT,onExpire:Ou}){const[Mu,Du]=reactExports.useState(()=>Date.now()),Lu=reactExports.useRef(lo??Math.max(1,Au-Date.now())),Bu=reactExports.useRef(!1);reactExports.useEffect(()=>{const Hu=window.setInterval(()=>{Du(Vu=>{const Gu=Date.now(),Wu=Ku=>Math.ceil((Au-Ku)/1e3);return Wu(Gu)===Wu(Vu)?Vu:Gu})},250);return()=>window.clearInterval(Hu)},[Au]);const ju=Math.max(0,Au-Mu);reactExports.useEffect(()=>{ju>0||Bu.current||(Bu.current=!0,Ou?.())},[ju,Ou]);const Fu=Math.min(1,Math.max(0,ju/Lu.current)),zu=Fu<=Pu,Uu=Fu<=Iu?"danger.fg":Fu<=Ru?"attention.fg":"fg.muted";return jsxRuntimeExports.jsxs(Box,{display:"inline-flex",alignItems:"center",gap:1,px:2,py:"2px",borderRadius:"999px",border:"1px solid",borderColor:"border.muted",bg:"canvas.subtle",color:Uu,fontVariantNumeric:"tabular-nums",sx:{...zu?{"@keyframes dla-key-pulse":{"0%, 100%":{opacity:1},"50%":{opacity:.45}},animation:`dla-key-pulse ${PULSE_MS}ms ease-in-out infinite`,"@media (prefers-reduced-motion: reduce)":{animation:"none"}}:null},title:`${$u}: this workspace is talking to the agent on a temporary key issued to nobody in particular. When it runs out the chat asks you to sign in. Sign in now for an account of your own.`,children:[jsxRuntimeExports.jsx(Box,{display:"flex",alignItems:"center",color:Uu,children:jsxRuntimeExports.jsx(KeyIcon,{size:12})}),jsxRuntimeExports.jsxs(Box,{as:"svg","aria-hidden":"true",focusable:"false",width:RING,height:RING,viewBox:`0 0 ${RING} ${RING}`,display:"block",flexShrink:0,children:[jsxRuntimeExports.jsx("circle",{cx:RING/2,cy:RING/2,r:RADIUS,fill:"none",stroke:"currentColor",strokeWidth:STROKE,opacity:.2}),jsxRuntimeExports.jsx("circle",{cx:RING/2,cy:RING/2,r:RADIUS,fill:"none",stroke:"currentColor",strokeWidth:STROKE,strokeLinecap:"round",strokeDasharray:CIRCUMFERENCE,strokeDashoffset:CIRCUMFERENCE*(1-Fu),transform:`rotate(-90 ${RING/2} ${RING/2})`,style:{transition:"stroke-dashoffset 0.5s linear"}})]}),jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:Uu,fontWeight:"semibold"},children:format(ju)})]})}function AnonymousKeyHeaderBadge({workspace:Au}){return jsxRuntimeExports.jsx(Box,{order:1,display:"inline-flex",alignItems:"center",children:jsxRuntimeExports.jsx(AnonymousKeyBadge,{workspace:Au})})}function AnonymousKeyBadge({workspace:Au}){const lo=useAnonymousSession(),$u=Au.sandbox.target??"local";return!targetRunsAgentInPage($u)||lo.status==="idle"||lo.status==="expired"?null:lo.expiresAt?jsxRuntimeExports.jsx(AnonymousKeyTimer,{expiresAt:lo.expiresAt,grantedMs:lo.grantedMs,onExpire:()=>useAnonymousSessionStore.getState().expire()}):jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:lo.error?"danger.fg":"fg.muted"},title:lo.error,children:lo.error?"No trial key":"Getting a trial key…"})}function SandboxSelector(Au){const lo=useOptionalSandboxService(),[$u,Ru]=reactExports.useState(!1),[Iu,Pu]=reactExports.useState(null),Ou=useSignalValue$1(lo?.snapshot??IDLE_SANDBOX_SNAPSHOT_SIGNAL),Mu=useSignalValue$1(lo?.status??EMPTY_STATUS),Du=useSignalValue$1(lo?.target??DEFAULT_TARGET),Lu=reactExports.useCallback(async ju=>{if(!(!lo||ju===Du)){Ru(!0),Pu(null);try{await lo.setTarget(ju)}catch(Fu){Pu(Fu instanceof Error?Fu.message:String(Fu))}finally{Ru(!1)}}},[lo,Du]);if(!lo)return null;const Bu=Math.max(0,SANDBOX_TARGETS.indexOf(Du));return jsxRuntimeExports.jsxs(Box,{display:"flex",alignItems:"center",gap:2,minWidth:0,children:[jsxRuntimeExports.jsx(Box,{width:16,flexShrink:0,display:"flex",justifyContent:"center",children:$u?jsxRuntimeExports.jsx(StyledSpinner,{size:"small"}):null}),jsxRuntimeExports.jsx(KernelIndicator,{state:sandboxIndicatorState(Ou.state,Mu?.execution_state,Mu?.is_executing),kernelId:Ou.kernelId??Mu?.kernel_id,kernelName:Mu?.kernel_name,serverUrl:Ou.jupyterUrl??Mu?.jupyter_url,websocketUrl:toWebsocketUrl(Ou.jupyterUrl??Mu?.jupyter_url),environmentName:TARGET_SPECS[Du].label,overlayTitle:`${TARGET_SPECS[Du].label} Kernel`,position:"se",bordered:!1}),jsxRuntimeExports.jsx(SegmentedControl,{"aria-label":"Where code runs",size:"small",style:{listStyle:"none",margin:0,padding:0},sx:{listStyle:"none",m:0,p:0,"& > li":{listStyle:"none"},"& > li::marker":{content:"none"}},children:SANDBOX_TARGETS.map((ju,Fu)=>{const zu=heldTargetReason(ju,lo?.serverUrl??"");return jsxRuntimeExports.jsx(SegmentedControl.Button,{selected:Fu===Bu,"aria-disabled":zu?!0:void 0,"data-sandbox-target":ju,"data-sandbox-target-held":zu?"":void 0,sx:{listStyle:"none",...zu?{color:"fg.subtle",cursor:"not-allowed"}:null},title:zu??TARGET_SPECS[ju].hint,onClick:()=>zu?void 0:void Lu(ju),children:TARGET_SPECS[ju].label},ju)})}),Iu||Ou.errorReason?jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:"danger.fg",lineHeight:1.3,maxWidth:280,minWidth:0},title:Iu??Ou.errorReason,children:Iu??Ou.errorReason}):jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:"fg.muted"},title:TARGET_SPECS[SANDBOX_TARGETS[Bu]].hint,children:Ou.state})]})}function toWebsocketUrl(Au){return Au?.replace(/^http/,"ws")}const EMPTY_STATUS={value:null,peek:()=>null},DEFAULT_TARGET={value:"local",peek:()=>"local"};function MemberIcon({icon:Au}){const lo=agentIcon(Au);return jsxRuntimeExports.jsx(lo,{})}function TeamMemberPicker(){const Au=useOptionalTeamSelection();return!Au||Au.members.length<2?null:jsxRuntimeExports.jsx(TeamMemberMenu,{selection:Au})}function TeamMemberMenu({selection:Au}){const[lo,$u]=reactExports.useState(!1),Ru=useSignalValue$1(Au.selected),Iu=Au.members.find(Pu=>Pu.id===Ru);return jsxRuntimeExports.jsx(AnchoredOverlay,{width:"large",open:lo,onOpen:()=>$u(!0),onClose:()=>$u(!1),renderAnchor:Pu=>jsxRuntimeExports.jsx(IconButton,{...Pu,"aria-labelledby":void 0,icon:ForwardRef$2,"aria-label":Iu?`Talking to ${Iu.name}. Choose another agent.`:"Choose an agent",variant:"invisible",size:"small"}),children:jsxRuntimeExports.jsx(Box,{width:440,maxWidth:"calc(100vw - 16px)",children:jsxRuntimeExports.jsxs(ActionList,{selectionVariant:"single",role:"listbox","aria-label":`Agents in ${Au.team.name}`,children:[jsxRuntimeExports.jsx(ActionList.GroupHeading,{children:Au.team.name}),Au.members.map(Pu=>jsxRuntimeExports.jsxs(ActionList.Item,{selected:Pu.id===Ru,onSelect:()=>{Au.select(Pu.id),$u(!1)},children:[jsxRuntimeExports.jsx(ActionList.LeadingVisual,{children:jsxRuntimeExports.jsx(MemberIcon,{icon:Pu.icon})}),jsxRuntimeExports.jsxs(Box,{as:"span",display:"flex",alignItems:"center",gap:2,children:[Pu.name,Pu.isSupervisor?jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:"fg.muted"},children:"supervisor"}):null]}),Pu.description?jsxRuntimeExports.jsx(ActionList.Description,{variant:"block",sx:{display:"block",whiteSpace:"normal",overflowWrap:"anywhere",minWidth:0},children:Pu.description}):null]},Pu.id))]})})})}function specIdOf(Au){return(Au??"").split(":")[0]??""}function teamMembers(Au){const lo=specIdOf(Au.supervisor?.ref),$u=Iu=>{const Pu=AGENTSPECS$1[Iu];return{description:Pu?.description,emoji:Pu?.emoji,icon:Pu?.icon}},Ru=(Au.agents??[]).map(Iu=>{const Pu=specIdOf(Iu.ref);return{id:Iu.id,name:Iu.name||Pu||Iu.id,specId:Pu,isSupervisor:Pu!==""&&Pu===lo,...$u(Pu)}});return[...Ru.filter(Iu=>Iu.isSupervisor),...Ru.filter(Iu=>!Iu.isSupervisor)]}function createTeamSelection(Au){const lo=TEAM_SPECS[Au];if(!lo)return;const $u=teamMembers(lo);if($u.length===0)return;const Ru=signal$2($u[0].id);return{team:lo,members:$u,selected:Ru,select:Iu=>{$u.some(Pu=>Pu.id===Iu)&&(Ru.value=Iu)},sharing:lo.context?.sharing??"shared",active:computed$1(()=>$u.find(Iu=>Iu.id===Ru.value))}}function subagentsFor(Au,lo){const $u=teamMembers(Au),Ru=$u.find(Du=>Du.id===lo);if(!Ru)return[];const Iu=(Du,Lu,Bu)=>{const ju=AGENTSPECS$1[Lu];if(ju)return{name:Du,description:Bu||ju.description||Du,instructions:ju.systemPrompt,model:ju.model,icon:ju.icon}},Pu=Ru.isSupervisor||Au.delegation?.allowPeerDelegation?$u.filter(Du=>Du.id!==lo).map(Du=>Iu(Du.name,Du.specId,Du.description)):[],Mu=((Au.agents??[]).find(Du=>Du.id===lo)?.subagents??[]).map(Du=>Iu(Du.name,(Du.ref??"").split(":")[0]??"",Du.description));return[...Pu,...Mu].filter(Boolean)}const DEFAULT_DATALAYER_AGENTSPEC="jupyter-tutor",AGENTS_PLUGIN_NAME="@datalayer/loop-plugin-agents",offeredTarget=(Au,lo)=>heldTargetReason(Au,lo)?"browser":Au,AgentsPlugin={name:AGENTS_PLUGIN_NAME,displayName:"Agents",description:"Where the agent and its code run: this page, a local server, or a Datalayer runtime.",octicon:"container",emoji:"📦",config:{serverUrl:"",target:"local"},contributionPoints:[LoopAgentBlueprint],preserveOutput:!0,build({config:Au,reactor:lo}){const $u=Au.showAgentVariants??!0,Ru=Au.teamId?createTeamSelection(Au.teamId):void 0;return{team:Ru,sandbox:createSwitchableSandboxService({serverUrl:Au.serverUrl,initialTarget:offeredTarget(($u||Au.targetFixed?Au.target:"browser")??"local",Au.serverUrl),kernelSource:Au.kernelSource,localAgent:Au.localAgent,blueprint:()=>{const Iu=lo.getContributions(LoopAgentBlueprint)[0]?.value;if(Iu)return{...Iu.specId?{agent_spec_id:Iu.specId}:null,...Iu.createPayload}}}),components:[{slot:LoopSlots.status,id:"sandbox-status",Component:SandboxStatusBridge},{slot:LoopSlots.status,id:"datalayer-agent",Component:DatalayerAgentMount},...Ru&&Au.showTeamPicker!==!1?[{slot:LoopSlots.header,id:"team-member-picker",Component:TeamMemberPicker}]:[],...$u?[{slot:LoopSlots.header,id:"sandbox-selector",Component:SandboxSelector}]:[],...Au.showAgentSummary===!1?[]:[{slot:LoopSlots.header,id:"agent-summary",Component:AgentSummaryPanel}],{slot:LoopSlots.chatHeader,id:"anonymous-key",Component:AnonymousKeyBadge},{slot:LoopSlots.header,id:"anonymous-key-header",Component:AnonymousKeyHeaderBadge}]}},register({contribute:Au,state:lo}){const $u=lo.getOutput()?.sandbox;if($u)return Au(LoopAgentGate,{check:Ru=>{const Iu=Ru.sandbox.target??$u.target.peek();return targetHasAgent(Iu)||TARGET_SPECS[Iu].noAgentReason}},{id:"sandbox-target"})},contributes:[contribution(LoopViewType,{viewType:"sandbox",title:"Sandbox",icon:ServerIcon,order:40,load:()=>__vitePreload(()=>import("./chunks/SandboxView-DDWPvnOk.js"),[],import.meta.url)},{id:"sandbox",order:40}),contribution(LoopCommand,{name:"sandbox",aliases:["code-sandbox"],description:"Show the code sandbox: variant, kernel, Jupyter server",group:"Capabilities",run:async({workspace:Au})=>{Au.setActiveViewType("sandbox")}},{id:"sandbox"})]},PULSE_ANIMATION="loop-subagent-pulse",KEYFRAMES=`@keyframes ${PULSE_ANIMATION} {
3856
+ `).filter(Iu=>Iu.startsWith("data:")).map(Iu=>Iu.slice(5).trim()).join("");if(Ru)try{lo.push(JSON.parse(Ru))}catch{}}return lo}function pageTurnOf(Au){let lo=null;for(const $u of streamEvents(Au)){if($u.type==="RUN_ERROR")return{refused:String($u.message??"Its page could not run.")};if($u.type==="CUSTOM"&&$u.name===LOOP_PAGE){const Ru=$u.value??{};lo={outputs:Ru.outputs??{},inputs:Ru.inputs??{}}}}return lo??{refused:"Its page showed nothing: its code answered no outputs."}}const base=Au=>`${Au.serverUrl.replace(/\/+$/,"")}/api/v1/apps/sessions`;async function posted(Au,lo,$u){const Ru=await(Au.fetcher??fetch)(lo,{method:"POST",headers:{"content-type":"application/json",...Au.token?{Authorization:`Bearer ${Au.token}`}:{}},body:JSON.stringify($u)});if(!Ru.ok){let Iu="";try{const Pu=await Ru.json();Iu=typeof Pu.detail=="string"?Pu.detail:""}catch{}throw new Error(Iu||`Its page was refused (${Ru.status}).`)}return Ru.text()}async function openPageSession(Au){const lo=await posted(Au,base(Au),{agent:Au.agentId});for(const $u of streamEvents(lo))if($u.type==="CUSTOM"&&$u.name==="loop.session"){const Ru=$u.value?.uid;if(typeof Ru=="string"&&Ru)return Ru}throw new Error("The runtime opened no session for its page.")}async function runPageIn(Au,lo,$u){try{const Ru=await posted(Au,`${base(Au)}/${encodeURIComponent(lo)}/page`,{inputs:$u});return pageTurnOf(Ru)}catch(Ru){return{refused:Ru instanceof Error?Ru.message:String(Ru)}}}function outputsData(Au){return Object.fromEntries(Object.entries(Au).map(([lo,$u])=>[`/outputs/${lo}`,$u]))}const PAGE_RUN_DELAY_MS=300,NO_TURN$6=signal$2({id:0,status:"idle"}),NO_CONVERSATION$2=signal$2([]);function componentsOnPage(Au){const lo=new Set;for(const $u of Au){const Ru=$u.updateComponents;for(const Iu of Ru?.components??[])lo.add(String(Iu.component))}return[...lo]}function blocksMissing(Au,lo){const $u=new Set(lo),Ru=Au.filter(Iu=>!$u.has(Iu));return Ru.length===0?null:`This page places ${Ru.join(", ")}, which no enabled plugin contributes: ${Ru.length===1?"it is":"they are"} drawn once the plugin that contributes ${Ru.length===1?"it":"them"} is on.`}function AppPage({app:Au,workspace:lo}){const $u=useContributions(LoopChatTurn),Ru=useSignalValue$1($u[0]?.value.turn??NO_TURN$6),Iu=useSignalValue$1($u[0]?.value.conversation??NO_CONVERSATION$2),Pu=reactExports.useMemo(()=>appPageMessages(Au,SURFACE_CATALOG_ID),[Au]),Ou=useContributions(LoopCanvasBlock),Mu=[...new Set(Ou.map(yd=>yd.value.id))].sort(),Du=Mu.join(","),Lu=useOwnComponents(),Bu=reactExports.useMemo(()=>{const yd=blocksMissing(componentsOnPage(Pu),Mu);if(yd)return{problem:yd};try{return{catalog:catalogOfBlocks(Mu,Lu)}}catch(wd){return{problem:wd instanceof Error?wd.message:String(wd)}}},[Pu,Du,Lu]),[ju,Fu]=reactExports.useState(null),zu=pageOf(Au),[Uu,Hu]=reactExports.useState({}),Vu=reactExports.useMemo(()=>({...appPageData(Au,Ru,Iu),...outputsData(Uu)}),[Au,Ru,Iu,Uu]),Gu=useIAMStore(yd=>yd.token)??"",Wu=useChatWords(),Ku=agentServerOf(lo.sandbox,lo.serverUrl),Ju=reactExports.useRef(null);Ju.current=Ku===void 0?null:{serverUrl:Ku,agentId:lo.agentId||Au.id,token:Gu||void 0};const Yu=reactExports.useRef("");Yu.current=Ku===void 0?noRuntimeSaid(lo.sandbox,Wu):"";const Xu=reactExports.useRef(null),ed=reactExports.useRef(!1),td=reactExports.useRef(null),nd=reactExports.useRef(""),od=reactExports.useRef(!0),sd=reactExports.useCallback(yd=>{td.current=yd,!ed.current&&(ed.current=!0,(async()=>{for(;td.current&&od.current;){const wd=td.current;td.current=null;const Ad=Ju.current;if(!Ad){Fu(Yu.current);continue}try{Xu.current??=openPageSession(Ad);const md=await runPageIn(Ad,await Xu.current,wd);if(!od.current)break;"refused"in md?Fu(md.refused):(Fu(null),Hu(md.outputs))}catch(md){Xu.current=null,od.current&&Fu(md instanceof Error?md.message:String(md))}}ed.current=!1})())},[]),ad=reactExports.useRef(null);reactExports.useEffect(()=>(od.current=!0,()=>{od.current=!1,ad.current?.()}),[]);const pd=reactExports.useCallback(yd=>{if(!zu?.live)return;ad.current?.();let wd;const Ad=dd=>{const bd=pageInputsOf(Au,dd),ld=JSON.stringify(bd);ld!==nd.current&&(clearTimeout(wd),wd=setTimeout(()=>{nd.current=ld,sd(bd)},PAGE_RUN_DELAY_MS))},md=yd.dataModel.subscribe("/inputs",Ad);Ad(md.value),ad.current=()=>{clearTimeout(wd),md.unsubscribe()}},[Au,zu?.live,sd]),gd=reactExports.useRef(lo);gd.current=lo;const Sd=reactExports.useRef(""),_d=reactExports.useCallback((yd,wd)=>{const Ad=appPageAction(Au,{name:yd.name,context:yd.context??{}},dd=>wd?.dataModel.get(dd),Sd.current),md=gd.current.viewControls;if("refused"in Ad){Fu(Ad.refused);return}if(Fu(null),"runPage"in Ad)sd(Ad.runPage);else if("stop"in Ad)md.stop?.();else if("newChat"in Ad)md.newChat?.();else{if(md.send){const dd=md.send(Ad.send,{loop:Ad.loop});if(dd){Fu(dd);return}}else if(Ad.loop.files){Fu("The conversation is not ready for a file yet: try again.");return}else gd.current.prompts.submit(Ad.send);Sd.current=Ad.inputs;for(const dd of Ad.clear)wd?.dataModel.set(dd,"")}},[Au,sd]);return jsxRuntimeExports.jsx(Box,{"data-testid":"app-page",height:"100%",minHeight:0,overflow:"auto",p:3,children:"problem"in Bu?jsxRuntimeExports.jsx(Box,{role:"status",color:"fg.muted",fontSize:1,children:Bu.problem}):jsxRuntimeExports.jsx(InlineSurface,{messages:Pu,data:Vu,onAction:_d,validationError:ju,catalog:Bu.catalog,...zu?{onSurface:pd}:{}},Du)})}const APP_PAGE_PLUGIN_NAME="@datalayer/loop-plugin-app-page";function defineAppPagePlugin(Au){function lo({workspace:Ru}){return jsxRuntimeExports.jsx(AppPage,{app:Au,workspace:Ru})}return{name:`${APP_PAGE_PLUGIN_NAME}-${Au.id}`,displayName:`${Au.name}: its page`,description:`The page of ${Au.name}, drawn beside its conversation.`,octicon:"browser",emoji:Au.emoji||void 0,contributes:[contribution(LoopEditorView,{surfaceId:APP_PAGE_SURFACE,title:Au.name,icon:BrowserIcon,order:-10,load:async()=>({default:lo})},{id:APP_PAGE_SURFACE,order:-10})]}}const APP_HOST_PAGE_VIEW="app-page";function defineAppHostPagePlugin(Au,lo){function $u({workspace:Iu}){return jsxRuntimeExports.jsx(lo,{app:Au,workspace:Iu})}return{name:`${APP_PAGE_PLUGIN_NAME}-${Au.id}`,displayName:`${Au.name}: its page`,description:`The page of ${Au.name}, drawn by its host.`,octicon:"browser",emoji:Au.emoji||void 0,contributes:[contribution(LoopViewType,{viewType:APP_HOST_PAGE_VIEW,title:Au.name,icon:BrowserIcon,order:-10,load:async()=>({default:$u})},{id:APP_HOST_PAGE_VIEW,order:-10})]}}const canvasBlocksPluginName=Au=>`@datalayer/loop-plugin-ui-${Au}`;function uiPluginBlocks(Au){return{name:canvasBlocksPluginName(Au.id),displayName:Au.name,description:`The blocks of ${Au.name} on the Canvas: ${Au.components.map(lo=>lo.name).join(", ")}.`,octicon:"apps",contributes:Au.components.map(lo=>contribution(LoopCanvasBlock,{id:lo.id,ui:Au.id,component:lo},{id:lo.id}))}}const CANVAS_BLOCK_PLUGINS=listUI().filter(Au=>Au.components.length>0).map(uiPluginBlocks),MANAGER_PLUGIN_NAME="@datalayer/reactor-manager",MANAGER_ACTIONS_SLOT="manager-actions",ManagerPluginSource=defineContributionPoint("manager.pluginSource");function usePluginRows(Au,lo){const $u=useReactorPlatform(),Ru=reactExports.useSyncExternalStore($u.subscribe,()=>$u.getRevision());return reactExports.useMemo(()=>$u.listPlugins().filter(Iu=>!lo.has(Iu)).map(Iu=>{const Pu=$u.getManifest(Iu);return{name:Iu,displayName:Pu?.displayName??Iu,description:Pu?.description,emoji:Pu?.emoji,version:Pu?.version,enabled:$u.isEnabled(Iu),disabledBy:Pu?.disabledBy,changeable:!Au.has(Iu),details:[{label:"Delivered by",values:Pu?.extension?[Pu.extension]:[]},{label:"Contributes to",values:Pu?.contributesTo??[]},{label:"Offers contribution points",values:Pu?.contributionPoints??[]},{label:"Requires backend plugins",values:Pu?.requiredBackendPlugins??[]},{label:"Uses if available",values:Pu?.optionalBackendPlugins??[]},{label:"Activates on",values:Pu?.activationEvents??[]}]}}),[$u,Ru,Au,lo])}function pluginMatches(Au,lo){if(!lo)return!0;const $u=lo.trim().toLowerCase();return[Au.name,Au.displayName,Au.description??""].join(" ").toLowerCase().includes($u)}const PluginHoverContext=reactExports.createContext(null);function usePluginHoverControl(){const[Au,lo]=reactExports.useState(null),$u=reactExports.useRef(void 0);return reactExports.useEffect(()=>()=>clearTimeout($u.current),[]),reactExports.useMemo(()=>({openName:Au,show:Ru=>{clearTimeout($u.current),lo(Ru)},hide:()=>{clearTimeout($u.current),$u.current=setTimeout(()=>lo(null),200)}}),[Au])}function useHoverControl(){const Au=reactExports.useContext(PluginHoverContext),lo=usePluginHoverControl();return Au??lo}function PluginDetails({row:Au}){const lo=(Au.details??[]).filter($u=>$u.values.length>0);return jsxRuntimeExports.jsxs(Box,{sx:{p:3,maxWidth:360,display:"grid",gap:2},children:[jsxRuntimeExports.jsxs(Box,{sx:{display:"flex",alignItems:"center",gap:2},children:[Au.emoji?jsxRuntimeExports.jsx(Text$3,{"aria-hidden":!0,children:Au.emoji}):null,jsxRuntimeExports.jsx(Text$3,{sx:{fontWeight:"semibold"},children:Au.displayName}),Au.version?jsxRuntimeExports.jsxs(Text$3,{sx:{fontSize:0,color:"fg.muted"},children:["v",Au.version]}):null]}),jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:"fg.muted",wordBreak:"break-all"},children:Au.name}),Au.description?jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0},children:Au.description}):null,lo.map($u=>jsxRuntimeExports.jsxs(Box,{sx:{display:"grid",gap:1},children:[jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,fontWeight:"semibold"},children:$u.label}),$u.values.map(Ru=>jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:"fg.muted",wordBreak:"break-all"},children:Ru},Ru))]},$u.label)),Au.disabledBy==="dependency"?jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:"attention.fg"},children:"Off because something it depends on is off. It comes back when that does."}):null,Au.changeable?null:jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:"attention.fg"},children:"This one cannot be switched off."})]})}const OVERLAY_TAKES_NO_FOCUS={preventFocusOnOpen:!0,sx:{pointerEvents:"none"},returnFocusRef:{current:null}};function PluginRowView({row:Au,size:lo,onToggle:$u}){const Ru=`plugin-name-${Au.name.replace(/[^a-zA-Z0-9]+/g,"-")}`,Iu=useHoverControl(),Pu=Iu.openName===Au.name,Ou=()=>Iu.show(Au.name),Mu=()=>Iu.hide();return jsxRuntimeExports.jsx(AnchoredOverlay,{open:Pu,onOpen:Ou,onClose:Mu,focusZoneSettings:{disabled:!0},focusTrapSettings:{disabled:!0},overlayProps:OVERLAY_TAKES_NO_FOCUS,side:"outside-right",renderAnchor:Du=>jsxRuntimeExports.jsxs(Box,{...Du,onMouseEnter:Ou,onMouseLeave:Mu,onFocus:Ou,onBlur:Mu,sx:{display:"flex",alignItems:"flex-start",gap:2,py:2,borderBottom:"1px solid",borderColor:"border.muted"},children:[jsxRuntimeExports.jsxs(Box,{sx:{minWidth:0,flex:1},children:[jsxRuntimeExports.jsxs(Box,{sx:{display:"flex",alignItems:"center",gap:1},children:[Au.emoji?jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:1},"aria-hidden":!0,children:Au.emoji}):null,jsxRuntimeExports.jsx(Text$3,{id:Ru,sx:{fontSize:1,fontWeight:"semibold",minWidth:0},children:jsxRuntimeExports.jsx(Truncate,{title:Au.name,maxWidth:"100%",inline:!0,children:Au.displayName})})]}),Au.description?jsxRuntimeExports.jsx(Text$3,{sx:{display:"block",fontSize:0,color:"fg.muted"},children:jsxRuntimeExports.jsx(Truncate,{title:Au.description,maxWidth:"100%",inline:!0,children:Au.description})}):null]}),jsxRuntimeExports.jsx(ToggleSwitch,{size:lo,checked:Au.enabled,disabled:!Au.changeable||Au.disabledBy==="dependency","aria-labelledby":Ru,onClick:()=>{Au.changeable&&Au.disabledBy!=="dependency"&&$u(Au.name,!Au.enabled)}})]}),children:jsxRuntimeExports.jsx(PluginDetails,{row:Au})})}function PluginList({plugins:Au,query:lo="",switchSize:$u="small",onToggle:Ru,emptyMessage:Iu}){const Pu=reactExports.useMemo(()=>Au.filter(Ou=>pluginMatches(Ou,lo)),[Au,lo]);return Pu.length===0?jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:"fg.muted"},children:Iu??`No plugin matches “${lo}”.`}):jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:Pu.map(Ou=>jsxRuntimeExports.jsx(PluginRowView,{row:Ou,size:$u,onToggle:Ru},Ou.name))})}function PluginsManagerView({protectedPlugins:Au,hiddenPlugins:lo,switchSize:$u,width:Ru,...Iu}){const Pu=useReactorPlatform(),Ou=Pu.getConfig(MANAGER_PLUGIN_NAME)??{},Mu=reactExports.useMemo(()=>new Set(Au??Ou.protected??[MANAGER_PLUGIN_NAME]),[Au,Ou.protected]),Du=reactExports.useMemo(()=>new Set(lo??Ou.hidden??[]),[lo,Ou.hidden]),Lu=usePluginHoverControl(),Bu=usePluginRows(Mu,Du),[ju,Fu]=reactExports.useState(""),zu=$u??Ou.switchSize??"small",Uu=useContributions(ManagerPluginSource),Hu=reactExports.useMemo(()=>[...Uu].map(Vu=>Vu.value).sort((Vu,Gu)=>(Vu.order??100)-(Gu.order??100)),[Uu]);return jsxRuntimeExports.jsx(PluginHoverContext.Provider,{value:Lu,children:jsxRuntimeExports.jsxs(Box,{sx:{display:"flex",flexDirection:"column",gap:3,width:Ru??Ou.width??"100%",maxWidth:"100%",minWidth:0},children:[jsxRuntimeExports.jsx(ReactorSlot,{slot:MANAGER_ACTIONS_SLOT,props:Iu}),jsxRuntimeExports.jsxs(Box,{children:[jsxRuntimeExports.jsx(Text$3,{as:"h2",sx:{fontSize:1,fontWeight:"semibold",display:"block",mb:2},children:Ou.title??"Plugins"}),jsxRuntimeExports.jsx(TextInput$1,{leadingVisual:SearchIcon,value:ju,onChange:Vu=>Fu(Vu.target.value),"aria-label":"Filter plugins",placeholder:"Filter…",block:!0,size:"small"})]}),jsxRuntimeExports.jsx(Box,{children:jsxRuntimeExports.jsx(PluginList,{plugins:Bu,query:ju,switchSize:zu,onToggle:(Vu,Gu)=>Gu?Pu.enable(Vu):Pu.disable(Vu)})}),Hu.map(Vu=>jsxRuntimeExports.jsxs(Box,{children:[jsxRuntimeExports.jsx(Text$3,{as:"h3",sx:{fontSize:1,fontWeight:"semibold",display:"block",mb:2},children:Vu.title}),jsxRuntimeExports.jsx(Vu.Component,{query:ju,switchSize:zu})]},Vu.title))]})})}const PLUGINS_PANEL_PLUGIN_NAME="@datalayer/loop-plugin-plugins-panel",SIDEBAR_WIDTH=420,REACTOR_GRAPH_PLUGIN_NAME="@datalayer/reactor-graph",PluginsPanelPlugin={name:PLUGINS_PANEL_PLUGIN_NAME,displayName:"Plugins panel",description:"Switch plugins on and off while the workspace runs.",octicon:"plug",emoji:"🔌",build:()=>({components:[{id:"plugins-panel",slot:LoopSlots.sidebar,order:900,Component:({workspace:Au})=>jsxRuntimeExports.jsx(PluginsManagerView,{protectedPlugins:[PLUGINS_PANEL_PLUGIN_NAME],hiddenPlugins:[REACTOR_GRAPH_PLUGIN_NAME],width:SIDEBAR_WIDTH,workspace:Au})}]})};function ViewSwitcher({views:Au,workspace:lo,compact:$u=!1}){return Au.length<2?null:jsxRuntimeExports.jsx(Box,{role:"tablist","aria-label":"Workspace views",display:"inline-flex",alignItems:"center",bg:"neutral.muted",borderRadius:"6px",p:"2px",gap:"1px",children:Au.map(Ru=>{const Iu=Ru.value,Pu=canOpenView(Iu,lo),Ou=lo.activeViewType===Iu.viewType,Mu=Iu.icon,Du=Pu?Iu.title:`${Iu.title} — ${Iu.unavailableReason?.(lo)??"unavailable"}`;return jsxRuntimeExports.jsx(Tooltip,{text:Du,direction:"n",children:jsxRuntimeExports.jsxs(Box,{as:"button",role:"tab","aria-selected":Ou,"aria-disabled":!Pu,onClick:()=>Pu&&lo.setActiveViewType(Iu.viewType),display:"inline-flex",alignItems:"center",gap:1,border:"none",borderRadius:"5px",px:2,py:"4px",fontSize:0,cursor:Pu?"pointer":"not-allowed",opacity:Pu?1:.5,bg:Ou?"canvas.default":"transparent",color:Ou?"fg.default":"fg.muted",boxShadow:Ou?"shadow.small":"none",children:[Mu?jsxRuntimeExports.jsx(Mu,{size:14}):null,$u&&Mu?null:Iu.title]})},Iu.viewType)})})}const paneOpenKeyframes=Au=>Au==="left"?"loopPaneOpenLeft":"loopPaneOpenRight",paneOpenAnimation=Au=>`${paneOpenKeyframes(Au)} var(--theme-motion-pane, 0ms) var(--theme-motion-easing, ease) both`;function paneOpening(Au){const lo="12px";return{animation:paneOpenAnimation(Au),[`@keyframes ${paneOpenKeyframes(Au)}`]:{from:{opacity:0,transform:`translateX(${lo})`},to:{opacity:1,transform:"none"}},"@media (prefers-reduced-motion: reduce)":{animation:"none"}}}function railItemsOf(Au){return Au.map(lo=>({id:lo.id,label:lo.rail?.label??lo.id,icon:lo.rail?.icon??SidebarExpandIcon}))}function railChoiceAfter(Au,lo){return Au===lo?null:lo}const RAIL_WIDTH=48;function SidebarRail({components:Au,props:lo,width:$u}){const Ru=railItemsOf(Au),[Iu,Pu]=reactExports.useState(Ru[0]?.id??null),Ou=Ru.some(Mu=>Mu.id===Iu)?Iu:null;return jsxRuntimeExports.jsxs(Box,{as:"aside","data-loop-rail-sidebar":"",flex:"0 0 auto",display:"flex",minHeight:0,children:[jsxRuntimeExports.jsx(Box,{"data-loop-rail-panel":Ou??void 0,display:Ou?"block":"none",width:`${$u}px`,minWidth:0,borderLeft:"var(--theme-hairline, 1px) solid",borderColor:"border.default",overflowY:"auto",px:3,py:3,children:Au.map(Mu=>{const{Component:Du}=Mu,Lu=Mu.id===Ou;return jsxRuntimeExports.jsx(Box,{id:`loop-rail-panel-${Mu.id}`,role:"region","aria-label":railItemsOf([Mu])[0].label,hidden:!Lu,sx:Lu?paneOpening("right"):void 0,children:jsxRuntimeExports.jsx(Du,{...lo})},Mu.id)})}),jsxRuntimeExports.jsx(Box,{as:"nav","aria-label":"Panels",width:`${RAIL_WIDTH}px`,flex:`0 0 ${RAIL_WIDTH}px`,display:"flex",flexDirection:"column",alignItems:"center",gap:1,py:2,borderLeft:"var(--theme-hairline, 1px) solid",borderColor:"border.default",children:Ru.map(Mu=>{const Du=Mu.icon,Lu=Mu.id===Ou;return jsxRuntimeExports.jsx(Box,{as:"button",type:"button","data-loop-rail-item":Mu.id,"aria-label":Mu.label,title:Mu.label,"aria-pressed":Lu,"aria-controls":`loop-rail-panel-${Mu.id}`,onClick:()=>Pu(railChoiceAfter(Ou,Mu.id)),width:32,height:32,display:"inline-flex",alignItems:"center",justifyContent:"center",p:0,border:"none",borderRadius:2,cursor:"pointer",color:Lu?"fg.default":"fg.muted",bg:Lu?"neutral.muted":"transparent",hover:{color:"fg.default",bg:"neutral.subtle"},focusVisible:{outline:"2px solid",outlineColor:"var(--focus-outlineColor, #0969da)",outlineOffset:"1px"},children:jsxRuntimeExports.jsx(Du,{size:16})},Mu.id)})})]})}function buildLoopReactor(Au){return buildReactorFromPlugins(Au)}function LoopWorkspace(Au){const{serverUrl:lo,agentId:$u,conversationId:Ru,model:Iu,sandbox:Pu={state:"idle"},extensions:Ou=[],reactor:Mu,manageReactor:Du=!0,initialViewType:Lu,onSend:Bu,layout:ju="page",showViewSelector:Fu=!0,showHeader:zu=!0,chatHeaderActions:Uu,chatViewModes:Hu,headerActions:Vu,headerContainer:Gu,sidebarRail:Wu=!1}=Au,Ku=reactExports.useMemo(()=>Mu??buildLoopReactor(Ou),[Mu]);return useReactor(Ku,{autoStart:Du}),jsxRuntimeExports.jsx(WorkspaceBody,{serverUrl:lo,agentId:$u,conversationId:Ru,model:Iu,initialSandbox:Pu,initialViewType:Lu,onSend:Bu,layout:ju,showViewSelector:Fu,showHeader:zu,chatHeaderActions:Uu,chatViewModes:Hu,headerActions:Vu,headerContainer:Gu,sidebarRail:Wu})}function WorkspaceBody({serverUrl:Au,agentId:lo,conversationId:$u,model:Ru,initialSandbox:Iu,initialViewType:Pu,onSend:Ou,layout:Mu="page",showViewSelector:Du=!0,showHeader:Lu=!0,chatHeaderActions:Bu,chatViewModes:ju,headerActions:Fu,headerContainer:zu,sidebarRail:Uu=!1}){const[Hu,Vu]=reactExports.useState(lo),Gu=reactExports.useRef(loopSurfaceId($u??`session-${Date.now().toString(36)}`));reactExports.useEffect(()=>{Vu(lo)},[lo]);const[Wu,Ku]=reactExports.useState(void 0),Ju=reactExports.useCallback(ld=>{Ku(ud=>ud===ld?ud:ld)},[]),[Yu,Xu]=reactExports.useState(Pu??""),[ed,td]=reactExports.useState(Iu),[nd]=reactExports.useState(createPromptChannel),[od,sd]=reactExports.useState({}),ad=reactExports.useCallback(ld=>{sd(ld??{})},[]),pd=useContributions(LoopViewType),gd=useContributions(LoopCommand),Sd=useSlotComponents(LoopSlots.sidebar),_d=reactExports.useRef(gd),yd=reactExports.useRef(null),wd=Mu==="panel",Ad=reactExports.useCallback(async ld=>{const ud=parseCommand(ld);if(!ud)return Ou?.(ld,yd.current),nd.submit(ld)||Ou?{handled:!0}:{handled:!1,reason:"Nothing is listening for prompts in this view yet."};const hd=_d.current.find(Ed=>Ed.value.name===ud.name||(Ed.value.aliases??[]).includes(ud.name));if(!hd)return{handled:!1,command:ud.name,reason:`Unknown command: /${ud.name}. Type /help to see what there is.`};const vd=await hd.value.run({workspace:yd.current,argv:ud.argv});return vd?.prompt&&(Ou?.(vd.prompt,yd.current),nd.submit(vd.prompt)),{handled:!0,command:ud.name,result:vd??void 0}},[Ou,nd]),md=reactExports.useMemo(()=>({serverUrl:Au,agentId:Hu,surfaceId:Gu.current,setAgentId:Vu,conversationId:$u,thread:Wu,setThread:Ju,model:Ru,sandbox:ed,setSandbox:td,activeViewType:Yu,setActiveViewType:Xu,prompts:nd,submit:Ad,viewControls:od,setViewControls:ad,chatHeaderActions:Bu,chatViewModes:ju}),[Au,Hu,$u,Wu,Ru,ed,Yu,nd,Ad,od,ad,Bu,ju]);yd.current=md,_d.current=gd;const dd=reactExports.useMemo(()=>Yu||(pd.find(ud=>canOpenView(ud.value,md))?.value.viewType??""),[Yu,pd,md]);useReactorEvent(dd?onView(dd):void 0);const bd=jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[Fu,jsxRuntimeExports.jsx(ReactorSlot,{slot:LoopSlots.header,props:{workspace:md}}),Du?jsxRuntimeExports.jsx(ViewSwitcher,{views:pd,workspace:md,compact:wd}):null]});return jsxRuntimeExports.jsxs(Box,{"data-loop-workspace":"",display:"flex",flexDirection:"column",height:"100%",minHeight:0,position:"relative",bg:"canvas.default",color:"fg.default",children:[Lu&&zu?reactDomExports.createPortal(jsxRuntimeExports.jsx(Box,{display:"flex",alignItems:"center",flexWrap:"wrap",gap:2,children:bd}),zu):null,Lu&&zu===void 0?jsxRuntimeExports.jsx(Box,{as:"header",display:"flex",alignItems:"center",justifyContent:wd?"flex-start":"space-between",flexWrap:"wrap",gap:2,px:wd?2:3,py:2,borderBottom:"1px solid",borderColor:"border.default",flex:"0 0 auto",children:bd}):null,jsxRuntimeExports.jsxs(Box,{flex:"1 1 auto",minHeight:0,display:"flex",children:[jsxRuntimeExports.jsx(Box,{flex:"1 1 auto",minWidth:0,minHeight:0,position:"relative",children:jsxRuntimeExports.jsx(ReactorViewHost,{point:LoopViewType,active:dd,props:{viewType:dd,workspace:md},fallback:jsxRuntimeExports.jsx(Centered,{children:"Loading…"}),empty:jsxRuntimeExports.jsx(Centered,{children:"No view is available yet."}),errorFallback:ld=>jsxRuntimeExports.jsxs(Centered,{children:["This view failed to load: ",ld.message]})})}),Sd.length>0&&Uu&&!wd?jsxRuntimeExports.jsx(SidebarRail,{components:Sd,props:{workspace:md},width:SIDEBAR_WIDTH}):Sd.length>0?jsxRuntimeExports.jsx(Box,{as:"aside",flex:"0 0 auto",width:wd?"100%":`${SIDEBAR_WIDTH}px`,minWidth:0,borderLeft:wd?"none":"1px solid",borderTop:wd?"1px solid":"none",borderColor:"border.default",bg:"canvas.subtle",overflowY:"auto",px:3,py:3,children:jsxRuntimeExports.jsx(ReactorSlot,{slot:LoopSlots.sidebar,props:{workspace:md}})}):null]}),jsxRuntimeExports.jsxs(Box,{flex:"0 0 auto",children:[jsxRuntimeExports.jsx(ReactorSlot,{slot:LoopSlots.footer,props:{workspace:md}}),jsxRuntimeExports.jsx(ReactorSlot,{slot:LoopSlots.status,props:{workspace:md}})]}),jsxRuntimeExports.jsx(ReactorSlot,{slot:LoopSlots.root,props:{workspace:md}})]})}function Centered({children:Au}){return jsxRuntimeExports.jsx(Box,{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"fg.muted",fontSize:1,px:3,textAlign:"center",children:Au})}function resolveTopOffset(Au){if(typeof Au=="number")return Au;if(!Au||typeof document>"u")return 0;const lo=document.querySelector(Au);return lo?Math.max(0,Math.round(lo.getBoundingClientRect().bottom)):0}function fullScreenNode(Au){return Au?.closest("[data-loop-fullscreen-root]")??Au?.closest("[data-loop-workspace]")??Au}function useWorkspaceFullScreen(Au,lo={}){const{forceOverlay:$u=!1,paintOverlay:Ru=!1,topOffset:Iu=0}=lo,[Pu,Ou]=reactExports.useState(!1),Mu=reactExports.useRef(!1);reactExports.useEffect(()=>{const ju=()=>{if(!Mu.current)return;const Fu=!!document.fullscreenElement&&!!Au.current&&document.fullscreenElement.contains(Au.current);Ou(Fu),Fu||(Mu.current=!1)};return document.addEventListener("fullscreenchange",ju),()=>document.removeEventListener("fullscreenchange",ju)},[Au]);const Du=reactExports.useCallback(()=>{const ju=fullScreenNode(Au.current);if(Pu){Mu.current&&document.fullscreenElement?document.exitFullscreen():Ou(!1);return}if($u||Ru||!ju?.requestFullscreen){Ou(!0);return}Mu.current=!0,ju.requestFullscreen().then(()=>Ou(!0),()=>{Mu.current=!1,Ou(!0)})},[Au,Pu,$u,Ru]),[Lu,Bu]=reactExports.useState(0);return reactExports.useEffect(()=>{if(!Pu||Mu.current){Bu(0);return}const ju=()=>Bu(resolveTopOffset(Iu));return ju(),window.addEventListener("resize",ju),()=>window.removeEventListener("resize",ju)},[Pu,Iu]),reactExports.useEffect(()=>{if(!Ru||!Pu||Mu.current)return;const ju=fullScreenNode(Au.current);if(!ju)return;const Fu=ju.getAttribute("style");return ju.style.position="fixed",ju.style.top=`${Lu}px`,ju.style.right="0",ju.style.bottom="0",ju.style.left="0",ju.style.height="auto",ju.style.zIndex="1000",()=>{Fu===null?ju.removeAttribute("style"):ju.setAttribute("style",Fu)}},[Ru,Pu,Au,Lu]),reactExports.useEffect(()=>{if(!Pu||Mu.current)return;const ju=Fu=>{Fu.key==="Escape"&&!Fu.defaultPrevented&&Ou(!1)};return window.addEventListener("keydown",ju),()=>window.removeEventListener("keydown",ju)},[Pu]),{fullScreen:Pu,usingApi:Mu,toggle:Du,topOffsetPx:Lu}}function messageText(Au){const lo=Au.content;return typeof lo=="string"?lo:lo.map($u=>typeof $u=="string"?$u:$u.text??"").join("")}const isToolCall=Au=>Au.type==="tool-call";function conversationOf(Au){const lo=[];for(const $u of Au){if(isToolCall($u)){lo.push({role:"tool",name:$u.toolName,args:$u.args??{},...$u.result===void 0?{}:{result:$u.result}});continue}if($u.role!=="user"&&$u.role!=="assistant")continue;const Ru=messageText($u);Ru.trim()&&lo.push({role:$u.role,text:Ru})}return lo}const sameConversation=(Au,lo)=>Au.length===lo.length&&Au.every(($u,Ru)=>JSON.stringify($u)===JSON.stringify(lo[Ru])),IDLE={id:0,status:"idle"};function createTurnFeed(){const Au=signal$2(IDLE),lo=signal$2([]),$u=signal$2("idle");return{turn:Au,conversation:lo,presence:$u,setPresence:Ru=>{$u.value!==Ru&&($u.value=Ru)},items:Ru=>{const Iu=conversationOf(Ru);sameConversation(lo.value,Iu)||(lo.value=Iu)},begin:(Ru,Iu)=>{Au.value={id:Au.value.id+1,user:Ru,...Iu?{thread:Iu}:{},status:"thinking",usage:Au.value.usage}},assistant:Ru=>{const Iu=Au.value;Iu.status==="idle"||Iu.assistant===Ru||(Au.value={...Iu,assistant:Ru,status:Iu.status==="done"||Iu.status==="error"?Iu.status:Ru?"streaming":Iu.status})},usage:Ru=>{const Iu=Au.value;Iu.usage!==Ru&&(Au.value={...Iu,usage:Ru})},activity:Ru=>{const Iu=Au.value;Iu.status==="idle"||Iu.activity===Ru||(Au.value={...Iu,activity:Ru})},end:(Ru="done")=>{const Iu=Au.value;Iu.status!=="idle"&&(Au.value={...Iu,status:Ru,activity:void 0})}}}const TURN_WRITERS=Symbol.for("loop.chat.turn.writers");function feedWriters(Au){return{[TURN_WRITERS]:Au}}function turnWritersOf(Au){return Au?.[TURN_WRITERS]}const SESSION_RULE_DECISIONS=["allow","ask","deny"],SESSION_RULE_CLASSES=["read","write","send","buy","delete","execute"],SESSION_RULES_WORDS={title:"This session",none:"No rule of your own on this session yet.",noSession:"Start a conversation to add a rule to its session.",add:"Add",remove:"Remove",namePlaceholder:"A name, quoted in every sentence it decides",decisions:{allow:"do it",ask:"ask me first",deny:"leave it to me"},classes:{read:"reading",write:"writing",send:"sending",buy:"buying",delete:"deleting",execute:"running a command"},scopes:{organization:"your organization",team:"this application",session:"this session"},goneWithSession:"In force at once, for this session only; gone when it ends.",unavailable:Au=>`Nothing is decided right now: ${Au}`},WHERE_WORDS={inside:"inside the workspace",outside:"outside the workspace"};function sessionRuleInWords(Au){const lo=(Au.classes??[]).map(Ru=>SESSION_RULES_WORDS.classes[Ru]??Ru);let $u=lo.length>0?lo.join(", "):"everything";return(Au.where==="inside"||Au.where==="outside")&&($u=`${$u} ${WHERE_WORDS[Au.where]}`),Au.paths&&Au.paths.length>0&&($u=`${$u} (${Au.paths.join(", ")})`),Au.commands&&Au.commands.length>0&&($u=`${$u} matching ${Au.commands.map(Ru=>`\`${Ru}\``).join(" or ")}`),`${$u}: ${SESSION_RULES_WORDS.decisions[Au.decision]}`}const FILE_AND_SHELL_RULES=[{name:"Edit inside the workspace",decision:"allow",classes:["write"],where:"inside"},{name:"Ask before deleting a file",decision:"ask",classes:["delete"]},{name:"Ask before running a command",decision:"ask",classes:["execute"]},{name:"Leave files outside the workspace to me",decision:"deny",classes:["read","write","delete"],where:"outside"},{name:"Ask before git push",decision:"ask",classes:["execute"],commands:["^git\\s+push\\b"]},{name:"Ask before installing a package",decision:"ask",classes:["execute"],commands:["\\b(pip|npm|uv|yarn|apt(-get)?)\\s+(install|add)\\b"]},{name:"Leave sudo to me",decision:"deny",classes:["execute"],commands:["^sudo\\b"]}];function sessionRuleOf(Au){const lo=Au.name.trim();if(!lo)return"A rule needs a name: it is quoted in every sentence it decides.";if(!SESSION_RULE_DECISIONS.includes(Au.decision))return`A rule says ${SESSION_RULE_DECISIONS.join(", ")}, not “${Au.decision}”.`;const $u=Au.classes.filter(Ru=>SESSION_RULE_CLASSES.includes(Ru));return{name:lo,decision:Au.decision,classes:$u}}const sessionRulesUrl=(Au,lo)=>`${Au}/api/v1/apps/sessions/${encodeURIComponent(lo)}/rules`;function parsed(Au){try{return Au?JSON.parse(Au):null}catch{return null}}async function answered(Au,lo){const $u=parsed(await Au.text());if(!Au.ok){const Ru=$u&&typeof $u=="object"&&"detail"in $u?String($u.detail):`${lo} (${Au.status})`;throw new Error(Ru)}return $u}async function readSessionRules(Au,lo,$u,Ru=fetch){const Iu=await Ru(sessionRulesUrl(Au,$u),{headers:{Authorization:`Bearer ${lo}`}});return answered(Iu,"The rules of the session could not be read")}async function addSessionRule(Au,lo,$u,Ru,Iu=fetch){const Pu=await Iu(sessionRulesUrl(Au,$u),{method:"POST",headers:{Authorization:`Bearer ${lo}`,"Content-Type":"application/json"},body:JSON.stringify(Ru)});return answered(Pu,"The rule could not be added")}async function removeSessionRule(Au,lo,$u,Ru,Iu=fetch){const Pu=await Iu(`${sessionRulesUrl(Au,$u)}/${encodeURIComponent(Ru)}`,{method:"DELETE",headers:{Authorization:`Bearer ${lo}`}});return answered(Pu,"The rule could not be removed")}const SAVE_TOOL="save_to_space",SAVE_WORDS={approve:"Approve and save",decline:"Decline",where:Au=>Au?`To keep as a page of ${Au}:`:"To keep as a page of its Space:"};function draftOfApproval(Au){if(Au.tool_name!==SAVE_TOOL)return null;const lo=$u=>{const Ru=Au.tool_args?.[$u];return typeof Ru=="string"?Ru:""};return{title:lo("title"),content:lo("content"),space:lo("space")}}const APP_RULES_WORDS={title:"Rules and approvals",byDefault:"With no rule of its own: reading is done, anything else waits for you.",none:"It has no rule of its own.",waiting:"Waiting for you",nothingWaiting:"Nothing is waiting for your yes.",signedOut:"Its approvals reach you here once you are signed in to Datalayer.",offline:"Approvals are not connected yet: what you approve or reject is not sent until they are.",approve:"Approve",reject:"Reject"};function ruleInWords(Au){const lo=BEHAVIOUR_WORDS[Au.behaviour];return{action:Au.action,covers:Au.appliesTo.map(coverOf).join(", "),says:lo.says,means:lo.means}}const ruleOfApproval=Au=>{const lo=Au.tool_args?._rule??Au.tool_args?._check;return typeof lo=="string"?lo:""};function approvalsOfApp(Au,lo){return Au.filter($u=>$u.agent_id===lo||$u.tool_args?._app===lo)}const PENDING={status:"pending"};function DraftShown({draft:Au}){return jsxRuntimeExports.jsxs(Box,{"data-testid":"app-draft",mt:1,children:[jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{m:0,fontSize:0,color:"fg.muted"},children:SAVE_WORDS.where(Au.space)}),jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{m:0,fontWeight:"semibold"},children:Au.title}),jsxRuntimeExports.jsx(Box,{as:"pre",m:0,mt:1,p:2,maxHeight:240,overflow:"auto",whiteSpace:"pre-wrap",fontFamily:"inherit",fontSize:0,bg:"canvas.subtle",borderRadius:2,children:Au.content})]})}function Approvals({app:Au}){const lo=useToolApprovalsQuery(PENDING),$u=useApproveToolRequest(),Ru=useRejectToolRequest(),Iu=reactExports.useMemo(()=>approvalsOfApp(lo.data?.approvals??[],Au.id),[lo.data,Au.id]);return jsxRuntimeExports.jsxs(Box,{"data-testid":"app-approvals",children:[jsxRuntimeExports.jsx(Heading$2,{as:"h4",sx:{fontSize:1,mt:3,mb:1},children:APP_RULES_WORDS.waiting}),$u.connectionState!=="connected"?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:0,color:"fg.muted",m:0,mb:1},children:APP_RULES_WORDS.offline}):null,Iu.length===0?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:1,color:"fg.muted",m:0},children:APP_RULES_WORDS.nothingWaiting}):jsxRuntimeExports.jsx(Box,{as:"ul",listStyle:"none",p:0,m:0,children:Iu.map(Pu=>{const Ou=draftOfApproval(Pu);return jsxRuntimeExports.jsxs(Box,{as:"li",py:2,borderTop:"1px solid",borderColor:"border.muted",fontSize:1,children:[jsxRuntimeExports.jsx(Text$3,{sx:{fontWeight:"semibold"},children:Pu.tool_name}),ruleOfApproval(Pu)?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{m:0,color:"fg.muted",fontSize:0},children:ruleOfApproval(Pu)}):null,Ou?jsxRuntimeExports.jsx(DraftShown,{draft:Ou}):null,jsxRuntimeExports.jsxs(Box,{display:"flex",gap:2,mt:1,children:[jsxRuntimeExports.jsx(ButtonComponent,{size:"small",variant:"primary",disabled:$u.isPending,onClick:()=>$u.mutate({id:Pu.id}),children:Ou?SAVE_WORDS.approve:APP_RULES_WORDS.approve}),jsxRuntimeExports.jsx(ButtonComponent,{size:"small",disabled:Ru.isPending,onClick:()=>Ru.mutate({id:Pu.id}),children:Ou?SAVE_WORDS.decline:APP_RULES_WORDS.reject})]})]},Pu.id)})})]})}function SessionRules({agentServerUrl:Au,sessionUid:lo,token:$u}){const[Ru,Iu]=reactExports.useState(null),[Pu,Ou]=reactExports.useState(""),[Mu,Du]=reactExports.useState(""),[Lu,Bu]=reactExports.useState("ask"),[ju,Fu]=reactExports.useState("send"),[zu,Uu]=reactExports.useState(!1),Hu=reactExports.useCallback(()=>{let Wu=!1;return readSessionRules(Au,$u,lo).then(Ku=>!Wu&&Iu(Ku),Ku=>!Wu&&Ou(Ku instanceof Error?Ku.message:String(Ku))),()=>{Wu=!0}},[Au,$u,lo]);reactExports.useEffect(Hu,[Hu]);const Vu=async Wu=>{Uu(!0),Ou("");try{Iu(await Wu())}catch(Ku){Ou(Ku instanceof Error?Ku.message:String(Ku))}finally{Uu(!1)}},Gu=()=>{const Wu=sessionRuleOf({name:Mu,decision:Lu,classes:[ju]});if(typeof Wu=="string"){Ou(Wu);return}Vu(()=>addSessionRule(Au,$u,lo,Wu)).then(()=>Du(""))};return jsxRuntimeExports.jsxs(Box,{"data-testid":"session-rules",mt:3,children:[jsxRuntimeExports.jsx(Heading$2,{as:"h4",sx:{fontSize:1,mb:1},children:SESSION_RULES_WORDS.title}),Ru?.unavailable?jsxRuntimeExports.jsx(Text$3,{as:"p",role:"alert",sx:{fontSize:0,m:0,mb:1},children:SESSION_RULES_WORDS.unavailable(Ru.unavailable)}):null,Ru&&Ru.session_rules.length===0?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:1,color:"fg.muted",m:0},children:SESSION_RULES_WORDS.none}):jsxRuntimeExports.jsx(Box,{as:"ul",listStyle:"none",p:0,m:0,children:(Ru?.session_rules??[]).map(Wu=>jsxRuntimeExports.jsxs(Box,{as:"li",py:1,fontSize:1,display:"flex",gap:2,alignItems:"center",children:[jsxRuntimeExports.jsx(Text$3,{sx:{fontWeight:"semibold"},children:Wu.name}),jsxRuntimeExports.jsx(Text$3,{sx:{color:"fg.muted",fontSize:0},children:sessionRuleInWords(Wu)}),jsxRuntimeExports.jsx(ButtonComponent,{size:"small",variant:"invisible",disabled:zu,onClick:()=>{Vu(()=>removeSessionRule(Au,$u,lo,Wu.name))},children:SESSION_RULES_WORDS.remove})]},Wu.name))}),jsxRuntimeExports.jsxs(Box,{display:"flex",gap:1,mt:1,flexWrap:"wrap",alignItems:"center",children:[jsxRuntimeExports.jsx(TextInput$1,{size:"small",value:Mu,placeholder:SESSION_RULES_WORDS.namePlaceholder,"aria-label":"The rule's name",onChange:Wu=>Du(Wu.target.value)}),jsxRuntimeExports.jsx(Select$1,{size:"small",value:ju,"aria-label":"What it covers",onChange:Wu=>Fu(Wu.target.value),children:SESSION_RULE_CLASSES.map(Wu=>jsxRuntimeExports.jsx(Select$1.Option,{value:Wu,children:SESSION_RULES_WORDS.classes[Wu]},Wu))}),jsxRuntimeExports.jsx(Select$1,{size:"small",value:Lu,"aria-label":"What it says",onChange:Wu=>Bu(Wu.target.value),children:SESSION_RULE_DECISIONS.map(Wu=>jsxRuntimeExports.jsx(Select$1.Option,{value:Wu,children:SESSION_RULES_WORDS.decisions[Wu]},Wu))}),jsxRuntimeExports.jsx(ButtonComponent,{size:"small",disabled:zu,onClick:Gu,children:SESSION_RULES_WORDS.add})]}),jsxRuntimeExports.jsx(Box,{display:"flex",gap:1,mt:1,flexWrap:"wrap","data-testid":"session-rules-file-and-shell",children:FILE_AND_SHELL_RULES.map(Wu=>jsxRuntimeExports.jsx(ButtonComponent,{size:"small",variant:"invisible",disabled:zu,title:sessionRuleInWords(Wu),onClick:()=>{Vu(()=>addSessionRule(Au,$u,lo,Wu))},children:Wu.name},Wu.name))}),Pu?jsxRuntimeExports.jsx(Text$3,{as:"p",role:"alert",sx:{fontSize:0,m:0,mt:1},children:Pu}):null,jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:0,color:"fg.muted",mt:1,mb:0},children:SESSION_RULES_WORDS.goneWithSession})]})}function sessionUidOf(Au){return Au?.conversationId||Au?.thread||void 0}function AppRulesCard({app:Au,workspace:lo}){const $u=useIAMStore(Ou=>Ou.token)??"",Ru=!!$u,Iu=lo?agentServerOf(lo.sandbox,lo.serverUrl):void 0,Pu=sessionUidOf(lo);return jsxRuntimeExports.jsxs(Box,{"data-testid":"app-rules",mb:4,children:[jsxRuntimeExports.jsx(Heading$2,{as:"h3",sx:{fontSize:2,mb:2},children:APP_RULES_WORDS.title}),Au.rules.length===0?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:1,color:"fg.muted",m:0},children:APP_RULES_WORDS.none}):jsxRuntimeExports.jsx(Box,{as:"ul",listStyle:"none",p:0,m:0,children:Au.rules.map(ruleInWords).map((Ou,Mu)=>jsxRuntimeExports.jsxs(Box,{as:"li",py:1,fontSize:1,children:[jsxRuntimeExports.jsx(Text$3,{children:Ou.action})," ",jsxRuntimeExports.jsx(Label,{title:Ou.means,children:Ou.says}),jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{m:0,color:"fg.muted",fontSize:0},children:Ou.covers})]},Mu))}),jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:0,color:"fg.muted",mt:1,mb:0},children:APP_RULES_WORDS.byDefault}),Ru?jsxRuntimeExports.jsx(Approvals,{app:Au}):jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:1,color:"fg.muted",mt:3,mb:0},children:APP_RULES_WORDS.signedOut}),Ru&&Iu?Pu?jsxRuntimeExports.jsx(SessionRules,{agentServerUrl:Iu,sessionUid:Pu,token:$u}):jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:0,color:"fg.muted",mt:3,mb:0},children:SESSION_RULES_WORDS.noSession}):null]})}const SESSION_RULES_ACTION_WORDS={label:"Rules for this session…",title:"Rules for this session",noPanel:"Showing the session’s rules needs a panel this page has not: use the Rules card of the application’s page.",signedOut:"Sign in to see and add the rules of this session."},SESSION_RULES={id:"session-rules",label:SESSION_RULES_ACTION_WORDS.label,order:25,when:Au=>Au.state==="open",run:(Au,lo)=>{if(!lo.show){lo.say(SESSION_RULES_ACTION_WORDS.noPanel);return}const $u=lo.client.accessToken()??"";if(!$u){lo.say(SESSION_RULES_ACTION_WORDS.signedOut);return}lo.show({title:SESSION_RULES_ACTION_WORDS.title,render:()=>jsxRuntimeExports.jsx(SessionRules,{agentServerUrl:lo.client.serverUrl,token:$u,sessionUid:Au.uid})})}},sessionFileName=Au=>`${Au.uid}.session.jsonl`,SESSION_ACTION_WORDS={switchAgent:"Switch agent…",switchTitle:Au=>`Switch ${Au} to`,noPicker:"Switching the agent needs a picker this page has not: use `loop sessions swap`.",noAgents:"No other agent of the catalogue runs on a harness.",cloneFromHere:"Clone from here",cloned:(Au,lo)=>`Cloned from turn ${Au} as ${lo}: opened here, the source untouched.`,export:"Export",exported:(Au,lo,$u)=>`Exported ${Au} turn${Au===1?"":"s"}, ${lo} redaction${lo===1?"":"s"} → ${$u}.`,import:"Import…",noFilePicker:"Importing a session needs a file picker this page has not: use `loop sessions import`.",imported:(Au,lo,$u)=>`Imported as ${Au} (${lo} turn${lo===1?"":"s"}, ${$u} redaction${$u===1?"":"s"}): opened here.`,resume:"Resume",resumed:Au=>`Resumed ${Au}.`};function agentChoices(Au){const lo=listAgentspecs();return listHarnesses().filter($u=>$u.id!=="custom"&&$u.enabled).flatMap($u=>{const Ru=lo.find(Iu=>Iu.harness===$u.id);return!Ru||Ru.id===Au.agent?[]:[{id:Ru.id,label:`${Ru.name} (${$u.name})`,description:$u.description}]})}const spokenAs=(Au,lo)=>(lo?listHarnesses().find(Ru=>Ru.id===lo):void 0)?.name??(lo||Au);function swapSentence(Au,lo){const $u=spokenAs(Au.agent,Au.harness),Ru=lo.label.replace(/\s*\(.*\)$/,"");return`This conversation was with ${$u} until turn ${Au.turns}; from here it is with ${Ru}. What was said stays.`}const idle=Au=>Au.state==="open"&&Au.turn==="idle";function redactionsOf(Au){const lo=Au.split(`
3857
+ `)[0]??"";try{return Number(JSON.parse(lo).redactions??0)||0}catch{return 0}}const SWITCH_AGENT={id:"switch-agent",label:SESSION_ACTION_WORDS.switchAgent,order:10,when:idle,run:async(Au,lo)=>{if(!lo.choose){lo.say(SESSION_ACTION_WORDS.noPicker);return}const $u=agentChoices(Au);if($u.length===0){lo.say(SESSION_ACTION_WORDS.noAgents);return}const Ru=await lo.choose({title:SESSION_ACTION_WORDS.switchTitle(Au.agent),options:$u,says:async Pu=>{const Ou=$u.find(Mu=>Mu.id===Pu);return Ou?swapSentence(Au,Ou):""}});if(!Ru)return;const Iu=await lo.client.swap(Au.uid,Ru);lo.say(String(Iu.said??`Swapped to ${Ru}.`))}},CLONE_FROM_HERE={id:"clone-from-here",label:SESSION_ACTION_WORDS.cloneFromHere,order:20,placement:"both",when:Au=>Au.turns>0,run:async(Au,lo)=>{const $u=lo.atTurn??Au.turns,Ru=await lo.client.clone(Au.uid,{upToTurn:$u}),Iu=String(Ru.uid??"");if(!Iu)throw new Error(`The runtime cloned session ${Au.uid} and named no new session.`);lo.say(SESSION_ACTION_WORDS.cloned($u,Iu)),lo.openThread?.(Iu)}},EXPORT={id:"export",label:SESSION_ACTION_WORDS.export,order:30,when:Au=>Au.turns>0,run:async(Au,lo)=>{const $u=await lo.client.exportFile(Au.uid),Ru=sessionFileName(Au);lo.download?.(Ru,$u,"application/x-ndjson"),lo.say(SESSION_ACTION_WORDS.exported(Au.turns,redactionsOf($u),Ru))}},IMPORT={id:"import",label:SESSION_ACTION_WORDS.import,order:35,when:()=>!0,run:async(Au,lo)=>{if(!lo.pickFile){lo.say(SESSION_ACTION_WORDS.noFilePicker);return}const $u=await lo.pickFile(".jsonl,application/x-ndjson");if(!$u)return;const Ru=await lo.client.importFile($u),Iu=String(Ru.uid??"");if(!Iu)throw new Error("The runtime imported the file and named no session.");lo.say(SESSION_ACTION_WORDS.imported(Iu,Number(Ru.turns??0)||0,Number(Ru.redactions??0)||0)),lo.openThread?.(Iu)}},RESUME={id:"resume",label:SESSION_ACTION_WORDS.resume,order:40,divider:!0,when:Au=>Au.state==="paused",run:async(Au,lo)=>{await lo.client.resume(Au.uid,Au.agent,{onEvent:()=>{}}),lo.say(SESSION_ACTION_WORDS.resumed(Au.uid)),lo.openThread?.(Au.uid)}},CHAT_SESSION_ACTIONS=[SWITCH_AGENT,CLONE_FROM_HERE,SESSION_RULES,EXPORT,IMPORT,RESUME];function agentAction(Au,lo){const{prompt:$u,...Ru}=lo;return{...Ru,type:"button",group:"agent",onClick:()=>Au.workspace.prompts.submit($u)}}const CHAT_PLUGIN_NAME="@datalayer/loop-plugin-chat",ChatPlugin={name:CHAT_PLUGIN_NAME,config:{placeholder:"",defaultSurface:"notebook",showSurfaceSelector:!0,hideHeader:!1,headerButtons:{newChat:!1,clear:!1},hidePrompt:!1,promptPlacement:"bottom",autoFocusPrompt:!0,suggestionLabels:!0,fullScreenTopOffset:0},displayName:"Chat",description:"The conversation, the prompt, and the point editors plug into.",octicon:"comment-discussion",emoji:"💬",contributionPoints:[LoopAgentGate,LoopFrontendTool,LoopChatComposer,LoopChatHeader,LoopChatSuggestion,LoopChatExtras,LoopChatTurn],build:Au=>{const lo=createTurnFeed();return Au.contribute(LoopChatTurn,{id:"chat-turn",turn:lo.turn,conversation:lo.conversation,presence:lo.presence,...feedWriters(lo)},{id:"chat-turn"}),{}},contributes:[...CHAT_SESSION_ACTIONS.map(Au=>contribution(LoopSessionAction,Au,{id:Au.id,order:Au.order})),contribution(LoopViewType,{viewType:"chat",title:"Chat",icon:CommentDiscussionIcon,order:0,load:()=>__vitePreload(()=>import("./chunks/ChatView-uYgfl4KN.js"),[],import.meta.url)},{id:"chat",order:0}),contribution(LoopCommand,{name:"chat",description:"Show the conversation",group:"Session",keybinding:"Mod+Alt+K",run:async({workspace:Au})=>{Au.setActiveViewType("chat")}},{id:"chat"}),contribution(LoopNotebookToolbarItem,{items:Au=>[agentAction(Au,{key:"loop-compact",ariaLabel:"Compact this notebook",title:"Ask @NotebookCompactor to shorten it without changing results",icon:FoldIcon,order:200,prompt:"@NotebookCompactor compact this notebook without changing what it computes."}),agentAction(Au,{key:"loop-reproduce",ariaLabel:"Check reproducibility",title:"Ask @NotebookReproducer to run it on a fresh sandbox",icon:SyncIcon,order:201,prompt:"@NotebookReproducer run this notebook top to bottom on a fresh sandbox and report what does not reproduce."})]},{id:"agent-actions",order:200}),contribution(LoopDocumentToolbarItem,{items:Au=>[agentAction(Au,{key:"loop-summarise",ariaLabel:"Summarise this document",title:"Ask the agent for a summary of what this document says",icon:SparkleFillIcon,order:200,prompt:"Summarise this document in a short paragraph."})]},{id:"agent-actions",order:200})]};function WorkspaceFullScreenAction(){const Au=reactExports.useRef(null),$u=useReactorPlatform().getConfig(CHAT_PLUGIN_NAME)?.fullScreenTopOffset??0,{fullScreen:Ru,toggle:Iu}=useWorkspaceFullScreen(Au,{paintOverlay:!!$u,topOffset:$u});return jsxRuntimeExports.jsx(IconButton,{ref:Au,icon:Ru?ScreenNormalIcon:ScreenFullIcon,"aria-label":Ru?"Exit full screen":"Enter full screen",variant:"invisible",size:"small",sx:{order:2},onClick:Iu})}const THEME_PLUGIN_NAME="@datalayer/primer-theme",TOGGLE_COLOR_MODE_COMMAND="theme.toggleColorMode",ThemePlugin={name:THEME_PLUGIN_NAME,displayName:"Theme",description:"Keeps Primer portals in the application’s color mode, and toggles it.",octicon:"sun",emoji:"🌗",commands:[{id:TOGGLE_COLOR_MODE_COMMAND,name:"Toggle the color mode",description:"Switch between light and dark",emoji:"🌗",category:"Appearance",keybinding:"Mod+Alt+C",execute:()=>{const Au=useThemeStore.getState(),lo=Au.colorMode==="auto"?typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light":Au.colorMode;Au.setColorMode(lo==="dark"?"light":"dark")}}],register:()=>{if(typeof document>"u")return;setupPrimerPortals(useThemeStore.getState().colorMode);const Au=useThemeStore.subscribe((Ru,Iu)=>{Ru.colorMode!==Iu.colorMode&&setupPrimerPortals(Ru.colorMode)}),lo=window.matchMedia("(prefers-color-scheme: dark)"),$u=()=>{useThemeStore.getState().colorMode==="auto"&&setupPrimerPortals("auto")};return lo.addEventListener("change",$u),()=>{Au(),lo.removeEventListener("change",$u)}}},pageLayoutPanelOpen=signal$2(!1),pageLayoutSheet=signal$2("page"),pageLayoutActivity=signal$2(void 0);function openPagePanel(){pageLayoutPanelOpen.value=!0}const PAGE_SHEET_WIDTH=920,PAGE_PANEL_WIDTH=400,PAGE_SIZE_FORMATS={letter:{width:816,height:1056},a4:{width:794,height:1123}};function resolvePageSize(Au,lo=PAGE_SHEET_WIDTH){const $u=Au?.format&&Au.format!=="free"?PAGE_SIZE_FORMATS[Au.format]:void 0;return{width:Au?.width??$u?.width??lo,height:Au?.height??$u?.height}}const CANVAS_PX=[2,3,4];function ActivityLine({label:Au}){return jsxRuntimeExports.jsxs(Box$1,{"data-page-activity":"",role:"status",sx:{position:"sticky",top:0,zIndex:2,alignSelf:"flex-start",display:"inline-flex",alignItems:"center",gap:2,px:2,py:"4px",borderRadius:"999px",border:"1px solid",borderColor:"accent.muted",bg:"accent.subtle",color:"accent.fg",fontSize:0,fontWeight:"semibold",whiteSpace:"nowrap",boxShadow:"0 4px 12px -6px rgba(0,0,0,0.3)"},children:[jsxRuntimeExports.jsx(Box$1,{as:"span","aria-hidden":"true",sx:{width:7,height:7,borderRadius:"50%",bg:"accent.fg",animation:"page-activity-dot 1.1s ease-in-out infinite","@keyframes page-activity-dot":{"0%, 100%":{opacity:1},"50%":{opacity:.3}}}}),jsxRuntimeExports.jsx(Text$3,{children:Au})]})}function panelOpening(Au){const lo=Au==="left"?"pagePanelOpenLeft":"pagePanelOpenRight";return{animation:`${lo} var(--theme-motion-pane, 0ms) var(--theme-motion-easing, ease) both`,[`@keyframes ${lo}`]:{from:{opacity:0,transform:`translateX(${Au==="left"?"-12px":"12px"})`},to:{opacity:1,transform:"none"}},"@media (prefers-reduced-motion: reduce)":{animation:"none"}}}function PageLayout({page:Au,hasPage:lo=Au!=null,panel:$u,band:Ru,chips:Iu,picker:Pu,transient:Ou,activity:Mu,bandMode:Du="docked",panelMode:Lu="docked",panelSide:Bu="right",sheetWidth:ju=PAGE_SHEET_WIDTH,pageSize:Fu,panelWidth:zu=PAGE_PANEL_WIDTH}){const Uu=Du==="panel",Hu=Ru!=null,{width:Vu,height:Gu}=resolvePageSize(Fu,ju),Ku=useSignalValue$1(pageLayoutPanelOpen)||Uu&&Hu,Ju=useSignalValue$1(pageLayoutActivity),Yu=Mu??Ju,Xu=lo?"page":"panel";return reactExports.useEffect(()=>{pageLayoutSheet.value=Xu},[Xu]),jsxRuntimeExports.jsxs(Box$1,{"data-page-layout":"",sx:{position:"relative",flex:"1 1 auto",minHeight:0,display:"flex",flexDirection:"column"},children:[Pu,jsxRuntimeExports.jsxs(Box$1,{sx:{flex:"1 1 auto",minHeight:0,display:"flex",bg:"canvas.inset"},children:[jsxRuntimeExports.jsxs(Box$1,{sx:{flex:"1 1 auto",minWidth:0,minHeight:0,display:"flex",flexDirection:"column"},children:[Ru&&Du==="docked"?jsxRuntimeExports.jsx(Box$1,{"data-page-band":"","data-page-prompt-dock":"",sx:{flex:"0 0 auto",display:"flex",justifyContent:"center",px:CANVAS_PX,bg:"canvas.subtle",borderBottom:"1px solid",borderColor:"border.default"},children:jsxRuntimeExports.jsx(Box$1,{sx:{width:"100%",maxWidth:Vu,minWidth:0},children:Ru})}):null,jsxRuntimeExports.jsxs(Box$1,{"data-page-canvas":"",sx:{flex:"1 1 auto",minWidth:0,minHeight:0,overflowY:lo?"auto":"hidden",overflowX:"hidden",display:"flex",flexDirection:"column",alignItems:"center",pt:3,pb:6,px:CANVAS_PX},children:[Ru&&Iu&&!Uu?jsxRuntimeExports.jsx(Box$1,{sx:{width:"100%",maxWidth:Vu,mb:3,display:"flex",justifyContent:"center","& > *":{justifyContent:"center"}},children:Iu}):null,Yu?jsxRuntimeExports.jsx(Box$1,{sx:{width:"100%",maxWidth:Vu,display:"flex",justifyContent:"flex-end",mb:2},children:jsxRuntimeExports.jsx(ActivityLine,{label:Yu})}):null,jsxRuntimeExports.jsx(Sheet,{"data-page-sheet":"",sx:{width:"100%",maxWidth:Vu,flex:lo?"1 0 auto":"1 1 auto",px:lo?[3,4,"56px"]:[2,3,4],py:lo?[3,4,4]:2,position:"relative",display:"flex",minHeight:lo?Gu??480:0,"& > *":{flex:"1 1 auto",minWidth:0}},children:lo?Au:$u}),lo||!Au?null:jsxRuntimeExports.jsx(Box$1,{"aria-hidden":"true",sx:{position:"absolute",inset:0,visibility:"hidden",pointerEvents:"none",zIndex:-1,display:"flex"},children:Au})]})]}),!lo||!$u?null:jsxRuntimeExports.jsxs(Box$1,{"data-page-panel":Ku?"":void 0,"data-page-panel-mode":Lu,"aria-hidden":Ku?void 0:"true",sx:{minWidth:0,minHeight:0,display:"flex",flexDirection:"column",bg:"canvas.default",borderColor:"border.default",...Ku?Lu==="docked"?{flex:`0 0 ${zu}px`,maxWidth:"45%",order:Bu==="left"?-1:void 0,[Bu==="left"?"borderRight":"borderLeft"]:"1px solid",zIndex:1}:Lu==="overlay"?{position:"absolute",top:0,bottom:0,[Bu]:0,width:zu,maxWidth:"85%",[Bu==="left"?"borderRight":"borderLeft"]:"1px solid",boxShadow:"shadow.large",zIndex:5}:{position:"absolute",[Bu]:16,bottom:16,width:zu,maxWidth:"calc(100% - 32px)",height:"min(70%, 560px)",border:"1px solid",borderRadius:2,boxShadow:"shadow.large",overflow:"hidden",zIndex:5}:{position:"absolute",inset:0,visibility:"hidden",pointerEvents:"none",overflow:"visible"}},children:[jsxRuntimeExports.jsx(Box$1,{sx:{flex:"1 1 auto",minHeight:0,display:"flex",flexDirection:"column","& > *":{flex:"1 1 auto",minHeight:0},...Ku?panelOpening(Bu):null},children:$u}),Hu&&Du!=="docked"?jsxRuntimeExports.jsxs(Box$1,{"data-page-panel-band":Uu?"":void 0,sx:Uu?{flex:"0 0 auto",borderTop:"1px solid",borderColor:"border.default",visibility:"visible",pointerEvents:"auto","& > *":{justifyContent:"center"}}:{position:"absolute",inset:0,visibility:"visible",pointerEvents:"none","& > *":{pointerEvents:"auto"}},children:[Uu?Iu:null,Ru]}):null]})]}),Ou]})}function PagePanelToggle({panelName:Au="panel",icon:lo=SidebarExpandIcon,sx:$u}){const Ru=useSignalValue$1(pageLayoutPanelOpen);return useSignalValue$1(pageLayoutSheet)==="panel"?null:jsxRuntimeExports.jsx(IconButton,{icon:lo,size:"small",variant:Ru?"default":"invisible","aria-label":Ru?`Hide the ${Au}`:`Show the ${Au}`,"aria-pressed":Ru,onClick:()=>{Ru?pageLayoutPanelOpen.value=!1:openPagePanel()},sx:{color:Ru?"accent.fg":"fg.muted",...$u}})}const INPUT_PROMPT_PLUGIN_NAME="@datalayer/loop-plugin-input-prompt",LazyComposerView=reactExports.lazy(()=>__vitePreload(()=>import("./chunks/ComposerView-B-gxvk_X.js"),[],import.meta.url));function ComposerView(Au){return jsxRuntimeExports.jsx(reactExports.Suspense,{fallback:null,children:jsxRuntimeExports.jsx(LazyComposerView,{...Au})})}const InputPromptPlugin={name:INPUT_PROMPT_PLUGIN_NAME,config:{},displayName:"Input Prompt",description:"The composer under (or over) the conversation.",octicon:"pencil",emoji:"✏️",contributionPoints:[LoopPromptPanel],contributes:[contribution(LoopChatComposer,{id:"input-prompt",Component:ComposerView},{id:"input-prompt"})]},AGENT_ICONS={agent:ForwardRef$2,beaker:BeakerIcon,bell:BellIcon,book:BookIcon,briefcase:BriefcaseIcon,browser:BrowserIcon,bug:BugIcon,clock:ClockIcon,code:CodeIcon,"comment-discussion":CommentDiscussionIcon,cpu:CpuIcon,"credit-card":CreditCardIcon,database:DatabaseIcon,file:FileIcon,checklist:ChecklistIcon,"code-review":CodeReviewIcon,fold:FoldIcon,"git-branch":GitBranchIcon,globe:GlobeIcon,graph:GraphIcon,heart:HeartIcon,"issue-opened":IssueOpenedIcon,lightbulb:LightBulbIcon,"light-bulb":LightBulbIcon,"list-unordered":ListUnorderedIcon,mail:MailIcon,megaphone:MegaphoneIcon,"mortar-board":MortarBoardIcon,note:NoteIcon,organization:OrganizationIcon,package:PackageIcon,pencil:PencilIcon,people:PeopleIcon,play:PlayIcon,pulse:PulseIcon,rss:RssIcon,search:SearchIcon,"share-2":ShareAndroidIcon,shield:ShieldIcon,"shield-check":ShieldCheckIcon,sliders:SlidersIcon,sun:SunIcon,sync:SyncIcon,table:TableIcon,tag:TagIcon,tasklist:TasklistIcon,telescope:TelescopeIcon,tools:ToolsIcon,"trending-up":GraphIcon,rocket:RocketIcon,zap:ZapIcon};function agentIcon(Au){return(Au?AGENT_ICONS[Au]:void 0)??ForwardRef$2}function useOptionalSandboxService(){return useReactorPlatform().getOutput(AGENTS_PLUGIN_NAME)?.sandbox}function useSandboxService(){const Au=useOptionalSandboxService();if(!Au)throw new Error(`The code sandbox plugin (${AGENTS_PLUGIN_NAME}) is not mounted. A view that needs a sandbox must declare it as a dependency.`);return Au}function SandboxStatusBridge({workspace:Au}){const lo=useOptionalSandboxService(),$u=useSignalValue$1(lo?.snapshot??IDLE_SANDBOX_SNAPSHOT_SIGNAL),Ru=useSignalValue$1(lo?.target??IDLE_SANDBOX_TARGET_SIGNAL),{setSandbox:Iu,agentId:Pu}=Au;return reactExports.useEffect(()=>lo?.connect(Pu),[lo,Pu]),reactExports.useEffect(()=>{lo&&Iu({...$u,target:Ru})},[lo,$u,Ru,Iu]),null}const DatalayerAgentBridge=reactExports.lazy(async()=>({default:(await __vitePreload(()=>import("./chunks/DatalayerAgentBridge-BNuZDTPn.js"),[],import.meta.url)).DatalayerAgentBridge}));function DatalayerAgentMount(){return jsxRuntimeExports.jsx(reactExports.Suspense,{fallback:null,children:jsxRuntimeExports.jsx(DatalayerAgentBridge,{})})}const CREATING_STATUSES=new Set(["creating","starting","launching","connecting","pending","resuming"]);function isCreatingAgent(Au){return!Au.isReady&&!Au.agentId&&CREATING_STATUSES.has((Au.status||"").toLowerCase())}const MAX_AGENT_NAME_LENGTH=32,toSandboxStatusUrl=Au=>{const lo=String(Au||"").trim();if(lo)try{const $u=new URL(lo);return $u.pathname=`${$u.pathname.replace(/\/$/,"")}/api`,$u.toString()}catch{const $u=lo.replace(/\/$/,"");return $u.endsWith("/api")?$u:`${$u}/api`}},OVERLAY_WIDTH=360,AgentSummary=({summary:Au,title:lo="Active Agent"})=>{const[$u,Ru]=reactExports.useState(!1),[Iu,Pu]=reactExports.useState(!1),Ou=reactExports.useRef(null),Mu=reactExports.useRef(null),Du=()=>{Mu.current!==null&&(window.clearTimeout(Mu.current),Mu.current=null)},Lu=()=>{Du();const Ju=Ou.current?.getBoundingClientRect();Pu(!!(Ju&&Ju.left+OVERLAY_WIDTH>window.innerWidth)),Ru(!0)},Bu=()=>{Du(),Mu.current=window.setTimeout(()=>{Ru(!1),Mu.current=null},300)};reactExports.useEffect(()=>()=>{Du()},[]);const ju=Au?.baseUrl?(()=>{const Ju=Au.baseUrl.replace(/\/$/,"");return Ju.endsWith("/api/v1")?Ju:`${Ju}/api/v1`})():void 0,Fu=ju?`${ju}/runtime/status`:void 0,zu=toSandboxStatusUrl(Au?.sandboxBaseUrl);if(!Au)return null;const Uu=isCreatingAgent(Au),Hu=!!Au.error,Vu=!!Au.agentId||Uu,Gu=strip(Au.agentName,MAX_AGENT_NAME_LENGTH),Wu=`${Au.agentName} · ${Au.location}`,Ku=`${Gu} · ${Au.location}`;return jsxRuntimeExports.jsxs(Box,{ref:Ou,position:"relative",onMouseEnter:Lu,onMouseLeave:Bu,children:[jsxRuntimeExports.jsxs(Box,{as:"button",type:"button",title:Wu,px:2,py:"6px",maxWidth:280,minWidth:0,border:"1px solid",borderColor:Hu?"danger.emphasis":"border.default",borderRadius:2,bg:Hu?"danger.subtle":"canvas.default",color:Hu?"danger.fg":"fg.default",fontSize:0,cursor:"default",display:"flex",alignItems:"center",gap:1,children:[Uu&&jsxRuntimeExports.jsx(StyledSpinner,{size:"small",sx:{width:12,height:12}}),Hu&&jsxRuntimeExports.jsx("span",{"aria-hidden":!0,children:"⚠"}),jsxRuntimeExports.jsx(Box,{as:"span",display:"block",minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",children:Ku})]}),$u&&jsxRuntimeExports.jsxs(Box,{position:"absolute",top:"calc(100% + 8px)",width:OVERLAY_WIDTH,p:2,border:"1px solid",borderColor:"border.default",borderRadius:2,bg:"canvas.overlay",boxShadow:"shadow.large",zIndex:120,fontSize:0,color:"fg.default",right:Iu?0:void 0,left:Iu?void 0:0,children:[jsxRuntimeExports.jsx(Box,{mb:1,fontWeight:600,children:lo}),jsxRuntimeExports.jsxs(Box,{color:"fg.muted",children:["Name: ",Au.agentName]}),jsxRuntimeExports.jsxs(Box,{color:"fg.muted",children:["Location: ",Au.location]}),jsxRuntimeExports.jsxs(Box,{color:"fg.muted",children:["Spec: ",Au.specId||"—"]}),jsxRuntimeExports.jsxs(Box,{color:"fg.muted",children:["Harness: ",Au.harness||"—"]}),jsxRuntimeExports.jsxs(Box,{color:"fg.muted",children:["Variant: ",Au.variant||"—"]}),jsxRuntimeExports.jsxs(Box,{color:"fg.muted",children:["Status: ",Uu?"creating":Au.status||"—"]}),jsxRuntimeExports.jsxs(Box,{color:"fg.muted",wordBreak:"break-all",children:["Agent base URL: ",Au.baseUrl||"—"]}),jsxRuntimeExports.jsxs(Box,{color:"fg.muted",wordBreak:"break-all",children:["Code sandbox base URL:"," ",Au.sandboxBaseUrl?jsxRuntimeExports.jsx(Box,{as:"a",href:Au.sandboxBaseUrl,target:"_blank",rel:"noopener noreferrer",color:"accent.fg",textDecoration:"underline",children:Au.sandboxBaseUrl}):"—"]}),jsxRuntimeExports.jsxs(Box,{color:"fg.muted",wordBreak:"break-all",display:"flex",alignItems:"center",gap:1,children:["Agent ID:"," ",Au.agentId?Au.agentId:Uu?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(StyledSpinner,{size:"small",sx:{width:12,height:12}}),"Creating…"]}):"—"]}),jsxRuntimeExports.jsxs(Box,{color:"fg.muted",wordBreak:"break-all",children:["Agent status:"," ",Vu&&Fu?jsxRuntimeExports.jsx(Box,{as:"a",href:Fu,target:"_blank",rel:"noopener noreferrer",color:"accent.fg",textDecoration:"underline",children:Fu}):"n/a"]}),jsxRuntimeExports.jsxs(Box,{color:"fg.muted",wordBreak:"break-all",children:["Code sandbox status:"," ",zu?jsxRuntimeExports.jsx(Box,{as:"a",href:zu,target:"_blank",rel:"noopener noreferrer",color:"accent.fg",textDecoration:"underline",children:zu}):"n/a"]}),Hu&&jsxRuntimeExports.jsxs(Box,{mt:1,p:1,border:"1px solid",borderColor:"danger.muted",borderRadius:2,bg:"danger.subtle",color:"danger.fg",wordBreak:"break-word",children:["Error: ",Au.error]})]})]})},insideJupyterLab=()=>loadJupyterConfig().insideJupyterLab;function collect(Au,lo){const $u=Au?.header?.msg_type,Ru=Au?.content??{};$u==="stream"?(lo.stdout.push(String(Ru.text??"")),lo.outputs.push({output_type:"stream",text:Ru.text})):$u==="execute_result"||$u==="display_data"?lo.outputs.push({output_type:$u,data:Ru.data}):$u==="error"&&(lo.error=`${Ru.ename??"Error"}: ${Ru.evalue??""}`,lo.outputs.push({output_type:"error",ename:Ru.ename,evalue:Ru.evalue,traceback:Ru.traceback}))}function browserSource(){let Au;return{variant:"pyodide",acquire:async()=>{const{createLiteServiceManager:lo,jupyterReactStore:$u,loadJupyterConfig:Ru}=await __vitePreload(async()=>{const{createLiteServiceManager:Pu,jupyterReactStore:Ou,loadJupyterConfig:Mu}=await import("./chunks/index-BOGJMsUN.js").then(Du=>Du.r);return{createLiteServiceManager:Pu,jupyterReactStore:Ou,loadJupyterConfig:Mu}},[],import.meta.url);Au=Au??{baseUrl:libExports$5.PageConfig.getOption("baseUrl"),wsUrl:libExports$5.PageConfig.getOption("wsUrl")},Ru({lite:!0});const Iu=await lo();return $u.getState().setServiceManager(Iu),Iu},release:()=>{Au&&(libExports$5.PageConfig.setOption("baseUrl",Au.baseUrl),libExports$5.PageConfig.setOption("wsUrl",Au.wsUrl),Au=void 0)},owned:!0}}function createBrowserSandboxService(Au=browserSource()){const lo=signal$2(null),$u=signal$2("idle"),Ru=signal$2(null),Iu=computed$1(()=>({state:$u.value,variant:Au.variant,kernelId:lo.value?.kernel_id})),Pu=computed$1(()=>$u.value==="running");let Ou=null,Mu=null,Du=null,Lu=null;async function Bu(){if(Mu)return;$u.value="starting",Ou=await Au.acquire();const ju=await Ou.sessions.startNew({name:"loop",path:"loop.ipynb",type:"notebook",kernel:{name:"python"}});Du=ju.kernel,Mu=ju.kernel,lo.value={variant:Au.variant,sandbox_running:!0,kernel_id:Mu?.id,kernel_name:"python"},$u.value="running"}return{kind:"browser",snapshot:Iu,status:lo,ready:Pu,lastExecution:Ru,serverUrl:"",getServiceManager:()=>Ou,getKernelConnection:()=>Du,report(ju){lo.value=ju},setState(ju){$u.value=ju},connect(){return Lu=Lu??Bu().catch(ju=>{throw $u.value="error",lo.value=null,Lu=null,ju}),()=>{Mu?.shutdown?.(),Mu=null,Du=null,Ou=Au.owned?null:Ou,Au.release?.(),Lu=null,$u.value="idle",lo.value=null}},async execute(ju){const Fu=Date.now();try{if(await(Lu??Bu()),!Mu)throw new Error("The browser kernel did not start");const zu={outputs:[],stdout:[],error:""},Uu=Mu.requestExecute({code:ju});Uu.onIOPub=Vu=>collect(Vu,zu),await Uu.done;const Hu={code:ju,success:!zu.error,stdout:zu.stdout.join(""),error:zu.error||void 0,outputs:zu.outputs,startedAt:Fu,finishedAt:Date.now()};return Ru.value=Hu,Hu}catch(zu){const Uu={code:ju,success:!1,error:zu instanceof Error?zu.message:String(zu),startedAt:Fu,finishedAt:Date.now()};return Ru.value=Uu,Uu}}}}function summarize(Au,lo){if(!Au)return{state:lo};const $u=Au.variant==="jupyter-server"||Au.variant==="datalayer";return{state:!!Au.sandbox_running||$u&&!!Au.jupyter_connected?"running":lo==="running"?"idle":lo,variant:Au.variant,kernelId:Au.kernel_id,jupyterUrl:Au.jupyter_url,jupyterToken:Au.jupyter_token,agentBaseUrl:Au.agent_base_url}}const RECONNECT_BASE_MS=1e3,RECONNECT_MAX_MS=3e4;function createServerSandboxService(Au){const lo=signal$2(null),$u=signal$2("idle"),Ru=signal$2(void 0),Iu=signal$2(null),Pu=computed$1(()=>({...summarize(lo.value,$u.value),errorReason:$u.value==="error"?Ru.value:void 0})),Ou=computed$1(()=>Pu.value.state==="running");return{kind:"server",connect(Mu){if(typeof WebSocket>"u")return()=>{};let Du=null,Lu=null,Bu=0,ju=!1;const Fu=()=>{if(ju)return;const zu=Au.replace(/^http/,"ws"),Uu=Mu?`?agent_id=${encodeURIComponent(Mu)}`:"";Du=new WebSocket(`${zu}/api/v1/configure/sandbox/ws${Uu}`),Du.onopen=()=>{Bu=0},Du.onmessage=Hu=>{try{lo.value=JSON.parse(String(Hu.data))}catch{}},Du.onclose=()=>{if(ju)return;lo.value=null,Bu+=1;const Hu=Math.min(RECONNECT_BASE_MS*2**(Bu-1),RECONNECT_MAX_MS);Lu=setTimeout(Fu,Hu)}};return Fu(),()=>{ju=!0,Lu&&clearTimeout(Lu),Du?.close(),Du=null}},snapshot:Pu,status:lo,ready:Ou,lastExecution:Iu,serverUrl:Au,report(Mu){lo.value=Mu},setState(Mu,Du){$u.value=Mu,Ru.value=Mu==="error"?Du:void 0},async execute(Mu){const Du=Date.now();try{const Lu=await fetch(`${Au}/api/v1/sandbox/execute`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({code:Mu})}),Bu=Lu.ok?await Lu.json():null,ju={code:Mu,success:Lu.ok&&!Bu?.error,stdout:Bu?.stdout,stderr:Bu?.stderr,error:Lu.ok?Bu?.error:`Execution failed: ${Lu.status}`,outputs:Bu?.outputs,startedAt:Du,finishedAt:Date.now()};return Iu.value=ju,ju}catch(Lu){const Bu={code:Mu,success:!1,error:Lu instanceof Error?Lu.message:String(Lu),startedAt:Du,finishedAt:Date.now()};return Iu.value=Bu,Bu}}}}const ANONYMOUS_JUPYTER_URL="https://prod1.datalayer.run/api/jupyter-server",ANONYMOUS_JUPYTER_TOKEN="60c1661cc408f978c309d04157af55c9588ff9557c9380e4fb50785750703da6",SANDBOX_TARGETS=["browser","local","jupyter","datalayer"];function heldTargetReason(Au,lo){if(Au==="local"&&!lo&&!insideJupyterLab())return"Not offered on the web for now: a local agent and the Jupyter server it starts run beside JupyterLab, not in a page."}const TARGET_SPECS={browser:{label:"Browser",hint:"Python in this page (Pyodide), with the agent loop running here too. Only the model is asked over the network.",hasAgent:!0,noAgentReason:""},local:{label:"Local",hint:"A local agent, with the Jupyter server it starts beside itself.",hasAgent:!0,noAgentReason:"",configure:{variant:"jupyter-server",jupyter_url:"",jupyter_token:""}},jupyter:{label:"Jupyter",hint:"A named Jupyter server: the anonymous one on prod1.datalayer.run.",hasAgent:!1,noAgentReason:"No agent on an anonymous Jupyter server",configure:{variant:"jupyter-server",jupyter_url:ANONYMOUS_JUPYTER_URL,jupyter_token:ANONYMOUS_JUPYTER_TOKEN}},datalayer:{label:"Datalayer",hint:"A Datalayer runtime running the agent this workspace asks for.",hasAgent:!0,noAgentReason:""}};function targetHasAgent(Au){return TARGET_SPECS[Au]?.hasAgent??!1}function targetRunsAgentInPage(Au){return Au==="browser"}function createSwitchableSandboxService({serverUrl:Au,initialTarget:lo="local",kernelSource:$u,localAgent:Ru,blueprint:Iu}){const Pu=signal$2(lo),Ou=createServerSandboxService(Au),Mu=createBrowserSandboxService($u??browserSource()),Du=computed$1(()=>Pu.value==="browser"?Mu:Ou);let Lu=null,Bu;const ju=computed$1(()=>Du.value.snapshot.value),Fu=computed$1(()=>Du.value.status.value),zu=computed$1(()=>Du.value.ready.value),Uu=computed$1(()=>Du.value.lastExecution.value);async function Hu(Wu){if(Wu==="local"){const ed=Iu?.()??Ru?.createPayload;ed&&await Vu(ed)}const Ku=TARGET_SPECS[Wu]?.configure;if(!Ku)return;const Ju=TARGET_SPECS[Wu].label;let Yu;try{Yu=await fetch(`${Au}/api/v1/agents/sandbox/configure`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(Ku)})}catch(ed){throw new Error(`${Ju} needs an agent-runtimes server at ${Au}, and nothing answered there. Start one and try again. (${ed instanceof Error?ed.message:String(ed)})`,{cause:ed})}if(!Yu.ok)throw new Error(`The server could not switch to ${Ju} (${Yu.status} ${Yu.statusText}). `+await detail(Yu));const Xu=await fetch(`${Au}/api/v1/agents/sandbox/restart`,{method:"POST"});if(!Xu.ok)throw new Error(`The server could not start ${Ju} (${Xu.status} ${Xu.statusText}). `+await detail(Xu))}function Vu(Wu){return ensureServerAgent(Au,Bu,Wu)}function Gu(){if(Lu?.(),Pu.peek()==="datalayer"){Lu=null,Ou.setState("starting");return}Lu=Du.peek().connect(Bu)}return{get kind(){return Pu.peek()==="browser"?"browser":"server"},target:Pu,snapshot:ju,status:Fu,ready:zu,lastExecution:Uu,serverUrl:Au,getServiceManager:()=>Pu.peek()==="browser"?Mu.getServiceManager():null,getKernelConnection:()=>Pu.peek()==="browser"?Mu.getKernelConnection():null,report(Wu){Du.peek().report(Wu)},setState(Wu,Ku){Du.peek().setState(Wu,Ku)},execute(Wu){return Du.peek().execute(Wu)},connect(Wu){Bu=Wu;const Ku=Pu.peek()==="local"&&Wu?Iu?.()??Ru?.createPayload:void 0;if(!Ku)return Gu(),()=>{Lu?.(),Lu=null};let Ju=!1;return Ou.setState("starting"),Vu(Ku).then(()=>{Ju||Gu()},Yu=>{Ju||(Ou.setState("error"),console.error("[loop] Local agent could not be started:",Yu))}),()=>{Ju=!0,Lu?.(),Lu=null}},async setTarget(Wu){const Ku=Pu.peek();if(Wu===Ku)return;const Ju=heldTargetReason(Wu,Au);if(Ju)throw new Error(Ju);Lu?.(),Lu=null;try{await Hu(Wu)}catch(Yu){throw Gu(),Yu}Pu.value=Wu,Gu()}}}async function ensureServerAgent(Au,lo,$u){const Ru=lo?.trim();if(!Ru)throw new Error("Local needs an agent id before its runtime can start.");let Iu;try{Iu=await fetch(`${Au}/api/v1/agents/${encodeURIComponent(Ru)}`)}catch(Ou){throw new Error(`Local needs an agent-runtimes server at ${Au}, and nothing answered there. Start one and try again. (${Ou instanceof Error?Ou.message:String(Ou)})`,{cause:Ou})}if(Iu.ok){await ensureServerSandbox(Au,Ru);return}if(Iu.status!==404)throw new Error(`The server could not inspect local agent ${Ru} (${Iu.status} ${Iu.statusText}). `+await detail(Iu));const Pu=await fetch(`${Au}/api/v1/agents`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({transport:"ag-ui",sandbox_variant:"jupyter-server",...$u,name:Ru})});if(!Pu.ok&&Pu.status!==409)throw new Error(`The server could not launch local agent ${Ru} (${Pu.status} ${Pu.statusText}). `+await detail(Pu));Pu.status===409&&await ensureServerSandbox(Au,Ru)}async function ensureServerSandbox(Au,lo){const $u=await fetch(`${Au}/api/v1/agents/${encodeURIComponent(lo)}/sandbox/ensure`,{method:"POST"});if(!$u.ok)throw new Error(`The server could not start a sandbox for local agent ${lo} (${$u.status} ${$u.statusText}). `+await detail($u))}async function detail(Au){try{const lo=await Au.json();return typeof lo.detail=="string"?lo.detail:""}catch{return""}}function useOptionalTeamSelection(){return useReactorPlatform().getOutput(AGENTS_PLUGIN_NAME)?.team}const NO_TARGET={value:void 0,peek:()=>{}},NO_MEMBER={value:void 0,peek:()=>{}};function AgentSummaryPanel({workspace:Au}){const lo=useSandboxService(),$u=useSignalValue$1(lo?.target??NO_TARGET),Ru=useOptionalTeamSelection(),Iu=useSignalValue$1(Ru?.active??NO_MEMBER);if(!lo)return null;const Pu=Au.sandbox,Ou=Iu?.specId||Au.agentId,Mu=AGENTSPECS$1[Ou],Du={agentName:Iu?.name||Mu?.name||Au.agentId,location:$u?TARGET_SPECS[$u].label:"—",specId:Ou,harness:Mu?.harness,variant:Pu.variant,status:Pu.state,baseUrl:Pu.agentBaseUrl||Au.serverUrl,sandboxBaseUrl:Pu.jupyterUrl,agentId:Au.agentId,isReady:Pu.state==="running"};return jsxRuntimeExports.jsx(AgentSummary,{summary:Du})}const RING=14,STROKE=2.5,RADIUS=(RING-STROKE)/2,CIRCUMFERENCE=2*Math.PI*RADIUS,DEFAULT_WARN_AT=.25,DEFAULT_DANGER_AT=.1,DEFAULT_PULSE_AT=.05,PULSE_MS=1200;function format(Au){const lo=Math.max(0,Math.ceil(Au/1e3)),$u=Math.floor(lo/60),Ru=lo%60;return`${$u}:${String(Ru).padStart(2,"0")}`}function AnonymousKeyTimer({expiresAt:Au,grantedMs:lo,label:$u="Trial key",warnAt:Ru=DEFAULT_WARN_AT,dangerAt:Iu=DEFAULT_DANGER_AT,pulseAt:Pu=DEFAULT_PULSE_AT,onExpire:Ou}){const[Mu,Du]=reactExports.useState(()=>Date.now()),Lu=reactExports.useRef(lo??Math.max(1,Au-Date.now())),Bu=reactExports.useRef(!1);reactExports.useEffect(()=>{const Hu=window.setInterval(()=>{Du(Vu=>{const Gu=Date.now(),Wu=Ku=>Math.ceil((Au-Ku)/1e3);return Wu(Gu)===Wu(Vu)?Vu:Gu})},250);return()=>window.clearInterval(Hu)},[Au]);const ju=Math.max(0,Au-Mu);reactExports.useEffect(()=>{ju>0||Bu.current||(Bu.current=!0,Ou?.())},[ju,Ou]);const Fu=Math.min(1,Math.max(0,ju/Lu.current)),zu=Fu<=Pu,Uu=Fu<=Iu?"danger.fg":Fu<=Ru?"attention.fg":"fg.muted";return jsxRuntimeExports.jsxs(Box,{display:"inline-flex",alignItems:"center",gap:1,px:2,py:"2px",borderRadius:"999px",border:"1px solid",borderColor:"border.muted",bg:"canvas.subtle",color:Uu,fontVariantNumeric:"tabular-nums",sx:{...zu?{"@keyframes dla-key-pulse":{"0%, 100%":{opacity:1},"50%":{opacity:.45}},animation:`dla-key-pulse ${PULSE_MS}ms ease-in-out infinite`,"@media (prefers-reduced-motion: reduce)":{animation:"none"}}:null},title:`${$u}: this workspace is talking to the agent on a temporary key issued to nobody in particular. When it runs out the chat asks you to sign in. Sign in now for an account of your own.`,children:[jsxRuntimeExports.jsx(Box,{display:"flex",alignItems:"center",color:Uu,children:jsxRuntimeExports.jsx(KeyIcon,{size:12})}),jsxRuntimeExports.jsxs(Box,{as:"svg","aria-hidden":"true",focusable:"false",width:RING,height:RING,viewBox:`0 0 ${RING} ${RING}`,display:"block",flexShrink:0,children:[jsxRuntimeExports.jsx("circle",{cx:RING/2,cy:RING/2,r:RADIUS,fill:"none",stroke:"currentColor",strokeWidth:STROKE,opacity:.2}),jsxRuntimeExports.jsx("circle",{cx:RING/2,cy:RING/2,r:RADIUS,fill:"none",stroke:"currentColor",strokeWidth:STROKE,strokeLinecap:"round",strokeDasharray:CIRCUMFERENCE,strokeDashoffset:CIRCUMFERENCE*(1-Fu),transform:`rotate(-90 ${RING/2} ${RING/2})`,style:{transition:"stroke-dashoffset 0.5s linear"}})]}),jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:Uu,fontWeight:"semibold"},children:format(ju)})]})}function AnonymousKeyHeaderBadge({workspace:Au}){return jsxRuntimeExports.jsx(Box,{order:1,display:"inline-flex",alignItems:"center",children:jsxRuntimeExports.jsx(AnonymousKeyBadge,{workspace:Au})})}function AnonymousKeyBadge({workspace:Au}){const lo=useAnonymousSession(),$u=Au.sandbox.target??"local";return!targetRunsAgentInPage($u)||lo.status==="idle"||lo.status==="expired"?null:lo.expiresAt?jsxRuntimeExports.jsx(AnonymousKeyTimer,{expiresAt:lo.expiresAt,grantedMs:lo.grantedMs,onExpire:()=>useAnonymousSessionStore.getState().expire()}):jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:lo.error?"danger.fg":"fg.muted"},title:lo.error,children:lo.error?"No trial key":"Getting a trial key…"})}function SandboxSelector(Au){const lo=useOptionalSandboxService(),[$u,Ru]=reactExports.useState(!1),[Iu,Pu]=reactExports.useState(null),Ou=useSignalValue$1(lo?.snapshot??IDLE_SANDBOX_SNAPSHOT_SIGNAL),Mu=useSignalValue$1(lo?.status??EMPTY_STATUS),Du=useSignalValue$1(lo?.target??DEFAULT_TARGET),Lu=reactExports.useCallback(async ju=>{if(!(!lo||ju===Du)){Ru(!0),Pu(null);try{await lo.setTarget(ju)}catch(Fu){Pu(Fu instanceof Error?Fu.message:String(Fu))}finally{Ru(!1)}}},[lo,Du]);if(!lo)return null;const Bu=Math.max(0,SANDBOX_TARGETS.indexOf(Du));return jsxRuntimeExports.jsxs(Box,{display:"flex",alignItems:"center",gap:2,minWidth:0,children:[jsxRuntimeExports.jsx(Box,{width:16,flexShrink:0,display:"flex",justifyContent:"center",children:$u?jsxRuntimeExports.jsx(StyledSpinner,{size:"small"}):null}),jsxRuntimeExports.jsx(KernelIndicator,{state:sandboxIndicatorState(Ou.state,Mu?.execution_state,Mu?.is_executing),kernelId:Ou.kernelId??Mu?.kernel_id,kernelName:Mu?.kernel_name,serverUrl:Ou.jupyterUrl??Mu?.jupyter_url,websocketUrl:toWebsocketUrl(Ou.jupyterUrl??Mu?.jupyter_url),environmentName:TARGET_SPECS[Du].label,overlayTitle:`${TARGET_SPECS[Du].label} Kernel`,position:"se",bordered:!1}),jsxRuntimeExports.jsx(SegmentedControl,{"aria-label":"Where code runs",size:"small",style:{listStyle:"none",margin:0,padding:0},sx:{listStyle:"none",m:0,p:0,"& > li":{listStyle:"none"},"& > li::marker":{content:"none"}},children:SANDBOX_TARGETS.map((ju,Fu)=>{const zu=heldTargetReason(ju,lo?.serverUrl??"");return jsxRuntimeExports.jsx(SegmentedControl.Button,{selected:Fu===Bu,"aria-disabled":zu?!0:void 0,"data-sandbox-target":ju,"data-sandbox-target-held":zu?"":void 0,sx:{listStyle:"none",...zu?{color:"fg.subtle",cursor:"not-allowed"}:null},title:zu??TARGET_SPECS[ju].hint,onClick:()=>zu?void 0:void Lu(ju),children:TARGET_SPECS[ju].label},ju)})}),Iu||Ou.errorReason?jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:"danger.fg",lineHeight:1.3,maxWidth:280,minWidth:0},title:Iu??Ou.errorReason,children:Iu??Ou.errorReason}):jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:"fg.muted"},title:TARGET_SPECS[SANDBOX_TARGETS[Bu]].hint,children:Ou.state})]})}function toWebsocketUrl(Au){return Au?.replace(/^http/,"ws")}const EMPTY_STATUS={value:null,peek:()=>null},DEFAULT_TARGET={value:"local",peek:()=>"local"};function MemberIcon({icon:Au}){const lo=agentIcon(Au);return jsxRuntimeExports.jsx(lo,{})}function TeamMemberPicker(){const Au=useOptionalTeamSelection();return!Au||Au.members.length<2?null:jsxRuntimeExports.jsx(TeamMemberMenu,{selection:Au})}function TeamMemberMenu({selection:Au}){const[lo,$u]=reactExports.useState(!1),Ru=useSignalValue$1(Au.selected),Iu=Au.members.find(Pu=>Pu.id===Ru);return jsxRuntimeExports.jsx(AnchoredOverlay,{width:"large",open:lo,onOpen:()=>$u(!0),onClose:()=>$u(!1),renderAnchor:Pu=>jsxRuntimeExports.jsx(IconButton,{...Pu,"aria-labelledby":void 0,icon:ForwardRef$2,"aria-label":Iu?`Talking to ${Iu.name}. Choose another agent.`:"Choose an agent",variant:"invisible",size:"small"}),children:jsxRuntimeExports.jsx(Box,{width:440,maxWidth:"calc(100vw - 16px)",children:jsxRuntimeExports.jsxs(ActionList,{selectionVariant:"single",role:"listbox","aria-label":`Agents in ${Au.team.name}`,children:[jsxRuntimeExports.jsx(ActionList.GroupHeading,{children:Au.team.name}),Au.members.map(Pu=>jsxRuntimeExports.jsxs(ActionList.Item,{selected:Pu.id===Ru,onSelect:()=>{Au.select(Pu.id),$u(!1)},children:[jsxRuntimeExports.jsx(ActionList.LeadingVisual,{children:jsxRuntimeExports.jsx(MemberIcon,{icon:Pu.icon})}),jsxRuntimeExports.jsxs(Box,{as:"span",display:"flex",alignItems:"center",gap:2,children:[Pu.name,Pu.isSupervisor?jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:"fg.muted"},children:"supervisor"}):null]}),Pu.description?jsxRuntimeExports.jsx(ActionList.Description,{variant:"block",sx:{display:"block",whiteSpace:"normal",overflowWrap:"anywhere",minWidth:0},children:Pu.description}):null]},Pu.id))]})})})}function specIdOf(Au){return(Au??"").split(":")[0]??""}function teamMembers(Au){const lo=specIdOf(Au.supervisor?.ref),$u=Iu=>{const Pu=AGENTSPECS$1[Iu];return{description:Pu?.description,emoji:Pu?.emoji,icon:Pu?.icon}},Ru=(Au.agents??[]).map(Iu=>{const Pu=specIdOf(Iu.ref);return{id:Iu.id,name:Iu.name||Pu||Iu.id,specId:Pu,isSupervisor:Pu!==""&&Pu===lo,...$u(Pu)}});return[...Ru.filter(Iu=>Iu.isSupervisor),...Ru.filter(Iu=>!Iu.isSupervisor)]}function createTeamSelection(Au){const lo=TEAM_SPECS[Au];if(!lo)return;const $u=teamMembers(lo);if($u.length===0)return;const Ru=signal$2($u[0].id);return{team:lo,members:$u,selected:Ru,select:Iu=>{$u.some(Pu=>Pu.id===Iu)&&(Ru.value=Iu)},sharing:lo.context?.sharing??"shared",active:computed$1(()=>$u.find(Iu=>Iu.id===Ru.value))}}function subagentsFor(Au,lo){const $u=teamMembers(Au),Ru=$u.find(Du=>Du.id===lo);if(!Ru)return[];const Iu=(Du,Lu,Bu)=>{const ju=AGENTSPECS$1[Lu];if(ju)return{name:Du,description:Bu||ju.description||Du,instructions:ju.systemPrompt,model:ju.model,icon:ju.icon}},Pu=Ru.isSupervisor||Au.delegation?.allowPeerDelegation?$u.filter(Du=>Du.id!==lo).map(Du=>Iu(Du.name,Du.specId,Du.description)):[],Mu=((Au.agents??[]).find(Du=>Du.id===lo)?.subagents??[]).map(Du=>Iu(Du.name,(Du.ref??"").split(":")[0]??"",Du.description));return[...Pu,...Mu].filter(Boolean)}const DEFAULT_DATALAYER_AGENTSPEC="jupyter-tutor",AGENTS_PLUGIN_NAME="@datalayer/loop-plugin-agents",offeredTarget=(Au,lo)=>heldTargetReason(Au,lo)?"browser":Au,AgentsPlugin={name:AGENTS_PLUGIN_NAME,displayName:"Agents",description:"Where the agent and its code run: this page, a local server, or a Datalayer runtime.",octicon:"container",emoji:"📦",config:{serverUrl:"",target:"local"},contributionPoints:[LoopAgentBlueprint],preserveOutput:!0,build({config:Au,reactor:lo}){const $u=Au.showAgentVariants??!0,Ru=Au.teamId?createTeamSelection(Au.teamId):void 0;return{team:Ru,sandbox:createSwitchableSandboxService({serverUrl:Au.serverUrl,initialTarget:offeredTarget(($u||Au.targetFixed?Au.target:"browser")??"local",Au.serverUrl),kernelSource:Au.kernelSource,localAgent:Au.localAgent,blueprint:()=>{const Iu=lo.getContributions(LoopAgentBlueprint)[0]?.value;if(Iu)return{...Iu.specId?{agent_spec_id:Iu.specId}:null,...Iu.createPayload}}}),components:[{slot:LoopSlots.status,id:"sandbox-status",Component:SandboxStatusBridge},{slot:LoopSlots.status,id:"datalayer-agent",Component:DatalayerAgentMount},...Ru&&Au.showTeamPicker!==!1?[{slot:LoopSlots.header,id:"team-member-picker",Component:TeamMemberPicker}]:[],...$u?[{slot:LoopSlots.header,id:"sandbox-selector",Component:SandboxSelector}]:[],...Au.showAgentSummary===!1?[]:[{slot:LoopSlots.header,id:"agent-summary",Component:AgentSummaryPanel}],{slot:LoopSlots.chatHeader,id:"anonymous-key",Component:AnonymousKeyBadge},{slot:LoopSlots.header,id:"anonymous-key-header",Component:AnonymousKeyHeaderBadge}]}},register({contribute:Au,state:lo}){const $u=lo.getOutput()?.sandbox;if($u)return Au(LoopAgentGate,{check:Ru=>{const Iu=Ru.sandbox.target??$u.target.peek();return targetHasAgent(Iu)||TARGET_SPECS[Iu].noAgentReason}},{id:"sandbox-target"})},contributes:[contribution(LoopViewType,{viewType:"sandbox",title:"Sandbox",icon:ServerIcon,order:40,load:()=>__vitePreload(()=>import("./chunks/SandboxView-DDWPvnOk.js"),[],import.meta.url)},{id:"sandbox",order:40}),contribution(LoopCommand,{name:"sandbox",aliases:["code-sandbox"],description:"Show the code sandbox: variant, kernel, Jupyter server",group:"Capabilities",run:async({workspace:Au})=>{Au.setActiveViewType("sandbox")}},{id:"sandbox"})]},PULSE_ANIMATION="loop-subagent-pulse",KEYFRAMES=`@keyframes ${PULSE_ANIMATION} {
3858
3858
  0%, 100% { opacity: 0.25; }
3859
3859
  50% { opacity: 1; }
3860
3860
  }`;function SubagentPulse(){const Au=useAgentRuntimeActiveSubagentToolCallId(),lo=useAgentRuntimeSubagentActivity(Au??void 0),$u=useOptionalReactorPlatform(),Ru=lo[0]?.subagentName??Au??"",Iu=$u?.getOutput(AGENTS_PLUGIN_NAME)?.team?.members.find(Du=>Du.name===Ru),Pu=agentIcon(Iu?.icon);if(!Au)return null;const Mu=lo.some(Du=>Du.transport==="a2a")?`${Ru} is working over A2A…`:`${Ru} is working…`;return jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx("style",{children:KEYFRAMES}),jsxRuntimeExports.jsx(Tooltip,{text:Mu,direction:"n",children:jsxRuntimeExports.jsx(Box,{as:"button",type:"button","aria-label":Mu,"data-subagent-pulse":Ru,display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,p:0,border:0,bg:"transparent",color:"accent.fg",cursor:"default",animation:`${PULSE_ANIMATION} 1.4s ease-in-out infinite`,children:jsxRuntimeExports.jsx(Pu,{size:16})})})]})}const SUBAGENT_ACTIVITY_PLUGIN_NAME="@datalayer/loop-plugin-subagent-activity",SubagentActivityPlugin={name:SUBAGENT_ACTIVITY_PLUGIN_NAME,displayName:"Subagent activity",description:"A delegated agent's icon, pulsing in the prompt's header while it works.",octicon:"people",emoji:"👥",dependencies:[InputPromptPlugin],build:()=>({components:[{id:"subagent-pulse",slot:LoopSlots.inpromptMenu,order:0,Component:SubagentPulse}]})},A2UI_PLUGIN_NAME="@datalayer/loop-plugin-a2ui",A2uiPlugin={name:A2UI_PLUGIN_NAME,displayName:"A2UI surfaces",description:"The last execution, rendered as a surface rather than dumped.",octicon:"browser",emoji:"🖼",dependencies:[AgentsPlugin],contributes:[contribution(LoopViewType,{viewType:"a2ui",title:"Surface",icon:BrowserIcon,order:30,canOpen:Au=>Au.sandbox.state==="running"&&Au.sandbox.variant!=="pyodide",unavailableReason:Au=>Au.sandbox.variant==="pyodide"?"Surfaces are rendered by the server; this sandbox runs in the browser":"Needs a running sandbox",load:()=>__vitePreload(()=>import("./chunks/A2uiView-CsiMsnAN.js"),[],import.meta.url)},{id:"a2ui",order:30}),contribution(LoopCommand,{name:"a2ui",aliases:["surface"],description:"Show the last execution as a rendered surface",group:"Open",keybinding:"Mod+Alt+U",run:async({workspace:Au})=>{Au.setActiveViewType("a2ui")}},{id:"a2ui"})]},NONE_VIEW="none";let state={viewId:NONE_VIEW,options:[],allowNone:!0},announcer=()=>!0;const listeners=new Set;function notify(){for(const Au of[...listeners])Au()}function getViewChoice(){return state}function subscribeViewChoice(Au){return listeners.add(Au),()=>{listeners.delete(Au)}}function setViewAnnouncer(Au){const lo=announcer;return announcer=Au,()=>{announcer=lo}}function setViewOptions(Au,lo=!0){if(lo===state.allowNone&&Au.length===state.options.length&&Au.every((Ru,Iu)=>Ru===state.options[Iu]))return;state={viewId:!lo&&!Au.includes(state.viewId)?Au[0]??NONE_VIEW:state.viewId,options:Au,allowNone:lo},notify()}function chooseView(Au){return state={...state,viewId:Au},notify(),announcer(Au)}function seedViewChoice(Au){state.viewId!==Au&&(state={...state,viewId:Au},notify())}function nextView(){const Au=state.allowNone?[NONE_VIEW,...state.options]:[...state.options];if(Au.length===0)return NONE_VIEW;const lo=Au.indexOf(state.viewId);return Au[(lo+1)%Au.length]}function ViewSelector({point:Au,describe:lo,context:$u,noneLabel:Ru,ariaLabel:Iu,allowNone:Pu=!0}){const Ou=useContributions(Au),Mu=reactExports.useSyncExternalStore(subscribeViewChoice,getViewChoice),[Du,Lu]=reactExports.useState(null),Bu=reactExports.useRef(null),ju=()=>{Bu.current!==null&&(window.clearTimeout(Bu.current),Bu.current=null)},Fu=Vu=>{ju(),Lu(Vu)},zu=()=>{ju(),Bu.current=window.setTimeout(()=>{Lu(null),Bu.current=null},250)};reactExports.useEffect(()=>ju,[]);const Uu=reactExports.useMemo(()=>Ou.map(Vu=>lo(Vu.value,$u)).sort((Vu,Gu)=>(Vu.order??100)-(Gu.order??100)),[Ou,lo,$u]);if(reactExports.useEffect(()=>{setViewOptions(Uu.map(Vu=>Vu.id),Pu)},[Uu,Pu]),Uu.length<(Pu?1:2))return null;const Hu=Uu.find(Vu=>Vu.id===Du&&Vu.details);return jsxRuntimeExports.jsxs(Box$1,{sx:{marginLeft:"auto",display:"flex",alignItems:"center",position:"relative"},children:[jsxRuntimeExports.jsxs(SegmentedControl,{"aria-label":Iu,size:"small",children:[Pu?jsxRuntimeExports.jsx(SegmentedControl.Button,{selected:Mu.viewId===NONE_VIEW,onClick:()=>chooseView(NONE_VIEW),children:Ru}):null,Uu.map(Vu=>jsxRuntimeExports.jsx(SegmentedControl.Button,{selected:Mu.viewId===Vu.id,"aria-disabled":Vu.disabled||void 0,title:Vu.disabled?Vu.disabledReason:Vu.title,leadingIcon:Vu.icon,onMouseEnter:Vu.details?()=>Fu(Vu.id):void 0,onMouseLeave:Vu.details?zu:void 0,onClick:()=>{Vu.disabled||chooseView(Vu.id)},children:Vu.badge?`${Vu.title} (${Vu.badge})`:Vu.title},Vu.id))]}),Hu?jsxRuntimeExports.jsx(Box$1,{onMouseEnter:ju,onMouseLeave:zu,sx:{position:"absolute",top:"calc(100% + 6px)",right:0,minWidth:260,maxWidth:380,maxHeight:320,overflowY:"auto",p:2,bg:"canvas.overlay",border:"1px solid",borderColor:"border.default",borderRadius:2,boxShadow:"shadow.large",zIndex:40,fontSize:0,color:"fg.default",textAlign:"left"},children:Hu.details}):null]})}const SHELL_PLUGIN_NAME$1="@datalayer/reactor-shell",ShellView=defineContributionPoint("reactor.shell.view"),describeAsIs=Au=>Au,ShellPlugin$1={name:SHELL_PLUGIN_NAME$1,displayName:"Shell",description:"A view point, its selector, and the choice as a command.",octicon:"columns",emoji:"📑",config:{point:ShellView,describe:describeAsIs,slot:"header",defaultView:NONE_VIEW,showSelector:!0,allowNone:!0,noneLabel:"None",ariaLabel:"View",announce:()=>!0,commandId:"shell.cycleView",commandName:"Switch the view",commandDescription:"Cycle through the contributed views, and none",keybinding:"Mod+Alt+E"},contributionPoints:[ShellView],register:({config:Au,registerCommand:lo})=>{const $u=setViewAnnouncer(Au.announce),Ru=lo({id:Au.commandId,name:Au.commandName,description:Au.commandDescription,emoji:"📑",category:"Workspace",keybinding:Au.keybinding||void 0,execute:()=>{chooseView(nextView())}});return()=>{$u(),Ru()}},build:({config:Au})=>(seedViewChoice(Au.defaultView||NONE_VIEW),{components:Au.showSelector?[{id:"view-selector",slot:Au.slot,Component:lo=>jsxRuntimeExports.jsx(ViewSelector,{point:Au.point,describe:Au.describe,context:lo,noneLabel:Au.noneLabel,allowNone:Au.allowNone,ariaLabel:Au.ariaLabel})}]:[]})};setViewAnnouncer(requestSurface);const NONE_EDITOR=NONE_VIEW;let mappedFor=null,mapped=null;function getEditorChoice(){const Au=getViewChoice();return(Au!==mappedFor||!mapped)&&(mappedFor=Au,mapped={editorId:Au.viewId,options:Au.options}),mapped}const subscribeEditorChoice=subscribeViewChoice,setEditorOptions=setViewOptions,chooseEditor=chooseView,seedEditorChoice=seedViewChoice,nextEditor=nextView;let jupyterReact=null;function loadJupyterReact(){return jupyterReact?Promise.resolve(jupyterReact):__vitePreload(()=>import("./chunks/index-BOGJMsUN.js").then(Au=>Au.r),[],import.meta.url).then(Au=>(jupyterReact=Au,Au))}const PREVIEW_LENGTH=56;function stripped(Au){const $u=(Au.split(`
@@ -4022,7 +4022,7 @@ ${Mu}`:ju,inputs:Mu,clear:Ou?[]:[DRAFT.path],loop:Lu()}:{refused:"Nothing to sen
4022
4022
  `);await navigator.clipboard?.writeText(ju),Du(!0)},[$u.user,$u.assistant]);if(Ru==="panel"||$u.status==="idle"||!$u.user||Pu===$u.id)return null;const Bu=$u.status==="thinking"||$u.status==="streaming";return jsxRuntimeExports.jsxs(Box,{"data-turn-panel":"",borderTop:"1px solid",borderColor:"border.muted",px:3,pt:2,pb:Au==="none"?2:1,display:"flex",flexDirection:"column",gap:2,bg:"canvas.default",children:[jsxRuntimeExports.jsx(Box,{display:"flex",justifyContent:"flex-end",children:jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,lineHeight:1.45,px:2,py:1,borderRadius:"10px",bg:"accent.subtle",color:"fg.default",maxWidth:"85%",overflow:"hidden",display:"-webkit-box",WebkitLineClamp:2,WebkitBoxOrient:"vertical"},children:$u.user})}),jsxRuntimeExports.jsxs(Box,{display:"flex",gap:2,alignItems:"flex-start",children:[jsxRuntimeExports.jsx(Box,{ref:Iu,flex:"1 1 auto",minWidth:0,maxHeight:MAX_HEIGHT,overflowY:"auto",fontSize:0,lineHeight:1.5,color:$u.assistant?"fg.default":"fg.muted",whiteSpace:$u.assistant?"normal":"pre-wrap",overflowWrap:"anywhere",children:$u.assistant?jsxRuntimeExports.jsx(Box,{sx:{...streamdownMarkdownStyles,fontSize:0},children:jsxRuntimeExports.jsx(_o$1,{rehypePlugins:REHYPE_PLUGINS_WITHOUT_HTML,children:normalizeAssistantMarkdown($u.assistant)})}):$u.activity?jsxRuntimeExports.jsx(Text$3,{sx:{color:"fg.muted",fontStyle:"italic"},children:$u.activity}):Bu?jsxRuntimeExports.jsx(Thinking,{}):$u.status==="error"?"The agent could not answer.":"Done — the result is in the page."}),jsxRuntimeExports.jsx(IconButton,{icon:CommentDiscussionIcon,size:"small",variant:"invisible","aria-label":"Open the conversation",onClick:openPagePanel,sx:{color:"fg.muted",flexShrink:0}})]}),$u.assistant&&$u.activity?jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:"fg.muted",fontStyle:"italic"},children:$u.activity}):null,Au==="full"?jsxRuntimeExports.jsx(TurnFooter,{usage:$u.usage,live:Bu,latest:!0,padding:0,onCopy:Lu,onRemove:()=>Ou($u.id)}):Au==="actions"?jsxRuntimeExports.jsxs(Box,{display:"flex",justifyContent:"flex-end",gap:1,mt:-1,children:[jsxRuntimeExports.jsx(IconButton,{icon:Mu?CheckIcon:CopyIcon,size:"small",variant:"invisible","aria-label":Mu?"Copied":"Copy this turn",onClick:()=>{Lu()},sx:{color:"fg.muted"}}),jsxRuntimeExports.jsx(IconButton,{icon:XIcon,size:"small",variant:"invisible","aria-label":"Dismiss until the next turn",onClick:()=>Ou($u.id),sx:{color:"fg.muted"}})]}):null]})}const SPLIT_DEFAULT_SHARE=.4,SPLIT_MIN_SHARE=.2,SPLIT_MAX_SHARE=.8,SPLIT_KEY_STEP=.05;function clampSplitShare(Au){return Number.isFinite(Au)?Math.min(SPLIT_MAX_SHARE,Math.max(SPLIT_MIN_SHARE,Au)):SPLIT_DEFAULT_SHARE}function splitShareForKey(Au,lo){switch(lo){case"ArrowLeft":return clampSplitShare(Au-SPLIT_KEY_STEP);case"ArrowRight":return clampSplitShare(Au+SPLIT_KEY_STEP);case"Home":return SPLIT_MIN_SHARE;case"End":return SPLIT_MAX_SHARE;default:return null}}function SplitLayout({editors:Au,hasEditor:lo,transcript:$u,prompt:Ru,chips:Iu,picker:Pu,transient:Ou}){const[Mu,Du]=reactExports.useState(SPLIT_DEFAULT_SHARE),Lu=reactExports.useRef(null),Bu=reactExports.useRef(!1),ju=reactExports.useCallback(Gu=>{const Wu=Lu.current?.getBoundingClientRect();return!Wu||Wu.width<=0?null:clampSplitShare((Gu-Wu.left)/Wu.width)},[]),Fu=Gu=>{Bu.current=!0,Gu.currentTarget.setPointerCapture?.(Gu.pointerId),Gu.preventDefault()},zu=Gu=>{if(!Bu.current)return;const Wu=ju(Gu.clientX);Wu!==null&&Du(Wu)},Uu=Gu=>{Bu.current=!1,Gu.currentTarget.releasePointerCapture?.(Gu.pointerId)},Hu=Gu=>{const Wu=splitShareForKey(Mu,Gu.key);Wu!==null&&(Gu.preventDefault(),Du(Wu))},Vu=Math.round(Mu*100);return jsxRuntimeExports.jsxs(Box,{"data-testid":"loop-split-layout",flex:"1 1 auto",minHeight:0,display:"flex",flexDirection:"column",children:[Pu,jsxRuntimeExports.jsxs(Box,{ref:Lu,flex:"1 1 auto",minHeight:0,display:"flex",position:"relative",overflow:"hidden",children:[jsxRuntimeExports.jsxs(Box,{"data-testid":"loop-split-conversation",flex:lo?`0 0 ${Vu}%`:"1 1 auto",minWidth:0,minHeight:0,display:"flex",flexDirection:"column",ml:lo?"-1px":0,children:[$u,Iu,Ru]}),lo?jsxRuntimeExports.jsx(Box,{role:"separator","aria-orientation":"vertical","aria-label":"Resize the conversation and the page","aria-valuemin":Math.round(SPLIT_MIN_SHARE*100),"aria-valuemax":Math.round(SPLIT_MAX_SHARE*100),"aria-valuenow":Vu,tabIndex:0,onPointerDown:Fu,onPointerMove:zu,onPointerUp:Uu,onPointerCancel:Uu,onKeyDown:Hu,flex:"0 0 7px",mx:"-3px",zIndex:1,cursor:"col-resize",display:"flex",justifyContent:"center",outline:"none",touchAction:"none",sx:{"&::before":{content:'""',width:"1px",height:"100%",bg:"border.default"},"&:hover::before, &:focus-visible::before":{width:"3px",bg:"accent.emphasis"}}}):null,jsxRuntimeExports.jsx(Box,{"data-testid":"loop-split-page",sx:lo?{flex:"1 1 0",minWidth:0,minHeight:0,display:"flex",...paneOpening("right")}:{position:"absolute",inset:0,visibility:"hidden",pointerEvents:"none",zIndex:-1},children:Au})]}),Ou]})}const LOOP_PAGE_LAYOUT_PLUGIN_NAME="@datalayer/loop-plugin-page-layout",NO_TURN$4=signal$2({id:0,status:"idle"}),pageLayoutChatMode=signal$2("floating-draggable"),promptStance=signal$2("floating-top");let floatingStance="floating-top";const PAGE_LAYOUT_DISABLED_MODES=["assistant"];function pageLayoutForChatMode(Au){switch(Au){case"sidebar":return{bandMode:"panel",panelMode:"docked"};case"floating":return{bandMode:"panel",panelMode:"overlay"};case"floating-small":return{bandMode:"panel",panelMode:"popup"};default:return{bandMode:"floating",panelMode:"docked"}}}function setPageLayoutChatMode(Au){pageLayoutChatMode.value=Au;const{bandMode:lo}=pageLayoutForChatMode(Au);promptStance.value=lo==="floating"?floatingStance:"docked-top",lo==="panel"&&openPagePanel()}function ChatModeAction(){const Au=useSignalValue$1(pageLayoutChatMode);return jsxRuntimeExports.jsx(ChatViewModeToggle,{value:Au,onChange:setPageLayoutChatMode,disabledModes:PAGE_LAYOUT_DISABLED_MODES})}function LoopPageLayout({parts:Au,promptMode:lo,pageSize:$u}){const Ru=useContributions(LoopChatTurn),Iu=useSignalValue$1(Ru[0]?.value.turn??NO_TURN$4),Pu=useSignalValue$1(pageLayoutChatMode),Ou=lo==="floating"?pageLayoutForChatMode(Pu):{bandMode:"docked",panelMode:"docked"};return jsxRuntimeExports.jsx(PageLayout,{page:Au.editors,hasPage:Au.hasEditor,panel:Au.transcript,band:Au.prompt,chips:Au.chips,picker:Au.picker,transient:Au.transient,activity:Iu.activity,bandMode:Ou.bandMode,panelMode:Ou.panelMode,pageSize:$u})}function ConversationToggle(){return jsxRuntimeExports.jsx(PagePanelToggle,{panelName:"conversation",icon:CommentDiscussionIcon,sx:{order:2}})}const LoopPageLayoutPlugin={name:LOOP_PAGE_LAYOUT_PLUGIN_NAME,config:{arrangement:"page",turnPanel:"below",turnPanelFooter:"full",prompt:"docked",promptAnchor:"top",pageSize:void 0},displayName:"Page layout",description:"The editor — or, in the chat view, the conversation — on a centred sheet, the prompt docked above it at the same width or floating over it as a draggable card, the current turn under the prompt, the conversation in a side panel; or, split, the conversation and the work side by side with a hairline to drag.",octicon:"file",emoji:"📄",build:({config:Au,...lo})=>{if(Au.arrangement==="split")return lo.contribute(LoopChatLayout,{id:"split-layout",prompt:"docked",Component:SplitLayout},{id:"split-layout"}),{components:[]};const $u=Au.prompt,Ru=Au.pageSize;floatingStance=Au.promptAnchor==="bottom"?"floating-bottom":"floating-top",$u==="floating"&&(promptStance.value=floatingStance);const Iu=Pu=>jsxRuntimeExports.jsx(LoopPageLayout,{parts:Pu,promptMode:$u,pageSize:Ru});if(lo.contribute(LoopChatLayout,{id:"page-layout",prompt:$u==="floating"?floatingStance:"docked-top",promptStance:$u==="floating"?promptStance:void 0,Component:Iu},{id:"page-layout"}),Au.turnPanel!=="none"){const Pu=Au.turnPanelFooter,Ou=()=>jsxRuntimeExports.jsx(TurnPanel,{footer:Pu});lo.contribute(LoopPromptPanel,{id:"page-layout-turn",placement:Au.turnPanel,order:0,Component:Ou},{id:"page-layout-turn"})}return{components:[{id:"page-layout-conversation-toggle",slot:LoopSlots.header,Component:ConversationToggle},...$u==="floating"?[{id:"page-layout-chat-mode",slot:LoopSlots.promptAction,Component:ChatModeAction}]:[]]}}};function loopPlugins(Au={}){const{serverUrl:lo,target:$u="browser",defaultEditor:Ru,showViewSelector:Iu=!0,hideChatHeader:Pu=!1,chatHeaderButtons:Ou=!1,promptPlacement:Mu,autoFocusPrompt:Du=!0,suggestionLabels:Lu=!0,fullScreenTopOffset:Bu=0,showAgentVariants:ju=!1,agentSummary:Fu=!0,teamId:zu,teamPicker:Uu=!0,pageLayout:Hu=!1,pageLayoutArrangement:Vu="page",pageLayoutTurnPanel:Gu="below",pageLayoutPrompt:Wu="docked",pageLayoutPromptAnchor:Ku="top",pageLayoutSize:Ju,pageLayoutTurnPanelFooter:Yu="full",localAgent:Xu,localAgentSpec:ed,datalayerAgentSpecId:td,datalayerCreatePayload:nd,datalayerVisitors:od,datalayerKept:sd,embedToken:ad,targetFixed:pd,themeVariant:gd,themeOverrides:Sd,colorMode:_d,presence:yd,showTokenUsage:wd,voice:Ad,thread:md,floatingPrompt:dd=!1,editorSelector:bd=!1,editors:ld=!0,conversation:ud=!0,commandPalette:hd=!1,pluginsPanel:vd=!1,windowFrame:Ed=!1,firstPromptHook:Cd}=Au,Rd=Ru??(ld?"notebook":"none");return ud?[configurePlugin(ChatPlugin,{defaultSurface:Rd,showSurfaceSelector:ld&&Iu&&!bd,hideHeader:Pu,headerButtons:{newChat:Ou,clear:Ou},promptPlacement:dd?"floating":Mu,autoFocusPrompt:Du,suggestionLabels:Lu,fullScreenTopOffset:Bu,themeVariant:gd,themeOverrides:Sd,colorMode:_d,presence:yd,showTokenUsage:wd,...Ad?{voice:Ad}:{},...md?{thread:md}:{}}),configurePlugin(InputPromptPlugin,{firstPromptHook:Cd}),ChatHeaderPlugin,A2uiSurfacePlugin,PapSignInPlugin,ShieldDisplaysPlugin,ChatViewPlugin,...ld?[NotebookViewPlugin,DocumentViewPlugin]:[],configurePlugin(AgentsPlugin,{serverUrl:lo,target:$u,datalayerAgentSpecId:td,datalayerCreatePayload:nd,datalayerVisitors:od,datalayerKept:sd,embedToken:ad,targetFixed:pd,showAgentVariants:ju,showAgentSummary:Fu,teamId:zu,showTeamPicker:Uu,localAgent:Xu??(ed?{createPayload:{description:`Local agent from the ${ed} spec`,agent_library:"pydantic-ai",agent_spec_id:ed,enable_codemode:!1}}:void 0)}),...ld?[NotebookExtension,DocumentExtension]:[],A2uiPlugin,AgentspecsPlugin,ModelsPlugin,ThemePlugin,SubagentActivityPlugin,configurePlugin(ShellPlugin,{defaultEditor:Rd,showSelector:ld&&bd}),...dd?[PromptPlugin]:[],...Hu?[configurePlugin(LoopPageLayoutPlugin,{arrangement:Vu,turnPanel:Gu,turnPanelFooter:Yu,prompt:Wu,promptAnchor:Ku,pageSize:Ju})]:[],...hd?[LoopCommandsPlugin]:[],...vd?[PluginsPanelPlugin]:[],...Ed?[WindowFramePlugin]:[]]:[ThemePlugin,configurePlugin(ShellPlugin,{defaultEditor:"none",showSelector:!1}),...hd?[LoopCommandsPlugin]:[],...vd?[PluginsPanelPlugin]:[],...Ed?[WindowFramePlugin]:[]]}function LoopEmbed({agentId:Au="",showHeader:lo=!1,chatHeaderActions:$u,headerActions:Ru,headerContainer:Iu,frameTitle:Pu,frameHeight:Ou,sidebarRail:Mu=!1,plugins:Du=[],...Lu}){const Bu=reactExports.useRef(Lu.firstPromptHook);Bu.current=Lu.firstPromptHook;const ju=reactExports.useMemo(()=>buildLoopReactor([...loopPlugins({...Lu,windowFrame:Lu.windowFrame||Pu!==void 0,firstPromptHook:()=>Bu.current?.()}),...Du]),[Lu.serverUrl,Lu.target,Lu.datalayerAgentSpecId,Lu.targetFixed,Lu.themeVariant,JSON.stringify(Lu.themeOverrides??null),Lu.colorMode,Lu.presence?.name,Lu.presence?.face,Lu.presence?.welcome,Lu.presence?.paused,Lu.showTokenUsage,JSON.stringify({...Lu.voice??{},engines:void 0,token:void 0}),Lu.thread?.id,JSON.stringify(Lu.datalayerCreatePayload??null),JSON.stringify(Lu.datalayerVisitors??null),Lu.datalayerKept?.url,Lu.embedToken,Lu.defaultEditor,Lu.showViewSelector,Lu.hideChatHeader,Lu.chatHeaderButtons,Lu.promptPlacement,Lu.autoFocusPrompt,Lu.suggestionLabels,Lu.fullScreenTopOffset,Lu.showAgentVariants,Lu.agentSummary,Lu.teamId,Lu.teamPicker,Lu.pageLayout,Lu.pageLayoutTurnPanel,Lu.pageLayoutTurnPanelFooter,Lu.pageLayoutPrompt,Lu.pageLayoutPromptAnchor,Lu.pageLayoutSize?.format,Lu.pageLayoutSize?.width,Lu.pageLayoutSize?.height,Lu.localAgentSpec,Lu.floatingPrompt,Lu.editorSelector,Lu.editors,Lu.conversation,Lu.commandPalette,Lu.pluginsPanel,Lu.windowFrame,Pu!==void 0,Du]);useReactor(ju);const Fu=jsxRuntimeExports.jsx(LoopWorkspace,{serverUrl:Lu.serverUrl??"",agentId:Au,reactor:ju,manageReactor:!1,showViewSelector:Lu.showViewSelector,showHeader:lo,chatHeaderActions:$u,headerActions:Ru,headerContainer:Iu,sidebarRail:Mu});return jsxRuntimeExports.jsx(QueryClientProvider,{client:internalQueryClient,children:Pu!==void 0?jsxRuntimeExports.jsx(WindowFrame,{title:Pu,height:Ou,children:Fu}):jsxRuntimeExports.jsx(Box,{height:"100%",minHeight:0,width:"100%",flex:"1 1 auto",minWidth:0,children:Fu})})}const RECORD_KIND_WORDS={session:"Session",tool_call:"Tool call",decision:"Rule",check:"Check",approval:"Approval",output:"Answer",feedback:"Feedback",turn:"Turn",run:"Working",notification:"Notification"};function entryOf(Au){return{uid:String(Au.uid??""),sessionUid:String(Au.session_uid??""),deploymentUid:String(Au.deployment_uid??""),version:Number(Au.version)||0,kind:String(Au.kind??"output"),summary:String(Au.summary??""),payload:Au.payload&&typeof Au.payload=="object"?Au.payload:{},createdAt:String(Au.created_at??"")}}function runEndOf(Au){const lo=Au.kind==="output"?Au.payload.status:void 0;return typeof lo=="string"&&lo in RUN_END_WORDS?lo:""}function entrySaid(Au){return Au.summary||RUN_END_WORDS[runEndOf(Au)]||""}function sessionSentence(Au){const lo=Au.filter(Ou=>Ou.kind==="tool_call").length,$u=Au.filter(Ou=>Ou.kind==="check"),Ru=Au.map(runEndOf).filter(Boolean),Iu=Ru.filter(Ou=>Ou==="answered").length,Pu=[lo===0?"No tool called":`${lo} tool call${lo===1?"":"s"}`];return $u.length&&Pu.push(`${$u.length} step${$u.length===1?"":"s"} a check did not let pass`),Ru[Ru.length-1]==="stopped"?Pu.push("stopped"):Iu&&Pu.push(`${Iu} answer${Iu===1?"":"s"}`),`${Pu.join(", ")}.`}async function read(Au,lo,$u){if(!Au.aiAgentsUrl)throw new Error("The record service is not configured.");const Ru=await fetch(`${Au.aiAgentsUrl.replace(/\/+$/,"")}/api/ai-agents/v1/apps${lo}`,{headers:Au.token?{Authorization:`Bearer ${Au.token}`}:{}}),Iu=await Ru.json().catch(()=>({}));if(!Ru.ok||Iu.success===!1)throw new Error(`${$u}: ${String(Iu.detail??Ru.status)}`);return Iu}async function listSessions(Au,lo,$u=20,Ru=!1){const Iu=await read(Au,`/sessions?app_uid=${encodeURIComponent(lo)}&limit=${$u}${Ru===null?"":`&tests=${Ru}`}`,"The sessions could not be read");return sessionPageOf(Iu)}async function readSession(Au,lo){const $u=await read(Au,`/records?session_uid=${encodeURIComponent(lo)}&limit=500`,"The session could not be read");return Array.isArray($u.entries)?$u.entries.map(entryOf).filter(Ru=>Ru.kind!=="run"):[]}const APP_ACTIVITY_WORDS={title:"Activity",unsaved:"Recorded once it is saved on Datalayer: each session there — its address, or its Preview on Datalayer — is listed here.",signedOut:"Its activity is its owner’s: sign in to Datalayer to read it.",none:"Nothing yet: a session on Datalayer — its address, or the Preview on Datalayer — is recorded here."},NO_TURN$3=signal$2({id:0,status:"idle"});function useRead(Au,lo,$u=!0){const[Ru,Iu]=reactExports.useState({loading:$u});return reactExports.useEffect(()=>{if(!$u)return;let Pu=!1;return Iu(Ou=>({...Ou,loading:!0})),Au().then(Ou=>!Pu&&Iu({value:Ou,loading:!1}),Ou=>!Pu&&Iu({error:Ou instanceof Error?Ou.message:String(Ou),loading:!1})),()=>{Pu=!0}},[lo,$u]),Ru}function Session({context:Au,session:lo}){const[$u,Ru]=reactExports.useState(!1),Iu=useRead(()=>readSession(Au,lo.uid),`${lo.uid}:${Au.token}`,$u),Pu=[sessionStateSaid(lo),sessionAgentSaid(lo),sessionLineageSaid(lo)].filter(Boolean);return jsxRuntimeExports.jsxs(Box,{as:"details",onToggle:Ou=>Ru(Ou.currentTarget.open),borderTop:"1px solid",borderColor:"border.muted",py:2,children:[jsxRuntimeExports.jsxs(Box,{as:"summary",cursor:"pointer",fontSize:1,children:[lo.startedAt?jsxRuntimeExports.jsx(RelativeTime,{datetime:lo.startedAt}):"A session",lo.title?` · ${lo.title}`:"",lo.version?` · version ${lo.version}`:"",Pu.length?` · ${Pu.join(" · ")}`:"",Iu.value?` · ${sessionSentence(Iu.value)}`:""]}),$u?Iu.loading?jsxRuntimeExports.jsx(StyledSpinner,{size:"small"}):Iu.error?jsxRuntimeExports.jsx(Text$3,{role:"alert",sx:{fontSize:1},children:Iu.error}):jsxRuntimeExports.jsx(Box,{as:"ol",pl:3,mt:2,mb:0,fontSize:1,children:(Iu.value??[]).map(Ou=>jsxRuntimeExports.jsxs(Box,{as:"li",mb:1,children:[jsxRuntimeExports.jsx(Label,{sx:{mr:2},children:RECORD_KIND_WORDS[Ou.kind]??Ou.kind}),entrySaid(Ou)]},Ou.uid))}):null]})}function AppActivity({appUid:Au}){const lo=useIAMStore(ju=>ju.token)??"",$u=useCoreStore(ju=>ju.configuration)?.aiAgentsUrl??"",Ru=useContributions(LoopChatTurn),Iu=useSignalValue$1(Ru[0]?.value.turn??NO_TURN$3),Pu=Iu.status!=="thinking"&&Iu.status!=="streaming",[Ou,Mu]=reactExports.useState(0);reactExports.useEffect(()=>{Pu&&Mu(Iu.id)},[Pu,Iu.id]);const Du={aiAgentsUrl:$u,token:lo},Lu=!!(Au&&lo),Bu=useRead(()=>listSessions(Du,Au??""),`${Au}:${lo}:${$u}:${Ou}`,Lu);return jsxRuntimeExports.jsxs(Box,{"data-testid":"app-activity",children:[jsxRuntimeExports.jsx(Heading$2,{as:"h3",sx:{fontSize:2,mb:2},children:APP_ACTIVITY_WORDS.title}),Au?lo?Bu.loading&&!Bu.value?jsxRuntimeExports.jsx(StyledSpinner,{size:"small"}):Bu.error?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:1,color:"fg.muted",m:0},children:Bu.error}):(Bu.value?.sessions??[]).length===0?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:1,color:"fg.muted",m:0},children:APP_ACTIVITY_WORDS.none}):(Bu.value?.sessions??[]).map(ju=>jsxRuntimeExports.jsx(Session,{context:Du,session:ju},ju.uid)):jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:1,color:"fg.muted",m:0},children:APP_ACTIVITY_WORDS.signedOut}):jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:1,color:"fg.muted",m:0},children:APP_ACTIVITY_WORDS.unsaved})]})}const APP_ACTIVITY_PLUGIN_NAME="@datalayer/loop-plugin-app-activity";function defineAppActivityPlugin(Au,lo){function $u(){return jsxRuntimeExports.jsx(AppActivity,{appUid:lo})}return{name:`${APP_ACTIVITY_PLUGIN_NAME}-${Au.id}`,displayName:`${Au.name}: activity`,description:`What ${Au.name} did, session by session, from its record.`,octicon:"pulse",build:()=>({components:[{id:"app-activity",slot:LoopSlots.sidebar,order:20,Component:$u,rail:{label:"Activity",icon:PulseIcon}}]})}}const APP_PANEL_WIDTH=380;function elementsByPlace(Au){const lo=Au.filter($u=>$u.where==="page");return{panels:Au.filter($u=>$u.where==="panel"),page:lo.length>0?lo[lo.length-1]:null}}function ElementBody({element:Au,send:lo}){return jsxRuntimeExports.jsx(AnswerShowsView,{display:Au.shows,send:($u,Ru)=>lo!==void 0&&!lo($u,Ru)})}function ElementHeader({element:Au}){return jsxRuntimeExports.jsxs(Box,{display:"flex",alignItems:"center",justifyContent:"space-between",gap:2,mb:2,children:[jsxRuntimeExports.jsx(Text$3,{as:"h2",sx:{fontSize:2,fontWeight:"bold",m:0},children:Au.title}),jsxRuntimeExports.jsx(IconButton,{icon:XIcon,variant:"invisible",size:"small","aria-label":`Close ${Au.title}`,onClick:()=>closeLoopElement(Au.id)})]})}function AppElements({workspace:Au}){const lo=reactExports.useSyncExternalStore(onLoopElements,openLoopElements,openLoopElements),{panels:$u,page:Ru}=elementsByPlace(lo),Iu=Au?.viewControls.send;return $u.length===0&&Ru===null?null:jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[$u.length>0?jsxRuntimeExports.jsx(Box,{as:"aside","aria-label":"Side panel",position:"absolute",top:0,right:0,bottom:0,width:`min(${APP_PANEL_WIDTH}px, 100%)`,zIndex:1,overflowY:"auto",borderLeft:"1px solid",borderColor:"border.default",bg:"canvas.subtle",boxShadow:"shadow.medium",p:3,display:"flex",flexDirection:"column",gap:3,children:$u.map(Pu=>jsxRuntimeExports.jsxs(Box,{as:"section","aria-label":Pu.title,children:[jsxRuntimeExports.jsx(ElementHeader,{element:Pu}),jsxRuntimeExports.jsx(ElementBody,{element:Pu,send:Iu})]},Pu.id))}):null,Ru!==null?jsxRuntimeExports.jsxs(Box,{role:"dialog","aria-label":Ru.title,position:"absolute",inset:0,zIndex:2,overflowY:"auto",bg:"canvas.default",p:[3,4],children:[jsxRuntimeExports.jsx(ElementHeader,{element:Ru}),jsxRuntimeExports.jsx(ElementBody,{element:Ru,send:Iu})]}):null]})}const QUESTION_DISPLAY_TYPE="application/vnd.datalayer.loop.question+json",SchemaForm=reactExports.lazy(()=>__vitePreload(()=>import("./chunks/SchemaForm-C6wDxDrg.js"),[],import.meta.url));function questionOf(Au){const lo=Au.data??{},$u=lo.kind;if(Au.type!==QUESTION_DISPLAY_TYPE||$u!=="text"&&$u!=="choice"&&$u!=="file"&&$u!=="form"||typeof lo.prompt!="string")throw new Error(`Display ${Au.id} is not a question`);const Ru=Iu=>Array.isArray(Iu)?Iu.filter(Pu=>typeof Pu=="string"):[];return{kind:$u,prompt:lo.prompt,options:Ru(lo.options),accept:Ru(lo.accept),form:lo.form&&typeof lo.form=="object"?lo.form:{},answered:typeof lo.answered=="string"?lo.answered:null,answerable:(Au.actions??[]).some(Iu=>Iu.name===ANSWER_ACTION)}}function QuestionView({display:Au,act:lo,upload:$u}){const Ru=questionOf(Au),[Iu,Pu]=reactExports.useState(""),[Ou,Mu]=reactExports.useState(null),Du=Bu=>{if(!lo){Mu("The chat cannot take an answer here.");return}Mu(null),Promise.resolve(lo({action:ANSWER_ACTION,payload:{value:Bu}})).catch(ju=>Mu(ju instanceof Error?ju.message:String(ju)))};if(Ru.answered!==null)return jsxRuntimeExports.jsxs(Text$3,{as:"p",sx:{color:"fg.muted",fontSize:1,m:0},children:["Answered: ",Ru.answered]});const Lu=Ru.answerable&&!!lo;return jsxRuntimeExports.jsxs(Box$1,{display:"flex",flexDirection:"column",gap:2,"data-question-kind":Ru.kind,children:[Ru.kind==="choice"?jsxRuntimeExports.jsx(Box$1,{display:"flex",gap:2,flexWrap:"wrap",children:Ru.options.map(Bu=>jsxRuntimeExports.jsx(ButtonComponent,{size:"small",disabled:!Lu,onClick:()=>Du(Bu),children:Bu},Bu))}):null,Ru.kind==="text"?jsxRuntimeExports.jsxs(Box$1,{as:"form",display:"flex",gap:2,onSubmit:Bu=>{Bu.preventDefault(),Iu.trim()&&Du(Iu.trim())},children:[jsxRuntimeExports.jsx(TextInput$1,{"aria-label":Ru.prompt,value:Iu,disabled:!Lu,onChange:Bu=>Pu(Bu.target.value)}),jsxRuntimeExports.jsx(ButtonComponent,{type:"submit",size:"small",disabled:!Lu||!Iu.trim(),children:"Answer"})]}):null,Ru.kind==="form"?jsxRuntimeExports.jsx(reactExports.Suspense,{fallback:null,children:jsxRuntimeExports.jsx(SchemaForm,{schema:Ru.form,disabled:!Lu,onSubmit:({formData:Bu})=>Du(Bu??{})})}):null,Ru.kind==="file"?jsxRuntimeExports.jsx("input",{type:"file","aria-label":Ru.prompt,accept:Ru.accept.join(",")||void 0,disabled:!Lu||!$u,onChange:Bu=>{const ju=Bu.target.files?.[0];if(ju){if(!$u){Mu("The chat cannot take a file here.");return}Mu(null),$u(ju).then(Fu=>Du(Fu)).catch(Fu=>Mu(Fu instanceof Error?Fu.message:String(Fu)))}}}):null,Ou?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{color:"danger.fg",fontSize:1,m:0},children:Ou}):null]})}const APP_ELEMENTS_PLUGIN_NAME="@datalayer/loop-plugin-app-elements",AppElementsPlugin={name:APP_ELEMENTS_PLUGIN_NAME,displayName:"Side panel and pages",description:"What an application opens beside the conversation: a side panel, or a page of its own.",octicon:"sidebar-expand",contributes:[contribution(Renderers,defineRenderer({type:QUESTION_DISPLAY_TYPE,component:QuestionView}),{id:"app-elements:question"})],build:()=>({components:[{id:"app-elements",slot:LoopSlots.root,Component:AppElements}]}),register:()=>clearLoopElements},appComponentsPluginName=Au=>`@datalayer/loop-plugin-app-components-${Au}`,hasCustomComponents=Au=>(Au.interface.customComponents??[]).length>0;function defineAppComponentsPlugin(Au,lo){const $u=Au.interface.customComponents??[];if($u.length===0)throw new Error(`“${Au.name}” has no component of its own to contribute.`);return{name:appComponentsPluginName(Au.id),displayName:`${Au.name}'s components`,description:`The components ${Au.name}'s developer wrote: ${$u.map(Ru=>Ru.name).join(", ")}.`,octicon:"apps",contributes:$u.flatMap(Ru=>[contribution(LoopCanvasBlock,{id:Ru.name,ui:`app:${Au.id}`,component:customComponentEntry(Ru,Au.version)},{id:Ru.name}),contribution(LoopA2uiComponent,{id:Ru.name,app:Au.id,implementation:customImplementation(Ru,Au.version,lo,Au.id)},{id:Ru.name})])}}const COMPUTER_PARTS=["browse","files","shell"],COMPUTER_PART_TOOLS={browse:["open_page","read_page","page_screenshot","click_on_page","type_on_page"],files:["list_computer_files","read_computer_file","write_computer_file"],shell:["execute_code","run_skill_script"]},COMPUTER_WORDS={title:"Computer",part:{browse:"Browse",files:"Files",shell:"Shell"},on:"on",off:"off",none:"It has no computer: browse, files and shell are all off. Turn one on in its permissions to give it one.",offSaid:Au=>`Off, so its agent is given no tool for it: ${Au.join(", ")}.`,browser:"Browser",noBrowser:"No browser is installed on its computer.",noPage:"Its browser has opened no page yet.",pageAlt:Au=>`The page its browser shows: ${Au}`,clickToAct:"Click on the page to click there; with the page selected, what you type goes to it.",typeOnPage:"Text to type on the page",type:"Type",address:"An address to open",open:"Open",scrollUp:"Scroll up",scrollDown:"Scroll down",agentHas:"Its agent has the computer.",youHave:"You have the computer: its agent waits for it until you hand it back.",someoneHas:"Somebody else has taken this computer over.",takeOver:"Take over",handBack:"Hand back",run:"Run",yourCode:"Python to run on its computer",terminal:"What ran on it",nothingRan:"Nothing has run on it yet in this conversation.",files:"Files",notStarted:"Its computer starts when its agent first uses it: no file yet.",emptyDirectory:"Empty.",up:"Up",download:"Download",signedOut:"Its computer is shown once you are signed in to Datalayer."};function computerParts(Au){const lo=Au.permissions?.computer;return{browse:!!lo?.browse,files:!!lo?.files,shell:!!lo?.shell}}const hasComputer=Au=>COMPUTER_PARTS.some(lo=>Au[lo]),partsOff=Au=>COMPUTER_PARTS.filter(lo=>!Au[lo]).map(lo=>COMPUTER_WORDS.part[lo].toLowerCase());function partOf(Au){return COMPUTER_PARTS.find(lo=>COMPUTER_PART_TOOLS[lo].includes(Au))}const OUTPUT_LIMIT=4e3;function outputOf(Au){let lo=Au;if(typeof lo=="string")try{const Ru=JSON.parse(lo);Ru&&typeof Ru=="object"&&!Array.isArray(Ru)&&(lo=Ru)}catch{}let $u;if(lo&&typeof lo=="object"&&!Array.isArray(lo)){const Ru=lo,Iu=[typeof Ru.stdout=="string"?Ru.stdout:Ru.output,Ru.stderr,Ru.error??Ru.execution_error??Ru.code_error].filter(Pu=>typeof Pu=="string"&&Pu.trim()!=="");$u=Iu.length>0?Iu.join(`
4023
4023
  `):"stdout"in Ru||"output"in Ru?"":JSON.stringify(lo,null,2)}else $u=typeof lo=="string"?lo:lo==null?"":JSON.stringify(lo,null,2);return $u.length>OUTPUT_LIMIT?`${$u.slice(0,OUTPUT_LIMIT)}
4024
4024
  … (${($u.length-OUTPUT_LIMIT).toLocaleString("en")} characters more)`:$u}function commandOf(Au){for(const lo of["code","path","script_name","url","selector"]){const $u=Au[lo];if(typeof $u=="string"&&$u.trim())return $u}return Object.keys(Au).length?JSON.stringify(Au):""}function terminalEntries(Au){const lo=[];for(const $u of Au){if($u.role!=="tool")continue;const Ru=partOf($u.name);Ru&&lo.push({tool:$u.name,part:Ru,command:commandOf($u.args??{}),output:$u.result===void 0?void 0:outputOf($u.result)})}return lo}const computerUrl=(Au,lo="")=>`${Au.serverUrl.replace(/\/+$/,"")}/api/v1/apps/agents/${encodeURIComponent(Au.agentId)}/computer${lo}`;function computerFileUrl(Au,lo){const $u=computerUrl(Au,`/file?path=${encodeURIComponent(lo)}`),Ru=(Au.userAppsUrl||"").trim();if(!Ru)return $u;try{const Iu=new URL($u),Pu=new URL(Ru);return Iu.protocol=Pu.protocol,Iu.host=Pu.host,Iu.toString()}catch{return $u}}async function asked(Au,lo,$u={}){const Ru=await fetch(computerUrl(Au,lo),{...$u,headers:{...$u.body?{"Content-Type":"application/json"}:{},...Au.token?{Authorization:`Bearer ${Au.token}`}:{}}});if(!Ru.ok){let Iu=`${Ru.status}`;try{const Pu=await Ru.json();Iu=typeof Pu.detail=="string"?Pu.detail:Iu}catch{}throw new Error(Iu)}return Ru}const readComputer=async Au=>(await asked(Au,"")).json(),listComputerFiles=async(Au,lo=".")=>(await(await asked(Au,`/files?path=${encodeURIComponent(lo)}`)).json()).entries,downloadComputerFile=async(Au,lo)=>{const $u=await fetch(computerFileUrl(Au,lo),{headers:Au.token?{Authorization:`Bearer ${Au.token}`}:{}});if(!$u.ok){let Ru=`${$u.status}`;try{const Iu=await $u.json();Ru=typeof Iu.detail=="string"?Iu.detail:Ru}catch{}throw new Error(Ru)}return $u.blob()},takeOverComputer=async Au=>(await asked(Au,"/take-over",{method:"POST"})).json(),handBackComputer=async Au=>{await asked(Au,"/hand-back",{method:"POST"})},runOnComputer=async(Au,lo)=>(await asked(Au,"/run",{method:"POST",body:JSON.stringify({code:lo})})).json(),BROWSER_KEYS=["Enter","Tab","Backspace","Escape","ArrowUp","ArrowDown","ArrowLeft","ArrowRight","PageUp","PageDown"],readBrowserScreenshot=async Au=>{const lo=await fetch(computerUrl(Au,"/browser/screenshot"),{headers:Au.token?{Authorization:`Bearer ${Au.token}`}:{},cache:"no-store"});if(lo.status!==404){if(!lo.ok){let $u=`${lo.status}`;try{const Ru=await lo.json();$u=typeof Ru.detail=="string"?Ru.detail:$u}catch{}throw new Error($u)}return lo.blob()}},onBrowser=async(Au,lo,$u)=>(await(await asked(Au,`/browser/${lo}`,{method:"POST",body:JSON.stringify($u)})).json()).page,clickOnBrowser=(Au,lo,$u)=>onBrowser(Au,"click",{x:lo,y:$u}),typeOnBrowser=(Au,lo)=>onBrowser(Au,"type",{text:lo}),pressOnBrowser=(Au,lo)=>onBrowser(Au,"key",{key:lo}),scrollBrowser=(Au,lo)=>onBrowser(Au,"scroll",{dy:lo}),openOnBrowser=(Au,lo)=>onBrowser(Au,"open",{url:lo});function pointOnPage(Au,lo,$u){const Ru=(Iu,Pu,Ou)=>Pu>0?Math.round(Iu*Ou/Pu):Iu;return{x:Math.max(0,Math.min($u.width,Ru(Au.x,lo.width,$u.width))),y:Math.max(0,Math.min($u.height,Ru(Au.y,lo.height,$u.height)))}}function parentOf(Au){const lo=Au.split("/").filter($u=>$u&&$u!==".");return lo.pop(),lo.length?lo.join("/"):"."}const NO_TURN$2=signal$2({id:0,status:"idle"}),NO_CONVERSATION$1=signal$2([]),MONO_FACE='ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace',MONO={fontFamily:MONO_FACE,fontSize:0,whiteSpace:"pre-wrap",wordBreak:"break-word",m:0};function Parts({app:Au}){const lo=computerParts(Au),$u=partsOff(lo);return jsxRuntimeExports.jsxs(Box,{"data-testid":"computer-parts",children:[jsxRuntimeExports.jsx(Box,{display:"flex",gap:1,flexWrap:"wrap",mb:1,children:COMPUTER_PARTS.map(Ru=>jsxRuntimeExports.jsxs(Label,{variant:lo[Ru]?"success":"secondary","data-part":Ru,"data-on":lo[Ru]?"true":"false",children:[COMPUTER_WORDS.part[Ru],":"," ",lo[Ru]?COMPUTER_WORDS.on:COMPUTER_WORDS.off]},Ru))}),$u.length>0&&$u.length<COMPUTER_PARTS.length?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:0,color:"fg.muted",m:0},children:COMPUTER_WORDS.offSaid($u)}):null]})}function Terminal({conversation:Au}){const lo=terminalEntries(Au);return jsxRuntimeExports.jsxs(Box,{"data-testid":"computer-terminal",children:[jsxRuntimeExports.jsx(Heading$2,{as:"h4",sx:{fontSize:1,mt:3,mb:1},children:COMPUTER_WORDS.terminal}),lo.length===0?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:1,color:"fg.muted",m:0},children:COMPUTER_WORDS.nothingRan}):jsxRuntimeExports.jsx(Box,{bg:"canvas.inset",border:"1px solid",borderColor:"border.muted",borderRadius:2,p:2,maxHeight:320,overflow:"auto",children:lo.map(($u,Ru)=>jsxRuntimeExports.jsxs(Box,{mb:2,children:[jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{...MONO,fontWeight:"semibold"},children:`$ ${$u.tool}${$u.command?`: ${$u.command}`:""}`}),$u.output===void 0?jsxRuntimeExports.jsx(StyledSpinner,{size:"small"}):jsxRuntimeExports.jsx(Text$3,{as:"pre",sx:{...MONO,color:"fg.muted"},children:$u.output})]},Ru))})]})}function save(Au,lo){const $u=URL.createObjectURL(new Blob([Au],{type:"application/octet-stream"})),Ru=document.createElement("a");Ru.href=$u,Ru.download=lo,Ru.click(),URL.revokeObjectURL($u)}function Files({context:Au,state:lo,ended:$u}){const[Ru,Iu]=reactExports.useState("."),[Pu,Ou]=reactExports.useState(),[Mu,Du]=reactExports.useState("");return reactExports.useEffect(()=>{if(!lo.started)return;let Lu=!1;return listComputerFiles(Au,Ru).then(Bu=>{Lu||(Ou(Bu),Du(""))},Bu=>!Lu&&Du(Bu instanceof Error?Bu.message:String(Bu))),()=>{Lu=!0}},[Au.serverUrl,Au.agentId,Au.token,Ru,lo.started,$u]),jsxRuntimeExports.jsxs(Box,{"data-testid":"computer-files",children:[jsxRuntimeExports.jsxs(Heading$2,{as:"h4",sx:{fontSize:1,mt:3,mb:1},children:[COMPUTER_WORDS.files,Ru!=="."?jsxRuntimeExports.jsx(Text$3,{sx:{fontWeight:"normal",color:"fg.muted"},children:` · ${Ru}`}):null]}),lo.started?Mu?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:1,color:"danger.fg",m:0},children:Mu}):Pu?jsxRuntimeExports.jsxs(Box,{as:"ul",listStyle:"none",p:0,m:0,children:[Ru!=="."?jsxRuntimeExports.jsx(Box,{as:"li",children:jsxRuntimeExports.jsx(ButtonComponent,{size:"small",variant:"invisible",onClick:()=>Iu(parentOf(Ru)),children:COMPUTER_WORDS.up})}):null,Pu.length===0?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:1,color:"fg.muted",m:0},children:COMPUTER_WORDS.emptyDirectory}):null,Pu.map(Lu=>jsxRuntimeExports.jsx(Box,{as:"li","data-path":Lu.path,display:"flex",alignItems:"center",gap:2,fontSize:1,py:1,borderTop:"1px solid",borderColor:"border.muted",children:Lu.type==="directory"?jsxRuntimeExports.jsx(ButtonComponent,{size:"small",variant:"invisible",onClick:()=>Iu(Lu.path),children:`${Lu.name}/`}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(Text$3,{sx:{flex:1,fontFamily:MONO_FACE,fontSize:0},children:Lu.name}),jsxRuntimeExports.jsx(Text$3,{sx:{color:"fg.muted",fontSize:0},children:`${Lu.size.toLocaleString("en")} bytes`}),jsxRuntimeExports.jsx(ButtonComponent,{size:"small","aria-label":`${COMPUTER_WORDS.download} ${Lu.name}`,onClick:()=>{downloadComputerFile(Au,Lu.path).then(Bu=>save(Bu,Lu.name),Bu=>Du(Bu instanceof Error?Bu.message:String(Bu)))},children:COMPUTER_WORDS.download})]})},Lu.path))]}):jsxRuntimeExports.jsx(StyledSpinner,{size:"small"}):jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:1,color:"fg.muted",m:0},children:COMPUTER_WORDS.notStarted})]})}const BROWSER_POLL_MS=1500;function BrowserView({context:Au,state:lo,mine:$u}){const[Ru,Iu]=reactExports.useState(),[Pu,Ou]=reactExports.useState(!1),[Mu,Du]=reactExports.useState(lo.page),[Lu,Bu]=reactExports.useState(""),[ju,Fu]=reactExports.useState(""),[zu,Uu]=reactExports.useState(""),[Hu,Vu]=reactExports.useState(0),Gu=reactExports.useRef(void 0);reactExports.useEffect(()=>Du(lo.page),[lo.page]),reactExports.useEffect(()=>{if(!lo.browser)return;let Yu=!1;const Xu=()=>readBrowserScreenshot(Au).then(td=>{Yu||(Bu(""),Ou(!td),Gu.current&&URL.revokeObjectURL(Gu.current),Gu.current=td?URL.createObjectURL(td):void 0,Iu(Gu.current))},td=>!Yu&&Bu(td instanceof Error?td.message:String(td)));Xu();const ed=setInterval(Xu,BROWSER_POLL_MS);return()=>{Yu=!0,clearInterval(ed)}},[Au.serverUrl,Au.agentId,Au.token,lo.browser,Hu]),reactExports.useEffect(()=>()=>{Gu.current&&URL.revokeObjectURL(Gu.current)},[]);const Wu=Yu=>Yu.then(Xu=>{Du(Xu),Bu(""),Vu(ed=>ed+1)},Xu=>Bu(Xu instanceof Error?Xu.message:String(Xu))),Ku=Yu=>{const Xu=Yu.currentTarget,ed=Xu.getBoundingClientRect(),td=pointOnPage({x:Yu.clientX-ed.left,y:Yu.clientY-ed.top},{width:ed.width,height:ed.height},{width:Xu.naturalWidth,height:Xu.naturalHeight});Xu.focus(),Wu(clickOnBrowser(Au,td.x,td.y))},Ju=Yu=>{Yu.metaKey||Yu.ctrlKey||Yu.altKey||(BROWSER_KEYS.includes(Yu.key)?(Yu.preventDefault(),Wu(pressOnBrowser(Au,Yu.key))):Yu.key.length===1&&(Yu.preventDefault(),Wu(typeOnBrowser(Au,Yu.key))))};return jsxRuntimeExports.jsxs(Box,{"data-testid":"computer-browser",children:[jsxRuntimeExports.jsxs(Heading$2,{as:"h4",sx:{fontSize:1,mt:3,mb:1},children:[COMPUTER_WORDS.browser,Mu?jsxRuntimeExports.jsx(Text$3,{sx:{fontWeight:"normal",color:"fg.muted"},children:` · ${Mu.title||Mu.url}`}):null]}),lo.browser?Pu||!Ru?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:1,color:"fg.muted",m:0},children:Pu?COMPUTER_WORDS.noPage:null}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[Mu?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontFamily:MONO_FACE,fontSize:0,color:"fg.muted",m:0,mb:1,wordBreak:"break-all"},children:Mu.url}):null,jsxRuntimeExports.jsx("img",{src:Ru,alt:COMPUTER_WORDS.pageAlt(Mu?.title||Mu?.url||""),"data-testid":"computer-browser-page",tabIndex:$u?0:-1,onClick:$u?Ku:void 0,onKeyDown:$u?Ju:void 0,style:{width:"100%",height:"auto",display:"block",border:"1px solid var(--borderColor-muted, #d0d7de)",borderRadius:6,cursor:$u?"pointer":"default"}})]}):jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:1,color:"fg.muted",m:0},children:COMPUTER_WORDS.noBrowser}),Lu?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:1,color:"danger.fg",m:0,mt:1},children:Lu}):null,$u&&lo.browser?jsxRuntimeExports.jsxs(Box,{mt:2,"data-testid":"computer-browser-controls",children:[jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:0,color:"fg.muted",m:0,mb:1},children:COMPUTER_WORDS.clickToAct}),jsxRuntimeExports.jsxs(Box,{display:"flex",gap:1,mb:1,children:[jsxRuntimeExports.jsx(TextInput$1,{size:"small","aria-label":COMPUTER_WORDS.typeOnPage,placeholder:COMPUTER_WORDS.typeOnPage,value:ju,onChange:Yu=>Fu(Yu.target.value),sx:{flex:1}}),jsxRuntimeExports.jsx(ButtonComponent,{size:"small",disabled:!ju,onClick:()=>{Wu(typeOnBrowser(Au,ju)),Fu("")},children:COMPUTER_WORDS.type}),jsxRuntimeExports.jsx(ButtonComponent,{size:"small",onClick:()=>{Wu(pressOnBrowser(Au,"Enter"))},children:"Enter"})]}),jsxRuntimeExports.jsxs(Box,{display:"flex",gap:1,mb:1,children:[jsxRuntimeExports.jsx(TextInput$1,{size:"small","aria-label":COMPUTER_WORDS.address,placeholder:COMPUTER_WORDS.address,value:zu,onChange:Yu=>Uu(Yu.target.value),sx:{flex:1}}),jsxRuntimeExports.jsx(ButtonComponent,{size:"small",disabled:!zu.trim(),onClick:()=>{Wu(openOnBrowser(Au,zu.trim()))},children:COMPUTER_WORDS.open})]}),jsxRuntimeExports.jsxs(Box,{display:"flex",gap:1,children:[jsxRuntimeExports.jsx(ButtonComponent,{size:"small",onClick:()=>{Wu(scrollBrowser(Au,-400))},children:COMPUTER_WORDS.scrollUp}),jsxRuntimeExports.jsx(ButtonComponent,{size:"small",onClick:()=>{Wu(scrollBrowser(Au,400))},children:COMPUTER_WORDS.scrollDown})]})]}):null]})}function YourTerminal({context:Au}){const[lo,$u]=reactExports.useState(""),[Ru,Iu]=reactExports.useState(!1),[Pu,Ou]=reactExports.useState([]),Mu=()=>{Iu(!0),runOnComputer(Au,lo).then(Du=>{Ou(Lu=>[...Lu,{code:lo,output:Du}]),$u(""),Iu(!1)},Du=>{Ou(Lu=>[...Lu,{code:lo,output:{stdout:"",stderr:"",error:Du instanceof Error?Du.message:String(Du)}}]),Iu(!1)})};return jsxRuntimeExports.jsxs(Box,{"data-testid":"computer-your-terminal",mt:2,children:[Pu.map((Du,Lu)=>jsxRuntimeExports.jsxs(Box,{mb:2,children:[jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{...MONO,fontWeight:"semibold"},children:`>>> ${Du.code}`}),jsxRuntimeExports.jsx(Text$3,{as:"pre",sx:{...MONO,color:"fg.muted"},children:[Du.output.stdout,Du.output.stderr,Du.output.error].filter(Boolean).join(`
4025
- `)})]},Lu)),jsxRuntimeExports.jsx(Textarea,{"aria-label":COMPUTER_WORDS.yourCode,placeholder:COMPUTER_WORDS.yourCode,value:lo,onChange:Du=>$u(Du.target.value),sx:{width:"100%",fontFamily:MONO_FACE},rows:3}),jsxRuntimeExports.jsx(ButtonComponent,{size:"small",sx:{mt:1},disabled:Ru||!lo.trim(),onClick:Mu,children:COMPUTER_WORDS.run})]})}function AppComputer({app:Au,workspace:lo}){const $u=useIAMStore(sd=>sd.token)??"",Ru=useContributions(LoopChatTurn),Iu=useSignalValue$1(Ru[0]?.value.turn??NO_TURN$2),Pu=useSignalValue$1(Ru[0]?.value.conversation??NO_CONVERSATION$1),Ou=Iu.status!=="thinking"&&Iu.status!=="streaming",[Mu,Du]=reactExports.useState(0);reactExports.useEffect(()=>{Ou&&Du(Iu.id)},[Ou,Iu.id]);const Lu=useChatWords(),Bu=lo?agentServerOf(lo.sandbox,lo.serverUrl):void 0,ju=Bu===void 0?noRuntimeSaid(lo?.sandbox??IDLE_SANDBOX_SNAPSHOT,Lu):void 0,Fu=lo?.agentId||Au.id,[zu,Uu]=reactExports.useState(),Hu=zu?.servedFrom??"",Vu=reactExports.useMemo(()=>Bu===void 0?void 0:{serverUrl:Bu,agentId:Fu,token:$u||void 0,userAppsUrl:Hu||void 0},[Bu,Fu,$u,Hu]),Gu=computerParts(Au),[Wu,Ku]=reactExports.useState(""),[Ju,Yu]=reactExports.useState(!1),Xu=reactExports.useRef(!0);reactExports.useEffect(()=>(Xu.current=!0,()=>{Xu.current=!1}),[]);const ed=reactExports.useCallback(()=>{Vu&&readComputer(Vu).then(sd=>{Xu.current&&(Uu(sd),Ku(""))},sd=>Xu.current&&Ku(sd instanceof Error?sd.message:String(sd)))},[Vu]),td=hasComputer(Gu);reactExports.useEffect(()=>{td&&Vu&&ed()},[td,Vu,ed,Mu]);const nd=sd=>{Vu&&(Yu(!0),sd(Vu).then(()=>{Xu.current&&(Yu(!1),ed())},ad=>{Xu.current&&(Yu(!1),Ku(ad instanceof Error?ad.message:String(ad)))}))},od=!!zu?.yours;return jsxRuntimeExports.jsxs(Box,{"data-testid":"app-computer",children:[jsxRuntimeExports.jsx(Heading$2,{as:"h3",sx:{fontSize:2,mb:2},children:COMPUTER_WORDS.title}),jsxRuntimeExports.jsx(Parts,{app:Au}),td?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[ju?jsxRuntimeExports.jsx(Text$3,{as:"p",role:"status",sx:{fontSize:1,color:"fg.default",m:0,mt:2},children:ju}):null,Wu?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:1,color:"danger.fg",m:0,mt:2},children:Wu}):null,zu&&Vu?jsxRuntimeExports.jsxs(Box,{mt:2,"data-testid":"computer-holder",children:[jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:1,m:0,mb:1},children:zu.held?od?COMPUTER_WORDS.youHave:COMPUTER_WORDS.someoneHas:COMPUTER_WORDS.agentHas}),zu.held?od?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(ButtonComponent,{size:"small",variant:"primary",disabled:Ju,onClick:()=>nd(handBackComputer),children:COMPUTER_WORDS.handBack}),jsxRuntimeExports.jsx(YourTerminal,{context:Vu})]}):null:jsxRuntimeExports.jsx(ButtonComponent,{size:"small",disabled:Ju,onClick:()=>nd(takeOverComputer),children:COMPUTER_WORDS.takeOver})]}):null,Gu.browse&&zu&&Vu?jsxRuntimeExports.jsx(BrowserView,{context:Vu,state:zu,mine:od}):null,jsxRuntimeExports.jsx(Terminal,{conversation:Pu}),zu&&Vu?jsxRuntimeExports.jsx(Files,{context:Vu,state:zu,ended:Mu}):null]}):jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:1,color:"fg.muted",m:0,mt:1},children:COMPUTER_WORDS.none})]})}const APP_COMPUTER_PLUGIN_NAME="@datalayer/loop-plugin-app-computer";function defineAppComputerPlugin(Au){function lo({workspace:Ru}){return jsxRuntimeExports.jsx(AppComputer,{app:Au,workspace:Ru})}return{name:`${APP_COMPUTER_PLUGIN_NAME}-${Au.id}`,displayName:`${Au.name}: computer`,description:`The computer ${Au.name} runs on: what ran on it, its files, and taking it over.`,octicon:"device-desktop",build:()=>({components:[{id:"app-computer",slot:LoopSlots.sidebar,order:30,Component:lo,rail:{label:"Computer",icon:DeviceDesktopIcon}}]})}}const SESSION_RULE_DECISIONS=["allow","ask","deny"],SESSION_RULE_CLASSES=["read","write","send","buy","delete","execute"],SESSION_RULES_WORDS={title:"This session",none:"No rule of your own on this session yet.",noSession:"Start a conversation to add a rule to its session.",add:"Add",remove:"Remove",namePlaceholder:"A name, quoted in every sentence it decides",decisions:{allow:"do it",ask:"ask me first",deny:"leave it to me"},classes:{read:"reading",write:"writing",send:"sending",buy:"buying",delete:"deleting",execute:"running a command"},scopes:{organization:"your organization",team:"this application",session:"this session"},goneWithSession:"In force at once, for this session only; gone when it ends.",unavailable:Au=>`Nothing is decided right now: ${Au}`},WHERE_WORDS={inside:"inside the workspace",outside:"outside the workspace"};function sessionRuleInWords(Au){const lo=(Au.classes??[]).map(Ru=>SESSION_RULES_WORDS.classes[Ru]??Ru);let $u=lo.length>0?lo.join(", "):"everything";return(Au.where==="inside"||Au.where==="outside")&&($u=`${$u} ${WHERE_WORDS[Au.where]}`),Au.paths&&Au.paths.length>0&&($u=`${$u} (${Au.paths.join(", ")})`),Au.commands&&Au.commands.length>0&&($u=`${$u} matching ${Au.commands.map(Ru=>`\`${Ru}\``).join(" or ")}`),`${$u}: ${SESSION_RULES_WORDS.decisions[Au.decision]}`}const FILE_AND_SHELL_RULES=[{name:"Edit inside the workspace",decision:"allow",classes:["write"],where:"inside"},{name:"Ask before deleting a file",decision:"ask",classes:["delete"]},{name:"Ask before running a command",decision:"ask",classes:["execute"]},{name:"Leave files outside the workspace to me",decision:"deny",classes:["read","write","delete"],where:"outside"},{name:"Ask before git push",decision:"ask",classes:["execute"],commands:["^git\\s+push\\b"]},{name:"Ask before installing a package",decision:"ask",classes:["execute"],commands:["\\b(pip|npm|uv|yarn|apt(-get)?)\\s+(install|add)\\b"]},{name:"Leave sudo to me",decision:"deny",classes:["execute"],commands:["^sudo\\b"]}];function sessionRuleOf(Au){const lo=Au.name.trim();if(!lo)return"A rule needs a name: it is quoted in every sentence it decides.";if(!SESSION_RULE_DECISIONS.includes(Au.decision))return`A rule says ${SESSION_RULE_DECISIONS.join(", ")}, not “${Au.decision}”.`;const $u=Au.classes.filter(Ru=>SESSION_RULE_CLASSES.includes(Ru));return{name:lo,decision:Au.decision,classes:$u}}const sessionRulesUrl=(Au,lo)=>`${Au}/api/v1/apps/sessions/${encodeURIComponent(lo)}/rules`;function parsed(Au){try{return Au?JSON.parse(Au):null}catch{return null}}async function answered(Au,lo){const $u=parsed(await Au.text());if(!Au.ok){const Ru=$u&&typeof $u=="object"&&"detail"in $u?String($u.detail):`${lo} (${Au.status})`;throw new Error(Ru)}return $u}async function readSessionRules(Au,lo,$u,Ru=fetch){const Iu=await Ru(sessionRulesUrl(Au,$u),{headers:{Authorization:`Bearer ${lo}`}});return answered(Iu,"The rules of the session could not be read")}async function addSessionRule(Au,lo,$u,Ru,Iu=fetch){const Pu=await Iu(sessionRulesUrl(Au,$u),{method:"POST",headers:{Authorization:`Bearer ${lo}`,"Content-Type":"application/json"},body:JSON.stringify(Ru)});return answered(Pu,"The rule could not be added")}async function removeSessionRule(Au,lo,$u,Ru,Iu=fetch){const Pu=await Iu(`${sessionRulesUrl(Au,$u)}/${encodeURIComponent(Ru)}`,{method:"DELETE",headers:{Authorization:`Bearer ${lo}`}});return answered(Pu,"The rule could not be removed")}const SAVE_TOOL="save_to_space",SAVE_WORDS={approve:"Approve and save",decline:"Decline",where:Au=>Au?`To keep as a page of ${Au}:`:"To keep as a page of its Space:"};function draftOfApproval(Au){if(Au.tool_name!==SAVE_TOOL)return null;const lo=$u=>{const Ru=Au.tool_args?.[$u];return typeof Ru=="string"?Ru:""};return{title:lo("title"),content:lo("content"),space:lo("space")}}const APP_RULES_WORDS={title:"Rules and approvals",byDefault:"With no rule of its own: reading is done, anything else waits for you.",none:"It has no rule of its own.",waiting:"Waiting for you",nothingWaiting:"Nothing is waiting for your yes.",signedOut:"Its approvals reach you here once you are signed in to Datalayer.",offline:"Approvals are not connected yet: what you approve or reject is not sent until they are.",approve:"Approve",reject:"Reject"};function ruleInWords(Au){const lo=BEHAVIOUR_WORDS[Au.behaviour];return{action:Au.action,covers:Au.appliesTo.map(coverOf).join(", "),says:lo.says,means:lo.means}}const ruleOfApproval=Au=>{const lo=Au.tool_args?._rule??Au.tool_args?._check;return typeof lo=="string"?lo:""};function approvalsOfApp(Au,lo){return Au.filter($u=>$u.agent_id===lo||$u.tool_args?._app===lo)}const PENDING={status:"pending"};function DraftShown({draft:Au}){return jsxRuntimeExports.jsxs(Box,{"data-testid":"app-draft",mt:1,children:[jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{m:0,fontSize:0,color:"fg.muted"},children:SAVE_WORDS.where(Au.space)}),jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{m:0,fontWeight:"semibold"},children:Au.title}),jsxRuntimeExports.jsx(Box,{as:"pre",m:0,mt:1,p:2,maxHeight:240,overflow:"auto",whiteSpace:"pre-wrap",fontFamily:"inherit",fontSize:0,bg:"canvas.subtle",borderRadius:2,children:Au.content})]})}function Approvals({app:Au}){const lo=useToolApprovalsQuery(PENDING),$u=useApproveToolRequest(),Ru=useRejectToolRequest(),Iu=reactExports.useMemo(()=>approvalsOfApp(lo.data?.approvals??[],Au.id),[lo.data,Au.id]);return jsxRuntimeExports.jsxs(Box,{"data-testid":"app-approvals",children:[jsxRuntimeExports.jsx(Heading$2,{as:"h4",sx:{fontSize:1,mt:3,mb:1},children:APP_RULES_WORDS.waiting}),$u.connectionState!=="connected"?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:0,color:"fg.muted",m:0,mb:1},children:APP_RULES_WORDS.offline}):null,Iu.length===0?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:1,color:"fg.muted",m:0},children:APP_RULES_WORDS.nothingWaiting}):jsxRuntimeExports.jsx(Box,{as:"ul",listStyle:"none",p:0,m:0,children:Iu.map(Pu=>{const Ou=draftOfApproval(Pu);return jsxRuntimeExports.jsxs(Box,{as:"li",py:2,borderTop:"1px solid",borderColor:"border.muted",fontSize:1,children:[jsxRuntimeExports.jsx(Text$3,{sx:{fontWeight:"semibold"},children:Pu.tool_name}),ruleOfApproval(Pu)?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{m:0,color:"fg.muted",fontSize:0},children:ruleOfApproval(Pu)}):null,Ou?jsxRuntimeExports.jsx(DraftShown,{draft:Ou}):null,jsxRuntimeExports.jsxs(Box,{display:"flex",gap:2,mt:1,children:[jsxRuntimeExports.jsx(ButtonComponent,{size:"small",variant:"primary",disabled:$u.isPending,onClick:()=>$u.mutate({id:Pu.id}),children:Ou?SAVE_WORDS.approve:APP_RULES_WORDS.approve}),jsxRuntimeExports.jsx(ButtonComponent,{size:"small",disabled:Ru.isPending,onClick:()=>Ru.mutate({id:Pu.id}),children:Ou?SAVE_WORDS.decline:APP_RULES_WORDS.reject})]})]},Pu.id)})})]})}function SessionRules({agentServerUrl:Au,sessionUid:lo,token:$u}){const[Ru,Iu]=reactExports.useState(null),[Pu,Ou]=reactExports.useState(""),[Mu,Du]=reactExports.useState(""),[Lu,Bu]=reactExports.useState("ask"),[ju,Fu]=reactExports.useState("send"),[zu,Uu]=reactExports.useState(!1),Hu=reactExports.useCallback(()=>{let Wu=!1;return readSessionRules(Au,$u,lo).then(Ku=>!Wu&&Iu(Ku),Ku=>!Wu&&Ou(Ku instanceof Error?Ku.message:String(Ku))),()=>{Wu=!0}},[Au,$u,lo]);reactExports.useEffect(Hu,[Hu]);const Vu=async Wu=>{Uu(!0),Ou("");try{Iu(await Wu())}catch(Ku){Ou(Ku instanceof Error?Ku.message:String(Ku))}finally{Uu(!1)}},Gu=()=>{const Wu=sessionRuleOf({name:Mu,decision:Lu,classes:[ju]});if(typeof Wu=="string"){Ou(Wu);return}Vu(()=>addSessionRule(Au,$u,lo,Wu)).then(()=>Du(""))};return jsxRuntimeExports.jsxs(Box,{"data-testid":"session-rules",mt:3,children:[jsxRuntimeExports.jsx(Heading$2,{as:"h4",sx:{fontSize:1,mb:1},children:SESSION_RULES_WORDS.title}),Ru?.unavailable?jsxRuntimeExports.jsx(Text$3,{as:"p",role:"alert",sx:{fontSize:0,m:0,mb:1},children:SESSION_RULES_WORDS.unavailable(Ru.unavailable)}):null,Ru&&Ru.session_rules.length===0?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:1,color:"fg.muted",m:0},children:SESSION_RULES_WORDS.none}):jsxRuntimeExports.jsx(Box,{as:"ul",listStyle:"none",p:0,m:0,children:(Ru?.session_rules??[]).map(Wu=>jsxRuntimeExports.jsxs(Box,{as:"li",py:1,fontSize:1,display:"flex",gap:2,alignItems:"center",children:[jsxRuntimeExports.jsx(Text$3,{sx:{fontWeight:"semibold"},children:Wu.name}),jsxRuntimeExports.jsx(Text$3,{sx:{color:"fg.muted",fontSize:0},children:sessionRuleInWords(Wu)}),jsxRuntimeExports.jsx(ButtonComponent,{size:"small",variant:"invisible",disabled:zu,onClick:()=>{Vu(()=>removeSessionRule(Au,$u,lo,Wu.name))},children:SESSION_RULES_WORDS.remove})]},Wu.name))}),jsxRuntimeExports.jsxs(Box,{display:"flex",gap:1,mt:1,flexWrap:"wrap",alignItems:"center",children:[jsxRuntimeExports.jsx(TextInput$1,{size:"small",value:Mu,placeholder:SESSION_RULES_WORDS.namePlaceholder,"aria-label":"The rule's name",onChange:Wu=>Du(Wu.target.value)}),jsxRuntimeExports.jsx(Select$1,{size:"small",value:ju,"aria-label":"What it covers",onChange:Wu=>Fu(Wu.target.value),children:SESSION_RULE_CLASSES.map(Wu=>jsxRuntimeExports.jsx(Select$1.Option,{value:Wu,children:SESSION_RULES_WORDS.classes[Wu]},Wu))}),jsxRuntimeExports.jsx(Select$1,{size:"small",value:Lu,"aria-label":"What it says",onChange:Wu=>Bu(Wu.target.value),children:SESSION_RULE_DECISIONS.map(Wu=>jsxRuntimeExports.jsx(Select$1.Option,{value:Wu,children:SESSION_RULES_WORDS.decisions[Wu]},Wu))}),jsxRuntimeExports.jsx(ButtonComponent,{size:"small",disabled:zu,onClick:Gu,children:SESSION_RULES_WORDS.add})]}),jsxRuntimeExports.jsx(Box,{display:"flex",gap:1,mt:1,flexWrap:"wrap","data-testid":"session-rules-file-and-shell",children:FILE_AND_SHELL_RULES.map(Wu=>jsxRuntimeExports.jsx(ButtonComponent,{size:"small",variant:"invisible",disabled:zu,title:sessionRuleInWords(Wu),onClick:()=>{Vu(()=>addSessionRule(Au,$u,lo,Wu))},children:Wu.name},Wu.name))}),Pu?jsxRuntimeExports.jsx(Text$3,{as:"p",role:"alert",sx:{fontSize:0,m:0,mt:1},children:Pu}):null,jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:0,color:"fg.muted",mt:1,mb:0},children:SESSION_RULES_WORDS.goneWithSession})]})}function sessionUidOf(Au){return Au?.conversationId||Au?.thread||void 0}function AppRulesCard({app:Au,workspace:lo}){const $u=useIAMStore(Ou=>Ou.token)??"",Ru=!!$u,Iu=lo?agentServerOf(lo.sandbox,lo.serverUrl):void 0,Pu=sessionUidOf(lo);return jsxRuntimeExports.jsxs(Box,{"data-testid":"app-rules",mb:4,children:[jsxRuntimeExports.jsx(Heading$2,{as:"h3",sx:{fontSize:2,mb:2},children:APP_RULES_WORDS.title}),Au.rules.length===0?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:1,color:"fg.muted",m:0},children:APP_RULES_WORDS.none}):jsxRuntimeExports.jsx(Box,{as:"ul",listStyle:"none",p:0,m:0,children:Au.rules.map(ruleInWords).map((Ou,Mu)=>jsxRuntimeExports.jsxs(Box,{as:"li",py:1,fontSize:1,children:[jsxRuntimeExports.jsx(Text$3,{children:Ou.action})," ",jsxRuntimeExports.jsx(Label,{title:Ou.means,children:Ou.says}),jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{m:0,color:"fg.muted",fontSize:0},children:Ou.covers})]},Mu))}),jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:0,color:"fg.muted",mt:1,mb:0},children:APP_RULES_WORDS.byDefault}),Ru?jsxRuntimeExports.jsx(Approvals,{app:Au}):jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:1,color:"fg.muted",mt:3,mb:0},children:APP_RULES_WORDS.signedOut}),Ru&&Iu?Pu?jsxRuntimeExports.jsx(SessionRules,{agentServerUrl:Iu,sessionUid:Pu,token:$u}):jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:0,color:"fg.muted",mt:3,mb:0},children:SESSION_RULES_WORDS.noSession}):null]})}const APP_RULES_PLUGIN_NAME="@datalayer/loop-plugin-app-rules";function defineAppRulesPlugin(Au){function lo(Ru){return jsxRuntimeExports.jsx(AppRulesCard,{app:Au,workspace:Ru.workspace})}return{name:`${APP_RULES_PLUGIN_NAME}-${Au.id}`,displayName:`${Au.name}: rules and approvals`,description:`When ${Au.name} acts alone, when it asks, and what waits for your yes.`,octicon:"shield-check",build:()=>({components:[{id:"app-rules",slot:LoopSlots.sidebar,order:10,Component:lo,rail:{label:"Rules",icon:ShieldCheckIcon}}]})}}const COMMAND_INPUT="{input}";function commandPrompt(Au,lo=""){const $u=lo.trim();return Au.prompt.includes(COMMAND_INPUT)?Au.prompt.split(COMMAND_INPUT).join($u).trim():$u?`${Au.prompt}
4025
+ `)})]},Lu)),jsxRuntimeExports.jsx(Textarea,{"aria-label":COMPUTER_WORDS.yourCode,placeholder:COMPUTER_WORDS.yourCode,value:lo,onChange:Du=>$u(Du.target.value),sx:{width:"100%",fontFamily:MONO_FACE},rows:3}),jsxRuntimeExports.jsx(ButtonComponent,{size:"small",sx:{mt:1},disabled:Ru||!lo.trim(),onClick:Mu,children:COMPUTER_WORDS.run})]})}function AppComputer({app:Au,workspace:lo}){const $u=useIAMStore(sd=>sd.token)??"",Ru=useContributions(LoopChatTurn),Iu=useSignalValue$1(Ru[0]?.value.turn??NO_TURN$2),Pu=useSignalValue$1(Ru[0]?.value.conversation??NO_CONVERSATION$1),Ou=Iu.status!=="thinking"&&Iu.status!=="streaming",[Mu,Du]=reactExports.useState(0);reactExports.useEffect(()=>{Ou&&Du(Iu.id)},[Ou,Iu.id]);const Lu=useChatWords(),Bu=lo?agentServerOf(lo.sandbox,lo.serverUrl):void 0,ju=Bu===void 0?noRuntimeSaid(lo?.sandbox??IDLE_SANDBOX_SNAPSHOT,Lu):void 0,Fu=lo?.agentId||Au.id,[zu,Uu]=reactExports.useState(),Hu=zu?.servedFrom??"",Vu=reactExports.useMemo(()=>Bu===void 0?void 0:{serverUrl:Bu,agentId:Fu,token:$u||void 0,userAppsUrl:Hu||void 0},[Bu,Fu,$u,Hu]),Gu=computerParts(Au),[Wu,Ku]=reactExports.useState(""),[Ju,Yu]=reactExports.useState(!1),Xu=reactExports.useRef(!0);reactExports.useEffect(()=>(Xu.current=!0,()=>{Xu.current=!1}),[]);const ed=reactExports.useCallback(()=>{Vu&&readComputer(Vu).then(sd=>{Xu.current&&(Uu(sd),Ku(""))},sd=>Xu.current&&Ku(sd instanceof Error?sd.message:String(sd)))},[Vu]),td=hasComputer(Gu);reactExports.useEffect(()=>{td&&Vu&&ed()},[td,Vu,ed,Mu]);const nd=sd=>{Vu&&(Yu(!0),sd(Vu).then(()=>{Xu.current&&(Yu(!1),ed())},ad=>{Xu.current&&(Yu(!1),Ku(ad instanceof Error?ad.message:String(ad)))}))},od=!!zu?.yours;return jsxRuntimeExports.jsxs(Box,{"data-testid":"app-computer",children:[jsxRuntimeExports.jsx(Heading$2,{as:"h3",sx:{fontSize:2,mb:2},children:COMPUTER_WORDS.title}),jsxRuntimeExports.jsx(Parts,{app:Au}),td?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[ju?jsxRuntimeExports.jsx(Text$3,{as:"p",role:"status",sx:{fontSize:1,color:"fg.default",m:0,mt:2},children:ju}):null,Wu?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:1,color:"danger.fg",m:0,mt:2},children:Wu}):null,zu&&Vu?jsxRuntimeExports.jsxs(Box,{mt:2,"data-testid":"computer-holder",children:[jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:1,m:0,mb:1},children:zu.held?od?COMPUTER_WORDS.youHave:COMPUTER_WORDS.someoneHas:COMPUTER_WORDS.agentHas}),zu.held?od?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(ButtonComponent,{size:"small",variant:"primary",disabled:Ju,onClick:()=>nd(handBackComputer),children:COMPUTER_WORDS.handBack}),jsxRuntimeExports.jsx(YourTerminal,{context:Vu})]}):null:jsxRuntimeExports.jsx(ButtonComponent,{size:"small",disabled:Ju,onClick:()=>nd(takeOverComputer),children:COMPUTER_WORDS.takeOver})]}):null,Gu.browse&&zu&&Vu?jsxRuntimeExports.jsx(BrowserView,{context:Vu,state:zu,mine:od}):null,jsxRuntimeExports.jsx(Terminal,{conversation:Pu}),zu&&Vu?jsxRuntimeExports.jsx(Files,{context:Vu,state:zu,ended:Mu}):null]}):jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:1,color:"fg.muted",m:0,mt:1},children:COMPUTER_WORDS.none})]})}const APP_COMPUTER_PLUGIN_NAME="@datalayer/loop-plugin-app-computer";function defineAppComputerPlugin(Au){function lo({workspace:Ru}){return jsxRuntimeExports.jsx(AppComputer,{app:Au,workspace:Ru})}return{name:`${APP_COMPUTER_PLUGIN_NAME}-${Au.id}`,displayName:`${Au.name}: computer`,description:`The computer ${Au.name} runs on: what ran on it, its files, and taking it over.`,octicon:"device-desktop",build:()=>({components:[{id:"app-computer",slot:LoopSlots.sidebar,order:30,Component:lo,rail:{label:"Computer",icon:DeviceDesktopIcon}}]})}}const APP_RULES_PLUGIN_NAME="@datalayer/loop-plugin-app-rules";function defineAppRulesPlugin(Au){function lo(Ru){return jsxRuntimeExports.jsx(AppRulesCard,{app:Au,workspace:Ru.workspace})}return{name:`${APP_RULES_PLUGIN_NAME}-${Au.id}`,displayName:`${Au.name}: rules and approvals`,description:`When ${Au.name} acts alone, when it asks, and what waits for your yes.`,octicon:"shield-check",build:()=>({components:[{id:"app-rules",slot:LoopSlots.sidebar,order:10,Component:lo,rail:{label:"Rules",icon:ShieldCheckIcon}}]})}}const COMMAND_INPUT="{input}";function commandPrompt(Au,lo=""){const $u=lo.trim();return Au.prompt.includes(COMMAND_INPUT)?Au.prompt.split(COMMAND_INPUT).join($u).trim():$u?`${Au.prompt}
4026
4026
 
4027
4027
  ${$u}`:Au.prompt}function modeDefaults(Au){return Object.fromEntries((Au.interface.modes??[]).filter(lo=>lo.options.length>0).map(lo=>[lo.id,lo.default||lo.options[0].id]))}function modeChoice(Au,lo={}){const $u=Au.interface.modes??[];for(const[Ru,Iu]of Object.entries(lo)){const Pu=$u.find(Ou=>Ou.id===Ru);if(!Pu)throw new Error(`${Au.name} has no mode “${Ru}”.`);if(!Pu.options.some(Ou=>Ou.id===Iu))throw new Error(`The mode ${Pu.label} has no option “${Iu}”.`)}return{...modeDefaults(Au),...lo}}function profileChoice(Au,lo){const $u=Au.interface.profiles??[];if(lo){const Ru=$u.find(Iu=>Iu.id===lo);if(!Ru)throw new Error($u.length===0?`${Au.name} has no profiles: “${lo}” cannot be chosen.`:`${Au.name} has no profile “${lo}”.`);return Ru}return $u[0]}function startersFor(Au,lo){const $u=profileChoice(Au,lo);return $u&&$u.starters.length>0?$u.starters:Au.interface.starters}function modeEffect(Au,lo={},$u){const Ru=modeChoice(Au,lo),Iu=profileChoice(Au,$u),Pu=(Au.interface.modes??[]).flatMap(Du=>Du.options.filter(Lu=>Lu.id===Ru[Du.id])),Ou=[Iu?.instructions??"",...Pu.map(Du=>Du.instructions??"")].map(Du=>Du.trim()).filter(Boolean).join(`
4028
4028
 
@@ -574,6 +574,18 @@ export type SessionActionContext = {
574
574
  say: (sentence: string) => void;
575
575
  /** The turn a *Clone from here* was pressed on, when it was; else the last. */
576
576
  atTurn?: number;
577
+ /**
578
+ * Show the person a panel of the session — its Rules (SH-54) — over the
579
+ * thread: a title and what is drawn in it. The thread's menu shows it in a
580
+ * dialog of its own when the host gives no other way.
581
+ */
582
+ show?: (panel: SessionPanel) => void;
583
+ };
584
+ /** A panel an entry shows over the thread (`SessionActionContext.show`). */
585
+ export type SessionPanel = {
586
+ title: string;
587
+ /** What the panel draws, rendered while it is open. */
588
+ render: () => import('react').ReactNode;
577
589
  };
578
590
  /** Where an entry is offered: the thread's `⋯` menu, each turn's row, or both. */
579
591
  export type SessionActionPlacement = 'thread' | 'turn' | 'both';
@@ -0,0 +1,17 @@
1
+ /**
2
+ * *Rules for this session…* on a thread's menu (SHIELD SH-54): the session
3
+ * section of the application's Rules card — what decides the session now,
4
+ * the rules the person added, the presets and a rule to add — shown over the
5
+ * thread, so an application whose layout is the conversation alone (`chat`,
6
+ * no rail) offers it too. The card itself (`SessionRules`), never a copy.
7
+ *
8
+ * @module apps/plugins/app-rules/sessionRulesAction
9
+ */
10
+ import type { SessionActionContribution } from '../../core';
11
+ export declare const SESSION_RULES_ACTION_WORDS: {
12
+ readonly label: "Rules for this session…";
13
+ readonly title: "Rules for this session";
14
+ readonly noPanel: "Showing the session’s rules needs a panel this page has not: use the Rules card of the application’s page.";
15
+ readonly signedOut: "Sign in to see and add the rules of this session.";
16
+ };
17
+ export declare const SESSION_RULES: SessionActionContribution;
@@ -0,0 +1,30 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { SessionRules } from './AppRulesCard.js';
3
+ export const SESSION_RULES_ACTION_WORDS = {
4
+ label: 'Rules for this session…',
5
+ title: 'Rules for this session',
6
+ noPanel: 'Showing the session’s rules needs a panel this page has not: use the Rules card of the application’s page.',
7
+ signedOut: 'Sign in to see and add the rules of this session.',
8
+ };
9
+ export const SESSION_RULES = {
10
+ id: 'session-rules',
11
+ label: SESSION_RULES_ACTION_WORDS.label,
12
+ order: 25,
13
+ // A rule is added to a running session, in force at once and gone with it.
14
+ when: session => session.state === 'open',
15
+ run: (session, context) => {
16
+ if (!context.show) {
17
+ context.say(SESSION_RULES_ACTION_WORDS.noPanel);
18
+ return;
19
+ }
20
+ const token = context.client.accessToken() ?? '';
21
+ if (!token) {
22
+ context.say(SESSION_RULES_ACTION_WORDS.signedOut);
23
+ return;
24
+ }
25
+ context.show({
26
+ title: SESSION_RULES_ACTION_WORDS.title,
27
+ render: () => (_jsx(SessionRules, { agentServerUrl: context.client.serverUrl, token: token, sessionUid: session.uid })),
28
+ });
29
+ },
30
+ };
@@ -2,6 +2,7 @@ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-run
2
2
  import { useCallback, useState } from 'react';
3
3
  import { ActionList, ActionMenu, Button, IconButton, Label, Text, } from '@primer/react';
4
4
  import { KebabHorizontalIcon } from '@primer/octicons-react';
5
+ import { Dialog } from '@primer/react/experimental';
5
6
  import { Box } from '@datalayer/primer-addons';
6
7
  import { useContributions } from '@datalayer/reactor/react';
7
8
  import { LoopSessionAction, sessionActionsFor, } from '../../core/index.js';
@@ -44,8 +45,12 @@ export function SessionActionsMenu({ uid, describe, context, }) {
44
45
  const [facts, setFacts] = useState(undefined);
45
46
  const [open, setOpen] = useState(false);
46
47
  const [said, setSaid] = useState('');
48
+ // A panel an entry shows (the session's Rules, SH-54), in a dialog of the
49
+ // menu's own when the host gives no other way.
50
+ const [panel, setPanel] = useState(undefined);
47
51
  const saying = {
48
52
  ...context,
53
+ show: context.show ?? setPanel,
49
54
  say: sentence => {
50
55
  setSaid(sentence);
51
56
  context.say(sentence);
@@ -61,13 +66,13 @@ export function SessionActionsMenu({ uid, describe, context, }) {
61
66
  return null;
62
67
  }
63
68
  const applicable = sessionActionsFor(entries, facts);
64
- return (_jsxs(ActionMenu, { open: open, onOpenChange: onOpenChange, children: [_jsx(ActionMenu.Anchor, { children: _jsx(IconButton, { icon: KebabHorizontalIcon, "aria-label": "Session actions", variant: "invisible", size: "small", "data-testid": "session-actions" }) }), _jsx(ActionMenu.Overlay, { width: "small", children: _jsxs(ActionList, { children: [applicable.length === 0 ? (_jsx(ActionList.Item, { disabled: true, children: facts
65
- ? 'Nothing applies to this session now.'
66
- : 'Reading the session…' })) : (applicable.map(entry => (_jsx(ActionList.Item, { "data-session-action": entry.id, onSelect: () => {
67
- if (!facts) {
68
- return;
69
- }
70
- Promise.resolve(entry.run(facts, saying)).catch(error => saying.say(String(error.message ?? error)));
71
- }, children: entry.label }, entry.id)))), said ? (_jsxs(_Fragment, { children: [_jsx(ActionList.Divider, {}), _jsx(ActionList.Item, { disabled: true, "data-testid": "session-actions-said", children: said })] })) : null] }) })] }));
69
+ return (_jsxs(_Fragment, { children: [_jsxs(ActionMenu, { open: open, onOpenChange: onOpenChange, children: [_jsx(ActionMenu.Anchor, { children: _jsx(IconButton, { icon: KebabHorizontalIcon, "aria-label": "Session actions", variant: "invisible", size: "small", "data-testid": "session-actions" }) }), _jsx(ActionMenu.Overlay, { width: "small", children: _jsxs(ActionList, { children: [applicable.length === 0 ? (_jsx(ActionList.Item, { disabled: true, children: facts
70
+ ? 'Nothing applies to this session now.'
71
+ : 'Reading the session…' })) : (applicable.map(entry => (_jsx(ActionList.Item, { "data-session-action": entry.id, onSelect: () => {
72
+ if (!facts) {
73
+ return;
74
+ }
75
+ Promise.resolve(entry.run(facts, saying)).catch(error => saying.say(String(error.message ?? error)));
76
+ }, children: entry.label }, entry.id)))), said ? (_jsxs(_Fragment, { children: [_jsx(ActionList.Divider, {}), _jsx(ActionList.Item, { disabled: true, "data-testid": "session-actions-said", children: said })] })) : null] }) })] }), panel ? (_jsx(Dialog, { title: panel.title, onClose: () => setPanel(undefined), width: "large", children: _jsx(Box, { "data-session-panel": "", children: panel.render() }) })) : null] }));
72
77
  }
73
78
  export default SessionActionsMenu;
@@ -4,6 +4,7 @@
4
4
  */
5
5
  import { listAgentspecs } from '../../../specs/agents/index.js';
6
6
  import { listHarnesses } from '../../../specs/harnesses.js';
7
+ import { SESSION_RULES } from '../app-rules/sessionRulesAction.js';
7
8
  /** The file a session is exported as. */
8
9
  export const sessionFileName = (session) => `${session.uid}.session.jsonl`;
9
10
  /** What the entries say, in a person's words. */
@@ -178,6 +179,9 @@ export const RESUME = {
178
179
  export const CHAT_SESSION_ACTIONS = [
179
180
  SWITCH_AGENT,
180
181
  CLONE_FROM_HERE,
182
+ // The session's Rules over the thread (SH-54): every chat offers them,
183
+ // a chat-layout application too.
184
+ SESSION_RULES,
181
185
  EXPORT,
182
186
  IMPORT,
183
187
  RESUME,
@@ -48,6 +48,10 @@ export type SessionStart = {
48
48
  * settings, resume (streamed), and stop, end, read (JSON).
49
49
  */
50
50
  export declare function appSessionsClient(options: RuntimeClientOptions): {
51
+ /** The runtime's agent-runtimes address this client speaks to. */
52
+ serverUrl: string;
53
+ /** The token it calls with now, or `undefined`. */
54
+ accessToken: () => string | undefined;
51
55
  /** Start a session with its first message. */
52
56
  start: (start: SessionStart, streaming: StreamOptions) => Promise<void>;
53
57
  /** The next turn, or the answer to what the application asked (text, a choice). */
@@ -66,6 +66,10 @@ const at = (uid) => `/api/v1/apps/sessions/${encodeURIComponent(uid)}`;
66
66
  export function appSessionsClient(options) {
67
67
  const { json, stream, fetcher, headers, refused, root } = clientOf(options);
68
68
  return {
69
+ /** The runtime's agent-runtimes address this client speaks to. */
70
+ serverUrl: root,
71
+ /** The token it calls with now, or `undefined`. */
72
+ accessToken: () => options.getAccessToken(),
69
73
  /** Start a session with its first message. */
70
74
  start: (start, streaming) => stream('/api/v1/apps/sessions', {
71
75
  agent: start.agent,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@datalayer/agent-runtimes",
3
- "version": "1.5.80",
3
+ "version": "1.5.81",
4
4
  "type": "module",
5
5
  "workspaces": [
6
6
  ".",
@@ -1,32 +0,0 @@
1
- import{a5 as _,fT as Ks,r as s,j as t,fU as Gs,fV as Ys,ch as Jn,B as h,H as xt,T as F,v as q,cN as qt,eN as nn,fW as se,cH as bt,y as qs,fX as Js,fY as Qs,em as Zs,fZ as Xs,a_ as eo,f_ as to,f$ as no,g0 as so,g1 as oo,g2 as ao,g3 as io,ee as ls,ec as ro,ef as sn,g4 as lo,g5 as co,g6 as uo,g7 as fo,g8 as cs,g9 as ds,ga as po,L as mo,gb as go,dq as Jt,I as us,bp as st,D as ho,gc as Qn,gd as xo,ge as bo,dm as vo,bh as So,gf as yo,gg as Co,gh as wo,gi as jo,gj as ko,gk as To,a0 as Qt,gl as Ro,gm as Io,gn as Eo,go as Ao,gp as Po,gq as $o,gr as Uo,gs as Mo,gt as Oo,gu as Lo,gv as Fo,gw as zo,gx as _o,gy as No,gz as Bo,gA as Vo,gB as Ho,gC as Do,gD as Wo,gE as Ko,gF as ot,gG as Go,gH as Yo,gI as qo,gJ as Jo,gK as Zn,gL as Qo,gM as Ne,gN as Zo,gO as Xo,bi as vt,gP as ea,gQ as ta,gR as Xn,gS as na,gT as sa,gU as oa,gV as aa,eV as ia,gW as Zt,gX as Ae,gY as ra,gZ as la,g_ as ca,g$ as es,h0 as da,h1 as ts,h2 as ua,h3 as fa,h4 as pa,h5 as ma,h6 as ga,h7 as ha,h8 as xa,h9 as ba,ha as va,hb as Sa,hc as St,hd as ya,he as Ca,hf as wa,hg as ja,hh as ka,hi as ns,hj as Ta,hk as Ra,hl as Ia,hm as on,hn as Ea,ho as Aa,eD as Xt,hp as Pa,hq as $a}from"../datalayer-app-main.js";import{S as Ua,E as Ma,a as Oa}from"./SignInIcon-B9ZNyM4_.js";import{F as La,a as Fa,b as za}from"./LinkedInGreyIcon-BoWXE-HS.js";import{K as _a}from"./KebabHorizontalIcon-DD3W5tPT.js";function fs(){const n=_(Ks);return s.useMemo(()=>n.map(o=>o.value),[n])}const en={github:{name:"github",oauth2CallbackServerRoute:"jupyter_iam/oauth2/callback",oauth2CallbackUIRoute:"/iam/oauth2/github/callback"},google:{name:"google",oauth2CallbackServerRoute:"jupyter_iam/oauth2/callback",oauth2CallbackUIRoute:"/iam/oauth2/google/callback"},linkedin:{name:"linkedin",oauth2CallbackServerRoute:"jupyter_iam/oauth2/callback",oauth2CallbackUIRoute:"/iam/oauth2/linkedin/callback"}},ss=()=>{if(typeof document>"u")return"";const n=document.getElementById("datalayer-config-data");if(!n?.textContent)return"";try{const o=JSON.parse(n.textContent);return String(o?.iamUrl||"").replace(/\/$/,"")}catch{return""}},Na=(n,o="Unable to start social sign-in.")=>{if(n instanceof Error&&n.message)return n.message;if(typeof n=="string"&&n.trim())return n;if(n&&typeof n=="object"&&"message"in n){const l=n.message;if(typeof l=="string"&&l.trim())return l}return o},Ba=Xs`
2
- .signin-input-theme-scope input:-webkit-autofill,
3
- .signin-input-theme-scope input:-webkit-autofill:hover,
4
- .signin-input-theme-scope input:-webkit-autofill:focus,
5
- .signin-input-theme-scope input:-webkit-autofill:active,
6
- .signin-input-theme-scope input:-webkit-autofill:disabled,
7
- .signin-input-theme-scope textarea:-webkit-autofill,
8
- .signin-input-theme-scope textarea:-webkit-autofill:hover,
9
- .signin-input-theme-scope textarea:-webkit-autofill:focus,
10
- .signin-input-theme-scope textarea:-webkit-autofill:active,
11
- .signin-input-theme-scope textarea:-webkit-autofill:disabled {
12
- -webkit-text-fill-color: var(--fgColor-default) !important;
13
- caret-color: var(--fgColor-default) !important;
14
- -webkit-box-shadow: 0 0 0 1000px var(--bgColor-default) inset !important;
15
- box-shadow: 0 0 0 1000px var(--bgColor-default) inset !important;
16
- background-color: var(--bgColor-default) !important;
17
- transition: background-color 9999s ease-in-out 0s !important;
18
- }
19
-
20
- .signin-input-theme-scope input:disabled,
21
- .signin-input-theme-scope textarea:disabled {
22
- -webkit-text-fill-color: var(--fgColor-muted) !important;
23
- -webkit-box-shadow: 0 0 0 1000px var(--bgColor-default) inset !important;
24
- box-shadow: 0 0 0 1000px var(--bgColor-default) inset !important;
25
- background-color: var(--bgColor-default) !important;
26
- opacity: 1 !important;
27
- }
28
- `,Va=({onSignIn:n,onApiKeySignIn:o,loginUrl:l,name:i,title:d="Datalayer OTEL",description:p="Sign in to access the observability dashboard.",icon:v,leadingIcon:c=t.jsx(Zs,{size:24}),github:f=!1,google:x=!1,linkedin:C=!1,apiKey:u=!1,signUp:ue=!0,socialSignInNavigationTarget:w,asDoc:y=!1,fillHeight:N=!0,hideHero:J=!1,calloutTitle:xe,calloutDescription:A,passwordToggleLabel:yt="Sign in with a password",signUpTitle:Ct="Don't have an account?",signUpDescription:an="Create a free Datalayer account with your email address.",signUpLabel:be="Sign up with email",signUpHref:wt="https://datalayer.ai/signup",onSignUp:Q,forgotPasswordHref:fe="/password",forgotPasswordLabel:at="Forgot password?",showForgotPassword:oe=!0,socialButtonMarginTop:Pe=3,actionButtonMaxWidth:te=320})=>{const ve=y&&!J,j=i??(y&&d==="Datalayer OTEL"?"Datalayer Sign In":d),it=v??(y?t.jsx(Ua,{size:24}):c),Se=s.useMemo(()=>{if(l)return l;const m=ss();return m?`${m}/api/iam/v1/login`:"/api/iam/v1/login"},[l]),[Z,jt]=s.useState(""),[O,kt]=s.useState(""),[ye,Tt]=s.useState(!1),[$e,Rt]=s.useState(!1),[P,Ue]=s.useState(!1),[X,Be]=s.useState(!1),[Me,Ve]=s.useState(null),[W,It]=s.useState(null),[ae,Et]=s.useState(""),[He,At]=s.useState(null),[Ce,ee]=s.useState(null),{enqueueToast:we}=Gs(),[je,ke]=s.useState(!1),[pe,De]=s.useState(""),me=s.useRef(null),We=s.useCallback(m=>Ys()?Jn.URLExt.join(Jn.PageConfig.getBaseUrl(),m.oauth2CallbackServerRoute):`${window.location.protocol}//${window.location.hostname}${window.location.port?`:${window.location.port}`:""}${m.oauth2CallbackUIRoute}`,[]),ie=s.useMemo(()=>{if(typeof window>"u")return"/";const m=`${window.location.pathname}${window.location.search}${window.location.hash}`;return m.startsWith("/")?m:"/"},[]),I=s.useCallback(async m=>{if(!X){ee(null),Ve(m.name),Be(!0);try{const $=ss(),B=new URLSearchParams({provider:m.name,callback_uri:We(m)}),V=w===void 0?void 0:String(w||"").trim(),Ge=V===void 0?ie&&ie!=="/"?ie:void 0:V&&V.startsWith("/")&&!V.startsWith("//")?V:void 0;Ge&&B.set("post_auth_redirect",Ge);const E=`${$||""}/api/iam/v1/oauth2/authz/url?${B.toString()}`,U=await fetch(E),k=await U.json(),ce=k?.autorization_url;if(!U.ok||!ce)throw new Error(k?.message||"Unable to start social sign-in.");window.location.assign(ce)}catch($){const B=Na($);ee(B),we(B,{variant:"error"}),Ve(null),Be(!1)}}},[We,ie,we,X,w]);s.useEffect(()=>{je&&me.current?.focus()},[je]);const re=s.useCallback(()=>{ke(!1),De("")},[]),Te=s.useCallback(()=>{!pe.trim()||!o||(o(pe.trim()),re())},[pe,o,re]),le=s.useCallback(()=>{if(Q){Q();return}window.location.assign(wt)},[Q,wt]),rt=s.useCallback(()=>{if(fe){if(fe.startsWith("http://")||fe.startsWith("https://")){window.open(fe,"_blank","noopener,noreferrer");return}window.location.assign(fe)}},[fe]),Oe=s.useCallback(async()=>{if(!(y||!Z||!O||P)){Ue(!0),ee(null);try{const m=await fetch(Se,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({handle:Z,password:O})});if(!m.ok)throw new Error(`HTTP ${m.status}`);const $=await m.json();if($.success&&$.token){const B=String($?.user?.id||$?.user?.uid||"").trim();if(!!$?.user?.mfaUrl&&B){It(B),At($.token),ee(null);return}n&&n($.token,Z)}else ee($.message||"Invalid username or password.")}catch(m){ee(m instanceof Error?m.message:String(m))}finally{Ue(!1)}}},[y,Z,O,P,Se,n]),Le=s.useCallback(async()=>{if(!(y||P||!W||!ae.trim()||!He)){Ue(!0),ee(null);try{const m=new URL(Se,window.location.origin),$=m.pathname.endsWith("/api/iam/v1/login")?m.href.replace(/\/api\/iam\/v1\/login$/,""):`${m.origin}`,B=await fetch(`${$}/api/iam/v1/users/${W}/mfa/validate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({userUid:W,code:ae.trim()})}),V=await B.json();if(!B.ok||!V?.success)throw new Error(V?.message||"Failed to validate your MFA code.");n&&n(He,Z)}catch(m){const $=m instanceof Error?m.message:String(m);ee($),we($,{variant:"error"})}finally{Ue(!1)}}},[y,we,Z,P,Se,ae,He,W,n]),K=s.useCallback(m=>{m.key==="Enter"&&(W?Le():Oe())},[W,Oe,Le]),Ke=X||P||y;return t.jsxs(h,{className:"signin-input-theme-scope",display:"flex",alignItems:J||ve||!N?"flex-start":"center",justifyContent:"center",minHeight:J||ve||!N?"auto":"100vh",bg:J?"transparent":"canvas.default",color:"fg.default",py:J?0:ve?2:4,children:[t.jsx(Ba,{}),t.jsxs(h,{width:"100%",maxWidth:440,p:0,children:[!J&&t.jsxs(t.Fragment,{children:[t.jsxs(h,{display:"flex",alignItems:"center",gap:2,mb:ve?2:3,justifyContent:"center",children:[it,t.jsx(xt,{sx:{fontSize:3},children:j})]}),t.jsx(F,{as:"p",sx:{fontSize:1,color:"fg.muted",mb:ve?2:3,textAlign:"center"},children:p})]}),(xe||A)&&t.jsxs(h,{mb:3,textAlign:"center",children:[xe&&t.jsx(xt,{as:"h3",sx:{fontSize:2,mb:1},children:xe}),A&&t.jsx(F,{sx:{color:"fg.muted",fontSize:1},children:A})]}),!W&&(f||x||C)&&t.jsxs(t.Fragment,{children:[f&&t.jsx(q,{block:!0,size:"large",leadingVisual:Me==="github"?()=>t.jsx(qt,{size:"small"}):La,disabled:Ke,onClick:()=>I(en.github),sx:{mt:Pe,maxWidth:te,mx:"auto"},children:"Sign in with GitHub"}),x&&t.jsx(q,{block:!0,size:"large",leadingVisual:Me==="google"?()=>t.jsx(qt,{size:"small"}):Fa,disabled:Ke,onClick:()=>I(en.google),sx:{mt:Pe,maxWidth:te,mx:"auto"},children:"Sign in with Google"}),C&&t.jsx(q,{block:!0,size:"large",leadingVisual:Me==="linkedin"?()=>t.jsx(qt,{size:"small"}):za,disabled:Ke,onClick:()=>I(en.linkedin),sx:{mt:Pe,maxWidth:te,mx:"auto"},children:"Sign in with LinkedIn"})]}),!W&&!ye&&t.jsx(h,{mt:3,display:"flex",justifyContent:"center",children:t.jsx(q,{leadingVisual:nn,size:"large",block:!0,disabled:y||P||X,onClick:()=>Tt(!0),sx:{maxWidth:te,mx:"auto"},children:yt})}),!W&&ye&&t.jsxs(h,{mt:4,children:[t.jsxs(se,{required:!0,sx:{mb:3},children:[t.jsx(se.Label,{children:"Username"}),t.jsx(bt,{autoFocus:!0,block:!0,placeholder:"Your username",value:Z,disabled:P||y,onChange:m=>jt(m.target.value),onKeyDown:K})]}),t.jsxs(se,{required:!0,sx:{mb:3},children:[t.jsx(se.Label,{children:"Password"}),t.jsx(bt,{block:!0,placeholder:"Your password",type:$e?"text":"password",value:O,disabled:P||y,onChange:m=>kt(m.target.value),onKeyDown:K,trailingAction:t.jsx(bt.Action,{onClick:()=>Rt(!$e),disabled:P||y,icon:$e?Ma:Oa,"aria-label":$e?"Hide password":"Show password",sx:{color:"var(--fgColor-muted)"}})})]}),t.jsxs(h,{display:"flex",alignItems:"center",justifyContent:"space-between",mt:3,children:[t.jsx(q,{variant:"primary",disabled:P||y||!Z||!O,onClick:Oe,children:P?"Signing in…":"Sign In"}),oe&&t.jsx(qs,{as:"button",sx:{fontSize:1,cursor:y?"not-allowed":"pointer",background:"none",border:"none",opacity:y?.6:1},onClick:()=>{y||P||rt()},children:at})]})]}),W&&t.jsxs(t.Fragment,{children:[t.jsxs(se,{required:!0,sx:{mb:3,mt:2},children:[t.jsx(se.Label,{children:"MFA Code"}),t.jsx(bt,{autoFocus:!0,block:!0,placeholder:"Your MFA code",value:ae,disabled:P||y,onChange:m=>Et(m.target.value),onKeyDown:K})]}),t.jsx(q,{variant:"primary",block:!0,disabled:P||y||!ae.trim(),onClick:Le,sx:{maxWidth:te,mx:"auto"},children:P?"Validating…":"Validate MFA Code"})]}),Ce&&t.jsx(F,{sx:{color:"danger.fg",fontSize:1,mt:3,display:"block"},children:Ce}),ue&&t.jsxs(h,{mt:4,pt:4,textAlign:"center",borderTop:"1px solid",borderColor:"border.muted",children:[t.jsx(xt,{as:"h3",sx:{fontSize:2,mb:2},children:Ct}),t.jsx(F,{as:"p",sx:{color:"fg.muted",fontSize:1,mb:3},children:an}),t.jsx(h,{display:"flex",justifyContent:"center",children:t.jsx(q,{variant:"primary",size:"large",leadingVisual:Js,disabled:y||P,onClick:le,children:be})})]}),u&&o&&t.jsxs(t.Fragment,{children:[t.jsxs(h,{display:"flex",alignItems:"center",gap:2,my:3,children:[t.jsx(h,{flex:1,height:"1px",bg:"border.default"}),t.jsx(F,{sx:{fontSize:0,color:"fg.muted"},children:"or"}),t.jsx(h,{flex:1,height:"1px",bg:"border.default"})]}),t.jsx(q,{block:!0,leadingVisual:nn,disabled:y||P||X,onClick:()=>ke(!0),sx:{maxWidth:te,mx:"auto"},children:"Sign in with an API Key"}),je&&t.jsx(h,{role:"dialog","aria-modal":"true","aria-labelledby":"signin-api-key-title",onKeyDown:m=>{m.key==="Escape"&&re()},onClick:re,position:"fixed",inset:0,zIndex:200,p:3,bg:"canvas.backdrop",display:"flex",alignItems:"center",justifyContent:"center",children:t.jsxs(h,{as:"form",onClick:m=>m.stopPropagation(),onSubmit:m=>{m.preventDefault(),Te()},width:"min(560px, 100%)",p:3,borderRadius:2,border:"1px solid",borderColor:"border.default",bg:"canvas.overlay",color:"fg.default",boxShadow:"shadow.large",children:[t.jsx(xt,{id:"signin-api-key-title",sx:{fontSize:2,mb:2},children:"Enter your API Key"}),t.jsxs(se,{required:!0,children:[t.jsx(se.Label,{children:"API Key"}),t.jsx(Qs,{block:!0,required:!0,autoFocus:!0,placeholder:"Paste your API key here",value:pe,onInput:m=>De(m.currentTarget.value),ref:me})]}),t.jsxs(h,{mt:3,display:"flex",justifyContent:"flex-end",gap:2,children:[t.jsx(q,{type:"button",onClick:re,children:"Cancel"}),t.jsx(q,{type:"submit",variant:"primary",disabled:!pe.trim(),children:"Authenticate"})]})]})})]})]})]})};function Ha(n){const{agentId:o,instructions:l,model:i,frontendTools:d,inference:p,subagents:v,sharing:c,onSubagentEvent:f,modeEffect:x}=n;return{type:"browser-vercel-ai",endpoint:"",agentId:o,enableConfigQuery:!1,options:{instructions:l,model:i,frontendTools:d,inference:p,subagents:v,sharing:c,onSubagentEvent:f,modeEffect:x}}}const os=eo((n,o)=>({pending:void 0,suggest:(l,i)=>{const d=l.trim();d&&n({pending:{text:d,submit:i?.submit??!1,nonce:(o().pending?.nonce??0)+1}})},consume:()=>n({pending:void 0})})),Da=({state:n})=>to[n];class Wa extends Error{constructor(o,l){super(l),this.status=o,this.name="RuntimeRefusal"}status}function Ka({baseUrl:n,getAccessToken:o,fetch:l}){const i=n.replace(/\/+$/,""),d=(f={})=>{const x=o();return{...f,...x?{Authorization:`Bearer ${x}`}:{}}},p=async f=>{throw new Wa(f.status,oo(f.status,f.statusText,await ao(f)))};return{json:async(f,x="GET",C)=>{const u=await l(`${i}${f}`,{method:x,headers:d({Accept:"application/json",...C===void 0?{}:{"Content-Type":"application/json"}}),...C===void 0?{}:{body:JSON.stringify(C)}});return u.ok?await u.json():p(u)},stream:async(f,x,{onEvent:C,signal:u},ue="POST")=>{const w=await l(`${i}${f}`,{method:ue,headers:d({"Content-Type":"application/json",Accept:"text/event-stream"}),body:JSON.stringify(x),signal:u});if(!w.ok)return p(w);await io(w,C)},refused:p,headers:d,root:i,fetcher:l}}const D=n=>`/api/v1/apps/sessions/${encodeURIComponent(n)}`;function Ga(n){const{json:o,stream:l,fetcher:i,headers:d,refused:p,root:v}=Ka(n);return{start:(c,f)=>l("/api/v1/apps/sessions",{agent:c.agent,...c.deploymentUid?{deployment_uid:c.deploymentUid}:{},...c.appUid?{app_uid:c.appUid}:{},...c.version?{version:c.version}:{},...c.session?{session:c.session}:{},opener:c.opener},f),message:(c,f,x)=>l(`${D(c)}/messages`,{text:f},x),changeSettings:(c,f,x)=>l(`${D(c)}/settings`,{values:f},x,"PUT"),resume:(c,f,x)=>l(`${D(c)}/resume`,{agent:f},x),stop:c=>o(`${D(c)}/stop`,"POST"),end:c=>o(`${D(c)}/end`,"POST"),describe:c=>o(D(c)),described:async c=>so(await o(D(c))),list:(c={})=>{const f=new URLSearchParams;for(const[C,u]of Object.entries(c))u!==""&&u!==void 0&&u!==!1&&f.set(C,String(u));const x=f.toString();return o(`/api/v1/apps/sessions${x?`?${x}`:""}`)},swap:(c,f)=>o(`${D(c)}/agent`,"POST",{agent:f}),clone:(c,f={})=>o(`${D(c)}/clone`,"POST",{up_to_turn:f.upToTurn??null,agent:f.agent??null,title:f.title??""}),exportFile:async(c,f="")=>{const x=await i(`${v}${D(c)}/export${f?`?format=${encodeURIComponent(f)}`:""}`,{method:"GET",headers:d()});return x.ok?x.text():p(x)},importFile:async(c,f={})=>{const x=new URLSearchParams;f.agent&&x.set("agent",f.agent),f.format&&x.set("format",f.format);const C=x.toString(),u=await i(`${v}/api/v1/apps/sessions/import${C?`?${C}`:""}`,{method:"POST",headers:d({"Content-Type":"application/x-ndjson"}),body:c});return u.ok?await u.json():p(u)},rename:(c,f)=>o(`${D(c)}/title`,"PUT",{title:f}),archive:(c,f)=>o(`${D(c)}/archived`,"PUT",{archived:f}),messages:async c=>no((await o(`${D(c)}/messages`)).messages)}}function Ya({agentName:n,sandboxStillRuns:o=!1,temporary:l=!0,onSignedIn:i,onSignUp:d}){const{configuration:p}=ls(),v=s.useCallback(c=>{ro.getState().checkIAMToken(c),i?.()},[i]);return t.jsx(h,{height:"100%",minHeight:0,overflowY:"auto",bg:"canvas.default",px:4,py:4,children:t.jsxs(h,{maxWidth:440,mx:"auto",children:[t.jsxs(h,{display:"flex",alignItems:"center",justifyContent:"center",gap:2,color:"attention.fg",mb:2,children:[t.jsx(nn,{size:20}),t.jsx(F,{sx:{fontSize:2,fontWeight:"semibold",color:"fg.default"},children:l?"This demo runs on a shared key":"Your key has expired"})]}),t.jsxs(F,{as:"p",sx:{fontSize:1,color:"fg.muted",textAlign:"center",mb:3},children:[l?`${n??"The agent"} has used the time this key allows. Sign in to point your own agent at it, use your own data, and drop the time limit.`:`${n??"The agent"} stopped because your session ran out.`,o?" Your notebook is still running in this page.":""]}),t.jsx(Va,{hideHero:!0,fillHeight:!1,calloutTitle:"Sign in to keep going",github:!0,google:!0,linkedin:!0,socialSignInNavigationTarget:typeof window>"u"?void 0:`${window.location.pathname}${window.location.search}`,loginUrl:p?.iamUrl?`${p.iamUrl}/api/iam/v1/login`:void 0,onSignIn:v,onSignUp:d})]})})}const qa="https://r1.datalayer.run";function Ja(n=!0){const{configuration:o}=ls(),l=sn(c=>c.token),i=o?.aiInferenceUrl||qa,d=lo(i,n&&!l),p=l||d.token,v=s.useMemo(()=>({inferenceUrl:i,token:p||void 0}),[i,p]);return{inference:v,needsSignIn:co(v),anonymous:d,inferenceUrl:i}}const Qa={name:"general-purpose",description:"A capable generalist for a task none of the specialists covers: research, reasoning, drafting, checking.",instructions:"You are a capable general-purpose assistant. Carry out the task you are given completely and report the result plainly, saying what you could not do."};function as(n){const o=n?.subagents;if(!o)return[];const l=(o.subagents??[]).map(i=>{const d=i.ref?uo(i.ref):void 0;return{name:i.name,description:i.description||d?.description||i.name,instructions:i.instructions??d?.systemPrompt,model:i.model??d?.model??o.defaultModel,icon:d?.icon}});return o.includeGeneralPurpose?[...l,Qa]:l}function Za(n){return n.replace(/^datalayer_/,"").replace(/_lexical$/,"")}function Xa(n){const o=Za(n);return/^executeCodeIn(Notebook|Document)$/.test(o)||/^(read|list)[A-Z]/.test(o)}function ei(n,o){return n.filter(l=>o?.has(l.name)||Xa(l.name))}function ti(n,o){const l=i=>o&&i.value.id===`${o}-tools`?0:i.value.id==="notebook-tools"?1:2;return n.map((i,d)=>({entry:i,index:d,rank:l(i)})).sort((i,d)=>i.rank-d.rank||i.index-d.index).map(i=>i.entry)}function ni(n,o,l){if(!l||!n.endsWith("-tools"))return!1;const i=n.slice(0,-6);return o.has(i)&&i!==l}const si={type:"object",properties:{}};function oi(n,o){const l=new Set(n.toolset);return n.commands.filter(i=>l.has(i.name)).map(i=>({name:i.name,description:i.description,parameters:i.parameters??si,location:"frontend",handler:async d=>{if(!o)throw new Error(`${i.name}: the ${n.plugin??n.id} plugin is not mounted on this page.`);const p=Object.keys(d??{}).length>0?d:void 0,v=await o.executeCommand(i.command,p);return v===void 0?{ok:!0,command:i.command,argument:p}:v}}))}function ps(n,o){return n.flatMap(l=>oi(l,o))}function ai(){const n=fo(),o=fs();return s.useMemo(()=>ps(o,n),[o,n])}function ii(n){const o=n?.app_instance;if(!o||typeof o!="object")return"";const l=o.deployment_uid;return typeof l=="string"?l.trim():""}function ri(n,o,l){return n||!o?n:{id:l,messages:[]}}function li(n){const o=(new URLSearchParams(n).get("session")??"").trim();if(!o)return"";if(!/^[A-Za-z0-9_-]{8,128}$/.test(o))throw new Error(`?session=${o} names no session: a session uid is 8 to 128 letters, digits, hyphens or underscores.`);return o}function ci({facts:n}){if(!n)return null;const o=po(n);return t.jsxs(h,{display:"inline-flex",alignItems:"center",gap:2,"data-session-state":n.state,children:[t.jsx(mo,{size:"small",variant:n.state==="open"?"accent":n.state==="paused"?"attention":"secondary",children:go(n)}),o?t.jsx(F,{sx:{fontSize:0,color:"fg.muted"},"data-session-lineage":"",children:o}):null]})}function di({facts:n,turn:o,context:l}){const i=_(cs),d=ds(i,n,"turn");return!n||d.length===0||o<1?null:t.jsx(h,{display:"inline-flex",gap:1,"data-turn-actions":o,children:d.map(p=>t.jsx(q,{size:"small",variant:"invisible","data-turn-action":p.id,onClick:()=>{Promise.resolve(p.run(n,{...l,atTurn:o})).catch(v=>l.say(String(v.message??v)))},children:p.label},p.id))})}function ui({uid:n,describe:o,context:l}){const i=_(cs),[d,p]=s.useState(void 0),[v,c]=s.useState(!1),[f,x]=s.useState(""),C={...l,say:w=>{x(w),l.say(w)}},u=s.useCallback(w=>{c(w),w&&n&&o(n).then(p,()=>p(void 0))},[o,n]);if(!n||i.length===0)return null;const ue=ds(i,d);return t.jsxs(Jt,{open:v,onOpenChange:u,children:[t.jsx(Jt.Anchor,{children:t.jsx(us,{icon:_a,"aria-label":"Session actions",variant:"invisible",size:"small","data-testid":"session-actions"})}),t.jsx(Jt.Overlay,{width:"small",children:t.jsxs(st,{children:[ue.length===0?t.jsx(st.Item,{disabled:!0,children:d?"Nothing applies to this session now.":"Reading the session…"}):ue.map(w=>t.jsx(st.Item,{"data-session-action":w.id,onSelect:()=>{d&&Promise.resolve(w.run(d,C)).catch(y=>C.say(String(y.message??y)))},children:w.label},w.id)),f?t.jsxs(t.Fragment,{children:[t.jsx(st.Divider,{}),t.jsx(st.Item,{disabled:!0,"data-testid":"session-actions-said",children:f})]}):null]})})]})}const is={confirm:"Switch",cancel:"Keep it"};function fi({question:n,onPick:o}){const[l,i]=s.useState(n.options[0]?.id??""),[d,p]=s.useState("");s.useEffect(()=>{let c=!0;if(!n.says||!l){p("");return}return n.says(l).then(f=>c&&p(f),()=>c&&p("")),()=>{c=!1}},[l,n]);const v=n.options.find(c=>c.id===l);return t.jsx(ho,{title:n.title,onClose:()=>o(void 0),width:"medium",footerButtons:[{buttonType:"default",content:is.cancel,onClick:()=>o(void 0)},{buttonType:"primary",content:is.confirm,disabled:!l,onClick:()=>o(l||void 0)}],children:t.jsxs(h,{display:"grid",gap:3,"data-session-choose":"",children:[t.jsxs(se,{children:[t.jsx(se.Label,{children:n.title}),t.jsx(Qn,{value:l,onChange:c=>i(c.target.value),block:!0,children:n.options.map(c=>t.jsx(Qn.Option,{value:c.id,children:c.label},c.id))})]}),v?.description?t.jsx(F,{sx:{fontSize:1,color:"fg.muted"},children:v.description}):null,d?t.jsx(F,{as:"p",sx:{m:0,fontSize:1,fontStyle:"italic"},"data-session-choose-says":"",children:d}):null]})})}const pi="var(--theme-accent)";function ms({face:n,size:o}){return typeof n=="string"?t.jsx(xo,{emoji:n,size:o,label:""}):t.jsx(t.Fragment,{children:n})}function mi({face:n,size:o,state:l}){const i=l==="thinking"||l==="working",d=l==="paused";return t.jsxs(h,{as:"span","aria-hidden":!0,"data-presence":l,position:"relative",display:"inline-flex",alignItems:"center",justifyContent:"center",width:o+8,height:o+8,flexShrink:0,fontSize:o,lineHeight:1,children:[t.jsx(h,{as:"span",position:"absolute",inset:0,borderRadius:"50%",boxShadow:d?"none":`0 0 0 2px ${pi}`,border:d?"2px dashed":"none",borderColor:"border.default",opacity:i||l==="waiting"||d?.9:0,transition:"opacity var(--theme-motion-status, 0ms) var(--theme-motion-easing, ease)",animation:i?"loopPresenceBreath 1.8s ease-in-out infinite":"none",reducedMotion:{animation:"none"},sx:{"@keyframes loopPresenceBreath":{"0%, 100%":{transform:"scale(0.92)",opacity:.35},"50%":{transform:"scale(1.06)",opacity:.9}}}}),t.jsx(h,{as:"span",display:"inline-flex",opacity:d?.55:1,filter:d?"grayscale(0.6)":"none",transition:"opacity var(--theme-motion-status, 0ms) var(--theme-motion-easing, ease)",children:t.jsx(ms,{face:n,size:o})})]})}function gi({state:n}){return t.jsx(F,{role:"status","aria-live":"polite","data-presence-line":n,sx:{fontSize:0,color:n==="waiting"?"fg.default":"fg.muted",fontWeight:n==="waiting"?"semibold":"normal",whiteSpace:"nowrap",flexShrink:0},children:Da({state:n})})}const hi=on(void 0),xi=on(""),bi=on({}),de="",vi=1400,rs=parseInt(Pa["--loop-face-large"],10);function ki({workspace:n}){const o=bo(),l=vo(),i=s.useRef(null),d=s.useRef(void 0),{setViewControls:p}=n,v=s.useRef(n.setThread);v.current=n.setThread;const c=s.useCallback(()=>{const e=i.current?.thread();return e&&v.current?.(e),e},[]),[f,x]=s.useState(null),C=So(),u=C.getConfig(yo),ue=u?.placeholder||o.placeholder,w=u?.defaultSurface??"notebook",y=C.getConfig(Co),[N,J]=s.useState(de),xe=s.useRef(!1),A=_(wo),yt=_(jo),Ct=_(ko),be=_(To)[0]?.value,Q=Qt(be?.promptStance??hi)??be?.prompt,fe=_(Ro),at=Io(fe[0]?.value),oe=s.useRef(at);oe.current=at;const Pe=s.useRef(""),te=_(Eo),ve=s.useMemo(()=>Ao(()=>te.reduce((e,a)=>({...e,...a.value.extras.value}),{})),[te]),j=Qt(te.length>0?ve:bi),it=s.useRef(new Set),Se=Po(Ea,n),Z=!Se.allowed,jt=Z?Se.reason??"Chat is unavailable for this sandbox":void 0,[O,kt]=s.useState(!1),[ye,Tt]=s.useState(!1),[$e,Rt]=s.useState(!1),[P,Ue]=s.useState({open:!1,pendingApproval:!1}),X=$o(O,P,u?.presence?.paused===!0),Be=u?.presence?.onPresence;s.useEffect(()=>{Be?.(X),oe.current?.setPresence(X)},[Be,X]);const Me=s.useRef(u?.presence?.onSaying);Me.current=u?.presence?.onSaying;const Ve=s.useRef({answering:!1}),W=s.useCallback(e=>{i.current=e,Tt(!!e)},[]),It=s.useCallback(e=>{const{open:a,pendingApproval:r}=Uo(e);Ue(Ee=>Ee.open===a&&Ee.pendingApproval===r?Ee:{open:a,pendingApproval:r});const b={saying:Oo(e),answering:Mo(e)},g=Ve.current;(g.saying?.id!==b.saying?.id||g.saying?.text!==b.saying?.text||g.answering!==b.answering)&&(Ve.current=b,Me.current?.(b));const Y=oe.current;if(!Y)return;Y.items(e);const L=new Set(["complete","completed","done","error","failed","cancelled","canceled","rejected","denied","stopped"]),ne={insertcell:"adding a cell",updatecell:"editing a cell",runcell:"running a cell",deletecells:"removing cells",readallcells:"reading the notebook",readcell:"reading a cell",executecode:"running code",insertblock:"adding a block",updateblock:"editing a block",runblock:"running a block",readdocument:"reading the document"};let S;for(let Ee=e.length-1;Ee>=0;Ee-=1){const ht=e[Ee];if(typeof ht.toolName=="string"&&ht.toolCallId){L.has(String(ht.status).toLowerCase())||(S=ht);break}}if(!S){Y.activity(void 0);return}const Ie=S.toolName.toLowerCase().replace(/^datalayer_/,"").replace(/_lexical$/,"").replace(/[^a-z]/g,""),Ws=ne[Ie]??`using ${S.toolName}`;Y.activity(`${Pe.current||"The agent"} is ${Ws}…`)},[]),ae=s.useRef(j);ae.current=j;const Et=s.useCallback(e=>{Ts(e),oe.current?.usage(e),ae.current.onUsage?.(e)},[]),He=s.useCallback(e=>{kt(e),e||oe.current?.end("done")},[]),At=s.useCallback(e=>{const a=oe.current;if(!a)return;let r=-1;for(let g=e.length-1;g>=0;g-=1)if(e[g].role==="user"){r=g;break}const b=e.slice(r+1).filter(g=>g.role==="assistant").map(Lo).filter(g=>g.trim().length>0).join(`
29
-
30
- `);a.assistant(b)},[]),Ce=s.useRef([]),ee=s.useRef(!1),we=s.useRef(void 0),je=s.useRef(void 0),ke=s.useRef(void 0),pe=_(Fo),De=s.useRef(pe);De.current=pe;const me=s.useCallback((e,a)=>{if(je.current)return je.current;const r=ke.current;ke.current=void 0;const b=zo(De.current.map(L=>L.value),r?{...a??{},voice:r}:a),g=b?.loop;if(ee.current&&g?.files&&g.files.length>0){const L=we.current;if(!L)return"A file is given to an application running on a runtime: run it on Datalayer or on your machine to give it one.";let ne;try{ne=g.files.map(S=>({file:No(String(S.name??"")),base64:_o(String(S.data_url??""))}))}catch(S){return S instanceof Error?S.message:String(S)}L.execute(Bo(ne)).then(S=>{if(!S.success){x(`The files could not be put in the sandbox: ${S.error??"it failed"}.`);return}me(`${e}
31
-
32
- ${Vo(ne.map(Ie=>Ie.file))}`,{...b,loop:Object.fromEntries(Object.entries(g).filter(([Ie])=>Ie!=="files"))})});return}oe.current?.begin(e,c());const Y=i.current?.send;if(!Y){Ce.current.push([e,b]);return}Y(e,b)},[c]);s.useEffect(()=>{p(ye?{busy:O,stop:i.current?.stop,newChat:i.current?.newChat,send:me}:null)},[O,ye,p,me]),s.useEffect(()=>()=>p(null),[p]),s.useEffect(()=>n.prompts.subscribe(me),[n.prompts,me]),s.useEffect(()=>{if(!ye||Ce.current.length===0)return;const e=Ce.current.splice(0,Ce.current.length);for(const[a,r]of e)c(),i.current?.send(a,r)},[ye,c]);const We=s.useRef(!1),ie=s.useCallback(async e=>{x(null);const a=await Ho(ae.current,e);if(a){a.sent?Xe(""):x(a.refused);return}We.current||(We.current=!0,y?.firstPromptHook?.());const r=await n.submit(e);if(!r.handled){x(r.reason??null);return}Xe(""),r.result?.content&&x(r.result.content)},[n,y?.firstPromptHook]),I=s.useMemo(()=>A.find(e=>e.value.surfaceId===N)?.value,[A,N]),re=s.useCallback(e=>{xe.current=!0,J(e)},[]);s.useEffect(()=>Do(re),[re]),s.useEffect(()=>{Wo(A.map(e=>e.value.surfaceId))},[A]),s.useEffect(()=>{Ko(N&&N!==de?N:$a)},[N]);const Te=s.useMemo(()=>w===de||w==="none"?void 0:A.find(e=>e.value.surfaceId===w),[A,w]);s.useEffect(()=>{xe.current||!Te||ot(Te.value,n)&&J(w)},[Te,n,w]);const[le,rt]=s.useState(null),Oe=s.useRef(null),Le=u?.fullScreenTopOffset??0,{fullScreen:K,usingApi:Ke,toggle:m,topOffsetPx:$}=Go(Oe,{forceOverlay:!!Le,topOffset:Le}),[B,V]=s.useState(!1),Ge=s.useRef(!1);s.useEffect(()=>{!O||Ge.current||K||(Ge.current=!0,V(!0))},[O,K]),s.useEffect(()=>{K&&V(!1)},[K]),s.useEffect(()=>{I&&!ot(I,n)&&(rt(I.surfaceId),J(de))},[I,n]);const lt=s.useMemo(()=>{if(le)return A.find(e=>e.value.surfaceId===le)?.value;if(!xe.current&&N===de)return Te?.value},[A,le,N,Te]);s.useEffect(()=>{if(!le||N!==de)return;const e=A.find(a=>a.value.surfaceId===le);e&&ot(e.value,n)&&(rt(null),J(le))},[A,N,le,n]);const E=n.agentId?.trim()||"default",U=Yo(n.sandbox.target??"local");ee.current=U;const k=qo(),ce=Qt(k?.selected??xi),R=k?.members.find(e=>e.id===ce),rn=_(Jo)[0]?.value,Pt=rn?.specId,M=Zn(R?.specId??E)??(Pt?Zn(Pt):void 0),Ye=R?void 0:rn,ln=U&&!R?Ia(Pt,M):void 0;Pe.current=R?.name??M?.name??E;const cn=_(Qo),dn=j.hiddenOpeners,un=j.hideOpeners,$t=j.openers,Ut=s.useMemo(()=>{if(un)return[];const e=new Set(dn??[]),a=S=>e.size===0?S:S.filter(Ie=>!e.has(Ie.text));if($t)return a($t);const r=cn.flatMap(S=>S.value.suggestions);if(r.length>0)return a(r);const b=a(M?.suggestions??[]),g=a(k?.team.suggestions??[]);if(g.length===0)return b;const Y=new Set(g.map(S=>S.text)),L=k?.team.name??"Team",ne=R?.name??M?.name??E;return[...g.map(S=>({...S,group:L})),...b.filter(S=>!Y.has(S.text)).map(S=>({...S,group:ne}))]},[cn,k,M,R,E,dn,un,$t]),ct=s.useMemo(()=>Ut.map(e=>({title:e.summary??e.text,message:e.message??e.text,group:e.group})),[Ut]),Mt=Ne(M?.icon),G=u?.presence,gs=Ne(k?.team.icon),fn=_(Zo),dt=s.useMemo(()=>{const e=[],a=new Map,r=new Set,b=new Set(A.map(g=>g.value.surfaceId));for(const g of ti(fn,I?.surfaceId)){if(ni(g.value.id,b,I?.surfaceId))continue;let Y;try{Y=g.value.tools(n)}catch(L){console.warn(`[loop] frontend tools from '${g.plugin}' failed:`,L);continue}for(const L of Y){const ne=a.get(L.name);if(ne){console.warn(`[loop] frontend tool '${L.name}' from '${g.plugin}' is shadowed by the one from '${ne}'.`);continue}a.set(L.name,g.plugin),e.push(L),g.value.chatView&&r.add(L.name)}}for(const g of j.frontendTools??[])a.has(g.name)||(a.set(g.name,"chat-extras"),e.push(g),r.add(g.name));return I?e:ei(e,r)},[fn,n.surfaceId,n.agentId,j.frontendTools,I?.surfaceId,A]),Ot=ai(),qe=s.useMemo(()=>{if(Ot.length===0)return dt;const e=new Set(dt.map(a=>a.name));return[...dt,...Ot.filter(a=>!e.has(a.name))]},[dt,Ot]),pn=fs(),Lt=j.agentToolBundles,hs=s.useMemo(()=>{const e=j.frontendTools??[];if(!Lt?.length)return j.frontendTools;const a=ps(pn.filter(b=>Lt.includes(b.id)),C),r=new Set(e.map(b=>b.name));return[...e,...a.filter(b=>!r.has(b.name))]},[j.frontendTools,Lt,pn,C]);we.current=U&&qe.some(e=>e.name===Xo)?C.getOutput(vt)?.sandbox:void 0;const T=ea(n.sandbox,n.serverUrl),Je=s.useMemo(()=>Ga({baseUrl:T??"",getAccessToken:()=>d.current,fetch:(e,a)=>fetch(e,a)}),[T]),mn=_(ta),xs=s.useMemo(()=>mn.filter(e=>e.value.composer).map(e=>({name:e.value.name,description:e.value.description})),[mn]),bs=s.useMemo(()=>{if(!k||!R)return as(M).map(r=>({name:r.name,description:r.description,icon:Ne(r.icon)}));const e=k.members.map(r=>({name:r.name,description:r.description,emoji:r.emoji,icon:Ne(r.icon),disabled:r.id===R.id,disabledReason:r.id===R.id?`You are already talking to ${r.name}`:void 0})),a=Xn(k.team,R.id).filter(r=>!k.members.some(b=>b.name===r.name)).map(r=>({name:r.name,description:r.description,icon:Ne(r.icon)}));return[...e,...a]},[k,R,M]),{inference:gn,anonymous:vs}=Ja(U),Ss=sn(e=>e.user),Ft=U&&vs.status==="expired",hn=!Ss,Qe=na();je.current=Qe.disabled?Qe.disableReason||"This conversation is closed here.":void 0;const zt=T===void 0?sa(n.sandbox,o):void 0,Ze=Z||Ft||!!ln||!!zt||Qe.disabled,xn=Ft?hn?o.demoKeyExpired:o.keyExpired:ln??zt??jt??(Qe.disabled?Qe.disableReason:void 0),[_t,Xe]=s.useState(""),[bn]=oa(),et=s.useMemo(()=>u?.voice?aa(u.voice,bn):void 0,[u?.voice,bn]),[ys,Cs]=s.useState(!1),[ws,vn]=s.useState(),ut=ws??Ye?.model??M?.model??n.model??"",Fe=ia(),Sn=s.useRef(Fe),yn=s.useRef(ce),Cn=s.useRef(Fe);Cn.current=Fe,s.useEffect(()=>{yn.current!==ce&&(yn.current=ce,Sn.current=Cn.current,vn(void 0))},[ce]);const js=Fe&&Fe!==Sn.current?Fe:null,[ks,Ts]=s.useState(),Rs=js??ks??null,Is=Zt(Ae.inpromptMenu),wn=Zt(Ae.promptAction),jn=Zt(Ae.chatHeader),Es=s.useMemo(()=>k?.members.map(e=>({id:e.id,name:e.name,description:e.description,icon:Ne(e.icon)}))??[],[k]),Re=os(e=>e.pending),[kn,As]=s.useState(0);s.useEffect(()=>ra(()=>As(e=>e+1)),[]),s.useEffect(()=>{Re&&(Xe(Re.text),os.getState().consume(),Re.submit&&ie(Re.text))},[Re]);const Tn=C.getConfig(vt)?.datalayerCreatePayload,H=!!(Ye?.createPayload?.app_spec||Tn?.app_spec),Nt=ii(Tn),Ps=sn(e=>e.token),Bt=C.getConfig(vt)?.datalayerVisitors,$s=la(Bt),Us=C.getConfig(vt)?.embedToken,ge=Bt?$s.token:Us||Ps;d.current=ge||void 0;const Ms=s.useMemo(()=>ca(u?.voice,ge||void 0),[u?.voice,ge]),he=!!(Nt||Bt);if(he&&!H)throw new Error("A deployment’s page runs its application: its host gave no app_spec.");const[Rn]=s.useState(es),[Vt,Os]=s.useMemo(()=>{try{return[li(typeof window>"u"?"":window.location.search),""]}catch(e){return["",e instanceof Error?e.message:String(e)]}},[]),[In,Ls]=s.useState(void 0),z=s.useMemo(()=>In??ri(u?.thread??(Vt&&H?{id:Vt,messages:[],fromRuntime:!0}:void 0),Nt,Rn),[In,u?.thread,Vt,H,Nt,Rn]),[ze,En]=s.useState(null),Fs=!!(z?.fromRuntime&&ze?.given!==z.id);s.useEffect(()=>{if(!z?.fromRuntime||!H||!T)return;let e=!0;return(async()=>{let a="";for(let r=0;r<4&&e;r+=1)try{const b=await da({agentBaseUrl:T,agentId:E,uid:z.id,token:ge});e&&En({given:z.id,thread:{...z,fromRuntime:!1,messages:b}});return}catch(b){a=b instanceof Error?b.message:String(b),await new Promise(g=>setTimeout(g,1500))}e&&En({given:z.id,thread:{id:es(),messages:[],onStarted:z.onStarted},said:ts.notOpened(a)})})(),()=>{e=!1}},[z?.id,z?.fromRuntime,H,T,E,ge]);const Ht=z?.fromRuntime?ze?.given===z.id?ze.thread:void 0:z,ft=n.thread||Ht?.id||"",[An,Pn]=s.useState(void 0),[zs,$n]=s.useState(0);s.useEffect(()=>{if(!H||!T||!ft||O)return;let e=!0;return Je.described(ft).then(a=>e&&Pn(a),()=>e&&Pn(void 0)),()=>{e=!1}},[H,T,ft,O,zs,Je]);const[Un,Mn]=s.useState(Os),[On,Ln]=s.useState(null),Dt=s.useRef(null),Wt=s.useRef(null),Fn=s.useRef(null),zn=s.useMemo(()=>({client:Je,say:e=>{Mn(e),$n(a=>a+1)},openThread:e=>{Ls({id:e,messages:[],fromRuntime:!0}),$n(a=>a+1)},download:(e,a,r)=>{const b=URL.createObjectURL(new Blob([a],{type:r})),g=document.createElement("a");g.href=b,g.download=e,g.click(),URL.revokeObjectURL(b)},choose:e=>new Promise(a=>{Dt.current=a,Ln(e)}),pickFile:e=>new Promise(a=>{const r=Fn.current;if(!r){a(void 0);return}Wt.current=a,r.accept=e,r.value="",r.click()})}),[Je]),Kt=s.useMemo(()=>U?Ha({agentId:R?.specId??E,instructions:ua(M,Ye?.instructions),model:ut||void 0,inference:gn,frontendTools:qe,subagents:k&&R?Xn(k.team,R.id):as(M),sharing:k?.sharing,onSubagentEvent:e=>Aa.getState().appendSubagentEvent(e),modeEffect:Ye?.modeEffect}):T!==void 0?{type:"ag-ui",endpoint:H?`${T}/api/v1/apps/agents/${encodeURIComponent(E)}/ag-ui/`:`${T}/api/v1/ag-ui/${E}/`,...H&&ge?{authToken:ge}:{},...H?{uiSocket:`${T.replace(/^http/,"ws")}/api/v1/apps/ui`,uiFiles:`${T}/api/v1/apps/agents/${encodeURIComponent(E)}/files`,appSessions:`${T}/api/v1/apps/sessions`,...he?{ownRoutesOnly:!0}:{}}:{},agentId:E,configEndpoint:`${T}/api/v1/configure`,enableConfigQuery:!0}:void 0,[E,U,gn,R,qe,k,M,Ye,ut,T,H,ge,he]),pt=fa(!U,Kt?.type==="ag-ui"?Kt.configEndpoint:void 0,void 0,E),tt=pa(),mt=ma(E),[_n,Gt]=s.useState(void 0),[_s,Ns]=s.useState(void 0);s.useEffect(()=>{if(U||T===void 0)return;const e=ga(T,E,he);if(!e){Gt([]);return}let a=!1;return fetch(e).then(r=>r.ok?r.json():null).then(r=>{a||(Gt(r?ha(r):[]),Ns(r?xa(r):void 0))}).catch(()=>{a||Gt([])}),()=>{a=!0}},[T,E,U,he]);const Bs=s.useMemo(()=>ba(_n,()=>Object.values(va).filter(e=>e.available&&Sa(e)).map(e=>({id:e.id,name:e.name,provider:e.provider}))),[_n]),Nn=s.useMemo(()=>{const e=pt.data?.builtinTools??[],a=new Set(e.map(r=>r.name));return{runtime:e,frontend:qe.filter(r=>!a.has(r.name)).map(r=>({id:r.name,name:r.name}))}},[pt.data?.builtinTools,qe]),Bn=s.useMemo(()=>new Set((tt.data?.skills??[]).filter(e=>e.status==="enabled"||e.status==="loaded").map(e=>e.id)),[tt.data]),Vs=s.useCallback(async e=>{if(he)throw new Error("A deployment’s chat does not switch its runtime’s model.");vn(e),!(U||T===void 0)&&await fetch(`${T}/api/v1/configure/inference/provider`,{method:"PUT",headers:{"content-type":"application/json"},body:JSON.stringify({model:e})}).catch(()=>{})},[T,U,he]),Vn=u?.promptPlacement==="bottom-chat",Hs=u?.promptPlacement==="floating",_e=u?.promptPlacement==="top",nt=u?.hidePrompt===!0||j.hidePrompt===!0,Ds={onSend:()=>{ie(_t)},input:_t,setInput:Xe,focusTrigger:Re||kn?(Re?.nonce??0)+kn:void 0,placement:Hs||Q==="floating"||Q==="floating-top"||Q==="floating-bottom"?"floating":"docked",floatingAnchor:Q==="floating-top"?"top":"bottom",isLoading:O,onStop:()=>n.viewControls.stop?.(),placeholder:xn??j.sendInstead?.says??ue,typingSuggestions:Ut.map(e=>e.text),suggestions:ct,disableInputPrompt:Ze,connectionConfirmed:!Ze,interim:ys,padding:_e||Q==="floating-top"||Q==="floating-bottom"||Q==="docked-top"?2:3,promptVariant:"lexical",autoFocus:u?.autoFocusPrompt??!0,mentionableAgents:bs,promptCommands:xs,headerContent:Is.length>0?t.jsx(St,{slot:Ae.inpromptMenu,props:{workspace:n}}):void 0,footerExtras:wn.length>0||et&&et.input!=="off"?t.jsxs(t.Fragment,{children:[wn.length>0?t.jsx(St,{slot:Ae.promptAction,props:{workspace:n}}):null,et&&et.input!=="off"?t.jsx(ya,{voice:et,input:_t,setInput:Xe,disabled:Ze,speaking:$e,onStopSpeaking:()=>i.current?.stopSpeaking?.(),playbackLevel:()=>i.current?.voiceLevel?.()??0,running:O,onStopRun:()=>(i.current?.interrupt??i.current?.stop)?.(),onInterrupted:()=>i.current?.markInterrupted(),onInterimChange:Cs,answers:!!(u?.voice?.output&&u.voice.output!=="off"&&u.voice.speechUrl),onSpoken:e=>{ke.current=e},send:(e,a)=>{ke.current=a,ie(e)}}):null]}):void 0,showAgentsMenu:!G,showInlineAgentsMenu:!1,agents:Es,selectedAgentId:ce,onSelectAgent:e=>k?.select(e),showTokenUsage:j.showTokenUsage??u?.showTokenUsage??!0,showContextRing:!0,agentUsage:Rs??void 0,showModelSelector:!G&&!he,models:Bs,decisions:_s,selectedModel:ut,onModelSelect:e=>{Vs(e)},showToolsMenu:!G,availableTools:Nn.runtime,availableFrontendTools:Nn.frontend,mcpServers:pt.data?.mcpServers??[],mcpStatusData:j.mcpStatusData??void 0,showSkillsMenu:!G,skills:tt.data?.skills??[],skillsLoading:tt.isLoading,enabledSkills:Bn,onToggleSkill:e=>Bn.has(e)?mt.disableSkill(e):mt.enableSkill(e),onToggleAllSkills:(e,a)=>e.forEach(r=>a?mt.enableSkill(r):mt.disableSkill(r)),codemodeEnabled:j.codemodeEnabled??!1,onToggleCodemode:j.onToggleCodemode,isA2AProtocol:!1,hasConfigData:!!pt.data,hasSkillsData:!!tt.data},Hn=yt[0]?.value.Component,Yt=Ct[0]?.value.Component,Dn=!u?.hideHeader&&!!Yt,gt=Hn?t.jsx(Hn,{workspace:n,composer:Ds}):null,Wn=A.length>0&&u?.showSurfaceSelector!==!1?t.jsx(Si,{surfaces:A.map(e=>e.value),active:I?.surfaceId??lt?.surfaceId??de,onChange:re,workspace:n}):null,Kn=t.jsxs(t.Fragment,{children:[A.map(e=>{const a=e.value,r=I?.surfaceId===a.surfaceId;return r||it.current.has(a.surfaceId)||ot(a,n)?(it.current.add(a.surfaceId),t.jsx(h,{sx:r?{flex:"1 1 0",minWidth:0,minHeight:0}:{position:"absolute",inset:0,visibility:"hidden",pointerEvents:"none",zIndex:-1},children:t.jsx(Ca,{load:a.load,props:{surfaceId:a.surfaceId,workspace:n},fallback:t.jsxs(tn,{children:["Loading ",a.title,"…"]}),errorFallback:g=>t.jsxs(tn,{children:[a.title," failed to load: ",g.message]})})},a.surfaceId)):null}),!I&&lt?t.jsx(h,{flex:"1 1 0",minWidth:0,minHeight:0,children:t.jsxs(tn,{children:["Starting ",lt.title,"…"]})}):null]}),Gn=t.jsx(t.Fragment,{children:t.jsxs(h,{flex:_e&&I?"0 0 34%":"1 1 0",maxWidth:_e&&I?460:void 0,minWidth:0,minHeight:0,display:"flex",flexDirection:"column",borderLeft:I?"1px solid":void 0,borderColor:"border.default",position:"relative",children:[j.errorBanner?t.jsx(h,{flexShrink:0,px:3,py:2,fontSize:1,borderBottom:"1px solid",bg:j.errorBanner.variant==="warning"?"attention.subtle":"danger.subtle",color:j.errorBanner.variant==="warning"?"attention.fg":"danger.fg",borderColor:j.errorBanner.variant==="warning"?"attention.muted":"danger.muted",children:j.errorBanner.message}):null,ze?.said&&ze.given===z?.id?t.jsx(F,{as:"p",role:"status",sx:{m:0,px:3,py:2,fontSize:1,color:"fg.muted"},children:ze.said}):null,Un?t.jsxs(h,{display:"flex",alignItems:"baseline",gap:2,px:3,py:2,fontSize:1,color:"fg.muted",role:"status","data-session-said":"",children:[t.jsx(F,{sx:{flex:1},children:Un}),t.jsx(q,{size:"small",variant:"invisible",onClick:()=>Mn(""),children:"Dismiss"})]}):null,On?t.jsx(fi,{question:On,onPick:e=>{Ln(null),Dt.current?.(e),Dt.current=null}}):null,t.jsx("input",{ref:Fn,type:"file",hidden:!0,"data-session-file":"",onChange:async e=>{const a=e.target.files?.[0],r=a?await a.text():void 0;Wt.current?.(r),Wt.current=null}}),t.jsx(h,{flex:"1 1 auto",minHeight:0,display:"flex",children:Fs?t.jsx(F,{as:"p",role:"status",sx:{m:0,p:3,fontSize:1,color:"fg.muted"},children:ts.opening}):t.jsx(wa,{themeVariant:u?.themeVariant,themeOverrides:u?.themeOverrides,colorMode:u?.colorMode,thread:Ht,voice:Ms,disabled:Ze,disableReason:xn,protocol:Kt,frontendTools:U?void 0:hs,initialModel:ut||void 0,title:G?.name??R?.name??M?.name??E,description:G?.welcome??M?.description,brandIcon:G?.face?t.jsx(mi,{face:G.face,size:20,state:X}):t.jsx(Mt,{size:20}),headerContent:G&&!zt?t.jsx(gi,{state:X}):void 0,emptyState:{icon:G?.face?t.jsx("span",{"aria-hidden":!0,style:{fontSize:rs,lineHeight:1},children:t.jsx(ms,{face:G.face,size:rs})}):t.jsx(Mt,{size:48}),title:G?.name??R?.name??M?.name??E,...k&&R?{sections:[{group:k.team.name,icon:t.jsx(gs,{size:48}),title:k.team.name,subtitle:k.team.description},{group:R.name,icon:t.jsx(Mt,{size:32}),title:R.name,subtitle:M?.description}]}:null},suggestions:_e||be||u?.suggestionLabels===!1?[]:ct,showHeader:Dn,headerButtons:{showNewChat:u?.headerButtons?.newChat??!1,showClear:u?.headerButtons?.clear??!1},renderHeader:Yt?e=>t.jsx(Yt,{workspace:n,header:n.chatViewModes?{...e,chatViewMode:n.chatViewModes.value,onChatViewModeChange:n.chatViewModes.onChange,offeredViewModes:n.chatViewModes.offered}:e}):void 0,showInformation:!0,headerActions:t.jsxs(h,{display:"inline-flex",alignItems:"center",gap:2,children:[n.chatHeaderActions,H&&T?t.jsxs(t.Fragment,{children:[t.jsx(ci,{facts:An}),t.jsx(ui,{uid:ft||void 0,describe:e=>Je.described(e),context:zn})]}):null,jn.length>0?t.jsx(St,{slot:Ae.chatHeader,props:{workspace:n}}):null,t.jsx(us,{icon:K?ja:ka,"aria-label":K?"Exit full screen":"Enter full screen",variant:"invisible",size:"small",onClick:()=>{V(!1),m()},sx:B?{"@keyframes dla-fullscreen-hint":{"0%, 100%":{opacity:1},"50%":{opacity:.4}},"&&":{bg:`color-mix(in srgb, ${l.primary} 16%, transparent)`,boxShadow:`inset 0 0 0 1.5px ${l.primary}`,animation:`dla-fullscreen-hint ${vi}ms ease-in-out infinite`},"@media (prefers-reduced-motion: reduce)":{"&&":{animation:"none"}}}:void 0})]}),showInput:!1,onSendReady:W,notebookToolSurfacesId:I?void 0:n.surfaceId,showTurnFooter:j.showTokenUsage??u?.showTokenUsage??!0,onContextSnapshot:Et,onLoadingChange:He,renderMessageFooter:H&&T?(e,a)=>e.role==="user"?t.jsx(di,{facts:An,turn:a.turn,context:zn}):null:void 0,onSpeakingChange:Rt,onItemsChange:At,onDisplayItemsChange:It,enableStreaming:!0},Ht?.id)}),!Dn&&jn.length>0?t.jsx(h,{hidden:!0,children:t.jsx(St,{slot:Ae.chatHeader,props:{workspace:n}})}):null,Vn&&!nt?gt:null]})}),Yn=u?.suggestionLabels!==!1&&ct.length>0?t.jsx(h,{"aria-label":o.suggestedPrompts,display:"flex",flexWrap:"wrap",gap:2,px:2,pb:"6px",children:ct.map(e=>t.jsx(h,{as:"button",type:"button",title:e.message,disabled:O||Ze,onClick:()=>{ie(e.message)},appearance:"none",font:"inherit",fontSize:0,fontWeight:"semibold",lineHeight:1.25,px:"10px",py:"5px",width:ns,flex:`0 0 ${ns}px`,borderRadius:"999px",border:"1px solid",bg:"canvas.subtle",whiteSpace:"nowrap",sx:{borderColor:"border.default",color:"fg.default",cursor:"pointer","&:hover:not(:disabled)":{borderColor:"accent.fg",color:"accent.fg"},"&:disabled":{opacity:.5,cursor:"default"}},children:t.jsx(Ta,{title:e.title,maxWidth:"100%",sx:{minWidth:0},children:e.title})},e.title))}):null,qn=f?t.jsx(h,{flex:"0 0 auto",px:3,py:2,borderTop:"1px solid",borderColor:"border.default",bg:"canvas.subtle",fontSize:1,maxHeight:"40%",overflowY:"auto",children:f}):null;return t.jsxs(h,{ref:Oe,sx:{height:"100%",minHeight:0,display:"flex",flexDirection:"column",position:"relative",...K?{bg:"canvas.default"}:null,...K&&!Ke.current?{position:"fixed",top:$,right:0,bottom:0,left:0,height:"auto",zIndex:1e3}:null},children:[be?t.jsx(be.Component,{workspace:n,editors:Kn,hasEditor:!!I,transcript:Gn,prompt:nt?null:gt,chips:nt?null:Yn,picker:Wn,transient:qn}):t.jsxs(t.Fragment,{children:[_e&&!nt?t.jsxs(h,{flex:"0 0 auto",borderBottom:"1px solid",borderColor:"border.default",children:[gt,Yn]}):null,Wn,t.jsxs(h,{flex:"1 1 auto",minHeight:0,display:"flex",position:"relative",children:[Kn,Gn]}),qn,Vn||nt||_e?null:gt]}),Ft?t.jsx(h,{position:"absolute",inset:0,zIndex:5,bg:"canvas.default",display:"flex",flexDirection:"column",minHeight:0,children:t.jsx(Ya,{agentName:R?.name??M?.name,sandboxStillRuns:U,temporary:hn,onSignedIn:()=>Ra.getState().clear()})}):null]})}function Si({surfaces:n,active:o,onChange:l,workspace:i}){const d=[...n].sort((p,v)=>(p.order??100)-(v.order??100));return t.jsxs(h,{flex:"0 0 auto",display:"flex",alignItems:"center",gap:2,px:3,py:2,borderBottom:"1px solid",borderColor:"border.default",children:[t.jsx(F,{sx:{fontSize:0,color:"fg.muted"},children:"Beside the chat"}),t.jsxs(Xt,{"aria-label":"Editor beside the chat",size:"small",children:[t.jsx(Xt.Button,{selected:o===de,onClick:()=>l(de),children:"Chat"}),d.map(p=>{const v=ot(p,i),c=v?void 0:p.unavailableReason?.(i)??"Not available right now";return t.jsx(Xt.Button,{selected:o===p.surfaceId,"aria-disabled":!v,title:c??p.title,leadingIcon:p.icon,onClick:()=>{v&&l(p.surfaceId)},children:p.title},p.surfaceId)})]})]})}function tn({children:n}){return t.jsx(h,{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"fg.muted",fontSize:1,px:3,textAlign:"center",children:n})}export{ki as default};