@robota-sdk/agent-core 3.0.0-beta.81 → 3.0.0-beta.82

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.
@@ -7,7 +7,7 @@ import{a as e,c as t,i as n,n as r,o as i,r as a,s as o,t as s}from"./project-to
7
7
 
8
8
  `),n.beginAssistant();let b=Oo(),{wrappedOnTextDelta:x,wrappedOnProviderNativeRawPayload:S}=bo(a,n,i,p),C=Za(s,o.defaultModel.model,i),w=await xo(_,o,s,f,a,n,p,i,b,u,x,S,t=>void(e.providerFailure=t),C);if(w===null)return!0;let{assistantResponse:T,assistantToolCalls:E}=ao(w,i,a.conversationId,p,u);if(E.length>0&&(a.toolChoice??o.defaultModel?.toolChoice)===`none`)throw Error(`Provider returned tool calls despite toolChoice none; no tools were executed.`);await J(l,`afterProviderCall`,{messages:m,responseMessage:w},u),await J(l,`onMessageAdded`,{message:w},u);let ee=typeof T.content==`string`&&T.content.trim().length>0;if(E.length===0&&!ee)return u.warn(`[ROUND] Provider returned empty assistant response without tool calls`,{executionId:i,conversationId:a.conversationId,round:p}),n.discardPending(),!0;let te=ko(T),ne=te?.inputTokens??0;ne>0&&(e.cumulativeInputTokens=ne);for(let e of E)n.appendToolCall(e);let re=a.signal?.aborted?`interrupted`:`complete`;n.commitAssistant(re,{round:p,usageObservationId:b,executionId:i,providerId:Y(C,s),modelId:X(C,s.aiProviderInfo.model),...te??{}});let ie=n.getMessages().at(-1);if(a.onExecutionEvent?.(`assistant_message_committed`,{executionId:i,conversationId:a.conversationId,round:p,message:T}),ie&&a.onExecutionEvent?.(`history_mutation`,{executionId:i,conversationId:a.conversationId,round:p,mutation:`append_message`,index:n.getMessages().length-1,message:ie}),e.runningAssistantCount++,e.lastTrackedAssistantMessage=T,E.length===0)return u.debug(`[AGENT-FLOW-CONTROL] Round ${p} completed - no tool calls, execution finished for agent ${a.conversationId}`),d.emitAssistantMessageComplete(T,i,p,r,v,y),!0;let ae=await Eo(E,n,r,i,p,v,y,e,c,o,a.signal,a.onExecutionEvent,a.maxSameToolInputs??o.maxSameToolInputs,a.traceContext);if(ae.contextOverflowed&&u.warn(`[ROUND] Tool results partially skipped due to context overflow — continuing to let AI respond`,{added:ae.addedCount,skipped:ae.skippedCount,round:p}),ae.unknownToolFailureCount>0?e.consecutiveUnknownToolFailureRounds+=1:e.consecutiveUnknownToolFailureRounds=0,e.consecutiveUnknownToolFailureRounds>=2){let t=[...new Set(ae.unknownToolNames)].sort();return e.forcedSummaryInstruction=[`The model repeatedly requested unavailable tool(s): ${t.join(`, `)}.`,`Those tool calls were not executed because they are not registered tools.`,`Respond to the user now with that reason and use the available tool results already in the conversation history.`].join(` `),u.warn(`[ROUND] Stopping repeated unavailable tool-call loop`,{unavailableTools:t,consecutiveRounds:e.consecutiveUnknownToolFailureRounds,round:p}),!0}return u.debug(`Round ${p} completed for agent ${a.conversationId}`),!1}function jo(e,t){let n=t.maxExecutionRounds??e.maxExecutionRounds;if(n===void 0)return 10;if(!Number.isInteger(n)||n<0)throw Error(`[EXECUTION] maxExecutionRounds must be a non-negative integer`);return n}function Mo(e,t){return t===0||e<t}async function No(e,t,n,r,i,a,o,s,c){let l=jo(i,r);for(;Mo(o.currentRound,l)&&!(s?.aborted||(o.currentRound++,await Ao(o,l,e,t,n,r,i,a,c))||s?.aborted););let u=e.getMessages(),d=u.length>0?u[u.length-1]:void 0,f=d?.role===`assistant`&&typeof d.content==`string`&&d.content.length>0&&(!(`toolCalls`in d)||d.toolCalls.length===0);s?.aborted||r.allowToolOnlyCompletion!==!0&&(f||await go(e,a,i,n,o,t,r,c.logger,l))}async function Po(e,t,n,r,i,a,o,s,c,l,u){let d={...ja(t,n,r,i.toolsExecuted,i.providerFailure),interrupted:o};await J(c,`afterRun`,{input:e,response:d.response,metadata:s?.metadata},l);let f={messages:d.messages,executionContext:{executionId:n,conversationId:a},executionResult:{response:d.response,duration:d.duration,...d.tokensUsed===void 0?{}:{tokensUsed:d.tokensUsed},toolsExecuted:d.toolsExecuted.length,success:d.success,toolCalls:d.toolsExecuted.map(e=>({name:e}))}};for(let e of[`afterExecution`,`afterConversation`,`afterToolExecution`])await J(c,e,f,l);return l.debug(`Execution pipeline completed successfully`,{executionId:n,conversationId:a,duration:d.duration,tokensUsed:d.tokensUsed,toolsExecuted:d.toolsExecuted.length,rounds:i.currentRound}),u.emitExecution(M.COMPLETE,{result:{success:!0,data:d.response.substring(0,100)+`...`},metadata:{method:`execute`,success:!0,duration:d.duration,tokensUsed:d.tokensUsed,toolsExecuted:d.toolsExecuted}},a,n),d}async function*Fo(e,t,n,r,i){let a=[],o=null,s=!1,c=null,l={result:null},u=new AbortController,d=r?.signal,f=d?AbortSignal.any([d,u.signal]):u.signal,p=r?.onTextDelta,m=e=>{a.push(e),p?.(e),o?.()},h=i(e,t,n,{...r,signal:f,onTextDelta:m}).then(e=>{l.result=e},e=>{c=e}).finally(()=>{s=!0,o?.()});try{for(;;){for(;a.length>0;)yield a.shift();if(s)break;await new Promise(e=>{o=()=>{o=null,e()}})}if(c!==null)throw c;if(l.result===null)throw Error(`[EXECUTION] streaming turn settled without a result`);return l.result}finally{u.abort(),await h}}function Io(e,t){return{executionId:e,...t===void 0?{}:{driverId:t}}}var Lo=class{toolExecutionService;aiProviders;tools;conversationHistory;plugins=[];logger;eventEmitter;cacheService;constructor(e,t,n,r,i,a){if(this.toolExecutionService=new ba(t),this.aiProviders=e,this.tools=t,this.conversationHistory=n,this.plugins=[],this.logger=O(`ExecutionService`),!r)throw Error(`[EXECUTION] EventService is required`);this.eventEmitter=new ka(r,this.logger,i),this.cacheService=a}setAskHandler(e){this.toolExecutionService.setAskHandler(e)}invokeRuntimeTool(e,t,n){return this.toolExecutionService.executeTool(e,t,n,`registered`)}registerPlugin(e){let t=e.priority??0,n=this.plugins.findIndex(e=>(e.priority??0)<t);n===-1?this.plugins.push(e):this.plugins.splice(n,0,e),this.logger.debug(`Plugin registered`,{pluginName:e.name,priority:t})}removePlugin(e){let t=this.plugins.findIndex(t=>t.name===e);return t===-1?!1:(this.plugins.splice(t,1),this.logger.debug(`Plugin removed`,{pluginName:e}),!0)}getPlugin(e){return this.plugins.find(t=>t.name===e)}getPlugins(){return[...this.plugins]}async execute(e,t,n,r){let i=Ga(),a=new Date,o=Ka(r,`execute`),s=qa(t,n,a,i,o,r);this.eventEmitter.prepareOwnerPathBases(o),this.logger.debug(`Starting execution pipeline`,{executionId:i,conversationId:o,messageCount:t.length,hasContext:!!r});let c=Va(this.aiProviders,this.tools,n);this.eventEmitter.emitExecutionStartEvent(e,n,t,c,o,i);let l=Ua(this.conversationHistory,o,t,n,i);try{let t=l.getMessages().length;l.addUserMessage(e,Io(i,r?.driverId));let u=l.getMessages()[t];u&&s.onExecutionEvent?.(`history_mutation`,{executionId:i,conversationId:o,mutation:`append_message`,index:t,message:u}),this.eventEmitter.emitUserMessageEvent(e,o,i),await J(this.plugins,`beforeRun`,{input:e,...r?.metadata?{metadata:r.metadata}:{}},this.logger);let d={executionId:i,conversationId:o};u&&await J(this.plugins,`onMessageAdded`,{message:u,executionContext:d},this.logger),await J(this.plugins,`beforeExecution`,{messages:l.getMessages(),executionContext:d},this.logger),Ha(c);let f={toolsExecuted:[],currentRound:0,runningAssistantCount:0,lastTrackedAssistantMessage:void 0,cumulativeInputTokens:0,consecutiveUnknownToolFailureRounds:0,sameToolInputCounts:new Map};for(let e of l.getMessages())e.role===`assistant`&&(f.runningAssistantCount++,f.lastTrackedAssistantMessage=e);return await No(l,o,i,s,n,c,f,r?.signal,{toolExecutionService:this.toolExecutionService,plugins:this.plugins,logger:this.logger,eventEmitter:this.eventEmitter,cacheService:this.cacheService}),Po(e,l,i,a,f,o,r?.signal?.aborted??!1,r,this.plugins,this.logger,this.eventEmitter)}catch(e){return Ft(e,r?.signal)?{response:``,messages:l.getMessages(),executionId:i,duration:Date.now()-a.getTime(),toolsExecuted:[],success:!0,interrupted:!0}:(await Wa(e,s,a,o,i,this.plugins,this.logger,this.eventEmitter),{response:``,messages:[],tokensUsed:0,toolsExecuted:[],duration:Date.now()-a.getTime(),executionId:i,success:!1,error:e instanceof Error?e:Error(String(e))})}finally{this.eventEmitter.resetOwnerPathBases()}}async*executeStream(e,t,n,r){return yield*Fo(e,t,n,r,this.execute.bind(this))}async getStats(){return{pluginCount:this.plugins.length,pluginNames:this.plugins.map(e=>e.name),historyStats:this.conversationHistory.getStats()}}clearPlugins(){this.plugins=[],this.logger.debug(`All plugins cleared`)}};function Ro(e){let t=new Xi;if(e.aiProviders)for(let n of e.aiProviders)t.addProvider(n.name,n);return e.defaultModel&&t.setCurrentProvider(e.defaultModel.provider,e.defaultModel.model),t}async function zo(e){let{config:t,aiProviders:n,tools:r,agentFactory:i,conversationHistory:a,moduleRegistry:o,eventEmitter:s,eventService:c,logger:l}=e;if(l.debug(`Starting Robota initialization with independent managers`),await Promise.all([n.initialize(),r.initialize(),i.initialize()]),t.modules){for(let e of t.modules)await o.registerModule(e,{autoInitialize:!0,validateDependencies:!0});l.debug(`Modules registered and initialized`,{moduleCount:t.modules.length,moduleNames:t.modules.map(e=>e.name)})}if(t.tools)for(let e of t.tools)e instanceof Nt&&c&&e.setEventService(c),r.addTool(e.schema,async(t,n)=>{if(!n)throw Error(`[ROBOTA] Missing ToolExecutionContext for tool execution`);let r=await e.execute(t,n);return Kr(e.schema.name,r)}),l.debug(`Tool registered during initialization`,{toolName:e.schema.name});let u;t.cache?.enabled&&(u=new $i(new Qi({maxEntries:t.cache.maxEntries,ttlMs:t.cache.ttlMs}),new Zi));let d=new Lo(n,r,a,c,t.executionContext,u);if(t.ask&&d.setAskHandler(t.ask),t.plugins)for(let e of t.plugins)d.registerPlugin(e),e.subscribeToModuleEvents&&(await e.subscribeToModuleEvents(s),l.debug(`Plugin subscribed to module events`,{pluginName:e.name}));return l.debug(`Robota initialization completed successfully with independent managers`),d}async function Bo(e){try{let t=await zo(e.ctx);e.setExecutionService(t),e.setFullyInitialized(!0)}catch(t){throw e.ctx.logger.error(`Robota initialization failed`,{error:t instanceof Error?t.message:String(t)}),t}}function Vo(e){let t=e.isFullyInitialized?e.aiProviders.getProviderNames():[],n=e.isFullyInitialized?e.aiProviders.getCurrentProvider():null,r=n?n.provider:null,i=e.isFullyInitialized?e.tools.getTools().map(e=>e.name):[],a=e.getPluginNames(),o=e.getModuleNames(),s=e.getHistory(),c=Date.now()-e.startTime,l={user:0,assistant:0,system:0,tool:0};for(let e of s)e.role in l&&l[e.role]++;return{name:e.name,version:e.version,conversationId:e.conversationId,providers:t,currentProvider:r,tools:i,plugins:a,modules:o,historyLength:s.length,historyStats:{userMessages:l.user,assistantMessages:l.assistant,systemMessages:l.system,toolMessages:l.tool},uptime:c}}async function Ho(e){e.logger.debug(`Destroying Robota instance`,{name:e.name});let t=[],n=async(n,r)=>{try{await r(),e.logger.debug(n)}catch(r){let i=r instanceof Error?r:Error(String(r));t.push(i),e.logger.error(`Error during Robota destruction step`,{step:n,error:i.message})}};if(e.isFullyInitialized&&e.moduleRegistry&&await n(`All modules disposed`,()=>e.moduleRegistry.disposeAllModules()),e.executionService){let t=e.executionService.getPlugins();for(let e of t)await n(`Plugin disposed: ${e.name}`,()=>e.dispose());e.logger.debug(`ExecutionService plugins cleaned up`)}return e.moduleRegistry&&await n(`ModuleRegistry cleared`,()=>e.moduleRegistry.clearAllModules()),e.eventEmitter&&await n(`EventEmitter disposed`,()=>e.eventEmitter.dispose()),await n(`Tools disposed`,()=>e.tools.dispose()),await n(`AIProviders disposed`,()=>e.aiProviders.dispose()),e.resetState(),t.length===0?e.logger.info(`Robota instance destroyed successfully`,{name:e.name}):e.logger.warn(`Robota instance destroyed with cleanup failures`,{name:e.name,failureCount:t.length}),{errors:t}}var Uo=class{tail=Promise.resolve();async acquire(e){let t=this.tail,n=()=>{};if(this.tail=new Promise(e=>{n=e}),await t,e?.aborted)throw n(),Error(`Run aborted while queued behind another run on this instance`);return n}async run(e,t){let n=await this.acquire(e);try{return await t()}finally{n()}}get drained(){return this.tail}};function Wo(e){return{maxConcurrentAgents:e.maxConcurrentAgents||100,defaultSystemMessage:e.defaultSystemMessage??``,strictValidation:e.strictValidation??!0,idFactory:e.idFactory??Ko,...e.defaultModel!==void 0&&{defaultModel:e.defaultModel},...e.defaultProvider!==void 0&&{defaultProvider:e.defaultProvider}}}function Go(e,t){if(!e.aiProviders||e.aiProviders.length===0)throw new y(`At least one AI provider must be specified in aiProviders array`);let n=e.defaultModel,r=n?.model??t.defaultModel;if(!r)throw new y(`No model specified: set config.defaultModel.model or the AgentFactory defaultModel option`);let i=n?.provider??e.aiProviders[0]?.name??t.defaultProvider;if(!i)throw new y(`No provider specified: set config.defaultModel.provider, an aiProviders entry, or the AgentFactory defaultProvider option`);return{id:e.id||Ko(),name:e.name||`Unnamed Agent`,aiProviders:e.aiProviders,defaultModel:{provider:i,model:r,temperature:n?.temperature??.7,...n?.maxTokens!==void 0&&{maxTokens:n.maxTokens},...n?.topP!==void 0&&{topP:n.topP}},systemMessage:e.systemMessage??t.defaultSystemMessage,tools:e.tools||[],plugins:e.plugins||[],metadata:e.metadata||{},...e.logging&&{logging:e.logging},...e.conversationId&&{conversationId:e.conversationId},...e}}function Ko(){return`agent_${Date.now()}_${Math.random().toString(36).substring(2,8)}`}function qo(e,t){return e.totalCreated++,e.activeCount++,t?e.fromTemplates++:e.customConfigured++,e.templateUsageRatio=e.totalCreated>0?e.fromTemplates/e.totalCreated:0,e}var Jo=class{templates=new Map;logger;constructor(){this.logger=O(`AgentTemplates`),this.logger.info(`AgentTemplates initialized`)}registerTemplate(e){if(!e.id)throw Error(`Template must have an ID`);this.templates.has(e.id)&&this.logger.warn(`Template "${e.id}" is already registered, overriding`),this.templates.set(e.id,e),this.logger.info(`Template "${e.id}" registered successfully`,{templateId:e.id,category:e.category,tags:e.tags})}unregisterTemplate(e){let t=this.templates.delete(e);return t?this.logger.info(`Template "${e}" unregistered`):this.logger.warn(`Attempted to unregister non-existent template "${e}"`),t}getTemplates(){return Array.from(this.templates.values())}getTemplate(e){return this.templates.get(e)}findTemplates(e){return this.getTemplates().filter(t=>!(e.category&&t.category!==e.category||e.tags&&e.tags.length>0&&!e.tags.some(e=>t.tags?.includes(e))||e.provider&&t.config.defaultModel?.provider!==e.provider||e.model&&t.config.defaultModel?.model!==e.model))}applyTemplate(e,t={}){let n=[],r=!1,i={...e.config},a={...i,...t},o=e=>{e in t&&i[e]!==t[e]&&(r=!0,i[e]!==void 0&&n.push(`Override: ${e} changed from "${String(i[e])}" to "${String(t[e])}"`))};t.name!==void 0&&o(`name`),t.systemMessage!==void 0&&o(`systemMessage`);let s=a;return this.logger.debug(`Template applied`,{templateId:e.id,overridesCount:Object.keys(t).length,warningsCount:n.length,modified:r}),{config:s,template:e,warnings:n,modified:r}}hasTemplate(e){return this.templates.has(e)}getTemplateCount(){return this.templates.size}clearAll(){this.templates.clear(),this.logger.info(`All templates cleared`)}getStats(){let e=this.getTemplates(),t=[...new Set(e.map(e=>e.category).filter(e=>typeof e==`string`&&e.length>0))],n=[...new Set(e.flatMap(e=>e.tags||[]))],r=[...new Set(e.map(e=>e.config.defaultModel?.provider).filter(e=>typeof e==`string`&&e.length>0))],i=[...new Set(e.map(e=>e.config.defaultModel?.model).filter(e=>typeof e==`string`&&e.length>0))];return{totalTemplates:e.length,categories:t,tags:n,providers:r,models:i}}};function Yo(e){let t=e,n=typeof t.initialize==`function`?t.initialize:void 0,r=typeof t.cleanup==`function`?t.cleanup:void 0;if(n!==void 0||r!==void 0)return{...n?{initialize:()=>n.call(e)}:{},...r?{cleanup:()=>r.call(e)}:{}}}function Xo(e){return e instanceof Error&&`failedStep`in e&&`rollbackErrors`in e}async function Zo(e){let t=[];for(let n of e){try{await n.run()}catch(e){let r=[];for(let e of t.reverse())if(e.undo!==void 0)try{await e.undo()}catch(t){r.push({step:e.name,error:t})}throw Qo(e,n.name,r)}t.push(n)}}function Qo(e,t,n){let r=e instanceof Error?e:Error(String(e));return Object.assign(r,{failedStep:t,rollbackErrors:n})}var $o=class{agentTemplates;initialized=!1;logger;options;activeAgents;pendingAgents=new Set;creationStats;lifecycleEvents;constructor(e={},t={}){this.agentTemplates=new Jo,this.logger=O(`AgentFactory`),this.options=Wo(e),this.activeAgents=new Map,this.creationStats={totalCreated:0,activeCount:0,fromTemplates:0,customConfigured:0,templateUsageRatio:0},this.lifecycleEvents=t,this.logger.debug(`AgentFactory initialized`,{maxConcurrentAgents:this.options.maxConcurrentAgents,strictValidation:this.options.strictValidation,hasDefaultModel:!!this.options.defaultModel,hasDefaultProvider:!!this.options.defaultProvider,hasLifecycleEvents:this.lifecycleEvents!==null})}async initialize(){this.initialized||(this.logger.debug(`Initializing AgentFactory`),this.initialized=!0,this.logger.debug(`AgentFactory initialization completed`))}async createAgent(e,t,n=!1){let r,i=this.admit();try{r=Go(t,this.options);let a=r;if(this.options.strictValidation){let e=Lt(r);if(!e.isValid)throw new l(`Invalid agent configuration: ${e.errors.join(`, `)}`)}let o;if(await Zo([{name:`beforeCreate`,run:()=>this.lifecycleEvents.beforeCreate?.(a)},{name:`construct`,run:()=>{o=new e(a)}},{name:`initialize`,run:()=>o?Yo(o)?.initialize?.():void 0,undo:()=>o?Yo(o)?.cleanup?.():void 0},{name:`commit`,run:()=>{if(!o)throw new y(`Agent was not constructed`);this.activeAgents.set(i,o),qo(this.creationStats,n)},undo:()=>{this.activeAgents.delete(i),this.creationStats.activeCount--,this.creationStats.totalCreated--,n?this.creationStats.fromTemplates--:this.creationStats.customConfigured--}},{name:`afterCreate`,run:()=>o?this.lifecycleEvents.afterCreate?.(o,a):void 0}]),this.pendingAgents.delete(i),!o)throw new y(`Agent was not constructed`);return this.logger.info(`Agent created successfully`,{agentId:i,model:r.defaultModel.model,provider:r.defaultModel.provider}),o}catch(e){this.pendingAgents.delete(i);let n=e instanceof Error?e:Error(String(e));throw this.lifecycleEvents.onCreateError&&r&&await this.lifecycleEvents.onCreateError(n,r),this.logger.error(`Failed to create agent`,{error:n.message,model:t.defaultModel?.model,provider:t.defaultModel?.provider,hasTools:!!t.tools?.length}),n}}admit(){if(this.activeAgents.size+this.pendingAgents.size>=this.options.maxConcurrentAgents)throw new y(`Maximum concurrent agents limit reached: ${this.options.maxConcurrentAgents}`);let e=this.options.idFactory(),t=0;for(;this.activeAgents.has(e)||this.pendingAgents.has(e);){if(t+=1,t>16)throw new y(`Agent id factory keeps returning ids that are already in use`);e=this.options.idFactory()}return this.pendingAgents.add(e),e}async createFromTemplate(e,t,n={}){let r=this.agentTemplates.getTemplate(t);if(!r)throw new y(`Template not found: ${t}`);let i=this.applyTemplate(r,n);i.warnings.length>0&&this.logger.warn(`Template application warnings`,{templateId:t,warnings:i.warnings});let a=await this.createAgent(e,i.config,!0);return this.logger.info(`Agent created from template`,{templateId:t,modified:i.modified,warnings:i.warnings.length}),a}registerTemplate(e){this.agentTemplates.registerTemplate(e)}unregisterTemplate(e){return this.agentTemplates.unregisterTemplate(e)}getTemplates(){return this.agentTemplates.getTemplates()}getTemplate(e){return this.agentTemplates.getTemplate(e)}findTemplates(e){return this.agentTemplates.findTemplates(e)}applyTemplate(e,t={}){return this.agentTemplates.applyTemplate(e,t)}async destroyAgent(e){let t=this.activeAgents.get(e);if(!t)return!1;try{return await Yo(t)?.cleanup?.(),this.activeAgents.delete(e),this.creationStats.activeCount--,this.lifecycleEvents.onDestroy&&await this.lifecycleEvents.onDestroy(e),this.logger.info(`Agent destroyed`,{agentId:e}),!0}catch(t){throw this.logger.error(`Error destroying agent`,{agentId:e,error:t instanceof Error?t.message:String(t)}),t}}getCreationStats(){return{...this.creationStats}}getActiveAgents(){return new Map(this.activeAgents)}validateConfiguration(e){return Lt(e)}};function es(e,t,n){if(!e.name||e.name.trim()===``)throw new y(`Module name is required`);if(!e.version||e.version.trim()===``)throw new y(`Module version is required`);let r=e.getModuleType(),i=t.validateTypeDescriptor(r);if(!i.valid)throw new y(`Invalid module type: ${i.errors.join(`, `)}`,{moduleName:e.name,errors:i.errors});i.warnings.length>0&&n.warn(`Module type validation warnings`,{moduleName:e.name,warnings:i.warnings})}async function ts(e,t,n,r){let i=e.getModuleType();if(!i.dependencies||i.dependencies.length===0)return;for(let n of i.dependencies)if(!t.hasType(n))throw new y(`Module '${e.name}' depends on unregistered type '${n}'`,{moduleName:e.name,dependencyType:n});let a=new Set;for(let e of n.values())a.add(e.getModuleType().type);let o=[];for(let e of i.dependencies)a.has(e)||o.push(e);o.length>0&&r.warn(`Module has unmet dependencies`,{moduleName:e.name,missingDependencies:o})}function ns(e,t){let n=t.get(e);if(!n)return[];let r=n.getModuleType().type,i=[];for(let[n,a]of t.entries())n!==e&&a.getModuleType().dependencies?.includes(r)&&i.push(n);return i}function rs(e,t){let n={},r=0,i=0,a=0,o=0,s=0,c=0;for(let t of e.values()){let e=t.getModuleType().type;n[e]=(n[e]||0)+1,t.isInitialized()&&r++,t.isEnabled()&&i++}for(let e of t.values())a+=e.totalExecutions,o+=e.successfulExecutions,s+=e.failedExecutions,c+=e.totalExecutionTime;return{totalModules:e.size,initializedModules:r,enabledModules:i,modulesByType:n,totalExecutions:a,totalSuccessfulExecutions:o,totalFailedExecutions:s,averageExecutionTime:a>0?c/a:0}}function is(){return[{type:`storage`,category:`storage`,layer:`infrastructure`,capabilities:[`data-persistence`,`data-retrieval`]},{type:`memory-storage`,category:`storage`,layer:`infrastructure`,dependencies:[`storage`],capabilities:[`in-memory-storage`,`fast-access`]},{type:`file-storage`,category:`storage`,layer:`infrastructure`,dependencies:[`storage`],capabilities:[`persistent-storage`,`file-system-access`]},{type:`text-processing`,category:`processing`,layer:`application`,capabilities:[`text-analysis`,`content-transformation`]},{type:`file-processing`,category:`processing`,layer:`application`,dependencies:[`storage`],capabilities:[`file-parsing`,`content-extraction`]},{type:`api-integration`,category:`integration`,layer:`application`,capabilities:[`external-api-access`,`data-synchronization`]},{type:`database-integration`,category:`integration`,layer:`infrastructure`,dependencies:[`storage`],capabilities:[`database-access`,`query-execution`]},{type:`rag`,category:`capability`,layer:`domain`,dependencies:[`storage`,`text-processing`],capabilities:[`document-search`,`context-retrieval`,`semantic-search`]},{type:`speech-processing`,category:`capability`,layer:`domain`,capabilities:[`speech-to-text`,`text-to-speech`,`audio-processing`]},{type:`image-analysis`,category:`capability`,layer:`domain`,capabilities:[`image-recognition`,`visual-analysis`,`content-extraction`]}]}function as(e,t){let n=[],r=[];if((!e.type||e.type.trim()===``)&&n.push(`Module type is required and cannot be empty`),e.category||n.push(`Module category is required`),e.layer||n.push(`Module layer is required`),e.type&&!/^[a-zA-Z][a-zA-Z0-9-_]*$/.test(e.type)&&n.push(`Module type must start with a letter and contain only letters, numbers, hyphens, and underscores`),e.dependencies){for(let t of e.dependencies)(!t||t.trim()===``)&&n.push(`Dependencies cannot be empty`);e.dependencies.includes(e.type)&&n.push(`Module cannot depend on itself`)}if(e.capabilities)for(let t of e.capabilities)(!t||t.trim()===``)&&n.push(`Capabilities cannot be empty`);if(e.dependencies){let n=[`infrastructure`,`core`,`application`,`domain`,`presentation`],i=n.indexOf(e.layer);for(let a of e.dependencies){let o=t(a);o&&n.indexOf(o.layer)>i&&r.push(`Module '${e.type}' (${e.layer}) depends on '${a}' (${o.layer}) which is in a higher layer`)}}return{valid:n.length===0,errors:n,warnings:r}}function os(e,t,n){let r=new Set,i=new Set,a=[],o=[],s=[];for(let r of e){let e=t(r);if(!e){s.push(r);continue}if(e.dependencies)for(let t of e.dependencies)!n(t)&&!s.includes(t)&&s.push(t)}let c=(s,l=[])=>{if(i.has(s)){let e=l.indexOf(s);o.push(l.slice(e).concat([s]));return}if(r.has(s))return;let u=t(s);if(!u)return;i.add(s);let d=[...l,s];if(u.dependencies)for(let t of u.dependencies)(e.includes(t)||n(t))&&c(t,d);i.delete(s),r.add(s),a.push(s)};for(let t of e)r.has(t)||c(t);return{resolved:s.length===0&&o.length===0,order:a,circularDependencies:o,missingDependencies:s}}function ss(e,t){let n=[],r=[],i=new Map;for(let n of e){let e=t(n);e&&(i.has(e.layer)||i.set(e.layer,[]),i.get(e.layer).push(n))}let a=new Map;for(let n of e){let e=t(n);if(e?.capabilities)for(let t of e.capabilities)a.has(t)||a.set(t,[]),a.get(t).push(n)}for(let[e,t]of Array.from(a.entries()))if(t.length>1)for(let r=0;r<t.length;r++)for(let i=r+1;i<t.length;i++){let a=t[r],o=t[i];a&&o&&n.push({module1:a,module2:o,reason:`Both modules provide capability '${e}'`})}return n.length>0&&(r.push(`Consider using only one module per capability`),r.push(`Check if modules can be configured to avoid conflicts`)),!i.has(`infrastructure`)&&e.length>1&&r.push(`Consider adding infrastructure modules for better foundation`),{compatible:n.length===0,conflicts:n,suggestions:r}}function cs(e){let t={core:0,storage:0,processing:0,integration:0,interface:0,capability:0},n={infrastructure:0,core:0,application:0,domain:0,presentation:0},r=0,i=0;for(let a of e.values())t[a.category]++,n[a.layer]++,a.dependencies&&a.dependencies.length>0&&r++,a.capabilities&&a.capabilities.length>0&&i++;return{totalTypes:e.size,typesByCategory:t,typesByLayer:n,typesWithDependencies:r,typesWithCapabilities:i}}var ls=class{registeredTypes=new Map;logger;constructor(){this.logger=O(`ModuleDescriptorRegistry`),this.registerBuiltinTypes()}registerType(e){let t=this.validateTypeDescriptor(e);if(!t.valid)throw new y(`Invalid module type descriptor: ${t.errors.join(`, `)}`,{type:e.type,errors:t.errors});if(this.registeredTypes.has(e.type)){let t=this.registeredTypes.get(e.type);this.logger.warn(`Overriding existing module type`,{type:e.type,previousCategory:t?.category||`unknown`,newCategory:e.category})}this.registeredTypes.set(e.type,e),this.logger.info(`Module type registered`,{type:e.type,category:e.category,layer:e.layer,dependencies:e.dependencies?.length||0,capabilities:e.capabilities?.length||0})}unregisterType(e){if(!this.registeredTypes.has(e))return!1;let t=this.findDependentTypes(e);if(t.length>0)throw new y(`Cannot unregister module type '${e}' - it is required by: ${t.join(`, `)}`,{type:e,dependentTypes:t});return this.registeredTypes.delete(e),this.logger.info(`Module type unregistered`,{type:e}),!0}getType(e){return this.registeredTypes.get(e)}getAllTypes(){return Array.from(this.registeredTypes.values())}getTypesByCategory(e){return Array.from(this.registeredTypes.values()).filter(t=>t.category===e)}getTypesByLayer(e){return Array.from(this.registeredTypes.values()).filter(t=>t.layer===e)}hasType(e){return this.registeredTypes.has(e)}validateTypeDescriptor(e){return as(e,e=>this.getType(e))}resolveDependencies(e){return os(e,e=>this.getType(e),e=>this.hasType(e))}checkCompatibility(e){return ss(e,e=>this.getType(e))}findDependentTypes(e){let t=[];for(let[n,r]of this.registeredTypes)r.dependencies?.includes(e)&&t.push(n);return t}registerBuiltinTypes(){for(let e of is())this.registerType(e);this.logger.info(`Built-in module types registered`,{totalTypes:this.registeredTypes.size})}clearAllTypes(){this.registeredTypes.clear(),this.logger.info(`All module types cleared`)}getStats(){return cs(this.registeredTypes)}};const us={REGISTERED:`module.registered`,UNREGISTERED:`module.unregistered`};var ds=class{modules=new Map;moduleOptions=new Map;moduleStatuses=new Map;moduleStats=new Map;registrationOrder=[];initializationOrder=[];typeRegistry;eventEmitter;logger;isDisposing=!1;constructor(e,t){this.eventEmitter=e,this.typeRegistry=t??new ls,this.logger=O(`ModuleRegistry`)}async registerModule(e,t={}){if(this.isDisposing)throw new y(`Cannot register modules during disposal`);if(es(e,this.typeRegistry,this.logger),this.modules.has(e.name))throw new y(`Module with name '${e.name}' is already registered`,{moduleName:e.name});t.validateDependencies!==!1&&await ts(e,this.typeRegistry,this.modules,this.logger),this.modules.set(e.name,e),this.moduleOptions.set(e.name,t.initOptions||{}),this.registrationOrder.push(e.name);let n=e.getModuleType();this.moduleStatuses.set(e.name,{name:e.name,type:n.type,enabled:e.isEnabled(),initialized:!1,hasEventEmitter:!!this.eventEmitter,registrationTime:new Date,dependencies:n.dependencies||[],dependents:[]}),this.moduleStats.set(e.name,{totalExecutions:0,successfulExecutions:0,failedExecutions:0,averageExecutionTime:0,totalExecutionTime:0}),t.autoInitialize&&await this.initializeModule(e.name,t.initTimeout),this.eventEmitter&&await this.eventEmitter.emit(us.REGISTERED,{data:{moduleName:e.name,moduleType:n.type},timestamp:new Date})}async unregisterModule(e){let t=this.modules.get(e);if(!t)return!1;let n=ns(e,this.modules);if(n.length>0)throw new y(`Cannot unregister module '${e}' - it is required by: ${n.join(`, `)}`,{moduleName:e,dependents:n});t.isInitialized()&&t.dispose&&await t.dispose(),this.modules.delete(e),this.moduleOptions.delete(e),this.moduleStatuses.delete(e),this.moduleStats.delete(e);let r=this.registrationOrder.indexOf(e);r!==-1&&this.registrationOrder.splice(r,1);let i=this.initializationOrder.indexOf(e);return i!==-1&&this.initializationOrder.splice(i,1),this.eventEmitter&&await this.eventEmitter.emit(us.UNREGISTERED,{data:{moduleName:e},timestamp:new Date}),!0}async initializeModule(e,t){let n=this.modules.get(e);if(!n)throw new y(`Module '${e}' not found`);if(n.isInitialized())return;let r=this.moduleOptions.get(e),i=n.initialize(r,this.eventEmitter);if(t&&t>0){let n,r=new Promise((r,i)=>{n=setTimeout(()=>{i(Error(`Module '${e}' initialization timed out after ${t}ms`))},t)});await Promise.race([i.then(e=>(clearTimeout(n),e)),r])}else await i;let a=this.moduleStatuses.get(e);a&&(a.initialized=!0,a.initializationTime=new Date),this.initializationOrder.includes(e)||this.initializationOrder.push(e)}async initializeAllModules(e){let t=Array.from(this.modules.keys());if(t.length===0)return;let n=t.map(e=>this.modules.get(e).getModuleType().type),r=this.typeRegistry.resolveDependencies(n);if(!r.resolved){let e=[];throw r.missingDependencies.length>0&&e.push(`Missing dependencies: ${r.missingDependencies.join(`, `)}`),r.circularDependencies.length>0&&e.push(`Circular dependencies: ${r.circularDependencies.map(e=>e.join(` -> `)).join(`; `)}`),new y(`Cannot initialize modules: ${e.join(`; `)}`,{missingDependencies:r.missingDependencies,circularDependencies:r.circularDependencies.map(e=>e.join(` -> `))})}for(let n of r.order){let r=t.find(e=>this.modules.get(e).getModuleType().type===n);r&&await this.initializeModule(r,e)}}async executeModule(e,t){let n=this.modules.get(e);if(!n)throw new y(`Module '${e}' not found`);if(!n.isInitialized())throw new y(`Module '${e}' is not initialized`);if(!n.isEnabled())throw new y(`Module '${e}' is disabled`);let r=this.moduleStats.get(e),i=Date.now();try{if(!n.execute)throw new y(`Module '${e}' does not support execute()`);let a=await n.execute(t),o=Date.now()-i;r.totalExecutions++,r.successfulExecutions++,r.totalExecutionTime+=o,r.averageExecutionTime=r.totalExecutionTime/r.totalExecutions,r.lastExecutionTime=new Date;let s=this.moduleStatuses.get(e);return s&&(s.lastActivity=new Date),a}catch(e){let t=Date.now()-i;throw r.totalExecutions++,r.failedExecutions++,r.totalExecutionTime+=t,r.averageExecutionTime=r.totalExecutionTime/r.totalExecutions,r.lastExecutionTime=new Date,e}}getModule(e){return this.modules.get(e)}getModulesByType(e){return Array.from(this.modules.values()).filter(t=>t.getModuleType().type===e)}getAllModules(){return Array.from(this.modules.values())}getModuleNames(){return Array.from(this.modules.keys())}hasModule(e){return this.modules.has(e)}getModuleStatus(e){return this.moduleStatuses.get(e)}getAllModuleStatuses(){return Array.from(this.moduleStatuses.values())}getModuleStats(e){return this.moduleStats.get(e)}getAllModuleStats(){let e={};for(let[t,n]of this.moduleStats.entries())e[t]={...n};return e}async disposeAllModules(){this.isDisposing=!0;let e=[...this.initializationOrder].reverse();for(let t of e){let e=this.modules.get(t);if(e&&e.isInitialized())try{e.dispose&&await e.dispose();let n=this.moduleStatuses.get(t);n&&(n.initialized=!1)}catch(e){this.logger.error(`Failed to dispose module`,{name:t,error:e instanceof Error?e.message:String(e)})}}this.initializationOrder=[],this.isDisposing=!1}clearAllModules(){this.modules.clear(),this.moduleOptions.clear(),this.moduleStatuses.clear(),this.moduleStats.clear(),this.registrationOrder=[],this.initializationOrder=[],this.isDisposing=!1}getRegistryStats(){return rs(this.modules,this.moduleStats)}},fs=class extends Gr{version=`1.0.0`;aiProviders;tools;agentFactory;conversationHistory;moduleRegistry;eventEmitter;executionService;eventService;agentEventService;conversationId;logger;initializationPromise;destroyed=!1;isFullyInitialized=!1;startTime;configVersion=1;configUpdatedAt=Date.now();configManager;constructor(e){super(),this.config=e,this.conversationId=Ci(e);let t=e.logging?.enabled===!1?`silent`:e.logging?.level;this.logger=O(`Robota`,t?{level:t}:{}),this.startTime=Date.now(),qr(e),this.aiProviders=Ro(e),this.tools=wi(()=>this.config),this.agentFactory=new $o,this.conversationHistory=new Qn,this.eventEmitter=Pi(),this.moduleRegistry=new ds(this.eventEmitter),this.eventService=e.eventService||Tr,this.agentEventService=q(this.eventService,{ownerType:`agent`,ownerId:this.conversationId,ownerPath:Fi(this.conversationId,this.config.executionContext)});let n=Di({getName:()=>this.name,getModuleRegistry:()=>this.moduleRegistry,getLogger:()=>this.logger,getIsFullyInitialized:()=>this.isFullyInitialized,ensureFullyInitialized:()=>this.ensureFullyInitialized(),getExecutionService:()=>this.executionService,getAiProviders:()=>this.aiProviders,getTools:()=>this.tools,getEventService:()=>this.eventService,getConfig:()=>this.config,setConfig:e=>{this.config=e},getConfigVersion:()=>this.configVersion,incrementConfigVersion:()=>++this.configVersion,getConfigUpdatedAt:()=>this.configUpdatedAt,setConfigUpdatedAt:e=>{this.configUpdatedAt=e},emitAgentEvent:(e,t)=>this.emitAgentEvent(e,t)});this.moduleManager=n.moduleManager,this.pluginManager=n.pluginManager,this.configManager=n.configManager,Mi(this.config,(e,t)=>this.emitAgentEvent(e,t))}async ensureReady(){await this.ensureFullyInitialized()}async listRuntimeTools(){return await this.ensureReady(),this.tools.getTools()}async invokeRuntimeTool(e,t,n){await this.ensureReady();let r=[...Fi(this.conversationId,this.config.executionContext),{type:`tool`,id:n.executionId??e}];return this.executionService.invokeRuntimeTool(e,t,{...n,baseEventService:this.eventService,eventService:q(this.eventService,{ownerPath:r,ownerType:`tool`,ownerId:n.executionId??e}),ownerPath:r,ownerType:`tool`,ownerId:n.executionId})}async run(e,t={}){return this.assertNotDestroyed(),this.runQueue.run(t.signal,async()=>{await this.ensureFullyInitialized();try{if(t.output){let n=wn(t.output);return await Vi(this.executionDeps(),e,t,n)}return await Li(this.executionDeps(),e,t)}finally{this.resetEphemeralHistory()}})}async*runStream(e,t={}){this.assertNotDestroyed();let n=await this.runQueue.acquire(t.signal);try{if(await this.ensureFullyInitialized(),t.output){let n=wn(t.output);return yield*Hi(this.executionDeps(),e,t,n)}return yield*Ri(this.executionDeps(),e,t)}finally{this.resetEphemeralHistory(),n()}}resetEphemeralHistory(){this.config.retainHistory===!1&&this.clearHistory()}runQueue=new Uo;executionDeps(){return{conversationId:this.conversationId,config:this.config,logger:this.logger,getHistory:()=>this.getHistory(),getExecutionService:()=>this.executionService,emitAgentEvent:(e,t)=>this.emitAgentEvent(e,t)}}getHistory(){return Wi(this.conversationHistory,this.conversationId)}getFullHistory(){return Gi(this.conversationHistory,this.conversationId)}addHistoryEntry(e){Ki(this.conversationHistory,this.conversationId,e)}clearHistory(){qi(this.conversationHistory,this.conversationId)}injectMessage(e,t,n){Ji(this.conversationHistory,this.conversationId,e,t,n)}injectRawMessage(e){Yi(this.conversationHistory,this.conversationId,e)}async updateTools(e){return this.configManager.updateTools(e)}async updateConfiguration(e){return this.configManager.updateConfiguration(e)}async getConfiguration(){return this.configManager.getConfiguration()}setModel(e){this.configManager.setModel(e)}getModel(){return this.configManager.getModel()}updateSystemPrompt(e){this.configManager.setSystemMessage(e),this.conversationHistory.getConversationStore(this.conversationId).setSystemPrompt(e)}getSystemPrompt(){return this.configManager.getSystemMessage()}registerTool(e){this.configManager.registerTool(e,this.tools)}unregisterTool(e){this.tools.removeTool(e)}getOfferedToolSchemas(){return this.tools.getOfferedTools()}getConfig(){return{...this.config}}swapDefaultProvider(e,t){this.aiProviders.addProvider(e.name,e),this.configManager.setModel({provider:e.name,model:t})}getStats(){return Vo({name:this.name,version:this.version,conversationId:this.conversationId,startTime:this.startTime,isFullyInitialized:this.isFullyInitialized,aiProviders:this.aiProviders,tools:this.tools,getPluginNames:()=>this.getPluginNames(),getModuleNames:()=>this.getModuleNames(),getHistory:()=>this.getHistory()})}async destroy(){return this.destroyed?{errors:[]}:(this.destroyed=!0,await this.runQueue.drained,Ho({name:this.name,isFullyInitialized:this.isFullyInitialized,moduleRegistry:this.moduleRegistry,eventEmitter:this.eventEmitter,executionService:this.executionService,tools:this.tools,aiProviders:this.aiProviders,logger:this.logger,resetState:()=>{this.isFullyInitialized=!1,this.initializationPromise=void 0}}))}assertNotDestroyed(){if(this.destroyed)throw Error(`[LIFECYCLE] Agent "${this.name}" has been destroyed — create a new instance`)}async initialize(){await this.ensureFullyInitialized()}async ensureFullyInitialized(){this.assertNotDestroyed(),!this.isFullyInitialized&&(this.initializationPromise||=this.doAsyncInit().catch(e=>{throw this.initializationPromise=void 0,e}),await this.initializationPromise)}doAsyncInit(){return Bo({ctx:{config:this.config,aiProviders:this.aiProviders,tools:this.tools,agentFactory:this.agentFactory,conversationHistory:this.conversationHistory,moduleRegistry:this.moduleRegistry,eventEmitter:this.eventEmitter,eventService:this.eventService,logger:this.logger},setExecutionService:e=>{this.executionService=e},setFullyInitialized:e=>{this.isFullyInitialized=e}})}emitAgentEvent(e,t){Ni(this.agentEventService,this.conversationId,this.config.executionContext,e,t)}};const ps=1e4,ms=25e3,hs=5e5,gs=/^tool-result:[A-Za-z0-9_-]{22,64}$/u,_s=Symbol.for(`@robota-sdk/tool-result-admitted`);var vs=class extends Error{code;constructor(e){super(`Tool result admission failed (${e})`),this.code=e,this.name=`ToolResultAdmissionError`}};function ys(e){return Object.getOwnPropertyDescriptor(e,_s)?.value===!0}function bs(e){return Object.defineProperty({...e},_s,{value:!0})}function xs(e){if(e.success)return typeof e.data==`string`?e.data:JSON.stringify(e.data)??``;let t=e.data===void 0?``:typeof e.data==`string`?e.data:JSON.stringify(e.data)??``;return`${e.error??``}${t}`}function Ss(e){return Number.isSafeInteger(e)&&e>0}function Cs(e,t){let n=e.warningChars??1e4,r=e.hardChars??25e3,i=e.repositoryMaxChars??5e5;if(!Ss(n)||!Ss(r)||!Ss(i)||n>=r||r>i||i>5e5)throw new vs(`invalid-policy`);if(t===void 0)return{warningChars:n,hardChars:r};if(!Ss(t))throw new vs(`invalid-override`);return{warningChars:n,hardChars:Math.max(r,Math.min(t,i))}}async function ws(e,t,n={},r){let{warningChars:i,hardChars:a}=Cs(n,r),o=xs(t),s=o.length;if(s>i&&n.onWarning?.({toolName:e,resultChars:s,warningChars:i}),s>a){if(!n.spillStore)throw new vs(`spill-unavailable`);let e;try{e=(await n.spillStore.write(o)).reference}catch{throw new vs(`spill-write-failed`)}if(!gs.test(e)||e.length>a)throw new vs(`invalid-reference`);return bs(t.success?{success:!0,data:e}:{success:!1,error:`Tool failure details: ${e}`})}return bs(t)}var Ts=class{store;listener;sequenceId=0;constructor(e,t){this.store=e,this.listener=(e,t,n)=>{if(!n?.ownerPath?.length)throw Error(`[HISTORY-MODULE] Missing ownerPath for ${e}`);let r={eventName:e,sequenceId:this.nextSequenceId(),timestamp:t.timestamp,eventData:t,context:n};this.store.append(r)},t.subscribe(this.listener)}append(e){this.store.append(e)}read(e,t){return this.store.read(e,t)}readStream(e,t){return this.store.readStream(e,t)}getSnapshot(){return this.store.getSnapshot?.()}detach(e){e.unsubscribe(this.listener)}nextSequenceId(){return this.sequenceId+=1,this.sequenceId}};const Es={STARTED:`started`,STEP_STARTED:`step_started`,STEP_COMPLETED:`step_completed`,COMPLETED:`completed`,FAILED:`failed`},Ds=`orchestration`;function Z(e){if(!(!e||typeof e!=`object`||Array.isArray(e)||e instanceof Date))return e}function Os(e){return typeof e==`string`?e.length:0}var ks=class{config;methodConfigs=new Map;constructor(e){this.config=e}configureMethod(e,t){return this.methodConfigs.set(e,t),this}configureStandardMethods(){return this.config.sourceType===`agent`&&(this.configureMethod(`run`,{startEvent:A.EXECUTION_START,completeEvent:A.EXECUTION_COMPLETE,errorEvent:A.EXECUTION_ERROR,extractMetadata:(e,t,n)=>({inputLength:Os(n[0]),conversationId:e.conversationId,options:Z(n[1])||{}}),extractResult:e=>({response:e})}),this.configureMethod(`runStream`,{startEvent:A.EXECUTION_START,completeEvent:A.EXECUTION_COMPLETE,errorEvent:A.EXECUTION_ERROR,extractMetadata:(e,t,n)=>({inputLength:Os(n[0]),conversationId:e.conversationId,streaming:!0,options:Z(n[1])||{}})})),this.config.sourceType===`tool`&&this.configureMethod(`execute`,{startEvent:P.CALL_START,completeEvent:P.CALL_COMPLETE,errorEvent:P.CALL_ERROR,extractMetadata:(e,t,n)=>({toolName:Z(e.schema)?.name||e.constructor.name,parameters:n[0],parametersCount:Z(n[0])?Object.keys(Z(n[0])||{}).length:0,context:n[1]}),extractResult:e=>({result:typeof Z(e)?.data==`string`?Z(e)?.data||``:JSON.stringify(Z(e)?.data),success:Z(e)?.success})}),this}wrap(e){return new Proxy(e,{get:(e,t,n)=>{let r=Reflect.get(e,t,n);if(typeof t!=`string`)return r;let i=t;if(typeof r==`function`&&this.methodConfigs.has(i)){let t=this.methodConfigs.get(i);return async(...n)=>{let a=Date.now(),o=this.generateExecutionId(),s=e;try{if(t.startEvent){let e=t.extractMetadata?.(s,i,n)||{};this.emitEvent(t.startEvent,{timestamp:new Date,metadata:{...e,executionId:o,methodName:i,phase:`start`}})}let c=await r.apply(e,n),l=Date.now()-a;if(t.completeEvent){let e=t.extractResult?.(c)||{},r=t.extractMetadata?.(s,i,n)||{};this.emitEvent(t.completeEvent,{timestamp:new Date,...e,metadata:{...r,executionId:o,methodName:i,duration:l,phase:`complete`,success:!0}})}return c}catch(e){let r=Date.now()-a;if(t.errorEvent){let a=t.extractMetadata?.(s,i,n)||{};this.emitEvent(t.errorEvent,{timestamp:new Date,error:e instanceof Error?e.message:String(e),metadata:{...a,executionId:o,methodName:i,duration:r,phase:`error`,errorName:e instanceof Error?e.name:`UnknownError`,success:!1}})}throw e}}}return r}})}emitEvent(e,t){let n={emitterSourceType:this.config.sourceType,emitterSourceId:this.config.sourceId},r={timestamp:new Date,...t.metadata?{metadata:{...n,...t.metadata}}:{metadata:n},...t};this.config.eventService.emit(e,r)}generateExecutionId(){return`${this.config.sourceType}-${this.config.sourceId}-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}};function As(e,t){let n=new ks(t);return n.configureStandardMethods(),n.wrap(e)}function js(e,t,n){return function(r){return As(r,{eventService:e,sourceType:t,sourceId:n})}}const Ms={safe:`plan`,moderate:`default`,full:`acceptEdits`},Ns=`inherit-allowlist`;function Ps(e){let t;for(let n=0;n<e.length;n+=1){let r=e[n];if(t===`'`){r===`'`&&(t=void 0);continue}if(r===`\\`){n+=1;continue}let i=e[n+1];if(r==="`"||r===`$`&&i===`(`)return!0;if(t===`"`){r===`"`&&(t=void 0);continue}if(r===`'`||r===`"`){t=r;continue}if(r===`;`||r===`|`||r===`
9
9
  `||(r===`<`||r===`>`)&&i===`(`)return!0;if(r===`&`){let t=e[n-1];if(t!==`>`&&t!==`<`&&i!==`>`)return!0}}return!1}function Fs(e){let t={segments:[],current:``,quote:void 0,substitutionDepth:0};for(let n=0;n<e.length;n+=1){let r=Ls(t,e,n);if(r!==void 0){n=r;continue}let i=Rs(t,e,n);if(i!==void 0){n=i;continue}if(zs(t,e[n]))continue;let a=Bs(t,e,n);if(a!==void 0){n=a;continue}t.current+=e[n]}return Is(t),t.segments}function Is(e){let t=e.current.trim();t!==``&&e.segments.push(t),e.current=``}function Ls(e,t,n){let r=t[n];if(e.quote===`'`)return e.current+=r,r===`'`&&(e.quote=void 0),n;if(r===`\\`){let i=t[n+1];return e.current+=i===void 0?r:r+i,n+1}}function Rs(e,t,n){let r=t[n];if(r==="`")return Is(e),n;if(r===`$`&&t[n+1]===`(`)return Is(e),e.substitutionDepth+=1,n+1}function zs(e,t){return e.quote===`"`?(e.current+=t,t===`"`&&(e.quote=void 0),!0):t===`'`||t===`"`?(e.quote=t,e.current+=t,!0):!1}function Bs(e,t,n){let r=t[n];if((r===`<`||r===`>`)&&t[n+1]===`(`)return Is(e),e.substitutionDepth+=1,n+1;if(r===`)`&&e.substitutionDepth>0)return Is(e),--e.substitutionDepth,n;if(r===`;`||r===`|`||r===`
10
- `||r===`&`&&Vs(t,n))return Is(e),n}function Vs(e,t){let n=e[t-1];return n!==`>`&&n!==`<`&&e[t+1]!==`>`}const Hs=/[.+^${}()|[\]\\]/g;function Us(e){let t=e.replace(Hs,`\\$&`).replace(/\*\*/g,`.+`).replace(/\*/g,`.*`);return RegExp(`^${t}$`)}function Ws(e,t,n){let r=Us(e);return n===`deny`?r.test(t)||Fs(t).some(e=>r.test(e))?`match`:`no-match`:r.test(t)?e.includes(`*`)&&Ps(t)?`no-match`:`match`:`no-match`}function Gs(e){let t=e.replace(/\*\*(?:\/\*\*)+/g,`**`).split(/(\/\*\*\/|\/\*\*$|^\*\*\/|\*\*)/).map(e=>e===`/**/`?`(?:/.*)?/`:e===`/**`?`(?:/.*)?`:e===`**/`?`(?:.*/)?`:e===`**`?`.*`:e.replace(Hs,`\\$&`).replace(/\*/g,`[^/]*`).replace(/\uE000/g,`\\*`)).join(``);return RegExp(`^${t}$`)}function Ks(e){return e.startsWith(`/`)||/^[A-Za-z]:(?=\/|$)/.test(e)}function qs(e){let t=e.replace(/\\/g,`/`),n=t.startsWith(`/`),r=[];for(let e of t.split(`/`))if(e!==``&&e!==`.`){if(e===`..`){r.length>0&&r[r.length-1]!==`..`?r.pop():n||r.push(`..`);continue}r.push(e)}let i=(n?`/`:``)+r.join(`/`);return(i===``?`.`:i).replace(/^[A-Za-z]:(?=\/|$)/,e=>e.toLowerCase())}function Js(e,t){let n=qs(e),r=qs(t);return Ks(n)&&!Ks(r)?`unevaluable`:Gs(n).test(r)?`match`:`no-match`}const Ys=/^(\*|[a-z][a-z0-9+.-]*):\/\/(\[[0-9a-fA-F:.]+\]|[^/\\:?#@[\]]+)(?::(\d+|\*))?(\/[^?#]*)?$/i,Xs=new Set([`http`,`https`,`ws`,`wss`,`ftp`]),Zs={http:`80`,https:`443`,ws:`80`,wss:`443`,ftp:`21`};function Qs(e){return e.replace(/\.$/,``).toLowerCase()}function $s(e){try{let t=new URL(`http://${e}/`).hostname;return t===``||t.includes(`.`)?null:t}catch{return null}}function ec(e){let t=Qs(e).replace(/\*\*(?:\.\*\*)+/g,`**`).split(`.`),n=[],r=`[^.]+(?:\\.[^.]+)*`;for(let[e,i]of t.entries()){let a=e===0,o=e===t.length-1;if(i===`**`){a&&o?n.push(r):o?n.push(`(?:\\.${r})?`):n.push(`${a?``:`\\.`}(?:${r}\\.)?`);continue}let s=!a&&t[e-1]===`**`,c=a||s?``:`\\.`;if(i===`*`)n.push(`${c}${r}`);else if(i.includes(`**`))return null;else if(i.includes(`*`))n.push(`${c}${i.replace(Hs,`\\$&`).replace(/\*/g,`[^.]*`)}`);else{let e=$s(i);if(e===null)return null;n.push(`${c}${e.replace(Hs,`\\$&`)}`)}}return RegExp(`^${n.join(``)}$`)}function tc(e){try{let t=e.split(`/`).map(e=>decodeURIComponent(e));return t.some(e=>e.includes(`/`))?null:t.join(`/`)}catch{return null}}function nc(e){let t;try{t=new URL(e)}catch{return null}let n=t.protocol.slice(0,-1).toLowerCase();return!Xs.has(n)||t.hostname===``||t.username!==``||t.password!==``?null:t}function rc(e,t){if(e.includes(`*`)){let n=ec(e);return n===null?`unevaluable`:n.test(t)?`match`:`no-match`}let n;try{n=new URL(`http://${e}/`).hostname}catch{return`unevaluable`}return Qs(n)===t?`match`:`no-match`}function ic(e,t,n){return e===void 0?t.port===``:e===`*`||e===(t.port===``?Zs[n]:t.port)}function ac(e,t){let n=tc(t),r=tc(e.replace(/%2a/gi,``));return n===null||r===null?`unevaluable`:Gs(r).test(n)?`match`:`no-match`}function oc(e,t){let n=Ys.exec(e);if(n===null)return`unevaluable`;let[,r,i,a,o]=n,s=nc(t);if(s===null)return`unevaluable`;let c=s.protocol.slice(0,-1).toLowerCase();if(r!==`*`&&r.toLowerCase()!==c)return`no-match`;let l=rc(i,Qs(s.hostname));return l===`match`?ic(a,s,c)?o===void 0?`match`:ac(o,s.pathname):`no-match`:l}const sc={plan:{inspect:`auto`,modify:`deny`,execute:`deny`},default:{inspect:`auto`,modify:`approve`,execute:`approve`},acceptEdits:{inspect:`auto`,modify:`auto`,execute:`approve`},bypassPermissions:{inspect:`auto`,modify:`auto`,execute:`auto`},auto:{inspect:`auto`,modify:`auto`,execute:`approve`}},cc={plan:`deny`,default:`approve`,acceptEdits:`approve`,bypassPermissions:`auto`,auto:`approve`},lc=[`.git`,`.robota`,`.claude`,`.agents`],uc=[`.mcp.json`,`.gitconfig`,`.npmrc`,`.bashrc`,`.bash_profile`,`.bash_login`,`.zshrc`,`.zshenv`,`.zprofile`,`.profile`];function dc(e){return e.replace(/\\/g,`/`).split(`/`).filter(e=>e!==``&&e!==`.`)}function fc(e){let t=[];for(let n of dc(e))n===`..`&&t.length>0&&t[t.length-1]!==`..`?t.pop():t.push(n);return t}function pc(e){let t=fc(e),n=t[t.length-1];if(n!==void 0&&uc.includes(n))return!0;for(let e=0;e<t.length;e+=1){let n=t[e];if(lc.includes(n)){if((n===`.robota`||n===`.claude`)&&t[e+1]===`worktrees`&&t[e+2]!==void 0){e+=2;continue}return!0}}return!1}function mc(e){let t=[];for(let n of dc(e))n===`..`?t.pop():t.push(n);return`/${t.join(`/`)}`}function hc(e){return e.replace(/^(['"])(.*)\1$/,`$2`)}const gc=/^(?:~|\$HOME|\$\{HOME\})(?=\/|$)(.*)$/;function _c(e,t){let n=hc(e),r=gc.exec(n),i;if(r!==null){let e=r[1]??``;if(t.homeDirectory===void 0)return e.replace(/\/+/g,``)===``;i=mc(`${t.homeDirectory}/${e}`)}else if(n===``||n.startsWith(`$`))return!1;else if(n.startsWith(`/`))i=mc(n);else{if(t.cwd===void 0)return!1;i=mc(`${t.cwd}/${n}`)}if(dc(i).length<=1||t.homeDirectory!==void 0&&i===mc(t.homeDirectory))return!0;if(t.cwd!==void 0){let e=mc(t.cwd);if(e===i||e.startsWith(`${i}/`))return!0}return!1}const vc=new Set([`rm`,`rmdir`]),yc=new Map([[`sudo`,new Set([`-u`,`-g`,`-h`,`-p`,`-C`,`-D`,`-r`,`-t`,`-U`,`-T`])],[`nice`,new Set([`-n`])],[`env`,new Set([`-u`,`-C`,`-S`])],[`command`,new Set],[`builtin`,new Set],[`nohup`,new Set],[`time`,new Set]]);function bc(e){let t=0,n;for(;t<e.length;){let r=e[t];if(/^[A-Za-z_]\w*=/.test(r)){t+=1;continue}let i=yc.get(r);if(i!==void 0){n=i,t+=1;continue}if(n!==void 0&&r.startsWith(`-`)){t+=n.has(r)?2:1;continue}return t}return t}function xc(e,t){return Fs(e).some(e=>{let n=e.split(/\s+/).filter(e=>e!==``),r=bc(n),i=n[r];if(i===void 0)return!1;let a=i.slice(i.lastIndexOf(`/`)+1);if(!vc.has(a))return!1;let o=!1;return n.slice(r+1).some(e=>!o&&e===`--`?(o=!0,!1):!o&&e.startsWith(`-`)?!1:_c(e,t))})}const Sc=new Set([`ls`,`cat`,`echo`,`pwd`,`head`,`tail`,`grep`,`wc`,`which`,`stat`,`du`,`cd`]),Cc=new Set([`-exec`,`-execdir`,`-ok`,`-okdir`,`-delete`,`-fprint`,`-fprint0`,`-fprintf`,`-fls`]),wc={ls:`aAlhtrSR1dFGinpsucCgmoQvx`,cat:`nbsvetAE`,head:`nqvc`,tail:`nqvcfF`,grep:`rinlLvcwxEFGPHhoqsABCmz`,wc:`lwcmL`,stat:`cftx`,du:`hsacdkmx`,which:`a`,pwd:`LP`,cd:`LP`},Tc=/^--?[A-Za-z0-9-]*(file|from|contents)(=|$)/,Ec=[`--dereference`,`--dereference-recursive`,`--dereference-args`,`--dereference-command-line`,`--file`,`--files0-from`,`--exclude-from`,`--from-file`,`--to-file`,`--contents`,`--ignore-revs-file`,`--output`,`--output-directory`,`--ext-diff`,`--no-index`,`--open-files-in-pager`];function Dc(e){if(!e.startsWith(`--`)||e.length<=2)return!1;let t=e.split(`=`,1)[0];return Ec.some(e=>e.startsWith(t))}function Oc(e,t){if(Bc(t).some(e=>Tc.test(e.text)||Dc(e.text)))return!0;if(e===`find`)return Bc(t).some(e=>e.text===`-L`||e.text===`-follow`);let n=wc[e];return n!==void 0&&Bc(t).some(({text:e})=>e.startsWith(`--`)||!/^-[A-Za-z]/.test(e)?!1:[...e.slice(1)].some(e=>!/\d/.test(e)&&!n.includes(e)))}const kc=new Set([`status`,`log`,`diff`,`show`,`rev-parse`,`ls-files`,`describe`,`branch`,`remote`]),Ac=new Set([`-l`,`--list`,`--show-current`,`--merged`,`--no-merged`,`--contains`,`--no-contains`,`--points-at`]),jc=new Set([`-a`,`--all`,`-r`,`--remotes`,`-v`,`-vv`,`--verbose`,`--color`,`--no-color`]),Mc=new Set([`/dev/null`]),Nc=/[A-Za-z0-9_./:=@+,*?[\]~-]/,Pc=new Set([`$`,"`",`\\`,`!`]),Fc=new Set([`*`,`?`,`[`]);function Ic(e){return/(^|[=,:])[/~]/.test(e)||/^-[A-Za-z]+[/~]/.test(e)||/(^|[/=,:]|^-[A-Za-z]+)\.\.(\/|$)/.test(e)||/(^|[=,])[A-Za-z][A-Za-z0-9]*:/.test(e)||Lc(e)}function Lc(e){let t=e.split(`/`),n=e=>/[*?[]/.test(e);if(t.slice(0,-1).some(n))return!0;let r=t[t.length-1];return n(r)&&/^[.?[]/.test(r)}function Rc(e){let t;for(let n of e){if(t===`'`){n===`'`&&(t=void 0);continue}if(n===`$`||n==="`"||n===`\\`)return!0;if(t===`"`){n===`"`&&(t=void 0);continue}if(n===`'`||n===`"`)t=n;else if(n===`(`||n===`)`||n===`{`||n===`}`)return!0}return!1}function zc(e){let t=[],n=``,r=!1,i=!1,a,o,s=!1,c=()=>{i&&=(o===`output`?(!Mc.has(n)||r)&&(s=!0):o===`duplicate`?/^(\d+|-)$/.test(n)||(s=!0):o===`input`?(r||Ic(n))&&(s=!0):t.push({text:n,expands:r}),o=void 0,n=``,r=!1,!1)};for(let t=0;t<e.length&&!s;t+=1){let l=e[t];if(a===`'`){l===`'`?a=void 0:n+=l;continue}if(a===`"`){l===`"`?a=void 0:Pc.has(l)?s=!0:n+=l;continue}if(l===`'`||l===`"`){a=l,i=!0;continue}if(l===` `||l===` `){c();continue}if(l===`>`||l===`<`||l===`&`&&e[t+1]===`>`){i&&!/^\d+$/.test(n)&&c(),n=``,r=!1,i=!1,l===`&`&&(t+=1);let a=l===`&`?`>`:l,u=e[t+1];if(a===`<`&&(u===`<`||u===`>`)){s=!0;break}if((u===a||u===`|`)&&(t+=1,u=e[t+1]),u===`&`&&l!==`&`){t+=1,o=`duplicate`;continue}o=a===`>`?`output`:`input`;continue}if(!Nc.test(l)){s=!0;break}Fc.has(l)&&(r=!0),n+=l,i=!0}return a!==void 0&&(s=!0),c(),o!==void 0&&(s=!0),{words:t,refused:s}}function Bc(e){let t=e.findIndex(e=>e.text===`--`);return(t<0?e:e.slice(0,t)).filter(e=>e.text.startsWith(`-`))}function Vc(e){return e.every(e=>!e.expands&&!Cc.has(e.text))}function Hc(e){let t=e.filter(e=>e.text.startsWith(`-`)),n=t.some(e=>Ac.has(e.text));return t.every(e=>Ac.has(e.text)||jc.has(e.text))&&(n||t.length===e.length)}function Uc(e){let[t,...n]=e[0]?.text===`--no-pager`?e.slice(1):e;return t===void 0||t.expands||!kc.has(t.text)||n.some(e=>e.expands)||n.some(e=>/^-[XO]/.test(e.text))||n.some(e=>/^--(output|ext-diff|open-files-in-pager|no-index)/.test(e.text))?!1:t.text===`branch`?Hc(n):t.text!==`remote`||n.every(e=>e.text===`-v`||e.text===`--verbose`)}function Wc(e){let[t,...n]=e;return t===void 0||t.expands||t.text.includes(`=`)||t.text.includes(`/`)||n.some(e=>/^[@=]/.test(e.text))||n.some(e=>e.expands)?!1:t.text===`echo`?!0:n.some(e=>Ic(e.text))||Oc(t.text,n)?!1:t.text===`cd`?n.length===1&&n[0].text!==`-`&&!n[0].expands:Sc.has(t.text)?!0:t.text===`find`?Vc(n):t.text===`git`&&Uc(n)}const Gc=new Set([`echo`,`which`,`git`]);function Kc(e,t){let n;for(let[r,...i]of e)if(!Gc.has(r.text))for(let e of i){if(e.text===`--`)continue;if(t===void 0)return!1;let i=t(n,e.text);if(i===void 0)return!1;r.text===`cd`&&(n=i)}return!0}function qc(e,t={}){if(t.otherDirectory===!0||e.length>1e4||Rc(e)||/[^\t\n\x20-\x7e]/.test(e))return!1;let n=Fs(e);if(n.length===0)return!1;let r=n.map(zc);if(r.some(e=>e.refused||!Wc(e.words)))return!1;let i=r.map(e=>e.words[0].text);return i.includes(`git`)&&i.includes(`cd`)?!1:Kc(r.map(e=>e.words),t.resolveInWorkspace)}function Jc(e){let t=e.indexOf(`(`);return t===-1?{toolName:e.trim(),argPattern:void 0}:{toolName:e.slice(0,t).trim(),argPattern:e.slice(t+1,e.lastIndexOf(`)`)).trim()}}const Q=new Map;function Yc(e,t){Q.set(e,{...Q.get(e),...t})}function Xc(){Q.clear()}function Zc(e){return Q.get(e)??{}}function Qc(e,t){let n=[t,...Q.get(t)?.aliases??[]];if(!e.includes(`*`))return n.includes(e);let r=Us(e);return n.some(e=>r.test(e))}function $c(e,t){let n=/^([A-Za-z_]\w*):([\s\S]*)$/.exec(t);if(n===null)return;let r=n[1],i=Q.get(e);if(i?.argument?.key===r)return`primary`;if(i?.parameters?.includes(r)===!0)return{name:r,value:n[2]}}function el(e,t){if(!Object.prototype.hasOwnProperty.call(t,e.name))return`no-match`;let n=t[e.name];return n===void 0?`no-match`:typeof n!=`string`&&typeof n!=`number`&&typeof n!=`boolean`?`unevaluable`:Us(e.value).test(String(n))?`match`:`no-match`}function tl(e,t){return t.some(t=>{let n=Jc(t);return(n.argPattern===void 0||n.argPattern===`*`||n.argPattern===`**`)&&Qc(n.toolName,e)})}function nl(e){return Q.get(e)?.argument?.key}function rl(e,t){let n=nl(e);if(n===void 0)return;let r=t[n];return typeof r==`string`?r:void 0}function il(e,t,n,r=`allow`){return n.some(n=>ol(e,t,n,r)===`match`)}function al(e,t,n){return n.some(n=>ol(e,t,n,`deny`)===`unevaluable`)}function ol(e,t,n,r){let i=Jc(n);if(!Qc(i.toolName,e))return`no-match`;if(i.argPattern===void 0||i.argPattern===`*`||i.argPattern===`**`)return`match`;let a=$c(e,i.argPattern);if(a===`primary`)return`unevaluable`;if(a!==void 0)return r===`deny`?el(a,t):`no-match`;let o=Q.get(e)?.argument;if(o===void 0)return`unevaluable`;let s=rl(e,t);if(s===void 0)return`no-match`;switch(o.kind){case`url`:return oc(i.argPattern,s);case`path`:return Js(i.argPattern,s);case`command`:return Ws(i.argPattern,s,r);case`text`:return Us(i.argPattern).test(s)?`match`:`no-match`;default:{let e=o.kind;throw Error(`unknown argument kind: ${String(e)}`)}}}function sl(e,t,n){let r=Q.get(e),i=r?.argument;if(i===void 0)return!1;let a=t[i.key];return typeof a==`string`?i.kind===`command`?xc(a,n):i.kind===`path`&&r?.riskClass===`modify`&&pc(a):!1}function cl(e,t,n,r){return il(e,t,n,`deny`)||al(e,t,n)||sl(e,t,r)}function ll(e,t,n={},r={}){return al(e,t,n.deny??[])||cl(e,t,n.ask??[],r)}const ul=[`workingDirectory`,`cwd`];function dl(e,t,n){let r=Q.get(e);if(r?.riskClass!==`execute`||r.argument?.kind!==`command`)return r?.riskClass;let i=t[r.argument.key];return typeof i==`string`&&qc(i,{otherDirectory:ul.some(e=>t[e]!==void 0),...n.resolveInWorkspace===void 0?{}:{resolveInWorkspace:n.resolveInWorkspace}})?`inspect`:r.riskClass}function fl(e,t,n,r={},i={}){let{allow:a=[],deny:o=[],ask:s=[]}=r,c=dl(e,t,i),l=n===`plan`&&c!==`inspect`?`deny`:`approve`;return il(e,t,o,`deny`)||i.ceiling!==void 0&&!il(e,t,i.ceiling)||Q.get(e)?.repliesToPeer===!0&&i.peerTurn!==!0?`deny`:al(e,t,o)?n===`plan`?`deny`:`approve`:cl(e,t,s,i)||i.askAll===!0?l:n===`bypassPermissions`||il(e,t,a)||i.sandboxAutoApproved===!0&&c===`execute`&&(n==="default"||n===`acceptEdits`||n===`auto`)?`auto`:c===void 0?cc[n]:sc[n][c]}function pl(e,t={}){let n=t.taskDeny??[];switch(e){case`deny`:return{ceiling:[],askAll:!1,allow:[],deny:n};case`prompt`:return{askAll:!0,allow:[],deny:n};case`preapproved`:{let e=t.taskAllow??[];return{ceiling:e,askAll:!1,allow:e,deny:n}}case`inherit-allowlist`:return{ceiling:t.parentAllow??[],askAll:!1,allow:[],deny:n};default:throw Error(`unknown permission policy: ${String(e)}`)}}const ml=/^[A-Za-z_]\w*:(?!\/\/)/;function hl(e){return e.slice(0,e.indexOf(`*`)).includes(`__`)}function gl(e,t=`deny`){let n=e.trim();if(n===``)return`is empty`;if(n.includes(`(`)&&!n.endsWith(`)`))return`opens "(" without closing it`;let{toolName:r,argPattern:i}=Jc(n);if(r===``)return`names no tool`;if(t===`allow`&&r.includes(`*`)&&!hl(r))return`globs the tool name without a literal "<server>__" prefix, which an allow rule may not do`;if(i===void 0||i===`*`||i===`**`)return;if(i===``)return`has an empty argument pattern; write Tool or Tool(*) instead`;if(r.includes(`*`))return t===`allow`&&ml.test(i)?`matches a named parameter, which only deny and ask rules may do`:void 0;let a=$c(r,i);if(a!==void 0&&a!==`primary`)return t===`allow`?`matches a named parameter, which only deny and ask rules may do`:void 0;let o=Zc(r);if(!(o.parameters===void 0&&ml.test(i)&&$c(r,i)===void 0)){if(o.argument===void 0)return o.riskClass===void 0?void 0:`tool "${r}" declares no argument key, so an argument-scoped pattern can never be evaluated`;if(o.argument.kind===`url`&&oc(i,`https://probe.invalid/`)===`unevaluable`)return`does not fit the URL pattern grammar scheme://host[:port][/path] that "${r}" is matched by`}}function _l(e,t=`deny`){let n=[];for(let r of e){let e=gl(r,t);e!==void 0&&n.push({pattern:r,reason:e})}return n}function vl(e){let t=[];for(let n of e){let{toolName:e,argPattern:r}=Jc(n.trim());if(r===void 0||e.includes(`*`))continue;let i=Zc(e),a=$c(e,r);if(a===void 0&&i.parameters!==void 0&&i.argument?.kind!==`url`&&ml.test(r)){t.push({pattern:n,reason:`names no parameter of "${e}" (${i.parameters.join(`, `)}), so it is read as an ordinary argument pattern`});continue}if(a!==`primary`)continue;let o=Zc(e).argument?.key??``;t.push({pattern:n,reason:`names "${e}"'s primary field "${o}", so it asks on every call; write ${e}(${r.slice(o.length+1)}) instead`})}return t}function yl(e){return(e??[]).map(e=>`${e}(*)`)}function bl(e,t){let n=yl(t.allowedTools),r=_l(n,`allow`);if(r.length>0){let e=r.map(({pattern:e,reason:t})=>`"${e}" ${t}`).join(`; `);throw Error(`Invalid preset allowedTools: ${e}.`)}return{allow:[...e.allow,...n],deny:[...new Set([...e.deny,...yl(t.deniedTools)])]}}const xl=[`Bash`,`Shell`,`BackgroundProcess`],Sl=[`Agent`],Cl=[...xl,...Sl,`ExecuteCommand`,`Computer`],wl=`python.node.deno.bun.ruby.perl.php.bash.sh.zsh.fish.pwsh.powershell.cmd.env.xargs.eval.exec.sudo.timeout.nohup.nice.time.command.setsid.stdbuf.watch.ssh.docker.podman.find`.split(`.`),Tl=[`npm run`,`npm run-script`,`npm exec`,`npm x`,`npx`,`pnpm`,`pnpx`,`yarn`,`bunx`,`uv run`,`uvx`,`pipx run`,`cargo run`,`go run`,`make`,`just`].map(e=>e.split(` `)),El=new Set([`run`,`run-script`,`exec`,`dlx`,`x`,`--`]);function Dl(e){return(e.split(/[\\/]/).pop()??e).replace(/(\.exe)?$/i,``).replace(/[\d.]+$/,``)}function Ol(e,t){if(e.length===0)return!0;let n=(e,n,r)=>t&&r?e.startsWith(n):e===n,r=Dl(e[0]);if(wl.some(t=>n(t,r,e.length===1)))return!0;for(let i of Tl){let a=Math.min(i.length,e.length);if(!i.slice(0,a).every((t,i)=>n(t,i===0?r:e[i],i===e.length-1)))continue;if(e.length<=i.length)return!0;let o=e.slice(i.length);for(;o.length>0&&(o[0].startsWith(`-`)||El.has(o[0]));)o=o.slice(1);return o.length===0||Ol(o,t)}return!1}function kl(e){let t=e.trim();if(!t.includes(`*`))return!1;let n=t.slice(0,t.indexOf(`*`));return Ol(n.trim().split(/\s+/).filter(e=>e.length>0),n.length>0&&!/\s$/.test(n))}function Al(e){let{toolName:t,argPattern:n}=Jc(e),r=e=>e.some(e=>Qc(t,e));return r(Sl)?!0:t.includes(`*`)?r(Cl):Cl.includes(t)||Zc(t).riskClass===`execute`?n===void 0||n.trim()===`*`||xl.includes(t)&&kl(n):!1}function jl(e){return e.filter(e=>!Al(e))}const Ml=1e6,Nl={"claude-opus-4-7":{inputPerMillion:15,outputPerMillion:75},"claude-opus-4-5":{inputPerMillion:15,outputPerMillion:75},"claude-sonnet-4-6":{inputPerMillion:3,outputPerMillion:15},"claude-sonnet-4-5":{inputPerMillion:3,outputPerMillion:15},"claude-haiku-4-5":{inputPerMillion:.8,outputPerMillion:4},"claude-3-5-sonnet-20241022":{inputPerMillion:3,outputPerMillion:15},"claude-3-5-haiku-20241022":{inputPerMillion:.8,outputPerMillion:4},"claude-3-opus-20240229":{inputPerMillion:15,outputPerMillion:75},"gpt-4o":{inputPerMillion:2.5,outputPerMillion:10},"gpt-4o-mini":{inputPerMillion:.15,outputPerMillion:.6},o1:{inputPerMillion:15,outputPerMillion:60},"o1-mini":{inputPerMillion:3,outputPerMillion:12},o3:{inputPerMillion:10,outputPerMillion:40},"o3-mini":{inputPerMillion:1.1,outputPerMillion:4.4},"deepseek-chat":{inputPerMillion:.14,outputPerMillion:.28},"deepseek-reasoner":{inputPerMillion:.55,outputPerMillion:2.19},"gemini-2.0-flash":{inputPerMillion:.1,outputPerMillion:.4},"gemini-2.0-flash-thinking":{inputPerMillion:.35,outputPerMillion:3.5},"gemini-1.5-pro":{inputPerMillion:1.25,outputPerMillion:5},"gemini-1.5-flash":{inputPerMillion:.075,outputPerMillion:.3}},Pl=[{pattern:/claude-opus/i,price:{inputPerMillion:15,outputPerMillion:75}},{pattern:/claude-sonnet/i,price:{inputPerMillion:3,outputPerMillion:15}},{pattern:/claude-haiku/i,price:{inputPerMillion:.8,outputPerMillion:4}},{pattern:/gpt-4o-mini/i,price:{inputPerMillion:.15,outputPerMillion:.6}},{pattern:/gpt-4/i,price:{inputPerMillion:2.5,outputPerMillion:10}},{pattern:/deepseek/i,price:{inputPerMillion:.14,outputPerMillion:.28}},{pattern:/gemini-2/i,price:{inputPerMillion:.1,outputPerMillion:.4}},{pattern:/gemini-1/i,price:{inputPerMillion:1.25,outputPerMillion:5}}];function Fl(e){let t=Object.hasOwn(Nl,e)?Nl[e]:void 0;if(t)return t;for(let{pattern:t,price:n}of Pl)if(t.test(e))return n}function Il(e,t,n){let r=Fl(e);if(r)return t/Ml*r.inputPerMillion+n/Ml*r.outputPerMillion}function Ll(e){let t=Fl(e);if(t)return(t.inputPerMillion+t.outputPerMillion)/2/1e3}function Rl(e,t){if(!e.matcher)return!0;if(!t)return!1;try{return new RegExp(e.matcher).test(t)}catch{return e.matcher===t}}function zl(e){if(e.tool_name)return e.tool_name;if(e.hook_event_name===`SubagentStart`||e.hook_event_name===`SubagentStop`)return e.agent_type??e.agent_id;if(e.hook_event_name===`SessionEnd`)return e.reason}async function Bl(){let[{CommandExecutor:e},{HttpExecutor:t}]=await Promise.all([import(`./command-executor-DV-H2oD6.js`).then(e=>e.n),import(`./http-executor-cWzI2svn.js`).then(e=>e.n)]);return[new e,new t]}async function Vl(e,t,n,r,i){if(!e)return{blocked:!1,stdout:``};let a=new Set,o=[],s=()=>({...a.size>0&&{unknownHookTypes:[...a].sort()},...o.length>0&&{errors:[...o]}}),c=e[t];if(!c||c.length===0)return{blocked:!1,stdout:``};let l=r??await Bl(),u=new Map;for(let e of l)u.set(e.type,e);let d=[],f=zl(n),p=-1,m,h;for(let e of c){if(!Rl(e,f))continue;let r=e.env?{...n,env:{...n.env,...e.env}}:n;for(let n of e.hooks){let e=u.get(n.type);if(!e){a.add(n.type);continue}let c=n.type===`command`&&i!==void 0?await e.execute(n,r,i):await e.execute(n,r);if(c.outcome===`deny`)return{blocked:!0,reason:c.reason||`Blocked by hook`,stdout:d.join(`
10
+ `||r===`&`&&Vs(t,n))return Is(e),n}function Vs(e,t){let n=e[t-1];return n!==`>`&&n!==`<`&&e[t+1]!==`>`}const Hs=/[.+^${}()|[\]\\]/g;function Us(e){let t=e.replace(Hs,`\\$&`).replace(/\*\*/g,`.+`).replace(/\*/g,`.*`);return RegExp(`^${t}$`)}function Ws(e,t,n){let r=Us(e);return n===`deny`?r.test(t)||Fs(t).some(e=>r.test(e))?`match`:`no-match`:r.test(t)?e.includes(`*`)&&Ps(t)?`no-match`:`match`:`no-match`}function Gs(e){let t=e.replace(/\*\*(?:\/\*\*)+/g,`**`).split(/(\/\*\*\/|\/\*\*$|^\*\*\/|\*\*)/).map(e=>e===`/**/`?`(?:/.*)?/`:e===`/**`?`(?:/.*)?`:e===`**/`?`(?:.*/)?`:e===`**`?`.*`:e.replace(Hs,`\\$&`).replace(/\*/g,`[^/]*`).replace(/\uE000/g,`\\*`)).join(``);return RegExp(`^${t}$`)}function Ks(e){return e.startsWith(`/`)||/^[A-Za-z]:(?=\/|$)/.test(e)}function qs(e){let t=e.replace(/\\/g,`/`),n=t.startsWith(`/`),r=[];for(let e of t.split(`/`))if(e!==``&&e!==`.`){if(e===`..`){r.length>0&&r[r.length-1]!==`..`?r.pop():n||r.push(`..`);continue}r.push(e)}let i=(n?`/`:``)+r.join(`/`);return(i===``?`.`:i).replace(/^[A-Za-z]:(?=\/|$)/,e=>e.toLowerCase())}function Js(e,t){let n=qs(e),r=qs(t);return Ks(n)&&!Ks(r)?`unevaluable`:Gs(n).test(r)?`match`:`no-match`}const Ys=/^(\*|[a-z][a-z0-9+.-]*):\/\/(\[[0-9a-fA-F:.]+\]|[^/\\:?#@[\]]+)(?::(\d+|\*))?(\/[^?#]*)?$/i,Xs=new Set([`http`,`https`,`ws`,`wss`,`ftp`]),Zs={http:`80`,https:`443`,ws:`80`,wss:`443`,ftp:`21`};function Qs(e){return e.replace(/\.$/,``).toLowerCase()}function $s(e){try{let t=new URL(`http://${e}/`).hostname;return t===``||t.includes(`.`)?null:t}catch{return null}}function ec(e){let t=Qs(e).replace(/\*\*(?:\.\*\*)+/g,`**`).split(`.`),n=[],r=`[^.]+(?:\\.[^.]+)*`;for(let[e,i]of t.entries()){let a=e===0,o=e===t.length-1;if(i===`**`){a&&o?n.push(r):o?n.push(`(?:\\.${r})?`):n.push(`${a?``:`\\.`}(?:${r}\\.)?`);continue}let s=!a&&t[e-1]===`**`,c=a||s?``:`\\.`;if(i===`*`)n.push(`${c}${r}`);else if(i.includes(`**`))return null;else if(i.includes(`*`))n.push(`${c}${i.replace(Hs,`\\$&`).replace(/\*/g,`[^.]*`)}`);else{let e=$s(i);if(e===null)return null;n.push(`${c}${e.replace(Hs,`\\$&`)}`)}}return RegExp(`^${n.join(``)}$`)}function tc(e){try{let t=e.split(`/`).map(e=>decodeURIComponent(e));return t.some(e=>e.includes(`/`))?null:t.join(`/`)}catch{return null}}function nc(e){let t;try{t=new URL(e)}catch{return null}let n=t.protocol.slice(0,-1).toLowerCase();return!Xs.has(n)||t.hostname===``||t.username!==``||t.password!==``?null:t}function rc(e,t){if(e.includes(`*`)){let n=ec(e);return n===null?`unevaluable`:n.test(t)?`match`:`no-match`}let n;try{n=new URL(`http://${e}/`).hostname}catch{return`unevaluable`}return Qs(n)===t?`match`:`no-match`}function ic(e,t,n){return e===void 0?t.port===``:e===`*`||e===(t.port===``?Zs[n]:t.port)}function ac(e,t){let n=tc(t),r=tc(e.replace(/%2a/gi,``));return n===null||r===null?`unevaluable`:Gs(r).test(n)?`match`:`no-match`}function oc(e,t){let n=Ys.exec(e);if(n===null)return`unevaluable`;let[,r,i,a,o]=n,s=nc(t);if(s===null)return`unevaluable`;let c=s.protocol.slice(0,-1).toLowerCase();if(r!==`*`&&r.toLowerCase()!==c)return`no-match`;let l=rc(i,Qs(s.hostname));return l===`match`?ic(a,s,c)?o===void 0?`match`:ac(o,s.pathname):`no-match`:l}const sc={plan:{inspect:`auto`,modify:`deny`,execute:`deny`},default:{inspect:`auto`,modify:`approve`,execute:`approve`},acceptEdits:{inspect:`auto`,modify:`auto`,execute:`approve`},bypassPermissions:{inspect:`auto`,modify:`auto`,execute:`auto`},auto:{inspect:`auto`,modify:`auto`,execute:`approve`}},cc={plan:`deny`,default:`approve`,acceptEdits:`approve`,bypassPermissions:`auto`,auto:`approve`},lc=[`.git`,`.robota`,`.claude`,`.agents`],uc=[`.mcp.json`,`.gitconfig`,`.npmrc`,`.bashrc`,`.bash_profile`,`.bash_login`,`.zshrc`,`.zshenv`,`.zprofile`,`.profile`];function dc(e){return e.replace(/\\/g,`/`).split(`/`).filter(e=>e!==``&&e!==`.`)}function fc(e){let t=[];for(let n of dc(e))n===`..`&&t.length>0&&t[t.length-1]!==`..`?t.pop():t.push(n);return t}function pc(e){let t=fc(e),n=t[t.length-1];if(n!==void 0&&uc.includes(n))return!0;for(let e=0;e<t.length;e+=1){let n=t[e];if(lc.includes(n)){if((n===`.robota`||n===`.claude`)&&t[e+1]===`worktrees`&&t[e+2]!==void 0){e+=2;continue}return!0}}return!1}function mc(e){let t=[];for(let n of dc(e))n===`..`?t.pop():t.push(n);return`/${t.join(`/`)}`}function hc(e){return e.replace(/^(['"])(.*)\1$/,`$2`)}const gc=/^(?:~|\$HOME|\$\{HOME\})(?=\/|$)(.*)$/;function _c(e,t){let n=hc(e),r=gc.exec(n),i;if(r!==null){let e=r[1]??``;if(t.homeDirectory===void 0)return e.replace(/\/+/g,``)===``;i=mc(`${t.homeDirectory}/${e}`)}else if(n===``||n.startsWith(`$`))return!1;else if(n.startsWith(`/`))i=mc(n);else{if(t.cwd===void 0)return!1;i=mc(`${t.cwd}/${n}`)}if(dc(i).length<=1||t.homeDirectory!==void 0&&i===mc(t.homeDirectory))return!0;if(t.cwd!==void 0){let e=mc(t.cwd);if(e===i||e.startsWith(`${i}/`))return!0}return!1}const vc=new Set([`rm`,`rmdir`]),yc=new Map([[`sudo`,new Set([`-u`,`-g`,`-h`,`-p`,`-C`,`-D`,`-r`,`-t`,`-U`,`-T`])],[`nice`,new Set([`-n`])],[`env`,new Set([`-u`,`-C`,`-S`])],[`command`,new Set],[`builtin`,new Set],[`nohup`,new Set],[`time`,new Set]]);function bc(e){let t=0,n;for(;t<e.length;){let r=e[t];if(/^[A-Za-z_]\w*=/.test(r)){t+=1;continue}let i=yc.get(r);if(i!==void 0){n=i,t+=1;continue}if(n!==void 0&&r.startsWith(`-`)){t+=n.has(r)?2:1;continue}return t}return t}function xc(e,t){return Fs(e).some(e=>{let n=e.split(/\s+/).filter(e=>e!==``),r=bc(n),i=n[r];if(i===void 0)return!1;let a=i.slice(i.lastIndexOf(`/`)+1);if(!vc.has(a))return!1;let o=!1;return n.slice(r+1).some(e=>!o&&e===`--`?(o=!0,!1):!o&&e.startsWith(`-`)?!1:_c(e,t))})}const Sc=new Set([`ls`,`cat`,`echo`,`pwd`,`head`,`tail`,`grep`,`wc`,`which`,`stat`,`du`,`cd`]),Cc=new Set([`-exec`,`-execdir`,`-ok`,`-okdir`,`-delete`,`-fprint`,`-fprint0`,`-fprintf`,`-fls`]),wc={ls:`aAlhtrSR1dFGinpsucCgmoQvx`,cat:`nbsvetAE`,head:`nqvc`,tail:`nqvcfF`,grep:`rinlLvcwxEFGPHhoqsABCmz`,wc:`lwcmL`,stat:`cftx`,du:`hsacdkmx`,which:`a`,pwd:`LP`,cd:`LP`},Tc=/^--?[A-Za-z0-9-]*(file|from|contents)(=|$)/,Ec=[`--dereference`,`--dereference-recursive`,`--dereference-args`,`--dereference-command-line`,`--file`,`--files0-from`,`--exclude-from`,`--from-file`,`--to-file`,`--contents`,`--ignore-revs-file`,`--output`,`--output-directory`,`--ext-diff`,`--no-index`,`--open-files-in-pager`];function Dc(e){if(!e.startsWith(`--`)||e.length<=2)return!1;let t=e.split(`=`,1)[0];return Ec.some(e=>e.startsWith(t))}function Oc(e,t){if(Bc(t).some(e=>Tc.test(e.text)||Dc(e.text)))return!0;if(e===`find`)return Bc(t).some(e=>e.text===`-L`||e.text===`-follow`);let n=wc[e];return n!==void 0&&Bc(t).some(({text:e})=>e.startsWith(`--`)||!/^-[A-Za-z]/.test(e)?!1:[...e.slice(1)].some(e=>!/\d/.test(e)&&!n.includes(e)))}const kc=new Set([`status`,`log`,`diff`,`show`,`rev-parse`,`ls-files`,`describe`,`branch`,`remote`]),Ac=new Set([`-l`,`--list`,`--show-current`,`--merged`,`--no-merged`,`--contains`,`--no-contains`,`--points-at`]),jc=new Set([`-a`,`--all`,`-r`,`--remotes`,`-v`,`-vv`,`--verbose`,`--color`,`--no-color`]),Mc=new Set([`/dev/null`]),Nc=/[A-Za-z0-9_./:=@+,*?[\]~-]/,Pc=new Set([`$`,"`",`\\`,`!`]),Fc=new Set([`*`,`?`,`[`]);function Ic(e){return/(^|[=,:])[/~]/.test(e)||/^-[A-Za-z]+[/~]/.test(e)||/(^|[/=,:]|^-[A-Za-z]+)\.\.(\/|$)/.test(e)||/(^|[=,])[A-Za-z][A-Za-z0-9]*:/.test(e)||Lc(e)}function Lc(e){let t=e.split(`/`),n=e=>/[*?[]/.test(e);if(t.slice(0,-1).some(n))return!0;let r=t[t.length-1];return n(r)&&/^[.?[]/.test(r)}function Rc(e){let t;for(let n of e){if(t===`'`){n===`'`&&(t=void 0);continue}if(n===`$`||n==="`"||n===`\\`)return!0;if(t===`"`){n===`"`&&(t=void 0);continue}if(n===`'`||n===`"`)t=n;else if(n===`(`||n===`)`||n===`{`||n===`}`)return!0}return!1}function zc(e){let t=[],n=``,r=!1,i=!1,a,o,s=!1,c=()=>{i&&=(o===`output`?(!Mc.has(n)||r)&&(s=!0):o===`duplicate`?/^(\d+|-)$/.test(n)||(s=!0):o===`input`?(r||Ic(n))&&(s=!0):t.push({text:n,expands:r}),o=void 0,n=``,r=!1,!1)};for(let t=0;t<e.length&&!s;t+=1){let l=e[t];if(a===`'`){l===`'`?a=void 0:n+=l;continue}if(a===`"`){l===`"`?a=void 0:Pc.has(l)?s=!0:n+=l;continue}if(l===`'`||l===`"`){a=l,i=!0;continue}if(l===` `||l===` `){c();continue}if(l===`>`||l===`<`||l===`&`&&e[t+1]===`>`){i&&!/^\d+$/.test(n)&&c(),n=``,r=!1,i=!1,l===`&`&&(t+=1);let a=l===`&`?`>`:l,u=e[t+1];if(a===`<`&&(u===`<`||u===`>`)){s=!0;break}if((u===a||u===`|`)&&(t+=1,u=e[t+1]),u===`&`&&l!==`&`){t+=1,o=`duplicate`;continue}o=a===`>`?`output`:`input`;continue}if(!Nc.test(l)){s=!0;break}Fc.has(l)&&(r=!0),n+=l,i=!0}return a!==void 0&&(s=!0),c(),o!==void 0&&(s=!0),{words:t,refused:s}}function Bc(e){let t=e.findIndex(e=>e.text===`--`);return(t<0?e:e.slice(0,t)).filter(e=>e.text.startsWith(`-`))}function Vc(e){return e.every(e=>!e.expands&&!Cc.has(e.text))}function Hc(e){let t=e.filter(e=>e.text.startsWith(`-`)),n=t.some(e=>Ac.has(e.text));return t.every(e=>Ac.has(e.text)||jc.has(e.text))&&(n||t.length===e.length)}function Uc(e){let[t,...n]=e[0]?.text===`--no-pager`?e.slice(1):e;return t===void 0||t.expands||!kc.has(t.text)||n.some(e=>e.expands)||n.some(e=>/^-[XO]/.test(e.text))||n.some(e=>/^--(output|ext-diff|open-files-in-pager|no-index)/.test(e.text))?!1:t.text===`branch`?Hc(n):t.text!==`remote`||n.every(e=>e.text===`-v`||e.text===`--verbose`)}function Wc(e){let[t,...n]=e;return t===void 0||t.expands||t.text.includes(`=`)||t.text.includes(`/`)||n.some(e=>/^[@=]/.test(e.text))||n.some(e=>e.expands)?!1:t.text===`echo`?!0:n.some(e=>Ic(e.text))||Oc(t.text,n)?!1:t.text===`cd`?n.length===1&&n[0].text!==`-`&&!n[0].expands:Sc.has(t.text)?!0:t.text===`find`?Vc(n):t.text===`git`&&Uc(n)}const Gc=new Set([`echo`,`which`,`git`]);function Kc(e,t){let n;for(let[r,...i]of e)if(!Gc.has(r.text))for(let e of i){if(e.text===`--`)continue;if(t===void 0)return!1;let i=t(n,e.text);if(i===void 0)return!1;r.text===`cd`&&(n=i)}return!0}function qc(e,t={}){if(t.otherDirectory===!0||e.length>1e4||Rc(e)||/[^\t\n\x20-\x7e]/.test(e))return!1;let n=Fs(e);if(n.length===0)return!1;let r=n.map(zc);if(r.some(e=>e.refused||!Wc(e.words)))return!1;let i=r.map(e=>e.words[0].text);return i.includes(`git`)&&i.includes(`cd`)?!1:Kc(r.map(e=>e.words),t.resolveInWorkspace)}function Jc(e){let t=e.indexOf(`(`);return t===-1?{toolName:e.trim(),argPattern:void 0}:{toolName:e.slice(0,t).trim(),argPattern:e.slice(t+1,e.lastIndexOf(`)`)).trim()}}const Q=new Map;function Yc(e,t){Q.set(e,{...Q.get(e),...t})}function Xc(){Q.clear()}function Zc(e){return Q.get(e)??{}}function Qc(e,t){let n=[t,...Q.get(t)?.aliases??[]];if(!e.includes(`*`))return n.includes(e);let r=Us(e);return n.some(e=>r.test(e))}function $c(e,t){let n=/^([A-Za-z_]\w*):([\s\S]*)$/.exec(t);if(n===null)return;let r=n[1],i=Q.get(e);if(i?.argument?.key===r)return`primary`;if(i?.parameters?.includes(r)===!0)return{name:r,value:n[2]}}function el(e,t){if(!Object.prototype.hasOwnProperty.call(t,e.name))return`no-match`;let n=t[e.name];return n===void 0?`no-match`:typeof n!=`string`&&typeof n!=`number`&&typeof n!=`boolean`?`unevaluable`:Us(e.value).test(String(n))?`match`:`no-match`}function tl(e,t){return t.some(t=>{let n=Jc(t);return(n.argPattern===void 0||n.argPattern===`*`||n.argPattern===`**`)&&Qc(n.toolName,e)})}function nl(e){return Q.get(e)?.argument?.key}function rl(e,t){let n=nl(e);if(n===void 0)return;let r=t[n];return typeof r==`string`?r:void 0}function il(e,t,n,r=`allow`){return n.some(n=>ol(e,t,n,r)===`match`)}function al(e,t,n){return n.some(n=>ol(e,t,n,`deny`)===`unevaluable`)}function ol(e,t,n,r){let i=Jc(n);if(!Qc(i.toolName,e))return`no-match`;if(i.argPattern===void 0||i.argPattern===`*`||i.argPattern===`**`)return`match`;let a=$c(e,i.argPattern);if(a===`primary`)return`unevaluable`;if(a!==void 0)return r===`deny`?el(a,t):`no-match`;let o=Q.get(e)?.argument;if(o===void 0)return`unevaluable`;let s=rl(e,t);if(s===void 0)return`no-match`;switch(o.kind){case`url`:return oc(i.argPattern,s);case`path`:return Js(i.argPattern,s);case`command`:return Ws(i.argPattern,s,r);case`text`:return Us(i.argPattern).test(s)?`match`:`no-match`;default:{let e=o.kind;throw Error(`unknown argument kind: ${String(e)}`)}}}function sl(e,t,n){let r=Q.get(e),i=r?.argument;if(i===void 0)return!1;let a=t[i.key];return typeof a==`string`?i.kind===`command`?xc(a,n):i.kind===`path`&&r?.riskClass===`modify`&&pc(a):!1}function cl(e,t,n,r){return il(e,t,n,`deny`)||al(e,t,n)||sl(e,t,r)}function ll(e,t,n={},r={}){return al(e,t,n.deny??[])||cl(e,t,n.ask??[],r)}const ul=[`workingDirectory`,`cwd`];function dl(e,t,n){let r=Q.get(e);if(r?.riskClass!==`execute`||r.argument?.kind!==`command`)return r?.riskClass;let i=t[r.argument.key];return typeof i==`string`&&qc(i,{otherDirectory:ul.some(e=>t[e]!==void 0),...n.resolveInWorkspace===void 0?{}:{resolveInWorkspace:n.resolveInWorkspace}})?`inspect`:r.riskClass}function fl(e,t,n,r={},i={}){let{allow:a=[],deny:o=[],ask:s=[]}=r,c=dl(e,t,i),l=n===`plan`&&c!==`inspect`?`deny`:`approve`;return il(e,t,o,`deny`)||i.ceiling!==void 0&&!il(e,t,i.ceiling)||Q.get(e)?.repliesToPeer===!0&&i.peerTurn!==!0||Q.get(e)?.notInPeerTurn===!0&&i.peerTurn===!0?`deny`:al(e,t,o)?n===`plan`?`deny`:`approve`:cl(e,t,s,i)||i.askAll===!0?l:n===`bypassPermissions`||il(e,t,a)||i.sandboxAutoApproved===!0&&c===`execute`&&(n==="default"||n===`acceptEdits`||n===`auto`)?`auto`:c===void 0?cc[n]:sc[n][c]}function pl(e,t={}){let n=t.taskDeny??[];switch(e){case`deny`:return{ceiling:[],askAll:!1,allow:[],deny:n};case`prompt`:return{askAll:!0,allow:[],deny:n};case`preapproved`:{let e=t.taskAllow??[];return{ceiling:e,askAll:!1,allow:e,deny:n}}case`inherit-allowlist`:return{ceiling:t.parentAllow??[],askAll:!1,allow:[],deny:n};default:throw Error(`unknown permission policy: ${String(e)}`)}}const ml=/^[A-Za-z_]\w*:(?!\/\/)/;function hl(e){return e.slice(0,e.indexOf(`*`)).includes(`__`)}function gl(e,t=`deny`){let n=e.trim();if(n===``)return`is empty`;if(n.includes(`(`)&&!n.endsWith(`)`))return`opens "(" without closing it`;let{toolName:r,argPattern:i}=Jc(n);if(r===``)return`names no tool`;if(t===`allow`&&r.includes(`*`)&&!hl(r))return`globs the tool name without a literal "<server>__" prefix, which an allow rule may not do`;if(i===void 0||i===`*`||i===`**`)return;if(i===``)return`has an empty argument pattern; write Tool or Tool(*) instead`;if(r.includes(`*`))return t===`allow`&&ml.test(i)?`matches a named parameter, which only deny and ask rules may do`:void 0;let a=$c(r,i);if(a!==void 0&&a!==`primary`)return t===`allow`?`matches a named parameter, which only deny and ask rules may do`:void 0;let o=Zc(r);if(!(o.parameters===void 0&&ml.test(i)&&$c(r,i)===void 0)){if(o.argument===void 0)return o.riskClass===void 0?void 0:`tool "${r}" declares no argument key, so an argument-scoped pattern can never be evaluated`;if(o.argument.kind===`url`&&oc(i,`https://probe.invalid/`)===`unevaluable`)return`does not fit the URL pattern grammar scheme://host[:port][/path] that "${r}" is matched by`}}function _l(e,t=`deny`){let n=[];for(let r of e){let e=gl(r,t);e!==void 0&&n.push({pattern:r,reason:e})}return n}function vl(e){let t=[];for(let n of e){let{toolName:e,argPattern:r}=Jc(n.trim());if(r===void 0||e.includes(`*`))continue;let i=Zc(e),a=$c(e,r);if(a===void 0&&i.parameters!==void 0&&i.argument?.kind!==`url`&&ml.test(r)){t.push({pattern:n,reason:`names no parameter of "${e}" (${i.parameters.join(`, `)}), so it is read as an ordinary argument pattern`});continue}if(a!==`primary`)continue;let o=Zc(e).argument?.key??``;t.push({pattern:n,reason:`names "${e}"'s primary field "${o}", so it asks on every call; write ${e}(${r.slice(o.length+1)}) instead`})}return t}function yl(e){return(e??[]).map(e=>`${e}(*)`)}function bl(e,t){let n=yl(t.allowedTools),r=_l(n,`allow`);if(r.length>0){let e=r.map(({pattern:e,reason:t})=>`"${e}" ${t}`).join(`; `);throw Error(`Invalid preset allowedTools: ${e}.`)}return{allow:[...e.allow,...n],deny:[...new Set([...e.deny,...yl(t.deniedTools)])]}}const xl=[`Bash`,`Shell`,`BackgroundProcess`],Sl=[`Agent`],Cl=[...xl,...Sl,`ExecuteCommand`,`Computer`],wl=`python.node.deno.bun.ruby.perl.php.bash.sh.zsh.fish.pwsh.powershell.cmd.env.xargs.eval.exec.sudo.timeout.nohup.nice.time.command.setsid.stdbuf.watch.ssh.docker.podman.find`.split(`.`),Tl=[`npm run`,`npm run-script`,`npm exec`,`npm x`,`npx`,`pnpm`,`pnpx`,`yarn`,`bunx`,`uv run`,`uvx`,`pipx run`,`cargo run`,`go run`,`make`,`just`].map(e=>e.split(` `)),El=new Set([`run`,`run-script`,`exec`,`dlx`,`x`,`--`]);function Dl(e){return(e.split(/[\\/]/).pop()??e).replace(/(\.exe)?$/i,``).replace(/[\d.]+$/,``)}function Ol(e,t){if(e.length===0)return!0;let n=(e,n,r)=>t&&r?e.startsWith(n):e===n,r=Dl(e[0]);if(wl.some(t=>n(t,r,e.length===1)))return!0;for(let i of Tl){let a=Math.min(i.length,e.length);if(!i.slice(0,a).every((t,i)=>n(t,i===0?r:e[i],i===e.length-1)))continue;if(e.length<=i.length)return!0;let o=e.slice(i.length);for(;o.length>0&&(o[0].startsWith(`-`)||El.has(o[0]));)o=o.slice(1);return o.length===0||Ol(o,t)}return!1}function kl(e){let t=e.trim();if(!t.includes(`*`))return!1;let n=t.slice(0,t.indexOf(`*`));return Ol(n.trim().split(/\s+/).filter(e=>e.length>0),n.length>0&&!/\s$/.test(n))}function Al(e){let{toolName:t,argPattern:n}=Jc(e),r=e=>e.some(e=>Qc(t,e));return r(Sl)?!0:t.includes(`*`)?r(Cl):Cl.includes(t)||Zc(t).riskClass===`execute`?n===void 0||n.trim()===`*`||xl.includes(t)&&kl(n):!1}function jl(e){return e.filter(e=>!Al(e))}const Ml=1e6,Nl={"claude-opus-4-7":{inputPerMillion:15,outputPerMillion:75},"claude-opus-4-5":{inputPerMillion:15,outputPerMillion:75},"claude-sonnet-4-6":{inputPerMillion:3,outputPerMillion:15},"claude-sonnet-4-5":{inputPerMillion:3,outputPerMillion:15},"claude-haiku-4-5":{inputPerMillion:.8,outputPerMillion:4},"claude-3-5-sonnet-20241022":{inputPerMillion:3,outputPerMillion:15},"claude-3-5-haiku-20241022":{inputPerMillion:.8,outputPerMillion:4},"claude-3-opus-20240229":{inputPerMillion:15,outputPerMillion:75},"gpt-4o":{inputPerMillion:2.5,outputPerMillion:10},"gpt-4o-mini":{inputPerMillion:.15,outputPerMillion:.6},o1:{inputPerMillion:15,outputPerMillion:60},"o1-mini":{inputPerMillion:3,outputPerMillion:12},o3:{inputPerMillion:10,outputPerMillion:40},"o3-mini":{inputPerMillion:1.1,outputPerMillion:4.4},"deepseek-chat":{inputPerMillion:.14,outputPerMillion:.28},"deepseek-reasoner":{inputPerMillion:.55,outputPerMillion:2.19},"gemini-2.0-flash":{inputPerMillion:.1,outputPerMillion:.4},"gemini-2.0-flash-thinking":{inputPerMillion:.35,outputPerMillion:3.5},"gemini-1.5-pro":{inputPerMillion:1.25,outputPerMillion:5},"gemini-1.5-flash":{inputPerMillion:.075,outputPerMillion:.3}},Pl=[{pattern:/claude-opus/i,price:{inputPerMillion:15,outputPerMillion:75}},{pattern:/claude-sonnet/i,price:{inputPerMillion:3,outputPerMillion:15}},{pattern:/claude-haiku/i,price:{inputPerMillion:.8,outputPerMillion:4}},{pattern:/gpt-4o-mini/i,price:{inputPerMillion:.15,outputPerMillion:.6}},{pattern:/gpt-4/i,price:{inputPerMillion:2.5,outputPerMillion:10}},{pattern:/deepseek/i,price:{inputPerMillion:.14,outputPerMillion:.28}},{pattern:/gemini-2/i,price:{inputPerMillion:.1,outputPerMillion:.4}},{pattern:/gemini-1/i,price:{inputPerMillion:1.25,outputPerMillion:5}}];function Fl(e){let t=Object.hasOwn(Nl,e)?Nl[e]:void 0;if(t)return t;for(let{pattern:t,price:n}of Pl)if(t.test(e))return n}function Il(e,t,n){let r=Fl(e);if(r)return t/Ml*r.inputPerMillion+n/Ml*r.outputPerMillion}function Ll(e){let t=Fl(e);if(t)return(t.inputPerMillion+t.outputPerMillion)/2/1e3}function Rl(e,t){if(!e.matcher)return!0;if(!t)return!1;try{return new RegExp(e.matcher).test(t)}catch{return e.matcher===t}}function zl(e){if(e.tool_name)return e.tool_name;if(e.hook_event_name===`SubagentStart`||e.hook_event_name===`SubagentStop`)return e.agent_type??e.agent_id;if(e.hook_event_name===`SessionEnd`)return e.reason}async function Bl(){let[{CommandExecutor:e},{HttpExecutor:t}]=await Promise.all([import(`./command-executor-DV-H2oD6.js`).then(e=>e.n),import(`./http-executor-cWzI2svn.js`).then(e=>e.n)]);return[new e,new t]}async function Vl(e,t,n,r,i){if(!e)return{blocked:!1,stdout:``};let a=new Set,o=[],s=()=>({...a.size>0&&{unknownHookTypes:[...a].sort()},...o.length>0&&{errors:[...o]}}),c=e[t];if(!c||c.length===0)return{blocked:!1,stdout:``};let l=r??await Bl(),u=new Map;for(let e of l)u.set(e.type,e);let d=[],f=zl(n),p=-1,m,h;for(let e of c){if(!Rl(e,f))continue;let r=e.env?{...n,env:{...n.env,...e.env}}:n;for(let n of e.hooks){let e=u.get(n.type);if(!e){a.add(n.type);continue}let c=n.type===`command`&&i!==void 0?await e.execute(n,r,i):await e.execute(n,r);if(c.outcome===`deny`)return{blocked:!0,reason:c.reason||`Blocked by hook`,stdout:d.join(`
11
11
  `),...s()};if(c.outcome===`error`){o.push(c);continue}let l=le(c.stdout,t);if(d.push(...l.context),l.blockReason!==void 0)return{blocked:!0,reason:l.blockReason,stdout:d.join(`
12
12
  `),...l.permissionDecision===`deny`&&{permissionDecision:`deny`},...s()};if(l.permissionDecision!==void 0){let e=ce[l.permissionDecision];e>p&&(p=e,m=l.permissionDecision),e>=p&&l.updatedInput!==void 0&&(h=l.updatedInput)}}}let g={blocked:!1,stdout:d.join(`
13
13
  `)};m!==void 0&&(g.permissionDecision=m),h!==void 0&&(g.updatedInput=h);let{unknownHookTypes:_,errors:v}=s();return _!==void 0&&(g.unknownHookTypes=_),v!==void 0&&(g.errors=v),g}var Hl=class extends Error{guardrailName;guardrailReason;constructor(e,t){super(t),this.guardrailName=e,this.guardrailReason=t,this.name=`GuardrailBlock`}},Ul=class{type=`guardrail`;guardrails;constructor(e){this.guardrails=e instanceof Map?new Map(e):new Map(Object.entries(e))}async execute(e,t){if(e.type!==`guardrail`)return{outcome:`error`,source:`guardrail`,kind:`malformed-response`,reason:`GuardrailExecutor received a '${e.type}' definition`};if(e.guardrails){let t=e.guardrails.filter(e=>!this.guardrails.has(e));if(t.length>0)return{outcome:`deny`,source:`guardrail`,reason:`Unknown guardrail(s) referenced but not registered: ${t.join(`, `)}`}}let n=this.selectGuardrails(e.guardrails);if(n.length===0)return{outcome:`allow`,source:`guardrail`,stdout:``};try{await Promise.all(n.map(async([e,n])=>{let r;try{r=await n(t)}catch(t){throw new Hl(e,`Guardrail "${e}" errored: ${t instanceof Error?t.message:String(t)}`)}if(!r.pass)throw new Hl(e,r.reason??`Guardrail "${e}" blocked the turn`)}))}catch(e){if(e instanceof Hl)return{outcome:`deny`,source:`guardrail`,reason:e.guardrailReason};throw e}return{outcome:`allow`,source:`guardrail`,stdout:``}}selectGuardrails(e){if(!e)return[...this.guardrails.entries()];let t=[];for(let n of e){let e=this.guardrails.get(n);e&&t.push([n,e])}return t}};function $(e){return{posture:`advisory`,enforcementReachable:!1,rationale:`Fire-and-forget at ${e}: the result is never awaited, so no posture can be honoured here.`}}function Wl(e,t){return{posture:`advisory`,enforcementReachable:!1,rationale:`Awaited at ${e} but only ${t} is read; \`blocked\` is never consulted.`}}function Gl(e){for(let t of Object.values(e))Object.freeze(t);return Object.freeze(e)}const Kl=Gl({PreToolUse:{posture:`enforcing`,enforcementReachable:!0,rationale:"The tool-execution gate. `runPreToolHook` awaits the result and turns `blocked` into a denial, so a hook that reached no verdict must not read as approval (tracker issue #2075)."},SessionEnd:Wl(`session-lifecycle.ts`,`nothing`),PreCompact:Wl(`compaction-orchestrator.ts`,`nothing`),UserPromptSubmit:Wl(`session-run.ts`,"`stdout`"),PostToolUse:$(`tool-hook-helpers.ts`),SessionStart:$(`session-lifecycle.ts`),PostCompact:$(`session-history-ops.ts`),Stop:$(`session-run.ts`),StopFailure:$(`session-run.ts`),SubagentStart:$(`background-task-hooks.ts`),SubagentStop:$(`background-task-hooks.ts`),WorktreeCreate:$(`worktree-subagent-runner.ts`),WorktreeRemove:$(`worktree-subagent-runner.ts`),PreModelCall:$(`session-run.ts`),PostModelCall:$(`session-run.ts`),PermissionDecision:$(`permission-enforcer.ts`)});function ql(e){return Kl[e].posture===`enforcing`}export{A as AGENT_EVENTS,j as AGENT_EVENT_PREFIX,xt as AbstractAIProvider,qe as AbstractAgent,Cr as AbstractEventService,Mt as AbstractExecutor,Je as AbstractManager,jt as AbstractPlugin,Nt as AbstractTool,$o as AgentFactory,Jo as AgentTemplates,E as AuthenticationError,Ie as CONFIRM_NO,Fe as CONFIRM_YES,ri as CONTEXT_ESTIMATE_CHARS_PER_TOKEN,C as CacheIntegrityError,b as CircuitBreakerOpenError,y as ConfigurationError,mt as ConsoleLogger,Qn as ConversationHistory,Zn as ConversationStore,Tr as DEFAULT_ABSTRACT_EVENT_SERVICE,Ns as DEFAULT_BACKGROUND_PERMISSION_POLICY,fi as DEFAULT_CONTEXT_WINDOW,vi as DEFAULT_MAX_OUTPUT,ms as DEFAULT_TOOL_RESULT_HARD_CHARS,ps as DEFAULT_TOOL_RESULT_WARNING_CHARS,Vr as DEFERRED_WITHOUT_LOADER_MESSAGE,wr as DefaultEventService,In as ENV_REFERENCE_PREFIX,L as EVENT_EMITTER_EVENTS,M as EXECUTION_EVENTS,N as EXECUTION_EVENT_PREFIX,Ht as ErrorUtils,pr as EventEmitterPlugin,Ts as EventHistoryModule,ks as ExecutionProxy,zr as FunctionTool,Ul as GuardrailExecutor,ir as InMemoryEventEmitterMetrics,tr as LocalExecutor,hs as MAX_TOOL_RESULT_CHARS,_e as MODEL_EFFORT_VALUES,Nl as MODEL_PRICES,It as MessageConverter,p as ModelNotAvailableError,ie as NetworkError,Es as ORCHESTRATION_EVENTS,Ds as ORCHESTRATION_EVENT_PREFIX,jr as ObservableEventService,s as PARAMETER_SCHEMA_KEYWORDS,r as PERMISSIVE_TOOL_SCHEMA_PROFILE,lc as PROTECTED_DIRECTORY_NAMES,uc as PROTECTED_FILE_NAMES,Nr as PROVIDER_CALL_EVENTS,Pr as PROVIDER_FALLBACK_EVENTS,wt as PluginCategory,se as PluginError,Tt as PluginPriority,h as ProviderError,sc as RISK_CLASS_POLICY,oe as RateLimitError,fs as Robota,d as RobotaError,Mr as SPAN_EVENTS,Rr as SPAN_EVENT_PREFIX,a as STRICT_TOOL_SCHEMA_PROFILE,c as SameToolInputLoopError,ft as SilentLogger,ae as StorageError,kr as StructuredEventService,f as StructuredOutputError,Oi as TASK_EVENTS,ki as TASK_EVENT_PREFIX,Ir as TOOL_BODY_EVENTS,P as TOOL_EVENTS,F as TOOL_EVENT_PREFIX,Lr as TOOL_PERMISSION_EVENTS,n as TOOL_SCHEMA_PROJECTION_MAX_DEPTH,e as TOOL_SCHEMA_PROJECTION_MAX_NODES,Pe as TOOL_SEARCH_TOOL_NAME,Ms as TRUST_TO_MODE,u as ToolExecutionError,hr as ToolRegistry,vs as ToolResultAdmissionError,fe as TypeUtils,cc as UNCLASSIFIED_TOOL_FALLBACK,Ai as USER_EVENTS,ji as USER_EVENT_PREFIX,_ as UnsupportedShellError,l as ValidationError,R as Validator,ws as admitToolResult,jl as allowRulesForAutoMode,bl as applyPresetToolLists,me as assertProviderNativeWebToolsAvailable,Wr as assertResidentToolRemains,Ar as bindEventServiceOwner,q as bindWithOwnerPath,w as buildTraceparent,Il as calculateModelCost,et as chatEntryToMessage,an as classifyProviderFailure,Xc as clearRegisteredToolProfiles,t as closeObjectSchemas,ko as collectAssistantUsageMetadata,Dr as composeEventName,Re as confirmAction,qn as createAssistantMessage,ne as createBoundedOutput,pe as createDefaultProviderCapabilities,As as createExecutionProxy,Pn as createImageProviderFromDefinition,O as createLogger,ye as createModelEffortOutcome,Hn as createProviderFromConfig,jn as createRecordEnvResolver,Jn as createSystemMessage,Yn as createToolMessage,Kn as createUserMessage,Fn as createVideoProviderFromDefinition,ue as decodeHookVerdict,Ll as estimateBlendedCostPer1000,oi as estimateContextTokensFromMessages,ii as estimateSerializedContextTokens,ai as estimateToolSchemaTokens,fl as evaluatePermission,pn as extractEnumValues,_l as findInvalidPermissionPatterns,Ne as findMediaProviderDefinition,gi as findModelDefinition,vl as findPermissionPatternWarnings,we as findProviderDefinition,Rn as formatEnvReference,Te as formatSupportedProviderTypes,xi as formatTokenCount,Or as generateSpanId,_t as getGlobalLogLevel,yt as getGlobalLoggerSink,nt as getMessagesForAPI,_i as getModelContextWindow,yi as getModelMaxOutput,bi as getModelName,Ce as getProviderCapabilities,Ee as getProviderCredentialRequirement,hn as getSchemaTypeName,We as getToolEstimatedDuration,Ge as getToolExecutionSteps,Zc as getToolPermissionProfile,Bn as hasUsableSecretReference,mn as hasValidationConstraints,i as hashToolSchema,Ft as isAbortFailure,it as isAssistantMessage,Al as isBroadExecutionAllowRule,D as isChatEntry,He as isConfirmed,Er as isDefaultEventService,ql as isEnforcing,Ln as isEnvReference,Ae as isImageGenerationProvider,Me as isMediaProviderDefinition,ee as isMintedSpanId,ve as isModelEffort,Ue as isProgressReportingTool,pc as isProtectedPath,qc as isReadOnlyCommandLine,Xo as isRegistryTransactionError,at as isSystemMessage,tl as isToolDeniedOutright,ot as isToolMessage,rt as isUserMessage,je as isVideoGenerationProvider,Yo as lifecycleOf,k as logger,Fl as lookupModelPrice,il as matchesAnyPattern,tt as messageToHistoryEntry,Oe as modelDeclaresCapability,Be as multiSelectAction,Vn as normalizeProviderConfig,wn as normalizeStructuredOutput,x as outboundTraceContextFor,$c as parseParameterRule,On as parseStructuredResponseText,uo as peerDriverOf,fo as printablePeerDriver,G as processEnvResolver,pl as projectPermissionPolicy,o as projectToolSchema,m as providerCallSpanId,Fr as readModelFallbackNotice,Yt as readProviderFailureDetails,Xr as readTokenUsageFromMessage,Zr as readTokenUsageFromMetadata,mi as registerModelMetadata,Yc as registerToolPermissionProfile,xc as removesCriticalPath,ll as requiresFreshApproval,zn as resolveEnvReference,Nn as resolveMediaProviderConfig,De as resolveModelCapabilities,ke as resolveModelCapability,Se as resolveModelEffort,v as resolvePlatformShell,An as resolveStructuredOutputCapability,Vl as runHooks,Zo as runRegistryTransaction,ze as selectAction,gt as setGlobalLogLevel,vt as setGlobalLoggerSink,Ke as setToolProgressCallback,rr as shellArgumentForDisplay,T as spanIdFromMintedId,Fs as splitCommandSegments,on as startPeriodicTask,sn as stopPeriodicTask,te as subprocessTraceEnvironment,Do as sumHistoryUsage,Ve as textAction,Qt as toProviderError,Qc as toolNameMatches,yl as toolNamesToPatterns,g as toolTraceContextFor,S as traceEnvFor,re as traceHeadersFor,W as validateAgainstJsonSchema,Lt as validateAgentConfig,Vt as validateApiKey,Bt as validateModelName,gl as validatePermissionPattern,zt as validateProviderName,Rt as validateUserInput,ys as wasToolResultAdmitted,js as withEventEmission,gn as zodToJsonSchema};