@robota-sdk/agent-cli 3.0.0-beta.100 → 3.0.0-beta.101
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +18 -8
- package/dist/node/bin.js +3 -3
- package/dist/node/cli-core-CIzUq54B.js +2920 -0
- package/dist/node/desktop-host.js +1 -1
- package/dist/node/headless.js +1 -1
- package/dist/node/host.d.ts +1 -1
- package/dist/node/host.js +1 -1
- package/dist/node/index.d.ts +1 -1
- package/dist/node/index.js +1 -1
- package/dist/node/index.js.map +1 -1
- package/dist/node/{node-CdgadDFa.js → node-AQEjsK5o.js} +2 -2
- package/dist/node/{node-CdgadDFa.js.map → node-AQEjsK5o.js.map} +1 -1
- package/dist/node/node-B5wKOmx1.js +165 -0
- package/dist/node/node-B5wKOmx1.js.map +1 -0
- package/dist/node/{node-aM3G__lp.js → node-BQfSVkbA.js} +1 -1
- package/dist/node/node-BRrU0Q8C.js +165 -0
- package/dist/node/{node-BTKWbzr0.js → node-CvUY6TbD.js} +2 -2
- package/dist/node/{node-BZfTvzcV.js → node-DQ4XoykT.js} +3 -3
- package/dist/node/node-DQ4XoykT.js.map +1 -0
- package/dist/node/product-host-Btm4B-p5.js +2954 -0
- package/dist/node/product-host-Btm4B-p5.js.map +1 -0
- package/dist/node/{product-host-DYR8lHfh.d.ts → product-host-Cle0fPIc.d.ts} +3 -3
- package/dist/node/{product-host-DYR8lHfh.d.ts.map → product-host-Cle0fPIc.d.ts.map} +1 -1
- package/package.json +38 -38
- package/dist/node/cli-core-QK7sBRp8.js +0 -2920
- package/dist/node/node-BRvqhy29.js +0 -165
- package/dist/node/node-BRvqhy29.js.map +0 -1
- package/dist/node/node-BZfTvzcV.js.map +0 -1
- package/dist/node/node-zABT8WBL.js +0 -165
- package/dist/node/product-host-CwqVX6Xg.js +0 -2954
- package/dist/node/product-host-CwqVX6Xg.js.map +0 -1
|
@@ -9,7 +9,7 @@ import{C as e,S as t,_ as n,a as r,b as i,c as a,d as o,f as s,g as c,i as l,l a
|
|
|
9
9
|
`),n.beginAssistant();let b=io(),{wrappedOnTextDelta:x,wrappedOnProviderNativeRawPayload:S,settleStreamingChunkHooks:C}=xo(a,n,i,p,l,u),w=Ka(s,o.defaultModel.model,i),T=W(),E;try{E=await So(_,o,s,f,a,n,p,i,b,u,x,S,t=>void(e.providerFailure=t),w,T,a.executionJournal?Da(m,e,a,o,t,c.toolExecutionService.getLoadedDeferredTools()):void 0)}finally{await C()}if(E===null)return!0;let{assistantResponse:D,assistantToolCalls:O}=eo(E,i,a.conversationId,p,u);if(O.length>0&&(a.toolChoice??o.defaultModel?.toolChoice)===`none`)throw Error(`Provider returned tool calls despite toolChoice none; no tools were executed.`);await G(l,`afterProviderCall`,{messages:m,responseMessage:E},u),await G(l,`onMessageAdded`,{message:E},u);let ee=typeof D.content==`string`&&D.content.trim().length>0;if(O.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=oo(D),ne=te.inputTokens??0;ne>0&&(e.cumulativeInputTokens=ne);for(let e of O)n.appendToolCall(e);let re=a.signal?.aborted?`interrupted`:`complete`;n.commitAssistant(re,{round:p,usageObservationId:b,executionId:i,providerId:K(w,s),providerCallId:T,modelId:q(w,s.aiProviderInfo.model),...te});let ie=n.getMessages().at(-1);return a.onExecutionEvent?.(`assistant_message_committed`,{executionId:i,conversationId:a.conversationId,round:p,message:D}),ie&&a.onExecutionEvent?.(`history_mutation`,{executionId:i,conversationId:a.conversationId,round:p,mutation:`append_message`,index:n.getMessages().length-1,message:ie}),e.runningAssistantCount++,e.lastTrackedAssistantMessage=D,O.length===0?(u.debug(`[AGENT-FLOW-CONTROL] Round ${p} completed - no tool calls, execution finished for agent ${a.conversationId}`),d.emitAssistantMessageComplete(D,i,p,r,v,y),!0):_o(await No(O,n,r,i,p,v,y,e,c,o,a.signal,a.onExecutionEvent,a.maxSameToolInputs??o.maxSameToolInputs,a.traceContext,a.executionJournal?{journal:a.executionJournal,parentCallId:T}:void 0),e,u)?!0:(u.debug(`Round ${p} completed for agent ${a.conversationId}`),!1)}function Fo(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 Io(e,t){return t===0||e<t}async function Lo(t,n,r,i,a,o,s,c,l,u=!1){let d=Fo(a,i);for(;!u&&!s.forcedSummaryInstruction&&Io(s.currentRound,d)&&!(c?.aborted||(s.currentRound++,await Po(s,d,t,n,r,i,a,o,l))||c?.aborted););let f=t.getMessages(),p=f.length>0?f[f.length-1]:void 0,m=p?.role===`assistant`&&typeof p.content==`string`&&p.content.length>0&&(!(`toolCalls`in p)||p.toolCalls.length===0);if(!c?.aborted){if(i.allowToolOnlyCompletion===!0){let t=p?.role===`tool`;if(!m&&!t)throw new e(s.currentRound,{conversationId:n,executionId:r});return}m||await go(t,o,a,r,s,n,i,l.logger,d,i.executionJournal?l.toolExecutionService.getLoadedDeferredTools():void 0)}}async function Ro(e,t,n,r,i,a,o,s,c,l,u,d){let f={...Ea(t,n,r,i.toolsExecuted,{turnMessageId:o,interrupted:s,...c?.allowToolOnlyCompletion===!0&&{allowToolOnlyCompletion:!0}},i.providerFailure),interrupted:s};await G(l,`afterRun`,{input:e,response:f.response,metadata:c?.metadata},u);let p={messages:f.messages,executionContext:{executionId:n,conversationId:a},executionResult:{response:f.response,duration:f.duration,...f.tokensUsed===void 0?{}:{tokensUsed:f.tokensUsed},toolsExecuted:f.toolsExecuted.length,success:f.success,toolCalls:i.toolCallOutcomes.map(e=>({...e.id===void 0?{}:{id:e.id},name:e.name,...e.success?{}:{result:null}}))}};for(let e of[`afterExecution`,`afterConversation`,`afterToolExecution`])await G(l,e,p,u);return u.debug(`Execution pipeline completed successfully`,{executionId:n,conversationId:a,duration:f.duration,tokensUsed:f.tokensUsed,toolsExecuted:f.toolsExecuted.length,rounds:i.currentRound}),d.emitExecution(P.COMPLETE,{result:{success:!0,data:f.response.substring(0,100)+`...`},metadata:{method:`execute`,success:!0,duration:f.duration,tokensUsed:f.tokensUsed,toolsExecuted:f.toolsExecuted}},a,n),f}function J(e){return JSON.stringify(e,(e,t)=>t&&typeof t==`object`&&!Array.isArray(t)?Object.fromEntries(Object.entries(t).sort(([e],[t])=>e.localeCompare(t))):t)}function Y(e){throw new z(`EXECUTION_RECOVERY_INVALID`,e)}function X(e){return typeof e==`string`&&e.length>0}function zo(e,t,n,r=!0){try{return Bo(structuredClone(e),t,n,r)}catch(e){if(e instanceof z)throw e;return Y(`Execution journal is not a valid recoverable record prefix`)}}function Bo(e,t,n,r){(!X(t)||!X(n)||!Array.isArray(e))&&Y(`Missing recovery identity`);let i=[],a=new Map,o,s=new Map,c=new Map,l=new Set,u=new Set;for(let n of e){(!n||n.executionId!==t||!X(n.recordId))&&Y(`Journal execution identity mismatch`);let e=J(n),r=a.get(n.recordId);if(r!==void 0){e!==r&&Y(`Conflicting journal record identity`);continue}if(a.set(n.recordId,e),i.push(n),`callId`in n)X(n.callId)||Y(`Missing model call identity`),n.kind===`model-request`||n.kind===`model-cache-hit`?o=n.callId:n.callId!==o&&Y(`Model settlement crossed a newer invocation`);else if(`actionId`in n){(!X(n.actionId)||!X(n.parentCallId))&&Y(`Missing action identity`);let e=s.get(n.actionId),t=J([n.parentCallId,n.toolCallId,n.toolName]);if(e&&e!==t&&Y(`Action identity belongs to multiple calls`),s.set(n.actionId,t),n.kind===`tool-wait`&&((!n.request||!X(n.request.requestId)||!X(n.request.kind)||c.has(n.request.requestId))&&Y(`Invalid or duplicate tool wait`),Do(n.request.data),c.set(n.request.requestId,n)),n.kind===`tool-response`){let e=n.response,t=e&&c.get(e.requestId);(!t||!X(e.responseId)||l.has(e.requestId)||u.has(e.responseId)||t.actionId!==n.actionId||t.parentCallId!==n.parentCallId||t.toolCallId!==n.toolCallId||t.toolName!==n.toolName)&&Y(`Tool response does not belong to an unanswered request`),Do(e.response),l.add(e.requestId),u.add(e.responseId)}}else Y(`Unknown journal record`)}o!==n&&Y(`Only the latest model invocation can be recovered`);let d,f,p,m=new Map;for(let e of i){if(`callId`in e){if(e.callId!==n)continue;e.kind===`model-request`?((d||f)&&Y(`Duplicate or out-of-order model request`),d=e):e.kind===`model-cache-hit`?((d||f||e.response.role!==`assistant`)&&Y(`Invalid cache settlement`),f=e.response,p=e.checkpoint):e.kind===`model-response`?((!d||f||e.response.role!==`assistant`)&&Y(`Invalid model response`),f=e.response):Y(`This model invocation has no recoverable tool response`);continue}if(e.parentCallId!==n)continue;f||Y(`Tool action precedes its model response`);let r=f.toolCalls?.find(t=>t.id===e.toolCallId);(!r||e.toolName!==r.function.name)&&Y(`Action does not belong to the saved model response`);let i=m.get(e.toolCallId);if(i&&i.actionId!==e.actionId&&Y(`Multiple actions claim one tool call`),i||(i={actionId:e.actionId,intent:!1,dispatched:!1,effectStarted:!1,waits:[]},m.set(e.toolCallId,i)),i.result&&Y(`Tool action continued after settlement`),e.kind===`tool-intent`)(i.intent||i.dispatched||i.effectStarted)&&Y(`Out-of-order action intent`),J(JSON.parse(r.function.arguments))!==J(e.parameters)&&Y(`Action arguments differ from saved intent`),i.intent=!0;else if(e.kind===`tool-dispatch`)(!i.intent||i.dispatched||i.effectStarted)&&Y(`Out-of-order dispatch`),i.dispatched=!0;else if(e.kind===`tool-effect-start`)(!i.dispatched||i.effectStarted)&&Y(`Out-of-order effect admission`),i.waits.some(e=>!e.response)&&Y(`Tool effect precedes a required response`),i.effectStarted=!0;else if(e.kind===`tool-wait`)(!i.dispatched||i.effectStarted)&&Y(`Tool wait is outside pre-effect dispatch`),i.waits.push({request:{...e.request,executionId:t,actionId:e.actionId,parentCallId:e.parentCallId,toolCallId:e.toolCallId,toolName:e.toolName}});else if(e.kind===`tool-response`){let t=i.waits.find(t=>t.request.requestId===e.response.requestId);(!t||t.response||i.effectStarted)&&Y(`Out-of-order tool response`),t.response=e.response}else if(e.kind===`tool-result`){let t=e.result,n=t.metadata?.errorCode===yt;n&&(t.success||i.dispatched||i.effectStarted||t.metadata?.dispatchStatus!==`not-dispatched`||t.result!==null)&&Y(`Skipped tool result cannot claim a dispatched or applied effect`),(!i.intent&&t.metadata?.errorCode!==`argument_decode_error`&&!n||t.executionId!==r.id||t.toolName!==r.function.name||typeof t.success!=`boolean`||t.success&&(!i.effectStarted||t.result===void 0)||!t.success&&!X(t.error))&&Y(`Invalid tool result linkage or payload`),e.loadedDeferredTools!==void 0&&(!Array.isArray(e.loadedDeferredTools)||e.loadedDeferredTools.some(e=>!X(e)))&&Y(`Invalid tool residency settlement`),i.result=t,i.loadedDeferredTools=e.loadedDeferredTools}else Y(`Unknown action record`)}let h=d?.checkpoint??p;(!f||!h||h.version!==1||h.effectAdmission!==`required`)&&Y(`A supported effect-admission checkpoint is required`),(!Number.isSafeInteger(h.round)||h.round<1||!Number.isFinite(h.contextLimit)||h.contextLimit<=0||!Number.isFinite(h.cumulativeInputTokens)||h.cumulativeInputTokens<0||!Array.isArray(h.messages)||!Array.isArray(h.sameToolInputCounts))&&Y(`Invalid round checkpoint`);let g=new Set;for(let e of h.messages)g.has(e.id)&&Y(`Duplicate checkpoint message identity`),g.add(e.id);for(let e of[...h.messages,f])(!X(e.id)||!(e.timestamp instanceof Date)||!Number.isFinite(e.timestamp.getTime())||(e.role===`assistant`?e.content!==null&&typeof e.content!=`string`:typeof e.content!=`string`)||e.role===`tool`&&!X(e.toolCallId)||![`user`,`assistant`,`system`,`tool`].includes(e.role)||![`complete`,`interrupted`].includes(e.state))&&Y(`Invalid checkpoint message`);let _=new Set;for(let[e,t]of h.sameToolInputCounts)(!X(e)||_.has(e)||!Number.isSafeInteger(t)||t<0)&&Y(`Invalid repeated-input checkpoint`),_.add(e);h.maxSameToolInputs!==void 0&&(!Number.isSafeInteger(h.maxSameToolInputs)||h.maxSameToolInputs<1)&&Y(`Invalid repeated-input limit`),r&&(!Array.isArray(f.toolCalls)||f.toolCalls.length===0)&&Y(`Saved response has no tool calls`),g.clear();for(let e of f.toolCalls??[])(!X(e.id)||g.has(e.id)||e.type!==`function`||!X(e.function?.name)||typeof e.function.arguments!=`string`)&&Y(`Invalid or duplicate saved tool call`),g.add(e.id);d?.options.toolChoice===`none`&&(f.toolCalls?.length??0)>0&&Y(`Saved invocation prohibited tool execution`);let v=[...m.values()].filter(e=>e.effectStarted&&!e.result);if(v.length)throw new z(`EXECUTION_RECOVERY_REQUIRED`,`Tool effects have no durable result; reconcile them before resuming`,v.map(e=>e.actionId));return{checkpoint:h,response:f,actions:m,offeredDeferredTools:d?.options.tools?.filter(e=>e.deferLoading).map(e=>e.name)??[]}}function Vo(e){throw new z(`EXECUTION_RECOVERY_CONFLICT`,e)}function Ho(e,t){return{...structuredClone(e.response),id:`recovery:${t.executionId}:${t.callId}:assistant`,...e.checkpoint.continuation?.kind===`summary`&&{content:e.response.content||`Maximum rounds reached. Partial results available in conversation history.`,toolCalls:[]},metadata:{...e.response.metadata,...oo(e.response),executionId:t.executionId,providerCallId:t.callId,round:e.checkpoint.round}}}function Uo(e,t,n,r){return e.role===`assistant`&&t.role===`assistant`&&(e.content??``)===(t.content??``)&&J(e.toolCalls??[])===J(t.toolCalls??[])&&e.metadata?.providerCallId===n&&e.metadata.executionId===r}function Wo(e,t,n,r){if(!e.length)return;let i=t.checkpoint.messages;(e.length<i.length||J(e.slice(0,i.length))!==J(i))&&Vo(`Current history differs from the saved runtime checkpoint`);let a=e.slice(i.length);if(!a.length)return;Uo(a[0],Ho(t,n),n.callId,n.executionId)||Vo(`Current assistant does not match the saved response`);let o=t.response.toolCalls??[];a.length>o.length+1&&Vo(`History has advanced beyond the recovered tool batch`);let s=o.slice(0,a.length-1),c=s.map(e=>{let n=t.actions.get(e.id)?.result;return n||Vo(`History contains a tool result without durable settlement`),n}),l=new Un;for(let e of i)l.addMessage(e);l.addMessage(a[0]),To(s,{results:c,errors:[]},l,t.checkpoint.round,r.logger,{contextLimit:t.checkpoint.contextLimit,cumulativeInputTokens:Go(t)});for(let e=1;e<a.length;e++){let t=l.getMessages()[i.length+e],n=a[e];(n.role!==`tool`||t.role!==`tool`||n.toolCallId!==t.toolCallId||n.name!==t.name||n.content!==t.content)&&Vo(`Existing tool result conflicts with the durable result`)}}function Go(e){let t=oo(e.response).inputTokens??0;return t>0?t:e.checkpoint.cumulativeInputTokens}async function Ko(e,t,n,r,i){let a=J(e.getMessages()),o=()=>{(a!==J(e.getMessages())||e.hasPendingAssistant())&&Vo(`History changed during execution recovery`)};o();let s=i?.records??await n.journal.read(n.executionId),c=i?.batch??zo(s,n.executionId,n.callId);n.signal?.throwIfAborted(),o();let l=structuredClone(e.getMessages());Wo(l,c,n,r);let u=await Ao(s,n);u.length!==s.length&&(c=zo(u,n.executionId,n.callId,!1)),n.signal?.throwIfAborted(),o();let d=new Set([...c.checkpoint.continuation?.loadedDeferredTools??[],...c.offeredDeferredTools]);for(let e of c.actions.values())for(let t of e.loadedDeferredTools??[])d.add(t);r.toolExecutionService.restoreLoadedDeferredTools([...d]);let f=new Un;for(let e of c.checkpoint.messages)f.addMessage(structuredClone(e));let p=c.checkpoint.continuation?.kind===`summary`,m=c.response.toolCalls??[];(p||m.length>0||(c.response.content?.trim().length??0)>0)&&f.addMessage(Ho(c,n));let h={toolsExecuted:[...c.checkpoint.continuation?.toolsExecuted??[]],toolCallOutcomes:[],currentRound:c.checkpoint.round,runningAssistantCount:f.getMessages().filter(e=>e.role===`assistant`).length,lastTrackedAssistantMessage:c.response,cumulativeInputTokens:Go(c),consecutiveUnknownToolFailureRounds:c.checkpoint.continuation?.consecutiveUnknownToolFailureRounds??0,forcedSummaryInstruction:c.checkpoint.continuation?.forcedSummaryInstruction,sameToolInputCounts:new Map(c.checkpoint.sameToolInputCounts)};r.eventEmitter.prepareOwnerPathBases(t);try{let i=m.length===0;m.length>0&&(i=_o(await No(m,f,t,n.executionId,c.checkpoint.round,n.callId,void 0,h,r,void 0,n.signal,void 0,c.checkpoint.maxSameToolInputs,void 0,{journal:n.journal,parentCallId:n.callId,recovery:c}),h,r.logger)),o();for(let t of f.getMessages().slice(l.length))e.addMessage(t);let a=structuredClone(e.getMessages()),s=J(a);for(let r=l.length;r<a.length;r++)n.onExecutionEvent?.(`history_mutation`,{executionId:n.executionId,conversationId:t,round:c.checkpoint.round,mutation:`append_message`,index:r,message:a[r]}),(s!==J(e.getMessages())||e.hasPendingAssistant())&&Vo(`History changed while announcing execution recovery`);if(n.signal?.aborted)throw Dt(`Execution recovery interrupted`,n.signal.reason);return{executionId:n.executionId,callId:n.callId,messages:structuredClone(e.getMessages()),batch:c,state:h,stop:i}}finally{r.eventEmitter.clearToolEventServices(),r.eventEmitter.resetOwnerPathBases()}}async function qo(e,t,n,r){let{executionId:i,callId:a,messages:o}=await Ko(e,t,n,r);return{executionId:i,callId:a,messages:o}}function Z(e){throw new z(`EXECUTION_RECOVERY_INVALID`,e)}function Jo(e){return(!e||e.version!==1||![`round`,`summary`].includes(e.kind)||typeof e.startedAt!=`string`||!Number.isFinite(Date.parse(e.startedAt))||typeof e.turnMessageId!=`string`||e.turnMessageId.length===0||!e.model||typeof e.model.provider!=`string`||typeof e.model.model!=`string`||!e.model.provider||!e.model.model||!e.options||!Number.isSafeInteger(e.options.maxExecutionRounds)||e.options.maxExecutionRounds<0||!Array.isArray(e.toolsExecuted)||e.toolsExecuted.some(e=>typeof e!=`string`)||!Number.isSafeInteger(e.consecutiveUnknownToolFailureRounds)||e.consecutiveUnknownToolFailureRounds<0||!Array.isArray(e.loadedDeferredTools)||e.loadedDeferredTools.some(e=>typeof e!=`string`||!e)||typeof e.structuredOutput!=`boolean`||typeof e.options.allowToolOnlyCompletion!=`boolean`||typeof e.options.withholdHostedTools!=`boolean`)&&Z(`Unsupported runtime continuation checkpoint`),e.structuredOutput&&Z(`Structured-output validators do not yet support execution continuation`),e}async function Yo(e,t,n,r,i,a){let o=J(e.getMessages()),s=await n.journal.read(n.executionId);n.signal?.throwIfAborted();let c=s.findLast(e=>e.kind===`model-request`||e.kind===`model-cache-hit`);if((!c||!(`callId`in c))&&Z(`No recoverable model invocation exists`),c.kind===`model-request`&&!s.some(e=>e.kind===`model-response`&&e.callId===c.callId))throw new z(`EXECUTION_RECOVERY_REQUIRED`,`The latest model invocation has no durable response; reconcile it before resuming`);let l=zo(s,n.executionId,c.callId,!1),u=Jo(l.checkpoint.continuation);(u.model.provider!==r.defaultModel.provider||u.model.model!==r.defaultModel.model)&&Z(`Active provider and model must match the saved runtime before continuation`);let d=l.checkpoint.messages.find(e=>e.id===u.turnMessageId);(!d||d.role!==`user`||d.metadata?.executionId!==n.executionId)&&Z(`Continuation has no matching original input`),(u.toolSearch??`auto`)!==(r.toolSearch??`auto`)&&Z(`Tool residency policy differs from the saved runtime`),r.responseFormat&&r.responseFormat.type!==`text`&&Z(`Current runtime requires an unsupported structured-output validator`),u.options.maxSameToolInputs!==l.checkpoint.maxSameToolInputs&&Z(`Conflicting repeated-input limits`),u.kind===`summary`&&(l.response.toolCalls?.length??0)>0&&Z(`Terminal summary cannot dispatch tools`);for(let e of l.actions.values())e.result&&e.loadedDeferredTools===void 0&&Z(`Settled action lacks runtime residency state`);let f={...r,defaultModel:structuredClone(u.model),timeout:u.timeout,maxExecutionRounds:u.options.maxExecutionRounds,maxSameToolInputs:u.options.maxSameToolInputs},p=i(f);if(p.currentInfo.provider!==u.model.provider&&Z(`Active provider manager differs from the saved runtime`),o!==J(e.getMessages()))throw new z(`EXECUTION_RECOVERY_CONFLICT`,`History changed while reading the execution journal`);let m=await Ko(e,t,{...n,callId:c.callId},a,{batch:l,records:s}),h=Ha(e.getMessages(),f,new Date(u.startedAt),n.executionId,t,{...u.options,signal:n.signal,executionJournal:n.journal,onTextDelta:n.onTextDelta,onThinkingDelta:n.onThinkingDelta,onExecutionEvent:n.onExecutionEvent,traceContext:n.traceContext});a.eventEmitter.prepareOwnerPathBases(t);try{if(await Lo(e,t,n.executionId,h,f,p,m.state,n.signal,a,m.stop||u.kind===`summary`),n.signal?.aborted)throw Dt(`Execution continuation interrupted`,n.signal.reason);return Ea(e,n.executionId,h.startTime,m.state.toolsExecuted,{turnMessageId:u.turnMessageId,allowToolOnlyCompletion:u.options.allowToolOnlyCompletion},m.state.providerFailure)}finally{a.eventEmitter.clearToolEventServices(),a.eventEmitter.resetOwnerPathBases()}}async function*Xo(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 Zo(e,t,n){return{executionId:e,...t===void 0?{}:{driverId:t},...n===void 0?{}:{turnSource:n}}}var Qo=class{toolExecutionService;aiProviders;tools;conversationHistory;plugins=[];logger;eventEmitter;cacheService;constructor(e,t,n,r,i,a){if(this.toolExecutionService=new fa(t),this.aiProviders=e,this.tools=t,this.conversationHistory=n,this.plugins=[],this.logger=j(`ExecutionService`),!r)throw Error(`[EXECUTION] EventService is required`);this.eventEmitter=new Sa(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`)}resume(e,t,n){return Yo(this.conversationHistory.getConversationStore(e),e,t,n,e=>Ia(this.aiProviders,this.tools,e),{toolExecutionService:this.toolExecutionService,plugins:this.plugins,logger:this.logger,eventEmitter:this.eventEmitter,cacheService:this.cacheService})}resumeToolCalls(e,t){return qo(this.conversationHistory.getConversationStore(e),e,t,{toolExecutionService:this.toolExecutionService,plugins:this.plugins,logger:this.logger,eventEmitter:this.eventEmitter})}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=Ba(),a=new Date,o=Va(r,`execute`),s=Ha(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=Ia(this.aiProviders,this.tools,n);this.eventEmitter.emitExecutionStartEvent(e,n,t,c,o,i);let l=Ra(this.conversationHistory,o,t,n,i),u,d={toolsExecuted:[],toolCallOutcomes:[],currentRound:0,runningAssistantCount:0,lastTrackedAssistantMessage:void 0,cumulativeInputTokens:0,consecutiveUnknownToolFailureRounds:0,sameToolInputCounts:new Map};try{let t=l.getMessages().length;l.addUserMessage(e,Zo(i,r?.driverId,r?.turnSource));let f=l.getMessages().at(-1);u=f?.id,f&&s.onExecutionEvent?.(`history_mutation`,{executionId:i,conversationId:o,mutation:`append_message`,index:t,message:f}),this.eventEmitter.emitUserMessageEvent(e,o,i),await G(this.plugins,`beforeRun`,{input:e,...r?.metadata?{metadata:r.metadata}:{}},this.logger);let p={executionId:i,conversationId:o};f&&await G(this.plugins,`onMessageAdded`,{message:f,executionContext:p},this.logger);for(let e of[`beforeExecution`,`beforeConversation`])await G(this.plugins,e,{messages:l.getMessages(),executionContext:p},this.logger);La(c);for(let e of l.getMessages())e.role===`assistant`&&(d.runningAssistantCount++,d.lastTrackedAssistantMessage=e);return await Lo(l,o,i,s,n,c,d,r?.signal,{toolExecutionService:this.toolExecutionService,plugins:this.plugins,logger:this.logger,eventEmitter:this.eventEmitter,cacheService:this.cacheService}),Ro(e,l,i,a,d,o,u,r?.signal?.aborted??!1,r,this.plugins,this.logger,this.eventEmitter)}catch(e){if(B(e))throw e;return Et(e,r?.signal)?{...Ea(l,i,a,d.toolsExecuted,{turnMessageId:u,interrupted:!0}),interrupted:!0}:(await za(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*Xo(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 $o(e){let t=new Ni;if(e.aiProviders)for(let n of e.aiProviders)t.addProvider(n.name,n,{ownership:e.providerOwnership&&Object.hasOwn(e.providerOwnership,n.name)?e.providerOwnership[n.name]:`owned`});return e.defaultModel&&t.setCurrentProvider(e.defaultModel.provider,e.defaultModel.model),t}async function es(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 ConversationAgent 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 wt&&c&&e.setEventService(c),r.addResultTool(e.schema,async(t,n)=>{if(!n)throw Error(`[AGENT] Missing ToolExecutionContext for tool execution`);return Fr(e,t,n)},e.provenance),l.debug(`Tool registered during initialization`,{toolName:e.schema.name});let u;t.cache?.enabled&&(u=new Ii(new Fi({maxEntries:t.cache.maxEntries,ttlMs:t.cache.ttlMs}),new Pi));let d=new Qo(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(`ConversationAgent initialization completed successfully with independent managers`),d}async function ts(e){try{let t=await es(e.ctx);e.setExecutionService(t),e.setFullyInitialized(!0)}catch(t){throw e.ctx.logger.error(`ConversationAgent initialization failed`,{error:t instanceof Error?t.message:String(t)}),t}}function ns(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 rs(e){e.logger.debug(`Destroying ConversationAgent 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 ConversationAgent 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(`ConversationAgent instance destroyed successfully`,{name:e.name}):e.logger.warn(`ConversationAgent instance destroyed with cleanup failures`,{name:e.name,failureCount:t.length}),{errors:t}}var is=class{tail=Promise.resolve();claimed=0;async acquire(e){let t=this.claimed>0;this.claimed+=1;let n=this.tail,r=()=>{};this.tail=new Promise(e=>{r=e});let i=!1,a=()=>{i||(i=!0,--this.claimed,r())};if(await n,e?.aborted)throw a(),as(e,t);return a}async run(e,t){let n=await this.acquire(e);try{return await t()}finally{n()}}get drained(){return this.tail}};function as(e,t){let n=e.reason;return Et(n)&&n.name===`AbortError`?n:Dt(t?`Run aborted while queued behind another run on this instance`:`Run aborted before it started`,n)}function os(e){return{maxConcurrentAgents:e.maxConcurrentAgents||100,defaultSystemMessage:e.defaultSystemMessage??``,strictValidation:e.strictValidation??!0,idFactory:e.idFactory??cs,...e.defaultModel!==void 0&&{defaultModel:e.defaultModel},...e.defaultProvider!==void 0&&{defaultProvider:e.defaultProvider}}}function ss(e,n){if(!e.aiProviders||e.aiProviders.length===0)throw new t(`At least one AI provider must be specified in aiProviders array`);let r=e.defaultModel,i=r?.model??n.defaultModel;if(!i)throw new t(`No model specified: set config.defaultModel.model or the AgentFactory defaultModel option`);let a=r?.provider??e.aiProviders[0]?.name??n.defaultProvider;if(!a)throw new t(`No provider specified: set config.defaultModel.provider, an aiProviders entry, or the AgentFactory defaultProvider option`);return{id:e.id||cs(),name:e.name||`Unnamed Agent`,aiProviders:e.aiProviders,defaultModel:{provider:a,model:i,temperature:r?.temperature??.7,...r?.maxTokens!==void 0&&{maxTokens:r.maxTokens},...r?.topP!==void 0&&{topP:r.topP}},systemMessage:e.systemMessage??n.defaultSystemMessage,tools:e.tools||[],plugins:e.plugins||[],metadata:e.metadata||{},...e.logging&&{logging:e.logging},...e.conversationId&&{conversationId:e.conversationId},...e}}function cs(){return`agent_${Date.now()}_${Math.random().toString(36).substring(2,8)}`}function ls(e,t){return e.totalCreated++,e.activeCount++,t?e.fromTemplates++:e.customConfigured++,e.templateUsageRatio=e.totalCreated>0?e.fromTemplates/e.totalCreated:0,e}var us=class{templates=new Map;logger;constructor(){this.logger=j(`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 ds(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 fs(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 ps(e,n.name,r)}t.push(n)}}function ps(e,t,n){let r=e instanceof Error?e:Error(String(e));return Object.assign(r,{failedStep:t,rollbackErrors:n})}var ms=class{agentTemplates;initialized=!1;logger;options;activeAgents;pendingAgents=new Set;creationStats;lifecycleEvents;constructor(e={},t={}){this.agentTemplates=new us,this.logger=j(`AgentFactory`),this.options=os(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,r,i=!1){let a,o=this.admit();try{a=ss(r,this.options);let s=a;if(this.options.strictValidation){let e=kt(a);if(!e.isValid)throw new n(`Invalid agent configuration: ${e.errors.join(`, `)}`)}let c;if(await fs([{name:`beforeCreate`,run:()=>this.lifecycleEvents.beforeCreate?.(s)},{name:`construct`,run:()=>{c=new e(s)}},{name:`initialize`,run:()=>c?ds(c)?.initialize?.():void 0,undo:()=>c?ds(c)?.cleanup?.():void 0},{name:`commit`,run:()=>{if(!c)throw new t(`Agent was not constructed`);this.activeAgents.set(o,c),ls(this.creationStats,i)},undo:()=>{this.activeAgents.delete(o),this.creationStats.activeCount--,this.creationStats.totalCreated--,i?this.creationStats.fromTemplates--:this.creationStats.customConfigured--}},{name:`afterCreate`,run:()=>c?this.lifecycleEvents.afterCreate?.(c,s):void 0}]),this.pendingAgents.delete(o),!c)throw new t(`Agent was not constructed`);return this.logger.info(`Agent created successfully`,{agentId:o,model:a.defaultModel.model,provider:a.defaultModel.provider}),c}catch(e){this.pendingAgents.delete(o);let t=e instanceof Error?e:Error(String(e));throw this.lifecycleEvents.onCreateError&&a&&await this.lifecycleEvents.onCreateError(t,a),this.logger.error(`Failed to create agent`,{error:t.message,model:r.defaultModel?.model,provider:r.defaultModel?.provider,hasTools:!!r.tools?.length}),t}}admit(){if(this.activeAgents.size+this.pendingAgents.size>=this.options.maxConcurrentAgents)throw new t(`Maximum concurrent agents limit reached: ${this.options.maxConcurrentAgents}`);let e=this.options.idFactory(),n=0;for(;this.activeAgents.has(e)||this.pendingAgents.has(e);){if(n+=1,n>16)throw new t(`Agent id factory keeps returning ids that are already in use`);e=this.options.idFactory()}return this.pendingAgents.add(e),e}async createFromTemplate(e,n,r={}){let i=this.agentTemplates.getTemplate(n);if(!i)throw new t(`Template not found: ${n}`);let a=this.applyTemplate(i,r);a.warnings.length>0&&this.logger.warn(`Template application warnings`,{templateId:n,warnings:a.warnings});let o=await this.createAgent(e,a.config,!0);return this.logger.info(`Agent created from template`,{templateId:n,modified:a.modified,warnings:a.warnings.length}),o}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 ds(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 kt(e)}};function hs(e,n,r){if(!e.name||e.name.trim()===``)throw new t(`Module name is required`);if(!e.version||e.version.trim()===``)throw new t(`Module version is required`);let i=e.getModuleType(),a=n.validateTypeDescriptor(i);if(!a.valid)throw new t(`Invalid module type: ${a.errors.join(`, `)}`,{moduleName:e.name,errors:a.errors});a.warnings.length>0&&r.warn(`Module type validation warnings`,{moduleName:e.name,warnings:a.warnings})}async function gs(e,n,r,i){let a=e.getModuleType();if(!a.dependencies||a.dependencies.length===0)return;for(let r of a.dependencies)if(!n.hasType(r))throw new t(`Module '${e.name}' depends on unregistered type '${r}'`,{moduleName:e.name,dependencyType:r});let o=new Set;for(let e of r.values())o.add(e.getModuleType().type);let s=[];for(let e of a.dependencies)o.has(e)||s.push(e);s.length>0&&i.warn(`Module has unmet dependencies`,{moduleName:e.name,missingDependencies:s})}function _s(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 vs(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 ys(){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 bs(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 xs(e,t,n){let r=new Set,i=new Set,a=[],o=[],s=[];for(let r of e){let e=t(r);if(!e){s.push(r);continue}if(e.dependencies)for(let t of e.dependencies)!n(t)&&!s.includes(t)&&s.push(t)}let c=(s,l=[])=>{if(i.has(s)){let e=l.indexOf(s);o.push(l.slice(e).concat([s]));return}if(r.has(s))return;let u=t(s);if(!u)return;i.add(s);let d=[...l,s];if(u.dependencies)for(let t of u.dependencies)(e.includes(t)||n(t))&&c(t,d);i.delete(s),r.add(s),a.push(s)};for(let t of e)r.has(t)||c(t);return{resolved:s.length===0&&o.length===0,order:a,circularDependencies:o,missingDependencies:s}}function Ss(e,t){let n=[],r=[],i=new Map;for(let n of e){let e=t(n);e&&(i.has(e.layer)||i.set(e.layer,[]),i.get(e.layer).push(n))}let a=new Map;for(let n of e){let e=t(n);if(e?.capabilities)for(let t of e.capabilities)a.has(t)||a.set(t,[]),a.get(t).push(n)}for(let[e,t]of Array.from(a.entries()))if(t.length>1)for(let r=0;r<t.length;r++)for(let i=r+1;i<t.length;i++){let a=t[r],o=t[i];a&&o&&n.push({module1:a,module2:o,reason:`Both modules provide capability '${e}'`})}return n.length>0&&(r.push(`Consider using only one module per capability`),r.push(`Check if modules can be configured to avoid conflicts`)),!i.has(`infrastructure`)&&e.length>1&&r.push(`Consider adding infrastructure modules for better foundation`),{compatible:n.length===0,conflicts:n,suggestions:r}}function Cs(e){let t={core:0,storage:0,processing:0,integration:0,interface:0,capability:0},n={infrastructure:0,core:0,application:0,domain:0,presentation:0},r=0,i=0;for(let a of e.values())t[a.category]++,n[a.layer]++,a.dependencies&&a.dependencies.length>0&&r++,a.capabilities&&a.capabilities.length>0&&i++;return{totalTypes:e.size,typesByCategory:t,typesByLayer:n,typesWithDependencies:r,typesWithCapabilities:i}}var ws=class{registeredTypes=new Map;logger;constructor(){this.logger=j(`ModuleDescriptorRegistry`),this.registerBuiltinTypes()}registerType(e){let n=this.validateTypeDescriptor(e);if(!n.valid)throw new t(`Invalid module type descriptor: ${n.errors.join(`, `)}`,{type:e.type,errors:n.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 n=this.findDependentTypes(e);if(n.length>0)throw new t(`Cannot unregister module type '${e}' - it is required by: ${n.join(`, `)}`,{type:e,dependentTypes:n});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 bs(e,e=>this.getType(e))}resolveDependencies(e){return xs(e,e=>this.getType(e),e=>this.hasType(e))}checkCompatibility(e){return Ss(e,e=>this.getType(e))}findDependentTypes(e){let t=[];for(let[n,r]of this.registeredTypes)r.dependencies?.includes(e)&&t.push(n);return t}registerBuiltinTypes(){for(let e of ys())this.registerType(e);this.logger.info(`Built-in module types registered`,{totalTypes:this.registeredTypes.size})}clearAllTypes(){this.registeredTypes.clear(),this.logger.info(`All module types cleared`)}getStats(){return Cs(this.registeredTypes)}};const Ts={REGISTERED:`module.registered`,UNREGISTERED:`module.unregistered`};var Es=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 ws,this.logger=j(`ModuleRegistry`)}async registerModule(e,n={}){if(this.isDisposing)throw new t(`Cannot register modules during disposal`);if(hs(e,this.typeRegistry,this.logger),this.modules.has(e.name))throw new t(`Module with name '${e.name}' is already registered`,{moduleName:e.name});n.validateDependencies!==!1&&await gs(e,this.typeRegistry,this.modules,this.logger),this.modules.set(e.name,e),this.moduleOptions.set(e.name,n.initOptions||{}),this.registrationOrder.push(e.name);let r=e.getModuleType();this.moduleStatuses.set(e.name,{name:e.name,type:r.type,enabled:e.isEnabled(),initialized:!1,hasEventEmitter:!!this.eventEmitter,registrationTime:new Date,dependencies:r.dependencies||[],dependents:[]}),this.moduleStats.set(e.name,{totalExecutions:0,successfulExecutions:0,failedExecutions:0,averageExecutionTime:0,totalExecutionTime:0}),n.autoInitialize&&await this.initializeModule(e.name,n.initTimeout),this.eventEmitter&&await this.eventEmitter.emit(Ts.REGISTERED,{data:{moduleName:e.name,moduleType:r.type},timestamp:new Date})}async unregisterModule(e){let n=this.modules.get(e);if(!n)return!1;let r=_s(e,this.modules);if(r.length>0)throw new t(`Cannot unregister module '${e}' - it is required by: ${r.join(`, `)}`,{moduleName:e,dependents:r});n.isInitialized()&&n.dispose&&await n.dispose(),this.modules.delete(e),this.moduleOptions.delete(e),this.moduleStatuses.delete(e),this.moduleStats.delete(e);let i=this.registrationOrder.indexOf(e);i!==-1&&this.registrationOrder.splice(i,1);let a=this.initializationOrder.indexOf(e);return a!==-1&&this.initializationOrder.splice(a,1),this.eventEmitter&&await this.eventEmitter.emit(Ts.UNREGISTERED,{data:{moduleName:e},timestamp:new Date}),!0}async initializeModule(e,n){let r=this.modules.get(e);if(!r)throw new t(`Module '${e}' not found`);if(r.isInitialized())return;let i=this.moduleOptions.get(e),a=r.initialize(i,this.eventEmitter);if(n&&n>0){let t,r=new Promise((r,i)=>{t=setTimeout(()=>{i(Error(`Module '${e}' initialization timed out after ${n}ms`))},n)});await Promise.race([a.then(e=>(clearTimeout(t),e)),r])}else await a;let o=this.moduleStatuses.get(e);o&&(o.initialized=!0,o.initializationTime=new Date),this.initializationOrder.includes(e)||this.initializationOrder.push(e)}async initializeAllModules(e){let n=Array.from(this.modules.keys());if(n.length===0)return;let r=n.map(e=>this.modules.get(e).getModuleType().type),i=this.typeRegistry.resolveDependencies(r);if(!i.resolved){let e=[];throw i.missingDependencies.length>0&&e.push(`Missing dependencies: ${i.missingDependencies.join(`, `)}`),i.circularDependencies.length>0&&e.push(`Circular dependencies: ${i.circularDependencies.map(e=>e.join(` -> `)).join(`; `)}`),new t(`Cannot initialize modules: ${e.join(`; `)}`,{missingDependencies:i.missingDependencies,circularDependencies:i.circularDependencies.map(e=>e.join(` -> `))})}for(let t of i.order){let r=n.find(e=>this.modules.get(e).getModuleType().type===t);r&&await this.initializeModule(r,e)}}async executeModule(e,n){let r=this.modules.get(e);if(!r)throw new t(`Module '${e}' not found`);if(!r.isInitialized())throw new t(`Module '${e}' is not initialized`);if(!r.isEnabled())throw new t(`Module '${e}' is disabled`);let i=this.moduleStats.get(e),a=Date.now();try{if(!r.execute)throw new t(`Module '${e}' does not support execute()`);let o=await r.execute(n),s=Date.now()-a;i.totalExecutions++,i.successfulExecutions++,i.totalExecutionTime+=s,i.averageExecutionTime=i.totalExecutionTime/i.totalExecutions,i.lastExecutionTime=new Date;let c=this.moduleStatuses.get(e);return c&&(c.lastActivity=new Date),o}catch(e){let t=Date.now()-a;throw i.totalExecutions++,i.failedExecutions++,i.totalExecutionTime+=t,i.averageExecutionTime=i.totalExecutionTime/i.totalExecutions,i.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 vs(this.modules,this.moduleStats)}},Ds=class extends Pr{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=ui(e);let t=e.logging?.enabled===!1?`silent`:e.logging?.level;this.logger=j(`ConversationAgent`,t?{level:t}:{}),this.startTime=Date.now(),Ir(e),this.config={...e,aiProviders:[...e.aiProviders],...e.providerOwnership?{providerOwnership:{...e.providerOwnership}}:{}},this.aiProviders=$o(e),this.tools=di(()=>this.config),this.agentFactory=new ms,this.conversationHistory=new Wn,this.eventEmitter=_i(),this.moduleRegistry=new Es(this.eventEmitter),this.eventService=e.eventService||mr,this.agentEventService=yr(this.eventService,{ownerType:`agent`,ownerId:this.conversationId,ownerPath:vi(this.conversationId,this.config.executionContext)});let n=mi({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,hi(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=[...vi(this.conversationId,this.config.executionContext),{type:`tool`,id:n.executionId??e}];return this.executionService.invokeRuntimeTool(e,t,{...n,baseEventService:this.eventService,eventService:yr(this.eventService,{ownerPath:r,ownerType:`tool`,ownerId:n.executionId??e}),ownerPath:r,ownerType:`tool`,ownerId:n.executionId})}async resume(e){let t={...e,toolResponses:structuredClone(e.toolResponses)};return this.assertNotDestroyed(),this.runQueue.run(t.signal,async()=>{await this.ensureFullyInitialized();let e=await this.executionService.resume(this.conversationId,t,this.config);if(!e.success)throw e.error??Error(`Execution continuation failed`);return e.response})}async resumeToolCalls(e){let t={...e,toolResponses:structuredClone(e.toolResponses)};return this.assertNotDestroyed(),this.runQueue.run(t.signal,async()=>(await this.ensureFullyInitialized(),this.executionService.resumeToolCalls(this.conversationId,t)))}async run(e,t={}){return this.assertNotDestroyed(),this.runQueue.run(t.signal,async()=>{await this.ensureFullyInitialized();try{if(t.output){let n=yn(t.output);return await wi(this.executionDeps(),e,t,n)}return await bi(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=yn(t.output);return yield*Ti(this.executionDeps(),e,t,n)}return yield*xi(this.executionDeps(),e,t)}finally{this.resetEphemeralHistory(),n()}}resetEphemeralHistory(){this.config.retainHistory===!1&&this.clearHistory()}runQueue=new is;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 Di(this.conversationHistory,this.conversationId)}getFullHistory(){return Oi(this.conversationHistory,this.conversationId)}addHistoryEntry(e){ki(this.conversationHistory,this.conversationId,e)}clearHistory(){Ai(this.conversationHistory,this.conversationId)}injectMessage(e,t,n){ji(this.conversationHistory,this.conversationId,e,t,n)}injectRawMessage(e){Mi(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,aiProviders:[...this.config.aiProviders],...this.config.providerOwnership?{providerOwnership:{...this.config.providerOwnership}}:{}}}swapDefaultProvider(e,t,n={}){this.aiProviders.addProvider(e.name,e,n),this.config={...this.config,aiProviders:Object.values(this.aiProviders.getProviders()),providerOwnership:{...this.config.providerOwnership,[e.name]:n.ownership??`owned`}},this.configManager.setModel({provider:e.name,model:t})}getStats(){return ns({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,rs({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 ts({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){gi(this.agentEventService,this.conversationId,this.config.executionContext,e,t)}};const Os=25e3,ks=5e5,As=/^tool-result:[A-Za-z0-9_-]{22,64}$/u,js=Symbol.for(`@robota-sdk/tool-result-admitted`);var Ms=class extends Error{code;constructor(e){super(`Tool result admission failed (${e})`),this.code=e,this.name=`ToolResultAdmissionError`}};function Ns(e){return Object.getOwnPropertyDescriptor(e,js)?.value===!0}function Ps(e){return Object.defineProperty({...e},js,{value:!0})}function Fs(e){if(e.parts?.length&&e.parts.every(e=>e.type===`text`)){let t=e.parts.map(e=>e.type===`text`?e.text:``).join(`
|
|
10
10
|
`);if(e.success&&e.data===t||!e.success&&e.data===void 0&&e.error===t)return t}if(e.parts?.length)return JSON.stringify({success:e.success,data:e.data,error:e.error,parts:e.parts});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 Is(e){return Number.isSafeInteger(e)&&e>0}function Ls(e,t){let n=e.warningChars??1e4,r=e.hardChars??25e3,i=e.repositoryMaxChars??5e5;if(!Is(n)||!Is(r)||!Is(i)||n>=r||r>i||i>5e5)throw new Ms(`invalid-policy`);if(t===void 0)return{warningChars:n,hardChars:r};if(!Is(t))throw new Ms(`invalid-override`);return{warningChars:n,hardChars:Math.max(r,Math.min(t,i))}}async function Rs(e,t,n={},r){let{warningChars:i,hardChars:a}=Ls(n,r),o=Fs(t),s=o.length;if(s>i&&n.onWarning?.({toolName:e,resultChars:s,warningChars:i}),s>a){if(!n.spillStore)throw new Ms(`spill-unavailable`);let e;try{e=(await n.spillStore.write(o)).reference}catch{throw new Ms(`spill-write-failed`)}if(!As.test(e)||e.length>a)throw new Ms(`invalid-reference`);let r=t.view?{view:t.view}:{};return Ps(t.success?{success:!0,data:e,...r}:{success:!1,error:`Tool failure details: ${e}`,...r})}return Ps(t)}const zs={safe:`plan`,moderate:`default`,full:`acceptEdits`},Bs=`inherit-allowlist`;function Vs(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===`
|
|
11
11
|
`||(r===`<`||r===`>`)&&i===`(`)return!0;if(r===`&`){let t=e[n-1];if(t!==`>`&&t!==`<`&&i!==`>`)return!0}}return!1}function Hs(e){let t={segments:[],current:``,quote:void 0,substitutionDepth:0};for(let n=0;n<e.length;n+=1){let r=Ws(t,e,n);if(r!==void 0){n=r;continue}let i=Gs(t,e,n);if(i!==void 0){n=i;continue}if(Ks(t,e[n]))continue;let a=qs(t,e,n);if(a!==void 0){n=a;continue}t.current+=e[n]}return Us(t),t.segments}function Us(e){let t=e.current.trim();t!==``&&e.segments.push(t),e.current=``}function Ws(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 Gs(e,t,n){let r=t[n];if(r==="`")return Us(e),n;if(r===`$`&&t[n+1]===`(`)return Us(e),e.substitutionDepth+=1,n+1}function Ks(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 qs(e,t,n){let r=t[n];if((r===`<`||r===`>`)&&t[n+1]===`(`)return Us(e),e.substitutionDepth+=1,n+1;if(r===`)`&&e.substitutionDepth>0)return Us(e),--e.substitutionDepth,n;if(r===`;`||r===`|`||r===`
|
|
12
|
-
`||r===`&`&&Js(t,n))return Us(e),n}function Js(e,t){let n=e[t-1];return n!==`>`&&n!==`<`&&e[t+1]!==`>`}const Ys=/[.+^${}()|[\]\\]/g;function Xs(e){let t=e.replace(Ys,`\\$&`).replace(/\*\*/g,`.+`).replace(/\*/g,`.*`);return RegExp(`^${t}$`)}function Zs(e,t,n){let r=Xs(e);return n===`deny`?r.test(t)||Hs(t).some(e=>r.test(e))?`match`:`no-match`:r.test(t)?e.includes(`*`)&&Vs(t)?`no-match`:`match`:`no-match`}function Qs(e){let t=e.replace(/\*\*(?:\/\*\*)+/g,`**`).split(/(\/\*\*\/|\/\*\*$|^\*\*\/|\*\*)/).map(e=>e===`/**/`?`(?:/.*)?/`:e===`/**`?`(?:/.*)?`:e===`**/`?`(?:.*/)?`:e===`**`?`.*`:e.replace(Ys,`\\$&`).replace(/\*/g,`[^/]*`).replace(/\uE000/g,`\\*`)).join(``);return RegExp(`^${t}$`)}function $s(e){return e.startsWith(`/`)||/^[A-Za-z]:(?=\/|$)/.test(e)}function ec(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 tc(e,t){let n=ec(e),r=ec(t);return $s(n)&&!$s(r)?`unevaluable`:Qs(n).test(r)?`match`:`no-match`}const nc=/^(\*|[a-z][a-z0-9+.-]*):\/\/(\[[0-9a-fA-F:.]+\]|[^/\\:?#@[\]]+)(?::(\d+|\*))?(\/[^?#]*)?$/i,rc=new Set([`http`,`https`,`ws`,`wss`,`ftp`]),ic={http:`80`,https:`443`,ws:`80`,wss:`443`,ftp:`21`};function ac(e){return e.replace(/\.$/,``).toLowerCase()}function oc(e){try{let t=new URL(`http://${e}/`).hostname;return t===``||t.includes(`.`)?null:t}catch{return null}}function sc(e,t=!1){let n=ac(e).replace(/\*\*(?:\.\*\*)+/g,`**`).split(`.`),r=[],i=`[^.]+(?:\\.[^.]+)*`;for(let[e,a]of n.entries()){let o=e===0,s=e===n.length-1;if(a===`**`){o&&s?r.push(i):s?r.push(`(?:\\.${i})?`):r.push(`${o?``:`\\.`}(?:${i}\\.)?`);continue}let c=!o&&n[e-1]===`**`,l=o||c?``:`\\.`;if(a===`*`)r.push(`${l}${t&&!o?`[^.]*`:i}`);else if(a.includes(`**`))return null;else if(a.includes(`*`))r.push(`${l}${a.replace(Ys,`\\$&`).replace(/\*/g,`[^.]*`)}`);else{let e=oc(a);if(e===null)return null;r.push(`${l}${e.replace(Ys,`\\$&`)}`)}}return RegExp(`^${r.join(``)}$`)}function cc(e){try{let t=e.split(`/`).map(e=>decodeURIComponent(e));return t.some(e=>e.includes(`/`))?null:t.join(`/`)}catch{return null}}function lc(e){let t;try{t=new URL(e)}catch{return null}let n=t.protocol.slice(0,-1).toLowerCase();return!rc.has(n)||t.hostname===``||t.username!==``||t.password!==``?null:t}function uc(e,t,n=!1){if(e.includes(`*`)){let r=sc(e,n);return r===null?`unevaluable`:r.test(t)?`match`:`no-match`}let r;try{r=new URL(`http://${e}/`).hostname}catch{return`unevaluable`}return ac(r)===t?`match`:`no-match`}function dc(e,t,n){return e===void 0?t.port===``:e===`*`||e===(t.port===``?ic[n]:t.port)}function fc(e,t){let n=cc(t),r=cc(e.replace(/%2a/gi,``));return n===null||r===null?`unevaluable`:Qs(r).test(n)?`match`:`no-match`}function pc(e,t){let n=nc.exec(e);if(n===null)return`unevaluable`;let[,r,i,a,o]=n,s=lc(t);if(s===null)return`unevaluable`;let c=s.protocol.slice(0,-1).toLowerCase();if(r!==`*`&&r.toLowerCase()!==c)return`no-match`;let l=uc(i,ac(s.hostname));return l===`match`?dc(a,s,c)?o===void 0?`match`:fc(o,s.pathname):`no-match`:l}function mc(e,t){if(!e.startsWith(`domain:`))return pc(e,t);let n=/^domain:([^/\\:?#@[\]\s]+)$/.exec(e);if(n===null)return`unevaluable`;let r=ac(n[1]);if(r.includes(`**`)||r.split(`.`).some(e=>e===``))return`unevaluable`;let i=lc(t);return i===null||i.protocol!==`http:`&&i.protocol!==`https:`?`unevaluable`:uc(r,ac(i.hostname),!0)}const hc={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`}},gc={plan:`deny`,default:`approve`,acceptEdits:`approve`,bypassPermissions:`auto`,auto:`approve`},_c=[`.git`,`.claude`,`.agents`],vc=[`.mcp.json`,`.gitconfig`,`.npmrc`,`.bashrc`,`.bash_profile`,`.bash_login`,`.zshrc`,`.zshenv`,`.zprofile`,`.profile`];function yc(e){return e.replace(/\\/g,`/`).split(`/`).filter(e=>e!==``&&e!==`.`)}function bc(e){let t=[];for(let n of yc(e))n===`..`&&t.length>0&&t[t.length-1]!==`..`?t.pop():t.push(n);return t}function xc(e,t={}){let n=t.pathProtection,r=wc.exec(e),i=r!==null&&t.homeDirectory!==void 0?`${t.homeDirectory}/${r[1]??``}`:e,a=i.startsWith(`/`)?Sc(i):t.cwd===void 0?void 0:Sc(`${t.cwd}/${i}`);if(a!==void 0&&n?.protectedPaths.some(e=>{let t=Sc(e);return a===t||a.startsWith(`${t}/`)}))return!0;let o=bc(i),s=o[o.length-1];if(s!==void 0&&vc.includes(s))return!0;let c=[..._c,...n?.protectedDirectoryNames??[]],l=[`.claude/worktrees`,...n?.writableWorktreeContainers??[]].map(bc);for(let e=0;e<o.length;e+=1){if(!c.includes(o[e]))continue;let t=l.find(t=>t.length>0&&t.every((t,n)=>o[e+n]===t)&&o[e+t.length]!==void 0);if(t!==void 0){e+=t.length;continue}return!0}return!1}function Sc(e){let t=[];for(let n of yc(e))n===`..`?t.pop():t.push(n);return`/${t.join(`/`)}`}function Cc(e){return e.replace(/^(['"])(.*)\1$/,`$2`)}const wc=/^(?:~|\$HOME|\$\{HOME\})(?=\/|$)(.*)$/;function Tc(e,t){let n=Cc(e),r=wc.exec(n),i;if(r!==null){let e=r[1]??``;if(t.homeDirectory===void 0)return e.replace(/\/+/g,``)===``;i=Sc(`${t.homeDirectory}/${e}`)}else if(n===``||n.startsWith(`$`))return!1;else if(n.startsWith(`/`))i=Sc(n);else{if(t.cwd===void 0)return!1;i=Sc(`${t.cwd}/${n}`)}if(yc(i).length<=1||t.homeDirectory!==void 0&&i===Sc(t.homeDirectory))return!0;if(t.cwd!==void 0){let e=Sc(t.cwd);if(e===i||e.startsWith(`${i}/`))return!0}return!1}const Ec=new Set([`rm`,`rmdir`]),Dc=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 Oc(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=Dc.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 kc(e,t){return Hs(e).some(e=>{let n=e.split(/\s+/).filter(e=>e!==``),r=Oc(n),i=n[r];if(i===void 0)return!1;let a=i.slice(i.lastIndexOf(`/`)+1);if(!Ec.has(a))return!1;let o=!1;return n.slice(r+1).some(e=>!o&&e===`--`?(o=!0,!1):!o&&e.startsWith(`-`)?!1:Tc(e,t))})}const Ac=new Set([`ls`,`cat`,`echo`,`pwd`,`head`,`tail`,`grep`,`wc`,`which`,`stat`,`du`,`cd`]),jc=new Set([`-exec`,`-execdir`,`-ok`,`-okdir`,`-delete`,`-fprint`,`-fprint0`,`-fprintf`,`-fls`]),Mc={ls:`aAlhtrSR1dFGinpsucCgmoQvx`,cat:`nbsvetAE`,head:`nqvc`,tail:`nqvcfF`,grep:`rinlLvcwxEFGPHhoqsABCmz`,wc:`lwcmL`,stat:`cftx`,du:`hsacdkmx`,which:`a`,pwd:`LP`,cd:`LP`},Nc=/^--?[A-Za-z0-9-]*(file|from|contents)(=|$)/,Pc=[`--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 Fc(e){if(!e.startsWith(`--`)||e.length<=2)return!1;let t=e.split(`=`,1)[0];return Pc.some(e=>e.startsWith(t))}function Ic(e,t){if(Jc(t).some(e=>Nc.test(e.text)||Fc(e.text)))return!0;if(e===`find`)return Jc(t).some(e=>e.text===`-L`||e.text===`-follow`);let n=Mc[e];return n!==void 0&&Jc(t).some(({text:e})=>e.startsWith(`--`)||!/^-[A-Za-z]/.test(e)?!1:[...e.slice(1)].some(e=>!/\d/.test(e)&&!n.includes(e)))}const Lc=new Set([`status`,`log`,`diff`,`show`,`rev-parse`,`ls-files`,`describe`,`branch`,`remote`]),Rc=new Set([`-l`,`--list`,`--show-current`,`--merged`,`--no-merged`,`--contains`,`--no-contains`,`--points-at`]),zc=new Set([`-a`,`--all`,`-r`,`--remotes`,`-v`,`-vv`,`--verbose`,`--color`,`--no-color`]),Bc=new Set([`/dev/null`]),Vc=/[A-Za-z0-9_./:=@+,*?[\]~-]/,Hc=new Set([`$`,"`",`\\`,`!`]),Uc=new Set([`*`,`?`,`[`]);function Wc(e){return/(^|[=,:])[/~]/.test(e)||/^-[A-Za-z]+[/~]/.test(e)||/(^|[/=,:]|^-[A-Za-z]+)\.\.(\/|$)/.test(e)||/(^|[=,])[A-Za-z][A-Za-z0-9]*:/.test(e)||Gc(e)}function Gc(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 Kc(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 qc(e){let t=[],n=``,r=!1,i=!1,a,o,s=!1,c=()=>{i&&=(o===`output`?(!Bc.has(n)||r)&&(s=!0):o===`duplicate`?/^(\d+|-)$/.test(n)||(s=!0):o===`input`?(r||Wc(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:Hc.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(!Vc.test(l)){s=!0;break}Uc.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 Jc(e){let t=e.findIndex(e=>e.text===`--`);return(t<0?e:e.slice(0,t)).filter(e=>e.text.startsWith(`-`))}function Yc(e){return e.every(e=>!e.expands&&!jc.has(e.text))}function Xc(e){let t=e.filter(e=>e.text.startsWith(`-`)),n=t.some(e=>Rc.has(e.text));return t.every(e=>Rc.has(e.text)||zc.has(e.text))&&(n||t.length===e.length)}function Zc(e){let[t,...n]=e[0]?.text===`--no-pager`?e.slice(1):e;return t===void 0||t.expands||!Lc.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`?Xc(n):t.text!==`remote`||n.every(e=>e.text===`-v`||e.text===`--verbose`)}function Qc(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=>Wc(e.text))||Ic(t.text,n)?!1:t.text===`cd`?n.length===1&&n[0].text!==`-`&&!n[0].expands:Ac.has(t.text)?!0:t.text===`find`?Yc(n):t.text===`git`&&Zc(n)}const $c=new Set([`echo`,`which`,`git`]);function el(e,t){let n;for(let[r,...i]of e)if(!$c.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 tl(e,t={}){if(t.otherDirectory===!0||e.length>1e4||Kc(e)||/[^\t\n\x20-\x7e]/.test(e))return!1;let n=Hs(e);if(n.length===0)return!1;let r=n.map(qc);if(r.some(e=>e.refused||!Qc(e.words)))return!1;let i=r.map(e=>e.words[0].text);return i.includes(`git`)&&i.includes(`cd`)?!1:el(r.map(e=>e.words),t.resolveInWorkspace)}function nl(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 rl(e,t){Q.set(e,{...Q.get(e),...t})}function il(e){return Q.get(e)??{}}function al(e,t){let n=[t,...Q.get(t)?.aliases??[]];if(!e.includes(`*`))return n.includes(e);let r=Xs(e);return n.some(e=>r.test(e))}function ol(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 sl(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`:Xs(e.value).test(String(n))?`match`:`no-match`}function cl(e,t){return t.some(t=>{let n=nl(t);return(n.argPattern===void 0||n.argPattern===`*`||n.argPattern===`**`)&&al(n.toolName,e)})}function ll(e){return Q.get(e)?.argument?.key}function ul(e,t){let n=ll(e);if(n===void 0)return;let r=t[n];return typeof r==`string`?r:void 0}function dl(e,t,n,r=`allow`){return n.some(n=>pl(e,t,n,r)===`match`)}function fl(e,t,n){return n.some(n=>pl(e,t,n,`deny`)===`unevaluable`)}function pl(e,t,n,r){let i=nl(n);if(!al(i.toolName,e))return`no-match`;if(i.argPattern===void 0||i.argPattern===`*`||i.argPattern===`**`)return`match`;let a=ol(e,i.argPattern);if(a===`primary`)return`unevaluable`;if(a!==void 0)return r===`deny`?sl(a,t):`no-match`;let o=Q.get(e)?.argument;if(o===void 0)return`unevaluable`;let s=ul(e,t);if(s===void 0)return`no-match`;switch(o.kind){case`url`:return e===`WebFetch`?mc(i.argPattern,s):pc(i.argPattern,s);case`path`:return tc(i.argPattern,s);case`command`:return Zs(i.argPattern,s,r);case`text`:return Xs(i.argPattern).test(s)?`match`:`no-match`;default:{let e=o.kind;throw Error(`unknown argument kind: ${String(e)}`)}}}function ml(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`?kc(a,n):i.kind===`path`&&r?.riskClass===`modify`&&xc(a,n):!1}function hl(e,t,n,r){return dl(e,t,n,`deny`)||fl(e,t,n)||ml(e,t,r)}function gl(e,t,n={},r={}){return fl(e,t,n.deny??[])||hl(e,t,n.ask??[],r)}const _l=[`workingDirectory`,`cwd`];function vl(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`&&tl(i,{otherDirectory:_l.some(e=>t[e]!==void 0),...n.resolveInWorkspace===void 0?{}:{resolveInWorkspace:n.resolveInWorkspace}})?`inspect`:r.riskClass}function yl(e,t,n,r={},i={}){let{allow:a=[],deny:o=[],ask:s=[]}=r,c=vl(e,t,i),l=n===`plan`&&c!==`inspect`?`deny`:`approve`;return dl(e,t,o,`deny`)||i.ceiling!==void 0&&!dl(e,t,i.ceiling)||Q.get(e)?.repliesToPeer===!0&&i.peerTurn!==!0||Q.get(e)?.notInPeerTurn===!0&&i.peerTurn===!0?`deny`:fl(e,t,o)?n===`plan`?`deny`:`approve`:hl(e,t,s,i)||i.askAll===!0?l:n===`bypassPermissions`||dl(e,t,a)||i.sandboxAutoApproved===!0&&c===`execute`&&(n==="default"||n===`acceptEdits`||n===`auto`)?`auto`:c===void 0?gc[n]:hc[n][c]}function bl(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 xl=/^[A-Za-z_]\w*:(?!\/\/)/;function Sl(e){return e.slice(0,e.indexOf(`*`)).includes(`__`)}function Cl(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}=nl(n);if(r===``)return`names no tool`;if(t===`allow`&&r.includes(`*`)&&!Sl(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`&&xl.test(i)?`matches a named parameter, which only deny and ask rules may do`:void 0;let a=ol(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=il(r);if(!(o.parameters===void 0&&xl.test(i)&&ol(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`&&(r===`WebFetch`?mc:pc)(i,`https://probe.invalid/`)===`unevaluable`)return`does not fit the URL pattern grammar scheme://host[:port][/path]${r===`WebFetch`?` or domain:hostname`:``} that "${r}" is matched by`}}function wl(e,t=`deny`){let n=[];for(let r of e){let e=Cl(r,t);e!==void 0&&n.push({pattern:r,reason:e})}return n}function Tl(e){let t=[];for(let n of e){let{toolName:e,argPattern:r}=nl(n.trim());if(r===void 0||e.includes(`*`))continue;let i=il(e),a=ol(e,r);if(a===void 0&&i.parameters!==void 0&&i.argument?.kind!==`url`&&xl.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=il(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 El(e){return(e??[]).map(e=>`${e}(*)`)}function Dl(e,t){let n=El(t.allowedTools),r=wl(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,...El(t.deniedTools)])]}}const Ol=[`Bash`,`Shell`,`BackgroundProcess`],kl=[`Agent`],Al=[...Ol,...kl,`ExecuteCommand`,`Computer`],jl=`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(`.`),Ml=[`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(` `)),Nl=new Set([`run`,`run-script`,`exec`,`dlx`,`x`,`--`]);function Pl(e){return(e.split(/[\\/]/).pop()??e).replace(/(\.exe)?$/i,``).replace(/[\d.]+$/,``)}function Fl(e,t){if(e.length===0)return!0;let n=(e,n,r)=>t&&r?e.startsWith(n):e===n,r=Pl(e[0]);if(jl.some(t=>n(t,r,e.length===1)))return!0;for(let i of Ml){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(`-`)||Nl.has(o[0]));)o=o.slice(1);return o.length===0||Fl(o,t)}return!1}function Il(e){let t=e.trim();if(!t.includes(`*`))return!1;let n=t.slice(0,t.indexOf(`*`));return Fl(n.trim().split(/\s+/).filter(e=>e.length>0),n.length>0&&!/\s$/.test(n))}function Ll(e){let{toolName:t,argPattern:n}=nl(e),r=e=>e.some(e=>al(t,e));return r(kl)?!0:t.includes(`*`)?r(Al):Al.includes(t)||il(t).riskClass===`execute`?n===void 0||n.trim()===`*`||Ol.includes(t)&&Il(n):!1}function Rl(e){return e.filter(e=>!Ll(e))}const zl=1e6,Bl={"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}},Vl=[{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:/gemini-2/i,price:{inputPerMillion:.1,outputPerMillion:.4}},{pattern:/gemini-1/i,price:{inputPerMillion:1.25,outputPerMillion:5}}];function Hl(e){let t=Object.hasOwn(Bl,e)?Bl[e]:void 0;if(t)return t;for(let{pattern:t,price:n}of Vl)if(t.test(e))return n}function Ul(e,t,n){let r=Hl(e);if(r)return t/zl*r.inputPerMillion+n/zl*r.outputPerMillion}function Wl(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 Gl(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 Kl(){let[{CommandExecutor:e},{HttpExecutor:t}]=await Promise.all([import(`./command-executor-D_UBZHxh-D7UrdAlN.js`).then(e=>e.t).then(e=>e.n),import(`./http-executor-ADn4locH-uz5KV6N-.js`).then(e=>e.t).then(e=>e.n)]);return[new e,new t]}async function ql(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 Kl(),u=new Map;for(let e of l)u.set(e.type,e);let d=[],f=Gl(n),p=-1,m,h;for(let e of c){if(!Wl(e,f))continue;let r=e.env?{...n,env:{...n.env,...e.env}}:n;for(let n of e.hooks){let e=u.get(n.type);if(!e){a.add(n.type);continue}let c=n.type===`command`&&i!==void 0?await e.execute(n,r,i):await e.execute(n,r);if(c.outcome===`deny`)return{blocked:!0,reason:c.reason||`Blocked by hook`,stdout:d.join(`
|
|
12
|
+
`||r===`&`&&Js(t,n))return Us(e),n}function Js(e,t){let n=e[t-1];return n!==`>`&&n!==`<`&&e[t+1]!==`>`}const Ys=/[.+^${}()|[\]\\]/g;function Xs(e,t){let n,r=``;for(let i of e){if(i===n){n=void 0;continue}if(n===void 0&&(i===`'`||i===`"`)){n=i;continue}if(n!==void 0&&(i===` `||i===` `))return;if(n===void 0&&(i===` `||i===` `)){r.endsWith(` `)||(r+=` `);continue}if(/[^\x20-\x7e]|[$`\\!%~<>()[\]{}?#]/u.test(i)||!t&&i===`*`)return;r+=i}return n===void 0?r:void 0}function Zs(e){let t=e.replace(Ys,`\\$&`).replace(/\*\*/g,`.+`).replace(/\*/g,`.*`);return RegExp(`^${t}$`)}function Qs(e,t,n){let r=Zs(e);if(n===`deny`){if(r.test(t))return`match`;let n=Hs(t);if(n.some(e=>r.test(e)))return`match`;let i=Xs(e,!0);if(i===void 0)return`unevaluable`;let a=Zs(i);for(let e of n){let t=Xs(e,!1);if(t!==void 0&&a.test(t))return`match`}return`unevaluable`}return r.test(t)?e.includes(`*`)&&Vs(t)?`no-match`:`match`:`no-match`}function $s(e){let t=e.replace(/\*\*(?:\/\*\*)+/g,`**`).split(/(\/\*\*\/|\/\*\*$|^\*\*\/|\*\*)/).map(e=>e===`/**/`?`(?:/.*)?/`:e===`/**`?`(?:/.*)?`:e===`**/`?`(?:.*/)?`:e===`**`?`.*`:e.replace(Ys,`\\$&`).replace(/\*/g,`[^/]*`).replace(/\uE000/g,`\\*`)).join(``);return RegExp(`^${t}$`)}function ec(e){return e.startsWith(`/`)||/^[A-Za-z]:(?=\/|$)/.test(e)}function tc(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 nc(e,t){let n=tc(e),r=tc(t);return ec(n)&&!ec(r)?`unevaluable`:$s(n).test(r)?`match`:`no-match`}const rc=/^(\*|[a-z][a-z0-9+.-]*):\/\/(\[[0-9a-fA-F:.]+\]|[^/\\:?#@[\]]+)(?::(\d+|\*))?(\/[^?#]*)?$/i,ic=new Set([`http`,`https`,`ws`,`wss`,`ftp`]),ac={http:`80`,https:`443`,ws:`80`,wss:`443`,ftp:`21`};function oc(e){return e.replace(/\.$/,``).toLowerCase()}function sc(e){try{let t=new URL(`http://${e}/`).hostname;return t===``||t.includes(`.`)?null:t}catch{return null}}function cc(e,t=!1){let n=oc(e).replace(/\*\*(?:\.\*\*)+/g,`**`).split(`.`),r=[],i=`[^.]+(?:\\.[^.]+)*`;for(let[e,a]of n.entries()){let o=e===0,s=e===n.length-1;if(a===`**`){o&&s?r.push(i):s?r.push(`(?:\\.${i})?`):r.push(`${o?``:`\\.`}(?:${i}\\.)?`);continue}let c=!o&&n[e-1]===`**`,l=o||c?``:`\\.`;if(a===`*`)r.push(`${l}${t&&!o?`[^.]*`:i}`);else if(a.includes(`**`))return null;else if(a.includes(`*`))r.push(`${l}${a.replace(Ys,`\\$&`).replace(/\*/g,`[^.]*`)}`);else{let e=sc(a);if(e===null)return null;r.push(`${l}${e.replace(Ys,`\\$&`)}`)}}return RegExp(`^${r.join(``)}$`)}function lc(e){try{let t=e.split(`/`).map(e=>decodeURIComponent(e));return t.some(e=>e.includes(`/`))?null:t.join(`/`)}catch{return null}}function uc(e){let t;try{t=new URL(e)}catch{return null}let n=t.protocol.slice(0,-1).toLowerCase();return!ic.has(n)||t.hostname===``||t.username!==``||t.password!==``?null:t}function dc(e,t,n=!1){if(e.includes(`*`)){let r=cc(e,n);return r===null?`unevaluable`:r.test(t)?`match`:`no-match`}let r;try{r=new URL(`http://${e}/`).hostname}catch{return`unevaluable`}return oc(r)===t?`match`:`no-match`}function fc(e,t,n){return e===void 0?t.port===``:e===`*`||e===(t.port===``?ac[n]:t.port)}function pc(e,t){let n=lc(t),r=lc(e.replace(/%2a/gi,``));return n===null||r===null?`unevaluable`:$s(r).test(n)?`match`:`no-match`}function mc(e,t){let n=rc.exec(e);if(n===null)return`unevaluable`;let[,r,i,a,o]=n,s=uc(t);if(s===null)return`unevaluable`;let c=s.protocol.slice(0,-1).toLowerCase();if(r!==`*`&&r.toLowerCase()!==c)return`no-match`;let l=dc(i,oc(s.hostname));return l===`match`?fc(a,s,c)?o===void 0?`match`:pc(o,s.pathname):`no-match`:l}function hc(e,t){if(!e.startsWith(`domain:`))return mc(e,t);let n=/^domain:([^/\\:?#@[\]\s]+)$/.exec(e);if(n===null)return`unevaluable`;let r=oc(n[1]);if(r.includes(`**`)||r.split(`.`).some(e=>e===``))return`unevaluable`;let i=uc(t);return i===null||i.protocol!==`http:`&&i.protocol!==`https:`?`unevaluable`:dc(r,oc(i.hostname),!0)}const gc={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`}},_c={plan:`deny`,default:`approve`,acceptEdits:`approve`,bypassPermissions:`auto`,auto:`approve`},vc=[`.git`,`.claude`,`.agents`],yc=[`.mcp.json`,`.gitconfig`,`.npmrc`,`.bashrc`,`.bash_profile`,`.bash_login`,`.zshrc`,`.zshenv`,`.zprofile`,`.profile`];function bc(e){return e.replace(/\\/g,`/`).split(`/`).filter(e=>e!==``&&e!==`.`)}function xc(e){let t=[];for(let n of bc(e))n===`..`&&t.length>0&&t[t.length-1]!==`..`?t.pop():t.push(n);return t}function Sc(e,t={}){let n=t.pathProtection,r=Tc.exec(e),i=r!==null&&t.homeDirectory!==void 0?`${t.homeDirectory}/${r[1]??``}`:e,a=i.startsWith(`/`)?Cc(i):t.cwd===void 0?void 0:Cc(`${t.cwd}/${i}`);if(a!==void 0&&n?.protectedPaths.some(e=>{let t=Cc(e);return a===t||a.startsWith(`${t}/`)}))return!0;let o=xc(i),s=o[o.length-1];if(s!==void 0&&yc.includes(s))return!0;let c=[...vc,...n?.protectedDirectoryNames??[]],l=[`.claude/worktrees`,...n?.writableWorktreeContainers??[]].map(xc);for(let e=0;e<o.length;e+=1){if(!c.includes(o[e]))continue;let t=l.find(t=>t.length>0&&t.every((t,n)=>o[e+n]===t)&&o[e+t.length]!==void 0);if(t!==void 0){e+=t.length;continue}return!0}return!1}function Cc(e){let t=[];for(let n of bc(e))n===`..`?t.pop():t.push(n);return`/${t.join(`/`)}`}function wc(e){return e.replace(/^(['"])(.*)\1$/,`$2`)}const Tc=/^(?:~|\$HOME|\$\{HOME\})(?=\/|$)(.*)$/;function Ec(e,t){let n=wc(e),r=Tc.exec(n),i;if(r!==null){let e=r[1]??``;if(t.homeDirectory===void 0)return e.replace(/\/+/g,``)===``;i=Cc(`${t.homeDirectory}/${e}`)}else if(n===``||n.startsWith(`$`))return!1;else if(n.startsWith(`/`))i=Cc(n);else{if(t.cwd===void 0)return!1;i=Cc(`${t.cwd}/${n}`)}if(bc(i).length<=1||t.homeDirectory!==void 0&&i===Cc(t.homeDirectory))return!0;if(t.cwd!==void 0){let e=Cc(t.cwd);if(e===i||e.startsWith(`${i}/`))return!0}return!1}const Dc=new Set([`rm`,`rmdir`]),Oc=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 kc(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=Oc.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 Ac(e,t){return Hs(e).some(e=>{let n=e.split(/\s+/).filter(e=>e!==``),r=kc(n),i=n[r];if(i===void 0)return!1;let a=i.slice(i.lastIndexOf(`/`)+1);if(!Dc.has(a))return!1;let o=!1;return n.slice(r+1).some(e=>!o&&e===`--`?(o=!0,!1):!o&&e.startsWith(`-`)?!1:Ec(e,t))})}const jc=new Set([`ls`,`cat`,`echo`,`pwd`,`head`,`tail`,`grep`,`wc`,`which`,`stat`,`du`,`cd`]),Mc=new Set([`-exec`,`-execdir`,`-ok`,`-okdir`,`-delete`,`-fprint`,`-fprint0`,`-fprintf`,`-fls`]),Nc={ls:`aAlhtrSR1dFGinpsucCgmoQvx`,cat:`nbsvetAE`,head:`nqvc`,tail:`nqvcfF`,grep:`rinlLvcwxEFGPHhoqsABCmz`,wc:`lwcmL`,stat:`cftx`,du:`hsacdkmx`,which:`a`,pwd:`LP`,cd:`LP`},Pc=/^--?[A-Za-z0-9-]*(file|from|contents)(=|$)/,Fc=[`--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 Ic(e){if(!e.startsWith(`--`)||e.length<=2)return!1;let t=e.split(`=`,1)[0];return Fc.some(e=>e.startsWith(t))}function Lc(e,t){if(Yc(t).some(e=>Pc.test(e.text)||Ic(e.text)))return!0;if(e===`find`)return Yc(t).some(e=>e.text===`-L`||e.text===`-follow`);let n=Nc[e];return n!==void 0&&Yc(t).some(({text:e})=>e.startsWith(`--`)||!/^-[A-Za-z]/.test(e)?!1:[...e.slice(1)].some(e=>!/\d/.test(e)&&!n.includes(e)))}const Rc=new Set([`status`,`log`,`diff`,`show`,`rev-parse`,`ls-files`,`describe`,`branch`,`remote`]),zc=new Set([`-l`,`--list`,`--show-current`,`--merged`,`--no-merged`,`--contains`,`--no-contains`,`--points-at`]),Bc=new Set([`-a`,`--all`,`-r`,`--remotes`,`-v`,`-vv`,`--verbose`,`--color`,`--no-color`]),Vc=new Set([`/dev/null`]),Hc=/[A-Za-z0-9_./:=@+,*?[\]~-]/,Uc=new Set([`$`,"`",`\\`,`!`]),Wc=new Set([`*`,`?`,`[`]);function Gc(e){return/(^|[=,:])[/~]/.test(e)||/^-[A-Za-z]+[/~]/.test(e)||/(^|[/=,:]|^-[A-Za-z]+)\.\.(\/|$)/.test(e)||/(^|[=,])[A-Za-z][A-Za-z0-9]*:/.test(e)||Kc(e)}function Kc(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 qc(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 Jc(e){let t=[],n=``,r=!1,i=!1,a,o,s=!1,c=()=>{i&&=(o===`output`?(!Vc.has(n)||r)&&(s=!0):o===`duplicate`?/^(\d+|-)$/.test(n)||(s=!0):o===`input`?(r||Gc(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:Uc.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(!Hc.test(l)){s=!0;break}Wc.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 Yc(e){let t=e.findIndex(e=>e.text===`--`);return(t<0?e:e.slice(0,t)).filter(e=>e.text.startsWith(`-`))}function Xc(e){return e.every(e=>!e.expands&&!Mc.has(e.text))}function Zc(e){let t=e.filter(e=>e.text.startsWith(`-`)),n=t.some(e=>zc.has(e.text));return t.every(e=>zc.has(e.text)||Bc.has(e.text))&&(n||t.length===e.length)}function Qc(e){let[t,...n]=e[0]?.text===`--no-pager`?e.slice(1):e;return t===void 0||t.expands||!Rc.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`?Zc(n):t.text!==`remote`||n.every(e=>e.text===`-v`||e.text===`--verbose`)}function $c(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=>Gc(e.text))||Lc(t.text,n)?!1:t.text===`cd`?n.length===1&&n[0].text!==`-`&&!n[0].expands:jc.has(t.text)?!0:t.text===`find`?Xc(n):t.text===`git`&&Qc(n)}const el=new Set([`echo`,`which`,`git`]);function tl(e,t){let n;for(let[r,...i]of e)if(!el.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 nl(e,t={}){if(t.otherDirectory===!0||e.length>1e4||qc(e)||/[^\t\n\x20-\x7e]/.test(e))return!1;let n=Hs(e);if(n.length===0)return!1;let r=n.map(Jc);if(r.some(e=>e.refused||!$c(e.words)))return!1;let i=r.map(e=>e.words[0].text);return i.includes(`git`)&&i.includes(`cd`)?!1:tl(r.map(e=>e.words),t.resolveInWorkspace)}function rl(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 il(e,t){Q.set(e,{...Q.get(e),...t})}function al(e){return Q.get(e)??{}}function ol(e,t){let n=[t,...Q.get(t)?.aliases??[]];if(!e.includes(`*`))return n.includes(e);let r=Zs(e);return n.some(e=>r.test(e))}function sl(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 cl(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`:Zs(e.value).test(String(n))?`match`:`no-match`}function ll(e,t){return t.some(t=>{let n=rl(t);return(n.argPattern===void 0||n.argPattern===`*`||n.argPattern===`**`)&&ol(n.toolName,e)})}function ul(e){return Q.get(e)?.argument?.key}function dl(e,t){let n=ul(e);if(n===void 0)return;let r=t[n];return typeof r==`string`?r:void 0}function fl(e,t,n,r=`allow`){return n.some(n=>ml(e,t,n,r)===`match`)}function pl(e,t,n){return n.some(n=>ml(e,t,n,`deny`)===`unevaluable`)}function ml(e,t,n,r){let i=rl(n);if(!ol(i.toolName,e))return`no-match`;if(i.argPattern===void 0||i.argPattern===`*`||i.argPattern===`**`)return`match`;let a=sl(e,i.argPattern);if(a===`primary`)return`unevaluable`;if(a!==void 0)return r===`deny`?cl(a,t):`no-match`;let o=Q.get(e)?.argument;if(o===void 0)return`unevaluable`;let s=dl(e,t);if(s===void 0)return`no-match`;switch(o.kind){case`url`:return e===`WebFetch`?hc(i.argPattern,s):mc(i.argPattern,s);case`path`:return nc(i.argPattern,s);case`command`:return Qs(i.argPattern,s,r);case`text`:return Zs(i.argPattern).test(s)?`match`:`no-match`;default:{let e=o.kind;throw Error(`unknown argument kind: ${String(e)}`)}}}function hl(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`?Ac(a,n):i.kind===`path`&&r?.riskClass===`modify`&&Sc(a,n):!1}function gl(e,t,n,r){return fl(e,t,n,`deny`)||pl(e,t,n)||hl(e,t,r)}function _l(e,t,n={},r={}){return pl(e,t,n.deny??[])||gl(e,t,n.ask??[],r)}const vl=[`workingDirectory`,`cwd`];function yl(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`&&nl(i,{otherDirectory:vl.some(e=>t[e]!==void 0),...n.resolveInWorkspace===void 0?{}:{resolveInWorkspace:n.resolveInWorkspace}})?`inspect`:r.riskClass}function bl(e,t,n,r={},i={}){let{allow:a=[],deny:o=[],ask:s=[]}=r,c=yl(e,t,i),l=n===`plan`&&c!==`inspect`?`deny`:`approve`;return fl(e,t,o,`deny`)||i.ceiling!==void 0&&!fl(e,t,i.ceiling)||Q.get(e)?.repliesToPeer===!0&&i.peerTurn!==!0||Q.get(e)?.notInPeerTurn===!0&&i.peerTurn===!0?`deny`:pl(e,t,o)?n===`plan`?`deny`:`approve`:gl(e,t,s,i)||i.askAll===!0?l:n===`bypassPermissions`||fl(e,t,a)||i.sandboxAutoApproved===!0&&c===`execute`&&(n==="default"||n===`acceptEdits`||n===`auto`)?`auto`:c===void 0?_c[n]:gc[n][c]}function xl(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 Sl=/^[A-Za-z_]\w*:(?!\/\/)/;function Cl(e){return e.slice(0,e.indexOf(`*`)).includes(`__`)}function wl(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}=rl(n);if(r===``)return`names no tool`;if(t===`allow`&&r.includes(`*`)&&!Cl(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`&&Sl.test(i)?`matches a named parameter, which only deny and ask rules may do`:void 0;let a=sl(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=al(r);if(!(o.parameters===void 0&&Sl.test(i)&&sl(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`&&(r===`WebFetch`?hc:mc)(i,`https://probe.invalid/`)===`unevaluable`)return`does not fit the URL pattern grammar scheme://host[:port][/path]${r===`WebFetch`?` or domain:hostname`:``} that "${r}" is matched by`}}function Tl(e,t=`deny`){let n=[];for(let r of e){let e=wl(r,t);e!==void 0&&n.push({pattern:r,reason:e})}return n}function El(e){let t=[];for(let n of e){let{toolName:e,argPattern:r}=rl(n.trim());if(r===void 0||e.includes(`*`))continue;let i=al(e),a=sl(e,r);if(a===void 0&&i.parameters!==void 0&&i.argument?.kind!==`url`&&Sl.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=al(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 Dl(e){return(e??[]).map(e=>`${e}(*)`)}function Ol(e,t){let n=Dl(t.allowedTools),r=Tl(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,...Dl(t.deniedTools)])]}}const kl=[`Bash`,`Shell`,`BackgroundProcess`],Al=[`Agent`],jl=[...kl,...Al,`ExecuteCommand`,`Computer`],Ml=`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(`.`),Nl=[`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(` `)),Pl=new Set([`run`,`run-script`,`exec`,`dlx`,`x`,`--`]);function Fl(e){return(e.split(/[\\/]/).pop()??e).replace(/(\.exe)?$/i,``).replace(/[\d.]+$/,``)}function Il(e,t){if(e.length===0)return!0;let n=(e,n,r)=>t&&r?e.startsWith(n):e===n,r=Fl(e[0]);if(Ml.some(t=>n(t,r,e.length===1)))return!0;for(let i of Nl){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(`-`)||Pl.has(o[0]));)o=o.slice(1);return o.length===0||Il(o,t)}return!1}function Ll(e){let t=e.trim();if(!t.includes(`*`))return!1;let n=t.slice(0,t.indexOf(`*`));return Il(n.trim().split(/\s+/).filter(e=>e.length>0),n.length>0&&!/\s$/.test(n))}function Rl(e){let{toolName:t,argPattern:n}=rl(e),r=e=>e.some(e=>ol(t,e));return r(Al)?!0:t.includes(`*`)?r(jl):jl.includes(t)||al(t).riskClass===`execute`?n===void 0||n.trim()===`*`||kl.includes(t)&&Ll(n):!1}function zl(e){return e.filter(e=>!Rl(e))}const Bl=1e6,Vl={"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}},Hl=[{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:/gemini-2/i,price:{inputPerMillion:.1,outputPerMillion:.4}},{pattern:/gemini-1/i,price:{inputPerMillion:1.25,outputPerMillion:5}}];function Ul(e){let t=Object.hasOwn(Vl,e)?Vl[e]:void 0;if(t)return t;for(let{pattern:t,price:n}of Hl)if(t.test(e))return n}function Wl(e,t,n){let r=Ul(e);if(r)return t/Bl*r.inputPerMillion+n/Bl*r.outputPerMillion}function Gl(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 Kl(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 ql(){let[{CommandExecutor:e},{HttpExecutor:t}]=await Promise.all([import(`./command-executor-D_UBZHxh-D7UrdAlN.js`).then(e=>e.t).then(e=>e.n),import(`./http-executor-ADn4locH-uz5KV6N-.js`).then(e=>e.t).then(e=>e.n)]);return[new e,new t]}async function Jl(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 ql(),u=new Map;for(let e of l)u.set(e.type,e);let d=[],f=Kl(n),p=-1,m,h;for(let e of c){if(!Gl(e,f))continue;let r=e.env?{...n,env:{...n.env,...e.env}}:n;for(let n of e.hooks){let e=u.get(n.type);if(!e){a.add(n.type);continue}let c=n.type===`command`&&i!==void 0?await e.execute(n,r,i):await e.execute(n,r);if(c.outcome===`deny`)return{blocked:!0,reason:c.reason||`Blocked by hook`,stdout:d.join(`
|
|
13
13
|
`),...s()};if(c.outcome===`error`){o.push(c);continue}let l=v(c.stdout,t);if(d.push(...l.context),l.blockReason!==void 0)return{blocked:!0,reason:l.blockReason,stdout:d.join(`
|
|
14
14
|
`),...l.permissionDecision===`deny`&&{permissionDecision:`deny`},...s()};if(l.permissionDecision!==void 0&&c.source===`command`){let e=y[l.permissionDecision];e>p?(p=e,m=l.permissionDecision,h=l.updatedInput):e===p&&l.updatedInput!==void 0&&(h=l.updatedInput)}}}let g={blocked:!1,stdout:d.join(`
|
|
15
|
-
`)};m!==void 0&&(g.permissionDecision=m),h!==void 0&&(g.updatedInput=h);let{unknownHookTypes:_,errors:b}=s();return _!==void 0&&(g.unknownHookTypes=_),b!==void 0&&(g.errors=b),g}var
|
|
15
|
+
`)};m!==void 0&&(g.permissionDecision=m),h!==void 0&&(g.updatedInput=h);let{unknownHookTypes:_,errors:b}=s();return _!==void 0&&(g.unknownHookTypes=_),b!==void 0&&(g.errors=b),g}var Yl=class extends Error{guardrailName;guardrailReason;constructor(e,t){super(t),this.guardrailName=e,this.guardrailReason=t,this.name=`GuardrailBlock`}},Xl=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 Yl(e,`Guardrail "${e}" errored: ${t instanceof Error?t.message:String(t)}`)}if(!r.pass)throw new Yl(e,r.reason??`Guardrail "${e}" blocked the turn`)}))}catch(e){if(e instanceof Yl)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 Zl(e,t){return{posture:`advisory`,enforcementReachable:!1,rationale:`Awaited at ${e} but only ${t} is read; \`blocked\` is never consulted.`}}function Ql(e){for(let t of Object.values(e))Object.freeze(t);return Object.freeze(e)}const $l=Ql({PreToolUse:{posture:`enforcing`,enforcementReachable:!0,rationale:"The tool-execution gate. `runPreToolGate` 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:Zl(`session-lifecycle.ts`,`nothing`),PreCompact:Zl(`compaction-orchestrator.ts`,`nothing`),UserPromptSubmit:Zl(`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 eu(e){return $l[e].posture===`enforcing`}function tu(e){if(e.type===`resource_link`)return`Resource reference (not fetched): ${JSON.stringify(e)}`;if(e.type===`resource_embedded`){let t=`${JSON.stringify(e.uri)}${e.mimeType?` (${e.mimeType})`:``}`;return e.text===void 0?`Embedded binary resource ${t}; binary content retained but not transmitted by this adapter.`:`Embedded resource ${t}:\n${e.text}`}if(e.type===`audio_inline`)return`Audio observation (${e.mimeType}); this adapter does not transmit audio payloads.`}export{Tr as $,Me as A,ll as At,en as B,ye as Bt,Xl as C,vc as Ct,je as D,al as Dt,z as E,qe as Et,Pe as F,An as Ft,Dt as G,Dl as Gt,Ee as H,xl as Ht,ni as I,Xe as It,Wl as J,Fe as Jt,Ie as K,ct as Kt,Vl as L,xr as Lt,eu as M,ao as Mt,B as N,Cr as Nt,j as O,Er as Ot,Hs as P,Dr as Pt,bl as Q,Ns as R,Nn as Rt,mr as S,Nr as St,Jl as T,Sr as Tt,Ol as U,Te as Ut,Tl as V,Vn as Vt,si as W,ut as Wt,ve as X,oe as Xt,Os as Y,se as Yt,Bn as Z,w as Zt,R as _,Or as _t,ii as a,br as at,zl as b,Qe as bt,Rs as c,Jt as ct,Kn as d,yc as dt,On as et,zs as f,Rn as ft,Et as g,qr as gt,Le as h,Ye as ht,Jr as i,Pn as it,uo as j,Re as jt,ke as k,kn as kt,De as l,zn as lt,ro as m,wr as mt,fo as n,jn as nt,we as o,il as ot,ci as p,it as pt,ai as q,be as qt,tu as r,Ar as rt,El as s,pe as st,Dn as t,zr as tt,nn as u,Ds as ut,Bs as v,Vt as vt,bn as w,_l as wt,ze as x,fl as xt,un as y,Mn as yt,Ce as z,ks as zt};
|
|
@@ -8,8 +8,8 @@ import{C as e,S as t,_ as n,a as r,b as i,c as a,d as o,f as s,g as c,i as l,l a
|
|
|
8
8
|
`),n.beginAssistant();let b=io(),{wrappedOnTextDelta:x,wrappedOnProviderNativeRawPayload:S,settleStreamingChunkHooks:C}=xo(a,n,i,p,l,u),w=Ka(s,o.defaultModel.model,i),T=W(),E;try{E=await So(_,o,s,f,a,n,p,i,b,u,x,S,t=>void(e.providerFailure=t),w,T,a.executionJournal?Da(m,e,a,o,t,c.toolExecutionService.getLoadedDeferredTools()):void 0)}finally{await C()}if(E===null)return!0;let{assistantResponse:D,assistantToolCalls:O}=eo(E,i,a.conversationId,p,u);if(O.length>0&&(a.toolChoice??o.defaultModel?.toolChoice)===`none`)throw Error(`Provider returned tool calls despite toolChoice none; no tools were executed.`);await G(l,`afterProviderCall`,{messages:m,responseMessage:E},u),await G(l,`onMessageAdded`,{message:E},u);let ee=typeof D.content==`string`&&D.content.trim().length>0;if(O.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=oo(D),ne=te.inputTokens??0;ne>0&&(e.cumulativeInputTokens=ne);for(let e of O)n.appendToolCall(e);let re=a.signal?.aborted?`interrupted`:`complete`;n.commitAssistant(re,{round:p,usageObservationId:b,executionId:i,providerId:K(w,s),providerCallId:T,modelId:q(w,s.aiProviderInfo.model),...te});let ie=n.getMessages().at(-1);return a.onExecutionEvent?.(`assistant_message_committed`,{executionId:i,conversationId:a.conversationId,round:p,message:D}),ie&&a.onExecutionEvent?.(`history_mutation`,{executionId:i,conversationId:a.conversationId,round:p,mutation:`append_message`,index:n.getMessages().length-1,message:ie}),e.runningAssistantCount++,e.lastTrackedAssistantMessage=D,O.length===0?(u.debug(`[AGENT-FLOW-CONTROL] Round ${p} completed - no tool calls, execution finished for agent ${a.conversationId}`),d.emitAssistantMessageComplete(D,i,p,r,v,y),!0):_o(await No(O,n,r,i,p,v,y,e,c,o,a.signal,a.onExecutionEvent,a.maxSameToolInputs??o.maxSameToolInputs,a.traceContext,a.executionJournal?{journal:a.executionJournal,parentCallId:T}:void 0),e,u)?!0:(u.debug(`Round ${p} completed for agent ${a.conversationId}`),!1)}function Fo(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 Io(e,t){return t===0||e<t}async function Lo(t,n,r,i,a,o,s,c,l,u=!1){let d=Fo(a,i);for(;!u&&!s.forcedSummaryInstruction&&Io(s.currentRound,d)&&!(c?.aborted||(s.currentRound++,await Po(s,d,t,n,r,i,a,o,l))||c?.aborted););let f=t.getMessages(),p=f.length>0?f[f.length-1]:void 0,m=p?.role===`assistant`&&typeof p.content==`string`&&p.content.length>0&&(!(`toolCalls`in p)||p.toolCalls.length===0);if(!c?.aborted){if(i.allowToolOnlyCompletion===!0){let t=p?.role===`tool`;if(!m&&!t)throw new e(s.currentRound,{conversationId:n,executionId:r});return}m||await go(t,o,a,r,s,n,i,l.logger,d,i.executionJournal?l.toolExecutionService.getLoadedDeferredTools():void 0)}}async function Ro(e,t,n,r,i,a,o,s,c,l,u,d){let f={...Ea(t,n,r,i.toolsExecuted,{turnMessageId:o,interrupted:s,...c?.allowToolOnlyCompletion===!0&&{allowToolOnlyCompletion:!0}},i.providerFailure),interrupted:s};await G(l,`afterRun`,{input:e,response:f.response,metadata:c?.metadata},u);let p={messages:f.messages,executionContext:{executionId:n,conversationId:a},executionResult:{response:f.response,duration:f.duration,...f.tokensUsed===void 0?{}:{tokensUsed:f.tokensUsed},toolsExecuted:f.toolsExecuted.length,success:f.success,toolCalls:i.toolCallOutcomes.map(e=>({...e.id===void 0?{}:{id:e.id},name:e.name,...e.success?{}:{result:null}}))}};for(let e of[`afterExecution`,`afterConversation`,`afterToolExecution`])await G(l,e,p,u);return u.debug(`Execution pipeline completed successfully`,{executionId:n,conversationId:a,duration:f.duration,tokensUsed:f.tokensUsed,toolsExecuted:f.toolsExecuted.length,rounds:i.currentRound}),d.emitExecution(P.COMPLETE,{result:{success:!0,data:f.response.substring(0,100)+`...`},metadata:{method:`execute`,success:!0,duration:f.duration,tokensUsed:f.tokensUsed,toolsExecuted:f.toolsExecuted}},a,n),f}function J(e){return JSON.stringify(e,(e,t)=>t&&typeof t==`object`&&!Array.isArray(t)?Object.fromEntries(Object.entries(t).sort(([e],[t])=>e.localeCompare(t))):t)}function Y(e){throw new z(`EXECUTION_RECOVERY_INVALID`,e)}function X(e){return typeof e==`string`&&e.length>0}function zo(e,t,n,r=!0){try{return Bo(structuredClone(e),t,n,r)}catch(e){if(e instanceof z)throw e;return Y(`Execution journal is not a valid recoverable record prefix`)}}function Bo(e,t,n,r){(!X(t)||!X(n)||!Array.isArray(e))&&Y(`Missing recovery identity`);let i=[],a=new Map,o,s=new Map,c=new Map,l=new Set,u=new Set;for(let n of e){(!n||n.executionId!==t||!X(n.recordId))&&Y(`Journal execution identity mismatch`);let e=J(n),r=a.get(n.recordId);if(r!==void 0){e!==r&&Y(`Conflicting journal record identity`);continue}if(a.set(n.recordId,e),i.push(n),`callId`in n)X(n.callId)||Y(`Missing model call identity`),n.kind===`model-request`||n.kind===`model-cache-hit`?o=n.callId:n.callId!==o&&Y(`Model settlement crossed a newer invocation`);else if(`actionId`in n){(!X(n.actionId)||!X(n.parentCallId))&&Y(`Missing action identity`);let e=s.get(n.actionId),t=J([n.parentCallId,n.toolCallId,n.toolName]);if(e&&e!==t&&Y(`Action identity belongs to multiple calls`),s.set(n.actionId,t),n.kind===`tool-wait`&&((!n.request||!X(n.request.requestId)||!X(n.request.kind)||c.has(n.request.requestId))&&Y(`Invalid or duplicate tool wait`),Do(n.request.data),c.set(n.request.requestId,n)),n.kind===`tool-response`){let e=n.response,t=e&&c.get(e.requestId);(!t||!X(e.responseId)||l.has(e.requestId)||u.has(e.responseId)||t.actionId!==n.actionId||t.parentCallId!==n.parentCallId||t.toolCallId!==n.toolCallId||t.toolName!==n.toolName)&&Y(`Tool response does not belong to an unanswered request`),Do(e.response),l.add(e.requestId),u.add(e.responseId)}}else Y(`Unknown journal record`)}o!==n&&Y(`Only the latest model invocation can be recovered`);let d,f,p,m=new Map;for(let e of i){if(`callId`in e){if(e.callId!==n)continue;e.kind===`model-request`?((d||f)&&Y(`Duplicate or out-of-order model request`),d=e):e.kind===`model-cache-hit`?((d||f||e.response.role!==`assistant`)&&Y(`Invalid cache settlement`),f=e.response,p=e.checkpoint):e.kind===`model-response`?((!d||f||e.response.role!==`assistant`)&&Y(`Invalid model response`),f=e.response):Y(`This model invocation has no recoverable tool response`);continue}if(e.parentCallId!==n)continue;f||Y(`Tool action precedes its model response`);let r=f.toolCalls?.find(t=>t.id===e.toolCallId);(!r||e.toolName!==r.function.name)&&Y(`Action does not belong to the saved model response`);let i=m.get(e.toolCallId);if(i&&i.actionId!==e.actionId&&Y(`Multiple actions claim one tool call`),i||(i={actionId:e.actionId,intent:!1,dispatched:!1,effectStarted:!1,waits:[]},m.set(e.toolCallId,i)),i.result&&Y(`Tool action continued after settlement`),e.kind===`tool-intent`)(i.intent||i.dispatched||i.effectStarted)&&Y(`Out-of-order action intent`),J(JSON.parse(r.function.arguments))!==J(e.parameters)&&Y(`Action arguments differ from saved intent`),i.intent=!0;else if(e.kind===`tool-dispatch`)(!i.intent||i.dispatched||i.effectStarted)&&Y(`Out-of-order dispatch`),i.dispatched=!0;else if(e.kind===`tool-effect-start`)(!i.dispatched||i.effectStarted)&&Y(`Out-of-order effect admission`),i.waits.some(e=>!e.response)&&Y(`Tool effect precedes a required response`),i.effectStarted=!0;else if(e.kind===`tool-wait`)(!i.dispatched||i.effectStarted)&&Y(`Tool wait is outside pre-effect dispatch`),i.waits.push({request:{...e.request,executionId:t,actionId:e.actionId,parentCallId:e.parentCallId,toolCallId:e.toolCallId,toolName:e.toolName}});else if(e.kind===`tool-response`){let t=i.waits.find(t=>t.request.requestId===e.response.requestId);(!t||t.response||i.effectStarted)&&Y(`Out-of-order tool response`),t.response=e.response}else if(e.kind===`tool-result`){let t=e.result,n=t.metadata?.errorCode===yt;n&&(t.success||i.dispatched||i.effectStarted||t.metadata?.dispatchStatus!==`not-dispatched`||t.result!==null)&&Y(`Skipped tool result cannot claim a dispatched or applied effect`),(!i.intent&&t.metadata?.errorCode!==`argument_decode_error`&&!n||t.executionId!==r.id||t.toolName!==r.function.name||typeof t.success!=`boolean`||t.success&&(!i.effectStarted||t.result===void 0)||!t.success&&!X(t.error))&&Y(`Invalid tool result linkage or payload`),e.loadedDeferredTools!==void 0&&(!Array.isArray(e.loadedDeferredTools)||e.loadedDeferredTools.some(e=>!X(e)))&&Y(`Invalid tool residency settlement`),i.result=t,i.loadedDeferredTools=e.loadedDeferredTools}else Y(`Unknown action record`)}let h=d?.checkpoint??p;(!f||!h||h.version!==1||h.effectAdmission!==`required`)&&Y(`A supported effect-admission checkpoint is required`),(!Number.isSafeInteger(h.round)||h.round<1||!Number.isFinite(h.contextLimit)||h.contextLimit<=0||!Number.isFinite(h.cumulativeInputTokens)||h.cumulativeInputTokens<0||!Array.isArray(h.messages)||!Array.isArray(h.sameToolInputCounts))&&Y(`Invalid round checkpoint`);let g=new Set;for(let e of h.messages)g.has(e.id)&&Y(`Duplicate checkpoint message identity`),g.add(e.id);for(let e of[...h.messages,f])(!X(e.id)||!(e.timestamp instanceof Date)||!Number.isFinite(e.timestamp.getTime())||(e.role===`assistant`?e.content!==null&&typeof e.content!=`string`:typeof e.content!=`string`)||e.role===`tool`&&!X(e.toolCallId)||![`user`,`assistant`,`system`,`tool`].includes(e.role)||![`complete`,`interrupted`].includes(e.state))&&Y(`Invalid checkpoint message`);let _=new Set;for(let[e,t]of h.sameToolInputCounts)(!X(e)||_.has(e)||!Number.isSafeInteger(t)||t<0)&&Y(`Invalid repeated-input checkpoint`),_.add(e);h.maxSameToolInputs!==void 0&&(!Number.isSafeInteger(h.maxSameToolInputs)||h.maxSameToolInputs<1)&&Y(`Invalid repeated-input limit`),r&&(!Array.isArray(f.toolCalls)||f.toolCalls.length===0)&&Y(`Saved response has no tool calls`),g.clear();for(let e of f.toolCalls??[])(!X(e.id)||g.has(e.id)||e.type!==`function`||!X(e.function?.name)||typeof e.function.arguments!=`string`)&&Y(`Invalid or duplicate saved tool call`),g.add(e.id);d?.options.toolChoice===`none`&&(f.toolCalls?.length??0)>0&&Y(`Saved invocation prohibited tool execution`);let v=[...m.values()].filter(e=>e.effectStarted&&!e.result);if(v.length)throw new z(`EXECUTION_RECOVERY_REQUIRED`,`Tool effects have no durable result; reconcile them before resuming`,v.map(e=>e.actionId));return{checkpoint:h,response:f,actions:m,offeredDeferredTools:d?.options.tools?.filter(e=>e.deferLoading).map(e=>e.name)??[]}}function Vo(e){throw new z(`EXECUTION_RECOVERY_CONFLICT`,e)}function Ho(e,t){return{...structuredClone(e.response),id:`recovery:${t.executionId}:${t.callId}:assistant`,...e.checkpoint.continuation?.kind===`summary`&&{content:e.response.content||`Maximum rounds reached. Partial results available in conversation history.`,toolCalls:[]},metadata:{...e.response.metadata,...oo(e.response),executionId:t.executionId,providerCallId:t.callId,round:e.checkpoint.round}}}function Uo(e,t,n,r){return e.role===`assistant`&&t.role===`assistant`&&(e.content??``)===(t.content??``)&&J(e.toolCalls??[])===J(t.toolCalls??[])&&e.metadata?.providerCallId===n&&e.metadata.executionId===r}function Wo(e,t,n,r){if(!e.length)return;let i=t.checkpoint.messages;(e.length<i.length||J(e.slice(0,i.length))!==J(i))&&Vo(`Current history differs from the saved runtime checkpoint`);let a=e.slice(i.length);if(!a.length)return;Uo(a[0],Ho(t,n),n.callId,n.executionId)||Vo(`Current assistant does not match the saved response`);let o=t.response.toolCalls??[];a.length>o.length+1&&Vo(`History has advanced beyond the recovered tool batch`);let s=o.slice(0,a.length-1),c=s.map(e=>{let n=t.actions.get(e.id)?.result;return n||Vo(`History contains a tool result without durable settlement`),n}),l=new Un;for(let e of i)l.addMessage(e);l.addMessage(a[0]),To(s,{results:c,errors:[]},l,t.checkpoint.round,r.logger,{contextLimit:t.checkpoint.contextLimit,cumulativeInputTokens:Go(t)});for(let e=1;e<a.length;e++){let t=l.getMessages()[i.length+e],n=a[e];(n.role!==`tool`||t.role!==`tool`||n.toolCallId!==t.toolCallId||n.name!==t.name||n.content!==t.content)&&Vo(`Existing tool result conflicts with the durable result`)}}function Go(e){let t=oo(e.response).inputTokens??0;return t>0?t:e.checkpoint.cumulativeInputTokens}async function Ko(e,t,n,r,i){let a=J(e.getMessages()),o=()=>{(a!==J(e.getMessages())||e.hasPendingAssistant())&&Vo(`History changed during execution recovery`)};o();let s=i?.records??await n.journal.read(n.executionId),c=i?.batch??zo(s,n.executionId,n.callId);n.signal?.throwIfAborted(),o();let l=structuredClone(e.getMessages());Wo(l,c,n,r);let u=await Ao(s,n);u.length!==s.length&&(c=zo(u,n.executionId,n.callId,!1)),n.signal?.throwIfAborted(),o();let d=new Set([...c.checkpoint.continuation?.loadedDeferredTools??[],...c.offeredDeferredTools]);for(let e of c.actions.values())for(let t of e.loadedDeferredTools??[])d.add(t);r.toolExecutionService.restoreLoadedDeferredTools([...d]);let f=new Un;for(let e of c.checkpoint.messages)f.addMessage(structuredClone(e));let p=c.checkpoint.continuation?.kind===`summary`,m=c.response.toolCalls??[];(p||m.length>0||(c.response.content?.trim().length??0)>0)&&f.addMessage(Ho(c,n));let h={toolsExecuted:[...c.checkpoint.continuation?.toolsExecuted??[]],toolCallOutcomes:[],currentRound:c.checkpoint.round,runningAssistantCount:f.getMessages().filter(e=>e.role===`assistant`).length,lastTrackedAssistantMessage:c.response,cumulativeInputTokens:Go(c),consecutiveUnknownToolFailureRounds:c.checkpoint.continuation?.consecutiveUnknownToolFailureRounds??0,forcedSummaryInstruction:c.checkpoint.continuation?.forcedSummaryInstruction,sameToolInputCounts:new Map(c.checkpoint.sameToolInputCounts)};r.eventEmitter.prepareOwnerPathBases(t);try{let i=m.length===0;m.length>0&&(i=_o(await No(m,f,t,n.executionId,c.checkpoint.round,n.callId,void 0,h,r,void 0,n.signal,void 0,c.checkpoint.maxSameToolInputs,void 0,{journal:n.journal,parentCallId:n.callId,recovery:c}),h,r.logger)),o();for(let t of f.getMessages().slice(l.length))e.addMessage(t);let a=structuredClone(e.getMessages()),s=J(a);for(let r=l.length;r<a.length;r++)n.onExecutionEvent?.(`history_mutation`,{executionId:n.executionId,conversationId:t,round:c.checkpoint.round,mutation:`append_message`,index:r,message:a[r]}),(s!==J(e.getMessages())||e.hasPendingAssistant())&&Vo(`History changed while announcing execution recovery`);if(n.signal?.aborted)throw Dt(`Execution recovery interrupted`,n.signal.reason);return{executionId:n.executionId,callId:n.callId,messages:structuredClone(e.getMessages()),batch:c,state:h,stop:i}}finally{r.eventEmitter.clearToolEventServices(),r.eventEmitter.resetOwnerPathBases()}}async function qo(e,t,n,r){let{executionId:i,callId:a,messages:o}=await Ko(e,t,n,r);return{executionId:i,callId:a,messages:o}}function Z(e){throw new z(`EXECUTION_RECOVERY_INVALID`,e)}function Jo(e){return(!e||e.version!==1||![`round`,`summary`].includes(e.kind)||typeof e.startedAt!=`string`||!Number.isFinite(Date.parse(e.startedAt))||typeof e.turnMessageId!=`string`||e.turnMessageId.length===0||!e.model||typeof e.model.provider!=`string`||typeof e.model.model!=`string`||!e.model.provider||!e.model.model||!e.options||!Number.isSafeInteger(e.options.maxExecutionRounds)||e.options.maxExecutionRounds<0||!Array.isArray(e.toolsExecuted)||e.toolsExecuted.some(e=>typeof e!=`string`)||!Number.isSafeInteger(e.consecutiveUnknownToolFailureRounds)||e.consecutiveUnknownToolFailureRounds<0||!Array.isArray(e.loadedDeferredTools)||e.loadedDeferredTools.some(e=>typeof e!=`string`||!e)||typeof e.structuredOutput!=`boolean`||typeof e.options.allowToolOnlyCompletion!=`boolean`||typeof e.options.withholdHostedTools!=`boolean`)&&Z(`Unsupported runtime continuation checkpoint`),e.structuredOutput&&Z(`Structured-output validators do not yet support execution continuation`),e}async function Yo(e,t,n,r,i,a){let o=J(e.getMessages()),s=await n.journal.read(n.executionId);n.signal?.throwIfAborted();let c=s.findLast(e=>e.kind===`model-request`||e.kind===`model-cache-hit`);if((!c||!(`callId`in c))&&Z(`No recoverable model invocation exists`),c.kind===`model-request`&&!s.some(e=>e.kind===`model-response`&&e.callId===c.callId))throw new z(`EXECUTION_RECOVERY_REQUIRED`,`The latest model invocation has no durable response; reconcile it before resuming`);let l=zo(s,n.executionId,c.callId,!1),u=Jo(l.checkpoint.continuation);(u.model.provider!==r.defaultModel.provider||u.model.model!==r.defaultModel.model)&&Z(`Active provider and model must match the saved runtime before continuation`);let d=l.checkpoint.messages.find(e=>e.id===u.turnMessageId);(!d||d.role!==`user`||d.metadata?.executionId!==n.executionId)&&Z(`Continuation has no matching original input`),(u.toolSearch??`auto`)!==(r.toolSearch??`auto`)&&Z(`Tool residency policy differs from the saved runtime`),r.responseFormat&&r.responseFormat.type!==`text`&&Z(`Current runtime requires an unsupported structured-output validator`),u.options.maxSameToolInputs!==l.checkpoint.maxSameToolInputs&&Z(`Conflicting repeated-input limits`),u.kind===`summary`&&(l.response.toolCalls?.length??0)>0&&Z(`Terminal summary cannot dispatch tools`);for(let e of l.actions.values())e.result&&e.loadedDeferredTools===void 0&&Z(`Settled action lacks runtime residency state`);let f={...r,defaultModel:structuredClone(u.model),timeout:u.timeout,maxExecutionRounds:u.options.maxExecutionRounds,maxSameToolInputs:u.options.maxSameToolInputs},p=i(f);if(p.currentInfo.provider!==u.model.provider&&Z(`Active provider manager differs from the saved runtime`),o!==J(e.getMessages()))throw new z(`EXECUTION_RECOVERY_CONFLICT`,`History changed while reading the execution journal`);let m=await Ko(e,t,{...n,callId:c.callId},a,{batch:l,records:s}),h=Ha(e.getMessages(),f,new Date(u.startedAt),n.executionId,t,{...u.options,signal:n.signal,executionJournal:n.journal,onTextDelta:n.onTextDelta,onThinkingDelta:n.onThinkingDelta,onExecutionEvent:n.onExecutionEvent,traceContext:n.traceContext});a.eventEmitter.prepareOwnerPathBases(t);try{if(await Lo(e,t,n.executionId,h,f,p,m.state,n.signal,a,m.stop||u.kind===`summary`),n.signal?.aborted)throw Dt(`Execution continuation interrupted`,n.signal.reason);return Ea(e,n.executionId,h.startTime,m.state.toolsExecuted,{turnMessageId:u.turnMessageId,allowToolOnlyCompletion:u.options.allowToolOnlyCompletion},m.state.providerFailure)}finally{a.eventEmitter.clearToolEventServices(),a.eventEmitter.resetOwnerPathBases()}}async function*Xo(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 Zo(e,t,n){return{executionId:e,...t===void 0?{}:{driverId:t},...n===void 0?{}:{turnSource:n}}}var Qo=class{toolExecutionService;aiProviders;tools;conversationHistory;plugins=[];logger;eventEmitter;cacheService;constructor(e,t,n,r,i,a){if(this.toolExecutionService=new fa(t),this.aiProviders=e,this.tools=t,this.conversationHistory=n,this.plugins=[],this.logger=j(`ExecutionService`),!r)throw Error(`[EXECUTION] EventService is required`);this.eventEmitter=new Sa(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`)}resume(e,t,n){return Yo(this.conversationHistory.getConversationStore(e),e,t,n,e=>Ia(this.aiProviders,this.tools,e),{toolExecutionService:this.toolExecutionService,plugins:this.plugins,logger:this.logger,eventEmitter:this.eventEmitter,cacheService:this.cacheService})}resumeToolCalls(e,t){return qo(this.conversationHistory.getConversationStore(e),e,t,{toolExecutionService:this.toolExecutionService,plugins:this.plugins,logger:this.logger,eventEmitter:this.eventEmitter})}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=Ba(),a=new Date,o=Va(r,`execute`),s=Ha(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=Ia(this.aiProviders,this.tools,n);this.eventEmitter.emitExecutionStartEvent(e,n,t,c,o,i);let l=Ra(this.conversationHistory,o,t,n,i),u,d={toolsExecuted:[],toolCallOutcomes:[],currentRound:0,runningAssistantCount:0,lastTrackedAssistantMessage:void 0,cumulativeInputTokens:0,consecutiveUnknownToolFailureRounds:0,sameToolInputCounts:new Map};try{let t=l.getMessages().length;l.addUserMessage(e,Zo(i,r?.driverId,r?.turnSource));let f=l.getMessages().at(-1);u=f?.id,f&&s.onExecutionEvent?.(`history_mutation`,{executionId:i,conversationId:o,mutation:`append_message`,index:t,message:f}),this.eventEmitter.emitUserMessageEvent(e,o,i),await G(this.plugins,`beforeRun`,{input:e,...r?.metadata?{metadata:r.metadata}:{}},this.logger);let p={executionId:i,conversationId:o};f&&await G(this.plugins,`onMessageAdded`,{message:f,executionContext:p},this.logger);for(let e of[`beforeExecution`,`beforeConversation`])await G(this.plugins,e,{messages:l.getMessages(),executionContext:p},this.logger);La(c);for(let e of l.getMessages())e.role===`assistant`&&(d.runningAssistantCount++,d.lastTrackedAssistantMessage=e);return await Lo(l,o,i,s,n,c,d,r?.signal,{toolExecutionService:this.toolExecutionService,plugins:this.plugins,logger:this.logger,eventEmitter:this.eventEmitter,cacheService:this.cacheService}),Ro(e,l,i,a,d,o,u,r?.signal?.aborted??!1,r,this.plugins,this.logger,this.eventEmitter)}catch(e){if(B(e))throw e;return Et(e,r?.signal)?{...Ea(l,i,a,d.toolsExecuted,{turnMessageId:u,interrupted:!0}),interrupted:!0}:(await za(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*Xo(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 $o(e){let t=new Ni;if(e.aiProviders)for(let n of e.aiProviders)t.addProvider(n.name,n,{ownership:e.providerOwnership&&Object.hasOwn(e.providerOwnership,n.name)?e.providerOwnership[n.name]:`owned`});return e.defaultModel&&t.setCurrentProvider(e.defaultModel.provider,e.defaultModel.model),t}async function es(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 ConversationAgent 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 wt&&c&&e.setEventService(c),r.addResultTool(e.schema,async(t,n)=>{if(!n)throw Error(`[AGENT] Missing ToolExecutionContext for tool execution`);return Fr(e,t,n)},e.provenance),l.debug(`Tool registered during initialization`,{toolName:e.schema.name});let u;t.cache?.enabled&&(u=new Ii(new Fi({maxEntries:t.cache.maxEntries,ttlMs:t.cache.ttlMs}),new Pi));let d=new Qo(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(`ConversationAgent initialization completed successfully with independent managers`),d}async function ts(e){try{let t=await es(e.ctx);e.setExecutionService(t),e.setFullyInitialized(!0)}catch(t){throw e.ctx.logger.error(`ConversationAgent initialization failed`,{error:t instanceof Error?t.message:String(t)}),t}}function ns(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 rs(e){e.logger.debug(`Destroying ConversationAgent 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 ConversationAgent 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(`ConversationAgent instance destroyed successfully`,{name:e.name}):e.logger.warn(`ConversationAgent instance destroyed with cleanup failures`,{name:e.name,failureCount:t.length}),{errors:t}}var is=class{tail=Promise.resolve();claimed=0;async acquire(e){let t=this.claimed>0;this.claimed+=1;let n=this.tail,r=()=>{};this.tail=new Promise(e=>{r=e});let i=!1,a=()=>{i||(i=!0,--this.claimed,r())};if(await n,e?.aborted)throw a(),as(e,t);return a}async run(e,t){let n=await this.acquire(e);try{return await t()}finally{n()}}get drained(){return this.tail}};function as(e,t){let n=e.reason;return Et(n)&&n.name===`AbortError`?n:Dt(t?`Run aborted while queued behind another run on this instance`:`Run aborted before it started`,n)}function os(e){return{maxConcurrentAgents:e.maxConcurrentAgents||100,defaultSystemMessage:e.defaultSystemMessage??``,strictValidation:e.strictValidation??!0,idFactory:e.idFactory??cs,...e.defaultModel!==void 0&&{defaultModel:e.defaultModel},...e.defaultProvider!==void 0&&{defaultProvider:e.defaultProvider}}}function ss(e,n){if(!e.aiProviders||e.aiProviders.length===0)throw new t(`At least one AI provider must be specified in aiProviders array`);let r=e.defaultModel,i=r?.model??n.defaultModel;if(!i)throw new t(`No model specified: set config.defaultModel.model or the AgentFactory defaultModel option`);let a=r?.provider??e.aiProviders[0]?.name??n.defaultProvider;if(!a)throw new t(`No provider specified: set config.defaultModel.provider, an aiProviders entry, or the AgentFactory defaultProvider option`);return{id:e.id||cs(),name:e.name||`Unnamed Agent`,aiProviders:e.aiProviders,defaultModel:{provider:a,model:i,temperature:r?.temperature??.7,...r?.maxTokens!==void 0&&{maxTokens:r.maxTokens},...r?.topP!==void 0&&{topP:r.topP}},systemMessage:e.systemMessage??n.defaultSystemMessage,tools:e.tools||[],plugins:e.plugins||[],metadata:e.metadata||{},...e.logging&&{logging:e.logging},...e.conversationId&&{conversationId:e.conversationId},...e}}function cs(){return`agent_${Date.now()}_${Math.random().toString(36).substring(2,8)}`}function ls(e,t){return e.totalCreated++,e.activeCount++,t?e.fromTemplates++:e.customConfigured++,e.templateUsageRatio=e.totalCreated>0?e.fromTemplates/e.totalCreated:0,e}var us=class{templates=new Map;logger;constructor(){this.logger=j(`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 ds(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 fs(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 ps(e,n.name,r)}t.push(n)}}function ps(e,t,n){let r=e instanceof Error?e:Error(String(e));return Object.assign(r,{failedStep:t,rollbackErrors:n})}var ms=class{agentTemplates;initialized=!1;logger;options;activeAgents;pendingAgents=new Set;creationStats;lifecycleEvents;constructor(e={},t={}){this.agentTemplates=new us,this.logger=j(`AgentFactory`),this.options=os(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,r,i=!1){let a,o=this.admit();try{a=ss(r,this.options);let s=a;if(this.options.strictValidation){let e=kt(a);if(!e.isValid)throw new n(`Invalid agent configuration: ${e.errors.join(`, `)}`)}let c;if(await fs([{name:`beforeCreate`,run:()=>this.lifecycleEvents.beforeCreate?.(s)},{name:`construct`,run:()=>{c=new e(s)}},{name:`initialize`,run:()=>c?ds(c)?.initialize?.():void 0,undo:()=>c?ds(c)?.cleanup?.():void 0},{name:`commit`,run:()=>{if(!c)throw new t(`Agent was not constructed`);this.activeAgents.set(o,c),ls(this.creationStats,i)},undo:()=>{this.activeAgents.delete(o),this.creationStats.activeCount--,this.creationStats.totalCreated--,i?this.creationStats.fromTemplates--:this.creationStats.customConfigured--}},{name:`afterCreate`,run:()=>c?this.lifecycleEvents.afterCreate?.(c,s):void 0}]),this.pendingAgents.delete(o),!c)throw new t(`Agent was not constructed`);return this.logger.info(`Agent created successfully`,{agentId:o,model:a.defaultModel.model,provider:a.defaultModel.provider}),c}catch(e){this.pendingAgents.delete(o);let t=e instanceof Error?e:Error(String(e));throw this.lifecycleEvents.onCreateError&&a&&await this.lifecycleEvents.onCreateError(t,a),this.logger.error(`Failed to create agent`,{error:t.message,model:r.defaultModel?.model,provider:r.defaultModel?.provider,hasTools:!!r.tools?.length}),t}}admit(){if(this.activeAgents.size+this.pendingAgents.size>=this.options.maxConcurrentAgents)throw new t(`Maximum concurrent agents limit reached: ${this.options.maxConcurrentAgents}`);let e=this.options.idFactory(),n=0;for(;this.activeAgents.has(e)||this.pendingAgents.has(e);){if(n+=1,n>16)throw new t(`Agent id factory keeps returning ids that are already in use`);e=this.options.idFactory()}return this.pendingAgents.add(e),e}async createFromTemplate(e,n,r={}){let i=this.agentTemplates.getTemplate(n);if(!i)throw new t(`Template not found: ${n}`);let a=this.applyTemplate(i,r);a.warnings.length>0&&this.logger.warn(`Template application warnings`,{templateId:n,warnings:a.warnings});let o=await this.createAgent(e,a.config,!0);return this.logger.info(`Agent created from template`,{templateId:n,modified:a.modified,warnings:a.warnings.length}),o}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 ds(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 kt(e)}};function hs(e,n,r){if(!e.name||e.name.trim()===``)throw new t(`Module name is required`);if(!e.version||e.version.trim()===``)throw new t(`Module version is required`);let i=e.getModuleType(),a=n.validateTypeDescriptor(i);if(!a.valid)throw new t(`Invalid module type: ${a.errors.join(`, `)}`,{moduleName:e.name,errors:a.errors});a.warnings.length>0&&r.warn(`Module type validation warnings`,{moduleName:e.name,warnings:a.warnings})}async function gs(e,n,r,i){let a=e.getModuleType();if(!a.dependencies||a.dependencies.length===0)return;for(let r of a.dependencies)if(!n.hasType(r))throw new t(`Module '${e.name}' depends on unregistered type '${r}'`,{moduleName:e.name,dependencyType:r});let o=new Set;for(let e of r.values())o.add(e.getModuleType().type);let s=[];for(let e of a.dependencies)o.has(e)||s.push(e);s.length>0&&i.warn(`Module has unmet dependencies`,{moduleName:e.name,missingDependencies:s})}function _s(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 vs(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 ys(){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 bs(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 xs(e,t,n){let r=new Set,i=new Set,a=[],o=[],s=[];for(let r of e){let e=t(r);if(!e){s.push(r);continue}if(e.dependencies)for(let t of e.dependencies)!n(t)&&!s.includes(t)&&s.push(t)}let c=(s,l=[])=>{if(i.has(s)){let e=l.indexOf(s);o.push(l.slice(e).concat([s]));return}if(r.has(s))return;let u=t(s);if(!u)return;i.add(s);let d=[...l,s];if(u.dependencies)for(let t of u.dependencies)(e.includes(t)||n(t))&&c(t,d);i.delete(s),r.add(s),a.push(s)};for(let t of e)r.has(t)||c(t);return{resolved:s.length===0&&o.length===0,order:a,circularDependencies:o,missingDependencies:s}}function Ss(e,t){let n=[],r=[],i=new Map;for(let n of e){let e=t(n);e&&(i.has(e.layer)||i.set(e.layer,[]),i.get(e.layer).push(n))}let a=new Map;for(let n of e){let e=t(n);if(e?.capabilities)for(let t of e.capabilities)a.has(t)||a.set(t,[]),a.get(t).push(n)}for(let[e,t]of Array.from(a.entries()))if(t.length>1)for(let r=0;r<t.length;r++)for(let i=r+1;i<t.length;i++){let a=t[r],o=t[i];a&&o&&n.push({module1:a,module2:o,reason:`Both modules provide capability '${e}'`})}return n.length>0&&(r.push(`Consider using only one module per capability`),r.push(`Check if modules can be configured to avoid conflicts`)),!i.has(`infrastructure`)&&e.length>1&&r.push(`Consider adding infrastructure modules for better foundation`),{compatible:n.length===0,conflicts:n,suggestions:r}}function Cs(e){let t={core:0,storage:0,processing:0,integration:0,interface:0,capability:0},n={infrastructure:0,core:0,application:0,domain:0,presentation:0},r=0,i=0;for(let a of e.values())t[a.category]++,n[a.layer]++,a.dependencies&&a.dependencies.length>0&&r++,a.capabilities&&a.capabilities.length>0&&i++;return{totalTypes:e.size,typesByCategory:t,typesByLayer:n,typesWithDependencies:r,typesWithCapabilities:i}}var ws=class{registeredTypes=new Map;logger;constructor(){this.logger=j(`ModuleDescriptorRegistry`),this.registerBuiltinTypes()}registerType(e){let n=this.validateTypeDescriptor(e);if(!n.valid)throw new t(`Invalid module type descriptor: ${n.errors.join(`, `)}`,{type:e.type,errors:n.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 n=this.findDependentTypes(e);if(n.length>0)throw new t(`Cannot unregister module type '${e}' - it is required by: ${n.join(`, `)}`,{type:e,dependentTypes:n});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 bs(e,e=>this.getType(e))}resolveDependencies(e){return xs(e,e=>this.getType(e),e=>this.hasType(e))}checkCompatibility(e){return Ss(e,e=>this.getType(e))}findDependentTypes(e){let t=[];for(let[n,r]of this.registeredTypes)r.dependencies?.includes(e)&&t.push(n);return t}registerBuiltinTypes(){for(let e of ys())this.registerType(e);this.logger.info(`Built-in module types registered`,{totalTypes:this.registeredTypes.size})}clearAllTypes(){this.registeredTypes.clear(),this.logger.info(`All module types cleared`)}getStats(){return Cs(this.registeredTypes)}};const Ts={REGISTERED:`module.registered`,UNREGISTERED:`module.unregistered`};var Es=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 ws,this.logger=j(`ModuleRegistry`)}async registerModule(e,n={}){if(this.isDisposing)throw new t(`Cannot register modules during disposal`);if(hs(e,this.typeRegistry,this.logger),this.modules.has(e.name))throw new t(`Module with name '${e.name}' is already registered`,{moduleName:e.name});n.validateDependencies!==!1&&await gs(e,this.typeRegistry,this.modules,this.logger),this.modules.set(e.name,e),this.moduleOptions.set(e.name,n.initOptions||{}),this.registrationOrder.push(e.name);let r=e.getModuleType();this.moduleStatuses.set(e.name,{name:e.name,type:r.type,enabled:e.isEnabled(),initialized:!1,hasEventEmitter:!!this.eventEmitter,registrationTime:new Date,dependencies:r.dependencies||[],dependents:[]}),this.moduleStats.set(e.name,{totalExecutions:0,successfulExecutions:0,failedExecutions:0,averageExecutionTime:0,totalExecutionTime:0}),n.autoInitialize&&await this.initializeModule(e.name,n.initTimeout),this.eventEmitter&&await this.eventEmitter.emit(Ts.REGISTERED,{data:{moduleName:e.name,moduleType:r.type},timestamp:new Date})}async unregisterModule(e){let n=this.modules.get(e);if(!n)return!1;let r=_s(e,this.modules);if(r.length>0)throw new t(`Cannot unregister module '${e}' - it is required by: ${r.join(`, `)}`,{moduleName:e,dependents:r});n.isInitialized()&&n.dispose&&await n.dispose(),this.modules.delete(e),this.moduleOptions.delete(e),this.moduleStatuses.delete(e),this.moduleStats.delete(e);let i=this.registrationOrder.indexOf(e);i!==-1&&this.registrationOrder.splice(i,1);let a=this.initializationOrder.indexOf(e);return a!==-1&&this.initializationOrder.splice(a,1),this.eventEmitter&&await this.eventEmitter.emit(Ts.UNREGISTERED,{data:{moduleName:e},timestamp:new Date}),!0}async initializeModule(e,n){let r=this.modules.get(e);if(!r)throw new t(`Module '${e}' not found`);if(r.isInitialized())return;let i=this.moduleOptions.get(e),a=r.initialize(i,this.eventEmitter);if(n&&n>0){let t,r=new Promise((r,i)=>{t=setTimeout(()=>{i(Error(`Module '${e}' initialization timed out after ${n}ms`))},n)});await Promise.race([a.then(e=>(clearTimeout(t),e)),r])}else await a;let o=this.moduleStatuses.get(e);o&&(o.initialized=!0,o.initializationTime=new Date),this.initializationOrder.includes(e)||this.initializationOrder.push(e)}async initializeAllModules(e){let n=Array.from(this.modules.keys());if(n.length===0)return;let r=n.map(e=>this.modules.get(e).getModuleType().type),i=this.typeRegistry.resolveDependencies(r);if(!i.resolved){let e=[];throw i.missingDependencies.length>0&&e.push(`Missing dependencies: ${i.missingDependencies.join(`, `)}`),i.circularDependencies.length>0&&e.push(`Circular dependencies: ${i.circularDependencies.map(e=>e.join(` -> `)).join(`; `)}`),new t(`Cannot initialize modules: ${e.join(`; `)}`,{missingDependencies:i.missingDependencies,circularDependencies:i.circularDependencies.map(e=>e.join(` -> `))})}for(let t of i.order){let r=n.find(e=>this.modules.get(e).getModuleType().type===t);r&&await this.initializeModule(r,e)}}async executeModule(e,n){let r=this.modules.get(e);if(!r)throw new t(`Module '${e}' not found`);if(!r.isInitialized())throw new t(`Module '${e}' is not initialized`);if(!r.isEnabled())throw new t(`Module '${e}' is disabled`);let i=this.moduleStats.get(e),a=Date.now();try{if(!r.execute)throw new t(`Module '${e}' does not support execute()`);let o=await r.execute(n),s=Date.now()-a;i.totalExecutions++,i.successfulExecutions++,i.totalExecutionTime+=s,i.averageExecutionTime=i.totalExecutionTime/i.totalExecutions,i.lastExecutionTime=new Date;let c=this.moduleStatuses.get(e);return c&&(c.lastActivity=new Date),o}catch(e){let t=Date.now()-a;throw i.totalExecutions++,i.failedExecutions++,i.totalExecutionTime+=t,i.averageExecutionTime=i.totalExecutionTime/i.totalExecutions,i.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 vs(this.modules,this.moduleStats)}},Ds=class extends Pr{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=ui(e);let t=e.logging?.enabled===!1?`silent`:e.logging?.level;this.logger=j(`ConversationAgent`,t?{level:t}:{}),this.startTime=Date.now(),Ir(e),this.config={...e,aiProviders:[...e.aiProviders],...e.providerOwnership?{providerOwnership:{...e.providerOwnership}}:{}},this.aiProviders=$o(e),this.tools=di(()=>this.config),this.agentFactory=new ms,this.conversationHistory=new Wn,this.eventEmitter=_i(),this.moduleRegistry=new Es(this.eventEmitter),this.eventService=e.eventService||mr,this.agentEventService=yr(this.eventService,{ownerType:`agent`,ownerId:this.conversationId,ownerPath:vi(this.conversationId,this.config.executionContext)});let n=mi({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,hi(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=[...vi(this.conversationId,this.config.executionContext),{type:`tool`,id:n.executionId??e}];return this.executionService.invokeRuntimeTool(e,t,{...n,baseEventService:this.eventService,eventService:yr(this.eventService,{ownerPath:r,ownerType:`tool`,ownerId:n.executionId??e}),ownerPath:r,ownerType:`tool`,ownerId:n.executionId})}async resume(e){let t={...e,toolResponses:structuredClone(e.toolResponses)};return this.assertNotDestroyed(),this.runQueue.run(t.signal,async()=>{await this.ensureFullyInitialized();let e=await this.executionService.resume(this.conversationId,t,this.config);if(!e.success)throw e.error??Error(`Execution continuation failed`);return e.response})}async resumeToolCalls(e){let t={...e,toolResponses:structuredClone(e.toolResponses)};return this.assertNotDestroyed(),this.runQueue.run(t.signal,async()=>(await this.ensureFullyInitialized(),this.executionService.resumeToolCalls(this.conversationId,t)))}async run(e,t={}){return this.assertNotDestroyed(),this.runQueue.run(t.signal,async()=>{await this.ensureFullyInitialized();try{if(t.output){let n=yn(t.output);return await wi(this.executionDeps(),e,t,n)}return await bi(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=yn(t.output);return yield*Ti(this.executionDeps(),e,t,n)}return yield*xi(this.executionDeps(),e,t)}finally{this.resetEphemeralHistory(),n()}}resetEphemeralHistory(){this.config.retainHistory===!1&&this.clearHistory()}runQueue=new is;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 Di(this.conversationHistory,this.conversationId)}getFullHistory(){return Oi(this.conversationHistory,this.conversationId)}addHistoryEntry(e){ki(this.conversationHistory,this.conversationId,e)}clearHistory(){Ai(this.conversationHistory,this.conversationId)}injectMessage(e,t,n){ji(this.conversationHistory,this.conversationId,e,t,n)}injectRawMessage(e){Mi(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,aiProviders:[...this.config.aiProviders],...this.config.providerOwnership?{providerOwnership:{...this.config.providerOwnership}}:{}}}swapDefaultProvider(e,t,n={}){this.aiProviders.addProvider(e.name,e,n),this.config={...this.config,aiProviders:Object.values(this.aiProviders.getProviders()),providerOwnership:{...this.config.providerOwnership,[e.name]:n.ownership??`owned`}},this.configManager.setModel({provider:e.name,model:t})}getStats(){return ns({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,rs({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 ts({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){gi(this.agentEventService,this.conversationId,this.config.executionContext,e,t)}};const Os=25e3,ks=5e5,As=/^tool-result:[A-Za-z0-9_-]{22,64}$/u,js=Symbol.for(`@robota-sdk/tool-result-admitted`);var Ms=class extends Error{code;constructor(e){super(`Tool result admission failed (${e})`),this.code=e,this.name=`ToolResultAdmissionError`}};function Ns(e){return Object.getOwnPropertyDescriptor(e,js)?.value===!0}function Ps(e){return Object.defineProperty({...e},js,{value:!0})}function Fs(e){if(e.parts?.length&&e.parts.every(e=>e.type===`text`)){let t=e.parts.map(e=>e.type===`text`?e.text:``).join(`
|
|
9
9
|
`);if(e.success&&e.data===t||!e.success&&e.data===void 0&&e.error===t)return t}if(e.parts?.length)return JSON.stringify({success:e.success,data:e.data,error:e.error,parts:e.parts});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 Is(e){return Number.isSafeInteger(e)&&e>0}function Ls(e,t){let n=e.warningChars??1e4,r=e.hardChars??25e3,i=e.repositoryMaxChars??5e5;if(!Is(n)||!Is(r)||!Is(i)||n>=r||r>i||i>5e5)throw new Ms(`invalid-policy`);if(t===void 0)return{warningChars:n,hardChars:r};if(!Is(t))throw new Ms(`invalid-override`);return{warningChars:n,hardChars:Math.max(r,Math.min(t,i))}}async function Rs(e,t,n={},r){let{warningChars:i,hardChars:a}=Ls(n,r),o=Fs(t),s=o.length;if(s>i&&n.onWarning?.({toolName:e,resultChars:s,warningChars:i}),s>a){if(!n.spillStore)throw new Ms(`spill-unavailable`);let e;try{e=(await n.spillStore.write(o)).reference}catch{throw new Ms(`spill-write-failed`)}if(!As.test(e)||e.length>a)throw new Ms(`invalid-reference`);let r=t.view?{view:t.view}:{};return Ps(t.success?{success:!0,data:e,...r}:{success:!1,error:`Tool failure details: ${e}`,...r})}return Ps(t)}const zs={safe:`plan`,moderate:`default`,full:`acceptEdits`},Bs=`inherit-allowlist`;function Vs(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===`
|
|
10
10
|
`||(r===`<`||r===`>`)&&i===`(`)return!0;if(r===`&`){let t=e[n-1];if(t!==`>`&&t!==`<`&&i!==`>`)return!0}}return!1}function Hs(e){let t={segments:[],current:``,quote:void 0,substitutionDepth:0};for(let n=0;n<e.length;n+=1){let r=Ws(t,e,n);if(r!==void 0){n=r;continue}let i=Gs(t,e,n);if(i!==void 0){n=i;continue}if(Ks(t,e[n]))continue;let a=qs(t,e,n);if(a!==void 0){n=a;continue}t.current+=e[n]}return Us(t),t.segments}function Us(e){let t=e.current.trim();t!==``&&e.segments.push(t),e.current=``}function Ws(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 Gs(e,t,n){let r=t[n];if(r==="`")return Us(e),n;if(r===`$`&&t[n+1]===`(`)return Us(e),e.substitutionDepth+=1,n+1}function Ks(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 qs(e,t,n){let r=t[n];if((r===`<`||r===`>`)&&t[n+1]===`(`)return Us(e),e.substitutionDepth+=1,n+1;if(r===`)`&&e.substitutionDepth>0)return Us(e),--e.substitutionDepth,n;if(r===`;`||r===`|`||r===`
|
|
11
|
-
`||r===`&`&&Js(t,n))return Us(e),n}function Js(e,t){let n=e[t-1];return n!==`>`&&n!==`<`&&e[t+1]!==`>`}const Ys=/[.+^${}()|[\]\\]/g;function Xs(e){let t=e.replace(Ys,`\\$&`).replace(/\*\*/g,`.+`).replace(/\*/g,`.*`);return RegExp(`^${t}$`)}function Zs(e,t,n){let r=Xs(e);return n===`deny`?r.test(t)||Hs(t).some(e=>r.test(e))?`match`:`no-match`:r.test(t)?e.includes(`*`)&&Vs(t)?`no-match`:`match`:`no-match`}function Qs(e){let t=e.replace(/\*\*(?:\/\*\*)+/g,`**`).split(/(\/\*\*\/|\/\*\*$|^\*\*\/|\*\*)/).map(e=>e===`/**/`?`(?:/.*)?/`:e===`/**`?`(?:/.*)?`:e===`**/`?`(?:.*/)?`:e===`**`?`.*`:e.replace(Ys,`\\$&`).replace(/\*/g,`[^/]*`).replace(/\uE000/g,`\\*`)).join(``);return RegExp(`^${t}$`)}function $s(e){return e.startsWith(`/`)||/^[A-Za-z]:(?=\/|$)/.test(e)}function ec(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 tc(e,t){let n=ec(e),r=ec(t);return $s(n)&&!$s(r)?`unevaluable`:Qs(n).test(r)?`match`:`no-match`}const nc=/^(\*|[a-z][a-z0-9+.-]*):\/\/(\[[0-9a-fA-F:.]+\]|[^/\\:?#@[\]]+)(?::(\d+|\*))?(\/[^?#]*)?$/i,rc=new Set([`http`,`https`,`ws`,`wss`,`ftp`]),ic={http:`80`,https:`443`,ws:`80`,wss:`443`,ftp:`21`};function ac(e){return e.replace(/\.$/,``).toLowerCase()}function oc(e){try{let t=new URL(`http://${e}/`).hostname;return t===``||t.includes(`.`)?null:t}catch{return null}}function sc(e,t=!1){let n=ac(e).replace(/\*\*(?:\.\*\*)+/g,`**`).split(`.`),r=[],i=`[^.]+(?:\\.[^.]+)*`;for(let[e,a]of n.entries()){let o=e===0,s=e===n.length-1;if(a===`**`){o&&s?r.push(i):s?r.push(`(?:\\.${i})?`):r.push(`${o?``:`\\.`}(?:${i}\\.)?`);continue}let c=!o&&n[e-1]===`**`,l=o||c?``:`\\.`;if(a===`*`)r.push(`${l}${t&&!o?`[^.]*`:i}`);else if(a.includes(`**`))return null;else if(a.includes(`*`))r.push(`${l}${a.replace(Ys,`\\$&`).replace(/\*/g,`[^.]*`)}`);else{let e=oc(a);if(e===null)return null;r.push(`${l}${e.replace(Ys,`\\$&`)}`)}}return RegExp(`^${r.join(``)}$`)}function cc(e){try{let t=e.split(`/`).map(e=>decodeURIComponent(e));return t.some(e=>e.includes(`/`))?null:t.join(`/`)}catch{return null}}function lc(e){let t;try{t=new URL(e)}catch{return null}let n=t.protocol.slice(0,-1).toLowerCase();return!rc.has(n)||t.hostname===``||t.username!==``||t.password!==``?null:t}function uc(e,t,n=!1){if(e.includes(`*`)){let r=sc(e,n);return r===null?`unevaluable`:r.test(t)?`match`:`no-match`}let r;try{r=new URL(`http://${e}/`).hostname}catch{return`unevaluable`}return ac(r)===t?`match`:`no-match`}function dc(e,t,n){return e===void 0?t.port===``:e===`*`||e===(t.port===``?ic[n]:t.port)}function fc(e,t){let n=cc(t),r=cc(e.replace(/%2a/gi,``));return n===null||r===null?`unevaluable`:Qs(r).test(n)?`match`:`no-match`}function pc(e,t){let n=nc.exec(e);if(n===null)return`unevaluable`;let[,r,i,a,o]=n,s=lc(t);if(s===null)return`unevaluable`;let c=s.protocol.slice(0,-1).toLowerCase();if(r!==`*`&&r.toLowerCase()!==c)return`no-match`;let l=uc(i,ac(s.hostname));return l===`match`?dc(a,s,c)?o===void 0?`match`:fc(o,s.pathname):`no-match`:l}function mc(e,t){if(!e.startsWith(`domain:`))return pc(e,t);let n=/^domain:([^/\\:?#@[\]\s]+)$/.exec(e);if(n===null)return`unevaluable`;let r=ac(n[1]);if(r.includes(`**`)||r.split(`.`).some(e=>e===``))return`unevaluable`;let i=lc(t);return i===null||i.protocol!==`http:`&&i.protocol!==`https:`?`unevaluable`:uc(r,ac(i.hostname),!0)}const hc={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`}},gc={plan:`deny`,default:`approve`,acceptEdits:`approve`,bypassPermissions:`auto`,auto:`approve`},_c=[`.git`,`.claude`,`.agents`],vc=[`.mcp.json`,`.gitconfig`,`.npmrc`,`.bashrc`,`.bash_profile`,`.bash_login`,`.zshrc`,`.zshenv`,`.zprofile`,`.profile`];function yc(e){return e.replace(/\\/g,`/`).split(`/`).filter(e=>e!==``&&e!==`.`)}function bc(e){let t=[];for(let n of yc(e))n===`..`&&t.length>0&&t[t.length-1]!==`..`?t.pop():t.push(n);return t}function xc(e,t={}){let n=t.pathProtection,r=wc.exec(e),i=r!==null&&t.homeDirectory!==void 0?`${t.homeDirectory}/${r[1]??``}`:e,a=i.startsWith(`/`)?Sc(i):t.cwd===void 0?void 0:Sc(`${t.cwd}/${i}`);if(a!==void 0&&n?.protectedPaths.some(e=>{let t=Sc(e);return a===t||a.startsWith(`${t}/`)}))return!0;let o=bc(i),s=o[o.length-1];if(s!==void 0&&vc.includes(s))return!0;let c=[..._c,...n?.protectedDirectoryNames??[]],l=[`.claude/worktrees`,...n?.writableWorktreeContainers??[]].map(bc);for(let e=0;e<o.length;e+=1){if(!c.includes(o[e]))continue;let t=l.find(t=>t.length>0&&t.every((t,n)=>o[e+n]===t)&&o[e+t.length]!==void 0);if(t!==void 0){e+=t.length;continue}return!0}return!1}function Sc(e){let t=[];for(let n of yc(e))n===`..`?t.pop():t.push(n);return`/${t.join(`/`)}`}function Cc(e){return e.replace(/^(['"])(.*)\1$/,`$2`)}const wc=/^(?:~|\$HOME|\$\{HOME\})(?=\/|$)(.*)$/;function Tc(e,t){let n=Cc(e),r=wc.exec(n),i;if(r!==null){let e=r[1]??``;if(t.homeDirectory===void 0)return e.replace(/\/+/g,``)===``;i=Sc(`${t.homeDirectory}/${e}`)}else if(n===``||n.startsWith(`$`))return!1;else if(n.startsWith(`/`))i=Sc(n);else{if(t.cwd===void 0)return!1;i=Sc(`${t.cwd}/${n}`)}if(yc(i).length<=1||t.homeDirectory!==void 0&&i===Sc(t.homeDirectory))return!0;if(t.cwd!==void 0){let e=Sc(t.cwd);if(e===i||e.startsWith(`${i}/`))return!0}return!1}const Ec=new Set([`rm`,`rmdir`]),Dc=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 Oc(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=Dc.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 kc(e,t){return Hs(e).some(e=>{let n=e.split(/\s+/).filter(e=>e!==``),r=Oc(n),i=n[r];if(i===void 0)return!1;let a=i.slice(i.lastIndexOf(`/`)+1);if(!Ec.has(a))return!1;let o=!1;return n.slice(r+1).some(e=>!o&&e===`--`?(o=!0,!1):!o&&e.startsWith(`-`)?!1:Tc(e,t))})}const Ac=new Set([`ls`,`cat`,`echo`,`pwd`,`head`,`tail`,`grep`,`wc`,`which`,`stat`,`du`,`cd`]),jc=new Set([`-exec`,`-execdir`,`-ok`,`-okdir`,`-delete`,`-fprint`,`-fprint0`,`-fprintf`,`-fls`]),Mc={ls:`aAlhtrSR1dFGinpsucCgmoQvx`,cat:`nbsvetAE`,head:`nqvc`,tail:`nqvcfF`,grep:`rinlLvcwxEFGPHhoqsABCmz`,wc:`lwcmL`,stat:`cftx`,du:`hsacdkmx`,which:`a`,pwd:`LP`,cd:`LP`},Nc=/^--?[A-Za-z0-9-]*(file|from|contents)(=|$)/,Pc=[`--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 Fc(e){if(!e.startsWith(`--`)||e.length<=2)return!1;let t=e.split(`=`,1)[0];return Pc.some(e=>e.startsWith(t))}function Ic(e,t){if(Jc(t).some(e=>Nc.test(e.text)||Fc(e.text)))return!0;if(e===`find`)return Jc(t).some(e=>e.text===`-L`||e.text===`-follow`);let n=Mc[e];return n!==void 0&&Jc(t).some(({text:e})=>e.startsWith(`--`)||!/^-[A-Za-z]/.test(e)?!1:[...e.slice(1)].some(e=>!/\d/.test(e)&&!n.includes(e)))}const Lc=new Set([`status`,`log`,`diff`,`show`,`rev-parse`,`ls-files`,`describe`,`branch`,`remote`]),Rc=new Set([`-l`,`--list`,`--show-current`,`--merged`,`--no-merged`,`--contains`,`--no-contains`,`--points-at`]),zc=new Set([`-a`,`--all`,`-r`,`--remotes`,`-v`,`-vv`,`--verbose`,`--color`,`--no-color`]),Bc=new Set([`/dev/null`]),Vc=/[A-Za-z0-9_./:=@+,*?[\]~-]/,Hc=new Set([`$`,"`",`\\`,`!`]),Uc=new Set([`*`,`?`,`[`]);function Wc(e){return/(^|[=,:])[/~]/.test(e)||/^-[A-Za-z]+[/~]/.test(e)||/(^|[/=,:]|^-[A-Za-z]+)\.\.(\/|$)/.test(e)||/(^|[=,])[A-Za-z][A-Za-z0-9]*:/.test(e)||Gc(e)}function Gc(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 Kc(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 qc(e){let t=[],n=``,r=!1,i=!1,a,o,s=!1,c=()=>{i&&=(o===`output`?(!Bc.has(n)||r)&&(s=!0):o===`duplicate`?/^(\d+|-)$/.test(n)||(s=!0):o===`input`?(r||Wc(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:Hc.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(!Vc.test(l)){s=!0;break}Uc.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 Jc(e){let t=e.findIndex(e=>e.text===`--`);return(t<0?e:e.slice(0,t)).filter(e=>e.text.startsWith(`-`))}function Yc(e){return e.every(e=>!e.expands&&!jc.has(e.text))}function Xc(e){let t=e.filter(e=>e.text.startsWith(`-`)),n=t.some(e=>Rc.has(e.text));return t.every(e=>Rc.has(e.text)||zc.has(e.text))&&(n||t.length===e.length)}function Zc(e){let[t,...n]=e[0]?.text===`--no-pager`?e.slice(1):e;return t===void 0||t.expands||!Lc.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`?Xc(n):t.text!==`remote`||n.every(e=>e.text===`-v`||e.text===`--verbose`)}function Qc(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=>Wc(e.text))||Ic(t.text,n)?!1:t.text===`cd`?n.length===1&&n[0].text!==`-`&&!n[0].expands:Ac.has(t.text)?!0:t.text===`find`?Yc(n):t.text===`git`&&Zc(n)}const $c=new Set([`echo`,`which`,`git`]);function el(e,t){let n;for(let[r,...i]of e)if(!$c.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 tl(e,t={}){if(t.otherDirectory===!0||e.length>1e4||Kc(e)||/[^\t\n\x20-\x7e]/.test(e))return!1;let n=Hs(e);if(n.length===0)return!1;let r=n.map(qc);if(r.some(e=>e.refused||!Qc(e.words)))return!1;let i=r.map(e=>e.words[0].text);return i.includes(`git`)&&i.includes(`cd`)?!1:el(r.map(e=>e.words),t.resolveInWorkspace)}function nl(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 rl(e,t){Q.set(e,{...Q.get(e),...t})}function il(e){return Q.get(e)??{}}function al(e,t){let n=[t,...Q.get(t)?.aliases??[]];if(!e.includes(`*`))return n.includes(e);let r=Xs(e);return n.some(e=>r.test(e))}function ol(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 sl(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`:Xs(e.value).test(String(n))?`match`:`no-match`}function cl(e,t){return t.some(t=>{let n=nl(t);return(n.argPattern===void 0||n.argPattern===`*`||n.argPattern===`**`)&&al(n.toolName,e)})}function ll(e){return Q.get(e)?.argument?.key}function ul(e,t){let n=ll(e);if(n===void 0)return;let r=t[n];return typeof r==`string`?r:void 0}function dl(e,t,n,r=`allow`){return n.some(n=>pl(e,t,n,r)===`match`)}function fl(e,t,n){return n.some(n=>pl(e,t,n,`deny`)===`unevaluable`)}function pl(e,t,n,r){let i=nl(n);if(!al(i.toolName,e))return`no-match`;if(i.argPattern===void 0||i.argPattern===`*`||i.argPattern===`**`)return`match`;let a=ol(e,i.argPattern);if(a===`primary`)return`unevaluable`;if(a!==void 0)return r===`deny`?sl(a,t):`no-match`;let o=Q.get(e)?.argument;if(o===void 0)return`unevaluable`;let s=ul(e,t);if(s===void 0)return`no-match`;switch(o.kind){case`url`:return e===`WebFetch`?mc(i.argPattern,s):pc(i.argPattern,s);case`path`:return tc(i.argPattern,s);case`command`:return Zs(i.argPattern,s,r);case`text`:return Xs(i.argPattern).test(s)?`match`:`no-match`;default:{let e=o.kind;throw Error(`unknown argument kind: ${String(e)}`)}}}function ml(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`?kc(a,n):i.kind===`path`&&r?.riskClass===`modify`&&xc(a,n):!1}function hl(e,t,n,r){return dl(e,t,n,`deny`)||fl(e,t,n)||ml(e,t,r)}function gl(e,t,n={},r={}){return fl(e,t,n.deny??[])||hl(e,t,n.ask??[],r)}const _l=[`workingDirectory`,`cwd`];function vl(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`&&tl(i,{otherDirectory:_l.some(e=>t[e]!==void 0),...n.resolveInWorkspace===void 0?{}:{resolveInWorkspace:n.resolveInWorkspace}})?`inspect`:r.riskClass}function yl(e,t,n,r={},i={}){let{allow:a=[],deny:o=[],ask:s=[]}=r,c=vl(e,t,i),l=n===`plan`&&c!==`inspect`?`deny`:`approve`;return dl(e,t,o,`deny`)||i.ceiling!==void 0&&!dl(e,t,i.ceiling)||Q.get(e)?.repliesToPeer===!0&&i.peerTurn!==!0||Q.get(e)?.notInPeerTurn===!0&&i.peerTurn===!0?`deny`:fl(e,t,o)?n===`plan`?`deny`:`approve`:hl(e,t,s,i)||i.askAll===!0?l:n===`bypassPermissions`||dl(e,t,a)||i.sandboxAutoApproved===!0&&c===`execute`&&(n==="default"||n===`acceptEdits`||n===`auto`)?`auto`:c===void 0?gc[n]:hc[n][c]}function bl(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 xl=/^[A-Za-z_]\w*:(?!\/\/)/;function Sl(e){return e.slice(0,e.indexOf(`*`)).includes(`__`)}function Cl(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}=nl(n);if(r===``)return`names no tool`;if(t===`allow`&&r.includes(`*`)&&!Sl(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`&&xl.test(i)?`matches a named parameter, which only deny and ask rules may do`:void 0;let a=ol(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=il(r);if(!(o.parameters===void 0&&xl.test(i)&&ol(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`&&(r===`WebFetch`?mc:pc)(i,`https://probe.invalid/`)===`unevaluable`)return`does not fit the URL pattern grammar scheme://host[:port][/path]${r===`WebFetch`?` or domain:hostname`:``} that "${r}" is matched by`}}function wl(e,t=`deny`){let n=[];for(let r of e){let e=Cl(r,t);e!==void 0&&n.push({pattern:r,reason:e})}return n}function Tl(e){let t=[];for(let n of e){let{toolName:e,argPattern:r}=nl(n.trim());if(r===void 0||e.includes(`*`))continue;let i=il(e),a=ol(e,r);if(a===void 0&&i.parameters!==void 0&&i.argument?.kind!==`url`&&xl.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=il(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 El(e){return(e??[]).map(e=>`${e}(*)`)}function Dl(e,t){let n=El(t.allowedTools),r=wl(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,...El(t.deniedTools)])]}}const Ol=[`Bash`,`Shell`,`BackgroundProcess`],kl=[`Agent`],Al=[...Ol,...kl,`ExecuteCommand`,`Computer`],jl=`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(`.`),Ml=[`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(` `)),Nl=new Set([`run`,`run-script`,`exec`,`dlx`,`x`,`--`]);function Pl(e){return(e.split(/[\\/]/).pop()??e).replace(/(\.exe)?$/i,``).replace(/[\d.]+$/,``)}function Fl(e,t){if(e.length===0)return!0;let n=(e,n,r)=>t&&r?e.startsWith(n):e===n,r=Pl(e[0]);if(jl.some(t=>n(t,r,e.length===1)))return!0;for(let i of Ml){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(`-`)||Nl.has(o[0]));)o=o.slice(1);return o.length===0||Fl(o,t)}return!1}function Il(e){let t=e.trim();if(!t.includes(`*`))return!1;let n=t.slice(0,t.indexOf(`*`));return Fl(n.trim().split(/\s+/).filter(e=>e.length>0),n.length>0&&!/\s$/.test(n))}function Ll(e){let{toolName:t,argPattern:n}=nl(e),r=e=>e.some(e=>al(t,e));return r(kl)?!0:t.includes(`*`)?r(Al):Al.includes(t)||il(t).riskClass===`execute`?n===void 0||n.trim()===`*`||Ol.includes(t)&&Il(n):!1}function Rl(e){return e.filter(e=>!Ll(e))}const zl=1e6,Bl={"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}},Vl=[{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:/gemini-2/i,price:{inputPerMillion:.1,outputPerMillion:.4}},{pattern:/gemini-1/i,price:{inputPerMillion:1.25,outputPerMillion:5}}];function Hl(e){let t=Object.hasOwn(Bl,e)?Bl[e]:void 0;if(t)return t;for(let{pattern:t,price:n}of Vl)if(t.test(e))return n}function Ul(e,t,n){let r=Hl(e);if(r)return t/zl*r.inputPerMillion+n/zl*r.outputPerMillion}function Wl(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 Gl(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 Kl(){let[{CommandExecutor:e},{HttpExecutor:t}]=await Promise.all([import(`./command-executor-D_UBZHxh-CVZipoOV.js`).then(e=>e.t).then(e=>e.n),import(`./http-executor-ADn4locH-D-8crzF8.js`).then(e=>e.t).then(e=>e.n)]);return[new e,new t]}async function ql(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 Kl(),u=new Map;for(let e of l)u.set(e.type,e);let d=[],f=Gl(n),p=-1,m,h;for(let e of c){if(!Wl(e,f))continue;let r=e.env?{...n,env:{...n.env,...e.env}}:n;for(let n of e.hooks){let e=u.get(n.type);if(!e){a.add(n.type);continue}let c=n.type===`command`&&i!==void 0?await e.execute(n,r,i):await e.execute(n,r);if(c.outcome===`deny`)return{blocked:!0,reason:c.reason||`Blocked by hook`,stdout:d.join(`
|
|
11
|
+
`||r===`&`&&Js(t,n))return Us(e),n}function Js(e,t){let n=e[t-1];return n!==`>`&&n!==`<`&&e[t+1]!==`>`}const Ys=/[.+^${}()|[\]\\]/g;function Xs(e,t){let n,r=``;for(let i of e){if(i===n){n=void 0;continue}if(n===void 0&&(i===`'`||i===`"`)){n=i;continue}if(n!==void 0&&(i===` `||i===` `))return;if(n===void 0&&(i===` `||i===` `)){r.endsWith(` `)||(r+=` `);continue}if(/[^\x20-\x7e]|[$`\\!%~<>()[\]{}?#]/u.test(i)||!t&&i===`*`)return;r+=i}return n===void 0?r:void 0}function Zs(e){let t=e.replace(Ys,`\\$&`).replace(/\*\*/g,`.+`).replace(/\*/g,`.*`);return RegExp(`^${t}$`)}function Qs(e,t,n){let r=Zs(e);if(n===`deny`){if(r.test(t))return`match`;let n=Hs(t);if(n.some(e=>r.test(e)))return`match`;let i=Xs(e,!0);if(i===void 0)return`unevaluable`;let a=Zs(i);for(let e of n){let t=Xs(e,!1);if(t!==void 0&&a.test(t))return`match`}return`unevaluable`}return r.test(t)?e.includes(`*`)&&Vs(t)?`no-match`:`match`:`no-match`}function $s(e){let t=e.replace(/\*\*(?:\/\*\*)+/g,`**`).split(/(\/\*\*\/|\/\*\*$|^\*\*\/|\*\*)/).map(e=>e===`/**/`?`(?:/.*)?/`:e===`/**`?`(?:/.*)?`:e===`**/`?`(?:.*/)?`:e===`**`?`.*`:e.replace(Ys,`\\$&`).replace(/\*/g,`[^/]*`).replace(/\uE000/g,`\\*`)).join(``);return RegExp(`^${t}$`)}function ec(e){return e.startsWith(`/`)||/^[A-Za-z]:(?=\/|$)/.test(e)}function tc(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 nc(e,t){let n=tc(e),r=tc(t);return ec(n)&&!ec(r)?`unevaluable`:$s(n).test(r)?`match`:`no-match`}const rc=/^(\*|[a-z][a-z0-9+.-]*):\/\/(\[[0-9a-fA-F:.]+\]|[^/\\:?#@[\]]+)(?::(\d+|\*))?(\/[^?#]*)?$/i,ic=new Set([`http`,`https`,`ws`,`wss`,`ftp`]),ac={http:`80`,https:`443`,ws:`80`,wss:`443`,ftp:`21`};function oc(e){return e.replace(/\.$/,``).toLowerCase()}function sc(e){try{let t=new URL(`http://${e}/`).hostname;return t===``||t.includes(`.`)?null:t}catch{return null}}function cc(e,t=!1){let n=oc(e).replace(/\*\*(?:\.\*\*)+/g,`**`).split(`.`),r=[],i=`[^.]+(?:\\.[^.]+)*`;for(let[e,a]of n.entries()){let o=e===0,s=e===n.length-1;if(a===`**`){o&&s?r.push(i):s?r.push(`(?:\\.${i})?`):r.push(`${o?``:`\\.`}(?:${i}\\.)?`);continue}let c=!o&&n[e-1]===`**`,l=o||c?``:`\\.`;if(a===`*`)r.push(`${l}${t&&!o?`[^.]*`:i}`);else if(a.includes(`**`))return null;else if(a.includes(`*`))r.push(`${l}${a.replace(Ys,`\\$&`).replace(/\*/g,`[^.]*`)}`);else{let e=sc(a);if(e===null)return null;r.push(`${l}${e.replace(Ys,`\\$&`)}`)}}return RegExp(`^${r.join(``)}$`)}function lc(e){try{let t=e.split(`/`).map(e=>decodeURIComponent(e));return t.some(e=>e.includes(`/`))?null:t.join(`/`)}catch{return null}}function uc(e){let t;try{t=new URL(e)}catch{return null}let n=t.protocol.slice(0,-1).toLowerCase();return!ic.has(n)||t.hostname===``||t.username!==``||t.password!==``?null:t}function dc(e,t,n=!1){if(e.includes(`*`)){let r=cc(e,n);return r===null?`unevaluable`:r.test(t)?`match`:`no-match`}let r;try{r=new URL(`http://${e}/`).hostname}catch{return`unevaluable`}return oc(r)===t?`match`:`no-match`}function fc(e,t,n){return e===void 0?t.port===``:e===`*`||e===(t.port===``?ac[n]:t.port)}function pc(e,t){let n=lc(t),r=lc(e.replace(/%2a/gi,``));return n===null||r===null?`unevaluable`:$s(r).test(n)?`match`:`no-match`}function mc(e,t){let n=rc.exec(e);if(n===null)return`unevaluable`;let[,r,i,a,o]=n,s=uc(t);if(s===null)return`unevaluable`;let c=s.protocol.slice(0,-1).toLowerCase();if(r!==`*`&&r.toLowerCase()!==c)return`no-match`;let l=dc(i,oc(s.hostname));return l===`match`?fc(a,s,c)?o===void 0?`match`:pc(o,s.pathname):`no-match`:l}function hc(e,t){if(!e.startsWith(`domain:`))return mc(e,t);let n=/^domain:([^/\\:?#@[\]\s]+)$/.exec(e);if(n===null)return`unevaluable`;let r=oc(n[1]);if(r.includes(`**`)||r.split(`.`).some(e=>e===``))return`unevaluable`;let i=uc(t);return i===null||i.protocol!==`http:`&&i.protocol!==`https:`?`unevaluable`:dc(r,oc(i.hostname),!0)}const gc={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`}},_c={plan:`deny`,default:`approve`,acceptEdits:`approve`,bypassPermissions:`auto`,auto:`approve`},vc=[`.git`,`.claude`,`.agents`],yc=[`.mcp.json`,`.gitconfig`,`.npmrc`,`.bashrc`,`.bash_profile`,`.bash_login`,`.zshrc`,`.zshenv`,`.zprofile`,`.profile`];function bc(e){return e.replace(/\\/g,`/`).split(`/`).filter(e=>e!==``&&e!==`.`)}function xc(e){let t=[];for(let n of bc(e))n===`..`&&t.length>0&&t[t.length-1]!==`..`?t.pop():t.push(n);return t}function Sc(e,t={}){let n=t.pathProtection,r=Tc.exec(e),i=r!==null&&t.homeDirectory!==void 0?`${t.homeDirectory}/${r[1]??``}`:e,a=i.startsWith(`/`)?Cc(i):t.cwd===void 0?void 0:Cc(`${t.cwd}/${i}`);if(a!==void 0&&n?.protectedPaths.some(e=>{let t=Cc(e);return a===t||a.startsWith(`${t}/`)}))return!0;let o=xc(i),s=o[o.length-1];if(s!==void 0&&yc.includes(s))return!0;let c=[...vc,...n?.protectedDirectoryNames??[]],l=[`.claude/worktrees`,...n?.writableWorktreeContainers??[]].map(xc);for(let e=0;e<o.length;e+=1){if(!c.includes(o[e]))continue;let t=l.find(t=>t.length>0&&t.every((t,n)=>o[e+n]===t)&&o[e+t.length]!==void 0);if(t!==void 0){e+=t.length;continue}return!0}return!1}function Cc(e){let t=[];for(let n of bc(e))n===`..`?t.pop():t.push(n);return`/${t.join(`/`)}`}function wc(e){return e.replace(/^(['"])(.*)\1$/,`$2`)}const Tc=/^(?:~|\$HOME|\$\{HOME\})(?=\/|$)(.*)$/;function Ec(e,t){let n=wc(e),r=Tc.exec(n),i;if(r!==null){let e=r[1]??``;if(t.homeDirectory===void 0)return e.replace(/\/+/g,``)===``;i=Cc(`${t.homeDirectory}/${e}`)}else if(n===``||n.startsWith(`$`))return!1;else if(n.startsWith(`/`))i=Cc(n);else{if(t.cwd===void 0)return!1;i=Cc(`${t.cwd}/${n}`)}if(bc(i).length<=1||t.homeDirectory!==void 0&&i===Cc(t.homeDirectory))return!0;if(t.cwd!==void 0){let e=Cc(t.cwd);if(e===i||e.startsWith(`${i}/`))return!0}return!1}const Dc=new Set([`rm`,`rmdir`]),Oc=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 kc(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=Oc.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 Ac(e,t){return Hs(e).some(e=>{let n=e.split(/\s+/).filter(e=>e!==``),r=kc(n),i=n[r];if(i===void 0)return!1;let a=i.slice(i.lastIndexOf(`/`)+1);if(!Dc.has(a))return!1;let o=!1;return n.slice(r+1).some(e=>!o&&e===`--`?(o=!0,!1):!o&&e.startsWith(`-`)?!1:Ec(e,t))})}const jc=new Set([`ls`,`cat`,`echo`,`pwd`,`head`,`tail`,`grep`,`wc`,`which`,`stat`,`du`,`cd`]),Mc=new Set([`-exec`,`-execdir`,`-ok`,`-okdir`,`-delete`,`-fprint`,`-fprint0`,`-fprintf`,`-fls`]),Nc={ls:`aAlhtrSR1dFGinpsucCgmoQvx`,cat:`nbsvetAE`,head:`nqvc`,tail:`nqvcfF`,grep:`rinlLvcwxEFGPHhoqsABCmz`,wc:`lwcmL`,stat:`cftx`,du:`hsacdkmx`,which:`a`,pwd:`LP`,cd:`LP`},Pc=/^--?[A-Za-z0-9-]*(file|from|contents)(=|$)/,Fc=[`--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 Ic(e){if(!e.startsWith(`--`)||e.length<=2)return!1;let t=e.split(`=`,1)[0];return Fc.some(e=>e.startsWith(t))}function Lc(e,t){if(Yc(t).some(e=>Pc.test(e.text)||Ic(e.text)))return!0;if(e===`find`)return Yc(t).some(e=>e.text===`-L`||e.text===`-follow`);let n=Nc[e];return n!==void 0&&Yc(t).some(({text:e})=>e.startsWith(`--`)||!/^-[A-Za-z]/.test(e)?!1:[...e.slice(1)].some(e=>!/\d/.test(e)&&!n.includes(e)))}const Rc=new Set([`status`,`log`,`diff`,`show`,`rev-parse`,`ls-files`,`describe`,`branch`,`remote`]),zc=new Set([`-l`,`--list`,`--show-current`,`--merged`,`--no-merged`,`--contains`,`--no-contains`,`--points-at`]),Bc=new Set([`-a`,`--all`,`-r`,`--remotes`,`-v`,`-vv`,`--verbose`,`--color`,`--no-color`]),Vc=new Set([`/dev/null`]),Hc=/[A-Za-z0-9_./:=@+,*?[\]~-]/,Uc=new Set([`$`,"`",`\\`,`!`]),Wc=new Set([`*`,`?`,`[`]);function Gc(e){return/(^|[=,:])[/~]/.test(e)||/^-[A-Za-z]+[/~]/.test(e)||/(^|[/=,:]|^-[A-Za-z]+)\.\.(\/|$)/.test(e)||/(^|[=,])[A-Za-z][A-Za-z0-9]*:/.test(e)||Kc(e)}function Kc(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 qc(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 Jc(e){let t=[],n=``,r=!1,i=!1,a,o,s=!1,c=()=>{i&&=(o===`output`?(!Vc.has(n)||r)&&(s=!0):o===`duplicate`?/^(\d+|-)$/.test(n)||(s=!0):o===`input`?(r||Gc(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:Uc.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(!Hc.test(l)){s=!0;break}Wc.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 Yc(e){let t=e.findIndex(e=>e.text===`--`);return(t<0?e:e.slice(0,t)).filter(e=>e.text.startsWith(`-`))}function Xc(e){return e.every(e=>!e.expands&&!Mc.has(e.text))}function Zc(e){let t=e.filter(e=>e.text.startsWith(`-`)),n=t.some(e=>zc.has(e.text));return t.every(e=>zc.has(e.text)||Bc.has(e.text))&&(n||t.length===e.length)}function Qc(e){let[t,...n]=e[0]?.text===`--no-pager`?e.slice(1):e;return t===void 0||t.expands||!Rc.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`?Zc(n):t.text!==`remote`||n.every(e=>e.text===`-v`||e.text===`--verbose`)}function $c(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=>Gc(e.text))||Lc(t.text,n)?!1:t.text===`cd`?n.length===1&&n[0].text!==`-`&&!n[0].expands:jc.has(t.text)?!0:t.text===`find`?Xc(n):t.text===`git`&&Qc(n)}const el=new Set([`echo`,`which`,`git`]);function tl(e,t){let n;for(let[r,...i]of e)if(!el.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 nl(e,t={}){if(t.otherDirectory===!0||e.length>1e4||qc(e)||/[^\t\n\x20-\x7e]/.test(e))return!1;let n=Hs(e);if(n.length===0)return!1;let r=n.map(Jc);if(r.some(e=>e.refused||!$c(e.words)))return!1;let i=r.map(e=>e.words[0].text);return i.includes(`git`)&&i.includes(`cd`)?!1:tl(r.map(e=>e.words),t.resolveInWorkspace)}function rl(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 il(e,t){Q.set(e,{...Q.get(e),...t})}function al(e){return Q.get(e)??{}}function ol(e,t){let n=[t,...Q.get(t)?.aliases??[]];if(!e.includes(`*`))return n.includes(e);let r=Zs(e);return n.some(e=>r.test(e))}function sl(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 cl(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`:Zs(e.value).test(String(n))?`match`:`no-match`}function ll(e,t){return t.some(t=>{let n=rl(t);return(n.argPattern===void 0||n.argPattern===`*`||n.argPattern===`**`)&&ol(n.toolName,e)})}function ul(e){return Q.get(e)?.argument?.key}function dl(e,t){let n=ul(e);if(n===void 0)return;let r=t[n];return typeof r==`string`?r:void 0}function fl(e,t,n,r=`allow`){return n.some(n=>ml(e,t,n,r)===`match`)}function pl(e,t,n){return n.some(n=>ml(e,t,n,`deny`)===`unevaluable`)}function ml(e,t,n,r){let i=rl(n);if(!ol(i.toolName,e))return`no-match`;if(i.argPattern===void 0||i.argPattern===`*`||i.argPattern===`**`)return`match`;let a=sl(e,i.argPattern);if(a===`primary`)return`unevaluable`;if(a!==void 0)return r===`deny`?cl(a,t):`no-match`;let o=Q.get(e)?.argument;if(o===void 0)return`unevaluable`;let s=dl(e,t);if(s===void 0)return`no-match`;switch(o.kind){case`url`:return e===`WebFetch`?hc(i.argPattern,s):mc(i.argPattern,s);case`path`:return nc(i.argPattern,s);case`command`:return Qs(i.argPattern,s,r);case`text`:return Zs(i.argPattern).test(s)?`match`:`no-match`;default:{let e=o.kind;throw Error(`unknown argument kind: ${String(e)}`)}}}function hl(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`?Ac(a,n):i.kind===`path`&&r?.riskClass===`modify`&&Sc(a,n):!1}function gl(e,t,n,r){return fl(e,t,n,`deny`)||pl(e,t,n)||hl(e,t,r)}function _l(e,t,n={},r={}){return pl(e,t,n.deny??[])||gl(e,t,n.ask??[],r)}const vl=[`workingDirectory`,`cwd`];function yl(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`&&nl(i,{otherDirectory:vl.some(e=>t[e]!==void 0),...n.resolveInWorkspace===void 0?{}:{resolveInWorkspace:n.resolveInWorkspace}})?`inspect`:r.riskClass}function bl(e,t,n,r={},i={}){let{allow:a=[],deny:o=[],ask:s=[]}=r,c=yl(e,t,i),l=n===`plan`&&c!==`inspect`?`deny`:`approve`;return fl(e,t,o,`deny`)||i.ceiling!==void 0&&!fl(e,t,i.ceiling)||Q.get(e)?.repliesToPeer===!0&&i.peerTurn!==!0||Q.get(e)?.notInPeerTurn===!0&&i.peerTurn===!0?`deny`:pl(e,t,o)?n===`plan`?`deny`:`approve`:gl(e,t,s,i)||i.askAll===!0?l:n===`bypassPermissions`||fl(e,t,a)||i.sandboxAutoApproved===!0&&c===`execute`&&(n==="default"||n===`acceptEdits`||n===`auto`)?`auto`:c===void 0?_c[n]:gc[n][c]}function xl(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 Sl=/^[A-Za-z_]\w*:(?!\/\/)/;function Cl(e){return e.slice(0,e.indexOf(`*`)).includes(`__`)}function wl(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}=rl(n);if(r===``)return`names no tool`;if(t===`allow`&&r.includes(`*`)&&!Cl(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`&&Sl.test(i)?`matches a named parameter, which only deny and ask rules may do`:void 0;let a=sl(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=al(r);if(!(o.parameters===void 0&&Sl.test(i)&&sl(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`&&(r===`WebFetch`?hc:mc)(i,`https://probe.invalid/`)===`unevaluable`)return`does not fit the URL pattern grammar scheme://host[:port][/path]${r===`WebFetch`?` or domain:hostname`:``} that "${r}" is matched by`}}function Tl(e,t=`deny`){let n=[];for(let r of e){let e=wl(r,t);e!==void 0&&n.push({pattern:r,reason:e})}return n}function El(e){let t=[];for(let n of e){let{toolName:e,argPattern:r}=rl(n.trim());if(r===void 0||e.includes(`*`))continue;let i=al(e),a=sl(e,r);if(a===void 0&&i.parameters!==void 0&&i.argument?.kind!==`url`&&Sl.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=al(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 Dl(e){return(e??[]).map(e=>`${e}(*)`)}function Ol(e,t){let n=Dl(t.allowedTools),r=Tl(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,...Dl(t.deniedTools)])]}}const kl=[`Bash`,`Shell`,`BackgroundProcess`],Al=[`Agent`],jl=[...kl,...Al,`ExecuteCommand`,`Computer`],Ml=`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(`.`),Nl=[`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(` `)),Pl=new Set([`run`,`run-script`,`exec`,`dlx`,`x`,`--`]);function Fl(e){return(e.split(/[\\/]/).pop()??e).replace(/(\.exe)?$/i,``).replace(/[\d.]+$/,``)}function Il(e,t){if(e.length===0)return!0;let n=(e,n,r)=>t&&r?e.startsWith(n):e===n,r=Fl(e[0]);if(Ml.some(t=>n(t,r,e.length===1)))return!0;for(let i of Nl){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(`-`)||Pl.has(o[0]));)o=o.slice(1);return o.length===0||Il(o,t)}return!1}function Ll(e){let t=e.trim();if(!t.includes(`*`))return!1;let n=t.slice(0,t.indexOf(`*`));return Il(n.trim().split(/\s+/).filter(e=>e.length>0),n.length>0&&!/\s$/.test(n))}function Rl(e){let{toolName:t,argPattern:n}=rl(e),r=e=>e.some(e=>ol(t,e));return r(Al)?!0:t.includes(`*`)?r(jl):jl.includes(t)||al(t).riskClass===`execute`?n===void 0||n.trim()===`*`||kl.includes(t)&&Ll(n):!1}function zl(e){return e.filter(e=>!Rl(e))}const Bl=1e6,Vl={"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}},Hl=[{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:/gemini-2/i,price:{inputPerMillion:.1,outputPerMillion:.4}},{pattern:/gemini-1/i,price:{inputPerMillion:1.25,outputPerMillion:5}}];function Ul(e){let t=Object.hasOwn(Vl,e)?Vl[e]:void 0;if(t)return t;for(let{pattern:t,price:n}of Hl)if(t.test(e))return n}function Wl(e,t,n){let r=Ul(e);if(r)return t/Bl*r.inputPerMillion+n/Bl*r.outputPerMillion}function Gl(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 Kl(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 ql(){let[{CommandExecutor:e},{HttpExecutor:t}]=await Promise.all([import(`./command-executor-D_UBZHxh-CVZipoOV.js`).then(e=>e.t).then(e=>e.n),import(`./http-executor-ADn4locH-D-8crzF8.js`).then(e=>e.t).then(e=>e.n)]);return[new e,new t]}async function Jl(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 ql(),u=new Map;for(let e of l)u.set(e.type,e);let d=[],f=Kl(n),p=-1,m,h;for(let e of c){if(!Gl(e,f))continue;let r=e.env?{...n,env:{...n.env,...e.env}}:n;for(let n of e.hooks){let e=u.get(n.type);if(!e){a.add(n.type);continue}let c=n.type===`command`&&i!==void 0?await e.execute(n,r,i):await e.execute(n,r);if(c.outcome===`deny`)return{blocked:!0,reason:c.reason||`Blocked by hook`,stdout:d.join(`
|
|
12
12
|
`),...s()};if(c.outcome===`error`){o.push(c);continue}let l=v(c.stdout,t);if(d.push(...l.context),l.blockReason!==void 0)return{blocked:!0,reason:l.blockReason,stdout:d.join(`
|
|
13
13
|
`),...l.permissionDecision===`deny`&&{permissionDecision:`deny`},...s()};if(l.permissionDecision!==void 0&&c.source===`command`){let e=y[l.permissionDecision];e>p?(p=e,m=l.permissionDecision,h=l.updatedInput):e===p&&l.updatedInput!==void 0&&(h=l.updatedInput)}}}let g={blocked:!1,stdout:d.join(`
|
|
14
|
-
`)};m!==void 0&&(g.permissionDecision=m),h!==void 0&&(g.updatedInput=h);let{unknownHookTypes:_,errors:b}=s();return _!==void 0&&(g.unknownHookTypes=_),b!==void 0&&(g.errors=b),g}var
|
|
15
|
-
//# sourceMappingURL=node-
|
|
14
|
+
`)};m!==void 0&&(g.permissionDecision=m),h!==void 0&&(g.updatedInput=h);let{unknownHookTypes:_,errors:b}=s();return _!==void 0&&(g.unknownHookTypes=_),b!==void 0&&(g.errors=b),g}var Yl=class extends Error{guardrailName;guardrailReason;constructor(e,t){super(t),this.guardrailName=e,this.guardrailReason=t,this.name=`GuardrailBlock`}},Xl=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 Yl(e,`Guardrail "${e}" errored: ${t instanceof Error?t.message:String(t)}`)}if(!r.pass)throw new Yl(e,r.reason??`Guardrail "${e}" blocked the turn`)}))}catch(e){if(e instanceof Yl)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 Zl(e,t){return{posture:`advisory`,enforcementReachable:!1,rationale:`Awaited at ${e} but only ${t} is read; \`blocked\` is never consulted.`}}function Ql(e){for(let t of Object.values(e))Object.freeze(t);return Object.freeze(e)}const $l=Ql({PreToolUse:{posture:`enforcing`,enforcementReachable:!0,rationale:"The tool-execution gate. `runPreToolGate` 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:Zl(`session-lifecycle.ts`,`nothing`),PreCompact:Zl(`compaction-orchestrator.ts`,`nothing`),UserPromptSubmit:Zl(`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 eu(e){return $l[e].posture===`enforcing`}function tu(e){if(e.type===`resource_link`)return`Resource reference (not fetched): ${JSON.stringify(e)}`;if(e.type===`resource_embedded`){let t=`${JSON.stringify(e.uri)}${e.mimeType?` (${e.mimeType})`:``}`;return e.text===void 0?`Embedded binary resource ${t}; binary content retained but not transmitted by this adapter.`:`Embedded resource ${t}:\n${e.text}`}if(e.type===`audio_inline`)return`Audio observation (${e.mimeType}); this adapter does not transmit audio payloads.`}export{Tr as $,Me as A,ll as At,en as B,ye as Bt,Xl as C,vc as Ct,je as D,al as Dt,z as E,qe as Et,Pe as F,An as Ft,Dt as G,Dl as Gt,Ee as H,xl as Ht,ni as I,Xe as It,Wl as J,Fe as Jt,Ie as K,ct as Kt,Vl as L,xr as Lt,eu as M,ao as Mt,B as N,Cr as Nt,j as O,Er as Ot,Hs as P,Dr as Pt,bl as Q,Ns as R,Nn as Rt,mr as S,Nr as St,Jl as T,Sr as Tt,Ol as U,Te as Ut,Tl as V,Vn as Vt,si as W,ut as Wt,ve as X,oe as Xt,Os as Y,se as Yt,Bn as Z,w as Zt,R as _,Or as _t,ii as a,br as at,zl as b,Qe as bt,Rs as c,Jt as ct,Kn as d,yc as dt,On as et,zs as f,Rn as ft,Et as g,qr as gt,Le as h,Ye as ht,Jr as i,Pn as it,uo as j,Re as jt,ke as k,kn as kt,De as l,zn as lt,ro as m,wr as mt,fo as n,jn as nt,we as o,il as ot,ci as p,it as pt,ai as q,be as qt,tu as r,Ar as rt,El as s,pe as st,Dn as t,zr as tt,nn as u,Ds as ut,Bs as v,Vt as vt,bn as w,_l as wt,ze as x,fl as xt,un as y,Mn as yt,Ce as z,ks as zt};
|
|
15
|
+
//# sourceMappingURL=node-DQ4XoykT.js.map
|