@datalayer/agent-runtimes 1.5.45 → 1.5.46

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.
Files changed (52) hide show
  1. package/dist-embed/datalayer-app-main.js +3 -3
  2. package/lib/portable/hosts/__tests__/fixtures/lock-with-jupyter.json +40 -0
  3. package/lib/portable/hosts/__tests__/fixtures/npm-ls-with-jupyter.json +21 -0
  4. package/lib/portable/hosts/agentClient.d.ts +167 -0
  5. package/lib/portable/hosts/agentClient.js +346 -0
  6. package/lib/portable/hosts/approvalRenderers.d.ts +43 -0
  7. package/lib/portable/hosts/approvalRenderers.js +180 -0
  8. package/lib/portable/hosts/client.d.ts +95 -0
  9. package/lib/portable/hosts/client.js +174 -0
  10. package/lib/portable/hosts/contracts.d.ts +199 -0
  11. package/lib/portable/hosts/contracts.js +235 -0
  12. package/lib/portable/hosts/contracts.json +381 -0
  13. package/lib/portable/hosts/deadLetters.d.ts +41 -0
  14. package/lib/portable/hosts/deadLetters.js +124 -0
  15. package/lib/portable/hosts/deliveries.d.ts +76 -0
  16. package/lib/portable/hosts/deliveries.js +147 -0
  17. package/lib/portable/hosts/forbiddenGraph.d.ts +77 -0
  18. package/lib/portable/hosts/forbiddenGraph.js +174 -0
  19. package/lib/portable/hosts/health.d.ts +35 -0
  20. package/lib/portable/hosts/health.js +92 -0
  21. package/lib/portable/hosts/index.d.ts +40 -0
  22. package/lib/portable/hosts/index.js +45 -0
  23. package/lib/portable/hosts/observability.d.ts +67 -0
  24. package/lib/portable/hosts/observability.js +171 -0
  25. package/lib/portable/hosts/postgresQueue.d.ts +55 -0
  26. package/lib/portable/hosts/postgresQueue.js +217 -0
  27. package/lib/portable/hosts/queue.d.ts +47 -0
  28. package/lib/portable/hosts/queue.js +63 -0
  29. package/lib/portable/hosts/quotas.d.ts +81 -0
  30. package/lib/portable/hosts/quotas.js +147 -0
  31. package/lib/portable/hosts/rateLimit.d.ts +13 -0
  32. package/lib/portable/hosts/rateLimit.js +8 -0
  33. package/lib/portable/hosts/resolution.d.ts +54 -0
  34. package/lib/portable/hosts/resolution.js +46 -0
  35. package/lib/portable/hosts/schema.d.ts +19 -0
  36. package/lib/portable/hosts/schema.js +81 -0
  37. package/lib/portable/hosts/secretCipher.d.ts +23 -0
  38. package/lib/portable/hosts/secretCipher.js +45 -0
  39. package/lib/portable/hosts/sessionUid.d.ts +7 -0
  40. package/lib/portable/hosts/sessionUid.js +28 -0
  41. package/lib/portable/hosts/turnState.d.ts +45 -0
  42. package/lib/portable/hosts/turnState.js +113 -0
  43. package/lib/portable/index.d.ts +2 -0
  44. package/lib/portable/index.js +3 -0
  45. package/lib/portable/semantic-events.json +480 -0
  46. package/lib/portable/semantic.d.ts +78 -0
  47. package/lib/portable/semantic.js +100 -0
  48. package/lib/portable/semanticOfAgUi.d.ts +41 -0
  49. package/lib/portable/semanticOfAgUi.js +108 -0
  50. package/lib/protocols/A2AAdapter.js +19 -0
  51. package/lib/test-setup.js +17 -14
  52. package/package.json +1 -1
@@ -2109,8 +2109,8 @@ Please change the parent <Route path="${Vu}"> to <Route path="${Vu==="/"?"*":`${
2109
2109
  `);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"})),RUN_END_WORDS={answered:"Answered",stopped:"Stopped",gone:"Its client went before the answer"},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 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;function sanitizeAssistantContent(Au){if(!Au||!Au.includes("<"))return Au;let lo=Au;return lo=lo.replace(/<\s*calls\b[\s\S]*?<\s*\/\s*calls\s*>/gi,"").replace(/<\s*(?:an:)?tml:invoke\b[\s\S]*?<\s*\/\s*(?:an:)?tml:invoke\s*>/gi,"").replace(/<\s*(?:an:)?tml:parameter\b[\s\S]*?<\s*\/\s*(?:an:)?tml:parameter\s*>/gi,""),lo=lo.replace(/<\s*\/?\s*(?:an:[a-z_]+|tml:[a-z_]+|calls)\b[^>]*>?/gi,"").replace(/<\s*\/\s*>/g,"").replace(/^[ \t]+$/gm,"").replace(/\n{3,}/g,`
2110
2110
 
2111
2111
  `).trim(),lo}const isRecord$4=Au=>!!Au&&typeof Au=="object"&&!Array.isArray(Au);function stateAnswers(Au){for(let lo=Au.items.length-1;lo>=0;lo-=1){const $u=Au.items[lo];if($u.kind==="tool"&&$u.status==="running"&&$u.awaiting!=="approval")return $u.input&&Array.isArray($u.input.steps)?null:$u.id}return null}function conversationEventsOf(Au,lo){switch(Au.type){case"connected":case"disconnected":return[];case"message":{const $u=Au.message;if($u===void 0)return[];if(typeof $u.id!="string"||!$u.id)throw new Error("A message came without its id.");if($u.role!=="user"&&$u.role!=="assistant")throw new Error(`Message ${$u.id} is said by ${String($u.role)}: only the person or the assistant speaks here.`);if(typeof $u.content!="string")throw new Error(`Message ${$u.id} says no words.`);return[{type:"MESSAGE_SAID",messageId:$u.id,role:$u.role,text:$u.role==="assistant"?sanitizeAssistantContent($u.content):$u.content}]}case"tool-call":{const $u=Au.toolCall;if(!$u||typeof $u.toolCallId!="string"||!$u.toolCallId||typeof $u.toolName!="string"||!$u.toolName)throw new Error("A tool call came without its id and its name.");if(!isRecord$4($u.args))throw new Error(`Tool call ${$u.toolCallId}'s arguments are not an object.`);return[{type:"TOOL_CALL_SAID",toolCallId:$u.toolCallId,toolCallName:$u.toolName,args:$u.args}]}case"tool-result":{const $u=Au.toolResult;if(!$u||typeof $u.toolCallId!="string"||!$u.toolCallId)throw new Error("A tool result came without the id of its call.");if(typeof $u.success!="boolean")throw new Error(`Tool result of ${$u.toolCallId} does not say whether it succeeded.`);if($u.error!==void 0&&typeof $u.error!="string")throw new Error(`Tool result of ${$u.toolCallId} says its error in no words.`);return[{type:"TOOL_CALL_DONE",toolCallId:$u.toolCallId,success:$u.success,result:$u.result,...$u.error!==void 0?{error:$u.error}:{}}]}case"state-update":{const $u=Au.data,Ru=$u?stateAnswers(lo):null;if(!Ru)return[];const Iu=isRecord$4($u)?$u:{};return[{type:"TOOL_CALL_DONE",toolCallId:Ru,success:!0,result:Iu.weather??Iu.result??Iu.toolResult??$u}]}case"activity":{if(!Au.activity||typeof Au.activity.type!="string")throw new Error("An activity came without its type.");return[{type:"CUSTOM",name:Au.activity.type,value:Au.activity.data}]}case"done":return[{type:"RUN_FINISHED"}];case"error":return[{type:"RUN_ERROR",message:Au.error?.message||"Run failed"}];default:throw new Error(`An adapter said ${Au.type}, which no client reads.`)}}function callOf(Au,lo){if(typeof Au.toolCallId!="string"||!Au.toolCallId)throw new Error(`Message ${lo} holds a tool call without its id.`);return{id:Au.toolCallId,type:"function",function:{name:Au.toolName,arguments:JSON.stringify(Au.args??{})}}}function snapshotOfMessages(Au){const lo=[];for(const $u of Au){if($u.role==="tool"){const Pu=$u.metadata?.toolCallId;if(typeof Pu!="string"||!Pu)throw new Error(`Tool result ${$u.id} does not say which call it answers.`);lo.push({id:$u.id,role:"tool",toolCallId:Pu,content:$u.content});continue}if($u.role!=="user"&&$u.role!=="assistant")throw new Error(`Message ${$u.id} is said by ${$u.role}: only the person, the assistant and its tools speak here.`);const Ru=typeof $u.content=="string"?$u.role==="assistant"?sanitizeAssistantContent($u.content):$u.content:"",Iu=$u.role==="assistant"?$u.toolCalls??[]:[];lo.push({id:$u.id,role:$u.role,content:Ru,...Iu.length?{toolCalls:Iu.map(Pu=>callOf(Pu,$u.id))}:{}});for(const Pu of Iu){if(Pu.status!==void 0&&Pu.status!=="completed"&&Pu.status!=="failed")throw new Error(`Tool call ${Pu.toolCallId} is read again ${Pu.status}: a conversation's past holds no call under way.`);(Pu.result!==void 0||Pu.status==="failed")&&lo.push({id:`${Pu.toolCallId}-result`,role:"tool",toolCallId:Pu.toolCallId,content:Pu.status==="failed"?{success:!1,error:"failed",result:Pu.result??null}:Pu.result})}}return{type:"MESSAGES_SNAPSHOT",messages:lo}}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.",REACTOR_UI_NAME="reactor.ui",UI_ON_RUN="A reactor.ui op came on the run stream: it comes over the ui socket (REACTOR_UI RU-W).",endsRun=Au=>Au.type==="RUN_FINISHED"||Au.type==="RUN_ERROR";class AgUiFrames{constructor(lo=()=>{}){this.malformed=lo}malformed;buffer="";data=[];push(lo){this.buffer+=lo;const $u=this.buffer.split(/\r?\n/);this.buffer=$u.pop()??"";const Ru=[];for(const Iu of $u)this.line(Iu,Ru);return Ru}end(){const lo=[];return this.buffer&&(this.line(this.buffer,lo),this.buffer=""),this.dispatch(lo),lo}line(lo,$u){if(lo===""){this.dispatch($u);return}if(lo.startsWith("data:")){const Ru=lo.slice(5);this.data.push(Ru.startsWith(" ")?Ru.slice(1):Ru)}}dispatch(lo){if(!this.data.length)return;const $u=this.data.join(`
2112
- `);this.data=[];let Ru;try{Ru=JSON.parse($u)}catch{this.malformed($u);return}Ru&&typeof Ru=="object"&&typeof Ru.type=="string"?lo.push(Ru):this.malformed($u)}}function eventsOfStream(Au){const lo=new AgUiFrames;return[...lo.push(Au),...lo.end()]}function toolResultOf(Au){let lo=Au;if(typeof lo=="string")try{lo=JSON.parse(lo)}catch{}const $u=lo&&typeof lo=="object"?lo:void 0;if(!($u?.execution_ok===!1||$u?.code_error!=null||$u?.error!=null&&!$u?.success))return{result:lo,success:!0};const Iu=$u?.code_error,Pu=typeof $u?.execution_error=="string"&&$u.execution_error||typeof $u?.error=="string"&&$u.error||(Iu?`${Iu.name||"Error"}: ${Iu.value||""}`:void 0);return{result:lo,success:!1,error:Pu}}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.aguiConfig.appSessions&&this.terminateAgent(this.currentThreadId).catch(lo=>{console.warn("[AGUIAdapter] Failed to terminate agent:",lo)}),this.setConnectionState("disconnected")}async terminateAgent(lo){const $u=this.aguiConfig.appSessions;if($u){await this.stopSession($u,lo||this.currentThreadId);return}try{const Iu=`${new URL(this.aguiConfig.baseUrl).origin}/api/v1/ag-ui/terminate`,Pu=await this.fetchOf()(Iu,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({thread_id:lo||this.currentThreadId})});Pu.ok||console.warn(`[AGUIAdapter] Terminate request failed: ${Pu.status}`)}catch{}}async stopSession(lo,$u){if(!$u)return;const Ru=`${lo.replace(/\/+$/,"")}/${encodeURIComponent($u)}/stop`,Iu=await this.fetchOf()(Ru,{method:"POST",headers:this.buildHeaders()});if(!Iu.ok)throw new Error(`The session ${$u} could not be stopped (${Iu.status}).`)}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,Iu=new AgUiFrames(Bu=>console.warn("[AGUIAdapter] Failed to parse event data:",Bu));let Pu=null,Ou="",Mu="";this.isContinuation=!1,this._streamParsingDepth===0&&(this._streamDonePromise=new Promise(Bu=>{this._streamDoneResolve=Bu})),this._streamParsingDepth++;let Du=!1;const Lu=Bu=>{for(const ju of Bu)endsRun(ju)&&(Du=!0),this.handleAGUIEvent(ju,{getCurrentMessageId:()=>Pu,setCurrentMessageId:Fu=>{Pu=Fu},getCurrentContent:()=>Ou,appendContent:Fu=>{Ou+=Fu},resetContent:()=>{Ou=""},appendTurnContent:Fu=>{Mu+=Fu},getCurrentTurnContent:()=>Mu})};try{for(;;){const{done:Bu,value:ju}=await $u.read();if(Bu){if(Lu(Iu.end()),!Du)throw new Error(RUN_CUT_SHORT);break}Lu(Iu.push(Ru.decode(ju,{stream:!0})))}}finally{if($u.releaseLock(),this._streamParsingDepth--,this._streamParsingDepth===0){const Bu=this._streamDoneResolve;this._streamDonePromise=null,this._streamDoneResolve=null,Bu?.()}}}refuseUiOnRun(){this.emit({type:"error",error:new Error(UI_ON_RUN),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;if(Iu){const Pu=toolResultOf(lo.content);this.emit({type:"tool-result",toolResult:{toolCallId:Iu,success:Pu.success,result:Pu.result,error:Pu.error},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===REACTOR_UI_NAME&&this.refuseUiOnRun();break}case"CUSTOM":{const Iu=lo.name;if(Iu===REACTOR_UI_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$3(Au){return typeof Au=="object"&&Au!==null}function ours(Au){if(!isRecord$3(Au))return;const lo=Au[ENVELOPE_KEY];return isRecord$3(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$3($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(`
2113
- `);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(`
2112
+ `);this.data=[];let Ru;try{Ru=JSON.parse($u)}catch{this.malformed($u);return}Ru&&typeof Ru=="object"&&typeof Ru.type=="string"?lo.push(Ru):this.malformed($u)}}function eventsOfStream(Au){const lo=new AgUiFrames;return[...lo.push(Au),...lo.end()]}function toolResultOf(Au){let lo=Au;if(typeof lo=="string")try{lo=JSON.parse(lo)}catch{}const $u=lo&&typeof lo=="object"?lo:void 0;if(!($u?.execution_ok===!1||$u?.code_error!=null||$u?.error!=null&&!$u?.success))return{result:lo,success:!0};const Iu=$u?.code_error,Pu=typeof $u?.execution_error=="string"&&$u.execution_error||typeof $u?.error=="string"&&$u.error||(Iu?`${Iu.name||"Error"}: ${Iu.value||""}`:void 0);return{result:lo,success:!1,error:Pu}}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.aguiConfig.appSessions&&this.terminateAgent(this.currentThreadId).catch(lo=>{console.warn("[AGUIAdapter] Failed to terminate agent:",lo)}),this.setConnectionState("disconnected")}async terminateAgent(lo){const $u=this.aguiConfig.appSessions;if($u){await this.stopSession($u,lo||this.currentThreadId);return}try{const Iu=`${new URL(this.aguiConfig.baseUrl).origin}/api/v1/ag-ui/terminate`,Pu=await this.fetchOf()(Iu,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({thread_id:lo||this.currentThreadId})});Pu.ok||console.warn(`[AGUIAdapter] Terminate request failed: ${Pu.status}`)}catch{}}async stopSession(lo,$u){if(!$u)return;const Ru=`${lo.replace(/\/+$/,"")}/${encodeURIComponent($u)}/stop`,Iu=await this.fetchOf()(Ru,{method:"POST",headers:this.buildHeaders()});if(!Iu.ok)throw new Error(`The session ${$u} could not be stopped (${Iu.status}).`)}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,Iu=new AgUiFrames(Bu=>console.warn("[AGUIAdapter] Failed to parse event data:",Bu));let Pu=null,Ou="",Mu="";this.isContinuation=!1,this._streamParsingDepth===0&&(this._streamDonePromise=new Promise(Bu=>{this._streamDoneResolve=Bu})),this._streamParsingDepth++;let Du=!1;const Lu=Bu=>{for(const ju of Bu)endsRun(ju)&&(Du=!0),this.handleAGUIEvent(ju,{getCurrentMessageId:()=>Pu,setCurrentMessageId:Fu=>{Pu=Fu},getCurrentContent:()=>Ou,appendContent:Fu=>{Ou+=Fu},resetContent:()=>{Ou=""},appendTurnContent:Fu=>{Mu+=Fu},getCurrentTurnContent:()=>Mu})};try{for(;;){const{done:Bu,value:ju}=await $u.read();if(Bu){if(Lu(Iu.end()),!Du)throw new Error(RUN_CUT_SHORT);break}Lu(Iu.push(Ru.decode(ju,{stream:!0})))}}finally{if($u.releaseLock(),this._streamParsingDepth--,this._streamParsingDepth===0){const Bu=this._streamDoneResolve;this._streamDonePromise=null,this._streamDoneResolve=null,Bu?.()}}}refuseUiOnRun(){this.emit({type:"error",error:new Error(UI_ON_RUN),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;if(Iu){const Pu=toolResultOf(lo.content);this.emit({type:"tool-result",toolResult:{toolCallId:Iu,success:Pu.success,result:Pu.result,error:Pu.error},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===REACTOR_UI_NAME&&this.refuseUiOnRun();break}case"CUSTOM":{const Iu=lo.name;if(Iu===REACTOR_UI_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$3(Au){return typeof Au=="object"&&Au!==null}function ours(Au){if(!isRecord$3(Au))return;const lo=Au[ENVELOPE_KEY];return isRecord$3(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$3($u)?tokenCountFromWire($u):void 0}const VOICE_SAY_EVENT="voice.say",VOICE_SETTINGS_EVENT="voice.settings",SAY_ALOUD_MAX_CHARACTERS=200,nameOf=Au=>Au.replace(/^data-/,"");function lineToSay(Au){if(nameOf(Au.type)!==VOICE_SAY_EVENT)return;const lo=Au.data,$u=lo&&typeof lo.text=="string"?lo.text.split(/\s+/).join(" ").trim():"";return $u?$u.slice(0,SAY_ALOUD_MAX_CHARACTERS):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(`
2113
+ `);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;console.log("[A2AAdapter] Status update:",Pu,"final:",lo.final);const Ou=lo.status?.message?.metadata?.voice;if(Ou?.settings&&this.emit({type:"activity",activity:{type:VOICE_SETTINGS_EVENT,data:Ou.settings},timestamp:new Date}),Ou?.say&&this.emit({type:"activity",activity:{type:VOICE_SAY_EVENT,data:Ou.say},timestamp:new Date}),lo.final&&(Pu==="completed"||Pu==="failed"||Pu==="canceled")){const Mu=this.orchestrationExtensionSupported?lo.status?.message?.metadata?.[ENVELOPE_KEY]:void 0,Du=Mu?readUsageMeta(lo.status.message.metadata):void 0;this.emit({type:"state-update",data:{state:Pu,final:!0,...Mu?.paused&&{datalayerPaused:Mu.paused},...Mu?.error&&{datalayerError:Mu.error},...Du&&{datalayerUsage:Du}},...Du&&{usage:{promptTokens:Du.inputTokens??0,completionTokens:Du.outputTokens??0,...Du.inputTokens!==void 0&&Du.outputTokens!==void 0&&{totalTokens:Du.inputTokens+Du.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(`
2114
2114
  `);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})}else typeof Gu.type=="string"&&Gu.type.startsWith("data-")&&this.emit({type:"activity",activity:{type:Gu.type,data:Gu.data},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 OS 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 OS.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}.
2115
2115
  Error message: ${getErrorMessage$2($u)}`,cause:$u}),this[_a7$4]=!0,this.text=lo}static isInstance(lo){return AISDKError$2.hasMarker(lo,marker7$4)}},name13$2="AI_TypeValidationError",marker14$2=`vercel.ai.error.${name13$2}`,symbol14$2=Symbol.for(marker14$2),_a14$2,_b14$2,TypeValidationError$2=class A_ extends(_b14$2=AISDKError$2,_a14$2=symbol14$2,_b14$2){constructor({value:lo,cause:$u,context:Ru}){let Iu="Type validation failed";if(Ru?.field&&(Iu+=` for ${Ru.field}`),Ru?.entityName||Ru?.entityId){Iu+=" (";const Pu=[];Ru.entityName&&Pu.push(Ru.entityName),Ru.entityId&&Pu.push(`id: "${Ru.entityId}"`),Iu+=Pu.join(", "),Iu+=")"}super({name:name13$2,message:`${Iu}: Value: ${JSON.stringify(lo)}.
2116
2116
  Error message: ${getErrorMessage$2($u)}`,cause:$u}),this[_a14$2]=!0,this.value=lo,this.context=Ru}static isInstance(lo){return AISDKError$2.hasMarker(lo,marker14$2)}static wrap({value:lo,cause:$u,context:Ru}){var Iu,Pu,Ou;return A_.isInstance($u)&&$u.value===lo&&((Iu=$u.context)==null?void 0:Iu.field)===Ru?.field&&((Pu=$u.context)==null?void 0:Pu.entityName)===Ru?.entityName&&((Ou=$u.context)==null?void 0:Ou.entityId)===Ru?.entityId?$u:new A_({value:lo,cause:$u,context:Ru})}};let ParseError$1=class extends Error{constructor(lo,$u){super(lo),this.name="ParseError",this.type=$u.type,this.field=$u.field,this.value=$u.value,this.line=$u.line}};const LF=10,CR=13,SPACE=32;function noop(Au){}function createParser(Au){if(typeof Au=="function")throw new TypeError("`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?");const{onEvent:lo=noop,onError:$u=noop,onRetry:Ru=noop,onComment:Iu,maxBufferSize:Pu}=Au,Ou=[];let Mu=0,Du=!0,Lu,Bu="",ju=0,Fu,zu=!1;function Uu(Yu){if(zu)throw new Error("Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.");if(Du&&(Du=!1,Yu.charCodeAt(0)===239&&Yu.charCodeAt(1)===187&&Yu.charCodeAt(2)===191&&(Yu=Yu.slice(3))),Ou.length===0){const td=Vu(Yu);td!==""&&(Ou.push(td),Mu=td.length),Hu();return}if(Yu.indexOf(`
@@ -3685,7 +3685,7 @@ ${Pu}\`\`\``}),lo}function ChatMarkdown({text:Au,density:lo="comfortable"}){retu
3685
3685
  text-decoration-thickness: 2px;
3686
3686
  text-underline-offset: 3px;
3687
3687
  background-color: var(--bgColor-accent-muted, rgba(84, 174, 255, 0.2));
3688
- }`;function squeezed(Au){return Au.replace(/\s+/g," ").trim()}function saidMessageId(Au,lo){const $u=squeezed(lo??"");if($u)for(let Ru=Au.length-1;Ru>=0;Ru-=1){const Iu=answerText(Au[Ru]);if(Iu!==void 0&&squeezed(plainWords(Iu)).includes($u)){const Pu=Au[Ru].id;return typeof Pu=="string"?Pu:void 0}}}function sentenceRange(Au,lo){const $u=squeezed(lo);if(!$u||!Au.ownerDocument)return;const Ru=Au.ownerDocument,Iu=Ru.createTreeWalker(Au,4);let Pu="";const Ou=[];let Mu=!0;for(let Fu=Iu.nextNode();Fu;Fu=Iu.nextNode()){const zu=Fu.nodeValue??"";for(let Uu=0;Uu<zu.length;Uu+=1){const Hu=zu[Uu];if(/\s/.test(Hu)){if(Mu)continue;Mu=!0,Pu+=" "}else Mu=!1,Pu+=Hu;Ou.push({node:Fu,offset:Uu})}}const Du=Pu.indexOf($u);if(Du<0)return;const Lu=Ou[Du],Bu=Ou[Du+$u.length-1],ju=Ru.createRange();return ju.setStart(Lu.node,Lu.offset),ju.setEnd(Bu.node,Bu.offset+1),ju}function registry(){return globalThis.CSS?.highlights}function highlightOf(Au){const lo=globalThis.Highlight;return lo?new lo(Au):void 0}let styled=!1;function ensureStyle(Au){if(styled||Au.getElementById("datalayer-voice-said")){styled=!0;return}const lo=Au.createElement("style");lo.id="datalayer-voice-said",lo.textContent=SAID_STYLE,Au.head.appendChild(lo),styled=!0}function useSaidSentence(Au,lo,$u){reactExports.useEffect(()=>{const Ru=registry(),Iu=Au.current?.querySelector("[data-voice-saying]");if(!Ru||!Iu||!lo)return;const Pu=()=>{const Mu=sentenceRange(Iu,lo),Du=Mu?highlightOf(Mu):void 0;return Du?(ensureStyle(Iu.ownerDocument),Ru.set(SAID_HIGHLIGHT,Du),!0):!1};let Ou;return!Pu()&&typeof MutationObserver<"u"&&(Ou=new MutationObserver(()=>{Pu()&&Ou?.disconnect()}),Ou.observe(Iu,{childList:!0,subtree:!0,characterData:!0})),()=>{Ou?.disconnect(),Ru.delete(SAID_HIGHLIGHT)}},[Au,lo,$u])}const VOICE_SAY_EVENT="voice.say",SAY_ALOUD_MAX_CHARACTERS=200,nameOf=Au=>Au.replace(/^data-/,"");function lineToSay(Au){if(nameOf(Au.type)!==VOICE_SAY_EVENT)return;const lo=Au.data,$u=lo&&typeof lo.text=="string"?lo.text.split(/\s+/).join(" ").trim():"";return $u?$u.slice(0,SAY_ALOUD_MAX_CHARACTERS):void 0}function ToolApprovalBanner({pendingApprovals:Au,onReview:lo,onApproveAll:$u,onDismiss:Ru,collapsible:Iu=!0}){const Pu=useChatWords(),[Ou,Mu]=reactExports.useState(!1);return Au.length===0?null:Ou?jsxRuntimeExports.jsxs(Box,{display:"flex",alignItems:"center",gap:2,px:3,py:2,bg:"attention.subtle",borderBottom:"1px solid",borderColor:"attention.muted",cursor:"pointer",onClick:()=>Mu(!1),children:[jsxRuntimeExports.jsx(ShieldCheckIcon,{size:16}),jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:1,fontWeight:"semibold"},children:Pu.toolApprovalsPending}),jsxRuntimeExports.jsx(CounterLabel,{children:Au.length})]}):jsxRuntimeExports.jsxs(Box,{borderBottom:"1px solid",borderColor:"attention.muted",bg:"attention.subtle",children:[jsxRuntimeExports.jsxs(Box,{display:"flex",alignItems:"center",justifyContent:"space-between",px:3,py:2,children:[jsxRuntimeExports.jsxs(Box,{display:"flex",alignItems:"center",gap:2,children:[jsxRuntimeExports.jsx(AlertIcon,{size:16}),jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:1,fontWeight:"semibold"},children:Pu.approvalsPending(Au.length)})]}),jsxRuntimeExports.jsxs(Box,{display:"flex",gap:1,children:[$u&&Au.length>=1&&jsxRuntimeExports.jsx(ButtonComponent,{size:"small",variant:"primary",leadingVisual:CheckIcon,onClick:$u,children:Pu.approveAll}),Iu&&jsxRuntimeExports.jsx(ButtonComponent,{size:"small",variant:"invisible",onClick:()=>Mu(!0),children:Pu.collapse}),Ru&&jsxRuntimeExports.jsx(ButtonComponent,{size:"small",variant:"invisible",leadingVisual:XIcon,onClick:Ru,"aria-label":Pu.dismiss})]})]}),jsxRuntimeExports.jsx(Box,{px:3,pb:2,children:Au.map(Du=>jsxRuntimeExports.jsxs(Box,{display:"flex",alignItems:"center",justifyContent:"space-between",py:1,px:2,mb:1,bg:"canvas.default",borderRadius:2,border:"1px solid",borderColor:"border.default",children:[jsxRuntimeExports.jsxs(Box,{children:[jsxRuntimeExports.jsx(Text$3,{sx:{fontWeight:"semibold",fontSize:1},children:Du.toolName}),Du.toolDescription&&jsxRuntimeExports.jsx(Text$3,{sx:{color:"fg.muted",fontSize:0,ml:2},children:Du.toolDescription})]}),jsxRuntimeExports.jsx(ButtonComponent,{size:"small",variant:"default",onClick:()=>lo(Du),children:Pu.review})]},Du.id))})]})}function ToolApprovalDialog({isOpen:Au,toolName:lo,toolDescription:$u,args:Ru,onApprove:Iu,onDeny:Pu,onClose:Ou,showRememberChoice:Mu=!0}){const Du=useChatWords(),[Lu,Bu]=reactExports.useState(!1),ju=reactExports.useCallback(()=>{Iu(Lu)},[Iu,Lu]),Fu=reactExports.useCallback(()=>{Pu(Lu)},[Pu,Lu]);return Au?jsxRuntimeExports.jsxs(Dialog$1,{onClose:Ou,"aria-labelledby":"tool-approval-title",children:[jsxRuntimeExports.jsx(Dialog$1.Header,{children:jsxRuntimeExports.jsxs(Box,{display:"flex",alignItems:"center",gap:2,children:[jsxRuntimeExports.jsx(AlertIcon,{size:16}),Du.approvalTitle]})}),jsxRuntimeExports.jsxs(Box,{p:3,children:[jsxRuntimeExports.jsxs(Box,{mb:3,children:[jsxRuntimeExports.jsxs(Box,{display:"flex",alignItems:"center",gap:2,mb:2,children:[jsxRuntimeExports.jsx(ToolsIcon,{size:20}),jsxRuntimeExports.jsx(Heading$2,{as:"h4",sx:{fontSize:2},children:lo})]}),$u&&jsxRuntimeExports.jsx(Text$3,{sx:{color:"fg.muted",fontSize:1},children:$u})]}),jsxRuntimeExports.jsxs(Box,{mb:3,children:[jsxRuntimeExports.jsx(Text$3,{sx:{fontWeight:"semibold",fontSize:1,mb:2,display:"block"},children:Du.arguments}),jsxRuntimeExports.jsx(Box,{as:"pre",p:3,bg:"canvas.subtle",borderRadius:2,border:"1px solid",borderColor:"border.default",overflow:"auto",maxHeight:200,fontSize:0,children:JSON.stringify(Ru,null,2)})]}),jsxRuntimeExports.jsx(Box,{p:3,bg:"attention.subtle",borderRadius:2,border:"1px solid",borderColor:"attention.muted",mb:3,children:jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:1},children:Du.approvalWarning})}),Mu&&jsxRuntimeExports.jsxs(FormControl$1,{sx:{mb:3},children:[jsxRuntimeExports.jsx(Checkbox,{checked:Lu,onChange:zu=>Bu(zu.target.checked)}),jsxRuntimeExports.jsx(FormControl$1.Label,{children:Du.rememberChoice})]}),jsxRuntimeExports.jsxs(Box,{display:"flex",justifyContent:"flex-end",gap:2,children:[jsxRuntimeExports.jsx(ButtonComponent,{variant:"danger",onClick:Fu,leadingVisual:XIcon,children:Du.deny}),jsxRuntimeExports.jsx(ButtonComponent,{variant:"primary",onClick:ju,leadingVisual:CheckIcon,children:Du.approve})]})]})]}):null}const isUsable=Au=>Au.isAvailable!==!1;function usableModels(Au){const lo=Au.filter(isUsable);return lo.length>0?lo:Au}function offeredModels(Au,lo){return usableModels(Au??lo())}const isOffered=(Au,lo)=>!!lo&&Au.some($u=>$u.id===lo&&isUsable($u));function initialModelId(Au,lo){return Au.some(Ru=>Ru.id===lo&&isUsable(Ru))?lo:(Au.find(isUsable)??Au[0])?.id}function readServerCatalogue(Au){return(Au?.models??[]).map(readServerModel)}function readServerDecisions(Au){return{models:Au.decision_models.map(readServerModel),note:Au.decisions_note}}function readServerModel(Au){const lo=Au.missing_env_vars??[],$u=Au.reason??(lo.length>0?`Set ${lo.join(", ")}`:void 0)??Au.warning??void 0;return{id:Au.id,name:Au.name??Au.id,isAvailable:Au.available!==!1,...$u&&Au.available===!1?{unavailableReason:$u}:{}}}const executionCache=new Map,CACHE_TTL_MS=2e3;function getOperationSignature(Au,lo){return`${Au}:${JSON.stringify(lo)}`}function isRecentDuplicate(Au,lo){const $u=getOperationSignature(Au,lo),Ru=executionCache.get($u);if(Ru&&Date.now()-Ru<CACHE_TTL_MS)return!0;for(const[Iu,Pu]of executionCache.entries())Date.now()-Pu>CACHE_TTL_MS*2&&executionCache.delete(Iu);return executionCache.set($u,Date.now()),!1}function processParameters(Au){if(!Au||typeof Au!="object"||Array.isArray(Au))return Au;const lo={};for(const[$u,Ru]of Object.entries(Au))if(typeof Ru=="string"&&(Ru.startsWith("{")||Ru.startsWith("[")))try{lo[$u]=JSON.parse(Ru)}catch{lo[$u]=Ru}else lo[$u]=Ru;return lo}function createAgentRuntimesTool(Au,lo,$u){const Ru=new OperationRunner;return{name:Au.toolReferenceName||Au.name,description:Au.description,parameters:Au.parameters,handler:async Iu=>{if(isRecentDuplicate(Au.name,Iu))return{success:!1,message:"Operation already executed recently (duplicate detected)"};try{const Pu=processParameters(Iu);return await Ru.execute(lo,Pu,{...$u,format:"toon"})}catch(Pu){return console.error("[agent-runtimes] ❌ ERROR in handler:",Pu),{success:!1,error:Pu instanceof Error?Pu.message:String(Pu)}}}}}function createAllAgentRuntimesTools(Au,lo,$u){const Ru=[];for(const Iu of Au){const Pu=lo[Iu.operation];if(!Pu){console.warn(`[agent-runtimes Tools] No operation found for ${Iu.name} (operation: ${Iu.operation})`);continue}const Ou=createAgentRuntimesTool(Iu,Pu,$u);Ru.push(Ou)}return Ru}const useNotebookStore=()=>notebookStore.getState();function createNotebookTools(Au,lo){const $u=new DefaultExecutor(Au,notebookStore.getState());return createAllAgentRuntimesTools(notebookToolDefinitions,notebookToolOperations,{documentId:Au,executor:$u,format:"toon",...lo})}function useNotebookTools(Au,lo){const $u=useNotebookStore(),Ru=reactExports.useMemo(()=>new DefaultExecutor(Au,$u),[Au]),Iu=reactExports.useMemo(()=>({documentId:Au,executor:Ru,format:"toon",...lo}),[Au,Ru,lo]);return reactExports.useMemo(()=>createAllAgentRuntimesTools(notebookToolDefinitions,notebookToolOperations,Iu),[Iu])}const notebookHooks=Object.freeze(Object.defineProperty({__proto__:null,createNotebookTools,useNotebookTools},Symbol.toStringTag,{value:"Module"})),AGENT_SPAN_ATTRIBUTES={operation:"gen_ai.operation.name",agentName:"gen_ai.agent.name",conversationId:"gen_ai.conversation.id",requestModel:"gen_ai.request.model",inputMessages:"gen_ai.input.messages",outputMessages:"gen_ai.output.messages",inputTokens:"gen_ai.usage.input_tokens",outputTokens:"gen_ai.usage.output_tokens",toolName:"gen_ai.tool.name",toolCallId:"gen_ai.tool.call.id",toolArguments:"gen_ai.tool.call.arguments",toolResult:"gen_ai.tool.call.result",toolType:"gen_ai.tool.type",toolKind:"datalayer.tool.kind",markIcon:"datalayer.mark.icon",markEmoji:"datalayer.mark.emoji",origin:"datalayer.span.origin",errorType:"error.type"},A=AGENT_SPAN_ATTRIBUTES;function jsonAttribute(Au){if(Au!==void 0)try{return JSON.stringify(Au)}catch{return String(Au)}}function shortLine(Au,lo=160){const $u=Au.replace(/\s+/g," ").trim();return $u.length>lo?`${$u.slice(0,lo-1)}…`:$u}function argumentsLine(Au,lo=100){if(!Au||typeof Au!="object")return Au===void 0?"":shortLine(String(Au),lo);const $u=Object.entries(Au).map(([Ru,Iu])=>`${Ru}=${typeof Iu=="string"?Iu:JSON.stringify(Iu)}`);return shortLine($u.join(", "),lo)}function messages(Au,lo){return JSON.stringify([{role:Au,parts:[{type:"text",content:lo}]}])}function startAgentTurn(Au,lo){return Au.startSpan(`invoke_agent ${lo.agent}`,{serviceName:lo.agent,parent:null,attributes:{[A.operation]:"invoke_agent",[A.agentName]:lo.agent,[A.requestModel]:lo.model||void 0,[A.conversationId]:lo.conversationId,[A.inputMessages]:messages("user",lo.prompt)}})}function endAgentTurn(Au,lo){const $u=lo.usage;Au.setAttributes({[A.outputMessages]:lo.text?messages("assistant",lo.text):void 0,[A.inputTokens]:$u?.inputTokens??$u?.promptTokens,[A.outputTokens]:$u?.outputTokens??$u?.completionTokens}),lo.error?(Au.setAttribute(A.errorType,"error"),Au.recordException(new Error(lo.error))):Au.setStatus("OK"),Au.end()}function toolType(Au){return Au==="mcp"?"extension":"function"}function startToolCall(Au,lo){return Au.startSpan(`execute_tool ${lo.name}`,{serviceName:lo.agent,...lo.parent?{parent:lo.parent}:{},attributes:{[A.operation]:"execute_tool",[A.agentName]:lo.agent,[A.toolName]:lo.name,[A.toolCallId]:lo.id,[A.toolArguments]:jsonAttribute(lo.args??{}),[A.toolType]:toolType(lo.tool.kind),[A.toolKind]:lo.tool.kind,[A.markIcon]:lo.tool.icon,[A.markEmoji]:lo.tool.emoji,[A.origin]:lo.origin}})}function endToolCall(Au,lo){Au.setAttribute(A.toolResult,jsonAttribute(lo.result)),lo.error?(Au.setAttribute(A.errorType,"tool_error"),Au.recordException(new Error(lo.error))):Au.setStatus("OK"),Au.end()}function sourceOfSpan(Au){const lo=Au.attributes??{};if(lo[A.toolKind])return String(lo[A.toolKind]);if(lo["rpc.service"]==="a2a"||Au.span_name.startsWith("a2a "))return"a2a";if(lo[A.operation]==="invoke_agent")return"model"}const SPAN_SOURCE_LABELS={a2a:"A2A",mcp:"MCP",frontend:"Frontend tool",skill:"Skill",codemode:"Codemode",runtime:"Runtime tool",model:"Model"};function messageText$1(Au){if(typeof Au!="string")return"";try{return(JSON.parse(Au)[0]?.parts??[]).map($u=>typeof $u.content=="string"?$u.content:"").join("")}catch{return""}}function describeAgentSpan(Au){const lo=Au.attributes??{},$u=lo[A.operation];if($u==="execute_tool"){let Mu;try{Mu=JSON.parse(String(lo[A.toolArguments]??"{}"))}catch{Mu=lo[A.toolArguments]}return argumentsLine(Mu)||void 0}if($u==="invoke_agent"){const Mu=messageText$1(lo[A.inputMessages]),Du=messageText$1(lo[A.outputMessages]),Lu=Number(lo[A.inputTokens]??0),Bu=Number(lo[A.outputTokens]??0),ju=Lu+Bu?` · ${Lu+Bu} tokens`:"";return shortLine(Du?`${shortLine(Mu,60)} → ${Du}`:Mu)+ju}const Ru=lo["a2a.message.text"],Iu=lo["a2a.task.state"],Pu=[typeof Iu=="string"?stateWord(Iu):"",typeof Ru=="string"?shortLine(Ru):""].filter(Boolean);if(Pu.length)return Pu.join(" · ");const Ou=lo["a2a.agent.skills"];return Array.isArray(Ou)?Ou.join(", "):void 0}function stateWord(Au){return typeof Au=="string"?Au.replace(/^TASK_STATE_/,"").toLowerCase().replace(/_/g," "):""}const AgentInspectorContext=reactExports.createContext(null);function useAgentInspectorTracer(){return reactExports.useContext(AgentInspectorContext)}const CODEMODE_TOOLS=new Set(["list_servers","list_tool_names","search_tools","get_tool_details","execute_code"]);function classifyToolCall(Au,lo,$u={}){const Ru=marksOfToolCall(Au,lo,$u.mcpServers);return{kind:$u.frontendTools?.includes(Au)?"frontend":Ru?.kind?Ru.kind:CODEMODE_TOOLS.has(Au)?"codemode":$u.fallback??"runtime",...Ru?.icon?{icon:Ru.icon}:{},...Ru?.emoji?{emoji:Ru.emoji}:{}}}function chatSpanRecorder(Au,lo,$u={}){let Ru;const Iu=new Map;return{turnStarted(Pu,Ou){Ru=startAgentTurn(Au,{agent:lo(),prompt:Pu,model:Ou})},turnEnded(Pu){Ru&&(endAgentTurn(Ru,Pu),Ru=void 0)},toolStarted({id:Pu,name:Ou,args:Mu}){const Du=Iu.get(Pu);if(Du){Du.setAttribute("gen_ai.tool.call.arguments",JSON.stringify(Mu??{}));return}Iu.set(Pu,startToolCall(Au,{agent:lo(),name:Ou,id:Pu,args:Mu,tool:classifyToolCall(Ou,Mu,{frontendTools:$u.frontendTools?.(),mcpServers:$u.mcpServers?.()}),...Ru?{parent:Ru.context}:{}}))},toolEnded(Pu,Ou){const Mu=Iu.get(Pu);Mu&&(Iu.delete(Pu),endToolCall(Mu,Ou))}}}const STEP_DISPLAY_TYPE="application/vnd.datalayer.loop.step+json",isStepDisplay=Au=>Au.type===STEP_DISPLAY_TYPE;function stepOfDisplay(Au){const lo=Au.data??{};if(!isStepDisplay(Au)||typeof lo.name!="string")throw new Error(`Display ${Au.id} is not a step`);return{id:Au.id,name:lo.name,kind:typeof lo.kind=="string"?lo.kind:"run",parentId:typeof lo.parent_id=="string"&&lo.parent_id?lo.parent_id:null,input:lo.input??null,output:lo.output??null,error:typeof lo.error=="string"?lo.error:"",ended:typeof lo.ended_at=="string"&&lo.ended_at!==""}}const stepCallId=Au=>`step-${Au}`;function stepItem(Au,lo){const $u=stepCallId(Au.id),Ru=`${Au.kind} step`;return{id:$u,type:"tool-call",toolCallId:$u,toolName:Au.name,args:{kind:Au.kind,...Au.input!==null?{input:Au.input}:{}},...!Au.error&&Au.output!==null?{result:Au.output}:{},status:Au.ended?Au.error?"error":"complete":"executing",...Au.error?{error:Au.error}:{},summary:lo?`${Ru}, inside ${lo}`:Ru}}function withLoopStep(Au,lo){const $u=lo.parentId?Au.find(Ou=>"toolCallId"in Ou&&Ou.toolCallId===stepCallId(lo.parentId)):void 0,Ru=stepItem(lo,$u&&"toolName"in $u?$u.toolName:void 0);let Iu=!1;const Pu=Au.map(Ou=>"toolCallId"in Ou&&Ou.toolCallId===Ru.toolCallId?(Iu=!0,Ru):Ou);return Iu?Pu:[...Au,Ru]}function elementOfDisplay(Au){const lo=Au.data?.where;if(lo!=="panel"&&lo!=="page")return null;const $u=Au.data?.title;return{id:Au.id,where:lo,title:typeof $u=="string"?$u:"",shows:Au}}function withLoopElement(Au,lo){if("closed"in lo)return Au.filter(Ru=>Ru.id!==lo.id);const $u=Au.findIndex(Ru=>Ru.id===lo.id);return $u<0?[...Au,lo]:Au.map((Ru,Iu)=>Iu===$u?lo:Ru)}let opened=[];const listeners$4=new Set,openLoopElements=()=>opened;function applyLoopElement(Au){opened=withLoopElement(opened,Au);for(const lo of[...listeners$4])lo(opened)}const closeLoopElement=Au=>applyLoopElement({id:Au,closed:!0});function clearLoopElements(){opened=[];for(const Au of[...listeners$4])Au(opened)}function onLoopElements(Au){return listeners$4.add(Au),()=>{listeners$4.delete(Au)}}const WINDOW_MESSAGE="message";function windowMessageOf(Au){if(Au.body.name!==WINDOW_MESSAGE)throw new Error(`A window op named ${Au.body.name} is not one this page acts on`);const lo=Au.body.args;if(!lo||!("data"in lo))throw new Error("A window message says no data");return lo.data}const listeners$3=new Set;function tellLoopWindow(Au){for(const lo of[...listeners$3])lo(Au)}function onLoopWindowMessage(Au){return listeners$3.add(Au),()=>{listeners$3.delete(Au)}}function windowTurnErrorOf(Au){let lo=null;for(const $u of Au.split(`
3688
+ }`;function squeezed(Au){return Au.replace(/\s+/g," ").trim()}function saidMessageId(Au,lo){const $u=squeezed(lo??"");if($u)for(let Ru=Au.length-1;Ru>=0;Ru-=1){const Iu=answerText(Au[Ru]);if(Iu!==void 0&&squeezed(plainWords(Iu)).includes($u)){const Pu=Au[Ru].id;return typeof Pu=="string"?Pu:void 0}}}function sentenceRange(Au,lo){const $u=squeezed(lo);if(!$u||!Au.ownerDocument)return;const Ru=Au.ownerDocument,Iu=Ru.createTreeWalker(Au,4);let Pu="";const Ou=[];let Mu=!0;for(let Fu=Iu.nextNode();Fu;Fu=Iu.nextNode()){const zu=Fu.nodeValue??"";for(let Uu=0;Uu<zu.length;Uu+=1){const Hu=zu[Uu];if(/\s/.test(Hu)){if(Mu)continue;Mu=!0,Pu+=" "}else Mu=!1,Pu+=Hu;Ou.push({node:Fu,offset:Uu})}}const Du=Pu.indexOf($u);if(Du<0)return;const Lu=Ou[Du],Bu=Ou[Du+$u.length-1],ju=Ru.createRange();return ju.setStart(Lu.node,Lu.offset),ju.setEnd(Bu.node,Bu.offset+1),ju}function registry(){return globalThis.CSS?.highlights}function highlightOf(Au){const lo=globalThis.Highlight;return lo?new lo(Au):void 0}let styled=!1;function ensureStyle(Au){if(styled||Au.getElementById("datalayer-voice-said")){styled=!0;return}const lo=Au.createElement("style");lo.id="datalayer-voice-said",lo.textContent=SAID_STYLE,Au.head.appendChild(lo),styled=!0}function useSaidSentence(Au,lo,$u){reactExports.useEffect(()=>{const Ru=registry(),Iu=Au.current?.querySelector("[data-voice-saying]");if(!Ru||!Iu||!lo)return;const Pu=()=>{const Mu=sentenceRange(Iu,lo),Du=Mu?highlightOf(Mu):void 0;return Du?(ensureStyle(Iu.ownerDocument),Ru.set(SAID_HIGHLIGHT,Du),!0):!1};let Ou;return!Pu()&&typeof MutationObserver<"u"&&(Ou=new MutationObserver(()=>{Pu()&&Ou?.disconnect()}),Ou.observe(Iu,{childList:!0,subtree:!0,characterData:!0})),()=>{Ou?.disconnect(),Ru.delete(SAID_HIGHLIGHT)}},[Au,lo,$u])}function ToolApprovalBanner({pendingApprovals:Au,onReview:lo,onApproveAll:$u,onDismiss:Ru,collapsible:Iu=!0}){const Pu=useChatWords(),[Ou,Mu]=reactExports.useState(!1);return Au.length===0?null:Ou?jsxRuntimeExports.jsxs(Box,{display:"flex",alignItems:"center",gap:2,px:3,py:2,bg:"attention.subtle",borderBottom:"1px solid",borderColor:"attention.muted",cursor:"pointer",onClick:()=>Mu(!1),children:[jsxRuntimeExports.jsx(ShieldCheckIcon,{size:16}),jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:1,fontWeight:"semibold"},children:Pu.toolApprovalsPending}),jsxRuntimeExports.jsx(CounterLabel,{children:Au.length})]}):jsxRuntimeExports.jsxs(Box,{borderBottom:"1px solid",borderColor:"attention.muted",bg:"attention.subtle",children:[jsxRuntimeExports.jsxs(Box,{display:"flex",alignItems:"center",justifyContent:"space-between",px:3,py:2,children:[jsxRuntimeExports.jsxs(Box,{display:"flex",alignItems:"center",gap:2,children:[jsxRuntimeExports.jsx(AlertIcon,{size:16}),jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:1,fontWeight:"semibold"},children:Pu.approvalsPending(Au.length)})]}),jsxRuntimeExports.jsxs(Box,{display:"flex",gap:1,children:[$u&&Au.length>=1&&jsxRuntimeExports.jsx(ButtonComponent,{size:"small",variant:"primary",leadingVisual:CheckIcon,onClick:$u,children:Pu.approveAll}),Iu&&jsxRuntimeExports.jsx(ButtonComponent,{size:"small",variant:"invisible",onClick:()=>Mu(!0),children:Pu.collapse}),Ru&&jsxRuntimeExports.jsx(ButtonComponent,{size:"small",variant:"invisible",leadingVisual:XIcon,onClick:Ru,"aria-label":Pu.dismiss})]})]}),jsxRuntimeExports.jsx(Box,{px:3,pb:2,children:Au.map(Du=>jsxRuntimeExports.jsxs(Box,{display:"flex",alignItems:"center",justifyContent:"space-between",py:1,px:2,mb:1,bg:"canvas.default",borderRadius:2,border:"1px solid",borderColor:"border.default",children:[jsxRuntimeExports.jsxs(Box,{children:[jsxRuntimeExports.jsx(Text$3,{sx:{fontWeight:"semibold",fontSize:1},children:Du.toolName}),Du.toolDescription&&jsxRuntimeExports.jsx(Text$3,{sx:{color:"fg.muted",fontSize:0,ml:2},children:Du.toolDescription})]}),jsxRuntimeExports.jsx(ButtonComponent,{size:"small",variant:"default",onClick:()=>lo(Du),children:Pu.review})]},Du.id))})]})}function ToolApprovalDialog({isOpen:Au,toolName:lo,toolDescription:$u,args:Ru,onApprove:Iu,onDeny:Pu,onClose:Ou,showRememberChoice:Mu=!0}){const Du=useChatWords(),[Lu,Bu]=reactExports.useState(!1),ju=reactExports.useCallback(()=>{Iu(Lu)},[Iu,Lu]),Fu=reactExports.useCallback(()=>{Pu(Lu)},[Pu,Lu]);return Au?jsxRuntimeExports.jsxs(Dialog$1,{onClose:Ou,"aria-labelledby":"tool-approval-title",children:[jsxRuntimeExports.jsx(Dialog$1.Header,{children:jsxRuntimeExports.jsxs(Box,{display:"flex",alignItems:"center",gap:2,children:[jsxRuntimeExports.jsx(AlertIcon,{size:16}),Du.approvalTitle]})}),jsxRuntimeExports.jsxs(Box,{p:3,children:[jsxRuntimeExports.jsxs(Box,{mb:3,children:[jsxRuntimeExports.jsxs(Box,{display:"flex",alignItems:"center",gap:2,mb:2,children:[jsxRuntimeExports.jsx(ToolsIcon,{size:20}),jsxRuntimeExports.jsx(Heading$2,{as:"h4",sx:{fontSize:2},children:lo})]}),$u&&jsxRuntimeExports.jsx(Text$3,{sx:{color:"fg.muted",fontSize:1},children:$u})]}),jsxRuntimeExports.jsxs(Box,{mb:3,children:[jsxRuntimeExports.jsx(Text$3,{sx:{fontWeight:"semibold",fontSize:1,mb:2,display:"block"},children:Du.arguments}),jsxRuntimeExports.jsx(Box,{as:"pre",p:3,bg:"canvas.subtle",borderRadius:2,border:"1px solid",borderColor:"border.default",overflow:"auto",maxHeight:200,fontSize:0,children:JSON.stringify(Ru,null,2)})]}),jsxRuntimeExports.jsx(Box,{p:3,bg:"attention.subtle",borderRadius:2,border:"1px solid",borderColor:"attention.muted",mb:3,children:jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:1},children:Du.approvalWarning})}),Mu&&jsxRuntimeExports.jsxs(FormControl$1,{sx:{mb:3},children:[jsxRuntimeExports.jsx(Checkbox,{checked:Lu,onChange:zu=>Bu(zu.target.checked)}),jsxRuntimeExports.jsx(FormControl$1.Label,{children:Du.rememberChoice})]}),jsxRuntimeExports.jsxs(Box,{display:"flex",justifyContent:"flex-end",gap:2,children:[jsxRuntimeExports.jsx(ButtonComponent,{variant:"danger",onClick:Fu,leadingVisual:XIcon,children:Du.deny}),jsxRuntimeExports.jsx(ButtonComponent,{variant:"primary",onClick:ju,leadingVisual:CheckIcon,children:Du.approve})]})]})]}):null}const isUsable=Au=>Au.isAvailable!==!1;function usableModels(Au){const lo=Au.filter(isUsable);return lo.length>0?lo:Au}function offeredModels(Au,lo){return usableModels(Au??lo())}const isOffered=(Au,lo)=>!!lo&&Au.some($u=>$u.id===lo&&isUsable($u));function initialModelId(Au,lo){return Au.some(Ru=>Ru.id===lo&&isUsable(Ru))?lo:(Au.find(isUsable)??Au[0])?.id}function readServerCatalogue(Au){return(Au?.models??[]).map(readServerModel)}function readServerDecisions(Au){return{models:Au.decision_models.map(readServerModel),note:Au.decisions_note}}function readServerModel(Au){const lo=Au.missing_env_vars??[],$u=Au.reason??(lo.length>0?`Set ${lo.join(", ")}`:void 0)??Au.warning??void 0;return{id:Au.id,name:Au.name??Au.id,isAvailable:Au.available!==!1,...$u&&Au.available===!1?{unavailableReason:$u}:{}}}const executionCache=new Map,CACHE_TTL_MS=2e3;function getOperationSignature(Au,lo){return`${Au}:${JSON.stringify(lo)}`}function isRecentDuplicate(Au,lo){const $u=getOperationSignature(Au,lo),Ru=executionCache.get($u);if(Ru&&Date.now()-Ru<CACHE_TTL_MS)return!0;for(const[Iu,Pu]of executionCache.entries())Date.now()-Pu>CACHE_TTL_MS*2&&executionCache.delete(Iu);return executionCache.set($u,Date.now()),!1}function processParameters(Au){if(!Au||typeof Au!="object"||Array.isArray(Au))return Au;const lo={};for(const[$u,Ru]of Object.entries(Au))if(typeof Ru=="string"&&(Ru.startsWith("{")||Ru.startsWith("[")))try{lo[$u]=JSON.parse(Ru)}catch{lo[$u]=Ru}else lo[$u]=Ru;return lo}function createAgentRuntimesTool(Au,lo,$u){const Ru=new OperationRunner;return{name:Au.toolReferenceName||Au.name,description:Au.description,parameters:Au.parameters,handler:async Iu=>{if(isRecentDuplicate(Au.name,Iu))return{success:!1,message:"Operation already executed recently (duplicate detected)"};try{const Pu=processParameters(Iu);return await Ru.execute(lo,Pu,{...$u,format:"toon"})}catch(Pu){return console.error("[agent-runtimes] ❌ ERROR in handler:",Pu),{success:!1,error:Pu instanceof Error?Pu.message:String(Pu)}}}}}function createAllAgentRuntimesTools(Au,lo,$u){const Ru=[];for(const Iu of Au){const Pu=lo[Iu.operation];if(!Pu){console.warn(`[agent-runtimes Tools] No operation found for ${Iu.name} (operation: ${Iu.operation})`);continue}const Ou=createAgentRuntimesTool(Iu,Pu,$u);Ru.push(Ou)}return Ru}const useNotebookStore=()=>notebookStore.getState();function createNotebookTools(Au,lo){const $u=new DefaultExecutor(Au,notebookStore.getState());return createAllAgentRuntimesTools(notebookToolDefinitions,notebookToolOperations,{documentId:Au,executor:$u,format:"toon",...lo})}function useNotebookTools(Au,lo){const $u=useNotebookStore(),Ru=reactExports.useMemo(()=>new DefaultExecutor(Au,$u),[Au]),Iu=reactExports.useMemo(()=>({documentId:Au,executor:Ru,format:"toon",...lo}),[Au,Ru,lo]);return reactExports.useMemo(()=>createAllAgentRuntimesTools(notebookToolDefinitions,notebookToolOperations,Iu),[Iu])}const notebookHooks=Object.freeze(Object.defineProperty({__proto__:null,createNotebookTools,useNotebookTools},Symbol.toStringTag,{value:"Module"})),AGENT_SPAN_ATTRIBUTES={operation:"gen_ai.operation.name",agentName:"gen_ai.agent.name",conversationId:"gen_ai.conversation.id",requestModel:"gen_ai.request.model",inputMessages:"gen_ai.input.messages",outputMessages:"gen_ai.output.messages",inputTokens:"gen_ai.usage.input_tokens",outputTokens:"gen_ai.usage.output_tokens",toolName:"gen_ai.tool.name",toolCallId:"gen_ai.tool.call.id",toolArguments:"gen_ai.tool.call.arguments",toolResult:"gen_ai.tool.call.result",toolType:"gen_ai.tool.type",toolKind:"datalayer.tool.kind",markIcon:"datalayer.mark.icon",markEmoji:"datalayer.mark.emoji",origin:"datalayer.span.origin",errorType:"error.type"},A=AGENT_SPAN_ATTRIBUTES;function jsonAttribute(Au){if(Au!==void 0)try{return JSON.stringify(Au)}catch{return String(Au)}}function shortLine(Au,lo=160){const $u=Au.replace(/\s+/g," ").trim();return $u.length>lo?`${$u.slice(0,lo-1)}…`:$u}function argumentsLine(Au,lo=100){if(!Au||typeof Au!="object")return Au===void 0?"":shortLine(String(Au),lo);const $u=Object.entries(Au).map(([Ru,Iu])=>`${Ru}=${typeof Iu=="string"?Iu:JSON.stringify(Iu)}`);return shortLine($u.join(", "),lo)}function messages(Au,lo){return JSON.stringify([{role:Au,parts:[{type:"text",content:lo}]}])}function startAgentTurn(Au,lo){return Au.startSpan(`invoke_agent ${lo.agent}`,{serviceName:lo.agent,parent:null,attributes:{[A.operation]:"invoke_agent",[A.agentName]:lo.agent,[A.requestModel]:lo.model||void 0,[A.conversationId]:lo.conversationId,[A.inputMessages]:messages("user",lo.prompt)}})}function endAgentTurn(Au,lo){const $u=lo.usage;Au.setAttributes({[A.outputMessages]:lo.text?messages("assistant",lo.text):void 0,[A.inputTokens]:$u?.inputTokens??$u?.promptTokens,[A.outputTokens]:$u?.outputTokens??$u?.completionTokens}),lo.error?(Au.setAttribute(A.errorType,"error"),Au.recordException(new Error(lo.error))):Au.setStatus("OK"),Au.end()}function toolType(Au){return Au==="mcp"?"extension":"function"}function startToolCall(Au,lo){return Au.startSpan(`execute_tool ${lo.name}`,{serviceName:lo.agent,...lo.parent?{parent:lo.parent}:{},attributes:{[A.operation]:"execute_tool",[A.agentName]:lo.agent,[A.toolName]:lo.name,[A.toolCallId]:lo.id,[A.toolArguments]:jsonAttribute(lo.args??{}),[A.toolType]:toolType(lo.tool.kind),[A.toolKind]:lo.tool.kind,[A.markIcon]:lo.tool.icon,[A.markEmoji]:lo.tool.emoji,[A.origin]:lo.origin}})}function endToolCall(Au,lo){Au.setAttribute(A.toolResult,jsonAttribute(lo.result)),lo.error?(Au.setAttribute(A.errorType,"tool_error"),Au.recordException(new Error(lo.error))):Au.setStatus("OK"),Au.end()}function sourceOfSpan(Au){const lo=Au.attributes??{};if(lo[A.toolKind])return String(lo[A.toolKind]);if(lo["rpc.service"]==="a2a"||Au.span_name.startsWith("a2a "))return"a2a";if(lo[A.operation]==="invoke_agent")return"model"}const SPAN_SOURCE_LABELS={a2a:"A2A",mcp:"MCP",frontend:"Frontend tool",skill:"Skill",codemode:"Codemode",runtime:"Runtime tool",model:"Model"};function messageText$1(Au){if(typeof Au!="string")return"";try{return(JSON.parse(Au)[0]?.parts??[]).map($u=>typeof $u.content=="string"?$u.content:"").join("")}catch{return""}}function describeAgentSpan(Au){const lo=Au.attributes??{},$u=lo[A.operation];if($u==="execute_tool"){let Mu;try{Mu=JSON.parse(String(lo[A.toolArguments]??"{}"))}catch{Mu=lo[A.toolArguments]}return argumentsLine(Mu)||void 0}if($u==="invoke_agent"){const Mu=messageText$1(lo[A.inputMessages]),Du=messageText$1(lo[A.outputMessages]),Lu=Number(lo[A.inputTokens]??0),Bu=Number(lo[A.outputTokens]??0),ju=Lu+Bu?` · ${Lu+Bu} tokens`:"";return shortLine(Du?`${shortLine(Mu,60)} → ${Du}`:Mu)+ju}const Ru=lo["a2a.message.text"],Iu=lo["a2a.task.state"],Pu=[typeof Iu=="string"?stateWord(Iu):"",typeof Ru=="string"?shortLine(Ru):""].filter(Boolean);if(Pu.length)return Pu.join(" · ");const Ou=lo["a2a.agent.skills"];return Array.isArray(Ou)?Ou.join(", "):void 0}function stateWord(Au){return typeof Au=="string"?Au.replace(/^TASK_STATE_/,"").toLowerCase().replace(/_/g," "):""}const AgentInspectorContext=reactExports.createContext(null);function useAgentInspectorTracer(){return reactExports.useContext(AgentInspectorContext)}const CODEMODE_TOOLS=new Set(["list_servers","list_tool_names","search_tools","get_tool_details","execute_code"]);function classifyToolCall(Au,lo,$u={}){const Ru=marksOfToolCall(Au,lo,$u.mcpServers);return{kind:$u.frontendTools?.includes(Au)?"frontend":Ru?.kind?Ru.kind:CODEMODE_TOOLS.has(Au)?"codemode":$u.fallback??"runtime",...Ru?.icon?{icon:Ru.icon}:{},...Ru?.emoji?{emoji:Ru.emoji}:{}}}function chatSpanRecorder(Au,lo,$u={}){let Ru;const Iu=new Map;return{turnStarted(Pu,Ou){Ru=startAgentTurn(Au,{agent:lo(),prompt:Pu,model:Ou})},turnEnded(Pu){Ru&&(endAgentTurn(Ru,Pu),Ru=void 0)},toolStarted({id:Pu,name:Ou,args:Mu}){const Du=Iu.get(Pu);if(Du){Du.setAttribute("gen_ai.tool.call.arguments",JSON.stringify(Mu??{}));return}Iu.set(Pu,startToolCall(Au,{agent:lo(),name:Ou,id:Pu,args:Mu,tool:classifyToolCall(Ou,Mu,{frontendTools:$u.frontendTools?.(),mcpServers:$u.mcpServers?.()}),...Ru?{parent:Ru.context}:{}}))},toolEnded(Pu,Ou){const Mu=Iu.get(Pu);Mu&&(Iu.delete(Pu),endToolCall(Mu,Ou))}}}const STEP_DISPLAY_TYPE="application/vnd.datalayer.loop.step+json",isStepDisplay=Au=>Au.type===STEP_DISPLAY_TYPE;function stepOfDisplay(Au){const lo=Au.data??{};if(!isStepDisplay(Au)||typeof lo.name!="string")throw new Error(`Display ${Au.id} is not a step`);return{id:Au.id,name:lo.name,kind:typeof lo.kind=="string"?lo.kind:"run",parentId:typeof lo.parent_id=="string"&&lo.parent_id?lo.parent_id:null,input:lo.input??null,output:lo.output??null,error:typeof lo.error=="string"?lo.error:"",ended:typeof lo.ended_at=="string"&&lo.ended_at!==""}}const stepCallId=Au=>`step-${Au}`;function stepItem(Au,lo){const $u=stepCallId(Au.id),Ru=`${Au.kind} step`;return{id:$u,type:"tool-call",toolCallId:$u,toolName:Au.name,args:{kind:Au.kind,...Au.input!==null?{input:Au.input}:{}},...!Au.error&&Au.output!==null?{result:Au.output}:{},status:Au.ended?Au.error?"error":"complete":"executing",...Au.error?{error:Au.error}:{},summary:lo?`${Ru}, inside ${lo}`:Ru}}function withLoopStep(Au,lo){const $u=lo.parentId?Au.find(Ou=>"toolCallId"in Ou&&Ou.toolCallId===stepCallId(lo.parentId)):void 0,Ru=stepItem(lo,$u&&"toolName"in $u?$u.toolName:void 0);let Iu=!1;const Pu=Au.map(Ou=>"toolCallId"in Ou&&Ou.toolCallId===Ru.toolCallId?(Iu=!0,Ru):Ou);return Iu?Pu:[...Au,Ru]}function elementOfDisplay(Au){const lo=Au.data?.where;if(lo!=="panel"&&lo!=="page")return null;const $u=Au.data?.title;return{id:Au.id,where:lo,title:typeof $u=="string"?$u:"",shows:Au}}function withLoopElement(Au,lo){if("closed"in lo)return Au.filter(Ru=>Ru.id!==lo.id);const $u=Au.findIndex(Ru=>Ru.id===lo.id);return $u<0?[...Au,lo]:Au.map((Ru,Iu)=>Iu===$u?lo:Ru)}let opened=[];const listeners$4=new Set,openLoopElements=()=>opened;function applyLoopElement(Au){opened=withLoopElement(opened,Au);for(const lo of[...listeners$4])lo(opened)}const closeLoopElement=Au=>applyLoopElement({id:Au,closed:!0});function clearLoopElements(){opened=[];for(const Au of[...listeners$4])Au(opened)}function onLoopElements(Au){return listeners$4.add(Au),()=>{listeners$4.delete(Au)}}const WINDOW_MESSAGE="message";function windowMessageOf(Au){if(Au.body.name!==WINDOW_MESSAGE)throw new Error(`A window op named ${Au.body.name} is not one this page acts on`);const lo=Au.body.args;if(!lo||!("data"in lo))throw new Error("A window message says no data");return lo.data}const listeners$3=new Set;function tellLoopWindow(Au){for(const lo of[...listeners$3])lo(Au)}function onLoopWindowMessage(Au){return listeners$3.add(Au),()=>{listeners$3.delete(Au)}}function windowTurnErrorOf(Au){let lo=null;for(const $u of Au.split(`
3689
3689
 
3690
3690
  `)){const Ru=$u.split(`
3691
3691
  `).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-rusBlgBp.js"),[],import.meta.url).then(Au=>({default:Au.EphemeralDocument}))),loadAgentDetails=()=>__vitePreload(()=>import("./chunks/AgentDetails-Xvq2IvHg.js"),[],import.meta.url).then(Au=>({default:Au.AgentDetails})),loadEphemeralNotebook=()=>__vitePreload(()=>import("./chunks/EphemeralNotebook-BqccUXGd.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)}
@@ -0,0 +1,40 @@
1
+ {
2
+ "name": "@datalayer/slack",
3
+ "lockfileVersion": 3,
4
+ "packages": {
5
+ "": {
6
+ "name": "@datalayer/slack",
7
+ "dependencies": {
8
+ "@slack/bolt": "5.1.0",
9
+ "@datalayer/agent-runtimes": "1.5.44"
10
+ },
11
+ "devDependencies": { "vitest": "4.1.11" }
12
+ },
13
+ "node_modules/@slack/bolt": {
14
+ "version": "5.1.0",
15
+ "dependencies": { "express": "5.0.0" }
16
+ },
17
+ "node_modules/express": { "version": "5.0.0" },
18
+ "node_modules/@datalayer/agent-runtimes": {
19
+ "version": "1.5.44",
20
+ "dependencies": { "@datalayer/jupyter-react": "2.0.0" }
21
+ },
22
+ "node_modules/@datalayer/jupyter-react": {
23
+ "version": "2.0.0",
24
+ "dependencies": {
25
+ "@jupyterlab/services": "7.0.0",
26
+ "@lumino/widgets": "2.0.0"
27
+ }
28
+ },
29
+ "node_modules/@datalayer/jupyter-react/node_modules/@jupyterlab/services": {
30
+ "version": "7.0.0"
31
+ },
32
+ "node_modules/@lumino/widgets": { "version": "2.0.0" },
33
+ "node_modules/vitest": {
34
+ "version": "4.1.11",
35
+ "dev": true,
36
+ "dependencies": { "react-dom": "19.0.0" }
37
+ },
38
+ "node_modules/react-dom": { "version": "19.0.0", "dev": true }
39
+ }
40
+ }
@@ -0,0 +1,21 @@
1
+ {
2
+ "name": "@datalayer/slack",
3
+ "dependencies": {
4
+ "@slack/bolt": {
5
+ "version": "5.1.0",
6
+ "dependencies": { "express": { "version": "5.0.0" } }
7
+ },
8
+ "@datalayer/agent-runtimes": {
9
+ "version": "1.5.44",
10
+ "dependencies": {
11
+ "@datalayer/jupyter-react": {
12
+ "version": "2.0.0",
13
+ "dependencies": {
14
+ "@jupyterlab/services": { "version": "7.0.0" },
15
+ "react-dom": { "version": "19.0.0" }
16
+ }
17
+ }
18
+ }
19
+ }
20
+ }
21
+ }