@datalayer/agent-runtimes 1.5.46 → 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.
|
@@ -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.
|
|
@@ -151,6 +151,12 @@ export type ConversationState = {
|
|
|
151
151
|
export declare const emptyConversation: (limits?: ConversationLimits) => ConversationState;
|
|
152
152
|
/** The question an application asks, as `RUN_FINISHED`'s `result.asking` or a session says it. */
|
|
153
153
|
export declare function questionOf(raw: unknown): ConversationQuestion | null;
|
|
154
|
+
/**
|
|
155
|
+
* A coding agent's row said again while it runs (the runtime's AG-UI
|
|
156
|
+
* stream, `agent_runtimes.transports.agui_stream`): a terminal's output so
|
|
157
|
+
* far rides it in `_meta["reactor.ui/display"]` (SHIELD SH-13, SH-16).
|
|
158
|
+
*/
|
|
159
|
+
export declare const HARNESS_TOOL_CALL = "datalayer.harness.tool_call";
|
|
154
160
|
/** The person's prompt, added before it is sent: its own row. */
|
|
155
161
|
export declare function withPrompt(state: ConversationState, id: string, words: string): ConversationState;
|
|
156
162
|
/**
|
|
@@ -36,7 +36,7 @@
|
|
|
36
36
|
* @module portable/conversation
|
|
37
37
|
*/
|
|
38
38
|
import { REACTOR_UI_NAME, toolResultOf, UI_ON_RUN, } from './agui';
|
|
39
|
-
import { displayOfToolResult } from './displays';
|
|
39
|
+
import { DISPLAY_META_KEY, displayOfToolResult, protocolDisplayOf, } from './displays';
|
|
40
40
|
import { RUN_END_WORDS } from './records';
|
|
41
41
|
import { messagesOfThread } from './thread';
|
|
42
42
|
/** How many rows a conversation on a phone keeps: its newest. */
|
|
@@ -159,6 +159,31 @@ function noted(state, event) {
|
|
|
159
159
|
diagnostics: [...state.diagnostics, entry].slice(-state.limits.diagnostics),
|
|
160
160
|
};
|
|
161
161
|
}
|
|
162
|
+
/**
|
|
163
|
+
* A coding agent's row said again while it runs (the runtime's AG-UI
|
|
164
|
+
* stream, `agent_runtimes.transports.agui_stream`): a terminal's output so
|
|
165
|
+
* far rides it in `_meta["reactor.ui/display"]` (SHIELD SH-13, SH-16).
|
|
166
|
+
*/
|
|
167
|
+
export const HARNESS_TOOL_CALL = 'datalayer.harness.tool_call';
|
|
168
|
+
/** A running row given the display its update carries; `null` when it carries none. */
|
|
169
|
+
function withRunningDisplay(state, value) {
|
|
170
|
+
if (!isRecord(value) || !isRecord(value._meta)) {
|
|
171
|
+
return null;
|
|
172
|
+
}
|
|
173
|
+
const embedded = value._meta[DISPLAY_META_KEY];
|
|
174
|
+
if (embedded === undefined) {
|
|
175
|
+
return null;
|
|
176
|
+
}
|
|
177
|
+
const display = protocolDisplayOf(embedded);
|
|
178
|
+
if (!display) {
|
|
179
|
+
throw new Error(`${HARNESS_TOOL_CALL} of ${text(value.id)} carries a display no client reads.`);
|
|
180
|
+
}
|
|
181
|
+
return changed(state, text(value.id), item => item.kind === 'tool' && item.status === 'running'
|
|
182
|
+
? // Its value is the display alone, as a result would carry it, so the
|
|
183
|
+
// web resolves the same card; its words stay empty until it ends.
|
|
184
|
+
{ ...item, value: { _meta: value._meta }, display }
|
|
185
|
+
: item);
|
|
186
|
+
}
|
|
162
187
|
let rowCount = 0;
|
|
163
188
|
const rowId = (prefix) => `${prefix}-${Date.now().toString(36)}-${(rowCount += 1)}`;
|
|
164
189
|
/** A tool call just begun: running, nothing said of it yet. */
|
|
@@ -563,6 +588,9 @@ export function reduceConversation(state, event) {
|
|
|
563
588
|
asking: questionOf(session.asking) ?? state.asking,
|
|
564
589
|
};
|
|
565
590
|
}
|
|
591
|
+
if (event.name === HARNESS_TOOL_CALL) {
|
|
592
|
+
return withRunningDisplay(state, event.value) ?? noted(state, event);
|
|
593
|
+
}
|
|
566
594
|
return noted(state, event);
|
|
567
595
|
}
|
|
568
596
|
case 'ACTIVITY_SNAPSHOT':
|