@robota-sdk/agent-cli 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 @@ var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=
7
7
 
8
8
  `),n.beginAssistant();let b=Ma(),{wrappedOnTextDelta:x,wrappedOnProviderNativeRawPayload:S}=wa(a,n,i,p),C=na(s,o.defaultModel.model,i),w=await Ta(_,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}=ua(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 Y(l,`afterProviderCall`,{messages:m,responseMessage:w},u),await Y(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=Na(T),D=te?.inputTokens??0;D>0&&(e.cumulativeInputTokens=D);for(let e of E)n.appendToolCall(e);let O=a.signal?.aborted?`interrupted`:`complete`;n.commitAssistant(O,{round:p,usageObservationId:b,executionId:i,providerId:X(C,s),modelId:Z(C,s.aiProviderInfo.model),...te??{}});let k=n.getMessages().at(-1);if(a.onExecutionEvent?.(`assistant_message_committed`,{executionId:i,conversationId:a.conversationId,round:p,message:T}),k&&a.onExecutionEvent?.(`history_mutation`,{executionId:i,conversationId:a.conversationId,round:p,mutation:`append_message`,index:n.getMessages().length-1,message:k}),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 A=await Aa(E,n,r,i,p,v,y,e,c,o,a.signal,a.onExecutionEvent,a.maxSameToolInputs??o.maxSameToolInputs,a.traceContext);if(A.contextOverflowed&&u.warn(`[ROUND] Tool results partially skipped due to context overflow — continuing to let AI respond`,{added:A.addedCount,skipped:A.skippedCount,round:p}),A.unknownToolFailureCount>0?e.consecutiveUnknownToolFailureRounds+=1:e.consecutiveUnknownToolFailureRounds=0,e.consecutiveUnknownToolFailureRounds>=2){let t=[...new Set(A.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 Fa(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 Ia(e,t){return t===0||e<t}async function La(e,t,n,r,i,a,o,s,c){let l=Fa(i,r);for(;Ia(o.currentRound,l)&&!(s?.aborted||(o.currentRound++,await Pa(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 ba(e,a,i,n,o,t,r,c.logger,l))}async function Ra(e,t,n,r,i,a,o,s,c,l,u){let d={...Ii(t,n,r,i.toolsExecuted,i.providerFailure),interrupted:o};await Y(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 Y(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(F.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*za(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 Ba(e,t){return{executionId:e,...t===void 0?{}:{driverId:t}}}var Va=class{toolExecutionService;aiProviders;tools;conversationHistory;plugins=[];logger;eventEmitter;cacheService;constructor(e,t,n,r,i,a){if(this.toolExecutionService=new Ti(t),this.aiProviders=e,this.tools=t,this.conversationHistory=n,this.plugins=[],this.logger=M(`ExecutionService`),!r)throw Error(`[EXECUTION] EventService is required`);this.eventEmitter=new Pi(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=Xi(),a=new Date,o=Zi(r,`execute`),s=Qi(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=Ki(this.aiProviders,this.tools,n);this.eventEmitter.emitExecutionStartEvent(e,n,t,c,o,i);let l=Ji(this.conversationHistory,o,t,n,i);try{let t=l.getMessages().length;l.addUserMessage(e,Ba(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 Y(this.plugins,`beforeRun`,{input:e,...r?.metadata?{metadata:r.metadata}:{}},this.logger);let d={executionId:i,conversationId:o};u&&await Y(this.plugins,`onMessageAdded`,{message:u,executionContext:d},this.logger),await Y(this.plugins,`beforeExecution`,{messages:l.getMessages(),executionContext:d},this.logger),qi(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 La(l,o,i,s,n,c,f,r?.signal,{toolExecutionService:this.toolExecutionService,plugins:this.plugins,logger:this.logger,eventEmitter:this.eventEmitter,cacheService:this.cacheService}),Ra(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 Yi(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*za(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 Ha(e){let t=new ti;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 Ua(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 ut&&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 rr(e.schema.name,r)}),l.debug(`Tool registered during initialization`,{toolName:e.schema.name});let u;t.cache?.enabled&&(u=new ii(new ri({maxEntries:t.cache.maxEntries,ttlMs:t.cache.ttlMs}),new ni));let d=new Va(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 Wa(e){try{let t=await Ua(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 Ga(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 Ka(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 qa=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 Ja(e){return{maxConcurrentAgents:e.maxConcurrentAgents||100,defaultSystemMessage:e.defaultSystemMessage??``,strictValidation:e.strictValidation??!0,idFactory:e.idFactory??Xa,...e.defaultModel!==void 0&&{defaultModel:e.defaultModel},...e.defaultProvider!==void 0&&{defaultProvider:e.defaultProvider}}}function Ya(e,t){if(!e.aiProviders||e.aiProviders.length===0)throw new u.S(`At least one AI provider must be specified in aiProviders array`);let n=e.defaultModel,r=n?.model??t.defaultModel;if(!r)throw new u.S(`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 u.S(`No provider specified: set config.defaultModel.provider, an aiProviders entry, or the AgentFactory defaultProvider option`);return{id:e.id||Xa(),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 Xa(){return`agent_${Date.now()}_${Math.random().toString(36).substring(2,8)}`}function Za(e,t){return e.totalCreated++,e.activeCount++,t?e.fromTemplates++:e.customConfigured++,e.templateUsageRatio=e.totalCreated>0?e.fromTemplates/e.totalCreated:0,e}var Qa=class{templates=new Map;logger;constructor(){this.logger=M(`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 $a(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)}:{}}}async function eo(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 to(e,n.name,r)}t.push(n)}}function to(e,t,n){let r=e instanceof Error?e:Error(String(e));return Object.assign(r,{failedStep:t,rollbackErrors:n})}var no=class{agentTemplates;initialized=!1;logger;options;activeAgents;pendingAgents=new Set;creationStats;lifecycleEvents;constructor(e={},t={}){this.agentTemplates=new Qa,this.logger=M(`AgentFactory`),this.options=Ja(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=Ya(t,this.options);let a=r;if(this.options.strictValidation){let e=pt(r);if(!e.isValid)throw new u.v(`Invalid agent configuration: ${e.errors.join(`, `)}`)}let o;if(await eo([{name:`beforeCreate`,run:()=>this.lifecycleEvents.beforeCreate?.(a)},{name:`construct`,run:()=>{o=new e(a)}},{name:`initialize`,run:()=>o?$a(o)?.initialize?.():void 0,undo:()=>o?$a(o)?.cleanup?.():void 0},{name:`commit`,run:()=>{if(!o)throw new u.S(`Agent was not constructed`);this.activeAgents.set(i,o),Za(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 u.S(`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 u.S(`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 u.S(`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 u.S(`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 $a(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 pt(e)}};function ro(e,t,n){if(!e.name||e.name.trim()===``)throw new u.S(`Module name is required`);if(!e.version||e.version.trim()===``)throw new u.S(`Module version is required`);let r=e.getModuleType(),i=t.validateTypeDescriptor(r);if(!i.valid)throw new u.S(`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 io(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 u.S(`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 ao(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 oo(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 so(){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 co(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 lo(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 uo(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 fo(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 po=class{registeredTypes=new Map;logger;constructor(){this.logger=M(`ModuleDescriptorRegistry`),this.registerBuiltinTypes()}registerType(e){let t=this.validateTypeDescriptor(e);if(!t.valid)throw new u.S(`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 u.S(`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 co(e,e=>this.getType(e))}resolveDependencies(e){return lo(e,e=>this.getType(e),e=>this.hasType(e))}checkCompatibility(e){return uo(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 so())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 fo(this.registeredTypes)}};const mo={REGISTERED:`module.registered`,UNREGISTERED:`module.unregistered`};var ho=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 po,this.logger=M(`ModuleRegistry`)}async registerModule(e,t={}){if(this.isDisposing)throw new u.S(`Cannot register modules during disposal`);if(ro(e,this.typeRegistry,this.logger),this.modules.has(e.name))throw new u.S(`Module with name '${e.name}' is already registered`,{moduleName:e.name});t.validateDependencies!==!1&&await io(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(mo.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=ao(e,this.modules);if(n.length>0)throw new u.S(`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(mo.UNREGISTERED,{data:{moduleName:e},timestamp:new Date}),!0}async initializeModule(e,t){let n=this.modules.get(e);if(!n)throw new u.S(`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 u.S(`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 u.S(`Module '${e}' not found`);if(!n.isInitialized())throw new u.S(`Module '${e}' is not initialized`);if(!n.isEnabled())throw new u.S(`Module '${e}' is disabled`);let r=this.moduleStats.get(e),i=Date.now();try{if(!n.execute)throw new u.S(`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 oo(this.modules,this.moduleStats)}},go=class extends nr{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=Mr(e);let t=e.logging?.enabled===!1?`silent`:e.logging?.level;this.logger=M(`Robota`,t?{level:t}:{}),this.startTime=Date.now(),ir(e),this.aiProviders=Ha(e),this.tools=Nr(()=>this.config),this.agentFactory=new no,this.conversationHistory=new mn,this.eventEmitter=zr(),this.moduleRegistry=new ho(this.eventEmitter),this.eventService=e.eventService||Rn,this.agentEventService=J(this.eventService,{ownerType:`agent`,ownerId:this.conversationId,ownerPath:Br(this.conversationId,this.config.executionContext)});let n=Ir({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,Lr(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=[...Br(this.conversationId,this.config.executionContext),{type:`tool`,id:n.executionId??e}];return this.executionService.invokeRuntimeTool(e,t,{...n,baseEventService:this.eventService,eventService:J(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=Wt(t.output);return await Kr(this.executionDeps(),e,t,n)}return await Hr(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=Wt(t.output);return yield*qr(this.executionDeps(),e,t,n)}return yield*Ur(this.executionDeps(),e,t)}finally{this.resetEphemeralHistory(),n()}}resetEphemeralHistory(){this.config.retainHistory===!1&&this.clearHistory()}runQueue=new qa;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 Yr(this.conversationHistory,this.conversationId)}getFullHistory(){return Xr(this.conversationHistory,this.conversationId)}addHistoryEntry(e){Zr(this.conversationHistory,this.conversationId,e)}clearHistory(){Qr(this.conversationHistory,this.conversationId)}injectMessage(e,t,n){$r(this.conversationHistory,this.conversationId,e,t,n)}injectRawMessage(e){ei(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 Ga({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,Ka({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 Wa({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){Rr(this.agentEventService,this.conversationId,this.config.executionContext,e,t)}};const _o=/^tool-result:[A-Za-z0-9_-]{22,64}$/u,vo=Symbol.for(`@robota-sdk/tool-result-admitted`);var yo=class extends Error{code;constructor(e){super(`Tool result admission failed (${e})`),this.code=e,this.name=`ToolResultAdmissionError`}};function bo(e){return Object.getOwnPropertyDescriptor(e,vo)?.value===!0}function xo(e){return Object.defineProperty({...e},vo,{value:!0})}function So(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 Co(e){return Number.isSafeInteger(e)&&e>0}function wo(e,t){let n=e.warningChars??1e4,r=e.hardChars??25e3,i=e.repositoryMaxChars??5e5;if(!Co(n)||!Co(r)||!Co(i)||n>=r||r>i||i>5e5)throw new yo(`invalid-policy`);if(t===void 0)return{warningChars:n,hardChars:r};if(!Co(t))throw new yo(`invalid-override`);return{warningChars:n,hardChars:Math.max(r,Math.min(t,i))}}async function To(e,t,n={},r){let{warningChars:i,hardChars:a}=wo(n,r),o=So(t),s=o.length;if(s>i&&n.onWarning?.({toolName:e,resultChars:s,warningChars:i}),s>a){if(!n.spillStore)throw new yo(`spill-unavailable`);let e;try{e=(await n.spillStore.write(o)).reference}catch{throw new yo(`spill-write-failed`)}if(!_o.test(e)||e.length>a)throw new yo(`invalid-reference`);return xo(t.success?{success:!0,data:e}:{success:!1,error:`Tool failure details: ${e}`})}return xo(t)}const Eo={safe:`plan`,moderate:`default`,full:`acceptEdits`};function Do(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 Oo(e){let t={segments:[],current:``,quote:void 0,substitutionDepth:0};for(let n=0;n<e.length;n+=1){let r=Ao(t,e,n);if(r!==void 0){n=r;continue}let i=jo(t,e,n);if(i!==void 0){n=i;continue}if(Mo(t,e[n]))continue;let a=No(t,e,n);if(a!==void 0){n=a;continue}t.current+=e[n]}return ko(t),t.segments}function ko(e){let t=e.current.trim();t!==``&&e.segments.push(t),e.current=``}function Ao(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 jo(e,t,n){let r=t[n];if(r==="`")return ko(e),n;if(r===`$`&&t[n+1]===`(`)return ko(e),e.substitutionDepth+=1,n+1}function Mo(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 No(e,t,n){let r=t[n];if((r===`<`||r===`>`)&&t[n+1]===`(`)return ko(e),e.substitutionDepth+=1,n+1;if(r===`)`&&e.substitutionDepth>0)return ko(e),--e.substitutionDepth,n;if(r===`;`||r===`|`||r===`
10
- `||r===`&`&&Po(t,n))return ko(e),n}function Po(e,t){let n=e[t-1];return n!==`>`&&n!==`<`&&e[t+1]!==`>`}const Fo=/[.+^${}()|[\]\\]/g;function Io(e){let t=e.replace(Fo,`\\$&`).replace(/\*\*/g,`.+`).replace(/\*/g,`.*`);return RegExp(`^${t}$`)}function Lo(e,t,n){let r=Io(e);return n===`deny`?r.test(t)||Oo(t).some(e=>r.test(e))?`match`:`no-match`:r.test(t)?e.includes(`*`)&&Do(t)?`no-match`:`match`:`no-match`}function Ro(e){let t=e.replace(/\*\*(?:\/\*\*)+/g,`**`).split(/(\/\*\*\/|\/\*\*$|^\*\*\/|\*\*)/).map(e=>e===`/**/`?`(?:/.*)?/`:e===`/**`?`(?:/.*)?`:e===`**/`?`(?:.*/)?`:e===`**`?`.*`:e.replace(Fo,`\\$&`).replace(/\*/g,`[^/]*`).replace(/\uE000/g,`\\*`)).join(``);return RegExp(`^${t}$`)}function zo(e){return e.startsWith(`/`)||/^[A-Za-z]:(?=\/|$)/.test(e)}function Bo(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 Vo(e,t){let n=Bo(e),r=Bo(t);return zo(n)&&!zo(r)?`unevaluable`:Ro(n).test(r)?`match`:`no-match`}const Ho=/^(\*|[a-z][a-z0-9+.-]*):\/\/(\[[0-9a-fA-F:.]+\]|[^/\\:?#@[\]]+)(?::(\d+|\*))?(\/[^?#]*)?$/i,Uo=new Set([`http`,`https`,`ws`,`wss`,`ftp`]),Wo={http:`80`,https:`443`,ws:`80`,wss:`443`,ftp:`21`};function Go(e){return e.replace(/\.$/,``).toLowerCase()}function Ko(e){try{let t=new URL(`http://${e}/`).hostname;return t===``||t.includes(`.`)?null:t}catch{return null}}function qo(e){let t=Go(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(Fo,`\\$&`).replace(/\*/g,`[^.]*`)}`);else{let e=Ko(i);if(e===null)return null;n.push(`${c}${e.replace(Fo,`\\$&`)}`)}}return RegExp(`^${n.join(``)}$`)}function Jo(e){try{let t=e.split(`/`).map(e=>decodeURIComponent(e));return t.some(e=>e.includes(`/`))?null:t.join(`/`)}catch{return null}}function Yo(e){let t;try{t=new URL(e)}catch{return null}let n=t.protocol.slice(0,-1).toLowerCase();return!Uo.has(n)||t.hostname===``||t.username!==``||t.password!==``?null:t}function Xo(e,t){if(e.includes(`*`)){let n=qo(e);return n===null?`unevaluable`:n.test(t)?`match`:`no-match`}let n;try{n=new URL(`http://${e}/`).hostname}catch{return`unevaluable`}return Go(n)===t?`match`:`no-match`}function Zo(e,t,n){return e===void 0?t.port===``:e===`*`||e===(t.port===``?Wo[n]:t.port)}function Qo(e,t){let n=Jo(t),r=Jo(e.replace(/%2a/gi,``));return n===null||r===null?`unevaluable`:Ro(r).test(n)?`match`:`no-match`}function $o(e,t){let n=Ho.exec(e);if(n===null)return`unevaluable`;let[,r,i,a,o]=n,s=Yo(t);if(s===null)return`unevaluable`;let c=s.protocol.slice(0,-1).toLowerCase();if(r!==`*`&&r.toLowerCase()!==c)return`no-match`;let l=Xo(i,Go(s.hostname));return l===`match`?Zo(a,s,c)?o===void 0?`match`:Qo(o,s.pathname):`no-match`:l}const es={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`}},ts={plan:`deny`,default:`approve`,acceptEdits:`approve`,bypassPermissions:`auto`,auto:`approve`},ns=[`.git`,`.robota`,`.claude`,`.agents`],rs=[`.mcp.json`,`.gitconfig`,`.npmrc`,`.bashrc`,`.bash_profile`,`.bash_login`,`.zshrc`,`.zshenv`,`.zprofile`,`.profile`];function is(e){return e.replace(/\\/g,`/`).split(`/`).filter(e=>e!==``&&e!==`.`)}function as(e){let t=[];for(let n of is(e))n===`..`&&t.length>0&&t[t.length-1]!==`..`?t.pop():t.push(n);return t}function os(e){let t=as(e),n=t[t.length-1];if(n!==void 0&&rs.includes(n))return!0;for(let e=0;e<t.length;e+=1){let n=t[e];if(ns.includes(n)){if((n===`.robota`||n===`.claude`)&&t[e+1]===`worktrees`&&t[e+2]!==void 0){e+=2;continue}return!0}}return!1}function ss(e){let t=[];for(let n of is(e))n===`..`?t.pop():t.push(n);return`/${t.join(`/`)}`}function cs(e){return e.replace(/^(['"])(.*)\1$/,`$2`)}const ls=/^(?:~|\$HOME|\$\{HOME\})(?=\/|$)(.*)$/;function us(e,t){let n=cs(e),r=ls.exec(n),i;if(r!==null){let e=r[1]??``;if(t.homeDirectory===void 0)return e.replace(/\/+/g,``)===``;i=ss(`${t.homeDirectory}/${e}`)}else if(n===``||n.startsWith(`$`))return!1;else if(n.startsWith(`/`))i=ss(n);else{if(t.cwd===void 0)return!1;i=ss(`${t.cwd}/${n}`)}if(is(i).length<=1||t.homeDirectory!==void 0&&i===ss(t.homeDirectory))return!0;if(t.cwd!==void 0){let e=ss(t.cwd);if(e===i||e.startsWith(`${i}/`))return!0}return!1}const ds=new Set([`rm`,`rmdir`]),fs=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 ps(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=fs.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 ms(e,t){return Oo(e).some(e=>{let n=e.split(/\s+/).filter(e=>e!==``),r=ps(n),i=n[r];if(i===void 0)return!1;let a=i.slice(i.lastIndexOf(`/`)+1);if(!ds.has(a))return!1;let o=!1;return n.slice(r+1).some(e=>!o&&e===`--`?(o=!0,!1):!o&&e.startsWith(`-`)?!1:us(e,t))})}const hs=new Set([`ls`,`cat`,`echo`,`pwd`,`head`,`tail`,`grep`,`wc`,`which`,`stat`,`du`,`cd`]),gs=new Set([`-exec`,`-execdir`,`-ok`,`-okdir`,`-delete`,`-fprint`,`-fprint0`,`-fprintf`,`-fls`]),_s={ls:`aAlhtrSR1dFGinpsucCgmoQvx`,cat:`nbsvetAE`,head:`nqvc`,tail:`nqvcfF`,grep:`rinlLvcwxEFGPHhoqsABCmz`,wc:`lwcmL`,stat:`cftx`,du:`hsacdkmx`,which:`a`,pwd:`LP`,cd:`LP`},vs=/^--?[A-Za-z0-9-]*(file|from|contents)(=|$)/,ys=[`--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 bs(e){if(!e.startsWith(`--`)||e.length<=2)return!1;let t=e.split(`=`,1)[0];return ys.some(e=>e.startsWith(t))}function xs(e,t){if(Ns(t).some(e=>vs.test(e.text)||bs(e.text)))return!0;if(e===`find`)return Ns(t).some(e=>e.text===`-L`||e.text===`-follow`);let n=_s[e];return n!==void 0&&Ns(t).some(({text:e})=>e.startsWith(`--`)||!/^-[A-Za-z]/.test(e)?!1:[...e.slice(1)].some(e=>!/\d/.test(e)&&!n.includes(e)))}const Ss=new Set([`status`,`log`,`diff`,`show`,`rev-parse`,`ls-files`,`describe`,`branch`,`remote`]),Cs=new Set([`-l`,`--list`,`--show-current`,`--merged`,`--no-merged`,`--contains`,`--no-contains`,`--points-at`]),ws=new Set([`-a`,`--all`,`-r`,`--remotes`,`-v`,`-vv`,`--verbose`,`--color`,`--no-color`]),Ts=new Set([`/dev/null`]),Es=/[A-Za-z0-9_./:=@+,*?[\]~-]/,Ds=new Set([`$`,"`",`\\`,`!`]),Os=new Set([`*`,`?`,`[`]);function ks(e){return/(^|[=,:])[/~]/.test(e)||/^-[A-Za-z]+[/~]/.test(e)||/(^|[/=,:]|^-[A-Za-z]+)\.\.(\/|$)/.test(e)||/(^|[=,])[A-Za-z][A-Za-z0-9]*:/.test(e)||As(e)}function As(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 js(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 Ms(e){let t=[],n=``,r=!1,i=!1,a,o,s=!1,c=()=>{i&&=(o===`output`?(!Ts.has(n)||r)&&(s=!0):o===`duplicate`?/^(\d+|-)$/.test(n)||(s=!0):o===`input`?(r||ks(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:Ds.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(!Es.test(l)){s=!0;break}Os.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 Ns(e){let t=e.findIndex(e=>e.text===`--`);return(t<0?e:e.slice(0,t)).filter(e=>e.text.startsWith(`-`))}function Ps(e){return e.every(e=>!e.expands&&!gs.has(e.text))}function Fs(e){let t=e.filter(e=>e.text.startsWith(`-`)),n=t.some(e=>Cs.has(e.text));return t.every(e=>Cs.has(e.text)||ws.has(e.text))&&(n||t.length===e.length)}function Is(e){let[t,...n]=e[0]?.text===`--no-pager`?e.slice(1):e;return t===void 0||t.expands||!Ss.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`?Fs(n):t.text!==`remote`||n.every(e=>e.text===`-v`||e.text===`--verbose`)}function Ls(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=>ks(e.text))||xs(t.text,n)?!1:t.text===`cd`?n.length===1&&n[0].text!==`-`&&!n[0].expands:hs.has(t.text)?!0:t.text===`find`?Ps(n):t.text===`git`&&Is(n)}const Rs=new Set([`echo`,`which`,`git`]);function zs(e,t){let n;for(let[r,...i]of e)if(!Rs.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 Bs(e,t={}){if(t.otherDirectory===!0||e.length>1e4||js(e)||/[^\t\n\x20-\x7e]/.test(e))return!1;let n=Oo(e);if(n.length===0)return!1;let r=n.map(Ms);if(r.some(e=>e.refused||!Ls(e.words)))return!1;let i=r.map(e=>e.words[0].text);return i.includes(`git`)&&i.includes(`cd`)?!1:zs(r.map(e=>e.words),t.resolveInWorkspace)}function Vs(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 Hs(e,t){Q.set(e,{...Q.get(e),...t})}function Us(e){return Q.get(e)??{}}function Ws(e,t){let n=[t,...Q.get(t)?.aliases??[]];if(!e.includes(`*`))return n.includes(e);let r=Io(e);return n.some(e=>r.test(e))}function Gs(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 Ks(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`:Io(e.value).test(String(n))?`match`:`no-match`}function qs(e,t){return t.some(t=>{let n=Vs(t);return(n.argPattern===void 0||n.argPattern===`*`||n.argPattern===`**`)&&Ws(n.toolName,e)})}function Js(e){return Q.get(e)?.argument?.key}function Ys(e,t){let n=Js(e);if(n===void 0)return;let r=t[n];return typeof r==`string`?r:void 0}function Xs(e,t,n,r=`allow`){return n.some(n=>Qs(e,t,n,r)===`match`)}function Zs(e,t,n){return n.some(n=>Qs(e,t,n,`deny`)===`unevaluable`)}function Qs(e,t,n,r){let i=Vs(n);if(!Ws(i.toolName,e))return`no-match`;if(i.argPattern===void 0||i.argPattern===`*`||i.argPattern===`**`)return`match`;let a=Gs(e,i.argPattern);if(a===`primary`)return`unevaluable`;if(a!==void 0)return r===`deny`?Ks(a,t):`no-match`;let o=Q.get(e)?.argument;if(o===void 0)return`unevaluable`;let s=Ys(e,t);if(s===void 0)return`no-match`;switch(o.kind){case`url`:return $o(i.argPattern,s);case`path`:return Vo(i.argPattern,s);case`command`:return Lo(i.argPattern,s,r);case`text`:return Io(i.argPattern).test(s)?`match`:`no-match`;default:{let e=o.kind;throw Error(`unknown argument kind: ${String(e)}`)}}}function $s(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`?ms(a,n):i.kind===`path`&&r?.riskClass===`modify`&&os(a):!1}function ec(e,t,n,r){return Xs(e,t,n,`deny`)||Zs(e,t,n)||$s(e,t,r)}function tc(e,t,n={},r={}){return Zs(e,t,n.deny??[])||ec(e,t,n.ask??[],r)}const nc=[`workingDirectory`,`cwd`];function rc(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`&&Bs(i,{otherDirectory:nc.some(e=>t[e]!==void 0),...n.resolveInWorkspace===void 0?{}:{resolveInWorkspace:n.resolveInWorkspace}})?`inspect`:r.riskClass}function ic(e,t,n,r={},i={}){let{allow:a=[],deny:o=[],ask:s=[]}=r,c=rc(e,t,i),l=n===`plan`&&c!==`inspect`?`deny`:`approve`;return Xs(e,t,o,`deny`)||i.ceiling!==void 0&&!Xs(e,t,i.ceiling)||Q.get(e)?.repliesToPeer===!0&&i.peerTurn!==!0?`deny`:Zs(e,t,o)?n===`plan`?`deny`:`approve`:ec(e,t,s,i)||i.askAll===!0?l:n===`bypassPermissions`||Xs(e,t,a)||i.sandboxAutoApproved===!0&&c===`execute`&&(n==="default"||n===`acceptEdits`||n===`auto`)?`auto`:c===void 0?ts[n]:es[n][c]}function ac(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 oc=/^[A-Za-z_]\w*:(?!\/\/)/;function sc(e){return e.slice(0,e.indexOf(`*`)).includes(`__`)}function cc(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}=Vs(n);if(r===``)return`names no tool`;if(t===`allow`&&r.includes(`*`)&&!sc(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`&&oc.test(i)?`matches a named parameter, which only deny and ask rules may do`:void 0;let a=Gs(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=Us(r);if(!(o.parameters===void 0&&oc.test(i)&&Gs(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`&&$o(i,`https://probe.invalid/`)===`unevaluable`)return`does not fit the URL pattern grammar scheme://host[:port][/path] that "${r}" is matched by`}}function lc(e,t=`deny`){let n=[];for(let r of e){let e=cc(r,t);e!==void 0&&n.push({pattern:r,reason:e})}return n}function uc(e){let t=[];for(let n of e){let{toolName:e,argPattern:r}=Vs(n.trim());if(r===void 0||e.includes(`*`))continue;let i=Us(e),a=Gs(e,r);if(a===void 0&&i.parameters!==void 0&&i.argument?.kind!==`url`&&oc.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=Us(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 dc(e){return(e??[]).map(e=>`${e}(*)`)}function fc(e,t){let n=dc(t.allowedTools),r=lc(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,...dc(t.deniedTools)])]}}const pc=[`Bash`,`Shell`,`BackgroundProcess`],mc=[`Agent`],hc=[...pc,...mc,`ExecuteCommand`,`Computer`],gc=`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(`.`),_c=[`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(` `)),vc=new Set([`run`,`run-script`,`exec`,`dlx`,`x`,`--`]);function yc(e){return(e.split(/[\\/]/).pop()??e).replace(/(\.exe)?$/i,``).replace(/[\d.]+$/,``)}function bc(e,t){if(e.length===0)return!0;let n=(e,n,r)=>t&&r?e.startsWith(n):e===n,r=yc(e[0]);if(gc.some(t=>n(t,r,e.length===1)))return!0;for(let i of _c){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(`-`)||vc.has(o[0]));)o=o.slice(1);return o.length===0||bc(o,t)}return!1}function xc(e){let t=e.trim();if(!t.includes(`*`))return!1;let n=t.slice(0,t.indexOf(`*`));return bc(n.trim().split(/\s+/).filter(e=>e.length>0),n.length>0&&!/\s$/.test(n))}function Sc(e){let{toolName:t,argPattern:n}=Vs(e),r=e=>e.some(e=>Ws(t,e));return r(mc)?!0:t.includes(`*`)?r(hc):hc.includes(t)||Us(t).riskClass===`execute`?n===void 0||n.trim()===`*`||pc.includes(t)&&xc(n):!1}function Cc(e){return e.filter(e=>!Sc(e))}const wc=1e6,Tc={"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}},Ec=[{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 Dc(e){let t=Object.hasOwn(Tc,e)?Tc[e]:void 0;if(t)return t;for(let{pattern:t,price:n}of Ec)if(t.test(e))return n}function Oc(e,t,n){let r=Dc(e);if(r)return t/wc*r.inputPerMillion+n/wc*r.outputPerMillion}function kc(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 Ac(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 jc(){let[{CommandExecutor:e},{HttpExecutor:t}]=await Promise.all([Promise.resolve().then(()=>require("./command-executor-DV-H2oD6-iQAXtTLY.cjs")).then(e=>e.t).then(e=>e.n),Promise.resolve().then(()=>require("./http-executor-cWzI2svn-C7F17ZGz.cjs")).then(e=>e.t).then(e=>e.n)]);return[new e,new t]}async function Mc(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 jc(),u=new Map;for(let e of l)u.set(e.type,e);let f=[],p=Ac(n),m=-1,h,g;for(let e of c){if(!kc(e,p))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:f.join(`
10
+ `||r===`&`&&Po(t,n))return ko(e),n}function Po(e,t){let n=e[t-1];return n!==`>`&&n!==`<`&&e[t+1]!==`>`}const Fo=/[.+^${}()|[\]\\]/g;function Io(e){let t=e.replace(Fo,`\\$&`).replace(/\*\*/g,`.+`).replace(/\*/g,`.*`);return RegExp(`^${t}$`)}function Lo(e,t,n){let r=Io(e);return n===`deny`?r.test(t)||Oo(t).some(e=>r.test(e))?`match`:`no-match`:r.test(t)?e.includes(`*`)&&Do(t)?`no-match`:`match`:`no-match`}function Ro(e){let t=e.replace(/\*\*(?:\/\*\*)+/g,`**`).split(/(\/\*\*\/|\/\*\*$|^\*\*\/|\*\*)/).map(e=>e===`/**/`?`(?:/.*)?/`:e===`/**`?`(?:/.*)?`:e===`**/`?`(?:.*/)?`:e===`**`?`.*`:e.replace(Fo,`\\$&`).replace(/\*/g,`[^/]*`).replace(/\uE000/g,`\\*`)).join(``);return RegExp(`^${t}$`)}function zo(e){return e.startsWith(`/`)||/^[A-Za-z]:(?=\/|$)/.test(e)}function Bo(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 Vo(e,t){let n=Bo(e),r=Bo(t);return zo(n)&&!zo(r)?`unevaluable`:Ro(n).test(r)?`match`:`no-match`}const Ho=/^(\*|[a-z][a-z0-9+.-]*):\/\/(\[[0-9a-fA-F:.]+\]|[^/\\:?#@[\]]+)(?::(\d+|\*))?(\/[^?#]*)?$/i,Uo=new Set([`http`,`https`,`ws`,`wss`,`ftp`]),Wo={http:`80`,https:`443`,ws:`80`,wss:`443`,ftp:`21`};function Go(e){return e.replace(/\.$/,``).toLowerCase()}function Ko(e){try{let t=new URL(`http://${e}/`).hostname;return t===``||t.includes(`.`)?null:t}catch{return null}}function qo(e){let t=Go(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(Fo,`\\$&`).replace(/\*/g,`[^.]*`)}`);else{let e=Ko(i);if(e===null)return null;n.push(`${c}${e.replace(Fo,`\\$&`)}`)}}return RegExp(`^${n.join(``)}$`)}function Jo(e){try{let t=e.split(`/`).map(e=>decodeURIComponent(e));return t.some(e=>e.includes(`/`))?null:t.join(`/`)}catch{return null}}function Yo(e){let t;try{t=new URL(e)}catch{return null}let n=t.protocol.slice(0,-1).toLowerCase();return!Uo.has(n)||t.hostname===``||t.username!==``||t.password!==``?null:t}function Xo(e,t){if(e.includes(`*`)){let n=qo(e);return n===null?`unevaluable`:n.test(t)?`match`:`no-match`}let n;try{n=new URL(`http://${e}/`).hostname}catch{return`unevaluable`}return Go(n)===t?`match`:`no-match`}function Zo(e,t,n){return e===void 0?t.port===``:e===`*`||e===(t.port===``?Wo[n]:t.port)}function Qo(e,t){let n=Jo(t),r=Jo(e.replace(/%2a/gi,``));return n===null||r===null?`unevaluable`:Ro(r).test(n)?`match`:`no-match`}function $o(e,t){let n=Ho.exec(e);if(n===null)return`unevaluable`;let[,r,i,a,o]=n,s=Yo(t);if(s===null)return`unevaluable`;let c=s.protocol.slice(0,-1).toLowerCase();if(r!==`*`&&r.toLowerCase()!==c)return`no-match`;let l=Xo(i,Go(s.hostname));return l===`match`?Zo(a,s,c)?o===void 0?`match`:Qo(o,s.pathname):`no-match`:l}const es={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`}},ts={plan:`deny`,default:`approve`,acceptEdits:`approve`,bypassPermissions:`auto`,auto:`approve`},ns=[`.git`,`.robota`,`.claude`,`.agents`],rs=[`.mcp.json`,`.gitconfig`,`.npmrc`,`.bashrc`,`.bash_profile`,`.bash_login`,`.zshrc`,`.zshenv`,`.zprofile`,`.profile`];function is(e){return e.replace(/\\/g,`/`).split(`/`).filter(e=>e!==``&&e!==`.`)}function as(e){let t=[];for(let n of is(e))n===`..`&&t.length>0&&t[t.length-1]!==`..`?t.pop():t.push(n);return t}function os(e){let t=as(e),n=t[t.length-1];if(n!==void 0&&rs.includes(n))return!0;for(let e=0;e<t.length;e+=1){let n=t[e];if(ns.includes(n)){if((n===`.robota`||n===`.claude`)&&t[e+1]===`worktrees`&&t[e+2]!==void 0){e+=2;continue}return!0}}return!1}function ss(e){let t=[];for(let n of is(e))n===`..`?t.pop():t.push(n);return`/${t.join(`/`)}`}function cs(e){return e.replace(/^(['"])(.*)\1$/,`$2`)}const ls=/^(?:~|\$HOME|\$\{HOME\})(?=\/|$)(.*)$/;function us(e,t){let n=cs(e),r=ls.exec(n),i;if(r!==null){let e=r[1]??``;if(t.homeDirectory===void 0)return e.replace(/\/+/g,``)===``;i=ss(`${t.homeDirectory}/${e}`)}else if(n===``||n.startsWith(`$`))return!1;else if(n.startsWith(`/`))i=ss(n);else{if(t.cwd===void 0)return!1;i=ss(`${t.cwd}/${n}`)}if(is(i).length<=1||t.homeDirectory!==void 0&&i===ss(t.homeDirectory))return!0;if(t.cwd!==void 0){let e=ss(t.cwd);if(e===i||e.startsWith(`${i}/`))return!0}return!1}const ds=new Set([`rm`,`rmdir`]),fs=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 ps(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=fs.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 ms(e,t){return Oo(e).some(e=>{let n=e.split(/\s+/).filter(e=>e!==``),r=ps(n),i=n[r];if(i===void 0)return!1;let a=i.slice(i.lastIndexOf(`/`)+1);if(!ds.has(a))return!1;let o=!1;return n.slice(r+1).some(e=>!o&&e===`--`?(o=!0,!1):!o&&e.startsWith(`-`)?!1:us(e,t))})}const hs=new Set([`ls`,`cat`,`echo`,`pwd`,`head`,`tail`,`grep`,`wc`,`which`,`stat`,`du`,`cd`]),gs=new Set([`-exec`,`-execdir`,`-ok`,`-okdir`,`-delete`,`-fprint`,`-fprint0`,`-fprintf`,`-fls`]),_s={ls:`aAlhtrSR1dFGinpsucCgmoQvx`,cat:`nbsvetAE`,head:`nqvc`,tail:`nqvcfF`,grep:`rinlLvcwxEFGPHhoqsABCmz`,wc:`lwcmL`,stat:`cftx`,du:`hsacdkmx`,which:`a`,pwd:`LP`,cd:`LP`},vs=/^--?[A-Za-z0-9-]*(file|from|contents)(=|$)/,ys=[`--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 bs(e){if(!e.startsWith(`--`)||e.length<=2)return!1;let t=e.split(`=`,1)[0];return ys.some(e=>e.startsWith(t))}function xs(e,t){if(Ns(t).some(e=>vs.test(e.text)||bs(e.text)))return!0;if(e===`find`)return Ns(t).some(e=>e.text===`-L`||e.text===`-follow`);let n=_s[e];return n!==void 0&&Ns(t).some(({text:e})=>e.startsWith(`--`)||!/^-[A-Za-z]/.test(e)?!1:[...e.slice(1)].some(e=>!/\d/.test(e)&&!n.includes(e)))}const Ss=new Set([`status`,`log`,`diff`,`show`,`rev-parse`,`ls-files`,`describe`,`branch`,`remote`]),Cs=new Set([`-l`,`--list`,`--show-current`,`--merged`,`--no-merged`,`--contains`,`--no-contains`,`--points-at`]),ws=new Set([`-a`,`--all`,`-r`,`--remotes`,`-v`,`-vv`,`--verbose`,`--color`,`--no-color`]),Ts=new Set([`/dev/null`]),Es=/[A-Za-z0-9_./:=@+,*?[\]~-]/,Ds=new Set([`$`,"`",`\\`,`!`]),Os=new Set([`*`,`?`,`[`]);function ks(e){return/(^|[=,:])[/~]/.test(e)||/^-[A-Za-z]+[/~]/.test(e)||/(^|[/=,:]|^-[A-Za-z]+)\.\.(\/|$)/.test(e)||/(^|[=,])[A-Za-z][A-Za-z0-9]*:/.test(e)||As(e)}function As(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 js(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 Ms(e){let t=[],n=``,r=!1,i=!1,a,o,s=!1,c=()=>{i&&=(o===`output`?(!Ts.has(n)||r)&&(s=!0):o===`duplicate`?/^(\d+|-)$/.test(n)||(s=!0):o===`input`?(r||ks(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:Ds.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(!Es.test(l)){s=!0;break}Os.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 Ns(e){let t=e.findIndex(e=>e.text===`--`);return(t<0?e:e.slice(0,t)).filter(e=>e.text.startsWith(`-`))}function Ps(e){return e.every(e=>!e.expands&&!gs.has(e.text))}function Fs(e){let t=e.filter(e=>e.text.startsWith(`-`)),n=t.some(e=>Cs.has(e.text));return t.every(e=>Cs.has(e.text)||ws.has(e.text))&&(n||t.length===e.length)}function Is(e){let[t,...n]=e[0]?.text===`--no-pager`?e.slice(1):e;return t===void 0||t.expands||!Ss.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`?Fs(n):t.text!==`remote`||n.every(e=>e.text===`-v`||e.text===`--verbose`)}function Ls(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=>ks(e.text))||xs(t.text,n)?!1:t.text===`cd`?n.length===1&&n[0].text!==`-`&&!n[0].expands:hs.has(t.text)?!0:t.text===`find`?Ps(n):t.text===`git`&&Is(n)}const Rs=new Set([`echo`,`which`,`git`]);function zs(e,t){let n;for(let[r,...i]of e)if(!Rs.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 Bs(e,t={}){if(t.otherDirectory===!0||e.length>1e4||js(e)||/[^\t\n\x20-\x7e]/.test(e))return!1;let n=Oo(e);if(n.length===0)return!1;let r=n.map(Ms);if(r.some(e=>e.refused||!Ls(e.words)))return!1;let i=r.map(e=>e.words[0].text);return i.includes(`git`)&&i.includes(`cd`)?!1:zs(r.map(e=>e.words),t.resolveInWorkspace)}function Vs(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 Hs(e,t){Q.set(e,{...Q.get(e),...t})}function Us(e){return Q.get(e)??{}}function Ws(e,t){let n=[t,...Q.get(t)?.aliases??[]];if(!e.includes(`*`))return n.includes(e);let r=Io(e);return n.some(e=>r.test(e))}function Gs(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 Ks(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`:Io(e.value).test(String(n))?`match`:`no-match`}function qs(e,t){return t.some(t=>{let n=Vs(t);return(n.argPattern===void 0||n.argPattern===`*`||n.argPattern===`**`)&&Ws(n.toolName,e)})}function Js(e){return Q.get(e)?.argument?.key}function Ys(e,t){let n=Js(e);if(n===void 0)return;let r=t[n];return typeof r==`string`?r:void 0}function Xs(e,t,n,r=`allow`){return n.some(n=>Qs(e,t,n,r)===`match`)}function Zs(e,t,n){return n.some(n=>Qs(e,t,n,`deny`)===`unevaluable`)}function Qs(e,t,n,r){let i=Vs(n);if(!Ws(i.toolName,e))return`no-match`;if(i.argPattern===void 0||i.argPattern===`*`||i.argPattern===`**`)return`match`;let a=Gs(e,i.argPattern);if(a===`primary`)return`unevaluable`;if(a!==void 0)return r===`deny`?Ks(a,t):`no-match`;let o=Q.get(e)?.argument;if(o===void 0)return`unevaluable`;let s=Ys(e,t);if(s===void 0)return`no-match`;switch(o.kind){case`url`:return $o(i.argPattern,s);case`path`:return Vo(i.argPattern,s);case`command`:return Lo(i.argPattern,s,r);case`text`:return Io(i.argPattern).test(s)?`match`:`no-match`;default:{let e=o.kind;throw Error(`unknown argument kind: ${String(e)}`)}}}function $s(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`?ms(a,n):i.kind===`path`&&r?.riskClass===`modify`&&os(a):!1}function ec(e,t,n,r){return Xs(e,t,n,`deny`)||Zs(e,t,n)||$s(e,t,r)}function tc(e,t,n={},r={}){return Zs(e,t,n.deny??[])||ec(e,t,n.ask??[],r)}const nc=[`workingDirectory`,`cwd`];function rc(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`&&Bs(i,{otherDirectory:nc.some(e=>t[e]!==void 0),...n.resolveInWorkspace===void 0?{}:{resolveInWorkspace:n.resolveInWorkspace}})?`inspect`:r.riskClass}function ic(e,t,n,r={},i={}){let{allow:a=[],deny:o=[],ask:s=[]}=r,c=rc(e,t,i),l=n===`plan`&&c!==`inspect`?`deny`:`approve`;return Xs(e,t,o,`deny`)||i.ceiling!==void 0&&!Xs(e,t,i.ceiling)||Q.get(e)?.repliesToPeer===!0&&i.peerTurn!==!0||Q.get(e)?.notInPeerTurn===!0&&i.peerTurn===!0?`deny`:Zs(e,t,o)?n===`plan`?`deny`:`approve`:ec(e,t,s,i)||i.askAll===!0?l:n===`bypassPermissions`||Xs(e,t,a)||i.sandboxAutoApproved===!0&&c===`execute`&&(n==="default"||n===`acceptEdits`||n===`auto`)?`auto`:c===void 0?ts[n]:es[n][c]}function ac(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 oc=/^[A-Za-z_]\w*:(?!\/\/)/;function sc(e){return e.slice(0,e.indexOf(`*`)).includes(`__`)}function cc(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}=Vs(n);if(r===``)return`names no tool`;if(t===`allow`&&r.includes(`*`)&&!sc(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`&&oc.test(i)?`matches a named parameter, which only deny and ask rules may do`:void 0;let a=Gs(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=Us(r);if(!(o.parameters===void 0&&oc.test(i)&&Gs(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`&&$o(i,`https://probe.invalid/`)===`unevaluable`)return`does not fit the URL pattern grammar scheme://host[:port][/path] that "${r}" is matched by`}}function lc(e,t=`deny`){let n=[];for(let r of e){let e=cc(r,t);e!==void 0&&n.push({pattern:r,reason:e})}return n}function uc(e){let t=[];for(let n of e){let{toolName:e,argPattern:r}=Vs(n.trim());if(r===void 0||e.includes(`*`))continue;let i=Us(e),a=Gs(e,r);if(a===void 0&&i.parameters!==void 0&&i.argument?.kind!==`url`&&oc.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=Us(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 dc(e){return(e??[]).map(e=>`${e}(*)`)}function fc(e,t){let n=dc(t.allowedTools),r=lc(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,...dc(t.deniedTools)])]}}const pc=[`Bash`,`Shell`,`BackgroundProcess`],mc=[`Agent`],hc=[...pc,...mc,`ExecuteCommand`,`Computer`],gc=`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(`.`),_c=[`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(` `)),vc=new Set([`run`,`run-script`,`exec`,`dlx`,`x`,`--`]);function yc(e){return(e.split(/[\\/]/).pop()??e).replace(/(\.exe)?$/i,``).replace(/[\d.]+$/,``)}function bc(e,t){if(e.length===0)return!0;let n=(e,n,r)=>t&&r?e.startsWith(n):e===n,r=yc(e[0]);if(gc.some(t=>n(t,r,e.length===1)))return!0;for(let i of _c){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(`-`)||vc.has(o[0]));)o=o.slice(1);return o.length===0||bc(o,t)}return!1}function xc(e){let t=e.trim();if(!t.includes(`*`))return!1;let n=t.slice(0,t.indexOf(`*`));return bc(n.trim().split(/\s+/).filter(e=>e.length>0),n.length>0&&!/\s$/.test(n))}function Sc(e){let{toolName:t,argPattern:n}=Vs(e),r=e=>e.some(e=>Ws(t,e));return r(mc)?!0:t.includes(`*`)?r(hc):hc.includes(t)||Us(t).riskClass===`execute`?n===void 0||n.trim()===`*`||pc.includes(t)&&xc(n):!1}function Cc(e){return e.filter(e=>!Sc(e))}const wc=1e6,Tc={"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}},Ec=[{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 Dc(e){let t=Object.hasOwn(Tc,e)?Tc[e]:void 0;if(t)return t;for(let{pattern:t,price:n}of Ec)if(t.test(e))return n}function Oc(e,t,n){let r=Dc(e);if(r)return t/wc*r.inputPerMillion+n/wc*r.outputPerMillion}function kc(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 Ac(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 jc(){let[{CommandExecutor:e},{HttpExecutor:t}]=await Promise.all([Promise.resolve().then(()=>require("./command-executor-DV-H2oD6-BAvcn7Tf.cjs")).then(e=>e.t).then(e=>e.n),Promise.resolve().then(()=>require("./http-executor-cWzI2svn-Nn7UFLl8.cjs")).then(e=>e.t).then(e=>e.n)]);return[new e,new t]}async function Mc(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 jc(),u=new Map;for(let e of l)u.set(e.type,e);let f=[],p=Ac(n),m=-1,h,g;for(let e of c){if(!kc(e,p))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:f.join(`
11
11
  `),...s()};if(c.outcome===`error`){o.push(c);continue}let l=d.n(c.stdout,t);if(f.push(...l.context),l.blockReason!==void 0)return{blocked:!0,reason:l.blockReason,stdout:f.join(`
12
12
  `),...l.permissionDecision===`deny`&&{permissionDecision:`deny`},...s()};if(l.permissionDecision!==void 0){let e=d.t[l.permissionDecision];e>m&&(m=e,h=l.permissionDecision),e>=m&&l.updatedInput!==void 0&&(g=l.updatedInput)}}}let _={blocked:!1,stdout:f.join(`
13
13
  `)};h!==void 0&&(_.permissionDecision=h),g!==void 0&&(_.updatedInput=g);let{unknownHookTypes:v,errors:y}=s();return v!==void 0&&(_.unknownHookTypes=v),y!==void 0&&(_.errors=y),_}var Nc=class extends Error{guardrailName;guardrailReason;constructor(e,t){super(t),this.guardrailName=e,this.guardrailReason=t,this.name=`GuardrailBlock`}},Pc=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 Nc(e,`Guardrail "${e}" errored: ${t instanceof Error?t.message:String(t)}`)}if(!r.pass)throw new Nc(e,r.reason??`Guardrail "${e}" blocked the turn`)}))}catch(e){if(e instanceof Nc)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 Fc(e,t){return{posture:`advisory`,enforcementReachable:!1,rationale:`Awaited at ${e} but only ${t} is read; \`blocked\` is never consulted.`}}function Ic(e){for(let t of Object.values(e))Object.freeze(t);return Object.freeze(e)}const Lc=Ic({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:Fc(`session-lifecycle.ts`,`nothing`),PreCompact:Fc(`compaction-orchestrator.ts`,`nothing`),UserPromptSubmit:Fc(`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 Rc(e){return Lc[e].posture===`enforcing`}Object.defineProperty(exports,"$",{enumerable:!0,get:function(){return Er}}),Object.defineProperty(exports,"A",{enumerable:!0,get:function(){return me}}),Object.defineProperty(exports,"At",{enumerable:!0,get:function(){return bo}}),Object.defineProperty(exports,"B",{enumerable:!0,get:function(){return Hs}}),Object.defineProperty(exports,"C",{enumerable:!0,get:function(){return M}}),Object.defineProperty(exports,"Ct",{enumerable:!0,get:function(){return ge}}),Object.defineProperty(exports,"D",{enumerable:!0,get:function(){return Ct}}),Object.defineProperty(exports,"Dt",{enumerable:!0,get:function(){return de}}),Object.defineProperty(exports,"E",{enumerable:!0,get:function(){return Kn}}),Object.defineProperty(exports,"Et",{enumerable:!0,get:function(){return Qe}}),Object.defineProperty(exports,"F",{enumerable:!0,get:function(){return nn}}),Object.defineProperty(exports,"Ft",{enumerable:!0,get:function(){return g}}),Object.defineProperty(exports,"G",{enumerable:!0,get:function(){return hr}}),Object.defineProperty(exports,"H",{enumerable:!0,get:function(){return le}}),Object.defineProperty(exports,"I",{enumerable:!0,get:function(){return Qn}}),Object.defineProperty(exports,"It",{enumerable:!0,get:function(){return o}}),Object.defineProperty(exports,"J",{enumerable:!0,get:function(){return j}}),Object.defineProperty(exports,"K",{enumerable:!0,get:function(){return kt}}),Object.defineProperty(exports,"L",{enumerable:!0,get:function(){return G}}),Object.defineProperty(exports,"Lt",{enumerable:!0,get:function(){return s}}),Object.defineProperty(exports,"M",{enumerable:!0,get:function(){return Pc}}),Object.defineProperty(exports,"Mt",{enumerable:!0,get:function(){return Xn}}),Object.defineProperty(exports,"N",{enumerable:!0,get:function(){return De}}),Object.defineProperty(exports,"Nt",{enumerable:!0,get:function(){return te}}),Object.defineProperty(exports,"O",{enumerable:!0,get:function(){return Te}}),Object.defineProperty(exports,"Ot",{enumerable:!0,get:function(){return kr}}),Object.defineProperty(exports,"P",{enumerable:!0,get:function(){return Mc}}),Object.defineProperty(exports,"Pt",{enumerable:!0,get:function(){return ee}}),Object.defineProperty(exports,"Q",{enumerable:!0,get:function(){return qe}}),Object.defineProperty(exports,"R",{enumerable:!0,get:function(){return tr}}),Object.defineProperty(exports,"Rt",{enumerable:!0,get:function(){return l}}),Object.defineProperty(exports,"S",{enumerable:!0,get:function(){return`inherit-allowlist`}}),Object.defineProperty(exports,"St",{enumerable:!0,get:function(){return uc}}),Object.defineProperty(exports,"T",{enumerable:!0,get:function(){return Ce}}),Object.defineProperty(exports,"Tt",{enumerable:!0,get:function(){return Ar}}),Object.defineProperty(exports,"U",{enumerable:!0,get:function(){return Dr}}),Object.defineProperty(exports,"V",{enumerable:!0,get:function(){return Us}}),Object.defineProperty(exports,"W",{enumerable:!0,get:function(){return lc}}),Object.defineProperty(exports,"X",{enumerable:!0,get:function(){return ga}}),Object.defineProperty(exports,"Y",{enumerable:!0,get:function(){return ic}}),Object.defineProperty(exports,"Z",{enumerable:!0,get:function(){return go}}),Object.defineProperty(exports,"_",{enumerable:!0,get:function(){return Wn}}),Object.defineProperty(exports,"_t",{enumerable:!0,get:function(){return qs}}),Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return qn}}),Object.defineProperty(exports,"at",{enumerable:!0,get:function(){return Un}}),Object.defineProperty(exports,"b",{enumerable:!0,get:function(){return Tc}}),Object.defineProperty(exports,"bt",{enumerable:!0,get:function(){return ha}}),Object.defineProperty(exports,"c",{enumerable:!0,get:function(){return Oe}}),Object.defineProperty(exports,"ct",{enumerable:!0,get:function(){return tc}}),Object.defineProperty(exports,"d",{enumerable:!0,get:function(){return Zt}}),Object.defineProperty(exports,"dt",{enumerable:!0,get:function(){return gr}}),Object.defineProperty(exports,"et",{enumerable:!0,get:function(){return It}}),Object.defineProperty(exports,"f",{enumerable:!0,get:function(){return Jn}}),Object.defineProperty(exports,"ft",{enumerable:!0,get:function(){return Ve}}),Object.defineProperty(exports,"g",{enumerable:!0,get:function(){return Yn}}),Object.defineProperty(exports,"gt",{enumerable:!0,get:function(){return gn}}),Object.defineProperty(exports,"h",{enumerable:!0,get:function(){return Qt}}),Object.defineProperty(exports,"ht",{enumerable:!0,get:function(){return ln}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return ve}}),Object.defineProperty(exports,"it",{enumerable:!0,get:function(){return Cc}}),Object.defineProperty(exports,"j",{enumerable:!0,get:function(){return _e}}),Object.defineProperty(exports,"jt",{enumerable:!0,get:function(){return Ee}}),Object.defineProperty(exports,"k",{enumerable:!0,get:function(){return $t}}),Object.defineProperty(exports,"kt",{enumerable:!0,get:function(){return dc}}),Object.defineProperty(exports,"l",{enumerable:!0,get:function(){return rn}}),Object.defineProperty(exports,"lt",{enumerable:!0,get:function(){return wr}}),Object.defineProperty(exports,"m",{enumerable:!0,get:function(){return cn}}),Object.defineProperty(exports,"mt",{enumerable:!0,get:function(){return Rc}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return he}}),Object.defineProperty(exports,"nt",{enumerable:!0,get:function(){return Xs}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return Oo}}),Object.defineProperty(exports,"ot",{enumerable:!0,get:function(){return Na}}),Object.defineProperty(exports,"p",{enumerable:!0,get:function(){return un}}),Object.defineProperty(exports,"pt",{enumerable:!0,get:function(){return ac}}),Object.defineProperty(exports,"q",{enumerable:!0,get:function(){return fc}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return ja}}),Object.defineProperty(exports,"rt",{enumerable:!0,get:function(){return ze}}),Object.defineProperty(exports,"s",{enumerable:!0,get:function(){return ft}}),Object.defineProperty(exports,"st",{enumerable:!0,get:function(){return ns}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return tn}}),Object.defineProperty(exports,"tt",{enumerable:!0,get:function(){return 5e5}}),Object.defineProperty(exports,"u",{enumerable:!0,get:function(){return Oc}}),Object.defineProperty(exports,"ut",{enumerable:!0,get:function(){return 25e3}}),Object.defineProperty(exports,"v",{enumerable:!0,get:function(){return Eo}}),Object.defineProperty(exports,"vt",{enumerable:!0,get:function(){return Re}}),Object.defineProperty(exports,"w",{enumerable:!0,get:function(){return be}}),Object.defineProperty(exports,"wt",{enumerable:!0,get:function(){return To}}),Object.defineProperty(exports,"x",{enumerable:!0,get:function(){return Gn}}),Object.defineProperty(exports,"xt",{enumerable:!0,get:function(){return ue}}),Object.defineProperty(exports,"y",{enumerable:!0,get:function(){return Se}}),Object.defineProperty(exports,"yt",{enumerable:!0,get:function(){return rs}}),Object.defineProperty(exports,"z",{enumerable:!0,get:function(){return sr}});
@@ -1,4 +1,4 @@
1
- const e=require("./node-tf433Aey.cjs"),t=require("./bounded-output-DpjpS98g-yPybHprY.cjs");require("./command-executor-DV-H2oD6-iQAXtTLY.cjs"),require("./http-executor-cWzI2svn-C7F17ZGz.cjs");let n=require("node:crypto"),r=require("node:path"),i=require("node:child_process"),a=require("node:fs/promises"),o=require("node:fs"),s=require("node:os"),c=require("zod"),l=require("node:dns/promises"),u=require("node:net"),d=require("fast-glob");d=e.Rt(d,1);let f=require("p-limit");f=e.Rt(f,1);let p=require("node:events"),m=require("node:worker_threads");const h=process.platform===`win32`;function g(e){return e.exitCode!==null||e.signalCode!==null}function _(e,t,n){if(n&&!h&&typeof e.pid==`number`)try{process.kill(-e.pid,t);return}catch{}try{e.kill(t)}catch{}}function v(e,t){if(h&&typeof e.pid==`number`){(0,i.spawnSync)(`taskkill`,[`/pid`,String(e.pid),`/T`,`/F`],{stdio:`ignore`});return}_(e,`SIGKILL`,t)}async function y(e,t={}){let n=t.graceMs??2e3,r=t.signal??`SIGTERM`,i=t.processGroup??!1;if(!g(e)){if(typeof e.pid!=`number`)throw Error(`[agent-process] killProcessTree called with an unspawned child (no pid)`);if(t.preKill){try{await t.preKill()}catch{}if(g(e))return}return new Promise(t=>{let a,o=()=>{a&&clearTimeout(a),t()};if(e.once(`exit`,o),g(e)){e.removeListener(`exit`,o),t();return}_(e,r,i),a=setTimeout(()=>{g(e)||v(e,i)},n),a.unref?.()})}}function b(e){if(typeof e!=`string`)throw TypeError(`executionRoot must be a string`);if(e.trim().length===0)throw TypeError(`executionRoot must be a non-empty string`);if(!(0,r.isAbsolute)(e))throw TypeError(`executionRoot must be an absolute path`);let t;try{t=(0,o.realpathSync)(e)}catch{throw TypeError(`executionRoot must name an existing accessible directory`)}if(!(0,o.statSync)(t).isDirectory())throw TypeError(`executionRoot must name a directory`);try{(0,o.accessSync)(t,o.constants.R_OK|o.constants.X_OK)}catch{throw TypeError(`executionRoot directory must be readable and traversable`)}return t}function x(e){let t=[],n=(0,r.resolve)(e);for(;;)try{return(0,r.join)((0,o.realpathSync)(n),...t)}catch{let i=(0,r.dirname)(n);if(i===n)return(0,r.resolve)(e);t.unshift((0,r.basename)(n)),n=i}}function S(e,t){let n=x(e),i=x(t);return i===n||i.startsWith(n+r.sep)}var ee=class extends Error{constructor(e){super(e),this.name=`OwnerOnlyModeError`}};function C(e=process.platform){return e===`win32`?`windows-acl`:`posix-mode`}function te(e,t){let n=(0,r.relative)(e,t);if(n.startsWith(`..`)||(0,r.isAbsolute)(n))throw new ee(`withinRoot ${e} is not an ancestor of ${t}, so this call cannot own the path between them.`);let i=n.split(r.sep).filter(e=>e.length>0),a=[e],o=e;for(let e of i)o=(0,r.join)(o,e),a.push(o);return a}function w(e,t,n={}){if(C()!==`posix-mode`)return;let r=(n.readMode??(e=>(0,o.statSync)(e).mode&4095))(e);if(r&63)throw new ee(`${t} ${e} is mode 0${r.toString(8)} after being set owner-only; group or other permissions survived, so its contents are readable by another account.`)}function T(e,t={}){let n=t.makeDirectory??((e,t)=>{(0,o.mkdirSync)(e,{recursive:!0,mode:t})}),r=t.setMode??((e,t)=>(0,o.chmodSync)(e,t));n(e,448);let i=t.withinRoot===void 0?[e]:te(t.withinRoot,e);for(let e of i)C()===`posix-mode`&&r(e,448),w(e,`directory`,t)}function ne(e,t){T((0,r.dirname)(e));let n=`${e}.${process.pid}.tmp`;(0,o.rmSync)(n,{force:!0}),(0,o.writeFileSync)(n,t,{encoding:`utf8`,mode:384,flag:`wx`});try{w(n,`file`),(0,o.renameSync)(n,e)}catch(e){try{(0,o.unlinkSync)(n)}catch{}throw e}w(e,`file`)}function re(e){if(C()!==`posix-mode`)return;let t;try{t=(0,o.statSync)(e).mode&4095}catch{return}t&63&&((0,o.chmodSync)(e,384),w(e,`file`))}function ie(e){let t=(0,u.isIP)(e);return t===4?ae(e.split(`.`).map(Number)):t!==6||oe(e)}function ae(e){let[t=0,n=0,r=0]=e;return t===0||t===10||t===127||t===100&&n>=64&&n<=127||t===169&&n===254||t===172&&n>=16&&n<=31||t===192&&n===0&&r===0||t===192&&n===168||t===198&&(n===18||n===19)||t>=224}function oe(e){let t=ce(e);if(t===void 0)return!0;let[n=0,r=0,i=0,a=0,o=0,s=0,c=0,l=0]=t;return n===0&&r===0&&i===0&&a===0&&o===0&&s===65535||n===100&&r===65435&&i===0&&a===0&&o===0&&s===0?ae([c>>8,c&255,l>>8,l&255]):n===0&&r===0&&i===0&&a===0&&o===0&&s===0||(n&65024)==64512||(n&65472)==65152||(n&65472)==65216||(n&65280)==65280}function se(e){let t=e.lastIndexOf(`:`),n=e.slice(t+1);if(!n.includes(`.`))return e;if(t<0||(0,u.isIP)(n)!==4)return;let[r=0,i=0,a=0,o=0]=n.split(`.`).map(Number),s=(r<<8|i).toString(16),c=(a<<8|o).toString(16);return`${e.slice(0,t+1)}${s}:${c}`}function ce(e){let t=se(e.split(`%`)[0]??e);if(t===void 0)return;let n=t.split(`::`);if(n.length>2)return;let r=e=>e.length===0?[]:e.split(`:`).map(e=>Number.parseInt(e,16)),i=r(n[0]??``),a=n.length===2?r(n[1]??``):[],o=8-i.length-a.length;if(o<0||n.length===1&&o!==0)return;let s=[...i,...Array(o).fill(0),...a];return s.some(e=>Number.isNaN(e)||e<0||e>65535)?void 0:s}const le=3e4,ue=5e6,de=new Set([301,302,303,307,308]),fe=new Set([`localhost`,`metadata`,`metadata.google.internal`,`metadata.goog`,`instance-data`,`instance-data.ec2.internal`]),E=async e=>(await(0,l.lookup)(e,{all:!0,verbatim:!0})).map(e=>e.address);async function D(e,t={},n=E){let r=e.href;if(e.protocol!==`http:`&&e.protocol!==`https:`)return{reason:`unsupported_scheme`,url:r,message:`Only http(s) URLs may be fetched.`};if(t.allowPrivateAddresses===!0)return;let i=e.hostname.replace(/^\[|\]$/g,``).toLowerCase();if(t.allowedHosts?.includes(i))return;if(fe.has(i)||i.endsWith(`.localhost`))return{reason:`metadata_host`,url:r,message:`Destination "${i}" is a loopback or cloud-metadata host and is not reachable from tools.`};let a=(0,u.isIP)(i)?[i]:await pe(i,n);if(a===void 0||a.length===0)return{reason:`unresolvable`,url:r,message:`Destination "${i}" did not resolve.`};let o=a.find(ie);if(o!==void 0)return{reason:`private_destination`,url:r,message:`Destination "${i}" resolves to ${o}, a private, loopback or link-local address, and is not reachable from tools.`}}async function pe(e,t){try{return await t(e)}catch{return}}async function me(e,t={},n={},r={}){let i=r.fetch??((e,t)=>globalThis.fetch(e,t)),a=r.lookup??E,o=t.maxResponseBytes??ue,s=n.maxRedirects??5,c=AbortSignal.timeout(t.timeoutMs??le),l=t.signal?AbortSignal.any([c,t.signal]):c,u=new URL(e),d={...t.headers??{}};for(let e=0;;e+=1){let t=await D(u,n,a);if(t!==void 0)return{ok:!1,rejection:t};let r=await i(u.href,{headers:d,signal:l,redirect:`manual`});if(!de.has(r.status))return _e(r,u.href,o,l);let c=r.headers.get(`location`);if(c===null)return{ok:!1,rejection:{reason:`redirect_without_location`,url:u.href,message:`HTTP ${r.status} without a Location header.`}};if(e>=s)return{ok:!1,rejection:{reason:`redirect_limit`,url:u.href,message:`More than ${s} redirects.`}};let f=new URL(c,u);f.origin!==u.origin&&(d=ge(d)),u=f}}async function he(e,t,n={},r={}){let i=r.fetch??((e,t)=>globalThis.fetch(e,t)),a=t.maxResponseBytes??ue,o=AbortSignal.timeout(t.timeoutMs??le),s=t.signal?AbortSignal.any([o,t.signal]):o,c=new URL(e),l=await D(c,n,r.lookup??E);if(l!==void 0)return{ok:!1,rejection:l};let u=await i(c.href,{method:`POST`,headers:{...t.headers??{}},body:t.body,signal:s,redirect:`manual`});return u.status>=300&&u.status<400?(await u.body?.cancel().catch(()=>void 0),{ok:!1,rejection:{reason:`redirect_refused`,url:c.href,message:`HTTP ${u.status}: a POST is never redirected.`}}):_e(u,c.href,a,s)}function ge(e){let t={};for(let[n,r]of Object.entries(e))n.toLowerCase()===`user-agent`&&(t[n]=r);return t}async function _e(e,t,n,r){let i=e=>({ok:!1,rejection:{reason:`response_too_large`,url:t,message:`Response exceeds ${n} bytes (${e} seen).`}}),a=Number(e.headers.get(`content-length`));if(Number.isFinite(a)&&a>n)return await e.body?.cancel(),i(a);let o=[],s=0;if(!e.body&&typeof e.arrayBuffer==`function`){let t=new Uint8Array(await e.arrayBuffer());if(t.byteLength>n)return i(t.byteLength);o.push(t),s=t.byteLength}else if(e.body){let t=e.body.getReader();for(;;){r.throwIfAborted();let{done:e,value:a}=await t.read();if(e)break;if(s+=a.byteLength,s>n)return await t.cancel(),i(s);o.push(a)}}let c=new Uint8Array(s),l=0;for(let e of o)c.set(e,l),l+=e.byteLength;return{ok:!0,status:e.status,statusText:e.statusText,headers:e.headers,body:c,finalUrl:t}}function ve(e){return e===void 0?`host`:`sandbox-${e.filesystem??`separate`}`}function ye(e){return ve(e)===`sandbox-separate`}function be(e){let t=[];e.environment&&Object.keys(e.environment).length>0&&t.push(`environment`);let n=e.permissions;if(n&&Object.values(n).some(e=>Array.isArray(e)?e.length>0:e!==void 0)&&t.push(`permissions`),t.length!==0)throw Error(`workspace manifest requests ${t.join(` and `)}, which this sandbox client cannot enforce. The built-in applicator applies entries only. Supply a sandbox client that implements applyManifest and honours these fields, or remove them from the manifest — they were previously accepted and silently ignored, which reported a sandbox policy that was never applied (issue #2027).`)}const xe=/^[A-Za-z]:[\\/]/,Se=/'/g;async function Ce(e,t,n={}){if(e.applyManifest)return e.applyManifest(t,n);be(t);let r=Ne(n.targetRoot??`/workspace`),i=[];for(let[a,o]of Object.entries(t.entries)){let t=we(a),s=Pe(r,t);i.push(await Te(e,t,s,r,o,n))}return{entries:i}}function we(e){if(e.length===0)throw Error(`workspace manifest path must not be empty`);if(e.includes(`\0`))throw Error(`workspace manifest path must not contain NUL bytes`);if(e.startsWith(`/`)||e.startsWith(`\\`)||xe.test(e))throw Error(`workspace manifest path must be workspace-relative`);let t=e.replace(/\\/g,`/`).split(`/`).filter(Boolean);if(t.length===0)throw Error(`workspace manifest path must not resolve to the workspace root`);if(t.some(e=>e===`..`))throw Error(`workspace manifest path cannot contain traversal segments`);let n=t.filter(e=>e!==`.`);if(n.length===0)throw Error(`workspace manifest path must not resolve to the workspace root`);return n.join(`/`)}async function Te(e,t,n,r,i,a){switch(i.type){case`file`:return await ke(e,n,r,i.content),O(t,i.type);case`dir`:return await A(e,n),O(t,i.type);case`localFile`:return await Ee(e,i.src,n,r,a),O(t,i.type);case`localDir`:return await De(e,i.src,n,a),O(t,i.type);case`gitRepo`:return await Oe(e,i,n),O(t,i.type);case`s3Mount`:case`gcsMount`:case`r2Mount`:case`azureBlobMount`:return{path:t,type:i.type,status:`unsupported`,message:`${i.type} requires a provider-specific sandbox adapter.`};default:return Fe(i)}}function O(e,t){return{path:e,type:t,status:`applied`}}async function Ee(e,t,n,r,i){await ke(e,n,r,await(0,a.readFile)(je(t,i.hostRoot),`utf8`))}async function De(e,t,n,r){await k(e,je(t,r.hostRoot),n)}async function k(e,t,n){await A(e,n);let i=await(0,a.readdir)(t,{withFileTypes:!0});for(let o of i){let i=(0,r.join)(t,o.name),s=Pe(n,o.name);if(o.isDirectory()){await k(e,i,s);continue}if(o.isFile()){let t=await(0,a.readFile)(i,`utf8`);await e.writeFile(s,t)}}}async function Oe(e,t,n){await Ae(e,`git clone${t.shallow===!1?``:` --depth 1`}${t.ref?` --branch ${j(t.ref)}`:``} ${j(t.url)} ${j(n)}`)}async function ke(e,t,n,i){let a=r.posix.dirname(t);a!==n&&await A(e,a),await e.writeFile(t,i)}async function A(e,t){await Ae(e,`mkdir -p ${j(t)}`)}async function Ae(e,t){let n=await e.run(t);if(n.exitCode!==0)throw Error(`workspace manifest command failed: ${t}\n${n.stderr??n.stdout}`)}function je(e,t){return(0,r.isAbsolute)(e)?(0,r.resolve)(e):(0,r.resolve)(t??process.cwd(),e)}function Me(e){let t=e.length;for(;t>0&&e[t-1]===`/`;)--t;return e.slice(0,t)}function Ne(e){let t=Me(e.replace(/\\/g,`/`));if(!t.startsWith(`/`))throw Error(`workspace manifest targetRoot must be an absolute sandbox path`);return t.length===0?`/`:t}function Pe(e,t){let n=Ne(e);return n===`/`?`/${t}`:`${n}/${t}`}function j(e){return`'${e.replace(Se,`'\\''`)}'`}function Fe(e){throw Error(`unsupported workspace manifest entry: ${JSON.stringify(e)}`)}const M=[`.robota/worktrees`,`.claude/worktrees`];function N(e,t){let n=e.length;for(;n>0&&e[n-1]===`/`;)--n;return`${e.slice(0,n)}/${t}`}function P(){return[...e.st,...e.yt]}function Ie(e){let{policy:t}=e,n=[`--ro-bind`,`/`,`/`,`--dev`,`/dev`,`--proc`,`/proc`];for(let e of[t.root,...t.tempDirectories,...t.allowWrite])n.push(`--bind-try`,e,e);for(let r of P()){let i=N(t.root,r);e.exists(i)&&n.push(`--ro-bind`,i,i)}for(let r of M){let i=N(t.root,r);if(e.exists(i)){n.push(`--bind`,i,i);for(let t of e.listDirectory(i)){let r=N(i,`${t}/.git`);e.exists(r)&&n.push(`--ro-bind`,r,r)}}}for(let r of t.denyRead)e.exists(r.path)&&(r.directory?n.push(`--tmpfs`,r.path):n.push(`--ro-bind`,`/dev/null`,r.path));if(!t.network){if(e.seccompDescriptor===void 0)throw Error(`A sandbox without network needs the Unix-socket seccomp filter.`);n.push(`--unshare-net`,`--seccomp`,String(e.seccompDescriptor))}return n.push(`--unshare-pid`,`--die-with-parent`,`--new-session`,`--chdir`,e.cwd),n.push(`--`,e.command),[...n,...e.args]}function Le(e){return e.replace(/[\\^$.*+?()[\]{}|"]/g,e=>`\\${e}`)}function F(e){return`"${e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}"`}function Re(t){let n=[t.root,...t.tempDirectories,...t.allowWrite].map(e=>`(subpath ${F(e)})`).join(` `),r=P().map(n=>{let r=N(t.root,n);return e.yt.includes(n)?`(literal ${F(r)})`:`(subpath ${F(r)})`}),i=M.map(e=>`(subpath ${F(N(t.root,e))})`),a=[`(literal ${F(N(t.root,`.git`))})`,...M.map(e=>`(regex #"^${Le(N(t.root,e))}/[^/]+/\\.git$")`)],o=[`(version 1)`,`(allow default)`,`(deny file-write*)`,`(allow file-write* ${n} (literal "/dev/null") (regex #"^/dev/tty") (regex #"^/dev/fd/"))`,`(deny file-write* ${r.join(` `)})`,`(allow file-write* ${i.join(` `)})`,`(deny file-write* ${a.join(` `)})`];if(t.denyRead.length>0){let e=t.denyRead.map(e=>e.directory?`(subpath ${F(e.path)})`:`(literal ${F(e.path)})`);o.push(`(deny file-read* ${e.join(` `)})`)}return t.network||o.push(`(deny network*)`),o.join(`
1
+ const e=require("./node-D8uo8Kzf.cjs"),t=require("./bounded-output-DpjpS98g-yPybHprY.cjs");require("./command-executor-DV-H2oD6-BAvcn7Tf.cjs"),require("./http-executor-cWzI2svn-Nn7UFLl8.cjs");let n=require("node:crypto"),r=require("node:path"),i=require("node:child_process"),a=require("node:fs/promises"),o=require("node:fs"),s=require("node:os"),c=require("zod"),l=require("node:dns/promises"),u=require("node:net"),d=require("fast-glob");d=e.Rt(d,1);let f=require("p-limit");f=e.Rt(f,1);let p=require("node:events"),m=require("node:worker_threads");const h=process.platform===`win32`;function g(e){return e.exitCode!==null||e.signalCode!==null}function _(e,t,n){if(n&&!h&&typeof e.pid==`number`)try{process.kill(-e.pid,t);return}catch{}try{e.kill(t)}catch{}}function v(e,t){if(h&&typeof e.pid==`number`){(0,i.spawnSync)(`taskkill`,[`/pid`,String(e.pid),`/T`,`/F`],{stdio:`ignore`});return}_(e,`SIGKILL`,t)}async function y(e,t={}){let n=t.graceMs??2e3,r=t.signal??`SIGTERM`,i=t.processGroup??!1;if(!g(e)){if(typeof e.pid!=`number`)throw Error(`[agent-process] killProcessTree called with an unspawned child (no pid)`);if(t.preKill){try{await t.preKill()}catch{}if(g(e))return}return new Promise(t=>{let a,o=()=>{a&&clearTimeout(a),t()};if(e.once(`exit`,o),g(e)){e.removeListener(`exit`,o),t();return}_(e,r,i),a=setTimeout(()=>{g(e)||v(e,i)},n),a.unref?.()})}}function b(e){if(typeof e!=`string`)throw TypeError(`executionRoot must be a string`);if(e.trim().length===0)throw TypeError(`executionRoot must be a non-empty string`);if(!(0,r.isAbsolute)(e))throw TypeError(`executionRoot must be an absolute path`);let t;try{t=(0,o.realpathSync)(e)}catch{throw TypeError(`executionRoot must name an existing accessible directory`)}if(!(0,o.statSync)(t).isDirectory())throw TypeError(`executionRoot must name a directory`);try{(0,o.accessSync)(t,o.constants.R_OK|o.constants.X_OK)}catch{throw TypeError(`executionRoot directory must be readable and traversable`)}return t}function x(e){let t=[],n=(0,r.resolve)(e);for(;;)try{return(0,r.join)((0,o.realpathSync)(n),...t)}catch{let i=(0,r.dirname)(n);if(i===n)return(0,r.resolve)(e);t.unshift((0,r.basename)(n)),n=i}}function S(e,t){let n=x(e),i=x(t);return i===n||i.startsWith(n+r.sep)}var ee=class extends Error{constructor(e){super(e),this.name=`OwnerOnlyModeError`}};function C(e=process.platform){return e===`win32`?`windows-acl`:`posix-mode`}function te(e,t){let n=(0,r.relative)(e,t);if(n.startsWith(`..`)||(0,r.isAbsolute)(n))throw new ee(`withinRoot ${e} is not an ancestor of ${t}, so this call cannot own the path between them.`);let i=n.split(r.sep).filter(e=>e.length>0),a=[e],o=e;for(let e of i)o=(0,r.join)(o,e),a.push(o);return a}function w(e,t,n={}){if(C()!==`posix-mode`)return;let r=(n.readMode??(e=>(0,o.statSync)(e).mode&4095))(e);if(r&63)throw new ee(`${t} ${e} is mode 0${r.toString(8)} after being set owner-only; group or other permissions survived, so its contents are readable by another account.`)}function T(e,t={}){let n=t.makeDirectory??((e,t)=>{(0,o.mkdirSync)(e,{recursive:!0,mode:t})}),r=t.setMode??((e,t)=>(0,o.chmodSync)(e,t));n(e,448);let i=t.withinRoot===void 0?[e]:te(t.withinRoot,e);for(let e of i)C()===`posix-mode`&&r(e,448),w(e,`directory`,t)}function ne(e,t){T((0,r.dirname)(e));let n=`${e}.${process.pid}.tmp`;(0,o.rmSync)(n,{force:!0}),(0,o.writeFileSync)(n,t,{encoding:`utf8`,mode:384,flag:`wx`});try{w(n,`file`),(0,o.renameSync)(n,e)}catch(e){try{(0,o.unlinkSync)(n)}catch{}throw e}w(e,`file`)}function re(e){if(C()!==`posix-mode`)return;let t;try{t=(0,o.statSync)(e).mode&4095}catch{return}t&63&&((0,o.chmodSync)(e,384),w(e,`file`))}function ie(e){let t=(0,u.isIP)(e);return t===4?ae(e.split(`.`).map(Number)):t!==6||oe(e)}function ae(e){let[t=0,n=0,r=0]=e;return t===0||t===10||t===127||t===100&&n>=64&&n<=127||t===169&&n===254||t===172&&n>=16&&n<=31||t===192&&n===0&&r===0||t===192&&n===168||t===198&&(n===18||n===19)||t>=224}function oe(e){let t=ce(e);if(t===void 0)return!0;let[n=0,r=0,i=0,a=0,o=0,s=0,c=0,l=0]=t;return n===0&&r===0&&i===0&&a===0&&o===0&&s===65535||n===100&&r===65435&&i===0&&a===0&&o===0&&s===0?ae([c>>8,c&255,l>>8,l&255]):n===0&&r===0&&i===0&&a===0&&o===0&&s===0||(n&65024)==64512||(n&65472)==65152||(n&65472)==65216||(n&65280)==65280}function se(e){let t=e.lastIndexOf(`:`),n=e.slice(t+1);if(!n.includes(`.`))return e;if(t<0||(0,u.isIP)(n)!==4)return;let[r=0,i=0,a=0,o=0]=n.split(`.`).map(Number),s=(r<<8|i).toString(16),c=(a<<8|o).toString(16);return`${e.slice(0,t+1)}${s}:${c}`}function ce(e){let t=se(e.split(`%`)[0]??e);if(t===void 0)return;let n=t.split(`::`);if(n.length>2)return;let r=e=>e.length===0?[]:e.split(`:`).map(e=>Number.parseInt(e,16)),i=r(n[0]??``),a=n.length===2?r(n[1]??``):[],o=8-i.length-a.length;if(o<0||n.length===1&&o!==0)return;let s=[...i,...Array(o).fill(0),...a];return s.some(e=>Number.isNaN(e)||e<0||e>65535)?void 0:s}const le=3e4,ue=5e6,de=new Set([301,302,303,307,308]),fe=new Set([`localhost`,`metadata`,`metadata.google.internal`,`metadata.goog`,`instance-data`,`instance-data.ec2.internal`]),E=async e=>(await(0,l.lookup)(e,{all:!0,verbatim:!0})).map(e=>e.address);async function D(e,t={},n=E){let r=e.href;if(e.protocol!==`http:`&&e.protocol!==`https:`)return{reason:`unsupported_scheme`,url:r,message:`Only http(s) URLs may be fetched.`};if(t.allowPrivateAddresses===!0)return;let i=e.hostname.replace(/^\[|\]$/g,``).toLowerCase();if(t.allowedHosts?.includes(i))return;if(fe.has(i)||i.endsWith(`.localhost`))return{reason:`metadata_host`,url:r,message:`Destination "${i}" is a loopback or cloud-metadata host and is not reachable from tools.`};let a=(0,u.isIP)(i)?[i]:await pe(i,n);if(a===void 0||a.length===0)return{reason:`unresolvable`,url:r,message:`Destination "${i}" did not resolve.`};let o=a.find(ie);if(o!==void 0)return{reason:`private_destination`,url:r,message:`Destination "${i}" resolves to ${o}, a private, loopback or link-local address, and is not reachable from tools.`}}async function pe(e,t){try{return await t(e)}catch{return}}async function me(e,t={},n={},r={}){let i=r.fetch??((e,t)=>globalThis.fetch(e,t)),a=r.lookup??E,o=t.maxResponseBytes??ue,s=n.maxRedirects??5,c=AbortSignal.timeout(t.timeoutMs??le),l=t.signal?AbortSignal.any([c,t.signal]):c,u=new URL(e),d={...t.headers??{}};for(let e=0;;e+=1){let t=await D(u,n,a);if(t!==void 0)return{ok:!1,rejection:t};let r=await i(u.href,{headers:d,signal:l,redirect:`manual`});if(!de.has(r.status))return _e(r,u.href,o,l);let c=r.headers.get(`location`);if(c===null)return{ok:!1,rejection:{reason:`redirect_without_location`,url:u.href,message:`HTTP ${r.status} without a Location header.`}};if(e>=s)return{ok:!1,rejection:{reason:`redirect_limit`,url:u.href,message:`More than ${s} redirects.`}};let f=new URL(c,u);f.origin!==u.origin&&(d=ge(d)),u=f}}async function he(e,t,n={},r={}){let i=r.fetch??((e,t)=>globalThis.fetch(e,t)),a=t.maxResponseBytes??ue,o=AbortSignal.timeout(t.timeoutMs??le),s=t.signal?AbortSignal.any([o,t.signal]):o,c=new URL(e),l=await D(c,n,r.lookup??E);if(l!==void 0)return{ok:!1,rejection:l};let u=await i(c.href,{method:`POST`,headers:{...t.headers??{}},body:t.body,signal:s,redirect:`manual`});return u.status>=300&&u.status<400?(await u.body?.cancel().catch(()=>void 0),{ok:!1,rejection:{reason:`redirect_refused`,url:c.href,message:`HTTP ${u.status}: a POST is never redirected.`}}):_e(u,c.href,a,s)}function ge(e){let t={};for(let[n,r]of Object.entries(e))n.toLowerCase()===`user-agent`&&(t[n]=r);return t}async function _e(e,t,n,r){let i=e=>({ok:!1,rejection:{reason:`response_too_large`,url:t,message:`Response exceeds ${n} bytes (${e} seen).`}}),a=Number(e.headers.get(`content-length`));if(Number.isFinite(a)&&a>n)return await e.body?.cancel(),i(a);let o=[],s=0;if(!e.body&&typeof e.arrayBuffer==`function`){let t=new Uint8Array(await e.arrayBuffer());if(t.byteLength>n)return i(t.byteLength);o.push(t),s=t.byteLength}else if(e.body){let t=e.body.getReader();for(;;){r.throwIfAborted();let{done:e,value:a}=await t.read();if(e)break;if(s+=a.byteLength,s>n)return await t.cancel(),i(s);o.push(a)}}let c=new Uint8Array(s),l=0;for(let e of o)c.set(e,l),l+=e.byteLength;return{ok:!0,status:e.status,statusText:e.statusText,headers:e.headers,body:c,finalUrl:t}}function ve(e){return e===void 0?`host`:`sandbox-${e.filesystem??`separate`}`}function ye(e){return ve(e)===`sandbox-separate`}function be(e){let t=[];e.environment&&Object.keys(e.environment).length>0&&t.push(`environment`);let n=e.permissions;if(n&&Object.values(n).some(e=>Array.isArray(e)?e.length>0:e!==void 0)&&t.push(`permissions`),t.length!==0)throw Error(`workspace manifest requests ${t.join(` and `)}, which this sandbox client cannot enforce. The built-in applicator applies entries only. Supply a sandbox client that implements applyManifest and honours these fields, or remove them from the manifest — they were previously accepted and silently ignored, which reported a sandbox policy that was never applied (issue #2027).`)}const xe=/^[A-Za-z]:[\\/]/,Se=/'/g;async function Ce(e,t,n={}){if(e.applyManifest)return e.applyManifest(t,n);be(t);let r=Ne(n.targetRoot??`/workspace`),i=[];for(let[a,o]of Object.entries(t.entries)){let t=we(a),s=Pe(r,t);i.push(await Te(e,t,s,r,o,n))}return{entries:i}}function we(e){if(e.length===0)throw Error(`workspace manifest path must not be empty`);if(e.includes(`\0`))throw Error(`workspace manifest path must not contain NUL bytes`);if(e.startsWith(`/`)||e.startsWith(`\\`)||xe.test(e))throw Error(`workspace manifest path must be workspace-relative`);let t=e.replace(/\\/g,`/`).split(`/`).filter(Boolean);if(t.length===0)throw Error(`workspace manifest path must not resolve to the workspace root`);if(t.some(e=>e===`..`))throw Error(`workspace manifest path cannot contain traversal segments`);let n=t.filter(e=>e!==`.`);if(n.length===0)throw Error(`workspace manifest path must not resolve to the workspace root`);return n.join(`/`)}async function Te(e,t,n,r,i,a){switch(i.type){case`file`:return await ke(e,n,r,i.content),O(t,i.type);case`dir`:return await A(e,n),O(t,i.type);case`localFile`:return await Ee(e,i.src,n,r,a),O(t,i.type);case`localDir`:return await De(e,i.src,n,a),O(t,i.type);case`gitRepo`:return await Oe(e,i,n),O(t,i.type);case`s3Mount`:case`gcsMount`:case`r2Mount`:case`azureBlobMount`:return{path:t,type:i.type,status:`unsupported`,message:`${i.type} requires a provider-specific sandbox adapter.`};default:return Fe(i)}}function O(e,t){return{path:e,type:t,status:`applied`}}async function Ee(e,t,n,r,i){await ke(e,n,r,await(0,a.readFile)(je(t,i.hostRoot),`utf8`))}async function De(e,t,n,r){await k(e,je(t,r.hostRoot),n)}async function k(e,t,n){await A(e,n);let i=await(0,a.readdir)(t,{withFileTypes:!0});for(let o of i){let i=(0,r.join)(t,o.name),s=Pe(n,o.name);if(o.isDirectory()){await k(e,i,s);continue}if(o.isFile()){let t=await(0,a.readFile)(i,`utf8`);await e.writeFile(s,t)}}}async function Oe(e,t,n){await Ae(e,`git clone${t.shallow===!1?``:` --depth 1`}${t.ref?` --branch ${j(t.ref)}`:``} ${j(t.url)} ${j(n)}`)}async function ke(e,t,n,i){let a=r.posix.dirname(t);a!==n&&await A(e,a),await e.writeFile(t,i)}async function A(e,t){await Ae(e,`mkdir -p ${j(t)}`)}async function Ae(e,t){let n=await e.run(t);if(n.exitCode!==0)throw Error(`workspace manifest command failed: ${t}\n${n.stderr??n.stdout}`)}function je(e,t){return(0,r.isAbsolute)(e)?(0,r.resolve)(e):(0,r.resolve)(t??process.cwd(),e)}function Me(e){let t=e.length;for(;t>0&&e[t-1]===`/`;)--t;return e.slice(0,t)}function Ne(e){let t=Me(e.replace(/\\/g,`/`));if(!t.startsWith(`/`))throw Error(`workspace manifest targetRoot must be an absolute sandbox path`);return t.length===0?`/`:t}function Pe(e,t){let n=Ne(e);return n===`/`?`/${t}`:`${n}/${t}`}function j(e){return`'${e.replace(Se,`'\\''`)}'`}function Fe(e){throw Error(`unsupported workspace manifest entry: ${JSON.stringify(e)}`)}const M=[`.robota/worktrees`,`.claude/worktrees`];function N(e,t){let n=e.length;for(;n>0&&e[n-1]===`/`;)--n;return`${e.slice(0,n)}/${t}`}function P(){return[...e.st,...e.yt]}function Ie(e){let{policy:t}=e,n=[`--ro-bind`,`/`,`/`,`--dev`,`/dev`,`--proc`,`/proc`];for(let e of[t.root,...t.tempDirectories,...t.allowWrite])n.push(`--bind-try`,e,e);for(let r of P()){let i=N(t.root,r);e.exists(i)&&n.push(`--ro-bind`,i,i)}for(let r of M){let i=N(t.root,r);if(e.exists(i)){n.push(`--bind`,i,i);for(let t of e.listDirectory(i)){let r=N(i,`${t}/.git`);e.exists(r)&&n.push(`--ro-bind`,r,r)}}}for(let r of t.denyRead)e.exists(r.path)&&(r.directory?n.push(`--tmpfs`,r.path):n.push(`--ro-bind`,`/dev/null`,r.path));if(!t.network){if(e.seccompDescriptor===void 0)throw Error(`A sandbox without network needs the Unix-socket seccomp filter.`);n.push(`--unshare-net`,`--seccomp`,String(e.seccompDescriptor))}return n.push(`--unshare-pid`,`--die-with-parent`,`--new-session`,`--chdir`,e.cwd),n.push(`--`,e.command),[...n,...e.args]}function Le(e){return e.replace(/[\\^$.*+?()[\]{}|"]/g,e=>`\\${e}`)}function F(e){return`"${e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}"`}function Re(t){let n=[t.root,...t.tempDirectories,...t.allowWrite].map(e=>`(subpath ${F(e)})`).join(` `),r=P().map(n=>{let r=N(t.root,n);return e.yt.includes(n)?`(literal ${F(r)})`:`(subpath ${F(r)})`}),i=M.map(e=>`(subpath ${F(N(t.root,e))})`),a=[`(literal ${F(N(t.root,`.git`))})`,...M.map(e=>`(regex #"^${Le(N(t.root,e))}/[^/]+/\\.git$")`)],o=[`(version 1)`,`(allow default)`,`(deny file-write*)`,`(allow file-write* ${n} (literal "/dev/null") (regex #"^/dev/tty") (regex #"^/dev/fd/"))`,`(deny file-write* ${r.join(` `)})`,`(allow file-write* ${i.join(` `)})`,`(deny file-write* ${a.join(` `)})`];if(t.denyRead.length>0){let e=t.denyRead.map(e=>e.directory?`(subpath ${F(e.path)})`:`(literal ${F(e.path)})`);o.push(`(deny file-read* ${e.join(` `)})`)}return t.network||o.push(`(deny network*)`),o.join(`
2
2
  `)}const ze={x64:{audit:3221225534,socket:41,ioUringSetup:425},arm64:{audit:3221225655,socket:198,ioUringSetup:425}};function I(e,t,n,r){return[e,t,n,r]}function Be(e=process.arch){let t=ze[e];if(t===void 0)return;let n=e=>327680|e,r=[I(32,0,0,4),I(21,1,0,t.audit),I(6,0,0,n(1)),I(32,0,0,0),I(69,0,1,1073741824),I(6,0,0,n(1)),I(21,0,1,t.ioUringSetup),I(6,0,0,n(1)),I(21,0,3,t.socket),I(32,0,0,16),I(21,0,1,1),I(6,0,0,n(97)),I(6,0,0,2147418112)],i=new Uint8Array(r.length*8),a=new DataView(i.buffer);return r.forEach(([e,t,n,r],i)=>{a.setUint16(i*8,e,!0),a.setUint8(i*8+2,t),a.setUint8(i*8+3,n),a.setUint32(i*8+4,r>>>0,!0)}),i}const Ve=Object.freeze({enabled:!1,autoAllowBashIfSandboxed:!0,excludedCommands:[],allowWrite:[],denyRead:[],network:!1}),He=`/usr/bin/sandbox-exec`;function Ue(e,t){let n=(0,i.spawnSync)(e,[...t],{timeout:5e3,encoding:`utf8`});if(n.error!==void 0)return{ok:!1,detail:n.error.message};let r=(n.stderr??``).trim().split(`
3
3
  `)[0];return n.status===0?{ok:!0}:{ok:!1,...r?{detail:r}:{}}}function We(e={}){let t=e.platform??process.platform,n=e.probe??Ue;if(t===`linux`){if(Be(e.arch??process.arch)===void 0)return{backend:`bubblewrap`,missing:[`a seccomp filter for ${e.arch??process.arch} (x64 and arm64 are supported)`]};let t=n(`bwrap`,[`--ro-bind`,`/`,`/`,`--dev`,`/dev`,`--unshare-pid`,`true`]);return t.ok?{backend:`bubblewrap`,executable:`bwrap`,missing:[]}:{backend:`bubblewrap`,missing:[t.detail?.includes(`ENOENT`)?"bubblewrap (install the `bubblewrap` package)":`bubblewrap cannot create a sandbox here${t.detail?`: ${t.detail}`:``}`]}}if(t===`darwin`){let e=n(He,[`-p`,`(version 1)(allow default)`,`/usr/bin/true`]);return e.ok?{backend:`seatbelt`,executable:He,missing:[]}:{backend:`seatbelt`,missing:[`sandbox-exec cannot run${e.detail?`: ${e.detail}`:``}`]}}return{missing:[],unsupportedPlatform:t}}function L(e){try{return(0,o.realpathSync)(e)}catch{return e}}function Ge(e){try{return(0,o.statSync)(e).isDirectory()}catch{return!1}}function Ke(e){let t=(0,o.lstatSync)(e);if(!t.isSymbolicLink()&&((0,o.chmodSync)(e,t.mode|448),t.isDirectory()))for(let t of(0,o.readdirSync)(e))Ke(`${e}/${t}`)}function qe(e){try{return(0,o.lstatSync)(e).isSymbolicLink()}catch{return!1}}function Je(e){return e.trim().split(/\s+/)[0]}var Ye=class{filesystem=`shared`;root;availability;homeDirectory;current;inFlight=0;baseline=[];unresolved=new Map;constructor(e){this.root=L(e.root),this.availability=e.availability,this.homeDirectory=e.homeDirectory??(0,s.homedir)(),this.current={...Ve,...e.settings}}status(){return{settings:this.current,availability:this.availability,active:this.current.enabled&&this.availability.executable!==void 0}}configure(e){this.current={...this.current,...e}}confines(t){if(!this.status().active)return!1;if(e.o(t).length!==1)return!0;let n=Je(t);return n===void 0||!this.current.excludedCommands.includes(n)}autoApproves(e){return!this.current.autoAllowBashIfSandboxed||!this.confines(e)||this.unresolved.size>0?!1:!this.protectedEntryStates().some(e=>e.kind===`symlink`&&!this.resolvesOutsideWritableWorkspace(e.path))}wrapCommand(e,t){if(!this.confines(t))return e;let n=this.policy(),r=this.availability.executable;if(this.availability.backend===`seatbelt`)return{command:r,args:[`-p`,Re(n),e.command,...e.args],cwd:e.cwd};let i=n.network?void 0:Be();this.protectedEntryStates().some(e=>e.path.endsWith(`/.robota`)&&e.kind===`symlink`)||(0,o.mkdirSync)(`${this.root}/.robota`,{recursive:!0});let a=Ie({policy:n,exists:e=>(0,o.existsSync)(e)&&!qe(e),listDirectory:e=>(0,o.readdirSync)(e),cwd:e.cwd,command:e.command,args:e.args,...i===void 0?{}:{seccompDescriptor:3}});this.inFlight===0&&(this.baseline=this.protectedEntryStates().map(e=>this.unresolved.get(e.path)??e)),this.inFlight+=1;let s=!1;return{command:r,args:a,cwd:e.cwd,...i===void 0?{}:{inputDescriptors:[i]},afterExit:()=>{if(!s)return s=!0,--this.inFlight,this.restoreProtectedEntries(this.baseline)}}}protectedEntryStates(){return P().map(e=>{let t=`${this.root}/${e}`;try{return(0,o.lstatSync)(t).isSymbolicLink()?{path:t,kind:`symlink`,target:(0,o.readlinkSync)(t)}:{path:t,kind:`present`}}catch{return{path:t,kind:`missing`}}})}resolvesOutsideWritableWorkspace(e){let t;try{t=(0,o.realpathSync)(e)}catch{return!1}let n=this.policy();return![n.root,...n.tempDirectories,...n.allowWrite].some(e=>t===e||t.startsWith(`${e}/`))}restoreProtectedEntries(e){let t=`${this.quarantineRoot(e)}/${Date.now()}-${(0,n.randomUUID)()}`,r=[];for(let n of e)if(n.kind!==`present`)try{let e=this.protectedEntryStates().find(e=>e.path===n.path);if(n.kind===`missing`&&e.kind===`missing`){this.unresolved.delete(n.path);continue}if(n.kind===`symlink`&&e.kind===`symlink`&&e.target===n.target){this.unresolved.delete(n.path);continue}e.kind!==`missing`&&r.push(this.setAside(n.path,t)),n.kind===`symlink`&&(0,o.symlinkSync)(n.target,n.path),this.unresolved.delete(n.path)}catch(e){this.unresolved.set(n.path,n),r.push(`could not restore ${n.path} (${e instanceof Error?e.message:String(e)}); commands will ask until it is removed`)}if(r.length!==0)return`[sandbox] A confined command may not create or replace git, agent, MCP or shell configuration: ${r.join(`; `)}.`}quarantineRoot(e){let t=`${this.root}/.robota`;return e.some(e=>e.path===t&&e.kind===`present`)?`${t}/sandbox-quarantine`:`${this.homeDirectory}/.robota/sandbox-quarantine`}setAside(e,t){let n=`${t}/${(0,r.basename)(e)}`;(0,o.mkdirSync)(t,{recursive:!0});try{(0,o.renameSync)(e,n)}catch(t){if(this.inFlight>0)throw t;Ke(e),t.code===`EXDEV`?((0,o.cpSync)(e,n,{recursive:!0,verbatimSymlinks:!0}),(0,o.rmSync)(e,{recursive:!0,force:!0})):(0,o.renameSync)(e,n)}return`moved ${e} to ${n}`}policy(){let e=e=>{let t=e===`~`||e.startsWith(`~/`)?`${this.homeDirectory}${e.slice(1)}`:e;return L((0,r.isAbsolute)(t)?t:(0,r.resolve)(this.root,t))},t=[...new Set([(0,s.tmpdir)(),`/tmp`].filter(o.existsSync).map(L))];return{root:this.root,tempDirectories:t,allowWrite:this.current.allowWrite.map(e),denyRead:this.current.denyRead.map(t=>{let n=e(t);return{path:n,directory:Ge(n)}}),network:this.current.network}}run(e,n={}){let r=t.n(),a=n.workingDirectory??this.root,o=this.wrapCommand({command:r.command,args:r.commandArgs(e),cwd:a},e);return new Promise((e,t)=>{let r=o.inputDescriptors??[],a;try{a=(0,i.spawn)(o.command,[...o.args],{cwd:o.cwd,stdio:[`ignore`,`pipe`,`pipe`,...r.map(()=>`pipe`)],...n.timeoutMs===void 0?{}:{timeout:n.timeoutMs}})}catch(e){o.afterExit?.(),t(e instanceof Error?e:Error(String(e)));return}r.forEach((e,t)=>{let n=a.stdio[t+3];n?.on(`error`,()=>void 0),n?.end(Buffer.from(e))});let s=``,c=``;a.stdout?.on(`data`,e=>s+=e.toString()),a.stderr?.on(`data`,e=>c+=e.toString()),a.on(`error`,e=>{o.afterExit?.(),t(e)}),a.on(`close`,t=>{let n=o.afterExit?.();e({stdout:n===void 0?s:`${s}\n${n}`,...c?{stderr:c}:{},exitCode:t??1})})})}readFile(e){return Promise.resolve((0,o.readFileSync)(e,`utf8`))}writeFile(e,t){return(0,o.writeFileSync)(e,t,`utf8`),Promise.resolve()}};function R(n,r,i,a,o={}){let s={name:n,description:r,parameters:e.et(i),...o.deferLoading!==void 0&&{deferLoading:o.deferLoading}};return new e.Mt(s,async(e,n)=>{let r=i.safeParse(e);if(!r.success)throw new t.v(`Zod validation failed: ${r.error}`);let o=await a(r.data,n);return typeof o==`string`?o:JSON.stringify(o)})}const Xe={Read:{argument:{key:`filePath`,kind:`path`},riskClass:`inspect`},Glob:{argument:{key:`pattern`,kind:`text`},riskClass:`inspect`},Grep:{argument:{key:`pattern`,kind:`text`},riskClass:`inspect`},WebFetch:{argument:{key:`url`,kind:`url`},riskClass:`inspect`},WebSearch:{argument:{key:`query`,kind:`text`},riskClass:`inspect`},CodebaseRetrieval:{riskClass:`inspect`},AskUserQuestion:{riskClass:`inspect`},ToolSearch:{argument:{key:`query`,kind:`text`},riskClass:`inspect`},ComputerView:{riskClass:`inspect`},Write:{argument:{key:`filePath`,kind:`path`},riskClass:`modify`},Edit:{argument:{key:`filePath`,kind:`path`},riskClass:`modify`},Shell:{argument:{key:`command`,kind:`command`},riskClass:`execute`,aliases:[`Bash`]},Bash:{argument:{key:`command`,kind:`command`},riskClass:`execute`,aliases:[`Shell`]},Computer:{riskClass:`execute`}};function Ze(){for(let[t,n]of Object.entries(Xe))e.B(t,n)}Ze();const Qe=1e3,$e=c.z.object({activeFiles:c.z.array(c.z.string()).optional().describe(`Repo-relative files currently in focus; the map is ranked toward what they reference.`),mentionedIdentifiers:c.z.array(c.z.string()).optional().describe(`Symbol names to bias the map toward (e.g. identifiers named in the task).`),tokenBudget:c.z.number().int().positive().optional().describe(`Maximum tokens for the returned map (default ${Qe}).`)});function et(e){return e.map(e=>`${e.file}:${e.line} ${e.kind} ${e.name}`).join(`
4
4
  `)}async function tt(e,t={}){if(!t.adapter)return`Codebase retrieval is not available in this session.`;let n=await t.adapter.retrieve({...e.activeFiles?{activeFiles:e.activeFiles}:{},...e.mentionedIdentifiers?{mentionedIdentifiers:e.mentionedIdentifiers}:{},tokenBudget:e.tokenBudget??Qe});return n.symbols.length===0?`No relevant symbols found within the token budget.`:`Most relevant symbols (~${n.totalTokens} tokens):\n${et(n.symbols)}`}function nt(e={}){return R(`CodebaseRetrieval`,`Retrieve the most relevant slice of the codebase (a ranked repo map of symbols) for the current task, within a token budget. Provide the files you are focused on and/or identifiers named in the task; returns the highest-centrality definitions first.`,$e,async t=>tt(t,e))}const rt=`Computer use is not available in this session (no driver injected).`,it=c.z.enum([`left`,`right`,`middle`]),at=c.z.object({x:c.z.number(),y:c.z.number()}),ot=c.z.object({type:c.z.enum([`click`,`double_click`,`type`,`keypress`,`scroll`,`drag`,`wait`,`takeover`]).describe(`Which action to perform.`),x:c.z.number().optional().describe(`X coordinate (click/double_click/scroll).`),y:c.z.number().optional().describe(`Y coordinate (click/double_click/scroll).`),button:it.optional().describe(`Mouse button (click/double_click/drag).`),text:c.z.string().optional().describe(`Text to type (type).`),keys:c.z.array(c.z.string()).optional().describe(`Keys to press as a chord (keypress).`),deltaX:c.z.number().optional().describe(`Horizontal wheel delta (scroll).`),deltaY:c.z.number().optional().describe(`Vertical wheel delta (scroll).`),path:c.z.array(at).optional().describe(`Points to drag through (drag).`),ms:c.z.number().optional().describe(`Milliseconds to wait (wait).`),reason:c.z.string().optional().describe(`Human-readable reason surfaced to the user (takeover).`)}),st=c.z.object({action:ot.describe(`The single mutating action to perform.`)}),ct=c.z.object({});var z=class extends Error{};function B(e,t,n){if(typeof e!=`number`)throw new z(`Action '${n}' requires numeric '${t}'.`);return e}function lt(e){let t=e.button;switch(e.type){case`click`:return{type:`click`,x:B(e.x,`x`,`click`),y:B(e.y,`y`,`click`),...t?{button:t}:{}};case`double_click`:return{type:`double_click`,x:B(e.x,`x`,`double_click`),y:B(e.y,`y`,`double_click`),...t?{button:t}:{}};case`type`:if(typeof e.text!=`string`)throw new z(`Action 'type' requires 'text'.`);return{type:`type`,text:e.text};case`keypress`:if(!e.keys||e.keys.length===0)throw new z(`Action 'keypress' requires non-empty 'keys'.`);return{type:`keypress`,keys:e.keys};case`scroll`:return{type:`scroll`,x:B(e.x,`x`,`scroll`),y:B(e.y,`y`,`scroll`),deltaX:B(e.deltaX,`deltaX`,`scroll`),deltaY:B(e.deltaY,`deltaY`,`scroll`)};case`drag`:if(!e.path||e.path.length<2)throw new z(`Action 'drag' requires a 'path' of at least two points.`);return{type:`drag`,path:e.path,...t?{button:t}:{}};case`wait`:return{type:`wait`,...typeof e.ms==`number`?{ms:e.ms}:{}};case`takeover`:return{type:`takeover`,...e.reason?{reason:e.reason}:{}};default:{let t=e.type;throw new z(`Unknown action type: ${String(t)}`)}}}async function ut(e){if(!e.driver)return JSON.stringify({success:!1,error:rt});let t=await e.driver.screenshot();return JSON.stringify(t?{success:!0,screenshot:t}:{success:!0,takeover:!0})}async function dt(e,t){if(!t.driver)return JSON.stringify({success:!1,error:rt});let n;try{n=lt(e.action)}catch(e){return JSON.stringify({success:!1,error:e instanceof Error?e.message:String(e)})}let r=await t.driver.act(n),i={success:!0,...r.screenshot?{screenshot:r.screenshot}:{},...r.takeover?{takeover:!0}:{}};return JSON.stringify(i)}function ft(e={}){return R(`ComputerView`,`Perceive the computer/browser surface: capture and return a screenshot of the current screen so you can reason about what to do next. Read-only — it never changes anything.`,ct,async()=>ut(e))}function pt(e={}){return R(`Computer`,"Perform one mutating action on the computer/browser surface (click, double_click, type, keypress, scroll, drag, wait, or takeover) and return the resulting screenshot. Use `takeover` to hand control to the human for sensitive input (credentials/payment); perception is paused during a takeover.",st,async t=>dt(t,e))}function mt(e={}){return[ft(e),pt(e)]}const ht=[{toolName:`Glob`,hint:` - File search: Use Glob (NOT find or ls)`},{toolName:`Grep`,hint:` - Content search: Use Grep (NOT grep or rg)`},{toolName:`Read`,hint:` - Read files: Use Read (NOT cat/head/tail)`},{toolName:`Edit`,hint:` - Edit files: Use Edit (NOT sed/awk)`}];function gt(e,t){let n=t?ht.filter(e=>t.includes(e.toolName)):ht,r=n.length>0?["IMPORTANT: Avoid using this tool to run `find`, `grep`, `cat`, `head`, `tail`, `sed`, `awk`, or `echo` commands. Instead, use the appropriate dedicated tool:",...n.map(e=>e.hint)]:[];return[`Executes a command in the host shell and returns its output.`,``,`Active shell: ${e.label}. ${e.syntaxHint}`,``,`Each command runs in a fresh shell in workingDirectory (default: the configured working directory); no shell state carries over between calls.`,``,...r].join(`