@datalayer/agent-runtimes 1.3.98 → 1.3.100
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist-embed/chunks/{ChatView-DE-jo1oJ.js → ChatView-Bqiq0mvd.js} +5 -5
- package/dist-embed/datalayer-app-main.js +3 -3
- package/lib/apps/embed/element.js +3 -1
- package/lib/apps/embed/embedConfig.d.ts +16 -0
- package/lib/apps/embed/embedConfig.js +28 -0
- package/lib/apps/plugins/chat/ChatView.js +10 -0
- package/package.json +1 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{y as q,f$ as rn,r as n,j as o,g0 as cn,g1 as ln,cf as fo,B as g,H as pt,T as D,c as W,cP as Pt,f9 as Lt,g2 as ae,cK as ht,e as dn,g3 as un,g4 as pn,eI as hn,g5 as mn,g6 as gn,g7 as fn,g8 as yn,g9 as
|
|
1
|
+
import{y as q,f$ as rn,r as n,j as o,g0 as cn,g1 as ln,cf as fo,B as g,H as pt,T as D,c as W,cP as Pt,f9 as Lt,g2 as ae,cK as ht,e as dn,g3 as un,g4 as pn,eI as hn,g5 as mn,g6 as gn,g7 as fn,g8 as yn,g9 as vn,ga as bn,gb as wn,gc as xn,gd as kn,aP as Sn,ey as Ro,ew as Cn,ez as qt,ge as Tn,gf as En,gg as Ao,gh as In,gi as yo,gj as jn,gk as Rn,gl as An,dt as Pn,c2 as _n,gm as On,gn as Nn,go as Mn,gp as Fn,gq as Un,gr as Ln,q as _t,gs as qn,gt as $n,gu as zn,gv as Bn,gw as Gn,gx as Hn,gy as Dn,gz as Vn,gA as Wn,gB as Kn,gC as Yn,gD as Jn,gE as Qn,gF as Xn,gG as Zn,gH as Ye,gI as ea,gJ as ta,gK as oa,gL as na,gM as aa,gN as Ie,gO as sa,gP as ra,gQ as ia,gR as vo,gS as ca,gT as la,fh as da,gU as Ot,gV as je,gW as ua,c3 as bo,gX as pa,gY as ha,gZ as ma,g_ as ga,g$ as fa,h0 as ya,h1 as va,h2 as ba,h3 as wa,h4 as Nt,h5 as xa,h6 as ka,I as Sa,h7 as Ca,h8 as Ta,h9 as wo,ha as Ea,hb as Ia,hc as $t,hd as ja,he as Ra,e_ as Mt,hf as Aa,hg as Pa}from"../datalayer-app-main.js";import{S as _a,E as Oa,a as Na}from"./SignInIcon-4HkE48mS.js";import{F as Ma,a as Fa,b as Ua}from"./LinkedInGreyIcon-BoWXE-HS.js";function La(){const e=q(rn);return n.useMemo(()=>e.map(a=>a.value),[e])}const Ft={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"}},xo=()=>{if(typeof document>"u")return"";const e=document.getElementById("datalayer-config-data");if(!e?.textContent)return"";try{const a=JSON.parse(e.textContent);return String(a?.iamUrl||"").replace(/\/$/,"")}catch{return""}},qa=(e,a="Unable to start social sign-in.")=>{if(e instanceof Error&&e.message)return e.message;if(typeof e=="string"&&e.trim())return e;if(e&&typeof e=="object"&&"message"in e){const i=e.message;if(typeof i=="string"&&i.trim())return i}return a},$a=mn`
|
|
2
2
|
.signin-input-theme-scope input:-webkit-autofill,
|
|
3
3
|
.signin-input-theme-scope input:-webkit-autofill:hover,
|
|
4
4
|
.signin-input-theme-scope input:-webkit-autofill:focus,
|
|
@@ -25,7 +25,7 @@ import{y as q,f$ as rn,r as n,j as o,g0 as cn,g1 as ln,cf as fo,B as g,H as pt,T
|
|
|
25
25
|
background-color: var(--bgColor-default) !important;
|
|
26
26
|
opacity: 1 !important;
|
|
27
27
|
}
|
|
28
|
-
`,za=({onSignIn:e,onApiKeySignIn:a,loginUrl:i,name:s,title:l="Datalayer OTEL",description:p="Sign in to access the observability dashboard.",icon:m,leadingIcon:y=o.jsx(hn,{size:24}),github:u=!1,google:K=!1,linkedin:z=!1,apiKey:Je=!1,signUp:O=!0,socialSignInNavigationTarget:Z,asDoc:b=!1,fillHeight:E=!0,hideHero:ee=!1,calloutTitle:Pe,calloutDescription:Qe,passwordToggleLabel:se="Sign in with a password",signUpTitle:Bt="Don't have an account?",signUpDescription:Y="Create a free Datalayer account with your email address.",signUpLabel:mt="Sign up with email",signUpHref:_e="https://datalayer.ai/signup",onSignUp:B,forgotPasswordHref:J="/password",forgotPasswordLabel:Oe="Forgot password?",showForgotPassword:gt=!0,socialButtonMarginTop:x=3,actionButtonMaxWidth:Q=320})=>{const te=b&&!ee,Xe=s??(b&&l==="Datalayer OTEL"?"Datalayer Sign In":l),ft=m??(b?o.jsx(_a,{size:24}):y),N=n.useMemo(()=>{if(i)return i;const r=xo();return r?`${r}/api/iam/v1/login`:"/api/iam/v1/login"},[i]),[V,fe]=n.useState(""),[re,yt]=n.useState(""),[Ze,ie]=n.useState(!1),[ce,et]=n.useState(!1),[C,ye]=n.useState(!1),[le,Ne]=n.useState(!1),[Me,tt]=n.useState(null),[M,be]=n.useState(null),[oe,ot]=n.useState(""),[ve,we]=n.useState(null),[Fe,F]=n.useState(null),{enqueueToast:k}=cn(),[de,ne]=n.useState(!1),[P,Ue]=n.useState(""),Le=n.useRef(null),qe=n.useCallback(r=>ln()?fo.URLExt.join(fo.PageConfig.getBaseUrl(),r.oauth2CallbackServerRoute):`${window.location.protocol}//${window.location.hostname}${window.location.port?`:${window.location.port}`:""}${r.oauth2CallbackUIRoute}`,[]),_=n.useMemo(()=>{if(typeof window>"u")return"/";const r=`${window.location.pathname}${window.location.search}${window.location.hash}`;return r.startsWith("/")?r:"/"},[]),$e=n.useCallback(async r=>{if(!le){F(null),tt(r.name),Ne(!0);try{const v=xo(),f=new URLSearchParams({provider:r.name,callback_uri:qe(r)}),U=Z===void 0?void 0:String(Z||"").trim(),ke=U===void 0?_&&_!=="/"?_:void 0:U&&U.startsWith("/")&&!U.startsWith("//")?U:void 0;ke&&f.set("post_auth_redirect",ke);const he=`${v||""}/api/iam/v1/oauth2/authz/url?${f.toString()}`,Be=await fetch(he),Ge=await Be.json(),He=Ge?.autorization_url;if(!Be.ok||!He)throw new Error(Ge?.message||"Unable to start social sign-in.");window.location.assign(He)}catch(v){const f=qa(v);F(f),k(f,{variant:"error"}),tt(null),Ne(!1)}}},[qe,_,k,le,Z]);n.useEffect(()=>{de&&Le.current?.focus()},[de]);const ue=n.useCallback(()=>{ne(!1),Ue("")},[]),bt=n.useCallback(()=>{!P.trim()||!a||(a(P.trim()),ue())},[P,a,ue]),vt=n.useCallback(()=>{if(B){B();return}window.location.assign(_e)},[B,_e]),ze=n.useCallback(()=>{if(J){if(J.startsWith("http://")||J.startsWith("https://")){window.open(J,"_blank","noopener,noreferrer");return}window.location.assign(J)}},[J]),xe=n.useCallback(async()=>{if(!(b||!V||!re||C)){ye(!0),F(null);try{const r=await fetch(N,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({handle:V,password:re})});if(!r.ok)throw new Error(`HTTP ${r.status}`);const v=await r.json();if(v.success&&v.token){const f=String(v?.user?.id||v?.user?.uid||"").trim();if(!!v?.user?.mfaUrl&&f){be(f),we(v.token),F(null);return}e&&e(v.token,V)}else F(v.message||"Invalid username or password.")}catch(r){F(r instanceof Error?r.message:String(r))}finally{ye(!1)}}},[b,V,re,C,N,e]),pe=n.useCallback(async()=>{if(!(b||C||!M||!oe.trim()||!ve)){ye(!0),F(null);try{const r=new URL(N,window.location.origin),v=r.pathname.endsWith("/api/iam/v1/login")?r.href.replace(/\/api\/iam\/v1\/login$/,""):`${r.origin}`,f=await fetch(`${v}/api/iam/v1/users/${M}/mfa/validate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({userUid:M,code:oe.trim()})}),U=await f.json();if(!f.ok||!U?.success)throw new Error(U?.message||"Failed to validate your MFA code.");e&&e(ve,V)}catch(r){const v=r instanceof Error?r.message:String(r);F(v),k(v,{variant:"error"})}finally{ye(!1)}}},[b,k,V,C,N,oe,ve,M,e]),S=n.useCallback(r=>{r.key==="Enter"&&(M?pe():xe())},[M,xe,pe]),j=le||C||b;return o.jsxs(g,{className:"signin-input-theme-scope",display:"flex",alignItems:ee||te||!E?"flex-start":"center",justifyContent:"center",minHeight:ee||te||!E?"auto":"100vh",bg:ee?"transparent":"canvas.default",color:"fg.default",py:ee?0:te?2:4,children:[o.jsx($a,{}),o.jsxs(g,{width:"100%",maxWidth:440,p:0,children:[!ee&&o.jsxs(o.Fragment,{children:[o.jsxs(g,{display:"flex",alignItems:"center",gap:2,mb:te?2:3,justifyContent:"center",children:[ft,o.jsx(pt,{sx:{fontSize:3},children:Xe})]}),o.jsx(D,{as:"p",sx:{fontSize:1,color:"fg.muted",mb:te?2:3,textAlign:"center"},children:p})]}),(Pe||Qe)&&o.jsxs(g,{mb:3,textAlign:"center",children:[Pe&&o.jsx(pt,{as:"h3",sx:{fontSize:2,mb:1},children:Pe}),Qe&&o.jsx(D,{sx:{color:"fg.muted",fontSize:1},children:Qe})]}),!M&&(u||K||z)&&o.jsxs(o.Fragment,{children:[u&&o.jsx(W,{block:!0,size:"large",leadingVisual:Me==="github"?()=>o.jsx(Pt,{size:"small"}):Ma,disabled:j,onClick:()=>$e(Ft.github),sx:{mt:x,maxWidth:Q,mx:"auto"},children:"Sign in with GitHub"}),K&&o.jsx(W,{block:!0,size:"large",leadingVisual:Me==="google"?()=>o.jsx(Pt,{size:"small"}):Fa,disabled:j,onClick:()=>$e(Ft.google),sx:{mt:x,maxWidth:Q,mx:"auto"},children:"Sign in with Google"}),z&&o.jsx(W,{block:!0,size:"large",leadingVisual:Me==="linkedin"?()=>o.jsx(Pt,{size:"small"}):Ua,disabled:j,onClick:()=>$e(Ft.linkedin),sx:{mt:x,maxWidth:Q,mx:"auto"},children:"Sign in with LinkedIn"})]}),!M&&!Ze&&o.jsx(g,{mt:3,display:"flex",justifyContent:"center",children:o.jsx(W,{leadingVisual:Lt,size:"large",block:!0,disabled:b||C||le,onClick:()=>ie(!0),sx:{maxWidth:Q,mx:"auto"},children:se})}),!M&&Ze&&o.jsxs(g,{mt:4,children:[o.jsxs(ae,{required:!0,sx:{mb:3},children:[o.jsx(ae.Label,{children:"Username"}),o.jsx(ht,{autoFocus:!0,block:!0,placeholder:"Your username",value:V,disabled:C||b,onChange:r=>fe(r.target.value),onKeyDown:S})]}),o.jsxs(ae,{required:!0,sx:{mb:3},children:[o.jsx(ae.Label,{children:"Password"}),o.jsx(ht,{block:!0,placeholder:"Your password",type:ce?"text":"password",value:re,disabled:C||b,onChange:r=>yt(r.target.value),onKeyDown:S,trailingAction:o.jsx(ht.Action,{onClick:()=>et(!ce),disabled:C||b,icon:ce?Oa:Na,"aria-label":ce?"Hide password":"Show password",sx:{color:"var(--fgColor-muted)"}})})]}),o.jsxs(g,{display:"flex",alignItems:"center",justifyContent:"space-between",mt:3,children:[o.jsx(W,{variant:"primary",disabled:C||b||!V||!re,onClick:xe,children:C?"Signing in…":"Sign In"}),gt&&o.jsx(dn,{as:"button",sx:{fontSize:1,cursor:b?"not-allowed":"pointer",background:"none",border:"none",opacity:b?.6:1},onClick:()=>{b||C||ze()},children:Oe})]})]}),M&&o.jsxs(o.Fragment,{children:[o.jsxs(ae,{required:!0,sx:{mb:3,mt:2},children:[o.jsx(ae.Label,{children:"MFA Code"}),o.jsx(ht,{autoFocus:!0,block:!0,placeholder:"Your MFA code",value:oe,disabled:C||b,onChange:r=>ot(r.target.value),onKeyDown:S})]}),o.jsx(W,{variant:"primary",block:!0,disabled:C||b||!oe.trim(),onClick:pe,sx:{maxWidth:Q,mx:"auto"},children:C?"Validating…":"Validate MFA Code"})]}),Fe&&o.jsx(D,{sx:{color:"danger.fg",fontSize:1,mt:3,display:"block"},children:Fe}),O&&o.jsxs(g,{mt:4,pt:4,textAlign:"center",borderTop:"1px solid",borderColor:"border.muted",children:[o.jsx(pt,{as:"h3",sx:{fontSize:2,mb:2},children:Bt}),o.jsx(D,{as:"p",sx:{color:"fg.muted",fontSize:1,mb:3},children:Y}),o.jsx(g,{display:"flex",justifyContent:"center",children:o.jsx(W,{variant:"primary",size:"large",leadingVisual:un,disabled:b||C,onClick:vt,children:mt})})]}),Je&&a&&o.jsxs(o.Fragment,{children:[o.jsxs(g,{display:"flex",alignItems:"center",gap:2,my:3,children:[o.jsx(g,{flex:1,height:"1px",bg:"border.default"}),o.jsx(D,{sx:{fontSize:0,color:"fg.muted"},children:"or"}),o.jsx(g,{flex:1,height:"1px",bg:"border.default"})]}),o.jsx(W,{block:!0,leadingVisual:Lt,disabled:b||C||le,onClick:()=>ne(!0),sx:{maxWidth:Q,mx:"auto"},children:"Sign in with an API Key"}),de&&o.jsx(g,{role:"dialog","aria-modal":"true","aria-labelledby":"signin-api-key-title",onKeyDown:r=>{r.key==="Escape"&&ue()},onClick:ue,position:"fixed",inset:0,zIndex:200,p:3,bg:"canvas.backdrop",display:"flex",alignItems:"center",justifyContent:"center",children:o.jsxs(g,{as:"form",onClick:r=>r.stopPropagation(),onSubmit:r=>{r.preventDefault(),bt()},width:"min(560px, 100%)",p:3,borderRadius:2,border:"1px solid",borderColor:"border.default",bg:"canvas.overlay",color:"fg.default",boxShadow:"shadow.large",children:[o.jsx(pt,{id:"signin-api-key-title",sx:{fontSize:2,mb:2},children:"Enter your API Key"}),o.jsxs(ae,{required:!0,children:[o.jsx(ae.Label,{children:"API Key"}),o.jsx(pn,{block:!0,required:!0,autoFocus:!0,placeholder:"Paste your API key here",value:P,onInput:r=>Ue(r.currentTarget.value),ref:Le})]}),o.jsxs(g,{mt:3,display:"flex",justifyContent:"flex-end",gap:2,children:[o.jsx(W,{type:"button",onClick:ue,children:"Cancel"}),o.jsx(W,{type:"submit",variant:"primary",disabled:!P.trim(),children:"Authenticate"})]})]})})]})]})]})};function Ba(e){const{agentId:a,instructions:i,model:s,frontendTools:l,inference:p,subagents:m,sharing:y,onSubagentEvent:u,modeEffect:K}=e;return{type:"browser-vercel-ai",endpoint:"",agentId:a,enableConfigQuery:!1,options:{instructions:i,model:s,frontendTools:l,inference:p,subagents:m,sharing:y,onSubagentEvent:u,modeEffect:K}}}const Ga={"tavily:0.0.1":bn},$={"crawl:0.0.1":kn,"events:0.0.1":vn,"github:0.0.1":xn,"text-summarizer:0.0.1":wn};function Re(e){return{id:e.id,name:e.name,description:e.description,version:e.version??"0.0.1",tags:e.tags,enabled:e.enabled,requiredEnvVars:e.requiredEnvVars}}const Po={"runtime-echo:0.0.1":yn},Ae={"jupyter-notebook:0.0.1":gn,"lexical-document:0.0.1":fn},Ha={id:"cog-crawler",version:"0.0.1",name:"Crawler Cog",description:"Researches the web and public repositories under the Web Research Frame: every finding rests on a source that was opened, is cited, and is checked before it is reported.",tags:["market-analyst","agent-worker","research","github","analysis","cog"],domain:"market-analyst",enabled:!0,model:"bedrock:us.anthropic.claude-sonnet-4-6",modelAdditionals:["alibaba:qwen-max"],mcpServers:[Ga["tavily:0.0.1"]],skills:[$["github:0.0.1"]?Re($["github:0.0.1"]):void 0,$["events:0.0.1"]?Re($["events:0.0.1"]):void 0,$["crawl:0.0.1"]?Re($["crawl:0.0.1"]):void 0].filter(Boolean),backendTools:[],frontendTools:[Ae["jupyter-notebook:0.0.1"],Ae["lexical-document:0.0.1"]],environmentName:"ai-agents-env",icon:"globe",emoji:"🌐",color:"#10B981",suggestions:[{text:"Search the web for recent news about AI agents",summary:"AI agent news"},{text:"Find trending open-source Python projects on GitHub",summary:"Trending Python projects"},{text:"Research best practices for building RAG applications",summary:"RAG best practices"},{text:"Compare popular JavaScript frameworks in 2024",summary:"JavaScript frameworks 2024"}],welcomeMessage:`Hi! I'm the Crawler Cog. I research the web and GitHub under the Web Research Frame: I open what I cite, I say which sources are primary, and I tell you where sources disagree.
|
|
28
|
+
`,za=({onSignIn:e,onApiKeySignIn:a,loginUrl:i,name:s,title:l="Datalayer OTEL",description:p="Sign in to access the observability dashboard.",icon:m,leadingIcon:y=o.jsx(hn,{size:24}),github:u=!1,google:K=!1,linkedin:z=!1,apiKey:Je=!1,signUp:O=!0,socialSignInNavigationTarget:Z,asDoc:v=!1,fillHeight:T=!0,hideHero:ee=!1,calloutTitle:Pe,calloutDescription:Qe,passwordToggleLabel:se="Sign in with a password",signUpTitle:Bt="Don't have an account?",signUpDescription:Y="Create a free Datalayer account with your email address.",signUpLabel:mt="Sign up with email",signUpHref:_e="https://datalayer.ai/signup",onSignUp:B,forgotPasswordHref:J="/password",forgotPasswordLabel:Oe="Forgot password?",showForgotPassword:gt=!0,socialButtonMarginTop:b=3,actionButtonMaxWidth:Q=320})=>{const te=v&&!ee,Xe=s??(v&&l==="Datalayer OTEL"?"Datalayer Sign In":l),ft=m??(v?o.jsx(_a,{size:24}):y),N=n.useMemo(()=>{if(i)return i;const r=xo();return r?`${r}/api/iam/v1/login`:"/api/iam/v1/login"},[i]),[V,fe]=n.useState(""),[re,yt]=n.useState(""),[Ze,ie]=n.useState(!1),[ce,et]=n.useState(!1),[C,ye]=n.useState(!1),[le,Ne]=n.useState(!1),[Me,tt]=n.useState(null),[M,ve]=n.useState(null),[oe,ot]=n.useState(""),[be,we]=n.useState(null),[Fe,F]=n.useState(null),{enqueueToast:k}=cn(),[de,ne]=n.useState(!1),[P,Ue]=n.useState(""),Le=n.useRef(null),qe=n.useCallback(r=>ln()?fo.URLExt.join(fo.PageConfig.getBaseUrl(),r.oauth2CallbackServerRoute):`${window.location.protocol}//${window.location.hostname}${window.location.port?`:${window.location.port}`:""}${r.oauth2CallbackUIRoute}`,[]),_=n.useMemo(()=>{if(typeof window>"u")return"/";const r=`${window.location.pathname}${window.location.search}${window.location.hash}`;return r.startsWith("/")?r:"/"},[]),$e=n.useCallback(async r=>{if(!le){F(null),tt(r.name),Ne(!0);try{const w=xo(),f=new URLSearchParams({provider:r.name,callback_uri:qe(r)}),U=Z===void 0?void 0:String(Z||"").trim(),ke=U===void 0?_&&_!=="/"?_:void 0:U&&U.startsWith("/")&&!U.startsWith("//")?U:void 0;ke&&f.set("post_auth_redirect",ke);const he=`${w||""}/api/iam/v1/oauth2/authz/url?${f.toString()}`,Be=await fetch(he),Ge=await Be.json(),He=Ge?.autorization_url;if(!Be.ok||!He)throw new Error(Ge?.message||"Unable to start social sign-in.");window.location.assign(He)}catch(w){const f=qa(w);F(f),k(f,{variant:"error"}),tt(null),Ne(!1)}}},[qe,_,k,le,Z]);n.useEffect(()=>{de&&Le.current?.focus()},[de]);const ue=n.useCallback(()=>{ne(!1),Ue("")},[]),vt=n.useCallback(()=>{!P.trim()||!a||(a(P.trim()),ue())},[P,a,ue]),bt=n.useCallback(()=>{if(B){B();return}window.location.assign(_e)},[B,_e]),ze=n.useCallback(()=>{if(J){if(J.startsWith("http://")||J.startsWith("https://")){window.open(J,"_blank","noopener,noreferrer");return}window.location.assign(J)}},[J]),xe=n.useCallback(async()=>{if(!(v||!V||!re||C)){ye(!0),F(null);try{const r=await fetch(N,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({handle:V,password:re})});if(!r.ok)throw new Error(`HTTP ${r.status}`);const w=await r.json();if(w.success&&w.token){const f=String(w?.user?.id||w?.user?.uid||"").trim();if(!!w?.user?.mfaUrl&&f){ve(f),we(w.token),F(null);return}e&&e(w.token,V)}else F(w.message||"Invalid username or password.")}catch(r){F(r instanceof Error?r.message:String(r))}finally{ye(!1)}}},[v,V,re,C,N,e]),pe=n.useCallback(async()=>{if(!(v||C||!M||!oe.trim()||!be)){ye(!0),F(null);try{const r=new URL(N,window.location.origin),w=r.pathname.endsWith("/api/iam/v1/login")?r.href.replace(/\/api\/iam\/v1\/login$/,""):`${r.origin}`,f=await fetch(`${w}/api/iam/v1/users/${M}/mfa/validate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({userUid:M,code:oe.trim()})}),U=await f.json();if(!f.ok||!U?.success)throw new Error(U?.message||"Failed to validate your MFA code.");e&&e(be,V)}catch(r){const w=r instanceof Error?r.message:String(r);F(w),k(w,{variant:"error"})}finally{ye(!1)}}},[v,k,V,C,N,oe,be,M,e]),S=n.useCallback(r=>{r.key==="Enter"&&(M?pe():xe())},[M,xe,pe]),I=le||C||v;return o.jsxs(g,{className:"signin-input-theme-scope",display:"flex",alignItems:ee||te||!T?"flex-start":"center",justifyContent:"center",minHeight:ee||te||!T?"auto":"100vh",bg:ee?"transparent":"canvas.default",color:"fg.default",py:ee?0:te?2:4,children:[o.jsx($a,{}),o.jsxs(g,{width:"100%",maxWidth:440,p:0,children:[!ee&&o.jsxs(o.Fragment,{children:[o.jsxs(g,{display:"flex",alignItems:"center",gap:2,mb:te?2:3,justifyContent:"center",children:[ft,o.jsx(pt,{sx:{fontSize:3},children:Xe})]}),o.jsx(D,{as:"p",sx:{fontSize:1,color:"fg.muted",mb:te?2:3,textAlign:"center"},children:p})]}),(Pe||Qe)&&o.jsxs(g,{mb:3,textAlign:"center",children:[Pe&&o.jsx(pt,{as:"h3",sx:{fontSize:2,mb:1},children:Pe}),Qe&&o.jsx(D,{sx:{color:"fg.muted",fontSize:1},children:Qe})]}),!M&&(u||K||z)&&o.jsxs(o.Fragment,{children:[u&&o.jsx(W,{block:!0,size:"large",leadingVisual:Me==="github"?()=>o.jsx(Pt,{size:"small"}):Ma,disabled:I,onClick:()=>$e(Ft.github),sx:{mt:b,maxWidth:Q,mx:"auto"},children:"Sign in with GitHub"}),K&&o.jsx(W,{block:!0,size:"large",leadingVisual:Me==="google"?()=>o.jsx(Pt,{size:"small"}):Fa,disabled:I,onClick:()=>$e(Ft.google),sx:{mt:b,maxWidth:Q,mx:"auto"},children:"Sign in with Google"}),z&&o.jsx(W,{block:!0,size:"large",leadingVisual:Me==="linkedin"?()=>o.jsx(Pt,{size:"small"}):Ua,disabled:I,onClick:()=>$e(Ft.linkedin),sx:{mt:b,maxWidth:Q,mx:"auto"},children:"Sign in with LinkedIn"})]}),!M&&!Ze&&o.jsx(g,{mt:3,display:"flex",justifyContent:"center",children:o.jsx(W,{leadingVisual:Lt,size:"large",block:!0,disabled:v||C||le,onClick:()=>ie(!0),sx:{maxWidth:Q,mx:"auto"},children:se})}),!M&&Ze&&o.jsxs(g,{mt:4,children:[o.jsxs(ae,{required:!0,sx:{mb:3},children:[o.jsx(ae.Label,{children:"Username"}),o.jsx(ht,{autoFocus:!0,block:!0,placeholder:"Your username",value:V,disabled:C||v,onChange:r=>fe(r.target.value),onKeyDown:S})]}),o.jsxs(ae,{required:!0,sx:{mb:3},children:[o.jsx(ae.Label,{children:"Password"}),o.jsx(ht,{block:!0,placeholder:"Your password",type:ce?"text":"password",value:re,disabled:C||v,onChange:r=>yt(r.target.value),onKeyDown:S,trailingAction:o.jsx(ht.Action,{onClick:()=>et(!ce),disabled:C||v,icon:ce?Oa:Na,"aria-label":ce?"Hide password":"Show password",sx:{color:"var(--fgColor-muted)"}})})]}),o.jsxs(g,{display:"flex",alignItems:"center",justifyContent:"space-between",mt:3,children:[o.jsx(W,{variant:"primary",disabled:C||v||!V||!re,onClick:xe,children:C?"Signing in…":"Sign In"}),gt&&o.jsx(dn,{as:"button",sx:{fontSize:1,cursor:v?"not-allowed":"pointer",background:"none",border:"none",opacity:v?.6:1},onClick:()=>{v||C||ze()},children:Oe})]})]}),M&&o.jsxs(o.Fragment,{children:[o.jsxs(ae,{required:!0,sx:{mb:3,mt:2},children:[o.jsx(ae.Label,{children:"MFA Code"}),o.jsx(ht,{autoFocus:!0,block:!0,placeholder:"Your MFA code",value:oe,disabled:C||v,onChange:r=>ot(r.target.value),onKeyDown:S})]}),o.jsx(W,{variant:"primary",block:!0,disabled:C||v||!oe.trim(),onClick:pe,sx:{maxWidth:Q,mx:"auto"},children:C?"Validating…":"Validate MFA Code"})]}),Fe&&o.jsx(D,{sx:{color:"danger.fg",fontSize:1,mt:3,display:"block"},children:Fe}),O&&o.jsxs(g,{mt:4,pt:4,textAlign:"center",borderTop:"1px solid",borderColor:"border.muted",children:[o.jsx(pt,{as:"h3",sx:{fontSize:2,mb:2},children:Bt}),o.jsx(D,{as:"p",sx:{color:"fg.muted",fontSize:1,mb:3},children:Y}),o.jsx(g,{display:"flex",justifyContent:"center",children:o.jsx(W,{variant:"primary",size:"large",leadingVisual:un,disabled:v||C,onClick:bt,children:mt})})]}),Je&&a&&o.jsxs(o.Fragment,{children:[o.jsxs(g,{display:"flex",alignItems:"center",gap:2,my:3,children:[o.jsx(g,{flex:1,height:"1px",bg:"border.default"}),o.jsx(D,{sx:{fontSize:0,color:"fg.muted"},children:"or"}),o.jsx(g,{flex:1,height:"1px",bg:"border.default"})]}),o.jsx(W,{block:!0,leadingVisual:Lt,disabled:v||C||le,onClick:()=>ne(!0),sx:{maxWidth:Q,mx:"auto"},children:"Sign in with an API Key"}),de&&o.jsx(g,{role:"dialog","aria-modal":"true","aria-labelledby":"signin-api-key-title",onKeyDown:r=>{r.key==="Escape"&&ue()},onClick:ue,position:"fixed",inset:0,zIndex:200,p:3,bg:"canvas.backdrop",display:"flex",alignItems:"center",justifyContent:"center",children:o.jsxs(g,{as:"form",onClick:r=>r.stopPropagation(),onSubmit:r=>{r.preventDefault(),vt()},width:"min(560px, 100%)",p:3,borderRadius:2,border:"1px solid",borderColor:"border.default",bg:"canvas.overlay",color:"fg.default",boxShadow:"shadow.large",children:[o.jsx(pt,{id:"signin-api-key-title",sx:{fontSize:2,mb:2},children:"Enter your API Key"}),o.jsxs(ae,{required:!0,children:[o.jsx(ae.Label,{children:"API Key"}),o.jsx(pn,{block:!0,required:!0,autoFocus:!0,placeholder:"Paste your API key here",value:P,onInput:r=>Ue(r.currentTarget.value),ref:Le})]}),o.jsxs(g,{mt:3,display:"flex",justifyContent:"flex-end",gap:2,children:[o.jsx(W,{type:"button",onClick:ue,children:"Cancel"}),o.jsx(W,{type:"submit",variant:"primary",disabled:!P.trim(),children:"Authenticate"})]})]})})]})]})]})};function Ba(e){const{agentId:a,instructions:i,model:s,frontendTools:l,inference:p,subagents:m,sharing:y,onSubagentEvent:u,modeEffect:K}=e;return{type:"browser-vercel-ai",endpoint:"",agentId:a,enableConfigQuery:!1,options:{instructions:i,model:s,frontendTools:l,inference:p,subagents:m,sharing:y,onSubagentEvent:u,modeEffect:K}}}const Ga={"tavily:0.0.1":vn},$={"crawl:0.0.1":kn,"events:0.0.1":bn,"github:0.0.1":xn,"text-summarizer:0.0.1":wn};function Re(e){return{id:e.id,name:e.name,description:e.description,version:e.version??"0.0.1",tags:e.tags,enabled:e.enabled,requiredEnvVars:e.requiredEnvVars}}const Po={"runtime-echo:0.0.1":yn},Ae={"jupyter-notebook:0.0.1":gn,"lexical-document:0.0.1":fn},Ha={id:"cog-crawler",version:"0.0.1",name:"Crawler Cog",description:"Researches the web and public repositories under the Web Research Frame: every finding rests on a source that was opened, is cited, and is checked before it is reported.",tags:["market-analyst","agent-worker","research","github","analysis","cog"],domain:"market-analyst",enabled:!0,model:"bedrock:us.anthropic.claude-sonnet-4-6",modelAdditionals:["alibaba:qwen-max"],mcpServers:[Ga["tavily:0.0.1"]],skills:[$["github:0.0.1"]?Re($["github:0.0.1"]):void 0,$["events:0.0.1"]?Re($["events:0.0.1"]):void 0,$["crawl:0.0.1"]?Re($["crawl:0.0.1"]):void 0].filter(Boolean),backendTools:[],frontendTools:[Ae["jupyter-notebook:0.0.1"],Ae["lexical-document:0.0.1"]],environmentName:"ai-agents-env",icon:"globe",emoji:"🌐",color:"#10B981",suggestions:[{text:"Search the web for recent news about AI agents",summary:"AI agent news"},{text:"Find trending open-source Python projects on GitHub",summary:"Trending Python projects"},{text:"Research best practices for building RAG applications",summary:"RAG best practices"},{text:"Compare popular JavaScript frameworks in 2024",summary:"JavaScript frameworks 2024"}],welcomeMessage:`Hi! I'm the Crawler Cog. I research the web and GitHub under the Web Research Frame: I open what I cite, I say which sources are primary, and I tell you where sources disagree.
|
|
29
29
|
`,welcomeNotebook:void 0,welcomeDocument:void 0,sandboxVariant:"jupyter-server",harness:"pydantic-ai",systemPrompt:`You are a web crawling and research assistant with access to Tavily search and GitHub tools. Use Tavily to search the web for current information and search GitHub repositories for relevant projects. Synthesize information from multiple sources and provide clear summaries with sources cited.
|
|
30
30
|
|
|
31
31
|
## Frames
|
|
@@ -281,8 +281,8 @@ You work under these Frames. They carry the context, the rules and the vocabular
|
|
|
281
281
|
- **finance-review** (expert, required): A person from Finance reviews the figures before the report is sent to the board.
|
|
282
282
|
|
|
283
283
|
Check your output against every Guard before you hand it over, and say which you could not satisfy.
|
|
284
|
-
`,systemPromptCodemodeAddons:"Compose focused execution steps, validate intermediate results, and summarize outcomes after each run. Prefer efficient, reproducible code paths.",goal:void 0,delegable:[{id:"data.transform"},{id:"data.analyse"},{id:"document.extract"},{id:"report.author"}],protocol:void 0,uiPlugin:void 0,trigger:void 0,modelConfig:void 0,mcpServerTools:void 0,guardrails:void 0,evals:void 0,codemode:{enabled:!0,token_reduction:"~80%",speedup:"~1.5x"},output:void 0,advanced:void 0,checkpoints:void 0,authorizationPolicy:void 0,notifications:void 0,memory:"ephemeral",preHooks:void 0,postHooks:void 0,toolHooks:void 0,parameters:void 0,subagents:void 0},Wa={id:"cog-crawler",version:"0.0.1",name:"Crawler Cog",description:"Researches the web and public repositories under the Web Research Frame: every finding rests on a source that was opened, is cited, and is checked before it is reported.",agent:"worker-crawler",frames:["web-research"],lineage:["datalayer","web-research"],kind:"context",enabled:!0,guards:[{id:"no-secrets",category:"policy-safety",description:"The output contains no credential, token, API key or password.",required:!0},{id:"sources-cited",category:"source-grounding",description:"Every factual claim in the output carries a link to the page or repository it was read on.",required:!0},{id:"source-supports-claim",category:"source-grounding",description:"Each cited page was opened, and what it says supports the claim made from it.",required:!0},{id:"recency-stated",category:"algorithmic",description:"Every source older than the recency window is marked with its date.",required:!1}],spec:Ha},Ka={id:"cog-customer-interviewer",version:"0.0.1",name:"Customer Interviewer Cog",description:"Conducts adaptive customer interviews under the Customer Research Frame: consent first, no leading question, and insights that each cite the interviewee's own words.",agent:"worker-customer-interviewer",frames:["customer-research"],lineage:["datalayer","customer-research"],kind:"context",enabled:!0,guards:[{id:"no-secrets",category:"policy-safety",description:"The output contains no credential, token, API key or password.",required:!0},{id:"no-leading-questions",category:"policy-safety",description:"No question in the interview suggests its own answer.",required:!0},{id:"insights-grounded",category:"source-grounding",description:"Every insight cites at least one verbatim from the interview that supports it.",required:!0},{id:"personal-data-removed",category:"policy-safety",description:"The insights name no person, employer or contact detail that consent does not cover.",required:!0}],spec:Da},Ya={id:"cog-sales-pipeline-board-report",version:"0.0.1",name:"Sales Pipeline Board Report Cog",description:"Builds the board's sales pipeline report under the Sales Pipeline and the Board Reporting Frames: figures computed by the definitions the sales organization uses, written the way the board reads.",agent:"worker-sales-pipeline-board-report",frames:["sales-pipeline","board-reporting"],lineage:["datalayer","sales-pipeline","board-reporting"],kind:"context",enabled:!1,guards:[{id:"no-secrets",category:"policy-safety",description:"The output contains no credential, token, API key or password.",required:!0},{id:"totals-reconcile",category:"algorithmic",description:"The totals by stage, by region and by segment each add up to the total pipeline.",required:!0},{id:"definitions-applied",category:"policy-safety",description:"Conversion, weighted pipeline and coverage are computed as this Frame defines them.",required:!0},{id:"data-quality-reported",category:"algorithmic",description:"Rows excluded from a figure, and why, are counted and reported.",required:!0},{id:"summary-first",category:"algorithmic",description:"The report opens with a summary of at most one page, with the key figures, the risks and the asks.",required:!0},{id:"forecast-labelled",category:"policy-safety",description:"Every forward-looking figure is labelled as a forecast and carries its assumption.",required:!0},{id:"finance-review",category:"expert",description:"A person from Finance reviews the figures before the report is sent to the board.",required:!0}],spec:Va},ko={"cog-crawler":Wa,"cog-customer-interviewer":Ka,"cog-sales-pipeline-board-report":Ya};function Ja(e){const a=e.lastIndexOf(":");return a>0&&e.slice(a+1).includes(".")?e.slice(0,a):e}function Qa(e){const a=Ja(e);return Object.prototype.hasOwnProperty.call(ko,a)?ko[a]:void 0}const So=Sn((e,a)=>({pending:void 0,suggest:(i,s)=>{const l=i.trim();l&&e({pending:{text:l,submit:s?.submit??!1,nonce:(a().pending?.nonce??0)+1}})},consume:()=>e({pending:void 0})}));function Xa({agentName:e,sandboxStillRuns:a=!1,temporary:i=!0,onSignedIn:s,onSignUp:l}){const{configuration:p}=Ro(),m=n.useCallback(y=>{Cn.getState().checkIAMToken(y),s?.()},[s]);return o.jsx(g,{height:"100%",minHeight:0,overflowY:"auto",bg:"canvas.default",px:4,py:4,children:o.jsxs(g,{maxWidth:440,mx:"auto",children:[o.jsxs(g,{display:"flex",alignItems:"center",justifyContent:"center",gap:2,color:"attention.fg",mb:2,children:[o.jsx(Lt,{size:20}),o.jsx(D,{sx:{fontSize:2,fontWeight:"semibold",color:"fg.default"},children:i?"This demo runs on a shared key":"Your key has expired"})]}),o.jsxs(D,{as:"p",sx:{fontSize:1,color:"fg.muted",textAlign:"center",mb:3},children:[i?`${e??"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.`:`${e??"The agent"} stopped because your session ran out.`,a?" Your notebook is still running in this page.":""]}),o.jsx(za,{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:m,onSignUp:l})]})})}const Za="https://r1.datalayer.run";function es(e=!0){const{configuration:a}=Ro(),i=qt(y=>y.token),s=a?.aiInferenceUrl||Za,l=
|
|
284
|
+
`,systemPromptCodemodeAddons:"Compose focused execution steps, validate intermediate results, and summarize outcomes after each run. Prefer efficient, reproducible code paths.",goal:void 0,delegable:[{id:"data.transform"},{id:"data.analyse"},{id:"document.extract"},{id:"report.author"}],protocol:void 0,uiPlugin:void 0,trigger:void 0,modelConfig:void 0,mcpServerTools:void 0,guardrails:void 0,evals:void 0,codemode:{enabled:!0,token_reduction:"~80%",speedup:"~1.5x"},output:void 0,advanced:void 0,checkpoints:void 0,authorizationPolicy:void 0,notifications:void 0,memory:"ephemeral",preHooks:void 0,postHooks:void 0,toolHooks:void 0,parameters:void 0,subagents:void 0},Wa={id:"cog-crawler",version:"0.0.1",name:"Crawler Cog",description:"Researches the web and public repositories under the Web Research Frame: every finding rests on a source that was opened, is cited, and is checked before it is reported.",agent:"worker-crawler",frames:["web-research"],lineage:["datalayer","web-research"],kind:"context",enabled:!0,guards:[{id:"no-secrets",category:"policy-safety",description:"The output contains no credential, token, API key or password.",required:!0},{id:"sources-cited",category:"source-grounding",description:"Every factual claim in the output carries a link to the page or repository it was read on.",required:!0},{id:"source-supports-claim",category:"source-grounding",description:"Each cited page was opened, and what it says supports the claim made from it.",required:!0},{id:"recency-stated",category:"algorithmic",description:"Every source older than the recency window is marked with its date.",required:!1}],spec:Ha},Ka={id:"cog-customer-interviewer",version:"0.0.1",name:"Customer Interviewer Cog",description:"Conducts adaptive customer interviews under the Customer Research Frame: consent first, no leading question, and insights that each cite the interviewee's own words.",agent:"worker-customer-interviewer",frames:["customer-research"],lineage:["datalayer","customer-research"],kind:"context",enabled:!0,guards:[{id:"no-secrets",category:"policy-safety",description:"The output contains no credential, token, API key or password.",required:!0},{id:"no-leading-questions",category:"policy-safety",description:"No question in the interview suggests its own answer.",required:!0},{id:"insights-grounded",category:"source-grounding",description:"Every insight cites at least one verbatim from the interview that supports it.",required:!0},{id:"personal-data-removed",category:"policy-safety",description:"The insights name no person, employer or contact detail that consent does not cover.",required:!0}],spec:Da},Ya={id:"cog-sales-pipeline-board-report",version:"0.0.1",name:"Sales Pipeline Board Report Cog",description:"Builds the board's sales pipeline report under the Sales Pipeline and the Board Reporting Frames: figures computed by the definitions the sales organization uses, written the way the board reads.",agent:"worker-sales-pipeline-board-report",frames:["sales-pipeline","board-reporting"],lineage:["datalayer","sales-pipeline","board-reporting"],kind:"context",enabled:!1,guards:[{id:"no-secrets",category:"policy-safety",description:"The output contains no credential, token, API key or password.",required:!0},{id:"totals-reconcile",category:"algorithmic",description:"The totals by stage, by region and by segment each add up to the total pipeline.",required:!0},{id:"definitions-applied",category:"policy-safety",description:"Conversion, weighted pipeline and coverage are computed as this Frame defines them.",required:!0},{id:"data-quality-reported",category:"algorithmic",description:"Rows excluded from a figure, and why, are counted and reported.",required:!0},{id:"summary-first",category:"algorithmic",description:"The report opens with a summary of at most one page, with the key figures, the risks and the asks.",required:!0},{id:"forecast-labelled",category:"policy-safety",description:"Every forward-looking figure is labelled as a forecast and carries its assumption.",required:!0},{id:"finance-review",category:"expert",description:"A person from Finance reviews the figures before the report is sent to the board.",required:!0}],spec:Va},ko={"cog-crawler":Wa,"cog-customer-interviewer":Ka,"cog-sales-pipeline-board-report":Ya};function Ja(e){const a=e.lastIndexOf(":");return a>0&&e.slice(a+1).includes(".")?e.slice(0,a):e}function Qa(e){const a=Ja(e);return Object.prototype.hasOwnProperty.call(ko,a)?ko[a]:void 0}const So=Sn((e,a)=>({pending:void 0,suggest:(i,s)=>{const l=i.trim();l&&e({pending:{text:l,submit:s?.submit??!1,nonce:(a().pending?.nonce??0)+1}})},consume:()=>e({pending:void 0})}));function Xa({agentName:e,sandboxStillRuns:a=!1,temporary:i=!0,onSignedIn:s,onSignUp:l}){const{configuration:p}=Ro(),m=n.useCallback(y=>{Cn.getState().checkIAMToken(y),s?.()},[s]);return o.jsx(g,{height:"100%",minHeight:0,overflowY:"auto",bg:"canvas.default",px:4,py:4,children:o.jsxs(g,{maxWidth:440,mx:"auto",children:[o.jsxs(g,{display:"flex",alignItems:"center",justifyContent:"center",gap:2,color:"attention.fg",mb:2,children:[o.jsx(Lt,{size:20}),o.jsx(D,{sx:{fontSize:2,fontWeight:"semibold",color:"fg.default"},children:i?"This demo runs on a shared key":"Your key has expired"})]}),o.jsxs(D,{as:"p",sx:{fontSize:1,color:"fg.muted",textAlign:"center",mb:3},children:[i?`${e??"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.`:`${e??"The agent"} stopped because your session ran out.`,a?" Your notebook is still running in this page.":""]}),o.jsx(za,{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:m,onSignUp:l})]})})}const Za="https://r1.datalayer.run";function es(e=!0){const{configuration:a}=Ro(),i=qt(y=>y.token),s=a?.aiInferenceUrl||Za,l=Tn(s,e&&!i),p=i||l.token,m=n.useMemo(()=>({inferenceUrl:s,token:p||void 0}),[s,p]);return{inference:m,needsSignIn:En(m),anonymous:l,inferenceUrl:s}}function Co(e){return Ao(e)??Qa(e)?.spec}function ts(e,a){const i=[e?.systemPrompt?.trim(),a?.trim()].filter(s=>!!s);return i.length>0?i.join(`
|
|
285
285
|
|
|
286
|
-
`):void 0}function os(e,a){return e&&!a?`There is no agent or Cog named “${e}” in this page, so it cannot answer here.`:void 0}const ns={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
|
|
286
|
+
`):void 0}function os(e,a){return e&&!a?`There is no agent or Cog named “${e}” in this page, so it cannot answer here.`:void 0}const ns={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 To(e){const a=e?.subagents;if(!a)return[];const i=(a.subagents??[]).map(s=>{const l=s.ref?Ao(s.ref):void 0;return{name:s.name,description:s.description||l?.description||s.name,instructions:s.instructions??l?.systemPrompt,model:s.model??l?.model??a.defaultModel,icon:l?.icon}});return a.includeGeneralPurpose?[...i,ns]:i}const _o="datalayer-loop-visitor",as=3e4;function zt(e){return typeof e=="string"&&/^[A-Za-z0-9-]{8,64}$/.test(e)}function ss(){try{const e=window.sessionStorage.getItem(_o);return zt(e)?e:""}catch{return""}}function rs(e){try{window.sessionStorage.setItem(_o,e)}catch{}}function is(e,a){return zt(a)?{app:e,visitor:a}:{app:e}}async function cs(e,a,i=ss(),s=fetch){const l=e.replace(/\/+$/,""),p=await s(`${l}/api/ai-inference/v1/anonymous/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(is(a,i))}),m=await p.json().catch(()=>({}));if(!p.ok||!m.token)throw new Error(m.detail||`A visitor's token was refused by ${l} (HTTP ${p.status}).`);zt(m.visitor)&&rs(m.visitor);const y=Math.max(6e4,(m.expires_in??300)*1e3);return{token:m.token,visitor:m.visitor??i,renewAt:Date.now()+y-as}}function ls(e){const[a,i]=n.useState({}),s=e?.app,l=e?.inferenceUrl;return n.useEffect(()=>{if(!s||!l){i({});return}let p=!1,m;const y=()=>{cs(l,s).then(u=>{p||(i({token:u.token}),m=setTimeout(y,Math.max(5e3,u.renewAt-Date.now())))}).catch(u=>{p||i({error:u instanceof Error?u.message:String(u)})})};return y(),()=>{p=!0,m&&clearTimeout(m)}},[s,l]),a}function ds(e){return e.replace(/^datalayer_/,"").replace(/_lexical$/,"")}function us(e){const a=ds(e);return/^executeCodeIn(Notebook|Document)$/.test(a)||/^(read|list)[A-Z]/.test(a)}function ps(e,a){return e.filter(i=>a?.has(i.name)||us(i.name))}function hs(e,a){const i=s=>a&&s.value.id===`${a}-tools`?0:s.value.id==="notebook-tools"?1:2;return e.map((s,l)=>({entry:s,index:l,rank:i(s)})).sort((s,l)=>s.rank-l.rank||s.index-l.index).map(s=>s.entry)}function ms(e,a,i){if(!i||!e.endsWith("-tools"))return!1;const s=e.slice(0,-6);return a.has(s)&&s!==i}const gs={type:"object",properties:{}};function fs(e,a){const i=new Set(e.toolset);return e.commands.filter(s=>i.has(s.name)).map(s=>({name:s.name,description:s.description,parameters:s.parameters??gs,location:"frontend",handler:async l=>{if(!a)throw new Error(`${s.name}: the ${e.plugin??e.id} plugin is not mounted on this page.`);const p=Object.keys(l??{}).length>0?l:void 0,m=await a.executeCommand(s.command,p);return m===void 0?{ok:!0,command:s.command,argument:p}:m}}))}function ys(e,a){return e.flatMap(i=>fs(i,a))}function vs(){const e=In(),a=La();return n.useMemo(()=>ys(a,e),[a,e])}const Eo={opening:"Opening your conversation…",notOpened:e=>`Your conversation could not be opened, so this is a new one: ${e}`};function bs(e){let a;for(const i of e.split(/\r?\n\r?\n/)){const s=i.split(/\r?\n/).filter(l=>l.startsWith("data:")).map(l=>l.slice(5).trim()).join("");if(s)try{const l=JSON.parse(s);l.type==="MESSAGES_SNAPSHOT"&&Array.isArray(l.messages)&&(a=l.messages)}catch{}}return a}async function Io(e){try{const a=await e.json();if(typeof a.detail=="string"&&a.detail)return a.detail}catch{}return`${e.status}`}async function ws({agentBaseUrl:e,agentId:a,uid:i,token:s,fetcher:l=fetch}){const p=`${e.replace(/\/+$/,"")}/api/v1/apps/sessions/${encodeURIComponent(i)}`,m=s?{Authorization:`Bearer ${s}`}:{},y=await l(`${p}/messages`,{headers:m});if(y.ok){const z=await y.json();return yo(z.messages)}if(y.status!==404)throw new Error(await Io(y));const u=await l(`${p}/resume`,{method:"POST",headers:{"Content-Type":"application/json",...m},body:JSON.stringify({agent:a})});if(!u.ok)throw new Error(await Io(u));const K=bs(await u.text());if(!K)throw new Error(`The runtime said nothing of session ${i}.`);return yo(K)}const xs="var(--theme-accent)";function Oo({face:e,size:a}){return typeof e=="string"?o.jsx(jn,{emoji:e,size:a,label:""}):o.jsx(o.Fragment,{children:e})}function ks({face:e,size:a,state:i}){const s=i==="thinking"||i==="working",l=i==="paused";return o.jsxs(g,{as:"span","aria-hidden":!0,"data-presence":i,position:"relative",display:"inline-flex",alignItems:"center",justifyContent:"center",width:a+8,height:a+8,flexShrink:0,fontSize:a,lineHeight:1,children:[o.jsx(g,{as:"span",position:"absolute",inset:0,borderRadius:"50%",boxShadow:l?"none":`0 0 0 2px ${xs}`,border:l?"2px dashed":"none",borderColor:"border.default",opacity:s||i==="waiting"||l?.9:0,transition:"opacity var(--theme-motion-status, 0ms) var(--theme-motion-easing, ease)",animation:s?"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}}}}),o.jsx(g,{as:"span",display:"inline-flex",opacity:l?.55:1,filter:l?"grayscale(0.6)":"none",transition:"opacity var(--theme-motion-status, 0ms) var(--theme-motion-easing, ease)",children:o.jsx(Oo,{face:e,size:a})})]})}function Ss({state:e}){return o.jsx(D,{role:"status","aria-live":"polite","data-presence-line":e,sx:{fontSize:0,color:e==="waiting"?"fg.default":"fg.muted",fontWeight:e==="waiting"?"semibold":"normal",whiteSpace:"nowrap",flexShrink:0},children:Rn[e]})}const Cs=$t(void 0),Ts=$t(""),Es=$t({}),X="",Is=1400,jo=parseInt(Aa["--loop-face-large"],10);function _s({workspace:e}){const a=An(),i=Pn(),s=n.useRef(null),{setViewControls:l}=e,[p,m]=n.useState(null),y=_n(),u=y.getConfig(On),K=u?.placeholder||a.placeholder,z=u?.defaultSurface??"notebook",Je=y.getConfig(Nn),[O,Z]=n.useState(X),v=n.useRef(!1),T=q(Mn),ee=q(Fn),Pe=q(Un),se=q(Ln)[0]?.value,Y=_t(se?.promptStance??Cs)??se?.prompt,mt=q(qn),_e=$n(mt[0]?.value),B=n.useRef(_e);B.current=_e;const J=n.useRef(""),Oe=q(zn),gt=n.useMemo(()=>Bn(()=>Oe.reduce((t,c)=>({...t,...c.value.extras.value}),{})),[Oe]),b=_t(Oe.length>0?gt:Es),Q=n.useRef(new Set),te=Gn(ja,e),Xe=!te.allowed,ft=Xe?te.reason??"Chat is unavailable for this sandbox":void 0,[N,V]=n.useState(!1),[fe,re]=n.useState(!1),[yt,Ze]=n.useState({open:!1,pendingApproval:!1}),ie=Hn(N,yt,u?.presence?.paused===!0),ce=u?.presence?.onPresence;n.useEffect(()=>{ce?.(ie),B.current?.setPresence(ie)},[ce,ie]);const et=n.useRef(u?.presence?.onSaying);et.current=u?.presence?.onSaying;const C=n.useRef({answering:!1}),ye=n.useCallback(t=>{s.current=t,re(!!t)},[]),le=n.useCallback(t=>{const{open:c,pendingApproval:d}=Dn(t);Ze(ge=>ge.open===c&&ge.pendingApproval===d?ge:{open:c,pendingApproval:d});const x={saying:Wn(t),answering:Vn(t)},h=C.current;(h.saying?.id!==x.saying?.id||h.saying?.text!==x.saying?.text||h.answering!==x.answering)&&(C.current=x,et.current?.(x));const G=B.current;if(!G)return;G.items(t);const H=new Set(["complete","completed","done","error","failed","cancelled","canceled","rejected","denied","stopped"]),Ee={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 j;for(let ge=t.length-1;ge>=0;ge-=1){const ut=t[ge];if(typeof ut.toolName=="string"&&ut.toolCallId){H.has(String(ut.status).toLowerCase())||(j=ut);break}}if(!j){G.activity(void 0);return}const At=j.toolName.toLowerCase().replace(/^datalayer_/,"").replace(/_lexical$/,"").replace(/[^a-z]/g,""),sn=Ee[At]??`using ${j.toolName}`;G.activity(`${J.current||"The agent"} is ${sn}…`)},[]),Ne=n.useRef(b);Ne.current=b;const Me=n.useCallback(t=>{Bo(t),B.current?.usage(t),Ne.current.onUsage?.(t)},[]),tt=n.useCallback(t=>{V(t),t||B.current?.end("done")},[]),M=n.useCallback(t=>{const c=B.current;if(!c)return;let d=-1;for(let h=t.length-1;h>=0;h-=1)if(t[h].role==="user"){d=h;break}const x=t.slice(d+1).filter(h=>h.role==="assistant").map(Kn).filter(h=>h.trim().length>0).join(`
|
|
287
287
|
|
|
288
|
-
`);c.assistant(w)},[]),be=n.useRef([]),oe=n.useRef(!1),ot=q(Yn),ve=n.useRef(ot);ve.current=ot;const we=n.useCallback((t,c)=>{const d=Jn(ve.current.map(G=>G.value),c),w=d?.loop;if(oe.current&&w?.files&&w.files.length>0)return"A file is given to an application running on a runtime: run it on Datalayer or on your machine to give it one.";B.current?.begin(t,s.current?.thread());const h=s.current?.send;if(!h){be.current.push([t,d]);return}h(t,d)},[]);n.useEffect(()=>{l(fe?{busy:N,stop:s.current?.stop,newChat:s.current?.newChat,send:we}:null)},[N,fe,l,we]),n.useEffect(()=>()=>l(null),[l]),n.useEffect(()=>e.prompts.subscribe(we),[e.prompts,we]),n.useEffect(()=>{if(!fe||be.current.length===0)return;const t=be.current.splice(0,be.current.length);for(const[c,d]of t)s.current?.send(c,d)},[fe]);const Fe=n.useRef(!1),F=n.useCallback(async t=>{Fe.current||(Fe.current=!0,Je?.firstPromptHook?.()),m(null);const c=await e.submit(t);if(!c.handled){m(c.reason??null);return}It(""),c.result?.content&&m(c.result.content)},[e,Je?.firstPromptHook]),k=n.useMemo(()=>E.find(t=>t.value.surfaceId===O)?.value,[E,O]),de=n.useCallback(t=>{b.current=!0,Z(t)},[]);n.useEffect(()=>Qn(de),[de]),n.useEffect(()=>{Xn(E.map(t=>t.value.surfaceId))},[E]),n.useEffect(()=>{Zn(O&&O!==X?O:Pa)},[O]);const ne=n.useMemo(()=>z===X||z==="none"?void 0:E.find(t=>t.value.surfaceId===z),[E,z]);n.useEffect(()=>{b.current||!ne||Ye(ne.value,e)&&Z(z)},[ne,e,z]);const[P,Ue]=n.useState(null),Le=n.useRef(null),qe=u?.fullScreenTopOffset??0,{fullScreen:_,usingApi:$e,toggle:ue,topOffsetPx:bt}=ea(Le,{forceOverlay:!!qe,topOffset:qe}),[vt,ze]=n.useState(!1),xe=n.useRef(!1);n.useEffect(()=>{!N||xe.current||_||(xe.current=!0,ze(!0))},[N,_]),n.useEffect(()=>{_&&ze(!1)},[_]),n.useEffect(()=>{k&&!Ye(k,e)&&(Ue(k.surfaceId),Z(X))},[k,e]);const pe=n.useMemo(()=>{if(P)return E.find(t=>t.value.surfaceId===P)?.value;if(!b.current&&O===X)return ne?.value},[E,P,O,ne]);n.useEffect(()=>{if(!P||O!==X)return;const t=E.find(c=>c.value.surfaceId===P);t&&Ye(t.value,e)&&(Ue(null),Z(P))},[E,O,P,e]);const S=e.agentId?.trim()||"default",j=ta(e.sandbox.target??"local");oe.current=j;const r=oa(),v=_t(r?.selected??Es),f=r?.members.find(t=>t.id===v),U=q(na)[0]?.value,ke=U?.specId,T=Co(f?.specId??S)??(ke?Co(ke):void 0),he=f?void 0:U,Be=j&&!f?os(ke,T):void 0;J.current=f?.name??T?.name??S;const Ge=q(aa),He=x.hiddenOpeners,Gt=x.hideOpeners,wt=x.openers,xt=n.useMemo(()=>{if(Gt)return[];const t=new Set(He??[]),c=I=>t.size===0?I:I.filter(At=>!t.has(At.text));if(wt)return c(wt);const d=Ge.flatMap(I=>I.value.suggestions);if(d.length>0)return c(d);const w=c(T?.suggestions??[]),h=c(r?.team.suggestions??[]);if(h.length===0)return w;const G=new Set(h.map(I=>I.text)),H=r?.team.name??"Team",Te=f?.name??T?.name??S;return[...h.map(I=>({...I,group:H})),...w.filter(I=>!G.has(I.text)).map(I=>({...I,group:Te}))]},[Ge,r,T,f,S,He,Gt,wt]),nt=n.useMemo(()=>xt.map(t=>({title:t.summary??t.text,message:t.message??t.text,group:t.group})),[xt]),kt=Ie(T?.icon),L=u?.presence,No=Ie(r?.team.icon),Ht=q(sa),at=n.useMemo(()=>{const t=[],c=new Map,d=new Set,w=new Set(E.map(h=>h.value.surfaceId));for(const h of hs(Ht,k?.surfaceId)){if(ms(h.value.id,w,k?.surfaceId))continue;let G;try{G=h.value.tools(e)}catch(H){console.warn(`[loop] frontend tools from '${h.plugin}' failed:`,H);continue}for(const H of G){const Te=c.get(H.name);if(Te){console.warn(`[loop] frontend tool '${H.name}' from '${h.plugin}' is shadowed by the one from '${Te}'.`);continue}c.set(H.name,h.plugin),t.push(H),h.value.chatView&&d.add(H.name)}}for(const h of x.frontendTools??[])c.has(h.name)||(c.set(h.name,"chat-extras"),t.push(h),d.add(h.name));return k?t:ps(t,d)},[Ht,e.surfaceId,e.agentId,x.frontendTools,k?.surfaceId,E]),St=bs(),st=n.useMemo(()=>{if(St.length===0)return at;const t=new Set(at.map(c=>c.name));return[...at,...St.filter(c=>!t.has(c.name))]},[at,St]),R=ra(e.sandbox,e.serverUrl),Dt=q(ia),Mo=n.useMemo(()=>Dt.filter(t=>t.value.composer).map(t=>({name:t.value.name,description:t.value.description})),[Dt]),Fo=n.useMemo(()=>{if(!r||!f)return Eo(T).map(d=>({name:d.name,description:d.description,icon:Ie(d.icon)}));const t=r.members.map(d=>({name:d.name,description:d.description,emoji:d.emoji,icon:Ie(d.icon),disabled:d.id===f.id,disabledReason:d.id===f.id?`You are already talking to ${d.name}`:void 0})),c=bo(r.team,f.id).filter(d=>!r.members.some(w=>w.name===d.name)).map(d=>({name:d.name,description:d.description,icon:Ie(d.icon)}));return[...t,...c]},[r,f,T]),{inference:Vt,anonymous:Uo}=es(j),Lo=qt(t=>t.user),Ct=j&&Uo.status==="expired",Wt=!Lo,Et=ca(),Tt=R===void 0?la(e.sandbox,a):void 0,rt=Xe||Ct||!!Be||!!Tt||Et.disabled,Kt=Ct?Wt?a.demoKeyExpired:a.keyExpired:Be??Tt??ft??(Et.disabled?Et.disableReason:void 0),[Yt,It]=n.useState(""),[qo,Jt]=n.useState(),it=qo??he?.model??T?.model??e.model??"",Se=da(),Qt=n.useRef(Se),Xt=n.useRef(v),Zt=n.useRef(Se);Zt.current=Se,n.useEffect(()=>{Xt.current!==v&&(Xt.current=v,Qt.current=Zt.current,Jt(void 0))},[v]);const $o=Se&&Se!==Qt.current?Se:null,[zo,Bo]=n.useState(),Go=$o??zo??null,Ho=Ot(je.inpromptMenu),Do=Ot(je.promptAction),Vo=Ot(je.chatHeader),Wo=n.useMemo(()=>r?.members.map(t=>({id:t.id,name:t.name,description:t.description,icon:Ie(t.icon)}))??[],[r]),me=So(t=>t.pending),[eo,Ko]=n.useState(0);n.useEffect(()=>ua(()=>Ko(t=>t+1)),[]),n.useEffect(()=>{me&&(It(me.text),So.getState().consume(),me.submit&&F(me.text))},[me]);const De=!!he?.createPayload?.app_spec,Yo=qt(t=>t.token),to=y.getConfig(vo)?.datalayerVisitors,Jo=ls(to),Qo=y.getConfig(vo)?.embedToken,Ve=to?Jo.token:Qo||Yo,A=u?.thread,[Ce,oo]=n.useState(null),Xo=!!(A?.fromRuntime&&Ce?.given!==A.id);n.useEffect(()=>{if(!A?.fromRuntime||!De||!R)return;let t=!0;return(async()=>{let c="";for(let d=0;d<4&&t;d+=1)try{const w=await ws({agentBaseUrl:R,agentId:S,uid:A.id,token:Ve});t&&oo({given:A.id,thread:{...A,fromRuntime:!1,messages:w}});return}catch(w){c=w instanceof Error?w.message:String(w),await new Promise(h=>setTimeout(h,1500))}t&&oo({given:A.id,thread:{id:pa(),messages:[],onStarted:A.onStarted},said:To.notOpened(c)})})(),()=>{t=!1}},[A?.id,A?.fromRuntime,De,R,S,Ve]);const no=A?.fromRuntime?Ce?.given===A.id?Ce.thread:void 0:A,jt=n.useMemo(()=>j?Ba({agentId:f?.specId??S,instructions:ts(T,he?.instructions),model:it||void 0,inference:Vt,frontendTools:st,subagents:r&&f?bo(r.team,f.id):Eo(T),sharing:r?.sharing,onSubagentEvent:t=>Ra.getState().appendSubagentEvent(t),modeEffect:he?.modeEffect}):R!==void 0?{type:"ag-ui",endpoint:De?`${R}/api/v1/apps/agents/${encodeURIComponent(S)}/ag-ui/`:`${R}/api/v1/ag-ui/${S}/`,...De&&Ve?{authToken:Ve}:{},agentId:S,configEndpoint:`${R}/api/v1/configure`,enableConfigQuery:!0}:void 0,[S,j,Vt,f,st,r,T,he,it,R,De,Ve]),ct=ha(!j,jt?.type==="ag-ui"?jt.configEndpoint:void 0,void 0,S),We=ma(),lt=ga(S),[ao,so]=n.useState(void 0),[Zo,en]=n.useState(void 0);n.useEffect(()=>{if(j||R===void 0)return;let t=!1;return fetch(`${R}/api/v1/configure/models?agent_id=${encodeURIComponent(S)}`).then(c=>c.ok?c.json():null).then(c=>{t||(so(c?fa(c):[]),en(c?ya(c):void 0))}).catch(()=>{t||so([])}),()=>{t=!0}},[R,S,j]);const tn=n.useMemo(()=>ba(ao,()=>Object.values(va).filter(t=>t.available&&wa(t)).map(t=>({id:t.id,name:t.name,provider:t.provider}))),[ao]),ro=n.useMemo(()=>{const t=ct.data?.builtinTools??[],c=new Set(t.map(d=>d.name));return{runtime:t,frontend:st.filter(d=>!c.has(d.name)).map(d=>({id:d.name,name:d.name}))}},[ct.data?.builtinTools,st]),io=n.useMemo(()=>new Set((We.data?.skills??[]).filter(t=>t.status==="enabled"||t.status==="loaded").map(t=>t.id)),[We.data]),on=n.useCallback(async t=>{Jt(t),!(j||R===void 0)&&await fetch(`${R}/api/v1/configure/inference/provider`,{method:"PUT",headers:{"content-type":"application/json"},body:JSON.stringify({model:t})}).catch(()=>{})},[R,j]),co=u?.promptPlacement==="bottom-chat",nn=u?.promptPlacement==="floating",Ee=u?.promptPlacement==="top",Ke=u?.hidePrompt===!0||x.hidePrompt===!0,an={onSend:()=>{F(Yt)},input:Yt,setInput:It,focusTrigger:me||eo?(me?.nonce??0)+eo:void 0,placement:nn||Y==="floating"||Y==="floating-top"||Y==="floating-bottom"?"floating":"docked",floatingAnchor:Y==="floating-top"?"top":"bottom",isLoading:N,onStop:()=>e.viewControls.stop?.(),placeholder:Kt??K,typingSuggestions:xt.map(t=>t.text),suggestions:nt,disableInputPrompt:rt,connectionConfirmed:!rt,padding:Ee||Y==="floating-top"||Y==="floating-bottom"||Y==="docked-top"?2:3,promptVariant:"lexical",autoFocus:u?.autoFocusPrompt??!0,mentionableAgents:Fo,promptCommands:Mo,headerContent:Ho.length>0?o.jsx(Nt,{slot:je.inpromptMenu,props:{workspace:e}}):void 0,footerExtras:Do.length>0?o.jsx(Nt,{slot:je.promptAction,props:{workspace:e}}):void 0,showAgentsMenu:!L,showInlineAgentsMenu:!1,agents:Wo,selectedAgentId:v,onSelectAgent:t=>r?.select(t),showTokenUsage:x.showTokenUsage??u?.showTokenUsage??!0,showContextRing:!0,agentUsage:Go??void 0,showModelSelector:!L,models:tn,decisions:Zo,selectedModel:it,onModelSelect:t=>{on(t)},showToolsMenu:!L,availableTools:ro.runtime,availableFrontendTools:ro.frontend,mcpServers:ct.data?.mcpServers??[],mcpStatusData:x.mcpStatusData??void 0,showSkillsMenu:!L,skills:We.data?.skills??[],skillsLoading:We.isLoading,enabledSkills:io,onToggleSkill:t=>io.has(t)?lt.disableSkill(t):lt.enableSkill(t),onToggleAllSkills:(t,c)=>t.forEach(d=>c?lt.enableSkill(d):lt.disableSkill(d)),codemodeEnabled:x.codemodeEnabled??!1,onToggleCodemode:x.onToggleCodemode,isA2AProtocol:!1,hasConfigData:!!ct.data,hasSkillsData:!!We.data},lo=ee[0]?.value.Component,Rt=Pe[0]?.value.Component,dt=lo?o.jsx(lo,{workspace:e,composer:an}):null,uo=E.length>0&&u?.showSurfaceSelector!==!1?o.jsx(js,{surfaces:E.map(t=>t.value),active:k?.surfaceId??pe?.surfaceId??X,onChange:de,workspace:e}):null,po=o.jsxs(o.Fragment,{children:[E.map(t=>{const c=t.value,d=k?.surfaceId===c.surfaceId;return d||Q.current.has(c.surfaceId)||Ye(c,e)?(Q.current.add(c.surfaceId),o.jsx(g,{sx:d?{flex:"1 1 0",minWidth:0,minHeight:0}:{position:"absolute",inset:0,visibility:"hidden",pointerEvents:"none",zIndex:-1},children:o.jsx(xa,{load:c.load,props:{surfaceId:c.surfaceId,workspace:e},fallback:o.jsxs(Ut,{children:["Loading ",c.title,"…"]}),errorFallback:h=>o.jsxs(Ut,{children:[c.title," failed to load: ",h.message]})})},c.surfaceId)):null}),!k&&pe?o.jsx(g,{flex:"1 1 0",minWidth:0,minHeight:0,children:o.jsxs(Ut,{children:["Starting ",pe.title,"…"]})}):null]}),ho=o.jsx(o.Fragment,{children:o.jsxs(g,{flex:Ee&&k?"0 0 34%":"1 1 0",maxWidth:Ee&&k?460:void 0,minWidth:0,minHeight:0,display:"flex",flexDirection:"column",borderLeft:k?"1px solid":void 0,borderColor:"border.default",position:"relative",children:[x.errorBanner?o.jsx(g,{flexShrink:0,px:3,py:2,fontSize:1,borderBottom:"1px solid",bg:x.errorBanner.variant==="warning"?"attention.subtle":"danger.subtle",color:x.errorBanner.variant==="warning"?"attention.fg":"danger.fg",borderColor:x.errorBanner.variant==="warning"?"attention.muted":"danger.muted",children:x.errorBanner.message}):null,Ce?.said&&Ce.given===A?.id?o.jsx(D,{as:"p",role:"status",sx:{m:0,px:3,py:2,fontSize:1,color:"fg.muted"},children:Ce.said}):null,o.jsx(g,{flex:"1 1 auto",minHeight:0,display:"flex",children:Xo?o.jsx(D,{as:"p",role:"status",sx:{m:0,p:3,fontSize:1,color:"fg.muted"},children:To.opening}):o.jsx(ka,{themeVariant:u?.themeVariant,themeOverrides:u?.themeOverrides,colorMode:u?.colorMode,thread:no,disabled:rt,disableReason:Kt,protocol:jt,initialModel:it||void 0,title:L?.name??f?.name??T?.name??S,description:L?.welcome??T?.description,brandIcon:L?.face?o.jsx(ks,{face:L.face,size:20,state:ie}):o.jsx(kt,{size:20}),headerContent:L&&!Tt?o.jsx(Ss,{state:ie}):void 0,emptyState:{icon:L?.face?o.jsx("span",{"aria-hidden":!0,style:{fontSize:jo,lineHeight:1},children:o.jsx(Oo,{face:L.face,size:jo})}):o.jsx(kt,{size:48}),title:L?.name??f?.name??T?.name??S,...r&&f?{sections:[{group:r.team.name,icon:o.jsx(No,{size:48}),title:r.team.name,subtitle:r.team.description},{group:f.name,icon:o.jsx(kt,{size:32}),title:f.name,subtitle:T?.description}]}:null},suggestions:Ee||se||u?.suggestionLabels===!1?[]:nt,showHeader:!u?.hideHeader&&!!Rt,headerButtons:{showNewChat:u?.headerButtons?.newChat??!1,showClear:u?.headerButtons?.clear??!1},renderHeader:Rt?t=>o.jsx(Rt,{workspace:e,header:t}):void 0,showInformation:!0,headerActions:o.jsxs(g,{display:"inline-flex",alignItems:"center",gap:2,children:[e.chatHeaderActions,Vo.length>0?o.jsx(Nt,{slot:je.chatHeader,props:{workspace:e}}):null,o.jsx(Sa,{icon:_?Ca:Ea,"aria-label":_?"Exit full screen":"Enter full screen",variant:"invisible",size:"small",onClick:()=>{ze(!1),ue()},sx:vt?{"@keyframes dla-fullscreen-hint":{"0%, 100%":{opacity:1},"50%":{opacity:.4}},"&&":{bg:`color-mix(in srgb, ${i.primary} 16%, transparent)`,boxShadow:`inset 0 0 0 1.5px ${i.primary}`,animation:`dla-fullscreen-hint ${Is}ms ease-in-out infinite`},"@media (prefers-reduced-motion: reduce)":{"&&":{animation:"none"}}}:void 0})]}),showInput:!1,onSendReady:ye,notebookToolSurfacesId:k?void 0:e.surfaceId,renderToolResult:x.renderToolResult,showTurnFooter:x.showTokenUsage??u?.showTokenUsage??!0,onContextSnapshot:Me,onLoadingChange:tt,onItemsChange:M,onDisplayItemsChange:le,enableStreaming:!0},no?.id)}),co&&!Ke?dt:null]})}),mo=u?.suggestionLabels!==!1&&nt.length>0?o.jsx(g,{"aria-label":a.suggestedPrompts,display:"flex",flexWrap:"wrap",gap:2,px:2,pb:"6px",children:nt.map(t=>o.jsx(g,{as:"button",type:"button",title:t.message,disabled:N||rt,onClick:()=>{F(t.message)},appearance:"none",font:"inherit",fontSize:0,fontWeight:"semibold",lineHeight:1.25,px:"10px",py:"5px",width:wo,flex:`0 0 ${wo}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:o.jsx(Ta,{title:t.title,maxWidth:"100%",sx:{minWidth:0},children:t.title})},t.title))}):null,go=p?o.jsx(g,{flex:"0 0 auto",px:3,py:2,borderTop:"1px solid",borderColor:"border.default",bg:"canvas.subtle",fontSize:1,maxHeight:"40%",overflowY:"auto",children:p}):null;return o.jsxs(g,{ref:Le,sx:{height:"100%",minHeight:0,display:"flex",flexDirection:"column",position:"relative",..._?{bg:"canvas.default"}:null,..._&&!$e.current?{position:"fixed",top:bt,right:0,bottom:0,left:0,height:"auto",zIndex:1e3}:null},children:[se?o.jsx(se.Component,{workspace:e,editors:po,hasEditor:!!k,transcript:ho,prompt:Ke?null:dt,chips:Ke?null:mo,picker:uo,transient:go}):o.jsxs(o.Fragment,{children:[Ee&&!Ke?o.jsxs(g,{flex:"0 0 auto",borderBottom:"1px solid",borderColor:"border.default",children:[dt,mo]}):null,uo,o.jsxs(g,{flex:"1 1 auto",minHeight:0,display:"flex",position:"relative",children:[po,ho]}),go,co||Ke||Ee?null:dt]}),Ct?o.jsx(g,{position:"absolute",inset:0,zIndex:5,bg:"canvas.default",display:"flex",flexDirection:"column",minHeight:0,children:o.jsx(Xa,{agentName:f?.name??T?.name,sandboxStillRuns:j,temporary:Wt,onSignedIn:()=>Ia.getState().clear()})}):null]})}function js({surfaces:e,active:a,onChange:i,workspace:s}){const l=[...e].sort((p,m)=>(p.order??100)-(m.order??100));return o.jsxs(g,{flex:"0 0 auto",display:"flex",alignItems:"center",gap:2,px:3,py:2,borderBottom:"1px solid",borderColor:"border.default",children:[o.jsx(D,{sx:{fontSize:0,color:"fg.muted"},children:"Beside the chat"}),o.jsxs(Mt,{"aria-label":"Editor beside the chat",size:"small",children:[o.jsx(Mt.Button,{selected:a===X,onClick:()=>i(X),children:"Chat"}),l.map(p=>{const m=Ye(p,s),y=m?void 0:p.unavailableReason?.(s)??"Not available right now";return o.jsx(Mt.Button,{selected:a===p.surfaceId,"aria-disabled":!m,title:y??p.title,leadingIcon:p.icon,onClick:()=>{m&&i(p.surfaceId)},children:p.title},p.surfaceId)})]})]})}function Ut({children:e}){return o.jsx(g,{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"fg.muted",fontSize:1,px:3,textAlign:"center",children:e})}export{_s as default};
|
|
288
|
+
`);c.assistant(x)},[]),ve=n.useRef([]),oe=n.useRef(!1),ot=q(Yn),be=n.useRef(ot);be.current=ot;const we=n.useCallback((t,c)=>{const d=Jn(be.current.map(G=>G.value),c),x=d?.loop;if(oe.current&&x?.files&&x.files.length>0)return"A file is given to an application running on a runtime: run it on Datalayer or on your machine to give it one.";B.current?.begin(t,s.current?.thread());const h=s.current?.send;if(!h){ve.current.push([t,d]);return}h(t,d)},[]);n.useEffect(()=>{l(fe?{busy:N,stop:s.current?.stop,newChat:s.current?.newChat,send:we}:null)},[N,fe,l,we]),n.useEffect(()=>()=>l(null),[l]),n.useEffect(()=>e.prompts.subscribe(we),[e.prompts,we]),n.useEffect(()=>{if(!fe||ve.current.length===0)return;const t=ve.current.splice(0,ve.current.length);for(const[c,d]of t)s.current?.send(c,d)},[fe]);const Fe=n.useRef(!1),F=n.useCallback(async t=>{Fe.current||(Fe.current=!0,Je?.firstPromptHook?.()),m(null);const c=await e.submit(t);if(!c.handled){m(c.reason??null);return}It(""),c.result?.content&&m(c.result.content)},[e,Je?.firstPromptHook]),k=n.useMemo(()=>T.find(t=>t.value.surfaceId===O)?.value,[T,O]),de=n.useCallback(t=>{v.current=!0,Z(t)},[]);n.useEffect(()=>Qn(de),[de]),n.useEffect(()=>{Xn(T.map(t=>t.value.surfaceId))},[T]),n.useEffect(()=>{Zn(O&&O!==X?O:Pa)},[O]);const ne=n.useMemo(()=>z===X||z==="none"?void 0:T.find(t=>t.value.surfaceId===z),[T,z]);n.useEffect(()=>{v.current||!ne||Ye(ne.value,e)&&Z(z)},[ne,e,z]);const[P,Ue]=n.useState(null),Le=n.useRef(null),qe=u?.fullScreenTopOffset??0,{fullScreen:_,usingApi:$e,toggle:ue,topOffsetPx:vt}=ea(Le,{forceOverlay:!!qe,topOffset:qe}),[bt,ze]=n.useState(!1),xe=n.useRef(!1);n.useEffect(()=>{!N||xe.current||_||(xe.current=!0,ze(!0))},[N,_]),n.useEffect(()=>{_&&ze(!1)},[_]),n.useEffect(()=>{k&&!Ye(k,e)&&(Ue(k.surfaceId),Z(X))},[k,e]);const pe=n.useMemo(()=>{if(P)return T.find(t=>t.value.surfaceId===P)?.value;if(!v.current&&O===X)return ne?.value},[T,P,O,ne]);n.useEffect(()=>{if(!P||O!==X)return;const t=T.find(c=>c.value.surfaceId===P);t&&Ye(t.value,e)&&(Ue(null),Z(P))},[T,O,P,e]);const S=e.agentId?.trim()||"default",I=ta(e.sandbox.target??"local");oe.current=I;const r=oa(),w=_t(r?.selected??Ts),f=r?.members.find(t=>t.id===w),U=q(na)[0]?.value,ke=U?.specId,E=Co(f?.specId??S)??(ke?Co(ke):void 0),he=f?void 0:U,Be=I&&!f?os(ke,E):void 0;J.current=f?.name??E?.name??S;const Ge=q(aa),He=b.hiddenOpeners,Gt=b.hideOpeners,wt=b.openers,xt=n.useMemo(()=>{if(Gt)return[];const t=new Set(He??[]),c=j=>t.size===0?j:j.filter(At=>!t.has(At.text));if(wt)return c(wt);const d=Ge.flatMap(j=>j.value.suggestions);if(d.length>0)return c(d);const x=c(E?.suggestions??[]),h=c(r?.team.suggestions??[]);if(h.length===0)return x;const G=new Set(h.map(j=>j.text)),H=r?.team.name??"Team",Ee=f?.name??E?.name??S;return[...h.map(j=>({...j,group:H})),...x.filter(j=>!G.has(j.text)).map(j=>({...j,group:Ee}))]},[Ge,r,E,f,S,He,Gt,wt]),nt=n.useMemo(()=>xt.map(t=>({title:t.summary??t.text,message:t.message??t.text,group:t.group})),[xt]),kt=Ie(E?.icon),L=u?.presence,No=Ie(r?.team.icon),Ht=q(sa),at=n.useMemo(()=>{const t=[],c=new Map,d=new Set,x=new Set(T.map(h=>h.value.surfaceId));for(const h of hs(Ht,k?.surfaceId)){if(ms(h.value.id,x,k?.surfaceId))continue;let G;try{G=h.value.tools(e)}catch(H){console.warn(`[loop] frontend tools from '${h.plugin}' failed:`,H);continue}for(const H of G){const Ee=c.get(H.name);if(Ee){console.warn(`[loop] frontend tool '${H.name}' from '${h.plugin}' is shadowed by the one from '${Ee}'.`);continue}c.set(H.name,h.plugin),t.push(H),h.value.chatView&&d.add(H.name)}}for(const h of b.frontendTools??[])c.has(h.name)||(c.set(h.name,"chat-extras"),t.push(h),d.add(h.name));return k?t:ps(t,d)},[Ht,e.surfaceId,e.agentId,b.frontendTools,k?.surfaceId,T]),St=vs(),st=n.useMemo(()=>{if(St.length===0)return at;const t=new Set(at.map(c=>c.name));return[...at,...St.filter(c=>!t.has(c.name))]},[at,St]),R=ra(e.sandbox,e.serverUrl),Dt=q(ia),Mo=n.useMemo(()=>Dt.filter(t=>t.value.composer).map(t=>({name:t.value.name,description:t.value.description})),[Dt]),Fo=n.useMemo(()=>{if(!r||!f)return To(E).map(d=>({name:d.name,description:d.description,icon:Ie(d.icon)}));const t=r.members.map(d=>({name:d.name,description:d.description,emoji:d.emoji,icon:Ie(d.icon),disabled:d.id===f.id,disabledReason:d.id===f.id?`You are already talking to ${d.name}`:void 0})),c=vo(r.team,f.id).filter(d=>!r.members.some(x=>x.name===d.name)).map(d=>({name:d.name,description:d.description,icon:Ie(d.icon)}));return[...t,...c]},[r,f,E]),{inference:Vt,anonymous:Uo}=es(I),Lo=qt(t=>t.user),Ct=I&&Uo.status==="expired",Wt=!Lo,Tt=ca(),Et=R===void 0?la(e.sandbox,a):void 0,rt=Xe||Ct||!!Be||!!Et||Tt.disabled,Kt=Ct?Wt?a.demoKeyExpired:a.keyExpired:Be??Et??ft??(Tt.disabled?Tt.disableReason:void 0),[Yt,It]=n.useState(""),[qo,Jt]=n.useState(),it=qo??he?.model??E?.model??e.model??"",Se=da(),Qt=n.useRef(Se),Xt=n.useRef(w),Zt=n.useRef(Se);Zt.current=Se,n.useEffect(()=>{Xt.current!==w&&(Xt.current=w,Qt.current=Zt.current,Jt(void 0))},[w]);const $o=Se&&Se!==Qt.current?Se:null,[zo,Bo]=n.useState(),Go=$o??zo??null,Ho=Ot(je.inpromptMenu),Do=Ot(je.promptAction),Vo=Ot(je.chatHeader),Wo=n.useMemo(()=>r?.members.map(t=>({id:t.id,name:t.name,description:t.description,icon:Ie(t.icon)}))??[],[r]),me=So(t=>t.pending),[eo,Ko]=n.useState(0);n.useEffect(()=>ua(()=>Ko(t=>t+1)),[]),n.useEffect(()=>{me&&(It(me.text),So.getState().consume(),me.submit&&F(me.text))},[me]);const De=!!he?.createPayload?.app_spec,Yo=qt(t=>t.token),to=y.getConfig(bo)?.datalayerVisitors,Jo=ls(to),Qo=y.getConfig(bo)?.embedToken,Ve=to?Jo.token:Qo||Yo,A=u?.thread,[Ce,oo]=n.useState(null),Xo=!!(A?.fromRuntime&&Ce?.given!==A.id);n.useEffect(()=>{if(!A?.fromRuntime||!De||!R)return;let t=!0;return(async()=>{let c="";for(let d=0;d<4&&t;d+=1)try{const x=await ws({agentBaseUrl:R,agentId:S,uid:A.id,token:Ve});t&&oo({given:A.id,thread:{...A,fromRuntime:!1,messages:x}});return}catch(x){c=x instanceof Error?x.message:String(x),await new Promise(h=>setTimeout(h,1500))}t&&oo({given:A.id,thread:{id:pa(),messages:[],onStarted:A.onStarted},said:Eo.notOpened(c)})})(),()=>{t=!1}},[A?.id,A?.fromRuntime,De,R,S,Ve]);const no=A?.fromRuntime?Ce?.given===A.id?Ce.thread:void 0:A,jt=n.useMemo(()=>I?Ba({agentId:f?.specId??S,instructions:ts(E,he?.instructions),model:it||void 0,inference:Vt,frontendTools:st,subagents:r&&f?vo(r.team,f.id):To(E),sharing:r?.sharing,onSubagentEvent:t=>Ra.getState().appendSubagentEvent(t),modeEffect:he?.modeEffect}):R!==void 0?{type:"ag-ui",endpoint:De?`${R}/api/v1/apps/agents/${encodeURIComponent(S)}/ag-ui/`:`${R}/api/v1/ag-ui/${S}/`,...De&&Ve?{authToken:Ve}:{},agentId:S,configEndpoint:`${R}/api/v1/configure`,enableConfigQuery:!0}:void 0,[S,I,Vt,f,st,r,E,he,it,R,De,Ve]),ct=ha(!I,jt?.type==="ag-ui"?jt.configEndpoint:void 0,void 0,S),We=ma(),lt=ga(S),[ao,so]=n.useState(void 0),[Zo,en]=n.useState(void 0);n.useEffect(()=>{if(I||R===void 0)return;let t=!1;return fetch(`${R}/api/v1/configure/models?agent_id=${encodeURIComponent(S)}`).then(c=>c.ok?c.json():null).then(c=>{t||(so(c?fa(c):[]),en(c?ya(c):void 0))}).catch(()=>{t||so([])}),()=>{t=!0}},[R,S,I]);const tn=n.useMemo(()=>va(ao,()=>Object.values(ba).filter(t=>t.available&&wa(t)).map(t=>({id:t.id,name:t.name,provider:t.provider}))),[ao]),ro=n.useMemo(()=>{const t=ct.data?.builtinTools??[],c=new Set(t.map(d=>d.name));return{runtime:t,frontend:st.filter(d=>!c.has(d.name)).map(d=>({id:d.name,name:d.name}))}},[ct.data?.builtinTools,st]),io=n.useMemo(()=>new Set((We.data?.skills??[]).filter(t=>t.status==="enabled"||t.status==="loaded").map(t=>t.id)),[We.data]),on=n.useCallback(async t=>{Jt(t),!(I||R===void 0)&&await fetch(`${R}/api/v1/configure/inference/provider`,{method:"PUT",headers:{"content-type":"application/json"},body:JSON.stringify({model:t})}).catch(()=>{})},[R,I]),co=u?.promptPlacement==="bottom-chat",nn=u?.promptPlacement==="floating",Te=u?.promptPlacement==="top",Ke=u?.hidePrompt===!0||b.hidePrompt===!0,an={onSend:()=>{F(Yt)},input:Yt,setInput:It,focusTrigger:me||eo?(me?.nonce??0)+eo:void 0,placement:nn||Y==="floating"||Y==="floating-top"||Y==="floating-bottom"?"floating":"docked",floatingAnchor:Y==="floating-top"?"top":"bottom",isLoading:N,onStop:()=>e.viewControls.stop?.(),placeholder:Kt??K,typingSuggestions:xt.map(t=>t.text),suggestions:nt,disableInputPrompt:rt,connectionConfirmed:!rt,padding:Te||Y==="floating-top"||Y==="floating-bottom"||Y==="docked-top"?2:3,promptVariant:"lexical",autoFocus:u?.autoFocusPrompt??!0,mentionableAgents:Fo,promptCommands:Mo,headerContent:Ho.length>0?o.jsx(Nt,{slot:je.inpromptMenu,props:{workspace:e}}):void 0,footerExtras:Do.length>0?o.jsx(Nt,{slot:je.promptAction,props:{workspace:e}}):void 0,showAgentsMenu:!L,showInlineAgentsMenu:!1,agents:Wo,selectedAgentId:w,onSelectAgent:t=>r?.select(t),showTokenUsage:b.showTokenUsage??u?.showTokenUsage??!0,showContextRing:!0,agentUsage:Go??void 0,showModelSelector:!L,models:tn,decisions:Zo,selectedModel:it,onModelSelect:t=>{on(t)},showToolsMenu:!L,availableTools:ro.runtime,availableFrontendTools:ro.frontend,mcpServers:ct.data?.mcpServers??[],mcpStatusData:b.mcpStatusData??void 0,showSkillsMenu:!L,skills:We.data?.skills??[],skillsLoading:We.isLoading,enabledSkills:io,onToggleSkill:t=>io.has(t)?lt.disableSkill(t):lt.enableSkill(t),onToggleAllSkills:(t,c)=>t.forEach(d=>c?lt.enableSkill(d):lt.disableSkill(d)),codemodeEnabled:b.codemodeEnabled??!1,onToggleCodemode:b.onToggleCodemode,isA2AProtocol:!1,hasConfigData:!!ct.data,hasSkillsData:!!We.data},lo=ee[0]?.value.Component,Rt=Pe[0]?.value.Component,dt=lo?o.jsx(lo,{workspace:e,composer:an}):null,uo=T.length>0&&u?.showSurfaceSelector!==!1?o.jsx(js,{surfaces:T.map(t=>t.value),active:k?.surfaceId??pe?.surfaceId??X,onChange:de,workspace:e}):null,po=o.jsxs(o.Fragment,{children:[T.map(t=>{const c=t.value,d=k?.surfaceId===c.surfaceId;return d||Q.current.has(c.surfaceId)||Ye(c,e)?(Q.current.add(c.surfaceId),o.jsx(g,{sx:d?{flex:"1 1 0",minWidth:0,minHeight:0}:{position:"absolute",inset:0,visibility:"hidden",pointerEvents:"none",zIndex:-1},children:o.jsx(xa,{load:c.load,props:{surfaceId:c.surfaceId,workspace:e},fallback:o.jsxs(Ut,{children:["Loading ",c.title,"…"]}),errorFallback:h=>o.jsxs(Ut,{children:[c.title," failed to load: ",h.message]})})},c.surfaceId)):null}),!k&&pe?o.jsx(g,{flex:"1 1 0",minWidth:0,minHeight:0,children:o.jsxs(Ut,{children:["Starting ",pe.title,"…"]})}):null]}),ho=o.jsx(o.Fragment,{children:o.jsxs(g,{flex:Te&&k?"0 0 34%":"1 1 0",maxWidth:Te&&k?460:void 0,minWidth:0,minHeight:0,display:"flex",flexDirection:"column",borderLeft:k?"1px solid":void 0,borderColor:"border.default",position:"relative",children:[b.errorBanner?o.jsx(g,{flexShrink:0,px:3,py:2,fontSize:1,borderBottom:"1px solid",bg:b.errorBanner.variant==="warning"?"attention.subtle":"danger.subtle",color:b.errorBanner.variant==="warning"?"attention.fg":"danger.fg",borderColor:b.errorBanner.variant==="warning"?"attention.muted":"danger.muted",children:b.errorBanner.message}):null,Ce?.said&&Ce.given===A?.id?o.jsx(D,{as:"p",role:"status",sx:{m:0,px:3,py:2,fontSize:1,color:"fg.muted"},children:Ce.said}):null,o.jsx(g,{flex:"1 1 auto",minHeight:0,display:"flex",children:Xo?o.jsx(D,{as:"p",role:"status",sx:{m:0,p:3,fontSize:1,color:"fg.muted"},children:Eo.opening}):o.jsx(ka,{themeVariant:u?.themeVariant,themeOverrides:u?.themeOverrides,colorMode:u?.colorMode,thread:no,disabled:rt,disableReason:Kt,protocol:jt,frontendTools:I?void 0:b.frontendTools,initialModel:it||void 0,title:L?.name??f?.name??E?.name??S,description:L?.welcome??E?.description,brandIcon:L?.face?o.jsx(ks,{face:L.face,size:20,state:ie}):o.jsx(kt,{size:20}),headerContent:L&&!Et?o.jsx(Ss,{state:ie}):void 0,emptyState:{icon:L?.face?o.jsx("span",{"aria-hidden":!0,style:{fontSize:jo,lineHeight:1},children:o.jsx(Oo,{face:L.face,size:jo})}):o.jsx(kt,{size:48}),title:L?.name??f?.name??E?.name??S,...r&&f?{sections:[{group:r.team.name,icon:o.jsx(No,{size:48}),title:r.team.name,subtitle:r.team.description},{group:f.name,icon:o.jsx(kt,{size:32}),title:f.name,subtitle:E?.description}]}:null},suggestions:Te||se||u?.suggestionLabels===!1?[]:nt,showHeader:!u?.hideHeader&&!!Rt,headerButtons:{showNewChat:u?.headerButtons?.newChat??!1,showClear:u?.headerButtons?.clear??!1},renderHeader:Rt?t=>o.jsx(Rt,{workspace:e,header:t}):void 0,showInformation:!0,headerActions:o.jsxs(g,{display:"inline-flex",alignItems:"center",gap:2,children:[e.chatHeaderActions,Vo.length>0?o.jsx(Nt,{slot:je.chatHeader,props:{workspace:e}}):null,o.jsx(Sa,{icon:_?Ca:Ta,"aria-label":_?"Exit full screen":"Enter full screen",variant:"invisible",size:"small",onClick:()=>{ze(!1),ue()},sx:bt?{"@keyframes dla-fullscreen-hint":{"0%, 100%":{opacity:1},"50%":{opacity:.4}},"&&":{bg:`color-mix(in srgb, ${i.primary} 16%, transparent)`,boxShadow:`inset 0 0 0 1.5px ${i.primary}`,animation:`dla-fullscreen-hint ${Is}ms ease-in-out infinite`},"@media (prefers-reduced-motion: reduce)":{"&&":{animation:"none"}}}:void 0})]}),showInput:!1,onSendReady:ye,notebookToolSurfacesId:k?void 0:e.surfaceId,renderToolResult:b.renderToolResult,showTurnFooter:b.showTokenUsage??u?.showTokenUsage??!0,onContextSnapshot:Me,onLoadingChange:tt,onItemsChange:M,onDisplayItemsChange:le,enableStreaming:!0},no?.id)}),co&&!Ke?dt:null]})}),mo=u?.suggestionLabels!==!1&&nt.length>0?o.jsx(g,{"aria-label":a.suggestedPrompts,display:"flex",flexWrap:"wrap",gap:2,px:2,pb:"6px",children:nt.map(t=>o.jsx(g,{as:"button",type:"button",title:t.message,disabled:N||rt,onClick:()=>{F(t.message)},appearance:"none",font:"inherit",fontSize:0,fontWeight:"semibold",lineHeight:1.25,px:"10px",py:"5px",width:wo,flex:`0 0 ${wo}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:o.jsx(Ea,{title:t.title,maxWidth:"100%",sx:{minWidth:0},children:t.title})},t.title))}):null,go=p?o.jsx(g,{flex:"0 0 auto",px:3,py:2,borderTop:"1px solid",borderColor:"border.default",bg:"canvas.subtle",fontSize:1,maxHeight:"40%",overflowY:"auto",children:p}):null;return o.jsxs(g,{ref:Le,sx:{height:"100%",minHeight:0,display:"flex",flexDirection:"column",position:"relative",..._?{bg:"canvas.default"}:null,..._&&!$e.current?{position:"fixed",top:vt,right:0,bottom:0,left:0,height:"auto",zIndex:1e3}:null},children:[se?o.jsx(se.Component,{workspace:e,editors:po,hasEditor:!!k,transcript:ho,prompt:Ke?null:dt,chips:Ke?null:mo,picker:uo,transient:go}):o.jsxs(o.Fragment,{children:[Te&&!Ke?o.jsxs(g,{flex:"0 0 auto",borderBottom:"1px solid",borderColor:"border.default",children:[dt,mo]}):null,uo,o.jsxs(g,{flex:"1 1 auto",minHeight:0,display:"flex",position:"relative",children:[po,ho]}),go,co||Ke||Te?null:dt]}),Ct?o.jsx(g,{position:"absolute",inset:0,zIndex:5,bg:"canvas.default",display:"flex",flexDirection:"column",minHeight:0,children:o.jsx(Xa,{agentName:f?.name??E?.name,sandboxStillRuns:I,temporary:Wt,onSignedIn:()=>Ia.getState().clear()})}):null]})}function js({surfaces:e,active:a,onChange:i,workspace:s}){const l=[...e].sort((p,m)=>(p.order??100)-(m.order??100));return o.jsxs(g,{flex:"0 0 auto",display:"flex",alignItems:"center",gap:2,px:3,py:2,borderBottom:"1px solid",borderColor:"border.default",children:[o.jsx(D,{sx:{fontSize:0,color:"fg.muted"},children:"Beside the chat"}),o.jsxs(Mt,{"aria-label":"Editor beside the chat",size:"small",children:[o.jsx(Mt.Button,{selected:a===X,onClick:()=>i(X),children:"Chat"}),l.map(p=>{const m=Ye(p,s),y=m?void 0:p.unavailableReason?.(s)??"Not available right now";return o.jsx(Mt.Button,{selected:a===p.surfaceId,"aria-disabled":!m,title:y??p.title,leadingIcon:p.icon,onClick:()=>{m&&i(p.surfaceId)},children:p.title},p.surfaceId)})]})]})}function Ut({children:e}){return o.jsx(g,{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"fg.muted",fontSize:1,px:3,textAlign:"center",children:e})}export{_s as default};
|
|
@@ -3596,7 +3596,7 @@ ${lo}`;let Iu=MODULES.get(Ru);return Iu||(Iu=(async()=>{const Ou=await $u(Au,{cr
|
|
|
3596
3596
|
${Du}`:zu,inputs:Du,clear:Pu?[]:[DRAFT.path],loop:Bu()}:{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},Ou=lo.outputs.flatMap(Pu=>[...Pu.title?[{id:`output-${Pu.name}-title`,component:"Text",text:Pu.title,variant:"h4"}]:[],{...Pu.props,id:`output-${Pu.name}`,component:Pu.component,[pageOutputShows(Pu.component,Au.interface.customComponents)??"text"]:{path:outputPath(Pu.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),...Ou]}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(Ou=>typeof Ou=="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(`
|
|
3597
3597
|
|
|
3598
3598
|
`)){const Ru=$u.split(`
|
|
3599
|
-
`).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 Ou=await Ru.json();Iu=typeof Ou.detail=="string"?Ou.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)}/actions`,{name:"page",payload:{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),Ou=reactExports.useMemo(()=>appPageMessages(Au,SURFACE_CATALOG_ID),[Au]),Pu=useContributions(LoopCanvasBlock),Du=[...new Set(Pu.map(bd=>bd.value.id))].sort(),Lu=Du.join(","),ju=useOwnComponents(),Bu=reactExports.useMemo(()=>{const bd=blocksMissing(componentsOnPage(Ou),Du);if(bd)return{problem:bd};try{return{catalog:catalogOfBlocks(Du,ju)}}catch(Td){return{problem:Td instanceof Error?Td.message:String(Td)}}},[Ou,Lu,ju]),[Fu,zu]=reactExports.useState(null),qu=pageOf(Au),[Uu,Hu]=reactExports.useState({}),Vu=reactExports.useMemo(()=>({...appPageData(Au,Ru,Iu),...outputsData(Uu)}),[Au,Ru,Iu,Uu]),Gu=useIAMStore(bd=>bd.token)??"",Ku=useChatWords(),Zu=agentServerOf(lo.sandbox,lo.serverUrl),Qu=reactExports.useRef(null);Qu.current=Zu===void 0?null:{serverUrl:Zu,agentId:lo.agentId||Au.id,token:Gu||void 0};const Yu=reactExports.useRef("");Yu.current=Zu===void 0?noRuntimeSaid(lo.sandbox,Ku):"";const ed=reactExports.useRef(null),Xu=reactExports.useRef(!1),rd=reactExports.useRef(null),nd=reactExports.useRef(""),od=reactExports.useRef(!0),ad=reactExports.useCallback(bd=>{rd.current=bd,!Xu.current&&(Xu.current=!0,(async()=>{for(;rd.current&&od.current;){const Td=rd.current;rd.current=null;const Pd=Qu.current;if(!Pd){zu(Yu.current);continue}try{ed.current??=openPageSession(Pd);const ud=await runPageIn(Pd,await ed.current,Td);if(!od.current)break;"refused"in ud?zu(ud.refused):(zu(null),Hu(ud.outputs))}catch(ud){ed.current=null,od.current&&zu(ud instanceof Error?ud.message:String(ud))}}Xu.current=!1})())},[]),ld=reactExports.useRef(null);reactExports.useEffect(()=>(od.current=!0,()=>{od.current=!1,ld.current?.()}),[]);const fd=reactExports.useCallback(bd=>{if(!qu?.live)return;ld.current?.();let Td;const Pd=md=>{const _d=pageInputsOf(Au,md),hd=JSON.stringify(_d);hd!==nd.current&&(clearTimeout(Td),Td=setTimeout(()=>{nd.current=hd,ad(_d)},PAGE_RUN_DELAY_MS))},ud=bd.dataModel.subscribe("/inputs",Pd);Pd(ud.value),ld.current=()=>{clearTimeout(Td),ud.unsubscribe()}},[Au,qu?.live,ad]),pd=reactExports.useRef(lo);pd.current=lo;const Sd=reactExports.useRef(""),wd=reactExports.useCallback((bd,Td)=>{const Pd=appPageAction(Au,{name:bd.name,context:bd.context??{}},md=>Td?.dataModel.get(md),Sd.current),ud=pd.current.viewControls;if("refused"in Pd){zu(Pd.refused);return}if(zu(null),"runPage"in Pd)ad(Pd.runPage);else if("stop"in Pd)ud.stop?.();else if("newChat"in Pd)ud.newChat?.();else{if(ud.send){const md=ud.send(Pd.send,{loop:Pd.loop});if(md){zu(md);return}}else if(Pd.loop.files){zu("The conversation is not ready for a file yet: try again.");return}else pd.current.prompts.submit(Pd.send);Sd.current=Pd.inputs;for(const md of Pd.clear)Td?.dataModel.set(md,"")}},[Au,ad]);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:Ou,data:Vu,onAction:wd,validationError:Fu,catalog:Bu.catalog,...qu?{onSurface:fd}:{}},Lu)})}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,uiPlugin:Au.id,component:lo},{id:lo.id}))}}const CANVAS_BLOCK_PLUGINS=listUIPlugins().filter(Au=>Au.enabled&&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 Ou=$u.getManifest(Iu);return{name:Iu,displayName:Ou?.displayName??Iu,description:Ou?.description,emoji:Ou?.emoji,version:Ou?.version,enabled:$u.isEnabled(Iu),disabledBy:Ou?.disabledBy,changeable:!Au.has(Iu),details:[{label:"Delivered by",values:Ou?.extension?[Ou.extension]:[]},{label:"Contributes to",values:Ou?.contributesTo??[]},{label:"Offers contribution points",values:Ou?.contributionPoints??[]},{label:"Requires backend plugins",values:Ou?.requiredBackendPlugins??[]},{label:"Uses if available",values:Ou?.optionalBackendPlugins??[]},{label:"Activates on",values:Ou?.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$5,{"aria-hidden":!0,children:Au.emoji}):null,jsxRuntimeExports.jsx(Text$5,{sx:{fontWeight:"semibold"},children:Au.displayName}),Au.version?jsxRuntimeExports.jsxs(Text$5,{sx:{fontSize:0,color:"fg.muted"},children:["v",Au.version]}):null]}),jsxRuntimeExports.jsx(Text$5,{sx:{fontSize:0,color:"fg.muted",wordBreak:"break-all"},children:Au.name}),Au.description?jsxRuntimeExports.jsx(Text$5,{sx:{fontSize:0},children:Au.description}):null,lo.map($u=>jsxRuntimeExports.jsxs(Box,{sx:{display:"grid",gap:1},children:[jsxRuntimeExports.jsx(Text$5,{sx:{fontSize:0,fontWeight:"semibold"},children:$u.label}),$u.values.map(Ru=>jsxRuntimeExports.jsx(Text$5,{sx:{fontSize:0,color:"fg.muted",wordBreak:"break-all"},children:Ru},Ru))]},$u.label)),Au.disabledBy==="dependency"?jsxRuntimeExports.jsx(Text$5,{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$5,{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(),Ou=Iu.openName===Au.name,Pu=()=>Iu.show(Au.name),Du=()=>Iu.hide();return jsxRuntimeExports.jsx(AnchoredOverlay,{open:Ou,onOpen:Pu,onClose:Du,focusZoneSettings:{disabled:!0},focusTrapSettings:{disabled:!0},overlayProps:OVERLAY_TAKES_NO_FOCUS,side:"outside-right",renderAnchor:Lu=>jsxRuntimeExports.jsxs(Box,{...Lu,onMouseEnter:Pu,onMouseLeave:Du,onFocus:Pu,onBlur:Du,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$5,{sx:{fontSize:1},"aria-hidden":!0,children:Au.emoji}):null,jsxRuntimeExports.jsx(Text$5,{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$5,{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 Ou=reactExports.useMemo(()=>Au.filter(Pu=>pluginMatches(Pu,lo)),[Au,lo]);return Ou.length===0?jsxRuntimeExports.jsx(Text$5,{sx:{fontSize:0,color:"fg.muted"},children:Iu??`No plugin matches “${lo}”.`}):jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:Ou.map(Pu=>jsxRuntimeExports.jsx(PluginRowView,{row:Pu,size:$u,onToggle:Ru},Pu.name))})}function PluginsManagerView({protectedPlugins:Au,hiddenPlugins:lo,switchSize:$u,width:Ru,...Iu}){const Ou=useReactorPlatform(),Pu=Ou.getConfig(MANAGER_PLUGIN_NAME)??{},Du=reactExports.useMemo(()=>new Set(Au??Pu.protected??[MANAGER_PLUGIN_NAME]),[Au,Pu.protected]),Lu=reactExports.useMemo(()=>new Set(lo??Pu.hidden??[]),[lo,Pu.hidden]),ju=usePluginHoverControl(),Bu=usePluginRows(Du,Lu),[Fu,zu]=reactExports.useState(""),qu=$u??Pu.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:ju,children:jsxRuntimeExports.jsxs(Box,{sx:{display:"flex",flexDirection:"column",gap:3,width:Ru??Pu.width??"100%",maxWidth:"100%",minWidth:0},children:[jsxRuntimeExports.jsx(ReactorSlot,{slot:MANAGER_ACTIONS_SLOT,props:Iu}),jsxRuntimeExports.jsxs(Box,{children:[jsxRuntimeExports.jsx(Text$5,{as:"h2",sx:{fontSize:1,fontWeight:"semibold",display:"block",mb:2},children:Pu.title??"Plugins"}),jsxRuntimeExports.jsx(TextInput$1,{leadingVisual:SearchIcon,value:Fu,onChange:Vu=>zu(Vu.target.value),"aria-label":"Filter plugins",placeholder:"Filter…",block:!0,size:"small"})]}),jsxRuntimeExports.jsx(Box,{children:jsxRuntimeExports.jsx(PluginList,{plugins:Bu,query:Fu,switchSize:qu,onToggle:(Vu,Gu)=>Gu?Ou.enable(Vu):Ou.disable(Vu)})}),Hu.map(Vu=>jsxRuntimeExports.jsxs(Box,{children:[jsxRuntimeExports.jsx(Text$5,{as:"h3",sx:{fontSize:1,fontWeight:"semibold",display:"block",mb:2},children:Vu.title}),jsxRuntimeExports.jsx(Vu.Component,{query:Fu,switchSize:qu})]},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,Ou=canOpenView(Iu,lo),Pu=lo.activeViewType===Iu.viewType,Du=Iu.icon,Lu=Ou?Iu.title:`${Iu.title} — ${Iu.unavailableReason?.(lo)??"unavailable"}`;return jsxRuntimeExports.jsx(Tooltip,{text:Lu,direction:"n",children:jsxRuntimeExports.jsxs(Box,{as:"button",role:"tab","aria-selected":Pu,"aria-disabled":!Ou,onClick:()=>Ou&&lo.setActiveViewType(Iu.viewType),display:"inline-flex",alignItems:"center",gap:1,border:"none",borderRadius:"5px",px:2,py:"4px",fontSize:0,cursor:Ou?"pointer":"not-allowed",opacity:Ou?1:.5,bg:Pu?"canvas.default":"transparent",color:Pu?"fg.default":"fg.muted",boxShadow:Pu?"shadow.small":"none",children:[Du?jsxRuntimeExports.jsx(Du,{size:14}):null,$u&&Du?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,Ou]=reactExports.useState(Ru[0]?.id??null),Pu=Ru.some(Du=>Du.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":Pu??void 0,display:Pu?"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(Du=>{const{Component:Lu}=Du,ju=Du.id===Pu;return jsxRuntimeExports.jsx(Box,{id:`loop-rail-panel-${Du.id}`,role:"region","aria-label":railItemsOf([Du])[0].label,hidden:!ju,sx:ju?paneOpening("right"):void 0,children:jsxRuntimeExports.jsx(Lu,{...lo})},Du.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(Du=>{const Lu=Du.icon,ju=Du.id===Pu;return jsxRuntimeExports.jsx(Box,{as:"button",type:"button","data-loop-rail-item":Du.id,"aria-label":Du.label,title:Du.label,"aria-pressed":ju,"aria-controls":`loop-rail-panel-${Du.id}`,onClick:()=>Ou(railChoiceAfter(Pu,Du.id)),width:32,height:32,display:"inline-flex",alignItems:"center",justifyContent:"center",p:0,border:"none",borderRadius:2,cursor:"pointer",color:ju?"fg.default":"fg.muted",bg:ju?"neutral.muted":"transparent",hover:{color:"fg.default",bg:"neutral.subtle"},focusVisible:{outline:"2px solid",outlineColor:"var(--focus-outlineColor, #0969da)",outlineOffset:"1px"},children:jsxRuntimeExports.jsx(Lu,{size:16})},Du.id)})})]})}function buildLoopReactor(Au){return buildReactorFromPlugins(Au)}function LoopWorkspace(Au){const{serverUrl:lo,agentId:$u,conversationId:Ru,model:Iu,sandbox:Ou={state:"idle"},extensions:Pu=[],reactor:Du,manageReactor:Lu=!0,initialViewType:ju,onSend:Bu,layout:Fu="page",showViewSelector:zu=!0,showHeader:qu=!0,chatHeaderActions:Uu,headerActions:Hu,headerContainer:Vu,sidebarRail:Gu=!1}=Au,Ku=reactExports.useMemo(()=>Du??buildLoopReactor(Pu),[Du]);return useReactor(Ku,{autoStart:Lu}),jsxRuntimeExports.jsx(WorkspaceBody,{serverUrl:lo,agentId:$u,conversationId:Ru,model:Iu,initialSandbox:Ou,initialViewType:ju,onSend:Bu,layout:Fu,showViewSelector:zu,showHeader:qu,chatHeaderActions:Uu,headerActions:Hu,headerContainer:Vu,sidebarRail:Gu})}function WorkspaceBody({serverUrl:Au,agentId:lo,conversationId:$u,model:Ru,initialSandbox:Iu,initialViewType:Ou,onSend:Pu,layout:Du="page",showViewSelector:Lu=!0,showHeader:ju=!0,chatHeaderActions:Bu,headerActions:Fu,headerContainer:zu,sidebarRail:qu=!1}){const[Uu,Hu]=reactExports.useState(lo),Vu=reactExports.useRef(loopSurfaceId($u??`session-${Date.now().toString(36)}`));reactExports.useEffect(()=>{Hu(lo)},[lo]);const[Gu,Ku]=reactExports.useState(Ou??""),[Zu,Qu]=reactExports.useState(Iu),[Yu]=reactExports.useState(createPromptChannel),[ed,Xu]=reactExports.useState({}),rd=reactExports.useCallback(Pd=>{Xu(Pd??{})},[]),nd=useContributions(LoopViewType),od=useContributions(LoopCommand),ad=useSlotComponents(LoopSlots.sidebar),ld=reactExports.useRef(od),fd=reactExports.useRef(null),pd=Du==="panel",Sd=reactExports.useCallback(async Pd=>{const ud=parseCommand(Pd);if(!ud)return Pu?.(Pd,fd.current),Yu.submit(Pd)||Pu?{handled:!0}:{handled:!1,reason:"Nothing is listening for prompts in this view yet."};const md=ld.current.find(hd=>hd.value.name===ud.name||(hd.value.aliases??[]).includes(ud.name));if(!md)return{handled:!1,command:ud.name,reason:`Unknown command: /${ud.name}. Type /help to see what there is.`};const _d=await md.value.run({workspace:fd.current,argv:ud.argv});return _d?.prompt&&(Pu?.(_d.prompt,fd.current),Yu.submit(_d.prompt)),{handled:!0,command:ud.name,result:_d??void 0}},[Pu,Yu]),wd=reactExports.useMemo(()=>({serverUrl:Au,agentId:Uu,surfaceId:Vu.current,setAgentId:Hu,conversationId:$u,model:Ru,sandbox:Zu,setSandbox:Qu,activeViewType:Gu,setActiveViewType:Ku,prompts:Yu,submit:Sd,viewControls:ed,setViewControls:rd,chatHeaderActions:Bu}),[Au,Uu,$u,Ru,Zu,Gu,Yu,Sd,ed,rd,Bu]);fd.current=wd,ld.current=od;const bd=reactExports.useMemo(()=>Gu||(nd.find(ud=>canOpenView(ud.value,wd))?.value.viewType??""),[Gu,nd,wd]);useReactorEvent(bd?onView(bd):void 0);const Td=jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[Fu,jsxRuntimeExports.jsx(ReactorSlot,{slot:LoopSlots.header,props:{workspace:wd}}),Lu?jsxRuntimeExports.jsx(ViewSwitcher,{views:nd,workspace:wd,compact:pd}):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:[ju&&zu?reactDomExports.createPortal(jsxRuntimeExports.jsx(Box,{display:"flex",alignItems:"center",flexWrap:"wrap",gap:2,children:Td}),zu):null,ju&&zu===void 0?jsxRuntimeExports.jsx(Box,{as:"header",display:"flex",alignItems:"center",justifyContent:pd?"flex-start":"space-between",flexWrap:"wrap",gap:2,px:pd?2:3,py:2,borderBottom:"1px solid",borderColor:"border.default",flex:"0 0 auto",children:Td}):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:bd,props:{viewType:bd,workspace:wd},fallback:jsxRuntimeExports.jsx(Centered,{children:"Loading…"}),empty:jsxRuntimeExports.jsx(Centered,{children:"No view is available yet."}),errorFallback:Pd=>jsxRuntimeExports.jsxs(Centered,{children:["This view failed to load: ",Pd.message]})})}),ad.length>0&&qu&&!pd?jsxRuntimeExports.jsx(SidebarRail,{components:ad,props:{workspace:wd},width:SIDEBAR_WIDTH}):ad.length>0?jsxRuntimeExports.jsx(Box,{as:"aside",flex:"0 0 auto",width:pd?"100%":`${SIDEBAR_WIDTH}px`,minWidth:0,borderLeft:pd?"none":"1px solid",borderTop:pd?"1px solid":"none",borderColor:"border.default",bg:"canvas.subtle",overflowY:"auto",px:3,py:3,children:jsxRuntimeExports.jsx(ReactorSlot,{slot:LoopSlots.sidebar,props:{workspace:wd}})}):null]}),jsxRuntimeExports.jsxs(Box,{flex:"0 0 auto",children:[jsxRuntimeExports.jsx(ReactorSlot,{slot:LoopSlots.footer,props:{workspace:wd}}),jsxRuntimeExports.jsx(ReactorSlot,{slot:LoopSlots.status,props:{workspace:wd}})]}),jsxRuntimeExports.jsx(ReactorSlot,{slot:LoopSlots.root,props:{workspace:wd}})]})}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,[Ou,Pu]=reactExports.useState(!1),Du=reactExports.useRef(!1);reactExports.useEffect(()=>{const Fu=()=>{if(!Du.current)return;const zu=!!document.fullscreenElement&&!!Au.current&&document.fullscreenElement.contains(Au.current);Pu(zu),zu||(Du.current=!1)};return document.addEventListener("fullscreenchange",Fu),()=>document.removeEventListener("fullscreenchange",Fu)},[Au]);const Lu=reactExports.useCallback(()=>{const Fu=fullScreenNode(Au.current);if(Ou){Du.current&&document.fullscreenElement?document.exitFullscreen():Pu(!1);return}if($u||Ru||!Fu?.requestFullscreen){Pu(!0);return}Du.current=!0,Fu.requestFullscreen().then(()=>Pu(!0),()=>{Du.current=!1,Pu(!0)})},[Au,Ou,$u,Ru]),[ju,Bu]=reactExports.useState(0);return reactExports.useEffect(()=>{if(!Ou||Du.current){Bu(0);return}const Fu=()=>Bu(resolveTopOffset(Iu));return Fu(),window.addEventListener("resize",Fu),()=>window.removeEventListener("resize",Fu)},[Ou,Iu]),reactExports.useEffect(()=>{if(!Ru||!Ou||Du.current)return;const Fu=fullScreenNode(Au.current);if(!Fu)return;const zu=Fu.getAttribute("style");return Fu.style.position="fixed",Fu.style.top=`${ju}px`,Fu.style.right="0",Fu.style.bottom="0",Fu.style.left="0",Fu.style.height="auto",Fu.style.zIndex="1000",()=>{zu===null?Fu.removeAttribute("style"):Fu.setAttribute("style",zu)}},[Ru,Ou,Au,ju]),reactExports.useEffect(()=>{if(!Ou||Du.current)return;const Fu=zu=>{zu.key==="Escape"&&!zu.defaultPrevented&&Pu(!1)};return window.addEventListener("keydown",Fu),()=>window.removeEventListener("keydown",Fu)},[Ou]),{fullScreen:Ou,usingApi:Du,toggle:Lu,topOffsetPx:ju}}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]}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:[contribution(LoopViewType,{viewType:"chat",title:"Chat",icon:CommentDiscussionIcon,order:0,load:()=>__vitePreload(()=>import("./chunks/ChatView-DE-jo1oJ.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$5,{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:Ou,transient:Pu,activity:Du,bandMode:Lu="docked",panelMode:ju="docked",panelSide:Bu="right",sheetWidth:Fu=PAGE_SHEET_WIDTH,pageSize:zu,panelWidth:qu=PAGE_PANEL_WIDTH}){const Uu=Lu==="panel",Hu=Ru!=null,{width:Vu,height:Gu}=resolvePageSize(zu,Fu),Zu=useSignalValue$1(pageLayoutPanelOpen)||Uu&&Hu,Qu=useSignalValue$1(pageLayoutActivity),Yu=Du??Qu,ed=lo?"page":"panel";return reactExports.useEffect(()=>{pageLayoutSheet.value=ed},[ed]),jsxRuntimeExports.jsxs(Box$1,{"data-page-layout":"",sx:{position:"relative",flex:"1 1 auto",minHeight:0,display:"flex",flexDirection:"column"},children:[Ou,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&&Lu==="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":Zu?"":void 0,"data-page-panel-mode":ju,"aria-hidden":Zu?void 0:"true",sx:{minWidth:0,minHeight:0,display:"flex",flexDirection:"column",bg:"canvas.default",borderColor:"border.default",...Zu?ju==="docked"?{flex:`0 0 ${qu}px`,maxWidth:"45%",order:Bu==="left"?-1:void 0,[Bu==="left"?"borderRight":"borderLeft"]:"1px solid",zIndex:1}:ju==="overlay"?{position:"absolute",top:0,bottom:0,[Bu]:0,width:qu,maxWidth:"85%",[Bu==="left"?"borderRight":"borderLeft"]:"1px solid",boxShadow:"shadow.large",zIndex:5}:{position:"absolute",[Bu]:16,bottom:16,width:qu,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},...Zu?panelOpening(Bu):null},children:$u}),Hu&&Lu!=="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]})]}),Pu]})}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-DcubnPoo.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$3,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$3}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:Ou}=Au;return reactExports.useEffect(()=>lo?.connect(Ou),[lo,Ou]),reactExports.useEffect(()=>{lo&&Iu({...$u,target:Ru})},[lo,$u,Ru,Iu]),null}const DatalayerAgentBridge=reactExports.lazy(async()=>({default:(await __vitePreload(()=>import("./chunks/DatalayerAgentBridge-BhxfUyb7.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"]),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,Ou]=reactExports.useState(!1),Pu=reactExports.useRef(null),Du=reactExports.useRef(null),Lu=()=>{Du.current!==null&&(window.clearTimeout(Du.current),Du.current=null)},ju=()=>{Lu();const Yu=Pu.current?.getBoundingClientRect();Ou(!!(Yu&&Yu.left+OVERLAY_WIDTH>window.innerWidth)),Ru(!0)},Bu=()=>{Lu(),Du.current=window.setTimeout(()=>{Ru(!1),Du.current=null},300)};reactExports.useEffect(()=>()=>{Lu()},[]);const Fu=Au?.baseUrl?(()=>{const Yu=Au.baseUrl.replace(/\/$/,"");return Yu.endsWith("/api/v1")?Yu:`${Yu}/api/v1`})():void 0,zu=Fu?`${Fu}/runtime/status`:void 0,qu=toSandboxStatusUrl(Au?.sandboxBaseUrl);if(!Au)return null;const Uu=(Au.status||"").toLowerCase(),Hu=!Au.isReady&&!Au.agentId&&CREATING_STATUSES.has(Uu),Vu=!!Au.error,Gu=!!Au.agentId||Hu,Ku=strip(Au.agentName,MAX_AGENT_NAME_LENGTH),Zu=`${Au.agentName} · ${Au.location}`,Qu=`${Ku} · ${Au.location}`;return jsxRuntimeExports.jsxs(Box,{ref:Pu,position:"relative",onMouseEnter:ju,onMouseLeave:Bu,children:[jsxRuntimeExports.jsxs(Box,{as:"button",type:"button",title:Zu,px:2,py:"6px",maxWidth:280,minWidth:0,border:"1px solid",borderColor:Vu?"danger.emphasis":"border.default",borderRadius:2,bg:Vu?"danger.subtle":"canvas.default",color:Vu?"danger.fg":"fg.default",fontSize:0,cursor:"default",display:"flex",alignItems:"center",gap:1,children:[Hu&&jsxRuntimeExports.jsx(StyledSpinner,{size:"small",sx:{width:12,height:12}}),Vu&&jsxRuntimeExports.jsx("span",{"aria-hidden":!0,children:"⚠"}),jsxRuntimeExports.jsx(Box,{as:"span",display:"block",minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",children:Qu})]}),$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: ",Hu?"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:Hu?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:"," ",Gu&&zu?jsxRuntimeExports.jsx(Box,{as:"a",href:zu,target:"_blank",rel:"noopener noreferrer",color:"accent.fg",textDecoration:"underline",children:zu}):"n/a"]}),jsxRuntimeExports.jsxs(Box,{color:"fg.muted",wordBreak:"break-all",children:["Code sandbox status:"," ",qu?jsxRuntimeExports.jsx(Box,{as:"a",href:qu,target:"_blank",rel:"noopener noreferrer",color:"accent.fg",textDecoration:"underline",children:qu}):"n/a"]}),Vu&&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:Ou,jupyterReactStore:Pu,loadJupyterConfig:Du}=await import("./chunks/index-CNx_s591.js").then(Lu=>Lu.r);return{createLiteServiceManager:Ou,jupyterReactStore:Pu,loadJupyterConfig:Du}},[],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})),Ou=computed$1(()=>$u.value==="running");let Pu=null,Du=null,Lu=null,ju=null;async function Bu(){if(Du)return;$u.value="starting",Pu=await Au.acquire();const Fu=await Pu.sessions.startNew({name:"loop",path:"loop.ipynb",type:"notebook",kernel:{name:"python"}});Lu=Fu.kernel,Du=Fu.kernel,lo.value={variant:Au.variant,sandbox_running:!0,kernel_id:Du?.id,kernel_name:"python"},$u.value="running"}return{kind:"browser",snapshot:Iu,status:lo,ready:Ou,lastExecution:Ru,serverUrl:"",getServiceManager:()=>Pu,getKernelConnection:()=>Lu,report(Fu){lo.value=Fu},setState(Fu){$u.value=Fu},connect(){return ju=ju??Bu().catch(Fu=>{throw $u.value="error",lo.value=null,ju=null,Fu}),()=>{Du?.shutdown?.(),Du=null,Lu=null,Pu=Au.owned?null:Pu,Au.release?.(),ju=null,$u.value="idle",lo.value=null}},async execute(Fu){const zu=Date.now();try{if(await(ju??Bu()),!Du)throw new Error("The browser kernel did not start");const qu={outputs:[],stdout:[],error:""},Uu=Du.requestExecute({code:Fu});Uu.onIOPub=Vu=>collect(Vu,qu),await Uu.done;const Hu={code:Fu,success:!qu.error,stdout:qu.stdout.join(""),error:qu.error||void 0,outputs:qu.outputs,startedAt:zu,finishedAt:Date.now()};return Ru.value=Hu,Hu}catch(qu){const Uu={code:Fu,success:!1,error:qu instanceof Error?qu.message:String(qu),startedAt:zu,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),Ou=computed$1(()=>({...summarize(lo.value,$u.value),errorReason:$u.value==="error"?Ru.value:void 0})),Pu=computed$1(()=>Ou.value.state==="running");return{kind:"server",connect(Du){if(typeof WebSocket>"u")return()=>{};let Lu=null,ju=null,Bu=0,Fu=!1;const zu=()=>{if(Fu)return;const qu=Au.replace(/^http/,"ws"),Uu=Du?`?agent_id=${encodeURIComponent(Du)}`:"";Lu=new WebSocket(`${qu}/api/v1/configure/sandbox/ws${Uu}`),Lu.onopen=()=>{Bu=0},Lu.onmessage=Hu=>{try{lo.value=JSON.parse(String(Hu.data))}catch{}},Lu.onclose=()=>{if(Fu)return;lo.value=null,Bu+=1;const Hu=Math.min(RECONNECT_BASE_MS*2**(Bu-1),RECONNECT_MAX_MS);ju=setTimeout(zu,Hu)}};return zu(),()=>{Fu=!0,ju&&clearTimeout(ju),Lu?.close(),Lu=null}},snapshot:Ou,status:lo,ready:Pu,lastExecution:Iu,serverUrl:Au,report(Du){lo.value=Du},setState(Du,Lu){$u.value=Du,Ru.value=Du==="error"?Lu:void 0},async execute(Du){const Lu=Date.now();try{const ju=await fetch(`${Au}/api/v1/sandbox/execute`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({code:Du})}),Bu=ju.ok?await ju.json():null,Fu={code:Du,success:ju.ok&&!Bu?.error,stdout:Bu?.stdout,stderr:Bu?.stderr,error:ju.ok?Bu?.error:`Execution failed: ${ju.status}`,outputs:Bu?.outputs,startedAt:Lu,finishedAt:Date.now()};return Iu.value=Fu,Fu}catch(ju){const Bu={code:Du,success:!1,error:ju instanceof Error?ju.message:String(ju),startedAt:Lu,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 Ou=signal$2(lo),Pu=createServerSandboxService(Au),Du=createBrowserSandboxService($u??browserSource()),Lu=computed$1(()=>Ou.value==="browser"?Du:Pu);let ju=null,Bu;const Fu=computed$1(()=>Lu.value.snapshot.value),zu=computed$1(()=>Lu.value.status.value),qu=computed$1(()=>Lu.value.ready.value),Uu=computed$1(()=>Lu.value.lastExecution.value);async function Hu(Ku){if(Ku==="local"){const Xu=Iu?.()??Ru?.createPayload;Xu&&await Vu(Xu)}const Zu=TARGET_SPECS[Ku]?.configure;if(!Zu)return;const Qu=TARGET_SPECS[Ku].label;let Yu;try{Yu=await fetch(`${Au}/api/v1/agents/sandbox/configure`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(Zu)})}catch(Xu){throw new Error(`${Qu} needs an agent-runtimes server at ${Au}, and nothing answered there. Start one and try again. (${Xu instanceof Error?Xu.message:String(Xu)})`,{cause:Xu})}if(!Yu.ok)throw new Error(`The server could not switch to ${Qu} (${Yu.status} ${Yu.statusText}). `+await detail(Yu));const ed=await fetch(`${Au}/api/v1/agents/sandbox/restart`,{method:"POST"});if(!ed.ok)throw new Error(`The server could not start ${Qu} (${ed.status} ${ed.statusText}). `+await detail(ed))}function Vu(Ku){return ensureServerAgent(Au,Bu,Ku)}function Gu(){if(ju?.(),Ou.peek()==="datalayer"){ju=null,Pu.setState("starting");return}ju=Lu.peek().connect(Bu)}return{get kind(){return Ou.peek()==="browser"?"browser":"server"},target:Ou,snapshot:Fu,status:zu,ready:qu,lastExecution:Uu,serverUrl:Au,getServiceManager:()=>Ou.peek()==="browser"?Du.getServiceManager():null,getKernelConnection:()=>Ou.peek()==="browser"?Du.getKernelConnection():null,report(Ku){Lu.peek().report(Ku)},setState(Ku){Lu.peek().setState(Ku)},execute(Ku){return Lu.peek().execute(Ku)},connect(Ku){Bu=Ku;const Zu=Ou.peek()==="local"&&Ku?Iu?.()??Ru?.createPayload:void 0;if(!Zu)return Gu(),()=>{ju?.(),ju=null};let Qu=!1;return Pu.setState("starting"),Vu(Zu).then(()=>{Qu||Gu()},Yu=>{Qu||(Pu.setState("error"),console.error("[loop] Local agent could not be started:",Yu))}),()=>{Qu=!0,ju?.(),ju=null}},async setTarget(Ku){const Zu=Ou.peek();if(Ku===Zu)return;const Qu=heldTargetReason(Ku,Au);if(Qu)throw new Error(Qu);ju?.(),ju=null;try{await Hu(Ku)}catch(Yu){throw Gu(),Yu}Ou.value=Ku,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(Pu){throw new Error(`Local needs an agent-runtimes server at ${Au}, and nothing answered there. Start one and try again. (${Pu instanceof Error?Pu.message:String(Pu)})`,{cause:Pu})}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 Ou=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(!Ou.ok&&Ou.status!==409)throw new Error(`The server could not launch local agent ${Ru} (${Ou.status} ${Ou.statusText}). `+await detail(Ou));Ou.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 Ou=Au.sandbox,Pu=Iu?.specId||Au.agentId,Du=AGENTSPECS$1[Pu],Lu={agentName:Iu?.name||Du?.name||Au.agentId,location:$u?TARGET_SPECS[$u].label:"—",specId:Pu,harness:Du?.harness,variant:Ou.variant,status:Ou.state,baseUrl:Ou.agentBaseUrl||Au.serverUrl,sandboxBaseUrl:Ou.jupyterUrl,agentId:Au.agentId,isReady:Ou.state==="running"};return jsxRuntimeExports.jsx(AgentSummary,{summary:Lu})}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:Ou=DEFAULT_PULSE_AT,onExpire:Pu}){const[Du,Lu]=reactExports.useState(()=>Date.now()),ju=reactExports.useRef(lo??Math.max(1,Au-Date.now())),Bu=reactExports.useRef(!1);reactExports.useEffect(()=>{const Hu=window.setInterval(()=>{Lu(Vu=>{const Gu=Date.now(),Ku=Zu=>Math.ceil((Au-Zu)/1e3);return Ku(Gu)===Ku(Vu)?Vu:Gu})},250);return()=>window.clearInterval(Hu)},[Au]);const Fu=Math.max(0,Au-Du);reactExports.useEffect(()=>{Fu>0||Bu.current||(Bu.current=!0,Pu?.())},[Fu,Pu]);const zu=Math.min(1,Math.max(0,Fu/ju.current)),qu=zu<=Ou,Uu=zu<=Iu?"danger.fg":zu<=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:{...qu?{"@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-zu),transform:`rotate(-90 ${RING/2} ${RING/2})`,style:{transition:"stroke-dashoffset 0.5s linear"}})]}),jsxRuntimeExports.jsx(Text$5,{sx:{fontSize:0,color:Uu,fontWeight:"semibold"},children:format(Fu)})]})}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$5,{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,Ou]=reactExports.useState(null),Pu=useSignalValue$1(lo?.snapshot??IDLE_SANDBOX_SNAPSHOT_SIGNAL),Du=useSignalValue$1(lo?.status??EMPTY_STATUS),Lu=useSignalValue$1(lo?.target??DEFAULT_TARGET),ju=reactExports.useCallback(async Fu=>{if(!(!lo||Fu===Lu)){Ru(!0),Ou(null);try{await lo.setTarget(Fu)}catch(zu){Ou(zu instanceof Error?zu.message:String(zu))}finally{Ru(!1)}}},[lo,Lu]);if(!lo)return null;const Bu=Math.max(0,SANDBOX_TARGETS.indexOf(Lu));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(Pu.state,Du?.execution_state,Du?.is_executing),kernelId:Pu.kernelId??Du?.kernel_id,kernelName:Du?.kernel_name,serverUrl:Pu.jupyterUrl??Du?.jupyter_url,websocketUrl:toWebsocketUrl(Pu.jupyterUrl??Du?.jupyter_url),environmentName:TARGET_SPECS[Lu].label,overlayTitle:`${TARGET_SPECS[Lu].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((Fu,zu)=>{const qu=heldTargetReason(Fu,lo?.serverUrl??"");return jsxRuntimeExports.jsx(SegmentedControl.Button,{selected:zu===Bu,"aria-disabled":qu?!0:void 0,"data-sandbox-target":Fu,"data-sandbox-target-held":qu?"":void 0,sx:{listStyle:"none",...qu?{color:"fg.subtle",cursor:"not-allowed"}:null},title:qu??TARGET_SPECS[Fu].hint,onClick:()=>qu?void 0:void ju(Fu),children:TARGET_SPECS[Fu].label},Fu)})}),Iu||Pu.errorReason?jsxRuntimeExports.jsx(Text$5,{sx:{fontSize:0,color:"danger.fg",lineHeight:1.3,maxWidth:280,minWidth:0},title:Iu??Pu.errorReason,children:Iu??Pu.errorReason}):jsxRuntimeExports.jsx(Text$5,{sx:{fontSize:0,color:"fg.muted"},title:TARGET_SPECS[SANDBOX_TARGETS[Bu]].hint,children:Pu.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(Ou=>Ou.id===Ru);return jsxRuntimeExports.jsx(AnchoredOverlay,{width:"large",open:lo,onOpen:()=>$u(!0),onClose:()=>$u(!1),renderAnchor:Ou=>jsxRuntimeExports.jsx(IconButton,{...Ou,"aria-labelledby":void 0,icon:ForwardRef$3,"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(Ou=>jsxRuntimeExports.jsxs(ActionList.Item,{selected:Ou.id===Ru,onSelect:()=>{Au.select(Ou.id),$u(!1)},children:[jsxRuntimeExports.jsx(ActionList.LeadingVisual,{children:jsxRuntimeExports.jsx(MemberIcon,{icon:Ou.icon})}),jsxRuntimeExports.jsxs(Box,{as:"span",display:"flex",alignItems:"center",gap:2,children:[Ou.name,Ou.isSupervisor?jsxRuntimeExports.jsx(Text$5,{sx:{fontSize:0,color:"fg.muted"},children:"supervisor"}):null]}),Ou.description?jsxRuntimeExports.jsx(ActionList.Description,{variant:"block",sx:{display:"block",whiteSpace:"normal",overflowWrap:"anywhere",minWidth:0},children:Ou.description}):null]},Ou.id))]})})})}function specIdOf(Au){return(Au??"").split(":")[0]??""}function teamMembers(Au){const lo=specIdOf(Au.supervisor?.ref),$u=Iu=>{const Ou=AGENTSPECS$1[Iu];return{description:Ou?.description,emoji:Ou?.emoji,icon:Ou?.icon}},Ru=(Au.agents??[]).map(Iu=>{const Ou=specIdOf(Iu.ref);return{id:Iu.id,name:Iu.name||Ou||Iu.id,specId:Ou,isSupervisor:Ou!==""&&Ou===lo,...$u(Ou)}});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(Ou=>Ou.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(Lu=>Lu.id===lo);if(!Ru)return[];const Iu=(Lu,ju,Bu)=>{const Fu=AGENTSPECS$1[ju];if(Fu)return{name:Lu,description:Bu||Fu.description||Lu,instructions:Fu.systemPrompt,model:Fu.model,icon:Fu.icon}},Ou=Ru.isSupervisor||Au.delegation?.allowPeerDelegation?$u.filter(Lu=>Lu.id!==lo).map(Lu=>Iu(Lu.name,Lu.specId,Lu.description)):[],Du=((Au.agents??[]).find(Lu=>Lu.id===lo)?.subagents??[]).map(Lu=>Iu(Lu.name,(Lu.ref??"").split(":")[0]??"",Lu.description));return[...Ou,...Du].filter(Boolean)}const 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-IYT-IKM6.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} {
|
|
3599
|
+
`).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 Ou=await Ru.json();Iu=typeof Ou.detail=="string"?Ou.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)}/actions`,{name:"page",payload:{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),Ou=reactExports.useMemo(()=>appPageMessages(Au,SURFACE_CATALOG_ID),[Au]),Pu=useContributions(LoopCanvasBlock),Du=[...new Set(Pu.map(bd=>bd.value.id))].sort(),Lu=Du.join(","),ju=useOwnComponents(),Bu=reactExports.useMemo(()=>{const bd=blocksMissing(componentsOnPage(Ou),Du);if(bd)return{problem:bd};try{return{catalog:catalogOfBlocks(Du,ju)}}catch(Td){return{problem:Td instanceof Error?Td.message:String(Td)}}},[Ou,Lu,ju]),[Fu,zu]=reactExports.useState(null),qu=pageOf(Au),[Uu,Hu]=reactExports.useState({}),Vu=reactExports.useMemo(()=>({...appPageData(Au,Ru,Iu),...outputsData(Uu)}),[Au,Ru,Iu,Uu]),Gu=useIAMStore(bd=>bd.token)??"",Ku=useChatWords(),Zu=agentServerOf(lo.sandbox,lo.serverUrl),Qu=reactExports.useRef(null);Qu.current=Zu===void 0?null:{serverUrl:Zu,agentId:lo.agentId||Au.id,token:Gu||void 0};const Yu=reactExports.useRef("");Yu.current=Zu===void 0?noRuntimeSaid(lo.sandbox,Ku):"";const ed=reactExports.useRef(null),Xu=reactExports.useRef(!1),rd=reactExports.useRef(null),nd=reactExports.useRef(""),od=reactExports.useRef(!0),ad=reactExports.useCallback(bd=>{rd.current=bd,!Xu.current&&(Xu.current=!0,(async()=>{for(;rd.current&&od.current;){const Td=rd.current;rd.current=null;const Pd=Qu.current;if(!Pd){zu(Yu.current);continue}try{ed.current??=openPageSession(Pd);const ud=await runPageIn(Pd,await ed.current,Td);if(!od.current)break;"refused"in ud?zu(ud.refused):(zu(null),Hu(ud.outputs))}catch(ud){ed.current=null,od.current&&zu(ud instanceof Error?ud.message:String(ud))}}Xu.current=!1})())},[]),ld=reactExports.useRef(null);reactExports.useEffect(()=>(od.current=!0,()=>{od.current=!1,ld.current?.()}),[]);const fd=reactExports.useCallback(bd=>{if(!qu?.live)return;ld.current?.();let Td;const Pd=md=>{const _d=pageInputsOf(Au,md),hd=JSON.stringify(_d);hd!==nd.current&&(clearTimeout(Td),Td=setTimeout(()=>{nd.current=hd,ad(_d)},PAGE_RUN_DELAY_MS))},ud=bd.dataModel.subscribe("/inputs",Pd);Pd(ud.value),ld.current=()=>{clearTimeout(Td),ud.unsubscribe()}},[Au,qu?.live,ad]),pd=reactExports.useRef(lo);pd.current=lo;const Sd=reactExports.useRef(""),wd=reactExports.useCallback((bd,Td)=>{const Pd=appPageAction(Au,{name:bd.name,context:bd.context??{}},md=>Td?.dataModel.get(md),Sd.current),ud=pd.current.viewControls;if("refused"in Pd){zu(Pd.refused);return}if(zu(null),"runPage"in Pd)ad(Pd.runPage);else if("stop"in Pd)ud.stop?.();else if("newChat"in Pd)ud.newChat?.();else{if(ud.send){const md=ud.send(Pd.send,{loop:Pd.loop});if(md){zu(md);return}}else if(Pd.loop.files){zu("The conversation is not ready for a file yet: try again.");return}else pd.current.prompts.submit(Pd.send);Sd.current=Pd.inputs;for(const md of Pd.clear)Td?.dataModel.set(md,"")}},[Au,ad]);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:Ou,data:Vu,onAction:wd,validationError:Fu,catalog:Bu.catalog,...qu?{onSurface:fd}:{}},Lu)})}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,uiPlugin:Au.id,component:lo},{id:lo.id}))}}const CANVAS_BLOCK_PLUGINS=listUIPlugins().filter(Au=>Au.enabled&&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 Ou=$u.getManifest(Iu);return{name:Iu,displayName:Ou?.displayName??Iu,description:Ou?.description,emoji:Ou?.emoji,version:Ou?.version,enabled:$u.isEnabled(Iu),disabledBy:Ou?.disabledBy,changeable:!Au.has(Iu),details:[{label:"Delivered by",values:Ou?.extension?[Ou.extension]:[]},{label:"Contributes to",values:Ou?.contributesTo??[]},{label:"Offers contribution points",values:Ou?.contributionPoints??[]},{label:"Requires backend plugins",values:Ou?.requiredBackendPlugins??[]},{label:"Uses if available",values:Ou?.optionalBackendPlugins??[]},{label:"Activates on",values:Ou?.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$5,{"aria-hidden":!0,children:Au.emoji}):null,jsxRuntimeExports.jsx(Text$5,{sx:{fontWeight:"semibold"},children:Au.displayName}),Au.version?jsxRuntimeExports.jsxs(Text$5,{sx:{fontSize:0,color:"fg.muted"},children:["v",Au.version]}):null]}),jsxRuntimeExports.jsx(Text$5,{sx:{fontSize:0,color:"fg.muted",wordBreak:"break-all"},children:Au.name}),Au.description?jsxRuntimeExports.jsx(Text$5,{sx:{fontSize:0},children:Au.description}):null,lo.map($u=>jsxRuntimeExports.jsxs(Box,{sx:{display:"grid",gap:1},children:[jsxRuntimeExports.jsx(Text$5,{sx:{fontSize:0,fontWeight:"semibold"},children:$u.label}),$u.values.map(Ru=>jsxRuntimeExports.jsx(Text$5,{sx:{fontSize:0,color:"fg.muted",wordBreak:"break-all"},children:Ru},Ru))]},$u.label)),Au.disabledBy==="dependency"?jsxRuntimeExports.jsx(Text$5,{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$5,{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(),Ou=Iu.openName===Au.name,Pu=()=>Iu.show(Au.name),Du=()=>Iu.hide();return jsxRuntimeExports.jsx(AnchoredOverlay,{open:Ou,onOpen:Pu,onClose:Du,focusZoneSettings:{disabled:!0},focusTrapSettings:{disabled:!0},overlayProps:OVERLAY_TAKES_NO_FOCUS,side:"outside-right",renderAnchor:Lu=>jsxRuntimeExports.jsxs(Box,{...Lu,onMouseEnter:Pu,onMouseLeave:Du,onFocus:Pu,onBlur:Du,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$5,{sx:{fontSize:1},"aria-hidden":!0,children:Au.emoji}):null,jsxRuntimeExports.jsx(Text$5,{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$5,{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 Ou=reactExports.useMemo(()=>Au.filter(Pu=>pluginMatches(Pu,lo)),[Au,lo]);return Ou.length===0?jsxRuntimeExports.jsx(Text$5,{sx:{fontSize:0,color:"fg.muted"},children:Iu??`No plugin matches “${lo}”.`}):jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:Ou.map(Pu=>jsxRuntimeExports.jsx(PluginRowView,{row:Pu,size:$u,onToggle:Ru},Pu.name))})}function PluginsManagerView({protectedPlugins:Au,hiddenPlugins:lo,switchSize:$u,width:Ru,...Iu}){const Ou=useReactorPlatform(),Pu=Ou.getConfig(MANAGER_PLUGIN_NAME)??{},Du=reactExports.useMemo(()=>new Set(Au??Pu.protected??[MANAGER_PLUGIN_NAME]),[Au,Pu.protected]),Lu=reactExports.useMemo(()=>new Set(lo??Pu.hidden??[]),[lo,Pu.hidden]),ju=usePluginHoverControl(),Bu=usePluginRows(Du,Lu),[Fu,zu]=reactExports.useState(""),qu=$u??Pu.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:ju,children:jsxRuntimeExports.jsxs(Box,{sx:{display:"flex",flexDirection:"column",gap:3,width:Ru??Pu.width??"100%",maxWidth:"100%",minWidth:0},children:[jsxRuntimeExports.jsx(ReactorSlot,{slot:MANAGER_ACTIONS_SLOT,props:Iu}),jsxRuntimeExports.jsxs(Box,{children:[jsxRuntimeExports.jsx(Text$5,{as:"h2",sx:{fontSize:1,fontWeight:"semibold",display:"block",mb:2},children:Pu.title??"Plugins"}),jsxRuntimeExports.jsx(TextInput$1,{leadingVisual:SearchIcon,value:Fu,onChange:Vu=>zu(Vu.target.value),"aria-label":"Filter plugins",placeholder:"Filter…",block:!0,size:"small"})]}),jsxRuntimeExports.jsx(Box,{children:jsxRuntimeExports.jsx(PluginList,{plugins:Bu,query:Fu,switchSize:qu,onToggle:(Vu,Gu)=>Gu?Ou.enable(Vu):Ou.disable(Vu)})}),Hu.map(Vu=>jsxRuntimeExports.jsxs(Box,{children:[jsxRuntimeExports.jsx(Text$5,{as:"h3",sx:{fontSize:1,fontWeight:"semibold",display:"block",mb:2},children:Vu.title}),jsxRuntimeExports.jsx(Vu.Component,{query:Fu,switchSize:qu})]},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,Ou=canOpenView(Iu,lo),Pu=lo.activeViewType===Iu.viewType,Du=Iu.icon,Lu=Ou?Iu.title:`${Iu.title} — ${Iu.unavailableReason?.(lo)??"unavailable"}`;return jsxRuntimeExports.jsx(Tooltip,{text:Lu,direction:"n",children:jsxRuntimeExports.jsxs(Box,{as:"button",role:"tab","aria-selected":Pu,"aria-disabled":!Ou,onClick:()=>Ou&&lo.setActiveViewType(Iu.viewType),display:"inline-flex",alignItems:"center",gap:1,border:"none",borderRadius:"5px",px:2,py:"4px",fontSize:0,cursor:Ou?"pointer":"not-allowed",opacity:Ou?1:.5,bg:Pu?"canvas.default":"transparent",color:Pu?"fg.default":"fg.muted",boxShadow:Pu?"shadow.small":"none",children:[Du?jsxRuntimeExports.jsx(Du,{size:14}):null,$u&&Du?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,Ou]=reactExports.useState(Ru[0]?.id??null),Pu=Ru.some(Du=>Du.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":Pu??void 0,display:Pu?"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(Du=>{const{Component:Lu}=Du,ju=Du.id===Pu;return jsxRuntimeExports.jsx(Box,{id:`loop-rail-panel-${Du.id}`,role:"region","aria-label":railItemsOf([Du])[0].label,hidden:!ju,sx:ju?paneOpening("right"):void 0,children:jsxRuntimeExports.jsx(Lu,{...lo})},Du.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(Du=>{const Lu=Du.icon,ju=Du.id===Pu;return jsxRuntimeExports.jsx(Box,{as:"button",type:"button","data-loop-rail-item":Du.id,"aria-label":Du.label,title:Du.label,"aria-pressed":ju,"aria-controls":`loop-rail-panel-${Du.id}`,onClick:()=>Ou(railChoiceAfter(Pu,Du.id)),width:32,height:32,display:"inline-flex",alignItems:"center",justifyContent:"center",p:0,border:"none",borderRadius:2,cursor:"pointer",color:ju?"fg.default":"fg.muted",bg:ju?"neutral.muted":"transparent",hover:{color:"fg.default",bg:"neutral.subtle"},focusVisible:{outline:"2px solid",outlineColor:"var(--focus-outlineColor, #0969da)",outlineOffset:"1px"},children:jsxRuntimeExports.jsx(Lu,{size:16})},Du.id)})})]})}function buildLoopReactor(Au){return buildReactorFromPlugins(Au)}function LoopWorkspace(Au){const{serverUrl:lo,agentId:$u,conversationId:Ru,model:Iu,sandbox:Ou={state:"idle"},extensions:Pu=[],reactor:Du,manageReactor:Lu=!0,initialViewType:ju,onSend:Bu,layout:Fu="page",showViewSelector:zu=!0,showHeader:qu=!0,chatHeaderActions:Uu,headerActions:Hu,headerContainer:Vu,sidebarRail:Gu=!1}=Au,Ku=reactExports.useMemo(()=>Du??buildLoopReactor(Pu),[Du]);return useReactor(Ku,{autoStart:Lu}),jsxRuntimeExports.jsx(WorkspaceBody,{serverUrl:lo,agentId:$u,conversationId:Ru,model:Iu,initialSandbox:Ou,initialViewType:ju,onSend:Bu,layout:Fu,showViewSelector:zu,showHeader:qu,chatHeaderActions:Uu,headerActions:Hu,headerContainer:Vu,sidebarRail:Gu})}function WorkspaceBody({serverUrl:Au,agentId:lo,conversationId:$u,model:Ru,initialSandbox:Iu,initialViewType:Ou,onSend:Pu,layout:Du="page",showViewSelector:Lu=!0,showHeader:ju=!0,chatHeaderActions:Bu,headerActions:Fu,headerContainer:zu,sidebarRail:qu=!1}){const[Uu,Hu]=reactExports.useState(lo),Vu=reactExports.useRef(loopSurfaceId($u??`session-${Date.now().toString(36)}`));reactExports.useEffect(()=>{Hu(lo)},[lo]);const[Gu,Ku]=reactExports.useState(Ou??""),[Zu,Qu]=reactExports.useState(Iu),[Yu]=reactExports.useState(createPromptChannel),[ed,Xu]=reactExports.useState({}),rd=reactExports.useCallback(Pd=>{Xu(Pd??{})},[]),nd=useContributions(LoopViewType),od=useContributions(LoopCommand),ad=useSlotComponents(LoopSlots.sidebar),ld=reactExports.useRef(od),fd=reactExports.useRef(null),pd=Du==="panel",Sd=reactExports.useCallback(async Pd=>{const ud=parseCommand(Pd);if(!ud)return Pu?.(Pd,fd.current),Yu.submit(Pd)||Pu?{handled:!0}:{handled:!1,reason:"Nothing is listening for prompts in this view yet."};const md=ld.current.find(hd=>hd.value.name===ud.name||(hd.value.aliases??[]).includes(ud.name));if(!md)return{handled:!1,command:ud.name,reason:`Unknown command: /${ud.name}. Type /help to see what there is.`};const _d=await md.value.run({workspace:fd.current,argv:ud.argv});return _d?.prompt&&(Pu?.(_d.prompt,fd.current),Yu.submit(_d.prompt)),{handled:!0,command:ud.name,result:_d??void 0}},[Pu,Yu]),wd=reactExports.useMemo(()=>({serverUrl:Au,agentId:Uu,surfaceId:Vu.current,setAgentId:Hu,conversationId:$u,model:Ru,sandbox:Zu,setSandbox:Qu,activeViewType:Gu,setActiveViewType:Ku,prompts:Yu,submit:Sd,viewControls:ed,setViewControls:rd,chatHeaderActions:Bu}),[Au,Uu,$u,Ru,Zu,Gu,Yu,Sd,ed,rd,Bu]);fd.current=wd,ld.current=od;const bd=reactExports.useMemo(()=>Gu||(nd.find(ud=>canOpenView(ud.value,wd))?.value.viewType??""),[Gu,nd,wd]);useReactorEvent(bd?onView(bd):void 0);const Td=jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[Fu,jsxRuntimeExports.jsx(ReactorSlot,{slot:LoopSlots.header,props:{workspace:wd}}),Lu?jsxRuntimeExports.jsx(ViewSwitcher,{views:nd,workspace:wd,compact:pd}):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:[ju&&zu?reactDomExports.createPortal(jsxRuntimeExports.jsx(Box,{display:"flex",alignItems:"center",flexWrap:"wrap",gap:2,children:Td}),zu):null,ju&&zu===void 0?jsxRuntimeExports.jsx(Box,{as:"header",display:"flex",alignItems:"center",justifyContent:pd?"flex-start":"space-between",flexWrap:"wrap",gap:2,px:pd?2:3,py:2,borderBottom:"1px solid",borderColor:"border.default",flex:"0 0 auto",children:Td}):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:bd,props:{viewType:bd,workspace:wd},fallback:jsxRuntimeExports.jsx(Centered,{children:"Loading…"}),empty:jsxRuntimeExports.jsx(Centered,{children:"No view is available yet."}),errorFallback:Pd=>jsxRuntimeExports.jsxs(Centered,{children:["This view failed to load: ",Pd.message]})})}),ad.length>0&&qu&&!pd?jsxRuntimeExports.jsx(SidebarRail,{components:ad,props:{workspace:wd},width:SIDEBAR_WIDTH}):ad.length>0?jsxRuntimeExports.jsx(Box,{as:"aside",flex:"0 0 auto",width:pd?"100%":`${SIDEBAR_WIDTH}px`,minWidth:0,borderLeft:pd?"none":"1px solid",borderTop:pd?"1px solid":"none",borderColor:"border.default",bg:"canvas.subtle",overflowY:"auto",px:3,py:3,children:jsxRuntimeExports.jsx(ReactorSlot,{slot:LoopSlots.sidebar,props:{workspace:wd}})}):null]}),jsxRuntimeExports.jsxs(Box,{flex:"0 0 auto",children:[jsxRuntimeExports.jsx(ReactorSlot,{slot:LoopSlots.footer,props:{workspace:wd}}),jsxRuntimeExports.jsx(ReactorSlot,{slot:LoopSlots.status,props:{workspace:wd}})]}),jsxRuntimeExports.jsx(ReactorSlot,{slot:LoopSlots.root,props:{workspace:wd}})]})}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,[Ou,Pu]=reactExports.useState(!1),Du=reactExports.useRef(!1);reactExports.useEffect(()=>{const Fu=()=>{if(!Du.current)return;const zu=!!document.fullscreenElement&&!!Au.current&&document.fullscreenElement.contains(Au.current);Pu(zu),zu||(Du.current=!1)};return document.addEventListener("fullscreenchange",Fu),()=>document.removeEventListener("fullscreenchange",Fu)},[Au]);const Lu=reactExports.useCallback(()=>{const Fu=fullScreenNode(Au.current);if(Ou){Du.current&&document.fullscreenElement?document.exitFullscreen():Pu(!1);return}if($u||Ru||!Fu?.requestFullscreen){Pu(!0);return}Du.current=!0,Fu.requestFullscreen().then(()=>Pu(!0),()=>{Du.current=!1,Pu(!0)})},[Au,Ou,$u,Ru]),[ju,Bu]=reactExports.useState(0);return reactExports.useEffect(()=>{if(!Ou||Du.current){Bu(0);return}const Fu=()=>Bu(resolveTopOffset(Iu));return Fu(),window.addEventListener("resize",Fu),()=>window.removeEventListener("resize",Fu)},[Ou,Iu]),reactExports.useEffect(()=>{if(!Ru||!Ou||Du.current)return;const Fu=fullScreenNode(Au.current);if(!Fu)return;const zu=Fu.getAttribute("style");return Fu.style.position="fixed",Fu.style.top=`${ju}px`,Fu.style.right="0",Fu.style.bottom="0",Fu.style.left="0",Fu.style.height="auto",Fu.style.zIndex="1000",()=>{zu===null?Fu.removeAttribute("style"):Fu.setAttribute("style",zu)}},[Ru,Ou,Au,ju]),reactExports.useEffect(()=>{if(!Ou||Du.current)return;const Fu=zu=>{zu.key==="Escape"&&!zu.defaultPrevented&&Pu(!1)};return window.addEventListener("keydown",Fu),()=>window.removeEventListener("keydown",Fu)},[Ou]),{fullScreen:Ou,usingApi:Du,toggle:Lu,topOffsetPx:ju}}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]}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:[contribution(LoopViewType,{viewType:"chat",title:"Chat",icon:CommentDiscussionIcon,order:0,load:()=>__vitePreload(()=>import("./chunks/ChatView-Bqiq0mvd.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$5,{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:Ou,transient:Pu,activity:Du,bandMode:Lu="docked",panelMode:ju="docked",panelSide:Bu="right",sheetWidth:Fu=PAGE_SHEET_WIDTH,pageSize:zu,panelWidth:qu=PAGE_PANEL_WIDTH}){const Uu=Lu==="panel",Hu=Ru!=null,{width:Vu,height:Gu}=resolvePageSize(zu,Fu),Zu=useSignalValue$1(pageLayoutPanelOpen)||Uu&&Hu,Qu=useSignalValue$1(pageLayoutActivity),Yu=Du??Qu,ed=lo?"page":"panel";return reactExports.useEffect(()=>{pageLayoutSheet.value=ed},[ed]),jsxRuntimeExports.jsxs(Box$1,{"data-page-layout":"",sx:{position:"relative",flex:"1 1 auto",minHeight:0,display:"flex",flexDirection:"column"},children:[Ou,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&&Lu==="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":Zu?"":void 0,"data-page-panel-mode":ju,"aria-hidden":Zu?void 0:"true",sx:{minWidth:0,minHeight:0,display:"flex",flexDirection:"column",bg:"canvas.default",borderColor:"border.default",...Zu?ju==="docked"?{flex:`0 0 ${qu}px`,maxWidth:"45%",order:Bu==="left"?-1:void 0,[Bu==="left"?"borderRight":"borderLeft"]:"1px solid",zIndex:1}:ju==="overlay"?{position:"absolute",top:0,bottom:0,[Bu]:0,width:qu,maxWidth:"85%",[Bu==="left"?"borderRight":"borderLeft"]:"1px solid",boxShadow:"shadow.large",zIndex:5}:{position:"absolute",[Bu]:16,bottom:16,width:qu,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},...Zu?panelOpening(Bu):null},children:$u}),Hu&&Lu!=="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]})]}),Pu]})}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-DcubnPoo.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$3,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$3}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:Ou}=Au;return reactExports.useEffect(()=>lo?.connect(Ou),[lo,Ou]),reactExports.useEffect(()=>{lo&&Iu({...$u,target:Ru})},[lo,$u,Ru,Iu]),null}const DatalayerAgentBridge=reactExports.lazy(async()=>({default:(await __vitePreload(()=>import("./chunks/DatalayerAgentBridge-BhxfUyb7.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"]),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,Ou]=reactExports.useState(!1),Pu=reactExports.useRef(null),Du=reactExports.useRef(null),Lu=()=>{Du.current!==null&&(window.clearTimeout(Du.current),Du.current=null)},ju=()=>{Lu();const Yu=Pu.current?.getBoundingClientRect();Ou(!!(Yu&&Yu.left+OVERLAY_WIDTH>window.innerWidth)),Ru(!0)},Bu=()=>{Lu(),Du.current=window.setTimeout(()=>{Ru(!1),Du.current=null},300)};reactExports.useEffect(()=>()=>{Lu()},[]);const Fu=Au?.baseUrl?(()=>{const Yu=Au.baseUrl.replace(/\/$/,"");return Yu.endsWith("/api/v1")?Yu:`${Yu}/api/v1`})():void 0,zu=Fu?`${Fu}/runtime/status`:void 0,qu=toSandboxStatusUrl(Au?.sandboxBaseUrl);if(!Au)return null;const Uu=(Au.status||"").toLowerCase(),Hu=!Au.isReady&&!Au.agentId&&CREATING_STATUSES.has(Uu),Vu=!!Au.error,Gu=!!Au.agentId||Hu,Ku=strip(Au.agentName,MAX_AGENT_NAME_LENGTH),Zu=`${Au.agentName} · ${Au.location}`,Qu=`${Ku} · ${Au.location}`;return jsxRuntimeExports.jsxs(Box,{ref:Pu,position:"relative",onMouseEnter:ju,onMouseLeave:Bu,children:[jsxRuntimeExports.jsxs(Box,{as:"button",type:"button",title:Zu,px:2,py:"6px",maxWidth:280,minWidth:0,border:"1px solid",borderColor:Vu?"danger.emphasis":"border.default",borderRadius:2,bg:Vu?"danger.subtle":"canvas.default",color:Vu?"danger.fg":"fg.default",fontSize:0,cursor:"default",display:"flex",alignItems:"center",gap:1,children:[Hu&&jsxRuntimeExports.jsx(StyledSpinner,{size:"small",sx:{width:12,height:12}}),Vu&&jsxRuntimeExports.jsx("span",{"aria-hidden":!0,children:"⚠"}),jsxRuntimeExports.jsx(Box,{as:"span",display:"block",minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",children:Qu})]}),$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: ",Hu?"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:Hu?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:"," ",Gu&&zu?jsxRuntimeExports.jsx(Box,{as:"a",href:zu,target:"_blank",rel:"noopener noreferrer",color:"accent.fg",textDecoration:"underline",children:zu}):"n/a"]}),jsxRuntimeExports.jsxs(Box,{color:"fg.muted",wordBreak:"break-all",children:["Code sandbox status:"," ",qu?jsxRuntimeExports.jsx(Box,{as:"a",href:qu,target:"_blank",rel:"noopener noreferrer",color:"accent.fg",textDecoration:"underline",children:qu}):"n/a"]}),Vu&&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:Ou,jupyterReactStore:Pu,loadJupyterConfig:Du}=await import("./chunks/index-CNx_s591.js").then(Lu=>Lu.r);return{createLiteServiceManager:Ou,jupyterReactStore:Pu,loadJupyterConfig:Du}},[],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})),Ou=computed$1(()=>$u.value==="running");let Pu=null,Du=null,Lu=null,ju=null;async function Bu(){if(Du)return;$u.value="starting",Pu=await Au.acquire();const Fu=await Pu.sessions.startNew({name:"loop",path:"loop.ipynb",type:"notebook",kernel:{name:"python"}});Lu=Fu.kernel,Du=Fu.kernel,lo.value={variant:Au.variant,sandbox_running:!0,kernel_id:Du?.id,kernel_name:"python"},$u.value="running"}return{kind:"browser",snapshot:Iu,status:lo,ready:Ou,lastExecution:Ru,serverUrl:"",getServiceManager:()=>Pu,getKernelConnection:()=>Lu,report(Fu){lo.value=Fu},setState(Fu){$u.value=Fu},connect(){return ju=ju??Bu().catch(Fu=>{throw $u.value="error",lo.value=null,ju=null,Fu}),()=>{Du?.shutdown?.(),Du=null,Lu=null,Pu=Au.owned?null:Pu,Au.release?.(),ju=null,$u.value="idle",lo.value=null}},async execute(Fu){const zu=Date.now();try{if(await(ju??Bu()),!Du)throw new Error("The browser kernel did not start");const qu={outputs:[],stdout:[],error:""},Uu=Du.requestExecute({code:Fu});Uu.onIOPub=Vu=>collect(Vu,qu),await Uu.done;const Hu={code:Fu,success:!qu.error,stdout:qu.stdout.join(""),error:qu.error||void 0,outputs:qu.outputs,startedAt:zu,finishedAt:Date.now()};return Ru.value=Hu,Hu}catch(qu){const Uu={code:Fu,success:!1,error:qu instanceof Error?qu.message:String(qu),startedAt:zu,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),Ou=computed$1(()=>({...summarize(lo.value,$u.value),errorReason:$u.value==="error"?Ru.value:void 0})),Pu=computed$1(()=>Ou.value.state==="running");return{kind:"server",connect(Du){if(typeof WebSocket>"u")return()=>{};let Lu=null,ju=null,Bu=0,Fu=!1;const zu=()=>{if(Fu)return;const qu=Au.replace(/^http/,"ws"),Uu=Du?`?agent_id=${encodeURIComponent(Du)}`:"";Lu=new WebSocket(`${qu}/api/v1/configure/sandbox/ws${Uu}`),Lu.onopen=()=>{Bu=0},Lu.onmessage=Hu=>{try{lo.value=JSON.parse(String(Hu.data))}catch{}},Lu.onclose=()=>{if(Fu)return;lo.value=null,Bu+=1;const Hu=Math.min(RECONNECT_BASE_MS*2**(Bu-1),RECONNECT_MAX_MS);ju=setTimeout(zu,Hu)}};return zu(),()=>{Fu=!0,ju&&clearTimeout(ju),Lu?.close(),Lu=null}},snapshot:Ou,status:lo,ready:Pu,lastExecution:Iu,serverUrl:Au,report(Du){lo.value=Du},setState(Du,Lu){$u.value=Du,Ru.value=Du==="error"?Lu:void 0},async execute(Du){const Lu=Date.now();try{const ju=await fetch(`${Au}/api/v1/sandbox/execute`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({code:Du})}),Bu=ju.ok?await ju.json():null,Fu={code:Du,success:ju.ok&&!Bu?.error,stdout:Bu?.stdout,stderr:Bu?.stderr,error:ju.ok?Bu?.error:`Execution failed: ${ju.status}`,outputs:Bu?.outputs,startedAt:Lu,finishedAt:Date.now()};return Iu.value=Fu,Fu}catch(ju){const Bu={code:Du,success:!1,error:ju instanceof Error?ju.message:String(ju),startedAt:Lu,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 Ou=signal$2(lo),Pu=createServerSandboxService(Au),Du=createBrowserSandboxService($u??browserSource()),Lu=computed$1(()=>Ou.value==="browser"?Du:Pu);let ju=null,Bu;const Fu=computed$1(()=>Lu.value.snapshot.value),zu=computed$1(()=>Lu.value.status.value),qu=computed$1(()=>Lu.value.ready.value),Uu=computed$1(()=>Lu.value.lastExecution.value);async function Hu(Ku){if(Ku==="local"){const Xu=Iu?.()??Ru?.createPayload;Xu&&await Vu(Xu)}const Zu=TARGET_SPECS[Ku]?.configure;if(!Zu)return;const Qu=TARGET_SPECS[Ku].label;let Yu;try{Yu=await fetch(`${Au}/api/v1/agents/sandbox/configure`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(Zu)})}catch(Xu){throw new Error(`${Qu} needs an agent-runtimes server at ${Au}, and nothing answered there. Start one and try again. (${Xu instanceof Error?Xu.message:String(Xu)})`,{cause:Xu})}if(!Yu.ok)throw new Error(`The server could not switch to ${Qu} (${Yu.status} ${Yu.statusText}). `+await detail(Yu));const ed=await fetch(`${Au}/api/v1/agents/sandbox/restart`,{method:"POST"});if(!ed.ok)throw new Error(`The server could not start ${Qu} (${ed.status} ${ed.statusText}). `+await detail(ed))}function Vu(Ku){return ensureServerAgent(Au,Bu,Ku)}function Gu(){if(ju?.(),Ou.peek()==="datalayer"){ju=null,Pu.setState("starting");return}ju=Lu.peek().connect(Bu)}return{get kind(){return Ou.peek()==="browser"?"browser":"server"},target:Ou,snapshot:Fu,status:zu,ready:qu,lastExecution:Uu,serverUrl:Au,getServiceManager:()=>Ou.peek()==="browser"?Du.getServiceManager():null,getKernelConnection:()=>Ou.peek()==="browser"?Du.getKernelConnection():null,report(Ku){Lu.peek().report(Ku)},setState(Ku){Lu.peek().setState(Ku)},execute(Ku){return Lu.peek().execute(Ku)},connect(Ku){Bu=Ku;const Zu=Ou.peek()==="local"&&Ku?Iu?.()??Ru?.createPayload:void 0;if(!Zu)return Gu(),()=>{ju?.(),ju=null};let Qu=!1;return Pu.setState("starting"),Vu(Zu).then(()=>{Qu||Gu()},Yu=>{Qu||(Pu.setState("error"),console.error("[loop] Local agent could not be started:",Yu))}),()=>{Qu=!0,ju?.(),ju=null}},async setTarget(Ku){const Zu=Ou.peek();if(Ku===Zu)return;const Qu=heldTargetReason(Ku,Au);if(Qu)throw new Error(Qu);ju?.(),ju=null;try{await Hu(Ku)}catch(Yu){throw Gu(),Yu}Ou.value=Ku,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(Pu){throw new Error(`Local needs an agent-runtimes server at ${Au}, and nothing answered there. Start one and try again. (${Pu instanceof Error?Pu.message:String(Pu)})`,{cause:Pu})}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 Ou=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(!Ou.ok&&Ou.status!==409)throw new Error(`The server could not launch local agent ${Ru} (${Ou.status} ${Ou.statusText}). `+await detail(Ou));Ou.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 Ou=Au.sandbox,Pu=Iu?.specId||Au.agentId,Du=AGENTSPECS$1[Pu],Lu={agentName:Iu?.name||Du?.name||Au.agentId,location:$u?TARGET_SPECS[$u].label:"—",specId:Pu,harness:Du?.harness,variant:Ou.variant,status:Ou.state,baseUrl:Ou.agentBaseUrl||Au.serverUrl,sandboxBaseUrl:Ou.jupyterUrl,agentId:Au.agentId,isReady:Ou.state==="running"};return jsxRuntimeExports.jsx(AgentSummary,{summary:Lu})}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:Ou=DEFAULT_PULSE_AT,onExpire:Pu}){const[Du,Lu]=reactExports.useState(()=>Date.now()),ju=reactExports.useRef(lo??Math.max(1,Au-Date.now())),Bu=reactExports.useRef(!1);reactExports.useEffect(()=>{const Hu=window.setInterval(()=>{Lu(Vu=>{const Gu=Date.now(),Ku=Zu=>Math.ceil((Au-Zu)/1e3);return Ku(Gu)===Ku(Vu)?Vu:Gu})},250);return()=>window.clearInterval(Hu)},[Au]);const Fu=Math.max(0,Au-Du);reactExports.useEffect(()=>{Fu>0||Bu.current||(Bu.current=!0,Pu?.())},[Fu,Pu]);const zu=Math.min(1,Math.max(0,Fu/ju.current)),qu=zu<=Ou,Uu=zu<=Iu?"danger.fg":zu<=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:{...qu?{"@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-zu),transform:`rotate(-90 ${RING/2} ${RING/2})`,style:{transition:"stroke-dashoffset 0.5s linear"}})]}),jsxRuntimeExports.jsx(Text$5,{sx:{fontSize:0,color:Uu,fontWeight:"semibold"},children:format(Fu)})]})}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$5,{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,Ou]=reactExports.useState(null),Pu=useSignalValue$1(lo?.snapshot??IDLE_SANDBOX_SNAPSHOT_SIGNAL),Du=useSignalValue$1(lo?.status??EMPTY_STATUS),Lu=useSignalValue$1(lo?.target??DEFAULT_TARGET),ju=reactExports.useCallback(async Fu=>{if(!(!lo||Fu===Lu)){Ru(!0),Ou(null);try{await lo.setTarget(Fu)}catch(zu){Ou(zu instanceof Error?zu.message:String(zu))}finally{Ru(!1)}}},[lo,Lu]);if(!lo)return null;const Bu=Math.max(0,SANDBOX_TARGETS.indexOf(Lu));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(Pu.state,Du?.execution_state,Du?.is_executing),kernelId:Pu.kernelId??Du?.kernel_id,kernelName:Du?.kernel_name,serverUrl:Pu.jupyterUrl??Du?.jupyter_url,websocketUrl:toWebsocketUrl(Pu.jupyterUrl??Du?.jupyter_url),environmentName:TARGET_SPECS[Lu].label,overlayTitle:`${TARGET_SPECS[Lu].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((Fu,zu)=>{const qu=heldTargetReason(Fu,lo?.serverUrl??"");return jsxRuntimeExports.jsx(SegmentedControl.Button,{selected:zu===Bu,"aria-disabled":qu?!0:void 0,"data-sandbox-target":Fu,"data-sandbox-target-held":qu?"":void 0,sx:{listStyle:"none",...qu?{color:"fg.subtle",cursor:"not-allowed"}:null},title:qu??TARGET_SPECS[Fu].hint,onClick:()=>qu?void 0:void ju(Fu),children:TARGET_SPECS[Fu].label},Fu)})}),Iu||Pu.errorReason?jsxRuntimeExports.jsx(Text$5,{sx:{fontSize:0,color:"danger.fg",lineHeight:1.3,maxWidth:280,minWidth:0},title:Iu??Pu.errorReason,children:Iu??Pu.errorReason}):jsxRuntimeExports.jsx(Text$5,{sx:{fontSize:0,color:"fg.muted"},title:TARGET_SPECS[SANDBOX_TARGETS[Bu]].hint,children:Pu.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(Ou=>Ou.id===Ru);return jsxRuntimeExports.jsx(AnchoredOverlay,{width:"large",open:lo,onOpen:()=>$u(!0),onClose:()=>$u(!1),renderAnchor:Ou=>jsxRuntimeExports.jsx(IconButton,{...Ou,"aria-labelledby":void 0,icon:ForwardRef$3,"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(Ou=>jsxRuntimeExports.jsxs(ActionList.Item,{selected:Ou.id===Ru,onSelect:()=>{Au.select(Ou.id),$u(!1)},children:[jsxRuntimeExports.jsx(ActionList.LeadingVisual,{children:jsxRuntimeExports.jsx(MemberIcon,{icon:Ou.icon})}),jsxRuntimeExports.jsxs(Box,{as:"span",display:"flex",alignItems:"center",gap:2,children:[Ou.name,Ou.isSupervisor?jsxRuntimeExports.jsx(Text$5,{sx:{fontSize:0,color:"fg.muted"},children:"supervisor"}):null]}),Ou.description?jsxRuntimeExports.jsx(ActionList.Description,{variant:"block",sx:{display:"block",whiteSpace:"normal",overflowWrap:"anywhere",minWidth:0},children:Ou.description}):null]},Ou.id))]})})})}function specIdOf(Au){return(Au??"").split(":")[0]??""}function teamMembers(Au){const lo=specIdOf(Au.supervisor?.ref),$u=Iu=>{const Ou=AGENTSPECS$1[Iu];return{description:Ou?.description,emoji:Ou?.emoji,icon:Ou?.icon}},Ru=(Au.agents??[]).map(Iu=>{const Ou=specIdOf(Iu.ref);return{id:Iu.id,name:Iu.name||Ou||Iu.id,specId:Ou,isSupervisor:Ou!==""&&Ou===lo,...$u(Ou)}});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(Ou=>Ou.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(Lu=>Lu.id===lo);if(!Ru)return[];const Iu=(Lu,ju,Bu)=>{const Fu=AGENTSPECS$1[ju];if(Fu)return{name:Lu,description:Bu||Fu.description||Lu,instructions:Fu.systemPrompt,model:Fu.model,icon:Fu.icon}},Ou=Ru.isSupervisor||Au.delegation?.allowPeerDelegation?$u.filter(Lu=>Lu.id!==lo).map(Lu=>Iu(Lu.name,Lu.specId,Lu.description)):[],Du=((Au.agents??[]).find(Lu=>Lu.id===lo)?.subagents??[]).map(Lu=>Iu(Lu.name,(Lu.ref??"").split(":")[0]??"",Lu.description));return[...Ou,...Du].filter(Boolean)}const 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-IYT-IKM6.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} {
|
|
3600
3600
|
0%, 100% { opacity: 0.25; }
|
|
3601
3601
|
50% { opacity: 1; }
|
|
3602
3602
|
}`;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(Lu=>Lu.name===Ru),Ou=agentIcon(Iu?.icon);if(!Au)return null;const Du=lo.some(Lu=>Lu.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:Du,direction:"n",children:jsxRuntimeExports.jsx(Box,{as:"button",type:"button","aria-label":Du,"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(Ou,{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-BmARc3pT.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:Ou=!0}){const Pu=useContributions(Au),Du=reactExports.useSyncExternalStore(subscribeViewChoice,getViewChoice),[Lu,ju]=reactExports.useState(null),Bu=reactExports.useRef(null),Fu=()=>{Bu.current!==null&&(window.clearTimeout(Bu.current),Bu.current=null)},zu=Vu=>{Fu(),ju(Vu)},qu=()=>{Fu(),Bu.current=window.setTimeout(()=>{ju(null),Bu.current=null},250)};reactExports.useEffect(()=>Fu,[]);const Uu=reactExports.useMemo(()=>Pu.map(Vu=>lo(Vu.value,$u)).sort((Vu,Gu)=>(Vu.order??100)-(Gu.order??100)),[Pu,lo,$u]);if(reactExports.useEffect(()=>{setViewOptions(Uu.map(Vu=>Vu.id),Ou)},[Uu,Ou]),Uu.length<(Ou?1:2))return null;const Hu=Uu.find(Vu=>Vu.id===Lu&&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:[Ou?jsxRuntimeExports.jsx(SegmentedControl.Button,{selected:Du.viewId===NONE_VIEW,onClick:()=>chooseView(NONE_VIEW),children:Ru}):null,Uu.map(Vu=>jsxRuntimeExports.jsx(SegmentedControl.Button,{selected:Du.viewId===Vu.id,"aria-disabled":Vu.disabled||void 0,title:Vu.disabled?Vu.disabledReason:Vu.title,leadingIcon:Vu.icon,onMouseEnter:Vu.details?()=>zu(Vu.id):void 0,onMouseLeave:Vu.details?qu: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:Fu,onMouseLeave:qu,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-CNx_s591.js").then(Au=>Au.r),[],import.meta.url).then(Au=>(jupyterReact=Au,Au))}const PREVIEW_LENGTH=56;function stripped(Au){const $u=(Au.split(`
|
|
@@ -3766,7 +3766,7 @@ ${Du}`:zu,inputs:Du,clear:Pu?[]:[DRAFT.path],loop:Bu()}:{refused:"Nothing to sen
|
|
|
3766
3766
|
|
|
3767
3767
|
${$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 Ou=$u.find(Pu=>Pu.id===Ru);if(!Ou)throw new Error(`${Au.name} has no mode “${Ru}”.`);if(!Ou.options.some(Pu=>Pu.id===Iu))throw new Error(`The mode ${Ou.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),Ou=(Au.interface.modes??[]).flatMap(Lu=>Lu.options.filter(ju=>ju.id===Ru[Lu.id])),Pu=[Iu?.instructions??"",...Ou.map(Lu=>Lu.instructions??"")].map(Lu=>Lu.trim()).filter(Boolean).join(`
|
|
3768
3768
|
|
|
3769
|
-
`),Du=Ou.find(Lu=>Lu.model)?.model??Iu?.model??void 0;return Du?{instructions:Pu,model:Du}:{instructions:Pu}}async function holdUploads(Au,lo,$u,Ru=readFile){const Iu=uploadsRefusal(Au,[...lo,...$u.map(Ou=>({name:Ou.name,type:Ou.type,size:Ou.size}))]);return Iu?{files:[...lo],refused:Iu}:{files:[...lo,...await Promise.all($u.map(Ru))],refused:null}}const APP_COMPOSER_PLUGIN_NAME="@datalayer/loop-plugin-app-composer";function startersAsOpeners(Au){return Au.map(lo=>({text:lo.label,message:lo.message,...lo.category?{group:lo.category}:{}}))}const needsAppComposer=Au=>(Au.interface.commands??[]).length>0||(Au.interface.modes??[]).length>0||(Au.interface.profiles??[]).length>0||!!Au.interface.uploads;function defineAppComposerPlugin(Au){const lo=Au.interface.profiles??[],$u=signal$2(profileChoice(Au)?.id),Ru=signal$2(!1),Iu=computed$1(()=>({openers:startersAsOpeners(startersFor(Au,$u.value))}));function Ou(){const zu=interfaceWords(useChatLanguage()),qu=profileChoice(Au,useSignalValue$1($u)),Uu=useSignalValue$1(Ru);if(!qu)return null;const Hu=`${zu.profile}: ${qu.label}`;return Uu?jsxRuntimeExports.jsx(Text$5,{title:`${Hu} (${zu.profileKept})`,sx:{fontSize:0,color:"fg.muted",px:2},children:Hu}):jsxRuntimeExports.jsxs(ActionMenu,{children:[jsxRuntimeExports.jsx(ActionMenu.Button,{size:"small",variant:"invisible","aria-label":Hu,children:Hu}),jsxRuntimeExports.jsx(ActionMenu.Overlay,{width:"medium",children:jsxRuntimeExports.jsx(ActionList,{selectionVariant:"single",children:jsxRuntimeExports.jsxs(ActionList.Group,{children:[jsxRuntimeExports.jsx(ActionList.GroupHeading,{children:zu.profile}),lo.map(Vu=>jsxRuntimeExports.jsxs(ActionList.Item,{selected:Vu.id===qu.id,onSelect:()=>{$u.value=profileChoice(Au,Vu.id)?.id},children:[Vu.label,Vu.description?jsxRuntimeExports.jsx(ActionList.Description,{variant:"block",children:Vu.description}):null]},Vu.id))]})})})]})}const Pu=Au.interface.modes??[],Du=signal$2(modeDefaults(Au));function Lu(){const zu=useSignalValue$1(Du);return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:Pu.map(qu=>{const Uu=qu.options.find(Hu=>Hu.id===zu[qu.id])??qu.options[0];return jsxRuntimeExports.jsxs(ActionMenu,{children:[jsxRuntimeExports.jsxs(ActionMenu.Button,{size:"small",variant:"invisible","aria-label":`${qu.label}: ${Uu.label}`,children:[qu.label,": ",Uu.label]}),jsxRuntimeExports.jsx(ActionMenu.Overlay,{width:"medium",children:jsxRuntimeExports.jsx(ActionList,{selectionVariant:"single",children:jsxRuntimeExports.jsxs(ActionList.Group,{children:[jsxRuntimeExports.jsx(ActionList.GroupHeading,{children:qu.label}),qu.options.map(Hu=>jsxRuntimeExports.jsxs(ActionList.Item,{selected:Hu.id===Uu.id,onSelect:()=>{Du.value=modeChoice(Au,{...Du.peek(),[qu.id]:Hu.id})},children:[Hu.label,Hu.description?jsxRuntimeExports.jsx(ActionList.Description,{variant:"block",children:Hu.description}):null]},Hu.id))]})})})]},qu.id)})})}const ju=Au.interface.uploads,Bu=signal$2({files:[],refused:null});function Fu(){const zu=interfaceWords(useChatLanguage()),qu=useSignalValue$1(Bu),Uu=reactExports.useRef(null);return ju?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(IconButton,{icon:PaperclipIcon,size:"small",variant:"invisible","aria-label":`${zu.attach}. ${uploadsInWords(ju)}`,onClick:()=>Uu.current?.click()}),jsxRuntimeExports.jsx("input",{ref:Uu,type:"file",hidden:!0,multiple:ju.maxFiles>1,accept:uploadsAccept(ju),"aria-label":zu.attach,onChange:Hu=>{const Vu=Array.from(Hu.target.files??[]);Hu.target.value="",holdUploads(Au,Bu.peek().files,Vu).then(Gu=>{Bu.value=Gu})}}),qu.files.map(Hu=>jsxRuntimeExports.jsx(Token$3,{text:Hu.name,size:"small",onRemove:()=>{Bu.value={files:Bu.peek().files.filter(Vu=>Vu!==Hu),refused:null}}},Hu.name)),qu.refused?jsxRuntimeExports.jsx(Text$5,{role:"alert",sx:{fontSize:0,color:"danger.fg"},children:qu.refused}):null]}):null}return{name:`${APP_COMPOSER_PLUGIN_NAME}-${Au.id}`,displayName:`${Au.name}: commands, modes, profiles and uploads`,description:`The commands, modes, profiles and files ${Au.name} takes in its composer.`,octicon:"command-palette",emoji:"⌘",contributes:[...lo.length>0?[contribution(LoopRunProps,{id:"app-profile",props:()=>(Ru.value=!0,{loop:{profile:$u.peek()}})},{id:"app-profile"}),contribution(LoopChatExtras,{id:"app-profile-starters",extras:Iu},{id:"app-profile-starters"})]:[],...(Au.interface.commands??[]).map(zu=>contribution(LoopCommand,{name:zu.name,description:zu.description,group:Au.name,composer:!0,run:async({argv:qu})=>({prompt:commandPrompt(zu,qu)})},{id:`app-command-${zu.name}`})),...Pu.length>0?[contribution(LoopRunProps,{id:"app-modes",props:()=>({loop:{modes:{...Du.peek()}}})},{id:"app-modes"})]:[],...ju?[contribution(LoopRunProps,{id:"app-uploads",props:()=>{const zu=Bu.peek().files;return zu.length===0?{}:(Bu.value={files:[],refused:null},{loop:{files:zu}})}},{id:"app-uploads"})]:[]],build:()=>({components:[...lo.length>0?[{id:"app-profile",slot:LoopSlots.promptAction,order:3,Component:Ou}]:[],...Pu.length>0?[{id:"app-modes",slot:LoopSlots.promptAction,order:5,Component:Lu}]:[],...ju?[{id:"app-uploads",slot:LoopSlots.promptAction,order:4,Component:Fu}]:[]]})}}const FEEDBACK_COMMENT_LIMIT=2e3,answerIdOf=Au=>Au>0?`answer-${Au}`:void 0,FEEDBACK_WORDS={ask:"Was this answer useful?",liked:"This answer was useful",disliked:"This answer was not useful",comment:"Anything to add? (optional)",send:"Send",kept:Au=>`Thank you. Kept in ${Au}’s record.`,where:Au=>`What you say is kept with this conversation in ${Au}’s record, for its builder to read.`,tooLong:`A comment is at most ${FEEDBACK_COMMENT_LIMIT} characters.`,noRuntime:"No runtime is assigned to this conversation, so nothing can be sent.",noSession:"This conversation has no name the application knows yet: send a message first."},keepsFeedback=Au=>(Au.record?.include??[]).includes("feedback"),feedbackEndpoint=Au=>`${Au.replace(/\/+$/,"")}/api/v1/apps/feedback`;function feedbackProblems(Au){const lo=[];return Au.session.trim()||lo.push(FEEDBACK_WORDS.noSession),Au.comment.trim().length>FEEDBACK_COMMENT_LIMIT&&lo.push(FEEDBACK_WORDS.tooLong),lo}async function sendFeedback(Au,{agentBaseUrl:lo,token:$u,fetcher:Ru=fetch}){const Iu=feedbackProblems(Au);if(Iu.length)throw new Error(Iu.join(" "));const Ou=await Ru(feedbackEndpoint(lo),{method:"POST",headers:{"Content-Type":"application/json",...$u?{Authorization:`Bearer ${$u}`}:{}},body:JSON.stringify({session:Au.session,liked:Au.liked,comment:Au.comment.trim(),...Au.message?{message:Au.message}:{}})}),Pu=await Ou.json().catch(()=>({}));if(!Ou.ok){const Du=typeof Pu.detail=="string"?Pu.detail:`${Ou.status}`;throw new Error(`The feedback was not kept: ${Du}`)}return String(Pu.summary??"")}const APP_FEEDBACK_PLUGIN_NAME="@datalayer/loop-plugin-app-feedback",NO_TURN$1=signal$2({id:0,status:"idle"}),NO_CONVERSATION=signal$2([]);function AppFeedback({app:Au,workspace:lo}){const $u=useContributions(LoopChatTurn),Ru=useSignalValue$1($u[0]?.value.turn??NO_TURN$1),Ou=useSignalValue$1($u[0]?.value.conversation??NO_CONVERSATION).filter(Ku=>Ku.role==="assistant").length,Pu=useIAMStore(Ku=>Ku.token),[Du,Lu]=reactExports.useState(null),[ju,Bu]=reactExports.useState(""),[Fu,zu]=reactExports.useState(null);if(Ru.status!=="done"||!Ru.assistant||!Ru.thread)return null;const qu=Ru.thread,Uu=Du?.turn===Ru.id?Du.liked:null,Hu=Fu?.turn===Ru.id?Fu:null,Vu=agentServerOf(lo.sandbox,lo.serverUrl),Gu=async()=>{if(Uu!==null){if(Vu===void 0){zu({turn:Ru.id,state:"refused",says:FEEDBACK_WORDS.noRuntime});return}zu({turn:Ru.id,state:"sending",says:""});try{await sendFeedback({session:qu,liked:Uu,comment:ju,message:answerIdOf(Ou)},{agentBaseUrl:Vu,token:Pu}),zu({turn:Ru.id,state:"kept",says:FEEDBACK_WORDS.kept(Au.name)}),Bu("")}catch(Ku){zu({turn:Ru.id,state:"refused",says:Ku instanceof Error?Ku.message:String(Ku)})}}};return Hu?.state==="kept"?jsxRuntimeExports.jsx("div",{style:{padding:"4px 8px"},children:jsxRuntimeExports.jsx(Text$5,{sx:{fontSize:0,color:"fg.muted"},children:Hu.says})}):jsxRuntimeExports.jsxs("div",{role:"group","aria-label":FEEDBACK_WORDS.ask,style:{display:"flex",flexDirection:"column",gap:4,padding:"4px 8px"},children:[jsxRuntimeExports.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4},children:[jsxRuntimeExports.jsx(Text$5,{sx:{fontSize:0,color:"fg.muted"},children:FEEDBACK_WORDS.ask}),jsxRuntimeExports.jsx(IconButton,{size:"small",variant:Uu===!0?"default":"invisible",icon:ThumbsupIcon,"aria-label":FEEDBACK_WORDS.liked,"aria-pressed":Uu===!0,unsafeDisableTooltip:!0,onClick:()=>Lu({turn:Ru.id,liked:!0})}),jsxRuntimeExports.jsx(IconButton,{size:"small",variant:Uu===!1?"default":"invisible",icon:ThumbsdownIcon,"aria-label":FEEDBACK_WORDS.disliked,"aria-pressed":Uu===!1,unsafeDisableTooltip:!0,onClick:()=>Lu({turn:Ru.id,liked:!1})})]}),Uu!==null?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(Textarea,{"aria-label":FEEDBACK_WORDS.comment,placeholder:FEEDBACK_WORDS.comment,value:ju,rows:2,resize:"vertical",block:!0,onChange:Ku=>Bu(Ku.target.value)}),jsxRuntimeExports.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[jsxRuntimeExports.jsx(ButtonComponent,{size:"small",variant:"default",disabled:Hu?.state==="sending",onClick:()=>{Gu()},children:FEEDBACK_WORDS.send}),jsxRuntimeExports.jsx(Text$5,{sx:{fontSize:0,color:"fg.muted"},children:FEEDBACK_WORDS.where(Au.name)})]})]}):null,Hu?.state==="refused"?jsxRuntimeExports.jsx(Text$5,{role:"alert",sx:{fontSize:0,color:"fg.default"},children:Hu.says}):null]})}function defineAppFeedbackPlugin(Au){function lo({workspace:$u}){return jsxRuntimeExports.jsx(AppFeedback,{app:Au,workspace:$u})}return{name:`${APP_FEEDBACK_PLUGIN_NAME}-${Au.id}`,displayName:`${Au.name}: feedback`,description:`A thumb and a comment on each answer of ${Au.name}, kept in its record.`,octicon:"thumbsup",emoji:"👍",contributes:[contribution(LoopPromptPanel,{id:"app-feedback",placement:"above",order:20,Component:lo},{id:"app-feedback"})]}}const KEPT_ITEMS={conversations:"this conversation",actions:"what it does",decisions:"how its rules decided",approvals:"what is approved",checks:"what its checks stopped",outputs:"its answers",feedback:"what you say of its answers"},RETENTION=/^([1-9]\d*)_(day|days|month|months|year|years)$/;function keptForWords(Au){const lo=RETENTION.exec(Au.trim());if(!lo)throw new Error(`Cannot read the retention \`${Au}\`: write 90_days, 18_months or 1_years.`);const $u=Number(lo[1]),Ru=lo[2].replace(/s$/,"");return $u===1?`a ${Ru}`:`${$u} ${Ru}s`}function inWords(Au){return Au.length<2?Au[0]??"":`${Au.slice(0,-1).join(", ")} and ${Au[Au.length-1]}`}function keptBeforeFirstMessage(Au,{visitor:lo=!1}={}){if(lo)return"Nothing of this conversation is kept: you are not signed in.";const $u=Au.name||"This application",Ru=keptForWords(Au.record.keepFor),Iu=Au.record.include.map(Ou=>KEPT_ITEMS[Ou]).filter(Ou=>!!Ou);return Iu.length?`${$u} keeps ${inWords(Iu)} for ${Ru}, then deletes it.`:`${$u} keeps only that this conversation took place, for ${Ru}.`}const beforeFirstMessage=Au=>Au.id===0&&!Au.user,APP_KEPT_PLUGIN_NAME="@datalayer/loop-plugin-app-kept",NO_TURN=signal$2({id:0,status:"idle"});function AppKept({says:Au}){const lo=useContributions(LoopChatTurn),$u=useSignalValue$1(lo[0]?.value.turn??NO_TURN);return beforeFirstMessage($u)?jsxRuntimeExports.jsx("div",{role:"note",style:{padding:"4px 8px"},children:jsxRuntimeExports.jsx(Text$5,{sx:{fontSize:0,color:"fg.muted"},children:Au})}):null}function defineAppKeptPlugin(Au,lo){function $u(){return jsxRuntimeExports.jsx(AppKept,{says:lo})}return{name:`${APP_KEPT_PLUGIN_NAME}-${Au.id}`,displayName:`${Au.name}: what it keeps`,description:`What ${Au.name} keeps of a conversation, and for how long, said before the first message.`,octicon:"archive",emoji:"🗄",contributes:[contribution(LoopPromptPanel,{id:"app-kept",placement:"below",order:30,Component:$u},{id:"app-kept"})]}}const appPluginName=Au=>`loop-app-${Au}`;function appPluginPair(Au){const lo=appPluginName(Au);return{page:{name:lo,requiredBackendPlugins:[lo]},server:{name:lo,frontendDependencies:[lo]},extension:lo}}const appPluginsBase=(Au,lo)=>`${Au.replace(/\/+$/,"")}/api/v1/apps/${encodeURIComponent(lo)}`;function appRuntimeOf({target:Au,snapshot:lo,serverUrl:$u}){if(!(!Au||Au==="browser")){if(lo.agentBaseUrl)return lo.agentBaseUrl;if(Au!=="datalayer")return lo.state==="running"&&$u?$u:void 0}}const APP_RUNTIME_PLUGIN_NAME="@datalayer/loop-plugin-app-runtime",runningOf=Au=>lo=>Au.includes(lo);function AppRuntimePlugins({appId:Au,pageSide:lo=!1}){const $u=useReactorPlatform(),Ru=useOptionalSandboxService(),Iu=useSignalValue$1(Ru?.target??IDLE_SANDBOX_TARGET_SIGNAL),Ou=useSignalValue$1(Ru?.snapshot??IDLE_SANDBOX_SNAPSHOT_SIGNAL),Pu=appRuntimeOf({target:Iu,snapshot:Ou,serverUrl:Ru?.serverUrl}),Du=appPluginName(Au);reactExports.useEffect(()=>{Pu||(registerReactor($u,runningOf([Du])),$u.setBackendPlugins([Du]))},[$u,Pu,Du]);const Lu=reactExports.useCallback(ju=>registerReactor($u,runningOf(ju.plugins.filter(Bu=>Bu.enabled).map(Bu=>Bu.name))),[$u]);return useBackendPluginStream(Pu?appPluginsBase(Pu,Au):void 0,{onState:Lu}),reactExports.useEffect(()=>{if(!Pu||!lo)return;let ju=!0;return bootstrapExtensions(appPluginsBase(Pu,Au)).then(Bu=>{for(const Fu of Bu.filter(zu=>zu.name===Du))ju&&$u.install(Fu)}),()=>{ju=!1}},[$u,Pu,Au,Du,lo]),null}function defineAppRuntimePlugin(Au,{pageSide:lo=!1}={}){const $u=()=>jsxRuntimeExports.jsx(AppRuntimePlugins,{appId:Au,pageSide:lo});return{name:APP_RUNTIME_PLUGIN_NAME,displayName:"Its runtime",description:"Tells the application’s page which of its plugins its runtime holds.",octicon:"server",build:()=>({components:[{slot:LoopSlots.status,id:"app-runtime-plugins",Component:$u}]})}}const agentIdOf=Au=>{const lo=Au.agent||Au.team,$u=lo.lastIndexOf(":");return $u>0&&lo.slice($u+1).includes(".")?lo.slice(0,$u):lo};function defineAppPlugin(Au,lo=Au){if(!Au.agent)throw new Error(`“${Au.name}” is run by a team, which the workspace does not run as an application yet.`);const $u=appPluginPair(Au.id);return defineAgentCapacityPlugin({key:`app-${Au.id}`,name:$u.page.name,requiredBackendPlugins:$u.page.requiredBackendPlugins,displayName:lo.name,description:lo.description||`The ${lo.name} application`,specId:agentIdOf(Au),emoji:Au.emoji,createPayload:{name:Au.id,app_spec:dumpAppspec(Au),enable_codemode:!!Au.permissions?.computer?.shell,...Au.model?{model:Au.model}:{}},suggestions:startersAsOpeners(lo.interface.starters),instructions:Au.instructions,model:Au.model,...(Au.interface.modes??[]).length>0||(Au.interface.profiles??[]).length>0?{modeEffect:(Ru,Iu)=>modeEffect(Au,Ru,Iu)}:{}})}function appExtension(Au,lo,$u){return defineExtension({name:appPluginPair(Au.id).extension,displayName:lo.name,description:lo.description||`The ${lo.name} application`,emoji:Au.emoji,version:Au.version,plugins:$u})}function appLayoutOptions(Au){const lo=Au.interface.layout;if(lo==="chat")return{editors:!1,showViewSelector:!1};const $u=hasAppPage(Au);return{editors:!$u,showViewSelector:!$u,...$u?{defaultEditor:APP_PAGE_SURFACE}:{},pageLayout:!0,pageLayoutArrangement:lo==="split"?"split":"page",pageLayoutPrompt:"floating",pageLayoutPromptAnchor:"bottom",pageLayoutTurnPanelFooter:"actions"}}function appPreset(Au,lo={}){if(Au.kind==="decision"){if(!lo.page)throw new Error(`“${Au.name}” is a decision, whose page is drawn by where it runs: none was given here.`);return{plugins:[defineAppHostPagePlugin(Au,lo.page)],workspace:{conversation:!1,editors:!1,showViewSelector:!1}}}const $u=hasAppPage(Au),Ru=lo.shown??Au,Iu=new Set((lo.pluginsOff??[]).map(canvasBlocksPluginName)),Ou=CANVAS_BLOCK_PLUGINS.filter(Pu=>!Iu.has(Pu.name));return{plugins:[defineAppPlugin(Au,Ru),defineAppRuntimePlugin(Au.id,{pageSide:hasFolderModules(Au)}),...$u?[defineAppPagePlugin(Ru),...Ou]:[],...hasCustomComponents(Au)?[defineAppComponentsPlugin(Au)]:[],...needsAppComposer(Au)?[defineAppComposerPlugin(Ru)]:[],...keepsFeedback(Au)?[defineAppFeedbackPlugin(Au)]:[],...lo.kept?[defineAppKeptPlugin(Au,keptBeforeFirstMessage(Au,lo.kept))]:[],...lo.sidebar?[defineAppRulesPlugin(Au),defineAppActivityPlugin(Au,lo.appUid),defineAppComputerPlugin(Au)]:lo.computer?[defineAppComputerPlugin(Au)]:[],AppElementsPlugin],workspace:appLayoutOptions(Au)}}function appDatalayerCreatePayload(Au,lo){return{name:Au.id,transport:"ag-ui",agent_spec_id:agentIdOf(Au),app_spec:dumpAppspec(Au),enable_codemode:!!Au.permissions?.computer?.shell,...lo?{app_instance:{app_uid:lo.appUid??"",deployment_uid:lo.deploymentUid??"",version:lo.version??0,...lo.organizationUid?{organization_uid:lo.organizationUid}:{}}}:{}}}const DATALAYER_BOOTSTRAP_AGENTSPEC="example-simple",NO_PLUGINS$1=[];function appThemeOverrides(Au){const lo=Au.interface?.accent;return lo?{light:themeAccentVars(lo,"light"),dark:themeAccentVars(lo,"dark")}:void 0}function AppRenderer({app:Au,plugins:lo=NO_PLUGINS$1,instance:$u,onPresence:Ru,onSaying:Iu,paused:Ou=!1,sidebar:Pu=!1,computer:Du=!1,frame:Lu=!1,page:ju,pluginsOff:Bu,language:Fu,...zu}){const qu=JSON.stringify(dumpAppspec(Au)),Uu=[...Bu??[]].sort().join(","),Hu=(Fu?[Fu]:preferredLanguages()).join(","),Vu=reactExports.useMemo(()=>translatedAppspec(Au,Hu.split(",").filter(Boolean)),[qu,Hu]),Gu=!!$u?.deploymentUid,Ku=!!zu.datalayerVisitors,Zu=reactExports.useMemo(()=>{try{return appPreset(Au,{page:ju,pluginsOff:Bu,sidebar:Pu,computer:Du,appUid:$u?.appUid,shown:Vu,...Gu?{kept:{visitor:Ku}}:{}})}catch(ld){return{problem:ld instanceof Error?ld.message:String(ld)}}},[qu,Vu,ju,Uu,Pu,Du,$u?.appUid,Gu,Ku]),Qu=reactExports.useMemo(()=>"problem"in Zu?lo:[appExtension(Au,Vu,Zu.plugins),...lo],[Zu,lo]),Yu=!("problem"in Zu)&&Zu.workspace.conversation!==!1,ed=reactExports.useMemo(()=>Yu?appDatalayerCreatePayload(Au,$u):void 0,[qu,Yu,$u?.appUid,$u?.deploymentUid,$u?.version]),Xu=useSystemColorMode(),rd=Au.interface?.theme,nd=rd?.mode==="auto"?Xu:rd?.mode==="light"||rd?.mode==="dark"?rd.mode:void 0,od=Au.interface?.accent,ad=reactExports.useMemo(()=>appThemeOverrides(Au),[od]);return"problem"in Zu?jsxRuntimeExports.jsx("div",{role:"status",style:{padding:16},children:Zu.problem}):jsxRuntimeExports.jsx(ChatLanguage,{language:Fu,children:jsxRuntimeExports.jsx(LoopEmbed,{agentId:Au.id,...Zu.workspace,...Lu?{frameTitle:[Au.emoji,Vu.name].filter(Boolean).join(" ")}:{},sidebarRail:Pu||Du,teamPicker:!1,showAgentVariants:!1,pluginsPanel:!1,datalayerAgentSpecId:DATALAYER_BOOTSTRAP_AGENTSPEC,targetFixed:!0,...rd?{themeVariant:rd.variant}:{},...nd?{colorMode:nd}:{},themeOverrides:ad,presence:{name:Vu.name,face:Au.emoji,welcome:Vu.interface.welcome||Vu.description,paused:Ou,onPresence:Ru,onSaying:Iu},showTokenUsage:!1,datalayerCreatePayload:ed,...zu,plugins:Qu})})}const ASSISTANT_CHARACTERS_PLUGIN_NAME="@datalayer/loop-plugin-assistant-characters",AssistantCharactersPlugin={name:ASSISTANT_CHARACTERS_PLUGIN_NAME,displayName:"Assistant characters",description:"Datalayer's own characters for the floating assistant: a paper clip, a wizard, a cat and the L👀P eyes.",octicon:"paperclip",contributes:ASSISTANT_CHARACTERS.map(Au=>contribution(LoopAssistantCharacter,{id:Au.id,character:Au},{id:Au.id}))};function assistantCharactersOf(Au){return Au.getContributions(LoopAssistantCharacter).map(lo=>lo.value)}function assistantCharactersFrom(Au){const lo=buildReactorFromPlugins(Au);lo.start();try{return assistantCharactersOf(lo)}finally{lo.stop()}}function assistantCharacterFor(Au,lo){const $u=lo.app?"app":lo.person?"person":"default",Ru=lo.app??lo.person??DEFAULT_ASSISTANT_CHARACTER,Iu=Au.find(Pu=>Pu.id===Ru);return Iu?{id:Ru,character:Iu.character,saidBy:$u}:{saidBy:$u,problem:`${$u==="app"?"This application names":$u==="person"?"Your settings name":"The default is"} the character “${Ru}”, which nothing enabled here draws; the characters are ${Au.map(Pu=>Pu.id).join(", ")||"none"}.`}}const EMBED_TAG="datalayer-app",EMBED_ATTRIBUTES={app:"The application’s id on Datalayer.",origin:"Where Datalayer is; the origin the script was loaded from by default.",token:"An embed token for an application that is not public, issued to your server for each visit.",spec:"The address of an Appspec (YAML or JSON) to run, in place of `app`.",mode:"inline, bubble, panel or assistant; the Appspec’s `deployment.embedded.mode` by default, then inline.",accent:"green, rose, sky, lime, sun or violet; the Appspec’s `interface.accent` by default, else the theme’s own colours.",theme:"light, dark or auto (the visitor’s system); auto by default.",font:"A CSS font family for the application’s text; Inter, then the system’s sans-serif, by default.",server:"An agent-runtimes server the application’s agent runs on; a Datalayer runtime by default.",api:"Datalayer’s API, where an application is read with its token; the platform’s by default.",height:"The height of an inline application, in pixels; 640 by default.",resume:"true or false: whether a visit’s conversation is picked up again after the page reloads, kept in the page’s storage; true by default.",language:"The language the visitor reads the application in, as BCP 47 tags it (fr, pt-BR): its translation into it, and the chat’s own words; the visitor’s browser’s by default.","user-token":"A token your server signed with the deployment’s secret, naming your user (HS256: sub, name, exp at most an hour away): what an application that says user: signed opens its session with."},EMBED_OBSERVED_ATTRIBUTES=Object.keys(EMBED_ATTRIBUTES),EMBED_HOST_VARIABLES={accent:"--datalayer-app-accent",font:"--datalayer-app-font",theme:"--datalayer-app-theme"},EMBED_COLOR_MODES=["light","dark","auto"],EMBED_FLOATING_VIEWS={bubble:"floating-small",panel:"panel",assistant:"assistant"};function floatingViewOf(Au){return Au==="inline"?void 0:EMBED_FLOATING_VIEWS[Au]}class EmbedAttributeError extends Error{constructor(lo){super(lo),this.name="EmbedAttributeError"}}function runnable({app:Au,problems:lo}){if(!Au.id)throw new EmbedAttributeError(`datalayer-app: the Appspec names no application${lo.length?` (${lo[0]})`:""}.`);if(Au.kind!=="decision"&&!Au.agent)throw new EmbedAttributeError(`datalayer-app: “${Au.name||Au.id}” names no agent to answer; an embedded application is run by an agent (a team is not supported yet).`);return Au}const listed=Au=>`${Au.slice(0,-1).join(", ")} or ${Au[Au.length-1]}`;function oneOf(Au,lo,$u){const Ru=Au?.trim();if(Ru){if(!lo.includes(Ru))throw new EmbedAttributeError(`datalayer-app: "${Ru}" is not ${$u}; it is ${listed(lo)}.`);return Ru}}function checkedFont(Au){const lo=Au?.trim()??"";if(!lo)return"";if(!/^[\w\s,"'.-]+$/u.test(lo))throw new EmbedAttributeError(`datalayer-app: the font "${lo}" is not a font family; write it as a CSS font-family is written, such as "Georgia, serif".`);return lo}function embedLookOf(Au,lo){const{attributes:$u,variables:Ru={}}=Au,Iu=oneOf($u.mode,APP_EMBED_MODES,"a mode")??lo?.deployment?.embedded?.mode??"inline",Ou=oneOf($u.accent,APP_ACCENTS,"an accent")??oneOf(Ru.accent,APP_ACCENTS,"an accent")??lo?.interface?.accent,Pu=oneOf($u.theme,EMBED_COLOR_MODES,"a theme")??oneOf(Ru.theme,EMBED_COLOR_MODES,"a theme")??lo?.interface?.theme?.mode??"auto",Du=checkedFont($u.font)||checkedFont(Ru.font),Lu=lo?.interface?.theme?.variant??"loop";return{mode:Iu,accent:Ou,colorMode:Pu,font:Du,variant:Lu}}function resumeOf(Au){return oneOf(Au,["true","false"],"a value of resume")!=="false"}function languageOf(Au){const lo=Au?.trim();if(lo){if(!LANGUAGE_TAG.test(lo))throw new EmbedAttributeError(`datalayer-app: "${lo}" is not a language as BCP 47 tags it, such as fr or pt-BR.`);return lo}}function inlineHeightOf(Au){const lo=Number.parseInt(Au??"",10);return Number.isFinite(lo)&&lo>=240?lo:640}const CHAT_EXTRAS_PLUGIN_NAME="@datalayer/loop-plugin-chat-extras";let counter=0;function createChatExtrasPlugin(){const Au=`chat-extras-${counter+=1}`,lo=signal$2({});return{plugin:{name:CHAT_EXTRAS_PLUGIN_NAME,displayName:"Chat Extras",description:"A host example’s live banner and footer status.",octicon:"megaphone",emoji:"📣",contributes:[contribution(LoopChatExtras,{id:Au,extras:lo},{id:Au})]},setExtras:Ru=>{lo.value=Ru}}}const HOST_CONTEXT_TOOL="host_context",hostTool=Au=>`host_${Au}`;function signedUser(Au){return Au?.user==="signed"}const hostRefused=Au=>`No rule of this application names ${Au}: it is left to the person, and the page was not called.`,hostNotAllowed=Au=>`The person did not allow ${Au}: the page was not called.`,confirmOnPage=Au=>typeof window<"u"&&typeof window.confirm=="function"?window.confirm(Au.sentence):!1,actionOf=(Au,lo)=>Au.rules.find($u=>$u.appliesTo.includes(lo))?.action;function hostFrontendTools(Au,lo){const $u=Au.deployment.embedded?.host;if(!$u)return[];const Ru=Pu=>behaviourFor(Au,Pu),Iu=Pu=>Ru(Pu)!=="leave_to_me",Ou=[];$u.context.length>0&&Ou.push({name:HOST_CONTEXT_TOOL,description:`What the page you are embedded in says of its visitor and of itself: ${$u.context.join(", ")}. Read it before answering what depends on them.`,parameters:{type:"object",properties:{}},location:"frontend",handler:async()=>{if(!Iu(HOST_CONTEXT_TOOL))return{error:hostRefused(HOST_CONTEXT_TOOL)};const Pu=lo().context?.()??{},Du={},Lu=[];for(const ju of $u.context)Pu[ju]===void 0?Lu.push(ju):Du[ju]=Pu[ju];return{values:Du,...Lu.length>0?{unsaid:Lu}:{}}}});for(const Pu of $u.functions){const Du=hostTool(Pu.name);Ou.push({name:Du,description:Pu.description,parameters:Pu.parameters,location:"frontend",handler:async Lu=>{const ju=Fu=>(lo().onEvent?.({type:"action",detail:{function:Pu.name,arguments:Lu,...Fu}}),Fu);if(!Iu(Du))return ju({error:hostRefused(Du)});if(Ru(Du)!=="do_it"){const Fu=actionOf(Au,Du)??Pu.description;if(!await(lo().ask??confirmOnPage)({function:Pu.name,arguments:Lu,sentence:`${Fu}? (${Pu.name} with ${JSON.stringify(Lu)})`}))return ju({error:hostNotAllowed(Du)})}const Bu=lo().functions?.[Pu.name];if(!Bu)return ju({error:`The page offers no function ${Pu.name}: it was not called.`});try{return ju({result:await Bu(Lu)})}catch(Fu){return ju({error:`The page's ${Pu.name} failed: ${Fu instanceof Error?Fu.message:String(Fu)}`})}}})}return Ou}function hostUserRunProps(Au,lo){if(signedUser(Au.deployment.embedded?.host))return{id:"host-user",props:()=>{const $u=lo().userToken?.()?.trim();return $u?{loop:{user_token:$u}}:{}}}}function withFace(Au,lo,$u){return!lo||!$u?Au:Object.fromEntries(Object.entries(Au).map(([Ru,Iu])=>[Ru,typeof Iu=="string"?Iu.split($u).join(lo):Iu]))}function faceOf(Au,lo){return Au==="loop"?loopFontFamily:typeof lo.fontFamily=="string"?lo.fontFamily:""}const accentOver=(Au,lo)=>Au?themeAccentVars(Au,lo):{};function embedThemeStyles({accent:Au,font:lo="",variant:$u="loop"}){const Ru=getThemeConfig($u).themeStyles,Iu=Ou=>{const Pu=Ru[Ou];return withFace({...Pu,...accentOver(Au,Ou)},lo,faceOf($u,Pu))};return{...Ru,light:Iu("light"),dark:Iu("dark")}}function embedThemeOverrides({accent:Au,font:lo="",variant:$u="loop"}){const Ru=getThemeConfig($u).themeStyles,Iu=Ou=>{const Pu=Ru[Ou];return{...Object.fromEntries(Object.entries(withFace(Pu,lo,faceOf($u,Pu))).filter(([Lu,ju])=>typeof ju=="string"&&ju!==Pu[Lu])),...accentOver(Au,Ou)}};return{light:Iu("light"),dark:Iu("dark")}}function embedShadowCss(Au){const lo=`
|
|
3769
|
+
`),Du=Ou.find(Lu=>Lu.model)?.model??Iu?.model??void 0;return Du?{instructions:Pu,model:Du}:{instructions:Pu}}async function holdUploads(Au,lo,$u,Ru=readFile){const Iu=uploadsRefusal(Au,[...lo,...$u.map(Ou=>({name:Ou.name,type:Ou.type,size:Ou.size}))]);return Iu?{files:[...lo],refused:Iu}:{files:[...lo,...await Promise.all($u.map(Ru))],refused:null}}const APP_COMPOSER_PLUGIN_NAME="@datalayer/loop-plugin-app-composer";function startersAsOpeners(Au){return Au.map(lo=>({text:lo.label,message:lo.message,...lo.category?{group:lo.category}:{}}))}const needsAppComposer=Au=>(Au.interface.commands??[]).length>0||(Au.interface.modes??[]).length>0||(Au.interface.profiles??[]).length>0||!!Au.interface.uploads;function defineAppComposerPlugin(Au){const lo=Au.interface.profiles??[],$u=signal$2(profileChoice(Au)?.id),Ru=signal$2(!1),Iu=computed$1(()=>({openers:startersAsOpeners(startersFor(Au,$u.value))}));function Ou(){const zu=interfaceWords(useChatLanguage()),qu=profileChoice(Au,useSignalValue$1($u)),Uu=useSignalValue$1(Ru);if(!qu)return null;const Hu=`${zu.profile}: ${qu.label}`;return Uu?jsxRuntimeExports.jsx(Text$5,{title:`${Hu} (${zu.profileKept})`,sx:{fontSize:0,color:"fg.muted",px:2},children:Hu}):jsxRuntimeExports.jsxs(ActionMenu,{children:[jsxRuntimeExports.jsx(ActionMenu.Button,{size:"small",variant:"invisible","aria-label":Hu,children:Hu}),jsxRuntimeExports.jsx(ActionMenu.Overlay,{width:"medium",children:jsxRuntimeExports.jsx(ActionList,{selectionVariant:"single",children:jsxRuntimeExports.jsxs(ActionList.Group,{children:[jsxRuntimeExports.jsx(ActionList.GroupHeading,{children:zu.profile}),lo.map(Vu=>jsxRuntimeExports.jsxs(ActionList.Item,{selected:Vu.id===qu.id,onSelect:()=>{$u.value=profileChoice(Au,Vu.id)?.id},children:[Vu.label,Vu.description?jsxRuntimeExports.jsx(ActionList.Description,{variant:"block",children:Vu.description}):null]},Vu.id))]})})})]})}const Pu=Au.interface.modes??[],Du=signal$2(modeDefaults(Au));function Lu(){const zu=useSignalValue$1(Du);return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:Pu.map(qu=>{const Uu=qu.options.find(Hu=>Hu.id===zu[qu.id])??qu.options[0];return jsxRuntimeExports.jsxs(ActionMenu,{children:[jsxRuntimeExports.jsxs(ActionMenu.Button,{size:"small",variant:"invisible","aria-label":`${qu.label}: ${Uu.label}`,children:[qu.label,": ",Uu.label]}),jsxRuntimeExports.jsx(ActionMenu.Overlay,{width:"medium",children:jsxRuntimeExports.jsx(ActionList,{selectionVariant:"single",children:jsxRuntimeExports.jsxs(ActionList.Group,{children:[jsxRuntimeExports.jsx(ActionList.GroupHeading,{children:qu.label}),qu.options.map(Hu=>jsxRuntimeExports.jsxs(ActionList.Item,{selected:Hu.id===Uu.id,onSelect:()=>{Du.value=modeChoice(Au,{...Du.peek(),[qu.id]:Hu.id})},children:[Hu.label,Hu.description?jsxRuntimeExports.jsx(ActionList.Description,{variant:"block",children:Hu.description}):null]},Hu.id))]})})})]},qu.id)})})}const ju=Au.interface.uploads,Bu=signal$2({files:[],refused:null});function Fu(){const zu=interfaceWords(useChatLanguage()),qu=useSignalValue$1(Bu),Uu=reactExports.useRef(null);return ju?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(IconButton,{icon:PaperclipIcon,size:"small",variant:"invisible","aria-label":`${zu.attach}. ${uploadsInWords(ju)}`,onClick:()=>Uu.current?.click()}),jsxRuntimeExports.jsx("input",{ref:Uu,type:"file",hidden:!0,multiple:ju.maxFiles>1,accept:uploadsAccept(ju),"aria-label":zu.attach,onChange:Hu=>{const Vu=Array.from(Hu.target.files??[]);Hu.target.value="",holdUploads(Au,Bu.peek().files,Vu).then(Gu=>{Bu.value=Gu})}}),qu.files.map(Hu=>jsxRuntimeExports.jsx(Token$3,{text:Hu.name,size:"small",onRemove:()=>{Bu.value={files:Bu.peek().files.filter(Vu=>Vu!==Hu),refused:null}}},Hu.name)),qu.refused?jsxRuntimeExports.jsx(Text$5,{role:"alert",sx:{fontSize:0,color:"danger.fg"},children:qu.refused}):null]}):null}return{name:`${APP_COMPOSER_PLUGIN_NAME}-${Au.id}`,displayName:`${Au.name}: commands, modes, profiles and uploads`,description:`The commands, modes, profiles and files ${Au.name} takes in its composer.`,octicon:"command-palette",emoji:"⌘",contributes:[...lo.length>0?[contribution(LoopRunProps,{id:"app-profile",props:()=>(Ru.value=!0,{loop:{profile:$u.peek()}})},{id:"app-profile"}),contribution(LoopChatExtras,{id:"app-profile-starters",extras:Iu},{id:"app-profile-starters"})]:[],...(Au.interface.commands??[]).map(zu=>contribution(LoopCommand,{name:zu.name,description:zu.description,group:Au.name,composer:!0,run:async({argv:qu})=>({prompt:commandPrompt(zu,qu)})},{id:`app-command-${zu.name}`})),...Pu.length>0?[contribution(LoopRunProps,{id:"app-modes",props:()=>({loop:{modes:{...Du.peek()}}})},{id:"app-modes"})]:[],...ju?[contribution(LoopRunProps,{id:"app-uploads",props:()=>{const zu=Bu.peek().files;return zu.length===0?{}:(Bu.value={files:[],refused:null},{loop:{files:zu}})}},{id:"app-uploads"})]:[]],build:()=>({components:[...lo.length>0?[{id:"app-profile",slot:LoopSlots.promptAction,order:3,Component:Ou}]:[],...Pu.length>0?[{id:"app-modes",slot:LoopSlots.promptAction,order:5,Component:Lu}]:[],...ju?[{id:"app-uploads",slot:LoopSlots.promptAction,order:4,Component:Fu}]:[]]})}}const FEEDBACK_COMMENT_LIMIT=2e3,answerIdOf=Au=>Au>0?`answer-${Au}`:void 0,FEEDBACK_WORDS={ask:"Was this answer useful?",liked:"This answer was useful",disliked:"This answer was not useful",comment:"Anything to add? (optional)",send:"Send",kept:Au=>`Thank you. Kept in ${Au}’s record.`,where:Au=>`What you say is kept with this conversation in ${Au}’s record, for its builder to read.`,tooLong:`A comment is at most ${FEEDBACK_COMMENT_LIMIT} characters.`,noRuntime:"No runtime is assigned to this conversation, so nothing can be sent.",noSession:"This conversation has no name the application knows yet: send a message first."},keepsFeedback=Au=>(Au.record?.include??[]).includes("feedback"),feedbackEndpoint=Au=>`${Au.replace(/\/+$/,"")}/api/v1/apps/feedback`;function feedbackProblems(Au){const lo=[];return Au.session.trim()||lo.push(FEEDBACK_WORDS.noSession),Au.comment.trim().length>FEEDBACK_COMMENT_LIMIT&&lo.push(FEEDBACK_WORDS.tooLong),lo}async function sendFeedback(Au,{agentBaseUrl:lo,token:$u,fetcher:Ru=fetch}){const Iu=feedbackProblems(Au);if(Iu.length)throw new Error(Iu.join(" "));const Ou=await Ru(feedbackEndpoint(lo),{method:"POST",headers:{"Content-Type":"application/json",...$u?{Authorization:`Bearer ${$u}`}:{}},body:JSON.stringify({session:Au.session,liked:Au.liked,comment:Au.comment.trim(),...Au.message?{message:Au.message}:{}})}),Pu=await Ou.json().catch(()=>({}));if(!Ou.ok){const Du=typeof Pu.detail=="string"?Pu.detail:`${Ou.status}`;throw new Error(`The feedback was not kept: ${Du}`)}return String(Pu.summary??"")}const APP_FEEDBACK_PLUGIN_NAME="@datalayer/loop-plugin-app-feedback",NO_TURN$1=signal$2({id:0,status:"idle"}),NO_CONVERSATION=signal$2([]);function AppFeedback({app:Au,workspace:lo}){const $u=useContributions(LoopChatTurn),Ru=useSignalValue$1($u[0]?.value.turn??NO_TURN$1),Ou=useSignalValue$1($u[0]?.value.conversation??NO_CONVERSATION).filter(Ku=>Ku.role==="assistant").length,Pu=useIAMStore(Ku=>Ku.token),[Du,Lu]=reactExports.useState(null),[ju,Bu]=reactExports.useState(""),[Fu,zu]=reactExports.useState(null);if(Ru.status!=="done"||!Ru.assistant||!Ru.thread)return null;const qu=Ru.thread,Uu=Du?.turn===Ru.id?Du.liked:null,Hu=Fu?.turn===Ru.id?Fu:null,Vu=agentServerOf(lo.sandbox,lo.serverUrl),Gu=async()=>{if(Uu!==null){if(Vu===void 0){zu({turn:Ru.id,state:"refused",says:FEEDBACK_WORDS.noRuntime});return}zu({turn:Ru.id,state:"sending",says:""});try{await sendFeedback({session:qu,liked:Uu,comment:ju,message:answerIdOf(Ou)},{agentBaseUrl:Vu,token:Pu}),zu({turn:Ru.id,state:"kept",says:FEEDBACK_WORDS.kept(Au.name)}),Bu("")}catch(Ku){zu({turn:Ru.id,state:"refused",says:Ku instanceof Error?Ku.message:String(Ku)})}}};return Hu?.state==="kept"?jsxRuntimeExports.jsx("div",{style:{padding:"4px 8px"},children:jsxRuntimeExports.jsx(Text$5,{sx:{fontSize:0,color:"fg.muted"},children:Hu.says})}):jsxRuntimeExports.jsxs("div",{role:"group","aria-label":FEEDBACK_WORDS.ask,style:{display:"flex",flexDirection:"column",gap:4,padding:"4px 8px"},children:[jsxRuntimeExports.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4},children:[jsxRuntimeExports.jsx(Text$5,{sx:{fontSize:0,color:"fg.muted"},children:FEEDBACK_WORDS.ask}),jsxRuntimeExports.jsx(IconButton,{size:"small",variant:Uu===!0?"default":"invisible",icon:ThumbsupIcon,"aria-label":FEEDBACK_WORDS.liked,"aria-pressed":Uu===!0,unsafeDisableTooltip:!0,onClick:()=>Lu({turn:Ru.id,liked:!0})}),jsxRuntimeExports.jsx(IconButton,{size:"small",variant:Uu===!1?"default":"invisible",icon:ThumbsdownIcon,"aria-label":FEEDBACK_WORDS.disliked,"aria-pressed":Uu===!1,unsafeDisableTooltip:!0,onClick:()=>Lu({turn:Ru.id,liked:!1})})]}),Uu!==null?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(Textarea,{"aria-label":FEEDBACK_WORDS.comment,placeholder:FEEDBACK_WORDS.comment,value:ju,rows:2,resize:"vertical",block:!0,onChange:Ku=>Bu(Ku.target.value)}),jsxRuntimeExports.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[jsxRuntimeExports.jsx(ButtonComponent,{size:"small",variant:"default",disabled:Hu?.state==="sending",onClick:()=>{Gu()},children:FEEDBACK_WORDS.send}),jsxRuntimeExports.jsx(Text$5,{sx:{fontSize:0,color:"fg.muted"},children:FEEDBACK_WORDS.where(Au.name)})]})]}):null,Hu?.state==="refused"?jsxRuntimeExports.jsx(Text$5,{role:"alert",sx:{fontSize:0,color:"fg.default"},children:Hu.says}):null]})}function defineAppFeedbackPlugin(Au){function lo({workspace:$u}){return jsxRuntimeExports.jsx(AppFeedback,{app:Au,workspace:$u})}return{name:`${APP_FEEDBACK_PLUGIN_NAME}-${Au.id}`,displayName:`${Au.name}: feedback`,description:`A thumb and a comment on each answer of ${Au.name}, kept in its record.`,octicon:"thumbsup",emoji:"👍",contributes:[contribution(LoopPromptPanel,{id:"app-feedback",placement:"above",order:20,Component:lo},{id:"app-feedback"})]}}const KEPT_ITEMS={conversations:"this conversation",actions:"what it does",decisions:"how its rules decided",approvals:"what is approved",checks:"what its checks stopped",outputs:"its answers",feedback:"what you say of its answers"},RETENTION=/^([1-9]\d*)_(day|days|month|months|year|years)$/;function keptForWords(Au){const lo=RETENTION.exec(Au.trim());if(!lo)throw new Error(`Cannot read the retention \`${Au}\`: write 90_days, 18_months or 1_years.`);const $u=Number(lo[1]),Ru=lo[2].replace(/s$/,"");return $u===1?`a ${Ru}`:`${$u} ${Ru}s`}function inWords(Au){return Au.length<2?Au[0]??"":`${Au.slice(0,-1).join(", ")} and ${Au[Au.length-1]}`}function keptBeforeFirstMessage(Au,{visitor:lo=!1}={}){if(lo)return"Nothing of this conversation is kept: you are not signed in.";const $u=Au.name||"This application",Ru=keptForWords(Au.record.keepFor),Iu=Au.record.include.map(Ou=>KEPT_ITEMS[Ou]).filter(Ou=>!!Ou);return Iu.length?`${$u} keeps ${inWords(Iu)} for ${Ru}, then deletes it.`:`${$u} keeps only that this conversation took place, for ${Ru}.`}const beforeFirstMessage=Au=>Au.id===0&&!Au.user,APP_KEPT_PLUGIN_NAME="@datalayer/loop-plugin-app-kept",NO_TURN=signal$2({id:0,status:"idle"});function AppKept({says:Au}){const lo=useContributions(LoopChatTurn),$u=useSignalValue$1(lo[0]?.value.turn??NO_TURN);return beforeFirstMessage($u)?jsxRuntimeExports.jsx("div",{role:"note",style:{padding:"4px 8px"},children:jsxRuntimeExports.jsx(Text$5,{sx:{fontSize:0,color:"fg.muted"},children:Au})}):null}function defineAppKeptPlugin(Au,lo){function $u(){return jsxRuntimeExports.jsx(AppKept,{says:lo})}return{name:`${APP_KEPT_PLUGIN_NAME}-${Au.id}`,displayName:`${Au.name}: what it keeps`,description:`What ${Au.name} keeps of a conversation, and for how long, said before the first message.`,octicon:"archive",emoji:"🗄",contributes:[contribution(LoopPromptPanel,{id:"app-kept",placement:"below",order:30,Component:$u},{id:"app-kept"})]}}const appPluginName=Au=>`loop-app-${Au}`;function appPluginPair(Au){const lo=appPluginName(Au);return{page:{name:lo,requiredBackendPlugins:[lo]},server:{name:lo,frontendDependencies:[lo]},extension:lo}}const appPluginsBase=(Au,lo)=>`${Au.replace(/\/+$/,"")}/api/v1/apps/${encodeURIComponent(lo)}`;function appRuntimeOf({target:Au,snapshot:lo,serverUrl:$u}){if(!(!Au||Au==="browser")){if(lo.agentBaseUrl)return lo.agentBaseUrl;if(Au!=="datalayer")return lo.state==="running"&&$u?$u:void 0}}const APP_RUNTIME_PLUGIN_NAME="@datalayer/loop-plugin-app-runtime",runningOf=Au=>lo=>Au.includes(lo);function AppRuntimePlugins({appId:Au,pageSide:lo=!1}){const $u=useReactorPlatform(),Ru=useOptionalSandboxService(),Iu=useSignalValue$1(Ru?.target??IDLE_SANDBOX_TARGET_SIGNAL),Ou=useSignalValue$1(Ru?.snapshot??IDLE_SANDBOX_SNAPSHOT_SIGNAL),Pu=appRuntimeOf({target:Iu,snapshot:Ou,serverUrl:Ru?.serverUrl}),Du=appPluginName(Au);reactExports.useEffect(()=>{Pu||(registerReactor($u,runningOf([Du])),$u.setBackendPlugins([Du]))},[$u,Pu,Du]);const Lu=reactExports.useCallback(ju=>registerReactor($u,runningOf(ju.plugins.filter(Bu=>Bu.enabled).map(Bu=>Bu.name))),[$u]);return useBackendPluginStream(Pu?appPluginsBase(Pu,Au):void 0,{onState:Lu}),reactExports.useEffect(()=>{if(!Pu||!lo)return;let ju=!0;return bootstrapExtensions(appPluginsBase(Pu,Au)).then(Bu=>{for(const Fu of Bu.filter(zu=>zu.name===Du))ju&&$u.install(Fu)}),()=>{ju=!1}},[$u,Pu,Au,Du,lo]),null}function defineAppRuntimePlugin(Au,{pageSide:lo=!1}={}){const $u=()=>jsxRuntimeExports.jsx(AppRuntimePlugins,{appId:Au,pageSide:lo});return{name:APP_RUNTIME_PLUGIN_NAME,displayName:"Its runtime",description:"Tells the application’s page which of its plugins its runtime holds.",octicon:"server",build:()=>({components:[{slot:LoopSlots.status,id:"app-runtime-plugins",Component:$u}]})}}const agentIdOf=Au=>{const lo=Au.agent||Au.team,$u=lo.lastIndexOf(":");return $u>0&&lo.slice($u+1).includes(".")?lo.slice(0,$u):lo};function defineAppPlugin(Au,lo=Au){if(!Au.agent)throw new Error(`“${Au.name}” is run by a team, which the workspace does not run as an application yet.`);const $u=appPluginPair(Au.id);return defineAgentCapacityPlugin({key:`app-${Au.id}`,name:$u.page.name,requiredBackendPlugins:$u.page.requiredBackendPlugins,displayName:lo.name,description:lo.description||`The ${lo.name} application`,specId:agentIdOf(Au),emoji:Au.emoji,createPayload:{name:Au.id,app_spec:dumpAppspec(Au),enable_codemode:!!Au.permissions?.computer?.shell,...Au.model?{model:Au.model}:{}},suggestions:startersAsOpeners(lo.interface.starters),instructions:Au.instructions,model:Au.model,...(Au.interface.modes??[]).length>0||(Au.interface.profiles??[]).length>0?{modeEffect:(Ru,Iu)=>modeEffect(Au,Ru,Iu)}:{}})}function appExtension(Au,lo,$u){return defineExtension({name:appPluginPair(Au.id).extension,displayName:lo.name,description:lo.description||`The ${lo.name} application`,emoji:Au.emoji,version:Au.version,plugins:$u})}function appLayoutOptions(Au){const lo=Au.interface.layout;if(lo==="chat")return{editors:!1,showViewSelector:!1};const $u=hasAppPage(Au);return{editors:!$u,showViewSelector:!$u,...$u?{defaultEditor:APP_PAGE_SURFACE}:{},pageLayout:!0,pageLayoutArrangement:lo==="split"?"split":"page",pageLayoutPrompt:"floating",pageLayoutPromptAnchor:"bottom",pageLayoutTurnPanelFooter:"actions"}}function appPreset(Au,lo={}){if(Au.kind==="decision"){if(!lo.page)throw new Error(`“${Au.name}” is a decision, whose page is drawn by where it runs: none was given here.`);return{plugins:[defineAppHostPagePlugin(Au,lo.page)],workspace:{conversation:!1,editors:!1,showViewSelector:!1}}}const $u=hasAppPage(Au),Ru=lo.shown??Au,Iu=new Set((lo.pluginsOff??[]).map(canvasBlocksPluginName)),Ou=CANVAS_BLOCK_PLUGINS.filter(Pu=>!Iu.has(Pu.name));return{plugins:[defineAppPlugin(Au,Ru),defineAppRuntimePlugin(Au.id,{pageSide:hasFolderModules(Au)}),...$u?[defineAppPagePlugin(Ru),...Ou]:[],...hasCustomComponents(Au)?[defineAppComponentsPlugin(Au)]:[],...needsAppComposer(Au)?[defineAppComposerPlugin(Ru)]:[],...keepsFeedback(Au)?[defineAppFeedbackPlugin(Au)]:[],...lo.kept?[defineAppKeptPlugin(Au,keptBeforeFirstMessage(Au,lo.kept))]:[],...lo.sidebar?[defineAppRulesPlugin(Au),defineAppActivityPlugin(Au,lo.appUid),defineAppComputerPlugin(Au)]:lo.computer?[defineAppComputerPlugin(Au)]:[],AppElementsPlugin],workspace:appLayoutOptions(Au)}}function appDatalayerCreatePayload(Au,lo){return{name:Au.id,transport:"ag-ui",agent_spec_id:agentIdOf(Au),app_spec:dumpAppspec(Au),enable_codemode:!!Au.permissions?.computer?.shell,...lo?{app_instance:{app_uid:lo.appUid??"",deployment_uid:lo.deploymentUid??"",version:lo.version??0,...lo.organizationUid?{organization_uid:lo.organizationUid}:{}}}:{}}}const DATALAYER_BOOTSTRAP_AGENTSPEC="example-simple",NO_PLUGINS$1=[];function appThemeOverrides(Au){const lo=Au.interface?.accent;return lo?{light:themeAccentVars(lo,"light"),dark:themeAccentVars(lo,"dark")}:void 0}function AppRenderer({app:Au,plugins:lo=NO_PLUGINS$1,instance:$u,onPresence:Ru,onSaying:Iu,paused:Ou=!1,sidebar:Pu=!1,computer:Du=!1,frame:Lu=!1,page:ju,pluginsOff:Bu,language:Fu,...zu}){const qu=JSON.stringify(dumpAppspec(Au)),Uu=[...Bu??[]].sort().join(","),Hu=(Fu?[Fu]:preferredLanguages()).join(","),Vu=reactExports.useMemo(()=>translatedAppspec(Au,Hu.split(",").filter(Boolean)),[qu,Hu]),Gu=!!$u?.deploymentUid,Ku=!!zu.datalayerVisitors,Zu=reactExports.useMemo(()=>{try{return appPreset(Au,{page:ju,pluginsOff:Bu,sidebar:Pu,computer:Du,appUid:$u?.appUid,shown:Vu,...Gu?{kept:{visitor:Ku}}:{}})}catch(ld){return{problem:ld instanceof Error?ld.message:String(ld)}}},[qu,Vu,ju,Uu,Pu,Du,$u?.appUid,Gu,Ku]),Qu=reactExports.useMemo(()=>"problem"in Zu?lo:[appExtension(Au,Vu,Zu.plugins),...lo],[Zu,lo]),Yu=!("problem"in Zu)&&Zu.workspace.conversation!==!1,ed=reactExports.useMemo(()=>Yu?appDatalayerCreatePayload(Au,$u):void 0,[qu,Yu,$u?.appUid,$u?.deploymentUid,$u?.version]),Xu=useSystemColorMode(),rd=Au.interface?.theme,nd=rd?.mode==="auto"?Xu:rd?.mode==="light"||rd?.mode==="dark"?rd.mode:void 0,od=Au.interface?.accent,ad=reactExports.useMemo(()=>appThemeOverrides(Au),[od]);return"problem"in Zu?jsxRuntimeExports.jsx("div",{role:"status",style:{padding:16},children:Zu.problem}):jsxRuntimeExports.jsx(ChatLanguage,{language:Fu,children:jsxRuntimeExports.jsx(LoopEmbed,{agentId:Au.id,...Zu.workspace,...Lu?{frameTitle:[Au.emoji,Vu.name].filter(Boolean).join(" ")}:{},sidebarRail:Pu||Du,teamPicker:!1,showAgentVariants:!1,pluginsPanel:!1,datalayerAgentSpecId:DATALAYER_BOOTSTRAP_AGENTSPEC,targetFixed:!0,...rd?{themeVariant:rd.variant}:{},...nd?{colorMode:nd}:{},themeOverrides:ad,presence:{name:Vu.name,face:Au.emoji,welcome:Vu.interface.welcome||Vu.description,paused:Ou,onPresence:Ru,onSaying:Iu},showTokenUsage:!1,datalayerCreatePayload:ed,...zu,plugins:Qu})})}const ASSISTANT_CHARACTERS_PLUGIN_NAME="@datalayer/loop-plugin-assistant-characters",AssistantCharactersPlugin={name:ASSISTANT_CHARACTERS_PLUGIN_NAME,displayName:"Assistant characters",description:"Datalayer's own characters for the floating assistant: a paper clip, a wizard, a cat and the L👀P eyes.",octicon:"paperclip",contributes:ASSISTANT_CHARACTERS.map(Au=>contribution(LoopAssistantCharacter,{id:Au.id,character:Au},{id:Au.id}))};function assistantCharactersOf(Au){return Au.getContributions(LoopAssistantCharacter).map(lo=>lo.value)}function assistantCharactersFrom(Au){const lo=buildReactorFromPlugins(Au);lo.start();try{return assistantCharactersOf(lo)}finally{lo.stop()}}function assistantCharacterFor(Au,lo){const $u=lo.app?"app":lo.person?"person":"default",Ru=lo.app??lo.person??DEFAULT_ASSISTANT_CHARACTER,Iu=Au.find(Pu=>Pu.id===Ru);return Iu?{id:Ru,character:Iu.character,saidBy:$u}:{saidBy:$u,problem:`${$u==="app"?"This application names":$u==="person"?"Your settings name":"The default is"} the character “${Ru}”, which nothing enabled here draws; the characters are ${Au.map(Pu=>Pu.id).join(", ")||"none"}.`}}const EMBED_TAG="datalayer-app",EMBED_ATTRIBUTES={app:"The application’s id on Datalayer.",origin:"Where Datalayer is; the origin the script was loaded from by default.",token:"An embed token for an application that is not public, issued to your server for each visit.",spec:"The address of an Appspec (YAML or JSON) to run, in place of `app`.",mode:"inline, bubble, panel or assistant; the Appspec’s `deployment.embedded.mode` by default, then inline.",accent:"green, rose, sky, lime, sun or violet; the Appspec’s `interface.accent` by default, else the theme’s own colours.",theme:"light, dark or auto (the visitor’s system); auto by default.",font:"A CSS font family for the application’s text; Inter, then the system’s sans-serif, by default.",server:"An agent-runtimes server the application’s agent runs on; a Datalayer runtime by default.",api:"Datalayer’s API, where an application is read with its token; the platform’s by default.",height:"The height of an inline application, in pixels; 640 by default.",resume:"true or false: whether a visit’s conversation is picked up again after the page reloads, kept in the page’s storage; true by default.",language:"The language the visitor reads the application in, as BCP 47 tags it (fr, pt-BR): its translation into it, and the chat’s own words; the visitor’s browser’s by default.","user-token":"A token your server signed with the deployment’s secret, naming your user (HS256: sub, name, exp at most an hour away): what an application that says user: signed opens its session with."},EMBED_OBSERVED_ATTRIBUTES=Object.keys(EMBED_ATTRIBUTES),EMBED_HOST_VARIABLES={accent:"--datalayer-app-accent",font:"--datalayer-app-font",theme:"--datalayer-app-theme"},EMBED_COLOR_MODES=["light","dark","auto"],EMBED_FLOATING_VIEWS={bubble:"floating-small",panel:"panel",assistant:"assistant"};function floatingViewOf(Au){return Au==="inline"?void 0:EMBED_FLOATING_VIEWS[Au]}class EmbedAttributeError extends Error{constructor(lo){super(lo),this.name="EmbedAttributeError"}}function runnable({app:Au,problems:lo}){if(!Au.id)throw new EmbedAttributeError(`datalayer-app: the Appspec names no application${lo.length?` (${lo[0]})`:""}.`);if(Au.kind!=="decision"&&!Au.agent)throw new EmbedAttributeError(`datalayer-app: “${Au.name||Au.id}” names no agent to answer; an embedded application is run by an agent (a team is not supported yet).`);return Au}const listed=Au=>`${Au.slice(0,-1).join(", ")} or ${Au[Au.length-1]}`;function oneOf(Au,lo,$u){const Ru=Au?.trim();if(Ru){if(!lo.includes(Ru))throw new EmbedAttributeError(`datalayer-app: "${Ru}" is not ${$u}; it is ${listed(lo)}.`);return Ru}}function checkedFont(Au){const lo=Au?.trim()??"";if(!lo)return"";if(!/^[\w\s,"'.-]+$/u.test(lo))throw new EmbedAttributeError(`datalayer-app: the font "${lo}" is not a font family; write it as a CSS font-family is written, such as "Georgia, serif".`);return lo}function embedLookOf(Au,lo){const{attributes:$u,variables:Ru={}}=Au,Iu=oneOf($u.mode,APP_EMBED_MODES,"a mode")??lo?.deployment?.embedded?.mode??"inline",Ou=oneOf($u.accent,APP_ACCENTS,"an accent")??oneOf(Ru.accent,APP_ACCENTS,"an accent")??lo?.interface?.accent,Pu=oneOf($u.theme,EMBED_COLOR_MODES,"a theme")??oneOf(Ru.theme,EMBED_COLOR_MODES,"a theme")??lo?.interface?.theme?.mode??"auto",Du=checkedFont($u.font)||checkedFont(Ru.font),Lu=lo?.interface?.theme?.variant??"loop";return{mode:Iu,accent:Ou,colorMode:Pu,font:Du,variant:Lu}}function resumeOf(Au){return oneOf(Au,["true","false"],"a value of resume")!=="false"}function languageOf(Au){const lo=Au?.trim();if(lo){if(!LANGUAGE_TAG.test(lo))throw new EmbedAttributeError(`datalayer-app: "${lo}" is not a language as BCP 47 tags it, such as fr or pt-BR.`);return lo}}function inlineHeightOf(Au){const lo=Number.parseInt(Au??"",10);return Number.isFinite(lo)&&lo>=240?lo:640}const EMBED_PROPERTIES=["context","functions","token"];function adoptPropertiesSetEarly(Au,lo=EMBED_PROPERTIES){const $u=[],Ru=Au;for(const Iu of lo)if(Object.prototype.hasOwnProperty.call(Au,Iu)){const Ou=Ru[Iu];delete Ru[Iu],Ru[Iu]=Ou,$u.push(Iu)}return $u}const CHAT_EXTRAS_PLUGIN_NAME="@datalayer/loop-plugin-chat-extras";let counter=0;function createChatExtrasPlugin(){const Au=`chat-extras-${counter+=1}`,lo=signal$2({});return{plugin:{name:CHAT_EXTRAS_PLUGIN_NAME,displayName:"Chat Extras",description:"A host example’s live banner and footer status.",octicon:"megaphone",emoji:"📣",contributes:[contribution(LoopChatExtras,{id:Au,extras:lo},{id:Au})]},setExtras:Ru=>{lo.value=Ru}}}const HOST_CONTEXT_TOOL="host_context",hostTool=Au=>`host_${Au}`;function signedUser(Au){return Au?.user==="signed"}const hostRefused=Au=>`No rule of this application names ${Au}: it is left to the person, and the page was not called.`,hostNotAllowed=Au=>`The person did not allow ${Au}: the page was not called.`,confirmOnPage=Au=>typeof window<"u"&&typeof window.confirm=="function"?window.confirm(Au.sentence):!1,actionOf=(Au,lo)=>Au.rules.find($u=>$u.appliesTo.includes(lo))?.action;function hostFrontendTools(Au,lo){const $u=Au.deployment.embedded?.host;if(!$u)return[];const Ru=Pu=>behaviourFor(Au,Pu),Iu=Pu=>Ru(Pu)!=="leave_to_me",Ou=[];$u.context.length>0&&Ou.push({name:HOST_CONTEXT_TOOL,description:`What the page you are embedded in says of its visitor and of itself: ${$u.context.join(", ")}. Read it before answering what depends on them.`,parameters:{type:"object",properties:{}},location:"frontend",handler:async()=>{if(!Iu(HOST_CONTEXT_TOOL))return{error:hostRefused(HOST_CONTEXT_TOOL)};const Pu=lo().context?.()??{},Du={},Lu=[];for(const ju of $u.context)Pu[ju]===void 0?Lu.push(ju):Du[ju]=Pu[ju];return{values:Du,...Lu.length>0?{unsaid:Lu}:{}}}});for(const Pu of $u.functions){const Du=hostTool(Pu.name);Ou.push({name:Du,description:Pu.description,parameters:Pu.parameters,location:"frontend",handler:async Lu=>{const ju=Fu=>(lo().onEvent?.({type:"action",detail:{function:Pu.name,arguments:Lu,...Fu}}),Fu);if(!Iu(Du))return ju({error:hostRefused(Du)});if(Ru(Du)!=="do_it"){const Fu=actionOf(Au,Du)??Pu.description;if(!await(lo().ask??confirmOnPage)({function:Pu.name,arguments:Lu,sentence:`${Fu}? (${Pu.name} with ${JSON.stringify(Lu)})`}))return ju({error:hostNotAllowed(Du)})}const Bu=lo().functions?.[Pu.name];if(!Bu)return ju({error:`The page offers no function ${Pu.name}: it was not called.`});try{return ju({result:await Bu(Lu)})}catch(Fu){return ju({error:`The page's ${Pu.name} failed: ${Fu instanceof Error?Fu.message:String(Fu)}`})}}})}return Ou}function hostUserRunProps(Au,lo){if(signedUser(Au.deployment.embedded?.host))return{id:"host-user",props:()=>{const $u=lo().userToken?.()?.trim();return $u?{loop:{user_token:$u}}:{}}}}function withFace(Au,lo,$u){return!lo||!$u?Au:Object.fromEntries(Object.entries(Au).map(([Ru,Iu])=>[Ru,typeof Iu=="string"?Iu.split($u).join(lo):Iu]))}function faceOf(Au,lo){return Au==="loop"?loopFontFamily:typeof lo.fontFamily=="string"?lo.fontFamily:""}const accentOver=(Au,lo)=>Au?themeAccentVars(Au,lo):{};function embedThemeStyles({accent:Au,font:lo="",variant:$u="loop"}){const Ru=getThemeConfig($u).themeStyles,Iu=Ou=>{const Pu=Ru[Ou];return withFace({...Pu,...accentOver(Au,Ou)},lo,faceOf($u,Pu))};return{...Ru,light:Iu("light"),dark:Iu("dark")}}function embedThemeOverrides({accent:Au,font:lo="",variant:$u="loop"}){const Ru=getThemeConfig($u).themeStyles,Iu=Ou=>{const Pu=Ru[Ou];return{...Object.fromEntries(Object.entries(withFace(Pu,lo,faceOf($u,Pu))).filter(([Lu,ju])=>typeof ju=="string"&&ju!==Pu[Lu])),...accentOver(Au,Ou)}};return{light:Iu("light"),dark:Iu("dark")}}function embedShadowCss(Au){const lo=`
|
|
3770
3770
|
:host {
|
|
3771
3771
|
all: initial;
|
|
3772
3772
|
display: block;
|
|
@@ -3801,4 +3801,4 @@ iframe.datalayer-app-frame {
|
|
|
3801
3801
|
`;return Au?`${lo}
|
|
3802
3802
|
${scopeThemeCss(Au,[`[${THEME_SCOPE_ATTRIBUTE}]`])}`:lo}const EMBED_SESSION_KEY_PREFIX="datalayer-app:session";function visitOfToken(Au){const lo=Au?.split(".")[1];if(lo)try{const $u=lo.replace(/-/g,"+").replace(/_/g,"/"),Ru=$u+"=".repeat((4-$u.length%4)%4),Iu=JSON.parse(atob(Ru));return typeof Iu.visit=="string"&&Iu.visit?Iu.visit:void 0}catch{return}}function embedSessionKey(Au,lo){return`${EMBED_SESSION_KEY_PREFIX}:${Au}:${lo}`}const IN_MEMORY=new Map;function hostStorage(){try{return typeof window<"u"?window.localStorage:void 0}catch{return}}function sessionKeeper({persist:Au,storage:lo=hostStorage}){return{read:$u=>{if(Au)try{const Ru=lo()?.getItem($u);if(Ru)return Ru}catch{}return IN_MEMORY.get($u)},keep:($u,Ru)=>{if(IN_MEMORY.set($u,Ru),Au)try{lo()?.setItem($u,Ru)}catch{}},forget:$u=>{IN_MEMORY.delete($u);try{lo()?.removeItem($u)}catch{}}}}function messagesOfThread(Au){if(!Array.isArray(Au))return[];const lo=[];for(const $u of Au){if(!$u||typeof $u!="object")continue;const{id:Ru,role:Iu,content:Ou}=$u;(Iu==="user"||Iu==="assistant")&&typeof Ru=="string"&&typeof Ou=="string"&&Ou.trim()&&lo.push({id:Ru,role:Iu,content:Ou,createdAt:new Date})}return lo}async function reattachSession({serverUrl:Au,uid:lo,token:$u,fetcher:Ru=fetch}){try{const Iu=await Ru(`${Au.replace(/\/+$/,"")}/api/v1/apps/sessions/${encodeURIComponent(lo)}/messages`,{headers:{Authorization:`Bearer ${$u}`}});if(!Iu.ok)return{kind:"gone",uid:lo};const Ou=await Iu.json();return{kind:"resumed",uid:lo,messages:messagesOfThread(Ou.messages)}}catch{return{kind:"gone",uid:lo}}}const WINDOW_NOT_YET='The application takes a window message once its conversation has started, on its own server (the "server" attribute).';async function postWindowMessage({serverUrl:Au,uid:lo,token:$u,data:Ru,fetcher:Iu=fetch}){const Ou=await Iu(`${Au.replace(/\/+$/,"")}/api/v1/apps/sessions/${encodeURIComponent(lo)}/window`,{method:"POST",headers:{"content-type":"application/json",...$u?{Authorization:`Bearer ${$u}`}:{}},body:JSON.stringify({data:Ru})});if(!Ou.ok){let Du="";try{const Lu=await Ou.json();Du=typeof Lu.detail=="string"?Lu.detail:""}catch{}throw new Error(Du||`The window message was refused (${Ou.status}).`)}const Pu=windowTurnOf(await Ou.text());if(Pu.error)throw new Error(Pu.error);return Pu.said}const sessionGoneSentence=Au=>`Your earlier conversation with ${Au} has ended, so this is a new one.`;function useEmbedSession({app:Au,serverUrl:lo,embedToken:$u,resume:Ru=!0}){const Iu=lo&&$u?visitOfToken($u):void 0,Ou=Iu?embedSessionKey(Au.id,Iu):void 0,Pu=reactExports.useMemo(()=>sessionKeeper({persist:Ru}),[Ru]),[Du,Lu]=reactExports.useState();return reactExports.useEffect(()=>{if(!Ou||!lo||!$u)return;let ju=!1;const Bu=qu=>{Pu.keep(Ou,qu),Lu(Uu=>Uu?.said?{...Uu,said:void 0}:Uu)},Fu=qu=>Lu({token:$u,thread:{id:generateMessageId(),messages:[],onStarted:Bu},...qu?{said:qu}:{}}),zu=Pu.read(Ou);if(!zu){Fu();return}return reattachSession({serverUrl:lo,uid:zu,token:$u}).then(qu=>{if(!ju){if(qu.kind==="resumed"){Lu({token:$u,thread:{id:zu,messages:qu.messages,onStarted:Bu}});return}Pu.forget(Ou),Fu(sessionGoneSentence(Au.name))}}),()=>{ju=!0}},[Ou,lo,$u,Pu]),Ou?!Du||Du.token!==$u?{ready:!1}:{ready:!0,thread:Du.thread,...Du.said?{said:Du.said}:{}}:{ready:!0}}function useWindowPort({serverUrl:Au,embedToken:lo,session:$u,host:Ru}){const Iu=reactExports.useRef(Ru);Iu.current=Ru;const Ou=$u.thread,Pu=reactExports.useRef(Ou?.messages.length?Ou.id:void 0),Du=reactExports.useMemo(()=>({id:generateMessageId(),messages:[]}),[]),Lu=Ou??(Au&&$u.ready?Du:void 0),ju=reactExports.useMemo(()=>Lu&&{...Lu,onStarted:Bu=>{Pu.current=Bu,Lu.onStarted?.(Bu)}},[Lu]);return reactExports.useEffect(()=>{const Bu=Ru?.onWindowPort;if(!(!Au||!Bu))return Bu(async Fu=>{if(!Pu.current)throw new Error(WINDOW_NOT_YET);const zu=await postWindowMessage({serverUrl:Au,uid:Pu.current,...lo?{token:lo}:{},data:Fu});for(const qu of zu)Iu.current?.onEvent?.({type:"window-message",detail:{data:qu}})}),()=>Bu(null)},[Au,lo,Ru]),ju?{...$u,thread:ju}:$u}function SessionSaid({said:Au}){return Au?jsxRuntimeExports.jsx(Text$5,{as:"p",role:"status",sx:{px:3,py:2,m:0,fontSize:1},children:Au}):null}const NO_HOST_PLUGINS=[];function useHostBridge(Au,lo){const $u=reactExports.useRef(lo);$u.current=lo;const Ru=reactExports.useMemo(()=>createChatExtrasPlugin(),[]),Iu=Au.deployment.embedded?.host,Ou=JSON.stringify([Iu??null,Au.rules,Au.connections]);reactExports.useEffect(()=>{Ru.setExtras({frontendTools:hostFrontendTools(Au,()=>$u.current??{})})},[Ru,Ou]);const Pu=Iu?.user==="signed",Du=reactExports.useMemo(()=>{const Uu=hostUserRunProps(Au,()=>$u.current??{});return Uu?{name:`loop-host-user-${Au.id}`,displayName:`${Au.name}: who its user is`,description:`The token naming its user that the host's server signed, sent with every run of ${Au.name}.`,octicon:"person",emoji:"👤",contributes:[contribution(LoopRunProps,Uu,{id:"host-user"})]}:void 0},[Au.id,Pu]),Lu=reactExports.useMemo(()=>Iu?[Ru.plugin,...Du?[Du]:[]]:NO_HOST_PLUGINS,[Iu,Ru,Du]);reactExports.useEffect(()=>onLoopWindowMessage(Uu=>$u.current?.onEvent?.({type:"window-message",detail:{data:Uu}})),[]);const ju=reactExports.useRef({answering:!1}),Bu=reactExports.useRef("idle"),Fu=reactExports.useRef(""),zu=reactExports.useCallback(Uu=>{ju.current=Uu},[]),qu=reactExports.useCallback(Uu=>{const Hu=Bu.current;Bu.current=Uu;const Vu=Uu==="idle"||Uu==="waiting",Gu=ju.current.saying;Vu&&Hu!=="idle"&&Hu!=="waiting"&&ju.current.answering&&Gu&&Gu.id!==Fu.current&&(Fu.current=Gu.id,$u.current?.onEvent?.({type:"message",detail:{id:Gu.id,text:Gu.markdown||Gu.text}}))},[]);return{plugins:Lu,onPresence:qu,onSaying:zu}}const NO_PLUGINS=[];function embedAssistantCharacter(Au,lo=NO_PLUGINS){return assistantCharacterFor(assistantCharactersFrom([AssistantCharactersPlugin,...lo]),{app:Au.interface.assistant})}const signedOutSentence=Au=>`${Au.name} runs on Datalayer, which needs you signed in. An application embedded for visitors who are not needs its embed token (LOOP D-14), or an agent-runtimes server of the host's own (the "server" attribute).`;function Face({emoji:Au}){return jsxRuntimeExports.jsx(FluentEmoji,{emoji:Au,size:20,label:""})}function AppFloating({app:Au,view:lo,colorMode:$u,themeVariant:Ru,themeOverrides:Iu,character:Ou,serverUrl:Pu,instance:Du,embedToken:Lu,renderer:ju,host:Bu,session:Fu,language:zu}){const qu=useChatWords(),[Uu,Hu]=reactExports.useState("idle"),[Vu,Gu]=reactExports.useState({answering:!1}),Ku=useHostBridge(Au,Bu),Zu=reactExports.useCallback(rd=>{Hu(rd),Ku.onPresence(rd)},[Ku.onPresence]),Qu=reactExports.useCallback(rd=>{Gu(rd),Ku.onSaying(rd)},[Ku.onSaying]),Yu=Au.interface.welcome||Au.description,ed=useIAMStore(rd=>rd.token),Xu=!Pu&&!ed&&!ju?.datalayerVisitors;return jsxRuntimeExports.jsx(ChatFloating,{defaultViewMode:lo,...Ou?{assistantCharacter:Ou}:{},...Au.interface.balloon?{balloonDisplay:Au.interface.balloon}:{},title:Au.name,description:Yu,brandIcon:jsxRuntimeExports.jsx(Face,{emoji:Au.emoji}),buttonIcon:jsxRuntimeExports.jsx(Face,{emoji:Au.emoji}),buttonTooltip:qu.talkTo(Au.name),colorMode:$u,useStore:!1,conversation:{body:Xu?jsxRuntimeExports.jsx(Text$5,{as:"p",role:"status",sx:{p:3,m:0,fontSize:1},children:signedOutSentence(Au)}):Fu&&!Fu.ready?null:jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(SessionSaid,{said:Fu?.said}),jsxRuntimeExports.jsx(AppRenderer,{app:Au,target:Pu?"local":"datalayer",...Pu?{serverUrl:Pu}:{},...Pu&&Lu?{embedToken:Lu}:{},instance:Du,themeOverrides:Iu,colorMode:$u,...Ru?{themeVariant:Ru}:{},hideChatHeader:!0,autoFocusPrompt:!1,onPresence:Zu,onSaying:Qu,plugins:Ku.plugins,...Fu?.thread?{thread:Fu.thread}:{},...zu?{language:zu}:{},...ju})]}),presence:Uu,saying:Vu.saying,answering:Vu.answering}})}function OwnPortalRoot(){const Au=reactExports.useRef(null);return reactExports.useLayoutEffect(()=>{Au.current&®isterPortalRoot(Au.current)},[]),jsxRuntimeExports.jsx("div",{ref:Au,className:"datalayer-app-portal"})}function useSystemMode(){const Au=typeof window<"u"&&typeof window.matchMedia=="function"?window.matchMedia("(prefers-color-scheme: dark)"):null,[lo,$u]=reactExports.useState(!!Au?.matches);return reactExports.useEffect(()=>{if(!Au)return;const Ru=()=>$u(Au.matches);return Au.addEventListener?.("change",Ru),()=>Au.removeEventListener?.("change",Ru)},[Au]),lo?"dark":"light"}function EmbedThemed({accent:Au,colorMode:lo,font:$u,variant:Ru,children:Iu,style:Ou}){const Pu=reactExports.useMemo(()=>embedThemeStyles({accent:Au,font:$u,variant:Ru}),[Au,$u,Ru]);return jsxRuntimeExports.jsx("div",{"data-color-mode":lo,style:{display:"contents"},children:jsxRuntimeExports.jsx(DatalayerThemeProvider,{colorMode:lo,theme:getThemeConfig(Ru).primerTheme,themeStyles:Pu,baseStyles:Ou,children:Iu})})}function AppEmbed({app:Au,mode:lo,accent:$u,colorMode:Ru,font:Iu,language:Ou,serverUrl:Pu,instance:Du,embedToken:Lu,visitors:ju,height:Bu=640,ownPortal:Fu=!1,plugins:zu=NO_PLUGINS,host:qu,resume:Uu=!0}){const Hu=lo??Au.deployment.embedded?.mode??"inline",Vu=useHostBridge(Au,Hu==="inline"?qu:void 0),Gu=reactExports.useMemo(()=>ju?{datalayerVisitors:ju}:void 0,[ju]),Ku=useEmbedSession({app:Au,serverUrl:Pu,embedToken:Lu,resume:Uu}),Zu=useWindowPort({serverUrl:Pu,embedToken:Lu,session:Ku,host:qu}),Qu=useSystemMode(),Yu=Au.interface.theme?.variant??"loop",ed=Ru??Au.interface.theme?.mode??"auto",Xu=ed==="auto"?Qu:ed,rd=floatingViewOf(Hu),nd=$u??Au.interface.accent,od=reactExports.useMemo(()=>embedThemeOverrides({accent:nd,font:Iu,variant:Yu}),[nd,Iu,Yu]),ad=Au.interface.assistant,ld=reactExports.useMemo(()=>rd==="assistant"?embedAssistantCharacter(Au,zu):void 0,[rd,ad,zu]);if(ld&&"problem"in ld)return jsxRuntimeExports.jsx("p",{role:"status",className:"datalayer-app-said",children:ld.problem});const fd=ld?.character;return jsxRuntimeExports.jsx(ChatLanguage,{language:Ou,children:jsxRuntimeExports.jsxs(EmbedThemed,{accent:nd,colorMode:Xu,font:Iu,variant:Yu,style:rd?{backgroundColor:"transparent"}:{height:Bu,display:"flex",flexDirection:"column"},children:[Fu?jsxRuntimeExports.jsx(OwnPortalRoot,{}):null,rd?jsxRuntimeExports.jsx(AppFloating,{app:Au,view:rd,serverUrl:Pu,instance:Du,embedToken:Lu,colorMode:Xu,themeVariant:Yu,themeOverrides:od,character:fd,host:qu,session:Zu,...Gu?{renderer:Gu}:{},...Ou?{language:Ou}:{}}):Zu.ready?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(SessionSaid,{said:Zu.said}),jsxRuntimeExports.jsx(AppRenderer,{app:Au,target:Pu?"local":"datalayer",...Pu?{serverUrl:Pu}:{},...Pu&&Lu?{embedToken:Lu}:{},...Gu??{},instance:Du,themeOverrides:od,colorMode:Xu,themeVariant:Yu,plugins:Vu.plugins,onPresence:Vu.onPresence,onSaying:Vu.onSaying,...Zu.thread?{thread:Zu.thread}:{},...Ou?{language:Ou}:{}})]}):null]})})}const VISITORS_PATH="/api/loop-visitors",VISITOR_EXAMPLES=["web-research","customer-interview"],AT_PREFIX="at:",DEFAULT_API="https://prod1.datalayer.run",isAppUid=Au=>/^[0-9A-HJKMNP-TV-Z]{26}$/.test(Au),SLUG=/^[a-z0-9][a-z0-9-]{0,62}$/;function visitorsAt(Au,lo){const $u=Au.replace(/\/+$/,"");return{url:`${$u}${VISITORS_PATH}`,app:lo,inferenceUrl:$u}}const TOKEN_HINT='Embedded for a visitor it refuses, it takes its embed token (the "token" attribute).',notKeptSentence=Au=>`datalayer-app: "${Au}" is an example Datalayer does not keep ready for visitors (${VISITOR_EXAMPLES.join(", ")} are); embed it at its address once it is deployed. ${TOKEN_HINT}`,refusedSentence=Au=>`datalayer-app: ${Au.trim().replace(/\.?\s*Sign in to use it\.?$/,".")} ${TOKEN_HINT}`;async function readVisitorApp({api:Au=DEFAULT_API,app:lo,fetcher:$u=fetch,catalogue:Ru=getApp}){const Iu=lo.trim();if(isAppUid(Iu))return{kind:"decision",app:Iu};const Ou=Ru(Iu);if(Ou)return Ou.kind==="decision"?{kind:"decision",app:Iu}:VISITOR_EXAMPLES.includes(Ou.id)?{kind:"visitors",app:runnable({app:Ou,problems:[]}),visitors:visitorsAt(Au,Ou.id)}:{kind:"said",text:notKeptSentence(Iu)};if(!SLUG.test(Iu))return{kind:"said",text:`datalayer-app: "${Iu}" is neither an application's id, an example's, nor an address.`};let Pu;try{Pu=await $u(`${Au.replace(/\/+$/,"")}/api/ai-agents/v1/apps/deployments/at/${encodeURIComponent(Iu)}`)}catch(zu){return{kind:"said",text:`datalayer-app: Datalayer could not be reached to read "${Iu}" (${zu instanceof Error?zu.message:String(zu)}).`}}const Du=await Pu.json().catch(()=>({}));if(!Pu.ok||Du.success===!1){const zu=String(Du.detail??Du.message??`No application is at "${Iu}".`);return{kind:"said",text:refusedSentence(zu)}}const Lu=Du.session??{};if(!Lu.opens)return{kind:"said",text:refusedSentence(String(Lu.reason||`"${Iu}" is not run without an account.`))};const ju=Du.deployment??{},Bu=parseAppspec(Du.spec);if(Bu.app.kind==="decision")return{kind:"decision",app:Iu};const Fu=typeof ju.app_name=="string"&&ju.app_name?ju.app_name:Bu.app.name;return{kind:"visitors",app:runnable({app:{...Bu.app,name:Fu},problems:Bu.problems}),visitors:visitorsAt(Au,`${AT_PREFIX}${Iu}`)}}const EMBED_MESSAGES={size:"datalayer-app:size",decision:"datalayer-app:decision",token:"datalayer-app:token",tokenExpired:"datalayer-app:token-expired"};function appspecOfText(Au){const lo=Au.replace(/\t/g," ").split(`
|
|
3803
3803
|
`),$u=Math.min(...lo.filter(Ou=>Ou.trim()).map(Ou=>Ou.length-Ou.trimStart().length)),Ru=lo.map(Ou=>Ou.slice(Number.isFinite($u)?$u:0)).join(`
|
|
3804
|
-
`).trim();if(!Ru)throw new EmbedAttributeError("datalayer-app: the Appspec is empty.");let Iu;if(Ru.startsWith("{")){let Ou;try{Ou=JSON.parse(Ru)}catch(Pu){throw new EmbedAttributeError(`datalayer-app: the Appspec is not JSON (${Pu.message}).`)}Iu=parseAppspec(Ou)}else Iu=readAppspecYaml(Ru);return runnable(Iu)}function frameSrcOf(Au,lo,$u=""){return`${Au.replace(/\/+$/,"")}/public/apps/${encodeURIComponent(lo)}/run?embed=1${$u?`#token=${encodeURIComponent($u)}`:""}`}function frameInLanguage(Au,lo){if(!lo)return Au;const $u=Au.indexOf("#"),[Ru,Iu]=$u<0?[Au,""]:[Au.slice(0,$u),Au.slice($u)];return`${Ru}${Ru.includes("?")?"&":"?"}language=${encodeURIComponent(lo)}${Iu}`}async function readEmbeddedApp({api:Au,origin:lo,app:$u,token:Ru,fetcher:Iu=fetch}){const Ou=await Iu(`${Au.replace(/\/+$/,"")}/api/spacer/v1/apps/${encodeURIComponent($u)}/embedded`,{headers:{Authorization:`Bearer ${Ru}`}});if(Ou.status===401)return{kind:"said",text:"datalayer-app: the embed token expired or is not for this application.",expired:!0};if(!Ou.ok)return{kind:"said",text:`datalayer-app: the application could not be read (${Ou.status}).`};const Pu=await Ou.json();let Du;try{Du=JSON.parse(String(Pu.app?.model_s??"{}"))}catch{Du={}}if(!Du.spec)return{kind:"frame",src:frameSrcOf(lo,$u,Ru)};const Lu=runnable(parseAppspec(Du.spec));return Lu.kind==="decision"?{kind:"frame",src:frameSrcOf(lo,$u,Ru)}:{kind:"spec",app:Lu}}function currentScriptUrl(){try{const Au=document.currentScript;return Au?.src?new URL(Au.src,location.href).href:""}catch{return""}}function defineDatalayerAppElement(Au={}){if(typeof window>"u"||!("customElements"in window))return;const lo=Au.tag??EMBED_TAG,$u=customElements.get(lo);if($u)return $u;const Ru=Au.scriptUrl??currentScriptUrl(),Iu=Ru?new URL(Ru).origin:"",Ou=Ru?Ru.replace(/\.js(\?.*)?$/,".css"):"";class Pu extends HTMLElement{static get observedAttributes(){return EMBED_OBSERVED_ATTRIBUTES}root=null;frame=null;source=null;loading=0;passed={};offered={};windowPort=null;host={context:()=>this.passed,userToken:()=>this.getAttribute("user-token")||void 0,functions:this.offered,onWindowPort:Lu=>{this.windowPort=Lu},onEvent:Lu=>this.dispatchEvent(new CustomEvent(Lu.type,{detail:Lu.detail,bubbles:!0,composed:!0}))};get context(){return this.passed}set context(Lu){this.passed={...Lu??{}}}postWindowMessage(Lu){const ju=this.windowPort;return ju?ju(Lu):Promise.reject(new Error(`datalayer-app: ${WINDOW_NOT_YET}`))}get functions(){return this.offered}set functions(Lu){for(const ju of Object.keys(this.offered))delete this.offered[ju];Object.assign(this.offered,Lu??{})}constructor(){super(),this.attachShadow({mode:"open"}),this.onMessage=this.onMessage.bind(this)}get token(){return this.getAttribute("token")??""}set token(Lu){Lu?this.setAttribute("token",String(Lu)):this.removeAttribute("token")}get userToken(){return this.getAttribute("user-token")??""}set userToken(Lu){Lu?this.setAttribute("user-token",String(Lu)):this.removeAttribute("user-token")}connectedCallback(){window.addEventListener("message",this.onMessage),this.load()}disconnectedCallback(){window.removeEventListener("message",this.onMessage),this.unmount()}attributeChangedCallback(Lu,ju,Bu){if(!(!this.isConnected||ju===Bu)&&Lu!=="user-token"){if(Lu==="token"&&this.frame?.contentWindow&&Bu){this.frame.contentWindow.postMessage({type:EMBED_MESSAGES.token,token:Bu},this.origin());return}if(["mode","accent","theme","font","height","resume","language"].includes(Lu)){this.draw();return}this.load()}}origin(){return(this.getAttribute("origin")||Iu||location.origin).replace(/\/+$/,"")}inputs(){const Lu={};for(const Fu of EMBED_OBSERVED_ATTRIBUTES)Lu[Fu]=this.getAttribute(Fu);const ju=getComputedStyle(this),Bu={};for(const[Fu,zu]of Object.entries(EMBED_HOST_VARIABLES)){const qu=ju.getPropertyValue(zu).trim();qu&&(Bu[Fu]=qu.replace(/^["']|["']$/g,""))}return{attributes:Lu,variables:Bu}}async read(){const Lu=this.querySelector('script[type="application/yaml"], script[type="application/json"], script[type="text/yaml"]');if(Lu?.textContent?.trim())return{kind:"spec",app:appspecOfText(Lu.textContent)};const ju=this.getAttribute("spec");if(ju){const zu=await fetch(new URL(ju,location.href).href);return zu.ok?{kind:"spec",app:appspecOfText(await zu.text())}:{kind:"said",text:`datalayer-app: the Appspec at ${ju} could not be read (${zu.status}).`}}const Bu=this.getAttribute("app");if(!Bu)return{kind:"said",text:'datalayer-app: the "app" attribute names the application to show, or "spec" the address of its Appspec.'};const Fu=this.token;if(!Fu){const zu=await readVisitorApp({api:this.api(),app:Bu});return zu.kind==="decision"?{kind:"frame",src:frameSrcOf(this.origin(),zu.app)}:zu.kind==="said"?{kind:"said",text:zu.text}:{kind:"spec",app:zu.app,visitors:zu.visitors}}return readEmbeddedApp({api:this.api(),origin:this.origin(),app:Bu,token:Fu})}api(){return(this.getAttribute("api")||coreStore.getState().configuration?.spacerUrl||DEFAULT_API).replace(/\/+$/,"")}async load(){const Lu=++this.loading;let ju;try{ju=await this.read()}catch(Bu){ju={kind:"said",text:Bu instanceof Error?Bu.message:`datalayer-app: ${String(Bu)}`}}Lu!==this.loading||!this.isConnected||(this.source=ju,this.draw(),ju.kind==="said"&&ju.expired&&this.dispatchEvent(new CustomEvent("token-expired",{detail:{app:this.getAttribute("app")??""},bubbles:!0,composed:!0})))}unmount(){this.root?.unmount(),this.root=null,this.frame=null}skeleton(Lu){const ju=this.shadowRoot;if(this.unmount(),ju.replaceChildren(),Ou){const Fu=document.createElement("link");Fu.rel="stylesheet",Fu.href=Ou,ju.appendChild(Fu)}const Bu=document.createElement("style");return Bu.textContent=embedShadowCss(Lu),ju.appendChild(Bu),ju}say(Lu){this.setAttribute("data-embed-mode","inline");const ju=this.skeleton(),Bu=document.createElement("p");Bu.className="datalayer-app-said",Bu.setAttribute("role","status"),Bu.textContent=Lu,ju.appendChild(Bu)}draw(){const Lu=this.source;if(!Lu)return;if(Lu.kind==="said"){this.say(Lu.text);return}if(Lu.kind==="frame"){let Hu;try{Hu=languageOf(this.getAttribute("language"))}catch(Ku){this.say(Ku.message);return}this.setAttribute("data-embed-mode","inline");const Vu=this.skeleton(),Gu=document.createElement("iframe");Gu.className="datalayer-app-frame",Gu.src=frameInLanguage(Lu.src,Hu),Gu.title="Datalayer app",Gu.style.height=`${inlineHeightOf(this.getAttribute("height"))}px`,Gu.setAttribute("allow","clipboard-write"),Vu.appendChild(Gu),this.frame=Gu;return}let ju,Bu,Fu;try{ju=embedLookOf(this.inputs(),Lu.app),Bu=resumeOf(this.getAttribute("resume")),Fu=languageOf(this.getAttribute("language"))}catch(Hu){this.say(Hu.message);return}if(ju.mode==="assistant"){const Hu=embedAssistantCharacter(Lu.app);if("problem"in Hu){this.say(Hu.problem);return}}this.setAttribute("data-embed-mode",ju.mode);const zu=this.skeleton(getThemeConfig(ju.variant).themeStyles.css),qu=document.createElement("div");qu.className="datalayer-app-root",zu.appendChild(qu),this.root=clientExports.createRoot(qu);const Uu=this.getAttribute("server")||void 0;this.root.render(jsxRuntimeExports.jsx(me$3,{target:zu,children:jsxRuntimeExports.jsx(AppEmbed,{app:Lu.app,mode:ju.mode,accent:ju.accent,colorMode:ju.colorMode,font:ju.font,serverUrl:Uu,...Uu&&this.token?{embedToken:this.token}:{},...Lu.visitors?{visitors:Lu.visitors}:{},height:inlineHeightOf(this.getAttribute("height")),ownPortal:!0,host:this.host,resume:Bu,...Fu?{language:Fu}:{}})}))}onMessage(Lu){if(!this.frame||Lu.source!==this.frame.contentWindow||Lu.origin!==this.origin())return;const ju=Lu.data??{};ju.type===EMBED_MESSAGES.size&&typeof ju.height=="number"&&ju.height>0?this.frame.style.height=`${Math.ceil(ju.height)}px`:ju.type===EMBED_MESSAGES.decision?this.dispatchEvent(new CustomEvent("decision",{detail:ju.record,bubbles:!0,composed:!0})):ju.type===EMBED_MESSAGES.tokenExpired&&this.dispatchEvent(new CustomEvent("token-expired",{detail:{app:this.getAttribute("app")??""},bubbles:!0,composed:!0}))}}return customElements.define(lo,Pu),Pu}const SCRIPT_FILE="datalayer-app.js";defineDatalayerAppElement({scriptUrl:new URL(SCRIPT_FILE,import.meta.url).href});const mermaidVLURNSYL=Object.freeze(Object.defineProperty({__proto__:null,Mermaid:Ee$2},Symbol.toStringTag,{value:"Module"}));export{ExternalTokenizer as $,A2uiSurfaceComposed as A,Box as B,CheckIcon as C,Dialog$1 as D,InputPrompt as E,Signal as F,o$1 as G,Heading$2 as H,IconButton as I,LoopOpeningNotebook as J,LoopNotebookToolbarItem as K,Label as L,MessageProcessor as M,NO_SANDBOX_YET as N,LoopNotebookToolbar as O,PlayIcon as P,QueryClient as Q,LRLanguage as R,SANDBOX_KIND_LABELS as S,Text$5 as T,LanguageSupport as U,indentNodeProp as V,continuedIndent as W,foldNodeProp as X,styleTags as Y,tags as Z,__vitePreload as _,QueryClientProvider as a,base$2 as a$,ifNotIn as a0,completeFromList as a1,LRParser as a2,syntaxTree as a3,delimitedIndent as a4,foldInside as a5,getDefaultExportFromCjs as a6,WIDGET_VIEW_MIMETYPE as a7,MimeModel as a8,Lumino as a9,useSystemColorMode as aA,getThemeConfig as aB,JupyterReactTheme$1 as aC,l$1 as aD,v$1 as aE,a$1 as aF,Kernel as aG,registerSandboxServiceManager as aH,DatalayerThemeProvider as aI,de$1 as aJ,on$1 as aK,nl as aL,es as aM,H as aN,disposeServiceManager as aO,create$i as aP,setIfUndefined as aQ,create$8 as aR,fromBase64 as aS,onChange as aT,varStorage as aU,toBase64 as aV,offChange as aW,createUint8ArrayFromArrayBuffer as aX,map$6 as aY,WIDGET_STATE_MIMETYPE as aZ,ManagerBase as a_,RenderMimeRegistry as aa,standardRendererFactories as ab,purify$1 as ac,format$2 as ad,Token$2 as ae,Menu as af,DisposableDelegate as ag,ArrayExt as ah,Widget as ai,PanelLayout as aj,HoverBox as ak,IToolbarWidgetRegistry as al,ITranslator as am,createToolbarFactory as an,nullTranslator as ao,createDefaultFactory as ap,ObservableList as aq,Toolbar$2 as ar,ReactWidget as as,some$2 as at,ISanitizer as au,ICommandPalette as av,StatusBar as aw,useAgentsRuntimes as ax,xu as ay,useThemeStore as az,sandboxExecuteOverHttp as b,contribution as b$,controls as b0,SemVerCache as b1,JUPYTER_WIDGETS_VERSION as b2,JUPYTER_CONTROLS_VERSION as b3,shims as b4,semverExports as b5,requireLoader as b6,serialize_state as b7,Panel as b8,PromiseDelegate as b9,Prec as bA,keymap as bB,EditorView as bC,Language as bD,indentUnit as bE,foldService as bF,defineLanguageFacet as bG,CompletionContext as bH,EditorState as bI,languageDataProp as bJ,LanguageDescription as bK,ParseContext as bL,ContextTracker as bM,bracketMatchingHandle as bN,LocalTokenGroup as bO,NodeWeakMap as bP,IterMode as bQ,sublanguageProp as bR,flatIndent as bS,snippetCompletion as bT,LoopDocumentToolbarItem as bU,LoopDocumentToolbar as bV,LoopOpeningDocument as bW,useOptionalSandboxService as bX,IDLE_SANDBOX_SNAPSHOT_SIGNAL as bY,definePlugin as bZ,DOCUMENT_TOOLBAR_PLUGIN_NAME as b_,DEFAULT_SERVICE_URLS as ba,requestDatalayerAPI as bb,API_BASE_PATHS as bc,ActionList as bd,distExports as be,ActionListContainerContext as bf,BoxWithFallback as bg,merge$5 as bh,defaultSxProp as bi,useId as bj,reactDomExports as bk,useIsomorphicLayoutEffect$2 as bl,ChevronDownIcon as bm,classes$t as bn,SubItem as bo,Box$1 as bp,themeConfigs as bq,Parser$4 as br,NodeType as bs,NodeProp as bt,Tag$1 as bu,NodeSet as bv,Tree as bw,parseMixed as bx,EditorSelection as by,countColumn as bz,ButtonComponent as c,setToolbar as c$,KernelIndicator as c0,NOTEBOOK_TOOLBAR_PLUGIN_NAME as c1,useReactorPlatform as c2,AGENTS_PLUGIN_NAME as c3,IDLE_SANDBOX_TARGET_SIGNAL as c4,AGENTSPECS$1 as c5,useAgentRuntimes as c6,Eu as c7,Ke$2 as c8,_c as c9,SearchDocumentModel as cA,SearchDocumentView as cB,isResponsiveValue as cC,clsx as cD,Rgb as cE,rgbConvert as cF,define as cG,extend$3 as cH,Color as cI,commonjsRequire as cJ,TextInput$1 as cK,SearchIcon as cL,SyncIcon as cM,ToggleSwitch as cN,ChevronRightIcon as cO,StyledSpinner as cP,ToolbarButton as cQ,fileUploadIcon as cR,TextItem as cS,GroupItem as cT,libExports$2 as cU,WidgetTracker as cV,folderIcon as cW,linkIcon as cX,Clipboard as cY,downloadIcon as cZ,copyIcon as c_,is as ca,Ys as cb,PencilIcon as cc,SingletonLayout as cd,FocusTracker as ce,libExports$5 as cf,VDomModel as cg,TableOfContents as ch,JSONExt as ci,VDomRenderer as cj,LabIcon as ck,classes as cl,map$8 as cm,showErrorMessage as cn,AttachedProperty as co,addIcon as cp,launcherIcon as cq,MainAreaWidget as cr,find$5 as cs,TranslatorConnector as ct,Gettext as cu,DEFAULT_LANGUAGE_CODE as cv,normalizeDomain as cw,ITranslatorConnector as cx,Dialog as cy,showDialog$1 as cz,displayUrl as d,EditorThemeRegistry as d$,InputDialog as d0,Notification as d1,CommandRegistry as d2,closeIcon as d3,cutIcon as d4,pasteIcon as d5,newFolderIcon as d6,textEditorIcon as d7,markdownIcon as d8,refreshIcon as d9,jupyterIcon as dA,SettingRegistry as dB,MenuFactory as dC,moveUpIcon as dD,moveDownIcon as dE,Button$1 as dF,deleteIcon as dG,DOMUtils as dH,lineFormIcon as dI,deleteLine as dJ,toggleBlockComment as dK,toggleComment as dL,toggleTabFocusMode as dM,selectNextOccurrence as dN,foldable as dO,foldCode as dP,unfoldCode as dQ,foldState as dR,foldEffect as dS,unfoldEffect as dT,foldAll as dU,unfoldAll as dV,IEditorServices as dW,EditorLanguageRegistry as dX,parseMathIPython as dY,StreamLanguage as dZ,pythonBuiltin as d_,editIcon as da,fileIcon as db,stopIcon as dc,filterIcon as dd,DisposableSet as de,clearNumbering as df,getHeadingId as dg,addPrefix as dh,parseHeadings as di,filterHeadings as dj,StackedLayout as dk,ABCWidgetFactory as dl,DocumentWidget as dm,ITableOfContentsRegistry as dn,markdownRendererFactory as dp,CommandLinker as dq,SkeletonBox as dr,getBrightPalette as ds,useColorPalette as dt,SkeletonText as du,Tooltip as dv,ActionMenu as dw,KebabHorizontalIcon as dx,IWindowResolver as dy,buildIcon as dz,Link$1 as e,ListUnorderedIcon as e$,EditorExtensionRegistry as e0,ybinding as e1,CodeMirrorEditorFactory as e2,CodeMirrorMimeTypeService as e3,IPositionModel as e4,KERNEL_PROVIDER_ID as e5,Completer as e6,CompleterModel as e7,ProviderReconciliator as e8,CompletionHandler as e9,useLayoutStore as eA,useRuntimesStore as eB,color$1 as eC,OutputPrompt as eD,Stdin as eE,CodeCell as eF,notebookStore as eG,useJupyterLabCssLoaded as eH,TelescopeIcon as eI,XIcon as eJ,CounterLabel as eK,PauseIcon as eL,DownloadIcon as eM,SPAN_SOURCE_LABELS as eN,sourceOfSpan as eO,AGENT_SPAN_ATTRIBUTES as eP,describeAgentSpan as eQ,SpecMark as eR,rgb as eS,parse$4 as eT,UUID as eU,EN_US as eV,errorIcon as eW,Platform as eX,caretDownEmptyThinIcon as eY,StringExt as eZ,SegmentedControl as e_,historyIcon as ea,ICompletionProviderManager as eb,IInlineCompleterFactory as ec,KernelCompleterProvider as ed,CommandToolbarButton as ee,caretLeftIcon as ef,caretRightIcon as eg,checkIcon as eh,COMPLETER_ACTIVE_CLASS as ei,Debouncer as ej,ISessionContextDialogs as ek,SessionContextDialogs as el,saveIcon as em,addCommandToolbarButtonClass as en,UseSignal as eo,CommandToolbarButtonComponent as ep,createStore$1 as eq,useStore$1 as er,runtimesStore as es,DATALAYER_IAM_TOKEN_KEY as et,DATALAYER_IAM_USER_KEY as eu,coreStore as ev,iamStore as ew,layoutStore as ex,useCoreStore as ey,useIAMStore as ez,CopyIcon as f,AgentTools as f$,GraphIcon as f0,ProgressBar as f1,ClockIcon as f2,DatabaseIcon as f3,FileIcon as f4,ToolsIcon as f5,CommentDiscussionIcon as f6,AiModelIcon as f7,InfoIcon as f8,KeyIcon as f9,useOnOutsideClick as fA,useResizeObserver as fB,VisuallyHidden as fC,TriangleDownIcon as fD,qe$4 as fE,sx as fF,requireSerialize as fG,requireMessages as fH,mockSocketExports as fI,ObservableMap as fJ,exponent as fK,formatSpecifier as fL,formatPrefix as fM,CodeEditorWrapper as fN,CodeEditor as fO,IEditorMimeTypeService as fP,EditorSearchProvider as fQ,CodeMirrorEditor$1 as fR,getPrefix as fS,isMarkdown as fT,findNext as fU,gotoLine as fV,consoleIcon as fW,undoIcon as fX,redoIcon as fY,selectAll as fZ,Sanitizer as f_,devtools as fa,subscribeWithSelector as fb,persist as fc,CheckCircleFillIcon as fd,AlertIcon as fe,useAgentRuntimeMcpStatus as ff,useAgentRuntimeCodemodeStatus as fg,useAgentRuntimeContextSnapshot as fh,useAgentRuntimeFullContext as fi,useAgentRuntimeWsState as fj,useMutation as fk,useQuery as fl,ForwardRef$3 as fm,NoteIcon as fn,ServerIcon as fo,CheckCircleIcon as fp,XCircleIcon as fq,BriefcaseIcon as fr,SemanticCommand as fs,MenuBar as ft,runIcon as fu,fastForwardIcon as fv,getAnchoredPosition as fw,reactIsExports as fx,useTheme as fy,useOnEscapePress as fz,createAllAgentRuntimesTools as g,readServerCatalogue as g$,useToast as g0,isInsideJupyterLab as g1,FormControl$1 as g2,MailIcon as g3,Textarea as g4,$e$5 as g5,JUPYTER_NOTEBOOK_FRONTEND_TOOL_SPEC_0_0_1 as g6,LEXICAL_DOCUMENT_FRONTEND_TOOL_SPEC_0_0_1 as g7,RUNTIME_ECHO_BACKEND_TOOL_SPEC_0_0_1 as g8,TAVILY_MCP_SERVER_0_0_1 as g9,latestSaying as gA,messageText as gB,LoopRunProps as gC,runForwardedProps as gD,onSurfaceRequest as gE,setEditorOptions as gF,seedEditorChoice as gG,canOpenView as gH,useWorkspaceFullScreen as gI,targetRunsAgentInPage as gJ,useOptionalTeamSelection as gK,LoopAgentBlueprint as gL,LoopChatSuggestion as gM,agentIcon as gN,LoopFrontendTool as gO,agentServerOf as gP,LoopCommand as gQ,subagentsFor as gR,useChatAvailability as gS,noRuntimeSaid as gT,useSlotComponents as gU,LoopSlots as gV,onPromptFocusRequest as gW,generateMessageId as gX,useConfig as gY,useSkills as gZ,useSkillActions as g_,EVENTS_SKILL_SPEC_0_0_1 as ga,TEXT_SUMMARIZER_SKILL_SPEC_0_0_1 as gb,GITHUB_SKILL_SPEC_0_0_1 as gc,CRAWL_SKILL_SPEC_0_0_1 as gd,useAnonymousInferenceSession as ge,browserModelRequiresSignIn as gf,getAgentspecs as gg,useOptionalReactorPlatform as gh,messagesOfThread as gi,FluentEmoji as gj,PRESENCE_LINES as gk,useChatWords as gl,CHAT_PLUGIN_NAME as gm,INPUT_PROMPT_PLUGIN_NAME as gn,LoopChatSurface as go,LoopChatComposer as gp,LoopChatHeader as gq,LoopChatLayout as gr,LoopChatTurn as gs,turnWritersOf as gt,LoopChatExtras as gu,computed$1 as gv,useGate as gw,presenceState as gx,presenceToolOf as gy,newestIsAnswer as gz,renderOcticon as h,StaticNotebook as h$,readServerDecisions as h0,offeredModels as h1,AI_MODEL_CATALOGUE as h2,isChatModel as h3,ReactorSlot as h4,ReactorLazy as h5,ChatBase as h6,ScreenNormalIcon as h7,ScreenFullIcon as h8,SUGGESTION_CHIP_WIDTH as h9,ThemeManager as hA,ToolbarWidgetRegistry as hB,Selector$1 as hC,Printing as hD,WindowResolver as hE,jupyterFaviconIcon as hF,caretDownEmptyIcon as hG,addToolbarButtonClass as hH,NotebookActions as hI,Toolbar as hJ,translateKernelStatuses as hK,offlineBoltIcon as hL,circleIcon as hM,MessageLoop as hN,Collapser$1 as hO,ObservableJSON as hP,ConflatableMessage as hQ,jumpBackIcon as hR,jumpForwardIcon as hS,MarkdownCell as hT,Cell$1 as hU,trustedIcon as hV,notTrustedIcon as hW,runCell as hX,InputPrompt$1 as hY,NotebookPanel as hZ,setCellExecutor as h_,Truncate as ha,useAnonymousSessionStore as hb,signal$2 as hc,LoopAgentGate as hd,agentRuntimeStore as he,loopShapeVars as hf,NONE_EDITOR as hg,filterListIcon as hh,CommandPalette$1 as hi,h$7 as hj,LabIconStyle as hk,ILicensesClient as hl,Licenses as hm,copyrightIcon as hn,ToolbarButtonComponent as ho,bellIcon as hp,clientExports as hq,Button$3 as hr,ModalCommandPalette as hs,paletteIcon as ht,Throttler as hu,IKernelStatusModel as hv,KernelStatus$1 as hw,RunningSessions as hx,IThemeManager as hy,ISplashScreen as hz,SquareFillIcon as i,useProperties as i$,notebookIcon as i0,NotebookSearchProvider as i1,duplicateIcon as i2,addAboveIcon as i3,addBelowIcon as i4,children$1 as i5,ref$2 as i6,html$7 as i7,startSlotTemplate as i8,endSlotTemplate as i9,focusStrokeWidth$1 as iA,strokeWidth$1 as iB,controlCornerRadius$1 as iC,heightNumber$1 as iD,neutralFillStealthHover$1 as iE,neutralFillStealthActive$1 as iF,designUnit$1 as iG,typeRampBaseFontSize$1 as iH,typeRampBaseLineHeight$1 as iI,density$1 as iJ,typeRampPlus1FontSize$1 as iK,disabledOpacity$1 as iL,disabledCursor as iM,baseHeightMultiplier$1 as iN,neutralFillRest$1 as iO,neutralFillHover$1 as iP,neutralFillActive$1 as iQ,accentForegroundRest$1 as iR,display as iS,css as iT,forcedColorsStylesheetBehavior as iU,SystemColors as iV,cssPartial as iW,DesignToken as iX,neutralFillStealthRecipe$1 as iY,neutralFillRecipe$1 as iZ,useEventListener as i_,slotted as ia,elements as ib,FoundationElement as ic,isHTMLElement as id,__decorate$1 as ie,attr as ig,observable as ih,applyMixins as ii,StartEnd as ij,keyEnter as ik,keyArrowUp as il,keyArrowDown as im,keyArrowRight as io,keyArrowLeft as ip,keyEnd as iq,keyHome as ir,DOM as is,getDisplayedNodes as it,direction$1 as iu,neutralForegroundRest$1 as iv,neutralFillStealthRest$1 as iw,bodyFont$1 as ix,focusVisible as iy,accentFillFocus$1 as iz,jsxRuntimeExports as j,CheckboxOrRadioGroupCaption as j$,provideJupyterDesignSystem$1 as j0,ITableOfContentsTracker as j1,tocIcon as j2,numberingIcon as j3,expandAllIcon as j4,collapseAllIcon as j5,ellipsesIcon as j6,VisuallyHidden$1 as j7,StopIcon as j8,ViewPlugin as j9,NotebookCommandIds as jA,OutputAreaModel as jB,useJupyterReactStore as jC,newUuid as jD,NotebookPanelProvider as jE,addNotebookCommands as jF,WIDGET_MIMETYPE as jG,rendererFactory$1 as jH,rendererFactory as jI,getMarked as jJ,createLatexTypesetter as jK,YArray as jL,YText as jM,newUlid as jN,k$2 as jO,loopColors as jP,sunColors as jQ,ivoryColors as jR,sandColors as jS,earthColors as jT,matrixColors as jU,lovelyColors as jV,spatialColors as jW,datalayerColors as jX,getColorPalette as jY,CheckboxOrRadioGroupValidation as jZ,CheckboxOrRadioGroupLabel as j_,createRelativePositionFromTypeIndex as ja,createRelativePositionFromJSON as jb,tooltips as jc,Facet as jd,Annotation as je,layer as jf,StateField as jg,showTooltip as jh,createAbsolutePositionFromRelativePosition as ji,RectangleMarker as jj,YDocument as jk,createCellModelFromSharedType as jl,createCell as jm,YMap as jn,RawCellModel as jo,MarkdownCellModel as jp,CodeCellModel as jq,MINOR_VERSION as jr,MAJOR_VERSION as js,SessionContext as jt,StateEffect as ju,Decoration as jv,WidgetType as jw,kernelIcon as jx,DEFAULT_VARIANT as jy,MarimoReactive as jz,TrashIcon as k,qc as k$,useRenderForcingRef as k0,CheckboxOrRadioGroup$1 as k1,CheckboxGroupContext as k2,Checkbox as k3,RadioGroup$1 as k4,Radio as k5,SelectPanel as k6,Select$1 as k7,TextInputWithTokens as k8,object as k9,qi as kA,Pi as kB,isStream as kC,isExecuteResult as kD,isDisplayData as kE,isError$2 as kF,Xo as kG,Ki as kH,Yi as kI,er as kJ,T as kK,v$2 as kL,S$1 as kM,C as kN,m$2 as kO,x$5 as kP,y$3 as kQ,p$4 as kR,ol as kS,He$2 as kT,pn$2 as kU,Kr as kV,ur as kW,ls as kX,cn$1 as kY,_n as kZ,hn$2 as k_,preprocess$1 as ka,record$1 as kb,string$2 as kc,unknown$1 as kd,zodToToolParameters as ke,array as kf,_enum as kg,number$2 as kh,boolean$1 as ki,validateWithZod as kj,whitespace as kk,svg$2 as kl,find as km,stringify$1 as kn,stringify as ko,ccount as kp,zwitch as kq,html$4 as kr,htmlVoidElements as ks,C$1 as kt,Dt$4 as ku,u$2 as kv,dt$2 as kw,Go as kx,ns as ky,mn$1 as kz,libExports$3 as l,rKernelIcon as l$,Ie$2 as l0,cs as l1,dr as l2,Jl as l3,fn$2 as l4,hn$1 as l5,pn$1 as l6,Wo as l7,xt$2 as l8,Zs as l9,hpass as lA,AccordionPanel as lB,caretDownIcon as lC,AccordionLayout as lD,FormAssociated as lE,nullableNumberConverter as lF,ARIAGlobalStatesAndProperties as lG,neutralFillInputRest$1 as lH,neutralFillStrongRest$1 as lI,errorFillRest$1 as lJ,neutralFillInputHover$1 as lK,neutralFillStrongHover$1 as lL,errorFillHover$1 as lM,neutralFillStrongActive$1 as lN,errorFillActive$1 as lO,errorFillFocus$1 as lP,neutralStrokeRest$1 as lQ,__decorate as lR,searchIcon as lS,jsonIcon as lT,BoxLayout as lU,VirtualDOM as lV,TextModelFactory as lW,pdfIcon as lX,pythonIcon as lY,juliaIcon as lZ,spreadsheetIcon as l_,gc as la,On as lb,na as lc,ea as ld,ia as le,sa as lf,useJupyter as lg,decodeNamedCharacterReference as lh,requireReact as li,StyleModule as lj,jupyterHighlightStyle as lk,requireDayjs_min as ll,useFocusZone as lm,FocusKeys as ln,useSafeTimeout as lo,useSlots as lp,useProvidedRefOrCreate as lq,useResponsiveValue as lr,ScrollableRegion as ls,viewportRanges as lt,JupyterLiteServer as lu,Router as lv,ContextMenu as lw,TabPanel$1 as lx,TabBar as ly,DockPanel as lz,PlusIcon as m,ClassicWidgetManager as m$,yamlIcon as m0,imageIcon as m1,audioIcon as m2,videoIcon as m3,writeVarUint as m4,encodeStateVector as m5,writeVarUint8Array as m6,encodeStateAsUpdate as m7,readVarUint as m8,applyUpdate as m9,filter$5 as mA,ElementExt as mB,caretUpIcon as mC,Poll as mD,each$1 as mE,Application as mF,StackedPanel as mG,tabIcon as mH,Base64ModelFactory as mI,useTerminalStore as mJ,InputViewer as mK,basicSetup as mL,drawSelection as mM,indentOnInput as mN,highlightActiveLine as mO,highlightSpecialChars as mP,highlightSelectionMatches as mQ,defaultKeymap as mR,searchKeymap as mS,requestAPI$1 as mT,loadJupyterConfig as mU,createLiteServiceManager as mV,jupyterReactStore as mW,ANSWER_MARKER as mX,BuilderManagerLess as mY,CellAdapter as mZ,CellCommands as m_,readVarUint8Array as ma,readVarString as mb,ObservableV2 as mc,Awareness as md,toUint8Array$1 as me,length as mf,encodeAwarenessUpdate as mg,removeAwarenessStates as mh,isNode as mi,getUnixTime as mj,createEncoder as mk,min$1 as ml,pow as mm,createDecoder as mn,applyAwarenessUpdate as mo,BoxPanel as mp,Cell as mq,UndoManager as mr,Doc$1 as ms,SplitPanel as mt,RawCell as mu,isCodeCellModel as mv,Drag as mw,MimeData as mx,useConsoleStore as my,folderFavoriteIcon as mz,CodeIcon as n,isServedByJupyterLab as n$,CodeMirrorDatalayerEditor as n0,CodeMirrorEditor as n1,CodeMirrorOutputToolbar as n2,ContentsManagerLess as n3,DEFAULT_API_KERNEL_PREFIX_URL as n4,DEFAULT_JUPYTER_SERVER_TOKEN as n5,DEFAULT_JUPYTER_SERVER_URL as n6,DEFAULT_KERNEL_NAME as n7,DefaultExecutor as n8,EventsManagerLess as n9,UserManagerLess as nA,WidgetRenderer as nB,WorkspaceManagerLess as nC,cellSourceAsString as nD,cellsStore as nE,codeMirrorTheme as nF,consoleStore as nG,createLiteServer as nH,createServerSettings as nI,deleteCellsOperation as nJ,deleteCellsTool as nK,disableKernelReconnect as nL,disposeKernelConnections as nM,ensureJupyterAuth as nN,ensureJupyterConfig as nO,execute as nP,executeCodeOperation as nQ,executeCodeTool as nR,formatResponse as nS,getCookie as nT,getJupyterServerToken as nU,getJupyterServerUrl as nV,getKernelIndicatorMeta as nW,insertCellOperation as nX,insertCellTool as nY,isAnyCellRunning as nZ,isReactiveVariant as n_,ExecutionPhase as na,HELPER_NAME as nb,HTMLManager as nc,JupyterLabCss as nd,KERNEL_HELPER_SOURCE as ne,KERNEL_STATES as nf,KERNEL_STATE_LABELS as ng,KERNEL_STATE_VISUALS as nh,KernelActionMenu as ni,KernelExecutor as nj,KernelManagerLess as nk,KernelProgressBar as nl,KernelspecManagerLess as nm,MIME_TYPE$1 as nn,NbConvertManagerLess as no,OperationRunner as np,Output as nq,OutputAdapter as nr,OutputRenderer as ns,OutputViewer as nt,OutputViewerAdapter as nu,RenderedPlotly as nv,ServiceManagerLess as nw,SessionManagerLess as nx,SettingManagerLess as ny,TerminalManagerLess as nz,formatTokenCount as o,rn$1 as o$,jupyterLabTheme as o0,kernelsStore as o1,loadJupyterLabCss as o2,notebookToolDefinitions as o3,notebookToolOperations as o4,notebookTools as o5,outputsAsString as o6,outputsStore as o7,readAllCellsOperation as o8,readAllCellsTool as o9,bu as oA,Nu as oB,Wl as oC,Fr as oD,Li as oE,Vc as oF,Fo as oG,sn$1 as oH,vc as oI,tr as oJ,Sn as oK,Zo as oL,Cu as oM,Bs as oN,Me as oO,yn as oP,Se as oQ,Cn as oR,fn as oS,qr as oT,Ia as oU,zs as oV,gn$2 as oW,or as oX,Jr as oY,sn$2 as oZ,ln$1 as o_,readCellOperation as oa,readCellTool as ob,refreshJupyterLabPortalTheme as oc,renderKernelStateGlyph as od,renderWidgets as oe,rendererFactory$2 as of,resetJupyterConfig as og,runCellOperation as oh,runCellTool as oi,setJupyterServerToken as oj,setJupyterServerUrl as ok,sleep as ol,syncJupyterLabPortalTheme as om,terminalStore as on,toKernelState as oo,updateCellOperation as op,updateCellTool as oq,useCellsStore as or,useJupyterReactColormode as os,useJupyterReactStoreFromProps as ot,useKernelsStore as ou,useOutputsStore as ov,ThemeProvider as ow,Overlay$1 as ox,Fi as oy,Zl as oz,useSandboxService as p,Xe$2 as p$,nn$2 as p0,Vr as p1,nu as p2,du as p3,Va as p4,au as p5,La as p6,Is as p7,Dl as p8,h$1 as p9,oa as pA,Cn$1 as pB,et as pC,xn as pD,St as pE,Rt as pF,xt as pG,yn$1 as pH,It$1 as pI,Tt as pJ,l$2 as pK,a$2 as pL,d$2 as pM,s$2 as pN,Ue$2 as pO,dn$2 as pP,$e$2 as pQ,un$1 as pR,Bi as pS,It as pT,en$2 as pU,_$1 as pV,te$2 as pW,le$2 as pX,on$2 as pY,$t$3 as pZ,mn$2 as p_,Sn$1 as pa,Nn$1 as pb,ce$1 as pc,Tu as pd,vu as pe,ae$1 as pf,xt$3 as pg,St$3 as ph,Pc as pi,Lc as pj,Ic as pk,mt$3 as pl,rs as pm,an$1 as pn,Je$2 as po,Ft$1 as pp,Os as pq,Mt$1 as pr,gt as ps,Co as pt,Tn as pu,Dt as pv,So as pw,vn as px,kn$1 as py,xl as pz,useSignalValue$1 as q,Ul as q$,gr as q0,Ge$2 as q1,_r as q2,Ve$2 as q3,je$1 as q4,Ye$1 as q5,qe$2 as q6,Yt as q7,Ya as q8,Pe$2 as q9,Al as qA,No as qB,bo as qC,as as qD,_t as qE,eu as qF,fc as qG,Re as qH,Kc as qI,Wt$1 as qJ,z$2 as qK,ac as qL,On$1 as qM,Ht$1 as qN,Le$2 as qO,zr as qP,Bt$1 as qQ,Ll as qR,ui as qS,ec as qT,nc as qU,zt$1 as qV,Ir as qW,i$1 as qX,uu as qY,Aa as qZ,Wa as q_,Ja as qa,tu as qb,zl as qc,Fl as qd,Ma as qe,ja as qf,Hl as qg,Ba as qh,Bl as qi,Pr as qj,Pe as qk,uo as ql,mu as qm,iu as qn,ku as qo,Mo as qp,Rl as qq,wu as qr,Fn as qs,lc as qt,$s as qu,he as qv,Fe as qw,Ut$1 as qx,We as qy,Fs as qz,reactExports as r,oe$1 as r$,ql as r0,dc as r1,be as r2,ke as r3,ft as r4,pi as r5,x$4 as r6,z as r7,O$1 as r8,r$2 as r9,vi as rA,Ql as rB,ut$2 as rC,Gl as rD,ReactDOM as rE,M$2 as rF,PersonIcon as rG,Pt$1 as rH,s$1 as rI,f$3 as rJ,P$1 as rK,fe$1 as rL,PaperAirplaneIcon as rM,bn$2 as rN,TableIcon as rO,q as rP,ChecklistIcon as rQ,fn$1 as rR,GrabberIcon as rS,vo as rT,yo as rU,wo as rV,mo as rW,j$1 as rX,r$3 as rY,$2AODx$react as rZ,jt$1 as r_,t$2 as ra,Es as rb,_s as rc,vt$2 as rd,n$2 as re,b$1 as rf,nn$1 as rg,r$1 as rh,g$1 as ri,Tt$2 as rj,ys as rk,e$1 as rl,vl as rm,u$1 as rn,b$3 as ro,z$1 as rp,zi as rq,Ji as rr,ko as rs,To as rt,Ze$2 as ru,Qe$2 as rv,Mn$1 as rw,wn$1 as rx,En$1 as ry,xo as rz,sandboxIsLive as s,requireIsObject as s$,ie$2 as s0,PaintbrushIcon as s1,RowsIcon as s2,x$2 as s3,AlertFillIcon as s4,ArrowRightIcon as s5,BeakerIcon as s6,BellIcon as s7,BookIcon as s8,BroadcastIcon as s9,RssIcon as sA,ShareAndroidIcon as sB,ShieldCheckIcon as sC,ShieldIcon as sD,SidebarExpandIcon as sE,SkipIcon as sF,SlidersIcon as sG,SparkleFillIcon as sH,SquareCircleIcon as sI,SunIcon as sJ,TagIcon as sK,TasklistIcon as sL,ThumbsdownIcon as sM,ThumbsupIcon as sN,UnmuteIcon as sO,UploadIcon as sP,XCircleFillIcon as sQ,ZapIcon as sR,require_Symbol as sS,requireIsArguments as sT,requireIsArray as sU,require_arrayPush as sV,require_baseGetTag as sW,requireIsObjectLike as sX,require_MapCache as sY,require_Stack as sZ,require_baseIsEqual as s_,BrowserIcon as sa,BugIcon as sb,CircleSlashIcon as sc,CodeReviewIcon as sd,CpuIcon as se,CreditCardIcon as sf,DependabotIcon as sg,DeviceDesktopIcon as sh,DeviceMobileIcon as si,FoldIcon as sj,GearIcon as sk,GitBranchIcon as sl,GlobeIcon as sm,HeartIcon as sn,IssueOpenedIcon as so,LightBulbIcon as sp,LinkExternalIcon as sq,MegaphoneIcon as sr,MortarBoardIcon as ss,MuteIcon as st,OrganizationIcon as su,PackageIcon as sv,PaperclipIcon as sw,PeopleIcon as sx,PulseIcon as sy,RocketIcon as sz,timeLeft as t,TUTOR_VIEW as t$,requireKeys as t0,require_isIndex as t1,requireIsLength as t2,requireIdentity as t3,require_baseFor as t4,requireIsArrayLike as t5,require_baseUnary as t6,require_baseRest as t7,require_isIterateeCall as t8,require_Set as t9,getAugmentedNamespace as tA,index_esm as tB,__assign as tC,requireReactDom as tD,__extends as tE,__awaiter as tF,__rest as tG,__generator as tH,darker as tI,brighter as tJ,require$$0$4 as tK,requireBase64Js as tL,hsl as tM,requireObjectAssign as tN,ulid$1 as tO,AGENTS_VIEW as tP,CONTENTS_VIEW as tQ,DATALAYER_VIEW as tR,JWT_DATALAYER_ISSUER as tS,JWT_REFRESH_TOKEN_COOKIE_NAME as tT,LIBRARY_VIEW as tU,NAVIGATION_VIEW_HOMES as tV,RESERVATION_WARNING_TIME_MS as tW,SESSION_COOKIES as tX,SESSION_LOCAL_STORAGE_KEYS as tY,SESSION_OWNER_KEY as tZ,SETTINGS_VIEW as t_,require_setToArray as ta,require_SetCache as tb,require_cacheHas as tc,requireEq$1 as td,requireKeysIn as te,requireIsArrayLikeObject as tf,requireIsEqual as tg,requireIsPlainObject$1 as th,require_baseMerge as ti,require_createAssigner as tj,require_apply as tk,require_copyArray as tl,require_arrayEach as tm,requireCloneDeep as tn,requireFastDeepEqual as to,requireFastUri as tp,ForwardRef$2 as tq,ForwardRef$1 as tr,ForwardRef as ts,memoize$1 as tt,isPropValid as tu,tabbable as tv,focusable as tw,isTabbable as tx,getTabIndex as ty,isFocusable as tz,useNotebookStore$1 as u,claimSessionState as u0,forgetSessionState as u1,getOtelConsumeUrl as u2,getStoredToken as u3,getStoredUser as u4,isRememberableRoute as u5,isShellNeutralRoute as u6,loadRefreshTokenFromCookie as u7,navigationStore as u8,pageConfiguration as u9,profileStore as ua,registerSessionState as ub,storeToken as uc,storeUser as ud,useNavigationStore as ue,useProfile as uf,useProfileStore as ug,viewForRoute as uh,__spreadArray as ui,index$4 as uj,index$3 as uk,index$2 as ul,katex$1 as um,Lexical_prod as un,LexicalUtils_prod as uo,vM as v,datalayerCatalog as w,ChatBaseHeader as x,useContributions as y,LoopPromptPanel as z};
|
|
3804
|
+
`).trim();if(!Ru)throw new EmbedAttributeError("datalayer-app: the Appspec is empty.");let Iu;if(Ru.startsWith("{")){let Ou;try{Ou=JSON.parse(Ru)}catch(Pu){throw new EmbedAttributeError(`datalayer-app: the Appspec is not JSON (${Pu.message}).`)}Iu=parseAppspec(Ou)}else Iu=readAppspecYaml(Ru);return runnable(Iu)}function frameSrcOf(Au,lo,$u=""){return`${Au.replace(/\/+$/,"")}/public/apps/${encodeURIComponent(lo)}/run?embed=1${$u?`#token=${encodeURIComponent($u)}`:""}`}function frameInLanguage(Au,lo){if(!lo)return Au;const $u=Au.indexOf("#"),[Ru,Iu]=$u<0?[Au,""]:[Au.slice(0,$u),Au.slice($u)];return`${Ru}${Ru.includes("?")?"&":"?"}language=${encodeURIComponent(lo)}${Iu}`}async function readEmbeddedApp({api:Au,origin:lo,app:$u,token:Ru,fetcher:Iu=fetch}){const Ou=await Iu(`${Au.replace(/\/+$/,"")}/api/spacer/v1/apps/${encodeURIComponent($u)}/embedded`,{headers:{Authorization:`Bearer ${Ru}`}});if(Ou.status===401)return{kind:"said",text:"datalayer-app: the embed token expired or is not for this application.",expired:!0};if(!Ou.ok)return{kind:"said",text:`datalayer-app: the application could not be read (${Ou.status}).`};const Pu=await Ou.json();let Du;try{Du=JSON.parse(String(Pu.app?.model_s??"{}"))}catch{Du={}}if(!Du.spec)return{kind:"frame",src:frameSrcOf(lo,$u,Ru)};const Lu=runnable(parseAppspec(Du.spec));return Lu.kind==="decision"?{kind:"frame",src:frameSrcOf(lo,$u,Ru)}:{kind:"spec",app:Lu}}function currentScriptUrl(){try{const Au=document.currentScript;return Au?.src?new URL(Au.src,location.href).href:""}catch{return""}}function defineDatalayerAppElement(Au={}){if(typeof window>"u"||!("customElements"in window))return;const lo=Au.tag??EMBED_TAG,$u=customElements.get(lo);if($u)return $u;const Ru=Au.scriptUrl??currentScriptUrl(),Iu=Ru?new URL(Ru).origin:"",Ou=Ru?Ru.replace(/\.js(\?.*)?$/,".css"):"";class Pu extends HTMLElement{static get observedAttributes(){return EMBED_OBSERVED_ATTRIBUTES}root=null;frame=null;source=null;loading=0;passed={};offered={};windowPort=null;host={context:()=>this.passed,userToken:()=>this.getAttribute("user-token")||void 0,functions:this.offered,onWindowPort:Lu=>{this.windowPort=Lu},onEvent:Lu=>this.dispatchEvent(new CustomEvent(Lu.type,{detail:Lu.detail,bubbles:!0,composed:!0}))};get context(){return this.passed}set context(Lu){this.passed={...Lu??{}}}postWindowMessage(Lu){const ju=this.windowPort;return ju?ju(Lu):Promise.reject(new Error(`datalayer-app: ${WINDOW_NOT_YET}`))}get functions(){return this.offered}set functions(Lu){for(const ju of Object.keys(this.offered))delete this.offered[ju];Object.assign(this.offered,Lu??{})}constructor(){super(),this.attachShadow({mode:"open"}),this.onMessage=this.onMessage.bind(this),adoptPropertiesSetEarly(this)}get token(){return this.getAttribute("token")??""}set token(Lu){Lu?this.setAttribute("token",String(Lu)):this.removeAttribute("token")}get userToken(){return this.getAttribute("user-token")??""}set userToken(Lu){Lu?this.setAttribute("user-token",String(Lu)):this.removeAttribute("user-token")}connectedCallback(){window.addEventListener("message",this.onMessage),this.load()}disconnectedCallback(){window.removeEventListener("message",this.onMessage),this.unmount()}attributeChangedCallback(Lu,ju,Bu){if(!(!this.isConnected||ju===Bu)&&Lu!=="user-token"){if(Lu==="token"&&this.frame?.contentWindow&&Bu){this.frame.contentWindow.postMessage({type:EMBED_MESSAGES.token,token:Bu},this.origin());return}if(["mode","accent","theme","font","height","resume","language"].includes(Lu)){this.draw();return}this.load()}}origin(){return(this.getAttribute("origin")||Iu||location.origin).replace(/\/+$/,"")}inputs(){const Lu={};for(const Fu of EMBED_OBSERVED_ATTRIBUTES)Lu[Fu]=this.getAttribute(Fu);const ju=getComputedStyle(this),Bu={};for(const[Fu,zu]of Object.entries(EMBED_HOST_VARIABLES)){const qu=ju.getPropertyValue(zu).trim();qu&&(Bu[Fu]=qu.replace(/^["']|["']$/g,""))}return{attributes:Lu,variables:Bu}}async read(){const Lu=this.querySelector('script[type="application/yaml"], script[type="application/json"], script[type="text/yaml"]');if(Lu?.textContent?.trim())return{kind:"spec",app:appspecOfText(Lu.textContent)};const ju=this.getAttribute("spec");if(ju){const zu=await fetch(new URL(ju,location.href).href);return zu.ok?{kind:"spec",app:appspecOfText(await zu.text())}:{kind:"said",text:`datalayer-app: the Appspec at ${ju} could not be read (${zu.status}).`}}const Bu=this.getAttribute("app");if(!Bu)return{kind:"said",text:'datalayer-app: the "app" attribute names the application to show, or "spec" the address of its Appspec.'};const Fu=this.token;if(!Fu){const zu=await readVisitorApp({api:this.api(),app:Bu});return zu.kind==="decision"?{kind:"frame",src:frameSrcOf(this.origin(),zu.app)}:zu.kind==="said"?{kind:"said",text:zu.text}:{kind:"spec",app:zu.app,visitors:zu.visitors}}return readEmbeddedApp({api:this.api(),origin:this.origin(),app:Bu,token:Fu})}api(){return(this.getAttribute("api")||coreStore.getState().configuration?.spacerUrl||DEFAULT_API).replace(/\/+$/,"")}async load(){const Lu=++this.loading;let ju;try{ju=await this.read()}catch(Bu){ju={kind:"said",text:Bu instanceof Error?Bu.message:`datalayer-app: ${String(Bu)}`}}Lu!==this.loading||!this.isConnected||(this.source=ju,this.draw(),ju.kind==="said"&&ju.expired&&this.dispatchEvent(new CustomEvent("token-expired",{detail:{app:this.getAttribute("app")??""},bubbles:!0,composed:!0})))}unmount(){this.root?.unmount(),this.root=null,this.frame=null}skeleton(Lu){const ju=this.shadowRoot;if(this.unmount(),ju.replaceChildren(),Ou){const Fu=document.createElement("link");Fu.rel="stylesheet",Fu.href=Ou,ju.appendChild(Fu)}const Bu=document.createElement("style");return Bu.textContent=embedShadowCss(Lu),ju.appendChild(Bu),ju}say(Lu){this.setAttribute("data-embed-mode","inline");const ju=this.skeleton(),Bu=document.createElement("p");Bu.className="datalayer-app-said",Bu.setAttribute("role","status"),Bu.textContent=Lu,ju.appendChild(Bu)}draw(){const Lu=this.source;if(!Lu)return;if(Lu.kind==="said"){this.say(Lu.text);return}if(Lu.kind==="frame"){let Hu;try{Hu=languageOf(this.getAttribute("language"))}catch(Ku){this.say(Ku.message);return}this.setAttribute("data-embed-mode","inline");const Vu=this.skeleton(),Gu=document.createElement("iframe");Gu.className="datalayer-app-frame",Gu.src=frameInLanguage(Lu.src,Hu),Gu.title="Datalayer app",Gu.style.height=`${inlineHeightOf(this.getAttribute("height"))}px`,Gu.setAttribute("allow","clipboard-write"),Vu.appendChild(Gu),this.frame=Gu;return}let ju,Bu,Fu;try{ju=embedLookOf(this.inputs(),Lu.app),Bu=resumeOf(this.getAttribute("resume")),Fu=languageOf(this.getAttribute("language"))}catch(Hu){this.say(Hu.message);return}if(ju.mode==="assistant"){const Hu=embedAssistantCharacter(Lu.app);if("problem"in Hu){this.say(Hu.problem);return}}this.setAttribute("data-embed-mode",ju.mode);const zu=this.skeleton(getThemeConfig(ju.variant).themeStyles.css),qu=document.createElement("div");qu.className="datalayer-app-root",zu.appendChild(qu),this.root=clientExports.createRoot(qu);const Uu=this.getAttribute("server")||void 0;this.root.render(jsxRuntimeExports.jsx(me$3,{target:zu,children:jsxRuntimeExports.jsx(AppEmbed,{app:Lu.app,mode:ju.mode,accent:ju.accent,colorMode:ju.colorMode,font:ju.font,serverUrl:Uu,...Uu&&this.token?{embedToken:this.token}:{},...Lu.visitors?{visitors:Lu.visitors}:{},height:inlineHeightOf(this.getAttribute("height")),ownPortal:!0,host:this.host,resume:Bu,...Fu?{language:Fu}:{}})}))}onMessage(Lu){if(!this.frame||Lu.source!==this.frame.contentWindow||Lu.origin!==this.origin())return;const ju=Lu.data??{};ju.type===EMBED_MESSAGES.size&&typeof ju.height=="number"&&ju.height>0?this.frame.style.height=`${Math.ceil(ju.height)}px`:ju.type===EMBED_MESSAGES.decision?this.dispatchEvent(new CustomEvent("decision",{detail:ju.record,bubbles:!0,composed:!0})):ju.type===EMBED_MESSAGES.tokenExpired&&this.dispatchEvent(new CustomEvent("token-expired",{detail:{app:this.getAttribute("app")??""},bubbles:!0,composed:!0}))}}return customElements.define(lo,Pu),Pu}const SCRIPT_FILE="datalayer-app.js";defineDatalayerAppElement({scriptUrl:new URL(SCRIPT_FILE,import.meta.url).href});const mermaidVLURNSYL=Object.freeze(Object.defineProperty({__proto__:null,Mermaid:Ee$2},Symbol.toStringTag,{value:"Module"}));export{ExternalTokenizer as $,A2uiSurfaceComposed as A,Box as B,CheckIcon as C,Dialog$1 as D,InputPrompt as E,Signal as F,o$1 as G,Heading$2 as H,IconButton as I,LoopOpeningNotebook as J,LoopNotebookToolbarItem as K,Label as L,MessageProcessor as M,NO_SANDBOX_YET as N,LoopNotebookToolbar as O,PlayIcon as P,QueryClient as Q,LRLanguage as R,SANDBOX_KIND_LABELS as S,Text$5 as T,LanguageSupport as U,indentNodeProp as V,continuedIndent as W,foldNodeProp as X,styleTags as Y,tags as Z,__vitePreload as _,QueryClientProvider as a,base$2 as a$,ifNotIn as a0,completeFromList as a1,LRParser as a2,syntaxTree as a3,delimitedIndent as a4,foldInside as a5,getDefaultExportFromCjs as a6,WIDGET_VIEW_MIMETYPE as a7,MimeModel as a8,Lumino as a9,useSystemColorMode as aA,getThemeConfig as aB,JupyterReactTheme$1 as aC,l$1 as aD,v$1 as aE,a$1 as aF,Kernel as aG,registerSandboxServiceManager as aH,DatalayerThemeProvider as aI,de$1 as aJ,on$1 as aK,nl as aL,es as aM,H as aN,disposeServiceManager as aO,create$i as aP,setIfUndefined as aQ,create$8 as aR,fromBase64 as aS,onChange as aT,varStorage as aU,toBase64 as aV,offChange as aW,createUint8ArrayFromArrayBuffer as aX,map$6 as aY,WIDGET_STATE_MIMETYPE as aZ,ManagerBase as a_,RenderMimeRegistry as aa,standardRendererFactories as ab,purify$1 as ac,format$2 as ad,Token$2 as ae,Menu as af,DisposableDelegate as ag,ArrayExt as ah,Widget as ai,PanelLayout as aj,HoverBox as ak,IToolbarWidgetRegistry as al,ITranslator as am,createToolbarFactory as an,nullTranslator as ao,createDefaultFactory as ap,ObservableList as aq,Toolbar$2 as ar,ReactWidget as as,some$2 as at,ISanitizer as au,ICommandPalette as av,StatusBar as aw,useAgentsRuntimes as ax,xu as ay,useThemeStore as az,sandboxExecuteOverHttp as b,contribution as b$,controls as b0,SemVerCache as b1,JUPYTER_WIDGETS_VERSION as b2,JUPYTER_CONTROLS_VERSION as b3,shims as b4,semverExports as b5,requireLoader as b6,serialize_state as b7,Panel as b8,PromiseDelegate as b9,Prec as bA,keymap as bB,EditorView as bC,Language as bD,indentUnit as bE,foldService as bF,defineLanguageFacet as bG,CompletionContext as bH,EditorState as bI,languageDataProp as bJ,LanguageDescription as bK,ParseContext as bL,ContextTracker as bM,bracketMatchingHandle as bN,LocalTokenGroup as bO,NodeWeakMap as bP,IterMode as bQ,sublanguageProp as bR,flatIndent as bS,snippetCompletion as bT,LoopDocumentToolbarItem as bU,LoopDocumentToolbar as bV,LoopOpeningDocument as bW,useOptionalSandboxService as bX,IDLE_SANDBOX_SNAPSHOT_SIGNAL as bY,definePlugin as bZ,DOCUMENT_TOOLBAR_PLUGIN_NAME as b_,DEFAULT_SERVICE_URLS as ba,requestDatalayerAPI as bb,API_BASE_PATHS as bc,ActionList as bd,distExports as be,ActionListContainerContext as bf,BoxWithFallback as bg,merge$5 as bh,defaultSxProp as bi,useId as bj,reactDomExports as bk,useIsomorphicLayoutEffect$2 as bl,ChevronDownIcon as bm,classes$t as bn,SubItem as bo,Box$1 as bp,themeConfigs as bq,Parser$4 as br,NodeType as bs,NodeProp as bt,Tag$1 as bu,NodeSet as bv,Tree as bw,parseMixed as bx,EditorSelection as by,countColumn as bz,ButtonComponent as c,setToolbar as c$,KernelIndicator as c0,NOTEBOOK_TOOLBAR_PLUGIN_NAME as c1,useReactorPlatform as c2,AGENTS_PLUGIN_NAME as c3,IDLE_SANDBOX_TARGET_SIGNAL as c4,AGENTSPECS$1 as c5,useAgentRuntimes as c6,Eu as c7,Ke$2 as c8,_c as c9,SearchDocumentModel as cA,SearchDocumentView as cB,isResponsiveValue as cC,clsx as cD,Rgb as cE,rgbConvert as cF,define as cG,extend$3 as cH,Color as cI,commonjsRequire as cJ,TextInput$1 as cK,SearchIcon as cL,SyncIcon as cM,ToggleSwitch as cN,ChevronRightIcon as cO,StyledSpinner as cP,ToolbarButton as cQ,fileUploadIcon as cR,TextItem as cS,GroupItem as cT,libExports$2 as cU,WidgetTracker as cV,folderIcon as cW,linkIcon as cX,Clipboard as cY,downloadIcon as cZ,copyIcon as c_,is as ca,Ys as cb,PencilIcon as cc,SingletonLayout as cd,FocusTracker as ce,libExports$5 as cf,VDomModel as cg,TableOfContents as ch,JSONExt as ci,VDomRenderer as cj,LabIcon as ck,classes as cl,map$8 as cm,showErrorMessage as cn,AttachedProperty as co,addIcon as cp,launcherIcon as cq,MainAreaWidget as cr,find$5 as cs,TranslatorConnector as ct,Gettext as cu,DEFAULT_LANGUAGE_CODE as cv,normalizeDomain as cw,ITranslatorConnector as cx,Dialog as cy,showDialog$1 as cz,displayUrl as d,EditorThemeRegistry as d$,InputDialog as d0,Notification as d1,CommandRegistry as d2,closeIcon as d3,cutIcon as d4,pasteIcon as d5,newFolderIcon as d6,textEditorIcon as d7,markdownIcon as d8,refreshIcon as d9,jupyterIcon as dA,SettingRegistry as dB,MenuFactory as dC,moveUpIcon as dD,moveDownIcon as dE,Button$1 as dF,deleteIcon as dG,DOMUtils as dH,lineFormIcon as dI,deleteLine as dJ,toggleBlockComment as dK,toggleComment as dL,toggleTabFocusMode as dM,selectNextOccurrence as dN,foldable as dO,foldCode as dP,unfoldCode as dQ,foldState as dR,foldEffect as dS,unfoldEffect as dT,foldAll as dU,unfoldAll as dV,IEditorServices as dW,EditorLanguageRegistry as dX,parseMathIPython as dY,StreamLanguage as dZ,pythonBuiltin as d_,editIcon as da,fileIcon as db,stopIcon as dc,filterIcon as dd,DisposableSet as de,clearNumbering as df,getHeadingId as dg,addPrefix as dh,parseHeadings as di,filterHeadings as dj,StackedLayout as dk,ABCWidgetFactory as dl,DocumentWidget as dm,ITableOfContentsRegistry as dn,markdownRendererFactory as dp,CommandLinker as dq,SkeletonBox as dr,getBrightPalette as ds,useColorPalette as dt,SkeletonText as du,Tooltip as dv,ActionMenu as dw,KebabHorizontalIcon as dx,IWindowResolver as dy,buildIcon as dz,Link$1 as e,ListUnorderedIcon as e$,EditorExtensionRegistry as e0,ybinding as e1,CodeMirrorEditorFactory as e2,CodeMirrorMimeTypeService as e3,IPositionModel as e4,KERNEL_PROVIDER_ID as e5,Completer as e6,CompleterModel as e7,ProviderReconciliator as e8,CompletionHandler as e9,useLayoutStore as eA,useRuntimesStore as eB,color$1 as eC,OutputPrompt as eD,Stdin as eE,CodeCell as eF,notebookStore as eG,useJupyterLabCssLoaded as eH,TelescopeIcon as eI,XIcon as eJ,CounterLabel as eK,PauseIcon as eL,DownloadIcon as eM,SPAN_SOURCE_LABELS as eN,sourceOfSpan as eO,AGENT_SPAN_ATTRIBUTES as eP,describeAgentSpan as eQ,SpecMark as eR,rgb as eS,parse$4 as eT,UUID as eU,EN_US as eV,errorIcon as eW,Platform as eX,caretDownEmptyThinIcon as eY,StringExt as eZ,SegmentedControl as e_,historyIcon as ea,ICompletionProviderManager as eb,IInlineCompleterFactory as ec,KernelCompleterProvider as ed,CommandToolbarButton as ee,caretLeftIcon as ef,caretRightIcon as eg,checkIcon as eh,COMPLETER_ACTIVE_CLASS as ei,Debouncer as ej,ISessionContextDialogs as ek,SessionContextDialogs as el,saveIcon as em,addCommandToolbarButtonClass as en,UseSignal as eo,CommandToolbarButtonComponent as ep,createStore$1 as eq,useStore$1 as er,runtimesStore as es,DATALAYER_IAM_TOKEN_KEY as et,DATALAYER_IAM_USER_KEY as eu,coreStore as ev,iamStore as ew,layoutStore as ex,useCoreStore as ey,useIAMStore as ez,CopyIcon as f,AgentTools as f$,GraphIcon as f0,ProgressBar as f1,ClockIcon as f2,DatabaseIcon as f3,FileIcon as f4,ToolsIcon as f5,CommentDiscussionIcon as f6,AiModelIcon as f7,InfoIcon as f8,KeyIcon as f9,useOnOutsideClick as fA,useResizeObserver as fB,VisuallyHidden as fC,TriangleDownIcon as fD,qe$4 as fE,sx as fF,requireSerialize as fG,requireMessages as fH,mockSocketExports as fI,ObservableMap as fJ,exponent as fK,formatSpecifier as fL,formatPrefix as fM,CodeEditorWrapper as fN,CodeEditor as fO,IEditorMimeTypeService as fP,EditorSearchProvider as fQ,CodeMirrorEditor$1 as fR,getPrefix as fS,isMarkdown as fT,findNext as fU,gotoLine as fV,consoleIcon as fW,undoIcon as fX,redoIcon as fY,selectAll as fZ,Sanitizer as f_,devtools as fa,subscribeWithSelector as fb,persist as fc,CheckCircleFillIcon as fd,AlertIcon as fe,useAgentRuntimeMcpStatus as ff,useAgentRuntimeCodemodeStatus as fg,useAgentRuntimeContextSnapshot as fh,useAgentRuntimeFullContext as fi,useAgentRuntimeWsState as fj,useMutation as fk,useQuery as fl,ForwardRef$3 as fm,NoteIcon as fn,ServerIcon as fo,CheckCircleIcon as fp,XCircleIcon as fq,BriefcaseIcon as fr,SemanticCommand as fs,MenuBar as ft,runIcon as fu,fastForwardIcon as fv,getAnchoredPosition as fw,reactIsExports as fx,useTheme as fy,useOnEscapePress as fz,createAllAgentRuntimesTools as g,readServerCatalogue as g$,useToast as g0,isInsideJupyterLab as g1,FormControl$1 as g2,MailIcon as g3,Textarea as g4,$e$5 as g5,JUPYTER_NOTEBOOK_FRONTEND_TOOL_SPEC_0_0_1 as g6,LEXICAL_DOCUMENT_FRONTEND_TOOL_SPEC_0_0_1 as g7,RUNTIME_ECHO_BACKEND_TOOL_SPEC_0_0_1 as g8,TAVILY_MCP_SERVER_0_0_1 as g9,latestSaying as gA,messageText as gB,LoopRunProps as gC,runForwardedProps as gD,onSurfaceRequest as gE,setEditorOptions as gF,seedEditorChoice as gG,canOpenView as gH,useWorkspaceFullScreen as gI,targetRunsAgentInPage as gJ,useOptionalTeamSelection as gK,LoopAgentBlueprint as gL,LoopChatSuggestion as gM,agentIcon as gN,LoopFrontendTool as gO,agentServerOf as gP,LoopCommand as gQ,subagentsFor as gR,useChatAvailability as gS,noRuntimeSaid as gT,useSlotComponents as gU,LoopSlots as gV,onPromptFocusRequest as gW,generateMessageId as gX,useConfig as gY,useSkills as gZ,useSkillActions as g_,EVENTS_SKILL_SPEC_0_0_1 as ga,TEXT_SUMMARIZER_SKILL_SPEC_0_0_1 as gb,GITHUB_SKILL_SPEC_0_0_1 as gc,CRAWL_SKILL_SPEC_0_0_1 as gd,useAnonymousInferenceSession as ge,browserModelRequiresSignIn as gf,getAgentspecs as gg,useOptionalReactorPlatform as gh,messagesOfThread as gi,FluentEmoji as gj,PRESENCE_LINES as gk,useChatWords as gl,CHAT_PLUGIN_NAME as gm,INPUT_PROMPT_PLUGIN_NAME as gn,LoopChatSurface as go,LoopChatComposer as gp,LoopChatHeader as gq,LoopChatLayout as gr,LoopChatTurn as gs,turnWritersOf as gt,LoopChatExtras as gu,computed$1 as gv,useGate as gw,presenceState as gx,presenceToolOf as gy,newestIsAnswer as gz,renderOcticon as h,StaticNotebook as h$,readServerDecisions as h0,offeredModels as h1,AI_MODEL_CATALOGUE as h2,isChatModel as h3,ReactorSlot as h4,ReactorLazy as h5,ChatBase as h6,ScreenNormalIcon as h7,ScreenFullIcon as h8,SUGGESTION_CHIP_WIDTH as h9,ThemeManager as hA,ToolbarWidgetRegistry as hB,Selector$1 as hC,Printing as hD,WindowResolver as hE,jupyterFaviconIcon as hF,caretDownEmptyIcon as hG,addToolbarButtonClass as hH,NotebookActions as hI,Toolbar as hJ,translateKernelStatuses as hK,offlineBoltIcon as hL,circleIcon as hM,MessageLoop as hN,Collapser$1 as hO,ObservableJSON as hP,ConflatableMessage as hQ,jumpBackIcon as hR,jumpForwardIcon as hS,MarkdownCell as hT,Cell$1 as hU,trustedIcon as hV,notTrustedIcon as hW,runCell as hX,InputPrompt$1 as hY,NotebookPanel as hZ,setCellExecutor as h_,Truncate as ha,useAnonymousSessionStore as hb,signal$2 as hc,LoopAgentGate as hd,agentRuntimeStore as he,loopShapeVars as hf,NONE_EDITOR as hg,filterListIcon as hh,CommandPalette$1 as hi,h$7 as hj,LabIconStyle as hk,ILicensesClient as hl,Licenses as hm,copyrightIcon as hn,ToolbarButtonComponent as ho,bellIcon as hp,clientExports as hq,Button$3 as hr,ModalCommandPalette as hs,paletteIcon as ht,Throttler as hu,IKernelStatusModel as hv,KernelStatus$1 as hw,RunningSessions as hx,IThemeManager as hy,ISplashScreen as hz,SquareFillIcon as i,useProperties as i$,notebookIcon as i0,NotebookSearchProvider as i1,duplicateIcon as i2,addAboveIcon as i3,addBelowIcon as i4,children$1 as i5,ref$2 as i6,html$7 as i7,startSlotTemplate as i8,endSlotTemplate as i9,focusStrokeWidth$1 as iA,strokeWidth$1 as iB,controlCornerRadius$1 as iC,heightNumber$1 as iD,neutralFillStealthHover$1 as iE,neutralFillStealthActive$1 as iF,designUnit$1 as iG,typeRampBaseFontSize$1 as iH,typeRampBaseLineHeight$1 as iI,density$1 as iJ,typeRampPlus1FontSize$1 as iK,disabledOpacity$1 as iL,disabledCursor as iM,baseHeightMultiplier$1 as iN,neutralFillRest$1 as iO,neutralFillHover$1 as iP,neutralFillActive$1 as iQ,accentForegroundRest$1 as iR,display as iS,css as iT,forcedColorsStylesheetBehavior as iU,SystemColors as iV,cssPartial as iW,DesignToken as iX,neutralFillStealthRecipe$1 as iY,neutralFillRecipe$1 as iZ,useEventListener as i_,slotted as ia,elements as ib,FoundationElement as ic,isHTMLElement as id,__decorate$1 as ie,attr as ig,observable as ih,applyMixins as ii,StartEnd as ij,keyEnter as ik,keyArrowUp as il,keyArrowDown as im,keyArrowRight as io,keyArrowLeft as ip,keyEnd as iq,keyHome as ir,DOM as is,getDisplayedNodes as it,direction$1 as iu,neutralForegroundRest$1 as iv,neutralFillStealthRest$1 as iw,bodyFont$1 as ix,focusVisible as iy,accentFillFocus$1 as iz,jsxRuntimeExports as j,CheckboxOrRadioGroupCaption as j$,provideJupyterDesignSystem$1 as j0,ITableOfContentsTracker as j1,tocIcon as j2,numberingIcon as j3,expandAllIcon as j4,collapseAllIcon as j5,ellipsesIcon as j6,VisuallyHidden$1 as j7,StopIcon as j8,ViewPlugin as j9,NotebookCommandIds as jA,OutputAreaModel as jB,useJupyterReactStore as jC,newUuid as jD,NotebookPanelProvider as jE,addNotebookCommands as jF,WIDGET_MIMETYPE as jG,rendererFactory$1 as jH,rendererFactory as jI,getMarked as jJ,createLatexTypesetter as jK,YArray as jL,YText as jM,newUlid as jN,k$2 as jO,loopColors as jP,sunColors as jQ,ivoryColors as jR,sandColors as jS,earthColors as jT,matrixColors as jU,lovelyColors as jV,spatialColors as jW,datalayerColors as jX,getColorPalette as jY,CheckboxOrRadioGroupValidation as jZ,CheckboxOrRadioGroupLabel as j_,createRelativePositionFromTypeIndex as ja,createRelativePositionFromJSON as jb,tooltips as jc,Facet as jd,Annotation as je,layer as jf,StateField as jg,showTooltip as jh,createAbsolutePositionFromRelativePosition as ji,RectangleMarker as jj,YDocument as jk,createCellModelFromSharedType as jl,createCell as jm,YMap as jn,RawCellModel as jo,MarkdownCellModel as jp,CodeCellModel as jq,MINOR_VERSION as jr,MAJOR_VERSION as js,SessionContext as jt,StateEffect as ju,Decoration as jv,WidgetType as jw,kernelIcon as jx,DEFAULT_VARIANT as jy,MarimoReactive as jz,TrashIcon as k,qc as k$,useRenderForcingRef as k0,CheckboxOrRadioGroup$1 as k1,CheckboxGroupContext as k2,Checkbox as k3,RadioGroup$1 as k4,Radio as k5,SelectPanel as k6,Select$1 as k7,TextInputWithTokens as k8,object as k9,qi as kA,Pi as kB,isStream as kC,isExecuteResult as kD,isDisplayData as kE,isError$2 as kF,Xo as kG,Ki as kH,Yi as kI,er as kJ,T as kK,v$2 as kL,S$1 as kM,C as kN,m$2 as kO,x$5 as kP,y$3 as kQ,p$4 as kR,ol as kS,He$2 as kT,pn$2 as kU,Kr as kV,ur as kW,ls as kX,cn$1 as kY,_n as kZ,hn$2 as k_,preprocess$1 as ka,record$1 as kb,string$2 as kc,unknown$1 as kd,zodToToolParameters as ke,array as kf,_enum as kg,number$2 as kh,boolean$1 as ki,validateWithZod as kj,whitespace as kk,svg$2 as kl,find as km,stringify$1 as kn,stringify as ko,ccount as kp,zwitch as kq,html$4 as kr,htmlVoidElements as ks,C$1 as kt,Dt$4 as ku,u$2 as kv,dt$2 as kw,Go as kx,ns as ky,mn$1 as kz,libExports$3 as l,rKernelIcon as l$,Ie$2 as l0,cs as l1,dr as l2,Jl as l3,fn$2 as l4,hn$1 as l5,pn$1 as l6,Wo as l7,xt$2 as l8,Zs as l9,hpass as lA,AccordionPanel as lB,caretDownIcon as lC,AccordionLayout as lD,FormAssociated as lE,nullableNumberConverter as lF,ARIAGlobalStatesAndProperties as lG,neutralFillInputRest$1 as lH,neutralFillStrongRest$1 as lI,errorFillRest$1 as lJ,neutralFillInputHover$1 as lK,neutralFillStrongHover$1 as lL,errorFillHover$1 as lM,neutralFillStrongActive$1 as lN,errorFillActive$1 as lO,errorFillFocus$1 as lP,neutralStrokeRest$1 as lQ,__decorate as lR,searchIcon as lS,jsonIcon as lT,BoxLayout as lU,VirtualDOM as lV,TextModelFactory as lW,pdfIcon as lX,pythonIcon as lY,juliaIcon as lZ,spreadsheetIcon as l_,gc as la,On as lb,na as lc,ea as ld,ia as le,sa as lf,useJupyter as lg,decodeNamedCharacterReference as lh,requireReact as li,StyleModule as lj,jupyterHighlightStyle as lk,requireDayjs_min as ll,useFocusZone as lm,FocusKeys as ln,useSafeTimeout as lo,useSlots as lp,useProvidedRefOrCreate as lq,useResponsiveValue as lr,ScrollableRegion as ls,viewportRanges as lt,JupyterLiteServer as lu,Router as lv,ContextMenu as lw,TabPanel$1 as lx,TabBar as ly,DockPanel as lz,PlusIcon as m,ClassicWidgetManager as m$,yamlIcon as m0,imageIcon as m1,audioIcon as m2,videoIcon as m3,writeVarUint as m4,encodeStateVector as m5,writeVarUint8Array as m6,encodeStateAsUpdate as m7,readVarUint as m8,applyUpdate as m9,filter$5 as mA,ElementExt as mB,caretUpIcon as mC,Poll as mD,each$1 as mE,Application as mF,StackedPanel as mG,tabIcon as mH,Base64ModelFactory as mI,useTerminalStore as mJ,InputViewer as mK,basicSetup as mL,drawSelection as mM,indentOnInput as mN,highlightActiveLine as mO,highlightSpecialChars as mP,highlightSelectionMatches as mQ,defaultKeymap as mR,searchKeymap as mS,requestAPI$1 as mT,loadJupyterConfig as mU,createLiteServiceManager as mV,jupyterReactStore as mW,ANSWER_MARKER as mX,BuilderManagerLess as mY,CellAdapter as mZ,CellCommands as m_,readVarUint8Array as ma,readVarString as mb,ObservableV2 as mc,Awareness as md,toUint8Array$1 as me,length as mf,encodeAwarenessUpdate as mg,removeAwarenessStates as mh,isNode as mi,getUnixTime as mj,createEncoder as mk,min$1 as ml,pow as mm,createDecoder as mn,applyAwarenessUpdate as mo,BoxPanel as mp,Cell as mq,UndoManager as mr,Doc$1 as ms,SplitPanel as mt,RawCell as mu,isCodeCellModel as mv,Drag as mw,MimeData as mx,useConsoleStore as my,folderFavoriteIcon as mz,CodeIcon as n,isServedByJupyterLab as n$,CodeMirrorDatalayerEditor as n0,CodeMirrorEditor as n1,CodeMirrorOutputToolbar as n2,ContentsManagerLess as n3,DEFAULT_API_KERNEL_PREFIX_URL as n4,DEFAULT_JUPYTER_SERVER_TOKEN as n5,DEFAULT_JUPYTER_SERVER_URL as n6,DEFAULT_KERNEL_NAME as n7,DefaultExecutor as n8,EventsManagerLess as n9,UserManagerLess as nA,WidgetRenderer as nB,WorkspaceManagerLess as nC,cellSourceAsString as nD,cellsStore as nE,codeMirrorTheme as nF,consoleStore as nG,createLiteServer as nH,createServerSettings as nI,deleteCellsOperation as nJ,deleteCellsTool as nK,disableKernelReconnect as nL,disposeKernelConnections as nM,ensureJupyterAuth as nN,ensureJupyterConfig as nO,execute as nP,executeCodeOperation as nQ,executeCodeTool as nR,formatResponse as nS,getCookie as nT,getJupyterServerToken as nU,getJupyterServerUrl as nV,getKernelIndicatorMeta as nW,insertCellOperation as nX,insertCellTool as nY,isAnyCellRunning as nZ,isReactiveVariant as n_,ExecutionPhase as na,HELPER_NAME as nb,HTMLManager as nc,JupyterLabCss as nd,KERNEL_HELPER_SOURCE as ne,KERNEL_STATES as nf,KERNEL_STATE_LABELS as ng,KERNEL_STATE_VISUALS as nh,KernelActionMenu as ni,KernelExecutor as nj,KernelManagerLess as nk,KernelProgressBar as nl,KernelspecManagerLess as nm,MIME_TYPE$1 as nn,NbConvertManagerLess as no,OperationRunner as np,Output as nq,OutputAdapter as nr,OutputRenderer as ns,OutputViewer as nt,OutputViewerAdapter as nu,RenderedPlotly as nv,ServiceManagerLess as nw,SessionManagerLess as nx,SettingManagerLess as ny,TerminalManagerLess as nz,formatTokenCount as o,rn$1 as o$,jupyterLabTheme as o0,kernelsStore as o1,loadJupyterLabCss as o2,notebookToolDefinitions as o3,notebookToolOperations as o4,notebookTools as o5,outputsAsString as o6,outputsStore as o7,readAllCellsOperation as o8,readAllCellsTool as o9,bu as oA,Nu as oB,Wl as oC,Fr as oD,Li as oE,Vc as oF,Fo as oG,sn$1 as oH,vc as oI,tr as oJ,Sn as oK,Zo as oL,Cu as oM,Bs as oN,Me as oO,yn as oP,Se as oQ,Cn as oR,fn as oS,qr as oT,Ia as oU,zs as oV,gn$2 as oW,or as oX,Jr as oY,sn$2 as oZ,ln$1 as o_,readCellOperation as oa,readCellTool as ob,refreshJupyterLabPortalTheme as oc,renderKernelStateGlyph as od,renderWidgets as oe,rendererFactory$2 as of,resetJupyterConfig as og,runCellOperation as oh,runCellTool as oi,setJupyterServerToken as oj,setJupyterServerUrl as ok,sleep as ol,syncJupyterLabPortalTheme as om,terminalStore as on,toKernelState as oo,updateCellOperation as op,updateCellTool as oq,useCellsStore as or,useJupyterReactColormode as os,useJupyterReactStoreFromProps as ot,useKernelsStore as ou,useOutputsStore as ov,ThemeProvider as ow,Overlay$1 as ox,Fi as oy,Zl as oz,useSandboxService as p,Xe$2 as p$,nn$2 as p0,Vr as p1,nu as p2,du as p3,Va as p4,au as p5,La as p6,Is as p7,Dl as p8,h$1 as p9,oa as pA,Cn$1 as pB,et as pC,xn as pD,St as pE,Rt as pF,xt as pG,yn$1 as pH,It$1 as pI,Tt as pJ,l$2 as pK,a$2 as pL,d$2 as pM,s$2 as pN,Ue$2 as pO,dn$2 as pP,$e$2 as pQ,un$1 as pR,Bi as pS,It as pT,en$2 as pU,_$1 as pV,te$2 as pW,le$2 as pX,on$2 as pY,$t$3 as pZ,mn$2 as p_,Sn$1 as pa,Nn$1 as pb,ce$1 as pc,Tu as pd,vu as pe,ae$1 as pf,xt$3 as pg,St$3 as ph,Pc as pi,Lc as pj,Ic as pk,mt$3 as pl,rs as pm,an$1 as pn,Je$2 as po,Ft$1 as pp,Os as pq,Mt$1 as pr,gt as ps,Co as pt,Tn as pu,Dt as pv,So as pw,vn as px,kn$1 as py,xl as pz,useSignalValue$1 as q,Ul as q$,gr as q0,Ge$2 as q1,_r as q2,Ve$2 as q3,je$1 as q4,Ye$1 as q5,qe$2 as q6,Yt as q7,Ya as q8,Pe$2 as q9,Al as qA,No as qB,bo as qC,as as qD,_t as qE,eu as qF,fc as qG,Re as qH,Kc as qI,Wt$1 as qJ,z$2 as qK,ac as qL,On$1 as qM,Ht$1 as qN,Le$2 as qO,zr as qP,Bt$1 as qQ,Ll as qR,ui as qS,ec as qT,nc as qU,zt$1 as qV,Ir as qW,i$1 as qX,uu as qY,Aa as qZ,Wa as q_,Ja as qa,tu as qb,zl as qc,Fl as qd,Ma as qe,ja as qf,Hl as qg,Ba as qh,Bl as qi,Pr as qj,Pe as qk,uo as ql,mu as qm,iu as qn,ku as qo,Mo as qp,Rl as qq,wu as qr,Fn as qs,lc as qt,$s as qu,he as qv,Fe as qw,Ut$1 as qx,We as qy,Fs as qz,reactExports as r,oe$1 as r$,ql as r0,dc as r1,be as r2,ke as r3,ft as r4,pi as r5,x$4 as r6,z as r7,O$1 as r8,r$2 as r9,vi as rA,Ql as rB,ut$2 as rC,Gl as rD,ReactDOM as rE,M$2 as rF,PersonIcon as rG,Pt$1 as rH,s$1 as rI,f$3 as rJ,P$1 as rK,fe$1 as rL,PaperAirplaneIcon as rM,bn$2 as rN,TableIcon as rO,q as rP,ChecklistIcon as rQ,fn$1 as rR,GrabberIcon as rS,vo as rT,yo as rU,wo as rV,mo as rW,j$1 as rX,r$3 as rY,$2AODx$react as rZ,jt$1 as r_,t$2 as ra,Es as rb,_s as rc,vt$2 as rd,n$2 as re,b$1 as rf,nn$1 as rg,r$1 as rh,g$1 as ri,Tt$2 as rj,ys as rk,e$1 as rl,vl as rm,u$1 as rn,b$3 as ro,z$1 as rp,zi as rq,Ji as rr,ko as rs,To as rt,Ze$2 as ru,Qe$2 as rv,Mn$1 as rw,wn$1 as rx,En$1 as ry,xo as rz,sandboxIsLive as s,requireIsObject as s$,ie$2 as s0,PaintbrushIcon as s1,RowsIcon as s2,x$2 as s3,AlertFillIcon as s4,ArrowRightIcon as s5,BeakerIcon as s6,BellIcon as s7,BookIcon as s8,BroadcastIcon as s9,RssIcon as sA,ShareAndroidIcon as sB,ShieldCheckIcon as sC,ShieldIcon as sD,SidebarExpandIcon as sE,SkipIcon as sF,SlidersIcon as sG,SparkleFillIcon as sH,SquareCircleIcon as sI,SunIcon as sJ,TagIcon as sK,TasklistIcon as sL,ThumbsdownIcon as sM,ThumbsupIcon as sN,UnmuteIcon as sO,UploadIcon as sP,XCircleFillIcon as sQ,ZapIcon as sR,require_Symbol as sS,requireIsArguments as sT,requireIsArray as sU,require_arrayPush as sV,require_baseGetTag as sW,requireIsObjectLike as sX,require_MapCache as sY,require_Stack as sZ,require_baseIsEqual as s_,BrowserIcon as sa,BugIcon as sb,CircleSlashIcon as sc,CodeReviewIcon as sd,CpuIcon as se,CreditCardIcon as sf,DependabotIcon as sg,DeviceDesktopIcon as sh,DeviceMobileIcon as si,FoldIcon as sj,GearIcon as sk,GitBranchIcon as sl,GlobeIcon as sm,HeartIcon as sn,IssueOpenedIcon as so,LightBulbIcon as sp,LinkExternalIcon as sq,MegaphoneIcon as sr,MortarBoardIcon as ss,MuteIcon as st,OrganizationIcon as su,PackageIcon as sv,PaperclipIcon as sw,PeopleIcon as sx,PulseIcon as sy,RocketIcon as sz,timeLeft as t,TUTOR_VIEW as t$,requireKeys as t0,require_isIndex as t1,requireIsLength as t2,requireIdentity as t3,require_baseFor as t4,requireIsArrayLike as t5,require_baseUnary as t6,require_baseRest as t7,require_isIterateeCall as t8,require_Set as t9,getAugmentedNamespace as tA,index_esm as tB,__assign as tC,requireReactDom as tD,__extends as tE,__awaiter as tF,__rest as tG,__generator as tH,darker as tI,brighter as tJ,require$$0$4 as tK,requireBase64Js as tL,hsl as tM,requireObjectAssign as tN,ulid$1 as tO,AGENTS_VIEW as tP,CONTENTS_VIEW as tQ,DATALAYER_VIEW as tR,JWT_DATALAYER_ISSUER as tS,JWT_REFRESH_TOKEN_COOKIE_NAME as tT,LIBRARY_VIEW as tU,NAVIGATION_VIEW_HOMES as tV,RESERVATION_WARNING_TIME_MS as tW,SESSION_COOKIES as tX,SESSION_LOCAL_STORAGE_KEYS as tY,SESSION_OWNER_KEY as tZ,SETTINGS_VIEW as t_,require_setToArray as ta,require_SetCache as tb,require_cacheHas as tc,requireEq$1 as td,requireKeysIn as te,requireIsArrayLikeObject as tf,requireIsEqual as tg,requireIsPlainObject$1 as th,require_baseMerge as ti,require_createAssigner as tj,require_apply as tk,require_copyArray as tl,require_arrayEach as tm,requireCloneDeep as tn,requireFastDeepEqual as to,requireFastUri as tp,ForwardRef$2 as tq,ForwardRef$1 as tr,ForwardRef as ts,memoize$1 as tt,isPropValid as tu,tabbable as tv,focusable as tw,isTabbable as tx,getTabIndex as ty,isFocusable as tz,useNotebookStore$1 as u,claimSessionState as u0,forgetSessionState as u1,getOtelConsumeUrl as u2,getStoredToken as u3,getStoredUser as u4,isRememberableRoute as u5,isShellNeutralRoute as u6,loadRefreshTokenFromCookie as u7,navigationStore as u8,pageConfiguration as u9,profileStore as ua,registerSessionState as ub,storeToken as uc,storeUser as ud,useNavigationStore as ue,useProfile as uf,useProfileStore as ug,viewForRoute as uh,__spreadArray as ui,index$4 as uj,index$3 as uk,index$2 as ul,katex$1 as um,Lexical_prod as un,LexicalUtils_prod as uo,vM as v,datalayerCatalog as w,ChatBaseHeader as x,useContributions as y,LoopPromptPanel as z};
|
|
@@ -70,7 +70,7 @@ import { parseAppspec } from '../apps/appspec';
|
|
|
70
70
|
import { readAppspecYaml } from '../apps/yaml';
|
|
71
71
|
import { AppEmbed, embedAssistantCharacter } from './AppEmbed';
|
|
72
72
|
import { WINDOW_NOT_YET } from './embedSession';
|
|
73
|
-
import { EMBED_HOST_VARIABLES, EMBED_OBSERVED_ATTRIBUTES, EMBED_TAG, EmbedAttributeError, embedLookOf, inlineHeightOf, languageOf, resumeOf, runnable, } from './embedConfig';
|
|
73
|
+
import { EMBED_HOST_VARIABLES, EMBED_OBSERVED_ATTRIBUTES, EMBED_TAG, EmbedAttributeError, adoptPropertiesSetEarly, embedLookOf, inlineHeightOf, languageOf, resumeOf, runnable, } from './embedConfig';
|
|
74
74
|
import { embedShadowCss } from './embedTheme';
|
|
75
75
|
import { DEFAULT_API, readVisitorApp } from './visitorApp';
|
|
76
76
|
export { runnable };
|
|
@@ -259,6 +259,8 @@ export function defineDatalayerAppElement(options = {}) {
|
|
|
259
259
|
super();
|
|
260
260
|
this.attachShadow({ mode: 'open' });
|
|
261
261
|
this.onMessage = this.onMessage.bind(this);
|
|
262
|
+
// What the page set before the element was defined (D-10).
|
|
263
|
+
adoptPropertiesSetEarly(this);
|
|
262
264
|
}
|
|
263
265
|
/** An embed token, the attribute's. Set it to hand a new one over. */
|
|
264
266
|
get token() {
|
|
@@ -120,6 +120,22 @@ export declare function resumeOf(value: string | null | undefined): boolean;
|
|
|
120
120
|
export declare function languageOf(value: string | null | undefined): string | undefined;
|
|
121
121
|
/** The height of an inline application, in pixels. */
|
|
122
122
|
export declare function inlineHeightOf(value: string | null | undefined): number;
|
|
123
|
+
/**
|
|
124
|
+
* The element's properties a page may set (D-10, D-08): what it passes, the
|
|
125
|
+
* functions it offers and the embed token.
|
|
126
|
+
*/
|
|
127
|
+
export declare const EMBED_PROPERTIES: readonly ["context", "functions", "token"];
|
|
128
|
+
/**
|
|
129
|
+
* Hand the element's own setters what the page set before it was defined.
|
|
130
|
+
*
|
|
131
|
+
* The script is loaded `async` and its module is imported after it, so a page
|
|
132
|
+
* that sets `element.functions` or `element.context` right after writing the
|
|
133
|
+
* element sets them on an element not yet upgraded: each becomes a property
|
|
134
|
+
* of that object, which shadows the class's accessor once it is defined, and
|
|
135
|
+
* the application was never offered the page's functions (seen 2026-10-10,
|
|
136
|
+
* STUDIO D-10: the run sent no tool). Called as the element is constructed.
|
|
137
|
+
*/
|
|
138
|
+
export declare function adoptPropertiesSetEarly(element: object, names?: readonly string[]): string[];
|
|
123
139
|
/** What a snippet says beside the application's id. */
|
|
124
140
|
export type EmbedSnippetOptions = {
|
|
125
141
|
/** Where Datalayer is: the script's origin, and the element's. */
|
|
@@ -161,6 +161,34 @@ const attributeValue = (value) => value
|
|
|
161
161
|
.replace(/"/g, '"')
|
|
162
162
|
.replace(/</g, '<')
|
|
163
163
|
.replace(/>/g, '>');
|
|
164
|
+
/**
|
|
165
|
+
* The element's properties a page may set (D-10, D-08): what it passes, the
|
|
166
|
+
* functions it offers and the embed token.
|
|
167
|
+
*/
|
|
168
|
+
export const EMBED_PROPERTIES = ['context', 'functions', 'token'];
|
|
169
|
+
/**
|
|
170
|
+
* Hand the element's own setters what the page set before it was defined.
|
|
171
|
+
*
|
|
172
|
+
* The script is loaded `async` and its module is imported after it, so a page
|
|
173
|
+
* that sets `element.functions` or `element.context` right after writing the
|
|
174
|
+
* element sets them on an element not yet upgraded: each becomes a property
|
|
175
|
+
* of that object, which shadows the class's accessor once it is defined, and
|
|
176
|
+
* the application was never offered the page's functions (seen 2026-10-10,
|
|
177
|
+
* STUDIO D-10: the run sent no tool). Called as the element is constructed.
|
|
178
|
+
*/
|
|
179
|
+
export function adoptPropertiesSetEarly(element, names = EMBED_PROPERTIES) {
|
|
180
|
+
const adopted = [];
|
|
181
|
+
const record = element;
|
|
182
|
+
for (const name of names) {
|
|
183
|
+
if (Object.prototype.hasOwnProperty.call(element, name)) {
|
|
184
|
+
const value = record[name];
|
|
185
|
+
delete record[name];
|
|
186
|
+
record[name] = value;
|
|
187
|
+
adopted.push(name);
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
return adopted;
|
|
191
|
+
}
|
|
164
192
|
/**
|
|
165
193
|
* The snippet a host pastes (D-08): one script tag and one element. A public
|
|
166
194
|
* application needs no token; a private one takes the token its owner was
|
|
@@ -1653,6 +1653,16 @@ export default function ChatView({ workspace }) {
|
|
|
1653
1653
|
// placeholder does: a dead control with no explanation is worse
|
|
1654
1654
|
// than an absent one.
|
|
1655
1655
|
disabled: chatDisabled, disableReason: disabledReason, protocol: protocol,
|
|
1656
|
+
/*
|
|
1657
|
+
The page's own tools — a host page's functions (LOOP D-10), an
|
|
1658
|
+
example's client tool — run by this chat when the agent is on a
|
|
1659
|
+
server: sent with each run and executed here when it calls
|
|
1660
|
+
one. An in-page agent is handed them in its protocol instead
|
|
1661
|
+
(above); given to both, each would run twice. Without this an
|
|
1662
|
+
embedded application's run carried no tool at all (seen
|
|
1663
|
+
2026-10-10: `toolsForRequest: []`).
|
|
1664
|
+
*/
|
|
1665
|
+
frontendTools: inPage ? undefined : chatExtras.frontendTools,
|
|
1656
1666
|
/*
|
|
1657
1667
|
The model this view is on, as the chat's opening pick.
|
|
1658
1668
|
|