@datalayer/agent-runtimes 1.5.15 → 1.5.16
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.
|
@@ -2096,7 +2096,7 @@ Please change the parent <Route path="${Vu}"> to <Route path="${Vu==="/"?"*":`${
|
|
|
2096
2096
|
[zustand devtools middleware] Unsupported __setState action format.
|
|
2097
2097
|
When using 'store' option in devtools(), the 'state' should have only one key, which is a value of 'store' that was passed in devtools(),
|
|
2098
2098
|
and value of this only key should be a state object. Example: { "type": "__setState", "state": { "abc123Store": { "foo": "bar" } } }
|
|
2099
|
-
`);const Wu=Gu.state[Mu];if(Wu==null)return;JSON.stringify(Iu.getState())!==JSON.stringify(Wu)&&zu(Wu);return}Iu.dispatchFromDevtools&&typeof Iu.dispatch=="function"&&Iu.dispatch(Gu)});case"DISPATCH":switch(Hu.payload.type){case"RESET":return zu(Uu),Mu===void 0?Bu?.init(Iu.getState()):Bu?.init(getTrackedConnectionState(Du.name));case"COMMIT":if(Mu===void 0){Bu?.init(Iu.getState());return}return Bu?.init(getTrackedConnectionState(Du.name));case"ROLLBACK":return parseJsonThen(Hu.state,Gu=>{if(Mu===void 0){zu(Gu),Bu?.init(Iu.getState());return}zu(Gu[Mu]),Bu?.init(getTrackedConnectionState(Du.name))});case"JUMP_TO_STATE":case"JUMP_TO_ACTION":return parseJsonThen(Hu.state,Gu=>{if(Mu===void 0){zu(Gu);return}JSON.stringify(Iu.getState())!==JSON.stringify(Gu[Mu])&&zu(Gu[Mu])});case"IMPORT_STATE":{const{nextLiftedState:Gu}=Hu.payload,Wu=(Vu=Gu.computedStates.slice(-1)[0])==null?void 0:Vu.state;if(!Wu)return;zu(Mu===void 0?Wu:Wu[Mu]),Bu?.send(null,Gu);return}case"PAUSE_RECORDING":return Fu=!Fu}return}}),Uu},devtools=devtoolsImpl,parseJsonThen=(Au,lo)=>{let $u;try{$u=JSON.parse(Au)}catch(Ru){console.error("[zustand devtools middleware] Could not parse the received json",Ru)}$u!==void 0&&lo($u)},subscribeWithSelectorImpl=Au=>(lo,$u,Ru)=>{const Iu=Ru.subscribe;return Ru.subscribe=(Ou,Mu,Du)=>{let Lu=Ou;if(Mu){const Bu=Du?.equalityFn||Object.is;let ju=Ou(Ru.getState());Lu=Fu=>{const zu=Ou(Fu);if(!Bu(ju,zu)){const Uu=ju;Mu(ju=zu,Uu)}},Du?.fireImmediately&&Mu(ju,ju)}return Iu(Lu)},Au(lo,$u,Ru)},subscribeWithSelector=subscribeWithSelectorImpl;function createJSONStorage(Au,lo){let $u;try{$u=Au()}catch{return}return{getItem:Iu=>{var Pu;const Ou=Du=>Du===null?null:JSON.parse(Du,void 0),Mu=(Pu=$u.getItem(Iu))!=null?Pu:null;return Mu instanceof Promise?Mu.then(Ou):Ou(Mu)},setItem:(Iu,Pu)=>$u.setItem(Iu,JSON.stringify(Pu,void 0)),removeItem:Iu=>$u.removeItem(Iu)}}const toThenable=Au=>lo=>{try{const $u=Au(lo);return $u instanceof Promise?$u:{then(Ru){return toThenable(Ru)($u)},catch(Ru){return this}}}catch($u){return{then(Ru){return this},catch(Ru){return toThenable(Ru)($u)}}}},oldImpl=(Au,lo)=>($u,Ru,Iu)=>{let Pu={getStorage:()=>localStorage,serialize:JSON.stringify,deserialize:JSON.parse,partialize:Vu=>Vu,version:0,merge:(Vu,Gu)=>({...Gu,...Vu}),...lo},Ou=!1;const Mu=new Set,Du=new Set;let Lu;try{Lu=Pu.getStorage()}catch{}if(!Lu)return Au((...Vu)=>{console.warn(`[zustand persist middleware] Unable to update item '${Pu.name}', the given storage is currently unavailable.`),$u(...Vu)},Ru,Iu);const Bu=toThenable(Pu.serialize),ju=()=>{const Vu=Pu.partialize({...Ru()});let Gu;const Wu=Bu({state:Vu,version:Pu.version}).then(Ku=>Lu.setItem(Pu.name,Ku)).catch(Ku=>{Gu=Ku});if(Gu)throw Gu;return Wu},Fu=Iu.setState;Iu.setState=(Vu,Gu)=>{Fu(Vu,Gu),ju()};const zu=Au((...Vu)=>{$u(...Vu),ju()},Ru,Iu);let Uu;const Hu=()=>{var Vu;if(!Lu)return;Ou=!1,Mu.forEach(Wu=>Wu(Ru()));const Gu=((Vu=Pu.onRehydrateStorage)==null?void 0:Vu.call(Pu,Ru()))||void 0;return toThenable(Lu.getItem.bind(Lu))(Pu.name).then(Wu=>{if(Wu)return Pu.deserialize(Wu)}).then(Wu=>{if(Wu)if(typeof Wu.version=="number"&&Wu.version!==Pu.version){if(Pu.migrate)return Pu.migrate(Wu.state,Wu.version);console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return Wu.state}).then(Wu=>{var Ku;return Uu=Pu.merge(Wu,(Ku=Ru())!=null?Ku:zu),$u(Uu,!0),ju()}).then(()=>{Gu?.(Uu,void 0),Ou=!0,Du.forEach(Wu=>Wu(Uu))}).catch(Wu=>{Gu?.(void 0,Wu)})};return Iu.persist={setOptions:Vu=>{Pu={...Pu,...Vu},Vu.getStorage&&(Lu=Vu.getStorage())},clearStorage:()=>{Lu?.removeItem(Pu.name)},getOptions:()=>Pu,rehydrate:()=>Hu(),hasHydrated:()=>Ou,onHydrate:Vu=>(Mu.add(Vu),()=>{Mu.delete(Vu)}),onFinishHydration:Vu=>(Du.add(Vu),()=>{Du.delete(Vu)})},Hu(),Uu||zu},newImpl=(Au,lo)=>($u,Ru,Iu)=>{let Pu={storage:createJSONStorage(()=>localStorage),partialize:Hu=>Hu,version:0,merge:(Hu,Vu)=>({...Vu,...Hu}),...lo},Ou=!1;const Mu=new Set,Du=new Set;let Lu=Pu.storage;if(!Lu)return Au((...Hu)=>{console.warn(`[zustand persist middleware] Unable to update item '${Pu.name}', the given storage is currently unavailable.`),$u(...Hu)},Ru,Iu);const Bu=()=>{const Hu=Pu.partialize({...Ru()});return Lu.setItem(Pu.name,{state:Hu,version:Pu.version})},ju=Iu.setState;Iu.setState=(Hu,Vu)=>{ju(Hu,Vu),Bu()};const Fu=Au((...Hu)=>{$u(...Hu),Bu()},Ru,Iu);Iu.getInitialState=()=>Fu;let zu;const Uu=()=>{var Hu,Vu;if(!Lu)return;Ou=!1,Mu.forEach(Wu=>{var Ku;return Wu((Ku=Ru())!=null?Ku:Fu)});const Gu=((Vu=Pu.onRehydrateStorage)==null?void 0:Vu.call(Pu,(Hu=Ru())!=null?Hu:Fu))||void 0;return toThenable(Lu.getItem.bind(Lu))(Pu.name).then(Wu=>{if(Wu)if(typeof Wu.version=="number"&&Wu.version!==Pu.version){if(Pu.migrate)return[!0,Pu.migrate(Wu.state,Wu.version)];console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return[!1,Wu.state];return[!1,void 0]}).then(Wu=>{var Ku;const[Ju,Yu]=Wu;if(zu=Pu.merge(Yu,(Ku=Ru())!=null?Ku:Fu),$u(zu,!0),Ju)return Bu()}).then(()=>{Gu?.(zu,void 0),zu=Ru(),Ou=!0,Du.forEach(Wu=>Wu(zu))}).catch(Wu=>{Gu?.(void 0,Wu)})};return Iu.persist={setOptions:Hu=>{Pu={...Pu,...Hu},Hu.storage&&(Lu=Hu.storage)},clearStorage:()=>{Lu?.removeItem(Pu.name)},getOptions:()=>Pu,rehydrate:()=>Uu(),hasHydrated:()=>Ou,onHydrate:Hu=>(Mu.add(Hu),()=>{Mu.delete(Hu)}),onFinishHydration:Hu=>(Du.add(Hu),()=>{Du.delete(Hu)})},Pu.skipHydration||Uu(),zu||Fu},persistImpl=(Au,lo)=>"getStorage"in lo||"serialize"in lo||"deserialize"in lo?((__vite_import_meta_env__?"production":void 0)!=="production"&&console.warn("[DEPRECATED] `getStorage`, `serialize` and `deserialize` options are deprecated. Use `storage` option instead."),oldImpl(Au,lo)):newImpl(Au,lo),persist=persistImpl,defaultChatConfig={defaultProvider:"datalayer",defaultProtocol:"vercel-ai",enableStreaming:!0,requireToolApproval:!1,debug:!1,persistToLocalStorage:!1},initialState$1={config:defaultChatConfig,ready:!0,inferenceProvider:null,protocolAdapter:null,toolExecutor:null,middlewarePipeline:null,uiPluginRegistry:null,messages:[],isLoading:!1,isStreaming:!1,streamingMessageId:null,currentThreadId:null,threads:new Map,tools:new Map,pendingToolCalls:new Map,uiPlugins:new Map,middlewares:[],isOpen:!1,error:null,suggestions:[]},useChatStore=create$g()(devtools(subscribeWithSelector((Au,lo)=>({...initialState$1,setConfig:$u=>{Au(Ru=>({config:{...Ru.config,...$u}}),!1,"setConfig")},setReady:$u=>{Au({ready:$u},!1,"setReady")},setInferenceProvider:$u=>{Au({inferenceProvider:$u},!1,"setInferenceProvider")},setProtocolAdapter:$u=>{Au({protocolAdapter:$u},!1,"setProtocolAdapter")},setToolExecutor:$u=>{Au({toolExecutor:$u},!1,"setToolExecutor")},setMiddlewarePipeline:$u=>{Au({middlewarePipeline:$u},!1,"setMiddlewarePipeline")},setUIPluginRegistry:$u=>{Au({uiPluginRegistry:$u},!1,"setUIPluginRegistry")},addMessage:$u=>{Au(Ru=>({messages:[...Ru.messages,$u]}),!1,"addMessage")},updateMessage:($u,Ru)=>{Au(Iu=>({messages:Iu.messages.map(Pu=>Pu.id===$u?{...Pu,...Ru}:Pu)}),!1,"updateMessage")},deleteMessage:$u=>{Au(Ru=>({messages:Ru.messages.filter(Iu=>Iu.id!==$u)}),!1,"deleteMessage")},setMessages:$u=>{Au({messages:$u},!1,"setMessages")},clearMessages:()=>{Au({messages:[]},!1,"clearMessages")},startStreaming:$u=>{Au({isStreaming:!0,streamingMessageId:$u},!1,"startStreaming")},appendToStream:($u,Ru)=>{Au(Iu=>({messages:Iu.messages.map(Pu=>Pu.id===$u?{...Pu,content:typeof Pu.content=="string"?Pu.content+Ru:Pu.content}:Pu)}),!1,"appendToStream")},stopStreaming:()=>{Au({isStreaming:!1,streamingMessageId:null},!1,"stopStreaming")},setLoading:$u=>{Au({isLoading:$u},!1,"setLoading")},setError:$u=>{Au({error:$u},!1,"setError")},setCurrentThread:$u=>{Au({currentThreadId:$u},!1,"setCurrentThread")},createThread:$u=>{const Ru=`thread_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,Iu={id:Ru,title:$u||"New Chat",createdAt:new Date,updatedAt:new Date};return Au(Pu=>{const Ou=new Map(Pu.threads);return Ou.set(Ru,Iu),{threads:Ou,currentThreadId:Ru}},!1,"createThread"),Ru},deleteThread:$u=>{Au(Ru=>{const Iu=new Map(Ru.threads);return Iu.delete($u),{threads:Iu,currentThreadId:Ru.currentThreadId===$u?null:Ru.currentThreadId}},!1,"deleteThread")},registerTool:$u=>{Au(Ru=>{const Iu=new Map(Ru.tools);return Iu.set($u.name,{definition:$u,registeredAt:new Date}),{tools:Iu}},!1,"registerTool")},unregisterTool:$u=>{Au(Ru=>{const Iu=new Map(Ru.tools);return Iu.delete($u),{tools:Iu}},!1,"unregisterTool")},getTool:$u=>lo().tools.get($u),getTools:()=>Array.from(lo().tools.values()).map($u=>$u.definition),startToolCall:($u,Ru,Iu)=>{Au(Pu=>{const Ou=new Map(Pu.pendingToolCalls);return Ou.set($u,{toolCallId:$u,toolName:Ru,args:Iu,status:"pending",startedAt:new Date}),{pendingToolCalls:Ou}},!1,"startToolCall")},updateToolCallStatus:($u,Ru,Iu,Pu)=>{Au(Ou=>{const Mu=new Map(Ou.pendingToolCalls),Du=Mu.get($u);return Du&&Mu.set($u,{...Du,status:Ru,result:Iu,error:Pu,completedAt:Ru==="completed"||Ru==="failed"?new Date:void 0}),{pendingToolCalls:Mu}},!1,"updateToolCallStatus")},getPendingToolCalls:()=>Array.from(lo().pendingToolCalls.values()).filter($u=>$u.status==="pending"||$u.status==="executing"),registerUIPlugin:($u,Ru)=>{Au(Iu=>{const Pu=new Map(Iu.uiPlugins);return Pu.set($u.name,{plugin:$u,enabled:Ru?.enabled??!0,registeredAt:new Date}),{uiPlugins:Pu}},!1,"registerUIPlugin")},unregisterUIPlugin:$u=>{Au(Ru=>{const Iu=new Map(Ru.uiPlugins);return Iu.delete($u),{uiPlugins:Iu}},!1,"unregisterUIPlugin")},enableUIPlugin:$u=>{Au(Ru=>{const Iu=new Map(Ru.uiPlugins),Pu=Iu.get($u);return Pu&&Iu.set($u,{...Pu,enabled:!0}),{uiPlugins:Iu}},!1,"enableUIPlugin")},disableUIPlugin:$u=>{Au(Ru=>{const Iu=new Map(Ru.uiPlugins),Pu=Iu.get($u);return Pu&&Iu.set($u,{...Pu,enabled:!1}),{uiPlugins:Iu}},!1,"disableUIPlugin")},getUIPlugins:$u=>{const Ru=Array.from(lo().uiPlugins.values()).filter(Iu=>Iu.enabled).map(Iu=>Iu.plugin);return $u?Ru.filter(Iu=>Iu.type===$u):Ru},addMiddleware:$u=>{Au(Ru=>({middlewares:[...Ru.middlewares,$u].sort((Iu,Pu)=>(Iu.priority??100)-(Pu.priority??100))}),!1,"addMiddleware")},removeMiddleware:$u=>{Au(Ru=>({middlewares:Ru.middlewares.filter(Iu=>Iu.name!==$u)}),!1,"removeMiddleware")},getMiddlewares:()=>lo().middlewares,setOpen:$u=>{Au({isOpen:$u},!1,"setOpen")},toggleOpen:()=>{Au($u=>({isOpen:!$u.isOpen}),!1,"toggleOpen")},setSuggestions:$u=>{Au({suggestions:$u},!1,"setSuggestions")},reset:()=>{Au(initialState$1,!1,"reset")}})),{name:"chat-store"})),useChatMessages=()=>useChatStore(Au=>Au.messages),useChatOpen=()=>useChatStore(Au=>Au.isOpen),initialState={conversations:{}},useConversationStore=create$g()(devtools(subscribeWithSelector((Au,lo)=>({...initialState,getMessages:$u=>lo().conversations[$u]?.messages||[],setMessages:($u,Ru)=>{Au(Iu=>({conversations:{...Iu.conversations,[$u]:{runtimeId:$u,messages:Ru,updatedAt:Date.now(),fetchedFromServer:Iu.conversations[$u]?.fetchedFromServer||!1,isFetching:Iu.conversations[$u]?.isFetching||!1}}}),!1,"setMessages")},addMessage:($u,Ru)=>{Au(Iu=>{const Pu=Iu.conversations[$u],Ou=Pu?.messages||[];return{conversations:{...Iu.conversations,[$u]:{runtimeId:$u,messages:[...Ou,Ru],updatedAt:Date.now(),fetchedFromServer:Pu?.fetchedFromServer||!1,isFetching:Pu?.isFetching||!1}}}},!1,"addMessage")},updateMessage:($u,Ru,Iu)=>{Au(Pu=>{const Ou=Pu.conversations[$u];return Ou?{conversations:{...Pu.conversations,[$u]:{...Ou,messages:Ou.messages.map(Mu=>Mu.id===Ru?{...Mu,...Iu}:Mu),updatedAt:Date.now()}}}:Pu},!1,"updateMessage")},clearMessages:$u=>{Au(Ru=>{const Iu=Ru.conversations[$u];return Iu?{conversations:{...Ru.conversations,[$u]:{...Iu,messages:[],updatedAt:Date.now(),fetchedFromServer:!1}}}:Ru},!1,"clearMessages")},clearAll:()=>{Au({conversations:{}},!1,"clearAll")},markFetched:$u=>{Au(Ru=>{const Iu=Ru.conversations[$u];return{conversations:{...Ru.conversations,[$u]:Iu?{...Iu,fetchedFromServer:!0,isFetching:!1}:{runtimeId:$u,messages:[],updatedAt:Date.now(),fetchedFromServer:!0,isFetching:!1}}}},!1,"markFetched")},setFetching:($u,Ru)=>{Au(Iu=>{const Pu=Iu.conversations[$u];return{conversations:{...Iu.conversations,[$u]:Pu?{...Pu,isFetching:Ru}:{runtimeId:$u,messages:[],updatedAt:Date.now(),fetchedFromServer:!1,isFetching:Ru}}}},!1,"setFetching")},needsFetch:$u=>{const Ru=lo().conversations[$u];return!Ru?.fetchedFromServer&&!Ru?.isFetching},isFetching:$u=>lo().conversations[$u]?.isFetching||!1,deleteConversation:$u=>{Au(Ru=>{const{[$u]:Iu,...Pu}=Ru.conversations;return{conversations:Pu}},!1,"deleteConversation")}})),{name:"ConversationStore"})),AIModels={BEDROCK_US_ANTHROPIC_CLAUDE_SONNET_4_6:"bedrock:us.anthropic.claude-sonnet-4-6"},ALIBABA_QWEN_MAX_0_0_1={id:"alibaba:qwen-max",version:"0.0.1",name:"Alibaba Qwen-Max",description:"Qwen-Max via Alibaba Cloud Model Studio - highest capability Qwen model",provider:"alibaba",providerUrl:"https://www.alibabacloud.com/help/en/model-studio/models",default:!1,available:!0,requiredEnvVars:[],tokensLimit:32768,capabilities:["chat","tools","codemode"]},ALIBABA_QWEN3_32B_0_0_1={id:"alibaba:qwen3-32b",version:"0.0.1",name:"Alibaba Qwen3-32B",description:"Qwen3-32B via Alibaba Cloud Model Studio - open-weight 32B model with tool calling",provider:"alibaba",providerUrl:"https://www.alibabacloud.com/help/en/model-studio/models",default:!1,available:!1,requiredEnvVars:[],tokensLimit:16384,capabilities:["chat","tools","codemode"]},ALIBABA_QWEN3_6_FLASH_0_0_1={id:"alibaba:qwen3.6-flash",version:"0.0.1",name:"Alibaba Qwen3.6-Flash",description:"Qwen3.6-Flash via Alibaba Cloud Model Studio - fast and low cost",provider:"alibaba",providerUrl:"https://www.alibabacloud.com/help/en/model-studio/models",default:!1,available:!1,requiredEnvVars:[],tokensLimit:16384,capabilities:["chat","tools","codemode"]},ALIBABA_QWEN3_6_PLUS_0_0_1={id:"alibaba:qwen3.6-plus",version:"0.0.1",name:"Alibaba Qwen3.6-Plus",description:"Qwen3.6-Plus via Alibaba Cloud Model Studio - balanced performance and cost",provider:"alibaba",providerUrl:"https://www.alibabacloud.com/help/en/model-studio/models",default:!1,available:!1,requiredEnvVars:[],tokensLimit:32768,capabilities:["chat","tools","codemode"]},ALIBABA_QWEN3_7_PLUS_0_0_1={id:"alibaba:qwen3.7-plus",version:"0.0.1",name:"Alibaba Qwen3.7-Plus",description:"Qwen3.7-Plus via Alibaba Cloud Model Studio - balanced flagship Qwen3 model",provider:"alibaba",providerUrl:"https://www.alibabacloud.com/help/en/model-studio/models",default:!1,available:!1,requiredEnvVars:[],tokensLimit:32768,capabilities:["chat","tools","codemode"]},ANTHROPIC_CLAUDE_3_5_HAIKU_20241022_0_0_1={id:"anthropic:claude-3-5-haiku-20241022",version:"0.0.1",name:"Anthropic Claude Haiku 3.5",description:"Claude Haiku 3.5 by Anthropic - fast and efficient",provider:"anthropic",providerUrl:"https://www.anthropic.com/claude/haiku",default:!1,available:!1,requiredEnvVars:["ANTHROPIC_API_KEY"],tokensLimit:8192,pricing:{inputUsdPerMillion:.8,outputUsdPerMillion:4}},ANTHROPIC_CLAUDE_OPUS_4_20250514_0_0_1={id:"anthropic:claude-opus-4-20250514",version:"0.0.1",name:"Anthropic Claude Opus 4",description:"Claude Opus 4 by Anthropic - highest capability model",provider:"anthropic",providerUrl:"https://www.anthropic.com/claude/opus",default:!1,available:!1,requiredEnvVars:["ANTHROPIC_API_KEY"],tokensLimit:32e3,pricing:{inputUsdPerMillion:15,outputUsdPerMillion:75}},ANTHROPIC_CLAUDE_SONNET_4_5_20250514_0_0_1={id:"anthropic:claude-sonnet-4-5-20250514",version:"0.0.1",name:"Anthropic Claude Sonnet 4.5",description:"Claude Sonnet 4.5 by Anthropic - balanced performance and speed",provider:"anthropic",providerUrl:"https://www.anthropic.com/claude/sonnet",default:!1,available:!1,requiredEnvVars:["ANTHROPIC_API_KEY"],tokensLimit:64e3,pricing:{inputUsdPerMillion:3,outputUsdPerMillion:15}},ANTHROPIC_CLAUDE_SONNET_4_20250514_0_0_1={id:"anthropic:claude-sonnet-4-20250514",version:"0.0.1",name:"Anthropic Claude Sonnet 4",description:"Claude Sonnet 4 by Anthropic - strong reasoning and coding",provider:"anthropic",providerUrl:"https://www.anthropic.com/claude/sonnet",default:!1,available:!1,requiredEnvVars:["ANTHROPIC_API_KEY"],tokensLimit:64e3,pricing:{inputUsdPerMillion:3,outputUsdPerMillion:15}},AZURE_OPENAI_GPT_4_1_MINI_0_0_1={id:"azure-openai:gpt-4.1-mini",version:"0.0.1",name:"Azure OpenAI GPT-4.1 Mini",description:"GPT-4.1 Mini via Azure OpenAI - compact version",provider:"azure-openai",providerUrl:"https://learn.microsoft.com/en-us/azure/ai-foundry/foundry-models/concepts/models-sold-directly-by-azure",default:!1,available:!1,requiredEnvVars:["AZURE_OPENAI_API_KEY","AZURE_OPENAI_ENDPOINT"],tokensLimit:32768,pricing:{inputUsdPerMillion:.4,outputUsdPerMillion:1.6}},AZURE_OPENAI_GPT_4_1_NANO_0_0_1={id:"azure-openai:gpt-4.1-nano",version:"0.0.1",name:"Azure OpenAI GPT-4.1 Nano",description:"GPT-4.1 Nano via Azure OpenAI - smallest and fastest",provider:"azure-openai",providerUrl:"https://learn.microsoft.com/en-us/azure/ai-foundry/foundry-models/concepts/models-sold-directly-by-azure",default:!1,available:!1,requiredEnvVars:["AZURE_OPENAI_API_KEY","AZURE_OPENAI_ENDPOINT"],tokensLimit:32768,pricing:{inputUsdPerMillion:.1,outputUsdPerMillion:.4}},AZURE_OPENAI_GPT_4_1_0_0_1={id:"azure-openai:gpt-4.1",version:"0.0.1",name:"Azure OpenAI GPT-4.1",description:"GPT-4.1 via Azure OpenAI - strong general purpose",provider:"azure-openai",providerUrl:"https://learn.microsoft.com/en-us/azure/ai-foundry/foundry-models/concepts/models-sold-directly-by-azure",default:!1,available:!1,requiredEnvVars:["AZURE_OPENAI_API_KEY","AZURE_OPENAI_ENDPOINT"],tokensLimit:32768,pricing:{inputUsdPerMillion:2,outputUsdPerMillion:8}},AZURE_OPENAI_GPT_4O_MINI_0_0_1={id:"azure-openai:gpt-4o-mini",version:"0.0.1",name:"Azure OpenAI GPT-4o Mini",description:"GPT-4o Mini via Azure OpenAI - compact enterprise deployment",provider:"azure-openai",providerUrl:"https://learn.microsoft.com/en-us/azure/ai-foundry/foundry-models/concepts/models-sold-directly-by-azure",default:!1,available:!1,requiredEnvVars:["AZURE_OPENAI_API_KEY","AZURE_OPENAI_ENDPOINT"],tokensLimit:16384,pricing:{inputUsdPerMillion:.15,outputUsdPerMillion:.6}},AZURE_OPENAI_GPT_4O_0_0_1={id:"azure-openai:gpt-4o",version:"0.0.1",name:"Azure OpenAI GPT-4o",description:"GPT-4o via Azure OpenAI - enterprise deployment",provider:"azure-openai",providerUrl:"https://learn.microsoft.com/en-us/azure/ai-foundry/foundry-models/concepts/models-sold-directly-by-azure",default:!1,available:!1,requiredEnvVars:["AZURE_OPENAI_API_KEY","AZURE_OPENAI_ENDPOINT"],tokensLimit:16384,pricing:{inputUsdPerMillion:2.5,outputUsdPerMillion:10}},BEDROCK_US_ANTHROPIC_CLAUDE_FABLE_5_0_0_1={id:"bedrock:us.anthropic.claude-fable-5",version:"0.0.1",name:"Bedrock Claude Fable 5",description:"Claude Fable 5 via AWS Bedrock",provider:"bedrock",providerUrl:"https://aws.amazon.com/bedrock/anthropic/",default:!1,available:!1,requiredEnvVars:["AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_DEFAULT_REGION"],tokensLimit:64e3,pricing:{inputUsdPerMillion:11,outputUsdPerMillion:55}},BEDROCK_US_ANTHROPIC_CLAUDE_OPUS_4_6_V1_0_0_1={id:"bedrock:us.anthropic.claude-opus-4-6-v1",version:"0.0.1",name:"Bedrock Claude Opus 4.6",description:"Claude Opus 4.6 via AWS Bedrock",provider:"bedrock",providerUrl:"https://aws.amazon.com/bedrock/anthropic/",default:!1,available:!1,requiredEnvVars:["AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_DEFAULT_REGION"],tokensLimit:32e3,pricing:{inputUsdPerMillion:5.5,outputUsdPerMillion:27.5}},BEDROCK_US_ANTHROPIC_CLAUDE_OPUS_4_8_0_0_1={id:"bedrock:us.anthropic.claude-opus-4-8",version:"0.0.1",name:"Bedrock Claude Opus 4.8",description:"Claude Opus 4.8 via AWS Bedrock",provider:"bedrock",providerUrl:"https://aws.amazon.com/bedrock/anthropic/",default:!1,available:!1,requiredEnvVars:["AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_DEFAULT_REGION"],tokensLimit:32e3,pricing:{inputUsdPerMillion:5.5,outputUsdPerMillion:27.5}},BEDROCK_US_ANTHROPIC_CLAUDE_OPUS_4_20250514_V1_0_0_0_1={id:"bedrock:us.anthropic.claude-opus-4-20250514-v1:0",version:"0.0.1",name:"Bedrock Claude Opus 4",description:"Claude Opus 4 via AWS Bedrock - highest capability",provider:"bedrock",providerUrl:"https://aws.amazon.com/bedrock/anthropic/",default:!1,available:!1,requiredEnvVars:["AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_DEFAULT_REGION"],tokensLimit:32e3,pricing:{inputUsdPerMillion:15,outputUsdPerMillion:75}},BEDROCK_US_ANTHROPIC_CLAUDE_OPUS_5_0_0_1={id:"bedrock:us.anthropic.claude-opus-5",version:"0.0.1",name:"Bedrock Claude Opus 5",description:"Claude Opus 5 via AWS Bedrock - the current frontier model",provider:"bedrock",providerUrl:"https://aws.amazon.com/bedrock/anthropic/",default:!1,available:!1,requiredEnvVars:["AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_DEFAULT_REGION"],tokensLimit:32e3,pricing:{inputUsdPerMillion:5.5,outputUsdPerMillion:27.5}},BEDROCK_US_ANTHROPIC_CLAUDE_SONNET_4_5_20250929_V1_0_0_0_1={id:"bedrock:us.anthropic.claude-sonnet-4-5-20250929-v1:0",version:"0.0.1",name:"Bedrock Claude Sonnet 4.5",description:"Claude Sonnet 4.5 via AWS Bedrock - balanced performance",provider:"bedrock",providerUrl:"https://aws.amazon.com/bedrock/anthropic/",default:!1,available:!1,requiredEnvVars:["AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_DEFAULT_REGION"],tokensLimit:64e3,pricing:{inputUsdPerMillion:3.3,outputUsdPerMillion:16.5}},BEDROCK_US_ANTHROPIC_CLAUDE_SONNET_4_6_0_0_1={id:"bedrock:us.anthropic.claude-sonnet-4-6",version:"0.0.1",name:"Bedrock Claude Sonnet 4.6",description:"Claude Sonnet 4.6 via AWS Bedrock - balanced performance",provider:"bedrock",providerUrl:"https://aws.amazon.com/bedrock/anthropic/",default:!0,available:!0,requiredEnvVars:["AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_DEFAULT_REGION"],tokensLimit:64e3,capabilities:["chat","tools","decider"],contextWindow:2e5,pricing:{inputUsdPerMillion:3.3,outputUsdPerMillion:16.5}},BEDROCK_US_ANTHROPIC_CLAUDE_SONNET_4_20250514_V1_0_0_0_1={id:"bedrock:us.anthropic.claude-sonnet-4-20250514-v1:0",version:"0.0.1",name:"Bedrock Claude Sonnet 4",description:"Claude Sonnet 4 via AWS Bedrock - strong reasoning",provider:"bedrock",providerUrl:"https://aws.amazon.com/bedrock/anthropic/",default:!1,available:!1,requiredEnvVars:["AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_DEFAULT_REGION"],tokensLimit:64e3,pricing:{inputUsdPerMillion:3,outputUsdPerMillion:15}},CLOUDFLARE_GTW_TYPESAFE_JEV_0_0_1={id:"cloudflare:gtw/typesafe/jev",version:"0.0.1",name:"Jev (Cloudflare AI Gateway)",description:"Typesafe's typed-decision model through the account's AI Gateway - noul, choice and score questions answered as calibrated probabilities; 32k context; zero data retention; the gateway keeps the logs and bills from its credits",provider:"cloudflare",providerUrl:"https://docs.typesafe.ai/models",default:!1,available:!0,requiredEnvVars:[],capabilities:["decisions"],billing:"credits",route:"ai-gateway",contextWindow:32e3,zeroDataRetention:!0,requestLogging:"gateway",pricing:{inputUsdPerMillion:.042,outputUsdPerMillion:0}},CLOUDFLARE_WRK_GOOGLE_GEMMA_4_26B_A4B_IT_0_0_1={id:"cloudflare:wrk/google/gemma-4-26b-a4b-it",version:"0.0.1",name:"Cloudflare Gemma 4 26B",description:"Google Gemma 4 26B (a4b, instruction-tuned) on Cloudflare Workers AI - 256k context, tool calling, standard billing",provider:"cloudflare",providerUrl:"https://developers.cloudflare.com/workers-ai/models/gemma-4-26b-a4b-it/",default:!1,available:!1,requiredEnvVars:[],tokensLimit:16384,capabilities:["chat","tools","codemode"],billing:"standard",route:"workers-ai",contextWindow:256e3,aliases:["cloudflare:google/gemma-4-26b-a4b-it"],pricing:{inputUsdPerMillion:.1,outputUsdPerMillion:.3}},CLOUDFLARE_WRK_ZAI_ORG_GLM_5_2_0_0_1={id:"cloudflare:wrk/zai-org/glm-5.2",version:"0.0.1",name:"Cloudflare GLM-5.2",description:"Z.ai GLM-5.2 on Cloudflare Workers AI - 262k context, tool calling; a frontier model billed from AI Gateway credits",provider:"cloudflare",providerUrl:"https://developers.cloudflare.com/workers-ai/models/glm-5.2/",default:!1,available:!1,requiredEnvVars:[],tokensLimit:32768,capabilities:["chat","tools","codemode"],billing:"credits",route:"workers-ai",contextWindow:262144,aliases:["cloudflare:zai-org/glm-5.2"],pricing:{inputUsdPerMillion:1.4,outputUsdPerMillion:4.4}},CLOUDFLARE_WRK_OPENAI_GPT_OSS_120B_0_0_1={id:"cloudflare:wrk/openai/gpt-oss-120b",version:"0.0.1",name:"Cloudflare gpt-oss-120b",description:"OpenAI gpt-oss-120b on Cloudflare Workers AI - 128k context, tool calling, standard billing",provider:"cloudflare",providerUrl:"https://developers.cloudflare.com/workers-ai/models/gpt-oss-120b/",default:!1,available:!1,requiredEnvVars:[],tokensLimit:32768,capabilities:["chat","tools","codemode","decider"],billing:"standard",route:"workers-ai",contextWindow:128e3,aliases:["cloudflare:openai/gpt-oss-120b"],pricing:{inputUsdPerMillion:.35,outputUsdPerMillion:.75}},CLOUDFLARE_WRK_MOONSHOTAI_KIMI_K2_6_0_0_1={id:"cloudflare:wrk/moonshotai/kimi-k2.6",version:"0.0.1",name:"Cloudflare Kimi K2.6",description:"Moonshot Kimi K2.6 on Cloudflare Workers AI - 262k context, tool calling; a frontier model billed from AI Gateway credits",provider:"cloudflare",providerUrl:"https://developers.cloudflare.com/workers-ai/models/kimi-k2.6/",default:!1,available:!1,requiredEnvVars:[],tokensLimit:32768,capabilities:["chat","tools","codemode"],billing:"credits",route:"workers-ai",contextWindow:262144,aliases:["cloudflare:moonshotai/kimi-k2.6"],pricing:{inputUsdPerMillion:.95,outputUsdPerMillion:4}},CLOUDFLARE_WRK_META_LLAMA_3_3_70B_INSTRUCT_FP8_FAST_0_0_1={id:"cloudflare:wrk/meta/llama-3.3-70b-instruct-fp8-fast",version:"0.0.1",name:"Cloudflare Llama 3.3 70B",description:"Meta Llama 3.3 70B Instruct (fp8, fast) on Cloudflare Workers AI - 24k context, tool calling, standard billing",provider:"cloudflare",providerUrl:"https://developers.cloudflare.com/workers-ai/models/llama-3.3-70b-instruct-fp8-fast/",default:!1,available:!1,requiredEnvVars:[],tokensLimit:8192,capabilities:["chat","tools","codemode"],billing:"standard",route:"workers-ai",contextWindow:24e3,aliases:["cloudflare:meta/llama-3.3-70b-instruct-fp8-fast"],pricing:{inputUsdPerMillion:.293,outputUsdPerMillion:2.253}},CLOUDFLARE_WRK_QWEN_QWEN3_8_27B_0_0_1={id:"cloudflare:wrk/qwen/qwen3.8-27b",version:"0.0.1",name:"Cloudflare Qwen3.8 27B",description:"Qwen3.8 27B on Cloudflare Workers AI - 262k context, tool calling, standard billing",provider:"cloudflare",providerUrl:"https://developers.cloudflare.com/workers-ai/models/qwen3.8-27b/",default:!1,available:!1,requiredEnvVars:[],tokensLimit:16384,capabilities:["chat","tools","codemode"],billing:"standard",route:"workers-ai",contextWindow:262144,aliases:["cloudflare:qwen/qwen3.8-27b"],pricing:{inputUsdPerMillion:.45,outputUsdPerMillion:3.2}},CLOUDFLARE_WRK_TYPESAFE_JEV_0_0_1={id:"cloudflare:wrk/typesafe/jev",version:"0.0.1",name:"Jev (Cloudflare Workers AI)",description:"Typesafe's typed-decision model at Workers AI's own endpoint - noul, choice and score questions answered as calibrated probabilities; 32k context; zero data retention; billed from the account's credits, no gateway in the way",provider:"cloudflare",providerUrl:"https://docs.typesafe.ai/models",default:!1,available:!0,requiredEnvVars:[],capabilities:["decisions"],billing:"credits",route:"workers-ai",contextWindow:32e3,zeroDataRetention:!0,requestLogging:"none",pricing:{inputUsdPerMillion:.042,outputUsdPerMillion:0}},OLLAMA_GEMMA3_4B_0_0_1={id:"ollama:gemma3:4b",version:"0.0.1",name:"Gemma 3 4B (Ollama)",description:"Gemma 3 4B running locally through Ollama - small and fast, no tool calling",provider:"ollama",providerUrl:"https://ollama.com/library/gemma3:4b",default:!1,available:!1,requiredEnvVars:[],tokensLimit:4096,local:!0,capabilities:["chat"]},OLLAMA_LLAMA3_1_8B_0_0_1={id:"ollama:llama3.1:8b",version:"0.0.1",name:"Llama 3.1 8B (Ollama)",description:"Meta Llama 3.1 8B running locally through Ollama - tool calling, no data leaves the machine",provider:"ollama",providerUrl:"https://ollama.com/library/llama3.1:8b",default:!1,available:!1,requiredEnvVars:[],tokensLimit:4096,local:!0,capabilities:["chat","tools","codemode"]},OLLAMA_QWEN2_5_CODER_7B_0_0_1={id:"ollama:qwen2.5-coder:7b",version:"0.0.1",name:"Qwen2.5 Coder 7B (Ollama)",description:"Qwen2.5 Coder 7B running locally through Ollama - code-focused with tool calling",provider:"ollama",providerUrl:"https://ollama.com/library/qwen2.5-coder:7b",default:!1,available:!1,requiredEnvVars:[],tokensLimit:4096,local:!0,capabilities:["chat","tools","codemode"]},OPENAI_GPT_4_1_MINI_0_0_1={id:"openai:gpt-4.1-mini",version:"0.0.1",name:"OpenAI GPT-4.1 Mini",description:"GPT-4.1 Mini by OpenAI - compact version of GPT-4.1",provider:"openai",providerUrl:"https://platform.openai.com/docs/models/gpt-4.1-mini",default:!1,available:!1,requiredEnvVars:["OPENAI_API_KEY"],tokensLimit:32768,pricing:{inputUsdPerMillion:.4,outputUsdPerMillion:1.6}},OPENAI_GPT_4_1_NANO_0_0_1={id:"openai:gpt-4.1-nano",version:"0.0.1",name:"OpenAI GPT-4.1 Nano",description:"GPT-4.1 Nano by OpenAI - smallest and fastest",provider:"openai",providerUrl:"https://platform.openai.com/docs/models/gpt-4.1-nano",default:!1,available:!1,requiredEnvVars:["OPENAI_API_KEY"],tokensLimit:32768,pricing:{inputUsdPerMillion:.1,outputUsdPerMillion:.4}},OPENAI_GPT_4_1_0_0_1={id:"openai:gpt-4.1",version:"0.0.1",name:"OpenAI GPT-4.1",description:"GPT-4.1 by OpenAI - strong general purpose model",provider:"openai",providerUrl:"https://platform.openai.com/docs/models/gpt-4.1",default:!1,available:!1,requiredEnvVars:["OPENAI_API_KEY"],tokensLimit:32768,pricing:{inputUsdPerMillion:2,outputUsdPerMillion:8}},OPENAI_GPT_4O_MINI_0_0_1={id:"openai:gpt-4o-mini",version:"0.0.1",name:"OpenAI GPT-4o Mini",description:"GPT-4o Mini by OpenAI - compact and cost-effective",provider:"openai",providerUrl:"https://platform.openai.com/docs/models/gpt-4o-mini",default:!1,available:!1,requiredEnvVars:["OPENAI_API_KEY"],tokensLimit:16384,pricing:{inputUsdPerMillion:.15,outputUsdPerMillion:.6}},OPENAI_GPT_4O_0_0_1={id:"openai:gpt-4o",version:"0.0.1",name:"OpenAI GPT-4o",description:"GPT-4o by OpenAI - fast multimodal model",provider:"openai",providerUrl:"https://platform.openai.com/docs/models/gpt-4o",default:!1,available:!1,requiredEnvVars:["OPENAI_API_KEY"],tokensLimit:16384,pricing:{inputUsdPerMillion:2.5,outputUsdPerMillion:10}},OPENAI_O3_MINI_0_0_1={id:"openai:o3-mini",version:"0.0.1",name:"OpenAI o3 Mini",description:"o3 Mini by OpenAI - reasoning-focused compact model",provider:"openai",providerUrl:"https://platform.openai.com/docs/models/o3-mini",default:!1,available:!1,requiredEnvVars:["OPENAI_API_KEY"],tokensLimit:1e5,pricing:{inputUsdPerMillion:1.1,outputUsdPerMillion:4.4}},AI_MODEL_CATALOGUE={"alibaba:qwen-max":ALIBABA_QWEN_MAX_0_0_1,"alibaba:qwen3-32b":ALIBABA_QWEN3_32B_0_0_1,"alibaba:qwen3.6-flash":ALIBABA_QWEN3_6_FLASH_0_0_1,"alibaba:qwen3.6-plus":ALIBABA_QWEN3_6_PLUS_0_0_1,"alibaba:qwen3.7-plus":ALIBABA_QWEN3_7_PLUS_0_0_1,"anthropic:claude-3-5-haiku-20241022":ANTHROPIC_CLAUDE_3_5_HAIKU_20241022_0_0_1,"anthropic:claude-opus-4-20250514":ANTHROPIC_CLAUDE_OPUS_4_20250514_0_0_1,"anthropic:claude-sonnet-4-5-20250514":ANTHROPIC_CLAUDE_SONNET_4_5_20250514_0_0_1,"anthropic:claude-sonnet-4-20250514":ANTHROPIC_CLAUDE_SONNET_4_20250514_0_0_1,"azure-openai:gpt-4.1-mini":AZURE_OPENAI_GPT_4_1_MINI_0_0_1,"azure-openai:gpt-4.1-nano":AZURE_OPENAI_GPT_4_1_NANO_0_0_1,"azure-openai:gpt-4.1":AZURE_OPENAI_GPT_4_1_0_0_1,"azure-openai:gpt-4o-mini":AZURE_OPENAI_GPT_4O_MINI_0_0_1,"azure-openai:gpt-4o":AZURE_OPENAI_GPT_4O_0_0_1,"bedrock:us.anthropic.claude-fable-5":BEDROCK_US_ANTHROPIC_CLAUDE_FABLE_5_0_0_1,"bedrock:us.anthropic.claude-opus-4-6-v1":BEDROCK_US_ANTHROPIC_CLAUDE_OPUS_4_6_V1_0_0_1,"bedrock:us.anthropic.claude-opus-4-8":BEDROCK_US_ANTHROPIC_CLAUDE_OPUS_4_8_0_0_1,"bedrock:us.anthropic.claude-opus-4-20250514-v1:0":BEDROCK_US_ANTHROPIC_CLAUDE_OPUS_4_20250514_V1_0_0_0_1,"bedrock:us.anthropic.claude-opus-5":BEDROCK_US_ANTHROPIC_CLAUDE_OPUS_5_0_0_1,"bedrock:us.anthropic.claude-sonnet-4-5-20250929-v1:0":BEDROCK_US_ANTHROPIC_CLAUDE_SONNET_4_5_20250929_V1_0_0_0_1,"bedrock:us.anthropic.claude-sonnet-4-6":BEDROCK_US_ANTHROPIC_CLAUDE_SONNET_4_6_0_0_1,"bedrock:us.anthropic.claude-sonnet-4-20250514-v1:0":BEDROCK_US_ANTHROPIC_CLAUDE_SONNET_4_20250514_V1_0_0_0_1,"cloudflare:gtw/typesafe/jev":CLOUDFLARE_GTW_TYPESAFE_JEV_0_0_1,"cloudflare:wrk/google/gemma-4-26b-a4b-it":CLOUDFLARE_WRK_GOOGLE_GEMMA_4_26B_A4B_IT_0_0_1,"cloudflare:wrk/zai-org/glm-5.2":CLOUDFLARE_WRK_ZAI_ORG_GLM_5_2_0_0_1,"cloudflare:wrk/openai/gpt-oss-120b":CLOUDFLARE_WRK_OPENAI_GPT_OSS_120B_0_0_1,"cloudflare:wrk/moonshotai/kimi-k2.6":CLOUDFLARE_WRK_MOONSHOTAI_KIMI_K2_6_0_0_1,"cloudflare:wrk/meta/llama-3.3-70b-instruct-fp8-fast":CLOUDFLARE_WRK_META_LLAMA_3_3_70B_INSTRUCT_FP8_FAST_0_0_1,"cloudflare:wrk/qwen/qwen3.8-27b":CLOUDFLARE_WRK_QWEN_QWEN3_8_27B_0_0_1,"cloudflare:wrk/typesafe/jev":CLOUDFLARE_WRK_TYPESAFE_JEV_0_0_1,"ollama:gemma3:4b":OLLAMA_GEMMA3_4B_0_0_1,"ollama:llama3.1:8b":OLLAMA_LLAMA3_1_8B_0_0_1,"ollama:qwen2.5-coder:7b":OLLAMA_QWEN2_5_CODER_7B_0_0_1,"openai:gpt-4.1-mini":OPENAI_GPT_4_1_MINI_0_0_1,"openai:gpt-4.1-nano":OPENAI_GPT_4_1_NANO_0_0_1,"openai:gpt-4.1":OPENAI_GPT_4_1_0_0_1,"openai:gpt-4o-mini":OPENAI_GPT_4O_MINI_0_0_1,"openai:gpt-4o":OPENAI_GPT_4O_0_0_1,"openai:o3-mini":OPENAI_O3_MINI_0_0_1};function isChatModel(Au){return!(Au.capabilities??[]).includes("decisions")}const DEFAULT_MODEL=AIModels.BEDROCK_US_ANTHROPIC_CLAUDE_SONNET_4_6;class BaseProtocolAdapter{config;_connectionState="disconnected";eventHandlers=new Set;reconnectAttempts=0;constructor(lo){this.config={autoReconnect:!0,reconnectDelay:1e3,maxReconnectAttempts:5,timeout:3e4,...lo}}get connectionState(){return this._connectionState}subscribe(lo){return this.eventHandlers.add(lo),()=>{this.eventHandlers.delete(lo)}}async getAgentCard(){return null}supportsFeature(lo){return!1}emit(lo){for(const $u of this.eventHandlers)try{$u(lo)}catch(Ru){console.error(`[${this.protocol}] Error in event handler:`,Ru)}}setConnectionState(lo){const $u=this._connectionState;this._connectionState=lo,$u!==lo&&this.emit({type:lo==="connected"?"connected":"disconnected",timestamp:new Date})}async handleReconnect(){if(!this.config.autoReconnect)return;if(this.reconnectAttempts>=(this.config.maxReconnectAttempts||5)){this.setConnectionState("error"),this.emit({type:"error",error:new Error("Max reconnection attempts reached"),timestamp:new Date});return}this.setConnectionState("reconnecting"),this.reconnectAttempts++;const lo=this.config.reconnectDelay*Math.pow(2,this.reconnectAttempts-1);await new Promise($u=>setTimeout($u,lo));try{await this.connect(),this.reconnectAttempts=0}catch{await this.handleReconnect()}}buildHeaders(lo){const $u={"Content-Type":"application/json"};return this.config.authToken&&($u.Authorization=`Bearer ${this.config.authToken}`),{...$u,...lo}}fetchOf(){return this.config.fetch??((lo,$u)=>fetch(lo,$u))}createTimeoutSignal(){return AbortSignal.timeout(this.config.timeout||3e4)}}const AG_UI_NOT_ON_RUNTIME="This agent is not on the runtime the page is addressing: its AG-UI address answered nothing. An agent that runs its code in the browser is never started on a runtime — run it in the page, or give it a sandbox a runtime has (eval, jupyter-server).",AG_UI_NOT_ALLOWED="This agent did not answer the page: the run was refused. Sign in again, or open the application from its own address.";function refusalDetail(Au){if(!Au)return"";let lo;try{lo=JSON.parse(Au)}catch{return""}if(!lo||typeof lo!="object")return"";const $u=lo.detail;return typeof $u=="string"?$u.trim():""}function agUiRefusal(Au,lo,$u){const Ru=refusalDetail($u);return Ru||(Au===404?AG_UI_NOT_ON_RUNTIME:Au===401||Au===403?AG_UI_NOT_ALLOWED:`AG-UI request failed: ${Au} ${lo}`.trim())}async function refusalBody(Au){try{return await Au.text()}catch{return}}const RUN_CUT_SHORT="The run stopped before it finished, without an answer or an error: send it again.";class AGUIAdapter extends BaseProtocolAdapter{protocol="ag-ui";protocolTransport="sse";aguiConfig;abortController=null;inFlight=new Set;currentThreadId=null;pendingToolCalls=new Map;collectedToolResults=new Map;messageHistory=[];lastAssistantContent="";lastTurnContent="";lastTools=[];isContinuation=!1;_streamParsingDepth=0;_streamDonePromise=null;_streamDoneResolve=null;constructor(lo){super(lo),this.aguiConfig={...lo,baseUrl:lo.baseUrl.endsWith("/")?lo.baseUrl:`${lo.baseUrl}/`}}async connect(){this.setConnectionState("connecting"),this.setConnectionState("connected")}disconnect(){this.stopGeneration(),this.currentThreadId&&this.terminateAgent(this.currentThreadId).catch(lo=>{console.warn("[AGUIAdapter] Failed to terminate agent:",lo)}),this.setConnectionState("disconnected")}async terminateAgent(lo){try{const Ru=`${new URL(this.aguiConfig.baseUrl).origin}/api/v1/ag-ui/terminate`,Iu=await this.fetchOf()(Ru,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({thread_id:lo||this.currentThreadId})});Iu.ok||console.warn(`[AGUIAdapter] Terminate request failed: ${Iu.status}`)}catch{}}async sendMessage(lo,$u){const Ru=new AbortController;this.abortController=Ru,this.inFlight.add(Ru);const Iu=$u?.threadId||this.currentThreadId||generateMessageId();this.currentThreadId=Iu;const Pu=$u?.messages||[lo];this.messageHistory=[...Pu],this.lastTools=$u?.tools||[],this.isContinuation||(this.lastAssistantContent="",this.lastTurnContent="");const Ou=Pu.map(Du=>{const Lu={id:Du.id,role:Du.role,content:Du.content};return Du.role==="tool"&&Du.metadata?.toolCallId&&(Lu.tool_call_id=Du.metadata.toolCallId),Du.role==="assistant"&&Du.toolCalls&&Du.toolCalls.length>0&&(Lu.content=typeof Du.content=="string"&&Du.content.trim()?Du.content:null,Lu.tool_calls=Du.toolCalls.map(Bu=>({id:Bu.toolCallId,type:"function",function:{name:Bu.toolName,arguments:JSON.stringify(Bu.args||{})}}))),Lu}),Mu={threadId:Iu,runId:generateMessageId(),messages:Ou,state:null,tools:$u?.tools||[],...$u?.builtinTools!==void 0&&{builtinTools:$u.builtinTools},...$u?.skills!==void 0&&{skills:$u.skills},context:[],forwardedProps:$u?.forwardedProps??null,...$u?.model&&{model:$u.model},...$u?.identities&&$u.identities.length>0&&{identities:$u.identities}};$u?.model&&console.log("[AGUIAdapter] Sending with model:",$u.model),$u?.identities&&$u.identities.length>0&&console.log("[AGUIAdapter] Sending with identities:",$u.identities.map(Du=>Du.provider));try{const Du=await this.fetchOf()(this.aguiConfig.baseUrl,{method:"POST",headers:this.buildHeaders({Accept:"text/event-stream"}),body:JSON.stringify(Mu),signal:Ru.signal});if(!Du.ok)throw new Error(agUiRefusal(Du.status,Du.statusText,await refusalBody(Du)));await this.parseSSEStream(Du)}catch(Du){if(Du.name==="AbortError")return;throw this.emit({type:"error",error:Du instanceof Error?Du:new Error(String(Du)),timestamp:new Date}),Du}finally{this.inFlight.delete(Ru),this.abortController===Ru&&(this.abortController=null)}}async sendToolResult(lo,$u){this.emit({type:"tool-result",toolResult:$u,timestamp:new Date});const Ru=this.pendingToolCalls.get(lo);Ru||console.warn("[AGUIAdapter] No pending tool call found for ID:",lo);const Iu=Ru?.toolName||"unknown";let Pu={};if(Ru?.argsJson)try{Pu=JSON.parse(Ru.argsJson)}catch(Fu){console.warn("[AGUIAdapter] Failed to parse tool args:",Fu)}this.collectedToolResults.set(lo,{toolCallId:lo,toolName:Iu,parsedArgs:Pu,result:$u});let Ou=Array.from(this.pendingToolCalls.keys()).every(Fu=>this.collectedToolResults.has(Fu));if(!Ou||this._streamParsingDepth>0&&this._streamDonePromise&&(await this._streamDonePromise,Ou=Array.from(this.pendingToolCalls.keys()).every(Fu=>this.collectedToolResults.has(Fu)),!Ou))return;const Mu=Array.from(this.collectedToolResults.values()).map(Fu=>({type:"tool-call",toolCallId:Fu.toolCallId,toolName:Fu.toolName,args:Fu.parsedArgs,status:"completed"})),Du={id:generateMessageId(),role:"assistant",content:this.lastTurnContent||this.lastAssistantContent||"",createdAt:new Date,toolCalls:Mu},Lu=Array.from(this.collectedToolResults.values()).map(Fu=>({id:generateMessageId(),role:"tool",content:typeof Fu.result.result=="string"?Fu.result.result:JSON.stringify(Fu.result.result),createdAt:new Date,metadata:{toolCallId:Fu.toolCallId,toolName:Fu.toolName,isError:!Fu.result.success}})),Bu=[...this.messageHistory,Du,...Lu];this.pendingToolCalls.clear(),this.collectedToolResults.clear(),this.messageHistory=Bu,console.log("[AGUIAdapter] === CONTINUATION MESSAGES ==="),Bu.forEach((Fu,zu)=>{const Uu=Fu.toolCalls?` [${Fu.toolCalls.length} tool_calls: ${Fu.toolCalls.map(Gu=>Gu.toolName).join(", ")}]`:"",Hu=Fu.metadata?.toolCallId?` [tool_call_id=${Fu.metadata.toolCallId}]`:"",Vu=typeof Fu.content=="string"?Fu.content.slice(0,80):"";console.log(`[AGUIAdapter] [${zu}] role=${Fu.role}${Uu}${Hu} content="${Vu}"`)}),console.log("[AGUIAdapter] === END CONTINUATION MESSAGES ==="),this.isContinuation=!0;const ju=Lu[Lu.length-1];await this.sendMessage(ju,{messages:Bu,tools:this.lastTools,threadId:this.currentThreadId||void 0})}stopGeneration(){for(const lo of this.inFlight)lo.abort();this.inFlight.clear(),this.abortController=null}supportsFeature(lo){return["streaming","tools","frontend-tools","backend-tools","activity-messages"].includes(lo)}async parseSSEStream(lo){const $u=lo.body?.getReader();if(!$u)throw new Error("Response body is not readable");const Ru=new TextDecoder;let Iu="",Pu=null,Ou="",Mu="";this.isContinuation=!1,this._streamParsingDepth===0&&(this._streamDonePromise=new Promise(Lu=>{this._streamDoneResolve=Lu})),this._streamParsingDepth++;let Du=!1;try{for(;;){const{done:Lu,value:Bu}=await $u.read();if(Lu){if(!Du)throw new Error(RUN_CUT_SHORT);break}Iu+=Ru.decode(Bu,{stream:!0});const ju=Iu.split(`
|
|
2099
|
+
`);const Wu=Gu.state[Mu];if(Wu==null)return;JSON.stringify(Iu.getState())!==JSON.stringify(Wu)&&zu(Wu);return}Iu.dispatchFromDevtools&&typeof Iu.dispatch=="function"&&Iu.dispatch(Gu)});case"DISPATCH":switch(Hu.payload.type){case"RESET":return zu(Uu),Mu===void 0?Bu?.init(Iu.getState()):Bu?.init(getTrackedConnectionState(Du.name));case"COMMIT":if(Mu===void 0){Bu?.init(Iu.getState());return}return Bu?.init(getTrackedConnectionState(Du.name));case"ROLLBACK":return parseJsonThen(Hu.state,Gu=>{if(Mu===void 0){zu(Gu),Bu?.init(Iu.getState());return}zu(Gu[Mu]),Bu?.init(getTrackedConnectionState(Du.name))});case"JUMP_TO_STATE":case"JUMP_TO_ACTION":return parseJsonThen(Hu.state,Gu=>{if(Mu===void 0){zu(Gu);return}JSON.stringify(Iu.getState())!==JSON.stringify(Gu[Mu])&&zu(Gu[Mu])});case"IMPORT_STATE":{const{nextLiftedState:Gu}=Hu.payload,Wu=(Vu=Gu.computedStates.slice(-1)[0])==null?void 0:Vu.state;if(!Wu)return;zu(Mu===void 0?Wu:Wu[Mu]),Bu?.send(null,Gu);return}case"PAUSE_RECORDING":return Fu=!Fu}return}}),Uu},devtools=devtoolsImpl,parseJsonThen=(Au,lo)=>{let $u;try{$u=JSON.parse(Au)}catch(Ru){console.error("[zustand devtools middleware] Could not parse the received json",Ru)}$u!==void 0&&lo($u)},subscribeWithSelectorImpl=Au=>(lo,$u,Ru)=>{const Iu=Ru.subscribe;return Ru.subscribe=(Ou,Mu,Du)=>{let Lu=Ou;if(Mu){const Bu=Du?.equalityFn||Object.is;let ju=Ou(Ru.getState());Lu=Fu=>{const zu=Ou(Fu);if(!Bu(ju,zu)){const Uu=ju;Mu(ju=zu,Uu)}},Du?.fireImmediately&&Mu(ju,ju)}return Iu(Lu)},Au(lo,$u,Ru)},subscribeWithSelector=subscribeWithSelectorImpl;function createJSONStorage(Au,lo){let $u;try{$u=Au()}catch{return}return{getItem:Iu=>{var Pu;const Ou=Du=>Du===null?null:JSON.parse(Du,void 0),Mu=(Pu=$u.getItem(Iu))!=null?Pu:null;return Mu instanceof Promise?Mu.then(Ou):Ou(Mu)},setItem:(Iu,Pu)=>$u.setItem(Iu,JSON.stringify(Pu,void 0)),removeItem:Iu=>$u.removeItem(Iu)}}const toThenable=Au=>lo=>{try{const $u=Au(lo);return $u instanceof Promise?$u:{then(Ru){return toThenable(Ru)($u)},catch(Ru){return this}}}catch($u){return{then(Ru){return this},catch(Ru){return toThenable(Ru)($u)}}}},oldImpl=(Au,lo)=>($u,Ru,Iu)=>{let Pu={getStorage:()=>localStorage,serialize:JSON.stringify,deserialize:JSON.parse,partialize:Vu=>Vu,version:0,merge:(Vu,Gu)=>({...Gu,...Vu}),...lo},Ou=!1;const Mu=new Set,Du=new Set;let Lu;try{Lu=Pu.getStorage()}catch{}if(!Lu)return Au((...Vu)=>{console.warn(`[zustand persist middleware] Unable to update item '${Pu.name}', the given storage is currently unavailable.`),$u(...Vu)},Ru,Iu);const Bu=toThenable(Pu.serialize),ju=()=>{const Vu=Pu.partialize({...Ru()});let Gu;const Wu=Bu({state:Vu,version:Pu.version}).then(Ku=>Lu.setItem(Pu.name,Ku)).catch(Ku=>{Gu=Ku});if(Gu)throw Gu;return Wu},Fu=Iu.setState;Iu.setState=(Vu,Gu)=>{Fu(Vu,Gu),ju()};const zu=Au((...Vu)=>{$u(...Vu),ju()},Ru,Iu);let Uu;const Hu=()=>{var Vu;if(!Lu)return;Ou=!1,Mu.forEach(Wu=>Wu(Ru()));const Gu=((Vu=Pu.onRehydrateStorage)==null?void 0:Vu.call(Pu,Ru()))||void 0;return toThenable(Lu.getItem.bind(Lu))(Pu.name).then(Wu=>{if(Wu)return Pu.deserialize(Wu)}).then(Wu=>{if(Wu)if(typeof Wu.version=="number"&&Wu.version!==Pu.version){if(Pu.migrate)return Pu.migrate(Wu.state,Wu.version);console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return Wu.state}).then(Wu=>{var Ku;return Uu=Pu.merge(Wu,(Ku=Ru())!=null?Ku:zu),$u(Uu,!0),ju()}).then(()=>{Gu?.(Uu,void 0),Ou=!0,Du.forEach(Wu=>Wu(Uu))}).catch(Wu=>{Gu?.(void 0,Wu)})};return Iu.persist={setOptions:Vu=>{Pu={...Pu,...Vu},Vu.getStorage&&(Lu=Vu.getStorage())},clearStorage:()=>{Lu?.removeItem(Pu.name)},getOptions:()=>Pu,rehydrate:()=>Hu(),hasHydrated:()=>Ou,onHydrate:Vu=>(Mu.add(Vu),()=>{Mu.delete(Vu)}),onFinishHydration:Vu=>(Du.add(Vu),()=>{Du.delete(Vu)})},Hu(),Uu||zu},newImpl=(Au,lo)=>($u,Ru,Iu)=>{let Pu={storage:createJSONStorage(()=>localStorage),partialize:Hu=>Hu,version:0,merge:(Hu,Vu)=>({...Vu,...Hu}),...lo},Ou=!1;const Mu=new Set,Du=new Set;let Lu=Pu.storage;if(!Lu)return Au((...Hu)=>{console.warn(`[zustand persist middleware] Unable to update item '${Pu.name}', the given storage is currently unavailable.`),$u(...Hu)},Ru,Iu);const Bu=()=>{const Hu=Pu.partialize({...Ru()});return Lu.setItem(Pu.name,{state:Hu,version:Pu.version})},ju=Iu.setState;Iu.setState=(Hu,Vu)=>{ju(Hu,Vu),Bu()};const Fu=Au((...Hu)=>{$u(...Hu),Bu()},Ru,Iu);Iu.getInitialState=()=>Fu;let zu;const Uu=()=>{var Hu,Vu;if(!Lu)return;Ou=!1,Mu.forEach(Wu=>{var Ku;return Wu((Ku=Ru())!=null?Ku:Fu)});const Gu=((Vu=Pu.onRehydrateStorage)==null?void 0:Vu.call(Pu,(Hu=Ru())!=null?Hu:Fu))||void 0;return toThenable(Lu.getItem.bind(Lu))(Pu.name).then(Wu=>{if(Wu)if(typeof Wu.version=="number"&&Wu.version!==Pu.version){if(Pu.migrate)return[!0,Pu.migrate(Wu.state,Wu.version)];console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return[!1,Wu.state];return[!1,void 0]}).then(Wu=>{var Ku;const[Ju,Yu]=Wu;if(zu=Pu.merge(Yu,(Ku=Ru())!=null?Ku:Fu),$u(zu,!0),Ju)return Bu()}).then(()=>{Gu?.(zu,void 0),zu=Ru(),Ou=!0,Du.forEach(Wu=>Wu(zu))}).catch(Wu=>{Gu?.(void 0,Wu)})};return Iu.persist={setOptions:Hu=>{Pu={...Pu,...Hu},Hu.storage&&(Lu=Hu.storage)},clearStorage:()=>{Lu?.removeItem(Pu.name)},getOptions:()=>Pu,rehydrate:()=>Uu(),hasHydrated:()=>Ou,onHydrate:Hu=>(Mu.add(Hu),()=>{Mu.delete(Hu)}),onFinishHydration:Hu=>(Du.add(Hu),()=>{Du.delete(Hu)})},Pu.skipHydration||Uu(),zu||Fu},persistImpl=(Au,lo)=>"getStorage"in lo||"serialize"in lo||"deserialize"in lo?((__vite_import_meta_env__?"production":void 0)!=="production"&&console.warn("[DEPRECATED] `getStorage`, `serialize` and `deserialize` options are deprecated. Use `storage` option instead."),oldImpl(Au,lo)):newImpl(Au,lo),persist=persistImpl,defaultChatConfig={defaultProvider:"datalayer",defaultProtocol:"vercel-ai",enableStreaming:!0,requireToolApproval:!1,debug:!1,persistToLocalStorage:!1},initialState$1={config:defaultChatConfig,ready:!0,inferenceProvider:null,protocolAdapter:null,toolExecutor:null,middlewarePipeline:null,uiPluginRegistry:null,messages:[],isLoading:!1,isStreaming:!1,streamingMessageId:null,currentThreadId:null,threads:new Map,tools:new Map,pendingToolCalls:new Map,uiPlugins:new Map,middlewares:[],isOpen:!1,error:null,suggestions:[]},useChatStore=create$g()(devtools(subscribeWithSelector((Au,lo)=>({...initialState$1,setConfig:$u=>{Au(Ru=>({config:{...Ru.config,...$u}}),!1,"setConfig")},setReady:$u=>{Au({ready:$u},!1,"setReady")},setInferenceProvider:$u=>{Au({inferenceProvider:$u},!1,"setInferenceProvider")},setProtocolAdapter:$u=>{Au({protocolAdapter:$u},!1,"setProtocolAdapter")},setToolExecutor:$u=>{Au({toolExecutor:$u},!1,"setToolExecutor")},setMiddlewarePipeline:$u=>{Au({middlewarePipeline:$u},!1,"setMiddlewarePipeline")},setUIPluginRegistry:$u=>{Au({uiPluginRegistry:$u},!1,"setUIPluginRegistry")},addMessage:$u=>{Au(Ru=>({messages:[...Ru.messages,$u]}),!1,"addMessage")},updateMessage:($u,Ru)=>{Au(Iu=>({messages:Iu.messages.map(Pu=>Pu.id===$u?{...Pu,...Ru}:Pu)}),!1,"updateMessage")},deleteMessage:$u=>{Au(Ru=>({messages:Ru.messages.filter(Iu=>Iu.id!==$u)}),!1,"deleteMessage")},setMessages:$u=>{Au({messages:$u},!1,"setMessages")},clearMessages:()=>{Au({messages:[]},!1,"clearMessages")},startStreaming:$u=>{Au({isStreaming:!0,streamingMessageId:$u},!1,"startStreaming")},appendToStream:($u,Ru)=>{Au(Iu=>({messages:Iu.messages.map(Pu=>Pu.id===$u?{...Pu,content:typeof Pu.content=="string"?Pu.content+Ru:Pu.content}:Pu)}),!1,"appendToStream")},stopStreaming:()=>{Au({isStreaming:!1,streamingMessageId:null},!1,"stopStreaming")},setLoading:$u=>{Au({isLoading:$u},!1,"setLoading")},setError:$u=>{Au({error:$u},!1,"setError")},setCurrentThread:$u=>{Au({currentThreadId:$u},!1,"setCurrentThread")},createThread:$u=>{const Ru=`thread_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,Iu={id:Ru,title:$u||"New Chat",createdAt:new Date,updatedAt:new Date};return Au(Pu=>{const Ou=new Map(Pu.threads);return Ou.set(Ru,Iu),{threads:Ou,currentThreadId:Ru}},!1,"createThread"),Ru},deleteThread:$u=>{Au(Ru=>{const Iu=new Map(Ru.threads);return Iu.delete($u),{threads:Iu,currentThreadId:Ru.currentThreadId===$u?null:Ru.currentThreadId}},!1,"deleteThread")},registerTool:$u=>{Au(Ru=>{const Iu=new Map(Ru.tools);return Iu.set($u.name,{definition:$u,registeredAt:new Date}),{tools:Iu}},!1,"registerTool")},unregisterTool:$u=>{Au(Ru=>{const Iu=new Map(Ru.tools);return Iu.delete($u),{tools:Iu}},!1,"unregisterTool")},getTool:$u=>lo().tools.get($u),getTools:()=>Array.from(lo().tools.values()).map($u=>$u.definition),startToolCall:($u,Ru,Iu)=>{Au(Pu=>{const Ou=new Map(Pu.pendingToolCalls);return Ou.set($u,{toolCallId:$u,toolName:Ru,args:Iu,status:"pending",startedAt:new Date}),{pendingToolCalls:Ou}},!1,"startToolCall")},updateToolCallStatus:($u,Ru,Iu,Pu)=>{Au(Ou=>{const Mu=new Map(Ou.pendingToolCalls),Du=Mu.get($u);return Du&&Mu.set($u,{...Du,status:Ru,result:Iu,error:Pu,completedAt:Ru==="completed"||Ru==="failed"?new Date:void 0}),{pendingToolCalls:Mu}},!1,"updateToolCallStatus")},getPendingToolCalls:()=>Array.from(lo().pendingToolCalls.values()).filter($u=>$u.status==="pending"||$u.status==="executing"),registerUIPlugin:($u,Ru)=>{Au(Iu=>{const Pu=new Map(Iu.uiPlugins);return Pu.set($u.name,{plugin:$u,enabled:Ru?.enabled??!0,registeredAt:new Date}),{uiPlugins:Pu}},!1,"registerUIPlugin")},unregisterUIPlugin:$u=>{Au(Ru=>{const Iu=new Map(Ru.uiPlugins);return Iu.delete($u),{uiPlugins:Iu}},!1,"unregisterUIPlugin")},enableUIPlugin:$u=>{Au(Ru=>{const Iu=new Map(Ru.uiPlugins),Pu=Iu.get($u);return Pu&&Iu.set($u,{...Pu,enabled:!0}),{uiPlugins:Iu}},!1,"enableUIPlugin")},disableUIPlugin:$u=>{Au(Ru=>{const Iu=new Map(Ru.uiPlugins),Pu=Iu.get($u);return Pu&&Iu.set($u,{...Pu,enabled:!1}),{uiPlugins:Iu}},!1,"disableUIPlugin")},getUIPlugins:$u=>{const Ru=Array.from(lo().uiPlugins.values()).filter(Iu=>Iu.enabled).map(Iu=>Iu.plugin);return $u?Ru.filter(Iu=>Iu.type===$u):Ru},addMiddleware:$u=>{Au(Ru=>({middlewares:[...Ru.middlewares,$u].sort((Iu,Pu)=>(Iu.priority??100)-(Pu.priority??100))}),!1,"addMiddleware")},removeMiddleware:$u=>{Au(Ru=>({middlewares:Ru.middlewares.filter(Iu=>Iu.name!==$u)}),!1,"removeMiddleware")},getMiddlewares:()=>lo().middlewares,setOpen:$u=>{Au({isOpen:$u},!1,"setOpen")},toggleOpen:()=>{Au($u=>({isOpen:!$u.isOpen}),!1,"toggleOpen")},setSuggestions:$u=>{Au({suggestions:$u},!1,"setSuggestions")},reset:()=>{Au(initialState$1,!1,"reset")}})),{name:"chat-store"})),useChatMessages=()=>useChatStore(Au=>Au.messages),useChatOpen=()=>useChatStore(Au=>Au.isOpen),initialState={conversations:{}},useConversationStore=create$g()(devtools(subscribeWithSelector((Au,lo)=>({...initialState,getMessages:$u=>lo().conversations[$u]?.messages||[],setMessages:($u,Ru)=>{Au(Iu=>({conversations:{...Iu.conversations,[$u]:{runtimeId:$u,messages:Ru,updatedAt:Date.now(),fetchedFromServer:Iu.conversations[$u]?.fetchedFromServer||!1,isFetching:Iu.conversations[$u]?.isFetching||!1}}}),!1,"setMessages")},addMessage:($u,Ru)=>{Au(Iu=>{const Pu=Iu.conversations[$u],Ou=Pu?.messages||[];return{conversations:{...Iu.conversations,[$u]:{runtimeId:$u,messages:[...Ou,Ru],updatedAt:Date.now(),fetchedFromServer:Pu?.fetchedFromServer||!1,isFetching:Pu?.isFetching||!1}}}},!1,"addMessage")},updateMessage:($u,Ru,Iu)=>{Au(Pu=>{const Ou=Pu.conversations[$u];return Ou?{conversations:{...Pu.conversations,[$u]:{...Ou,messages:Ou.messages.map(Mu=>Mu.id===Ru?{...Mu,...Iu}:Mu),updatedAt:Date.now()}}}:Pu},!1,"updateMessage")},clearMessages:$u=>{Au(Ru=>{const Iu=Ru.conversations[$u];return Iu?{conversations:{...Ru.conversations,[$u]:{...Iu,messages:[],updatedAt:Date.now(),fetchedFromServer:!1}}}:Ru},!1,"clearMessages")},clearAll:()=>{Au({conversations:{}},!1,"clearAll")},markFetched:$u=>{Au(Ru=>{const Iu=Ru.conversations[$u];return{conversations:{...Ru.conversations,[$u]:Iu?{...Iu,fetchedFromServer:!0,isFetching:!1}:{runtimeId:$u,messages:[],updatedAt:Date.now(),fetchedFromServer:!0,isFetching:!1}}}},!1,"markFetched")},setFetching:($u,Ru)=>{Au(Iu=>{const Pu=Iu.conversations[$u];return{conversations:{...Iu.conversations,[$u]:Pu?{...Pu,isFetching:Ru}:{runtimeId:$u,messages:[],updatedAt:Date.now(),fetchedFromServer:!1,isFetching:Ru}}}},!1,"setFetching")},needsFetch:$u=>{const Ru=lo().conversations[$u];return!Ru?.fetchedFromServer&&!Ru?.isFetching},isFetching:$u=>lo().conversations[$u]?.isFetching||!1,deleteConversation:$u=>{Au(Ru=>{const{[$u]:Iu,...Pu}=Ru.conversations;return{conversations:Pu}},!1,"deleteConversation")}})),{name:"ConversationStore"})),RECORD_KIND_WORDS={session:"Session",tool_call:"Tool call",decision:"Rule",check:"Check",approval:"Approval",output:"Answer",feedback:"Feedback",turn:"Turn",run:"Working",notification:"Notification"};function entryOf(Au){return{uid:String(Au.uid??""),sessionUid:String(Au.session_uid??""),deploymentUid:String(Au.deployment_uid??""),version:Number(Au.version)||0,kind:String(Au.kind??"output"),summary:String(Au.summary??""),payload:Au.payload&&typeof Au.payload=="object"?Au.payload:{},createdAt:String(Au.created_at??"")}}const RUN_END_WORDS={answered:"Answered",stopped:"Stopped",gone:"Its client went before the answer"};function runEndOf(Au){const lo=Au.kind==="output"?Au.payload.status:void 0;return typeof lo=="string"&&lo in RUN_END_WORDS?lo:""}function entrySaid(Au){return Au.summary||RUN_END_WORDS[runEndOf(Au)]||""}const ASKED_FOR_TAG="asked-for";function askedOf(Au){const lo=`<${ASKED_FOR_TAG}>`,$u=`</${ASKED_FOR_TAG}>`;if(!Au.startsWith(lo))return Au;const Ru=Au.indexOf($u);if(Ru<0)throw new Error(`What was asked opens <${ASKED_FOR_TAG}> and never closes it.`);return Au.slice(Ru+$u.length).trimStart()}function sessionSentence(Au){const lo=Au.filter(Ou=>Ou.kind==="tool_call").length,$u=Au.filter(Ou=>Ou.kind==="check"),Ru=Au.map(runEndOf).filter(Boolean),Iu=Ru.filter(Ou=>Ou==="answered").length,Pu=[lo===0?"No tool called":`${lo} tool call${lo===1?"":"s"}`];return $u.length&&Pu.push(`${$u.length} step${$u.length===1?"":"s"} a check did not let pass`),Ru[Ru.length-1]==="stopped"?Pu.push("stopped"):Iu&&Pu.push(`${Iu} answer${Iu===1?"":"s"}`),`${Pu.join(", ")}.`}async function read(Au,lo,$u){if(!Au.aiAgentsUrl)throw new Error("The record service is not configured.");const Ru=await fetch(`${Au.aiAgentsUrl.replace(/\/+$/,"")}/api/ai-agents/v1/apps${lo}`,{headers:Au.token?{Authorization:`Bearer ${Au.token}`}:{}}),Iu=await Ru.json().catch(()=>({}));if(!Ru.ok||Iu.success===!1)throw new Error(`${$u}: ${String(Iu.detail??Ru.status)}`);return Iu}async function listSessions(Au,lo,$u=20,Ru=!1){const Iu=await read(Au,`/sessions?app_uid=${encodeURIComponent(lo)}&limit=${$u}${Ru===null?"":`&tests=${Ru}`}`,"The sessions could not be read");return Array.isArray(Iu.sessions)?Iu.sessions.map(entryOf):[]}async function readSession(Au,lo){const $u=await read(Au,`/records?session_uid=${encodeURIComponent(lo)}&limit=500`,"The session could not be read");return Array.isArray($u.entries)?$u.entries.map(entryOf).filter(Ru=>Ru.kind!=="run"):[]}function extractChatMessagesFromFullContext(Au){return Au?(Array.isArray(Au.messages)?Au.messages:[]).map(($u,Ru)=>{const Iu=String($u.role||"").toLowerCase(),Pu=typeof $u.timestamp=="string"&&$u.timestamp.length>0?$u.timestamp:new Date().toISOString(),Ou=new Date(Pu),Mu=Number.isNaN(Ou.getTime())?new Date:Ou,Du=typeof $u.content=="string"?$u.content:JSON.stringify($u.content??""),Lu=!!$u.isToolCall,Bu=!!$u.isToolResult,ju=typeof $u.toolCallId=="string"&&$u.toolCallId.length>0?$u.toolCallId:void 0,Fu=typeof $u.toolName=="string"&&$u.toolName.length>0?$u.toolName:void 0;if(Lu){let zu={};if(Du)try{const Hu=JSON.parse(Du);Hu&&typeof Hu=="object"&&!Array.isArray(Hu)&&(zu=Hu)}catch{zu={}}const Uu=ju||`history-tc-${Ru}`;return{id:`history-toolcall-${Ru}-${Pu}`,role:"assistant",content:"",createdAt:Mu,toolCalls:[{type:"tool-call",toolCallId:Uu,toolName:Fu||"tool",args:zu,status:"completed"}]}}return Bu||Iu==="tool"?{id:`history-toolresult-${Ru}-${Pu}`,role:"tool",content:Du,createdAt:Mu,metadata:{toolCallId:ju,toolName:Fu}}:Iu!=="user"&&Iu!=="assistant"?null:{id:`history-${Iu}-${Ru}-${Pu}`,role:Iu,content:Iu==="user"?askedOf(Du):Du,createdAt:Mu}}).filter($u=>$u!==null):[]}const AIModels={BEDROCK_US_ANTHROPIC_CLAUDE_SONNET_4_6:"bedrock:us.anthropic.claude-sonnet-4-6"},ALIBABA_QWEN_MAX_0_0_1={id:"alibaba:qwen-max",version:"0.0.1",name:"Alibaba Qwen-Max",description:"Qwen-Max via Alibaba Cloud Model Studio - highest capability Qwen model",provider:"alibaba",providerUrl:"https://www.alibabacloud.com/help/en/model-studio/models",default:!1,available:!0,requiredEnvVars:[],tokensLimit:32768,capabilities:["chat","tools","codemode"]},ALIBABA_QWEN3_32B_0_0_1={id:"alibaba:qwen3-32b",version:"0.0.1",name:"Alibaba Qwen3-32B",description:"Qwen3-32B via Alibaba Cloud Model Studio - open-weight 32B model with tool calling",provider:"alibaba",providerUrl:"https://www.alibabacloud.com/help/en/model-studio/models",default:!1,available:!1,requiredEnvVars:[],tokensLimit:16384,capabilities:["chat","tools","codemode"]},ALIBABA_QWEN3_6_FLASH_0_0_1={id:"alibaba:qwen3.6-flash",version:"0.0.1",name:"Alibaba Qwen3.6-Flash",description:"Qwen3.6-Flash via Alibaba Cloud Model Studio - fast and low cost",provider:"alibaba",providerUrl:"https://www.alibabacloud.com/help/en/model-studio/models",default:!1,available:!1,requiredEnvVars:[],tokensLimit:16384,capabilities:["chat","tools","codemode"]},ALIBABA_QWEN3_6_PLUS_0_0_1={id:"alibaba:qwen3.6-plus",version:"0.0.1",name:"Alibaba Qwen3.6-Plus",description:"Qwen3.6-Plus via Alibaba Cloud Model Studio - balanced performance and cost",provider:"alibaba",providerUrl:"https://www.alibabacloud.com/help/en/model-studio/models",default:!1,available:!1,requiredEnvVars:[],tokensLimit:32768,capabilities:["chat","tools","codemode"]},ALIBABA_QWEN3_7_PLUS_0_0_1={id:"alibaba:qwen3.7-plus",version:"0.0.1",name:"Alibaba Qwen3.7-Plus",description:"Qwen3.7-Plus via Alibaba Cloud Model Studio - balanced flagship Qwen3 model",provider:"alibaba",providerUrl:"https://www.alibabacloud.com/help/en/model-studio/models",default:!1,available:!1,requiredEnvVars:[],tokensLimit:32768,capabilities:["chat","tools","codemode"]},ANTHROPIC_CLAUDE_3_5_HAIKU_20241022_0_0_1={id:"anthropic:claude-3-5-haiku-20241022",version:"0.0.1",name:"Anthropic Claude Haiku 3.5",description:"Claude Haiku 3.5 by Anthropic - fast and efficient",provider:"anthropic",providerUrl:"https://www.anthropic.com/claude/haiku",default:!1,available:!1,requiredEnvVars:["ANTHROPIC_API_KEY"],tokensLimit:8192,pricing:{inputUsdPerMillion:.8,outputUsdPerMillion:4}},ANTHROPIC_CLAUDE_OPUS_4_20250514_0_0_1={id:"anthropic:claude-opus-4-20250514",version:"0.0.1",name:"Anthropic Claude Opus 4",description:"Claude Opus 4 by Anthropic - highest capability model",provider:"anthropic",providerUrl:"https://www.anthropic.com/claude/opus",default:!1,available:!1,requiredEnvVars:["ANTHROPIC_API_KEY"],tokensLimit:32e3,pricing:{inputUsdPerMillion:15,outputUsdPerMillion:75}},ANTHROPIC_CLAUDE_SONNET_4_5_20250514_0_0_1={id:"anthropic:claude-sonnet-4-5-20250514",version:"0.0.1",name:"Anthropic Claude Sonnet 4.5",description:"Claude Sonnet 4.5 by Anthropic - balanced performance and speed",provider:"anthropic",providerUrl:"https://www.anthropic.com/claude/sonnet",default:!1,available:!1,requiredEnvVars:["ANTHROPIC_API_KEY"],tokensLimit:64e3,pricing:{inputUsdPerMillion:3,outputUsdPerMillion:15}},ANTHROPIC_CLAUDE_SONNET_4_20250514_0_0_1={id:"anthropic:claude-sonnet-4-20250514",version:"0.0.1",name:"Anthropic Claude Sonnet 4",description:"Claude Sonnet 4 by Anthropic - strong reasoning and coding",provider:"anthropic",providerUrl:"https://www.anthropic.com/claude/sonnet",default:!1,available:!1,requiredEnvVars:["ANTHROPIC_API_KEY"],tokensLimit:64e3,pricing:{inputUsdPerMillion:3,outputUsdPerMillion:15}},AZURE_OPENAI_GPT_4_1_MINI_0_0_1={id:"azure-openai:gpt-4.1-mini",version:"0.0.1",name:"Azure OpenAI GPT-4.1 Mini",description:"GPT-4.1 Mini via Azure OpenAI - compact version",provider:"azure-openai",providerUrl:"https://learn.microsoft.com/en-us/azure/ai-foundry/foundry-models/concepts/models-sold-directly-by-azure",default:!1,available:!1,requiredEnvVars:["AZURE_OPENAI_API_KEY","AZURE_OPENAI_ENDPOINT"],tokensLimit:32768,pricing:{inputUsdPerMillion:.4,outputUsdPerMillion:1.6}},AZURE_OPENAI_GPT_4_1_NANO_0_0_1={id:"azure-openai:gpt-4.1-nano",version:"0.0.1",name:"Azure OpenAI GPT-4.1 Nano",description:"GPT-4.1 Nano via Azure OpenAI - smallest and fastest",provider:"azure-openai",providerUrl:"https://learn.microsoft.com/en-us/azure/ai-foundry/foundry-models/concepts/models-sold-directly-by-azure",default:!1,available:!1,requiredEnvVars:["AZURE_OPENAI_API_KEY","AZURE_OPENAI_ENDPOINT"],tokensLimit:32768,pricing:{inputUsdPerMillion:.1,outputUsdPerMillion:.4}},AZURE_OPENAI_GPT_4_1_0_0_1={id:"azure-openai:gpt-4.1",version:"0.0.1",name:"Azure OpenAI GPT-4.1",description:"GPT-4.1 via Azure OpenAI - strong general purpose",provider:"azure-openai",providerUrl:"https://learn.microsoft.com/en-us/azure/ai-foundry/foundry-models/concepts/models-sold-directly-by-azure",default:!1,available:!1,requiredEnvVars:["AZURE_OPENAI_API_KEY","AZURE_OPENAI_ENDPOINT"],tokensLimit:32768,pricing:{inputUsdPerMillion:2,outputUsdPerMillion:8}},AZURE_OPENAI_GPT_4O_MINI_0_0_1={id:"azure-openai:gpt-4o-mini",version:"0.0.1",name:"Azure OpenAI GPT-4o Mini",description:"GPT-4o Mini via Azure OpenAI - compact enterprise deployment",provider:"azure-openai",providerUrl:"https://learn.microsoft.com/en-us/azure/ai-foundry/foundry-models/concepts/models-sold-directly-by-azure",default:!1,available:!1,requiredEnvVars:["AZURE_OPENAI_API_KEY","AZURE_OPENAI_ENDPOINT"],tokensLimit:16384,pricing:{inputUsdPerMillion:.15,outputUsdPerMillion:.6}},AZURE_OPENAI_GPT_4O_0_0_1={id:"azure-openai:gpt-4o",version:"0.0.1",name:"Azure OpenAI GPT-4o",description:"GPT-4o via Azure OpenAI - enterprise deployment",provider:"azure-openai",providerUrl:"https://learn.microsoft.com/en-us/azure/ai-foundry/foundry-models/concepts/models-sold-directly-by-azure",default:!1,available:!1,requiredEnvVars:["AZURE_OPENAI_API_KEY","AZURE_OPENAI_ENDPOINT"],tokensLimit:16384,pricing:{inputUsdPerMillion:2.5,outputUsdPerMillion:10}},BEDROCK_US_ANTHROPIC_CLAUDE_FABLE_5_0_0_1={id:"bedrock:us.anthropic.claude-fable-5",version:"0.0.1",name:"Bedrock Claude Fable 5",description:"Claude Fable 5 via AWS Bedrock",provider:"bedrock",providerUrl:"https://aws.amazon.com/bedrock/anthropic/",default:!1,available:!1,requiredEnvVars:["AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_DEFAULT_REGION"],tokensLimit:64e3,pricing:{inputUsdPerMillion:11,outputUsdPerMillion:55}},BEDROCK_US_ANTHROPIC_CLAUDE_OPUS_4_6_V1_0_0_1={id:"bedrock:us.anthropic.claude-opus-4-6-v1",version:"0.0.1",name:"Bedrock Claude Opus 4.6",description:"Claude Opus 4.6 via AWS Bedrock",provider:"bedrock",providerUrl:"https://aws.amazon.com/bedrock/anthropic/",default:!1,available:!1,requiredEnvVars:["AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_DEFAULT_REGION"],tokensLimit:32e3,pricing:{inputUsdPerMillion:5.5,outputUsdPerMillion:27.5}},BEDROCK_US_ANTHROPIC_CLAUDE_OPUS_4_8_0_0_1={id:"bedrock:us.anthropic.claude-opus-4-8",version:"0.0.1",name:"Bedrock Claude Opus 4.8",description:"Claude Opus 4.8 via AWS Bedrock",provider:"bedrock",providerUrl:"https://aws.amazon.com/bedrock/anthropic/",default:!1,available:!1,requiredEnvVars:["AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_DEFAULT_REGION"],tokensLimit:32e3,pricing:{inputUsdPerMillion:5.5,outputUsdPerMillion:27.5}},BEDROCK_US_ANTHROPIC_CLAUDE_OPUS_4_20250514_V1_0_0_0_1={id:"bedrock:us.anthropic.claude-opus-4-20250514-v1:0",version:"0.0.1",name:"Bedrock Claude Opus 4",description:"Claude Opus 4 via AWS Bedrock - highest capability",provider:"bedrock",providerUrl:"https://aws.amazon.com/bedrock/anthropic/",default:!1,available:!1,requiredEnvVars:["AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_DEFAULT_REGION"],tokensLimit:32e3,pricing:{inputUsdPerMillion:15,outputUsdPerMillion:75}},BEDROCK_US_ANTHROPIC_CLAUDE_OPUS_5_0_0_1={id:"bedrock:us.anthropic.claude-opus-5",version:"0.0.1",name:"Bedrock Claude Opus 5",description:"Claude Opus 5 via AWS Bedrock - the current frontier model",provider:"bedrock",providerUrl:"https://aws.amazon.com/bedrock/anthropic/",default:!1,available:!1,requiredEnvVars:["AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_DEFAULT_REGION"],tokensLimit:32e3,pricing:{inputUsdPerMillion:5.5,outputUsdPerMillion:27.5}},BEDROCK_US_ANTHROPIC_CLAUDE_SONNET_4_5_20250929_V1_0_0_0_1={id:"bedrock:us.anthropic.claude-sonnet-4-5-20250929-v1:0",version:"0.0.1",name:"Bedrock Claude Sonnet 4.5",description:"Claude Sonnet 4.5 via AWS Bedrock - balanced performance",provider:"bedrock",providerUrl:"https://aws.amazon.com/bedrock/anthropic/",default:!1,available:!1,requiredEnvVars:["AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_DEFAULT_REGION"],tokensLimit:64e3,pricing:{inputUsdPerMillion:3.3,outputUsdPerMillion:16.5}},BEDROCK_US_ANTHROPIC_CLAUDE_SONNET_4_6_0_0_1={id:"bedrock:us.anthropic.claude-sonnet-4-6",version:"0.0.1",name:"Bedrock Claude Sonnet 4.6",description:"Claude Sonnet 4.6 via AWS Bedrock - balanced performance",provider:"bedrock",providerUrl:"https://aws.amazon.com/bedrock/anthropic/",default:!0,available:!0,requiredEnvVars:["AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_DEFAULT_REGION"],tokensLimit:64e3,capabilities:["chat","tools","decider"],contextWindow:2e5,pricing:{inputUsdPerMillion:3.3,outputUsdPerMillion:16.5}},BEDROCK_US_ANTHROPIC_CLAUDE_SONNET_4_20250514_V1_0_0_0_1={id:"bedrock:us.anthropic.claude-sonnet-4-20250514-v1:0",version:"0.0.1",name:"Bedrock Claude Sonnet 4",description:"Claude Sonnet 4 via AWS Bedrock - strong reasoning",provider:"bedrock",providerUrl:"https://aws.amazon.com/bedrock/anthropic/",default:!1,available:!1,requiredEnvVars:["AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_DEFAULT_REGION"],tokensLimit:64e3,pricing:{inputUsdPerMillion:3,outputUsdPerMillion:15}},CLOUDFLARE_GTW_TYPESAFE_JEV_0_0_1={id:"cloudflare:gtw/typesafe/jev",version:"0.0.1",name:"Jev (Cloudflare AI Gateway)",description:"Typesafe's typed-decision model through the account's AI Gateway - noul, choice and score questions answered as calibrated probabilities; 32k context; zero data retention; the gateway keeps the logs and bills from its credits",provider:"cloudflare",providerUrl:"https://docs.typesafe.ai/models",default:!1,available:!0,requiredEnvVars:[],capabilities:["decisions"],billing:"credits",route:"ai-gateway",contextWindow:32e3,zeroDataRetention:!0,requestLogging:"gateway",pricing:{inputUsdPerMillion:.042,outputUsdPerMillion:0}},CLOUDFLARE_WRK_GOOGLE_GEMMA_4_26B_A4B_IT_0_0_1={id:"cloudflare:wrk/google/gemma-4-26b-a4b-it",version:"0.0.1",name:"Cloudflare Gemma 4 26B",description:"Google Gemma 4 26B (a4b, instruction-tuned) on Cloudflare Workers AI - 256k context, tool calling, standard billing",provider:"cloudflare",providerUrl:"https://developers.cloudflare.com/workers-ai/models/gemma-4-26b-a4b-it/",default:!1,available:!1,requiredEnvVars:[],tokensLimit:16384,capabilities:["chat","tools","codemode"],billing:"standard",route:"workers-ai",contextWindow:256e3,aliases:["cloudflare:google/gemma-4-26b-a4b-it"],pricing:{inputUsdPerMillion:.1,outputUsdPerMillion:.3}},CLOUDFLARE_WRK_ZAI_ORG_GLM_5_2_0_0_1={id:"cloudflare:wrk/zai-org/glm-5.2",version:"0.0.1",name:"Cloudflare GLM-5.2",description:"Z.ai GLM-5.2 on Cloudflare Workers AI - 262k context, tool calling; a frontier model billed from AI Gateway credits",provider:"cloudflare",providerUrl:"https://developers.cloudflare.com/workers-ai/models/glm-5.2/",default:!1,available:!1,requiredEnvVars:[],tokensLimit:32768,capabilities:["chat","tools","codemode"],billing:"credits",route:"workers-ai",contextWindow:262144,aliases:["cloudflare:zai-org/glm-5.2"],pricing:{inputUsdPerMillion:1.4,outputUsdPerMillion:4.4}},CLOUDFLARE_WRK_OPENAI_GPT_OSS_120B_0_0_1={id:"cloudflare:wrk/openai/gpt-oss-120b",version:"0.0.1",name:"Cloudflare gpt-oss-120b",description:"OpenAI gpt-oss-120b on Cloudflare Workers AI - 128k context, tool calling, standard billing",provider:"cloudflare",providerUrl:"https://developers.cloudflare.com/workers-ai/models/gpt-oss-120b/",default:!1,available:!1,requiredEnvVars:[],tokensLimit:32768,capabilities:["chat","tools","codemode","decider"],billing:"standard",route:"workers-ai",contextWindow:128e3,aliases:["cloudflare:openai/gpt-oss-120b"],pricing:{inputUsdPerMillion:.35,outputUsdPerMillion:.75}},CLOUDFLARE_WRK_MOONSHOTAI_KIMI_K2_6_0_0_1={id:"cloudflare:wrk/moonshotai/kimi-k2.6",version:"0.0.1",name:"Cloudflare Kimi K2.6",description:"Moonshot Kimi K2.6 on Cloudflare Workers AI - 262k context, tool calling; a frontier model billed from AI Gateway credits",provider:"cloudflare",providerUrl:"https://developers.cloudflare.com/workers-ai/models/kimi-k2.6/",default:!1,available:!1,requiredEnvVars:[],tokensLimit:32768,capabilities:["chat","tools","codemode"],billing:"credits",route:"workers-ai",contextWindow:262144,aliases:["cloudflare:moonshotai/kimi-k2.6"],pricing:{inputUsdPerMillion:.95,outputUsdPerMillion:4}},CLOUDFLARE_WRK_META_LLAMA_3_3_70B_INSTRUCT_FP8_FAST_0_0_1={id:"cloudflare:wrk/meta/llama-3.3-70b-instruct-fp8-fast",version:"0.0.1",name:"Cloudflare Llama 3.3 70B",description:"Meta Llama 3.3 70B Instruct (fp8, fast) on Cloudflare Workers AI - 24k context, tool calling, standard billing",provider:"cloudflare",providerUrl:"https://developers.cloudflare.com/workers-ai/models/llama-3.3-70b-instruct-fp8-fast/",default:!1,available:!1,requiredEnvVars:[],tokensLimit:8192,capabilities:["chat","tools","codemode"],billing:"standard",route:"workers-ai",contextWindow:24e3,aliases:["cloudflare:meta/llama-3.3-70b-instruct-fp8-fast"],pricing:{inputUsdPerMillion:.293,outputUsdPerMillion:2.253}},CLOUDFLARE_WRK_QWEN_QWEN3_8_27B_0_0_1={id:"cloudflare:wrk/qwen/qwen3.8-27b",version:"0.0.1",name:"Cloudflare Qwen3.8 27B",description:"Qwen3.8 27B on Cloudflare Workers AI - 262k context, tool calling, standard billing",provider:"cloudflare",providerUrl:"https://developers.cloudflare.com/workers-ai/models/qwen3.8-27b/",default:!1,available:!1,requiredEnvVars:[],tokensLimit:16384,capabilities:["chat","tools","codemode"],billing:"standard",route:"workers-ai",contextWindow:262144,aliases:["cloudflare:qwen/qwen3.8-27b"],pricing:{inputUsdPerMillion:.45,outputUsdPerMillion:3.2}},CLOUDFLARE_WRK_TYPESAFE_JEV_0_0_1={id:"cloudflare:wrk/typesafe/jev",version:"0.0.1",name:"Jev (Cloudflare Workers AI)",description:"Typesafe's typed-decision model at Workers AI's own endpoint - noul, choice and score questions answered as calibrated probabilities; 32k context; zero data retention; billed from the account's credits, no gateway in the way",provider:"cloudflare",providerUrl:"https://docs.typesafe.ai/models",default:!1,available:!0,requiredEnvVars:[],capabilities:["decisions"],billing:"credits",route:"workers-ai",contextWindow:32e3,zeroDataRetention:!0,requestLogging:"none",pricing:{inputUsdPerMillion:.042,outputUsdPerMillion:0}},OLLAMA_GEMMA3_4B_0_0_1={id:"ollama:gemma3:4b",version:"0.0.1",name:"Gemma 3 4B (Ollama)",description:"Gemma 3 4B running locally through Ollama - small and fast, no tool calling",provider:"ollama",providerUrl:"https://ollama.com/library/gemma3:4b",default:!1,available:!1,requiredEnvVars:[],tokensLimit:4096,local:!0,capabilities:["chat"]},OLLAMA_LLAMA3_1_8B_0_0_1={id:"ollama:llama3.1:8b",version:"0.0.1",name:"Llama 3.1 8B (Ollama)",description:"Meta Llama 3.1 8B running locally through Ollama - tool calling, no data leaves the machine",provider:"ollama",providerUrl:"https://ollama.com/library/llama3.1:8b",default:!1,available:!1,requiredEnvVars:[],tokensLimit:4096,local:!0,capabilities:["chat","tools","codemode"]},OLLAMA_QWEN2_5_CODER_7B_0_0_1={id:"ollama:qwen2.5-coder:7b",version:"0.0.1",name:"Qwen2.5 Coder 7B (Ollama)",description:"Qwen2.5 Coder 7B running locally through Ollama - code-focused with tool calling",provider:"ollama",providerUrl:"https://ollama.com/library/qwen2.5-coder:7b",default:!1,available:!1,requiredEnvVars:[],tokensLimit:4096,local:!0,capabilities:["chat","tools","codemode"]},OPENAI_GPT_4_1_MINI_0_0_1={id:"openai:gpt-4.1-mini",version:"0.0.1",name:"OpenAI GPT-4.1 Mini",description:"GPT-4.1 Mini by OpenAI - compact version of GPT-4.1",provider:"openai",providerUrl:"https://platform.openai.com/docs/models/gpt-4.1-mini",default:!1,available:!1,requiredEnvVars:["OPENAI_API_KEY"],tokensLimit:32768,pricing:{inputUsdPerMillion:.4,outputUsdPerMillion:1.6}},OPENAI_GPT_4_1_NANO_0_0_1={id:"openai:gpt-4.1-nano",version:"0.0.1",name:"OpenAI GPT-4.1 Nano",description:"GPT-4.1 Nano by OpenAI - smallest and fastest",provider:"openai",providerUrl:"https://platform.openai.com/docs/models/gpt-4.1-nano",default:!1,available:!1,requiredEnvVars:["OPENAI_API_KEY"],tokensLimit:32768,pricing:{inputUsdPerMillion:.1,outputUsdPerMillion:.4}},OPENAI_GPT_4_1_0_0_1={id:"openai:gpt-4.1",version:"0.0.1",name:"OpenAI GPT-4.1",description:"GPT-4.1 by OpenAI - strong general purpose model",provider:"openai",providerUrl:"https://platform.openai.com/docs/models/gpt-4.1",default:!1,available:!1,requiredEnvVars:["OPENAI_API_KEY"],tokensLimit:32768,pricing:{inputUsdPerMillion:2,outputUsdPerMillion:8}},OPENAI_GPT_4O_MINI_0_0_1={id:"openai:gpt-4o-mini",version:"0.0.1",name:"OpenAI GPT-4o Mini",description:"GPT-4o Mini by OpenAI - compact and cost-effective",provider:"openai",providerUrl:"https://platform.openai.com/docs/models/gpt-4o-mini",default:!1,available:!1,requiredEnvVars:["OPENAI_API_KEY"],tokensLimit:16384,pricing:{inputUsdPerMillion:.15,outputUsdPerMillion:.6}},OPENAI_GPT_4O_0_0_1={id:"openai:gpt-4o",version:"0.0.1",name:"OpenAI GPT-4o",description:"GPT-4o by OpenAI - fast multimodal model",provider:"openai",providerUrl:"https://platform.openai.com/docs/models/gpt-4o",default:!1,available:!1,requiredEnvVars:["OPENAI_API_KEY"],tokensLimit:16384,pricing:{inputUsdPerMillion:2.5,outputUsdPerMillion:10}},OPENAI_O3_MINI_0_0_1={id:"openai:o3-mini",version:"0.0.1",name:"OpenAI o3 Mini",description:"o3 Mini by OpenAI - reasoning-focused compact model",provider:"openai",providerUrl:"https://platform.openai.com/docs/models/o3-mini",default:!1,available:!1,requiredEnvVars:["OPENAI_API_KEY"],tokensLimit:1e5,pricing:{inputUsdPerMillion:1.1,outputUsdPerMillion:4.4}},AI_MODEL_CATALOGUE={"alibaba:qwen-max":ALIBABA_QWEN_MAX_0_0_1,"alibaba:qwen3-32b":ALIBABA_QWEN3_32B_0_0_1,"alibaba:qwen3.6-flash":ALIBABA_QWEN3_6_FLASH_0_0_1,"alibaba:qwen3.6-plus":ALIBABA_QWEN3_6_PLUS_0_0_1,"alibaba:qwen3.7-plus":ALIBABA_QWEN3_7_PLUS_0_0_1,"anthropic:claude-3-5-haiku-20241022":ANTHROPIC_CLAUDE_3_5_HAIKU_20241022_0_0_1,"anthropic:claude-opus-4-20250514":ANTHROPIC_CLAUDE_OPUS_4_20250514_0_0_1,"anthropic:claude-sonnet-4-5-20250514":ANTHROPIC_CLAUDE_SONNET_4_5_20250514_0_0_1,"anthropic:claude-sonnet-4-20250514":ANTHROPIC_CLAUDE_SONNET_4_20250514_0_0_1,"azure-openai:gpt-4.1-mini":AZURE_OPENAI_GPT_4_1_MINI_0_0_1,"azure-openai:gpt-4.1-nano":AZURE_OPENAI_GPT_4_1_NANO_0_0_1,"azure-openai:gpt-4.1":AZURE_OPENAI_GPT_4_1_0_0_1,"azure-openai:gpt-4o-mini":AZURE_OPENAI_GPT_4O_MINI_0_0_1,"azure-openai:gpt-4o":AZURE_OPENAI_GPT_4O_0_0_1,"bedrock:us.anthropic.claude-fable-5":BEDROCK_US_ANTHROPIC_CLAUDE_FABLE_5_0_0_1,"bedrock:us.anthropic.claude-opus-4-6-v1":BEDROCK_US_ANTHROPIC_CLAUDE_OPUS_4_6_V1_0_0_1,"bedrock:us.anthropic.claude-opus-4-8":BEDROCK_US_ANTHROPIC_CLAUDE_OPUS_4_8_0_0_1,"bedrock:us.anthropic.claude-opus-4-20250514-v1:0":BEDROCK_US_ANTHROPIC_CLAUDE_OPUS_4_20250514_V1_0_0_0_1,"bedrock:us.anthropic.claude-opus-5":BEDROCK_US_ANTHROPIC_CLAUDE_OPUS_5_0_0_1,"bedrock:us.anthropic.claude-sonnet-4-5-20250929-v1:0":BEDROCK_US_ANTHROPIC_CLAUDE_SONNET_4_5_20250929_V1_0_0_0_1,"bedrock:us.anthropic.claude-sonnet-4-6":BEDROCK_US_ANTHROPIC_CLAUDE_SONNET_4_6_0_0_1,"bedrock:us.anthropic.claude-sonnet-4-20250514-v1:0":BEDROCK_US_ANTHROPIC_CLAUDE_SONNET_4_20250514_V1_0_0_0_1,"cloudflare:gtw/typesafe/jev":CLOUDFLARE_GTW_TYPESAFE_JEV_0_0_1,"cloudflare:wrk/google/gemma-4-26b-a4b-it":CLOUDFLARE_WRK_GOOGLE_GEMMA_4_26B_A4B_IT_0_0_1,"cloudflare:wrk/zai-org/glm-5.2":CLOUDFLARE_WRK_ZAI_ORG_GLM_5_2_0_0_1,"cloudflare:wrk/openai/gpt-oss-120b":CLOUDFLARE_WRK_OPENAI_GPT_OSS_120B_0_0_1,"cloudflare:wrk/moonshotai/kimi-k2.6":CLOUDFLARE_WRK_MOONSHOTAI_KIMI_K2_6_0_0_1,"cloudflare:wrk/meta/llama-3.3-70b-instruct-fp8-fast":CLOUDFLARE_WRK_META_LLAMA_3_3_70B_INSTRUCT_FP8_FAST_0_0_1,"cloudflare:wrk/qwen/qwen3.8-27b":CLOUDFLARE_WRK_QWEN_QWEN3_8_27B_0_0_1,"cloudflare:wrk/typesafe/jev":CLOUDFLARE_WRK_TYPESAFE_JEV_0_0_1,"ollama:gemma3:4b":OLLAMA_GEMMA3_4B_0_0_1,"ollama:llama3.1:8b":OLLAMA_LLAMA3_1_8B_0_0_1,"ollama:qwen2.5-coder:7b":OLLAMA_QWEN2_5_CODER_7B_0_0_1,"openai:gpt-4.1-mini":OPENAI_GPT_4_1_MINI_0_0_1,"openai:gpt-4.1-nano":OPENAI_GPT_4_1_NANO_0_0_1,"openai:gpt-4.1":OPENAI_GPT_4_1_0_0_1,"openai:gpt-4o-mini":OPENAI_GPT_4O_MINI_0_0_1,"openai:gpt-4o":OPENAI_GPT_4O_0_0_1,"openai:o3-mini":OPENAI_O3_MINI_0_0_1};function isChatModel(Au){return!(Au.capabilities??[]).includes("decisions")}const DEFAULT_MODEL=AIModels.BEDROCK_US_ANTHROPIC_CLAUDE_SONNET_4_6;class BaseProtocolAdapter{config;_connectionState="disconnected";eventHandlers=new Set;reconnectAttempts=0;constructor(lo){this.config={autoReconnect:!0,reconnectDelay:1e3,maxReconnectAttempts:5,timeout:3e4,...lo}}get connectionState(){return this._connectionState}subscribe(lo){return this.eventHandlers.add(lo),()=>{this.eventHandlers.delete(lo)}}async getAgentCard(){return null}supportsFeature(lo){return!1}emit(lo){for(const $u of this.eventHandlers)try{$u(lo)}catch(Ru){console.error(`[${this.protocol}] Error in event handler:`,Ru)}}setConnectionState(lo){const $u=this._connectionState;this._connectionState=lo,$u!==lo&&this.emit({type:lo==="connected"?"connected":"disconnected",timestamp:new Date})}async handleReconnect(){if(!this.config.autoReconnect)return;if(this.reconnectAttempts>=(this.config.maxReconnectAttempts||5)){this.setConnectionState("error"),this.emit({type:"error",error:new Error("Max reconnection attempts reached"),timestamp:new Date});return}this.setConnectionState("reconnecting"),this.reconnectAttempts++;const lo=this.config.reconnectDelay*Math.pow(2,this.reconnectAttempts-1);await new Promise($u=>setTimeout($u,lo));try{await this.connect(),this.reconnectAttempts=0}catch{await this.handleReconnect()}}buildHeaders(lo){const $u={"Content-Type":"application/json"};return this.config.authToken&&($u.Authorization=`Bearer ${this.config.authToken}`),{...$u,...lo}}fetchOf(){return this.config.fetch??((lo,$u)=>fetch(lo,$u))}createTimeoutSignal(){return AbortSignal.timeout(this.config.timeout||3e4)}}const AG_UI_NOT_ON_RUNTIME="This agent is not on the runtime the page is addressing: its AG-UI address answered nothing. An agent that runs its code in the browser is never started on a runtime — run it in the page, or give it a sandbox a runtime has (eval, jupyter-server).",AG_UI_NOT_ALLOWED="This agent did not answer the page: the run was refused. Sign in again, or open the application from its own address.";function refusalDetail(Au){if(!Au)return"";let lo;try{lo=JSON.parse(Au)}catch{return""}if(!lo||typeof lo!="object")return"";const $u=lo.detail;return typeof $u=="string"?$u.trim():""}function agUiRefusal(Au,lo,$u){const Ru=refusalDetail($u);return Ru||(Au===404?AG_UI_NOT_ON_RUNTIME:Au===401||Au===403?AG_UI_NOT_ALLOWED:`AG-UI request failed: ${Au} ${lo}`.trim())}async function refusalBody(Au){try{return await Au.text()}catch{return}}const RUN_CUT_SHORT="The run stopped before it finished, without an answer or an error: send it again.";class AGUIAdapter extends BaseProtocolAdapter{protocol="ag-ui";protocolTransport="sse";aguiConfig;abortController=null;inFlight=new Set;currentThreadId=null;pendingToolCalls=new Map;collectedToolResults=new Map;messageHistory=[];lastAssistantContent="";lastTurnContent="";lastTools=[];isContinuation=!1;_streamParsingDepth=0;_streamDonePromise=null;_streamDoneResolve=null;constructor(lo){super(lo),this.aguiConfig={...lo,baseUrl:lo.baseUrl.endsWith("/")?lo.baseUrl:`${lo.baseUrl}/`}}async connect(){this.setConnectionState("connecting"),this.setConnectionState("connected")}disconnect(){this.stopGeneration(),this.currentThreadId&&this.terminateAgent(this.currentThreadId).catch(lo=>{console.warn("[AGUIAdapter] Failed to terminate agent:",lo)}),this.setConnectionState("disconnected")}async terminateAgent(lo){try{const Ru=`${new URL(this.aguiConfig.baseUrl).origin}/api/v1/ag-ui/terminate`,Iu=await this.fetchOf()(Ru,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({thread_id:lo||this.currentThreadId})});Iu.ok||console.warn(`[AGUIAdapter] Terminate request failed: ${Iu.status}`)}catch{}}async sendMessage(lo,$u){const Ru=new AbortController;this.abortController=Ru,this.inFlight.add(Ru);const Iu=$u?.threadId||this.currentThreadId||generateMessageId();this.currentThreadId=Iu;const Pu=$u?.messages||[lo];this.messageHistory=[...Pu],this.lastTools=$u?.tools||[],this.isContinuation||(this.lastAssistantContent="",this.lastTurnContent="");const Ou=Pu.map(Du=>{const Lu={id:Du.id,role:Du.role,content:Du.content};return Du.role==="tool"&&Du.metadata?.toolCallId&&(Lu.tool_call_id=Du.metadata.toolCallId),Du.role==="assistant"&&Du.toolCalls&&Du.toolCalls.length>0&&(Lu.content=typeof Du.content=="string"&&Du.content.trim()?Du.content:null,Lu.tool_calls=Du.toolCalls.map(Bu=>({id:Bu.toolCallId,type:"function",function:{name:Bu.toolName,arguments:JSON.stringify(Bu.args||{})}}))),Lu}),Mu={threadId:Iu,runId:generateMessageId(),messages:Ou,state:null,tools:$u?.tools||[],...$u?.builtinTools!==void 0&&{builtinTools:$u.builtinTools},...$u?.skills!==void 0&&{skills:$u.skills},context:[],forwardedProps:$u?.forwardedProps??null,...$u?.model&&{model:$u.model},...$u?.identities&&$u.identities.length>0&&{identities:$u.identities}};$u?.model&&console.log("[AGUIAdapter] Sending with model:",$u.model),$u?.identities&&$u.identities.length>0&&console.log("[AGUIAdapter] Sending with identities:",$u.identities.map(Du=>Du.provider));try{const Du=await this.fetchOf()(this.aguiConfig.baseUrl,{method:"POST",headers:this.buildHeaders({Accept:"text/event-stream"}),body:JSON.stringify(Mu),signal:Ru.signal});if(!Du.ok)throw new Error(agUiRefusal(Du.status,Du.statusText,await refusalBody(Du)));await this.parseSSEStream(Du)}catch(Du){if(Du.name==="AbortError")return;throw this.emit({type:"error",error:Du instanceof Error?Du:new Error(String(Du)),timestamp:new Date}),Du}finally{this.inFlight.delete(Ru),this.abortController===Ru&&(this.abortController=null)}}async sendToolResult(lo,$u){this.emit({type:"tool-result",toolResult:$u,timestamp:new Date});const Ru=this.pendingToolCalls.get(lo);Ru||console.warn("[AGUIAdapter] No pending tool call found for ID:",lo);const Iu=Ru?.toolName||"unknown";let Pu={};if(Ru?.argsJson)try{Pu=JSON.parse(Ru.argsJson)}catch(Fu){console.warn("[AGUIAdapter] Failed to parse tool args:",Fu)}this.collectedToolResults.set(lo,{toolCallId:lo,toolName:Iu,parsedArgs:Pu,result:$u});let Ou=Array.from(this.pendingToolCalls.keys()).every(Fu=>this.collectedToolResults.has(Fu));if(!Ou||this._streamParsingDepth>0&&this._streamDonePromise&&(await this._streamDonePromise,Ou=Array.from(this.pendingToolCalls.keys()).every(Fu=>this.collectedToolResults.has(Fu)),!Ou))return;const Mu=Array.from(this.collectedToolResults.values()).map(Fu=>({type:"tool-call",toolCallId:Fu.toolCallId,toolName:Fu.toolName,args:Fu.parsedArgs,status:"completed"})),Du={id:generateMessageId(),role:"assistant",content:this.lastTurnContent||this.lastAssistantContent||"",createdAt:new Date,toolCalls:Mu},Lu=Array.from(this.collectedToolResults.values()).map(Fu=>({id:generateMessageId(),role:"tool",content:typeof Fu.result.result=="string"?Fu.result.result:JSON.stringify(Fu.result.result),createdAt:new Date,metadata:{toolCallId:Fu.toolCallId,toolName:Fu.toolName,isError:!Fu.result.success}})),Bu=[...this.messageHistory,Du,...Lu];this.pendingToolCalls.clear(),this.collectedToolResults.clear(),this.messageHistory=Bu,console.log("[AGUIAdapter] === CONTINUATION MESSAGES ==="),Bu.forEach((Fu,zu)=>{const Uu=Fu.toolCalls?` [${Fu.toolCalls.length} tool_calls: ${Fu.toolCalls.map(Gu=>Gu.toolName).join(", ")}]`:"",Hu=Fu.metadata?.toolCallId?` [tool_call_id=${Fu.metadata.toolCallId}]`:"",Vu=typeof Fu.content=="string"?Fu.content.slice(0,80):"";console.log(`[AGUIAdapter] [${zu}] role=${Fu.role}${Uu}${Hu} content="${Vu}"`)}),console.log("[AGUIAdapter] === END CONTINUATION MESSAGES ==="),this.isContinuation=!0;const ju=Lu[Lu.length-1];await this.sendMessage(ju,{messages:Bu,tools:this.lastTools,threadId:this.currentThreadId||void 0})}stopGeneration(){for(const lo of this.inFlight)lo.abort();this.inFlight.clear(),this.abortController=null}supportsFeature(lo){return["streaming","tools","frontend-tools","backend-tools","activity-messages"].includes(lo)}async parseSSEStream(lo){const $u=lo.body?.getReader();if(!$u)throw new Error("Response body is not readable");const Ru=new TextDecoder;let Iu="",Pu=null,Ou="",Mu="";this.isContinuation=!1,this._streamParsingDepth===0&&(this._streamDonePromise=new Promise(Lu=>{this._streamDoneResolve=Lu})),this._streamParsingDepth++;let Du=!1;try{for(;;){const{done:Lu,value:Bu}=await $u.read();if(Lu){if(!Du)throw new Error(RUN_CUT_SHORT);break}Iu+=Ru.decode(Bu,{stream:!0});const ju=Iu.split(`
|
|
2100
2100
|
`);Iu=ju.pop()||"";for(const Fu of ju)if(!Fu.startsWith("event: ")){if(Fu.startsWith("data: ")){const zu=Fu.slice(6);try{const Uu=JSON.parse(zu),Hu=Uu.type;(Hu==="RUN_FINISHED"||Hu==="RUN_ERROR")&&(Du=!0),this.handleAGUIEvent(Uu,{getCurrentMessageId:()=>Pu,setCurrentMessageId:Vu=>{Pu=Vu},getCurrentContent:()=>Ou,appendContent:Vu=>{Ou+=Vu},resetContent:()=>{Ou=""},appendTurnContent:Vu=>{Mu+=Vu},getCurrentTurnContent:()=>Mu})}catch(Uu){console.warn("[AGUIAdapter] Failed to parse event data:",Uu)}}}}}finally{if($u.releaseLock(),this._streamParsingDepth--,this._streamParsingDepth===0){const Lu=this._streamDoneResolve;this._streamDonePromise=null,this._streamDoneResolve=null,Lu?.()}}}refuseUiOnRun(){this.emit({type:"error",error:new Error("A reactor.ui op came on the run stream: it comes over the ui socket (REACTOR_UI RU-W)."),timestamp:new Date})}handleAGUIEvent(lo,$u){switch(lo.type){case"RUN_STARTED":$u.getCurrentMessageId()||$u.setCurrentMessageId(generateMessageId()),$u.getCurrentContent()||$u.resetContent();break;case"TEXT_MESSAGE_START":{const Iu=lo.messageId;$u.setCurrentMessageId(Iu||generateMessageId()),$u.resetContent();break}case"TEXT_MESSAGE_CONTENT":{const Iu=lo.delta;if(Iu){$u.appendContent(Iu),$u.appendTurnContent(Iu);const Pu=createAssistantMessage($u.getCurrentContent());Pu.id=$u.getCurrentMessageId()||generateMessageId(),this.emit({type:"message",message:Pu,timestamp:new Date})}break}case"TEXT_MESSAGE_END":{const Iu=createAssistantMessage($u.getCurrentContent());Iu.id=$u.getCurrentMessageId()||generateMessageId(),this.lastAssistantContent=$u.getCurrentContent(),this.lastTurnContent=$u.getCurrentTurnContent(),this.emit({type:"message",message:Iu,timestamp:new Date});break}case"TOOL_CALL_START":{const Iu=lo.toolCallId||lo.tool_call_id||generateMessageId(),Pu=lo.toolCallName||lo.tool_call_name||lo.name||"";this.pendingToolCalls.set(Iu,{toolCallId:Iu,toolName:Pu,argsJson:""}),this.emit({type:"tool-call",toolCall:{toolCallId:Iu,toolName:Pu,args:{},argsComplete:!1},timestamp:new Date});break}case"TOOL_CALL_ARGS":{const Iu=lo.toolCallId||lo.tool_call_id,Pu=lo.delta;if(Iu&&Pu&&this.pendingToolCalls.has(Iu)){const Ou=this.pendingToolCalls.get(Iu);Ou&&(Ou.argsJson+=Pu)}break}case"TOOL_CALL_END":{const Iu=lo.toolCallId||lo.tool_call_id;if(Iu&&this.pendingToolCalls.has(Iu)){const Pu=this.pendingToolCalls.get(Iu);if(Pu){let Ou={};if(Pu.argsJson)try{Ou=JSON.parse(Pu.argsJson)}catch{}this.emit({type:"tool-call",toolCall:{toolCallId:Pu.toolCallId,toolName:Pu.toolName,args:Ou,argsComplete:!0},timestamp:new Date})}}break}case"TOOL_CALL_RESULT":{const Iu=lo.toolCallId||lo.tool_call_id;let Pu=lo.content;if(typeof Pu=="string")try{Pu=JSON.parse(Pu)}catch{}if(Iu){const Ou=Pu,Mu=Ou?.execution_ok===!1||Ou?.code_error!=null||Ou?.error!=null&&!Ou?.success,Du=Ou?.execution_error||Ou?.error||(Ou?.code_error?`${Ou.code_error?.name||"Error"}: ${Ou.code_error?.value||""}`:void 0);this.emit({type:"tool-result",toolResult:{toolCallId:Iu,success:!Mu,result:Pu,error:Mu?Du:void 0},timestamp:new Date}),this.pendingToolCalls.delete(Iu)}break}case"STATE_SNAPSHOT":{const Iu=lo.snapshot;this.emit({type:"state-update",data:Iu,timestamp:new Date});break}case"STATE_DELTA":{const Iu=lo.delta;this.emit({type:"state-update",data:{__delta:Iu},timestamp:new Date});break}case"ACTIVITY_SNAPSHOT":case"ACTIVITY_DELTA":{lo.activityType===AGUI_NAME&&this.refuseUiOnRun();break}case"CUSTOM":{const Iu=lo.name;if(Iu===AGUI_NAME){this.refuseUiOnRun();break}this.emit({type:"activity",activity:{type:Iu||"custom",data:lo.value},timestamp:new Date});break}case"RUN_FINISHED":{const Iu=lo.usage;Iu&&this.emit({type:"message",usage:{promptTokens:Iu.promptTokens??0,completionTokens:Iu.completionTokens??0,totalTokens:Iu.totalTokens??(Iu.promptTokens??0)+(Iu.completionTokens??0)},timestamp:new Date}),this.pendingToolCalls.size===0&&this.emit({type:"done",timestamp:new Date});break}case"RUN_ERROR":{const Iu=lo.message;this.emit({type:"error",error:new Error(Iu||"Run failed"),timestamp:new Date});break}}}}const ORCHESTRATION_EXTENSION_URI="https://datalayer.ai/extensions/orchestration/v1",ENVELOPE_KEY="datalayer",USAGE_FIELD="usage";function isRecord$2(Au){return typeof Au=="object"&&Au!==null}function ours(Au){if(!isRecord$2(Au))return;const lo=Au[ENVELOPE_KEY];return isRecord$2(lo)?lo:void 0}function tokenCountFromWire(Au){return{inputTokens:typeof Au.inputTokens=="number"?Au.inputTokens:void 0,outputTokens:typeof Au.outputTokens=="number"?Au.outputTokens:void 0,cost:typeof Au.cost=="number"?Au.cost:void 0,currency:typeof Au.currency=="string"?Au.currency:"USD"}}function readUsageMeta(Au){const $u=ours(Au)?.[USAGE_FIELD];return isRecord$2($u)?tokenCountFromWire($u):void 0}const A2A_EXTENSIONS_HEADER="A2A-Extensions",TERMINAL_TASK_STATES=new Set(["completed","failed","canceled","rejected"]);function normalizeA2AResult(Au){if(!Au||typeof Au!="object"||Au.kind)return Au;if(Au.task)return{...Au.task,kind:"task"};if(Au.statusUpdate){const lo=Au.statusUpdate;return{...lo,kind:"status-update",final:lo.final??TERMINAL_TASK_STATES.has(lo.status?.state)}}return Au.artifactUpdate?{...Au.artifactUpdate,kind:"artifact-update"}:Au.message?{...Au.message,kind:"message"}:Au}class A2AAdapter extends BaseProtocolAdapter{protocol="a2a";protocolTransport="sse";a2aConfig;abortController=null;inFlight=new Set;agentCard=null;currentTaskId=null;orchestrationExtensionSupported=!1;constructor(lo){super(lo),this.a2aConfig={enableA2UI:!0,...lo}}async connect(){this.setConnectionState("connecting");try{const lo=this.a2aConfig.agentUrl||this.a2aConfig.baseUrl,$u=new URL("/.well-known/agent-card.json",lo).toString(),Ru=await fetch($u,{method:"GET",headers:this.buildHeaders(),signal:this.createTimeoutSignal()});Ru.ok&&(this.agentCard=await Ru.json(),this.orchestrationExtensionSupported=this.agentCard?.capabilities?.extensions?.some(Iu=>Iu.uri===ORCHESTRATION_EXTENSION_URI)??!1),this.setConnectionState("connected")}catch(lo){console.warn("[A2AAdapter] Could not fetch agent card:",lo),this.setConnectionState("connected")}}disconnect(){this.stopGeneration(),this.currentTaskId&&this.terminateTask(this.currentTaskId).catch(lo=>{console.warn("[A2AAdapter] Failed to terminate task:",lo)}),this.setConnectionState("disconnected")}async terminateTask(lo){try{const Ru=`${new URL(this.a2aConfig.baseUrl).origin}/api/v1/a2a/terminate`,Iu=await fetch(Ru,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({task_id:lo||this.currentTaskId})});if(!Iu.ok)console.warn(`[A2AAdapter] Terminate request failed: ${Iu.status}`);else{const Pu=await Iu.json();console.debug("[A2AAdapter] Terminate result:",Pu)}}catch($u){console.debug("[A2AAdapter] Terminate request error:",$u)}}async getAgentCard(){return this.agentCard}get supportsOrchestrationExtension(){return this.orchestrationExtensionSupported}async sendMessage(lo,$u){const Ru=new AbortController;this.abortController=Ru,this.inFlight.add(Ru);const Iu=$u?.threadId||this.currentTaskId||generateMessageId();this.currentTaskId=Iu;const Pu=[];if(typeof lo.content=="string")Pu.push({kind:"text",text:lo.content});else if(Array.isArray(lo.content))for(const Lu of lo.content)Lu.type==="text"?Pu.push({kind:"text",text:Lu.text}):Lu.type==="activity"&&Pu.push({kind:"data",data:Lu.data});const Ou={};$u?.model&&(Ou.model=$u.model),$u?.identities&&$u.identities.length>0&&(Ou.identities=$u.identities);const Du={jsonrpc:"2.0",method:"message/stream",params:{message:{kind:"message",messageId:generateMessageId(),role:lo.role,parts:Pu},configuration:{acceptedOutputModes:["text","text/plain"],requestedExtensions:this.a2aConfig.enableA2UI?["a2ui"]:[],...$u?.model&&{model:$u.model}},...Object.keys(Ou).length>0&&{metadata:Ou}},id:Iu};$u?.model&&console.log("[A2AAdapter] Sending with model:",$u.model,"(Note: A2A uses agent-level model, not per-request)"),$u?.identities&&$u.identities.length>0&&console.log("[A2AAdapter] Sending with identities:",$u.identities.map(Lu=>Lu.provider));try{const Lu=await fetch(this.a2aConfig.baseUrl,{method:"POST",headers:this.buildHeaders({Accept:"text/event-stream, application/json",...this.orchestrationExtensionSupported&&{[A2A_EXTENSIONS_HEADER]:ORCHESTRATION_EXTENSION_URI}}),body:JSON.stringify(Du),signal:Ru.signal});if(!Lu.ok)throw new Error(`A2A request failed: ${Lu.status} ${Lu.statusText}`);if((Lu.headers.get("content-type")||"").includes("text/event-stream"))await this.parseSSEStream(Lu);else{const ju=await Lu.json();console.log("[A2AAdapter] JSON response:",JSON.stringify(ju,null,2)),this.handleA2AEvent(ju)}}catch(Lu){if(Lu.name==="AbortError")return;throw this.emit({type:"error",error:Lu instanceof Error?Lu:new Error(String(Lu)),timestamp:new Date}),Lu}finally{this.inFlight.delete(Ru),this.abortController===Ru&&(this.abortController=null)}}stopGeneration(){for(const lo of this.inFlight)lo.abort();this.inFlight.clear(),this.abortController=null}async sendToolResult(lo,$u){this.emit({type:"tool-result",toolResult:$u,timestamp:new Date})}supportsFeature(lo){return["streaming","agent-discovery","a2ui","activity-messages","multi-agent"].includes(lo)}async parseSSEStream(lo){const $u=lo.body?.getReader();if(!$u)throw new Error("Response body is not readable");const Ru=new TextDecoder;let Iu="";try{for(;;){const{done:Pu,value:Ou}=await $u.read();if(Pu)break;Iu+=Ru.decode(Ou,{stream:!0});const Mu=Iu.split(`
|
|
2101
2101
|
`);Iu=Mu.pop()||"";for(const Du of Mu)if(Du.startsWith("data: ")){const Lu=Du.slice(6);try{const Bu=JSON.parse(Lu);this.handleA2AEvent(Bu)}catch(Bu){console.warn("[A2AAdapter] Failed to parse event data:",Bu)}}}}finally{$u.releaseLock()}}handleA2AEvent(lo){console.log("[A2AAdapter] Received event:",JSON.stringify(lo,null,2)),lo.result?this.handleTaskUpdate(normalizeA2AResult(lo.result)):lo.error&&this.emit({type:"error",error:new Error(lo.error.message||"A2A error"),timestamp:new Date})}handleTaskUpdate(lo){console.log("[A2AAdapter] Handling task update:",JSON.stringify(lo,null,2));const $u=lo.kind;if($u==="message"&&lo.role==="agent"){this.processA2AMessage(lo);return}if($u==="status-update"){const Pu=lo.status?.state;if(console.log("[A2AAdapter] Status update:",Pu,"final:",lo.final),lo.final&&(Pu==="completed"||Pu==="failed"||Pu==="canceled")){const Ou=this.orchestrationExtensionSupported?lo.status?.message?.metadata?.[ENVELOPE_KEY]:void 0,Mu=Ou?readUsageMeta(lo.status.message.metadata):void 0;this.emit({type:"state-update",data:{state:Pu,final:!0,...Ou?.paused&&{datalayerPaused:Ou.paused},...Ou?.error&&{datalayerError:Ou.error},...Mu&&{datalayerUsage:Mu}},...Mu&&{usage:{promptTokens:Mu.inputTokens??0,completionTokens:Mu.outputTokens??0,...Mu.inputTokens!==void 0&&Mu.outputTokens!==void 0&&{totalTokens:Mu.inputTokens+Mu.outputTokens}}},timestamp:new Date})}return}if($u==="artifact-update"){console.log("[A2AAdapter] Artifact update:",lo.artifact);return}if($u==="task"){lo.id&&(this.currentTaskId=lo.id);const Pu=lo.history||lo.messages||[];for(const Ou of Pu)(Ou.role==="assistant"||Ou.role==="model"||Ou.role==="agent")&&this.processA2AMessage(Ou);return}const Ru=lo.history||lo.messages||[];for(const Pu of Ru)(Pu.role==="assistant"||Pu.role==="model"||Pu.role==="agent")&&this.processA2AMessage(Pu);(typeof lo.status=="object"?lo.status?.state:lo.status)==="completed"&&lo.result&&this.emit({type:"message",message:createAssistantMessage(typeof lo.result=="string"?lo.result:JSON.stringify(lo.result)),timestamp:new Date})}processA2AMessage(lo){if(console.log("[A2AAdapter] Processing message:",JSON.stringify(lo,null,2)),!lo.parts)return;let $u="";const Ru=[];for(const Iu of lo.parts){const Pu=Iu.kind||Iu.type;Pu==="text"&&Iu.text?$u+=Iu.text:Pu==="data"&&(Iu.data?.beginRendering||Iu.data?.surfaceUpdate||Iu.data?.dataModelUpdate?Ru.push({type:"a2ui",data:Iu.data}):Ru.push({type:"data",data:Iu.data}))}$u&&(console.log("[A2AAdapter] Emitting text message:",$u),this.emit({type:"message",message:createAssistantMessage($u),timestamp:new Date}));for(const Iu of Ru)this.emit({type:"activity",activity:Iu,timestamp:new Date})}}class VercelAIAdapter extends BaseProtocolAdapter{protocol="vercel-ai";protocolTransport="sse";vercelConfig;abortController=null;inFlight=new Set;currentRequestId=null;pendingToolCalls=new Map;collectedToolResults=new Map;messageHistory=[];lastAssistantText="";lastTools=[];lastFrontendToolNames=new Set;isContinuation=!1;deferredToolMeta=new Map;_streamParsingDepth=0;_streamDonePromise=null;_streamDoneResolve=null;getDeferredToolCallId(lo){if(!lo)return this.deferredToolMeta.keys().next().value;for(const[$u,Ru]of this.deferredToolMeta)if(Ru.toolName===lo||Ru.toolName===lo.replace(/-/g,"_")||Ru.toolName===lo.replace(/_/g,"-"))return $u;return this.deferredToolMeta.keys().next().value}constructor(lo){super(lo),this.vercelConfig=lo}async connect(){this.setConnectionState("connecting"),this.setConnectionState("connected")}disconnect(){this.abortController?.abort(),this.abortController=null,this.currentRequestId&&this.terminateRequest(this.currentRequestId).catch(lo=>{console.warn("[VercelAIAdapter] Failed to terminate request:",lo)}),this.setConnectionState("disconnected")}async terminateRequest(lo){try{const Ru=`${new URL(this.vercelConfig.baseUrl).origin}/api/v1/vercel-ai/terminate`,Iu=await fetch(Ru,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({request_id:lo||this.currentRequestId})});Iu.ok?await Iu.json():console.warn(`[VercelAIAdapter] Terminate request failed: ${Iu.status}`)}catch{}}async sendMessage(lo,$u){this.stopGeneration();const Ru=new AbortController;this.abortController=Ru,this.inFlight.add(Ru);const Iu=$u?.threadId||generateMessageId();this.currentRequestId=Iu,$u?.tools?(this.lastTools=$u.tools,this.lastFrontendToolNames=new Set($u.tools.map(Pu=>Pu?.name).filter(Pu=>!!Pu))):this.lastFrontendToolNames=new Set,this.isContinuation||(this.lastAssistantText="",this.deferredToolMeta.clear());try{let Pu;$u?._vercelMessages?Pu=$u._vercelMessages:Pu=($u?.messages||[lo]).map(Bu=>{const Fu=[{type:"text",text:typeof Bu.content=="string"?Bu.content:String(Bu.content??"")}];if(Bu.role==="assistant"&&Bu.toolCalls&&Bu.toolCalls.length>0)for(const zu of Bu.toolCalls)Fu.push({type:"tool-invocation",toolInvocationId:zu.toolCallId,toolName:zu.toolName,args:zu.args,state:"result",result:zu.result});return{id:Bu.id,role:Bu.role,parts:Fu,...Bu.role==="user"&&Bu.metadata?.input==="voice"?{metadata:Bu.metadata}:{}}}),this.isContinuation?this.messageHistory=[...Pu]:this.messageHistory=[...Pu];const Ou={id:Iu,messages:Pu,sdkVersion:6,trigger:"submit-message",...$u?.tools&&{tools:$u.tools},...$u?.model&&{model:$u.model},...$u?.builtinTools!==void 0&&{builtinTools:$u.builtinTools},...$u?.skills!==void 0&&{skills:$u.skills},...$u?.identities&&$u.identities.length>0&&{identities:$u.identities}};$u?.tools&&$u.tools.length>0?console.log("[VercelAIAdapter] Sending with frontend tools:",$u.tools.map(Lu=>Lu.name)):console.log("[VercelAIAdapter] No frontend tools in request"),$u?.model&&console.log("[VercelAIAdapter] Sending with model:",$u.model),$u?.builtinTools&&$u.builtinTools.length>0&&console.log("[VercelAIAdapter] Sending with builtinTools:",$u.builtinTools),$u?.skills&&$u.skills.length>0&&console.log("[VercelAIAdapter] Sending with skills:",$u.skills),$u?.identities&&$u.identities.length>0&&console.log("[VercelAIAdapter] Sending with identities:",$u.identities.map(Lu=>Lu.provider));const Mu={"Content-Type":"application/json",Accept:"text/event-stream",...this.vercelConfig.headers};this.vercelConfig.authToken&&(Mu.Authorization=`token ${this.vercelConfig.authToken}`);const Du=await fetch(this.vercelConfig.baseUrl,{method:"POST",headers:Mu,body:JSON.stringify(Ou),signal:Ru.signal,mode:this.vercelConfig.fetchOptions?.mode,credentials:this.vercelConfig.fetchOptions?.credentials});if(!Du.ok)throw new Error(`HTTP ${Du.status}: ${Du.statusText}`);if(!Du.body)throw new Error("Response body is null");await this.parseSSEStream(Du.body)}catch(Pu){if(Pu.name!=="AbortError")throw console.error("[VercelAIAdapter] Send error:",Pu),Pu}finally{this.inFlight.delete(Ru),this.abortController===Ru&&(this.abortController=null)}}async parseSSEStream(lo){const $u=lo.getReader(),Ru=new TextDecoder;let Iu="",Pu=generateMessageId(),Ou="";const Mu=new Map,Du=new Map;let Lu=!1;this.isContinuation=!1,this._streamParsingDepth===0&&(this._streamDonePromise=new Promise(Fu=>{this._streamDoneResolve=Fu})),this._streamParsingDepth++;const Bu=()=>{Lu||this.pendingToolCalls.size>0||(Lu=!0,this.emit({type:"done",timestamp:new Date}))},ju=(Fu,zu="")=>{if(Fu&&typeof Fu=="object"&&!Array.isArray(Fu))return Fu;const Uu=typeof Fu=="string"&&Fu.trim().length>0?Fu:zu;if(!Uu.trim())return{};try{const Hu=JSON.parse(Uu);if(Hu&&typeof Hu=="object"&&!Array.isArray(Hu))return Hu}catch{}return{}};try{for(;;){const{done:Fu,value:zu}=await $u.read();if(Fu){if(Ou){this.lastAssistantText=Ou;const Hu=createAssistantMessage(Ou);Hu.id=Pu,this.emit({type:"message",message:Hu,timestamp:new Date})}Bu();break}Iu+=Ru.decode(zu,{stream:!0});const Uu=Iu.split(`
|
|
2102
2102
|
`);Iu=Uu.pop()||"";for(const Hu of Uu)if(!(!Hu.trim()||Hu.startsWith(":"))&&(console.debug("[VercelAIAdapter] SSE line:",Hu),Hu.startsWith("data: "))){const Vu=Hu.slice(6);if(Vu==="[DONE]"){if(Ou){this.lastAssistantText=Ou;const Gu=createAssistantMessage(Ou);Gu.id=Pu,this.emit({type:"message",message:Gu,timestamp:new Date})}Bu();break}try{const Gu=JSON.parse(Vu);if(console.debug("[VercelAIAdapter] Parsed event:",Gu),Gu.type==="text-delta"&&Gu.delta){Ou+=Gu.delta;const Wu=createAssistantMessage(Ou);Wu.id=Pu,this.emit({type:"message",message:Wu,timestamp:new Date})}else if(Gu.type==="text-start")Pu=Gu.id||generateMessageId(),Ou="";else if(Gu.type==="finish"||Gu.type==="end-step"||Gu.type==="finish-step"){if(Ou){const Ku=createAssistantMessage(Ou);Ku.id=Pu,this.emit({type:"message",message:Ku,timestamp:new Date})}if(Gu.usage){const Ku=Gu.usage;this.emit({type:"message",usage:{promptTokens:Ku.promptTokens??0,completionTokens:Ku.completionTokens??0,totalTokens:Ku.totalTokens??(Ku.promptTokens??0)+(Ku.completionTokens??0)},timestamp:new Date})}const Wu=String(Gu.finishReason||Gu.finish_reason||"").toLowerCase();if(Gu.type==="finish"&&(Wu==="tool-calls"||Wu==="tool_calls")&&Mu.size>0){for(const[Ku]of Mu.entries())if(!this.pendingToolCalls.has(Ku)){const Ju=Du.get(Ku);this.emit({type:"tool-result",toolResult:{toolCallId:Ku,success:!0,result:{pending_approval:!0,approval_id:Ju,message:"Awaiting user approval"}},timestamp:new Date})}}Gu.type==="finish"&&Bu()}else if(Gu.type==="tool-input-start"){const Wu=Gu.toolCallId||Gu.tool_call_id||Gu.id||generateMessageId(),Ku=Gu.toolName||Gu.tool_name||Gu.name||Gu.tool?.name;Mu.set(Wu,{toolName:Ku,inputText:""})}else if(Gu.type==="tool-input-delta"){const Wu=Gu.toolCallId||Gu.tool_call_id||Gu.id;if(Wu&&Mu.has(Wu)){const Ku=Mu.get(Wu);Ku&&(Ku.inputText+=Gu.inputTextDelta||"",Mu.set(Wu,Ku))}}else if(Gu.type==="tool-input-available"){const Wu=Gu.toolCallId||Gu.tool_call_id||Gu.id||generateMessageId(),Ku=Mu.get(Wu),Ju=Gu.toolName||Gu.tool_name||Gu.name||Ku?.toolName||Gu.tool?.name,Yu=ju(Gu.input||Gu.args||Gu.arguments,Ku?.inputText||"");Ju&&(this.emit({type:"tool-call",toolCall:{toolCallId:Wu,toolName:Ju,args:Yu,argsComplete:!0},timestamp:new Date}),this.deferredToolMeta.set(Wu,{toolCallId:Wu,toolName:Ju,args:Yu}),this.lastFrontendToolNames.has(Ju)&&this.pendingToolCalls.set(Wu,{toolCallId:Wu,toolName:Ju,args:Yu}))}else if(Gu.type==="tool-output-available"){const Wu=Gu.toolCallId||Gu.tool_call_id||Gu.id||generateMessageId(),Ku=Gu.output??Gu.result??Gu.data??Gu.content;this.emit({type:"tool-result",toolResult:{toolCallId:Wu,success:!0,result:Ku},timestamp:new Date}),Mu.delete(Wu),Du.delete(Wu),this.pendingToolCalls.delete(Wu),this.deferredToolMeta.delete(Wu)}else if(Gu.type==="tool-output-error"||Gu.type==="tool-error"){const Wu=Gu.toolCallId||Gu.tool_call_id||Gu.id||generateMessageId(),Ku=Gu.error||Gu.errorText||Gu.message||"Tool error";this.pendingToolCalls.delete(Wu),this.deferredToolMeta.delete(Wu),this.emit({type:"tool-result",toolResult:{toolCallId:Wu,success:!1,error:Ku,result:Gu.output??Gu.result},timestamp:new Date}),Mu.delete(Wu),Du.delete(Wu)}else if(Gu.type==="error"){const Wu=Gu.error||Gu.errorText||Gu.message||Gu.detail||"Unknown server error";console.error("[VercelAIAdapter] Server error event:",Gu),this.emit({type:"error",error:new Error(Wu),timestamp:new Date})}else if(Gu.type==="tool-approval-request"){const Wu=Gu.toolCallId||Gu.tool_call_id||Gu.id||generateMessageId(),Ku=Gu.approvalId||Gu.approval_id;typeof Ku=="string"&&Ku.length>0&&Du.set(Wu,Ku)}else if(Gu.type==="tool-call"||Gu.type==="tool-call-start"){const Wu=Gu.toolName||Gu.tool_name||Gu.name||Gu.tool?.name,Ku=ju(Gu.args||Gu.arguments||Gu.input||Gu.tool?.arguments)||{},Ju=Gu.toolCallId||Gu.tool_call_id||Gu.id||generateMessageId();Wu&&this.emit({type:"tool-call",toolCall:{toolCallId:Ju,toolName:Wu,args:Ku},timestamp:new Date})}}catch(Gu){console.error("[VercelAIAdapter] Failed to parse SSE data:",Gu)}}}}finally{if($u.releaseLock(),this._streamParsingDepth--,this._streamParsingDepth===0){const Fu=this._streamDoneResolve;this._streamDonePromise=null,this._streamDoneResolve=null,Fu?.()}}}async sendToolResult(lo,$u){console.info("[VercelAIAdapter] sendToolResult called",{toolCallId:lo,success:$u?.success,hasApprovalDecision:!!$u?.result&&typeof $u.result=="object"&&typeof $u.result.approved=="boolean",knownDeferredToolCallIds:Array.from(this.deferredToolMeta.keys()),pendingToolCallIds:Array.from(this.pendingToolCalls.keys())}),this.emit({type:"tool-result",toolResult:$u,timestamp:new Date});const Ru=this.pendingToolCalls.get(lo)??this.deferredToolMeta.get(lo);Ru||console.warn("[VercelAIAdapter] No pending tool call found for ID:",lo);const Iu=Ru?.toolName??"unknown",Pu=Ru?.args??{};this.collectedToolResults.set(lo,{toolCallId:lo,toolName:Iu,args:Pu,result:$u});let Ou=Array.from(this.pendingToolCalls.keys()).every(ju=>this.collectedToolResults.has(ju));if(!Ou||this._streamParsingDepth>0&&this._streamDonePromise&&(await this._streamDonePromise,Ou=Array.from(this.pendingToolCalls.keys()).every(ju=>this.collectedToolResults.has(ju)),!Ou))return;const Mu=[];this.lastAssistantText&&Mu.push({type:"text",text:this.lastAssistantText,state:"done"});for(const ju of this.collectedToolResults.values()){const Fu=ju.result.result&&typeof ju.result.result=="object"?ju.result.result:void 0;if(!!Fu&&typeof Fu.approved=="boolean"){const Uu=typeof Fu?.approvalId=="string"?Fu.approvalId:ju.toolCallId,Hu=!!Fu?.approved,Vu=typeof Fu?.message=="string"?Fu.message:void 0;Mu.push({type:"dynamic-tool",toolName:ju.toolName,toolCallId:ju.toolCallId,state:"approval-responded",input:ju.args,approval:{id:Uu,approved:Hu,...Vu?{reason:Vu}:{}}})}else ju.result.success?Mu.push({type:"dynamic-tool",toolName:ju.toolName,toolCallId:ju.toolCallId,state:"output-available",input:ju.args,output:ju.result.result}):Mu.push({type:"dynamic-tool",toolName:ju.toolName,toolCallId:ju.toolCallId,state:"output-error",input:ju.args,errorText:ju.result.error??"Tool execution failed"})}const Du={id:generateMessageId(),role:"assistant",parts:Mu},Lu=[...this.messageHistory,Du];this.pendingToolCalls.clear(),this.collectedToolResults.clear(),this.deferredToolMeta.clear(),this.messageHistory=Lu,this.isContinuation=!0;const Bu={id:generateMessageId(),role:"user",content:"",createdAt:new Date};console.info("[VercelAIAdapter] Sending continuation request",{messageCount:Lu.length,assistantParts:Mu.map(ju=>({type:ju.type,state:ju.state,toolName:ju.toolName}))}),await this.sendMessage(Bu,{_vercelMessages:Lu,tools:this.lastTools,threadId:this.currentRequestId??void 0})}async requestPermission(lo){return!0}supportsFeature(lo){return["streaming","tools","frontend-tools","backend-tools"].includes(lo)}stopGeneration(){for(const lo of this.inFlight)lo.abort();this.inFlight.clear(),this.abortController=null}}var marker$6="vercel.ai.error",symbol$7=Symbol.for(marker$6),_a$9,_b$7,AISDKError$2=class IS extends(_b$7=Error,_a$9=symbol$7,_b$7){constructor({name:lo,message:$u,cause:Ru}){super($u),this[_a$9]=!0,this.name=lo,this.cause=Ru}static isInstance(lo){return IS.hasMarker(lo,marker$6)}static hasMarker(lo,$u){const Ru=Symbol.for($u);return lo!=null&&typeof lo=="object"&&Ru in lo&&typeof lo[Ru]=="boolean"&&lo[Ru]===!0}},name$8="AI_APICallError",marker2$5=`vercel.ai.error.${name$8}`,symbol2$4=Symbol.for(marker2$5),_a2$4,_b2$4,APICallError$2=class extends(_b2$4=AISDKError$2,_a2$4=symbol2$4,_b2$4){constructor({message:lo,url:$u,requestBodyValues:Ru,statusCode:Iu,responseHeaders:Pu,responseBody:Ou,cause:Mu,isRetryable:Du=Iu!=null&&(Iu===408||Iu===409||Iu===429||Iu>=500),data:Lu}){super({name:name$8,message:lo,cause:Mu}),this[_a2$4]=!0,this.url=$u,this.requestBodyValues=Ru,this.statusCode=Iu,this.responseHeaders=Pu,this.responseBody=Ou,this.isRetryable=Du,this.data=Lu}static isInstance(lo){return AISDKError$2.hasMarker(lo,marker2$5)}},name2$3="AI_EmptyResponseBodyError",marker3$4=`vercel.ai.error.${name2$3}`,symbol3$3=Symbol.for(marker3$4),_a3$3,_b3$3,EmptyResponseBodyError$1=class extends(_b3$3=AISDKError$2,_a3$3=symbol3$3,_b3$3){constructor({message:lo="Empty response body"}={}){super({name:name2$3,message:lo}),this[_a3$3]=!0}static isInstance(lo){return AISDKError$2.hasMarker(lo,marker3$4)}};function getErrorMessage$2(Au){return Au==null?"unknown error":typeof Au=="string"?Au:Au instanceof Error?Au.toString():JSON.stringify(Au)}var name3$4="AI_InvalidArgumentError",marker4$4=`vercel.ai.error.${name3$4}`,symbol4$4=Symbol.for(marker4$4),_a4$4,_b4$4,InvalidArgumentError$3=class extends(_b4$4=AISDKError$2,_a4$4=symbol4$4,_b4$4){constructor({message:lo,cause:$u,argument:Ru}){super({name:name3$4,message:lo,cause:$u}),this[_a4$4]=!0,this.argument=Ru}static isInstance(lo){return AISDKError$2.hasMarker(lo,marker4$4)}},name6$4="AI_JSONParseError",marker7$4=`vercel.ai.error.${name6$4}`,symbol7$4=Symbol.for(marker7$4),_a7$4,_b7$4,JSONParseError$2=class extends(_b7$4=AISDKError$2,_a7$4=symbol7$4,_b7$4){constructor({text:lo,cause:$u}){super({name:name6$4,message:`JSON parsing failed: Text: ${lo}.
|
|
@@ -3670,7 +3670,7 @@ ${Pu}\`\`\``}),lo}function ChatMarkdown({text:Au,density:lo="comfortable"}){retu
|
|
|
3670
3670
|
|
|
3671
3671
|
`)){const Ru=$u.split(`
|
|
3672
3672
|
`).filter(Pu=>Pu.startsWith("data:")).map(Pu=>Pu.slice(5).trim()).join("");if(!Ru)continue;let Iu;try{Iu=JSON.parse(Ru)}catch{continue}if(Iu.type==="RUN_ERROR")lo=String(Iu.message??"The turn failed.");else if(Iu.type==="CUSTOM"&&Iu.name===AGUI_NAME)throw new Error("A reactor.ui op came on the run stream: it comes over the ui socket.")}return lo}function messageOfDisplay(Au){const lo=Au.data?.message_id;if(typeof lo!="string"||!lo)throw new Error(`Display ${Au.id} says no message it is under`);return lo}function speakerOf(Au){return{id:`author:${Au}`,name:Au}}function changed(Au,lo,$u){const Ru=Au.findIndex(Iu=>(Iu.displays??[]).some(Pu=>Pu.id===lo));if(Ru<0)throw new Error(`Display ${lo} is shown under no message here`);return Au.map((Iu,Pu)=>{if(Pu!==Ru)return Iu;const Ou=[];for(const Mu of Iu.displays??[]){if(Mu.id!==lo){Ou.push(Mu);continue}const Du=$u(Mu);Du&&Ou.push({...Du,id:lo})}return{...Iu,displays:Ou}})}function replaced(Au,lo){const $u=Au.findIndex(Ru=>Ru.id===lo.id);return $u<0?[...Au,lo]:Au.map((Ru,Iu)=>Iu===$u?lo:Ru)}function withUiOp(Au,lo){switch(lo.op){case"show":case"ask":{const $u=lo.body,Ru=messageOfDisplay($u);if(!Au.some(Iu=>Iu.id===Ru))throw new Error(`Display ${$u.id} is under message ${Ru}, which is not here`);return Au.map(Iu=>Iu.id===Ru?{...Iu,displays:replaced(Iu.displays??[],$u)}:Iu)}case"remove":{if(Au.some(Ru=>(Ru.displays??[]).some(Iu=>Iu.id===lo.id)))return changed(Au,lo.id,()=>{});if(!Au.some(Ru=>Ru.id===lo.id))throw new Error(`Nothing here is ${lo.id}: it cannot be removed`);return Au.filter(Ru=>Ru.id!==lo.id)}case"patch":{const $u=lo.body;return changed(Au,lo.id,Ru=>applyPatch$1(Ru,$u))}case"append":{const{path:$u,value:Ru}=lo.body;return changed(Au,lo.id,Iu=>applyPatch$1(Iu,[{op:"add",path:`${$u}/-`,value:Ru}]))}case"meta":{const $u=lo.body.author,Ru=Object.keys(lo.body);if(!lo.id||Ru.length!==1||typeof $u!="string"||!$u.trim())throw new Error(`A meta op says ${JSON.stringify(lo.body)}: only a message's author is read`);if(!Au.some(Iu=>Iu.id===lo.id))throw new Error(`Message ${lo.id} is not here: it has no author to say`);return Au.map(Iu=>Iu.id===lo.id?{...Iu,speaker:speakerOf($u.trim())}:Iu)}case"window":throw new Error("A window op is for the page, not the messages");default:return Au}}function routeUiOp(Au,lo,$u){switch(Au.op){case"window":return{routed:{to:"window",data:windowMessageOf(Au)},steps:lo};case"show":case"ask":{if(isStepDisplay(Au.body)){const Iu=applyUiOp(lo,Au);return{routed:{to:"step",step:stepOfDisplay(Au.body)},steps:Iu}}const Ru=elementOfDisplay(Au.body);return Ru?{routed:{to:"element",change:Ru},steps:lo}:{routed:{to:"messages",op:Au},steps:lo}}case"patch":case"append":{if(Au.id in lo.displays){const Ru=applyUiOp(lo,Au);return{routed:{to:"step",step:stepOfDisplay(Ru.displays[Au.id])},steps:Ru}}return{routed:{to:"messages",op:Au},steps:lo}}case"remove":{if(Au.id in lo.displays)throw new Error(`Step ${Au.id} is never removed: it ends`);return $u.has(Au.id)?{routed:{to:"element",change:{id:Au.id,closed:!0}},steps:lo}:{routed:{to:"messages",op:Au},steps:lo}}default:return{routed:{to:"messages",op:Au},steps:lo}}}function placeable(Au,lo){const $u=Iu=>!!Iu&&Au.some(Pu=>Pu.id===Iu),Ru=Iu=>!!Iu&&Au.some(Pu=>(Pu.displays??[]).some(Ou=>Ou.id===Iu));switch(lo.op){case"show":case"ask":{const Iu=lo.body.data?.message_id;return typeof Iu=="string"&&$u(Iu)}case"meta":return $u(lo.id);case"patch":case"append":return Ru(lo.id);case"remove":return Ru(lo.id)||$u(lo.id);default:return!0}}function displayPressOf(Au){const $u=Au?.loop?.action;if(!$u||typeof $u.display_id!="string")return null;if(typeof $u.name!="string"||typeof $u.token!="string")throw new Error("A press of a display says its action and its token");return{action:$u.name,display_id:$u.display_id,token:$u.token,payload:$u.payload??{}}}function withPress(Au,lo){const $u=lo?.press;if(typeof $u!="string"||!$u)throw new Error("The runtime checked the press but named none");const Ru={...Au.loop};return delete Ru.action,{...Au,loop:{...Ru,press:$u}}}function blobOfDataUrl(Au,lo,$u){const[Ru,Iu]=[Au.slice(0,Au.indexOf(",")),Au.slice(Au.indexOf(",")+1)];if(!Ru.startsWith("data:")||Au.indexOf(",")<0)throw new Error(`${lo} could not be read: it is not a data URL.`);const Pu=$u||Ru.slice(5).split(";")[0];let Ou;if(Ru.endsWith(";base64")){const Mu=atob(Iu);Ou=new Uint8Array(Mu.length);for(let Du=0;Du<Mu.length;Du+=1)Ou[Du]=Mu.charCodeAt(Du)}else Ou=new TextEncoder().encode(decodeURIComponent(Iu));return Object.assign(new Blob([Ou],{type:Pu}),{name:lo})}function namesFiles(Au){const lo=Au?.loop?.files;return Array.isArray(lo)&&lo.length>0}async function withUploadedFiles(Au,lo){const $u=Au.loop,Ru=$u.files,Iu=[];for(const Pu of Ru){if(isFileRef(Pu)){Iu.push(Pu);continue}const Ou=Pu;if(typeof Ou.name!="string"||typeof Ou.data_url!="string")throw new Error("A file given is neither the page’s nor a ref.");Iu.push(await lo(blobOfDataUrl(Ou.data_url,Ou.name,typeof Ou.type=="string"?Ou.type:void 0)))}return{...Au,loop:{...$u,files:Iu}}}const EphemeralDocument=vM.lazy(()=>__vitePreload(()=>import("./chunks/EphemeralDocument-DLaNvwm_.js"),[],import.meta.url).then(Au=>({default:Au.EphemeralDocument}))),loadAgentDetails=()=>__vitePreload(()=>import("./chunks/AgentDetails-CMBy5o1q.js"),[],import.meta.url).then(Au=>({default:Au.AgentDetails})),loadEphemeralNotebook=()=>__vitePreload(()=>import("./chunks/EphemeralNotebook-jnqAJFPI.js"),[],import.meta.url).then(Au=>({default:Au.EphemeralNotebook})),lazyViewRefused=Au=>lo=>jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{p:3,color:"danger.fg"},children:`The ${Au} could not be loaded: ${lo.message}`}),agentDetailsRefused=lazyViewRefused("agent details"),ephemeralNotebookRefused=lazyViewRefused("notebook"),sentPendingPromptKeys=new Set;function frontendToolExpectsArgs(Au){const lo=Au?.parameters;if(!lo)return!1;if(Array.isArray(lo))return lo.length>0;const $u=lo.properties;return $u&&typeof $u=="object"?Object.keys($u).length>0:Object.keys(lo).length>0}function CompanionSurfaceSkeleton({mode:Au}){return jsxRuntimeExports.jsx(Box,{"aria-label":Au==="notebook"?"Preparing notebook…":"Preparing document…",flex:1,minHeight:0,overflow:"hidden",display:"flex",flexDirection:"column",gap:3,p:4,children:Au==="notebook"?jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:[0,1,2].map(lo=>jsxRuntimeExports.jsxs(Box,{p:3,border:"1px solid",borderColor:"border.muted",borderRadius:2,bg:"canvas.subtle",display:"flex",flexDirection:"column",gap:2,children:[jsxRuntimeExports.jsx(SkeletonText,{lines:1}),jsxRuntimeExports.jsx(SkeletonText,{lines:lo===0?2:3})]},lo))}):jsxRuntimeExports.jsxs(Box,{maxWidth:860,width:"100%",mx:"auto",display:"flex",flexDirection:"column",gap:3,children:[jsxRuntimeExports.jsx(SkeletonText,{lines:1}),jsxRuntimeExports.jsx(SkeletonText,{lines:4}),jsxRuntimeExports.jsx(SkeletonText,{lines:3}),jsxRuntimeExports.jsx(SkeletonText,{lines:5})]})})}const ThemedJupyterReactTheme=JupyterReactTheme$1;function ThemedChatBoundary({children:Au,themeVariant:lo,colorMode:$u,themeOverrides:Ru}){const Iu=useThemeStore(zu=>zu.colorMode),Pu=useThemeStore(zu=>zu.theme),Ou=$u??Iu,Mu=lo??Pu,Du=useSystemColorMode(),Lu=getThemeConfig(Mu),Bu=Ou==="auto"?Du:Ou,ju={...Bu==="dark"?Lu.themeStyles.dark:Lu.themeStyles.light,...Ru?.[Bu]},Fu=ju.backgroundColor??"";return jsxRuntimeExports.jsx(ThemedJupyterReactTheme,{colormode:Bu,theme:Lu.primerTheme,backgroundColor:Fu,loadJupyterLabCss:!1,style:{...ju,color:"var(--fgColor-default)",fontSize:"var(--text-body-size-medium)",display:"contents"},children:Au})}const AI_AGENTS_API_PREFIX="/api/ai-agents/v1",isDevTraceEnabled=()=>{try{return!1}catch{return!1}},logApprovalTrace=(Au,lo)=>{isDevTraceEnabled()&&console.debug(`[approval-trace] ${Au}`,lo)},normalizeAgentId=Au=>(Au??"").trim().toLowerCase(),normalizeToolName=Au=>Au.replace(/[-_]/g,"").toLowerCase(),normalizeSkillApprovalId=Au=>{const lo=Au.indexOf(":");return lo<=0?Au:Au.slice(0,lo)},stableStringify=Au=>Au===null||typeof Au!="object"?JSON.stringify(Au):Array.isArray(Au)?`[${Au.map($u=>stableStringify($u)).join(",")}]`:`{${Object.entries(Au).sort(([$u],[Ru])=>$u.localeCompare(Ru)).map(([$u,Ru])=>`${JSON.stringify($u)}:${stableStringify(Ru)}`).join(",")}}`,approvalSignature=(Au,lo)=>`${normalizeToolName(Au)}::${stableStringify(lo??{})}`,normalizeAiAgentsBaseUrl=Au=>{const lo=Au.replace(/\/$/,"");return lo.endsWith(AI_AGENTS_API_PREFIX)?lo.slice(0,-AI_AGENTS_API_PREFIX.length):lo},toWsUrl=(Au,lo,$u)=>{try{const Ru=new URL(Au);return Ru.protocol=Ru.protocol==="https:"?"wss:":"ws:",Ru.pathname=lo,$u?Ru.searchParams.set("token",$u):Ru.search="",Ru.toString()}catch{return null}},normalizeApprovalPayload=Au=>{const lo=typeof Au.id=="string"&&Au.id||typeof Au.approval_id=="string"&&Au.approval_id||typeof Au.approvalId=="string"&&Au.approvalId||"",$u=typeof Au.tool_name=="string"&&Au.tool_name||typeof Au.toolName=="string"&&Au.toolName||"";if(!lo||!$u)return null;const Ru=(Au.tool_args&&typeof Au.tool_args=="object"?Au.tool_args:Au.toolArgs&&typeof Au.toolArgs=="object"?Au.toolArgs:void 0)??{};return{id:lo,tool_name:$u,tool_args:Ru,tool_call_id:typeof Au.tool_call_id=="string"&&Au.tool_call_id||typeof Au.toolCallId=="string"&&Au.toolCallId||void 0,note:typeof Au.note=="string"&&Au.note||typeof Au.message=="string"&&Au.message||void 0,status:typeof Au.status=="string"&&Au.status||"pending",agent_id:typeof Au.agent_id=="string"&&Au.agent_id||typeof Au.agentId=="string"&&Au.agentId||void 0,created_at:typeof Au.created_at=="string"&&Au.created_at||typeof Au.createdAt=="string"&&Au.createdAt||void 0,updated_at:typeof Au.updated_at=="string"&&Au.updated_at||typeof Au.updatedAt=="string"&&Au.updatedAt||void 0}},statusFromApprovalEvent=Au=>{if(Au==="tool_approval_created")return"pending";if(Au==="tool_approval_approved")return"approved";if(Au==="tool_approval_rejected")return"rejected";if(Au==="tool_approval_deleted")return"deleted"},RESOLVED_TOOL_CALL_SUPPRESSION_MS=15e3,isApprovalForAgent=(Au,lo)=>{if(!lo)return!0;if(!Au.agent_id)return!1;if(Au.agent_id===lo)return!0;const $u=normalizeAgentId(Au.agent_id),Ru=normalizeAgentId(lo);return $u.includes(Ru)||Ru.includes($u)};function isToolCallOnlyPrompt(Au){const lo=Au.toLowerCase();return/tool\s*call\s*only/.test(lo)||/use\s+(?:a\s+)?tool\s+call\s+only/.test(lo)}function formatToolResultFallback(Au){if(typeof Au=="string")return Au;if(typeof Au=="number"||typeof Au=="boolean"||Au===null)return String(Au);try{const lo=JSON.stringify(Au,null,2);return lo.length>2e3?`${lo.slice(0,2e3)}
|
|
3673
|
-
...`:lo}catch{return"Tool completed successfully."}}function extractChatMessagesFromFullContext(Au){return Au?(Array.isArray(Au.messages)?Au.messages:[]).map(($u,Ru)=>{const Iu=String($u.role||"").toLowerCase(),Pu=typeof $u.timestamp=="string"&&$u.timestamp.length>0?$u.timestamp:new Date().toISOString(),Ou=new Date(Pu),Mu=Number.isNaN(Ou.getTime())?new Date:Ou,Du=typeof $u.content=="string"?$u.content:JSON.stringify($u.content??""),Lu=!!$u.isToolCall,Bu=!!$u.isToolResult,ju=typeof $u.toolCallId=="string"&&$u.toolCallId.length>0?$u.toolCallId:void 0,Fu=typeof $u.toolName=="string"&&$u.toolName.length>0?$u.toolName:void 0;if(Lu){let zu={};if(Du)try{const Hu=JSON.parse(Du);Hu&&typeof Hu=="object"&&!Array.isArray(Hu)&&(zu=Hu)}catch{zu={}}const Uu=ju||`history-tc-${Ru}`;return{id:`history-toolcall-${Ru}-${Pu}`,role:"assistant",content:"",createdAt:Mu,toolCalls:[{type:"tool-call",toolCallId:Uu,toolName:Fu||"tool",args:zu,status:"completed"}]}}return Bu||Iu==="tool"?{id:`history-toolresult-${Ru}-${Pu}`,role:"tool",content:Du,createdAt:Mu,metadata:{toolCallId:ju,toolName:Fu}}:Iu!=="user"&&Iu!=="assistant"?null:{id:`history-${Iu}-${Ru}-${Pu}`,role:Iu,content:Du,createdAt:Mu}}).filter($u=>$u!==null):[]}function parseEnabledMcpToolsByServer(Au){if(!Au||typeof Au!="object")return null;const lo=Au.enabled_tools_by_server;if(lo==null)return new Map;if(typeof lo!="object")return new Map;const $u=new Map;for(const[Ru,Iu]of Object.entries(lo)){if(!Array.isArray(Iu))continue;const Ou=Iu.filter(Mu=>typeof Mu=="string"&&Mu.length>0).map(Mu=>{const Du=Mu.indexOf("__");return Du>=0?Mu.slice(Du+2):Mu});$u.set(Ru,new Set(Ou))}return $u}function parseApprovedMcpToolsByServer(Au){if(!Au||typeof Au!="object")return null;const lo=Au.approved_tools_by_server;if(lo==null)return new Map;if(typeof lo!="object")return new Map;const $u=new Map;for(const[Ru,Iu]of Object.entries(lo)){if(!Array.isArray(Iu))continue;const Ou=Iu.filter(Mu=>typeof Mu=="string"&&Mu.length>0).map(Mu=>{const Du=Mu.indexOf("__");return Du>=0?Mu.slice(Du+2):Mu});$u.set(Ru,new Set(Ou))}return $u}const WELCOME_AT=new Date(0);function ChatBase(Au){const{agentRuntimeConfig:lo,protocol:$u,useStore:Ru=!0,disableInternalJupyterTheme:Iu=!1,themeVariant:Pu,colorMode:Ou,themeOverrides:Mu}=Au,Bu=lo?{type:(typeof $u=="string"?$u:void 0)||lo.protocol||"vercel-ai",endpoint:lo.url,authToken:lo.authToken,agentId:lo.agentId,enableConfigQuery:!0,configEndpoint:`${lo.url}/api/v1/config`}:typeof $u=="object"?$u:void 0,ju=lo?!1:Ru,Fu=reactExports.useContext(QueryClientContext),zu={...Au,protocol:Bu,useStore:ju},Uu=jsxRuntimeExports.jsx(ChatBaseInner,{...zu}),Hu=Iu?Uu:jsxRuntimeExports.jsx(ThemedChatBoundary,{themeVariant:Pu,colorMode:Ou,themeOverrides:Mu,children:Uu});return Fu?Hu:jsxRuntimeExports.jsx(QueryClientProvider,{client:internalQueryClient,children:Hu})}function ChatBaseInner({title:Au,subtitle:lo,showHeader:$u=!1,showTokenUsage:Ru=!0,showContextRing:Iu=!1,showLoadingIndicator:Pu=!0,showErrors:Ou=!0,showInput:Mu=!0,showModelSelector:Du=!0,showToolsMenu:Lu=!0,showSkillsMenu:Bu=!0,disableInputPrompt:ju=!1,promptVariant:Fu,mentionableAgents:zu,promptCommands:Uu,showAgentsMenu:Hu=!0,agents:Vu,selectedAgentId:Gu,onSelectAgent:Wu,disabled:Ku,disableReason:Ju,overlay:Yu,launching:Xu=!1,launchingMessage:ed,autoConnect:td=!0,codemodeEnabled:nd=!1,onToggleCodemode:od,initialModel:sd,availableModels:ad,mcpServers:pd,initialSkills:gd,className:xd,loadingState:yd,headerActions:bd,kernelIndicatorState:wd,kernelIndicatorPlacement:kd="left",kernel:cd,kernelEnvironmentName:dd,kernelCpu:md,kernelMemory:ld,kernelGpu:hd,themeVariant:vd,colorMode:Sd,chatViewMode:Td,onChatViewModeChange:Rd,disabledViewModes:Od,useStore:Bd=!0,protocol:Ed,onSendMessage:Ad,onSendReady:Id,onLoadingChange:Wd,onContextSnapshot:Dd,enableStreaming:Hd=!1,brandIcon:nh,avatarConfig:Xd,headerButtons:mh,showPoweredBy:uh=!1,poweredByProps:Sh,emptyState:yh,renderHeader:eh,showTurnFooter:rh=!0,notebookToolSurfacesId:dh,footerContent:Dh,welcome:Vd,trailingContent:Ud,voice:$d,voiceSpeaking:Pd=!1,onStopSpeaking:Gd,showInformation:Nd=!1,onInformationClick:Kd,headerContent:Qd,children:gh,borderRadius:xh,backgroundColor:wh,border:Kh,boxShadow:Md,compact:_d=!1,placeholder:qd,description:Fd="Start a conversation with the AI agent.",onStateUpdate:sh,onNewChat:Eh,onClear:Ch,onMessagesChange:kh,onItemsChange:Ph,onDisplayItemsChange:zh,autoFocus:jh=!1,suggestions:Zh,submitOnSuggestionClick:Oh=!0,hideMessagesAfterToolUI:np=!1,focusTrigger:rp,frontendTools:dp,enableEphemeralNotebook:gp=!1,initialEphemeralNotebookOpen:Qh=!0,onEphemeralNotebookOpenChange:xp,enableEphemeralDocument:ip=!1,initialEphemeralSurfaceMode:cp,onEphemeralSurfaceModeChange:Hh,collapsed:Fh=!1,onExpandFromCollapsed:Xh,ephemeralNotebookToolbar:zf,ephemeralNotebookToolbarExtraItems:Rp,ephemeralDocumentToolbarExtraItems:Rh,ephemeralNotebookCollaborationProvider:Bh,ephemeralNotebookCollaborationDocumentId:hf,ephemeralDocumentCollaboration:jp,ephemeralRuntimeOverride:Qp,onToolCallStart:ef,onToolCallComplete:ep,inspector:Vp,onAuthorizationRequired:Uf,connectedIdentities:om,runtimeId:Fp,thread:Tf,historyEndpoint:Kf,historyAuthToken:bp,pendingPrompt:Ip,contextSnapshot:Sp,mcpStatusData:Gp,sandboxStatusData:Nf,showToolApprovalBanner:Wp=!0,pendingApprovals:zp,onApproveApproval:yp,onRejectApproval:mm}){const of=useChatWords();reactExports.useEffect(()=>{setupPrimerPortals()},[]);const gm=useChatAvailability(),Pf=Ku??gm.disabled,Xm=Ju??gm.disableReason,{theme:_f}=useThemeStore(),km=getColorPalette(_f,"dark").textLight,vm=useAgentRuntimeStore(jd=>jd.approvals),kf=useAgentRuntimeStore(jd=>jd.historyVersion),Lh=useAgentRuntimeStore(jd=>jd.mcpStatus),zd=Gp??Lh,ih=typeof Ed=="object"?Ed:void 0,Nh=useCoreStore(jd=>jd.configuration?.aiAgentsUrl),fh=ih?.agentId||Fp,qh=Fp||fh,sp=ih?.authToken,Dp=reactExports.useRef(`ephemeral-notebook-${Math.random().toString(36).slice(2,10)}`),kp=Fp||ih?.agentId||fh,sf=hf||(kp?`ephemeral-notebook-${kp}`:Dp.current),_p=useAgentRuntimeStore(jd=>jd.getEphemeralNotebookModel(sf)),Of=useAgentRuntimeStore(jd=>jd.setEphemeralNotebookModel),Jp=reactExports.useCallback(jd=>{Of(sf,jd)},[sf,Of]),Zf=jp?.roomId||(kp?`ephemeral-document-${kp}`:`ephemeral-document-${Dp.current}`),Yf=useAgentRuntimeStore(jd=>jd.getEphemeralDocumentModel(Zf)),xf=useAgentRuntimeStore(jd=>jd.setEphemeralDocumentModel),Am=reactExports.useCallback(jd=>{xf(Zf,jd)},[Zf,xf]),$m=cp??(gp&&Qh?"notebook":"none"),[wm,Lf]=reactExports.useState($m),Mf=reactExports.useCallback(jd=>{Lf(jd),Hh?.(jd),xp?.(jd==="notebook")},[Hh,xp]),im=gp&&wm==="notebook",Af=ip&&wm==="document",vp=im||Af,vf=vp&&Fh,$f=vf?{key:"ephemeral-surface",type:"custom",order:900,render:()=>jsxRuntimeExports.jsx(EphemeralSurfaceControl,{mode:wm,onChange:Mf,enableNotebook:gp,enableDocument:ip,enableChatOnly:!1})}:null,cm=$f?[...Rp??[],$f]:Rp,bm=$f?[...Rh??[],$f]:Rh,[Wh,Bp]=reactExports.useState(null);reactExports.useEffect(()=>{if(!im){Bp(null);return}const jd=()=>notebookStore.getState().selectNotebook(sf)?.adapter?.kernel??null,Zd=()=>{const ah=jd();Bp(bh=>bh?.id===ah?.id?bh:ah)};Zd();const Yd=window.setInterval(Zd,750),lh=notebookStore.subscribe(Zd);return()=>{window.clearInterval(Yd),lh()}},[im,sf]);const[Xp,Sf]=reactExports.useState(null),bf=reactExports.useCallback(jd=>{Sf(Zd=>Zd?.id===jd?.id?Zd:jd)},[]);reactExports.useEffect(()=>{Af||Sf(null)},[Af]);const wf=vp&&isFloatingChatViewMode(Td),um=Td==="floating-small"||Td==="floating-draggable",Up=useNotebookTools(sf),[Jf,Xf]=reactExports.useState([]),af=reactExports.useCallback(jd=>{Xf(jd)},[]),Yh=reactExports.useMemo(()=>im?[...dp||[],...Up]:Af?[...dp||[],...Jf]:dp,[im,Af,dp,Up,Jf]),Ep=reactExports.useMemo(()=>normalizeAiAgentsBaseUrl(Nh||DEFAULT_SERVICE_URLS.AI_AGENTS),[Nh]),pf=reactExports.useRef(null),Hf=reactExports.useRef(new Map),Df=reactExports.useCallback((jd,Zd,Yd)=>{const lh=pf.current;if(!lh||lh.readyState!==WebSocket.OPEN)return logApprovalTrace("send_decision_skipped_ws_not_ready",{approvalId:jd,approved:Zd,wsReadyState:lh?.readyState}),!1;try{return logApprovalTrace("send_decision",{approvalId:jd,approved:Zd,hasNote:!!Yd}),lh.send(JSON.stringify({type:"tool_approval_decision",approvalId:jd,approved:Zd,...Yd?{note:Yd}:{}})),!0}catch{return logApprovalTrace("send_decision_failed",{approvalId:jd,approved:Zd}),!1}},[]),zm=reactExports.useCallback(()=>{const jd=pf.current;if(!jd||jd.readyState!==WebSocket.OPEN)return!1;try{return jd.send(JSON.stringify({type:"tool-approvals-history"})),logApprovalTrace("request_history",{}),!0}catch{return!1}},[]),Um=reactExports.useCallback(jd=>{jd&&(Hf.current.set(jd,Date.now()+RESOLVED_TOOL_CALL_SUPPRESSION_MS),logApprovalTrace("suppress_pending_for_tool_call",{toolCallId:jd,windowMs:RESOLVED_TOOL_CALL_SUPPRESSION_MS}))},[]),X0=reactExports.useCallback(jd=>{if(!jd)return!1;const Zd=Hf.current.get(jd);return Zd?Zd<Date.now()?(Hf.current.delete(jd),!1):!0:!1},[]),Rm=reactExports.useCallback((jd,Zd,Yd)=>{window.setTimeout(()=>{if(!agentRuntimeStore.getState().approvals.some(bh=>bh.id===jd&&bh.status==="pending"))return;const ah=Df(jd,Zd,Yd);logApprovalTrace("retry_send_decision",{approvalId:jd,approved:Zd,sent:ah}),ah&&zm()},500)},[zm,Df]),Ag=reactExports.useMemo(()=>zp||vm.filter(jd=>jd.status==="pending"&&isApprovalForAgent(jd,fh)).map(jd=>({id:jd.id,toolName:jd.tool_name,toolDescription:jd.note??void 0,args:jd.tool_args??{},agentId:jd.agent_id??"",requestedAt:jd.created_at??new Date().toISOString()})),[zp,vm,fh]),r1=reactExports.useCallback((jd,Zd)=>{const Yd=agentRuntimeStore.getState().approvals.find(Vh=>Vh.id===jd),lh=Yd?.tool_name;if(!lh)return;const bh=(()=>{if(lh.startsWith("skill:")){const Uh=lh.slice(6);return Uh?normalizeSkillApprovalId(Uh):null}if(!new Set(["run_skill_script","load_skill","read_skill_resource"]).has(lh))return null;const hp=Yd?.tool_args??{},Gh=hp.skill_name??hp.skill??hp.name;return typeof Gh!="string"||!Gh?null:normalizeSkillApprovalId(Gh)})();if(bh){Rg(hp=>{const Gh=new Map(hp);return Gh.set(bh,Zd),Gh}),agentRuntimeStore.getState().sendRawMessage({type:Zd?"skill_approve":"skill_unapprove",skillId:bh},fh)||console.warn("[ChatBase] skill_approve persistence dropped: websocket not ready");return}const Ah=lh.indexOf("__");if(Ah!==-1){const Vh=lh.slice(0,Ah),hp=lh.slice(Ah+2);agentRuntimeStore.getState().sendRawMessage({type:"mcp_server_tool_approve",serverId:Vh,toolName:hp,approved:Zd},fh)||console.warn("[ChatBase] mcp_server_tool_approve persistence dropped: websocket not ready")}},[fh]),Q0=reactExports.useCallback(async(jd,Zd,Yd)=>{const ah=agentRuntimeStore.getState().approvals.find(Vh=>Vh.id===jd)?.tool_call_id??Yd;Um(ah);const bh=Df(jd,!0,Zd);bh||console.warn("[ChatBase] ai-agents tool_approval_decision not sent: websocket not ready");const Ah=agentRuntimeStore.getState().sendDecision(jd,!0,Zd,ah,fh);Ah?r1(jd,!0):console.warn("[ChatBase] tool_approval_decision dropped: websocket not ready"),(bh||Ah)&&agentRuntimeStore.getState().removeApproval(jd),zm(),Rm(jd,!0,Zd),await yp?.(jd,Zd)},[fh,Um,yp,r1,Rm,zm,Df]),D0=reactExports.useCallback(async(jd,Zd,Yd)=>{const ah=agentRuntimeStore.getState().approvals.find(Vh=>Vh.id===jd)?.tool_call_id??Yd;Um(ah);const bh=Df(jd,!1,Zd);bh||console.warn("[ChatBase] ai-agents tool_approval_decision not sent: websocket not ready");const Ah=agentRuntimeStore.getState().sendDecision(jd,!1,Zd,ah,fh);Ah||console.warn("[ChatBase] tool_approval_decision dropped: websocket not ready"),(bh||Ah)&&agentRuntimeStore.getState().removeApproval(jd),zm(),Rm(jd,!1,Zd),await mm?.(jd,Zd)},[fh,Um,mm,Rm,zm,Df]),n1=reactExports.useRef(null),eg=reactExports.useCallback(jd=>{const Zd=agentRuntimeStore.getState(),Yd=new Set([jd.id]),ah=!!jd.tool_name?approvalSignature(jd.tool_name,jd.tool_args??{}):null;for(const bh of Zd.approvals){if(bh.status!=="pending"||!isApprovalForAgent(bh,fh))continue;if(bh.id===jd.id){Yd.add(bh.id);continue}if(jd.tool_call_id&&bh.tool_call_id&&bh.tool_call_id===jd.tool_call_id){Yd.add(bh.id);continue}if(!ah||!bh.tool_name)continue;approvalSignature(bh.tool_name,bh.tool_args??{})===ah&&Yd.add(bh.id)}for(const bh of Yd)Zd.removeApproval(bh)},[fh]);reactExports.useEffect(()=>{if(!Wp||zp||!sp)return;const jd=toWsUrl(Ep,`${AI_AGENTS_API_PREFIX}/ws`,sp);if(!jd)return;let Zd=!1;const Yd=new WebSocket(jd);return pf.current=Yd,Yd.onopen=()=>{logApprovalTrace("ws_open_request_history",{activeAgentId:fh}),Yd.send(JSON.stringify({type:"tool-approvals-history"}))},Yd.onmessage=lh=>{try{const ah=JSON.parse(String(lh.data)),bh=[],Ah=typeof ah.type=="string"?ah.type:void 0,Vh=typeof ah.event=="string"?ah.event:void 0;if(Ah==="tool-approvals-history"){const Uh=(ah.data&&typeof ah.data=="object"?ah.data:{}).approvals;if(Array.isArray(Uh))for(const Jh of Uh)Jh&&typeof Jh=="object"&&bh.push(Jh)}else if(Vh?.startsWith("tool_approval_")){const Gh=ah.data&&typeof ah.data=="object"?ah.data:ah.payload&&typeof ah.payload=="object"?ah.payload:null;if(Gh){const Uh=statusFromApprovalEvent(Vh);logApprovalTrace("recv_tool_approval_event",{event:Vh,approvalId:typeof Gh.id=="string"?Gh.id:typeof Gh.approval_id=="string"?Gh.approval_id:void 0,status:typeof Gh.status=="string"?Gh.status:Uh}),bh.push(Uh&&typeof Gh.status!="string"?{...Gh,status:Uh}:Gh)}}if(bh.length===0)return;const hp=agentRuntimeStore.getState();for(const Gh of bh){let Uh=normalizeApprovalPayload(Gh);if(!Uh){const up=typeof Gh.id=="string"&&Gh.id||typeof Gh.approval_id=="string"&&Gh.approval_id||typeof Gh.approvalId=="string"&&Gh.approvalId||"",fp=typeof Gh.status=="string"&&Gh.status||"";if(up&&fp&&fp!=="pending"){const tf=hp.approvals.find(Vf=>Vf.id===up);tf&&(Uh={...tf,status:fp})}}if(!Uh)continue;const Jh=Uh.agent_id||!fh?Uh:{...Uh,agent_id:fh};if(isApprovalForAgent(Jh,fh)){if(Jh.status==="pending"&&X0(Jh.tool_call_id)){logApprovalTrace("drop_transient_pending",{approvalId:Jh.id,toolCallId:Jh.tool_call_id,status:Jh.status});continue}logApprovalTrace("apply_tool_approval_update",{approvalId:Jh.id,status:Jh.status,agentId:Jh.agent_id,activeAgentId:fh}),Jh.status==="pending"?hp.upsertApproval(Jh):(eg(Jh),n1.current?.(Jh,Jh.status==="approved",Jh.note??void 0))}}}catch{}},Yd.onclose=()=>{Zd||(pf.current=null)},Yd.onerror=()=>{pf.current=null},()=>{Zd=!0,pf.current=null,Yd.close()}},[Wp,zp,Ep,sp,fh,X0,eg]);const ap=typeof Ed=="object"?Ed:void 0,J1=ap?JSON.stringify(ap):"",$g="agent-runtimes",dm=useChatStore(jd=>jd.clearMessages),N0=ap?.type==="a2a",[Rf,Ap]=reactExports.useState([]),[u0,sm]=reactExports.useState(null),[X1,tg]=reactExports.useState(!1),[Im,x0]=reactExports.useState(!1),[rg,d0]=reactExports.useState(),[Q1,Hm]=reactExports.useState(!1),[ng,Pm]=reactExports.useState(null),[Em,L0]=reactExports.useState("");reactExports.useEffect(()=>{if(!cd){d0(void 0);return}d0(cd.status);const jd=(Zd,Yd)=>{d0(Yd)};return cd.statusChanged.connect(jd),()=>{cd.statusChanged.disconnect(jd)}},[cd]);const[h0,yf]=reactExports.useState(!qh),[Qm,B0]=reactExports.useState(0),j0=reactExports.useRef(new Map),og=reactExports.useRef(emptyUiModel()),S0=reactExports.useRef(new Set),[e0,b1]=reactExports.useState(!1),Mh=reactExports.useRef(null),Cp=Ip&&[Fp||Kf||ap?.endpoint||ap?.agentId,Ip].filter(Boolean).join("::"),[ff,hm]=reactExports.useState(""),[Kp,Om]=reactExports.useState(new Map),[p0,am]=reactExports.useState(new Map),[w0,y1]=reactExports.useState([]),qm=useAgentRuntimeWsState(),ig=!!ap?.enableConfigQuery&&td,Pp=useConfig(ig,ap?.configEndpoint,ap?.authToken,ap?.agentId),Ef=useSkills(ig&&Bu,ap?.configEndpoint,ap?.authToken),{enableSkill:Vm,disableSkill:F0,approveSkill:ev,unapproveSkill:tv}=useSkillActions(fh),[rv,Rg]=reactExports.useState(new Map);reactExports.useEffect(()=>{Rg(new Map)},[fh]);const o1=reactExports.useMemo(()=>{const jd=new Set;for(const Zd of Ef.data?.skills??[])(Zd.status==="enabled"||Zd.status==="loaded")&&jd.add(Zd.id);return jd},[Ef.data]);reactExports.useEffect(()=>{if(!fh||ym.current.has(fh))return;const jd=Ef.data?.skills??[];if(jd.length===0)return;if(jd.some(ah=>ah.status==="enabled"||ah.status==="loaded")){ym.current.add(fh);return}const Yd=jd.filter(ah=>ah.status==="available").map(ah=>ah.id).filter(Boolean);if(Yd.length===0){ym.current.add(fh);return}Yd.every(ah=>Vm(ah))&&ym.current.add(fh)},[fh,Ef.data,Vm]);const z0=reactExports.useMemo(()=>{const jd=new Set;for(const Zd of Ef.data?.skills??[])Zd.approved===!0&&jd.add(Zd.id);return rv.forEach((Zd,Yd)=>{Zd?jd.add(Yd):jd.delete(Yd)}),jd},[rv,Ef.data]),_1=reactExports.useMemo(()=>{const jd=Pp.data?.builtinTools??[],Zd=ap?.options?.frontendTools??[],Yd=new Set(jd.map(ah=>ah.name)),lh=[...Yh??[],...Zd].filter(ah=>Yd.has(ah.name)?!1:(Yd.add(ah.name),!0)).map(ah=>({id:ah.name,name:ah.name}));return{runtime:jd,frontend:lh}},[Pp.data?.builtinTools,Yh,ap?.options]),E0=reactExports.useMemo(()=>Vu??(fh?[{id:fh,name:Au||fh,description:lo||Fd}]:[]),[Vu,fh,Au,lo,Fd]),Ig=typeof ap?.options?.model=="string"?(ap?.options).model:void 0,U0=reactExports.useMemo(()=>{const jd=ad||Pp.data?.models||(Pp.isError?[]:void 0);return offeredModels(jd,()=>{const Zd=Object.values(AI_MODEL_CATALOGUE).filter(Yd=>Yd.available&&isChatModel(Yd)).map(Yd=>({id:Yd.id,name:Yd.name,provider:Yd.provider}));return Zd.length>0?Zd:Ig?[{id:Ig,name:Ig,provider:"inference"}]:[]})},[ad,Pp.data?.models,Pp.isError,Ig]),sg=reactExports.useMemo(()=>zu??E0.map(jd=>({name:jd.name,description:jd.description,icon:jd.icon,disabled:jd.id===(Gu??E0[0]?.id),disabledReason:`You are already talking to ${jd.name}`})),[zu,E0,Gu]),Pg=useContextSnapshot(ig&&Ru,ap?.configEndpoint,ap?.agentId,ap?.authToken),nv=reactExports.useMemo(()=>ap?.enableConfigQuery?void 0:{totalTokens:u0?.totalTokens??0,contextWindow:2e5,sumResponseInputTokens:u0?.sessionInput??0,sumResponseOutputTokens:u0?.sessionOutput??0,systemPromptTokens:0,userMessageTokens:0,assistantMessageTokens:0,toolTokens:0,toolCallTokens:0,toolReturnTokens:0,historyToolCallTokens:0,historyToolReturnTokens:0,currentToolCallTokens:0,currentToolReturnTokens:0,turnUsage:{inputTokens:u0?.turnInput??0,outputTokens:u0?.turnOutput??0,requests:0,toolCalls:0,toolNames:[],durationSeconds:0},sessionUsage:{inputTokens:u0?.sessionInput??0,outputTokens:u0?.sessionOutput??0,requests:0,toolCalls:0,turns:0,durationSeconds:0}},[u0,ap?.enableConfigQuery]),ov=reactExports.useRef(fh),H0=reactExports.useRef(null),Og=Pg.data,iv=reactExports.useRef(Og);iv.current=Og,reactExports.useEffect(()=>{ov.current!==fh&&(ov.current=fh,sm(null),H0.current=iv.current??null)},[fh]);const qv=Og&&Og!==H0.current?Og:void 0,x1=Sp??qv??nv;reactExports.useEffect(()=>{Dd?.(x1)},[x1,Dd]);const Vv=useSandbox(ig&&$u,ap?.configEndpoint,ap?.authToken,ap?.agentId),Mm=reactExports.useRef(null),sv=reactExports.useRef(null),lf=reactExports.useRef(new Map),Cm=reactExports.useRef(0),Qf=reactExports.useRef(null),i1=reactExports.useRef(new Set),ym=reactExports.useRef(new Set),ag=reactExports.useRef(new Set),C0=reactExports.useRef(!1),Mg=reactExports.useRef(np);Mg.current=np;const f0=reactExports.useRef(Tf?.id||generateMessageId()),S1=reactExports.useRef(Tf),q0=reactExports.useRef(Tf?.messages.length?Tf.id:null),av=reactExports.useCallback(()=>{const jd=f0.current;q0.current!==jd&&(q0.current=jd,S1.current?.onStarted?.(jd))},[]),V0=reactExports.useRef(null),m0=reactExports.useRef([]),lv=reactExports.useRef(new Set),pm=reactExports.useRef([]),s1=ap?.uiSocket,t0=reactExports.useRef(ap?.authToken);t0.current=ap?.authToken;const w1=ap?.uiFiles,Dg=reactExports.useCallback(jd=>w1?uploadFile(jd,{url:w1,scope:f0.current,token:t0.current}):Promise.reject(new Error("This conversation takes no file.")),[w1]),r0=reactExports.useCallback(jd=>{const Zd=Yd=>{try{return withUiOp(Yd,jd)}catch(lh){return console.error("[ChatBase] reactor.ui op not applied:",lh),Yd}};if(Ap(Yd=>Zd(Yd)),Bd){const Yd=useChatStore.getState();Yd.setMessages(Zd(Yd.messages))}},[Bd]),E1=reactExports.useCallback((jd,Zd)=>{if(Zd){if(jd.op==="window")return;if((jd.op==="show"||jd.op==="ask")&&isStepDisplay(jd.body)){lv.current.add(jd.body.id);return}if((jd.op==="patch"||jd.op==="append")&&lv.current.has(jd.id))return}let Yd;try{Yd=routeUiOp(jd,og.current,S0.current)}catch(ah){console.error("[ChatBase] reactor.ui op not applied:",ah);return}og.current=Yd.steps;const lh=Yd.routed;if(lh.to==="window")tellLoopWindow(lh.data);else if(lh.to==="step"){const ah=lh.step;Ap(bh=>withLoopStep(bh,ah))}else if(lh.to==="element")S0.current.add(lh.change.id),applyLoopElement(lh.change);else if(placeable(pm.current,lh.op))r0(lh.op);else{const ah=lh.op.op==="show"||lh.op.op==="ask"?lh.op.body.data?.message_id:void 0;if(Zd&&typeof ah=="string"){const bh={id:ah,role:"assistant",content:"",createdAt:new Date};pm.current=[...pm.current,bh],Ap(Ah=>Ah.some(Vh=>Vh.id===ah)?Ah:[...Ah,bh]),Bd&&useChatStore.getState().addMessage(bh),r0(lh.op)}else m0.current.push(lh.op)}},[r0,Bd]),cv=reactExports.useRef(E1);cv.current=E1,reactExports.useEffect(()=>{if(pm.current=Rf,m0.current.length===0)return;const jd=m0.current.splice(0);let Zd=Rf;for(const Yd of jd){if(!placeable(Zd,Yd)){m0.current.push(Yd);continue}try{Zd=withUiOp(Zd,Yd)}catch{}r0(Yd)}},[Rf,r0]);const C1=reactExports.useCallback(()=>{if(!s1)return null;const jd=f0.current,Zd=V0.current;if(Zd&&Zd.scope===jd)return Zd.socket;Zd?.socket.close(),og.current=emptyUiModel(),S0.current=new Set,m0.current=[],lv.current=new Set;const Yd=new UiSocket({url:s1,scope:jd,token:()=>t0.current??"",onOp:(lh,ah,bh)=>cv.current(lh,bh),onStatus:(lh,ah)=>{(lh==="refused"||lh==="gone")&&console.error(`[ChatBase] ui socket ${lh}: ${ah??""}`)}});return V0.current={socket:Yd,scope:jd},Yd.connect(),Yd},[s1]),T1=reactExports.useRef(C1);T1.current=C1,reactExports.useEffect(()=>(Tf?.messages.length&&T1.current(),()=>{V0.current?.socket.close(),V0.current=null}),[]);const Tm=reactExports.useRef(null),lg=reactExports.useRef(null),Dm=reactExports.useRef(null),cg=reactExports.useRef(null),T0=reactExports.useRef(!1),Nm=reactExports.useRef(om);Nm.current=om;const _m=reactExports.useRef(Yh);_m.current=Yh;const k0=reactExports.useRef(ef);k0.current=ef;const n0=reactExports.useRef(ep);n0.current=ep;const g0=useAgentInspectorTracer(),Lm=Vp??g0,uv=reactExports.useRef("Agent");uv.current=typeof Au=="string"&&Au||fh||"Agent";const Gm=reactExports.useRef(null);Lm&&Gm.current?.tracer!==Lm?Gm.current={tracer:Lm,recorder:chatSpanRecorder(Lm,()=>uv.current,{frontendTools:()=>(_m.current??[]).map(jd=>jd.name)})}:Lm||(Gm.current=null);const Ng=reactExports.useRef(""),k1=reactExports.useRef(null);reactExports.useEffect(()=>{let jd=agentRuntimeStore.getState().toolDecisionRequest?.seq??0;return agentRuntimeStore.subscribe(Zd=>Zd.toolDecisionRequest,Zd=>{if(!Zd||Zd.seq===jd)return;jd=Zd.seq;const Yd=k1.current;if(!Yd)return;const lh=Ah=>(Ah??"").toLowerCase().replace(/[-_]/g,""),ah=Array.from(lf.current.values()),bh=ah.find(Ah=>Ah.result?.approvalId===Zd.approvalId)??ah.find(Ah=>lh(Ah.toolName)===lh(Zd.toolName)&&(Ah.status==="executing"||Ah.status==="inProgress"));bh&&Yd(bh.toolCallId,{type:"tool-approval-decision",approved:Zd.approved,approvalId:Zd.approvalId,toolName:bh.toolName})})},[]);const qf=reactExports.useCallback((jd,Zd,Yd)=>{if(!jd?.id||i1.current.has(jd.id))return!1;let lh=jd.tool_call_id;if(!lh)for(const[bh,Ah]of lf.current.entries()){if(Ah.status!=="inProgress"&&Ah.status!=="executing")continue;const Vh=approvalSignature(Ah.toolName,Ah.args??{}),hp=approvalSignature(jd.tool_name,jd.tool_args??{});if(Vh===hp){lh=bh;break}}if(!lh)return!1;const ah=lf.current.get(lh);return!ah||ah.status!=="inProgress"&&ah.status!=="executing"?!1:(i1.current.add(jd.id),k1.current?.(lh,{type:"tool-approval-decision",approved:Zd,approvalId:jd.id,toolName:jd.tool_name||ah.toolName,_fromServerEcho:!0,_alreadyDispatched:!0,...Yd?{message:Yd}:{}}),!0)},[fh]);n1.current=qf;const mf=!!(ap?.endpoint&&/\/api\/runtimes\/v1\/agent-nodes\/[^/]+\/ag-ui\/?$/.test(ap.endpoint)),$p=ap?.configEndpoint?ap.configEndpoint.replace(/\/api\/v1\/(config|configure)\/?$/,""):ap?.endpoint?.replace(/\/api\/v1\/.*$/,"")??"";useAgentRuntimeWebSocket({enabled:!!ap&&!!$p&&!mf,baseUrl:$p,authToken:ap?.authToken,agentId:ap?.agentId,onMessage:jd=>{if(jd.type!=="tool_approval_created"&&jd.type!=="tool_approval_approved"&&jd.type!=="tool_approval_rejected")return;const Zd=jd.payload;if(Zd){if(jd.type==="tool_approval_created"){isApprovalForAgent(Zd,fh)&&agentRuntimeStore.getState().upsertApproval(Zd);return}eg(Zd),qf(Zd,jd.type==="tool_approval_approved",Zd.note??void 0)}}});const Bm=reactExports.useCallback(jd=>{if(!pd)return!0;const Zd=jd.isConfig===!1?"catalog":"config";return pd.some(Yd=>Yd.id===jd.id&&Yd.origin===Zd)},[pd]);reactExports.useEffect(()=>{if(jh&&Dm.current){const jd=setTimeout(()=>Dm.current?.focus(),100);return()=>clearTimeout(jd)}},[jh]),reactExports.useEffect(()=>{if(rp!==void 0&&rp>0&&Dm.current){const jd=setTimeout(()=>Dm.current?.focus(),150);return()=>clearTimeout(jd)}},[rp]);const jm=reactExports.useRef(!1);reactExports.useEffect(()=>{if(jm.current&&!Im&&Dm.current){const jd=setTimeout(()=>Dm.current?.focus(),50);return()=>clearTimeout(jd)}jm.current=Im},[Im]);const Lg=reactExports.useCallback(()=>{const jd=Dm.current;if(jd){jd.style.height="auto";const Zd=120,lh=Math.min(Math.max(jd.scrollHeight,40),Zd);jd.style.height=`${lh}px`,jd.style.overflowY=jd.scrollHeight>Zd?"auto":"hidden"}},[]);reactExports.useEffect(()=>{Lg()},[Em,Lg]),reactExports.useEffect(()=>{const jd=setTimeout(Lg,0);return()=>clearTimeout(jd)},[Lg]),reactExports.useEffect(()=>{if(U0.length===0||isOffered(U0,ff))return;const jd=initialModelId(U0,sd||Pp.data?.defaultModel||DEFAULT_MODEL);jd&&jd!==ff&&hm(jd)},[U0,ff,sd,Pp.data?.defaultModel]);const A0=reactExports.useRef(!1);reactExports.useEffect(()=>{if(U0.length>0&&!A0.current){A0.current=!0;const jd=Pp.data?.builtinTools?.map(Zd=>Zd.id)||[];if(y1(jd),Pp.data?.mcpServers){const Zd=new Map;for(const Yd of Pp.data.mcpServers)if(Yd.isAvailable&&Yd.enabled&&Bm(Yd)){const ah=new Set(Yd.tools.map(bh=>bh.name).filter(bh=>!!bh));Zd.set(Yd.id,ah)}Om(Zd)}}},[Pp.data,U0,ff,sd,ad,pd,Bm]),reactExports.useEffect(()=>{!Pp.data?.mcpServers||!pd||Om(jd=>{const Zd=new Map;for(const Yd of Pp.data?.mcpServers??[])if(Bm(Yd)&&jd.has(Yd.id)){const lh=jd.get(Yd.id);lh&&Zd.set(Yd.id,lh)}else if(Bm(Yd)&&Yd.isAvailable&&Yd.enabled){const lh=new Set(Yd.tools.map(ah=>ah.name).filter(ah=>!!ah));Zd.set(Yd.id,lh)}return Zd})},[pd,Pp.data?.mcpServers,Bm]);const G0=reactExports.useRef(pd);G0.current=pd,reactExports.useEffect(()=>{const jd=parseEnabledMcpToolsByServer(zd);if(!jd)return;const Zd=fh||"__global__",Yd=!ag.current.has(Zd)&&qm==="connected";Om(lh=>{const ah=new Map(lh);if(jd.forEach((bh,Ah)=>{(!G0.current||G0.current.some(hp=>hp.id===Ah))&&bh.size!==0&&ah.set(Ah,new Set(bh))}),Yd){const bh=[];for(const Vh of Pp.data?.mcpServers??[]){if(!(!G0.current||G0.current.some(Jh=>Jh.id===Vh.id))||!Vh.isAvailable||!Vh.enabled)continue;const Gh=Vh.tools.map(Jh=>Jh.name).filter(Jh=>!!Jh);if(Gh.length===0)continue;const Uh=ah.get(Vh.id);(!Uh||Uh.size===0)&&(ah.set(Vh.id,new Set(Gh)),bh.push({serverId:Vh.id,enabledToolNames:Gh}))}let Ah=!0;for(const Vh of bh)agentRuntimeStore.getState().sendRawMessage({type:"mcp_server_tools_set",serverId:Vh.serverId,enabledToolNames:Vh.enabledToolNames},fh)||(Ah=!1,console.warn("[ChatBase] initial mcp_server_tools_set dropped: websocket not ready"));Ah&&ag.current.add(Zd)}return ah})},[zd,fh,Pp.data?.mcpServers,qm]),reactExports.useEffect(()=>{const jd=parseApprovedMcpToolsByServer(zd);jd&&am(()=>{const Zd=new Map;return jd.forEach((Yd,lh)=>{(!G0.current||G0.current.some(bh=>bh.id===lh))&&Zd.set(lh,new Set(Yd))}),Zd})},[zd]);const dv=reactExports.useRef("");reactExports.useEffect(()=>{const jd=zd?.servers;if(!jd||jd.length===0)return;const Zd=jd.filter(bh=>bh.status==="started").map(bh=>bh.id).sort();if(Zd.length===0)return;const Yd=Pp.data?.mcpServers||[],lh=Zd.some(bh=>{const Ah=Yd.find(Vh=>Vh.id===bh);return!Ah||Ah.tools.length===0}),ah=Zd.join(",");lh&&ah!==dv.current&&Pp.refetch&&(dv.current=ah,Pp.refetch())},[zd,Pp]);const Bg=reactExports.useCallback((jd,Zd)=>{Om(Yd=>{const lh=new Map(Yd),ah=new Set(Yd.get(jd)||[]);return ah.has(Zd)?ah.delete(Zd):ah.add(Zd),lh.set(jd,ah),agentRuntimeStore.getState().sendRawMessage({type:"mcp_server_tools_set",serverId:jd,enabledToolNames:Array.from(ah)},fh)||console.warn("[ChatBase] mcp_server_tools_set dropped: websocket not ready"),lh})},[fh]),ug=reactExports.useCallback((jd,Zd,Yd)=>{Om(lh=>{const ah=new Map(lh),bh=Yd?new Set(Zd):new Set;return ah.set(jd,bh),agentRuntimeStore.getState().sendRawMessage({type:"mcp_server_tools_set",serverId:jd,enabledToolNames:Array.from(bh)},fh)||console.warn("[ChatBase] mcp_server_tools_set dropped: websocket not ready"),ah})},[fh]),hv=reactExports.useCallback(jd=>{o1.has(jd)?F0(jd):Vm(jd)},[o1,Vm,F0]),a1=reactExports.useCallback((jd,Zd)=>{for(const Yd of jd)Zd?Vm(Yd):F0(Yd)},[Vm,F0]),pv=reactExports.useCallback((jd,Zd)=>{am(Yd=>{const lh=new Map(Yd),ah=new Set(Yd.get(jd)??[]),bh=ah.has(Zd);return bh?ah.delete(Zd):ah.add(Zd),lh.set(jd,ah),agentRuntimeStore.getState().sendRawMessage({type:"mcp_server_tool_approve",serverId:jd,toolName:Zd,approved:!bh},fh)||console.warn("[ChatBase] mcp_server_tool_approve dropped: websocket not ready"),lh})},[fh]),dg=reactExports.useCallback(jd=>{z0.has(jd)?(Rg(Zd=>{const Yd=new Map(Zd);return Yd.set(jd,!1),Yd}),tv(jd)):(Rg(Zd=>{const Yd=new Map(Zd);return Yd.set(jd,!0),Yd}),ev(jd))},[z0,ev,tv]),o0=reactExports.useCallback(()=>{const jd=[];return Kp.forEach((Zd,Yd)=>{(!pd||pd.some(lh=>lh.id===Yd))&&Zd.forEach(lh=>jd.push(lh))}),jd},[Kp,pd]),$0=reactExports.useCallback(()=>Array.from(o1),[o1]);reactExports.useEffect(()=>{if(Bd&&!Fp){const jd=useChatStore.getState().messages;jd.length>0&&Ap(jd)}},[Bd,Fp]);const v0=reactExports.useRef(void 0),A1=reactExports.useRef(0),l1=reactExports.useRef(!1),hg=reactExports.useRef(null);reactExports.useEffect(()=>{if(qh!==v0.current&&(qh&&j0.current.set(qh,0),v0.current=qh,Ap([]),lf.current.clear(),!qh)||!qh)return;const jd=S1.current;if(jd){hg.current!==jd.id&&(hg.current=jd.id,useConversationStore.getState().setMessages(qh,jd.messages),Ap(convertHistoryToDisplayItems(jd.messages)),useConversationStore.getState().markFetched(qh),yf(!0));return}kf!==A1.current&&(A1.current=kf,kf>0&&(useConversationStore.getState().clearMessages(qh),Ap([]),lf.current.clear(),j0.current.set(qh,0),l1.current=!0));const Zd=useConversationStore.getState(),Yd=Zd.isFetching(qh),lh=Zd.getMessages(qh);if(lh.length>0&&(Ap(fp=>fp.length>0?fp:lh),yf(!0)),Yd)return;if(qm!=="connected"){lh.length===0&&yf(!1);return}Zd.setFetching(qh,!0);const ah=()=>extractChatMessagesFromFullContext(agentRuntimeStore.getState().fullContext),bh=fp=>{Zd.setMessages(qh,fp),Ap(convertHistoryToDisplayItems(fp)),j0.current.set(qh,0),Zd.markFetched(qh),yf(!0)},Ah=l1.current?[]:ah();if(l1.current=!1,Ah.length>0){bh(Ah);return}const Vh=()=>{const fp=[fh,ih?.agentId,Fp,qh,"default",void 0],tf=new Set;for(const Vf of fp){const gg=typeof Vf=="string"?Vf.trim():void 0,I0=gg||"__global__";if(tf.has(I0))continue;if(tf.add(I0),agentRuntimeStore.getState().requestRefresh(gg))return!0}return!1};if(!Vh()){Zd.setFetching(qh,!1),lh.length===0&&yf(!1);return}let Gh=!1;const Uh=window.setTimeout(()=>{Gh||Vh()},500),Jh=agentRuntimeStore.subscribe(fp=>fp.fullContext,fp=>{if(Gh||!fp)return;const tf=extractChatMessagesFromFullContext(fp);Gh=!0,Jh(),bh(tf)}),up=window.setTimeout(()=>{if(Gh)return;Gh=!0,Jh(),Zd.setFetching(qh,!1),yf(lh.length>0);const fp=j0.current.get(qh)??0;qm==="connected"&&fp<3?(j0.current.set(qh,fp+1),Vh(),B0(Vf=>Vf+1)):yf(!0)},2e3);return()=>{window.clearTimeout(Uh),window.clearTimeout(up),Jh()}},[qh,Kf,ap?.agentId,qm,fh,Qm,kf]),reactExports.useEffect(()=>{if(qh&&Rf.length>0){const jd=Rf.filter(Zd=>!isToolCallMessage(Zd));jd.length>0&&useConversationStore.getState().setMessages(qh,jd)}},[qh,Rf]);const pg=Rf.filter(jd=>!isToolCallMessage(jd)),W0=reactExports.useRef(0);reactExports.useEffect(()=>{const jd=pg.length;jd!==W0.current&&(W0.current=jd,kh?.(pg))},[Rf,pg,kh]),reactExports.useEffect(()=>{Ph?.(Rf.filter(jd=>!isToolCallMessage(jd)))},[Rf,Ph]),reactExports.useEffect(()=>{zh?.(Rf)},[Rf,zh]);const Bf=_d?2:3,$1=reactExports.useMemo(()=>{if(ap?.configEndpoint)return{apiBaseUrl:getApiBaseFromConfig(ap.configEndpoint),authToken:ap.authToken}},[ap?.configEndpoint,ap?.authToken]),Gv={userAvatar:jsxRuntimeExports.jsx(PersonIcon,{size:16}),assistantAvatar:jsxRuntimeExports.jsx(ForwardRef$2,{size:16,color:km}),showAvatars:!0,avatarSize:32,userAvatarBg:"neutral.muted",assistantAvatarBg:"accent.emphasis",...Xd};reactExports.useEffect(()=>{if(!ap||!td||Pf)return;const jd=createProtocolAdapter(ap);if(jd)return Mm.current=jd,b1(!0),sv.current=jd.subscribe(Zd=>{if(T1.current(),!(T0.current&&Zd.type!=="state-update"&&Zd.type!=="error"&&Zd.type!=="done"))switch(Zd.type){case"message":if(Zd.usage){const Yd=Zd.timestamp instanceof Date?Zd.timestamp.getTime():Date.now(),lh=Math.max(0,Zd.usage.promptTokens??0),ah=Math.max(0,Zd.usage.completionTokens??0),bh=Math.max(lh+ah,Zd.usage.totalTokens??0),Ah=agentRuntimeStore.getState();Ah.appendLocalTokenTurn({serviceName:$g,agentId:ap?.agentId,timestampMs:Yd,promptTokens:lh,completionTokens:ah,totalTokens:bh});const Vh=Ah.costUsage?.cumulativeCostUsd;typeof Vh=="number"&&Number.isFinite(Vh)&&Ah.upsertLocalCostPoint({serviceName:$g,agentId:ap?.agentId,timestampMs:Yd,cumulativeUsd:Math.max(0,Vh)})}if(C0.current){const Yd=Qf.current?.id;Yd&&(Ap(lh=>lh.filter(ah=>isToolCallMessage(ah)||ah.id!==Yd)),Bd&&useChatStore.getState().deleteMessage(Yd),Qf.current=null);break}if(Zd.message){const Yd=Zd.message.id,lh=Qf.current?.id;if(lh&&!(!lh||Yd&&Yd!==lh)){const bh=Zd.message.content,Ah=typeof bh=="string"?sanitizeAssistantContent(bh):bh??"";typeof Ah=="string"&&Ah&&(Ng.current=Ah),Ap(Vh=>{const hp=[...Vh],Gh=hp.findIndex(Uh=>!isToolCallMessage(Uh)&&Uh.id===lh);return Gh>=0&&!isToolCallMessage(hp[Gh])&&(hp[Gh]={...hp[Gh],content:Ah}),hp}),Bd&&useChatStore.getState().updateMessage(lh,{content:Ah})}else{const bh=Zd.message.content,Ah=typeof bh=="string"?bh:bh??"",Vh=typeof Ah=="string"?sanitizeAssistantContent(Ah):"",hp=createAssistantMessage(Vh);hp.id=Zd.message.id||hp.id,Qf.current=hp,Ap(Gh=>{const Uh=Gh.findIndex(Jh=>!isToolCallMessage(Jh)&&Jh.id===hp.id);if(Uh>=0){const Jh=[...Gh];return Jh[Uh]={...Jh[Uh],content:Vh},Jh}return[...Gh,hp]}),Bd&&(useChatStore.getState().messages.find(Uh=>Uh.id===hp.id)?useChatStore.getState().updateMessage(hp.id,{content:Vh}):useChatStore.getState().addMessage(hp))}}break;case"tool-call":if(Zd.toolCall&&!T0.current){const Yd=Zd.toolCall.toolCallId||generateMessageId(),lh=Zd.toolCall.toolName,ah=Zd.toolCall.args||{},bh=Zd.toolCall.argsComplete;if(lf.current.has(Yd)){const Ah=lf.current.get(Yd);if(Ah){const Vh={...Ah,args:{...Ah.args,...ah}};lf.current.set(Yd,Vh),Ap(Uh=>Uh.map(Jh=>isToolCallMessage(Jh)&&Jh.toolCallId===Yd?Vh:Jh));const Gh=_m.current?.find(Uh=>Uh.name===lh)?.handler;Gh&&Ah.status==="executing"&&(bh??Object.keys(ah).length>0)&&(Cm.current++,Wv(Gh,Vh,Yd))}}else{const Ah={id:`tool-${Yd}`,type:"tool-call",toolCallId:Yd,toolName:lh,args:ah,status:"executing"};lf.current.set(Yd,Ah),Ap(Gh=>[...Gh,Ah]),k0.current?.({toolName:lh,toolCallId:Yd,args:ah}),Gm.current?.recorder.toolStarted({id:Yd,name:lh,args:ah});const Vh=_m.current?.find(Gh=>Gh.name===lh),hp=Vh?.handler;hp&&(bh??(Object.keys(ah).length>0||!frontendToolExpectsArgs(Vh)))&&(Cm.current++,Wv(hp,Ah,Yd))}}break;case"tool-result":if(Zd.toolResult){const Yd=Zd.toolResult.toolCallId;if(Yd&&lf.current.has(Yd)){const lh=lf.current.get(Yd);if(lh){const ah=lh.args&&"steps"in lh.args&&Array.isArray(lh.args.steps),bh=Zd.toolResult.result;let Ah,Vh,hp,Gh=!1,Uh=!!Zd.toolResult.error;if(bh&&typeof bh=="object"){if("pending_approval"in bh&&bh.pending_approval===!0&&(Gh=!0),bh.execution_error&&typeof bh.execution_error=="string"&&(Ah=bh.execution_error,Uh=!0),bh.code_error&&typeof bh.code_error=="object"){const up=bh.code_error;Vh={name:up.name||"Error",value:up.value||"Unknown error",traceback:up.traceback},Uh=!0}if("exit_code"in bh){const up=bh.exit_code;hp=typeof up=="number"?up:null,hp!=null&&hp!==0&&(Uh=!0)}"execution_ok"in bh&&bh.execution_ok===!1&&(Uh=!0)}const Jh={...lh,result:Zd.toolResult.result,status:Uh?"error":Gh?"inProgress":ah?"executing":"complete",error:Zd.toolResult.error,executionError:Ah,codeError:Vh,exitCode:hp};lf.current.set(Yd,Jh),Ap(up=>up.map(fp=>isToolCallMessage(fp)&&fp.toolCallId===Yd?Jh:fp)),Gm.current?.recorder.toolEnded(Yd,{result:Zd.toolResult.result,error:Zd.toolResult.error??(Jh.status==="error"?Ah??"failed":void 0)}),n0.current?.({toolName:lh.toolName,toolCallId:Yd,args:lh.args,result:Zd.toolResult.result,status:Jh.status,error:Zd.toolResult.error})}}}break;case"state-update":if(sh?.(Zd.data),Zd.data){const Yd=Array.from(lf.current.entries()).filter(([lh,ah])=>ah.status==="executing");if(Yd.length>0){const[lh,ah]=Yd[Yd.length-1];if(!(ah.args&&"steps"in ah.args&&Array.isArray(ah.args.steps))){const Ah=Zd.data,Vh=Ah.weather??Ah.result??Ah.toolResult??Ah,hp={...ah,result:Vh,status:"complete"};lf.current.set(lh,hp),Ap(Gh=>Gh.map(Uh=>isToolCallMessage(Uh)&&Uh.toolCallId===lh?hp:Uh))}}}break;case"activity":break;case"done":{Gm.current?.recorder.turnEnded({text:Ng.current||void 0,usage:Zd.usage}),Ng.current="";const Yd=Zd.usage?.promptTokens??0,lh=Zd.usage?.completionTokens??0,ah=Zd.usage?.totalTokens??Yd+lh;ah>0&&sm(bh=>({turnInput:Yd,turnOutput:lh,sessionInput:(bh?.sessionInput??0)+Yd,sessionOutput:(bh?.sessionOutput??0)+lh,totalTokens:ah}))}C0.current&&Mg.current&&Ap(Yd=>{if(Yd.some(Ah=>!isToolCallMessage(Ah)&&Ah.role==="assistant"&&String(Ah.content||"").trim().length>0))return Yd;const ah=[...Yd].reverse().find(Ah=>isToolCallMessage(Ah)&&Ah.status==="complete"&&Ah.result!==void 0);if(!ah||!isToolCallMessage(ah))return Yd;const bh=createAssistantMessage(formatToolResultFallback(ah.result));return Bd&&useChatStore.getState().addMessage(bh),[...Yd,bh]}),C0.current=!1,Cm.current=0,x0(!1),Hm(!1),agentRuntimeStore.getState().requestRefresh(fh);break;case"error":console.error("[ChatBase] Protocol error:",Zd.error),Gm.current?.recorder.turnEnded({error:Zd.error?.message??"error"}),Zd.error?.message&&/exceeded maximum retries/i.test(Zd.error.message)&&Mg.current&&Ap(Yd=>{if(Yd.some(Ah=>!isToolCallMessage(Ah)&&Ah.role==="assistant"&&String(Ah.content||"").trim().length>0))return Yd;const ah=[...Yd].reverse().find(Ah=>isToolCallMessage(Ah)&&Ah.status==="complete"&&Ah.result!==void 0);if(!ah||!isToolCallMessage(ah))return Yd;const bh=createAssistantMessage(formatToolResultFallback(ah.result));return Bd&&useChatStore.getState().addMessage(bh),[...Yd,bh]}),C0.current=!1,Pm(Zd.error||new Error("Unknown error")),Cm.current=0,x0(!1),Hm(!1),agentRuntimeStore.getState().requestRefresh(fh);break}}),jd.connect().catch(console.error),()=>{sv.current?.(),Mm.current?.disconnect()}},[J1,sh,Bd,td]);function Wv(jd,Zd,Yd){(async()=>{if(T0.current){Cm.current--,Cm.current<0&&(Cm.current=0);return}try{const lh=await jd(Zd.args);Mm.current&&await Mm.current.sendToolResult(Yd,{toolCallId:Yd,success:!0,result:lh});const ah={...Zd,result:lh,status:"complete"};Gm.current?.recorder.toolEnded(Yd,{result:lh}),lf.current.set(Yd,ah),Ap(bh=>bh.map(Ah=>isToolCallMessage(Ah)&&Ah.toolCallId===Yd?ah:Ah))}catch(lh){console.error("[ChatBase] Frontend tool execution error:",lh);const ah={...Zd,status:"error",error:lh.message};Gm.current?.recorder.toolEnded(Yd,{error:lh.message}),lf.current.set(Yd,ah),Ap(bh=>bh.map(Ah=>isToolCallMessage(Ah)&&Ah.toolCallId===Yd?ah:Ah))}finally{Cm.current--,Cm.current<0&&(Cm.current=0)}})()}reactExports.useEffect(()=>{const jd=Tm.current;if(jd){jd.scrollTo({top:jd.scrollHeight,behavior:"smooth"});return}lg.current?.scrollIntoView({behavior:"smooth"})},[Rf]);const fv=reactExports.useRef(void 0),Kv=reactExports.useMemo(()=>$d&&$d.input!=="off"?new DeviceHearing($d.modelsUrl,$d.engines):void 0,[$d?.input,$d?.modelsUrl,$d?.engines]),Zp=reactExports.useCallback(async(jd,Zd,Yd)=>{const lh=(jd??Em).trim();if(!lh||Im||!Mm.current&&!Ad)return;if(Zd&&namesFiles(Zd))try{Zd=await withUploadedFiles(Zd,Dg)}catch(Uh){Pm(Uh instanceof Error?Uh:new Error(String(Uh)));return}const ah=displayPressOf(Zd);if(ah&&Zd){const Uh=V0.current?.socket;if(!Uh){Pm(new Error("This conversation’s ui channel is not open."));return}try{const Jh=await Uh.act(ah);if(!Jh.ok){Pm(new Error(Jh.detail||`The press was refused (${Jh.status}).`));return}Zd=withPress(Zd,Jh.value)}catch(Jh){Pm(Jh instanceof Error?Jh:new Error(String(Jh)));return}}T0.current=!1,Ng.current="",Gm.current?.recorder.turnStarted(lh,ff||void 0),C0.current=isToolCallOnlyPrompt(lh);const bh=Yd??(jd===void 0?fv.current:void 0);fv.current=void 0;const Ah=bh?{...Zd??{},voice:bh}:Zd,Vh=createUserMessage(lh,bh?{...bh}:void 0),Gh=[...Rf.filter(Uh=>!isToolCallMessage(Uh)),Vh];Ap(Uh=>[...Uh,Vh]),L0(""),x0(!0),Hm(!0),Pm(null),Qf.current=null,Bd&&useChatStore.getState().addMessage(Vh);try{if(Ad)if(Hd){const Uh=generateMessageId(),Jh=createAssistantMessage("");Jh.id=Uh,Ap(up=>[...up,Jh]),Qf.current=Jh,Bd&&(useChatStore.getState().addMessage(Jh),useChatStore.getState().startStreaming(Uh)),cg.current=new AbortController,await Ad(lh,Gh,{onChunk:up=>{Ap(fp=>fp.map(tf=>tf.id===Uh?{...tf,content:tf.content+up}:tf)),Bd&&useChatStore.getState().appendToStream(Uh,up)},onComplete:up=>{Ap(fp=>fp.map(tf=>tf.id===Uh?{...tf,content:up}:tf)),Bd&&(useChatStore.getState().updateMessage(Uh,{content:up}),useChatStore.getState().stopStreaming())},onError:up=>{const fp=of.error(up.message);Ap(tf=>tf.map(Vf=>Vf.id===Uh?{...Vf,content:fp}:Vf)),Bd&&(useChatStore.getState().updateMessage(Uh,{content:fp}),useChatStore.getState().stopStreaming()),Pm(up)},signal:cg.current.signal})}else{const Uh=await Ad(lh,Gh);if(Uh){const Jh=createAssistantMessage(Uh);Ap(up=>[...up,Jh]),Bd&&useChatStore.getState().addMessage(Jh)}}else if(Mm.current){const Uh=(Yh||[]).map(fp=>({name:fp.name,description:fp.description,parameters:fp.parameters||{type:"object",properties:{}}}));console.warn("[ChatBase] frontendTools count:",Yh?.length??0,"toolsForRequest:",Uh.map(fp=>fp.name));const Jh=o0(),up=$0();av(),await Mm.current.sendMessage(Vh,{threadId:f0.current,messages:Gh,...ff&&{model:ff},tools:Uh,builtinTools:Jh,skills:up,identities:Nm.current,...Ah?{forwardedProps:Ah}:{}})}}catch(Uh){if(Uh.name!=="AbortError"){console.error("[ChatBase] Send error:",Uh);const Jh=createAssistantMessage(of.error(Uh.message));Ap(up=>[...up,Jh]),Pm(Uh)}}finally{Mm.current||(x0(!1),Hm(!1),agentRuntimeStore.getState().requestRefresh(fh)),C0.current=!1,Qf.current=null,cg.current=null}},[Em,Im,Rf,ff,Yh,Bd,Ad,fh,Hd,o0,$0,av,of,Dg]);reactExports.useEffect(()=>{if(!Ip||Cp&&Mh.current===Cp)return;if(Cp&&sentPendingPromptKeys.has(Cp)){Mh.current=Cp;return}!h0&&!(!qh||qm!=="connected")||!e0&&!Ad||(Mh.current=Cp??null,Cp&&sentPendingPromptKeys.add(Cp),queueMicrotask(()=>Zp(Ip)))},[Ip,Cp,h0,qh,qm,e0,Zp,Ad,qf]);const c1=reactExports.useCallback(()=>{T0.current=!0,cg.current?.abort();const jd=Mm.current;jd&&(typeof jd.stopGeneration=="function"&&jd.stopGeneration(),typeof jd.terminateSession=="function"?jd.terminateSession().catch(()=>{}):typeof jd.terminateAgent=="function"?jd.terminateAgent().catch(()=>{}):typeof jd.terminateTask=="function"?jd.terminateTask().catch(()=>{}):typeof jd.terminateRequest=="function"&&jd.terminateRequest().catch(()=>{}));for(const[Zd,Yd]of lf.current.entries())(Yd.status==="executing"||Yd.status==="inProgress")&&lf.current.set(Zd,{...Yd,status:"error",error:"Interrupted by user"});Ap(Zd=>Zd.map(Yd=>!isToolCallMessage(Yd)||Yd.status!=="executing"&&Yd.status!=="inProgress"?Yd:{...Yd,status:"error",error:"Interrupted by user"})),Bd&&useChatStore.getState().stopStreaming(),Cm.current=0,x0(!1),Hm(!1),agentRuntimeStore.getState().requestRefresh(fh),agentRuntimeStore.getState().stopSubagentActivity(),C0.current=!1,Qf.current=null,Vv.interrupt(),cd&&cd.interrupt().catch(()=>{})},[cd,Bd,fh,ap?.configEndpoint,ap?.authToken,ap?.agentId]),u1=reactExports.useCallback(jd=>async Zd=>{const Yd=jd.actions?.find(bh=>bh.name===Zd.action);if(!Yd)throw new Error(`“${Zd.action}” was not offered here.`);const lh=Zd.payload?.value,ah=Zd.action===ANSWER_ACTION?typeof lh=="string"?lh:isFileRef(lh)?lh.name:"Answered.":Zd.action;await Zp(ah,{loop:{action:{name:Zd.action,display_id:jd.id,token:Yd.token,payload:Zd.payload??{}}}})},[Zp]),fg=reactExports.useCallback(()=>{Ap([]),lf.current.clear(),Cm.current=0,L0(""),f0.current=generateMessageId(),Bd&&dm(),qh&&useConversationStore.getState().clearMessages(qh),Eh?.(),mh?.onNewChat?.()},[dm,Eh,mh,Bd,Fp]);reactExports.useEffect(()=>{if(Id){if(!e0&&!Ad){Id(null);return}return Id({send:(jd,Zd)=>{Zp(jd,Zd)},stop:c1,newChat:fg,thread:()=>f0.current}),()=>{Id(null)}}},[Id,e0,Ad,Zp,c1,fg]),reactExports.useEffect(()=>{Wd?.(Im)},[Wd,Im]);const mv=reactExports.useCallback(()=>{window.confirm("Clear all messages?")&&(Ap([]),lf.current.clear(),Bd&&dm(),qh&&useConversationStore.getState().clearMessages(qh),Ch?.(),mh?.onClear?.())},[dm,Ch,mh,Bd,Fp]),jg=reactExports.useCallback(jd=>{const Zd=new Set(jd);Ap(Yd=>Yd.filter(lh=>!Zd.has(lh.id)));for(const[Yd,lh]of lf.current.entries())Zd.has(lh.id)&&lf.current.delete(Yd)},[]),mg=reactExports.useCallback(async(jd,Zd)=>{const Yd=lf.current.get(jd);if(Yd&&(Yd.status==="executing"||Yd.status==="inProgress")){if(!!Zd&&typeof Zd=="object"&&Zd.type==="tool-approval-decision"&&typeof Zd.approved=="boolean"&&Mm.current){const bh=Zd,Ah=!!bh.approved,Vh=bh._fromServerEcho===!0,hp=bh._alreadyDispatched===!0,Gh=Yd.status==="inProgress",Uh=typeof bh.toolName=="string"?bh.toolName:Yd.toolName,Jh=Uh.includes("__");if(Ah){const up=Uh.indexOf("__");if(up!==-1){const fp=Uh.slice(0,up),tf=Uh.slice(up+2);am(Vf=>{const gg=new Map(Vf),I0=new Set(Vf.get(fp)??[]);return I0.add(tf),gg.set(fp,I0),gg})}}try{const up=typeof Zd=="object"&&Zd!==null&&typeof Zd.approvalId=="string"?Zd.approvalId:void 0;if(!Vh&&!Gh){up&&(Ah?await Q0?.(up,void 0,jd):await D0?.(up,void 0,jd));return}if(up&&!hp&&(Ah?await Q0?.(up,void 0,jd):await D0?.(up,void 0,jd)),Jh&&!Gh)return;const fp={...Yd,result:Zd,status:Ah?"complete":"error",error:Ah?void 0:"Tool approval rejected by user"};lf.current.set(jd,fp),Ap(tf=>tf.map(Vf=>isToolCallMessage(Vf)&&Vf.toolCallId===jd?fp:Vf)),x0(!0),Hm(!0),await Mm.current.sendToolResult(jd,{toolCallId:jd,success:Ah,result:Ah?{approved:!0,message:"Tool call approved by user.",...up?{approvalId:up}:{}}:{approved:!1,message:"Tool call rejected by user.",...up?{approvalId:up}:{}},...Ah?{}:{error:"Tool approval rejected by user"}})}catch(up){console.error("[ChatBase] Approval continuation error:",up),Pm(up)}return}const ah={...Yd,result:Zd,status:"complete"};if(lf.current.set(jd,ah),Ap(bh=>bh.map(Ah=>isToolCallMessage(Ah)&&Ah.toolCallId===jd?ah:Ah)),Mm.current){let bh;if(typeof Zd=="string")bh=Zd;else if(Zd&&typeof Zd=="object"&&"accepted"in Zd){const Vh=Zd;if(Vh.accepted){const hp=Vh.steps?.map(Gh=>Gh.description).join(", ")||"";bh=hp?`I confirm and approve the following steps: ${hp}`:"I confirm and approve the plan."}else bh="I reject this plan. Please suggest something else."}else bh=JSON.stringify(Zd,null,2);const Ah={id:generateMessageId(),role:"user",content:bh,createdAt:new Date};x0(!0),Hm(!0);try{const Vh=Rf.filter(hp=>!isToolCallMessage(hp));await Mm.current.sendMessage(Ah,{threadId:f0.current,messages:[...Vh,Ah]})}catch(Vh){console.error("[ChatBase] HITL respond error:",Vh)}}}},[Rf,Q0,D0]);k1.current=mg;const Gb=reactExports.useCallback(jd=>{Zp(jd.message)},[Zp]),Zv=reactExports.useCallback(jd=>{L0(jd),setTimeout(()=>Dm.current?.focus(),0)},[]),Wb=reactExports.useCallback(async(jd,Zd)=>{await Q0?.(jd,Zd)},[Q0]),Yv=reactExports.useCallback(async(jd,Zd)=>{await D0?.(jd,Zd)},[D0]),R0=(Pp.data?.mcpServers||[]).filter(jd=>!pd||Bm(jd)),R1=reactExports.useMemo(()=>{const jd=R0.map(Yd=>{const lh=zd?.servers?.find(ah=>ah.id===Yd.id);if(lh&&lh.status==="started"){const ah={};if(Yd.isAvailable||(ah.isAvailable=!0),lh.tools&&lh.tools.length>0&&(ah.tools=lh.tools.map(bh=>({name:bh.name,description:bh.description||"",enabled:bh.enabled??!0}))),Object.keys(ah).length>0)return{...Yd,...ah}}return Yd}),Zd=new Set(R0.map(Yd=>Yd.id));for(const Yd of zd?.servers??[])Yd.status==="started"&&!Zd.has(Yd.id)&&Yd.tools&&Yd.tools.length>0&&(!pd||pd.some(ah=>ah.id===Yd.id))&&jd.push({id:Yd.id,name:Yd.id,description:"",url:"",enabled:!0,tools:Yd.tools.map(ah=>({name:ah.name,description:ah.description||"",enabled:ah.enabled??!0})),args:[],requiredEnvVars:[],isAvailable:!0,transport:"stdio",isConfig:!1,isRunning:!0});return jd},[R0,zd,pd]),I1=ap?.configEndpoint?ap.configEndpoint.replace(/\/api\/v1\/(config|configure)\/?$/,""):void 0,Jv=!ap||!ap.enableConfigQuery||!!Pp.data||!!Ef.data,Fg=Fd||Pp.data?.welcomeMessage||"",d1=Pp.data?.suggestions,h1=Zh&&Zh.length>0?Zh:Array.isArray(d1)&&d1.length>0?d1.map(jd=>{if(typeof jd=="string"){const lh=jd.trim();return{title:lh,message:lh}}const Zd=(jd?.text??"").trim();return{title:(jd?.summary??"").trim()||Zd,message:Zd}}).filter(jd=>jd.message):void 0,P1=Vd?[{id:"__welcome__",role:"assistant",content:Vd,createdAt:WELCOME_AT},...Rf]:Rf,gv=gh||jsxRuntimeExports.jsxs(Box,{display:"flex",flexDirection:"column",minHeight:0,width:"100%",maxWidth:920,mx:"auto",bg:"canvas.default",children:[jsxRuntimeExports.jsx(ChatMessageList,{displayItems:P1,actOn:ap?.uiSocket?u1:void 0,upload:ap?.uiFiles?Dg:void 0,isLoading:Im,isStreaming:Q1,showLoadingIndicator:Pu,hideMessagesAfterToolUI:np,avatarConfig:Gv,padding:Bf,notebookToolSurfacesId:dh,approvalConfig:$1,messagesEndRef:lg,onRespond:mg,showTurnFooters:rh,agentUsage:x1,onRemoveItems:jg,mcpServers:R1,emptyContent:Xu?null:jsxRuntimeExports.jsx(ChatEmptyState,{emptyState:yh,brandIcon:nh,description:Fg,suggestions:h1,submitOnSuggestionClick:Oh,onSuggestionSubmit:Gb,onSuggestionFill:Zv})}),Ud]}),Xv=Kv&&$d?jsxRuntimeExports.jsx(VoiceInput,{hearing:Kv,language:$d.language,consentKey:$d.consentKey??"chat",disabled:Pf||Xu,speaking:Pd,onStopSpeaking:Gd,onListen:Gd,onTranscript:jd=>{if($d.sendWhatISay){Zp(jd.text,void 0,jd.metadata);return}fv.current=jd.metadata,L0(Em.trim()?`${Em.trim()} ${jd.text}`:jd.text)}}):void 0,K0=Mu?jsxRuntimeExports.jsx(InputPrompt,{footerExtras:Xv,input:Em,setInput:L0,isLoading:Im,kernelStatus:rg,connectionConfirmed:Jv,placeholder:qd,typingSuggestions:h1?.map(jd=>jd.message||jd.title),autoFocus:jh,focusTrigger:rp,padding:Bf,onSend:()=>Zp(),onStop:c1,disableInputPrompt:ju||Pf||!!Yu||Xu,promptVariant:Fu,mentionableAgents:sg,promptCommands:Uu,promptHistory:Pp.data?.promptHistory,showTokenUsage:Ru,showContextRing:Iu,agentUsage:x1,showModelSelector:Du,showToolsMenu:Lu,showSkillsMenu:Bu,codemodeEnabled:nd,onToggleCodemode:od,isA2AProtocol:N0,showAgentsMenu:Hu,agents:E0,selectedAgentId:Gu??E0[0]?.id,onSelectAgent:Wu,hasConfigData:!!Pp.data,hasSkillsData:!!Ef.data,configLoading:Pp.isLoading,models:U0,decisions:Pp.data?{models:Pp.data.decisionModels,note:Pp.data.decisionsNote}:void 0,selectedModel:ff,onModelSelect:hm,availableTools:_1.runtime,availableFrontendTools:_1.frontend,mcpServers:R1,enabledMcpTools:Kp,enabledMcpToolCount:o0().length,onToggleMcpTool:Bg,onToggleAllMcpServerTools:ug,approvedMcpTools:p0,onToggleMcpToolApproval:pv,skills:Ef.data?.skills||[],skillsLoading:!1,enabledSkills:o1,onToggleSkill:hv,onToggleAllSkills:a1,approvedSkills:z0,onToggleSkillApproval:dg,apiBase:I1,authToken:ap?.authToken,mcpStatusData:zd}):null,Z0={title:Au,subtitle:lo,disableReason:Pf?Xm:void 0,brandIcon:nh,headerContent:Qd,headerActions:bd,showInformation:Nd,onInformationClick:Kd??(()=>tg(!0)),padding:Bf,kernelIndicatorState:wd,kernelIndicatorPlacement:kd,runtimeStatus:Nf??Vv.data,kernel:im?Wh??cd:Af?Xp??cd:cd,kernelEnvironmentName:dd,kernelCpu:md,kernelMemory:ld,kernelGpu:hd,headerButtons:mh,messageCount:pg.length,onNewChat:fg,onClear:mv,chatViewMode:Td,onChatViewModeChange:Rd,disabledViewModes:Od,showEphemeralSurfaceControl:gp||ip,enableEphemeralNotebookOption:gp,enableEphemeralDocumentOption:ip,ephemeralSurfaceMode:wm,onEphemeralSurfaceModeChange:Mf},vv=$u?eh?eh(Z0):jsxRuntimeExports.jsx(ChatBaseHeader,{...Z0}):null;return jsxRuntimeExports.jsxs(Box,{className:xd,position:"relative",display:"flex",flexDirection:"column",height:"100%",maxHeight:"100%",minHeight:0,flex:"1 1 auto",width:"100%",minWidth:0,bg:wh||"canvas.default",borderRadius:xh,border:Kh,boxShadow:Md,overflow:"hidden",children:[!vp&&vv,X1&&jsxRuntimeExports.jsx(Box,{flex:"1 1 auto",minHeight:0,display:"flex",flexDirection:"column",children:jsxRuntimeExports.jsx(ReactorLazy,{load:loadAgentDetails,errorFallback:agentDetailsRefused,props:{name:Au||"AI Agent",icon:nh,protocol:ap?.type??"unknown",url:ap?.endpoint||"",messageCount:Rf.length,agentId:fh,apiBase:ap?.configEndpoint,onBack:()=>tg(!1)}})}),Wp&&Ag&&Ag.length>0&&jsxRuntimeExports.jsx(ToolApprovalBannerSection,{pendingApprovals:Ag,onApprove:Wb,onReject:Yv}),Ou&&ng&&jsxRuntimeExports.jsxs(Box,{display:"flex",alignItems:"center",gap:2,p:Bf,bg:"danger.subtle",borderBottom:"1px solid",borderColor:"danger.muted",children:[jsxRuntimeExports.jsx(AlertIcon,{size:16}),jsxRuntimeExports.jsx(Text$3,{sx:{color:"danger.fg",fontSize:1},children:ng.message})]}),vp?jsxRuntimeExports.jsxs(Box,{flex:1,minHeight:0,display:"flex",overflow:"hidden",position:"relative",children:[jsxRuntimeExports.jsx(Box,{flex:1,minWidth:0,minHeight:0,display:"flex",flexDirection:"column",overflow:"hidden",sx:wf||vf?null:{borderRight:"1px solid",borderColor:"border.default"},children:Xu||Yu?jsxRuntimeExports.jsx(CompanionSurfaceSkeleton,{mode:im?"notebook":"document"}):im?jsxRuntimeExports.jsx(ReactorLazy,{load:loadEphemeralNotebook,errorFallback:ephemeralNotebookRefused,fallback:jsxRuntimeExports.jsx(CompanionSurfaceSkeleton,{mode:"notebook"}),props:{notebookId:sf,runtimeName:Fp||fh,runtimeOverride:Qp,themeVariant:vd,colorMode:Sd,nbformat:_p??void 0,onNbformatChange:Jp,toolbarComponent:zf,toolbarExtraItems:cm,collaborationProvider:Bh}}):jsxRuntimeExports.jsx(vM.Suspense,{fallback:null,children:jsxRuntimeExports.jsx(EphemeralDocument,{documentId:Zf,runtimeName:Fp||fh,runtimeOverride:Qp,themeVariant:vd,colorMode:Sd,content:Yf??void 0,onContentChange:Am,onToolsReady:af,onKernelChange:bf,collaboration:jp,toolbarExtraItems:bm})})}),!vf&&jsxRuntimeExports.jsxs(Box,{sx:wf?{position:"absolute",right:16,width:um?360:440,maxWidth:"calc(100% - 32px)",...um?{bottom:16,height:"62%"}:{top:16,bottom:16},display:"flex",flexDirection:"column",minHeight:0,overflow:"hidden",bg:"canvas.default",border:"1px solid",borderColor:"border.default",borderRadius:2,boxShadow:"shadow.large",zIndex:5}:{flexShrink:0,width:440,minWidth:320,maxWidth:"48%",minHeight:0,display:"flex",flexDirection:"column",overflow:"hidden",bg:"canvas.default"},children:[vv,jsxRuntimeExports.jsx(Box,{ref:Tm,flex:1,minHeight:0,overflow:"auto",bg:"canvas.default",children:gv}),Dh,K0]}),vf&&Xh&&(Td==="sidebar"?jsxRuntimeExports.jsx(Box,{position:"absolute",top:8,right:8,zIndex:6,children:jsxRuntimeExports.jsx(IconButton,{icon:SidebarExpandIcon,"aria-label":"Open chat",onClick:Xh,variant:"default",size:"small"})}):jsxRuntimeExports.jsx(FloatingBrandButton,{isOpen:!1,onToggle:Xh,position:"bottom-right",tooltip:"Open chat"}))]}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(Box,{ref:Tm,"data-chat-history":"",flex:1,flexGrow:1,minHeight:0,overflow:"auto",bg:"canvas.default",children:gv}),Dh,K0]}),uh&&jsxRuntimeExports.jsx(PoweredByTag,{...Sh}),Yu&&jsxRuntimeExports.jsxs(Box,{position:"absolute",inset:0,zIndex:20,display:"flex",alignItems:"center",justifyContent:"center",p:3,overflow:"auto",children:[jsxRuntimeExports.jsx(Box,{"aria-hidden":!0,position:"absolute",inset:0,bg:"canvas.default",opacity:.4,backdropFilter:"blur(1px)"}),jsxRuntimeExports.jsx(Box,{position:"relative",zIndex:1,maxWidth:"100%",children:Yu})]}),Xu&&!Yu&&jsxRuntimeExports.jsxs(Box,{position:"absolute",inset:0,zIndex:15,display:"flex",alignItems:"center",justifyContent:"center",p:3,children:[jsxRuntimeExports.jsx(Box,{"aria-hidden":!0,position:"absolute",inset:0,bg:"canvas.default",opacity:.35,backdropFilter:"blur(1px)"}),jsxRuntimeExports.jsxs(Box,{position:"relative",zIndex:1,display:"flex",flexDirection:"column",alignItems:"center",gap:3,children:[jsxRuntimeExports.jsx(StyledSpinner,{size:"large"}),jsxRuntimeExports.jsx(Text$3,{sx:{color:"fg.muted"},children:ed||"Launching your agent…"})]})]})]})}function ToolApprovalBannerSection({pendingApprovals:Au,onApprove:lo,onReject:$u}){const[Ru,Iu]=reactExports.useState(null);return reactExports.useEffect(()=>{Ru&&(Au.some(Pu=>Pu.id===Ru.id)||Iu(null))},[Au,Ru]),jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(ToolApprovalBanner,{pendingApprovals:Au,onReview:Pu=>Iu(Pu),onApproveAll:async()=>{if(lo)for(const Pu of Au)await lo(Pu.id)}}),jsxRuntimeExports.jsx(ToolApprovalDialog,{isOpen:!!Ru,toolName:Ru?.toolName??"",toolDescription:Ru?.toolDescription,args:Ru?.args??{},onApprove:async()=>{if(!Ru||!lo){Iu(null);return}await lo(Ru.id)!==!1&&Iu(null)},onDeny:async()=>{if(!Ru||!$u){Iu(null);return}await $u(Ru.id,"Rejected from tool approval dialog")!==!1&&Iu(null)},onClose:()=>Iu(null)})]})}const halo=Au=>({position:"absolute",inset:0,borderRadius:"50%",bg:Au||"accent.emphasis",zIndex:-1,pointerEvents:"none",willChange:"transform, opacity"});function ButtonGlow({color:Au}){return jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(Box,{"aria-hidden":!0,"data-button-glow":"breath",sx:{...halo(Au),filter:"blur(10px)",animation:"agentRuntimesGlowBreath 3.4s ease-in-out infinite","@keyframes agentRuntimesGlowBreath":{"0%, 100%":{transform:"scale(0.9)",opacity:.35},"50%":{transform:"scale(1.25)",opacity:.7}},"@media (prefers-reduced-motion: reduce)":{animation:"none",transform:"scale(1.1)",opacity:.4}}}),jsxRuntimeExports.jsx(Box,{"aria-hidden":!0,"data-button-glow":"aura",sx:{...halo(Au),filter:"blur(18px)",animation:"agentRuntimesGlowAura 5.3s ease-in-out infinite","@keyframes agentRuntimesGlowAura":{"0%, 100%":{transform:"scale(1)",opacity:.15},"40%":{transform:"scale(1.55)",opacity:.4},"70%":{transform:"scale(1.3)",opacity:.25}},"@media (prefers-reduced-motion: reduce)":{animation:"none",transform:"scale(1.3)",opacity:.2}}})]})}const MARGIN=24;function useViewportDrag(Au,{whole:lo=!1}={}){const[$u,Ru]=reactExports.useState(null),Iu=reactExports.useRef(null),Pu=reactExports.useCallback(Mu=>{const Du=Au.current;if(!Du)return;const Lu=Du.getBoundingClientRect();Iu.current={dx:Mu.clientX-Lu.left,dy:Mu.clientY-Lu.top};const Bu=Mu.currentTarget;Bu.setPointerCapture?.(Mu.pointerId);const ju=zu=>{if(!Iu.current)return;const Uu=Math.min(Math.max(zu.clientX-Iu.current.dx,lo?0:MARGIN-Lu.width),window.innerWidth-(lo?Lu.width:MARGIN)),Hu=Math.min(Math.max(zu.clientY-Iu.current.dy,0),window.innerHeight-(lo?Lu.height:MARGIN));Ru({left:Uu,top:Hu})},Fu=()=>{Iu.current=null,Bu.removeEventListener("pointermove",ju),Bu.removeEventListener("pointerup",Fu),Bu.removeEventListener("pointercancel",Fu)};Bu.addEventListener("pointermove",ju),Bu.addEventListener("pointerup",Fu),Bu.addEventListener("pointercancel",Fu),Mu.preventDefault()},[Au,lo]),Ou=reactExports.useCallback(()=>Ru(null),[]);return{position:$u,onHandlePointerDown:Pu,reset:Ou}}const INK=loopColors.ink,INK_DARK=loopColors.inkDark;function Eyes({cx:Au,cy:lo,gap:$u,r:Ru,colours:Iu}){const Pu=Au-$u/2,Ou=Au+$u/2;return jsxRuntimeExports.jsxs("g",{children:[jsxRuntimeExports.jsx("circle",{cx:Pu,cy:lo,r:Ru,fill:Iu.white,stroke:Iu.ring,strokeWidth:1.5}),jsxRuntimeExports.jsx("circle",{cx:Ou,cy:lo,r:Ru,fill:Iu.white,stroke:Iu.ring,strokeWidth:1.5}),jsxRuntimeExports.jsxs("g",{className:"assistant-pupils",children:[jsxRuntimeExports.jsx("circle",{cx:Pu+Ru*.15,cy:lo+Ru*.1,r:Ru*.45,fill:Iu.pupil}),jsxRuntimeExports.jsx("circle",{cx:Ou+Ru*.15,cy:lo+Ru*.1,r:Ru*.45,fill:Iu.pupil}),jsxRuntimeExports.jsx("circle",{cx:Pu+Ru*.3,cy:lo-Ru*.1,r:Ru*.14,fill:Iu.white}),jsxRuntimeExports.jsx("circle",{cx:Ou+Ru*.3,cy:lo-Ru*.1,r:Ru*.14,fill:Iu.white})]}),jsxRuntimeExports.jsxs("g",{className:"assistant-lids",children:[jsxRuntimeExports.jsx("ellipse",{cx:Pu,cy:lo,rx:Ru+.5,ry:Ru+.5,fill:Iu.lid}),jsxRuntimeExports.jsx("ellipse",{cx:Ou,cy:lo,rx:Ru+.5,ry:Ru+.5,fill:Iu.lid})]})]})}const PAPER_CLIP={light:{wire:"#7A808A",shine:"#E3E6EB",line:INK,eye:{white:loopColors.white,ring:INK,pupil:INK,lid:"#B8BDC6"}},dark:{wire:"#C9CED6",shine:"#8D93A0",line:INK_DARK,eye:{white:INK_DARK,ring:loopColors.grayDark,pupil:INK,lid:"#8D93A0"}}},WIZARD={light:{hat:"#6E5CD6",brim:"#4A3C9E",robe:"#5B4BB7",face:"#F2D3B3",beard:"#F4F4F6",beardEdge:"#7A808A",star:"#F8D469",eye:{white:loopColors.white,ring:INK,pupil:INK,lid:"#F2D3B3"}},dark:{hat:"#9C88F0",brim:"#7B67DB",robe:"#8F7CE8",face:"#E8C4A0",beard:"#E4E4EA",beardEdge:loopColors.grayDark,star:"#F8D469",eye:{white:INK_DARK,ring:INK,pupil:INK,lid:"#E8C4A0"}}},CAT={light:{fur:"#F4A261",edge:"#B4571A",tail:"#E08A45",ear:"#F6A5C1",nose:"#B83A6B",whiskers:INK,eye:{white:loopColors.white,ring:INK,pupil:INK,lid:"#F4A261"}},dark:{fur:"#F4A261",edge:"#F4A261",tail:"#E08A45",ear:"#F6A5C1",nose:"#B83A6B",whiskers:INK_DARK,eye:{white:INK_DARK,ring:INK,pupil:INK,lid:"#F4A261"}}},LOOP_EYES={light:{eye:{white:loopColors.white,ring:INK,pupil:INK,lid:"#E3E6EB"}},dark:{eye:{white:INK_DARK,ring:INK_DARK,pupil:loopColors.black,lid:loopColors.grayDark}}};function PaperClip({size:Au,mode:lo="light"}){const $u=PAPER_CLIP[lo],Ru="M40 86 L40 30 Q40 14 52 14 Q64 14 64 30 L64 74 Q64 82 56 82 Q48 82 48 74 L48 36";return jsxRuntimeExports.jsx("svg",{width:Au,height:Au,viewBox:"0 0 96 96",role:"img","aria-label":"Paper clip","data-assistant-mode":lo,children:jsxRuntimeExports.jsxs("g",{className:"assistant-body",children:[jsxRuntimeExports.jsx("path",{d:Ru,fill:"none",stroke:$u.wire,strokeWidth:6,strokeLinecap:"round",strokeLinejoin:"round"}),jsxRuntimeExports.jsx("path",{d:Ru,fill:"none",stroke:$u.shine,strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"}),jsxRuntimeExports.jsx("path",{d:"M36 22 Q42 18 47 21",stroke:$u.line,strokeWidth:2,fill:"none",strokeLinecap:"round"}),jsxRuntimeExports.jsx("path",{d:"M57 21 Q62 18 68 22",stroke:$u.line,strokeWidth:2,fill:"none",strokeLinecap:"round"}),jsxRuntimeExports.jsx(Eyes,{cx:52,cy:30,gap:16,r:6.5,colours:$u.eye}),jsxRuntimeExports.jsx("path",{className:"assistant-mouth",d:"M48 44 Q52 47 56 44",stroke:$u.line,strokeWidth:2,fill:"none",strokeLinecap:"round"})]})})}function Wizard({size:Au,mode:lo="light"}){const $u=WIZARD[lo];return jsxRuntimeExports.jsx("svg",{width:Au,height:Au,viewBox:"0 0 96 96",role:"img","aria-label":"Wizard","data-assistant-mode":lo,children:jsxRuntimeExports.jsxs("g",{className:"assistant-body",children:[jsxRuntimeExports.jsx("path",{d:"M34 58 Q48 52 62 58 Q70 74 76 92 Q48 98 20 92 Q26 74 34 58 Z",fill:$u.robe}),jsxRuntimeExports.jsx("path",{d:"M21 90 Q48 96 75 90 L76 92 Q48 98 20 92 Z",fill:$u.brim}),jsxRuntimeExports.jsx("circle",{cx:30,cy:82,r:1.6,fill:$u.star}),jsxRuntimeExports.jsx("circle",{cx:67,cy:78,r:1.3,fill:$u.star}),jsxRuntimeExports.jsx("ellipse",{cx:48,cy:46,rx:13,ry:12,fill:$u.face}),jsxRuntimeExports.jsx("path",{d:"M33 38 Q31 66 40 77 Q48 89 56 77 Q65 66 63 38 Q61 50 56 53 Q48 58 40 53 Q35 50 33 38 Z",fill:$u.beard,stroke:$u.beardEdge,strokeWidth:1,strokeLinejoin:"round"}),jsxRuntimeExports.jsx("path",{className:"assistant-mouth",d:"M44 59 Q48 62 52 59",stroke:INK,strokeWidth:1.8,fill:"none",strokeLinecap:"round"}),jsxRuntimeExports.jsx("path",{d:"M39 55 Q44 51 48 54 Q52 51 57 55 Q52 57 48 56 Q44 57 39 55 Z",fill:$u.beard,stroke:$u.beardEdge,strokeWidth:.8}),jsxRuntimeExports.jsx("path",{d:"M25 36 Q35 26 39 14 Q43 2 58 3 Q50 8 53 18 Q58 30 71 36 Q48 30 25 36 Z",fill:$u.hat}),jsxRuntimeExports.jsx("path",{d:"M18 37 Q48 27 78 37 Q48 45 18 37 Z",fill:$u.brim}),jsxRuntimeExports.jsx("path",{d:"M47 17 l1.8 3.6 4 .6 -2.9 2.8 .7 4 -3.6 -1.9 -3.6 1.9 .7 -4 -2.9 -2.8 4 -.6 Z",fill:$u.star}),jsxRuntimeExports.jsx("circle",{cx:56,cy:28,r:1.4,fill:$u.star}),jsxRuntimeExports.jsx(Eyes,{cx:48,cy:46,gap:11,r:4,colours:$u.eye})]})})}function Cat({size:Au,mode:lo="light"}){const $u=CAT[lo],Ru="M70 84 Q90 78 84 58";return jsxRuntimeExports.jsx("svg",{width:Au,height:Au,viewBox:"0 0 96 96",role:"img","aria-label":"Cat","data-assistant-mode":lo,children:jsxRuntimeExports.jsxs("g",{className:"assistant-body",children:[jsxRuntimeExports.jsx("path",{d:Ru,stroke:$u.edge,strokeWidth:8,fill:"none",strokeLinecap:"round"}),jsxRuntimeExports.jsx("path",{d:Ru,stroke:$u.tail,strokeWidth:5,fill:"none",strokeLinecap:"round"}),jsxRuntimeExports.jsx("ellipse",{cx:48,cy:78,rx:24,ry:14,fill:$u.fur,stroke:$u.edge,strokeWidth:1.5}),jsxRuntimeExports.jsx("path",{d:"M24 30 L28 8 L42 22 Z",fill:$u.fur,stroke:$u.edge,strokeWidth:1.5,strokeLinejoin:"round"}),jsxRuntimeExports.jsx("path",{d:"M72 30 L68 8 L54 22 Z",fill:$u.fur,stroke:$u.edge,strokeWidth:1.5,strokeLinejoin:"round"}),jsxRuntimeExports.jsx("path",{d:"M28 26 L30 14 L38 22 Z",fill:$u.ear}),jsxRuntimeExports.jsx("path",{d:"M68 26 L66 14 L58 22 Z",fill:$u.ear}),jsxRuntimeExports.jsx("circle",{cx:48,cy:42,r:24,fill:$u.fur,stroke:$u.edge,strokeWidth:1.5}),jsxRuntimeExports.jsx(Eyes,{cx:48,cy:38,gap:18,r:6.5,colours:$u.eye}),jsxRuntimeExports.jsx("path",{d:"M45 48 L51 48 L48 52 Z",fill:$u.nose}),jsxRuntimeExports.jsx("path",{className:"assistant-mouth",d:"M43 55 Q48 58 53 55",stroke:INK,strokeWidth:2,fill:"none",strokeLinecap:"round"}),jsxRuntimeExports.jsx("path",{d:"M30 48 L18 46 M30 52 L18 54 M66 48 L78 46 M66 52 L78 54",stroke:$u.whiskers,strokeWidth:1.2,strokeLinecap:"round"})]})})}function LoopEyes({size:Au,mode:lo="light"}){const $u=LOOP_EYES[lo];return jsxRuntimeExports.jsx("svg",{width:Au,height:Au,viewBox:"0 0 96 96",role:"img","aria-label":"L👀P eyes","data-assistant-mode":lo,children:jsxRuntimeExports.jsxs("g",{className:"assistant-body",children:[jsxRuntimeExports.jsx(Eyes,{cx:48,cy:50,gap:40,r:18,colours:$u.eye}),jsxRuntimeExports.jsx("path",{className:"assistant-mouth",d:"M42 80 Q48 84 54 80",stroke:lo==="dark"?INK_DARK:INK,strokeWidth:2.5,fill:"none",strokeLinecap:"round",opacity:0})]})})}const eyeOf=(Au,lo)=>({white:Au.white,ring:Au.ring,pupil:Au.pupil,on:lo}),ASSISTANT_CHARACTERS=[{id:"paperclip",name:"Paper clip",Drawing:PaperClip,keyColours:{light:{edges:[PAPER_CLIP.light.wire,PAPER_CLIP.light.line],eye:eyeOf(PAPER_CLIP.light.eye,"page")},dark:{edges:[PAPER_CLIP.dark.wire,PAPER_CLIP.dark.line],eye:eyeOf(PAPER_CLIP.dark.eye,"page")}}},{id:"wizard",name:"Wizard",Drawing:Wizard,keyColours:{light:{edges:[WIZARD.light.hat,WIZARD.light.brim,WIZARD.light.robe,WIZARD.light.beardEdge],eye:eyeOf(WIZARD.light.eye,WIZARD.light.face)},dark:{edges:[WIZARD.dark.hat,WIZARD.dark.brim,WIZARD.dark.robe,WIZARD.dark.beardEdge],eye:eyeOf(WIZARD.dark.eye,WIZARD.dark.face)}}},{id:"cat",name:"Cat",Drawing:Cat,keyColours:{light:{edges:[CAT.light.edge,CAT.light.whiskers],eye:eyeOf(CAT.light.eye,CAT.light.fur)},dark:{edges:[CAT.dark.edge,CAT.dark.whiskers],eye:eyeOf(CAT.dark.eye,CAT.dark.fur)}}},{id:"eyes",name:"L👀P eyes",Drawing:LoopEyes,keyColours:{light:{edges:[LOOP_EYES.light.eye.ring],eye:eyeOf(LOOP_EYES.light.eye,"page")},dark:{edges:[LOOP_EYES.dark.eye.white],eye:eyeOf(LOOP_EYES.dark.eye,"page")}}}],DEFAULT_ASSISTANT_CHARACTER="paperclip";function assistantCharacter(Au){const lo=ASSISTANT_CHARACTERS.find($u=>$u.id===Au);if(!lo)throw new Error(`There is no assistant character "${Au}"; the characters are ${ASSISTANT_CHARACTERS.map($u=>$u.id).join(", ")}.`);return lo}const DEFAULT_DECISION_NAME="Answer",DEFAULT_SCORE_RANGE={from:1,to:5},MAX_SCORE_STEPS=11;function scoreSteps(Au){const lo=[];for(let $u=Au.from;$u<=Au.to;$u+=1)lo.push(String($u));return lo}function decisionAskProblem(Au){if(!Au.situation.trim())return"Say the situation the question is about.";if(!Au.question.trim())return"Ask a question.";if(Au.type==="choice"){const lo=(Au.options??[]).filter($u=>$u.trim());if(lo.length<2)return"A choice needs at least two options.";if(new Set(lo.map($u=>$u.trim())).size!==lo.length)return"Two options are the same."}if(Au.type==="score"){const lo=Au.range??DEFAULT_SCORE_RANGE;if(!Number.isInteger(lo.from)||!Number.isInteger(lo.to))return"A score goes from a whole number to another.";if(lo.to<=lo.from)return"A score goes from a lower number to a higher one.";if(lo.to-lo.from+1>MAX_SCORE_STEPS)return`A score has at most ${MAX_SCORE_STEPS} steps.`}}function decisionRequest(Au){const lo=Au.type==="choice"?(Au.options??[]).map($u=>$u.trim()).filter(Boolean):Au.type==="score"?scoreSteps(Au.range??DEFAULT_SCORE_RANGE):[];return{state:Au.situation.trim(),questions:[{name:Au.name?.trim()||DEFAULT_DECISION_NAME,type:Au.type,instructions:Au.question.trim(),options:lo}]}}function confidenceWords(Au){return String(Number(Au.toFixed(2)))}function decisionAnswerWords(Au,lo,$u=[]){if(typeof lo.probability=="number"&&lo.choice===void 0){const Iu=lo.probability>=.5;return`${Au}: ${Iu?"yes":"no"} (${confidenceWords(Iu?lo.probability:1-lo.probability)})`}const Ru=typeof lo.confidence=="number"?` (${confidenceWords(lo.confidence)})`:"";if(typeof lo.score=="number"){const Iu=$u.length?$u:Object.keys(lo.legend??{}).sort((Du,Lu)=>Number(Du)-Number(Lu)).map(Du=>lo.legend?.[Du]??Du),Pu=lo.legend?.[String(lo.score)]??Iu[lo.score],Ou=Iu[Iu.length-1],Mu=Iu.length>0&&Iu.every(Du=>/^-?\d+$/.test(Du.trim()));return`${Au}: ${Pu??lo.score+1}${Mu&&Ou!==void 0?` of ${Ou}`:""}${Ru}`}return typeof lo.choice=="string"?`${Au}: ${lo.choice}${Ru}`:`${Au}: no answer`}function decisionResponseWords(Au,lo){if(lo.refusal)return lo.refusal;const[$u]=Au.questions,Ru=lo.answers?.[$u.name];return Ru?decisionAnswerWords($u.name,Ru,$u.options):"Nothing was decided: the answer did not come back."}function decisionsAskerAt(Au,lo){const $u=Au.replace(/\/+$/,"");return async Ru=>{let Iu;try{Iu=await fetch(`${$u}/api/v1/configure/inference/decisions`,{method:"POST",headers:{"Content-Type":"application/json",...lo?{Authorization:`Bearer ${lo}`}:{}},body:JSON.stringify(Ru)})}catch{return{refusal:"Nothing was decided: the runtime could not be reached."}}if(!Iu.ok){let Pu="";try{const Ou=await Iu.json();Pu=typeof Ou.detail=="string"?Ou.detail:""}catch{}return{refusal:`Nothing was decided: the runtime refused it (${Iu.status})${Pu?`: ${Pu}`:"."}`}}return await Iu.json()}}const DECISION_WORDS={ask:"Ask a decision",asking:"Asking…",submit:"Ask",cancel:"Cancel",again:"Ask another",types:{noul:"Yes or no",choice:"A choice",score:"A score"}},LINK_SX={mt:1,p:0,border:0,bg:"transparent",color:"accent.fg",textDecoration:"underline",cursor:"pointer",fontSize:1};function DecisionAsk({ask:Au,onActiveChange:lo}){const[$u,Ru]=reactExports.useState(!1),[Iu,Pu]=reactExports.useState(""),[Ou,Mu]=reactExports.useState(""),[Du,Lu]=reactExports.useState(""),[Bu,ju]=reactExports.useState("noul"),[Fu,zu]=reactExports.useState(""),[Uu,Hu]=reactExports.useState(String(DEFAULT_SCORE_RANGE.from)),[Vu,Gu]=reactExports.useState(String(DEFAULT_SCORE_RANGE.to)),[Wu,Ku]=reactExports.useState(),[Ju,Yu]=reactExports.useState(!1),[Xu,ed]=reactExports.useState(),td=reactExports.useRef(lo);td.current=lo,reactExports.useEffect(()=>()=>td.current?.(!1),[]);const nd=ad=>{Ru(ad),lo?.(ad)},od=()=>{ed(void 0),Ku(void 0),nd(!1)};if(!$u)return jsxRuntimeExports.jsx(Box,{as:"button",type:"button","data-balloon-ask-decision":"",onClick:()=>nd(!0),...LINK_SX,display:"block",children:DECISION_WORDS.ask});if(Xu!==void 0)return jsxRuntimeExports.jsxs(Box,{"data-balloon-decision":"answered",mt:2,children:[jsxRuntimeExports.jsx(Text$3,{as:"p","data-decision-answer":"",sx:{m:0,fontWeight:"semibold"},children:Xu}),jsxRuntimeExports.jsxs(Box,{display:"flex",gap:2,mt:2,children:[jsxRuntimeExports.jsx(ButtonComponent,{size:"small",onClick:()=>ed(void 0),children:DECISION_WORDS.again}),jsxRuntimeExports.jsx(ButtonComponent,{size:"small",variant:"invisible",onClick:od,children:DECISION_WORDS.cancel})]})]});const sd=async()=>{const ad={situation:Iu,question:Ou,type:Bu,name:Du,options:Fu.split(`
|
|
3673
|
+
...`:lo}catch{return"Tool completed successfully."}}function parseEnabledMcpToolsByServer(Au){if(!Au||typeof Au!="object")return null;const lo=Au.enabled_tools_by_server;if(lo==null)return new Map;if(typeof lo!="object")return new Map;const $u=new Map;for(const[Ru,Iu]of Object.entries(lo)){if(!Array.isArray(Iu))continue;const Ou=Iu.filter(Mu=>typeof Mu=="string"&&Mu.length>0).map(Mu=>{const Du=Mu.indexOf("__");return Du>=0?Mu.slice(Du+2):Mu});$u.set(Ru,new Set(Ou))}return $u}function parseApprovedMcpToolsByServer(Au){if(!Au||typeof Au!="object")return null;const lo=Au.approved_tools_by_server;if(lo==null)return new Map;if(typeof lo!="object")return new Map;const $u=new Map;for(const[Ru,Iu]of Object.entries(lo)){if(!Array.isArray(Iu))continue;const Ou=Iu.filter(Mu=>typeof Mu=="string"&&Mu.length>0).map(Mu=>{const Du=Mu.indexOf("__");return Du>=0?Mu.slice(Du+2):Mu});$u.set(Ru,new Set(Ou))}return $u}const WELCOME_AT=new Date(0);function ChatBase(Au){const{agentRuntimeConfig:lo,protocol:$u,useStore:Ru=!0,disableInternalJupyterTheme:Iu=!1,themeVariant:Pu,colorMode:Ou,themeOverrides:Mu}=Au,Bu=lo?{type:(typeof $u=="string"?$u:void 0)||lo.protocol||"vercel-ai",endpoint:lo.url,authToken:lo.authToken,agentId:lo.agentId,enableConfigQuery:!0,configEndpoint:`${lo.url}/api/v1/config`}:typeof $u=="object"?$u:void 0,ju=lo?!1:Ru,Fu=reactExports.useContext(QueryClientContext),zu={...Au,protocol:Bu,useStore:ju},Uu=jsxRuntimeExports.jsx(ChatBaseInner,{...zu}),Hu=Iu?Uu:jsxRuntimeExports.jsx(ThemedChatBoundary,{themeVariant:Pu,colorMode:Ou,themeOverrides:Mu,children:Uu});return Fu?Hu:jsxRuntimeExports.jsx(QueryClientProvider,{client:internalQueryClient,children:Hu})}function ChatBaseInner({title:Au,subtitle:lo,showHeader:$u=!1,showTokenUsage:Ru=!0,showContextRing:Iu=!1,showLoadingIndicator:Pu=!0,showErrors:Ou=!0,showInput:Mu=!0,showModelSelector:Du=!0,showToolsMenu:Lu=!0,showSkillsMenu:Bu=!0,disableInputPrompt:ju=!1,promptVariant:Fu,mentionableAgents:zu,promptCommands:Uu,showAgentsMenu:Hu=!0,agents:Vu,selectedAgentId:Gu,onSelectAgent:Wu,disabled:Ku,disableReason:Ju,overlay:Yu,launching:Xu=!1,launchingMessage:ed,autoConnect:td=!0,codemodeEnabled:nd=!1,onToggleCodemode:od,initialModel:sd,availableModels:ad,mcpServers:pd,initialSkills:gd,className:xd,loadingState:yd,headerActions:bd,kernelIndicatorState:wd,kernelIndicatorPlacement:kd="left",kernel:cd,kernelEnvironmentName:dd,kernelCpu:md,kernelMemory:ld,kernelGpu:hd,themeVariant:vd,colorMode:Sd,chatViewMode:Td,onChatViewModeChange:Rd,disabledViewModes:Od,useStore:Bd=!0,protocol:Ed,onSendMessage:Ad,onSendReady:Id,onLoadingChange:Wd,onContextSnapshot:Dd,enableStreaming:Hd=!1,brandIcon:nh,avatarConfig:Xd,headerButtons:mh,showPoweredBy:uh=!1,poweredByProps:Sh,emptyState:yh,renderHeader:eh,showTurnFooter:rh=!0,notebookToolSurfacesId:dh,footerContent:Dh,welcome:Vd,trailingContent:Ud,voice:$d,voiceSpeaking:Pd=!1,onStopSpeaking:Gd,showInformation:Nd=!1,onInformationClick:Kd,headerContent:Qd,children:gh,borderRadius:xh,backgroundColor:wh,border:Kh,boxShadow:Md,compact:_d=!1,placeholder:qd,description:Fd="Start a conversation with the AI agent.",onStateUpdate:sh,onNewChat:Eh,onClear:Ch,onMessagesChange:kh,onItemsChange:Ph,onDisplayItemsChange:zh,autoFocus:jh=!1,suggestions:Zh,submitOnSuggestionClick:Oh=!0,hideMessagesAfterToolUI:np=!1,focusTrigger:rp,frontendTools:dp,enableEphemeralNotebook:gp=!1,initialEphemeralNotebookOpen:Qh=!0,onEphemeralNotebookOpenChange:xp,enableEphemeralDocument:ip=!1,initialEphemeralSurfaceMode:cp,onEphemeralSurfaceModeChange:Hh,collapsed:Fh=!1,onExpandFromCollapsed:Xh,ephemeralNotebookToolbar:zf,ephemeralNotebookToolbarExtraItems:Rp,ephemeralDocumentToolbarExtraItems:Rh,ephemeralNotebookCollaborationProvider:Bh,ephemeralNotebookCollaborationDocumentId:hf,ephemeralDocumentCollaboration:jp,ephemeralRuntimeOverride:Qp,onToolCallStart:ef,onToolCallComplete:ep,inspector:Vp,onAuthorizationRequired:Uf,connectedIdentities:om,runtimeId:Fp,thread:Tf,historyEndpoint:Kf,historyAuthToken:bp,pendingPrompt:Ip,contextSnapshot:Sp,mcpStatusData:Gp,sandboxStatusData:Nf,showToolApprovalBanner:Wp=!0,pendingApprovals:zp,onApproveApproval:yp,onRejectApproval:mm}){const of=useChatWords();reactExports.useEffect(()=>{setupPrimerPortals()},[]);const gm=useChatAvailability(),Pf=Ku??gm.disabled,Xm=Ju??gm.disableReason,{theme:_f}=useThemeStore(),km=getColorPalette(_f,"dark").textLight,vm=useAgentRuntimeStore(jd=>jd.approvals),kf=useAgentRuntimeStore(jd=>jd.historyVersion),Lh=useAgentRuntimeStore(jd=>jd.mcpStatus),zd=Gp??Lh,ih=typeof Ed=="object"?Ed:void 0,Nh=useCoreStore(jd=>jd.configuration?.aiAgentsUrl),fh=ih?.agentId||Fp,qh=Fp||fh,sp=ih?.authToken,Dp=reactExports.useRef(`ephemeral-notebook-${Math.random().toString(36).slice(2,10)}`),kp=Fp||ih?.agentId||fh,sf=hf||(kp?`ephemeral-notebook-${kp}`:Dp.current),_p=useAgentRuntimeStore(jd=>jd.getEphemeralNotebookModel(sf)),Of=useAgentRuntimeStore(jd=>jd.setEphemeralNotebookModel),Jp=reactExports.useCallback(jd=>{Of(sf,jd)},[sf,Of]),Zf=jp?.roomId||(kp?`ephemeral-document-${kp}`:`ephemeral-document-${Dp.current}`),Yf=useAgentRuntimeStore(jd=>jd.getEphemeralDocumentModel(Zf)),xf=useAgentRuntimeStore(jd=>jd.setEphemeralDocumentModel),Am=reactExports.useCallback(jd=>{xf(Zf,jd)},[Zf,xf]),$m=cp??(gp&&Qh?"notebook":"none"),[wm,Lf]=reactExports.useState($m),Mf=reactExports.useCallback(jd=>{Lf(jd),Hh?.(jd),xp?.(jd==="notebook")},[Hh,xp]),im=gp&&wm==="notebook",Af=ip&&wm==="document",vp=im||Af,vf=vp&&Fh,$f=vf?{key:"ephemeral-surface",type:"custom",order:900,render:()=>jsxRuntimeExports.jsx(EphemeralSurfaceControl,{mode:wm,onChange:Mf,enableNotebook:gp,enableDocument:ip,enableChatOnly:!1})}:null,cm=$f?[...Rp??[],$f]:Rp,bm=$f?[...Rh??[],$f]:Rh,[Wh,Bp]=reactExports.useState(null);reactExports.useEffect(()=>{if(!im){Bp(null);return}const jd=()=>notebookStore.getState().selectNotebook(sf)?.adapter?.kernel??null,Zd=()=>{const ah=jd();Bp(bh=>bh?.id===ah?.id?bh:ah)};Zd();const Yd=window.setInterval(Zd,750),lh=notebookStore.subscribe(Zd);return()=>{window.clearInterval(Yd),lh()}},[im,sf]);const[Xp,Sf]=reactExports.useState(null),bf=reactExports.useCallback(jd=>{Sf(Zd=>Zd?.id===jd?.id?Zd:jd)},[]);reactExports.useEffect(()=>{Af||Sf(null)},[Af]);const wf=vp&&isFloatingChatViewMode(Td),um=Td==="floating-small"||Td==="floating-draggable",Up=useNotebookTools(sf),[Jf,Xf]=reactExports.useState([]),af=reactExports.useCallback(jd=>{Xf(jd)},[]),Yh=reactExports.useMemo(()=>im?[...dp||[],...Up]:Af?[...dp||[],...Jf]:dp,[im,Af,dp,Up,Jf]),Ep=reactExports.useMemo(()=>normalizeAiAgentsBaseUrl(Nh||DEFAULT_SERVICE_URLS.AI_AGENTS),[Nh]),pf=reactExports.useRef(null),Hf=reactExports.useRef(new Map),Df=reactExports.useCallback((jd,Zd,Yd)=>{const lh=pf.current;if(!lh||lh.readyState!==WebSocket.OPEN)return logApprovalTrace("send_decision_skipped_ws_not_ready",{approvalId:jd,approved:Zd,wsReadyState:lh?.readyState}),!1;try{return logApprovalTrace("send_decision",{approvalId:jd,approved:Zd,hasNote:!!Yd}),lh.send(JSON.stringify({type:"tool_approval_decision",approvalId:jd,approved:Zd,...Yd?{note:Yd}:{}})),!0}catch{return logApprovalTrace("send_decision_failed",{approvalId:jd,approved:Zd}),!1}},[]),zm=reactExports.useCallback(()=>{const jd=pf.current;if(!jd||jd.readyState!==WebSocket.OPEN)return!1;try{return jd.send(JSON.stringify({type:"tool-approvals-history"})),logApprovalTrace("request_history",{}),!0}catch{return!1}},[]),Um=reactExports.useCallback(jd=>{jd&&(Hf.current.set(jd,Date.now()+RESOLVED_TOOL_CALL_SUPPRESSION_MS),logApprovalTrace("suppress_pending_for_tool_call",{toolCallId:jd,windowMs:RESOLVED_TOOL_CALL_SUPPRESSION_MS}))},[]),X0=reactExports.useCallback(jd=>{if(!jd)return!1;const Zd=Hf.current.get(jd);return Zd?Zd<Date.now()?(Hf.current.delete(jd),!1):!0:!1},[]),Rm=reactExports.useCallback((jd,Zd,Yd)=>{window.setTimeout(()=>{if(!agentRuntimeStore.getState().approvals.some(bh=>bh.id===jd&&bh.status==="pending"))return;const ah=Df(jd,Zd,Yd);logApprovalTrace("retry_send_decision",{approvalId:jd,approved:Zd,sent:ah}),ah&&zm()},500)},[zm,Df]),Ag=reactExports.useMemo(()=>zp||vm.filter(jd=>jd.status==="pending"&&isApprovalForAgent(jd,fh)).map(jd=>({id:jd.id,toolName:jd.tool_name,toolDescription:jd.note??void 0,args:jd.tool_args??{},agentId:jd.agent_id??"",requestedAt:jd.created_at??new Date().toISOString()})),[zp,vm,fh]),r1=reactExports.useCallback((jd,Zd)=>{const Yd=agentRuntimeStore.getState().approvals.find(Vh=>Vh.id===jd),lh=Yd?.tool_name;if(!lh)return;const bh=(()=>{if(lh.startsWith("skill:")){const Uh=lh.slice(6);return Uh?normalizeSkillApprovalId(Uh):null}if(!new Set(["run_skill_script","load_skill","read_skill_resource"]).has(lh))return null;const hp=Yd?.tool_args??{},Gh=hp.skill_name??hp.skill??hp.name;return typeof Gh!="string"||!Gh?null:normalizeSkillApprovalId(Gh)})();if(bh){Rg(hp=>{const Gh=new Map(hp);return Gh.set(bh,Zd),Gh}),agentRuntimeStore.getState().sendRawMessage({type:Zd?"skill_approve":"skill_unapprove",skillId:bh},fh)||console.warn("[ChatBase] skill_approve persistence dropped: websocket not ready");return}const Ah=lh.indexOf("__");if(Ah!==-1){const Vh=lh.slice(0,Ah),hp=lh.slice(Ah+2);agentRuntimeStore.getState().sendRawMessage({type:"mcp_server_tool_approve",serverId:Vh,toolName:hp,approved:Zd},fh)||console.warn("[ChatBase] mcp_server_tool_approve persistence dropped: websocket not ready")}},[fh]),Q0=reactExports.useCallback(async(jd,Zd,Yd)=>{const ah=agentRuntimeStore.getState().approvals.find(Vh=>Vh.id===jd)?.tool_call_id??Yd;Um(ah);const bh=Df(jd,!0,Zd);bh||console.warn("[ChatBase] ai-agents tool_approval_decision not sent: websocket not ready");const Ah=agentRuntimeStore.getState().sendDecision(jd,!0,Zd,ah,fh);Ah?r1(jd,!0):console.warn("[ChatBase] tool_approval_decision dropped: websocket not ready"),(bh||Ah)&&agentRuntimeStore.getState().removeApproval(jd),zm(),Rm(jd,!0,Zd),await yp?.(jd,Zd)},[fh,Um,yp,r1,Rm,zm,Df]),D0=reactExports.useCallback(async(jd,Zd,Yd)=>{const ah=agentRuntimeStore.getState().approvals.find(Vh=>Vh.id===jd)?.tool_call_id??Yd;Um(ah);const bh=Df(jd,!1,Zd);bh||console.warn("[ChatBase] ai-agents tool_approval_decision not sent: websocket not ready");const Ah=agentRuntimeStore.getState().sendDecision(jd,!1,Zd,ah,fh);Ah||console.warn("[ChatBase] tool_approval_decision dropped: websocket not ready"),(bh||Ah)&&agentRuntimeStore.getState().removeApproval(jd),zm(),Rm(jd,!1,Zd),await mm?.(jd,Zd)},[fh,Um,mm,Rm,zm,Df]),n1=reactExports.useRef(null),eg=reactExports.useCallback(jd=>{const Zd=agentRuntimeStore.getState(),Yd=new Set([jd.id]),ah=!!jd.tool_name?approvalSignature(jd.tool_name,jd.tool_args??{}):null;for(const bh of Zd.approvals){if(bh.status!=="pending"||!isApprovalForAgent(bh,fh))continue;if(bh.id===jd.id){Yd.add(bh.id);continue}if(jd.tool_call_id&&bh.tool_call_id&&bh.tool_call_id===jd.tool_call_id){Yd.add(bh.id);continue}if(!ah||!bh.tool_name)continue;approvalSignature(bh.tool_name,bh.tool_args??{})===ah&&Yd.add(bh.id)}for(const bh of Yd)Zd.removeApproval(bh)},[fh]);reactExports.useEffect(()=>{if(!Wp||zp||!sp)return;const jd=toWsUrl(Ep,`${AI_AGENTS_API_PREFIX}/ws`,sp);if(!jd)return;let Zd=!1;const Yd=new WebSocket(jd);return pf.current=Yd,Yd.onopen=()=>{logApprovalTrace("ws_open_request_history",{activeAgentId:fh}),Yd.send(JSON.stringify({type:"tool-approvals-history"}))},Yd.onmessage=lh=>{try{const ah=JSON.parse(String(lh.data)),bh=[],Ah=typeof ah.type=="string"?ah.type:void 0,Vh=typeof ah.event=="string"?ah.event:void 0;if(Ah==="tool-approvals-history"){const Uh=(ah.data&&typeof ah.data=="object"?ah.data:{}).approvals;if(Array.isArray(Uh))for(const Jh of Uh)Jh&&typeof Jh=="object"&&bh.push(Jh)}else if(Vh?.startsWith("tool_approval_")){const Gh=ah.data&&typeof ah.data=="object"?ah.data:ah.payload&&typeof ah.payload=="object"?ah.payload:null;if(Gh){const Uh=statusFromApprovalEvent(Vh);logApprovalTrace("recv_tool_approval_event",{event:Vh,approvalId:typeof Gh.id=="string"?Gh.id:typeof Gh.approval_id=="string"?Gh.approval_id:void 0,status:typeof Gh.status=="string"?Gh.status:Uh}),bh.push(Uh&&typeof Gh.status!="string"?{...Gh,status:Uh}:Gh)}}if(bh.length===0)return;const hp=agentRuntimeStore.getState();for(const Gh of bh){let Uh=normalizeApprovalPayload(Gh);if(!Uh){const up=typeof Gh.id=="string"&&Gh.id||typeof Gh.approval_id=="string"&&Gh.approval_id||typeof Gh.approvalId=="string"&&Gh.approvalId||"",fp=typeof Gh.status=="string"&&Gh.status||"";if(up&&fp&&fp!=="pending"){const tf=hp.approvals.find(Vf=>Vf.id===up);tf&&(Uh={...tf,status:fp})}}if(!Uh)continue;const Jh=Uh.agent_id||!fh?Uh:{...Uh,agent_id:fh};if(isApprovalForAgent(Jh,fh)){if(Jh.status==="pending"&&X0(Jh.tool_call_id)){logApprovalTrace("drop_transient_pending",{approvalId:Jh.id,toolCallId:Jh.tool_call_id,status:Jh.status});continue}logApprovalTrace("apply_tool_approval_update",{approvalId:Jh.id,status:Jh.status,agentId:Jh.agent_id,activeAgentId:fh}),Jh.status==="pending"?hp.upsertApproval(Jh):(eg(Jh),n1.current?.(Jh,Jh.status==="approved",Jh.note??void 0))}}}catch{}},Yd.onclose=()=>{Zd||(pf.current=null)},Yd.onerror=()=>{pf.current=null},()=>{Zd=!0,pf.current=null,Yd.close()}},[Wp,zp,Ep,sp,fh,X0,eg]);const ap=typeof Ed=="object"?Ed:void 0,J1=ap?JSON.stringify(ap):"",$g="agent-runtimes",dm=useChatStore(jd=>jd.clearMessages),N0=ap?.type==="a2a",[Rf,Ap]=reactExports.useState([]),[u0,sm]=reactExports.useState(null),[X1,tg]=reactExports.useState(!1),[Im,x0]=reactExports.useState(!1),[rg,d0]=reactExports.useState(),[Q1,Hm]=reactExports.useState(!1),[ng,Pm]=reactExports.useState(null),[Em,L0]=reactExports.useState("");reactExports.useEffect(()=>{if(!cd){d0(void 0);return}d0(cd.status);const jd=(Zd,Yd)=>{d0(Yd)};return cd.statusChanged.connect(jd),()=>{cd.statusChanged.disconnect(jd)}},[cd]);const[h0,yf]=reactExports.useState(!qh),[Qm,B0]=reactExports.useState(0),j0=reactExports.useRef(new Map),og=reactExports.useRef(emptyUiModel()),S0=reactExports.useRef(new Set),[e0,b1]=reactExports.useState(!1),Mh=reactExports.useRef(null),Cp=Ip&&[Fp||Kf||ap?.endpoint||ap?.agentId,Ip].filter(Boolean).join("::"),[ff,hm]=reactExports.useState(""),[Kp,Om]=reactExports.useState(new Map),[p0,am]=reactExports.useState(new Map),[w0,y1]=reactExports.useState([]),qm=useAgentRuntimeWsState(),ig=!!ap?.enableConfigQuery&&td,Pp=useConfig(ig,ap?.configEndpoint,ap?.authToken,ap?.agentId),Ef=useSkills(ig&&Bu,ap?.configEndpoint,ap?.authToken),{enableSkill:Vm,disableSkill:F0,approveSkill:ev,unapproveSkill:tv}=useSkillActions(fh),[rv,Rg]=reactExports.useState(new Map);reactExports.useEffect(()=>{Rg(new Map)},[fh]);const o1=reactExports.useMemo(()=>{const jd=new Set;for(const Zd of Ef.data?.skills??[])(Zd.status==="enabled"||Zd.status==="loaded")&&jd.add(Zd.id);return jd},[Ef.data]);reactExports.useEffect(()=>{if(!fh||ym.current.has(fh))return;const jd=Ef.data?.skills??[];if(jd.length===0)return;if(jd.some(ah=>ah.status==="enabled"||ah.status==="loaded")){ym.current.add(fh);return}const Yd=jd.filter(ah=>ah.status==="available").map(ah=>ah.id).filter(Boolean);if(Yd.length===0){ym.current.add(fh);return}Yd.every(ah=>Vm(ah))&&ym.current.add(fh)},[fh,Ef.data,Vm]);const z0=reactExports.useMemo(()=>{const jd=new Set;for(const Zd of Ef.data?.skills??[])Zd.approved===!0&&jd.add(Zd.id);return rv.forEach((Zd,Yd)=>{Zd?jd.add(Yd):jd.delete(Yd)}),jd},[rv,Ef.data]),_1=reactExports.useMemo(()=>{const jd=Pp.data?.builtinTools??[],Zd=ap?.options?.frontendTools??[],Yd=new Set(jd.map(ah=>ah.name)),lh=[...Yh??[],...Zd].filter(ah=>Yd.has(ah.name)?!1:(Yd.add(ah.name),!0)).map(ah=>({id:ah.name,name:ah.name}));return{runtime:jd,frontend:lh}},[Pp.data?.builtinTools,Yh,ap?.options]),E0=reactExports.useMemo(()=>Vu??(fh?[{id:fh,name:Au||fh,description:lo||Fd}]:[]),[Vu,fh,Au,lo,Fd]),Ig=typeof ap?.options?.model=="string"?(ap?.options).model:void 0,U0=reactExports.useMemo(()=>{const jd=ad||Pp.data?.models||(Pp.isError?[]:void 0);return offeredModels(jd,()=>{const Zd=Object.values(AI_MODEL_CATALOGUE).filter(Yd=>Yd.available&&isChatModel(Yd)).map(Yd=>({id:Yd.id,name:Yd.name,provider:Yd.provider}));return Zd.length>0?Zd:Ig?[{id:Ig,name:Ig,provider:"inference"}]:[]})},[ad,Pp.data?.models,Pp.isError,Ig]),sg=reactExports.useMemo(()=>zu??E0.map(jd=>({name:jd.name,description:jd.description,icon:jd.icon,disabled:jd.id===(Gu??E0[0]?.id),disabledReason:`You are already talking to ${jd.name}`})),[zu,E0,Gu]),Pg=useContextSnapshot(ig&&Ru,ap?.configEndpoint,ap?.agentId,ap?.authToken),nv=reactExports.useMemo(()=>ap?.enableConfigQuery?void 0:{totalTokens:u0?.totalTokens??0,contextWindow:2e5,sumResponseInputTokens:u0?.sessionInput??0,sumResponseOutputTokens:u0?.sessionOutput??0,systemPromptTokens:0,userMessageTokens:0,assistantMessageTokens:0,toolTokens:0,toolCallTokens:0,toolReturnTokens:0,historyToolCallTokens:0,historyToolReturnTokens:0,currentToolCallTokens:0,currentToolReturnTokens:0,turnUsage:{inputTokens:u0?.turnInput??0,outputTokens:u0?.turnOutput??0,requests:0,toolCalls:0,toolNames:[],durationSeconds:0},sessionUsage:{inputTokens:u0?.sessionInput??0,outputTokens:u0?.sessionOutput??0,requests:0,toolCalls:0,turns:0,durationSeconds:0}},[u0,ap?.enableConfigQuery]),ov=reactExports.useRef(fh),H0=reactExports.useRef(null),Og=Pg.data,iv=reactExports.useRef(Og);iv.current=Og,reactExports.useEffect(()=>{ov.current!==fh&&(ov.current=fh,sm(null),H0.current=iv.current??null)},[fh]);const qv=Og&&Og!==H0.current?Og:void 0,x1=Sp??qv??nv;reactExports.useEffect(()=>{Dd?.(x1)},[x1,Dd]);const Vv=useSandbox(ig&&$u,ap?.configEndpoint,ap?.authToken,ap?.agentId),Mm=reactExports.useRef(null),sv=reactExports.useRef(null),lf=reactExports.useRef(new Map),Cm=reactExports.useRef(0),Qf=reactExports.useRef(null),i1=reactExports.useRef(new Set),ym=reactExports.useRef(new Set),ag=reactExports.useRef(new Set),C0=reactExports.useRef(!1),Mg=reactExports.useRef(np);Mg.current=np;const f0=reactExports.useRef(Tf?.id||generateMessageId()),S1=reactExports.useRef(Tf),q0=reactExports.useRef(Tf?.messages.length?Tf.id:null),av=reactExports.useCallback(()=>{const jd=f0.current;q0.current!==jd&&(q0.current=jd,S1.current?.onStarted?.(jd))},[]),V0=reactExports.useRef(null),m0=reactExports.useRef([]),lv=reactExports.useRef(new Set),pm=reactExports.useRef([]),s1=ap?.uiSocket,t0=reactExports.useRef(ap?.authToken);t0.current=ap?.authToken;const w1=ap?.uiFiles,Dg=reactExports.useCallback(jd=>w1?uploadFile(jd,{url:w1,scope:f0.current,token:t0.current}):Promise.reject(new Error("This conversation takes no file.")),[w1]),r0=reactExports.useCallback(jd=>{const Zd=Yd=>{try{return withUiOp(Yd,jd)}catch(lh){return console.error("[ChatBase] reactor.ui op not applied:",lh),Yd}};if(Ap(Yd=>Zd(Yd)),Bd){const Yd=useChatStore.getState();Yd.setMessages(Zd(Yd.messages))}},[Bd]),E1=reactExports.useCallback((jd,Zd)=>{if(Zd){if(jd.op==="window")return;if((jd.op==="show"||jd.op==="ask")&&isStepDisplay(jd.body)){lv.current.add(jd.body.id);return}if((jd.op==="patch"||jd.op==="append")&&lv.current.has(jd.id))return}let Yd;try{Yd=routeUiOp(jd,og.current,S0.current)}catch(ah){console.error("[ChatBase] reactor.ui op not applied:",ah);return}og.current=Yd.steps;const lh=Yd.routed;if(lh.to==="window")tellLoopWindow(lh.data);else if(lh.to==="step"){const ah=lh.step;Ap(bh=>withLoopStep(bh,ah))}else if(lh.to==="element")S0.current.add(lh.change.id),applyLoopElement(lh.change);else if(placeable(pm.current,lh.op))r0(lh.op);else{const ah=lh.op.op==="show"||lh.op.op==="ask"?lh.op.body.data?.message_id:void 0;if(Zd&&typeof ah=="string"){const bh={id:ah,role:"assistant",content:"",createdAt:new Date};pm.current=[...pm.current,bh],Ap(Ah=>Ah.some(Vh=>Vh.id===ah)?Ah:[...Ah,bh]),Bd&&useChatStore.getState().addMessage(bh),r0(lh.op)}else m0.current.push(lh.op)}},[r0,Bd]),cv=reactExports.useRef(E1);cv.current=E1,reactExports.useEffect(()=>{if(pm.current=Rf,m0.current.length===0)return;const jd=m0.current.splice(0);let Zd=Rf;for(const Yd of jd){if(!placeable(Zd,Yd)){m0.current.push(Yd);continue}try{Zd=withUiOp(Zd,Yd)}catch{}r0(Yd)}},[Rf,r0]);const C1=reactExports.useCallback(()=>{if(!s1)return null;const jd=f0.current,Zd=V0.current;if(Zd&&Zd.scope===jd)return Zd.socket;Zd?.socket.close(),og.current=emptyUiModel(),S0.current=new Set,m0.current=[],lv.current=new Set;const Yd=new UiSocket({url:s1,scope:jd,token:()=>t0.current??"",onOp:(lh,ah,bh)=>cv.current(lh,bh),onStatus:(lh,ah)=>{(lh==="refused"||lh==="gone")&&console.error(`[ChatBase] ui socket ${lh}: ${ah??""}`)}});return V0.current={socket:Yd,scope:jd},Yd.connect(),Yd},[s1]),T1=reactExports.useRef(C1);T1.current=C1,reactExports.useEffect(()=>(Tf?.messages.length&&T1.current(),()=>{V0.current?.socket.close(),V0.current=null}),[]);const Tm=reactExports.useRef(null),lg=reactExports.useRef(null),Dm=reactExports.useRef(null),cg=reactExports.useRef(null),T0=reactExports.useRef(!1),Nm=reactExports.useRef(om);Nm.current=om;const _m=reactExports.useRef(Yh);_m.current=Yh;const k0=reactExports.useRef(ef);k0.current=ef;const n0=reactExports.useRef(ep);n0.current=ep;const g0=useAgentInspectorTracer(),Lm=Vp??g0,uv=reactExports.useRef("Agent");uv.current=typeof Au=="string"&&Au||fh||"Agent";const Gm=reactExports.useRef(null);Lm&&Gm.current?.tracer!==Lm?Gm.current={tracer:Lm,recorder:chatSpanRecorder(Lm,()=>uv.current,{frontendTools:()=>(_m.current??[]).map(jd=>jd.name)})}:Lm||(Gm.current=null);const Ng=reactExports.useRef(""),k1=reactExports.useRef(null);reactExports.useEffect(()=>{let jd=agentRuntimeStore.getState().toolDecisionRequest?.seq??0;return agentRuntimeStore.subscribe(Zd=>Zd.toolDecisionRequest,Zd=>{if(!Zd||Zd.seq===jd)return;jd=Zd.seq;const Yd=k1.current;if(!Yd)return;const lh=Ah=>(Ah??"").toLowerCase().replace(/[-_]/g,""),ah=Array.from(lf.current.values()),bh=ah.find(Ah=>Ah.result?.approvalId===Zd.approvalId)??ah.find(Ah=>lh(Ah.toolName)===lh(Zd.toolName)&&(Ah.status==="executing"||Ah.status==="inProgress"));bh&&Yd(bh.toolCallId,{type:"tool-approval-decision",approved:Zd.approved,approvalId:Zd.approvalId,toolName:bh.toolName})})},[]);const qf=reactExports.useCallback((jd,Zd,Yd)=>{if(!jd?.id||i1.current.has(jd.id))return!1;let lh=jd.tool_call_id;if(!lh)for(const[bh,Ah]of lf.current.entries()){if(Ah.status!=="inProgress"&&Ah.status!=="executing")continue;const Vh=approvalSignature(Ah.toolName,Ah.args??{}),hp=approvalSignature(jd.tool_name,jd.tool_args??{});if(Vh===hp){lh=bh;break}}if(!lh)return!1;const ah=lf.current.get(lh);return!ah||ah.status!=="inProgress"&&ah.status!=="executing"?!1:(i1.current.add(jd.id),k1.current?.(lh,{type:"tool-approval-decision",approved:Zd,approvalId:jd.id,toolName:jd.tool_name||ah.toolName,_fromServerEcho:!0,_alreadyDispatched:!0,...Yd?{message:Yd}:{}}),!0)},[fh]);n1.current=qf;const mf=!!(ap?.endpoint&&/\/api\/runtimes\/v1\/agent-nodes\/[^/]+\/ag-ui\/?$/.test(ap.endpoint)),$p=ap?.configEndpoint?ap.configEndpoint.replace(/\/api\/v1\/(config|configure)\/?$/,""):ap?.endpoint?.replace(/\/api\/v1\/.*$/,"")??"";useAgentRuntimeWebSocket({enabled:!!ap&&!!$p&&!mf,baseUrl:$p,authToken:ap?.authToken,agentId:ap?.agentId,onMessage:jd=>{if(jd.type!=="tool_approval_created"&&jd.type!=="tool_approval_approved"&&jd.type!=="tool_approval_rejected")return;const Zd=jd.payload;if(Zd){if(jd.type==="tool_approval_created"){isApprovalForAgent(Zd,fh)&&agentRuntimeStore.getState().upsertApproval(Zd);return}eg(Zd),qf(Zd,jd.type==="tool_approval_approved",Zd.note??void 0)}}});const Bm=reactExports.useCallback(jd=>{if(!pd)return!0;const Zd=jd.isConfig===!1?"catalog":"config";return pd.some(Yd=>Yd.id===jd.id&&Yd.origin===Zd)},[pd]);reactExports.useEffect(()=>{if(jh&&Dm.current){const jd=setTimeout(()=>Dm.current?.focus(),100);return()=>clearTimeout(jd)}},[jh]),reactExports.useEffect(()=>{if(rp!==void 0&&rp>0&&Dm.current){const jd=setTimeout(()=>Dm.current?.focus(),150);return()=>clearTimeout(jd)}},[rp]);const jm=reactExports.useRef(!1);reactExports.useEffect(()=>{if(jm.current&&!Im&&Dm.current){const jd=setTimeout(()=>Dm.current?.focus(),50);return()=>clearTimeout(jd)}jm.current=Im},[Im]);const Lg=reactExports.useCallback(()=>{const jd=Dm.current;if(jd){jd.style.height="auto";const Zd=120,lh=Math.min(Math.max(jd.scrollHeight,40),Zd);jd.style.height=`${lh}px`,jd.style.overflowY=jd.scrollHeight>Zd?"auto":"hidden"}},[]);reactExports.useEffect(()=>{Lg()},[Em,Lg]),reactExports.useEffect(()=>{const jd=setTimeout(Lg,0);return()=>clearTimeout(jd)},[Lg]),reactExports.useEffect(()=>{if(U0.length===0||isOffered(U0,ff))return;const jd=initialModelId(U0,sd||Pp.data?.defaultModel||DEFAULT_MODEL);jd&&jd!==ff&&hm(jd)},[U0,ff,sd,Pp.data?.defaultModel]);const A0=reactExports.useRef(!1);reactExports.useEffect(()=>{if(U0.length>0&&!A0.current){A0.current=!0;const jd=Pp.data?.builtinTools?.map(Zd=>Zd.id)||[];if(y1(jd),Pp.data?.mcpServers){const Zd=new Map;for(const Yd of Pp.data.mcpServers)if(Yd.isAvailable&&Yd.enabled&&Bm(Yd)){const ah=new Set(Yd.tools.map(bh=>bh.name).filter(bh=>!!bh));Zd.set(Yd.id,ah)}Om(Zd)}}},[Pp.data,U0,ff,sd,ad,pd,Bm]),reactExports.useEffect(()=>{!Pp.data?.mcpServers||!pd||Om(jd=>{const Zd=new Map;for(const Yd of Pp.data?.mcpServers??[])if(Bm(Yd)&&jd.has(Yd.id)){const lh=jd.get(Yd.id);lh&&Zd.set(Yd.id,lh)}else if(Bm(Yd)&&Yd.isAvailable&&Yd.enabled){const lh=new Set(Yd.tools.map(ah=>ah.name).filter(ah=>!!ah));Zd.set(Yd.id,lh)}return Zd})},[pd,Pp.data?.mcpServers,Bm]);const G0=reactExports.useRef(pd);G0.current=pd,reactExports.useEffect(()=>{const jd=parseEnabledMcpToolsByServer(zd);if(!jd)return;const Zd=fh||"__global__",Yd=!ag.current.has(Zd)&&qm==="connected";Om(lh=>{const ah=new Map(lh);if(jd.forEach((bh,Ah)=>{(!G0.current||G0.current.some(hp=>hp.id===Ah))&&bh.size!==0&&ah.set(Ah,new Set(bh))}),Yd){const bh=[];for(const Vh of Pp.data?.mcpServers??[]){if(!(!G0.current||G0.current.some(Jh=>Jh.id===Vh.id))||!Vh.isAvailable||!Vh.enabled)continue;const Gh=Vh.tools.map(Jh=>Jh.name).filter(Jh=>!!Jh);if(Gh.length===0)continue;const Uh=ah.get(Vh.id);(!Uh||Uh.size===0)&&(ah.set(Vh.id,new Set(Gh)),bh.push({serverId:Vh.id,enabledToolNames:Gh}))}let Ah=!0;for(const Vh of bh)agentRuntimeStore.getState().sendRawMessage({type:"mcp_server_tools_set",serverId:Vh.serverId,enabledToolNames:Vh.enabledToolNames},fh)||(Ah=!1,console.warn("[ChatBase] initial mcp_server_tools_set dropped: websocket not ready"));Ah&&ag.current.add(Zd)}return ah})},[zd,fh,Pp.data?.mcpServers,qm]),reactExports.useEffect(()=>{const jd=parseApprovedMcpToolsByServer(zd);jd&&am(()=>{const Zd=new Map;return jd.forEach((Yd,lh)=>{(!G0.current||G0.current.some(bh=>bh.id===lh))&&Zd.set(lh,new Set(Yd))}),Zd})},[zd]);const dv=reactExports.useRef("");reactExports.useEffect(()=>{const jd=zd?.servers;if(!jd||jd.length===0)return;const Zd=jd.filter(bh=>bh.status==="started").map(bh=>bh.id).sort();if(Zd.length===0)return;const Yd=Pp.data?.mcpServers||[],lh=Zd.some(bh=>{const Ah=Yd.find(Vh=>Vh.id===bh);return!Ah||Ah.tools.length===0}),ah=Zd.join(",");lh&&ah!==dv.current&&Pp.refetch&&(dv.current=ah,Pp.refetch())},[zd,Pp]);const Bg=reactExports.useCallback((jd,Zd)=>{Om(Yd=>{const lh=new Map(Yd),ah=new Set(Yd.get(jd)||[]);return ah.has(Zd)?ah.delete(Zd):ah.add(Zd),lh.set(jd,ah),agentRuntimeStore.getState().sendRawMessage({type:"mcp_server_tools_set",serverId:jd,enabledToolNames:Array.from(ah)},fh)||console.warn("[ChatBase] mcp_server_tools_set dropped: websocket not ready"),lh})},[fh]),ug=reactExports.useCallback((jd,Zd,Yd)=>{Om(lh=>{const ah=new Map(lh),bh=Yd?new Set(Zd):new Set;return ah.set(jd,bh),agentRuntimeStore.getState().sendRawMessage({type:"mcp_server_tools_set",serverId:jd,enabledToolNames:Array.from(bh)},fh)||console.warn("[ChatBase] mcp_server_tools_set dropped: websocket not ready"),ah})},[fh]),hv=reactExports.useCallback(jd=>{o1.has(jd)?F0(jd):Vm(jd)},[o1,Vm,F0]),a1=reactExports.useCallback((jd,Zd)=>{for(const Yd of jd)Zd?Vm(Yd):F0(Yd)},[Vm,F0]),pv=reactExports.useCallback((jd,Zd)=>{am(Yd=>{const lh=new Map(Yd),ah=new Set(Yd.get(jd)??[]),bh=ah.has(Zd);return bh?ah.delete(Zd):ah.add(Zd),lh.set(jd,ah),agentRuntimeStore.getState().sendRawMessage({type:"mcp_server_tool_approve",serverId:jd,toolName:Zd,approved:!bh},fh)||console.warn("[ChatBase] mcp_server_tool_approve dropped: websocket not ready"),lh})},[fh]),dg=reactExports.useCallback(jd=>{z0.has(jd)?(Rg(Zd=>{const Yd=new Map(Zd);return Yd.set(jd,!1),Yd}),tv(jd)):(Rg(Zd=>{const Yd=new Map(Zd);return Yd.set(jd,!0),Yd}),ev(jd))},[z0,ev,tv]),o0=reactExports.useCallback(()=>{const jd=[];return Kp.forEach((Zd,Yd)=>{(!pd||pd.some(lh=>lh.id===Yd))&&Zd.forEach(lh=>jd.push(lh))}),jd},[Kp,pd]),$0=reactExports.useCallback(()=>Array.from(o1),[o1]);reactExports.useEffect(()=>{if(Bd&&!Fp){const jd=useChatStore.getState().messages;jd.length>0&&Ap(jd)}},[Bd,Fp]);const v0=reactExports.useRef(void 0),A1=reactExports.useRef(0),l1=reactExports.useRef(!1),hg=reactExports.useRef(null);reactExports.useEffect(()=>{if(qh!==v0.current&&(qh&&j0.current.set(qh,0),v0.current=qh,Ap([]),lf.current.clear(),!qh)||!qh)return;const jd=S1.current;if(jd){hg.current!==jd.id&&(hg.current=jd.id,useConversationStore.getState().setMessages(qh,jd.messages),Ap(convertHistoryToDisplayItems(jd.messages)),useConversationStore.getState().markFetched(qh),yf(!0));return}kf!==A1.current&&(A1.current=kf,kf>0&&(useConversationStore.getState().clearMessages(qh),Ap([]),lf.current.clear(),j0.current.set(qh,0),l1.current=!0));const Zd=useConversationStore.getState(),Yd=Zd.isFetching(qh),lh=Zd.getMessages(qh);if(lh.length>0&&(Ap(fp=>fp.length>0?fp:lh),yf(!0)),Yd)return;if(qm!=="connected"){lh.length===0&&yf(!1);return}Zd.setFetching(qh,!0);const ah=()=>extractChatMessagesFromFullContext(agentRuntimeStore.getState().fullContext),bh=fp=>{Zd.setMessages(qh,fp),Ap(convertHistoryToDisplayItems(fp)),j0.current.set(qh,0),Zd.markFetched(qh),yf(!0)},Ah=l1.current?[]:ah();if(l1.current=!1,Ah.length>0){bh(Ah);return}const Vh=()=>{const fp=[fh,ih?.agentId,Fp,qh,"default",void 0],tf=new Set;for(const Vf of fp){const gg=typeof Vf=="string"?Vf.trim():void 0,I0=gg||"__global__";if(tf.has(I0))continue;if(tf.add(I0),agentRuntimeStore.getState().requestRefresh(gg))return!0}return!1};if(!Vh()){Zd.setFetching(qh,!1),lh.length===0&&yf(!1);return}let Gh=!1;const Uh=window.setTimeout(()=>{Gh||Vh()},500),Jh=agentRuntimeStore.subscribe(fp=>fp.fullContext,fp=>{if(Gh||!fp)return;const tf=extractChatMessagesFromFullContext(fp);Gh=!0,Jh(),bh(tf)}),up=window.setTimeout(()=>{if(Gh)return;Gh=!0,Jh(),Zd.setFetching(qh,!1),yf(lh.length>0);const fp=j0.current.get(qh)??0;qm==="connected"&&fp<3?(j0.current.set(qh,fp+1),Vh(),B0(Vf=>Vf+1)):yf(!0)},2e3);return()=>{window.clearTimeout(Uh),window.clearTimeout(up),Jh()}},[qh,Kf,ap?.agentId,qm,fh,Qm,kf]),reactExports.useEffect(()=>{if(qh&&Rf.length>0){const jd=Rf.filter(Zd=>!isToolCallMessage(Zd));jd.length>0&&useConversationStore.getState().setMessages(qh,jd)}},[qh,Rf]);const pg=Rf.filter(jd=>!isToolCallMessage(jd)),W0=reactExports.useRef(0);reactExports.useEffect(()=>{const jd=pg.length;jd!==W0.current&&(W0.current=jd,kh?.(pg))},[Rf,pg,kh]),reactExports.useEffect(()=>{Ph?.(Rf.filter(jd=>!isToolCallMessage(jd)))},[Rf,Ph]),reactExports.useEffect(()=>{zh?.(Rf)},[Rf,zh]);const Bf=_d?2:3,$1=reactExports.useMemo(()=>{if(ap?.configEndpoint)return{apiBaseUrl:getApiBaseFromConfig(ap.configEndpoint),authToken:ap.authToken}},[ap?.configEndpoint,ap?.authToken]),Gv={userAvatar:jsxRuntimeExports.jsx(PersonIcon,{size:16}),assistantAvatar:jsxRuntimeExports.jsx(ForwardRef$2,{size:16,color:km}),showAvatars:!0,avatarSize:32,userAvatarBg:"neutral.muted",assistantAvatarBg:"accent.emphasis",...Xd};reactExports.useEffect(()=>{if(!ap||!td||Pf)return;const jd=createProtocolAdapter(ap);if(jd)return Mm.current=jd,b1(!0),sv.current=jd.subscribe(Zd=>{if(T1.current(),!(T0.current&&Zd.type!=="state-update"&&Zd.type!=="error"&&Zd.type!=="done"))switch(Zd.type){case"message":if(Zd.usage){const Yd=Zd.timestamp instanceof Date?Zd.timestamp.getTime():Date.now(),lh=Math.max(0,Zd.usage.promptTokens??0),ah=Math.max(0,Zd.usage.completionTokens??0),bh=Math.max(lh+ah,Zd.usage.totalTokens??0),Ah=agentRuntimeStore.getState();Ah.appendLocalTokenTurn({serviceName:$g,agentId:ap?.agentId,timestampMs:Yd,promptTokens:lh,completionTokens:ah,totalTokens:bh});const Vh=Ah.costUsage?.cumulativeCostUsd;typeof Vh=="number"&&Number.isFinite(Vh)&&Ah.upsertLocalCostPoint({serviceName:$g,agentId:ap?.agentId,timestampMs:Yd,cumulativeUsd:Math.max(0,Vh)})}if(C0.current){const Yd=Qf.current?.id;Yd&&(Ap(lh=>lh.filter(ah=>isToolCallMessage(ah)||ah.id!==Yd)),Bd&&useChatStore.getState().deleteMessage(Yd),Qf.current=null);break}if(Zd.message){const Yd=Zd.message.id,lh=Qf.current?.id;if(lh&&!(!lh||Yd&&Yd!==lh)){const bh=Zd.message.content,Ah=typeof bh=="string"?sanitizeAssistantContent(bh):bh??"";typeof Ah=="string"&&Ah&&(Ng.current=Ah),Ap(Vh=>{const hp=[...Vh],Gh=hp.findIndex(Uh=>!isToolCallMessage(Uh)&&Uh.id===lh);return Gh>=0&&!isToolCallMessage(hp[Gh])&&(hp[Gh]={...hp[Gh],content:Ah}),hp}),Bd&&useChatStore.getState().updateMessage(lh,{content:Ah})}else{const bh=Zd.message.content,Ah=typeof bh=="string"?bh:bh??"",Vh=typeof Ah=="string"?sanitizeAssistantContent(Ah):"",hp=createAssistantMessage(Vh);hp.id=Zd.message.id||hp.id,Qf.current=hp,Ap(Gh=>{const Uh=Gh.findIndex(Jh=>!isToolCallMessage(Jh)&&Jh.id===hp.id);if(Uh>=0){const Jh=[...Gh];return Jh[Uh]={...Jh[Uh],content:Vh},Jh}return[...Gh,hp]}),Bd&&(useChatStore.getState().messages.find(Uh=>Uh.id===hp.id)?useChatStore.getState().updateMessage(hp.id,{content:Vh}):useChatStore.getState().addMessage(hp))}}break;case"tool-call":if(Zd.toolCall&&!T0.current){const Yd=Zd.toolCall.toolCallId||generateMessageId(),lh=Zd.toolCall.toolName,ah=Zd.toolCall.args||{},bh=Zd.toolCall.argsComplete;if(lf.current.has(Yd)){const Ah=lf.current.get(Yd);if(Ah){const Vh={...Ah,args:{...Ah.args,...ah}};lf.current.set(Yd,Vh),Ap(Uh=>Uh.map(Jh=>isToolCallMessage(Jh)&&Jh.toolCallId===Yd?Vh:Jh));const Gh=_m.current?.find(Uh=>Uh.name===lh)?.handler;Gh&&Ah.status==="executing"&&(bh??Object.keys(ah).length>0)&&(Cm.current++,Wv(Gh,Vh,Yd))}}else{const Ah={id:`tool-${Yd}`,type:"tool-call",toolCallId:Yd,toolName:lh,args:ah,status:"executing"};lf.current.set(Yd,Ah),Ap(Gh=>[...Gh,Ah]),k0.current?.({toolName:lh,toolCallId:Yd,args:ah}),Gm.current?.recorder.toolStarted({id:Yd,name:lh,args:ah});const Vh=_m.current?.find(Gh=>Gh.name===lh),hp=Vh?.handler;hp&&(bh??(Object.keys(ah).length>0||!frontendToolExpectsArgs(Vh)))&&(Cm.current++,Wv(hp,Ah,Yd))}}break;case"tool-result":if(Zd.toolResult){const Yd=Zd.toolResult.toolCallId;if(Yd&&lf.current.has(Yd)){const lh=lf.current.get(Yd);if(lh){const ah=lh.args&&"steps"in lh.args&&Array.isArray(lh.args.steps),bh=Zd.toolResult.result;let Ah,Vh,hp,Gh=!1,Uh=!!Zd.toolResult.error;if(bh&&typeof bh=="object"){if("pending_approval"in bh&&bh.pending_approval===!0&&(Gh=!0),bh.execution_error&&typeof bh.execution_error=="string"&&(Ah=bh.execution_error,Uh=!0),bh.code_error&&typeof bh.code_error=="object"){const up=bh.code_error;Vh={name:up.name||"Error",value:up.value||"Unknown error",traceback:up.traceback},Uh=!0}if("exit_code"in bh){const up=bh.exit_code;hp=typeof up=="number"?up:null,hp!=null&&hp!==0&&(Uh=!0)}"execution_ok"in bh&&bh.execution_ok===!1&&(Uh=!0)}const Jh={...lh,result:Zd.toolResult.result,status:Uh?"error":Gh?"inProgress":ah?"executing":"complete",error:Zd.toolResult.error,executionError:Ah,codeError:Vh,exitCode:hp};lf.current.set(Yd,Jh),Ap(up=>up.map(fp=>isToolCallMessage(fp)&&fp.toolCallId===Yd?Jh:fp)),Gm.current?.recorder.toolEnded(Yd,{result:Zd.toolResult.result,error:Zd.toolResult.error??(Jh.status==="error"?Ah??"failed":void 0)}),n0.current?.({toolName:lh.toolName,toolCallId:Yd,args:lh.args,result:Zd.toolResult.result,status:Jh.status,error:Zd.toolResult.error})}}}break;case"state-update":if(sh?.(Zd.data),Zd.data){const Yd=Array.from(lf.current.entries()).filter(([lh,ah])=>ah.status==="executing");if(Yd.length>0){const[lh,ah]=Yd[Yd.length-1];if(!(ah.args&&"steps"in ah.args&&Array.isArray(ah.args.steps))){const Ah=Zd.data,Vh=Ah.weather??Ah.result??Ah.toolResult??Ah,hp={...ah,result:Vh,status:"complete"};lf.current.set(lh,hp),Ap(Gh=>Gh.map(Uh=>isToolCallMessage(Uh)&&Uh.toolCallId===lh?hp:Uh))}}}break;case"activity":break;case"done":{Gm.current?.recorder.turnEnded({text:Ng.current||void 0,usage:Zd.usage}),Ng.current="";const Yd=Zd.usage?.promptTokens??0,lh=Zd.usage?.completionTokens??0,ah=Zd.usage?.totalTokens??Yd+lh;ah>0&&sm(bh=>({turnInput:Yd,turnOutput:lh,sessionInput:(bh?.sessionInput??0)+Yd,sessionOutput:(bh?.sessionOutput??0)+lh,totalTokens:ah}))}C0.current&&Mg.current&&Ap(Yd=>{if(Yd.some(Ah=>!isToolCallMessage(Ah)&&Ah.role==="assistant"&&String(Ah.content||"").trim().length>0))return Yd;const ah=[...Yd].reverse().find(Ah=>isToolCallMessage(Ah)&&Ah.status==="complete"&&Ah.result!==void 0);if(!ah||!isToolCallMessage(ah))return Yd;const bh=createAssistantMessage(formatToolResultFallback(ah.result));return Bd&&useChatStore.getState().addMessage(bh),[...Yd,bh]}),C0.current=!1,Cm.current=0,x0(!1),Hm(!1),agentRuntimeStore.getState().requestRefresh(fh);break;case"error":console.error("[ChatBase] Protocol error:",Zd.error),Gm.current?.recorder.turnEnded({error:Zd.error?.message??"error"}),Zd.error?.message&&/exceeded maximum retries/i.test(Zd.error.message)&&Mg.current&&Ap(Yd=>{if(Yd.some(Ah=>!isToolCallMessage(Ah)&&Ah.role==="assistant"&&String(Ah.content||"").trim().length>0))return Yd;const ah=[...Yd].reverse().find(Ah=>isToolCallMessage(Ah)&&Ah.status==="complete"&&Ah.result!==void 0);if(!ah||!isToolCallMessage(ah))return Yd;const bh=createAssistantMessage(formatToolResultFallback(ah.result));return Bd&&useChatStore.getState().addMessage(bh),[...Yd,bh]}),C0.current=!1,Pm(Zd.error||new Error("Unknown error")),Cm.current=0,x0(!1),Hm(!1),agentRuntimeStore.getState().requestRefresh(fh);break}}),jd.connect().catch(console.error),()=>{sv.current?.(),Mm.current?.disconnect()}},[J1,sh,Bd,td]);function Wv(jd,Zd,Yd){(async()=>{if(T0.current){Cm.current--,Cm.current<0&&(Cm.current=0);return}try{const lh=await jd(Zd.args);Mm.current&&await Mm.current.sendToolResult(Yd,{toolCallId:Yd,success:!0,result:lh});const ah={...Zd,result:lh,status:"complete"};Gm.current?.recorder.toolEnded(Yd,{result:lh}),lf.current.set(Yd,ah),Ap(bh=>bh.map(Ah=>isToolCallMessage(Ah)&&Ah.toolCallId===Yd?ah:Ah))}catch(lh){console.error("[ChatBase] Frontend tool execution error:",lh);const ah={...Zd,status:"error",error:lh.message};Gm.current?.recorder.toolEnded(Yd,{error:lh.message}),lf.current.set(Yd,ah),Ap(bh=>bh.map(Ah=>isToolCallMessage(Ah)&&Ah.toolCallId===Yd?ah:Ah))}finally{Cm.current--,Cm.current<0&&(Cm.current=0)}})()}reactExports.useEffect(()=>{const jd=Tm.current;if(jd){jd.scrollTo({top:jd.scrollHeight,behavior:"smooth"});return}lg.current?.scrollIntoView({behavior:"smooth"})},[Rf]);const fv=reactExports.useRef(void 0),Kv=reactExports.useMemo(()=>$d&&$d.input!=="off"?new DeviceHearing($d.modelsUrl,$d.engines):void 0,[$d?.input,$d?.modelsUrl,$d?.engines]),Zp=reactExports.useCallback(async(jd,Zd,Yd)=>{const lh=(jd??Em).trim();if(!lh||Im||!Mm.current&&!Ad)return;if(Zd&&namesFiles(Zd))try{Zd=await withUploadedFiles(Zd,Dg)}catch(Uh){Pm(Uh instanceof Error?Uh:new Error(String(Uh)));return}const ah=displayPressOf(Zd);if(ah&&Zd){const Uh=V0.current?.socket;if(!Uh){Pm(new Error("This conversation’s ui channel is not open."));return}try{const Jh=await Uh.act(ah);if(!Jh.ok){Pm(new Error(Jh.detail||`The press was refused (${Jh.status}).`));return}Zd=withPress(Zd,Jh.value)}catch(Jh){Pm(Jh instanceof Error?Jh:new Error(String(Jh)));return}}T0.current=!1,Ng.current="",Gm.current?.recorder.turnStarted(lh,ff||void 0),C0.current=isToolCallOnlyPrompt(lh);const bh=Yd??(jd===void 0?fv.current:void 0);fv.current=void 0;const Ah=bh?{...Zd??{},voice:bh}:Zd,Vh=createUserMessage(lh,bh?{...bh}:void 0),Gh=[...Rf.filter(Uh=>!isToolCallMessage(Uh)),Vh];Ap(Uh=>[...Uh,Vh]),L0(""),x0(!0),Hm(!0),Pm(null),Qf.current=null,Bd&&useChatStore.getState().addMessage(Vh);try{if(Ad)if(Hd){const Uh=generateMessageId(),Jh=createAssistantMessage("");Jh.id=Uh,Ap(up=>[...up,Jh]),Qf.current=Jh,Bd&&(useChatStore.getState().addMessage(Jh),useChatStore.getState().startStreaming(Uh)),cg.current=new AbortController,await Ad(lh,Gh,{onChunk:up=>{Ap(fp=>fp.map(tf=>tf.id===Uh?{...tf,content:tf.content+up}:tf)),Bd&&useChatStore.getState().appendToStream(Uh,up)},onComplete:up=>{Ap(fp=>fp.map(tf=>tf.id===Uh?{...tf,content:up}:tf)),Bd&&(useChatStore.getState().updateMessage(Uh,{content:up}),useChatStore.getState().stopStreaming())},onError:up=>{const fp=of.error(up.message);Ap(tf=>tf.map(Vf=>Vf.id===Uh?{...Vf,content:fp}:Vf)),Bd&&(useChatStore.getState().updateMessage(Uh,{content:fp}),useChatStore.getState().stopStreaming()),Pm(up)},signal:cg.current.signal})}else{const Uh=await Ad(lh,Gh);if(Uh){const Jh=createAssistantMessage(Uh);Ap(up=>[...up,Jh]),Bd&&useChatStore.getState().addMessage(Jh)}}else if(Mm.current){const Uh=(Yh||[]).map(fp=>({name:fp.name,description:fp.description,parameters:fp.parameters||{type:"object",properties:{}}}));console.warn("[ChatBase] frontendTools count:",Yh?.length??0,"toolsForRequest:",Uh.map(fp=>fp.name));const Jh=o0(),up=$0();av(),await Mm.current.sendMessage(Vh,{threadId:f0.current,messages:Gh,...ff&&{model:ff},tools:Uh,builtinTools:Jh,skills:up,identities:Nm.current,...Ah?{forwardedProps:Ah}:{}})}}catch(Uh){if(Uh.name!=="AbortError"){console.error("[ChatBase] Send error:",Uh);const Jh=createAssistantMessage(of.error(Uh.message));Ap(up=>[...up,Jh]),Pm(Uh)}}finally{Mm.current||(x0(!1),Hm(!1),agentRuntimeStore.getState().requestRefresh(fh)),C0.current=!1,Qf.current=null,cg.current=null}},[Em,Im,Rf,ff,Yh,Bd,Ad,fh,Hd,o0,$0,av,of,Dg]);reactExports.useEffect(()=>{if(!Ip||Cp&&Mh.current===Cp)return;if(Cp&&sentPendingPromptKeys.has(Cp)){Mh.current=Cp;return}!h0&&!(!qh||qm!=="connected")||!e0&&!Ad||(Mh.current=Cp??null,Cp&&sentPendingPromptKeys.add(Cp),queueMicrotask(()=>Zp(Ip)))},[Ip,Cp,h0,qh,qm,e0,Zp,Ad,qf]);const c1=reactExports.useCallback(()=>{T0.current=!0,cg.current?.abort();const jd=Mm.current;jd&&(typeof jd.stopGeneration=="function"&&jd.stopGeneration(),typeof jd.terminateSession=="function"?jd.terminateSession().catch(()=>{}):typeof jd.terminateAgent=="function"?jd.terminateAgent().catch(()=>{}):typeof jd.terminateTask=="function"?jd.terminateTask().catch(()=>{}):typeof jd.terminateRequest=="function"&&jd.terminateRequest().catch(()=>{}));for(const[Zd,Yd]of lf.current.entries())(Yd.status==="executing"||Yd.status==="inProgress")&&lf.current.set(Zd,{...Yd,status:"error",error:"Interrupted by user"});Ap(Zd=>Zd.map(Yd=>!isToolCallMessage(Yd)||Yd.status!=="executing"&&Yd.status!=="inProgress"?Yd:{...Yd,status:"error",error:"Interrupted by user"})),Bd&&useChatStore.getState().stopStreaming(),Cm.current=0,x0(!1),Hm(!1),agentRuntimeStore.getState().requestRefresh(fh),agentRuntimeStore.getState().stopSubagentActivity(),C0.current=!1,Qf.current=null,Vv.interrupt(),cd&&cd.interrupt().catch(()=>{})},[cd,Bd,fh,ap?.configEndpoint,ap?.authToken,ap?.agentId]),u1=reactExports.useCallback(jd=>async Zd=>{const Yd=jd.actions?.find(bh=>bh.name===Zd.action);if(!Yd)throw new Error(`“${Zd.action}” was not offered here.`);const lh=Zd.payload?.value,ah=Zd.action===ANSWER_ACTION?typeof lh=="string"?lh:isFileRef(lh)?lh.name:"Answered.":Zd.action;await Zp(ah,{loop:{action:{name:Zd.action,display_id:jd.id,token:Yd.token,payload:Zd.payload??{}}}})},[Zp]),fg=reactExports.useCallback(()=>{Ap([]),lf.current.clear(),Cm.current=0,L0(""),f0.current=generateMessageId(),Bd&&dm(),qh&&useConversationStore.getState().clearMessages(qh),Eh?.(),mh?.onNewChat?.()},[dm,Eh,mh,Bd,Fp]);reactExports.useEffect(()=>{if(Id){if(!e0&&!Ad){Id(null);return}return Id({send:(jd,Zd)=>{Zp(jd,Zd)},stop:c1,newChat:fg,thread:()=>f0.current}),()=>{Id(null)}}},[Id,e0,Ad,Zp,c1,fg]),reactExports.useEffect(()=>{Wd?.(Im)},[Wd,Im]);const mv=reactExports.useCallback(()=>{window.confirm("Clear all messages?")&&(Ap([]),lf.current.clear(),Bd&&dm(),qh&&useConversationStore.getState().clearMessages(qh),Ch?.(),mh?.onClear?.())},[dm,Ch,mh,Bd,Fp]),jg=reactExports.useCallback(jd=>{const Zd=new Set(jd);Ap(Yd=>Yd.filter(lh=>!Zd.has(lh.id)));for(const[Yd,lh]of lf.current.entries())Zd.has(lh.id)&&lf.current.delete(Yd)},[]),mg=reactExports.useCallback(async(jd,Zd)=>{const Yd=lf.current.get(jd);if(Yd&&(Yd.status==="executing"||Yd.status==="inProgress")){if(!!Zd&&typeof Zd=="object"&&Zd.type==="tool-approval-decision"&&typeof Zd.approved=="boolean"&&Mm.current){const bh=Zd,Ah=!!bh.approved,Vh=bh._fromServerEcho===!0,hp=bh._alreadyDispatched===!0,Gh=Yd.status==="inProgress",Uh=typeof bh.toolName=="string"?bh.toolName:Yd.toolName,Jh=Uh.includes("__");if(Ah){const up=Uh.indexOf("__");if(up!==-1){const fp=Uh.slice(0,up),tf=Uh.slice(up+2);am(Vf=>{const gg=new Map(Vf),I0=new Set(Vf.get(fp)??[]);return I0.add(tf),gg.set(fp,I0),gg})}}try{const up=typeof Zd=="object"&&Zd!==null&&typeof Zd.approvalId=="string"?Zd.approvalId:void 0;if(!Vh&&!Gh){up&&(Ah?await Q0?.(up,void 0,jd):await D0?.(up,void 0,jd));return}if(up&&!hp&&(Ah?await Q0?.(up,void 0,jd):await D0?.(up,void 0,jd)),Jh&&!Gh)return;const fp={...Yd,result:Zd,status:Ah?"complete":"error",error:Ah?void 0:"Tool approval rejected by user"};lf.current.set(jd,fp),Ap(tf=>tf.map(Vf=>isToolCallMessage(Vf)&&Vf.toolCallId===jd?fp:Vf)),x0(!0),Hm(!0),await Mm.current.sendToolResult(jd,{toolCallId:jd,success:Ah,result:Ah?{approved:!0,message:"Tool call approved by user.",...up?{approvalId:up}:{}}:{approved:!1,message:"Tool call rejected by user.",...up?{approvalId:up}:{}},...Ah?{}:{error:"Tool approval rejected by user"}})}catch(up){console.error("[ChatBase] Approval continuation error:",up),Pm(up)}return}const ah={...Yd,result:Zd,status:"complete"};if(lf.current.set(jd,ah),Ap(bh=>bh.map(Ah=>isToolCallMessage(Ah)&&Ah.toolCallId===jd?ah:Ah)),Mm.current){let bh;if(typeof Zd=="string")bh=Zd;else if(Zd&&typeof Zd=="object"&&"accepted"in Zd){const Vh=Zd;if(Vh.accepted){const hp=Vh.steps?.map(Gh=>Gh.description).join(", ")||"";bh=hp?`I confirm and approve the following steps: ${hp}`:"I confirm and approve the plan."}else bh="I reject this plan. Please suggest something else."}else bh=JSON.stringify(Zd,null,2);const Ah={id:generateMessageId(),role:"user",content:bh,createdAt:new Date};x0(!0),Hm(!0);try{const Vh=Rf.filter(hp=>!isToolCallMessage(hp));await Mm.current.sendMessage(Ah,{threadId:f0.current,messages:[...Vh,Ah]})}catch(Vh){console.error("[ChatBase] HITL respond error:",Vh)}}}},[Rf,Q0,D0]);k1.current=mg;const Gb=reactExports.useCallback(jd=>{Zp(jd.message)},[Zp]),Zv=reactExports.useCallback(jd=>{L0(jd),setTimeout(()=>Dm.current?.focus(),0)},[]),Wb=reactExports.useCallback(async(jd,Zd)=>{await Q0?.(jd,Zd)},[Q0]),Yv=reactExports.useCallback(async(jd,Zd)=>{await D0?.(jd,Zd)},[D0]),R0=(Pp.data?.mcpServers||[]).filter(jd=>!pd||Bm(jd)),R1=reactExports.useMemo(()=>{const jd=R0.map(Yd=>{const lh=zd?.servers?.find(ah=>ah.id===Yd.id);if(lh&&lh.status==="started"){const ah={};if(Yd.isAvailable||(ah.isAvailable=!0),lh.tools&&lh.tools.length>0&&(ah.tools=lh.tools.map(bh=>({name:bh.name,description:bh.description||"",enabled:bh.enabled??!0}))),Object.keys(ah).length>0)return{...Yd,...ah}}return Yd}),Zd=new Set(R0.map(Yd=>Yd.id));for(const Yd of zd?.servers??[])Yd.status==="started"&&!Zd.has(Yd.id)&&Yd.tools&&Yd.tools.length>0&&(!pd||pd.some(ah=>ah.id===Yd.id))&&jd.push({id:Yd.id,name:Yd.id,description:"",url:"",enabled:!0,tools:Yd.tools.map(ah=>({name:ah.name,description:ah.description||"",enabled:ah.enabled??!0})),args:[],requiredEnvVars:[],isAvailable:!0,transport:"stdio",isConfig:!1,isRunning:!0});return jd},[R0,zd,pd]),I1=ap?.configEndpoint?ap.configEndpoint.replace(/\/api\/v1\/(config|configure)\/?$/,""):void 0,Jv=!ap||!ap.enableConfigQuery||!!Pp.data||!!Ef.data,Fg=Fd||Pp.data?.welcomeMessage||"",d1=Pp.data?.suggestions,h1=Zh&&Zh.length>0?Zh:Array.isArray(d1)&&d1.length>0?d1.map(jd=>{if(typeof jd=="string"){const lh=jd.trim();return{title:lh,message:lh}}const Zd=(jd?.text??"").trim();return{title:(jd?.summary??"").trim()||Zd,message:Zd}}).filter(jd=>jd.message):void 0,P1=Vd?[{id:"__welcome__",role:"assistant",content:Vd,createdAt:WELCOME_AT},...Rf]:Rf,gv=gh||jsxRuntimeExports.jsxs(Box,{display:"flex",flexDirection:"column",minHeight:0,width:"100%",maxWidth:920,mx:"auto",bg:"canvas.default",children:[jsxRuntimeExports.jsx(ChatMessageList,{displayItems:P1,actOn:ap?.uiSocket?u1:void 0,upload:ap?.uiFiles?Dg:void 0,isLoading:Im,isStreaming:Q1,showLoadingIndicator:Pu,hideMessagesAfterToolUI:np,avatarConfig:Gv,padding:Bf,notebookToolSurfacesId:dh,approvalConfig:$1,messagesEndRef:lg,onRespond:mg,showTurnFooters:rh,agentUsage:x1,onRemoveItems:jg,mcpServers:R1,emptyContent:Xu?null:jsxRuntimeExports.jsx(ChatEmptyState,{emptyState:yh,brandIcon:nh,description:Fg,suggestions:h1,submitOnSuggestionClick:Oh,onSuggestionSubmit:Gb,onSuggestionFill:Zv})}),Ud]}),Xv=Kv&&$d?jsxRuntimeExports.jsx(VoiceInput,{hearing:Kv,language:$d.language,consentKey:$d.consentKey??"chat",disabled:Pf||Xu,speaking:Pd,onStopSpeaking:Gd,onListen:Gd,onTranscript:jd=>{if($d.sendWhatISay){Zp(jd.text,void 0,jd.metadata);return}fv.current=jd.metadata,L0(Em.trim()?`${Em.trim()} ${jd.text}`:jd.text)}}):void 0,K0=Mu?jsxRuntimeExports.jsx(InputPrompt,{footerExtras:Xv,input:Em,setInput:L0,isLoading:Im,kernelStatus:rg,connectionConfirmed:Jv,placeholder:qd,typingSuggestions:h1?.map(jd=>jd.message||jd.title),autoFocus:jh,focusTrigger:rp,padding:Bf,onSend:()=>Zp(),onStop:c1,disableInputPrompt:ju||Pf||!!Yu||Xu,promptVariant:Fu,mentionableAgents:sg,promptCommands:Uu,promptHistory:Pp.data?.promptHistory?.map(askedOf),showTokenUsage:Ru,showContextRing:Iu,agentUsage:x1,showModelSelector:Du,showToolsMenu:Lu,showSkillsMenu:Bu,codemodeEnabled:nd,onToggleCodemode:od,isA2AProtocol:N0,showAgentsMenu:Hu,agents:E0,selectedAgentId:Gu??E0[0]?.id,onSelectAgent:Wu,hasConfigData:!!Pp.data,hasSkillsData:!!Ef.data,configLoading:Pp.isLoading,models:U0,decisions:Pp.data?{models:Pp.data.decisionModels,note:Pp.data.decisionsNote}:void 0,selectedModel:ff,onModelSelect:hm,availableTools:_1.runtime,availableFrontendTools:_1.frontend,mcpServers:R1,enabledMcpTools:Kp,enabledMcpToolCount:o0().length,onToggleMcpTool:Bg,onToggleAllMcpServerTools:ug,approvedMcpTools:p0,onToggleMcpToolApproval:pv,skills:Ef.data?.skills||[],skillsLoading:!1,enabledSkills:o1,onToggleSkill:hv,onToggleAllSkills:a1,approvedSkills:z0,onToggleSkillApproval:dg,apiBase:I1,authToken:ap?.authToken,mcpStatusData:zd}):null,Z0={title:Au,subtitle:lo,disableReason:Pf?Xm:void 0,brandIcon:nh,headerContent:Qd,headerActions:bd,showInformation:Nd,onInformationClick:Kd??(()=>tg(!0)),padding:Bf,kernelIndicatorState:wd,kernelIndicatorPlacement:kd,runtimeStatus:Nf??Vv.data,kernel:im?Wh??cd:Af?Xp??cd:cd,kernelEnvironmentName:dd,kernelCpu:md,kernelMemory:ld,kernelGpu:hd,headerButtons:mh,messageCount:pg.length,onNewChat:fg,onClear:mv,chatViewMode:Td,onChatViewModeChange:Rd,disabledViewModes:Od,showEphemeralSurfaceControl:gp||ip,enableEphemeralNotebookOption:gp,enableEphemeralDocumentOption:ip,ephemeralSurfaceMode:wm,onEphemeralSurfaceModeChange:Mf},vv=$u?eh?eh(Z0):jsxRuntimeExports.jsx(ChatBaseHeader,{...Z0}):null;return jsxRuntimeExports.jsxs(Box,{className:xd,position:"relative",display:"flex",flexDirection:"column",height:"100%",maxHeight:"100%",minHeight:0,flex:"1 1 auto",width:"100%",minWidth:0,bg:wh||"canvas.default",borderRadius:xh,border:Kh,boxShadow:Md,overflow:"hidden",children:[!vp&&vv,X1&&jsxRuntimeExports.jsx(Box,{flex:"1 1 auto",minHeight:0,display:"flex",flexDirection:"column",children:jsxRuntimeExports.jsx(ReactorLazy,{load:loadAgentDetails,errorFallback:agentDetailsRefused,props:{name:Au||"AI Agent",icon:nh,protocol:ap?.type??"unknown",url:ap?.endpoint||"",messageCount:Rf.length,agentId:fh,apiBase:ap?.configEndpoint,onBack:()=>tg(!1)}})}),Wp&&Ag&&Ag.length>0&&jsxRuntimeExports.jsx(ToolApprovalBannerSection,{pendingApprovals:Ag,onApprove:Wb,onReject:Yv}),Ou&&ng&&jsxRuntimeExports.jsxs(Box,{display:"flex",alignItems:"center",gap:2,p:Bf,bg:"danger.subtle",borderBottom:"1px solid",borderColor:"danger.muted",children:[jsxRuntimeExports.jsx(AlertIcon,{size:16}),jsxRuntimeExports.jsx(Text$3,{sx:{color:"danger.fg",fontSize:1},children:ng.message})]}),vp?jsxRuntimeExports.jsxs(Box,{flex:1,minHeight:0,display:"flex",overflow:"hidden",position:"relative",children:[jsxRuntimeExports.jsx(Box,{flex:1,minWidth:0,minHeight:0,display:"flex",flexDirection:"column",overflow:"hidden",sx:wf||vf?null:{borderRight:"1px solid",borderColor:"border.default"},children:Xu||Yu?jsxRuntimeExports.jsx(CompanionSurfaceSkeleton,{mode:im?"notebook":"document"}):im?jsxRuntimeExports.jsx(ReactorLazy,{load:loadEphemeralNotebook,errorFallback:ephemeralNotebookRefused,fallback:jsxRuntimeExports.jsx(CompanionSurfaceSkeleton,{mode:"notebook"}),props:{notebookId:sf,runtimeName:Fp||fh,runtimeOverride:Qp,themeVariant:vd,colorMode:Sd,nbformat:_p??void 0,onNbformatChange:Jp,toolbarComponent:zf,toolbarExtraItems:cm,collaborationProvider:Bh}}):jsxRuntimeExports.jsx(vM.Suspense,{fallback:null,children:jsxRuntimeExports.jsx(EphemeralDocument,{documentId:Zf,runtimeName:Fp||fh,runtimeOverride:Qp,themeVariant:vd,colorMode:Sd,content:Yf??void 0,onContentChange:Am,onToolsReady:af,onKernelChange:bf,collaboration:jp,toolbarExtraItems:bm})})}),!vf&&jsxRuntimeExports.jsxs(Box,{sx:wf?{position:"absolute",right:16,width:um?360:440,maxWidth:"calc(100% - 32px)",...um?{bottom:16,height:"62%"}:{top:16,bottom:16},display:"flex",flexDirection:"column",minHeight:0,overflow:"hidden",bg:"canvas.default",border:"1px solid",borderColor:"border.default",borderRadius:2,boxShadow:"shadow.large",zIndex:5}:{flexShrink:0,width:440,minWidth:320,maxWidth:"48%",minHeight:0,display:"flex",flexDirection:"column",overflow:"hidden",bg:"canvas.default"},children:[vv,jsxRuntimeExports.jsx(Box,{ref:Tm,flex:1,minHeight:0,overflow:"auto",bg:"canvas.default",children:gv}),Dh,K0]}),vf&&Xh&&(Td==="sidebar"?jsxRuntimeExports.jsx(Box,{position:"absolute",top:8,right:8,zIndex:6,children:jsxRuntimeExports.jsx(IconButton,{icon:SidebarExpandIcon,"aria-label":"Open chat",onClick:Xh,variant:"default",size:"small"})}):jsxRuntimeExports.jsx(FloatingBrandButton,{isOpen:!1,onToggle:Xh,position:"bottom-right",tooltip:"Open chat"}))]}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(Box,{ref:Tm,"data-chat-history":"",flex:1,flexGrow:1,minHeight:0,overflow:"auto",bg:"canvas.default",children:gv}),Dh,K0]}),uh&&jsxRuntimeExports.jsx(PoweredByTag,{...Sh}),Yu&&jsxRuntimeExports.jsxs(Box,{position:"absolute",inset:0,zIndex:20,display:"flex",alignItems:"center",justifyContent:"center",p:3,overflow:"auto",children:[jsxRuntimeExports.jsx(Box,{"aria-hidden":!0,position:"absolute",inset:0,bg:"canvas.default",opacity:.4,backdropFilter:"blur(1px)"}),jsxRuntimeExports.jsx(Box,{position:"relative",zIndex:1,maxWidth:"100%",children:Yu})]}),Xu&&!Yu&&jsxRuntimeExports.jsxs(Box,{position:"absolute",inset:0,zIndex:15,display:"flex",alignItems:"center",justifyContent:"center",p:3,children:[jsxRuntimeExports.jsx(Box,{"aria-hidden":!0,position:"absolute",inset:0,bg:"canvas.default",opacity:.35,backdropFilter:"blur(1px)"}),jsxRuntimeExports.jsxs(Box,{position:"relative",zIndex:1,display:"flex",flexDirection:"column",alignItems:"center",gap:3,children:[jsxRuntimeExports.jsx(StyledSpinner,{size:"large"}),jsxRuntimeExports.jsx(Text$3,{sx:{color:"fg.muted"},children:ed||"Launching your agent…"})]})]})]})}function ToolApprovalBannerSection({pendingApprovals:Au,onApprove:lo,onReject:$u}){const[Ru,Iu]=reactExports.useState(null);return reactExports.useEffect(()=>{Ru&&(Au.some(Pu=>Pu.id===Ru.id)||Iu(null))},[Au,Ru]),jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(ToolApprovalBanner,{pendingApprovals:Au,onReview:Pu=>Iu(Pu),onApproveAll:async()=>{if(lo)for(const Pu of Au)await lo(Pu.id)}}),jsxRuntimeExports.jsx(ToolApprovalDialog,{isOpen:!!Ru,toolName:Ru?.toolName??"",toolDescription:Ru?.toolDescription,args:Ru?.args??{},onApprove:async()=>{if(!Ru||!lo){Iu(null);return}await lo(Ru.id)!==!1&&Iu(null)},onDeny:async()=>{if(!Ru||!$u){Iu(null);return}await $u(Ru.id,"Rejected from tool approval dialog")!==!1&&Iu(null)},onClose:()=>Iu(null)})]})}const halo=Au=>({position:"absolute",inset:0,borderRadius:"50%",bg:Au||"accent.emphasis",zIndex:-1,pointerEvents:"none",willChange:"transform, opacity"});function ButtonGlow({color:Au}){return jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(Box,{"aria-hidden":!0,"data-button-glow":"breath",sx:{...halo(Au),filter:"blur(10px)",animation:"agentRuntimesGlowBreath 3.4s ease-in-out infinite","@keyframes agentRuntimesGlowBreath":{"0%, 100%":{transform:"scale(0.9)",opacity:.35},"50%":{transform:"scale(1.25)",opacity:.7}},"@media (prefers-reduced-motion: reduce)":{animation:"none",transform:"scale(1.1)",opacity:.4}}}),jsxRuntimeExports.jsx(Box,{"aria-hidden":!0,"data-button-glow":"aura",sx:{...halo(Au),filter:"blur(18px)",animation:"agentRuntimesGlowAura 5.3s ease-in-out infinite","@keyframes agentRuntimesGlowAura":{"0%, 100%":{transform:"scale(1)",opacity:.15},"40%":{transform:"scale(1.55)",opacity:.4},"70%":{transform:"scale(1.3)",opacity:.25}},"@media (prefers-reduced-motion: reduce)":{animation:"none",transform:"scale(1.3)",opacity:.2}}})]})}const MARGIN=24;function useViewportDrag(Au,{whole:lo=!1}={}){const[$u,Ru]=reactExports.useState(null),Iu=reactExports.useRef(null),Pu=reactExports.useCallback(Mu=>{const Du=Au.current;if(!Du)return;const Lu=Du.getBoundingClientRect();Iu.current={dx:Mu.clientX-Lu.left,dy:Mu.clientY-Lu.top};const Bu=Mu.currentTarget;Bu.setPointerCapture?.(Mu.pointerId);const ju=zu=>{if(!Iu.current)return;const Uu=Math.min(Math.max(zu.clientX-Iu.current.dx,lo?0:MARGIN-Lu.width),window.innerWidth-(lo?Lu.width:MARGIN)),Hu=Math.min(Math.max(zu.clientY-Iu.current.dy,0),window.innerHeight-(lo?Lu.height:MARGIN));Ru({left:Uu,top:Hu})},Fu=()=>{Iu.current=null,Bu.removeEventListener("pointermove",ju),Bu.removeEventListener("pointerup",Fu),Bu.removeEventListener("pointercancel",Fu)};Bu.addEventListener("pointermove",ju),Bu.addEventListener("pointerup",Fu),Bu.addEventListener("pointercancel",Fu),Mu.preventDefault()},[Au,lo]),Ou=reactExports.useCallback(()=>Ru(null),[]);return{position:$u,onHandlePointerDown:Pu,reset:Ou}}const INK=loopColors.ink,INK_DARK=loopColors.inkDark;function Eyes({cx:Au,cy:lo,gap:$u,r:Ru,colours:Iu}){const Pu=Au-$u/2,Ou=Au+$u/2;return jsxRuntimeExports.jsxs("g",{children:[jsxRuntimeExports.jsx("circle",{cx:Pu,cy:lo,r:Ru,fill:Iu.white,stroke:Iu.ring,strokeWidth:1.5}),jsxRuntimeExports.jsx("circle",{cx:Ou,cy:lo,r:Ru,fill:Iu.white,stroke:Iu.ring,strokeWidth:1.5}),jsxRuntimeExports.jsxs("g",{className:"assistant-pupils",children:[jsxRuntimeExports.jsx("circle",{cx:Pu+Ru*.15,cy:lo+Ru*.1,r:Ru*.45,fill:Iu.pupil}),jsxRuntimeExports.jsx("circle",{cx:Ou+Ru*.15,cy:lo+Ru*.1,r:Ru*.45,fill:Iu.pupil}),jsxRuntimeExports.jsx("circle",{cx:Pu+Ru*.3,cy:lo-Ru*.1,r:Ru*.14,fill:Iu.white}),jsxRuntimeExports.jsx("circle",{cx:Ou+Ru*.3,cy:lo-Ru*.1,r:Ru*.14,fill:Iu.white})]}),jsxRuntimeExports.jsxs("g",{className:"assistant-lids",children:[jsxRuntimeExports.jsx("ellipse",{cx:Pu,cy:lo,rx:Ru+.5,ry:Ru+.5,fill:Iu.lid}),jsxRuntimeExports.jsx("ellipse",{cx:Ou,cy:lo,rx:Ru+.5,ry:Ru+.5,fill:Iu.lid})]})]})}const PAPER_CLIP={light:{wire:"#7A808A",shine:"#E3E6EB",line:INK,eye:{white:loopColors.white,ring:INK,pupil:INK,lid:"#B8BDC6"}},dark:{wire:"#C9CED6",shine:"#8D93A0",line:INK_DARK,eye:{white:INK_DARK,ring:loopColors.grayDark,pupil:INK,lid:"#8D93A0"}}},WIZARD={light:{hat:"#6E5CD6",brim:"#4A3C9E",robe:"#5B4BB7",face:"#F2D3B3",beard:"#F4F4F6",beardEdge:"#7A808A",star:"#F8D469",eye:{white:loopColors.white,ring:INK,pupil:INK,lid:"#F2D3B3"}},dark:{hat:"#9C88F0",brim:"#7B67DB",robe:"#8F7CE8",face:"#E8C4A0",beard:"#E4E4EA",beardEdge:loopColors.grayDark,star:"#F8D469",eye:{white:INK_DARK,ring:INK,pupil:INK,lid:"#E8C4A0"}}},CAT={light:{fur:"#F4A261",edge:"#B4571A",tail:"#E08A45",ear:"#F6A5C1",nose:"#B83A6B",whiskers:INK,eye:{white:loopColors.white,ring:INK,pupil:INK,lid:"#F4A261"}},dark:{fur:"#F4A261",edge:"#F4A261",tail:"#E08A45",ear:"#F6A5C1",nose:"#B83A6B",whiskers:INK_DARK,eye:{white:INK_DARK,ring:INK,pupil:INK,lid:"#F4A261"}}},LOOP_EYES={light:{eye:{white:loopColors.white,ring:INK,pupil:INK,lid:"#E3E6EB"}},dark:{eye:{white:INK_DARK,ring:INK_DARK,pupil:loopColors.black,lid:loopColors.grayDark}}};function PaperClip({size:Au,mode:lo="light"}){const $u=PAPER_CLIP[lo],Ru="M40 86 L40 30 Q40 14 52 14 Q64 14 64 30 L64 74 Q64 82 56 82 Q48 82 48 74 L48 36";return jsxRuntimeExports.jsx("svg",{width:Au,height:Au,viewBox:"0 0 96 96",role:"img","aria-label":"Paper clip","data-assistant-mode":lo,children:jsxRuntimeExports.jsxs("g",{className:"assistant-body",children:[jsxRuntimeExports.jsx("path",{d:Ru,fill:"none",stroke:$u.wire,strokeWidth:6,strokeLinecap:"round",strokeLinejoin:"round"}),jsxRuntimeExports.jsx("path",{d:Ru,fill:"none",stroke:$u.shine,strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"}),jsxRuntimeExports.jsx("path",{d:"M36 22 Q42 18 47 21",stroke:$u.line,strokeWidth:2,fill:"none",strokeLinecap:"round"}),jsxRuntimeExports.jsx("path",{d:"M57 21 Q62 18 68 22",stroke:$u.line,strokeWidth:2,fill:"none",strokeLinecap:"round"}),jsxRuntimeExports.jsx(Eyes,{cx:52,cy:30,gap:16,r:6.5,colours:$u.eye}),jsxRuntimeExports.jsx("path",{className:"assistant-mouth",d:"M48 44 Q52 47 56 44",stroke:$u.line,strokeWidth:2,fill:"none",strokeLinecap:"round"})]})})}function Wizard({size:Au,mode:lo="light"}){const $u=WIZARD[lo];return jsxRuntimeExports.jsx("svg",{width:Au,height:Au,viewBox:"0 0 96 96",role:"img","aria-label":"Wizard","data-assistant-mode":lo,children:jsxRuntimeExports.jsxs("g",{className:"assistant-body",children:[jsxRuntimeExports.jsx("path",{d:"M34 58 Q48 52 62 58 Q70 74 76 92 Q48 98 20 92 Q26 74 34 58 Z",fill:$u.robe}),jsxRuntimeExports.jsx("path",{d:"M21 90 Q48 96 75 90 L76 92 Q48 98 20 92 Z",fill:$u.brim}),jsxRuntimeExports.jsx("circle",{cx:30,cy:82,r:1.6,fill:$u.star}),jsxRuntimeExports.jsx("circle",{cx:67,cy:78,r:1.3,fill:$u.star}),jsxRuntimeExports.jsx("ellipse",{cx:48,cy:46,rx:13,ry:12,fill:$u.face}),jsxRuntimeExports.jsx("path",{d:"M33 38 Q31 66 40 77 Q48 89 56 77 Q65 66 63 38 Q61 50 56 53 Q48 58 40 53 Q35 50 33 38 Z",fill:$u.beard,stroke:$u.beardEdge,strokeWidth:1,strokeLinejoin:"round"}),jsxRuntimeExports.jsx("path",{className:"assistant-mouth",d:"M44 59 Q48 62 52 59",stroke:INK,strokeWidth:1.8,fill:"none",strokeLinecap:"round"}),jsxRuntimeExports.jsx("path",{d:"M39 55 Q44 51 48 54 Q52 51 57 55 Q52 57 48 56 Q44 57 39 55 Z",fill:$u.beard,stroke:$u.beardEdge,strokeWidth:.8}),jsxRuntimeExports.jsx("path",{d:"M25 36 Q35 26 39 14 Q43 2 58 3 Q50 8 53 18 Q58 30 71 36 Q48 30 25 36 Z",fill:$u.hat}),jsxRuntimeExports.jsx("path",{d:"M18 37 Q48 27 78 37 Q48 45 18 37 Z",fill:$u.brim}),jsxRuntimeExports.jsx("path",{d:"M47 17 l1.8 3.6 4 .6 -2.9 2.8 .7 4 -3.6 -1.9 -3.6 1.9 .7 -4 -2.9 -2.8 4 -.6 Z",fill:$u.star}),jsxRuntimeExports.jsx("circle",{cx:56,cy:28,r:1.4,fill:$u.star}),jsxRuntimeExports.jsx(Eyes,{cx:48,cy:46,gap:11,r:4,colours:$u.eye})]})})}function Cat({size:Au,mode:lo="light"}){const $u=CAT[lo],Ru="M70 84 Q90 78 84 58";return jsxRuntimeExports.jsx("svg",{width:Au,height:Au,viewBox:"0 0 96 96",role:"img","aria-label":"Cat","data-assistant-mode":lo,children:jsxRuntimeExports.jsxs("g",{className:"assistant-body",children:[jsxRuntimeExports.jsx("path",{d:Ru,stroke:$u.edge,strokeWidth:8,fill:"none",strokeLinecap:"round"}),jsxRuntimeExports.jsx("path",{d:Ru,stroke:$u.tail,strokeWidth:5,fill:"none",strokeLinecap:"round"}),jsxRuntimeExports.jsx("ellipse",{cx:48,cy:78,rx:24,ry:14,fill:$u.fur,stroke:$u.edge,strokeWidth:1.5}),jsxRuntimeExports.jsx("path",{d:"M24 30 L28 8 L42 22 Z",fill:$u.fur,stroke:$u.edge,strokeWidth:1.5,strokeLinejoin:"round"}),jsxRuntimeExports.jsx("path",{d:"M72 30 L68 8 L54 22 Z",fill:$u.fur,stroke:$u.edge,strokeWidth:1.5,strokeLinejoin:"round"}),jsxRuntimeExports.jsx("path",{d:"M28 26 L30 14 L38 22 Z",fill:$u.ear}),jsxRuntimeExports.jsx("path",{d:"M68 26 L66 14 L58 22 Z",fill:$u.ear}),jsxRuntimeExports.jsx("circle",{cx:48,cy:42,r:24,fill:$u.fur,stroke:$u.edge,strokeWidth:1.5}),jsxRuntimeExports.jsx(Eyes,{cx:48,cy:38,gap:18,r:6.5,colours:$u.eye}),jsxRuntimeExports.jsx("path",{d:"M45 48 L51 48 L48 52 Z",fill:$u.nose}),jsxRuntimeExports.jsx("path",{className:"assistant-mouth",d:"M43 55 Q48 58 53 55",stroke:INK,strokeWidth:2,fill:"none",strokeLinecap:"round"}),jsxRuntimeExports.jsx("path",{d:"M30 48 L18 46 M30 52 L18 54 M66 48 L78 46 M66 52 L78 54",stroke:$u.whiskers,strokeWidth:1.2,strokeLinecap:"round"})]})})}function LoopEyes({size:Au,mode:lo="light"}){const $u=LOOP_EYES[lo];return jsxRuntimeExports.jsx("svg",{width:Au,height:Au,viewBox:"0 0 96 96",role:"img","aria-label":"L👀P eyes","data-assistant-mode":lo,children:jsxRuntimeExports.jsxs("g",{className:"assistant-body",children:[jsxRuntimeExports.jsx(Eyes,{cx:48,cy:50,gap:40,r:18,colours:$u.eye}),jsxRuntimeExports.jsx("path",{className:"assistant-mouth",d:"M42 80 Q48 84 54 80",stroke:lo==="dark"?INK_DARK:INK,strokeWidth:2.5,fill:"none",strokeLinecap:"round",opacity:0})]})})}const eyeOf=(Au,lo)=>({white:Au.white,ring:Au.ring,pupil:Au.pupil,on:lo}),ASSISTANT_CHARACTERS=[{id:"paperclip",name:"Paper clip",Drawing:PaperClip,keyColours:{light:{edges:[PAPER_CLIP.light.wire,PAPER_CLIP.light.line],eye:eyeOf(PAPER_CLIP.light.eye,"page")},dark:{edges:[PAPER_CLIP.dark.wire,PAPER_CLIP.dark.line],eye:eyeOf(PAPER_CLIP.dark.eye,"page")}}},{id:"wizard",name:"Wizard",Drawing:Wizard,keyColours:{light:{edges:[WIZARD.light.hat,WIZARD.light.brim,WIZARD.light.robe,WIZARD.light.beardEdge],eye:eyeOf(WIZARD.light.eye,WIZARD.light.face)},dark:{edges:[WIZARD.dark.hat,WIZARD.dark.brim,WIZARD.dark.robe,WIZARD.dark.beardEdge],eye:eyeOf(WIZARD.dark.eye,WIZARD.dark.face)}}},{id:"cat",name:"Cat",Drawing:Cat,keyColours:{light:{edges:[CAT.light.edge,CAT.light.whiskers],eye:eyeOf(CAT.light.eye,CAT.light.fur)},dark:{edges:[CAT.dark.edge,CAT.dark.whiskers],eye:eyeOf(CAT.dark.eye,CAT.dark.fur)}}},{id:"eyes",name:"L👀P eyes",Drawing:LoopEyes,keyColours:{light:{edges:[LOOP_EYES.light.eye.ring],eye:eyeOf(LOOP_EYES.light.eye,"page")},dark:{edges:[LOOP_EYES.dark.eye.white],eye:eyeOf(LOOP_EYES.dark.eye,"page")}}}],DEFAULT_ASSISTANT_CHARACTER="paperclip";function assistantCharacter(Au){const lo=ASSISTANT_CHARACTERS.find($u=>$u.id===Au);if(!lo)throw new Error(`There is no assistant character "${Au}"; the characters are ${ASSISTANT_CHARACTERS.map($u=>$u.id).join(", ")}.`);return lo}const DEFAULT_DECISION_NAME="Answer",DEFAULT_SCORE_RANGE={from:1,to:5},MAX_SCORE_STEPS=11;function scoreSteps(Au){const lo=[];for(let $u=Au.from;$u<=Au.to;$u+=1)lo.push(String($u));return lo}function decisionAskProblem(Au){if(!Au.situation.trim())return"Say the situation the question is about.";if(!Au.question.trim())return"Ask a question.";if(Au.type==="choice"){const lo=(Au.options??[]).filter($u=>$u.trim());if(lo.length<2)return"A choice needs at least two options.";if(new Set(lo.map($u=>$u.trim())).size!==lo.length)return"Two options are the same."}if(Au.type==="score"){const lo=Au.range??DEFAULT_SCORE_RANGE;if(!Number.isInteger(lo.from)||!Number.isInteger(lo.to))return"A score goes from a whole number to another.";if(lo.to<=lo.from)return"A score goes from a lower number to a higher one.";if(lo.to-lo.from+1>MAX_SCORE_STEPS)return`A score has at most ${MAX_SCORE_STEPS} steps.`}}function decisionRequest(Au){const lo=Au.type==="choice"?(Au.options??[]).map($u=>$u.trim()).filter(Boolean):Au.type==="score"?scoreSteps(Au.range??DEFAULT_SCORE_RANGE):[];return{state:Au.situation.trim(),questions:[{name:Au.name?.trim()||DEFAULT_DECISION_NAME,type:Au.type,instructions:Au.question.trim(),options:lo}]}}function confidenceWords(Au){return String(Number(Au.toFixed(2)))}function decisionAnswerWords(Au,lo,$u=[]){if(typeof lo.probability=="number"&&lo.choice===void 0){const Iu=lo.probability>=.5;return`${Au}: ${Iu?"yes":"no"} (${confidenceWords(Iu?lo.probability:1-lo.probability)})`}const Ru=typeof lo.confidence=="number"?` (${confidenceWords(lo.confidence)})`:"";if(typeof lo.score=="number"){const Iu=$u.length?$u:Object.keys(lo.legend??{}).sort((Du,Lu)=>Number(Du)-Number(Lu)).map(Du=>lo.legend?.[Du]??Du),Pu=lo.legend?.[String(lo.score)]??Iu[lo.score],Ou=Iu[Iu.length-1],Mu=Iu.length>0&&Iu.every(Du=>/^-?\d+$/.test(Du.trim()));return`${Au}: ${Pu??lo.score+1}${Mu&&Ou!==void 0?` of ${Ou}`:""}${Ru}`}return typeof lo.choice=="string"?`${Au}: ${lo.choice}${Ru}`:`${Au}: no answer`}function decisionResponseWords(Au,lo){if(lo.refusal)return lo.refusal;const[$u]=Au.questions,Ru=lo.answers?.[$u.name];return Ru?decisionAnswerWords($u.name,Ru,$u.options):"Nothing was decided: the answer did not come back."}function decisionsAskerAt(Au,lo){const $u=Au.replace(/\/+$/,"");return async Ru=>{let Iu;try{Iu=await fetch(`${$u}/api/v1/configure/inference/decisions`,{method:"POST",headers:{"Content-Type":"application/json",...lo?{Authorization:`Bearer ${lo}`}:{}},body:JSON.stringify(Ru)})}catch{return{refusal:"Nothing was decided: the runtime could not be reached."}}if(!Iu.ok){let Pu="";try{const Ou=await Iu.json();Pu=typeof Ou.detail=="string"?Ou.detail:""}catch{}return{refusal:`Nothing was decided: the runtime refused it (${Iu.status})${Pu?`: ${Pu}`:"."}`}}return await Iu.json()}}const DECISION_WORDS={ask:"Ask a decision",asking:"Asking…",submit:"Ask",cancel:"Cancel",again:"Ask another",types:{noul:"Yes or no",choice:"A choice",score:"A score"}},LINK_SX={mt:1,p:0,border:0,bg:"transparent",color:"accent.fg",textDecoration:"underline",cursor:"pointer",fontSize:1};function DecisionAsk({ask:Au,onActiveChange:lo}){const[$u,Ru]=reactExports.useState(!1),[Iu,Pu]=reactExports.useState(""),[Ou,Mu]=reactExports.useState(""),[Du,Lu]=reactExports.useState(""),[Bu,ju]=reactExports.useState("noul"),[Fu,zu]=reactExports.useState(""),[Uu,Hu]=reactExports.useState(String(DEFAULT_SCORE_RANGE.from)),[Vu,Gu]=reactExports.useState(String(DEFAULT_SCORE_RANGE.to)),[Wu,Ku]=reactExports.useState(),[Ju,Yu]=reactExports.useState(!1),[Xu,ed]=reactExports.useState(),td=reactExports.useRef(lo);td.current=lo,reactExports.useEffect(()=>()=>td.current?.(!1),[]);const nd=ad=>{Ru(ad),lo?.(ad)},od=()=>{ed(void 0),Ku(void 0),nd(!1)};if(!$u)return jsxRuntimeExports.jsx(Box,{as:"button",type:"button","data-balloon-ask-decision":"",onClick:()=>nd(!0),...LINK_SX,display:"block",children:DECISION_WORDS.ask});if(Xu!==void 0)return jsxRuntimeExports.jsxs(Box,{"data-balloon-decision":"answered",mt:2,children:[jsxRuntimeExports.jsx(Text$3,{as:"p","data-decision-answer":"",sx:{m:0,fontWeight:"semibold"},children:Xu}),jsxRuntimeExports.jsxs(Box,{display:"flex",gap:2,mt:2,children:[jsxRuntimeExports.jsx(ButtonComponent,{size:"small",onClick:()=>ed(void 0),children:DECISION_WORDS.again}),jsxRuntimeExports.jsx(ButtonComponent,{size:"small",variant:"invisible",onClick:od,children:DECISION_WORDS.cancel})]})]});const sd=async()=>{const ad={situation:Iu,question:Ou,type:Bu,name:Du,options:Fu.split(`
|
|
3674
3674
|
`),range:{from:Number(Uu),to:Number(Vu)}},pd=decisionAskProblem(ad);if(Ku(pd),pd)return;const gd=decisionRequest(ad);Yu(!0);try{ed(decisionResponseWords(gd,await Au(gd)))}catch(xd){ed(`Nothing was decided: ${xd instanceof Error?xd.message:String(xd)}`)}finally{Yu(!1)}};return jsxRuntimeExports.jsxs(Box,{as:"form","data-balloon-decision":"asking","aria-label":DECISION_WORDS.ask,onSubmit:ad=>{ad.preventDefault(),sd()},onKeyDown:ad=>{ad.key==="Escape"&&od()},mt:2,display:"flex",flexDirection:"column",gap:2,children:[jsxRuntimeExports.jsxs(FormControl$1,{children:[jsxRuntimeExports.jsx(FormControl$1.Label,{children:"Situation"}),jsxRuntimeExports.jsx(Textarea,{block:!0,rows:3,resize:"vertical",name:"situation",placeholder:"Help! My payouts have been failing for 3 days.",value:Iu,onChange:ad=>Pu(ad.target.value)})]}),jsxRuntimeExports.jsxs(FormControl$1,{children:[jsxRuntimeExports.jsx(FormControl$1.Label,{children:"Question"}),jsxRuntimeExports.jsx(TextInput$1,{block:!0,size:"small",name:"question",placeholder:"Is it urgent?",value:Ou,onChange:ad=>Mu(ad.target.value)})]}),jsxRuntimeExports.jsxs(Box,{display:"flex",gap:2,children:[jsxRuntimeExports.jsxs(FormControl$1,{sx:{flex:1},children:[jsxRuntimeExports.jsx(FormControl$1.Label,{children:"Type"}),jsxRuntimeExports.jsx(Select$1,{block:!0,size:"small",name:"type",value:Bu,onChange:ad=>ju(ad.target.value),children:Object.keys(DECISION_WORDS.types).map(ad=>jsxRuntimeExports.jsx(Select$1.Option,{value:ad,children:DECISION_WORDS.types[ad]},ad))})]}),jsxRuntimeExports.jsxs(FormControl$1,{sx:{flex:1},children:[jsxRuntimeExports.jsx(FormControl$1.Label,{children:"Name"}),jsxRuntimeExports.jsx(TextInput$1,{block:!0,size:"small",name:"name",placeholder:"Answer",value:Du,onChange:ad=>Lu(ad.target.value)})]})]}),Bu==="choice"&&jsxRuntimeExports.jsxs(FormControl$1,{children:[jsxRuntimeExports.jsx(FormControl$1.Label,{children:"Options, one per line"}),jsxRuntimeExports.jsx(Textarea,{block:!0,rows:3,resize:"vertical",name:"options",placeholder:`Billing
|
|
3675
3675
|
Tech
|
|
3676
3676
|
Sales`,value:Fu,onChange:ad=>zu(ad.target.value)})]}),Bu==="score"&&jsxRuntimeExports.jsxs(Box,{display:"flex",gap:2,children:[jsxRuntimeExports.jsxs(FormControl$1,{sx:{flex:1},children:[jsxRuntimeExports.jsx(FormControl$1.Label,{children:"From"}),jsxRuntimeExports.jsx(TextInput$1,{block:!0,size:"small",type:"number",name:"from",value:Uu,onChange:ad=>Hu(ad.target.value)})]}),jsxRuntimeExports.jsxs(FormControl$1,{sx:{flex:1},children:[jsxRuntimeExports.jsx(FormControl$1.Label,{children:"To"}),jsxRuntimeExports.jsx(TextInput$1,{block:!0,size:"small",type:"number",name:"to",value:Vu,onChange:ad=>Gu(ad.target.value)})]})]}),Wu?jsxRuntimeExports.jsx(Text$3,{as:"p",role:"alert",sx:{m:0,color:"danger.fg",fontSize:0},children:Wu}):null,jsxRuntimeExports.jsxs(Box,{display:"flex",gap:2,children:[jsxRuntimeExports.jsx(ButtonComponent,{size:"small",variant:"primary",type:"submit",disabled:Ju,children:Ju?DECISION_WORDS.asking:DECISION_WORDS.submit}),jsxRuntimeExports.jsx(ButtonComponent,{size:"small",type:"button",onClick:od,disabled:Ju,children:DECISION_WORDS.cancel})]})]})}const DEFAULT_BALLOON_DISPLAY="history";let displayNames=null;function toolDisplayName(Au){if(!displayNames){displayNames=new Map;for(const Ru of Object.values(BACKEND_TOOL_CATALOG)){const Iu=Ru.runtime?.method;Iu&&Ru.name&&!displayNames.has(Iu)&&displayNames.set(Iu,Ru.name)}}const lo=displayNames.get(Au);if(lo)return lo;const $u=Au.indexOf("__");return $u>0?Au.slice($u+2):Au}function toolLineParts(Au,lo=ENGLISH_CHAT_WORDS){if(Au.phase==="running"&&Au.words)return{before:"",name:"",after:Au.words};switch(Au.phase){case"running":return{...lo.toolRunning,name:Au.name};case"done":return{...lo.toolDone,name:Au.name};case"failed":return{...lo.toolFailedLine,name:Au.name}}}function toolLineText(Au,lo=ENGLISH_CHAT_WORDS){const{before:$u,name:Ru,after:Iu}=toolLineParts(Au,lo);return`${$u}${Ru}${Iu}`}function newestToolLine(Au){const lo=Au[Au.length-1];if(!lo||typeof lo.toolName!="string"||!lo.toolName)return;const $u=lo.status==="error"||typeof lo.error=="string"&&lo.error?"failed":lo.status==="complete"?"done":"running";return{id:String(lo.toolCallId??lo.id??lo.toolName),tool:lo.toolName,name:toolDisplayName(lo.toolName),phase:$u}}function toolAnnouncement(Au,lo,$u=ENGLISH_CHAT_WORDS){if(Au&&!(lo&&lo.id===Au.id&&lo.phase===Au.phase))return toolLineText(Au,$u)}function conversationCount(Au){return Au.filter(lo=>{const $u=lo;return($u.role==="user"||$u.role==="assistant")&&typeof $u.toolName!="string"}).length}function displayItemOfLine(Au){return!Au.tool&&!Au.name?{id:`balloon-activity:${Au.id}`,role:"assistant",content:Au.words??"",createdAt:new Date(0)}:toolCallOfLine(Au)}function toolCallOfLine(Au){return{id:`balloon-tool:${Au.id}`,type:"tool-call",toolCallId:Au.id,toolName:Au.tool||Au.name,args:{},status:Au.phase==="failed"?"error":Au.phase==="done"?"complete":"executing",...Au.words?{summary:Au.words}:{}}}function withToolCall(Au,lo){return!lo||Au.some($u=>$u.toolCallId===lo.id||$u.id===lo.id)?Au:[...Au,displayItemOfLine(lo)]}function plainWords(Au){return Au.replace(/```[\s\S]*?(```|$)/g," A code block. ").replace(/(^|\n)(\|[^\n]*\|[ \t]*(\n|$))+/g,`$1 A table.
|
|
@@ -4000,7 +4000,7 @@ ${Mu}`:ju,inputs:Mu,clear:Ou?[]:[DRAFT.path],loop:Lu()}:{refused:"Nothing to sen
|
|
|
4000
4000
|
}
|
|
4001
4001
|
`;function usePaletteStyles(){reactExports.useEffect(()=>{if(typeof document>"u"||document.getElementById(STYLE_ELEMENT_ID))return;const Au=document.createElement("style");Au.id=STYLE_ELEMENT_ID,Au.textContent=PALETTE_CSS,document.head.appendChild(Au)},[])}function rank(Au,lo){if(!lo)return{command:Au,score:0};const $u=lo.toLowerCase(),Ru=[[Au.name.toLowerCase(),0],[Au.id.toLowerCase(),100],[(Au.category??"").toLowerCase(),200],[(Au.description??"").toLowerCase(),300]];for(const[Iu,Pu]of Ru){const Ou=Iu.indexOf($u);if(Ou>=0)return{command:Au,score:Pu+Ou}}return null}const PRIMER_PORTAL_ROOT_ID="__primerPortalRoot__";function paletteRoot(){return document.getElementById(PRIMER_PORTAL_ROOT_ID)??document.body}const LIST_ID="dla-cmdk-list",optionId=Au=>`dla-cmdk-option-${Au}`,PALETTE_KEYBINDING="Mod+K",PALETTE_CHORD=parseKeybinding(PALETTE_KEYBINDING);function CommandPalette(){const Au=useReactorPlatform(),lo=useCommands();usePaletteStyles();const[$u,Ru]=reactExports.useState(!1),[Iu,Pu]=reactExports.useState(""),[Ou,Mu]=reactExports.useState(0),[Du,Lu]=reactExports.useState(null),[Bu,ju]=reactExports.useState(null),Fu=reactExports.useRef(null),zu=reactExports.useMemo(()=>lo.map(Wu=>rank(Wu,Iu)).filter(Wu=>Wu!==null).sort((Wu,Ku)=>Wu.score-Ku.score).map(Wu=>Wu.command),[lo,Iu]),Uu=reactExports.useCallback(()=>{Ru(!1),Pu(""),Mu(0),ju(null)},[]),Hu=reactExports.useCallback(async Wu=>{Lu(Wu.id),ju(null);try{await Au.executeCommand(Wu.id),Uu()}catch(Ku){ju(Ku instanceof Error?Ku.message:String(Ku))}finally{Lu(null)}},[Uu,Au]);if(reactExports.useEffect(()=>{const Wu=lo.map(Yu=>{const Xu=Yu.keybinding?parseKeybinding(Yu.keybinding):null;return Xu?{chord:Xu,id:Yu.id}:null}).filter(Yu=>Yu!==null),Ku=isApplePlatform();function Ju(Yu){if(PALETTE_CHORD&&matchesKeybinding(Yu,PALETTE_CHORD,Ku)){Yu.preventDefault(),Yu.stopPropagation(),Ru(Xu=>!Xu);return}if(Yu.key==="Escape"){Ru(Xu=>Xu&&!1);return}if(!$u){for(const Xu of Wu)if(matchesKeybinding(Yu,Xu.chord,Ku)){Yu.preventDefault(),Yu.stopPropagation();const ed=Au.getCommand(Xu.id);ed&&ed.isEnabled?.()!==!1&&Au.executeCommand(Xu.id).catch(td=>{console.error(`Command ${Xu.id} failed`,td)});return}}}return document.addEventListener("keydown",Ju,{capture:!0}),()=>document.removeEventListener("keydown",Ju,{capture:!0})},[lo,$u,Au]),reactExports.useEffect(()=>{if(!$u)return;Pu(""),Mu(0),ju(null);const Wu=window.requestAnimationFrame(()=>Fu.current?.focus());return()=>window.cancelAnimationFrame(Wu)},[$u]),reactExports.useEffect(()=>{Mu(Wu=>Wu>=zu.length?0:Wu)},[zu.length]),!$u||typeof document>"u")return null;const Vu=Wu=>{if(Wu.key==="ArrowDown")Wu.preventDefault(),Mu(Ku=>zu.length===0?0:(Ku+1)%zu.length);else if(Wu.key==="ArrowUp")Wu.preventDefault(),Mu(Ku=>zu.length===0?0:(Ku-1+zu.length)%zu.length);else if(Wu.key==="Enter"){Wu.preventDefault();const Ku=zu[Ou];Ku&&Ku.isEnabled?.()!==!1&&Hu(Ku)}},Gu=jsxRuntimeExports.jsx("div",{className:"dla-cmdk-backdrop",onClick:Uu,children:jsxRuntimeExports.jsxs("div",{className:"dla-cmdk-panel",role:"dialog","aria-modal":"true","aria-label":"Command palette",onClick:Wu=>Wu.stopPropagation(),children:[jsxRuntimeExports.jsx("div",{className:"dla-cmdk-search",children:jsxRuntimeExports.jsx("input",{ref:Fu,className:"dla-cmdk-input",type:"text",placeholder:"Run a command…","aria-label":"Search commands",autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",spellCheck:!1,role:"combobox","aria-expanded":!0,"aria-controls":LIST_ID,"aria-autocomplete":"list","aria-activedescendant":zu.length>0?optionId(Ou):void 0,value:Iu,onChange:Wu=>Pu(Wu.target.value),onKeyDown:Vu})}),Bu!==null&&jsxRuntimeExports.jsx("div",{className:"dla-cmdk-error",children:Bu}),jsxRuntimeExports.jsx("ul",{className:"dla-cmdk-list",id:LIST_ID,role:"listbox",children:zu.length===0?jsxRuntimeExports.jsx("li",{className:"dla-cmdk-empty",children:lo.length===0?"No plugin has registered a command yet.":`Nothing matches “${Iu}”.`}):zu.map((Wu,Ku)=>{const Ju=Wu.isEnabled?.()!==!1;return jsxRuntimeExports.jsx("li",{children:jsxRuntimeExports.jsxs("button",{type:"button",className:"dla-cmdk-item",id:optionId(Ku),role:"option","aria-selected":Ku===Ou,"aria-disabled":!Ju,disabled:!Ju,onMouseEnter:()=>Mu(Ku),onClick:()=>{Hu(Wu)},children:[jsxRuntimeExports.jsx("span",{className:"dla-cmdk-mark","aria-hidden":"true",children:Wu.emoji??"·"}),jsxRuntimeExports.jsxs("span",{className:"dla-cmdk-text",children:[jsxRuntimeExports.jsx("span",{className:"dla-cmdk-name",children:Wu.name}),Wu.description&&jsxRuntimeExports.jsx("p",{className:"dla-cmdk-description",children:Wu.description})]}),Du===Wu.id&&jsxRuntimeExports.jsx("span",{className:"dla-cmdk-meta",children:"running…"}),Wu.keybinding&&jsxRuntimeExports.jsx("kbd",{className:"dla-cmdk-key",children:formatKeybinding(Wu.keybinding)}),Wu.category&&jsxRuntimeExports.jsx("span",{className:"dla-cmdk-meta",children:Wu.category})]})},Wu.id)})}),jsxRuntimeExports.jsxs("div",{className:"dla-cmdk-footer",children:[jsxRuntimeExports.jsxs("span",{children:["↑↓ to move · ↵ to run · esc to close ·"," ",jsxRuntimeExports.jsx("kbd",{className:"dla-cmdk-key",children:formatKeybinding(PALETTE_KEYBINDING)})," ","to reopen"]}),jsxRuntimeExports.jsxs("span",{children:[zu.length," of ",lo.length]})]})]})});return reactDomExports.createPortal(Gu,paletteRoot())}const CommandsPlugin={name:"@datalayer/reactor-commands",version:"1.0.0",displayName:"Commands",description:"A command palette: Ctrl-K opens a floating search over every command plugins have registered.",octicon:"command-palette",emoji:"⌘",build(){return{components:[{slot:"root",id:"command-palette",Component:CommandPalette}]}},commands:[{id:"commands.showPalette",name:"Show the command palette",description:"The same thing Ctrl-K does — listed so it is discoverable",emoji:"⌘",category:"Commands",keybinding:PALETTE_KEYBINDING,execute:()=>{document.dispatchEvent(new KeyboardEvent("keydown",{key:"k",ctrlKey:!0,bubbles:!0}))}}]},COMMANDS_PLUGIN_NAME="@datalayer/loop-plugin-commands",DEFAULT_CATEGORY="Workspace",GROUP_EMOJI={Agents:"🤖",Open:"📂",Session:"🧭",Workspace:"🪟"};function LoopCommandBridge({workspace:Au,sync:lo}){const $u=useContributions(LoopCommand);return reactExports.useEffect(()=>{lo($u,Au)},[$u,Au,lo]),null}const LoopCommandsPlugin={name:COMMANDS_PLUGIN_NAME,displayName:"Command palette",description:"Puts the workspace commands in a Ctrl-K palette, beside every plugin that registers one.",octicon:"command-palette",emoji:"⌘",dependencies:[CommandsPlugin,ThemePlugin],build:Au=>{const lo=new Map;let $u="",Ru;const Iu=(Pu,Ou)=>{const Mu=Ou?Pu.map(Du=>`${Du.plugin}:${Du.value.name}`).join("|"):"";if(!(Mu===$u&&Ou===Ru)){$u=Mu,Ru=Ou;for(const Du of lo.values())Du();if(lo.clear(),!!Ou)for(const Du of Pu){const Lu=Du.value,Bu=Lu.group??DEFAULT_CATEGORY;lo.set(Lu.name,Au.registerCommand({id:`loop.${Lu.name}`,name:Lu.description,description:`/${Lu.name}`,emoji:GROUP_EMOJI[Bu]??"💠",category:Bu,keybinding:Lu.keybinding,execute:async()=>{await Lu.run({workspace:Ou,argv:""})}}))}}};return{components:[{id:"loop-command-bridge",slot:LoopSlots.status,Component:({workspace:Pu})=>jsxRuntimeExports.jsx(LoopCommandBridge,{workspace:Pu,sync:Iu})}]}}},MODELS_PLUGIN_NAME="@datalayer/loop-plugin-models",ModelsPlugin={name:MODELS_PLUGIN_NAME,displayName:"Models",description:"Which model answers, from the agentspecs catalog.",octicon:"cpu",emoji:"🧠",contributes:[contribution(LoopCommand,{name:"models",aliases:["model"],description:"Show the models available to this session",group:"Agents",keybinding:"Mod+Alt+M",run:async({workspace:Au})=>{const lo=await fetch(`${Au.serverUrl}/api/v1/configure/models`);if(!lo.ok)return{content:"The model catalogue is unavailable."};const $u=await lo.json();return{content:`${($u.models??[]).filter(Iu=>Iu.available!==!1).length} of ${($u.models??[]).length} models are ready. Pick one under the prompt.`}}},{id:"models"})]},WINDOW_CONTROLS_SLOT="loop.window.controls",WINDOW_ACTIONS_SLOT="loop.window.actions";function WindowFrame({children:Au,title:lo,height:$u,slotProps:Ru={}}){const Iu=useOptionalSlotComponents(WINDOW_ACTIONS_SLOT);return jsxRuntimeExports.jsxs(Box,{position:"relative",borderRadius:"14px",overflow:"hidden",border:"1px solid",borderColor:"border.default",bg:"canvas.default",boxShadow:"0 24px 60px -28px rgba(0, 0, 0, 0.55)",height:$u===void 0?"100%":void 0,display:$u===void 0?"flex":void 0,flexDirection:$u===void 0?"column":void 0,children:[jsxRuntimeExports.jsxs(Box,{display:"flex",alignItems:"center",gap:2,px:3,py:2,borderBottom:"1px solid",borderColor:"border.default",bg:"canvas.subtle",flexWrap:"wrap",rowGap:2,flex:"0 0 auto",children:[jsxRuntimeExports.jsx(Box,{display:"flex",alignItems:"center",gap:"6px",mr:1,flexShrink:0,children:jsxRuntimeExports.jsx(ReactorSlot,{slot:WINDOW_CONTROLS_SLOT,props:Ru})}),jsxRuntimeExports.jsx(Box,{minWidth:0,flex:"1 1 auto",children:lo}),Iu.length>0?jsxRuntimeExports.jsx(Box,{display:"flex",alignItems:"center",gap:2,flexShrink:0,ml:"auto",children:jsxRuntimeExports.jsx(ReactorSlot,{slot:WINDOW_ACTIONS_SLOT,props:Ru})}):null]}),jsxRuntimeExports.jsx(Box,{sx:$u===void 0?{flex:"1 1 auto",minHeight:0}:{height:$u,minHeight:0},children:Au})]})}const WINDOW_FRAME_PLUGIN_NAME="@datalayer/loop-plugin-window-frame";function WindowControls(){return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:["danger.emphasis","attention.emphasis","success.emphasis"].map(Au=>jsxRuntimeExports.jsx(Box,{width:10,height:10,borderRadius:"50%",bg:Au},Au))})}const WindowFramePlugin={name:WINDOW_FRAME_PLUGIN_NAME,displayName:"Window frame",description:"Draws Loop as a window, and opens its title bar to controls and actions.",octicon:"browser",emoji:"🪟",build:()=>({components:[{id:"window-controls",slot:WINDOW_CONTROLS_SLOT,Component:WindowControls},{id:"full-screen",slot:LoopSlots.header,Component:WorkspaceFullScreenAction}]})},DOCUMENT_PLUGIN_NAME="@datalayer/loop-plugin-document",DocumentPlugin={name:DOCUMENT_PLUGIN_NAME,displayName:"Document editor",description:"A rich-text document beside the chat, driven by the agent.",octicon:"file",emoji:"📄",dependencies:[AgentsPlugin],contributionPoints:[LoopDocumentToolbar,LoopOpeningDocument],contributes:[contribution(LoopEditorView,{surfaceId:"document",title:"Document",icon:FileIcon,order:20,canOpen:Au=>Au.sandbox.state==="running",unavailableReason:()=>"Needs a running sandbox",load:()=>__vitePreload(()=>import("./chunks/DocumentView-BqsGfNys.js"),[],import.meta.url)},{id:"document",order:20}),contribution(LoopCommand,{name:"document",description:"Open the document beside the chat",group:"Open",keybinding:"Mod+Alt+O",run:async({workspace:Au})=>{if(Au.setActiveViewType("chat"),!requestSurface("document"))throw new Error("No chat is on screen to open the document beside.")}},{id:"document"})],build:Au=>(__vitePreload(async()=>{const{createLexicalTools:lo}=await import("./chunks/lexicalHooks-DQxNZEiJ.js");return{createLexicalTools:lo}},[],import.meta.url).then(({createLexicalTools:lo})=>{Au.contribute(LoopFrontendTool,{id:"document-tools",tools:$u=>lo($u.surfaceId)},{id:"document-tools"})},lo=>{console.warn("The document tools could not be loaded",lo)}),{})},DOCUMENT_TOOLBAR_PLUGIN_NAME="@datalayer/loop-plugin-document-toolbar",DocumentToolbarPlugin=defineLazyPlugin({name:DOCUMENT_TOOLBAR_PLUGIN_NAME,displayName:"Document toolbar",description:"Shows what the document’s code blocks run on.",octicon:"circle",emoji:"🔵",activationEvents:[onContributionPoint(LoopDocumentToolbar)],contributionPoints:[LoopDocumentToolbarItem],load:()=>__vitePreload(()=>import("./chunks/plugin-Cf3g-jak.js"),[],import.meta.url)}),NOTEBOOK_PLUGIN_NAME="@datalayer/loop-plugin-notebook",NotebookPlugin={name:NOTEBOOK_PLUGIN_NAME,displayName:"Notebook editor",description:"A notebook beside the chat, on the session’s kernel.",octicon:"rows",emoji:"📓",dependencies:[AgentsPlugin],contributionPoints:[LoopNotebookToolbar,LoopOpeningNotebook],contributes:[contribution(LoopEditorView,{surfaceId:"notebook",title:"Notebook",icon:RowsIcon,order:10,canOpen:Au=>Au.sandbox.state==="running",unavailableReason:()=>"Needs a running sandbox",load:()=>__vitePreload(()=>import("./chunks/NotebookView-IX0wNuX8.js"),[],import.meta.url)},{id:"notebook",order:10}),contribution(LoopCommand,{name:"notebook",description:"Open the notebook beside the chat",group:"Open",keybinding:"Mod+Alt+N",run:async({workspace:Au})=>{if(Au.setActiveViewType("chat"),!requestSurface("notebook"))throw new Error("No chat is on screen to open the notebook beside.")}},{id:"notebook"})],build:Au=>(__vitePreload(async()=>{const{createNotebookTools:lo}=await Promise.resolve().then(()=>notebookHooks);return{createNotebookTools:lo}},void 0,import.meta.url).then(({createNotebookTools:lo})=>{Au.contribute(LoopFrontendTool,{id:"notebook-tools",tools:$u=>lo($u.surfaceId)},{id:"notebook-tools"})},lo=>{console.warn("The notebook tools could not be loaded",lo)}),{})},NOTEBOOK_TOOLBAR_PLUGIN_NAME="@datalayer/loop-plugin-notebook-toolbar",NotebookToolbarPlugin=defineLazyPlugin({name:NOTEBOOK_TOOLBAR_PLUGIN_NAME,displayName:"Notebook toolbar",description:"Shows what the notebook is running on, on its toolbar.",octicon:"circle",emoji:"🟢",activationEvents:[onContributionPoint(LoopNotebookToolbar)],contributionPoints:[LoopNotebookToolbarItem],load:()=>__vitePreload(()=>import("./chunks/plugin-DA_NCYQX.js"),[],import.meta.url)}),NotebookExtension=defineExtension({name:"@datalayer/loop-extension-notebook",displayName:"Notebooks",description:"A notebook beside the chat, and the toolbar that reports on it.",octicon:"rows",emoji:"📓",plugins:[NotebookPlugin,NotebookToolbarPlugin]}),DocumentExtension=defineExtension({name:"@datalayer/loop-extension-document",displayName:"Documents",description:"A rich-text document beside the chat, and the toolbar that reports on it.",octicon:"file",emoji:"📄",plugins:[DocumentPlugin,DocumentToolbarPlugin]}),NO_TURN$5=signal$2({id:0,status:"idle"}),MAX_HEIGHT=168;function Thinking(){return jsxRuntimeExports.jsxs(Box,{as:"span","aria-label":"The agent is thinking",display:"inline-flex",gap:"4px",alignItems:"center",sx:{height:"1.5em","& > i":{width:5,height:5,borderRadius:"50%",bg:"fg.muted",animation:"loop-turn-dot 1.2s ease-in-out infinite"},"& > i:nth-of-type(2)":{animationDelay:"0.15s"},"& > i:nth-of-type(3)":{animationDelay:"0.3s"},"@keyframes loop-turn-dot":{"0%, 80%, 100%":{opacity:.25},"40%":{opacity:1}}},children:[jsxRuntimeExports.jsx("i",{}),jsxRuntimeExports.jsx("i",{}),jsxRuntimeExports.jsx("i",{})]})}function TurnPanel({footer:Au="full"}){const lo=useContributions(LoopChatTurn),$u=useSignalValue$1(lo[0]?.value.turn??NO_TURN$5),Ru=useSignalValue$1(pageLayoutSheet),Iu=reactExports.useRef(null),[Pu,Ou]=reactExports.useState(null),[Mu,Du]=reactExports.useState(!1);reactExports.useEffect(()=>{const ju=Iu.current;ju&&(ju.scrollTop=ju.scrollHeight)},[$u.assistant]),reactExports.useEffect(()=>{if(!Mu)return;const ju=window.setTimeout(()=>Du(!1),1400);return()=>window.clearTimeout(ju)},[Mu]);const Lu=reactExports.useCallback(async()=>{const ju=[$u.user,$u.assistant].filter(Boolean).join(`
|
|
4002
4002
|
|
|
4003
|
-
`);await navigator.clipboard?.writeText(ju),Du(!0)},[$u.user,$u.assistant]);if(Ru==="panel"||$u.status==="idle"||!$u.user||Pu===$u.id)return null;const Bu=$u.status==="thinking"||$u.status==="streaming";return jsxRuntimeExports.jsxs(Box,{"data-turn-panel":"",borderTop:"1px solid",borderColor:"border.muted",px:3,pt:2,pb:Au==="none"?2:1,display:"flex",flexDirection:"column",gap:2,bg:"canvas.default",children:[jsxRuntimeExports.jsx(Box,{display:"flex",justifyContent:"flex-end",children:jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,lineHeight:1.45,px:2,py:1,borderRadius:"10px",bg:"accent.subtle",color:"fg.default",maxWidth:"85%",overflow:"hidden",display:"-webkit-box",WebkitLineClamp:2,WebkitBoxOrient:"vertical"},children:$u.user})}),jsxRuntimeExports.jsxs(Box,{display:"flex",gap:2,alignItems:"flex-start",children:[jsxRuntimeExports.jsx(Box,{ref:Iu,flex:"1 1 auto",minWidth:0,maxHeight:MAX_HEIGHT,overflowY:"auto",fontSize:0,lineHeight:1.5,color:$u.assistant?"fg.default":"fg.muted",whiteSpace:$u.assistant?"normal":"pre-wrap",overflowWrap:"anywhere",children:$u.assistant?jsxRuntimeExports.jsx(Box,{sx:{...streamdownMarkdownStyles,fontSize:0},children:jsxRuntimeExports.jsx(_o$1,{rehypePlugins:REHYPE_PLUGINS_WITHOUT_HTML,children:normalizeAssistantMarkdown($u.assistant)})}):$u.activity?jsxRuntimeExports.jsx(Text$3,{sx:{color:"fg.muted",fontStyle:"italic"},children:$u.activity}):Bu?jsxRuntimeExports.jsx(Thinking,{}):$u.status==="error"?"The agent could not answer.":"Done — the result is in the page."}),jsxRuntimeExports.jsx(IconButton,{icon:CommentDiscussionIcon,size:"small",variant:"invisible","aria-label":"Open the conversation",onClick:openPagePanel,sx:{color:"fg.muted",flexShrink:0}})]}),$u.assistant&&$u.activity?jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:"fg.muted",fontStyle:"italic"},children:$u.activity}):null,Au==="full"?jsxRuntimeExports.jsx(TurnFooter,{usage:$u.usage,live:Bu,latest:!0,padding:0,onCopy:Lu,onRemove:()=>Ou($u.id)}):Au==="actions"?jsxRuntimeExports.jsxs(Box,{display:"flex",justifyContent:"flex-end",gap:1,mt:-1,children:[jsxRuntimeExports.jsx(IconButton,{icon:Mu?CheckIcon:CopyIcon,size:"small",variant:"invisible","aria-label":Mu?"Copied":"Copy this turn",onClick:()=>{Lu()},sx:{color:"fg.muted"}}),jsxRuntimeExports.jsx(IconButton,{icon:XIcon,size:"small",variant:"invisible","aria-label":"Dismiss until the next turn",onClick:()=>Ou($u.id),sx:{color:"fg.muted"}})]}):null]})}const SPLIT_DEFAULT_SHARE=.4,SPLIT_MIN_SHARE=.2,SPLIT_MAX_SHARE=.8,SPLIT_KEY_STEP=.05;function clampSplitShare(Au){return Number.isFinite(Au)?Math.min(SPLIT_MAX_SHARE,Math.max(SPLIT_MIN_SHARE,Au)):SPLIT_DEFAULT_SHARE}function splitShareForKey(Au,lo){switch(lo){case"ArrowLeft":return clampSplitShare(Au-SPLIT_KEY_STEP);case"ArrowRight":return clampSplitShare(Au+SPLIT_KEY_STEP);case"Home":return SPLIT_MIN_SHARE;case"End":return SPLIT_MAX_SHARE;default:return null}}function SplitLayout({editors:Au,hasEditor:lo,transcript:$u,prompt:Ru,chips:Iu,picker:Pu,transient:Ou}){const[Mu,Du]=reactExports.useState(SPLIT_DEFAULT_SHARE),Lu=reactExports.useRef(null),Bu=reactExports.useRef(!1),ju=reactExports.useCallback(Gu=>{const Wu=Lu.current?.getBoundingClientRect();return!Wu||Wu.width<=0?null:clampSplitShare((Gu-Wu.left)/Wu.width)},[]),Fu=Gu=>{Bu.current=!0,Gu.currentTarget.setPointerCapture?.(Gu.pointerId),Gu.preventDefault()},zu=Gu=>{if(!Bu.current)return;const Wu=ju(Gu.clientX);Wu!==null&&Du(Wu)},Uu=Gu=>{Bu.current=!1,Gu.currentTarget.releasePointerCapture?.(Gu.pointerId)},Hu=Gu=>{const Wu=splitShareForKey(Mu,Gu.key);Wu!==null&&(Gu.preventDefault(),Du(Wu))},Vu=Math.round(Mu*100);return jsxRuntimeExports.jsxs(Box,{"data-testid":"loop-split-layout",flex:"1 1 auto",minHeight:0,display:"flex",flexDirection:"column",children:[Pu,jsxRuntimeExports.jsxs(Box,{ref:Lu,flex:"1 1 auto",minHeight:0,display:"flex",position:"relative",overflow:"hidden",children:[jsxRuntimeExports.jsxs(Box,{"data-testid":"loop-split-conversation",flex:lo?`0 0 ${Vu}%`:"1 1 auto",minWidth:0,minHeight:0,display:"flex",flexDirection:"column",ml:lo?"-1px":0,children:[$u,Iu,Ru]}),lo?jsxRuntimeExports.jsx(Box,{role:"separator","aria-orientation":"vertical","aria-label":"Resize the conversation and the page","aria-valuemin":Math.round(SPLIT_MIN_SHARE*100),"aria-valuemax":Math.round(SPLIT_MAX_SHARE*100),"aria-valuenow":Vu,tabIndex:0,onPointerDown:Fu,onPointerMove:zu,onPointerUp:Uu,onPointerCancel:Uu,onKeyDown:Hu,flex:"0 0 7px",mx:"-3px",zIndex:1,cursor:"col-resize",display:"flex",justifyContent:"center",outline:"none",touchAction:"none",sx:{"&::before":{content:'""',width:"1px",height:"100%",bg:"border.default"},"&:hover::before, &:focus-visible::before":{width:"3px",bg:"accent.emphasis"}}}):null,jsxRuntimeExports.jsx(Box,{"data-testid":"loop-split-page",sx:lo?{flex:"1 1 0",minWidth:0,minHeight:0,display:"flex",...paneOpening("right")}:{position:"absolute",inset:0,visibility:"hidden",pointerEvents:"none",zIndex:-1},children:Au})]}),Ou]})}const LOOP_PAGE_LAYOUT_PLUGIN_NAME="@datalayer/loop-plugin-page-layout",NO_TURN$4=signal$2({id:0,status:"idle"}),pageLayoutChatMode=signal$2("floating-draggable"),promptStance=signal$2("floating-top");let floatingStance="floating-top";const PAGE_LAYOUT_DISABLED_MODES=["assistant"];function pageLayoutForChatMode(Au){switch(Au){case"sidebar":return{bandMode:"panel",panelMode:"docked"};case"floating":return{bandMode:"panel",panelMode:"overlay"};case"floating-small":return{bandMode:"panel",panelMode:"popup"};default:return{bandMode:"floating",panelMode:"docked"}}}function setPageLayoutChatMode(Au){pageLayoutChatMode.value=Au;const{bandMode:lo}=pageLayoutForChatMode(Au);promptStance.value=lo==="floating"?floatingStance:"docked-top",lo==="panel"&&openPagePanel()}function ChatModeAction(){const Au=useSignalValue$1(pageLayoutChatMode);return jsxRuntimeExports.jsx(ChatViewModeToggle,{value:Au,onChange:setPageLayoutChatMode,disabledModes:PAGE_LAYOUT_DISABLED_MODES})}function LoopPageLayout({parts:Au,promptMode:lo,pageSize:$u}){const Ru=useContributions(LoopChatTurn),Iu=useSignalValue$1(Ru[0]?.value.turn??NO_TURN$4),Pu=useSignalValue$1(pageLayoutChatMode),Ou=lo==="floating"?pageLayoutForChatMode(Pu):{bandMode:"docked",panelMode:"docked"};return jsxRuntimeExports.jsx(PageLayout,{page:Au.editors,hasPage:Au.hasEditor,panel:Au.transcript,band:Au.prompt,chips:Au.chips,picker:Au.picker,transient:Au.transient,activity:Iu.activity,bandMode:Ou.bandMode,panelMode:Ou.panelMode,pageSize:$u})}function ConversationToggle(){return jsxRuntimeExports.jsx(PagePanelToggle,{panelName:"conversation",icon:CommentDiscussionIcon,sx:{order:2}})}const LoopPageLayoutPlugin={name:LOOP_PAGE_LAYOUT_PLUGIN_NAME,config:{arrangement:"page",turnPanel:"below",turnPanelFooter:"full",prompt:"docked",promptAnchor:"top",pageSize:void 0},displayName:"Page layout",description:"The editor — or, in the chat view, the conversation — on a centred sheet, the prompt docked above it at the same width or floating over it as a draggable card, the current turn under the prompt, the conversation in a side panel; or, split, the conversation and the work side by side with a hairline to drag.",octicon:"file",emoji:"📄",build:({config:Au,...lo})=>{if(Au.arrangement==="split")return lo.contribute(LoopChatLayout,{id:"split-layout",prompt:"docked",Component:SplitLayout},{id:"split-layout"}),{components:[]};const $u=Au.prompt,Ru=Au.pageSize;floatingStance=Au.promptAnchor==="bottom"?"floating-bottom":"floating-top",$u==="floating"&&(promptStance.value=floatingStance);const Iu=Pu=>jsxRuntimeExports.jsx(LoopPageLayout,{parts:Pu,promptMode:$u,pageSize:Ru});if(lo.contribute(LoopChatLayout,{id:"page-layout",prompt:$u==="floating"?floatingStance:"docked-top",promptStance:$u==="floating"?promptStance:void 0,Component:Iu},{id:"page-layout"}),Au.turnPanel!=="none"){const Pu=Au.turnPanelFooter,Ou=()=>jsxRuntimeExports.jsx(TurnPanel,{footer:Pu});lo.contribute(LoopPromptPanel,{id:"page-layout-turn",placement:Au.turnPanel,order:0,Component:Ou},{id:"page-layout-turn"})}return{components:[{id:"page-layout-conversation-toggle",slot:LoopSlots.header,Component:ConversationToggle},...$u==="floating"?[{id:"page-layout-chat-mode",slot:LoopSlots.promptAction,Component:ChatModeAction}]:[]]}}};function loopPlugins(Au={}){const{serverUrl:lo,target:$u="browser",defaultEditor:Ru,showViewSelector:Iu=!0,hideChatHeader:Pu=!1,chatHeaderButtons:Ou=!1,promptPlacement:Mu,autoFocusPrompt:Du=!0,suggestionLabels:Lu=!0,fullScreenTopOffset:Bu=0,showAgentVariants:ju=!1,agentSummary:Fu=!0,teamId:zu,teamPicker:Uu=!0,pageLayout:Hu=!1,pageLayoutArrangement:Vu="page",pageLayoutTurnPanel:Gu="below",pageLayoutPrompt:Wu="docked",pageLayoutPromptAnchor:Ku="top",pageLayoutSize:Ju,pageLayoutTurnPanelFooter:Yu="full",localAgent:Xu,localAgentSpec:ed,datalayerAgentSpecId:td,datalayerCreatePayload:nd,datalayerVisitors:od,datalayerKept:sd,embedToken:ad,targetFixed:pd,themeVariant:gd,themeOverrides:xd,colorMode:yd,presence:bd,showTokenUsage:wd,thread:kd,floatingPrompt:cd=!1,editorSelector:dd=!1,editors:md=!0,conversation:ld=!0,commandPalette:hd=!1,pluginsPanel:vd=!1,windowFrame:Sd=!1,firstPromptHook:Td}=Au,Rd=Ru??(md?"notebook":"none");return ld?[configurePlugin(ChatPlugin,{defaultSurface:Rd,showSurfaceSelector:md&&Iu&&!dd,hideHeader:Pu,headerButtons:{newChat:Ou,clear:Ou},promptPlacement:cd?"floating":Mu,autoFocusPrompt:Du,suggestionLabels:Lu,fullScreenTopOffset:Bu,themeVariant:gd,themeOverrides:xd,colorMode:yd,presence:bd,showTokenUsage:wd,...kd?{thread:kd}:{}}),configurePlugin(InputPromptPlugin,{firstPromptHook:Td}),ChatHeaderPlugin,A2uiSurfacePlugin,PapSignInPlugin,ChatViewPlugin,...md?[NotebookViewPlugin,DocumentViewPlugin]:[],configurePlugin(AgentsPlugin,{serverUrl:lo,target:$u,datalayerAgentSpecId:td,datalayerCreatePayload:nd,datalayerVisitors:od,datalayerKept:sd,embedToken:ad,targetFixed:pd,showAgentVariants:ju,showAgentSummary:Fu,teamId:zu,showTeamPicker:Uu,localAgent:Xu??(ed?{createPayload:{description:`Local agent from the ${ed} spec`,agent_library:"pydantic-ai",agent_spec_id:ed,enable_codemode:!1}}:void 0)}),...md?[NotebookExtension,DocumentExtension]:[],A2uiPlugin,AgentspecsPlugin,ModelsPlugin,ThemePlugin,SubagentActivityPlugin,configurePlugin(ShellPlugin,{defaultEditor:Rd,showSelector:md&&dd}),...cd?[PromptPlugin]:[],...Hu?[configurePlugin(LoopPageLayoutPlugin,{arrangement:Vu,turnPanel:Gu,turnPanelFooter:Yu,prompt:Wu,promptAnchor:Ku,pageSize:Ju})]:[],...hd?[LoopCommandsPlugin]:[],...vd?[PluginsPanelPlugin]:[],...Sd?[WindowFramePlugin]:[]]:[ThemePlugin,configurePlugin(ShellPlugin,{defaultEditor:"none",showSelector:!1}),...hd?[LoopCommandsPlugin]:[],...vd?[PluginsPanelPlugin]:[],...Sd?[WindowFramePlugin]:[]]}function LoopEmbed({agentId:Au="",showHeader:lo=!1,chatHeaderActions:$u,headerActions:Ru,headerContainer:Iu,frameTitle:Pu,frameHeight:Ou,sidebarRail:Mu=!1,plugins:Du=[],...Lu}){const Bu=reactExports.useRef(Lu.firstPromptHook);Bu.current=Lu.firstPromptHook;const ju=reactExports.useMemo(()=>buildLoopReactor([...loopPlugins({...Lu,windowFrame:Lu.windowFrame||Pu!==void 0,firstPromptHook:()=>Bu.current?.()}),...Du]),[Lu.serverUrl,Lu.target,Lu.datalayerAgentSpecId,Lu.targetFixed,Lu.themeVariant,JSON.stringify(Lu.themeOverrides??null),Lu.colorMode,Lu.presence?.name,Lu.presence?.face,Lu.presence?.welcome,Lu.presence?.paused,Lu.showTokenUsage,Lu.thread?.id,JSON.stringify(Lu.datalayerCreatePayload??null),JSON.stringify(Lu.datalayerVisitors??null),Lu.datalayerKept?.url,Lu.embedToken,Lu.defaultEditor,Lu.showViewSelector,Lu.hideChatHeader,Lu.chatHeaderButtons,Lu.promptPlacement,Lu.autoFocusPrompt,Lu.suggestionLabels,Lu.fullScreenTopOffset,Lu.showAgentVariants,Lu.agentSummary,Lu.teamId,Lu.teamPicker,Lu.pageLayout,Lu.pageLayoutTurnPanel,Lu.pageLayoutTurnPanelFooter,Lu.pageLayoutPrompt,Lu.pageLayoutPromptAnchor,Lu.pageLayoutSize?.format,Lu.pageLayoutSize?.width,Lu.pageLayoutSize?.height,Lu.localAgentSpec,Lu.floatingPrompt,Lu.editorSelector,Lu.editors,Lu.conversation,Lu.commandPalette,Lu.pluginsPanel,Lu.windowFrame,Pu!==void 0,Du]);useReactor(ju);const Fu=jsxRuntimeExports.jsx(LoopWorkspace,{serverUrl:Lu.serverUrl??"",agentId:Au,reactor:ju,manageReactor:!1,showViewSelector:Lu.showViewSelector,showHeader:lo,chatHeaderActions:$u,headerActions:Ru,headerContainer:Iu,sidebarRail:Mu});return jsxRuntimeExports.jsx(QueryClientProvider,{client:internalQueryClient,children:Pu!==void 0?jsxRuntimeExports.jsx(WindowFrame,{title:Pu,height:Ou,children:Fu}):jsxRuntimeExports.jsx(Box,{height:"100%",minHeight:0,width:"100%",flex:"1 1 auto",minWidth:0,children:Fu})})}const RECORD_KIND_WORDS={session:"Session",tool_call:"Tool call",decision:"Rule",check:"Check",approval:"Approval",output:"Answer",feedback:"Feedback",turn:"Turn",run:"Working",notification:"Notification"};function entryOf(Au){return{uid:String(Au.uid??""),sessionUid:String(Au.session_uid??""),deploymentUid:String(Au.deployment_uid??""),version:Number(Au.version)||0,kind:String(Au.kind??"output"),summary:String(Au.summary??""),payload:Au.payload&&typeof Au.payload=="object"?Au.payload:{},createdAt:String(Au.created_at??"")}}const RUN_END_WORDS={answered:"Answered",stopped:"Stopped",gone:"Its client went before the answer"};function runEndOf(Au){const lo=Au.kind==="output"?Au.payload.status:void 0;return typeof lo=="string"&&lo in RUN_END_WORDS?lo:""}function entrySaid(Au){return Au.summary||RUN_END_WORDS[runEndOf(Au)]||""}const ASKED_FOR_TAG="asked-for";function askedOf(Au){const lo=`<${ASKED_FOR_TAG}>`,$u=`</${ASKED_FOR_TAG}>`;if(!Au.startsWith(lo))return Au;const Ru=Au.indexOf($u);if(Ru<0)throw new Error(`What was asked opens <${ASKED_FOR_TAG}> and never closes it.`);return Au.slice(Ru+$u.length).trimStart()}function sessionSentence(Au){const lo=Au.filter(Ou=>Ou.kind==="tool_call").length,$u=Au.filter(Ou=>Ou.kind==="check"),Ru=Au.map(runEndOf).filter(Boolean),Iu=Ru.filter(Ou=>Ou==="answered").length,Pu=[lo===0?"No tool called":`${lo} tool call${lo===1?"":"s"}`];return $u.length&&Pu.push(`${$u.length} step${$u.length===1?"":"s"} a check did not let pass`),Ru[Ru.length-1]==="stopped"?Pu.push("stopped"):Iu&&Pu.push(`${Iu} answer${Iu===1?"":"s"}`),`${Pu.join(", ")}.`}async function read(Au,lo,$u){if(!Au.aiAgentsUrl)throw new Error("The record service is not configured.");const Ru=await fetch(`${Au.aiAgentsUrl.replace(/\/+$/,"")}/api/ai-agents/v1/apps${lo}`,{headers:Au.token?{Authorization:`Bearer ${Au.token}`}:{}}),Iu=await Ru.json().catch(()=>({}));if(!Ru.ok||Iu.success===!1)throw new Error(`${$u}: ${String(Iu.detail??Ru.status)}`);return Iu}async function listSessions(Au,lo,$u=20,Ru=!1){const Iu=await read(Au,`/sessions?app_uid=${encodeURIComponent(lo)}&limit=${$u}${Ru===null?"":`&tests=${Ru}`}`,"The sessions could not be read");return Array.isArray(Iu.sessions)?Iu.sessions.map(entryOf):[]}async function readSession(Au,lo){const $u=await read(Au,`/records?session_uid=${encodeURIComponent(lo)}&limit=500`,"The session could not be read");return Array.isArray($u.entries)?$u.entries.map(entryOf).filter(Ru=>Ru.kind!=="run"):[]}const APP_ACTIVITY_WORDS={title:"Activity",unsaved:"Recorded once it is saved on Datalayer: each session there — its address, or its Preview on Datalayer — is listed here.",signedOut:"Its activity is its owner’s: sign in to Datalayer to read it.",none:"Nothing yet: a session on Datalayer — its address, or the Preview on Datalayer — is recorded here."},NO_TURN$3=signal$2({id:0,status:"idle"});function useRead(Au,lo,$u=!0){const[Ru,Iu]=reactExports.useState({loading:$u});return reactExports.useEffect(()=>{if(!$u)return;let Pu=!1;return Iu(Ou=>({...Ou,loading:!0})),Au().then(Ou=>!Pu&&Iu({value:Ou,loading:!1}),Ou=>!Pu&&Iu({error:Ou instanceof Error?Ou.message:String(Ou),loading:!1})),()=>{Pu=!0}},[lo,$u]),Ru}function Session({context:Au,session:lo}){const[$u,Ru]=reactExports.useState(!1),Iu=useRead(()=>readSession(Au,lo.sessionUid),`${lo.sessionUid}:${Au.token}`,$u);return jsxRuntimeExports.jsxs(Box,{as:"details",onToggle:Pu=>Ru(Pu.currentTarget.open),borderTop:"1px solid",borderColor:"border.muted",py:2,children:[jsxRuntimeExports.jsxs(Box,{as:"summary",cursor:"pointer",fontSize:1,children:[lo.createdAt?jsxRuntimeExports.jsx(RelativeTime,{datetime:lo.createdAt}):"A session",lo.version?` · version ${lo.version}`:"",Iu.value?` · ${sessionSentence(Iu.value)}`:""]}),$u?Iu.loading?jsxRuntimeExports.jsx(StyledSpinner,{size:"small"}):Iu.error?jsxRuntimeExports.jsx(Text$3,{role:"alert",sx:{fontSize:1},children:Iu.error}):jsxRuntimeExports.jsx(Box,{as:"ol",pl:3,mt:2,mb:0,fontSize:1,children:(Iu.value??[]).map(Pu=>jsxRuntimeExports.jsxs(Box,{as:"li",mb:1,children:[jsxRuntimeExports.jsx(Label,{sx:{mr:2},children:RECORD_KIND_WORDS[Pu.kind]??Pu.kind}),entrySaid(Pu)]},Pu.uid))}):null]})}function AppActivity({appUid:Au}){const lo=useIAMStore(ju=>ju.token)??"",$u=useCoreStore(ju=>ju.configuration)?.aiAgentsUrl??"",Ru=useContributions(LoopChatTurn),Iu=useSignalValue$1(Ru[0]?.value.turn??NO_TURN$3),Pu=Iu.status!=="thinking"&&Iu.status!=="streaming",[Ou,Mu]=reactExports.useState(0);reactExports.useEffect(()=>{Pu&&Mu(Iu.id)},[Pu,Iu.id]);const Du={aiAgentsUrl:$u,token:lo},Lu=!!(Au&&lo),Bu=useRead(()=>listSessions(Du,Au??""),`${Au}:${lo}:${$u}:${Ou}`,Lu);return jsxRuntimeExports.jsxs(Box,{"data-testid":"app-activity",children:[jsxRuntimeExports.jsx(Heading$2,{as:"h3",sx:{fontSize:2,mb:2},children:APP_ACTIVITY_WORDS.title}),Au?lo?Bu.loading&&!Bu.value?jsxRuntimeExports.jsx(StyledSpinner,{size:"small"}):Bu.error?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:1,color:"fg.muted",m:0},children:Bu.error}):(Bu.value??[]).length===0?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:1,color:"fg.muted",m:0},children:APP_ACTIVITY_WORDS.none}):(Bu.value??[]).map(ju=>jsxRuntimeExports.jsx(Session,{context:Du,session:ju},ju.uid)):jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:1,color:"fg.muted",m:0},children:APP_ACTIVITY_WORDS.signedOut}):jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:1,color:"fg.muted",m:0},children:APP_ACTIVITY_WORDS.unsaved})]})}const APP_ACTIVITY_PLUGIN_NAME="@datalayer/loop-plugin-app-activity";function defineAppActivityPlugin(Au,lo){function $u(){return jsxRuntimeExports.jsx(AppActivity,{appUid:lo})}return{name:`${APP_ACTIVITY_PLUGIN_NAME}-${Au.id}`,displayName:`${Au.name}: activity`,description:`What ${Au.name} did, session by session, from its record.`,octicon:"pulse",build:()=>({components:[{id:"app-activity",slot:LoopSlots.sidebar,order:20,Component:$u,rail:{label:"Activity",icon:PulseIcon}}]})}}const APP_PANEL_WIDTH=380;function elementsByPlace(Au){const lo=Au.filter($u=>$u.where==="page");return{panels:Au.filter($u=>$u.where==="panel"),page:lo.length>0?lo[lo.length-1]:null}}function ElementBody({element:Au,send:lo}){return jsxRuntimeExports.jsx(AnswerShowsView,{display:Au.shows,send:($u,Ru)=>lo!==void 0&&!lo($u,Ru)})}function ElementHeader({element:Au}){return jsxRuntimeExports.jsxs(Box,{display:"flex",alignItems:"center",justifyContent:"space-between",gap:2,mb:2,children:[jsxRuntimeExports.jsx(Text$3,{as:"h2",sx:{fontSize:2,fontWeight:"bold",m:0},children:Au.title}),jsxRuntimeExports.jsx(IconButton,{icon:XIcon,variant:"invisible",size:"small","aria-label":`Close ${Au.title}`,onClick:()=>closeLoopElement(Au.id)})]})}function AppElements({workspace:Au}){const lo=reactExports.useSyncExternalStore(onLoopElements,openLoopElements,openLoopElements),{panels:$u,page:Ru}=elementsByPlace(lo),Iu=Au?.viewControls.send;return $u.length===0&&Ru===null?null:jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[$u.length>0?jsxRuntimeExports.jsx(Box,{as:"aside","aria-label":"Side panel",position:"absolute",top:0,right:0,bottom:0,width:`min(${APP_PANEL_WIDTH}px, 100%)`,zIndex:1,overflowY:"auto",borderLeft:"1px solid",borderColor:"border.default",bg:"canvas.subtle",boxShadow:"shadow.medium",p:3,display:"flex",flexDirection:"column",gap:3,children:$u.map(Pu=>jsxRuntimeExports.jsxs(Box,{as:"section","aria-label":Pu.title,children:[jsxRuntimeExports.jsx(ElementHeader,{element:Pu}),jsxRuntimeExports.jsx(ElementBody,{element:Pu,send:Iu})]},Pu.id))}):null,Ru!==null?jsxRuntimeExports.jsxs(Box,{role:"dialog","aria-label":Ru.title,position:"absolute",inset:0,zIndex:2,overflowY:"auto",bg:"canvas.default",p:[3,4],children:[jsxRuntimeExports.jsx(ElementHeader,{element:Ru}),jsxRuntimeExports.jsx(ElementBody,{element:Ru,send:Iu})]}):null]})}const QUESTION_DISPLAY_TYPE="application/vnd.datalayer.loop.question+json",SchemaForm=reactExports.lazy(()=>__vitePreload(()=>import("./chunks/SchemaForm-WIwdKnrk.js"),[],import.meta.url));function questionOf(Au){const lo=Au.data??{},$u=lo.kind;if(Au.type!==QUESTION_DISPLAY_TYPE||$u!=="text"&&$u!=="choice"&&$u!=="file"&&$u!=="form"||typeof lo.prompt!="string")throw new Error(`Display ${Au.id} is not a question`);const Ru=Iu=>Array.isArray(Iu)?Iu.filter(Pu=>typeof Pu=="string"):[];return{kind:$u,prompt:lo.prompt,options:Ru(lo.options),accept:Ru(lo.accept),form:lo.form&&typeof lo.form=="object"?lo.form:{},answered:typeof lo.answered=="string"?lo.answered:null,answerable:(Au.actions??[]).some(Iu=>Iu.name===ANSWER_ACTION)}}function QuestionView({display:Au,act:lo,upload:$u}){const Ru=questionOf(Au),[Iu,Pu]=reactExports.useState(""),[Ou,Mu]=reactExports.useState(null),Du=Bu=>{if(!lo){Mu("The chat cannot take an answer here.");return}Mu(null),Promise.resolve(lo({action:ANSWER_ACTION,payload:{value:Bu}})).catch(ju=>Mu(ju instanceof Error?ju.message:String(ju)))};if(Ru.answered!==null)return jsxRuntimeExports.jsxs(Text$3,{as:"p",sx:{color:"fg.muted",fontSize:1,m:0},children:["Answered: ",Ru.answered]});const Lu=Ru.answerable&&!!lo;return jsxRuntimeExports.jsxs(Box$1,{display:"flex",flexDirection:"column",gap:2,"data-question-kind":Ru.kind,children:[Ru.kind==="choice"?jsxRuntimeExports.jsx(Box$1,{display:"flex",gap:2,flexWrap:"wrap",children:Ru.options.map(Bu=>jsxRuntimeExports.jsx(ButtonComponent,{size:"small",disabled:!Lu,onClick:()=>Du(Bu),children:Bu},Bu))}):null,Ru.kind==="text"?jsxRuntimeExports.jsxs(Box$1,{as:"form",display:"flex",gap:2,onSubmit:Bu=>{Bu.preventDefault(),Iu.trim()&&Du(Iu.trim())},children:[jsxRuntimeExports.jsx(TextInput$1,{"aria-label":Ru.prompt,value:Iu,disabled:!Lu,onChange:Bu=>Pu(Bu.target.value)}),jsxRuntimeExports.jsx(ButtonComponent,{type:"submit",size:"small",disabled:!Lu||!Iu.trim(),children:"Answer"})]}):null,Ru.kind==="form"?jsxRuntimeExports.jsx(reactExports.Suspense,{fallback:null,children:jsxRuntimeExports.jsx(SchemaForm,{schema:Ru.form,disabled:!Lu,onSubmit:({formData:Bu})=>Du(Bu??{})})}):null,Ru.kind==="file"?jsxRuntimeExports.jsx("input",{type:"file","aria-label":Ru.prompt,accept:Ru.accept.join(",")||void 0,disabled:!Lu||!$u,onChange:Bu=>{const ju=Bu.target.files?.[0];if(ju){if(!$u){Mu("The chat cannot take a file here.");return}Mu(null),$u(ju).then(Fu=>Du(Fu)).catch(Fu=>Mu(Fu instanceof Error?Fu.message:String(Fu)))}}}):null,Ou?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{color:"danger.fg",fontSize:1,m:0},children:Ou}):null]})}const APP_ELEMENTS_PLUGIN_NAME="@datalayer/loop-plugin-app-elements",AppElementsPlugin={name:APP_ELEMENTS_PLUGIN_NAME,displayName:"Side panel and pages",description:"What an application opens beside the conversation: a side panel, or a page of its own.",octicon:"sidebar-expand",contributes:[contribution(Renderers,defineRenderer({type:QUESTION_DISPLAY_TYPE,component:QuestionView}),{id:"app-elements:question"})],build:()=>({components:[{id:"app-elements",slot:LoopSlots.root,Component:AppElements}]}),register:()=>clearLoopElements},appComponentsPluginName=Au=>`@datalayer/loop-plugin-app-components-${Au}`,hasCustomComponents=Au=>(Au.interface.customComponents??[]).length>0;function defineAppComponentsPlugin(Au,lo){const $u=Au.interface.customComponents??[];if($u.length===0)throw new Error(`“${Au.name}” has no component of its own to contribute.`);return{name:appComponentsPluginName(Au.id),displayName:`${Au.name}'s components`,description:`The components ${Au.name}'s developer wrote: ${$u.map(Ru=>Ru.name).join(", ")}.`,octicon:"apps",contributes:$u.flatMap(Ru=>[contribution(LoopCanvasBlock,{id:Ru.name,ui:`app:${Au.id}`,component:customComponentEntry(Ru,Au.version)},{id:Ru.name}),contribution(LoopA2uiComponent,{id:Ru.name,app:Au.id,implementation:customImplementation(Ru,Au.version,lo,Au.id)},{id:Ru.name})])}}const COMPUTER_PARTS=["browse","files","shell"],COMPUTER_PART_TOOLS={browse:["open_page","read_page","page_screenshot","click_on_page","type_on_page"],files:["list_computer_files","read_computer_file","write_computer_file"],shell:["execute_code","run_skill_script"]},COMPUTER_WORDS={title:"Computer",part:{browse:"Browse",files:"Files",shell:"Shell"},on:"on",off:"off",none:"It has no computer: browse, files and shell are all off. Turn one on in its permissions to give it one.",offSaid:Au=>`Off, so its agent is given no tool for it: ${Au.join(", ")}.`,browser:"Browser",noBrowser:"No browser is installed on its computer.",noPage:"Its browser has opened no page yet.",pageAlt:Au=>`The page its browser shows: ${Au}`,clickToAct:"Click on the page to click there; with the page selected, what you type goes to it.",typeOnPage:"Text to type on the page",type:"Type",address:"An address to open",open:"Open",scrollUp:"Scroll up",scrollDown:"Scroll down",agentHas:"Its agent has the computer.",youHave:"You have the computer: its agent waits for it until you hand it back.",someoneHas:"Somebody else has taken this computer over.",takeOver:"Take over",handBack:"Hand back",run:"Run",yourCode:"Python to run on its computer",terminal:"What ran on it",nothingRan:"Nothing has run on it yet in this conversation.",files:"Files",notStarted:"Its computer starts when its agent first uses it: no file yet.",emptyDirectory:"Empty.",up:"Up",download:"Download",signedOut:"Its computer is shown once you are signed in to Datalayer."};function computerParts(Au){const lo=Au.permissions?.computer;return{browse:!!lo?.browse,files:!!lo?.files,shell:!!lo?.shell}}const hasComputer=Au=>COMPUTER_PARTS.some(lo=>Au[lo]),partsOff=Au=>COMPUTER_PARTS.filter(lo=>!Au[lo]).map(lo=>COMPUTER_WORDS.part[lo].toLowerCase());function partOf(Au){return COMPUTER_PARTS.find(lo=>COMPUTER_PART_TOOLS[lo].includes(Au))}const OUTPUT_LIMIT=4e3;function outputOf(Au){let lo=Au;if(typeof lo=="string")try{const Ru=JSON.parse(lo);Ru&&typeof Ru=="object"&&!Array.isArray(Ru)&&(lo=Ru)}catch{}let $u;if(lo&&typeof lo=="object"&&!Array.isArray(lo)){const Ru=lo,Iu=[typeof Ru.stdout=="string"?Ru.stdout:Ru.output,Ru.stderr,Ru.error??Ru.execution_error??Ru.code_error].filter(Pu=>typeof Pu=="string"&&Pu.trim()!=="");$u=Iu.length>0?Iu.join(`
|
|
4003
|
+
`);await navigator.clipboard?.writeText(ju),Du(!0)},[$u.user,$u.assistant]);if(Ru==="panel"||$u.status==="idle"||!$u.user||Pu===$u.id)return null;const Bu=$u.status==="thinking"||$u.status==="streaming";return jsxRuntimeExports.jsxs(Box,{"data-turn-panel":"",borderTop:"1px solid",borderColor:"border.muted",px:3,pt:2,pb:Au==="none"?2:1,display:"flex",flexDirection:"column",gap:2,bg:"canvas.default",children:[jsxRuntimeExports.jsx(Box,{display:"flex",justifyContent:"flex-end",children:jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,lineHeight:1.45,px:2,py:1,borderRadius:"10px",bg:"accent.subtle",color:"fg.default",maxWidth:"85%",overflow:"hidden",display:"-webkit-box",WebkitLineClamp:2,WebkitBoxOrient:"vertical"},children:$u.user})}),jsxRuntimeExports.jsxs(Box,{display:"flex",gap:2,alignItems:"flex-start",children:[jsxRuntimeExports.jsx(Box,{ref:Iu,flex:"1 1 auto",minWidth:0,maxHeight:MAX_HEIGHT,overflowY:"auto",fontSize:0,lineHeight:1.5,color:$u.assistant?"fg.default":"fg.muted",whiteSpace:$u.assistant?"normal":"pre-wrap",overflowWrap:"anywhere",children:$u.assistant?jsxRuntimeExports.jsx(Box,{sx:{...streamdownMarkdownStyles,fontSize:0},children:jsxRuntimeExports.jsx(_o$1,{rehypePlugins:REHYPE_PLUGINS_WITHOUT_HTML,children:normalizeAssistantMarkdown($u.assistant)})}):$u.activity?jsxRuntimeExports.jsx(Text$3,{sx:{color:"fg.muted",fontStyle:"italic"},children:$u.activity}):Bu?jsxRuntimeExports.jsx(Thinking,{}):$u.status==="error"?"The agent could not answer.":"Done — the result is in the page."}),jsxRuntimeExports.jsx(IconButton,{icon:CommentDiscussionIcon,size:"small",variant:"invisible","aria-label":"Open the conversation",onClick:openPagePanel,sx:{color:"fg.muted",flexShrink:0}})]}),$u.assistant&&$u.activity?jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:"fg.muted",fontStyle:"italic"},children:$u.activity}):null,Au==="full"?jsxRuntimeExports.jsx(TurnFooter,{usage:$u.usage,live:Bu,latest:!0,padding:0,onCopy:Lu,onRemove:()=>Ou($u.id)}):Au==="actions"?jsxRuntimeExports.jsxs(Box,{display:"flex",justifyContent:"flex-end",gap:1,mt:-1,children:[jsxRuntimeExports.jsx(IconButton,{icon:Mu?CheckIcon:CopyIcon,size:"small",variant:"invisible","aria-label":Mu?"Copied":"Copy this turn",onClick:()=>{Lu()},sx:{color:"fg.muted"}}),jsxRuntimeExports.jsx(IconButton,{icon:XIcon,size:"small",variant:"invisible","aria-label":"Dismiss until the next turn",onClick:()=>Ou($u.id),sx:{color:"fg.muted"}})]}):null]})}const SPLIT_DEFAULT_SHARE=.4,SPLIT_MIN_SHARE=.2,SPLIT_MAX_SHARE=.8,SPLIT_KEY_STEP=.05;function clampSplitShare(Au){return Number.isFinite(Au)?Math.min(SPLIT_MAX_SHARE,Math.max(SPLIT_MIN_SHARE,Au)):SPLIT_DEFAULT_SHARE}function splitShareForKey(Au,lo){switch(lo){case"ArrowLeft":return clampSplitShare(Au-SPLIT_KEY_STEP);case"ArrowRight":return clampSplitShare(Au+SPLIT_KEY_STEP);case"Home":return SPLIT_MIN_SHARE;case"End":return SPLIT_MAX_SHARE;default:return null}}function SplitLayout({editors:Au,hasEditor:lo,transcript:$u,prompt:Ru,chips:Iu,picker:Pu,transient:Ou}){const[Mu,Du]=reactExports.useState(SPLIT_DEFAULT_SHARE),Lu=reactExports.useRef(null),Bu=reactExports.useRef(!1),ju=reactExports.useCallback(Gu=>{const Wu=Lu.current?.getBoundingClientRect();return!Wu||Wu.width<=0?null:clampSplitShare((Gu-Wu.left)/Wu.width)},[]),Fu=Gu=>{Bu.current=!0,Gu.currentTarget.setPointerCapture?.(Gu.pointerId),Gu.preventDefault()},zu=Gu=>{if(!Bu.current)return;const Wu=ju(Gu.clientX);Wu!==null&&Du(Wu)},Uu=Gu=>{Bu.current=!1,Gu.currentTarget.releasePointerCapture?.(Gu.pointerId)},Hu=Gu=>{const Wu=splitShareForKey(Mu,Gu.key);Wu!==null&&(Gu.preventDefault(),Du(Wu))},Vu=Math.round(Mu*100);return jsxRuntimeExports.jsxs(Box,{"data-testid":"loop-split-layout",flex:"1 1 auto",minHeight:0,display:"flex",flexDirection:"column",children:[Pu,jsxRuntimeExports.jsxs(Box,{ref:Lu,flex:"1 1 auto",minHeight:0,display:"flex",position:"relative",overflow:"hidden",children:[jsxRuntimeExports.jsxs(Box,{"data-testid":"loop-split-conversation",flex:lo?`0 0 ${Vu}%`:"1 1 auto",minWidth:0,minHeight:0,display:"flex",flexDirection:"column",ml:lo?"-1px":0,children:[$u,Iu,Ru]}),lo?jsxRuntimeExports.jsx(Box,{role:"separator","aria-orientation":"vertical","aria-label":"Resize the conversation and the page","aria-valuemin":Math.round(SPLIT_MIN_SHARE*100),"aria-valuemax":Math.round(SPLIT_MAX_SHARE*100),"aria-valuenow":Vu,tabIndex:0,onPointerDown:Fu,onPointerMove:zu,onPointerUp:Uu,onPointerCancel:Uu,onKeyDown:Hu,flex:"0 0 7px",mx:"-3px",zIndex:1,cursor:"col-resize",display:"flex",justifyContent:"center",outline:"none",touchAction:"none",sx:{"&::before":{content:'""',width:"1px",height:"100%",bg:"border.default"},"&:hover::before, &:focus-visible::before":{width:"3px",bg:"accent.emphasis"}}}):null,jsxRuntimeExports.jsx(Box,{"data-testid":"loop-split-page",sx:lo?{flex:"1 1 0",minWidth:0,minHeight:0,display:"flex",...paneOpening("right")}:{position:"absolute",inset:0,visibility:"hidden",pointerEvents:"none",zIndex:-1},children:Au})]}),Ou]})}const LOOP_PAGE_LAYOUT_PLUGIN_NAME="@datalayer/loop-plugin-page-layout",NO_TURN$4=signal$2({id:0,status:"idle"}),pageLayoutChatMode=signal$2("floating-draggable"),promptStance=signal$2("floating-top");let floatingStance="floating-top";const PAGE_LAYOUT_DISABLED_MODES=["assistant"];function pageLayoutForChatMode(Au){switch(Au){case"sidebar":return{bandMode:"panel",panelMode:"docked"};case"floating":return{bandMode:"panel",panelMode:"overlay"};case"floating-small":return{bandMode:"panel",panelMode:"popup"};default:return{bandMode:"floating",panelMode:"docked"}}}function setPageLayoutChatMode(Au){pageLayoutChatMode.value=Au;const{bandMode:lo}=pageLayoutForChatMode(Au);promptStance.value=lo==="floating"?floatingStance:"docked-top",lo==="panel"&&openPagePanel()}function ChatModeAction(){const Au=useSignalValue$1(pageLayoutChatMode);return jsxRuntimeExports.jsx(ChatViewModeToggle,{value:Au,onChange:setPageLayoutChatMode,disabledModes:PAGE_LAYOUT_DISABLED_MODES})}function LoopPageLayout({parts:Au,promptMode:lo,pageSize:$u}){const Ru=useContributions(LoopChatTurn),Iu=useSignalValue$1(Ru[0]?.value.turn??NO_TURN$4),Pu=useSignalValue$1(pageLayoutChatMode),Ou=lo==="floating"?pageLayoutForChatMode(Pu):{bandMode:"docked",panelMode:"docked"};return jsxRuntimeExports.jsx(PageLayout,{page:Au.editors,hasPage:Au.hasEditor,panel:Au.transcript,band:Au.prompt,chips:Au.chips,picker:Au.picker,transient:Au.transient,activity:Iu.activity,bandMode:Ou.bandMode,panelMode:Ou.panelMode,pageSize:$u})}function ConversationToggle(){return jsxRuntimeExports.jsx(PagePanelToggle,{panelName:"conversation",icon:CommentDiscussionIcon,sx:{order:2}})}const LoopPageLayoutPlugin={name:LOOP_PAGE_LAYOUT_PLUGIN_NAME,config:{arrangement:"page",turnPanel:"below",turnPanelFooter:"full",prompt:"docked",promptAnchor:"top",pageSize:void 0},displayName:"Page layout",description:"The editor — or, in the chat view, the conversation — on a centred sheet, the prompt docked above it at the same width or floating over it as a draggable card, the current turn under the prompt, the conversation in a side panel; or, split, the conversation and the work side by side with a hairline to drag.",octicon:"file",emoji:"📄",build:({config:Au,...lo})=>{if(Au.arrangement==="split")return lo.contribute(LoopChatLayout,{id:"split-layout",prompt:"docked",Component:SplitLayout},{id:"split-layout"}),{components:[]};const $u=Au.prompt,Ru=Au.pageSize;floatingStance=Au.promptAnchor==="bottom"?"floating-bottom":"floating-top",$u==="floating"&&(promptStance.value=floatingStance);const Iu=Pu=>jsxRuntimeExports.jsx(LoopPageLayout,{parts:Pu,promptMode:$u,pageSize:Ru});if(lo.contribute(LoopChatLayout,{id:"page-layout",prompt:$u==="floating"?floatingStance:"docked-top",promptStance:$u==="floating"?promptStance:void 0,Component:Iu},{id:"page-layout"}),Au.turnPanel!=="none"){const Pu=Au.turnPanelFooter,Ou=()=>jsxRuntimeExports.jsx(TurnPanel,{footer:Pu});lo.contribute(LoopPromptPanel,{id:"page-layout-turn",placement:Au.turnPanel,order:0,Component:Ou},{id:"page-layout-turn"})}return{components:[{id:"page-layout-conversation-toggle",slot:LoopSlots.header,Component:ConversationToggle},...$u==="floating"?[{id:"page-layout-chat-mode",slot:LoopSlots.promptAction,Component:ChatModeAction}]:[]]}}};function loopPlugins(Au={}){const{serverUrl:lo,target:$u="browser",defaultEditor:Ru,showViewSelector:Iu=!0,hideChatHeader:Pu=!1,chatHeaderButtons:Ou=!1,promptPlacement:Mu,autoFocusPrompt:Du=!0,suggestionLabels:Lu=!0,fullScreenTopOffset:Bu=0,showAgentVariants:ju=!1,agentSummary:Fu=!0,teamId:zu,teamPicker:Uu=!0,pageLayout:Hu=!1,pageLayoutArrangement:Vu="page",pageLayoutTurnPanel:Gu="below",pageLayoutPrompt:Wu="docked",pageLayoutPromptAnchor:Ku="top",pageLayoutSize:Ju,pageLayoutTurnPanelFooter:Yu="full",localAgent:Xu,localAgentSpec:ed,datalayerAgentSpecId:td,datalayerCreatePayload:nd,datalayerVisitors:od,datalayerKept:sd,embedToken:ad,targetFixed:pd,themeVariant:gd,themeOverrides:xd,colorMode:yd,presence:bd,showTokenUsage:wd,thread:kd,floatingPrompt:cd=!1,editorSelector:dd=!1,editors:md=!0,conversation:ld=!0,commandPalette:hd=!1,pluginsPanel:vd=!1,windowFrame:Sd=!1,firstPromptHook:Td}=Au,Rd=Ru??(md?"notebook":"none");return ld?[configurePlugin(ChatPlugin,{defaultSurface:Rd,showSurfaceSelector:md&&Iu&&!dd,hideHeader:Pu,headerButtons:{newChat:Ou,clear:Ou},promptPlacement:cd?"floating":Mu,autoFocusPrompt:Du,suggestionLabels:Lu,fullScreenTopOffset:Bu,themeVariant:gd,themeOverrides:xd,colorMode:yd,presence:bd,showTokenUsage:wd,...kd?{thread:kd}:{}}),configurePlugin(InputPromptPlugin,{firstPromptHook:Td}),ChatHeaderPlugin,A2uiSurfacePlugin,PapSignInPlugin,ChatViewPlugin,...md?[NotebookViewPlugin,DocumentViewPlugin]:[],configurePlugin(AgentsPlugin,{serverUrl:lo,target:$u,datalayerAgentSpecId:td,datalayerCreatePayload:nd,datalayerVisitors:od,datalayerKept:sd,embedToken:ad,targetFixed:pd,showAgentVariants:ju,showAgentSummary:Fu,teamId:zu,showTeamPicker:Uu,localAgent:Xu??(ed?{createPayload:{description:`Local agent from the ${ed} spec`,agent_library:"pydantic-ai",agent_spec_id:ed,enable_codemode:!1}}:void 0)}),...md?[NotebookExtension,DocumentExtension]:[],A2uiPlugin,AgentspecsPlugin,ModelsPlugin,ThemePlugin,SubagentActivityPlugin,configurePlugin(ShellPlugin,{defaultEditor:Rd,showSelector:md&&dd}),...cd?[PromptPlugin]:[],...Hu?[configurePlugin(LoopPageLayoutPlugin,{arrangement:Vu,turnPanel:Gu,turnPanelFooter:Yu,prompt:Wu,promptAnchor:Ku,pageSize:Ju})]:[],...hd?[LoopCommandsPlugin]:[],...vd?[PluginsPanelPlugin]:[],...Sd?[WindowFramePlugin]:[]]:[ThemePlugin,configurePlugin(ShellPlugin,{defaultEditor:"none",showSelector:!1}),...hd?[LoopCommandsPlugin]:[],...vd?[PluginsPanelPlugin]:[],...Sd?[WindowFramePlugin]:[]]}function LoopEmbed({agentId:Au="",showHeader:lo=!1,chatHeaderActions:$u,headerActions:Ru,headerContainer:Iu,frameTitle:Pu,frameHeight:Ou,sidebarRail:Mu=!1,plugins:Du=[],...Lu}){const Bu=reactExports.useRef(Lu.firstPromptHook);Bu.current=Lu.firstPromptHook;const ju=reactExports.useMemo(()=>buildLoopReactor([...loopPlugins({...Lu,windowFrame:Lu.windowFrame||Pu!==void 0,firstPromptHook:()=>Bu.current?.()}),...Du]),[Lu.serverUrl,Lu.target,Lu.datalayerAgentSpecId,Lu.targetFixed,Lu.themeVariant,JSON.stringify(Lu.themeOverrides??null),Lu.colorMode,Lu.presence?.name,Lu.presence?.face,Lu.presence?.welcome,Lu.presence?.paused,Lu.showTokenUsage,Lu.thread?.id,JSON.stringify(Lu.datalayerCreatePayload??null),JSON.stringify(Lu.datalayerVisitors??null),Lu.datalayerKept?.url,Lu.embedToken,Lu.defaultEditor,Lu.showViewSelector,Lu.hideChatHeader,Lu.chatHeaderButtons,Lu.promptPlacement,Lu.autoFocusPrompt,Lu.suggestionLabels,Lu.fullScreenTopOffset,Lu.showAgentVariants,Lu.agentSummary,Lu.teamId,Lu.teamPicker,Lu.pageLayout,Lu.pageLayoutTurnPanel,Lu.pageLayoutTurnPanelFooter,Lu.pageLayoutPrompt,Lu.pageLayoutPromptAnchor,Lu.pageLayoutSize?.format,Lu.pageLayoutSize?.width,Lu.pageLayoutSize?.height,Lu.localAgentSpec,Lu.floatingPrompt,Lu.editorSelector,Lu.editors,Lu.conversation,Lu.commandPalette,Lu.pluginsPanel,Lu.windowFrame,Pu!==void 0,Du]);useReactor(ju);const Fu=jsxRuntimeExports.jsx(LoopWorkspace,{serverUrl:Lu.serverUrl??"",agentId:Au,reactor:ju,manageReactor:!1,showViewSelector:Lu.showViewSelector,showHeader:lo,chatHeaderActions:$u,headerActions:Ru,headerContainer:Iu,sidebarRail:Mu});return jsxRuntimeExports.jsx(QueryClientProvider,{client:internalQueryClient,children:Pu!==void 0?jsxRuntimeExports.jsx(WindowFrame,{title:Pu,height:Ou,children:Fu}):jsxRuntimeExports.jsx(Box,{height:"100%",minHeight:0,width:"100%",flex:"1 1 auto",minWidth:0,children:Fu})})}const APP_ACTIVITY_WORDS={title:"Activity",unsaved:"Recorded once it is saved on Datalayer: each session there — its address, or its Preview on Datalayer — is listed here.",signedOut:"Its activity is its owner’s: sign in to Datalayer to read it.",none:"Nothing yet: a session on Datalayer — its address, or the Preview on Datalayer — is recorded here."},NO_TURN$3=signal$2({id:0,status:"idle"});function useRead(Au,lo,$u=!0){const[Ru,Iu]=reactExports.useState({loading:$u});return reactExports.useEffect(()=>{if(!$u)return;let Pu=!1;return Iu(Ou=>({...Ou,loading:!0})),Au().then(Ou=>!Pu&&Iu({value:Ou,loading:!1}),Ou=>!Pu&&Iu({error:Ou instanceof Error?Ou.message:String(Ou),loading:!1})),()=>{Pu=!0}},[lo,$u]),Ru}function Session({context:Au,session:lo}){const[$u,Ru]=reactExports.useState(!1),Iu=useRead(()=>readSession(Au,lo.sessionUid),`${lo.sessionUid}:${Au.token}`,$u);return jsxRuntimeExports.jsxs(Box,{as:"details",onToggle:Pu=>Ru(Pu.currentTarget.open),borderTop:"1px solid",borderColor:"border.muted",py:2,children:[jsxRuntimeExports.jsxs(Box,{as:"summary",cursor:"pointer",fontSize:1,children:[lo.createdAt?jsxRuntimeExports.jsx(RelativeTime,{datetime:lo.createdAt}):"A session",lo.version?` · version ${lo.version}`:"",Iu.value?` · ${sessionSentence(Iu.value)}`:""]}),$u?Iu.loading?jsxRuntimeExports.jsx(StyledSpinner,{size:"small"}):Iu.error?jsxRuntimeExports.jsx(Text$3,{role:"alert",sx:{fontSize:1},children:Iu.error}):jsxRuntimeExports.jsx(Box,{as:"ol",pl:3,mt:2,mb:0,fontSize:1,children:(Iu.value??[]).map(Pu=>jsxRuntimeExports.jsxs(Box,{as:"li",mb:1,children:[jsxRuntimeExports.jsx(Label,{sx:{mr:2},children:RECORD_KIND_WORDS[Pu.kind]??Pu.kind}),entrySaid(Pu)]},Pu.uid))}):null]})}function AppActivity({appUid:Au}){const lo=useIAMStore(ju=>ju.token)??"",$u=useCoreStore(ju=>ju.configuration)?.aiAgentsUrl??"",Ru=useContributions(LoopChatTurn),Iu=useSignalValue$1(Ru[0]?.value.turn??NO_TURN$3),Pu=Iu.status!=="thinking"&&Iu.status!=="streaming",[Ou,Mu]=reactExports.useState(0);reactExports.useEffect(()=>{Pu&&Mu(Iu.id)},[Pu,Iu.id]);const Du={aiAgentsUrl:$u,token:lo},Lu=!!(Au&&lo),Bu=useRead(()=>listSessions(Du,Au??""),`${Au}:${lo}:${$u}:${Ou}`,Lu);return jsxRuntimeExports.jsxs(Box,{"data-testid":"app-activity",children:[jsxRuntimeExports.jsx(Heading$2,{as:"h3",sx:{fontSize:2,mb:2},children:APP_ACTIVITY_WORDS.title}),Au?lo?Bu.loading&&!Bu.value?jsxRuntimeExports.jsx(StyledSpinner,{size:"small"}):Bu.error?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:1,color:"fg.muted",m:0},children:Bu.error}):(Bu.value??[]).length===0?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:1,color:"fg.muted",m:0},children:APP_ACTIVITY_WORDS.none}):(Bu.value??[]).map(ju=>jsxRuntimeExports.jsx(Session,{context:Du,session:ju},ju.uid)):jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:1,color:"fg.muted",m:0},children:APP_ACTIVITY_WORDS.signedOut}):jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:1,color:"fg.muted",m:0},children:APP_ACTIVITY_WORDS.unsaved})]})}const APP_ACTIVITY_PLUGIN_NAME="@datalayer/loop-plugin-app-activity";function defineAppActivityPlugin(Au,lo){function $u(){return jsxRuntimeExports.jsx(AppActivity,{appUid:lo})}return{name:`${APP_ACTIVITY_PLUGIN_NAME}-${Au.id}`,displayName:`${Au.name}: activity`,description:`What ${Au.name} did, session by session, from its record.`,octicon:"pulse",build:()=>({components:[{id:"app-activity",slot:LoopSlots.sidebar,order:20,Component:$u,rail:{label:"Activity",icon:PulseIcon}}]})}}const APP_PANEL_WIDTH=380;function elementsByPlace(Au){const lo=Au.filter($u=>$u.where==="page");return{panels:Au.filter($u=>$u.where==="panel"),page:lo.length>0?lo[lo.length-1]:null}}function ElementBody({element:Au,send:lo}){return jsxRuntimeExports.jsx(AnswerShowsView,{display:Au.shows,send:($u,Ru)=>lo!==void 0&&!lo($u,Ru)})}function ElementHeader({element:Au}){return jsxRuntimeExports.jsxs(Box,{display:"flex",alignItems:"center",justifyContent:"space-between",gap:2,mb:2,children:[jsxRuntimeExports.jsx(Text$3,{as:"h2",sx:{fontSize:2,fontWeight:"bold",m:0},children:Au.title}),jsxRuntimeExports.jsx(IconButton,{icon:XIcon,variant:"invisible",size:"small","aria-label":`Close ${Au.title}`,onClick:()=>closeLoopElement(Au.id)})]})}function AppElements({workspace:Au}){const lo=reactExports.useSyncExternalStore(onLoopElements,openLoopElements,openLoopElements),{panels:$u,page:Ru}=elementsByPlace(lo),Iu=Au?.viewControls.send;return $u.length===0&&Ru===null?null:jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[$u.length>0?jsxRuntimeExports.jsx(Box,{as:"aside","aria-label":"Side panel",position:"absolute",top:0,right:0,bottom:0,width:`min(${APP_PANEL_WIDTH}px, 100%)`,zIndex:1,overflowY:"auto",borderLeft:"1px solid",borderColor:"border.default",bg:"canvas.subtle",boxShadow:"shadow.medium",p:3,display:"flex",flexDirection:"column",gap:3,children:$u.map(Pu=>jsxRuntimeExports.jsxs(Box,{as:"section","aria-label":Pu.title,children:[jsxRuntimeExports.jsx(ElementHeader,{element:Pu}),jsxRuntimeExports.jsx(ElementBody,{element:Pu,send:Iu})]},Pu.id))}):null,Ru!==null?jsxRuntimeExports.jsxs(Box,{role:"dialog","aria-label":Ru.title,position:"absolute",inset:0,zIndex:2,overflowY:"auto",bg:"canvas.default",p:[3,4],children:[jsxRuntimeExports.jsx(ElementHeader,{element:Ru}),jsxRuntimeExports.jsx(ElementBody,{element:Ru,send:Iu})]}):null]})}const QUESTION_DISPLAY_TYPE="application/vnd.datalayer.loop.question+json",SchemaForm=reactExports.lazy(()=>__vitePreload(()=>import("./chunks/SchemaForm-WIwdKnrk.js"),[],import.meta.url));function questionOf(Au){const lo=Au.data??{},$u=lo.kind;if(Au.type!==QUESTION_DISPLAY_TYPE||$u!=="text"&&$u!=="choice"&&$u!=="file"&&$u!=="form"||typeof lo.prompt!="string")throw new Error(`Display ${Au.id} is not a question`);const Ru=Iu=>Array.isArray(Iu)?Iu.filter(Pu=>typeof Pu=="string"):[];return{kind:$u,prompt:lo.prompt,options:Ru(lo.options),accept:Ru(lo.accept),form:lo.form&&typeof lo.form=="object"?lo.form:{},answered:typeof lo.answered=="string"?lo.answered:null,answerable:(Au.actions??[]).some(Iu=>Iu.name===ANSWER_ACTION)}}function QuestionView({display:Au,act:lo,upload:$u}){const Ru=questionOf(Au),[Iu,Pu]=reactExports.useState(""),[Ou,Mu]=reactExports.useState(null),Du=Bu=>{if(!lo){Mu("The chat cannot take an answer here.");return}Mu(null),Promise.resolve(lo({action:ANSWER_ACTION,payload:{value:Bu}})).catch(ju=>Mu(ju instanceof Error?ju.message:String(ju)))};if(Ru.answered!==null)return jsxRuntimeExports.jsxs(Text$3,{as:"p",sx:{color:"fg.muted",fontSize:1,m:0},children:["Answered: ",Ru.answered]});const Lu=Ru.answerable&&!!lo;return jsxRuntimeExports.jsxs(Box$1,{display:"flex",flexDirection:"column",gap:2,"data-question-kind":Ru.kind,children:[Ru.kind==="choice"?jsxRuntimeExports.jsx(Box$1,{display:"flex",gap:2,flexWrap:"wrap",children:Ru.options.map(Bu=>jsxRuntimeExports.jsx(ButtonComponent,{size:"small",disabled:!Lu,onClick:()=>Du(Bu),children:Bu},Bu))}):null,Ru.kind==="text"?jsxRuntimeExports.jsxs(Box$1,{as:"form",display:"flex",gap:2,onSubmit:Bu=>{Bu.preventDefault(),Iu.trim()&&Du(Iu.trim())},children:[jsxRuntimeExports.jsx(TextInput$1,{"aria-label":Ru.prompt,value:Iu,disabled:!Lu,onChange:Bu=>Pu(Bu.target.value)}),jsxRuntimeExports.jsx(ButtonComponent,{type:"submit",size:"small",disabled:!Lu||!Iu.trim(),children:"Answer"})]}):null,Ru.kind==="form"?jsxRuntimeExports.jsx(reactExports.Suspense,{fallback:null,children:jsxRuntimeExports.jsx(SchemaForm,{schema:Ru.form,disabled:!Lu,onSubmit:({formData:Bu})=>Du(Bu??{})})}):null,Ru.kind==="file"?jsxRuntimeExports.jsx("input",{type:"file","aria-label":Ru.prompt,accept:Ru.accept.join(",")||void 0,disabled:!Lu||!$u,onChange:Bu=>{const ju=Bu.target.files?.[0];if(ju){if(!$u){Mu("The chat cannot take a file here.");return}Mu(null),$u(ju).then(Fu=>Du(Fu)).catch(Fu=>Mu(Fu instanceof Error?Fu.message:String(Fu)))}}}):null,Ou?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{color:"danger.fg",fontSize:1,m:0},children:Ou}):null]})}const APP_ELEMENTS_PLUGIN_NAME="@datalayer/loop-plugin-app-elements",AppElementsPlugin={name:APP_ELEMENTS_PLUGIN_NAME,displayName:"Side panel and pages",description:"What an application opens beside the conversation: a side panel, or a page of its own.",octicon:"sidebar-expand",contributes:[contribution(Renderers,defineRenderer({type:QUESTION_DISPLAY_TYPE,component:QuestionView}),{id:"app-elements:question"})],build:()=>({components:[{id:"app-elements",slot:LoopSlots.root,Component:AppElements}]}),register:()=>clearLoopElements},appComponentsPluginName=Au=>`@datalayer/loop-plugin-app-components-${Au}`,hasCustomComponents=Au=>(Au.interface.customComponents??[]).length>0;function defineAppComponentsPlugin(Au,lo){const $u=Au.interface.customComponents??[];if($u.length===0)throw new Error(`“${Au.name}” has no component of its own to contribute.`);return{name:appComponentsPluginName(Au.id),displayName:`${Au.name}'s components`,description:`The components ${Au.name}'s developer wrote: ${$u.map(Ru=>Ru.name).join(", ")}.`,octicon:"apps",contributes:$u.flatMap(Ru=>[contribution(LoopCanvasBlock,{id:Ru.name,ui:`app:${Au.id}`,component:customComponentEntry(Ru,Au.version)},{id:Ru.name}),contribution(LoopA2uiComponent,{id:Ru.name,app:Au.id,implementation:customImplementation(Ru,Au.version,lo,Au.id)},{id:Ru.name})])}}const COMPUTER_PARTS=["browse","files","shell"],COMPUTER_PART_TOOLS={browse:["open_page","read_page","page_screenshot","click_on_page","type_on_page"],files:["list_computer_files","read_computer_file","write_computer_file"],shell:["execute_code","run_skill_script"]},COMPUTER_WORDS={title:"Computer",part:{browse:"Browse",files:"Files",shell:"Shell"},on:"on",off:"off",none:"It has no computer: browse, files and shell are all off. Turn one on in its permissions to give it one.",offSaid:Au=>`Off, so its agent is given no tool for it: ${Au.join(", ")}.`,browser:"Browser",noBrowser:"No browser is installed on its computer.",noPage:"Its browser has opened no page yet.",pageAlt:Au=>`The page its browser shows: ${Au}`,clickToAct:"Click on the page to click there; with the page selected, what you type goes to it.",typeOnPage:"Text to type on the page",type:"Type",address:"An address to open",open:"Open",scrollUp:"Scroll up",scrollDown:"Scroll down",agentHas:"Its agent has the computer.",youHave:"You have the computer: its agent waits for it until you hand it back.",someoneHas:"Somebody else has taken this computer over.",takeOver:"Take over",handBack:"Hand back",run:"Run",yourCode:"Python to run on its computer",terminal:"What ran on it",nothingRan:"Nothing has run on it yet in this conversation.",files:"Files",notStarted:"Its computer starts when its agent first uses it: no file yet.",emptyDirectory:"Empty.",up:"Up",download:"Download",signedOut:"Its computer is shown once you are signed in to Datalayer."};function computerParts(Au){const lo=Au.permissions?.computer;return{browse:!!lo?.browse,files:!!lo?.files,shell:!!lo?.shell}}const hasComputer=Au=>COMPUTER_PARTS.some(lo=>Au[lo]),partsOff=Au=>COMPUTER_PARTS.filter(lo=>!Au[lo]).map(lo=>COMPUTER_WORDS.part[lo].toLowerCase());function partOf(Au){return COMPUTER_PARTS.find(lo=>COMPUTER_PART_TOOLS[lo].includes(Au))}const OUTPUT_LIMIT=4e3;function outputOf(Au){let lo=Au;if(typeof lo=="string")try{const Ru=JSON.parse(lo);Ru&&typeof Ru=="object"&&!Array.isArray(Ru)&&(lo=Ru)}catch{}let $u;if(lo&&typeof lo=="object"&&!Array.isArray(lo)){const Ru=lo,Iu=[typeof Ru.stdout=="string"?Ru.stdout:Ru.output,Ru.stderr,Ru.error??Ru.execution_error??Ru.code_error].filter(Pu=>typeof Pu=="string"&&Pu.trim()!=="");$u=Iu.length>0?Iu.join(`
|
|
4004
4004
|
`):"stdout"in Ru||"output"in Ru?"":JSON.stringify(lo,null,2)}else $u=typeof lo=="string"?lo:lo==null?"":JSON.stringify(lo,null,2);return $u.length>OUTPUT_LIMIT?`${$u.slice(0,OUTPUT_LIMIT)}
|
|
4005
4005
|
… (${($u.length-OUTPUT_LIMIT).toLocaleString("en")} characters more)`:$u}function commandOf(Au){for(const lo of["code","path","script_name","url","selector"]){const $u=Au[lo];if(typeof $u=="string"&&$u.trim())return $u}return Object.keys(Au).length?JSON.stringify(Au):""}function terminalEntries(Au){const lo=[];for(const $u of Au){if($u.role!=="tool")continue;const Ru=partOf($u.name);Ru&&lo.push({tool:$u.name,part:Ru,command:commandOf($u.args??{}),output:$u.result===void 0?void 0:outputOf($u.result)})}return lo}const computerUrl=(Au,lo="")=>`${Au.serverUrl.replace(/\/+$/,"")}/api/v1/apps/agents/${encodeURIComponent(Au.agentId)}/computer${lo}`;function computerFileUrl(Au,lo){const $u=computerUrl(Au,`/file?path=${encodeURIComponent(lo)}`),Ru=(Au.userAppsUrl||"").trim();if(!Ru)return $u;try{const Iu=new URL($u),Pu=new URL(Ru);return Iu.protocol=Pu.protocol,Iu.host=Pu.host,Iu.toString()}catch{return $u}}async function asked(Au,lo,$u={}){const Ru=await fetch(computerUrl(Au,lo),{...$u,headers:{...$u.body?{"Content-Type":"application/json"}:{},...Au.token?{Authorization:`Bearer ${Au.token}`}:{}}});if(!Ru.ok){let Iu=`${Ru.status}`;try{const Pu=await Ru.json();Iu=typeof Pu.detail=="string"?Pu.detail:Iu}catch{}throw new Error(Iu)}return Ru}const readComputer=async Au=>(await asked(Au,"")).json(),listComputerFiles=async(Au,lo=".")=>(await(await asked(Au,`/files?path=${encodeURIComponent(lo)}`)).json()).entries,downloadComputerFile=async(Au,lo)=>{const $u=await fetch(computerFileUrl(Au,lo),{headers:Au.token?{Authorization:`Bearer ${Au.token}`}:{}});if(!$u.ok){let Ru=`${$u.status}`;try{const Iu=await $u.json();Ru=typeof Iu.detail=="string"?Iu.detail:Ru}catch{}throw new Error(Ru)}return $u.blob()},takeOverComputer=async Au=>(await asked(Au,"/take-over",{method:"POST"})).json(),handBackComputer=async Au=>{await asked(Au,"/hand-back",{method:"POST"})},runOnComputer=async(Au,lo)=>(await asked(Au,"/run",{method:"POST",body:JSON.stringify({code:lo})})).json(),BROWSER_KEYS=["Enter","Tab","Backspace","Escape","ArrowUp","ArrowDown","ArrowLeft","ArrowRight","PageUp","PageDown"],readBrowserScreenshot=async Au=>{const lo=await fetch(computerUrl(Au,"/browser/screenshot"),{headers:Au.token?{Authorization:`Bearer ${Au.token}`}:{},cache:"no-store"});if(lo.status!==404){if(!lo.ok){let $u=`${lo.status}`;try{const Ru=await lo.json();$u=typeof Ru.detail=="string"?Ru.detail:$u}catch{}throw new Error($u)}return lo.blob()}},onBrowser=async(Au,lo,$u)=>(await(await asked(Au,`/browser/${lo}`,{method:"POST",body:JSON.stringify($u)})).json()).page,clickOnBrowser=(Au,lo,$u)=>onBrowser(Au,"click",{x:lo,y:$u}),typeOnBrowser=(Au,lo)=>onBrowser(Au,"type",{text:lo}),pressOnBrowser=(Au,lo)=>onBrowser(Au,"key",{key:lo}),scrollBrowser=(Au,lo)=>onBrowser(Au,"scroll",{dy:lo}),openOnBrowser=(Au,lo)=>onBrowser(Au,"open",{url:lo});function pointOnPage(Au,lo,$u){const Ru=(Iu,Pu,Ou)=>Pu>0?Math.round(Iu*Ou/Pu):Iu;return{x:Math.max(0,Math.min($u.width,Ru(Au.x,lo.width,$u.width))),y:Math.max(0,Math.min($u.height,Ru(Au.y,lo.height,$u.height)))}}function parentOf(Au){const lo=Au.split("/").filter($u=>$u&&$u!==".");return lo.pop(),lo.length?lo.join("/"):"."}const NO_TURN$2=signal$2({id:0,status:"idle"}),NO_CONVERSATION$1=signal$2([]),MONO_FACE='ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace',MONO={fontFamily:MONO_FACE,fontSize:0,whiteSpace:"pre-wrap",wordBreak:"break-word",m:0};function Parts({app:Au}){const lo=computerParts(Au),$u=partsOff(lo);return jsxRuntimeExports.jsxs(Box,{"data-testid":"computer-parts",children:[jsxRuntimeExports.jsx(Box,{display:"flex",gap:1,flexWrap:"wrap",mb:1,children:COMPUTER_PARTS.map(Ru=>jsxRuntimeExports.jsxs(Label,{variant:lo[Ru]?"success":"secondary","data-part":Ru,"data-on":lo[Ru]?"true":"false",children:[COMPUTER_WORDS.part[Ru],":"," ",lo[Ru]?COMPUTER_WORDS.on:COMPUTER_WORDS.off]},Ru))}),$u.length>0&&$u.length<COMPUTER_PARTS.length?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:0,color:"fg.muted",m:0},children:COMPUTER_WORDS.offSaid($u)}):null]})}function Terminal({conversation:Au}){const lo=terminalEntries(Au);return jsxRuntimeExports.jsxs(Box,{"data-testid":"computer-terminal",children:[jsxRuntimeExports.jsx(Heading$2,{as:"h4",sx:{fontSize:1,mt:3,mb:1},children:COMPUTER_WORDS.terminal}),lo.length===0?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:1,color:"fg.muted",m:0},children:COMPUTER_WORDS.nothingRan}):jsxRuntimeExports.jsx(Box,{bg:"canvas.inset",border:"1px solid",borderColor:"border.muted",borderRadius:2,p:2,maxHeight:320,overflow:"auto",children:lo.map(($u,Ru)=>jsxRuntimeExports.jsxs(Box,{mb:2,children:[jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{...MONO,fontWeight:"semibold"},children:`$ ${$u.tool}${$u.command?`: ${$u.command}`:""}`}),$u.output===void 0?jsxRuntimeExports.jsx(StyledSpinner,{size:"small"}):jsxRuntimeExports.jsx(Text$3,{as:"pre",sx:{...MONO,color:"fg.muted"},children:$u.output})]},Ru))})]})}function save(Au,lo){const $u=URL.createObjectURL(new Blob([Au],{type:"application/octet-stream"})),Ru=document.createElement("a");Ru.href=$u,Ru.download=lo,Ru.click(),URL.revokeObjectURL($u)}function Files({context:Au,state:lo,ended:$u}){const[Ru,Iu]=reactExports.useState("."),[Pu,Ou]=reactExports.useState(),[Mu,Du]=reactExports.useState("");return reactExports.useEffect(()=>{if(!lo.started)return;let Lu=!1;return listComputerFiles(Au,Ru).then(Bu=>{Lu||(Ou(Bu),Du(""))},Bu=>!Lu&&Du(Bu instanceof Error?Bu.message:String(Bu))),()=>{Lu=!0}},[Au.serverUrl,Au.agentId,Au.token,Ru,lo.started,$u]),jsxRuntimeExports.jsxs(Box,{"data-testid":"computer-files",children:[jsxRuntimeExports.jsxs(Heading$2,{as:"h4",sx:{fontSize:1,mt:3,mb:1},children:[COMPUTER_WORDS.files,Ru!=="."?jsxRuntimeExports.jsx(Text$3,{sx:{fontWeight:"normal",color:"fg.muted"},children:` · ${Ru}`}):null]}),lo.started?Mu?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:1,color:"danger.fg",m:0},children:Mu}):Pu?jsxRuntimeExports.jsxs(Box,{as:"ul",listStyle:"none",p:0,m:0,children:[Ru!=="."?jsxRuntimeExports.jsx(Box,{as:"li",children:jsxRuntimeExports.jsx(ButtonComponent,{size:"small",variant:"invisible",onClick:()=>Iu(parentOf(Ru)),children:COMPUTER_WORDS.up})}):null,Pu.length===0?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:1,color:"fg.muted",m:0},children:COMPUTER_WORDS.emptyDirectory}):null,Pu.map(Lu=>jsxRuntimeExports.jsx(Box,{as:"li","data-path":Lu.path,display:"flex",alignItems:"center",gap:2,fontSize:1,py:1,borderTop:"1px solid",borderColor:"border.muted",children:Lu.type==="directory"?jsxRuntimeExports.jsx(ButtonComponent,{size:"small",variant:"invisible",onClick:()=>Iu(Lu.path),children:`${Lu.name}/`}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(Text$3,{sx:{flex:1,fontFamily:MONO_FACE,fontSize:0},children:Lu.name}),jsxRuntimeExports.jsx(Text$3,{sx:{color:"fg.muted",fontSize:0},children:`${Lu.size.toLocaleString("en")} bytes`}),jsxRuntimeExports.jsx(ButtonComponent,{size:"small","aria-label":`${COMPUTER_WORDS.download} ${Lu.name}`,onClick:()=>{downloadComputerFile(Au,Lu.path).then(Bu=>save(Bu,Lu.name),Bu=>Du(Bu instanceof Error?Bu.message:String(Bu)))},children:COMPUTER_WORDS.download})]})},Lu.path))]}):jsxRuntimeExports.jsx(StyledSpinner,{size:"small"}):jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:1,color:"fg.muted",m:0},children:COMPUTER_WORDS.notStarted})]})}const BROWSER_POLL_MS=1500;function BrowserView({context:Au,state:lo,mine:$u}){const[Ru,Iu]=reactExports.useState(),[Pu,Ou]=reactExports.useState(!1),[Mu,Du]=reactExports.useState(lo.page),[Lu,Bu]=reactExports.useState(""),[ju,Fu]=reactExports.useState(""),[zu,Uu]=reactExports.useState(""),[Hu,Vu]=reactExports.useState(0),Gu=reactExports.useRef(void 0);reactExports.useEffect(()=>Du(lo.page),[lo.page]),reactExports.useEffect(()=>{if(!lo.browser)return;let Yu=!1;const Xu=()=>readBrowserScreenshot(Au).then(td=>{Yu||(Bu(""),Ou(!td),Gu.current&&URL.revokeObjectURL(Gu.current),Gu.current=td?URL.createObjectURL(td):void 0,Iu(Gu.current))},td=>!Yu&&Bu(td instanceof Error?td.message:String(td)));Xu();const ed=setInterval(Xu,BROWSER_POLL_MS);return()=>{Yu=!0,clearInterval(ed)}},[Au.serverUrl,Au.agentId,Au.token,lo.browser,Hu]),reactExports.useEffect(()=>()=>{Gu.current&&URL.revokeObjectURL(Gu.current)},[]);const Wu=Yu=>Yu.then(Xu=>{Du(Xu),Bu(""),Vu(ed=>ed+1)},Xu=>Bu(Xu instanceof Error?Xu.message:String(Xu))),Ku=Yu=>{const Xu=Yu.currentTarget,ed=Xu.getBoundingClientRect(),td=pointOnPage({x:Yu.clientX-ed.left,y:Yu.clientY-ed.top},{width:ed.width,height:ed.height},{width:Xu.naturalWidth,height:Xu.naturalHeight});Xu.focus(),Wu(clickOnBrowser(Au,td.x,td.y))},Ju=Yu=>{Yu.metaKey||Yu.ctrlKey||Yu.altKey||(BROWSER_KEYS.includes(Yu.key)?(Yu.preventDefault(),Wu(pressOnBrowser(Au,Yu.key))):Yu.key.length===1&&(Yu.preventDefault(),Wu(typeOnBrowser(Au,Yu.key))))};return jsxRuntimeExports.jsxs(Box,{"data-testid":"computer-browser",children:[jsxRuntimeExports.jsxs(Heading$2,{as:"h4",sx:{fontSize:1,mt:3,mb:1},children:[COMPUTER_WORDS.browser,Mu?jsxRuntimeExports.jsx(Text$3,{sx:{fontWeight:"normal",color:"fg.muted"},children:` · ${Mu.title||Mu.url}`}):null]}),lo.browser?Pu||!Ru?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:1,color:"fg.muted",m:0},children:Pu?COMPUTER_WORDS.noPage:null}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[Mu?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontFamily:MONO_FACE,fontSize:0,color:"fg.muted",m:0,mb:1,wordBreak:"break-all"},children:Mu.url}):null,jsxRuntimeExports.jsx("img",{src:Ru,alt:COMPUTER_WORDS.pageAlt(Mu?.title||Mu?.url||""),"data-testid":"computer-browser-page",tabIndex:$u?0:-1,onClick:$u?Ku:void 0,onKeyDown:$u?Ju:void 0,style:{width:"100%",height:"auto",display:"block",border:"1px solid var(--borderColor-muted, #d0d7de)",borderRadius:6,cursor:$u?"pointer":"default"}})]}):jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:1,color:"fg.muted",m:0},children:COMPUTER_WORDS.noBrowser}),Lu?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:1,color:"danger.fg",m:0,mt:1},children:Lu}):null,$u&&lo.browser?jsxRuntimeExports.jsxs(Box,{mt:2,"data-testid":"computer-browser-controls",children:[jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:0,color:"fg.muted",m:0,mb:1},children:COMPUTER_WORDS.clickToAct}),jsxRuntimeExports.jsxs(Box,{display:"flex",gap:1,mb:1,children:[jsxRuntimeExports.jsx(TextInput$1,{size:"small","aria-label":COMPUTER_WORDS.typeOnPage,placeholder:COMPUTER_WORDS.typeOnPage,value:ju,onChange:Yu=>Fu(Yu.target.value),sx:{flex:1}}),jsxRuntimeExports.jsx(ButtonComponent,{size:"small",disabled:!ju,onClick:()=>{Wu(typeOnBrowser(Au,ju)),Fu("")},children:COMPUTER_WORDS.type}),jsxRuntimeExports.jsx(ButtonComponent,{size:"small",onClick:()=>{Wu(pressOnBrowser(Au,"Enter"))},children:"Enter"})]}),jsxRuntimeExports.jsxs(Box,{display:"flex",gap:1,mb:1,children:[jsxRuntimeExports.jsx(TextInput$1,{size:"small","aria-label":COMPUTER_WORDS.address,placeholder:COMPUTER_WORDS.address,value:zu,onChange:Yu=>Uu(Yu.target.value),sx:{flex:1}}),jsxRuntimeExports.jsx(ButtonComponent,{size:"small",disabled:!zu.trim(),onClick:()=>{Wu(openOnBrowser(Au,zu.trim()))},children:COMPUTER_WORDS.open})]}),jsxRuntimeExports.jsxs(Box,{display:"flex",gap:1,children:[jsxRuntimeExports.jsx(ButtonComponent,{size:"small",onClick:()=>{Wu(scrollBrowser(Au,-400))},children:COMPUTER_WORDS.scrollUp}),jsxRuntimeExports.jsx(ButtonComponent,{size:"small",onClick:()=>{Wu(scrollBrowser(Au,400))},children:COMPUTER_WORDS.scrollDown})]})]}):null]})}function YourTerminal({context:Au}){const[lo,$u]=reactExports.useState(""),[Ru,Iu]=reactExports.useState(!1),[Pu,Ou]=reactExports.useState([]),Mu=()=>{Iu(!0),runOnComputer(Au,lo).then(Du=>{Ou(Lu=>[...Lu,{code:lo,output:Du}]),$u(""),Iu(!1)},Du=>{Ou(Lu=>[...Lu,{code:lo,output:{stdout:"",stderr:"",error:Du instanceof Error?Du.message:String(Du)}}]),Iu(!1)})};return jsxRuntimeExports.jsxs(Box,{"data-testid":"computer-your-terminal",mt:2,children:[Pu.map((Du,Lu)=>jsxRuntimeExports.jsxs(Box,{mb:2,children:[jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{...MONO,fontWeight:"semibold"},children:`>>> ${Du.code}`}),jsxRuntimeExports.jsx(Text$3,{as:"pre",sx:{...MONO,color:"fg.muted"},children:[Du.output.stdout,Du.output.stderr,Du.output.error].filter(Boolean).join(`
|
|
4006
4006
|
`)})]},Lu)),jsxRuntimeExports.jsx(Textarea,{"aria-label":COMPUTER_WORDS.yourCode,placeholder:COMPUTER_WORDS.yourCode,value:lo,onChange:Du=>$u(Du.target.value),sx:{width:"100%",fontFamily:MONO_FACE},rows:3}),jsxRuntimeExports.jsx(ButtonComponent,{size:"small",sx:{mt:1},disabled:Ru||!lo.trim(),onClick:Mu,children:COMPUTER_WORDS.run})]})}function AppComputer({app:Au,workspace:lo}){const $u=useIAMStore(sd=>sd.token)??"",Ru=useContributions(LoopChatTurn),Iu=useSignalValue$1(Ru[0]?.value.turn??NO_TURN$2),Pu=useSignalValue$1(Ru[0]?.value.conversation??NO_CONVERSATION$1),Ou=Iu.status!=="thinking"&&Iu.status!=="streaming",[Mu,Du]=reactExports.useState(0);reactExports.useEffect(()=>{Ou&&Du(Iu.id)},[Ou,Iu.id]);const Lu=useChatWords(),Bu=lo?agentServerOf(lo.sandbox,lo.serverUrl):void 0,ju=Bu===void 0?noRuntimeSaid(lo?.sandbox??IDLE_SANDBOX_SNAPSHOT,Lu):void 0,Fu=lo?.agentId||Au.id,[zu,Uu]=reactExports.useState(),Hu=zu?.servedFrom??"",Vu=reactExports.useMemo(()=>Bu===void 0?void 0:{serverUrl:Bu,agentId:Fu,token:$u||void 0,userAppsUrl:Hu||void 0},[Bu,Fu,$u,Hu]),Gu=computerParts(Au),[Wu,Ku]=reactExports.useState(""),[Ju,Yu]=reactExports.useState(!1),Xu=reactExports.useRef(!0);reactExports.useEffect(()=>(Xu.current=!0,()=>{Xu.current=!1}),[]);const ed=reactExports.useCallback(()=>{Vu&&readComputer(Vu).then(sd=>{Xu.current&&(Uu(sd),Ku(""))},sd=>Xu.current&&Ku(sd instanceof Error?sd.message:String(sd)))},[Vu]),td=hasComputer(Gu);reactExports.useEffect(()=>{td&&Vu&&ed()},[td,Vu,ed,Mu]);const nd=sd=>{Vu&&(Yu(!0),sd(Vu).then(()=>{Xu.current&&(Yu(!1),ed())},ad=>{Xu.current&&(Yu(!1),Ku(ad instanceof Error?ad.message:String(ad)))}))},od=!!zu?.yours;return jsxRuntimeExports.jsxs(Box,{"data-testid":"app-computer",children:[jsxRuntimeExports.jsx(Heading$2,{as:"h3",sx:{fontSize:2,mb:2},children:COMPUTER_WORDS.title}),jsxRuntimeExports.jsx(Parts,{app:Au}),td?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[ju?jsxRuntimeExports.jsx(Text$3,{as:"p",role:"status",sx:{fontSize:1,color:"fg.default",m:0,mt:2},children:ju}):null,Wu?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:1,color:"danger.fg",m:0,mt:2},children:Wu}):null,zu&&Vu?jsxRuntimeExports.jsxs(Box,{mt:2,"data-testid":"computer-holder",children:[jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:1,m:0,mb:1},children:zu.held?od?COMPUTER_WORDS.youHave:COMPUTER_WORDS.someoneHas:COMPUTER_WORDS.agentHas}),zu.held?od?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(ButtonComponent,{size:"small",variant:"primary",disabled:Ju,onClick:()=>nd(handBackComputer),children:COMPUTER_WORDS.handBack}),jsxRuntimeExports.jsx(YourTerminal,{context:Vu})]}):null:jsxRuntimeExports.jsx(ButtonComponent,{size:"small",disabled:Ju,onClick:()=>nd(takeOverComputer),children:COMPUTER_WORDS.takeOver})]}):null,Gu.browse&&zu&&Vu?jsxRuntimeExports.jsx(BrowserView,{context:Vu,state:zu,mine:od}):null,jsxRuntimeExports.jsx(Terminal,{conversation:Pu}),zu&&Vu?jsxRuntimeExports.jsx(Files,{context:Vu,state:zu,ended:Mu}):null]}):jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:1,color:"fg.muted",m:0,mt:1},children:COMPUTER_WORDS.none})]})}const APP_COMPUTER_PLUGIN_NAME="@datalayer/loop-plugin-app-computer";function defineAppComputerPlugin(Au){function lo({workspace:Ru}){return jsxRuntimeExports.jsx(AppComputer,{app:Au,workspace:Ru})}return{name:`${APP_COMPUTER_PLUGIN_NAME}-${Au.id}`,displayName:`${Au.name}: computer`,description:`The computer ${Au.name} runs on: what ran on it, its files, and taking it over.`,octicon:"device-desktop",build:()=>({components:[{id:"app-computer",slot:LoopSlots.sidebar,order:30,Component:lo,rail:{label:"Computer",icon:DeviceDesktopIcon}}]})}}const SAVE_TOOL="save_to_space",SAVE_WORDS={approve:"Approve and save",decline:"Decline",where:Au=>Au?`To keep as a page of ${Au}:`:"To keep as a page of its Space:"};function draftOfApproval(Au){if(Au.tool_name!==SAVE_TOOL)return null;const lo=$u=>{const Ru=Au.tool_args?.[$u];return typeof Ru=="string"?Ru:""};return{title:lo("title"),content:lo("content"),space:lo("space")}}const APP_RULES_WORDS={title:"Rules and approvals",byDefault:"With no rule of its own: reading is done, anything else waits for you.",none:"It has no rule of its own.",waiting:"Waiting for you",nothingWaiting:"Nothing is waiting for your yes.",signedOut:"Its approvals reach you here once you are signed in to Datalayer.",offline:"Approvals are not connected yet: what you approve or reject is not sent until they are.",approve:"Approve",reject:"Reject"};function ruleInWords(Au){const lo=BEHAVIOUR_WORDS[Au.behaviour];return{action:Au.action,covers:Au.appliesTo.map(coverOf).join(", "),says:lo.says,means:lo.means}}const ruleOfApproval=Au=>{const lo=Au.tool_args?._rule??Au.tool_args?._check;return typeof lo=="string"?lo:""};function approvalsOfApp(Au,lo){return Au.filter($u=>$u.agent_id===lo||$u.tool_args?._app===lo)}const PENDING={status:"pending"};function DraftShown({draft:Au}){return jsxRuntimeExports.jsxs(Box,{"data-testid":"app-draft",mt:1,children:[jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{m:0,fontSize:0,color:"fg.muted"},children:SAVE_WORDS.where(Au.space)}),jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{m:0,fontWeight:"semibold"},children:Au.title}),jsxRuntimeExports.jsx(Box,{as:"pre",m:0,mt:1,p:2,maxHeight:240,overflow:"auto",whiteSpace:"pre-wrap",fontFamily:"inherit",fontSize:0,bg:"canvas.subtle",borderRadius:2,children:Au.content})]})}function Approvals({app:Au}){const lo=useToolApprovalsQuery(PENDING),$u=useApproveToolRequest(),Ru=useRejectToolRequest(),Iu=reactExports.useMemo(()=>approvalsOfApp(lo.data?.approvals??[],Au.id),[lo.data,Au.id]);return jsxRuntimeExports.jsxs(Box,{"data-testid":"app-approvals",children:[jsxRuntimeExports.jsx(Heading$2,{as:"h4",sx:{fontSize:1,mt:3,mb:1},children:APP_RULES_WORDS.waiting}),$u.connectionState!=="connected"?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:0,color:"fg.muted",m:0,mb:1},children:APP_RULES_WORDS.offline}):null,Iu.length===0?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:1,color:"fg.muted",m:0},children:APP_RULES_WORDS.nothingWaiting}):jsxRuntimeExports.jsx(Box,{as:"ul",listStyle:"none",p:0,m:0,children:Iu.map(Pu=>{const Ou=draftOfApproval(Pu);return jsxRuntimeExports.jsxs(Box,{as:"li",py:2,borderTop:"1px solid",borderColor:"border.muted",fontSize:1,children:[jsxRuntimeExports.jsx(Text$3,{sx:{fontWeight:"semibold"},children:Pu.tool_name}),ruleOfApproval(Pu)?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{m:0,color:"fg.muted",fontSize:0},children:ruleOfApproval(Pu)}):null,Ou?jsxRuntimeExports.jsx(DraftShown,{draft:Ou}):null,jsxRuntimeExports.jsxs(Box,{display:"flex",gap:2,mt:1,children:[jsxRuntimeExports.jsx(ButtonComponent,{size:"small",variant:"primary",disabled:$u.isPending,onClick:()=>$u.mutate({id:Pu.id}),children:Ou?SAVE_WORDS.approve:APP_RULES_WORDS.approve}),jsxRuntimeExports.jsx(ButtonComponent,{size:"small",disabled:Ru.isPending,onClick:()=>Ru.mutate({id:Pu.id}),children:Ou?SAVE_WORDS.decline:APP_RULES_WORDS.reject})]})]},Pu.id)})})]})}function AppRulesCard({app:Au}){const lo=!!useIAMStore($u=>$u.token);return jsxRuntimeExports.jsxs(Box,{"data-testid":"app-rules",mb:4,children:[jsxRuntimeExports.jsx(Heading$2,{as:"h3",sx:{fontSize:2,mb:2},children:APP_RULES_WORDS.title}),Au.rules.length===0?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:1,color:"fg.muted",m:0},children:APP_RULES_WORDS.none}):jsxRuntimeExports.jsx(Box,{as:"ul",listStyle:"none",p:0,m:0,children:Au.rules.map(ruleInWords).map(($u,Ru)=>jsxRuntimeExports.jsxs(Box,{as:"li",py:1,fontSize:1,children:[jsxRuntimeExports.jsx(Text$3,{children:$u.action})," ",jsxRuntimeExports.jsx(Label,{title:$u.means,children:$u.says}),jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{m:0,color:"fg.muted",fontSize:0},children:$u.covers})]},Ru))}),jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:0,color:"fg.muted",mt:1,mb:0},children:APP_RULES_WORDS.byDefault}),lo?jsxRuntimeExports.jsx(Approvals,{app:Au}):jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:1,color:"fg.muted",mt:3,mb:0},children:APP_RULES_WORDS.signedOut})]})}const APP_RULES_PLUGIN_NAME="@datalayer/loop-plugin-app-rules";function defineAppRulesPlugin(Au){function lo(){return jsxRuntimeExports.jsx(AppRulesCard,{app:Au})}return{name:`${APP_RULES_PLUGIN_NAME}-${Au.id}`,displayName:`${Au.name}: rules and approvals`,description:`When ${Au.name} acts alone, when it asks, and what waits for your yes.`,octicon:"shield-check",build:()=>({components:[{id:"app-rules",slot:LoopSlots.sidebar,order:10,Component:lo,rail:{label:"Rules",icon:ShieldCheckIcon}}]})}}const COMMAND_INPUT="{input}";function commandPrompt(Au,lo=""){const $u=lo.trim();return Au.prompt.includes(COMMAND_INPUT)?Au.prompt.split(COMMAND_INPUT).join($u).trim():$u?`${Au.prompt}
|