@datalayer/agent-runtimes 1.5.45 → 1.5.47

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 (54) hide show
  1. package/dist-embed/datalayer-app-main.js +4 -4
  2. package/lib/portable/conversation.d.ts +6 -0
  3. package/lib/portable/conversation.js +29 -1
  4. package/lib/portable/hosts/__tests__/fixtures/lock-with-jupyter.json +40 -0
  5. package/lib/portable/hosts/__tests__/fixtures/npm-ls-with-jupyter.json +21 -0
  6. package/lib/portable/hosts/agentClient.d.ts +167 -0
  7. package/lib/portable/hosts/agentClient.js +346 -0
  8. package/lib/portable/hosts/approvalRenderers.d.ts +43 -0
  9. package/lib/portable/hosts/approvalRenderers.js +180 -0
  10. package/lib/portable/hosts/client.d.ts +95 -0
  11. package/lib/portable/hosts/client.js +174 -0
  12. package/lib/portable/hosts/contracts.d.ts +199 -0
  13. package/lib/portable/hosts/contracts.js +235 -0
  14. package/lib/portable/hosts/contracts.json +381 -0
  15. package/lib/portable/hosts/deadLetters.d.ts +41 -0
  16. package/lib/portable/hosts/deadLetters.js +124 -0
  17. package/lib/portable/hosts/deliveries.d.ts +76 -0
  18. package/lib/portable/hosts/deliveries.js +147 -0
  19. package/lib/portable/hosts/forbiddenGraph.d.ts +77 -0
  20. package/lib/portable/hosts/forbiddenGraph.js +174 -0
  21. package/lib/portable/hosts/health.d.ts +35 -0
  22. package/lib/portable/hosts/health.js +92 -0
  23. package/lib/portable/hosts/index.d.ts +40 -0
  24. package/lib/portable/hosts/index.js +45 -0
  25. package/lib/portable/hosts/observability.d.ts +67 -0
  26. package/lib/portable/hosts/observability.js +171 -0
  27. package/lib/portable/hosts/postgresQueue.d.ts +55 -0
  28. package/lib/portable/hosts/postgresQueue.js +217 -0
  29. package/lib/portable/hosts/queue.d.ts +47 -0
  30. package/lib/portable/hosts/queue.js +63 -0
  31. package/lib/portable/hosts/quotas.d.ts +81 -0
  32. package/lib/portable/hosts/quotas.js +147 -0
  33. package/lib/portable/hosts/rateLimit.d.ts +13 -0
  34. package/lib/portable/hosts/rateLimit.js +8 -0
  35. package/lib/portable/hosts/resolution.d.ts +54 -0
  36. package/lib/portable/hosts/resolution.js +46 -0
  37. package/lib/portable/hosts/schema.d.ts +19 -0
  38. package/lib/portable/hosts/schema.js +81 -0
  39. package/lib/portable/hosts/secretCipher.d.ts +23 -0
  40. package/lib/portable/hosts/secretCipher.js +45 -0
  41. package/lib/portable/hosts/sessionUid.d.ts +7 -0
  42. package/lib/portable/hosts/sessionUid.js +28 -0
  43. package/lib/portable/hosts/turnState.d.ts +45 -0
  44. package/lib/portable/hosts/turnState.js +113 -0
  45. package/lib/portable/index.d.ts +2 -0
  46. package/lib/portable/index.js +3 -0
  47. package/lib/portable/semantic-events.json +480 -0
  48. package/lib/portable/semantic.d.ts +78 -0
  49. package/lib/portable/semantic.js +100 -0
  50. package/lib/portable/semanticOfAgUi.d.ts +41 -0
  51. package/lib/portable/semanticOfAgUi.js +108 -0
  52. package/lib/protocols/A2AAdapter.js +19 -0
  53. package/lib/test-setup.js +17 -14
  54. 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(`
@@ -2194,7 +2194,7 @@ ${lo}:`]}}function getResponseMetadata2({id:Au,model:lo,created:$u}){return{id:A
2194
2194
  `):ju,zu=streamText({model:this.resolveModel(Bu?.model||$u?.model),system:Fu,messages:Iu,tools:this.tools,stopWhen:isStepCount(this.browserConfig.maxSteps??DEFAULT_BROWSER_MAX_STEPS),abortSignal:Ru.signal});for await(const Uu of zu.fullStream){if(Ru.signal.aborted)break;switch(Uu.type){case"text-start":Du();break;case"text-delta":Ou===null&&Du(),Mu+=Uu.text,Lu();break;case"tool-call":this.emit({type:"tool-call",toolCall:{toolCallId:Uu.toolCallId,toolName:Uu.toolName,args:Uu.input??{},argsComplete:!0},timestamp:new Date});break;case"tool-result":this.emit({type:"tool-result",toolResult:{toolCallId:Uu.toolCallId,success:!0,result:Uu.output},timestamp:new Date});break;case"tool-error":this.emit({type:"tool-result",toolResult:{toolCallId:Uu.toolCallId,success:!1,error:Uu.error instanceof Error?Uu.error.message:String(Uu.error)},timestamp:new Date});break;case"error":this.emit({type:"error",error:Uu.error instanceof Error?Uu.error:new Error(String(Uu.error)),timestamp:new Date});break;case"finish":{const Hu=Uu.totalUsage,Vu=Hu?.inputTokens??0,Gu=Hu?.outputTokens??0,Wu=Hu?.totalTokens??(Vu+Gu>0?Vu+Gu:void 0);this.emit({type:"done",usage:{promptTokens:Vu,completionTokens:Gu,totalTokens:Wu},timestamp:new Date});break}default:break}}}catch(Bu){if(Ru.signal.aborted)return;this.emit({type:"error",error:Bu instanceof Error?Bu:new Error(String(Bu)),timestamp:new Date}),this.emit({type:"done",timestamp:new Date})}finally{this.abortController===Ru&&(this.abortController=null)}}}const AGENT_METHODS={authenticate:"authenticate",initialize:"initialize",session_cancel:"session/cancel",session_fork:"session/fork",session_list:"session/list",session_load:"session/load",session_new:"session/new",session_prompt:"session/prompt",session_set_mode:"session/set_mode",session_set_model:"session/set_model"},CLIENT_METHODS={fs_read_text_file:"fs/read_text_file",fs_write_text_file:"fs/write_text_file",session_request_permission:"session/request_permission",session_update:"session/update",terminal_create:"terminal/create",terminal_kill:"terminal/kill",terminal_output:"terminal/output",terminal_release:"terminal/release",terminal_wait_for_exit:"terminal/wait_for_exit"},PROTOCOL_VERSION=1,zAuthMethod=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),description:union([string$2(),_null()]).optional(),id:string$2(),name:string$2()}),zAuthenticateRequest=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),methodId:string$2()}),zAuthenticateResponse=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional()}),zBlobResourceContents=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),blob:string$2(),mimeType:union([string$2(),_null()]).optional(),uri:string$2()}),zCreateTerminalResponse=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),terminalId:string$2()}),zDiff=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),newText:string$2(),oldText:union([string$2(),_null()]).optional(),path:string$2()}),zEnvVariable=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),name:string$2(),value:string$2()}),zErrorCode=union([literal(-32700),literal(-32600),literal(-32601),literal(-32602),literal(-32603),literal(-32e3),literal(-32002),number$2().int()]),zError=object({code:zErrorCode,data:unknown$1().optional(),message:string$2()}),zExtNotification=unknown$1(),zExtRequest=unknown$1(),zExtResponse=unknown$1(),zFileSystemCapability=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),readTextFile:boolean$1().optional().default(!1),writeTextFile:boolean$1().optional().default(!1)}),zClientCapabilities=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),fs:zFileSystemCapability.optional().default({readTextFile:!1,writeTextFile:!1}),terminal:boolean$1().optional().default(!1)}),zHttpHeader=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),name:string$2(),value:string$2()}),zImplementation=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),name:string$2(),title:union([string$2(),_null()]).optional(),version:string$2()}),zKillTerminalCommandResponse=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional()}),zListSessionsRequest=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),cursor:union([string$2(),_null()]).optional(),cwd:union([string$2(),_null()]).optional()}),zMcpCapabilities=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),http:boolean$1().optional().default(!1),sse:boolean$1().optional().default(!1)}),zMcpServerHttp=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),headers:array(zHttpHeader),name:string$2(),url:string$2()}),zMcpServerSse=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),headers:array(zHttpHeader),name:string$2(),url:string$2()}),zMcpServerStdio=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),args:array(string$2()),command:string$2(),env:array(zEnvVariable),name:string$2()}),zMcpServer=union([zMcpServerHttp.and(object({type:literal("http")})),zMcpServerSse.and(object({type:literal("sse")})),zMcpServerStdio]),zModelId=string$2(),zModelInfo=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),description:union([string$2(),_null()]).optional(),modelId:zModelId,name:string$2()}),zNewSessionRequest=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),cwd:string$2(),mcpServers:array(zMcpServer)}),zPermissionOptionId=string$2(),zPermissionOptionKind=union([literal("allow_once"),literal("allow_always"),literal("reject_once"),literal("reject_always")]),zPermissionOption=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),kind:zPermissionOptionKind,name:string$2(),optionId:zPermissionOptionId}),zPlanEntryPriority=union([literal("high"),literal("medium"),literal("low")]),zPlanEntryStatus=union([literal("pending"),literal("in_progress"),literal("completed")]),zPlanEntry=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),content:string$2(),priority:zPlanEntryPriority,status:zPlanEntryStatus}),zPlan=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),entries:array(zPlanEntry)}),zPromptCapabilities=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),audio:boolean$1().optional().default(!1),embeddedContext:boolean$1().optional().default(!1),image:boolean$1().optional().default(!1)}),zProtocolVersion=number$2().int().gte(0).lte(65535),zInitializeRequest=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),clientCapabilities:zClientCapabilities.optional().default({fs:{readTextFile:!1,writeTextFile:!1},terminal:!1}),clientInfo:union([zImplementation,_null()]).optional(),protocolVersion:zProtocolVersion}),zReadTextFileResponse=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),content:string$2()}),zReleaseTerminalResponse=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional()}),zRequestId=union([_null(),bigint(),string$2()]),zRole=_enum(["assistant","user"]),zAnnotations=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),audience:union([array(zRole),_null()]).optional(),lastModified:union([string$2(),_null()]).optional(),priority:union([number$2(),_null()]).optional()}),zAudioContent=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),annotations:union([zAnnotations,_null()]).optional(),data:string$2(),mimeType:string$2()}),zImageContent=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),annotations:union([zAnnotations,_null()]).optional(),data:string$2(),mimeType:string$2(),uri:union([string$2(),_null()]).optional()}),zResourceLink=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),annotations:union([zAnnotations,_null()]).optional(),description:union([string$2(),_null()]).optional(),mimeType:union([string$2(),_null()]).optional(),name:string$2(),size:union([bigint(),_null()]).optional(),title:union([string$2(),_null()]).optional(),uri:string$2()}),zSelectedPermissionOutcome=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),optionId:zPermissionOptionId}),zRequestPermissionOutcome=union([object({outcome:literal("cancelled")}),zSelectedPermissionOutcome.and(object({outcome:literal("selected")}))]),zRequestPermissionResponse=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),outcome:zRequestPermissionOutcome}),zSessionForkCapabilities=object({_meta:unknown$1().optional()}),zSessionId=string$2(),zCancelNotification=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),sessionId:zSessionId});object({method:string$2(),params:union([union([zCancelNotification,zExtNotification]),_null()]).optional()});const zCreateTerminalRequest=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),args:array(string$2()).optional(),command:string$2(),cwd:union([string$2(),_null()]).optional(),env:array(zEnvVariable).optional(),outputByteLimit:union([number$2().int().gte(0),_null()]).optional(),sessionId:zSessionId}),zForkSessionRequest=object({_meta:unknown$1().optional(),sessionId:zSessionId}),zKillTerminalCommandRequest=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),sessionId:zSessionId,terminalId:string$2()}),zLoadSessionRequest=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),cwd:string$2(),mcpServers:array(zMcpServer),sessionId:zSessionId}),zReadTextFileRequest=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),limit:union([number$2().int().gte(0),_null()]).optional(),line:union([number$2().int().gte(0),_null()]).optional(),path:string$2(),sessionId:zSessionId}),zReleaseTerminalRequest=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),sessionId:zSessionId,terminalId:string$2()}),zSessionInfo=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),cwd:string$2(),sessionId:zSessionId,title:union([string$2(),_null()]).optional(),updatedAt:union([string$2(),_null()]).optional()}),zListSessionsResponse=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),nextCursor:union([string$2(),_null()]).optional(),sessions:array(zSessionInfo)}),zSessionListCapabilities=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional()}),zSessionCapabilities=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),fork:union([zSessionForkCapabilities,_null()]).optional(),list:union([zSessionListCapabilities,_null()]).optional()}),zAgentCapabilities=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),loadSession:boolean$1().optional().default(!1),mcpCapabilities:zMcpCapabilities.optional().default({http:!1,sse:!1}),promptCapabilities:zPromptCapabilities.optional().default({audio:!1,embeddedContext:!1,image:!1}),sessionCapabilities:zSessionCapabilities.optional().default({})}),zInitializeResponse=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),agentCapabilities:zAgentCapabilities.optional().default({loadSession:!1,mcpCapabilities:{http:!1,sse:!1},promptCapabilities:{audio:!1,embeddedContext:!1,image:!1},sessionCapabilities:{}}),agentInfo:union([zImplementation,_null()]).optional(),authMethods:array(zAuthMethod).optional().default([]),protocolVersion:zProtocolVersion}),zSessionModeId=string$2(),zCurrentModeUpdate=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),currentModeId:zSessionModeId}),zSessionMode=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),description:union([string$2(),_null()]).optional(),id:zSessionModeId,name:string$2()}),zSessionModeState=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),availableModes:array(zSessionMode),currentModeId:zSessionModeId}),zSessionModelState=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),availableModels:array(zModelInfo),currentModelId:zModelId}),zForkSessionResponse=object({_meta:unknown$1().optional(),models:union([zSessionModelState,_null()]).optional(),modes:union([zSessionModeState,_null()]).optional(),sessionId:zSessionId}),zLoadSessionResponse=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),models:union([zSessionModelState,_null()]).optional(),modes:union([zSessionModeState,_null()]).optional()}),zNewSessionResponse=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),models:union([zSessionModelState,_null()]).optional(),modes:union([zSessionModeState,_null()]).optional(),sessionId:zSessionId}),zSetSessionModeRequest=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),modeId:zSessionModeId,sessionId:zSessionId}),zSetSessionModeResponse=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional()}),zSetSessionModelRequest=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),modelId:zModelId,sessionId:zSessionId}),zSetSessionModelResponse=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional()}),zStopReason=union([literal("end_turn"),literal("max_tokens"),literal("max_turn_requests"),literal("refusal"),literal("cancelled")]),zPromptResponse=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),stopReason:zStopReason});union([object({id:zRequestId,result:union([zInitializeResponse,zAuthenticateResponse,zNewSessionResponse,zLoadSessionResponse,zListSessionsResponse,zForkSessionResponse,zSetSessionModeResponse,zPromptResponse,zSetSessionModelResponse,zExtResponse])}),object({error:zError,id:zRequestId})]);const zTerminal=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),terminalId:string$2()}),zTerminalExitStatus=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),exitCode:union([number$2().int().gte(0),_null()]).optional(),signal:union([string$2(),_null()]).optional()}),zTerminalOutputRequest=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),sessionId:zSessionId,terminalId:string$2()}),zTerminalOutputResponse=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),exitStatus:union([zTerminalExitStatus,_null()]).optional(),output:string$2(),truncated:boolean$1()}),zTextContent=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),annotations:union([zAnnotations,_null()]).optional(),text:string$2()}),zTextResourceContents=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),mimeType:union([string$2(),_null()]).optional(),text:string$2(),uri:string$2()}),zEmbeddedResourceResource=union([zTextResourceContents,zBlobResourceContents]),zEmbeddedResource=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),annotations:union([zAnnotations,_null()]).optional(),resource:zEmbeddedResourceResource}),zContentBlock=union([zTextContent.and(object({type:literal("text")})),zImageContent.and(object({type:literal("image")})),zAudioContent.and(object({type:literal("audio")})),zResourceLink.and(object({type:literal("resource_link")})),zEmbeddedResource.and(object({type:literal("resource")}))]),zContent=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),content:zContentBlock}),zContentChunk=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),content:zContentBlock}),zPromptRequest=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),prompt:array(zContentBlock),sessionId:zSessionId});object({id:zRequestId,method:string$2(),params:union([union([zInitializeRequest,zAuthenticateRequest,zNewSessionRequest,zLoadSessionRequest,zListSessionsRequest,zForkSessionRequest,zSetSessionModeRequest,zPromptRequest,zSetSessionModelRequest,zExtRequest]),_null()]).optional()});const zToolCallContent=union([zContent.and(object({type:literal("content")})),zDiff.and(object({type:literal("diff")})),zTerminal.and(object({type:literal("terminal")}))]),zToolCallId=string$2(),zToolCallLocation=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),line:union([number$2().int().gte(0),_null()]).optional(),path:string$2()}),zToolCallStatus=union([literal("pending"),literal("in_progress"),literal("completed"),literal("failed")]),zToolKind=union([literal("read"),literal("edit"),literal("delete"),literal("move"),literal("search"),literal("execute"),literal("think"),literal("fetch"),literal("switch_mode"),literal("other")]),zToolCall=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),content:array(zToolCallContent).optional(),kind:zToolKind.optional(),locations:array(zToolCallLocation).optional(),rawInput:unknown$1().optional(),rawOutput:unknown$1().optional(),status:zToolCallStatus.optional(),title:string$2(),toolCallId:zToolCallId}),zToolCallUpdate=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),content:union([array(zToolCallContent),_null()]).optional(),kind:union([zToolKind,_null()]).optional(),locations:union([array(zToolCallLocation),_null()]).optional(),rawInput:unknown$1().optional(),rawOutput:unknown$1().optional(),status:union([zToolCallStatus,_null()]).optional(),title:union([string$2(),_null()]).optional(),toolCallId:zToolCallId}),zRequestPermissionRequest=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),options:array(zPermissionOption),sessionId:zSessionId,toolCall:zToolCallUpdate}),zUnstructuredCommandInput=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),hint:string$2()}),zAvailableCommandInput=zUnstructuredCommandInput,zAvailableCommand=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),description:string$2(),input:union([zAvailableCommandInput,_null()]).optional(),name:string$2()}),zAvailableCommandsUpdate=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),availableCommands:array(zAvailableCommand)}),zSessionUpdate=union([zContentChunk.and(object({sessionUpdate:literal("user_message_chunk")})),zContentChunk.and(object({sessionUpdate:literal("agent_message_chunk")})),zContentChunk.and(object({sessionUpdate:literal("agent_thought_chunk")})),zToolCall.and(object({sessionUpdate:literal("tool_call")})),zToolCallUpdate.and(object({sessionUpdate:literal("tool_call_update")})),zPlan.and(object({sessionUpdate:literal("plan")})),zAvailableCommandsUpdate.and(object({sessionUpdate:literal("available_commands_update")})),zCurrentModeUpdate.and(object({sessionUpdate:literal("current_mode_update")}))]),zSessionNotification=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),sessionId:zSessionId,update:zSessionUpdate});object({method:string$2(),params:union([union([zSessionNotification,zExtNotification]),_null()]).optional()});const zWaitForTerminalExitRequest=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),sessionId:zSessionId,terminalId:string$2()}),zWaitForTerminalExitResponse=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),exitCode:union([number$2().int().gte(0),_null()]).optional(),signal:union([string$2(),_null()]).optional()}),zWriteTextFileRequest=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),content:string$2(),path:string$2(),sessionId:zSessionId});object({id:zRequestId,method:string$2(),params:union([union([zWriteTextFileRequest,zReadTextFileRequest,zRequestPermissionRequest,zCreateTerminalRequest,zTerminalOutputRequest,zReleaseTerminalRequest,zWaitForTerminalExitRequest,zKillTerminalCommandRequest,zExtRequest]),_null()]).optional()});const zWriteTextFileResponse=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional()});union([object({id:zRequestId,result:union([zWriteTextFileResponse,zReadTextFileResponse,zRequestPermissionResponse,zCreateTerminalResponse,zTerminalOutputResponse,zReleaseTerminalResponse,zWaitForTerminalExitResponse,zKillTerminalCommandResponse,zExtResponse])}),object({error:zError,id:zRequestId})]);class ACPAdapter extends BaseProtocolAdapter{protocol="acp";protocolTransport="websocket";acpConfig;ws=null;session=null;agent=null;streamingContent="";streamingMessageId=null;pendingPermission=null;pendingRequests=new Map;constructor(lo){super(lo),this.acpConfig=lo}getSession(){return this.session}getAgent(){return this.agent}getPendingPermission(){return this.pendingPermission}async connect(){if(this.ws?.readyState!==WebSocket.OPEN)return this.setConnectionState("connecting"),new Promise((lo,$u)=>{try{const Ru=this.acpConfig.wsUrl||this.config.baseUrl,Iu=this.config.agentId,Pu=Iu?`${Ru}/${Iu}`:Ru;this.ws=new WebSocket(Pu),this.ws.onopen=async()=>{this.reconnectAttempts=0;try{const Ou=await this.sendRequest("initialize",{protocolVersion:PROTOCOL_VERSION,clientCapabilities:this.acpConfig.clientCapabilities||{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1}});Ou.agentCapabilities?.agent&&(this.agent=Ou.agentCapabilities.agent);const Mu=await this.sendRequest(AGENT_METHODS.session_new,{});Mu.sessionId?this.session={sessionId:Mu.sessionId,agentId:this.config.agentId||"",createdAt:new Date().toISOString(),status:"active"}:Ou.session_id&&(this.session={sessionId:Ou.session_id,agentId:this.config.agentId||"",createdAt:new Date().toISOString(),status:"active"}),this.setConnectionState("connected"),lo()}catch(Ou){console.error("[ACPAdapter] Initialization error:",Ou),this.setConnectionState("connected"),lo()}},this.ws.onmessage=Ou=>{this.handleMessage(Ou)},this.ws.onerror=Ou=>{console.error("[ACPAdapter] WebSocket error:",Ou),this.emit({type:"error",error:new Error("WebSocket error"),timestamp:new Date})},this.ws.onclose=()=>{this.ws=null,this.setConnectionState("disconnected"),this.handleReconnect()}}catch(Ru){this.setConnectionState("error"),this.emit({type:"error",error:Ru instanceof Error?Ru:new Error(String(Ru)),timestamp:new Date}),$u(Ru)}})}disconnect(){this.session&&this.ws&&this.ws.readyState===WebSocket.OPEN&&this.terminateSession(this.session.sessionId).catch(lo=>{console.warn("[ACPAdapter] Failed to terminate session:",lo)});for(const[,{reject:lo}]of this.pendingRequests)lo(new Error("Connection closed"));this.pendingRequests.clear(),this.ws&&(this.ws.close(),this.ws=null),this.session=null,this.agent=null,this.pendingPermission=null,this.setConnectionState("disconnected")}async terminateSession(lo){if(!this.ws||this.ws.readyState!==WebSocket.OPEN){console.warn("[ACPAdapter] Cannot terminate: WebSocket not connected");return}try{const $u=lo||this.session?.sessionId;if(!$u){console.warn("[ACPAdapter] Cannot terminate: No session ID");return}const Ru={jsonrpc:"2.0",method:"session/cancel",params:{sessionId:$u}};this.ws.send(JSON.stringify(Ru)),console.debug("[ACPAdapter] Sent session/cancel for:",$u)}catch($u){console.debug("[ACPAdapter] Terminate request error:",$u)}}async sendMessage(lo,$u){if(!this.session)throw new Error("No active session");this.streamingContent="",this.streamingMessageId=generateMessageId();try{const Ru=typeof lo.content=="string"?lo.content:lo.content.filter(Pu=>Pu.type==="text").map(Pu=>Pu.text||"").join("");$u?.model&&console.log("[ACPAdapter] Sending with model:",$u.model),$u?.identities&&$u.identities.length>0&&console.log("[ACPAdapter] Sending with identities:",$u.identities.map(Pu=>Pu.provider));const Iu={};$u?.model&&(Iu.model=$u.model),$u?.identities&&$u.identities.length>0&&(Iu.identities=$u.identities),await this.sendRequest(AGENT_METHODS.session_prompt,{sessionId:this.session.sessionId,prompt:[{type:"text",text:Ru}],...Object.keys(Iu).length>0&&{metadata:Iu}})}catch(Ru){throw this.emit({type:"error",error:Ru instanceof Error?Ru:new Error(String(Ru)),timestamp:new Date}),Ru}}async sendToolResult(lo,$u){if(!this.session)throw new Error("No active session");this.emit({type:"tool-result",toolResult:$u,timestamp:new Date}),this.pendingPermission&&this.grantPermission()}grantPermission(lo){if(this.pendingPermission){const $u=lo||this.pendingPermission.options[0]?.optionId||"allow";this.sendResponse(this.pendingPermission.requestId,{outcome:{outcome:"selected",optionId:$u}}),this.pendingPermission=null}}denyPermission(){this.pendingPermission&&(this.sendResponse(this.pendingPermission.requestId,{outcome:{outcome:"cancelled"}}),this.pendingPermission=null)}supportsFeature(lo){return["streaming","tools","permissions","session-management","bidirectional"].includes(lo)}generateId(){return`${Date.now()}-${Math.random().toString(36).substring(2,9)}`}async sendRequest(lo,$u={}){if(!this.ws||this.ws.readyState!==WebSocket.OPEN)throw new Error("Not connected to agent");const Ru=this.generateId(),Iu={jsonrpc:"2.0",id:Ru,method:lo,params:$u};return new Promise((Pu,Ou)=>{this.pendingRequests.set(Ru,{resolve:Pu,reject:Ou}),this.ws&&this.ws.send(JSON.stringify(Iu)),setTimeout(()=>{this.pendingRequests.has(Ru)&&(this.pendingRequests.delete(Ru),Ou(new Error("Request timeout")))},this.config.timeout||3e4)})}sendResponse(lo,$u){if(!this.ws||this.ws.readyState!==WebSocket.OPEN){console.error("[ACPAdapter] Cannot send response: not connected");return}const Ru={jsonrpc:"2.0",id:lo,result:$u};this.ws.send(JSON.stringify(Ru))}handleMessage(lo){try{const $u=JSON.parse(lo.data);if($u.id&&this.pendingRequests.has($u.id)){const Ru=this.pendingRequests.get($u.id);if(!Ru)return;const{resolve:Iu,reject:Pu}=Ru;this.pendingRequests.delete($u.id),$u.error?Pu(new Error($u.error.message)):Iu($u.result),$u.result&&typeof $u.result=="object"&&"stopReason"in $u.result&&this.handleCompletion($u.result);return}if($u.method==="session/update"){this.handleSessionUpdate($u.params||{});return}if($u.method===CLIENT_METHODS.session_request_permission&&$u.id){this.handlePermissionRequest($u.id,$u.params);return}$u.result&&typeof $u.result=="object"&&"stopReason"in $u.result&&this.handleCompletion($u.result)}catch($u){console.error("[ACPAdapter] Failed to parse message:",$u)}}handleSessionUpdate(lo){const $u=lo.update;if(!$u)return;const Ru=$u.sessionUpdate,Iu=Pu=>Pu&&typeof Pu=="object"&&Pu.type==="text"?String(Pu.text??""):"";if(Ru==="agent_message_chunk"){const Pu=Iu($u.content);if(Pu){this.streamingContent+=Pu;const Ou=createAssistantMessage(this.streamingContent);this.streamingMessageId&&(Ou.id=this.streamingMessageId),this.emit({type:"message",message:Ou,timestamp:new Date})}}if(Ru==="tool_call"){const Pu=$u;this.emit({type:"tool-call",toolCall:{toolCallId:Pu.toolCallId||generateMessageId(),toolName:Pu.title||"",args:Pu.rawInput||{}},timestamp:new Date})}if(Ru==="tool_call_update"){const Pu=$u;(Pu.status==="completed"||Pu.status==="failed")&&this.emit({type:"tool-result",toolResult:{toolCallId:Pu.toolCallId??"",success:Pu.status==="completed",result:Pu.rawOutput},timestamp:new Date})}if(Ru==="agent_thought_chunk"){const Pu=Iu($u.content);Pu&&this.emit({type:"activity",activity:{type:"thought",data:Pu},timestamp:new Date})}}handlePermissionRequest(lo,$u){this.pendingPermission={requestId:lo,sessionId:$u.sessionId,toolCall:$u.toolCall,options:$u.options},this.emit({type:"tool-call",toolCall:{toolCallId:$u.toolCall.toolCallId,toolName:$u.toolCall.title||"",args:$u.toolCall.rawInput||{}},timestamp:new Date}),this.acpConfig.onPermissionRequest?.(this.pendingPermission)}handleCompletion(lo){if(this.streamingContent){const $u=createAssistantMessage(this.streamingContent);$u.id=this.streamingMessageId||generateMessageId(),this.emit({type:"message",message:$u,timestamp:new Date}),this.streamingContent="",this.streamingMessageId=null}this.emit({type:"activity",activity:{type:"completed",data:{stopReason:lo.stopReason}},timestamp:new Date})}}const internalQueryClient=new QueryClient({defaultOptions:{queries:{staleTime:300*1e3,refetchOnWindowFocus:!1}}});function isToolCallMessage(Au){return"type"in Au&&Au.type==="tool-call"}function getMessageText(Au){const lo=typeof Au.content=="string"?Au.content:Au.content.filter($u=>$u.type==="text").map($u=>$u.text).join("");return Au.role==="assistant"?sanitizeAssistantContent(lo):lo}function formatTokenCount(Au){return Au>=1e6?`${(Au/1e6).toFixed(1)}M`:Au>=1e3?`${(Au/1e3).toFixed(1)}K`:Au.toString()}function getApiBaseFromConfig(Au){return Au.replace(/\/(config|configure)\/?$/,"")}function createProtocolAdapter(Au){const lo={protocol:Au.type,baseUrl:Au.endpoint,authToken:Au.authToken,agentId:Au.agentId,...Au.options};switch(Au.type){case"ag-ui":if(Au.ownRoutesOnly&&!Au.appSessions)throw new Error("A chat whose runtime answers only the application’s own routes is an application’s: it needs its sessions (appSessions).");return new AGUIAdapter({...lo,...Au.appSessions?{appSessions:Au.appSessions}:{}});case"a2a":return new A2AAdapter(lo);case"vercel-ai":return new VercelAIAdapter(lo);case"acp":return new ACPAdapter(lo);case"browser-vercel-ai":return new BrowserAgentAdapter(lo);default:return console.warn(`[ChatBase] Unknown protocol type: ${Au.type}`),null}}const PAP_SIGN_IN_WORDS={title:Au=>`Sign in at ${Au}`,direct:"Open the company’s page through Datalayer, sign in there, and this conversation goes on once you are back.",device:"Open the company’s page and enter this code there.",mediatedTitle:Au=>`Sign in through ${Au}`,mediated:"Open this page: it names the company and asks what the company needs. Type it there, never in this conversation.",sentTo:Au=>`The company sent a code to ${Au}.`,needs:Au=>`It needs: ${Au.join(", ")}.`,open:Au=>`Open ${Au}`,code:"Your code",copy:"Copy the code",copied:"Copied",until:Au=>`Until ${new Date(Au).toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"})}.`,checkAgain:"I have signed in: check again",tellMe:"Tell me when you are done.",checkMessage:Au=>`I have signed in at ${Au}. Please check again.`,refused:"This sign-in link cannot be opened safely, so it is not shown.",qr:Au=>`A code to scan to open ${Au} on your phone`,returned:{signed_in:Au=>`Signed in at ${Au}: checking again.`,denied:Au=>`You did not sign in at ${Au}: ask again when you want to.`,refused:Au=>`That sign-in at ${Au} was refused, and nothing was kept: start it again here.`}},PAP_SIGN_IN_CHANNEL="datalayer-pap-sign-in",SCOPE=/^[\x21\x23-\x5B\x5D-\x7E]{1,128}$/,DOMAIN=/^(?=.{1,253}$)([a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/;function signInReturnOf(Au,lo){if(!Au||typeof Au!="object"||Array.isArray(Au))return null;const $u=Au,Ru=$u.outcome;return $u.company===lo&&(Ru==="signed_in"||Ru==="denied"||Ru==="refused")?Ru:null}const PAP_SIGN_IN_TOOL=/(^|[_.:\-/])pa(?:p|ct)_sign_in$/,isPapSignInTool=Au=>PAP_SIGN_IN_TOOL.test(Au);function unwrapped(Au){let lo=Au;if(typeof lo=="string")try{lo=JSON.parse(lo)}catch{return null}if(!lo||typeof lo!="object"||Array.isArray(lo))return null;const $u=lo;if($u.structuredContent&&typeof $u.structuredContent=="object")return unwrapped($u.structuredContent);if(Array.isArray($u.content)){const Ru=$u.content.find(Iu=>Iu?.type==="text"&&typeof Iu.text=="string");return Ru?unwrapped(Ru.text):null}return $u.result&&typeof $u.result=="object"&&!("status"in $u)?unwrapped($u.result):$u}function safeSignInUrl(Au){if(typeof Au!="string")return null;try{const lo=new URL(Au);return lo.protocol==="https:"&&lo.hostname?lo:null}catch{return null}}function readPapSignIn(Au){const lo=unwrapped(Au);if(!lo||lo.status!=="waiting_for_the_person"||lo.mode!=="direct"&&lo.mode!=="device"&&lo.mode!=="mediated")return null;const $u=safeSignInUrl(lo.open);if(!$u)return{refused:PAP_SIGN_IN_WORDS.refused};if(lo.mode==="device"&&(typeof lo.code!="string"||!lo.code))return null;const Ru=typeof lo.company=="string"&&DOMAIN.test(lo.company)?lo.company:"",Iu=Array.isArray(lo.needs)?lo.needs.filter(Pu=>typeof Pu=="string"&&SCOPE.test(Pu)):[];return{mode:lo.mode,open:$u.toString(),host:$u.hostname,...Ru?{company:Ru}:{},...typeof lo.code=="string"&&lo.code?{code:lo.code}:{},...lo.mode==="mediated"&&typeof lo.sent_to=="string"&&lo.sent_to?{sentTo:lo.sent_to}:{},...typeof lo.expires_at=="string"&&lo.expires_at?{expiresAt:lo.expires_at}:{},...Iu.length>0?{needs:Iu}:{}}}const PAP_SIGN_IN_TYPE$1="application/vnd.datalayer.pap.sign-in+json",PAP_CONFIRM_TYPE="application/vnd.datalayer.pap.confirm+json",PAP_OUTCOME_TYPE="application/vnd.datalayer.pap.outcome+json",PAP_REPLIES_TYPE="application/vnd.datalayer.pap.replies+json",SHIELD_DIFF_TYPE="application/vnd.datalayer.shield.diff+json",SHIELD_TERMINAL_TYPE="application/vnd.datalayer.shield.terminal+json",DISPLAY_META_KEY="reactor.ui/display",record$1=Au=>Au&&typeof Au=="object"&&!Array.isArray(Au)?Au:null,text$h=Au=>typeof Au=="string"?Au:"",words=Au=>text$h(Au).trim(),count=Au=>typeof Au=="number"&&Number.isInteger(Au)&&Au>=1?Au:0,ACTIONS=["read","write","send","buy","delete","publish"],OUTCOMES=["in_progress","succeeded","failed","cancelled","expired"],STATUSES=["working","idle","queued","closed"],who=Au=>Au==="agent"||Au==="human"?Au:null;function protocolDisplayOf(Au){const lo=record$1(Au);if(!lo||!text$h(lo.type))return null;const $u=text$h(lo.id),Ru=record$1(lo.data)??{},Iu={kind:"unknown",id:$u,type:text$h(lo.type),version:typeof lo.version=="number"?lo.version:0,text:text$h(lo.text)};switch(lo.type){case PAP_SIGN_IN_TYPE$1:{const Pu=readPapSignIn({status:"waiting_for_the_person",...Ru});return Pu?"refused"in Pu?{kind:"sign-in-refused",id:$u,why:Pu.refused}:{kind:"sign-in",id:$u,...Pu}:Iu}case PAP_CONFIRM_TYPE:{const Pu=words(Ru.company),Ou=text$h(Ru.summary),Mu=words(Ru.operation_ref),Du=count(Ru.revision),Lu=record$1(Ru.terms),Bu=record$1(Ru.was),ju=Bu?count(Bu.revision):0;if(!Pu||!Ou.trim()||!Mu||!Du||!Lu||!$u.endsWith("-confirm")||Bu&&(!ju||ju>=Du))return Iu;const Fu=Ru.does===null||Ru.does===void 0?null:ACTIONS.find(Uu=>Uu===Ru.does);if(Fu===void 0)return Iu;const zu=record$1(Ru.session);return{kind:"confirm",id:$u,approvalId:$u.slice(0,-8),company:Pu,summary:Ou,terms:Lu,operationRef:Mu,revision:Du,does:Fu,signedIn:zu&&typeof zu.signed_in=="boolean"?zu.signed_in:null,expiresAt:text$h(Ru.expires_at),was:Bu?{revision:ju,terms:record$1(Bu.terms)??{}}:null,onlyThePerson:Ru.only_the_person===!0}}case PAP_OUTCOME_TYPE:{const Pu=OUTCOMES.find(Lu=>Lu===Ru.state),Ou=words(Ru.company),Mu=text$h(Ru.summary),Du=text$h(Ru.result);return!Pu||!Ou||!Mu.trim()||!words(Ru.operation_ref)||!count(Ru.revision)||Pu==="in_progress"!=!Du.trim()?Iu:{kind:"outcome",id:$u,company:Ou,summary:Mu,operationRef:words(Ru.operation_ref),revision:count(Ru.revision),state:Pu,result:Du,approvedBy:Ru.approved_by==="user"||Ru.approved_by==="standing_permission"?Ru.approved_by:null}}case PAP_REPLIES_TYPE:{const Pu=words(Ru.company),Ou=text$h(Ru.conversation),Mu=Array.isArray(Ru.replies)?Ru.replies.map(record$1).map(Du=>({sender:who(Du?.sender),text:text$h(Du?.text)})):[];return!Pu||!/^[A-Za-z0-9_-]{1,256}$/.test(Ou)||!Mu.length||Mu.some(Du=>!Du.sender||!Du.text.trim())?Iu:{kind:"replies",id:$u,company:Pu,conversation:Ou,replies:Mu,status:STATUSES.find(Du=>Du===Ru.status)??null,responder:who(Ru.responder)}}case SHIELD_DIFF_TYPE:{const Pu=words(Ru.path);return!Pu||typeof Ru.new_text!="string"||!(Ru.old_text===null||Ru.old_text===void 0||typeof Ru.old_text=="string")?Iu:{kind:"diff",id:$u,path:Pu,oldText:typeof Ru.old_text=="string"?Ru.old_text:null,newText:Ru.new_text,language:words(Ru.language)||languageOf$1(Pu)}}case SHIELD_TERMINAL_TYPE:{const Pu=words(Ru.terminal_id);if(!Pu)return Iu;const Ou=typeof Ru.exit_code=="number"&&Number.isInteger(Ru.exit_code)?Ru.exit_code:null;return Ru.exit_code!==null&&Ru.exit_code!==void 0&&Ou===null?Iu:{kind:"terminal",id:$u,terminalId:Pu,command:text$h(Ru.command),output:text$h(Ru.output),exitCode:Ou,released:Ru.released===!0}}default:return Iu}}const PAP_HANDOFF_TOOL=/(^|[_.:\-/])pap_handoff$/;function displayOfToolResult(Au,lo,$u=""){const Ru=record$1(lo),Iu=record$1(Ru?._meta)?.[DISPLAY_META_KEY];if(Iu!==void 0)return protocolDisplayOf(Iu);if(isPapSignInTool(Au)){const Pu=readPapSignIn(lo);return Pu?"refused"in Pu?{kind:"sign-in-refused",id:$u,why:Pu.refused}:{kind:"sign-in",id:$u,...Pu}:null}if(PAP_HANDOFF_TOOL.test(Au)&&Ru){const Pu=text$h(Ru.status);return Pu?{kind:"handoff",id:$u,handed:Pu!=="closed"&&Pu!=="direct_conversation_open",responder:who(Ru.responder),note:text$h(Ru.note)}:null}return null}function displayLine(Au){switch(Au.kind){case"sign-in":return Au.mode==="mediated"?`Sign in through ${Au.host}`:`Sign in at ${Au.company||Au.host}`;case"sign-in-refused":return Au.why;case"confirm":return`${Au.company} asks you to confirm: ${Au.summary} (version ${Au.revision})`;case"outcome":return Au.state==="in_progress"?`Still in progress at ${Au.company}: ${Au.summary}`:`${OUTCOME_LEADS[Au.state]} ${Au.company}: ${Au.result}`;case"replies":return`${Au.company} answered${Au.responder==="human"?": one of its people is answering":""}`;case"handoff":return Au.handed?`Handed to ${Au.responder==="human"?"one of the company’s people":"the company"}`:Au.note||"Nothing was handed over.";case"diff":{const lo=countLines(Au.newText);return Au.oldText===null?`Wrote ${Au.path} (${lo} lines)`:`Changed ${Au.path} (+${lo} −${countLines(Au.oldText)} lines)`}case"terminal":{const lo=Au.command?`Ran \`${Au.command}\``:`Terminal ${Au.terminalId}`;return Au.exitCode===null?`${lo}: running`:`${lo}: exit ${Au.exitCode}`}case"unknown":return Au.text||`A display this app cannot draw (${Au.type})`}}const OUTCOME_LEADS={succeeded:"Done at",failed:"Failed at",cancelled:"Cancelled at",expired:"Expired at"},countLines=Au=>Au===""?0:Au.split(`
2195
2195
  `).length-(Au.endsWith(`
2196
2196
  `)?1:0),LANGUAGES={py:"python",pyi:"python",ts:"typescript",tsx:"tsx",js:"javascript",jsx:"jsx",mjs:"javascript",json:"json",md:"markdown",mdx:"markdown",yaml:"yaml",yml:"yaml",toml:"toml",sh:"bash",bash:"bash",css:"css",scss:"scss",html:"html",xml:"xml",sql:"sql",rs:"rust",go:"go",java:"java",c:"c",h:"c",cpp:"cpp",rb:"ruby",ipynb:"json",txt:"text"};function languageOf$1(Au){const lo=Au.split("/").pop()??"";if(lo==="Dockerfile"||lo==="Makefile")return lo.toLowerCase();const $u=lo.lastIndexOf(".");return $u>0?LANGUAGES[lo.slice($u+1).toLowerCase()]??"text":"text"}const DIFF_LINES_LIMIT=2e3,lines=Au=>Au===""?[]:Au.replace(/\n$/,"").split(`
2197
- `);function unifiedDiffLines(Au,lo){const $u=Au===null?[]:lines(Au),Ru=lines(lo);if($u.length>DIFF_LINES_LIMIT||Ru.length>DIFF_LINES_LIMIT)return[...$u.map(Du=>({kind:"remove",text:Du})),...Ru.map(Du=>({kind:"add",text:Du}))];const Iu=[];for(let Du=0;Du<=$u.length;Du++)Iu.push(new Uint32Array(Ru.length+1));for(let Du=$u.length-1;Du>=0;Du--)for(let Lu=Ru.length-1;Lu>=0;Lu--)Iu[Du][Lu]=$u[Du]===Ru[Lu]?Iu[Du+1][Lu+1]+1:Math.max(Iu[Du+1][Lu],Iu[Du][Lu+1]);const Pu=[];let Ou=0,Mu=0;for(;Ou<$u.length&&Mu<Ru.length;)$u[Ou]===Ru[Mu]?(Pu.push({kind:"context",text:$u[Ou]}),Ou++,Mu++):Iu[Ou+1][Mu]>=Iu[Ou][Mu+1]?(Pu.push({kind:"remove",text:$u[Ou]}),Ou++):(Pu.push({kind:"add",text:Ru[Mu]}),Mu++);for(;Ou<$u.length;)Pu.push({kind:"remove",text:$u[Ou++]});for(;Mu<Ru.length;)Pu.push({kind:"add",text:Ru[Mu++]});return Pu}const THREAD_WORDS={opening:"Opening your conversation…",notOpened:Au=>`Your conversation could not be opened, so this is a new one: ${Au}`};function messagesOfThread(Au){if(!Array.isArray(Au))return[];const lo=[];for(const $u of Au){if(!$u||typeof $u!="object")continue;const{id:Ru,role:Iu,content:Pu,activityType:Ou}=$u;if(Iu==="activity"&&Ou===REACTOR_UI_NAME)throw new Error(`Activity ${String(Ru)}: what a message showed comes on the ui socket (REACTOR_UI RU-W)`);(Iu==="user"||Iu==="assistant")&&typeof Ru=="string"&&typeof Pu=="string"&&Pu.trim()&&lo.push({id:Ru,role:Iu,content:Iu==="user"?askedOf(Pu):Pu,createdAt:new Date})}return lo}function snapshotOfStream(Au){let lo;for(const $u of eventsOfStream(Au))$u.type==="MESSAGES_SNAPSHOT"&&Array.isArray($u.messages)&&(lo=$u.messages);return lo}async function detailOf(Au){try{const lo=await Au.json();if(typeof lo.detail=="string"&&lo.detail)return lo.detail}catch{}return`${Au.status}`}async function openThread({agentBaseUrl:Au,agentId:lo,uid:$u,token:Ru,fetcher:Iu=fetch}){const Pu=`${Au.replace(/\/+$/,"")}/api/v1/apps/sessions/${encodeURIComponent($u)}`,Ou=Ru?{Authorization:`Bearer ${Ru}`}:{},Mu=await Iu(`${Pu}/messages`,{headers:Ou});if(Mu.ok){const Bu=await Mu.json();return messagesOfThread(Bu.messages)}if(Mu.status!==404)throw new Error(await detailOf(Mu));const Du=await Iu(`${Pu}/resume`,{method:"POST",headers:{"Content-Type":"application/json",...Ou},body:JSON.stringify({agent:lo})});if(!Du.ok)throw new Error(await detailOf(Du));const Lu=snapshotOfStream(await Du.text());if(!Lu)throw new Error(`The runtime said nothing of session ${$u}.`);return messagesOfThread(Lu)}const ITEM_LIMIT=400,MESSAGE_TEXT_LIMIT=1e5,TOOL_TEXT_LIMIT=4e3,DIAGNOSTIC_LIMIT=50,DEVICE_LIMITS={items:ITEM_LIMIT,messageText:MESSAGE_TEXT_LIMIT,toolText:TOOL_TEXT_LIMIT,diagnostics:DIAGNOSTIC_LIMIT},BROWSER_LIMITS={items:5e3,messageText:1e6,toolText:1e6,diagnostics:DIAGNOSTIC_LIMIT},CUT_MARK="… (cut: too long to keep on this device)",emptyConversation=(Au=DEVICE_LIMITS)=>{for(const[lo,$u]of Object.entries(Au))if(!Number.isInteger($u)||$u<1)throw new Error(`A conversation's ${lo} bound is ${String($u)}: give a whole number of at least 1.`);return{items:[],running:!1,session:null,asking:null,dropped:0,diagnostics:[],turnRows:0,limits:Au}},text$g=Au=>typeof Au=="string"?Au:"",cut=(Au,lo)=>Au.length>lo?`${Au.slice(0,lo)}${CUT_MARK}`:Au,appended=(Au,lo,$u)=>Au.endsWith(CUT_MARK)?Au:cut(Au+lo,$u),isRecord$1=Au=>!!Au&&typeof Au=="object"&&!Array.isArray(Au);function withoutMeta(Au){if(isRecord$1(Au)&&"_meta"in Au){const{_meta:lo,...$u}=Au;return $u}return Au}function said(Au){return Au==null?"":typeof Au=="string"?Au:JSON.stringify(Au)}function questionOf$1(Au){if(!Au||typeof Au!="object")return null;const lo=Au,$u=lo.kind;if($u!=="text"&&$u!=="choice"&&$u!=="form"&&$u!=="file")throw new Error(`The application asks something no client knows: ${String($u)}.`);const Ru=Pu=>Array.isArray(Pu)?Pu.filter(Ou=>typeof Ou=="string"):[],Iu=lo.schema;return{kind:$u,prompt:text$g(lo.prompt),options:Ru(lo.options),schema:isRecord$1(Iu)?Iu:null,accept:Ru(lo.accept)}}function withItems(Au,lo,$u=0){const Ru=lo.length-Au.limits.items;return{...Au,items:Ru>0?lo.slice(Ru):lo,dropped:Au.dropped+Math.max(0,Ru),turnRows:Au.turnRows+$u}}function changed$1(Au,lo,$u){const Ru=Au.items.findIndex(Pu=>Pu.id===lo);if(Ru<0)return null;const Iu=Au.items.slice();return Iu[Ru]=$u(Iu[Ru]),{...Au,items:Iu}}function noted(Au,lo){const $u={type:lo.type,name:text$g(lo.name)||text$g(lo.activityType)};return{...Au,diagnostics:[...Au.diagnostics,$u].slice(-Au.limits.diagnostics)}}let rowCount=0;const rowId=Au=>`${Au}-${Date.now().toString(36)}-${rowCount+=1}`;function toolRow(Au,lo){return{kind:"tool",id:Au,name:lo,args:"",input:null,status:"running",awaiting:null,result:"",value:void 0,error:"",executionError:"",codeError:null,exitCode:null,display:null}}function withInput(Au,lo,$u){const Ru=JSON.stringify(lo),Iu=Ru.length<=$u;return{...Au,args:cut(Ru,$u),input:Iu?lo:null}}const asksThePerson=Au=>!!Au&&Array.isArray(Au.steps);function withResult(Au,lo,$u,Ru=!1){const Iu=lo.result,Pu=said(withoutMeta(Iu)),Ou=isRecord$1(Iu)?Iu:null,Mu=typeof Ou?.execution_error=="string"?Ou.execution_error:"",Du=isRecord$1(Ou?.code_error)?Ou.code_error:null,Lu=Du?{name:text$g(Du.name)||"Error",value:text$g(Du.value)||"Unknown error",traceback:cut(text$g(Du.traceback),$u)}:null,Bu=Ou&&typeof Ou.exit_code=="number"?Ou.exit_code:null,ju=!lo.success||Mu!==""||Lu!==null||Bu!==null&&Bu!==0||Ou?.execution_ok===!1,Fu=ju||Ru?null:Ou?.pending_approval===!0?"approval":asksThePerson(Au.input)?"person":null;return{...Au,status:ju?"error":Fu?"running":"complete",awaiting:Fu,result:cut(Pu,$u),value:Pu.length<=$u?Iu:void 0,error:lo.error??"",executionError:cut(Mu,$u),codeError:Lu,exitCode:Bu,display:displayOfToolResult(Au.name,Iu,Au.id)}}function rowsOfSnapshot(Au,lo,$u){if(!Array.isArray(Au))throw new Error("A messages snapshot carries no list of messages.");const Ru=[],Iu=new Map;for(const Pu of Au){for(const Ou of messagesOfThread([Pu]))Ru.push({kind:"message",id:Ou.id,role:Ou.role==="user"?"user":"assistant",text:cut(typeof Ou.content=="string"?Ou.content:"",lo.messageText),streaming:!1});if(isRecord$1(Pu)){if(Pu.role==="assistant"&&Pu.toolCalls!==void 0){if(!Array.isArray(Pu.toolCalls))throw new Error(`Message ${String(Pu.id)}'s tool calls are not a list.`);for(const Ou of Pu.toolCalls){const Mu=isRecord$1(Ou)?Ou.function:void 0;if(!isRecord$1(Ou)||typeof Ou.id!="string"||!isRecord$1(Mu))throw new Error(`Message ${String(Pu.id)} holds a tool call without its id and function.`);const Du=text$g(Mu.arguments);let Lu=null;if(Du&&Du.length<=lo.toolText){let Bu;try{Bu=JSON.parse(Du)}catch{Bu=void 0}if(!isRecord$1(Bu))throw new Error(`Tool call ${Ou.id}'s arguments are not a JSON object.`);Lu=Bu}Iu.set(Ou.id,Ru.length),Ru.push({...toolRow(Ou.id,text$g(Mu.name)),args:cut(Du,lo.toolText),input:Du?Lu:{},status:"complete"})}}if(Pu.role==="tool"){const Ou=text$g(Pu.toolCallId),Mu=Iu.get(Ou);if(Mu===void 0){$u.push(Ou||"no call");continue}Ru[Mu]=withResult(Ru[Mu],toolResultOf(Pu.content),lo.toolText,!0)}}}return Ru}function withPrompt(Au,lo,$u){return withItems({...Au,asking:null},[...Au.items,{kind:"message",id:lo,role:"user",text:$u,streaming:!1}])}function withoutItems(Au,lo){const $u=new Set(lo);return{...Au,items:Au.items.filter(Ru=>!$u.has(Ru.id))}}function withTurnEnded(Au,lo){const $u=Au.items.map(Iu=>Iu.kind==="message"&&Iu.streaming?{...Iu,streaming:!1}:Iu.kind==="tool"&&Iu.status==="running"?{...Iu,status:"error",awaiting:null,error:RUN_END_WORDS[lo]}:Iu.kind==="step"&&Iu.status==="running"?{...Iu,status:"complete"}:Iu),Ru={...Au,items:$u,running:!1};return withItems(Ru,[...$u,{kind:"end",id:rowId("end"),end:lo,words:RUN_END_WORDS[lo]}])}function withError(Au,lo){const $u=Au.items.map(Ru=>Ru.kind==="message"&&Ru.streaming?{...Ru,streaming:!1}:Ru.kind==="tool"&&Ru.status==="running"?{...Ru,status:"error",awaiting:null}:Ru.kind==="step"&&Ru.status==="running"?{...Ru,status:"complete"}:Ru);return withItems({...Au,running:!1},[...$u,{kind:"error",id:rowId("error"),text:lo}])}function required(Au,lo){const $u=Au[lo];if(typeof $u!="string"||!$u)throw new Error(`${Au.type} carries no ${lo}.`);return $u}function reduceConversation(Au,lo){const{limits:$u}=Au;switch(lo.type){case"RUN_STARTED":return{...Au,running:!0,asking:null,turnRows:0};case"TEXT_MESSAGE_START":{const Ru=text$g(lo.messageId)||rowId("message");if(Au.items.some(Pu=>Pu.id===Ru))return Au;const Iu=lo.role==="user"?"user":"assistant";return withItems(Au,[...Au.items,{kind:"message",id:Ru,role:Iu,text:"",streaming:!0}],1)}case"TEXT_MESSAGE_CONTENT":case"TEXT_MESSAGE_CHUNK":{const Ru=text$g(lo.delta),Iu=text$g(lo.messageId),Pu=changed$1(Au,Iu,Ou=>Ou.kind==="message"?{...Ou,text:appended(Ou.text,Ru,$u.messageText)}:Ou);return Pu||withItems(Au,[...Au.items,{kind:"message",id:Iu||rowId("message"),role:lo.role==="user"?"user":"assistant",text:cut(Ru,$u.messageText),streaming:lo.type==="TEXT_MESSAGE_CONTENT"}],1)}case"TEXT_MESSAGE_END":return changed$1(Au,text$g(lo.messageId),Ru=>Ru.kind==="message"?{...Ru,streaming:!1}:Ru)??Au;case"MESSAGE_SAID":{const Ru=required(lo,"messageId");if(typeof lo.text!="string")throw new Error(`MESSAGE_SAID of ${Ru} carries no text.`);if(lo.role!=="user"&&lo.role!=="assistant")throw new Error(`MESSAGE_SAID of ${Ru} is said by ${String(lo.role)}: only the person or the assistant speaks here.`);const Iu=lo.role,Pu=cut(lo.text,$u.messageText),Ou=Iu==="assistant"&&lo.streaming!==!1,Mu=Au.items.findIndex(Du=>Du.id===Ru);if(Mu>=0){const Du=Au.items[Mu];if(Du.kind!=="message")throw new Error(`MESSAGE_SAID of ${Ru} names a ${Du.kind} row.`);const Lu=Au.items.slice();return Lu[Mu]={...Du,text:Pu,streaming:Ou},{...Au,items:Lu}}return withItems(Au,[...Au.items,{kind:"message",id:Ru,role:Iu,text:Pu,streaming:Ou}],1)}case"TOOL_CALL_START":{const Ru=text$g(lo.toolCallId)||rowId("tool");return Au.items.some(Iu=>Iu.id===Ru)?Au:withItems(Au,[...Au.items,toolRow(Ru,text$g(lo.toolCallName)||text$g(lo.name))],1)}case"TOOL_CALL_ARGS":return changed$1(Au,text$g(lo.toolCallId),Ru=>Ru.kind==="tool"?{...Ru,args:appended(Ru.args,text$g(lo.delta),$u.toolText)}:Ru)??Au;case"TOOL_CALL_END":return changed$1(Au,text$g(lo.toolCallId),Ru=>{if(Ru.kind!=="tool"||Ru.args.endsWith(CUT_MARK))return Ru;if(!Ru.args)return{...Ru,input:{}};let Iu;try{Iu=JSON.parse(Ru.args)}catch{Iu=void 0}return isRecord$1(Iu)?{...Ru,input:Iu}:{...Ru,status:"error",awaiting:null,error:"Its arguments are not a JSON object."}})??Au;case"TOOL_CALL_SAID":{const Ru=required(lo,"toolCallId"),Iu=required(lo,"toolCallName");if(!isRecord$1(lo.args))throw new Error(`TOOL_CALL_SAID of ${Ru} carries arguments that are not an object.`);const Pu=lo.args,Ou=Au.items.findIndex(Lu=>Lu.id===Ru);if(Ou<0)return withItems(Au,[...Au.items,withInput(toolRow(Ru,Iu),Pu,$u.toolText)],1);const Mu=Au.items[Ou];if(Mu.kind!=="tool")throw new Error(`TOOL_CALL_SAID of ${Ru} names a ${Mu.kind} row.`);const Du=Au.items.slice();return Du[Ou]=withInput(Mu,{...Mu.input??{},...Pu},$u.toolText),{...Au,items:Du}}case"TOOL_CALL_RESULT":{const Ru=toolResultOf(lo.content);return changed$1(Au,text$g(lo.toolCallId),Iu=>Iu.kind==="tool"?withResult(Iu,Ru,$u.toolText):Iu)??noted(Au,lo)}case"TOOL_CALL_DONE":{const Ru=required(lo,"toolCallId");if(typeof lo.success!="boolean")throw new Error(`TOOL_CALL_DONE of ${Ru} does not say whether it succeeded.`);if(lo.error!==void 0&&typeof lo.error!="string")throw new Error(`TOOL_CALL_DONE of ${Ru} says its error in no words.`);const Iu={result:lo.result,success:lo.success,...lo.error!==void 0?{error:lo.error}:{}};return changed$1(Au,Ru,Pu=>Pu.kind==="tool"?withResult(Pu,Iu,$u.toolText,lo.answered===!0):Pu)??noted(Au,lo)}case"STEP_STARTED":{const Ru=text$g(lo.stepName)||text$g(lo.name);return withItems(Au,[...Au.items,{kind:"step",id:rowId("step"),name:Ru,status:"running"}],1)}case"STEP_FINISHED":{const Ru=text$g(lo.stepName)||text$g(lo.name),Iu=Au.items.map((Ou,Mu)=>({item:Ou,index:Mu})).reverse().find(({item:Ou})=>Ou.kind==="step"&&Ou.name===Ru&&Ou.status==="running");if(!Iu)return noted(Au,lo);const Pu=Au.items.slice();return Pu[Iu.index]={...Iu.item,status:"complete"},{...Au,items:Pu}}case"MESSAGES_SNAPSHOT":{const Ru=[],Iu=rowsOfSnapshot(lo.messages,$u,Ru),Pu=withItems({...Au,dropped:0},Iu,1);return Ru.reduce((Ou,Mu)=>noted(Ou,{type:"TOOL_CALL_RESULT",name:`${Mu} (no call)`}),Pu)}case"CUSTOM":{if(lo.name===REACTOR_UI_NAME)return withError(Au,UI_ON_RUN);if(lo.name==="loop.session"&&isRecord$1(lo.value)){const Ru=lo.value;return{...Au,session:Ru,asking:questionOf$1(Ru.asking)??Au.asking}}return noted(Au,lo)}case"ACTIVITY_SNAPSHOT":case"ACTIVITY_DELTA":return lo.activityType===REACTOR_UI_NAME?withError(Au,UI_ON_RUN):noted(Au,lo);case"RUN_FINISHED":{const Ru=isRecord$1(lo.result)?lo.result:{},Iu=questionOf$1(Ru.asking),Pu=Au.items.map(Mu=>Mu.kind==="message"&&Mu.streaming?{...Mu,streaming:!1}:Mu),Ou={...Au,items:Pu,running:!1,asking:Iu};return Iu||Au.turnRows>0?Ou:withItems(Ou,[...Pu,{kind:"end",id:rowId("end"),end:"answered",words:RUN_END_WORDS.answered}])}case"RUN_ERROR":return withError(Au,text$g(lo.message)||"Run failed");default:return noted(Au,lo)}}const emptyChatLayer=()=>({extras:new Map,displays:new Map,speakers:new Map,steps:[]}),toolCardId=Au=>`tool-${Au}`,rowIdOf=Au=>"toolCallId"in Au&&Au.id===toolCardId(Au.toolCallId)?Au.toolCallId:Au.id;function cardStatusOf(Au){return Au.status!=="running"?Au.status:Au.awaiting==="approval"?"inProgress":"executing"}function toolCallOf(Au){return{id:toolCardId(Au.id),type:"tool-call",toolCallId:Au.id,toolName:Au.name,args:Au.input??{},...Au.value!==void 0?{result:Au.value}:Au.result?{result:Au.result}:{},status:cardStatusOf(Au),...Au.error?{error:Au.error}:{},...Au.executionError?{executionError:Au.executionError}:{},...Au.codeError?{codeError:{name:Au.codeError.name,value:Au.codeError.value,...Au.codeError.traceback?{traceback:Au.codeError.traceback}:{}}}:{},...Au.exitCode!==null?{exitCode:Au.exitCode}:{}}}function conversationDrawer(Au){const lo=new Map,$u=(Iu,Pu)=>{const Ou=Pu.extras.get(Iu.id),Mu=Pu.displays.get(Iu.id),Du=Pu.speakers.get(Iu.id),Lu=lo.get(Iu.id);if(Lu&&Lu.row===Iu&&Lu.extras===Ou&&Lu.displays===Mu&&Lu.speaker===Du)return Lu.item;const Bu={...Ou,createdAt:Ou?.createdAt??new Date,id:Iu.id,role:Iu.kind==="message"?Iu.role:"assistant",content:Iu.kind==="message"?Iu.text:Au(Iu.text),...Mu?{displays:Mu}:{},...Du?{speaker:Du}:{}};return lo.set(Iu.id,{row:Iu,extras:Ou,displays:Mu,speaker:Du,item:Bu}),Bu},Ru=Iu=>{const Pu=lo.get(Iu.id);if(Pu&&Pu.row===Iu)return Pu.item;const Ou=toolCallOf(Iu);return lo.set(Iu.id,{row:Iu,item:Ou}),Ou};return(Iu,Pu)=>{const Ou=[],Mu=new Map;for(const Lu of Pu.steps)Mu.set(Lu.after,[...Mu.get(Lu.after)??[],Lu.item]);Ou.push(...Mu.get(null)??[]);const Du=new Set;for(const Lu of Iu.items)Du.add(Lu.id),Lu.kind==="message"||Lu.kind==="error"?Ou.push($u(Lu,Pu)):Lu.kind==="tool"&&Ou.push(Ru(Lu)),Ou.push(...Mu.get(Lu.id)??[]);for(const[Lu,Bu]of Mu)Lu!==null&&!Du.has(Lu)&&Ou.push(...Bu);for(const Lu of lo.keys())Du.has(Lu)||lo.delete(Lu);return Ou}}function isSubagentRunOver(Au){return Au.some(lo=>lo.phase==="end"||lo.phase==="error")}function getMonitoringCacheKey(Au,lo){return`${Au||"__unknown_service__"}::${lo||"__unknown_agent__"}`}function getTransportEndpoint(Au,lo,$u){switch(lo){case"vercel-ai":return`${Au}/api/v1/vercel-ai/${$u}`;case"a2a":return`${Au}/api/v1/a2a/agents/${$u}/`;case"acp":return`${Au}/api/v1/acp/ws/${$u}`;default:return`${Au}/api/v1/ag-ui/${$u}/`}}function toAgentRuntimeBaseUrl(Au){const lo=Au.replace(/\/$/,"");return lo.includes("/api/agent-runtimes")?lo:lo.includes("/api/jupyter-server")?lo.replace("/api/jupyter-server","/api/agent-runtimes"):lo.includes("/jupyter/server/")?lo.replace("/jupyter/server/","/agent-runtimes/"):lo.includes("/jupyter-server/")?lo.replace("/jupyter-server/","/agent-runtimes/"):lo.replace("/jupyter/","/agent-runtimes/")}async function createAgentOnRuntime(Au,lo,$u={}){const{iamStore:Ru}=await __vitePreload(async()=>{const{iamStore:Lu}=await import("./chunks/index-fQxrRXLD.js");return{iamStore:Lu}},[],import.meta.url),Iu=Ru.getState().token||"";if(!$u.protocol&&!$u.agentSpecId)throw new Error("Agent protocol is required. Provide config.protocol from the selected spec/config.");const Pu=$u.protocol||"vercel-ai";if(!$u.model&&!$u.agentSpecId)throw new Error("Agent model is required. Provide config.model from the selected spec/config.");const Ou={name:$u.name||lo,description:$u.description||"AI assistant",agent_library:$u.agentLibrary||"pydantic-ai",transport:Pu,model:$u.model,system_prompt:$u.systemPrompt||"You are a helpful AI assistant."};$u.agentSpecId&&(Ou.agent_spec_id=$u.agentSpecId),typeof $u.enableSkills=="boolean"&&(Ou.enable_skills=$u.enableSkills),Array.isArray($u.backendTools)&&(Ou.backend_tools=$u.backendTools),$u.inferenceProvider&&(Ou.inferenceProvider=$u.inferenceProvider),typeof $u.enableCodemode=="boolean"&&(Ou.enable_codemode=$u.enableCodemode),$u.sandboxVariant&&(Ou.sandbox_variant=$u.sandboxVariant),$u.jupyterSandbox&&(Ou.jupyter_sandbox=$u.jupyterSandbox),$u.createPayload&&typeof $u.createPayload=="object"&&Object.assign(Ou,$u.createPayload);const Mu=await fetch(`${Au}/api/v1/agents`,{method:"POST",headers:{"Content-Type":"application/json",...Iu?{Authorization:`Bearer ${Iu}`}:{}},body:JSON.stringify(Ou)});if(Mu.ok||Mu.status===400||Mu.status===409){const Lu=getTransportEndpoint(Au,Pu,lo);return{agentId:lo,endpoint:Lu,isReady:!0}}const Du=await Mu.json().catch(()=>({}));throw new Error(Du.detail||`Failed to create agent: ${Mu.status}`)}const initialRuntimeState={runtime:null,status:"idle",error:null,isLaunching:!1,historyVersion:0,toolDecisionRequest:null},initialWsState={wsState:"closed",approvals:[],pendingApprovalCount:0,subagentActivity:{},compaction:null,contextSnapshot:null,costUsage:null,mcpStatus:null,codemodeStatus:null,fullContext:null,monitoringCache:{},loadedSkillsByAgentId:{}},initialNotebookState={ephemeralNotebookModels:{},ephemeralDocumentModels:{},editorModeByRuntime:{}},countPendingApprovals=Au=>Au.filter(lo=>lo.status==="pending").length;let _ws=null;const _wsByAgentId=new Map;function _resolveWs(Au){const lo=_wsByAgentId.size>0;if(Au){const $u=_wsByAgentId.get(Au);if($u&&$u.readyState===WebSocket.OPEN)return $u;if(lo)return null}return lo?null:_ws&&_ws.readyState===WebSocket.OPEN?_ws:null}const agentRuntimeStore=createStore$1()(subscribeWithSelector(persist((Au,lo)=>({agents:[],upsertAgent:$u=>{Au(Ru=>{const Iu=Ru.agents.findIndex(Mu=>Mu.id===$u.id),Pu=Date.now();if(Iu>=0){const Mu=[...Ru.agents];return Mu[Iu]={...Mu[Iu],...$u,lastUpdated:Pu},{agents:Mu}}const Ou={name:$u.name||$u.id,description:$u.description||"",status:$u.status||"initializing",lastUpdated:Pu,...$u};return{agents:[...Ru.agents,Ou]}})},getAgentById:$u=>lo().agents.find(Ru=>Ru.id===$u),getAgentByUrl:($u,Ru)=>lo().agents.find(Iu=>Iu.baseUrl===$u&&Iu.protocol===Ru),updateAgentStatus:($u,Ru,Iu=null)=>{Au(Pu=>{const Ou=Pu.agents.findIndex(Mu=>Mu.id===$u);if(Ou>=0){const Mu=[...Pu.agents];return Mu[Ou]={...Mu[Ou],status:Ru,error:Iu,lastUpdated:Date.now()},{agents:Mu}}return{}})},toggleAgentStatus:$u=>{Au(Ru=>{const Iu=Ru.agents.findIndex(Pu=>Pu.id===$u);if(Iu>=0){const Pu=[...Ru.agents],Ou=Pu[Iu].status;return Pu[Iu]={...Pu[Iu],status:Ou==="running"?"paused":"running",lastUpdated:Date.now()},{agents:Pu}}return{}})},deleteAgent:$u=>{Au(Ru=>{const{[$u]:Iu,...Pu}=Ru.loadedSkillsByAgentId;return{agents:Ru.agents.filter(Ou=>Ou.id!==$u),loadedSkillsByAgentId:Pu}})},clearAgents:()=>{Au({agents:[]})},setLoadedSkillsForAgent:($u,Ru)=>{Au(Iu=>({loadedSkillsByAgentId:{...Iu.loadedSkillsByAgentId,[$u]:Ru}}))},getLoadedSkillsForAgent:$u=>lo().loadedSkillsByAgentId[$u]??[],clearLoadedSkillsForAgent:$u=>{Au(Ru=>{if(!($u in Ru.loadedSkillsByAgentId))return{};const{[$u]:Iu,...Pu}=Ru.loadedSkillsByAgentId;return{loadedSkillsByAgentId:Pu}})},setEphemeralNotebookModel:($u,Ru)=>{Au(Iu=>({ephemeralNotebookModels:{...Iu.ephemeralNotebookModels,[$u]:Ru}}))},getEphemeralNotebookModel:$u=>lo().ephemeralNotebookModels[$u]??null,clearEphemeralNotebookModel:$u=>{Au(Ru=>{if(!($u in Ru.ephemeralNotebookModels))return{};const{[$u]:Iu,...Pu}=Ru.ephemeralNotebookModels;return{ephemeralNotebookModels:Pu}})},setEphemeralDocumentModel:($u,Ru)=>{Au(Iu=>({ephemeralDocumentModels:{...Iu.ephemeralDocumentModels,[$u]:Ru}}))},getEphemeralDocumentModel:$u=>lo().ephemeralDocumentModels[$u]??null,clearEphemeralDocumentModel:$u=>{Au(Ru=>{if(!($u in Ru.ephemeralDocumentModels))return{};const{[$u]:Iu,...Pu}=Ru.ephemeralDocumentModels;return{ephemeralDocumentModels:Pu}})},setEditorMode:($u,Ru)=>{$u&&Au(Iu=>({editorModeByRuntime:{...Iu.editorModeByRuntime,[$u]:Ru}}))},getEditorMode:$u=>lo().editorModeByRuntime[$u]??null,...initialRuntimeState,connectAgent:$u=>{const Ru=$u.jupyterBaseUrl||$u.serviceManager?.serverSettings.baseUrl;if(!Ru)throw new Error("connectAgent requires either jupyterBaseUrl or serviceManager");const Iu=toAgentRuntimeBaseUrl(Ru);Au({runtime:{runtimeName:$u.runtimeName,environmentName:$u.environmentName,jupyterBaseUrl:Ru,agentBaseUrl:Iu,serviceManager:$u.serviceManager,status:"ready",kernelId:$u.kernelId},status:"ready",error:null})},launchAgent:async $u=>{Au({status:"launching",error:null,isLaunching:!0});try{const{createRuntime:Ru}=await __vitePreload(async()=>{const{createRuntime:ju}=await Promise.resolve().then(()=>actions);return{createRuntime:ju}},void 0,import.meta.url),{runtimesStore:Iu}=await __vitePreload(async()=>{const{runtimesStore:ju}=await import("./chunks/index-DiBcWu6d.js");return{runtimesStore:ju}},[],import.meta.url);$u.runtimesUrl&&Iu.setState({runtimesUrl:$u.runtimesUrl});const{runtimesUrl:Pu,...Ou}=$u,Mu=await Ru({environmentName:Ou.environmentName,creditsLimit:Ou.creditsLimit,type:Ou.type||"notebook",givenName:Ou.givenName,capabilities:Ou.capabilities,snapshot:Ou.snapshot,appSpec:Ou.appSpec,appUid:Ou.appUid,deploymentUid:Ou.deploymentUid});Au({status:"connecting"});const Du=Mu.ingress,Lu=toAgentRuntimeBaseUrl(Du),Bu={runtimeName:Mu.runtime_name,environmentName:Mu.environment.name,jupyterBaseUrl:Du,agentBaseUrl:Lu,status:"ready"};return Au({runtime:Bu,status:"ready",isLaunching:!1}),Bu}catch(Ru){const Iu=Ru instanceof Error?Ru.message:"Failed to launch runtime";throw Au({status:"error",error:Iu,isLaunching:!1}),Ru}},createAgent:async($u={})=>{const{runtime:Ru}=lo();if(!Ru)throw new Error("No runtime connected. Launch or connect to a runtime first.");try{const Iu=$u.name||Ru.runtimeName,Pu=await createAgentOnRuntime(Ru.agentBaseUrl,Iu,$u);return Au({runtime:{...Ru,agentId:Pu.agentId,endpoint:Pu.endpoint,isReady:Pu.isReady}}),Pu}catch(Iu){const Pu=Iu instanceof Error?Iu.message:"Failed to create agent";throw Au({error:Pu}),Iu}},disconnect:()=>{Au({runtime:null,status:"disconnected",error:null})},clearError:()=>Au({error:null}),setError:$u=>Au({error:$u,status:"error"}),...initialWsState,...initialNotebookState,setWsState:$u=>Au({wsState:$u}),setWs:($u,Ru)=>{_ws=$u,Ru&&($u?_wsByAgentId.set(Ru,$u):_wsByAgentId.delete(Ru))},applySnapshot:$u=>Au(Ru=>({approvals:Ru.approvals,pendingApprovalCount:Ru.pendingApprovalCount,contextSnapshot:$u.contextSnapshot??null,costUsage:$u.costUsage??null,mcpStatus:$u.mcpStatus??null,codemodeStatus:$u.codemodeStatus??null,fullContext:$u.fullContext??null})),appendSubagentEvent:$u=>Au(Ru=>{const Iu=$u.toolCallId??$u.subagentName,Pu=Ru.subagentActivity[Iu]??[];return Pu.some(Ou=>Ou.phase==="error"&&Ou.error===SUBAGENT_STOPPED)?{}:{subagentActivity:{...Ru.subagentActivity,[Iu]:[...Pu,$u]}}}),clearSubagentActivity:()=>Au({subagentActivity:{}}),stopSubagentActivity:()=>Au($u=>{let Ru=!1;const Iu={};for(const[Pu,Ou]of Object.entries($u.subagentActivity)){if(Ou.length===0||isSubagentRunOver(Ou)){Iu[Pu]=Ou;continue}Ru=!0,Iu[Pu]=[...Ou,{subagentName:Ou[0].subagentName,toolCallId:Ou[0].toolCallId??Pu,phase:"error",error:SUBAGENT_STOPPED,transport:Ou[0].transport}]}return Ru?{subagentActivity:Iu}:{}}),requestHistoryReload:()=>Au($u=>({historyVersion:$u.historyVersion+1})),requestToolDecision:$u=>Au(Ru=>({toolDecisionRequest:{seq:(Ru.toolDecisionRequest?.seq??0)+1,...$u}})),setCompaction:$u=>Au({compaction:$u}),upsertApproval:$u=>Au(Ru=>{const Iu=Ru.approvals.filter(Ou=>Ou.id!==$u.id),Pu=[$u,...Iu];return{approvals:Pu,pendingApprovalCount:countPendingApprovals(Pu)}}),removeApproval:$u=>Au(Ru=>{const Iu=Ru.approvals.filter(Pu=>Pu.id!==$u);return{approvals:Iu,pendingApprovalCount:countPendingApprovals(Iu)}}),sendDecision:($u,Ru,Iu,Pu,Ou)=>{const Mu=_resolveWs(Ou);return Mu?(Mu.send(JSON.stringify({type:"tool_approval_decision",approvalId:$u,approved:Ru,...Iu?{note:Iu}:{},...Pu?{toolCallId:Pu}:{}})),!0):!1},requestRefresh:$u=>{const Ru=_resolveWs($u);return Ru?(Ru.send(JSON.stringify({type:"request_snapshot"})),Ru.send(JSON.stringify({type:"request_otel_flush"})),!0):!1},sendRawMessage:($u,Ru)=>{const Iu=_resolveWs(Ru);return Iu?(Iu.send(JSON.stringify($u)),!0):!1},appendLocalTokenTurn:({serviceName:$u,agentId:Ru,timestampMs:Iu,promptTokens:Pu,completionTokens:Ou,totalTokens:Mu})=>{Au(Du=>{const Lu=getMonitoringCacheKey($u,Ru),Bu=Du.monitoringCache[Lu]??{tokenTurns:[],costPoints:[]},ju=[...Bu.tokenTurns],Fu=ju[ju.length-1];if(Fu&&Fu.userMessageTokens===Pu&&Fu.aiMessageTokens===Ou&&Fu.systemPromptTokens===0&&Fu.toolsDescriptionTokens===0&&Fu.toolsUsageTokens===0&&Fu.totalTokens===Mu)return ju[ju.length-1]={...Fu,timestampMs:Math.max(Fu.timestampMs,Iu)},{monitoringCache:{...Du.monitoringCache,[Lu]:{...Bu,tokenTurns:ju}}};const zu=(Fu?.turnNumber??0)+1;return ju.push({turnNumber:zu,timestampMs:Iu,systemPromptTokens:0,toolsDescriptionTokens:0,userMessageTokens:Pu,aiMessageTokens:Ou,toolsUsageTokens:0,totalTokens:Mu}),{monitoringCache:{...Du.monitoringCache,[Lu]:{...Bu,tokenTurns:ju}}}})},mergeTokenTurns:({serviceName:$u,agentId:Ru,turns:Iu})=>{Iu.length!==0&&Au(Pu=>{const Ou=getMonitoringCacheKey($u,Ru),Mu=Pu.monitoringCache[Ou]??{tokenTurns:[],costPoints:[]},Du=new Map;for(const Bu of Mu.tokenTurns)Du.set(Bu.turnNumber,Bu);for(const Bu of Iu)Du.set(Bu.turnNumber,Bu);const Lu=Array.from(Du.values()).sort((Bu,ju)=>Bu.turnNumber-ju.turnNumber);return{monitoringCache:{...Pu.monitoringCache,[Ou]:{...Mu,tokenTurns:Lu}}}})},appendLocalTokenTurnFull:({serviceName:$u,agentId:Ru,timestampMs:Iu,systemPromptTokens:Pu,toolsDescriptionTokens:Ou,userMessageTokens:Mu,aiMessageTokens:Du,toolsUsageTokens:Lu,totalTokens:Bu})=>{Au(ju=>{const Fu=getMonitoringCacheKey($u,Ru),zu=ju.monitoringCache[Fu]??{tokenTurns:[],costPoints:[]},Uu=[...zu.tokenTurns],Hu=Uu[Uu.length-1];if(Hu&&Hu.systemPromptTokens===Pu&&Hu.toolsDescriptionTokens===Ou&&Hu.userMessageTokens===Mu&&Hu.aiMessageTokens===Du&&Hu.toolsUsageTokens===Lu&&Hu.totalTokens===Bu)return Uu[Uu.length-1]={...Hu,timestampMs:Math.max(Hu.timestampMs,Iu)},{monitoringCache:{...ju.monitoringCache,[Fu]:{...zu,tokenTurns:Uu}}};const Vu=(Hu?.turnNumber??0)+1;return Uu.push({turnNumber:Vu,timestampMs:Iu,systemPromptTokens:Pu,toolsDescriptionTokens:Ou,userMessageTokens:Mu,aiMessageTokens:Du,toolsUsageTokens:Lu,totalTokens:Bu}),{monitoringCache:{...ju.monitoringCache,[Fu]:{...zu,tokenTurns:Uu}}}})},upsertLocalCostPoint:({serviceName:$u,agentId:Ru,timestampMs:Iu,cumulativeUsd:Pu})=>{Au(Ou=>{const Mu=getMonitoringCacheKey($u,Ru),Du=Ou.monitoringCache[Mu]??{tokenTurns:[],costPoints:[]},Lu=[...Du.costPoints],Bu=Lu.findIndex(ju=>Math.abs(ju.timestampMs-Iu)<1);return Bu>=0?Lu[Bu]={...Lu[Bu],cumulativeUsd:Math.max(Lu[Bu].cumulativeUsd,Pu)}:Lu.push({timestampMs:Iu,cumulativeUsd:Pu}),Lu.sort((ju,Fu)=>ju.timestampMs-Fu.timestampMs),{monitoringCache:{...Ou.monitoringCache,[Mu]:{...Du,costPoints:Lu}}}})},mergeCostPoints:({serviceName:$u,agentId:Ru,points:Iu})=>{Iu.length!==0&&Au(Pu=>{const Ou=getMonitoringCacheKey($u,Ru),Mu=Pu.monitoringCache[Ou]??{tokenTurns:[],costPoints:[]},Du=new Map;for(const Bu of Mu.costPoints)Du.set(Bu.timestampMs,Bu);for(const Bu of Iu){const ju=Du.get(Bu.timestampMs);ju?Du.set(Bu.timestampMs,{timestampMs:Bu.timestampMs,cumulativeUsd:Math.max(ju.cumulativeUsd,Bu.cumulativeUsd)}):Du.set(Bu.timestampMs,Bu)}const Lu=Array.from(Du.values()).sort((Bu,ju)=>Bu.timestampMs-ju.timestampMs);return{monitoringCache:{...Pu.monitoringCache,[Ou]:{...Mu,costPoints:Lu}}}})},reset:()=>{if(_ws)try{_ws.close(1e3,"reset")}catch{}_ws=null,_wsByAgentId.clear(),Au($u=>({...initialRuntimeState,...initialWsState,ephemeralNotebookModels:$u.ephemeralNotebookModels,ephemeralDocumentModels:$u.ephemeralDocumentModels,editorModeByRuntime:$u.editorModeByRuntime}))},resetWs:()=>{if(_ws)try{_ws.close(1e3,"reset")}catch{}_ws=null,_wsByAgentId.clear(),Au($u=>({...initialWsState,ephemeralNotebookModels:$u.ephemeralNotebookModels,ephemeralDocumentModels:$u.ephemeralDocumentModels,editorModeByRuntime:$u.editorModeByRuntime,subagentActivity:$u.subagentActivity}))}}),{name:"agent-runtimes-storage",storage:createJSONStorage(()=>localStorage),partialize:Au=>({agents:Au.agents.map(lo=>({id:lo.id,name:lo.name,description:lo.description,baseUrl:lo.baseUrl,transport:lo.protocol,status:lo.status,lastUpdated:lo.lastUpdated,documentId:lo.documentId,runtimeId:lo.runtimeId})),monitoringCache:Au.monitoringCache,loadedSkillsByAgentId:Au.loadedSkillsByAgentId,ephemeralNotebookModels:Au.ephemeralNotebookModels,ephemeralDocumentModels:Au.ephemeralDocumentModels,editorModeByRuntime:Au.editorModeByRuntime})})));function useAgentRuntimeStore(Au){return useStore$1(agentRuntimeStore,Au||($u=>$u))}const useAgentRuntimeStoreWithStatics=useAgentRuntimeStore;useAgentRuntimeStoreWithStatics.getState=agentRuntimeStore.getState;useAgentRuntimeStoreWithStatics.subscribe=agentRuntimeStore.subscribe;const useAgentRuntimeConnection=()=>useAgentRuntimeStore(Au=>Au.runtime),useAgentRuntimeStatus=()=>useAgentRuntimeStore(Au=>Au.status),useAgentRuntimeError=()=>useAgentRuntimeStore(Au=>Au.error),useAgentRuntimeIsLaunching=()=>useAgentRuntimeStore(Au=>Au.isLaunching),useAgentRuntimeMcpStatus=()=>useAgentRuntimeStore(Au=>Au.mcpStatus),useAgentRuntimeFullContext=()=>useAgentRuntimeStore(Au=>Au.fullContext),useAgentRuntimeContextSnapshot=()=>useAgentRuntimeStore(Au=>Au.contextSnapshot),useAgentRuntimeCodemodeStatus=()=>useAgentRuntimeStore(Au=>Au.codemodeStatus),useAgentRuntimeWsState=()=>useAgentRuntimeStore(Au=>Au.wsState),EMPTY_SUBAGENT_EVENTS=[],useAgentRuntimeSubagentActivity=Au=>useAgentRuntimeStore(lo=>Au?lo.subagentActivity[Au]??EMPTY_SUBAGENT_EVENTS:EMPTY_SUBAGENT_EVENTS),useAgentRuntimeSubagentActivityByToolCall=(Au,lo)=>useAgentRuntimeStore($u=>{if(Au){const Ru=$u.subagentActivity[Au];if(Ru&&Ru.length>0)return Ru}if(lo){const Ru=$u.subagentActivity[lo];if(Ru&&Ru.length>0)return Ru;let Iu;for(const Pu of Object.values($u.subagentActivity))Pu.length>0&&Pu[0]?.subagentName===lo&&(Iu=Pu);if(Iu)return Iu}return EMPTY_SUBAGENT_EVENTS}),useAgentRuntimeActiveSubagentToolCallId=()=>useAgentRuntimeStore(Au=>{let lo=null;for(const[$u,Ru]of Object.entries(Au.subagentActivity))Ru.length!==0&&(isSubagentRunOver(Ru)||(lo=$u));return lo});agentRuntimeStore.subscribe;async function requestAPI(Au="",lo={}){const $u=libExports$3.ServerConnection.makeSettings(),Ru=libExports$5.URLExt.join($u.baseUrl,"agent_runtimes",Au);let Iu;try{Iu=await libExports$3.ServerConnection.makeRequest(Ru,lo,$u)}catch(Ou){throw new libExports$3.ServerConnection.NetworkError(Ou)}let Pu=await Iu.text();if(Pu.length>0)try{Pu=JSON.parse(Pu)}catch{}if(!Iu.ok)throw new libExports$3.ServerConnection.ResponseError(Iu,Pu.message||Pu);return Pu}function useConfig(Au,lo,$u,Ru){return reactExports.useContext(QueryClientContext)?useQuery({queryFn:async()=>{if(lo){const Pu={"Content-Type":"application/json"};$u&&(Pu.Authorization=`Bearer ${$u}`);let Ou=lo;if(Ru){const Du=new URL(lo,window.location.origin);Du.searchParams.set("agent_id",Ru),Ou=Du.toString()}const Mu=await fetch(Ou,{headers:Pu});if(!Mu.ok)throw new Error(`Config fetch failed: ${Mu.statusText}`);return Mu.json()}return requestAPI("configure")},queryKey:["models",lo||"jupyter-server",Ru||"global"],enabled:Au,retry:1}):{data:void 0,isLoading:!1,isError:!1,error:null,refetch:()=>Promise.resolve({data:void 0})}}function parseSkillStatus(Au){return Au==="available"||Au==="enabled"||Au==="loaded"?Au:"available"}function useSkills(Au,lo,$u){const Ru=useAgentRuntimeCodemodeStatus(),Iu=reactExports.useMemo(()=>{if(!Ru)return;const Pu=(Ru.skills??[]).map(Ou=>({id:Ou.id??Ou.name,name:Ou.name,description:Ou.description,tags:Ou.tags,has_scripts:Ou.has_scripts,has_resources:Ou.has_resources,status:parseSkillStatus(Ou.status),approved:Ou.approved!==!1,skill_definition:Ou.skill_definition??null,source_variant:Ou.source_variant,module:Ou.module,package:Ou.package,method:Ou.method,path:Ou.path}));return{skills:Pu,total:Pu.length}},[Ru]);return{data:Iu,isLoading:!1,isError:!1,error:null,refetch:()=>Promise.resolve({data:Iu})}}function useSkillActions(Au){const lo=reactExports.useCallback(Pu=>{const Ou=agentRuntimeStore.getState().sendRawMessage({type:"skill_enable",skillId:Pu},Au);return Ou||console.warn("[useSkillActions] skill_enable dropped: websocket not ready"),Ou},[Au]),$u=reactExports.useCallback(Pu=>{const Ou=agentRuntimeStore.getState().sendRawMessage({type:"skill_disable",skillId:Pu},Au);return Ou||console.warn("[useSkillActions] skill_disable dropped: websocket not ready"),Ou},[Au]),Ru=reactExports.useCallback(Pu=>{const Ou=agentRuntimeStore.getState().sendRawMessage({type:"skill_approve",skillId:Pu},Au);return Ou||console.warn("[useSkillActions] skill_approve dropped: websocket not ready"),Ou},[Au]),Iu=reactExports.useCallback(Pu=>{const Ou=agentRuntimeStore.getState().sendRawMessage({type:"skill_unapprove",skillId:Pu},Au);return Ou||console.warn("[useSkillActions] skill_unapprove dropped: websocket not ready"),Ou},[Au]);return{enableSkill:lo,disableSkill:$u,approveSkill:Ru,unapproveSkill:Iu}}function useContextSnapshot(Au,lo,$u,Ru){return{data:useAgentRuntimeContextSnapshot()??void 0,isLoading:!1,isError:!1,error:null}}const RECONNECT_BASE_MS$1=1e3,RECONNECT_MAX_MS$1=3e4;function isRetryableCloseCode(Au){return!new Set([1002,1003,1007,1008,4401,4403]).has(Au)}function useSandbox(Au,lo,$u,Ru){const[Iu,Pu]=reactExports.useState(void 0),Ou=reactExports.useRef(null);reactExports.useEffect(()=>{if(!Au||!lo){Pu(void 0);return}const Du=getApiBaseFromConfig(lo);if(!Du)return;const Lu=Du.replace(/^http/,"ws"),Bu=[];Ru&&Bu.push(`agent_id=${encodeURIComponent(Ru)}`),$u&&Bu.push(`token=${encodeURIComponent($u)}`);const ju=`${Lu}/configure/sandbox/ws${Bu.length?`?${Bu.join("&")}`:""}`;let Fu=!1,zu,Uu=0;const Hu=Gu=>{if(Fu||!isRetryableCloseCode(Gu))return;const Wu=Math.min(RECONNECT_BASE_MS$1*2**Uu,RECONNECT_MAX_MS$1);Uu+=1,zu=setTimeout(Vu,Wu)},Vu=()=>{if(Fu)return;const Gu=new WebSocket(ju);Ou.current=Gu,Gu.onopen=()=>{Uu=0},Gu.onmessage=Wu=>{try{const Ku=JSON.parse(Wu.data);if(Ku&&Ku.action==="interrupt")return;const Ju=typeof Ku?.variant=="string"?Ku.variant:"";Pu({available:Ju!=="unavailable"&&Ju!=="error",sandbox_running:!!Ku?.sandbox_running,is_executing:!!Ku?.is_executing,variant:Ju})}catch{}},Gu.onclose=Wu=>{Ou.current=null,Hu(Wu.code)},Gu.onerror=()=>{Gu.close()}};return Vu(),()=>{Fu=!0,zu&&clearTimeout(zu),Ou.current?.close(),Ou.current=null,Pu(void 0)}},[Au,lo,$u,Ru]);const Mu=reactExports.useCallback(()=>{const Du=Ou.current;Du&&Du.readyState===WebSocket.OPEN&&Du.send(JSON.stringify({action:"interrupt"}))},[]);return{data:Iu,interrupt:Mu}}function _typeof$8(Au){"@babel/helpers - typeof";return _typeof$8=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(lo){return typeof lo}:function(lo){return lo&&typeof Symbol=="function"&&lo.constructor===Symbol&&lo!==Symbol.prototype?"symbol":typeof lo},_typeof$8(Au)}function _createClass$8(Au,lo,$u){return Object.defineProperty(Au,"prototype",{writable:!1}),Au}function _classCallCheck$8(Au,lo){if(!(Au instanceof lo))throw new TypeError("Cannot call a class as a function")}function _callSuper$1(Au,lo,$u){return lo=_getPrototypeOf$1(lo),_possibleConstructorReturn$1(Au,_isNativeReflectConstruct$1()?Reflect.construct(lo,$u||[],_getPrototypeOf$1(Au).constructor):lo.apply(Au,$u))}function _possibleConstructorReturn$1(Au,lo){if(lo&&(_typeof$8(lo)==="object"||typeof lo=="function"))return lo;if(lo!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return _assertThisInitialized$1(Au)}function _assertThisInitialized$1(Au){if(Au===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return Au}function _inherits$1(Au,lo){if(typeof lo!="function"&&lo!==null)throw new TypeError("Super expression must either be null or a function");Au.prototype=Object.create(lo&&lo.prototype,{constructor:{value:Au,writable:!0,configurable:!0}}),Object.defineProperty(Au,"prototype",{writable:!1}),lo&&_setPrototypeOf$1(Au,lo)}function _wrapNativeSuper(Au){var lo=typeof Map=="function"?new Map:void 0;return _wrapNativeSuper=function(Ru){if(Ru===null||!_isNativeFunction(Ru))return Ru;if(typeof Ru!="function")throw new TypeError("Super expression must either be null or a function");if(typeof lo<"u"){if(lo.has(Ru))return lo.get(Ru);lo.set(Ru,Iu)}function Iu(){return _construct(Ru,arguments,_getPrototypeOf$1(this).constructor)}return Iu.prototype=Object.create(Ru.prototype,{constructor:{value:Iu,enumerable:!1,writable:!0,configurable:!0}}),_setPrototypeOf$1(Iu,Ru)},_wrapNativeSuper(Au)}function _construct(Au,lo,$u){if(_isNativeReflectConstruct$1())return Reflect.construct.apply(null,arguments);var Ru=[null];Ru.push.apply(Ru,lo);var Iu=new(Au.bind.apply(Au,Ru));return $u&&_setPrototypeOf$1(Iu,$u.prototype),Iu}function _isNativeReflectConstruct$1(){try{var Au=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(_isNativeReflectConstruct$1=function(){return!!Au})()}function _isNativeFunction(Au){try{return Function.toString.call(Au).indexOf("[native code]")!==-1}catch{return typeof Au=="function"}}function _setPrototypeOf$1(Au,lo){return _setPrototypeOf$1=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(Ru,Iu){return Ru.__proto__=Iu,Ru},_setPrototypeOf$1(Au,lo)}function _getPrototypeOf$1(Au){return _getPrototypeOf$1=Object.setPrototypeOf?Object.getPrototypeOf.bind():function($u){return $u.__proto__||Object.getPrototypeOf($u)},_getPrototypeOf$1(Au)}var DetailedError=(function(Au){function lo($u){var Ru,Iu=arguments.length>1&&arguments[1]!==void 0?arguments[1]:null,Pu=arguments.length>2&&arguments[2]!==void 0?arguments[2]:null,Ou=arguments.length>3&&arguments[3]!==void 0?arguments[3]:null;if(_classCallCheck$8(this,lo),Ru=_callSuper$1(this,lo,[$u]),Ru.originalRequest=Pu,Ru.originalResponse=Ou,Ru.causingError=Iu,Iu!=null&&($u+=", caused by ".concat(Iu.toString())),Pu!=null){var Mu=Pu.getHeader("X-Request-ID")||"n/a",Du=Pu.getMethod(),Lu=Pu.getURL(),Bu=Ou?Ou.getStatus():"n/a",ju=Ou?Ou.getBody()||"":"n/a";$u+=", originated from request (method: ".concat(Du,", url: ").concat(Lu,", response code: ").concat(Bu,", response text: ").concat(ju,", request id: ").concat(Mu,")")}return Ru.message=$u,Ru}return _inherits$1(lo,Au),_createClass$8(lo)})(_wrapNativeSuper(Error));function log(Au){}function _typeof$7(Au){"@babel/helpers - typeof";return _typeof$7=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(lo){return typeof lo}:function(lo){return lo&&typeof Symbol=="function"&&lo.constructor===Symbol&&lo!==Symbol.prototype?"symbol":typeof lo},_typeof$7(Au)}function _classCallCheck$7(Au,lo){if(!(Au instanceof lo))throw new TypeError("Cannot call a class as a function")}function _defineProperties$7(Au,lo){for(var $u=0;$u<lo.length;$u++){var Ru=lo[$u];Ru.enumerable=Ru.enumerable||!1,Ru.configurable=!0,"value"in Ru&&(Ru.writable=!0),Object.defineProperty(Au,_toPropertyKey$7(Ru.key),Ru)}}function _createClass$7(Au,lo,$u){return lo&&_defineProperties$7(Au.prototype,lo),Object.defineProperty(Au,"prototype",{writable:!1}),Au}function _toPropertyKey$7(Au){var lo=_toPrimitive$7(Au,"string");return _typeof$7(lo)=="symbol"?lo:lo+""}function _toPrimitive$7(Au,lo){if(_typeof$7(Au)!="object"||!Au)return Au;var $u=Au[Symbol.toPrimitive];if($u!==void 0){var Ru=$u.call(Au,lo);if(_typeof$7(Ru)!="object")return Ru;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(Au)}var NoopUrlStorage=(function(){function Au(){_classCallCheck$7(this,Au)}return _createClass$7(Au,[{key:"listAllUploads",value:function(){return Promise.resolve([])}},{key:"findUploadsByFingerprint",value:function($u){return Promise.resolve([])}},{key:"removeUpload",value:function($u){return Promise.resolve()}},{key:"addUpload",value:function($u,Ru){return Promise.resolve(null)}}])})();const version$1="3.9.4",VERSION=version$1,_TD=typeof TextDecoder=="function"?new TextDecoder("utf-8",{ignoreBOM:!0}):void 0,_TE=typeof TextEncoder=="function"?new TextEncoder:void 0,b64ch="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",b64chs=Array.prototype.slice.call(b64ch),b64tab=(Au=>{let lo={};return Au.forEach(($u,Ru)=>lo[$u]=Ru),lo})(b64chs),b64re=/^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/,_fromCC=String.fromCharCode.bind(String),_U8Afrom=typeof Uint8Array.from=="function"?Uint8Array.from.bind(Uint8Array):Au=>new Uint8Array(Array.prototype.slice.call(Au,0)),_mkUriSafe=Au=>Au.replace(/=/g,"").replace(/[+\/]/g,lo=>lo=="+"?"-":"_"),_tidyB64=Au=>Au.replace(/[^A-Za-z0-9\+\/]/g,""),btoaPolyfill=Au=>{let lo,$u,Ru,Iu,Pu="";const Ou=Au.length%3;for(let Mu=0;Mu<Au.length;){if(($u=Au.charCodeAt(Mu++))>255||(Ru=Au.charCodeAt(Mu++))>255||(Iu=Au.charCodeAt(Mu++))>255)throw new TypeError("invalid character found");lo=$u<<16|Ru<<8|Iu,Pu+=b64chs[lo>>18&63]+b64chs[lo>>12&63]+b64chs[lo>>6&63]+b64chs[lo&63]}return Ou?Pu.slice(0,Ou-3)+"===".substring(Ou):Pu},_btoa=typeof btoa=="function"?Au=>btoa(Au):btoaPolyfill,_fromUint8Array=typeof Uint8Array.prototype.toBase64=="function"?Au=>Au.toBase64():Au=>{let $u=[];for(let Ru=0,Iu=Au.length;Ru<Iu;Ru+=4096)$u.push(_fromCC.apply(null,Au.subarray(Ru,Ru+4096)));return _btoa($u.join(""))},fromUint8Array=(Au,lo=!1)=>lo?_mkUriSafe(_fromUint8Array(Au)):_fromUint8Array(Au),cb_utob=Au=>{if(Au.length<2){var lo=Au.charCodeAt(0);return lo<128?Au:lo<2048?_fromCC(192|lo>>>6)+_fromCC(128|lo&63):_fromCC(224|lo>>>12&15)+_fromCC(128|lo>>>6&63)+_fromCC(128|lo&63)}else{var lo=65536+(Au.charCodeAt(0)-55296)*1024+(Au.charCodeAt(1)-56320);return _fromCC(240|lo>>>18&7)+_fromCC(128|lo>>>12&63)+_fromCC(128|lo>>>6&63)+_fromCC(128|lo&63)}},re_utob=/[\uD800-\uDBFF][\uDC00-\uDFFF]|[^\x00-\x7F]/g,utob=Au=>Au.replace(re_utob,cb_utob),_encode=_TE?Au=>_fromUint8Array(_TE.encode(Au)):Au=>_btoa(utob(Au)),encode$2=(Au,lo=!1)=>lo?_mkUriSafe(_encode(Au)):_encode(Au),encodeURI$1=Au=>encode$2(Au,!0),re_btou=/[\xC0-\xDF][\x80-\xBF]|[\xE0-\xEF][\x80-\xBF]{2}|[\xF0-\xF7][\x80-\xBF]{3}/g,cb_btou=Au=>{switch(Au.length){case 4:var lo=(7&Au.charCodeAt(0))<<18|(63&Au.charCodeAt(1))<<12|(63&Au.charCodeAt(2))<<6|63&Au.charCodeAt(3),$u=lo-65536;return _fromCC(($u>>>10)+55296)+_fromCC(($u&1023)+56320);case 3:return _fromCC((15&Au.charCodeAt(0))<<12|(63&Au.charCodeAt(1))<<6|63&Au.charCodeAt(2));default:return _fromCC((31&Au.charCodeAt(0))<<6|63&Au.charCodeAt(1))}},btou=Au=>Au.replace(re_btou,cb_btou),atobPolyfill=Au=>{if(Au=Au.replace(/\s+/g,""),!b64re.test(Au))throw new TypeError("malformed base64.");Au+="==".slice(2-(Au.length&3));let lo,$u,Ru,Iu=[];for(let Pu=0;Pu<Au.length;)lo=b64tab[Au.charAt(Pu++)]<<18|b64tab[Au.charAt(Pu++)]<<12|($u=b64tab[Au.charAt(Pu++)])<<6|(Ru=b64tab[Au.charAt(Pu++)]),$u===64?Iu.push(_fromCC(lo>>16&255)):Ru===64?Iu.push(_fromCC(lo>>16&255,lo>>8&255)):Iu.push(_fromCC(lo>>16&255,lo>>8&255,lo&255));return Iu.join("")},_atob=typeof atob=="function"?Au=>atob(_tidyB64(Au)):atobPolyfill,_toUint8Array=typeof Uint8Array.fromBase64=="function"?Au=>Uint8Array.fromBase64(Au):Au=>_U8Afrom(_atob(Au).split("").map(lo=>lo.charCodeAt(0))),toUint8Array=Au=>_toUint8Array(_unURI(Au)),_decode=_TD?Au=>_TD.decode(_toUint8Array(Au)):Au=>btou(_atob(Au)),_unURI=Au=>_tidyB64(Au.replace(/[-_]/g,lo=>lo=="-"?"+":"/")),decode$3=Au=>_decode(_unURI(Au)),isValid$1=Au=>{if(typeof Au!="string")return!1;const lo=Au.replace(/\s+/g,"").replace(/={0,2}$/,"");return!/[^\s0-9a-zA-Z\+/]/.test(lo)||!/[^\s0-9a-zA-Z\-_]/.test(lo)},_noEnum=Au=>({value:Au,enumerable:!1,writable:!0,configurable:!0}),extendString=function(){const Au=(lo,$u)=>Object.defineProperty(String.prototype,lo,_noEnum($u));Au("fromBase64",function(){return decode$3(this)}),Au("toBase64",function(lo){return encode$2(this,lo)}),Au("toBase64URI",function(){return encode$2(this,!0)}),Au("toBase64URL",function(){return encode$2(this,!0)}),Au("toUint8Array",function(){return toUint8Array(this)})},extendUint8Array=function(){const Au=(lo,$u)=>Object.defineProperty(Uint8Array.prototype,lo,_noEnum($u));Au("toBase64",function(lo){return fromUint8Array(this,lo)}),Au("toBase64URI",function(){return fromUint8Array(this,!0)}),Au("toBase64URL",function(){return fromUint8Array(this,!0)})},extendBuiltins=()=>{extendString(),extendUint8Array()},gBase64={version:version$1,VERSION,atob:_atob,atobPolyfill,btoa:_btoa,btoaPolyfill,fromBase64:decode$3,toBase64:encode$2,encode:encode$2,encodeURI:encodeURI$1,encodeURL:encodeURI$1,utob,btou,decode:decode$3,isValid:isValid$1,fromUint8Array,toUint8Array,extendString,extendUint8Array,extendBuiltins};var urlParseExports=requireUrlParse();const URL$1=getDefaultExportFromCjs(urlParseExports);function uuid(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(Au){var lo=Math.random()*16|0,$u=Au==="x"?lo:lo&3|8;return $u.toString(16)})}function _regeneratorRuntime$1(){_regeneratorRuntime$1=function(){return lo};var Au,lo={},$u=Object.prototype,Ru=$u.hasOwnProperty,Iu=Object.defineProperty||function(_d,vd,wd){_d[vd]=wd.value},Pu=typeof Symbol=="function"?Symbol:{},Ou=Pu.iterator||"@@iterator",Mu=Pu.asyncIterator||"@@asyncIterator",Du=Pu.toStringTag||"@@toStringTag";function Lu(_d,vd,wd){return Object.defineProperty(_d,vd,{value:wd,enumerable:!0,configurable:!0,writable:!0}),_d[vd]}try{Lu({},"")}catch{Lu=function(wd,Ed,cd){return wd[Ed]=cd}}function Bu(_d,vd,wd,Ed){var cd=vd&&vd.prototype instanceof Gu?vd:Gu,dd=Object.create(cd.prototype),md=new gd(Ed||[]);return Iu(dd,"_invoke",{value:od(_d,wd,md)}),dd}function ju(_d,vd,wd){try{return{type:"normal",arg:_d.call(vd,wd)}}catch(Ed){return{type:"throw",arg:Ed}}}lo.wrap=Bu;var Fu="suspendedStart",zu="suspendedYield",Uu="executing",Hu="completed",Vu={};function Gu(){}function Wu(){}function Ku(){}var Ju={};Lu(Ju,Ou,function(){return this});var Yu=Object.getPrototypeOf,Xu=Yu&&Yu(Yu(yd([])));Xu&&Xu!==$u&&Ru.call(Xu,Ou)&&(Ju=Xu);var ed=Ku.prototype=Gu.prototype=Object.create(Ju);function td(_d){["next","throw","return"].forEach(function(vd){Lu(_d,vd,function(wd){return this._invoke(vd,wd)})})}function nd(_d,vd){function wd(cd,dd,md,ld){var hd=ju(_d[cd],_d,dd);if(hd.type!=="throw"){var bd=hd.arg,Sd=bd.value;return Sd&&_typeof$6(Sd)=="object"&&Ru.call(Sd,"__await")?vd.resolve(Sd.__await).then(function(kd){wd("next",kd,md,ld)},function(kd){wd("throw",kd,md,ld)}):vd.resolve(Sd).then(function(kd){bd.value=kd,md(bd)},function(kd){return wd("throw",kd,md,ld)})}ld(hd.arg)}var Ed;Iu(this,"_invoke",{value:function(dd,md){function ld(){return new vd(function(hd,bd){wd(dd,md,hd,bd)})}return Ed=Ed?Ed.then(ld,ld):ld()}})}function od(_d,vd,wd){var Ed=Fu;return function(cd,dd){if(Ed===Uu)throw Error("Generator is already running");if(Ed===Hu){if(cd==="throw")throw dd;return{value:Au,done:!0}}for(wd.method=cd,wd.arg=dd;;){var md=wd.delegate;if(md){var ld=sd(md,wd);if(ld){if(ld===Vu)continue;return ld}}if(wd.method==="next")wd.sent=wd._sent=wd.arg;else if(wd.method==="throw"){if(Ed===Fu)throw Ed=Hu,wd.arg;wd.dispatchException(wd.arg)}else wd.method==="return"&&wd.abrupt("return",wd.arg);Ed=Uu;var hd=ju(_d,vd,wd);if(hd.type==="normal"){if(Ed=wd.done?Hu:zu,hd.arg===Vu)continue;return{value:hd.arg,done:wd.done}}hd.type==="throw"&&(Ed=Hu,wd.method="throw",wd.arg=hd.arg)}}}function sd(_d,vd){var wd=vd.method,Ed=_d.iterator[wd];if(Ed===Au)return vd.delegate=null,wd==="throw"&&_d.iterator.return&&(vd.method="return",vd.arg=Au,sd(_d,vd),vd.method==="throw")||wd!=="return"&&(vd.method="throw",vd.arg=new TypeError("The iterator does not provide a '"+wd+"' method")),Vu;var cd=ju(Ed,_d.iterator,vd.arg);if(cd.type==="throw")return vd.method="throw",vd.arg=cd.arg,vd.delegate=null,Vu;var dd=cd.arg;return dd?dd.done?(vd[_d.resultName]=dd.value,vd.next=_d.nextLoc,vd.method!=="return"&&(vd.method="next",vd.arg=Au),vd.delegate=null,Vu):dd:(vd.method="throw",vd.arg=new TypeError("iterator result is not an object"),vd.delegate=null,Vu)}function ad(_d){var vd={tryLoc:_d[0]};1 in _d&&(vd.catchLoc=_d[1]),2 in _d&&(vd.finallyLoc=_d[2],vd.afterLoc=_d[3]),this.tryEntries.push(vd)}function pd(_d){var vd=_d.completion||{};vd.type="normal",delete vd.arg,_d.completion=vd}function gd(_d){this.tryEntries=[{tryLoc:"root"}],_d.forEach(ad,this),this.reset(!0)}function yd(_d){if(_d||_d===""){var vd=_d[Ou];if(vd)return vd.call(_d);if(typeof _d.next=="function")return _d;if(!isNaN(_d.length)){var wd=-1,Ed=function cd(){for(;++wd<_d.length;)if(Ru.call(_d,wd))return cd.value=_d[wd],cd.done=!1,cd;return cd.value=Au,cd.done=!0,cd};return Ed.next=Ed}}throw new TypeError(_typeof$6(_d)+" is not iterable")}return Wu.prototype=Ku,Iu(ed,"constructor",{value:Ku,configurable:!0}),Iu(Ku,"constructor",{value:Wu,configurable:!0}),Wu.displayName=Lu(Ku,Du,"GeneratorFunction"),lo.isGeneratorFunction=function(_d){var vd=typeof _d=="function"&&_d.constructor;return!!vd&&(vd===Wu||(vd.displayName||vd.name)==="GeneratorFunction")},lo.mark=function(_d){return Object.setPrototypeOf?Object.setPrototypeOf(_d,Ku):(_d.__proto__=Ku,Lu(_d,Du,"GeneratorFunction")),_d.prototype=Object.create(ed),_d},lo.awrap=function(_d){return{__await:_d}},td(nd.prototype),Lu(nd.prototype,Mu,function(){return this}),lo.AsyncIterator=nd,lo.async=function(_d,vd,wd,Ed,cd){cd===void 0&&(cd=Promise);var dd=new nd(Bu(_d,vd,wd,Ed),cd);return lo.isGeneratorFunction(vd)?dd:dd.next().then(function(md){return md.done?md.value:dd.next()})},td(ed),Lu(ed,Du,"Generator"),Lu(ed,Ou,function(){return this}),Lu(ed,"toString",function(){return"[object Generator]"}),lo.keys=function(_d){var vd=Object(_d),wd=[];for(var Ed in vd)wd.push(Ed);return wd.reverse(),function cd(){for(;wd.length;){var dd=wd.pop();if(dd in vd)return cd.value=dd,cd.done=!1,cd}return cd.done=!0,cd}},lo.values=yd,gd.prototype={constructor:gd,reset:function(vd){if(this.prev=0,this.next=0,this.sent=this._sent=Au,this.done=!1,this.delegate=null,this.method="next",this.arg=Au,this.tryEntries.forEach(pd),!vd)for(var wd in this)wd.charAt(0)==="t"&&Ru.call(this,wd)&&!isNaN(+wd.slice(1))&&(this[wd]=Au)},stop:function(){this.done=!0;var vd=this.tryEntries[0].completion;if(vd.type==="throw")throw vd.arg;return this.rval},dispatchException:function(vd){if(this.done)throw vd;var wd=this;function Ed(bd,Sd){return md.type="throw",md.arg=vd,wd.next=bd,Sd&&(wd.method="next",wd.arg=Au),!!Sd}for(var cd=this.tryEntries.length-1;cd>=0;--cd){var dd=this.tryEntries[cd],md=dd.completion;if(dd.tryLoc==="root")return Ed("end");if(dd.tryLoc<=this.prev){var ld=Ru.call(dd,"catchLoc"),hd=Ru.call(dd,"finallyLoc");if(ld&&hd){if(this.prev<dd.catchLoc)return Ed(dd.catchLoc,!0);if(this.prev<dd.finallyLoc)return Ed(dd.finallyLoc)}else if(ld){if(this.prev<dd.catchLoc)return Ed(dd.catchLoc,!0)}else{if(!hd)throw Error("try statement without catch or finally");if(this.prev<dd.finallyLoc)return Ed(dd.finallyLoc)}}}},abrupt:function(vd,wd){for(var Ed=this.tryEntries.length-1;Ed>=0;--Ed){var cd=this.tryEntries[Ed];if(cd.tryLoc<=this.prev&&Ru.call(cd,"finallyLoc")&&this.prev<cd.finallyLoc){var dd=cd;break}}dd&&(vd==="break"||vd==="continue")&&dd.tryLoc<=wd&&wd<=dd.finallyLoc&&(dd=null);var md=dd?dd.completion:{};return md.type=vd,md.arg=wd,dd?(this.method="next",this.next=dd.finallyLoc,Vu):this.complete(md)},complete:function(vd,wd){if(vd.type==="throw")throw vd.arg;return vd.type==="break"||vd.type==="continue"?this.next=vd.arg:vd.type==="return"?(this.rval=this.arg=vd.arg,this.method="return",this.next="end"):vd.type==="normal"&&wd&&(this.next=wd),Vu},finish:function(vd){for(var wd=this.tryEntries.length-1;wd>=0;--wd){var Ed=this.tryEntries[wd];if(Ed.finallyLoc===vd)return this.complete(Ed.completion,Ed.afterLoc),pd(Ed),Vu}},catch:function(vd){for(var wd=this.tryEntries.length-1;wd>=0;--wd){var Ed=this.tryEntries[wd];if(Ed.tryLoc===vd){var cd=Ed.completion;if(cd.type==="throw"){var dd=cd.arg;pd(Ed)}return dd}}throw Error("illegal catch attempt")},delegateYield:function(vd,wd,Ed){return this.delegate={iterator:yd(vd),resultName:wd,nextLoc:Ed},this.method==="next"&&(this.arg=Au),Vu}},lo}function asyncGeneratorStep$1(Au,lo,$u,Ru,Iu,Pu,Ou){try{var Mu=Au[Pu](Ou),Du=Mu.value}catch(Lu){$u(Lu);return}Mu.done?lo(Du):Promise.resolve(Du).then(Ru,Iu)}function _asyncToGenerator$1(Au){return function(){var lo=this,$u=arguments;return new Promise(function(Ru,Iu){var Pu=Au.apply(lo,$u);function Ou(Du){asyncGeneratorStep$1(Pu,Ru,Iu,Ou,Mu,"next",Du)}function Mu(Du){asyncGeneratorStep$1(Pu,Ru,Iu,Ou,Mu,"throw",Du)}Ou(void 0)})}}function _slicedToArray$1(Au,lo){return _arrayWithHoles$1(Au)||_iterableToArrayLimit$1(Au,lo)||_unsupportedIterableToArray$1(Au,lo)||_nonIterableRest$1()}function _nonIterableRest$1(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
2197
+ `);function unifiedDiffLines(Au,lo){const $u=Au===null?[]:lines(Au),Ru=lines(lo);if($u.length>DIFF_LINES_LIMIT||Ru.length>DIFF_LINES_LIMIT)return[...$u.map(Du=>({kind:"remove",text:Du})),...Ru.map(Du=>({kind:"add",text:Du}))];const Iu=[];for(let Du=0;Du<=$u.length;Du++)Iu.push(new Uint32Array(Ru.length+1));for(let Du=$u.length-1;Du>=0;Du--)for(let Lu=Ru.length-1;Lu>=0;Lu--)Iu[Du][Lu]=$u[Du]===Ru[Lu]?Iu[Du+1][Lu+1]+1:Math.max(Iu[Du+1][Lu],Iu[Du][Lu+1]);const Pu=[];let Ou=0,Mu=0;for(;Ou<$u.length&&Mu<Ru.length;)$u[Ou]===Ru[Mu]?(Pu.push({kind:"context",text:$u[Ou]}),Ou++,Mu++):Iu[Ou+1][Mu]>=Iu[Ou][Mu+1]?(Pu.push({kind:"remove",text:$u[Ou]}),Ou++):(Pu.push({kind:"add",text:Ru[Mu]}),Mu++);for(;Ou<$u.length;)Pu.push({kind:"remove",text:$u[Ou++]});for(;Mu<Ru.length;)Pu.push({kind:"add",text:Ru[Mu++]});return Pu}const THREAD_WORDS={opening:"Opening your conversation…",notOpened:Au=>`Your conversation could not be opened, so this is a new one: ${Au}`};function messagesOfThread(Au){if(!Array.isArray(Au))return[];const lo=[];for(const $u of Au){if(!$u||typeof $u!="object")continue;const{id:Ru,role:Iu,content:Pu,activityType:Ou}=$u;if(Iu==="activity"&&Ou===REACTOR_UI_NAME)throw new Error(`Activity ${String(Ru)}: what a message showed comes on the ui socket (REACTOR_UI RU-W)`);(Iu==="user"||Iu==="assistant")&&typeof Ru=="string"&&typeof Pu=="string"&&Pu.trim()&&lo.push({id:Ru,role:Iu,content:Iu==="user"?askedOf(Pu):Pu,createdAt:new Date})}return lo}function snapshotOfStream(Au){let lo;for(const $u of eventsOfStream(Au))$u.type==="MESSAGES_SNAPSHOT"&&Array.isArray($u.messages)&&(lo=$u.messages);return lo}async function detailOf(Au){try{const lo=await Au.json();if(typeof lo.detail=="string"&&lo.detail)return lo.detail}catch{}return`${Au.status}`}async function openThread({agentBaseUrl:Au,agentId:lo,uid:$u,token:Ru,fetcher:Iu=fetch}){const Pu=`${Au.replace(/\/+$/,"")}/api/v1/apps/sessions/${encodeURIComponent($u)}`,Ou=Ru?{Authorization:`Bearer ${Ru}`}:{},Mu=await Iu(`${Pu}/messages`,{headers:Ou});if(Mu.ok){const Bu=await Mu.json();return messagesOfThread(Bu.messages)}if(Mu.status!==404)throw new Error(await detailOf(Mu));const Du=await Iu(`${Pu}/resume`,{method:"POST",headers:{"Content-Type":"application/json",...Ou},body:JSON.stringify({agent:lo})});if(!Du.ok)throw new Error(await detailOf(Du));const Lu=snapshotOfStream(await Du.text());if(!Lu)throw new Error(`The runtime said nothing of session ${$u}.`);return messagesOfThread(Lu)}const ITEM_LIMIT=400,MESSAGE_TEXT_LIMIT=1e5,TOOL_TEXT_LIMIT=4e3,DIAGNOSTIC_LIMIT=50,DEVICE_LIMITS={items:ITEM_LIMIT,messageText:MESSAGE_TEXT_LIMIT,toolText:TOOL_TEXT_LIMIT,diagnostics:DIAGNOSTIC_LIMIT},BROWSER_LIMITS={items:5e3,messageText:1e6,toolText:1e6,diagnostics:DIAGNOSTIC_LIMIT},CUT_MARK="… (cut: too long to keep on this device)",emptyConversation=(Au=DEVICE_LIMITS)=>{for(const[lo,$u]of Object.entries(Au))if(!Number.isInteger($u)||$u<1)throw new Error(`A conversation's ${lo} bound is ${String($u)}: give a whole number of at least 1.`);return{items:[],running:!1,session:null,asking:null,dropped:0,diagnostics:[],turnRows:0,limits:Au}},text$g=Au=>typeof Au=="string"?Au:"",cut=(Au,lo)=>Au.length>lo?`${Au.slice(0,lo)}${CUT_MARK}`:Au,appended=(Au,lo,$u)=>Au.endsWith(CUT_MARK)?Au:cut(Au+lo,$u),isRecord$1=Au=>!!Au&&typeof Au=="object"&&!Array.isArray(Au);function withoutMeta(Au){if(isRecord$1(Au)&&"_meta"in Au){const{_meta:lo,...$u}=Au;return $u}return Au}function said(Au){return Au==null?"":typeof Au=="string"?Au:JSON.stringify(Au)}function questionOf$1(Au){if(!Au||typeof Au!="object")return null;const lo=Au,$u=lo.kind;if($u!=="text"&&$u!=="choice"&&$u!=="form"&&$u!=="file")throw new Error(`The application asks something no client knows: ${String($u)}.`);const Ru=Pu=>Array.isArray(Pu)?Pu.filter(Ou=>typeof Ou=="string"):[],Iu=lo.schema;return{kind:$u,prompt:text$g(lo.prompt),options:Ru(lo.options),schema:isRecord$1(Iu)?Iu:null,accept:Ru(lo.accept)}}function withItems(Au,lo,$u=0){const Ru=lo.length-Au.limits.items;return{...Au,items:Ru>0?lo.slice(Ru):lo,dropped:Au.dropped+Math.max(0,Ru),turnRows:Au.turnRows+$u}}function changed$1(Au,lo,$u){const Ru=Au.items.findIndex(Pu=>Pu.id===lo);if(Ru<0)return null;const Iu=Au.items.slice();return Iu[Ru]=$u(Iu[Ru]),{...Au,items:Iu}}function noted(Au,lo){const $u={type:lo.type,name:text$g(lo.name)||text$g(lo.activityType)};return{...Au,diagnostics:[...Au.diagnostics,$u].slice(-Au.limits.diagnostics)}}const HARNESS_TOOL_CALL="datalayer.harness.tool_call";function withRunningDisplay(Au,lo){if(!isRecord$1(lo)||!isRecord$1(lo._meta))return null;const $u=lo._meta[DISPLAY_META_KEY];if($u===void 0)return null;const Ru=protocolDisplayOf($u);if(!Ru)throw new Error(`${HARNESS_TOOL_CALL} of ${text$g(lo.id)} carries a display no client reads.`);return changed$1(Au,text$g(lo.id),Iu=>Iu.kind==="tool"&&Iu.status==="running"?{...Iu,value:{_meta:lo._meta},display:Ru}:Iu)}let rowCount=0;const rowId=Au=>`${Au}-${Date.now().toString(36)}-${rowCount+=1}`;function toolRow(Au,lo){return{kind:"tool",id:Au,name:lo,args:"",input:null,status:"running",awaiting:null,result:"",value:void 0,error:"",executionError:"",codeError:null,exitCode:null,display:null}}function withInput(Au,lo,$u){const Ru=JSON.stringify(lo),Iu=Ru.length<=$u;return{...Au,args:cut(Ru,$u),input:Iu?lo:null}}const asksThePerson=Au=>!!Au&&Array.isArray(Au.steps);function withResult(Au,lo,$u,Ru=!1){const Iu=lo.result,Pu=said(withoutMeta(Iu)),Ou=isRecord$1(Iu)?Iu:null,Mu=typeof Ou?.execution_error=="string"?Ou.execution_error:"",Du=isRecord$1(Ou?.code_error)?Ou.code_error:null,Lu=Du?{name:text$g(Du.name)||"Error",value:text$g(Du.value)||"Unknown error",traceback:cut(text$g(Du.traceback),$u)}:null,Bu=Ou&&typeof Ou.exit_code=="number"?Ou.exit_code:null,ju=!lo.success||Mu!==""||Lu!==null||Bu!==null&&Bu!==0||Ou?.execution_ok===!1,Fu=ju||Ru?null:Ou?.pending_approval===!0?"approval":asksThePerson(Au.input)?"person":null;return{...Au,status:ju?"error":Fu?"running":"complete",awaiting:Fu,result:cut(Pu,$u),value:Pu.length<=$u?Iu:void 0,error:lo.error??"",executionError:cut(Mu,$u),codeError:Lu,exitCode:Bu,display:displayOfToolResult(Au.name,Iu,Au.id)}}function rowsOfSnapshot(Au,lo,$u){if(!Array.isArray(Au))throw new Error("A messages snapshot carries no list of messages.");const Ru=[],Iu=new Map;for(const Pu of Au){for(const Ou of messagesOfThread([Pu]))Ru.push({kind:"message",id:Ou.id,role:Ou.role==="user"?"user":"assistant",text:cut(typeof Ou.content=="string"?Ou.content:"",lo.messageText),streaming:!1});if(isRecord$1(Pu)){if(Pu.role==="assistant"&&Pu.toolCalls!==void 0){if(!Array.isArray(Pu.toolCalls))throw new Error(`Message ${String(Pu.id)}'s tool calls are not a list.`);for(const Ou of Pu.toolCalls){const Mu=isRecord$1(Ou)?Ou.function:void 0;if(!isRecord$1(Ou)||typeof Ou.id!="string"||!isRecord$1(Mu))throw new Error(`Message ${String(Pu.id)} holds a tool call without its id and function.`);const Du=text$g(Mu.arguments);let Lu=null;if(Du&&Du.length<=lo.toolText){let Bu;try{Bu=JSON.parse(Du)}catch{Bu=void 0}if(!isRecord$1(Bu))throw new Error(`Tool call ${Ou.id}'s arguments are not a JSON object.`);Lu=Bu}Iu.set(Ou.id,Ru.length),Ru.push({...toolRow(Ou.id,text$g(Mu.name)),args:cut(Du,lo.toolText),input:Du?Lu:{},status:"complete"})}}if(Pu.role==="tool"){const Ou=text$g(Pu.toolCallId),Mu=Iu.get(Ou);if(Mu===void 0){$u.push(Ou||"no call");continue}Ru[Mu]=withResult(Ru[Mu],toolResultOf(Pu.content),lo.toolText,!0)}}}return Ru}function withPrompt(Au,lo,$u){return withItems({...Au,asking:null},[...Au.items,{kind:"message",id:lo,role:"user",text:$u,streaming:!1}])}function withoutItems(Au,lo){const $u=new Set(lo);return{...Au,items:Au.items.filter(Ru=>!$u.has(Ru.id))}}function withTurnEnded(Au,lo){const $u=Au.items.map(Iu=>Iu.kind==="message"&&Iu.streaming?{...Iu,streaming:!1}:Iu.kind==="tool"&&Iu.status==="running"?{...Iu,status:"error",awaiting:null,error:RUN_END_WORDS[lo]}:Iu.kind==="step"&&Iu.status==="running"?{...Iu,status:"complete"}:Iu),Ru={...Au,items:$u,running:!1};return withItems(Ru,[...$u,{kind:"end",id:rowId("end"),end:lo,words:RUN_END_WORDS[lo]}])}function withError(Au,lo){const $u=Au.items.map(Ru=>Ru.kind==="message"&&Ru.streaming?{...Ru,streaming:!1}:Ru.kind==="tool"&&Ru.status==="running"?{...Ru,status:"error",awaiting:null}:Ru.kind==="step"&&Ru.status==="running"?{...Ru,status:"complete"}:Ru);return withItems({...Au,running:!1},[...$u,{kind:"error",id:rowId("error"),text:lo}])}function required(Au,lo){const $u=Au[lo];if(typeof $u!="string"||!$u)throw new Error(`${Au.type} carries no ${lo}.`);return $u}function reduceConversation(Au,lo){const{limits:$u}=Au;switch(lo.type){case"RUN_STARTED":return{...Au,running:!0,asking:null,turnRows:0};case"TEXT_MESSAGE_START":{const Ru=text$g(lo.messageId)||rowId("message");if(Au.items.some(Pu=>Pu.id===Ru))return Au;const Iu=lo.role==="user"?"user":"assistant";return withItems(Au,[...Au.items,{kind:"message",id:Ru,role:Iu,text:"",streaming:!0}],1)}case"TEXT_MESSAGE_CONTENT":case"TEXT_MESSAGE_CHUNK":{const Ru=text$g(lo.delta),Iu=text$g(lo.messageId),Pu=changed$1(Au,Iu,Ou=>Ou.kind==="message"?{...Ou,text:appended(Ou.text,Ru,$u.messageText)}:Ou);return Pu||withItems(Au,[...Au.items,{kind:"message",id:Iu||rowId("message"),role:lo.role==="user"?"user":"assistant",text:cut(Ru,$u.messageText),streaming:lo.type==="TEXT_MESSAGE_CONTENT"}],1)}case"TEXT_MESSAGE_END":return changed$1(Au,text$g(lo.messageId),Ru=>Ru.kind==="message"?{...Ru,streaming:!1}:Ru)??Au;case"MESSAGE_SAID":{const Ru=required(lo,"messageId");if(typeof lo.text!="string")throw new Error(`MESSAGE_SAID of ${Ru} carries no text.`);if(lo.role!=="user"&&lo.role!=="assistant")throw new Error(`MESSAGE_SAID of ${Ru} is said by ${String(lo.role)}: only the person or the assistant speaks here.`);const Iu=lo.role,Pu=cut(lo.text,$u.messageText),Ou=Iu==="assistant"&&lo.streaming!==!1,Mu=Au.items.findIndex(Du=>Du.id===Ru);if(Mu>=0){const Du=Au.items[Mu];if(Du.kind!=="message")throw new Error(`MESSAGE_SAID of ${Ru} names a ${Du.kind} row.`);const Lu=Au.items.slice();return Lu[Mu]={...Du,text:Pu,streaming:Ou},{...Au,items:Lu}}return withItems(Au,[...Au.items,{kind:"message",id:Ru,role:Iu,text:Pu,streaming:Ou}],1)}case"TOOL_CALL_START":{const Ru=text$g(lo.toolCallId)||rowId("tool");return Au.items.some(Iu=>Iu.id===Ru)?Au:withItems(Au,[...Au.items,toolRow(Ru,text$g(lo.toolCallName)||text$g(lo.name))],1)}case"TOOL_CALL_ARGS":return changed$1(Au,text$g(lo.toolCallId),Ru=>Ru.kind==="tool"?{...Ru,args:appended(Ru.args,text$g(lo.delta),$u.toolText)}:Ru)??Au;case"TOOL_CALL_END":return changed$1(Au,text$g(lo.toolCallId),Ru=>{if(Ru.kind!=="tool"||Ru.args.endsWith(CUT_MARK))return Ru;if(!Ru.args)return{...Ru,input:{}};let Iu;try{Iu=JSON.parse(Ru.args)}catch{Iu=void 0}return isRecord$1(Iu)?{...Ru,input:Iu}:{...Ru,status:"error",awaiting:null,error:"Its arguments are not a JSON object."}})??Au;case"TOOL_CALL_SAID":{const Ru=required(lo,"toolCallId"),Iu=required(lo,"toolCallName");if(!isRecord$1(lo.args))throw new Error(`TOOL_CALL_SAID of ${Ru} carries arguments that are not an object.`);const Pu=lo.args,Ou=Au.items.findIndex(Lu=>Lu.id===Ru);if(Ou<0)return withItems(Au,[...Au.items,withInput(toolRow(Ru,Iu),Pu,$u.toolText)],1);const Mu=Au.items[Ou];if(Mu.kind!=="tool")throw new Error(`TOOL_CALL_SAID of ${Ru} names a ${Mu.kind} row.`);const Du=Au.items.slice();return Du[Ou]=withInput(Mu,{...Mu.input??{},...Pu},$u.toolText),{...Au,items:Du}}case"TOOL_CALL_RESULT":{const Ru=toolResultOf(lo.content);return changed$1(Au,text$g(lo.toolCallId),Iu=>Iu.kind==="tool"?withResult(Iu,Ru,$u.toolText):Iu)??noted(Au,lo)}case"TOOL_CALL_DONE":{const Ru=required(lo,"toolCallId");if(typeof lo.success!="boolean")throw new Error(`TOOL_CALL_DONE of ${Ru} does not say whether it succeeded.`);if(lo.error!==void 0&&typeof lo.error!="string")throw new Error(`TOOL_CALL_DONE of ${Ru} says its error in no words.`);const Iu={result:lo.result,success:lo.success,...lo.error!==void 0?{error:lo.error}:{}};return changed$1(Au,Ru,Pu=>Pu.kind==="tool"?withResult(Pu,Iu,$u.toolText,lo.answered===!0):Pu)??noted(Au,lo)}case"STEP_STARTED":{const Ru=text$g(lo.stepName)||text$g(lo.name);return withItems(Au,[...Au.items,{kind:"step",id:rowId("step"),name:Ru,status:"running"}],1)}case"STEP_FINISHED":{const Ru=text$g(lo.stepName)||text$g(lo.name),Iu=Au.items.map((Ou,Mu)=>({item:Ou,index:Mu})).reverse().find(({item:Ou})=>Ou.kind==="step"&&Ou.name===Ru&&Ou.status==="running");if(!Iu)return noted(Au,lo);const Pu=Au.items.slice();return Pu[Iu.index]={...Iu.item,status:"complete"},{...Au,items:Pu}}case"MESSAGES_SNAPSHOT":{const Ru=[],Iu=rowsOfSnapshot(lo.messages,$u,Ru),Pu=withItems({...Au,dropped:0},Iu,1);return Ru.reduce((Ou,Mu)=>noted(Ou,{type:"TOOL_CALL_RESULT",name:`${Mu} (no call)`}),Pu)}case"CUSTOM":{if(lo.name===REACTOR_UI_NAME)return withError(Au,UI_ON_RUN);if(lo.name==="loop.session"&&isRecord$1(lo.value)){const Ru=lo.value;return{...Au,session:Ru,asking:questionOf$1(Ru.asking)??Au.asking}}return lo.name===HARNESS_TOOL_CALL?withRunningDisplay(Au,lo.value)??noted(Au,lo):noted(Au,lo)}case"ACTIVITY_SNAPSHOT":case"ACTIVITY_DELTA":return lo.activityType===REACTOR_UI_NAME?withError(Au,UI_ON_RUN):noted(Au,lo);case"RUN_FINISHED":{const Ru=isRecord$1(lo.result)?lo.result:{},Iu=questionOf$1(Ru.asking),Pu=Au.items.map(Mu=>Mu.kind==="message"&&Mu.streaming?{...Mu,streaming:!1}:Mu),Ou={...Au,items:Pu,running:!1,asking:Iu};return Iu||Au.turnRows>0?Ou:withItems(Ou,[...Pu,{kind:"end",id:rowId("end"),end:"answered",words:RUN_END_WORDS.answered}])}case"RUN_ERROR":return withError(Au,text$g(lo.message)||"Run failed");default:return noted(Au,lo)}}const emptyChatLayer=()=>({extras:new Map,displays:new Map,speakers:new Map,steps:[]}),toolCardId=Au=>`tool-${Au}`,rowIdOf=Au=>"toolCallId"in Au&&Au.id===toolCardId(Au.toolCallId)?Au.toolCallId:Au.id;function cardStatusOf(Au){return Au.status!=="running"?Au.status:Au.awaiting==="approval"?"inProgress":"executing"}function toolCallOf(Au){return{id:toolCardId(Au.id),type:"tool-call",toolCallId:Au.id,toolName:Au.name,args:Au.input??{},...Au.value!==void 0?{result:Au.value}:Au.result?{result:Au.result}:{},status:cardStatusOf(Au),...Au.error?{error:Au.error}:{},...Au.executionError?{executionError:Au.executionError}:{},...Au.codeError?{codeError:{name:Au.codeError.name,value:Au.codeError.value,...Au.codeError.traceback?{traceback:Au.codeError.traceback}:{}}}:{},...Au.exitCode!==null?{exitCode:Au.exitCode}:{}}}function conversationDrawer(Au){const lo=new Map,$u=(Iu,Pu)=>{const Ou=Pu.extras.get(Iu.id),Mu=Pu.displays.get(Iu.id),Du=Pu.speakers.get(Iu.id),Lu=lo.get(Iu.id);if(Lu&&Lu.row===Iu&&Lu.extras===Ou&&Lu.displays===Mu&&Lu.speaker===Du)return Lu.item;const Bu={...Ou,createdAt:Ou?.createdAt??new Date,id:Iu.id,role:Iu.kind==="message"?Iu.role:"assistant",content:Iu.kind==="message"?Iu.text:Au(Iu.text),...Mu?{displays:Mu}:{},...Du?{speaker:Du}:{}};return lo.set(Iu.id,{row:Iu,extras:Ou,displays:Mu,speaker:Du,item:Bu}),Bu},Ru=Iu=>{const Pu=lo.get(Iu.id);if(Pu&&Pu.row===Iu)return Pu.item;const Ou=toolCallOf(Iu);return lo.set(Iu.id,{row:Iu,item:Ou}),Ou};return(Iu,Pu)=>{const Ou=[],Mu=new Map;for(const Lu of Pu.steps)Mu.set(Lu.after,[...Mu.get(Lu.after)??[],Lu.item]);Ou.push(...Mu.get(null)??[]);const Du=new Set;for(const Lu of Iu.items)Du.add(Lu.id),Lu.kind==="message"||Lu.kind==="error"?Ou.push($u(Lu,Pu)):Lu.kind==="tool"&&Ou.push(Ru(Lu)),Ou.push(...Mu.get(Lu.id)??[]);for(const[Lu,Bu]of Mu)Lu!==null&&!Du.has(Lu)&&Ou.push(...Bu);for(const Lu of lo.keys())Du.has(Lu)||lo.delete(Lu);return Ou}}function isSubagentRunOver(Au){return Au.some(lo=>lo.phase==="end"||lo.phase==="error")}function getMonitoringCacheKey(Au,lo){return`${Au||"__unknown_service__"}::${lo||"__unknown_agent__"}`}function getTransportEndpoint(Au,lo,$u){switch(lo){case"vercel-ai":return`${Au}/api/v1/vercel-ai/${$u}`;case"a2a":return`${Au}/api/v1/a2a/agents/${$u}/`;case"acp":return`${Au}/api/v1/acp/ws/${$u}`;default:return`${Au}/api/v1/ag-ui/${$u}/`}}function toAgentRuntimeBaseUrl(Au){const lo=Au.replace(/\/$/,"");return lo.includes("/api/agent-runtimes")?lo:lo.includes("/api/jupyter-server")?lo.replace("/api/jupyter-server","/api/agent-runtimes"):lo.includes("/jupyter/server/")?lo.replace("/jupyter/server/","/agent-runtimes/"):lo.includes("/jupyter-server/")?lo.replace("/jupyter-server/","/agent-runtimes/"):lo.replace("/jupyter/","/agent-runtimes/")}async function createAgentOnRuntime(Au,lo,$u={}){const{iamStore:Ru}=await __vitePreload(async()=>{const{iamStore:Lu}=await import("./chunks/index-fQxrRXLD.js");return{iamStore:Lu}},[],import.meta.url),Iu=Ru.getState().token||"";if(!$u.protocol&&!$u.agentSpecId)throw new Error("Agent protocol is required. Provide config.protocol from the selected spec/config.");const Pu=$u.protocol||"vercel-ai";if(!$u.model&&!$u.agentSpecId)throw new Error("Agent model is required. Provide config.model from the selected spec/config.");const Ou={name:$u.name||lo,description:$u.description||"AI assistant",agent_library:$u.agentLibrary||"pydantic-ai",transport:Pu,model:$u.model,system_prompt:$u.systemPrompt||"You are a helpful AI assistant."};$u.agentSpecId&&(Ou.agent_spec_id=$u.agentSpecId),typeof $u.enableSkills=="boolean"&&(Ou.enable_skills=$u.enableSkills),Array.isArray($u.backendTools)&&(Ou.backend_tools=$u.backendTools),$u.inferenceProvider&&(Ou.inferenceProvider=$u.inferenceProvider),typeof $u.enableCodemode=="boolean"&&(Ou.enable_codemode=$u.enableCodemode),$u.sandboxVariant&&(Ou.sandbox_variant=$u.sandboxVariant),$u.jupyterSandbox&&(Ou.jupyter_sandbox=$u.jupyterSandbox),$u.createPayload&&typeof $u.createPayload=="object"&&Object.assign(Ou,$u.createPayload);const Mu=await fetch(`${Au}/api/v1/agents`,{method:"POST",headers:{"Content-Type":"application/json",...Iu?{Authorization:`Bearer ${Iu}`}:{}},body:JSON.stringify(Ou)});if(Mu.ok||Mu.status===400||Mu.status===409){const Lu=getTransportEndpoint(Au,Pu,lo);return{agentId:lo,endpoint:Lu,isReady:!0}}const Du=await Mu.json().catch(()=>({}));throw new Error(Du.detail||`Failed to create agent: ${Mu.status}`)}const initialRuntimeState={runtime:null,status:"idle",error:null,isLaunching:!1,historyVersion:0,toolDecisionRequest:null},initialWsState={wsState:"closed",approvals:[],pendingApprovalCount:0,subagentActivity:{},compaction:null,contextSnapshot:null,costUsage:null,mcpStatus:null,codemodeStatus:null,fullContext:null,monitoringCache:{},loadedSkillsByAgentId:{}},initialNotebookState={ephemeralNotebookModels:{},ephemeralDocumentModels:{},editorModeByRuntime:{}},countPendingApprovals=Au=>Au.filter(lo=>lo.status==="pending").length;let _ws=null;const _wsByAgentId=new Map;function _resolveWs(Au){const lo=_wsByAgentId.size>0;if(Au){const $u=_wsByAgentId.get(Au);if($u&&$u.readyState===WebSocket.OPEN)return $u;if(lo)return null}return lo?null:_ws&&_ws.readyState===WebSocket.OPEN?_ws:null}const agentRuntimeStore=createStore$1()(subscribeWithSelector(persist((Au,lo)=>({agents:[],upsertAgent:$u=>{Au(Ru=>{const Iu=Ru.agents.findIndex(Mu=>Mu.id===$u.id),Pu=Date.now();if(Iu>=0){const Mu=[...Ru.agents];return Mu[Iu]={...Mu[Iu],...$u,lastUpdated:Pu},{agents:Mu}}const Ou={name:$u.name||$u.id,description:$u.description||"",status:$u.status||"initializing",lastUpdated:Pu,...$u};return{agents:[...Ru.agents,Ou]}})},getAgentById:$u=>lo().agents.find(Ru=>Ru.id===$u),getAgentByUrl:($u,Ru)=>lo().agents.find(Iu=>Iu.baseUrl===$u&&Iu.protocol===Ru),updateAgentStatus:($u,Ru,Iu=null)=>{Au(Pu=>{const Ou=Pu.agents.findIndex(Mu=>Mu.id===$u);if(Ou>=0){const Mu=[...Pu.agents];return Mu[Ou]={...Mu[Ou],status:Ru,error:Iu,lastUpdated:Date.now()},{agents:Mu}}return{}})},toggleAgentStatus:$u=>{Au(Ru=>{const Iu=Ru.agents.findIndex(Pu=>Pu.id===$u);if(Iu>=0){const Pu=[...Ru.agents],Ou=Pu[Iu].status;return Pu[Iu]={...Pu[Iu],status:Ou==="running"?"paused":"running",lastUpdated:Date.now()},{agents:Pu}}return{}})},deleteAgent:$u=>{Au(Ru=>{const{[$u]:Iu,...Pu}=Ru.loadedSkillsByAgentId;return{agents:Ru.agents.filter(Ou=>Ou.id!==$u),loadedSkillsByAgentId:Pu}})},clearAgents:()=>{Au({agents:[]})},setLoadedSkillsForAgent:($u,Ru)=>{Au(Iu=>({loadedSkillsByAgentId:{...Iu.loadedSkillsByAgentId,[$u]:Ru}}))},getLoadedSkillsForAgent:$u=>lo().loadedSkillsByAgentId[$u]??[],clearLoadedSkillsForAgent:$u=>{Au(Ru=>{if(!($u in Ru.loadedSkillsByAgentId))return{};const{[$u]:Iu,...Pu}=Ru.loadedSkillsByAgentId;return{loadedSkillsByAgentId:Pu}})},setEphemeralNotebookModel:($u,Ru)=>{Au(Iu=>({ephemeralNotebookModels:{...Iu.ephemeralNotebookModels,[$u]:Ru}}))},getEphemeralNotebookModel:$u=>lo().ephemeralNotebookModels[$u]??null,clearEphemeralNotebookModel:$u=>{Au(Ru=>{if(!($u in Ru.ephemeralNotebookModels))return{};const{[$u]:Iu,...Pu}=Ru.ephemeralNotebookModels;return{ephemeralNotebookModels:Pu}})},setEphemeralDocumentModel:($u,Ru)=>{Au(Iu=>({ephemeralDocumentModels:{...Iu.ephemeralDocumentModels,[$u]:Ru}}))},getEphemeralDocumentModel:$u=>lo().ephemeralDocumentModels[$u]??null,clearEphemeralDocumentModel:$u=>{Au(Ru=>{if(!($u in Ru.ephemeralDocumentModels))return{};const{[$u]:Iu,...Pu}=Ru.ephemeralDocumentModels;return{ephemeralDocumentModels:Pu}})},setEditorMode:($u,Ru)=>{$u&&Au(Iu=>({editorModeByRuntime:{...Iu.editorModeByRuntime,[$u]:Ru}}))},getEditorMode:$u=>lo().editorModeByRuntime[$u]??null,...initialRuntimeState,connectAgent:$u=>{const Ru=$u.jupyterBaseUrl||$u.serviceManager?.serverSettings.baseUrl;if(!Ru)throw new Error("connectAgent requires either jupyterBaseUrl or serviceManager");const Iu=toAgentRuntimeBaseUrl(Ru);Au({runtime:{runtimeName:$u.runtimeName,environmentName:$u.environmentName,jupyterBaseUrl:Ru,agentBaseUrl:Iu,serviceManager:$u.serviceManager,status:"ready",kernelId:$u.kernelId},status:"ready",error:null})},launchAgent:async $u=>{Au({status:"launching",error:null,isLaunching:!0});try{const{createRuntime:Ru}=await __vitePreload(async()=>{const{createRuntime:ju}=await Promise.resolve().then(()=>actions);return{createRuntime:ju}},void 0,import.meta.url),{runtimesStore:Iu}=await __vitePreload(async()=>{const{runtimesStore:ju}=await import("./chunks/index-DiBcWu6d.js");return{runtimesStore:ju}},[],import.meta.url);$u.runtimesUrl&&Iu.setState({runtimesUrl:$u.runtimesUrl});const{runtimesUrl:Pu,...Ou}=$u,Mu=await Ru({environmentName:Ou.environmentName,creditsLimit:Ou.creditsLimit,type:Ou.type||"notebook",givenName:Ou.givenName,capabilities:Ou.capabilities,snapshot:Ou.snapshot,appSpec:Ou.appSpec,appUid:Ou.appUid,deploymentUid:Ou.deploymentUid});Au({status:"connecting"});const Du=Mu.ingress,Lu=toAgentRuntimeBaseUrl(Du),Bu={runtimeName:Mu.runtime_name,environmentName:Mu.environment.name,jupyterBaseUrl:Du,agentBaseUrl:Lu,status:"ready"};return Au({runtime:Bu,status:"ready",isLaunching:!1}),Bu}catch(Ru){const Iu=Ru instanceof Error?Ru.message:"Failed to launch runtime";throw Au({status:"error",error:Iu,isLaunching:!1}),Ru}},createAgent:async($u={})=>{const{runtime:Ru}=lo();if(!Ru)throw new Error("No runtime connected. Launch or connect to a runtime first.");try{const Iu=$u.name||Ru.runtimeName,Pu=await createAgentOnRuntime(Ru.agentBaseUrl,Iu,$u);return Au({runtime:{...Ru,agentId:Pu.agentId,endpoint:Pu.endpoint,isReady:Pu.isReady}}),Pu}catch(Iu){const Pu=Iu instanceof Error?Iu.message:"Failed to create agent";throw Au({error:Pu}),Iu}},disconnect:()=>{Au({runtime:null,status:"disconnected",error:null})},clearError:()=>Au({error:null}),setError:$u=>Au({error:$u,status:"error"}),...initialWsState,...initialNotebookState,setWsState:$u=>Au({wsState:$u}),setWs:($u,Ru)=>{_ws=$u,Ru&&($u?_wsByAgentId.set(Ru,$u):_wsByAgentId.delete(Ru))},applySnapshot:$u=>Au(Ru=>({approvals:Ru.approvals,pendingApprovalCount:Ru.pendingApprovalCount,contextSnapshot:$u.contextSnapshot??null,costUsage:$u.costUsage??null,mcpStatus:$u.mcpStatus??null,codemodeStatus:$u.codemodeStatus??null,fullContext:$u.fullContext??null})),appendSubagentEvent:$u=>Au(Ru=>{const Iu=$u.toolCallId??$u.subagentName,Pu=Ru.subagentActivity[Iu]??[];return Pu.some(Ou=>Ou.phase==="error"&&Ou.error===SUBAGENT_STOPPED)?{}:{subagentActivity:{...Ru.subagentActivity,[Iu]:[...Pu,$u]}}}),clearSubagentActivity:()=>Au({subagentActivity:{}}),stopSubagentActivity:()=>Au($u=>{let Ru=!1;const Iu={};for(const[Pu,Ou]of Object.entries($u.subagentActivity)){if(Ou.length===0||isSubagentRunOver(Ou)){Iu[Pu]=Ou;continue}Ru=!0,Iu[Pu]=[...Ou,{subagentName:Ou[0].subagentName,toolCallId:Ou[0].toolCallId??Pu,phase:"error",error:SUBAGENT_STOPPED,transport:Ou[0].transport}]}return Ru?{subagentActivity:Iu}:{}}),requestHistoryReload:()=>Au($u=>({historyVersion:$u.historyVersion+1})),requestToolDecision:$u=>Au(Ru=>({toolDecisionRequest:{seq:(Ru.toolDecisionRequest?.seq??0)+1,...$u}})),setCompaction:$u=>Au({compaction:$u}),upsertApproval:$u=>Au(Ru=>{const Iu=Ru.approvals.filter(Ou=>Ou.id!==$u.id),Pu=[$u,...Iu];return{approvals:Pu,pendingApprovalCount:countPendingApprovals(Pu)}}),removeApproval:$u=>Au(Ru=>{const Iu=Ru.approvals.filter(Pu=>Pu.id!==$u);return{approvals:Iu,pendingApprovalCount:countPendingApprovals(Iu)}}),sendDecision:($u,Ru,Iu,Pu,Ou)=>{const Mu=_resolveWs(Ou);return Mu?(Mu.send(JSON.stringify({type:"tool_approval_decision",approvalId:$u,approved:Ru,...Iu?{note:Iu}:{},...Pu?{toolCallId:Pu}:{}})),!0):!1},requestRefresh:$u=>{const Ru=_resolveWs($u);return Ru?(Ru.send(JSON.stringify({type:"request_snapshot"})),Ru.send(JSON.stringify({type:"request_otel_flush"})),!0):!1},sendRawMessage:($u,Ru)=>{const Iu=_resolveWs(Ru);return Iu?(Iu.send(JSON.stringify($u)),!0):!1},appendLocalTokenTurn:({serviceName:$u,agentId:Ru,timestampMs:Iu,promptTokens:Pu,completionTokens:Ou,totalTokens:Mu})=>{Au(Du=>{const Lu=getMonitoringCacheKey($u,Ru),Bu=Du.monitoringCache[Lu]??{tokenTurns:[],costPoints:[]},ju=[...Bu.tokenTurns],Fu=ju[ju.length-1];if(Fu&&Fu.userMessageTokens===Pu&&Fu.aiMessageTokens===Ou&&Fu.systemPromptTokens===0&&Fu.toolsDescriptionTokens===0&&Fu.toolsUsageTokens===0&&Fu.totalTokens===Mu)return ju[ju.length-1]={...Fu,timestampMs:Math.max(Fu.timestampMs,Iu)},{monitoringCache:{...Du.monitoringCache,[Lu]:{...Bu,tokenTurns:ju}}};const zu=(Fu?.turnNumber??0)+1;return ju.push({turnNumber:zu,timestampMs:Iu,systemPromptTokens:0,toolsDescriptionTokens:0,userMessageTokens:Pu,aiMessageTokens:Ou,toolsUsageTokens:0,totalTokens:Mu}),{monitoringCache:{...Du.monitoringCache,[Lu]:{...Bu,tokenTurns:ju}}}})},mergeTokenTurns:({serviceName:$u,agentId:Ru,turns:Iu})=>{Iu.length!==0&&Au(Pu=>{const Ou=getMonitoringCacheKey($u,Ru),Mu=Pu.monitoringCache[Ou]??{tokenTurns:[],costPoints:[]},Du=new Map;for(const Bu of Mu.tokenTurns)Du.set(Bu.turnNumber,Bu);for(const Bu of Iu)Du.set(Bu.turnNumber,Bu);const Lu=Array.from(Du.values()).sort((Bu,ju)=>Bu.turnNumber-ju.turnNumber);return{monitoringCache:{...Pu.monitoringCache,[Ou]:{...Mu,tokenTurns:Lu}}}})},appendLocalTokenTurnFull:({serviceName:$u,agentId:Ru,timestampMs:Iu,systemPromptTokens:Pu,toolsDescriptionTokens:Ou,userMessageTokens:Mu,aiMessageTokens:Du,toolsUsageTokens:Lu,totalTokens:Bu})=>{Au(ju=>{const Fu=getMonitoringCacheKey($u,Ru),zu=ju.monitoringCache[Fu]??{tokenTurns:[],costPoints:[]},Uu=[...zu.tokenTurns],Hu=Uu[Uu.length-1];if(Hu&&Hu.systemPromptTokens===Pu&&Hu.toolsDescriptionTokens===Ou&&Hu.userMessageTokens===Mu&&Hu.aiMessageTokens===Du&&Hu.toolsUsageTokens===Lu&&Hu.totalTokens===Bu)return Uu[Uu.length-1]={...Hu,timestampMs:Math.max(Hu.timestampMs,Iu)},{monitoringCache:{...ju.monitoringCache,[Fu]:{...zu,tokenTurns:Uu}}};const Vu=(Hu?.turnNumber??0)+1;return Uu.push({turnNumber:Vu,timestampMs:Iu,systemPromptTokens:Pu,toolsDescriptionTokens:Ou,userMessageTokens:Mu,aiMessageTokens:Du,toolsUsageTokens:Lu,totalTokens:Bu}),{monitoringCache:{...ju.monitoringCache,[Fu]:{...zu,tokenTurns:Uu}}}})},upsertLocalCostPoint:({serviceName:$u,agentId:Ru,timestampMs:Iu,cumulativeUsd:Pu})=>{Au(Ou=>{const Mu=getMonitoringCacheKey($u,Ru),Du=Ou.monitoringCache[Mu]??{tokenTurns:[],costPoints:[]},Lu=[...Du.costPoints],Bu=Lu.findIndex(ju=>Math.abs(ju.timestampMs-Iu)<1);return Bu>=0?Lu[Bu]={...Lu[Bu],cumulativeUsd:Math.max(Lu[Bu].cumulativeUsd,Pu)}:Lu.push({timestampMs:Iu,cumulativeUsd:Pu}),Lu.sort((ju,Fu)=>ju.timestampMs-Fu.timestampMs),{monitoringCache:{...Ou.monitoringCache,[Mu]:{...Du,costPoints:Lu}}}})},mergeCostPoints:({serviceName:$u,agentId:Ru,points:Iu})=>{Iu.length!==0&&Au(Pu=>{const Ou=getMonitoringCacheKey($u,Ru),Mu=Pu.monitoringCache[Ou]??{tokenTurns:[],costPoints:[]},Du=new Map;for(const Bu of Mu.costPoints)Du.set(Bu.timestampMs,Bu);for(const Bu of Iu){const ju=Du.get(Bu.timestampMs);ju?Du.set(Bu.timestampMs,{timestampMs:Bu.timestampMs,cumulativeUsd:Math.max(ju.cumulativeUsd,Bu.cumulativeUsd)}):Du.set(Bu.timestampMs,Bu)}const Lu=Array.from(Du.values()).sort((Bu,ju)=>Bu.timestampMs-ju.timestampMs);return{monitoringCache:{...Pu.monitoringCache,[Ou]:{...Mu,costPoints:Lu}}}})},reset:()=>{if(_ws)try{_ws.close(1e3,"reset")}catch{}_ws=null,_wsByAgentId.clear(),Au($u=>({...initialRuntimeState,...initialWsState,ephemeralNotebookModels:$u.ephemeralNotebookModels,ephemeralDocumentModels:$u.ephemeralDocumentModels,editorModeByRuntime:$u.editorModeByRuntime}))},resetWs:()=>{if(_ws)try{_ws.close(1e3,"reset")}catch{}_ws=null,_wsByAgentId.clear(),Au($u=>({...initialWsState,ephemeralNotebookModels:$u.ephemeralNotebookModels,ephemeralDocumentModels:$u.ephemeralDocumentModels,editorModeByRuntime:$u.editorModeByRuntime,subagentActivity:$u.subagentActivity}))}}),{name:"agent-runtimes-storage",storage:createJSONStorage(()=>localStorage),partialize:Au=>({agents:Au.agents.map(lo=>({id:lo.id,name:lo.name,description:lo.description,baseUrl:lo.baseUrl,transport:lo.protocol,status:lo.status,lastUpdated:lo.lastUpdated,documentId:lo.documentId,runtimeId:lo.runtimeId})),monitoringCache:Au.monitoringCache,loadedSkillsByAgentId:Au.loadedSkillsByAgentId,ephemeralNotebookModels:Au.ephemeralNotebookModels,ephemeralDocumentModels:Au.ephemeralDocumentModels,editorModeByRuntime:Au.editorModeByRuntime})})));function useAgentRuntimeStore(Au){return useStore$1(agentRuntimeStore,Au||($u=>$u))}const useAgentRuntimeStoreWithStatics=useAgentRuntimeStore;useAgentRuntimeStoreWithStatics.getState=agentRuntimeStore.getState;useAgentRuntimeStoreWithStatics.subscribe=agentRuntimeStore.subscribe;const useAgentRuntimeConnection=()=>useAgentRuntimeStore(Au=>Au.runtime),useAgentRuntimeStatus=()=>useAgentRuntimeStore(Au=>Au.status),useAgentRuntimeError=()=>useAgentRuntimeStore(Au=>Au.error),useAgentRuntimeIsLaunching=()=>useAgentRuntimeStore(Au=>Au.isLaunching),useAgentRuntimeMcpStatus=()=>useAgentRuntimeStore(Au=>Au.mcpStatus),useAgentRuntimeFullContext=()=>useAgentRuntimeStore(Au=>Au.fullContext),useAgentRuntimeContextSnapshot=()=>useAgentRuntimeStore(Au=>Au.contextSnapshot),useAgentRuntimeCodemodeStatus=()=>useAgentRuntimeStore(Au=>Au.codemodeStatus),useAgentRuntimeWsState=()=>useAgentRuntimeStore(Au=>Au.wsState),EMPTY_SUBAGENT_EVENTS=[],useAgentRuntimeSubagentActivity=Au=>useAgentRuntimeStore(lo=>Au?lo.subagentActivity[Au]??EMPTY_SUBAGENT_EVENTS:EMPTY_SUBAGENT_EVENTS),useAgentRuntimeSubagentActivityByToolCall=(Au,lo)=>useAgentRuntimeStore($u=>{if(Au){const Ru=$u.subagentActivity[Au];if(Ru&&Ru.length>0)return Ru}if(lo){const Ru=$u.subagentActivity[lo];if(Ru&&Ru.length>0)return Ru;let Iu;for(const Pu of Object.values($u.subagentActivity))Pu.length>0&&Pu[0]?.subagentName===lo&&(Iu=Pu);if(Iu)return Iu}return EMPTY_SUBAGENT_EVENTS}),useAgentRuntimeActiveSubagentToolCallId=()=>useAgentRuntimeStore(Au=>{let lo=null;for(const[$u,Ru]of Object.entries(Au.subagentActivity))Ru.length!==0&&(isSubagentRunOver(Ru)||(lo=$u));return lo});agentRuntimeStore.subscribe;async function requestAPI(Au="",lo={}){const $u=libExports$3.ServerConnection.makeSettings(),Ru=libExports$5.URLExt.join($u.baseUrl,"agent_runtimes",Au);let Iu;try{Iu=await libExports$3.ServerConnection.makeRequest(Ru,lo,$u)}catch(Ou){throw new libExports$3.ServerConnection.NetworkError(Ou)}let Pu=await Iu.text();if(Pu.length>0)try{Pu=JSON.parse(Pu)}catch{}if(!Iu.ok)throw new libExports$3.ServerConnection.ResponseError(Iu,Pu.message||Pu);return Pu}function useConfig(Au,lo,$u,Ru){return reactExports.useContext(QueryClientContext)?useQuery({queryFn:async()=>{if(lo){const Pu={"Content-Type":"application/json"};$u&&(Pu.Authorization=`Bearer ${$u}`);let Ou=lo;if(Ru){const Du=new URL(lo,window.location.origin);Du.searchParams.set("agent_id",Ru),Ou=Du.toString()}const Mu=await fetch(Ou,{headers:Pu});if(!Mu.ok)throw new Error(`Config fetch failed: ${Mu.statusText}`);return Mu.json()}return requestAPI("configure")},queryKey:["models",lo||"jupyter-server",Ru||"global"],enabled:Au,retry:1}):{data:void 0,isLoading:!1,isError:!1,error:null,refetch:()=>Promise.resolve({data:void 0})}}function parseSkillStatus(Au){return Au==="available"||Au==="enabled"||Au==="loaded"?Au:"available"}function useSkills(Au,lo,$u){const Ru=useAgentRuntimeCodemodeStatus(),Iu=reactExports.useMemo(()=>{if(!Ru)return;const Pu=(Ru.skills??[]).map(Ou=>({id:Ou.id??Ou.name,name:Ou.name,description:Ou.description,tags:Ou.tags,has_scripts:Ou.has_scripts,has_resources:Ou.has_resources,status:parseSkillStatus(Ou.status),approved:Ou.approved!==!1,skill_definition:Ou.skill_definition??null,source_variant:Ou.source_variant,module:Ou.module,package:Ou.package,method:Ou.method,path:Ou.path}));return{skills:Pu,total:Pu.length}},[Ru]);return{data:Iu,isLoading:!1,isError:!1,error:null,refetch:()=>Promise.resolve({data:Iu})}}function useSkillActions(Au){const lo=reactExports.useCallback(Pu=>{const Ou=agentRuntimeStore.getState().sendRawMessage({type:"skill_enable",skillId:Pu},Au);return Ou||console.warn("[useSkillActions] skill_enable dropped: websocket not ready"),Ou},[Au]),$u=reactExports.useCallback(Pu=>{const Ou=agentRuntimeStore.getState().sendRawMessage({type:"skill_disable",skillId:Pu},Au);return Ou||console.warn("[useSkillActions] skill_disable dropped: websocket not ready"),Ou},[Au]),Ru=reactExports.useCallback(Pu=>{const Ou=agentRuntimeStore.getState().sendRawMessage({type:"skill_approve",skillId:Pu},Au);return Ou||console.warn("[useSkillActions] skill_approve dropped: websocket not ready"),Ou},[Au]),Iu=reactExports.useCallback(Pu=>{const Ou=agentRuntimeStore.getState().sendRawMessage({type:"skill_unapprove",skillId:Pu},Au);return Ou||console.warn("[useSkillActions] skill_unapprove dropped: websocket not ready"),Ou},[Au]);return{enableSkill:lo,disableSkill:$u,approveSkill:Ru,unapproveSkill:Iu}}function useContextSnapshot(Au,lo,$u,Ru){return{data:useAgentRuntimeContextSnapshot()??void 0,isLoading:!1,isError:!1,error:null}}const RECONNECT_BASE_MS$1=1e3,RECONNECT_MAX_MS$1=3e4;function isRetryableCloseCode(Au){return!new Set([1002,1003,1007,1008,4401,4403]).has(Au)}function useSandbox(Au,lo,$u,Ru){const[Iu,Pu]=reactExports.useState(void 0),Ou=reactExports.useRef(null);reactExports.useEffect(()=>{if(!Au||!lo){Pu(void 0);return}const Du=getApiBaseFromConfig(lo);if(!Du)return;const Lu=Du.replace(/^http/,"ws"),Bu=[];Ru&&Bu.push(`agent_id=${encodeURIComponent(Ru)}`),$u&&Bu.push(`token=${encodeURIComponent($u)}`);const ju=`${Lu}/configure/sandbox/ws${Bu.length?`?${Bu.join("&")}`:""}`;let Fu=!1,zu,Uu=0;const Hu=Gu=>{if(Fu||!isRetryableCloseCode(Gu))return;const Wu=Math.min(RECONNECT_BASE_MS$1*2**Uu,RECONNECT_MAX_MS$1);Uu+=1,zu=setTimeout(Vu,Wu)},Vu=()=>{if(Fu)return;const Gu=new WebSocket(ju);Ou.current=Gu,Gu.onopen=()=>{Uu=0},Gu.onmessage=Wu=>{try{const Ku=JSON.parse(Wu.data);if(Ku&&Ku.action==="interrupt")return;const Ju=typeof Ku?.variant=="string"?Ku.variant:"";Pu({available:Ju!=="unavailable"&&Ju!=="error",sandbox_running:!!Ku?.sandbox_running,is_executing:!!Ku?.is_executing,variant:Ju})}catch{}},Gu.onclose=Wu=>{Ou.current=null,Hu(Wu.code)},Gu.onerror=()=>{Gu.close()}};return Vu(),()=>{Fu=!0,zu&&clearTimeout(zu),Ou.current?.close(),Ou.current=null,Pu(void 0)}},[Au,lo,$u,Ru]);const Mu=reactExports.useCallback(()=>{const Du=Ou.current;Du&&Du.readyState===WebSocket.OPEN&&Du.send(JSON.stringify({action:"interrupt"}))},[]);return{data:Iu,interrupt:Mu}}function _typeof$8(Au){"@babel/helpers - typeof";return _typeof$8=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(lo){return typeof lo}:function(lo){return lo&&typeof Symbol=="function"&&lo.constructor===Symbol&&lo!==Symbol.prototype?"symbol":typeof lo},_typeof$8(Au)}function _createClass$8(Au,lo,$u){return Object.defineProperty(Au,"prototype",{writable:!1}),Au}function _classCallCheck$8(Au,lo){if(!(Au instanceof lo))throw new TypeError("Cannot call a class as a function")}function _callSuper$1(Au,lo,$u){return lo=_getPrototypeOf$1(lo),_possibleConstructorReturn$1(Au,_isNativeReflectConstruct$1()?Reflect.construct(lo,$u||[],_getPrototypeOf$1(Au).constructor):lo.apply(Au,$u))}function _possibleConstructorReturn$1(Au,lo){if(lo&&(_typeof$8(lo)==="object"||typeof lo=="function"))return lo;if(lo!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return _assertThisInitialized$1(Au)}function _assertThisInitialized$1(Au){if(Au===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return Au}function _inherits$1(Au,lo){if(typeof lo!="function"&&lo!==null)throw new TypeError("Super expression must either be null or a function");Au.prototype=Object.create(lo&&lo.prototype,{constructor:{value:Au,writable:!0,configurable:!0}}),Object.defineProperty(Au,"prototype",{writable:!1}),lo&&_setPrototypeOf$1(Au,lo)}function _wrapNativeSuper(Au){var lo=typeof Map=="function"?new Map:void 0;return _wrapNativeSuper=function(Ru){if(Ru===null||!_isNativeFunction(Ru))return Ru;if(typeof Ru!="function")throw new TypeError("Super expression must either be null or a function");if(typeof lo<"u"){if(lo.has(Ru))return lo.get(Ru);lo.set(Ru,Iu)}function Iu(){return _construct(Ru,arguments,_getPrototypeOf$1(this).constructor)}return Iu.prototype=Object.create(Ru.prototype,{constructor:{value:Iu,enumerable:!1,writable:!0,configurable:!0}}),_setPrototypeOf$1(Iu,Ru)},_wrapNativeSuper(Au)}function _construct(Au,lo,$u){if(_isNativeReflectConstruct$1())return Reflect.construct.apply(null,arguments);var Ru=[null];Ru.push.apply(Ru,lo);var Iu=new(Au.bind.apply(Au,Ru));return $u&&_setPrototypeOf$1(Iu,$u.prototype),Iu}function _isNativeReflectConstruct$1(){try{var Au=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(_isNativeReflectConstruct$1=function(){return!!Au})()}function _isNativeFunction(Au){try{return Function.toString.call(Au).indexOf("[native code]")!==-1}catch{return typeof Au=="function"}}function _setPrototypeOf$1(Au,lo){return _setPrototypeOf$1=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(Ru,Iu){return Ru.__proto__=Iu,Ru},_setPrototypeOf$1(Au,lo)}function _getPrototypeOf$1(Au){return _getPrototypeOf$1=Object.setPrototypeOf?Object.getPrototypeOf.bind():function($u){return $u.__proto__||Object.getPrototypeOf($u)},_getPrototypeOf$1(Au)}var DetailedError=(function(Au){function lo($u){var Ru,Iu=arguments.length>1&&arguments[1]!==void 0?arguments[1]:null,Pu=arguments.length>2&&arguments[2]!==void 0?arguments[2]:null,Ou=arguments.length>3&&arguments[3]!==void 0?arguments[3]:null;if(_classCallCheck$8(this,lo),Ru=_callSuper$1(this,lo,[$u]),Ru.originalRequest=Pu,Ru.originalResponse=Ou,Ru.causingError=Iu,Iu!=null&&($u+=", caused by ".concat(Iu.toString())),Pu!=null){var Mu=Pu.getHeader("X-Request-ID")||"n/a",Du=Pu.getMethod(),Lu=Pu.getURL(),Bu=Ou?Ou.getStatus():"n/a",ju=Ou?Ou.getBody()||"":"n/a";$u+=", originated from request (method: ".concat(Du,", url: ").concat(Lu,", response code: ").concat(Bu,", response text: ").concat(ju,", request id: ").concat(Mu,")")}return Ru.message=$u,Ru}return _inherits$1(lo,Au),_createClass$8(lo)})(_wrapNativeSuper(Error));function log(Au){}function _typeof$7(Au){"@babel/helpers - typeof";return _typeof$7=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(lo){return typeof lo}:function(lo){return lo&&typeof Symbol=="function"&&lo.constructor===Symbol&&lo!==Symbol.prototype?"symbol":typeof lo},_typeof$7(Au)}function _classCallCheck$7(Au,lo){if(!(Au instanceof lo))throw new TypeError("Cannot call a class as a function")}function _defineProperties$7(Au,lo){for(var $u=0;$u<lo.length;$u++){var Ru=lo[$u];Ru.enumerable=Ru.enumerable||!1,Ru.configurable=!0,"value"in Ru&&(Ru.writable=!0),Object.defineProperty(Au,_toPropertyKey$7(Ru.key),Ru)}}function _createClass$7(Au,lo,$u){return lo&&_defineProperties$7(Au.prototype,lo),Object.defineProperty(Au,"prototype",{writable:!1}),Au}function _toPropertyKey$7(Au){var lo=_toPrimitive$7(Au,"string");return _typeof$7(lo)=="symbol"?lo:lo+""}function _toPrimitive$7(Au,lo){if(_typeof$7(Au)!="object"||!Au)return Au;var $u=Au[Symbol.toPrimitive];if($u!==void 0){var Ru=$u.call(Au,lo);if(_typeof$7(Ru)!="object")return Ru;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(Au)}var NoopUrlStorage=(function(){function Au(){_classCallCheck$7(this,Au)}return _createClass$7(Au,[{key:"listAllUploads",value:function(){return Promise.resolve([])}},{key:"findUploadsByFingerprint",value:function($u){return Promise.resolve([])}},{key:"removeUpload",value:function($u){return Promise.resolve()}},{key:"addUpload",value:function($u,Ru){return Promise.resolve(null)}}])})();const version$1="3.9.4",VERSION=version$1,_TD=typeof TextDecoder=="function"?new TextDecoder("utf-8",{ignoreBOM:!0}):void 0,_TE=typeof TextEncoder=="function"?new TextEncoder:void 0,b64ch="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",b64chs=Array.prototype.slice.call(b64ch),b64tab=(Au=>{let lo={};return Au.forEach(($u,Ru)=>lo[$u]=Ru),lo})(b64chs),b64re=/^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/,_fromCC=String.fromCharCode.bind(String),_U8Afrom=typeof Uint8Array.from=="function"?Uint8Array.from.bind(Uint8Array):Au=>new Uint8Array(Array.prototype.slice.call(Au,0)),_mkUriSafe=Au=>Au.replace(/=/g,"").replace(/[+\/]/g,lo=>lo=="+"?"-":"_"),_tidyB64=Au=>Au.replace(/[^A-Za-z0-9\+\/]/g,""),btoaPolyfill=Au=>{let lo,$u,Ru,Iu,Pu="";const Ou=Au.length%3;for(let Mu=0;Mu<Au.length;){if(($u=Au.charCodeAt(Mu++))>255||(Ru=Au.charCodeAt(Mu++))>255||(Iu=Au.charCodeAt(Mu++))>255)throw new TypeError("invalid character found");lo=$u<<16|Ru<<8|Iu,Pu+=b64chs[lo>>18&63]+b64chs[lo>>12&63]+b64chs[lo>>6&63]+b64chs[lo&63]}return Ou?Pu.slice(0,Ou-3)+"===".substring(Ou):Pu},_btoa=typeof btoa=="function"?Au=>btoa(Au):btoaPolyfill,_fromUint8Array=typeof Uint8Array.prototype.toBase64=="function"?Au=>Au.toBase64():Au=>{let $u=[];for(let Ru=0,Iu=Au.length;Ru<Iu;Ru+=4096)$u.push(_fromCC.apply(null,Au.subarray(Ru,Ru+4096)));return _btoa($u.join(""))},fromUint8Array=(Au,lo=!1)=>lo?_mkUriSafe(_fromUint8Array(Au)):_fromUint8Array(Au),cb_utob=Au=>{if(Au.length<2){var lo=Au.charCodeAt(0);return lo<128?Au:lo<2048?_fromCC(192|lo>>>6)+_fromCC(128|lo&63):_fromCC(224|lo>>>12&15)+_fromCC(128|lo>>>6&63)+_fromCC(128|lo&63)}else{var lo=65536+(Au.charCodeAt(0)-55296)*1024+(Au.charCodeAt(1)-56320);return _fromCC(240|lo>>>18&7)+_fromCC(128|lo>>>12&63)+_fromCC(128|lo>>>6&63)+_fromCC(128|lo&63)}},re_utob=/[\uD800-\uDBFF][\uDC00-\uDFFF]|[^\x00-\x7F]/g,utob=Au=>Au.replace(re_utob,cb_utob),_encode=_TE?Au=>_fromUint8Array(_TE.encode(Au)):Au=>_btoa(utob(Au)),encode$2=(Au,lo=!1)=>lo?_mkUriSafe(_encode(Au)):_encode(Au),encodeURI$1=Au=>encode$2(Au,!0),re_btou=/[\xC0-\xDF][\x80-\xBF]|[\xE0-\xEF][\x80-\xBF]{2}|[\xF0-\xF7][\x80-\xBF]{3}/g,cb_btou=Au=>{switch(Au.length){case 4:var lo=(7&Au.charCodeAt(0))<<18|(63&Au.charCodeAt(1))<<12|(63&Au.charCodeAt(2))<<6|63&Au.charCodeAt(3),$u=lo-65536;return _fromCC(($u>>>10)+55296)+_fromCC(($u&1023)+56320);case 3:return _fromCC((15&Au.charCodeAt(0))<<12|(63&Au.charCodeAt(1))<<6|63&Au.charCodeAt(2));default:return _fromCC((31&Au.charCodeAt(0))<<6|63&Au.charCodeAt(1))}},btou=Au=>Au.replace(re_btou,cb_btou),atobPolyfill=Au=>{if(Au=Au.replace(/\s+/g,""),!b64re.test(Au))throw new TypeError("malformed base64.");Au+="==".slice(2-(Au.length&3));let lo,$u,Ru,Iu=[];for(let Pu=0;Pu<Au.length;)lo=b64tab[Au.charAt(Pu++)]<<18|b64tab[Au.charAt(Pu++)]<<12|($u=b64tab[Au.charAt(Pu++)])<<6|(Ru=b64tab[Au.charAt(Pu++)]),$u===64?Iu.push(_fromCC(lo>>16&255)):Ru===64?Iu.push(_fromCC(lo>>16&255,lo>>8&255)):Iu.push(_fromCC(lo>>16&255,lo>>8&255,lo&255));return Iu.join("")},_atob=typeof atob=="function"?Au=>atob(_tidyB64(Au)):atobPolyfill,_toUint8Array=typeof Uint8Array.fromBase64=="function"?Au=>Uint8Array.fromBase64(Au):Au=>_U8Afrom(_atob(Au).split("").map(lo=>lo.charCodeAt(0))),toUint8Array=Au=>_toUint8Array(_unURI(Au)),_decode=_TD?Au=>_TD.decode(_toUint8Array(Au)):Au=>btou(_atob(Au)),_unURI=Au=>_tidyB64(Au.replace(/[-_]/g,lo=>lo=="-"?"+":"/")),decode$3=Au=>_decode(_unURI(Au)),isValid$1=Au=>{if(typeof Au!="string")return!1;const lo=Au.replace(/\s+/g,"").replace(/={0,2}$/,"");return!/[^\s0-9a-zA-Z\+/]/.test(lo)||!/[^\s0-9a-zA-Z\-_]/.test(lo)},_noEnum=Au=>({value:Au,enumerable:!1,writable:!0,configurable:!0}),extendString=function(){const Au=(lo,$u)=>Object.defineProperty(String.prototype,lo,_noEnum($u));Au("fromBase64",function(){return decode$3(this)}),Au("toBase64",function(lo){return encode$2(this,lo)}),Au("toBase64URI",function(){return encode$2(this,!0)}),Au("toBase64URL",function(){return encode$2(this,!0)}),Au("toUint8Array",function(){return toUint8Array(this)})},extendUint8Array=function(){const Au=(lo,$u)=>Object.defineProperty(Uint8Array.prototype,lo,_noEnum($u));Au("toBase64",function(lo){return fromUint8Array(this,lo)}),Au("toBase64URI",function(){return fromUint8Array(this,!0)}),Au("toBase64URL",function(){return fromUint8Array(this,!0)})},extendBuiltins=()=>{extendString(),extendUint8Array()},gBase64={version:version$1,VERSION,atob:_atob,atobPolyfill,btoa:_btoa,btoaPolyfill,fromBase64:decode$3,toBase64:encode$2,encode:encode$2,encodeURI:encodeURI$1,encodeURL:encodeURI$1,utob,btou,decode:decode$3,isValid:isValid$1,fromUint8Array,toUint8Array,extendString,extendUint8Array,extendBuiltins};var urlParseExports=requireUrlParse();const URL$1=getDefaultExportFromCjs(urlParseExports);function uuid(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(Au){var lo=Math.random()*16|0,$u=Au==="x"?lo:lo&3|8;return $u.toString(16)})}function _regeneratorRuntime$1(){_regeneratorRuntime$1=function(){return lo};var Au,lo={},$u=Object.prototype,Ru=$u.hasOwnProperty,Iu=Object.defineProperty||function(_d,vd,wd){_d[vd]=wd.value},Pu=typeof Symbol=="function"?Symbol:{},Ou=Pu.iterator||"@@iterator",Mu=Pu.asyncIterator||"@@asyncIterator",Du=Pu.toStringTag||"@@toStringTag";function Lu(_d,vd,wd){return Object.defineProperty(_d,vd,{value:wd,enumerable:!0,configurable:!0,writable:!0}),_d[vd]}try{Lu({},"")}catch{Lu=function(wd,Ed,cd){return wd[Ed]=cd}}function Bu(_d,vd,wd,Ed){var cd=vd&&vd.prototype instanceof Gu?vd:Gu,dd=Object.create(cd.prototype),md=new gd(Ed||[]);return Iu(dd,"_invoke",{value:od(_d,wd,md)}),dd}function ju(_d,vd,wd){try{return{type:"normal",arg:_d.call(vd,wd)}}catch(Ed){return{type:"throw",arg:Ed}}}lo.wrap=Bu;var Fu="suspendedStart",zu="suspendedYield",Uu="executing",Hu="completed",Vu={};function Gu(){}function Wu(){}function Ku(){}var Ju={};Lu(Ju,Ou,function(){return this});var Yu=Object.getPrototypeOf,Xu=Yu&&Yu(Yu(yd([])));Xu&&Xu!==$u&&Ru.call(Xu,Ou)&&(Ju=Xu);var ed=Ku.prototype=Gu.prototype=Object.create(Ju);function td(_d){["next","throw","return"].forEach(function(vd){Lu(_d,vd,function(wd){return this._invoke(vd,wd)})})}function nd(_d,vd){function wd(cd,dd,md,ld){var hd=ju(_d[cd],_d,dd);if(hd.type!=="throw"){var bd=hd.arg,Sd=bd.value;return Sd&&_typeof$6(Sd)=="object"&&Ru.call(Sd,"__await")?vd.resolve(Sd.__await).then(function(kd){wd("next",kd,md,ld)},function(kd){wd("throw",kd,md,ld)}):vd.resolve(Sd).then(function(kd){bd.value=kd,md(bd)},function(kd){return wd("throw",kd,md,ld)})}ld(hd.arg)}var Ed;Iu(this,"_invoke",{value:function(dd,md){function ld(){return new vd(function(hd,bd){wd(dd,md,hd,bd)})}return Ed=Ed?Ed.then(ld,ld):ld()}})}function od(_d,vd,wd){var Ed=Fu;return function(cd,dd){if(Ed===Uu)throw Error("Generator is already running");if(Ed===Hu){if(cd==="throw")throw dd;return{value:Au,done:!0}}for(wd.method=cd,wd.arg=dd;;){var md=wd.delegate;if(md){var ld=sd(md,wd);if(ld){if(ld===Vu)continue;return ld}}if(wd.method==="next")wd.sent=wd._sent=wd.arg;else if(wd.method==="throw"){if(Ed===Fu)throw Ed=Hu,wd.arg;wd.dispatchException(wd.arg)}else wd.method==="return"&&wd.abrupt("return",wd.arg);Ed=Uu;var hd=ju(_d,vd,wd);if(hd.type==="normal"){if(Ed=wd.done?Hu:zu,hd.arg===Vu)continue;return{value:hd.arg,done:wd.done}}hd.type==="throw"&&(Ed=Hu,wd.method="throw",wd.arg=hd.arg)}}}function sd(_d,vd){var wd=vd.method,Ed=_d.iterator[wd];if(Ed===Au)return vd.delegate=null,wd==="throw"&&_d.iterator.return&&(vd.method="return",vd.arg=Au,sd(_d,vd),vd.method==="throw")||wd!=="return"&&(vd.method="throw",vd.arg=new TypeError("The iterator does not provide a '"+wd+"' method")),Vu;var cd=ju(Ed,_d.iterator,vd.arg);if(cd.type==="throw")return vd.method="throw",vd.arg=cd.arg,vd.delegate=null,Vu;var dd=cd.arg;return dd?dd.done?(vd[_d.resultName]=dd.value,vd.next=_d.nextLoc,vd.method!=="return"&&(vd.method="next",vd.arg=Au),vd.delegate=null,Vu):dd:(vd.method="throw",vd.arg=new TypeError("iterator result is not an object"),vd.delegate=null,Vu)}function ad(_d){var vd={tryLoc:_d[0]};1 in _d&&(vd.catchLoc=_d[1]),2 in _d&&(vd.finallyLoc=_d[2],vd.afterLoc=_d[3]),this.tryEntries.push(vd)}function pd(_d){var vd=_d.completion||{};vd.type="normal",delete vd.arg,_d.completion=vd}function gd(_d){this.tryEntries=[{tryLoc:"root"}],_d.forEach(ad,this),this.reset(!0)}function yd(_d){if(_d||_d===""){var vd=_d[Ou];if(vd)return vd.call(_d);if(typeof _d.next=="function")return _d;if(!isNaN(_d.length)){var wd=-1,Ed=function cd(){for(;++wd<_d.length;)if(Ru.call(_d,wd))return cd.value=_d[wd],cd.done=!1,cd;return cd.value=Au,cd.done=!0,cd};return Ed.next=Ed}}throw new TypeError(_typeof$6(_d)+" is not iterable")}return Wu.prototype=Ku,Iu(ed,"constructor",{value:Ku,configurable:!0}),Iu(Ku,"constructor",{value:Wu,configurable:!0}),Wu.displayName=Lu(Ku,Du,"GeneratorFunction"),lo.isGeneratorFunction=function(_d){var vd=typeof _d=="function"&&_d.constructor;return!!vd&&(vd===Wu||(vd.displayName||vd.name)==="GeneratorFunction")},lo.mark=function(_d){return Object.setPrototypeOf?Object.setPrototypeOf(_d,Ku):(_d.__proto__=Ku,Lu(_d,Du,"GeneratorFunction")),_d.prototype=Object.create(ed),_d},lo.awrap=function(_d){return{__await:_d}},td(nd.prototype),Lu(nd.prototype,Mu,function(){return this}),lo.AsyncIterator=nd,lo.async=function(_d,vd,wd,Ed,cd){cd===void 0&&(cd=Promise);var dd=new nd(Bu(_d,vd,wd,Ed),cd);return lo.isGeneratorFunction(vd)?dd:dd.next().then(function(md){return md.done?md.value:dd.next()})},td(ed),Lu(ed,Du,"Generator"),Lu(ed,Ou,function(){return this}),Lu(ed,"toString",function(){return"[object Generator]"}),lo.keys=function(_d){var vd=Object(_d),wd=[];for(var Ed in vd)wd.push(Ed);return wd.reverse(),function cd(){for(;wd.length;){var dd=wd.pop();if(dd in vd)return cd.value=dd,cd.done=!1,cd}return cd.done=!0,cd}},lo.values=yd,gd.prototype={constructor:gd,reset:function(vd){if(this.prev=0,this.next=0,this.sent=this._sent=Au,this.done=!1,this.delegate=null,this.method="next",this.arg=Au,this.tryEntries.forEach(pd),!vd)for(var wd in this)wd.charAt(0)==="t"&&Ru.call(this,wd)&&!isNaN(+wd.slice(1))&&(this[wd]=Au)},stop:function(){this.done=!0;var vd=this.tryEntries[0].completion;if(vd.type==="throw")throw vd.arg;return this.rval},dispatchException:function(vd){if(this.done)throw vd;var wd=this;function Ed(bd,Sd){return md.type="throw",md.arg=vd,wd.next=bd,Sd&&(wd.method="next",wd.arg=Au),!!Sd}for(var cd=this.tryEntries.length-1;cd>=0;--cd){var dd=this.tryEntries[cd],md=dd.completion;if(dd.tryLoc==="root")return Ed("end");if(dd.tryLoc<=this.prev){var ld=Ru.call(dd,"catchLoc"),hd=Ru.call(dd,"finallyLoc");if(ld&&hd){if(this.prev<dd.catchLoc)return Ed(dd.catchLoc,!0);if(this.prev<dd.finallyLoc)return Ed(dd.finallyLoc)}else if(ld){if(this.prev<dd.catchLoc)return Ed(dd.catchLoc,!0)}else{if(!hd)throw Error("try statement without catch or finally");if(this.prev<dd.finallyLoc)return Ed(dd.finallyLoc)}}}},abrupt:function(vd,wd){for(var Ed=this.tryEntries.length-1;Ed>=0;--Ed){var cd=this.tryEntries[Ed];if(cd.tryLoc<=this.prev&&Ru.call(cd,"finallyLoc")&&this.prev<cd.finallyLoc){var dd=cd;break}}dd&&(vd==="break"||vd==="continue")&&dd.tryLoc<=wd&&wd<=dd.finallyLoc&&(dd=null);var md=dd?dd.completion:{};return md.type=vd,md.arg=wd,dd?(this.method="next",this.next=dd.finallyLoc,Vu):this.complete(md)},complete:function(vd,wd){if(vd.type==="throw")throw vd.arg;return vd.type==="break"||vd.type==="continue"?this.next=vd.arg:vd.type==="return"?(this.rval=this.arg=vd.arg,this.method="return",this.next="end"):vd.type==="normal"&&wd&&(this.next=wd),Vu},finish:function(vd){for(var wd=this.tryEntries.length-1;wd>=0;--wd){var Ed=this.tryEntries[wd];if(Ed.finallyLoc===vd)return this.complete(Ed.completion,Ed.afterLoc),pd(Ed),Vu}},catch:function(vd){for(var wd=this.tryEntries.length-1;wd>=0;--wd){var Ed=this.tryEntries[wd];if(Ed.tryLoc===vd){var cd=Ed.completion;if(cd.type==="throw"){var dd=cd.arg;pd(Ed)}return dd}}throw Error("illegal catch attempt")},delegateYield:function(vd,wd,Ed){return this.delegate={iterator:yd(vd),resultName:wd,nextLoc:Ed},this.method==="next"&&(this.arg=Au),Vu}},lo}function asyncGeneratorStep$1(Au,lo,$u,Ru,Iu,Pu,Ou){try{var Mu=Au[Pu](Ou),Du=Mu.value}catch(Lu){$u(Lu);return}Mu.done?lo(Du):Promise.resolve(Du).then(Ru,Iu)}function _asyncToGenerator$1(Au){return function(){var lo=this,$u=arguments;return new Promise(function(Ru,Iu){var Pu=Au.apply(lo,$u);function Ou(Du){asyncGeneratorStep$1(Pu,Ru,Iu,Ou,Mu,"next",Du)}function Mu(Du){asyncGeneratorStep$1(Pu,Ru,Iu,Ou,Mu,"throw",Du)}Ou(void 0)})}}function _slicedToArray$1(Au,lo){return _arrayWithHoles$1(Au)||_iterableToArrayLimit$1(Au,lo)||_unsupportedIterableToArray$1(Au,lo)||_nonIterableRest$1()}function _nonIterableRest$1(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
2198
2198
  In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function _iterableToArrayLimit$1(Au,lo){var $u=Au==null?null:typeof Symbol<"u"&&Au[Symbol.iterator]||Au["@@iterator"];if($u!=null){var Ru,Iu,Pu,Ou,Mu=[],Du=!0,Lu=!1;try{if(Pu=($u=$u.call(Au)).next,lo!==0)for(;!(Du=(Ru=Pu.call($u)).done)&&(Mu.push(Ru.value),Mu.length!==lo);Du=!0);}catch(Bu){Lu=!0,Iu=Bu}finally{try{if(!Du&&$u.return!=null&&(Ou=$u.return(),Object(Ou)!==Ou))return}finally{if(Lu)throw Iu}}return Mu}}function _arrayWithHoles$1(Au){if(Array.isArray(Au))return Au}function _typeof$6(Au){"@babel/helpers - typeof";return _typeof$6=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(lo){return typeof lo}:function(lo){return lo&&typeof Symbol=="function"&&lo.constructor===Symbol&&lo!==Symbol.prototype?"symbol":typeof lo},_typeof$6(Au)}function _createForOfIteratorHelper(Au,lo){var $u=typeof Symbol<"u"&&Au[Symbol.iterator]||Au["@@iterator"];if(!$u){if(Array.isArray(Au)||($u=_unsupportedIterableToArray$1(Au))||lo){$u&&(Au=$u);var Ru=0,Iu=function(){};return{s:Iu,n:function(){return Ru>=Au.length?{done:!0}:{done:!1,value:Au[Ru++]}},e:function(Lu){throw Lu},f:Iu}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
2199
2199
  In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var Pu=!0,Ou=!1,Mu;return{s:function(){$u=$u.call(Au)},n:function(){var Lu=$u.next();return Pu=Lu.done,Lu},e:function(Lu){Ou=!0,Mu=Lu},f:function(){try{!Pu&&$u.return!=null&&$u.return()}finally{if(Ou)throw Mu}}}}function _unsupportedIterableToArray$1(Au,lo){if(Au){if(typeof Au=="string")return _arrayLikeToArray$1(Au,lo);var $u=Object.prototype.toString.call(Au).slice(8,-1);if($u==="Object"&&Au.constructor&&($u=Au.constructor.name),$u==="Map"||$u==="Set")return Array.from(Au);if($u==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test($u))return _arrayLikeToArray$1(Au,lo)}}function _arrayLikeToArray$1(Au,lo){(lo==null||lo>Au.length)&&(lo=Au.length);for(var $u=0,Ru=new Array(lo);$u<lo;$u++)Ru[$u]=Au[$u];return Ru}function ownKeys$1(Au,lo){var $u=Object.keys(Au);if(Object.getOwnPropertySymbols){var Ru=Object.getOwnPropertySymbols(Au);lo&&(Ru=Ru.filter(function(Iu){return Object.getOwnPropertyDescriptor(Au,Iu).enumerable})),$u.push.apply($u,Ru)}return $u}function _objectSpread$1(Au){for(var lo=1;lo<arguments.length;lo++){var $u=arguments[lo]!=null?arguments[lo]:{};lo%2?ownKeys$1(Object($u),!0).forEach(function(Ru){_defineProperty$1(Au,Ru,$u[Ru])}):Object.getOwnPropertyDescriptors?Object.defineProperties(Au,Object.getOwnPropertyDescriptors($u)):ownKeys$1(Object($u)).forEach(function(Ru){Object.defineProperty(Au,Ru,Object.getOwnPropertyDescriptor($u,Ru))})}return Au}function _defineProperty$1(Au,lo,$u){return lo=_toPropertyKey$6(lo),lo in Au?Object.defineProperty(Au,lo,{value:$u,enumerable:!0,configurable:!0,writable:!0}):Au[lo]=$u,Au}function _classCallCheck$6(Au,lo){if(!(Au instanceof lo))throw new TypeError("Cannot call a class as a function")}function _defineProperties$6(Au,lo){for(var $u=0;$u<lo.length;$u++){var Ru=lo[$u];Ru.enumerable=Ru.enumerable||!1,Ru.configurable=!0,"value"in Ru&&(Ru.writable=!0),Object.defineProperty(Au,_toPropertyKey$6(Ru.key),Ru)}}function _createClass$6(Au,lo,$u){return lo&&_defineProperties$6(Au.prototype,lo),$u&&_defineProperties$6(Au,$u),Object.defineProperty(Au,"prototype",{writable:!1}),Au}function _toPropertyKey$6(Au){var lo=_toPrimitive$6(Au,"string");return _typeof$6(lo)=="symbol"?lo:lo+""}function _toPrimitive$6(Au,lo){if(_typeof$6(Au)!="object"||!Au)return Au;var $u=Au[Symbol.toPrimitive];if($u!==void 0){var Ru=$u.call(Au,lo);if(_typeof$6(Ru)!="object")return Ru;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(Au)}var PROTOCOL_TUS_V1="tus-v1",PROTOCOL_IETF_DRAFT_03="ietf-draft-03",PROTOCOL_IETF_DRAFT_05="ietf-draft-05",defaultOptions$2={endpoint:null,uploadUrl:null,metadata:{},metadataForPartialUploads:{},fingerprint:null,uploadSize:null,onProgress:null,onChunkComplete:null,onSuccess:null,onError:null,onUploadUrlAvailable:null,overridePatchMethod:!1,headers:{},addRequestId:!1,onBeforeRequest:null,onAfterResponse:null,onShouldRetry:defaultOnShouldRetry,chunkSize:Number.POSITIVE_INFINITY,retryDelays:[0,1e3,3e3,5e3],parallelUploads:1,parallelUploadBoundaries:null,storeFingerprintForResuming:!0,removeFingerprintOnSuccess:!1,uploadLengthDeferred:!1,uploadDataDuringCreation:!1,urlStorage:null,fileReader:null,httpStack:null,protocol:PROTOCOL_TUS_V1},BaseUpload=(function(){function Au(lo,$u){_classCallCheck$6(this,Au),"resume"in $u&&console.log("tus: The `resume` option has been removed in tus-js-client v2. Please use the URL storage API instead."),this.options=$u,this.options.chunkSize=Number(this.options.chunkSize),this._urlStorage=this.options.urlStorage,this.file=lo,this.url=null,this._req=null,this._fingerprint=null,this._urlStorageKey=null,this._offset=null,this._aborted=!1,this._size=null,this._source=null,this._retryAttempt=0,this._retryTimeout=null,this._offsetBeforeRetry=0,this._parallelUploads=null,this._parallelUploadUrls=null}return _createClass$6(Au,[{key:"findPreviousUploads",value:function(){var $u=this;return this.options.fingerprint(this.file,this.options).then(function(Ru){return $u._urlStorage.findUploadsByFingerprint(Ru)})}},{key:"resumeFromPreviousUpload",value:function($u){this.url=$u.uploadUrl||null,this._parallelUploadUrls=$u.parallelUploadUrls||null,this._urlStorageKey=$u.urlStorageKey}},{key:"start",value:function(){var $u=this,Ru=this.file;if(!Ru){this._emitError(new Error("tus: no file or stream to upload provided"));return}if(![PROTOCOL_TUS_V1,PROTOCOL_IETF_DRAFT_03,PROTOCOL_IETF_DRAFT_05].includes(this.options.protocol)){this._emitError(new Error("tus: unsupported protocol ".concat(this.options.protocol)));return}if(!this.options.endpoint&&!this.options.uploadUrl&&!this.url){this._emitError(new Error("tus: neither an endpoint or an upload URL is provided"));return}var Iu=this.options.retryDelays;if(Iu!=null&&Object.prototype.toString.call(Iu)!=="[object Array]"){this._emitError(new Error("tus: the `retryDelays` option must either be an array or null"));return}if(this.options.parallelUploads>1)for(var Pu=0,Ou=["uploadUrl","uploadSize","uploadLengthDeferred"];Pu<Ou.length;Pu++){var Mu=Ou[Pu];if(this.options[Mu]){this._emitError(new Error("tus: cannot use the ".concat(Mu," option when parallelUploads is enabled")));return}}if(this.options.parallelUploadBoundaries){if(this.options.parallelUploads<=1){this._emitError(new Error("tus: cannot use the `parallelUploadBoundaries` option when `parallelUploads` is disabled"));return}if(this.options.parallelUploads!==this.options.parallelUploadBoundaries.length){this._emitError(new Error("tus: the `parallelUploadBoundaries` must have the same length as the value of `parallelUploads`"));return}}this.options.fingerprint(Ru,this.options).then(function(Du){return $u._fingerprint=Du,$u._source?$u._source:$u.options.fileReader.openFile(Ru,$u.options.chunkSize)}).then(function(Du){if($u._source=Du,$u.options.uploadLengthDeferred)$u._size=null;else if($u.options.uploadSize!=null){if($u._size=Number($u.options.uploadSize),Number.isNaN($u._size)){$u._emitError(new Error("tus: cannot convert `uploadSize` option into a number"));return}}else if($u._size=$u._source.size,$u._size==null){$u._emitError(new Error("tus: cannot automatically derive upload's size from input. Specify it manually using the `uploadSize` option or use the `uploadLengthDeferred` option"));return}$u.options.parallelUploads>1||$u._parallelUploadUrls!=null?$u._startParallelUpload():$u._startSingleUpload()}).catch(function(Du){$u._emitError(Du)})}},{key:"_startParallelUpload",value:function(){var $u,Ru=this,Iu=this._size,Pu=0;this._parallelUploads=[];var Ou=this._parallelUploadUrls!=null?this._parallelUploadUrls.length:this.options.parallelUploads,Mu=($u=this.options.parallelUploadBoundaries)!==null&&$u!==void 0?$u:splitSizeIntoParts(this._source.size,Ou);this._parallelUploadUrls&&Mu.forEach(function(Bu,ju){Bu.uploadUrl=Ru._parallelUploadUrls[ju]||null}),this._parallelUploadUrls=new Array(Mu.length);var Du=Mu.map(function(Bu,ju){var Fu=0;return Ru._source.slice(Bu.start,Bu.end).then(function(zu){var Uu=zu.value;return new Promise(function(Hu,Vu){var Gu=_objectSpread$1(_objectSpread$1({},Ru.options),{},{uploadUrl:Bu.uploadUrl||null,storeFingerprintForResuming:!1,removeFingerprintOnSuccess:!1,parallelUploads:1,parallelUploadBoundaries:null,metadata:Ru.options.metadataForPartialUploads,headers:_objectSpread$1(_objectSpread$1({},Ru.options.headers),{},{"Upload-Concat":"partial"}),onSuccess:Hu,onError:Vu,onProgress:function(Ju){Pu=Pu-Fu+Ju,Fu=Ju,Ru._emitProgress(Pu,Iu)},onUploadUrlAvailable:function(){Ru._parallelUploadUrls[ju]=Wu.url,Ru._parallelUploadUrls.filter(function(Ju){return!!Ju}).length===Mu.length&&Ru._saveUploadInUrlStorage()}}),Wu=new Au(Uu,Gu);Wu.start(),Ru._parallelUploads.push(Wu)})})}),Lu;Promise.all(Du).then(function(){Lu=Ru._openRequest("POST",Ru.options.endpoint),Lu.setHeader("Upload-Concat","final;".concat(Ru._parallelUploadUrls.join(" ")));var Bu=encodeMetadata(Ru.options.metadata);return Bu!==""&&Lu.setHeader("Upload-Metadata",Bu),Ru._sendRequest(Lu,null)}).then(function(Bu){if(!inStatusCategory(Bu.getStatus(),200)){Ru._emitHttpError(Lu,Bu,"tus: unexpected response while creating upload");return}var ju=Bu.getHeader("Location");if(ju==null){Ru._emitHttpError(Lu,Bu,"tus: invalid or missing Location header");return}Ru.url=resolveUrl(Ru.options.endpoint,ju),"Created upload at ".concat(Ru.url),Ru._emitSuccess(Bu)}).catch(function(Bu){Ru._emitError(Bu)})}},{key:"_startSingleUpload",value:function(){if(this._aborted=!1,this.url!=null){"Resuming upload from previous URL: ".concat(this.url),this._resumeUpload();return}if(this.options.uploadUrl!=null){"Resuming upload from provided URL: ".concat(this.options.uploadUrl),this.url=this.options.uploadUrl,this._resumeUpload();return}this._createUpload()}},{key:"abort",value:function($u){var Ru=this;if(this._parallelUploads!=null){var Iu=_createForOfIteratorHelper(this._parallelUploads),Pu;try{for(Iu.s();!(Pu=Iu.n()).done;){var Ou=Pu.value;Ou.abort($u)}}catch(Mu){Iu.e(Mu)}finally{Iu.f()}}return this._req!==null&&this._req.abort(),this._aborted=!0,this._retryTimeout!=null&&(clearTimeout(this._retryTimeout),this._retryTimeout=null),!$u||this.url==null?Promise.resolve():Au.terminate(this.url,this.options).then(function(){return Ru._removeFromUrlStorage()})}},{key:"_emitHttpError",value:function($u,Ru,Iu,Pu){this._emitError(new DetailedError(Iu,Pu,$u,Ru))}},{key:"_emitError",value:function($u){var Ru=this;if(!this._aborted){if(this.options.retryDelays!=null){var Iu=this._offset!=null&&this._offset>this._offsetBeforeRetry;if(Iu&&(this._retryAttempt=0),shouldRetry($u,this._retryAttempt,this.options)){var Pu=this.options.retryDelays[this._retryAttempt++];this._offsetBeforeRetry=this._offset,this._retryTimeout=setTimeout(function(){Ru.start()},Pu);return}}if(typeof this.options.onError=="function")this.options.onError($u);else throw $u}}},{key:"_emitSuccess",value:function($u){this.options.removeFingerprintOnSuccess&&this._removeFromUrlStorage(),typeof this.options.onSuccess=="function"&&this.options.onSuccess({lastResponse:$u})}},{key:"_emitProgress",value:function($u,Ru){typeof this.options.onProgress=="function"&&this.options.onProgress($u,Ru)}},{key:"_emitChunkComplete",value:function($u,Ru,Iu){typeof this.options.onChunkComplete=="function"&&this.options.onChunkComplete($u,Ru,Iu)}},{key:"_createUpload",value:function(){var $u=this;if(!this.options.endpoint){this._emitError(new Error("tus: unable to create upload because no endpoint is provided"));return}var Ru=this._openRequest("POST",this.options.endpoint);this.options.uploadLengthDeferred?Ru.setHeader("Upload-Defer-Length","1"):Ru.setHeader("Upload-Length","".concat(this._size));var Iu=encodeMetadata(this.options.metadata);Iu!==""&&Ru.setHeader("Upload-Metadata",Iu);var Pu;this.options.uploadDataDuringCreation&&!this.options.uploadLengthDeferred?(this._offset=0,Pu=this._addChunkToRequest(Ru)):((this.options.protocol===PROTOCOL_IETF_DRAFT_03||this.options.protocol===PROTOCOL_IETF_DRAFT_05)&&Ru.setHeader("Upload-Complete","?0"),Pu=this._sendRequest(Ru,null)),Pu.then(function(Ou){if(!inStatusCategory(Ou.getStatus(),200)){$u._emitHttpError(Ru,Ou,"tus: unexpected response while creating upload");return}var Mu=Ou.getHeader("Location");if(Mu==null){$u._emitHttpError(Ru,Ou,"tus: invalid or missing Location header");return}if($u.url=resolveUrl($u.options.endpoint,Mu),"Created upload at ".concat($u.url),typeof $u.options.onUploadUrlAvailable=="function"&&$u.options.onUploadUrlAvailable(),$u._size===0){$u._emitSuccess(Ou),$u._source.close();return}$u._saveUploadInUrlStorage().then(function(){$u.options.uploadDataDuringCreation?$u._handleUploadResponse(Ru,Ou):($u._offset=0,$u._performUpload())})}).catch(function(Ou){$u._emitHttpError(Ru,null,"tus: failed to create upload",Ou)})}},{key:"_resumeUpload",value:function(){var $u=this,Ru=this._openRequest("HEAD",this.url),Iu=this._sendRequest(Ru,null);Iu.then(function(Pu){var Ou=Pu.getStatus();if(!inStatusCategory(Ou,200)){if(Ou===423){$u._emitHttpError(Ru,Pu,"tus: upload is currently locked; retry later");return}if(inStatusCategory(Ou,400)&&$u._removeFromUrlStorage(),!$u.options.endpoint){$u._emitHttpError(Ru,Pu,"tus: unable to resume upload (new upload cannot be created without an endpoint)");return}$u.url=null,$u._createUpload();return}var Mu=Number.parseInt(Pu.getHeader("Upload-Offset"),10);if(Number.isNaN(Mu)){$u._emitHttpError(Ru,Pu,"tus: invalid or missing offset value");return}var Du=Number.parseInt(Pu.getHeader("Upload-Length"),10);if(Number.isNaN(Du)&&!$u.options.uploadLengthDeferred&&$u.options.protocol===PROTOCOL_TUS_V1){$u._emitHttpError(Ru,Pu,"tus: invalid or missing length value");return}typeof $u.options.onUploadUrlAvailable=="function"&&$u.options.onUploadUrlAvailable(),$u._saveUploadInUrlStorage().then(function(){if(Mu===Du){$u._emitProgress(Du,Du),$u._emitSuccess(Pu);return}$u._offset=Mu,$u._performUpload()})}).catch(function(Pu){$u._emitHttpError(Ru,null,"tus: failed to resume upload",Pu)})}},{key:"_performUpload",value:function(){var $u=this;if(!this._aborted){var Ru;this.options.overridePatchMethod?(Ru=this._openRequest("POST",this.url),Ru.setHeader("X-HTTP-Method-Override","PATCH")):Ru=this._openRequest("PATCH",this.url),Ru.setHeader("Upload-Offset","".concat(this._offset));var Iu=this._addChunkToRequest(Ru);Iu.then(function(Pu){if(!inStatusCategory(Pu.getStatus(),200)){$u._emitHttpError(Ru,Pu,"tus: unexpected response while uploading chunk");return}$u._handleUploadResponse(Ru,Pu)}).catch(function(Pu){$u._aborted||$u._emitHttpError(Ru,null,"tus: failed to upload chunk at offset ".concat($u._offset),Pu)})}}},{key:"_addChunkToRequest",value:function($u){var Ru=this,Iu=this._offset,Pu=this._offset+this.options.chunkSize;return $u.setProgressHandler(function(Ou){Ru._emitProgress(Iu+Ou,Ru._size)}),this.options.protocol===PROTOCOL_TUS_V1?$u.setHeader("Content-Type","application/offset+octet-stream"):this.options.protocol===PROTOCOL_IETF_DRAFT_05&&$u.setHeader("Content-Type","application/partial-upload"),(Pu===Number.POSITIVE_INFINITY||Pu>this._size)&&!this.options.uploadLengthDeferred&&(Pu=this._size),this._source.slice(Iu,Pu).then(function(Ou){var Mu=Ou.value,Du=Ou.done,Lu=Mu!=null&&Mu.size?Mu.size:0;Ru.options.uploadLengthDeferred&&Du&&(Ru._size=Ru._offset+Lu,$u.setHeader("Upload-Length","".concat(Ru._size)));var Bu=Ru._offset+Lu;return!Ru.options.uploadLengthDeferred&&Du&&Bu!==Ru._size?Promise.reject(new Error("upload was configured with a size of ".concat(Ru._size," bytes, but the source is done after ").concat(Bu," bytes"))):Mu===null?Ru._sendRequest($u):((Ru.options.protocol===PROTOCOL_IETF_DRAFT_03||Ru.options.protocol===PROTOCOL_IETF_DRAFT_05)&&$u.setHeader("Upload-Complete",Du?"?1":"?0"),Ru._emitProgress(Ru._offset,Ru._size),Ru._sendRequest($u,Mu))})}},{key:"_handleUploadResponse",value:function($u,Ru){var Iu=Number.parseInt(Ru.getHeader("Upload-Offset"),10);if(Number.isNaN(Iu)){this._emitHttpError($u,Ru,"tus: invalid or missing offset value");return}if(this._emitProgress(Iu,this._size),this._emitChunkComplete(Iu-this._offset,Iu,this._size),this._offset=Iu,Iu===this._size){this._emitSuccess(Ru),this._source.close();return}this._performUpload()}},{key:"_openRequest",value:function($u,Ru){var Iu=openRequest($u,Ru,this.options);return this._req=Iu,Iu}},{key:"_removeFromUrlStorage",value:function(){var $u=this;this._urlStorageKey&&(this._urlStorage.removeUpload(this._urlStorageKey).catch(function(Ru){$u._emitError(Ru)}),this._urlStorageKey=null)}},{key:"_saveUploadInUrlStorage",value:function(){var $u=this;if(!this.options.storeFingerprintForResuming||!this._fingerprint||this._urlStorageKey!==null)return Promise.resolve();var Ru={size:this._size,metadata:this.options.metadata,creationTime:new Date().toString()};return this._parallelUploads?Ru.parallelUploadUrls=this._parallelUploadUrls:Ru.uploadUrl=this.url,this._urlStorage.addUpload(this._fingerprint,Ru).then(function(Iu){$u._urlStorageKey=Iu})}},{key:"_sendRequest",value:function($u){var Ru=arguments.length>1&&arguments[1]!==void 0?arguments[1]:null;return sendRequest($u,Ru,this.options)}}],[{key:"terminate",value:function($u){var Ru=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},Iu=openRequest("DELETE",$u,Ru);return sendRequest(Iu,null,Ru).then(function(Pu){if(Pu.getStatus()!==204)throw new DetailedError("tus: unexpected response while terminating upload",null,Iu,Pu)}).catch(function(Pu){if(Pu instanceof DetailedError||(Pu=new DetailedError("tus: failed to terminate upload",Pu,Iu,null)),!shouldRetry(Pu,0,Ru))throw Pu;var Ou=Ru.retryDelays[0],Mu=Ru.retryDelays.slice(1),Du=_objectSpread$1(_objectSpread$1({},Ru),{},{retryDelays:Mu});return new Promise(function(Lu){return setTimeout(Lu,Ou)}).then(function(){return Au.terminate($u,Du)})})}}])})();function encodeMetadata(Au){return Object.entries(Au).map(function(lo){var $u=_slicedToArray$1(lo,2),Ru=$u[0],Iu=$u[1];return"".concat(Ru," ").concat(gBase64.encode(String(Iu)))}).join(",")}function inStatusCategory(Au,lo){return Au>=lo&&Au<lo+100}function openRequest(Au,lo,$u){var Ru=$u.httpStack.createRequest(Au,lo);$u.protocol===PROTOCOL_IETF_DRAFT_03?Ru.setHeader("Upload-Draft-Interop-Version","5"):$u.protocol===PROTOCOL_IETF_DRAFT_05?Ru.setHeader("Upload-Draft-Interop-Version","6"):Ru.setHeader("Tus-Resumable","1.0.0");for(var Iu=$u.headers||{},Pu=0,Ou=Object.entries(Iu);Pu<Ou.length;Pu++){var Mu=_slicedToArray$1(Ou[Pu],2),Du=Mu[0],Lu=Mu[1];Ru.setHeader(Du,Lu)}if($u.addRequestId){var Bu=uuid();Ru.setHeader("X-Request-ID",Bu)}return Ru}function sendRequest(Au,lo,$u){return _sendRequest2.apply(this,arguments)}function _sendRequest2(){return _sendRequest2=_asyncToGenerator$1(_regeneratorRuntime$1().mark(function Au(lo,$u,Ru){var Iu;return _regeneratorRuntime$1().wrap(function(Ou){for(;;)switch(Ou.prev=Ou.next){case 0:if(typeof Ru.onBeforeRequest!="function"){Ou.next=3;break}return Ou.next=3,Ru.onBeforeRequest(lo);case 3:return Ou.next=5,lo.send($u);case 5:if(Iu=Ou.sent,typeof Ru.onAfterResponse!="function"){Ou.next=9;break}return Ou.next=9,Ru.onAfterResponse(lo,Iu);case 9:return Ou.abrupt("return",Iu);case 10:case"end":return Ou.stop()}},Au)})),_sendRequest2.apply(this,arguments)}function isOnline(){var Au=!0;return typeof navigator<"u"&&navigator.onLine===!1&&(Au=!1),Au}function shouldRetry(Au,lo,$u){return $u.retryDelays==null||lo>=$u.retryDelays.length||Au.originalRequest==null?!1:$u&&typeof $u.onShouldRetry=="function"?$u.onShouldRetry(Au,lo,$u):defaultOnShouldRetry(Au)}function defaultOnShouldRetry(Au){var lo=Au.originalResponse?Au.originalResponse.getStatus():0;return(!inStatusCategory(lo,400)||lo===409||lo===423)&&isOnline()}function resolveUrl(Au,lo){return new URL$1(lo,Au).toString()}function splitSizeIntoParts(Au,lo){for(var $u=Math.floor(Au/lo),Ru=[],Iu=0;Iu<lo;Iu++)Ru.push({start:$u*Iu,end:$u*(Iu+1)});return Ru[lo-1].end=Au,Ru}BaseUpload.defaultOptions=defaultOptions$2;var isReactNative=function Au(){return typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative"};function uriToBlob(Au){return new Promise(function(lo,$u){var Ru=new XMLHttpRequest;Ru.responseType="blob",Ru.onload=function(){var Iu=Ru.response;lo(Iu)},Ru.onerror=function(Iu){$u(Iu)},Ru.open("GET",Au),Ru.send()})}var isCordova=function Au(){return typeof window<"u"&&(typeof window.PhoneGap<"u"||typeof window.Cordova<"u"||typeof window.cordova<"u")};function readAsByteArray(Au){return new Promise(function(lo,$u){var Ru=new FileReader;Ru.onload=function(){var Iu=new Uint8Array(Ru.result);lo({value:Iu})},Ru.onerror=function(Iu){$u(Iu)},Ru.readAsArrayBuffer(Au)})}function _typeof$5(Au){"@babel/helpers - typeof";return _typeof$5=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(lo){return typeof lo}:function(lo){return lo&&typeof Symbol=="function"&&lo.constructor===Symbol&&lo!==Symbol.prototype?"symbol":typeof lo},_typeof$5(Au)}function _classCallCheck$5(Au,lo){if(!(Au instanceof lo))throw new TypeError("Cannot call a class as a function")}function _defineProperties$5(Au,lo){for(var $u=0;$u<lo.length;$u++){var Ru=lo[$u];Ru.enumerable=Ru.enumerable||!1,Ru.configurable=!0,"value"in Ru&&(Ru.writable=!0),Object.defineProperty(Au,_toPropertyKey$5(Ru.key),Ru)}}function _createClass$5(Au,lo,$u){return lo&&_defineProperties$5(Au.prototype,lo),Object.defineProperty(Au,"prototype",{writable:!1}),Au}function _toPropertyKey$5(Au){var lo=_toPrimitive$5(Au,"string");return _typeof$5(lo)=="symbol"?lo:lo+""}function _toPrimitive$5(Au,lo){if(_typeof$5(Au)!="object"||!Au)return Au;var $u=Au[Symbol.toPrimitive];if($u!==void 0){var Ru=$u.call(Au,lo);if(_typeof$5(Ru)!="object")return Ru;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(Au)}var FileSource=(function(){function Au(lo){_classCallCheck$5(this,Au),this._file=lo,this.size=lo.size}return _createClass$5(Au,[{key:"slice",value:function($u,Ru){if(isCordova())return readAsByteArray(this._file.slice($u,Ru));var Iu=this._file.slice($u,Ru),Pu=Ru>=this.size;return Promise.resolve({value:Iu,done:Pu})}},{key:"close",value:function(){}}])})();function _typeof$4(Au){"@babel/helpers - typeof";return _typeof$4=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(lo){return typeof lo}:function(lo){return lo&&typeof Symbol=="function"&&lo.constructor===Symbol&&lo!==Symbol.prototype?"symbol":typeof lo},_typeof$4(Au)}function _classCallCheck$4(Au,lo){if(!(Au instanceof lo))throw new TypeError("Cannot call a class as a function")}function _defineProperties$4(Au,lo){for(var $u=0;$u<lo.length;$u++){var Ru=lo[$u];Ru.enumerable=Ru.enumerable||!1,Ru.configurable=!0,"value"in Ru&&(Ru.writable=!0),Object.defineProperty(Au,_toPropertyKey$4(Ru.key),Ru)}}function _createClass$4(Au,lo,$u){return lo&&_defineProperties$4(Au.prototype,lo),Object.defineProperty(Au,"prototype",{writable:!1}),Au}function _toPropertyKey$4(Au){var lo=_toPrimitive$4(Au,"string");return _typeof$4(lo)=="symbol"?lo:lo+""}function _toPrimitive$4(Au,lo){if(_typeof$4(Au)!="object"||!Au)return Au;var $u=Au[Symbol.toPrimitive];if($u!==void 0){var Ru=$u.call(Au,lo);if(_typeof$4(Ru)!="object")return Ru;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(Au)}function len(Au){return Au===void 0?0:Au.size!==void 0?Au.size:Au.length}function concat(Au,lo){if(Au.concat)return Au.concat(lo);if(Au instanceof Blob)return new Blob([Au,lo],{type:Au.type});if(Au.set){var $u=new Au.constructor(Au.length+lo.length);return $u.set(Au),$u.set(lo,Au.length),$u}throw new Error("Unknown data type")}var StreamSource=(function(){function Au(lo){_classCallCheck$4(this,Au),this._buffer=void 0,this._bufferOffset=0,this._reader=lo,this._done=!1}return _createClass$4(Au,[{key:"slice",value:function($u,Ru){return $u<this._bufferOffset?Promise.reject(new Error("Requested data is before the reader's current offset")):this._readUntilEnoughDataOrDone($u,Ru)}},{key:"_readUntilEnoughDataOrDone",value:function($u,Ru){var Iu=this,Pu=Ru<=this._bufferOffset+len(this._buffer);if(this._done||Pu){var Ou=this._getDataFromBuffer($u,Ru),Mu=Ou==null?this._done:!1;return Promise.resolve({value:Ou,done:Mu})}return this._reader.read().then(function(Du){var Lu=Du.value,Bu=Du.done;return Bu?Iu._done=!0:Iu._buffer===void 0?Iu._buffer=Lu:Iu._buffer=concat(Iu._buffer,Lu),Iu._readUntilEnoughDataOrDone($u,Ru)})}},{key:"_getDataFromBuffer",value:function($u,Ru){$u>this._bufferOffset&&(this._buffer=this._buffer.slice($u-this._bufferOffset),this._bufferOffset=$u);var Iu=len(this._buffer)===0;return this._done&&Iu?null:this._buffer.slice(0,Ru-$u)}},{key:"close",value:function(){this._reader.cancel&&this._reader.cancel()}}])})();function _typeof$3(Au){"@babel/helpers - typeof";return _typeof$3=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(lo){return typeof lo}:function(lo){return lo&&typeof Symbol=="function"&&lo.constructor===Symbol&&lo!==Symbol.prototype?"symbol":typeof lo},_typeof$3(Au)}function _regeneratorRuntime(){_regeneratorRuntime=function(){return lo};var Au,lo={},$u=Object.prototype,Ru=$u.hasOwnProperty,Iu=Object.defineProperty||function(_d,vd,wd){_d[vd]=wd.value},Pu=typeof Symbol=="function"?Symbol:{},Ou=Pu.iterator||"@@iterator",Mu=Pu.asyncIterator||"@@asyncIterator",Du=Pu.toStringTag||"@@toStringTag";function Lu(_d,vd,wd){return Object.defineProperty(_d,vd,{value:wd,enumerable:!0,configurable:!0,writable:!0}),_d[vd]}try{Lu({},"")}catch{Lu=function(wd,Ed,cd){return wd[Ed]=cd}}function Bu(_d,vd,wd,Ed){var cd=vd&&vd.prototype instanceof Gu?vd:Gu,dd=Object.create(cd.prototype),md=new gd(Ed||[]);return Iu(dd,"_invoke",{value:od(_d,wd,md)}),dd}function ju(_d,vd,wd){try{return{type:"normal",arg:_d.call(vd,wd)}}catch(Ed){return{type:"throw",arg:Ed}}}lo.wrap=Bu;var Fu="suspendedStart",zu="suspendedYield",Uu="executing",Hu="completed",Vu={};function Gu(){}function Wu(){}function Ku(){}var Ju={};Lu(Ju,Ou,function(){return this});var Yu=Object.getPrototypeOf,Xu=Yu&&Yu(Yu(yd([])));Xu&&Xu!==$u&&Ru.call(Xu,Ou)&&(Ju=Xu);var ed=Ku.prototype=Gu.prototype=Object.create(Ju);function td(_d){["next","throw","return"].forEach(function(vd){Lu(_d,vd,function(wd){return this._invoke(vd,wd)})})}function nd(_d,vd){function wd(cd,dd,md,ld){var hd=ju(_d[cd],_d,dd);if(hd.type!=="throw"){var bd=hd.arg,Sd=bd.value;return Sd&&_typeof$3(Sd)=="object"&&Ru.call(Sd,"__await")?vd.resolve(Sd.__await).then(function(kd){wd("next",kd,md,ld)},function(kd){wd("throw",kd,md,ld)}):vd.resolve(Sd).then(function(kd){bd.value=kd,md(bd)},function(kd){return wd("throw",kd,md,ld)})}ld(hd.arg)}var Ed;Iu(this,"_invoke",{value:function(dd,md){function ld(){return new vd(function(hd,bd){wd(dd,md,hd,bd)})}return Ed=Ed?Ed.then(ld,ld):ld()}})}function od(_d,vd,wd){var Ed=Fu;return function(cd,dd){if(Ed===Uu)throw Error("Generator is already running");if(Ed===Hu){if(cd==="throw")throw dd;return{value:Au,done:!0}}for(wd.method=cd,wd.arg=dd;;){var md=wd.delegate;if(md){var ld=sd(md,wd);if(ld){if(ld===Vu)continue;return ld}}if(wd.method==="next")wd.sent=wd._sent=wd.arg;else if(wd.method==="throw"){if(Ed===Fu)throw Ed=Hu,wd.arg;wd.dispatchException(wd.arg)}else wd.method==="return"&&wd.abrupt("return",wd.arg);Ed=Uu;var hd=ju(_d,vd,wd);if(hd.type==="normal"){if(Ed=wd.done?Hu:zu,hd.arg===Vu)continue;return{value:hd.arg,done:wd.done}}hd.type==="throw"&&(Ed=Hu,wd.method="throw",wd.arg=hd.arg)}}}function sd(_d,vd){var wd=vd.method,Ed=_d.iterator[wd];if(Ed===Au)return vd.delegate=null,wd==="throw"&&_d.iterator.return&&(vd.method="return",vd.arg=Au,sd(_d,vd),vd.method==="throw")||wd!=="return"&&(vd.method="throw",vd.arg=new TypeError("The iterator does not provide a '"+wd+"' method")),Vu;var cd=ju(Ed,_d.iterator,vd.arg);if(cd.type==="throw")return vd.method="throw",vd.arg=cd.arg,vd.delegate=null,Vu;var dd=cd.arg;return dd?dd.done?(vd[_d.resultName]=dd.value,vd.next=_d.nextLoc,vd.method!=="return"&&(vd.method="next",vd.arg=Au),vd.delegate=null,Vu):dd:(vd.method="throw",vd.arg=new TypeError("iterator result is not an object"),vd.delegate=null,Vu)}function ad(_d){var vd={tryLoc:_d[0]};1 in _d&&(vd.catchLoc=_d[1]),2 in _d&&(vd.finallyLoc=_d[2],vd.afterLoc=_d[3]),this.tryEntries.push(vd)}function pd(_d){var vd=_d.completion||{};vd.type="normal",delete vd.arg,_d.completion=vd}function gd(_d){this.tryEntries=[{tryLoc:"root"}],_d.forEach(ad,this),this.reset(!0)}function yd(_d){if(_d||_d===""){var vd=_d[Ou];if(vd)return vd.call(_d);if(typeof _d.next=="function")return _d;if(!isNaN(_d.length)){var wd=-1,Ed=function cd(){for(;++wd<_d.length;)if(Ru.call(_d,wd))return cd.value=_d[wd],cd.done=!1,cd;return cd.value=Au,cd.done=!0,cd};return Ed.next=Ed}}throw new TypeError(_typeof$3(_d)+" is not iterable")}return Wu.prototype=Ku,Iu(ed,"constructor",{value:Ku,configurable:!0}),Iu(Ku,"constructor",{value:Wu,configurable:!0}),Wu.displayName=Lu(Ku,Du,"GeneratorFunction"),lo.isGeneratorFunction=function(_d){var vd=typeof _d=="function"&&_d.constructor;return!!vd&&(vd===Wu||(vd.displayName||vd.name)==="GeneratorFunction")},lo.mark=function(_d){return Object.setPrototypeOf?Object.setPrototypeOf(_d,Ku):(_d.__proto__=Ku,Lu(_d,Du,"GeneratorFunction")),_d.prototype=Object.create(ed),_d},lo.awrap=function(_d){return{__await:_d}},td(nd.prototype),Lu(nd.prototype,Mu,function(){return this}),lo.AsyncIterator=nd,lo.async=function(_d,vd,wd,Ed,cd){cd===void 0&&(cd=Promise);var dd=new nd(Bu(_d,vd,wd,Ed),cd);return lo.isGeneratorFunction(vd)?dd:dd.next().then(function(md){return md.done?md.value:dd.next()})},td(ed),Lu(ed,Du,"Generator"),Lu(ed,Ou,function(){return this}),Lu(ed,"toString",function(){return"[object Generator]"}),lo.keys=function(_d){var vd=Object(_d),wd=[];for(var Ed in vd)wd.push(Ed);return wd.reverse(),function cd(){for(;wd.length;){var dd=wd.pop();if(dd in vd)return cd.value=dd,cd.done=!1,cd}return cd.done=!0,cd}},lo.values=yd,gd.prototype={constructor:gd,reset:function(vd){if(this.prev=0,this.next=0,this.sent=this._sent=Au,this.done=!1,this.delegate=null,this.method="next",this.arg=Au,this.tryEntries.forEach(pd),!vd)for(var wd in this)wd.charAt(0)==="t"&&Ru.call(this,wd)&&!isNaN(+wd.slice(1))&&(this[wd]=Au)},stop:function(){this.done=!0;var vd=this.tryEntries[0].completion;if(vd.type==="throw")throw vd.arg;return this.rval},dispatchException:function(vd){if(this.done)throw vd;var wd=this;function Ed(bd,Sd){return md.type="throw",md.arg=vd,wd.next=bd,Sd&&(wd.method="next",wd.arg=Au),!!Sd}for(var cd=this.tryEntries.length-1;cd>=0;--cd){var dd=this.tryEntries[cd],md=dd.completion;if(dd.tryLoc==="root")return Ed("end");if(dd.tryLoc<=this.prev){var ld=Ru.call(dd,"catchLoc"),hd=Ru.call(dd,"finallyLoc");if(ld&&hd){if(this.prev<dd.catchLoc)return Ed(dd.catchLoc,!0);if(this.prev<dd.finallyLoc)return Ed(dd.finallyLoc)}else if(ld){if(this.prev<dd.catchLoc)return Ed(dd.catchLoc,!0)}else{if(!hd)throw Error("try statement without catch or finally");if(this.prev<dd.finallyLoc)return Ed(dd.finallyLoc)}}}},abrupt:function(vd,wd){for(var Ed=this.tryEntries.length-1;Ed>=0;--Ed){var cd=this.tryEntries[Ed];if(cd.tryLoc<=this.prev&&Ru.call(cd,"finallyLoc")&&this.prev<cd.finallyLoc){var dd=cd;break}}dd&&(vd==="break"||vd==="continue")&&dd.tryLoc<=wd&&wd<=dd.finallyLoc&&(dd=null);var md=dd?dd.completion:{};return md.type=vd,md.arg=wd,dd?(this.method="next",this.next=dd.finallyLoc,Vu):this.complete(md)},complete:function(vd,wd){if(vd.type==="throw")throw vd.arg;return vd.type==="break"||vd.type==="continue"?this.next=vd.arg:vd.type==="return"?(this.rval=this.arg=vd.arg,this.method="return",this.next="end"):vd.type==="normal"&&wd&&(this.next=wd),Vu},finish:function(vd){for(var wd=this.tryEntries.length-1;wd>=0;--wd){var Ed=this.tryEntries[wd];if(Ed.finallyLoc===vd)return this.complete(Ed.completion,Ed.afterLoc),pd(Ed),Vu}},catch:function(vd){for(var wd=this.tryEntries.length-1;wd>=0;--wd){var Ed=this.tryEntries[wd];if(Ed.tryLoc===vd){var cd=Ed.completion;if(cd.type==="throw"){var dd=cd.arg;pd(Ed)}return dd}}throw Error("illegal catch attempt")},delegateYield:function(vd,wd,Ed){return this.delegate={iterator:yd(vd),resultName:wd,nextLoc:Ed},this.method==="next"&&(this.arg=Au),Vu}},lo}function asyncGeneratorStep(Au,lo,$u,Ru,Iu,Pu,Ou){try{var Mu=Au[Pu](Ou),Du=Mu.value}catch(Lu){$u(Lu);return}Mu.done?lo(Du):Promise.resolve(Du).then(Ru,Iu)}function _asyncToGenerator(Au){return function(){var lo=this,$u=arguments;return new Promise(function(Ru,Iu){var Pu=Au.apply(lo,$u);function Ou(Du){asyncGeneratorStep(Pu,Ru,Iu,Ou,Mu,"next",Du)}function Mu(Du){asyncGeneratorStep(Pu,Ru,Iu,Ou,Mu,"throw",Du)}Ou(void 0)})}}function _classCallCheck$3(Au,lo){if(!(Au instanceof lo))throw new TypeError("Cannot call a class as a function")}function _defineProperties$3(Au,lo){for(var $u=0;$u<lo.length;$u++){var Ru=lo[$u];Ru.enumerable=Ru.enumerable||!1,Ru.configurable=!0,"value"in Ru&&(Ru.writable=!0),Object.defineProperty(Au,_toPropertyKey$3(Ru.key),Ru)}}function _createClass$3(Au,lo,$u){return lo&&_defineProperties$3(Au.prototype,lo),Object.defineProperty(Au,"prototype",{writable:!1}),Au}function _toPropertyKey$3(Au){var lo=_toPrimitive$3(Au,"string");return _typeof$3(lo)=="symbol"?lo:lo+""}function _toPrimitive$3(Au,lo){if(_typeof$3(Au)!="object"||!Au)return Au;var $u=Au[Symbol.toPrimitive];if($u!==void 0){var Ru=$u.call(Au,lo);if(_typeof$3(Ru)!="object")return Ru;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(Au)}var FileReader$1=(function(){function Au(){_classCallCheck$3(this,Au)}return _createClass$3(Au,[{key:"openFile",value:(function(){var lo=_asyncToGenerator(_regeneratorRuntime().mark(function Ru(Iu,Pu){var Ou;return _regeneratorRuntime().wrap(function(Du){for(;;)switch(Du.prev=Du.next){case 0:if(!(isReactNative()&&Iu&&typeof Iu.uri<"u")){Du.next=11;break}return Du.prev=1,Du.next=4,uriToBlob(Iu.uri);case 4:return Ou=Du.sent,Du.abrupt("return",new FileSource(Ou));case 8:throw Du.prev=8,Du.t0=Du.catch(1),new Error("tus: cannot fetch `file.uri` as Blob, make sure the uri is correct and accessible. ".concat(Du.t0));case 11:if(!(typeof Iu.slice=="function"&&typeof Iu.size<"u")){Du.next=13;break}return Du.abrupt("return",Promise.resolve(new FileSource(Iu)));case 13:if(typeof Iu.read!="function"){Du.next=18;break}if(Pu=Number(Pu),Number.isFinite(Pu)){Du.next=17;break}return Du.abrupt("return",Promise.reject(new Error("cannot create source for stream without a finite value for the `chunkSize` option")));case 17:return Du.abrupt("return",Promise.resolve(new StreamSource(Iu,Pu)));case 18:return Du.abrupt("return",Promise.reject(new Error("source object may only be an instance of File, Blob, or Reader in this environment")));case 19:case"end":return Du.stop()}},Ru,null,[[1,8]])}));function $u(Ru,Iu){return lo.apply(this,arguments)}return $u})()}])})();function fingerprint(Au,lo){return isReactNative()?Promise.resolve(reactNativeFingerprint(Au,lo)):Promise.resolve(["tus-br",Au.name,Au.type,Au.size,Au.lastModified,lo.endpoint].join("-"))}function reactNativeFingerprint(Au,lo){var $u=Au.exif?hashCode(JSON.stringify(Au.exif)):"noexif";return["tus-rn",Au.name||"noname",Au.size||"nosize",$u,lo.endpoint].join("/")}function hashCode(Au){var lo=0;if(Au.length===0)return lo;for(var $u=0;$u<Au.length;$u++){var Ru=Au.charCodeAt($u);lo=(lo<<5)-lo+Ru,lo&=lo}return lo}function _typeof$2(Au){"@babel/helpers - typeof";return _typeof$2=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(lo){return typeof lo}:function(lo){return lo&&typeof Symbol=="function"&&lo.constructor===Symbol&&lo!==Symbol.prototype?"symbol":typeof lo},_typeof$2(Au)}function _classCallCheck$2(Au,lo){if(!(Au instanceof lo))throw new TypeError("Cannot call a class as a function")}function _defineProperties$2(Au,lo){for(var $u=0;$u<lo.length;$u++){var Ru=lo[$u];Ru.enumerable=Ru.enumerable||!1,Ru.configurable=!0,"value"in Ru&&(Ru.writable=!0),Object.defineProperty(Au,_toPropertyKey$2(Ru.key),Ru)}}function _createClass$2(Au,lo,$u){return lo&&_defineProperties$2(Au.prototype,lo),Object.defineProperty(Au,"prototype",{writable:!1}),Au}function _toPropertyKey$2(Au){var lo=_toPrimitive$2(Au,"string");return _typeof$2(lo)=="symbol"?lo:lo+""}function _toPrimitive$2(Au,lo){if(_typeof$2(Au)!="object"||!Au)return Au;var $u=Au[Symbol.toPrimitive];if($u!==void 0){var Ru=$u.call(Au,lo);if(_typeof$2(Ru)!="object")return Ru;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(Au)}var XHRHttpStack=(function(){function Au(){_classCallCheck$2(this,Au)}return _createClass$2(Au,[{key:"createRequest",value:function($u,Ru){return new Request$1($u,Ru)}},{key:"getName",value:function(){return"XHRHttpStack"}}])})(),Request$1=(function(){function Au(lo,$u){_classCallCheck$2(this,Au),this._xhr=new XMLHttpRequest,this._xhr.open(lo,$u,!0),this._method=lo,this._url=$u,this._headers={}}return _createClass$2(Au,[{key:"getMethod",value:function(){return this._method}},{key:"getURL",value:function(){return this._url}},{key:"setHeader",value:function($u,Ru){this._xhr.setRequestHeader($u,Ru),this._headers[$u]=Ru}},{key:"getHeader",value:function($u){return this._headers[$u]}},{key:"setProgressHandler",value:function($u){"upload"in this._xhr&&(this._xhr.upload.onprogress=function(Ru){Ru.lengthComputable&&$u(Ru.loaded)})}},{key:"send",value:function(){var $u=this,Ru=arguments.length>0&&arguments[0]!==void 0?arguments[0]:null;return new Promise(function(Iu,Pu){$u._xhr.onload=function(){Iu(new Response$1($u._xhr))},$u._xhr.onerror=function(Ou){Pu(Ou)},$u._xhr.send(Ru)})}},{key:"abort",value:function(){return this._xhr.abort(),Promise.resolve()}},{key:"getUnderlyingObject",value:function(){return this._xhr}}])})(),Response$1=(function(){function Au(lo){_classCallCheck$2(this,Au),this._xhr=lo}return _createClass$2(Au,[{key:"getStatus",value:function(){return this._xhr.status}},{key:"getHeader",value:function($u){return this._xhr.getResponseHeader($u)}},{key:"getBody",value:function(){return this._xhr.responseText}},{key:"getUnderlyingObject",value:function(){return this._xhr}}])})();function _typeof$1(Au){"@babel/helpers - typeof";return _typeof$1=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(lo){return typeof lo}:function(lo){return lo&&typeof Symbol=="function"&&lo.constructor===Symbol&&lo!==Symbol.prototype?"symbol":typeof lo},_typeof$1(Au)}function _classCallCheck$1(Au,lo){if(!(Au instanceof lo))throw new TypeError("Cannot call a class as a function")}function _defineProperties$1(Au,lo){for(var $u=0;$u<lo.length;$u++){var Ru=lo[$u];Ru.enumerable=Ru.enumerable||!1,Ru.configurable=!0,"value"in Ru&&(Ru.writable=!0),Object.defineProperty(Au,_toPropertyKey$1(Ru.key),Ru)}}function _createClass$1(Au,lo,$u){return lo&&_defineProperties$1(Au.prototype,lo),Object.defineProperty(Au,"prototype",{writable:!1}),Au}function _toPropertyKey$1(Au){var lo=_toPrimitive$1(Au,"string");return _typeof$1(lo)=="symbol"?lo:lo+""}function _toPrimitive$1(Au,lo){if(_typeof$1(Au)!="object"||!Au)return Au;var $u=Au[Symbol.toPrimitive];if($u!==void 0){var Ru=$u.call(Au,lo);if(_typeof$1(Ru)!="object")return Ru;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(Au)}var hasStorage=!1;try{hasStorage="localStorage"in window;var key="tusSupport",originalValue=localStorage.getItem(key);localStorage.setItem(key,originalValue),originalValue===null&&localStorage.removeItem(key)}catch(Au){if(Au.code===Au.SECURITY_ERR||Au.code===Au.QUOTA_EXCEEDED_ERR)hasStorage=!1;else throw Au}var canStoreURLs=hasStorage,WebStorageUrlStorage=(function(){function Au(){_classCallCheck$1(this,Au)}return _createClass$1(Au,[{key:"findAllUploads",value:function(){var $u=this._findEntries("tus::");return Promise.resolve($u)}},{key:"findUploadsByFingerprint",value:function($u){var Ru=this._findEntries("tus::".concat($u,"::"));return Promise.resolve(Ru)}},{key:"removeUpload",value:function($u){return localStorage.removeItem($u),Promise.resolve()}},{key:"addUpload",value:function($u,Ru){var Iu=Math.round(Math.random()*1e12),Pu="tus::".concat($u,"::").concat(Iu);return localStorage.setItem(Pu,JSON.stringify(Ru)),Promise.resolve(Pu)}},{key:"_findEntries",value:function($u){for(var Ru=[],Iu=0;Iu<localStorage.length;Iu++){var Pu=localStorage.key(Iu);if(Pu.indexOf($u)===0)try{var Ou=JSON.parse(localStorage.getItem(Pu));Ou.urlStorageKey=Pu,Ru.push(Ou)}catch{}}return Ru}}])})();function _typeof(Au){"@babel/helpers - typeof";return _typeof=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(lo){return typeof lo}:function(lo){return lo&&typeof Symbol=="function"&&lo.constructor===Symbol&&lo!==Symbol.prototype?"symbol":typeof lo},_typeof(Au)}function _classCallCheck(Au,lo){if(!(Au instanceof lo))throw new TypeError("Cannot call a class as a function")}function _defineProperties(Au,lo){for(var $u=0;$u<lo.length;$u++){var Ru=lo[$u];Ru.enumerable=Ru.enumerable||!1,Ru.configurable=!0,"value"in Ru&&(Ru.writable=!0),Object.defineProperty(Au,_toPropertyKey(Ru.key),Ru)}}function _createClass(Au,lo,$u){return $u&&_defineProperties(Au,$u),Object.defineProperty(Au,"prototype",{writable:!1}),Au}function _callSuper(Au,lo,$u){return lo=_getPrototypeOf(lo),_possibleConstructorReturn(Au,_isNativeReflectConstruct()?Reflect.construct(lo,$u||[],_getPrototypeOf(Au).constructor):lo.apply(Au,$u))}function _possibleConstructorReturn(Au,lo){if(lo&&(_typeof(lo)==="object"||typeof lo=="function"))return lo;if(lo!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return _assertThisInitialized(Au)}function _assertThisInitialized(Au){if(Au===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return Au}function _isNativeReflectConstruct(){try{var Au=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(_isNativeReflectConstruct=function(){return!!Au})()}function _getPrototypeOf(Au){return _getPrototypeOf=Object.setPrototypeOf?Object.getPrototypeOf.bind():function($u){return $u.__proto__||Object.getPrototypeOf($u)},_getPrototypeOf(Au)}function _inherits(Au,lo){if(typeof lo!="function"&&lo!==null)throw new TypeError("Super expression must either be null or a function");Au.prototype=Object.create(lo&&lo.prototype,{constructor:{value:Au,writable:!0,configurable:!0}}),Object.defineProperty(Au,"prototype",{writable:!1}),lo&&_setPrototypeOf(Au,lo)}function _setPrototypeOf(Au,lo){return _setPrototypeOf=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(Ru,Iu){return Ru.__proto__=Iu,Ru},_setPrototypeOf(Au,lo)}function ownKeys(Au,lo){var $u=Object.keys(Au);if(Object.getOwnPropertySymbols){var Ru=Object.getOwnPropertySymbols(Au);lo&&(Ru=Ru.filter(function(Iu){return Object.getOwnPropertyDescriptor(Au,Iu).enumerable})),$u.push.apply($u,Ru)}return $u}function _objectSpread(Au){for(var lo=1;lo<arguments.length;lo++){var $u=arguments[lo]!=null?arguments[lo]:{};lo%2?ownKeys(Object($u),!0).forEach(function(Ru){_defineProperty(Au,Ru,$u[Ru])}):Object.getOwnPropertyDescriptors?Object.defineProperties(Au,Object.getOwnPropertyDescriptors($u)):ownKeys(Object($u)).forEach(function(Ru){Object.defineProperty(Au,Ru,Object.getOwnPropertyDescriptor($u,Ru))})}return Au}function _defineProperty(Au,lo,$u){return lo=_toPropertyKey(lo),lo in Au?Object.defineProperty(Au,lo,{value:$u,enumerable:!0,configurable:!0,writable:!0}):Au[lo]=$u,Au}function _toPropertyKey(Au){var lo=_toPrimitive(Au,"string");return _typeof(lo)=="symbol"?lo:lo+""}function _toPrimitive(Au,lo){if(_typeof(Au)!="object"||!Au)return Au;var $u=Au[Symbol.toPrimitive];if($u!==void 0){var Ru=$u.call(Au,lo);if(_typeof(Ru)!="object")return Ru;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(Au)}var defaultOptions$1=_objectSpread(_objectSpread({},BaseUpload.defaultOptions),{},{httpStack:new XHRHttpStack,fileReader:new FileReader$1,urlStorage:canStoreURLs?new WebStorageUrlStorage:new NoopUrlStorage,fingerprint}),Upload=(function(Au){function lo(){var $u=arguments.length>0&&arguments[0]!==void 0?arguments[0]:null,Ru=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return _classCallCheck(this,lo),Ru=_objectSpread(_objectSpread({},defaultOptions$1),Ru),_callSuper(this,lo,[$u,Ru])}return _inherits(lo,Au),_createClass(lo,null,[{key:"terminate",value:function(Ru){var Iu=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return Iu=_objectSpread(_objectSpread({},defaultOptions$1),Iu),BaseUpload.terminate(Ru,Iu)}}])})(BaseUpload);const RUNTIMES_API_PREFIX="api/runtimes/v1";function join$1(Au,lo){return`${Au.replace(/\/+$/,"")}/${lo.replace(/^\/+/,"")}`}function runtimesUrl(Au){return join$1(Au,`${RUNTIMES_API_PREFIX}/runtimes`)}function runtimeUrl(Au,lo){return`${runtimesUrl(Au)}/${lo}`}function sandboxSnapshotsUrl(Au){return join$1(Au,`${RUNTIMES_API_PREFIX}/sandbox-snapshots`)}function sandboxSnapshotUrl(Au,lo){return`${sandboxSnapshotsUrl(Au)}/${lo}`}function asCodeSandboxSnapshot(Au){const{uid:lo,updated_at:$u,format_version:Ru,...Iu}=Au;return{...Iu,id:lo,updatedAt:new Date($u),formatVersion:Ru}}async function getEnvironments(){const Au=await requestDatalayerAPI({url:libExports$5.URLExt.join(runtimesStore.getState().runtimesUrl,"api/runtimes/v1/environments"),token:iamStore.getState().token});return Au.success?Au.environments??[]:(console.error("Failed to fetch available environments.",Au),[])}async function createRuntime(Au){const{externalToken:lo,token:$u}=iamStore.getState();if(typeof Au.creditsLimit!="number"||!Number.isFinite(Au.creditsLimit)||Au.creditsLimit<0)throw new Error(`Invalid runtime creditsLimit for environment ${Au.environmentName}. A number of zero or more is required.`);if(Au.deploymentUid&&!Au.appUid)throw new Error(`Deployment ${Au.deploymentUid} is named without its application: give appUid.`);if(Au.appUid&&!Au.appSpec)throw new Error(`Application ${Au.appUid} is launched without its Appspec: give appSpec, so its runtime is given the secrets its connections declare.`);const Ru={name:Au.environmentName};Au.environmentVersion!==void 0&&Au.environmentVersion!==""&&(Ru.version=Au.environmentVersion);const Iu={environment:Ru,type:Au.type??"notebook",given_name:Au.givenName,credits_limit:Au.creditsLimit};Au.capabilities&&(Iu.capabilities=Au.capabilities),Au.snapshot&&(Iu.from=Au.snapshot),Au.appUid&&(Iu.app_uid=Au.appUid),Au.deploymentUid&&(Iu.deployment_uid=Au.deploymentUid),Au.appSpec&&(Iu.app_spec=Au.appSpec);const Pu=await requestDatalayerAPI({url:runtimesUrl(runtimesStore.getState().runtimesUrl),method:"POST",body:Iu,token:$u,headers:lo?{"X-External-Token":lo}:void 0});if(!Pu.success||!Pu.runtime){const Ou=`Failed to create a kernel for the environment ${Au.environmentName}.`;throw console.error(Ou,Pu),new Error(Ou)}return Pu.runtime}async function getRuntimes(){const Au=await requestDatalayerAPI({url:runtimesUrl(runtimesStore.getState().runtimesUrl),token:iamStore.getState().token});if(!Au.success){const lo="Failed to list the running kernels.";throw console.error(lo,Au),new Error(lo)}return Au.runtimes??[]}async function getRuntimeRecord(Au){try{return(await requestDatalayerAPI({url:runtimeUrl(runtimesStore.getState().runtimesUrl,Au),token:iamStore.getState().token})).runtime??null}catch(lo){if(lo.response?.status===404)return null;throw lo}}async function deleteRuntime(Au){const lo=iamStore.getState().externalToken;await requestDatalayerAPI({url:runtimeUrl(runtimesStore.getState().runtimesUrl,Au.id)+libExports$5.URLExt.objectToQueryString(Au.reason?{reason:Au.reason}:{}),method:"DELETE",token:iamStore.getState().token,headers:lo?{"X-External-Token":lo}:void 0})}async function snapshotRuntime(Au){const lo=await requestDatalayerAPI({url:sandboxSnapshotsUrl(runtimesStore.getState().runtimesUrl),method:"POST",body:{runtime_name:Au.id,name:Au.name,description:Au.description,stop:Au.stop},token:iamStore.getState().token});if(!lo.success)throw new Error(`Failed to take the code sandbox snapshot ${Au.id} - ${lo}`);if(lo.snapshot)return asCodeSandboxSnapshot(lo.snapshot)}async function getSandboxSnapshots(){const Au=await requestDatalayerAPI({url:sandboxSnapshotsUrl(runtimesStore.getState().runtimesUrl),token:iamStore.getState().token});return Au.success?(Au.snapshots??[]).map(asCodeSandboxSnapshot):(console.error("Failed to fetch code sandbox snapshots.",Au),[])}async function loadSandboxSnapshot(Au){const lo=await requestDatalayerAPI({url:runtimeUrl(runtimesStore.getState().runtimesUrl,Au.id),method:"PUT",body:{from:Au.from},token:iamStore.getState().token});if(!lo.success)throw new Error(`Failed to load the code sandbox snapshot; ${lo.message}`)}function createSandboxSnapshotDownloadURL(Au){return sandboxSnapshotUrl(runtimesStore.getState().runtimesUrl,Au)+libExports$5.URLExt.objectToQueryString({download:"1",token:iamStore.getState().token??""})}function exportCodeSandboxSnapshot(Au){const lo=createSandboxSnapshotDownloadURL(Au),$u=document.createElement("a");$u.href=lo,$u.download="",document.body.appendChild($u),$u.click(),document.body.removeChild($u)}async function deleteCodeSandboxSnapshot(Au){await requestDatalayerAPI({url:sandboxSnapshotUrl(runtimesStore.getState().runtimesUrl,Au),method:"DELETE",token:iamStore.getState().token})}async function updateCodeSandboxSnapshot(Au,lo){(lo.name||lo.description)&&await requestDatalayerAPI({url:sandboxSnapshotUrl(runtimesStore.getState().runtimesUrl,Au),method:"PATCH",body:{...lo},token:iamStore.getState().token})}async function uploadCodeSandboxSnapshot(Au){if(Au.file.size===0)return Promise.reject("Empty Code Sandbox Snapshot.");const lo=new PromiseDelegate,$u=new Upload(Au.file,{endpoint:`${sandboxSnapshotsUrl(runtimesStore.getState().runtimesUrl)}/upload`,headers:{Authorization:`Bearer ${iamStore.getState().token}`},retryDelays:null,metadata:Au.metadata,onError:Iu=>{console.error(`Failed to upload ${Au.metadata.filename}.`,Iu),lo.reject(Iu)},onProgress:Au.onProgress,onSuccess:()=>{lo.resolve()}}),Ru=await $u.findPreviousUploads();return Ru.length&&$u.resumeFromPreviousUpload(Ru[0]),$u.start(),lo.promise}const actions=Object.freeze(Object.defineProperty({__proto__:null,createRuntime,createSandboxSnapshotDownloadURL,deleteCodeSandboxSnapshot,deleteRuntime,exportCodeSandboxSnapshot,getEnvironments,getRuntimeRecord,getRuntimes,getSandboxSnapshots,loadSandboxSnapshot,snapshotRuntime,updateCodeSandboxSnapshot,uploadCodeSandboxSnapshot},Symbol.toStringTag,{value:"Module"})),AGENT_RUNTIME_VARIANTS=["browser-vercelai","local-pydanticai","cloud-pydanticai"],DEFAULT_AGENT_RUNTIME_VARIANT="cloud-pydanticai",VARIANT_BY_LEGACY_TARGET={"backend-services":"cloud-pydanticai","local-agent-runtimes":"local-pydanticai"};function isAgentRuntimeVariant(Au){return typeof Au=="string"&&AGENT_RUNTIME_VARIANTS.includes(Au)}function toAgentRuntimeVariant(Au,lo=DEFAULT_AGENT_RUNTIME_VARIANT){return Au?isAgentRuntimeVariant(Au)?Au:VARIANT_BY_LEGACY_TARGET[Au]??lo:lo}function locationOf(Au){return Au.slice(0,Au.indexOf("-"))}function runsInBrowser(Au){return locationOf(Au)==="browser"}function legacyTargetOf(Au){return locationOf(Au)==="cloud"?"backend-services":"local-agent-runtimes"}const runtimesStore=createStore$1((Au,lo)=>({configuration:{maxNotebookRuntimes:5,maxCellRuntimes:3},setConfiguration:$u=>{Au(Ru=>JSONExt.deepEqual(Ru.configuration,$u)?{}:{configuration:{...$u}})},runtimesUrl:coreStore.getState().configuration?.runtimesUrl,tab:0,getIntTab:()=>Math.floor(lo().tab),setTab:$u=>Au(Ru=>({tab:$u})),runtimes:[],refreshRuntimes:async()=>{const $u=await getRuntimes();JSONExt.deepEqual(lo().runtimes,$u)||Au({runtimes:[...$u]})},removeRuntime:$u=>{if(!$u)return;const Ru=lo().runtimes,Iu=Ru.filter(Pu=>Pu.runtime_name!==$u);Iu.length!==Ru.length&&Au({runtimes:Iu})},runtimeModels:[],addRuntimeModel:$u=>{const Ru=lo().runtimeModels;Ru.findIndex(Pu=>$u.id&&$u.id===Pu.id||!!$u.uid&&$u.uid===Pu.uid)<0&&Au({runtimeModels:[...Ru,$u]})},removeRuntimeModel:$u=>{const Ru=[...lo().runtimeModels],Iu=Ru?.findIndex(Pu=>!!Pu.id&&$u===Pu.id||$u===Pu.runtime_name)??-1;Iu>=0&&(Ru.splice(Iu,1),Au({runtimeModels:Ru}))},setRuntimeModels:$u=>{JSONExt.deepEqual(lo().runtimeModels,$u)||Au({runtimeModels:[...$u]})},multiServiceManager:void 0,setMultiServiceManager:$u=>{Au(Ru=>({multiServiceManager:$u}))},showDisclaimer:!1,setShowDisclaimer:$u=>{Au(Ru=>({showDisclaimer:$u}))},runtimeSnapshots:[],addSandboxSnapshot:$u=>{const Ru=lo().runtimeSnapshots,Iu=Ru.findIndex(Pu=>Pu.id===$u.id);if(Iu<0){const Pu=[...Ru,$u];Au({runtimeSnapshots:Pu})}else if(!JSONExt.deepEqual(Ru[Iu],$u)){const Pu=[...Ru];Pu.splice(Iu,1,$u),Au({runtimeSnapshots:Pu})}},removeSandboxSnapshot:$u=>{const Ru=lo().runtimeSnapshots,Iu=Ru.findIndex(Pu=>Pu.id===$u);if(Iu>=0){const Pu=[...Ru];Pu.splice(Iu,1),Au({runtimeSnapshots:Pu})}},setSandboxSnapshots:$u=>{JSONExt.deepEqual(lo().runtimeSnapshots,$u)||Au({runtimeSnapshots:[...$u]})},version:"",setVersion:$u=>{$u&&!lo().version&&Au(Ru=>({version:$u}))}})),kernelsPoll=new Poll({auto:!0,factory:()=>runtimesStore.getState().refreshRuntimes(),frequency:{interval:61*1e3,backoff:!0,max:300*1e3},name:"@datalayer/jupyter-kernels:KernelsManager#kernels",standby:()=>iamStore.getState().token||runtimesStore.getState().runtimesUrl?"when-hidden":!0});runtimesStore.subscribe((Au,lo)=>{if(!JSONExt.deepEqual(Au.runtimes,lo.runtimes)){const $u=Date.now(),Ru=Math.min(...Au.runtimes.map(Iu=>Iu.expired_at?parseFloat(Iu.expired_at):1/0))*1e3;$u+kernelsPoll.frequency.interval>Ru+2e3&&setTimeout(()=>{kernelsPoll.refresh()},Ru+2e3-$u)}});coreStore.subscribe((Au,lo)=>{if(Au.configuration.runtimesUrl&&Au.configuration.runtimesUrl!==lo.configuration.runtimesUrl){const $u=Au.configuration.runtimesUrl;console.log(`Updating runtimesUrl with new value ${$u}`),runtimesStore.setState({runtimesUrl:$u}),kernelsPoll.refresh().then(()=>kernelsPoll.tick).catch(Ru=>{console.error("Failed to refresh kernel servers list following service URL changed.",Ru)})}});function useRuntimesStore(Au){return useStore$1(runtimesStore,Au)}const DEFAULT_AGENT_CONFIG={name:"ai-agent",description:"AI Assistant",model:"",systemPrompt:"You are a helpful AI assistant.",agentLibrary:"pydantic-ai",protocol:"vercel-ai"};requireManager();const sandboxManagersByRuntime=new Map;function registerSandboxServiceManager(Au,lo){const $u=String(Au||"").trim();if(!$u||!lo)return()=>{};let Ru=sandboxManagersByRuntime.get($u);return Ru||(Ru=new Set,sandboxManagersByRuntime.set($u,Ru)),Ru.add(lo),()=>{const Iu=sandboxManagersByRuntime.get($u);Iu&&(Iu.delete(lo),Iu.size===0&&sandboxManagersByRuntime.delete($u))}}function disposeSandboxServiceManagers(Au){const lo=String(Au||"").trim();if(!lo)return;const $u=sandboxManagersByRuntime.get(lo);$u&&(sandboxManagersByRuntime.delete(lo),$u.forEach(Ru=>{try{disposeServiceManager(Ru)}catch(Iu){console.warn(`[sandboxServiceManagers] Failed disposing service manager for pod ${lo}`,Iu)}}))}function launchesOwnRoutesOnly(Au){return!!Au?.deploymentUid}const base$2=Au=>Au.trim().replace(/\/$/,"");function agentDeletionUrl(Au,lo,$u){if(!$u)return`${base$2(Au)}/api/v1/agents/${encodeURIComponent(lo)}`}function runtimeModelsUrl(Au,lo,$u){if(!$u)return`${base$2(Au)}/api/v1/configure/models?agent_id=${encodeURIComponent(lo)}`}const EMPTY_RUNTIMES=[],BROWSER_AGENT_CONNECTION=Object.freeze({runtimeName:"",environmentName:"",jupyterBaseUrl:"",agentBaseUrl:"",status:"ready",isReady:!0}),AGENT_QUERY_OPTIONS={staleTime:300*1e3,gcTime:600*1e3},agentQueryKeys={agentRuntimes:{all:()=>["agentRuntimes"],lists:()=>[...agentQueryKeys.agentRuntimes.all(),"list"],details:()=>[...agentQueryKeys.agentRuntimes.all(),"detail"],detail:Au=>[...agentQueryKeys.agentRuntimes.details(),Au]},checkpoints:{all:()=>["checkpoints"],lists:()=>[...agentQueryKeys.checkpoints.all(),"list"]}},DELETED_POD_TOMBSTONE_TTL_MS=300*1e3,deletedRuntimeTombstones=new Map;function markRuntimeDeleted(Au){const lo=String(Au||"").trim();lo&&(deletedRuntimeTombstones.set(lo,Date.now()),disposeSandboxServiceManagers(lo))}function clearRuntimeDeleted(Au){deletedRuntimeTombstones.delete(String(Au||"").trim())}const LIVE_RUNTIME_STATUSES=new Set(["running","resumed","starting","resuming"]);function isStaleDeletedRuntime(Au){const lo=String(Au?.runtime_name||"").trim(),$u=deletedRuntimeTombstones.get(lo);return $u===void 0?!1:Date.now()-$u>DELETED_POD_TOMBSTONE_TTL_MS?(deletedRuntimeTombstones.delete(lo),!1):LIVE_RUNTIME_STATUSES.has(Au.status)}const RUNTIME_STATUS_MAP={resume:"resumed",resumed:"resumed",resuming:"resuming",pausing:"pausing",paused:"paused",starting:"starting",pending:"starting",launching:"starting",terminated:"terminated",archived:"archived",running:"running"};function toAgentRuntimeData(Au){const lo=typeof Au.status=="string"?Au.status.toLowerCase():"",$u=RUNTIME_STATUS_MAP[lo]??"running",Ru=Au.environment;return{...Au,environment:{name:String(Ru?.name||"").trim(),title:String(Ru?.title||"").trim()||void 0,cpu:String(Ru?.cpu||"").trim()||void 0,memory:String(Ru?.memory||"").trim()||void 0,gpu:String(Ru?.gpu||"").trim()||void 0,resources:Ru?.resources},status:$u,name:Au.given_name||Au.runtime_name,id:Au.runtime_name,url:Au.ingress,messageCount:0,agent_spec_id:Au.agent_spec_id||void 0,content_attachments:Array.isArray(Au.content_attachments)?Au.content_attachments:[]}}function useAgentRuntimes(Au={}){const{agentSpecId:lo,agentConfig:$u,autoCreateAgent:Ru=!0,autoStart:Iu=!1,agentSpec:Pu,variant:Ou,runtimeCreationTarget:Mu,runtimeCreationBaseUrl:Du,runtimeConnection:Lu,appLaunch:Bu}=Au,ju=toAgentRuntimeVariant(Ou??Mu),Fu=launchesOwnRoutesOnly(Bu),{configuration:zu}=useCoreStore(),Uu=useAgentRuntimeConnection(),Hu=useAgentRuntimeStatus(),Vu=useAgentRuntimeError(),Gu=useAgentRuntimeIsLaunching(),Wu=useAgentRuntimeStore(Ad=>Ad.launchAgent),Ku=useAgentRuntimeStore(Ad=>Ad.connectAgent),Ju=useAgentRuntimeStore(Ad=>Ad.createAgent),Yu=useAgentRuntimeStore(Ad=>Ad.disconnect),[Xu,ed]=reactExports.useState("idle"),[td,nd]=reactExports.useState(null),[od,sd]=reactExports.useState(!1),ad=reactExports.useRef(!1),[pd,gd]=reactExports.useState(!1),yd=reactExports.useRef(!1),_d=reactExports.useRef(null),vd=reactExports.useRef(!1),wd=reactExports.useRef($u);wd.current=$u;const Ed=!!lo&&locationOf(ju)==="cloud",cd=Lu?[Lu.runtimeName,Lu.environmentName,Lu.jupyterBaseUrl||Lu.serviceManager?.serverSettings.baseUrl||"",Lu.kernelId||""].join(":"):null,dd=reactExports.useMemo(()=>Du||(runsInBrowser(ju)?"":locationOf(ju)==="local"?"http://localhost:8765":zu?.runtimesUrl||void 0||"https://r1.datalayer.run"),[zu?.runtimesUrl,Du,ju]),md=reactExports.useCallback(async()=>{try{const{iamStore:Ad,coreStore:$d}=await __vitePreload(async()=>{const{iamStore:Jd,coreStore:gh}=await import("./chunks/index-fQxrRXLD.js");return{iamStore:Jd,coreStore:gh}},[],import.meta.url),Vd=Ad.getState().token||"",Hd=$d.getState().configuration?.aiAgentsUrl||"";return{token:Vd,aiAgentsUrl:Hd,runtimesUrl:dd}}catch{return{token:"",aiAgentsUrl:"",runtimesUrl:""}}},[dd]);reactExports.useEffect(()=>{!Lu||!cd||(Uu?[Uu.runtimeName,Uu.environmentName,Uu.jupyterBaseUrl||"",Uu.kernelId||""].join(":"):null)===cd||(yd.current=!1,Ku(Lu))},[Lu,cd,Uu,Ku]);const ld=reactExports.useCallback(async Ad=>{if(runsInBrowser(ju))return BROWSER_AGENT_CONNECTION;if(Ed){ed("launching"),nd(null);try{const Vd=(typeof $u?.name=="string"&&$u.name||typeof Pu?.name=="string"&&Pu.name||`${lo}`).replace(/\//g,"-").replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"").slice(0,63),Dd=await Wu(Ad?{...Ad,...Bu,runtimesUrl:dd}:{environmentName:"ai-agents-env",creditsLimit:10,givenName:Vd,...Bu,runtimesUrl:dd});return ed("ready"),Dd}catch($d){const Vd=$d instanceof Error?$d.message:String($d);throw nd(Vd),ed("error"),$d}}else{if(!Ad)throw new Error("Runtime options are required in connect mode");return Wu({...Ad,runtimesUrl:dd})}},[$u?.name,Pu?.name,lo,Bu,Ed,dd,Wu,ju]),hd=reactExports.useCallback(async Ad=>{if(vd.current)throw new Error("Agent creation already in progress");vd.current=!0,sd(!0);try{const $d={};Pu&&(Pu.model&&($d.model=Pu.model),Pu.protocol&&($d.protocol=Pu.protocol),Pu.systemPrompt&&($d.systemPrompt=Pu.systemPrompt),Pu.description&&($d.description=Pu.description),Pu.name&&($d.name=Pu.name));const Vd={...DEFAULT_AGENT_CONFIG,...$d,...$u,...Ad,name:Ad?.name||$u?.name||(Ed&&lo?lo:Uu?.runtimeName)};return await Ju(Vd)}catch($d){const Vd=$d instanceof Error?$d.message:String($d);throw Ed&&(nd(Vd),ed("error")),$d}finally{vd.current=!1,sd(!1)}},[lo,$u,Pu,Ed,Uu,Ju]),bd=reactExports.useCallback(async()=>{const Ad=Uu?.agentId,$d=Uu?.agentBaseUrl,Vd=Ad&&$d?agentDeletionUrl($d,Ad,Fu):void 0;if(Vd)try{const{token:Dd}=await md();await fetch(Vd,{method:"DELETE",headers:Dd?{Authorization:`Bearer ${Dd}`}:{}})}catch{}yd.current=!1,ad.current=!1,ed("idle"),nd(null),agentRuntimeStore.getState().reset()},[Uu?.agentId,Uu?.agentBaseUrl,md,Fu]);reactExports.useEffect(()=>{!Ed&&Ru&&Uu&&Hu==="ready"&&!Uu.isReady&&!yd.current&&(yd.current=!0,Ju(wd.current).catch(Ad=>{console.error("[useAgent] Failed to auto-create agent:",Ad),yd.current=!1}))},[Ed,Ru,Uu,Hu,Ju]),reactExports.useEffect(()=>{Ed&&Ru&&Uu&&(Xu==="ready"||Xu==="resumed")&&!Uu.isReady&&!yd.current&&(yd.current=!0,hd(wd.current).catch(Ad=>{console.error("[useAgents] Failed to auto-create agent:",Ad);const $d=Ad instanceof Error?Ad.message:String(Ad);nd($d),ed("error"),yd.current=!1}))},[Ed,Ru,Uu,Xu,hd]),reactExports.useEffect(()=>{const Ad=Uu?.runtimeName||null;if(!Ad){_d.current=null;return}_d.current&&_d.current!==Ad&&(yd.current=!1),_d.current=Ad},[Uu?.runtimeName]),reactExports.useEffect(()=>{if(!Ed||Uu||Xu!=="idle")return;if(Bu){gd(!0);return}let Ad=!1;return(async()=>{try{const{token:Vd,runtimesUrl:Dd}=await md();if(!Vd)return;const{listRuntimes:Hd}=await __vitePreload(async()=>{const{listRuntimes:uh}=await import("./chunks/runtimes-BQWpLsQm.js");return{listRuntimes:uh}},[],import.meta.url),sh=((await Hd(Vd,Dd)).runtimes||[]).filter(uh=>uh.environment?.name!=="ai-agents-env"?!1:lo?uh.agent_spec_id===lo:!0).slice().sort((uh,Oh)=>{const Gd=Number(uh.started_at||0);return Number(Oh.started_at||0)-Gd})[0];if(Ad||!sh?.runtime_name||!sh?.ingress)return;Ku({runtimeName:sh.runtime_name,environmentName:sh.environment.name,jupyterBaseUrl:sh.ingress}),yd.current=!1;const Eh=sh,vh=typeof Eh.status=="string"?Eh.status.toLowerCase():"",Qd=RUNTIME_STATUS_MAP[vh]??"running",th=Qd==="paused"?"paused":Qd==="resuming"||Qd==="resumed"?"resumed":"running";ed(th==="paused"?"paused":th==="resumed"?"resumed":"ready")}catch(Vd){console.warn("[useAgents] Failed to find existing runtime:",Vd)}finally{Ad||gd(!0)}})(),()=>{Ad=!0}},[Ed,Uu,Iu,Xu,md,lo,Bu,Ku]),reactExports.useEffect(()=>{(Hu==="disconnected"||Hu==="idle")&&(yd.current=!1)},[Hu]),reactExports.useEffect(()=>{Ed&&Iu&&pd&&!Uu&&!ad.current&&Xu==="idle"&&(ad.current=!0,ld())},[Ed,Iu,pd,Uu,Xu,ld]),reactExports.useEffect(()=>{Vu&&Ed&&Xu!=="error"&&(nd(Vu),ed("error"))},[Vu,Ed,Xu]);const Sd=runsInBrowser(ju),kd=Sd?"ready":Ed?Xu:Hu,Rd=Sd?null:Ed&&td||Vu,Od=Sd?!0:Ed?(Xu==="ready"||Xu==="resumed")&&!!Uu?.isReady:Hu==="ready"&&!!Uu?.isReady,jd=Uu?.endpoint||null,Cd=Uu?.serviceManager||null;return{runtime:Uu,status:kd,isLaunching:Gu,launchRuntime:ld,connectToRuntime:Ku,disconnect:Yu,endpoint:jd,serviceManager:Cd,createAgent:hd,teardown:bd,isCreating:od,isReady:Od,error:Rd,variant:ju,runtimeCreationTarget:legacyTargetOf(ju),runtimeCreationBaseUrl:dd}}function useAgentRuntimesQuery(Au,lo){const{configuration:$u}=useCoreStore(),{requestDatalayer:Ru}=useDatalayer({notifyOnError:!1}),{user:Iu}=useIAMStore(),Pu=useQueryClient();return useQuery({queryKey:[...agentQueryKeys.agentRuntimes.lists(),"","","",""],queryFn:async()=>{const Mu=new URLSearchParams().toString(),Du=await Ru({url:`${runtimesUrl($u.runtimesUrl)}${Mu?`?${Mu}`:""}`,method:"GET"});if(Du.success&&Du.runtimes){const Lu=Du.runtimes.filter(Bu=>Bu.environment?.name==="ai-agents-env").map(toAgentRuntimeData).filter(Bu=>!isStaleDeletedRuntime(Bu));return Lu.forEach(Bu=>{Pu.setQueryData(agentQueryKeys.agentRuntimes.detail(Bu.runtime_name),Bu)}),Lu}return[]},...AGENT_QUERY_OPTIONS,refetchInterval:lo?.refetchInterval??1e4,refetchOnMount:!0,refetchOnWindowFocus:!0,enabled:(lo?.enabled??!0)&&!!Iu})}function useCreateAgentRuntime(){const{configuration:Au}=useCoreStore(),{requestDatalayer:lo}=useDatalayer({notifyOnError:!1}),$u=useQueryClient();return useMutation({mutationFn:async Ru=>{const Iu=(Ru.contentAttachmentUids??[]).map(Pu=>String(Pu||"").trim()).filter(Boolean);return lo({url:runtimesUrl(Au.runtimesUrl),method:"POST",body:{environment:{name:Ru.environmentName||"ai-agents-env"},given_name:Ru.givenName||"Agent",credits_limit:Ru.creditsLimit||10,type:Ru.type||"notebook",editor_variant:Ru.editorVariant||"none",enable_codemode:Ru.enableCodemode??!1,agent_spec_id:Ru.agentSpecId||void 0,agent_spec:Ru.agentSpec||void 0,user_account_handle:Ru.userAccountHandle||void 0,billing_entity_uid:Ru.billingEntityUid||void 0,billing_entity_type:Ru.billingEntityType||void 0,billing_entity_handle:Ru.billingEntityHandle||void 0,billing_source_organization_uid:Ru.billingSourceOrganizationUid||void 0,billing_source_organization_handle:Ru.billingSourceOrganizationHandle||void 0,runtime_name:Ru.runtimeName||void 0,content_attachment_uids:Iu.length?Iu:void 0}})},onSuccess:Ru=>{if(Ru.success&&Ru.runtime){const Iu=toAgentRuntimeData(Ru.runtime);clearRuntimeDeleted(Iu.runtime_name),$u.setQueryData(agentQueryKeys.agentRuntimes.detail(Iu.runtime_name),Iu),$u.invalidateQueries({queryKey:agentQueryKeys.agentRuntimes.all()})}}})}function useDeleteAgentRuntime(){const{configuration:Au}=useCoreStore(),{requestDatalayer:lo}=useDatalayer({notifyOnError:!1}),$u=useQueryClient(),Ru=Pu=>{if(!Pu||typeof Pu!="object")return;const Ou=Pu.response;return typeof Ou?.status=="number"?Ou.status:void 0},Iu=Pu=>{if(!Pu||typeof Pu!="object")return"";const Ou=Pu.response?.data;return String(Ou?.detail||Ou?.message||Pu.message||"").toLowerCase()};return useMutation({mutationFn:async Pu=>{try{return await lo({url:runtimeUrl(Au.runtimesUrl,Pu),method:"DELETE"})}catch(Ou){const Mu=Ru(Ou),Du=Iu(Ou);if(!(Mu===404||Du.includes("no reservation")||Du.includes("unknown reservation")||Du.includes("not found")))throw Ou;try{throw await lo({url:runtimeUrl(Au.runtimesUrl,Pu),method:"GET"}),Ou}catch(Bu){if(Ru(Bu)===404)return{success:!0,recovered:!0};throw Ou}}},onSuccess:(Pu,Ou)=>{markRuntimeDeleted(Ou),runtimesStore.getState().removeRuntime(Ou),$u.setQueriesData({queryKey:agentQueryKeys.agentRuntimes.lists()},Mu=>Array.isArray(Mu)?Mu.filter(Du=>Du.runtime_name!==Ou):Mu),$u.cancelQueries({queryKey:agentQueryKeys.agentRuntimes.detail(Ou)}),$u.removeQueries({queryKey:agentQueryKeys.agentRuntimes.detail(Ou)}),$u.invalidateQueries({queryKey:agentQueryKeys.agentRuntimes.lists()}),$u.refetchQueries({queryKey:agentQueryKeys.agentRuntimes.lists(),type:"active"}),$u.invalidateQueries({queryKey:agentQueryKeys.checkpoints.all()})}})}function useRefreshAgentRuntimes(){const Au=useQueryClient();return reactExports.useCallback(()=>{Au.invalidateQueries({queryKey:agentQueryKeys.agentRuntimes.all()})},[Au])}const DEFAULT_LIFECYCLE_RECORD={resumePending:!1,pauseLockedForResumed:!1};create$g()(persist((Au,lo)=>({byRuntimeKey:{},markResumePending:$u=>{$u&&Au(Ru=>({byRuntimeKey:{...Ru.byRuntimeKey,[$u]:{...DEFAULT_LIFECYCLE_RECORD,...Ru.byRuntimeKey[$u]??{},resumePending:!0}}}))},markResumeFailed:$u=>{$u&&Au(Ru=>({byRuntimeKey:{...Ru.byRuntimeKey,[$u]:{...DEFAULT_LIFECYCLE_RECORD,...Ru.byRuntimeKey[$u]??{},resumePending:!1,pauseLockedForResumed:!1}}}))},markResumeSettled:$u=>{$u&&Au(Ru=>({byRuntimeKey:{...Ru.byRuntimeKey,[$u]:{...DEFAULT_LIFECYCLE_RECORD,...Ru.byRuntimeKey[$u]??{},resumePending:!1,pauseLockedForResumed:!0}}}))},clearRuntimeLifecycle:$u=>{if(!$u)return;const Ru={...lo().byRuntimeKey};delete Ru[$u],Au({byRuntimeKey:Ru})}}),{name:"datalayer-agent-lifecycle",storage:createJSONStorage(()=>localStorage),partialize:Au=>({byRuntimeKey:Au.byRuntimeKey})}));function useAgentsRuntimes(Au,lo){const $u=useAgentRuntimesQuery(Au,lo),Ru=useCreateAgentRuntime(),Iu=useDeleteAgentRuntime(),Pu=useRefreshAgentRuntimes(),Ou=reactExports.useCallback(async(Mu,Du)=>{const Lu=String(Mu||"").trim();if(Lu)return Du?.beforeStop&&await Du.beforeStop(),Iu.mutateAsync(Lu)},[Iu]);return reactExports.useMemo(()=>({runtimes:$u.data??EMPTY_RUNTIMES,isRuntimesLoading:$u.isLoading,isRuntimesError:$u.isError,runtimesError:$u.error,refetchRuntimes:()=>$u.refetch(),refreshRuntimes:Pu,stopRuntimeByName:Ou,createRuntime:async Mu=>Ru.mutateAsync(Mu)}),[$u.data,$u.isLoading,$u.isError,$u.error,$u.refetch,Pu,Ou,Ru,Iu])}const DEFAULT_WS_PATH="/api/v1/tool-approvals/ws",DEFAULT_RECONNECT_DELAY_MS=3e3;function useAgentRuntimeWebSocket(Au){const{enabled:lo=!0,baseUrl:$u,authToken:Ru,agentId:Iu,autoReconnect:Pu=!0,reconnectDelayMs:Ou=DEFAULT_RECONNECT_DELAY_MS,maxReconnectAttempts:Mu}=Au,Du=reactExports.useRef(Au.onMessage);Du.current=Au.onMessage,reactExports.useEffect(()=>{if(!lo||!$u){agentRuntimeStore.getState().setWsState("closed");return}let Lu=!1,Bu=0,ju=null;function Fu(){const Uu=`${$u}${DEFAULT_WS_PATH}`,Hu=new URL(Uu.replace(/^http/,"ws"));return Ru&&Hu.searchParams.set("token",Ru),Iu&&Hu.searchParams.set("agent_id",Iu),Hu.toString()}function zu(){if(Lu)return;const Uu=Fu();agentRuntimeStore.getState().setWsState("connecting");const Hu=new WebSocket(Uu);agentRuntimeStore.getState().setWs(Hu,Iu),Hu.onopen=()=>{Bu=0,agentRuntimeStore.getState().setWsState("connected")},Hu.onmessage=Vu=>{let Gu;try{Gu=JSON.parse(String(Vu.data))}catch{return}const Wu=parseAgentStreamMessage(Gu);if(Du.current?.({type:Wu?.type,payload:Wu?.payload,raw:Gu}),!Wu)return;const Ku=agentRuntimeStore.getState();if(Wu.type==="agent.snapshot"){Ku.applySnapshot(Wu.payload);return}if(Wu.type==="agent.subagent"){Ku.appendSubagentEvent(Wu.payload);return}if(Wu.type==="agent.compaction"){Ku.setCompaction(Wu.payload);return}},Hu.onclose=()=>{if(agentRuntimeStore.getState().setWs(null,Iu),agentRuntimeStore.getState().setWsState("closed"),Lu||!Pu||(Bu+=1,typeof Mu=="number"&&Bu>Mu))return;const Vu=typeof Ou=="function"?Ou(Bu):Ou;ju=setTimeout(zu,Math.max(0,Vu))},Hu.onerror=()=>{(Hu.readyState===WebSocket.CONNECTING||Hu.readyState===WebSocket.OPEN)&&Hu.close()}}return zu(),()=>{Lu=!0,ju&&clearTimeout(ju),agentRuntimeStore.getState().setWs(null,Iu),agentRuntimeStore.getState().resetWs()}},[lo,$u,Ru,Iu,Pu,Ou,Mu])}const ALPHAVANTAGE_MCP_SERVER_0_0_1={id:"alphavantage",version:"0.0.1",name:"Alpha Vantage",description:"Financial market data and stock information",icon:"@primer/octicons-react:graph",emoji:"💹",url:"",command:"uvx",args:["av-mcp==0.2.1","${ALPHAVANTAGE_API_KEY}"],transport:"stdio",enabled:!1,isAvailable:!1,tools:[],requiredEnvVars:["ALPHAVANTAGE_API_KEY:0.0.1"]},CHART_MCP_SERVER_0_0_1={id:"chart",version:"0.0.1",name:"Chart Generator",description:"Generate charts and visualizations",icon:"@datalayer/icons-react:chart-bar",emoji:"📊",url:"",command:"npx",args:["-y","@antv/mcp-server-chart"],transport:"stdio",enabled:!1,isAvailable:!1,tools:[],requiredEnvVars:[]},DATALAYER_MCP_SERVER_0_0_1={id:"datalayer",version:"0.0.1",name:"Datalayer",description:"Read, edit and run Jupyter notebooks on Datalayer, with sandboxes and data",icon:"@datalayer/icons-react:datalayer",emoji:"🚀",url:"",command:"npx",args:["-y","mcp-remote","https://mcp.datalayer.run/mcp","--header","Authorization: Bearer ${DATALAYER_API_KEY}"],transport:"stdio",enabled:!1,isAvailable:!1,tools:[],requiredEnvVars:["DATALAYER_API_KEY:0.0.1"]},EARTHDATA_MCP_SERVER_0_0_1={id:"earthdata",version:"0.0.1",name:"Earthdata MCP",description:"Access NASA Earthdata search and metadata capabilities",icon:"@datalayer/icons-react:globe-americas",emoji:"🌍",url:"",command:"npx",args:["-y","mcp-remote","https://mcp.datalayer.run/mcp?only=earthdata","--header","Authorization: Bearer ${DATALAYER_API_KEY}"],transport:"stdio",enabled:!0,isAvailable:!1,tools:[],requiredEnvVars:["DATALAYER_API_KEY:0.0.1"]},EURUS_MCP_SERVER_0_0_1={id:"eurus",version:"0.0.1",name:"Eurus Climate MCP",description:"Climate and reanalysis analysis tools for spatial workflows",icon:"@primer/octicons-react:cloud",emoji:"🌦️",url:"",command:"eurus-mcp",args:[],transport:"stdio",enabled:!1,isAvailable:!1,tools:[],requiredEnvVars:[]},FILESYSTEM_MCP_SERVER_0_0_1={id:"filesystem",version:"0.0.1",name:"Filesystem",description:"Local filesystem read/write operations",icon:"@primer/octicons-react:file-directory",emoji:"📁",url:"",command:"npx",args:["-y","@modelcontextprotocol/server-filesystem","${TMPDIR}"],transport:"stdio",enabled:!1,isAvailable:!1,tools:[],requiredEnvVars:[]},GITHUB_MCP_SERVER_0_0_1={id:"github",version:"0.0.1",name:"GitHub",description:"GitHub repository operations (issues, PRs, code search)",icon:"@datalayer/icons-react:github-mark",emoji:"🐙",url:"",command:"docker",args:["run","-i","--rm","-e","GITHUB_PERSONAL_ACCESS_TOKEN","ghcr.io/github/github-mcp-server"],transport:"stdio",enabled:!1,isAvailable:!1,tools:[],requiredEnvVars:["GITHUB_TOKEN:0.0.1"]},GOOGLE_WORKSPACE_MCP_SERVER_0_0_1={id:"google-workspace",version:"0.0.1",name:"Google Workspace",description:"Gmail of the person an application acts for, read or read and send, with a token Datalayer mints per call",icon:"@datalayer/icons-react:google",emoji:"📧",url:"http://127.0.0.1:9711/mcp",command:"uvx",args:["workspace-mcp","--transport","streamable-http","--permissions","gmail:send"],transport:"streamable-http",enabled:!1,isAvailable:!1,tools:[],requiredEnvVars:[]},HUGGINGFACE_MCP_SERVER_0_0_1={id:"huggingface",version:"0.0.1",name:"Hugging Face",description:"Hugging Face models, datasets, spaces, and papers access",icon:"@primer/octicons-react:hubot",emoji:"🤗",url:"",command:"npx",args:["-y","mcp-remote","https://huggingface.co/mcp","--header","Authorization: Bearer ${HF_TOKEN}"],transport:"stdio",enabled:!1,isAvailable:!1,tools:[],requiredEnvVars:["HF_TOKEN:0.0.1"]},KAGGLE_MCP_SERVER_0_0_1={id:"kaggle",version:"0.0.1",name:"Kaggle",description:"Kaggle datasets, models, competitions, and notebooks access",icon:"@datalayer/icons-react:kaggle",emoji:"🏆",url:"",command:"npx",args:["-y","mcp-remote","https://www.kaggle.com/mcp","--header","Authorization: Bearer ${KAGGLE_API_TOKEN}"],transport:"stdio",enabled:!1,isAvailable:!1,tools:[],requiredEnvVars:["KAGGLE_API_TOKEN:0.0.1"]},ODOO_ACCOUNTING_MCP_SERVER_0_0_1={id:"odoo-accounting",version:"0.0.1",name:"Odoo Accounting",description:"An accountant's day in Odoo — invoices, bills, journal entries, reconciliations, bank lines and tax returns — through the Datalayer MCP server",icon:"@datalayer/icons-react:odoo",emoji:"🧮",url:"",command:"npx",args:["-y","mcp-remote","https://mcp.datalayer.run/mcp?only=odoo-accounting","--header","Authorization: Bearer ${DATALAYER_API_KEY}"],transport:"stdio",enabled:!1,isAvailable:!1,tools:[],requiredEnvVars:["DATALAYER_API_KEY:0.0.1"]},ODOO_MCP_SERVER_0_0_1={id:"odoo",version:"0.0.1",name:"Odoo",description:"Odoo ERP operations (search, invoices, journals, reconciliations)",icon:"@datalayer/icons-react:odoo",emoji:"🧾",url:"",command:"uvx",args:["mcp-server-odoo"],transport:"stdio",enabled:!1,isAvailable:!1,tools:[],requiredEnvVars:[]},SALESFORCE_MCP_SERVER_0_0_1={id:"salesforce",version:"0.0.1",name:"Salesforce",description:"Salesforce CRM operations (queries, reports, objects, SOQL)",icon:"@primer/octicons-react:briefcase",emoji:"☁️",url:"",command:"npx",args:["-y","@anthropic/salesforce-mcp-server"],transport:"stdio",enabled:!1,isAvailable:!1,tools:[],requiredEnvVars:["SALESFORCE_ACCESS_TOKEN:0.0.1","SALESFORCE_INSTANCE_URL:0.0.1"]},SLACK_MCP_SERVER_0_0_1={id:"slack",version:"0.0.1",name:"Slack",description:"Slack messaging and channel operations",icon:"@datalayer/icons-react:slack",emoji:"💬",url:"",command:"npx",args:["-y","@datalayer/slack-mcp-server"],transport:"stdio",enabled:!1,isAvailable:!1,tools:[],requiredEnvVars:["SLACK_BOT_TOKEN:0.0.1","SLACK_TEAM_ID:0.0.1","SLACK_CHANNEL_IDS:0.0.1"]},TAVILY_MCP_SERVER_0_0_1={id:"tavily",version:"0.0.1",name:"Tavily Search",description:"Web search and research capabilities via Tavily API",icon:"@primer/octicons-react:search",emoji:"🔍",url:"",command:"npx",args:["-y","tavily-mcp"],transport:"stdio",enabled:!0,isAvailable:!1,tools:[],requiredEnvVars:["TAVILY_API_KEY:0.0.1"]},MCP_SERVER_LIBRARY={alphavantage:ALPHAVANTAGE_MCP_SERVER_0_0_1,chart:CHART_MCP_SERVER_0_0_1,datalayer:DATALAYER_MCP_SERVER_0_0_1,earthdata:EARTHDATA_MCP_SERVER_0_0_1,eurus:EURUS_MCP_SERVER_0_0_1,filesystem:FILESYSTEM_MCP_SERVER_0_0_1,github:GITHUB_MCP_SERVER_0_0_1,"google-workspace":GOOGLE_WORKSPACE_MCP_SERVER_0_0_1,huggingface:HUGGINGFACE_MCP_SERVER_0_0_1,kaggle:KAGGLE_MCP_SERVER_0_0_1,"odoo-accounting":ODOO_ACCOUNTING_MCP_SERVER_0_0_1,odoo:ODOO_MCP_SERVER_0_0_1,salesforce:SALESFORCE_MCP_SERVER_0_0_1,slack:SLACK_MCP_SERVER_0_0_1,tavily:TAVILY_MCP_SERVER_0_0_1},ACCOUNTING_SKILL_SPEC_0_0_1={id:"accounting",version:"0.0.1",name:"Accounting Skill",description:"Accounting analysis workflows for reconciliation, close, variance, and audit-ready summaries",module:"agent_skills.skills.accounting",package:void 0,method:void 0,path:void 0,requiredEnvVars:[],optionalEnvVars:[],dependencies:["pandas>=2.0.0"],tags:["accounting","finance","reconciliation","close"],icon:"@primer/octicons-react:book",emoji:"🧮",enabled:!1},CRAWL_SKILL_SPEC_0_0_1={id:"crawl",version:"0.0.1",name:"Web Crawl Skill",description:"Web crawling and content extraction capabilities",module:"agent_skills.skills.crawl",package:void 0,method:void 0,path:void 0,requiredEnvVars:["TAVILY_API_KEY:0.0.1"],optionalEnvVars:[],dependencies:["requests>=2.31.0","beautifulsoup4>=4.12.0"],tags:["web","crawl","scraping"],icon:"@primer/octicons-react:globe",emoji:"🌐",enabled:!0},EVENTS_SKILL_SPEC_0_0_1={id:"events",version:"0.0.1",name:"Events Skill",description:"Event generation, enrichment, and lifecycle orchestration",module:"agent_skills.skills.events",package:void 0,method:void 0,path:void 0,requiredEnvVars:[],optionalEnvVars:[],dependencies:["httpx>=0.27.0"],tags:["events","orchestration","automation"],icon:"@primer/octicons-react:calendar",emoji:"📅",enabled:!1},GITHUB_SKILL_SPEC_0_0_1={id:"github",version:"0.0.1",name:"GitHub Skill",description:"GitHub repository management and code operations",module:"agent_skills.skills.github",package:void 0,method:void 0,path:void 0,requiredEnvVars:["GITHUB_TOKEN:0.0.1"],optionalEnvVars:[],dependencies:["PyGithub>=2.1.0"],tags:["github","git","code"],icon:"@datalayer/icons-react:github-mark",emoji:"🐙",enabled:!1},JOKES_SKILL_SPEC_0_0_1={id:"jokes",version:"0.0.1",name:"Jokes Skill",description:"Return random jokes from a local path-based skill.",module:void 0,package:void 0,method:void 0,path:"jokes",requiredEnvVars:[],optionalEnvVars:[],dependencies:[],tags:["fun","humor","demo"],icon:"@primer/octicons-react:smiley",emoji:"😄",enabled:!1},PDF_SKILL_SPEC_0_0_1={id:"pdf",version:"0.0.1",name:"PDF Processing Skill",description:"PDF document reading, parsing, and extraction",module:"agent_skills.skills.pdf",package:void 0,method:void 0,path:void 0,requiredEnvVars:[],optionalEnvVars:[],dependencies:["PyPDF2>=3.0.0","pdfplumber>=0.10.0"],tags:["pdf","documents","extraction"],icon:"@primer/octicons-react:file",emoji:"📄",enabled:!1},TEXT_SUMMARIZER_SKILL_SPEC_0_0_1={id:"text-summarizer",version:"0.0.1",name:"Text Summarizer Skill",description:"Summarize text content using extractive and abstractive techniques. Use when the user asks for summaries, key points, or condensed versions of documents.",module:void 0,package:"agent_skills.skills.text_summarizer",method:"summarize_text",path:void 0,requiredEnvVars:[],optionalEnvVars:[],dependencies:["agent-skills>=0.0.1"],tags:["nlp","summarization","text-processing"],icon:"@primer/octicons-react:note",emoji:"📝",enabled:!1},SKILLS_CATALOG={accounting:ACCOUNTING_SKILL_SPEC_0_0_1,crawl:CRAWL_SKILL_SPEC_0_0_1,events:EVENTS_SKILL_SPEC_0_0_1,github:GITHUB_SKILL_SPEC_0_0_1,jokes:JOKES_SKILL_SPEC_0_0_1,pdf:PDF_SKILL_SPEC_0_0_1,"text-summarizer":TEXT_SUMMARIZER_SKILL_SPEC_0_0_1},CREATE_PLAN_BACKEND_TOOL_SPEC_0_0_1={id:"create-plan",version:"0.0.1",name:"Create Plan",description:"Create a plan with multiple steps and emit an AG-UI state snapshot.",tags:["example","ag-ui","state"],enabled:!0,approval:"auto",timeout:void 0,requiresApproval:!1,runtime:{language:"python",package:"agent_runtimes.examples.tools.ag_ui",method:"create_plan"},icon:"@primer/octicons-react:list-unordered",emoji:"📋"},CURRENT_TIME_BACKEND_TOOL_SPEC_0_0_1={id:"current-time",version:"0.0.1",name:"Current Time",description:"Return the current time in ISO format for a given timezone.",tags:["example","ag-ui","time"],enabled:!0,approval:"auto",timeout:void 0,requiresApproval:!1,runtime:{language:"python",package:"agent_runtimes.examples.tools.ag_ui",method:"current_time"},icon:"@primer/octicons-react:clock",emoji:"🕒"},DECIDE_BACKEND_TOOL_SPEC_0_0_1={id:"decide",version:"0.0.1",name:"Decide",description:"Ask Jev typed questions about a text — noul (does a statement hold, with its probability), choice (one of named options) or score (a step on a rubric) — and get the typed answers back, through datalayer-ai-inference.",tags:["runtime","decisions","jev"],enabled:!0,approval:"auto",timeout:void 0,requiresApproval:!1,runtime:{language:"python",package:"agent_runtimes.tools.decisions",method:"decide"},icon:"@primer/octicons-react:law",emoji:"⚖️"},DISPLAY_RECIPE_BACKEND_TOOL_SPEC_0_0_1={id:"display-recipe",version:"0.0.1",name:"Display Recipe",description:"Update the shared recipe state and emit an AG-UI state snapshot.",tags:["example","ag-ui","shared-state"],enabled:!0,approval:"auto",timeout:void 0,requiresApproval:!1,runtime:{language:"python",package:"agent_runtimes.examples.tools.ag_ui",method:"display_recipe"},icon:"@primer/octicons-react:book",emoji:"🍳"},EXAMPLE_CREATE_PLAN_BACKEND_TOOL_SPEC_0_0_1={id:"example-create-plan",version:"0.0.1",name:"Create Plan",description:"Create a plan with multiple steps and emit an AG-UI state snapshot.",tags:["example","ag-ui","state"],enabled:!0,approval:"auto",timeout:void 0,requiresApproval:!1,runtime:{language:"python",package:"agent_runtimes.examples.tools.ag_ui",method:"create_plan"},icon:"@primer/octicons-react:list-unordered",emoji:"📋"},EXAMPLE_CURRENT_TIME_BACKEND_TOOL_SPEC_0_0_1={id:"example-current-time",version:"0.0.1",name:"Current Time",description:"Return the current time in ISO format for a given timezone.",tags:["example","ag-ui","time"],enabled:!0,approval:"auto",timeout:void 0,requiresApproval:!1,runtime:{language:"python",package:"agent_runtimes.examples.tools.ag_ui",method:"current_time"},icon:"@primer/octicons-react:clock",emoji:"🕒"},EXAMPLE_DISPLAY_RECIPE_BACKEND_TOOL_SPEC_0_0_1={id:"example-display-recipe",version:"0.0.1",name:"Display Recipe",description:"Update the shared recipe state and emit an AG-UI state snapshot.",tags:["example","ag-ui","shared-state"],enabled:!0,approval:"auto",timeout:void 0,requiresApproval:!1,runtime:{language:"python",package:"agent_runtimes.examples.tools.ag_ui",method:"display_recipe"},icon:"@primer/octicons-react:book",emoji:"🍳"},EXAMPLE_GENERATE_HAIKU_BACKEND_TOOL_SPEC_0_0_1={id:"example-generate-haiku",version:"0.0.1",name:"Generate Haiku",description:"Generate a haiku (Japanese + English + gradient) rendered as a card by the frontend.",tags:["example","ag-ui","generative-ui"],enabled:!0,approval:"auto",timeout:void 0,requiresApproval:!1,runtime:{language:"python",package:"agent_runtimes.examples.tools.ag_ui",method:"generate_haiku"},icon:"@primer/octicons-react:pencil",emoji:"🖋️"},EXAMPLE_GENERATE_TASK_STEPS_BACKEND_TOOL_SPEC_0_0_1={id:"example-generate-task-steps",version:"0.0.1",name:"Generate Task Steps",description:"Generate task steps for human review and emit an AG-UI state snapshot.",tags:["example","ag-ui","human-in-the-loop"],enabled:!0,approval:"auto",timeout:void 0,requiresApproval:!1,runtime:{language:"python",package:"agent_runtimes.examples.tools.ag_ui",method:"generate_task_steps"},icon:"@primer/octicons-react:tasklist",emoji:"🙋"},EXAMPLE_GET_WEATHER_BACKEND_TOOL_SPEC_0_0_1={id:"example-get-weather",version:"0.0.1",name:"Get Weather",description:"Fetch current weather for a location from the Open-Meteo API for frontend rendering.",tags:["example","ag-ui","weather"],enabled:!0,approval:"auto",timeout:void 0,requiresApproval:!1,runtime:{language:"python",package:"agent_runtimes.examples.tools.ag_ui",method:"get_weather"},icon:"@primer/octicons-react:sun",emoji:"🌤️"},EXAMPLE_RENDER_A2UI_SURFACE_BACKEND_TOOL_SPEC_0_0_1={id:"example-render-a2ui-surface",version:"0.0.1",name:"Render A2UI Surface",description:"Turn a declarative field spec into a validated A2UI v0.9 surface rendered live by the frontend as an interactive form/card.",tags:["example","ag-ui","a2ui","generative-ui"],enabled:!0,approval:"auto",timeout:void 0,requiresApproval:!1,runtime:{language:"python",package:"agent_runtimes.examples.tools.a2ui",method:"render_a2ui_surface"},icon:"@primer/octicons-react:browser",emoji:"🎛️"},EXAMPLE_UPDATE_PLAN_STEP_BACKEND_TOOL_SPEC_0_0_1={id:"example-update-plan-step",version:"0.0.1",name:"Update Plan Step",description:"Update a plan step and emit an AG-UI state delta (JSON Patch RFC 6902).",tags:["example","ag-ui","state"],enabled:!0,approval:"auto",timeout:void 0,requiresApproval:!1,runtime:{language:"python",package:"agent_runtimes.examples.tools.ag_ui",method:"update_plan_step"},icon:"@primer/octicons-react:checklist",emoji:"✅"},GENERATE_HAIKU_BACKEND_TOOL_SPEC_0_0_1={id:"generate-haiku",version:"0.0.1",name:"Generate Haiku",description:"Generate a haiku (Japanese + English + gradient) rendered as a card by the frontend.",tags:["example","ag-ui","generative-ui"],enabled:!0,approval:"auto",timeout:void 0,requiresApproval:!1,runtime:{language:"python",package:"agent_runtimes.examples.tools.ag_ui",method:"generate_haiku"},icon:"@primer/octicons-react:pencil",emoji:"🖋️"},GENERATE_TASK_STEPS_BACKEND_TOOL_SPEC_0_0_1={id:"generate-task-steps",version:"0.0.1",name:"Generate Task Steps",description:"Generate task steps for human review and emit an AG-UI state snapshot.",tags:["example","ag-ui","human-in-the-loop"],enabled:!0,approval:"auto",timeout:void 0,requiresApproval:!1,runtime:{language:"python",package:"agent_runtimes.examples.tools.ag_ui",method:"generate_task_steps"},icon:"@primer/octicons-react:tasklist",emoji:"🙋"},GET_WEATHER_BACKEND_TOOL_SPEC_0_0_1={id:"get-weather",version:"0.0.1",name:"Get Weather",description:"Fetch current weather for a location from the Open-Meteo API for frontend rendering.",tags:["example","ag-ui","weather"],enabled:!0,approval:"auto",timeout:void 0,requiresApproval:!1,runtime:{language:"python",package:"agent_runtimes.examples.tools.ag_ui",method:"get_weather"},icon:"@primer/octicons-react:sun",emoji:"🌤️"},RUNTIME_ECHO_BACKEND_TOOL_SPEC_0_0_1={id:"runtime-echo",version:"0.0.1",name:"Runtime Echo",description:"Echo text back to the caller for quick runtime verification.",tags:["runtime","utility"],enabled:!0,approval:"auto",timeout:void 0,requiresApproval:!1,runtime:{language:"python",package:"agent_runtimes.examples.tools",method:"runtime_echo"},icon:"@primer/octicons-react:comment",emoji:"💬"},RUNTIME_SEND_MAIL_BACKEND_TOOL_SPEC_0_0_1={id:"runtime-send-mail",version:"0.0.1",name:"Runtime Send Mail (Fake)",description:"Fake mail sender for tool approval demos; returns a simulated send receipt.",tags:["runtime","approval","mail"],enabled:!0,approval:"manual",timeout:void 0,requiresApproval:!0,runtime:{language:"python",package:"agent_runtimes.examples.tools",method:"runtime_send_mail"},icon:"@primer/octicons-react:mail",emoji:"📧"},RUNTIME_SENSITIVE_ECHO_BACKEND_TOOL_SPEC_0_0_1={id:"runtime-sensitive-echo",version:"0.0.1",name:"Runtime Sensitive Echo",description:"Echo text with a manual approval checkpoint before execution.",tags:["runtime","approval"],enabled:!0,approval:"manual",timeout:void 0,requiresApproval:!0,runtime:{language:"python",package:"agent_runtimes.examples.tools",method:"runtime_sensitive_echo"},icon:"@primer/octicons-react:shield",emoji:"🛡️"},UPDATE_PLAN_STEP_BACKEND_TOOL_SPEC_0_0_1={id:"update-plan-step",version:"0.0.1",name:"Update Plan Step",description:"Update a plan step and emit an AG-UI state delta (JSON Patch RFC 6902).",tags:["example","ag-ui","state"],enabled:!0,approval:"auto",timeout:void 0,requiresApproval:!1,runtime:{language:"python",package:"agent_runtimes.examples.tools.ag_ui",method:"update_plan_step"},icon:"@primer/octicons-react:checklist",emoji:"✅"},BACKEND_TOOL_CATALOG={"create-plan":CREATE_PLAN_BACKEND_TOOL_SPEC_0_0_1,"current-time":CURRENT_TIME_BACKEND_TOOL_SPEC_0_0_1,decide:DECIDE_BACKEND_TOOL_SPEC_0_0_1,"display-recipe":DISPLAY_RECIPE_BACKEND_TOOL_SPEC_0_0_1,"example-create-plan":EXAMPLE_CREATE_PLAN_BACKEND_TOOL_SPEC_0_0_1,"example-current-time":EXAMPLE_CURRENT_TIME_BACKEND_TOOL_SPEC_0_0_1,"example-display-recipe":EXAMPLE_DISPLAY_RECIPE_BACKEND_TOOL_SPEC_0_0_1,"example-generate-haiku":EXAMPLE_GENERATE_HAIKU_BACKEND_TOOL_SPEC_0_0_1,"example-generate-task-steps":EXAMPLE_GENERATE_TASK_STEPS_BACKEND_TOOL_SPEC_0_0_1,"example-get-weather":EXAMPLE_GET_WEATHER_BACKEND_TOOL_SPEC_0_0_1,"example-render-a2ui-surface":EXAMPLE_RENDER_A2UI_SURFACE_BACKEND_TOOL_SPEC_0_0_1,"example-update-plan-step":EXAMPLE_UPDATE_PLAN_STEP_BACKEND_TOOL_SPEC_0_0_1,"generate-haiku":GENERATE_HAIKU_BACKEND_TOOL_SPEC_0_0_1,"generate-task-steps":GENERATE_TASK_STEPS_BACKEND_TOOL_SPEC_0_0_1,"get-weather":GET_WEATHER_BACKEND_TOOL_SPEC_0_0_1,"runtime-echo":RUNTIME_ECHO_BACKEND_TOOL_SPEC_0_0_1,"runtime-send-mail":RUNTIME_SEND_MAIL_BACKEND_TOOL_SPEC_0_0_1,"runtime-sensitive-echo":RUNTIME_SENSITIVE_ECHO_BACKEND_TOOL_SPEC_0_0_1,"update-plan-step":UPDATE_PLAN_STEP_BACKEND_TOOL_SPEC_0_0_1},DECKS_FRONTEND_TOOL_SPEC_0_0_1={id:"decks",version:"0.0.1",name:"Decks",description:"Read, write and drive presentations kept as data — a deck, its slides, and the one on screen.",tags:["frontend","decks","presentations"],enabled:!0,toolset:["decks_list_decks","decks_get_deck","decks_create_deck","decks_update_deck","decks_update_slide","decks_insert_slide","decks_delete_slide","decks_list_slides","decks_get_slide","decks_add_slide","decks_delete_deck","decks_list","decks_open","decks_go_to_slide","decks_next_slide","decks_previous_slide","decks_present","decks_print"],icon:"@primer/octicons-react:project",emoji:"🃏"},JUPYTER_NOTEBOOK_EDIT_FRONTEND_TOOL_SPEC_0_0_1={id:"jupyter-notebook-edit",version:"0.0.1",name:"Jupyter Notebook (edit)",description:"Read and edit a notebook, and run cells — but never delete from it.",tags:["frontend","notebook","edit"],enabled:!0,toolset:["readCell","readAllCells","insertCell","updateCell","runCell","executeCode"],icon:"@datalayer/icons-react:jupyter",emoji:"📓"},JUPYTER_NOTEBOOK_PROPOSE_FRONTEND_TOOL_SPEC_0_0_1={id:"jupyter-notebook-propose",version:"0.0.1",name:"Jupyter Notebook (propose)",description:"Read a notebook and propose changes for a person to accept, never applying them.",tags:["frontend","notebook","propose"],enabled:!0,toolset:["readCell","readAllCells","proposeCellUpdate","runCell"],icon:"@datalayer/icons-react:jupyter",emoji:"📓"},JUPYTER_NOTEBOOK_READ_FRONTEND_TOOL_SPEC_0_0_1={id:"jupyter-notebook-read",version:"0.0.1",name:"Jupyter Notebook (read only)",description:"Read a notebook without changing it — cells, outputs and errors.",tags:["frontend","notebook","read"],enabled:!0,toolset:["readCell","readAllCells"],icon:"@datalayer/icons-react:jupyter",emoji:"📓"},JUPYTER_NOTEBOOK_FRONTEND_TOOL_SPEC_0_0_1={id:"jupyter-notebook",version:"0.0.1",name:"Jupyter Notebook",description:"Frontend tools for interacting with Jupyter notebooks.",tags:["frontend","notebook","jupyter-server"],enabled:!0,toolset:"all",icon:"@datalayer/icons-react:jupyter",emoji:"📓"},LEXICAL_DOCUMENT_FRONTEND_TOOL_SPEC_0_0_1={id:"lexical-document",version:"0.0.1",name:"Lexical Document",description:"Frontend tools for interacting with Lexical documents: reading and writing blocks, running Jupyter cells in the page, and drawing diagrams into the document with Excalidraw.",tags:["frontend","document","lexical","drawing","diagram"],enabled:!0,toolset:"all",icon:"@primer/octicons-react:file",emoji:"📄"},FRONTEND_TOOL_CATALOG={decks:DECKS_FRONTEND_TOOL_SPEC_0_0_1,"jupyter-notebook-edit":JUPYTER_NOTEBOOK_EDIT_FRONTEND_TOOL_SPEC_0_0_1,"jupyter-notebook-propose":JUPYTER_NOTEBOOK_PROPOSE_FRONTEND_TOOL_SPEC_0_0_1,"jupyter-notebook-read":JUPYTER_NOTEBOOK_READ_FRONTEND_TOOL_SPEC_0_0_1,"jupyter-notebook":JUPYTER_NOTEBOOK_FRONTEND_TOOL_SPEC_0_0_1,"lexical-document":LEXICAL_DOCUMENT_FRONTEND_TOOL_SPEC_0_0_1},MCP_SERVER_MAP$1={"alphavantage:0.0.1":ALPHAVANTAGE_MCP_SERVER_0_0_1,"chart:0.0.1":CHART_MCP_SERVER_0_0_1,"earthdata:0.0.1":EARTHDATA_MCP_SERVER_0_0_1,"eurus:0.0.1":EURUS_MCP_SERVER_0_0_1,"filesystem:0.0.1":FILESYSTEM_MCP_SERVER_0_0_1,"github:0.0.1":GITHUB_MCP_SERVER_0_0_1,"google-workspace:0.0.1":GOOGLE_WORKSPACE_MCP_SERVER_0_0_1,"huggingface:0.0.1":HUGGINGFACE_MCP_SERVER_0_0_1,"kaggle:0.0.1":KAGGLE_MCP_SERVER_0_0_1,"odoo:0.0.1":ODOO_MCP_SERVER_0_0_1,"salesforce:0.0.1":SALESFORCE_MCP_SERVER_0_0_1,"slack:0.0.1":SLACK_MCP_SERVER_0_0_1,"tavily:0.0.1":TAVILY_MCP_SERVER_0_0_1},SKILL_MAP$1={"accounting:0.0.1":ACCOUNTING_SKILL_SPEC_0_0_1,"crawl:0.0.1":CRAWL_SKILL_SPEC_0_0_1,"events:0.0.1":EVENTS_SKILL_SPEC_0_0_1,"github:0.0.1":GITHUB_SKILL_SPEC_0_0_1,"jokes:0.0.1":JOKES_SKILL_SPEC_0_0_1,"pdf:0.0.1":PDF_SKILL_SPEC_0_0_1,"text-summarizer:0.0.1":TEXT_SUMMARIZER_SKILL_SPEC_0_0_1};function toAgentSkillSpec$1(Au){return{id:Au.id,name:Au.name,description:Au.description,version:Au.version??"0.0.1",tags:Au.tags,enabled:Au.enabled,requiredEnvVars:Au.requiredEnvVars}}const TOOL_MAP$1={"decide:0.0.1":DECIDE_BACKEND_TOOL_SPEC_0_0_1,"example-create-plan:0.0.1":EXAMPLE_CREATE_PLAN_BACKEND_TOOL_SPEC_0_0_1,"example-current-time:0.0.1":EXAMPLE_CURRENT_TIME_BACKEND_TOOL_SPEC_0_0_1,"example-display-recipe:0.0.1":EXAMPLE_DISPLAY_RECIPE_BACKEND_TOOL_SPEC_0_0_1,"example-generate-haiku:0.0.1":EXAMPLE_GENERATE_HAIKU_BACKEND_TOOL_SPEC_0_0_1,"example-generate-task-steps:0.0.1":EXAMPLE_GENERATE_TASK_STEPS_BACKEND_TOOL_SPEC_0_0_1,"example-get-weather:0.0.1":EXAMPLE_GET_WEATHER_BACKEND_TOOL_SPEC_0_0_1,"example-render-a2ui-surface:0.0.1":EXAMPLE_RENDER_A2UI_SURFACE_BACKEND_TOOL_SPEC_0_0_1,"example-update-plan-step:0.0.1":EXAMPLE_UPDATE_PLAN_STEP_BACKEND_TOOL_SPEC_0_0_1,"runtime-echo:0.0.1":RUNTIME_ECHO_BACKEND_TOOL_SPEC_0_0_1,"runtime-send-mail:0.0.1":RUNTIME_SEND_MAIL_BACKEND_TOOL_SPEC_0_0_1,"runtime-sensitive-echo:0.0.1":RUNTIME_SENSITIVE_ECHO_BACKEND_TOOL_SPEC_0_0_1},FRONTEND_TOOL_MAP$1={"decks:0.0.1":DECKS_FRONTEND_TOOL_SPEC_0_0_1,"jupyter-notebook-edit:0.0.1":JUPYTER_NOTEBOOK_EDIT_FRONTEND_TOOL_SPEC_0_0_1,"jupyter-notebook-propose:0.0.1":JUPYTER_NOTEBOOK_PROPOSE_FRONTEND_TOOL_SPEC_0_0_1,"jupyter-notebook-read:0.0.1":JUPYTER_NOTEBOOK_READ_FRONTEND_TOOL_SPEC_0_0_1,"jupyter-notebook:0.0.1":JUPYTER_NOTEBOOK_FRONTEND_TOOL_SPEC_0_0_1,"lexical-document:0.0.1":LEXICAL_DOCUMENT_FRONTEND_TOOL_SPEC_0_0_1},EXAMPLE_A2A_RESEARCHER_AGENTSPEC_0_0_1={id:"example-a2a-researcher",version:"0.0.1",name:"Example A2A Researcher",description:"A research specialist served over the A2A protocol. Given a topic, gathers the key facts and returns concise, source-aware notes.",tags:["research","a2a"],domain:void 0,enabled:!1,model:"bedrock:us.anthropic.claude-sonnet-4-6",mcpServers:[],skills:[].filter(Boolean),backendTools:[],frontendTools:[],environmentName:"ai-agents-env",icon:"search",emoji:"🔎",color:"#0EA5E9",suggestions:[{text:"Gather the key facts on a topic, with sources",summary:"Key facts with sources"}],welcomeMessage:"A2A researcher ready.",welcomeNotebook:void 0,welcomeDocument:void 0,sandboxVariant:void 0,harness:"pydantic-ai",systemPrompt:"You are a meticulous research specialist, reached by other agents over the A2A protocol. Given a topic, gather the key facts and return concise, source-aware notes. Prefer verifiable claims and flag anything uncertain. Answer with the notes themselves: no preamble, no questions back. You have no tools and no web access: work from what you know, and say when something should be checked.",systemPromptCodemodeAddons:void 0,goal:void 0,delegable:[],protocol:"a2a",ui:[],protocols:[],trigger:void 0,modelConfig:void 0,mcpServerTools:void 0,guardrails:void 0,evals:void 0,codemode:void 0,output:void 0,advanced:void 0,checkpoints:void 0,authorizationPolicy:void 0,notifications:void 0,memory:"ephemeral",preHooks:void 0,postHooks:void 0,toolHooks:void 0,parameters:void 0,subagents:void 0},EXAMPLE_A2A_WRITER_AGENTSPEC_0_0_1={id:"example-a2a-writer",version:"0.0.1",name:"Example A2A Writer",description:"A writing specialist served over the A2A protocol. Given notes or instructions, produces clear, well-structured prose.",tags:["writing","a2a"],domain:void 0,enabled:!1,model:"bedrock:us.anthropic.claude-sonnet-4-6",mcpServers:[],skills:[].filter(Boolean),backendTools:[],frontendTools:[],environmentName:"ai-agents-env",icon:"pencil",emoji:"✍️",color:"#F59E0B",suggestions:[{text:"Turn a set of notes into a short, structured write-up",summary:"Notes into a write-up"}],welcomeMessage:"A2A writer ready.",welcomeNotebook:void 0,welcomeDocument:void 0,sandboxVariant:void 0,harness:"pydantic-ai",systemPrompt:"You are a concise writing specialist, reached by other agents over the A2A protocol. Given notes or findings, produce clear, well-structured prose. Keep it focused and free of filler. Answer with the text itself: no preamble, no questions back. You have no tools: work from the notes and instructions you are given.",systemPromptCodemodeAddons:void 0,goal:void 0,delegable:[],protocol:"a2a",ui:[],protocols:[],trigger:void 0,modelConfig:void 0,mcpServerTools:void 0,guardrails:void 0,evals:void 0,codemode:void 0,output:void 0,advanced:void 0,checkpoints:void 0,authorizationPolicy:void 0,notifications:void 0,memory:"ephemeral",preHooks:void 0,postHooks:void 0,toolHooks:void 0,parameters:void 0,subagents:void 0},EXAMPLE_A2A_AGENTSPEC_0_0_1={id:"example-a2a",version:"0.0.1",name:"Example A2A Agent",description:"Demonstrates delegation to separate agents over the A2A protocol. The orchestrator hands research and writing to a researcher and a writer that run as agents of their own — launched beside it on the local server, or on Datalayer runtimes when it runs in the cloud — and talks to them over A2A.",tags:["research","workflow","a2a"],domain:void 0,enabled:!1,model:"bedrock:us.anthropic.claude-sonnet-4-6",mcpServers:[],skills:[].filter(Boolean),backendTools:[],frontendTools:[],environmentName:"ai-agents-env",icon:"broadcast",emoji:"📡",color:"#7C3AED",suggestions:[{text:"Research three key facts about the A2A protocol through the researcher, then have the writer turn them into one short paragraph.",summary:"Research then write over A2A"},{text:"Have the researcher gather five source-backed notes on Jupyter kernels and report them to me as they are.",summary:"Research via the A2A researcher"},{text:"Have the writer draft a short guide to naming variables from these points: be specific, prefer words to abbreviations, keep units in the name.",summary:"Draft via the A2A writer"}],welcomeMessage:"A2A example agent ready. Ask me to delegate research and writing to the agents I reach over A2A.",welcomeNotebook:void 0,welcomeDocument:void 0,sandboxVariant:"jupyter-server",harness:"pydantic-ai",systemPrompt:'You are the A2A Orchestrator. You do not research or write yourself: you split a request into specialist tasks and hand each to a separate agent reached over the A2A protocol, then synthesize their answers into one coherent reply.\nYour agents are `researcher` — facts, background, source-backed notes — and `writer` — clear, structured prose from notes or instructions. Reach them with `delegate_task`, naming the agent; a request to "research and write" is two delegations, the researcher\'s notes handed to the writer. Give each a task it can carry out without the rest of this conversation. The first delegation to an agent may take a moment while it is launched.\nAnswer in the conversation, and only with the tools you actually have; never call a tool you were not given.',systemPromptCodemodeAddons:void 0,goal:void 0,delegable:[],protocol:void 0,ui:[],protocols:[],trigger:void 0,modelConfig:void 0,mcpServerTools:void 0,guardrails:void 0,evals:void 0,codemode:void 0,output:void 0,advanced:void 0,checkpoints:void 0,authorizationPolicy:void 0,notifications:void 0,memory:"ephemeral",preHooks:void 0,postHooks:void 0,toolHooks:void 0,parameters:void 0,subagents:{includeGeneralPurpose:!1,subagents:[{name:"researcher",description:"A separate research agent, reached over A2A. Gathers facts and source-backed notes on a topic; use for research, fact-finding and background gathering.",ref:"example-a2a-researcher:0.0.1",a2a:{launch:"auto"}},{name:"writer",description:"A separate writing agent, reached over A2A. Turns notes into clear, well-structured prose; use for summaries, drafts and final write-ups.",ref:"example-a2a-writer:0.0.1",a2a:{launch:"auto"}}]}},EXAMPLE_A2UI_AGENT_SPEC_0_0_1={id:"example-a2ui-agent",version:"0.0.1",name:"A2UI Agent",description:"An AG-UI agent that generates interactive A2UI surfaces on demand. Describe a form, intake, configurator, survey or booking flow and the agent renders a validated, themeable A2UI surface you can fill in.",tags:["workflow","automation","analysis"],domain:void 0,enabled:!1,model:"bedrock:us.anthropic.claude-sonnet-4-6",mcpServers:[],skills:[].filter(Boolean),backendTools:[TOOL_MAP$1["example-render-a2ui-surface:0.0.1"]],frontendTools:[],frontendRenderTools:[{tool:"render_a2ui_surface",renderer:"a2ui-surface"}],environmentName:"ai-agents-env",icon:"browser",emoji:"🎛️",color:"#6366F1",suggestions:[{text:"Build a support ticket intake form with category, priority and a description.",summary:"Support ticket form"},{text:"Create a trip booking form with destination, dates, travelers and budget.",summary:"Trip booking form"},{text:"Generate a customer feedback survey with a rating slider and comments.",summary:"Feedback survey"},{text:"Make a product configurator for a laptop with CPU, RAM and add-ons.",summary:"Laptop configurator"}],welcomeMessage:`Hi! I turn requests into interactive A2UI surfaces. Ask me to build a form, survey, configurator or booking flow and I'll render it live for you.
2200
2200
  `,welcomeNotebook:void 0,welcomeDocument:void 0,sandboxVariant:void 0,harness:"pydantic-ai",systemPrompt:"You are an A2UI generative-UI agent. You render real, interactive user\ninterfaces (forms, intakes, configurators, surveys, bookings, checklists)\nfrom the user's request.\n\nHow to respond:\n1. ALWAYS call the `render_a2ui_surface` tool to produce the UI. Never\n describe the form in prose instead of rendering it.\n2. Choose a concise `title` and a one-sentence `intro`.\n3. Design a sensible ordered list of `fields`. Pick the best `type` for each:\n - `text` / `email` for short input, `longtext` for descriptions/notes\n - `choice` (single) or `multichoice` (many) with `options` for pick-lists\n - `checkbox` for yes/no, `slider` (with `min`/`max`) for ranges/ratings\n - `date` / `datetime` for scheduling\n4. When the request implies triage or categorization (e.g. support tickets),\n add `summary_items` such as detected Category or Priority.\n5. Keep forms focused: usually 4-8 fields.\n6. After the tool call, reply with ONE short sentence confirming what you\n built. Do NOT repeat every field in text — the surface is shown directly.\n",systemPromptCodemodeAddons:void 0,goal:void 0,delegable:[],protocol:"ag-ui",ui:[],protocols:[],trigger:void 0,modelConfig:void 0,mcpServerTools:void 0,guardrails:void 0,evals:void 0,codemode:void 0,output:void 0,advanced:void 0,checkpoints:void 0,authorizationPolicy:void 0,notifications:void 0,memory:"ephemeral",preHooks:void 0,postHooks:void 0,toolHooks:void 0,parameters:void 0,subagents:void 0},EXAMPLE_A2UI_JUPYTER_OUTPUT_AGENTSPEC_0_0_1={id:"example-a2ui-jupyter-output",version:"0.0.1",name:"A2UI Jupyter Output Agent",description:"Drives the A2UI Jupyter Output example by selecting a kernel-output demonstration and asking the frontend to execute it in the connected sandbox.",tags:["a2ui","jupyter","output"],domain:void 0,enabled:!1,model:"bedrock:us.anthropic.claude-sonnet-4-6",mcpServers:[],skills:[].filter(Boolean),backendTools:[],frontendTools:[],environmentName:"ai-agents-env",icon:"notebook",emoji:"📓",color:"#0969DA",suggestions:[{text:"Run something in the code sandbox that prints as it goes.",summary:"Streaming output",emoji:"📜"},{text:"Plot a chart in the code sandbox and show me the image.",summary:"Plot a chart",emoji:"📈"},{text:"Build a small DataFrame in the code sandbox and show it as a table.",summary:"DataFrame as a table",emoji:"🧮"},{text:"Run something in the code sandbox that fails, so I can see the traceback.",summary:"Show a traceback",emoji:"🐛"},{text:"Show me an interactive slider from the code sandbox.",summary:"Interactive slider",emoji:"🎛️"},{text:"Give me a surface with buttons I can press.",summary:"Buttons to press",emoji:"🖲️"}],welcomeMessage:"Choose a suggestion to execute a Jupyter output demonstration and compare the kernel output with its A2UI surface.",welcomeNotebook:void 0,welcomeDocument:void 0,sandboxVariant:"jupyter-server",harness:"pydantic-ai",systemPrompt:"You operate the A2UI Jupyter Output example. It exists to show one code\nsandbox execution twice over: what the kernel itself returned, and the A2UI\nsurface the server converter made of the same outputs.\n\nShowing that comparison is done with one tool and nothing else:\n`run_jupyter_output_demo`, whose `kind` is one of `stream`, `figure`,\n`table`, `error`, `ipywidgets`, or `interactive`.\n\nSo: whenever somebody asks you to run something in the code sandbox, or to\nshow what some kind of output looks like, call `run_jupyter_output_demo`\nexactly once with the kind that matches what they asked for. They will ask\nin ordinary words rather than by naming the tool or the kind, and reading\nthe request is your job:\n\n- printing, stdout, output arriving as it goes, a returned value -> `stream`\n- a plot, a chart, a figure, an image -> `figure`\n- a DataFrame, a table, tabular data -> `table`\n- a failure, an exception, a traceback, something that breaks -> `error`\n- a slider, a widget, an interactive control -> `ipywidgets`\n- a surface with buttons, something to press or click -> `interactive`\n\nNever write or execute Python of your own instead. The six demonstrations\nare fixed on purpose: the two panels are only worth comparing when both are\nshowing the same execution, and substituted code breaks the comparison the\nexample exists to make.\n\nAfter the tool returns, say in a sentence what was run and that it is now\nvisible in both the A2UI Surface and the Jupyter Output panels, with a word\non what differs between them where it is interesting. An `error`\ndemonstration is deliberate and has succeeded when its traceback is on\nscreen — do not apologise for it or offer to fix the code.\n",systemPromptCodemodeAddons:void 0,goal:void 0,delegable:[],protocol:"vercel-ai",ui:[],protocols:[],trigger:void 0,modelConfig:void 0,mcpServerTools:void 0,guardrails:void 0,evals:void 0,codemode:void 0,output:void 0,advanced:void 0,checkpoints:void 0,authorizationPolicy:void 0,notifications:void 0,memory:"ephemeral",preHooks:void 0,postHooks:void 0,toolHooks:void 0,parameters:void 0,subagents:void 0},EXAMPLE_A2UI_VIEWER_AGENTSPEC_0_0_1={id:"example-a2ui-viewer",version:"0.0.1",name:"A2UI Viewer Agent",description:"Answers beside the A2UI Viewer, whose scenes — a recipe card, a booking form, a sales snapshot and a shipping status — it renders on request as live A2UI surfaces, and runs code in the sandbox to show its outputs.",tags:["a2ui","viewer","loop"],domain:void 0,enabled:!1,model:"bedrock:us.anthropic.claude-sonnet-4-6",mcpServers:[],skills:[].filter(Boolean),backendTools:[TOOL_MAP$1["example-render-a2ui-surface:0.0.1"]],frontendTools:[],frontendRenderTools:[{tool:"render_a2ui_surface",renderer:"a2ui-surface"}],environmentName:"ai-agents-env",icon:"browser",emoji:"🔍",color:"#6366F1",suggestions:[{text:"Show a recipe card for a Mediterranean quinoa bowl, with a photo, its rating and review count, prep and cook time, and how many it serves.",summary:"Recipe Card",emoji:"🍲"},{text:"Build a table booking form with party size, date and time, dietary requirements and a Submit Reservation button.",summary:"Booking Form",emoji:"📅"},{text:"Show a Q2 sales snapshot by category — Apparel, Electronics, Home Goods and Health & Beauty — as KPI tiles under one headline.",summary:"Sales Snapshot",emoji:"📈"},{text:"Show a package status card with the tracking number, the steps from placed to shipped to out for delivery, and the ETA.",summary:"Shipping Status",emoji:"📦"},{text:"Plot a chart in the code sandbox and show me the image.",summary:"Plot a chart",emoji:"📈"},{text:"Build a small DataFrame in the code sandbox and show it as a table.",summary:"DataFrame as a table",emoji:"🧮"},{text:"Run something in the code sandbox that fails, so I can see the traceback.",summary:"Show a traceback",emoji:"🐛"},{text:"Show me an interactive slider from the code sandbox.",summary:"Interactive slider",emoji:"🎛️"}],welcomeMessage:"This is the A2UI Viewer. Pick a scene above to see a surface drawn from A2UI messages, ask me to render one of them here, or run something in the code sandbox and see its output.",welcomeNotebook:void 0,welcomeDocument:void 0,sandboxVariant:"browser",harness:"vercel-ai",systemPrompt:"You answer beside the A2UI Viewer, an example that renders A2UI surfaces\nfrom pasted protocol messages: a recipe card, a table booking form, a sales\nsnapshot of KPI tiles, and a shipping status timeline.\n\nWhen asked for a surface — one of those, or anything like them:\n1. ALWAYS call the `render_a2ui_surface` tool to produce it. Never describe\n the surface in prose instead of rendering it.\n2. Choose a concise `title` and a one-sentence `intro`.\n3. Design a sensible ordered list of `fields`, picking the best `type` for\n each: `text` / `email` for short input, `longtext` for notes, `choice`\n or `multichoice` with `options` for pick-lists, `checkbox` for yes/no,\n `slider` with `min`/`max` for ranges and ratings, `date` / `datetime`\n for scheduling. A card that shows values rather than asking for them\n still renders as a surface: put each value in a field with its label.\n4. After the tool call, reply with ONE short sentence saying what you\n rendered. Do not repeat the fields in text — the surface is shown.\n\nWhen asked to run code, use `execute_code` in the sandbox and let the\noutputs speak: a figure, a table, a traceback, a widget. Do not look for\nhelpers or skills in the sandbox; write the Python yourself.\n",systemPromptCodemodeAddons:void 0,goal:void 0,delegable:[],protocol:"vercel-ai",ui:[],protocols:[],trigger:void 0,modelConfig:void 0,mcpServerTools:void 0,guardrails:void 0,evals:void 0,codemode:void 0,output:void 0,advanced:void 0,checkpoints:void 0,authorizationPolicy:void 0,notifications:void 0,memory:"ephemeral",preHooks:void 0,postHooks:void 0,toolHooks:void 0,parameters:void 0,subagents:void 0},EXAMPLE_AGENT_CRITIC_LOOP_FOR_ANALYSIS_AGENTSPEC_0_0_1={id:"example-agent-critic-loop-for-analysis",version:"0.0.1",name:"Agent Critic Loop for Analysis",description:"Use a planner, executor, and critic agent loop to iteratively improve analysis quality and reduce logical errors in outputs.",tags:["analysis","data-quality","analytics"],domain:void 0,enabled:!1,model:"bedrock:us.anthropic.claude-sonnet-4-6",mcpServers:[],skills:[SKILL_MAP$1["events:0.0.1"]?toAgentSkillSpec$1(SKILL_MAP$1["events:0.0.1"]):void 0].filter(Boolean),backendTools:[TOOL_MAP$1["runtime-echo:0.0.1"]],frontendTools:[FRONTEND_TOOL_MAP$1["jupyter-notebook:0.0.1"],FRONTEND_TOOL_MAP$1["lexical-document:0.0.1"]],environmentName:"ai-agents-env",icon:"sync",emoji:"📊",color:"#1F883D",suggestions:[{text:"Use /home/datalayer/datasets/datalayer-nfs/finance/transactions_q1.csv and run a critic loop: first produce a reconciliation analysis, then critique it for gaps and publish a corrected final report.",summary:"Critic loop on transactions"}],welcomeMessage:"Hi! I can help with agent critic loop for analysis. Share data, files, or context and I will run the workflow end-to-end, explain what matters, and suggest practical next steps.",welcomeNotebook:void 0,welcomeDocument:void 0,sandboxVariant:"jupyter-server",harness:"pydantic-ai",systemPrompt:"You are a specialized assistant for this gallery workflow: Agent Critic Loop for Analysis. Objective: Use a planner, executor, and critic agent loop to iteratively improve analysis quality and reduce logical errors in outputs. Use the runtime tools and notebook execution environment when needed. Keep outputs concise, structured, and decision-oriented. Provide clear reasoning and recommended next actions.",systemPromptCodemodeAddons:"Compose focused execution steps, validate intermediate results, and summarize outcomes after each run. Prefer efficient, reproducible code paths.",goal:void 0,delegable:[],protocol:void 0,ui:[],protocols:[],trigger:void 0,modelConfig:void 0,mcpServerTools:void 0,guardrails:void 0,evals:void 0,codemode:{enabled:!0,token_reduction:"~80%",speedup:"~1.5x"},output:void 0,advanced:void 0,checkpoints:void 0,authorizationPolicy:void 0,notifications:void 0,memory:"ephemeral",preHooks:void 0,postHooks:void 0,toolHooks:void 0,parameters:void 0,subagents:void 0},EXAMPLE_AGENTIC_CHAT_AGENTSPEC_0_0_1={id:"example-agentic-chat",version:"0.0.1",name:"Agentic Chat",description:"A basic conversational AG-UI agent that can chat and use a tool to get the current time in any timezone.",tags:["workflow","automation","analysis"],domain:void 0,enabled:!1,model:"bedrock:us.anthropic.claude-sonnet-4-6",mcpServers:[],skills:[].filter(Boolean),backendTools:[TOOL_MAP$1["example-current-time:0.0.1"]],frontendTools:[],environmentName:"ai-agents-env",icon:"clock",emoji:"🕒",color:"#6366F1",suggestions:[{text:"What is the current time?",summary:"Current time"},{text:"What's the current date?",summary:"Current date"}],welcomeMessage:`Hi! Ask me for the current time in any timezone.
@@ -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)}