@datalayer/agent-runtimes 1.3.97 → 1.3.99

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.
@@ -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 bn,ga as vn,gb as wn,gc as xn,gd as kn,aP as Sn,ey as Ro,ew as Cn,ez as qt,ge as En,gf as Tn,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 bo,gS as ca,gT as la,fh as da,gU as Ot,gV as je,gW as ua,c3 as vo,gX as pa,gY as ha,gZ as ma,g_ as ga,g$ as fa,h0 as ya,h1 as ba,h2 as va,h3 as wa,h4 as Nt,h5 as xa,h6 as ka,I as Sa,h7 as Ca,h8 as Ea,h9 as wo,ha as Ta,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`
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=En(s,e&&!i),p=i||l.token,m=n.useMemo(()=>({inferenceUrl:s,token:p||void 0}),[s,p]);return{inference:m,needsSignIn:Tn(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(`
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 Eo(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 bs(){const e=In(),a=La();return n.useMemo(()=>ys(a,e),[a,e])}const To={opening:"Opening your conversation…",notOpened:e=>`Your conversation could not be opened, so this is a new one: ${e}`};function vs(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=vs(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),Es=$t(""),Ts=$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),b=n.useRef(!1),E=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]),x=_t(Oe.length>0?gt:Ts),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 w={saying:Wn(t),answering:Vn(t)},h=C.current;(h.saying?.id!==w.saying?.id||h.saying?.text!==w.saying?.text||h.answering!==w.answering)&&(C.current=w,et.current?.(w));const G=B.current;if(!G)return;G.items(t);const H=new Set(["complete","completed","done","error","failed","cancelled","canceled","rejected","denied","stopped"]),Te={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 I;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())||(I=ut);break}}if(!I){G.activity(void 0);return}const At=I.toolName.toLowerCase().replace(/^datalayer_/,"").replace(/_lexical$/,"").replace(/[^a-z]/g,""),sn=Te[At]??`using ${I.toolName}`;G.activity(`${J.current||"The agent"} is ${sn}…`)},[]),Ne=n.useRef(x);Ne.current=x;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 w=t.slice(d+1).filter(h=>h.role==="assistant").map(Kn).filter(h=>h.trim().length>0).join(`
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};