@datalayer/agent-runtimes 1.5.32 → 1.5.34
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.
- package/dist-embed/chunks/{ChatView-C_NOLqwI.js → ChatView-kCmBbnDa.js} +3 -3
- package/dist-embed/datalayer-app-main.js +10 -7
- package/lib/apps/plugins/shield-displays/DiffCard.d.ts +17 -0
- package/lib/apps/plugins/shield-displays/DiffCard.js +34 -0
- package/lib/apps/plugins/shield-displays/TerminalCard.d.ts +16 -0
- package/lib/apps/plugins/shield-displays/TerminalCard.js +31 -0
- package/lib/apps/plugins/shield-displays/index.d.ts +9 -0
- package/lib/apps/plugins/shield-displays/index.js +63 -0
- package/lib/apps/presets.js +4 -0
- package/lib/portable/displays.d.ts +47 -0
- package/lib/portable/displays.js +170 -0
- package/lib/portable/fixtures.d.ts +9 -0
- package/lib/portable/fixtures.js +36 -0
- package/lib/portable/index.d.ts +2 -1
- package/lib/portable/index.js +4 -1
- package/lib/portable/views.d.ts +3 -1
- package/lib/specs/agents/agents.d.ts +1 -0
- package/lib/specs/agents/agents.js +49 -0
- package/package.json +1 -1
|
@@ -2191,7 +2191,10 @@ ${Ou}
|
|
|
2191
2191
|
`,{prompt:Ru,stopSequences:[`
|
|
2192
2192
|
${lo}:`]}}function getResponseMetadata2({id:Au,model:lo,created:$u}){return{id:Au??void 0,modelId:lo??void 0,timestamp:$u!=null?new Date($u*1e3):void 0}}function mapOpenAIFinishReason2(Au){switch(Au){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"other"}}var openaiCompletionResponseSchema=lazySchema(()=>zodSchema(object({id:string$2().nullish(),created:number$2().nullish(),model:string$2().nullish(),choices:array(object({text:string$2(),finish_reason:string$2(),logprobs:object({tokens:array(string$2()),token_logprobs:array(number$2()),top_logprobs:array(record$2(string$2(),number$2())).nullish()}).nullish()})),usage:object({prompt_tokens:number$2(),completion_tokens:number$2(),total_tokens:number$2()}).nullish()}))),openaiCompletionChunkSchema=lazySchema(()=>zodSchema(union([object({id:string$2().nullish(),created:number$2().nullish(),model:string$2().nullish(),choices:array(object({text:string$2(),finish_reason:string$2().nullish(),index:number$2(),logprobs:object({tokens:array(string$2()),token_logprobs:array(number$2()),top_logprobs:array(record$2(string$2(),number$2())).nullish()}).nullish()})),usage:object({prompt_tokens:number$2(),completion_tokens:number$2(),total_tokens:number$2()}).nullish()}),openaiErrorDataSchema]))),openaiLanguageModelCompletionOptions=lazySchema(()=>zodSchema(object({echo:boolean$1().optional(),logitBias:record$2(string$2(),number$2()).optional(),suffix:string$2().optional(),user:string$2().optional(),logprobs:union([boolean$1(),number$2()]).optional()}))),OpenAICompletionLanguageModel=class Uw{constructor(lo,$u){this.specificationVersion="v4",this.supportedUrls={},this.modelId=lo,this.config=$u}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}static[WORKFLOW_SERIALIZE](lo){return serializeModelOptions({modelId:lo.modelId,config:lo.config})}static[WORKFLOW_DESERIALIZE](lo){return new Uw(lo.modelId,lo.config)}get provider(){return this.config.provider}async getArgs({prompt:lo,maxOutputTokens:$u,temperature:Ru,topP:Iu,topK:Pu,frequencyPenalty:Ou,presencePenalty:Mu,stopSequences:Du,responseFormat:Lu,tools:Bu,toolChoice:ju,seed:Fu,providerOptions:zu}){const Uu=[],Hu={...await parseProviderOptions({provider:"openai",providerOptions:zu,schema:openaiLanguageModelCompletionOptions}),...await parseProviderOptions({provider:this.providerOptionsName,providerOptions:zu,schema:openaiLanguageModelCompletionOptions})};Pu!=null&&Uu.push({type:"unsupported",feature:"topK"}),Bu?.length&&Uu.push({type:"unsupported",feature:"tools"}),ju!=null&&Uu.push({type:"unsupported",feature:"toolChoice"}),Lu!=null&&Lu.type!=="text"&&Uu.push({type:"unsupported",feature:"responseFormat",details:"JSON response format is not supported."});const{prompt:Vu,stopSequences:Gu}=convertToOpenAICompletionPrompt({prompt:lo}),Wu=[...Gu??[],...Du??[]];return{args:{model:this.modelId,echo:Hu.echo,logit_bias:Hu.logitBias,logprobs:Hu?.logprobs===!0?0:Hu?.logprobs===!1?void 0:Hu?.logprobs,suffix:Hu.suffix,user:Hu.user,max_tokens:$u,temperature:Ru,top_p:Iu,frequency_penalty:Ou,presence_penalty:Mu,seed:Fu,prompt:Vu,stop:Wu.length>0?Wu:void 0},warnings:Uu}}async doGenerate(lo){var $u,Ru,Iu;const{args:Pu,warnings:Ou}=await this.getArgs(lo),{responseHeaders:Mu,value:Du,rawValue:Lu}=await postJsonToApi({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:combineHeaders((Ru=($u=this.config).headers)==null?void 0:Ru.call($u),lo.headers),body:Pu,failedResponseHandler:openaiFailedResponseHandler,successfulResponseHandler:createJsonResponseHandler(openaiCompletionResponseSchema),abortSignal:lo.abortSignal,fetch:this.config.fetch}),Bu=Du.choices[0],ju={openai:{}};return Bu.logprobs!=null&&(ju.openai.logprobs=Bu.logprobs),{content:[{type:"text",text:Bu.text}],usage:convertOpenAICompletionUsage(Du.usage),finishReason:{unified:mapOpenAIFinishReason2(Bu.finish_reason),raw:(Iu=Bu.finish_reason)!=null?Iu:void 0},request:{body:Pu},response:{...getResponseMetadata2(Du),headers:Mu,body:Lu},providerMetadata:ju,warnings:Ou}}async doStream(lo){var $u,Ru;const{args:Iu,warnings:Pu}=await this.getArgs(lo),Ou={...Iu,stream:!0,stream_options:{include_usage:!0}},Mu=this.config.url({path:"/completions",modelId:this.modelId}),{responseHeaders:Du,value:Lu}=await postJsonToApi({url:Mu,headers:combineHeaders((Ru=($u=this.config).headers)==null?void 0:Ru.call($u),lo.headers),body:Ou,failedResponseHandler:openaiFailedResponseHandler,successfulResponseHandler:createEventSourceResponseHandler(openaiCompletionChunkSchema),abortSignal:lo.abortSignal,fetch:this.config.fetch}),Bu=await throwIfOpenAIStreamErrorBeforeOutput({stream:Lu,getError:Vu=>"error"in Vu?Vu.error:void 0,isOutputChunk:isOpenAICompletionOutputChunk,url:Mu,requestBodyValues:Ou,responseHeaders:Du});let ju={unified:"other",raw:void 0};const Fu={openai:{}};let zu,Uu=!0;return{stream:Bu.pipeThrough(new TransformStream({start(Vu){Vu.enqueue({type:"stream-start",warnings:Pu})},transform(Vu,Gu){if(lo.includeRawChunks&&Gu.enqueue({type:"raw",rawValue:Vu.rawValue}),!Vu.success){ju={unified:"error",raw:void 0},Gu.enqueue({type:"error",error:Vu.error});return}const Wu=Vu.value;if("error"in Wu){ju={unified:"error",raw:void 0},Gu.enqueue({type:"error",error:Wu.error});return}Uu&&(Uu=!1,Gu.enqueue({type:"response-metadata",...getResponseMetadata2(Wu)}),Gu.enqueue({type:"text-start",id:"0"})),Wu.usage!=null&&(zu=Wu.usage);const Ku=Wu.choices[0];Ku?.finish_reason!=null&&(ju={unified:mapOpenAIFinishReason2(Ku.finish_reason),raw:Ku.finish_reason}),Ku?.logprobs!=null&&(Fu.openai.logprobs=Ku.logprobs),Ku?.text!=null&&Ku.text.length>0&&Gu.enqueue({type:"text-delta",id:"0",delta:Ku.text})},flush(Vu){Uu||Vu.enqueue({type:"text-end",id:"0"}),Vu.enqueue({type:"finish",finishReason:ju,providerMetadata:Fu,usage:convertOpenAICompletionUsage(zu)})}})),request:{body:Ou},response:{headers:Du}}}};function isOpenAICompletionOutputChunk(Au){return!("error"in Au)&&Au.choices.some(lo=>lo.text.length>0)}var openaiEmbeddingModelOptions=lazySchema(()=>zodSchema(object({dimensions:number$2().optional(),user:string$2().optional()}))),openaiTextEmbeddingResponseSchema=lazySchema(()=>zodSchema(object({data:array(object({embedding:array(number$2())})),usage:object({prompt_tokens:number$2()}).nullish()}))),OpenAIEmbeddingModel=class Hw{constructor(lo,$u){this.specificationVersion="v4",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=lo,this.config=$u}static[WORKFLOW_SERIALIZE](lo){return serializeModelOptions({modelId:lo.modelId,config:lo.config})}static[WORKFLOW_DESERIALIZE](lo){return new Hw(lo.modelId,lo.config)}get provider(){return this.config.provider}async doEmbed({values:lo,headers:$u,abortSignal:Ru,providerOptions:Iu}){var Pu,Ou,Mu;if(lo.length>this.maxEmbeddingsPerCall)throw new TooManyEmbeddingValuesForCallError({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:lo});const Du=(Pu=await parseProviderOptions({provider:"openai",providerOptions:Iu,schema:openaiEmbeddingModelOptions}))!=null?Pu:{},{responseHeaders:Lu,value:Bu,rawValue:ju}=await postJsonToApi({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:combineHeaders((Mu=(Ou=this.config).headers)==null?void 0:Mu.call(Ou),$u),body:{model:this.modelId,input:lo,encoding_format:"float",dimensions:Du.dimensions,user:Du.user},failedResponseHandler:openaiFailedResponseHandler,successfulResponseHandler:createJsonResponseHandler(openaiTextEmbeddingResponseSchema),abortSignal:Ru,fetch:this.config.fetch});return{warnings:[],embeddings:Bu.data.map(Fu=>Fu.embedding),usage:Bu.usage?{tokens:Bu.usage.prompt_tokens}:void 0,response:{headers:Lu,body:ju}}}},openaiFilesResponseSchema=lazySchema(()=>zodSchema(object({id:string$2(),object:string$2().nullish(),bytes:number$2().nullish(),created_at:number$2().nullish(),filename:string$2().nullish(),purpose:string$2().nullish(),status:string$2().nullish(),expires_at:number$2().nullish()}))),openaiFilesOptionsSchema=lazySchema(()=>zodSchema(object({purpose:string$2().optional(),expiresAfter:number$2().optional()}))),OpenAIFiles=class{constructor(Au){this.config=Au,this.specificationVersion="v4"}get provider(){return this.config.provider}async uploadFile({data:Au,mediaType:lo,filename:$u,providerOptions:Ru}){var Iu,Pu,Ou;const Mu=await parseProviderOptions({provider:"openai",providerOptions:Ru,schema:openaiFilesOptionsSchema}),Du=convertInlineFileDataToUint8Array(Au),Lu=new Blob([Du],{type:lo}),Bu=new FormData;$u!=null?Bu.append("file",Lu,$u):Bu.append("file",Lu),Bu.append("purpose",(Iu=Mu?.purpose)!=null?Iu:"assistants"),Mu?.expiresAfter!=null&&Bu.append("expires_after",String(Mu.expiresAfter));const{value:ju}=await postFormDataToApi({url:`${this.config.baseURL}/files`,headers:combineHeaders(this.config.headers()),formData:Bu,failedResponseHandler:openaiFailedResponseHandler,successfulResponseHandler:createJsonResponseHandler(openaiFilesResponseSchema),fetch:this.config.fetch});return{warnings:[],providerReference:{openai:ju.id},...((Pu=ju.filename)!=null?Pu:$u)?{filename:(Ou=ju.filename)!=null?Ou:$u}:{},...lo!=null?{mediaType:lo}:{},providerMetadata:{openai:{...ju.filename!=null?{filename:ju.filename}:{},...ju.purpose!=null?{purpose:ju.purpose}:{},...ju.bytes!=null?{bytes:ju.bytes}:{},...ju.created_at!=null?{createdAt:ju.created_at}:{},...ju.status!=null?{status:ju.status}:{},...ju.expires_at!=null?{expiresAt:ju.expires_at}:{}}}}}},openaiImageResponseSchema=lazySchema(()=>zodSchema(object({created:number$2().nullish(),data:array(object({b64_json:string$2(),revised_prompt:string$2().nullish()})),background:string$2().nullish(),output_format:string$2().nullish(),size:string$2().nullish(),quality:string$2().nullish(),usage:object({input_tokens:number$2().nullish(),output_tokens:number$2().nullish(),total_tokens:number$2().nullish(),input_tokens_details:object({image_tokens:number$2().nullish(),text_tokens:number$2().nullish()}).nullish()}).nullish()}))),modelMaxImagesPerCall={"dall-e-3":1,"dall-e-2":10,"gpt-image-1":10,"gpt-image-1-mini":10,"gpt-image-1.5":10,"gpt-image-2":10,"chatgpt-image-latest":10},defaultResponseFormatPrefixes=["chatgpt-image-","gpt-image-"];function hasDefaultResponseFormat(Au){return defaultResponseFormatPrefixes.some(lo=>Au.startsWith(lo))}function getMaxImagesPerCall(Au){var lo;return(lo=modelMaxImagesPerCall[Au])!=null?lo:Au.startsWith("gpt-image-")?10:1}var baseImageModelOptionsObject=object({quality:_enum(["standard","hd","low","medium","high","auto"]).optional(),background:_enum(["transparent","opaque","auto"]).optional(),outputFormat:_enum(["png","jpeg","webp"]).optional(),outputCompression:number$2().int().min(0).max(100).optional(),user:string$2().optional()}),openaiImageModelGenerationOptions=lazySchema(()=>zodSchema(baseImageModelOptionsObject.extend({style:_enum(["vivid","natural"]).optional(),moderation:_enum(["auto","low"]).optional()}))),openaiImageModelEditOptions=lazySchema(()=>zodSchema(baseImageModelOptionsObject.extend({inputFidelity:_enum(["high","low"]).optional()}))),OpenAIImageModel=class qw{constructor(lo,$u){this.modelId=lo,this.config=$u,this.specificationVersion="v4"}static[WORKFLOW_SERIALIZE](lo){return serializeModelOptions({modelId:lo.modelId,config:lo.config})}static[WORKFLOW_DESERIALIZE](lo){return new qw(lo.modelId,lo.config)}get maxImagesPerCall(){return getMaxImagesPerCall(this.modelId)}get provider(){return this.config.provider}async doGenerate({prompt:lo,files:$u,mask:Ru,n:Iu,size:Pu,aspectRatio:Ou,seed:Mu,providerOptions:Du,headers:Lu,abortSignal:Bu}){var ju,Fu,zu,Uu,Hu,Vu,Gu,Wu,Ku,Ju,Yu,Xu,ed,td,nd;const od=[];Ou!=null&&od.push({type:"unsupported",feature:"aspectRatio",details:"This model does not support aspect ratio. Use `size` instead."}),Mu!=null&&od.push({type:"unsupported",feature:"seed"});const sd=(zu=(Fu=(ju=this.config._internal)==null?void 0:ju.currentDate)==null?void 0:Fu.call(ju))!=null?zu:new Date;if($u!=null){const _d=(Uu=await parseProviderOptions({provider:"openai",providerOptions:Du,schema:openaiImageModelEditOptions}))!=null?Uu:{},{value:yd,responseHeaders:bd}=await postFormDataToApi({url:this.config.url({path:"/images/edits",modelId:this.modelId}),headers:combineHeaders((Vu=(Hu=this.config).headers)==null?void 0:Vu.call(Hu),Lu),formData:convertToFormData({model:this.modelId,prompt:lo,image:await Promise.all($u.map(Sd=>Sd.type==="file"?new Blob([Sd.data instanceof Uint8Array?new Blob([Sd.data],{type:Sd.mediaType}):new Blob([convertBase64ToUint8Array(Sd.data)],{type:Sd.mediaType})],{type:Sd.mediaType}):downloadBlob(Sd.url))),mask:Ru!=null?await fileToBlob(Ru):void 0,n:Iu,size:Pu,quality:_d.quality,background:_d.background,output_format:_d.outputFormat,output_compression:_d.outputCompression,input_fidelity:_d.inputFidelity,user:_d.user}),failedResponseHandler:openaiFailedResponseHandler,successfulResponseHandler:createJsonResponseHandler(openaiImageResponseSchema),abortSignal:Bu,fetch:this.config.fetch});return{images:yd.data.map(Sd=>Sd.b64_json),warnings:od,usage:yd.usage!=null?{inputTokens:(Gu=yd.usage.input_tokens)!=null?Gu:void 0,outputTokens:(Wu=yd.usage.output_tokens)!=null?Wu:void 0,totalTokens:(Ku=yd.usage.total_tokens)!=null?Ku:void 0}:void 0,response:{timestamp:sd,modelId:this.modelId,headers:bd},providerMetadata:{openai:{images:yd.data.map((Sd,Ed)=>{var cd,dd,md,ld,hd,vd;return{...Sd.revised_prompt?{revisedPrompt:Sd.revised_prompt}:{},created:(cd=yd.created)!=null?cd:void 0,size:(dd=yd.size)!=null?dd:void 0,quality:(md=yd.quality)!=null?md:void 0,background:(ld=yd.background)!=null?ld:void 0,outputFormat:(hd=yd.output_format)!=null?hd:void 0,...distributeTokenDetails((vd=yd.usage)==null?void 0:vd.input_tokens_details,Ed,yd.data.length)}})}}}}const ad=(Ju=await parseProviderOptions({provider:"openai",providerOptions:Du,schema:openaiImageModelGenerationOptions}))!=null?Ju:{},{value:pd,responseHeaders:gd}=await postJsonToApi({url:this.config.url({path:"/images/generations",modelId:this.modelId}),headers:combineHeaders((Xu=(Yu=this.config).headers)==null?void 0:Xu.call(Yu),Lu),body:{model:this.modelId,prompt:lo,n:Iu,size:Pu,quality:ad.quality,style:ad.style,background:ad.background,moderation:ad.moderation,output_format:ad.outputFormat,output_compression:ad.outputCompression,user:ad.user,...hasDefaultResponseFormat(this.modelId)?{}:{response_format:"b64_json"}},failedResponseHandler:openaiFailedResponseHandler,successfulResponseHandler:createJsonResponseHandler(openaiImageResponseSchema),abortSignal:Bu,fetch:this.config.fetch});return{images:pd.data.map(_d=>_d.b64_json),warnings:od,usage:pd.usage!=null?{inputTokens:(ed=pd.usage.input_tokens)!=null?ed:void 0,outputTokens:(td=pd.usage.output_tokens)!=null?td:void 0,totalTokens:(nd=pd.usage.total_tokens)!=null?nd:void 0}:void 0,response:{timestamp:sd,modelId:this.modelId,headers:gd},providerMetadata:{openai:{images:pd.data.map((_d,yd)=>{var bd,Sd,Ed,cd,dd,md;return{..._d.revised_prompt?{revisedPrompt:_d.revised_prompt}:{},created:(bd=pd.created)!=null?bd:void 0,size:(Sd=pd.size)!=null?Sd:void 0,quality:(Ed=pd.quality)!=null?Ed:void 0,background:(cd=pd.background)!=null?cd:void 0,outputFormat:(dd=pd.output_format)!=null?dd:void 0,...distributeTokenDetails((md=pd.usage)==null?void 0:md.input_tokens_details,yd,pd.data.length)}})}}}}};function distributeTokenDetails(Au,lo,$u){if(Au==null)return{};const Ru={};if(Au.image_tokens!=null){const Iu=Math.floor(Au.image_tokens/$u),Pu=Au.image_tokens-Iu*($u-1);Ru.imageTokens=lo===$u-1?Pu:Iu}if(Au.text_tokens!=null){const Iu=Math.floor(Au.text_tokens/$u),Pu=Au.text_tokens-Iu*($u-1);Ru.textTokens=lo===$u-1?Pu:Iu}return Ru}async function fileToBlob(Au){if(!Au)return;if(Au.type==="url")return downloadBlob(Au.url);const lo=Au.data instanceof Uint8Array?Au.data:convertBase64ToUint8Array(Au.data);return new Blob([lo],{type:Au.mediaType})}var applyPatchInputSchema=lazySchema(()=>zodSchema(object({callId:string$2(),operation:discriminatedUnion("type",[object({type:literal("create_file"),path:string$2(),diff:string$2()}),object({type:literal("delete_file"),path:string$2()}),object({type:literal("update_file"),path:string$2(),diff:string$2()})])}))),applyPatchOutputSchema=lazySchema(()=>zodSchema(object({status:_enum(["completed","failed"]),output:string$2().optional()}))),applyPatchToolFactory=createProviderDefinedToolFactoryWithOutputSchema({id:"openai.apply_patch",inputSchema:applyPatchInputSchema,outputSchema:applyPatchOutputSchema}),applyPatch=applyPatchToolFactory,codeInterpreterInputSchema=lazySchema(()=>zodSchema(object({code:string$2().nullish(),containerId:string$2()}))),codeInterpreterOutputSchema=lazySchema(()=>zodSchema(object({outputs:array(discriminatedUnion("type",[object({type:literal("logs"),logs:string$2()}),object({type:literal("image"),url:string$2()})])).nullish()}))),codeInterpreterArgsSchema=lazySchema(()=>zodSchema(object({container:union([string$2(),object({fileIds:array(string$2()).optional()})]).optional()}))),codeInterpreterToolFactory=createProviderExecutedToolFactory({id:"openai.code_interpreter",inputSchema:codeInterpreterInputSchema,outputSchema:codeInterpreterOutputSchema}),codeInterpreter=(Au={})=>codeInterpreterToolFactory(Au),safetyCheckSchema=object({id:string$2(),code:string$2().optional(),message:string$2().optional()}),computerActionSchema=discriminatedUnion("type",[object({type:literal("click"),button:_enum(["left","right","wheel","back","forward"]),x:number$2(),y:number$2(),keys:array(string$2()).optional()}),object({type:literal("double_click"),x:number$2(),y:number$2(),keys:array(string$2()).optional()}),object({type:literal("drag"),path:array(object({x:number$2(),y:number$2()})),keys:array(string$2()).optional()}),object({type:literal("keypress"),keys:array(string$2())}),object({type:literal("move"),x:number$2(),y:number$2(),keys:array(string$2()).optional()}),object({type:literal("screenshot")}),object({type:literal("scroll"),x:number$2(),y:number$2(),scrollX:number$2(),scrollY:number$2(),keys:array(string$2()).optional()}),object({type:literal("type"),text:string$2()}),object({type:literal("wait")})]),computerInputSchema=lazySchema(()=>zodSchema(object({actions:array(computerActionSchema),pendingSafetyChecks:array(safetyCheckSchema),status:_enum(["in_progress","completed","incomplete"])}))),computerOutputSchema=lazySchema(()=>zodSchema(object({output:union([object({type:literal("computer_screenshot"),imageUrl:string$2(),fileId:string$2().optional(),detail:_enum(["auto","low","high","original"]).optional()}),object({type:literal("computer_screenshot"),fileId:string$2(),imageUrl:string$2().optional(),detail:_enum(["auto","low","high","original"]).optional()})]),acknowledgedSafetyChecks:array(safetyCheckSchema).optional()}))),computerToolFactory=createProviderDefinedToolFactoryWithOutputSchema({id:"openai.computer",inputSchema:computerInputSchema,outputSchema:computerOutputSchema}),computer=(Au={})=>computerToolFactory(Au),customArgsSchema=lazySchema(()=>zodSchema(object({description:string$2().optional(),format:union([object({type:literal("grammar"),syntax:_enum(["regex","lark"]),definition:string$2()}),object({type:literal("text")})]).optional()}))),customInputSchema=lazySchema(()=>zodSchema(string$2())),customToolFactory=createProviderDefinedToolFactory({id:"openai.custom",inputSchema:customInputSchema}),customTool=Au=>customToolFactory(Au),comparisonFilterSchema=object({key:string$2(),type:_enum(["eq","ne","gt","gte","lt","lte","in","nin"]),value:union([string$2(),number$2(),boolean$1(),array(string$2())])}),compoundFilterSchema=object({type:_enum(["and","or"]),filters:array(union([comparisonFilterSchema,lazy(()=>compoundFilterSchema)]))}),fileSearchArgsSchema=lazySchema(()=>zodSchema(object({vectorStoreIds:array(string$2()),maxNumResults:number$2().optional(),ranking:object({ranker:string$2().optional(),scoreThreshold:number$2().optional()}).optional(),filters:union([comparisonFilterSchema,compoundFilterSchema]).optional()}))),fileSearchOutputSchema=lazySchema(()=>zodSchema(object({queries:array(string$2()),results:array(object({attributes:record$2(string$2(),unknown$1()),fileId:string$2(),filename:string$2(),score:number$2(),text:string$2()})).nullable()}))),fileSearch=createProviderExecutedToolFactory({id:"openai.file_search",inputSchema:object({}),outputSchema:fileSearchOutputSchema}),imageGenerationArgsSchema=lazySchema(()=>zodSchema(object({background:_enum(["auto","opaque","transparent"]).optional(),inputFidelity:_enum(["low","high"]).optional(),inputImageMask:object({fileId:string$2().optional(),imageUrl:string$2().optional()}).optional(),model:string$2().optional(),moderation:_enum(["auto"]).optional(),outputCompression:number$2().int().min(0).max(100).optional(),outputFormat:_enum(["png","jpeg","webp"]).optional(),partialImages:number$2().int().min(0).max(3).optional(),quality:_enum(["auto","low","medium","high"]).optional(),size:_enum(["1024x1024","1024x1536","1536x1024","auto"]).optional()}).strict())),imageGenerationInputSchema=lazySchema(()=>zodSchema(object({}))),imageGenerationOutputSchema=lazySchema(()=>zodSchema(object({result:string$2()}))),imageGenerationToolFactory=createProviderExecutedToolFactory({id:"openai.image_generation",inputSchema:imageGenerationInputSchema,outputSchema:imageGenerationOutputSchema}),imageGeneration=(Au={})=>imageGenerationToolFactory(Au),localShellInputSchema=lazySchema(()=>zodSchema(object({action:object({type:literal("exec"),command:array(string$2()),timeoutMs:number$2().optional(),user:string$2().optional(),workingDirectory:string$2().optional(),env:record$2(string$2(),string$2()).optional()})}))),localShellOutputSchema=lazySchema(()=>zodSchema(object({output:string$2()}))),localShell=createProviderDefinedToolFactoryWithOutputSchema({id:"openai.local_shell",inputSchema:localShellInputSchema,outputSchema:localShellOutputSchema}),shellInputSchema=lazySchema(()=>zodSchema(object({action:object({commands:array(string$2()),timeoutMs:number$2().optional(),maxOutputLength:number$2().optional()})}))),shellOutputSchema=lazySchema(()=>zodSchema(object({output:array(object({stdout:string$2(),stderr:string$2(),outcome:discriminatedUnion("type",[object({type:literal("timeout")}),object({type:literal("exit"),exitCode:number$2()})])}))}))),shellSkillsSchema=array(discriminatedUnion("type",[object({type:literal("skillReference"),providerReference:record$2(string$2(),string$2()),version:string$2().optional()}),object({type:literal("inline"),name:string$2(),description:string$2(),source:object({type:literal("base64"),mediaType:literal("application/zip"),data:string$2()})})])).optional(),shellArgsSchema=lazySchema(()=>zodSchema(object({environment:union([object({type:literal("containerAuto"),fileIds:array(string$2()).optional(),memoryLimit:_enum(["1g","4g","16g","64g"]).optional(),networkPolicy:discriminatedUnion("type",[object({type:literal("disabled")}),object({type:literal("allowlist"),allowedDomains:array(string$2()),domainSecrets:array(object({domain:string$2(),name:string$2(),value:string$2()})).optional()})]).optional(),skills:shellSkillsSchema}),object({type:literal("containerReference"),containerId:string$2()}),object({type:literal("local").optional(),skills:array(object({name:string$2(),description:string$2(),path:string$2()})).optional()})]).optional()}))),shell=createProviderDefinedToolFactoryWithOutputSchema({id:"openai.shell",inputSchema:shellInputSchema,outputSchema:shellOutputSchema}),toolSearchArgsSchema=lazySchema(()=>zodSchema(object({execution:_enum(["server","client"]).optional(),description:string$2().optional(),parameters:record$2(string$2(),unknown$1()).optional()}))),toolSearchInputSchema=lazySchema(()=>zodSchema(object({arguments:unknown$1().optional(),call_id:string$2().nullish()}))),toolSearchOutputSchema=lazySchema(()=>zodSchema(object({tools:array(record$2(string$2(),unknown$1()))}))),toolSearchToolFactory=createProviderDefinedToolFactoryWithOutputSchema({id:"openai.tool_search",inputSchema:toolSearchInputSchema,outputSchema:toolSearchOutputSchema}),toolSearch=(Au={})=>toolSearchToolFactory(Au),webSearchArgsSchema=lazySchema(()=>zodSchema(object({externalWebAccess:boolean$1().optional(),filters:object({allowedDomains:array(string$2()).optional()}).optional(),searchContextSize:_enum(["low","medium","high"]).optional(),userLocation:object({type:literal("approximate"),country:string$2().optional(),city:string$2().optional(),region:string$2().optional(),timezone:string$2().optional()}).optional()}))),webSearchInputSchema=lazySchema(()=>zodSchema(object({}))),webSearchOutputSchema=lazySchema(()=>zodSchema(object({action:discriminatedUnion("type",[object({type:literal("search"),query:string$2().optional(),queries:array(string$2()).optional()}),object({type:literal("openPage"),url:string$2().nullish()}),object({type:literal("findInPage"),url:string$2().nullish(),pattern:string$2().nullish()})]).optional(),sources:array(discriminatedUnion("type",[object({type:literal("url"),url:string$2()}),object({type:literal("api"),name:string$2()})])).optional()}))),webSearchToolFactory=createProviderExecutedToolFactory({id:"openai.web_search",inputSchema:webSearchInputSchema,outputSchema:webSearchOutputSchema}),webSearch=(Au={})=>webSearchToolFactory(Au),webSearchPreviewArgsSchema=lazySchema(()=>zodSchema(object({searchContextSize:_enum(["low","medium","high"]).optional(),userLocation:object({type:literal("approximate"),country:string$2().optional(),city:string$2().optional(),region:string$2().optional(),timezone:string$2().optional()}).optional()}))),webSearchPreviewInputSchema=lazySchema(()=>zodSchema(object({}))),webSearchPreviewOutputSchema=lazySchema(()=>zodSchema(object({action:discriminatedUnion("type",[object({type:literal("search"),query:string$2().optional()}),object({type:literal("openPage"),url:string$2().nullish()}),object({type:literal("findInPage"),url:string$2().nullish(),pattern:string$2().nullish()})]).optional()}))),webSearchPreview=createProviderExecutedToolFactory({id:"openai.web_search_preview",inputSchema:webSearchPreviewInputSchema,outputSchema:webSearchPreviewOutputSchema}),jsonValueSchema=lazy(()=>union([string$2(),number$2(),boolean$1(),_null(),array(jsonValueSchema),record$2(string$2(),jsonValueSchema)])),mcpArgsSchema=lazySchema(()=>zodSchema(object({serverLabel:string$2(),allowedTools:union([array(string$2()),object({readOnly:boolean$1().optional(),toolNames:array(string$2()).optional()})]).optional(),authorization:string$2().optional(),connectorId:string$2().optional(),headers:record$2(string$2(),string$2()).optional(),requireApproval:union([_enum(["always","never"]),object({never:object({toolNames:array(string$2()).optional()}).optional()})]).optional(),serverDescription:string$2().optional(),serverUrl:string$2().optional()}).refine(Au=>Au.serverUrl!=null||Au.connectorId!=null,"One of serverUrl or connectorId must be provided."))),mcpInputSchema=lazySchema(()=>zodSchema(object({}))),mcpOutputSchema=lazySchema(()=>zodSchema(object({type:literal("call"),serverLabel:string$2(),name:string$2(),arguments:string$2(),output:string$2().nullish(),error:union([string$2(),jsonValueSchema]).optional()}))),mcpToolFactory=createProviderExecutedToolFactory({id:"openai.mcp",inputSchema:mcpInputSchema,outputSchema:mcpOutputSchema}),mcp=Au=>mcpToolFactory(Au),programmaticToolCallingInputSchema=lazySchema(()=>zodSchema(object({code:string$2(),fingerprint:string$2()}))),programmaticToolCallingOutputSchema=lazySchema(()=>zodSchema(object({result:string$2(),status:_enum(["completed","incomplete"])}))),programmaticToolCallingFactory=createProviderExecutedToolFactory({id:"openai.programmatic_tool_calling",inputSchema:programmaticToolCallingInputSchema,outputSchema:programmaticToolCallingOutputSchema,supportsDeferredResults:!0}),programmaticToolCalling=()=>programmaticToolCallingFactory({}),openaiTools={applyPatch,customTool,codeInterpreter,computer,fileSearch,imageGeneration,localShell,shell,webSearchPreview,webSearch,mcp,programmaticToolCalling,toolSearch};function parseOpenAIRealtimeServerEvent(Au){var lo,$u,Ru,Iu,Pu,Ou,Mu,Du,Lu,Bu,ju,Fu,zu,Uu,Hu,Vu,Gu,Wu,Ku;const Ju=Au,Yu=Ju.type;switch(Yu){case"session.created":return{type:"session-created",sessionId:(lo=Ju.session)==null?void 0:lo.id,raw:Au};case"session.updated":return{type:"session-updated",raw:Au};case"input_audio_buffer.speech_started":return{type:"speech-started",itemId:Ju.item_id,raw:Au};case"input_audio_buffer.speech_stopped":return{type:"speech-stopped",itemId:Ju.item_id,raw:Au};case"input_audio_buffer.committed":return{type:"audio-committed",itemId:Ju.item_id,previousItemId:Ju.previous_item_id,raw:Au};case"conversation.item.added":return{type:"conversation-item-added",itemId:(Ru=($u=Ju.item)==null?void 0:$u.id)!=null?Ru:Ju.item_id,item:Ju.item,raw:Au};case"conversation.item.input_audio_transcription.completed":return{type:"input-transcription-completed",itemId:Ju.item_id,transcript:(Iu=Ju.transcript)!=null?Iu:"",raw:Au};case"response.created":return{type:"response-created",responseId:(Ou=(Pu=Ju.response)==null?void 0:Pu.id)!=null?Ou:Ju.response_id,raw:Au};case"response.done":return{type:"response-done",responseId:(Du=(Mu=Ju.response)==null?void 0:Mu.id)!=null?Du:Ju.response_id,status:(Bu=(Lu=Ju.response)==null?void 0:Lu.status)!=null?Bu:"completed",raw:Au};case"response.output_item.added":return{type:"output-item-added",responseId:Ju.response_id,itemId:(Fu=(ju=Ju.item)==null?void 0:ju.id)!=null?Fu:Ju.item_id,raw:Au};case"response.output_item.done":return{type:"output-item-done",responseId:Ju.response_id,itemId:(Uu=(zu=Ju.item)==null?void 0:zu.id)!=null?Uu:Ju.item_id,raw:Au};case"response.content_part.added":return{type:"content-part-added",responseId:Ju.response_id,itemId:Ju.item_id,raw:Au};case"response.content_part.done":return{type:"content-part-done",responseId:Ju.response_id,itemId:Ju.item_id,raw:Au};case"response.output_audio.delta":return{type:"audio-delta",responseId:Ju.response_id,itemId:Ju.item_id,delta:Ju.delta,raw:Au};case"response.output_audio.done":return{type:"audio-done",responseId:Ju.response_id,itemId:Ju.item_id,raw:Au};case"response.output_audio_transcript.delta":return{type:"audio-transcript-delta",responseId:Ju.response_id,itemId:Ju.item_id,delta:Ju.delta,raw:Au};case"response.output_audio_transcript.done":return{type:"audio-transcript-done",responseId:Ju.response_id,itemId:Ju.item_id,transcript:Ju.transcript,raw:Au};case"response.output_text.delta":return{type:"text-delta",responseId:Ju.response_id,itemId:Ju.item_id,delta:Ju.delta,raw:Au};case"response.output_text.done":return{type:"text-done",responseId:Ju.response_id,itemId:Ju.item_id,text:Ju.text,raw:Au};case"response.function_call_arguments.delta":return{type:"function-call-arguments-delta",responseId:Ju.response_id,itemId:Ju.item_id,callId:Ju.call_id,delta:Ju.delta,raw:Au};case"response.function_call_arguments.done":return{type:"function-call-arguments-done",responseId:Ju.response_id,itemId:Ju.item_id,callId:Ju.call_id,name:Ju.name,arguments:Ju.arguments,raw:Au};case"error":return{type:"error",message:(Gu=(Vu=(Hu=Ju.error)==null?void 0:Hu.message)!=null?Vu:Ju.message)!=null?Gu:"Unknown error",code:(Ku=(Wu=Ju.error)==null?void 0:Wu.code)!=null?Ku:Ju.code,raw:Au};default:return{type:"custom",rawType:Yu,raw:Au}}}function serializeOpenAIRealtimeClientEvent(Au,lo){switch(Au.type){case"session-update":return{type:"session.update",session:buildOpenAISessionConfig(Au.config,lo)};case"input-audio-append":return{type:"input_audio_buffer.append",audio:Au.audio};case"input-audio-commit":return{type:"input_audio_buffer.commit"};case"input-audio-clear":return{type:"input_audio_buffer.clear"};case"conversation-item-create":{const $u=Au.item;switch($u.type){case"text-message":return{type:"conversation.item.create",item:{type:"message",role:$u.role,content:[{type:"input_text",text:$u.text}]}};case"audio-message":return{type:"conversation.item.create",item:{type:"message",role:$u.role,content:[{type:"input_audio",audio:$u.audio}]}};case"function-call-output":return{type:"conversation.item.create",item:{type:"function_call_output",call_id:$u.callId,output:$u.output}}}break}case"conversation-item-truncate":return{type:"conversation.item.truncate",item_id:Au.itemId,content_index:Au.contentIndex,audio_end_ms:Au.audioEndMs};case"response-create":return{type:"response.create",...Au.options!=null?{response:{...Au.options.modalities!=null?{output_modalities:Au.options.modalities}:{},...Au.options.instructions!=null?{instructions:Au.options.instructions}:{},...Au.options.metadata!=null?{metadata:Au.options.metadata}:{}}}:{}};case"response-cancel":return{type:"response.cancel"}}}function buildOpenAISessionConfig(Au,lo){var $u;const Ru={type:"realtime",model:lo};Au.instructions!=null&&(Ru.instructions=Au.instructions),Au.outputModalities!=null&&(Ru.output_modalities=Au.outputModalities);const Iu={};if(Au.inputAudioFormat!=null||Au.inputAudioTranscription!=null||Au.turnDetection!=null){const Pu={};if(Au.inputAudioFormat!=null&&(Pu.format={type:Au.inputAudioFormat.type,...Au.inputAudioFormat.rate!=null?{rate:Au.inputAudioFormat.rate}:{}}),Au.turnDetection!=null)if(Au.turnDetection.type==="disabled")Pu.turn_detection=null;else{const Ou={type:Au.turnDetection.type==="server-vad"?"server_vad":"semantic_vad"};Au.turnDetection.threshold!=null&&(Ou.threshold=Au.turnDetection.threshold),Au.turnDetection.silenceDurationMs!=null&&(Ou.silence_duration_ms=Au.turnDetection.silenceDurationMs),Au.turnDetection.prefixPaddingMs!=null&&(Ou.prefix_padding_ms=Au.turnDetection.prefixPaddingMs),Pu.turn_detection=Ou}Au.inputAudioTranscription!=null&&(Pu.transcription={model:($u=Au.inputAudioTranscription.model)!=null?$u:"gpt-realtime-whisper",...Au.inputAudioTranscription.language!=null?{language:Au.inputAudioTranscription.language}:{},...Au.inputAudioTranscription.prompt!=null?{prompt:Au.inputAudioTranscription.prompt}:{}}),Iu.input=Pu}if(Au.outputAudioFormat!=null||Au.voice!=null){const Pu={};Au.outputAudioFormat!=null&&(Pu.format={type:Au.outputAudioFormat.type,...Au.outputAudioFormat.rate!=null?{rate:Au.outputAudioFormat.rate}:{}}),Au.voice!=null&&(Pu.voice=Au.voice),Iu.output=Pu}return Object.keys(Iu).length>0&&(Ru.audio=Iu),Au.tools!=null&&Au.tools.length>0&&(Ru.tools=Au.tools.map(Pu=>({type:Pu.type,name:Pu.name,description:Pu.description,parameters:Pu.parameters})),Ru.tool_choice="auto"),Au.providerOptions!=null&&Object.assign(Ru,Au.providerOptions),Ru}var OpenAIRealtimeModel=class{constructor(Au,lo){this.specificationVersion="v4",this.modelId=Au,this.provider=lo.provider,this.config=lo}async doCreateClientSecret(Au){var lo;const $u=(lo=this.config.fetch)!=null?lo:fetch,Ru=`${this.config.baseURL}/realtime/client_secrets`,Iu=Au.sessionConfig!=null?buildOpenAISessionConfig(Au.sessionConfig,this.modelId):{type:"realtime",model:this.modelId},Pu=await $u(Ru,{method:"POST",headers:{...this.config.headers(),"Content-Type":"application/json"},body:JSON.stringify({session:Iu,...Au.expiresAfterSeconds!=null?{expires_after:{anchor:"created_at",seconds:Au.expiresAfterSeconds}}:{}})});if(!Pu.ok){const Mu=await Pu.text();throw new Error(`OpenAI realtime client secret request failed: ${Pu.status} ${Mu}`)}const Ou=await Pu.json();return{token:Ou.value,url:`wss://${new URL(this.config.baseURL).host}/v1/realtime?model=${encodeURIComponent(this.modelId)}`,expiresAt:Ou.expires_at}}getWebSocketConfig(Au){return{url:Au.url,protocols:["realtime",`openai-insecure-api-key.${Au.token}`]}}parseServerEvent(Au){return parseOpenAIRealtimeServerEvent(Au)}serializeClientEvent(Au){return serializeOpenAIRealtimeClientEvent(Au,this.modelId)}buildSessionConfig(Au){return buildOpenAISessionConfig(Au,this.modelId)}};function convertOpenAIResponsesUsage(Au){var lo,$u,Ru,Iu,Pu,Ou;if(Au==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};const Mu=Au.input_tokens,Du=Au.output_tokens,Lu=($u=(lo=Au.input_tokens_details)==null?void 0:lo.cached_tokens)!=null?$u:0,Bu=(Iu=(Ru=Au.input_tokens_details)==null?void 0:Ru.cache_write_tokens)!=null?Iu:void 0,ju=(Ou=(Pu=Au.output_tokens_details)==null?void 0:Pu.reasoning_tokens)!=null?Ou:0;return{inputTokens:{total:Mu,noCache:Mu-Lu-(Bu??0),cacheRead:Lu,cacheWrite:Bu},outputTokens:{total:Du,text:Du-ju,reasoning:ju},raw:Au}}function serializeToolCallArguments2(Au){return JSON.stringify(Au===void 0?{}:Au)}function mapToolCaller(Au){return Au==null?void 0:Au.type==="program"?{type:"program",caller_id:Au.callerId}:Au}function getPromptCacheBreakpoint2(Au,lo){var $u;return($u=Au?.[lo])==null?void 0:$u.promptCacheBreakpoint}function isFileId(Au,lo){return lo?lo.some($u=>Au.startsWith($u)):!1}async function convertToOpenAIResponsesInput({prompt:Au,toolNameMapping:lo,systemMessageMode:$u,providerOptionsName:Ru,fileIdPrefixes:Iu,passThroughUnsupportedFiles:Pu=!1,store:Ou,hasConversation:Mu=!1,hasPreviousResponseId:Du=!1,hasLocalShellTool:Lu=!1,hasShellTool:Bu=!1,hasApplyPatchTool:ju=!1,hasComputerTool:Fu=!1,customProviderToolNames:zu}){var Uu,Hu,Vu,Gu,Wu,Ku,Ju,Yu,Xu,ed,td,nd,od,sd,ad,pd,gd,_d,yd,bd,Sd,Ed,cd,dd,md,ld,hd,vd,wd,kd,Rd,Od,jd,Cd,Ad,$d,qd,Dd;let Ud=[];const rh=[],Jd=new Set;for(const{role:vh,content:sh,providerOptions:Eh}of Au)switch(vh){case"system":{switch($u){case"system":{const bh=getPromptCacheBreakpoint2(Eh,Ru);Ud.push({role:"system",content:bh==null?sh:[{type:"input_text",text:sh,prompt_cache_breakpoint:bh}]});break}case"developer":{const bh=getPromptCacheBreakpoint2(Eh,Ru);Ud.push({role:"developer",content:bh==null?sh:[{type:"input_text",text:sh,prompt_cache_breakpoint:bh}]});break}case"remove":{rh.push({type:"other",message:"system messages are removed for this model"});break}default:{const bh=$u;throw new Error(`Unsupported system message mode: ${bh}`)}}break}case"user":{Ud.push({role:"user",content:sh.map((bh,Qd)=>{var th,lh,Dh,Vd,Fd;switch(bh.type){case"text":{const Id=getPromptCacheBreakpoint2(bh.providerOptions,Ru);return{type:"input_text",text:bh.text,...Id!=null&&{prompt_cache_breakpoint:Id}}}case"file":{const Id=getPromptCacheBreakpoint2(bh.providerOptions,Ru);switch(bh.data.type){case"reference":{const Pd=resolveProviderReference({reference:bh.data.reference,provider:Ru});return getTopLevelMediaType(bh.mediaType)==="image"?{type:"input_image",file_id:Pd,detail:(lh=(th=bh.providerOptions)==null?void 0:th[Ru])==null?void 0:lh.imageDetail,...Id!=null&&{prompt_cache_breakpoint:Id}}:{type:"input_file",file_id:Pd,...Id!=null&&{prompt_cache_breakpoint:Id}}}case"text":throw new UnsupportedFunctionalityError({functionality:"text file parts"});case"url":case"data":{if(getTopLevelMediaType(bh.mediaType)==="image")return{type:"input_image",...bh.data.type==="url"?{image_url:bh.data.url.toString()}:typeof bh.data.data=="string"&&isFileId(bh.data.data,Iu)?{file_id:bh.data.data}:{image_url:`data:${resolveFullMediaType({part:bh})};base64,${convertToBase64(bh.data.data)}`},detail:(Vd=(Dh=bh.providerOptions)==null?void 0:Dh[Ru])==null?void 0:Vd.imageDetail,...Id!=null&&{prompt_cache_breakpoint:Id}};{if(bh.data.type==="url")return{type:"input_file",file_url:bh.data.url.toString(),...Id!=null&&{prompt_cache_breakpoint:Id}};const Wd=resolveFullMediaType({part:bh});if(Wd!=="application/pdf"&&!Pu)throw new UnsupportedFunctionalityError({functionality:`file part media type ${Wd}`});return{type:"input_file",...typeof bh.data.data=="string"&&isFileId(bh.data.data,Iu)?{file_id:bh.data.data}:{filename:(Fd=bh.filename)!=null?Fd:Wd==="application/pdf"?`part-${Qd}.pdf`:`part-${Qd}`,file_data:`data:${Wd};base64,${convertToBase64(bh.data.data)}`},...Id!=null&&{prompt_cache_breakpoint:Id}}}}}}}})});break}case"assistant":{const bh={};for(const Qd of sh)switch(Qd.type){case"text":{const th=(Uu=Qd.providerOptions)==null?void 0:Uu[Ru],lh=th?.itemId,Dh=th?.phase;if(Mu&&lh!=null)break;if(Ou&&lh!=null){Ud.push({type:"item_reference",id:lh});break}Ud.push({role:"assistant",content:[{type:"output_text",text:Qd.text}],id:lh,...Dh!=null&&{phase:Dh}});break}case"tool-call":{const th=(Ku=(Vu=(Hu=Qd.providerOptions)==null?void 0:Hu[Ru])==null?void 0:Vu.itemId)!=null?Ku:(Wu=(Gu=Qd.providerMetadata)==null?void 0:Gu[Ru])==null?void 0:Wu.itemId,lh=(td=(Yu=(Ju=Qd.providerOptions)==null?void 0:Ju[Ru])==null?void 0:Yu.namespace)!=null?td:(ed=(Xu=Qd.providerMetadata)==null?void 0:Xu[Ru])==null?void 0:ed.namespace,Dh=(od=(nd=Qd.providerOptions)==null?void 0:nd[Ru])==null?void 0:od.caller;if(Mu&&th!=null)break;const Vd=lo.toProviderToolName(Qd.toolName);if(Vd==="tool_search"){if(Ou&&th!=null){Ud.push({type:"item_reference",id:th});break}const Id=typeof Qd.input=="string"?await parseJSON({text:Qd.input,schema:toolSearchInputSchema}):await validateTypes({value:Qd.input,schema:toolSearchInputSchema}),Pd=Id.call_id!=null?"client":"server";Ud.push({type:"tool_search_call",id:th??Qd.toolCallId,execution:Pd,call_id:(sd=Id.call_id)!=null?sd:null,status:"completed",arguments:Id.arguments});break}if(Vd==="programmatic_tool_calling"){if(Ou&&th!=null){Ud.push({type:"item_reference",id:th});break}const Id=await validateTypes({value:Qd.input,schema:programmaticToolCallingInputSchema});Ud.push({type:"program",id:th??Qd.toolCallId,call_id:Qd.toolCallId,code:Id.code,fingerprint:Id.fingerprint});break}if(Qd.providerExecuted){Ou&&th!=null&&Ud.push({type:"item_reference",id:th});break}if(Du&&Ou&&th!=null)break;const Fd=Lu&&Vd==="local_shell"||Bu&&Vd==="shell"||ju&&Vd==="apply_patch"||Fu&&Vd==="computer"||((ad=zu?.has(Vd))!=null?ad:!1);if(Ou&&th!=null&&Fd){Ud.push({type:"item_reference",id:th});break}if(Lu&&Vd==="local_shell"){const Id=await validateTypes({value:Qd.input,schema:localShellInputSchema});Ud.push({type:"local_shell_call",call_id:Qd.toolCallId,id:th,action:{type:"exec",command:Id.action.command,timeout_ms:Id.action.timeoutMs,user:Id.action.user,working_directory:Id.action.workingDirectory,env:Id.action.env}});break}if(Bu&&Vd==="shell"){const Id=await validateTypes({value:Qd.input,schema:shellInputSchema});Ud.push({type:"shell_call",call_id:Qd.toolCallId,id:th,status:"completed",action:{commands:Id.action.commands,timeout_ms:Id.action.timeoutMs,max_output_length:Id.action.maxOutputLength}});break}if(ju&&Vd==="apply_patch"){const Id=await validateTypes({value:Qd.input,schema:applyPatchInputSchema});Ud.push({type:"apply_patch_call",call_id:Id.callId,id:th,status:"completed",operation:Id.operation});break}if(Fu&&Vd==="computer"){const Id=await validateTypes({value:Qd.input,schema:computerInputSchema});Ud.push({type:"computer_call",call_id:Qd.toolCallId,id:th,status:Id.status,actions:Id.actions.map(Pd=>{switch(Pd.type){case"click":case"double_click":case"move":return{...Pd,keys:Pd.keys};case"drag":return{...Pd,keys:Pd.keys};case"scroll":return{type:"scroll",x:Pd.x,y:Pd.y,scroll_x:Pd.scrollX,scroll_y:Pd.scrollY,keys:Pd.keys};default:return Pd}}),pending_safety_checks:Id.pendingSafetyChecks.map(Pd=>({id:Pd.id,code:Pd.code,message:Pd.message}))});break}if(zu?.has(Vd)){Ud.push({type:"custom_tool_call",call_id:Qd.toolCallId,name:Vd,input:typeof Qd.input=="string"?Qd.input:JSON.stringify(Qd.input),id:th});break}Ud.push({type:"function_call",call_id:Qd.toolCallId,name:Vd,arguments:serializeToolCallArguments2(Qd.input),...lh!=null&&{namespace:lh},...Dh!=null&&{caller:mapToolCaller(Dh)}});break}case"tool-result":{if(Qd.output.type==="execution-denied"||Qd.output.type==="json"&&typeof Qd.output.value=="object"&&Qd.output.value!=null&&"type"in Qd.output.value&&Qd.output.value.type==="execution-denied"||Mu)break;const th=lo.toProviderToolName(Qd.toolName);if(th==="tool_search"){const lh=(Sd=(bd=(gd=(pd=Qd.providerOptions)==null?void 0:pd[Ru])==null?void 0:gd.itemId)!=null?bd:(yd=(_d=Qd.providerMetadata)==null?void 0:_d[Ru])==null?void 0:yd.itemId)!=null?Sd:Qd.toolCallId;if(Ou)Ud.push({type:"item_reference",id:lh});else if(Qd.output.type==="json"){const Dh=await validateTypes({value:Qd.output.value,schema:toolSearchOutputSchema});Ud.push({type:"tool_search_output",id:lh,execution:"server",call_id:null,status:"completed",tools:Dh.tools})}break}if(th==="programmatic_tool_calling"){const lh=(hd=(ld=(cd=(Ed=Qd.providerOptions)==null?void 0:Ed[Ru])==null?void 0:cd.itemId)!=null?ld:(md=(dd=Qd.providerMetadata)==null?void 0:dd[Ru])==null?void 0:md.itemId)!=null?hd:Qd.toolCallId;if(Ou)Ud.push({type:"item_reference",id:lh});else if(Qd.output.type==="json"){const Dh=await validateTypes({value:Qd.output.value,schema:programmaticToolCallingOutputSchema});Ud.push({type:"program_output",id:lh,call_id:Qd.toolCallId,result:Dh.result,status:Dh.status})}break}if(Bu&&th==="shell"){if(Qd.output.type==="json"){const lh=await validateTypes({value:Qd.output.value,schema:shellOutputSchema});Ud.push({type:"shell_call_output",call_id:Qd.toolCallId,output:lh.output.map(Dh=>({stdout:Dh.stdout,stderr:Dh.stderr,outcome:Dh.outcome.type==="timeout"?{type:"timeout"}:{type:"exit",exit_code:Dh.outcome.exitCode}}))})}break}if(Ou){const lh=(kd=(wd=(vd=Qd.providerOptions)==null?void 0:vd[Ru])==null?void 0:wd.itemId)!=null?kd:Qd.toolCallId;Ud.push({type:"item_reference",id:lh})}else rh.push({type:"other",message:`Results for OpenAI tool ${Qd.toolName} are not sent to the API when store is false`});break}case"reasoning":{const th=await parseProviderOptions({provider:Ru,providerOptions:Qd.providerOptions,schema:openaiResponsesReasoningProviderOptionsSchema}),lh=th?.itemId;if((Mu||Du)&&lh!=null)break;if(lh!=null){const Dh=bh[lh];if(Ou)Dh===void 0&&(Ud.push({type:"item_reference",id:lh}),bh[lh]={type:"reasoning",id:lh,summary:[]});else{const Vd=[];Qd.text.length>0?Vd.push({type:"summary_text",text:Qd.text}):Dh!==void 0&&rh.push({type:"other",message:`Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(Qd)}.`}),Dh===void 0?(bh[lh]={type:"reasoning",id:lh,encrypted_content:th?.reasoningEncryptedContent,summary:Vd},Ud.push(bh[lh])):(Dh.summary.push(...Vd),th?.reasoningEncryptedContent!=null&&(Dh.encrypted_content=th.reasoningEncryptedContent))}}else{const Dh=th?.reasoningEncryptedContent;if(Dh!=null){const Vd=[];Qd.text.length>0&&Vd.push({type:"summary_text",text:Qd.text}),Ud.push({type:"reasoning",encrypted_content:Dh,summary:Vd})}else rh.push({type:"other",message:`Non-OpenAI reasoning parts are not supported. Skipping reasoning part: ${JSON.stringify(Qd)}.`})}break}case"custom":{if(Qd.kind==="openai.compaction"){const th=(Rd=Qd.providerOptions)==null?void 0:Rd[Ru],lh=th?.itemId;if(Mu&&lh!=null)break;if(Ou&&lh!=null){Ud.push({type:"item_reference",id:lh});break}const Dh=th?.encryptedContent;lh!=null&&Ud.push({type:"compaction",id:lh,encrypted_content:Dh})}break}}break}case"tool":{for(const bh of sh){if(bh.type==="tool-approval-response"){const Vd=bh;if(Jd.has(Vd.approvalId))continue;Jd.add(Vd.approvalId),Ou&&Ud.push({type:"item_reference",id:Vd.approvalId}),Ud.push({type:"mcp_approval_response",approval_request_id:Vd.approvalId,approve:Vd.approved});continue}const Qd=bh.output;if(Qd.type==="execution-denied"&&((jd=(Od=Qd.providerOptions)==null?void 0:Od.openai)==null?void 0:jd.approvalId))continue;const th=lo.toProviderToolName(bh.toolName);if(th==="tool_search"&&Qd.type==="json"){const Vd=await validateTypes({value:Qd.value,schema:toolSearchOutputSchema});Ud.push({type:"tool_search_output",execution:"client",call_id:bh.toolCallId,status:"completed",tools:Vd.tools});continue}if(Lu&&th==="local_shell"&&Qd.type==="json"){const Vd=await validateTypes({value:Qd.value,schema:localShellOutputSchema});Ud.push({type:"local_shell_call_output",call_id:bh.toolCallId,output:Vd.output});continue}if(Bu&&th==="shell"&&Qd.type==="json"){const Vd=await validateTypes({value:Qd.value,schema:shellOutputSchema});Ud.push({type:"shell_call_output",call_id:bh.toolCallId,output:Vd.output.map(Fd=>({stdout:Fd.stdout,stderr:Fd.stderr,outcome:Fd.outcome.type==="timeout"?{type:"timeout"}:{type:"exit",exit_code:Fd.outcome.exitCode}}))});continue}if(ju&&bh.toolName==="apply_patch"&&Qd.type==="json"){const Vd=await validateTypes({value:Qd.value,schema:applyPatchOutputSchema});Ud.push({type:"apply_patch_call_output",call_id:bh.toolCallId,status:Vd.status,output:Vd.output});continue}if(Fu&&th==="computer"&&Qd.type==="json"){const Vd=await validateTypes({value:Qd.value,schema:computerOutputSchema});Ud.push({type:"computer_call_output",call_id:bh.toolCallId,output:{type:"computer_screenshot",image_url:Vd.output.imageUrl,file_id:Vd.output.fileId,detail:Vd.output.detail},acknowledged_safety_checks:(Cd=Vd.acknowledgedSafetyChecks)==null?void 0:Cd.map(Fd=>({id:Fd.id,code:Fd.code,message:Fd.message}))});continue}if(zu?.has(th)){let Vd;switch(Qd.type){case"text":case"error-text":Vd=Qd.value;break;case"execution-denied":Vd=(Ad=Qd.reason)!=null?Ad:"Tool call execution denied.";break;case"json":case"error-json":Vd=JSON.stringify(Qd.value);break;case"content":Vd=Qd.value.map(Fd=>{var Id,Pd,Wd;const Nd=getPromptCacheBreakpoint2(Fd.providerOptions,Ru);switch(Fd.type){case"text":return{type:"input_text",text:Fd.text,...Nd!=null&&{prompt_cache_breakpoint:Nd}};case"file":{const Kd=getTopLevelMediaType(Fd.mediaType),Xd=(Pd=(Id=Fd.providerOptions)==null?void 0:Id[Ru])==null?void 0:Pd.imageDetail;if(Fd.data.type==="data"){const gh=resolveFullMediaType({part:Fd});return Kd==="image"?{type:"input_image",image_url:`data:${gh};base64,${convertToBase64(Fd.data.data)}`,detail:Xd,...Nd!=null&&{prompt_cache_breakpoint:Nd}}:{type:"input_file",filename:(Wd=Fd.filename)!=null?Wd:"data",file_data:`data:${gh};base64,${convertToBase64(Fd.data.data)}`,...Nd!=null&&{prompt_cache_breakpoint:Nd}}}if(Fd.data.type==="url")return Kd==="image"?{type:"input_image",image_url:Fd.data.url.toString(),detail:Xd,...Nd!=null&&{prompt_cache_breakpoint:Nd}}:{type:"input_file",file_url:Fd.data.url.toString(),...Nd!=null&&{prompt_cache_breakpoint:Nd}};rh.push({type:"other",message:`unsupported custom tool content part type: ${Fd.type} with data type: ${Fd.data.type}`});return}default:rh.push({type:"other",message:`unsupported custom tool content part type: ${Fd.type}`});return}}).filter(isNonNullable);break;default:Vd=""}Ud.push({type:"custom_tool_call_output",call_id:bh.toolCallId,output:Vd});continue}let lh;switch(Qd.type){case"text":case"error-text":lh=Qd.value;break;case"execution-denied":lh=($d=Qd.reason)!=null?$d:"Tool call execution denied.";break;case"json":case"error-json":lh=JSON.stringify(Qd.value);break;case"content":lh=Qd.value.map(Vd=>{var Fd,Id,Pd;const Wd=getPromptCacheBreakpoint2(Vd.providerOptions,Ru);switch(Vd.type){case"text":return{type:"input_text",text:Vd.text,...Wd!=null&&{prompt_cache_breakpoint:Wd}};case"file":{const Nd=getTopLevelMediaType(Vd.mediaType),Kd=(Id=(Fd=Vd.providerOptions)==null?void 0:Fd[Ru])==null?void 0:Id.imageDetail;if(Vd.data.type==="data"){const Xd=resolveFullMediaType({part:Vd});return Nd==="image"?{type:"input_image",image_url:`data:${Xd};base64,${convertToBase64(Vd.data.data)}`,detail:Kd,...Wd!=null&&{prompt_cache_breakpoint:Wd}}:{type:"input_file",filename:(Pd=Vd.filename)!=null?Pd:"data",file_data:`data:${Xd};base64,${convertToBase64(Vd.data.data)}`,...Wd!=null&&{prompt_cache_breakpoint:Wd}}}if(Vd.data.type==="url")return Nd==="image"?{type:"input_image",image_url:Vd.data.url.toString(),detail:Kd,...Wd!=null&&{prompt_cache_breakpoint:Wd}}:{type:"input_file",file_url:Vd.data.url.toString(),...Wd!=null&&{prompt_cache_breakpoint:Wd}};rh.push({type:"other",message:`unsupported tool content part type: ${Vd.type} with data type: ${Vd.data.type}`});return}default:{rh.push({type:"other",message:`unsupported tool content part type: ${Vd.type}`});return}}}).filter(isNonNullable);break}const Dh=mapToolCaller((Dd=(qd=bh.providerOptions)==null?void 0:qd[Ru])==null?void 0:Dd.caller);Ud.push({type:"function_call_output",call_id:bh.toolCallId,output:lh,...Dh!=null&&{caller:Dh}})}break}default:{const bh=vh;throw new Error(`Unsupported role: ${bh}`)}}return!Ou&&Ud.some(vh=>"type"in vh&&vh.type==="reasoning"&&vh.encrypted_content==null)&&(rh.push({type:"other",message:"Reasoning parts without encrypted content are not supported when store is false. Skipping reasoning parts."}),Ud=Ud.filter(vh=>!("type"in vh)||vh.type!=="reasoning"||vh.encrypted_content!=null)),{input:Ud,warnings:rh}}var openaiResponsesReasoningProviderOptionsSchema=object({itemId:string$2().nullish(),reasoningEncryptedContent:string$2().nullish()});function mapOpenAIResponseFinishReason({finishReason:Au,hasFunctionCall:lo}){switch(Au){case void 0:case null:return lo?"tool-calls":"stop";case"max_output_tokens":return"length";case"content_filter":return"content-filter";default:return lo?"tool-calls":"other"}}var jsonValueSchema2=lazy(()=>union([string$2(),number$2(),boolean$1(),_null(),array(jsonValueSchema2),record$2(string$2(),jsonValueSchema2.optional())])),openaiResponsesComputerSafetyCheckSchema=object({id:string$2(),code:string$2().nullish(),message:string$2().nullish()}),openaiResponsesComputerActionSchema=discriminatedUnion("type",[object({type:literal("click"),button:_enum(["left","right","wheel","back","forward"]),x:number$2(),y:number$2(),keys:array(string$2()).nullish()}),object({type:literal("double_click"),x:number$2(),y:number$2(),keys:array(string$2()).nullish()}),object({type:literal("drag"),path:array(object({x:number$2(),y:number$2()})),keys:array(string$2()).nullish()}),object({type:literal("keypress"),keys:array(string$2())}),object({type:literal("move"),x:number$2(),y:number$2(),keys:array(string$2()).nullish()}),object({type:literal("screenshot")}),object({type:literal("scroll"),x:number$2(),y:number$2(),scroll_x:number$2(),scroll_y:number$2(),keys:array(string$2()).nullish()}),object({type:literal("type"),text:string$2()}),object({type:literal("wait")})]),openaiResponsesComputerCallSchema=object({type:literal("computer_call"),id:string$2(),call_id:string$2().nullish(),status:_enum(["in_progress","completed","incomplete"]),action:openaiResponsesComputerActionSchema.nullish(),actions:array(openaiResponsesComputerActionSchema).nullish(),pending_safety_checks:array(openaiResponsesComputerSafetyCheckSchema).nullish()}),openaiResponsesToolCallerSchema=discriminatedUnion("type",[object({type:literal("direct")}),object({type:literal("program"),caller_id:string$2()})]),openaiResponsesProgramSchema=object({type:literal("program"),id:string$2(),call_id:string$2(),code:string$2(),fingerprint:string$2()}),openaiResponsesProgramOutputSchema=object({type:literal("program_output"),id:string$2(),call_id:string$2(),result:string$2(),status:_enum(["completed","incomplete"])}),openaiResponsesNestedErrorChunkSchema=object({type:literal("error"),sequence_number:number$2(),error:object({type:string$2(),code:string$2(),message:string$2(),param:string$2().nullish()})}),openaiResponsesErrorChunkSchema=object({type:literal("error"),sequence_number:number$2(),code:string$2().nullish(),message:string$2(),param:string$2().nullish()}),openaiResponsesChunkSchema=lazySchema(()=>zodSchema(union([object({type:literal("response.output_text.delta"),item_id:string$2(),delta:string$2(),logprobs:array(object({token:string$2(),logprob:number$2(),top_logprobs:array(object({token:string$2(),logprob:number$2()}))})).nullish()}),object({type:_enum(["response.completed","response.incomplete"]),response:object({incomplete_details:object({reason:string$2()}).nullish(),usage:object({input_tokens:number$2(),input_tokens_details:object({cached_tokens:number$2().nullish(),cache_write_tokens:number$2().nullish(),orchestration_input_tokens:number$2().nullish(),orchestration_input_cached_tokens:number$2().nullish()}).nullish(),output_tokens:number$2(),output_tokens_details:object({reasoning_tokens:number$2().nullish(),orchestration_output_tokens:number$2().nullish()}).nullish()}),reasoning:object({context:string$2().nullish()}).nullish(),service_tier:string$2().nullish()})}),object({type:literal("response.failed"),sequence_number:number$2(),response:object({error:object({code:string$2().nullish(),message:string$2()}).nullish(),incomplete_details:object({reason:string$2()}).nullish(),usage:object({input_tokens:number$2(),input_tokens_details:object({cached_tokens:number$2().nullish(),cache_write_tokens:number$2().nullish(),orchestration_input_tokens:number$2().nullish(),orchestration_input_cached_tokens:number$2().nullish()}).nullish(),output_tokens:number$2(),output_tokens_details:object({reasoning_tokens:number$2().nullish(),orchestration_output_tokens:number$2().nullish()}).nullish()}).nullish(),reasoning:object({context:string$2().nullish()}).nullish(),service_tier:string$2().nullish()})}),object({type:literal("response.created"),response:object({id:string$2(),created_at:number$2(),model:string$2(),service_tier:string$2().nullish()})}),object({type:literal("response.output_item.added"),output_index:number$2(),item:discriminatedUnion("type",[object({type:literal("message"),id:string$2(),phase:_enum(["commentary","final_answer"]).nullish()}),object({type:literal("reasoning"),id:string$2(),encrypted_content:string$2().nullish()}),object({type:literal("function_call"),id:string$2(),call_id:string$2(),name:string$2(),arguments:string$2(),namespace:string$2().nullish(),caller:openaiResponsesToolCallerSchema.nullish()}),openaiResponsesProgramSchema,openaiResponsesProgramOutputSchema,object({type:literal("web_search_call"),id:string$2(),status:string$2()}),openaiResponsesComputerCallSchema,object({type:literal("file_search_call"),id:string$2()}),object({type:literal("image_generation_call"),id:string$2()}),object({type:literal("code_interpreter_call"),id:string$2(),container_id:string$2(),code:string$2().nullable(),outputs:array(discriminatedUnion("type",[object({type:literal("logs"),logs:string$2()}),object({type:literal("image"),url:string$2()})])).nullable(),status:string$2()}),object({type:literal("mcp_call"),id:string$2(),status:string$2(),approval_request_id:string$2().nullish()}),object({type:literal("mcp_list_tools"),id:string$2()}),object({type:literal("mcp_approval_request"),id:string$2()}),object({type:literal("apply_patch_call"),id:string$2(),call_id:string$2(),status:_enum(["in_progress","completed"]),operation:discriminatedUnion("type",[object({type:literal("create_file"),path:string$2(),diff:string$2()}),object({type:literal("delete_file"),path:string$2()}),object({type:literal("update_file"),path:string$2(),diff:string$2()})])}),object({type:literal("custom_tool_call"),id:string$2(),call_id:string$2(),name:string$2(),input:string$2()}),object({type:literal("shell_call"),id:string$2(),call_id:string$2(),status:_enum(["in_progress","completed","incomplete"]),action:object({commands:array(string$2())})}),object({type:literal("compaction"),id:string$2(),encrypted_content:string$2().nullish()}),object({type:literal("shell_call_output"),id:string$2(),call_id:string$2(),status:_enum(["in_progress","completed","incomplete"]),output:array(object({stdout:string$2(),stderr:string$2(),outcome:discriminatedUnion("type",[object({type:literal("timeout")}),object({type:literal("exit"),exit_code:number$2()})])}))}),object({type:literal("tool_search_call"),id:string$2(),execution:_enum(["server","client"]),call_id:string$2().nullable(),status:_enum(["in_progress","completed","incomplete"]),arguments:unknown$1()}),object({type:literal("tool_search_output"),id:string$2(),execution:_enum(["server","client"]),call_id:string$2().nullable(),status:_enum(["in_progress","completed","incomplete"]),tools:array(record$2(string$2(),jsonValueSchema2.optional()))})])}),object({type:literal("response.output_item.done"),output_index:number$2(),item:discriminatedUnion("type",[object({type:literal("message"),id:string$2(),phase:_enum(["commentary","final_answer"]).nullish()}),object({type:literal("reasoning"),id:string$2(),encrypted_content:string$2().nullish()}),object({type:literal("function_call"),id:string$2(),call_id:string$2(),name:string$2(),arguments:string$2(),status:_enum(["in_progress","completed","incomplete"]),namespace:string$2().nullish(),caller:openaiResponsesToolCallerSchema.nullish()}),openaiResponsesProgramSchema,openaiResponsesProgramOutputSchema,object({type:literal("custom_tool_call"),id:string$2(),call_id:string$2(),name:string$2(),input:string$2(),status:literal("completed")}),object({type:literal("code_interpreter_call"),id:string$2(),code:string$2().nullable(),container_id:string$2(),outputs:array(discriminatedUnion("type",[object({type:literal("logs"),logs:string$2()}),object({type:literal("image"),url:string$2()})])).nullable()}),object({type:literal("image_generation_call"),id:string$2(),result:string$2()}),object({type:literal("web_search_call"),id:string$2(),status:string$2(),action:discriminatedUnion("type",[object({type:literal("search"),query:string$2().nullish(),queries:array(string$2()).nullish(),sources:array(discriminatedUnion("type",[object({type:literal("url"),url:string$2()}),object({type:literal("api"),name:string$2()})])).nullish()}),object({type:literal("open_page"),url:string$2().nullish()}),object({type:literal("find_in_page"),url:string$2().nullish(),pattern:string$2().nullish()})]).nullish()}),object({type:literal("file_search_call"),id:string$2(),queries:array(string$2()),results:array(object({attributes:record$2(string$2(),union([string$2(),number$2(),boolean$1()])),file_id:string$2(),filename:string$2(),score:number$2(),text:string$2()})).nullish()}),object({type:literal("local_shell_call"),id:string$2(),call_id:string$2(),action:object({type:literal("exec"),command:array(string$2()),timeout_ms:number$2().optional(),user:string$2().optional(),working_directory:string$2().optional(),env:record$2(string$2(),string$2()).optional()})}),openaiResponsesComputerCallSchema,object({type:literal("mcp_call"),id:string$2(),status:string$2(),arguments:string$2(),name:string$2(),server_label:string$2(),output:string$2().nullish(),error:union([string$2(),object({type:string$2().optional(),code:union([number$2(),string$2()]).optional(),message:string$2().optional()}).loose()]).nullish(),approval_request_id:string$2().nullish()}),object({type:literal("mcp_list_tools"),id:string$2(),server_label:string$2(),tools:array(object({name:string$2(),description:string$2().optional(),input_schema:any(),annotations:record$2(string$2(),unknown$1()).optional()})),error:union([string$2(),object({type:string$2().optional(),code:union([number$2(),string$2()]).optional(),message:string$2().optional()}).loose()]).optional()}),object({type:literal("mcp_approval_request"),id:string$2(),server_label:string$2(),name:string$2(),arguments:string$2(),approval_request_id:string$2().optional()}),object({type:literal("apply_patch_call"),id:string$2(),call_id:string$2(),status:_enum(["in_progress","completed"]),operation:discriminatedUnion("type",[object({type:literal("create_file"),path:string$2(),diff:string$2()}),object({type:literal("delete_file"),path:string$2()}),object({type:literal("update_file"),path:string$2(),diff:string$2()})])}),object({type:literal("shell_call"),id:string$2(),call_id:string$2(),status:_enum(["in_progress","completed","incomplete"]),action:object({commands:array(string$2())})}),object({type:literal("compaction"),id:string$2(),encrypted_content:string$2()}),object({type:literal("shell_call_output"),id:string$2(),call_id:string$2(),status:_enum(["in_progress","completed","incomplete"]),output:array(object({stdout:string$2(),stderr:string$2(),outcome:discriminatedUnion("type",[object({type:literal("timeout")}),object({type:literal("exit"),exit_code:number$2()})])}))}),object({type:literal("tool_search_call"),id:string$2(),execution:_enum(["server","client"]),call_id:string$2().nullable(),status:_enum(["in_progress","completed","incomplete"]),arguments:unknown$1()}),object({type:literal("tool_search_output"),id:string$2(),execution:_enum(["server","client"]),call_id:string$2().nullable(),status:_enum(["in_progress","completed","incomplete"]),tools:array(record$2(string$2(),jsonValueSchema2.optional()))})])}),object({type:literal("response.function_call_arguments.delta"),item_id:string$2(),output_index:number$2(),delta:string$2()}),object({type:literal("response.custom_tool_call_input.delta"),item_id:string$2(),output_index:number$2(),delta:string$2()}),object({type:literal("response.image_generation_call.partial_image"),item_id:string$2(),output_index:number$2(),partial_image_b64:string$2()}),object({type:literal("response.code_interpreter_call_code.delta"),item_id:string$2(),output_index:number$2(),delta:string$2()}),object({type:literal("response.code_interpreter_call_code.done"),item_id:string$2(),output_index:number$2(),code:string$2()}),object({type:literal("response.output_text.annotation.added"),annotation:discriminatedUnion("type",[object({type:literal("url_citation"),start_index:number$2(),end_index:number$2(),url:string$2(),title:string$2()}),object({type:literal("file_citation"),file_id:string$2(),filename:string$2(),index:number$2()}),object({type:literal("container_file_citation"),container_id:string$2(),file_id:string$2(),filename:string$2(),start_index:number$2(),end_index:number$2()}),object({type:literal("file_path"),file_id:string$2(),index:number$2()})])}),object({type:literal("response.reasoning_summary_part.added"),item_id:string$2(),summary_index:number$2()}),object({type:literal("response.reasoning_summary_text.delta"),item_id:string$2(),summary_index:number$2(),delta:string$2()}),object({type:literal("response.reasoning_summary_part.done"),item_id:string$2(),summary_index:number$2()}),object({type:literal("response.apply_patch_call_operation_diff.delta"),item_id:string$2(),output_index:number$2(),delta:string$2(),obfuscation:string$2().nullish()}),object({type:literal("response.apply_patch_call_operation_diff.done"),item_id:string$2(),output_index:number$2(),diff:string$2()}),openaiResponsesNestedErrorChunkSchema,openaiResponsesErrorChunkSchema,object({type:string$2()}).loose().transform(Au=>({type:"unknown_chunk",message:Au.type}))]))),openaiResponsesResponseSchema=lazySchema(()=>zodSchema(object({id:string$2().optional(),created_at:number$2().optional(),error:object({message:string$2(),type:string$2(),param:string$2().nullish(),code:string$2()}).nullish(),model:string$2().optional(),output:array(discriminatedUnion("type",[object({type:literal("message"),role:literal("assistant"),id:string$2(),phase:_enum(["commentary","final_answer"]).nullish(),content:array(object({type:literal("output_text"),text:string$2(),logprobs:array(object({token:string$2(),logprob:number$2(),top_logprobs:array(object({token:string$2(),logprob:number$2()}))})).nullish(),annotations:array(discriminatedUnion("type",[object({type:literal("url_citation"),start_index:number$2(),end_index:number$2(),url:string$2(),title:string$2()}),object({type:literal("file_citation"),file_id:string$2(),filename:string$2(),index:number$2()}),object({type:literal("container_file_citation"),container_id:string$2(),file_id:string$2(),filename:string$2(),start_index:number$2(),end_index:number$2()}),object({type:literal("file_path"),file_id:string$2(),index:number$2()})]))}))}),object({type:literal("web_search_call"),id:string$2(),status:string$2(),action:discriminatedUnion("type",[object({type:literal("search"),query:string$2().nullish(),queries:array(string$2()).nullish(),sources:array(discriminatedUnion("type",[object({type:literal("url"),url:string$2()}),object({type:literal("api"),name:string$2()})])).nullish()}),object({type:literal("open_page"),url:string$2().nullish()}),object({type:literal("find_in_page"),url:string$2().nullish(),pattern:string$2().nullish()})]).nullish()}),object({type:literal("file_search_call"),id:string$2(),queries:array(string$2()),results:array(object({attributes:record$2(string$2(),union([string$2(),number$2(),boolean$1()])),file_id:string$2(),filename:string$2(),score:number$2(),text:string$2()})).nullish()}),object({type:literal("code_interpreter_call"),id:string$2(),code:string$2().nullable(),container_id:string$2(),outputs:array(discriminatedUnion("type",[object({type:literal("logs"),logs:string$2()}),object({type:literal("image"),url:string$2()})])).nullable()}),object({type:literal("image_generation_call"),id:string$2(),result:string$2()}),object({type:literal("local_shell_call"),id:string$2(),call_id:string$2(),action:object({type:literal("exec"),command:array(string$2()),timeout_ms:number$2().optional(),user:string$2().optional(),working_directory:string$2().optional(),env:record$2(string$2(),string$2()).optional()})}),object({type:literal("function_call"),call_id:string$2(),name:string$2(),arguments:string$2(),id:string$2(),namespace:string$2().nullish(),caller:openaiResponsesToolCallerSchema.nullish()}),openaiResponsesProgramSchema,openaiResponsesProgramOutputSchema,object({type:literal("custom_tool_call"),call_id:string$2(),name:string$2(),input:string$2(),id:string$2()}),openaiResponsesComputerCallSchema,object({type:literal("reasoning"),id:string$2(),encrypted_content:string$2().nullish(),summary:array(object({type:literal("summary_text"),text:string$2()}))}),object({type:literal("mcp_call"),id:string$2(),status:string$2(),arguments:string$2(),name:string$2(),server_label:string$2(),output:string$2().nullish(),error:union([string$2(),object({type:string$2().optional(),code:union([number$2(),string$2()]).optional(),message:string$2().optional()}).loose()]).nullish(),approval_request_id:string$2().nullish()}),object({type:literal("mcp_list_tools"),id:string$2(),server_label:string$2(),tools:array(object({name:string$2(),description:string$2().optional(),input_schema:any(),annotations:record$2(string$2(),unknown$1()).optional()})),error:union([string$2(),object({type:string$2().optional(),code:union([number$2(),string$2()]).optional(),message:string$2().optional()}).loose()]).optional()}),object({type:literal("mcp_approval_request"),id:string$2(),server_label:string$2(),name:string$2(),arguments:string$2(),approval_request_id:string$2().optional()}),object({type:literal("apply_patch_call"),id:string$2(),call_id:string$2(),status:_enum(["in_progress","completed"]),operation:discriminatedUnion("type",[object({type:literal("create_file"),path:string$2(),diff:string$2()}),object({type:literal("delete_file"),path:string$2()}),object({type:literal("update_file"),path:string$2(),diff:string$2()})])}),object({type:literal("shell_call"),id:string$2(),call_id:string$2(),status:_enum(["in_progress","completed","incomplete"]),action:object({commands:array(string$2())})}),object({type:literal("compaction"),id:string$2(),encrypted_content:string$2()}),object({type:literal("shell_call_output"),id:string$2(),call_id:string$2(),status:_enum(["in_progress","completed","incomplete"]),output:array(object({stdout:string$2(),stderr:string$2(),outcome:discriminatedUnion("type",[object({type:literal("timeout")}),object({type:literal("exit"),exit_code:number$2()})])}))}),object({type:literal("tool_search_call"),id:string$2(),execution:_enum(["server","client"]),call_id:string$2().nullable(),status:_enum(["in_progress","completed","incomplete"]),arguments:unknown$1()}),object({type:literal("tool_search_output"),id:string$2(),execution:_enum(["server","client"]),call_id:string$2().nullable(),status:_enum(["in_progress","completed","incomplete"]),tools:array(record$2(string$2(),jsonValueSchema2.optional()))})])).optional(),service_tier:string$2().nullish(),reasoning:object({context:string$2().nullish()}).nullish(),incomplete_details:object({reason:string$2()}).nullish(),usage:object({input_tokens:number$2(),input_tokens_details:object({cached_tokens:number$2().nullish(),cache_write_tokens:number$2().nullish(),orchestration_input_tokens:number$2().nullish(),orchestration_input_cached_tokens:number$2().nullish()}).nullish(),output_tokens:number$2(),output_tokens_details:object({reasoning_tokens:number$2().nullish(),orchestration_output_tokens:number$2().nullish()}).nullish()}).optional()}))),TOP_LOGPROBS_MAX=20,openaiLanguageModelResponsesOptionsSchema=lazySchema(()=>zodSchema(object({conversation:string$2().nullish(),include:array(_enum(["reasoning.encrypted_content","file_search_call.results","web_search_call.results","message.output_text.logprobs"])).nullish(),instructions:string$2().nullish(),logprobs:union([boolean$1(),number$2().min(1).max(TOP_LOGPROBS_MAX)]).optional(),maxToolCalls:number$2().nullish(),metadata:any().nullish(),parallelToolCalls:boolean$1().nullish(),previousResponseId:string$2().nullish(),promptCacheKey:string$2().nullish(),promptCacheOptions:object({mode:_enum(["implicit","explicit"]).optional(),ttl:literal("30m").optional()}).optional(),promptCacheRetention:_enum(["in_memory","24h"]).nullish(),reasoningEffort:string$2().nullish(),reasoningMode:_enum(["standard","pro"]).optional(),reasoningContext:_enum(["auto","current_turn","all_turns"]).optional(),reasoningSummary:string$2().nullish(),safetyIdentifier:string$2().nullish(),serviceTier:_enum(["auto","flex","priority","default"]).nullish(),store:boolean$1().nullish(),passThroughUnsupportedFiles:boolean$1().optional(),strictJsonSchema:boolean$1().nullish(),textVerbosity:_enum(["low","medium","high"]).nullish(),truncation:_enum(["auto","disabled"]).nullish(),user:string$2().nullish(),systemMessageMode:_enum(["system","developer","remove"]).optional(),forceReasoning:boolean$1().optional(),contextManagement:array(object({type:literal("compaction"),compactThreshold:number$2()})).nullish(),allowedTools:object({toolNames:array(string$2()).min(1),mode:_enum(["auto","required"]).optional()}).optional()})));async function prepareResponsesTools({tools:Au,toolChoice:lo,allowedTools:$u,toolNameMapping:Ru,customProviderToolNames:Iu}){var Pu,Ou,Mu;Au=Au?.length?Au:void 0;const Du=[];if(Au==null)return{tools:void 0,toolChoice:void 0,toolWarnings:Du};const Lu=[],Bu=new Map,ju=Iu??new Set;for(const zu of Au)switch(zu.type){case"function":{const Uu=(Pu=zu.providerOptions)==null?void 0:Pu.openai,Hu=prepareFunctionTool({tool:zu,options:Uu}),Vu=Uu?.namespace;if(Vu==null)Lu.push(Hu);else{let Gu=Bu.get(Vu.name);if(Gu==null)Gu={type:"namespace",name:Vu.name,description:Vu.description,tools:[]},Bu.set(Vu.name,Gu),Lu.push(Gu);else if(Gu.description!==Vu.description)throw new UnsupportedFunctionalityError({functionality:`conflicting descriptions for OpenAI tool namespace "${Vu.name}"`});Gu.tools.push(Hu)}break}case"provider":{switch(zu.id){case"openai.file_search":{const Uu=await validateTypes({value:zu.args,schema:fileSearchArgsSchema});Lu.push({type:"file_search",vector_store_ids:Uu.vectorStoreIds,max_num_results:Uu.maxNumResults,ranking_options:Uu.ranking?{ranker:Uu.ranking.ranker,score_threshold:Uu.ranking.scoreThreshold}:void 0,filters:Uu.filters});break}case"openai.local_shell":{Lu.push({type:"local_shell"});break}case"openai.shell":{const Uu=await validateTypes({value:zu.args,schema:shellArgsSchema});Lu.push({type:"shell",...Uu.environment&&{environment:mapShellEnvironment(Uu.environment)}});break}case"openai.apply_patch":{Lu.push({type:"apply_patch"});break}case"openai.computer":{Lu.push({type:"computer"});break}case"openai.web_search_preview":{const Uu=await validateTypes({value:zu.args,schema:webSearchPreviewArgsSchema});Lu.push({type:"web_search_preview",search_context_size:Uu.searchContextSize,user_location:Uu.userLocation});break}case"openai.web_search":{const Uu=await validateTypes({value:zu.args,schema:webSearchArgsSchema});Lu.push({type:"web_search",filters:Uu.filters!=null?{allowed_domains:Uu.filters.allowedDomains}:void 0,external_web_access:Uu.externalWebAccess,search_context_size:Uu.searchContextSize,user_location:Uu.userLocation});break}case"openai.code_interpreter":{const Uu=await validateTypes({value:zu.args,schema:codeInterpreterArgsSchema});Lu.push({type:"code_interpreter",container:Uu.container==null?{type:"auto",file_ids:void 0}:typeof Uu.container=="string"?Uu.container:{type:"auto",file_ids:Uu.container.fileIds}});break}case"openai.image_generation":{const Uu=await validateTypes({value:zu.args,schema:imageGenerationArgsSchema});Lu.push({type:"image_generation",background:Uu.background,input_fidelity:Uu.inputFidelity,input_image_mask:Uu.inputImageMask?{file_id:Uu.inputImageMask.fileId,image_url:Uu.inputImageMask.imageUrl}:void 0,model:Uu.model,moderation:Uu.moderation,partial_images:Uu.partialImages,quality:Uu.quality,output_compression:Uu.outputCompression,output_format:Uu.outputFormat,size:Uu.size});break}case"openai.mcp":{const Uu=await validateTypes({value:zu.args,schema:mcpArgsSchema}),Hu=Wu=>({tool_names:Wu.toolNames}),Vu=Uu.requireApproval,Gu=Vu==null?void 0:typeof Vu=="string"?Vu:Vu.never!=null?{never:Hu(Vu.never)}:void 0;Lu.push({type:"mcp",server_label:Uu.serverLabel,allowed_tools:Array.isArray(Uu.allowedTools)?Uu.allowedTools:Uu.allowedTools?{read_only:Uu.allowedTools.readOnly,tool_names:Uu.allowedTools.toolNames}:void 0,authorization:Uu.authorization,connector_id:Uu.connectorId,headers:Uu.headers,require_approval:Gu??"never",server_description:Uu.serverDescription,server_url:Uu.serverUrl});break}case"openai.custom":{const Uu=await validateTypes({value:zu.args,schema:customArgsSchema});Lu.push({type:"custom",name:zu.name,description:Uu.description,format:Uu.format}),ju.add(zu.name);break}case"openai.programmatic_tool_calling":{Lu.push({type:"programmatic_tool_calling"});break}case"openai.tool_search":{const Uu=await validateTypes({value:zu.args,schema:toolSearchArgsSchema});Lu.push({type:"tool_search",...Uu.execution!=null?{execution:Uu.execution}:{},...Uu.description!=null?{description:Uu.description}:{},...Uu.parameters!=null?{parameters:Uu.parameters}:{}});break}}break}default:Du.push({type:"unsupported",feature:`function tool ${zu}`});break}if($u!=null)return{tools:Lu,toolChoice:{type:"allowed_tools",mode:(Ou=$u.mode)!=null?Ou:"auto",tools:$u.toolNames.map(zu=>{var Uu;return{type:"function",name:(Uu=Ru?.toProviderToolName(zu))!=null?Uu:zu}})},toolWarnings:Du};if(lo==null)return{tools:Lu,toolChoice:void 0,toolWarnings:Du};const Fu=lo.type;switch(Fu){case"auto":case"none":case"required":return{tools:Lu,toolChoice:Fu,toolWarnings:Du};case"tool":{const zu=(Mu=Ru?.toProviderToolName(lo.toolName))!=null?Mu:lo.toolName;return{tools:Lu,toolChoice:zu==="code_interpreter"||zu==="file_search"||zu==="image_generation"||zu==="web_search_preview"||zu==="web_search"||zu==="mcp"||zu==="apply_patch"||zu==="computer"||zu==="programmatic_tool_calling"?{type:zu}:ju.has(zu)?{type:"custom",name:zu}:{type:"function",name:zu},toolWarnings:Du}}default:{const zu=Fu;throw new UnsupportedFunctionalityError({functionality:`tool choice type: ${zu}`})}}}function prepareFunctionTool({tool:Au,options:lo}){const $u=lo?.deferLoading;return{type:"function",name:Au.name,description:Au.description,parameters:Au.inputSchema,...Au.strict!=null?{strict:Au.strict}:{},...$u!=null?{defer_loading:$u}:{},...lo?.allowedCallers!=null?{allowed_callers:lo.allowedCallers}:{},...lo?.outputSchema!=null?{output_schema:lo.outputSchema}:{}}}function mapShellEnvironment(Au){if(Au.type==="containerReference")return{type:"container_reference",container_id:Au.containerId};if(Au.type==="containerAuto"){const $u=Au;return{type:"container_auto",file_ids:$u.fileIds,memory_limit:$u.memoryLimit,network_policy:$u.networkPolicy==null?void 0:$u.networkPolicy.type==="disabled"?{type:"disabled"}:{type:"allowlist",allowed_domains:$u.networkPolicy.allowedDomains,domain_secrets:$u.networkPolicy.domainSecrets},skills:mapShellSkills($u.skills)}}return{type:"local",skills:Au.skills}}function mapShellSkills(Au){return Au?.map(lo=>{var $u,Ru;return lo.type==="skillReference"?{type:"skill_reference",skill_id:resolveProviderReference({reference:($u=lo.providerReference)!=null?$u:{},provider:"openai"}),version:(Ru=lo.version)!=null?Ru:"latest"}:{type:"inline",name:lo.name,description:lo.description,source:{type:"base64",media_type:lo.source.mediaType,data:lo.source.data}}})}function extractApprovalRequestIdToToolCallIdMapping(Au){var lo,$u;const Ru={};for(const Iu of Au)if(Iu.role==="assistant")for(const Pu of Iu.content){if(Pu.type!=="tool-call")continue;const Ou=($u=(lo=Pu.providerOptions)==null?void 0:lo.openai)==null?void 0:$u.approvalRequestId;Ou!=null&&(Ru[Ou]=Pu.toolCallId)}return Ru}function mapComputerAction(Au){switch(Au.type){case"click":return{type:"click",button:Au.button,x:Au.x,y:Au.y,...Au.keys!=null&&{keys:Au.keys}};case"double_click":return{type:"double_click",x:Au.x,y:Au.y,...Au.keys!=null&&{keys:Au.keys}};case"drag":return{type:"drag",path:Au.path,...Au.keys!=null&&{keys:Au.keys}};case"keypress":return Au;case"move":return{type:"move",x:Au.x,y:Au.y,...Au.keys!=null&&{keys:Au.keys}};case"screenshot":return Au;case"scroll":return{type:"scroll",x:Au.x,y:Au.y,scrollX:Au.scroll_x,scrollY:Au.scroll_y,...Au.keys!=null&&{keys:Au.keys}};case"type":return Au;case"wait":return Au}}function mapComputerCallInput({action:Au,actions:lo,pending_safety_checks:$u,status:Ru}){var Iu;return{actions:(lo??(Au!=null?[Au]:[])).map(mapComputerAction),pendingSafetyChecks:(Iu=$u?.map(Pu=>({id:Pu.id,...Pu.code!=null&&{code:Pu.code},...Pu.message!=null&&{message:Pu.message}})))!=null?Iu:[],status:Ru}}var OpenAIResponsesLanguageModel=class Vw{constructor(lo,$u){this.specificationVersion="v4",this.supportedUrls={"image/*":[/^https?:\/\/.*$/],"application/pdf":[/^https?:\/\/.*$/]},this.modelId=lo,this.config=$u}static[WORKFLOW_SERIALIZE](lo){return serializeModelOptions({modelId:lo.modelId,config:lo.config})}static[WORKFLOW_DESERIALIZE](lo){return new Vw(lo.modelId,lo.config)}get provider(){return this.config.provider}async getArgs({maxOutputTokens:lo,temperature:$u,stopSequences:Ru,topP:Iu,topK:Pu,presencePenalty:Ou,frequencyPenalty:Mu,seed:Du,prompt:Lu,reasoning:Bu,providerOptions:ju,tools:Fu,toolChoice:zu,responseFormat:Uu}){var Hu,Vu,Gu,Wu,Ku,Ju,Yu,Xu,ed,td,nd,od;const sd=[],ad=getOpenAILanguageModelCapabilities(this.modelId);Pu!=null&&sd.push({type:"unsupported",feature:"topK"}),Du!=null&&sd.push({type:"unsupported",feature:"seed"}),Ou!=null&&sd.push({type:"unsupported",feature:"presencePenalty"}),Mu!=null&&sd.push({type:"unsupported",feature:"frequencyPenalty"}),Ru!=null&&sd.push({type:"unsupported",feature:"stopSequences"});const pd=this.config.provider.includes("azure")?"azure":"openai";let gd=await parseProviderOptions({provider:pd,providerOptions:ju,schema:openaiLanguageModelResponsesOptionsSchema});gd==null&&pd!=="openai"&&(gd=await parseProviderOptions({provider:"openai",providerOptions:ju,schema:openaiLanguageModelResponsesOptionsSchema}));const _d=(Hu=gd?.reasoningEffort)!=null?Hu:isCustomReasoning(Bu)?Bu:void 0,yd=gd?.reasoningSummary!==void 0?gd.reasoningSummary:_d!=null&&_d!=="none"?"detailed":void 0,bd=(Vu=gd?.forceReasoning)!=null?Vu:ad.isReasoningModel;gd?.conversation&&gd?.previousResponseId&&sd.push({type:"unsupported",feature:"conversation",details:"conversation and previousResponseId cannot be used together"});const Sd=createToolNameMapping({tools:Fu,providerToolNames:{"openai.code_interpreter":"code_interpreter","openai.computer":"computer","openai.file_search":"file_search","openai.image_generation":"image_generation","openai.local_shell":"local_shell","openai.shell":"shell","openai.web_search":"web_search","openai.web_search_preview":"web_search_preview","openai.mcp":"mcp","openai.apply_patch":"apply_patch","openai.tool_search":"tool_search","openai.programmatic_tool_calling":"programmatic_tool_calling"}}),Ed=new Set,{tools:cd,toolChoice:dd,toolWarnings:md}=await prepareResponsesTools({tools:Fu,toolChoice:zu,allowedTools:(Gu=gd?.allowedTools)!=null?Gu:void 0,toolNameMapping:Sd,customProviderToolNames:Ed}),{input:ld,warnings:hd}=await convertToOpenAIResponsesInput({prompt:Lu,toolNameMapping:Sd,systemMessageMode:(Wu=gd?.systemMessageMode)!=null?Wu:bd?"developer":ad.systemMessageMode,providerOptionsName:pd,fileIdPrefixes:this.config.fileIdPrefixes,passThroughUnsupportedFiles:(Ku=gd?.passThroughUnsupportedFiles)!=null?Ku:!1,store:(Ju=gd?.store)!=null?Ju:!0,hasConversation:gd?.conversation!=null,hasPreviousResponseId:gd?.previousResponseId!=null,hasLocalShellTool:Rd("openai.local_shell"),hasShellTool:Rd("openai.shell"),hasApplyPatchTool:Rd("openai.apply_patch"),hasComputerTool:Rd("openai.computer"),customProviderToolNames:Ed.size>0?Ed:void 0});sd.push(...hd);const vd=(Yu=gd?.strictJsonSchema)!=null?Yu:!0;let wd=gd?.include;function kd(Dd){wd==null?wd=[Dd]:wd.includes(Dd)||(wd=[...wd,Dd])}function Rd(Dd){return Fu?.find(Ud=>Ud.type==="provider"&&Ud.id===Dd)!=null}const Od=typeof gd?.logprobs=="number"?gd?.logprobs:gd?.logprobs===!0?TOP_LOGPROBS_MAX:void 0;Od&&kd("message.output_text.logprobs");const jd=(Xu=Fu?.find(Dd=>Dd.type==="provider"&&(Dd.id==="openai.web_search"||Dd.id==="openai.web_search_preview")))==null?void 0:Xu.name;jd&&kd("web_search_call.action.sources"),Rd("openai.code_interpreter")&&kd("code_interpreter_call.outputs");const Cd=gd?.store;Cd===!1&&bd&&kd("reasoning.encrypted_content");const Ad={model:this.modelId,input:ld,temperature:$u,top_p:Iu,max_output_tokens:lo,...(Uu?.type==="json"||gd?.textVerbosity)&&{text:{...Uu?.type==="json"&&{format:Uu.schema!=null?{type:"json_schema",strict:vd,name:(ed=Uu.name)!=null?ed:"response",description:Uu.description,schema:Uu.schema}:{type:"json_object"}},...gd?.textVerbosity&&{verbosity:gd.textVerbosity}}},conversation:gd?.conversation,max_tool_calls:gd?.maxToolCalls,metadata:gd?.metadata,parallel_tool_calls:gd?.parallelToolCalls,previous_response_id:gd?.previousResponseId,store:Cd,user:gd?.user,instructions:gd?.instructions,service_tier:gd?.serviceTier,include:wd,prompt_cache_key:gd?.promptCacheKey,prompt_cache_options:gd?.promptCacheOptions,prompt_cache_retention:gd?.promptCacheRetention,safety_identifier:gd?.safetyIdentifier,top_logprobs:Od,truncation:gd?.truncation,...gd?.contextManagement&&{context_management:gd.contextManagement.map(Dd=>({type:Dd.type,compact_threshold:Dd.compactThreshold}))},...bd&&(_d!=null||yd!=null||gd?.reasoningMode!=null||gd?.reasoningContext!=null)&&{reasoning:{..._d!=null&&{effort:_d},...yd!=null&&{summary:yd},...gd?.reasoningMode!=null&&{mode:gd.reasoningMode},...gd?.reasoningContext!=null&&{context:gd.reasoningContext}}}};bd?_d==="none"&&ad.supportsNonReasoningParameters||(Ad.temperature!=null&&(Ad.temperature=void 0,sd.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for reasoning models"})),Ad.top_p!=null&&(Ad.top_p=void 0,sd.push({type:"unsupported",feature:"topP",details:"topP is not supported for reasoning models"}))):(gd?.reasoningEffort!=null&&sd.push({type:"unsupported",feature:"reasoningEffort",details:"reasoningEffort is not supported for non-reasoning models"}),gd?.reasoningSummary!=null&&sd.push({type:"unsupported",feature:"reasoningSummary",details:"reasoningSummary is not supported for non-reasoning models"}),gd?.reasoningMode!=null&&sd.push({type:"unsupported",feature:"reasoningMode",details:"reasoningMode is not supported for non-reasoning models"}),gd?.reasoningContext!=null&&sd.push({type:"unsupported",feature:"reasoningContext",details:"reasoningContext is not supported for non-reasoning models"})),gd?.serviceTier==="flex"&&!ad.supportsFlexProcessing&&(sd.push({type:"unsupported",feature:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),delete Ad.service_tier),gd?.serviceTier==="priority"&&!ad.supportsPriorityProcessing&&(sd.push({type:"unsupported",feature:"serviceTier",details:"priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported"}),delete Ad.service_tier);const $d=(od=(nd=(td=Fu?.find(Dd=>Dd.type==="provider"&&Dd.id==="openai.shell"))==null?void 0:td.args)==null?void 0:nd.environment)==null?void 0:od.type,qd=$d==="containerAuto"||$d==="containerReference";return{webSearchToolName:jd,args:{...Ad,tools:cd,tool_choice:dd},warnings:[...sd,...md],store:Cd,toolNameMapping:Sd,providerOptionsName:pd,isShellProviderExecuted:qd}}async doGenerate(lo){var $u,Ru,Iu,Pu,Ou,Mu,Du,Lu,Bu,ju,Fu,zu,Uu,Hu,Vu,Gu,Wu,Ku,Ju,Yu,Xu,ed,td,nd,od,sd,ad,pd,gd,_d,yd,bd;const{args:Sd,warnings:Ed,webSearchToolName:cd,toolNameMapping:dd,providerOptionsName:md,isShellProviderExecuted:ld}=await this.getArgs(lo),hd=this.config.url({path:"/responses",modelId:this.modelId}),vd=extractApprovalRequestIdToToolCallIdMapping(lo.prompt),{responseHeaders:wd,value:kd,rawValue:Rd}=await postJsonToApi({url:hd,headers:combineHeaders((Ru=($u=this.config).headers)==null?void 0:Ru.call($u),lo.headers),body:Sd,failedResponseHandler:openaiFailedResponseHandler,successfulResponseHandler:createJsonResponseHandler(openaiResponsesResponseSchema),abortSignal:lo.abortSignal,fetch:this.config.fetch});if(kd.error)throw new APICallError({message:kd.error.message,url:hd,requestBodyValues:Sd,statusCode:400,responseHeaders:wd,responseBody:Rd,isRetryable:!1});if(kd.output==null){const Dd=(Iu=kd.incomplete_details)==null?void 0:Iu.reason;throw new APICallError({message:Dd?`Responses API returned no output (${Dd})`:"Responses API returned no output",url:hd,requestBodyValues:Sd,statusCode:500,responseHeaders:wd,responseBody:Rd,isRetryable:!1})}const Od=[],jd=[];let Cd=!1;const Ad=[];for(const Dd of kd.output)switch(Dd.type){case"reasoning":{Dd.summary.length===0&&Dd.summary.push({type:"summary_text",text:""});for(const Ud of Dd.summary)Od.push({type:"reasoning",text:Ud.text,providerMetadata:{[md]:{itemId:Dd.id,reasoningEncryptedContent:(Pu=Dd.encrypted_content)!=null?Pu:null}}});break}case"image_generation_call":{Od.push({type:"tool-call",toolCallId:Dd.id,toolName:dd.toCustomToolName("image_generation"),input:"{}",providerExecuted:!0}),Od.push({type:"tool-result",toolCallId:Dd.id,toolName:dd.toCustomToolName("image_generation"),result:{result:Dd.result}});break}case"tool_search_call":{const Ud=(Ou=Dd.call_id)!=null?Ou:Dd.id,rh=Dd.execution==="server";rh&&Ad.push(Ud),Od.push({type:"tool-call",toolCallId:Ud,toolName:dd.toCustomToolName("tool_search"),input:JSON.stringify({arguments:Dd.arguments,call_id:Dd.call_id}),...rh?{providerExecuted:!0}:{},providerMetadata:{[md]:{itemId:Dd.id}}});break}case"tool_search_output":{const Ud=(Du=(Mu=Dd.call_id)!=null?Mu:Ad.shift())!=null?Du:Dd.id;Od.push({type:"tool-result",toolCallId:Ud,toolName:dd.toCustomToolName("tool_search"),result:{tools:Dd.tools},providerMetadata:{[md]:{itemId:Dd.id}}});break}case"local_shell_call":{Od.push({type:"tool-call",toolCallId:Dd.call_id,toolName:dd.toCustomToolName("local_shell"),input:JSON.stringify({action:Dd.action}),providerMetadata:{[md]:{itemId:Dd.id}}});break}case"shell_call":{Od.push({type:"tool-call",toolCallId:Dd.call_id,toolName:dd.toCustomToolName("shell"),input:JSON.stringify({action:{commands:Dd.action.commands}}),...ld&&{providerExecuted:!0},providerMetadata:{[md]:{itemId:Dd.id}}});break}case"shell_call_output":{Od.push({type:"tool-result",toolCallId:Dd.call_id,toolName:dd.toCustomToolName("shell"),result:{output:Dd.output.map(Ud=>({stdout:Ud.stdout,stderr:Ud.stderr,outcome:Ud.outcome.type==="exit"?{type:"exit",exitCode:Ud.outcome.exit_code}:{type:"timeout"}}))}});break}case"message":{for(const Ud of Dd.content){(Bu=(Lu=lo.providerOptions)==null?void 0:Lu[md])!=null&&Bu.logprobs&&Ud.logprobs&&jd.push(Ud.logprobs);const rh={itemId:Dd.id,...Dd.phase!=null&&{phase:Dd.phase},...Ud.annotations.length>0&&{annotations:Ud.annotations}};Od.push({type:"text",text:Ud.text,providerMetadata:{[md]:rh}});for(const Jd of Ud.annotations)Jd.type==="url_citation"?Od.push({type:"source",sourceType:"url",id:(zu=(Fu=(ju=this.config).generateId)==null?void 0:Fu.call(ju))!=null?zu:generateId(),url:Jd.url,title:Jd.title}):Jd.type==="file_citation"?Od.push({type:"source",sourceType:"document",id:(Vu=(Hu=(Uu=this.config).generateId)==null?void 0:Hu.call(Uu))!=null?Vu:generateId(),mediaType:"text/plain",title:Jd.filename,filename:Jd.filename,providerMetadata:{[md]:{type:Jd.type,fileId:Jd.file_id,index:Jd.index}}}):Jd.type==="container_file_citation"?Od.push({type:"source",sourceType:"document",id:(Ku=(Wu=(Gu=this.config).generateId)==null?void 0:Wu.call(Gu))!=null?Ku:generateId(),mediaType:"text/plain",title:Jd.filename,filename:Jd.filename,providerMetadata:{[md]:{type:Jd.type,fileId:Jd.file_id,containerId:Jd.container_id}}}):Jd.type==="file_path"&&Od.push({type:"source",sourceType:"document",id:(Xu=(Yu=(Ju=this.config).generateId)==null?void 0:Yu.call(Ju))!=null?Xu:generateId(),mediaType:"application/octet-stream",title:Jd.file_id,filename:Jd.file_id,providerMetadata:{[md]:{type:Jd.type,fileId:Jd.file_id,index:Jd.index}}})}break}case"function_call":{Cd=!0,Od.push({type:"tool-call",toolCallId:Dd.call_id,toolName:Dd.name,input:Dd.arguments,providerMetadata:{[md]:{itemId:Dd.id,...Dd.namespace!=null&&{namespace:Dd.namespace},...Dd.caller!=null&&{caller:Dd.caller.type==="program"?{type:"program",callerId:Dd.caller.caller_id}:Dd.caller}}}});break}case"program":{Od.push({type:"tool-call",toolCallId:Dd.call_id,toolName:dd.toCustomToolName("programmatic_tool_calling"),input:JSON.stringify({code:Dd.code,fingerprint:Dd.fingerprint}),providerExecuted:!0,providerMetadata:{[md]:{itemId:Dd.id}}});break}case"program_output":{Od.push({type:"tool-result",toolCallId:Dd.call_id,toolName:dd.toCustomToolName("programmatic_tool_calling"),result:{result:Dd.result,status:Dd.status},providerMetadata:{[md]:{itemId:Dd.id}}});break}case"custom_tool_call":{Cd=!0;const Ud=dd.toCustomToolName(Dd.name);Od.push({type:"tool-call",toolCallId:Dd.call_id,toolName:Ud,input:JSON.stringify(Dd.input),providerMetadata:{[md]:{itemId:Dd.id}}});break}case"web_search_call":{Od.push({type:"tool-call",toolCallId:Dd.id,toolName:dd.toCustomToolName(cd??"web_search"),input:JSON.stringify({}),providerExecuted:!0}),Od.push({type:"tool-result",toolCallId:Dd.id,toolName:dd.toCustomToolName(cd??"web_search"),result:mapWebSearchOutput(Dd.action)});break}case"mcp_call":{const Ud=Dd.approval_request_id!=null&&(ed=vd[Dd.approval_request_id])!=null?ed:Dd.id,rh=`mcp.${Dd.name}`;Od.push({type:"tool-call",toolCallId:Ud,toolName:rh,input:Dd.arguments,providerExecuted:!0,dynamic:!0}),Od.push({type:"tool-result",toolCallId:Ud,toolName:rh,result:{type:"call",serverLabel:Dd.server_label,name:Dd.name,arguments:Dd.arguments,...Dd.output!=null?{output:Dd.output}:{},...Dd.error!=null?{error:Dd.error}:{}},providerMetadata:{[md]:{itemId:Dd.id}}});break}case"mcp_list_tools":break;case"mcp_approval_request":{const Ud=(td=Dd.approval_request_id)!=null?td:Dd.id,rh=(sd=(od=(nd=this.config).generateId)==null?void 0:od.call(nd))!=null?sd:generateId(),Jd=`mcp.${Dd.name}`;Od.push({type:"tool-call",toolCallId:rh,toolName:Jd,input:Dd.arguments,providerExecuted:!0,dynamic:!0}),Od.push({type:"tool-approval-request",approvalId:Ud,toolCallId:rh});break}case"computer_call":{if(Dd.call_id==null){Od.push({type:"tool-call",toolCallId:Dd.id,toolName:dd.toCustomToolName("computer_use"),input:"",providerExecuted:!0}),Od.push({type:"tool-result",toolCallId:Dd.id,toolName:dd.toCustomToolName("computer_use"),result:{type:"computer_use_tool_result",status:Dd.status}});break}Cd=!0;const Ud=dd.toCustomToolName("computer");Od.push({type:"tool-call",toolCallId:Dd.call_id,toolName:Ud,input:JSON.stringify(mapComputerCallInput(Dd)),providerMetadata:{[md]:{itemId:Dd.id}}});break}case"file_search_call":{Od.push({type:"tool-call",toolCallId:Dd.id,toolName:dd.toCustomToolName("file_search"),input:"{}",providerExecuted:!0}),Od.push({type:"tool-result",toolCallId:Dd.id,toolName:dd.toCustomToolName("file_search"),result:{queries:Dd.queries,results:(pd=(ad=Dd.results)==null?void 0:ad.map(Ud=>({attributes:Ud.attributes,fileId:Ud.file_id,filename:Ud.filename,score:Ud.score,text:Ud.text})))!=null?pd:null}});break}case"code_interpreter_call":{Od.push({type:"tool-call",toolCallId:Dd.id,toolName:dd.toCustomToolName("code_interpreter"),input:JSON.stringify({code:Dd.code,containerId:Dd.container_id}),providerExecuted:!0}),Od.push({type:"tool-result",toolCallId:Dd.id,toolName:dd.toCustomToolName("code_interpreter"),result:{outputs:Dd.outputs}});break}case"apply_patch_call":{Od.push({type:"tool-call",toolCallId:Dd.call_id,toolName:dd.toCustomToolName("apply_patch"),input:JSON.stringify({callId:Dd.call_id,operation:Dd.operation}),providerMetadata:{[md]:{itemId:Dd.id}}});break}case"compaction":{Od.push({type:"custom",kind:"openai.compaction",providerMetadata:{[md]:{type:"compaction",itemId:Dd.id,encryptedContent:Dd.encrypted_content}}});break}}const $d={[md]:{responseId:kd.id,...jd.length>0?{logprobs:jd}:{},...typeof kd.service_tier=="string"?{serviceTier:kd.service_tier}:{},...((gd=kd.reasoning)==null?void 0:gd.context)!=null?{reasoningContext:kd.reasoning.context}:{}}},qd=kd.usage;return{content:Od,finishReason:{unified:mapOpenAIResponseFinishReason({finishReason:(_d=kd.incomplete_details)==null?void 0:_d.reason,hasFunctionCall:Cd}),raw:(bd=(yd=kd.incomplete_details)==null?void 0:yd.reason)!=null?bd:void 0},usage:convertOpenAIResponsesUsage(qd),request:{body:Sd},response:{id:kd.id,timestamp:new Date(kd.created_at*1e3),modelId:kd.model,headers:wd,body:Rd},providerMetadata:$d,warnings:Ed}}async doStream(lo){var $u,Ru;const{args:Iu,warnings:Pu,webSearchToolName:Ou,toolNameMapping:Mu,store:Du,providerOptionsName:Lu,isShellProviderExecuted:Bu}=await this.getArgs(lo),ju=this.config.url({path:"/responses",modelId:this.modelId}),{responseHeaders:Fu,value:zu}=await postJsonToApi({url:ju,headers:combineHeaders((Ru=($u=this.config).headers)==null?void 0:Ru.call($u),lo.headers),body:{...Iu,stream:!0},failedResponseHandler:openaiFailedResponseHandler,successfulResponseHandler:createEventSourceResponseHandler(openaiResponsesChunkSchema),abortSignal:lo.abortSignal,fetch:this.config.fetch}),Uu=await throwIfOpenAIStreamErrorBeforeOutput({stream:zu,getError:yd=>isErrorChunk(yd)||isResponseFailedChunk(yd)&&yd.response.error!=null?yd:void 0,isOutputChunk:isResponseOutputChunk,url:ju,requestBodyValues:Iu,responseHeaders:Fu}),Hu=this,Vu=extractApprovalRequestIdToToolCallIdMapping(lo.prompt),Gu=new Map;let Wu={unified:"other",raw:void 0},Ku;const Ju=[];let Yu=null;const Xu={},ed=[];let td,nd=!1;const od={};let sd,ad;const pd=[];let gd=!1;return{stream:Uu.pipeThrough(new TransformStream({start(yd){yd.enqueue({type:"stream-start",warnings:Pu})},transform(yd,bd){var Sd,Ed,cd,dd,md,ld,hd,vd,wd,kd,Rd,Od,jd,Cd,Ad,$d,qd,Dd,Ud,rh,Jd,vh,sh,Eh,bh,Qd,th,lh,Dh,Vd,Fd,Id,Pd,Wd,Nd,Kd,Xd,gh,wh,Sh,Kh;if(lo.includeRawChunks&&bd.enqueue({type:"raw",rawValue:yd.rawValue}),!yd.success){const xd=isOpenAIChatCompletionChunk(yd.rawValue)?createOpenAIResponsesChatCompletionsMismatchError({value:yd.rawValue,cause:yd.error,url:ju,requestBodyValues:Iu,responseHeaders:Fu}):yd.error;Wu={unified:"error",raw:void 0},bd.enqueue({type:"error",error:xd});return}const Md=yd.value;if(isResponseOutputItemAddedChunk(Md)){if(Md.item.type==="function_call")Xu[Md.output_index]={toolName:Md.item.name,toolCallId:Md.item.call_id},bd.enqueue({type:"tool-input-start",id:Md.item.call_id,toolName:Md.item.name});else if(Md.item.type==="custom_tool_call"){const xd=Mu.toCustomToolName(Md.item.name);Xu[Md.output_index]={toolName:xd,toolCallId:Md.item.call_id},bd.enqueue({type:"tool-input-start",id:Md.item.call_id,toolName:xd})}else if(Md.item.type==="web_search_call")Xu[Md.output_index]={toolName:Mu.toCustomToolName(Ou??"web_search"),toolCallId:Md.item.id},bd.enqueue({type:"tool-input-start",id:Md.item.id,toolName:Mu.toCustomToolName(Ou??"web_search"),providerExecuted:!0}),bd.enqueue({type:"tool-input-end",id:Md.item.id}),bd.enqueue({type:"tool-call",toolCallId:Md.item.id,toolName:Mu.toCustomToolName(Ou??"web_search"),input:JSON.stringify({}),providerExecuted:!0});else if(Md.item.type==="computer_call"){const xd=(Sd=Md.item.call_id)!=null?Sd:Md.item.id;Xu[Md.output_index]={toolName:Mu.toCustomToolName("computer"),toolCallId:xd},bd.enqueue({type:"tool-input-start",id:xd,toolName:Mu.toCustomToolName("computer")})}else if(Md.item.type==="code_interpreter_call")Xu[Md.output_index]={toolName:Mu.toCustomToolName("code_interpreter"),toolCallId:Md.item.id,codeInterpreter:{containerId:Md.item.container_id}},bd.enqueue({type:"tool-input-start",id:Md.item.id,toolName:Mu.toCustomToolName("code_interpreter"),providerExecuted:!0}),bd.enqueue({type:"tool-input-delta",id:Md.item.id,delta:`{"containerId":"${Md.item.container_id}","code":"`});else if(Md.item.type==="file_search_call")bd.enqueue({type:"tool-call",toolCallId:Md.item.id,toolName:Mu.toCustomToolName("file_search"),input:"{}",providerExecuted:!0});else if(Md.item.type==="image_generation_call")bd.enqueue({type:"tool-call",toolCallId:Md.item.id,toolName:Mu.toCustomToolName("image_generation"),input:"{}",providerExecuted:!0});else if(Md.item.type==="tool_search_call"){const xd=Md.item.id,Hd=Mu.toCustomToolName("tool_search"),Zd=Md.item.execution==="server";Xu[Md.output_index]={toolName:Hd,toolCallId:xd,toolSearchExecution:(Ed=Md.item.execution)!=null?Ed:"server"},Zd&&bd.enqueue({type:"tool-input-start",id:xd,toolName:Hd,providerExecuted:!0})}else if(Md.item.type!=="tool_search_output"){if(!(Md.item.type==="mcp_call"||Md.item.type==="mcp_list_tools"||Md.item.type==="mcp_approval_request"))if(Md.item.type==="apply_patch_call"){const{call_id:xd,operation:Hd}=Md.item;if(Xu[Md.output_index]={toolName:Mu.toCustomToolName("apply_patch"),toolCallId:xd,applyPatch:{hasDiff:Hd.type==="delete_file",endEmitted:Hd.type==="delete_file"}},bd.enqueue({type:"tool-input-start",id:xd,toolName:Mu.toCustomToolName("apply_patch")}),Hd.type==="delete_file"){const Zd=JSON.stringify({callId:xd,operation:Hd});bd.enqueue({type:"tool-input-delta",id:xd,delta:Zd}),bd.enqueue({type:"tool-input-end",id:xd})}else bd.enqueue({type:"tool-input-delta",id:xd,delta:`{"callId":"${escapeJSONDelta(xd)}","operation":{"type":"${escapeJSONDelta(Hd.type)}","path":"${escapeJSONDelta(Hd.path)}","diff":"`})}else Md.item.type==="shell_call"?Xu[Md.output_index]={toolName:Mu.toCustomToolName("shell"),toolCallId:Md.item.call_id}:Md.item.type==="shell_call_output"||(Md.item.type==="message"?(ed.splice(0,ed.length),td=(cd=Md.item.phase)!=null?cd:void 0,bd.enqueue({type:"text-start",id:Md.item.id,providerMetadata:{[Lu]:{itemId:Md.item.id,...Md.item.phase!=null&&{phase:Md.item.phase}}}})):isResponseOutputItemAddedChunk(Md)&&Md.item.type==="reasoning"&&(od[Md.item.id]={encryptedContent:Md.item.encrypted_content,summaryParts:{0:"active"}},bd.enqueue({type:"reasoning-start",id:`${Md.item.id}:0`,providerMetadata:{[Lu]:{itemId:Md.item.id,reasoningEncryptedContent:(dd=Md.item.encrypted_content)!=null?dd:null}}})))}}else if(isResponseOutputItemDoneChunk(Md))if(Md.item.type==="message"){const xd=(md=Md.item.phase)!=null?md:td;td=void 0,bd.enqueue({type:"text-end",id:Md.item.id,providerMetadata:{[Lu]:{itemId:Md.item.id,...xd!=null&&{phase:xd},...ed.length>0&&{annotations:ed}}}})}else if(Md.item.type==="function_call")Xu[Md.output_index]=void 0,nd=!0,bd.enqueue({type:"tool-input-end",id:Md.item.call_id,...Md.item.namespace!=null&&{providerMetadata:{[Lu]:{namespace:Md.item.namespace}}}}),bd.enqueue({type:"tool-call",toolCallId:Md.item.call_id,toolName:Md.item.name,input:Md.item.arguments,providerMetadata:{[Lu]:{itemId:Md.item.id,...Md.item.namespace!=null&&{namespace:Md.item.namespace},...Md.item.caller!=null&&{caller:Md.item.caller.type==="program"?{type:"program",callerId:Md.item.caller.caller_id}:Md.item.caller}}}});else if(Md.item.type==="program")bd.enqueue({type:"tool-call",toolCallId:Md.item.call_id,toolName:Mu.toCustomToolName("programmatic_tool_calling"),input:JSON.stringify({code:Md.item.code,fingerprint:Md.item.fingerprint}),providerExecuted:!0,providerMetadata:{[Lu]:{itemId:Md.item.id}}});else if(Md.item.type==="program_output")bd.enqueue({type:"tool-result",toolCallId:Md.item.call_id,toolName:Mu.toCustomToolName("programmatic_tool_calling"),result:{result:Md.item.result,status:Md.item.status},providerMetadata:{[Lu]:{itemId:Md.item.id}}});else if(Md.item.type==="custom_tool_call"){Xu[Md.output_index]=void 0,nd=!0;const xd=Mu.toCustomToolName(Md.item.name);bd.enqueue({type:"tool-input-end",id:Md.item.call_id}),bd.enqueue({type:"tool-call",toolCallId:Md.item.call_id,toolName:xd,input:JSON.stringify(Md.item.input),providerMetadata:{[Lu]:{itemId:Md.item.id}}})}else if(Md.item.type==="web_search_call")Xu[Md.output_index]=void 0,bd.enqueue({type:"tool-result",toolCallId:Md.item.id,toolName:Mu.toCustomToolName(Ou??"web_search"),result:mapWebSearchOutput(Md.item.action)});else if(Md.item.type==="computer_call"){if(Xu[Md.output_index]=void 0,Md.item.call_id==null){bd.enqueue({type:"tool-input-end",id:Md.item.id}),bd.enqueue({type:"tool-call",toolCallId:Md.item.id,toolName:Mu.toCustomToolName("computer_use"),input:"",providerExecuted:!0}),bd.enqueue({type:"tool-result",toolCallId:Md.item.id,toolName:Mu.toCustomToolName("computer_use"),result:{type:"computer_use_tool_result",status:Md.item.status}});return}nd=!0;const xd=Mu.toCustomToolName("computer"),Hd=JSON.stringify(mapComputerCallInput(Md.item));bd.enqueue({type:"tool-input-delta",id:Md.item.call_id,delta:Hd}),bd.enqueue({type:"tool-input-end",id:Md.item.call_id}),bd.enqueue({type:"tool-call",toolCallId:Md.item.call_id,toolName:xd,input:Hd,providerMetadata:{[Lu]:{itemId:Md.item.id}}})}else if(Md.item.type==="file_search_call")Xu[Md.output_index]=void 0,bd.enqueue({type:"tool-result",toolCallId:Md.item.id,toolName:Mu.toCustomToolName("file_search"),result:{queries:Md.item.queries,results:(hd=(ld=Md.item.results)==null?void 0:ld.map(xd=>({attributes:xd.attributes,fileId:xd.file_id,filename:xd.filename,score:xd.score,text:xd.text})))!=null?hd:null}});else if(Md.item.type==="code_interpreter_call")Xu[Md.output_index]=void 0,bd.enqueue({type:"tool-result",toolCallId:Md.item.id,toolName:Mu.toCustomToolName("code_interpreter"),result:{outputs:Md.item.outputs}});else if(Md.item.type==="image_generation_call")bd.enqueue({type:"tool-result",toolCallId:Md.item.id,toolName:Mu.toCustomToolName("image_generation"),result:{result:Md.item.result}});else if(Md.item.type==="tool_search_call"){const xd=Xu[Md.output_index],Hd=Md.item.execution==="server";if(xd!=null){const Zd=Hd?xd.toolCallId:(vd=Md.item.call_id)!=null?vd:Md.item.id;Hd?pd.push(Zd):bd.enqueue({type:"tool-input-start",id:Zd,toolName:xd.toolName}),bd.enqueue({type:"tool-input-end",id:Zd}),bd.enqueue({type:"tool-call",toolCallId:Zd,toolName:xd.toolName,input:JSON.stringify({arguments:Md.item.arguments,call_id:Hd?null:Zd}),...Hd?{providerExecuted:!0}:{},providerMetadata:{[Lu]:{itemId:Md.item.id}}})}Xu[Md.output_index]=void 0}else if(Md.item.type==="tool_search_output"){const xd=(kd=(wd=Md.item.call_id)!=null?wd:pd.shift())!=null?kd:Md.item.id;bd.enqueue({type:"tool-result",toolCallId:xd,toolName:Mu.toCustomToolName("tool_search"),result:{tools:Md.item.tools},providerMetadata:{[Lu]:{itemId:Md.item.id}}})}else if(Md.item.type==="mcp_call"){Xu[Md.output_index]=void 0;const xd=(Rd=Md.item.approval_request_id)!=null?Rd:void 0,Hd=xd!=null&&(jd=(Od=Gu.get(xd))!=null?Od:Vu[xd])!=null?jd:Md.item.id,Zd=`mcp.${Md.item.name}`;bd.enqueue({type:"tool-call",toolCallId:Hd,toolName:Zd,input:Md.item.arguments,providerExecuted:!0,dynamic:!0}),bd.enqueue({type:"tool-result",toolCallId:Hd,toolName:Zd,result:{type:"call",serverLabel:Md.item.server_label,name:Md.item.name,arguments:Md.item.arguments,...Md.item.output!=null?{output:Md.item.output}:{},...Md.item.error!=null?{error:Md.item.error}:{}},providerMetadata:{[Lu]:{itemId:Md.item.id}}})}else if(Md.item.type==="mcp_list_tools")Xu[Md.output_index]=void 0;else if(Md.item.type==="apply_patch_call"){const xd=Xu[Md.output_index];xd?.applyPatch&&!xd.applyPatch.endEmitted&&Md.item.operation.type!=="delete_file"&&(xd.applyPatch.hasDiff||bd.enqueue({type:"tool-input-delta",id:xd.toolCallId,delta:escapeJSONDelta(Md.item.operation.diff)}),bd.enqueue({type:"tool-input-delta",id:xd.toolCallId,delta:'"}}'}),bd.enqueue({type:"tool-input-end",id:xd.toolCallId}),xd.applyPatch.endEmitted=!0),xd&&Md.item.status==="completed"&&bd.enqueue({type:"tool-call",toolCallId:xd.toolCallId,toolName:Mu.toCustomToolName("apply_patch"),input:JSON.stringify({callId:Md.item.call_id,operation:Md.item.operation}),providerMetadata:{[Lu]:{itemId:Md.item.id}}}),Xu[Md.output_index]=void 0}else if(Md.item.type==="mcp_approval_request"){Xu[Md.output_index]=void 0;const xd=($d=(Ad=(Cd=Hu.config).generateId)==null?void 0:Ad.call(Cd))!=null?$d:generateId(),Hd=(qd=Md.item.approval_request_id)!=null?qd:Md.item.id;Gu.set(Hd,xd);const Zd=`mcp.${Md.item.name}`;bd.enqueue({type:"tool-call",toolCallId:xd,toolName:Zd,input:Md.item.arguments,providerExecuted:!0,dynamic:!0}),bd.enqueue({type:"tool-approval-request",approvalId:Hd,toolCallId:xd})}else if(Md.item.type==="local_shell_call")Xu[Md.output_index]=void 0,bd.enqueue({type:"tool-call",toolCallId:Md.item.call_id,toolName:Mu.toCustomToolName("local_shell"),input:JSON.stringify({action:{type:"exec",command:Md.item.action.command,timeoutMs:Md.item.action.timeout_ms,user:Md.item.action.user,workingDirectory:Md.item.action.working_directory,env:Md.item.action.env}}),providerMetadata:{[Lu]:{itemId:Md.item.id}}});else if(Md.item.type==="shell_call")Xu[Md.output_index]=void 0,bd.enqueue({type:"tool-call",toolCallId:Md.item.call_id,toolName:Mu.toCustomToolName("shell"),input:JSON.stringify({action:{commands:Md.item.action.commands}}),...Bu&&{providerExecuted:!0},providerMetadata:{[Lu]:{itemId:Md.item.id}}});else if(Md.item.type==="shell_call_output")bd.enqueue({type:"tool-result",toolCallId:Md.item.call_id,toolName:Mu.toCustomToolName("shell"),result:{output:Md.item.output.map(xd=>({stdout:xd.stdout,stderr:xd.stderr,outcome:xd.outcome.type==="exit"?{type:"exit",exitCode:xd.outcome.exit_code}:{type:"timeout"}}))}});else if(Md.item.type==="reasoning"){const xd=od[Md.item.id],Hd=Object.entries(xd.summaryParts).filter(([Zd,mh])=>mh==="active"||mh==="can-conclude").map(([Zd])=>Zd);for(const Zd of Hd)bd.enqueue({type:"reasoning-end",id:`${Md.item.id}:${Zd}`,providerMetadata:{[Lu]:{itemId:Md.item.id,reasoningEncryptedContent:(Dd=Md.item.encrypted_content)!=null?Dd:null}}});delete od[Md.item.id]}else Md.item.type==="compaction"&&bd.enqueue({type:"custom",kind:"openai.compaction",providerMetadata:{[Lu]:{type:"compaction",itemId:Md.item.id,encryptedContent:Md.item.encrypted_content}}});else if(isResponseFunctionCallArgumentsDeltaChunk(Md)){const xd=Xu[Md.output_index];xd!=null&&bd.enqueue({type:"tool-input-delta",id:xd.toolCallId,delta:Md.delta})}else if(isResponseCustomToolCallInputDeltaChunk(Md)){const xd=Xu[Md.output_index];xd!=null&&bd.enqueue({type:"tool-input-delta",id:xd.toolCallId,delta:Md.delta})}else if(isResponseApplyPatchCallOperationDiffDeltaChunk(Md)){const xd=Xu[Md.output_index];xd?.applyPatch&&(bd.enqueue({type:"tool-input-delta",id:xd.toolCallId,delta:escapeJSONDelta(Md.delta)}),xd.applyPatch.hasDiff=!0)}else if(isResponseApplyPatchCallOperationDiffDoneChunk(Md)){const xd=Xu[Md.output_index];xd?.applyPatch&&!xd.applyPatch.endEmitted&&(xd.applyPatch.hasDiff||(bd.enqueue({type:"tool-input-delta",id:xd.toolCallId,delta:escapeJSONDelta(Md.diff)}),xd.applyPatch.hasDiff=!0),bd.enqueue({type:"tool-input-delta",id:xd.toolCallId,delta:'"}}'}),bd.enqueue({type:"tool-input-end",id:xd.toolCallId}),xd.applyPatch.endEmitted=!0)}else if(isResponseImageGenerationCallPartialImageChunk(Md))bd.enqueue({type:"tool-result",toolCallId:Md.item_id,toolName:Mu.toCustomToolName("image_generation"),result:{result:Md.partial_image_b64},preliminary:!0});else if(isResponseCodeInterpreterCallCodeDeltaChunk(Md)){const xd=Xu[Md.output_index];xd!=null&&bd.enqueue({type:"tool-input-delta",id:xd.toolCallId,delta:escapeJSONDelta(Md.delta)})}else if(isResponseCodeInterpreterCallCodeDoneChunk(Md)){const xd=Xu[Md.output_index];xd!=null&&(bd.enqueue({type:"tool-input-delta",id:xd.toolCallId,delta:'"}'}),bd.enqueue({type:"tool-input-end",id:xd.toolCallId}),bd.enqueue({type:"tool-call",toolCallId:xd.toolCallId,toolName:Mu.toCustomToolName("code_interpreter"),input:JSON.stringify({code:Md.code,containerId:xd.codeInterpreter.containerId}),providerExecuted:!0}))}else if(isResponseCreatedChunk(Md))Yu=Md.response.id,bd.enqueue({type:"response-metadata",id:Md.response.id,timestamp:new Date(Md.response.created_at*1e3),modelId:Md.response.model});else if(isTextDeltaChunk(Md))bd.enqueue({type:"text-delta",id:Md.item_id,delta:Md.delta}),(rh=(Ud=lo.providerOptions)==null?void 0:Ud[Lu])!=null&&rh.logprobs&&Md.logprobs&&Ju.push(Md.logprobs);else if(Md.type==="response.reasoning_summary_part.added"){if(Md.summary_index>0){const xd=od[Md.item_id];xd.summaryParts[Md.summary_index]="active";for(const Hd of Object.keys(xd.summaryParts))xd.summaryParts[Hd]==="can-conclude"&&(bd.enqueue({type:"reasoning-end",id:`${Md.item_id}:${Hd}`,providerMetadata:{[Lu]:{itemId:Md.item_id}}}),xd.summaryParts[Hd]="concluded");bd.enqueue({type:"reasoning-start",id:`${Md.item_id}:${Md.summary_index}`,providerMetadata:{[Lu]:{itemId:Md.item_id,reasoningEncryptedContent:(vh=(Jd=od[Md.item_id])==null?void 0:Jd.encryptedContent)!=null?vh:null}}})}}else if(Md.type==="response.reasoning_summary_text.delta")bd.enqueue({type:"reasoning-delta",id:`${Md.item_id}:${Md.summary_index}`,delta:Md.delta,providerMetadata:{[Lu]:{itemId:Md.item_id}}});else if(Md.type==="response.reasoning_summary_part.done")Du?(bd.enqueue({type:"reasoning-end",id:`${Md.item_id}:${Md.summary_index}`,providerMetadata:{[Lu]:{itemId:Md.item_id}}}),od[Md.item_id].summaryParts[Md.summary_index]="concluded"):od[Md.item_id].summaryParts[Md.summary_index]="can-conclude";else if(isResponseFinishedChunk(Md))Wu={unified:mapOpenAIResponseFinishReason({finishReason:(sh=Md.response.incomplete_details)==null?void 0:sh.reason,hasFunctionCall:nd}),raw:(bh=(Eh=Md.response.incomplete_details)==null?void 0:Eh.reason)!=null?bh:void 0},Ku=Md.response.usage,typeof Md.response.service_tier=="string"&&(sd=Md.response.service_tier),((Qd=Md.response.reasoning)==null?void 0:Qd.context)!=null&&(ad=Md.response.reasoning.context);else if(isResponseFailedChunk(Md)){const xd=(th=Md.response.incomplete_details)==null?void 0:th.reason;Wu={unified:xd?mapOpenAIResponseFinishReason({finishReason:xd,hasFunctionCall:nd}):"error",raw:xd??"error"},Ku=(lh=Md.response.usage)!=null?lh:void 0,((Dh=Md.response.reasoning)==null?void 0:Dh.context)!=null&&(ad=Md.response.reasoning.context),!gd&&Md.response.error!=null&&(gd=!0,bd.enqueue({type:"error",error:{type:"response.failed",sequence_number:Md.sequence_number,response:{error:Md.response.error,incomplete_details:Md.response.incomplete_details,service_tier:Md.response.service_tier}}}))}else isResponseAnnotationAddedChunk(Md)?(ed.push(Md.annotation),Md.annotation.type==="url_citation"?bd.enqueue({type:"source",sourceType:"url",id:(Id=(Fd=(Vd=Hu.config).generateId)==null?void 0:Fd.call(Vd))!=null?Id:generateId(),url:Md.annotation.url,title:Md.annotation.title}):Md.annotation.type==="file_citation"?bd.enqueue({type:"source",sourceType:"document",id:(Nd=(Wd=(Pd=Hu.config).generateId)==null?void 0:Wd.call(Pd))!=null?Nd:generateId(),mediaType:"text/plain",title:Md.annotation.filename,filename:Md.annotation.filename,providerMetadata:{[Lu]:{type:Md.annotation.type,fileId:Md.annotation.file_id,index:Md.annotation.index}}}):Md.annotation.type==="container_file_citation"?bd.enqueue({type:"source",sourceType:"document",id:(gh=(Xd=(Kd=Hu.config).generateId)==null?void 0:Xd.call(Kd))!=null?gh:generateId(),mediaType:"text/plain",title:Md.annotation.filename,filename:Md.annotation.filename,providerMetadata:{[Lu]:{type:Md.annotation.type,fileId:Md.annotation.file_id,containerId:Md.annotation.container_id}}}):Md.annotation.type==="file_path"&&bd.enqueue({type:"source",sourceType:"document",id:(Kh=(Sh=(wh=Hu.config).generateId)==null?void 0:Sh.call(wh))!=null?Kh:generateId(),mediaType:"application/octet-stream",title:Md.annotation.file_id,filename:Md.annotation.file_id,providerMetadata:{[Lu]:{type:Md.annotation.type,fileId:Md.annotation.file_id,index:Md.annotation.index}}})):isErrorChunk(Md)&&(gd=!0,Wu={unified:"error",raw:"error"},bd.enqueue({type:"error",error:Md}))},flush(yd){const bd={[Lu]:{responseId:Yu,...Ju.length>0?{logprobs:Ju}:{},...sd!==void 0?{serviceTier:sd}:{},...ad!==void 0?{reasoningContext:ad}:{}}};yd.enqueue({type:"finish",finishReason:Wu,usage:convertOpenAIResponsesUsage(Ku),providerMetadata:bd})}})),request:{body:Iu},response:{headers:Fu}}}};function isTextDeltaChunk(Au){return Au.type==="response.output_text.delta"}function isOpenAIChatCompletionChunk(Au){const lo=asRecord2(Au);return lo!=null&&Array.isArray(lo.choices)&&typeof lo.type!="string"}function createOpenAIResponsesChatCompletionsMismatchError({value:Au,cause:lo,url:$u,requestBodyValues:Ru,responseHeaders:Iu}){return new APICallError({message:"Received a Chat Completions stream while using the OpenAI Responses API. The default OpenAI provider model uses the Responses API. If your custom baseURL targets a Chat Completions-compatible endpoint, use openai.chat('model-id') or createOpenAI(...).chat('model-id') instead. You can also use @ai-sdk/openai-compatible for OpenAI-compatible providers.",url:$u,requestBodyValues:Ru,responseHeaders:Iu,responseBody:JSON.stringify(Au),cause:lo,data:Au,isRetryable:!1})}function asRecord2(Au){return typeof Au=="object"&&Au!=null?Au:void 0}function isResponseOutputItemDoneChunk(Au){return Au.type==="response.output_item.done"}function isResponseFinishedChunk(Au){return Au.type==="response.completed"||Au.type==="response.incomplete"}function isResponseFailedChunk(Au){return Au.type==="response.failed"}function isResponseCreatedChunk(Au){return Au.type==="response.created"}function isResponseFunctionCallArgumentsDeltaChunk(Au){return Au.type==="response.function_call_arguments.delta"}function isResponseCustomToolCallInputDeltaChunk(Au){return Au.type==="response.custom_tool_call_input.delta"}function isResponseImageGenerationCallPartialImageChunk(Au){return Au.type==="response.image_generation_call.partial_image"}function isResponseCodeInterpreterCallCodeDeltaChunk(Au){return Au.type==="response.code_interpreter_call_code.delta"}function isResponseCodeInterpreterCallCodeDoneChunk(Au){return Au.type==="response.code_interpreter_call_code.done"}function isResponseApplyPatchCallOperationDiffDeltaChunk(Au){return Au.type==="response.apply_patch_call_operation_diff.delta"}function isResponseApplyPatchCallOperationDiffDoneChunk(Au){return Au.type==="response.apply_patch_call_operation_diff.done"}function isResponseOutputItemAddedChunk(Au){return Au.type==="response.output_item.added"}function isResponseAnnotationAddedChunk(Au){return Au.type==="response.output_text.annotation.added"}function isErrorChunk(Au){return Au.type==="error"}function isResponseOutputChunk(Au){return!(Au.type==="response.created"||Au.type==="response.failed"||Au.type==="error"||Au.type==="unknown_chunk")}function mapWebSearchOutput(Au){var lo;if(Au==null)return{};switch(Au.type){case"search":return{action:{type:"search",query:(lo=Au.query)!=null?lo:void 0,...Au.queries!=null&&{queries:Au.queries}},...Au.sources!=null&&{sources:Au.sources}};case"open_page":return{action:{type:"openPage",url:Au.url}};case"find_in_page":return{action:{type:"findInPage",url:Au.url,pattern:Au.pattern}}}}function escapeJSONDelta(Au){return JSON.stringify(Au).slice(1,-1)}var openaiSpeechModelOptionsSchema=lazySchema(()=>zodSchema(object({instructions:string$2().nullish(),speed:number$2().min(.25).max(4).default(1).nullish()}))),OpenAISpeechModel=class Gw{constructor(lo,$u){this.modelId=lo,this.config=$u,this.specificationVersion="v4"}static[WORKFLOW_SERIALIZE](lo){return serializeModelOptions({modelId:lo.modelId,config:lo.config})}static[WORKFLOW_DESERIALIZE](lo){return new Gw(lo.modelId,lo.config)}get provider(){return this.config.provider}async getArgs({text:lo,voice:$u="alloy",outputFormat:Ru="mp3",speed:Iu,instructions:Pu,language:Ou,providerOptions:Mu}){const Du=[],Lu=await parseProviderOptions({provider:"openai",providerOptions:Mu,schema:openaiSpeechModelOptionsSchema}),Bu={model:this.modelId,input:lo,voice:$u,response_format:"mp3",speed:Iu,instructions:Pu};if(Ru&&(["mp3","opus","aac","flac","wav","pcm"].includes(Ru)?Bu.response_format=Ru:Du.push({type:"unsupported",feature:"outputFormat",details:`Unsupported output format: ${Ru}. Using mp3 instead.`})),Lu){const ju={};for(const Fu in ju){const zu=ju[Fu];zu!==void 0&&(Bu[Fu]=zu)}}return Ou&&Du.push({type:"unsupported",feature:"language",details:`OpenAI speech models do not support language selection. Language parameter "${Ou}" was ignored.`}),{requestBody:Bu,warnings:Du}}async doGenerate(lo){var $u,Ru,Iu,Pu,Ou;const Mu=(Iu=(Ru=($u=this.config._internal)==null?void 0:$u.currentDate)==null?void 0:Ru.call($u))!=null?Iu:new Date,{requestBody:Du,warnings:Lu}=await this.getArgs(lo),{value:Bu,responseHeaders:ju,rawValue:Fu}=await postJsonToApi({url:this.config.url({path:"/audio/speech",modelId:this.modelId}),headers:combineHeaders((Ou=(Pu=this.config).headers)==null?void 0:Ou.call(Pu),lo.headers),body:Du,failedResponseHandler:openaiFailedResponseHandler,successfulResponseHandler:createBinaryResponseHandler(),abortSignal:lo.abortSignal,fetch:this.config.fetch});return{audio:Bu,warnings:Lu,request:{body:JSON.stringify(Du)},response:{timestamp:Mu,modelId:this.modelId,headers:ju,body:Fu}}}},openaiTranscriptionResponseSchema=lazySchema(()=>zodSchema(object({text:string$2(),language:string$2().nullish(),duration:number$2().nullish(),words:array(object({word:string$2(),start:number$2(),end:number$2()})).nullish(),segments:array(object({id:number$2(),seek:number$2(),start:number$2(),end:number$2(),text:string$2(),tokens:array(number$2()),temperature:number$2(),avg_logprob:number$2(),compression_ratio:number$2(),no_speech_prob:number$2()})).nullish()}))),openAITranscriptionModelOptions=lazySchema(()=>zodSchema(object({include:array(string$2()).optional(),language:string$2().optional(),prompt:string$2().optional(),temperature:number$2().min(0).max(1).default(0).optional(),timestampGranularities:array(_enum(["word","segment"])).default(["segment"]).optional(),streaming:object({delay:_enum(["minimal","low","medium","high","xhigh"]).optional(),include:array(string$2()).optional()}).optional()})));function isRealtimeTranscriptionModelId(Au){return Au==="gpt-realtime-whisper"||Au.startsWith("gpt-realtime-whisper-")}var languageMap={afrikaans:"af",arabic:"ar",armenian:"hy",azerbaijani:"az",belarusian:"be",bosnian:"bs",bulgarian:"bg",catalan:"ca",chinese:"zh",croatian:"hr",czech:"cs",danish:"da",dutch:"nl",english:"en",estonian:"et",finnish:"fi",french:"fr",galician:"gl",german:"de",greek:"el",hebrew:"he",hindi:"hi",hungarian:"hu",icelandic:"is",indonesian:"id",italian:"it",japanese:"ja",kannada:"kn",kazakh:"kk",korean:"ko",latvian:"lv",lithuanian:"lt",macedonian:"mk",malay:"ms",marathi:"mr",maori:"mi",nepali:"ne",norwegian:"no",persian:"fa",polish:"pl",portuguese:"pt",romanian:"ro",russian:"ru",serbian:"sr",slovak:"sk",slovenian:"sl",spanish:"es",swahili:"sw",swedish:"sv",tagalog:"tl",tamil:"ta",thai:"th",turkish:"tr",ukrainian:"uk",urdu:"ur",vietnamese:"vi",welsh:"cy"},OpenAITranscriptionModel=class Ww{constructor(lo,$u){this.modelId=lo,this.config=$u,this.specificationVersion="v4"}static[WORKFLOW_SERIALIZE](lo){return serializeModelOptions({modelId:lo.modelId,config:lo.config})}static[WORKFLOW_DESERIALIZE](lo){return new Ww(lo.modelId,lo.config)}get provider(){return this.config.provider}async getArgs({audio:lo,mediaType:$u,providerOptions:Ru}){const Iu=[],Pu=await parseProviderOptions({provider:"openai",providerOptions:Ru,schema:openAITranscriptionModelOptions}),Ou=new FormData,Mu=lo instanceof Uint8Array?new Blob([lo]):new Blob([convertBase64ToUint8Array(lo)]);Ou.append("model",this.modelId);const Du=mediaTypeToExtension($u);if(Ou.append("file",new File([Mu],"audio",{type:$u}),`audio.${Du}`),this.modelId==="whisper-1"&&Ou.append("response_format","verbose_json"),Pu){const Lu=["gpt-4o-transcribe","gpt-4o-mini-transcribe"].includes(this.modelId),Bu={include:Pu.include,language:Pu.language,prompt:Pu.prompt,...this.modelId!=="whisper-1"&&{response_format:Lu?"json":"verbose_json"},temperature:Pu.temperature,timestamp_granularities:Pu.timestampGranularities};for(const[ju,Fu]of Object.entries(Bu))if(Fu!=null)if(Array.isArray(Fu))for(const zu of Fu)Ou.append(`${ju}[]`,String(zu));else Ou.append(ju,String(Fu))}return{formData:Ou,warnings:Iu}}async doGenerate(lo){var $u,Ru,Iu,Pu,Ou,Mu,Du,Lu,Bu,ju;if(isRealtimeTranscriptionModelId(this.modelId))throw new UnsupportedFunctionalityError({functionality:`non-streaming transcription with ${this.modelId}`});const Fu=(Iu=(Ru=($u=this.config._internal)==null?void 0:$u.currentDate)==null?void 0:Ru.call($u))!=null?Iu:new Date,{formData:zu,warnings:Uu}=await this.getArgs(lo),{value:Hu,responseHeaders:Vu,rawValue:Gu}=await postFormDataToApi({url:this.config.url({path:"/audio/transcriptions",modelId:this.modelId}),headers:combineHeaders((Ou=(Pu=this.config).headers)==null?void 0:Ou.call(Pu),lo.headers),formData:zu,failedResponseHandler:openaiFailedResponseHandler,successfulResponseHandler:createJsonResponseHandler(openaiTranscriptionResponseSchema),abortSignal:lo.abortSignal,fetch:this.config.fetch}),Wu=Hu.language!=null&&Hu.language in languageMap?languageMap[Hu.language]:void 0;return{text:Hu.text,segments:(Bu=(Lu=(Mu=Hu.segments)==null?void 0:Mu.map(Ku=>({text:Ku.text,startSecond:Ku.start,endSecond:Ku.end})))!=null?Lu:(Du=Hu.words)==null?void 0:Du.map(Ku=>({text:Ku.word,startSecond:Ku.start,endSecond:Ku.end})))!=null?Bu:[],language:Wu,durationInSeconds:(ju=Hu.duration)!=null?ju:void 0,warnings:Uu,response:{timestamp:Fu,modelId:this.modelId,headers:Vu,body:Gu}}}async doStream(lo){var $u,Ru,Iu,Pu,Ou,Mu,Du;if(!isRealtimeTranscriptionModelId(this.modelId))throw new UnsupportedFunctionalityError({functionality:`streaming transcription with ${this.modelId}`});const Lu=(Iu=(Ru=($u=this.config._internal)==null?void 0:$u.currentDate)==null?void 0:Ru.call($u))!=null?Iu:new Date,Bu=await parseProviderOptions({provider:"openai",providerOptions:lo.providerOptions,schema:openAITranscriptionModelOptions}),ju=[],Fu=(Ou=(Pu=lo.providerOptions)==null?void 0:Pu.openai)!=null?Ou:{};for(const Hu of["include","prompt","temperature","timestampGranularities"])Fu[Hu]!=null&&ju.push({type:"unsupported",feature:`providerOptions.openai.${Hu}`,details:`OpenAI streaming transcription does not support ${Hu}.`});const zu=combineHeaders((Du=(Mu=this.config).headers)==null?void 0:Du.call(Mu),lo.headers),Uu=buildOpenAIRealtimeTranscriptionSession({modelId:this.modelId,inputAudioFormat:lo.inputAudioFormat,providerOptions:Bu});return{request:{body:Uu},response:{timestamp:Lu,modelId:this.modelId},stream:createOpenAIRealtimeTranscriptionStream({webSocket:this.config.webSocket,url:toWebSocketUrl(this.config.url({path:"/realtime?intent=transcription",modelId:this.modelId})),headers:zu,sessionUpdate:Uu,language:Bu?.language,warnings:ju,audio:lo.audio,abortSignal:lo.abortSignal,includeRawChunks:lo.includeRawChunks})}}};function createOpenAIRealtimeTranscriptionStream({webSocket:Au,url:lo,headers:$u,sessionUpdate:Ru,language:Iu,warnings:Pu,audio:Ou,abortSignal:Mu,includeRawChunks:Du}){let Lu=!1,Bu=()=>{};return new ReadableStream({start:ju=>{const Fu=getOpenAIRealtimeConnection($u);let zu,Uu;Bu=Wu=>{zu!=null?zu.cancel().catch(()=>{}):Ou.cancel().catch(()=>{}),Uu?.close(Wu)};const Hu=Wu=>{Lu||(Lu=!0,Bu(),ju.error(Wu))},Vu=(Wu,Ku)=>{Lu||(Lu=!0,Ku!=null&&ju.enqueue({type:"transcript-final",id:Ku,text:Wu}),ju.enqueue({type:"finish",text:Wu,segments:[],language:Iu}),ju.close(),Bu(1e3))},Gu=async Wu=>{zu=Ou.getReader();try{for(;;){const{done:Ku,value:Ju}=await zu.read();if(Ku||Lu)break;Wu.send(JSON.stringify({type:"input_audio_buffer.append",audio:convertToBase64(Ju)})),await waitForWebSocketBufferDrain(Wu)}}finally{zu.releaseLock(),zu=void 0}Lu||Wu.send(JSON.stringify({type:"input_audio_buffer.commit"}))};Uu=connectToWebSocket({url:lo,protocols:Fu.protocols,headers:Fu.headers,webSocket:Au,abortSignal:Mu,onAbort:Hu,onProcessingError:Hu,onOpen:Wu=>{ju.enqueue({type:"stream-start",warnings:Pu}),Wu.send(JSON.stringify(Ru)),Gu(Wu).catch(Hu)},onMessageText:async Wu=>{var Ku,Ju,Yu,Xu;const ed=await safeParseJSON({text:Wu});if(!ed.success)return;const td=ed.value;switch(Du&&ju.enqueue({type:"raw",rawValue:td}),td.type){case"conversation.item.input_audio_transcription.delta":{ju.enqueue({type:"transcript-delta",id:td.item_id,delta:(Ku=td.delta)!=null?Ku:""});break}case"conversation.item.input_audio_transcription.completed":{Vu((Ju=td.transcript)!=null?Ju:"",td.item_id);break}case"error":{Hu(new Error((Xu=(Yu=td.error)==null?void 0:Yu.message)!=null?Xu:"OpenAI realtime error"));break}}},onSocketError:()=>{Hu(new Error("OpenAI realtime transcription error"))},onClose:()=>{Lu||(Lu=!0,Bu(),ju.close())}})},cancel:()=>{Lu||(Lu=!0,Bu())}})}function buildOpenAIRealtimeTranscriptionSession({modelId:Au,inputAudioFormat:lo,providerOptions:$u}){var Ru,Iu;return{type:"session.update",session:{type:"transcription",audio:{input:{format:{type:lo.type,...lo.rate!=null?{rate:lo.rate}:{}},transcription:{model:Au,...$u?.language!=null?{language:$u.language}:{},...((Ru=$u?.streaming)==null?void 0:Ru.delay)!=null?{delay:$u.streaming.delay}:{}},turn_detection:null}},...((Iu=$u?.streaming)==null?void 0:Iu.include)!=null?{include:$u.streaming.include}:{}}}}function getOpenAIRealtimeConnection(Au){var lo;let $u;for(const[Iu,Pu]of Object.entries(Au))Iu.toLowerCase()==="authorization"&&Pu!=null&&($u=Pu);const Ru=(lo=$u?.match(/^bearer\s+(.+)$/i))==null?void 0:lo[1];return Ru==null?{protocols:["realtime"],headers:Au}:{protocols:["realtime",`openai-insecure-api-key.${Ru}`],headers:Object.fromEntries(Object.entries(Au).filter(([Iu])=>Iu.toLowerCase()!=="authorization"))}}var openaiSkillResponseSchema=lazySchema(()=>zodSchema(object({id:string$2(),name:string$2().nullish(),description:string$2().nullish(),default_version:string$2().nullish(),latest_version:string$2().nullish(),created_at:number$2(),updated_at:number$2().nullish()}))),OpenAISkills=class{constructor(Au){this.config=Au,this.specificationVersion="v4"}get provider(){return this.config.provider}async uploadSkill(Au){const lo=[];Au.displayTitle!=null&&lo.push({type:"unsupported",feature:"displayTitle"});const $u=new FormData;for(const Iu of Au.files){const Pu=convertInlineFileDataToUint8Array(Iu.data);$u.append("files[]",new Blob([Pu]),Iu.path)}const{value:Ru}=await postFormDataToApi({url:this.config.url({path:"/skills"}),headers:combineHeaders(this.config.headers()),formData:$u,failedResponseHandler:openaiFailedResponseHandler,successfulResponseHandler:createJsonResponseHandler(openaiSkillResponseSchema),fetch:this.config.fetch});return{providerReference:{openai:Ru.id},...Ru.name!=null?{name:Ru.name}:{},...Ru.description!=null?{description:Ru.description}:{},...Ru.latest_version!=null?{latestVersion:Ru.latest_version}:{},providerMetadata:{openai:{...Ru.default_version!=null?{defaultVersion:Ru.default_version}:{},...Ru.created_at!=null?{createdAt:Ru.created_at}:{},...Ru.updated_at!=null?{updatedAt:Ru.updated_at}:{}}},warnings:lo}}},VERSION$1="4.0.20";function createOpenAI(Au={}){var lo,$u;const Ru=(lo=withoutTrailingSlash(validateBaseURL(loadOptionalSetting({settingValue:Au.baseURL,environmentVariableName:"OPENAI_BASE_URL"}))))!=null?lo:"https://api.openai.com/v1",Iu=($u=Au.name)!=null?$u:"openai",Pu=()=>withUserAgentSuffix({Authorization:`Bearer ${loadApiKey({apiKey:Au.apiKey,environmentVariableName:"OPENAI_API_KEY",description:"OpenAI"})}`,"OpenAI-Organization":Au.organization,"OpenAI-Project":Au.project,...Au.headers},`ai-sdk/openai/${VERSION$1}`),Ou=Ku=>new OpenAIChatLanguageModel(Ku,{provider:`${Iu}.chat`,url:({path:Ju})=>`${Ru}${Ju}`,headers:Pu,fetch:Au.fetch}),Mu=Ku=>new OpenAICompletionLanguageModel(Ku,{provider:`${Iu}.completion`,url:({path:Ju})=>`${Ru}${Ju}`,headers:Pu,fetch:Au.fetch}),Du=Ku=>new OpenAIEmbeddingModel(Ku,{provider:`${Iu}.embedding`,url:({path:Ju})=>`${Ru}${Ju}`,headers:Pu,fetch:Au.fetch}),Lu=Ku=>new OpenAIImageModel(Ku,{provider:`${Iu}.image`,url:({path:Ju})=>`${Ru}${Ju}`,headers:Pu,fetch:Au.fetch}),Bu=Ku=>new OpenAITranscriptionModel(Ku,{provider:`${Iu}.transcription`,url:({path:Ju})=>`${Ru}${Ju}`,headers:Pu,fetch:Au.fetch,webSocket:Au.webSocket}),ju=Ku=>new OpenAISpeechModel(Ku,{provider:`${Iu}.speech`,url:({path:Ju})=>`${Ru}${Ju}`,headers:Pu,fetch:Au.fetch}),Fu=()=>new OpenAIFiles({provider:`${Iu}.files`,baseURL:Ru,headers:Pu,fetch:Au.fetch}),zu=()=>new OpenAISkills({provider:`${Iu}.skills`,url:({path:Ku})=>`${Ru}${Ku}`,headers:Pu,fetch:Au.fetch}),Uu=Ku=>{if(new.target)throw new Error("The OpenAI model function cannot be called with the new keyword.");return Hu(Ku)},Hu=Ku=>new OpenAIResponsesLanguageModel(Ku,{provider:`${Iu}.responses`,url:({path:Ju})=>`${Ru}${Ju}`,headers:Pu,fetch:Au.fetch,fileIdPrefixes:["file-"]}),Vu=Ku=>new OpenAIRealtimeModel(Ku,{provider:`${Iu}.realtime`,baseURL:Ru,headers:Pu,fetch:Au.fetch}),Gu=Object.assign(Ku=>Vu(Ku),{getToken:async Ku=>{const Yu=await Vu(Ku.model).doCreateClientSecret({sessionConfig:Ku.sessionConfig,expiresAfterSeconds:Ku.expiresAfterSeconds});return{token:Yu.token,url:Yu.url,expiresAt:Yu.expiresAt}}}),Wu=function(Ku){return Uu(Ku)};return Wu.specificationVersion="v4",Wu.languageModel=Uu,Wu.chat=Ou,Wu.completion=Mu,Wu.responses=Hu,Wu.embedding=Du,Wu.embeddingModel=Du,Wu.textEmbedding=Du,Wu.textEmbeddingModel=Du,Wu.image=Lu,Wu.imageModel=Lu,Wu.transcription=Bu,Wu.transcriptionModel=Bu,Wu.speech=ju,Wu.speechModel=ju,Wu.files=Fu,Wu.skills=zu,Wu.experimental_realtime=Gu,Wu.tools=openaiTools,Wu}createOpenAI();const INFERENCE_API_PATH="/api/ai-inference/v1",DEFAULT_BROWSER_MODEL="bedrock:us.anthropic.claude-sonnet-4-6";function browserModelRequiresSignIn(Au){return!Au.token?.trim()}function inferenceApiUrl(Au){const lo=Au.replace(/\/+$/,"");return lo.endsWith(INFERENCE_API_PATH)?lo:`${lo}${INFERENCE_API_PATH}`}function describingFetch(Au,lo){return async($u,Ru)=>{try{return await Au($u,Ru)}catch(Iu){throw new Error(`Could not reach the inference service at ${lo}. Check that this is the right host — the service runs with the control plane, not the runtimes plane — and that it allows this origin. (${Iu instanceof Error?Iu.message:String(Iu)})`,{cause:Iu})}}}function createBrowserModel(Au){const lo=inferenceApiUrl(Au.inferenceUrl);return createOpenAI({name:"datalayer-ai-inference",baseURL:lo,apiKey:Au.token?.trim()||"anonymous",headers:Au.headers,fetch:describingFetch(Au.fetch??globalThis.fetch,lo)}).chat(Au.model||DEFAULT_BROWSER_MODEL)}const DEFAULT_BROWSER_MAX_STEPS=24,DEFAULT_TTL_MS=3e5,RETRY_MS=3e3;let pendingTimer;function readJwtClaims(Au){const lo=Au.split(".")[1];if(lo)try{const $u=lo.replace(/-/g,"+").replace(/_/g,"/"),Ru=$u.padEnd($u.length+(4-$u.length%4)%4,"="),Iu=JSON.parse(atob(Ru));return Iu&&typeof Iu=="object"?Iu:void 0}catch{return}}function tokenLifetimeMs(Au,lo){const $u=readJwtClaims(Au);return $u?.exp&&$u?.iat&&$u.exp>$u.iat?($u.exp-$u.iat)*1e3:lo&&lo>0?lo*1e3:DEFAULT_TTL_MS}async function fetchAnonymousToken(Au,lo){const $u=Au.replace(/\/+$/,""),Ru=await fetch(`${$u}/api/ai-inference/v1/anonymous/token`,{method:"POST",headers:{"Content-Type":"application/json"},signal:lo});if(!Ru.ok)throw new Error(`Anonymous inference token refused by ${$u} (HTTP ${Ru.status})`);const Iu=await Ru.json();if(!Iu.token)throw new Error(`No token in the reply from ${$u}`);const Pu=tokenLifetimeMs(Iu.token,Iu.expires_in);return{token:Iu.token,lifetimeMs:Pu,expiresAt:Date.now()+Pu}}const useAnonymousSessionStore=create$g((Au,lo)=>{const $u=Ru=>{Au({status:"minting",error:void 0}),fetchAnonymousToken(Ru).then(Iu=>{lo().status==="minting"&&(Au({status:"active",token:Iu.token,expiresAt:Iu.expiresAt,grantedMs:Iu.lifetimeMs,error:void 0}),clearTimeout(pendingTimer),pendingTimer=setTimeout(()=>lo().expire(),Math.max(0,Iu.expiresAt-Date.now())))}).catch(Iu=>{if(lo().status!=="minting")return;const Pu=Iu instanceof Error?Iu.message:String(Iu);console.warn("[anonymousToken] could not mint a token",Iu);const Ou=!lo().retried;Au({status:"failed",error:Pu,retried:!0}),Ou&&(clearTimeout(pendingTimer),pendingTimer=setTimeout(()=>{lo().status==="failed"&&$u(Ru)},RETRY_MS))})};return{status:"idle",start:Ru=>{const{status:Iu}=lo();Iu==="idle"&&Ru&&$u(Ru)},expire:()=>{const{status:Ru}=lo();Ru==="idle"||Ru==="expired"||(clearTimeout(pendingTimer),pendingTimer=void 0,Au({status:"expired",token:void 0}))},clear:()=>{lo().status!=="idle"&&(clearTimeout(pendingTimer),pendingTimer=void 0,Au({status:"idle",token:void 0,expiresAt:void 0,grantedMs:void 0,error:void 0,retried:!1}))}}});function useAnonymousSession(){return useAnonymousSessionStore()}function useAnonymousInferenceSession(Au,lo){const $u=useAnonymousSession();return reactExports.useEffect(()=>{const{start:Ru,clear:Iu}=useAnonymousSessionStore.getState();if(lo&&Au){Ru(Au);return}Iu()},[Au,lo]),$u}const SUBAGENT_STOPPED="Stopped.",isObject$2=Au=>!!Au&&typeof Au=="object";function parseAgentStreamMessage(Au){return isObject$2(Au)?typeof Au.type=="string"&&isObject$2(Au.payload)?{version:typeof Au.version=="string"?Au.version:"1.0",type:Au.type,agentId:typeof Au.agentId=="string"?Au.agentId:void 0,timestamp:typeof Au.timestamp=="string"?Au.timestamp:new Date().toISOString(),payload:Au.payload,event:typeof Au.event=="string"?Au.event:void 0,data:Au.data}:typeof Au.event=="string"&&isObject$2(Au.data)?{version:"1.0",type:Au.event,timestamp:new Date().toISOString(),payload:Au.data,event:Au.event,data:Au.data}:null:null}const DEFAULT_SUBAGENT_MAX_STEPS=12,TASK_SCHEMA={type:"object",properties:{task:{type:"string",description:"What to do, stated so that it can be carried out without the rest of this conversation."}},required:["task"]};function subagentTools(Au){const{subagents:lo,inference:$u,model:Ru,sharing:Iu="shared",maxSteps:Pu=DEFAULT_SUBAGENT_MAX_STEPS,tools:Ou,onEvent:Mu,signal:Du}=Au,Lu={};for(const Bu of lo)Lu[Bu.name]={description:Bu.description,inputSchema:jsonSchema$1(TASK_SCHEMA),execute:async(ju,Fu)=>{const{task:zu}=ju??{};if(!zu?.trim())return{error:"A delegated task needs to say what to do."};const Uu=Fu?.toolCallId??null;let Hu=!1;const Vu=Ku=>{if(Ku.phase==="end"||Ku.phase==="error"){if(Hu)return;Hu=!0}Mu?.({subagentName:Bu.name,toolCallId:Uu,...Ku})},Gu=new ToolLoopAgent({id:Bu.name,model:createBrowserModel({...$u,model:Bu.model??Ru}),instructions:Bu.instructions,tools:Bu.tools??Ou??{},stopWhen:isStepCount(Pu)}),Wu=anySignal([Fu?.abortSignal,Du?.()]);Vu({phase:"start",task:zu});try{const Ku=Iu==="shared"?Fu?.messages??[]:[],Ju=await Gu.stream({messages:[...Ku,{role:"user",content:zu}],abortSignal:Wu}),Yu=await relaySubagentRun(Ju.fullStream,Vu,Wu);if(Wu?.aborted)return Vu({phase:"error",error:STOPPED}),{agent:Bu.name,error:STOPPED};const Xu=Yu||await Ju.text;return Vu({phase:"end",output:Xu}),{agent:Bu.name,result:Xu}}catch(Ku){const Ju=Wu?.aborted?STOPPED:Ku instanceof Error?Ku.message:String(Ku);return Vu({phase:"error",error:Ju}),{agent:Bu.name,error:Ju}}},toModelOutput:({output:ju})=>{const Fu=ju;return{type:"text",value:Fu?.error?`${Bu.name} could not finish: ${Fu.error}`:Fu?.result??"Done."}}};return Lu}const STOPPED=SUBAGENT_STOPPED;function anySignal(Au){const lo=Au.filter(Ru=>!!Ru);if(lo.length<=1)return lo[0];if(typeof AbortSignal.any=="function")return AbortSignal.any(lo);const $u=new AbortController;for(const Ru of lo){if(Ru.aborted){$u.abort(Ru.reason);break}Ru.addEventListener("abort",()=>$u.abort(Ru.reason),{once:!0})}return $u.signal}function preview(Au){const lo=typeof Au=="string"?Au:JSON.stringify(Au);return lo.length>400?`${lo.slice(0,400)}…`:lo}async function relaySubagentRun(Au,lo,$u){let Ru="";for await(const Iu of Au){if($u?.aborted)break;switch(Iu.type){case"text-delta":Ru+=Iu.text??"",lo({phase:"text",text:Iu.text??""});break;case"reasoning-delta":lo({phase:"thinking",text:Iu.text??""});break;case"tool-call":lo({phase:"tool_call",toolName:Iu.toolName,toolArgs:Iu.input??{}});break;case"tool-result":lo({phase:"tool_result",toolName:Iu.toolName,result:preview(Iu.output)});break;case"tool-error":lo({phase:"tool_result",toolName:Iu.toolName,result:preview(Iu.error)});break;case"error":lo({phase:"error",error:Iu.error instanceof Error?Iu.error.message:String(Iu.error)});break}}return Ru}function messageText$2(Au){return typeof Au.content=="string"?Au.content:Au.content.map(lo=>typeof lo=="string"?lo:lo.text??"").join("")}function isModelRole(Au){return Au==="user"||Au==="assistant"||Au==="system"}class BrowserAgentAdapter extends BaseProtocolAdapter{protocol="browser-vercel-ai";protocolTransport="http";browserConfig;abortController=null;tools;constructor(lo){super(lo),this.browserConfig=lo;const $u=frontendToolsToVercelAI(lo.frontendTools??[],{onHitlRequired:lo.onHitlRequired,onStatusChange:lo.onStatusChange});this.tools={...$u,...lo.subagents?.length&&lo.inference?subagentTools({subagents:lo.subagents,inference:lo.inference,model:lo.model,sharing:lo.sharing,tools:$u,onEvent:lo.onSubagentEvent,signal:()=>this.abortController?.signal}):{}}}async connect(){this.setConnectionState("connected")}disconnect(){this.abortController?.abort(),this.abortController=null,this.setConnectionState("disconnected")}stopGeneration(){this.abortController?.abort()}supportsFeature(lo){return lo==="tools"}async sendToolResult(){}resolveModel(lo){const{languageModel:$u,inference:Ru,model:Iu}=this.browserConfig;if($u)return $u;if(!Ru)throw new Error("A browser agent needs either a `languageModel` or an `inference` endpoint to reach one.");return createBrowserModel({...Ru,model:lo||Iu})}runModes(lo){const $u=lo?.loop,Ru=$u?.modes??{},Iu=$u?.profile||void 0;if(Object.keys(Ru).length===0&&!Iu)return;const{modeEffect:Pu,languageModel:Ou}=this.browserConfig;if(!Pu)throw new Error("This agent has no modes or profiles: what was chosen in the composer cannot be applied to it.");const Mu=Pu(Ru,Iu);if(Mu.model&&Ou)throw new Error(`The mode or profile chosen runs on ${Mu.model}, and this agent's model is its host's own: it cannot run on another.`);return Mu}async sendMessage(lo,$u){this.abortController?.abort();const Ru=new AbortController;this.abortController=Ru;const Iu=($u?.messages??[]).filter(Bu=>isModelRole(Bu.role)).map(Bu=>({role:Bu.role,content:messageText$2(Bu)})).filter(Bu=>Bu.content.length>0),Pu=messageText$2(lo);Pu&&Iu[Iu.length-1]?.content!==Pu&&Iu.push({role:"user",content:Pu});let Ou=null,Mu="";const Du=()=>{Ou=generateMessageId(),Mu=""},Lu=()=>{const Bu=createAssistantMessage(Mu);Bu.id=Ou,this.emit({type:"message",message:Bu,timestamp:new Date})};try{const Bu=this.runModes($u?.forwardedProps),{instructions:ju}=this.browserConfig,Fu=Bu?.instructions?[ju?.trim(),Bu.instructions].filter(Boolean).join(`
|
|
2193
2193
|
|
|
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",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)}}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}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(yd,bd,Sd){yd[bd]=Sd.value},Pu=typeof Symbol=="function"?Symbol:{},Ou=Pu.iterator||"@@iterator",Mu=Pu.asyncIterator||"@@asyncIterator",Du=Pu.toStringTag||"@@toStringTag";function Lu(yd,bd,Sd){return Object.defineProperty(yd,bd,{value:Sd,enumerable:!0,configurable:!0,writable:!0}),yd[bd]}try{Lu({},"")}catch{Lu=function(Sd,Ed,cd){return Sd[Ed]=cd}}function Bu(yd,bd,Sd,Ed){var cd=bd&&bd.prototype instanceof Gu?bd:Gu,dd=Object.create(cd.prototype),md=new gd(Ed||[]);return Iu(dd,"_invoke",{value:od(yd,Sd,md)}),dd}function ju(yd,bd,Sd){try{return{type:"normal",arg:yd.call(bd,Sd)}}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(_d([])));Xu&&Xu!==$u&&Ru.call(Xu,Ou)&&(Ju=Xu);var ed=Ku.prototype=Gu.prototype=Object.create(Ju);function td(yd){["next","throw","return"].forEach(function(bd){Lu(yd,bd,function(Sd){return this._invoke(bd,Sd)})})}function nd(yd,bd){function Sd(cd,dd,md,ld){var hd=ju(yd[cd],yd,dd);if(hd.type!=="throw"){var vd=hd.arg,wd=vd.value;return wd&&_typeof$6(wd)=="object"&&Ru.call(wd,"__await")?bd.resolve(wd.__await).then(function(kd){Sd("next",kd,md,ld)},function(kd){Sd("throw",kd,md,ld)}):bd.resolve(wd).then(function(kd){vd.value=kd,md(vd)},function(kd){return Sd("throw",kd,md,ld)})}ld(hd.arg)}var Ed;Iu(this,"_invoke",{value:function(dd,md){function ld(){return new bd(function(hd,vd){Sd(dd,md,hd,vd)})}return Ed=Ed?Ed.then(ld,ld):ld()}})}function od(yd,bd,Sd){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(Sd.method=cd,Sd.arg=dd;;){var md=Sd.delegate;if(md){var ld=sd(md,Sd);if(ld){if(ld===Vu)continue;return ld}}if(Sd.method==="next")Sd.sent=Sd._sent=Sd.arg;else if(Sd.method==="throw"){if(Ed===Fu)throw Ed=Hu,Sd.arg;Sd.dispatchException(Sd.arg)}else Sd.method==="return"&&Sd.abrupt("return",Sd.arg);Ed=Uu;var hd=ju(yd,bd,Sd);if(hd.type==="normal"){if(Ed=Sd.done?Hu:zu,hd.arg===Vu)continue;return{value:hd.arg,done:Sd.done}}hd.type==="throw"&&(Ed=Hu,Sd.method="throw",Sd.arg=hd.arg)}}}function sd(yd,bd){var Sd=bd.method,Ed=yd.iterator[Sd];if(Ed===Au)return bd.delegate=null,Sd==="throw"&&yd.iterator.return&&(bd.method="return",bd.arg=Au,sd(yd,bd),bd.method==="throw")||Sd!=="return"&&(bd.method="throw",bd.arg=new TypeError("The iterator does not provide a '"+Sd+"' method")),Vu;var cd=ju(Ed,yd.iterator,bd.arg);if(cd.type==="throw")return bd.method="throw",bd.arg=cd.arg,bd.delegate=null,Vu;var dd=cd.arg;return dd?dd.done?(bd[yd.resultName]=dd.value,bd.next=yd.nextLoc,bd.method!=="return"&&(bd.method="next",bd.arg=Au),bd.delegate=null,Vu):dd:(bd.method="throw",bd.arg=new TypeError("iterator result is not an object"),bd.delegate=null,Vu)}function ad(yd){var bd={tryLoc:yd[0]};1 in yd&&(bd.catchLoc=yd[1]),2 in yd&&(bd.finallyLoc=yd[2],bd.afterLoc=yd[3]),this.tryEntries.push(bd)}function pd(yd){var bd=yd.completion||{};bd.type="normal",delete bd.arg,yd.completion=bd}function gd(yd){this.tryEntries=[{tryLoc:"root"}],yd.forEach(ad,this),this.reset(!0)}function _d(yd){if(yd||yd===""){var bd=yd[Ou];if(bd)return bd.call(yd);if(typeof yd.next=="function")return yd;if(!isNaN(yd.length)){var Sd=-1,Ed=function cd(){for(;++Sd<yd.length;)if(Ru.call(yd,Sd))return cd.value=yd[Sd],cd.done=!1,cd;return cd.value=Au,cd.done=!0,cd};return Ed.next=Ed}}throw new TypeError(_typeof$6(yd)+" 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(yd){var bd=typeof yd=="function"&&yd.constructor;return!!bd&&(bd===Wu||(bd.displayName||bd.name)==="GeneratorFunction")},lo.mark=function(yd){return Object.setPrototypeOf?Object.setPrototypeOf(yd,Ku):(yd.__proto__=Ku,Lu(yd,Du,"GeneratorFunction")),yd.prototype=Object.create(ed),yd},lo.awrap=function(yd){return{__await:yd}},td(nd.prototype),Lu(nd.prototype,Mu,function(){return this}),lo.AsyncIterator=nd,lo.async=function(yd,bd,Sd,Ed,cd){cd===void 0&&(cd=Promise);var dd=new nd(Bu(yd,bd,Sd,Ed),cd);return lo.isGeneratorFunction(bd)?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(yd){var bd=Object(yd),Sd=[];for(var Ed in bd)Sd.push(Ed);return Sd.reverse(),function cd(){for(;Sd.length;){var dd=Sd.pop();if(dd in bd)return cd.value=dd,cd.done=!1,cd}return cd.done=!0,cd}},lo.values=_d,gd.prototype={constructor:gd,reset:function(bd){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),!bd)for(var Sd in this)Sd.charAt(0)==="t"&&Ru.call(this,Sd)&&!isNaN(+Sd.slice(1))&&(this[Sd]=Au)},stop:function(){this.done=!0;var bd=this.tryEntries[0].completion;if(bd.type==="throw")throw bd.arg;return this.rval},dispatchException:function(bd){if(this.done)throw bd;var Sd=this;function Ed(vd,wd){return md.type="throw",md.arg=bd,Sd.next=vd,wd&&(Sd.method="next",Sd.arg=Au),!!wd}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(bd,Sd){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&&(bd==="break"||bd==="continue")&&dd.tryLoc<=Sd&&Sd<=dd.finallyLoc&&(dd=null);var md=dd?dd.completion:{};return md.type=bd,md.arg=Sd,dd?(this.method="next",this.next=dd.finallyLoc,Vu):this.complete(md)},complete:function(bd,Sd){if(bd.type==="throw")throw bd.arg;return bd.type==="break"||bd.type==="continue"?this.next=bd.arg:bd.type==="return"?(this.rval=this.arg=bd.arg,this.method="return",this.next="end"):bd.type==="normal"&&Sd&&(this.next=Sd),Vu},finish:function(bd){for(var Sd=this.tryEntries.length-1;Sd>=0;--Sd){var Ed=this.tryEntries[Sd];if(Ed.finallyLoc===bd)return this.complete(Ed.completion,Ed.afterLoc),pd(Ed),Vu}},catch:function(bd){for(var Sd=this.tryEntries.length-1;Sd>=0;--Sd){var Ed=this.tryEntries[Sd];if(Ed.tryLoc===bd){var cd=Ed.completion;if(cd.type==="throw"){var dd=cd.arg;pd(Ed)}return dd}}throw Error("illegal catch attempt")},delegateYield:function(bd,Sd,Ed){return this.delegate={iterator:_d(bd),resultName:Sd,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.
|
|
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
|
+
`).length-(Au.endsWith(`
|
|
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(yd,bd,Sd){yd[bd]=Sd.value},Pu=typeof Symbol=="function"?Symbol:{},Ou=Pu.iterator||"@@iterator",Mu=Pu.asyncIterator||"@@asyncIterator",Du=Pu.toStringTag||"@@toStringTag";function Lu(yd,bd,Sd){return Object.defineProperty(yd,bd,{value:Sd,enumerable:!0,configurable:!0,writable:!0}),yd[bd]}try{Lu({},"")}catch{Lu=function(Sd,Ed,cd){return Sd[Ed]=cd}}function Bu(yd,bd,Sd,Ed){var cd=bd&&bd.prototype instanceof Gu?bd:Gu,dd=Object.create(cd.prototype),md=new gd(Ed||[]);return Iu(dd,"_invoke",{value:od(yd,Sd,md)}),dd}function ju(yd,bd,Sd){try{return{type:"normal",arg:yd.call(bd,Sd)}}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(_d([])));Xu&&Xu!==$u&&Ru.call(Xu,Ou)&&(Ju=Xu);var ed=Ku.prototype=Gu.prototype=Object.create(Ju);function td(yd){["next","throw","return"].forEach(function(bd){Lu(yd,bd,function(Sd){return this._invoke(bd,Sd)})})}function nd(yd,bd){function Sd(cd,dd,md,ld){var hd=ju(yd[cd],yd,dd);if(hd.type!=="throw"){var vd=hd.arg,wd=vd.value;return wd&&_typeof$6(wd)=="object"&&Ru.call(wd,"__await")?bd.resolve(wd.__await).then(function(kd){Sd("next",kd,md,ld)},function(kd){Sd("throw",kd,md,ld)}):bd.resolve(wd).then(function(kd){vd.value=kd,md(vd)},function(kd){return Sd("throw",kd,md,ld)})}ld(hd.arg)}var Ed;Iu(this,"_invoke",{value:function(dd,md){function ld(){return new bd(function(hd,vd){Sd(dd,md,hd,vd)})}return Ed=Ed?Ed.then(ld,ld):ld()}})}function od(yd,bd,Sd){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(Sd.method=cd,Sd.arg=dd;;){var md=Sd.delegate;if(md){var ld=sd(md,Sd);if(ld){if(ld===Vu)continue;return ld}}if(Sd.method==="next")Sd.sent=Sd._sent=Sd.arg;else if(Sd.method==="throw"){if(Ed===Fu)throw Ed=Hu,Sd.arg;Sd.dispatchException(Sd.arg)}else Sd.method==="return"&&Sd.abrupt("return",Sd.arg);Ed=Uu;var hd=ju(yd,bd,Sd);if(hd.type==="normal"){if(Ed=Sd.done?Hu:zu,hd.arg===Vu)continue;return{value:hd.arg,done:Sd.done}}hd.type==="throw"&&(Ed=Hu,Sd.method="throw",Sd.arg=hd.arg)}}}function sd(yd,bd){var Sd=bd.method,Ed=yd.iterator[Sd];if(Ed===Au)return bd.delegate=null,Sd==="throw"&&yd.iterator.return&&(bd.method="return",bd.arg=Au,sd(yd,bd),bd.method==="throw")||Sd!=="return"&&(bd.method="throw",bd.arg=new TypeError("The iterator does not provide a '"+Sd+"' method")),Vu;var cd=ju(Ed,yd.iterator,bd.arg);if(cd.type==="throw")return bd.method="throw",bd.arg=cd.arg,bd.delegate=null,Vu;var dd=cd.arg;return dd?dd.done?(bd[yd.resultName]=dd.value,bd.next=yd.nextLoc,bd.method!=="return"&&(bd.method="next",bd.arg=Au),bd.delegate=null,Vu):dd:(bd.method="throw",bd.arg=new TypeError("iterator result is not an object"),bd.delegate=null,Vu)}function ad(yd){var bd={tryLoc:yd[0]};1 in yd&&(bd.catchLoc=yd[1]),2 in yd&&(bd.finallyLoc=yd[2],bd.afterLoc=yd[3]),this.tryEntries.push(bd)}function pd(yd){var bd=yd.completion||{};bd.type="normal",delete bd.arg,yd.completion=bd}function gd(yd){this.tryEntries=[{tryLoc:"root"}],yd.forEach(ad,this),this.reset(!0)}function _d(yd){if(yd||yd===""){var bd=yd[Ou];if(bd)return bd.call(yd);if(typeof yd.next=="function")return yd;if(!isNaN(yd.length)){var Sd=-1,Ed=function cd(){for(;++Sd<yd.length;)if(Ru.call(yd,Sd))return cd.value=yd[Sd],cd.done=!1,cd;return cd.value=Au,cd.done=!0,cd};return Ed.next=Ed}}throw new TypeError(_typeof$6(yd)+" 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(yd){var bd=typeof yd=="function"&&yd.constructor;return!!bd&&(bd===Wu||(bd.displayName||bd.name)==="GeneratorFunction")},lo.mark=function(yd){return Object.setPrototypeOf?Object.setPrototypeOf(yd,Ku):(yd.__proto__=Ku,Lu(yd,Du,"GeneratorFunction")),yd.prototype=Object.create(ed),yd},lo.awrap=function(yd){return{__await:yd}},td(nd.prototype),Lu(nd.prototype,Mu,function(){return this}),lo.AsyncIterator=nd,lo.async=function(yd,bd,Sd,Ed,cd){cd===void 0&&(cd=Promise);var dd=new nd(Bu(yd,bd,Sd,Ed),cd);return lo.isGeneratorFunction(bd)?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(yd){var bd=Object(yd),Sd=[];for(var Ed in bd)Sd.push(Ed);return Sd.reverse(),function cd(){for(;Sd.length;){var dd=Sd.pop();if(dd in bd)return cd.value=dd,cd.done=!1,cd}return cd.done=!0,cd}},lo.values=_d,gd.prototype={constructor:gd,reset:function(bd){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),!bd)for(var Sd in this)Sd.charAt(0)==="t"&&Ru.call(this,Sd)&&!isNaN(+Sd.slice(1))&&(this[Sd]=Au)},stop:function(){this.done=!0;var bd=this.tryEntries[0].completion;if(bd.type==="throw")throw bd.arg;return this.rval},dispatchException:function(bd){if(this.done)throw bd;var Sd=this;function Ed(vd,wd){return md.type="throw",md.arg=bd,Sd.next=vd,wd&&(Sd.method="next",Sd.arg=Au),!!wd}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(bd,Sd){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&&(bd==="break"||bd==="continue")&&dd.tryLoc<=Sd&&Sd<=dd.finallyLoc&&(dd=null);var md=dd?dd.completion:{};return md.type=bd,md.arg=Sd,dd?(this.method="next",this.next=dd.finallyLoc,Vu):this.complete(md)},complete:function(bd,Sd){if(bd.type==="throw")throw bd.arg;return bd.type==="break"||bd.type==="continue"?this.next=bd.arg:bd.type==="return"?(this.rval=this.arg=bd.arg,this.method="return",this.next="end"):bd.type==="normal"&&Sd&&(this.next=Sd),Vu},finish:function(bd){for(var Sd=this.tryEntries.length-1;Sd>=0;--Sd){var Ed=this.tryEntries[Sd];if(Ed.finallyLoc===bd)return this.complete(Ed.completion,Ed.afterLoc),pd(Ed),Vu}},catch:function(bd){for(var Sd=this.tryEntries.length-1;Sd>=0;--Sd){var Ed=this.tryEntries[Sd];if(Ed.tryLoc===bd){var cd=Ed.completion;if(cd.type==="throw"){var dd=cd.arg;pd(Ed)}return dd}}throw Error("illegal catch attempt")},delegateYield:function(bd,Sd,Ed){return this.delegate={iterator:_d(bd),resultName:Sd,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.
|
|
2195
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.
|
|
2196
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(yd,bd,Sd){yd[bd]=Sd.value},Pu=typeof Symbol=="function"?Symbol:{},Ou=Pu.iterator||"@@iterator",Mu=Pu.asyncIterator||"@@asyncIterator",Du=Pu.toStringTag||"@@toStringTag";function Lu(yd,bd,Sd){return Object.defineProperty(yd,bd,{value:Sd,enumerable:!0,configurable:!0,writable:!0}),yd[bd]}try{Lu({},"")}catch{Lu=function(Sd,Ed,cd){return Sd[Ed]=cd}}function Bu(yd,bd,Sd,Ed){var cd=bd&&bd.prototype instanceof Gu?bd:Gu,dd=Object.create(cd.prototype),md=new gd(Ed||[]);return Iu(dd,"_invoke",{value:od(yd,Sd,md)}),dd}function ju(yd,bd,Sd){try{return{type:"normal",arg:yd.call(bd,Sd)}}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(_d([])));Xu&&Xu!==$u&&Ru.call(Xu,Ou)&&(Ju=Xu);var ed=Ku.prototype=Gu.prototype=Object.create(Ju);function td(yd){["next","throw","return"].forEach(function(bd){Lu(yd,bd,function(Sd){return this._invoke(bd,Sd)})})}function nd(yd,bd){function Sd(cd,dd,md,ld){var hd=ju(yd[cd],yd,dd);if(hd.type!=="throw"){var vd=hd.arg,wd=vd.value;return wd&&_typeof$3(wd)=="object"&&Ru.call(wd,"__await")?bd.resolve(wd.__await).then(function(kd){Sd("next",kd,md,ld)},function(kd){Sd("throw",kd,md,ld)}):bd.resolve(wd).then(function(kd){vd.value=kd,md(vd)},function(kd){return Sd("throw",kd,md,ld)})}ld(hd.arg)}var Ed;Iu(this,"_invoke",{value:function(dd,md){function ld(){return new bd(function(hd,vd){Sd(dd,md,hd,vd)})}return Ed=Ed?Ed.then(ld,ld):ld()}})}function od(yd,bd,Sd){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(Sd.method=cd,Sd.arg=dd;;){var md=Sd.delegate;if(md){var ld=sd(md,Sd);if(ld){if(ld===Vu)continue;return ld}}if(Sd.method==="next")Sd.sent=Sd._sent=Sd.arg;else if(Sd.method==="throw"){if(Ed===Fu)throw Ed=Hu,Sd.arg;Sd.dispatchException(Sd.arg)}else Sd.method==="return"&&Sd.abrupt("return",Sd.arg);Ed=Uu;var hd=ju(yd,bd,Sd);if(hd.type==="normal"){if(Ed=Sd.done?Hu:zu,hd.arg===Vu)continue;return{value:hd.arg,done:Sd.done}}hd.type==="throw"&&(Ed=Hu,Sd.method="throw",Sd.arg=hd.arg)}}}function sd(yd,bd){var Sd=bd.method,Ed=yd.iterator[Sd];if(Ed===Au)return bd.delegate=null,Sd==="throw"&&yd.iterator.return&&(bd.method="return",bd.arg=Au,sd(yd,bd),bd.method==="throw")||Sd!=="return"&&(bd.method="throw",bd.arg=new TypeError("The iterator does not provide a '"+Sd+"' method")),Vu;var cd=ju(Ed,yd.iterator,bd.arg);if(cd.type==="throw")return bd.method="throw",bd.arg=cd.arg,bd.delegate=null,Vu;var dd=cd.arg;return dd?dd.done?(bd[yd.resultName]=dd.value,bd.next=yd.nextLoc,bd.method!=="return"&&(bd.method="next",bd.arg=Au),bd.delegate=null,Vu):dd:(bd.method="throw",bd.arg=new TypeError("iterator result is not an object"),bd.delegate=null,Vu)}function ad(yd){var bd={tryLoc:yd[0]};1 in yd&&(bd.catchLoc=yd[1]),2 in yd&&(bd.finallyLoc=yd[2],bd.afterLoc=yd[3]),this.tryEntries.push(bd)}function pd(yd){var bd=yd.completion||{};bd.type="normal",delete bd.arg,yd.completion=bd}function gd(yd){this.tryEntries=[{tryLoc:"root"}],yd.forEach(ad,this),this.reset(!0)}function _d(yd){if(yd||yd===""){var bd=yd[Ou];if(bd)return bd.call(yd);if(typeof yd.next=="function")return yd;if(!isNaN(yd.length)){var Sd=-1,Ed=function cd(){for(;++Sd<yd.length;)if(Ru.call(yd,Sd))return cd.value=yd[Sd],cd.done=!1,cd;return cd.value=Au,cd.done=!0,cd};return Ed.next=Ed}}throw new TypeError(_typeof$3(yd)+" 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(yd){var bd=typeof yd=="function"&&yd.constructor;return!!bd&&(bd===Wu||(bd.displayName||bd.name)==="GeneratorFunction")},lo.mark=function(yd){return Object.setPrototypeOf?Object.setPrototypeOf(yd,Ku):(yd.__proto__=Ku,Lu(yd,Du,"GeneratorFunction")),yd.prototype=Object.create(ed),yd},lo.awrap=function(yd){return{__await:yd}},td(nd.prototype),Lu(nd.prototype,Mu,function(){return this}),lo.AsyncIterator=nd,lo.async=function(yd,bd,Sd,Ed,cd){cd===void 0&&(cd=Promise);var dd=new nd(Bu(yd,bd,Sd,Ed),cd);return lo.isGeneratorFunction(bd)?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(yd){var bd=Object(yd),Sd=[];for(var Ed in bd)Sd.push(Ed);return Sd.reverse(),function cd(){for(;Sd.length;){var dd=Sd.pop();if(dd in bd)return cd.value=dd,cd.done=!1,cd}return cd.done=!0,cd}},lo.values=_d,gd.prototype={constructor:gd,reset:function(bd){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),!bd)for(var Sd in this)Sd.charAt(0)==="t"&&Ru.call(this,Sd)&&!isNaN(+Sd.slice(1))&&(this[Sd]=Au)},stop:function(){this.done=!0;var bd=this.tryEntries[0].completion;if(bd.type==="throw")throw bd.arg;return this.rval},dispatchException:function(bd){if(this.done)throw bd;var Sd=this;function Ed(vd,wd){return md.type="throw",md.arg=bd,Sd.next=vd,wd&&(Sd.method="next",Sd.arg=Au),!!wd}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(bd,Sd){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&&(bd==="break"||bd==="continue")&&dd.tryLoc<=Sd&&Sd<=dd.finallyLoc&&(dd=null);var md=dd?dd.completion:{};return md.type=bd,md.arg=Sd,dd?(this.method="next",this.next=dd.finallyLoc,Vu):this.complete(md)},complete:function(bd,Sd){if(bd.type==="throw")throw bd.arg;return bd.type==="break"||bd.type==="continue"?this.next=bd.arg:bd.type==="return"?(this.rval=this.arg=bd.arg,this.method="return",this.next="end"):bd.type==="normal"&&Sd&&(this.next=Sd),Vu},finish:function(bd){for(var Sd=this.tryEntries.length-1;Sd>=0;--Sd){var Ed=this.tryEntries[Sd];if(Ed.finallyLoc===bd)return this.complete(Ed.completion,Ed.afterLoc),pd(Ed),Vu}},catch:function(bd){for(var Sd=this.tryEntries.length-1;Sd>=0;--Sd){var Ed=this.tryEntries[Sd];if(Ed.tryLoc===bd){var cd=Ed.completion;if(cd.type==="throw"){var dd=cd.arg;pd(Ed)}return dd}}throw Error("illegal catch attempt")},delegateYield:function(bd,Sd,Ed){return this.delegate={iterator:_d(bd),resultName:Sd,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),_d=reactExports.useRef(!1),yd=reactExports.useRef(null),bd=reactExports.useRef(!1),Sd=reactExports.useRef($u);Sd.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:vh}=await import("./chunks/index-fQxrRXLD.js");return{iamStore:Jd,coreStore:vh}},[],import.meta.url),qd=Ad.getState().token||"",Ud=$d.getState().configuration?.aiAgentsUrl||"";return{token:qd,aiAgentsUrl:Ud,runtimesUrl:dd}}catch{return{token:"",aiAgentsUrl:"",runtimesUrl:""}}},[dd]);reactExports.useEffect(()=>{!Lu||!cd||(Uu?[Uu.runtimeName,Uu.environmentName,Uu.jupyterBaseUrl||"",Uu.kernelId||""].join(":"):null)===cd||(_d.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 qd=(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:qd,...Bu,runtimesUrl:dd});return ed("ready"),Dd}catch($d){const qd=$d instanceof Error?$d.message:String($d);throw nd(qd),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(bd.current)throw new Error("Agent creation already in progress");bd.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 qd={...DEFAULT_AGENT_CONFIG,...$d,...$u,...Ad,name:Ad?.name||$u?.name||(Ed&&lo?lo:Uu?.runtimeName)};return await Ju(qd)}catch($d){const qd=$d instanceof Error?$d.message:String($d);throw Ed&&(nd(qd),ed("error")),$d}finally{bd.current=!1,sd(!1)}},[lo,$u,Pu,Ed,Uu,Ju]),vd=reactExports.useCallback(async()=>{const Ad=Uu?.agentId,$d=Uu?.agentBaseUrl,qd=Ad&&$d?agentDeletionUrl($d,Ad,Fu):void 0;if(qd)try{const{token:Dd}=await md();await fetch(qd,{method:"DELETE",headers:Dd?{Authorization:`Bearer ${Dd}`}:{}})}catch{}_d.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&&!_d.current&&(_d.current=!0,Ju(Sd.current).catch(Ad=>{console.error("[useAgent] Failed to auto-create agent:",Ad),_d.current=!1}))},[Ed,Ru,Uu,Hu,Ju]),reactExports.useEffect(()=>{Ed&&Ru&&Uu&&(Xu==="ready"||Xu==="resumed")&&!Uu.isReady&&!_d.current&&(_d.current=!0,hd(Sd.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"),_d.current=!1}))},[Ed,Ru,Uu,Xu,hd]),reactExports.useEffect(()=>{const Ad=Uu?.runtimeName||null;if(!Ad){yd.current=null;return}yd.current&&yd.current!==Ad&&(_d.current=!1),yd.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:qd,runtimesUrl:Dd}=await md();if(!qd)return;const{listRuntimes:Ud}=await __vitePreload(async()=>{const{listRuntimes:lh}=await import("./chunks/runtimes-BQWpLsQm.js");return{listRuntimes:lh}},[],import.meta.url),sh=((await Ud(qd,Dd)).runtimes||[]).filter(lh=>lh.environment?.name!=="ai-agents-env"?!1:lo?lh.agent_spec_id===lo:!0).slice().sort((lh,Dh)=>{const Vd=Number(lh.started_at||0);return Number(Dh.started_at||0)-Vd})[0];if(Ad||!sh?.runtime_name||!sh?.ingress)return;Ku({runtimeName:sh.runtime_name,environmentName:sh.environment.name,jupyterBaseUrl:sh.ingress}),_d.current=!1;const Eh=sh,bh=typeof Eh.status=="string"?Eh.status.toLowerCase():"",Qd=RUNTIME_STATUS_MAP[bh]??"running",th=Qd==="paused"?"paused":Qd==="resuming"||Qd==="resumed"?"resumed":"running";ed(th==="paused"?"paused":th==="resumed"?"resumed":"ready")}catch(qd){console.warn("[useAgents] Failed to find existing runtime:",qd)}finally{Ad||gd(!0)}})(),()=>{Ad=!0}},[Ed,Uu,Iu,Xu,md,lo,Bu,Ku]),reactExports.useEffect(()=>{(Hu==="disconnected"||Hu==="idle")&&(_d.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 wd=runsInBrowser(ju),kd=wd?"ready":Ed?Xu:Hu,Rd=wd?null:Ed&&td||Vu,Od=wd?!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:vd,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.
|
|
2197
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.
|
|
@@ -2261,7 +2264,7 @@ contemplation. That said, any topic is fair game.
|
|
|
2261
2264
|
|
|
2262
2265
|
Do not repeat the haiku content in your text response - the UI will display it
|
|
2263
2266
|
beautifully. Just acknowledge that you've created the haiku.
|
|
2264
|
-
`,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_HOOKS_AGENTSPEC_0_0_1={id:"example-hooks",version:"0.0.1",name:"Example Hooks Agent",description:"Demonstrates pre-hooks and post-hooks executed in the sandbox lifecycle.",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["runtime-echo:0.0.1"],TOOL_MAP$1["runtime-sensitive-echo:0.0.1"]],frontendTools:[],environmentName:"ai-agents-env",icon:"zap",emoji:"🪝",color:"#0E7490",suggestions:[{text:"Read the pre-hook marker file at /tmp/agent_runtimes_pre_hook_demo.txt using execute_code.",summary:"Read the pre-hook marker"},{text:"Print the hook_ran_at and hook_name variables that the pre-hook set in the sandbox.",summary:"Print the hook variables"},{text:"Run execute_code to verify that the 'rich' package was installed by the pre-hook.",summary:"Verify rich installed"},{text:"Show me all variables that the pre-hook defined in the sandbox namespace.",summary:"Pre-hook variables"},{text:"Call runtime_sensitive_echo with reason 'audit' to trigger per-tool authorization hooks.",summary:"Trigger authorization hooks"},{text:"Use execute_code to read /tmp/agent_runtimes_tool_approvals_audit.jsonl and summarize the latest authorization + execution entries.",summary:"Summarize the audit log"}],welcomeMessage:`I ran a pre-hook before starting up. It installed the 'rich' package, wrote a marker file, and set several sandbox variables (hook_name, hook_ran_at, hook_env). Ask me to read the file or inspect those variables.
|
|
2267
|
+
`,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_HARNESS_CLAUDE_CODE_AGENTSPEC_0_0_1={id:"example-harness-claude-code",version:"0.0.1",name:"A Claude Code Agent",description:"Claude Code as a Datalayer agent: launched in the runtime over the Agent Client Protocol, its files, terminals and permissions decided by the Shield under the application's Rules, every action in the record. Needs the account's ANTHROPIC_API_KEY.",tags:["coding","harness","acp"],domain:void 0,enabled:!1,model:void 0,mcpServers:[],skills:[].filter(Boolean),backendTools:[],frontendTools:[],environmentName:"ai-agents-env",icon:void 0,emoji:void 0,color:void 0,suggestions:[],welcomeMessage:void 0,welcomeNotebook:void 0,welcomeDocument:void 0,sandboxVariant:"jupyter-server",harness:"claude-code",systemPrompt:void 0,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:void 0},EXAMPLE_HOOKS_AGENTSPEC_0_0_1={id:"example-hooks",version:"0.0.1",name:"Example Hooks Agent",description:"Demonstrates pre-hooks and post-hooks executed in the sandbox lifecycle.",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["runtime-echo:0.0.1"],TOOL_MAP$1["runtime-sensitive-echo:0.0.1"]],frontendTools:[],environmentName:"ai-agents-env",icon:"zap",emoji:"🪝",color:"#0E7490",suggestions:[{text:"Read the pre-hook marker file at /tmp/agent_runtimes_pre_hook_demo.txt using execute_code.",summary:"Read the pre-hook marker"},{text:"Print the hook_ran_at and hook_name variables that the pre-hook set in the sandbox.",summary:"Print the hook variables"},{text:"Run execute_code to verify that the 'rich' package was installed by the pre-hook.",summary:"Verify rich installed"},{text:"Show me all variables that the pre-hook defined in the sandbox namespace.",summary:"Pre-hook variables"},{text:"Call runtime_sensitive_echo with reason 'audit' to trigger per-tool authorization hooks.",summary:"Trigger authorization hooks"},{text:"Use execute_code to read /tmp/agent_runtimes_tool_approvals_audit.jsonl and summarize the latest authorization + execution entries.",summary:"Summarize the audit log"}],welcomeMessage:`I ran a pre-hook before starting up. It installed the 'rich' package, wrote a marker file, and set several sandbox variables (hook_name, hook_ran_at, hook_env). Ask me to read the file or inspect those variables.
|
|
2265
2268
|
`,welcomeNotebook:void 0,welcomeDocument:void 0,sandboxVariant:"eval",harness:"pydantic-ai",systemPrompt:`You are a demo assistant for lifecycle hooks.
|
|
2266
2269
|
The sandbox pre-hook ran before this agent started and did three things:
|
|
2267
2270
|
1. Installed the Python package 'rich' (pip install). 2. Wrote a UTF-8 marker file to /tmp/agent_runtimes_pre_hook_demo.txt
|
|
@@ -2921,7 +2924,7 @@ Use only tools actually provided to you.
|
|
|
2921
2924
|
`,goal:void 0,delegable:[{id:"data.analyse"},{id:"document.summarise"}],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:void 0},WORKER_SUMMARIZE_DOCUMENTS_AGENTSPEC_0_0_1={id:"worker-summarize-documents",version:"0.0.1",name:"Summarize Documents",description:"A generic document summarization agent that processes PDFs, Word files, Markdown, and plain text. Produces structured executive summaries with key findings, action items, and metadata extraction. Useful across every industry vertical — from legal contracts to research papers.",tags:["personal-assistant","agent-worker","research","document-processing","summarization"],domain:"personal-assistant",enabled:!1,model:"bedrock:us.anthropic.claude-sonnet-4-6",mcpServers:[MCP_SERVER_MAP$1["filesystem:0.0.1"]],skills:[SKILL_MAP$1["pdf:0.0.1"]?toAgentSkillSpec$1(SKILL_MAP$1["pdf:0.0.1"]):void 0,SKILL_MAP$1["events:0.0.1"]?toAgentSkillSpec$1(SKILL_MAP$1["events:0.0.1"]):void 0].filter(Boolean),backendTools:[],frontendTools:[FRONTEND_TOOL_MAP$1["jupyter-notebook:0.0.1"],FRONTEND_TOOL_MAP$1["lexical-document:0.0.1"]],environmentName:"ai-agents-env",icon:"file",emoji:"📄",color:"#8250df",suggestions:[],welcomeMessage:void 0,welcomeNotebook:void 0,welcomeDocument:void 0,sandboxVariant:"jupyter-server",harness:"pydantic-ai",systemPrompt:void 0,systemPromptCodemodeAddons:void 0,goal:"Summarize uploaded documents (PDFs, Word, Markdown, text) into structured executive summaries. Extract key findings, decisions, action items, dates, and named entities. Output a concise summary (max 500 words) plus metadata in JSON format.",delegable:[{id:"data.extract"},{id:"document.summarise"},{id:"document.extract"},{id:"research.gather"}],protocol:"vercel-ai",ui:[{plugin:"a2ui-surface",renderer:"a2ui"}],protocols:[],trigger:{type:"event",event:"document_uploaded",description:"Triggered when a new document is uploaded to the workspace",prompt:"Handle the 'document_uploaded' event and execute the workflow end-to-end."},modelConfig:{temperature:.2,max_tokens:4096},mcpServerTools:[{server:"Document Reader",tools:[{name:"read_pdf",approval:"auto"},{name:"read_docx",approval:"auto"},{name:"extract_text",approval:"auto"}]},{server:"Output Writer",tools:[{name:"write_summary",approval:"auto"},{name:"store_metadata",approval:"auto"}]}],guardrails:[{name:"Default Platform User",identity_provider:"datalayer",identity_name:"doc-agent@acme.com",permissions:{"read:data":!0,"write:data":!0,"execute:code":!0,"access:internet":!1,"send:email":!1,"deploy:production":!1},token_limits:{per_run:"30K",per_day:"300K",per_month:"3M"}}],evals:[{name:"Summarization Accuracy",category:"reasoning",task_count:350},{name:"Key Finding Extraction",category:"reasoning",task_count:280},{name:"Action Item Detection",category:"coding",task_count:200}],codemode:void 0,output:{type:"Markdown",formats:["Markdown","JSON"],template:"executive-summary-v1",storage:"s3://acme-summaries/"},advanced:void 0,checkpoints:void 0,authorizationPolicy:void 0,notifications:{slack:"#document-summaries",email:"team@acme.com"},memory:"ephemeral",preHooks:void 0,postHooks:void 0,toolHooks:void 0,parameters:void 0,subagents:void 0},WORKER_SYNC_CRM_CONTACTS_AGENTSPEC_0_0_1={id:"worker-sync-crm-contacts",version:"0.0.1",name:"Sync CRM Contacts",description:"A multi-agent team that collects and aggregates contact data from multiple CRM sources, analyzes and deduplicates records, writes cleaned data back, and generates sync summary reports.",tags:["marketing","agent-worker","sales","crm","data-acquisition"],domain:"marketing",enabled:!1,model:"bedrock:us.anthropic.claude-sonnet-4-6",mcpServers:[MCP_SERVER_MAP$1["filesystem:0.0.1"],MCP_SERVER_MAP$1["slack:0.0.1"]],skills:[SKILL_MAP$1["pdf:0.0.1"]?toAgentSkillSpec$1(SKILL_MAP$1["pdf:0.0.1"]):void 0,SKILL_MAP$1["events:0.0.1"]?toAgentSkillSpec$1(SKILL_MAP$1["events:0.0.1"]):void 0].filter(Boolean),backendTools:[],frontendTools:[FRONTEND_TOOL_MAP$1["jupyter-notebook:0.0.1"],FRONTEND_TOOL_MAP$1["lexical-document:0.0.1"]],environmentName:"ai-agents-env",icon:"people",emoji:"🔄",color:"#0969da",suggestions:[{text:"Run a full CRM contact sync now",summary:"Full CRM sync"},{text:"Show the latest sync report",summary:"Latest sync report"},{text:"How many duplicates were found in the last run?",summary:"Duplicates found"},{text:"List contacts that failed to sync",summary:"Failed contacts"}],welcomeMessage:`Hello! I'm the CRM Contact Sync team orchestrator. I coordinate four specialised agents — Data Collector, Analyzer, Sync Writer, and Report Generator — to keep your CRM contacts clean, deduplicated, and in sync across all platforms.
|
|
2922
2925
|
`,welcomeNotebook:void 0,welcomeDocument:void 0,sandboxVariant:"jupyter-server",harness:"pydantic-ai",systemPrompt:`You are the supervisor of a CRM contact synchronization team. You coordinate four agents in sequence: 1. Data Collector — pulls contact data from Salesforce, HubSpot, and other CRM sources 2. Analyzer — identifies duplicates, patterns, and data quality issues 3. Sync Writer — writes cleaned, merged contacts back to all CRM systems 4. Report Generator — produces sync summary reports and sends notifications Route tasks sequentially. Escalate to human review if any sync operation fails 3 times. Always confirm merge decisions for contacts with conflicting data.
|
|
2923
2926
|
`,systemPromptCodemodeAddons:void 0,goal:"Collect and aggregate contact data from multiple CRM sources, analyze and deduplicate records, write cleaned data back to CRM systems, and generate sync summary reports with notifications.",delegable:[{id:"data.acquire"},{id:"data.transform"},{id:"data.analyse"},{id:"report.author"},{id:"document.author"}],protocol:"vercel-ai",ui:[{plugin:"a2ui-surface",renderer:"a2ui"}],protocols:[],trigger:{type:"schedule",cron:"0 2 * * *",description:`Daily at 02:00 — sync CRM contacts across all sources during off-peak hours.
|
|
2924
|
-
`,prompt:"Run the scheduled workflow and produce the configured deliverable."},modelConfig:void 0,mcpServerTools:void 0,guardrails:[{name:"GitHub CI Bot",identity_provider:"github",identity_name:"ci-bot@acme.com",permissions:{"read:data":!0,"write:data":!0,"execute:code":!0,"access:internet":!0,"send:email":!0,"deploy:production":!1},token_limits:{per_run:"60K",per_day:"600K",per_month:"6M"}}],evals:[{name:"Data Quality",category:"coding",task_count:300},{name:"Deduplication Accuracy",category:"reasoning",task_count:150}],codemode:{enabled:!0,token_reduction:"~85%",speedup:"~1.5× faster"},output:{formats:["JSON","PDF"],template:"CRM Sync Report",storage:"/outputs/crm-sync/"},advanced:{cost_limit:"$10.00 per run",time_limit:"600 seconds",max_iterations:100,validation:"All CRM records must reconcile after sync"},checkpoints:void 0,authorizationPolicy:"",notifications:{email:"jennifer.c@company.com",slack:"#crm-sync"},memory:"ephemeral",preHooks:void 0,postHooks:void 0,toolHooks:void 0,parameters:void 0,subagents:void 0},WORKER_THEMATIC_ANALYSIS_AGENTSPEC_0_0_1={id:"worker-thematic-analysis",version:"0.0.1",name:"Thematic Analyst",description:"Codes transcripts, extracts themes, and organizes qualitative evidence.",tags:["market-analyst","agent-worker"],domain:"market-analyst",enabled:!1,model:"bedrock:us.anthropic.claude-sonnet-4-6",mcpServers:[MCP_SERVER_MAP$1["tavily:0.0.1"],MCP_SERVER_MAP$1["salesforce:0.0.1"]],skills:[SKILL_MAP$1["text-summarizer:0.0.1"]?toAgentSkillSpec$1(SKILL_MAP$1["text-summarizer:0.0.1"]):void 0,SKILL_MAP$1["crawl:0.0.1"]?toAgentSkillSpec$1(SKILL_MAP$1["crawl:0.0.1"]):void 0].filter(Boolean),backendTools:[TOOL_MAP$1["runtime-echo:0.0.1"],TOOL_MAP$1["runtime-sensitive-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:"note",emoji:"🔎",color:"#EC4899",suggestions:[],welcomeMessage:void 0,welcomeNotebook:void 0,welcomeDocument:void 0,sandboxVariant:"jupyter-server",harness:"pydantic-ai",systemPrompt:"You are the Thematic Analysis Worker, an autonomous agent worker in the market analyst domain. Codes transcripts, extracts themes, and organizes qualitative evidence. Work step by step, show your reasoning and evidence, and require explicit human approval before any external or irreversible action.",systemPromptCodemodeAddons:void 0,goal:"Code transcripts, extract themes, and organize the supporting evidence.",delegable:[{id:"data.extract"},{id:"data.analyse"}],protocol:"vercel-ai",ui:[{plugin:"a2ui-surface",renderer:"a2ui"}],protocols:[],trigger:void 0,modelConfig:{temperature:.5,max_tokens:4096},mcpServerTools:void 0,guardrails:void 0,evals:void 0,codemode:{enabled:!0},output:void 0,advanced:void 0,checkpoints:void 0,authorizationPolicy:void 0,notifications:void 0,memory:"mem0",preHooks:void 0,postHooks:void 0,toolHooks:void 0,parameters:void 0,subagents:void 0},WORKER_TRAVEL_RECOMMENDER_AGENTSPEC_0_0_1={id:"worker-travel-recommender",version:"0.0.1",name:"Travel Recommender",description:"Researches travel options and builds personalized itineraries with source comparison.",tags:["personal-assistant","agent-worker"],domain:"personal-assistant",enabled:!1,model:"bedrock:us.anthropic.claude-sonnet-4-6",mcpServers:[MCP_SERVER_MAP$1["tavily:0.0.1"],MCP_SERVER_MAP$1["google-workspace:0.0.1"]],skills:[SKILL_MAP$1["text-summarizer:0.0.1"]?toAgentSkillSpec$1(SKILL_MAP$1["text-summarizer:0.0.1"]):void 0,SKILL_MAP$1["crawl:0.0.1"]?toAgentSkillSpec$1(SKILL_MAP$1["crawl:0.0.1"]):void 0,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"],TOOL_MAP$1["runtime-sensitive-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:"globe",emoji:"🤖",color:"#A855F7",suggestions:[],welcomeMessage:void 0,welcomeNotebook:void 0,welcomeDocument:void 0,sandboxVariant:"jupyter-server",harness:"pydantic-ai",systemPrompt:"You are the Travel Recommender, an autonomous agent worker in the personal assistant domain. Researches travel options and builds personalized itineraries with source comparison. Work step by step, show your reasoning and evidence, and require explicit human approval before any external or irreversible action.",systemPromptCodemodeAddons:void 0,goal:"Research travel options and build a personalized itinerary, comparing sources and prices.",delegable:[{id:"research.gather"}],protocol:"vercel-ai",ui:[{plugin:"a2ui-surface",renderer:"a2ui"}],protocols:[],trigger:void 0,modelConfig:{temperature:.5,max_tokens:4096},mcpServerTools:void 0,guardrails:void 0,evals:void 0,codemode:{enabled:!0},output:void 0,advanced:void 0,checkpoints:void 0,authorizationPolicy:void 0,notifications:void 0,memory:"mem0",preHooks:void 0,postHooks:void 0,toolHooks:void 0,parameters:void 0,subagents:void 0},WORKER_TRENDS_SEEKER_AGENTSPEC_0_0_1={id:"worker-trends-seeker",version:"0.0.1",name:"Trends Seeker",description:"Tracks emerging trends across sources and summarizes what is gaining momentum.",tags:["personal-assistant","agent-worker"],domain:"personal-assistant",enabled:!1,model:"bedrock:us.anthropic.claude-sonnet-4-6",mcpServers:[MCP_SERVER_MAP$1["tavily:0.0.1"],MCP_SERVER_MAP$1["google-workspace:0.0.1"]],skills:[SKILL_MAP$1["text-summarizer:0.0.1"]?toAgentSkillSpec$1(SKILL_MAP$1["text-summarizer:0.0.1"]):void 0,SKILL_MAP$1["crawl:0.0.1"]?toAgentSkillSpec$1(SKILL_MAP$1["crawl:0.0.1"]):void 0,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"],TOOL_MAP$1["runtime-sensitive-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:"graph",emoji:"🤖",color:"#A855F7",suggestions:[],welcomeMessage:void 0,welcomeNotebook:void 0,welcomeDocument:void 0,sandboxVariant:"jupyter-server",harness:"pydantic-ai",systemPrompt:"You are the Trends Seeker, an autonomous agent worker in the personal assistant domain. Tracks emerging trends across sources and summarizes what is gaining momentum. Work step by step, show your reasoning and evidence, and require explicit human approval before any external or irreversible action.",systemPromptCodemodeAddons:void 0,goal:"Track emerging trends across sources and summarize what is worth attention and why.",delegable:[{id:"document.summarise"}],protocol:"vercel-ai",ui:[{plugin:"a2ui-surface",renderer:"a2ui"}],protocols:[],trigger:void 0,modelConfig:{temperature:.5,max_tokens:4096},mcpServerTools:void 0,guardrails:void 0,evals:void 0,codemode:{enabled:!0},output:void 0,advanced:void 0,checkpoints:void 0,authorizationPolicy:void 0,notifications:void 0,memory:"mem0",preHooks:void 0,postHooks:void 0,toolHooks:void 0,parameters:void 0,subagents:void 0},WORKER_VARIANT_ANALYSIS_AGENTSPEC_0_0_1={id:"worker-variant-analysis",version:"0.0.1",name:"Variant Analyst",description:"Analyzes genomic variants, annotates findings, and prepares interpretable reports.",tags:["life-sciences","agent-worker"],domain:"life-sciences",enabled:!1,model:"bedrock:us.anthropic.claude-sonnet-4-6",mcpServers:[MCP_SERVER_MAP$1["huggingface:0.0.1"],MCP_SERVER_MAP$1["kaggle:0.0.1"]],skills:[SKILL_MAP$1["text-summarizer:0.0.1"]?toAgentSkillSpec$1(SKILL_MAP$1["text-summarizer:0.0.1"]):void 0,SKILL_MAP$1["pdf:0.0.1"]?toAgentSkillSpec$1(SKILL_MAP$1["pdf:0.0.1"]):void 0].filter(Boolean),backendTools:[TOOL_MAP$1["runtime-echo:0.0.1"],TOOL_MAP$1["runtime-sensitive-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:"beaker",emoji:"🧬",color:"#06B6D4",suggestions:[],welcomeMessage:void 0,welcomeNotebook:void 0,welcomeDocument:void 0,sandboxVariant:"jupyter-server",harness:"pydantic-ai",systemPrompt:"You are the Variant Analysis Worker, an autonomous agent worker in the life sciences domain. Analyzes genomic variants, annotates findings, and prepares interpretable reports. Work step by step, show your reasoning and evidence, and require explicit human approval before any external or irreversible action.",systemPromptCodemodeAddons:void 0,goal:"Analyze and annotate genomic variants and produce an interpretable, provenance-tracked report.",delegable:[{id:"data.analyse"},{id:"report.author"}],protocol:"vercel-ai",ui:[{plugin:"a2ui-surface",renderer:"a2ui"}],protocols:[],trigger:void 0,modelConfig:{temperature:.5,max_tokens:4096},mcpServerTools:void 0,guardrails:void 0,evals:void 0,codemode:{enabled:!0},output:void 0,advanced:void 0,checkpoints:void 0,authorizationPolicy:void 0,notifications:void 0,memory:"mem0",preHooks:void 0,postHooks:void 0,toolHooks:void 0,parameters:void 0,subagents:void 0},WORKER_WEEKLY_EXECUTIVE_BRIEFING_AGENTSPEC_0_0_1={id:"worker-weekly-executive-briefing",version:"0.0.1",name:"Weekly Executive Briefing",description:"Generate a weekly executive summary with KPI deltas, top risks, and recommended actions from operational and analytics data.",tags:["personal-assistant","agent-worker","analytics","reporting","risk"],domain:"personal-assistant",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:"lightbulb",emoji:"📊",color:"#1F883D",suggestions:[{text:"Use /home/datalayer/datasets/datalayer-nfs/sales/sales_pipeline.csv to produce a weekly executive briefing with trends, risks, and actions.",summary:"Weekly executive briefing"}],welcomeMessage:"Hi! I can help with weekly executive briefing. 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: Weekly Executive Briefing. Objective: Generate a weekly executive summary with KPI deltas, top risks, and recommended actions from operational and analytics data. 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:[{id:"data.analyse"},{id:"report.author"}],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},AGENTSPECS$1={"example-a2a-researcher":EXAMPLE_A2A_RESEARCHER_AGENTSPEC_0_0_1,"example-a2a-writer":EXAMPLE_A2A_WRITER_AGENTSPEC_0_0_1,"example-a2a":EXAMPLE_A2A_AGENTSPEC_0_0_1,"example-a2ui-agent":EXAMPLE_A2UI_AGENT_SPEC_0_0_1,"example-a2ui-jupyter-output":EXAMPLE_A2UI_JUPYTER_OUTPUT_AGENTSPEC_0_0_1,"example-a2ui-viewer":EXAMPLE_A2UI_VIEWER_AGENTSPEC_0_0_1,"example-agent-critic-loop-for-analysis":EXAMPLE_AGENT_CRITIC_LOOP_FOR_ANALYSIS_AGENTSPEC_0_0_1,"example-agentic-chat":EXAMPLE_AGENTIC_CHAT_AGENTSPEC_0_0_1,"example-agentic-generative-ui":EXAMPLE_AGENTIC_GENERATIVE_UI_AGENTSPEC_0_0_1,"example-ai-creates-dashboards":EXAMPLE_AI_CREATES_DASHBOARDS_AGENTSPEC_0_0_1,"example-ai-explains-notebook-output":EXAMPLE_AI_EXPLAINS_NOTEBOOK_OUTPUT_AGENTSPEC_0_0_1,"example-ai-writes-pandas-code":EXAMPLE_AI_WRITES_PANDAS_CODE_AGENTSPEC_0_0_1,"example-analyze-excel-spreadsheet":EXAMPLE_ANALYZE_EXCEL_SPREADSHEET_AGENTSPEC_0_0_1,"example-backend-tool-rendering":EXAMPLE_BACKEND_TOOL_RENDERING_AGENTSPEC_0_0_1,"example-blank":EXAMPLE_BLANK_AGENTSPEC_0_0_1,"example-build-notebook-with-one-prompt":EXAMPLE_BUILD_NOTEBOOK_WITH_ONE_PROMPT_AGENTSPEC_0_0_1,"example-checkpoints":EXAMPLE_CHECKPOINTS_AGENTSPEC_0_0_1,"example-cloudflare":EXAMPLE_CLOUDFLARE_AGENTSPEC_0_0_1,"example-code-sandbox":EXAMPLE_CODE_SANDBOX_AGENTSPEC_0_0_1,"example-codemode":EXAMPLE_CODEMODE_AGENTSPEC_0_0_1,"example-compaction":EXAMPLE_COMPACTION_AGENTSPEC_0_0_1,"example-compare-two-spreadsheets":EXAMPLE_COMPARE_TWO_SPREADSHEETS_AGENTSPEC_0_0_1,"example-cost-comparison-report":EXAMPLE_COST_COMPARISON_REPORT_AGENTSPEC_0_0_1,"example-decks":EXAMPLE_DECKS_AGENTSPEC_0_0_1,"example-document-agent-sidebar":EXAMPLE_DOCUMENT_AGENT_SIDEBAR_AGENTSPEC_0_0_1,"example-document-agent":EXAMPLE_DOCUMENT_AGENT_SPEC_0_0_1,"example-evals-nocodemode":EXAMPLE_EVALS_NOCODEMODE_AGENTSPEC_0_0_1,"example-evals":EXAMPLE_EVALS_AGENTSPEC_0_0_1,"example-explore-sql-database":EXAMPLE_EXPLORE_SQL_DATABASE_AGENTSPEC_0_0_1,"example-five-ai-agents-analyze-csv":EXAMPLE_FIVE_AI_AGENTS_ANALYZE_CSV_AGENTSPEC_0_0_1,"example-five-notebooks-in-parallel":EXAMPLE_FIVE_NOTEBOOKS_IN_PARALLEL_AGENTSPEC_0_0_1,"example-full":EXAMPLE_FULL_AGENTSPEC_0_0_1,"example-gpt-and-claude-collaborate":EXAMPLE_GPT_AND_CLAUDE_COLLABORATE_AGENTSPEC_0_0_1,"example-guardrails":EXAMPLE_GUARDRAILS_AGENTSPEC_0_0_1,"example-haiku-generative-ui":EXAMPLE_HAIKU_GENERATIVE_UI_AGENTSPEC_0_0_1,"example-hooks":EXAMPLE_HOOKS_AGENTSPEC_0_0_1,"example-human-approved-automation":EXAMPLE_HUMAN_APPROVED_AUTOMATION_AGENTSPEC_0_0_1,"example-human-in-the-loop":EXAMPLE_HUMAN_IN_THE_LOOP_AGENTSPEC_0_0_1,"example-inference":EXAMPLE_INFERENCE_AGENTSPEC_0_0_1,"example-long-running-agent-overnight":EXAMPLE_LONG_RUNNING_AGENT_OVERNIGHT_AGENTSPEC_0_0_1,"example-mcp":EXAMPLE_MCP_AGENTSPEC_0_0_1,"example-memory":EXAMPLE_MEMORY_AGENTSPEC_0_0_1,"example-monitoring":EXAMPLE_MONITORING_AGENTSPEC_0_0_1,"example-multi-agent-data-cleaning":EXAMPLE_MULTI_AGENT_DATA_CLEANING_AGENTSPEC_0_0_1,"example-multi-agent-root-cause-analysis":EXAMPLE_MULTI_AGENT_ROOT_CAUSE_ANALYSIS_AGENTSPEC_0_0_1,"example-no-codemode":EXAMPLE_NO_CODEMODE_AGENTSPEC_0_0_1,"example-notifications":EXAMPLE_NOTIFICATIONS_AGENTSPEC_0_0_1,"example-one-trigger-approval":EXAMPLE_ONE_TRIGGER_APPROVAL_AGENTSPEC_0_0_1,"example-one-trigger":EXAMPLE_ONE_TRIGGER_AGENTSPEC_0_0_1,"example-otel":EXAMPLE_OTEL_AGENTSPEC_0_0_1,"example-output":EXAMPLE_OUTPUT_AGENTSPEC_0_0_1,"example-parameters":EXAMPLE_PARAMETERS_AGENTSPEC_0_0_1,"example-replace-excel-pivot-work":EXAMPLE_REPLACE_EXCEL_PIVOT_WORK_AGENTSPEC_0_0_1,"example-resumable-etl-with-checkpoints":EXAMPLE_RESUMABLE_ETL_WITH_CHECKPOINTS_AGENTSPEC_0_0_1,"example-run-python-safely-in-the-cloud":EXAMPLE_RUN_PYTHON_SAFELY_IN_THE_CLOUD_AGENTSPEC_0_0_1,"example-sandbox-colab":EXAMPLE_SANDBOX_COLAB_AGENTSPEC_0_0_1,"example-sandbox-datalayer":EXAMPLE_SANDBOX_DATALAYER_AGENTSPEC_0_0_1,"example-sandbox-docker":EXAMPLE_SANDBOX_DOCKER_AGENTSPEC_0_0_1,"example-sandbox-eval":EXAMPLE_SANDBOX_EVAL_AGENTSPEC_0_0_1,"example-sandbox-jupyter":EXAMPLE_SANDBOX_JUPYTER_AGENTSPEC_0_0_1,"example-sandbox-kaggle":EXAMPLE_SANDBOX_KAGGLE_AGENTSPEC_0_0_1,"example-sandbox-modal":EXAMPLE_SANDBOX_MODAL_AGENTSPEC_0_0_1,"example-sandbox-monty":EXAMPLE_SANDBOX_MONTY_AGENTSPEC_0_0_1,"example-shared-state":EXAMPLE_SHARED_STATE_AGENTSPEC_0_0_1,"example-simple":EXAMPLE_SIMPLE_AGENTSPEC_0_0_1,"example-skills":EXAMPLE_SKILLS_AGENTSPEC_0_0_1,"example-subagents":EXAMPLE_SUBAGENTS_AGENTSPEC_0_0_1,"example-tool-approvals":EXAMPLE_TOOL_APPROVALS_AGENTSPEC_0_0_1,"example-tool-based-generative-ui":EXAMPLE_TOOL_BASED_GENERATIVE_UI_AGENTSPEC_0_0_1,"jupyter-cell-fixer":JUPYTER_CELL_FIXER_AGENTSPEC_0_0_1,"jupyter-data-analyst":JUPYTER_DATA_ANALYST_AGENTSPEC_0_0_1,"jupyter-notebook-compactor":JUPYTER_NOTEBOOK_COMPACTOR_AGENTSPEC_0_0_1,"jupyter-notebook-reproducer":JUPYTER_NOTEBOOK_REPRODUCER_AGENTSPEC_0_0_1,"jupyter-notebook-reviewer":JUPYTER_NOTEBOOK_REVIEWER_AGENTSPEC_0_0_1,"jupyter-notebook-writer":JUPYTER_NOTEBOOK_WRITER_AGENTSPEC_0_0_1,"jupyter-tutor":JUPYTER_TUTOR_AGENTSPEC_0_0_1,"loop-shell":LOOP_SHELL_AGENTSPEC_0_0_1,"worker-accountant":WORKER_ACCOUNTANT_AGENTSPEC_0_0_1,"worker-agent-reviews-sql":WORKER_AGENT_REVIEWS_SQL_AGENTSPEC_0_0_1,"worker-analyze-campaign-performance":WORKER_ANALYZE_CAMPAIGN_PERFORMANCE_AGENTSPEC_0_0_1,"worker-analyze-support-tickets":WORKER_ANALYZE_SUPPORT_TICKETS_AGENTSPEC_0_0_1,"worker-ap-invoice":WORKER_AP_INVOICE_AGENTSPEC_0_0_1,"worker-audit-inventory-levels":WORKER_AUDIT_INVENTORY_LEVELS_AGENTSPEC_0_0_1,"worker-audit-pack-builder":WORKER_AUDIT_PACK_BUILDER_AGENTSPEC_0_0_1,"worker-automate-regulatory-reporting":WORKER_AUTOMATE_REGULATORY_REPORTING_AGENTSPEC_0_0_1,"worker-backtest-auditor":WORKER_BACKTEST_AUDITOR_AGENTSPEC_0_0_1,"worker-bank-reconciliation":WORKER_BANK_RECONCILIATION_AGENTSPEC_0_0_1,"worker-campaign-planning":WORKER_CAMPAIGN_PLANNING_AGENTSPEC_0_0_1,"worker-cat-exposure":WORKER_CAT_EXPOSURE_AGENTSPEC_0_0_1,"worker-change-detection":WORKER_CHANGE_DETECTION_AGENTSPEC_0_0_1,"worker-classify-route-emails":WORKER_CLASSIFY_ROUTE_EMAILS_AGENTSPEC_0_0_1,"worker-cms-astro":WORKER_CMS_ASTRO_AGENTSPEC_0_0_1,"worker-coding-tutor":WORKER_CODING_TUTOR_AGENTSPEC_0_0_1,"worker-cohort-comparison":WORKER_COHORT_COMPARISON_AGENTSPEC_0_0_1,"worker-collections":WORKER_COLLECTIONS_AGENTSPEC_0_0_1,"worker-community-response":WORKER_COMMUNITY_RESPONSE_AGENTSPEC_0_0_1,"worker-competitive-intelligence":WORKER_COMPETITIVE_INTELLIGENCE_AGENTSPEC_0_0_1,"worker-compliance-report-draft":WORKER_COMPLIANCE_REPORT_DRAFT_AGENTSPEC_0_0_1,"worker-comprehensive-sales-analytics":WORKER_COMPREHENSIVE_SALES_ANALYTICS_AGENTSPEC_0_0_1,"worker-compute-cost-optimizer":WORKER_COMPUTE_COST_OPTIMIZER_AGENTSPEC_0_0_1,"worker-content-repurposing":WORKER_CONTENT_REPURPOSING_AGENTSPEC_0_0_1,"worker-crawler":WORKER_CRAWLER_AGENTSPEC_0_0_1,"worker-crop-monitoring":WORKER_CROP_MONITORING_AGENTSPEC_0_0_1,"worker-curtailment-investigator":WORKER_CURTAILMENT_INVESTIGATOR_AGENTSPEC_0_0_1,"worker-customer-churn-analysis":WORKER_CUSTOMER_CHURN_ANALYSIS_AGENTSPEC_0_0_1,"worker-customer-interviewer":WORKER_CUSTOMER_INTERVIEWER_AGENTSPEC_0_0_1,"worker-data-acquisition":WORKER_DATA_ACQUISITION_AGENTSPEC_0_0_1,"worker-disaster-assessment":WORKER_DISASTER_ASSESSMENT_AGENTSPEC_0_0_1,"worker-document-qa":WORKER_DOCUMENT_QA_AGENTSPEC_0_0_1,"worker-end-of-month-performance":WORKER_END_OF_MONTH_PERFORMANCE_AGENTSPEC_0_0_1,"worker-energy-trading-analyst":WORKER_ENERGY_TRADING_ANALYST_AGENTSPEC_0_0_1,"worker-environmental-compliance":WORKER_ENVIRONMENTAL_COMPLIANCE_AGENTSPEC_0_0_1,"worker-event-response":WORKER_EVENT_RESPONSE_AGENTSPEC_0_0_1,"worker-evidence-repository":WORKER_EVIDENCE_REPOSITORY_AGENTSPEC_0_0_1,"worker-expense-audit":WORKER_EXPENSE_AUDIT_AGENTSPEC_0_0_1,"worker-exposure-data-quality":WORKER_EXPOSURE_DATA_QUALITY_AGENTSPEC_0_0_1,"worker-extract-data-from-files":WORKER_EXTRACT_DATA_FROM_FILES_AGENTSPEC_0_0_1,"worker-extract-kpis-from-quarterly-pdf":WORKER_EXTRACT_KPIS_FROM_QUARTERLY_PDF_AGENTSPEC_0_0_1,"worker-factor-analysis":WORKER_FACTOR_ANALYSIS_AGENTSPEC_0_0_1,"worker-financial-viz":WORKER_FINANCIAL_VIZ_AGENTSPEC_0_0_1,"worker-generate-weekly-reports":WORKER_GENERATE_WEEKLY_REPORTS_AGENTSPEC_0_0_1,"worker-github-agent":WORKER_GITHUB_AGENT_SPEC_0_0_1,"worker-grid-forecast":WORKER_GRID_FORECAST_AGENTSPEC_0_0_1,"worker-information-routing":WORKER_INFORMATION_ROUTING_AGENTSPEC_0_0_1,"worker-infrastructure-monitoring":WORKER_INFRASTRUCTURE_MONITORING_AGENTSPEC_0_0_1,"worker-insurance-claims-review":WORKER_INSURANCE_CLAIMS_REVIEW_AGENTSPEC_0_0_1,"worker-interview-guide":WORKER_INTERVIEW_GUIDE_AGENTSPEC_0_0_1,"worker-inventory-demand-planning":WORKER_INVENTORY_DEMAND_PLANNING_AGENTSPEC_0_0_1,"worker-job-hunter":WORKER_JOB_HUNTER_AGENTSPEC_0_0_1,"worker-mail-triage":WORKER_MAIL_TRIAGE_AGENTSPEC_0_0_1,"worker-marketing-analytics":WORKER_MARKETING_ANALYTICS_AGENTSPEC_0_0_1,"worker-medical-research-review":WORKER_MEDICAL_RESEARCH_REVIEW_AGENTSPEC_0_0_1,"worker-model-comparison":WORKER_MODEL_COMPARISON_AGENTSPEC_0_0_1,"worker-monitor-sales-kpis":WORKER_MONITOR_SALES_KPIS_AGENTSPEC_0_0_1,"worker-month-end-close":WORKER_MONTH_END_CLOSE_AGENTSPEC_0_0_1,"worker-news-aggregator":WORKER_NEWS_AGGREGATOR_AGENTSPEC_0_0_1,"worker-optimize-dynamic-pricing":WORKER_OPTIMIZE_DYNAMIC_PRICING_AGENTSPEC_0_0_1,"worker-optimize-grid-operations":WORKER_OPTIMIZE_GRID_OPERATIONS_AGENTSPEC_0_0_1,"worker-optimize-sql-query-performance":WORKER_OPTIMIZE_SQL_QUERY_PERFORMANCE_AGENTSPEC_0_0_1,"worker-performance-attribution":WORKER_PERFORMANCE_ATTRIBUTION_AGENTSPEC_0_0_1,"worker-pipeline-debugger":WORKER_PIPELINE_DEBUGGER_AGENTSPEC_0_0_1,"worker-pitcher":WORKER_PITCHER_AGENTSPEC_0_0_1,"worker-portfolio-accumulation":WORKER_PORTFOLIO_ACCUMULATION_AGENTSPEC_0_0_1,"worker-portfolio-risk":WORKER_PORTFOLIO_RISK_AGENTSPEC_0_0_1,"worker-predictive-maintenance":WORKER_PREDICTIVE_MAINTENANCE_AGENTSPEC_0_0_1,"worker-process-citizen-requests":WORKER_PROCESS_CITIZEN_REQUESTS_AGENTSPEC_0_0_1,"worker-process-clinical-trial-data":WORKER_PROCESS_CLINICAL_TRIAL_DATA_AGENTSPEC_0_0_1,"worker-process-financial-transactions":WORKER_PROCESS_FINANCIAL_TRANSACTIONS_AGENTSPEC_0_0_1,"worker-product-finder":WORKER_PRODUCT_FINDER_AGENTSPEC_0_0_1,"worker-quant-research":WORKER_QUANT_RESEARCH_AGENTSPEC_0_0_1,"worker-renewable-asset-performance":WORKER_RENEWABLE_ASSET_PERFORMANCE_AGENTSPEC_0_0_1,"worker-research-recruiter":WORKER_RESEARCH_RECRUITER_AGENTSPEC_0_0_1,"worker-rna-seq":WORKER_RNA_SEQ_AGENTSPEC_0_0_1,"worker-sales-forecasting":WORKER_SALES_FORECASTING_AGENTSPEC_0_0_1,"worker-sales-pipeline-board-report":WORKER_SALES_PIPELINE_BOARD_REPORT_AGENTSPEC_0_0_1,"worker-scenario-testing":WORKER_SCENARIO_TESTING_AGENTSPEC_0_0_1,"worker-scheduled-nightly-data-quality-checks":WORKER_SCHEDULED_NIGHTLY_DATA_QUALITY_CHECKS_AGENTSPEC_0_0_1,"worker-scientific-notebook-assistant":WORKER_SCIENTIFIC_NOTEBOOK_ASSISTANT_AGENTSPEC_0_0_1,"worker-single-cell-processing":WORKER_SINGLE_CELL_PROCESSING_AGENTSPEC_0_0_1,"worker-social-listening":WORKER_SOCIAL_LISTENING_AGENTSPEC_0_0_1,"worker-social-marketer":WORKER_SOCIAL_MARKETER_AGENTSPEC_0_0_1,"worker-spatial-data-analysis":WORKER_SPATIAL_DATA_ANALYSIS_AGENTSPEC_0_0_1,"worker-summarize-documents":WORKER_SUMMARIZE_DOCUMENTS_AGENTSPEC_0_0_1,"worker-sync-crm-contacts":WORKER_SYNC_CRM_CONTACTS_AGENTSPEC_0_0_1,"worker-thematic-analysis":WORKER_THEMATIC_ANALYSIS_AGENTSPEC_0_0_1,"worker-travel-recommender":WORKER_TRAVEL_RECOMMENDER_AGENTSPEC_0_0_1,"worker-trends-seeker":WORKER_TRENDS_SEEKER_AGENTSPEC_0_0_1,"worker-variant-analysis":WORKER_VARIANT_ANALYSIS_AGENTSPEC_0_0_1,"worker-weekly-executive-briefing":WORKER_WEEKLY_EXECUTIVE_BRIEFING_AGENTSPEC_0_0_1},AGENTSPECS={...AGENTSPECS$1};function resolveAgentId(Au){if(Au in AGENTSPECS)return Au;const lo=Au.lastIndexOf(":");if(lo>0){const $u=Au.slice(0,lo);if($u in AGENTSPECS)return $u}return Au}function getAgentspecs(Au){return AGENTSPECS[resolveAgentId(Au)]}const ANALYZE_CAMPAIGN_PERFORMANCE_TEAM_SPEC_0_0_1={id:"analyze-campaign-performance",version:"0.0.1",name:"Analyze Campaign Performance Team",description:"A multi-agent team that unifies marketing data from Google Ads, Meta, TikTok, LinkedIn, GA4, CRM, and email platforms. Normalises metrics into a unified view, detects performance anomalies in real time, and generates budget reallocation recommendations to maximise ROAS.",tags:["marketing","media","campaigns","analytics","advertising","social-media"],enabled:!0,icon:"megaphone",emoji:"📢",color:"#8250df",agentSpecId:"analyze-campaign-performance:0.0.1",orchestrationProtocol:"datalayer",executionMode:"sequential",supervisor:{name:"Campaign Analytics Orchestrator Agent",ref:"",model:"openai:gpt-4.1",goal:"",instructions:"",approval:"auto",canTerminate:!0},routingInstructions:"Start with Platform Connector to pull data from all ad platforms, then Metrics Normaliser for unified KPIs, then Anomaly Detector for real-time performance monitoring, then Budget Optimiser for reallocation recommendations. Escalate CPA spikes above 50% immediately.",delegation:{maxDepth:2,allowPeerDelegation:!1,includeGeneralPurpose:!1},context:{sharing:"shared"},validation:{timeout:"300s",retryOnFailure:!0,maxRetries:2},agents:[{id:"cp-1",name:"Platform Connector Agent",ref:"",role:"initiator",goal:"Pull campaign data from Google Ads, Meta, TikTok, LinkedIn, GA4, and email platforms",dependsOn:[],subagents:[],model:"openai:gpt-4.1",mcpServer:"Ad Platforms MCP",tools:["Google Ads Connector","Meta Ads Connector","TikTok Ads Connector","LinkedIn Ads Connector","GA4 Connector"],trigger:"Schedule: Every 4 hours",approval:"auto"},{id:"cp-2",name:"Metrics Normaliser Agent",ref:"",role:"contributor",goal:"Normalise CPA, ROAS, CTR, and attribution across all platforms into unified view",dependsOn:["cp-1"],subagents:[],model:"openai:gpt-4.1",mcpServer:"Analytics MCP",tools:["Metric Unifier","Currency Converter","Attribution Mapper","Naming Convention Resolver"],trigger:"",approval:"auto"},{id:"cp-3",name:"Anomaly Detector Agent",ref:"",role:"contributor",goal:"Monitor all KPIs for CTR drops, CPA spikes, and budget pacing issues",dependsOn:["cp-2"],subagents:[],model:"anthropic:claude-sonnet-4-20250514",mcpServer:"Monitoring MCP",tools:["Anomaly Scanner","Budget Pacer","Alert Generator","Campaign Pauser"],trigger:"",approval:"manual"},{id:"cp-4",name:"Budget Optimiser Agent",ref:"",role:"finalizer",goal:"Generate budget reallocation recommendations to maximise ROAS across channels",dependsOn:["cp-3"],subagents:[],model:"openai:gpt-4.1",mcpServer:"Optimisation MCP",tools:["ROAS Calculator","Budget Allocator","Scenario Modeller","Report Generator"],trigger:"",approval:"manual"}],reactionRules:[{id:"rr-camp-1",trigger:"budget_threshold_exceeded",action:"pause_and_notify",auto:!0,maxRetries:1,escalateAfterRetries:1,priority:"high"},{id:"rr-camp-2",trigger:"data_quality_low",action:"retry_collection",auto:!0,maxRetries:3,escalateAfterRetries:3,priority:"medium"}],healthMonitoring:{heartbeatInterval:"30s",staleThreshold:"120s",unresponsiveThreshold:"300s",stuckThreshold:"600s",maxRestartAttempts:3},notifications:{on_start:!0,on_completion:!0,on_failure:!0,on_escalation:!0},output:{formats:["pdf","csv","json"],template:"Campaign Performance Report",storage:"s3://reports/campaign-analytics/"}},ANALYZE_SUPPORT_TICKETS_TEAM_SPEC_0_0_1={id:"analyze-support-tickets",version:"0.0.1",name:"Analyze Support Tickets Team",description:"A multi-agent team that triages incoming support tickets, categorizes by urgency and topic, identifies recurring patterns, and generates resolution recommendations with escalation paths.",tags:["analytics","data","support","tickets"],enabled:!0,icon:"issue-opened",emoji:"🎫",color:"#bf8700",agentSpecId:"analyze-support-tickets:0.0.1",orchestrationProtocol:"datalayer",executionMode:"sequential",supervisor:{name:"Support Orchestrator Agent",ref:"",model:"openai:gpt-4.1",goal:"",instructions:"",approval:"auto",canTerminate:!0},routingInstructions:"Route new tickets to the Triage Agent first, then to the Categorizer, then to the Pattern Analyzer. Escalate P1/critical tickets immediately to human support leads.",delegation:{maxDepth:2,allowPeerDelegation:!1,includeGeneralPurpose:!1},context:{sharing:"shared"},validation:{timeout:"180s",retryOnFailure:!0,maxRetries:2},agents:[{id:"st-1",name:"Triage Agent",ref:"",role:"initiator",goal:"Ingest new support tickets and assess urgency level (P1-P4)",dependsOn:[],subagents:[],model:"openai:gpt-4.1",mcpServer:"Helpdesk MCP",tools:["Ticket Reader","Priority Classifier"],trigger:"Event: new ticket received",approval:"auto"},{id:"st-2",name:"Categorizer Agent",ref:"",role:"contributor",goal:"Categorize tickets by topic, product area, and sentiment",dependsOn:["st-1"],subagents:[],model:"openai:gpt-4.1",mcpServer:"NLP Pipeline MCP",tools:["Topic Classifier","Sentiment Analyzer","Product Tagger"],trigger:"",approval:"auto"},{id:"st-3",name:"Pattern Analyzer Agent",ref:"",role:"finalizer",goal:"Identify recurring issues and generate resolution recommendations",dependsOn:["st-2"],subagents:[],model:"anthropic:claude-sonnet-4-20250514",mcpServer:"Analytics MCP",tools:["Pattern Detector","Knowledge Base Search","Resolution Generator"],trigger:"",approval:"manual"}],reactionRules:[{id:"rr-supp-1",trigger:"ticket_surge_detected",action:"escalate_to_supervisor",auto:!0,maxRetries:2,escalateAfterRetries:2,priority:"high"},{id:"rr-supp-2",trigger:"classification_confidence_low",action:"request_human_review",auto:!1,maxRetries:1,escalateAfterRetries:1,priority:"medium"}],healthMonitoring:{heartbeatInterval:"15s",staleThreshold:"60s",unresponsiveThreshold:"180s",stuckThreshold:"300s",maxRestartAttempts:3},notifications:{on_start:!1,on_completion:!0,on_failure:!0,on_escalation:!0},output:{formats:["pdf","json"],template:"Support Ticket Analysis",storage:"s3://reports/support-analytics/"}},AUDIT_INVENTORY_LEVELS_TEAM_SPEC_0_0_1={id:"audit-inventory-levels",version:"0.0.1",name:"Audit Inventory Levels Team",description:"A multi-agent team that monitors inventory levels across warehouses, detects discrepancies between physical and system counts, forecasts demand by SKU, and generates automated reorder recommendations.",tags:["finance","automation","inventory","supply-chain"],enabled:!0,icon:"package",emoji:"📦",color:"#0969da",agentSpecId:"audit-inventory-levels:0.0.1",orchestrationProtocol:"datalayer",executionMode:"sequential",supervisor:{name:"Inventory Orchestrator Agent",ref:"",model:"openai:gpt-4.1",goal:"",instructions:"",approval:"auto",canTerminate:!0},routingInstructions:"Start with the Scanner to pull current levels, then Auditor to check discrepancies, then Forecaster for demand predictions, then Planner for reorder recommendations, then Reporter for the final audit report. Escalate critical shortages immediately.",delegation:{maxDepth:2,allowPeerDelegation:!1,includeGeneralPurpose:!1},context:{sharing:"shared"},validation:{timeout:"600s",retryOnFailure:!0,maxRetries:3},agents:[{id:"inv-1",name:"Inventory Scanner Agent",ref:"",role:"initiator",goal:"Pull current inventory levels from all warehouse management systems",dependsOn:[],subagents:[],model:"openai:gpt-4.1",mcpServer:"Warehouse MCP",tools:["WMS Connector","Barcode Scanner API"],trigger:"Schedule: Every 6 hours",approval:"auto"},{id:"inv-2",name:"Discrepancy Auditor Agent",ref:"",role:"contributor",goal:"Compare system counts vs physical counts and flag discrepancies",dependsOn:["inv-1"],subagents:[],model:"openai:gpt-4.1",mcpServer:"Audit MCP",tools:["Count Comparator","Discrepancy Logger","Shrinkage Calculator"],trigger:"",approval:"auto"},{id:"inv-3",name:"Demand Forecaster Agent",ref:"",role:"contributor",goal:"Forecast demand by SKU using historical sales and seasonal patterns",dependsOn:["inv-2"],subagents:[],model:"anthropic:claude-sonnet-4-20250514",mcpServer:"Analytics MCP",tools:["Time Series Model","Seasonal Analyzer","External Signals Fetcher"],trigger:"",approval:"auto"},{id:"inv-4",name:"Reorder Planner Agent",ref:"",role:"contributor",goal:"Calculate optimal reorder points and generate purchase order recommendations",dependsOn:["inv-3"],subagents:[],model:"openai:gpt-4.1",mcpServer:"Procurement MCP",tools:["EOQ Calculator","Supplier Catalog","PO Generator"],trigger:"",approval:"manual"},{id:"inv-5",name:"Audit Report Agent",ref:"",role:"finalizer",goal:"Compile inventory audit report with discrepancies, forecasts, and reorder plan",dependsOn:["inv-4"],subagents:[],model:"openai:gpt-4.1",mcpServer:"Document Generation MCP",tools:["PDF Generator","Chart Builder","Email Sender"],trigger:"",approval:"auto"}],reactionRules:[{id:"rr-inv-1",trigger:"stockout_risk_detected",action:"escalate_to_supervisor",auto:!0,maxRetries:1,escalateAfterRetries:1,priority:"high"},{id:"rr-inv-2",trigger:"discrepancy_threshold_exceeded",action:"flag_for_manual_audit",auto:!1,maxRetries:2,escalateAfterRetries:2,priority:"high"}],healthMonitoring:{heartbeatInterval:"30s",staleThreshold:"120s",unresponsiveThreshold:"300s",stuckThreshold:"600s",maxRestartAttempts:3},notifications:{on_start:!0,on_completion:!0,on_failure:!0,on_escalation:!0},output:{formats:["pdf","xlsx","csv"],template:"Inventory Audit Report",storage:"s3://reports/inventory-audits/"}},AUTOMATE_REGULATORY_REPORTING_TEAM_SPEC_0_0_1={id:"automate-regulatory-reporting",version:"0.0.1",name:"Automate Regulatory Reporting Team",description:"A multi-agent team that automates end-to-end regulatory reporting for financial institutions. Ingests data from trading systems, risk engines, and accounting platforms, reconciles positions, computes risk metrics, validates against regulatory rules (Basel III/IV, MiFID II, SOX), and generates submission-ready compliance reports with full audit trails.",tags:["finance","compliance","regulatory","risk","banking","audit"],enabled:!0,icon:"shield-check",emoji:"🏦",color:"#0969da",agentSpecId:"automate-regulatory-reporting:0.0.1",orchestrationProtocol:"datalayer",executionMode:"sequential",supervisor:{name:"Compliance Orchestrator Agent",ref:"",model:"openai:gpt-4.1",goal:"",instructions:"",approval:"auto",canTerminate:!0},routingInstructions:"Start with Data Ingestion to pull positions and transactions, then Risk Calculator for metric computation, then Reconciliation Agent to cross-check figures, then Validation Agent for regulatory rule checks, then Report Generator for submission-ready output. Escalate any reconciliation breaks above $10K immediately to the compliance team.",delegation:{maxDepth:2,allowPeerDelegation:!1,includeGeneralPurpose:!1},context:{sharing:"shared"},validation:{timeout:"900s",retryOnFailure:!0,maxRetries:2},agents:[{id:"reg-1",name:"Data Ingestion Agent",ref:"",role:"initiator",goal:"Extract positions, transactions, and P&L from trading and accounting systems",dependsOn:[],subagents:[],model:"openai:gpt-4.1",mcpServer:"Trading Systems MCP",tools:["Position Reader","Transaction Fetcher","P&L Extractor"],trigger:"Schedule: Monthly on the 3rd business day",approval:"auto"},{id:"reg-2",name:"Risk Calculator Agent",ref:"",role:"contributor",goal:"Compute Basel III/IV risk-weighted assets, capital ratios, and VaR metrics",dependsOn:["reg-1"],subagents:[],model:"anthropic:claude-sonnet-4-20250514",mcpServer:"Risk Engine MCP",tools:["RWA Calculator","VaR Engine","Capital Ratio Computer","Stress Test Runner"],trigger:"",approval:"auto"},{id:"reg-3",name:"Reconciliation Agent",ref:"",role:"contributor",goal:"Cross-check computed figures against source systems and flag discrepancies",dependsOn:["reg-2"],subagents:[],model:"openai:gpt-4.1",mcpServer:"Reconciliation MCP",tools:["Position Reconciler","Break Detector","Audit Logger"],trigger:"",approval:"auto"},{id:"reg-4",name:"Validation Agent",ref:"",role:"contributor",goal:"Validate all metrics against Basel III/IV, MiFID II, and SOX regulatory rules",dependsOn:["reg-3"],subagents:[],model:"openai:gpt-4.1",mcpServer:"Compliance Rules MCP",tools:["Basel Rule Validator","MiFID II Checker","SOX Control Verifier"],trigger:"",approval:"manual"},{id:"reg-5",name:"Report Generator Agent",ref:"",role:"finalizer",goal:"Generate submission-ready regulatory reports with full data lineage and audit trail",dependsOn:["reg-4"],subagents:[],model:"openai:gpt-4.1",mcpServer:"Document Generation MCP",tools:["PDF Generator","XBRL Formatter","Email Sender"],trigger:"",approval:"auto"}],reactionRules:[{id:"rr-reg-1",trigger:"compliance_violation_detected",action:"halt_and_escalate",auto:!0,maxRetries:0,escalateAfterRetries:0,priority:"critical"},{id:"rr-reg-2",trigger:"data_validation_failure",action:"retry_with_fallback",auto:!0,maxRetries:3,escalateAfterRetries:3,priority:"high"}],healthMonitoring:{heartbeatInterval:"15s",staleThreshold:"60s",unresponsiveThreshold:"120s",stuckThreshold:"300s",maxRestartAttempts:2},notifications:{on_start:!0,on_completion:!0,on_failure:!0,on_escalation:!0},output:{formats:["pdf","xbrl","json"],template:"Regulatory Submission Report",storage:"s3://reports/regulatory-submissions/"}},COMPREHENSIVE_SALES_ANALYTICS_TEAM_SPEC_0_0_1={id:"comprehensive-sales-analytics",version:"0.0.1",name:"Comprehensive Sales Analytics Team",description:"A multi-agent team that replaces a single KPI monitor with four specialized agents: a Data Collector that pulls real-time CRM metrics, an Anomaly Detector that flags statistical outliers, a Trend Analyzer that identifies patterns and forecasts, and a Report Generator that compiles executive dashboards and sends alerts. Together they deliver deeper insights, faster detection, and richer reporting than any single agent could.",tags:["sales","analytics","kpi","monitoring","horizontal"],enabled:!0,icon:"graph",emoji:"📈",color:"#1a7f37",agentSpecId:"comprehensive-sales-analytics:0.0.1",orchestrationProtocol:"datalayer",executionMode:"sequential",supervisor:{name:"Sales Analytics Supervisor",ref:"",model:"bedrock:us.anthropic.claude-sonnet-4-6",goal:"",instructions:"",approval:"auto",canTerminate:!0},routingInstructions:"Route data collection to KPI Collector first, then pass raw metrics to Anomaly Detector and Trend Analyzer in parallel, then aggregate all outputs into the Report Generator. Escalate if anomalies exceed the critical threshold (>25% deviation from target).",delegation:{maxDepth:2,allowPeerDelegation:!1,includeGeneralPurpose:!1},context:{sharing:"shared"},validation:{timeout:"300s",retryOnFailure:!0,maxRetries:3},agents:[{id:"sa-1",name:"KPI Data Collector",ref:"",role:"initiator",goal:"Pull real-time sales metrics from CRM, ERP, and marketing platforms. Normalize data into a unified schema with timestamps, dimensions (region, product line, rep), and measures (revenue, pipeline, conversion).",dependsOn:[],subagents:[],model:"openai:gpt-4.1",mcpServer:"CRM Data Server",tools:["get_sales_data","get_customer_list","API Connector"],trigger:"Schedule: Daily at 7:30 AM",approval:"auto"},{id:"sa-2",name:"Anomaly Detector",ref:"",role:"contributor",goal:"Apply statistical anomaly detection (Z-score, IQR, moving average) to the collected KPIs. Flag any metric deviating more than 10% from its rolling 30-day average. Classify anomalies as info, warning, or critical.",dependsOn:["sa-1"],subagents:[],model:"anthropic:claude-sonnet-4-20250514",mcpServer:"Analytics Server",tools:["run_analysis","Statistical Analysis","ML Predictor"],trigger:"",approval:"auto"},{id:"sa-3",name:"Trend Analyzer",ref:"",role:"contributor",goal:"Identify week-over-week, month-over-month, and quarter-over-quarter trends. Generate 30-day forecasts for each KPI using time-series models. Highlight the top 3 improving and top 3 declining metrics.",dependsOn:["sa-1"],subagents:[],model:"anthropic:claude-sonnet-4-20250514",mcpServer:"Analytics Server",tools:["run_analysis","generate_charts","Forecaster"],trigger:"",approval:"auto"},{id:"sa-4",name:"Executive Report Generator",ref:"",role:"finalizer",goal:"Compile all insights — raw KPIs, anomalies, trends, and forecasts — into a polished executive dashboard with charts, tables, and narrative commentary. Send the report via Slack and email. Highlight critical anomalies with a red-flag summary at the top.",dependsOn:["sa-2","sa-3"],subagents:[],model:"openai:gpt-4.1",mcpServer:"Document Generation MCP",tools:["PDF Generator","Chart Builder","Email Sender","Slack Notifier"],trigger:"",approval:"manual"}],reactionRules:[{id:"rr-sales-1",trigger:"anomaly_critical",action:"escalate_to_supervisor",auto:!0,maxRetries:2,escalateAfterRetries:2,priority:"high"},{id:"rr-sales-2",trigger:"data_stale",action:"retry_collection",auto:!0,maxRetries:3,escalateAfterRetries:3,priority:"medium"}],healthMonitoring:{heartbeatInterval:"30s",staleThreshold:"120s",unresponsiveThreshold:"300s",stuckThreshold:"600s",maxRestartAttempts:3},notifications:{on_start:!0,on_completion:!0,on_failure:!0,on_escalation:!0},output:{formats:["pdf","xlsx","json"],template:"Executive Sales Dashboard",storage:"s3://reports/sales-analytics/"}},CROP_MONITORING_TEAM_SPEC_0_0_1={id:"crop-monitoring",version:"0.0.1",name:"Crop Monitoring",description:"One agent, its data: Crop Monitoring follows crop vigour and growth over a season from the satellite imagery NASA Earthdata holds, and flags the fields that need attention.",tags:["example","scene","earth-observation","agriculture","earthdata","a2a"],enabled:!0,icon:"telescope",emoji:"🛰️",color:"#1a7f37",agentSpecId:"",orchestrationProtocol:"a2a",executionMode:"supervisor",supervisor:{name:"Crop Monitoring",ref:"",app:"crop-monitoring:0.0.2",model:"",goal:"",instructions:"",approval:"auto",canTerminate:!0},routingInstructions:"Crop Monitoring answers every request from the imagery itself, one search at a time, and reports what the granules show without adding to it.",entry:"crop-monitoring",suggestions:[{text:"How has crop vigour evolved over the last three months around 45.5N, 10.2E?",emoji:"🌱"},{text:"Which fields around 41.9N, 12.5E show a drop in vegetation this month compared with last?",emoji:"🌾"},{text:"Which datasets and granules cover the Po valley for June 2026?",emoji:"🛰️"},{text:"Save the June 2026 granules of the Po valley to my Space.",emoji:"💾"}],delegation:{maxDepth:0,allowPeerDelegation:!1,includeGeneralPurpose:!1},context:{sharing:"shared"},validation:{timeout:"300s",retryOnFailure:!1,maxRetries:0},agents:[{id:"crop-monitoring",name:"",ref:"",app:"crop-monitoring:0.0.2",runsIn:"runtime",role:"initiator",goal:"Take the person's field and period, search the imagery that covers them, and report the vigour, the growth and the fields to watch.",dependsOn:[],subagents:[],model:"",mcpServer:"",tools:[],trigger:"",approval:"auto"}]},DISASTER_ASSESSMENT_TEAM_SPEC_0_0_1={id:"disaster-assessment",version:"0.0.1",name:"Disaster Assessment",description:"An event desk in the browser that gets the area a disaster affected and the damage from Disaster Assessment, and what changed on the ground from Change detection, each on a runtime over A2A, each reading NASA Earthdata. Event response takes the event and reports; the two others read the imagery and answer.",tags:["example","scene","earth-observation","disaster","insurance","earthdata","a2a"],enabled:!0,icon:"pulse",emoji:"🛰️",color:"#cf222e",agentSpecId:"",orchestrationProtocol:"a2a",executionMode:"supervisor",supervisor:{name:"Event response",ref:"",app:"event-response:0.0.3",model:"",goal:"",instructions:"",approval:"auto",canTerminate:!0},routingInstructions:"Event response asks Disaster Assessment for the area and the damage, and Change detection for the change on the ground, one request each, and reports what they answer without adding to it.",entry:"event-response",suggestions:[{text:"Valencia, Spain, was flooded on 29 October 2024. What was affected, and what changed?",emoji:"🌊"},{text:"Fires burned around Los Angeles from 7 January 2025. Which imagery shows what changed?",emoji:"🔥"},{text:"The Ahr valley was hit by a storm on 14 July 2021. Chart the imagery found each day from 10 to 20 July.",emoji:"🌧️"},{text:"Send the Valencia flood assessment to the emergency services.",emoji:"📣"}],delegation:{maxDepth:1,allowPeerDelegation:!0,includeGeneralPurpose:!1},context:{sharing:"shared"},validation:{timeout:"600s",retryOnFailure:!1,maxRetries:0},agents:[{id:"event-response",name:"",ref:"",app:"event-response:0.0.3",runsIn:"browser",talksTo:[{member:"disaster-assessment",over:"a2a"},{member:"change-detection",over:"a2a"}],role:"initiator",goal:"Take the person's event, ask Disaster Assessment and Change detection for it, and report what they answered.",dependsOn:[],subagents:[],model:"",mcpServer:"",tools:[],trigger:"",approval:"auto"},{id:"disaster-assessment",name:"",ref:"",app:"disaster-assessment:0.0.2",runsIn:"runtime",role:"contributor",goal:"Estimate the area the event affected and the extent of the damage from the imagery before and after it, over A2A.",dependsOn:[],subagents:[],model:"",mcpServer:"",tools:[],trigger:"",approval:"auto"},{id:"change-detection",name:"",ref:"",app:"change-detection:0.0.2",runsIn:"runtime",role:"contributor",goal:"Find what changed on the ground between the two dates from the imagery, over A2A.",dependsOn:[],subagents:[],model:"",mcpServer:"",tools:[],trigger:"",approval:"auto"}]},JUPYTER_TEAM_SPEC_0_0_1={id:"jupyter",version:"0.0.1",name:"Jupyter Team",description:"Six agents working in the same Jupyter notebook: the Analyst adds and runs the cells, the Reviewer checks them and records what it finds, the Writer writes the result up between them, Decks turns what they found into a presentation, the Tutor teaches the person Python in the cells they have, and the Compactor rewrites the notebook as short as it can be without changing what it computes.",tags:["notebook","jupyter","collaboration","analysis","review","presentations","teaching","refactoring"],enabled:!0,icon:"book",emoji:"📓",color:"#F37726",agentSpecId:"",orchestrationProtocol:"datalayer",executionMode:"supervisor",supervisor:{name:"Jupyter Analyst",ref:"jupyter-data-analyst:0.0.1",model:"bedrock:us.anthropic.claude-sonnet-4-6",goal:"Keep the work in the notebook. Answer analysis requests directly; send a request to check something to the Reviewer, a request to write something up to the Writer, a request for slides to Decks, a question about the code to the Tutor and a request to tidy the notebook to the Compactor — and never leave results anywhere but the cells, or the deck made from them.",instructions:"",approval:"auto",canTerminate:!1},routingInstructions:'Send anything about exploring, computing, plotting or extending the analysis — "analyze", "plot", "compute", "add a cell that…" — to the Jupyter Analyst. Send anything about checking, verifying, doubting or re-running — "find what is wrong", "check this", "is this right", "re-run" — to Jupyter Reviewer. Send anything about explaining, summarising, writing up or verifying the wording of a conclusion to Jupyter Writer. Send anything about slides, a deck or a presentation — "make a deck of this", "turn the findings into slides", "present this", "add a slide" — to Jupyter Decks, which builds the deck from what the cells show and opens it beside the conversation. Send anything about understanding or learning — "what does this do", "why did this fail", "teach me", a request for an exercise — to Jupyter Tutor. Send anything about the shape of the notebook — shortening it, merging cells, removing dead code or stale outputs — to Jupyter Compactor. When a request is two of these, the one that produces cells goes first and the one that reads them follows: the Analyst before the Writer or Decks ("analyze this and write it up", "analyze this and make a deck"), the Tutor before the Compactor ("clean this up and explain what you did"). Never let the Compactor rewrite a notebook the person is still learning from without saying what changed. When none fits, answer directly rather than forcing the request onto a specialist.',suggestions:[{text:"Analyze the dataset",summary:"Analyze the dataset",icon:"graph",emoji:"🔎"},{text:"Find what is wrong",summary:"Find what is wrong",icon:"checklist",emoji:"🧐"},{text:"Verify the conclusion",summary:"Verify the conclusion",icon:"pencil",emoji:"✍️"},{text:"Turn the findings into a deck",summary:"Findings into a deck",icon:"project",emoji:"📊"},{text:"Explain this notebook cell by cell, as if I am new to Python",summary:"Cell by cell, for beginners",icon:"book",emoji:"📖"},{text:"Shorten this notebook without changing what it computes",summary:"Shorten the notebook",icon:"fold",emoji:"✂️"}],delegation:{maxDepth:2,allowPeerDelegation:!1,includeGeneralPurpose:!1},context:{sharing:"shared"},validation:{timeout:"300s",retryOnFailure:!0,maxRetries:1},agents:[{id:"analyst",name:"Jupyter Analyst",ref:"jupyter-data-analyst:0.0.1",role:"initiator",goal:"Explore the data in the open notebook — add the cells, run them, and leave the results on them for the others to build on.",dependsOn:[],subagents:[],model:"",mcpServer:"",tools:[],trigger:"",approval:"auto"},{id:"reviewer",name:"Jupyter Reviewer",ref:"jupyter-notebook-reviewer:0.0.1",role:"reviewer",goal:"Re-run what matters, find what is wrong or unsupported, and record the verdict in the notebook beside the code it concerns.",dependsOn:[],subagents:[],model:"",mcpServer:"",tools:[],trigger:"",approval:"auto"},{id:"writer",name:"Jupyter Writer",ref:"jupyter-notebook-writer:0.0.1",role:"finalizer",goal:"Write the analysis up between the cells — summary, explanations, conclusion — saying only what the cells support.",dependsOn:[],subagents:[],model:"",mcpServer:"",tools:[],trigger:"",approval:"auto"},{id:"decks",name:"Jupyter Decks",ref:"example-decks:0.0.1",role:"contributor",goal:"Turn what the notebook found into a deck — a title, the numbers as metrics or a chart, the conclusion — open it beside the conversation, and step through it on request.",dependsOn:[],subagents:[],model:"",mcpServer:"",tools:[],trigger:"",approval:"auto"},{id:"tutor",name:"Jupyter Tutor",ref:"jupyter-tutor:0.0.1",role:"contributor",goal:"Teach the person Python in the notebook they have open — what their code does, why it broke, and what to try next — leaving them able to write the next cell themselves.",dependsOn:[],subagents:[],model:"",mcpServer:"",tools:[],trigger:"",approval:"auto"},{id:"compactor",name:"Jupyter Compactor",ref:"jupyter-notebook-compactor:0.0.1",role:"finalizer",goal:"Rewrite the notebook as short as it can be without changing what it computes, and report exactly which cells were touched.",dependsOn:[],subagents:[{name:"CellFixer",ref:"jupyter-cell-fixer:0.0.1",description:"Fixes a failing cell and proves the fix by running it. Reach for this when compaction uncovers a cell that was already broken — repairing it is not part of compacting, and silently leaving it is worse.",instructions:""},{name:"NotebookReproducer",ref:"jupyter-notebook-reproducer:0.0.1",description:"Runs the notebook top to bottom on a fresh sandbox and reports what does not reproduce. Reach for this to prove a compaction changed nothing, which is the claim a compaction rests on.",instructions:""}],model:"",mcpServer:"",tools:[],trigger:"",approval:"manual"}],reactionRules:[{id:"rr-nb-1",trigger:"compaction_would_change_results",action:"request_human_review",auto:!1,maxRetries:0,escalateAfterRetries:0,priority:"high"},{id:"rr-nb-2",trigger:"learner_repeatedly_stuck",action:"escalate_to_supervisor",auto:!0,maxRetries:2,escalateAfterRetries:2,priority:"medium"},{id:"rr-nb-3",trigger:"review_found_unsupported_claim",action:"escalate_to_supervisor",auto:!0,maxRetries:1,escalateAfterRetries:1,priority:"medium"}],healthMonitoring:{heartbeatInterval:"15s",staleThreshold:"60s",unresponsiveThreshold:"180s",stuckThreshold:"300s",maxRestartAttempts:3},notifications:{on_start:!1,on_completion:!0,on_failure:!0,on_escalation:!0},output:{formats:["ipynb","markdown"],template:"Notebook Session Summary",storage:""}},MONTH_END_CLOSE_TEAM_SPEC_0_0_1={id:"month-end-close",version:"0.0.1",name:"Month-end Close",description:"One agent, its data: Month-end Close drives the close from the Odoo books, which it only reads — the checklist, the accruals to book, the reconciliation gaps that remain.",tags:["example","scene","accounting","finance","odoo","a2a"],enabled:!0,icon:"sync",emoji:"🧾",color:"#bf8700",agentSpecId:"",orchestrationProtocol:"a2a",executionMode:"supervisor",supervisor:{name:"Month-end Close",ref:"",app:"month-end-close:0.0.2",model:"",goal:"",instructions:"",approval:"auto",canTerminate:!0},routingInstructions:"Month-end Close answers every request from the books itself, one read at a time, and reports what the books hold without adding to it.",entry:"month-end-close",suggestions:[{text:"Where does the month-end close stand for last month? Give me the checklist.",emoji:"☑️"},{text:"Which accruals should be booked for last month? Show me the entries each rests on.",emoji:"🧾"},{text:"Chart last month's expenses by account against the month before.",emoji:"📊"},{text:"Post the accruals you suggested for last month.",emoji:"✍️"}],delegation:{maxDepth:0,allowPeerDelegation:!1,includeGeneralPurpose:!1},context:{sharing:"shared"},validation:{timeout:"300s",retryOnFailure:!1,maxRetries:0},agents:[{id:"month-end-close",name:"",ref:"",app:"month-end-close:0.0.2",runsIn:"runtime",role:"initiator",goal:"Take the person's request, read the period's books, and report where the close stands: what is done, what is to book, what is still open.",dependsOn:[],subagents:[],model:"",mcpServer:"",tools:[],trigger:"",approval:"auto"}]},NOTEBOOK_BENCHMARK_TEAM_SPEC_0_0_1={id:"notebook-benchmark",version:"0.0.1",name:"Notebook Benchmark Team",description:"Runs a notebook benchmark end to end: one agent executes it from a clean sandbox, a second compares what came out against what the evalset expected, and a third checks the comparison before it is published. Section 17's vertical slice.",tags:["benchmark","notebook","evaluation","orchestration"],enabled:!0,icon:"beaker",emoji:"🧪",color:"#1ABC9C",agentSpecId:"jupyter-data-analyst:0.0.1",orchestrationProtocol:"datalayer",executionMode:"sequential",supervisor:{name:"Benchmark Supervisor",ref:"",model:"bedrock:us.anthropic.claude-sonnet-4-6",goal:"",instructions:"",approval:"auto",canTerminate:!0},routingInstructions:"Place the runner first and wait for it: nothing can be analysed before the notebook has run. Give the analyst the runner's outputs and the evalset's expectations, and the reviewer the analyst's comparison. Answer with the reviewer's verdict and the evidence behind it, never with a summary of your own that nothing produced.",delegation:{maxDepth:2,allowPeerDelegation:!1,includeGeneralPurpose:!1},context:{sharing:"shared"},validation:{timeout:"900s",retryOnFailure:!0,maxRetries:2},agents:[{id:"runner",name:"Benchmark Runner",ref:"",role:"initiator",goal:"Execute the benchmark's notebook from a clean sandbox and return it with its outputs",dependsOn:[],subagents:[],model:"bedrock:us.anthropic.claude-sonnet-4-6",mcpServer:"",tools:["Notebook Executor"],trigger:"",approval:"auto"},{id:"analyst",name:"Benchmark Analyst",ref:"",role:"contributor",goal:"Compare what the notebook produced against what the evalset expected, and say where and by how much they differ",dependsOn:["runner"],subagents:[],model:"bedrock:us.anthropic.claude-sonnet-4-6",mcpServer:"",tools:["Notebook Reader"],trigger:"",approval:"auto"},{id:"reviewer",name:"Benchmark Reviewer",ref:"",role:"finalizer",goal:"Check the analyst's comparison against the notebook's own outputs and say whether the conclusion is supported by the evidence",dependsOn:["analyst"],subagents:[],model:"bedrock:us.anthropic.claude-sonnet-4-6",mcpServer:"",tools:["Notebook Reader"],trigger:"",approval:"auto"}]},OPTIMIZE_GRID_OPERATIONS_TEAM_SPEC_0_0_1={id:"optimize-grid-operations",version:"0.0.1",name:"Optimize Grid Operations Team",description:"A multi-agent team that processes millions of IoT sensor data points from smart meters, substations, and renewable generation assets. Predicts equipment failures 2–4 weeks in advance, optimises load balancing across the grid, and reduces unplanned downtime by 50%.",tags:["energy","utilities","smart-grid","iot","predictive-maintenance","sustainability"],enabled:!0,icon:"zap",emoji:"⚡",color:"#1a7f37",agentSpecId:"optimize-grid-operations:0.0.1",orchestrationProtocol:"datalayer",executionMode:"sequential",supervisor:{name:"Grid Operations Orchestrator Agent",ref:"",model:"openai:gpt-4.1",goal:"",instructions:"",approval:"auto",canTerminate:!0},routingInstructions:"Start with Sensor Ingestion to process real-time telemetry, then Anomaly Detector for pattern identification, then Failure Predictor for maintenance forecasting, then Grid Balancer for load optimisation. Escalate critical failure predictions (< 48h) immediately to operations dispatch.",delegation:{maxDepth:2,allowPeerDelegation:!1,includeGeneralPurpose:!1},context:{sharing:"shared"},validation:{timeout:"600s",retryOnFailure:!0,maxRetries:3},agents:[{id:"grid-1",name:"Sensor Ingestion Agent",ref:"",role:"initiator",goal:"Ingest and process real-time telemetry from SCADA, smart meters, and IoT gateways",dependsOn:[],subagents:[],model:"openai:gpt-4.1",mcpServer:"SCADA MCP",tools:["SCADA Connector","Smart Meter Reader","IoT Gateway Adapter","Time Series Processor"],trigger:"Schedule: Every 5 minutes",approval:"auto"},{id:"grid-2",name:"Anomaly Detector Agent",ref:"",role:"contributor",goal:"Detect vibration, temperature, and voltage anomalies across all grid assets",dependsOn:["grid-1"],subagents:[],model:"openai:gpt-4.1",mcpServer:"Monitoring MCP",tools:["Vibration Analyzer","Temperature Anomaly Detector","Voltage Pattern Scanner","Historical Comparator"],trigger:"",approval:"auto"},{id:"grid-3",name:"Failure Predictor Agent",ref:"",role:"contributor",goal:"Predict equipment failures 2–4 weeks in advance using anomaly patterns and failure history",dependsOn:["grid-2"],subagents:[],model:"anthropic:claude-sonnet-4-20250514",mcpServer:"Predictive Analytics MCP",tools:["Failure Correlation Engine","Risk Scorer","Maintenance Scheduler","Work Order Generator"],trigger:"",approval:"manual"},{id:"grid-4",name:"Grid Balancer Agent",ref:"",role:"finalizer",goal:"Optimise real-time load balancing across renewable and conventional generation sources",dependsOn:["grid-3"],subagents:[],model:"openai:gpt-4.1",mcpServer:"Grid Control MCP",tools:["Load Forecaster","Renewable Integration Model","Dispatch Optimiser","Grid Stability Checker"],trigger:"",approval:"auto"}],reactionRules:[{id:"rr-grid-1",trigger:"grid_instability_detected",action:"emergency_rebalance",auto:!0,maxRetries:1,escalateAfterRetries:1,priority:"critical"},{id:"rr-grid-2",trigger:"forecast_deviation_high",action:"recalibrate_model",auto:!0,maxRetries:2,escalateAfterRetries:2,priority:"medium"}],healthMonitoring:{heartbeatInterval:"10s",staleThreshold:"30s",unresponsiveThreshold:"60s",stuckThreshold:"120s",maxRestartAttempts:5},notifications:{on_start:!0,on_completion:!0,on_failure:!0,on_escalation:!0},output:{formats:["json","csv","pdf"],template:"Grid Operations Dashboard",storage:"s3://reports/grid-operations/"}},PROCESS_CITIZEN_REQUESTS_TEAM_SPEC_0_0_1={id:"process-citizen-requests",version:"0.0.1",name:"Process Citizen Requests Team",description:"A multi-agent team that automates citizen request processing for government agencies. Classifies and triages permits, FOIA requests, and benefit claims from multiple channels. Models policy impacts across population datasets and ensures every automated decision is explainable, auditable, and compliant with transparency mandates.",tags:["government","public-sector","civic","policy","compliance","transparency"],enabled:!0,icon:"organization",emoji:"🏛️",color:"#0550ae",agentSpecId:"process-citizen-requests:0.0.1",orchestrationProtocol:"datalayer",executionMode:"sequential",supervisor:{name:"Citizen Services Orchestrator Agent",ref:"",model:"openai:gpt-4.1",goal:"",instructions:"",approval:"auto",canTerminate:!0},routingInstructions:"Route incoming citizen requests to the Intake Agent for classification and triage, then to the Case Processor for handling and routing, then to the Policy Analyst for impact assessment on relevant items, then to the Transparency Agent for audit trail and public documentation. Escalate urgent citizen safety issues immediately to supervisors.",delegation:{maxDepth:2,allowPeerDelegation:!1,includeGeneralPurpose:!1},context:{sharing:"shared"},validation:{timeout:"300s",retryOnFailure:!0,maxRetries:2},agents:[{id:"cit-1",name:"Intake & Classification Agent",ref:"",role:"initiator",goal:"Classify, triage, and route citizen submissions from web portals, email, and documents",dependsOn:[],subagents:[],model:"openai:gpt-4.1",mcpServer:"Citizen Portal MCP",tools:["Request Classifier","Urgency Assessor","Jurisdiction Router","OCR Scanner"],trigger:"Event: new citizen request received",approval:"auto"},{id:"cit-2",name:"Case Processor Agent",ref:"",role:"contributor",goal:"Process and route requests to appropriate departments with required documentation",dependsOn:["cit-1"],subagents:[],model:"openai:gpt-4.1",mcpServer:"Case Management MCP",tools:["Case Creator","Document Assembler","Department Router","Status Tracker"],trigger:"",approval:"auto"},{id:"cit-3",name:"Policy Impact Analyst Agent",ref:"",role:"contributor",goal:"Model policy outcomes across population datasets with scenario simulation",dependsOn:["cit-2"],subagents:[],model:"anthropic:claude-sonnet-4-20250514",mcpServer:"Policy Analytics MCP",tools:["Monte Carlo Simulator","Demographic Analyzer","Budget Impact Model","Scenario Comparator"],trigger:"",approval:"manual"},{id:"cit-4",name:"Transparency & Audit Agent",ref:"",role:"finalizer",goal:"Generate explainable decision documentation with full audit trail for public record",dependsOn:["cit-3"],subagents:[],model:"openai:gpt-4.1",mcpServer:"Compliance MCP",tools:["Decision Explainer","Audit Trail Builder","FOIA Compliance Checker","Public Record Generator"],trigger:"",approval:"auto"}],reactionRules:[{id:"rr-cit-1",trigger:"priority_request_detected",action:"fast_track_processing",auto:!0,maxRetries:2,escalateAfterRetries:2,priority:"high"},{id:"rr-cit-2",trigger:"policy_ambiguity_detected",action:"request_human_review",auto:!1,maxRetries:1,escalateAfterRetries:1,priority:"medium"}],healthMonitoring:{heartbeatInterval:"30s",staleThreshold:"120s",unresponsiveThreshold:"300s",stuckThreshold:"600s",maxRestartAttempts:3},notifications:{on_start:!1,on_completion:!0,on_failure:!0,on_escalation:!0},output:{formats:["pdf","json"],template:"Citizen Request Processing Report",storage:"s3://reports/citizen-requests/"}},PROCESS_CLINICAL_TRIAL_DATA_TEAM_SPEC_0_0_1={id:"process-clinical-trial-data",version:"0.0.1",name:"Process Clinical Trial Data Team",description:"A multi-agent team that automates clinical trial data processing across dozens of trial sites. Harmonises patient records and lab results to CDISC SDTM format, detects safety signals and adverse events in real time, and prepares submission-ready datasets — all with strict HIPAA and GxP compliance guardrails.",tags:["healthcare","pharma","clinical-trials","patient-data","compliance"],enabled:!0,icon:"heart",emoji:"🏥",color:"#cf222e",agentSpecId:"process-clinical-trial-data:0.0.1",orchestrationProtocol:"datalayer",executionMode:"sequential",supervisor:{name:"Clinical Data Orchestrator Agent",ref:"",model:"anthropic:claude-sonnet-4-20250514",goal:"",instructions:"",approval:"auto",canTerminate:!0},routingInstructions:"Route incoming data through the Ingestion Agent first for format detection and parsing, then to Harmonisation Agent for CDISC SDTM standardisation, then Safety Monitor for adverse event screening, then Submission Preparer for final dataset assembly. Escalate serious adverse events (SAEs) immediately to the medical officer.",delegation:{maxDepth:2,allowPeerDelegation:!1,includeGeneralPurpose:!1},context:{sharing:"shared"},validation:{timeout:"600s",retryOnFailure:!0,maxRetries:2},agents:[{id:"ct-1",name:"Data Ingestion Agent",ref:"",role:"initiator",goal:"Ingest patient records, lab results, and CRFs from clinical sites",dependsOn:[],subagents:[],model:"openai:gpt-4.1",mcpServer:"Clinical EDC MCP",tools:["Medidata Connector","Veeva Vault Reader","Oracle Clinical Adapter","Format Detector"],trigger:"Event: new data batch received from site",approval:"auto"},{id:"ct-2",name:"Harmonisation Agent",ref:"",role:"contributor",goal:"Standardise all data to CDISC SDTM format with MedDRA coding",dependsOn:["ct-1"],subagents:[],model:"openai:gpt-4.1",mcpServer:"Data Standards MCP",tools:["SDTM Mapper","MedDRA Coder","Unit Converter","Site Normaliser"],trigger:"",approval:"auto"},{id:"ct-3",name:"Safety Monitor Agent",ref:"",role:"contributor",goal:"Screen every data point for adverse events and safety signals",dependsOn:["ct-2"],subagents:[],model:"anthropic:claude-sonnet-4-20250514",mcpServer:"Safety Database MCP",tools:["AE Classifier","Signal Detector","SAE Escalator","Evidence Trail Builder"],trigger:"",approval:"manual"},{id:"ct-4",name:"Submission Preparer Agent",ref:"",role:"finalizer",goal:"Assemble submission-ready SDTM datasets with validation and define.xml",dependsOn:["ct-3"],subagents:[],model:"openai:gpt-4.1",mcpServer:"Submission MCP",tools:["Dataset Validator","Define.xml Generator","PDF Report Builder","Compliance Checker"],trigger:"",approval:"auto"}],reactionRules:[{id:"rr-clin-1",trigger:"safety_signal_detected",action:"halt_and_escalate",auto:!0,maxRetries:0,escalateAfterRetries:0,priority:"critical"},{id:"rr-clin-2",trigger:"data_integrity_violation",action:"quarantine_and_notify",auto:!0,maxRetries:1,escalateAfterRetries:1,priority:"critical"}],healthMonitoring:{heartbeatInterval:"10s",staleThreshold:"45s",unresponsiveThreshold:"90s",stuckThreshold:"180s",maxRestartAttempts:2},notifications:{on_start:!0,on_completion:!0,on_failure:!0,on_escalation:!0},output:{formats:["pdf","json","xml"],template:"Clinical Trial Data Report",storage:"s3://reports/clinical-trials/"}},SALES_AND_ACCOUNTING_TEAM_SPEC_0_0_1={id:"sales-and-accounting",version:"0.0.1",name:"Sales and Accounting",description:"A sales desk in the browser that gets financial reports from an accounting application on a runtime, over A2A. Sales takes the request and reports the answer; Accounting reads the Odoo books and answers.",tags:["example","sales","accounting","finance","a2a","odoo"],enabled:!0,icon:"people",emoji:"🤝",color:"#0969da",agentSpecId:"",orchestrationProtocol:"a2a",executionMode:"supervisor",supervisor:{name:"Sales",ref:"",app:"sales:0.0.3",model:"",goal:"",instructions:"",approval:"auto",canTerminate:!0},routingInstructions:"Sales asks Accounting for every figure from the books, one request each time, and reports what Accounting answers without adding to it.",entry:"sales",suggestions:[{text:"Which customer invoices are still open, and how much is due in total?",emoji:"🧾"},{text:"Chart the aged receivables as of today, by customer.",emoji:"⏳"},{text:"Which invoices make up the largest balance due? Show me each one.",emoji:"🔎"},{text:"Send a payment reminder to every customer whose invoice is overdue.",emoji:"✉️"}],delegation:{maxDepth:1,allowPeerDelegation:!0,includeGeneralPurpose:!1},context:{sharing:"shared"},validation:{timeout:"300s",retryOnFailure:!1,maxRetries:0},agents:[{id:"sales",name:"",ref:"",app:"sales:0.0.3",runsIn:"browser",talksTo:[{member:"accounting",over:"a2a"}],role:"initiator",goal:"Take the person's request for a financial report, ask Accounting for it, and hand over what Accounting answered.",dependsOn:[],subagents:[],model:"",mcpServer:"",tools:[],trigger:"",approval:"auto"},{id:"accounting",name:"",ref:"",app:"accounting:0.0.2",runsIn:"runtime",role:"contributor",goal:"Answer report requests from the Odoo books, read only, over A2A.",dependsOn:[],subagents:[],model:"",mcpServer:"",tools:[],trigger:"",approval:"auto"}]},SYNC_CRM_CONTACTS_TEAM_SPEC_0_0_1={id:"sync-crm-contacts",version:"0.0.1",name:"Sync CRM Contacts Team",description:"A multi-agent team that collects and aggregates contact data from multiple CRM sources, analyzes and deduplicates records, writes cleaned data back, and generates sync summary reports.",tags:["sales","crm","data-sync","deduplication"],enabled:!0,icon:"people",emoji:"🔄",color:"#0969da",agentSpecId:"sync-crm-contacts:0.0.1",orchestrationProtocol:"datalayer",executionMode:"sequential",supervisor:{name:"CRM Orchestrator Agent",ref:"",model:"bedrock:us.anthropic.claude-sonnet-4-6",goal:"",instructions:"",approval:"auto",canTerminate:!0},routingInstructions:"Route data collection tasks to the Data Collector first, then analysis, then sync, then reporting. Escalate to human if sync fails 3 times.",delegation:{maxDepth:2,allowPeerDelegation:!1,includeGeneralPurpose:!1},context:{sharing:"shared"},validation:{timeout:"300s",retryOnFailure:!0,maxRetries:3},agents:[{id:"tm-1",name:"Data Collector Agent",ref:"",role:"initiator",goal:"Collect and aggregate contact data from multiple CRM sources",dependsOn:[],subagents:[],model:"openai:gpt-4.1",mcpServer:"Data Processing MCP",tools:["API Connector","Data Parser"],trigger:"Schedule: Daily at 2:00 AM",approval:"auto"},{id:"tm-2",name:"Analyzer Agent",ref:"",role:"contributor",goal:"Analyze collected data and identify patterns and duplicates",dependsOn:["tm-1"],subagents:[],model:"bedrock:us.anthropic.claude-sonnet-4-6",mcpServer:"Analytics MCP",tools:["Statistical Analysis","ML Predictor","Deduplicator"],trigger:"",approval:"manual"},{id:"tm-3",name:"Sync Writer Agent",ref:"",role:"contributor",goal:"Write cleaned and merged contacts back to the CRM systems",dependsOn:["tm-2"],subagents:[],model:"openai:gpt-4.1",mcpServer:"CRM Write MCP",tools:["Salesforce Connector","HubSpot Connector"],trigger:"",approval:"manual"},{id:"tm-4",name:"Report Generator Agent",ref:"",role:"finalizer",goal:"Generate sync summary reports and send notifications",dependsOn:["tm-3"],subagents:[],model:"openai:gpt-4.1",mcpServer:"Document Generation MCP",tools:["PDF Generator","Chart Builder","Email Sender"],trigger:"",approval:"auto"}],reactionRules:[{id:"rr-crm-1",trigger:"sync_conflict_detected",action:"log_and_skip",auto:!0,maxRetries:3,escalateAfterRetries:3,priority:"medium"},{id:"rr-crm-2",trigger:"api_rate_limit_hit",action:"backoff_and_retry",auto:!0,maxRetries:5,escalateAfterRetries:5,priority:"low"}],healthMonitoring:{heartbeatInterval:"30s",staleThreshold:"120s",unresponsiveThreshold:"300s",stuckThreshold:"600s",maxRestartAttempts:3},notifications:{on_start:!1,on_completion:!0,on_failure:!0,on_escalation:!1},output:{formats:["json","csv"],template:"CRM Sync Summary",storage:"s3://reports/crm-sync/"}},TEAM_SPECS={"analyze-campaign-performance":ANALYZE_CAMPAIGN_PERFORMANCE_TEAM_SPEC_0_0_1,"analyze-support-tickets":ANALYZE_SUPPORT_TICKETS_TEAM_SPEC_0_0_1,"audit-inventory-levels":AUDIT_INVENTORY_LEVELS_TEAM_SPEC_0_0_1,"automate-regulatory-reporting":AUTOMATE_REGULATORY_REPORTING_TEAM_SPEC_0_0_1,"comprehensive-sales-analytics":COMPREHENSIVE_SALES_ANALYTICS_TEAM_SPEC_0_0_1,"crop-monitoring":CROP_MONITORING_TEAM_SPEC_0_0_1,"disaster-assessment":DISASTER_ASSESSMENT_TEAM_SPEC_0_0_1,jupyter:JUPYTER_TEAM_SPEC_0_0_1,"month-end-close":MONTH_END_CLOSE_TEAM_SPEC_0_0_1,"notebook-benchmark":NOTEBOOK_BENCHMARK_TEAM_SPEC_0_0_1,"optimize-grid-operations":OPTIMIZE_GRID_OPERATIONS_TEAM_SPEC_0_0_1,"process-citizen-requests":PROCESS_CITIZEN_REQUESTS_TEAM_SPEC_0_0_1,"process-clinical-trial-data":PROCESS_CLINICAL_TRIAL_DATA_TEAM_SPEC_0_0_1,"sales-and-accounting":SALES_AND_ACCOUNTING_TEAM_SPEC_0_0_1,"sync-crm-contacts":SYNC_CRM_CONTACTS_TEAM_SPEC_0_0_1},VOICE_CATALOGUE={"kokoro-af-heart":{id:"kokoro-af-heart",version:"0.0.1",name:"Heart",description:"A warm American English voice, Kokoro's best graded (A).",engine:"kokoro",model:"kokoro-82m",voice:"af_heart",languages:["en-US"],where:["server"],licence:{weights:"Apache-2.0"},attribution:"",watermark:!1,sample:"Hello. I read the answers aloud, sentence by sentence, as they are written."},"kokoro-bf-emma":{id:"kokoro-bf-emma",version:"0.0.1",name:"Emma",description:"A clear British English voice.",engine:"kokoro",model:"kokoro-82m",voice:"bf_emma",languages:["en-GB"],where:["server"],licence:{weights:"Apache-2.0"},attribution:"",watermark:!1,sample:"Hello. I read the answers aloud, sentence by sentence, as they are written."},"kokoro-ff-siwis":{id:"kokoro-ff-siwis",version:"0.0.1",name:"Siwis",description:"A French voice, Kokoro's only one, trained on the SIWIS French Speech Synthesis Database, whose licence asks for its attribution.",engine:"kokoro",model:"kokoro-82m",voice:"ff_siwis",languages:["fr-FR"],where:["server"],licence:{weights:"Apache-2.0",dataset:"CC-BY-4.0"},attribution:"Trained on the SIWIS French Speech Synthesis Database, by Pierre-Edouard Honnet, Alexandros Lazaridis, Philip N. Garner and Junichi Yamagishi (Idiap Research Institute), under CC BY 4.0.",watermark:!1,sample:"Bonjour. Je lis les réponses à voix haute, phrase par phrase, à mesure qu'elles s'écrivent."}},SPEECH_MODEL_CATALOGUE={"kokoro-82m":{id:"kokoro-82m",version:"0.0.1",name:"Kokoro 82M",description:"Text to speech on Datalayer's servers, on CPU: hexgrad's Kokoro-82M v1.0 exported to ONNX, in full precision, with the voices file that holds its 54 voices, run by kokoro-onnx. Its phonemes come from eSpeak NG (GPL-3.0), which runs on the server and is never sent to a browser. Full precision, not the 8-bit export: on a 16-core CPU the 8-bit one speaks slower than real time (6 s for 3.9 s of speech), this one about four times faster than real time (1 s).",provider:"hexgrad",task:"tts",engine:"kokoro-onnx",dtype:"fp32",languages:["en","fr","es","it","pt","hi","ja","zh"],where:["server"],streaming:!1,licence:{weights:"Apache-2.0",code:"MIT"},attribution:"",upstream:"https://huggingface.co/hexgrad/Kokoro-82M",revision:"model-files-v1.0",files:[{path:"kokoro-v1.0.onnx",sha256:"7d5df8ecf7d4b1878015a32686053fd0eebe2bc377234608764cc0ef3636a6c5",size:325532387},{path:"voices-v1.0.bin",sha256:"bca610b8308e8d99f32e6fe4197e7ec01679264efed0cac9140fe9c29f1fbf7d",size:28214398}]},"moonshine-base-en":{id:"moonshine-base-en",version:"0.0.1",name:"Moonshine Base (English)",description:"Speech to text in the browser, in English: Useful Sensors' Moonshine Base (61M parameters), its ONNX export quantized to 8 bits, run by transformers.js. One of the English models whose weights are MIT; the legacy non-English Moonshine models are under a non-commercial licence and are not listed.",provider:"usefulsensors",task:"stt",engine:"transformers.js",dtype:"q8",languages:["en"],where:["device"],streaming:!1,licence:{weights:"MIT",code:"MIT"},attribution:"",upstream:"https://huggingface.co/UsefulSensors/moonshine-base",revision:"b1e9b6aae3c3c7298f10c3798393fdf38e8fbbad",files:[{path:"config.json",sha256:"fab7241d1e9fc6c2370c4c6dfb5da79bb54d67ed9ab6b507ac51d29d2abe01d1",size:922},{path:"generation_config.json",sha256:"f9b3f711b57be7def2e50a8942f64f36ee0a55fad5b84ff93a687b6c5bcc1d44",size:147},{path:"preprocessor_config.json",sha256:"fa43a7017ef85cd1d0fba0d9aae77c8adb16990ae6f11115631f41ec5d8aa679",size:128},{path:"special_tokens_map.json",sha256:"ca3d163bab055381827226140568f3bef7eaac187cebd76878e0b63e9e442356",size:3},{path:"tokenizer.json",sha256:"7b913404bdd039af4756783218af4440bc07fb7d6d8258d677e34f95b3ec416f",size:3761754},{path:"tokenizer_config.json",sha256:"edaee394565d428ea98a663ae7209cdcfeefc5585c42d7a570ff7c986df2cd15",size:135735},{path:"onnx/encoder_model_quantized.onnx",sha256:"1dd9ab0a7f987113d30affcba5a068d11c8f90fa0223caa3e491ade431ad9751",size:20513063},{path:"onnx/decoder_model_merged_quantized.onnx",sha256:"cc9f3cd6698a369c6008b41aa60aa3fb3322e7f03c9bdf19d8e6b7200afca4f3",size:42498870}]},"moonshine-tiny-en":{id:"moonshine-tiny-en",version:"0.0.1",name:"Moonshine Tiny (English)",description:"Speech to text in the browser, in English: Useful Sensors' Moonshine Tiny (27M parameters), its ONNX export quantized to 8 bits, run by transformers.js. One of the English models whose weights are MIT; the legacy non-English Moonshine models are under a non-commercial licence and are not listed.",provider:"usefulsensors",task:"stt",engine:"transformers.js",dtype:"q8",languages:["en"],where:["device"],streaming:!1,licence:{weights:"MIT",code:"MIT"},attribution:"",upstream:"https://huggingface.co/UsefulSensors/moonshine-tiny",revision:"a6da1241cd305dcd64eab1edbd615f2bb9aabb95",files:[{path:"config.json",sha256:"558e1e02069137c796ace1e50c48d8fe451f04a295929138e6bea885517f0edb",size:921},{path:"generation_config.json",sha256:"f9b3f711b57be7def2e50a8942f64f36ee0a55fad5b84ff93a687b6c5bcc1d44",size:147},{path:"preprocessor_config.json",sha256:"fa43a7017ef85cd1d0fba0d9aae77c8adb16990ae6f11115631f41ec5d8aa679",size:128},{path:"special_tokens_map.json",sha256:"ca3d163bab055381827226140568f3bef7eaac187cebd76878e0b63e9e442356",size:3},{path:"tokenizer.json",sha256:"7b913404bdd039af4756783218af4440bc07fb7d6d8258d677e34f95b3ec416f",size:3761754},{path:"tokenizer_config.json",sha256:"edaee394565d428ea98a663ae7209cdcfeefc5585c42d7a570ff7c986df2cd15",size:135735},{path:"onnx/encoder_model_quantized.onnx",sha256:"c6fc4b7bc5af75c0591fd157a1f3829b533d18e9769a888fd95a62e470dd4f4a",size:7937661},{path:"onnx/decoder_model_merged_quantized.onnx",sha256:"eed87831c3a6103534aae7d47a5d485025c659a1323901513961c39fe8a1a367",size:20243286}]},"silero-vad":{id:"silero-vad",version:"0.0.1",name:"Silero VAD",description:"Where speech starts and ends in what the microphone heard, in the browser: Silero VAD (about 2 MB), the build @ricky0123/vad-web 0.0.31 ships and runs on onnxruntime-web. Push-to-talk keeps the speech it finds and drops the rest.",provider:"snakers4",task:"vad",engine:"vad-web",dtype:"fp32",languages:[],where:["device"],streaming:!0,licence:{weights:"MIT",code:"ISC"},attribution:"",upstream:"https://github.com/snakers4/silero-vad",revision:"0.0.31",files:[{path:"silero_vad_legacy.onnx",sha256:"a35ebf52fd3ce5f1469b2a36158dba761bc47b973ea3382b3186ca15b1f5af28",size:1807522}]},"whisper-base":{id:"whisper-base",version:"0.0.1",name:"Whisper Base",description:"Speech to text in the browser for the languages Moonshine's MIT models do not speak, French first: OpenAI's Whisper base (74M parameters, 99 languages), its ONNX export quantized to 8 bits, run by transformers.js. A clip at a time.",provider:"openai",task:"stt",engine:"transformers.js",dtype:"q8",languages:["en","fr"],where:["device"],streaming:!1,licence:{weights:"MIT",code:"MIT"},attribution:"",upstream:"https://huggingface.co/openai/whisper-base",revision:"1846881b6b3a3024392c1eea3ad983695bc23925",files:[{path:"config.json",sha256:"f4d0608f7d918166da7edb3e188de5ef1bfe70d9802e785d271fd88111e9cf4b",size:2243},{path:"generation_config.json",sha256:"61070cf8de25b1e9256e8e102ded49d8d24a8369ed36ef84fdf21549e68125a0",size:3832},{path:"preprocessor_config.json",sha256:"a6a76d28c93edb273669eb9e0b0636a2bddbb1272c3261e47b7ca6dfdbac1b8d",size:339},{path:"special_tokens_map.json",sha256:"e67ae3a0aaa99abcd9f187138e12db1f65c16a14761c50ef10eef2c174a7a691",size:2194},{path:"tokenizer.json",sha256:"27fc476bfe7f17299480be2273fc0608e4d5a99aba2ab5dec5374b4482d1a566",size:2480466},{path:"tokenizer_config.json",sha256:"2e036e4dbacfdeb7242c7d4ec4149f4a16e86026048f94d1637e3a8ee9c6a573",size:282682},{path:"added_tokens.json",sha256:"9715fd2243b6f06a5858b5e32950d2853f73dd5bc201aafcf76f5082a2d8acd1",size:34604},{path:"normalizer.json",sha256:"bf1c507dc8724ca9cf9903640dacfb69dae2f00edee4f21ceba106a7392f26dd",size:52666},{path:"vocab.json",sha256:"50d6a919f0a0601d56a04eb583c780d18553aa388254ba3158eb6a00f13e2c1a",size:1036584},{path:"onnx/encoder_model_quantized.onnx",sha256:"5862993336bf33acd23736071aae2b32261d3b1b2f37780194460d4ef974dd46",size:23201314},{path:"onnx/decoder_model_merged_quantized.onnx",sha256:"fa3ef9902734ce5ae6f9ef2bdb2ba9a6c4b5785b09f4f420ce036573dc9d090b",size:53693315}]},"whisper-large-v3-turbo":{id:"whisper-large-v3-turbo",version:"0.0.1",name:"Whisper Large v3 Turbo",description:"Speech to text on Datalayer's servers, on CPU: OpenAI's Whisper large-v3-turbo (809M parameters, 99 languages), converted to CTranslate2 in half precision and run by faster-whisper, its weights quantized to 8 bits when loaded. A recording of up to a minute at a time; the language is detected when the page does not say it.",provider:"openai",task:"stt",engine:"faster-whisper",dtype:"float16",languages:["en","fr","es","it","pt","de","nl","ja","zh","hi"],where:["server"],streaming:!1,licence:{weights:"MIT",code:"MIT"},attribution:"",upstream:"https://huggingface.co/openai/whisper-large-v3-turbo",revision:"0a363e9161cbc7ed1431c9597a8ceaf0c4f78fcf",files:[{path:"config.json",sha256:"b0253ea6c0d3bea6b1e19e91a02acfd3b53f4467362efcb5a3e6b16c9b3a9b7e",size:2263},{path:"preprocessor_config.json",sha256:"7ccc62c6f2765af1f3b46c00c9b5894426835a05021c8b9c01eecb6dfb542711",size:340},{path:"tokenizer.json",sha256:"297b13372ac43916285644fb9687add3cc62ee2a1adb60da3dc25cc94c1871fd",size:2710337},{path:"vocabulary.json",sha256:"c69260f2ab26d659b7c398f9a2b2b48ed0df16c3b47d7326782fd9cba71690c1",size:1068114},{path:"model.bin",sha256:"e76620f83d5f5b69efd3d87e3dc180c1bd21df9fbebacfd4335e5e1efcc018da",size:1617884929}]},"whisper-small":{id:"whisper-small",version:"0.0.1",name:"Whisper Small",description:"Speech to text on Datalayer's servers for short spoken turns, on CPU: OpenAI's Whisper small (244M parameters, 99 languages), converted to CTranslate2 and run by faster-whisper, its weights quantized to 8 bits when loaded. About four times faster than large-v3-turbo; on the fixtures it hears English as well (3.3% against 2.4%) and French less well (16.1% against 2.6%). Recordings longer than a turn go to large-v3-turbo.",provider:"openai",task:"stt",engine:"faster-whisper",dtype:"float16",languages:["en","fr","es","it","pt","de","nl","ja","zh","hi"],where:["server"],streaming:!1,licence:{weights:"MIT",code:"MIT"},attribution:"",upstream:"https://huggingface.co/openai/whisper-small",revision:"536b0662742c02347bc0e980a01041f333bce120",files:[{path:"config.json",sha256:"b55496ac7940a7ae47d2c01eab40edfd8701feec1229d9cce3b40014383fb828",size:2370},{path:"tokenizer.json",sha256:"fb7b63191e9bb045082c79fd742a3106a12c99513ab30df4a0d47fa6cb6fd0ab",size:2203239},{path:"vocabulary.txt",sha256:"34ce3fe1c5041027b3f8d42912270993f986dbc4bb34cf27f951e34a1e453913",size:459861},{path:"model.bin",sha256:"3e305921506d8872816023e4c273e75d2419fb89b24da97b4fe7bce14170d671",size:483546902}]}};function voiceSpeaks(Au,lo){return Au.languages.some($u=>$u===lo||$u.split("-")[0]===lo)}function voiceFor(Au){const lo=Object.values(VOICE_CATALOGUE);return lo.find($u=>$u.languages.includes(Au))??lo.find($u=>voiceSpeaks($u,Au.split("-")[0]))}function transcriberFor(Au){const lo=Au.split("-")[0],$u=Object.values(SPEECH_MODEL_CATALOGUE).filter(Ru=>Ru.task==="stt"&&Ru.where.includes("device")&&Ru.languages.includes(lo));return $u.find(Ru=>Ru.id==="moonshine-tiny-en")??$u.find(Ru=>Ru.id.startsWith("moonshine-"))??$u[0]}const MCP_SERVER_MAP={"tavily:0.0.1":TAVILY_MCP_SERVER_0_0_1},SKILL_MAP={"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,"text-summarizer:0.0.1":TEXT_SUMMARIZER_SKILL_SPEC_0_0_1};function toAgentSkillSpec(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={"runtime-echo:0.0.1":RUNTIME_ECHO_BACKEND_TOOL_SPEC_0_0_1},FRONTEND_TOOL_MAP={"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},COG_CRAWLER_AGENTSPEC_0_0_1={id:"cog-crawler",version:"0.0.1",name:"Crawler Cog",description:"Researches the web and public repositories under the Web Research Frame: every finding rests on a source that was opened, is cited, and is checked before it is reported.",tags:["market-analyst","agent-worker","research","github","analysis","cog"],domain:"market-analyst",enabled:!0,model:"bedrock:us.anthropic.claude-sonnet-4-6",modelAdditionals:["alibaba:qwen-max"],mcpServers:[MCP_SERVER_MAP["tavily:0.0.1"]],skills:[SKILL_MAP["github:0.0.1"]?toAgentSkillSpec(SKILL_MAP["github:0.0.1"]):void 0,SKILL_MAP["events:0.0.1"]?toAgentSkillSpec(SKILL_MAP["events:0.0.1"]):void 0,SKILL_MAP["crawl:0.0.1"]?toAgentSkillSpec(SKILL_MAP["crawl:0.0.1"]):void 0].filter(Boolean),backendTools:[],frontendTools:[FRONTEND_TOOL_MAP["jupyter-notebook:0.0.1"],FRONTEND_TOOL_MAP["lexical-document:0.0.1"]],environmentName:"ai-agents-env",icon:"globe",emoji:"🌐",color:"#10B981",suggestions:[{text:"Search the web for recent news about AI agents",summary:"AI agent news"},{text:"Find trending open-source Python projects on GitHub",summary:"Trending Python projects"},{text:"Research best practices for building RAG applications",summary:"RAG best practices"},{text:"Compare popular JavaScript frameworks in 2024",summary:"JavaScript frameworks 2024"}],welcomeMessage:`Hi! I'm the Crawler Cog. I research the web and GitHub under the Web Research Frame: I open what I cite, I say which sources are primary, and I tell you where sources disagree.
|
|
2927
|
+
`,prompt:"Run the scheduled workflow and produce the configured deliverable."},modelConfig:void 0,mcpServerTools:void 0,guardrails:[{name:"GitHub CI Bot",identity_provider:"github",identity_name:"ci-bot@acme.com",permissions:{"read:data":!0,"write:data":!0,"execute:code":!0,"access:internet":!0,"send:email":!0,"deploy:production":!1},token_limits:{per_run:"60K",per_day:"600K",per_month:"6M"}}],evals:[{name:"Data Quality",category:"coding",task_count:300},{name:"Deduplication Accuracy",category:"reasoning",task_count:150}],codemode:{enabled:!0,token_reduction:"~85%",speedup:"~1.5× faster"},output:{formats:["JSON","PDF"],template:"CRM Sync Report",storage:"/outputs/crm-sync/"},advanced:{cost_limit:"$10.00 per run",time_limit:"600 seconds",max_iterations:100,validation:"All CRM records must reconcile after sync"},checkpoints:void 0,authorizationPolicy:"",notifications:{email:"jennifer.c@company.com",slack:"#crm-sync"},memory:"ephemeral",preHooks:void 0,postHooks:void 0,toolHooks:void 0,parameters:void 0,subagents:void 0},WORKER_THEMATIC_ANALYSIS_AGENTSPEC_0_0_1={id:"worker-thematic-analysis",version:"0.0.1",name:"Thematic Analyst",description:"Codes transcripts, extracts themes, and organizes qualitative evidence.",tags:["market-analyst","agent-worker"],domain:"market-analyst",enabled:!1,model:"bedrock:us.anthropic.claude-sonnet-4-6",mcpServers:[MCP_SERVER_MAP$1["tavily:0.0.1"],MCP_SERVER_MAP$1["salesforce:0.0.1"]],skills:[SKILL_MAP$1["text-summarizer:0.0.1"]?toAgentSkillSpec$1(SKILL_MAP$1["text-summarizer:0.0.1"]):void 0,SKILL_MAP$1["crawl:0.0.1"]?toAgentSkillSpec$1(SKILL_MAP$1["crawl:0.0.1"]):void 0].filter(Boolean),backendTools:[TOOL_MAP$1["runtime-echo:0.0.1"],TOOL_MAP$1["runtime-sensitive-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:"note",emoji:"🔎",color:"#EC4899",suggestions:[],welcomeMessage:void 0,welcomeNotebook:void 0,welcomeDocument:void 0,sandboxVariant:"jupyter-server",harness:"pydantic-ai",systemPrompt:"You are the Thematic Analysis Worker, an autonomous agent worker in the market analyst domain. Codes transcripts, extracts themes, and organizes qualitative evidence. Work step by step, show your reasoning and evidence, and require explicit human approval before any external or irreversible action.",systemPromptCodemodeAddons:void 0,goal:"Code transcripts, extract themes, and organize the supporting evidence.",delegable:[{id:"data.extract"},{id:"data.analyse"}],protocol:"vercel-ai",ui:[{plugin:"a2ui-surface",renderer:"a2ui"}],protocols:[],trigger:void 0,modelConfig:{temperature:.5,max_tokens:4096},mcpServerTools:void 0,guardrails:void 0,evals:void 0,codemode:{enabled:!0},output:void 0,advanced:void 0,checkpoints:void 0,authorizationPolicy:void 0,notifications:void 0,memory:"mem0",preHooks:void 0,postHooks:void 0,toolHooks:void 0,parameters:void 0,subagents:void 0},WORKER_TRAVEL_RECOMMENDER_AGENTSPEC_0_0_1={id:"worker-travel-recommender",version:"0.0.1",name:"Travel Recommender",description:"Researches travel options and builds personalized itineraries with source comparison.",tags:["personal-assistant","agent-worker"],domain:"personal-assistant",enabled:!1,model:"bedrock:us.anthropic.claude-sonnet-4-6",mcpServers:[MCP_SERVER_MAP$1["tavily:0.0.1"],MCP_SERVER_MAP$1["google-workspace:0.0.1"]],skills:[SKILL_MAP$1["text-summarizer:0.0.1"]?toAgentSkillSpec$1(SKILL_MAP$1["text-summarizer:0.0.1"]):void 0,SKILL_MAP$1["crawl:0.0.1"]?toAgentSkillSpec$1(SKILL_MAP$1["crawl:0.0.1"]):void 0,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"],TOOL_MAP$1["runtime-sensitive-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:"globe",emoji:"🤖",color:"#A855F7",suggestions:[],welcomeMessage:void 0,welcomeNotebook:void 0,welcomeDocument:void 0,sandboxVariant:"jupyter-server",harness:"pydantic-ai",systemPrompt:"You are the Travel Recommender, an autonomous agent worker in the personal assistant domain. Researches travel options and builds personalized itineraries with source comparison. Work step by step, show your reasoning and evidence, and require explicit human approval before any external or irreversible action.",systemPromptCodemodeAddons:void 0,goal:"Research travel options and build a personalized itinerary, comparing sources and prices.",delegable:[{id:"research.gather"}],protocol:"vercel-ai",ui:[{plugin:"a2ui-surface",renderer:"a2ui"}],protocols:[],trigger:void 0,modelConfig:{temperature:.5,max_tokens:4096},mcpServerTools:void 0,guardrails:void 0,evals:void 0,codemode:{enabled:!0},output:void 0,advanced:void 0,checkpoints:void 0,authorizationPolicy:void 0,notifications:void 0,memory:"mem0",preHooks:void 0,postHooks:void 0,toolHooks:void 0,parameters:void 0,subagents:void 0},WORKER_TRENDS_SEEKER_AGENTSPEC_0_0_1={id:"worker-trends-seeker",version:"0.0.1",name:"Trends Seeker",description:"Tracks emerging trends across sources and summarizes what is gaining momentum.",tags:["personal-assistant","agent-worker"],domain:"personal-assistant",enabled:!1,model:"bedrock:us.anthropic.claude-sonnet-4-6",mcpServers:[MCP_SERVER_MAP$1["tavily:0.0.1"],MCP_SERVER_MAP$1["google-workspace:0.0.1"]],skills:[SKILL_MAP$1["text-summarizer:0.0.1"]?toAgentSkillSpec$1(SKILL_MAP$1["text-summarizer:0.0.1"]):void 0,SKILL_MAP$1["crawl:0.0.1"]?toAgentSkillSpec$1(SKILL_MAP$1["crawl:0.0.1"]):void 0,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"],TOOL_MAP$1["runtime-sensitive-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:"graph",emoji:"🤖",color:"#A855F7",suggestions:[],welcomeMessage:void 0,welcomeNotebook:void 0,welcomeDocument:void 0,sandboxVariant:"jupyter-server",harness:"pydantic-ai",systemPrompt:"You are the Trends Seeker, an autonomous agent worker in the personal assistant domain. Tracks emerging trends across sources and summarizes what is gaining momentum. Work step by step, show your reasoning and evidence, and require explicit human approval before any external or irreversible action.",systemPromptCodemodeAddons:void 0,goal:"Track emerging trends across sources and summarize what is worth attention and why.",delegable:[{id:"document.summarise"}],protocol:"vercel-ai",ui:[{plugin:"a2ui-surface",renderer:"a2ui"}],protocols:[],trigger:void 0,modelConfig:{temperature:.5,max_tokens:4096},mcpServerTools:void 0,guardrails:void 0,evals:void 0,codemode:{enabled:!0},output:void 0,advanced:void 0,checkpoints:void 0,authorizationPolicy:void 0,notifications:void 0,memory:"mem0",preHooks:void 0,postHooks:void 0,toolHooks:void 0,parameters:void 0,subagents:void 0},WORKER_VARIANT_ANALYSIS_AGENTSPEC_0_0_1={id:"worker-variant-analysis",version:"0.0.1",name:"Variant Analyst",description:"Analyzes genomic variants, annotates findings, and prepares interpretable reports.",tags:["life-sciences","agent-worker"],domain:"life-sciences",enabled:!1,model:"bedrock:us.anthropic.claude-sonnet-4-6",mcpServers:[MCP_SERVER_MAP$1["huggingface:0.0.1"],MCP_SERVER_MAP$1["kaggle:0.0.1"]],skills:[SKILL_MAP$1["text-summarizer:0.0.1"]?toAgentSkillSpec$1(SKILL_MAP$1["text-summarizer:0.0.1"]):void 0,SKILL_MAP$1["pdf:0.0.1"]?toAgentSkillSpec$1(SKILL_MAP$1["pdf:0.0.1"]):void 0].filter(Boolean),backendTools:[TOOL_MAP$1["runtime-echo:0.0.1"],TOOL_MAP$1["runtime-sensitive-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:"beaker",emoji:"🧬",color:"#06B6D4",suggestions:[],welcomeMessage:void 0,welcomeNotebook:void 0,welcomeDocument:void 0,sandboxVariant:"jupyter-server",harness:"pydantic-ai",systemPrompt:"You are the Variant Analysis Worker, an autonomous agent worker in the life sciences domain. Analyzes genomic variants, annotates findings, and prepares interpretable reports. Work step by step, show your reasoning and evidence, and require explicit human approval before any external or irreversible action.",systemPromptCodemodeAddons:void 0,goal:"Analyze and annotate genomic variants and produce an interpretable, provenance-tracked report.",delegable:[{id:"data.analyse"},{id:"report.author"}],protocol:"vercel-ai",ui:[{plugin:"a2ui-surface",renderer:"a2ui"}],protocols:[],trigger:void 0,modelConfig:{temperature:.5,max_tokens:4096},mcpServerTools:void 0,guardrails:void 0,evals:void 0,codemode:{enabled:!0},output:void 0,advanced:void 0,checkpoints:void 0,authorizationPolicy:void 0,notifications:void 0,memory:"mem0",preHooks:void 0,postHooks:void 0,toolHooks:void 0,parameters:void 0,subagents:void 0},WORKER_WEEKLY_EXECUTIVE_BRIEFING_AGENTSPEC_0_0_1={id:"worker-weekly-executive-briefing",version:"0.0.1",name:"Weekly Executive Briefing",description:"Generate a weekly executive summary with KPI deltas, top risks, and recommended actions from operational and analytics data.",tags:["personal-assistant","agent-worker","analytics","reporting","risk"],domain:"personal-assistant",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:"lightbulb",emoji:"📊",color:"#1F883D",suggestions:[{text:"Use /home/datalayer/datasets/datalayer-nfs/sales/sales_pipeline.csv to produce a weekly executive briefing with trends, risks, and actions.",summary:"Weekly executive briefing"}],welcomeMessage:"Hi! I can help with weekly executive briefing. 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: Weekly Executive Briefing. Objective: Generate a weekly executive summary with KPI deltas, top risks, and recommended actions from operational and analytics data. 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:[{id:"data.analyse"},{id:"report.author"}],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},AGENTSPECS$1={"example-a2a-researcher":EXAMPLE_A2A_RESEARCHER_AGENTSPEC_0_0_1,"example-a2a-writer":EXAMPLE_A2A_WRITER_AGENTSPEC_0_0_1,"example-a2a":EXAMPLE_A2A_AGENTSPEC_0_0_1,"example-a2ui-agent":EXAMPLE_A2UI_AGENT_SPEC_0_0_1,"example-a2ui-jupyter-output":EXAMPLE_A2UI_JUPYTER_OUTPUT_AGENTSPEC_0_0_1,"example-a2ui-viewer":EXAMPLE_A2UI_VIEWER_AGENTSPEC_0_0_1,"example-agent-critic-loop-for-analysis":EXAMPLE_AGENT_CRITIC_LOOP_FOR_ANALYSIS_AGENTSPEC_0_0_1,"example-agentic-chat":EXAMPLE_AGENTIC_CHAT_AGENTSPEC_0_0_1,"example-agentic-generative-ui":EXAMPLE_AGENTIC_GENERATIVE_UI_AGENTSPEC_0_0_1,"example-ai-creates-dashboards":EXAMPLE_AI_CREATES_DASHBOARDS_AGENTSPEC_0_0_1,"example-ai-explains-notebook-output":EXAMPLE_AI_EXPLAINS_NOTEBOOK_OUTPUT_AGENTSPEC_0_0_1,"example-ai-writes-pandas-code":EXAMPLE_AI_WRITES_PANDAS_CODE_AGENTSPEC_0_0_1,"example-analyze-excel-spreadsheet":EXAMPLE_ANALYZE_EXCEL_SPREADSHEET_AGENTSPEC_0_0_1,"example-backend-tool-rendering":EXAMPLE_BACKEND_TOOL_RENDERING_AGENTSPEC_0_0_1,"example-blank":EXAMPLE_BLANK_AGENTSPEC_0_0_1,"example-build-notebook-with-one-prompt":EXAMPLE_BUILD_NOTEBOOK_WITH_ONE_PROMPT_AGENTSPEC_0_0_1,"example-checkpoints":EXAMPLE_CHECKPOINTS_AGENTSPEC_0_0_1,"example-cloudflare":EXAMPLE_CLOUDFLARE_AGENTSPEC_0_0_1,"example-code-sandbox":EXAMPLE_CODE_SANDBOX_AGENTSPEC_0_0_1,"example-codemode":EXAMPLE_CODEMODE_AGENTSPEC_0_0_1,"example-compaction":EXAMPLE_COMPACTION_AGENTSPEC_0_0_1,"example-compare-two-spreadsheets":EXAMPLE_COMPARE_TWO_SPREADSHEETS_AGENTSPEC_0_0_1,"example-cost-comparison-report":EXAMPLE_COST_COMPARISON_REPORT_AGENTSPEC_0_0_1,"example-decks":EXAMPLE_DECKS_AGENTSPEC_0_0_1,"example-document-agent-sidebar":EXAMPLE_DOCUMENT_AGENT_SIDEBAR_AGENTSPEC_0_0_1,"example-document-agent":EXAMPLE_DOCUMENT_AGENT_SPEC_0_0_1,"example-evals-nocodemode":EXAMPLE_EVALS_NOCODEMODE_AGENTSPEC_0_0_1,"example-evals":EXAMPLE_EVALS_AGENTSPEC_0_0_1,"example-explore-sql-database":EXAMPLE_EXPLORE_SQL_DATABASE_AGENTSPEC_0_0_1,"example-five-ai-agents-analyze-csv":EXAMPLE_FIVE_AI_AGENTS_ANALYZE_CSV_AGENTSPEC_0_0_1,"example-five-notebooks-in-parallel":EXAMPLE_FIVE_NOTEBOOKS_IN_PARALLEL_AGENTSPEC_0_0_1,"example-full":EXAMPLE_FULL_AGENTSPEC_0_0_1,"example-gpt-and-claude-collaborate":EXAMPLE_GPT_AND_CLAUDE_COLLABORATE_AGENTSPEC_0_0_1,"example-guardrails":EXAMPLE_GUARDRAILS_AGENTSPEC_0_0_1,"example-haiku-generative-ui":EXAMPLE_HAIKU_GENERATIVE_UI_AGENTSPEC_0_0_1,"example-harness-claude-code":EXAMPLE_HARNESS_CLAUDE_CODE_AGENTSPEC_0_0_1,"example-hooks":EXAMPLE_HOOKS_AGENTSPEC_0_0_1,"example-human-approved-automation":EXAMPLE_HUMAN_APPROVED_AUTOMATION_AGENTSPEC_0_0_1,"example-human-in-the-loop":EXAMPLE_HUMAN_IN_THE_LOOP_AGENTSPEC_0_0_1,"example-inference":EXAMPLE_INFERENCE_AGENTSPEC_0_0_1,"example-long-running-agent-overnight":EXAMPLE_LONG_RUNNING_AGENT_OVERNIGHT_AGENTSPEC_0_0_1,"example-mcp":EXAMPLE_MCP_AGENTSPEC_0_0_1,"example-memory":EXAMPLE_MEMORY_AGENTSPEC_0_0_1,"example-monitoring":EXAMPLE_MONITORING_AGENTSPEC_0_0_1,"example-multi-agent-data-cleaning":EXAMPLE_MULTI_AGENT_DATA_CLEANING_AGENTSPEC_0_0_1,"example-multi-agent-root-cause-analysis":EXAMPLE_MULTI_AGENT_ROOT_CAUSE_ANALYSIS_AGENTSPEC_0_0_1,"example-no-codemode":EXAMPLE_NO_CODEMODE_AGENTSPEC_0_0_1,"example-notifications":EXAMPLE_NOTIFICATIONS_AGENTSPEC_0_0_1,"example-one-trigger-approval":EXAMPLE_ONE_TRIGGER_APPROVAL_AGENTSPEC_0_0_1,"example-one-trigger":EXAMPLE_ONE_TRIGGER_AGENTSPEC_0_0_1,"example-otel":EXAMPLE_OTEL_AGENTSPEC_0_0_1,"example-output":EXAMPLE_OUTPUT_AGENTSPEC_0_0_1,"example-parameters":EXAMPLE_PARAMETERS_AGENTSPEC_0_0_1,"example-replace-excel-pivot-work":EXAMPLE_REPLACE_EXCEL_PIVOT_WORK_AGENTSPEC_0_0_1,"example-resumable-etl-with-checkpoints":EXAMPLE_RESUMABLE_ETL_WITH_CHECKPOINTS_AGENTSPEC_0_0_1,"example-run-python-safely-in-the-cloud":EXAMPLE_RUN_PYTHON_SAFELY_IN_THE_CLOUD_AGENTSPEC_0_0_1,"example-sandbox-colab":EXAMPLE_SANDBOX_COLAB_AGENTSPEC_0_0_1,"example-sandbox-datalayer":EXAMPLE_SANDBOX_DATALAYER_AGENTSPEC_0_0_1,"example-sandbox-docker":EXAMPLE_SANDBOX_DOCKER_AGENTSPEC_0_0_1,"example-sandbox-eval":EXAMPLE_SANDBOX_EVAL_AGENTSPEC_0_0_1,"example-sandbox-jupyter":EXAMPLE_SANDBOX_JUPYTER_AGENTSPEC_0_0_1,"example-sandbox-kaggle":EXAMPLE_SANDBOX_KAGGLE_AGENTSPEC_0_0_1,"example-sandbox-modal":EXAMPLE_SANDBOX_MODAL_AGENTSPEC_0_0_1,"example-sandbox-monty":EXAMPLE_SANDBOX_MONTY_AGENTSPEC_0_0_1,"example-shared-state":EXAMPLE_SHARED_STATE_AGENTSPEC_0_0_1,"example-simple":EXAMPLE_SIMPLE_AGENTSPEC_0_0_1,"example-skills":EXAMPLE_SKILLS_AGENTSPEC_0_0_1,"example-subagents":EXAMPLE_SUBAGENTS_AGENTSPEC_0_0_1,"example-tool-approvals":EXAMPLE_TOOL_APPROVALS_AGENTSPEC_0_0_1,"example-tool-based-generative-ui":EXAMPLE_TOOL_BASED_GENERATIVE_UI_AGENTSPEC_0_0_1,"jupyter-cell-fixer":JUPYTER_CELL_FIXER_AGENTSPEC_0_0_1,"jupyter-data-analyst":JUPYTER_DATA_ANALYST_AGENTSPEC_0_0_1,"jupyter-notebook-compactor":JUPYTER_NOTEBOOK_COMPACTOR_AGENTSPEC_0_0_1,"jupyter-notebook-reproducer":JUPYTER_NOTEBOOK_REPRODUCER_AGENTSPEC_0_0_1,"jupyter-notebook-reviewer":JUPYTER_NOTEBOOK_REVIEWER_AGENTSPEC_0_0_1,"jupyter-notebook-writer":JUPYTER_NOTEBOOK_WRITER_AGENTSPEC_0_0_1,"jupyter-tutor":JUPYTER_TUTOR_AGENTSPEC_0_0_1,"loop-shell":LOOP_SHELL_AGENTSPEC_0_0_1,"worker-accountant":WORKER_ACCOUNTANT_AGENTSPEC_0_0_1,"worker-agent-reviews-sql":WORKER_AGENT_REVIEWS_SQL_AGENTSPEC_0_0_1,"worker-analyze-campaign-performance":WORKER_ANALYZE_CAMPAIGN_PERFORMANCE_AGENTSPEC_0_0_1,"worker-analyze-support-tickets":WORKER_ANALYZE_SUPPORT_TICKETS_AGENTSPEC_0_0_1,"worker-ap-invoice":WORKER_AP_INVOICE_AGENTSPEC_0_0_1,"worker-audit-inventory-levels":WORKER_AUDIT_INVENTORY_LEVELS_AGENTSPEC_0_0_1,"worker-audit-pack-builder":WORKER_AUDIT_PACK_BUILDER_AGENTSPEC_0_0_1,"worker-automate-regulatory-reporting":WORKER_AUTOMATE_REGULATORY_REPORTING_AGENTSPEC_0_0_1,"worker-backtest-auditor":WORKER_BACKTEST_AUDITOR_AGENTSPEC_0_0_1,"worker-bank-reconciliation":WORKER_BANK_RECONCILIATION_AGENTSPEC_0_0_1,"worker-campaign-planning":WORKER_CAMPAIGN_PLANNING_AGENTSPEC_0_0_1,"worker-cat-exposure":WORKER_CAT_EXPOSURE_AGENTSPEC_0_0_1,"worker-change-detection":WORKER_CHANGE_DETECTION_AGENTSPEC_0_0_1,"worker-classify-route-emails":WORKER_CLASSIFY_ROUTE_EMAILS_AGENTSPEC_0_0_1,"worker-cms-astro":WORKER_CMS_ASTRO_AGENTSPEC_0_0_1,"worker-coding-tutor":WORKER_CODING_TUTOR_AGENTSPEC_0_0_1,"worker-cohort-comparison":WORKER_COHORT_COMPARISON_AGENTSPEC_0_0_1,"worker-collections":WORKER_COLLECTIONS_AGENTSPEC_0_0_1,"worker-community-response":WORKER_COMMUNITY_RESPONSE_AGENTSPEC_0_0_1,"worker-competitive-intelligence":WORKER_COMPETITIVE_INTELLIGENCE_AGENTSPEC_0_0_1,"worker-compliance-report-draft":WORKER_COMPLIANCE_REPORT_DRAFT_AGENTSPEC_0_0_1,"worker-comprehensive-sales-analytics":WORKER_COMPREHENSIVE_SALES_ANALYTICS_AGENTSPEC_0_0_1,"worker-compute-cost-optimizer":WORKER_COMPUTE_COST_OPTIMIZER_AGENTSPEC_0_0_1,"worker-content-repurposing":WORKER_CONTENT_REPURPOSING_AGENTSPEC_0_0_1,"worker-crawler":WORKER_CRAWLER_AGENTSPEC_0_0_1,"worker-crop-monitoring":WORKER_CROP_MONITORING_AGENTSPEC_0_0_1,"worker-curtailment-investigator":WORKER_CURTAILMENT_INVESTIGATOR_AGENTSPEC_0_0_1,"worker-customer-churn-analysis":WORKER_CUSTOMER_CHURN_ANALYSIS_AGENTSPEC_0_0_1,"worker-customer-interviewer":WORKER_CUSTOMER_INTERVIEWER_AGENTSPEC_0_0_1,"worker-data-acquisition":WORKER_DATA_ACQUISITION_AGENTSPEC_0_0_1,"worker-disaster-assessment":WORKER_DISASTER_ASSESSMENT_AGENTSPEC_0_0_1,"worker-document-qa":WORKER_DOCUMENT_QA_AGENTSPEC_0_0_1,"worker-end-of-month-performance":WORKER_END_OF_MONTH_PERFORMANCE_AGENTSPEC_0_0_1,"worker-energy-trading-analyst":WORKER_ENERGY_TRADING_ANALYST_AGENTSPEC_0_0_1,"worker-environmental-compliance":WORKER_ENVIRONMENTAL_COMPLIANCE_AGENTSPEC_0_0_1,"worker-event-response":WORKER_EVENT_RESPONSE_AGENTSPEC_0_0_1,"worker-evidence-repository":WORKER_EVIDENCE_REPOSITORY_AGENTSPEC_0_0_1,"worker-expense-audit":WORKER_EXPENSE_AUDIT_AGENTSPEC_0_0_1,"worker-exposure-data-quality":WORKER_EXPOSURE_DATA_QUALITY_AGENTSPEC_0_0_1,"worker-extract-data-from-files":WORKER_EXTRACT_DATA_FROM_FILES_AGENTSPEC_0_0_1,"worker-extract-kpis-from-quarterly-pdf":WORKER_EXTRACT_KPIS_FROM_QUARTERLY_PDF_AGENTSPEC_0_0_1,"worker-factor-analysis":WORKER_FACTOR_ANALYSIS_AGENTSPEC_0_0_1,"worker-financial-viz":WORKER_FINANCIAL_VIZ_AGENTSPEC_0_0_1,"worker-generate-weekly-reports":WORKER_GENERATE_WEEKLY_REPORTS_AGENTSPEC_0_0_1,"worker-github-agent":WORKER_GITHUB_AGENT_SPEC_0_0_1,"worker-grid-forecast":WORKER_GRID_FORECAST_AGENTSPEC_0_0_1,"worker-information-routing":WORKER_INFORMATION_ROUTING_AGENTSPEC_0_0_1,"worker-infrastructure-monitoring":WORKER_INFRASTRUCTURE_MONITORING_AGENTSPEC_0_0_1,"worker-insurance-claims-review":WORKER_INSURANCE_CLAIMS_REVIEW_AGENTSPEC_0_0_1,"worker-interview-guide":WORKER_INTERVIEW_GUIDE_AGENTSPEC_0_0_1,"worker-inventory-demand-planning":WORKER_INVENTORY_DEMAND_PLANNING_AGENTSPEC_0_0_1,"worker-job-hunter":WORKER_JOB_HUNTER_AGENTSPEC_0_0_1,"worker-mail-triage":WORKER_MAIL_TRIAGE_AGENTSPEC_0_0_1,"worker-marketing-analytics":WORKER_MARKETING_ANALYTICS_AGENTSPEC_0_0_1,"worker-medical-research-review":WORKER_MEDICAL_RESEARCH_REVIEW_AGENTSPEC_0_0_1,"worker-model-comparison":WORKER_MODEL_COMPARISON_AGENTSPEC_0_0_1,"worker-monitor-sales-kpis":WORKER_MONITOR_SALES_KPIS_AGENTSPEC_0_0_1,"worker-month-end-close":WORKER_MONTH_END_CLOSE_AGENTSPEC_0_0_1,"worker-news-aggregator":WORKER_NEWS_AGGREGATOR_AGENTSPEC_0_0_1,"worker-optimize-dynamic-pricing":WORKER_OPTIMIZE_DYNAMIC_PRICING_AGENTSPEC_0_0_1,"worker-optimize-grid-operations":WORKER_OPTIMIZE_GRID_OPERATIONS_AGENTSPEC_0_0_1,"worker-optimize-sql-query-performance":WORKER_OPTIMIZE_SQL_QUERY_PERFORMANCE_AGENTSPEC_0_0_1,"worker-performance-attribution":WORKER_PERFORMANCE_ATTRIBUTION_AGENTSPEC_0_0_1,"worker-pipeline-debugger":WORKER_PIPELINE_DEBUGGER_AGENTSPEC_0_0_1,"worker-pitcher":WORKER_PITCHER_AGENTSPEC_0_0_1,"worker-portfolio-accumulation":WORKER_PORTFOLIO_ACCUMULATION_AGENTSPEC_0_0_1,"worker-portfolio-risk":WORKER_PORTFOLIO_RISK_AGENTSPEC_0_0_1,"worker-predictive-maintenance":WORKER_PREDICTIVE_MAINTENANCE_AGENTSPEC_0_0_1,"worker-process-citizen-requests":WORKER_PROCESS_CITIZEN_REQUESTS_AGENTSPEC_0_0_1,"worker-process-clinical-trial-data":WORKER_PROCESS_CLINICAL_TRIAL_DATA_AGENTSPEC_0_0_1,"worker-process-financial-transactions":WORKER_PROCESS_FINANCIAL_TRANSACTIONS_AGENTSPEC_0_0_1,"worker-product-finder":WORKER_PRODUCT_FINDER_AGENTSPEC_0_0_1,"worker-quant-research":WORKER_QUANT_RESEARCH_AGENTSPEC_0_0_1,"worker-renewable-asset-performance":WORKER_RENEWABLE_ASSET_PERFORMANCE_AGENTSPEC_0_0_1,"worker-research-recruiter":WORKER_RESEARCH_RECRUITER_AGENTSPEC_0_0_1,"worker-rna-seq":WORKER_RNA_SEQ_AGENTSPEC_0_0_1,"worker-sales-forecasting":WORKER_SALES_FORECASTING_AGENTSPEC_0_0_1,"worker-sales-pipeline-board-report":WORKER_SALES_PIPELINE_BOARD_REPORT_AGENTSPEC_0_0_1,"worker-scenario-testing":WORKER_SCENARIO_TESTING_AGENTSPEC_0_0_1,"worker-scheduled-nightly-data-quality-checks":WORKER_SCHEDULED_NIGHTLY_DATA_QUALITY_CHECKS_AGENTSPEC_0_0_1,"worker-scientific-notebook-assistant":WORKER_SCIENTIFIC_NOTEBOOK_ASSISTANT_AGENTSPEC_0_0_1,"worker-single-cell-processing":WORKER_SINGLE_CELL_PROCESSING_AGENTSPEC_0_0_1,"worker-social-listening":WORKER_SOCIAL_LISTENING_AGENTSPEC_0_0_1,"worker-social-marketer":WORKER_SOCIAL_MARKETER_AGENTSPEC_0_0_1,"worker-spatial-data-analysis":WORKER_SPATIAL_DATA_ANALYSIS_AGENTSPEC_0_0_1,"worker-summarize-documents":WORKER_SUMMARIZE_DOCUMENTS_AGENTSPEC_0_0_1,"worker-sync-crm-contacts":WORKER_SYNC_CRM_CONTACTS_AGENTSPEC_0_0_1,"worker-thematic-analysis":WORKER_THEMATIC_ANALYSIS_AGENTSPEC_0_0_1,"worker-travel-recommender":WORKER_TRAVEL_RECOMMENDER_AGENTSPEC_0_0_1,"worker-trends-seeker":WORKER_TRENDS_SEEKER_AGENTSPEC_0_0_1,"worker-variant-analysis":WORKER_VARIANT_ANALYSIS_AGENTSPEC_0_0_1,"worker-weekly-executive-briefing":WORKER_WEEKLY_EXECUTIVE_BRIEFING_AGENTSPEC_0_0_1},AGENTSPECS={...AGENTSPECS$1};function resolveAgentId(Au){if(Au in AGENTSPECS)return Au;const lo=Au.lastIndexOf(":");if(lo>0){const $u=Au.slice(0,lo);if($u in AGENTSPECS)return $u}return Au}function getAgentspecs(Au){return AGENTSPECS[resolveAgentId(Au)]}const ANALYZE_CAMPAIGN_PERFORMANCE_TEAM_SPEC_0_0_1={id:"analyze-campaign-performance",version:"0.0.1",name:"Analyze Campaign Performance Team",description:"A multi-agent team that unifies marketing data from Google Ads, Meta, TikTok, LinkedIn, GA4, CRM, and email platforms. Normalises metrics into a unified view, detects performance anomalies in real time, and generates budget reallocation recommendations to maximise ROAS.",tags:["marketing","media","campaigns","analytics","advertising","social-media"],enabled:!0,icon:"megaphone",emoji:"📢",color:"#8250df",agentSpecId:"analyze-campaign-performance:0.0.1",orchestrationProtocol:"datalayer",executionMode:"sequential",supervisor:{name:"Campaign Analytics Orchestrator Agent",ref:"",model:"openai:gpt-4.1",goal:"",instructions:"",approval:"auto",canTerminate:!0},routingInstructions:"Start with Platform Connector to pull data from all ad platforms, then Metrics Normaliser for unified KPIs, then Anomaly Detector for real-time performance monitoring, then Budget Optimiser for reallocation recommendations. Escalate CPA spikes above 50% immediately.",delegation:{maxDepth:2,allowPeerDelegation:!1,includeGeneralPurpose:!1},context:{sharing:"shared"},validation:{timeout:"300s",retryOnFailure:!0,maxRetries:2},agents:[{id:"cp-1",name:"Platform Connector Agent",ref:"",role:"initiator",goal:"Pull campaign data from Google Ads, Meta, TikTok, LinkedIn, GA4, and email platforms",dependsOn:[],subagents:[],model:"openai:gpt-4.1",mcpServer:"Ad Platforms MCP",tools:["Google Ads Connector","Meta Ads Connector","TikTok Ads Connector","LinkedIn Ads Connector","GA4 Connector"],trigger:"Schedule: Every 4 hours",approval:"auto"},{id:"cp-2",name:"Metrics Normaliser Agent",ref:"",role:"contributor",goal:"Normalise CPA, ROAS, CTR, and attribution across all platforms into unified view",dependsOn:["cp-1"],subagents:[],model:"openai:gpt-4.1",mcpServer:"Analytics MCP",tools:["Metric Unifier","Currency Converter","Attribution Mapper","Naming Convention Resolver"],trigger:"",approval:"auto"},{id:"cp-3",name:"Anomaly Detector Agent",ref:"",role:"contributor",goal:"Monitor all KPIs for CTR drops, CPA spikes, and budget pacing issues",dependsOn:["cp-2"],subagents:[],model:"anthropic:claude-sonnet-4-20250514",mcpServer:"Monitoring MCP",tools:["Anomaly Scanner","Budget Pacer","Alert Generator","Campaign Pauser"],trigger:"",approval:"manual"},{id:"cp-4",name:"Budget Optimiser Agent",ref:"",role:"finalizer",goal:"Generate budget reallocation recommendations to maximise ROAS across channels",dependsOn:["cp-3"],subagents:[],model:"openai:gpt-4.1",mcpServer:"Optimisation MCP",tools:["ROAS Calculator","Budget Allocator","Scenario Modeller","Report Generator"],trigger:"",approval:"manual"}],reactionRules:[{id:"rr-camp-1",trigger:"budget_threshold_exceeded",action:"pause_and_notify",auto:!0,maxRetries:1,escalateAfterRetries:1,priority:"high"},{id:"rr-camp-2",trigger:"data_quality_low",action:"retry_collection",auto:!0,maxRetries:3,escalateAfterRetries:3,priority:"medium"}],healthMonitoring:{heartbeatInterval:"30s",staleThreshold:"120s",unresponsiveThreshold:"300s",stuckThreshold:"600s",maxRestartAttempts:3},notifications:{on_start:!0,on_completion:!0,on_failure:!0,on_escalation:!0},output:{formats:["pdf","csv","json"],template:"Campaign Performance Report",storage:"s3://reports/campaign-analytics/"}},ANALYZE_SUPPORT_TICKETS_TEAM_SPEC_0_0_1={id:"analyze-support-tickets",version:"0.0.1",name:"Analyze Support Tickets Team",description:"A multi-agent team that triages incoming support tickets, categorizes by urgency and topic, identifies recurring patterns, and generates resolution recommendations with escalation paths.",tags:["analytics","data","support","tickets"],enabled:!0,icon:"issue-opened",emoji:"🎫",color:"#bf8700",agentSpecId:"analyze-support-tickets:0.0.1",orchestrationProtocol:"datalayer",executionMode:"sequential",supervisor:{name:"Support Orchestrator Agent",ref:"",model:"openai:gpt-4.1",goal:"",instructions:"",approval:"auto",canTerminate:!0},routingInstructions:"Route new tickets to the Triage Agent first, then to the Categorizer, then to the Pattern Analyzer. Escalate P1/critical tickets immediately to human support leads.",delegation:{maxDepth:2,allowPeerDelegation:!1,includeGeneralPurpose:!1},context:{sharing:"shared"},validation:{timeout:"180s",retryOnFailure:!0,maxRetries:2},agents:[{id:"st-1",name:"Triage Agent",ref:"",role:"initiator",goal:"Ingest new support tickets and assess urgency level (P1-P4)",dependsOn:[],subagents:[],model:"openai:gpt-4.1",mcpServer:"Helpdesk MCP",tools:["Ticket Reader","Priority Classifier"],trigger:"Event: new ticket received",approval:"auto"},{id:"st-2",name:"Categorizer Agent",ref:"",role:"contributor",goal:"Categorize tickets by topic, product area, and sentiment",dependsOn:["st-1"],subagents:[],model:"openai:gpt-4.1",mcpServer:"NLP Pipeline MCP",tools:["Topic Classifier","Sentiment Analyzer","Product Tagger"],trigger:"",approval:"auto"},{id:"st-3",name:"Pattern Analyzer Agent",ref:"",role:"finalizer",goal:"Identify recurring issues and generate resolution recommendations",dependsOn:["st-2"],subagents:[],model:"anthropic:claude-sonnet-4-20250514",mcpServer:"Analytics MCP",tools:["Pattern Detector","Knowledge Base Search","Resolution Generator"],trigger:"",approval:"manual"}],reactionRules:[{id:"rr-supp-1",trigger:"ticket_surge_detected",action:"escalate_to_supervisor",auto:!0,maxRetries:2,escalateAfterRetries:2,priority:"high"},{id:"rr-supp-2",trigger:"classification_confidence_low",action:"request_human_review",auto:!1,maxRetries:1,escalateAfterRetries:1,priority:"medium"}],healthMonitoring:{heartbeatInterval:"15s",staleThreshold:"60s",unresponsiveThreshold:"180s",stuckThreshold:"300s",maxRestartAttempts:3},notifications:{on_start:!1,on_completion:!0,on_failure:!0,on_escalation:!0},output:{formats:["pdf","json"],template:"Support Ticket Analysis",storage:"s3://reports/support-analytics/"}},AUDIT_INVENTORY_LEVELS_TEAM_SPEC_0_0_1={id:"audit-inventory-levels",version:"0.0.1",name:"Audit Inventory Levels Team",description:"A multi-agent team that monitors inventory levels across warehouses, detects discrepancies between physical and system counts, forecasts demand by SKU, and generates automated reorder recommendations.",tags:["finance","automation","inventory","supply-chain"],enabled:!0,icon:"package",emoji:"📦",color:"#0969da",agentSpecId:"audit-inventory-levels:0.0.1",orchestrationProtocol:"datalayer",executionMode:"sequential",supervisor:{name:"Inventory Orchestrator Agent",ref:"",model:"openai:gpt-4.1",goal:"",instructions:"",approval:"auto",canTerminate:!0},routingInstructions:"Start with the Scanner to pull current levels, then Auditor to check discrepancies, then Forecaster for demand predictions, then Planner for reorder recommendations, then Reporter for the final audit report. Escalate critical shortages immediately.",delegation:{maxDepth:2,allowPeerDelegation:!1,includeGeneralPurpose:!1},context:{sharing:"shared"},validation:{timeout:"600s",retryOnFailure:!0,maxRetries:3},agents:[{id:"inv-1",name:"Inventory Scanner Agent",ref:"",role:"initiator",goal:"Pull current inventory levels from all warehouse management systems",dependsOn:[],subagents:[],model:"openai:gpt-4.1",mcpServer:"Warehouse MCP",tools:["WMS Connector","Barcode Scanner API"],trigger:"Schedule: Every 6 hours",approval:"auto"},{id:"inv-2",name:"Discrepancy Auditor Agent",ref:"",role:"contributor",goal:"Compare system counts vs physical counts and flag discrepancies",dependsOn:["inv-1"],subagents:[],model:"openai:gpt-4.1",mcpServer:"Audit MCP",tools:["Count Comparator","Discrepancy Logger","Shrinkage Calculator"],trigger:"",approval:"auto"},{id:"inv-3",name:"Demand Forecaster Agent",ref:"",role:"contributor",goal:"Forecast demand by SKU using historical sales and seasonal patterns",dependsOn:["inv-2"],subagents:[],model:"anthropic:claude-sonnet-4-20250514",mcpServer:"Analytics MCP",tools:["Time Series Model","Seasonal Analyzer","External Signals Fetcher"],trigger:"",approval:"auto"},{id:"inv-4",name:"Reorder Planner Agent",ref:"",role:"contributor",goal:"Calculate optimal reorder points and generate purchase order recommendations",dependsOn:["inv-3"],subagents:[],model:"openai:gpt-4.1",mcpServer:"Procurement MCP",tools:["EOQ Calculator","Supplier Catalog","PO Generator"],trigger:"",approval:"manual"},{id:"inv-5",name:"Audit Report Agent",ref:"",role:"finalizer",goal:"Compile inventory audit report with discrepancies, forecasts, and reorder plan",dependsOn:["inv-4"],subagents:[],model:"openai:gpt-4.1",mcpServer:"Document Generation MCP",tools:["PDF Generator","Chart Builder","Email Sender"],trigger:"",approval:"auto"}],reactionRules:[{id:"rr-inv-1",trigger:"stockout_risk_detected",action:"escalate_to_supervisor",auto:!0,maxRetries:1,escalateAfterRetries:1,priority:"high"},{id:"rr-inv-2",trigger:"discrepancy_threshold_exceeded",action:"flag_for_manual_audit",auto:!1,maxRetries:2,escalateAfterRetries:2,priority:"high"}],healthMonitoring:{heartbeatInterval:"30s",staleThreshold:"120s",unresponsiveThreshold:"300s",stuckThreshold:"600s",maxRestartAttempts:3},notifications:{on_start:!0,on_completion:!0,on_failure:!0,on_escalation:!0},output:{formats:["pdf","xlsx","csv"],template:"Inventory Audit Report",storage:"s3://reports/inventory-audits/"}},AUTOMATE_REGULATORY_REPORTING_TEAM_SPEC_0_0_1={id:"automate-regulatory-reporting",version:"0.0.1",name:"Automate Regulatory Reporting Team",description:"A multi-agent team that automates end-to-end regulatory reporting for financial institutions. Ingests data from trading systems, risk engines, and accounting platforms, reconciles positions, computes risk metrics, validates against regulatory rules (Basel III/IV, MiFID II, SOX), and generates submission-ready compliance reports with full audit trails.",tags:["finance","compliance","regulatory","risk","banking","audit"],enabled:!0,icon:"shield-check",emoji:"🏦",color:"#0969da",agentSpecId:"automate-regulatory-reporting:0.0.1",orchestrationProtocol:"datalayer",executionMode:"sequential",supervisor:{name:"Compliance Orchestrator Agent",ref:"",model:"openai:gpt-4.1",goal:"",instructions:"",approval:"auto",canTerminate:!0},routingInstructions:"Start with Data Ingestion to pull positions and transactions, then Risk Calculator for metric computation, then Reconciliation Agent to cross-check figures, then Validation Agent for regulatory rule checks, then Report Generator for submission-ready output. Escalate any reconciliation breaks above $10K immediately to the compliance team.",delegation:{maxDepth:2,allowPeerDelegation:!1,includeGeneralPurpose:!1},context:{sharing:"shared"},validation:{timeout:"900s",retryOnFailure:!0,maxRetries:2},agents:[{id:"reg-1",name:"Data Ingestion Agent",ref:"",role:"initiator",goal:"Extract positions, transactions, and P&L from trading and accounting systems",dependsOn:[],subagents:[],model:"openai:gpt-4.1",mcpServer:"Trading Systems MCP",tools:["Position Reader","Transaction Fetcher","P&L Extractor"],trigger:"Schedule: Monthly on the 3rd business day",approval:"auto"},{id:"reg-2",name:"Risk Calculator Agent",ref:"",role:"contributor",goal:"Compute Basel III/IV risk-weighted assets, capital ratios, and VaR metrics",dependsOn:["reg-1"],subagents:[],model:"anthropic:claude-sonnet-4-20250514",mcpServer:"Risk Engine MCP",tools:["RWA Calculator","VaR Engine","Capital Ratio Computer","Stress Test Runner"],trigger:"",approval:"auto"},{id:"reg-3",name:"Reconciliation Agent",ref:"",role:"contributor",goal:"Cross-check computed figures against source systems and flag discrepancies",dependsOn:["reg-2"],subagents:[],model:"openai:gpt-4.1",mcpServer:"Reconciliation MCP",tools:["Position Reconciler","Break Detector","Audit Logger"],trigger:"",approval:"auto"},{id:"reg-4",name:"Validation Agent",ref:"",role:"contributor",goal:"Validate all metrics against Basel III/IV, MiFID II, and SOX regulatory rules",dependsOn:["reg-3"],subagents:[],model:"openai:gpt-4.1",mcpServer:"Compliance Rules MCP",tools:["Basel Rule Validator","MiFID II Checker","SOX Control Verifier"],trigger:"",approval:"manual"},{id:"reg-5",name:"Report Generator Agent",ref:"",role:"finalizer",goal:"Generate submission-ready regulatory reports with full data lineage and audit trail",dependsOn:["reg-4"],subagents:[],model:"openai:gpt-4.1",mcpServer:"Document Generation MCP",tools:["PDF Generator","XBRL Formatter","Email Sender"],trigger:"",approval:"auto"}],reactionRules:[{id:"rr-reg-1",trigger:"compliance_violation_detected",action:"halt_and_escalate",auto:!0,maxRetries:0,escalateAfterRetries:0,priority:"critical"},{id:"rr-reg-2",trigger:"data_validation_failure",action:"retry_with_fallback",auto:!0,maxRetries:3,escalateAfterRetries:3,priority:"high"}],healthMonitoring:{heartbeatInterval:"15s",staleThreshold:"60s",unresponsiveThreshold:"120s",stuckThreshold:"300s",maxRestartAttempts:2},notifications:{on_start:!0,on_completion:!0,on_failure:!0,on_escalation:!0},output:{formats:["pdf","xbrl","json"],template:"Regulatory Submission Report",storage:"s3://reports/regulatory-submissions/"}},COMPREHENSIVE_SALES_ANALYTICS_TEAM_SPEC_0_0_1={id:"comprehensive-sales-analytics",version:"0.0.1",name:"Comprehensive Sales Analytics Team",description:"A multi-agent team that replaces a single KPI monitor with four specialized agents: a Data Collector that pulls real-time CRM metrics, an Anomaly Detector that flags statistical outliers, a Trend Analyzer that identifies patterns and forecasts, and a Report Generator that compiles executive dashboards and sends alerts. Together they deliver deeper insights, faster detection, and richer reporting than any single agent could.",tags:["sales","analytics","kpi","monitoring","horizontal"],enabled:!0,icon:"graph",emoji:"📈",color:"#1a7f37",agentSpecId:"comprehensive-sales-analytics:0.0.1",orchestrationProtocol:"datalayer",executionMode:"sequential",supervisor:{name:"Sales Analytics Supervisor",ref:"",model:"bedrock:us.anthropic.claude-sonnet-4-6",goal:"",instructions:"",approval:"auto",canTerminate:!0},routingInstructions:"Route data collection to KPI Collector first, then pass raw metrics to Anomaly Detector and Trend Analyzer in parallel, then aggregate all outputs into the Report Generator. Escalate if anomalies exceed the critical threshold (>25% deviation from target).",delegation:{maxDepth:2,allowPeerDelegation:!1,includeGeneralPurpose:!1},context:{sharing:"shared"},validation:{timeout:"300s",retryOnFailure:!0,maxRetries:3},agents:[{id:"sa-1",name:"KPI Data Collector",ref:"",role:"initiator",goal:"Pull real-time sales metrics from CRM, ERP, and marketing platforms. Normalize data into a unified schema with timestamps, dimensions (region, product line, rep), and measures (revenue, pipeline, conversion).",dependsOn:[],subagents:[],model:"openai:gpt-4.1",mcpServer:"CRM Data Server",tools:["get_sales_data","get_customer_list","API Connector"],trigger:"Schedule: Daily at 7:30 AM",approval:"auto"},{id:"sa-2",name:"Anomaly Detector",ref:"",role:"contributor",goal:"Apply statistical anomaly detection (Z-score, IQR, moving average) to the collected KPIs. Flag any metric deviating more than 10% from its rolling 30-day average. Classify anomalies as info, warning, or critical.",dependsOn:["sa-1"],subagents:[],model:"anthropic:claude-sonnet-4-20250514",mcpServer:"Analytics Server",tools:["run_analysis","Statistical Analysis","ML Predictor"],trigger:"",approval:"auto"},{id:"sa-3",name:"Trend Analyzer",ref:"",role:"contributor",goal:"Identify week-over-week, month-over-month, and quarter-over-quarter trends. Generate 30-day forecasts for each KPI using time-series models. Highlight the top 3 improving and top 3 declining metrics.",dependsOn:["sa-1"],subagents:[],model:"anthropic:claude-sonnet-4-20250514",mcpServer:"Analytics Server",tools:["run_analysis","generate_charts","Forecaster"],trigger:"",approval:"auto"},{id:"sa-4",name:"Executive Report Generator",ref:"",role:"finalizer",goal:"Compile all insights — raw KPIs, anomalies, trends, and forecasts — into a polished executive dashboard with charts, tables, and narrative commentary. Send the report via Slack and email. Highlight critical anomalies with a red-flag summary at the top.",dependsOn:["sa-2","sa-3"],subagents:[],model:"openai:gpt-4.1",mcpServer:"Document Generation MCP",tools:["PDF Generator","Chart Builder","Email Sender","Slack Notifier"],trigger:"",approval:"manual"}],reactionRules:[{id:"rr-sales-1",trigger:"anomaly_critical",action:"escalate_to_supervisor",auto:!0,maxRetries:2,escalateAfterRetries:2,priority:"high"},{id:"rr-sales-2",trigger:"data_stale",action:"retry_collection",auto:!0,maxRetries:3,escalateAfterRetries:3,priority:"medium"}],healthMonitoring:{heartbeatInterval:"30s",staleThreshold:"120s",unresponsiveThreshold:"300s",stuckThreshold:"600s",maxRestartAttempts:3},notifications:{on_start:!0,on_completion:!0,on_failure:!0,on_escalation:!0},output:{formats:["pdf","xlsx","json"],template:"Executive Sales Dashboard",storage:"s3://reports/sales-analytics/"}},CROP_MONITORING_TEAM_SPEC_0_0_1={id:"crop-monitoring",version:"0.0.1",name:"Crop Monitoring",description:"One agent, its data: Crop Monitoring follows crop vigour and growth over a season from the satellite imagery NASA Earthdata holds, and flags the fields that need attention.",tags:["example","scene","earth-observation","agriculture","earthdata","a2a"],enabled:!0,icon:"telescope",emoji:"🛰️",color:"#1a7f37",agentSpecId:"",orchestrationProtocol:"a2a",executionMode:"supervisor",supervisor:{name:"Crop Monitoring",ref:"",app:"crop-monitoring:0.0.2",model:"",goal:"",instructions:"",approval:"auto",canTerminate:!0},routingInstructions:"Crop Monitoring answers every request from the imagery itself, one search at a time, and reports what the granules show without adding to it.",entry:"crop-monitoring",suggestions:[{text:"How has crop vigour evolved over the last three months around 45.5N, 10.2E?",emoji:"🌱"},{text:"Which fields around 41.9N, 12.5E show a drop in vegetation this month compared with last?",emoji:"🌾"},{text:"Which datasets and granules cover the Po valley for June 2026?",emoji:"🛰️"},{text:"Save the June 2026 granules of the Po valley to my Space.",emoji:"💾"}],delegation:{maxDepth:0,allowPeerDelegation:!1,includeGeneralPurpose:!1},context:{sharing:"shared"},validation:{timeout:"300s",retryOnFailure:!1,maxRetries:0},agents:[{id:"crop-monitoring",name:"",ref:"",app:"crop-monitoring:0.0.2",runsIn:"runtime",role:"initiator",goal:"Take the person's field and period, search the imagery that covers them, and report the vigour, the growth and the fields to watch.",dependsOn:[],subagents:[],model:"",mcpServer:"",tools:[],trigger:"",approval:"auto"}]},DISASTER_ASSESSMENT_TEAM_SPEC_0_0_1={id:"disaster-assessment",version:"0.0.1",name:"Disaster Assessment",description:"An event desk in the browser that gets the area a disaster affected and the damage from Disaster Assessment, and what changed on the ground from Change detection, each on a runtime over A2A, each reading NASA Earthdata. Event response takes the event and reports; the two others read the imagery and answer.",tags:["example","scene","earth-observation","disaster","insurance","earthdata","a2a"],enabled:!0,icon:"pulse",emoji:"🛰️",color:"#cf222e",agentSpecId:"",orchestrationProtocol:"a2a",executionMode:"supervisor",supervisor:{name:"Event response",ref:"",app:"event-response:0.0.3",model:"",goal:"",instructions:"",approval:"auto",canTerminate:!0},routingInstructions:"Event response asks Disaster Assessment for the area and the damage, and Change detection for the change on the ground, one request each, and reports what they answer without adding to it.",entry:"event-response",suggestions:[{text:"Valencia, Spain, was flooded on 29 October 2024. What was affected, and what changed?",emoji:"🌊"},{text:"Fires burned around Los Angeles from 7 January 2025. Which imagery shows what changed?",emoji:"🔥"},{text:"The Ahr valley was hit by a storm on 14 July 2021. Chart the imagery found each day from 10 to 20 July.",emoji:"🌧️"},{text:"Send the Valencia flood assessment to the emergency services.",emoji:"📣"}],delegation:{maxDepth:1,allowPeerDelegation:!0,includeGeneralPurpose:!1},context:{sharing:"shared"},validation:{timeout:"600s",retryOnFailure:!1,maxRetries:0},agents:[{id:"event-response",name:"",ref:"",app:"event-response:0.0.3",runsIn:"browser",talksTo:[{member:"disaster-assessment",over:"a2a"},{member:"change-detection",over:"a2a"}],role:"initiator",goal:"Take the person's event, ask Disaster Assessment and Change detection for it, and report what they answered.",dependsOn:[],subagents:[],model:"",mcpServer:"",tools:[],trigger:"",approval:"auto"},{id:"disaster-assessment",name:"",ref:"",app:"disaster-assessment:0.0.2",runsIn:"runtime",role:"contributor",goal:"Estimate the area the event affected and the extent of the damage from the imagery before and after it, over A2A.",dependsOn:[],subagents:[],model:"",mcpServer:"",tools:[],trigger:"",approval:"auto"},{id:"change-detection",name:"",ref:"",app:"change-detection:0.0.2",runsIn:"runtime",role:"contributor",goal:"Find what changed on the ground between the two dates from the imagery, over A2A.",dependsOn:[],subagents:[],model:"",mcpServer:"",tools:[],trigger:"",approval:"auto"}]},JUPYTER_TEAM_SPEC_0_0_1={id:"jupyter",version:"0.0.1",name:"Jupyter Team",description:"Six agents working in the same Jupyter notebook: the Analyst adds and runs the cells, the Reviewer checks them and records what it finds, the Writer writes the result up between them, Decks turns what they found into a presentation, the Tutor teaches the person Python in the cells they have, and the Compactor rewrites the notebook as short as it can be without changing what it computes.",tags:["notebook","jupyter","collaboration","analysis","review","presentations","teaching","refactoring"],enabled:!0,icon:"book",emoji:"📓",color:"#F37726",agentSpecId:"",orchestrationProtocol:"datalayer",executionMode:"supervisor",supervisor:{name:"Jupyter Analyst",ref:"jupyter-data-analyst:0.0.1",model:"bedrock:us.anthropic.claude-sonnet-4-6",goal:"Keep the work in the notebook. Answer analysis requests directly; send a request to check something to the Reviewer, a request to write something up to the Writer, a request for slides to Decks, a question about the code to the Tutor and a request to tidy the notebook to the Compactor — and never leave results anywhere but the cells, or the deck made from them.",instructions:"",approval:"auto",canTerminate:!1},routingInstructions:'Send anything about exploring, computing, plotting or extending the analysis — "analyze", "plot", "compute", "add a cell that…" — to the Jupyter Analyst. Send anything about checking, verifying, doubting or re-running — "find what is wrong", "check this", "is this right", "re-run" — to Jupyter Reviewer. Send anything about explaining, summarising, writing up or verifying the wording of a conclusion to Jupyter Writer. Send anything about slides, a deck or a presentation — "make a deck of this", "turn the findings into slides", "present this", "add a slide" — to Jupyter Decks, which builds the deck from what the cells show and opens it beside the conversation. Send anything about understanding or learning — "what does this do", "why did this fail", "teach me", a request for an exercise — to Jupyter Tutor. Send anything about the shape of the notebook — shortening it, merging cells, removing dead code or stale outputs — to Jupyter Compactor. When a request is two of these, the one that produces cells goes first and the one that reads them follows: the Analyst before the Writer or Decks ("analyze this and write it up", "analyze this and make a deck"), the Tutor before the Compactor ("clean this up and explain what you did"). Never let the Compactor rewrite a notebook the person is still learning from without saying what changed. When none fits, answer directly rather than forcing the request onto a specialist.',suggestions:[{text:"Analyze the dataset",summary:"Analyze the dataset",icon:"graph",emoji:"🔎"},{text:"Find what is wrong",summary:"Find what is wrong",icon:"checklist",emoji:"🧐"},{text:"Verify the conclusion",summary:"Verify the conclusion",icon:"pencil",emoji:"✍️"},{text:"Turn the findings into a deck",summary:"Findings into a deck",icon:"project",emoji:"📊"},{text:"Explain this notebook cell by cell, as if I am new to Python",summary:"Cell by cell, for beginners",icon:"book",emoji:"📖"},{text:"Shorten this notebook without changing what it computes",summary:"Shorten the notebook",icon:"fold",emoji:"✂️"}],delegation:{maxDepth:2,allowPeerDelegation:!1,includeGeneralPurpose:!1},context:{sharing:"shared"},validation:{timeout:"300s",retryOnFailure:!0,maxRetries:1},agents:[{id:"analyst",name:"Jupyter Analyst",ref:"jupyter-data-analyst:0.0.1",role:"initiator",goal:"Explore the data in the open notebook — add the cells, run them, and leave the results on them for the others to build on.",dependsOn:[],subagents:[],model:"",mcpServer:"",tools:[],trigger:"",approval:"auto"},{id:"reviewer",name:"Jupyter Reviewer",ref:"jupyter-notebook-reviewer:0.0.1",role:"reviewer",goal:"Re-run what matters, find what is wrong or unsupported, and record the verdict in the notebook beside the code it concerns.",dependsOn:[],subagents:[],model:"",mcpServer:"",tools:[],trigger:"",approval:"auto"},{id:"writer",name:"Jupyter Writer",ref:"jupyter-notebook-writer:0.0.1",role:"finalizer",goal:"Write the analysis up between the cells — summary, explanations, conclusion — saying only what the cells support.",dependsOn:[],subagents:[],model:"",mcpServer:"",tools:[],trigger:"",approval:"auto"},{id:"decks",name:"Jupyter Decks",ref:"example-decks:0.0.1",role:"contributor",goal:"Turn what the notebook found into a deck — a title, the numbers as metrics or a chart, the conclusion — open it beside the conversation, and step through it on request.",dependsOn:[],subagents:[],model:"",mcpServer:"",tools:[],trigger:"",approval:"auto"},{id:"tutor",name:"Jupyter Tutor",ref:"jupyter-tutor:0.0.1",role:"contributor",goal:"Teach the person Python in the notebook they have open — what their code does, why it broke, and what to try next — leaving them able to write the next cell themselves.",dependsOn:[],subagents:[],model:"",mcpServer:"",tools:[],trigger:"",approval:"auto"},{id:"compactor",name:"Jupyter Compactor",ref:"jupyter-notebook-compactor:0.0.1",role:"finalizer",goal:"Rewrite the notebook as short as it can be without changing what it computes, and report exactly which cells were touched.",dependsOn:[],subagents:[{name:"CellFixer",ref:"jupyter-cell-fixer:0.0.1",description:"Fixes a failing cell and proves the fix by running it. Reach for this when compaction uncovers a cell that was already broken — repairing it is not part of compacting, and silently leaving it is worse.",instructions:""},{name:"NotebookReproducer",ref:"jupyter-notebook-reproducer:0.0.1",description:"Runs the notebook top to bottom on a fresh sandbox and reports what does not reproduce. Reach for this to prove a compaction changed nothing, which is the claim a compaction rests on.",instructions:""}],model:"",mcpServer:"",tools:[],trigger:"",approval:"manual"}],reactionRules:[{id:"rr-nb-1",trigger:"compaction_would_change_results",action:"request_human_review",auto:!1,maxRetries:0,escalateAfterRetries:0,priority:"high"},{id:"rr-nb-2",trigger:"learner_repeatedly_stuck",action:"escalate_to_supervisor",auto:!0,maxRetries:2,escalateAfterRetries:2,priority:"medium"},{id:"rr-nb-3",trigger:"review_found_unsupported_claim",action:"escalate_to_supervisor",auto:!0,maxRetries:1,escalateAfterRetries:1,priority:"medium"}],healthMonitoring:{heartbeatInterval:"15s",staleThreshold:"60s",unresponsiveThreshold:"180s",stuckThreshold:"300s",maxRestartAttempts:3},notifications:{on_start:!1,on_completion:!0,on_failure:!0,on_escalation:!0},output:{formats:["ipynb","markdown"],template:"Notebook Session Summary",storage:""}},MONTH_END_CLOSE_TEAM_SPEC_0_0_1={id:"month-end-close",version:"0.0.1",name:"Month-end Close",description:"One agent, its data: Month-end Close drives the close from the Odoo books, which it only reads — the checklist, the accruals to book, the reconciliation gaps that remain.",tags:["example","scene","accounting","finance","odoo","a2a"],enabled:!0,icon:"sync",emoji:"🧾",color:"#bf8700",agentSpecId:"",orchestrationProtocol:"a2a",executionMode:"supervisor",supervisor:{name:"Month-end Close",ref:"",app:"month-end-close:0.0.2",model:"",goal:"",instructions:"",approval:"auto",canTerminate:!0},routingInstructions:"Month-end Close answers every request from the books itself, one read at a time, and reports what the books hold without adding to it.",entry:"month-end-close",suggestions:[{text:"Where does the month-end close stand for last month? Give me the checklist.",emoji:"☑️"},{text:"Which accruals should be booked for last month? Show me the entries each rests on.",emoji:"🧾"},{text:"Chart last month's expenses by account against the month before.",emoji:"📊"},{text:"Post the accruals you suggested for last month.",emoji:"✍️"}],delegation:{maxDepth:0,allowPeerDelegation:!1,includeGeneralPurpose:!1},context:{sharing:"shared"},validation:{timeout:"300s",retryOnFailure:!1,maxRetries:0},agents:[{id:"month-end-close",name:"",ref:"",app:"month-end-close:0.0.2",runsIn:"runtime",role:"initiator",goal:"Take the person's request, read the period's books, and report where the close stands: what is done, what is to book, what is still open.",dependsOn:[],subagents:[],model:"",mcpServer:"",tools:[],trigger:"",approval:"auto"}]},NOTEBOOK_BENCHMARK_TEAM_SPEC_0_0_1={id:"notebook-benchmark",version:"0.0.1",name:"Notebook Benchmark Team",description:"Runs a notebook benchmark end to end: one agent executes it from a clean sandbox, a second compares what came out against what the evalset expected, and a third checks the comparison before it is published. Section 17's vertical slice.",tags:["benchmark","notebook","evaluation","orchestration"],enabled:!0,icon:"beaker",emoji:"🧪",color:"#1ABC9C",agentSpecId:"jupyter-data-analyst:0.0.1",orchestrationProtocol:"datalayer",executionMode:"sequential",supervisor:{name:"Benchmark Supervisor",ref:"",model:"bedrock:us.anthropic.claude-sonnet-4-6",goal:"",instructions:"",approval:"auto",canTerminate:!0},routingInstructions:"Place the runner first and wait for it: nothing can be analysed before the notebook has run. Give the analyst the runner's outputs and the evalset's expectations, and the reviewer the analyst's comparison. Answer with the reviewer's verdict and the evidence behind it, never with a summary of your own that nothing produced.",delegation:{maxDepth:2,allowPeerDelegation:!1,includeGeneralPurpose:!1},context:{sharing:"shared"},validation:{timeout:"900s",retryOnFailure:!0,maxRetries:2},agents:[{id:"runner",name:"Benchmark Runner",ref:"",role:"initiator",goal:"Execute the benchmark's notebook from a clean sandbox and return it with its outputs",dependsOn:[],subagents:[],model:"bedrock:us.anthropic.claude-sonnet-4-6",mcpServer:"",tools:["Notebook Executor"],trigger:"",approval:"auto"},{id:"analyst",name:"Benchmark Analyst",ref:"",role:"contributor",goal:"Compare what the notebook produced against what the evalset expected, and say where and by how much they differ",dependsOn:["runner"],subagents:[],model:"bedrock:us.anthropic.claude-sonnet-4-6",mcpServer:"",tools:["Notebook Reader"],trigger:"",approval:"auto"},{id:"reviewer",name:"Benchmark Reviewer",ref:"",role:"finalizer",goal:"Check the analyst's comparison against the notebook's own outputs and say whether the conclusion is supported by the evidence",dependsOn:["analyst"],subagents:[],model:"bedrock:us.anthropic.claude-sonnet-4-6",mcpServer:"",tools:["Notebook Reader"],trigger:"",approval:"auto"}]},OPTIMIZE_GRID_OPERATIONS_TEAM_SPEC_0_0_1={id:"optimize-grid-operations",version:"0.0.1",name:"Optimize Grid Operations Team",description:"A multi-agent team that processes millions of IoT sensor data points from smart meters, substations, and renewable generation assets. Predicts equipment failures 2–4 weeks in advance, optimises load balancing across the grid, and reduces unplanned downtime by 50%.",tags:["energy","utilities","smart-grid","iot","predictive-maintenance","sustainability"],enabled:!0,icon:"zap",emoji:"⚡",color:"#1a7f37",agentSpecId:"optimize-grid-operations:0.0.1",orchestrationProtocol:"datalayer",executionMode:"sequential",supervisor:{name:"Grid Operations Orchestrator Agent",ref:"",model:"openai:gpt-4.1",goal:"",instructions:"",approval:"auto",canTerminate:!0},routingInstructions:"Start with Sensor Ingestion to process real-time telemetry, then Anomaly Detector for pattern identification, then Failure Predictor for maintenance forecasting, then Grid Balancer for load optimisation. Escalate critical failure predictions (< 48h) immediately to operations dispatch.",delegation:{maxDepth:2,allowPeerDelegation:!1,includeGeneralPurpose:!1},context:{sharing:"shared"},validation:{timeout:"600s",retryOnFailure:!0,maxRetries:3},agents:[{id:"grid-1",name:"Sensor Ingestion Agent",ref:"",role:"initiator",goal:"Ingest and process real-time telemetry from SCADA, smart meters, and IoT gateways",dependsOn:[],subagents:[],model:"openai:gpt-4.1",mcpServer:"SCADA MCP",tools:["SCADA Connector","Smart Meter Reader","IoT Gateway Adapter","Time Series Processor"],trigger:"Schedule: Every 5 minutes",approval:"auto"},{id:"grid-2",name:"Anomaly Detector Agent",ref:"",role:"contributor",goal:"Detect vibration, temperature, and voltage anomalies across all grid assets",dependsOn:["grid-1"],subagents:[],model:"openai:gpt-4.1",mcpServer:"Monitoring MCP",tools:["Vibration Analyzer","Temperature Anomaly Detector","Voltage Pattern Scanner","Historical Comparator"],trigger:"",approval:"auto"},{id:"grid-3",name:"Failure Predictor Agent",ref:"",role:"contributor",goal:"Predict equipment failures 2–4 weeks in advance using anomaly patterns and failure history",dependsOn:["grid-2"],subagents:[],model:"anthropic:claude-sonnet-4-20250514",mcpServer:"Predictive Analytics MCP",tools:["Failure Correlation Engine","Risk Scorer","Maintenance Scheduler","Work Order Generator"],trigger:"",approval:"manual"},{id:"grid-4",name:"Grid Balancer Agent",ref:"",role:"finalizer",goal:"Optimise real-time load balancing across renewable and conventional generation sources",dependsOn:["grid-3"],subagents:[],model:"openai:gpt-4.1",mcpServer:"Grid Control MCP",tools:["Load Forecaster","Renewable Integration Model","Dispatch Optimiser","Grid Stability Checker"],trigger:"",approval:"auto"}],reactionRules:[{id:"rr-grid-1",trigger:"grid_instability_detected",action:"emergency_rebalance",auto:!0,maxRetries:1,escalateAfterRetries:1,priority:"critical"},{id:"rr-grid-2",trigger:"forecast_deviation_high",action:"recalibrate_model",auto:!0,maxRetries:2,escalateAfterRetries:2,priority:"medium"}],healthMonitoring:{heartbeatInterval:"10s",staleThreshold:"30s",unresponsiveThreshold:"60s",stuckThreshold:"120s",maxRestartAttempts:5},notifications:{on_start:!0,on_completion:!0,on_failure:!0,on_escalation:!0},output:{formats:["json","csv","pdf"],template:"Grid Operations Dashboard",storage:"s3://reports/grid-operations/"}},PROCESS_CITIZEN_REQUESTS_TEAM_SPEC_0_0_1={id:"process-citizen-requests",version:"0.0.1",name:"Process Citizen Requests Team",description:"A multi-agent team that automates citizen request processing for government agencies. Classifies and triages permits, FOIA requests, and benefit claims from multiple channels. Models policy impacts across population datasets and ensures every automated decision is explainable, auditable, and compliant with transparency mandates.",tags:["government","public-sector","civic","policy","compliance","transparency"],enabled:!0,icon:"organization",emoji:"🏛️",color:"#0550ae",agentSpecId:"process-citizen-requests:0.0.1",orchestrationProtocol:"datalayer",executionMode:"sequential",supervisor:{name:"Citizen Services Orchestrator Agent",ref:"",model:"openai:gpt-4.1",goal:"",instructions:"",approval:"auto",canTerminate:!0},routingInstructions:"Route incoming citizen requests to the Intake Agent for classification and triage, then to the Case Processor for handling and routing, then to the Policy Analyst for impact assessment on relevant items, then to the Transparency Agent for audit trail and public documentation. Escalate urgent citizen safety issues immediately to supervisors.",delegation:{maxDepth:2,allowPeerDelegation:!1,includeGeneralPurpose:!1},context:{sharing:"shared"},validation:{timeout:"300s",retryOnFailure:!0,maxRetries:2},agents:[{id:"cit-1",name:"Intake & Classification Agent",ref:"",role:"initiator",goal:"Classify, triage, and route citizen submissions from web portals, email, and documents",dependsOn:[],subagents:[],model:"openai:gpt-4.1",mcpServer:"Citizen Portal MCP",tools:["Request Classifier","Urgency Assessor","Jurisdiction Router","OCR Scanner"],trigger:"Event: new citizen request received",approval:"auto"},{id:"cit-2",name:"Case Processor Agent",ref:"",role:"contributor",goal:"Process and route requests to appropriate departments with required documentation",dependsOn:["cit-1"],subagents:[],model:"openai:gpt-4.1",mcpServer:"Case Management MCP",tools:["Case Creator","Document Assembler","Department Router","Status Tracker"],trigger:"",approval:"auto"},{id:"cit-3",name:"Policy Impact Analyst Agent",ref:"",role:"contributor",goal:"Model policy outcomes across population datasets with scenario simulation",dependsOn:["cit-2"],subagents:[],model:"anthropic:claude-sonnet-4-20250514",mcpServer:"Policy Analytics MCP",tools:["Monte Carlo Simulator","Demographic Analyzer","Budget Impact Model","Scenario Comparator"],trigger:"",approval:"manual"},{id:"cit-4",name:"Transparency & Audit Agent",ref:"",role:"finalizer",goal:"Generate explainable decision documentation with full audit trail for public record",dependsOn:["cit-3"],subagents:[],model:"openai:gpt-4.1",mcpServer:"Compliance MCP",tools:["Decision Explainer","Audit Trail Builder","FOIA Compliance Checker","Public Record Generator"],trigger:"",approval:"auto"}],reactionRules:[{id:"rr-cit-1",trigger:"priority_request_detected",action:"fast_track_processing",auto:!0,maxRetries:2,escalateAfterRetries:2,priority:"high"},{id:"rr-cit-2",trigger:"policy_ambiguity_detected",action:"request_human_review",auto:!1,maxRetries:1,escalateAfterRetries:1,priority:"medium"}],healthMonitoring:{heartbeatInterval:"30s",staleThreshold:"120s",unresponsiveThreshold:"300s",stuckThreshold:"600s",maxRestartAttempts:3},notifications:{on_start:!1,on_completion:!0,on_failure:!0,on_escalation:!0},output:{formats:["pdf","json"],template:"Citizen Request Processing Report",storage:"s3://reports/citizen-requests/"}},PROCESS_CLINICAL_TRIAL_DATA_TEAM_SPEC_0_0_1={id:"process-clinical-trial-data",version:"0.0.1",name:"Process Clinical Trial Data Team",description:"A multi-agent team that automates clinical trial data processing across dozens of trial sites. Harmonises patient records and lab results to CDISC SDTM format, detects safety signals and adverse events in real time, and prepares submission-ready datasets — all with strict HIPAA and GxP compliance guardrails.",tags:["healthcare","pharma","clinical-trials","patient-data","compliance"],enabled:!0,icon:"heart",emoji:"🏥",color:"#cf222e",agentSpecId:"process-clinical-trial-data:0.0.1",orchestrationProtocol:"datalayer",executionMode:"sequential",supervisor:{name:"Clinical Data Orchestrator Agent",ref:"",model:"anthropic:claude-sonnet-4-20250514",goal:"",instructions:"",approval:"auto",canTerminate:!0},routingInstructions:"Route incoming data through the Ingestion Agent first for format detection and parsing, then to Harmonisation Agent for CDISC SDTM standardisation, then Safety Monitor for adverse event screening, then Submission Preparer for final dataset assembly. Escalate serious adverse events (SAEs) immediately to the medical officer.",delegation:{maxDepth:2,allowPeerDelegation:!1,includeGeneralPurpose:!1},context:{sharing:"shared"},validation:{timeout:"600s",retryOnFailure:!0,maxRetries:2},agents:[{id:"ct-1",name:"Data Ingestion Agent",ref:"",role:"initiator",goal:"Ingest patient records, lab results, and CRFs from clinical sites",dependsOn:[],subagents:[],model:"openai:gpt-4.1",mcpServer:"Clinical EDC MCP",tools:["Medidata Connector","Veeva Vault Reader","Oracle Clinical Adapter","Format Detector"],trigger:"Event: new data batch received from site",approval:"auto"},{id:"ct-2",name:"Harmonisation Agent",ref:"",role:"contributor",goal:"Standardise all data to CDISC SDTM format with MedDRA coding",dependsOn:["ct-1"],subagents:[],model:"openai:gpt-4.1",mcpServer:"Data Standards MCP",tools:["SDTM Mapper","MedDRA Coder","Unit Converter","Site Normaliser"],trigger:"",approval:"auto"},{id:"ct-3",name:"Safety Monitor Agent",ref:"",role:"contributor",goal:"Screen every data point for adverse events and safety signals",dependsOn:["ct-2"],subagents:[],model:"anthropic:claude-sonnet-4-20250514",mcpServer:"Safety Database MCP",tools:["AE Classifier","Signal Detector","SAE Escalator","Evidence Trail Builder"],trigger:"",approval:"manual"},{id:"ct-4",name:"Submission Preparer Agent",ref:"",role:"finalizer",goal:"Assemble submission-ready SDTM datasets with validation and define.xml",dependsOn:["ct-3"],subagents:[],model:"openai:gpt-4.1",mcpServer:"Submission MCP",tools:["Dataset Validator","Define.xml Generator","PDF Report Builder","Compliance Checker"],trigger:"",approval:"auto"}],reactionRules:[{id:"rr-clin-1",trigger:"safety_signal_detected",action:"halt_and_escalate",auto:!0,maxRetries:0,escalateAfterRetries:0,priority:"critical"},{id:"rr-clin-2",trigger:"data_integrity_violation",action:"quarantine_and_notify",auto:!0,maxRetries:1,escalateAfterRetries:1,priority:"critical"}],healthMonitoring:{heartbeatInterval:"10s",staleThreshold:"45s",unresponsiveThreshold:"90s",stuckThreshold:"180s",maxRestartAttempts:2},notifications:{on_start:!0,on_completion:!0,on_failure:!0,on_escalation:!0},output:{formats:["pdf","json","xml"],template:"Clinical Trial Data Report",storage:"s3://reports/clinical-trials/"}},SALES_AND_ACCOUNTING_TEAM_SPEC_0_0_1={id:"sales-and-accounting",version:"0.0.1",name:"Sales and Accounting",description:"A sales desk in the browser that gets financial reports from an accounting application on a runtime, over A2A. Sales takes the request and reports the answer; Accounting reads the Odoo books and answers.",tags:["example","sales","accounting","finance","a2a","odoo"],enabled:!0,icon:"people",emoji:"🤝",color:"#0969da",agentSpecId:"",orchestrationProtocol:"a2a",executionMode:"supervisor",supervisor:{name:"Sales",ref:"",app:"sales:0.0.3",model:"",goal:"",instructions:"",approval:"auto",canTerminate:!0},routingInstructions:"Sales asks Accounting for every figure from the books, one request each time, and reports what Accounting answers without adding to it.",entry:"sales",suggestions:[{text:"Which customer invoices are still open, and how much is due in total?",emoji:"🧾"},{text:"Chart the aged receivables as of today, by customer.",emoji:"⏳"},{text:"Which invoices make up the largest balance due? Show me each one.",emoji:"🔎"},{text:"Send a payment reminder to every customer whose invoice is overdue.",emoji:"✉️"}],delegation:{maxDepth:1,allowPeerDelegation:!0,includeGeneralPurpose:!1},context:{sharing:"shared"},validation:{timeout:"300s",retryOnFailure:!1,maxRetries:0},agents:[{id:"sales",name:"",ref:"",app:"sales:0.0.3",runsIn:"browser",talksTo:[{member:"accounting",over:"a2a"}],role:"initiator",goal:"Take the person's request for a financial report, ask Accounting for it, and hand over what Accounting answered.",dependsOn:[],subagents:[],model:"",mcpServer:"",tools:[],trigger:"",approval:"auto"},{id:"accounting",name:"",ref:"",app:"accounting:0.0.2",runsIn:"runtime",role:"contributor",goal:"Answer report requests from the Odoo books, read only, over A2A.",dependsOn:[],subagents:[],model:"",mcpServer:"",tools:[],trigger:"",approval:"auto"}]},SYNC_CRM_CONTACTS_TEAM_SPEC_0_0_1={id:"sync-crm-contacts",version:"0.0.1",name:"Sync CRM Contacts Team",description:"A multi-agent team that collects and aggregates contact data from multiple CRM sources, analyzes and deduplicates records, writes cleaned data back, and generates sync summary reports.",tags:["sales","crm","data-sync","deduplication"],enabled:!0,icon:"people",emoji:"🔄",color:"#0969da",agentSpecId:"sync-crm-contacts:0.0.1",orchestrationProtocol:"datalayer",executionMode:"sequential",supervisor:{name:"CRM Orchestrator Agent",ref:"",model:"bedrock:us.anthropic.claude-sonnet-4-6",goal:"",instructions:"",approval:"auto",canTerminate:!0},routingInstructions:"Route data collection tasks to the Data Collector first, then analysis, then sync, then reporting. Escalate to human if sync fails 3 times.",delegation:{maxDepth:2,allowPeerDelegation:!1,includeGeneralPurpose:!1},context:{sharing:"shared"},validation:{timeout:"300s",retryOnFailure:!0,maxRetries:3},agents:[{id:"tm-1",name:"Data Collector Agent",ref:"",role:"initiator",goal:"Collect and aggregate contact data from multiple CRM sources",dependsOn:[],subagents:[],model:"openai:gpt-4.1",mcpServer:"Data Processing MCP",tools:["API Connector","Data Parser"],trigger:"Schedule: Daily at 2:00 AM",approval:"auto"},{id:"tm-2",name:"Analyzer Agent",ref:"",role:"contributor",goal:"Analyze collected data and identify patterns and duplicates",dependsOn:["tm-1"],subagents:[],model:"bedrock:us.anthropic.claude-sonnet-4-6",mcpServer:"Analytics MCP",tools:["Statistical Analysis","ML Predictor","Deduplicator"],trigger:"",approval:"manual"},{id:"tm-3",name:"Sync Writer Agent",ref:"",role:"contributor",goal:"Write cleaned and merged contacts back to the CRM systems",dependsOn:["tm-2"],subagents:[],model:"openai:gpt-4.1",mcpServer:"CRM Write MCP",tools:["Salesforce Connector","HubSpot Connector"],trigger:"",approval:"manual"},{id:"tm-4",name:"Report Generator Agent",ref:"",role:"finalizer",goal:"Generate sync summary reports and send notifications",dependsOn:["tm-3"],subagents:[],model:"openai:gpt-4.1",mcpServer:"Document Generation MCP",tools:["PDF Generator","Chart Builder","Email Sender"],trigger:"",approval:"auto"}],reactionRules:[{id:"rr-crm-1",trigger:"sync_conflict_detected",action:"log_and_skip",auto:!0,maxRetries:3,escalateAfterRetries:3,priority:"medium"},{id:"rr-crm-2",trigger:"api_rate_limit_hit",action:"backoff_and_retry",auto:!0,maxRetries:5,escalateAfterRetries:5,priority:"low"}],healthMonitoring:{heartbeatInterval:"30s",staleThreshold:"120s",unresponsiveThreshold:"300s",stuckThreshold:"600s",maxRestartAttempts:3},notifications:{on_start:!1,on_completion:!0,on_failure:!0,on_escalation:!1},output:{formats:["json","csv"],template:"CRM Sync Summary",storage:"s3://reports/crm-sync/"}},TEAM_SPECS={"analyze-campaign-performance":ANALYZE_CAMPAIGN_PERFORMANCE_TEAM_SPEC_0_0_1,"analyze-support-tickets":ANALYZE_SUPPORT_TICKETS_TEAM_SPEC_0_0_1,"audit-inventory-levels":AUDIT_INVENTORY_LEVELS_TEAM_SPEC_0_0_1,"automate-regulatory-reporting":AUTOMATE_REGULATORY_REPORTING_TEAM_SPEC_0_0_1,"comprehensive-sales-analytics":COMPREHENSIVE_SALES_ANALYTICS_TEAM_SPEC_0_0_1,"crop-monitoring":CROP_MONITORING_TEAM_SPEC_0_0_1,"disaster-assessment":DISASTER_ASSESSMENT_TEAM_SPEC_0_0_1,jupyter:JUPYTER_TEAM_SPEC_0_0_1,"month-end-close":MONTH_END_CLOSE_TEAM_SPEC_0_0_1,"notebook-benchmark":NOTEBOOK_BENCHMARK_TEAM_SPEC_0_0_1,"optimize-grid-operations":OPTIMIZE_GRID_OPERATIONS_TEAM_SPEC_0_0_1,"process-citizen-requests":PROCESS_CITIZEN_REQUESTS_TEAM_SPEC_0_0_1,"process-clinical-trial-data":PROCESS_CLINICAL_TRIAL_DATA_TEAM_SPEC_0_0_1,"sales-and-accounting":SALES_AND_ACCOUNTING_TEAM_SPEC_0_0_1,"sync-crm-contacts":SYNC_CRM_CONTACTS_TEAM_SPEC_0_0_1},VOICE_CATALOGUE={"kokoro-af-heart":{id:"kokoro-af-heart",version:"0.0.1",name:"Heart",description:"A warm American English voice, Kokoro's best graded (A).",engine:"kokoro",model:"kokoro-82m",voice:"af_heart",languages:["en-US"],where:["server"],licence:{weights:"Apache-2.0"},attribution:"",watermark:!1,sample:"Hello. I read the answers aloud, sentence by sentence, as they are written."},"kokoro-bf-emma":{id:"kokoro-bf-emma",version:"0.0.1",name:"Emma",description:"A clear British English voice.",engine:"kokoro",model:"kokoro-82m",voice:"bf_emma",languages:["en-GB"],where:["server"],licence:{weights:"Apache-2.0"},attribution:"",watermark:!1,sample:"Hello. I read the answers aloud, sentence by sentence, as they are written."},"kokoro-ff-siwis":{id:"kokoro-ff-siwis",version:"0.0.1",name:"Siwis",description:"A French voice, Kokoro's only one, trained on the SIWIS French Speech Synthesis Database, whose licence asks for its attribution.",engine:"kokoro",model:"kokoro-82m",voice:"ff_siwis",languages:["fr-FR"],where:["server"],licence:{weights:"Apache-2.0",dataset:"CC-BY-4.0"},attribution:"Trained on the SIWIS French Speech Synthesis Database, by Pierre-Edouard Honnet, Alexandros Lazaridis, Philip N. Garner and Junichi Yamagishi (Idiap Research Institute), under CC BY 4.0.",watermark:!1,sample:"Bonjour. Je lis les réponses à voix haute, phrase par phrase, à mesure qu'elles s'écrivent."}},SPEECH_MODEL_CATALOGUE={"kokoro-82m":{id:"kokoro-82m",version:"0.0.1",name:"Kokoro 82M",description:"Text to speech on Datalayer's servers, on CPU: hexgrad's Kokoro-82M v1.0 exported to ONNX, in full precision, with the voices file that holds its 54 voices, run by kokoro-onnx. Its phonemes come from eSpeak NG (GPL-3.0), which runs on the server and is never sent to a browser. Full precision, not the 8-bit export: on a 16-core CPU the 8-bit one speaks slower than real time (6 s for 3.9 s of speech), this one about four times faster than real time (1 s).",provider:"hexgrad",task:"tts",engine:"kokoro-onnx",dtype:"fp32",languages:["en","fr","es","it","pt","hi","ja","zh"],where:["server"],streaming:!1,licence:{weights:"Apache-2.0",code:"MIT"},attribution:"",upstream:"https://huggingface.co/hexgrad/Kokoro-82M",revision:"model-files-v1.0",files:[{path:"kokoro-v1.0.onnx",sha256:"7d5df8ecf7d4b1878015a32686053fd0eebe2bc377234608764cc0ef3636a6c5",size:325532387},{path:"voices-v1.0.bin",sha256:"bca610b8308e8d99f32e6fe4197e7ec01679264efed0cac9140fe9c29f1fbf7d",size:28214398}]},"moonshine-base-en":{id:"moonshine-base-en",version:"0.0.1",name:"Moonshine Base (English)",description:"Speech to text in the browser, in English: Useful Sensors' Moonshine Base (61M parameters), its ONNX export quantized to 8 bits, run by transformers.js. One of the English models whose weights are MIT; the legacy non-English Moonshine models are under a non-commercial licence and are not listed.",provider:"usefulsensors",task:"stt",engine:"transformers.js",dtype:"q8",languages:["en"],where:["device"],streaming:!1,licence:{weights:"MIT",code:"MIT"},attribution:"",upstream:"https://huggingface.co/UsefulSensors/moonshine-base",revision:"b1e9b6aae3c3c7298f10c3798393fdf38e8fbbad",files:[{path:"config.json",sha256:"fab7241d1e9fc6c2370c4c6dfb5da79bb54d67ed9ab6b507ac51d29d2abe01d1",size:922},{path:"generation_config.json",sha256:"f9b3f711b57be7def2e50a8942f64f36ee0a55fad5b84ff93a687b6c5bcc1d44",size:147},{path:"preprocessor_config.json",sha256:"fa43a7017ef85cd1d0fba0d9aae77c8adb16990ae6f11115631f41ec5d8aa679",size:128},{path:"special_tokens_map.json",sha256:"ca3d163bab055381827226140568f3bef7eaac187cebd76878e0b63e9e442356",size:3},{path:"tokenizer.json",sha256:"7b913404bdd039af4756783218af4440bc07fb7d6d8258d677e34f95b3ec416f",size:3761754},{path:"tokenizer_config.json",sha256:"edaee394565d428ea98a663ae7209cdcfeefc5585c42d7a570ff7c986df2cd15",size:135735},{path:"onnx/encoder_model_quantized.onnx",sha256:"1dd9ab0a7f987113d30affcba5a068d11c8f90fa0223caa3e491ade431ad9751",size:20513063},{path:"onnx/decoder_model_merged_quantized.onnx",sha256:"cc9f3cd6698a369c6008b41aa60aa3fb3322e7f03c9bdf19d8e6b7200afca4f3",size:42498870}]},"moonshine-tiny-en":{id:"moonshine-tiny-en",version:"0.0.1",name:"Moonshine Tiny (English)",description:"Speech to text in the browser, in English: Useful Sensors' Moonshine Tiny (27M parameters), its ONNX export quantized to 8 bits, run by transformers.js. One of the English models whose weights are MIT; the legacy non-English Moonshine models are under a non-commercial licence and are not listed.",provider:"usefulsensors",task:"stt",engine:"transformers.js",dtype:"q8",languages:["en"],where:["device"],streaming:!1,licence:{weights:"MIT",code:"MIT"},attribution:"",upstream:"https://huggingface.co/UsefulSensors/moonshine-tiny",revision:"a6da1241cd305dcd64eab1edbd615f2bb9aabb95",files:[{path:"config.json",sha256:"558e1e02069137c796ace1e50c48d8fe451f04a295929138e6bea885517f0edb",size:921},{path:"generation_config.json",sha256:"f9b3f711b57be7def2e50a8942f64f36ee0a55fad5b84ff93a687b6c5bcc1d44",size:147},{path:"preprocessor_config.json",sha256:"fa43a7017ef85cd1d0fba0d9aae77c8adb16990ae6f11115631f41ec5d8aa679",size:128},{path:"special_tokens_map.json",sha256:"ca3d163bab055381827226140568f3bef7eaac187cebd76878e0b63e9e442356",size:3},{path:"tokenizer.json",sha256:"7b913404bdd039af4756783218af4440bc07fb7d6d8258d677e34f95b3ec416f",size:3761754},{path:"tokenizer_config.json",sha256:"edaee394565d428ea98a663ae7209cdcfeefc5585c42d7a570ff7c986df2cd15",size:135735},{path:"onnx/encoder_model_quantized.onnx",sha256:"c6fc4b7bc5af75c0591fd157a1f3829b533d18e9769a888fd95a62e470dd4f4a",size:7937661},{path:"onnx/decoder_model_merged_quantized.onnx",sha256:"eed87831c3a6103534aae7d47a5d485025c659a1323901513961c39fe8a1a367",size:20243286}]},"silero-vad":{id:"silero-vad",version:"0.0.1",name:"Silero VAD",description:"Where speech starts and ends in what the microphone heard, in the browser: Silero VAD (about 2 MB), the build @ricky0123/vad-web 0.0.31 ships and runs on onnxruntime-web. Push-to-talk keeps the speech it finds and drops the rest.",provider:"snakers4",task:"vad",engine:"vad-web",dtype:"fp32",languages:[],where:["device"],streaming:!0,licence:{weights:"MIT",code:"ISC"},attribution:"",upstream:"https://github.com/snakers4/silero-vad",revision:"0.0.31",files:[{path:"silero_vad_legacy.onnx",sha256:"a35ebf52fd3ce5f1469b2a36158dba761bc47b973ea3382b3186ca15b1f5af28",size:1807522}]},"whisper-base":{id:"whisper-base",version:"0.0.1",name:"Whisper Base",description:"Speech to text in the browser for the languages Moonshine's MIT models do not speak, French first: OpenAI's Whisper base (74M parameters, 99 languages), its ONNX export quantized to 8 bits, run by transformers.js. A clip at a time.",provider:"openai",task:"stt",engine:"transformers.js",dtype:"q8",languages:["en","fr"],where:["device"],streaming:!1,licence:{weights:"MIT",code:"MIT"},attribution:"",upstream:"https://huggingface.co/openai/whisper-base",revision:"1846881b6b3a3024392c1eea3ad983695bc23925",files:[{path:"config.json",sha256:"f4d0608f7d918166da7edb3e188de5ef1bfe70d9802e785d271fd88111e9cf4b",size:2243},{path:"generation_config.json",sha256:"61070cf8de25b1e9256e8e102ded49d8d24a8369ed36ef84fdf21549e68125a0",size:3832},{path:"preprocessor_config.json",sha256:"a6a76d28c93edb273669eb9e0b0636a2bddbb1272c3261e47b7ca6dfdbac1b8d",size:339},{path:"special_tokens_map.json",sha256:"e67ae3a0aaa99abcd9f187138e12db1f65c16a14761c50ef10eef2c174a7a691",size:2194},{path:"tokenizer.json",sha256:"27fc476bfe7f17299480be2273fc0608e4d5a99aba2ab5dec5374b4482d1a566",size:2480466},{path:"tokenizer_config.json",sha256:"2e036e4dbacfdeb7242c7d4ec4149f4a16e86026048f94d1637e3a8ee9c6a573",size:282682},{path:"added_tokens.json",sha256:"9715fd2243b6f06a5858b5e32950d2853f73dd5bc201aafcf76f5082a2d8acd1",size:34604},{path:"normalizer.json",sha256:"bf1c507dc8724ca9cf9903640dacfb69dae2f00edee4f21ceba106a7392f26dd",size:52666},{path:"vocab.json",sha256:"50d6a919f0a0601d56a04eb583c780d18553aa388254ba3158eb6a00f13e2c1a",size:1036584},{path:"onnx/encoder_model_quantized.onnx",sha256:"5862993336bf33acd23736071aae2b32261d3b1b2f37780194460d4ef974dd46",size:23201314},{path:"onnx/decoder_model_merged_quantized.onnx",sha256:"fa3ef9902734ce5ae6f9ef2bdb2ba9a6c4b5785b09f4f420ce036573dc9d090b",size:53693315}]},"whisper-large-v3-turbo":{id:"whisper-large-v3-turbo",version:"0.0.1",name:"Whisper Large v3 Turbo",description:"Speech to text on Datalayer's servers, on CPU: OpenAI's Whisper large-v3-turbo (809M parameters, 99 languages), converted to CTranslate2 in half precision and run by faster-whisper, its weights quantized to 8 bits when loaded. A recording of up to a minute at a time; the language is detected when the page does not say it.",provider:"openai",task:"stt",engine:"faster-whisper",dtype:"float16",languages:["en","fr","es","it","pt","de","nl","ja","zh","hi"],where:["server"],streaming:!1,licence:{weights:"MIT",code:"MIT"},attribution:"",upstream:"https://huggingface.co/openai/whisper-large-v3-turbo",revision:"0a363e9161cbc7ed1431c9597a8ceaf0c4f78fcf",files:[{path:"config.json",sha256:"b0253ea6c0d3bea6b1e19e91a02acfd3b53f4467362efcb5a3e6b16c9b3a9b7e",size:2263},{path:"preprocessor_config.json",sha256:"7ccc62c6f2765af1f3b46c00c9b5894426835a05021c8b9c01eecb6dfb542711",size:340},{path:"tokenizer.json",sha256:"297b13372ac43916285644fb9687add3cc62ee2a1adb60da3dc25cc94c1871fd",size:2710337},{path:"vocabulary.json",sha256:"c69260f2ab26d659b7c398f9a2b2b48ed0df16c3b47d7326782fd9cba71690c1",size:1068114},{path:"model.bin",sha256:"e76620f83d5f5b69efd3d87e3dc180c1bd21df9fbebacfd4335e5e1efcc018da",size:1617884929}]},"whisper-small":{id:"whisper-small",version:"0.0.1",name:"Whisper Small",description:"Speech to text on Datalayer's servers for short spoken turns, on CPU: OpenAI's Whisper small (244M parameters, 99 languages), converted to CTranslate2 and run by faster-whisper, its weights quantized to 8 bits when loaded. About four times faster than large-v3-turbo; on the fixtures it hears English as well (3.3% against 2.4%) and French less well (16.1% against 2.6%). Recordings longer than a turn go to large-v3-turbo.",provider:"openai",task:"stt",engine:"faster-whisper",dtype:"float16",languages:["en","fr","es","it","pt","de","nl","ja","zh","hi"],where:["server"],streaming:!1,licence:{weights:"MIT",code:"MIT"},attribution:"",upstream:"https://huggingface.co/openai/whisper-small",revision:"536b0662742c02347bc0e980a01041f333bce120",files:[{path:"config.json",sha256:"b55496ac7940a7ae47d2c01eab40edfd8701feec1229d9cce3b40014383fb828",size:2370},{path:"tokenizer.json",sha256:"fb7b63191e9bb045082c79fd742a3106a12c99513ab30df4a0d47fa6cb6fd0ab",size:2203239},{path:"vocabulary.txt",sha256:"34ce3fe1c5041027b3f8d42912270993f986dbc4bb34cf27f951e34a1e453913",size:459861},{path:"model.bin",sha256:"3e305921506d8872816023e4c273e75d2419fb89b24da97b4fe7bce14170d671",size:483546902}]}};function voiceSpeaks(Au,lo){return Au.languages.some($u=>$u===lo||$u.split("-")[0]===lo)}function voiceFor(Au){const lo=Object.values(VOICE_CATALOGUE);return lo.find($u=>$u.languages.includes(Au))??lo.find($u=>voiceSpeaks($u,Au.split("-")[0]))}function transcriberFor(Au){const lo=Au.split("-")[0],$u=Object.values(SPEECH_MODEL_CATALOGUE).filter(Ru=>Ru.task==="stt"&&Ru.where.includes("device")&&Ru.languages.includes(lo));return $u.find(Ru=>Ru.id==="moonshine-tiny-en")??$u.find(Ru=>Ru.id.startsWith("moonshine-"))??$u[0]}const MCP_SERVER_MAP={"tavily:0.0.1":TAVILY_MCP_SERVER_0_0_1},SKILL_MAP={"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,"text-summarizer:0.0.1":TEXT_SUMMARIZER_SKILL_SPEC_0_0_1};function toAgentSkillSpec(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={"runtime-echo:0.0.1":RUNTIME_ECHO_BACKEND_TOOL_SPEC_0_0_1},FRONTEND_TOOL_MAP={"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},COG_CRAWLER_AGENTSPEC_0_0_1={id:"cog-crawler",version:"0.0.1",name:"Crawler Cog",description:"Researches the web and public repositories under the Web Research Frame: every finding rests on a source that was opened, is cited, and is checked before it is reported.",tags:["market-analyst","agent-worker","research","github","analysis","cog"],domain:"market-analyst",enabled:!0,model:"bedrock:us.anthropic.claude-sonnet-4-6",modelAdditionals:["alibaba:qwen-max"],mcpServers:[MCP_SERVER_MAP["tavily:0.0.1"]],skills:[SKILL_MAP["github:0.0.1"]?toAgentSkillSpec(SKILL_MAP["github:0.0.1"]):void 0,SKILL_MAP["events:0.0.1"]?toAgentSkillSpec(SKILL_MAP["events:0.0.1"]):void 0,SKILL_MAP["crawl:0.0.1"]?toAgentSkillSpec(SKILL_MAP["crawl:0.0.1"]):void 0].filter(Boolean),backendTools:[],frontendTools:[FRONTEND_TOOL_MAP["jupyter-notebook:0.0.1"],FRONTEND_TOOL_MAP["lexical-document:0.0.1"]],environmentName:"ai-agents-env",icon:"globe",emoji:"🌐",color:"#10B981",suggestions:[{text:"Search the web for recent news about AI agents",summary:"AI agent news"},{text:"Find trending open-source Python projects on GitHub",summary:"Trending Python projects"},{text:"Research best practices for building RAG applications",summary:"RAG best practices"},{text:"Compare popular JavaScript frameworks in 2024",summary:"JavaScript frameworks 2024"}],welcomeMessage:`Hi! I'm the Crawler Cog. I research the web and GitHub under the Web Research Frame: I open what I cite, I say which sources are primary, and I tell you where sources disagree.
|
|
2925
2928
|
`,welcomeNotebook:void 0,welcomeDocument:void 0,sandboxVariant:"jupyter-server",harness:"pydantic-ai",systemPrompt:`You are a web crawling and research assistant with access to Tavily search and GitHub tools. Use Tavily to search the web for current information and search GitHub repositories for relevant projects. Synthesize information from multiple sources and provide clear summaries with sources cited.
|
|
2926
2929
|
|
|
2927
2930
|
## Frames
|
|
@@ -3845,13 +3848,13 @@ ${lo}`;let Iu=MODULES.get(Ru);return Iu||(Iu=(async()=>{const Pu=await $u(Au,{cr
|
|
|
3845
3848
|
${Mu}`:ju,inputs:Mu,clear:Ou?[]:[DRAFT.path],loop:Lu()}:{refused:"Nothing to send: write a message first."}}}}const text=(Au,lo,$u)=>({id:Au,component:"Text",text:{path:lo},...$u?{variant:$u}:{}}),button=(Au,lo,$u,Ru=!1)=>[{id:Au,component:"Button",child:`${Au}-label`,...Ru?{variant:"primary"}:{},action:{event:{name:$u}}},{id:`${Au}-label`,component:"Text",text:lo}];function settingsForm(Au){const lo=pageOf(Au);return lo?pageForm(Au,lo):Au.interface.settings&&settingFields(Au.interface.settings).length?[{id:"settings",component:"Form",schema:Au.interface.settings,...Au.interface.settingsUi?{ui:Au.interface.settingsUi}:{},values:{path:"/inputs"}}]:[]}function pageForm(Au,lo){const $u=Au.interface.settings,Ru={...lo.inputs,type:"object",properties:{...$u?.properties,...lo.inputs.properties},required:[...$u?.required??[],...lo.inputs.required??[]]},Iu={...Au.interface.settingsUi,...lo.inputsUi},Pu=lo.outputs.flatMap(Ou=>[...Ou.title?[{id:`output-${Ou.name}-title`,component:"Text",text:Ou.title,variant:"h4"}]:[],{...Ou.props,id:`output-${Ou.name}`,component:Ou.component,[pageOutputShows(Ou.component,Au.interface.customComponents)??"text"]:{path:outputPath(Ou.name)}}]);return[{id:"inputs",component:"Form",schema:Ru,...Object.keys(Iu).length>0?{ui:Iu}:{},values:{path:"/inputs"}},...lo.live?[]:button("run-page","Run",PAGE_ACTION,!0),...Pu]}function defaultAppSurface(Au){const lo=appKindPaths(Au).inputs?settingsForm(Au):[],$u=[];switch(Au.kind){case"chat":$u.push(text("question","/question","h3"),text("answer","/answer"),text("status","/status","caption"),...lo);break;case"widget":if(pageOf(Au)){$u.push(...lo);break}$u.push(...lo,{id:"actions",component:"Row",children:["run","stop"]},...button("run","Run","run",!0),...button("stop","Stop","stop"),text("status","/status","caption"),text("output","/output"));break;case"worker":$u.push(text("goal","/goal","h3"),text("status","/status","caption"),text("activity","/activity","caption"),text("report","/report"));break}const Ru=new Set($u.flatMap(Iu=>[...Array.isArray(Iu.children)?Iu.children:[],Iu.child].filter(Pu=>typeof Pu=="string")));return[{id:"root",component:"Column",children:$u.map(Iu=>Iu.id).filter(Iu=>!Ru.has(Iu))},...$u]}function appPageMessages(Au,lo){const $u=surfaceComponents(Au);return[{version:"v0.9",createSurface:{surfaceId:APP_PAGE_SURFACE_ID,catalogId:lo}},{version:"v0.9",updateComponents:{surfaceId:APP_PAGE_SURFACE_ID,components:$u.length>0?$u:defaultAppSurface(Au)}},{version:"v0.9",updateDataModel:{surfaceId:APP_PAGE_SURFACE_ID,path:"/",value:appPageInitialData(Au)}}]}const LOOP_PAGE="loop.page";function streamEvents(Au){const lo=[];for(const $u of Au.split(`
|
|
3846
3849
|
|
|
3847
3850
|
`)){const Ru=$u.split(`
|
|
3848
|
-
`).filter(Iu=>Iu.startsWith("data:")).map(Iu=>Iu.slice(5).trim()).join("");if(Ru)try{lo.push(JSON.parse(Ru))}catch{}}return lo}function pageTurnOf(Au){let lo=null;for(const $u of streamEvents(Au)){if($u.type==="RUN_ERROR")return{refused:String($u.message??"Its page could not run.")};if($u.type==="CUSTOM"&&$u.name===LOOP_PAGE){const Ru=$u.value??{};lo={outputs:Ru.outputs??{},inputs:Ru.inputs??{}}}}return lo??{refused:"Its page showed nothing: its code answered no outputs."}}const base=Au=>`${Au.serverUrl.replace(/\/+$/,"")}/api/v1/apps/sessions`;async function posted(Au,lo,$u){const Ru=await(Au.fetcher??fetch)(lo,{method:"POST",headers:{"content-type":"application/json",...Au.token?{Authorization:`Bearer ${Au.token}`}:{}},body:JSON.stringify($u)});if(!Ru.ok){let Iu="";try{const Pu=await Ru.json();Iu=typeof Pu.detail=="string"?Pu.detail:""}catch{}throw new Error(Iu||`Its page was refused (${Ru.status}).`)}return Ru.text()}async function openPageSession(Au){const lo=await posted(Au,base(Au),{agent:Au.agentId});for(const $u of streamEvents(lo))if($u.type==="CUSTOM"&&$u.name==="loop.session"){const Ru=$u.value?.uid;if(typeof Ru=="string"&&Ru)return Ru}throw new Error("The runtime opened no session for its page.")}async function runPageIn(Au,lo,$u){try{const Ru=await posted(Au,`${base(Au)}/${encodeURIComponent(lo)}/page`,{inputs:$u});return pageTurnOf(Ru)}catch(Ru){return{refused:Ru instanceof Error?Ru.message:String(Ru)}}}function outputsData(Au){return Object.fromEntries(Object.entries(Au).map(([lo,$u])=>[`/outputs/${lo}`,$u]))}const PAGE_RUN_DELAY_MS=300,NO_TURN$6=signal$2({id:0,status:"idle"}),NO_CONVERSATION$2=signal$2([]);function componentsOnPage(Au){const lo=new Set;for(const $u of Au){const Ru=$u.updateComponents;for(const Iu of Ru?.components??[])lo.add(String(Iu.component))}return[...lo]}function blocksMissing(Au,lo){const $u=new Set(lo),Ru=Au.filter(Iu=>!$u.has(Iu));return Ru.length===0?null:`This page places ${Ru.join(", ")}, which no enabled plugin contributes: ${Ru.length===1?"it is":"they are"} drawn once the plugin that contributes ${Ru.length===1?"it":"them"} is on.`}function AppPage({app:Au,workspace:lo}){const $u=useContributions(LoopChatTurn),Ru=useSignalValue$1($u[0]?.value.turn??NO_TURN$6),Iu=useSignalValue$1($u[0]?.value.conversation??NO_CONVERSATION$2),Pu=reactExports.useMemo(()=>appPageMessages(Au,SURFACE_CATALOG_ID),[Au]),Ou=useContributions(LoopCanvasBlock),Mu=[...new Set(Ou.map(bd=>bd.value.id))].sort(),Du=Mu.join(","),Lu=useOwnComponents(),Bu=reactExports.useMemo(()=>{const bd=blocksMissing(componentsOnPage(Pu),Mu);if(bd)return{problem:bd};try{return{catalog:catalogOfBlocks(Mu,Lu)}}catch(Sd){return{problem:Sd instanceof Error?Sd.message:String(Sd)}}},[Pu,Du,Lu]),[ju,Fu]=reactExports.useState(null),zu=pageOf(Au),[Uu,Hu]=reactExports.useState({}),Vu=reactExports.useMemo(()=>({...appPageData(Au,Ru,Iu),...outputsData(Uu)}),[Au,Ru,Iu,Uu]),Gu=useIAMStore(bd=>bd.token)??"",Wu=useChatWords(),Ku=agentServerOf(lo.sandbox,lo.serverUrl),Ju=reactExports.useRef(null);Ju.current=Ku===void 0?null:{serverUrl:Ku,agentId:lo.agentId||Au.id,token:Gu||void 0};const Yu=reactExports.useRef("");Yu.current=Ku===void 0?noRuntimeSaid(lo.sandbox,Wu):"";const Xu=reactExports.useRef(null),ed=reactExports.useRef(!1),td=reactExports.useRef(null),nd=reactExports.useRef(""),od=reactExports.useRef(!0),sd=reactExports.useCallback(bd=>{td.current=bd,!ed.current&&(ed.current=!0,(async()=>{for(;td.current&&od.current;){const Sd=td.current;td.current=null;const Ed=Ju.current;if(!Ed){Fu(Yu.current);continue}try{Xu.current??=openPageSession(Ed);const cd=await runPageIn(Ed,await Xu.current,Sd);if(!od.current)break;"refused"in cd?Fu(cd.refused):(Fu(null),Hu(cd.outputs))}catch(cd){Xu.current=null,od.current&&Fu(cd instanceof Error?cd.message:String(cd))}}ed.current=!1})())},[]),ad=reactExports.useRef(null);reactExports.useEffect(()=>(od.current=!0,()=>{od.current=!1,ad.current?.()}),[]);const pd=reactExports.useCallback(bd=>{if(!zu?.live)return;ad.current?.();let Sd;const Ed=dd=>{const md=pageInputsOf(Au,dd),ld=JSON.stringify(md);ld!==nd.current&&(clearTimeout(Sd),Sd=setTimeout(()=>{nd.current=ld,sd(md)},PAGE_RUN_DELAY_MS))},cd=bd.dataModel.subscribe("/inputs",Ed);Ed(cd.value),ad.current=()=>{clearTimeout(Sd),cd.unsubscribe()}},[Au,zu?.live,sd]),gd=reactExports.useRef(lo);gd.current=lo;const _d=reactExports.useRef(""),yd=reactExports.useCallback((bd,Sd)=>{const Ed=appPageAction(Au,{name:bd.name,context:bd.context??{}},dd=>Sd?.dataModel.get(dd),_d.current),cd=gd.current.viewControls;if("refused"in Ed){Fu(Ed.refused);return}if(Fu(null),"runPage"in Ed)sd(Ed.runPage);else if("stop"in Ed)cd.stop?.();else if("newChat"in Ed)cd.newChat?.();else{if(cd.send){const dd=cd.send(Ed.send,{loop:Ed.loop});if(dd){Fu(dd);return}}else if(Ed.loop.files){Fu("The conversation is not ready for a file yet: try again.");return}else gd.current.prompts.submit(Ed.send);_d.current=Ed.inputs;for(const dd of Ed.clear)Sd?.dataModel.set(dd,"")}},[Au,sd]);return jsxRuntimeExports.jsx(Box,{"data-testid":"app-page",height:"100%",minHeight:0,overflow:"auto",p:3,children:"problem"in Bu?jsxRuntimeExports.jsx(Box,{role:"status",color:"fg.muted",fontSize:1,children:Bu.problem}):jsxRuntimeExports.jsx(InlineSurface,{messages:Pu,data:Vu,onAction:yd,validationError:ju,catalog:Bu.catalog,...zu?{onSurface:pd}:{}},Du)})}const APP_PAGE_PLUGIN_NAME="@datalayer/loop-plugin-app-page";function defineAppPagePlugin(Au){function lo({workspace:Ru}){return jsxRuntimeExports.jsx(AppPage,{app:Au,workspace:Ru})}return{name:`${APP_PAGE_PLUGIN_NAME}-${Au.id}`,displayName:`${Au.name}: its page`,description:`The page of ${Au.name}, drawn beside its conversation.`,octicon:"browser",emoji:Au.emoji||void 0,contributes:[contribution(LoopEditorView,{surfaceId:APP_PAGE_SURFACE,title:Au.name,icon:BrowserIcon,order:-10,load:async()=>({default:lo})},{id:APP_PAGE_SURFACE,order:-10})]}}const APP_HOST_PAGE_VIEW="app-page";function defineAppHostPagePlugin(Au,lo){function $u({workspace:Iu}){return jsxRuntimeExports.jsx(lo,{app:Au,workspace:Iu})}return{name:`${APP_PAGE_PLUGIN_NAME}-${Au.id}`,displayName:`${Au.name}: its page`,description:`The page of ${Au.name}, drawn by its host.`,octicon:"browser",emoji:Au.emoji||void 0,contributes:[contribution(LoopViewType,{viewType:APP_HOST_PAGE_VIEW,title:Au.name,icon:BrowserIcon,order:-10,load:async()=>({default:$u})},{id:APP_HOST_PAGE_VIEW,order:-10})]}}const canvasBlocksPluginName=Au=>`@datalayer/loop-plugin-ui-${Au}`;function uiPluginBlocks(Au){return{name:canvasBlocksPluginName(Au.id),displayName:Au.name,description:`The blocks of ${Au.name} on the Canvas: ${Au.components.map(lo=>lo.name).join(", ")}.`,octicon:"apps",contributes:Au.components.map(lo=>contribution(LoopCanvasBlock,{id:lo.id,ui:Au.id,component:lo},{id:lo.id}))}}const CANVAS_BLOCK_PLUGINS=listUI().filter(Au=>Au.components.length>0).map(uiPluginBlocks),MANAGER_PLUGIN_NAME="@datalayer/reactor-manager",MANAGER_ACTIONS_SLOT="manager-actions",ManagerPluginSource=defineContributionPoint("manager.pluginSource");function usePluginRows(Au,lo){const $u=useReactorPlatform(),Ru=reactExports.useSyncExternalStore($u.subscribe,()=>$u.getRevision());return reactExports.useMemo(()=>$u.listPlugins().filter(Iu=>!lo.has(Iu)).map(Iu=>{const Pu=$u.getManifest(Iu);return{name:Iu,displayName:Pu?.displayName??Iu,description:Pu?.description,emoji:Pu?.emoji,version:Pu?.version,enabled:$u.isEnabled(Iu),disabledBy:Pu?.disabledBy,changeable:!Au.has(Iu),details:[{label:"Delivered by",values:Pu?.extension?[Pu.extension]:[]},{label:"Contributes to",values:Pu?.contributesTo??[]},{label:"Offers contribution points",values:Pu?.contributionPoints??[]},{label:"Requires backend plugins",values:Pu?.requiredBackendPlugins??[]},{label:"Uses if available",values:Pu?.optionalBackendPlugins??[]},{label:"Activates on",values:Pu?.activationEvents??[]}]}}),[$u,Ru,Au,lo])}function pluginMatches(Au,lo){if(!lo)return!0;const $u=lo.trim().toLowerCase();return[Au.name,Au.displayName,Au.description??""].join(" ").toLowerCase().includes($u)}const PluginHoverContext=reactExports.createContext(null);function usePluginHoverControl(){const[Au,lo]=reactExports.useState(null),$u=reactExports.useRef(void 0);return reactExports.useEffect(()=>()=>clearTimeout($u.current),[]),reactExports.useMemo(()=>({openName:Au,show:Ru=>{clearTimeout($u.current),lo(Ru)},hide:()=>{clearTimeout($u.current),$u.current=setTimeout(()=>lo(null),200)}}),[Au])}function useHoverControl(){const Au=reactExports.useContext(PluginHoverContext),lo=usePluginHoverControl();return Au??lo}function PluginDetails({row:Au}){const lo=(Au.details??[]).filter($u=>$u.values.length>0);return jsxRuntimeExports.jsxs(Box,{sx:{p:3,maxWidth:360,display:"grid",gap:2},children:[jsxRuntimeExports.jsxs(Box,{sx:{display:"flex",alignItems:"center",gap:2},children:[Au.emoji?jsxRuntimeExports.jsx(Text$3,{"aria-hidden":!0,children:Au.emoji}):null,jsxRuntimeExports.jsx(Text$3,{sx:{fontWeight:"semibold"},children:Au.displayName}),Au.version?jsxRuntimeExports.jsxs(Text$3,{sx:{fontSize:0,color:"fg.muted"},children:["v",Au.version]}):null]}),jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:"fg.muted",wordBreak:"break-all"},children:Au.name}),Au.description?jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0},children:Au.description}):null,lo.map($u=>jsxRuntimeExports.jsxs(Box,{sx:{display:"grid",gap:1},children:[jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,fontWeight:"semibold"},children:$u.label}),$u.values.map(Ru=>jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:"fg.muted",wordBreak:"break-all"},children:Ru},Ru))]},$u.label)),Au.disabledBy==="dependency"?jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:"attention.fg"},children:"Off because something it depends on is off. It comes back when that does."}):null,Au.changeable?null:jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:"attention.fg"},children:"This one cannot be switched off."})]})}const OVERLAY_TAKES_NO_FOCUS={preventFocusOnOpen:!0,sx:{pointerEvents:"none"},returnFocusRef:{current:null}};function PluginRowView({row:Au,size:lo,onToggle:$u}){const Ru=`plugin-name-${Au.name.replace(/[^a-zA-Z0-9]+/g,"-")}`,Iu=useHoverControl(),Pu=Iu.openName===Au.name,Ou=()=>Iu.show(Au.name),Mu=()=>Iu.hide();return jsxRuntimeExports.jsx(AnchoredOverlay,{open:Pu,onOpen:Ou,onClose:Mu,focusZoneSettings:{disabled:!0},focusTrapSettings:{disabled:!0},overlayProps:OVERLAY_TAKES_NO_FOCUS,side:"outside-right",renderAnchor:Du=>jsxRuntimeExports.jsxs(Box,{...Du,onMouseEnter:Ou,onMouseLeave:Mu,onFocus:Ou,onBlur:Mu,sx:{display:"flex",alignItems:"flex-start",gap:2,py:2,borderBottom:"1px solid",borderColor:"border.muted"},children:[jsxRuntimeExports.jsxs(Box,{sx:{minWidth:0,flex:1},children:[jsxRuntimeExports.jsxs(Box,{sx:{display:"flex",alignItems:"center",gap:1},children:[Au.emoji?jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:1},"aria-hidden":!0,children:Au.emoji}):null,jsxRuntimeExports.jsx(Text$3,{id:Ru,sx:{fontSize:1,fontWeight:"semibold",minWidth:0},children:jsxRuntimeExports.jsx(Truncate,{title:Au.name,maxWidth:"100%",inline:!0,children:Au.displayName})})]}),Au.description?jsxRuntimeExports.jsx(Text$3,{sx:{display:"block",fontSize:0,color:"fg.muted"},children:jsxRuntimeExports.jsx(Truncate,{title:Au.description,maxWidth:"100%",inline:!0,children:Au.description})}):null]}),jsxRuntimeExports.jsx(ToggleSwitch,{size:lo,checked:Au.enabled,disabled:!Au.changeable||Au.disabledBy==="dependency","aria-labelledby":Ru,onClick:()=>{Au.changeable&&Au.disabledBy!=="dependency"&&$u(Au.name,!Au.enabled)}})]}),children:jsxRuntimeExports.jsx(PluginDetails,{row:Au})})}function PluginList({plugins:Au,query:lo="",switchSize:$u="small",onToggle:Ru,emptyMessage:Iu}){const Pu=reactExports.useMemo(()=>Au.filter(Ou=>pluginMatches(Ou,lo)),[Au,lo]);return Pu.length===0?jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:"fg.muted"},children:Iu??`No plugin matches “${lo}”.`}):jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:Pu.map(Ou=>jsxRuntimeExports.jsx(PluginRowView,{row:Ou,size:$u,onToggle:Ru},Ou.name))})}function PluginsManagerView({protectedPlugins:Au,hiddenPlugins:lo,switchSize:$u,width:Ru,...Iu}){const Pu=useReactorPlatform(),Ou=Pu.getConfig(MANAGER_PLUGIN_NAME)??{},Mu=reactExports.useMemo(()=>new Set(Au??Ou.protected??[MANAGER_PLUGIN_NAME]),[Au,Ou.protected]),Du=reactExports.useMemo(()=>new Set(lo??Ou.hidden??[]),[lo,Ou.hidden]),Lu=usePluginHoverControl(),Bu=usePluginRows(Mu,Du),[ju,Fu]=reactExports.useState(""),zu=$u??Ou.switchSize??"small",Uu=useContributions(ManagerPluginSource),Hu=reactExports.useMemo(()=>[...Uu].map(Vu=>Vu.value).sort((Vu,Gu)=>(Vu.order??100)-(Gu.order??100)),[Uu]);return jsxRuntimeExports.jsx(PluginHoverContext.Provider,{value:Lu,children:jsxRuntimeExports.jsxs(Box,{sx:{display:"flex",flexDirection:"column",gap:3,width:Ru??Ou.width??"100%",maxWidth:"100%",minWidth:0},children:[jsxRuntimeExports.jsx(ReactorSlot,{slot:MANAGER_ACTIONS_SLOT,props:Iu}),jsxRuntimeExports.jsxs(Box,{children:[jsxRuntimeExports.jsx(Text$3,{as:"h2",sx:{fontSize:1,fontWeight:"semibold",display:"block",mb:2},children:Ou.title??"Plugins"}),jsxRuntimeExports.jsx(TextInput$1,{leadingVisual:SearchIcon,value:ju,onChange:Vu=>Fu(Vu.target.value),"aria-label":"Filter plugins",placeholder:"Filter…",block:!0,size:"small"})]}),jsxRuntimeExports.jsx(Box,{children:jsxRuntimeExports.jsx(PluginList,{plugins:Bu,query:ju,switchSize:zu,onToggle:(Vu,Gu)=>Gu?Pu.enable(Vu):Pu.disable(Vu)})}),Hu.map(Vu=>jsxRuntimeExports.jsxs(Box,{children:[jsxRuntimeExports.jsx(Text$3,{as:"h3",sx:{fontSize:1,fontWeight:"semibold",display:"block",mb:2},children:Vu.title}),jsxRuntimeExports.jsx(Vu.Component,{query:ju,switchSize:zu})]},Vu.title))]})})}const PLUGINS_PANEL_PLUGIN_NAME="@datalayer/loop-plugin-plugins-panel",SIDEBAR_WIDTH=420,REACTOR_GRAPH_PLUGIN_NAME="@datalayer/reactor-graph",PluginsPanelPlugin={name:PLUGINS_PANEL_PLUGIN_NAME,displayName:"Plugins panel",description:"Switch plugins on and off while the workspace runs.",octicon:"plug",emoji:"🔌",build:()=>({components:[{id:"plugins-panel",slot:LoopSlots.sidebar,order:900,Component:({workspace:Au})=>jsxRuntimeExports.jsx(PluginsManagerView,{protectedPlugins:[PLUGINS_PANEL_PLUGIN_NAME],hiddenPlugins:[REACTOR_GRAPH_PLUGIN_NAME],width:SIDEBAR_WIDTH,workspace:Au})}]})};function ViewSwitcher({views:Au,workspace:lo,compact:$u=!1}){return Au.length<2?null:jsxRuntimeExports.jsx(Box,{role:"tablist","aria-label":"Workspace views",display:"inline-flex",alignItems:"center",bg:"neutral.muted",borderRadius:"6px",p:"2px",gap:"1px",children:Au.map(Ru=>{const Iu=Ru.value,Pu=canOpenView(Iu,lo),Ou=lo.activeViewType===Iu.viewType,Mu=Iu.icon,Du=Pu?Iu.title:`${Iu.title} — ${Iu.unavailableReason?.(lo)??"unavailable"}`;return jsxRuntimeExports.jsx(Tooltip,{text:Du,direction:"n",children:jsxRuntimeExports.jsxs(Box,{as:"button",role:"tab","aria-selected":Ou,"aria-disabled":!Pu,onClick:()=>Pu&&lo.setActiveViewType(Iu.viewType),display:"inline-flex",alignItems:"center",gap:1,border:"none",borderRadius:"5px",px:2,py:"4px",fontSize:0,cursor:Pu?"pointer":"not-allowed",opacity:Pu?1:.5,bg:Ou?"canvas.default":"transparent",color:Ou?"fg.default":"fg.muted",boxShadow:Ou?"shadow.small":"none",children:[Mu?jsxRuntimeExports.jsx(Mu,{size:14}):null,$u&&Mu?null:Iu.title]})},Iu.viewType)})})}const paneOpenKeyframes=Au=>Au==="left"?"loopPaneOpenLeft":"loopPaneOpenRight",paneOpenAnimation=Au=>`${paneOpenKeyframes(Au)} var(--theme-motion-pane, 0ms) var(--theme-motion-easing, ease) both`;function paneOpening(Au){const lo="12px";return{animation:paneOpenAnimation(Au),[`@keyframes ${paneOpenKeyframes(Au)}`]:{from:{opacity:0,transform:`translateX(${lo})`},to:{opacity:1,transform:"none"}},"@media (prefers-reduced-motion: reduce)":{animation:"none"}}}function railItemsOf(Au){return Au.map(lo=>({id:lo.id,label:lo.rail?.label??lo.id,icon:lo.rail?.icon??SidebarExpandIcon}))}function railChoiceAfter(Au,lo){return Au===lo?null:lo}const RAIL_WIDTH=48;function SidebarRail({components:Au,props:lo,width:$u}){const Ru=railItemsOf(Au),[Iu,Pu]=reactExports.useState(Ru[0]?.id??null),Ou=Ru.some(Mu=>Mu.id===Iu)?Iu:null;return jsxRuntimeExports.jsxs(Box,{as:"aside","data-loop-rail-sidebar":"",flex:"0 0 auto",display:"flex",minHeight:0,children:[jsxRuntimeExports.jsx(Box,{"data-loop-rail-panel":Ou??void 0,display:Ou?"block":"none",width:`${$u}px`,minWidth:0,borderLeft:"var(--theme-hairline, 1px) solid",borderColor:"border.default",overflowY:"auto",px:3,py:3,children:Au.map(Mu=>{const{Component:Du}=Mu,Lu=Mu.id===Ou;return jsxRuntimeExports.jsx(Box,{id:`loop-rail-panel-${Mu.id}`,role:"region","aria-label":railItemsOf([Mu])[0].label,hidden:!Lu,sx:Lu?paneOpening("right"):void 0,children:jsxRuntimeExports.jsx(Du,{...lo})},Mu.id)})}),jsxRuntimeExports.jsx(Box,{as:"nav","aria-label":"Panels",width:`${RAIL_WIDTH}px`,flex:`0 0 ${RAIL_WIDTH}px`,display:"flex",flexDirection:"column",alignItems:"center",gap:1,py:2,borderLeft:"var(--theme-hairline, 1px) solid",borderColor:"border.default",children:Ru.map(Mu=>{const Du=Mu.icon,Lu=Mu.id===Ou;return jsxRuntimeExports.jsx(Box,{as:"button",type:"button","data-loop-rail-item":Mu.id,"aria-label":Mu.label,title:Mu.label,"aria-pressed":Lu,"aria-controls":`loop-rail-panel-${Mu.id}`,onClick:()=>Pu(railChoiceAfter(Ou,Mu.id)),width:32,height:32,display:"inline-flex",alignItems:"center",justifyContent:"center",p:0,border:"none",borderRadius:2,cursor:"pointer",color:Lu?"fg.default":"fg.muted",bg:Lu?"neutral.muted":"transparent",hover:{color:"fg.default",bg:"neutral.subtle"},focusVisible:{outline:"2px solid",outlineColor:"var(--focus-outlineColor, #0969da)",outlineOffset:"1px"},children:jsxRuntimeExports.jsx(Du,{size:16})},Mu.id)})})]})}function buildLoopReactor(Au){return buildReactorFromPlugins(Au)}function LoopWorkspace(Au){const{serverUrl:lo,agentId:$u,conversationId:Ru,model:Iu,sandbox:Pu={state:"idle"},extensions:Ou=[],reactor:Mu,manageReactor:Du=!0,initialViewType:Lu,onSend:Bu,layout:ju="page",showViewSelector:Fu=!0,showHeader:zu=!0,chatHeaderActions:Uu,chatViewModes:Hu,headerActions:Vu,headerContainer:Gu,sidebarRail:Wu=!1}=Au,Ku=reactExports.useMemo(()=>Mu??buildLoopReactor(Ou),[Mu]);return useReactor(Ku,{autoStart:Du}),jsxRuntimeExports.jsx(WorkspaceBody,{serverUrl:lo,agentId:$u,conversationId:Ru,model:Iu,initialSandbox:Pu,initialViewType:Lu,onSend:Bu,layout:ju,showViewSelector:Fu,showHeader:zu,chatHeaderActions:Uu,chatViewModes:Hu,headerActions:Vu,headerContainer:Gu,sidebarRail:Wu})}function WorkspaceBody({serverUrl:Au,agentId:lo,conversationId:$u,model:Ru,initialSandbox:Iu,initialViewType:Pu,onSend:Ou,layout:Mu="page",showViewSelector:Du=!0,showHeader:Lu=!0,chatHeaderActions:Bu,chatViewModes:ju,headerActions:Fu,headerContainer:zu,sidebarRail:Uu=!1}){const[Hu,Vu]=reactExports.useState(lo),Gu=reactExports.useRef(loopSurfaceId($u??`session-${Date.now().toString(36)}`));reactExports.useEffect(()=>{Vu(lo)},[lo]);const[Wu,Ku]=reactExports.useState(Pu??""),[Ju,Yu]=reactExports.useState(Iu),[Xu]=reactExports.useState(createPromptChannel),[ed,td]=reactExports.useState({}),nd=reactExports.useCallback(cd=>{td(cd??{})},[]),od=useContributions(LoopViewType),sd=useContributions(LoopCommand),ad=useSlotComponents(LoopSlots.sidebar),pd=reactExports.useRef(sd),gd=reactExports.useRef(null),_d=Mu==="panel",yd=reactExports.useCallback(async cd=>{const dd=parseCommand(cd);if(!dd)return Ou?.(cd,gd.current),Xu.submit(cd)||Ou?{handled:!0}:{handled:!1,reason:"Nothing is listening for prompts in this view yet."};const md=pd.current.find(hd=>hd.value.name===dd.name||(hd.value.aliases??[]).includes(dd.name));if(!md)return{handled:!1,command:dd.name,reason:`Unknown command: /${dd.name}. Type /help to see what there is.`};const ld=await md.value.run({workspace:gd.current,argv:dd.argv});return ld?.prompt&&(Ou?.(ld.prompt,gd.current),Xu.submit(ld.prompt)),{handled:!0,command:dd.name,result:ld??void 0}},[Ou,Xu]),bd=reactExports.useMemo(()=>({serverUrl:Au,agentId:Hu,surfaceId:Gu.current,setAgentId:Vu,conversationId:$u,model:Ru,sandbox:Ju,setSandbox:Yu,activeViewType:Wu,setActiveViewType:Ku,prompts:Xu,submit:yd,viewControls:ed,setViewControls:nd,chatHeaderActions:Bu,chatViewModes:ju}),[Au,Hu,$u,Ru,Ju,Wu,Xu,yd,ed,nd,Bu,ju]);gd.current=bd,pd.current=sd;const Sd=reactExports.useMemo(()=>Wu||(od.find(dd=>canOpenView(dd.value,bd))?.value.viewType??""),[Wu,od,bd]);useReactorEvent(Sd?onView(Sd):void 0);const Ed=jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[Fu,jsxRuntimeExports.jsx(ReactorSlot,{slot:LoopSlots.header,props:{workspace:bd}}),Du?jsxRuntimeExports.jsx(ViewSwitcher,{views:od,workspace:bd,compact:_d}):null]});return jsxRuntimeExports.jsxs(Box,{"data-loop-workspace":"",display:"flex",flexDirection:"column",height:"100%",minHeight:0,position:"relative",bg:"canvas.default",color:"fg.default",children:[Lu&&zu?reactDomExports.createPortal(jsxRuntimeExports.jsx(Box,{display:"flex",alignItems:"center",flexWrap:"wrap",gap:2,children:Ed}),zu):null,Lu&&zu===void 0?jsxRuntimeExports.jsx(Box,{as:"header",display:"flex",alignItems:"center",justifyContent:_d?"flex-start":"space-between",flexWrap:"wrap",gap:2,px:_d?2:3,py:2,borderBottom:"1px solid",borderColor:"border.default",flex:"0 0 auto",children:Ed}):null,jsxRuntimeExports.jsxs(Box,{flex:"1 1 auto",minHeight:0,display:"flex",children:[jsxRuntimeExports.jsx(Box,{flex:"1 1 auto",minWidth:0,minHeight:0,position:"relative",children:jsxRuntimeExports.jsx(ReactorViewHost,{point:LoopViewType,active:Sd,props:{viewType:Sd,workspace:bd},fallback:jsxRuntimeExports.jsx(Centered,{children:"Loading…"}),empty:jsxRuntimeExports.jsx(Centered,{children:"No view is available yet."}),errorFallback:cd=>jsxRuntimeExports.jsxs(Centered,{children:["This view failed to load: ",cd.message]})})}),ad.length>0&&Uu&&!_d?jsxRuntimeExports.jsx(SidebarRail,{components:ad,props:{workspace:bd},width:SIDEBAR_WIDTH}):ad.length>0?jsxRuntimeExports.jsx(Box,{as:"aside",flex:"0 0 auto",width:_d?"100%":`${SIDEBAR_WIDTH}px`,minWidth:0,borderLeft:_d?"none":"1px solid",borderTop:_d?"1px solid":"none",borderColor:"border.default",bg:"canvas.subtle",overflowY:"auto",px:3,py:3,children:jsxRuntimeExports.jsx(ReactorSlot,{slot:LoopSlots.sidebar,props:{workspace:bd}})}):null]}),jsxRuntimeExports.jsxs(Box,{flex:"0 0 auto",children:[jsxRuntimeExports.jsx(ReactorSlot,{slot:LoopSlots.footer,props:{workspace:bd}}),jsxRuntimeExports.jsx(ReactorSlot,{slot:LoopSlots.status,props:{workspace:bd}})]}),jsxRuntimeExports.jsx(ReactorSlot,{slot:LoopSlots.root,props:{workspace:bd}})]})}function Centered({children:Au}){return jsxRuntimeExports.jsx(Box,{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"fg.muted",fontSize:1,px:3,textAlign:"center",children:Au})}function resolveTopOffset(Au){if(typeof Au=="number")return Au;if(!Au||typeof document>"u")return 0;const lo=document.querySelector(Au);return lo?Math.max(0,Math.round(lo.getBoundingClientRect().bottom)):0}function fullScreenNode(Au){return Au?.closest("[data-loop-fullscreen-root]")??Au?.closest("[data-loop-workspace]")??Au}function useWorkspaceFullScreen(Au,lo={}){const{forceOverlay:$u=!1,paintOverlay:Ru=!1,topOffset:Iu=0}=lo,[Pu,Ou]=reactExports.useState(!1),Mu=reactExports.useRef(!1);reactExports.useEffect(()=>{const ju=()=>{if(!Mu.current)return;const Fu=!!document.fullscreenElement&&!!Au.current&&document.fullscreenElement.contains(Au.current);Ou(Fu),Fu||(Mu.current=!1)};return document.addEventListener("fullscreenchange",ju),()=>document.removeEventListener("fullscreenchange",ju)},[Au]);const Du=reactExports.useCallback(()=>{const ju=fullScreenNode(Au.current);if(Pu){Mu.current&&document.fullscreenElement?document.exitFullscreen():Ou(!1);return}if($u||Ru||!ju?.requestFullscreen){Ou(!0);return}Mu.current=!0,ju.requestFullscreen().then(()=>Ou(!0),()=>{Mu.current=!1,Ou(!0)})},[Au,Pu,$u,Ru]),[Lu,Bu]=reactExports.useState(0);return reactExports.useEffect(()=>{if(!Pu||Mu.current){Bu(0);return}const ju=()=>Bu(resolveTopOffset(Iu));return ju(),window.addEventListener("resize",ju),()=>window.removeEventListener("resize",ju)},[Pu,Iu]),reactExports.useEffect(()=>{if(!Ru||!Pu||Mu.current)return;const ju=fullScreenNode(Au.current);if(!ju)return;const Fu=ju.getAttribute("style");return ju.style.position="fixed",ju.style.top=`${Lu}px`,ju.style.right="0",ju.style.bottom="0",ju.style.left="0",ju.style.height="auto",ju.style.zIndex="1000",()=>{Fu===null?ju.removeAttribute("style"):ju.setAttribute("style",Fu)}},[Ru,Pu,Au,Lu]),reactExports.useEffect(()=>{if(!Pu||Mu.current)return;const ju=Fu=>{Fu.key==="Escape"&&!Fu.defaultPrevented&&Ou(!1)};return window.addEventListener("keydown",ju),()=>window.removeEventListener("keydown",ju)},[Pu]),{fullScreen:Pu,usingApi:Mu,toggle:Du,topOffsetPx:Lu}}function messageText(Au){const lo=Au.content;return typeof lo=="string"?lo:lo.map($u=>typeof $u=="string"?$u:$u.text??"").join("")}const isToolCall=Au=>Au.type==="tool-call";function conversationOf(Au){const lo=[];for(const $u of Au){if(isToolCall($u)){lo.push({role:"tool",name:$u.toolName,args:$u.args??{},...$u.result===void 0?{}:{result:$u.result}});continue}if($u.role!=="user"&&$u.role!=="assistant")continue;const Ru=messageText($u);Ru.trim()&&lo.push({role:$u.role,text:Ru})}return lo}const sameConversation=(Au,lo)=>Au.length===lo.length&&Au.every(($u,Ru)=>JSON.stringify($u)===JSON.stringify(lo[Ru])),IDLE={id:0,status:"idle"};function createTurnFeed(){const Au=signal$2(IDLE),lo=signal$2([]),$u=signal$2("idle");return{turn:Au,conversation:lo,presence:$u,setPresence:Ru=>{$u.value!==Ru&&($u.value=Ru)},items:Ru=>{const Iu=conversationOf(Ru);sameConversation(lo.value,Iu)||(lo.value=Iu)},begin:(Ru,Iu)=>{Au.value={id:Au.value.id+1,user:Ru,...Iu?{thread:Iu}:{},status:"thinking",usage:Au.value.usage}},assistant:Ru=>{const Iu=Au.value;Iu.status==="idle"||Iu.assistant===Ru||(Au.value={...Iu,assistant:Ru,status:Iu.status==="done"||Iu.status==="error"?Iu.status:Ru?"streaming":Iu.status})},usage:Ru=>{const Iu=Au.value;Iu.usage!==Ru&&(Au.value={...Iu,usage:Ru})},activity:Ru=>{const Iu=Au.value;Iu.status==="idle"||Iu.activity===Ru||(Au.value={...Iu,activity:Ru})},end:(Ru="done")=>{const Iu=Au.value;Iu.status!=="idle"&&(Au.value={...Iu,status:Ru,activity:void 0})}}}const TURN_WRITERS=Symbol.for("loop.chat.turn.writers");function feedWriters(Au){return{[TURN_WRITERS]:Au}}function turnWritersOf(Au){return Au?.[TURN_WRITERS]}function agentAction(Au,lo){const{prompt:$u,...Ru}=lo;return{...Ru,type:"button",group:"agent",onClick:()=>Au.workspace.prompts.submit($u)}}const CHAT_PLUGIN_NAME="@datalayer/loop-plugin-chat",ChatPlugin={name:CHAT_PLUGIN_NAME,config:{placeholder:"",defaultSurface:"notebook",showSurfaceSelector:!0,hideHeader:!1,headerButtons:{newChat:!1,clear:!1},hidePrompt:!1,promptPlacement:"bottom",autoFocusPrompt:!0,suggestionLabels:!0,fullScreenTopOffset:0},displayName:"Chat",description:"The conversation, the prompt, and the point editors plug into.",octicon:"comment-discussion",emoji:"💬",contributionPoints:[LoopAgentGate,LoopFrontendTool,LoopChatComposer,LoopChatHeader,LoopChatSuggestion,LoopChatExtras,LoopChatTurn],build:Au=>{const lo=createTurnFeed();return Au.contribute(LoopChatTurn,{id:"chat-turn",turn:lo.turn,conversation:lo.conversation,presence:lo.presence,...feedWriters(lo)},{id:"chat-turn"}),{}},contributes:[contribution(LoopViewType,{viewType:"chat",title:"Chat",icon:CommentDiscussionIcon,order:0,load:()=>__vitePreload(()=>import("./chunks/ChatView-C_NOLqwI.js"),[],import.meta.url)},{id:"chat",order:0}),contribution(LoopCommand,{name:"chat",description:"Show the conversation",group:"Session",keybinding:"Mod+Alt+K",run:async({workspace:Au})=>{Au.setActiveViewType("chat")}},{id:"chat"}),contribution(LoopNotebookToolbarItem,{items:Au=>[agentAction(Au,{key:"loop-compact",ariaLabel:"Compact this notebook",title:"Ask @NotebookCompactor to shorten it without changing results",icon:FoldIcon,order:200,prompt:"@NotebookCompactor compact this notebook without changing what it computes."}),agentAction(Au,{key:"loop-reproduce",ariaLabel:"Check reproducibility",title:"Ask @NotebookReproducer to run it on a fresh sandbox",icon:SyncIcon,order:201,prompt:"@NotebookReproducer run this notebook top to bottom on a fresh sandbox and report what does not reproduce."})]},{id:"agent-actions",order:200}),contribution(LoopDocumentToolbarItem,{items:Au=>[agentAction(Au,{key:"loop-summarise",ariaLabel:"Summarise this document",title:"Ask the agent for a summary of what this document says",icon:SparkleFillIcon,order:200,prompt:"Summarise this document in a short paragraph."})]},{id:"agent-actions",order:200})]};function WorkspaceFullScreenAction(){const Au=reactExports.useRef(null),$u=useReactorPlatform().getConfig(CHAT_PLUGIN_NAME)?.fullScreenTopOffset??0,{fullScreen:Ru,toggle:Iu}=useWorkspaceFullScreen(Au,{paintOverlay:!!$u,topOffset:$u});return jsxRuntimeExports.jsx(IconButton,{ref:Au,icon:Ru?ScreenNormalIcon:ScreenFullIcon,"aria-label":Ru?"Exit full screen":"Enter full screen",variant:"invisible",size:"small",sx:{order:2},onClick:Iu})}const THEME_PLUGIN_NAME="@datalayer/primer-theme",TOGGLE_COLOR_MODE_COMMAND="theme.toggleColorMode",ThemePlugin={name:THEME_PLUGIN_NAME,displayName:"Theme",description:"Keeps Primer portals in the application’s color mode, and toggles it.",octicon:"sun",emoji:"🌗",commands:[{id:TOGGLE_COLOR_MODE_COMMAND,name:"Toggle the color mode",description:"Switch between light and dark",emoji:"🌗",category:"Appearance",keybinding:"Mod+Alt+C",execute:()=>{const Au=useThemeStore.getState(),lo=Au.colorMode==="auto"?typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light":Au.colorMode;Au.setColorMode(lo==="dark"?"light":"dark")}}],register:()=>{if(typeof document>"u")return;setupPrimerPortals(useThemeStore.getState().colorMode);const Au=useThemeStore.subscribe((Ru,Iu)=>{Ru.colorMode!==Iu.colorMode&&setupPrimerPortals(Ru.colorMode)}),lo=window.matchMedia("(prefers-color-scheme: dark)"),$u=()=>{useThemeStore.getState().colorMode==="auto"&&setupPrimerPortals("auto")};return lo.addEventListener("change",$u),()=>{Au(),lo.removeEventListener("change",$u)}}},pageLayoutPanelOpen=signal$2(!1),pageLayoutSheet=signal$2("page"),pageLayoutActivity=signal$2(void 0);function openPagePanel(){pageLayoutPanelOpen.value=!0}const PAGE_SHEET_WIDTH=920,PAGE_PANEL_WIDTH=400,PAGE_SIZE_FORMATS={letter:{width:816,height:1056},a4:{width:794,height:1123}};function resolvePageSize(Au,lo=PAGE_SHEET_WIDTH){const $u=Au?.format&&Au.format!=="free"?PAGE_SIZE_FORMATS[Au.format]:void 0;return{width:Au?.width??$u?.width??lo,height:Au?.height??$u?.height}}const CANVAS_PX=[2,3,4];function ActivityLine({label:Au}){return jsxRuntimeExports.jsxs(Box$1,{"data-page-activity":"",role:"status",sx:{position:"sticky",top:0,zIndex:2,alignSelf:"flex-start",display:"inline-flex",alignItems:"center",gap:2,px:2,py:"4px",borderRadius:"999px",border:"1px solid",borderColor:"accent.muted",bg:"accent.subtle",color:"accent.fg",fontSize:0,fontWeight:"semibold",whiteSpace:"nowrap",boxShadow:"0 4px 12px -6px rgba(0,0,0,0.3)"},children:[jsxRuntimeExports.jsx(Box$1,{as:"span","aria-hidden":"true",sx:{width:7,height:7,borderRadius:"50%",bg:"accent.fg",animation:"page-activity-dot 1.1s ease-in-out infinite","@keyframes page-activity-dot":{"0%, 100%":{opacity:1},"50%":{opacity:.3}}}}),jsxRuntimeExports.jsx(Text$3,{children:Au})]})}function panelOpening(Au){const lo=Au==="left"?"pagePanelOpenLeft":"pagePanelOpenRight";return{animation:`${lo} var(--theme-motion-pane, 0ms) var(--theme-motion-easing, ease) both`,[`@keyframes ${lo}`]:{from:{opacity:0,transform:`translateX(${Au==="left"?"-12px":"12px"})`},to:{opacity:1,transform:"none"}},"@media (prefers-reduced-motion: reduce)":{animation:"none"}}}function PageLayout({page:Au,hasPage:lo=Au!=null,panel:$u,band:Ru,chips:Iu,picker:Pu,transient:Ou,activity:Mu,bandMode:Du="docked",panelMode:Lu="docked",panelSide:Bu="right",sheetWidth:ju=PAGE_SHEET_WIDTH,pageSize:Fu,panelWidth:zu=PAGE_PANEL_WIDTH}){const Uu=Du==="panel",Hu=Ru!=null,{width:Vu,height:Gu}=resolvePageSize(Fu,ju),Ku=useSignalValue$1(pageLayoutPanelOpen)||Uu&&Hu,Ju=useSignalValue$1(pageLayoutActivity),Yu=Mu??Ju,Xu=lo?"page":"panel";return reactExports.useEffect(()=>{pageLayoutSheet.value=Xu},[Xu]),jsxRuntimeExports.jsxs(Box$1,{"data-page-layout":"",sx:{position:"relative",flex:"1 1 auto",minHeight:0,display:"flex",flexDirection:"column"},children:[Pu,jsxRuntimeExports.jsxs(Box$1,{sx:{flex:"1 1 auto",minHeight:0,display:"flex",bg:"canvas.inset"},children:[jsxRuntimeExports.jsxs(Box$1,{sx:{flex:"1 1 auto",minWidth:0,minHeight:0,display:"flex",flexDirection:"column"},children:[Ru&&Du==="docked"?jsxRuntimeExports.jsx(Box$1,{"data-page-band":"","data-page-prompt-dock":"",sx:{flex:"0 0 auto",display:"flex",justifyContent:"center",px:CANVAS_PX,bg:"canvas.subtle",borderBottom:"1px solid",borderColor:"border.default"},children:jsxRuntimeExports.jsx(Box$1,{sx:{width:"100%",maxWidth:Vu,minWidth:0},children:Ru})}):null,jsxRuntimeExports.jsxs(Box$1,{"data-page-canvas":"",sx:{flex:"1 1 auto",minWidth:0,minHeight:0,overflowY:lo?"auto":"hidden",overflowX:"hidden",display:"flex",flexDirection:"column",alignItems:"center",pt:3,pb:6,px:CANVAS_PX},children:[Ru&&Iu&&!Uu?jsxRuntimeExports.jsx(Box$1,{sx:{width:"100%",maxWidth:Vu,mb:3,display:"flex",justifyContent:"center","& > *":{justifyContent:"center"}},children:Iu}):null,Yu?jsxRuntimeExports.jsx(Box$1,{sx:{width:"100%",maxWidth:Vu,display:"flex",justifyContent:"flex-end",mb:2},children:jsxRuntimeExports.jsx(ActivityLine,{label:Yu})}):null,jsxRuntimeExports.jsx(Sheet,{"data-page-sheet":"",sx:{width:"100%",maxWidth:Vu,flex:lo?"1 0 auto":"1 1 auto",px:lo?[3,4,"56px"]:[2,3,4],py:lo?[3,4,4]:2,position:"relative",display:"flex",minHeight:lo?Gu??480:0,"& > *":{flex:"1 1 auto",minWidth:0}},children:lo?Au:$u}),lo||!Au?null:jsxRuntimeExports.jsx(Box$1,{"aria-hidden":"true",sx:{position:"absolute",inset:0,visibility:"hidden",pointerEvents:"none",zIndex:-1,display:"flex"},children:Au})]})]}),!lo||!$u?null:jsxRuntimeExports.jsxs(Box$1,{"data-page-panel":Ku?"":void 0,"data-page-panel-mode":Lu,"aria-hidden":Ku?void 0:"true",sx:{minWidth:0,minHeight:0,display:"flex",flexDirection:"column",bg:"canvas.default",borderColor:"border.default",...Ku?Lu==="docked"?{flex:`0 0 ${zu}px`,maxWidth:"45%",order:Bu==="left"?-1:void 0,[Bu==="left"?"borderRight":"borderLeft"]:"1px solid",zIndex:1}:Lu==="overlay"?{position:"absolute",top:0,bottom:0,[Bu]:0,width:zu,maxWidth:"85%",[Bu==="left"?"borderRight":"borderLeft"]:"1px solid",boxShadow:"shadow.large",zIndex:5}:{position:"absolute",[Bu]:16,bottom:16,width:zu,maxWidth:"calc(100% - 32px)",height:"min(70%, 560px)",border:"1px solid",borderRadius:2,boxShadow:"shadow.large",overflow:"hidden",zIndex:5}:{position:"absolute",inset:0,visibility:"hidden",pointerEvents:"none",overflow:"visible"}},children:[jsxRuntimeExports.jsx(Box$1,{sx:{flex:"1 1 auto",minHeight:0,display:"flex",flexDirection:"column","& > *":{flex:"1 1 auto",minHeight:0},...Ku?panelOpening(Bu):null},children:$u}),Hu&&Du!=="docked"?jsxRuntimeExports.jsxs(Box$1,{"data-page-panel-band":Uu?"":void 0,sx:Uu?{flex:"0 0 auto",borderTop:"1px solid",borderColor:"border.default",visibility:"visible",pointerEvents:"auto","& > *":{justifyContent:"center"}}:{position:"absolute",inset:0,visibility:"visible",pointerEvents:"none","& > *":{pointerEvents:"auto"}},children:[Uu?Iu:null,Ru]}):null]})]}),Ou]})}function PagePanelToggle({panelName:Au="panel",icon:lo=SidebarExpandIcon,sx:$u}){const Ru=useSignalValue$1(pageLayoutPanelOpen);return useSignalValue$1(pageLayoutSheet)==="panel"?null:jsxRuntimeExports.jsx(IconButton,{icon:lo,size:"small",variant:Ru?"default":"invisible","aria-label":Ru?`Hide the ${Au}`:`Show the ${Au}`,"aria-pressed":Ru,onClick:()=>{Ru?pageLayoutPanelOpen.value=!1:openPagePanel()},sx:{color:Ru?"accent.fg":"fg.muted",...$u}})}const INPUT_PROMPT_PLUGIN_NAME="@datalayer/loop-plugin-input-prompt",LazyComposerView=reactExports.lazy(()=>__vitePreload(()=>import("./chunks/ComposerView-Wa0dy8ex.js"),[],import.meta.url));function ComposerView(Au){return jsxRuntimeExports.jsx(reactExports.Suspense,{fallback:null,children:jsxRuntimeExports.jsx(LazyComposerView,{...Au})})}const InputPromptPlugin={name:INPUT_PROMPT_PLUGIN_NAME,config:{},displayName:"Input Prompt",description:"The composer under (or over) the conversation.",octicon:"pencil",emoji:"✏️",contributionPoints:[LoopPromptPanel],contributes:[contribution(LoopChatComposer,{id:"input-prompt",Component:ComposerView},{id:"input-prompt"})]},AGENT_ICONS={agent:ForwardRef$2,beaker:BeakerIcon,bell:BellIcon,book:BookIcon,briefcase:BriefcaseIcon,browser:BrowserIcon,bug:BugIcon,clock:ClockIcon,code:CodeIcon,"comment-discussion":CommentDiscussionIcon,cpu:CpuIcon,"credit-card":CreditCardIcon,database:DatabaseIcon,file:FileIcon,checklist:ChecklistIcon,"code-review":CodeReviewIcon,fold:FoldIcon,"git-branch":GitBranchIcon,globe:GlobeIcon,graph:GraphIcon,heart:HeartIcon,"issue-opened":IssueOpenedIcon,lightbulb:LightBulbIcon,"light-bulb":LightBulbIcon,"list-unordered":ListUnorderedIcon,mail:MailIcon,megaphone:MegaphoneIcon,"mortar-board":MortarBoardIcon,note:NoteIcon,organization:OrganizationIcon,package:PackageIcon,pencil:PencilIcon,people:PeopleIcon,play:PlayIcon,pulse:PulseIcon,rss:RssIcon,search:SearchIcon,"share-2":ShareAndroidIcon,shield:ShieldIcon,"shield-check":ShieldCheckIcon,sliders:SlidersIcon,sun:SunIcon,sync:SyncIcon,table:TableIcon,tag:TagIcon,tasklist:TasklistIcon,telescope:TelescopeIcon,tools:ToolsIcon,"trending-up":GraphIcon,rocket:RocketIcon,zap:ZapIcon};function agentIcon(Au){return(Au?AGENT_ICONS[Au]:void 0)??ForwardRef$2}function useOptionalSandboxService(){return useReactorPlatform().getOutput(AGENTS_PLUGIN_NAME)?.sandbox}function useSandboxService(){const Au=useOptionalSandboxService();if(!Au)throw new Error(`The code sandbox plugin (${AGENTS_PLUGIN_NAME}) is not mounted. A view that needs a sandbox must declare it as a dependency.`);return Au}function SandboxStatusBridge({workspace:Au}){const lo=useOptionalSandboxService(),$u=useSignalValue$1(lo?.snapshot??IDLE_SANDBOX_SNAPSHOT_SIGNAL),Ru=useSignalValue$1(lo?.target??IDLE_SANDBOX_TARGET_SIGNAL),{setSandbox:Iu,agentId:Pu}=Au;return reactExports.useEffect(()=>lo?.connect(Pu),[lo,Pu]),reactExports.useEffect(()=>{lo&&Iu({...$u,target:Ru})},[lo,$u,Ru,Iu]),null}const DatalayerAgentBridge=reactExports.lazy(async()=>({default:(await __vitePreload(()=>import("./chunks/DatalayerAgentBridge-D54Z9BZ3.js"),[],import.meta.url)).DatalayerAgentBridge}));function DatalayerAgentMount(){return jsxRuntimeExports.jsx(reactExports.Suspense,{fallback:null,children:jsxRuntimeExports.jsx(DatalayerAgentBridge,{})})}const CREATING_STATUSES=new Set(["creating","starting","launching","connecting","pending","resuming"]),MAX_AGENT_NAME_LENGTH=32,toSandboxStatusUrl=Au=>{const lo=String(Au||"").trim();if(lo)try{const $u=new URL(lo);return $u.pathname=`${$u.pathname.replace(/\/$/,"")}/api`,$u.toString()}catch{const $u=lo.replace(/\/$/,"");return $u.endsWith("/api")?$u:`${$u}/api`}},OVERLAY_WIDTH=360,AgentSummary=({summary:Au,title:lo="Active Agent"})=>{const[$u,Ru]=reactExports.useState(!1),[Iu,Pu]=reactExports.useState(!1),Ou=reactExports.useRef(null),Mu=reactExports.useRef(null),Du=()=>{Mu.current!==null&&(window.clearTimeout(Mu.current),Mu.current=null)},Lu=()=>{Du();const Yu=Ou.current?.getBoundingClientRect();Pu(!!(Yu&&Yu.left+OVERLAY_WIDTH>window.innerWidth)),Ru(!0)},Bu=()=>{Du(),Mu.current=window.setTimeout(()=>{Ru(!1),Mu.current=null},300)};reactExports.useEffect(()=>()=>{Du()},[]);const ju=Au?.baseUrl?(()=>{const Yu=Au.baseUrl.replace(/\/$/,"");return Yu.endsWith("/api/v1")?Yu:`${Yu}/api/v1`})():void 0,Fu=ju?`${ju}/runtime/status`:void 0,zu=toSandboxStatusUrl(Au?.sandboxBaseUrl);if(!Au)return null;const Uu=(Au.status||"").toLowerCase(),Hu=!Au.isReady&&!Au.agentId&&CREATING_STATUSES.has(Uu),Vu=!!Au.error,Gu=!!Au.agentId||Hu,Wu=strip(Au.agentName,MAX_AGENT_NAME_LENGTH),Ku=`${Au.agentName} · ${Au.location}`,Ju=`${Wu} · ${Au.location}`;return jsxRuntimeExports.jsxs(Box,{ref:Ou,position:"relative",onMouseEnter:Lu,onMouseLeave:Bu,children:[jsxRuntimeExports.jsxs(Box,{as:"button",type:"button",title:Ku,px:2,py:"6px",maxWidth:280,minWidth:0,border:"1px solid",borderColor:Vu?"danger.emphasis":"border.default",borderRadius:2,bg:Vu?"danger.subtle":"canvas.default",color:Vu?"danger.fg":"fg.default",fontSize:0,cursor:"default",display:"flex",alignItems:"center",gap:1,children:[Hu&&jsxRuntimeExports.jsx(StyledSpinner,{size:"small",sx:{width:12,height:12}}),Vu&&jsxRuntimeExports.jsx("span",{"aria-hidden":!0,children:"⚠"}),jsxRuntimeExports.jsx(Box,{as:"span",display:"block",minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",children:Ju})]}),$u&&jsxRuntimeExports.jsxs(Box,{position:"absolute",top:"calc(100% + 8px)",width:OVERLAY_WIDTH,p:2,border:"1px solid",borderColor:"border.default",borderRadius:2,bg:"canvas.overlay",boxShadow:"shadow.large",zIndex:120,fontSize:0,color:"fg.default",right:Iu?0:void 0,left:Iu?void 0:0,children:[jsxRuntimeExports.jsx(Box,{mb:1,fontWeight:600,children:lo}),jsxRuntimeExports.jsxs(Box,{color:"fg.muted",children:["Name: ",Au.agentName]}),jsxRuntimeExports.jsxs(Box,{color:"fg.muted",children:["Location: ",Au.location]}),jsxRuntimeExports.jsxs(Box,{color:"fg.muted",children:["Spec: ",Au.specId||"—"]}),jsxRuntimeExports.jsxs(Box,{color:"fg.muted",children:["Harness: ",Au.harness||"—"]}),jsxRuntimeExports.jsxs(Box,{color:"fg.muted",children:["Variant: ",Au.variant||"—"]}),jsxRuntimeExports.jsxs(Box,{color:"fg.muted",children:["Status: ",Hu?"creating":Au.status||"—"]}),jsxRuntimeExports.jsxs(Box,{color:"fg.muted",wordBreak:"break-all",children:["Agent base URL: ",Au.baseUrl||"—"]}),jsxRuntimeExports.jsxs(Box,{color:"fg.muted",wordBreak:"break-all",children:["Code sandbox base URL:"," ",Au.sandboxBaseUrl?jsxRuntimeExports.jsx(Box,{as:"a",href:Au.sandboxBaseUrl,target:"_blank",rel:"noopener noreferrer",color:"accent.fg",textDecoration:"underline",children:Au.sandboxBaseUrl}):"—"]}),jsxRuntimeExports.jsxs(Box,{color:"fg.muted",wordBreak:"break-all",display:"flex",alignItems:"center",gap:1,children:["Agent ID:"," ",Au.agentId?Au.agentId:Hu?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(StyledSpinner,{size:"small",sx:{width:12,height:12}}),"Creating…"]}):"—"]}),jsxRuntimeExports.jsxs(Box,{color:"fg.muted",wordBreak:"break-all",children:["Agent status:"," ",Gu&&Fu?jsxRuntimeExports.jsx(Box,{as:"a",href:Fu,target:"_blank",rel:"noopener noreferrer",color:"accent.fg",textDecoration:"underline",children:Fu}):"n/a"]}),jsxRuntimeExports.jsxs(Box,{color:"fg.muted",wordBreak:"break-all",children:["Code sandbox status:"," ",zu?jsxRuntimeExports.jsx(Box,{as:"a",href:zu,target:"_blank",rel:"noopener noreferrer",color:"accent.fg",textDecoration:"underline",children:zu}):"n/a"]}),Vu&&jsxRuntimeExports.jsxs(Box,{mt:1,p:1,border:"1px solid",borderColor:"danger.muted",borderRadius:2,bg:"danger.subtle",color:"danger.fg",wordBreak:"break-word",children:["Error: ",Au.error]})]})]})},insideJupyterLab=()=>loadJupyterConfig().insideJupyterLab;function collect(Au,lo){const $u=Au?.header?.msg_type,Ru=Au?.content??{};$u==="stream"?(lo.stdout.push(String(Ru.text??"")),lo.outputs.push({output_type:"stream",text:Ru.text})):$u==="execute_result"||$u==="display_data"?lo.outputs.push({output_type:$u,data:Ru.data}):$u==="error"&&(lo.error=`${Ru.ename??"Error"}: ${Ru.evalue??""}`,lo.outputs.push({output_type:"error",ename:Ru.ename,evalue:Ru.evalue,traceback:Ru.traceback}))}function browserSource(){let Au;return{variant:"pyodide",acquire:async()=>{const{createLiteServiceManager:lo,jupyterReactStore:$u,loadJupyterConfig:Ru}=await __vitePreload(async()=>{const{createLiteServiceManager:Pu,jupyterReactStore:Ou,loadJupyterConfig:Mu}=await import("./chunks/index-BN8Bbau-.js").then(Du=>Du.r);return{createLiteServiceManager:Pu,jupyterReactStore:Ou,loadJupyterConfig:Mu}},[],import.meta.url);Au=Au??{baseUrl:libExports$5.PageConfig.getOption("baseUrl"),wsUrl:libExports$5.PageConfig.getOption("wsUrl")},Ru({lite:!0});const Iu=await lo();return $u.getState().setServiceManager(Iu),Iu},release:()=>{Au&&(libExports$5.PageConfig.setOption("baseUrl",Au.baseUrl),libExports$5.PageConfig.setOption("wsUrl",Au.wsUrl),Au=void 0)},owned:!0}}function createBrowserSandboxService(Au=browserSource()){const lo=signal$2(null),$u=signal$2("idle"),Ru=signal$2(null),Iu=computed$1(()=>({state:$u.value,variant:Au.variant,kernelId:lo.value?.kernel_id})),Pu=computed$1(()=>$u.value==="running");let Ou=null,Mu=null,Du=null,Lu=null;async function Bu(){if(Mu)return;$u.value="starting",Ou=await Au.acquire();const ju=await Ou.sessions.startNew({name:"loop",path:"loop.ipynb",type:"notebook",kernel:{name:"python"}});Du=ju.kernel,Mu=ju.kernel,lo.value={variant:Au.variant,sandbox_running:!0,kernel_id:Mu?.id,kernel_name:"python"},$u.value="running"}return{kind:"browser",snapshot:Iu,status:lo,ready:Pu,lastExecution:Ru,serverUrl:"",getServiceManager:()=>Ou,getKernelConnection:()=>Du,report(ju){lo.value=ju},setState(ju){$u.value=ju},connect(){return Lu=Lu??Bu().catch(ju=>{throw $u.value="error",lo.value=null,Lu=null,ju}),()=>{Mu?.shutdown?.(),Mu=null,Du=null,Ou=Au.owned?null:Ou,Au.release?.(),Lu=null,$u.value="idle",lo.value=null}},async execute(ju){const Fu=Date.now();try{if(await(Lu??Bu()),!Mu)throw new Error("The browser kernel did not start");const zu={outputs:[],stdout:[],error:""},Uu=Mu.requestExecute({code:ju});Uu.onIOPub=Vu=>collect(Vu,zu),await Uu.done;const Hu={code:ju,success:!zu.error,stdout:zu.stdout.join(""),error:zu.error||void 0,outputs:zu.outputs,startedAt:Fu,finishedAt:Date.now()};return Ru.value=Hu,Hu}catch(zu){const Uu={code:ju,success:!1,error:zu instanceof Error?zu.message:String(zu),startedAt:Fu,finishedAt:Date.now()};return Ru.value=Uu,Uu}}}}function summarize(Au,lo){if(!Au)return{state:lo};const $u=Au.variant==="jupyter-server"||Au.variant==="datalayer";return{state:!!Au.sandbox_running||$u&&!!Au.jupyter_connected?"running":lo==="running"?"idle":lo,variant:Au.variant,kernelId:Au.kernel_id,jupyterUrl:Au.jupyter_url,jupyterToken:Au.jupyter_token,agentBaseUrl:Au.agent_base_url}}const RECONNECT_BASE_MS=1e3,RECONNECT_MAX_MS=3e4;function createServerSandboxService(Au){const lo=signal$2(null),$u=signal$2("idle"),Ru=signal$2(void 0),Iu=signal$2(null),Pu=computed$1(()=>({...summarize(lo.value,$u.value),errorReason:$u.value==="error"?Ru.value:void 0})),Ou=computed$1(()=>Pu.value.state==="running");return{kind:"server",connect(Mu){if(typeof WebSocket>"u")return()=>{};let Du=null,Lu=null,Bu=0,ju=!1;const Fu=()=>{if(ju)return;const zu=Au.replace(/^http/,"ws"),Uu=Mu?`?agent_id=${encodeURIComponent(Mu)}`:"";Du=new WebSocket(`${zu}/api/v1/configure/sandbox/ws${Uu}`),Du.onopen=()=>{Bu=0},Du.onmessage=Hu=>{try{lo.value=JSON.parse(String(Hu.data))}catch{}},Du.onclose=()=>{if(ju)return;lo.value=null,Bu+=1;const Hu=Math.min(RECONNECT_BASE_MS*2**(Bu-1),RECONNECT_MAX_MS);Lu=setTimeout(Fu,Hu)}};return Fu(),()=>{ju=!0,Lu&&clearTimeout(Lu),Du?.close(),Du=null}},snapshot:Pu,status:lo,ready:Ou,lastExecution:Iu,serverUrl:Au,report(Mu){lo.value=Mu},setState(Mu,Du){$u.value=Mu,Ru.value=Mu==="error"?Du:void 0},async execute(Mu){const Du=Date.now();try{const Lu=await fetch(`${Au}/api/v1/sandbox/execute`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({code:Mu})}),Bu=Lu.ok?await Lu.json():null,ju={code:Mu,success:Lu.ok&&!Bu?.error,stdout:Bu?.stdout,stderr:Bu?.stderr,error:Lu.ok?Bu?.error:`Execution failed: ${Lu.status}`,outputs:Bu?.outputs,startedAt:Du,finishedAt:Date.now()};return Iu.value=ju,ju}catch(Lu){const Bu={code:Mu,success:!1,error:Lu instanceof Error?Lu.message:String(Lu),startedAt:Du,finishedAt:Date.now()};return Iu.value=Bu,Bu}}}}const ANONYMOUS_JUPYTER_URL="https://prod1.datalayer.run/api/jupyter-server",ANONYMOUS_JUPYTER_TOKEN="60c1661cc408f978c309d04157af55c9588ff9557c9380e4fb50785750703da6",SANDBOX_TARGETS=["browser","local","jupyter","datalayer"];function heldTargetReason(Au,lo){if(Au==="local"&&!lo&&!insideJupyterLab())return"Not offered on the web for now: a local agent and the Jupyter server it starts run beside JupyterLab, not in a page."}const TARGET_SPECS={browser:{label:"Browser",hint:"Python in this page (Pyodide), with the agent loop running here too. Only the model is asked over the network.",hasAgent:!0,noAgentReason:""},local:{label:"Local",hint:"A local agent, with the Jupyter server it starts beside itself.",hasAgent:!0,noAgentReason:"",configure:{variant:"jupyter-server",jupyter_url:"",jupyter_token:""}},jupyter:{label:"Jupyter",hint:"A named Jupyter server: the anonymous one on prod1.datalayer.run.",hasAgent:!1,noAgentReason:"No agent on an anonymous Jupyter server",configure:{variant:"jupyter-server",jupyter_url:ANONYMOUS_JUPYTER_URL,jupyter_token:ANONYMOUS_JUPYTER_TOKEN}},datalayer:{label:"Datalayer",hint:"A Datalayer runtime running the agent this workspace asks for.",hasAgent:!0,noAgentReason:""}};function targetHasAgent(Au){return TARGET_SPECS[Au]?.hasAgent??!1}function targetRunsAgentInPage(Au){return Au==="browser"}function createSwitchableSandboxService({serverUrl:Au,initialTarget:lo="local",kernelSource:$u,localAgent:Ru,blueprint:Iu}){const Pu=signal$2(lo),Ou=createServerSandboxService(Au),Mu=createBrowserSandboxService($u??browserSource()),Du=computed$1(()=>Pu.value==="browser"?Mu:Ou);let Lu=null,Bu;const ju=computed$1(()=>Du.value.snapshot.value),Fu=computed$1(()=>Du.value.status.value),zu=computed$1(()=>Du.value.ready.value),Uu=computed$1(()=>Du.value.lastExecution.value);async function Hu(Wu){if(Wu==="local"){const ed=Iu?.()??Ru?.createPayload;ed&&await Vu(ed)}const Ku=TARGET_SPECS[Wu]?.configure;if(!Ku)return;const Ju=TARGET_SPECS[Wu].label;let Yu;try{Yu=await fetch(`${Au}/api/v1/agents/sandbox/configure`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(Ku)})}catch(ed){throw new Error(`${Ju} needs an agent-runtimes server at ${Au}, and nothing answered there. Start one and try again. (${ed instanceof Error?ed.message:String(ed)})`,{cause:ed})}if(!Yu.ok)throw new Error(`The server could not switch to ${Ju} (${Yu.status} ${Yu.statusText}). `+await detail(Yu));const Xu=await fetch(`${Au}/api/v1/agents/sandbox/restart`,{method:"POST"});if(!Xu.ok)throw new Error(`The server could not start ${Ju} (${Xu.status} ${Xu.statusText}). `+await detail(Xu))}function Vu(Wu){return ensureServerAgent(Au,Bu,Wu)}function Gu(){if(Lu?.(),Pu.peek()==="datalayer"){Lu=null,Ou.setState("starting");return}Lu=Du.peek().connect(Bu)}return{get kind(){return Pu.peek()==="browser"?"browser":"server"},target:Pu,snapshot:ju,status:Fu,ready:zu,lastExecution:Uu,serverUrl:Au,getServiceManager:()=>Pu.peek()==="browser"?Mu.getServiceManager():null,getKernelConnection:()=>Pu.peek()==="browser"?Mu.getKernelConnection():null,report(Wu){Du.peek().report(Wu)},setState(Wu,Ku){Du.peek().setState(Wu,Ku)},execute(Wu){return Du.peek().execute(Wu)},connect(Wu){Bu=Wu;const Ku=Pu.peek()==="local"&&Wu?Iu?.()??Ru?.createPayload:void 0;if(!Ku)return Gu(),()=>{Lu?.(),Lu=null};let Ju=!1;return Ou.setState("starting"),Vu(Ku).then(()=>{Ju||Gu()},Yu=>{Ju||(Ou.setState("error"),console.error("[loop] Local agent could not be started:",Yu))}),()=>{Ju=!0,Lu?.(),Lu=null}},async setTarget(Wu){const Ku=Pu.peek();if(Wu===Ku)return;const Ju=heldTargetReason(Wu,Au);if(Ju)throw new Error(Ju);Lu?.(),Lu=null;try{await Hu(Wu)}catch(Yu){throw Gu(),Yu}Pu.value=Wu,Gu()}}}async function ensureServerAgent(Au,lo,$u){const Ru=lo?.trim();if(!Ru)throw new Error("Local needs an agent id before its runtime can start.");let Iu;try{Iu=await fetch(`${Au}/api/v1/agents/${encodeURIComponent(Ru)}`)}catch(Ou){throw new Error(`Local needs an agent-runtimes server at ${Au}, and nothing answered there. Start one and try again. (${Ou instanceof Error?Ou.message:String(Ou)})`,{cause:Ou})}if(Iu.ok){await ensureServerSandbox(Au,Ru);return}if(Iu.status!==404)throw new Error(`The server could not inspect local agent ${Ru} (${Iu.status} ${Iu.statusText}). `+await detail(Iu));const Pu=await fetch(`${Au}/api/v1/agents`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({transport:"ag-ui",sandbox_variant:"jupyter-server",...$u,name:Ru})});if(!Pu.ok&&Pu.status!==409)throw new Error(`The server could not launch local agent ${Ru} (${Pu.status} ${Pu.statusText}). `+await detail(Pu));Pu.status===409&&await ensureServerSandbox(Au,Ru)}async function ensureServerSandbox(Au,lo){const $u=await fetch(`${Au}/api/v1/agents/${encodeURIComponent(lo)}/sandbox/ensure`,{method:"POST"});if(!$u.ok)throw new Error(`The server could not start a sandbox for local agent ${lo} (${$u.status} ${$u.statusText}). `+await detail($u))}async function detail(Au){try{const lo=await Au.json();return typeof lo.detail=="string"?lo.detail:""}catch{return""}}function useOptionalTeamSelection(){return useReactorPlatform().getOutput(AGENTS_PLUGIN_NAME)?.team}const NO_TARGET={value:void 0,peek:()=>{}},NO_MEMBER={value:void 0,peek:()=>{}};function AgentSummaryPanel({workspace:Au}){const lo=useSandboxService(),$u=useSignalValue$1(lo?.target??NO_TARGET),Ru=useOptionalTeamSelection(),Iu=useSignalValue$1(Ru?.active??NO_MEMBER);if(!lo)return null;const Pu=Au.sandbox,Ou=Iu?.specId||Au.agentId,Mu=AGENTSPECS$1[Ou],Du={agentName:Iu?.name||Mu?.name||Au.agentId,location:$u?TARGET_SPECS[$u].label:"—",specId:Ou,harness:Mu?.harness,variant:Pu.variant,status:Pu.state,baseUrl:Pu.agentBaseUrl||Au.serverUrl,sandboxBaseUrl:Pu.jupyterUrl,agentId:Au.agentId,isReady:Pu.state==="running"};return jsxRuntimeExports.jsx(AgentSummary,{summary:Du})}const RING=14,STROKE=2.5,RADIUS=(RING-STROKE)/2,CIRCUMFERENCE=2*Math.PI*RADIUS,DEFAULT_WARN_AT=.25,DEFAULT_DANGER_AT=.1,DEFAULT_PULSE_AT=.05,PULSE_MS=1200;function format(Au){const lo=Math.max(0,Math.ceil(Au/1e3)),$u=Math.floor(lo/60),Ru=lo%60;return`${$u}:${String(Ru).padStart(2,"0")}`}function AnonymousKeyTimer({expiresAt:Au,grantedMs:lo,label:$u="Trial key",warnAt:Ru=DEFAULT_WARN_AT,dangerAt:Iu=DEFAULT_DANGER_AT,pulseAt:Pu=DEFAULT_PULSE_AT,onExpire:Ou}){const[Mu,Du]=reactExports.useState(()=>Date.now()),Lu=reactExports.useRef(lo??Math.max(1,Au-Date.now())),Bu=reactExports.useRef(!1);reactExports.useEffect(()=>{const Hu=window.setInterval(()=>{Du(Vu=>{const Gu=Date.now(),Wu=Ku=>Math.ceil((Au-Ku)/1e3);return Wu(Gu)===Wu(Vu)?Vu:Gu})},250);return()=>window.clearInterval(Hu)},[Au]);const ju=Math.max(0,Au-Mu);reactExports.useEffect(()=>{ju>0||Bu.current||(Bu.current=!0,Ou?.())},[ju,Ou]);const Fu=Math.min(1,Math.max(0,ju/Lu.current)),zu=Fu<=Pu,Uu=Fu<=Iu?"danger.fg":Fu<=Ru?"attention.fg":"fg.muted";return jsxRuntimeExports.jsxs(Box,{display:"inline-flex",alignItems:"center",gap:1,px:2,py:"2px",borderRadius:"999px",border:"1px solid",borderColor:"border.muted",bg:"canvas.subtle",color:Uu,fontVariantNumeric:"tabular-nums",sx:{...zu?{"@keyframes dla-key-pulse":{"0%, 100%":{opacity:1},"50%":{opacity:.45}},animation:`dla-key-pulse ${PULSE_MS}ms ease-in-out infinite`,"@media (prefers-reduced-motion: reduce)":{animation:"none"}}:null},title:`${$u}: this workspace is talking to the agent on a temporary key issued to nobody in particular. When it runs out the chat asks you to sign in. Sign in now for an account of your own.`,children:[jsxRuntimeExports.jsx(Box,{display:"flex",alignItems:"center",color:Uu,children:jsxRuntimeExports.jsx(KeyIcon,{size:12})}),jsxRuntimeExports.jsxs(Box,{as:"svg","aria-hidden":"true",focusable:"false",width:RING,height:RING,viewBox:`0 0 ${RING} ${RING}`,display:"block",flexShrink:0,children:[jsxRuntimeExports.jsx("circle",{cx:RING/2,cy:RING/2,r:RADIUS,fill:"none",stroke:"currentColor",strokeWidth:STROKE,opacity:.2}),jsxRuntimeExports.jsx("circle",{cx:RING/2,cy:RING/2,r:RADIUS,fill:"none",stroke:"currentColor",strokeWidth:STROKE,strokeLinecap:"round",strokeDasharray:CIRCUMFERENCE,strokeDashoffset:CIRCUMFERENCE*(1-Fu),transform:`rotate(-90 ${RING/2} ${RING/2})`,style:{transition:"stroke-dashoffset 0.5s linear"}})]}),jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:Uu,fontWeight:"semibold"},children:format(ju)})]})}function AnonymousKeyHeaderBadge({workspace:Au}){return jsxRuntimeExports.jsx(Box,{order:1,display:"inline-flex",alignItems:"center",children:jsxRuntimeExports.jsx(AnonymousKeyBadge,{workspace:Au})})}function AnonymousKeyBadge({workspace:Au}){const lo=useAnonymousSession(),$u=Au.sandbox.target??"local";return!targetRunsAgentInPage($u)||lo.status==="idle"||lo.status==="expired"?null:lo.expiresAt?jsxRuntimeExports.jsx(AnonymousKeyTimer,{expiresAt:lo.expiresAt,grantedMs:lo.grantedMs,onExpire:()=>useAnonymousSessionStore.getState().expire()}):jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:lo.error?"danger.fg":"fg.muted"},title:lo.error,children:lo.error?"No trial key":"Getting a trial key…"})}function SandboxSelector(Au){const lo=useOptionalSandboxService(),[$u,Ru]=reactExports.useState(!1),[Iu,Pu]=reactExports.useState(null),Ou=useSignalValue$1(lo?.snapshot??IDLE_SANDBOX_SNAPSHOT_SIGNAL),Mu=useSignalValue$1(lo?.status??EMPTY_STATUS),Du=useSignalValue$1(lo?.target??DEFAULT_TARGET),Lu=reactExports.useCallback(async ju=>{if(!(!lo||ju===Du)){Ru(!0),Pu(null);try{await lo.setTarget(ju)}catch(Fu){Pu(Fu instanceof Error?Fu.message:String(Fu))}finally{Ru(!1)}}},[lo,Du]);if(!lo)return null;const Bu=Math.max(0,SANDBOX_TARGETS.indexOf(Du));return jsxRuntimeExports.jsxs(Box,{display:"flex",alignItems:"center",gap:2,minWidth:0,children:[jsxRuntimeExports.jsx(Box,{width:16,flexShrink:0,display:"flex",justifyContent:"center",children:$u?jsxRuntimeExports.jsx(StyledSpinner,{size:"small"}):null}),jsxRuntimeExports.jsx(KernelIndicator,{state:sandboxIndicatorState(Ou.state,Mu?.execution_state,Mu?.is_executing),kernelId:Ou.kernelId??Mu?.kernel_id,kernelName:Mu?.kernel_name,serverUrl:Ou.jupyterUrl??Mu?.jupyter_url,websocketUrl:toWebsocketUrl(Ou.jupyterUrl??Mu?.jupyter_url),environmentName:TARGET_SPECS[Du].label,overlayTitle:`${TARGET_SPECS[Du].label} Kernel`,position:"se",bordered:!1}),jsxRuntimeExports.jsx(SegmentedControl,{"aria-label":"Where code runs",size:"small",style:{listStyle:"none",margin:0,padding:0},sx:{listStyle:"none",m:0,p:0,"& > li":{listStyle:"none"},"& > li::marker":{content:"none"}},children:SANDBOX_TARGETS.map((ju,Fu)=>{const zu=heldTargetReason(ju,lo?.serverUrl??"");return jsxRuntimeExports.jsx(SegmentedControl.Button,{selected:Fu===Bu,"aria-disabled":zu?!0:void 0,"data-sandbox-target":ju,"data-sandbox-target-held":zu?"":void 0,sx:{listStyle:"none",...zu?{color:"fg.subtle",cursor:"not-allowed"}:null},title:zu??TARGET_SPECS[ju].hint,onClick:()=>zu?void 0:void Lu(ju),children:TARGET_SPECS[ju].label},ju)})}),Iu||Ou.errorReason?jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:"danger.fg",lineHeight:1.3,maxWidth:280,minWidth:0},title:Iu??Ou.errorReason,children:Iu??Ou.errorReason}):jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:"fg.muted"},title:TARGET_SPECS[SANDBOX_TARGETS[Bu]].hint,children:Ou.state})]})}function toWebsocketUrl(Au){return Au?.replace(/^http/,"ws")}const EMPTY_STATUS={value:null,peek:()=>null},DEFAULT_TARGET={value:"local",peek:()=>"local"};function MemberIcon({icon:Au}){const lo=agentIcon(Au);return jsxRuntimeExports.jsx(lo,{})}function TeamMemberPicker(){const Au=useOptionalTeamSelection();return!Au||Au.members.length<2?null:jsxRuntimeExports.jsx(TeamMemberMenu,{selection:Au})}function TeamMemberMenu({selection:Au}){const[lo,$u]=reactExports.useState(!1),Ru=useSignalValue$1(Au.selected),Iu=Au.members.find(Pu=>Pu.id===Ru);return jsxRuntimeExports.jsx(AnchoredOverlay,{width:"large",open:lo,onOpen:()=>$u(!0),onClose:()=>$u(!1),renderAnchor:Pu=>jsxRuntimeExports.jsx(IconButton,{...Pu,"aria-labelledby":void 0,icon:ForwardRef$2,"aria-label":Iu?`Talking to ${Iu.name}. Choose another agent.`:"Choose an agent",variant:"invisible",size:"small"}),children:jsxRuntimeExports.jsx(Box,{width:440,maxWidth:"calc(100vw - 16px)",children:jsxRuntimeExports.jsxs(ActionList,{selectionVariant:"single",role:"listbox","aria-label":`Agents in ${Au.team.name}`,children:[jsxRuntimeExports.jsx(ActionList.GroupHeading,{children:Au.team.name}),Au.members.map(Pu=>jsxRuntimeExports.jsxs(ActionList.Item,{selected:Pu.id===Ru,onSelect:()=>{Au.select(Pu.id),$u(!1)},children:[jsxRuntimeExports.jsx(ActionList.LeadingVisual,{children:jsxRuntimeExports.jsx(MemberIcon,{icon:Pu.icon})}),jsxRuntimeExports.jsxs(Box,{as:"span",display:"flex",alignItems:"center",gap:2,children:[Pu.name,Pu.isSupervisor?jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:"fg.muted"},children:"supervisor"}):null]}),Pu.description?jsxRuntimeExports.jsx(ActionList.Description,{variant:"block",sx:{display:"block",whiteSpace:"normal",overflowWrap:"anywhere",minWidth:0},children:Pu.description}):null]},Pu.id))]})})})}function specIdOf(Au){return(Au??"").split(":")[0]??""}function teamMembers(Au){const lo=specIdOf(Au.supervisor?.ref),$u=Iu=>{const Pu=AGENTSPECS$1[Iu];return{description:Pu?.description,emoji:Pu?.emoji,icon:Pu?.icon}},Ru=(Au.agents??[]).map(Iu=>{const Pu=specIdOf(Iu.ref);return{id:Iu.id,name:Iu.name||Pu||Iu.id,specId:Pu,isSupervisor:Pu!==""&&Pu===lo,...$u(Pu)}});return[...Ru.filter(Iu=>Iu.isSupervisor),...Ru.filter(Iu=>!Iu.isSupervisor)]}function createTeamSelection(Au){const lo=TEAM_SPECS[Au];if(!lo)return;const $u=teamMembers(lo);if($u.length===0)return;const Ru=signal$2($u[0].id);return{team:lo,members:$u,selected:Ru,select:Iu=>{$u.some(Pu=>Pu.id===Iu)&&(Ru.value=Iu)},sharing:lo.context?.sharing??"shared",active:computed$1(()=>$u.find(Iu=>Iu.id===Ru.value))}}function subagentsFor(Au,lo){const $u=teamMembers(Au),Ru=$u.find(Du=>Du.id===lo);if(!Ru)return[];const Iu=(Du,Lu,Bu)=>{const ju=AGENTSPECS$1[Lu];if(ju)return{name:Du,description:Bu||ju.description||Du,instructions:ju.systemPrompt,model:ju.model,icon:ju.icon}},Pu=Ru.isSupervisor||Au.delegation?.allowPeerDelegation?$u.filter(Du=>Du.id!==lo).map(Du=>Iu(Du.name,Du.specId,Du.description)):[],Mu=((Au.agents??[]).find(Du=>Du.id===lo)?.subagents??[]).map(Du=>Iu(Du.name,(Du.ref??"").split(":")[0]??"",Du.description));return[...Pu,...Mu].filter(Boolean)}const DEFAULT_DATALAYER_AGENTSPEC="jupyter-tutor",AGENTS_PLUGIN_NAME="@datalayer/loop-plugin-agents",offeredTarget=(Au,lo)=>heldTargetReason(Au,lo)?"browser":Au,AgentsPlugin={name:AGENTS_PLUGIN_NAME,displayName:"Agents",description:"Where the agent and its code run: this page, a local server, or a Datalayer runtime.",octicon:"container",emoji:"📦",config:{serverUrl:"",target:"local"},contributionPoints:[LoopAgentBlueprint],preserveOutput:!0,build({config:Au,reactor:lo}){const $u=Au.showAgentVariants??!0,Ru=Au.teamId?createTeamSelection(Au.teamId):void 0;return{team:Ru,sandbox:createSwitchableSandboxService({serverUrl:Au.serverUrl,initialTarget:offeredTarget(($u||Au.targetFixed?Au.target:"browser")??"local",Au.serverUrl),kernelSource:Au.kernelSource,localAgent:Au.localAgent,blueprint:()=>{const Iu=lo.getContributions(LoopAgentBlueprint)[0]?.value;if(Iu)return{...Iu.specId?{agent_spec_id:Iu.specId}:null,...Iu.createPayload}}}),components:[{slot:LoopSlots.status,id:"sandbox-status",Component:SandboxStatusBridge},{slot:LoopSlots.status,id:"datalayer-agent",Component:DatalayerAgentMount},...Ru&&Au.showTeamPicker!==!1?[{slot:LoopSlots.header,id:"team-member-picker",Component:TeamMemberPicker}]:[],...$u?[{slot:LoopSlots.header,id:"sandbox-selector",Component:SandboxSelector}]:[],...Au.showAgentSummary===!1?[]:[{slot:LoopSlots.header,id:"agent-summary",Component:AgentSummaryPanel}],{slot:LoopSlots.chatHeader,id:"anonymous-key",Component:AnonymousKeyBadge},{slot:LoopSlots.header,id:"anonymous-key-header",Component:AnonymousKeyHeaderBadge}]}},register({contribute:Au,state:lo}){const $u=lo.getOutput()?.sandbox;if($u)return Au(LoopAgentGate,{check:Ru=>{const Iu=Ru.sandbox.target??$u.target.peek();return targetHasAgent(Iu)||TARGET_SPECS[Iu].noAgentReason}},{id:"sandbox-target"})},contributes:[contribution(LoopViewType,{viewType:"sandbox",title:"Sandbox",icon:ServerIcon,order:40,load:()=>__vitePreload(()=>import("./chunks/SandboxView-NqXA2LuS.js"),[],import.meta.url)},{id:"sandbox",order:40}),contribution(LoopCommand,{name:"sandbox",aliases:["code-sandbox"],description:"Show the code sandbox: variant, kernel, Jupyter server",group:"Capabilities",run:async({workspace:Au})=>{Au.setActiveViewType("sandbox")}},{id:"sandbox"})]},PULSE_ANIMATION="loop-subagent-pulse",KEYFRAMES=`@keyframes ${PULSE_ANIMATION} {
|
|
3851
|
+
`).filter(Iu=>Iu.startsWith("data:")).map(Iu=>Iu.slice(5).trim()).join("");if(Ru)try{lo.push(JSON.parse(Ru))}catch{}}return lo}function pageTurnOf(Au){let lo=null;for(const $u of streamEvents(Au)){if($u.type==="RUN_ERROR")return{refused:String($u.message??"Its page could not run.")};if($u.type==="CUSTOM"&&$u.name===LOOP_PAGE){const Ru=$u.value??{};lo={outputs:Ru.outputs??{},inputs:Ru.inputs??{}}}}return lo??{refused:"Its page showed nothing: its code answered no outputs."}}const base=Au=>`${Au.serverUrl.replace(/\/+$/,"")}/api/v1/apps/sessions`;async function posted(Au,lo,$u){const Ru=await(Au.fetcher??fetch)(lo,{method:"POST",headers:{"content-type":"application/json",...Au.token?{Authorization:`Bearer ${Au.token}`}:{}},body:JSON.stringify($u)});if(!Ru.ok){let Iu="";try{const Pu=await Ru.json();Iu=typeof Pu.detail=="string"?Pu.detail:""}catch{}throw new Error(Iu||`Its page was refused (${Ru.status}).`)}return Ru.text()}async function openPageSession(Au){const lo=await posted(Au,base(Au),{agent:Au.agentId});for(const $u of streamEvents(lo))if($u.type==="CUSTOM"&&$u.name==="loop.session"){const Ru=$u.value?.uid;if(typeof Ru=="string"&&Ru)return Ru}throw new Error("The runtime opened no session for its page.")}async function runPageIn(Au,lo,$u){try{const Ru=await posted(Au,`${base(Au)}/${encodeURIComponent(lo)}/page`,{inputs:$u});return pageTurnOf(Ru)}catch(Ru){return{refused:Ru instanceof Error?Ru.message:String(Ru)}}}function outputsData(Au){return Object.fromEntries(Object.entries(Au).map(([lo,$u])=>[`/outputs/${lo}`,$u]))}const PAGE_RUN_DELAY_MS=300,NO_TURN$6=signal$2({id:0,status:"idle"}),NO_CONVERSATION$2=signal$2([]);function componentsOnPage(Au){const lo=new Set;for(const $u of Au){const Ru=$u.updateComponents;for(const Iu of Ru?.components??[])lo.add(String(Iu.component))}return[...lo]}function blocksMissing(Au,lo){const $u=new Set(lo),Ru=Au.filter(Iu=>!$u.has(Iu));return Ru.length===0?null:`This page places ${Ru.join(", ")}, which no enabled plugin contributes: ${Ru.length===1?"it is":"they are"} drawn once the plugin that contributes ${Ru.length===1?"it":"them"} is on.`}function AppPage({app:Au,workspace:lo}){const $u=useContributions(LoopChatTurn),Ru=useSignalValue$1($u[0]?.value.turn??NO_TURN$6),Iu=useSignalValue$1($u[0]?.value.conversation??NO_CONVERSATION$2),Pu=reactExports.useMemo(()=>appPageMessages(Au,SURFACE_CATALOG_ID),[Au]),Ou=useContributions(LoopCanvasBlock),Mu=[...new Set(Ou.map(bd=>bd.value.id))].sort(),Du=Mu.join(","),Lu=useOwnComponents(),Bu=reactExports.useMemo(()=>{const bd=blocksMissing(componentsOnPage(Pu),Mu);if(bd)return{problem:bd};try{return{catalog:catalogOfBlocks(Mu,Lu)}}catch(Sd){return{problem:Sd instanceof Error?Sd.message:String(Sd)}}},[Pu,Du,Lu]),[ju,Fu]=reactExports.useState(null),zu=pageOf(Au),[Uu,Hu]=reactExports.useState({}),Vu=reactExports.useMemo(()=>({...appPageData(Au,Ru,Iu),...outputsData(Uu)}),[Au,Ru,Iu,Uu]),Gu=useIAMStore(bd=>bd.token)??"",Wu=useChatWords(),Ku=agentServerOf(lo.sandbox,lo.serverUrl),Ju=reactExports.useRef(null);Ju.current=Ku===void 0?null:{serverUrl:Ku,agentId:lo.agentId||Au.id,token:Gu||void 0};const Yu=reactExports.useRef("");Yu.current=Ku===void 0?noRuntimeSaid(lo.sandbox,Wu):"";const Xu=reactExports.useRef(null),ed=reactExports.useRef(!1),td=reactExports.useRef(null),nd=reactExports.useRef(""),od=reactExports.useRef(!0),sd=reactExports.useCallback(bd=>{td.current=bd,!ed.current&&(ed.current=!0,(async()=>{for(;td.current&&od.current;){const Sd=td.current;td.current=null;const Ed=Ju.current;if(!Ed){Fu(Yu.current);continue}try{Xu.current??=openPageSession(Ed);const cd=await runPageIn(Ed,await Xu.current,Sd);if(!od.current)break;"refused"in cd?Fu(cd.refused):(Fu(null),Hu(cd.outputs))}catch(cd){Xu.current=null,od.current&&Fu(cd instanceof Error?cd.message:String(cd))}}ed.current=!1})())},[]),ad=reactExports.useRef(null);reactExports.useEffect(()=>(od.current=!0,()=>{od.current=!1,ad.current?.()}),[]);const pd=reactExports.useCallback(bd=>{if(!zu?.live)return;ad.current?.();let Sd;const Ed=dd=>{const md=pageInputsOf(Au,dd),ld=JSON.stringify(md);ld!==nd.current&&(clearTimeout(Sd),Sd=setTimeout(()=>{nd.current=ld,sd(md)},PAGE_RUN_DELAY_MS))},cd=bd.dataModel.subscribe("/inputs",Ed);Ed(cd.value),ad.current=()=>{clearTimeout(Sd),cd.unsubscribe()}},[Au,zu?.live,sd]),gd=reactExports.useRef(lo);gd.current=lo;const _d=reactExports.useRef(""),yd=reactExports.useCallback((bd,Sd)=>{const Ed=appPageAction(Au,{name:bd.name,context:bd.context??{}},dd=>Sd?.dataModel.get(dd),_d.current),cd=gd.current.viewControls;if("refused"in Ed){Fu(Ed.refused);return}if(Fu(null),"runPage"in Ed)sd(Ed.runPage);else if("stop"in Ed)cd.stop?.();else if("newChat"in Ed)cd.newChat?.();else{if(cd.send){const dd=cd.send(Ed.send,{loop:Ed.loop});if(dd){Fu(dd);return}}else if(Ed.loop.files){Fu("The conversation is not ready for a file yet: try again.");return}else gd.current.prompts.submit(Ed.send);_d.current=Ed.inputs;for(const dd of Ed.clear)Sd?.dataModel.set(dd,"")}},[Au,sd]);return jsxRuntimeExports.jsx(Box,{"data-testid":"app-page",height:"100%",minHeight:0,overflow:"auto",p:3,children:"problem"in Bu?jsxRuntimeExports.jsx(Box,{role:"status",color:"fg.muted",fontSize:1,children:Bu.problem}):jsxRuntimeExports.jsx(InlineSurface,{messages:Pu,data:Vu,onAction:yd,validationError:ju,catalog:Bu.catalog,...zu?{onSurface:pd}:{}},Du)})}const APP_PAGE_PLUGIN_NAME="@datalayer/loop-plugin-app-page";function defineAppPagePlugin(Au){function lo({workspace:Ru}){return jsxRuntimeExports.jsx(AppPage,{app:Au,workspace:Ru})}return{name:`${APP_PAGE_PLUGIN_NAME}-${Au.id}`,displayName:`${Au.name}: its page`,description:`The page of ${Au.name}, drawn beside its conversation.`,octicon:"browser",emoji:Au.emoji||void 0,contributes:[contribution(LoopEditorView,{surfaceId:APP_PAGE_SURFACE,title:Au.name,icon:BrowserIcon,order:-10,load:async()=>({default:lo})},{id:APP_PAGE_SURFACE,order:-10})]}}const APP_HOST_PAGE_VIEW="app-page";function defineAppHostPagePlugin(Au,lo){function $u({workspace:Iu}){return jsxRuntimeExports.jsx(lo,{app:Au,workspace:Iu})}return{name:`${APP_PAGE_PLUGIN_NAME}-${Au.id}`,displayName:`${Au.name}: its page`,description:`The page of ${Au.name}, drawn by its host.`,octicon:"browser",emoji:Au.emoji||void 0,contributes:[contribution(LoopViewType,{viewType:APP_HOST_PAGE_VIEW,title:Au.name,icon:BrowserIcon,order:-10,load:async()=>({default:$u})},{id:APP_HOST_PAGE_VIEW,order:-10})]}}const canvasBlocksPluginName=Au=>`@datalayer/loop-plugin-ui-${Au}`;function uiPluginBlocks(Au){return{name:canvasBlocksPluginName(Au.id),displayName:Au.name,description:`The blocks of ${Au.name} on the Canvas: ${Au.components.map(lo=>lo.name).join(", ")}.`,octicon:"apps",contributes:Au.components.map(lo=>contribution(LoopCanvasBlock,{id:lo.id,ui:Au.id,component:lo},{id:lo.id}))}}const CANVAS_BLOCK_PLUGINS=listUI().filter(Au=>Au.components.length>0).map(uiPluginBlocks),MANAGER_PLUGIN_NAME="@datalayer/reactor-manager",MANAGER_ACTIONS_SLOT="manager-actions",ManagerPluginSource=defineContributionPoint("manager.pluginSource");function usePluginRows(Au,lo){const $u=useReactorPlatform(),Ru=reactExports.useSyncExternalStore($u.subscribe,()=>$u.getRevision());return reactExports.useMemo(()=>$u.listPlugins().filter(Iu=>!lo.has(Iu)).map(Iu=>{const Pu=$u.getManifest(Iu);return{name:Iu,displayName:Pu?.displayName??Iu,description:Pu?.description,emoji:Pu?.emoji,version:Pu?.version,enabled:$u.isEnabled(Iu),disabledBy:Pu?.disabledBy,changeable:!Au.has(Iu),details:[{label:"Delivered by",values:Pu?.extension?[Pu.extension]:[]},{label:"Contributes to",values:Pu?.contributesTo??[]},{label:"Offers contribution points",values:Pu?.contributionPoints??[]},{label:"Requires backend plugins",values:Pu?.requiredBackendPlugins??[]},{label:"Uses if available",values:Pu?.optionalBackendPlugins??[]},{label:"Activates on",values:Pu?.activationEvents??[]}]}}),[$u,Ru,Au,lo])}function pluginMatches(Au,lo){if(!lo)return!0;const $u=lo.trim().toLowerCase();return[Au.name,Au.displayName,Au.description??""].join(" ").toLowerCase().includes($u)}const PluginHoverContext=reactExports.createContext(null);function usePluginHoverControl(){const[Au,lo]=reactExports.useState(null),$u=reactExports.useRef(void 0);return reactExports.useEffect(()=>()=>clearTimeout($u.current),[]),reactExports.useMemo(()=>({openName:Au,show:Ru=>{clearTimeout($u.current),lo(Ru)},hide:()=>{clearTimeout($u.current),$u.current=setTimeout(()=>lo(null),200)}}),[Au])}function useHoverControl(){const Au=reactExports.useContext(PluginHoverContext),lo=usePluginHoverControl();return Au??lo}function PluginDetails({row:Au}){const lo=(Au.details??[]).filter($u=>$u.values.length>0);return jsxRuntimeExports.jsxs(Box,{sx:{p:3,maxWidth:360,display:"grid",gap:2},children:[jsxRuntimeExports.jsxs(Box,{sx:{display:"flex",alignItems:"center",gap:2},children:[Au.emoji?jsxRuntimeExports.jsx(Text$3,{"aria-hidden":!0,children:Au.emoji}):null,jsxRuntimeExports.jsx(Text$3,{sx:{fontWeight:"semibold"},children:Au.displayName}),Au.version?jsxRuntimeExports.jsxs(Text$3,{sx:{fontSize:0,color:"fg.muted"},children:["v",Au.version]}):null]}),jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:"fg.muted",wordBreak:"break-all"},children:Au.name}),Au.description?jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0},children:Au.description}):null,lo.map($u=>jsxRuntimeExports.jsxs(Box,{sx:{display:"grid",gap:1},children:[jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,fontWeight:"semibold"},children:$u.label}),$u.values.map(Ru=>jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:"fg.muted",wordBreak:"break-all"},children:Ru},Ru))]},$u.label)),Au.disabledBy==="dependency"?jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:"attention.fg"},children:"Off because something it depends on is off. It comes back when that does."}):null,Au.changeable?null:jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:"attention.fg"},children:"This one cannot be switched off."})]})}const OVERLAY_TAKES_NO_FOCUS={preventFocusOnOpen:!0,sx:{pointerEvents:"none"},returnFocusRef:{current:null}};function PluginRowView({row:Au,size:lo,onToggle:$u}){const Ru=`plugin-name-${Au.name.replace(/[^a-zA-Z0-9]+/g,"-")}`,Iu=useHoverControl(),Pu=Iu.openName===Au.name,Ou=()=>Iu.show(Au.name),Mu=()=>Iu.hide();return jsxRuntimeExports.jsx(AnchoredOverlay,{open:Pu,onOpen:Ou,onClose:Mu,focusZoneSettings:{disabled:!0},focusTrapSettings:{disabled:!0},overlayProps:OVERLAY_TAKES_NO_FOCUS,side:"outside-right",renderAnchor:Du=>jsxRuntimeExports.jsxs(Box,{...Du,onMouseEnter:Ou,onMouseLeave:Mu,onFocus:Ou,onBlur:Mu,sx:{display:"flex",alignItems:"flex-start",gap:2,py:2,borderBottom:"1px solid",borderColor:"border.muted"},children:[jsxRuntimeExports.jsxs(Box,{sx:{minWidth:0,flex:1},children:[jsxRuntimeExports.jsxs(Box,{sx:{display:"flex",alignItems:"center",gap:1},children:[Au.emoji?jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:1},"aria-hidden":!0,children:Au.emoji}):null,jsxRuntimeExports.jsx(Text$3,{id:Ru,sx:{fontSize:1,fontWeight:"semibold",minWidth:0},children:jsxRuntimeExports.jsx(Truncate,{title:Au.name,maxWidth:"100%",inline:!0,children:Au.displayName})})]}),Au.description?jsxRuntimeExports.jsx(Text$3,{sx:{display:"block",fontSize:0,color:"fg.muted"},children:jsxRuntimeExports.jsx(Truncate,{title:Au.description,maxWidth:"100%",inline:!0,children:Au.description})}):null]}),jsxRuntimeExports.jsx(ToggleSwitch,{size:lo,checked:Au.enabled,disabled:!Au.changeable||Au.disabledBy==="dependency","aria-labelledby":Ru,onClick:()=>{Au.changeable&&Au.disabledBy!=="dependency"&&$u(Au.name,!Au.enabled)}})]}),children:jsxRuntimeExports.jsx(PluginDetails,{row:Au})})}function PluginList({plugins:Au,query:lo="",switchSize:$u="small",onToggle:Ru,emptyMessage:Iu}){const Pu=reactExports.useMemo(()=>Au.filter(Ou=>pluginMatches(Ou,lo)),[Au,lo]);return Pu.length===0?jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:"fg.muted"},children:Iu??`No plugin matches “${lo}”.`}):jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:Pu.map(Ou=>jsxRuntimeExports.jsx(PluginRowView,{row:Ou,size:$u,onToggle:Ru},Ou.name))})}function PluginsManagerView({protectedPlugins:Au,hiddenPlugins:lo,switchSize:$u,width:Ru,...Iu}){const Pu=useReactorPlatform(),Ou=Pu.getConfig(MANAGER_PLUGIN_NAME)??{},Mu=reactExports.useMemo(()=>new Set(Au??Ou.protected??[MANAGER_PLUGIN_NAME]),[Au,Ou.protected]),Du=reactExports.useMemo(()=>new Set(lo??Ou.hidden??[]),[lo,Ou.hidden]),Lu=usePluginHoverControl(),Bu=usePluginRows(Mu,Du),[ju,Fu]=reactExports.useState(""),zu=$u??Ou.switchSize??"small",Uu=useContributions(ManagerPluginSource),Hu=reactExports.useMemo(()=>[...Uu].map(Vu=>Vu.value).sort((Vu,Gu)=>(Vu.order??100)-(Gu.order??100)),[Uu]);return jsxRuntimeExports.jsx(PluginHoverContext.Provider,{value:Lu,children:jsxRuntimeExports.jsxs(Box,{sx:{display:"flex",flexDirection:"column",gap:3,width:Ru??Ou.width??"100%",maxWidth:"100%",minWidth:0},children:[jsxRuntimeExports.jsx(ReactorSlot,{slot:MANAGER_ACTIONS_SLOT,props:Iu}),jsxRuntimeExports.jsxs(Box,{children:[jsxRuntimeExports.jsx(Text$3,{as:"h2",sx:{fontSize:1,fontWeight:"semibold",display:"block",mb:2},children:Ou.title??"Plugins"}),jsxRuntimeExports.jsx(TextInput$1,{leadingVisual:SearchIcon,value:ju,onChange:Vu=>Fu(Vu.target.value),"aria-label":"Filter plugins",placeholder:"Filter…",block:!0,size:"small"})]}),jsxRuntimeExports.jsx(Box,{children:jsxRuntimeExports.jsx(PluginList,{plugins:Bu,query:ju,switchSize:zu,onToggle:(Vu,Gu)=>Gu?Pu.enable(Vu):Pu.disable(Vu)})}),Hu.map(Vu=>jsxRuntimeExports.jsxs(Box,{children:[jsxRuntimeExports.jsx(Text$3,{as:"h3",sx:{fontSize:1,fontWeight:"semibold",display:"block",mb:2},children:Vu.title}),jsxRuntimeExports.jsx(Vu.Component,{query:ju,switchSize:zu})]},Vu.title))]})})}const PLUGINS_PANEL_PLUGIN_NAME="@datalayer/loop-plugin-plugins-panel",SIDEBAR_WIDTH=420,REACTOR_GRAPH_PLUGIN_NAME="@datalayer/reactor-graph",PluginsPanelPlugin={name:PLUGINS_PANEL_PLUGIN_NAME,displayName:"Plugins panel",description:"Switch plugins on and off while the workspace runs.",octicon:"plug",emoji:"🔌",build:()=>({components:[{id:"plugins-panel",slot:LoopSlots.sidebar,order:900,Component:({workspace:Au})=>jsxRuntimeExports.jsx(PluginsManagerView,{protectedPlugins:[PLUGINS_PANEL_PLUGIN_NAME],hiddenPlugins:[REACTOR_GRAPH_PLUGIN_NAME],width:SIDEBAR_WIDTH,workspace:Au})}]})};function ViewSwitcher({views:Au,workspace:lo,compact:$u=!1}){return Au.length<2?null:jsxRuntimeExports.jsx(Box,{role:"tablist","aria-label":"Workspace views",display:"inline-flex",alignItems:"center",bg:"neutral.muted",borderRadius:"6px",p:"2px",gap:"1px",children:Au.map(Ru=>{const Iu=Ru.value,Pu=canOpenView(Iu,lo),Ou=lo.activeViewType===Iu.viewType,Mu=Iu.icon,Du=Pu?Iu.title:`${Iu.title} — ${Iu.unavailableReason?.(lo)??"unavailable"}`;return jsxRuntimeExports.jsx(Tooltip,{text:Du,direction:"n",children:jsxRuntimeExports.jsxs(Box,{as:"button",role:"tab","aria-selected":Ou,"aria-disabled":!Pu,onClick:()=>Pu&&lo.setActiveViewType(Iu.viewType),display:"inline-flex",alignItems:"center",gap:1,border:"none",borderRadius:"5px",px:2,py:"4px",fontSize:0,cursor:Pu?"pointer":"not-allowed",opacity:Pu?1:.5,bg:Ou?"canvas.default":"transparent",color:Ou?"fg.default":"fg.muted",boxShadow:Ou?"shadow.small":"none",children:[Mu?jsxRuntimeExports.jsx(Mu,{size:14}):null,$u&&Mu?null:Iu.title]})},Iu.viewType)})})}const paneOpenKeyframes=Au=>Au==="left"?"loopPaneOpenLeft":"loopPaneOpenRight",paneOpenAnimation=Au=>`${paneOpenKeyframes(Au)} var(--theme-motion-pane, 0ms) var(--theme-motion-easing, ease) both`;function paneOpening(Au){const lo="12px";return{animation:paneOpenAnimation(Au),[`@keyframes ${paneOpenKeyframes(Au)}`]:{from:{opacity:0,transform:`translateX(${lo})`},to:{opacity:1,transform:"none"}},"@media (prefers-reduced-motion: reduce)":{animation:"none"}}}function railItemsOf(Au){return Au.map(lo=>({id:lo.id,label:lo.rail?.label??lo.id,icon:lo.rail?.icon??SidebarExpandIcon}))}function railChoiceAfter(Au,lo){return Au===lo?null:lo}const RAIL_WIDTH=48;function SidebarRail({components:Au,props:lo,width:$u}){const Ru=railItemsOf(Au),[Iu,Pu]=reactExports.useState(Ru[0]?.id??null),Ou=Ru.some(Mu=>Mu.id===Iu)?Iu:null;return jsxRuntimeExports.jsxs(Box,{as:"aside","data-loop-rail-sidebar":"",flex:"0 0 auto",display:"flex",minHeight:0,children:[jsxRuntimeExports.jsx(Box,{"data-loop-rail-panel":Ou??void 0,display:Ou?"block":"none",width:`${$u}px`,minWidth:0,borderLeft:"var(--theme-hairline, 1px) solid",borderColor:"border.default",overflowY:"auto",px:3,py:3,children:Au.map(Mu=>{const{Component:Du}=Mu,Lu=Mu.id===Ou;return jsxRuntimeExports.jsx(Box,{id:`loop-rail-panel-${Mu.id}`,role:"region","aria-label":railItemsOf([Mu])[0].label,hidden:!Lu,sx:Lu?paneOpening("right"):void 0,children:jsxRuntimeExports.jsx(Du,{...lo})},Mu.id)})}),jsxRuntimeExports.jsx(Box,{as:"nav","aria-label":"Panels",width:`${RAIL_WIDTH}px`,flex:`0 0 ${RAIL_WIDTH}px`,display:"flex",flexDirection:"column",alignItems:"center",gap:1,py:2,borderLeft:"var(--theme-hairline, 1px) solid",borderColor:"border.default",children:Ru.map(Mu=>{const Du=Mu.icon,Lu=Mu.id===Ou;return jsxRuntimeExports.jsx(Box,{as:"button",type:"button","data-loop-rail-item":Mu.id,"aria-label":Mu.label,title:Mu.label,"aria-pressed":Lu,"aria-controls":`loop-rail-panel-${Mu.id}`,onClick:()=>Pu(railChoiceAfter(Ou,Mu.id)),width:32,height:32,display:"inline-flex",alignItems:"center",justifyContent:"center",p:0,border:"none",borderRadius:2,cursor:"pointer",color:Lu?"fg.default":"fg.muted",bg:Lu?"neutral.muted":"transparent",hover:{color:"fg.default",bg:"neutral.subtle"},focusVisible:{outline:"2px solid",outlineColor:"var(--focus-outlineColor, #0969da)",outlineOffset:"1px"},children:jsxRuntimeExports.jsx(Du,{size:16})},Mu.id)})})]})}function buildLoopReactor(Au){return buildReactorFromPlugins(Au)}function LoopWorkspace(Au){const{serverUrl:lo,agentId:$u,conversationId:Ru,model:Iu,sandbox:Pu={state:"idle"},extensions:Ou=[],reactor:Mu,manageReactor:Du=!0,initialViewType:Lu,onSend:Bu,layout:ju="page",showViewSelector:Fu=!0,showHeader:zu=!0,chatHeaderActions:Uu,chatViewModes:Hu,headerActions:Vu,headerContainer:Gu,sidebarRail:Wu=!1}=Au,Ku=reactExports.useMemo(()=>Mu??buildLoopReactor(Ou),[Mu]);return useReactor(Ku,{autoStart:Du}),jsxRuntimeExports.jsx(WorkspaceBody,{serverUrl:lo,agentId:$u,conversationId:Ru,model:Iu,initialSandbox:Pu,initialViewType:Lu,onSend:Bu,layout:ju,showViewSelector:Fu,showHeader:zu,chatHeaderActions:Uu,chatViewModes:Hu,headerActions:Vu,headerContainer:Gu,sidebarRail:Wu})}function WorkspaceBody({serverUrl:Au,agentId:lo,conversationId:$u,model:Ru,initialSandbox:Iu,initialViewType:Pu,onSend:Ou,layout:Mu="page",showViewSelector:Du=!0,showHeader:Lu=!0,chatHeaderActions:Bu,chatViewModes:ju,headerActions:Fu,headerContainer:zu,sidebarRail:Uu=!1}){const[Hu,Vu]=reactExports.useState(lo),Gu=reactExports.useRef(loopSurfaceId($u??`session-${Date.now().toString(36)}`));reactExports.useEffect(()=>{Vu(lo)},[lo]);const[Wu,Ku]=reactExports.useState(Pu??""),[Ju,Yu]=reactExports.useState(Iu),[Xu]=reactExports.useState(createPromptChannel),[ed,td]=reactExports.useState({}),nd=reactExports.useCallback(cd=>{td(cd??{})},[]),od=useContributions(LoopViewType),sd=useContributions(LoopCommand),ad=useSlotComponents(LoopSlots.sidebar),pd=reactExports.useRef(sd),gd=reactExports.useRef(null),_d=Mu==="panel",yd=reactExports.useCallback(async cd=>{const dd=parseCommand(cd);if(!dd)return Ou?.(cd,gd.current),Xu.submit(cd)||Ou?{handled:!0}:{handled:!1,reason:"Nothing is listening for prompts in this view yet."};const md=pd.current.find(hd=>hd.value.name===dd.name||(hd.value.aliases??[]).includes(dd.name));if(!md)return{handled:!1,command:dd.name,reason:`Unknown command: /${dd.name}. Type /help to see what there is.`};const ld=await md.value.run({workspace:gd.current,argv:dd.argv});return ld?.prompt&&(Ou?.(ld.prompt,gd.current),Xu.submit(ld.prompt)),{handled:!0,command:dd.name,result:ld??void 0}},[Ou,Xu]),bd=reactExports.useMemo(()=>({serverUrl:Au,agentId:Hu,surfaceId:Gu.current,setAgentId:Vu,conversationId:$u,model:Ru,sandbox:Ju,setSandbox:Yu,activeViewType:Wu,setActiveViewType:Ku,prompts:Xu,submit:yd,viewControls:ed,setViewControls:nd,chatHeaderActions:Bu,chatViewModes:ju}),[Au,Hu,$u,Ru,Ju,Wu,Xu,yd,ed,nd,Bu,ju]);gd.current=bd,pd.current=sd;const Sd=reactExports.useMemo(()=>Wu||(od.find(dd=>canOpenView(dd.value,bd))?.value.viewType??""),[Wu,od,bd]);useReactorEvent(Sd?onView(Sd):void 0);const Ed=jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[Fu,jsxRuntimeExports.jsx(ReactorSlot,{slot:LoopSlots.header,props:{workspace:bd}}),Du?jsxRuntimeExports.jsx(ViewSwitcher,{views:od,workspace:bd,compact:_d}):null]});return jsxRuntimeExports.jsxs(Box,{"data-loop-workspace":"",display:"flex",flexDirection:"column",height:"100%",minHeight:0,position:"relative",bg:"canvas.default",color:"fg.default",children:[Lu&&zu?reactDomExports.createPortal(jsxRuntimeExports.jsx(Box,{display:"flex",alignItems:"center",flexWrap:"wrap",gap:2,children:Ed}),zu):null,Lu&&zu===void 0?jsxRuntimeExports.jsx(Box,{as:"header",display:"flex",alignItems:"center",justifyContent:_d?"flex-start":"space-between",flexWrap:"wrap",gap:2,px:_d?2:3,py:2,borderBottom:"1px solid",borderColor:"border.default",flex:"0 0 auto",children:Ed}):null,jsxRuntimeExports.jsxs(Box,{flex:"1 1 auto",minHeight:0,display:"flex",children:[jsxRuntimeExports.jsx(Box,{flex:"1 1 auto",minWidth:0,minHeight:0,position:"relative",children:jsxRuntimeExports.jsx(ReactorViewHost,{point:LoopViewType,active:Sd,props:{viewType:Sd,workspace:bd},fallback:jsxRuntimeExports.jsx(Centered,{children:"Loading…"}),empty:jsxRuntimeExports.jsx(Centered,{children:"No view is available yet."}),errorFallback:cd=>jsxRuntimeExports.jsxs(Centered,{children:["This view failed to load: ",cd.message]})})}),ad.length>0&&Uu&&!_d?jsxRuntimeExports.jsx(SidebarRail,{components:ad,props:{workspace:bd},width:SIDEBAR_WIDTH}):ad.length>0?jsxRuntimeExports.jsx(Box,{as:"aside",flex:"0 0 auto",width:_d?"100%":`${SIDEBAR_WIDTH}px`,minWidth:0,borderLeft:_d?"none":"1px solid",borderTop:_d?"1px solid":"none",borderColor:"border.default",bg:"canvas.subtle",overflowY:"auto",px:3,py:3,children:jsxRuntimeExports.jsx(ReactorSlot,{slot:LoopSlots.sidebar,props:{workspace:bd}})}):null]}),jsxRuntimeExports.jsxs(Box,{flex:"0 0 auto",children:[jsxRuntimeExports.jsx(ReactorSlot,{slot:LoopSlots.footer,props:{workspace:bd}}),jsxRuntimeExports.jsx(ReactorSlot,{slot:LoopSlots.status,props:{workspace:bd}})]}),jsxRuntimeExports.jsx(ReactorSlot,{slot:LoopSlots.root,props:{workspace:bd}})]})}function Centered({children:Au}){return jsxRuntimeExports.jsx(Box,{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"fg.muted",fontSize:1,px:3,textAlign:"center",children:Au})}function resolveTopOffset(Au){if(typeof Au=="number")return Au;if(!Au||typeof document>"u")return 0;const lo=document.querySelector(Au);return lo?Math.max(0,Math.round(lo.getBoundingClientRect().bottom)):0}function fullScreenNode(Au){return Au?.closest("[data-loop-fullscreen-root]")??Au?.closest("[data-loop-workspace]")??Au}function useWorkspaceFullScreen(Au,lo={}){const{forceOverlay:$u=!1,paintOverlay:Ru=!1,topOffset:Iu=0}=lo,[Pu,Ou]=reactExports.useState(!1),Mu=reactExports.useRef(!1);reactExports.useEffect(()=>{const ju=()=>{if(!Mu.current)return;const Fu=!!document.fullscreenElement&&!!Au.current&&document.fullscreenElement.contains(Au.current);Ou(Fu),Fu||(Mu.current=!1)};return document.addEventListener("fullscreenchange",ju),()=>document.removeEventListener("fullscreenchange",ju)},[Au]);const Du=reactExports.useCallback(()=>{const ju=fullScreenNode(Au.current);if(Pu){Mu.current&&document.fullscreenElement?document.exitFullscreen():Ou(!1);return}if($u||Ru||!ju?.requestFullscreen){Ou(!0);return}Mu.current=!0,ju.requestFullscreen().then(()=>Ou(!0),()=>{Mu.current=!1,Ou(!0)})},[Au,Pu,$u,Ru]),[Lu,Bu]=reactExports.useState(0);return reactExports.useEffect(()=>{if(!Pu||Mu.current){Bu(0);return}const ju=()=>Bu(resolveTopOffset(Iu));return ju(),window.addEventListener("resize",ju),()=>window.removeEventListener("resize",ju)},[Pu,Iu]),reactExports.useEffect(()=>{if(!Ru||!Pu||Mu.current)return;const ju=fullScreenNode(Au.current);if(!ju)return;const Fu=ju.getAttribute("style");return ju.style.position="fixed",ju.style.top=`${Lu}px`,ju.style.right="0",ju.style.bottom="0",ju.style.left="0",ju.style.height="auto",ju.style.zIndex="1000",()=>{Fu===null?ju.removeAttribute("style"):ju.setAttribute("style",Fu)}},[Ru,Pu,Au,Lu]),reactExports.useEffect(()=>{if(!Pu||Mu.current)return;const ju=Fu=>{Fu.key==="Escape"&&!Fu.defaultPrevented&&Ou(!1)};return window.addEventListener("keydown",ju),()=>window.removeEventListener("keydown",ju)},[Pu]),{fullScreen:Pu,usingApi:Mu,toggle:Du,topOffsetPx:Lu}}function messageText(Au){const lo=Au.content;return typeof lo=="string"?lo:lo.map($u=>typeof $u=="string"?$u:$u.text??"").join("")}const isToolCall=Au=>Au.type==="tool-call";function conversationOf(Au){const lo=[];for(const $u of Au){if(isToolCall($u)){lo.push({role:"tool",name:$u.toolName,args:$u.args??{},...$u.result===void 0?{}:{result:$u.result}});continue}if($u.role!=="user"&&$u.role!=="assistant")continue;const Ru=messageText($u);Ru.trim()&&lo.push({role:$u.role,text:Ru})}return lo}const sameConversation=(Au,lo)=>Au.length===lo.length&&Au.every(($u,Ru)=>JSON.stringify($u)===JSON.stringify(lo[Ru])),IDLE={id:0,status:"idle"};function createTurnFeed(){const Au=signal$2(IDLE),lo=signal$2([]),$u=signal$2("idle");return{turn:Au,conversation:lo,presence:$u,setPresence:Ru=>{$u.value!==Ru&&($u.value=Ru)},items:Ru=>{const Iu=conversationOf(Ru);sameConversation(lo.value,Iu)||(lo.value=Iu)},begin:(Ru,Iu)=>{Au.value={id:Au.value.id+1,user:Ru,...Iu?{thread:Iu}:{},status:"thinking",usage:Au.value.usage}},assistant:Ru=>{const Iu=Au.value;Iu.status==="idle"||Iu.assistant===Ru||(Au.value={...Iu,assistant:Ru,status:Iu.status==="done"||Iu.status==="error"?Iu.status:Ru?"streaming":Iu.status})},usage:Ru=>{const Iu=Au.value;Iu.usage!==Ru&&(Au.value={...Iu,usage:Ru})},activity:Ru=>{const Iu=Au.value;Iu.status==="idle"||Iu.activity===Ru||(Au.value={...Iu,activity:Ru})},end:(Ru="done")=>{const Iu=Au.value;Iu.status!=="idle"&&(Au.value={...Iu,status:Ru,activity:void 0})}}}const TURN_WRITERS=Symbol.for("loop.chat.turn.writers");function feedWriters(Au){return{[TURN_WRITERS]:Au}}function turnWritersOf(Au){return Au?.[TURN_WRITERS]}function agentAction(Au,lo){const{prompt:$u,...Ru}=lo;return{...Ru,type:"button",group:"agent",onClick:()=>Au.workspace.prompts.submit($u)}}const CHAT_PLUGIN_NAME="@datalayer/loop-plugin-chat",ChatPlugin={name:CHAT_PLUGIN_NAME,config:{placeholder:"",defaultSurface:"notebook",showSurfaceSelector:!0,hideHeader:!1,headerButtons:{newChat:!1,clear:!1},hidePrompt:!1,promptPlacement:"bottom",autoFocusPrompt:!0,suggestionLabels:!0,fullScreenTopOffset:0},displayName:"Chat",description:"The conversation, the prompt, and the point editors plug into.",octicon:"comment-discussion",emoji:"💬",contributionPoints:[LoopAgentGate,LoopFrontendTool,LoopChatComposer,LoopChatHeader,LoopChatSuggestion,LoopChatExtras,LoopChatTurn],build:Au=>{const lo=createTurnFeed();return Au.contribute(LoopChatTurn,{id:"chat-turn",turn:lo.turn,conversation:lo.conversation,presence:lo.presence,...feedWriters(lo)},{id:"chat-turn"}),{}},contributes:[contribution(LoopViewType,{viewType:"chat",title:"Chat",icon:CommentDiscussionIcon,order:0,load:()=>__vitePreload(()=>import("./chunks/ChatView-kCmBbnDa.js"),[],import.meta.url)},{id:"chat",order:0}),contribution(LoopCommand,{name:"chat",description:"Show the conversation",group:"Session",keybinding:"Mod+Alt+K",run:async({workspace:Au})=>{Au.setActiveViewType("chat")}},{id:"chat"}),contribution(LoopNotebookToolbarItem,{items:Au=>[agentAction(Au,{key:"loop-compact",ariaLabel:"Compact this notebook",title:"Ask @NotebookCompactor to shorten it without changing results",icon:FoldIcon,order:200,prompt:"@NotebookCompactor compact this notebook without changing what it computes."}),agentAction(Au,{key:"loop-reproduce",ariaLabel:"Check reproducibility",title:"Ask @NotebookReproducer to run it on a fresh sandbox",icon:SyncIcon,order:201,prompt:"@NotebookReproducer run this notebook top to bottom on a fresh sandbox and report what does not reproduce."})]},{id:"agent-actions",order:200}),contribution(LoopDocumentToolbarItem,{items:Au=>[agentAction(Au,{key:"loop-summarise",ariaLabel:"Summarise this document",title:"Ask the agent for a summary of what this document says",icon:SparkleFillIcon,order:200,prompt:"Summarise this document in a short paragraph."})]},{id:"agent-actions",order:200})]};function WorkspaceFullScreenAction(){const Au=reactExports.useRef(null),$u=useReactorPlatform().getConfig(CHAT_PLUGIN_NAME)?.fullScreenTopOffset??0,{fullScreen:Ru,toggle:Iu}=useWorkspaceFullScreen(Au,{paintOverlay:!!$u,topOffset:$u});return jsxRuntimeExports.jsx(IconButton,{ref:Au,icon:Ru?ScreenNormalIcon:ScreenFullIcon,"aria-label":Ru?"Exit full screen":"Enter full screen",variant:"invisible",size:"small",sx:{order:2},onClick:Iu})}const THEME_PLUGIN_NAME="@datalayer/primer-theme",TOGGLE_COLOR_MODE_COMMAND="theme.toggleColorMode",ThemePlugin={name:THEME_PLUGIN_NAME,displayName:"Theme",description:"Keeps Primer portals in the application’s color mode, and toggles it.",octicon:"sun",emoji:"🌗",commands:[{id:TOGGLE_COLOR_MODE_COMMAND,name:"Toggle the color mode",description:"Switch between light and dark",emoji:"🌗",category:"Appearance",keybinding:"Mod+Alt+C",execute:()=>{const Au=useThemeStore.getState(),lo=Au.colorMode==="auto"?typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light":Au.colorMode;Au.setColorMode(lo==="dark"?"light":"dark")}}],register:()=>{if(typeof document>"u")return;setupPrimerPortals(useThemeStore.getState().colorMode);const Au=useThemeStore.subscribe((Ru,Iu)=>{Ru.colorMode!==Iu.colorMode&&setupPrimerPortals(Ru.colorMode)}),lo=window.matchMedia("(prefers-color-scheme: dark)"),$u=()=>{useThemeStore.getState().colorMode==="auto"&&setupPrimerPortals("auto")};return lo.addEventListener("change",$u),()=>{Au(),lo.removeEventListener("change",$u)}}},pageLayoutPanelOpen=signal$2(!1),pageLayoutSheet=signal$2("page"),pageLayoutActivity=signal$2(void 0);function openPagePanel(){pageLayoutPanelOpen.value=!0}const PAGE_SHEET_WIDTH=920,PAGE_PANEL_WIDTH=400,PAGE_SIZE_FORMATS={letter:{width:816,height:1056},a4:{width:794,height:1123}};function resolvePageSize(Au,lo=PAGE_SHEET_WIDTH){const $u=Au?.format&&Au.format!=="free"?PAGE_SIZE_FORMATS[Au.format]:void 0;return{width:Au?.width??$u?.width??lo,height:Au?.height??$u?.height}}const CANVAS_PX=[2,3,4];function ActivityLine({label:Au}){return jsxRuntimeExports.jsxs(Box$1,{"data-page-activity":"",role:"status",sx:{position:"sticky",top:0,zIndex:2,alignSelf:"flex-start",display:"inline-flex",alignItems:"center",gap:2,px:2,py:"4px",borderRadius:"999px",border:"1px solid",borderColor:"accent.muted",bg:"accent.subtle",color:"accent.fg",fontSize:0,fontWeight:"semibold",whiteSpace:"nowrap",boxShadow:"0 4px 12px -6px rgba(0,0,0,0.3)"},children:[jsxRuntimeExports.jsx(Box$1,{as:"span","aria-hidden":"true",sx:{width:7,height:7,borderRadius:"50%",bg:"accent.fg",animation:"page-activity-dot 1.1s ease-in-out infinite","@keyframes page-activity-dot":{"0%, 100%":{opacity:1},"50%":{opacity:.3}}}}),jsxRuntimeExports.jsx(Text$3,{children:Au})]})}function panelOpening(Au){const lo=Au==="left"?"pagePanelOpenLeft":"pagePanelOpenRight";return{animation:`${lo} var(--theme-motion-pane, 0ms) var(--theme-motion-easing, ease) both`,[`@keyframes ${lo}`]:{from:{opacity:0,transform:`translateX(${Au==="left"?"-12px":"12px"})`},to:{opacity:1,transform:"none"}},"@media (prefers-reduced-motion: reduce)":{animation:"none"}}}function PageLayout({page:Au,hasPage:lo=Au!=null,panel:$u,band:Ru,chips:Iu,picker:Pu,transient:Ou,activity:Mu,bandMode:Du="docked",panelMode:Lu="docked",panelSide:Bu="right",sheetWidth:ju=PAGE_SHEET_WIDTH,pageSize:Fu,panelWidth:zu=PAGE_PANEL_WIDTH}){const Uu=Du==="panel",Hu=Ru!=null,{width:Vu,height:Gu}=resolvePageSize(Fu,ju),Ku=useSignalValue$1(pageLayoutPanelOpen)||Uu&&Hu,Ju=useSignalValue$1(pageLayoutActivity),Yu=Mu??Ju,Xu=lo?"page":"panel";return reactExports.useEffect(()=>{pageLayoutSheet.value=Xu},[Xu]),jsxRuntimeExports.jsxs(Box$1,{"data-page-layout":"",sx:{position:"relative",flex:"1 1 auto",minHeight:0,display:"flex",flexDirection:"column"},children:[Pu,jsxRuntimeExports.jsxs(Box$1,{sx:{flex:"1 1 auto",minHeight:0,display:"flex",bg:"canvas.inset"},children:[jsxRuntimeExports.jsxs(Box$1,{sx:{flex:"1 1 auto",minWidth:0,minHeight:0,display:"flex",flexDirection:"column"},children:[Ru&&Du==="docked"?jsxRuntimeExports.jsx(Box$1,{"data-page-band":"","data-page-prompt-dock":"",sx:{flex:"0 0 auto",display:"flex",justifyContent:"center",px:CANVAS_PX,bg:"canvas.subtle",borderBottom:"1px solid",borderColor:"border.default"},children:jsxRuntimeExports.jsx(Box$1,{sx:{width:"100%",maxWidth:Vu,minWidth:0},children:Ru})}):null,jsxRuntimeExports.jsxs(Box$1,{"data-page-canvas":"",sx:{flex:"1 1 auto",minWidth:0,minHeight:0,overflowY:lo?"auto":"hidden",overflowX:"hidden",display:"flex",flexDirection:"column",alignItems:"center",pt:3,pb:6,px:CANVAS_PX},children:[Ru&&Iu&&!Uu?jsxRuntimeExports.jsx(Box$1,{sx:{width:"100%",maxWidth:Vu,mb:3,display:"flex",justifyContent:"center","& > *":{justifyContent:"center"}},children:Iu}):null,Yu?jsxRuntimeExports.jsx(Box$1,{sx:{width:"100%",maxWidth:Vu,display:"flex",justifyContent:"flex-end",mb:2},children:jsxRuntimeExports.jsx(ActivityLine,{label:Yu})}):null,jsxRuntimeExports.jsx(Sheet,{"data-page-sheet":"",sx:{width:"100%",maxWidth:Vu,flex:lo?"1 0 auto":"1 1 auto",px:lo?[3,4,"56px"]:[2,3,4],py:lo?[3,4,4]:2,position:"relative",display:"flex",minHeight:lo?Gu??480:0,"& > *":{flex:"1 1 auto",minWidth:0}},children:lo?Au:$u}),lo||!Au?null:jsxRuntimeExports.jsx(Box$1,{"aria-hidden":"true",sx:{position:"absolute",inset:0,visibility:"hidden",pointerEvents:"none",zIndex:-1,display:"flex"},children:Au})]})]}),!lo||!$u?null:jsxRuntimeExports.jsxs(Box$1,{"data-page-panel":Ku?"":void 0,"data-page-panel-mode":Lu,"aria-hidden":Ku?void 0:"true",sx:{minWidth:0,minHeight:0,display:"flex",flexDirection:"column",bg:"canvas.default",borderColor:"border.default",...Ku?Lu==="docked"?{flex:`0 0 ${zu}px`,maxWidth:"45%",order:Bu==="left"?-1:void 0,[Bu==="left"?"borderRight":"borderLeft"]:"1px solid",zIndex:1}:Lu==="overlay"?{position:"absolute",top:0,bottom:0,[Bu]:0,width:zu,maxWidth:"85%",[Bu==="left"?"borderRight":"borderLeft"]:"1px solid",boxShadow:"shadow.large",zIndex:5}:{position:"absolute",[Bu]:16,bottom:16,width:zu,maxWidth:"calc(100% - 32px)",height:"min(70%, 560px)",border:"1px solid",borderRadius:2,boxShadow:"shadow.large",overflow:"hidden",zIndex:5}:{position:"absolute",inset:0,visibility:"hidden",pointerEvents:"none",overflow:"visible"}},children:[jsxRuntimeExports.jsx(Box$1,{sx:{flex:"1 1 auto",minHeight:0,display:"flex",flexDirection:"column","& > *":{flex:"1 1 auto",minHeight:0},...Ku?panelOpening(Bu):null},children:$u}),Hu&&Du!=="docked"?jsxRuntimeExports.jsxs(Box$1,{"data-page-panel-band":Uu?"":void 0,sx:Uu?{flex:"0 0 auto",borderTop:"1px solid",borderColor:"border.default",visibility:"visible",pointerEvents:"auto","& > *":{justifyContent:"center"}}:{position:"absolute",inset:0,visibility:"visible",pointerEvents:"none","& > *":{pointerEvents:"auto"}},children:[Uu?Iu:null,Ru]}):null]})]}),Ou]})}function PagePanelToggle({panelName:Au="panel",icon:lo=SidebarExpandIcon,sx:$u}){const Ru=useSignalValue$1(pageLayoutPanelOpen);return useSignalValue$1(pageLayoutSheet)==="panel"?null:jsxRuntimeExports.jsx(IconButton,{icon:lo,size:"small",variant:Ru?"default":"invisible","aria-label":Ru?`Hide the ${Au}`:`Show the ${Au}`,"aria-pressed":Ru,onClick:()=>{Ru?pageLayoutPanelOpen.value=!1:openPagePanel()},sx:{color:Ru?"accent.fg":"fg.muted",...$u}})}const INPUT_PROMPT_PLUGIN_NAME="@datalayer/loop-plugin-input-prompt",LazyComposerView=reactExports.lazy(()=>__vitePreload(()=>import("./chunks/ComposerView-Wa0dy8ex.js"),[],import.meta.url));function ComposerView(Au){return jsxRuntimeExports.jsx(reactExports.Suspense,{fallback:null,children:jsxRuntimeExports.jsx(LazyComposerView,{...Au})})}const InputPromptPlugin={name:INPUT_PROMPT_PLUGIN_NAME,config:{},displayName:"Input Prompt",description:"The composer under (or over) the conversation.",octicon:"pencil",emoji:"✏️",contributionPoints:[LoopPromptPanel],contributes:[contribution(LoopChatComposer,{id:"input-prompt",Component:ComposerView},{id:"input-prompt"})]},AGENT_ICONS={agent:ForwardRef$2,beaker:BeakerIcon,bell:BellIcon,book:BookIcon,briefcase:BriefcaseIcon,browser:BrowserIcon,bug:BugIcon,clock:ClockIcon,code:CodeIcon,"comment-discussion":CommentDiscussionIcon,cpu:CpuIcon,"credit-card":CreditCardIcon,database:DatabaseIcon,file:FileIcon,checklist:ChecklistIcon,"code-review":CodeReviewIcon,fold:FoldIcon,"git-branch":GitBranchIcon,globe:GlobeIcon,graph:GraphIcon,heart:HeartIcon,"issue-opened":IssueOpenedIcon,lightbulb:LightBulbIcon,"light-bulb":LightBulbIcon,"list-unordered":ListUnorderedIcon,mail:MailIcon,megaphone:MegaphoneIcon,"mortar-board":MortarBoardIcon,note:NoteIcon,organization:OrganizationIcon,package:PackageIcon,pencil:PencilIcon,people:PeopleIcon,play:PlayIcon,pulse:PulseIcon,rss:RssIcon,search:SearchIcon,"share-2":ShareAndroidIcon,shield:ShieldIcon,"shield-check":ShieldCheckIcon,sliders:SlidersIcon,sun:SunIcon,sync:SyncIcon,table:TableIcon,tag:TagIcon,tasklist:TasklistIcon,telescope:TelescopeIcon,tools:ToolsIcon,"trending-up":GraphIcon,rocket:RocketIcon,zap:ZapIcon};function agentIcon(Au){return(Au?AGENT_ICONS[Au]:void 0)??ForwardRef$2}function useOptionalSandboxService(){return useReactorPlatform().getOutput(AGENTS_PLUGIN_NAME)?.sandbox}function useSandboxService(){const Au=useOptionalSandboxService();if(!Au)throw new Error(`The code sandbox plugin (${AGENTS_PLUGIN_NAME}) is not mounted. A view that needs a sandbox must declare it as a dependency.`);return Au}function SandboxStatusBridge({workspace:Au}){const lo=useOptionalSandboxService(),$u=useSignalValue$1(lo?.snapshot??IDLE_SANDBOX_SNAPSHOT_SIGNAL),Ru=useSignalValue$1(lo?.target??IDLE_SANDBOX_TARGET_SIGNAL),{setSandbox:Iu,agentId:Pu}=Au;return reactExports.useEffect(()=>lo?.connect(Pu),[lo,Pu]),reactExports.useEffect(()=>{lo&&Iu({...$u,target:Ru})},[lo,$u,Ru,Iu]),null}const DatalayerAgentBridge=reactExports.lazy(async()=>({default:(await __vitePreload(()=>import("./chunks/DatalayerAgentBridge-D54Z9BZ3.js"),[],import.meta.url)).DatalayerAgentBridge}));function DatalayerAgentMount(){return jsxRuntimeExports.jsx(reactExports.Suspense,{fallback:null,children:jsxRuntimeExports.jsx(DatalayerAgentBridge,{})})}const CREATING_STATUSES=new Set(["creating","starting","launching","connecting","pending","resuming"]),MAX_AGENT_NAME_LENGTH=32,toSandboxStatusUrl=Au=>{const lo=String(Au||"").trim();if(lo)try{const $u=new URL(lo);return $u.pathname=`${$u.pathname.replace(/\/$/,"")}/api`,$u.toString()}catch{const $u=lo.replace(/\/$/,"");return $u.endsWith("/api")?$u:`${$u}/api`}},OVERLAY_WIDTH=360,AgentSummary=({summary:Au,title:lo="Active Agent"})=>{const[$u,Ru]=reactExports.useState(!1),[Iu,Pu]=reactExports.useState(!1),Ou=reactExports.useRef(null),Mu=reactExports.useRef(null),Du=()=>{Mu.current!==null&&(window.clearTimeout(Mu.current),Mu.current=null)},Lu=()=>{Du();const Yu=Ou.current?.getBoundingClientRect();Pu(!!(Yu&&Yu.left+OVERLAY_WIDTH>window.innerWidth)),Ru(!0)},Bu=()=>{Du(),Mu.current=window.setTimeout(()=>{Ru(!1),Mu.current=null},300)};reactExports.useEffect(()=>()=>{Du()},[]);const ju=Au?.baseUrl?(()=>{const Yu=Au.baseUrl.replace(/\/$/,"");return Yu.endsWith("/api/v1")?Yu:`${Yu}/api/v1`})():void 0,Fu=ju?`${ju}/runtime/status`:void 0,zu=toSandboxStatusUrl(Au?.sandboxBaseUrl);if(!Au)return null;const Uu=(Au.status||"").toLowerCase(),Hu=!Au.isReady&&!Au.agentId&&CREATING_STATUSES.has(Uu),Vu=!!Au.error,Gu=!!Au.agentId||Hu,Wu=strip(Au.agentName,MAX_AGENT_NAME_LENGTH),Ku=`${Au.agentName} · ${Au.location}`,Ju=`${Wu} · ${Au.location}`;return jsxRuntimeExports.jsxs(Box,{ref:Ou,position:"relative",onMouseEnter:Lu,onMouseLeave:Bu,children:[jsxRuntimeExports.jsxs(Box,{as:"button",type:"button",title:Ku,px:2,py:"6px",maxWidth:280,minWidth:0,border:"1px solid",borderColor:Vu?"danger.emphasis":"border.default",borderRadius:2,bg:Vu?"danger.subtle":"canvas.default",color:Vu?"danger.fg":"fg.default",fontSize:0,cursor:"default",display:"flex",alignItems:"center",gap:1,children:[Hu&&jsxRuntimeExports.jsx(StyledSpinner,{size:"small",sx:{width:12,height:12}}),Vu&&jsxRuntimeExports.jsx("span",{"aria-hidden":!0,children:"⚠"}),jsxRuntimeExports.jsx(Box,{as:"span",display:"block",minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",children:Ju})]}),$u&&jsxRuntimeExports.jsxs(Box,{position:"absolute",top:"calc(100% + 8px)",width:OVERLAY_WIDTH,p:2,border:"1px solid",borderColor:"border.default",borderRadius:2,bg:"canvas.overlay",boxShadow:"shadow.large",zIndex:120,fontSize:0,color:"fg.default",right:Iu?0:void 0,left:Iu?void 0:0,children:[jsxRuntimeExports.jsx(Box,{mb:1,fontWeight:600,children:lo}),jsxRuntimeExports.jsxs(Box,{color:"fg.muted",children:["Name: ",Au.agentName]}),jsxRuntimeExports.jsxs(Box,{color:"fg.muted",children:["Location: ",Au.location]}),jsxRuntimeExports.jsxs(Box,{color:"fg.muted",children:["Spec: ",Au.specId||"—"]}),jsxRuntimeExports.jsxs(Box,{color:"fg.muted",children:["Harness: ",Au.harness||"—"]}),jsxRuntimeExports.jsxs(Box,{color:"fg.muted",children:["Variant: ",Au.variant||"—"]}),jsxRuntimeExports.jsxs(Box,{color:"fg.muted",children:["Status: ",Hu?"creating":Au.status||"—"]}),jsxRuntimeExports.jsxs(Box,{color:"fg.muted",wordBreak:"break-all",children:["Agent base URL: ",Au.baseUrl||"—"]}),jsxRuntimeExports.jsxs(Box,{color:"fg.muted",wordBreak:"break-all",children:["Code sandbox base URL:"," ",Au.sandboxBaseUrl?jsxRuntimeExports.jsx(Box,{as:"a",href:Au.sandboxBaseUrl,target:"_blank",rel:"noopener noreferrer",color:"accent.fg",textDecoration:"underline",children:Au.sandboxBaseUrl}):"—"]}),jsxRuntimeExports.jsxs(Box,{color:"fg.muted",wordBreak:"break-all",display:"flex",alignItems:"center",gap:1,children:["Agent ID:"," ",Au.agentId?Au.agentId:Hu?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(StyledSpinner,{size:"small",sx:{width:12,height:12}}),"Creating…"]}):"—"]}),jsxRuntimeExports.jsxs(Box,{color:"fg.muted",wordBreak:"break-all",children:["Agent status:"," ",Gu&&Fu?jsxRuntimeExports.jsx(Box,{as:"a",href:Fu,target:"_blank",rel:"noopener noreferrer",color:"accent.fg",textDecoration:"underline",children:Fu}):"n/a"]}),jsxRuntimeExports.jsxs(Box,{color:"fg.muted",wordBreak:"break-all",children:["Code sandbox status:"," ",zu?jsxRuntimeExports.jsx(Box,{as:"a",href:zu,target:"_blank",rel:"noopener noreferrer",color:"accent.fg",textDecoration:"underline",children:zu}):"n/a"]}),Vu&&jsxRuntimeExports.jsxs(Box,{mt:1,p:1,border:"1px solid",borderColor:"danger.muted",borderRadius:2,bg:"danger.subtle",color:"danger.fg",wordBreak:"break-word",children:["Error: ",Au.error]})]})]})},insideJupyterLab=()=>loadJupyterConfig().insideJupyterLab;function collect(Au,lo){const $u=Au?.header?.msg_type,Ru=Au?.content??{};$u==="stream"?(lo.stdout.push(String(Ru.text??"")),lo.outputs.push({output_type:"stream",text:Ru.text})):$u==="execute_result"||$u==="display_data"?lo.outputs.push({output_type:$u,data:Ru.data}):$u==="error"&&(lo.error=`${Ru.ename??"Error"}: ${Ru.evalue??""}`,lo.outputs.push({output_type:"error",ename:Ru.ename,evalue:Ru.evalue,traceback:Ru.traceback}))}function browserSource(){let Au;return{variant:"pyodide",acquire:async()=>{const{createLiteServiceManager:lo,jupyterReactStore:$u,loadJupyterConfig:Ru}=await __vitePreload(async()=>{const{createLiteServiceManager:Pu,jupyterReactStore:Ou,loadJupyterConfig:Mu}=await import("./chunks/index-BN8Bbau-.js").then(Du=>Du.r);return{createLiteServiceManager:Pu,jupyterReactStore:Ou,loadJupyterConfig:Mu}},[],import.meta.url);Au=Au??{baseUrl:libExports$5.PageConfig.getOption("baseUrl"),wsUrl:libExports$5.PageConfig.getOption("wsUrl")},Ru({lite:!0});const Iu=await lo();return $u.getState().setServiceManager(Iu),Iu},release:()=>{Au&&(libExports$5.PageConfig.setOption("baseUrl",Au.baseUrl),libExports$5.PageConfig.setOption("wsUrl",Au.wsUrl),Au=void 0)},owned:!0}}function createBrowserSandboxService(Au=browserSource()){const lo=signal$2(null),$u=signal$2("idle"),Ru=signal$2(null),Iu=computed$1(()=>({state:$u.value,variant:Au.variant,kernelId:lo.value?.kernel_id})),Pu=computed$1(()=>$u.value==="running");let Ou=null,Mu=null,Du=null,Lu=null;async function Bu(){if(Mu)return;$u.value="starting",Ou=await Au.acquire();const ju=await Ou.sessions.startNew({name:"loop",path:"loop.ipynb",type:"notebook",kernel:{name:"python"}});Du=ju.kernel,Mu=ju.kernel,lo.value={variant:Au.variant,sandbox_running:!0,kernel_id:Mu?.id,kernel_name:"python"},$u.value="running"}return{kind:"browser",snapshot:Iu,status:lo,ready:Pu,lastExecution:Ru,serverUrl:"",getServiceManager:()=>Ou,getKernelConnection:()=>Du,report(ju){lo.value=ju},setState(ju){$u.value=ju},connect(){return Lu=Lu??Bu().catch(ju=>{throw $u.value="error",lo.value=null,Lu=null,ju}),()=>{Mu?.shutdown?.(),Mu=null,Du=null,Ou=Au.owned?null:Ou,Au.release?.(),Lu=null,$u.value="idle",lo.value=null}},async execute(ju){const Fu=Date.now();try{if(await(Lu??Bu()),!Mu)throw new Error("The browser kernel did not start");const zu={outputs:[],stdout:[],error:""},Uu=Mu.requestExecute({code:ju});Uu.onIOPub=Vu=>collect(Vu,zu),await Uu.done;const Hu={code:ju,success:!zu.error,stdout:zu.stdout.join(""),error:zu.error||void 0,outputs:zu.outputs,startedAt:Fu,finishedAt:Date.now()};return Ru.value=Hu,Hu}catch(zu){const Uu={code:ju,success:!1,error:zu instanceof Error?zu.message:String(zu),startedAt:Fu,finishedAt:Date.now()};return Ru.value=Uu,Uu}}}}function summarize(Au,lo){if(!Au)return{state:lo};const $u=Au.variant==="jupyter-server"||Au.variant==="datalayer";return{state:!!Au.sandbox_running||$u&&!!Au.jupyter_connected?"running":lo==="running"?"idle":lo,variant:Au.variant,kernelId:Au.kernel_id,jupyterUrl:Au.jupyter_url,jupyterToken:Au.jupyter_token,agentBaseUrl:Au.agent_base_url}}const RECONNECT_BASE_MS=1e3,RECONNECT_MAX_MS=3e4;function createServerSandboxService(Au){const lo=signal$2(null),$u=signal$2("idle"),Ru=signal$2(void 0),Iu=signal$2(null),Pu=computed$1(()=>({...summarize(lo.value,$u.value),errorReason:$u.value==="error"?Ru.value:void 0})),Ou=computed$1(()=>Pu.value.state==="running");return{kind:"server",connect(Mu){if(typeof WebSocket>"u")return()=>{};let Du=null,Lu=null,Bu=0,ju=!1;const Fu=()=>{if(ju)return;const zu=Au.replace(/^http/,"ws"),Uu=Mu?`?agent_id=${encodeURIComponent(Mu)}`:"";Du=new WebSocket(`${zu}/api/v1/configure/sandbox/ws${Uu}`),Du.onopen=()=>{Bu=0},Du.onmessage=Hu=>{try{lo.value=JSON.parse(String(Hu.data))}catch{}},Du.onclose=()=>{if(ju)return;lo.value=null,Bu+=1;const Hu=Math.min(RECONNECT_BASE_MS*2**(Bu-1),RECONNECT_MAX_MS);Lu=setTimeout(Fu,Hu)}};return Fu(),()=>{ju=!0,Lu&&clearTimeout(Lu),Du?.close(),Du=null}},snapshot:Pu,status:lo,ready:Ou,lastExecution:Iu,serverUrl:Au,report(Mu){lo.value=Mu},setState(Mu,Du){$u.value=Mu,Ru.value=Mu==="error"?Du:void 0},async execute(Mu){const Du=Date.now();try{const Lu=await fetch(`${Au}/api/v1/sandbox/execute`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({code:Mu})}),Bu=Lu.ok?await Lu.json():null,ju={code:Mu,success:Lu.ok&&!Bu?.error,stdout:Bu?.stdout,stderr:Bu?.stderr,error:Lu.ok?Bu?.error:`Execution failed: ${Lu.status}`,outputs:Bu?.outputs,startedAt:Du,finishedAt:Date.now()};return Iu.value=ju,ju}catch(Lu){const Bu={code:Mu,success:!1,error:Lu instanceof Error?Lu.message:String(Lu),startedAt:Du,finishedAt:Date.now()};return Iu.value=Bu,Bu}}}}const ANONYMOUS_JUPYTER_URL="https://prod1.datalayer.run/api/jupyter-server",ANONYMOUS_JUPYTER_TOKEN="60c1661cc408f978c309d04157af55c9588ff9557c9380e4fb50785750703da6",SANDBOX_TARGETS=["browser","local","jupyter","datalayer"];function heldTargetReason(Au,lo){if(Au==="local"&&!lo&&!insideJupyterLab())return"Not offered on the web for now: a local agent and the Jupyter server it starts run beside JupyterLab, not in a page."}const TARGET_SPECS={browser:{label:"Browser",hint:"Python in this page (Pyodide), with the agent loop running here too. Only the model is asked over the network.",hasAgent:!0,noAgentReason:""},local:{label:"Local",hint:"A local agent, with the Jupyter server it starts beside itself.",hasAgent:!0,noAgentReason:"",configure:{variant:"jupyter-server",jupyter_url:"",jupyter_token:""}},jupyter:{label:"Jupyter",hint:"A named Jupyter server: the anonymous one on prod1.datalayer.run.",hasAgent:!1,noAgentReason:"No agent on an anonymous Jupyter server",configure:{variant:"jupyter-server",jupyter_url:ANONYMOUS_JUPYTER_URL,jupyter_token:ANONYMOUS_JUPYTER_TOKEN}},datalayer:{label:"Datalayer",hint:"A Datalayer runtime running the agent this workspace asks for.",hasAgent:!0,noAgentReason:""}};function targetHasAgent(Au){return TARGET_SPECS[Au]?.hasAgent??!1}function targetRunsAgentInPage(Au){return Au==="browser"}function createSwitchableSandboxService({serverUrl:Au,initialTarget:lo="local",kernelSource:$u,localAgent:Ru,blueprint:Iu}){const Pu=signal$2(lo),Ou=createServerSandboxService(Au),Mu=createBrowserSandboxService($u??browserSource()),Du=computed$1(()=>Pu.value==="browser"?Mu:Ou);let Lu=null,Bu;const ju=computed$1(()=>Du.value.snapshot.value),Fu=computed$1(()=>Du.value.status.value),zu=computed$1(()=>Du.value.ready.value),Uu=computed$1(()=>Du.value.lastExecution.value);async function Hu(Wu){if(Wu==="local"){const ed=Iu?.()??Ru?.createPayload;ed&&await Vu(ed)}const Ku=TARGET_SPECS[Wu]?.configure;if(!Ku)return;const Ju=TARGET_SPECS[Wu].label;let Yu;try{Yu=await fetch(`${Au}/api/v1/agents/sandbox/configure`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(Ku)})}catch(ed){throw new Error(`${Ju} needs an agent-runtimes server at ${Au}, and nothing answered there. Start one and try again. (${ed instanceof Error?ed.message:String(ed)})`,{cause:ed})}if(!Yu.ok)throw new Error(`The server could not switch to ${Ju} (${Yu.status} ${Yu.statusText}). `+await detail(Yu));const Xu=await fetch(`${Au}/api/v1/agents/sandbox/restart`,{method:"POST"});if(!Xu.ok)throw new Error(`The server could not start ${Ju} (${Xu.status} ${Xu.statusText}). `+await detail(Xu))}function Vu(Wu){return ensureServerAgent(Au,Bu,Wu)}function Gu(){if(Lu?.(),Pu.peek()==="datalayer"){Lu=null,Ou.setState("starting");return}Lu=Du.peek().connect(Bu)}return{get kind(){return Pu.peek()==="browser"?"browser":"server"},target:Pu,snapshot:ju,status:Fu,ready:zu,lastExecution:Uu,serverUrl:Au,getServiceManager:()=>Pu.peek()==="browser"?Mu.getServiceManager():null,getKernelConnection:()=>Pu.peek()==="browser"?Mu.getKernelConnection():null,report(Wu){Du.peek().report(Wu)},setState(Wu,Ku){Du.peek().setState(Wu,Ku)},execute(Wu){return Du.peek().execute(Wu)},connect(Wu){Bu=Wu;const Ku=Pu.peek()==="local"&&Wu?Iu?.()??Ru?.createPayload:void 0;if(!Ku)return Gu(),()=>{Lu?.(),Lu=null};let Ju=!1;return Ou.setState("starting"),Vu(Ku).then(()=>{Ju||Gu()},Yu=>{Ju||(Ou.setState("error"),console.error("[loop] Local agent could not be started:",Yu))}),()=>{Ju=!0,Lu?.(),Lu=null}},async setTarget(Wu){const Ku=Pu.peek();if(Wu===Ku)return;const Ju=heldTargetReason(Wu,Au);if(Ju)throw new Error(Ju);Lu?.(),Lu=null;try{await Hu(Wu)}catch(Yu){throw Gu(),Yu}Pu.value=Wu,Gu()}}}async function ensureServerAgent(Au,lo,$u){const Ru=lo?.trim();if(!Ru)throw new Error("Local needs an agent id before its runtime can start.");let Iu;try{Iu=await fetch(`${Au}/api/v1/agents/${encodeURIComponent(Ru)}`)}catch(Ou){throw new Error(`Local needs an agent-runtimes server at ${Au}, and nothing answered there. Start one and try again. (${Ou instanceof Error?Ou.message:String(Ou)})`,{cause:Ou})}if(Iu.ok){await ensureServerSandbox(Au,Ru);return}if(Iu.status!==404)throw new Error(`The server could not inspect local agent ${Ru} (${Iu.status} ${Iu.statusText}). `+await detail(Iu));const Pu=await fetch(`${Au}/api/v1/agents`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({transport:"ag-ui",sandbox_variant:"jupyter-server",...$u,name:Ru})});if(!Pu.ok&&Pu.status!==409)throw new Error(`The server could not launch local agent ${Ru} (${Pu.status} ${Pu.statusText}). `+await detail(Pu));Pu.status===409&&await ensureServerSandbox(Au,Ru)}async function ensureServerSandbox(Au,lo){const $u=await fetch(`${Au}/api/v1/agents/${encodeURIComponent(lo)}/sandbox/ensure`,{method:"POST"});if(!$u.ok)throw new Error(`The server could not start a sandbox for local agent ${lo} (${$u.status} ${$u.statusText}). `+await detail($u))}async function detail(Au){try{const lo=await Au.json();return typeof lo.detail=="string"?lo.detail:""}catch{return""}}function useOptionalTeamSelection(){return useReactorPlatform().getOutput(AGENTS_PLUGIN_NAME)?.team}const NO_TARGET={value:void 0,peek:()=>{}},NO_MEMBER={value:void 0,peek:()=>{}};function AgentSummaryPanel({workspace:Au}){const lo=useSandboxService(),$u=useSignalValue$1(lo?.target??NO_TARGET),Ru=useOptionalTeamSelection(),Iu=useSignalValue$1(Ru?.active??NO_MEMBER);if(!lo)return null;const Pu=Au.sandbox,Ou=Iu?.specId||Au.agentId,Mu=AGENTSPECS$1[Ou],Du={agentName:Iu?.name||Mu?.name||Au.agentId,location:$u?TARGET_SPECS[$u].label:"—",specId:Ou,harness:Mu?.harness,variant:Pu.variant,status:Pu.state,baseUrl:Pu.agentBaseUrl||Au.serverUrl,sandboxBaseUrl:Pu.jupyterUrl,agentId:Au.agentId,isReady:Pu.state==="running"};return jsxRuntimeExports.jsx(AgentSummary,{summary:Du})}const RING=14,STROKE=2.5,RADIUS=(RING-STROKE)/2,CIRCUMFERENCE=2*Math.PI*RADIUS,DEFAULT_WARN_AT=.25,DEFAULT_DANGER_AT=.1,DEFAULT_PULSE_AT=.05,PULSE_MS=1200;function format(Au){const lo=Math.max(0,Math.ceil(Au/1e3)),$u=Math.floor(lo/60),Ru=lo%60;return`${$u}:${String(Ru).padStart(2,"0")}`}function AnonymousKeyTimer({expiresAt:Au,grantedMs:lo,label:$u="Trial key",warnAt:Ru=DEFAULT_WARN_AT,dangerAt:Iu=DEFAULT_DANGER_AT,pulseAt:Pu=DEFAULT_PULSE_AT,onExpire:Ou}){const[Mu,Du]=reactExports.useState(()=>Date.now()),Lu=reactExports.useRef(lo??Math.max(1,Au-Date.now())),Bu=reactExports.useRef(!1);reactExports.useEffect(()=>{const Hu=window.setInterval(()=>{Du(Vu=>{const Gu=Date.now(),Wu=Ku=>Math.ceil((Au-Ku)/1e3);return Wu(Gu)===Wu(Vu)?Vu:Gu})},250);return()=>window.clearInterval(Hu)},[Au]);const ju=Math.max(0,Au-Mu);reactExports.useEffect(()=>{ju>0||Bu.current||(Bu.current=!0,Ou?.())},[ju,Ou]);const Fu=Math.min(1,Math.max(0,ju/Lu.current)),zu=Fu<=Pu,Uu=Fu<=Iu?"danger.fg":Fu<=Ru?"attention.fg":"fg.muted";return jsxRuntimeExports.jsxs(Box,{display:"inline-flex",alignItems:"center",gap:1,px:2,py:"2px",borderRadius:"999px",border:"1px solid",borderColor:"border.muted",bg:"canvas.subtle",color:Uu,fontVariantNumeric:"tabular-nums",sx:{...zu?{"@keyframes dla-key-pulse":{"0%, 100%":{opacity:1},"50%":{opacity:.45}},animation:`dla-key-pulse ${PULSE_MS}ms ease-in-out infinite`,"@media (prefers-reduced-motion: reduce)":{animation:"none"}}:null},title:`${$u}: this workspace is talking to the agent on a temporary key issued to nobody in particular. When it runs out the chat asks you to sign in. Sign in now for an account of your own.`,children:[jsxRuntimeExports.jsx(Box,{display:"flex",alignItems:"center",color:Uu,children:jsxRuntimeExports.jsx(KeyIcon,{size:12})}),jsxRuntimeExports.jsxs(Box,{as:"svg","aria-hidden":"true",focusable:"false",width:RING,height:RING,viewBox:`0 0 ${RING} ${RING}`,display:"block",flexShrink:0,children:[jsxRuntimeExports.jsx("circle",{cx:RING/2,cy:RING/2,r:RADIUS,fill:"none",stroke:"currentColor",strokeWidth:STROKE,opacity:.2}),jsxRuntimeExports.jsx("circle",{cx:RING/2,cy:RING/2,r:RADIUS,fill:"none",stroke:"currentColor",strokeWidth:STROKE,strokeLinecap:"round",strokeDasharray:CIRCUMFERENCE,strokeDashoffset:CIRCUMFERENCE*(1-Fu),transform:`rotate(-90 ${RING/2} ${RING/2})`,style:{transition:"stroke-dashoffset 0.5s linear"}})]}),jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:Uu,fontWeight:"semibold"},children:format(ju)})]})}function AnonymousKeyHeaderBadge({workspace:Au}){return jsxRuntimeExports.jsx(Box,{order:1,display:"inline-flex",alignItems:"center",children:jsxRuntimeExports.jsx(AnonymousKeyBadge,{workspace:Au})})}function AnonymousKeyBadge({workspace:Au}){const lo=useAnonymousSession(),$u=Au.sandbox.target??"local";return!targetRunsAgentInPage($u)||lo.status==="idle"||lo.status==="expired"?null:lo.expiresAt?jsxRuntimeExports.jsx(AnonymousKeyTimer,{expiresAt:lo.expiresAt,grantedMs:lo.grantedMs,onExpire:()=>useAnonymousSessionStore.getState().expire()}):jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:lo.error?"danger.fg":"fg.muted"},title:lo.error,children:lo.error?"No trial key":"Getting a trial key…"})}function SandboxSelector(Au){const lo=useOptionalSandboxService(),[$u,Ru]=reactExports.useState(!1),[Iu,Pu]=reactExports.useState(null),Ou=useSignalValue$1(lo?.snapshot??IDLE_SANDBOX_SNAPSHOT_SIGNAL),Mu=useSignalValue$1(lo?.status??EMPTY_STATUS),Du=useSignalValue$1(lo?.target??DEFAULT_TARGET),Lu=reactExports.useCallback(async ju=>{if(!(!lo||ju===Du)){Ru(!0),Pu(null);try{await lo.setTarget(ju)}catch(Fu){Pu(Fu instanceof Error?Fu.message:String(Fu))}finally{Ru(!1)}}},[lo,Du]);if(!lo)return null;const Bu=Math.max(0,SANDBOX_TARGETS.indexOf(Du));return jsxRuntimeExports.jsxs(Box,{display:"flex",alignItems:"center",gap:2,minWidth:0,children:[jsxRuntimeExports.jsx(Box,{width:16,flexShrink:0,display:"flex",justifyContent:"center",children:$u?jsxRuntimeExports.jsx(StyledSpinner,{size:"small"}):null}),jsxRuntimeExports.jsx(KernelIndicator,{state:sandboxIndicatorState(Ou.state,Mu?.execution_state,Mu?.is_executing),kernelId:Ou.kernelId??Mu?.kernel_id,kernelName:Mu?.kernel_name,serverUrl:Ou.jupyterUrl??Mu?.jupyter_url,websocketUrl:toWebsocketUrl(Ou.jupyterUrl??Mu?.jupyter_url),environmentName:TARGET_SPECS[Du].label,overlayTitle:`${TARGET_SPECS[Du].label} Kernel`,position:"se",bordered:!1}),jsxRuntimeExports.jsx(SegmentedControl,{"aria-label":"Where code runs",size:"small",style:{listStyle:"none",margin:0,padding:0},sx:{listStyle:"none",m:0,p:0,"& > li":{listStyle:"none"},"& > li::marker":{content:"none"}},children:SANDBOX_TARGETS.map((ju,Fu)=>{const zu=heldTargetReason(ju,lo?.serverUrl??"");return jsxRuntimeExports.jsx(SegmentedControl.Button,{selected:Fu===Bu,"aria-disabled":zu?!0:void 0,"data-sandbox-target":ju,"data-sandbox-target-held":zu?"":void 0,sx:{listStyle:"none",...zu?{color:"fg.subtle",cursor:"not-allowed"}:null},title:zu??TARGET_SPECS[ju].hint,onClick:()=>zu?void 0:void Lu(ju),children:TARGET_SPECS[ju].label},ju)})}),Iu||Ou.errorReason?jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:"danger.fg",lineHeight:1.3,maxWidth:280,minWidth:0},title:Iu??Ou.errorReason,children:Iu??Ou.errorReason}):jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:"fg.muted"},title:TARGET_SPECS[SANDBOX_TARGETS[Bu]].hint,children:Ou.state})]})}function toWebsocketUrl(Au){return Au?.replace(/^http/,"ws")}const EMPTY_STATUS={value:null,peek:()=>null},DEFAULT_TARGET={value:"local",peek:()=>"local"};function MemberIcon({icon:Au}){const lo=agentIcon(Au);return jsxRuntimeExports.jsx(lo,{})}function TeamMemberPicker(){const Au=useOptionalTeamSelection();return!Au||Au.members.length<2?null:jsxRuntimeExports.jsx(TeamMemberMenu,{selection:Au})}function TeamMemberMenu({selection:Au}){const[lo,$u]=reactExports.useState(!1),Ru=useSignalValue$1(Au.selected),Iu=Au.members.find(Pu=>Pu.id===Ru);return jsxRuntimeExports.jsx(AnchoredOverlay,{width:"large",open:lo,onOpen:()=>$u(!0),onClose:()=>$u(!1),renderAnchor:Pu=>jsxRuntimeExports.jsx(IconButton,{...Pu,"aria-labelledby":void 0,icon:ForwardRef$2,"aria-label":Iu?`Talking to ${Iu.name}. Choose another agent.`:"Choose an agent",variant:"invisible",size:"small"}),children:jsxRuntimeExports.jsx(Box,{width:440,maxWidth:"calc(100vw - 16px)",children:jsxRuntimeExports.jsxs(ActionList,{selectionVariant:"single",role:"listbox","aria-label":`Agents in ${Au.team.name}`,children:[jsxRuntimeExports.jsx(ActionList.GroupHeading,{children:Au.team.name}),Au.members.map(Pu=>jsxRuntimeExports.jsxs(ActionList.Item,{selected:Pu.id===Ru,onSelect:()=>{Au.select(Pu.id),$u(!1)},children:[jsxRuntimeExports.jsx(ActionList.LeadingVisual,{children:jsxRuntimeExports.jsx(MemberIcon,{icon:Pu.icon})}),jsxRuntimeExports.jsxs(Box,{as:"span",display:"flex",alignItems:"center",gap:2,children:[Pu.name,Pu.isSupervisor?jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:"fg.muted"},children:"supervisor"}):null]}),Pu.description?jsxRuntimeExports.jsx(ActionList.Description,{variant:"block",sx:{display:"block",whiteSpace:"normal",overflowWrap:"anywhere",minWidth:0},children:Pu.description}):null]},Pu.id))]})})})}function specIdOf(Au){return(Au??"").split(":")[0]??""}function teamMembers(Au){const lo=specIdOf(Au.supervisor?.ref),$u=Iu=>{const Pu=AGENTSPECS$1[Iu];return{description:Pu?.description,emoji:Pu?.emoji,icon:Pu?.icon}},Ru=(Au.agents??[]).map(Iu=>{const Pu=specIdOf(Iu.ref);return{id:Iu.id,name:Iu.name||Pu||Iu.id,specId:Pu,isSupervisor:Pu!==""&&Pu===lo,...$u(Pu)}});return[...Ru.filter(Iu=>Iu.isSupervisor),...Ru.filter(Iu=>!Iu.isSupervisor)]}function createTeamSelection(Au){const lo=TEAM_SPECS[Au];if(!lo)return;const $u=teamMembers(lo);if($u.length===0)return;const Ru=signal$2($u[0].id);return{team:lo,members:$u,selected:Ru,select:Iu=>{$u.some(Pu=>Pu.id===Iu)&&(Ru.value=Iu)},sharing:lo.context?.sharing??"shared",active:computed$1(()=>$u.find(Iu=>Iu.id===Ru.value))}}function subagentsFor(Au,lo){const $u=teamMembers(Au),Ru=$u.find(Du=>Du.id===lo);if(!Ru)return[];const Iu=(Du,Lu,Bu)=>{const ju=AGENTSPECS$1[Lu];if(ju)return{name:Du,description:Bu||ju.description||Du,instructions:ju.systemPrompt,model:ju.model,icon:ju.icon}},Pu=Ru.isSupervisor||Au.delegation?.allowPeerDelegation?$u.filter(Du=>Du.id!==lo).map(Du=>Iu(Du.name,Du.specId,Du.description)):[],Mu=((Au.agents??[]).find(Du=>Du.id===lo)?.subagents??[]).map(Du=>Iu(Du.name,(Du.ref??"").split(":")[0]??"",Du.description));return[...Pu,...Mu].filter(Boolean)}const DEFAULT_DATALAYER_AGENTSPEC="jupyter-tutor",AGENTS_PLUGIN_NAME="@datalayer/loop-plugin-agents",offeredTarget=(Au,lo)=>heldTargetReason(Au,lo)?"browser":Au,AgentsPlugin={name:AGENTS_PLUGIN_NAME,displayName:"Agents",description:"Where the agent and its code run: this page, a local server, or a Datalayer runtime.",octicon:"container",emoji:"📦",config:{serverUrl:"",target:"local"},contributionPoints:[LoopAgentBlueprint],preserveOutput:!0,build({config:Au,reactor:lo}){const $u=Au.showAgentVariants??!0,Ru=Au.teamId?createTeamSelection(Au.teamId):void 0;return{team:Ru,sandbox:createSwitchableSandboxService({serverUrl:Au.serverUrl,initialTarget:offeredTarget(($u||Au.targetFixed?Au.target:"browser")??"local",Au.serverUrl),kernelSource:Au.kernelSource,localAgent:Au.localAgent,blueprint:()=>{const Iu=lo.getContributions(LoopAgentBlueprint)[0]?.value;if(Iu)return{...Iu.specId?{agent_spec_id:Iu.specId}:null,...Iu.createPayload}}}),components:[{slot:LoopSlots.status,id:"sandbox-status",Component:SandboxStatusBridge},{slot:LoopSlots.status,id:"datalayer-agent",Component:DatalayerAgentMount},...Ru&&Au.showTeamPicker!==!1?[{slot:LoopSlots.header,id:"team-member-picker",Component:TeamMemberPicker}]:[],...$u?[{slot:LoopSlots.header,id:"sandbox-selector",Component:SandboxSelector}]:[],...Au.showAgentSummary===!1?[]:[{slot:LoopSlots.header,id:"agent-summary",Component:AgentSummaryPanel}],{slot:LoopSlots.chatHeader,id:"anonymous-key",Component:AnonymousKeyBadge},{slot:LoopSlots.header,id:"anonymous-key-header",Component:AnonymousKeyHeaderBadge}]}},register({contribute:Au,state:lo}){const $u=lo.getOutput()?.sandbox;if($u)return Au(LoopAgentGate,{check:Ru=>{const Iu=Ru.sandbox.target??$u.target.peek();return targetHasAgent(Iu)||TARGET_SPECS[Iu].noAgentReason}},{id:"sandbox-target"})},contributes:[contribution(LoopViewType,{viewType:"sandbox",title:"Sandbox",icon:ServerIcon,order:40,load:()=>__vitePreload(()=>import("./chunks/SandboxView-NqXA2LuS.js"),[],import.meta.url)},{id:"sandbox",order:40}),contribution(LoopCommand,{name:"sandbox",aliases:["code-sandbox"],description:"Show the code sandbox: variant, kernel, Jupyter server",group:"Capabilities",run:async({workspace:Au})=>{Au.setActiveViewType("sandbox")}},{id:"sandbox"})]},PULSE_ANIMATION="loop-subagent-pulse",KEYFRAMES=`@keyframes ${PULSE_ANIMATION} {
|
|
3849
3852
|
0%, 100% { opacity: 0.25; }
|
|
3850
3853
|
50% { opacity: 1; }
|
|
3851
3854
|
}`;function SubagentPulse(){const Au=useAgentRuntimeActiveSubagentToolCallId(),lo=useAgentRuntimeSubagentActivity(Au??void 0),$u=useOptionalReactorPlatform(),Ru=lo[0]?.subagentName??Au??"",Iu=$u?.getOutput(AGENTS_PLUGIN_NAME)?.team?.members.find(Du=>Du.name===Ru),Pu=agentIcon(Iu?.icon);if(!Au)return null;const Mu=lo.some(Du=>Du.transport==="a2a")?`${Ru} is working over A2A…`:`${Ru} is working…`;return jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx("style",{children:KEYFRAMES}),jsxRuntimeExports.jsx(Tooltip,{text:Mu,direction:"n",children:jsxRuntimeExports.jsx(Box,{as:"button",type:"button","aria-label":Mu,"data-subagent-pulse":Ru,display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,p:0,border:0,bg:"transparent",color:"accent.fg",cursor:"default",animation:`${PULSE_ANIMATION} 1.4s ease-in-out infinite`,children:jsxRuntimeExports.jsx(Pu,{size:16})})})]})}const SUBAGENT_ACTIVITY_PLUGIN_NAME="@datalayer/loop-plugin-subagent-activity",SubagentActivityPlugin={name:SUBAGENT_ACTIVITY_PLUGIN_NAME,displayName:"Subagent activity",description:"A delegated agent's icon, pulsing in the prompt's header while it works.",octicon:"people",emoji:"👥",dependencies:[InputPromptPlugin],build:()=>({components:[{id:"subagent-pulse",slot:LoopSlots.inpromptMenu,order:0,Component:SubagentPulse}]})},A2UI_PLUGIN_NAME="@datalayer/loop-plugin-a2ui",A2uiPlugin={name:A2UI_PLUGIN_NAME,displayName:"A2UI surfaces",description:"The last execution, rendered as a surface rather than dumped.",octicon:"browser",emoji:"🖼",dependencies:[AgentsPlugin],contributes:[contribution(LoopViewType,{viewType:"a2ui",title:"Surface",icon:BrowserIcon,order:30,canOpen:Au=>Au.sandbox.state==="running"&&Au.sandbox.variant!=="pyodide",unavailableReason:Au=>Au.sandbox.variant==="pyodide"?"Surfaces are rendered by the server; this sandbox runs in the browser":"Needs a running sandbox",load:()=>__vitePreload(()=>import("./chunks/A2uiView-EmeKVJZp.js"),[],import.meta.url)},{id:"a2ui",order:30}),contribution(LoopCommand,{name:"a2ui",aliases:["surface"],description:"Show the last execution as a rendered surface",group:"Open",keybinding:"Mod+Alt+U",run:async({workspace:Au})=>{Au.setActiveViewType("a2ui")}},{id:"a2ui"})]},NONE_VIEW="none";let state={viewId:NONE_VIEW,options:[],allowNone:!0},announcer=()=>!0;const listeners=new Set;function notify(){for(const Au of[...listeners])Au()}function getViewChoice(){return state}function subscribeViewChoice(Au){return listeners.add(Au),()=>{listeners.delete(Au)}}function setViewAnnouncer(Au){const lo=announcer;return announcer=Au,()=>{announcer=lo}}function setViewOptions(Au,lo=!0){if(lo===state.allowNone&&Au.length===state.options.length&&Au.every((Ru,Iu)=>Ru===state.options[Iu]))return;state={viewId:!lo&&!Au.includes(state.viewId)?Au[0]??NONE_VIEW:state.viewId,options:Au,allowNone:lo},notify()}function chooseView(Au){return state={...state,viewId:Au},notify(),announcer(Au)}function seedViewChoice(Au){state.viewId!==Au&&(state={...state,viewId:Au},notify())}function nextView(){const Au=state.allowNone?[NONE_VIEW,...state.options]:[...state.options];if(Au.length===0)return NONE_VIEW;const lo=Au.indexOf(state.viewId);return Au[(lo+1)%Au.length]}function ViewSelector({point:Au,describe:lo,context:$u,noneLabel:Ru,ariaLabel:Iu,allowNone:Pu=!0}){const Ou=useContributions(Au),Mu=reactExports.useSyncExternalStore(subscribeViewChoice,getViewChoice),[Du,Lu]=reactExports.useState(null),Bu=reactExports.useRef(null),ju=()=>{Bu.current!==null&&(window.clearTimeout(Bu.current),Bu.current=null)},Fu=Vu=>{ju(),Lu(Vu)},zu=()=>{ju(),Bu.current=window.setTimeout(()=>{Lu(null),Bu.current=null},250)};reactExports.useEffect(()=>ju,[]);const Uu=reactExports.useMemo(()=>Ou.map(Vu=>lo(Vu.value,$u)).sort((Vu,Gu)=>(Vu.order??100)-(Gu.order??100)),[Ou,lo,$u]);if(reactExports.useEffect(()=>{setViewOptions(Uu.map(Vu=>Vu.id),Pu)},[Uu,Pu]),Uu.length<(Pu?1:2))return null;const Hu=Uu.find(Vu=>Vu.id===Du&&Vu.details);return jsxRuntimeExports.jsxs(Box$1,{sx:{marginLeft:"auto",display:"flex",alignItems:"center",position:"relative"},children:[jsxRuntimeExports.jsxs(SegmentedControl,{"aria-label":Iu,size:"small",children:[Pu?jsxRuntimeExports.jsx(SegmentedControl.Button,{selected:Mu.viewId===NONE_VIEW,onClick:()=>chooseView(NONE_VIEW),children:Ru}):null,Uu.map(Vu=>jsxRuntimeExports.jsx(SegmentedControl.Button,{selected:Mu.viewId===Vu.id,"aria-disabled":Vu.disabled||void 0,title:Vu.disabled?Vu.disabledReason:Vu.title,leadingIcon:Vu.icon,onMouseEnter:Vu.details?()=>Fu(Vu.id):void 0,onMouseLeave:Vu.details?zu:void 0,onClick:()=>{Vu.disabled||chooseView(Vu.id)},children:Vu.badge?`${Vu.title} (${Vu.badge})`:Vu.title},Vu.id))]}),Hu?jsxRuntimeExports.jsx(Box$1,{onMouseEnter:ju,onMouseLeave:zu,sx:{position:"absolute",top:"calc(100% + 6px)",right:0,minWidth:260,maxWidth:380,maxHeight:320,overflowY:"auto",p:2,bg:"canvas.overlay",border:"1px solid",borderColor:"border.default",borderRadius:2,boxShadow:"shadow.large",zIndex:40,fontSize:0,color:"fg.default",textAlign:"left"},children:Hu.details}):null]})}const SHELL_PLUGIN_NAME$1="@datalayer/reactor-shell",ShellView=defineContributionPoint("reactor.shell.view"),describeAsIs=Au=>Au,ShellPlugin$1={name:SHELL_PLUGIN_NAME$1,displayName:"Shell",description:"A view point, its selector, and the choice as a command.",octicon:"columns",emoji:"📑",config:{point:ShellView,describe:describeAsIs,slot:"header",defaultView:NONE_VIEW,showSelector:!0,allowNone:!0,noneLabel:"None",ariaLabel:"View",announce:()=>!0,commandId:"shell.cycleView",commandName:"Switch the view",commandDescription:"Cycle through the contributed views, and none",keybinding:"Mod+Alt+E"},contributionPoints:[ShellView],register:({config:Au,registerCommand:lo})=>{const $u=setViewAnnouncer(Au.announce),Ru=lo({id:Au.commandId,name:Au.commandName,description:Au.commandDescription,emoji:"📑",category:"Workspace",keybinding:Au.keybinding||void 0,execute:()=>{chooseView(nextView())}});return()=>{$u(),Ru()}},build:({config:Au})=>(seedViewChoice(Au.defaultView||NONE_VIEW),{components:Au.showSelector?[{id:"view-selector",slot:Au.slot,Component:lo=>jsxRuntimeExports.jsx(ViewSelector,{point:Au.point,describe:Au.describe,context:lo,noneLabel:Au.noneLabel,allowNone:Au.allowNone,ariaLabel:Au.ariaLabel})}]:[]})};setViewAnnouncer(requestSurface);const NONE_EDITOR=NONE_VIEW;let mappedFor=null,mapped=null;function getEditorChoice(){const Au=getViewChoice();return(Au!==mappedFor||!mapped)&&(mappedFor=Au,mapped={editorId:Au.viewId,options:Au.options}),mapped}const subscribeEditorChoice=subscribeViewChoice,setEditorOptions=setViewOptions,chooseEditor=chooseView,seedEditorChoice=seedViewChoice,nextEditor=nextView;let jupyterReact=null;function loadJupyterReact(){return jupyterReact?Promise.resolve(jupyterReact):__vitePreload(()=>import("./chunks/index-BN8Bbau-.js").then(Au=>Au.r),[],import.meta.url).then(Au=>(jupyterReact=Au,Au))}const PREVIEW_LENGTH=56;function stripped(Au){const $u=(Au.split(`
|
|
3852
3855
|
`).find(Ru=>Ru.trim())??"").trim();return $u.length>PREVIEW_LENGTH?`${$u.slice(0,PREVIEW_LENGTH-1)}…`:$u||"(empty)"}function PreviewList({title:Au,rows:lo}){return jsxRuntimeExports.jsxs(Box,{children:[jsxRuntimeExports.jsx(Text$3,{sx:{fontWeight:"semibold",display:"block",mb:1},children:Au}),lo.length===0?jsxRuntimeExports.jsx(Text$3,{sx:{color:"fg.muted"},children:"Empty so far."}):lo.map(($u,Ru)=>jsxRuntimeExports.jsxs(Box,{display:"flex",gap:2,py:"2px",alignItems:"baseline",children:[jsxRuntimeExports.jsxs(Text$3,{sx:{color:"fg.muted",flexShrink:0,fontFamily:"mono"},children:[Ru," · ",$u.kind]}),jsxRuntimeExports.jsx(Text$3,{sx:{fontFamily:"mono",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:$u.text})]},Ru))]})}function useOfferedEditors(){return reactExports.useSyncExternalStore(subscribeEditorChoice,()=>getEditorChoice().options)}function useNotebookRows(Au,lo){const[$u,Ru]=reactExports.useState(0);return reactExports.useEffect(()=>{if(!lo)return;let Iu=!1;const Pu=()=>Ru(Du=>Du+1),Ou=[],Mu=jupyterReact!==null;return loadJupyterReact().then(({notebookStore:Du})=>{if(!Iu)try{const Lu=Du.subscribe?.(Pu);Lu&&Ou.push(Lu);const Bu=Du.getState()?.notebooks?.get(Au)?.model;if(Bu){const ju=[Bu.contentChanged,Bu.cells?.changed];for(const Fu of ju)Fu?.connect&&(Fu.connect(Pu),Ou.push(()=>Fu.disconnect(Pu)))}Mu||Pu()}catch{}}),()=>{Iu=!0;for(const Du of Ou)try{Du()}catch{}}},[lo,Au,$u]),reactExports.useMemo(()=>{if(!lo)return null;const Iu=safeModel(Au);if(!Iu)return null;const Pu=[],Ou=Iu.cells;for(let Mu=0;Mu<Ou.length;Mu+=1){const Du=Ou.get(Mu);Pu.push({kind:Du.type,text:stripped(Du.sharedModel.getSource())})}return Pu},[lo,Au,$u])}function safeModel(Au){try{return jupyterReact?.notebookStore.getState()?.notebooks?.get(Au)?.model??null}catch{return null}}function useDocumentRows(Au,lo){const[$u,Ru]=reactExports.useState(null);return reactExports.useEffect(()=>{if(!lo){Ru(null);return}let Iu=!1,Pu,Ou=!1;return __vitePreload(()=>import("./chunks/PrismCss-CcU1ChRk.js").then(Mu=>Mu.a),[],import.meta.url).then(()=>__vitePreload(()=>import("./chunks/index-_nsBY26B.js"),[],import.meta.url)).then(({lexicalStore:Mu})=>{if(Iu)return;const Du=()=>{Ou||(Ou=!0,Mu.getState().readAllBlocks(Au,"brief").then(Lu=>{Ou=!1,!(Iu||!Array.isArray(Lu))&&Ru(Lu.map(Bu=>({kind:Bu.block_type??"block",text:stripped(Bu.preview??"")})))}).catch(()=>{Ou=!1,Iu||Ru(null)}))};Du(),Pu=Mu.subscribe(Du)}).catch(()=>{Iu||Ru(null)}),()=>{Iu=!0,Pu?.()}},[lo,Au]),$u}function useEditorPreviews(Au){const lo=useOfferedEditors(),$u=useNotebookRows(Au,lo.includes("notebook")),Ru=useDocumentRows(Au,lo.includes("document"));return reactExports.useMemo(()=>{const Iu={};return $u&&(Iu.notebook={badge:String($u.length),details:jsxRuntimeExports.jsx(PreviewList,{title:"Cells",rows:$u})}),Ru&&(Iu.document={badge:String(Ru.length),details:jsxRuntimeExports.jsx(PreviewList,{title:"Blocks",rows:Ru})}),Iu},[$u,Ru])}const SHELL_PLUGIN_NAME="@datalayer/loop-plugin-shell";function describeEditor(Au,lo){const $u=Au,Ru=lo?.workspace,Iu=Ru?canOpenView($u,Ru):!0;return{id:$u.surfaceId,title:$u.title,icon:$u.icon,order:$u.order,disabled:!Iu,disabledReason:Iu?void 0:Ru&&$u.unavailableReason?.(Ru)||"Not available right now"}}function EditorSelectorComponent(Au){const lo=Au.workspace,$u=useEditorPreviews(lo?.surfaceId??""),Ru=(Iu,Pu)=>{const Ou=describeEditor(Iu,Pu),Mu=$u[Ou.id];return Mu?{...Ou,badge:Mu.badge,details:Mu.details}:Ou};return jsxRuntimeExports.jsx(ViewSelector,{point:LoopEditorView,describe:Ru,context:Au,noneLabel:"Chat",ariaLabel:"Editor"})}const ShellPlugin={name:SHELL_PLUGIN_NAME,displayName:"Loop shell",description:"The Loop workspace’s extension points, and the editor choice.",octicon:"columns",emoji:"📑",config:{defaultEditor:NONE_EDITOR,showSelector:!0},dependencies:[configurePlugin(ShellPlugin$1,{point:LoopEditorView,describe:describeEditor,showSelector:!1,announce:Au=>requestSurface(Au),commandId:"loop.shell.cycleEditor",commandName:"Switch the editor",commandDescription:"Cycle through the editors beside the conversation, and none",keybinding:""})],contributionPoints:[LoopViewType,LoopEditorView],contributes:[contribution(LoopCommand,{name:"editor",aliases:["editors"],description:"Switch the editor beside the conversation",group:"Open",keybinding:"Mod+Alt+E",args:[{name:"editor",description:"Which editor: none, or a surface id. Omit to cycle.",required:!1,choices:()=>[NONE_EDITOR,...getEditorChoice().options]}],run:async({argv:Au})=>{const lo=Au.trim(),$u=lo===""?nextEditor():lo,Ru=[NONE_EDITOR,...getEditorChoice().options];if(!Ru.includes($u))throw new Error(`No editor called '${$u}'. There is: ${Ru.join(", ")}.`);if(!chooseEditor($u))throw new Error("No chat is on screen to host the editor.")}},{id:"editor"})],build:({config:Au})=>(seedEditorChoice(Au.defaultEditor||NONE_EDITOR),{components:Au.showSelector?[{id:"editor-selector",slot:LoopSlots.header,Component:EditorSelectorComponent}]:[]})};function NewChatAction({workspace:Au}){return Au?jsxRuntimeExports.jsx(IconButton,{icon:PlusIcon,"aria-label":"New conversation",title:"New conversation",variant:"invisible",size:"small",onClick:()=>{Au.submit("/new")}}):null}const PROMPT_PLUGIN_NAME="@datalayer/loop-plugin-prompt",PromptPlugin={name:PROMPT_PLUGIN_NAME,displayName:"Prompt",description:"Prompt commands: focus the composer, start over, and the +.",octicon:"paper-airplane",emoji:"🪶",contributes:[contribution(LoopCommand,{name:"prompt",description:"Focus the prompt",group:"Session",keybinding:"Mod+Alt+P",run:async()=>{if(!focusPrompt())throw new Error("No prompt is on screen to focus.")}},{id:"prompt"}),contribution(LoopCommand,{name:"new",aliases:["reset"],description:"Start the conversation over",group:"Session",keybinding:"Mod+Alt+R",run:async({workspace:Au})=>{const lo=Au.viewControls.newChat;if(!lo)throw new Error("No conversation is on screen to start over.");lo()}},{id:"new"})],build:()=>({components:[{id:"new-chat",slot:LoopSlots.promptAction,Component:NewChatAction}]})};function AgentspecPicker({workspace:Au}){const[lo,$u]=reactExports.useState([]),[Ru,Iu]=reactExports.useState(!1),[Pu,Ou]=reactExports.useState(Au.agentId),Mu=Au.sandbox.target,Du=Au.sandbox.state;reactExports.useEffect(()=>{let Fu=!1;return fetch(`${Au.serverUrl}/api/v1/agents`).then(zu=>zu.ok?zu.json():{agents:[]}).then(zu=>{Fu||$u(zu.agents??[])}).catch(()=>{}),()=>{Fu=!0}},[Au.serverUrl,Mu,Du]),reactExports.useEffect(()=>{Ou(Au.agentId)},[Au.agentId]);const Lu=reactExports.useCallback(async Fu=>{Iu(!0);try{(await fetch(`${Au.serverUrl}/api/v1/loop/sessions/${encodeURIComponent(Au.conversationId||Au.agentId||"session")}/agent`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({agent_id:Fu})})).ok&&(Ou(Fu),Au.setAgentId(Fu))}finally{Iu(!1)}},[Au.agentId,Au.conversationId,Au.serverUrl,Au.setAgentId]),Bu=lo.find(Fu=>Fu.id===Pu),ju=Bu?.name||getAgentspecs(Pu)?.name||Pu||"Agent";return lo.length===0?null:jsxRuntimeExports.jsxs(Box,{display:"flex",alignItems:"center",gap:1,children:[Ru?jsxRuntimeExports.jsx(StyledSpinner,{size:"small"}):null,jsxRuntimeExports.jsxs(ActionMenu,{children:[jsxRuntimeExports.jsxs(ActionMenu.Button,{variant:"invisible",size:"small",children:[Bu?.emoji?`${Bu.emoji} `:"",ju]}),jsxRuntimeExports.jsx(ActionMenu.Overlay,{width:"medium",children:jsxRuntimeExports.jsx(ActionList,{selectionVariant:"single",children:lo.map(Fu=>jsxRuntimeExports.jsxs(ActionList.Item,{selected:Fu.id===Pu,onSelect:()=>{Lu(Fu.id)},children:[Fu.emoji?`${Fu.emoji} `:"",Fu.name||Fu.id,Fu.description?jsxRuntimeExports.jsx(ActionList.Description,{variant:"block",children:Fu.description}):null]},Fu.id))})})]})]})}const AGENTSPECS_PLUGIN_NAME="@datalayer/loop-plugin-agentspecs",AgentspecsPlugin={name:AGENTSPECS_PLUGIN_NAME,displayName:"Agentspecs",description:"Pick the agentspec this session runs.",octicon:"people",emoji:"🤖",build(){return{components:[{slot:LoopSlots.header,id:"agent-picker",Component:AgentspecPicker}]}},contributes:[contribution(LoopCommand,{name:"agents",aliases:["agent"],description:"Switch the agent this session is using",group:"Agents",keybinding:"Mod+Alt+A",args:[{name:"agent-id",description:"Agent to switch to"}],run:async({workspace:Au,argv:lo})=>{const $u=lo.trim();if(!$u)return{content:"Pick an agent from the header, or /agents <id>."};const Ru=await fetch(`${Au.serverUrl}/api/v1/loop/sessions/${encodeURIComponent(Au.conversationId||Au.agentId||"session")}/agent`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({agent_id:$u})});if(!Ru.ok)return{content:`Unknown agent: ${$u}`};const Iu=await Ru.json();return{content:`Now using ${Iu.name??Iu.agent_id}.`}}},{id:"agents"})]},CHAT_HEADER_PLUGIN_NAME="@datalayer/loop-plugin-chat-header",LazyHeaderView=reactExports.lazy(()=>__vitePreload(()=>import("./chunks/HeaderView-DVGhaRai.js"),[],import.meta.url));function HeaderView(Au){return jsxRuntimeExports.jsx(reactExports.Suspense,{fallback:null,children:jsxRuntimeExports.jsx(LazyHeaderView,{...Au})})}const ChatHeaderPlugin={name:CHAT_HEADER_PLUGIN_NAME,displayName:"Chat Header",description:"The conversation’s title bar: agent, kernel, actions.",octicon:"rows",emoji:"🏷️",contributes:[contribution(LoopChatHeader,{id:"chat-header",Component:HeaderView},{id:"chat-header"})]};function readA2uiToolResult(Au,lo){if(!Au)return null;let $u=Au;if(typeof Au=="string")try{$u=JSON.parse(Au)}catch{return null}if(typeof $u!="object"||$u===null||!Array.isArray($u.messages))return null;const Ru=$u,Iu=(Ru.messages??[]).map(Pu=>{const Ou=Pu;return Ou.createSurface&&Ou.createSurface.catalogId!==lo?{...Ou,createSurface:{...Ou.createSurface,catalogId:lo}}:Pu});return{...Ru,messages:Iu}}function isEmptyA2uiValue(Au){return Au==null?!0:typeof Au=="string"?Au.trim()==="":Array.isArray(Au)?Au.length===0:typeof Au=="boolean"?Au===!1:!1}const EMAIL_PATTERN=/^[^\s@]+@[^\s@]+\.[^\s@]+$/;function validateA2uiField(Au,lo){if(isEmptyA2uiValue(lo))return Au.required?`${Au.label} is required.`:null;if(Au.format==="email"&&typeof lo=="string"&&!EMAIL_PATTERN.test(lo.trim()))return`${Au.label} must be a valid email address.`;if(Au.pattern&&typeof lo=="string"){let $u;try{$u=new RegExp(Au.pattern).test(lo.trim())}catch{$u=!0}if(!$u)return`${Au.label} is not in the expected format.`}if(Au.minLength!==void 0&&typeof lo=="string"&&lo.trim().length<Au.minLength)return`${Au.label} must be at least ${Au.minLength} characters.`;if(Au.type==="slider"&&typeof lo=="number"){if(Au.min!==void 0&&lo<Au.min)return`${Au.label} must be at least ${Au.min}.`;if(Au.max!==void 0&&lo>Au.max)return`${Au.label} must be at most ${Au.max}.`}return null}function validateA2uiSubmission(Au,lo){return Au.map($u=>validateA2uiField($u,lo[$u.id])).filter($u=>$u!==null)}const ANSWER_DISPLAY_TYPE="application/vnd.datalayer.loop.answer+json";function answerSurface(Au,lo){return Au.type!==ANSWER_DISPLAY_TYPE?null:readA2uiToolResult(Au.data?.surface,lo)}function answerPress(Au,lo){const $u=lo.name.trim(),Ru=(Au.actions??[]).find(Iu=>Iu.name===$u);return Ru?{message:$u,forwardedProps:{loop:{action:{name:$u,display_id:Au.id,token:Ru.token,payload:{...lo.context}}}}}:{refused:`“${$u||"This button"}” was not offered here.`}}function AnswerShowsView({display:Au,send:lo}){const $u=reactExports.useMemo(()=>answerSurface(Au,SURFACE_CATALOG_ID),[Au]),Ru=useOwnCatalog(),[Iu,Pu]=reactExports.useState(null);if(!$u?.messages||$u.messages.length===0)return jsxRuntimeExports.jsx(Text$3,{sx:{color:"fg.muted"},children:Au.text});const Ou=Mu=>{const Du=answerPress(Au,Mu);if("refused"in Du){Pu(Du.refused);return}Pu(lo(Du.message,Du.forwardedProps)?null:"The chat is not ready to take it yet.")};return jsxRuntimeExports.jsx(InlineSurface,{messages:$u.messages,onAction:Ou,validationError:Iu,catalog:Ru},JSON.stringify(Au))}function SurfaceToolResult({context:Au,send:lo,onRendered:$u,onSubmitted:Ru}){const Iu=reactExports.useMemo(()=>Au.status==="complete"?readA2uiToolResult(Au.result,SURFACE_CATALOG_ID):null,[Au.status,Au.result]),Pu=Iu?.title??"the form",[Ou,Mu]=reactExports.useState(null),Du=useOwnCatalog();reactExports.useEffect(()=>{Iu?.messages&&Iu.messages.length>0&&$u?.({toolCallId:Au.toolCallId,surfaceId:Iu.surfaceId,title:Pu,messages:Iu.messages,result:Iu})},[Iu,Au.toolCallId]);const Lu=reactExports.useCallback(Bu=>{if(Bu.name!=="submit_a2ui_form")return;const ju=Bu.context??{},Fu=validateA2uiSubmission(Iu?.fieldRules??[],ju);if(Fu.length>0){Mu(Fu.join(" "));return}Mu(null),Ru?.({surfaceId:Bu.surfaceId,title:Pu,values:ju}),lo(encodeFormSubmission({title:Pu,surfaceId:Bu.surfaceId,values:ju}))||Mu("The chat is not ready to take the submission yet.")},[Iu,Pu,lo,Ru]);return!Iu?.messages||Iu.messages.length===0?jsxRuntimeExports.jsxs(Box,{border:"1px solid",borderColor:"border.default",borderRadius:2,px:3,py:2,bg:"canvas.default",display:"flex",alignItems:"center",gap:2,children:[jsxRuntimeExports.jsx(StyledSpinner,{size:"small"}),jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:1,color:"fg.muted"},children:"Rendering A2UI surface..."})]}):jsxRuntimeExports.jsxs(Box,{display:"flex",flexDirection:"column",gap:2,children:[jsxRuntimeExports.jsx(Text$3,{sx:{fontWeight:"bold"},children:Pu}),jsxRuntimeExports.jsx(InlineSurface,{messages:Iu.messages,onAction:Lu,validationError:Ou,catalog:Du})]})}const A2UI_SURFACE_PLUGIN_NAME="@datalayer/loop-plugin-a2ui-surface",A2UI_SURFACE_RENDERER="a2ui-surface",A2UI_SURFACE_TYPE="application/vnd.datalayer.a2ui.surface+json";function surfaceToolNames(){const Au=new Set;for(const lo of Object.values(AGENTSPECS))for(const $u of lo.frontendRenderTools??[])$u.renderer===A2UI_SURFACE_RENDERER&&Au.add($u.tool);return Au}let counter=0;function createA2uiSurfacePlugin(Au={}){const lo=`a2ui-surface-${counter+=1}`;let $u;const Ru=(Du,Lu)=>$u?!$u(Du,Lu):!1;function Iu({workspace:Du}){const Lu=Du?.viewControls.send;return reactExports.useEffect(()=>($u=Lu,()=>{$u===Lu&&($u=void 0)}),[Lu]),null}function Pu({context:Du}){return Du?Du.status==="error"?jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:Du.defaultUI}):jsxRuntimeExports.jsx(SurfaceToolResult,{context:Du,send:Ru,onRendered:Au.onRendered,onSubmitted:Au.onSubmitted},Du.toolCallId):null}function Ou({display:Du}){return jsxRuntimeExports.jsx(AnswerShowsView,{display:Du,send:Ru})}return{name:counter===1?A2UI_SURFACE_PLUGIN_NAME:`${A2UI_SURFACE_PLUGIN_NAME}-${lo}`,displayName:"A2UI surfaces",description:"Generated surfaces drawn in the transcript, and submitted back to the agent.",octicon:"browser",emoji:"🪟",contributes:[contribution(Renderers,defineRenderer({type:A2UI_SURFACE_TYPE,component:Pu,rank:Au.onRendered||Au.onSubmitted?1:0}),{id:lo}),contribution(Renderers,defineRenderer({type:ANSWER_DISPLAY_TYPE,component:Ou}),{id:`${lo}:answer`}),...[...surfaceToolNames()].map(Du=>contribution(ToolBindings,{tool:Du,type:A2UI_SURFACE_TYPE},{id:`${lo}:${Du}`}))],build(){return{components:[{slot:LoopSlots.chatHeader,id:lo,Component:Iu}]}}}}const A2uiSurfacePlugin=createA2uiSurfacePlugin(),qrcode=function(Au,lo){let Iu=Au;const Pu=QRErrorCorrectionLevel[lo];let Ou=null,Mu=0,Du=null;const Lu=[],Bu={},ju=function(ed,td){Mu=Iu*4+17,Ou=(function(nd){const od=new Array(nd);for(let sd=0;sd<nd;sd+=1){od[sd]=new Array(nd);for(let ad=0;ad<nd;ad+=1)od[sd][ad]=null}return od})(Mu),Fu(0,0),Fu(Mu-7,0),Fu(0,Mu-7),Hu(),Uu(),Gu(ed,td),Iu>=7&&Vu(ed),Du==null&&(Du=Ju(Iu,Pu,Lu)),Wu(Du,td)},Fu=function(ed,td){for(let nd=-1;nd<=7;nd+=1)if(!(ed+nd<=-1||Mu<=ed+nd))for(let od=-1;od<=7;od+=1)td+od<=-1||Mu<=td+od||(0<=nd&&nd<=6&&(od==0||od==6)||0<=od&&od<=6&&(nd==0||nd==6)||2<=nd&&nd<=4&&2<=od&&od<=4?Ou[ed+nd][td+od]=!0:Ou[ed+nd][td+od]=!1)},zu=function(){let ed=0,td=0;for(let nd=0;nd<8;nd+=1){ju(!0,nd);const od=QRUtil.getLostPoint(Bu);(nd==0||ed>od)&&(ed=od,td=nd)}return td},Uu=function(){for(let ed=8;ed<Mu-8;ed+=1)Ou[ed][6]==null&&(Ou[ed][6]=ed%2==0);for(let ed=8;ed<Mu-8;ed+=1)Ou[6][ed]==null&&(Ou[6][ed]=ed%2==0)},Hu=function(){const ed=QRUtil.getPatternPosition(Iu);for(let td=0;td<ed.length;td+=1)for(let nd=0;nd<ed.length;nd+=1){const od=ed[td],sd=ed[nd];if(Ou[od][sd]==null)for(let ad=-2;ad<=2;ad+=1)for(let pd=-2;pd<=2;pd+=1)ad==-2||ad==2||pd==-2||pd==2||ad==0&&pd==0?Ou[od+ad][sd+pd]=!0:Ou[od+ad][sd+pd]=!1}},Vu=function(ed){const td=QRUtil.getBCHTypeNumber(Iu);for(let nd=0;nd<18;nd+=1){const od=!ed&&(td>>nd&1)==1;Ou[Math.floor(nd/3)][nd%3+Mu-8-3]=od}for(let nd=0;nd<18;nd+=1){const od=!ed&&(td>>nd&1)==1;Ou[nd%3+Mu-8-3][Math.floor(nd/3)]=od}},Gu=function(ed,td){const nd=Pu<<3|td,od=QRUtil.getBCHTypeInfo(nd);for(let sd=0;sd<15;sd+=1){const ad=!ed&&(od>>sd&1)==1;sd<6?Ou[sd][8]=ad:sd<8?Ou[sd+1][8]=ad:Ou[Mu-15+sd][8]=ad}for(let sd=0;sd<15;sd+=1){const ad=!ed&&(od>>sd&1)==1;sd<8?Ou[8][Mu-sd-1]=ad:sd<9?Ou[8][15-sd-1+1]=ad:Ou[8][15-sd-1]=ad}Ou[Mu-8][8]=!ed},Wu=function(ed,td){let nd=-1,od=Mu-1,sd=7,ad=0;const pd=QRUtil.getMaskFunction(td);for(let gd=Mu-1;gd>0;gd-=2)for(gd==6&&(gd-=1);;){for(let _d=0;_d<2;_d+=1)if(Ou[od][gd-_d]==null){let yd=!1;ad<ed.length&&(yd=(ed[ad]>>>sd&1)==1),pd(od,gd-_d)&&(yd=!yd),Ou[od][gd-_d]=yd,sd-=1,sd==-1&&(ad+=1,sd=7)}if(od+=nd,od<0||Mu<=od){od-=nd,nd=-nd;break}}},Ku=function(ed,td){let nd=0,od=0,sd=0;const ad=new Array(td.length),pd=new Array(td.length);for(let bd=0;bd<td.length;bd+=1){const Sd=td[bd].dataCount,Ed=td[bd].totalCount-Sd;od=Math.max(od,Sd),sd=Math.max(sd,Ed),ad[bd]=new Array(Sd);for(let ld=0;ld<ad[bd].length;ld+=1)ad[bd][ld]=255&ed.getBuffer()[ld+nd];nd+=Sd;const cd=QRUtil.getErrorCorrectPolynomial(Ed),md=qrPolynomial(ad[bd],cd.getLength()-1).mod(cd);pd[bd]=new Array(cd.getLength()-1);for(let ld=0;ld<pd[bd].length;ld+=1){const hd=ld+md.getLength()-pd[bd].length;pd[bd][ld]=hd>=0?md.getAt(hd):0}}let gd=0;for(let bd=0;bd<td.length;bd+=1)gd+=td[bd].totalCount;const _d=new Array(gd);let yd=0;for(let bd=0;bd<od;bd+=1)for(let Sd=0;Sd<td.length;Sd+=1)bd<ad[Sd].length&&(_d[yd]=ad[Sd][bd],yd+=1);for(let bd=0;bd<sd;bd+=1)for(let Sd=0;Sd<td.length;Sd+=1)bd<pd[Sd].length&&(_d[yd]=pd[Sd][bd],yd+=1);return _d},Ju=function(ed,td,nd){const od=QRRSBlock.getRSBlocks(ed,td),sd=qrBitBuffer();for(let pd=0;pd<nd.length;pd+=1){const gd=nd[pd];sd.put(gd.getMode(),4),sd.put(gd.getLength(),QRUtil.getLengthInBits(gd.getMode(),ed)),gd.write(sd)}let ad=0;for(let pd=0;pd<od.length;pd+=1)ad+=od[pd].dataCount;if(sd.getLengthInBits()>ad*8)throw"code length overflow. ("+sd.getLengthInBits()+">"+ad*8+")";for(sd.getLengthInBits()+4<=ad*8&&sd.put(0,4);sd.getLengthInBits()%8!=0;)sd.putBit(!1);for(;!(sd.getLengthInBits()>=ad*8||(sd.put(236,8),sd.getLengthInBits()>=ad*8));)sd.put(17,8);return Ku(sd,od)};Bu.addData=function(ed,td){td=td||"Byte";let nd=null;switch(td){case"Numeric":nd=qrNumber(ed);break;case"Alphanumeric":nd=qrAlphaNum(ed);break;case"Byte":nd=qr8BitByte(ed);break;case"Kanji":nd=qrKanji(ed);break;default:throw"mode:"+td}Lu.push(nd),Du=null},Bu.isDark=function(ed,td){if(ed<0||Mu<=ed||td<0||Mu<=td)throw ed+","+td;return Ou[ed][td]},Bu.getModuleCount=function(){return Mu},Bu.make=function(){if(Iu<1){let ed=1;for(;ed<40;ed++){const td=QRRSBlock.getRSBlocks(ed,Pu),nd=qrBitBuffer();for(let sd=0;sd<Lu.length;sd++){const ad=Lu[sd];nd.put(ad.getMode(),4),nd.put(ad.getLength(),QRUtil.getLengthInBits(ad.getMode(),ed)),ad.write(nd)}let od=0;for(let sd=0;sd<td.length;sd++)od+=td[sd].dataCount;if(nd.getLengthInBits()<=od*8)break}Iu=ed}ju(!1,zu())},Bu.createTableTag=function(ed,td){ed=ed||2,td=typeof td>"u"?ed*4:td;let nd="";nd+='<table style="',nd+=" border-width: 0px; border-style: none;",nd+=" border-collapse: collapse;",nd+=" padding: 0px; margin: "+td+"px;",nd+='">',nd+="<tbody>";for(let od=0;od<Bu.getModuleCount();od+=1){nd+="<tr>";for(let sd=0;sd<Bu.getModuleCount();sd+=1)nd+='<td style="',nd+=" border-width: 0px; border-style: none;",nd+=" border-collapse: collapse;",nd+=" padding: 0px; margin: 0px;",nd+=" width: "+ed+"px;",nd+=" height: "+ed+"px;",nd+=" background-color: ",nd+=Bu.isDark(od,sd)?"#000000":"#ffffff",nd+=";",nd+='"/>';nd+="</tr>"}return nd+="</tbody>",nd+="</table>",nd},Bu.createSvgTag=function(ed,td,nd,od){let sd={};typeof arguments[0]=="object"&&(sd=arguments[0],ed=sd.cellSize,td=sd.margin,nd=sd.alt,od=sd.title),ed=ed||2,td=typeof td>"u"?ed*4:td,nd=typeof nd=="string"?{text:nd}:nd||{},nd.text=nd.text||null,nd.id=nd.text?nd.id||"qrcode-description":null,od=typeof od=="string"?{text:od}:od||{},od.text=od.text||null,od.id=od.text?od.id||"qrcode-title":null;const ad=Bu.getModuleCount()*ed+td*2;let pd,gd,_d,yd,bd="",Sd;for(Sd="l"+ed+",0 0,"+ed+" -"+ed+",0 0,-"+ed+"z ",bd+='<svg version="1.1" xmlns="http://www.w3.org/2000/svg"',bd+=sd.scalable?"":' width="'+ad+'px" height="'+ad+'px"',bd+=' viewBox="0 0 '+ad+" "+ad+'" ',bd+=' preserveAspectRatio="xMinYMin meet"',bd+=od.text||nd.text?' role="img" aria-labelledby="'+Yu([od.id,nd.id].join(" ").trim())+'"':"",bd+=">",bd+=od.text?'<title id="'+Yu(od.id)+'">'+Yu(od.text)+"</title>":"",bd+=nd.text?'<description id="'+Yu(nd.id)+'">'+Yu(nd.text)+"</description>":"",bd+='<rect width="100%" height="100%" fill="white" cx="0" cy="0"/>',bd+='<path d="',_d=0;_d<Bu.getModuleCount();_d+=1)for(yd=_d*ed+td,pd=0;pd<Bu.getModuleCount();pd+=1)Bu.isDark(_d,pd)&&(gd=pd*ed+td,bd+="M"+gd+","+yd+Sd);return bd+='" stroke="transparent" fill="black"/>',bd+="</svg>",bd},Bu.createDataURL=function(ed,td){ed=ed||2,td=typeof td>"u"?ed*4:td;const nd=Bu.getModuleCount()*ed+td*2,od=td,sd=nd-td;return createDataURL(nd,nd,function(ad,pd){if(od<=ad&&ad<sd&&od<=pd&&pd<sd){const gd=Math.floor((ad-od)/ed),_d=Math.floor((pd-od)/ed);return Bu.isDark(_d,gd)?0:1}else return 1})},Bu.createImgTag=function(ed,td,nd){ed=ed||2,td=typeof td>"u"?ed*4:td;const od=Bu.getModuleCount()*ed+td*2;let sd="";return sd+="<img",sd+=' src="',sd+=Bu.createDataURL(ed,td),sd+='"',sd+=' width="',sd+=od,sd+='"',sd+=' height="',sd+=od,sd+='"',nd&&(sd+=' alt="',sd+=Yu(nd),sd+='"'),sd+="/>",sd};const Yu=function(ed){let td="";for(let nd=0;nd<ed.length;nd+=1){const od=ed.charAt(nd);switch(od){case"<":td+="<";break;case">":td+=">";break;case"&":td+="&";break;case'"':td+=""";break;default:td+=od;break}}return td},Xu=function(ed){ed=typeof ed>"u"?2:ed;const nd=Bu.getModuleCount()*1+ed*2,od=ed,sd=nd-ed;let ad,pd,gd,_d,yd;const bd={"██":"█","█ ":"▀"," █":"▄"," ":" "},Sd={"██":"▀","█ ":"▀"," █":" "," ":" "};let Ed="";for(ad=0;ad<nd;ad+=2){for(gd=Math.floor((ad-od)/1),_d=Math.floor((ad+1-od)/1),pd=0;pd<nd;pd+=1)yd="█",od<=pd&&pd<sd&&od<=ad&&ad<sd&&Bu.isDark(gd,Math.floor((pd-od)/1))&&(yd=" "),od<=pd&&pd<sd&&od<=ad+1&&ad+1<sd&&Bu.isDark(_d,Math.floor((pd-od)/1))?yd+=" ":yd+="█",Ed+=ed<1&&ad+1>=sd?Sd[yd]:bd[yd];Ed+=`
|
|
3853
3856
|
`}return nd%2&&ed>0?Ed.substring(0,Ed.length-nd-1)+Array(nd+1).join("▀"):Ed.substring(0,Ed.length-1)};return Bu.createASCII=function(ed,td){if(ed=ed||1,ed<2)return Xu(td);ed-=1,td=typeof td>"u"?ed*2:td;const nd=Bu.getModuleCount()*ed+td*2,od=td,sd=nd-td;let ad,pd,gd,_d;const yd=Array(ed+1).join("██"),bd=Array(ed+1).join(" ");let Sd="",Ed="";for(ad=0;ad<nd;ad+=1){for(gd=Math.floor((ad-od)/ed),Ed="",pd=0;pd<nd;pd+=1)_d=1,od<=pd&&pd<sd&&od<=ad&&ad<sd&&Bu.isDark(gd,Math.floor((pd-od)/ed))&&(_d=0),Ed+=_d?yd:bd;for(gd=0;gd<ed;gd+=1)Sd+=Ed+`
|
|
3854
|
-
`}return Sd.substring(0,Sd.length-1)},Bu.renderTo2dContext=function(ed,td){td=td||2;const nd=Bu.getModuleCount();for(let od=0;od<nd;od++)for(let sd=0;sd<nd;sd++)ed.fillStyle=Bu.isDark(od,sd)?"black":"white",ed.fillRect(sd*td,od*td,td,td)},Bu};qrcode.stringToBytes=function(Au){const lo=[];for(let $u=0;$u<Au.length;$u+=1){const Ru=Au.charCodeAt($u);lo.push(Ru&255)}return lo};qrcode.createStringToBytes=function(Au,lo){const $u=(function(){const Iu=base64DecodeInputStream(Au),Pu=function(){const Du=Iu.read();if(Du==-1)throw"eof";return Du};let Ou=0;const Mu={};for(;;){const Du=Iu.read();if(Du==-1)break;const Lu=Pu(),Bu=Pu(),ju=Pu(),Fu=String.fromCharCode(Du<<8|Lu),zu=Bu<<8|ju;Mu[Fu]=zu,Ou+=1}if(Ou!=lo)throw Ou+" != "+lo;return Mu})(),Ru=63;return function(Iu){const Pu=[];for(let Ou=0;Ou<Iu.length;Ou+=1){const Mu=Iu.charCodeAt(Ou);if(Mu<128)Pu.push(Mu);else{const Du=$u[Iu.charAt(Ou)];typeof Du=="number"?(Du&255)==Du?Pu.push(Du):(Pu.push(Du>>>8),Pu.push(Du&255)):Pu.push(Ru)}}return Pu}};const QRMode={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8},QRErrorCorrectionLevel={L:1,M:0,Q:3,H:2},QRMaskPattern={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7},QRUtil=(function(){const Au=[[],[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50],[6,30,54],[6,32,58],[6,34,62],[6,26,46,66],[6,26,48,70],[6,26,50,74],[6,30,54,78],[6,30,56,82],[6,30,58,86],[6,34,62,90],[6,28,50,72,94],[6,26,50,74,98],[6,30,54,78,102],[6,28,54,80,106],[6,32,58,84,110],[6,30,58,86,114],[6,34,62,90,118],[6,26,50,74,98,122],[6,30,54,78,102,126],[6,26,52,78,104,130],[6,30,56,82,108,134],[6,34,60,86,112,138],[6,30,58,86,114,142],[6,34,62,90,118,146],[6,30,54,78,102,126,150],[6,24,50,76,102,128,154],[6,28,54,80,106,132,158],[6,32,58,84,110,136,162],[6,26,54,82,110,138,166],[6,30,58,86,114,142,170]],lo=1335,$u=7973,Ru=21522,Iu={},Pu=function(Ou){let Mu=0;for(;Ou!=0;)Mu+=1,Ou>>>=1;return Mu};return Iu.getBCHTypeInfo=function(Ou){let Mu=Ou<<10;for(;Pu(Mu)-Pu(lo)>=0;)Mu^=lo<<Pu(Mu)-Pu(lo);return(Ou<<10|Mu)^Ru},Iu.getBCHTypeNumber=function(Ou){let Mu=Ou<<12;for(;Pu(Mu)-Pu($u)>=0;)Mu^=$u<<Pu(Mu)-Pu($u);return Ou<<12|Mu},Iu.getPatternPosition=function(Ou){return Au[Ou-1]},Iu.getMaskFunction=function(Ou){switch(Ou){case QRMaskPattern.PATTERN000:return function(Mu,Du){return(Mu+Du)%2==0};case QRMaskPattern.PATTERN001:return function(Mu,Du){return Mu%2==0};case QRMaskPattern.PATTERN010:return function(Mu,Du){return Du%3==0};case QRMaskPattern.PATTERN011:return function(Mu,Du){return(Mu+Du)%3==0};case QRMaskPattern.PATTERN100:return function(Mu,Du){return(Math.floor(Mu/2)+Math.floor(Du/3))%2==0};case QRMaskPattern.PATTERN101:return function(Mu,Du){return Mu*Du%2+Mu*Du%3==0};case QRMaskPattern.PATTERN110:return function(Mu,Du){return(Mu*Du%2+Mu*Du%3)%2==0};case QRMaskPattern.PATTERN111:return function(Mu,Du){return(Mu*Du%3+(Mu+Du)%2)%2==0};default:throw"bad maskPattern:"+Ou}},Iu.getErrorCorrectPolynomial=function(Ou){let Mu=qrPolynomial([1],0);for(let Du=0;Du<Ou;Du+=1)Mu=Mu.multiply(qrPolynomial([1,QRMath.gexp(Du)],0));return Mu},Iu.getLengthInBits=function(Ou,Mu){if(1<=Mu&&Mu<10)switch(Ou){case QRMode.MODE_NUMBER:return 10;case QRMode.MODE_ALPHA_NUM:return 9;case QRMode.MODE_8BIT_BYTE:return 8;case QRMode.MODE_KANJI:return 8;default:throw"mode:"+Ou}else if(Mu<27)switch(Ou){case QRMode.MODE_NUMBER:return 12;case QRMode.MODE_ALPHA_NUM:return 11;case QRMode.MODE_8BIT_BYTE:return 16;case QRMode.MODE_KANJI:return 10;default:throw"mode:"+Ou}else if(Mu<41)switch(Ou){case QRMode.MODE_NUMBER:return 14;case QRMode.MODE_ALPHA_NUM:return 13;case QRMode.MODE_8BIT_BYTE:return 16;case QRMode.MODE_KANJI:return 12;default:throw"mode:"+Ou}else throw"type:"+Mu},Iu.getLostPoint=function(Ou){const Mu=Ou.getModuleCount();let Du=0;for(let ju=0;ju<Mu;ju+=1)for(let Fu=0;Fu<Mu;Fu+=1){let zu=0;const Uu=Ou.isDark(ju,Fu);for(let Hu=-1;Hu<=1;Hu+=1)if(!(ju+Hu<0||Mu<=ju+Hu))for(let Vu=-1;Vu<=1;Vu+=1)Fu+Vu<0||Mu<=Fu+Vu||Hu==0&&Vu==0||Uu==Ou.isDark(ju+Hu,Fu+Vu)&&(zu+=1);zu>5&&(Du+=3+zu-5)}for(let ju=0;ju<Mu-1;ju+=1)for(let Fu=0;Fu<Mu-1;Fu+=1){let zu=0;Ou.isDark(ju,Fu)&&(zu+=1),Ou.isDark(ju+1,Fu)&&(zu+=1),Ou.isDark(ju,Fu+1)&&(zu+=1),Ou.isDark(ju+1,Fu+1)&&(zu+=1),(zu==0||zu==4)&&(Du+=3)}for(let ju=0;ju<Mu;ju+=1)for(let Fu=0;Fu<Mu-6;Fu+=1)Ou.isDark(ju,Fu)&&!Ou.isDark(ju,Fu+1)&&Ou.isDark(ju,Fu+2)&&Ou.isDark(ju,Fu+3)&&Ou.isDark(ju,Fu+4)&&!Ou.isDark(ju,Fu+5)&&Ou.isDark(ju,Fu+6)&&(Du+=40);for(let ju=0;ju<Mu;ju+=1)for(let Fu=0;Fu<Mu-6;Fu+=1)Ou.isDark(Fu,ju)&&!Ou.isDark(Fu+1,ju)&&Ou.isDark(Fu+2,ju)&&Ou.isDark(Fu+3,ju)&&Ou.isDark(Fu+4,ju)&&!Ou.isDark(Fu+5,ju)&&Ou.isDark(Fu+6,ju)&&(Du+=40);let Lu=0;for(let ju=0;ju<Mu;ju+=1)for(let Fu=0;Fu<Mu;Fu+=1)Ou.isDark(Fu,ju)&&(Lu+=1);const Bu=Math.abs(100*Lu/Mu/Mu-50)/5;return Du+=Bu*10,Du},Iu})(),QRMath=(function(){const Au=new Array(256),lo=new Array(256);for(let Ru=0;Ru<8;Ru+=1)Au[Ru]=1<<Ru;for(let Ru=8;Ru<256;Ru+=1)Au[Ru]=Au[Ru-4]^Au[Ru-5]^Au[Ru-6]^Au[Ru-8];for(let Ru=0;Ru<255;Ru+=1)lo[Au[Ru]]=Ru;const $u={};return $u.glog=function(Ru){if(Ru<1)throw"glog("+Ru+")";return lo[Ru]},$u.gexp=function(Ru){for(;Ru<0;)Ru+=255;for(;Ru>=256;)Ru-=255;return Au[Ru]},$u})(),qrPolynomial=function(Au,lo){if(typeof Au.length>"u")throw Au.length+"/"+lo;const $u=(function(){let Iu=0;for(;Iu<Au.length&&Au[Iu]==0;)Iu+=1;const Pu=new Array(Au.length-Iu+lo);for(let Ou=0;Ou<Au.length-Iu;Ou+=1)Pu[Ou]=Au[Ou+Iu];return Pu})(),Ru={};return Ru.getAt=function(Iu){return $u[Iu]},Ru.getLength=function(){return $u.length},Ru.multiply=function(Iu){const Pu=new Array(Ru.getLength()+Iu.getLength()-1);for(let Ou=0;Ou<Ru.getLength();Ou+=1)for(let Mu=0;Mu<Iu.getLength();Mu+=1)Pu[Ou+Mu]^=QRMath.gexp(QRMath.glog(Ru.getAt(Ou))+QRMath.glog(Iu.getAt(Mu)));return qrPolynomial(Pu,0)},Ru.mod=function(Iu){if(Ru.getLength()-Iu.getLength()<0)return Ru;const Pu=QRMath.glog(Ru.getAt(0))-QRMath.glog(Iu.getAt(0)),Ou=new Array(Ru.getLength());for(let Mu=0;Mu<Ru.getLength();Mu+=1)Ou[Mu]=Ru.getAt(Mu);for(let Mu=0;Mu<Iu.getLength();Mu+=1)Ou[Mu]^=QRMath.gexp(QRMath.glog(Iu.getAt(Mu))+Pu);return qrPolynomial(Ou,0).mod(Iu)},Ru},QRRSBlock=(function(){const Au=[[1,26,19],[1,26,16],[1,26,13],[1,26,9],[1,44,34],[1,44,28],[1,44,22],[1,44,16],[1,70,55],[1,70,44],[2,35,17],[2,35,13],[1,100,80],[2,50,32],[2,50,24],[4,25,9],[1,134,108],[2,67,43],[2,33,15,2,34,16],[2,33,11,2,34,12],[2,86,68],[4,43,27],[4,43,19],[4,43,15],[2,98,78],[4,49,31],[2,32,14,4,33,15],[4,39,13,1,40,14],[2,121,97],[2,60,38,2,61,39],[4,40,18,2,41,19],[4,40,14,2,41,15],[2,146,116],[3,58,36,2,59,37],[4,36,16,4,37,17],[4,36,12,4,37,13],[2,86,68,2,87,69],[4,69,43,1,70,44],[6,43,19,2,44,20],[6,43,15,2,44,16],[4,101,81],[1,80,50,4,81,51],[4,50,22,4,51,23],[3,36,12,8,37,13],[2,116,92,2,117,93],[6,58,36,2,59,37],[4,46,20,6,47,21],[7,42,14,4,43,15],[4,133,107],[8,59,37,1,60,38],[8,44,20,4,45,21],[12,33,11,4,34,12],[3,145,115,1,146,116],[4,64,40,5,65,41],[11,36,16,5,37,17],[11,36,12,5,37,13],[5,109,87,1,110,88],[5,65,41,5,66,42],[5,54,24,7,55,25],[11,36,12,7,37,13],[5,122,98,1,123,99],[7,73,45,3,74,46],[15,43,19,2,44,20],[3,45,15,13,46,16],[1,135,107,5,136,108],[10,74,46,1,75,47],[1,50,22,15,51,23],[2,42,14,17,43,15],[5,150,120,1,151,121],[9,69,43,4,70,44],[17,50,22,1,51,23],[2,42,14,19,43,15],[3,141,113,4,142,114],[3,70,44,11,71,45],[17,47,21,4,48,22],[9,39,13,16,40,14],[3,135,107,5,136,108],[3,67,41,13,68,42],[15,54,24,5,55,25],[15,43,15,10,44,16],[4,144,116,4,145,117],[17,68,42],[17,50,22,6,51,23],[19,46,16,6,47,17],[2,139,111,7,140,112],[17,74,46],[7,54,24,16,55,25],[34,37,13],[4,151,121,5,152,122],[4,75,47,14,76,48],[11,54,24,14,55,25],[16,45,15,14,46,16],[6,147,117,4,148,118],[6,73,45,14,74,46],[11,54,24,16,55,25],[30,46,16,2,47,17],[8,132,106,4,133,107],[8,75,47,13,76,48],[7,54,24,22,55,25],[22,45,15,13,46,16],[10,142,114,2,143,115],[19,74,46,4,75,47],[28,50,22,6,51,23],[33,46,16,4,47,17],[8,152,122,4,153,123],[22,73,45,3,74,46],[8,53,23,26,54,24],[12,45,15,28,46,16],[3,147,117,10,148,118],[3,73,45,23,74,46],[4,54,24,31,55,25],[11,45,15,31,46,16],[7,146,116,7,147,117],[21,73,45,7,74,46],[1,53,23,37,54,24],[19,45,15,26,46,16],[5,145,115,10,146,116],[19,75,47,10,76,48],[15,54,24,25,55,25],[23,45,15,25,46,16],[13,145,115,3,146,116],[2,74,46,29,75,47],[42,54,24,1,55,25],[23,45,15,28,46,16],[17,145,115],[10,74,46,23,75,47],[10,54,24,35,55,25],[19,45,15,35,46,16],[17,145,115,1,146,116],[14,74,46,21,75,47],[29,54,24,19,55,25],[11,45,15,46,46,16],[13,145,115,6,146,116],[14,74,46,23,75,47],[44,54,24,7,55,25],[59,46,16,1,47,17],[12,151,121,7,152,122],[12,75,47,26,76,48],[39,54,24,14,55,25],[22,45,15,41,46,16],[6,151,121,14,152,122],[6,75,47,34,76,48],[46,54,24,10,55,25],[2,45,15,64,46,16],[17,152,122,4,153,123],[29,74,46,14,75,47],[49,54,24,10,55,25],[24,45,15,46,46,16],[4,152,122,18,153,123],[13,74,46,32,75,47],[48,54,24,14,55,25],[42,45,15,32,46,16],[20,147,117,4,148,118],[40,75,47,7,76,48],[43,54,24,22,55,25],[10,45,15,67,46,16],[19,148,118,6,149,119],[18,75,47,31,76,48],[34,54,24,34,55,25],[20,45,15,61,46,16]],lo=function(Iu,Pu){const Ou={};return Ou.totalCount=Iu,Ou.dataCount=Pu,Ou},$u={},Ru=function(Iu,Pu){switch(Pu){case QRErrorCorrectionLevel.L:return Au[(Iu-1)*4+0];case QRErrorCorrectionLevel.M:return Au[(Iu-1)*4+1];case QRErrorCorrectionLevel.Q:return Au[(Iu-1)*4+2];case QRErrorCorrectionLevel.H:return Au[(Iu-1)*4+3];default:return}};return $u.getRSBlocks=function(Iu,Pu){const Ou=Ru(Iu,Pu);if(typeof Ou>"u")throw"bad rs block @ typeNumber:"+Iu+"/errorCorrectionLevel:"+Pu;const Mu=Ou.length/3,Du=[];for(let Lu=0;Lu<Mu;Lu+=1){const Bu=Ou[Lu*3+0],ju=Ou[Lu*3+1],Fu=Ou[Lu*3+2];for(let zu=0;zu<Bu;zu+=1)Du.push(lo(ju,Fu))}return Du},$u})(),qrBitBuffer=function(){const Au=[];let lo=0;const $u={};return $u.getBuffer=function(){return Au},$u.getAt=function(Ru){const Iu=Math.floor(Ru/8);return(Au[Iu]>>>7-Ru%8&1)==1},$u.put=function(Ru,Iu){for(let Pu=0;Pu<Iu;Pu+=1)$u.putBit((Ru>>>Iu-Pu-1&1)==1)},$u.getLengthInBits=function(){return lo},$u.putBit=function(Ru){const Iu=Math.floor(lo/8);Au.length<=Iu&&Au.push(0),Ru&&(Au[Iu]|=128>>>lo%8),lo+=1},$u},qrNumber=function(Au){const lo=QRMode.MODE_NUMBER,$u=Au,Ru={};Ru.getMode=function(){return lo},Ru.getLength=function(Ou){return $u.length},Ru.write=function(Ou){const Mu=$u;let Du=0;for(;Du+2<Mu.length;)Ou.put(Iu(Mu.substring(Du,Du+3)),10),Du+=3;Du<Mu.length&&(Mu.length-Du==1?Ou.put(Iu(Mu.substring(Du,Du+1)),4):Mu.length-Du==2&&Ou.put(Iu(Mu.substring(Du,Du+2)),7))};const Iu=function(Ou){let Mu=0;for(let Du=0;Du<Ou.length;Du+=1)Mu=Mu*10+Pu(Ou.charAt(Du));return Mu},Pu=function(Ou){if("0"<=Ou&&Ou<="9")return Ou.charCodeAt(0)-48;throw"illegal char :"+Ou};return Ru},qrAlphaNum=function(Au){const lo=QRMode.MODE_ALPHA_NUM,$u=Au,Ru={};Ru.getMode=function(){return lo},Ru.getLength=function(Pu){return $u.length},Ru.write=function(Pu){const Ou=$u;let Mu=0;for(;Mu+1<Ou.length;)Pu.put(Iu(Ou.charAt(Mu))*45+Iu(Ou.charAt(Mu+1)),11),Mu+=2;Mu<Ou.length&&Pu.put(Iu(Ou.charAt(Mu)),6)};const Iu=function(Pu){if("0"<=Pu&&Pu<="9")return Pu.charCodeAt(0)-48;if("A"<=Pu&&Pu<="Z")return Pu.charCodeAt(0)-65+10;switch(Pu){case" ":return 36;case"$":return 37;case"%":return 38;case"*":return 39;case"+":return 40;case"-":return 41;case".":return 42;case"/":return 43;case":":return 44;default:throw"illegal char :"+Pu}};return Ru},qr8BitByte=function(Au){const lo=QRMode.MODE_8BIT_BYTE,$u=qrcode.stringToBytes(Au),Ru={};return Ru.getMode=function(){return lo},Ru.getLength=function(Iu){return $u.length},Ru.write=function(Iu){for(let Pu=0;Pu<$u.length;Pu+=1)Iu.put($u[Pu],8)},Ru},qrKanji=function(Au){const lo=QRMode.MODE_KANJI,$u=qrcode.stringToBytes;(function(Pu,Ou){const Mu=$u(Pu);if(Mu.length!=2||(Mu[0]<<8|Mu[1])!=Ou)throw"sjis not supported."})("友",38726);const Ru=$u(Au),Iu={};return Iu.getMode=function(){return lo},Iu.getLength=function(Pu){return~~(Ru.length/2)},Iu.write=function(Pu){const Ou=Ru;let Mu=0;for(;Mu+1<Ou.length;){let Du=(255&Ou[Mu])<<8|255&Ou[Mu+1];if(33088<=Du&&Du<=40956)Du-=33088;else if(57408<=Du&&Du<=60351)Du-=49472;else throw"illegal char at "+(Mu+1)+"/"+Du;Du=(Du>>>8&255)*192+(Du&255),Pu.put(Du,13),Mu+=2}if(Mu<Ou.length)throw"illegal char at "+(Mu+1)},Iu},byteArrayOutputStream=function(){const Au=[],lo={};return lo.writeByte=function($u){Au.push($u&255)},lo.writeShort=function($u){lo.writeByte($u),lo.writeByte($u>>>8)},lo.writeBytes=function($u,Ru,Iu){Ru=Ru||0,Iu=Iu||$u.length;for(let Pu=0;Pu<Iu;Pu+=1)lo.writeByte($u[Pu+Ru])},lo.writeString=function($u){for(let Ru=0;Ru<$u.length;Ru+=1)lo.writeByte($u.charCodeAt(Ru))},lo.toByteArray=function(){return Au},lo.toString=function(){let $u="";$u+="[";for(let Ru=0;Ru<Au.length;Ru+=1)Ru>0&&($u+=","),$u+=Au[Ru];return $u+="]",$u},lo},base64EncodeOutputStream=function(){let Au=0,lo=0,$u=0,Ru="";const Iu={},Pu=function(Mu){Ru+=String.fromCharCode(Ou(Mu&63))},Ou=function(Mu){if(Mu<0)throw"n:"+Mu;if(Mu<26)return 65+Mu;if(Mu<52)return 97+(Mu-26);if(Mu<62)return 48+(Mu-52);if(Mu==62)return 43;if(Mu==63)return 47;throw"n:"+Mu};return Iu.writeByte=function(Mu){for(Au=Au<<8|Mu&255,lo+=8,$u+=1;lo>=6;)Pu(Au>>>lo-6),lo-=6},Iu.flush=function(){if(lo>0&&(Pu(Au<<6-lo),Au=0,lo=0),$u%3!=0){const Mu=3-$u%3;for(let Du=0;Du<Mu;Du+=1)Ru+="="}},Iu.toString=function(){return Ru},Iu},base64DecodeInputStream=function(Au){const lo=Au;let $u=0,Ru=0,Iu=0;const Pu={};Pu.read=function(){for(;Iu<8;){if($u>=lo.length){if(Iu==0)return-1;throw"unexpected end of file./"+Iu}const Du=lo.charAt($u);if($u+=1,Du=="=")return Iu=0,-1;if(Du.match(/^\s$/))continue;Ru=Ru<<6|Ou(Du.charCodeAt(0)),Iu+=6}const Mu=Ru>>>Iu-8&255;return Iu-=8,Mu};const Ou=function(Mu){if(65<=Mu&&Mu<=90)return Mu-65;if(97<=Mu&&Mu<=122)return Mu-97+26;if(48<=Mu&&Mu<=57)return Mu-48+52;if(Mu==43)return 62;if(Mu==47)return 63;throw"c:"+Mu};return Pu},gifImage=function(Au,lo){const $u=Au,Ru=lo,Iu=new Array(Au*lo),Pu={};Pu.setPixel=function(Lu,Bu,ju){Iu[Bu*$u+Lu]=ju},Pu.write=function(Lu){Lu.writeString("GIF87a"),Lu.writeShort($u),Lu.writeShort(Ru),Lu.writeByte(128),Lu.writeByte(0),Lu.writeByte(0),Lu.writeByte(0),Lu.writeByte(0),Lu.writeByte(0),Lu.writeByte(255),Lu.writeByte(255),Lu.writeByte(255),Lu.writeString(","),Lu.writeShort(0),Lu.writeShort(0),Lu.writeShort($u),Lu.writeShort(Ru),Lu.writeByte(0);const Bu=2,ju=Mu(Bu);Lu.writeByte(Bu);let Fu=0;for(;ju.length-Fu>255;)Lu.writeByte(255),Lu.writeBytes(ju,Fu,255),Fu+=255;Lu.writeByte(ju.length-Fu),Lu.writeBytes(ju,Fu,ju.length-Fu),Lu.writeByte(0),Lu.writeString(";")};const Ou=function(Lu){const Bu=Lu;let ju=0,Fu=0;const zu={};return zu.write=function(Uu,Hu){if(Uu>>>Hu)throw"length over";for(;ju+Hu>=8;)Bu.writeByte(255&(Uu<<ju|Fu)),Hu-=8-ju,Uu>>>=8-ju,Fu=0,ju=0;Fu=Uu<<ju|Fu,ju=ju+Hu},zu.flush=function(){ju>0&&Bu.writeByte(Fu)},zu},Mu=function(Lu){const Bu=1<<Lu,ju=(1<<Lu)+1;let Fu=Lu+1;const zu=Du();for(let Wu=0;Wu<Bu;Wu+=1)zu.add(String.fromCharCode(Wu));zu.add(String.fromCharCode(Bu)),zu.add(String.fromCharCode(ju));const Uu=byteArrayOutputStream(),Hu=Ou(Uu);Hu.write(Bu,Fu);let Vu=0,Gu=String.fromCharCode(Iu[Vu]);for(Vu+=1;Vu<Iu.length;){const Wu=String.fromCharCode(Iu[Vu]);Vu+=1,zu.contains(Gu+Wu)?Gu=Gu+Wu:(Hu.write(zu.indexOf(Gu),Fu),zu.size()<4095&&(zu.size()==1<<Fu&&(Fu+=1),zu.add(Gu+Wu)),Gu=Wu)}return Hu.write(zu.indexOf(Gu),Fu),Hu.write(ju,Fu),Hu.flush(),Uu.toByteArray()},Du=function(){const Lu={};let Bu=0;const ju={};return ju.add=function(Fu){if(ju.contains(Fu))throw"dup key:"+Fu;Lu[Fu]=Bu,Bu+=1},ju.size=function(){return Bu},ju.indexOf=function(Fu){return Lu[Fu]},ju.contains=function(Fu){return typeof Lu[Fu]<"u"},ju};return Pu},createDataURL=function(Au,lo,$u){const Ru=gifImage(Au,lo);for(let Mu=0;Mu<lo;Mu+=1)for(let Du=0;Du<Au;Du+=1)Ru.setPixel(Du,Mu,$u(Du,Mu));const Iu=byteArrayOutputStream();Ru.write(Iu);const Pu=base64EncodeOutputStream(),Ou=Iu.toByteArray();for(let Mu=0;Mu<Ou.length;Mu+=1)Pu.writeByte(Ou[Mu]);return Pu.flush(),"data:image/gif;base64,"+Pu};qrcode.stringToBytes;function _extends(){return _extends=Object.assign?Object.assign.bind():function(Au){for(var lo=1;lo<arguments.length;lo++){var $u=arguments[lo];for(var Ru in $u)({}).hasOwnProperty.call($u,Ru)&&(Au[Ru]=$u[Ru])}return Au},_extends.apply(null,arguments)}function _objectWithoutProperties(Au,lo){if(Au==null)return{};var $u,Ru,Iu=_objectWithoutPropertiesLoose(Au,lo);if(Object.getOwnPropertySymbols){var Pu=Object.getOwnPropertySymbols(Au);for(Ru=0;Ru<Pu.length;Ru++)$u=Pu[Ru],lo.indexOf($u)===-1&&{}.propertyIsEnumerable.call(Au,$u)&&(Iu[$u]=Au[$u])}return Iu}function _objectWithoutPropertiesLoose(Au,lo){if(Au==null)return{};var $u={};for(var Ru in Au)if({}.hasOwnProperty.call(Au,Ru)){if(lo.indexOf(Ru)!==-1)continue;$u[Ru]=Au[Ru]}return $u}var _excluded$1=["bgColor","bgD","fgD","fgColor","size","title","viewBoxSize","xmlns"],propTypes$1={bgColor:s$5.oneOfType([s$5.object,s$5.string]).isRequired,bgD:s$5.string.isRequired,fgColor:s$5.oneOfType([s$5.object,s$5.string]).isRequired,fgD:s$5.string.isRequired,size:s$5.number.isRequired,title:s$5.string,viewBoxSize:s$5.number.isRequired,xmlns:s$5.string},QRCodeSvg=reactExports.forwardRef(function(Au,lo){var $u=Au.bgColor,Ru=Au.bgD,Iu=Au.fgD,Pu=Au.fgColor,Ou=Au.size,Mu=Au.title,Du=Au.viewBoxSize,Lu=Au.xmlns,Bu=Lu===void 0?"http://www.w3.org/2000/svg":Lu,ju=_objectWithoutProperties(Au,_excluded$1);return vM.createElement("svg",_extends({},ju,{height:Ou,ref:lo,viewBox:"0 0 ".concat(Du," ").concat(Du),width:Ou,xmlns:Bu}),Mu?vM.createElement("title",null,Mu):null,vM.createElement("path",{d:Ru,fill:$u}),vM.createElement("path",{d:Iu,fill:Pu}))});QRCodeSvg.displayName="QRCodeSvg";QRCodeSvg.propTypes=propTypes$1;var _excluded=["bgColor","fgColor","level","size","value"];qrcode.stringToBytes=function(Au){return Array.from(new TextEncoder().encode(Au))};var propTypes={bgColor:s$5.oneOfType([s$5.object,s$5.string]),fgColor:s$5.oneOfType([s$5.object,s$5.string]),level:s$5.string,size:s$5.number,value:s$5.string.isRequired},QRCode=reactExports.forwardRef(function(Au,lo){var $u=Au.bgColor,Ru=$u===void 0?"#FFFFFF":$u,Iu=Au.fgColor,Pu=Iu===void 0?"#000000":Iu,Ou=Au.level,Mu=Ou===void 0?"L":Ou,Du=Au.size,Lu=Du===void 0?256:Du,Bu=Au.value,ju=_objectWithoutProperties(Au,_excluded),Fu=qrcode(0,Mu);Fu.addData(Bu),Fu.make();var zu=Fu.getModuleCount(),Uu=Array.from({length:zu},function(Hu,Vu){return Array.from({length:zu},function(Gu,Wu){return Fu.isDark(Vu,Wu)})});return vM.createElement(QRCodeSvg,_extends({},ju,{bgColor:Ru,bgD:Uu.map(function(Hu,Vu){return Hu.map(function(Gu,Wu){return Gu?"":"M ".concat(Wu," ").concat(Vu," l 1 0 0 1 -1 0 Z")}).join(" ")}).join(" "),fgColor:Pu,fgD:Uu.map(function(Hu,Vu){return Hu.map(function(Gu,Wu){return Gu?"M ".concat(Wu," ").concat(Vu," l 1 0 0 1 -1 0 Z"):""}).join(" ")}).join(" "),ref:lo,size:Lu,viewBoxSize:zu}))});QRCode.displayName="QRCode";QRCode.propTypes=propTypes;function PapSignInCard({context:Au,send:lo}){const[$u,Ru]=reactExports.useState(!1),[Iu,Pu]=reactExports.useState(!1),[Ou,Mu]=reactExports.useState(null),Du=Au.status==="complete"?readPapSignIn(Au.result):null,Lu=Du&&!("refused"in Du)&&Du.mode==="direct"?Du.company??"":"";if(reactExports.useEffect(()=>{if(!Lu||typeof BroadcastChannel>"u")return;const zu=new BroadcastChannel(PAP_SIGN_IN_CHANNEL);return zu.onmessage=Uu=>{const Hu=signInReturnOf(Uu.data,Lu);Hu&&(Mu(Hu),zu.close())},()=>zu.close()},[Lu]),reactExports.useEffect(()=>{Ou==="signed_in"&&lo&&!Iu&&Pu(lo(PAP_SIGN_IN_WORDS.checkMessage(Lu)))},[Ou,lo,Iu,Lu]),!Du)return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:Au.defaultUI});if("refused"in Du)return jsxRuntimeExports.jsx(Flash,{variant:"danger",role:"alert",sx:{my:2},children:Du.refused});const Bu=async()=>{try{await navigator.clipboard.writeText(Du.code??""),Ru(!0)}catch{Ru(!1)}},ju=Du.company??Du.host,Fu=Du.mode==="mediated"?PAP_SIGN_IN_WORDS.mediatedTitle(Du.host):PAP_SIGN_IN_WORDS.title(ju);return jsxRuntimeExports.jsxs(Box,{as:"section","aria-label":Fu,my:2,p:3,border:"1px solid",borderColor:"border.default",borderRadius:2,bg:"canvas.subtle",maxWidth:480,children:[jsxRuntimeExports.jsx(Heading$2,{as:"h4",sx:{fontSize:2,mb:1},children:Fu}),jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{mt:0,mb:2,color:"fg.muted",fontSize:1},children:Du.mode==="device"?PAP_SIGN_IN_WORDS.device:Du.mode==="mediated"?PAP_SIGN_IN_WORDS.mediated:PAP_SIGN_IN_WORDS.direct}),Du.needs?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{mt:0,mb:2,fontSize:1},children:PAP_SIGN_IN_WORDS.needs(Du.needs)}):null,Du.sentTo?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{mt:0,mb:2,fontSize:1},children:PAP_SIGN_IN_WORDS.sentTo(Du.sentTo)}):null,Du.code?jsxRuntimeExports.jsxs(Box,{display:"flex",gap:3,alignItems:"center",flexWrap:"wrap",mb:2,children:[jsxRuntimeExports.jsxs(Box,{children:[jsxRuntimeExports.jsx(Text$3,{as:"div",sx:{fontSize:0,color:"fg.muted"},children:PAP_SIGN_IN_WORDS.code}),jsxRuntimeExports.jsx(Text$3,{as:"div","aria-live":"polite",sx:{fontFamily:"mono",fontSize:5,fontWeight:"bold",letterSpacing:"0.15em"},children:Du.code}),jsxRuntimeExports.jsx(ButtonComponent,{size:"small",leadingVisual:CopyIcon,onClick:()=>{Bu()},children:$u?PAP_SIGN_IN_WORDS.copied:PAP_SIGN_IN_WORDS.copy})]}),jsxRuntimeExports.jsx(Box,{bg:"#ffffff",p:2,borderRadius:2,lineHeight:0,children:jsxRuntimeExports.jsx(QRCode,{value:Du.open,size:112,title:PAP_SIGN_IN_WORDS.qr(Du.host)})})]}):null,jsxRuntimeExports.jsxs(Box,{display:"flex",gap:2,flexWrap:"wrap",alignItems:"center",children:[jsxRuntimeExports.jsx(ButtonComponent,{as:"a",href:Du.open,target:"_blank",rel:"noopener noreferrer",variant:"primary",trailingVisual:LinkExternalIcon,children:PAP_SIGN_IN_WORDS.open(ju)}),lo?jsxRuntimeExports.jsx(ButtonComponent,{disabled:Iu,onClick:()=>Pu(lo(PAP_SIGN_IN_WORDS.checkMessage(ju))),children:PAP_SIGN_IN_WORDS.checkAgain}):null]}),Ou?jsxRuntimeExports.jsx(Text$3,{as:"p",role:"status",sx:{mt:2,mb:0,fontSize:1},children:PAP_SIGN_IN_WORDS.returned[Ou](ju)}):null,Du.expiresAt?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{mt:2,mb:0,fontSize:0,color:"fg.muted"},children:PAP_SIGN_IN_WORDS.until(Du.expiresAt)}):null,lo?null:jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{mt:1,mb:0,fontSize:1},children:PAP_SIGN_IN_WORDS.tellMe})]})}const PAP_SIGN_IN_PLUGIN_NAME="@datalayer/loop-plugin-pap-sign-in",PAP_SIGN_IN_TYPE="application/vnd.datalayer.pap.sign-in+json";function resultOf(Au,lo){const $u=Au.data??{};return"toolName"in $u?lo?.result:{status:"waiting_for_the_person",...$u}}function createPapSignInPlugin(){let Au;const lo=Pu=>Au?!Au(Pu):!1;function $u({workspace:Pu}){const Ou=Pu?.viewControls.send;return reactExports.useEffect(()=>(Au=Ou,()=>{Au===Ou&&(Au=void 0)}),[Ou]),null}function Ru({display:Pu,context:Ou}){const Mu=resultOf(Pu,Ou);return reactExports.createElement(PapSignInCard,{key:Pu.id,context:Ou?{...Ou,result:Mu}:{toolCallId:Pu.id,toolName:"pap_sign_in",name:"pap_sign_in",args:{},status:"complete",result:Mu},send:Au?lo:void 0})}return{name:PAP_SIGN_IN_PLUGIN_NAME,displayName:"Sign in at a company",description:"The company’s page, the code and until when, where the agent asks the person to sign in.",octicon:"sign-in",emoji:"🔑",contributes:[contribution(Renderers,defineRenderer({type:PAP_SIGN_IN_TYPE,component:Ru}),{id:"pap-sign-in"}),contribution(ToolBindings,{tool:PAP_SIGN_IN_TOOL,type:PAP_SIGN_IN_TYPE},{id:"pap-sign-in"})],build(){return{components:[{slot:LoopSlots.chatHeader,id:"pap-sign-in",Component:$u}]}}}}const PapSignInPlugin=createPapSignInPlugin();function makeViewSwitchAction({viewId:Au,icon:lo,tooltip:$u}){return function(){const Iu=reactExports.useSyncExternalStore(subscribeEditorChoice,()=>getEditorChoice().editorId),Pu=useContributions(LoopEditorView);if(Au!==NONE_EDITOR&&!Pu.some(Mu=>Mu.value.surfaceId===Au))return null;const Ou=(Iu||NONE_EDITOR)===Au;return jsxRuntimeExports.jsx(IconButton,{icon:lo,"aria-label":$u,size:"small",variant:"invisible",onClick:()=>{chooseEditor(Au)||console.warn(`[loop] No chat is on screen to switch to '${Au}'.`)},sx:Ou?{color:"accent.fg"}:void 0})}}function defineViewPlugin(Au){const{key:lo,viewId:$u,displayName:Ru,description:Iu,icon:Pu,tooltip:Ou,order:Mu}=Au,Du=makeViewSwitchAction({viewId:$u,icon:Pu,tooltip:Ou});return{name:`@datalayer/loop-plugin-${lo}-view`,displayName:Ru,description:Iu,octicon:Au.octicon??"eye",emoji:Au.emoji,dependencies:[InputPromptPlugin],build:()=>({components:[{id:`${lo}-view-action`,slot:LoopSlots.promptAction,order:Mu,Component:Du}]})}}const ChatViewPlugin=defineViewPlugin({key:"chat",viewId:NONE_EDITOR,displayName:"Chat view",description:"The conversation on its own, from the composer footer.",icon:CommentDiscussionIcon,tooltip:"Show the chat",octicon:"comment-discussion",emoji:"💬",order:10}),DocumentViewPlugin=defineViewPlugin({key:"document",viewId:"document",displayName:"Document view",description:"The document beside the chat, from the composer footer.",icon:FileIcon,tooltip:"Show the document",octicon:"file",emoji:"📄",order:12}),NotebookViewPlugin=defineViewPlugin({key:"notebook",viewId:"notebook",displayName:"Notebook view",description:"The notebook beside the chat, from the composer footer.",icon:RowsIcon,tooltip:"Show the notebook",octicon:"rows",emoji:"📓",order:11}),STYLE_ELEMENT_ID="datalayer-reactor-commands-style",PALETTE_CSS=`
|
|
3857
|
+
`}return Sd.substring(0,Sd.length-1)},Bu.renderTo2dContext=function(ed,td){td=td||2;const nd=Bu.getModuleCount();for(let od=0;od<nd;od++)for(let sd=0;sd<nd;sd++)ed.fillStyle=Bu.isDark(od,sd)?"black":"white",ed.fillRect(sd*td,od*td,td,td)},Bu};qrcode.stringToBytes=function(Au){const lo=[];for(let $u=0;$u<Au.length;$u+=1){const Ru=Au.charCodeAt($u);lo.push(Ru&255)}return lo};qrcode.createStringToBytes=function(Au,lo){const $u=(function(){const Iu=base64DecodeInputStream(Au),Pu=function(){const Du=Iu.read();if(Du==-1)throw"eof";return Du};let Ou=0;const Mu={};for(;;){const Du=Iu.read();if(Du==-1)break;const Lu=Pu(),Bu=Pu(),ju=Pu(),Fu=String.fromCharCode(Du<<8|Lu),zu=Bu<<8|ju;Mu[Fu]=zu,Ou+=1}if(Ou!=lo)throw Ou+" != "+lo;return Mu})(),Ru=63;return function(Iu){const Pu=[];for(let Ou=0;Ou<Iu.length;Ou+=1){const Mu=Iu.charCodeAt(Ou);if(Mu<128)Pu.push(Mu);else{const Du=$u[Iu.charAt(Ou)];typeof Du=="number"?(Du&255)==Du?Pu.push(Du):(Pu.push(Du>>>8),Pu.push(Du&255)):Pu.push(Ru)}}return Pu}};const QRMode={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8},QRErrorCorrectionLevel={L:1,M:0,Q:3,H:2},QRMaskPattern={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7},QRUtil=(function(){const Au=[[],[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50],[6,30,54],[6,32,58],[6,34,62],[6,26,46,66],[6,26,48,70],[6,26,50,74],[6,30,54,78],[6,30,56,82],[6,30,58,86],[6,34,62,90],[6,28,50,72,94],[6,26,50,74,98],[6,30,54,78,102],[6,28,54,80,106],[6,32,58,84,110],[6,30,58,86,114],[6,34,62,90,118],[6,26,50,74,98,122],[6,30,54,78,102,126],[6,26,52,78,104,130],[6,30,56,82,108,134],[6,34,60,86,112,138],[6,30,58,86,114,142],[6,34,62,90,118,146],[6,30,54,78,102,126,150],[6,24,50,76,102,128,154],[6,28,54,80,106,132,158],[6,32,58,84,110,136,162],[6,26,54,82,110,138,166],[6,30,58,86,114,142,170]],lo=1335,$u=7973,Ru=21522,Iu={},Pu=function(Ou){let Mu=0;for(;Ou!=0;)Mu+=1,Ou>>>=1;return Mu};return Iu.getBCHTypeInfo=function(Ou){let Mu=Ou<<10;for(;Pu(Mu)-Pu(lo)>=0;)Mu^=lo<<Pu(Mu)-Pu(lo);return(Ou<<10|Mu)^Ru},Iu.getBCHTypeNumber=function(Ou){let Mu=Ou<<12;for(;Pu(Mu)-Pu($u)>=0;)Mu^=$u<<Pu(Mu)-Pu($u);return Ou<<12|Mu},Iu.getPatternPosition=function(Ou){return Au[Ou-1]},Iu.getMaskFunction=function(Ou){switch(Ou){case QRMaskPattern.PATTERN000:return function(Mu,Du){return(Mu+Du)%2==0};case QRMaskPattern.PATTERN001:return function(Mu,Du){return Mu%2==0};case QRMaskPattern.PATTERN010:return function(Mu,Du){return Du%3==0};case QRMaskPattern.PATTERN011:return function(Mu,Du){return(Mu+Du)%3==0};case QRMaskPattern.PATTERN100:return function(Mu,Du){return(Math.floor(Mu/2)+Math.floor(Du/3))%2==0};case QRMaskPattern.PATTERN101:return function(Mu,Du){return Mu*Du%2+Mu*Du%3==0};case QRMaskPattern.PATTERN110:return function(Mu,Du){return(Mu*Du%2+Mu*Du%3)%2==0};case QRMaskPattern.PATTERN111:return function(Mu,Du){return(Mu*Du%3+(Mu+Du)%2)%2==0};default:throw"bad maskPattern:"+Ou}},Iu.getErrorCorrectPolynomial=function(Ou){let Mu=qrPolynomial([1],0);for(let Du=0;Du<Ou;Du+=1)Mu=Mu.multiply(qrPolynomial([1,QRMath.gexp(Du)],0));return Mu},Iu.getLengthInBits=function(Ou,Mu){if(1<=Mu&&Mu<10)switch(Ou){case QRMode.MODE_NUMBER:return 10;case QRMode.MODE_ALPHA_NUM:return 9;case QRMode.MODE_8BIT_BYTE:return 8;case QRMode.MODE_KANJI:return 8;default:throw"mode:"+Ou}else if(Mu<27)switch(Ou){case QRMode.MODE_NUMBER:return 12;case QRMode.MODE_ALPHA_NUM:return 11;case QRMode.MODE_8BIT_BYTE:return 16;case QRMode.MODE_KANJI:return 10;default:throw"mode:"+Ou}else if(Mu<41)switch(Ou){case QRMode.MODE_NUMBER:return 14;case QRMode.MODE_ALPHA_NUM:return 13;case QRMode.MODE_8BIT_BYTE:return 16;case QRMode.MODE_KANJI:return 12;default:throw"mode:"+Ou}else throw"type:"+Mu},Iu.getLostPoint=function(Ou){const Mu=Ou.getModuleCount();let Du=0;for(let ju=0;ju<Mu;ju+=1)for(let Fu=0;Fu<Mu;Fu+=1){let zu=0;const Uu=Ou.isDark(ju,Fu);for(let Hu=-1;Hu<=1;Hu+=1)if(!(ju+Hu<0||Mu<=ju+Hu))for(let Vu=-1;Vu<=1;Vu+=1)Fu+Vu<0||Mu<=Fu+Vu||Hu==0&&Vu==0||Uu==Ou.isDark(ju+Hu,Fu+Vu)&&(zu+=1);zu>5&&(Du+=3+zu-5)}for(let ju=0;ju<Mu-1;ju+=1)for(let Fu=0;Fu<Mu-1;Fu+=1){let zu=0;Ou.isDark(ju,Fu)&&(zu+=1),Ou.isDark(ju+1,Fu)&&(zu+=1),Ou.isDark(ju,Fu+1)&&(zu+=1),Ou.isDark(ju+1,Fu+1)&&(zu+=1),(zu==0||zu==4)&&(Du+=3)}for(let ju=0;ju<Mu;ju+=1)for(let Fu=0;Fu<Mu-6;Fu+=1)Ou.isDark(ju,Fu)&&!Ou.isDark(ju,Fu+1)&&Ou.isDark(ju,Fu+2)&&Ou.isDark(ju,Fu+3)&&Ou.isDark(ju,Fu+4)&&!Ou.isDark(ju,Fu+5)&&Ou.isDark(ju,Fu+6)&&(Du+=40);for(let ju=0;ju<Mu;ju+=1)for(let Fu=0;Fu<Mu-6;Fu+=1)Ou.isDark(Fu,ju)&&!Ou.isDark(Fu+1,ju)&&Ou.isDark(Fu+2,ju)&&Ou.isDark(Fu+3,ju)&&Ou.isDark(Fu+4,ju)&&!Ou.isDark(Fu+5,ju)&&Ou.isDark(Fu+6,ju)&&(Du+=40);let Lu=0;for(let ju=0;ju<Mu;ju+=1)for(let Fu=0;Fu<Mu;Fu+=1)Ou.isDark(Fu,ju)&&(Lu+=1);const Bu=Math.abs(100*Lu/Mu/Mu-50)/5;return Du+=Bu*10,Du},Iu})(),QRMath=(function(){const Au=new Array(256),lo=new Array(256);for(let Ru=0;Ru<8;Ru+=1)Au[Ru]=1<<Ru;for(let Ru=8;Ru<256;Ru+=1)Au[Ru]=Au[Ru-4]^Au[Ru-5]^Au[Ru-6]^Au[Ru-8];for(let Ru=0;Ru<255;Ru+=1)lo[Au[Ru]]=Ru;const $u={};return $u.glog=function(Ru){if(Ru<1)throw"glog("+Ru+")";return lo[Ru]},$u.gexp=function(Ru){for(;Ru<0;)Ru+=255;for(;Ru>=256;)Ru-=255;return Au[Ru]},$u})(),qrPolynomial=function(Au,lo){if(typeof Au.length>"u")throw Au.length+"/"+lo;const $u=(function(){let Iu=0;for(;Iu<Au.length&&Au[Iu]==0;)Iu+=1;const Pu=new Array(Au.length-Iu+lo);for(let Ou=0;Ou<Au.length-Iu;Ou+=1)Pu[Ou]=Au[Ou+Iu];return Pu})(),Ru={};return Ru.getAt=function(Iu){return $u[Iu]},Ru.getLength=function(){return $u.length},Ru.multiply=function(Iu){const Pu=new Array(Ru.getLength()+Iu.getLength()-1);for(let Ou=0;Ou<Ru.getLength();Ou+=1)for(let Mu=0;Mu<Iu.getLength();Mu+=1)Pu[Ou+Mu]^=QRMath.gexp(QRMath.glog(Ru.getAt(Ou))+QRMath.glog(Iu.getAt(Mu)));return qrPolynomial(Pu,0)},Ru.mod=function(Iu){if(Ru.getLength()-Iu.getLength()<0)return Ru;const Pu=QRMath.glog(Ru.getAt(0))-QRMath.glog(Iu.getAt(0)),Ou=new Array(Ru.getLength());for(let Mu=0;Mu<Ru.getLength();Mu+=1)Ou[Mu]=Ru.getAt(Mu);for(let Mu=0;Mu<Iu.getLength();Mu+=1)Ou[Mu]^=QRMath.gexp(QRMath.glog(Iu.getAt(Mu))+Pu);return qrPolynomial(Ou,0).mod(Iu)},Ru},QRRSBlock=(function(){const Au=[[1,26,19],[1,26,16],[1,26,13],[1,26,9],[1,44,34],[1,44,28],[1,44,22],[1,44,16],[1,70,55],[1,70,44],[2,35,17],[2,35,13],[1,100,80],[2,50,32],[2,50,24],[4,25,9],[1,134,108],[2,67,43],[2,33,15,2,34,16],[2,33,11,2,34,12],[2,86,68],[4,43,27],[4,43,19],[4,43,15],[2,98,78],[4,49,31],[2,32,14,4,33,15],[4,39,13,1,40,14],[2,121,97],[2,60,38,2,61,39],[4,40,18,2,41,19],[4,40,14,2,41,15],[2,146,116],[3,58,36,2,59,37],[4,36,16,4,37,17],[4,36,12,4,37,13],[2,86,68,2,87,69],[4,69,43,1,70,44],[6,43,19,2,44,20],[6,43,15,2,44,16],[4,101,81],[1,80,50,4,81,51],[4,50,22,4,51,23],[3,36,12,8,37,13],[2,116,92,2,117,93],[6,58,36,2,59,37],[4,46,20,6,47,21],[7,42,14,4,43,15],[4,133,107],[8,59,37,1,60,38],[8,44,20,4,45,21],[12,33,11,4,34,12],[3,145,115,1,146,116],[4,64,40,5,65,41],[11,36,16,5,37,17],[11,36,12,5,37,13],[5,109,87,1,110,88],[5,65,41,5,66,42],[5,54,24,7,55,25],[11,36,12,7,37,13],[5,122,98,1,123,99],[7,73,45,3,74,46],[15,43,19,2,44,20],[3,45,15,13,46,16],[1,135,107,5,136,108],[10,74,46,1,75,47],[1,50,22,15,51,23],[2,42,14,17,43,15],[5,150,120,1,151,121],[9,69,43,4,70,44],[17,50,22,1,51,23],[2,42,14,19,43,15],[3,141,113,4,142,114],[3,70,44,11,71,45],[17,47,21,4,48,22],[9,39,13,16,40,14],[3,135,107,5,136,108],[3,67,41,13,68,42],[15,54,24,5,55,25],[15,43,15,10,44,16],[4,144,116,4,145,117],[17,68,42],[17,50,22,6,51,23],[19,46,16,6,47,17],[2,139,111,7,140,112],[17,74,46],[7,54,24,16,55,25],[34,37,13],[4,151,121,5,152,122],[4,75,47,14,76,48],[11,54,24,14,55,25],[16,45,15,14,46,16],[6,147,117,4,148,118],[6,73,45,14,74,46],[11,54,24,16,55,25],[30,46,16,2,47,17],[8,132,106,4,133,107],[8,75,47,13,76,48],[7,54,24,22,55,25],[22,45,15,13,46,16],[10,142,114,2,143,115],[19,74,46,4,75,47],[28,50,22,6,51,23],[33,46,16,4,47,17],[8,152,122,4,153,123],[22,73,45,3,74,46],[8,53,23,26,54,24],[12,45,15,28,46,16],[3,147,117,10,148,118],[3,73,45,23,74,46],[4,54,24,31,55,25],[11,45,15,31,46,16],[7,146,116,7,147,117],[21,73,45,7,74,46],[1,53,23,37,54,24],[19,45,15,26,46,16],[5,145,115,10,146,116],[19,75,47,10,76,48],[15,54,24,25,55,25],[23,45,15,25,46,16],[13,145,115,3,146,116],[2,74,46,29,75,47],[42,54,24,1,55,25],[23,45,15,28,46,16],[17,145,115],[10,74,46,23,75,47],[10,54,24,35,55,25],[19,45,15,35,46,16],[17,145,115,1,146,116],[14,74,46,21,75,47],[29,54,24,19,55,25],[11,45,15,46,46,16],[13,145,115,6,146,116],[14,74,46,23,75,47],[44,54,24,7,55,25],[59,46,16,1,47,17],[12,151,121,7,152,122],[12,75,47,26,76,48],[39,54,24,14,55,25],[22,45,15,41,46,16],[6,151,121,14,152,122],[6,75,47,34,76,48],[46,54,24,10,55,25],[2,45,15,64,46,16],[17,152,122,4,153,123],[29,74,46,14,75,47],[49,54,24,10,55,25],[24,45,15,46,46,16],[4,152,122,18,153,123],[13,74,46,32,75,47],[48,54,24,14,55,25],[42,45,15,32,46,16],[20,147,117,4,148,118],[40,75,47,7,76,48],[43,54,24,22,55,25],[10,45,15,67,46,16],[19,148,118,6,149,119],[18,75,47,31,76,48],[34,54,24,34,55,25],[20,45,15,61,46,16]],lo=function(Iu,Pu){const Ou={};return Ou.totalCount=Iu,Ou.dataCount=Pu,Ou},$u={},Ru=function(Iu,Pu){switch(Pu){case QRErrorCorrectionLevel.L:return Au[(Iu-1)*4+0];case QRErrorCorrectionLevel.M:return Au[(Iu-1)*4+1];case QRErrorCorrectionLevel.Q:return Au[(Iu-1)*4+2];case QRErrorCorrectionLevel.H:return Au[(Iu-1)*4+3];default:return}};return $u.getRSBlocks=function(Iu,Pu){const Ou=Ru(Iu,Pu);if(typeof Ou>"u")throw"bad rs block @ typeNumber:"+Iu+"/errorCorrectionLevel:"+Pu;const Mu=Ou.length/3,Du=[];for(let Lu=0;Lu<Mu;Lu+=1){const Bu=Ou[Lu*3+0],ju=Ou[Lu*3+1],Fu=Ou[Lu*3+2];for(let zu=0;zu<Bu;zu+=1)Du.push(lo(ju,Fu))}return Du},$u})(),qrBitBuffer=function(){const Au=[];let lo=0;const $u={};return $u.getBuffer=function(){return Au},$u.getAt=function(Ru){const Iu=Math.floor(Ru/8);return(Au[Iu]>>>7-Ru%8&1)==1},$u.put=function(Ru,Iu){for(let Pu=0;Pu<Iu;Pu+=1)$u.putBit((Ru>>>Iu-Pu-1&1)==1)},$u.getLengthInBits=function(){return lo},$u.putBit=function(Ru){const Iu=Math.floor(lo/8);Au.length<=Iu&&Au.push(0),Ru&&(Au[Iu]|=128>>>lo%8),lo+=1},$u},qrNumber=function(Au){const lo=QRMode.MODE_NUMBER,$u=Au,Ru={};Ru.getMode=function(){return lo},Ru.getLength=function(Ou){return $u.length},Ru.write=function(Ou){const Mu=$u;let Du=0;for(;Du+2<Mu.length;)Ou.put(Iu(Mu.substring(Du,Du+3)),10),Du+=3;Du<Mu.length&&(Mu.length-Du==1?Ou.put(Iu(Mu.substring(Du,Du+1)),4):Mu.length-Du==2&&Ou.put(Iu(Mu.substring(Du,Du+2)),7))};const Iu=function(Ou){let Mu=0;for(let Du=0;Du<Ou.length;Du+=1)Mu=Mu*10+Pu(Ou.charAt(Du));return Mu},Pu=function(Ou){if("0"<=Ou&&Ou<="9")return Ou.charCodeAt(0)-48;throw"illegal char :"+Ou};return Ru},qrAlphaNum=function(Au){const lo=QRMode.MODE_ALPHA_NUM,$u=Au,Ru={};Ru.getMode=function(){return lo},Ru.getLength=function(Pu){return $u.length},Ru.write=function(Pu){const Ou=$u;let Mu=0;for(;Mu+1<Ou.length;)Pu.put(Iu(Ou.charAt(Mu))*45+Iu(Ou.charAt(Mu+1)),11),Mu+=2;Mu<Ou.length&&Pu.put(Iu(Ou.charAt(Mu)),6)};const Iu=function(Pu){if("0"<=Pu&&Pu<="9")return Pu.charCodeAt(0)-48;if("A"<=Pu&&Pu<="Z")return Pu.charCodeAt(0)-65+10;switch(Pu){case" ":return 36;case"$":return 37;case"%":return 38;case"*":return 39;case"+":return 40;case"-":return 41;case".":return 42;case"/":return 43;case":":return 44;default:throw"illegal char :"+Pu}};return Ru},qr8BitByte=function(Au){const lo=QRMode.MODE_8BIT_BYTE,$u=qrcode.stringToBytes(Au),Ru={};return Ru.getMode=function(){return lo},Ru.getLength=function(Iu){return $u.length},Ru.write=function(Iu){for(let Pu=0;Pu<$u.length;Pu+=1)Iu.put($u[Pu],8)},Ru},qrKanji=function(Au){const lo=QRMode.MODE_KANJI,$u=qrcode.stringToBytes;(function(Pu,Ou){const Mu=$u(Pu);if(Mu.length!=2||(Mu[0]<<8|Mu[1])!=Ou)throw"sjis not supported."})("友",38726);const Ru=$u(Au),Iu={};return Iu.getMode=function(){return lo},Iu.getLength=function(Pu){return~~(Ru.length/2)},Iu.write=function(Pu){const Ou=Ru;let Mu=0;for(;Mu+1<Ou.length;){let Du=(255&Ou[Mu])<<8|255&Ou[Mu+1];if(33088<=Du&&Du<=40956)Du-=33088;else if(57408<=Du&&Du<=60351)Du-=49472;else throw"illegal char at "+(Mu+1)+"/"+Du;Du=(Du>>>8&255)*192+(Du&255),Pu.put(Du,13),Mu+=2}if(Mu<Ou.length)throw"illegal char at "+(Mu+1)},Iu},byteArrayOutputStream=function(){const Au=[],lo={};return lo.writeByte=function($u){Au.push($u&255)},lo.writeShort=function($u){lo.writeByte($u),lo.writeByte($u>>>8)},lo.writeBytes=function($u,Ru,Iu){Ru=Ru||0,Iu=Iu||$u.length;for(let Pu=0;Pu<Iu;Pu+=1)lo.writeByte($u[Pu+Ru])},lo.writeString=function($u){for(let Ru=0;Ru<$u.length;Ru+=1)lo.writeByte($u.charCodeAt(Ru))},lo.toByteArray=function(){return Au},lo.toString=function(){let $u="";$u+="[";for(let Ru=0;Ru<Au.length;Ru+=1)Ru>0&&($u+=","),$u+=Au[Ru];return $u+="]",$u},lo},base64EncodeOutputStream=function(){let Au=0,lo=0,$u=0,Ru="";const Iu={},Pu=function(Mu){Ru+=String.fromCharCode(Ou(Mu&63))},Ou=function(Mu){if(Mu<0)throw"n:"+Mu;if(Mu<26)return 65+Mu;if(Mu<52)return 97+(Mu-26);if(Mu<62)return 48+(Mu-52);if(Mu==62)return 43;if(Mu==63)return 47;throw"n:"+Mu};return Iu.writeByte=function(Mu){for(Au=Au<<8|Mu&255,lo+=8,$u+=1;lo>=6;)Pu(Au>>>lo-6),lo-=6},Iu.flush=function(){if(lo>0&&(Pu(Au<<6-lo),Au=0,lo=0),$u%3!=0){const Mu=3-$u%3;for(let Du=0;Du<Mu;Du+=1)Ru+="="}},Iu.toString=function(){return Ru},Iu},base64DecodeInputStream=function(Au){const lo=Au;let $u=0,Ru=0,Iu=0;const Pu={};Pu.read=function(){for(;Iu<8;){if($u>=lo.length){if(Iu==0)return-1;throw"unexpected end of file./"+Iu}const Du=lo.charAt($u);if($u+=1,Du=="=")return Iu=0,-1;if(Du.match(/^\s$/))continue;Ru=Ru<<6|Ou(Du.charCodeAt(0)),Iu+=6}const Mu=Ru>>>Iu-8&255;return Iu-=8,Mu};const Ou=function(Mu){if(65<=Mu&&Mu<=90)return Mu-65;if(97<=Mu&&Mu<=122)return Mu-97+26;if(48<=Mu&&Mu<=57)return Mu-48+52;if(Mu==43)return 62;if(Mu==47)return 63;throw"c:"+Mu};return Pu},gifImage=function(Au,lo){const $u=Au,Ru=lo,Iu=new Array(Au*lo),Pu={};Pu.setPixel=function(Lu,Bu,ju){Iu[Bu*$u+Lu]=ju},Pu.write=function(Lu){Lu.writeString("GIF87a"),Lu.writeShort($u),Lu.writeShort(Ru),Lu.writeByte(128),Lu.writeByte(0),Lu.writeByte(0),Lu.writeByte(0),Lu.writeByte(0),Lu.writeByte(0),Lu.writeByte(255),Lu.writeByte(255),Lu.writeByte(255),Lu.writeString(","),Lu.writeShort(0),Lu.writeShort(0),Lu.writeShort($u),Lu.writeShort(Ru),Lu.writeByte(0);const Bu=2,ju=Mu(Bu);Lu.writeByte(Bu);let Fu=0;for(;ju.length-Fu>255;)Lu.writeByte(255),Lu.writeBytes(ju,Fu,255),Fu+=255;Lu.writeByte(ju.length-Fu),Lu.writeBytes(ju,Fu,ju.length-Fu),Lu.writeByte(0),Lu.writeString(";")};const Ou=function(Lu){const Bu=Lu;let ju=0,Fu=0;const zu={};return zu.write=function(Uu,Hu){if(Uu>>>Hu)throw"length over";for(;ju+Hu>=8;)Bu.writeByte(255&(Uu<<ju|Fu)),Hu-=8-ju,Uu>>>=8-ju,Fu=0,ju=0;Fu=Uu<<ju|Fu,ju=ju+Hu},zu.flush=function(){ju>0&&Bu.writeByte(Fu)},zu},Mu=function(Lu){const Bu=1<<Lu,ju=(1<<Lu)+1;let Fu=Lu+1;const zu=Du();for(let Wu=0;Wu<Bu;Wu+=1)zu.add(String.fromCharCode(Wu));zu.add(String.fromCharCode(Bu)),zu.add(String.fromCharCode(ju));const Uu=byteArrayOutputStream(),Hu=Ou(Uu);Hu.write(Bu,Fu);let Vu=0,Gu=String.fromCharCode(Iu[Vu]);for(Vu+=1;Vu<Iu.length;){const Wu=String.fromCharCode(Iu[Vu]);Vu+=1,zu.contains(Gu+Wu)?Gu=Gu+Wu:(Hu.write(zu.indexOf(Gu),Fu),zu.size()<4095&&(zu.size()==1<<Fu&&(Fu+=1),zu.add(Gu+Wu)),Gu=Wu)}return Hu.write(zu.indexOf(Gu),Fu),Hu.write(ju,Fu),Hu.flush(),Uu.toByteArray()},Du=function(){const Lu={};let Bu=0;const ju={};return ju.add=function(Fu){if(ju.contains(Fu))throw"dup key:"+Fu;Lu[Fu]=Bu,Bu+=1},ju.size=function(){return Bu},ju.indexOf=function(Fu){return Lu[Fu]},ju.contains=function(Fu){return typeof Lu[Fu]<"u"},ju};return Pu},createDataURL=function(Au,lo,$u){const Ru=gifImage(Au,lo);for(let Mu=0;Mu<lo;Mu+=1)for(let Du=0;Du<Au;Du+=1)Ru.setPixel(Du,Mu,$u(Du,Mu));const Iu=byteArrayOutputStream();Ru.write(Iu);const Pu=base64EncodeOutputStream(),Ou=Iu.toByteArray();for(let Mu=0;Mu<Ou.length;Mu+=1)Pu.writeByte(Ou[Mu]);return Pu.flush(),"data:image/gif;base64,"+Pu};qrcode.stringToBytes;function _extends(){return _extends=Object.assign?Object.assign.bind():function(Au){for(var lo=1;lo<arguments.length;lo++){var $u=arguments[lo];for(var Ru in $u)({}).hasOwnProperty.call($u,Ru)&&(Au[Ru]=$u[Ru])}return Au},_extends.apply(null,arguments)}function _objectWithoutProperties(Au,lo){if(Au==null)return{};var $u,Ru,Iu=_objectWithoutPropertiesLoose(Au,lo);if(Object.getOwnPropertySymbols){var Pu=Object.getOwnPropertySymbols(Au);for(Ru=0;Ru<Pu.length;Ru++)$u=Pu[Ru],lo.indexOf($u)===-1&&{}.propertyIsEnumerable.call(Au,$u)&&(Iu[$u]=Au[$u])}return Iu}function _objectWithoutPropertiesLoose(Au,lo){if(Au==null)return{};var $u={};for(var Ru in Au)if({}.hasOwnProperty.call(Au,Ru)){if(lo.indexOf(Ru)!==-1)continue;$u[Ru]=Au[Ru]}return $u}var _excluded$1=["bgColor","bgD","fgD","fgColor","size","title","viewBoxSize","xmlns"],propTypes$1={bgColor:s$5.oneOfType([s$5.object,s$5.string]).isRequired,bgD:s$5.string.isRequired,fgColor:s$5.oneOfType([s$5.object,s$5.string]).isRequired,fgD:s$5.string.isRequired,size:s$5.number.isRequired,title:s$5.string,viewBoxSize:s$5.number.isRequired,xmlns:s$5.string},QRCodeSvg=reactExports.forwardRef(function(Au,lo){var $u=Au.bgColor,Ru=Au.bgD,Iu=Au.fgD,Pu=Au.fgColor,Ou=Au.size,Mu=Au.title,Du=Au.viewBoxSize,Lu=Au.xmlns,Bu=Lu===void 0?"http://www.w3.org/2000/svg":Lu,ju=_objectWithoutProperties(Au,_excluded$1);return vM.createElement("svg",_extends({},ju,{height:Ou,ref:lo,viewBox:"0 0 ".concat(Du," ").concat(Du),width:Ou,xmlns:Bu}),Mu?vM.createElement("title",null,Mu):null,vM.createElement("path",{d:Ru,fill:$u}),vM.createElement("path",{d:Iu,fill:Pu}))});QRCodeSvg.displayName="QRCodeSvg";QRCodeSvg.propTypes=propTypes$1;var _excluded=["bgColor","fgColor","level","size","value"];qrcode.stringToBytes=function(Au){return Array.from(new TextEncoder().encode(Au))};var propTypes={bgColor:s$5.oneOfType([s$5.object,s$5.string]),fgColor:s$5.oneOfType([s$5.object,s$5.string]),level:s$5.string,size:s$5.number,value:s$5.string.isRequired},QRCode=reactExports.forwardRef(function(Au,lo){var $u=Au.bgColor,Ru=$u===void 0?"#FFFFFF":$u,Iu=Au.fgColor,Pu=Iu===void 0?"#000000":Iu,Ou=Au.level,Mu=Ou===void 0?"L":Ou,Du=Au.size,Lu=Du===void 0?256:Du,Bu=Au.value,ju=_objectWithoutProperties(Au,_excluded),Fu=qrcode(0,Mu);Fu.addData(Bu),Fu.make();var zu=Fu.getModuleCount(),Uu=Array.from({length:zu},function(Hu,Vu){return Array.from({length:zu},function(Gu,Wu){return Fu.isDark(Vu,Wu)})});return vM.createElement(QRCodeSvg,_extends({},ju,{bgColor:Ru,bgD:Uu.map(function(Hu,Vu){return Hu.map(function(Gu,Wu){return Gu?"":"M ".concat(Wu," ").concat(Vu," l 1 0 0 1 -1 0 Z")}).join(" ")}).join(" "),fgColor:Pu,fgD:Uu.map(function(Hu,Vu){return Hu.map(function(Gu,Wu){return Gu?"M ".concat(Wu," ").concat(Vu," l 1 0 0 1 -1 0 Z"):""}).join(" ")}).join(" "),ref:lo,size:Lu,viewBoxSize:zu}))});QRCode.displayName="QRCode";QRCode.propTypes=propTypes;function PapSignInCard({context:Au,send:lo}){const[$u,Ru]=reactExports.useState(!1),[Iu,Pu]=reactExports.useState(!1),[Ou,Mu]=reactExports.useState(null),Du=Au.status==="complete"?readPapSignIn(Au.result):null,Lu=Du&&!("refused"in Du)&&Du.mode==="direct"?Du.company??"":"";if(reactExports.useEffect(()=>{if(!Lu||typeof BroadcastChannel>"u")return;const zu=new BroadcastChannel(PAP_SIGN_IN_CHANNEL);return zu.onmessage=Uu=>{const Hu=signInReturnOf(Uu.data,Lu);Hu&&(Mu(Hu),zu.close())},()=>zu.close()},[Lu]),reactExports.useEffect(()=>{Ou==="signed_in"&&lo&&!Iu&&Pu(lo(PAP_SIGN_IN_WORDS.checkMessage(Lu)))},[Ou,lo,Iu,Lu]),!Du)return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:Au.defaultUI});if("refused"in Du)return jsxRuntimeExports.jsx(Flash,{variant:"danger",role:"alert",sx:{my:2},children:Du.refused});const Bu=async()=>{try{await navigator.clipboard.writeText(Du.code??""),Ru(!0)}catch{Ru(!1)}},ju=Du.company??Du.host,Fu=Du.mode==="mediated"?PAP_SIGN_IN_WORDS.mediatedTitle(Du.host):PAP_SIGN_IN_WORDS.title(ju);return jsxRuntimeExports.jsxs(Box,{as:"section","aria-label":Fu,my:2,p:3,border:"1px solid",borderColor:"border.default",borderRadius:2,bg:"canvas.subtle",maxWidth:480,children:[jsxRuntimeExports.jsx(Heading$2,{as:"h4",sx:{fontSize:2,mb:1},children:Fu}),jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{mt:0,mb:2,color:"fg.muted",fontSize:1},children:Du.mode==="device"?PAP_SIGN_IN_WORDS.device:Du.mode==="mediated"?PAP_SIGN_IN_WORDS.mediated:PAP_SIGN_IN_WORDS.direct}),Du.needs?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{mt:0,mb:2,fontSize:1},children:PAP_SIGN_IN_WORDS.needs(Du.needs)}):null,Du.sentTo?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{mt:0,mb:2,fontSize:1},children:PAP_SIGN_IN_WORDS.sentTo(Du.sentTo)}):null,Du.code?jsxRuntimeExports.jsxs(Box,{display:"flex",gap:3,alignItems:"center",flexWrap:"wrap",mb:2,children:[jsxRuntimeExports.jsxs(Box,{children:[jsxRuntimeExports.jsx(Text$3,{as:"div",sx:{fontSize:0,color:"fg.muted"},children:PAP_SIGN_IN_WORDS.code}),jsxRuntimeExports.jsx(Text$3,{as:"div","aria-live":"polite",sx:{fontFamily:"mono",fontSize:5,fontWeight:"bold",letterSpacing:"0.15em"},children:Du.code}),jsxRuntimeExports.jsx(ButtonComponent,{size:"small",leadingVisual:CopyIcon,onClick:()=>{Bu()},children:$u?PAP_SIGN_IN_WORDS.copied:PAP_SIGN_IN_WORDS.copy})]}),jsxRuntimeExports.jsx(Box,{bg:"#ffffff",p:2,borderRadius:2,lineHeight:0,children:jsxRuntimeExports.jsx(QRCode,{value:Du.open,size:112,title:PAP_SIGN_IN_WORDS.qr(Du.host)})})]}):null,jsxRuntimeExports.jsxs(Box,{display:"flex",gap:2,flexWrap:"wrap",alignItems:"center",children:[jsxRuntimeExports.jsx(ButtonComponent,{as:"a",href:Du.open,target:"_blank",rel:"noopener noreferrer",variant:"primary",trailingVisual:LinkExternalIcon,children:PAP_SIGN_IN_WORDS.open(ju)}),lo?jsxRuntimeExports.jsx(ButtonComponent,{disabled:Iu,onClick:()=>Pu(lo(PAP_SIGN_IN_WORDS.checkMessage(ju))),children:PAP_SIGN_IN_WORDS.checkAgain}):null]}),Ou?jsxRuntimeExports.jsx(Text$3,{as:"p",role:"status",sx:{mt:2,mb:0,fontSize:1},children:PAP_SIGN_IN_WORDS.returned[Ou](ju)}):null,Du.expiresAt?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{mt:2,mb:0,fontSize:0,color:"fg.muted"},children:PAP_SIGN_IN_WORDS.until(Du.expiresAt)}):null,lo?null:jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{mt:1,mb:0,fontSize:1},children:PAP_SIGN_IN_WORDS.tellMe})]})}const PAP_SIGN_IN_PLUGIN_NAME="@datalayer/loop-plugin-pap-sign-in",PAP_SIGN_IN_TYPE="application/vnd.datalayer.pap.sign-in+json";function resultOf(Au,lo){const $u=Au.data??{};return"toolName"in $u?lo?.result:{status:"waiting_for_the_person",...$u}}function createPapSignInPlugin(){let Au;const lo=Pu=>Au?!Au(Pu):!1;function $u({workspace:Pu}){const Ou=Pu?.viewControls.send;return reactExports.useEffect(()=>(Au=Ou,()=>{Au===Ou&&(Au=void 0)}),[Ou]),null}function Ru({display:Pu,context:Ou}){const Mu=resultOf(Pu,Ou);return reactExports.createElement(PapSignInCard,{key:Pu.id,context:Ou?{...Ou,result:Mu}:{toolCallId:Pu.id,toolName:"pap_sign_in",name:"pap_sign_in",args:{},status:"complete",result:Mu},send:Au?lo:void 0})}return{name:PAP_SIGN_IN_PLUGIN_NAME,displayName:"Sign in at a company",description:"The company’s page, the code and until when, where the agent asks the person to sign in.",octicon:"sign-in",emoji:"🔑",contributes:[contribution(Renderers,defineRenderer({type:PAP_SIGN_IN_TYPE,component:Ru}),{id:"pap-sign-in"}),contribution(ToolBindings,{tool:PAP_SIGN_IN_TOOL,type:PAP_SIGN_IN_TYPE},{id:"pap-sign-in"})],build(){return{components:[{slot:LoopSlots.chatHeader,id:"pap-sign-in",Component:$u}]}}}}const PapSignInPlugin=createPapSignInPlugin(),COLOURS={context:{bg:"transparent",fg:"fg.muted",sign:" "},add:{bg:"success.subtle",fg:"success.fg",sign:"+"},remove:{bg:"danger.subtle",fg:"danger.fg",sign:"-"}};function DiffCard({display:Au}){const lo=unifiedDiffLines(Au.oldText,Au.newText);return jsxRuntimeExports.jsxs(Box,{"data-shield-display":"diff","data-language":Au.language,sx:{width:"100%",border:"1px solid",borderColor:"border.default",borderRadius:2,overflow:"hidden",fontSize:0},children:[jsxRuntimeExports.jsxs(Box,{sx:{px:2,py:1,bg:"canvas.subtle",borderBottom:"1px solid",borderColor:"border.default",display:"flex",justifyContent:"space-between"},children:[jsxRuntimeExports.jsx(Text$3,{sx:{fontFamily:"mono",fontWeight:"bold"},children:Au.path}),jsxRuntimeExports.jsx(Text$3,{sx:{color:"fg.muted"},children:displayLine(Au)})]}),jsxRuntimeExports.jsx(Box,{as:"pre",className:`language-${Au.language}`,sx:{m:0,overflowX:"auto",fontFamily:"mono"},children:lo.map(($u,Ru)=>jsxRuntimeExports.jsxs(Box,{as:"span","data-diff-line":$u.kind,sx:{display:"block",px:2,bg:COLOURS[$u.kind].bg,color:COLOURS[$u.kind].fg,whiteSpace:"pre"},children:[COLOURS[$u.kind].sign,$u.text]},Ru))})]})}function TerminalCard({display:Au}){const lo=Au.exitCode!==null&&Au.exitCode!==0;return jsxRuntimeExports.jsxs(Box,{"data-shield-display":"terminal","data-exit-code":Au.exitCode===null?"running":Au.exitCode,sx:{width:"100%",border:"1px solid",borderColor:lo?"danger.muted":"border.default",borderRadius:2,overflow:"hidden",fontSize:0},children:[jsxRuntimeExports.jsxs(Box,{sx:{px:2,py:1,bg:"canvas.subtle",borderBottom:"1px solid",borderColor:"border.default",display:"flex",justifyContent:"space-between"},children:[jsxRuntimeExports.jsx(Text$3,{sx:{fontFamily:"mono",fontWeight:"bold"},children:Au.command?`$ ${Au.command}`:Au.terminalId}),jsxRuntimeExports.jsx(Text$3,{sx:{color:lo?"danger.fg":"fg.muted"},children:displayLine(Au)})]}),jsxRuntimeExports.jsx(Box,{as:"pre",sx:{m:0,px:2,py:1,overflowX:"auto",fontFamily:"mono",whiteSpace:"pre-wrap",bg:"canvas.default"},children:Au.output||(Au.exitCode===null?"…":"(no output)")})]})}const SHIELD_DISPLAYS_PLUGIN_NAME="@datalayer/loop-plugin-shield-displays";function Diff({display:Au,context:lo}){const $u=protocolDisplayOf(Au);return!$u||$u.kind!=="diff"?reactExports.createElement("span",null,lo?.defaultUI??Au.text):reactExports.createElement(DiffCard,{key:Au.id,display:$u})}function Terminal$1({display:Au,context:lo}){const $u=protocolDisplayOf(Au);return!$u||$u.kind!=="terminal"?reactExports.createElement("span",null,lo?.defaultUI??Au.text):reactExports.createElement(TerminalCard,{key:Au.id,display:$u})}function createShieldDisplaysPlugin(){return{name:SHIELD_DISPLAYS_PLUGIN_NAME,displayName:"Diffs and terminals",description:"What a coding agent changed, as a unified diff, and what it ran, with its output.",octicon:"diff",emoji:"🛡",contributes:[contribution(Renderers,defineRenderer({type:SHIELD_DIFF_TYPE,component:Diff}),{id:"shield-diff"}),contribution(Renderers,defineRenderer({type:SHIELD_TERMINAL_TYPE,component:Terminal$1}),{id:"shield-terminal"})]}}const ShieldDisplaysPlugin=createShieldDisplaysPlugin();function makeViewSwitchAction({viewId:Au,icon:lo,tooltip:$u}){return function(){const Iu=reactExports.useSyncExternalStore(subscribeEditorChoice,()=>getEditorChoice().editorId),Pu=useContributions(LoopEditorView);if(Au!==NONE_EDITOR&&!Pu.some(Mu=>Mu.value.surfaceId===Au))return null;const Ou=(Iu||NONE_EDITOR)===Au;return jsxRuntimeExports.jsx(IconButton,{icon:lo,"aria-label":$u,size:"small",variant:"invisible",onClick:()=>{chooseEditor(Au)||console.warn(`[loop] No chat is on screen to switch to '${Au}'.`)},sx:Ou?{color:"accent.fg"}:void 0})}}function defineViewPlugin(Au){const{key:lo,viewId:$u,displayName:Ru,description:Iu,icon:Pu,tooltip:Ou,order:Mu}=Au,Du=makeViewSwitchAction({viewId:$u,icon:Pu,tooltip:Ou});return{name:`@datalayer/loop-plugin-${lo}-view`,displayName:Ru,description:Iu,octicon:Au.octicon??"eye",emoji:Au.emoji,dependencies:[InputPromptPlugin],build:()=>({components:[{id:`${lo}-view-action`,slot:LoopSlots.promptAction,order:Mu,Component:Du}]})}}const ChatViewPlugin=defineViewPlugin({key:"chat",viewId:NONE_EDITOR,displayName:"Chat view",description:"The conversation on its own, from the composer footer.",icon:CommentDiscussionIcon,tooltip:"Show the chat",octicon:"comment-discussion",emoji:"💬",order:10}),DocumentViewPlugin=defineViewPlugin({key:"document",viewId:"document",displayName:"Document view",description:"The document beside the chat, from the composer footer.",icon:FileIcon,tooltip:"Show the document",octicon:"file",emoji:"📄",order:12}),NotebookViewPlugin=defineViewPlugin({key:"notebook",viewId:"notebook",displayName:"Notebook view",description:"The notebook beside the chat, from the composer footer.",icon:RowsIcon,tooltip:"Show the notebook",octicon:"rows",emoji:"📓",order:11}),STYLE_ELEMENT_ID="datalayer-reactor-commands-style",PALETTE_CSS=`
|
|
3855
3858
|
/*
|
|
3856
3859
|
* Colours live on the panel as variables with light defaults, and the dark
|
|
3857
3860
|
* values are applied by whichever signal the host actually uses:
|
|
@@ -4010,7 +4013,7 @@ ${Mu}`:ju,inputs:Mu,clear:Ou?[]:[DRAFT.path],loop:Lu()}:{refused:"Nothing to sen
|
|
|
4010
4013
|
}
|
|
4011
4014
|
`;function usePaletteStyles(){reactExports.useEffect(()=>{if(typeof document>"u"||document.getElementById(STYLE_ELEMENT_ID))return;const Au=document.createElement("style");Au.id=STYLE_ELEMENT_ID,Au.textContent=PALETTE_CSS,document.head.appendChild(Au)},[])}function rank(Au,lo){if(!lo)return{command:Au,score:0};const $u=lo.toLowerCase(),Ru=[[Au.name.toLowerCase(),0],[Au.id.toLowerCase(),100],[(Au.category??"").toLowerCase(),200],[(Au.description??"").toLowerCase(),300]];for(const[Iu,Pu]of Ru){const Ou=Iu.indexOf($u);if(Ou>=0)return{command:Au,score:Pu+Ou}}return null}const PRIMER_PORTAL_ROOT_ID="__primerPortalRoot__";function paletteRoot(){return document.getElementById(PRIMER_PORTAL_ROOT_ID)??document.body}const LIST_ID="dla-cmdk-list",optionId=Au=>`dla-cmdk-option-${Au}`,PALETTE_KEYBINDING="Mod+K",PALETTE_CHORD=parseKeybinding(PALETTE_KEYBINDING);function CommandPalette(){const Au=useReactorPlatform(),lo=useCommands();usePaletteStyles();const[$u,Ru]=reactExports.useState(!1),[Iu,Pu]=reactExports.useState(""),[Ou,Mu]=reactExports.useState(0),[Du,Lu]=reactExports.useState(null),[Bu,ju]=reactExports.useState(null),Fu=reactExports.useRef(null),zu=reactExports.useMemo(()=>lo.map(Wu=>rank(Wu,Iu)).filter(Wu=>Wu!==null).sort((Wu,Ku)=>Wu.score-Ku.score).map(Wu=>Wu.command),[lo,Iu]),Uu=reactExports.useCallback(()=>{Ru(!1),Pu(""),Mu(0),ju(null)},[]),Hu=reactExports.useCallback(async Wu=>{Lu(Wu.id),ju(null);try{await Au.executeCommand(Wu.id),Uu()}catch(Ku){ju(Ku instanceof Error?Ku.message:String(Ku))}finally{Lu(null)}},[Uu,Au]);if(reactExports.useEffect(()=>{const Wu=lo.map(Yu=>{const Xu=Yu.keybinding?parseKeybinding(Yu.keybinding):null;return Xu?{chord:Xu,id:Yu.id}:null}).filter(Yu=>Yu!==null),Ku=isApplePlatform();function Ju(Yu){if(PALETTE_CHORD&&matchesKeybinding(Yu,PALETTE_CHORD,Ku)){Yu.preventDefault(),Yu.stopPropagation(),Ru(Xu=>!Xu);return}if(Yu.key==="Escape"){Ru(Xu=>Xu&&!1);return}if(!$u){for(const Xu of Wu)if(matchesKeybinding(Yu,Xu.chord,Ku)){Yu.preventDefault(),Yu.stopPropagation();const ed=Au.getCommand(Xu.id);ed&&ed.isEnabled?.()!==!1&&Au.executeCommand(Xu.id).catch(td=>{console.error(`Command ${Xu.id} failed`,td)});return}}}return document.addEventListener("keydown",Ju,{capture:!0}),()=>document.removeEventListener("keydown",Ju,{capture:!0})},[lo,$u,Au]),reactExports.useEffect(()=>{if(!$u)return;Pu(""),Mu(0),ju(null);const Wu=window.requestAnimationFrame(()=>Fu.current?.focus());return()=>window.cancelAnimationFrame(Wu)},[$u]),reactExports.useEffect(()=>{Mu(Wu=>Wu>=zu.length?0:Wu)},[zu.length]),!$u||typeof document>"u")return null;const Vu=Wu=>{if(Wu.key==="ArrowDown")Wu.preventDefault(),Mu(Ku=>zu.length===0?0:(Ku+1)%zu.length);else if(Wu.key==="ArrowUp")Wu.preventDefault(),Mu(Ku=>zu.length===0?0:(Ku-1+zu.length)%zu.length);else if(Wu.key==="Enter"){Wu.preventDefault();const Ku=zu[Ou];Ku&&Ku.isEnabled?.()!==!1&&Hu(Ku)}},Gu=jsxRuntimeExports.jsx("div",{className:"dla-cmdk-backdrop",onClick:Uu,children:jsxRuntimeExports.jsxs("div",{className:"dla-cmdk-panel",role:"dialog","aria-modal":"true","aria-label":"Command palette",onClick:Wu=>Wu.stopPropagation(),children:[jsxRuntimeExports.jsx("div",{className:"dla-cmdk-search",children:jsxRuntimeExports.jsx("input",{ref:Fu,className:"dla-cmdk-input",type:"text",placeholder:"Run a command…","aria-label":"Search commands",autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",spellCheck:!1,role:"combobox","aria-expanded":!0,"aria-controls":LIST_ID,"aria-autocomplete":"list","aria-activedescendant":zu.length>0?optionId(Ou):void 0,value:Iu,onChange:Wu=>Pu(Wu.target.value),onKeyDown:Vu})}),Bu!==null&&jsxRuntimeExports.jsx("div",{className:"dla-cmdk-error",children:Bu}),jsxRuntimeExports.jsx("ul",{className:"dla-cmdk-list",id:LIST_ID,role:"listbox",children:zu.length===0?jsxRuntimeExports.jsx("li",{className:"dla-cmdk-empty",children:lo.length===0?"No plugin has registered a command yet.":`Nothing matches “${Iu}”.`}):zu.map((Wu,Ku)=>{const Ju=Wu.isEnabled?.()!==!1;return jsxRuntimeExports.jsx("li",{children:jsxRuntimeExports.jsxs("button",{type:"button",className:"dla-cmdk-item",id:optionId(Ku),role:"option","aria-selected":Ku===Ou,"aria-disabled":!Ju,disabled:!Ju,onMouseEnter:()=>Mu(Ku),onClick:()=>{Hu(Wu)},children:[jsxRuntimeExports.jsx("span",{className:"dla-cmdk-mark","aria-hidden":"true",children:Wu.emoji??"·"}),jsxRuntimeExports.jsxs("span",{className:"dla-cmdk-text",children:[jsxRuntimeExports.jsx("span",{className:"dla-cmdk-name",children:Wu.name}),Wu.description&&jsxRuntimeExports.jsx("p",{className:"dla-cmdk-description",children:Wu.description})]}),Du===Wu.id&&jsxRuntimeExports.jsx("span",{className:"dla-cmdk-meta",children:"running…"}),Wu.keybinding&&jsxRuntimeExports.jsx("kbd",{className:"dla-cmdk-key",children:formatKeybinding(Wu.keybinding)}),Wu.category&&jsxRuntimeExports.jsx("span",{className:"dla-cmdk-meta",children:Wu.category})]})},Wu.id)})}),jsxRuntimeExports.jsxs("div",{className:"dla-cmdk-footer",children:[jsxRuntimeExports.jsxs("span",{children:["↑↓ to move · ↵ to run · esc to close ·"," ",jsxRuntimeExports.jsx("kbd",{className:"dla-cmdk-key",children:formatKeybinding(PALETTE_KEYBINDING)})," ","to reopen"]}),jsxRuntimeExports.jsxs("span",{children:[zu.length," of ",lo.length]})]})]})});return reactDomExports.createPortal(Gu,paletteRoot())}const CommandsPlugin={name:"@datalayer/reactor-commands",version:"1.0.0",displayName:"Commands",description:"A command palette: Ctrl-K opens a floating search over every command plugins have registered.",octicon:"command-palette",emoji:"⌘",build(){return{components:[{slot:"root",id:"command-palette",Component:CommandPalette}]}},commands:[{id:"commands.showPalette",name:"Show the command palette",description:"The same thing Ctrl-K does — listed so it is discoverable",emoji:"⌘",category:"Commands",keybinding:PALETTE_KEYBINDING,execute:()=>{document.dispatchEvent(new KeyboardEvent("keydown",{key:"k",ctrlKey:!0,bubbles:!0}))}}]},COMMANDS_PLUGIN_NAME="@datalayer/loop-plugin-commands",DEFAULT_CATEGORY="Workspace",GROUP_EMOJI={Agents:"🤖",Open:"📂",Session:"🧭",Workspace:"🪟"};function LoopCommandBridge({workspace:Au,sync:lo}){const $u=useContributions(LoopCommand);return reactExports.useEffect(()=>{lo($u,Au)},[$u,Au,lo]),null}const LoopCommandsPlugin={name:COMMANDS_PLUGIN_NAME,displayName:"Command palette",description:"Puts the workspace commands in a Ctrl-K palette, beside every plugin that registers one.",octicon:"command-palette",emoji:"⌘",dependencies:[CommandsPlugin,ThemePlugin],build:Au=>{const lo=new Map;let $u="",Ru;const Iu=(Pu,Ou)=>{const Mu=Ou?Pu.map(Du=>`${Du.plugin}:${Du.value.name}`).join("|"):"";if(!(Mu===$u&&Ou===Ru)){$u=Mu,Ru=Ou;for(const Du of lo.values())Du();if(lo.clear(),!!Ou)for(const Du of Pu){const Lu=Du.value,Bu=Lu.group??DEFAULT_CATEGORY;lo.set(Lu.name,Au.registerCommand({id:`loop.${Lu.name}`,name:Lu.description,description:`/${Lu.name}`,emoji:GROUP_EMOJI[Bu]??"💠",category:Bu,keybinding:Lu.keybinding,execute:async()=>{await Lu.run({workspace:Ou,argv:""})}}))}}};return{components:[{id:"loop-command-bridge",slot:LoopSlots.status,Component:({workspace:Pu})=>jsxRuntimeExports.jsx(LoopCommandBridge,{workspace:Pu,sync:Iu})}]}}},MODELS_PLUGIN_NAME="@datalayer/loop-plugin-models",ModelsPlugin={name:MODELS_PLUGIN_NAME,displayName:"Models",description:"Which model answers, from the agentspecs catalog.",octicon:"cpu",emoji:"🧠",contributes:[contribution(LoopCommand,{name:"models",aliases:["model"],description:"Show the models available to this session",group:"Agents",keybinding:"Mod+Alt+M",run:async({workspace:Au})=>{const lo=await fetch(`${Au.serverUrl}/api/v1/configure/models`);if(!lo.ok)return{content:"The model catalogue is unavailable."};const $u=await lo.json();return{content:`${($u.models??[]).filter(Iu=>Iu.available!==!1).length} of ${($u.models??[]).length} models are ready. Pick one under the prompt.`}}},{id:"models"})]},WINDOW_CONTROLS_SLOT="loop.window.controls",WINDOW_ACTIONS_SLOT="loop.window.actions";function WindowFrame({children:Au,title:lo,height:$u,slotProps:Ru={}}){const Iu=useOptionalSlotComponents(WINDOW_ACTIONS_SLOT);return jsxRuntimeExports.jsxs(Box,{position:"relative",borderRadius:"14px",overflow:"hidden",border:"1px solid",borderColor:"border.default",bg:"canvas.default",boxShadow:"0 24px 60px -28px rgba(0, 0, 0, 0.55)",height:$u===void 0?"100%":void 0,display:$u===void 0?"flex":void 0,flexDirection:$u===void 0?"column":void 0,children:[jsxRuntimeExports.jsxs(Box,{display:"flex",alignItems:"center",gap:2,px:3,py:2,borderBottom:"1px solid",borderColor:"border.default",bg:"canvas.subtle",flexWrap:"wrap",rowGap:2,flex:"0 0 auto",children:[jsxRuntimeExports.jsx(Box,{display:"flex",alignItems:"center",gap:"6px",mr:1,flexShrink:0,children:jsxRuntimeExports.jsx(ReactorSlot,{slot:WINDOW_CONTROLS_SLOT,props:Ru})}),jsxRuntimeExports.jsx(Box,{minWidth:0,flex:"1 1 auto",children:lo}),Iu.length>0?jsxRuntimeExports.jsx(Box,{display:"flex",alignItems:"center",gap:2,flexShrink:0,ml:"auto",children:jsxRuntimeExports.jsx(ReactorSlot,{slot:WINDOW_ACTIONS_SLOT,props:Ru})}):null]}),jsxRuntimeExports.jsx(Box,{sx:$u===void 0?{flex:"1 1 auto",minHeight:0}:{height:$u,minHeight:0},children:Au})]})}const WINDOW_FRAME_PLUGIN_NAME="@datalayer/loop-plugin-window-frame";function WindowControls(){return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:["danger.emphasis","attention.emphasis","success.emphasis"].map(Au=>jsxRuntimeExports.jsx(Box,{width:10,height:10,borderRadius:"50%",bg:Au},Au))})}const WindowFramePlugin={name:WINDOW_FRAME_PLUGIN_NAME,displayName:"Window frame",description:"Draws Loop as a window, and opens its title bar to controls and actions.",octicon:"browser",emoji:"🪟",build:()=>({components:[{id:"window-controls",slot:WINDOW_CONTROLS_SLOT,Component:WindowControls},{id:"full-screen",slot:LoopSlots.header,Component:WorkspaceFullScreenAction}]})},DOCUMENT_PLUGIN_NAME="@datalayer/loop-plugin-document",DocumentPlugin={name:DOCUMENT_PLUGIN_NAME,displayName:"Document editor",description:"A rich-text document beside the chat, driven by the agent.",octicon:"file",emoji:"📄",dependencies:[AgentsPlugin],contributionPoints:[LoopDocumentToolbar,LoopOpeningDocument],contributes:[contribution(LoopEditorView,{surfaceId:"document",title:"Document",icon:FileIcon,order:20,canOpen:Au=>Au.sandbox.state==="running",unavailableReason:()=>"Needs a running sandbox",load:()=>__vitePreload(()=>import("./chunks/DocumentView-i99p_Qzt.js"),[],import.meta.url)},{id:"document",order:20}),contribution(LoopCommand,{name:"document",description:"Open the document beside the chat",group:"Open",keybinding:"Mod+Alt+O",run:async({workspace:Au})=>{if(Au.setActiveViewType("chat"),!requestSurface("document"))throw new Error("No chat is on screen to open the document beside.")}},{id:"document"})],build:Au=>(__vitePreload(async()=>{const{createLexicalTools:lo}=await import("./chunks/lexicalHooks-Pqoe8h_O.js");return{createLexicalTools:lo}},[],import.meta.url).then(({createLexicalTools:lo})=>{Au.contribute(LoopFrontendTool,{id:"document-tools",tools:$u=>lo($u.surfaceId)},{id:"document-tools"})},lo=>{console.warn("The document tools could not be loaded",lo)}),{})},DOCUMENT_TOOLBAR_PLUGIN_NAME="@datalayer/loop-plugin-document-toolbar",DocumentToolbarPlugin=defineLazyPlugin({name:DOCUMENT_TOOLBAR_PLUGIN_NAME,displayName:"Document toolbar",description:"Shows what the document’s code blocks run on.",octicon:"circle",emoji:"🔵",activationEvents:[onContributionPoint(LoopDocumentToolbar)],contributionPoints:[LoopDocumentToolbarItem],load:()=>__vitePreload(()=>import("./chunks/plugin-Cf3g-jak.js"),[],import.meta.url)}),NOTEBOOK_PLUGIN_NAME="@datalayer/loop-plugin-notebook",NotebookPlugin={name:NOTEBOOK_PLUGIN_NAME,displayName:"Notebook editor",description:"A notebook beside the chat, on the session’s kernel.",octicon:"rows",emoji:"📓",dependencies:[AgentsPlugin],contributionPoints:[LoopNotebookToolbar,LoopOpeningNotebook],contributes:[contribution(LoopEditorView,{surfaceId:"notebook",title:"Notebook",icon:RowsIcon,order:10,canOpen:Au=>Au.sandbox.state==="running",unavailableReason:()=>"Needs a running sandbox",load:()=>__vitePreload(()=>import("./chunks/NotebookView-BJpTApeL.js"),[],import.meta.url)},{id:"notebook",order:10}),contribution(LoopCommand,{name:"notebook",description:"Open the notebook beside the chat",group:"Open",keybinding:"Mod+Alt+N",run:async({workspace:Au})=>{if(Au.setActiveViewType("chat"),!requestSurface("notebook"))throw new Error("No chat is on screen to open the notebook beside.")}},{id:"notebook"})],build:Au=>(__vitePreload(async()=>{const{createNotebookTools:lo}=await Promise.resolve().then(()=>notebookHooks);return{createNotebookTools:lo}},void 0,import.meta.url).then(({createNotebookTools:lo})=>{Au.contribute(LoopFrontendTool,{id:"notebook-tools",tools:$u=>lo($u.surfaceId)},{id:"notebook-tools"})},lo=>{console.warn("The notebook tools could not be loaded",lo)}),{})},NOTEBOOK_TOOLBAR_PLUGIN_NAME="@datalayer/loop-plugin-notebook-toolbar",NotebookToolbarPlugin=defineLazyPlugin({name:NOTEBOOK_TOOLBAR_PLUGIN_NAME,displayName:"Notebook toolbar",description:"Shows what the notebook is running on, on its toolbar.",octicon:"circle",emoji:"🟢",activationEvents:[onContributionPoint(LoopNotebookToolbar)],contributionPoints:[LoopNotebookToolbarItem],load:()=>__vitePreload(()=>import("./chunks/plugin-DA_NCYQX.js"),[],import.meta.url)}),NotebookExtension=defineExtension({name:"@datalayer/loop-extension-notebook",displayName:"Notebooks",description:"A notebook beside the chat, and the toolbar that reports on it.",octicon:"rows",emoji:"📓",plugins:[NotebookPlugin,NotebookToolbarPlugin]}),DocumentExtension=defineExtension({name:"@datalayer/loop-extension-document",displayName:"Documents",description:"A rich-text document beside the chat, and the toolbar that reports on it.",octicon:"file",emoji:"📄",plugins:[DocumentPlugin,DocumentToolbarPlugin]}),NO_TURN$5=signal$2({id:0,status:"idle"}),MAX_HEIGHT=168;function Thinking(){return jsxRuntimeExports.jsxs(Box,{as:"span","aria-label":"The agent is thinking",display:"inline-flex",gap:"4px",alignItems:"center",sx:{height:"1.5em","& > i":{width:5,height:5,borderRadius:"50%",bg:"fg.muted",animation:"loop-turn-dot 1.2s ease-in-out infinite"},"& > i:nth-of-type(2)":{animationDelay:"0.15s"},"& > i:nth-of-type(3)":{animationDelay:"0.3s"},"@keyframes loop-turn-dot":{"0%, 80%, 100%":{opacity:.25},"40%":{opacity:1}}},children:[jsxRuntimeExports.jsx("i",{}),jsxRuntimeExports.jsx("i",{}),jsxRuntimeExports.jsx("i",{})]})}function TurnPanel({footer:Au="full"}){const lo=useContributions(LoopChatTurn),$u=useSignalValue$1(lo[0]?.value.turn??NO_TURN$5),Ru=useSignalValue$1(pageLayoutSheet),Iu=reactExports.useRef(null),[Pu,Ou]=reactExports.useState(null),[Mu,Du]=reactExports.useState(!1);reactExports.useEffect(()=>{const ju=Iu.current;ju&&(ju.scrollTop=ju.scrollHeight)},[$u.assistant]),reactExports.useEffect(()=>{if(!Mu)return;const ju=window.setTimeout(()=>Du(!1),1400);return()=>window.clearTimeout(ju)},[Mu]);const Lu=reactExports.useCallback(async()=>{const ju=[$u.user,$u.assistant].filter(Boolean).join(`
|
|
4012
4015
|
|
|
4013
|
-
`);await navigator.clipboard?.writeText(ju),Du(!0)},[$u.user,$u.assistant]);if(Ru==="panel"||$u.status==="idle"||!$u.user||Pu===$u.id)return null;const Bu=$u.status==="thinking"||$u.status==="streaming";return jsxRuntimeExports.jsxs(Box,{"data-turn-panel":"",borderTop:"1px solid",borderColor:"border.muted",px:3,pt:2,pb:Au==="none"?2:1,display:"flex",flexDirection:"column",gap:2,bg:"canvas.default",children:[jsxRuntimeExports.jsx(Box,{display:"flex",justifyContent:"flex-end",children:jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,lineHeight:1.45,px:2,py:1,borderRadius:"10px",bg:"accent.subtle",color:"fg.default",maxWidth:"85%",overflow:"hidden",display:"-webkit-box",WebkitLineClamp:2,WebkitBoxOrient:"vertical"},children:$u.user})}),jsxRuntimeExports.jsxs(Box,{display:"flex",gap:2,alignItems:"flex-start",children:[jsxRuntimeExports.jsx(Box,{ref:Iu,flex:"1 1 auto",minWidth:0,maxHeight:MAX_HEIGHT,overflowY:"auto",fontSize:0,lineHeight:1.5,color:$u.assistant?"fg.default":"fg.muted",whiteSpace:$u.assistant?"normal":"pre-wrap",overflowWrap:"anywhere",children:$u.assistant?jsxRuntimeExports.jsx(Box,{sx:{...streamdownMarkdownStyles,fontSize:0},children:jsxRuntimeExports.jsx(_o$1,{rehypePlugins:REHYPE_PLUGINS_WITHOUT_HTML,children:normalizeAssistantMarkdown($u.assistant)})}):$u.activity?jsxRuntimeExports.jsx(Text$3,{sx:{color:"fg.muted",fontStyle:"italic"},children:$u.activity}):Bu?jsxRuntimeExports.jsx(Thinking,{}):$u.status==="error"?"The agent could not answer.":"Done — the result is in the page."}),jsxRuntimeExports.jsx(IconButton,{icon:CommentDiscussionIcon,size:"small",variant:"invisible","aria-label":"Open the conversation",onClick:openPagePanel,sx:{color:"fg.muted",flexShrink:0}})]}),$u.assistant&&$u.activity?jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:"fg.muted",fontStyle:"italic"},children:$u.activity}):null,Au==="full"?jsxRuntimeExports.jsx(TurnFooter,{usage:$u.usage,live:Bu,latest:!0,padding:0,onCopy:Lu,onRemove:()=>Ou($u.id)}):Au==="actions"?jsxRuntimeExports.jsxs(Box,{display:"flex",justifyContent:"flex-end",gap:1,mt:-1,children:[jsxRuntimeExports.jsx(IconButton,{icon:Mu?CheckIcon:CopyIcon,size:"small",variant:"invisible","aria-label":Mu?"Copied":"Copy this turn",onClick:()=>{Lu()},sx:{color:"fg.muted"}}),jsxRuntimeExports.jsx(IconButton,{icon:XIcon,size:"small",variant:"invisible","aria-label":"Dismiss until the next turn",onClick:()=>Ou($u.id),sx:{color:"fg.muted"}})]}):null]})}const SPLIT_DEFAULT_SHARE=.4,SPLIT_MIN_SHARE=.2,SPLIT_MAX_SHARE=.8,SPLIT_KEY_STEP=.05;function clampSplitShare(Au){return Number.isFinite(Au)?Math.min(SPLIT_MAX_SHARE,Math.max(SPLIT_MIN_SHARE,Au)):SPLIT_DEFAULT_SHARE}function splitShareForKey(Au,lo){switch(lo){case"ArrowLeft":return clampSplitShare(Au-SPLIT_KEY_STEP);case"ArrowRight":return clampSplitShare(Au+SPLIT_KEY_STEP);case"Home":return SPLIT_MIN_SHARE;case"End":return SPLIT_MAX_SHARE;default:return null}}function SplitLayout({editors:Au,hasEditor:lo,transcript:$u,prompt:Ru,chips:Iu,picker:Pu,transient:Ou}){const[Mu,Du]=reactExports.useState(SPLIT_DEFAULT_SHARE),Lu=reactExports.useRef(null),Bu=reactExports.useRef(!1),ju=reactExports.useCallback(Gu=>{const Wu=Lu.current?.getBoundingClientRect();return!Wu||Wu.width<=0?null:clampSplitShare((Gu-Wu.left)/Wu.width)},[]),Fu=Gu=>{Bu.current=!0,Gu.currentTarget.setPointerCapture?.(Gu.pointerId),Gu.preventDefault()},zu=Gu=>{if(!Bu.current)return;const Wu=ju(Gu.clientX);Wu!==null&&Du(Wu)},Uu=Gu=>{Bu.current=!1,Gu.currentTarget.releasePointerCapture?.(Gu.pointerId)},Hu=Gu=>{const Wu=splitShareForKey(Mu,Gu.key);Wu!==null&&(Gu.preventDefault(),Du(Wu))},Vu=Math.round(Mu*100);return jsxRuntimeExports.jsxs(Box,{"data-testid":"loop-split-layout",flex:"1 1 auto",minHeight:0,display:"flex",flexDirection:"column",children:[Pu,jsxRuntimeExports.jsxs(Box,{ref:Lu,flex:"1 1 auto",minHeight:0,display:"flex",position:"relative",overflow:"hidden",children:[jsxRuntimeExports.jsxs(Box,{"data-testid":"loop-split-conversation",flex:lo?`0 0 ${Vu}%`:"1 1 auto",minWidth:0,minHeight:0,display:"flex",flexDirection:"column",ml:lo?"-1px":0,children:[$u,Iu,Ru]}),lo?jsxRuntimeExports.jsx(Box,{role:"separator","aria-orientation":"vertical","aria-label":"Resize the conversation and the page","aria-valuemin":Math.round(SPLIT_MIN_SHARE*100),"aria-valuemax":Math.round(SPLIT_MAX_SHARE*100),"aria-valuenow":Vu,tabIndex:0,onPointerDown:Fu,onPointerMove:zu,onPointerUp:Uu,onPointerCancel:Uu,onKeyDown:Hu,flex:"0 0 7px",mx:"-3px",zIndex:1,cursor:"col-resize",display:"flex",justifyContent:"center",outline:"none",touchAction:"none",sx:{"&::before":{content:'""',width:"1px",height:"100%",bg:"border.default"},"&:hover::before, &:focus-visible::before":{width:"3px",bg:"accent.emphasis"}}}):null,jsxRuntimeExports.jsx(Box,{"data-testid":"loop-split-page",sx:lo?{flex:"1 1 0",minWidth:0,minHeight:0,display:"flex",...paneOpening("right")}:{position:"absolute",inset:0,visibility:"hidden",pointerEvents:"none",zIndex:-1},children:Au})]}),Ou]})}const LOOP_PAGE_LAYOUT_PLUGIN_NAME="@datalayer/loop-plugin-page-layout",NO_TURN$4=signal$2({id:0,status:"idle"}),pageLayoutChatMode=signal$2("floating-draggable"),promptStance=signal$2("floating-top");let floatingStance="floating-top";const PAGE_LAYOUT_DISABLED_MODES=["assistant"];function pageLayoutForChatMode(Au){switch(Au){case"sidebar":return{bandMode:"panel",panelMode:"docked"};case"floating":return{bandMode:"panel",panelMode:"overlay"};case"floating-small":return{bandMode:"panel",panelMode:"popup"};default:return{bandMode:"floating",panelMode:"docked"}}}function setPageLayoutChatMode(Au){pageLayoutChatMode.value=Au;const{bandMode:lo}=pageLayoutForChatMode(Au);promptStance.value=lo==="floating"?floatingStance:"docked-top",lo==="panel"&&openPagePanel()}function ChatModeAction(){const Au=useSignalValue$1(pageLayoutChatMode);return jsxRuntimeExports.jsx(ChatViewModeToggle,{value:Au,onChange:setPageLayoutChatMode,disabledModes:PAGE_LAYOUT_DISABLED_MODES})}function LoopPageLayout({parts:Au,promptMode:lo,pageSize:$u}){const Ru=useContributions(LoopChatTurn),Iu=useSignalValue$1(Ru[0]?.value.turn??NO_TURN$4),Pu=useSignalValue$1(pageLayoutChatMode),Ou=lo==="floating"?pageLayoutForChatMode(Pu):{bandMode:"docked",panelMode:"docked"};return jsxRuntimeExports.jsx(PageLayout,{page:Au.editors,hasPage:Au.hasEditor,panel:Au.transcript,band:Au.prompt,chips:Au.chips,picker:Au.picker,transient:Au.transient,activity:Iu.activity,bandMode:Ou.bandMode,panelMode:Ou.panelMode,pageSize:$u})}function ConversationToggle(){return jsxRuntimeExports.jsx(PagePanelToggle,{panelName:"conversation",icon:CommentDiscussionIcon,sx:{order:2}})}const LoopPageLayoutPlugin={name:LOOP_PAGE_LAYOUT_PLUGIN_NAME,config:{arrangement:"page",turnPanel:"below",turnPanelFooter:"full",prompt:"docked",promptAnchor:"top",pageSize:void 0},displayName:"Page layout",description:"The editor — or, in the chat view, the conversation — on a centred sheet, the prompt docked above it at the same width or floating over it as a draggable card, the current turn under the prompt, the conversation in a side panel; or, split, the conversation and the work side by side with a hairline to drag.",octicon:"file",emoji:"📄",build:({config:Au,...lo})=>{if(Au.arrangement==="split")return lo.contribute(LoopChatLayout,{id:"split-layout",prompt:"docked",Component:SplitLayout},{id:"split-layout"}),{components:[]};const $u=Au.prompt,Ru=Au.pageSize;floatingStance=Au.promptAnchor==="bottom"?"floating-bottom":"floating-top",$u==="floating"&&(promptStance.value=floatingStance);const Iu=Pu=>jsxRuntimeExports.jsx(LoopPageLayout,{parts:Pu,promptMode:$u,pageSize:Ru});if(lo.contribute(LoopChatLayout,{id:"page-layout",prompt:$u==="floating"?floatingStance:"docked-top",promptStance:$u==="floating"?promptStance:void 0,Component:Iu},{id:"page-layout"}),Au.turnPanel!=="none"){const Pu=Au.turnPanelFooter,Ou=()=>jsxRuntimeExports.jsx(TurnPanel,{footer:Pu});lo.contribute(LoopPromptPanel,{id:"page-layout-turn",placement:Au.turnPanel,order:0,Component:Ou},{id:"page-layout-turn"})}return{components:[{id:"page-layout-conversation-toggle",slot:LoopSlots.header,Component:ConversationToggle},...$u==="floating"?[{id:"page-layout-chat-mode",slot:LoopSlots.promptAction,Component:ChatModeAction}]:[]]}}};function loopPlugins(Au={}){const{serverUrl:lo,target:$u="browser",defaultEditor:Ru,showViewSelector:Iu=!0,hideChatHeader:Pu=!1,chatHeaderButtons:Ou=!1,promptPlacement:Mu,autoFocusPrompt:Du=!0,suggestionLabels:Lu=!0,fullScreenTopOffset:Bu=0,showAgentVariants:ju=!1,agentSummary:Fu=!0,teamId:zu,teamPicker:Uu=!0,pageLayout:Hu=!1,pageLayoutArrangement:Vu="page",pageLayoutTurnPanel:Gu="below",pageLayoutPrompt:Wu="docked",pageLayoutPromptAnchor:Ku="top",pageLayoutSize:Ju,pageLayoutTurnPanelFooter:Yu="full",localAgent:Xu,localAgentSpec:ed,datalayerAgentSpecId:td,datalayerCreatePayload:nd,datalayerVisitors:od,datalayerKept:sd,embedToken:ad,targetFixed:pd,themeVariant:gd,themeOverrides:_d,colorMode:yd,presence:bd,showTokenUsage:Sd,voice:Ed,thread:cd,floatingPrompt:dd=!1,editorSelector:md=!1,editors:ld=!0,conversation:hd=!0,commandPalette:vd=!1,pluginsPanel:wd=!1,windowFrame:kd=!1,firstPromptHook:Rd}=Au,Od=Ru??(ld?"notebook":"none");return hd?[configurePlugin(ChatPlugin,{defaultSurface:Od,showSurfaceSelector:ld&&Iu&&!md,hideHeader:Pu,headerButtons:{newChat:Ou,clear:Ou},promptPlacement:dd?"floating":Mu,autoFocusPrompt:Du,suggestionLabels:Lu,fullScreenTopOffset:Bu,themeVariant:gd,themeOverrides:_d,colorMode:yd,presence:bd,showTokenUsage:Sd,...Ed?{voice:Ed}:{},...cd?{thread:cd}:{}}),configurePlugin(InputPromptPlugin,{firstPromptHook:Rd}),ChatHeaderPlugin,A2uiSurfacePlugin,PapSignInPlugin,ChatViewPlugin,...ld?[NotebookViewPlugin,DocumentViewPlugin]:[],configurePlugin(AgentsPlugin,{serverUrl:lo,target:$u,datalayerAgentSpecId:td,datalayerCreatePayload:nd,datalayerVisitors:od,datalayerKept:sd,embedToken:ad,targetFixed:pd,showAgentVariants:ju,showAgentSummary:Fu,teamId:zu,showTeamPicker:Uu,localAgent:Xu??(ed?{createPayload:{description:`Local agent from the ${ed} spec`,agent_library:"pydantic-ai",agent_spec_id:ed,enable_codemode:!1}}:void 0)}),...ld?[NotebookExtension,DocumentExtension]:[],A2uiPlugin,AgentspecsPlugin,ModelsPlugin,ThemePlugin,SubagentActivityPlugin,configurePlugin(ShellPlugin,{defaultEditor:Od,showSelector:ld&&md}),...dd?[PromptPlugin]:[],...Hu?[configurePlugin(LoopPageLayoutPlugin,{arrangement:Vu,turnPanel:Gu,turnPanelFooter:Yu,prompt:Wu,promptAnchor:Ku,pageSize:Ju})]:[],...vd?[LoopCommandsPlugin]:[],...wd?[PluginsPanelPlugin]:[],...kd?[WindowFramePlugin]:[]]:[ThemePlugin,configurePlugin(ShellPlugin,{defaultEditor:"none",showSelector:!1}),...vd?[LoopCommandsPlugin]:[],...wd?[PluginsPanelPlugin]:[],...kd?[WindowFramePlugin]:[]]}function LoopEmbed({agentId:Au="",showHeader:lo=!1,chatHeaderActions:$u,headerActions:Ru,headerContainer:Iu,frameTitle:Pu,frameHeight:Ou,sidebarRail:Mu=!1,plugins:Du=[],...Lu}){const Bu=reactExports.useRef(Lu.firstPromptHook);Bu.current=Lu.firstPromptHook;const ju=reactExports.useMemo(()=>buildLoopReactor([...loopPlugins({...Lu,windowFrame:Lu.windowFrame||Pu!==void 0,firstPromptHook:()=>Bu.current?.()}),...Du]),[Lu.serverUrl,Lu.target,Lu.datalayerAgentSpecId,Lu.targetFixed,Lu.themeVariant,JSON.stringify(Lu.themeOverrides??null),Lu.colorMode,Lu.presence?.name,Lu.presence?.face,Lu.presence?.welcome,Lu.presence?.paused,Lu.showTokenUsage,JSON.stringify({...Lu.voice??{},engines:void 0,token:void 0}),Lu.thread?.id,JSON.stringify(Lu.datalayerCreatePayload??null),JSON.stringify(Lu.datalayerVisitors??null),Lu.datalayerKept?.url,Lu.embedToken,Lu.defaultEditor,Lu.showViewSelector,Lu.hideChatHeader,Lu.chatHeaderButtons,Lu.promptPlacement,Lu.autoFocusPrompt,Lu.suggestionLabels,Lu.fullScreenTopOffset,Lu.showAgentVariants,Lu.agentSummary,Lu.teamId,Lu.teamPicker,Lu.pageLayout,Lu.pageLayoutTurnPanel,Lu.pageLayoutTurnPanelFooter,Lu.pageLayoutPrompt,Lu.pageLayoutPromptAnchor,Lu.pageLayoutSize?.format,Lu.pageLayoutSize?.width,Lu.pageLayoutSize?.height,Lu.localAgentSpec,Lu.floatingPrompt,Lu.editorSelector,Lu.editors,Lu.conversation,Lu.commandPalette,Lu.pluginsPanel,Lu.windowFrame,Pu!==void 0,Du]);useReactor(ju);const Fu=jsxRuntimeExports.jsx(LoopWorkspace,{serverUrl:Lu.serverUrl??"",agentId:Au,reactor:ju,manageReactor:!1,showViewSelector:Lu.showViewSelector,showHeader:lo,chatHeaderActions:$u,headerActions:Ru,headerContainer:Iu,sidebarRail:Mu});return jsxRuntimeExports.jsx(QueryClientProvider,{client:internalQueryClient,children:Pu!==void 0?jsxRuntimeExports.jsx(WindowFrame,{title:Pu,height:Ou,children:Fu}):jsxRuntimeExports.jsx(Box,{height:"100%",minHeight:0,width:"100%",flex:"1 1 auto",minWidth:0,children:Fu})})}const RECORD_KIND_WORDS={session:"Session",tool_call:"Tool call",decision:"Rule",check:"Check",approval:"Approval",output:"Answer",feedback:"Feedback",turn:"Turn",run:"Working",notification:"Notification"};function entryOf(Au){return{uid:String(Au.uid??""),sessionUid:String(Au.session_uid??""),deploymentUid:String(Au.deployment_uid??""),version:Number(Au.version)||0,kind:String(Au.kind??"output"),summary:String(Au.summary??""),payload:Au.payload&&typeof Au.payload=="object"?Au.payload:{},createdAt:String(Au.created_at??"")}}function runEndOf(Au){const lo=Au.kind==="output"?Au.payload.status:void 0;return typeof lo=="string"&&lo in RUN_END_WORDS?lo:""}function entrySaid(Au){return Au.summary||RUN_END_WORDS[runEndOf(Au)]||""}function sessionSentence(Au){const lo=Au.filter(Ou=>Ou.kind==="tool_call").length,$u=Au.filter(Ou=>Ou.kind==="check"),Ru=Au.map(runEndOf).filter(Boolean),Iu=Ru.filter(Ou=>Ou==="answered").length,Pu=[lo===0?"No tool called":`${lo} tool call${lo===1?"":"s"}`];return $u.length&&Pu.push(`${$u.length} step${$u.length===1?"":"s"} a check did not let pass`),Ru[Ru.length-1]==="stopped"?Pu.push("stopped"):Iu&&Pu.push(`${Iu} answer${Iu===1?"":"s"}`),`${Pu.join(", ")}.`}async function read(Au,lo,$u){if(!Au.aiAgentsUrl)throw new Error("The record service is not configured.");const Ru=await fetch(`${Au.aiAgentsUrl.replace(/\/+$/,"")}/api/ai-agents/v1/apps${lo}`,{headers:Au.token?{Authorization:`Bearer ${Au.token}`}:{}}),Iu=await Ru.json().catch(()=>({}));if(!Ru.ok||Iu.success===!1)throw new Error(`${$u}: ${String(Iu.detail??Ru.status)}`);return Iu}async function listSessions(Au,lo,$u=20,Ru=!1){const Iu=await read(Au,`/sessions?app_uid=${encodeURIComponent(lo)}&limit=${$u}${Ru===null?"":`&tests=${Ru}`}`,"The sessions could not be read");return Array.isArray(Iu.sessions)?Iu.sessions.map(entryOf):[]}async function readSession(Au,lo){const $u=await read(Au,`/records?session_uid=${encodeURIComponent(lo)}&limit=500`,"The session could not be read");return Array.isArray($u.entries)?$u.entries.map(entryOf).filter(Ru=>Ru.kind!=="run"):[]}const APP_ACTIVITY_WORDS={title:"Activity",unsaved:"Recorded once it is saved on Datalayer: each session there — its address, or its Preview on Datalayer — is listed here.",signedOut:"Its activity is its owner’s: sign in to Datalayer to read it.",none:"Nothing yet: a session on Datalayer — its address, or the Preview on Datalayer — is recorded here."},NO_TURN$3=signal$2({id:0,status:"idle"});function useRead(Au,lo,$u=!0){const[Ru,Iu]=reactExports.useState({loading:$u});return reactExports.useEffect(()=>{if(!$u)return;let Pu=!1;return Iu(Ou=>({...Ou,loading:!0})),Au().then(Ou=>!Pu&&Iu({value:Ou,loading:!1}),Ou=>!Pu&&Iu({error:Ou instanceof Error?Ou.message:String(Ou),loading:!1})),()=>{Pu=!0}},[lo,$u]),Ru}function Session({context:Au,session:lo}){const[$u,Ru]=reactExports.useState(!1),Iu=useRead(()=>readSession(Au,lo.sessionUid),`${lo.sessionUid}:${Au.token}`,$u);return jsxRuntimeExports.jsxs(Box,{as:"details",onToggle:Pu=>Ru(Pu.currentTarget.open),borderTop:"1px solid",borderColor:"border.muted",py:2,children:[jsxRuntimeExports.jsxs(Box,{as:"summary",cursor:"pointer",fontSize:1,children:[lo.createdAt?jsxRuntimeExports.jsx(RelativeTime,{datetime:lo.createdAt}):"A session",lo.version?` · version ${lo.version}`:"",Iu.value?` · ${sessionSentence(Iu.value)}`:""]}),$u?Iu.loading?jsxRuntimeExports.jsx(StyledSpinner,{size:"small"}):Iu.error?jsxRuntimeExports.jsx(Text$3,{role:"alert",sx:{fontSize:1},children:Iu.error}):jsxRuntimeExports.jsx(Box,{as:"ol",pl:3,mt:2,mb:0,fontSize:1,children:(Iu.value??[]).map(Pu=>jsxRuntimeExports.jsxs(Box,{as:"li",mb:1,children:[jsxRuntimeExports.jsx(Label,{sx:{mr:2},children:RECORD_KIND_WORDS[Pu.kind]??Pu.kind}),entrySaid(Pu)]},Pu.uid))}):null]})}function AppActivity({appUid:Au}){const lo=useIAMStore(ju=>ju.token)??"",$u=useCoreStore(ju=>ju.configuration)?.aiAgentsUrl??"",Ru=useContributions(LoopChatTurn),Iu=useSignalValue$1(Ru[0]?.value.turn??NO_TURN$3),Pu=Iu.status!=="thinking"&&Iu.status!=="streaming",[Ou,Mu]=reactExports.useState(0);reactExports.useEffect(()=>{Pu&&Mu(Iu.id)},[Pu,Iu.id]);const Du={aiAgentsUrl:$u,token:lo},Lu=!!(Au&&lo),Bu=useRead(()=>listSessions(Du,Au??""),`${Au}:${lo}:${$u}:${Ou}`,Lu);return jsxRuntimeExports.jsxs(Box,{"data-testid":"app-activity",children:[jsxRuntimeExports.jsx(Heading$2,{as:"h3",sx:{fontSize:2,mb:2},children:APP_ACTIVITY_WORDS.title}),Au?lo?Bu.loading&&!Bu.value?jsxRuntimeExports.jsx(StyledSpinner,{size:"small"}):Bu.error?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:1,color:"fg.muted",m:0},children:Bu.error}):(Bu.value??[]).length===0?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:1,color:"fg.muted",m:0},children:APP_ACTIVITY_WORDS.none}):(Bu.value??[]).map(ju=>jsxRuntimeExports.jsx(Session,{context:Du,session:ju},ju.uid)):jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:1,color:"fg.muted",m:0},children:APP_ACTIVITY_WORDS.signedOut}):jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:1,color:"fg.muted",m:0},children:APP_ACTIVITY_WORDS.unsaved})]})}const APP_ACTIVITY_PLUGIN_NAME="@datalayer/loop-plugin-app-activity";function defineAppActivityPlugin(Au,lo){function $u(){return jsxRuntimeExports.jsx(AppActivity,{appUid:lo})}return{name:`${APP_ACTIVITY_PLUGIN_NAME}-${Au.id}`,displayName:`${Au.name}: activity`,description:`What ${Au.name} did, session by session, from its record.`,octicon:"pulse",build:()=>({components:[{id:"app-activity",slot:LoopSlots.sidebar,order:20,Component:$u,rail:{label:"Activity",icon:PulseIcon}}]})}}const APP_PANEL_WIDTH=380;function elementsByPlace(Au){const lo=Au.filter($u=>$u.where==="page");return{panels:Au.filter($u=>$u.where==="panel"),page:lo.length>0?lo[lo.length-1]:null}}function ElementBody({element:Au,send:lo}){return jsxRuntimeExports.jsx(AnswerShowsView,{display:Au.shows,send:($u,Ru)=>lo!==void 0&&!lo($u,Ru)})}function ElementHeader({element:Au}){return jsxRuntimeExports.jsxs(Box,{display:"flex",alignItems:"center",justifyContent:"space-between",gap:2,mb:2,children:[jsxRuntimeExports.jsx(Text$3,{as:"h2",sx:{fontSize:2,fontWeight:"bold",m:0},children:Au.title}),jsxRuntimeExports.jsx(IconButton,{icon:XIcon,variant:"invisible",size:"small","aria-label":`Close ${Au.title}`,onClick:()=>closeLoopElement(Au.id)})]})}function AppElements({workspace:Au}){const lo=reactExports.useSyncExternalStore(onLoopElements,openLoopElements,openLoopElements),{panels:$u,page:Ru}=elementsByPlace(lo),Iu=Au?.viewControls.send;return $u.length===0&&Ru===null?null:jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[$u.length>0?jsxRuntimeExports.jsx(Box,{as:"aside","aria-label":"Side panel",position:"absolute",top:0,right:0,bottom:0,width:`min(${APP_PANEL_WIDTH}px, 100%)`,zIndex:1,overflowY:"auto",borderLeft:"1px solid",borderColor:"border.default",bg:"canvas.subtle",boxShadow:"shadow.medium",p:3,display:"flex",flexDirection:"column",gap:3,children:$u.map(Pu=>jsxRuntimeExports.jsxs(Box,{as:"section","aria-label":Pu.title,children:[jsxRuntimeExports.jsx(ElementHeader,{element:Pu}),jsxRuntimeExports.jsx(ElementBody,{element:Pu,send:Iu})]},Pu.id))}):null,Ru!==null?jsxRuntimeExports.jsxs(Box,{role:"dialog","aria-label":Ru.title,position:"absolute",inset:0,zIndex:2,overflowY:"auto",bg:"canvas.default",p:[3,4],children:[jsxRuntimeExports.jsx(ElementHeader,{element:Ru}),jsxRuntimeExports.jsx(ElementBody,{element:Ru,send:Iu})]}):null]})}const QUESTION_DISPLAY_TYPE="application/vnd.datalayer.loop.question+json",SchemaForm=reactExports.lazy(()=>__vitePreload(()=>import("./chunks/SchemaForm-CE5NfpBU.js"),[],import.meta.url));function questionOf(Au){const lo=Au.data??{},$u=lo.kind;if(Au.type!==QUESTION_DISPLAY_TYPE||$u!=="text"&&$u!=="choice"&&$u!=="file"&&$u!=="form"||typeof lo.prompt!="string")throw new Error(`Display ${Au.id} is not a question`);const Ru=Iu=>Array.isArray(Iu)?Iu.filter(Pu=>typeof Pu=="string"):[];return{kind:$u,prompt:lo.prompt,options:Ru(lo.options),accept:Ru(lo.accept),form:lo.form&&typeof lo.form=="object"?lo.form:{},answered:typeof lo.answered=="string"?lo.answered:null,answerable:(Au.actions??[]).some(Iu=>Iu.name===ANSWER_ACTION)}}function QuestionView({display:Au,act:lo,upload:$u}){const Ru=questionOf(Au),[Iu,Pu]=reactExports.useState(""),[Ou,Mu]=reactExports.useState(null),Du=Bu=>{if(!lo){Mu("The chat cannot take an answer here.");return}Mu(null),Promise.resolve(lo({action:ANSWER_ACTION,payload:{value:Bu}})).catch(ju=>Mu(ju instanceof Error?ju.message:String(ju)))};if(Ru.answered!==null)return jsxRuntimeExports.jsxs(Text$3,{as:"p",sx:{color:"fg.muted",fontSize:1,m:0},children:["Answered: ",Ru.answered]});const Lu=Ru.answerable&&!!lo;return jsxRuntimeExports.jsxs(Box$1,{display:"flex",flexDirection:"column",gap:2,"data-question-kind":Ru.kind,children:[Ru.kind==="choice"?jsxRuntimeExports.jsx(Box$1,{display:"flex",gap:2,flexWrap:"wrap",children:Ru.options.map(Bu=>jsxRuntimeExports.jsx(ButtonComponent,{size:"small",disabled:!Lu,onClick:()=>Du(Bu),children:Bu},Bu))}):null,Ru.kind==="text"?jsxRuntimeExports.jsxs(Box$1,{as:"form",display:"flex",gap:2,onSubmit:Bu=>{Bu.preventDefault(),Iu.trim()&&Du(Iu.trim())},children:[jsxRuntimeExports.jsx(TextInput$1,{"aria-label":Ru.prompt,value:Iu,disabled:!Lu,onChange:Bu=>Pu(Bu.target.value)}),jsxRuntimeExports.jsx(ButtonComponent,{type:"submit",size:"small",disabled:!Lu||!Iu.trim(),children:"Answer"})]}):null,Ru.kind==="form"?jsxRuntimeExports.jsx(reactExports.Suspense,{fallback:null,children:jsxRuntimeExports.jsx(SchemaForm,{schema:Ru.form,disabled:!Lu,onSubmit:({formData:Bu})=>Du(Bu??{})})}):null,Ru.kind==="file"?jsxRuntimeExports.jsx("input",{type:"file","aria-label":Ru.prompt,accept:Ru.accept.join(",")||void 0,disabled:!Lu||!$u,onChange:Bu=>{const ju=Bu.target.files?.[0];if(ju){if(!$u){Mu("The chat cannot take a file here.");return}Mu(null),$u(ju).then(Fu=>Du(Fu)).catch(Fu=>Mu(Fu instanceof Error?Fu.message:String(Fu)))}}}):null,Ou?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{color:"danger.fg",fontSize:1,m:0},children:Ou}):null]})}const APP_ELEMENTS_PLUGIN_NAME="@datalayer/loop-plugin-app-elements",AppElementsPlugin={name:APP_ELEMENTS_PLUGIN_NAME,displayName:"Side panel and pages",description:"What an application opens beside the conversation: a side panel, or a page of its own.",octicon:"sidebar-expand",contributes:[contribution(Renderers,defineRenderer({type:QUESTION_DISPLAY_TYPE,component:QuestionView}),{id:"app-elements:question"})],build:()=>({components:[{id:"app-elements",slot:LoopSlots.root,Component:AppElements}]}),register:()=>clearLoopElements},appComponentsPluginName=Au=>`@datalayer/loop-plugin-app-components-${Au}`,hasCustomComponents=Au=>(Au.interface.customComponents??[]).length>0;function defineAppComponentsPlugin(Au,lo){const $u=Au.interface.customComponents??[];if($u.length===0)throw new Error(`“${Au.name}” has no component of its own to contribute.`);return{name:appComponentsPluginName(Au.id),displayName:`${Au.name}'s components`,description:`The components ${Au.name}'s developer wrote: ${$u.map(Ru=>Ru.name).join(", ")}.`,octicon:"apps",contributes:$u.flatMap(Ru=>[contribution(LoopCanvasBlock,{id:Ru.name,ui:`app:${Au.id}`,component:customComponentEntry(Ru,Au.version)},{id:Ru.name}),contribution(LoopA2uiComponent,{id:Ru.name,app:Au.id,implementation:customImplementation(Ru,Au.version,lo,Au.id)},{id:Ru.name})])}}const COMPUTER_PARTS=["browse","files","shell"],COMPUTER_PART_TOOLS={browse:["open_page","read_page","page_screenshot","click_on_page","type_on_page"],files:["list_computer_files","read_computer_file","write_computer_file"],shell:["execute_code","run_skill_script"]},COMPUTER_WORDS={title:"Computer",part:{browse:"Browse",files:"Files",shell:"Shell"},on:"on",off:"off",none:"It has no computer: browse, files and shell are all off. Turn one on in its permissions to give it one.",offSaid:Au=>`Off, so its agent is given no tool for it: ${Au.join(", ")}.`,browser:"Browser",noBrowser:"No browser is installed on its computer.",noPage:"Its browser has opened no page yet.",pageAlt:Au=>`The page its browser shows: ${Au}`,clickToAct:"Click on the page to click there; with the page selected, what you type goes to it.",typeOnPage:"Text to type on the page",type:"Type",address:"An address to open",open:"Open",scrollUp:"Scroll up",scrollDown:"Scroll down",agentHas:"Its agent has the computer.",youHave:"You have the computer: its agent waits for it until you hand it back.",someoneHas:"Somebody else has taken this computer over.",takeOver:"Take over",handBack:"Hand back",run:"Run",yourCode:"Python to run on its computer",terminal:"What ran on it",nothingRan:"Nothing has run on it yet in this conversation.",files:"Files",notStarted:"Its computer starts when its agent first uses it: no file yet.",emptyDirectory:"Empty.",up:"Up",download:"Download",signedOut:"Its computer is shown once you are signed in to Datalayer."};function computerParts(Au){const lo=Au.permissions?.computer;return{browse:!!lo?.browse,files:!!lo?.files,shell:!!lo?.shell}}const hasComputer=Au=>COMPUTER_PARTS.some(lo=>Au[lo]),partsOff=Au=>COMPUTER_PARTS.filter(lo=>!Au[lo]).map(lo=>COMPUTER_WORDS.part[lo].toLowerCase());function partOf(Au){return COMPUTER_PARTS.find(lo=>COMPUTER_PART_TOOLS[lo].includes(Au))}const OUTPUT_LIMIT=4e3;function outputOf(Au){let lo=Au;if(typeof lo=="string")try{const Ru=JSON.parse(lo);Ru&&typeof Ru=="object"&&!Array.isArray(Ru)&&(lo=Ru)}catch{}let $u;if(lo&&typeof lo=="object"&&!Array.isArray(lo)){const Ru=lo,Iu=[typeof Ru.stdout=="string"?Ru.stdout:Ru.output,Ru.stderr,Ru.error??Ru.execution_error??Ru.code_error].filter(Pu=>typeof Pu=="string"&&Pu.trim()!=="");$u=Iu.length>0?Iu.join(`
|
|
4016
|
+
`);await navigator.clipboard?.writeText(ju),Du(!0)},[$u.user,$u.assistant]);if(Ru==="panel"||$u.status==="idle"||!$u.user||Pu===$u.id)return null;const Bu=$u.status==="thinking"||$u.status==="streaming";return jsxRuntimeExports.jsxs(Box,{"data-turn-panel":"",borderTop:"1px solid",borderColor:"border.muted",px:3,pt:2,pb:Au==="none"?2:1,display:"flex",flexDirection:"column",gap:2,bg:"canvas.default",children:[jsxRuntimeExports.jsx(Box,{display:"flex",justifyContent:"flex-end",children:jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,lineHeight:1.45,px:2,py:1,borderRadius:"10px",bg:"accent.subtle",color:"fg.default",maxWidth:"85%",overflow:"hidden",display:"-webkit-box",WebkitLineClamp:2,WebkitBoxOrient:"vertical"},children:$u.user})}),jsxRuntimeExports.jsxs(Box,{display:"flex",gap:2,alignItems:"flex-start",children:[jsxRuntimeExports.jsx(Box,{ref:Iu,flex:"1 1 auto",minWidth:0,maxHeight:MAX_HEIGHT,overflowY:"auto",fontSize:0,lineHeight:1.5,color:$u.assistant?"fg.default":"fg.muted",whiteSpace:$u.assistant?"normal":"pre-wrap",overflowWrap:"anywhere",children:$u.assistant?jsxRuntimeExports.jsx(Box,{sx:{...streamdownMarkdownStyles,fontSize:0},children:jsxRuntimeExports.jsx(_o$1,{rehypePlugins:REHYPE_PLUGINS_WITHOUT_HTML,children:normalizeAssistantMarkdown($u.assistant)})}):$u.activity?jsxRuntimeExports.jsx(Text$3,{sx:{color:"fg.muted",fontStyle:"italic"},children:$u.activity}):Bu?jsxRuntimeExports.jsx(Thinking,{}):$u.status==="error"?"The agent could not answer.":"Done — the result is in the page."}),jsxRuntimeExports.jsx(IconButton,{icon:CommentDiscussionIcon,size:"small",variant:"invisible","aria-label":"Open the conversation",onClick:openPagePanel,sx:{color:"fg.muted",flexShrink:0}})]}),$u.assistant&&$u.activity?jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:"fg.muted",fontStyle:"italic"},children:$u.activity}):null,Au==="full"?jsxRuntimeExports.jsx(TurnFooter,{usage:$u.usage,live:Bu,latest:!0,padding:0,onCopy:Lu,onRemove:()=>Ou($u.id)}):Au==="actions"?jsxRuntimeExports.jsxs(Box,{display:"flex",justifyContent:"flex-end",gap:1,mt:-1,children:[jsxRuntimeExports.jsx(IconButton,{icon:Mu?CheckIcon:CopyIcon,size:"small",variant:"invisible","aria-label":Mu?"Copied":"Copy this turn",onClick:()=>{Lu()},sx:{color:"fg.muted"}}),jsxRuntimeExports.jsx(IconButton,{icon:XIcon,size:"small",variant:"invisible","aria-label":"Dismiss until the next turn",onClick:()=>Ou($u.id),sx:{color:"fg.muted"}})]}):null]})}const SPLIT_DEFAULT_SHARE=.4,SPLIT_MIN_SHARE=.2,SPLIT_MAX_SHARE=.8,SPLIT_KEY_STEP=.05;function clampSplitShare(Au){return Number.isFinite(Au)?Math.min(SPLIT_MAX_SHARE,Math.max(SPLIT_MIN_SHARE,Au)):SPLIT_DEFAULT_SHARE}function splitShareForKey(Au,lo){switch(lo){case"ArrowLeft":return clampSplitShare(Au-SPLIT_KEY_STEP);case"ArrowRight":return clampSplitShare(Au+SPLIT_KEY_STEP);case"Home":return SPLIT_MIN_SHARE;case"End":return SPLIT_MAX_SHARE;default:return null}}function SplitLayout({editors:Au,hasEditor:lo,transcript:$u,prompt:Ru,chips:Iu,picker:Pu,transient:Ou}){const[Mu,Du]=reactExports.useState(SPLIT_DEFAULT_SHARE),Lu=reactExports.useRef(null),Bu=reactExports.useRef(!1),ju=reactExports.useCallback(Gu=>{const Wu=Lu.current?.getBoundingClientRect();return!Wu||Wu.width<=0?null:clampSplitShare((Gu-Wu.left)/Wu.width)},[]),Fu=Gu=>{Bu.current=!0,Gu.currentTarget.setPointerCapture?.(Gu.pointerId),Gu.preventDefault()},zu=Gu=>{if(!Bu.current)return;const Wu=ju(Gu.clientX);Wu!==null&&Du(Wu)},Uu=Gu=>{Bu.current=!1,Gu.currentTarget.releasePointerCapture?.(Gu.pointerId)},Hu=Gu=>{const Wu=splitShareForKey(Mu,Gu.key);Wu!==null&&(Gu.preventDefault(),Du(Wu))},Vu=Math.round(Mu*100);return jsxRuntimeExports.jsxs(Box,{"data-testid":"loop-split-layout",flex:"1 1 auto",minHeight:0,display:"flex",flexDirection:"column",children:[Pu,jsxRuntimeExports.jsxs(Box,{ref:Lu,flex:"1 1 auto",minHeight:0,display:"flex",position:"relative",overflow:"hidden",children:[jsxRuntimeExports.jsxs(Box,{"data-testid":"loop-split-conversation",flex:lo?`0 0 ${Vu}%`:"1 1 auto",minWidth:0,minHeight:0,display:"flex",flexDirection:"column",ml:lo?"-1px":0,children:[$u,Iu,Ru]}),lo?jsxRuntimeExports.jsx(Box,{role:"separator","aria-orientation":"vertical","aria-label":"Resize the conversation and the page","aria-valuemin":Math.round(SPLIT_MIN_SHARE*100),"aria-valuemax":Math.round(SPLIT_MAX_SHARE*100),"aria-valuenow":Vu,tabIndex:0,onPointerDown:Fu,onPointerMove:zu,onPointerUp:Uu,onPointerCancel:Uu,onKeyDown:Hu,flex:"0 0 7px",mx:"-3px",zIndex:1,cursor:"col-resize",display:"flex",justifyContent:"center",outline:"none",touchAction:"none",sx:{"&::before":{content:'""',width:"1px",height:"100%",bg:"border.default"},"&:hover::before, &:focus-visible::before":{width:"3px",bg:"accent.emphasis"}}}):null,jsxRuntimeExports.jsx(Box,{"data-testid":"loop-split-page",sx:lo?{flex:"1 1 0",minWidth:0,minHeight:0,display:"flex",...paneOpening("right")}:{position:"absolute",inset:0,visibility:"hidden",pointerEvents:"none",zIndex:-1},children:Au})]}),Ou]})}const LOOP_PAGE_LAYOUT_PLUGIN_NAME="@datalayer/loop-plugin-page-layout",NO_TURN$4=signal$2({id:0,status:"idle"}),pageLayoutChatMode=signal$2("floating-draggable"),promptStance=signal$2("floating-top");let floatingStance="floating-top";const PAGE_LAYOUT_DISABLED_MODES=["assistant"];function pageLayoutForChatMode(Au){switch(Au){case"sidebar":return{bandMode:"panel",panelMode:"docked"};case"floating":return{bandMode:"panel",panelMode:"overlay"};case"floating-small":return{bandMode:"panel",panelMode:"popup"};default:return{bandMode:"floating",panelMode:"docked"}}}function setPageLayoutChatMode(Au){pageLayoutChatMode.value=Au;const{bandMode:lo}=pageLayoutForChatMode(Au);promptStance.value=lo==="floating"?floatingStance:"docked-top",lo==="panel"&&openPagePanel()}function ChatModeAction(){const Au=useSignalValue$1(pageLayoutChatMode);return jsxRuntimeExports.jsx(ChatViewModeToggle,{value:Au,onChange:setPageLayoutChatMode,disabledModes:PAGE_LAYOUT_DISABLED_MODES})}function LoopPageLayout({parts:Au,promptMode:lo,pageSize:$u}){const Ru=useContributions(LoopChatTurn),Iu=useSignalValue$1(Ru[0]?.value.turn??NO_TURN$4),Pu=useSignalValue$1(pageLayoutChatMode),Ou=lo==="floating"?pageLayoutForChatMode(Pu):{bandMode:"docked",panelMode:"docked"};return jsxRuntimeExports.jsx(PageLayout,{page:Au.editors,hasPage:Au.hasEditor,panel:Au.transcript,band:Au.prompt,chips:Au.chips,picker:Au.picker,transient:Au.transient,activity:Iu.activity,bandMode:Ou.bandMode,panelMode:Ou.panelMode,pageSize:$u})}function ConversationToggle(){return jsxRuntimeExports.jsx(PagePanelToggle,{panelName:"conversation",icon:CommentDiscussionIcon,sx:{order:2}})}const LoopPageLayoutPlugin={name:LOOP_PAGE_LAYOUT_PLUGIN_NAME,config:{arrangement:"page",turnPanel:"below",turnPanelFooter:"full",prompt:"docked",promptAnchor:"top",pageSize:void 0},displayName:"Page layout",description:"The editor — or, in the chat view, the conversation — on a centred sheet, the prompt docked above it at the same width or floating over it as a draggable card, the current turn under the prompt, the conversation in a side panel; or, split, the conversation and the work side by side with a hairline to drag.",octicon:"file",emoji:"📄",build:({config:Au,...lo})=>{if(Au.arrangement==="split")return lo.contribute(LoopChatLayout,{id:"split-layout",prompt:"docked",Component:SplitLayout},{id:"split-layout"}),{components:[]};const $u=Au.prompt,Ru=Au.pageSize;floatingStance=Au.promptAnchor==="bottom"?"floating-bottom":"floating-top",$u==="floating"&&(promptStance.value=floatingStance);const Iu=Pu=>jsxRuntimeExports.jsx(LoopPageLayout,{parts:Pu,promptMode:$u,pageSize:Ru});if(lo.contribute(LoopChatLayout,{id:"page-layout",prompt:$u==="floating"?floatingStance:"docked-top",promptStance:$u==="floating"?promptStance:void 0,Component:Iu},{id:"page-layout"}),Au.turnPanel!=="none"){const Pu=Au.turnPanelFooter,Ou=()=>jsxRuntimeExports.jsx(TurnPanel,{footer:Pu});lo.contribute(LoopPromptPanel,{id:"page-layout-turn",placement:Au.turnPanel,order:0,Component:Ou},{id:"page-layout-turn"})}return{components:[{id:"page-layout-conversation-toggle",slot:LoopSlots.header,Component:ConversationToggle},...$u==="floating"?[{id:"page-layout-chat-mode",slot:LoopSlots.promptAction,Component:ChatModeAction}]:[]]}}};function loopPlugins(Au={}){const{serverUrl:lo,target:$u="browser",defaultEditor:Ru,showViewSelector:Iu=!0,hideChatHeader:Pu=!1,chatHeaderButtons:Ou=!1,promptPlacement:Mu,autoFocusPrompt:Du=!0,suggestionLabels:Lu=!0,fullScreenTopOffset:Bu=0,showAgentVariants:ju=!1,agentSummary:Fu=!0,teamId:zu,teamPicker:Uu=!0,pageLayout:Hu=!1,pageLayoutArrangement:Vu="page",pageLayoutTurnPanel:Gu="below",pageLayoutPrompt:Wu="docked",pageLayoutPromptAnchor:Ku="top",pageLayoutSize:Ju,pageLayoutTurnPanelFooter:Yu="full",localAgent:Xu,localAgentSpec:ed,datalayerAgentSpecId:td,datalayerCreatePayload:nd,datalayerVisitors:od,datalayerKept:sd,embedToken:ad,targetFixed:pd,themeVariant:gd,themeOverrides:_d,colorMode:yd,presence:bd,showTokenUsage:Sd,voice:Ed,thread:cd,floatingPrompt:dd=!1,editorSelector:md=!1,editors:ld=!0,conversation:hd=!0,commandPalette:vd=!1,pluginsPanel:wd=!1,windowFrame:kd=!1,firstPromptHook:Rd}=Au,Od=Ru??(ld?"notebook":"none");return hd?[configurePlugin(ChatPlugin,{defaultSurface:Od,showSurfaceSelector:ld&&Iu&&!md,hideHeader:Pu,headerButtons:{newChat:Ou,clear:Ou},promptPlacement:dd?"floating":Mu,autoFocusPrompt:Du,suggestionLabels:Lu,fullScreenTopOffset:Bu,themeVariant:gd,themeOverrides:_d,colorMode:yd,presence:bd,showTokenUsage:Sd,...Ed?{voice:Ed}:{},...cd?{thread:cd}:{}}),configurePlugin(InputPromptPlugin,{firstPromptHook:Rd}),ChatHeaderPlugin,A2uiSurfacePlugin,PapSignInPlugin,ShieldDisplaysPlugin,ChatViewPlugin,...ld?[NotebookViewPlugin,DocumentViewPlugin]:[],configurePlugin(AgentsPlugin,{serverUrl:lo,target:$u,datalayerAgentSpecId:td,datalayerCreatePayload:nd,datalayerVisitors:od,datalayerKept:sd,embedToken:ad,targetFixed:pd,showAgentVariants:ju,showAgentSummary:Fu,teamId:zu,showTeamPicker:Uu,localAgent:Xu??(ed?{createPayload:{description:`Local agent from the ${ed} spec`,agent_library:"pydantic-ai",agent_spec_id:ed,enable_codemode:!1}}:void 0)}),...ld?[NotebookExtension,DocumentExtension]:[],A2uiPlugin,AgentspecsPlugin,ModelsPlugin,ThemePlugin,SubagentActivityPlugin,configurePlugin(ShellPlugin,{defaultEditor:Od,showSelector:ld&&md}),...dd?[PromptPlugin]:[],...Hu?[configurePlugin(LoopPageLayoutPlugin,{arrangement:Vu,turnPanel:Gu,turnPanelFooter:Yu,prompt:Wu,promptAnchor:Ku,pageSize:Ju})]:[],...vd?[LoopCommandsPlugin]:[],...wd?[PluginsPanelPlugin]:[],...kd?[WindowFramePlugin]:[]]:[ThemePlugin,configurePlugin(ShellPlugin,{defaultEditor:"none",showSelector:!1}),...vd?[LoopCommandsPlugin]:[],...wd?[PluginsPanelPlugin]:[],...kd?[WindowFramePlugin]:[]]}function LoopEmbed({agentId:Au="",showHeader:lo=!1,chatHeaderActions:$u,headerActions:Ru,headerContainer:Iu,frameTitle:Pu,frameHeight:Ou,sidebarRail:Mu=!1,plugins:Du=[],...Lu}){const Bu=reactExports.useRef(Lu.firstPromptHook);Bu.current=Lu.firstPromptHook;const ju=reactExports.useMemo(()=>buildLoopReactor([...loopPlugins({...Lu,windowFrame:Lu.windowFrame||Pu!==void 0,firstPromptHook:()=>Bu.current?.()}),...Du]),[Lu.serverUrl,Lu.target,Lu.datalayerAgentSpecId,Lu.targetFixed,Lu.themeVariant,JSON.stringify(Lu.themeOverrides??null),Lu.colorMode,Lu.presence?.name,Lu.presence?.face,Lu.presence?.welcome,Lu.presence?.paused,Lu.showTokenUsage,JSON.stringify({...Lu.voice??{},engines:void 0,token:void 0}),Lu.thread?.id,JSON.stringify(Lu.datalayerCreatePayload??null),JSON.stringify(Lu.datalayerVisitors??null),Lu.datalayerKept?.url,Lu.embedToken,Lu.defaultEditor,Lu.showViewSelector,Lu.hideChatHeader,Lu.chatHeaderButtons,Lu.promptPlacement,Lu.autoFocusPrompt,Lu.suggestionLabels,Lu.fullScreenTopOffset,Lu.showAgentVariants,Lu.agentSummary,Lu.teamId,Lu.teamPicker,Lu.pageLayout,Lu.pageLayoutTurnPanel,Lu.pageLayoutTurnPanelFooter,Lu.pageLayoutPrompt,Lu.pageLayoutPromptAnchor,Lu.pageLayoutSize?.format,Lu.pageLayoutSize?.width,Lu.pageLayoutSize?.height,Lu.localAgentSpec,Lu.floatingPrompt,Lu.editorSelector,Lu.editors,Lu.conversation,Lu.commandPalette,Lu.pluginsPanel,Lu.windowFrame,Pu!==void 0,Du]);useReactor(ju);const Fu=jsxRuntimeExports.jsx(LoopWorkspace,{serverUrl:Lu.serverUrl??"",agentId:Au,reactor:ju,manageReactor:!1,showViewSelector:Lu.showViewSelector,showHeader:lo,chatHeaderActions:$u,headerActions:Ru,headerContainer:Iu,sidebarRail:Mu});return jsxRuntimeExports.jsx(QueryClientProvider,{client:internalQueryClient,children:Pu!==void 0?jsxRuntimeExports.jsx(WindowFrame,{title:Pu,height:Ou,children:Fu}):jsxRuntimeExports.jsx(Box,{height:"100%",minHeight:0,width:"100%",flex:"1 1 auto",minWidth:0,children:Fu})})}const RECORD_KIND_WORDS={session:"Session",tool_call:"Tool call",decision:"Rule",check:"Check",approval:"Approval",output:"Answer",feedback:"Feedback",turn:"Turn",run:"Working",notification:"Notification"};function entryOf(Au){return{uid:String(Au.uid??""),sessionUid:String(Au.session_uid??""),deploymentUid:String(Au.deployment_uid??""),version:Number(Au.version)||0,kind:String(Au.kind??"output"),summary:String(Au.summary??""),payload:Au.payload&&typeof Au.payload=="object"?Au.payload:{},createdAt:String(Au.created_at??"")}}function runEndOf(Au){const lo=Au.kind==="output"?Au.payload.status:void 0;return typeof lo=="string"&&lo in RUN_END_WORDS?lo:""}function entrySaid(Au){return Au.summary||RUN_END_WORDS[runEndOf(Au)]||""}function sessionSentence(Au){const lo=Au.filter(Ou=>Ou.kind==="tool_call").length,$u=Au.filter(Ou=>Ou.kind==="check"),Ru=Au.map(runEndOf).filter(Boolean),Iu=Ru.filter(Ou=>Ou==="answered").length,Pu=[lo===0?"No tool called":`${lo} tool call${lo===1?"":"s"}`];return $u.length&&Pu.push(`${$u.length} step${$u.length===1?"":"s"} a check did not let pass`),Ru[Ru.length-1]==="stopped"?Pu.push("stopped"):Iu&&Pu.push(`${Iu} answer${Iu===1?"":"s"}`),`${Pu.join(", ")}.`}async function read(Au,lo,$u){if(!Au.aiAgentsUrl)throw new Error("The record service is not configured.");const Ru=await fetch(`${Au.aiAgentsUrl.replace(/\/+$/,"")}/api/ai-agents/v1/apps${lo}`,{headers:Au.token?{Authorization:`Bearer ${Au.token}`}:{}}),Iu=await Ru.json().catch(()=>({}));if(!Ru.ok||Iu.success===!1)throw new Error(`${$u}: ${String(Iu.detail??Ru.status)}`);return Iu}async function listSessions(Au,lo,$u=20,Ru=!1){const Iu=await read(Au,`/sessions?app_uid=${encodeURIComponent(lo)}&limit=${$u}${Ru===null?"":`&tests=${Ru}`}`,"The sessions could not be read");return Array.isArray(Iu.sessions)?Iu.sessions.map(entryOf):[]}async function readSession(Au,lo){const $u=await read(Au,`/records?session_uid=${encodeURIComponent(lo)}&limit=500`,"The session could not be read");return Array.isArray($u.entries)?$u.entries.map(entryOf).filter(Ru=>Ru.kind!=="run"):[]}const APP_ACTIVITY_WORDS={title:"Activity",unsaved:"Recorded once it is saved on Datalayer: each session there — its address, or its Preview on Datalayer — is listed here.",signedOut:"Its activity is its owner’s: sign in to Datalayer to read it.",none:"Nothing yet: a session on Datalayer — its address, or the Preview on Datalayer — is recorded here."},NO_TURN$3=signal$2({id:0,status:"idle"});function useRead(Au,lo,$u=!0){const[Ru,Iu]=reactExports.useState({loading:$u});return reactExports.useEffect(()=>{if(!$u)return;let Pu=!1;return Iu(Ou=>({...Ou,loading:!0})),Au().then(Ou=>!Pu&&Iu({value:Ou,loading:!1}),Ou=>!Pu&&Iu({error:Ou instanceof Error?Ou.message:String(Ou),loading:!1})),()=>{Pu=!0}},[lo,$u]),Ru}function Session({context:Au,session:lo}){const[$u,Ru]=reactExports.useState(!1),Iu=useRead(()=>readSession(Au,lo.sessionUid),`${lo.sessionUid}:${Au.token}`,$u);return jsxRuntimeExports.jsxs(Box,{as:"details",onToggle:Pu=>Ru(Pu.currentTarget.open),borderTop:"1px solid",borderColor:"border.muted",py:2,children:[jsxRuntimeExports.jsxs(Box,{as:"summary",cursor:"pointer",fontSize:1,children:[lo.createdAt?jsxRuntimeExports.jsx(RelativeTime,{datetime:lo.createdAt}):"A session",lo.version?` · version ${lo.version}`:"",Iu.value?` · ${sessionSentence(Iu.value)}`:""]}),$u?Iu.loading?jsxRuntimeExports.jsx(StyledSpinner,{size:"small"}):Iu.error?jsxRuntimeExports.jsx(Text$3,{role:"alert",sx:{fontSize:1},children:Iu.error}):jsxRuntimeExports.jsx(Box,{as:"ol",pl:3,mt:2,mb:0,fontSize:1,children:(Iu.value??[]).map(Pu=>jsxRuntimeExports.jsxs(Box,{as:"li",mb:1,children:[jsxRuntimeExports.jsx(Label,{sx:{mr:2},children:RECORD_KIND_WORDS[Pu.kind]??Pu.kind}),entrySaid(Pu)]},Pu.uid))}):null]})}function AppActivity({appUid:Au}){const lo=useIAMStore(ju=>ju.token)??"",$u=useCoreStore(ju=>ju.configuration)?.aiAgentsUrl??"",Ru=useContributions(LoopChatTurn),Iu=useSignalValue$1(Ru[0]?.value.turn??NO_TURN$3),Pu=Iu.status!=="thinking"&&Iu.status!=="streaming",[Ou,Mu]=reactExports.useState(0);reactExports.useEffect(()=>{Pu&&Mu(Iu.id)},[Pu,Iu.id]);const Du={aiAgentsUrl:$u,token:lo},Lu=!!(Au&&lo),Bu=useRead(()=>listSessions(Du,Au??""),`${Au}:${lo}:${$u}:${Ou}`,Lu);return jsxRuntimeExports.jsxs(Box,{"data-testid":"app-activity",children:[jsxRuntimeExports.jsx(Heading$2,{as:"h3",sx:{fontSize:2,mb:2},children:APP_ACTIVITY_WORDS.title}),Au?lo?Bu.loading&&!Bu.value?jsxRuntimeExports.jsx(StyledSpinner,{size:"small"}):Bu.error?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:1,color:"fg.muted",m:0},children:Bu.error}):(Bu.value??[]).length===0?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:1,color:"fg.muted",m:0},children:APP_ACTIVITY_WORDS.none}):(Bu.value??[]).map(ju=>jsxRuntimeExports.jsx(Session,{context:Du,session:ju},ju.uid)):jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:1,color:"fg.muted",m:0},children:APP_ACTIVITY_WORDS.signedOut}):jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:1,color:"fg.muted",m:0},children:APP_ACTIVITY_WORDS.unsaved})]})}const APP_ACTIVITY_PLUGIN_NAME="@datalayer/loop-plugin-app-activity";function defineAppActivityPlugin(Au,lo){function $u(){return jsxRuntimeExports.jsx(AppActivity,{appUid:lo})}return{name:`${APP_ACTIVITY_PLUGIN_NAME}-${Au.id}`,displayName:`${Au.name}: activity`,description:`What ${Au.name} did, session by session, from its record.`,octicon:"pulse",build:()=>({components:[{id:"app-activity",slot:LoopSlots.sidebar,order:20,Component:$u,rail:{label:"Activity",icon:PulseIcon}}]})}}const APP_PANEL_WIDTH=380;function elementsByPlace(Au){const lo=Au.filter($u=>$u.where==="page");return{panels:Au.filter($u=>$u.where==="panel"),page:lo.length>0?lo[lo.length-1]:null}}function ElementBody({element:Au,send:lo}){return jsxRuntimeExports.jsx(AnswerShowsView,{display:Au.shows,send:($u,Ru)=>lo!==void 0&&!lo($u,Ru)})}function ElementHeader({element:Au}){return jsxRuntimeExports.jsxs(Box,{display:"flex",alignItems:"center",justifyContent:"space-between",gap:2,mb:2,children:[jsxRuntimeExports.jsx(Text$3,{as:"h2",sx:{fontSize:2,fontWeight:"bold",m:0},children:Au.title}),jsxRuntimeExports.jsx(IconButton,{icon:XIcon,variant:"invisible",size:"small","aria-label":`Close ${Au.title}`,onClick:()=>closeLoopElement(Au.id)})]})}function AppElements({workspace:Au}){const lo=reactExports.useSyncExternalStore(onLoopElements,openLoopElements,openLoopElements),{panels:$u,page:Ru}=elementsByPlace(lo),Iu=Au?.viewControls.send;return $u.length===0&&Ru===null?null:jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[$u.length>0?jsxRuntimeExports.jsx(Box,{as:"aside","aria-label":"Side panel",position:"absolute",top:0,right:0,bottom:0,width:`min(${APP_PANEL_WIDTH}px, 100%)`,zIndex:1,overflowY:"auto",borderLeft:"1px solid",borderColor:"border.default",bg:"canvas.subtle",boxShadow:"shadow.medium",p:3,display:"flex",flexDirection:"column",gap:3,children:$u.map(Pu=>jsxRuntimeExports.jsxs(Box,{as:"section","aria-label":Pu.title,children:[jsxRuntimeExports.jsx(ElementHeader,{element:Pu}),jsxRuntimeExports.jsx(ElementBody,{element:Pu,send:Iu})]},Pu.id))}):null,Ru!==null?jsxRuntimeExports.jsxs(Box,{role:"dialog","aria-label":Ru.title,position:"absolute",inset:0,zIndex:2,overflowY:"auto",bg:"canvas.default",p:[3,4],children:[jsxRuntimeExports.jsx(ElementHeader,{element:Ru}),jsxRuntimeExports.jsx(ElementBody,{element:Ru,send:Iu})]}):null]})}const QUESTION_DISPLAY_TYPE="application/vnd.datalayer.loop.question+json",SchemaForm=reactExports.lazy(()=>__vitePreload(()=>import("./chunks/SchemaForm-CE5NfpBU.js"),[],import.meta.url));function questionOf(Au){const lo=Au.data??{},$u=lo.kind;if(Au.type!==QUESTION_DISPLAY_TYPE||$u!=="text"&&$u!=="choice"&&$u!=="file"&&$u!=="form"||typeof lo.prompt!="string")throw new Error(`Display ${Au.id} is not a question`);const Ru=Iu=>Array.isArray(Iu)?Iu.filter(Pu=>typeof Pu=="string"):[];return{kind:$u,prompt:lo.prompt,options:Ru(lo.options),accept:Ru(lo.accept),form:lo.form&&typeof lo.form=="object"?lo.form:{},answered:typeof lo.answered=="string"?lo.answered:null,answerable:(Au.actions??[]).some(Iu=>Iu.name===ANSWER_ACTION)}}function QuestionView({display:Au,act:lo,upload:$u}){const Ru=questionOf(Au),[Iu,Pu]=reactExports.useState(""),[Ou,Mu]=reactExports.useState(null),Du=Bu=>{if(!lo){Mu("The chat cannot take an answer here.");return}Mu(null),Promise.resolve(lo({action:ANSWER_ACTION,payload:{value:Bu}})).catch(ju=>Mu(ju instanceof Error?ju.message:String(ju)))};if(Ru.answered!==null)return jsxRuntimeExports.jsxs(Text$3,{as:"p",sx:{color:"fg.muted",fontSize:1,m:0},children:["Answered: ",Ru.answered]});const Lu=Ru.answerable&&!!lo;return jsxRuntimeExports.jsxs(Box$1,{display:"flex",flexDirection:"column",gap:2,"data-question-kind":Ru.kind,children:[Ru.kind==="choice"?jsxRuntimeExports.jsx(Box$1,{display:"flex",gap:2,flexWrap:"wrap",children:Ru.options.map(Bu=>jsxRuntimeExports.jsx(ButtonComponent,{size:"small",disabled:!Lu,onClick:()=>Du(Bu),children:Bu},Bu))}):null,Ru.kind==="text"?jsxRuntimeExports.jsxs(Box$1,{as:"form",display:"flex",gap:2,onSubmit:Bu=>{Bu.preventDefault(),Iu.trim()&&Du(Iu.trim())},children:[jsxRuntimeExports.jsx(TextInput$1,{"aria-label":Ru.prompt,value:Iu,disabled:!Lu,onChange:Bu=>Pu(Bu.target.value)}),jsxRuntimeExports.jsx(ButtonComponent,{type:"submit",size:"small",disabled:!Lu||!Iu.trim(),children:"Answer"})]}):null,Ru.kind==="form"?jsxRuntimeExports.jsx(reactExports.Suspense,{fallback:null,children:jsxRuntimeExports.jsx(SchemaForm,{schema:Ru.form,disabled:!Lu,onSubmit:({formData:Bu})=>Du(Bu??{})})}):null,Ru.kind==="file"?jsxRuntimeExports.jsx("input",{type:"file","aria-label":Ru.prompt,accept:Ru.accept.join(",")||void 0,disabled:!Lu||!$u,onChange:Bu=>{const ju=Bu.target.files?.[0];if(ju){if(!$u){Mu("The chat cannot take a file here.");return}Mu(null),$u(ju).then(Fu=>Du(Fu)).catch(Fu=>Mu(Fu instanceof Error?Fu.message:String(Fu)))}}}):null,Ou?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{color:"danger.fg",fontSize:1,m:0},children:Ou}):null]})}const APP_ELEMENTS_PLUGIN_NAME="@datalayer/loop-plugin-app-elements",AppElementsPlugin={name:APP_ELEMENTS_PLUGIN_NAME,displayName:"Side panel and pages",description:"What an application opens beside the conversation: a side panel, or a page of its own.",octicon:"sidebar-expand",contributes:[contribution(Renderers,defineRenderer({type:QUESTION_DISPLAY_TYPE,component:QuestionView}),{id:"app-elements:question"})],build:()=>({components:[{id:"app-elements",slot:LoopSlots.root,Component:AppElements}]}),register:()=>clearLoopElements},appComponentsPluginName=Au=>`@datalayer/loop-plugin-app-components-${Au}`,hasCustomComponents=Au=>(Au.interface.customComponents??[]).length>0;function defineAppComponentsPlugin(Au,lo){const $u=Au.interface.customComponents??[];if($u.length===0)throw new Error(`“${Au.name}” has no component of its own to contribute.`);return{name:appComponentsPluginName(Au.id),displayName:`${Au.name}'s components`,description:`The components ${Au.name}'s developer wrote: ${$u.map(Ru=>Ru.name).join(", ")}.`,octicon:"apps",contributes:$u.flatMap(Ru=>[contribution(LoopCanvasBlock,{id:Ru.name,ui:`app:${Au.id}`,component:customComponentEntry(Ru,Au.version)},{id:Ru.name}),contribution(LoopA2uiComponent,{id:Ru.name,app:Au.id,implementation:customImplementation(Ru,Au.version,lo,Au.id)},{id:Ru.name})])}}const COMPUTER_PARTS=["browse","files","shell"],COMPUTER_PART_TOOLS={browse:["open_page","read_page","page_screenshot","click_on_page","type_on_page"],files:["list_computer_files","read_computer_file","write_computer_file"],shell:["execute_code","run_skill_script"]},COMPUTER_WORDS={title:"Computer",part:{browse:"Browse",files:"Files",shell:"Shell"},on:"on",off:"off",none:"It has no computer: browse, files and shell are all off. Turn one on in its permissions to give it one.",offSaid:Au=>`Off, so its agent is given no tool for it: ${Au.join(", ")}.`,browser:"Browser",noBrowser:"No browser is installed on its computer.",noPage:"Its browser has opened no page yet.",pageAlt:Au=>`The page its browser shows: ${Au}`,clickToAct:"Click on the page to click there; with the page selected, what you type goes to it.",typeOnPage:"Text to type on the page",type:"Type",address:"An address to open",open:"Open",scrollUp:"Scroll up",scrollDown:"Scroll down",agentHas:"Its agent has the computer.",youHave:"You have the computer: its agent waits for it until you hand it back.",someoneHas:"Somebody else has taken this computer over.",takeOver:"Take over",handBack:"Hand back",run:"Run",yourCode:"Python to run on its computer",terminal:"What ran on it",nothingRan:"Nothing has run on it yet in this conversation.",files:"Files",notStarted:"Its computer starts when its agent first uses it: no file yet.",emptyDirectory:"Empty.",up:"Up",download:"Download",signedOut:"Its computer is shown once you are signed in to Datalayer."};function computerParts(Au){const lo=Au.permissions?.computer;return{browse:!!lo?.browse,files:!!lo?.files,shell:!!lo?.shell}}const hasComputer=Au=>COMPUTER_PARTS.some(lo=>Au[lo]),partsOff=Au=>COMPUTER_PARTS.filter(lo=>!Au[lo]).map(lo=>COMPUTER_WORDS.part[lo].toLowerCase());function partOf(Au){return COMPUTER_PARTS.find(lo=>COMPUTER_PART_TOOLS[lo].includes(Au))}const OUTPUT_LIMIT=4e3;function outputOf(Au){let lo=Au;if(typeof lo=="string")try{const Ru=JSON.parse(lo);Ru&&typeof Ru=="object"&&!Array.isArray(Ru)&&(lo=Ru)}catch{}let $u;if(lo&&typeof lo=="object"&&!Array.isArray(lo)){const Ru=lo,Iu=[typeof Ru.stdout=="string"?Ru.stdout:Ru.output,Ru.stderr,Ru.error??Ru.execution_error??Ru.code_error].filter(Pu=>typeof Pu=="string"&&Pu.trim()!=="");$u=Iu.length>0?Iu.join(`
|
|
4014
4017
|
`):"stdout"in Ru||"output"in Ru?"":JSON.stringify(lo,null,2)}else $u=typeof lo=="string"?lo:lo==null?"":JSON.stringify(lo,null,2);return $u.length>OUTPUT_LIMIT?`${$u.slice(0,OUTPUT_LIMIT)}
|
|
4015
4018
|
… (${($u.length-OUTPUT_LIMIT).toLocaleString("en")} characters more)`:$u}function commandOf(Au){for(const lo of["code","path","script_name","url","selector"]){const $u=Au[lo];if(typeof $u=="string"&&$u.trim())return $u}return Object.keys(Au).length?JSON.stringify(Au):""}function terminalEntries(Au){const lo=[];for(const $u of Au){if($u.role!=="tool")continue;const Ru=partOf($u.name);Ru&&lo.push({tool:$u.name,part:Ru,command:commandOf($u.args??{}),output:$u.result===void 0?void 0:outputOf($u.result)})}return lo}const computerUrl=(Au,lo="")=>`${Au.serverUrl.replace(/\/+$/,"")}/api/v1/apps/agents/${encodeURIComponent(Au.agentId)}/computer${lo}`;function computerFileUrl(Au,lo){const $u=computerUrl(Au,`/file?path=${encodeURIComponent(lo)}`),Ru=(Au.userAppsUrl||"").trim();if(!Ru)return $u;try{const Iu=new URL($u),Pu=new URL(Ru);return Iu.protocol=Pu.protocol,Iu.host=Pu.host,Iu.toString()}catch{return $u}}async function asked(Au,lo,$u={}){const Ru=await fetch(computerUrl(Au,lo),{...$u,headers:{...$u.body?{"Content-Type":"application/json"}:{},...Au.token?{Authorization:`Bearer ${Au.token}`}:{}}});if(!Ru.ok){let Iu=`${Ru.status}`;try{const Pu=await Ru.json();Iu=typeof Pu.detail=="string"?Pu.detail:Iu}catch{}throw new Error(Iu)}return Ru}const readComputer=async Au=>(await asked(Au,"")).json(),listComputerFiles=async(Au,lo=".")=>(await(await asked(Au,`/files?path=${encodeURIComponent(lo)}`)).json()).entries,downloadComputerFile=async(Au,lo)=>{const $u=await fetch(computerFileUrl(Au,lo),{headers:Au.token?{Authorization:`Bearer ${Au.token}`}:{}});if(!$u.ok){let Ru=`${$u.status}`;try{const Iu=await $u.json();Ru=typeof Iu.detail=="string"?Iu.detail:Ru}catch{}throw new Error(Ru)}return $u.blob()},takeOverComputer=async Au=>(await asked(Au,"/take-over",{method:"POST"})).json(),handBackComputer=async Au=>{await asked(Au,"/hand-back",{method:"POST"})},runOnComputer=async(Au,lo)=>(await asked(Au,"/run",{method:"POST",body:JSON.stringify({code:lo})})).json(),BROWSER_KEYS=["Enter","Tab","Backspace","Escape","ArrowUp","ArrowDown","ArrowLeft","ArrowRight","PageUp","PageDown"],readBrowserScreenshot=async Au=>{const lo=await fetch(computerUrl(Au,"/browser/screenshot"),{headers:Au.token?{Authorization:`Bearer ${Au.token}`}:{},cache:"no-store"});if(lo.status!==404){if(!lo.ok){let $u=`${lo.status}`;try{const Ru=await lo.json();$u=typeof Ru.detail=="string"?Ru.detail:$u}catch{}throw new Error($u)}return lo.blob()}},onBrowser=async(Au,lo,$u)=>(await(await asked(Au,`/browser/${lo}`,{method:"POST",body:JSON.stringify($u)})).json()).page,clickOnBrowser=(Au,lo,$u)=>onBrowser(Au,"click",{x:lo,y:$u}),typeOnBrowser=(Au,lo)=>onBrowser(Au,"type",{text:lo}),pressOnBrowser=(Au,lo)=>onBrowser(Au,"key",{key:lo}),scrollBrowser=(Au,lo)=>onBrowser(Au,"scroll",{dy:lo}),openOnBrowser=(Au,lo)=>onBrowser(Au,"open",{url:lo});function pointOnPage(Au,lo,$u){const Ru=(Iu,Pu,Ou)=>Pu>0?Math.round(Iu*Ou/Pu):Iu;return{x:Math.max(0,Math.min($u.width,Ru(Au.x,lo.width,$u.width))),y:Math.max(0,Math.min($u.height,Ru(Au.y,lo.height,$u.height)))}}function parentOf(Au){const lo=Au.split("/").filter($u=>$u&&$u!==".");return lo.pop(),lo.length?lo.join("/"):"."}const NO_TURN$2=signal$2({id:0,status:"idle"}),NO_CONVERSATION$1=signal$2([]),MONO_FACE='ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace',MONO={fontFamily:MONO_FACE,fontSize:0,whiteSpace:"pre-wrap",wordBreak:"break-word",m:0};function Parts({app:Au}){const lo=computerParts(Au),$u=partsOff(lo);return jsxRuntimeExports.jsxs(Box,{"data-testid":"computer-parts",children:[jsxRuntimeExports.jsx(Box,{display:"flex",gap:1,flexWrap:"wrap",mb:1,children:COMPUTER_PARTS.map(Ru=>jsxRuntimeExports.jsxs(Label,{variant:lo[Ru]?"success":"secondary","data-part":Ru,"data-on":lo[Ru]?"true":"false",children:[COMPUTER_WORDS.part[Ru],":"," ",lo[Ru]?COMPUTER_WORDS.on:COMPUTER_WORDS.off]},Ru))}),$u.length>0&&$u.length<COMPUTER_PARTS.length?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:0,color:"fg.muted",m:0},children:COMPUTER_WORDS.offSaid($u)}):null]})}function Terminal({conversation:Au}){const lo=terminalEntries(Au);return jsxRuntimeExports.jsxs(Box,{"data-testid":"computer-terminal",children:[jsxRuntimeExports.jsx(Heading$2,{as:"h4",sx:{fontSize:1,mt:3,mb:1},children:COMPUTER_WORDS.terminal}),lo.length===0?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:1,color:"fg.muted",m:0},children:COMPUTER_WORDS.nothingRan}):jsxRuntimeExports.jsx(Box,{bg:"canvas.inset",border:"1px solid",borderColor:"border.muted",borderRadius:2,p:2,maxHeight:320,overflow:"auto",children:lo.map(($u,Ru)=>jsxRuntimeExports.jsxs(Box,{mb:2,children:[jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{...MONO,fontWeight:"semibold"},children:`$ ${$u.tool}${$u.command?`: ${$u.command}`:""}`}),$u.output===void 0?jsxRuntimeExports.jsx(StyledSpinner,{size:"small"}):jsxRuntimeExports.jsx(Text$3,{as:"pre",sx:{...MONO,color:"fg.muted"},children:$u.output})]},Ru))})]})}function save(Au,lo){const $u=URL.createObjectURL(new Blob([Au],{type:"application/octet-stream"})),Ru=document.createElement("a");Ru.href=$u,Ru.download=lo,Ru.click(),URL.revokeObjectURL($u)}function Files({context:Au,state:lo,ended:$u}){const[Ru,Iu]=reactExports.useState("."),[Pu,Ou]=reactExports.useState(),[Mu,Du]=reactExports.useState("");return reactExports.useEffect(()=>{if(!lo.started)return;let Lu=!1;return listComputerFiles(Au,Ru).then(Bu=>{Lu||(Ou(Bu),Du(""))},Bu=>!Lu&&Du(Bu instanceof Error?Bu.message:String(Bu))),()=>{Lu=!0}},[Au.serverUrl,Au.agentId,Au.token,Ru,lo.started,$u]),jsxRuntimeExports.jsxs(Box,{"data-testid":"computer-files",children:[jsxRuntimeExports.jsxs(Heading$2,{as:"h4",sx:{fontSize:1,mt:3,mb:1},children:[COMPUTER_WORDS.files,Ru!=="."?jsxRuntimeExports.jsx(Text$3,{sx:{fontWeight:"normal",color:"fg.muted"},children:` · ${Ru}`}):null]}),lo.started?Mu?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:1,color:"danger.fg",m:0},children:Mu}):Pu?jsxRuntimeExports.jsxs(Box,{as:"ul",listStyle:"none",p:0,m:0,children:[Ru!=="."?jsxRuntimeExports.jsx(Box,{as:"li",children:jsxRuntimeExports.jsx(ButtonComponent,{size:"small",variant:"invisible",onClick:()=>Iu(parentOf(Ru)),children:COMPUTER_WORDS.up})}):null,Pu.length===0?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:1,color:"fg.muted",m:0},children:COMPUTER_WORDS.emptyDirectory}):null,Pu.map(Lu=>jsxRuntimeExports.jsx(Box,{as:"li","data-path":Lu.path,display:"flex",alignItems:"center",gap:2,fontSize:1,py:1,borderTop:"1px solid",borderColor:"border.muted",children:Lu.type==="directory"?jsxRuntimeExports.jsx(ButtonComponent,{size:"small",variant:"invisible",onClick:()=>Iu(Lu.path),children:`${Lu.name}/`}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(Text$3,{sx:{flex:1,fontFamily:MONO_FACE,fontSize:0},children:Lu.name}),jsxRuntimeExports.jsx(Text$3,{sx:{color:"fg.muted",fontSize:0},children:`${Lu.size.toLocaleString("en")} bytes`}),jsxRuntimeExports.jsx(ButtonComponent,{size:"small","aria-label":`${COMPUTER_WORDS.download} ${Lu.name}`,onClick:()=>{downloadComputerFile(Au,Lu.path).then(Bu=>save(Bu,Lu.name),Bu=>Du(Bu instanceof Error?Bu.message:String(Bu)))},children:COMPUTER_WORDS.download})]})},Lu.path))]}):jsxRuntimeExports.jsx(StyledSpinner,{size:"small"}):jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:1,color:"fg.muted",m:0},children:COMPUTER_WORDS.notStarted})]})}const BROWSER_POLL_MS=1500;function BrowserView({context:Au,state:lo,mine:$u}){const[Ru,Iu]=reactExports.useState(),[Pu,Ou]=reactExports.useState(!1),[Mu,Du]=reactExports.useState(lo.page),[Lu,Bu]=reactExports.useState(""),[ju,Fu]=reactExports.useState(""),[zu,Uu]=reactExports.useState(""),[Hu,Vu]=reactExports.useState(0),Gu=reactExports.useRef(void 0);reactExports.useEffect(()=>Du(lo.page),[lo.page]),reactExports.useEffect(()=>{if(!lo.browser)return;let Yu=!1;const Xu=()=>readBrowserScreenshot(Au).then(td=>{Yu||(Bu(""),Ou(!td),Gu.current&&URL.revokeObjectURL(Gu.current),Gu.current=td?URL.createObjectURL(td):void 0,Iu(Gu.current))},td=>!Yu&&Bu(td instanceof Error?td.message:String(td)));Xu();const ed=setInterval(Xu,BROWSER_POLL_MS);return()=>{Yu=!0,clearInterval(ed)}},[Au.serverUrl,Au.agentId,Au.token,lo.browser,Hu]),reactExports.useEffect(()=>()=>{Gu.current&&URL.revokeObjectURL(Gu.current)},[]);const Wu=Yu=>Yu.then(Xu=>{Du(Xu),Bu(""),Vu(ed=>ed+1)},Xu=>Bu(Xu instanceof Error?Xu.message:String(Xu))),Ku=Yu=>{const Xu=Yu.currentTarget,ed=Xu.getBoundingClientRect(),td=pointOnPage({x:Yu.clientX-ed.left,y:Yu.clientY-ed.top},{width:ed.width,height:ed.height},{width:Xu.naturalWidth,height:Xu.naturalHeight});Xu.focus(),Wu(clickOnBrowser(Au,td.x,td.y))},Ju=Yu=>{Yu.metaKey||Yu.ctrlKey||Yu.altKey||(BROWSER_KEYS.includes(Yu.key)?(Yu.preventDefault(),Wu(pressOnBrowser(Au,Yu.key))):Yu.key.length===1&&(Yu.preventDefault(),Wu(typeOnBrowser(Au,Yu.key))))};return jsxRuntimeExports.jsxs(Box,{"data-testid":"computer-browser",children:[jsxRuntimeExports.jsxs(Heading$2,{as:"h4",sx:{fontSize:1,mt:3,mb:1},children:[COMPUTER_WORDS.browser,Mu?jsxRuntimeExports.jsx(Text$3,{sx:{fontWeight:"normal",color:"fg.muted"},children:` · ${Mu.title||Mu.url}`}):null]}),lo.browser?Pu||!Ru?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:1,color:"fg.muted",m:0},children:Pu?COMPUTER_WORDS.noPage:null}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[Mu?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontFamily:MONO_FACE,fontSize:0,color:"fg.muted",m:0,mb:1,wordBreak:"break-all"},children:Mu.url}):null,jsxRuntimeExports.jsx("img",{src:Ru,alt:COMPUTER_WORDS.pageAlt(Mu?.title||Mu?.url||""),"data-testid":"computer-browser-page",tabIndex:$u?0:-1,onClick:$u?Ku:void 0,onKeyDown:$u?Ju:void 0,style:{width:"100%",height:"auto",display:"block",border:"1px solid var(--borderColor-muted, #d0d7de)",borderRadius:6,cursor:$u?"pointer":"default"}})]}):jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:1,color:"fg.muted",m:0},children:COMPUTER_WORDS.noBrowser}),Lu?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:1,color:"danger.fg",m:0,mt:1},children:Lu}):null,$u&&lo.browser?jsxRuntimeExports.jsxs(Box,{mt:2,"data-testid":"computer-browser-controls",children:[jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:0,color:"fg.muted",m:0,mb:1},children:COMPUTER_WORDS.clickToAct}),jsxRuntimeExports.jsxs(Box,{display:"flex",gap:1,mb:1,children:[jsxRuntimeExports.jsx(TextInput$1,{size:"small","aria-label":COMPUTER_WORDS.typeOnPage,placeholder:COMPUTER_WORDS.typeOnPage,value:ju,onChange:Yu=>Fu(Yu.target.value),sx:{flex:1}}),jsxRuntimeExports.jsx(ButtonComponent,{size:"small",disabled:!ju,onClick:()=>{Wu(typeOnBrowser(Au,ju)),Fu("")},children:COMPUTER_WORDS.type}),jsxRuntimeExports.jsx(ButtonComponent,{size:"small",onClick:()=>{Wu(pressOnBrowser(Au,"Enter"))},children:"Enter"})]}),jsxRuntimeExports.jsxs(Box,{display:"flex",gap:1,mb:1,children:[jsxRuntimeExports.jsx(TextInput$1,{size:"small","aria-label":COMPUTER_WORDS.address,placeholder:COMPUTER_WORDS.address,value:zu,onChange:Yu=>Uu(Yu.target.value),sx:{flex:1}}),jsxRuntimeExports.jsx(ButtonComponent,{size:"small",disabled:!zu.trim(),onClick:()=>{Wu(openOnBrowser(Au,zu.trim()))},children:COMPUTER_WORDS.open})]}),jsxRuntimeExports.jsxs(Box,{display:"flex",gap:1,children:[jsxRuntimeExports.jsx(ButtonComponent,{size:"small",onClick:()=>{Wu(scrollBrowser(Au,-400))},children:COMPUTER_WORDS.scrollUp}),jsxRuntimeExports.jsx(ButtonComponent,{size:"small",onClick:()=>{Wu(scrollBrowser(Au,400))},children:COMPUTER_WORDS.scrollDown})]})]}):null]})}function YourTerminal({context:Au}){const[lo,$u]=reactExports.useState(""),[Ru,Iu]=reactExports.useState(!1),[Pu,Ou]=reactExports.useState([]),Mu=()=>{Iu(!0),runOnComputer(Au,lo).then(Du=>{Ou(Lu=>[...Lu,{code:lo,output:Du}]),$u(""),Iu(!1)},Du=>{Ou(Lu=>[...Lu,{code:lo,output:{stdout:"",stderr:"",error:Du instanceof Error?Du.message:String(Du)}}]),Iu(!1)})};return jsxRuntimeExports.jsxs(Box,{"data-testid":"computer-your-terminal",mt:2,children:[Pu.map((Du,Lu)=>jsxRuntimeExports.jsxs(Box,{mb:2,children:[jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{...MONO,fontWeight:"semibold"},children:`>>> ${Du.code}`}),jsxRuntimeExports.jsx(Text$3,{as:"pre",sx:{...MONO,color:"fg.muted"},children:[Du.output.stdout,Du.output.stderr,Du.output.error].filter(Boolean).join(`
|
|
4016
4019
|
`)})]},Lu)),jsxRuntimeExports.jsx(Textarea,{"aria-label":COMPUTER_WORDS.yourCode,placeholder:COMPUTER_WORDS.yourCode,value:lo,onChange:Du=>$u(Du.target.value),sx:{width:"100%",fontFamily:MONO_FACE},rows:3}),jsxRuntimeExports.jsx(ButtonComponent,{size:"small",sx:{mt:1},disabled:Ru||!lo.trim(),onClick:Mu,children:COMPUTER_WORDS.run})]})}function AppComputer({app:Au,workspace:lo}){const $u=useIAMStore(sd=>sd.token)??"",Ru=useContributions(LoopChatTurn),Iu=useSignalValue$1(Ru[0]?.value.turn??NO_TURN$2),Pu=useSignalValue$1(Ru[0]?.value.conversation??NO_CONVERSATION$1),Ou=Iu.status!=="thinking"&&Iu.status!=="streaming",[Mu,Du]=reactExports.useState(0);reactExports.useEffect(()=>{Ou&&Du(Iu.id)},[Ou,Iu.id]);const Lu=useChatWords(),Bu=lo?agentServerOf(lo.sandbox,lo.serverUrl):void 0,ju=Bu===void 0?noRuntimeSaid(lo?.sandbox??IDLE_SANDBOX_SNAPSHOT,Lu):void 0,Fu=lo?.agentId||Au.id,[zu,Uu]=reactExports.useState(),Hu=zu?.servedFrom??"",Vu=reactExports.useMemo(()=>Bu===void 0?void 0:{serverUrl:Bu,agentId:Fu,token:$u||void 0,userAppsUrl:Hu||void 0},[Bu,Fu,$u,Hu]),Gu=computerParts(Au),[Wu,Ku]=reactExports.useState(""),[Ju,Yu]=reactExports.useState(!1),Xu=reactExports.useRef(!0);reactExports.useEffect(()=>(Xu.current=!0,()=>{Xu.current=!1}),[]);const ed=reactExports.useCallback(()=>{Vu&&readComputer(Vu).then(sd=>{Xu.current&&(Uu(sd),Ku(""))},sd=>Xu.current&&Ku(sd instanceof Error?sd.message:String(sd)))},[Vu]),td=hasComputer(Gu);reactExports.useEffect(()=>{td&&Vu&&ed()},[td,Vu,ed,Mu]);const nd=sd=>{Vu&&(Yu(!0),sd(Vu).then(()=>{Xu.current&&(Yu(!1),ed())},ad=>{Xu.current&&(Yu(!1),Ku(ad instanceof Error?ad.message:String(ad)))}))},od=!!zu?.yours;return jsxRuntimeExports.jsxs(Box,{"data-testid":"app-computer",children:[jsxRuntimeExports.jsx(Heading$2,{as:"h3",sx:{fontSize:2,mb:2},children:COMPUTER_WORDS.title}),jsxRuntimeExports.jsx(Parts,{app:Au}),td?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[ju?jsxRuntimeExports.jsx(Text$3,{as:"p",role:"status",sx:{fontSize:1,color:"fg.default",m:0,mt:2},children:ju}):null,Wu?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:1,color:"danger.fg",m:0,mt:2},children:Wu}):null,zu&&Vu?jsxRuntimeExports.jsxs(Box,{mt:2,"data-testid":"computer-holder",children:[jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:1,m:0,mb:1},children:zu.held?od?COMPUTER_WORDS.youHave:COMPUTER_WORDS.someoneHas:COMPUTER_WORDS.agentHas}),zu.held?od?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(ButtonComponent,{size:"small",variant:"primary",disabled:Ju,onClick:()=>nd(handBackComputer),children:COMPUTER_WORDS.handBack}),jsxRuntimeExports.jsx(YourTerminal,{context:Vu})]}):null:jsxRuntimeExports.jsx(ButtonComponent,{size:"small",disabled:Ju,onClick:()=>nd(takeOverComputer),children:COMPUTER_WORDS.takeOver})]}):null,Gu.browse&&zu&&Vu?jsxRuntimeExports.jsx(BrowserView,{context:Vu,state:zu,mine:od}):null,jsxRuntimeExports.jsx(Terminal,{conversation:Pu}),zu&&Vu?jsxRuntimeExports.jsx(Files,{context:Vu,state:zu,ended:Mu}):null]}):jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:1,color:"fg.muted",m:0,mt:1},children:COMPUTER_WORDS.none})]})}const APP_COMPUTER_PLUGIN_NAME="@datalayer/loop-plugin-app-computer";function defineAppComputerPlugin(Au){function lo({workspace:Ru}){return jsxRuntimeExports.jsx(AppComputer,{app:Au,workspace:Ru})}return{name:`${APP_COMPUTER_PLUGIN_NAME}-${Au.id}`,displayName:`${Au.name}: computer`,description:`The computer ${Au.name} runs on: what ran on it, its files, and taking it over.`,octicon:"device-desktop",build:()=>({components:[{id:"app-computer",slot:LoopSlots.sidebar,order:30,Component:lo,rail:{label:"Computer",icon:DeviceDesktopIcon}}]})}}const SAVE_TOOL="save_to_space",SAVE_WORDS={approve:"Approve and save",decline:"Decline",where:Au=>Au?`To keep as a page of ${Au}:`:"To keep as a page of its Space:"};function draftOfApproval(Au){if(Au.tool_name!==SAVE_TOOL)return null;const lo=$u=>{const Ru=Au.tool_args?.[$u];return typeof Ru=="string"?Ru:""};return{title:lo("title"),content:lo("content"),space:lo("space")}}const APP_RULES_WORDS={title:"Rules and approvals",byDefault:"With no rule of its own: reading is done, anything else waits for you.",none:"It has no rule of its own.",waiting:"Waiting for you",nothingWaiting:"Nothing is waiting for your yes.",signedOut:"Its approvals reach you here once you are signed in to Datalayer.",offline:"Approvals are not connected yet: what you approve or reject is not sent until they are.",approve:"Approve",reject:"Reject"};function ruleInWords(Au){const lo=BEHAVIOUR_WORDS[Au.behaviour];return{action:Au.action,covers:Au.appliesTo.map(coverOf).join(", "),says:lo.says,means:lo.means}}const ruleOfApproval=Au=>{const lo=Au.tool_args?._rule??Au.tool_args?._check;return typeof lo=="string"?lo:""};function approvalsOfApp(Au,lo){return Au.filter($u=>$u.agent_id===lo||$u.tool_args?._app===lo)}const PENDING={status:"pending"};function DraftShown({draft:Au}){return jsxRuntimeExports.jsxs(Box,{"data-testid":"app-draft",mt:1,children:[jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{m:0,fontSize:0,color:"fg.muted"},children:SAVE_WORDS.where(Au.space)}),jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{m:0,fontWeight:"semibold"},children:Au.title}),jsxRuntimeExports.jsx(Box,{as:"pre",m:0,mt:1,p:2,maxHeight:240,overflow:"auto",whiteSpace:"pre-wrap",fontFamily:"inherit",fontSize:0,bg:"canvas.subtle",borderRadius:2,children:Au.content})]})}function Approvals({app:Au}){const lo=useToolApprovalsQuery(PENDING),$u=useApproveToolRequest(),Ru=useRejectToolRequest(),Iu=reactExports.useMemo(()=>approvalsOfApp(lo.data?.approvals??[],Au.id),[lo.data,Au.id]);return jsxRuntimeExports.jsxs(Box,{"data-testid":"app-approvals",children:[jsxRuntimeExports.jsx(Heading$2,{as:"h4",sx:{fontSize:1,mt:3,mb:1},children:APP_RULES_WORDS.waiting}),$u.connectionState!=="connected"?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:0,color:"fg.muted",m:0,mb:1},children:APP_RULES_WORDS.offline}):null,Iu.length===0?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:1,color:"fg.muted",m:0},children:APP_RULES_WORDS.nothingWaiting}):jsxRuntimeExports.jsx(Box,{as:"ul",listStyle:"none",p:0,m:0,children:Iu.map(Pu=>{const Ou=draftOfApproval(Pu);return jsxRuntimeExports.jsxs(Box,{as:"li",py:2,borderTop:"1px solid",borderColor:"border.muted",fontSize:1,children:[jsxRuntimeExports.jsx(Text$3,{sx:{fontWeight:"semibold"},children:Pu.tool_name}),ruleOfApproval(Pu)?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{m:0,color:"fg.muted",fontSize:0},children:ruleOfApproval(Pu)}):null,Ou?jsxRuntimeExports.jsx(DraftShown,{draft:Ou}):null,jsxRuntimeExports.jsxs(Box,{display:"flex",gap:2,mt:1,children:[jsxRuntimeExports.jsx(ButtonComponent,{size:"small",variant:"primary",disabled:$u.isPending,onClick:()=>$u.mutate({id:Pu.id}),children:Ou?SAVE_WORDS.approve:APP_RULES_WORDS.approve}),jsxRuntimeExports.jsx(ButtonComponent,{size:"small",disabled:Ru.isPending,onClick:()=>Ru.mutate({id:Pu.id}),children:Ou?SAVE_WORDS.decline:APP_RULES_WORDS.reject})]})]},Pu.id)})})]})}function AppRulesCard({app:Au}){const lo=!!useIAMStore($u=>$u.token);return jsxRuntimeExports.jsxs(Box,{"data-testid":"app-rules",mb:4,children:[jsxRuntimeExports.jsx(Heading$2,{as:"h3",sx:{fontSize:2,mb:2},children:APP_RULES_WORDS.title}),Au.rules.length===0?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:1,color:"fg.muted",m:0},children:APP_RULES_WORDS.none}):jsxRuntimeExports.jsx(Box,{as:"ul",listStyle:"none",p:0,m:0,children:Au.rules.map(ruleInWords).map(($u,Ru)=>jsxRuntimeExports.jsxs(Box,{as:"li",py:1,fontSize:1,children:[jsxRuntimeExports.jsx(Text$3,{children:$u.action})," ",jsxRuntimeExports.jsx(Label,{title:$u.means,children:$u.says}),jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{m:0,color:"fg.muted",fontSize:0},children:$u.covers})]},Ru))}),jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:0,color:"fg.muted",mt:1,mb:0},children:APP_RULES_WORDS.byDefault}),lo?jsxRuntimeExports.jsx(Approvals,{app:Au}):jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:1,color:"fg.muted",mt:3,mb:0},children:APP_RULES_WORDS.signedOut})]})}const APP_RULES_PLUGIN_NAME="@datalayer/loop-plugin-app-rules";function defineAppRulesPlugin(Au){function lo(){return jsxRuntimeExports.jsx(AppRulesCard,{app:Au})}return{name:`${APP_RULES_PLUGIN_NAME}-${Au.id}`,displayName:`${Au.name}: rules and approvals`,description:`When ${Au.name} acts alone, when it asks, and what waits for your yes.`,octicon:"shield-check",build:()=>({components:[{id:"app-rules",slot:LoopSlots.sidebar,order:10,Component:lo,rail:{label:"Rules",icon:ShieldCheckIcon}}]})}}const COMMAND_INPUT="{input}";function commandPrompt(Au,lo=""){const $u=lo.trim();return Au.prompt.includes(COMMAND_INPUT)?Au.prompt.split(COMMAND_INPUT).join($u).trim():$u?`${Au.prompt}
|
|
@@ -4060,4 +4063,4 @@ iframe.datalayer-app-frame {
|
|
|
4060
4063
|
`;return Au?`${lo}
|
|
4061
4064
|
${scopeThemeCss(Au,[`[${THEME_SCOPE_ATTRIBUTE}]`])}`:lo}const EMBED_SESSION_KEY_PREFIX="datalayer-app:session";function visitOfToken(Au){const lo=Au?.split(".")[1];if(lo)try{const $u=lo.replace(/-/g,"+").replace(/_/g,"/"),Ru=$u+"=".repeat((4-$u.length%4)%4),Iu=JSON.parse(atob(Ru));return typeof Iu.visit=="string"&&Iu.visit?Iu.visit:void 0}catch{return}}function embedSessionKey(Au,lo){return`${EMBED_SESSION_KEY_PREFIX}:${Au}:${lo}`}const IN_MEMORY=new Map;function hostStorage(){try{return typeof window<"u"?window.localStorage:void 0}catch{return}}function sessionKeeper({persist:Au,storage:lo=hostStorage}){return{read:$u=>{if(Au)try{const Ru=lo()?.getItem($u);if(Ru)return Ru}catch{}return IN_MEMORY.get($u)},keep:($u,Ru)=>{if(IN_MEMORY.set($u,Ru),Au)try{lo()?.setItem($u,Ru)}catch{}},forget:$u=>{IN_MEMORY.delete($u);try{lo()?.removeItem($u)}catch{}}}}async function reattachSession({serverUrl:Au,uid:lo,token:$u,fetcher:Ru=fetch}){try{const Iu=await Ru(`${Au.replace(/\/+$/,"")}/api/v1/apps/sessions/${encodeURIComponent(lo)}/messages`,{headers:{Authorization:`Bearer ${$u}`}});if(!Iu.ok)return{kind:"gone",uid:lo};const Pu=await Iu.json();return{kind:"resumed",uid:lo,messages:messagesOfThread(Pu.messages)}}catch{return{kind:"gone",uid:lo}}}const WINDOW_NOT_YET='The application takes a window message once its conversation has started, on its own server (the "server" attribute).';async function postWindowMessage({serverUrl:Au,uid:lo,token:$u,data:Ru,fetcher:Iu=fetch}){const Pu=await Iu(`${Au.replace(/\/+$/,"")}/api/v1/apps/sessions/${encodeURIComponent(lo)}/window`,{method:"POST",headers:{"content-type":"application/json",...$u?{Authorization:`Bearer ${$u}`}:{}},body:JSON.stringify({data:Ru})});if(!Pu.ok){let Mu="";try{const Du=await Pu.json();Mu=typeof Du.detail=="string"?Du.detail:""}catch{}throw new Error(Mu||`The window message was refused (${Pu.status}).`)}const Ou=windowTurnErrorOf(await Pu.text());if(Ou)throw new Error(Ou)}const sessionGoneSentence=Au=>`Your earlier conversation with ${Au} has ended, so this is a new one.`;function useEmbedSession({app:Au,serverUrl:lo,embedToken:$u,resume:Ru=!0}){const Iu=lo&&$u?visitOfToken($u):void 0,Pu=Iu?embedSessionKey(Au.id,Iu):void 0,Ou=reactExports.useMemo(()=>sessionKeeper({persist:Ru}),[Ru]),[Mu,Du]=reactExports.useState();return reactExports.useEffect(()=>{if(!Pu||!lo||!$u)return;let Lu=!1;const Bu=zu=>{Ou.keep(Pu,zu),Du(Uu=>Uu?.said?{...Uu,said:void 0}:Uu)},ju=zu=>Du({token:$u,thread:{id:generateMessageId(),messages:[],onStarted:Bu},...zu?{said:zu}:{}}),Fu=Ou.read(Pu);if(!Fu){ju();return}return reattachSession({serverUrl:lo,uid:Fu,token:$u}).then(zu=>{if(!Lu){if(zu.kind==="resumed"){Du({token:$u,thread:{id:Fu,messages:zu.messages,onStarted:Bu}});return}Ou.forget(Pu),ju(sessionGoneSentence(Au.name))}}),()=>{Lu=!0}},[Pu,lo,$u,Ou]),Pu?!Mu||Mu.token!==$u?{ready:!1}:{ready:!0,thread:Mu.thread,...Mu.said?{said:Mu.said}:{}}:{ready:!0}}function useWindowPort({serverUrl:Au,embedToken:lo,session:$u,host:Ru}){const Iu=reactExports.useRef(Ru);Iu.current=Ru;const Pu=$u.thread,Ou=reactExports.useRef(Pu?.messages.length?Pu.id:void 0),Mu=reactExports.useMemo(()=>({id:generateMessageId(),messages:[]}),[]),Du=Pu??(Au&&$u.ready?Mu:void 0),Lu=reactExports.useMemo(()=>Du&&{...Du,onStarted:Bu=>{Ou.current=Bu,Du.onStarted?.(Bu)}},[Du]);return reactExports.useEffect(()=>{const Bu=Ru?.onWindowPort;if(!(!Au||!Bu))return Bu(async ju=>{if(!Ou.current)throw new Error(WINDOW_NOT_YET);await postWindowMessage({serverUrl:Au,uid:Ou.current,...lo?{token:lo}:{},data:ju})}),()=>Bu(null)},[Au,lo,Ru]),Lu?{...$u,thread:Lu}:$u}function SessionSaid({said:Au}){return Au?jsxRuntimeExports.jsx(Text$3,{as:"p",role:"status",sx:{px:3,py:2,m:0,fontSize:1},children:Au}):null}const NO_HOST_PLUGINS=[];function useHostBridge(Au,lo){const $u=reactExports.useRef(lo);$u.current=lo;const Ru=Au.deployment.embedded?.host,Iu=JSON.stringify([Ru??null,Au.rules,Au.connections]),Pu=reactExports.useMemo(()=>hostPlugin(Au,()=>$u.current??{}),[Au.id,Iu]),Ou=Ru?.user==="signed",Mu=reactExports.useMemo(()=>{const Uu=hostUserRunProps(Au,()=>$u.current??{});return Uu?{name:`loop-host-user-${Au.id}`,displayName:`${Au.name}: who its user is`,description:`The token naming its user that the host's server signed, sent with every run of ${Au.name}.`,octicon:"person",emoji:"👤",contributes:[contribution(LoopRunProps,Uu,{id:"host-user"})]}:void 0},[Au.id,Ou]),Du=reactExports.useMemo(()=>Pu?[Pu,...Mu?[Mu]:[]]:NO_HOST_PLUGINS,[Pu,Mu]);reactExports.useEffect(()=>onLoopWindowMessage(Uu=>$u.current?.onEvent?.({type:"window-message",detail:{data:Uu}})),[]);const Lu=reactExports.useRef({answering:!1}),Bu=reactExports.useRef("idle"),ju=reactExports.useRef(""),Fu=reactExports.useCallback(Uu=>{Lu.current=Uu},[]),zu=reactExports.useCallback(Uu=>{const Hu=Bu.current;Bu.current=Uu;const Vu=Uu==="idle"||Uu==="waiting",Gu=Lu.current.saying;Vu&&Hu!=="idle"&&Hu!=="waiting"&&Lu.current.answering&&Gu&&Gu.id!==ju.current&&(ju.current=Gu.id,$u.current?.onEvent?.({type:"message",detail:{id:Gu.id,text:Gu.markdown||Gu.text}}))},[]);return{plugins:Du,onPresence:zu,onSaying:Fu}}const NO_PLUGINS=[];function embedAssistantCharacter(Au,lo=NO_PLUGINS){return assistantCharacterFor(assistantCharactersFrom([AssistantCharactersPlugin,...lo]),{app:Au.interface.assistant})}const signedOutSentence=Au=>`${Au.name} runs on Datalayer, which needs you signed in. An application embedded for visitors who are not needs its embed token (LOOP D-14), or an agent-runtimes server of the host's own (the "server" attribute).`;function Face({emoji:Au}){return jsxRuntimeExports.jsx(FluentEmoji,{emoji:Au,size:20,label:""})}function AppFloating({app:Au,view:lo,colorMode:$u,themeVariant:Ru,themeOverrides:Iu,character:Pu,serverUrl:Ou,instance:Mu,embedToken:Du,renderer:Lu,host:Bu,session:ju,language:Fu}){const zu=useChatWords(),[Uu,Hu]=reactExports.useState("idle"),[Vu,Gu]=reactExports.useState({answering:!1}),Wu=useHostBridge(Au,Bu),Ku=reactExports.useCallback(td=>{Hu(td),Wu.onPresence(td)},[Wu.onPresence]),Ju=reactExports.useCallback(td=>{Gu(td),Wu.onSaying(td)},[Wu.onSaying]),Yu=Au.interface.welcome||Au.description,Xu=useIAMStore(td=>td.token),ed=!Ou&&!Xu&&!Lu?.datalayerVisitors;return jsxRuntimeExports.jsx(ChatFloating,{defaultViewMode:lo,...Pu?{assistantCharacter:Pu}:{},...Au.interface.balloon?{balloonDisplay:Au.interface.balloon}:{},title:Au.name,description:Yu,brandIcon:jsxRuntimeExports.jsx(Face,{emoji:Au.emoji}),buttonIcon:jsxRuntimeExports.jsx(Face,{emoji:Au.emoji}),buttonTooltip:zu.talkTo(Au.name),colorMode:$u,useStore:!1,conversation:{body:ed?jsxRuntimeExports.jsx(Text$3,{as:"p",role:"status",sx:{p:3,m:0,fontSize:1},children:signedOutSentence(Au)}):ju&&!ju.ready?null:jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(SessionSaid,{said:ju?.said}),jsxRuntimeExports.jsx(AppRenderer,{app:Au,target:Ou?"local":"datalayer",...Ou?{serverUrl:Ou}:{},...Ou&&Du?{embedToken:Du}:{},instance:Mu,themeOverrides:Iu,colorMode:$u,...Ru?{themeVariant:Ru}:{},hideChatHeader:!0,autoFocusPrompt:!1,onPresence:Ku,onSaying:Ju,plugins:Wu.plugins,...ju?.thread?{thread:ju.thread}:{},...Fu?{language:Fu}:{},...Lu})]}),presence:Uu,saying:Vu.saying,answering:Vu.answering}})}function OwnPortalRoot(){const Au=reactExports.useRef(null);return reactExports.useLayoutEffect(()=>{Au.current&®isterPortalRoot(Au.current)},[]),jsxRuntimeExports.jsx("div",{ref:Au,className:"datalayer-app-portal"})}function useSystemMode(){const Au=typeof window<"u"&&typeof window.matchMedia=="function"?window.matchMedia("(prefers-color-scheme: dark)"):null,[lo,$u]=reactExports.useState(!!Au?.matches);return reactExports.useEffect(()=>{if(!Au)return;const Ru=()=>$u(Au.matches);return Au.addEventListener?.("change",Ru),()=>Au.removeEventListener?.("change",Ru)},[Au]),lo?"dark":"light"}function EmbedThemed({accent:Au,colorMode:lo,font:$u,variant:Ru,children:Iu,style:Pu}){const Ou=reactExports.useMemo(()=>embedThemeStyles({accent:Au,font:$u,variant:Ru}),[Au,$u,Ru]);return jsxRuntimeExports.jsx("div",{"data-color-mode":lo,style:{display:"contents"},children:jsxRuntimeExports.jsx(DatalayerThemeProvider,{colorMode:lo,theme:getThemeConfig(Ru).primerTheme,themeStyles:Ou,baseStyles:Pu,children:Iu})})}function AppEmbed({app:Au,mode:lo,accent:$u,colorMode:Ru,font:Iu,language:Pu,serverUrl:Ou,instance:Mu,embedToken:Du,visitors:Lu,speech:Bu,height:ju=640,ownPortal:Fu=!1,plugins:zu=NO_PLUGINS,host:Uu,resume:Hu=!0}){const Vu=lo??Au.deployment.embedded?.mode??"inline",Gu=useHostBridge(Au,Vu==="inline"?Uu:void 0),Wu=reactExports.useMemo(()=>Lu||Bu?{...Lu?{datalayerVisitors:Lu}:{},...Bu?{speech:Bu}:{}}:void 0,[Lu,Bu]),Ku=useEmbedSession({app:Au,serverUrl:Ou,embedToken:Du,resume:Hu}),Ju=useWindowPort({serverUrl:Ou,embedToken:Du,session:Ku,host:Uu}),Yu=useSystemMode(),Xu=Au.interface.theme?.variant??"loop",ed=Ru??Au.interface.theme?.mode??"auto",td=ed==="auto"?Yu:ed,nd=floatingViewOf(Vu),od=$u??Au.interface.accent,sd=reactExports.useMemo(()=>embedThemeOverrides({accent:od,font:Iu,variant:Xu}),[od,Iu,Xu]),ad=Au.interface.assistant,pd=reactExports.useMemo(()=>nd==="assistant"?embedAssistantCharacter(Au,zu):void 0,[nd,ad,zu]);if(pd&&"problem"in pd)return jsxRuntimeExports.jsx("p",{role:"status",className:"datalayer-app-said",children:pd.problem});const gd=pd?.character;return jsxRuntimeExports.jsx(ChatLanguage,{language:Pu,children:jsxRuntimeExports.jsxs(EmbedThemed,{accent:od,colorMode:td,font:Iu,variant:Xu,style:nd?{backgroundColor:"transparent"}:{height:ju,display:"flex",flexDirection:"column"},children:[Fu?jsxRuntimeExports.jsx(OwnPortalRoot,{}):null,nd?jsxRuntimeExports.jsx(AppFloating,{app:Au,view:nd,serverUrl:Ou,instance:Mu,embedToken:Du,colorMode:td,themeVariant:Xu,themeOverrides:sd,character:gd,host:Uu,session:Ju,...Wu?{renderer:Wu}:{},...Pu?{language:Pu}:{}}):Ju.ready?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(SessionSaid,{said:Ju.said}),jsxRuntimeExports.jsx(AppRenderer,{app:Au,target:Ou?"local":"datalayer",...Ou?{serverUrl:Ou}:{},...Ou&&Du?{embedToken:Du}:{},...Wu??{},instance:Mu,themeOverrides:sd,colorMode:td,themeVariant:Xu,plugins:Gu.plugins,onPresence:Gu.onPresence,onSaying:Gu.onSaying,...Ju.thread?{thread:Ju.thread}:{},...Pu?{language:Pu}:{}})]}):null]})})}const VISITORS_PATH="/api/runtime-visitors",VISITOR_EXAMPLES=["web-research","customer-interview"],AT_PREFIX="at:",DEFAULT_API="https://r1.datalayer.run",isAppUid=Au=>/^[0-9A-HJKMNP-TV-Z]{26}$/.test(Au),SLUG=/^[a-z0-9][a-z0-9-]{0,62}$/;function visitorsAt(Au,lo,$u){const Ru=Au.replace(/\/+$/,"");return{url:$u?$u.replace(/\/+$/,""):`${Ru}${VISITORS_PATH}`,app:lo,inferenceUrl:Ru}}const TOKEN_HINT='Embedded for a visitor it refuses, it takes its embed token (the "token" attribute).',notKeptSentence=Au=>`datalayer-app: "${Au}" is an example Datalayer does not keep ready for visitors (${VISITOR_EXAMPLES.join(", ")} are); embed it at its address once it is deployed. ${TOKEN_HINT}`,refusedSentence=Au=>`datalayer-app: ${Au.trim().replace(/\.?\s*Sign in to use it\.?$/,".")} ${TOKEN_HINT}`;async function readVisitorApp({api:Au=DEFAULT_API,app:lo,fetcher:$u=fetch,catalogue:Ru=getApp}){const Iu=lo.trim();if(isAppUid(Iu))return{kind:"decision",app:Iu};const Pu=Ru(Iu);if(Pu)return Pu.kind==="decision"?{kind:"decision",app:Iu}:VISITOR_EXAMPLES.includes(Pu.id)?{kind:"visitors",app:runnable({app:Pu,problems:[]}),visitors:visitorsAt(Au,Pu.id)}:{kind:"said",text:notKeptSentence(Iu)};if(!SLUG.test(Iu))return{kind:"said",text:`datalayer-app: "${Iu}" is neither an application's id, an example's, nor an address.`};let Ou;try{Ou=await $u(`${Au.replace(/\/+$/,"")}/api/ai-agents/v1/apps/deployments/at/${encodeURIComponent(Iu)}`)}catch(zu){return{kind:"said",text:`datalayer-app: Datalayer could not be reached to read "${Iu}" (${zu instanceof Error?zu.message:String(zu)}).`}}const Mu=await Ou.json().catch(()=>({}));if(!Ou.ok||Mu.success===!1){const zu=String(Mu.detail??Mu.message??`No application is at "${Iu}".`);return{kind:"said",text:refusedSentence(zu)}}const Du=Mu.session??{};if(!Du.opens)return{kind:"said",text:refusedSentence(String(Du.reason||`"${Iu}" is not run without an account.`))};const Lu=Mu.deployment??{},Bu=parseAppspec(Mu.spec);if(Bu.app.kind==="decision")return{kind:"decision",app:Iu};const ju=typeof Lu.app_name=="string"&&Lu.app_name?Lu.app_name:Bu.app.name,Fu=signedOutRuntime(Mu);return"said"in Fu?{kind:"said",text:refusedSentence(Fu.said)}:{kind:"visitors",app:runnable({app:{...Bu.app,name:ju},problems:Bu.problems}),visitors:visitorsAt(Au,`${AT_PREFIX}${Iu}`,Fu.url)}}function signedOutRuntime(Au){if(typeof Au.runs_code!="boolean")return{said:"Datalayer did not say whether it runs code of its own, so it is not run."};if(!Au.runs_code)return{};const lo=Au.kept??{},$u=typeof lo.url=="string"?lo.url.trim():"";return $u?{url:$u}:{said:"It runs its own code on a runtime kept for it, and none is running now."}}const EMBED_MESSAGES={size:"datalayer-app:size",decision:"datalayer-app:decision",token:"datalayer-app:token",tokenExpired:"datalayer-app:token-expired"};function appspecOfText(Au){const lo=Au.replace(/\t/g," ").split(`
|
|
4062
4065
|
`),$u=Math.min(...lo.filter(Pu=>Pu.trim()).map(Pu=>Pu.length-Pu.trimStart().length)),Ru=lo.map(Pu=>Pu.slice(Number.isFinite($u)?$u:0)).join(`
|
|
4063
|
-
`).trim();if(!Ru)throw new EmbedAttributeError("datalayer-app: the Appspec is empty.");let Iu;if(Ru.startsWith("{")){let Pu;try{Pu=JSON.parse(Ru)}catch(Ou){throw new EmbedAttributeError(`datalayer-app: the Appspec is not JSON (${Ou.message}).`)}Iu=parseAppspec(Pu)}else Iu=readAppspecYaml(Ru);return runnable(Iu)}function frameSrcOf(Au,lo,$u=""){return`${Au.replace(/\/+$/,"")}/public/apps/${encodeURIComponent(lo)}/run?embed=1${$u?`#token=${encodeURIComponent($u)}`:""}`}function frameInLanguage(Au,lo){if(!lo)return Au;const $u=Au.indexOf("#"),[Ru,Iu]=$u<0?[Au,""]:[Au.slice(0,$u),Au.slice($u)];return`${Ru}${Ru.includes("?")?"&":"?"}language=${encodeURIComponent(lo)}${Iu}`}async function readEmbeddedApp({api:Au,origin:lo,app:$u,token:Ru,fetcher:Iu=fetch}){const Pu=await Iu(`${Au.replace(/\/+$/,"")}/api/spacer/v1/apps/${encodeURIComponent($u)}/embedded`,{headers:{Authorization:`Bearer ${Ru}`}});if(Pu.status===401)return{kind:"said",text:"datalayer-app: the embed token expired or is not for this application.",expired:!0};if(!Pu.ok)return{kind:"said",text:`datalayer-app: the application could not be read (${Pu.status}).`};const Ou=await Pu.json();let Mu;try{Mu=JSON.parse(String(Ou.app?.model_s??"{}"))}catch{Mu={}}if(!Mu.spec)return{kind:"frame",src:frameSrcOf(lo,$u,Ru)};const Du=runnable(parseAppspec(Mu.spec));return Du.kind==="decision"?{kind:"frame",src:frameSrcOf(lo,$u,Ru)}:embedTokenDeployment(Ru)?{kind:"spec",app:Du}:{kind:"said",text:EMBED_TOKEN_NAMES_NO_DEPLOYMENT}}function currentScriptUrl(){try{const Au=document.currentScript;return Au?.src?new URL(Au.src,location.href).href:""}catch{return""}}function defineDatalayerAppElement(Au={}){if(typeof window>"u"||!("customElements"in window))return;const lo=Au.tag??EMBED_TAG,$u=customElements.get(lo);if($u)return $u;const Ru=Au.scriptUrl??currentScriptUrl(),Iu=Ru?new URL(Ru).origin:"",Pu=Ru?Ru.replace(/\.js(\?.*)?$/,".css"):"";class Ou extends HTMLElement{static get observedAttributes(){return EMBED_OBSERVED_ATTRIBUTES}root=null;frame=null;source=null;loading=0;passed={};offered={};windowPort=null;host={context:()=>this.passed,userToken:()=>this.getAttribute("user-token")||void 0,functions:this.offered,onWindowPort:Du=>{this.windowPort=Du},onEvent:Du=>this.dispatchEvent(new CustomEvent(Du.type,{detail:Du.detail,bubbles:!0,composed:!0}))};get context(){return this.passed}set context(Du){this.passed={...Du??{}}}postWindowMessage(Du){const Lu=this.windowPort;return Lu?Lu(Du):Promise.reject(new Error(`datalayer-app: ${WINDOW_NOT_YET}`))}get functions(){return this.offered}set functions(Du){for(const Lu of Object.keys(this.offered))delete this.offered[Lu];Object.assign(this.offered,Du??{})}constructor(){super(),this.attachShadow({mode:"open"}),this.onMessage=this.onMessage.bind(this),adoptPropertiesSetEarly(this)}get token(){return this.getAttribute("token")??""}set token(Du){Du?this.setAttribute("token",String(Du)):this.removeAttribute("token")}get userToken(){return this.getAttribute("user-token")??""}set userToken(Du){Du?this.setAttribute("user-token",String(Du)):this.removeAttribute("user-token")}connectedCallback(){window.addEventListener("message",this.onMessage),this.load()}disconnectedCallback(){window.removeEventListener("message",this.onMessage),this.unmount()}attributeChangedCallback(Du,Lu,Bu){if(!(!this.isConnected||Lu===Bu)&&Du!=="user-token"){if(Du==="token"&&this.frame?.contentWindow&&Bu){this.frame.contentWindow.postMessage({type:EMBED_MESSAGES.token,token:Bu},this.origin());return}if(["mode","accent","theme","font","height","resume","language"].includes(Du)){this.draw();return}this.load()}}origin(){return(this.getAttribute("origin")||Iu||location.origin).replace(/\/+$/,"")}inputs(){const Du={};for(const ju of EMBED_OBSERVED_ATTRIBUTES)Du[ju]=this.getAttribute(ju);const Lu=getComputedStyle(this),Bu={};for(const[ju,Fu]of Object.entries(EMBED_HOST_VARIABLES)){const zu=Lu.getPropertyValue(Fu).trim();zu&&(Bu[ju]=zu.replace(/^["']|["']$/g,""))}return{attributes:Du,variables:Bu}}async read(){const Du=this.querySelector('script[type="application/yaml"], script[type="application/json"], script[type="text/yaml"]');if(Du?.textContent?.trim())return{kind:"spec",app:appspecOfText(Du.textContent)};const Lu=this.getAttribute("spec");if(Lu){const Fu=await fetch(new URL(Lu,location.href).href);return Fu.ok?{kind:"spec",app:appspecOfText(await Fu.text())}:{kind:"said",text:`datalayer-app: the Appspec at ${Lu} could not be read (${Fu.status}).`}}const Bu=this.getAttribute("app");if(!Bu)return{kind:"said",text:'datalayer-app: the "app" attribute names the application to show, or "spec" the address of its Appspec.'};const ju=this.token;if(!ju){const Fu=await readVisitorApp({api:this.agents(),app:Bu});return Fu.kind==="decision"?{kind:"frame",src:frameSrcOf(this.origin(),Fu.app)}:Fu.kind==="said"?{kind:"said",text:Fu.text}:{kind:"spec",app:Fu.app,visitors:Fu.visitors}}return readEmbeddedApp({api:this.api(),origin:this.origin(),app:Bu,token:ju})}spoken=null;get speech(){const Du=coreStore.getState().configuration?.aiAgentsUrl??"";return this.spoken?.speechUrl!==Du&&(this.spoken={speechUrl:Du}),this.spoken}agents(){return(this.getAttribute("api")||coreStore.getState().configuration?.aiAgentsUrl||DEFAULT_API).replace(/\/+$/,"")}api(){return(this.getAttribute("api")||coreStore.getState().configuration?.spacerUrl||"https://prod1.datalayer.run").replace(/\/+$/,"")}async load(){const Du=++this.loading;let Lu;try{Lu=await this.read()}catch(Bu){Lu={kind:"said",text:Bu instanceof Error?Bu.message:`datalayer-app: ${String(Bu)}`}}Du!==this.loading||!this.isConnected||(this.source=Lu,this.draw(),Lu.kind==="said"&&Lu.expired&&this.dispatchEvent(new CustomEvent("token-expired",{detail:{app:this.getAttribute("app")??""},bubbles:!0,composed:!0})))}unmount(){this.root?.unmount(),this.root=null,this.frame=null}skeleton(Du){const Lu=this.shadowRoot;if(this.unmount(),Lu.replaceChildren(),Pu){const ju=document.createElement("link");ju.rel="stylesheet",ju.href=Pu,Lu.appendChild(ju)}const Bu=document.createElement("style");return Bu.textContent=embedShadowCss(Du),Lu.appendChild(Bu),Lu}say(Du){this.setAttribute("data-embed-mode","inline");const Lu=this.skeleton(),Bu=document.createElement("p");Bu.className="datalayer-app-said",Bu.setAttribute("role","status"),Bu.textContent=Du,Lu.appendChild(Bu)}draw(){const Du=this.source;if(!Du)return;if(Du.kind==="said"){this.say(Du.text);return}if(Du.kind==="frame"){let Hu;try{Hu=languageOf(this.getAttribute("language"))}catch(Wu){this.say(Wu.message);return}this.setAttribute("data-embed-mode","inline");const Vu=this.skeleton(),Gu=document.createElement("iframe");Gu.className="datalayer-app-frame",Gu.src=frameInLanguage(Du.src,Hu),Gu.title="Datalayer app",Gu.style.height=`${inlineHeightOf(this.getAttribute("height"))}px`,Gu.setAttribute("allow","clipboard-write"),Vu.appendChild(Gu),this.frame=Gu;return}let Lu,Bu,ju;try{Lu=embedLookOf(this.inputs(),Du.app),Bu=resumeOf(this.getAttribute("resume")),ju=languageOf(this.getAttribute("language"))}catch(Hu){this.say(Hu.message);return}if(Lu.mode==="assistant"){const Hu=embedAssistantCharacter(Du.app);if("problem"in Hu){this.say(Hu.problem);return}}this.setAttribute("data-embed-mode",Lu.mode);const Fu=this.skeleton(getThemeConfig(Lu.variant).themeStyles.css),zu=document.createElement("div");zu.className="datalayer-app-root",Fu.appendChild(zu),this.root=clientExports.createRoot(zu);const Uu=this.getAttribute("server")||void 0;this.root.render(jsxRuntimeExports.jsx(me$3,{target:Fu,children:jsxRuntimeExports.jsx(AppEmbed,{app:Du.app,mode:Lu.mode,accent:Lu.accent,colorMode:Lu.colorMode,font:Lu.font,serverUrl:Uu,...Uu&&this.token?{embedToken:this.token}:{},...Du.visitors?{visitors:Du.visitors}:{},speech:this.speech,height:inlineHeightOf(this.getAttribute("height")),ownPortal:!0,host:this.host,resume:Bu,...ju?{language:ju}:{}})}))}onMessage(Du){if(!this.frame||Du.source!==this.frame.contentWindow||Du.origin!==this.origin())return;const Lu=Du.data??{};Lu.type===EMBED_MESSAGES.size&&typeof Lu.height=="number"&&Lu.height>0?this.frame.style.height=`${Math.ceil(Lu.height)}px`:Lu.type===EMBED_MESSAGES.decision?this.dispatchEvent(new CustomEvent("decision",{detail:Lu.record,bubbles:!0,composed:!0})):Lu.type===EMBED_MESSAGES.tokenExpired&&this.dispatchEvent(new CustomEvent("token-expired",{detail:{app:this.getAttribute("app")??""},bubbles:!0,composed:!0}))}}return customElements.define(lo,Ou),Ou}const SCRIPT_FILE="datalayer-app.js";defineDatalayerAppElement({scriptUrl:new URL(SCRIPT_FILE,import.meta.url).href});const mermaidVLURNSYL=Object.freeze(Object.defineProperty({__proto__:null,Mermaid:Ee$2},Symbol.toStringTag,{value:"Module"}));export{styleTags as $,A2uiSurfaceComposed as A,Box as B,CheckIcon as C,Dialog$1 as D,useContributions as E,LoopPromptPanel as F,InputPrompt as G,Heading$2 as H,IconButton as I,Signal as J,o$1 as K,Label as L,MessageProcessor as M,NO_SANDBOX_YET as N,LoopOpeningNotebook as O,PlayIcon as P,QueryClient as Q,LoopNotebookToolbarItem as R,SANDBOX_KIND_LABELS as S,Text$3 as T,LoopNotebookToolbar as U,LRLanguage as V,LanguageSupport as W,indentNodeProp as X,continuedIndent as Y,foldNodeProp as Z,__vitePreload as _,QueryClientProvider as a,AGENTS_PLUGIN_NAME as a$,tags as a0,ExternalTokenizer as a1,ifNotIn as a2,completeFromList as a3,LRParser as a4,syntaxTree as a5,delimitedIndent as a6,foldInside as a7,getDefaultExportFromCjs as a8,MimeModel as a9,DatalayerThemeProvider as aA,de$1 as aB,on$1 as aC,nl as aD,es as aE,H as aF,disposeServiceManager as aG,create$g as aH,setIfUndefined as aI,create$6 as aJ,fromBase64 as aK,onChange as aL,varStorage as aM,toBase64 as aN,offChange as aO,createUint8ArrayFromArrayBuffer as aP,map$3 as aQ,ContextTracker as aR,NodeWeakMap as aS,IterMode as aT,snippetCompletion as aU,Panel as aV,PromiseDelegate as aW,DEFAULT_SERVICE_URLS as aX,requestDatalayerAPI as aY,API_BASE_PATHS as aZ,useReactorPlatform as a_,standardRendererFactories as aa,purify$1 as ab,Token$2 as ac,Menu as ad,DisposableDelegate as ae,ArrayExt as af,Widget as ag,PanelLayout as ah,ITranslator as ai,createToolbarFactory as aj,nullTranslator as ak,ObservableList as al,Toolbar$1 as am,ReactWidget as an,some$1 as ao,useAgentsRuntimes as ap,xu as aq,useThemeStore as ar,useSystemColorMode as as,getThemeConfig as at,JupyterReactTheme$1 as au,l$1 as av,v$1 as aw,a$1 as ax,Kernel as ay,registerSandboxServiceManager as az,sandboxExecuteOverHttp as b,VDomModel as b$,DEFAULT_DATALAYER_AGENTSPEC as b0,useOptionalSandboxService as b1,IDLE_SANDBOX_TARGET_SIGNAL as b2,ensureVisitorAgent as b3,AGENTSPECS$1 as b4,useAgentRuntimes as b5,ActionList as b6,distExports as b7,ActionListContainerContext as b8,BoxWithFallback as b9,defineLanguageFacet as bA,Parser$2 as bB,NodeType as bC,NodeProp as bD,Tag as bE,NodeSet as bF,Tree as bG,countColumn as bH,Prec as bI,keymap as bJ,Language as bK,indentUnit as bL,foldService as bM,CompletionContext as bN,EditorState as bO,languageDataProp as bP,LanguageDescription as bQ,ParseContext as bR,Eu as bS,Ke$2 as bT,_c as bU,is as bV,Ys as bW,PencilIcon as bX,SingletonLayout as bY,FocusTracker as bZ,libExports$5 as b_,merge$5 as ba,defaultSxProp as bb,useId as bc,reactDomExports as bd,useIsomorphicLayoutEffect$2 as be,ChevronDownIcon as bf,classes$t as bg,SubItem as bh,Box$1 as bi,themeConfigs as bj,LoopDocumentToolbarItem as bk,LoopDocumentToolbar as bl,LoopOpeningDocument as bm,IDLE_SANDBOX_SNAPSHOT_SIGNAL as bn,definePlugin as bo,DOCUMENT_TOOLBAR_PLUGIN_NAME as bp,contribution as bq,KernelIndicator as br,NOTEBOOK_TOOLBAR_PLUGIN_NAME as bs,LocalTokenGroup as bt,flatIndent as bu,parseMixed as bv,bracketMatchingHandle as bw,EditorView as bx,EditorSelection as by,sublanguageProp as bz,ButtonComponent as c,ITableOfContentsRegistry as c$,TableOfContents as c0,JSONExt as c1,VDomRenderer as c2,LabIcon as c3,classes as c4,map$5 as c5,showErrorMessage as c6,AttachedProperty as c7,addIcon as c8,launcherIcon as c9,linkIcon as cA,Clipboard as cB,downloadIcon as cC,copyIcon as cD,setToolbar as cE,Notification as cF,CommandRegistry as cG,closeIcon as cH,cutIcon as cI,pasteIcon as cJ,newFolderIcon as cK,textEditorIcon as cL,markdownIcon as cM,refreshIcon as cN,editIcon as cO,fileIcon as cP,stopIcon as cQ,filterIcon as cR,DisposableSet as cS,clearNumbering as cT,getHeadingId as cU,addPrefix as cV,parseHeadings as cW,filterHeadings as cX,StackedLayout as cY,ABCWidgetFactory as cZ,DocumentWidget as c_,MainAreaWidget as ca,find$3 as cb,TranslatorConnector as cc,Gettext as cd,DEFAULT_LANGUAGE_CODE as ce,normalizeDomain as cf,ITranslatorConnector as cg,Dialog as ch,showDialog$1 as ci,SearchDocumentModel as cj,SearchDocumentView as ck,isResponsiveValue as cl,clsx as cm,commonjsRequire as cn,TextInput$1 as co,SearchIcon as cp,SyncIcon as cq,ToggleSwitch as cr,Flash as cs,ChevronRightIcon as ct,StyledSpinner as cu,ToolbarButton as cv,fileUploadIcon as cw,libExports$2 as cx,WidgetTracker as cy,folderIcon as cz,displayUrl as d,OutputPrompt as d$,markdownRendererFactory as d0,SkeletonBox as d1,getBrightPalette as d2,useColorPalette as d3,SkeletonText as d4,Tooltip as d5,ActionMenu as d6,buildIcon as d7,jupyterIcon as d8,SettingRegistry as d9,EditorExtensionRegistry as dA,ybinding as dB,IPositionModel as dC,historyIcon as dD,CommandToolbarButton as dE,caretLeftIcon as dF,caretRightIcon as dG,checkIcon as dH,COMPLETER_ACTIVE_CLASS as dI,Debouncer as dJ,SessionContextDialogs as dK,saveIcon as dL,addCommandToolbarButtonClass as dM,UseSignal as dN,CommandToolbarButtonComponent as dO,createStore$1 as dP,useStore$1 as dQ,runtimesStore as dR,DATALAYER_IAM_TOKEN_KEY as dS,DATALAYER_IAM_USER_KEY as dT,coreStore as dU,iamStore as dV,layoutStore as dW,useCoreStore as dX,useIAMStore as dY,useLayoutStore as dZ,useRuntimesStore as d_,moveUpIcon as da,moveDownIcon as db,Button$1 as dc,deleteIcon as dd,DOMUtils as de,lineFormIcon as df,deleteLine as dg,toggleBlockComment as dh,toggleComment as di,toggleTabFocusMode as dj,selectNextOccurrence as dk,foldable as dl,foldCode as dm,unfoldCode as dn,foldState as dp,foldEffect as dq,unfoldEffect as dr,foldAll as ds,unfoldAll as dt,IEditorServices as du,EditorLanguageRegistry as dv,parseMathIPython as dw,StreamLanguage as dx,pythonBuiltin as dy,EditorThemeRegistry as dz,Link$1 as e,AgentTools as e$,Stdin as e0,CodeCell as e1,useJupyterLabCssLoaded as e2,TelescopeIcon as e3,XIcon as e4,CounterLabel as e5,PauseIcon as e6,DownloadIcon as e7,SPAN_SOURCE_LABELS as e8,sourceOfSpan as e9,useAgentRuntimeMcpStatus as eA,useAgentRuntimeCodemodeStatus as eB,useAgentRuntimeContextSnapshot as eC,useAgentRuntimeFullContext as eD,useAgentRuntimeWsState as eE,useMutation as eF,useQuery as eG,ForwardRef$2 as eH,NoteIcon as eI,ServerIcon as eJ,CheckCircleIcon as eK,XCircleIcon as eL,BriefcaseIcon as eM,MenuBar as eN,runIcon as eO,fastForwardIcon as eP,require_MapCache as eQ,require_Symbol as eR,require_Uint8Array as eS,requireEq as eT,require_getAllKeys as eU,require_Stack as eV,require_getTag as eW,requireIsArray as eX,requireIsBuffer as eY,requireIsTypedArray as eZ,requireIsObjectLike as e_,AGENT_SPAN_ATTRIBUTES as ea,describeAgentSpan as eb,SpecMark as ec,parse$4 as ed,UUID as ee,EN_US as ef,errorIcon as eg,Platform as eh,caretDownEmptyThinIcon as ei,StringExt as ej,SegmentedControl as ek,ListUnorderedIcon as el,GraphIcon as em,ClockIcon as en,DatabaseIcon as eo,FileIcon as ep,ToolsIcon as eq,CommentDiscussionIcon as er,AiModelIcon as es,InfoIcon as et,KeyIcon as eu,devtools as ev,subscribeWithSelector as ew,persist as ex,CheckCircleFillIcon as ey,AlertIcon as ez,CopyIcon as f,THREAD_WORDS as f$,useToast as f0,isInsideJupyterLab as f1,FormControl$1 as f2,MailIcon as f3,Textarea as f4,$e$5 as f5,useAnonymousInferenceSession as f6,browserModelRequiresSignIn as f7,getAgentspecs as f8,useOptionalReactorPlatform as f9,onSurfaceRequest as fA,setEditorOptions as fB,seedEditorChoice as fC,canOpenView as fD,useWorkspaceFullScreen as fE,targetRunsAgentInPage as fF,useOptionalTeamSelection as fG,LoopAgentBlueprint as fH,resolveAgentspec as fI,LoopChatSuggestion as fJ,agentIcon as fK,LoopFrontendTool as fL,BROWSER_CODE_TOOL as fM,agentServerOf as fN,LoopCommand as fO,subagentsFor as fP,useChatAvailability as fQ,noRuntimeSaid as fR,useVoiceSettings as fS,settledVoice as fT,useSlotComponents as fU,LoopSlots as fV,onPromptFocusRequest as fW,useVisitorToken as fX,voiceAskedAs as fY,generateMessageId as fZ,openThread as f_,PRESENCE_LINES as fa,FluentEmoji as fb,useChatWords as fc,CHAT_PLUGIN_NAME as fd,INPUT_PROMPT_PLUGIN_NAME as fe,LoopChatSurface as ff,LoopChatComposer as fg,LoopChatHeader as fh,LoopChatLayout as fi,LoopChatTurn as fj,turnWritersOf as fk,LoopChatExtras as fl,computed$1 as fm,useGate as fn,presenceState as fo,presenceToolOf as fp,newestIsAnswer as fq,latestSaying as fr,messageText as fs,LoopRunProps as ft,runForwardedProps as fu,dataUrlBase64 as fv,sandboxFileName as fw,writeFilesCode as fx,givenFilesSentence as fy,sendInstead as fz,createAllAgentRuntimesTools as g,CommandPalette$1 as g$,agentInstructions as g0,useConfig as g1,useSkills as g2,useSkillActions as g3,runtimeModelsUrl as g4,readServerCatalogue as g5,readServerDecisions as g6,offeredModels as g7,AI_MODEL_CATALOGUE as g8,isChatModel as g9,requireMessages as gA,mockSocketExports as gB,ObservableMap as gC,CodeEditorWrapper as gD,CodeEditor as gE,IEditorMimeTypeService as gF,EditorSearchProvider as gG,CodeMirrorEditor as gH,getPrefix as gI,isMarkdown as gJ,findNext as gK,gotoLine as gL,consoleIcon as gM,undoIcon as gN,redoIcon as gO,selectAll as gP,Sanitizer as gQ,COMPLETER_ENABLED_CLASS as gR,MessageLoop as gS,COMPLETER_LINE_BEGINNING_CLASS as gT,Message as gU,ElementExt as gV,renderText as gW,Printing as gX,clientExports as gY,RenderedJavaScript as gZ,filterListIcon as g_,ReactorSlot as ga,ComposerVoice as gb,ReactorLazy as gc,ChatBase as gd,ScreenNormalIcon as ge,ScreenFullIcon as gf,SUGGESTION_CHIP_WIDTH as gg,Truncate as gh,useAnonymousSessionStore as gi,inPageAgentRefusal as gj,signal$2 as gk,LoopAgentGate as gl,agentRuntimeStore as gm,loopShapeVars as gn,NONE_EDITOR as go,getAnchoredPosition as gp,reactIsExports as gq,useTheme as gr,useOnEscapePress as gs,useOnOutsideClick as gt,useResizeObserver as gu,VisuallyHidden as gv,TriangleDownIcon as gw,qe$4 as gx,sx as gy,requireSerialize as gz,renderOcticon as h,strokeWidth$1 as h$,h$7 as h0,LabIconStyle as h1,copyrightIcon as h2,ToolbarButtonComponent as h3,bellIcon as h4,Button$3 as h5,paletteIcon as h6,Throttler as h7,Selector$1 as h8,jupyterFaviconIcon as h9,startSlotTemplate as hA,endSlotTemplate as hB,slotted as hC,elements as hD,FoundationElement as hE,isHTMLElement as hF,__decorate$1 as hG,attr as hH,observable as hI,applyMixins as hJ,StartEnd as hK,keyEnter as hL,keyArrowUp as hM,keyArrowDown as hN,keyArrowRight as hO,keyArrowLeft as hP,keyEnd as hQ,keyHome as hR,DOM as hS,getDisplayedNodes as hT,direction$1 as hU,neutralForegroundRest$1 as hV,neutralFillStealthRest$1 as hW,bodyFont$1 as hX,focusVisible as hY,accentFillFocus$1 as hZ,focusStrokeWidth$1 as h_,caretDownEmptyIcon as ha,addToolbarButtonClass as hb,NotebookActions as hc,offlineBoltIcon as hd,circleIcon as he,ObservableJSON as hf,ConflatableMessage as hg,jumpBackIcon as hh,jumpForwardIcon as hi,MarkdownCell as hj,Cell as hk,trustedIcon as hl,notTrustedIcon as hm,runCell as hn,InputPrompt$1 as ho,NotebookPanel as hp,setCellExecutor as hq,StaticNotebook as hr,notebookIcon as hs,NotebookSearchProvider as ht,duplicateIcon as hu,addAboveIcon as hv,addBelowIcon as hw,children$1 as hx,ref$1 as hy,html$6 as hz,SquareFillIcon as i,createCellModelFromSharedType as i$,controlCornerRadius$1 as i0,heightNumber$1 as i1,neutralFillStealthHover$1 as i2,neutralFillStealthActive$1 as i3,designUnit$1 as i4,typeRampBaseFontSize$1 as i5,typeRampBaseLineHeight$1 as i6,density$1 as i7,typeRampPlus1FontSize$1 as i8,disabledOpacity$1 as i9,circleEmptyIcon as iA,searchIcon as iB,SplitPanel as iC,TabBar as iD,jsonIcon as iE,spreadsheetIcon as iF,terminalIcon as iG,kernelIcon as iH,NotificationManager as iI,SessionContext as iJ,Spinner as iK,Styling as iL,SystemClipboard as iM,VisuallyHidden$1 as iN,StopIcon as iO,ViewPlugin as iP,createRelativePositionFromTypeIndex as iQ,createRelativePositionFromJSON as iR,tooltips as iS,Facet as iT,Annotation as iU,layer as iV,StateField as iW,showTooltip as iX,createAbsolutePositionFromRelativePosition as iY,RectangleMarker as iZ,YDocument as i_,disabledCursor as ia,baseHeightMultiplier$1 as ib,neutralFillRest$1 as ic,neutralFillHover$1 as id,neutralFillActive$1 as ie,accentForegroundRest$1 as ig,display as ih,css as ii,forcedColorsStylesheetBehavior as ij,SystemColors as ik,cssPartial as il,DesignToken as im,neutralFillStealthRecipe$1 as io,neutralFillRecipe$1 as ip,useEventListener as iq,useProperties as ir,provideJupyterDesignSystem$1 as is,ITableOfContentsTracker as it,tocIcon as iu,numberingIcon as iv,expandAllIcon as iw,collapseAllIcon as ix,ellipsesIcon as iy,caretDownIcon as iz,jsxRuntimeExports as j,activateHover as j$,createCell as j0,YMap as j1,RawCellModel as j2,MarkdownCellModel as j3,CodeCellModel as j4,MINOR_VERSION as j5,MAJOR_VERSION as j6,StateEffect as j7,Decoration as j8,WidgetType as j9,CheckboxOrRadioGroup$1 as jA,CheckboxGroupContext as jB,Checkbox as jC,RadioGroup$1 as jD,Radio as jE,SelectPanel as jF,Select$1 as jG,TextInputWithTokens as jH,object as jI,preprocess$1 as jJ,record$2 as jK,string$2 as jL,unknown$1 as jM,zodToToolParameters as jN,array as jO,_enum as jP,number$2 as jQ,boolean$1 as jR,validateWithZod as jS,useJupyterReactStoreFromProps as jT,OutputArea as jU,createStandaloneCell as jV,BoxPanel as jW,cellsStore as jX,RawCell as jY,useCellsStore as jZ,getPanel as j_,DEFAULT_VARIANT as ja,MarimoReactive as jb,NotebookCommandIds as jc,OutputAreaModel as jd,useJupyterReactStore as je,newUuid as jf,NotebookPanelProvider as jg,addNotebookCommands as jh,YArray as ji,YText as jj,newUlid as jk,k$2 as jl,loopColors as jm,sunColors as jn,ivoryColors as jo,sandColors as jp,earthColors as jq,matrixColors as jr,lovelyColors as js,spatialColors as jt,datalayerColors as ju,getColorPalette as jv,CheckboxOrRadioGroupValidation as jw,CheckboxOrRadioGroupLabel as jx,CheckboxOrRadioGroupCaption as jy,useRenderForcingRef as jz,TrashIcon as k,y$3 as k$,showPanel as k0,combineConfig as k1,RangeSetBuilder as k2,crelt as k3,hoverTooltip as k4,lineNumbers as k5,highlightActiveLineGutter as k6,highlightSpecialChars as k7,history as k8,foldGutter as k9,ccount as kA,zwitch as kB,html$4 as kC,htmlVoidElements as kD,C$1 as kE,Dt$4 as kF,u$2 as kG,dt$2 as kH,Go as kI,ns as kJ,mn$1 as kK,qi as kL,Pi as kM,isStream as kN,isExecuteResult as kO,isDisplayData as kP,isError$1 as kQ,Xo as kR,Ki as kS,Yi as kT,er as kU,T as kV,v$2 as kW,S$1 as kX,C as kY,m$2 as kZ,x$5 as k_,drawSelection as ka,dropCursor as kb,indentOnInput as kc,syntaxHighlighting as kd,bracketMatching as ke,closeBrackets as kf,autocompletion as kg,rectangularSelection as kh,crosshairCursor as ki,highlightActiveLine as kj,highlightSelectionMatches as kk,closeBracketsKeymap as kl,defaultKeymap as km,searchKeymap as kn,historyKeymap as ko,foldKeymap as kp,completionKeymap as kq,defaultHighlightStyle as kr,ArrowRightIcon as ks,useOutputsStore as kt,Compartment as ku,whitespace as kv,svg$2 as kw,find as kx,stringify$1 as ky,stringify as kz,libExports$3 as l,TextModelFactory as l$,p$4 as l0,ol as l1,He$2 as l2,pn$2 as l3,Kr as l4,ur as l5,ls as l6,cn$1 as l7,_n as l8,hn$2 as l9,useResponsiveValue as lA,ScrollableRegion as lB,viewportRanges as lC,JupyterLiteServer as lD,Router as lE,ContextMenu as lF,TabPanel as lG,DockPanel as lH,hpass as lI,AccordionPanel as lJ,AccordionLayout as lK,FormAssociated as lL,nullableNumberConverter as lM,ARIAGlobalStatesAndProperties as lN,neutralFillInputRest$1 as lO,neutralFillStrongRest$1 as lP,errorFillRest$1 as lQ,neutralFillInputHover$1 as lR,neutralFillStrongHover$1 as lS,errorFillHover$1 as lT,neutralFillStrongActive$1 as lU,errorFillActive$1 as lV,errorFillFocus$1 as lW,neutralStrokeRest$1 as lX,__decorate as lY,BoxLayout as lZ,VirtualDOM as l_,qc as la,Ie$2 as lb,cs as lc,dr as ld,Jl as le,fn$2 as lf,hn$1 as lg,pn$1 as lh,Wo as li,xt$2 as lj,Zs as lk,gc as ll,On as lm,na as ln,ea as lo,ia as lp,sa as lq,decodeNamedCharacterReference as lr,requireReact as ls,StyleModule as lt,jupyterHighlightStyle as lu,useFocusZone as lv,FocusKeys as lw,useSafeTimeout as lx,useSlots as ly,useProvidedRefOrCreate as lz,PlusIcon as m,KERNEL_STATE_LABELS as m$,pdfIcon as m0,pythonIcon as m1,juliaIcon as m2,rKernelIcon as m3,yamlIcon as m4,imageIcon as m5,audioIcon as m6,videoIcon as m7,writeVarUint as m8,encodeStateVector as m9,filter$3 as mA,caretUpIcon as mB,Poll as mC,each as mD,Application as mE,StackedPanel as mF,tabIcon as mG,Base64ModelFactory as mH,useTerminalStore as mI,requestAPI$1 as mJ,loadJupyterConfig as mK,createLiteServiceManager as mL,jupyterReactStore as mM,ANSWER_MARKER as mN,BuilderManagerLess as mO,ContentsManagerLess as mP,DEFAULT_API_KERNEL_PREFIX_URL as mQ,DEFAULT_JUPYTER_SERVER_TOKEN as mR,DEFAULT_JUPYTER_SERVER_URL as mS,DEFAULT_KERNEL_NAME as mT,DefaultExecutor as mU,EventsManagerLess as mV,ExecutionPhase as mW,HELPER_NAME as mX,JupyterLabCss as mY,KERNEL_HELPER_SOURCE as mZ,KERNEL_STATES as m_,writeVarUint8Array as ma,encodeStateAsUpdate as mb,readVarUint as mc,applyUpdate as md,readVarUint8Array as me,readVarString as mf,ObservableV2 as mg,Awareness as mh,toUint8Array$1 as mi,length as mj,encodeAwarenessUpdate as mk,removeAwarenessStates as ml,isNode as mm,getUnixTime as mn,createEncoder as mo,min as mp,pow as mq,createDecoder as mr,applyAwarenessUpdate as ms,UndoManager as mt,Doc$1 as mu,isCodeCellModel as mv,Drag as mw,MimeData as mx,useConsoleStore as my,folderFavoriteIcon as mz,CodeIcon as n,Fi as n$,KERNEL_STATE_VISUALS as n0,KernelExecutor as n1,KernelManagerLess as n2,KernelspecManagerLess as n3,NbConvertManagerLess as n4,OperationRunner as n5,ServiceManagerLess as n6,SessionManagerLess as n7,SettingManagerLess as n8,TerminalManagerLess as n9,loadJupyterLabCss as nA,notebookToolDefinitions as nB,notebookToolOperations as nC,notebookTools as nD,outputsAsString as nE,outputsStore as nF,readAllCellsOperation as nG,readAllCellsTool as nH,readCellOperation as nI,readCellTool as nJ,refreshJupyterLabPortalTheme as nK,renderKernelStateGlyph as nL,resetJupyterConfig as nM,runCellOperation as nN,runCellTool as nO,setJupyterServerToken as nP,setJupyterServerUrl as nQ,sleep as nR,syncJupyterLabPortalTheme as nS,terminalStore as nT,toKernelState as nU,updateCellOperation as nV,updateCellTool as nW,useJupyterReactColormode as nX,useKernelsStore as nY,ThemeProvider as nZ,Overlay$1 as n_,UserManagerLess as na,WorkspaceManagerLess as nb,cellSourceAsString as nc,consoleStore as nd,createLiteServer as ne,createServerSettings as nf,deleteCellsOperation as ng,deleteCellsTool as nh,disableKernelReconnect as ni,disposeKernelConnections as nj,ensureJupyterAuth as nk,ensureJupyterConfig as nl,executeCodeOperation as nm,executeCodeTool as nn,formatResponse as no,getCookie as np,getJupyterServerToken as nq,getJupyterServerUrl as nr,getKernelIndicatorMeta as ns,insertCellOperation as nt,insertCellTool as nu,isAnyCellRunning as nv,isReactiveVariant as nw,isServedByJupyterLab as nx,jupyterLabTheme as ny,kernelsStore as nz,notebookStore as o,kn$1 as o$,Zl as o0,bu as o1,Nu as o2,Wl as o3,Fr as o4,Li as o5,Vc as o6,Fo as o7,sn$1 as o8,vc as o9,Is as oA,Dl as oB,h$1 as oC,Sn$1 as oD,Nn$1 as oE,ce$1 as oF,Tu as oG,vu as oH,ae$1 as oI,xt$3 as oJ,St$3 as oK,Pc as oL,Lc as oM,Ic as oN,mt$3 as oO,rs as oP,an$1 as oQ,Je$2 as oR,Ft$1 as oS,Os as oT,Mt$1 as oU,gt as oV,Co as oW,Tn as oX,Dt as oY,So as oZ,vn as o_,tr as oa,Sn as ob,Zo as oc,Cu as od,Bs as oe,Me as of,yn as og,Se as oh,Cn as oi,fn as oj,qr as ok,Ia as ol,zs as om,gn$2 as on,or as oo,Jr as op,sn$2 as oq,ln$1 as or,rn$1 as os,nn$2 as ot,Vr as ou,nu as ov,du as ow,Va as ox,au as oy,La as oz,decode$4 as p,We as p$,xl as p0,oa as p1,Cn$1 as p2,et as p3,xn as p4,St as p5,Rt as p6,xt as p7,yn$1 as p8,It$1 as p9,Yt as pA,Ya as pB,Pe$2 as pC,Ja as pD,tu as pE,zl as pF,Fl as pG,Ma as pH,ja as pI,Hl as pJ,Ba as pK,Bl as pL,Pr as pM,Pe as pN,uo as pO,mu as pP,iu as pQ,ku as pR,Mo as pS,Rl as pT,wu as pU,Fn as pV,lc as pW,$s as pX,he as pY,Fe as pZ,Ut$1 as p_,Tt as pa,l$2 as pb,a$2 as pc,d$2 as pd,s$2 as pe,Ue$2 as pf,dn$2 as pg,$e$2 as ph,un$1 as pi,Bi as pj,It as pk,en$2 as pl,_$1 as pm,te$2 as pn,le$2 as po,on$2 as pp,$t$3 as pq,mn$2 as pr,Xe$2 as ps,gr as pt,Ge$2 as pu,_r as pv,Ve$2 as pw,je$1 as px,Ye$1 as py,qe$2 as pz,formatTokenCount as q,En$1 as q$,Fs as q0,Al as q1,No as q2,bo as q3,as as q4,_t as q5,eu as q6,fc as q7,Re as q8,Kc as q9,z as qA,O$1 as qB,r$2 as qC,t$2 as qD,Es as qE,_s as qF,vt$2 as qG,n$2 as qH,b$1 as qI,nn$1 as qJ,r$1 as qK,g$1 as qL,Tt$2 as qM,ys as qN,e$1 as qO,vl as qP,u$1 as qQ,b$3 as qR,z$1 as qS,zi as qT,Ji as qU,ko as qV,To as qW,Ze$2 as qX,Qe$2 as qY,Mn$1 as qZ,wn$1 as q_,Wt$1 as qa,z$2 as qb,ac as qc,On$1 as qd,Ht$1 as qe,Le$2 as qf,zr as qg,Bt$1 as qh,Ll as qi,ui as qj,ec as qk,nc as ql,zt$1 as qm,Ir as qn,i$1 as qo,uu as qp,Aa as qq,Wa as qr,Ul as qs,ql as qt,dc as qu,be as qv,ke as qw,ft as qx,pi as qy,x$4 as qz,reactExports as r,RssIcon as r$,xo as r0,vi as r1,Ql as r2,ut$2 as r3,Gl as r4,ReactDOM as r5,M$2 as r6,PersonIcon as r7,Pt$1 as r8,s$1 as r9,BroadcastIcon as rA,BrowserIcon as rB,BugIcon as rC,CircleSlashIcon as rD,CodeReviewIcon as rE,CpuIcon as rF,CreditCardIcon as rG,DependabotIcon as rH,DeviceDesktopIcon as rI,DeviceMobileIcon as rJ,FoldIcon as rK,GearIcon as rL,GitBranchIcon as rM,GlobeIcon as rN,HeartIcon as rO,IssueOpenedIcon as rP,LightBulbIcon as rQ,LinkExternalIcon as rR,MegaphoneIcon as rS,MortarBoardIcon as rT,MuteIcon as rU,OrganizationIcon as rV,PackageIcon as rW,PaperclipIcon as rX,PeopleIcon as rY,PulseIcon as rZ,RocketIcon as r_,f$3 as ra,P$1 as rb,fe$1 as rc,PaperAirplaneIcon as rd,bn$2 as re,TableIcon as rf,q as rg,ChecklistIcon as rh,fn$1 as ri,GrabberIcon as rj,vo as rk,yo as rl,wo as rm,mo as rn,j$1 as ro,r$3 as rp,$2AODx$react as rq,jt$1 as rr,oe$1 as rs,ie$2 as rt,RowsIcon as ru,x$2 as rv,AlertFillIcon as rw,BeakerIcon as rx,BellIcon as ry,BookIcon as rz,sandboxIsLive as s,__rest as s$,ShareAndroidIcon as s0,ShieldCheckIcon as s1,ShieldIcon as s2,SidebarExpandIcon as s3,SkipIcon as s4,SlidersIcon as s5,SparkleFillIcon as s6,SquareCircleIcon as s7,SunIcon as s8,TagIcon as s9,require_Set as sA,requireKeysIn as sB,requireIsArrayLikeObject as sC,requireIsPlainObject$1 as sD,require_baseMerge as sE,require_createAssigner as sF,require_apply as sG,require_copyArray as sH,require_arrayEach as sI,requireCloneDeep as sJ,requireFastUri as sK,ForwardRef$1 as sL,ForwardRef as sM,memoize as sN,isPropValid as sO,tabbable as sP,focusable as sQ,isTabbable as sR,getTabIndex as sS,isFocusable as sT,index_esm as sU,requirePropTypes as sV,s$5 as sW,__assign as sX,requireReactDom as sY,__extends as sZ,__awaiter as s_,TasklistIcon as sa,ThumbsdownIcon as sb,ThumbsupIcon as sc,UnmuteIcon as sd,UploadIcon as se,XCircleFillIcon as sf,ZapIcon as sg,requireFastDeepEqual as sh,getAugmentedNamespace as si,requireParseSrcset as sj,requirePostcss as sk,requireIsPlainObject as sl,requireEscapeStringRegexp as sm,requireIsArguments as sn,require_arrayPush as so,require_baseGetTag as sp,requireIsObject as sq,requireKeys as sr,require_isIndex as ss,requireIsLength as st,requireIdentity as su,require_baseFor as sv,requireIsArrayLike as sw,require_baseUnary as sx,require_baseRest as sy,require_isIterateeCall as sz,timeLeft as t,__generator as t0,require$$0 as t1,requireObjectAssign as t2,ulid$1 as t3,AGENTS_VIEW as t4,CONTENTS_VIEW as t5,DATALAYER_VIEW as t6,JWT_DATALAYER_ISSUER as t7,JWT_REFRESH_TOKEN_COOKIE_NAME as t8,LIBRARY_VIEW as t9,katex$1 as tA,Lexical_prod as tB,LexicalUtils_prod as tC,NAVIGATION_VIEW_HOMES as ta,RESERVATION_WARNING_TIME_MS as tb,SESSION_COOKIES as tc,SESSION_LOCAL_STORAGE_KEYS as td,SESSION_OWNER_KEY as te,SETTINGS_VIEW as tf,TUTOR_VIEW as tg,claimSessionState as th,forgetSessionState as ti,getOtelConsumeUrl as tj,getStoredToken as tk,getStoredUser as tl,isRememberableRoute as tm,isShellNeutralRoute as tn,loadRefreshTokenFromCookie as to,navigationStore as tp,pageConfiguration as tq,profileStore as tr,registerSessionState as ts,storeToken as tt,storeUser as tu,useNavigationStore as tv,useProfile as tw,useProfileStore as tx,viewForRoute as ty,__spreadArray as tz,useNotebookStore$1 as u,vM as v,useSandboxService as w,useSignalValue$1 as x,datalayerCatalog as y,ChatBaseHeader as z};
|
|
4066
|
+
`).trim();if(!Ru)throw new EmbedAttributeError("datalayer-app: the Appspec is empty.");let Iu;if(Ru.startsWith("{")){let Pu;try{Pu=JSON.parse(Ru)}catch(Ou){throw new EmbedAttributeError(`datalayer-app: the Appspec is not JSON (${Ou.message}).`)}Iu=parseAppspec(Pu)}else Iu=readAppspecYaml(Ru);return runnable(Iu)}function frameSrcOf(Au,lo,$u=""){return`${Au.replace(/\/+$/,"")}/public/apps/${encodeURIComponent(lo)}/run?embed=1${$u?`#token=${encodeURIComponent($u)}`:""}`}function frameInLanguage(Au,lo){if(!lo)return Au;const $u=Au.indexOf("#"),[Ru,Iu]=$u<0?[Au,""]:[Au.slice(0,$u),Au.slice($u)];return`${Ru}${Ru.includes("?")?"&":"?"}language=${encodeURIComponent(lo)}${Iu}`}async function readEmbeddedApp({api:Au,origin:lo,app:$u,token:Ru,fetcher:Iu=fetch}){const Pu=await Iu(`${Au.replace(/\/+$/,"")}/api/spacer/v1/apps/${encodeURIComponent($u)}/embedded`,{headers:{Authorization:`Bearer ${Ru}`}});if(Pu.status===401)return{kind:"said",text:"datalayer-app: the embed token expired or is not for this application.",expired:!0};if(!Pu.ok)return{kind:"said",text:`datalayer-app: the application could not be read (${Pu.status}).`};const Ou=await Pu.json();let Mu;try{Mu=JSON.parse(String(Ou.app?.model_s??"{}"))}catch{Mu={}}if(!Mu.spec)return{kind:"frame",src:frameSrcOf(lo,$u,Ru)};const Du=runnable(parseAppspec(Mu.spec));return Du.kind==="decision"?{kind:"frame",src:frameSrcOf(lo,$u,Ru)}:embedTokenDeployment(Ru)?{kind:"spec",app:Du}:{kind:"said",text:EMBED_TOKEN_NAMES_NO_DEPLOYMENT}}function currentScriptUrl(){try{const Au=document.currentScript;return Au?.src?new URL(Au.src,location.href).href:""}catch{return""}}function defineDatalayerAppElement(Au={}){if(typeof window>"u"||!("customElements"in window))return;const lo=Au.tag??EMBED_TAG,$u=customElements.get(lo);if($u)return $u;const Ru=Au.scriptUrl??currentScriptUrl(),Iu=Ru?new URL(Ru).origin:"",Pu=Ru?Ru.replace(/\.js(\?.*)?$/,".css"):"";class Ou extends HTMLElement{static get observedAttributes(){return EMBED_OBSERVED_ATTRIBUTES}root=null;frame=null;source=null;loading=0;passed={};offered={};windowPort=null;host={context:()=>this.passed,userToken:()=>this.getAttribute("user-token")||void 0,functions:this.offered,onWindowPort:Du=>{this.windowPort=Du},onEvent:Du=>this.dispatchEvent(new CustomEvent(Du.type,{detail:Du.detail,bubbles:!0,composed:!0}))};get context(){return this.passed}set context(Du){this.passed={...Du??{}}}postWindowMessage(Du){const Lu=this.windowPort;return Lu?Lu(Du):Promise.reject(new Error(`datalayer-app: ${WINDOW_NOT_YET}`))}get functions(){return this.offered}set functions(Du){for(const Lu of Object.keys(this.offered))delete this.offered[Lu];Object.assign(this.offered,Du??{})}constructor(){super(),this.attachShadow({mode:"open"}),this.onMessage=this.onMessage.bind(this),adoptPropertiesSetEarly(this)}get token(){return this.getAttribute("token")??""}set token(Du){Du?this.setAttribute("token",String(Du)):this.removeAttribute("token")}get userToken(){return this.getAttribute("user-token")??""}set userToken(Du){Du?this.setAttribute("user-token",String(Du)):this.removeAttribute("user-token")}connectedCallback(){window.addEventListener("message",this.onMessage),this.load()}disconnectedCallback(){window.removeEventListener("message",this.onMessage),this.unmount()}attributeChangedCallback(Du,Lu,Bu){if(!(!this.isConnected||Lu===Bu)&&Du!=="user-token"){if(Du==="token"&&this.frame?.contentWindow&&Bu){this.frame.contentWindow.postMessage({type:EMBED_MESSAGES.token,token:Bu},this.origin());return}if(["mode","accent","theme","font","height","resume","language"].includes(Du)){this.draw();return}this.load()}}origin(){return(this.getAttribute("origin")||Iu||location.origin).replace(/\/+$/,"")}inputs(){const Du={};for(const ju of EMBED_OBSERVED_ATTRIBUTES)Du[ju]=this.getAttribute(ju);const Lu=getComputedStyle(this),Bu={};for(const[ju,Fu]of Object.entries(EMBED_HOST_VARIABLES)){const zu=Lu.getPropertyValue(Fu).trim();zu&&(Bu[ju]=zu.replace(/^["']|["']$/g,""))}return{attributes:Du,variables:Bu}}async read(){const Du=this.querySelector('script[type="application/yaml"], script[type="application/json"], script[type="text/yaml"]');if(Du?.textContent?.trim())return{kind:"spec",app:appspecOfText(Du.textContent)};const Lu=this.getAttribute("spec");if(Lu){const Fu=await fetch(new URL(Lu,location.href).href);return Fu.ok?{kind:"spec",app:appspecOfText(await Fu.text())}:{kind:"said",text:`datalayer-app: the Appspec at ${Lu} could not be read (${Fu.status}).`}}const Bu=this.getAttribute("app");if(!Bu)return{kind:"said",text:'datalayer-app: the "app" attribute names the application to show, or "spec" the address of its Appspec.'};const ju=this.token;if(!ju){const Fu=await readVisitorApp({api:this.agents(),app:Bu});return Fu.kind==="decision"?{kind:"frame",src:frameSrcOf(this.origin(),Fu.app)}:Fu.kind==="said"?{kind:"said",text:Fu.text}:{kind:"spec",app:Fu.app,visitors:Fu.visitors}}return readEmbeddedApp({api:this.api(),origin:this.origin(),app:Bu,token:ju})}spoken=null;get speech(){const Du=coreStore.getState().configuration?.aiAgentsUrl??"";return this.spoken?.speechUrl!==Du&&(this.spoken={speechUrl:Du}),this.spoken}agents(){return(this.getAttribute("api")||coreStore.getState().configuration?.aiAgentsUrl||DEFAULT_API).replace(/\/+$/,"")}api(){return(this.getAttribute("api")||coreStore.getState().configuration?.spacerUrl||"https://prod1.datalayer.run").replace(/\/+$/,"")}async load(){const Du=++this.loading;let Lu;try{Lu=await this.read()}catch(Bu){Lu={kind:"said",text:Bu instanceof Error?Bu.message:`datalayer-app: ${String(Bu)}`}}Du!==this.loading||!this.isConnected||(this.source=Lu,this.draw(),Lu.kind==="said"&&Lu.expired&&this.dispatchEvent(new CustomEvent("token-expired",{detail:{app:this.getAttribute("app")??""},bubbles:!0,composed:!0})))}unmount(){this.root?.unmount(),this.root=null,this.frame=null}skeleton(Du){const Lu=this.shadowRoot;if(this.unmount(),Lu.replaceChildren(),Pu){const ju=document.createElement("link");ju.rel="stylesheet",ju.href=Pu,Lu.appendChild(ju)}const Bu=document.createElement("style");return Bu.textContent=embedShadowCss(Du),Lu.appendChild(Bu),Lu}say(Du){this.setAttribute("data-embed-mode","inline");const Lu=this.skeleton(),Bu=document.createElement("p");Bu.className="datalayer-app-said",Bu.setAttribute("role","status"),Bu.textContent=Du,Lu.appendChild(Bu)}draw(){const Du=this.source;if(!Du)return;if(Du.kind==="said"){this.say(Du.text);return}if(Du.kind==="frame"){let Hu;try{Hu=languageOf(this.getAttribute("language"))}catch(Wu){this.say(Wu.message);return}this.setAttribute("data-embed-mode","inline");const Vu=this.skeleton(),Gu=document.createElement("iframe");Gu.className="datalayer-app-frame",Gu.src=frameInLanguage(Du.src,Hu),Gu.title="Datalayer app",Gu.style.height=`${inlineHeightOf(this.getAttribute("height"))}px`,Gu.setAttribute("allow","clipboard-write"),Vu.appendChild(Gu),this.frame=Gu;return}let Lu,Bu,ju;try{Lu=embedLookOf(this.inputs(),Du.app),Bu=resumeOf(this.getAttribute("resume")),ju=languageOf(this.getAttribute("language"))}catch(Hu){this.say(Hu.message);return}if(Lu.mode==="assistant"){const Hu=embedAssistantCharacter(Du.app);if("problem"in Hu){this.say(Hu.problem);return}}this.setAttribute("data-embed-mode",Lu.mode);const Fu=this.skeleton(getThemeConfig(Lu.variant).themeStyles.css),zu=document.createElement("div");zu.className="datalayer-app-root",Fu.appendChild(zu),this.root=clientExports.createRoot(zu);const Uu=this.getAttribute("server")||void 0;this.root.render(jsxRuntimeExports.jsx(me$3,{target:Fu,children:jsxRuntimeExports.jsx(AppEmbed,{app:Du.app,mode:Lu.mode,accent:Lu.accent,colorMode:Lu.colorMode,font:Lu.font,serverUrl:Uu,...Uu&&this.token?{embedToken:this.token}:{},...Du.visitors?{visitors:Du.visitors}:{},speech:this.speech,height:inlineHeightOf(this.getAttribute("height")),ownPortal:!0,host:this.host,resume:Bu,...ju?{language:ju}:{}})}))}onMessage(Du){if(!this.frame||Du.source!==this.frame.contentWindow||Du.origin!==this.origin())return;const Lu=Du.data??{};Lu.type===EMBED_MESSAGES.size&&typeof Lu.height=="number"&&Lu.height>0?this.frame.style.height=`${Math.ceil(Lu.height)}px`:Lu.type===EMBED_MESSAGES.decision?this.dispatchEvent(new CustomEvent("decision",{detail:Lu.record,bubbles:!0,composed:!0})):Lu.type===EMBED_MESSAGES.tokenExpired&&this.dispatchEvent(new CustomEvent("token-expired",{detail:{app:this.getAttribute("app")??""},bubbles:!0,composed:!0}))}}return customElements.define(lo,Ou),Ou}const SCRIPT_FILE="datalayer-app.js";defineDatalayerAppElement({scriptUrl:new URL(SCRIPT_FILE,import.meta.url).href});const mermaidVLURNSYL=Object.freeze(Object.defineProperty({__proto__:null,Mermaid:Ee$2},Symbol.toStringTag,{value:"Module"}));export{styleTags as $,A2uiSurfaceComposed as A,Box as B,CheckIcon as C,Dialog$1 as D,useContributions as E,LoopPromptPanel as F,InputPrompt as G,Heading$2 as H,IconButton as I,Signal as J,o$1 as K,Label as L,MessageProcessor as M,NO_SANDBOX_YET as N,LoopOpeningNotebook as O,PlayIcon as P,QueryClient as Q,LoopNotebookToolbarItem as R,SANDBOX_KIND_LABELS as S,Text$3 as T,LoopNotebookToolbar as U,LRLanguage as V,LanguageSupport as W,indentNodeProp as X,continuedIndent as Y,foldNodeProp as Z,__vitePreload as _,QueryClientProvider as a,AGENTS_PLUGIN_NAME as a$,tags as a0,ExternalTokenizer as a1,ifNotIn as a2,completeFromList as a3,LRParser as a4,syntaxTree as a5,delimitedIndent as a6,foldInside as a7,getDefaultExportFromCjs as a8,MimeModel as a9,DatalayerThemeProvider as aA,de$1 as aB,on$1 as aC,nl as aD,es as aE,H as aF,disposeServiceManager as aG,create$g as aH,setIfUndefined as aI,create$6 as aJ,fromBase64 as aK,onChange as aL,varStorage as aM,toBase64 as aN,offChange as aO,createUint8ArrayFromArrayBuffer as aP,map$3 as aQ,ContextTracker as aR,NodeWeakMap as aS,IterMode as aT,snippetCompletion as aU,Panel as aV,PromiseDelegate as aW,DEFAULT_SERVICE_URLS as aX,requestDatalayerAPI as aY,API_BASE_PATHS as aZ,useReactorPlatform as a_,standardRendererFactories as aa,purify$1 as ab,Token$2 as ac,Menu as ad,DisposableDelegate as ae,ArrayExt as af,Widget as ag,PanelLayout as ah,ITranslator as ai,createToolbarFactory as aj,nullTranslator as ak,ObservableList as al,Toolbar$1 as am,ReactWidget as an,some$1 as ao,useAgentsRuntimes as ap,xu as aq,useThemeStore as ar,useSystemColorMode as as,getThemeConfig as at,JupyterReactTheme$1 as au,l$1 as av,v$1 as aw,a$1 as ax,Kernel as ay,registerSandboxServiceManager as az,sandboxExecuteOverHttp as b,VDomModel as b$,DEFAULT_DATALAYER_AGENTSPEC as b0,useOptionalSandboxService as b1,IDLE_SANDBOX_TARGET_SIGNAL as b2,ensureVisitorAgent as b3,AGENTSPECS$1 as b4,useAgentRuntimes as b5,ActionList as b6,distExports as b7,ActionListContainerContext as b8,BoxWithFallback as b9,defineLanguageFacet as bA,Parser$2 as bB,NodeType as bC,NodeProp as bD,Tag as bE,NodeSet as bF,Tree as bG,countColumn as bH,Prec as bI,keymap as bJ,Language as bK,indentUnit as bL,foldService as bM,CompletionContext as bN,EditorState as bO,languageDataProp as bP,LanguageDescription as bQ,ParseContext as bR,Eu as bS,Ke$2 as bT,_c as bU,is as bV,Ys as bW,PencilIcon as bX,SingletonLayout as bY,FocusTracker as bZ,libExports$5 as b_,merge$5 as ba,defaultSxProp as bb,useId as bc,reactDomExports as bd,useIsomorphicLayoutEffect$2 as be,ChevronDownIcon as bf,classes$t as bg,SubItem as bh,Box$1 as bi,themeConfigs as bj,LoopDocumentToolbarItem as bk,LoopDocumentToolbar as bl,LoopOpeningDocument as bm,IDLE_SANDBOX_SNAPSHOT_SIGNAL as bn,definePlugin as bo,DOCUMENT_TOOLBAR_PLUGIN_NAME as bp,contribution as bq,KernelIndicator as br,NOTEBOOK_TOOLBAR_PLUGIN_NAME as bs,LocalTokenGroup as bt,flatIndent as bu,parseMixed as bv,bracketMatchingHandle as bw,EditorView as bx,EditorSelection as by,sublanguageProp as bz,ButtonComponent as c,ITableOfContentsRegistry as c$,TableOfContents as c0,JSONExt as c1,VDomRenderer as c2,LabIcon as c3,classes as c4,map$5 as c5,showErrorMessage as c6,AttachedProperty as c7,addIcon as c8,launcherIcon as c9,linkIcon as cA,Clipboard as cB,downloadIcon as cC,copyIcon as cD,setToolbar as cE,Notification as cF,CommandRegistry as cG,closeIcon as cH,cutIcon as cI,pasteIcon as cJ,newFolderIcon as cK,textEditorIcon as cL,markdownIcon as cM,refreshIcon as cN,editIcon as cO,fileIcon as cP,stopIcon as cQ,filterIcon as cR,DisposableSet as cS,clearNumbering as cT,getHeadingId as cU,addPrefix as cV,parseHeadings as cW,filterHeadings as cX,StackedLayout as cY,ABCWidgetFactory as cZ,DocumentWidget as c_,MainAreaWidget as ca,find$3 as cb,TranslatorConnector as cc,Gettext as cd,DEFAULT_LANGUAGE_CODE as ce,normalizeDomain as cf,ITranslatorConnector as cg,Dialog as ch,showDialog$1 as ci,SearchDocumentModel as cj,SearchDocumentView as ck,isResponsiveValue as cl,clsx as cm,commonjsRequire as cn,TextInput$1 as co,SearchIcon as cp,SyncIcon as cq,ToggleSwitch as cr,Flash as cs,ChevronRightIcon as ct,StyledSpinner as cu,ToolbarButton as cv,fileUploadIcon as cw,libExports$2 as cx,WidgetTracker as cy,folderIcon as cz,displayUrl as d,OutputPrompt as d$,markdownRendererFactory as d0,SkeletonBox as d1,getBrightPalette as d2,useColorPalette as d3,SkeletonText as d4,Tooltip as d5,ActionMenu as d6,buildIcon as d7,jupyterIcon as d8,SettingRegistry as d9,EditorExtensionRegistry as dA,ybinding as dB,IPositionModel as dC,historyIcon as dD,CommandToolbarButton as dE,caretLeftIcon as dF,caretRightIcon as dG,checkIcon as dH,COMPLETER_ACTIVE_CLASS as dI,Debouncer as dJ,SessionContextDialogs as dK,saveIcon as dL,addCommandToolbarButtonClass as dM,UseSignal as dN,CommandToolbarButtonComponent as dO,createStore$1 as dP,useStore$1 as dQ,runtimesStore as dR,DATALAYER_IAM_TOKEN_KEY as dS,DATALAYER_IAM_USER_KEY as dT,coreStore as dU,iamStore as dV,layoutStore as dW,useCoreStore as dX,useIAMStore as dY,useLayoutStore as dZ,useRuntimesStore as d_,moveUpIcon as da,moveDownIcon as db,Button$1 as dc,deleteIcon as dd,DOMUtils as de,lineFormIcon as df,deleteLine as dg,toggleBlockComment as dh,toggleComment as di,toggleTabFocusMode as dj,selectNextOccurrence as dk,foldable as dl,foldCode as dm,unfoldCode as dn,foldState as dp,foldEffect as dq,unfoldEffect as dr,foldAll as ds,unfoldAll as dt,IEditorServices as du,EditorLanguageRegistry as dv,parseMathIPython as dw,StreamLanguage as dx,pythonBuiltin as dy,EditorThemeRegistry as dz,Link$1 as e,AgentTools as e$,Stdin as e0,CodeCell as e1,useJupyterLabCssLoaded as e2,TelescopeIcon as e3,XIcon as e4,CounterLabel as e5,PauseIcon as e6,DownloadIcon as e7,SPAN_SOURCE_LABELS as e8,sourceOfSpan as e9,useAgentRuntimeMcpStatus as eA,useAgentRuntimeCodemodeStatus as eB,useAgentRuntimeContextSnapshot as eC,useAgentRuntimeFullContext as eD,useAgentRuntimeWsState as eE,useMutation as eF,useQuery as eG,ForwardRef$2 as eH,NoteIcon as eI,ServerIcon as eJ,CheckCircleIcon as eK,XCircleIcon as eL,BriefcaseIcon as eM,MenuBar as eN,runIcon as eO,fastForwardIcon as eP,require_MapCache as eQ,require_Symbol as eR,require_Uint8Array as eS,requireEq as eT,require_getAllKeys as eU,require_Stack as eV,require_getTag as eW,requireIsArray as eX,requireIsBuffer as eY,requireIsTypedArray as eZ,requireIsObjectLike as e_,AGENT_SPAN_ATTRIBUTES as ea,describeAgentSpan as eb,SpecMark as ec,parse$4 as ed,UUID as ee,EN_US as ef,errorIcon as eg,Platform as eh,caretDownEmptyThinIcon as ei,StringExt as ej,SegmentedControl as ek,ListUnorderedIcon as el,GraphIcon as em,ClockIcon as en,DatabaseIcon as eo,FileIcon as ep,ToolsIcon as eq,CommentDiscussionIcon as er,AiModelIcon as es,InfoIcon as et,KeyIcon as eu,devtools as ev,subscribeWithSelector as ew,persist as ex,CheckCircleFillIcon as ey,AlertIcon as ez,CopyIcon as f,THREAD_WORDS as f$,useToast as f0,isInsideJupyterLab as f1,FormControl$1 as f2,MailIcon as f3,Textarea as f4,$e$5 as f5,PRESENCE_LINES as f6,useAnonymousInferenceSession as f7,browserModelRequiresSignIn as f8,getAgentspecs as f9,onSurfaceRequest as fA,setEditorOptions as fB,seedEditorChoice as fC,canOpenView as fD,useWorkspaceFullScreen as fE,targetRunsAgentInPage as fF,useOptionalTeamSelection as fG,LoopAgentBlueprint as fH,resolveAgentspec as fI,LoopChatSuggestion as fJ,agentIcon as fK,LoopFrontendTool as fL,BROWSER_CODE_TOOL as fM,agentServerOf as fN,LoopCommand as fO,subagentsFor as fP,useChatAvailability as fQ,noRuntimeSaid as fR,useVoiceSettings as fS,settledVoice as fT,useSlotComponents as fU,LoopSlots as fV,onPromptFocusRequest as fW,useVisitorToken as fX,voiceAskedAs as fY,generateMessageId as fZ,openThread as f_,useOptionalReactorPlatform as fa,FluentEmoji as fb,useChatWords as fc,CHAT_PLUGIN_NAME as fd,INPUT_PROMPT_PLUGIN_NAME as fe,LoopChatSurface as ff,LoopChatComposer as fg,LoopChatHeader as fh,LoopChatLayout as fi,LoopChatTurn as fj,turnWritersOf as fk,LoopChatExtras as fl,computed$1 as fm,useGate as fn,presenceState as fo,presenceToolOf as fp,newestIsAnswer as fq,latestSaying as fr,messageText as fs,LoopRunProps as ft,runForwardedProps as fu,dataUrlBase64 as fv,sandboxFileName as fw,writeFilesCode as fx,givenFilesSentence as fy,sendInstead as fz,createAllAgentRuntimesTools as g,CommandPalette$1 as g$,agentInstructions as g0,useConfig as g1,useSkills as g2,useSkillActions as g3,runtimeModelsUrl as g4,readServerCatalogue as g5,readServerDecisions as g6,offeredModels as g7,AI_MODEL_CATALOGUE as g8,isChatModel as g9,requireMessages as gA,mockSocketExports as gB,ObservableMap as gC,CodeEditorWrapper as gD,CodeEditor as gE,IEditorMimeTypeService as gF,EditorSearchProvider as gG,CodeMirrorEditor as gH,getPrefix as gI,isMarkdown as gJ,findNext as gK,gotoLine as gL,consoleIcon as gM,undoIcon as gN,redoIcon as gO,selectAll as gP,Sanitizer as gQ,COMPLETER_ENABLED_CLASS as gR,MessageLoop as gS,COMPLETER_LINE_BEGINNING_CLASS as gT,Message as gU,ElementExt as gV,renderText as gW,Printing as gX,clientExports as gY,RenderedJavaScript as gZ,filterListIcon as g_,ReactorSlot as ga,ComposerVoice as gb,ReactorLazy as gc,ChatBase as gd,ScreenNormalIcon as ge,ScreenFullIcon as gf,SUGGESTION_CHIP_WIDTH as gg,Truncate as gh,useAnonymousSessionStore as gi,inPageAgentRefusal as gj,signal$2 as gk,LoopAgentGate as gl,agentRuntimeStore as gm,loopShapeVars as gn,NONE_EDITOR as go,getAnchoredPosition as gp,reactIsExports as gq,useTheme as gr,useOnEscapePress as gs,useOnOutsideClick as gt,useResizeObserver as gu,VisuallyHidden as gv,TriangleDownIcon as gw,qe$4 as gx,sx as gy,requireSerialize as gz,renderOcticon as h,strokeWidth$1 as h$,h$7 as h0,LabIconStyle as h1,copyrightIcon as h2,ToolbarButtonComponent as h3,bellIcon as h4,Button$3 as h5,paletteIcon as h6,Throttler as h7,Selector$1 as h8,jupyterFaviconIcon as h9,startSlotTemplate as hA,endSlotTemplate as hB,slotted as hC,elements as hD,FoundationElement as hE,isHTMLElement as hF,__decorate$1 as hG,attr as hH,observable as hI,applyMixins as hJ,StartEnd as hK,keyEnter as hL,keyArrowUp as hM,keyArrowDown as hN,keyArrowRight as hO,keyArrowLeft as hP,keyEnd as hQ,keyHome as hR,DOM as hS,getDisplayedNodes as hT,direction$1 as hU,neutralForegroundRest$1 as hV,neutralFillStealthRest$1 as hW,bodyFont$1 as hX,focusVisible as hY,accentFillFocus$1 as hZ,focusStrokeWidth$1 as h_,caretDownEmptyIcon as ha,addToolbarButtonClass as hb,NotebookActions as hc,offlineBoltIcon as hd,circleIcon as he,ObservableJSON as hf,ConflatableMessage as hg,jumpBackIcon as hh,jumpForwardIcon as hi,MarkdownCell as hj,Cell as hk,trustedIcon as hl,notTrustedIcon as hm,runCell as hn,InputPrompt$1 as ho,NotebookPanel as hp,setCellExecutor as hq,StaticNotebook as hr,notebookIcon as hs,NotebookSearchProvider as ht,duplicateIcon as hu,addAboveIcon as hv,addBelowIcon as hw,children$1 as hx,ref$1 as hy,html$6 as hz,SquareFillIcon as i,createCellModelFromSharedType as i$,controlCornerRadius$1 as i0,heightNumber$1 as i1,neutralFillStealthHover$1 as i2,neutralFillStealthActive$1 as i3,designUnit$1 as i4,typeRampBaseFontSize$1 as i5,typeRampBaseLineHeight$1 as i6,density$1 as i7,typeRampPlus1FontSize$1 as i8,disabledOpacity$1 as i9,circleEmptyIcon as iA,searchIcon as iB,SplitPanel as iC,TabBar as iD,jsonIcon as iE,spreadsheetIcon as iF,terminalIcon as iG,kernelIcon as iH,NotificationManager as iI,SessionContext as iJ,Spinner as iK,Styling as iL,SystemClipboard as iM,VisuallyHidden$1 as iN,StopIcon as iO,ViewPlugin as iP,createRelativePositionFromTypeIndex as iQ,createRelativePositionFromJSON as iR,tooltips as iS,Facet as iT,Annotation as iU,layer as iV,StateField as iW,showTooltip as iX,createAbsolutePositionFromRelativePosition as iY,RectangleMarker as iZ,YDocument as i_,disabledCursor as ia,baseHeightMultiplier$1 as ib,neutralFillRest$1 as ic,neutralFillHover$1 as id,neutralFillActive$1 as ie,accentForegroundRest$1 as ig,display as ih,css as ii,forcedColorsStylesheetBehavior as ij,SystemColors as ik,cssPartial as il,DesignToken as im,neutralFillStealthRecipe$1 as io,neutralFillRecipe$1 as ip,useEventListener as iq,useProperties as ir,provideJupyterDesignSystem$1 as is,ITableOfContentsTracker as it,tocIcon as iu,numberingIcon as iv,expandAllIcon as iw,collapseAllIcon as ix,ellipsesIcon as iy,caretDownIcon as iz,jsxRuntimeExports as j,activateHover as j$,createCell as j0,YMap as j1,RawCellModel as j2,MarkdownCellModel as j3,CodeCellModel as j4,MINOR_VERSION as j5,MAJOR_VERSION as j6,StateEffect as j7,Decoration as j8,WidgetType as j9,CheckboxOrRadioGroup$1 as jA,CheckboxGroupContext as jB,Checkbox as jC,RadioGroup$1 as jD,Radio as jE,SelectPanel as jF,Select$1 as jG,TextInputWithTokens as jH,object as jI,preprocess$1 as jJ,record$2 as jK,string$2 as jL,unknown$1 as jM,zodToToolParameters as jN,array as jO,_enum as jP,number$2 as jQ,boolean$1 as jR,validateWithZod as jS,useJupyterReactStoreFromProps as jT,OutputArea as jU,createStandaloneCell as jV,BoxPanel as jW,cellsStore as jX,RawCell as jY,useCellsStore as jZ,getPanel as j_,DEFAULT_VARIANT as ja,MarimoReactive as jb,NotebookCommandIds as jc,OutputAreaModel as jd,useJupyterReactStore as je,newUuid as jf,NotebookPanelProvider as jg,addNotebookCommands as jh,YArray as ji,YText as jj,newUlid as jk,k$2 as jl,loopColors as jm,sunColors as jn,ivoryColors as jo,sandColors as jp,earthColors as jq,matrixColors as jr,lovelyColors as js,spatialColors as jt,datalayerColors as ju,getColorPalette as jv,CheckboxOrRadioGroupValidation as jw,CheckboxOrRadioGroupLabel as jx,CheckboxOrRadioGroupCaption as jy,useRenderForcingRef as jz,TrashIcon as k,y$3 as k$,showPanel as k0,combineConfig as k1,RangeSetBuilder as k2,crelt as k3,hoverTooltip as k4,lineNumbers as k5,highlightActiveLineGutter as k6,highlightSpecialChars as k7,history as k8,foldGutter as k9,ccount as kA,zwitch as kB,html$4 as kC,htmlVoidElements as kD,C$1 as kE,Dt$4 as kF,u$2 as kG,dt$2 as kH,Go as kI,ns as kJ,mn$1 as kK,qi as kL,Pi as kM,isStream as kN,isExecuteResult as kO,isDisplayData as kP,isError$1 as kQ,Xo as kR,Ki as kS,Yi as kT,er as kU,T as kV,v$2 as kW,S$1 as kX,C as kY,m$2 as kZ,x$5 as k_,drawSelection as ka,dropCursor as kb,indentOnInput as kc,syntaxHighlighting as kd,bracketMatching as ke,closeBrackets as kf,autocompletion as kg,rectangularSelection as kh,crosshairCursor as ki,highlightActiveLine as kj,highlightSelectionMatches as kk,closeBracketsKeymap as kl,defaultKeymap as km,searchKeymap as kn,historyKeymap as ko,foldKeymap as kp,completionKeymap as kq,defaultHighlightStyle as kr,ArrowRightIcon as ks,useOutputsStore as kt,Compartment as ku,whitespace as kv,svg$2 as kw,find as kx,stringify$1 as ky,stringify as kz,libExports$3 as l,TextModelFactory as l$,p$4 as l0,ol as l1,He$2 as l2,pn$2 as l3,Kr as l4,ur as l5,ls as l6,cn$1 as l7,_n as l8,hn$2 as l9,useResponsiveValue as lA,ScrollableRegion as lB,viewportRanges as lC,JupyterLiteServer as lD,Router as lE,ContextMenu as lF,TabPanel as lG,DockPanel as lH,hpass as lI,AccordionPanel as lJ,AccordionLayout as lK,FormAssociated as lL,nullableNumberConverter as lM,ARIAGlobalStatesAndProperties as lN,neutralFillInputRest$1 as lO,neutralFillStrongRest$1 as lP,errorFillRest$1 as lQ,neutralFillInputHover$1 as lR,neutralFillStrongHover$1 as lS,errorFillHover$1 as lT,neutralFillStrongActive$1 as lU,errorFillActive$1 as lV,errorFillFocus$1 as lW,neutralStrokeRest$1 as lX,__decorate as lY,BoxLayout as lZ,VirtualDOM as l_,qc as la,Ie$2 as lb,cs as lc,dr as ld,Jl as le,fn$2 as lf,hn$1 as lg,pn$1 as lh,Wo as li,xt$2 as lj,Zs as lk,gc as ll,On as lm,na as ln,ea as lo,ia as lp,sa as lq,decodeNamedCharacterReference as lr,requireReact as ls,StyleModule as lt,jupyterHighlightStyle as lu,useFocusZone as lv,FocusKeys as lw,useSafeTimeout as lx,useSlots as ly,useProvidedRefOrCreate as lz,PlusIcon as m,KERNEL_STATE_LABELS as m$,pdfIcon as m0,pythonIcon as m1,juliaIcon as m2,rKernelIcon as m3,yamlIcon as m4,imageIcon as m5,audioIcon as m6,videoIcon as m7,writeVarUint as m8,encodeStateVector as m9,filter$3 as mA,caretUpIcon as mB,Poll as mC,each as mD,Application as mE,StackedPanel as mF,tabIcon as mG,Base64ModelFactory as mH,useTerminalStore as mI,requestAPI$1 as mJ,loadJupyterConfig as mK,createLiteServiceManager as mL,jupyterReactStore as mM,ANSWER_MARKER as mN,BuilderManagerLess as mO,ContentsManagerLess as mP,DEFAULT_API_KERNEL_PREFIX_URL as mQ,DEFAULT_JUPYTER_SERVER_TOKEN as mR,DEFAULT_JUPYTER_SERVER_URL as mS,DEFAULT_KERNEL_NAME as mT,DefaultExecutor as mU,EventsManagerLess as mV,ExecutionPhase as mW,HELPER_NAME as mX,JupyterLabCss as mY,KERNEL_HELPER_SOURCE as mZ,KERNEL_STATES as m_,writeVarUint8Array as ma,encodeStateAsUpdate as mb,readVarUint as mc,applyUpdate as md,readVarUint8Array as me,readVarString as mf,ObservableV2 as mg,Awareness as mh,toUint8Array$1 as mi,length as mj,encodeAwarenessUpdate as mk,removeAwarenessStates as ml,isNode as mm,getUnixTime as mn,createEncoder as mo,min as mp,pow as mq,createDecoder as mr,applyAwarenessUpdate as ms,UndoManager as mt,Doc$1 as mu,isCodeCellModel as mv,Drag as mw,MimeData as mx,useConsoleStore as my,folderFavoriteIcon as mz,CodeIcon as n,Fi as n$,KERNEL_STATE_VISUALS as n0,KernelExecutor as n1,KernelManagerLess as n2,KernelspecManagerLess as n3,NbConvertManagerLess as n4,OperationRunner as n5,ServiceManagerLess as n6,SessionManagerLess as n7,SettingManagerLess as n8,TerminalManagerLess as n9,loadJupyterLabCss as nA,notebookToolDefinitions as nB,notebookToolOperations as nC,notebookTools as nD,outputsAsString as nE,outputsStore as nF,readAllCellsOperation as nG,readAllCellsTool as nH,readCellOperation as nI,readCellTool as nJ,refreshJupyterLabPortalTheme as nK,renderKernelStateGlyph as nL,resetJupyterConfig as nM,runCellOperation as nN,runCellTool as nO,setJupyterServerToken as nP,setJupyterServerUrl as nQ,sleep as nR,syncJupyterLabPortalTheme as nS,terminalStore as nT,toKernelState as nU,updateCellOperation as nV,updateCellTool as nW,useJupyterReactColormode as nX,useKernelsStore as nY,ThemeProvider as nZ,Overlay$1 as n_,UserManagerLess as na,WorkspaceManagerLess as nb,cellSourceAsString as nc,consoleStore as nd,createLiteServer as ne,createServerSettings as nf,deleteCellsOperation as ng,deleteCellsTool as nh,disableKernelReconnect as ni,disposeKernelConnections as nj,ensureJupyterAuth as nk,ensureJupyterConfig as nl,executeCodeOperation as nm,executeCodeTool as nn,formatResponse as no,getCookie as np,getJupyterServerToken as nq,getJupyterServerUrl as nr,getKernelIndicatorMeta as ns,insertCellOperation as nt,insertCellTool as nu,isAnyCellRunning as nv,isReactiveVariant as nw,isServedByJupyterLab as nx,jupyterLabTheme as ny,kernelsStore as nz,notebookStore as o,kn$1 as o$,Zl as o0,bu as o1,Nu as o2,Wl as o3,Fr as o4,Li as o5,Vc as o6,Fo as o7,sn$1 as o8,vc as o9,Is as oA,Dl as oB,h$1 as oC,Sn$1 as oD,Nn$1 as oE,ce$1 as oF,Tu as oG,vu as oH,ae$1 as oI,xt$3 as oJ,St$3 as oK,Pc as oL,Lc as oM,Ic as oN,mt$3 as oO,rs as oP,an$1 as oQ,Je$2 as oR,Ft$1 as oS,Os as oT,Mt$1 as oU,gt as oV,Co as oW,Tn as oX,Dt as oY,So as oZ,vn as o_,tr as oa,Sn as ob,Zo as oc,Cu as od,Bs as oe,Me as of,yn as og,Se as oh,Cn as oi,fn as oj,qr as ok,Ia as ol,zs as om,gn$2 as on,or as oo,Jr as op,sn$2 as oq,ln$1 as or,rn$1 as os,nn$2 as ot,Vr as ou,nu as ov,du as ow,Va as ox,au as oy,La as oz,decode$4 as p,We as p$,xl as p0,oa as p1,Cn$1 as p2,et as p3,xn as p4,St as p5,Rt as p6,xt as p7,yn$1 as p8,It$1 as p9,Yt as pA,Ya as pB,Pe$2 as pC,Ja as pD,tu as pE,zl as pF,Fl as pG,Ma as pH,ja as pI,Hl as pJ,Ba as pK,Bl as pL,Pr as pM,Pe as pN,uo as pO,mu as pP,iu as pQ,ku as pR,Mo as pS,Rl as pT,wu as pU,Fn as pV,lc as pW,$s as pX,he as pY,Fe as pZ,Ut$1 as p_,Tt as pa,l$2 as pb,a$2 as pc,d$2 as pd,s$2 as pe,Ue$2 as pf,dn$2 as pg,$e$2 as ph,un$1 as pi,Bi as pj,It as pk,en$2 as pl,_$1 as pm,te$2 as pn,le$2 as po,on$2 as pp,$t$3 as pq,mn$2 as pr,Xe$2 as ps,gr as pt,Ge$2 as pu,_r as pv,Ve$2 as pw,je$1 as px,Ye$1 as py,qe$2 as pz,formatTokenCount as q,En$1 as q$,Fs as q0,Al as q1,No as q2,bo as q3,as as q4,_t as q5,eu as q6,fc as q7,Re as q8,Kc as q9,z as qA,O$1 as qB,r$2 as qC,t$2 as qD,Es as qE,_s as qF,vt$2 as qG,n$2 as qH,b$1 as qI,nn$1 as qJ,r$1 as qK,g$1 as qL,Tt$2 as qM,ys as qN,e$1 as qO,vl as qP,u$1 as qQ,b$3 as qR,z$1 as qS,zi as qT,Ji as qU,ko as qV,To as qW,Ze$2 as qX,Qe$2 as qY,Mn$1 as qZ,wn$1 as q_,Wt$1 as qa,z$2 as qb,ac as qc,On$1 as qd,Ht$1 as qe,Le$2 as qf,zr as qg,Bt$1 as qh,Ll as qi,ui as qj,ec as qk,nc as ql,zt$1 as qm,Ir as qn,i$1 as qo,uu as qp,Aa as qq,Wa as qr,Ul as qs,ql as qt,dc as qu,be as qv,ke as qw,ft as qx,pi as qy,x$4 as qz,reactExports as r,RssIcon as r$,xo as r0,vi as r1,Ql as r2,ut$2 as r3,Gl as r4,ReactDOM as r5,M$2 as r6,PersonIcon as r7,Pt$1 as r8,s$1 as r9,BroadcastIcon as rA,BrowserIcon as rB,BugIcon as rC,CircleSlashIcon as rD,CodeReviewIcon as rE,CpuIcon as rF,CreditCardIcon as rG,DependabotIcon as rH,DeviceDesktopIcon as rI,DeviceMobileIcon as rJ,FoldIcon as rK,GearIcon as rL,GitBranchIcon as rM,GlobeIcon as rN,HeartIcon as rO,IssueOpenedIcon as rP,LightBulbIcon as rQ,LinkExternalIcon as rR,MegaphoneIcon as rS,MortarBoardIcon as rT,MuteIcon as rU,OrganizationIcon as rV,PackageIcon as rW,PaperclipIcon as rX,PeopleIcon as rY,PulseIcon as rZ,RocketIcon as r_,f$3 as ra,P$1 as rb,fe$1 as rc,PaperAirplaneIcon as rd,bn$2 as re,TableIcon as rf,q as rg,ChecklistIcon as rh,fn$1 as ri,GrabberIcon as rj,vo as rk,yo as rl,wo as rm,mo as rn,j$1 as ro,r$3 as rp,$2AODx$react as rq,jt$1 as rr,oe$1 as rs,ie$2 as rt,RowsIcon as ru,x$2 as rv,AlertFillIcon as rw,BeakerIcon as rx,BellIcon as ry,BookIcon as rz,sandboxIsLive as s,__rest as s$,ShareAndroidIcon as s0,ShieldCheckIcon as s1,ShieldIcon as s2,SidebarExpandIcon as s3,SkipIcon as s4,SlidersIcon as s5,SparkleFillIcon as s6,SquareCircleIcon as s7,SunIcon as s8,TagIcon as s9,require_Set as sA,requireKeysIn as sB,requireIsArrayLikeObject as sC,requireIsPlainObject$1 as sD,require_baseMerge as sE,require_createAssigner as sF,require_apply as sG,require_copyArray as sH,require_arrayEach as sI,requireCloneDeep as sJ,requireFastUri as sK,ForwardRef$1 as sL,ForwardRef as sM,memoize as sN,isPropValid as sO,tabbable as sP,focusable as sQ,isTabbable as sR,getTabIndex as sS,isFocusable as sT,index_esm as sU,requirePropTypes as sV,s$5 as sW,__assign as sX,requireReactDom as sY,__extends as sZ,__awaiter as s_,TasklistIcon as sa,ThumbsdownIcon as sb,ThumbsupIcon as sc,UnmuteIcon as sd,UploadIcon as se,XCircleFillIcon as sf,ZapIcon as sg,requireFastDeepEqual as sh,getAugmentedNamespace as si,requireParseSrcset as sj,requirePostcss as sk,requireIsPlainObject as sl,requireEscapeStringRegexp as sm,requireIsArguments as sn,require_arrayPush as so,require_baseGetTag as sp,requireIsObject as sq,requireKeys as sr,require_isIndex as ss,requireIsLength as st,requireIdentity as su,require_baseFor as sv,requireIsArrayLike as sw,require_baseUnary as sx,require_baseRest as sy,require_isIterateeCall as sz,timeLeft as t,__generator as t0,require$$0 as t1,requireObjectAssign as t2,ulid$1 as t3,AGENTS_VIEW as t4,CONTENTS_VIEW as t5,DATALAYER_VIEW as t6,JWT_DATALAYER_ISSUER as t7,JWT_REFRESH_TOKEN_COOKIE_NAME as t8,LIBRARY_VIEW as t9,katex$1 as tA,Lexical_prod as tB,LexicalUtils_prod as tC,NAVIGATION_VIEW_HOMES as ta,RESERVATION_WARNING_TIME_MS as tb,SESSION_COOKIES as tc,SESSION_LOCAL_STORAGE_KEYS as td,SESSION_OWNER_KEY as te,SETTINGS_VIEW as tf,TUTOR_VIEW as tg,claimSessionState as th,forgetSessionState as ti,getOtelConsumeUrl as tj,getStoredToken as tk,getStoredUser as tl,isRememberableRoute as tm,isShellNeutralRoute as tn,loadRefreshTokenFromCookie as to,navigationStore as tp,pageConfiguration as tq,profileStore as tr,registerSessionState as ts,storeToken as tt,storeUser as tu,useNavigationStore as tv,useProfile as tw,useProfileStore as tx,viewForRoute as ty,__spreadArray as tz,useNotebookStore$1 as u,vM as v,useSandboxService as w,useSignalValue$1 as x,datalayerCatalog as y,ChatBaseHeader as z};
|