@robota-sdk/agent-core 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 +5 -0
- package/dist/browser/index.d.ts +12 -5
- package/dist/browser/index.d.ts.map +1 -1
- package/dist/browser/index.js +9 -9
- package/dist/browser/index.js.map +1 -1
- package/dist/node/{index-De7jXKGE.d.cts → index-CU-S1l2D.d.cts} +13 -6
- package/dist/node/{index-De7jXKGE.d.cts.map → index-CU-S1l2D.d.cts.map} +1 -1
- package/dist/node/{index-BFTag17m.d.ts → index-KukO8qT-.d.ts} +13 -6
- package/dist/node/{index-BFTag17m.d.ts.map → index-KukO8qT-.d.ts.map} +1 -1
- package/dist/node/index.cjs +2 -2
- package/dist/node/index.d.cts +2 -2
- package/dist/node/index.d.ts +2 -2
- package/dist/node/index.js +2 -2
- package/dist/node/index.js.map +1 -1
- package/dist/node/node.cjs +1 -1
- package/dist/node/node.js +1 -1
- package/dist/node/node.js.map +1 -1
- package/dist/node/testing/index.d.cts +1 -1
- package/dist/node/testing/index.d.ts +1 -1
- package/package.json +1 -1
package/dist/node/index.js
CHANGED
|
@@ -8,8 +8,8 @@ import{a as e,c as t,i as n,n as r,o as i,r as a,s as o,t as s}from"./project-to
|
|
|
8
8
|
`),n.beginAssistant();let b=Ko(),{wrappedOnTextDelta:x,wrappedOnProviderNativeRawPayload:S,settleStreamingChunkHooks:C}=cs(a,n,i,p,l,u),w=Po(s,o.defaultModel.model,i),T=H(),E;try{E=await ls(_,o,s,f,a,n,p,i,b,u,x,S,t=>void(e.providerFailure=t),w,T,a.executionJournal?ho(m,e,a,o,t,c.toolExecutionService.getLoadedDeferredTools()):void 0)}finally{await C()}if(E===null)return!0;let{assistantResponse:D,assistantToolCalls:ee}=Ho(E,i,a.conversationId,p,u);if(ee.length>0&&(a.toolChoice??o.defaultModel?.toolChoice)===`none`)throw Error(`Provider returned tool calls despite toolChoice none; no tools were executed.`);await W(l,`afterProviderCall`,{messages:m,responseMessage:E},u),await W(l,`onMessageAdded`,{message:E},u);let te=typeof D.content==`string`&&D.content.trim().length>0;if(ee.length===0&&!te)return u.warn(`[ROUND] Provider returned empty assistant response without tool calls`,{executionId:i,conversationId:a.conversationId,round:p}),n.discardPending(),!0;let ne=Jo(D),re=ne.inputTokens??0;re>0&&(e.cumulativeInputTokens=re);for(let e of ee)n.appendToolCall(e);let ie=a.signal?.aborted?`interrupted`:`complete`;n.commitAssistant(ie,{round:p,usageObservationId:b,executionId:i,providerId:G(w,s),providerCallId:T,modelId:K(w,s.aiProviderInfo.model),...ne});let ae=n.getMessages().at(-1);return a.onExecutionEvent?.(`assistant_message_committed`,{executionId:i,conversationId:a.conversationId,round:p,message:D}),ae&&a.onExecutionEvent?.(`history_mutation`,{executionId:i,conversationId:a.conversationId,round:p,mutation:`append_message`,index:n.getMessages().length-1,message:ae}),e.runningAssistantCount++,e.lastTrackedAssistantMessage=D,ee.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):is(await bs(ee,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 Ss(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 Cs(e,t){return t===0||e<t}async function ws(e,t,n,r,i,a,o,s,c,l=!1){let u=Ss(i,r);for(;!l&&!o.forcedSummaryInstruction&&Cs(o.currentRound,u)&&!(s?.aborted||(o.currentRound++,await xs(o,u,e,t,n,r,i,a,c))||s?.aborted););let d=e.getMessages(),f=d.length>0?d[d.length-1]:void 0,p=f?.role===`assistant`&&typeof f.content==`string`&&f.content.length>0&&(!(`toolCalls`in f)||f.toolCalls.length===0);if(!s?.aborted){if(r.allowToolOnlyCompletion===!0){let e=f?.role===`tool`;if(!p&&!e)throw new ie(o.currentRound,{conversationId:t,executionId:n});return}p||await rs(e,a,i,n,o,t,r,c.logger,u,r.executionJournal?c.toolExecutionService.getLoadedDeferredTools():void 0)}}async function Ts(e,t,n,r,i,a,o,s,c,l,u,d){let f={...mo(t,n,r,i.toolsExecuted,{turnMessageId:o,interrupted:s,...c?.allowToolOnlyCompletion===!0&&{allowToolOnlyCompletion:!0}},i.providerFailure),interrupted:s};await W(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 W(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(j.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 q(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 J(e){throw new L(`EXECUTION_RECOVERY_INVALID`,e)}function Y(e){return typeof e==`string`&&e.length>0}function Es(e,t,n,r=!0){try{return Ds(structuredClone(e),t,n,r)}catch(e){if(e instanceof L)throw e;return J(`Execution journal is not a valid recoverable record prefix`)}}function Ds(e,t,n,r){(!Y(t)||!Y(n)||!Array.isArray(e))&&J(`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||!Y(n.recordId))&&J(`Journal execution identity mismatch`);let e=q(n),r=a.get(n.recordId);if(r!==void 0){e!==r&&J(`Conflicting journal record identity`);continue}if(a.set(n.recordId,e),i.push(n),`callId`in n)Y(n.callId)||J(`Missing model call identity`),n.kind===`model-request`||n.kind===`model-cache-hit`?o=n.callId:n.callId!==o&&J(`Model settlement crossed a newer invocation`);else if(`actionId`in n){(!Y(n.actionId)||!Y(n.parentCallId))&&J(`Missing action identity`);let e=s.get(n.actionId),t=q([n.parentCallId,n.toolCallId,n.toolName]);if(e&&e!==t&&J(`Action identity belongs to multiple calls`),s.set(n.actionId,t),n.kind===`tool-wait`&&((!n.request||!Y(n.request.requestId)||!Y(n.request.kind)||c.has(n.request.requestId))&&J(`Invalid or duplicate tool wait`),ms(n.request.data),c.set(n.request.requestId,n)),n.kind===`tool-response`){let e=n.response,t=e&&c.get(e.requestId);(!t||!Y(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)&&J(`Tool response does not belong to an unanswered request`),ms(e.response),l.add(e.requestId),u.add(e.responseId)}}else J(`Unknown journal record`)}o!==n&&J(`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)&&J(`Duplicate or out-of-order model request`),d=e):e.kind===`model-cache-hit`?((d||f||e.response.role!==`assistant`)&&J(`Invalid cache settlement`),f=e.response,p=e.checkpoint):e.kind===`model-response`?((!d||f||e.response.role!==`assistant`)&&J(`Invalid model response`),f=e.response):J(`This model invocation has no recoverable tool response`);continue}if(e.parentCallId!==n)continue;f||J(`Tool action precedes its model response`);let r=f.toolCalls?.find(t=>t.id===e.toolCallId);(!r||e.toolName!==r.function.name)&&J(`Action does not belong to the saved model response`);let i=m.get(e.toolCallId);if(i&&i.actionId!==e.actionId&&J(`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&&J(`Tool action continued after settlement`),e.kind===`tool-intent`)(i.intent||i.dispatched||i.effectStarted)&&J(`Out-of-order action intent`),q(JSON.parse(r.function.arguments))!==q(e.parameters)&&J(`Action arguments differ from saved intent`),i.intent=!0;else if(e.kind===`tool-dispatch`)(!i.intent||i.dispatched||i.effectStarted)&&J(`Out-of-order dispatch`),i.dispatched=!0;else if(e.kind===`tool-effect-start`)(!i.dispatched||i.effectStarted)&&J(`Out-of-order effect admission`),i.waits.some(e=>!e.response)&&J(`Tool effect precedes a required response`),i.effectStarted=!0;else if(e.kind===`tool-wait`)(!i.dispatched||i.effectStarted)&&J(`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)&&J(`Out-of-order tool response`),t.response=e.response}else if(e.kind===`tool-result`){let t=e.result,n=t.metadata?.errorCode===Pt;n&&(t.success||i.dispatched||i.effectStarted||t.metadata?.dispatchStatus!==`not-dispatched`||t.result!==null)&&J(`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&&!Y(t.error))&&J(`Invalid tool result linkage or payload`),e.loadedDeferredTools!==void 0&&(!Array.isArray(e.loadedDeferredTools)||e.loadedDeferredTools.some(e=>!Y(e)))&&J(`Invalid tool residency settlement`),i.result=t,i.loadedDeferredTools=e.loadedDeferredTools}else J(`Unknown action record`)}let h=d?.checkpoint??p;(!f||!h||h.version!==1||h.effectAdmission!==`required`)&&J(`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))&&J(`Invalid round checkpoint`);let g=new Set;for(let e of h.messages)g.has(e.id)&&J(`Duplicate checkpoint message identity`),g.add(e.id);for(let e of[...h.messages,f])(!Y(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`&&!Y(e.toolCallId)||![`user`,`assistant`,`system`,`tool`].includes(e.role)||![`complete`,`interrupted`].includes(e.state))&&J(`Invalid checkpoint message`);let _=new Set;for(let[e,t]of h.sameToolInputCounts)(!Y(e)||_.has(e)||!Number.isSafeInteger(t)||t<0)&&J(`Invalid repeated-input checkpoint`),_.add(e);h.maxSameToolInputs!==void 0&&(!Number.isSafeInteger(h.maxSameToolInputs)||h.maxSameToolInputs<1)&&J(`Invalid repeated-input limit`),r&&(!Array.isArray(f.toolCalls)||f.toolCalls.length===0)&&J(`Saved response has no tool calls`),g.clear();for(let e of f.toolCalls??[])(!Y(e.id)||g.has(e.id)||e.type!==`function`||!Y(e.function?.name)||typeof e.function.arguments!=`string`)&&J(`Invalid or duplicate saved tool call`),g.add(e.id);d?.options.toolChoice===`none`&&(f.toolCalls?.length??0)>0&&J(`Saved invocation prohibited tool execution`);let v=[...m.values()].filter(e=>e.effectStarted&&!e.result);if(v.length)throw new L(`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 Os(e){throw new L(`EXECUTION_RECOVERY_CONFLICT`,e)}function ks(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,...Jo(e.response),executionId:t.executionId,providerCallId:t.callId,round:e.checkpoint.round}}}function As(e,t,n,r){return e.role===`assistant`&&t.role===`assistant`&&(e.content??``)===(t.content??``)&&q(e.toolCalls??[])===q(t.toolCalls??[])&&e.metadata?.providerCallId===n&&e.metadata.executionId===r}function js(e,t,n,r){if(!e.length)return;let i=t.checkpoint.messages;(e.length<i.length||q(e.slice(0,i.length))!==q(i))&&Os(`Current history differs from the saved runtime checkpoint`);let a=e.slice(i.length);if(!a.length)return;As(a[0],ks(t,n),n.callId,n.executionId)||Os(`Current assistant does not match the saved response`);let o=t.response.toolCalls??[];a.length>o.length+1&&Os(`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||Os(`History contains a tool result without durable settlement`),n}),l=new br;for(let e of i)l.addMessage(e);l.addMessage(a[0]),fs(s,{results:c,errors:[]},l,t.checkpoint.round,r.logger,{contextLimit:t.checkpoint.contextLimit,cumulativeInputTokens:Ms(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)&&Os(`Existing tool result conflicts with the durable result`)}}function Ms(e){let t=Jo(e.response).inputTokens??0;return t>0?t:e.checkpoint.cumulativeInputTokens}async function Ns(e,t,n,r,i){let a=q(e.getMessages()),o=()=>{(a!==q(e.getMessages())||e.hasPendingAssistant())&&Os(`History changed during execution recovery`)};o();let s=i?.records??await n.journal.read(n.executionId),c=i?.batch??Es(s,n.executionId,n.callId);n.signal?.throwIfAborted(),o();let l=structuredClone(e.getMessages());js(l,c,n,r);let u=await _s(s,n);u.length!==s.length&&(c=Es(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 br;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(ks(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:Ms(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=is(await bs(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=q(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!==q(e.getMessages())||e.hasPendingAssistant())&&Os(`History changed while announcing execution recovery`);if(n.signal?.aborted)throw Ut(`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 Ps(e,t,n,r){let{executionId:i,callId:a,messages:o}=await Ns(e,t,n,r);return{executionId:i,callId:a,messages:o}}function X(e){throw new L(`EXECUTION_RECOVERY_INVALID`,e)}function Fs(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`)&&X(`Unsupported runtime continuation checkpoint`),e.structuredOutput&&X(`Structured-output validators do not yet support execution continuation`),e}async function Is(e,t,n,r,i,a){let o=q(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))&&X(`No recoverable model invocation exists`),c.kind===`model-request`&&!s.some(e=>e.kind===`model-response`&&e.callId===c.callId))throw new L(`EXECUTION_RECOVERY_REQUIRED`,`The latest model invocation has no durable response; reconcile it before resuming`);let l=Es(s,n.executionId,c.callId,!1),u=Fs(l.checkpoint.continuation);(u.model.provider!==r.defaultModel.provider||u.model.model!==r.defaultModel.model)&&X(`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)&&X(`Continuation has no matching original input`),(u.toolSearch??`auto`)!==(r.toolSearch??`auto`)&&X(`Tool residency policy differs from the saved runtime`),r.responseFormat&&r.responseFormat.type!==`text`&&X(`Current runtime requires an unsupported structured-output validator`),u.options.maxSameToolInputs!==l.checkpoint.maxSameToolInputs&&X(`Conflicting repeated-input limits`),u.kind===`summary`&&(l.response.toolCalls?.length??0)>0&&X(`Terminal summary cannot dispatch tools`);for(let e of l.actions.values())e.result&&e.loadedDeferredTools===void 0&&X(`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&&X(`Active provider manager differs from the saved runtime`),o!==q(e.getMessages()))throw new L(`EXECUTION_RECOVERY_CONFLICT`,`History changed while reading the execution journal`);let m=await Ns(e,t,{...n,callId:c.callId},a,{batch:l,records:s}),h=Ao(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 ws(e,t,n.executionId,h,f,p,m.state,n.signal,a,m.stop||u.kind===`summary`),n.signal?.aborted)throw Ut(`Execution continuation interrupted`,n.signal.reason);return mo(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*Ls(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 Rs(e,t,n){return{executionId:e,...t===void 0?{}:{driverId:t},...n===void 0?{}:{turnSource:n}}}var zs=class{toolExecutionService;aiProviders;tools;conversationHistory;plugins=[];logger;eventEmitter;cacheService;constructor(e,t,n,r,i,a){if(this.toolExecutionService=new $a(t),this.aiProviders=e,this.tools=t,this.conversationHistory=n,this.plugins=[],this.logger=O(`ExecutionService`),!r)throw Error(`[EXECUTION] EventService is required`);this.eventEmitter=new lo(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 Is(this.conversationHistory.getConversationStore(e),e,t,n,e=>wo(this.aiProviders,this.tools,e),{toolExecutionService:this.toolExecutionService,plugins:this.plugins,logger:this.logger,eventEmitter:this.eventEmitter,cacheService:this.cacheService})}resumeToolCalls(e,t){return Ps(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=Oo(),a=new Date,o=ko(r,`execute`),s=Ao(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=wo(this.aiProviders,this.tools,n);this.eventEmitter.emitExecutionStartEvent(e,n,t,c,o,i);let l=Eo(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,Rs(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 W(this.plugins,`beforeRun`,{input:e,...r?.metadata?{metadata:r.metadata}:{}},this.logger);let p={executionId:i,conversationId:o};f&&await W(this.plugins,`onMessageAdded`,{message:f,executionContext:p},this.logger);for(let e of[`beforeExecution`,`beforeConversation`])await W(this.plugins,e,{messages:l.getMessages(),executionContext:p},this.logger);To(c);for(let e of l.getMessages())e.role===`assistant`&&(d.runningAssistantCount++,d.lastTrackedAssistantMessage=e);return await ws(l,o,i,s,n,c,d,r?.signal,{toolExecutionService:this.toolExecutionService,plugins:this.plugins,logger:this.logger,eventEmitter:this.eventEmitter,cacheService:this.cacheService}),Ts(e,l,i,a,d,o,u,r?.signal?.aborted??!1,r,this.plugins,this.logger,this.eventEmitter)}catch(e){if(R(e))throw e;return Ht(e,r?.signal)?{...mo(l,i,a,d.toolsExecuted,{turnMessageId:u,interrupted:!0}),interrupted:!0}:(await Do(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*Ls(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 Bs(e){let t=new ba;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 Vs(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 Bt&&c&&e.setEventService(c),r.addResultTool(e.schema,async(t,n)=>{if(!n)throw Error(`[AGENT] Missing ToolExecutionContext for tool execution`);return gi(e,t,n)},e.provenance),l.debug(`Tool registered during initialization`,{toolName:e.schema.name});let u;t.cache?.enabled&&(u=new Ca(new Sa({maxEntries:t.cache.maxEntries,ttlMs:t.cache.ttlMs}),new xa));let d=new zs(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 Hs(e){try{let t=await Vs(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 Us(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 Ws(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 Gs=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(),Ks(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 Ks(e,t){let n=e.reason;return Ht(n)&&n.name===`AbortError`?n:Ut(t?`Run aborted while queued behind another run on this instance`:`Run aborted before it started`,n)}function qs(e){return{maxConcurrentAgents:e.maxConcurrentAgents||100,defaultSystemMessage:e.defaultSystemMessage??``,strictValidation:e.strictValidation??!0,idFactory:e.idFactory??Ys,...e.defaultModel!==void 0&&{defaultModel:e.defaultModel},...e.defaultProvider!==void 0&&{defaultProvider:e.defaultProvider}}}function Js(e,t){if(!e.aiProviders||e.aiProviders.length===0)throw new m(`At least one AI provider must be specified in aiProviders array`);let n=e.defaultModel,r=n?.model??t.defaultModel;if(!r)throw new m(`No model specified: set config.defaultModel.model or the AgentFactory defaultModel option`);let i=n?.provider??e.aiProviders[0]?.name??t.defaultProvider;if(!i)throw new m(`No provider specified: set config.defaultModel.provider, an aiProviders entry, or the AgentFactory defaultProvider option`);return{id:e.id||Ys(),name:e.name||`Unnamed Agent`,aiProviders:e.aiProviders,defaultModel:{provider:i,model:r,temperature:n?.temperature??.7,...n?.maxTokens!==void 0&&{maxTokens:n.maxTokens},...n?.topP!==void 0&&{topP:n.topP}},systemMessage:e.systemMessage??t.defaultSystemMessage,tools:e.tools||[],plugins:e.plugins||[],metadata:e.metadata||{},...e.logging&&{logging:e.logging},...e.conversationId&&{conversationId:e.conversationId},...e}}function Ys(){return`agent_${Date.now()}_${Math.random().toString(36).substring(2,8)}`}function Xs(e,t){return e.totalCreated++,e.activeCount++,t?e.fromTemplates++:e.customConfigured++,e.templateUsageRatio=e.totalCreated>0?e.fromTemplates/e.totalCreated:0,e}var Zs=class{templates=new Map;logger;constructor(){this.logger=O(`AgentTemplates`),this.logger.info(`AgentTemplates initialized`)}registerTemplate(e){if(!e.id)throw Error(`Template must have an ID`);this.templates.has(e.id)&&this.logger.warn(`Template "${e.id}" is already registered, overriding`),this.templates.set(e.id,e),this.logger.info(`Template "${e.id}" registered successfully`,{templateId:e.id,category:e.category,tags:e.tags})}unregisterTemplate(e){let t=this.templates.delete(e);return t?this.logger.info(`Template "${e}" unregistered`):this.logger.warn(`Attempted to unregister non-existent template "${e}"`),t}getTemplates(){return Array.from(this.templates.values())}getTemplate(e){return this.templates.get(e)}findTemplates(e){return this.getTemplates().filter(t=>!(e.category&&t.category!==e.category||e.tags&&e.tags.length>0&&!e.tags.some(e=>t.tags?.includes(e))||e.provider&&t.config.defaultModel?.provider!==e.provider||e.model&&t.config.defaultModel?.model!==e.model))}applyTemplate(e,t={}){let n=[],r=!1,i={...e.config},a={...i,...t},o=e=>{e in t&&i[e]!==t[e]&&(r=!0,i[e]!==void 0&&n.push(`Override: ${e} changed from "${String(i[e])}" to "${String(t[e])}"`))};t.name!==void 0&&o(`name`),t.systemMessage!==void 0&&o(`systemMessage`);let s=a;return this.logger.debug(`Template applied`,{templateId:e.id,overridesCount:Object.keys(t).length,warningsCount:n.length,modified:r}),{config:s,template:e,warnings:n,modified:r}}hasTemplate(e){return this.templates.has(e)}getTemplateCount(){return this.templates.size}clearAll(){this.templates.clear(),this.logger.info(`All templates cleared`)}getStats(){let e=this.getTemplates(),t=[...new Set(e.map(e=>e.category).filter(e=>typeof e==`string`&&e.length>0))],n=[...new Set(e.flatMap(e=>e.tags||[]))],r=[...new Set(e.map(e=>e.config.defaultModel?.provider).filter(e=>typeof e==`string`&&e.length>0))],i=[...new Set(e.map(e=>e.config.defaultModel?.model).filter(e=>typeof e==`string`&&e.length>0))];return{totalTemplates:e.length,categories:t,tags:n,providers:r,models:i}}};function Qs(e){let t=e,n=typeof t.initialize==`function`?t.initialize:void 0,r=typeof t.cleanup==`function`?t.cleanup:void 0;if(n!==void 0||r!==void 0)return{...n?{initialize:()=>n.call(e)}:{},...r?{cleanup:()=>r.call(e)}:{}}}function $s(e){return e instanceof Error&&`failedStep`in e&&`rollbackErrors`in e}async function ec(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 tc(e,n.name,r)}t.push(n)}}function tc(e,t,n){let r=e instanceof Error?e:Error(String(e));return Object.assign(r,{failedStep:t,rollbackErrors:n})}var nc=class{agentTemplates;initialized=!1;logger;options;activeAgents;pendingAgents=new Set;creationStats;lifecycleEvents;constructor(e={},t={}){this.agentTemplates=new Zs,this.logger=O(`AgentFactory`),this.options=qs(e),this.activeAgents=new Map,this.creationStats={totalCreated:0,activeCount:0,fromTemplates:0,customConfigured:0,templateUsageRatio:0},this.lifecycleEvents=t,this.logger.debug(`AgentFactory initialized`,{maxConcurrentAgents:this.options.maxConcurrentAgents,strictValidation:this.options.strictValidation,hasDefaultModel:!!this.options.defaultModel,hasDefaultProvider:!!this.options.defaultProvider,hasLifecycleEvents:this.lifecycleEvents!==null})}async initialize(){this.initialized||(this.logger.debug(`Initializing AgentFactory`),this.initialized=!0,this.logger.debug(`AgentFactory initialization completed`))}async createAgent(e,t,n=!1){let r,i=this.admit();try{r=Js(t,this.options);let a=r;if(this.options.strictValidation){let e=Kt(r);if(!e.isValid)throw new d(`Invalid agent configuration: ${e.errors.join(`, `)}`)}let o;if(await ec([{name:`beforeCreate`,run:()=>this.lifecycleEvents.beforeCreate?.(a)},{name:`construct`,run:()=>{o=new e(a)}},{name:`initialize`,run:()=>o?Qs(o)?.initialize?.():void 0,undo:()=>o?Qs(o)?.cleanup?.():void 0},{name:`commit`,run:()=>{if(!o)throw new m(`Agent was not constructed`);this.activeAgents.set(i,o),Xs(this.creationStats,n)},undo:()=>{this.activeAgents.delete(i),this.creationStats.activeCount--,this.creationStats.totalCreated--,n?this.creationStats.fromTemplates--:this.creationStats.customConfigured--}},{name:`afterCreate`,run:()=>o?this.lifecycleEvents.afterCreate?.(o,a):void 0}]),this.pendingAgents.delete(i),!o)throw new m(`Agent was not constructed`);return this.logger.info(`Agent created successfully`,{agentId:i,model:r.defaultModel.model,provider:r.defaultModel.provider}),o}catch(e){this.pendingAgents.delete(i);let n=e instanceof Error?e:Error(String(e));throw this.lifecycleEvents.onCreateError&&r&&await this.lifecycleEvents.onCreateError(n,r),this.logger.error(`Failed to create agent`,{error:n.message,model:t.defaultModel?.model,provider:t.defaultModel?.provider,hasTools:!!t.tools?.length}),n}}admit(){if(this.activeAgents.size+this.pendingAgents.size>=this.options.maxConcurrentAgents)throw new m(`Maximum concurrent agents limit reached: ${this.options.maxConcurrentAgents}`);let e=this.options.idFactory(),t=0;for(;this.activeAgents.has(e)||this.pendingAgents.has(e);){if(t+=1,t>16)throw new m(`Agent id factory keeps returning ids that are already in use`);e=this.options.idFactory()}return this.pendingAgents.add(e),e}async createFromTemplate(e,t,n={}){let r=this.agentTemplates.getTemplate(t);if(!r)throw new m(`Template not found: ${t}`);let i=this.applyTemplate(r,n);i.warnings.length>0&&this.logger.warn(`Template application warnings`,{templateId:t,warnings:i.warnings});let a=await this.createAgent(e,i.config,!0);return this.logger.info(`Agent created from template`,{templateId:t,modified:i.modified,warnings:i.warnings.length}),a}registerTemplate(e){this.agentTemplates.registerTemplate(e)}unregisterTemplate(e){return this.agentTemplates.unregisterTemplate(e)}getTemplates(){return this.agentTemplates.getTemplates()}getTemplate(e){return this.agentTemplates.getTemplate(e)}findTemplates(e){return this.agentTemplates.findTemplates(e)}applyTemplate(e,t={}){return this.agentTemplates.applyTemplate(e,t)}async destroyAgent(e){let t=this.activeAgents.get(e);if(!t)return!1;try{return await Qs(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 rc(e,t,n){if(!e.name||e.name.trim()===``)throw new m(`Module name is required`);if(!e.version||e.version.trim()===``)throw new m(`Module version is required`);let r=e.getModuleType(),i=t.validateTypeDescriptor(r);if(!i.valid)throw new m(`Invalid module type: ${i.errors.join(`, `)}`,{moduleName:e.name,errors:i.errors});i.warnings.length>0&&n.warn(`Module type validation warnings`,{moduleName:e.name,warnings:i.warnings})}async function ic(e,t,n,r){let i=e.getModuleType();if(!i.dependencies||i.dependencies.length===0)return;for(let n of i.dependencies)if(!t.hasType(n))throw new m(`Module '${e.name}' depends on unregistered type '${n}'`,{moduleName:e.name,dependencyType:n});let a=new Set;for(let e of n.values())a.add(e.getModuleType().type);let o=[];for(let e of i.dependencies)a.has(e)||o.push(e);o.length>0&&r.warn(`Module has unmet dependencies`,{moduleName:e.name,missingDependencies:o})}function ac(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 oc(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 sc(){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 cc(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 lc(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 uc(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 dc(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 fc=class{registeredTypes=new Map;logger;constructor(){this.logger=O(`ModuleDescriptorRegistry`),this.registerBuiltinTypes()}registerType(e){let t=this.validateTypeDescriptor(e);if(!t.valid)throw new m(`Invalid module type descriptor: ${t.errors.join(`, `)}`,{type:e.type,errors:t.errors});if(this.registeredTypes.has(e.type)){let t=this.registeredTypes.get(e.type);this.logger.warn(`Overriding existing module type`,{type:e.type,previousCategory:t?.category||`unknown`,newCategory:e.category})}this.registeredTypes.set(e.type,e),this.logger.info(`Module type registered`,{type:e.type,category:e.category,layer:e.layer,dependencies:e.dependencies?.length||0,capabilities:e.capabilities?.length||0})}unregisterType(e){if(!this.registeredTypes.has(e))return!1;let t=this.findDependentTypes(e);if(t.length>0)throw new m(`Cannot unregister module type '${e}' - it is required by: ${t.join(`, `)}`,{type:e,dependentTypes:t});return this.registeredTypes.delete(e),this.logger.info(`Module type unregistered`,{type:e}),!0}getType(e){return this.registeredTypes.get(e)}getAllTypes(){return Array.from(this.registeredTypes.values())}getTypesByCategory(e){return Array.from(this.registeredTypes.values()).filter(t=>t.category===e)}getTypesByLayer(e){return Array.from(this.registeredTypes.values()).filter(t=>t.layer===e)}hasType(e){return this.registeredTypes.has(e)}validateTypeDescriptor(e){return cc(e,e=>this.getType(e))}resolveDependencies(e){return lc(e,e=>this.getType(e),e=>this.hasType(e))}checkCompatibility(e){return uc(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 sc())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 dc(this.registeredTypes)}};const pc={REGISTERED:`module.registered`,UNREGISTERED:`module.unregistered`};var mc=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 fc,this.logger=O(`ModuleRegistry`)}async registerModule(e,t={}){if(this.isDisposing)throw new m(`Cannot register modules during disposal`);if(rc(e,this.typeRegistry,this.logger),this.modules.has(e.name))throw new m(`Module with name '${e.name}' is already registered`,{moduleName:e.name});t.validateDependencies!==!1&&await ic(e,this.typeRegistry,this.modules,this.logger),this.modules.set(e.name,e),this.moduleOptions.set(e.name,t.initOptions||{}),this.registrationOrder.push(e.name);let n=e.getModuleType();this.moduleStatuses.set(e.name,{name:e.name,type:n.type,enabled:e.isEnabled(),initialized:!1,hasEventEmitter:!!this.eventEmitter,registrationTime:new Date,dependencies:n.dependencies||[],dependents:[]}),this.moduleStats.set(e.name,{totalExecutions:0,successfulExecutions:0,failedExecutions:0,averageExecutionTime:0,totalExecutionTime:0}),t.autoInitialize&&await this.initializeModule(e.name,t.initTimeout),this.eventEmitter&&await this.eventEmitter.emit(pc.REGISTERED,{data:{moduleName:e.name,moduleType:n.type},timestamp:new Date})}async unregisterModule(e){let t=this.modules.get(e);if(!t)return!1;let n=ac(e,this.modules);if(n.length>0)throw new m(`Cannot unregister module '${e}' - it is required by: ${n.join(`, `)}`,{moduleName:e,dependents:n});t.isInitialized()&&t.dispose&&await t.dispose(),this.modules.delete(e),this.moduleOptions.delete(e),this.moduleStatuses.delete(e),this.moduleStats.delete(e);let r=this.registrationOrder.indexOf(e);r!==-1&&this.registrationOrder.splice(r,1);let i=this.initializationOrder.indexOf(e);return i!==-1&&this.initializationOrder.splice(i,1),this.eventEmitter&&await this.eventEmitter.emit(pc.UNREGISTERED,{data:{moduleName:e},timestamp:new Date}),!0}async initializeModule(e,t){let n=this.modules.get(e);if(!n)throw new m(`Module '${e}' not found`);if(n.isInitialized())return;let r=this.moduleOptions.get(e),i=n.initialize(r,this.eventEmitter);if(t&&t>0){let n,r=new Promise((r,i)=>{n=setTimeout(()=>{i(Error(`Module '${e}' initialization timed out after ${t}ms`))},t)});await Promise.race([i.then(e=>(clearTimeout(n),e)),r])}else await i;let a=this.moduleStatuses.get(e);a&&(a.initialized=!0,a.initializationTime=new Date),this.initializationOrder.includes(e)||this.initializationOrder.push(e)}async initializeAllModules(e){let t=Array.from(this.modules.keys());if(t.length===0)return;let n=t.map(e=>this.modules.get(e).getModuleType().type),r=this.typeRegistry.resolveDependencies(n);if(!r.resolved){let e=[];throw r.missingDependencies.length>0&&e.push(`Missing dependencies: ${r.missingDependencies.join(`, `)}`),r.circularDependencies.length>0&&e.push(`Circular dependencies: ${r.circularDependencies.map(e=>e.join(` -> `)).join(`; `)}`),new m(`Cannot initialize modules: ${e.join(`; `)}`,{missingDependencies:r.missingDependencies,circularDependencies:r.circularDependencies.map(e=>e.join(` -> `))})}for(let n of r.order){let r=t.find(e=>this.modules.get(e).getModuleType().type===n);r&&await this.initializeModule(r,e)}}async executeModule(e,t){let n=this.modules.get(e);if(!n)throw new m(`Module '${e}' not found`);if(!n.isInitialized())throw new m(`Module '${e}' is not initialized`);if(!n.isEnabled())throw new m(`Module '${e}' is disabled`);let r=this.moduleStats.get(e),i=Date.now();try{if(!n.execute)throw new m(`Module '${e}' does not support execute()`);let a=await n.execute(t),o=Date.now()-i;r.totalExecutions++,r.successfulExecutions++,r.totalExecutionTime+=o,r.averageExecutionTime=r.totalExecutionTime/r.totalExecutions,r.lastExecutionTime=new Date;let s=this.moduleStatuses.get(e);return s&&(s.lastActivity=new Date),a}catch(e){let t=Date.now()-i;throw r.totalExecutions++,r.failedExecutions++,r.totalExecutionTime+=t,r.averageExecutionTime=r.totalExecutionTime/r.totalExecutions,r.lastExecutionTime=new Date,e}}getModule(e){return this.modules.get(e)}getModulesByType(e){return Array.from(this.modules.values()).filter(t=>t.getModuleType().type===e)}getAllModules(){return Array.from(this.modules.values())}getModuleNames(){return Array.from(this.modules.keys())}hasModule(e){return this.modules.has(e)}getModuleStatus(e){return this.moduleStatuses.get(e)}getAllModuleStatuses(){return Array.from(this.moduleStatuses.values())}getModuleStats(e){return this.moduleStats.get(e)}getAllModuleStats(){let e={};for(let[t,n]of this.moduleStats.entries())e[t]={...n};return e}async disposeAllModules(){this.isDisposing=!0;let e=[...this.initializationOrder].reverse();for(let t of e){let e=this.modules.get(t);if(e&&e.isInitialized())try{e.dispose&&await e.dispose();let n=this.moduleStatuses.get(t);n&&(n.initialized=!1)}catch(e){this.logger.error(`Failed to dispose module`,{name:t,error:e instanceof Error?e.message:String(e)})}}this.initializationOrder=[],this.isDisposing=!1}clearAllModules(){this.modules.clear(),this.moduleOptions.clear(),this.moduleStatuses.clear(),this.moduleStats.clear(),this.registrationOrder=[],this.initializationOrder=[],this.isDisposing=!1}getRegistryStats(){return oc(this.modules,this.moduleStats)}},hc=class extends hi{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=qi(e);let t=e.logging?.enabled===!1?`silent`:e.logging?.level;this.logger=O(`ConversationAgent`,t?{level:t}:{}),this.startTime=Date.now(),_i(e),this.config={...e,aiProviders:[...e.aiProviders],...e.providerOwnership?{providerOwnership:{...e.providerOwnership}}:{}},this.aiProviders=Bs(e),this.tools=Ji(()=>this.config),this.agentFactory=new nc,this.conversationHistory=new xr,this.eventEmitter=ia(),this.moduleRegistry=new mc(this.eventEmitter),this.eventService=e.eventService||Jr,this.agentEventService=U(this.eventService,{ownerType:`agent`,ownerId:this.conversationId,ownerPath:aa(this.conversationId,this.config.executionContext)});let n=Zi({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,na(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=[...aa(this.conversationId,this.config.executionContext),{type:`tool`,id:n.executionId??e}];return this.executionService.invokeRuntimeTool(e,t,{...n,baseEventService:this.eventService,eventService:U(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=Gn(t.output);return await da(this.executionDeps(),e,t,n)}return await sa(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=Gn(t.output);return yield*fa(this.executionDeps(),e,t,n)}return yield*ca(this.executionDeps(),e,t)}finally{this.resetEphemeralHistory(),n()}}resetEphemeralHistory(){this.config.retainHistory===!1&&this.clearHistory()}runQueue=new Gs;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 ma(this.conversationHistory,this.conversationId)}getFullHistory(){return ha(this.conversationHistory,this.conversationId)}addHistoryEntry(e){ga(this.conversationHistory,this.conversationId,e)}clearHistory(){_a(this.conversationHistory,this.conversationId)}injectMessage(e,t,n){va(this.conversationHistory,this.conversationId,e,t,n)}injectRawMessage(e){ya(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 Us({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,Ws({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 Hs({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){ra(this.agentEventService,this.conversationId,this.config.executionContext,e,t)}};const gc=1e4,_c=25e3,vc=5e5,yc=/^tool-result:[A-Za-z0-9_-]{22,64}$/u,bc=Symbol.for(`@robota-sdk/tool-result-admitted`);var xc=class extends Error{code;constructor(e){super(`Tool result admission failed (${e})`),this.code=e,this.name=`ToolResultAdmissionError`}};function Sc(e){return Object.getOwnPropertyDescriptor(e,bc)?.value===!0}function Cc(e){return Object.defineProperty({...e},bc,{value:!0})}function wc(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 Tc(e){return Number.isSafeInteger(e)&&e>0}function Ec(e,t){let n=e.warningChars??1e4,r=e.hardChars??25e3,i=e.repositoryMaxChars??5e5;if(!Tc(n)||!Tc(r)||!Tc(i)||n>=r||r>i||i>5e5)throw new xc(`invalid-policy`);if(t===void 0)return{warningChars:n,hardChars:r};if(!Tc(t))throw new xc(`invalid-override`);return{warningChars:n,hardChars:Math.max(r,Math.min(t,i))}}async function Dc(e,t,n={},r){let{warningChars:i,hardChars:a}=Ec(n,r),o=wc(t),s=o.length;if(s>i&&n.onWarning?.({toolName:e,resultChars:s,warningChars:i}),s>a){if(!n.spillStore)throw new xc(`spill-unavailable`);let e;try{e=(await n.spillStore.write(o)).reference}catch{throw new xc(`spill-write-failed`)}if(!yc.test(e)||e.length>a)throw new xc(`invalid-reference`);let r=t.view?{view:t.view}:{};return Cc(t.success?{success:!0,data:e,...r}:{success:!1,error:`Tool failure details: ${e}`,...r})}return Cc(t)}var Oc=class{store;listener;sequenceId=0;constructor(e,t){this.store=e,this.listener=(e,t,n)=>{if(!n?.ownerPath?.length)throw Error(`[HISTORY-MODULE] Missing ownerPath for ${e}`);let r={eventName:e,sequenceId:this.nextSequenceId(),timestamp:t.timestamp,eventData:t,context:n};this.store.append(r)},t.subscribe(this.listener)}append(e){this.store.append(e)}read(e,t){return this.store.read(e,t)}readStream(e,t){return this.store.readStream(e,t)}getSnapshot(){return this.store.getSnapshot?.()}detach(e){e.unsubscribe(this.listener)}nextSequenceId(){return this.sequenceId+=1,this.sequenceId}};const kc={STARTED:`started`,STEP_STARTED:`step_started`,STEP_COMPLETED:`step_completed`,COMPLETED:`completed`,FAILED:`failed`},Ac=`orchestration`;function Z(e){if(!(!e||typeof e!=`object`||Array.isArray(e)||e instanceof Date))return e}function jc(e){return typeof e==`string`?e.length:0}var Mc=class{config;methodConfigs=new Map;constructor(e){this.config=e}configureMethod(e,t){return this.methodConfigs.set(e,t),this}configureStandardMethods(){return this.config.sourceType===`agent`&&(this.configureMethod(`run`,{startEvent:A.EXECUTION_START,completeEvent:A.EXECUTION_COMPLETE,errorEvent:A.EXECUTION_ERROR,extractMetadata:(e,t,n)=>({inputLength:jc(n[0]),conversationId:e.conversationId,options:Z(n[1])||{}}),extractResult:e=>({response:e})}),this.configureMethod(`runStream`,{startEvent:A.EXECUTION_START,completeEvent:A.EXECUTION_COMPLETE,errorEvent:A.EXECUTION_ERROR,extractMetadata:(e,t,n)=>({inputLength:jc(n[0]),conversationId:e.conversationId,streaming:!0,options:Z(n[1])||{}})})),this.config.sourceType===`tool`&&this.configureMethod(`execute`,{startEvent:M.CALL_START,completeEvent:M.CALL_COMPLETE,errorEvent:M.CALL_ERROR,extractMetadata:(e,t,n)=>({toolName:Z(e.schema)?.name||e.constructor.name,parameters:n[0],parametersCount:Z(n[0])?Object.keys(Z(n[0])||{}).length:0,context:n[1]}),extractResult:e=>({result:typeof Z(e)?.data==`string`?Z(e)?.data||``:JSON.stringify(Z(e)?.data),success:Z(e)?.success})}),this}wrap(e){return new Proxy(e,{get:(e,t,n)=>{let r=Reflect.get(e,t,n);if(typeof t!=`string`)return r;let i=t;if(typeof r==`function`&&this.methodConfigs.has(i)){let t=this.methodConfigs.get(i);return async(...n)=>{let a=Date.now(),o=this.generateExecutionId(),s=e;try{if(t.startEvent){let e=t.extractMetadata?.(s,i,n)||{};this.emitEvent(t.startEvent,{timestamp:new Date,metadata:{...e,executionId:o,methodName:i,phase:`start`}})}let c=await r.apply(e,n),l=Date.now()-a;if(t.completeEvent){let e=t.extractResult?.(c)||{},r=t.extractMetadata?.(s,i,n)||{};this.emitEvent(t.completeEvent,{timestamp:new Date,...e,metadata:{...r,executionId:o,methodName:i,duration:l,phase:`complete`,success:!0}})}return c}catch(e){let r=Date.now()-a;if(t.errorEvent){let a=t.extractMetadata?.(s,i,n)||{};this.emitEvent(t.errorEvent,{timestamp:new Date,error:e instanceof Error?e.message:String(e),metadata:{...a,executionId:o,methodName:i,duration:r,phase:`error`,errorName:e instanceof Error?e.name:`UnknownError`,success:!1}})}throw e}}}return r}})}emitEvent(e,t){let n={emitterSourceType:this.config.sourceType,emitterSourceId:this.config.sourceId},r={timestamp:new Date,...t.metadata?{metadata:{...n,...t.metadata}}:{metadata:n},...t};this.config.eventService.emit(e,r)}generateExecutionId(){return`${this.config.sourceType}-${this.config.sourceId}-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}};function Nc(e,t){let n=new Mc(t);return n.configureStandardMethods(),n.wrap(e)}function Pc(e,t,n){return function(r){return Nc(r,{eventService:e,sourceType:t,sourceId:n})}}const Fc={safe:`plan`,moderate:`default`,full:`acceptEdits`},Ic=`inherit-allowlist`;function Lc(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 Rc(e){let t={segments:[],current:``,quote:void 0,substitutionDepth:0};for(let n=0;n<e.length;n+=1){let r=Bc(t,e,n);if(r!==void 0){n=r;continue}let i=Vc(t,e,n);if(i!==void 0){n=i;continue}if(Hc(t,e[n]))continue;let a=Uc(t,e,n);if(a!==void 0){n=a;continue}t.current+=e[n]}return zc(t),t.segments}function zc(e){let t=e.current.trim();t!==``&&e.segments.push(t),e.current=``}function Bc(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 Vc(e,t,n){let r=t[n];if(r==="`")return zc(e),n;if(r===`$`&&t[n+1]===`(`)return zc(e),e.substitutionDepth+=1,n+1}function Hc(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 Uc(e,t,n){let r=t[n];if((r===`<`||r===`>`)&&t[n+1]===`(`)return zc(e),e.substitutionDepth+=1,n+1;if(r===`)`&&e.substitutionDepth>0)return zc(e),--e.substitutionDepth,n;if(r===`;`||r===`|`||r===`
|
|
11
|
-
`||r===`&`&&Wc(t,n))return zc(e),n}function Wc(e,t){let n=e[t-1];return n!==`>`&&n!==`<`&&e[t+1]!==`>`}const Gc=/[.+^${}()|[\]\\]/g;function Kc(e){let t=e.replace(Gc,`\\$&`).replace(/\*\*/g,`.+`).replace(/\*/g,`.*`);return RegExp(`^${t}$`)}function qc(e,t,n){let r=Kc(e);return n===`deny`?r.test(t)||Rc(t).some(e=>r.test(e))?`match`:`no-match`:r.test(t)?e.includes(`*`)&&Lc(t)?`no-match`:`match`:`no-match`}function Jc(e){let t=e.replace(/\*\*(?:\/\*\*)+/g,`**`).split(/(\/\*\*\/|\/\*\*$|^\*\*\/|\*\*)/).map(e=>e===`/**/`?`(?:/.*)?/`:e===`/**`?`(?:/.*)?`:e===`**/`?`(?:.*/)?`:e===`**`?`.*`:e.replace(Gc,`\\$&`).replace(/\*/g,`[^/]*`).replace(/\uE000/g,`\\*`)).join(``);return RegExp(`^${t}$`)}function Yc(e){return e.startsWith(`/`)||/^[A-Za-z]:(?=\/|$)/.test(e)}function Xc(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 Zc(e,t){let n=Xc(e),r=Xc(t);return Yc(n)&&!Yc(r)?`unevaluable`:Jc(n).test(r)?`match`:`no-match`}const Qc=/^(\*|[a-z][a-z0-9+.-]*):\/\/(\[[0-9a-fA-F:.]+\]|[^/\\:?#@[\]]+)(?::(\d+|\*))?(\/[^?#]*)?$/i,$c=new Set([`http`,`https`,`ws`,`wss`,`ftp`]),el={http:`80`,https:`443`,ws:`80`,wss:`443`,ftp:`21`};function tl(e){return e.replace(/\.$/,``).toLowerCase()}function nl(e){try{let t=new URL(`http://${e}/`).hostname;return t===``||t.includes(`.`)?null:t}catch{return null}}function rl(e,t=!1){let n=tl(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(Gc,`\\$&`).replace(/\*/g,`[^.]*`)}`);else{let e=nl(a);if(e===null)return null;r.push(`${l}${e.replace(Gc,`\\$&`)}`)}}return RegExp(`^${r.join(``)}$`)}function il(e){try{let t=e.split(`/`).map(e=>decodeURIComponent(e));return t.some(e=>e.includes(`/`))?null:t.join(`/`)}catch{return null}}function al(e){let t;try{t=new URL(e)}catch{return null}let n=t.protocol.slice(0,-1).toLowerCase();return!$c.has(n)||t.hostname===``||t.username!==``||t.password!==``?null:t}function ol(e,t,n=!1){if(e.includes(`*`)){let r=rl(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 tl(r)===t?`match`:`no-match`}function sl(e,t,n){return e===void 0?t.port===``:e===`*`||e===(t.port===``?el[n]:t.port)}function cl(e,t){let n=il(t),r=il(e.replace(/%2a/gi,``));return n===null||r===null?`unevaluable`:Jc(r).test(n)?`match`:`no-match`}function ll(e,t){let n=Qc.exec(e);if(n===null)return`unevaluable`;let[,r,i,a,o]=n,s=al(t);if(s===null)return`unevaluable`;let c=s.protocol.slice(0,-1).toLowerCase();if(r!==`*`&&r.toLowerCase()!==c)return`no-match`;let l=ol(i,tl(s.hostname));return l===`match`?sl(a,s,c)?o===void 0?`match`:cl(o,s.pathname):`no-match`:l}function ul(e,t){if(!e.startsWith(`domain:`))return ll(e,t);let n=/^domain:([^/\\:?#@[\]\s]+)$/.exec(e);if(n===null)return`unevaluable`;let r=tl(n[1]);if(r.includes(`**`)||r.split(`.`).some(e=>e===``))return`unevaluable`;let i=al(t);return i===null||i.protocol!==`http:`&&i.protocol!==`https:`?`unevaluable`:ol(r,tl(i.hostname),!0)}const dl={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`}},fl={plan:`deny`,default:`approve`,acceptEdits:`approve`,bypassPermissions:`auto`,auto:`approve`},pl=[`.git`,`.claude`,`.agents`],ml=[`.mcp.json`,`.gitconfig`,`.npmrc`,`.bashrc`,`.bash_profile`,`.bash_login`,`.zshrc`,`.zshenv`,`.zprofile`,`.profile`];function hl(e){return e.replace(/\\/g,`/`).split(`/`).filter(e=>e!==``&&e!==`.`)}function gl(e){let t=[];for(let n of hl(e))n===`..`&&t.length>0&&t[t.length-1]!==`..`?t.pop():t.push(n);return t}function _l(e,t={}){let n=t.pathProtection,r=bl.exec(e),i=r!==null&&t.homeDirectory!==void 0?`${t.homeDirectory}/${r[1]??``}`:e,a=i.startsWith(`/`)?vl(i):t.cwd===void 0?void 0:vl(`${t.cwd}/${i}`);if(a!==void 0&&n?.protectedPaths.some(e=>{let t=vl(e);return a===t||a.startsWith(`${t}/`)}))return!0;let o=gl(i),s=o[o.length-1];if(s!==void 0&&ml.includes(s))return!0;let c=[...pl,...n?.protectedDirectoryNames??[]],l=[`.claude/worktrees`,...n?.writableWorktreeContainers??[]].map(gl);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 vl(e){let t=[];for(let n of hl(e))n===`..`?t.pop():t.push(n);return`/${t.join(`/`)}`}function yl(e){return e.replace(/^(['"])(.*)\1$/,`$2`)}const bl=/^(?:~|\$HOME|\$\{HOME\})(?=\/|$)(.*)$/;function xl(e,t){let n=yl(e),r=bl.exec(n),i;if(r!==null){let e=r[1]??``;if(t.homeDirectory===void 0)return e.replace(/\/+/g,``)===``;i=vl(`${t.homeDirectory}/${e}`)}else if(n===``||n.startsWith(`$`))return!1;else if(n.startsWith(`/`))i=vl(n);else{if(t.cwd===void 0)return!1;i=vl(`${t.cwd}/${n}`)}if(hl(i).length<=1||t.homeDirectory!==void 0&&i===vl(t.homeDirectory))return!0;if(t.cwd!==void 0){let e=vl(t.cwd);if(e===i||e.startsWith(`${i}/`))return!0}return!1}const Sl=new Set([`rm`,`rmdir`]),Cl=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 wl(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=Cl.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 Tl(e,t){return Rc(e).some(e=>{let n=e.split(/\s+/).filter(e=>e!==``),r=wl(n),i=n[r];if(i===void 0)return!1;let a=i.slice(i.lastIndexOf(`/`)+1);if(!Sl.has(a))return!1;let o=!1;return n.slice(r+1).some(e=>!o&&e===`--`?(o=!0,!1):!o&&e.startsWith(`-`)?!1:xl(e,t))})}const El=new Set([`ls`,`cat`,`echo`,`pwd`,`head`,`tail`,`grep`,`wc`,`which`,`stat`,`du`,`cd`]),Dl=new Set([`-exec`,`-execdir`,`-ok`,`-okdir`,`-delete`,`-fprint`,`-fprint0`,`-fprintf`,`-fls`]),Ol={ls:`aAlhtrSR1dFGinpsucCgmoQvx`,cat:`nbsvetAE`,head:`nqvc`,tail:`nqvcfF`,grep:`rinlLvcwxEFGPHhoqsABCmz`,wc:`lwcmL`,stat:`cftx`,du:`hsacdkmx`,which:`a`,pwd:`LP`,cd:`LP`},kl=/^--?[A-Za-z0-9-]*(file|from|contents)(=|$)/,Al=[`--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 jl(e){if(!e.startsWith(`--`)||e.length<=2)return!1;let t=e.split(`=`,1)[0];return Al.some(e=>e.startsWith(t))}function Ml(e,t){if(Wl(t).some(e=>kl.test(e.text)||jl(e.text)))return!0;if(e===`find`)return Wl(t).some(e=>e.text===`-L`||e.text===`-follow`);let n=Ol[e];return n!==void 0&&Wl(t).some(({text:e})=>e.startsWith(`--`)||!/^-[A-Za-z]/.test(e)?!1:[...e.slice(1)].some(e=>!/\d/.test(e)&&!n.includes(e)))}const Nl=new Set([`status`,`log`,`diff`,`show`,`rev-parse`,`ls-files`,`describe`,`branch`,`remote`]),Pl=new Set([`-l`,`--list`,`--show-current`,`--merged`,`--no-merged`,`--contains`,`--no-contains`,`--points-at`]),Fl=new Set([`-a`,`--all`,`-r`,`--remotes`,`-v`,`-vv`,`--verbose`,`--color`,`--no-color`]),Il=new Set([`/dev/null`]),Ll=/[A-Za-z0-9_./:=@+,*?[\]~-]/,Rl=new Set([`$`,"`",`\\`,`!`]),zl=new Set([`*`,`?`,`[`]);function Bl(e){return/(^|[=,:])[/~]/.test(e)||/^-[A-Za-z]+[/~]/.test(e)||/(^|[/=,:]|^-[A-Za-z]+)\.\.(\/|$)/.test(e)||/(^|[=,])[A-Za-z][A-Za-z0-9]*:/.test(e)||Vl(e)}function Vl(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 Hl(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 Ul(e){let t=[],n=``,r=!1,i=!1,a,o,s=!1,c=()=>{i&&=(o===`output`?(!Il.has(n)||r)&&(s=!0):o===`duplicate`?/^(\d+|-)$/.test(n)||(s=!0):o===`input`?(r||Bl(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:Rl.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(!Ll.test(l)){s=!0;break}zl.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 Wl(e){let t=e.findIndex(e=>e.text===`--`);return(t<0?e:e.slice(0,t)).filter(e=>e.text.startsWith(`-`))}function Gl(e){return e.every(e=>!e.expands&&!Dl.has(e.text))}function Kl(e){let t=e.filter(e=>e.text.startsWith(`-`)),n=t.some(e=>Pl.has(e.text));return t.every(e=>Pl.has(e.text)||Fl.has(e.text))&&(n||t.length===e.length)}function ql(e){let[t,...n]=e[0]?.text===`--no-pager`?e.slice(1):e;return t===void 0||t.expands||!Nl.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`?Kl(n):t.text!==`remote`||n.every(e=>e.text===`-v`||e.text===`--verbose`)}function Jl(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=>Bl(e.text))||Ml(t.text,n)?!1:t.text===`cd`?n.length===1&&n[0].text!==`-`&&!n[0].expands:El.has(t.text)?!0:t.text===`find`?Gl(n):t.text===`git`&&ql(n)}const Yl=new Set([`echo`,`which`,`git`]);function Xl(e,t){let n;for(let[r,...i]of e)if(!Yl.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 Zl(e,t={}){if(t.otherDirectory===!0||e.length>1e4||Hl(e)||/[^\t\n\x20-\x7e]/.test(e))return!1;let n=Rc(e);if(n.length===0)return!1;let r=n.map(Ul);if(r.some(e=>e.refused||!Jl(e.words)))return!1;let i=r.map(e=>e.words[0].text);return i.includes(`git`)&&i.includes(`cd`)?!1:Xl(r.map(e=>e.words),t.resolveInWorkspace)}function Ql(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 $l(e,t){Q.set(e,{...Q.get(e),...t})}function eu(){Q.clear()}function tu(e){return Q.get(e)??{}}function nu(e,t){let n=[t,...Q.get(t)?.aliases??[]];if(!e.includes(`*`))return n.includes(e);let r=Kc(e);return n.some(e=>r.test(e))}function ru(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 iu(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`:Kc(e.value).test(String(n))?`match`:`no-match`}function au(e,t){return t.some(t=>{let n=Ql(t);return(n.argPattern===void 0||n.argPattern===`*`||n.argPattern===`**`)&&nu(n.toolName,e)})}function ou(e){return Q.get(e)?.argument?.key}function su(e,t){let n=ou(e);if(n===void 0)return;let r=t[n];return typeof r==`string`?r:void 0}function cu(e,t,n,r=`allow`){return n.some(n=>uu(e,t,n,r)===`match`)}function lu(e,t,n){return n.some(n=>uu(e,t,n,`deny`)===`unevaluable`)}function uu(e,t,n,r){let i=Ql(n);if(!nu(i.toolName,e))return`no-match`;if(i.argPattern===void 0||i.argPattern===`*`||i.argPattern===`**`)return`match`;let a=ru(e,i.argPattern);if(a===`primary`)return`unevaluable`;if(a!==void 0)return r===`deny`?iu(a,t):`no-match`;let o=Q.get(e)?.argument;if(o===void 0)return`unevaluable`;let s=su(e,t);if(s===void 0)return`no-match`;switch(o.kind){case`url`:return e===`WebFetch`?ul(i.argPattern,s):ll(i.argPattern,s);case`path`:return Zc(i.argPattern,s);case`command`:return qc(i.argPattern,s,r);case`text`:return Kc(i.argPattern).test(s)?`match`:`no-match`;default:{let e=o.kind;throw Error(`unknown argument kind: ${String(e)}`)}}}function du(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`?Tl(a,n):i.kind===`path`&&r?.riskClass===`modify`&&_l(a,n):!1}function fu(e,t,n,r){return cu(e,t,n,`deny`)||lu(e,t,n)||du(e,t,r)}function pu(e,t,n={},r={}){return lu(e,t,n.deny??[])||fu(e,t,n.ask??[],r)}const mu=[`workingDirectory`,`cwd`];function hu(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`&&Zl(i,{otherDirectory:mu.some(e=>t[e]!==void 0),...n.resolveInWorkspace===void 0?{}:{resolveInWorkspace:n.resolveInWorkspace}})?`inspect`:r.riskClass}function gu(e,t,n,r={},i={}){let{allow:a=[],deny:o=[],ask:s=[]}=r,c=hu(e,t,i),l=n===`plan`&&c!==`inspect`?`deny`:`approve`;return cu(e,t,o,`deny`)||i.ceiling!==void 0&&!cu(e,t,i.ceiling)||Q.get(e)?.repliesToPeer===!0&&i.peerTurn!==!0||Q.get(e)?.notInPeerTurn===!0&&i.peerTurn===!0?`deny`:lu(e,t,o)?n===`plan`?`deny`:`approve`:fu(e,t,s,i)||i.askAll===!0?l:n===`bypassPermissions`||cu(e,t,a)||i.sandboxAutoApproved===!0&&c===`execute`&&(n==="default"||n===`acceptEdits`||n===`auto`)?`auto`:c===void 0?fl[n]:dl[n][c]}function _u(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 vu=/^[A-Za-z_]\w*:(?!\/\/)/;function yu(e){return e.slice(0,e.indexOf(`*`)).includes(`__`)}function bu(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}=Ql(n);if(r===``)return`names no tool`;if(t===`allow`&&r.includes(`*`)&&!yu(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`&&vu.test(i)?`matches a named parameter, which only deny and ask rules may do`:void 0;let a=ru(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=tu(r);if(!(o.parameters===void 0&&vu.test(i)&&ru(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`?ul:ll)(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 xu(e,t=`deny`){let n=[];for(let r of e){let e=bu(r,t);e!==void 0&&n.push({pattern:r,reason:e})}return n}function Su(e){let t=[];for(let n of e){let{toolName:e,argPattern:r}=Ql(n.trim());if(r===void 0||e.includes(`*`))continue;let i=tu(e),a=ru(e,r);if(a===void 0&&i.parameters!==void 0&&i.argument?.kind!==`url`&&vu.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=tu(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 Cu(e){return(e??[]).map(e=>`${e}(*)`)}function wu(e,t){let n=Cu(t.allowedTools),r=xu(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,...Cu(t.deniedTools)])]}}const Tu=[`Bash`,`Shell`,`BackgroundProcess`],Eu=[`Agent`],Du=[...Tu,...Eu,`ExecuteCommand`,`Computer`],Ou=`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(`.`),ku=[`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(` `)),Au=new Set([`run`,`run-script`,`exec`,`dlx`,`x`,`--`]);function ju(e){return(e.split(/[\\/]/).pop()??e).replace(/(\.exe)?$/i,``).replace(/[\d.]+$/,``)}function Mu(e,t){if(e.length===0)return!0;let n=(e,n,r)=>t&&r?e.startsWith(n):e===n,r=ju(e[0]);if(Ou.some(t=>n(t,r,e.length===1)))return!0;for(let i of ku){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(`-`)||Au.has(o[0]));)o=o.slice(1);return o.length===0||Mu(o,t)}return!1}function Nu(e){let t=e.trim();if(!t.includes(`*`))return!1;let n=t.slice(0,t.indexOf(`*`));return Mu(n.trim().split(/\s+/).filter(e=>e.length>0),n.length>0&&!/\s$/.test(n))}function Pu(e){let{toolName:t,argPattern:n}=Ql(e),r=e=>e.some(e=>nu(t,e));return r(Eu)?!0:t.includes(`*`)?r(Du):Du.includes(t)||tu(t).riskClass===`execute`?n===void 0||n.trim()===`*`||Tu.includes(t)&&Nu(n):!1}function Fu(e){return e.filter(e=>!Pu(e))}const Iu=1e6,Lu={"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}},Ru=[{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 zu(e){let t=Object.hasOwn(Lu,e)?Lu[e]:void 0;if(t)return t;for(let{pattern:t,price:n}of Ru)if(t.test(e))return n}function Bu(e,t,n){let r=zu(e);if(r)return t/Iu*r.inputPerMillion+n/Iu*r.outputPerMillion}function Vu(e){let t=zu(e);if(t)return(t.inputPerMillion+t.outputPerMillion)/2/1e3}function Hu(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 Uu(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 Wu(){let[{CommandExecutor:e},{HttpExecutor:t}]=await Promise.all([import(`./command-executor-D_UBZHxh.js`).then(e=>e.n),import(`./http-executor-ADn4locH.js`).then(e=>e.n)]);return[new e,new t]}async function Gu(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 Wu(),u=new Map;for(let e of l)u.set(e.type,e);let d=[],f=Uu(n),p=-1,m,h;for(let e of c){if(!Hu(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===`&`&&Wc(t,n))return zc(e),n}function Wc(e,t){let n=e[t-1];return n!==`>`&&n!==`<`&&e[t+1]!==`>`}const Gc=/[.+^${}()|[\]\\]/g;function Kc(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 qc(e){let t=e.replace(Gc,`\\$&`).replace(/\*\*/g,`.+`).replace(/\*/g,`.*`);return RegExp(`^${t}$`)}function Jc(e,t,n){let r=qc(e);if(n===`deny`){if(r.test(t))return`match`;let n=Rc(t);if(n.some(e=>r.test(e)))return`match`;let i=Kc(e,!0);if(i===void 0)return`unevaluable`;let a=qc(i);for(let e of n){let t=Kc(e,!1);if(t!==void 0&&a.test(t))return`match`}return`unevaluable`}return r.test(t)?e.includes(`*`)&&Lc(t)?`no-match`:`match`:`no-match`}function Yc(e){let t=e.replace(/\*\*(?:\/\*\*)+/g,`**`).split(/(\/\*\*\/|\/\*\*$|^\*\*\/|\*\*)/).map(e=>e===`/**/`?`(?:/.*)?/`:e===`/**`?`(?:/.*)?`:e===`**/`?`(?:.*/)?`:e===`**`?`.*`:e.replace(Gc,`\\$&`).replace(/\*/g,`[^/]*`).replace(/\uE000/g,`\\*`)).join(``);return RegExp(`^${t}$`)}function Xc(e){return e.startsWith(`/`)||/^[A-Za-z]:(?=\/|$)/.test(e)}function Zc(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 Qc(e,t){let n=Zc(e),r=Zc(t);return Xc(n)&&!Xc(r)?`unevaluable`:Yc(n).test(r)?`match`:`no-match`}const $c=/^(\*|[a-z][a-z0-9+.-]*):\/\/(\[[0-9a-fA-F:.]+\]|[^/\\:?#@[\]]+)(?::(\d+|\*))?(\/[^?#]*)?$/i,el=new Set([`http`,`https`,`ws`,`wss`,`ftp`]),tl={http:`80`,https:`443`,ws:`80`,wss:`443`,ftp:`21`};function nl(e){return e.replace(/\.$/,``).toLowerCase()}function rl(e){try{let t=new URL(`http://${e}/`).hostname;return t===``||t.includes(`.`)?null:t}catch{return null}}function il(e,t=!1){let n=nl(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(Gc,`\\$&`).replace(/\*/g,`[^.]*`)}`);else{let e=rl(a);if(e===null)return null;r.push(`${l}${e.replace(Gc,`\\$&`)}`)}}return RegExp(`^${r.join(``)}$`)}function al(e){try{let t=e.split(`/`).map(e=>decodeURIComponent(e));return t.some(e=>e.includes(`/`))?null:t.join(`/`)}catch{return null}}function ol(e){let t;try{t=new URL(e)}catch{return null}let n=t.protocol.slice(0,-1).toLowerCase();return!el.has(n)||t.hostname===``||t.username!==``||t.password!==``?null:t}function sl(e,t,n=!1){if(e.includes(`*`)){let r=il(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 nl(r)===t?`match`:`no-match`}function cl(e,t,n){return e===void 0?t.port===``:e===`*`||e===(t.port===``?tl[n]:t.port)}function ll(e,t){let n=al(t),r=al(e.replace(/%2a/gi,``));return n===null||r===null?`unevaluable`:Yc(r).test(n)?`match`:`no-match`}function ul(e,t){let n=$c.exec(e);if(n===null)return`unevaluable`;let[,r,i,a,o]=n,s=ol(t);if(s===null)return`unevaluable`;let c=s.protocol.slice(0,-1).toLowerCase();if(r!==`*`&&r.toLowerCase()!==c)return`no-match`;let l=sl(i,nl(s.hostname));return l===`match`?cl(a,s,c)?o===void 0?`match`:ll(o,s.pathname):`no-match`:l}function dl(e,t){if(!e.startsWith(`domain:`))return ul(e,t);let n=/^domain:([^/\\:?#@[\]\s]+)$/.exec(e);if(n===null)return`unevaluable`;let r=nl(n[1]);if(r.includes(`**`)||r.split(`.`).some(e=>e===``))return`unevaluable`;let i=ol(t);return i===null||i.protocol!==`http:`&&i.protocol!==`https:`?`unevaluable`:sl(r,nl(i.hostname),!0)}const fl={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`}},pl={plan:`deny`,default:`approve`,acceptEdits:`approve`,bypassPermissions:`auto`,auto:`approve`},ml=[`.git`,`.claude`,`.agents`],hl=[`.mcp.json`,`.gitconfig`,`.npmrc`,`.bashrc`,`.bash_profile`,`.bash_login`,`.zshrc`,`.zshenv`,`.zprofile`,`.profile`];function gl(e){return e.replace(/\\/g,`/`).split(`/`).filter(e=>e!==``&&e!==`.`)}function _l(e){let t=[];for(let n of gl(e))n===`..`&&t.length>0&&t[t.length-1]!==`..`?t.pop():t.push(n);return t}function vl(e,t={}){let n=t.pathProtection,r=xl.exec(e),i=r!==null&&t.homeDirectory!==void 0?`${t.homeDirectory}/${r[1]??``}`:e,a=i.startsWith(`/`)?yl(i):t.cwd===void 0?void 0:yl(`${t.cwd}/${i}`);if(a!==void 0&&n?.protectedPaths.some(e=>{let t=yl(e);return a===t||a.startsWith(`${t}/`)}))return!0;let o=_l(i),s=o[o.length-1];if(s!==void 0&&hl.includes(s))return!0;let c=[...ml,...n?.protectedDirectoryNames??[]],l=[`.claude/worktrees`,...n?.writableWorktreeContainers??[]].map(_l);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 yl(e){let t=[];for(let n of gl(e))n===`..`?t.pop():t.push(n);return`/${t.join(`/`)}`}function bl(e){return e.replace(/^(['"])(.*)\1$/,`$2`)}const xl=/^(?:~|\$HOME|\$\{HOME\})(?=\/|$)(.*)$/;function Sl(e,t){let n=bl(e),r=xl.exec(n),i;if(r!==null){let e=r[1]??``;if(t.homeDirectory===void 0)return e.replace(/\/+/g,``)===``;i=yl(`${t.homeDirectory}/${e}`)}else if(n===``||n.startsWith(`$`))return!1;else if(n.startsWith(`/`))i=yl(n);else{if(t.cwd===void 0)return!1;i=yl(`${t.cwd}/${n}`)}if(gl(i).length<=1||t.homeDirectory!==void 0&&i===yl(t.homeDirectory))return!0;if(t.cwd!==void 0){let e=yl(t.cwd);if(e===i||e.startsWith(`${i}/`))return!0}return!1}const Cl=new Set([`rm`,`rmdir`]),wl=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 Tl(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=wl.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 El(e,t){return Rc(e).some(e=>{let n=e.split(/\s+/).filter(e=>e!==``),r=Tl(n),i=n[r];if(i===void 0)return!1;let a=i.slice(i.lastIndexOf(`/`)+1);if(!Cl.has(a))return!1;let o=!1;return n.slice(r+1).some(e=>!o&&e===`--`?(o=!0,!1):!o&&e.startsWith(`-`)?!1:Sl(e,t))})}const Dl=new Set([`ls`,`cat`,`echo`,`pwd`,`head`,`tail`,`grep`,`wc`,`which`,`stat`,`du`,`cd`]),Ol=new Set([`-exec`,`-execdir`,`-ok`,`-okdir`,`-delete`,`-fprint`,`-fprint0`,`-fprintf`,`-fls`]),kl={ls:`aAlhtrSR1dFGinpsucCgmoQvx`,cat:`nbsvetAE`,head:`nqvc`,tail:`nqvcfF`,grep:`rinlLvcwxEFGPHhoqsABCmz`,wc:`lwcmL`,stat:`cftx`,du:`hsacdkmx`,which:`a`,pwd:`LP`,cd:`LP`},Al=/^--?[A-Za-z0-9-]*(file|from|contents)(=|$)/,jl=[`--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 Ml(e){if(!e.startsWith(`--`)||e.length<=2)return!1;let t=e.split(`=`,1)[0];return jl.some(e=>e.startsWith(t))}function Nl(e,t){if(Gl(t).some(e=>Al.test(e.text)||Ml(e.text)))return!0;if(e===`find`)return Gl(t).some(e=>e.text===`-L`||e.text===`-follow`);let n=kl[e];return n!==void 0&&Gl(t).some(({text:e})=>e.startsWith(`--`)||!/^-[A-Za-z]/.test(e)?!1:[...e.slice(1)].some(e=>!/\d/.test(e)&&!n.includes(e)))}const Pl=new Set([`status`,`log`,`diff`,`show`,`rev-parse`,`ls-files`,`describe`,`branch`,`remote`]),Fl=new Set([`-l`,`--list`,`--show-current`,`--merged`,`--no-merged`,`--contains`,`--no-contains`,`--points-at`]),Il=new Set([`-a`,`--all`,`-r`,`--remotes`,`-v`,`-vv`,`--verbose`,`--color`,`--no-color`]),Ll=new Set([`/dev/null`]),Rl=/[A-Za-z0-9_./:=@+,*?[\]~-]/,zl=new Set([`$`,"`",`\\`,`!`]),Bl=new Set([`*`,`?`,`[`]);function Vl(e){return/(^|[=,:])[/~]/.test(e)||/^-[A-Za-z]+[/~]/.test(e)||/(^|[/=,:]|^-[A-Za-z]+)\.\.(\/|$)/.test(e)||/(^|[=,])[A-Za-z][A-Za-z0-9]*:/.test(e)||Hl(e)}function Hl(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 Ul(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 Wl(e){let t=[],n=``,r=!1,i=!1,a,o,s=!1,c=()=>{i&&=(o===`output`?(!Ll.has(n)||r)&&(s=!0):o===`duplicate`?/^(\d+|-)$/.test(n)||(s=!0):o===`input`?(r||Vl(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:zl.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(!Rl.test(l)){s=!0;break}Bl.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 Gl(e){let t=e.findIndex(e=>e.text===`--`);return(t<0?e:e.slice(0,t)).filter(e=>e.text.startsWith(`-`))}function Kl(e){return e.every(e=>!e.expands&&!Ol.has(e.text))}function ql(e){let t=e.filter(e=>e.text.startsWith(`-`)),n=t.some(e=>Fl.has(e.text));return t.every(e=>Fl.has(e.text)||Il.has(e.text))&&(n||t.length===e.length)}function Jl(e){let[t,...n]=e[0]?.text===`--no-pager`?e.slice(1):e;return t===void 0||t.expands||!Pl.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`?ql(n):t.text!==`remote`||n.every(e=>e.text===`-v`||e.text===`--verbose`)}function Yl(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=>Vl(e.text))||Nl(t.text,n)?!1:t.text===`cd`?n.length===1&&n[0].text!==`-`&&!n[0].expands:Dl.has(t.text)?!0:t.text===`find`?Kl(n):t.text===`git`&&Jl(n)}const Xl=new Set([`echo`,`which`,`git`]);function Zl(e,t){let n;for(let[r,...i]of e)if(!Xl.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 Ql(e,t={}){if(t.otherDirectory===!0||e.length>1e4||Ul(e)||/[^\t\n\x20-\x7e]/.test(e))return!1;let n=Rc(e);if(n.length===0)return!1;let r=n.map(Wl);if(r.some(e=>e.refused||!Yl(e.words)))return!1;let i=r.map(e=>e.words[0].text);return i.includes(`git`)&&i.includes(`cd`)?!1:Zl(r.map(e=>e.words),t.resolveInWorkspace)}function $l(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 eu(e,t){Q.set(e,{...Q.get(e),...t})}function tu(){Q.clear()}function nu(e){return Q.get(e)??{}}function ru(e,t){let n=[t,...Q.get(t)?.aliases??[]];if(!e.includes(`*`))return n.includes(e);let r=qc(e);return n.some(e=>r.test(e))}function iu(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 au(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`:qc(e.value).test(String(n))?`match`:`no-match`}function ou(e,t){return t.some(t=>{let n=$l(t);return(n.argPattern===void 0||n.argPattern===`*`||n.argPattern===`**`)&&ru(n.toolName,e)})}function su(e){return Q.get(e)?.argument?.key}function cu(e,t){let n=su(e);if(n===void 0)return;let r=t[n];return typeof r==`string`?r:void 0}function lu(e,t,n,r=`allow`){return n.some(n=>du(e,t,n,r)===`match`)}function uu(e,t,n){return n.some(n=>du(e,t,n,`deny`)===`unevaluable`)}function du(e,t,n,r){let i=$l(n);if(!ru(i.toolName,e))return`no-match`;if(i.argPattern===void 0||i.argPattern===`*`||i.argPattern===`**`)return`match`;let a=iu(e,i.argPattern);if(a===`primary`)return`unevaluable`;if(a!==void 0)return r===`deny`?au(a,t):`no-match`;let o=Q.get(e)?.argument;if(o===void 0)return`unevaluable`;let s=cu(e,t);if(s===void 0)return`no-match`;switch(o.kind){case`url`:return e===`WebFetch`?dl(i.argPattern,s):ul(i.argPattern,s);case`path`:return Qc(i.argPattern,s);case`command`:return Jc(i.argPattern,s,r);case`text`:return qc(i.argPattern).test(s)?`match`:`no-match`;default:{let e=o.kind;throw Error(`unknown argument kind: ${String(e)}`)}}}function fu(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`?El(a,n):i.kind===`path`&&r?.riskClass===`modify`&&vl(a,n):!1}function pu(e,t,n,r){return lu(e,t,n,`deny`)||uu(e,t,n)||fu(e,t,r)}function mu(e,t,n={},r={}){return uu(e,t,n.deny??[])||pu(e,t,n.ask??[],r)}const hu=[`workingDirectory`,`cwd`];function gu(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`&&Ql(i,{otherDirectory:hu.some(e=>t[e]!==void 0),...n.resolveInWorkspace===void 0?{}:{resolveInWorkspace:n.resolveInWorkspace}})?`inspect`:r.riskClass}function _u(e,t,n,r={},i={}){let{allow:a=[],deny:o=[],ask:s=[]}=r,c=gu(e,t,i),l=n===`plan`&&c!==`inspect`?`deny`:`approve`;return lu(e,t,o,`deny`)||i.ceiling!==void 0&&!lu(e,t,i.ceiling)||Q.get(e)?.repliesToPeer===!0&&i.peerTurn!==!0||Q.get(e)?.notInPeerTurn===!0&&i.peerTurn===!0?`deny`:uu(e,t,o)?n===`plan`?`deny`:`approve`:pu(e,t,s,i)||i.askAll===!0?l:n===`bypassPermissions`||lu(e,t,a)||i.sandboxAutoApproved===!0&&c===`execute`&&(n==="default"||n===`acceptEdits`||n===`auto`)?`auto`:c===void 0?pl[n]:fl[n][c]}function vu(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 yu=/^[A-Za-z_]\w*:(?!\/\/)/;function bu(e){return e.slice(0,e.indexOf(`*`)).includes(`__`)}function xu(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}=$l(n);if(r===``)return`names no tool`;if(t===`allow`&&r.includes(`*`)&&!bu(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`&&yu.test(i)?`matches a named parameter, which only deny and ask rules may do`:void 0;let a=iu(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=nu(r);if(!(o.parameters===void 0&&yu.test(i)&&iu(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`?dl:ul)(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 Su(e,t=`deny`){let n=[];for(let r of e){let e=xu(r,t);e!==void 0&&n.push({pattern:r,reason:e})}return n}function Cu(e){let t=[];for(let n of e){let{toolName:e,argPattern:r}=$l(n.trim());if(r===void 0||e.includes(`*`))continue;let i=nu(e),a=iu(e,r);if(a===void 0&&i.parameters!==void 0&&i.argument?.kind!==`url`&&yu.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=nu(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 wu(e){return(e??[]).map(e=>`${e}(*)`)}function Tu(e,t){let n=wu(t.allowedTools),r=Su(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,...wu(t.deniedTools)])]}}const Eu=[`Bash`,`Shell`,`BackgroundProcess`],Du=[`Agent`],Ou=[...Eu,...Du,`ExecuteCommand`,`Computer`],ku=`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(`.`),Au=[`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(` `)),ju=new Set([`run`,`run-script`,`exec`,`dlx`,`x`,`--`]);function Mu(e){return(e.split(/[\\/]/).pop()??e).replace(/(\.exe)?$/i,``).replace(/[\d.]+$/,``)}function Nu(e,t){if(e.length===0)return!0;let n=(e,n,r)=>t&&r?e.startsWith(n):e===n,r=Mu(e[0]);if(ku.some(t=>n(t,r,e.length===1)))return!0;for(let i of Au){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(`-`)||ju.has(o[0]));)o=o.slice(1);return o.length===0||Nu(o,t)}return!1}function Pu(e){let t=e.trim();if(!t.includes(`*`))return!1;let n=t.slice(0,t.indexOf(`*`));return Nu(n.trim().split(/\s+/).filter(e=>e.length>0),n.length>0&&!/\s$/.test(n))}function Fu(e){let{toolName:t,argPattern:n}=$l(e),r=e=>e.some(e=>ru(t,e));return r(Du)?!0:t.includes(`*`)?r(Ou):Ou.includes(t)||nu(t).riskClass===`execute`?n===void 0||n.trim()===`*`||Eu.includes(t)&&Pu(n):!1}function Iu(e){return e.filter(e=>!Fu(e))}const Lu=1e6,Ru={"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}},zu=[{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 Bu(e){let t=Object.hasOwn(Ru,e)?Ru[e]:void 0;if(t)return t;for(let{pattern:t,price:n}of zu)if(t.test(e))return n}function Vu(e,t,n){let r=Bu(e);if(r)return t/Lu*r.inputPerMillion+n/Lu*r.outputPerMillion}function Hu(e){let t=Bu(e);if(t)return(t.inputPerMillion+t.outputPerMillion)/2/1e3}function Uu(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 Wu(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 Gu(){let[{CommandExecutor:e},{HttpExecutor:t}]=await Promise.all([import(`./command-executor-D_UBZHxh.js`).then(e=>e.n),import(`./http-executor-ADn4locH.js`).then(e=>e.n)]);return[new e,new t]}async function Ku(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 Gu(),u=new Map;for(let e of l)u.set(e.type,e);let d=[],f=Wu(n),p=-1,m,h;for(let e of c){if(!Uu(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=le(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=ce[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:v}=s();return _!==void 0&&(g.unknownHookTypes=_),v!==void 0&&(g.errors=v),g}var
|
|
14
|
+
`)};m!==void 0&&(g.permissionDecision=m),h!==void 0&&(g.updatedInput=h);let{unknownHookTypes:_,errors:v}=s();return _!==void 0&&(g.unknownHookTypes=_),v!==void 0&&(g.errors=v),g}var qu=class extends Error{guardrailName;guardrailReason;constructor(e,t){super(t),this.guardrailName=e,this.guardrailReason=t,this.name=`GuardrailBlock`}},Ju=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 qu(e,`Guardrail "${e}" errored: ${t instanceof Error?t.message:String(t)}`)}if(!r.pass)throw new qu(e,r.reason??`Guardrail "${e}" blocked the turn`)}))}catch(e){if(e instanceof qu)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 Yu(e,t){return{posture:`advisory`,enforcementReachable:!1,rationale:`Awaited at ${e} but only ${t} is read; \`blocked\` is never consulted.`}}function Xu(e){for(let t of Object.values(e))Object.freeze(t);return Object.freeze(e)}const Zu=Xu({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:Yu(`session-lifecycle.ts`,`nothing`),PreCompact:Yu(`compaction-orchestrator.ts`,`nothing`),UserPromptSubmit:Yu(`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 Qu(e){return Zu[e].posture===`enforcing`}function $u(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{A as AGENT_EVENTS,kt as AGENT_EVENT_PREFIX,wt as AbstractAIProvider,Ye as AbstractAgent,Kr as AbstractEventService,zt as AbstractExecutor,Xe as AbstractManager,Rt as AbstractPlugin,Bt as AbstractTool,nc as AgentFactory,D as AgentRuntimeError,Zs as AgentTemplates,w as AuthenticationError,Ie as CONFIRM_NO,Fe as CONFIRM_YES,Di as CONTEXT_ESTIMATE_CHARS_PER_TOKEN,x as CacheIntegrityError,b as CircuitBreakerOpenError,m as ConfigurationError,_t as ConsoleLogger,hc as ConversationAgent,hc as Robota,xr as ConversationHistory,br as ConversationStore,Jr as DEFAULT_ABSTRACT_EVENT_SERVICE,Ic as DEFAULT_BACKGROUND_PERMISSION_POLICY,Ii as DEFAULT_CONTEXT_WINDOW,Hi as DEFAULT_MAX_OUTPUT,_c as DEFAULT_TOOL_RESULT_HARD_CHARS,gc as DEFAULT_TOOL_RESULT_WARNING_CHARS,di as DEFERRED_WITHOUT_LOADER_MESSAGE,qr as DefaultEventService,ar as ENV_REFERENCE_PREFIX,P as EVENT_EMITTER_EVENTS,j as EXECUTION_EVENTS,At as EXECUTION_EVENT_PREFIX,ie as EmptyCompletionError,Zt as ErrorUtils,Ir as EventEmitterPlugin,Oc as EventHistoryModule,F as ExecutionJournalError,Mc as ExecutionProxy,L as ExecutionRecoveryError,I as ExecutionSuspendedError,li as FunctionTool,Ju as GuardrailExecutor,Dr as InMemoryEventEmitterMetrics,wr as LocalExecutor,vc as MAX_TOOL_RESULT_CHARS,_e as MODEL_EFFORT_VALUES,Ru as MODEL_PRICES,Wt as MessageConverter,se as ModelNotAvailableError,g as NetworkError,kc as ORCHESTRATION_EVENTS,Ac as ORCHESTRATION_EVENT_PREFIX,ei as ObservableEventService,s as PARAMETER_SCHEMA_KEYWORDS,r as PERMISSIVE_TOOL_SCHEMA_PROFILE,ml as PROTECTED_DIRECTORY_NAMES,hl as PROTECTED_FILE_NAMES,ni as PROVIDER_CALL_EVENTS,ri as PROVIDER_FALLBACK_EVENTS,Dt as PluginCategory,oe as PluginError,Ot as PluginPriority,f as ProviderError,fl as RISK_CLASS_POLICY,c as RateLimitError,ti as SPAN_EVENTS,ci as SPAN_EVENT_PREFIX,a as STRICT_TOOL_SCHEMA_PROFILE,ae as SameToolInputLoopError,ht as SilentLogger,p as StorageError,Qr as StructuredEventService,u as StructuredOutputError,Qi as TASK_EVENTS,$i as TASK_EVENT_PREFIX,ai as TOOL_BODY_EVENTS,M as TOOL_EVENTS,jt as TOOL_EVENT_PREFIX,si as TOOL_PERMISSION_EVENTS,oi as TOOL_QUEUE_EVENTS,n as TOOL_SCHEMA_PROJECTION_MAX_DEPTH,e as TOOL_SCHEMA_PROJECTION_MAX_NODES,Pe as TOOL_SEARCH_TOOL_NAME,Fc as TRUST_TO_MODE,l as ToolExecutionError,Rr as ToolRegistry,xc as ToolResultAdmissionError,fe as TypeUtils,pl as UNCLASSIFIED_TOOL_FALLBACK,ea as USER_EVENTS,ta as USER_EVENT_PREFIX,v as UnsupportedShellError,d as ValidationError,Gt as Validator,Dc as admitToolResult,Iu as allowRulesForAutoMode,Tu as applyPresetToolLists,me as assertProviderNativeWebToolsAvailable,mi as assertResidentToolRemains,$r as bindEventServiceOwner,U as bindWithOwnerPath,T as buildTraceparent,Vu as calculateModelCost,En as callJournaledProvider,rt as chatEntryToMessage,Sn as classifyProviderFailure,tu as clearRegisteredToolProfiles,t as closeObjectSchemas,qo as collectAssistantUsageMetadata,Xr as composeEventName,Re as confirmAction,Ut as createAbortError,gr as createAssistantMessage,ne as createBoundedOutput,pe as createDefaultProviderCapabilities,Nc as createExecutionProxy,rr as createImageProviderFromDefinition,O as createLogger,ye as createModelEffortOutcome,dr as createProviderFromConfig,er as createRecordEnvResolver,_r as createSystemMessage,vr as createToolMessage,hr as createUserMessage,ir as createVideoProviderFromDefinition,ue as decodeHookVerdict,Hu as estimateBlendedCostPer1000,Ai as estimateContextTokensFromMessages,Oi as estimateSerializedContextTokens,ki as estimateToolSchemaTokens,_u as evaluatePermission,Nn as extractEnumValues,Su as findInvalidPermissionPatterns,Ne as findMediaProviderDefinition,Bi as findModelDefinition,Cu as findPermissionPatternWarnings,we as findProviderDefinition,sr as formatEnvReference,Te as formatSupportedProviderTypes,Gi as formatTokenCount,Zr as generateSpanId,bt as getGlobalLogLevel,St as getGlobalLoggerSink,at as getMessagesForAPI,Vi as getModelContextWindow,Ui as getModelMaxOutput,Wi as getModelName,Ce as getProviderCapabilities,Ee as getProviderCredentialRequirement,Fn as getSchemaTypeName,We as getToolEstimatedDuration,Ge as getToolExecutionSteps,nu as getToolPermissionProfile,uu as hasUnevaluableArgumentPattern,lr as hasUsableSecretReference,Pn as hasValidationConstraints,i as hashToolSchema,Ht as isAbortFailure,st as isAssistantMessage,Fu as isBroadExecutionAllowRule,nt as isChatEntry,He as isConfirmed,Yr as isDefaultEventService,Qu as isEnforcing,or as isEnvReference,R as isExecutionControlError,Ae as isImageGenerationProvider,Me as isMediaProviderDefinition,ee as isMintedSpanId,ve as isModelEffort,Ue as isProgressReportingTool,vl as isProtectedPath,Ql as isReadOnlyCommandLine,$s as isRegistryTransactionError,ct as isSystemMessage,ou as isToolDeniedOutright,lt as isToolMessage,ot as isUserMessage,je as isVideoGenerationProvider,Qs as lifecycleOf,k as logger,Bu as lookupModelPrice,lu as matchesAnyPattern,it as messageToHistoryEntry,Oe as modelDeclaresCapability,Be as multiSelectAction,$u as nonVisualObservationText,ur as normalizeProviderConfig,Gn as normalizeStructuredOutput,S as outboundTraceContextFor,iu as parseParameterRule,Xn as parseStructuredResponseText,Qo as peerDriverOf,$o as printablePeerDriver,$n as processEnvResolver,vu as projectPermissionPolicy,o as projectToolSchema,h as providerCallSpanId,ii as readModelFallbackNotice,dn as readProviderFailureDetails,bi as readTokenUsageFromMessage,xi as readTokenUsageFromMetadata,Ri as registerModelMetadata,eu as registerToolPermissionProfile,El as removesCriticalPath,mu as requiresFreshApproval,cr as resolveEnvReference,nr as resolveMediaProviderConfig,De as resolveModelCapabilities,ke as resolveModelCapability,Se as resolveModelEffort,y as resolvePlatformShell,Qn as resolveStructuredOutputCapability,Ku as runHooks,ec as runRegistryTransaction,ln as scrubSecrets,ze as selectAction,yt as setGlobalLogLevel,xt as setGlobalLoggerSink,Ke as setToolProgressCallback,Er as shellArgumentForDisplay,qe as snapshotToolProvenance,E as spanIdFromMintedId,Rc as splitCommandSegments,Cn as startPeriodicTask,wn as stopPeriodicTask,te as subprocessTraceEnvironment,Go as sumHistoryUsage,Wo as sumMessagesUsage,Ve as textAction,gn as toProviderError,ru as toolNameMatches,wu as toolNamesToPatterns,_ as toolTraceContextFor,C as traceEnvFor,re as traceHeadersFor,Kn as validateAgainstJsonSchema,Kt as validateAgentConfig,Xt as validateApiKey,Yt as validateModelName,xu as validatePermissionPattern,Jt as validateProviderName,qt as validateUserInput,Uo as verifiedProviderCallUsage,Sc as wasToolResultAdmitted,Pc as withEventEmission,Je as withToolProvenance,In as zodToJsonSchema};
|
|
15
15
|
//# sourceMappingURL=index.js.map
|