@robota-sdk/agent-core 3.0.0-beta.90 → 3.0.0-beta.93

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.
@@ -1,3 +1,3 @@
1
1
  import { A as TModelEffortProviderDispatch, C as IModelEffortResolution, D as TModelEffortDisposition, E as TModelEffort, F as IUniversalObjectValue, I as TPrimitiveValue, L as TUniversalArrayValue, M as createModelEffortOutcome, N as isModelEffort, O as TModelEffortNativeControl, P as resolveModelEffort, R as TUniversalValue, S as IModelEffortOutcome, T as MODEL_EFFORT_VALUES, _ as IOutboundTraceContext, b as TSubprocessTraceClass, c as IHookTypeExecutor, d as TGuardrail, f as THookDefinition, g as TSessionEndReason, h as THooksConfig, i as IGuardrailResult, j as TModelEffortSelection, k as TModelEffortOutcomeCallback, l as IHttpHookDefinition, m as THookOutcome, n as ICommandHookDefinition, o as IHookGroup, p as THookEvent, r as IGuardrailHookDefinition, s as IHookInput, t as IAgentHookDefinition, u as IPromptHookDefinition, v as IRunTraceContext, w as IProviderModelEffortTable, x as IModelEffortCapability, y as ISubprocessTraceEnv } from "./types-Ge2XB-y-.js";
2
- import { $ as matchesAnyPattern, $a as IProviderProbeResult, $c as TJSONSchemaKind, $i as IToolExecutionRequest, $l as IToolMessage, $n as createToolMessage, $o as TExecutionEventData, $r as TMessageFormatConverter, $s as SPAN_EVENT_PREFIX, $t as TProviderUsageProvenance, A as IContextWindowState, Aa as IImageGenerationRequest, Ac as TEventListener, Ai as IFileSystemAsync, Al as StorageError, An as FunctionTool, Ao as setGlobalLogLevel, Ar as IPlatformShell, As as IToolCallScheduling, At as TOrchestrationEvent, Au as TypeUtils, B as IPermissionPolicyContext, Ba as TImageInputSource, Bc as ITokenUsageWithCacheRead, Bi as IExecutorChatResult, Bl as modelDeclaresCapability, Bn as IBoundedOutputOptions, Bo as IPluginHooks, Br as TExecutionRecoveryErrorCode, Bs as IDeferredToolCatalog, Bt as ISequentialOrchestrationSpec, C as CONTEXT_ESTIMATE_CHARS_PER_TOKEN, Ca as IMediaProviderCredentialRequirement, Cc as IEventObjectValue, Ci as AbstractAgent, Cl as IProviderFailureDetails, Cn as IDestroyResult, Co as IUtilLogEntry, Cr as outboundTraceContextFor, Cs as IResumeToolCallsOptions, Ct as TTrustLevel, Cu as TConfigData, D as estimateSerializedContextTokens, Da as IImageComposeRequest, Dc as IOwnerPathSegment, Di as ICredentialStore, Dl as ProviderError, Dn as TOOL_EVENT_PREFIX, Do as getGlobalLogLevel, Dr as toolTraceContextFor, Ds as IFunctionTool, Dt as IExecutionProxyConfig, Du as TMetadata, E as estimateContextTokensFromMessages, Ea as isMediaProviderDefinition, Ec as IExecutionEventData, Ei as ICredentialKey, El as PluginError, En as TOOL_EVENTS, Eo as createLogger, Er as subprocessTraceEnvironment, Es as TJournalModelOptions, Et as withEventEmission, Eu as TLoggerData, F as toolNamesToPatterns, Fa as IUriImageInputSource, Fc as IProviderNativeRawPayloadEvent, Fi as IEventHistoryModule, Fl as ValidationError, Fn as IEventEmitterMetrics, Fo as IPluginContract, Fr as startPeriodicTask, Fs as IToolRegistry, Ft as IOrchestrationEventData, G as IPermissionLists, Ga as TStructuredOutputMechanism, Gc as TProviderOptionValueBase, Gi as IStreamExecutionRequest, Gl as IBaseMessage, Gn as hasUsableSecretReference, Go as EVENT_EMITTER_EVENTS, Gr as Validator, Gs as IActionOption, Gt as printablePeerDriver, H as projectPermissionPolicy, Ha as isImageGenerationProvider, Hc as TProviderNativeRawPayload, Hi as IExecutorStreamTerminalEvent, Hl as resolveModelCapability, Hn as createBoundedOutput, Ho as IPluginStats, Hr as ExecutionJournalError, Hs as TToolSearchMode, Ht as AGENT_EVENTS, I as IPermissionPatternProblem, Ia as IVideoGenerationProvider, Ic as IProviderOptions, Ii as IEventHistoryRecord, Il as IModelRef, In as IEventEmitterMetricsSnapshot, Io as IPluginData, Ir as stopPeriodicTask, Is as IToolResult, It as IOrchestrationRunResult, J as TToolArgs, Ja as IProviderDefinition, Jc as getProviderCapabilities, Ji as IConversationContext, Jl as IInlineImageMessagePart, Jn as IAIProviderInstance, Jo as TEventEmitterListener, Jr as validateModelName, Js as TActionResponse, Jt as ISessionUsageTotals, K as IToolPermissionArgument, Ka as TStructuredOutputProvenance, Kc as TTextDeltaCallback, Ki as TExecutorStreamEvent, Kl as IHistoryEntry, Kn as isEnvReference, Ko as IEventEmitterEventData, Kr as validateAgentConfig, Ks as IActionRequest, Kt as EventHistoryModule, L as findInvalidPermissionPatterns, La as IVideoGenerationRequest, Lc as IProviderRequest, Li as IEventHistorySnapshot, Ll as TRoleModelMap, Ln as InMemoryEventEmitterMetrics, Lo as IPluginErrorContext, Lr as TTimerId, Ls as TToolEffectAdmission, Lt as IOrchestrationStep, M as isBroadExecutionAllowRule, Ma as IInlineImageInputSource, Mc as TEventUniversalValue, Mi as ISession, Ml as TErrorContextData, Mn as EventEmitterPlugin, Mo as IPlugin, Mr as TShellKind, Ms as IToolExecutionPolicy, Mt as IHandoffOrchestrationSpec, N as splitCommandSegments, Na as IMediaOutputRef, Nc as IAIProvider, Ni as ISpinner, Nl as TErrorExternalInput, Nn as IEventEmitterHierarchicalEventData, No as IPluginConfig, Nr as UnsupportedShellError, Ns as IToolExecutionResult, Nt as IHierarchicalOrchestrationSpec, O as estimateToolSchemaTokens, Oa as IImageEditRequest, Oc as IToolEventData, Oi as IDirent, Ol as RateLimitError, On as DEFERRED_WITHOUT_LOADER_MESSAGE, Oo as getGlobalLoggerSink, Or as traceEnvFor, Os as IParameterValidationResult, Ot as ORCHESTRATION_EVENTS, Ou as TMetadataValue, P as applyPresetToolLists, Pa as IProviderMediaError, Pc as IChatOptions, Pi as ITerminalOutput, Pl as ToolExecutionError, Pn as IEventEmitterPluginOptions, Po as IPluginContext, Pr as resolvePlatformShell, Ps as IToolProvenance, Pt as IOrchestrationDelegation, Q as isToolDeniedOutright, Qa as IProviderModelCatalogEntry, Qc as TJSONSchemaEnum, Qi as IStreamingChunk, Ql as IToolCall, Qn as createSystemMessage, Qo as TExecutionEventCallback, Qr as TMessageConverterRegistry, Qs as SPAN_EVENTS, Qt as IVerifiedProviderCallUsage, R as findPermissionPatternWarnings, Ra as IVideoJobAccepted, Rc as IRawProviderResponse, Ri as IChatExecutionRequest, Rl as IModelCapabilityDeviation, Rn as shellArgumentForDisplay, Ro as IPluginExecutionContext, Rr as isExecutionControlError, Rs as TToolExecutor, Rt as IOrchestrationStepResult, S as readTokenUsageFromMetadata, Sa as IMediaProviderConfig, Sc as IEventContext, Si as IManagerLifecycleOptions, Sl as EmptyCompletionError, Sn as ConversationAgent, So as ILoggerOptions, Sr as isMintedSpanId, Ss as IResumeExecutionOptions, St as TRUST_TO_MODE, Su as TComplexConfigValue, T as IContextTokenEstimateOptions, Ta as findMediaProviderDefinition, Tc as IEventServiceOwnerBinding, Ti as withToolProvenance, Tl as NetworkError, Tn as EXECUTION_EVENT_PREFIX, To as TUtilLogLevel, Tr as spanIdFromMintedId, Ts as TExecutionJournalRecord, Tt as createExecutionProxy, Tu as TContextData, U as IParameterRule, Ua as isVideoGenerationProvider, Uc as TProviderNativeRawPayloadCallback, Ui as ILocalExecutorConfig, Ul as TProviderModelCapability, Un as ENV_REFERENCE_PREFIX, Uo as PluginCategory, Ur as ErrorUtils, Us as TToolSearchSetting, Ut as AGENT_EVENT_PREFIX, V as IPermissionPolicyProjection, Va as TProviderMediaResult, Vc as TProviderConfigValue, Vi as IExecutorStreamMessageEvent, Vl as resolveModelCapabilities, Vn as TOutputRetention, Vo as IPluginOptions, Vr as ExecutionSuspendedError, Vs as TOOL_SEARCH_TOOL_NAME, Vt as TOrchestrationPrimitive, W as IPermissionEvaluationContext, Wa as IProviderStructuredOutputCapability, Wc as TProviderNativeRawPayloadKind, Wi as IRemoteExecutorConfig, Wl as IAssistantMessage, Wn as formatEnvReference, Wo as PluginPriority, Wr as ISimpleValidationResult, Ws as IActionDefault, Wt as peerDriverOf, X as evaluatePermission, Xa as IProviderEndpoint, Xc as IParameterSchema, Xi as IConversationService, Xl as ISystemMessage, Xn as ConversationHistory, Xo as TExecutionEventName, Xr as validateUserInput, Xs as PROVIDER_CALL_EVENTS, Xt as sumHistoryUsage, Y as clearRegisteredToolProfiles, Ya as IProviderDefinitionConfig, Yc as IObjectParameterSchema, Yi as IConversationResponse, Yl as IResourceLinkMessagePart, Yn as LocalExecutor, Yo as TEventName, Yr as validateProviderName, Ys as ISpanCompletionEventData, Yt as collectAssistantUsageMetadata, Z as getToolPermissionProfile, Za as IProviderModelCatalog, Zc as IToolSchema, Zi as IConversationServiceOptions, Zl as ITextMessagePart, Zn as createAssistantMessage, Zo as IRunOptions, Zr as MessageConverter, Zs as PROVIDER_FALLBACK_EVENTS, Zt as sumMessagesUsage, _ as getModelMaxOutput, _a as IOpenAPIToolConfig, _c as composeEventName, _i as TToolSchemaProjectionOutcome, _l as AgentRuntimeError, _n as MAX_TOOL_RESULT_CHARS, _o as IToolContract, _r as ISchemaClosureOptions, _s as IExecutionContinuationState, _t as isReadOnlyCommandLine, _u as IToolContinuation, a as runHooks, aa as TToolProgressCallback, ac as TUserEvent, ai as AbstractAIProvider, al as IProviderNativeWebToolCapability, an as lifecycleOf, ao as TProviderModelCatalogStatus, ar as createImageProviderFromDefinition, as as parseStructuredResponseText, at as IPathProtectionPolicy, au as TUniversalMessageMetadata, b as IMessageTokenUsage, ba as IToolManager, bc as IAgentEventData, bi as projectToolSchema, bl as CircuitBreakerOpenError, bn as admitToolResult, bo as ConsoleLogger, br as callJournaledProvider, bs as IModelJournalContext, bt as TPermissionDecision, bu as IToolWaitResponse, c as calculateModelCost, ca as isProgressReportingTool, cc as TASK_EVENTS, ci as TProviderLoggingData, cl as createDefaultProviderCapabilities, cn as AgentTemplates, co as TProviderSetupHelpLinkKind, cr as TEnvResolver, cs as IZodParseResult, ct as isProtectedPath, cu as chatEntryToMessage, d as DEFAULT_CONTEXT_WINDOW, da as CONFIRM_YES, dc as DEFAULT_ABSTRACT_EVENT_SERVICE, di as IToolSchemaProjectionProfile, dl as IProviderFailureClassification, dn as IAgentFactoryOptions, do as getProviderCredentialRequirement, dr as IStructuredOutputResolutionInput, ds as IResponseFormatConfig, dt as TToolRiskClass, du as isChatEntry, ea as TConversationContextMetadata, ec as TOOL_BODY_EVENTS, ei as TProviderMessage, el as TParameterDefaultValue, en as verifiedProviderCallUsage, eo as IProviderProfileConfig, er as createUserMessage, es as IJsonSchemaOutput, et as parseParameterRule, eu as IUriImageMessagePart, f as DEFAULT_MAX_OUTPUT, fa as confirmAction, fc as DefaultEventService, fi as PARAMETER_SCHEMA_KEYWORDS, fl as TProviderFailureReason, fn as IAgentLifecycleEvents, fo as IAgent, fr as resolveStructuredOutputCapability, fs as ICacheEntry, ft as UNCLASSIFIED_TOOL_FALLBACK, fu as isSystemMessage, g as getModelContextWindow, ga as textAction, gc as bindWithOwnerPath, gi as TOOL_SCHEMA_PROJECTION_MAX_NODES, gl as toProviderError, gn as IToolResultSpillStore, go as IAbstractToolOptions, gr as ISchemaClosureChange, gs as ICacheStorage, gt as TResolveInWorkspace, gu as IToolActionIdentity, h as formatTokenCount, ha as selectAction, hc as bindEventServiceOwner, hi as TOOL_SCHEMA_PROJECTION_MAX_DEPTH, hl as scrubSecrets, hn as IToolResultAdmissionOptions, ho as IAbstractTool, hr as hasValidationConstraints, hs as ICacheStats, ht as IReadOnlyCommandContext, hu as messageToHistoryEntry, i as GuardrailExecutor, ia as IToolExecutionStep, ic as readModelFallbackNotice, ii as AbstractPlugin, il as IProviderNativeWebToolCapabilities, in as isRegistryTransactionError, io as TProviderCredentialField, ir as IMediaProviderOverrides, is as normalizeStructuredOutput, it as ICriticalPathContext, iu as TUniversalMessage, j as allowRulesForAutoMode, ja as IImageGenerationResult, jc as TEventLoggerData, ji as IStats, jl as StructuredOutputError, jn as ToolRegistry, jo as setGlobalLoggerSink, jr as IPlatformShellResolutionRequest, js as IToolExecutionContext, jt as IGroupChatOrchestrationSpec, k as IContextTokenUsage, ka as IImageGenerationProvider, kc as TEventExtensionValue, ki as IFileSystem, kl as SameToolInputLoopError, kn as assertResidentToolRemains, ko as logger, kr as traceHeadersFor, ks as ITool, kt as ORCHESTRATION_EVENT_PREFIX, ku as TToolParameters, l as estimateBlendedCostPer1000, la as setToolProgressCallback, lc as TASK_EVENT_PREFIX, li as IToolSchemaProjection, ll as IModelFallbackNotice, ln as ITemplateApplicationResult, lo as findProviderDefinition, lr as createRecordEnvResolver, ls as IZodSchema, lt as removesCriticalPath, lu as getMessagesForAPI, m as findModelDefinition, ma as multiSelectAction, mc as StructuredEventService, mi as STRICT_TOOL_SCHEMA_PROFILE, ml as readProviderFailureDetails, mn as DEFAULT_TOOL_RESULT_WARNING_CHARS, mo as IAgentTemplate, mr as getSchemaTypeName, ms as ICacheOptions, mt as TMatchDirection, mu as isUserMessage, n as isEnforcing, na as TToolExecutionParameters, nc as TOOL_QUEUE_EVENTS, ni as AbstractTool, nl as IProviderCapabilities, nn as IRegistryTransactionError, no as IProviderSetupHelpLink, nr as createProviderFromConfig, ns as TStructuredOutputSchema, nt as requiresFreshApproval, nu as TEmbeddedResourceMessagePart, o as IModelPrice, oa as getToolEstimatedDuration, oc as USER_EVENTS, oi as IExecutorAwareProviderConfig, ol as IProviderNativeWebToolRequest, on as runRegistryTransaction, oo as TProviderModelLifecycle, or as createVideoProviderFromDefinition, os as validateAgainstJsonSchema, ot as PROTECTED_DIRECTORY_NAMES, ou as TUniversalMessagePart, p as IModelDefinition, pa as isConfirmed, pc as ObservableEventService, pi as PERMISSIVE_TOOL_SCHEMA_PROFILE, pl as classifyProviderFailure, pn as DEFAULT_TOOL_RESULT_HARD_CHARS, po as IAgentConfig, pr as extractEnumValues, ps as ICacheKey, pt as TArgumentKind, pu as isToolMessage, q as IToolPermissionProfile, qa as IProviderCredentialRequirement, qc as TToolChoice, qi as IContextOptions, ql as IInlineAudioMessagePart, qn as resolveEnvReference, qo as IEventEmitterPlugin, qr as validateApiKey, qs as IUserInteraction, qt as IAssistantUsageMetadata, r as decodeHookVerdict, ra as IProgressReportingTool, rc as TSpanEvent, ri as AbstractExecutor, rl as IProviderFunctionCallingCapability, rn as IRegistryTransactionStep, ro as IProviderSetupStepDefinition, rr as normalizeProviderConfig, rs as TStructuredOutputValidation, rt as toolNameMatches, ru as TMessageState, s as MODEL_PRICES, sa as getToolExecutionSteps, sc as USER_EVENT_PREFIX, si as IProviderRuntimeConfig, sl as assertProviderNativeWebToolsAvailable, sn as AgentFactory, so as TProviderSetupField, sr as resolveMediaProviderConfig, ss as ISchemaConversionOptions, st as PROTECTED_FILE_NAMES, su as TUniversalMessageRole, t as nonVisualObservationText, ta as TResponseMetadata, tc as TOOL_PERMISSION_EVENTS, ti as isAbortFailure, tl as IProviderSpecificOptions, tn as IRegistryOwnedLifecycle, to as IProviderProfileDefaults, tr as ConversationStore, ts as IStructuredOutputSpec, tt as registerToolPermissionProfile, tu as IUserMessage, u as lookupModelPrice, ua as CONFIRM_NO, uc as AbstractEventService, ui as IToolSchemaProjectionChange, ul as TModelFallbackCallback, un as IAgentCreationStats, uo as formatSupportedProviderTypes, ur as processEnvResolver, us as IZodSchemaDef, ut as RISK_CLASS_POLICY, uu as isAssistantMessage, v as getModelName, va as IToolFactory, vc as generateSpanId, vi as TToolSchemaProjectionProfileBase, vl as AuthenticationError, vn as TToolResultAdmissionErrorCode, vo as IToolWithEventService, vr as closeObjectSchemas, vs as IExecutionJournal, vt as DEFAULT_BACKGROUND_PERMISSION_POLICY, vu as IToolContinuationPrompt, w as IContextTokenEstimate, wa as IMediaProviderDefinition, wc as IEventService, wi as snapshotToolProvenance, wl as ModelNotAvailableError, wn as EXECUTION_EVENTS, wo as SilentLogger, wr as providerCallSpanId, ws as IResumeToolCallsResult, wt as ExecutionProxy, wu as TConfigValue, x as readTokenUsageFromMessage, xa as TManagerToolParameters, xc as IBaseEventData, xi as AbstractManager, xl as ConfigurationError, xn as wasToolResultAdmitted, xo as ILogger, xr as buildTraceparent, xs as IRecoverableExecutionJournal, xt as TPermissionMode, xu as IToolWaitState, y as registerModelMetadata, ya as IAIProviderManager, yc as isDefaultEventService, yi as hashToolSchema, yl as CacheIntegrityError, yn as ToolResultAdmissionError, yo as TToolExecutionFunction, yr as zodToJsonSchema, ys as IExecutionRoundCheckpoint, yt as TBackgroundPermissionPolicy, yu as IToolWaitRequest, z as validatePermissionPattern, za as IVideoJobSnapshot, zc as ITokenUsage, zi as IExecutor, zl as IProviderCapabilityTable, zn as IBoundedOutput, zo as IPluginExecutionResult, zr as ExecutionRecoveryError, zs as TToolMetadata, zt as IParallelOrchestrationSpec } from "./index-CjyNzgQN.js";
3
- export { AGENT_EVENTS, AGENT_EVENT_PREFIX, AbstractAIProvider, AbstractAgent, AbstractEventService, AbstractExecutor, AbstractManager, AbstractPlugin, AbstractTool, AgentFactory, AgentRuntimeError, AgentTemplates, AuthenticationError, CONFIRM_NO, CONFIRM_YES, CONTEXT_ESTIMATE_CHARS_PER_TOKEN, CacheIntegrityError, CircuitBreakerOpenError, ConfigurationError, ConsoleLogger, ConversationAgent, ConversationAgent as Robota, ConversationHistory, ConversationStore, DEFAULT_ABSTRACT_EVENT_SERVICE, DEFAULT_BACKGROUND_PERMISSION_POLICY, DEFAULT_CONTEXT_WINDOW, DEFAULT_MAX_OUTPUT, DEFAULT_TOOL_RESULT_HARD_CHARS, DEFAULT_TOOL_RESULT_WARNING_CHARS, DEFERRED_WITHOUT_LOADER_MESSAGE, DefaultEventService, ENV_REFERENCE_PREFIX, EVENT_EMITTER_EVENTS, EXECUTION_EVENTS, EXECUTION_EVENT_PREFIX, EmptyCompletionError, ErrorUtils, EventEmitterPlugin, EventHistoryModule, ExecutionJournalError, ExecutionProxy, ExecutionRecoveryError, ExecutionSuspendedError, FunctionTool, GuardrailExecutor, type IAIProvider, type IAIProviderInstance, type IAIProviderManager, type IAbstractTool, type IAbstractToolOptions, type IActionDefault, type IActionOption, type IActionRequest, type IAgent, type IAgentConfig, type IAgentCreationStats, type IAgentEventData, type IAgentFactoryOptions, type IAgentHookDefinition, type IAgentLifecycleEvents, type IAgentTemplate, type IAssistantMessage, type IAssistantUsageMetadata, type IBaseEventData, type IBaseMessage, type IBoundedOutput, type IBoundedOutputOptions, type ICacheEntry, type ICacheKey, type ICacheOptions, type ICacheStats, type ICacheStorage, type IChatExecutionRequest, type IChatOptions, type ICommandHookDefinition, type IContextOptions, type IContextTokenEstimate, type IContextTokenEstimateOptions, type IContextTokenUsage, type IContextWindowState, type IConversationContext, type IConversationResponse, type IConversationService, type IConversationServiceOptions, type ICredentialKey, type ICredentialStore, type ICriticalPathContext, type IDeferredToolCatalog, type IDestroyResult, type IDirent, type IEventContext, type IEventEmitterEventData, type IEventEmitterHierarchicalEventData, type IEventEmitterMetrics, type IEventEmitterMetricsSnapshot, type IEventEmitterPlugin, type IEventEmitterPluginOptions, type IEventHistoryModule, type IEventHistoryRecord, type IEventHistorySnapshot, type IEventObjectValue, type IEventService, type IEventServiceOwnerBinding, type IExecutionContinuationState, type IExecutionEventData, type IExecutionJournal, type IExecutionProxyConfig, type IExecutionRoundCheckpoint, type IExecutor, IExecutorAwareProviderConfig, type IExecutorChatResult, type IExecutorStreamMessageEvent, type IExecutorStreamTerminalEvent, type IFileSystem, type IFileSystemAsync, type IFunctionTool, type IGroupChatOrchestrationSpec, type IGuardrailHookDefinition, type IGuardrailResult, type IHandoffOrchestrationSpec, type IHierarchicalOrchestrationSpec, type IHistoryEntry, type IHookGroup, type IHookInput, type IHookTypeExecutor, type IHttpHookDefinition, type IImageComposeRequest, type IImageEditRequest, type IImageGenerationProvider, type IImageGenerationRequest, type IImageGenerationResult, type IInlineAudioMessagePart, type IInlineImageInputSource, type IInlineImageMessagePart, type IJsonSchemaOutput, type ILocalExecutorConfig, ILogger, ILoggerOptions, IManagerLifecycleOptions, type IMediaOutputRef, type IMediaProviderConfig, type IMediaProviderCredentialRequirement, type IMediaProviderDefinition, type IMediaProviderOverrides, type IMessageTokenUsage, type IModelCapabilityDeviation, type IModelDefinition, type IModelEffortCapability, type IModelEffortOutcome, type IModelEffortResolution, type IModelFallbackNotice, type IModelJournalContext, type IModelPrice, type IModelRef, type IObjectParameterSchema, type IOpenAPIToolConfig, type IOrchestrationDelegation, type IOrchestrationEventData, type IOrchestrationRunResult, type IOrchestrationStep, type IOrchestrationStepResult, type IOutboundTraceContext, type IOwnerPathSegment, type IParallelOrchestrationSpec, type IParameterRule, type IParameterSchema, type IParameterValidationResult, type IPathProtectionPolicy, type IPermissionEvaluationContext, type IPermissionLists, type IPermissionPatternProblem, type IPermissionPolicyContext, type IPermissionPolicyProjection, IPlatformShell, IPlatformShellResolutionRequest, type IPlugin, type IPluginConfig, type IPluginContext, type IPluginContract, type IPluginData, type IPluginErrorContext, type IPluginExecutionContext, type IPluginExecutionResult, type IPluginHooks, type IPluginOptions, type IPluginStats, type IProgressReportingTool, type IPromptHookDefinition, type IProviderCapabilities, type IProviderCapabilityTable, type IProviderCredentialRequirement, type IProviderDefinition, type IProviderDefinitionConfig, type IProviderEndpoint, type IProviderFailureClassification, IProviderFailureDetails, type IProviderFunctionCallingCapability, type IProviderMediaError, type IProviderModelCatalog, type IProviderModelCatalogEntry, type IProviderModelEffortTable, type IProviderNativeRawPayloadEvent, type IProviderNativeWebToolCapabilities, type IProviderNativeWebToolCapability, type IProviderNativeWebToolRequest, type IProviderOptions, type IProviderProbeResult, type IProviderProfileConfig, type IProviderProfileDefaults, type IProviderRequest, IProviderRuntimeConfig, type IProviderSetupHelpLink, type IProviderSetupStepDefinition, type IProviderSpecificOptions, type IProviderStructuredOutputCapability, type IRawProviderResponse, type IReadOnlyCommandContext, type IRecoverableExecutionJournal, type IRegistryOwnedLifecycle, type IRegistryTransactionError, type IRegistryTransactionStep, type IRemoteExecutorConfig, type IResourceLinkMessagePart, type IResponseFormatConfig, type IResumeExecutionOptions, type IResumeToolCallsOptions, type IResumeToolCallsResult, type IRunOptions, type IRunTraceContext, type ISchemaClosureChange, type ISchemaClosureOptions, type ISchemaConversionOptions, type ISequentialOrchestrationSpec, type ISession, type ISessionUsageTotals, ISimpleValidationResult, type ISpanCompletionEventData, type ISpinner, type IStats, type IStreamExecutionRequest, type IStreamingChunk, type IStructuredOutputResolutionInput, type IStructuredOutputSpec, type ISubprocessTraceEnv, type ISystemMessage, type ITemplateApplicationResult, type ITerminalOutput, type ITextMessagePart, type ITokenUsage, type ITokenUsageWithCacheRead, type ITool, type IToolActionIdentity, type IToolCall, type IToolCallScheduling, type IToolContinuation, type IToolContinuationPrompt, type IToolContract, type IToolEventData, type IToolExecutionContext, type IToolExecutionPolicy, type IToolExecutionRequest, type IToolExecutionResult, type IToolExecutionStep, type IToolFactory, type IToolManager, type IToolMessage, type IToolPermissionArgument, type IToolPermissionProfile, type IToolProvenance, type IToolRegistry, type IToolResult, type IToolResultAdmissionOptions, type IToolResultSpillStore, type IToolSchema, type IToolSchemaProjection, type IToolSchemaProjectionChange, type IToolSchemaProjectionProfile, type IToolWaitRequest, type IToolWaitResponse, type IToolWaitState, type IToolWithEventService, type IUniversalObjectValue, type IUriImageInputSource, type IUriImageMessagePart, type IUserInteraction, type IUserMessage, IUtilLogEntry, type IVerifiedProviderCallUsage, type IVideoGenerationProvider, type IVideoGenerationRequest, type IVideoJobAccepted, type IVideoJobSnapshot, type IZodParseResult, type IZodSchema, type IZodSchemaDef, InMemoryEventEmitterMetrics, LocalExecutor, MAX_TOOL_RESULT_CHARS, MODEL_EFFORT_VALUES, MODEL_PRICES, MessageConverter, ModelNotAvailableError, NetworkError, ORCHESTRATION_EVENTS, ORCHESTRATION_EVENT_PREFIX, ObservableEventService, PARAMETER_SCHEMA_KEYWORDS, PERMISSIVE_TOOL_SCHEMA_PROFILE, PROTECTED_DIRECTORY_NAMES, PROTECTED_FILE_NAMES, PROVIDER_CALL_EVENTS, PROVIDER_FALLBACK_EVENTS, PluginCategory, PluginError, PluginPriority, ProviderError, RISK_CLASS_POLICY, RateLimitError, SPAN_EVENTS, SPAN_EVENT_PREFIX, STRICT_TOOL_SCHEMA_PROFILE, SameToolInputLoopError, SilentLogger, StorageError, StructuredEventService, StructuredOutputError, TASK_EVENTS, TASK_EVENT_PREFIX, type TActionResponse, type TArgumentKind, type TBackgroundPermissionPolicy, TComplexConfigValue, TConfigData, TConfigValue, TContextData, type TConversationContextMetadata, type TEmbeddedResourceMessagePart, type TEnvResolver, TErrorContextData, TErrorExternalInput, type TEventEmitterListener, type TEventExtensionValue, type TEventListener, type TEventLoggerData, type TEventName, type TEventUniversalValue, type TExecutionEventCallback, type TExecutionEventData, type TExecutionEventName, type TExecutionJournalRecord, type TExecutionRecoveryErrorCode, type TExecutorStreamEvent, type TGuardrail, type THookDefinition, type THookEvent, type THookOutcome, type THooksConfig, type TImageInputSource, type TJSONSchemaEnum, type TJSONSchemaKind, type TJournalModelOptions, TLoggerData, type TManagerToolParameters, type TMatchDirection, TMessageConverterRegistry, TMessageFormatConverter, type TMessageState, TMetadata, TMetadataValue, type TModelEffort, type TModelEffortDisposition, type TModelEffortNativeControl, type TModelEffortOutcomeCallback, type TModelEffortProviderDispatch, type TModelEffortSelection, type TModelFallbackCallback, TOOL_BODY_EVENTS, TOOL_EVENTS, TOOL_EVENT_PREFIX, TOOL_PERMISSION_EVENTS, TOOL_QUEUE_EVENTS, TOOL_SCHEMA_PROJECTION_MAX_DEPTH, TOOL_SCHEMA_PROJECTION_MAX_NODES, TOOL_SEARCH_TOOL_NAME, type TOrchestrationEvent, type TOrchestrationPrimitive, type TOutputRetention, type TParameterDefaultValue, type TPermissionDecision, type TPermissionMode, type TPrimitiveValue, type TProviderConfigValue, type TProviderCredentialField, type TProviderFailureReason, TProviderLoggingData, type TProviderMediaResult, TProviderMessage, type TProviderModelCapability, type TProviderModelCatalogStatus, type TProviderModelLifecycle, type TProviderNativeRawPayload, type TProviderNativeRawPayloadCallback, type TProviderNativeRawPayloadKind, type TProviderOptionValueBase, type TProviderSetupField, type TProviderSetupHelpLinkKind, type TProviderUsageProvenance, TRUST_TO_MODE, type TResolveInWorkspace, type TResponseMetadata, type TRoleModelMap, type TSessionEndReason, TShellKind, type TSpanEvent, type TStructuredOutputMechanism, type TStructuredOutputProvenance, type TStructuredOutputSchema, type TStructuredOutputValidation, type TSubprocessTraceClass, type TTextDeltaCallback, type TTimerId, type TToolArgs, type TToolChoice, type TToolEffectAdmission, type TToolExecutionFunction, type TToolExecutionParameters, type TToolExecutor, type TToolMetadata, TToolParameters, type TToolProgressCallback, type TToolResultAdmissionErrorCode, type TToolRiskClass, type TToolSchemaProjectionOutcome, type TToolSchemaProjectionProfileBase, type TToolSearchMode, type TToolSearchSetting, type TTrustLevel, type TUniversalArrayValue, type TUniversalMessage, type TUniversalMessageMetadata, type TUniversalMessagePart, type TUniversalMessageRole, type TUniversalValue, type TUserEvent, TUtilLogLevel, ToolExecutionError, ToolRegistry, ToolResultAdmissionError, TypeUtils, UNCLASSIFIED_TOOL_FALLBACK, USER_EVENTS, USER_EVENT_PREFIX, UnsupportedShellError, ValidationError, Validator, admitToolResult, allowRulesForAutoMode, applyPresetToolLists, assertProviderNativeWebToolsAvailable, assertResidentToolRemains, bindEventServiceOwner, bindWithOwnerPath, buildTraceparent, calculateModelCost, callJournaledProvider, chatEntryToMessage, classifyProviderFailure, clearRegisteredToolProfiles, closeObjectSchemas, collectAssistantUsageMetadata, composeEventName, confirmAction, createAssistantMessage, createBoundedOutput, createDefaultProviderCapabilities, createExecutionProxy, createImageProviderFromDefinition, createLogger, createModelEffortOutcome, createProviderFromConfig, createRecordEnvResolver, createSystemMessage, createToolMessage, createUserMessage, createVideoProviderFromDefinition, decodeHookVerdict, estimateBlendedCostPer1000, estimateContextTokensFromMessages, estimateSerializedContextTokens, estimateToolSchemaTokens, evaluatePermission, extractEnumValues, findInvalidPermissionPatterns, findMediaProviderDefinition, findModelDefinition, findPermissionPatternWarnings, findProviderDefinition, formatEnvReference, formatSupportedProviderTypes, formatTokenCount, generateSpanId, getGlobalLogLevel, getGlobalLoggerSink, getMessagesForAPI, getModelContextWindow, getModelMaxOutput, getModelName, getProviderCapabilities, getProviderCredentialRequirement, getSchemaTypeName, getToolEstimatedDuration, getToolExecutionSteps, getToolPermissionProfile, hasUsableSecretReference, hasValidationConstraints, hashToolSchema, isAbortFailure, isAssistantMessage, isBroadExecutionAllowRule, isChatEntry, isConfirmed, isDefaultEventService, isEnforcing, isEnvReference, isExecutionControlError, isImageGenerationProvider, isMediaProviderDefinition, isMintedSpanId, isModelEffort, isProgressReportingTool, isProtectedPath, isReadOnlyCommandLine, isRegistryTransactionError, isSystemMessage, isToolDeniedOutright, isToolMessage, isUserMessage, isVideoGenerationProvider, lifecycleOf, logger, lookupModelPrice, matchesAnyPattern, messageToHistoryEntry, modelDeclaresCapability, multiSelectAction, nonVisualObservationText, normalizeProviderConfig, normalizeStructuredOutput, outboundTraceContextFor, parseParameterRule, parseStructuredResponseText, peerDriverOf, printablePeerDriver, processEnvResolver, projectPermissionPolicy, projectToolSchema, providerCallSpanId, readModelFallbackNotice, readProviderFailureDetails, readTokenUsageFromMessage, readTokenUsageFromMetadata, registerModelMetadata, registerToolPermissionProfile, removesCriticalPath, requiresFreshApproval, resolveEnvReference, resolveMediaProviderConfig, resolveModelCapabilities, resolveModelCapability, resolveModelEffort, resolvePlatformShell, resolveStructuredOutputCapability, runHooks, runRegistryTransaction, scrubSecrets, selectAction, setGlobalLogLevel, setGlobalLoggerSink, setToolProgressCallback, shellArgumentForDisplay, snapshotToolProvenance, spanIdFromMintedId, splitCommandSegments, startPeriodicTask, stopPeriodicTask, subprocessTraceEnvironment, sumHistoryUsage, sumMessagesUsage, textAction, toProviderError, toolNameMatches, toolNamesToPatterns, toolTraceContextFor, traceEnvFor, traceHeadersFor, validateAgainstJsonSchema, validateAgentConfig, validateApiKey, validateModelName, validatePermissionPattern, validateProviderName, validateUserInput, verifiedProviderCallUsage, wasToolResultAdmitted, withEventEmission, withToolProvenance, zodToJsonSchema };
2
+ import { $ as matchesAnyPattern, $a as IProviderProbeResult, $c as IToolSchema, $i as IToolExecutionRequest, $l as ITextMessagePart, $n as createToolMessage, $o as IRunOptions, $r as TMessageFormatConverter, $s as PROVIDER_FALLBACK_EVENTS, $t as TProviderUsageProvenance, A as IContextWindowState, Aa as IImageGenerationRequest, Ac as IToolEventData, Ai as IFileSystemAsync, Al as RateLimitError, An as FunctionTool, Ao as getGlobalLoggerSink, Ar as IPlatformShell, As as IParameterValidationResult, At as TOrchestrationEvent, Au as TMetadataValue, B as IPermissionPolicyContext, Ba as TImageInputSource, Bc as IRawProviderResponse, Bi as IExecutorChatResult, Bl as IModelCapabilityDeviation, Bn as IBoundedOutputOptions, Bo as IPluginExecutionContext, Br as TExecutionRecoveryErrorCode, Bs as TToolExecutor, Bt as ISequentialOrchestrationSpec, C as CONTEXT_ESTIMATE_CHARS_PER_TOKEN, Ca as IMediaProviderCredentialRequirement, Cc as IBaseEventData, Ci as AbstractAgent, Cl as ConfigurationError, Cn as IDestroyResult, Co as ILogger, Cr as outboundTraceContextFor, Cs as IRecoverableExecutionJournal, Ct as TTrustLevel, Cu as IToolWaitState, D as estimateSerializedContextTokens, Da as IImageComposeRequest, Dc as IEventServiceOwnerBinding, Di as ICredentialStore, Dl as NetworkError, Dn as TOOL_EVENT_PREFIX, Do as TUtilLogLevel, Dr as toolTraceContextFor, Ds as TExecutionJournalRecord, Dt as IExecutionProxyConfig, Du as TContextData, E as estimateContextTokensFromMessages, Ea as isMediaProviderDefinition, Ec as IEventService, Ei as ICredentialKey, El as ModelNotAvailableError, En as TOOL_EVENTS, Eo as SilentLogger, Er as subprocessTraceEnvironment, Es as IResumeToolCallsResult, Et as withEventEmission, Eu as TConfigValue, F as toolNamesToPatterns, Fa as IUriImageInputSource, Fc as IAIProvider, Fi as IEventHistoryModule, Fl as TErrorExternalInput, Fn as IEventEmitterMetrics, Fo as IPluginConfig, Fr as startPeriodicTask, Fs as IToolExecutionResult, Ft as IOrchestrationEventData, G as IPermissionLists, Ga as TStructuredOutputMechanism, Gc as TProviderNativeRawPayloadCallback, Gi as IStreamExecutionRequest, Gl as TProviderModelCapability, Gn as hasUsableSecretReference, Go as PluginCategory, Gr as Validator, Gs as TToolSearchSetting, Gt as printablePeerDriver, H as projectPermissionPolicy, Ha as isImageGenerationProvider, Hc as ITokenUsageWithCacheRead, Hi as IExecutorStreamTerminalEvent, Hl as modelDeclaresCapability, Hn as createBoundedOutput, Ho as IPluginHooks, Hr as ExecutionJournalError, Hs as IDeferredToolCatalog, Ht as AGENT_EVENTS, I as IPermissionPatternProblem, Ia as IVideoGenerationProvider, Ic as IChatOptions, Ii as IEventHistoryRecord, Il as ToolExecutionError, In as IEventEmitterMetricsSnapshot, Io as IPluginContext, Ir as stopPeriodicTask, Is as IToolProvenance, It as IOrchestrationRunResult, J as TToolArgs, Ja as IProviderDefinition, Jc as TTextDeltaCallback, Ji as IConversationContext, Jl as IHistoryEntry, Jn as IAIProviderInstance, Jo as IEventEmitterEventData, Jr as validateModelName, Js as IActionRequest, Jt as ISessionUsageTotals, K as IToolPermissionArgument, Ka as TStructuredOutputProvenance, Kc as TProviderNativeRawPayloadKind, Ki as TExecutorStreamEvent, Kl as IAssistantMessage, Kn as isEnvReference, Ko as PluginPriority, Kr as validateAgentConfig, Ks as IActionDefault, Kt as EventHistoryModule, L as findInvalidPermissionPatterns, La as IVideoGenerationRequest, Lc as IProviderNativeRawPayloadEvent, Li as IEventHistorySnapshot, Ll as ValidationError, Ln as InMemoryEventEmitterMetrics, Lo as IPluginContract, Lr as TTimerId, Ls as IToolRegistry, Lt as IOrchestrationStep, M as isBroadExecutionAllowRule, Ma as IInlineImageInputSource, Mc as TEventListener, Mi as ISession, Ml as StorageError, Mn as EventEmitterPlugin, Mo as setGlobalLogLevel, Mr as TShellKind, Ms as IToolCallScheduling, Mt as IHandoffOrchestrationSpec, Mu as TypeUtils, N as splitCommandSegments, Na as IMediaOutputRef, Nc as TEventLoggerData, Ni as ISpinner, Nl as StructuredOutputError, Nn as IEventEmitterHierarchicalEventData, No as setGlobalLoggerSink, Nr as UnsupportedShellError, Ns as IToolExecutionContext, Nt as IHierarchicalOrchestrationSpec, O as estimateToolSchemaTokens, Oa as IImageEditRequest, Oc as IExecutionEventData, Oi as IDirent, Ol as PluginError, On as DEFERRED_WITHOUT_LOADER_MESSAGE, Oo as createLogger, Or as traceEnvFor, Os as TJournalModelOptions, Ot as ORCHESTRATION_EVENTS, Ou as TLoggerData, P as applyPresetToolLists, Pa as IProviderMediaError, Pc as TEventUniversalValue, Pi as ITerminalOutput, Pl as TErrorContextData, Pn as IEventEmitterPluginOptions, Po as IPlugin, Pr as resolvePlatformShell, Ps as IToolExecutionPolicy, Pt as IOrchestrationDelegation, Q as isToolDeniedOutright, Qa as IProviderModelCatalogEntry, Qc as IParameterSchema, Qi as IStreamingChunk, Ql as ISystemMessage, Qn as createSystemMessage, Qo as TExecutionEventName, Qr as TMessageConverterRegistry, Qs as PROVIDER_CALL_EVENTS, Qt as IVerifiedProviderCallUsage, R as findPermissionPatternWarnings, Ra as IVideoJobAccepted, Rc as IProviderOptions, Ri as IChatExecutionRequest, Rl as IModelRef, Rn as shellArgumentForDisplay, Ro as IPluginData, Rr as isExecutionControlError, Rs as IToolResult, Rt as IOrchestrationStepResult, S as readTokenUsageFromMetadata, Sa as IMediaProviderConfig, Sc as IAgentEventData, Si as IManagerLifecycleOptions, Sl as CircuitBreakerOpenError, Sn as ConversationAgent, So as ConsoleLogger, Sr as isMintedSpanId, Ss as IModelJournalContext, St as TRUST_TO_MODE, Su as IToolWaitResponse, T as IContextTokenEstimateOptions, Ta as findMediaProviderDefinition, Tc as IEventObjectValue, Ti as withToolProvenance, Tl as IProviderFailureDetails, Tn as EXECUTION_EVENT_PREFIX, To as IUtilLogEntry, Tr as spanIdFromMintedId, Ts as IResumeToolCallsOptions, Tt as createExecutionProxy, Tu as TConfigData, U as IParameterRule, Ua as isVideoGenerationProvider, Uc as TProviderConfigValue, Ui as ILocalExecutorConfig, Ul as resolveModelCapabilities, Un as ENV_REFERENCE_PREFIX, Uo as IPluginOptions, Ur as ErrorUtils, Us as TOOL_SEARCH_TOOL_NAME, Ut as AGENT_EVENT_PREFIX, V as IPermissionPolicyProjection, Va as TProviderMediaResult, Vc as ITokenUsage, Vi as IExecutorStreamMessageEvent, Vl as IProviderCapabilityTable, Vn as TOutputRetention, Vo as IPluginExecutionResult, Vr as ExecutionSuspendedError, Vs as TToolMetadata, Vt as TOrchestrationPrimitive, W as IPermissionEvaluationContext, Wa as IProviderStructuredOutputCapability, Wc as TProviderNativeRawPayload, Wi as IRemoteExecutorConfig, Wl as resolveModelCapability, Wn as formatEnvReference, Wo as IPluginStats, Wr as ISimpleValidationResult, Ws as TToolSearchMode, Wt as peerDriverOf, X as evaluatePermission, Xa as IProviderEndpoint, Xc as getProviderCapabilities, Xi as IConversationService, Xl as IInlineImageMessagePart, Xn as ConversationHistory, Xo as TEventEmitterListener, Xr as validateUserInput, Xs as TActionResponse, Xt as sumHistoryUsage, Y as clearRegisteredToolProfiles, Ya as IProviderDefinitionConfig, Yc as TToolChoice, Yi as IConversationResponse, Yl as IInlineAudioMessagePart, Yn as LocalExecutor, Yo as IEventEmitterPlugin, Yr as validateProviderName, Ys as IUserInteraction, Yt as collectAssistantUsageMetadata, Z as getToolPermissionProfile, Za as IProviderModelCatalog, Zc as IObjectParameterSchema, Zi as IConversationServiceOptions, Zl as IResourceLinkMessagePart, Zn as createAssistantMessage, Zo as TEventName, Zr as MessageConverter, Zs as ISpanCompletionEventData, Zt as sumMessagesUsage, _ as getModelMaxOutput, _a as IOpenAPIToolConfig, _c as bindEventServiceOwner, _i as TToolSchemaProjectionOutcome, _l as scrubSecrets, _n as MAX_TOOL_RESULT_CHARS, _o as IAbstractTool, _r as ISchemaClosureOptions, _s as ICacheStats, _t as isReadOnlyCommandLine, _u as messageToHistoryEntry, a as runHooks, aa as TToolProgressCallback, ac as TSpanEvent, ai as AbstractAIProvider, al as IProviderFunctionCallingCapability, an as lifecycleOf, ao as TProviderCredentialReference, ar as createImageProviderFromDefinition, as as TStructuredOutputValidation, at as IPathProtectionPolicy, au as TMessageState, b as IMessageTokenUsage, ba as IToolManager, bc as generateSpanId, bi as projectToolSchema, bl as AuthenticationError, bn as admitToolResult, bo as IToolWithEventService, br as callJournaledProvider, bs as IExecutionJournal, bt as TPermissionDecision, bu as IToolContinuationPrompt, c as calculateModelCost, ca as isProgressReportingTool, cc as USER_EVENTS, ci as TProviderLoggingData, cl as IProviderNativeWebToolRequest, cn as AgentTemplates, co as TProviderModelLifecycle, cr as TEnvResolver, cs as validateAgainstJsonSchema, ct as isProtectedPath, cu as TUniversalMessagePart, d as DEFAULT_CONTEXT_WINDOW, da as CONFIRM_YES, dc as TASK_EVENT_PREFIX, di as IToolSchemaProjectionProfile, dl as IModelFallbackNotice, dn as IAgentFactoryOptions, do as findProviderDefinition, dr as IStructuredOutputResolutionInput, ds as IZodSchema, dt as TToolRiskClass, du as getMessagesForAPI, ea as TConversationContextMetadata, ec as SPAN_EVENTS, ei as TProviderMessage, el as TJSONSchemaEnum, en as verifiedProviderCallUsage, eo as IProviderProfileConfig, er as createUserMessage, es as TExecutionEventCallback, et as parseParameterRule, eu as IToolCall, f as DEFAULT_MAX_OUTPUT, fa as confirmAction, fc as AbstractEventService, fi as PARAMETER_SCHEMA_KEYWORDS, fl as TModelFallbackCallback, fn as IAgentLifecycleEvents, fo as formatSupportedProviderTypes, fr as resolveStructuredOutputCapability, fs as IZodSchemaDef, ft as UNCLASSIFIED_TOOL_FALLBACK, fu as isAssistantMessage, g as getModelContextWindow, ga as textAction, gc as StructuredEventService, gi as TOOL_SCHEMA_PROJECTION_MAX_NODES, gl as readProviderFailureDetails, gn as IToolResultSpillStore, go as IAgentTemplate, gr as ISchemaClosureChange, gs as ICacheOptions, gt as TResolveInWorkspace, gu as isUserMessage, h as formatTokenCount, ha as selectAction, hc as ObservableEventService, hi as TOOL_SCHEMA_PROJECTION_MAX_DEPTH, hl as classifyProviderFailure, hn as IToolResultAdmissionOptions, ho as IAgentConfig, hr as hasValidationConstraints, hs as ICacheKey, ht as IReadOnlyCommandContext, hu as isToolMessage, i as GuardrailExecutor, ia as IToolExecutionStep, ic as TOOL_QUEUE_EVENTS, ii as AbstractPlugin, il as IProviderCapabilities, in as isRegistryTransactionError, io as TProviderCredentialField, ir as IMediaProviderOverrides, is as TStructuredOutputSchema, it as ICriticalPathContext, iu as TEmbeddedResourceMessagePart, j as allowRulesForAutoMode, ja as IImageGenerationResult, jc as TEventExtensionValue, ji as IStats, jl as SameToolInputLoopError, jn as ToolRegistry, jo as logger, jr as IPlatformShellResolutionRequest, js as ITool, jt as IGroupChatOrchestrationSpec, ju as TToolParameters, k as IContextTokenUsage, ka as IImageGenerationProvider, kc as IOwnerPathSegment, ki as IFileSystem, kl as ProviderError, kn as assertResidentToolRemains, ko as getGlobalLogLevel, kr as traceHeadersFor, ks as IFunctionTool, kt as ORCHESTRATION_EVENT_PREFIX, ku as TMetadata, l as estimateBlendedCostPer1000, la as setToolProgressCallback, lc as USER_EVENT_PREFIX, li as IToolSchemaProjection, ll as assertProviderNativeWebToolsAvailable, ln as ITemplateApplicationResult, lo as TProviderSetupField, lr as createRecordEnvResolver, ls as ISchemaConversionOptions, lt as removesCriticalPath, lu as TUniversalMessageRole, m as findModelDefinition, ma as multiSelectAction, mc as DefaultEventService, mi as STRICT_TOOL_SCHEMA_PROFILE, ml as TProviderFailureReason, mn as DEFAULT_TOOL_RESULT_WARNING_CHARS, mo as IAgent, mr as getSchemaTypeName, ms as ICacheEntry, mt as TMatchDirection, mu as isSystemMessage, n as isEnforcing, na as TToolExecutionParameters, nc as TOOL_BODY_EVENTS, ni as AbstractTool, nl as TParameterDefaultValue, nn as IRegistryTransactionError, no as IProviderSetupHelpLink, nr as createProviderFromConfig, ns as IJsonSchemaOutput, nt as requiresFreshApproval, nu as IUriImageMessagePart, o as IModelPrice, oa as getToolEstimatedDuration, oc as readModelFallbackNotice, oi as IExecutorAwareProviderConfig, ol as IProviderNativeWebToolCapabilities, on as runRegistryTransaction, oo as TProviderCredentialResolver, or as createVideoProviderFromDefinition, os as normalizeStructuredOutput, ot as PROTECTED_DIRECTORY_NAMES, ou as TUniversalMessage, p as IModelDefinition, pa as isConfirmed, pc as DEFAULT_ABSTRACT_EVENT_SERVICE, pi as PERMISSIVE_TOOL_SCHEMA_PROFILE, pl as IProviderFailureClassification, pn as DEFAULT_TOOL_RESULT_HARD_CHARS, po as getProviderCredentialRequirement, pr as extractEnumValues, ps as IResponseFormatConfig, pt as TArgumentKind, pu as isChatEntry, q as IToolPermissionProfile, qa as IProviderCredentialRequirement, qc as TProviderOptionValueBase, qi as IContextOptions, ql as IBaseMessage, qn as resolveEnvReference, qo as EVENT_EMITTER_EVENTS, qr as validateApiKey, qs as IActionOption, qt as IAssistantUsageMetadata, r as decodeHookVerdict, ra as IProgressReportingTool, rc as TOOL_PERMISSION_EVENTS, ri as AbstractExecutor, rl as IProviderSpecificOptions, rn as IRegistryTransactionStep, ro as IProviderSetupStepDefinition, rr as normalizeProviderConfig, rs as IStructuredOutputSpec, rt as toolNameMatches, ru as IUserMessage, s as MODEL_PRICES, sa as getToolExecutionSteps, sc as TUserEvent, si as IProviderRuntimeConfig, sl as IProviderNativeWebToolCapability, sn as AgentFactory, so as TProviderModelCatalogStatus, sr as resolveMediaProviderConfig, ss as parseStructuredResponseText, st as PROTECTED_FILE_NAMES, su as TUniversalMessageMetadata, t as nonVisualObservationText, ta as TResponseMetadata, tc as SPAN_EVENT_PREFIX, ti as isAbortFailure, tl as TJSONSchemaKind, tn as IRegistryOwnedLifecycle, to as IProviderProfileDefaults, tr as ConversationStore, ts as TExecutionEventData, tt as registerToolPermissionProfile, tu as IToolMessage, u as lookupModelPrice, ua as CONFIRM_NO, uc as TASK_EVENTS, ui as IToolSchemaProjectionChange, ul as createDefaultProviderCapabilities, un as IAgentCreationStats, uo as TProviderSetupHelpLinkKind, ur as processEnvResolver, us as IZodParseResult, ut as RISK_CLASS_POLICY, uu as chatEntryToMessage, v as getModelName, va as IToolFactory, vc as bindWithOwnerPath, vi as TToolSchemaProjectionProfileBase, vl as toProviderError, vn as TToolResultAdmissionErrorCode, vo as IAbstractToolOptions, vr as closeObjectSchemas, vs as ICacheStorage, vt as DEFAULT_BACKGROUND_PERMISSION_POLICY, vu as IToolActionIdentity, w as IContextTokenEstimate, wa as IMediaProviderDefinition, wc as IEventContext, wi as snapshotToolProvenance, wl as EmptyCompletionError, wn as EXECUTION_EVENTS, wo as ILoggerOptions, wr as providerCallSpanId, ws as IResumeExecutionOptions, wt as ExecutionProxy, wu as TComplexConfigValue, x as readTokenUsageFromMessage, xa as TManagerToolParameters, xc as isDefaultEventService, xi as AbstractManager, xl as CacheIntegrityError, xn as wasToolResultAdmitted, xo as TToolExecutionFunction, xr as buildTraceparent, xs as IExecutionRoundCheckpoint, xt as TPermissionMode, xu as IToolWaitRequest, y as registerModelMetadata, ya as IAIProviderManager, yc as composeEventName, yi as hashToolSchema, yl as AgentRuntimeError, yn as ToolResultAdmissionError, yo as IToolContract, yr as zodToJsonSchema, ys as IExecutionContinuationState, yt as TBackgroundPermissionPolicy, yu as IToolContinuation, z as validatePermissionPattern, za as IVideoJobSnapshot, zc as IProviderRequest, zi as IExecutor, zl as TRoleModelMap, zn as IBoundedOutput, zo as IPluginErrorContext, zr as ExecutionRecoveryError, zs as TToolEffectAdmission, zt as IParallelOrchestrationSpec } from "./index-DEOjWLlC.js";
3
+ export { AGENT_EVENTS, AGENT_EVENT_PREFIX, AbstractAIProvider, AbstractAgent, AbstractEventService, AbstractExecutor, AbstractManager, AbstractPlugin, AbstractTool, AgentFactory, AgentRuntimeError, AgentTemplates, AuthenticationError, CONFIRM_NO, CONFIRM_YES, CONTEXT_ESTIMATE_CHARS_PER_TOKEN, CacheIntegrityError, CircuitBreakerOpenError, ConfigurationError, ConsoleLogger, ConversationAgent, ConversationAgent as Robota, ConversationHistory, ConversationStore, DEFAULT_ABSTRACT_EVENT_SERVICE, DEFAULT_BACKGROUND_PERMISSION_POLICY, DEFAULT_CONTEXT_WINDOW, DEFAULT_MAX_OUTPUT, DEFAULT_TOOL_RESULT_HARD_CHARS, DEFAULT_TOOL_RESULT_WARNING_CHARS, DEFERRED_WITHOUT_LOADER_MESSAGE, DefaultEventService, ENV_REFERENCE_PREFIX, EVENT_EMITTER_EVENTS, EXECUTION_EVENTS, EXECUTION_EVENT_PREFIX, EmptyCompletionError, ErrorUtils, EventEmitterPlugin, EventHistoryModule, ExecutionJournalError, ExecutionProxy, ExecutionRecoveryError, ExecutionSuspendedError, FunctionTool, GuardrailExecutor, type IAIProvider, type IAIProviderInstance, type IAIProviderManager, type IAbstractTool, type IAbstractToolOptions, type IActionDefault, type IActionOption, type IActionRequest, type IAgent, type IAgentConfig, type IAgentCreationStats, type IAgentEventData, type IAgentFactoryOptions, type IAgentHookDefinition, type IAgentLifecycleEvents, type IAgentTemplate, type IAssistantMessage, type IAssistantUsageMetadata, type IBaseEventData, type IBaseMessage, type IBoundedOutput, type IBoundedOutputOptions, type ICacheEntry, type ICacheKey, type ICacheOptions, type ICacheStats, type ICacheStorage, type IChatExecutionRequest, type IChatOptions, type ICommandHookDefinition, type IContextOptions, type IContextTokenEstimate, type IContextTokenEstimateOptions, type IContextTokenUsage, type IContextWindowState, type IConversationContext, type IConversationResponse, type IConversationService, type IConversationServiceOptions, type ICredentialKey, type ICredentialStore, type ICriticalPathContext, type IDeferredToolCatalog, type IDestroyResult, type IDirent, type IEventContext, type IEventEmitterEventData, type IEventEmitterHierarchicalEventData, type IEventEmitterMetrics, type IEventEmitterMetricsSnapshot, type IEventEmitterPlugin, type IEventEmitterPluginOptions, type IEventHistoryModule, type IEventHistoryRecord, type IEventHistorySnapshot, type IEventObjectValue, type IEventService, type IEventServiceOwnerBinding, type IExecutionContinuationState, type IExecutionEventData, type IExecutionJournal, type IExecutionProxyConfig, type IExecutionRoundCheckpoint, type IExecutor, IExecutorAwareProviderConfig, type IExecutorChatResult, type IExecutorStreamMessageEvent, type IExecutorStreamTerminalEvent, type IFileSystem, type IFileSystemAsync, type IFunctionTool, type IGroupChatOrchestrationSpec, type IGuardrailHookDefinition, type IGuardrailResult, type IHandoffOrchestrationSpec, type IHierarchicalOrchestrationSpec, type IHistoryEntry, type IHookGroup, type IHookInput, type IHookTypeExecutor, type IHttpHookDefinition, type IImageComposeRequest, type IImageEditRequest, type IImageGenerationProvider, type IImageGenerationRequest, type IImageGenerationResult, type IInlineAudioMessagePart, type IInlineImageInputSource, type IInlineImageMessagePart, type IJsonSchemaOutput, type ILocalExecutorConfig, ILogger, ILoggerOptions, IManagerLifecycleOptions, type IMediaOutputRef, type IMediaProviderConfig, type IMediaProviderCredentialRequirement, type IMediaProviderDefinition, type IMediaProviderOverrides, type IMessageTokenUsage, type IModelCapabilityDeviation, type IModelDefinition, type IModelEffortCapability, type IModelEffortOutcome, type IModelEffortResolution, type IModelFallbackNotice, type IModelJournalContext, type IModelPrice, type IModelRef, type IObjectParameterSchema, type IOpenAPIToolConfig, type IOrchestrationDelegation, type IOrchestrationEventData, type IOrchestrationRunResult, type IOrchestrationStep, type IOrchestrationStepResult, type IOutboundTraceContext, type IOwnerPathSegment, type IParallelOrchestrationSpec, type IParameterRule, type IParameterSchema, type IParameterValidationResult, type IPathProtectionPolicy, type IPermissionEvaluationContext, type IPermissionLists, type IPermissionPatternProblem, type IPermissionPolicyContext, type IPermissionPolicyProjection, IPlatformShell, IPlatformShellResolutionRequest, type IPlugin, type IPluginConfig, type IPluginContext, type IPluginContract, type IPluginData, type IPluginErrorContext, type IPluginExecutionContext, type IPluginExecutionResult, type IPluginHooks, type IPluginOptions, type IPluginStats, type IProgressReportingTool, type IPromptHookDefinition, type IProviderCapabilities, type IProviderCapabilityTable, type IProviderCredentialRequirement, type IProviderDefinition, type IProviderDefinitionConfig, type IProviderEndpoint, type IProviderFailureClassification, IProviderFailureDetails, type IProviderFunctionCallingCapability, type IProviderMediaError, type IProviderModelCatalog, type IProviderModelCatalogEntry, type IProviderModelEffortTable, type IProviderNativeRawPayloadEvent, type IProviderNativeWebToolCapabilities, type IProviderNativeWebToolCapability, type IProviderNativeWebToolRequest, type IProviderOptions, type IProviderProbeResult, type IProviderProfileConfig, type IProviderProfileDefaults, type IProviderRequest, IProviderRuntimeConfig, type IProviderSetupHelpLink, type IProviderSetupStepDefinition, type IProviderSpecificOptions, type IProviderStructuredOutputCapability, type IRawProviderResponse, type IReadOnlyCommandContext, type IRecoverableExecutionJournal, type IRegistryOwnedLifecycle, type IRegistryTransactionError, type IRegistryTransactionStep, type IRemoteExecutorConfig, type IResourceLinkMessagePart, type IResponseFormatConfig, type IResumeExecutionOptions, type IResumeToolCallsOptions, type IResumeToolCallsResult, type IRunOptions, type IRunTraceContext, type ISchemaClosureChange, type ISchemaClosureOptions, type ISchemaConversionOptions, type ISequentialOrchestrationSpec, type ISession, type ISessionUsageTotals, ISimpleValidationResult, type ISpanCompletionEventData, type ISpinner, type IStats, type IStreamExecutionRequest, type IStreamingChunk, type IStructuredOutputResolutionInput, type IStructuredOutputSpec, type ISubprocessTraceEnv, type ISystemMessage, type ITemplateApplicationResult, type ITerminalOutput, type ITextMessagePart, type ITokenUsage, type ITokenUsageWithCacheRead, type ITool, type IToolActionIdentity, type IToolCall, type IToolCallScheduling, type IToolContinuation, type IToolContinuationPrompt, type IToolContract, type IToolEventData, type IToolExecutionContext, type IToolExecutionPolicy, type IToolExecutionRequest, type IToolExecutionResult, type IToolExecutionStep, type IToolFactory, type IToolManager, type IToolMessage, type IToolPermissionArgument, type IToolPermissionProfile, type IToolProvenance, type IToolRegistry, type IToolResult, type IToolResultAdmissionOptions, type IToolResultSpillStore, type IToolSchema, type IToolSchemaProjection, type IToolSchemaProjectionChange, type IToolSchemaProjectionProfile, type IToolWaitRequest, type IToolWaitResponse, type IToolWaitState, type IToolWithEventService, type IUniversalObjectValue, type IUriImageInputSource, type IUriImageMessagePart, type IUserInteraction, type IUserMessage, IUtilLogEntry, type IVerifiedProviderCallUsage, type IVideoGenerationProvider, type IVideoGenerationRequest, type IVideoJobAccepted, type IVideoJobSnapshot, type IZodParseResult, type IZodSchema, type IZodSchemaDef, InMemoryEventEmitterMetrics, LocalExecutor, MAX_TOOL_RESULT_CHARS, MODEL_EFFORT_VALUES, MODEL_PRICES, MessageConverter, ModelNotAvailableError, NetworkError, ORCHESTRATION_EVENTS, ORCHESTRATION_EVENT_PREFIX, ObservableEventService, PARAMETER_SCHEMA_KEYWORDS, PERMISSIVE_TOOL_SCHEMA_PROFILE, PROTECTED_DIRECTORY_NAMES, PROTECTED_FILE_NAMES, PROVIDER_CALL_EVENTS, PROVIDER_FALLBACK_EVENTS, PluginCategory, PluginError, PluginPriority, ProviderError, RISK_CLASS_POLICY, RateLimitError, SPAN_EVENTS, SPAN_EVENT_PREFIX, STRICT_TOOL_SCHEMA_PROFILE, SameToolInputLoopError, SilentLogger, StorageError, StructuredEventService, StructuredOutputError, TASK_EVENTS, TASK_EVENT_PREFIX, type TActionResponse, type TArgumentKind, type TBackgroundPermissionPolicy, TComplexConfigValue, TConfigData, TConfigValue, TContextData, type TConversationContextMetadata, type TEmbeddedResourceMessagePart, type TEnvResolver, TErrorContextData, TErrorExternalInput, type TEventEmitterListener, type TEventExtensionValue, type TEventListener, type TEventLoggerData, type TEventName, type TEventUniversalValue, type TExecutionEventCallback, type TExecutionEventData, type TExecutionEventName, type TExecutionJournalRecord, type TExecutionRecoveryErrorCode, type TExecutorStreamEvent, type TGuardrail, type THookDefinition, type THookEvent, type THookOutcome, type THooksConfig, type TImageInputSource, type TJSONSchemaEnum, type TJSONSchemaKind, type TJournalModelOptions, TLoggerData, type TManagerToolParameters, type TMatchDirection, TMessageConverterRegistry, TMessageFormatConverter, type TMessageState, TMetadata, TMetadataValue, type TModelEffort, type TModelEffortDisposition, type TModelEffortNativeControl, type TModelEffortOutcomeCallback, type TModelEffortProviderDispatch, type TModelEffortSelection, type TModelFallbackCallback, TOOL_BODY_EVENTS, TOOL_EVENTS, TOOL_EVENT_PREFIX, TOOL_PERMISSION_EVENTS, TOOL_QUEUE_EVENTS, TOOL_SCHEMA_PROJECTION_MAX_DEPTH, TOOL_SCHEMA_PROJECTION_MAX_NODES, TOOL_SEARCH_TOOL_NAME, type TOrchestrationEvent, type TOrchestrationPrimitive, type TOutputRetention, type TParameterDefaultValue, type TPermissionDecision, type TPermissionMode, type TPrimitiveValue, type TProviderConfigValue, type TProviderCredentialField, type TProviderCredentialReference, type TProviderCredentialResolver, type TProviderFailureReason, TProviderLoggingData, type TProviderMediaResult, TProviderMessage, type TProviderModelCapability, type TProviderModelCatalogStatus, type TProviderModelLifecycle, type TProviderNativeRawPayload, type TProviderNativeRawPayloadCallback, type TProviderNativeRawPayloadKind, type TProviderOptionValueBase, type TProviderSetupField, type TProviderSetupHelpLinkKind, type TProviderUsageProvenance, TRUST_TO_MODE, type TResolveInWorkspace, type TResponseMetadata, type TRoleModelMap, type TSessionEndReason, TShellKind, type TSpanEvent, type TStructuredOutputMechanism, type TStructuredOutputProvenance, type TStructuredOutputSchema, type TStructuredOutputValidation, type TSubprocessTraceClass, type TTextDeltaCallback, type TTimerId, type TToolArgs, type TToolChoice, type TToolEffectAdmission, type TToolExecutionFunction, type TToolExecutionParameters, type TToolExecutor, type TToolMetadata, TToolParameters, type TToolProgressCallback, type TToolResultAdmissionErrorCode, type TToolRiskClass, type TToolSchemaProjectionOutcome, type TToolSchemaProjectionProfileBase, type TToolSearchMode, type TToolSearchSetting, type TTrustLevel, type TUniversalArrayValue, type TUniversalMessage, type TUniversalMessageMetadata, type TUniversalMessagePart, type TUniversalMessageRole, type TUniversalValue, type TUserEvent, TUtilLogLevel, ToolExecutionError, ToolRegistry, ToolResultAdmissionError, TypeUtils, UNCLASSIFIED_TOOL_FALLBACK, USER_EVENTS, USER_EVENT_PREFIX, UnsupportedShellError, ValidationError, Validator, admitToolResult, allowRulesForAutoMode, applyPresetToolLists, assertProviderNativeWebToolsAvailable, assertResidentToolRemains, bindEventServiceOwner, bindWithOwnerPath, buildTraceparent, calculateModelCost, callJournaledProvider, chatEntryToMessage, classifyProviderFailure, clearRegisteredToolProfiles, closeObjectSchemas, collectAssistantUsageMetadata, composeEventName, confirmAction, createAssistantMessage, createBoundedOutput, createDefaultProviderCapabilities, createExecutionProxy, createImageProviderFromDefinition, createLogger, createModelEffortOutcome, createProviderFromConfig, createRecordEnvResolver, createSystemMessage, createToolMessage, createUserMessage, createVideoProviderFromDefinition, decodeHookVerdict, estimateBlendedCostPer1000, estimateContextTokensFromMessages, estimateSerializedContextTokens, estimateToolSchemaTokens, evaluatePermission, extractEnumValues, findInvalidPermissionPatterns, findMediaProviderDefinition, findModelDefinition, findPermissionPatternWarnings, findProviderDefinition, formatEnvReference, formatSupportedProviderTypes, formatTokenCount, generateSpanId, getGlobalLogLevel, getGlobalLoggerSink, getMessagesForAPI, getModelContextWindow, getModelMaxOutput, getModelName, getProviderCapabilities, getProviderCredentialRequirement, getSchemaTypeName, getToolEstimatedDuration, getToolExecutionSteps, getToolPermissionProfile, hasUsableSecretReference, hasValidationConstraints, hashToolSchema, isAbortFailure, isAssistantMessage, isBroadExecutionAllowRule, isChatEntry, isConfirmed, isDefaultEventService, isEnforcing, isEnvReference, isExecutionControlError, isImageGenerationProvider, isMediaProviderDefinition, isMintedSpanId, isModelEffort, isProgressReportingTool, isProtectedPath, isReadOnlyCommandLine, isRegistryTransactionError, isSystemMessage, isToolDeniedOutright, isToolMessage, isUserMessage, isVideoGenerationProvider, lifecycleOf, logger, lookupModelPrice, matchesAnyPattern, messageToHistoryEntry, modelDeclaresCapability, multiSelectAction, nonVisualObservationText, normalizeProviderConfig, normalizeStructuredOutput, outboundTraceContextFor, parseParameterRule, parseStructuredResponseText, peerDriverOf, printablePeerDriver, processEnvResolver, projectPermissionPolicy, projectToolSchema, providerCallSpanId, readModelFallbackNotice, readProviderFailureDetails, readTokenUsageFromMessage, readTokenUsageFromMetadata, registerModelMetadata, registerToolPermissionProfile, removesCriticalPath, requiresFreshApproval, resolveEnvReference, resolveMediaProviderConfig, resolveModelCapabilities, resolveModelCapability, resolveModelEffort, resolvePlatformShell, resolveStructuredOutputCapability, runHooks, runRegistryTransaction, scrubSecrets, selectAction, setGlobalLogLevel, setGlobalLoggerSink, setToolProgressCallback, shellArgumentForDisplay, snapshotToolProvenance, spanIdFromMintedId, splitCommandSegments, startPeriodicTask, stopPeriodicTask, subprocessTraceEnvironment, sumHistoryUsage, sumMessagesUsage, textAction, toProviderError, toolNameMatches, toolNamesToPatterns, toolTraceContextFor, traceEnvFor, traceHeadersFor, validateAgainstJsonSchema, validateAgentConfig, validateApiKey, validateModelName, validatePermissionPattern, validateProviderName, validateUserInput, verifiedProviderCallUsage, wasToolResultAdmitted, withEventEmission, withToolProvenance, zodToJsonSchema };
@@ -1,4 +1,4 @@
1
- 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-tool-schema-_UKfY7yO.js";import{C as c,D as l,E as u,O as d,S as f,T as p,_ as m,a as h,b as g,c as _,d as v,f as y,g as b,h as x,i as S,l as C,m as w,n as T,o as E,p as D,r as ee,s as te,t as ne,u as re,v as ie,w as ae,x as oe,y as se}from"./bounded-output-BdWv9SX3.js";import{n as ce,r as le,t as ue}from"./verdict-decoder-Dz_rjoIZ.js";import de from"jssha";const fe={isPrimitive:e=>e==null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`,isArray:e=>Array.isArray(e)&&e.every(e=>fe.isUniversalValue(e)),isObject:e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Date)&&Object.values(e).every(e=>fe.isUniversalValue(e)),isUniversalValue:e=>e instanceof Date||fe.isPrimitive(e)||fe.isArray(e)||fe.isObject(e)};function pe(e){return{functionCalling:{supported:e},nativeWebTools:{webSearch:{supported:!1,enabled:!1,reason:`Provider does not declare native web search support.`},webFetch:{supported:!1,enabled:!1,reason:`Provider does not declare native web fetch support.`}}}}function me(e,t,n){n?.webSearch===!0&&he(e,`web search`,t.nativeWebTools.webSearch),n?.webFetch===!0&&he(e,`web fetch`,t.nativeWebTools.webFetch)}function he(e,t,n){if(!n.supported)throw Error(`Provider ${e} does not support native ${t}.${ge(n.reason)}`);if(!n.enabled)throw Error(`Provider ${e} supports native ${t} but it is not enabled.${ge(n.reason)}`)}function ge(e){return e?` ${e}`:``}const _e=[`none`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`];function ve(e){return typeof e==`string`&&_e.includes(e)}function ye(e,t){return{resolution:e,...t}}const be=new Map(_e.map((e,t)=>[e,t]));function xe(e,t){return{selection:e,effective:null,disposition:`not-applied`,fingerprint:`${t}|${e}|not-applied`}}function Se(e,t,n){let r=e?.models[t];if(!r)return xe(n,t);let i=(i,a)=>`${t}|${n}|${i}|${a}|${r.nativeControlId}|${e.verifiedAt}`;if(n===`auto`)return r.supportedEfforts.includes(r.defaultEffort)?{selection:n,effective:r.defaultEffort,disposition:`model-default`,fingerprint:i(r.defaultEffort,`model-default`)}:xe(n,t);if(r.supportedEfforts.includes(n))return{selection:n,effective:n,disposition:`exact`,fingerprint:i(n,`exact`)};let a=be.get(n),o=r.supportedEfforts.filter(e=>(be.get(e)??1/0)<(a??-1)).at(-1);return o?{selection:n,effective:o,disposition:`clamped`,fingerprint:i(o,`clamped`)}:xe(n,t)}function Ce(e){let t=typeof e.supportsTools==`function`&&e.supportsTools();return e.getCapabilities?.()??pe(t)}function we(e,t){return e.find(e=>e.type===t||e.aliases?.includes(t)===!0)}function Te(e){return e.map(e=>{if(!e.aliases||e.aliases.length===0)return e.type;let t=e.aliases.length===1?`alias`:`aliases`;return`${e.type} (${t}: ${e.aliases.join(`, `)})`}).join(`, `)}function Ee(e){if(e?.credentialRequirement!==void 0)return e.credentialRequirement;if(e?.requiresApiKey===!0)return{anyOf:[`apiKey`]}}function De(e,t){if(e)return e.deviations?.[t]?.capabilities??e.vendorDefault}function Oe(e,t,n){let r=De(e,t);if(!(!r||r.length===0))return r.includes(n)}function ke(e,t,n,r){return Oe(e,t,n)??r}function Ae(e){return`generateImage`in e&&typeof e.generateImage==`function`}function je(e){return`createVideo`in e&&`getVideoJob`in e&&`cancelVideoJob`in e&&typeof e.createVideo==`function`&&typeof e.getVideoJob==`function`&&typeof e.cancelVideoJob==`function`}function Me(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.type==`string`&&t.type.length>0&&(typeof t.createImageProvider==`function`||typeof t.createVideoProvider==`function`)}function Ne(e,t){return e.find(e=>e.type===t)}const Pe=`ToolSearch`,Fe=`yes`,Ie=`no`,Le=[{value:`yes`,label:`Yes`},{value:`no`,label:`No`}];function Re(e,t,n){return{id:e,title:t,description:n?.description,options:Le,maxSelect:1,default:n?.defaultYes===void 0?void 0:{values:[n.defaultYes?`yes`:`no`]}}}function ze(e,t,n,r){return{id:e,title:t,options:n,maxSelect:1,description:r?.description,allowFreeText:r?.allowFreeText,maxVisible:r?.maxVisible,default:r?.default}}function Be(e,t,n,r){return{id:e,title:t,options:n,minSelect:r?.minSelect??1,maxSelect:r?.maxSelect??n.length,description:r?.description,maxVisible:r?.maxVisible,default:r?.default}}function Ve(e,t,n){return{id:e,title:t,allowFreeText:!0,description:n?.description,masked:n?.masked,allowEmpty:n?.allowEmpty,placeholder:n?.placeholder,default:n?.default}}function He(e){return e.type===`answer`&&e.values.includes(`yes`)}function Ue(e){return`getEstimatedDuration`in e||`getExecutionSteps`in e||`setProgressCallback`in e}function We(e,t){if(Ue(e)&&e.getEstimatedDuration)return e.getEstimatedDuration(t)}function Ge(e,t){if(Ue(e)&&e.getExecutionSteps)return e.getExecutionSteps(t)}function Ke(e,t){return Ue(e)&&e.setProgressCallback?(e.setProgressCallback(t),!0):!1}function qe(e){if(e)return Object.freeze({sourceId:e.sourceId,component:e.component,origin:e.origin,...e.version===void 0?{}:{version:e.version},...e.protocolVersion===void 0?{}:{protocolVersion:e.protocolVersion},...e.generation===void 0?{}:{generation:e.generation}})}function Je(e,t){let{toolProvenance:n,...r}=e.metadata??{};if(!t)return n===void 0?e:{...e,metadata:r};let i=JSON.stringify(t),a=`Tool source (attribution only, not authority): ${i}`,o=e.parts??[];return{...e,metadata:{...r,toolProvenance:i},parts:o[0]?.type===`text`&&o[0].text===a?o:[{type:`text`,text:a},...o]}}var Ye=class{history=[];isInitialized=!1;config;async configure(e){this.config=e,await this.ensureInitialized()}getHistory(){return[...this.history]}clearHistory(){this.history=[]}addMessage(e){this.history.push(e)}validateInput(e){if(!e||typeof e!=`string`)throw Error(`Input must be a non-empty string`)}async ensureInitialized(){this.isInitialized||=(await this.initialize(),!0)}async dispose(){this.clearHistory(),this.isInitialized=!1}},Xe=class{initialized=!1;disposed=!1;constructor(e={}){this.initialized=e.readyOnConstruction===!0}async initialize(){this.initialized||(await this.doInitialize(),this.initialized=!0,this.disposed=!1)}async dispose(){await this.doDispose(),this.initialized=!1,this.disposed=!0}isInitialized(){return this.initialized}ensureInitialized(){if(this.disposed)throw Error(`${this.constructor.name} was disposed — re-initialize it before use, or build a new one`);if(!this.initialized)throw Error(`${this.constructor.name} is not initialized`)}};function Ze(e){if(!Array.isArray(e))throw Error(`Messages must be an array`);if(e.length===0)throw Error(`Messages array cannot be empty`);for(let t of e)if(!t.role||![`user`,`assistant`,`system`,`tool`].includes(t.role))throw Error(`Invalid message role: ${t.role}`)}function Qe(e){if(e){if(!Array.isArray(e))throw Error(`Tools must be an array`);for(let t of e){if(!t.name||typeof t.name!=`string`)throw Error(`Tool must have a valid name`);if(!t.description||typeof t.description!=`string`)throw Error(`Tool must have a valid description`);if(!t.parameters||typeof t.parameters!=`object`||t.parameters===null||Array.isArray(t.parameters))throw Error(`Tool must have valid parameters`)}}}async function $e(e,t,n,r){if(!e)throw Error(`Executor is required for ${t} provider. Configure an executor or use direct execution path.`);if(!r?.model)throw Error(`Model is required for executor execution in ${t} provider.`);return await e.executeChat({messages:n,options:r,provider:t,model:r.model,...r.tools&&{tools:r.tools}})}async function*et(e,t,n,r){if(!e||!e.executeChatStream)throw Error(`Streaming executor is required for ${t} provider.`);if(!r?.model)throw Error(`Model is required for executor streaming in ${t} provider.`);let i=e.executeChatStream({messages:n,options:r,provider:t,model:r.model,stream:!0,...r.tools&&{tools:r.tools}}),a=!1;for await(let e of i){if(e.kind===`terminal`){if(a)throw Error(`Executor "${t}" emitted more than one stream terminal result.`);a=!0}yield e}if(!a)throw Error(`Executor "${t}" ended a stream without a terminal result.`)}async function*tt(e,t,n,r,i){e.debug?.(`🔍 [TOOL-FLOW] AbstractAIProvider.executeStreamViaExecutorOrDirect() - Executor request`,{provider:n,model:i?.model,hasTools:!!i?.tools,toolsCount:i?.tools?.length||0,toolNames:i?.tools?.map(e=>e.name)||[]}),yield*et(t,n,r,i)}function nt(e){return e.category===`chat`}function rt(e){let t=e.data;if(!t)throw Error(`Chat entry ${e.id} has no data`);return{...t,id:e.id,timestamp:e.timestamp}}function it(e){return{id:e.id,timestamp:e.timestamp,category:`chat`,type:e.role,data:{...e}}}function at(e){return e.filter(nt).map(rt)}function ot(e){return e.role===`user`}function st(e){return e.role===`assistant`}function ct(e){return e.role===`system`}function lt(e){return e.role===`tool`}function ut(e,t,n,r){let i=e.effort!==void 0||e.effortResolution!==void 0,a=e.onModelEffortOutcome,o=i?e=>{if(r(e),a!==void 0)try{a(e)}catch(e){n.warn(`Model-effort outcome observer failed`,{error:e instanceof Error?e.message:String(e)})}}:a,s={...e.model!==void 0&&{model:e.model},...e.effort!==void 0&&{effort:e.effort},...e.effortResolution!==void 0&&{effortResolution:e.effortResolution},...o!==void 0&&{onModelEffortOutcome:o},...e.temperature!==void 0&&{temperature:e.temperature},...e.maxTokens!==void 0&&{maxTokens:e.maxTokens},...e.tools!==void 0&&{tools:e.tools}};return s.effort===void 0||s.effortResolution!==void 0||s.model===void 0?s:{...s,effortResolution:Se(t?.(),s.model,s.effort)}}function dt(e,t,n){if(t)return;let r=e.effortResolution,i=e.onModelEffortOutcome;if(r===void 0||i===void 0)return;let a=ye(r,{nativeControl:{state:`omitted`,reason:`model-effort-not-applied`},providerDispatch:{state:`sent`}});try{i(a)}catch(e){n.warn(`Model-effort outcome observer failed`,{error:e instanceof Error?e.message:String(e)})}return a}function ft(e,t,n){if(t.effort!==void 0&&n===void 0)throw Error(`Provider "${e}" did not emit a model-effort terminal outcome for a selected generic request.`)}async function pt(e,t,n){let r,i=ut(n,e.effortTable?.bind(e),t,e=>{r=e}),a=await e.chat(n.messages,i);return r??=dt(i,e.effortTable!==void 0,t),ft(e.name,i,r),{content:a.content??null,toolCalls:st(a)?a.toolCalls:void 0,model:n.model,metadata:n.metadata,...r!==void 0&&{modelEffortOutcome:r}}}async function*mt(e,t,n){if(!e.chatStream)throw Error(`[AI-PROVIDER] Streaming is not supported by provider "${e.name}"`);let r,i=ut(n,e.effortTable?.bind(e),t,e=>{r=e});for await(let t of e.chatStream(n.messages,i))yield{content:t.content??null,toolCalls:st(t)?t.toolCalls:void 0,model:n.model,metadata:n.metadata};r??=dt(i,e.effortTable!==void 0,t),ft(e.name,i,r),r!==void 0&&(yield{content:null,model:n.model,metadata:n.metadata,modelEffortOutcome:r})}const ht={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{},log:()=>{},group:()=>{},groupEnd:()=>{}};var gt=class e{static instance;globalLevel;globalSink;constructor(){this.globalLevel=`warn`}static getInstance(){return e.instance||=new e,e.instance}getGlobalLevel(){return this.globalLevel}setGlobalLevel(e){this.globalLevel=e}getGlobalSink(){return this.globalSink}setGlobalSink(e){this.globalSink=e}},_t=class{level;packageName;explicitSink;constructor(e,t={}){this.packageName=e,this.explicitSink=t.sink,this.level=t.level}get sinkLogger(){return this.explicitSink??gt.getInstance().getGlobalSink()??ht}debug(...e){if(this.shouldLog(`debug`)){let[t,n]=e;this.forward(`debug`,String(t??``),vt(n)?n:void 0)}}info(...e){if(this.shouldLog(`info`)){let[t,n]=e;this.forward(`info`,String(t??``),vt(n)?n:void 0)}}warn(...e){if(this.shouldLog(`warn`)){let[t,n]=e;this.forward(`warn`,String(t??``),vt(n)?n:void 0)}}error(...e){if(this.shouldLog(`error`)){let[t,n]=e;this.forward(`error`,String(t??``),vt(n)?n:void 0)}}log(...e){this.info(...e)}getLevel(){return this.level||gt.getInstance().getGlobalLevel()}shouldLog(e){let t=this.getLevel();if(t===`silent`)return!1;let n=[`debug`,`info`,`warn`,`error`,`silent`];return n.indexOf(e)>=n.indexOf(t)}forward(e,t,n){let r={timestamp:new Date().toISOString(),level:e,message:t,...n&&{context:n},packageName:this.packageName},i=`[${r.timestamp}] [${r.level.toUpperCase()}] [${r.packageName}] ${r.message}`;switch(e){case`debug`:this.sinkLogger.debug(i,n??{});return;case`info`:this.sinkLogger.info(i,n??{});return;case`warn`:this.sinkLogger.warn(i,n??{});return;case`error`:this.sinkLogger.error(i,n??{});return;case`silent`:return}}};function vt(e){return typeof e==`object`&&!!e&&!(e instanceof Error)&&!(e instanceof Date)&&!Array.isArray(e)}function O(e,t={}){return new _t(e,t)}function yt(e){gt.getInstance().setGlobalLevel(e)}function bt(){return gt.getInstance().getGlobalLevel()}function xt(e){gt.getInstance().setGlobalSink(e)}function St(){return gt.getInstance().getGlobalSink()}const k=O(`agents`),Ct=O(`ToolSchemaProjection`);var wt=class{config;executor;logger;quarantinedToolSchemas=new Map;constructor(e=ht){this.logger=e}async configure(e){this.config=e,this.hasExecutor(e)&&e.executor&&(this.executor=e.executor)}hasExecutor(e){return typeof e==`object`&&!!e&&`executor`in e}async*streamWithAbort(e,t){let n=e[Symbol.asyncIterator]();try{for(;!t?.aborted;){let e=await Tt(n,t);if(e.done||(await Et(t),t?.aborted))break;yield e.value}}finally{t?.aborted&&await n.return?.()}}async generateResponse(e){return pt(this,this.logger,e)}async*generateStreamingResponse(e){yield*mt(this,this.logger,e)}supportsTools(){return!0}getCapabilities(){return pe(this.supportsTools())}validateConfig(){return!0}validateMessages(e){Ze(e)}validateTools(e){Qe(e)}projectionProfile(){}projectTools(e,t){let n=this.projectionProfile();if(!n||!e)return e;let r=[];for(let a of e){let e=o(a,n);if(e.outcome!==`rejected`){r.push(e.tool);continue}let s=`${this.name}${t}${a.name}${i(a.parameters)}`;if(this.quarantinedToolSchemas.has(s))continue;this.quarantinedToolSchemas.set(s,!0);let{path:c,keyword:l,reason:u}=e.rejection??{path:``,keyword:``,reason:`rejected`};Ct.warn(`tool_schema_quarantined provider=${this.name} model=${t} tool=${a.name} path=${c} keyword=${l} reason=${u}`)}return r}validateNativeWebTools(e){me(this.name,this.getCapabilities(),e)}async executeViaExecutorOrDirect(e,t){return $e(this.executor,this.name,e,t)}async*executeStreamViaExecutorOrDirect(e,t){yield*tt(this.logger,this.executor,this.name,e,t)}async dispose(){this.executor?.dispose&&await this.executor.dispose()}};async function Tt(e,t){if(!t)return e.next();if(t.aborted)return{done:!0,value:void 0};let n,r=new Promise(e=>{n=()=>e({done:!0,value:void 0}),t.addEventListener(`abort`,n,{once:!0})});try{return await Promise.race([e.next(),r])}finally{n&&t.removeEventListener(`abort`,n)}}async function Et(e){e?.aborted||await new Promise(e=>setTimeout(e,0))}let Dt=function(e){return e.MONITORING=`monitoring`,e.LOGGING=`logging`,e.STORAGE=`storage`,e.NOTIFICATION=`notification`,e.SECURITY=`security`,e.PERFORMANCE=`performance`,e.ERROR_HANDLING=`error_handling`,e.LIMITS=`limits`,e.EVENT_PROCESSING=`event_processing`,e.CUSTOM=`custom`,e}({}),Ot=function(e){return e[e.CRITICAL=1e3]=`CRITICAL`,e[e.HIGH=800]=`HIGH`,e[e.NORMAL=500]=`NORMAL`,e[e.LOW=200]=`LOW`,e[e.MINIMAL=100]=`MINIMAL`,e}({});const A={CREATED:`created`,EXECUTION_START:`execution_start`,EXECUTION_COMPLETE:`execution_complete`,EXECUTION_ERROR:`execution_error`,AGGREGATION_COMPLETE:`aggregation_complete`,CONFIG_UPDATED:`config_updated`},kt=`agent`,j={START:`start`,COMPLETE:`complete`,ERROR:`error`,ASSISTANT_MESSAGE_START:`assistant_message_start`,ASSISTANT_MESSAGE_COMPLETE:`assistant_message_complete`,USER_MESSAGE:`user_message`,TOOL_RESULTS_TO_LLM:`tool_results_to_llm`,TOOL_RESULTS_READY:`tool_results_ready`},At=`execution`,M={CALL_START:`call_start`,CALL_COMPLETE:`call_complete`,CALL_ERROR:`call_error`,CALL_RESPONSE_READY:`call_response_ready`},jt=`tool`,Mt=`unknown_tool`,Nt=`argument_decode_error`,Pt=`tool_call_skipped`,N=(e,t)=>`${e}.${t}`,Ft={START:N(At,j.START),COMPLETE:N(At,j.COMPLETE),ERROR:N(At,j.ERROR)},It={CALL_START:N(jt,M.CALL_START),CALL_COMPLETE:N(jt,M.CALL_COMPLETE),CALL_ERROR:N(jt,M.CALL_ERROR)},Lt={EXECUTION_START:N(kt,A.EXECUTION_START),EXECUTION_COMPLETE:N(kt,A.EXECUTION_COMPLETE),EXECUTION_ERROR:N(kt,A.EXECUTION_ERROR),CREATED:N(kt,A.CREATED)},P={EXECUTION_START:Ft.START,EXECUTION_COMPLETE:Ft.COMPLETE,EXECUTION_ERROR:Ft.ERROR,TOOL_BEFORE_EXECUTE:`tool.beforeExecute`,TOOL_AFTER_EXECUTE:`tool.afterExecute`,TOOL_SUCCESS:`tool.success`,TOOL_ERROR:It.CALL_ERROR,CONVERSATION_START:`conversation.start`,CONVERSATION_COMPLETE:`conversation.complete`,CONVERSATION_ERROR:`conversation.error`,AGENT_EXECUTION_START:Lt.EXECUTION_START,AGENT_EXECUTION_COMPLETE:Lt.EXECUTION_COMPLETE,AGENT_EXECUTION_ERROR:Lt.EXECUTION_ERROR,AGENT_CREATED:Lt.CREATED,AGENT_DESTROYED:`agent.destroyed`,PLUGIN_LOADED:`plugin.loaded`,PLUGIN_UNLOADED:`plugin.unloaded`,PLUGIN_ERROR:`plugin.error`,ERROR_OCCURRED:`error.occurred`,WARNING_OCCURRED:`warning.occurred`,MODULE_INITIALIZE_START:`module.initialize.start`,MODULE_INITIALIZE_COMPLETE:`module.initialize.complete`,MODULE_INITIALIZE_ERROR:`module.initialize.error`,MODULE_EXECUTION_START:`module.execution.start`,MODULE_EXECUTION_COMPLETE:`module.execution.complete`,MODULE_EXECUTION_ERROR:`module.execution.error`,MODULE_DISPOSE_START:`module.dispose.start`,MODULE_DISPOSE_COMPLETE:`module.dispose.complete`,MODULE_DISPOSE_ERROR:`module.dispose.error`,MODULE_REGISTERED:`module.registered`,MODULE_UNREGISTERED:`module.unregistered`,EXECUTION_HIERARCHY:`execution.hierarchy`,EXECUTION_REALTIME:`execution.realtime`,TOOL_REALTIME:`tool.realtime`,CUSTOM:`custom`};var Rt=class{enabled=!0;category=`custom`;priority=Ot.NORMAL;options;eventEmitter;subscribedEvents=[];eventHandlers=new Map;pluginLogger=O(`AbstractPlugin`);stats={calls:0,errors:0,moduleEventsReceived:0,lastActivity:void 0};async initialize(e){this.options=e,e&&`enabled`in e&&typeof e.enabled==`boolean`?this.enabled=e.enabled:this.enabled=!0,e?.category&&(this.category=e.category),e?.priority!==void 0&&(this.priority=(e.priority,e.priority))}async subscribeToModuleEvents(e){if(this.eventEmitter=e,!this.options)return;let t=[];this.options.subscribeToAllModuleEvents&&t.push(P.MODULE_INITIALIZE_START,P.MODULE_INITIALIZE_COMPLETE,P.MODULE_INITIALIZE_ERROR,P.MODULE_EXECUTION_START,P.MODULE_EXECUTION_COMPLETE,P.MODULE_EXECUTION_ERROR,P.MODULE_DISPOSE_START,P.MODULE_DISPOSE_COMPLETE,P.MODULE_DISPOSE_ERROR),this.options.moduleEvents&&t.push(...this.options.moduleEvents);for(let e of t){let t=this.eventEmitter.on(e,async t=>{try{this.stats.moduleEventsReceived++,this.stats.lastActivity=new Date,await this.onModuleEvent?.(e,t)}catch(t){this.stats.errors++;let n=t instanceof Error?t:Error(String(t));this.pluginLogger.error(`Plugin "${this.name}" failed to handle module event "${String(e)}"`,{plugin:this.name,eventType:String(e),error:n.message})}}),n=this.eventHandlers.get(e);n?n.push(t):this.eventHandlers.set(e,[t]),this.subscribedEvents.push(e)}}async unsubscribeFromModuleEvents(e){for(let[t,n]of this.eventHandlers.entries())for(let r of n)e.off(t,r);this.eventHandlers.clear(),this.subscribedEvents=[],this.eventEmitter=void 0}async dispose(){this.eventEmitter&&await this.unsubscribeFromModuleEvents(this.eventEmitter)}enable(){this.enabled=!0}disable(){this.enabled=!1}isEnabled(){return this.enabled}getConfig(){return{}}updateConfig(e){}getData(){return{name:this.name,version:this.version,enabled:this.enabled,category:this.category,priority:this.priority,subscribedEvents:[...this.subscribedEvents],metadata:{moduleEventsReceived:this.stats.moduleEventsReceived,totalCalls:this.stats.calls,totalErrors:this.stats.errors}}}getStatus(){return{name:this.name,version:this.version,enabled:this.enabled,initialized:!0,category:this.category,priority:this.priority,subscribedEventsCount:this.subscribedEvents.length,hasEventEmitter:!!this.eventEmitter}}getStats(){return{enabled:this.enabled,calls:this.stats.calls,errors:this.stats.errors,moduleEventsReceived:this.stats.moduleEventsReceived,...this.stats.lastActivity&&{lastActivity:this.stats.lastActivity}}}updateCallStats(){this.stats.calls++,this.stats.lastActivity=new Date}updateErrorStats(){this.stats.errors++,this.stats.lastActivity=new Date}},zt=class{logger;constructor(e=ht){this.logger=e}supportsTools(){return!1}validateConfig(){return!0}async dispose(){}async withRetry(e,t=3,n=1e3){let r;for(let i=0;i<=t;i++)try{return await e()}catch(e){r=e instanceof Error?e:Error(String(e)),i<t&&(this.logger.warn?.(`[${this.name}] Attempt ${i+1} failed, retrying in ${n}ms`,{error:r.message,attempt:i+1,maxRetries:t}),await this.delay(n))}throw r}withTimeout(e,t){let n;return Promise.race([e.then(e=>(clearTimeout(n),e)),new Promise((e,r)=>{n=setTimeout(()=>r(Error(`Operation timed out after ${t}ms`)),t)})])}delay(e){return new Promise(t=>setTimeout(t,e))}logDebug(e,t){this.logger.debug?.(`[${this.name}] ${e}`,t)}logError(e,t,n){this.logger.error?.(`[${this.name}] ${e}`,{error:t.message,stack:t.stack,...n})}validateRequest(e){if(!e.messages||e.messages.length===0)throw Error(`Request must include at least one message`);if(!e.provider)throw Error(`Request must specify a provider`);if(!e.model)throw Error(`Request must specify a model`)}validateResponse(e){if(!e.role)throw Error(`Response must have a role`);let t=e.role===`assistant`&&`toolCalls`in e&&Array.isArray(e.toolCalls)&&e.toolCalls.length>0;if(!e.content&&!t)throw Error(`Response must have content or tool calls`)}},Bt=class{provenance;logger;eventService;constructor(e={}){this.eventService=e.eventService,this.logger=e.logger??ht}setEventService(e){this.eventService=e}getEventService(){return this.eventService}emitEvent(e,t){this.eventService&&this.eventService.emit(e,t)}async execute(e,t){return await this.executeImpl(e,t)}validate(e){return(this.schema.parameters.required||[]).every(t=>t in e)}validateParameters(e){let t=this.schema.parameters.required||[],n=[],r=e;for(let e of t)e in r||n.push(`Missing required parameter: ${e}`);return{isValid:n.length===0,errors:n}}getDescription(){return this.schema.description}getName(){return this.schema.name}};function Vt(e){return typeof e==`object`&&!!e&&typeof e.name==`string`&&typeof e.message==`string`}function Ht(e,t){if(t?.aborted===!0)return!0;if(!Vt(e))return!1;if(e.name===`AbortError`)return!0;let n=e.cause;return Vt(n)&&n.name===`AbortError`}function Ut(e=`aborted`,t){let n=t===void 0?Error(e):Error(e,{cause:t});return n.name=`AbortError`,n}var Wt=class{static toProviderFormat(e,t,n={}){if(typeof t==`function`)return t(e);if(typeof t==`string`){let r=n[t];if(r!==void 0)return r(e)}return this.toUniversalFormat(e)}static toUniversalFormat(e){return e}static extractSystemMessage(e){return e.find(e=>e.role===`system`)?.content}static filterNonSystemMessages(e){return e.filter(e=>e.role!==`system`)}},Gt=class{static validateAgentConfig(e){let t=[],n=[];return e.name||t.push(`name is required`),(!e.aiProviders||e.aiProviders.length===0)&&t.push(`aiProviders array is required and must have at least one provider`),e.defaultModel?(e.defaultModel.provider||t.push(`defaultModel.provider is required`),e.defaultModel.model||t.push(`defaultModel.model is required`)):t.push(`defaultModel is required`),e.aiProviders&&e.defaultModel?.provider&&(e.aiProviders.map(e=>e.name).includes(e.defaultModel.provider)||t.push(`defaultModel.provider "${e.defaultModel.provider}" is not found in aiProviders list`)),e.defaultModel?.temperature!==void 0&&(typeof e.defaultModel.temperature!=`number`||e.defaultModel.temperature<0||e.defaultModel.temperature>2)&&t.push(`defaultModel.temperature must be a number between 0 and 2`),e.defaultModel?.maxTokens!==void 0&&(typeof e.defaultModel.maxTokens!=`number`||e.defaultModel.maxTokens<=0)&&t.push(`defaultModel.maxTokens must be a positive number`),e.systemMessage&&e.systemMessage.length>1e3&&n.push(`systemMessage is quite long, consider keeping it concise for better performance`),e.tools&&e.tools.length>20&&n.push(`Large number of tools may impact performance, consider grouping related tools`),{isValid:t.length===0,errors:t,warnings:n}}static validateUserInput(e){let t=[],n=[];return!e||typeof e!=`string`?t.push(`Input must be a non-empty string`):(e.trim().length===0&&t.push(`Input cannot be only whitespace`),e.length>1e4&&n.push(`Very long input may be truncated by AI providers`)),{isValid:t.length===0,errors:t,warnings:n}}static validateProviderName(e){let t=[];return!e||typeof e!=`string`?t.push(`Provider name must be a non-empty string`):/^[a-zA-Z][a-zA-Z0-9_-]*$/.test(e)||t.push(`Provider name must start with a letter and contain only letters, numbers, underscores, and hyphens`),{isValid:t.length===0,errors:t}}static validateModelName(e){let t=[];return!e||typeof e!=`string`?t.push(`Model name must be a non-empty string`):e.trim().length===0&&t.push(`Model name cannot be only whitespace`),{isValid:t.length===0,errors:t}}static validateApiKey(e){let t=[];return!e||typeof e!=`string`?(t.push(`API key must be a non-empty string`),{isValid:!1,errors:t}):(e.length<10&&t.push(`API key appears to be too short`),/\s/.test(e)&&t.push(`API key should not contain whitespace`),{isValid:t.length===0,errors:t,warnings:[]})}};const Kt=Gt.validateAgentConfig,qt=Gt.validateUserInput,Jt=Gt.validateProviderName,Yt=Gt.validateModelName,Xt=Gt.validateApiKey;var Zt=class{static isRecoverable(e){return e instanceof D&&e.recoverable}static getErrorCode(e){return e instanceof D?e.code:`UNKNOWN_ERROR`}static fromUnknown(e,t=`An unknown error occurred`){return e instanceof D?e:e instanceof Error?new m(e.message||t):new m(typeof e==`string`?e:t)}static wrapProviderError(e,t,n){let r=e instanceof Error?e:Error(String(e));return new f(`Failed to ${n}`,t,r,{operation:n})}},F=class extends Error{code=`EXECUTION_JOURNAL_FAILED`;recordId;kind;constructor(e,t){super(`Execution journal failed at ${e.kind}`,{cause:t}),this.name=`ExecutionJournalError`,this.recordId=e.recordId,this.kind=e.kind}},I=class extends Error{code=`EXECUTION_SUSPENDED`;requests;constructor(e){super(`Execution is waiting for correlated tool responses`),this.name=`ExecutionSuspendedError`,this.requests=structuredClone(e)}},L=class extends Error{code;actionIds;constructor(e,t,n=[]){super(t),this.code=e,this.actionIds=n,this.name=`ExecutionRecoveryError`}};function R(e){return e instanceof F||e instanceof L||e instanceof I}function Qt(e,t){return e instanceof F?e:t instanceof F?t:e instanceof L?e:t instanceof L?t:e instanceof I&&t instanceof I?new I([...new Map([...e.requests,...t.requests].map(e=>[e.requestId,e])).values()]):e instanceof I?e:t}const $t=new Set([`rate_limit_error`]),en=new Set([`overloaded_error`]),tn=new Set([`authentication_error`,`permission_error`]),nn=new Set([`model_not_found`]),rn=new Set([`ECONNRESET`,`ECONNREFUSED`,`ENOTFOUND`,`ETIMEDOUT`,`EPIPE`,`EAI_AGAIN`,`UND_ERR_SOCKET`,`UND_ERR_CONNECT_TIMEOUT`]),an=new Set([`APIConnectionError`,`APIConnectionTimeoutError`]),on=[/\bmodel:\s*\S/i,/\bmodels?\b[^.\n]{0,80}\b(?:not found|does not exist|doesn't exist|is not available|not available|unavailable|unrecognized|not recognized|unknown)\b/i,/\b(?:no such model|unknown model|invalid model|unrecognized model|model not found)\b/i];function sn(e){return on.some(t=>t.test(e))}const cn=`[^\\s,;)"]+`;function ln(e){return e.replace(RegExp(`\\bauthorization(")?\\s*[:=]\\s*(")?(?:(?:bearer|basic)\\s+)?${cn}`,`gi`),`Authorization$1: $2[REDACTED]`).replace(RegExp(`\\bbearer\\s+${cn}`,`gi`),`Bearer [REDACTED]`).replace(RegExp(`\\b(api[-_]?key)(")?\\s*[:=]\\s*(")?${cn}`,`gi`),`$1$2: $3[REDACTED]`).replace(RegExp(`\\bkey=${cn}`,`gi`),`key=[REDACTED]`).replace(/\bsk-[A-Za-z0-9_-]{8,}/gi,`[REDACTED]`).replace(/\bAIza[0-9A-Za-z_-]{35}\b/g,`[REDACTED]`)}function z(e){return typeof e==`object`&&e?e:void 0}function un(e,t){let n=e?.[t];return typeof n==`string`&&n.length>0?n:void 0}function dn(e){let t=z(e);if(t===void 0)return{};let n=typeof t.status==`number`?t.status:void 0,r=z(t.error),i=z(r?.error),a=un(r,`type`),o=un(t,`type`)??un(i,`type`)??(a===`error`?void 0:a)??(n!==void 0&&!(e instanceof D)?un(t,`code`):void 0);return{...n!==void 0&&{status:n},...o!==void 0&&{type:o}}}function fn(e){let t=z(e)?.constructor;if(typeof t!=`function`)return;let n=t.name;return typeof n==`string`&&n.length>0?n:void 0}function pn(e){return Ht(e)||fn(e)===`APIUserAbortError`}function mn(e){let t=z(e)?.headers,n=t instanceof Headers?t.get(`retry-after`):z(t)?.[`retry-after`]??z(t)?.[`Retry-After`];if(n==null||n.trim().length===0)return;let r=Number(n);if(Number.isFinite(r))return Math.max(0,r);let i=Date.parse(n);return Number.isNaN(i)?void 0:Math.max(0,Math.round((i-Date.now())/1e3))}function hn(e){if(e.status!==void 0||e.type!==void 0)return{...e.status!==void 0&&{status:e.status},...e.type!==void 0&&{type:e.type}}}function gn(e,t,n){if(e instanceof D||pn(e))return e;let r=e instanceof Error?e:Error(typeof e==`string`?e:``),i=dn(e),a=ln(r.message||`request failed`),o=hn(i);if(i.status===429||i.type!==void 0&&$t.has(i.type))return new c(a||`${t} rate limit exceeded.`,mn(e),t,o);if(i.status===401||i.status===403||i.type!==void 0&&tn.has(i.type))return new w(a,t,o);let s=i.status===void 0||i.status===400||i.status===404,l=bn(e)||i.type!==void 0&&nn.has(i.type)||sn(a);return s&&l?new se(void 0,t,void 0,{...o,originalMessage:a}):_n(e)?new g(a,r,o,t):new f(`${n}: ${a}`,t,r,void 0,i)}function _n(e){if(e instanceof g)return!0;let t=z(e);if(t===void 0)return!1;let n=un(t,`code`);if(n!==void 0&&rn.has(n))return!0;let r=fn(e);if(r!==void 0&&an.has(r))return!0;let i=un(t,`name`);return i!==void 0&&an.has(i)?!0:i===`TypeError`&&un(t,`message`)===`fetch failed`}function vn(e){let t=[],n=new Set,r=[e];for(let e=0;e<=8&&r.length>0;e++){let e=[];for(let i of r){if(i==null||n.has(i))continue;n.add(i),t.push(i);let r=z(i);r!==void 0&&e.push(r.originalError,r.cause)}r=e}return t}const B=(e,t)=>({kind:`definitive`,classification:{switchable:e,reason:t}});function yn(e){return e instanceof f?{...e.status!==void 0&&{status:e.status},...e.type!==void 0&&{type:e.type}}:dn(e)}function bn(e){if(e instanceof D)return!1;let t=un(z(e),`code`);return t!==void 0&&nn.has(t)}function xn(e){if(e instanceof c)return B(!1,`rate-limit`);if(e instanceof w)return B(!1,`authentication`);if(e instanceof se)return B(!0,`model-unavailable`);let{status:t,type:n}=yn(e);return t===429||n!==void 0&&$t.has(n)?B(!1,`rate-limit`):t===401||t===403||n!==void 0&&tn.has(n)?B(!1,`authentication`):t===402?B(!1,`billing`):(t===void 0||t===400||t===404)&&(bn(e)||n!==void 0&&nn.has(n))?B(!0,`model-unavailable`):_n(e)?B(!1,`network`):t===529||n!==void 0&&en.has(n)?B(!0,`overloaded`):t===503?B(!0,`service-unavailable`):t===500||t===502||t===504?B(!0,`server-error`):t===404?{kind:`tentative`,classification:{switchable:!0,reason:`model-unavailable`}}:t===400||t===413?{kind:`tentative`,classification:{switchable:!1,reason:`invalid-request`}}:{kind:`none`}}function Sn(e,t){let n=vn(e);if(t?.aborted===!0||n.some(e=>pn(e)))return{switchable:!1,reason:`aborted`};let r;for(let e of n){let t=xn(e);if(t.kind!==`none`){if(r===void 0&&t.kind===`definitive`)return t.classification;if(r===void 0){r=t.classification;continue}if(t.kind===`definitive`)return t.classification.reason===`model-unavailable`?t.classification:r}}return r??{switchable:!1,reason:`unknown`}}function Cn(e,t,n){return setInterval(()=>{(async()=>{try{await n()}catch(n){e.error(`Periodic task failed`,{task:t.name,error:n instanceof Error?n.message:String(n)})}})()},t.intervalMs)}function wn(e){e&&clearInterval(e)}async function V(e,t){try{await e.append(structuredClone(t))}catch(e){throw new F(t,e)}}function Tn(e){return{...e.model!==void 0&&{model:e.model},...e.tools!==void 0&&{tools:e.tools},...e.maxTokens!==void 0&&{maxTokens:e.maxTokens},...e.temperature!==void 0&&{temperature:e.temperature},...e.effort!==void 0&&{effort:e.effort},...e.toolChoice!==void 0&&{toolChoice:e.toolChoice},...e.nativeWebTools!==void 0&&{nativeWebTools:e.nativeWebTools},...e.responseFormat!==void 0&&{responseFormat:e.responseFormat}}}async function En(e,t,n,r){if(!r)return e(t,n);let{journal:i,executionId:a,callId:o}=r;await V(i,{kind:`model-request`,recordId:`${o}:request`,executionId:a,callId:o,...r.route(),messages:t,options:Tn(n),...r.checkpoint&&{checkpoint:r.checkpoint}}),n.signal?.throwIfAborted();let s;try{s=await e(t,n)}catch(e){throw await V(i,{kind:`model-failure`,recordId:`${o}:failure`,executionId:a,callId:o,...r.route(),error:{name:e instanceof Error?e.name:`Error`,message:e instanceof Error?e.message:String(e)}}),e}return await V(i,{kind:`model-response`,recordId:`${o}:response`,executionId:a,callId:o,...r.route(),response:s}),s}function Dn(e,t){if(t)return!0;switch(e.unknownKeys){case`passthrough`:case`strip`:return!0;case`strict`:return!1;default:return}}function On(e){let t=kn(e);return t.typeName===`ZodObject`?t:void 0}function kn(e){let t=e;for(let e=0;e<=64;e+=1){let e=t.typeName===`ZodEffects`?t.schema:t.typeName===`ZodOptional`||t.typeName===`ZodNullable`||t.typeName===`ZodDefault`?t.innerType:void 0;if(!e)return t;t=An(e,`${String(t.typeName)} inner type`)}throw Error(`Zod wrapper chain exceeds 64 levels; refusing to unwrap further (cyclic schema?).`)}function An(e,t){let n=e._def;if(!n)throw Error(`${t} is missing _def; cannot convert to JSON schema.`);return n}function jn(e){if(typeof e==`string`)return`string`;if(typeof e==`number`)return`number`;if(typeof e==`boolean`)return`boolean`;if(e===null)return`null`}function Mn(e){let t=e._def;if(!t)throw Error(`Zod schema is missing _def; cannot determine required fields.`);let n=t;for(let e=0;n.typeName===`ZodEffects`&&e<=64&&n.schema;e+=1)n=An(n.schema,`ZodEffects inner type`);return n.typeName!==`ZodOptional`&&n.typeName!==`ZodNullable`&&n.typeName!==`ZodDefault`}function Nn(e){let t=An(e,`Zod schema`);if(!t.values||!Array.isArray(t.values))throw Error(`ZodEnum schema is missing enum values; cannot extract enum values.`);return t.values}function Pn(e){let t=An(e,`Zod schema`);return!!(t.checks&&t.checks.length>0)}function Fn(e){let t=An(e,`Zod schema`);if(!t.typeName)throw Error(`Zod schema has empty typeName; cannot determine schema type name.`);return t.typeName}function In(e,t={}){let n=An(e,`Zod schema`),r=On(n);if(!r)throw Error(`Zod schema root must be an object; got ${String(n.typeName)}. Wrap the fields in z.object({ … }) before converting.`);return Ln(r,t.allowAdditionalProperties)}function Ln(e,t){let n={},r=[],i=typeof e.shape==`function`?e.shape():e.shape;for(let[e,a]of Object.entries(i??{}))n[e]=Rn(a,t),Mn(a)&&r.push(e);let a=Dn(e,t);return{type:`object`,properties:n,required:r,...a!==void 0&&{additionalProperties:a}}}function Rn(e,t){let n=An(e,`Zod type`),r={};switch(n.description&&(r.description=n.description),n.typeName){case`ZodString`:return{type:`string`,...r};case`ZodNumber`:return{type:`number`,...r};case`ZodBoolean`:return{type:`boolean`,...r};case`ZodArray`:if(!n.type)throw Error(`ZodArray is missing item type; cannot convert to JSON schema.`);return{type:`array`,items:Rn(n.type,t),...r};case`ZodObject`:return{...Ln(n,t),...r};case`ZodEnum`:{let e=n.values;if(!e||!Array.isArray(e))throw Error(`ZodEnum is missing enum values; cannot convert to JSON schema.`);return{type:`string`,enum:e,...r}}case`ZodNativeEnum`:return{...Bn(n.values),...r};case`ZodDate`:return{type:`string`,format:`date-time`,...r};case`ZodLiteral`:return{...zn(n.value),...r};case`ZodUnion`:case`ZodDiscriminatedUnion`:{let e=n.options;if(!e||!Array.isArray(e)||e.length===0)throw Error(`${String(n.typeName)} is missing options; cannot convert to JSON schema.`);return{anyOf:e.map(e=>Rn(e,t)),...r}}case`ZodEffects`:if(!n.schema)throw Error(`ZodEffects is missing schema; cannot convert to JSON schema.`);return{...Rn(n.schema,t),...r};case`ZodNullable`:if(!n.innerType)throw Error(`ZodNullable is missing innerType; cannot convert to JSON schema.`);return{anyOf:[Rn(n.innerType,t),{type:`null`}],...r};case`ZodOptional`:case`ZodDefault`:if(!n.innerType)throw Error(`${String(n.typeName)} is missing innerType; cannot convert to JSON schema.`);return{...Rn(n.innerType,t),...r};case`ZodRecord`:return n.valueType?{type:`object`,additionalProperties:Rn(n.valueType,t),...r}:{type:`object`,additionalProperties:{type:`string`},...r};default:throw Error(Hn(String(n.typeName)))}}function zn(e){let t=jn(e);if(!t)throw Error(`ZodLiteral value ${String(e)} is not a JSON primitive; cannot convert to JSON schema.`);return t===`null`?{type:`null`}:{type:t,enum:[e]}}function Bn(e){if(!e||typeof e!=`object`)throw Error(`ZodNativeEnum is missing enum values; cannot convert to JSON schema.`);let t=Array.isArray(e)?e:Object.values(e),n=t.filter(e=>typeof e==`number`),r=n.length>0?n:t;if(r.length===0)throw Error(`ZodNativeEnum declares no members; cannot convert to JSON schema.`);return{type:n.length>0?`number`:`string`,enum:r}}const Vn={ZodTuple:"a tuple needs positional `items`, and the subset models `items` as ONE schema — use `z.object({...})` for a fixed-shape record, or `z.array(z.union([...]))` if order genuinely does not matter",ZodIntersection:"an intersection needs `allOf` — merge the two object schemas yourself with `.merge()`, which produces a single object node the subset can carry",ZodLazy:"a recursive schema needs `$ref` — flatten the recursion to a fixed depth, or model the nested level as `z.record(...)`",ZodDate:"use `z.string()` (optionally with `.datetime()`), which is what a provider receives"};function Hn(e){return`${e} cannot be carried by the universal JSON-schema subset: ${Vn[e]??`it has no representation in the subset`}. The subset is the one language every provider mapper forwards intact; a construct outside it would be advertised to the model and enforced by nothing.`}function Un(e){return typeof e.safeParse==`function`&&typeof e.parse==`function`}function Wn(e){if(e&&typeof e==`object`&&`issues`in e){let t=e.issues;if(Array.isArray(t))return t.map(e=>{if(e&&typeof e==`object`&&`message`in e){let t=Array.isArray(e.path)?e.path.join(`.`):``,n=String(e.message);return t?`${t}: ${n}`:n}return String(e)})}return[String(e)]}function Gn(e){if(Un(e))return{name:`structured_output`,jsonSchema:In(e),validate:t=>{let n=e.safeParse(t);return n.success?{success:!0,value:n.data}:{success:!1,issues:Wn(n.error)}}};let{jsonSchema:t,name:n}=e;return{name:n??`structured_output`,jsonSchema:t,validate:e=>{let n=Kn(t,e,`$`);return n.length===0?{success:!0,value:e}:{success:!1,issues:n}}}}function Kn(e,t,n){let r=[],i=e.type;if(e.anyOf)return Jn(e.anyOf,t,n);switch(i){case`object`:{if(typeof t!=`object`||!t||Array.isArray(t))return[`${n}: expected object, got ${Yn(t)}`];let i=t,a=e.required??[];for(let e of a)e in i||r.push(`${n}.${e}: required property missing`);let o=e.properties??{};for(let[e,t]of Object.entries(o))e in i&&r.push(...Kn(t,i[e],`${n}.${e}`));let s=e.additionalProperties;if(qn(e))for(let e of Object.keys(i))e in o||r.push(`${n}.${e}: unexpected additional property`);else if(typeof s==`object`)for(let[e,t]of Object.entries(i))e in o||r.push(...Kn(s,t,`${n}.${e}`));return r}case`array`:{if(!Array.isArray(t))return[`${n}: expected array, got ${Yn(t)}`];let i=e.items;return i&&t.forEach((e,t)=>{r.push(...Kn(i,e,`${n}[${t}]`))}),r}case`string`:return typeof t==`string`?(e.enum&&!e.enum.some(e=>e===t)&&r.push(`${n}: value ${JSON.stringify(t)} is not one of the allowed enum values`),e.pattern&&!new RegExp(e.pattern).test(t)&&r.push(`${n}: value does not match pattern ${e.pattern}`),r):[`${n}: expected string, got ${Yn(t)}`];case`number`:case`integer`:return typeof t!=`number`||Number.isNaN(t)?[`${n}: expected number, got ${Yn(t)}`]:(i===`integer`&&!Number.isInteger(t)&&r.push(`${n}: expected integer, got non-integer number`),e.minimum!==void 0&&t<e.minimum&&r.push(`${n}: value ${t} is below minimum ${e.minimum}`),e.maximum!==void 0&&t>e.maximum&&r.push(`${n}: value ${t} is above maximum ${e.maximum}`),e.enum&&!e.enum.some(e=>e===t)&&r.push(`${n}: value ${t} is not one of the allowed enum values`),r);case`boolean`:return typeof t==`boolean`?r:[`${n}: expected boolean, got ${Yn(t)}`];case`null`:return t===null?r:[`${n}: expected null, got ${Yn(t)}`];default:return i===void 0?[`${n}: schema node declares neither a type nor anyOf`]:[`${n}: unsupported schema type ${String(i)}`]}}function qn(e){let t=e.additionalProperties;return t===!1||t===void 0&&e.properties!==void 0}function Jn(e,t,n){if(e.length===0)return[`${n}: anyOf declares no members`];let r=e.map((e,r)=>Kn(e,t,`${n}|anyOf[${r}]`));return r.some(e=>e.length===0)?[]:[`${n}: value matches none of the ${e.length} allowed shapes`,...r.flat()]}function Yn(e){return e===null?`null`:Array.isArray(e)?`array`:typeof e}function Xn(e){let t=e.trim(),n=/^```(?:json)?[^\S\n]*\n([\s\S]*?)\n?```$/.exec(t),r=n?n[1]:t;try{return{success:!0,value:JSON.parse(r)}}catch(e){return{success:!1,issue:`response is not valid JSON: ${e instanceof Error?e.message:String(e)}`}}}function Zn(e,t){return Oe(e,t,`json_schema`)===!0?`response_schema`:Oe(e,t,`json_object`)===!0?`json_object`:`none`}function Qn(e){let{table:t,model:n,endpointIsVendorDefault:r}=e;if(!t)return r===!1?{mechanism:`response_schema`,provenance:`unverified-endpoint`,reason:`a custom baseURL is configured and the provider declares no capability table, so nothing here can claim the endpoint enforces the schema`}:{mechanism:`response_schema`,provenance:`undeclared`,reason:`the provider declares no capability table, so the request is sent as asked — silence is not a denial`};let i=Zn(t,n),a=t.deviations?.[n]!==void 0;return r===!1?{mechanism:i,provenance:`unverified-endpoint`,reason:`a custom baseURL is configured, so the vendor capability table describes the protocol but not necessarily the endpoint serving it`}:{mechanism:i,provenance:a?`catalog`:`vendor-default`,...i===`none`&&{reason:`${n} declares no schema transport, so the schema travels in the prompt and is enforced by validation`},...i===`json_object`&&{reason:`${n} guarantees JSON but not its shape, so the schema travels in the prompt and is enforced by validation`}}}const $n=e=>process.env[e];function er(e){return t=>e[t]}function tr(e,t){for(let n of e??[]){let e=t(n);if(typeof e==`string`&&e.trim().length>0)return e.trim()}}function nr(e,t={},n=$n){let r=e.credentialRequirement,i=t.baseUrl??tr(r?.baseUrlEnvVars,n)??e.defaults?.baseUrl;if(r===void 0)return{ok:!0,config:{...i===void 0?{}:{baseUrl:i},...t.imageCapableModels===void 0?{}:{imageCapableModels:t.imageCapableModels}}};let a=tr(r.credentialEnvVars,n),o=[];return a===void 0&&o.push(...r.credentialEnvVars),r.requiresBaseUrl===!0&&i===void 0&&o.push(...r.baseUrlEnvVars??[]),o.length>0?{ok:!1,missing:o}:{ok:!0,config:{...a===void 0?{}:{credential:a},...i===void 0?{}:{baseUrl:i},...t.imageCapableModels===void 0?{}:{imageCapableModels:t.imageCapableModels}}}}function rr(e,t={},n=$n){if(e.createImageProvider===void 0)return;let r=nr(e,t,n);if(r.ok)try{let t=e.createImageProvider(r.config);return Ae(t)?t:void 0}catch{return}}function ir(e,t={},n=$n){if(e.createVideoProvider===void 0)return;let r=nr(e,t,n);if(r.ok)try{let t=e.createVideoProvider(r.config);return je(t)?t:void 0}catch{return}}const ar=`$ENV:`;function or(e){return e.startsWith(ar)}function sr(e){return`${ar}${e}`}function cr(e,t=$n){if(!or(e))return e;let n=e.slice(5).trim();if(n.length!==0)return t(n)}function lr(e,t=$n){return e===void 0||e.length===0?!1:cr(e,t)!==void 0}function ur(e,t,n=$n){let r=we(t,e.name)?.defaults??{},i=e.model??r.model;if(!i)throw Error(`Provider ${e.name} requires model`);let a=e.apiKey??r.apiKey,o=a!==void 0&&or(a)?a.slice(5).trim():void 0,s=e.options??r.options;return{name:e.name,model:i,apiKey:a===void 0?void 0:cr(a,n),...o?{apiKeyEnv:o}:{},baseURL:e.baseURL??r.baseURL,timeout:e.timeout,...s!==void 0&&{options:s}}}function dr(e,t){let n=we(t,e.name);if(n===void 0)throw Error(`Unknown provider: ${e.name}. Currently supported: ${Te(t)}`);let r=Ee(n);if(r!==void 0&&!fr(e,r))throw Error(`Provider ${e.name} requires ${mr(r)}`);return n.createProvider(e)}function fr(e,t){return t.anyOf.some(t=>pr(e,t))}function pr(e,t){let n=e[t];return n!==void 0&&n.length>0}function mr(e){return e.anyOf.map(e=>e===`apiKey`?`apiKey (API key)`:e).join(` or `)}function H(){let e=globalThis.crypto;if(typeof e?.randomUUID==`function`)return e.randomUUID();if(typeof e?.getRandomValues==`function`){let t=e.getRandomValues(new Uint8Array(16));t[6]=(t[6]??0)&15|64,t[8]=(t[8]??0)&63|128;let n=Array.from(t,e=>e.toString(16).padStart(2,`0`)).join(``);return`${n.slice(0,8)}-${n.slice(8,12)}-${n.slice(12,16)}-${n.slice(16,20)}-${n.slice(20)}`}throw Error(`No cryptographic randomness is available on this platform (globalThis.crypto is missing both randomUUID and getRandomValues), so a unique identifier cannot be generated. This is not something to substitute Math.random for.`)}function hr(e,t){let n={id:H(),role:`user`,content:e,state:`complete`,timestamp:new Date};return t?.name&&(n.name=t.name),t?.metadata&&(n.metadata=t.metadata),t?.parts&&(n.parts=t.parts),n}function gr(e,t){let n={id:H(),role:`assistant`,content:e,state:t?.state??`complete`,timestamp:new Date};return t?.toolCalls&&(n.toolCalls=t.toolCalls),t?.metadata&&(n.metadata=t.metadata),t?.parts&&(n.parts=t.parts),n}function _r(e,t){let n={id:H(),role:`system`,content:e,state:`complete`,timestamp:new Date};return t?.name&&(n.name=t.name),t?.metadata&&(n.metadata=t.metadata),t?.parts&&(n.parts=t.parts),n}function vr(e,t){let n={id:H(),role:`tool`,content:e,toolCallId:t.toolCallId,state:`complete`,timestamp:new Date};return t.name&&(n.name=t.name),t.metadata&&(n.metadata=t.metadata),t.parts&&(n.parts=t.parts),n}var yr=class{maxMessages;entries=[];constructor(e){this.maxMessages=e?.maxMessages||0}addMessage(e){this.entries.push(it(e)),this.applyMessageLimit()}addEntry(e){this.entries.push(e)}getHistory(){return[...this.entries]}addUserMessage(e,t,n){this.addMessage(hr(e,{...t&&{metadata:t},...n&&{parts:n}}))}addAssistantMessage(e,t,n,r){this.addMessage(gr(e,{...t&&{toolCalls:t},...n&&{metadata:n},...r&&{parts:r}}))}addSystemMessage(e,t,n){this.addMessage(_r(e,{...t&&{metadata:t},...n&&{parts:n}}))}setSystemPrompt(e,t,n){let r=e=>nt(e)&&ct(rt(e)),i=this.entries.filter(e=>!r(e)),a=it(_r(e,{...t&&{metadata:t},...n&&{parts:n}}));i.unshift(a),this.entries=i}addToolMessageWithId(e,t,n,r,i){this.addMessage(vr(e,{toolCallId:t,name:n,...r&&{metadata:r},...i&&{parts:i}}))}getMessages(){return this.entries.filter(nt).map(rt)}getMessagesByRole(e){return this.getMessages().filter(t=>t.role===e)}getRecentMessages(e){return this.getMessages().slice(-e)}getMessageCount(){return this.entries.filter(nt).length}clear(){this.entries=[]}applyMessageLimit(){if(this.maxMessages<=0)return;let e=this.entries.filter(nt);if(e.length<=this.maxMessages)return;let t=e.map(rt),n=t.filter(ct),r=t.filter(e=>!ct(e)),i=Math.max(0,this.maxMessages-n.length),a=[...n,...r.slice(-i)],o=new Set(a.map(e=>e.id));this.entries=this.entries.filter(e=>!nt(e)||o.has(e.id))}},br=class{history;pendingAssistant=null;constructor(e=0){this.history=new yr({maxMessages:e})}addMessage(e){this.history.addMessage(e)}addUserMessage(e,t,n){this.history.addUserMessage(e,t,n)}addAssistantMessage(e,t,n,r){this.history.addAssistantMessage(e,t,n,r)}addSystemMessage(e,t,n){this.history.addSystemMessage(e,t,n)}setSystemPrompt(e,t,n){this.history.setSystemPrompt(e,t,n)}addToolMessage(e,t,n,r,i){this.history.addToolMessageWithId(e,t,n||`unknown`,r,i)}addToolMessageWithId(e,t,n,r,i){this.history.addToolMessageWithId(e,t,n,r,i)}addEntry(e){this.history.addEntry(e)}getHistory(){return this.history.getHistory()}getMessages(){return this.history.getMessages()}getMessagesByRole(e){return this.history.getMessagesByRole(e)}getRecentMessages(e){return this.history.getRecentMessages(e)}getMessageCount(){return this.history.getMessageCount()}beginAssistant(){this.pendingAssistant||={id:H(),content:``,toolCalls:[]}}appendStreaming(e){this.pendingAssistant||={id:H(),content:``,toolCalls:[]},this.pendingAssistant.content+=e}appendToolCall(e){this.pendingAssistant||={id:H(),content:``,toolCalls:[]},this.pendingAssistant.toolCalls.some(t=>t.id===e.id)||this.pendingAssistant.toolCalls.push(e)}commitAssistant(e,t){if(!this.pendingAssistant)return;let n=this.pendingAssistant,r=n.toolCalls.length>0,i=n.content,a={id:n.id,role:`assistant`,content:i,state:e,timestamp:new Date,...r&&{toolCalls:n.toolCalls},...t&&{metadata:t}};this.history.addMessage(a),this.pendingAssistant=null}discardPending(){this.pendingAssistant=null}hasPendingAssistant(){return this.pendingAssistant!==null}getPendingContent(){return this.pendingAssistant?.content??``}getMessagesForAPI(){return this.history.getMessages().map(e=>{let t={role:e.role,content:e.content};return st(e)&&e.state===`interrupted`&&(t.content=(t.content||``)+`
1
+ 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-tool-schema-_UKfY7yO.js";import{C as c,D as l,E as u,O as d,S as f,T as p,_ as m,a as h,b as g,c as _,d as v,f as y,g as b,h as x,i as S,l as C,m as w,n as T,o as E,p as D,r as ee,s as te,t as ne,u as re,v as ie,w as ae,x as oe,y as se}from"./bounded-output-BdWv9SX3.js";import{n as ce,r as le,t as ue}from"./verdict-decoder-Dz_rjoIZ.js";import de from"jssha";const fe={isPrimitive:e=>e==null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`,isArray:e=>Array.isArray(e)&&e.every(e=>fe.isUniversalValue(e)),isObject:e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Date)&&Object.values(e).every(e=>fe.isUniversalValue(e)),isUniversalValue:e=>e instanceof Date||fe.isPrimitive(e)||fe.isArray(e)||fe.isObject(e)};function pe(e){return{functionCalling:{supported:e},nativeWebTools:{webSearch:{supported:!1,enabled:!1,reason:`Provider does not declare native web search support.`},webFetch:{supported:!1,enabled:!1,reason:`Provider does not declare native web fetch support.`}}}}function me(e,t,n){n?.webSearch===!0&&he(e,`web search`,t.nativeWebTools.webSearch),n?.webFetch===!0&&he(e,`web fetch`,t.nativeWebTools.webFetch)}function he(e,t,n){if(!n.supported)throw Error(`Provider ${e} does not support native ${t}.${ge(n.reason)}`);if(!n.enabled)throw Error(`Provider ${e} supports native ${t} but it is not enabled.${ge(n.reason)}`)}function ge(e){return e?` ${e}`:``}const _e=[`none`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`];function ve(e){return typeof e==`string`&&_e.includes(e)}function ye(e,t){return{resolution:e,...t}}const be=new Map(_e.map((e,t)=>[e,t]));function xe(e,t){return{selection:e,effective:null,disposition:`not-applied`,fingerprint:`${t}|${e}|not-applied`}}function Se(e,t,n){let r=e?.models[t];if(!r)return xe(n,t);let i=(i,a)=>`${t}|${n}|${i}|${a}|${r.nativeControlId}|${e.verifiedAt}`;if(n===`auto`)return r.supportedEfforts.includes(r.defaultEffort)?{selection:n,effective:r.defaultEffort,disposition:`model-default`,fingerprint:i(r.defaultEffort,`model-default`)}:xe(n,t);if(r.supportedEfforts.includes(n))return{selection:n,effective:n,disposition:`exact`,fingerprint:i(n,`exact`)};let a=be.get(n),o=r.supportedEfforts.filter(e=>(be.get(e)??1/0)<(a??-1)).at(-1);return o?{selection:n,effective:o,disposition:`clamped`,fingerprint:i(o,`clamped`)}:xe(n,t)}function Ce(e){let t=typeof e.supportsTools==`function`&&e.supportsTools();return e.getCapabilities?.()??pe(t)}function we(e,t){return e.find(e=>e.type===t||e.aliases?.includes(t)===!0)}function Te(e){return e.map(e=>{if(!e.aliases||e.aliases.length===0)return e.type;let t=e.aliases.length===1?`alias`:`aliases`;return`${e.type} (${t}: ${e.aliases.join(`, `)})`}).join(`, `)}function Ee(e){if(e?.credentialRequirement!==void 0)return e.credentialRequirement;if(e?.requiresApiKey===!0)return{anyOf:[`apiKey`]}}function De(e,t){if(e)return e.deviations?.[t]?.capabilities??e.vendorDefault}function Oe(e,t,n){let r=De(e,t);if(!(!r||r.length===0))return r.includes(n)}function ke(e,t,n,r){return Oe(e,t,n)??r}function Ae(e){return`generateImage`in e&&typeof e.generateImage==`function`}function je(e){return`createVideo`in e&&`getVideoJob`in e&&`cancelVideoJob`in e&&typeof e.createVideo==`function`&&typeof e.getVideoJob==`function`&&typeof e.cancelVideoJob==`function`}function Me(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.type==`string`&&t.type.length>0&&(typeof t.createImageProvider==`function`||typeof t.createVideoProvider==`function`)}function Ne(e,t){return e.find(e=>e.type===t)}const Pe=`ToolSearch`,Fe=`yes`,Ie=`no`,Le=[{value:`yes`,label:`Yes`},{value:`no`,label:`No`}];function Re(e,t,n){return{id:e,title:t,description:n?.description,options:Le,maxSelect:1,default:n?.defaultYes===void 0?void 0:{values:[n.defaultYes?`yes`:`no`]}}}function ze(e,t,n,r){return{id:e,title:t,options:n,maxSelect:1,description:r?.description,allowFreeText:r?.allowFreeText,maxVisible:r?.maxVisible,default:r?.default}}function Be(e,t,n,r){return{id:e,title:t,options:n,minSelect:r?.minSelect??1,maxSelect:r?.maxSelect??n.length,description:r?.description,maxVisible:r?.maxVisible,default:r?.default}}function Ve(e,t,n){return{id:e,title:t,allowFreeText:!0,description:n?.description,masked:n?.masked,allowEmpty:n?.allowEmpty,placeholder:n?.placeholder,default:n?.default}}function He(e){return e.type===`answer`&&e.values.includes(`yes`)}function Ue(e){return`getEstimatedDuration`in e||`getExecutionSteps`in e||`setProgressCallback`in e}function We(e,t){if(Ue(e)&&e.getEstimatedDuration)return e.getEstimatedDuration(t)}function Ge(e,t){if(Ue(e)&&e.getExecutionSteps)return e.getExecutionSteps(t)}function Ke(e,t){return Ue(e)&&e.setProgressCallback?(e.setProgressCallback(t),!0):!1}function qe(e){if(e)return Object.freeze({sourceId:e.sourceId,component:e.component,origin:e.origin,...e.version===void 0?{}:{version:e.version},...e.protocolVersion===void 0?{}:{protocolVersion:e.protocolVersion},...e.generation===void 0?{}:{generation:e.generation}})}function Je(e,t){let{toolProvenance:n,...r}=e.metadata??{};if(!t)return n===void 0?e:{...e,metadata:r};let i=JSON.stringify(t),a=`Tool source (attribution only, not authority): ${i}`,o=e.parts??[];return{...e,metadata:{...r,toolProvenance:i},parts:o[0]?.type===`text`&&o[0].text===a?o:[{type:`text`,text:a},...o]}}var Ye=class{history=[];isInitialized=!1;config;async configure(e){this.config=e,await this.ensureInitialized()}getHistory(){return[...this.history]}clearHistory(){this.history=[]}addMessage(e){this.history.push(e)}validateInput(e){if(!e||typeof e!=`string`)throw Error(`Input must be a non-empty string`)}async ensureInitialized(){this.isInitialized||=(await this.initialize(),!0)}async dispose(){this.clearHistory(),this.isInitialized=!1}},Xe=class{initialized=!1;disposed=!1;constructor(e={}){this.initialized=e.readyOnConstruction===!0}async initialize(){this.initialized||(await this.doInitialize(),this.initialized=!0,this.disposed=!1)}async dispose(){await this.doDispose(),this.initialized=!1,this.disposed=!0}isInitialized(){return this.initialized}ensureInitialized(){if(this.disposed)throw Error(`${this.constructor.name} was disposed — re-initialize it before use, or build a new one`);if(!this.initialized)throw Error(`${this.constructor.name} is not initialized`)}};function Ze(e){if(!Array.isArray(e))throw Error(`Messages must be an array`);if(e.length===0)throw Error(`Messages array cannot be empty`);for(let t of e)if(!t.role||![`user`,`assistant`,`system`,`tool`].includes(t.role))throw Error(`Invalid message role: ${t.role}`)}function Qe(e){if(e){if(!Array.isArray(e))throw Error(`Tools must be an array`);for(let t of e){if(!t.name||typeof t.name!=`string`)throw Error(`Tool must have a valid name`);if(!t.description||typeof t.description!=`string`)throw Error(`Tool must have a valid description`);if(!t.parameters||typeof t.parameters!=`object`||t.parameters===null||Array.isArray(t.parameters))throw Error(`Tool must have valid parameters`)}}}async function $e(e,t,n,r){if(!e)throw Error(`Executor is required for ${t} provider. Configure an executor or use direct execution path.`);if(!r?.model)throw Error(`Model is required for executor execution in ${t} provider.`);return await e.executeChat({messages:n,options:r,provider:t,model:r.model,...r.tools&&{tools:r.tools}})}async function*et(e,t,n,r){if(!e||!e.executeChatStream)throw Error(`Streaming executor is required for ${t} provider.`);if(!r?.model)throw Error(`Model is required for executor streaming in ${t} provider.`);let i=e.executeChatStream({messages:n,options:r,provider:t,model:r.model,stream:!0,...r.tools&&{tools:r.tools}}),a=!1;for await(let e of i){if(e.kind===`terminal`){if(a)throw Error(`Executor "${t}" emitted more than one stream terminal result.`);a=!0}yield e}if(!a)throw Error(`Executor "${t}" ended a stream without a terminal result.`)}async function*tt(e,t,n,r,i){e.debug?.(`🔍 [TOOL-FLOW] AbstractAIProvider.executeStreamViaExecutorOrDirect() - Executor request`,{provider:n,model:i?.model,hasTools:!!i?.tools,toolsCount:i?.tools?.length||0,toolNames:i?.tools?.map(e=>e.name)||[]}),yield*et(t,n,r,i)}function nt(e){return e.category===`chat`}function rt(e){let t=e.data;if(!t)throw Error(`Chat entry ${e.id} has no data`);return{...t,id:e.id,timestamp:e.timestamp}}function it(e){return{id:e.id,timestamp:e.timestamp,category:`chat`,type:e.role,data:{...e}}}function at(e){return e.filter(nt).map(rt)}function ot(e){return e.role===`user`}function st(e){return e.role===`assistant`}function ct(e){return e.role===`system`}function lt(e){return e.role===`tool`}function ut(e,t,n,r){let i=e.effort!==void 0||e.effortResolution!==void 0,a=e.onModelEffortOutcome,o=i?e=>{if(r(e),a!==void 0)try{a(e)}catch(e){n.warn(`Model-effort outcome observer failed`,{error:e instanceof Error?e.message:String(e)})}}:a,s={...e.model!==void 0&&{model:e.model},...e.effort!==void 0&&{effort:e.effort},...e.effortResolution!==void 0&&{effortResolution:e.effortResolution},...o!==void 0&&{onModelEffortOutcome:o},...e.temperature!==void 0&&{temperature:e.temperature},...e.maxTokens!==void 0&&{maxTokens:e.maxTokens},...e.tools!==void 0&&{tools:e.tools}};return s.effort===void 0||s.effortResolution!==void 0||s.model===void 0?s:{...s,effortResolution:Se(t?.(),s.model,s.effort)}}function dt(e,t,n){if(t)return;let r=e.effortResolution,i=e.onModelEffortOutcome;if(r===void 0||i===void 0)return;let a=ye(r,{nativeControl:{state:`omitted`,reason:`model-effort-not-applied`},providerDispatch:{state:`sent`}});try{i(a)}catch(e){n.warn(`Model-effort outcome observer failed`,{error:e instanceof Error?e.message:String(e)})}return a}function ft(e,t,n){if(t.effort!==void 0&&n===void 0)throw Error(`Provider "${e}" did not emit a model-effort terminal outcome for a selected generic request.`)}async function pt(e,t,n){let r,i=ut(n,e.effortTable?.bind(e),t,e=>{r=e}),a=await e.chat(n.messages,i);return r??=dt(i,e.effortTable!==void 0,t),ft(e.name,i,r),{content:a.content??null,toolCalls:st(a)?a.toolCalls:void 0,model:n.model,metadata:n.metadata,...r!==void 0&&{modelEffortOutcome:r}}}async function*mt(e,t,n){if(!e.chatStream)throw Error(`[AI-PROVIDER] Streaming is not supported by provider "${e.name}"`);let r,i=ut(n,e.effortTable?.bind(e),t,e=>{r=e});for await(let t of e.chatStream(n.messages,i))yield{content:t.content??null,toolCalls:st(t)?t.toolCalls:void 0,model:n.model,metadata:n.metadata};r??=dt(i,e.effortTable!==void 0,t),ft(e.name,i,r),r!==void 0&&(yield{content:null,model:n.model,metadata:n.metadata,modelEffortOutcome:r})}const ht={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{},log:()=>{},group:()=>{},groupEnd:()=>{}};var gt=class e{static instance;globalLevel;globalSink;constructor(){this.globalLevel=`warn`}static getInstance(){return e.instance||=new e,e.instance}getGlobalLevel(){return this.globalLevel}setGlobalLevel(e){this.globalLevel=e}getGlobalSink(){return this.globalSink}setGlobalSink(e){this.globalSink=e}},_t=class{level;packageName;explicitSink;constructor(e,t={}){this.packageName=e,this.explicitSink=t.sink,this.level=t.level}get sinkLogger(){return this.explicitSink??gt.getInstance().getGlobalSink()??ht}debug(...e){if(this.shouldLog(`debug`)){let[t,n]=e;this.forward(`debug`,String(t??``),vt(n)?n:void 0)}}info(...e){if(this.shouldLog(`info`)){let[t,n]=e;this.forward(`info`,String(t??``),vt(n)?n:void 0)}}warn(...e){if(this.shouldLog(`warn`)){let[t,n]=e;this.forward(`warn`,String(t??``),vt(n)?n:void 0)}}error(...e){if(this.shouldLog(`error`)){let[t,n]=e;this.forward(`error`,String(t??``),vt(n)?n:void 0)}}log(...e){this.info(...e)}getLevel(){return this.level||gt.getInstance().getGlobalLevel()}shouldLog(e){let t=this.getLevel();if(t===`silent`)return!1;let n=[`debug`,`info`,`warn`,`error`,`silent`];return n.indexOf(e)>=n.indexOf(t)}forward(e,t,n){let r={timestamp:new Date().toISOString(),level:e,message:t,...n&&{context:n},packageName:this.packageName},i=`[${r.timestamp}] [${r.level.toUpperCase()}] [${r.packageName}] ${r.message}`;switch(e){case`debug`:this.sinkLogger.debug(i,n??{});return;case`info`:this.sinkLogger.info(i,n??{});return;case`warn`:this.sinkLogger.warn(i,n??{});return;case`error`:this.sinkLogger.error(i,n??{});return;case`silent`:return}}};function vt(e){return typeof e==`object`&&!!e&&!(e instanceof Error)&&!(e instanceof Date)&&!Array.isArray(e)}function O(e,t={}){return new _t(e,t)}function yt(e){gt.getInstance().setGlobalLevel(e)}function bt(){return gt.getInstance().getGlobalLevel()}function xt(e){gt.getInstance().setGlobalSink(e)}function St(){return gt.getInstance().getGlobalSink()}const k=O(`agents`),Ct=O(`ToolSchemaProjection`);var wt=class{config;executor;logger;quarantinedToolSchemas=new Map;constructor(e=ht){this.logger=e}async configure(e){this.config=e,this.hasExecutor(e)&&e.executor&&(this.executor=e.executor)}hasExecutor(e){return typeof e==`object`&&!!e&&`executor`in e}async*streamWithAbort(e,t){let n=e[Symbol.asyncIterator]();try{for(;!t?.aborted;){let e=await Tt(n,t);if(e.done||(await Et(t),t?.aborted))break;yield e.value}}finally{t?.aborted&&await n.return?.()}}async generateResponse(e){return pt(this,this.logger,e)}async*generateStreamingResponse(e){yield*mt(this,this.logger,e)}supportsTools(){return!0}getCapabilities(){return pe(this.supportsTools())}validateConfig(){return!0}validateMessages(e){Ze(e)}validateTools(e){Qe(e)}projectionProfile(){}projectTools(e,t){let n=this.projectionProfile();if(!n||!e)return e;let r=[];for(let a of e){let e=o(a,n);if(e.outcome!==`rejected`){r.push(e.tool);continue}let s=`${this.name}${t}${a.name}${i(a.parameters)}`;if(this.quarantinedToolSchemas.has(s))continue;this.quarantinedToolSchemas.set(s,!0);let{path:c,keyword:l,reason:u}=e.rejection??{path:``,keyword:``,reason:`rejected`};Ct.warn(`tool_schema_quarantined provider=${this.name} model=${t} tool=${a.name} path=${c} keyword=${l} reason=${u}`)}return r}validateNativeWebTools(e){me(this.name,this.getCapabilities(),e)}async executeViaExecutorOrDirect(e,t){return $e(this.executor,this.name,e,t)}async*executeStreamViaExecutorOrDirect(e,t){yield*tt(this.logger,this.executor,this.name,e,t)}async dispose(){this.executor?.dispose&&await this.executor.dispose()}};async function Tt(e,t){if(!t)return e.next();if(t.aborted)return{done:!0,value:void 0};let n,r=new Promise(e=>{n=()=>e({done:!0,value:void 0}),t.addEventListener(`abort`,n,{once:!0})});try{return await Promise.race([e.next(),r])}finally{n&&t.removeEventListener(`abort`,n)}}async function Et(e){e?.aborted||await new Promise(e=>setTimeout(e,0))}let Dt=function(e){return e.MONITORING=`monitoring`,e.LOGGING=`logging`,e.STORAGE=`storage`,e.NOTIFICATION=`notification`,e.SECURITY=`security`,e.PERFORMANCE=`performance`,e.ERROR_HANDLING=`error_handling`,e.LIMITS=`limits`,e.EVENT_PROCESSING=`event_processing`,e.CUSTOM=`custom`,e}({}),Ot=function(e){return e[e.CRITICAL=1e3]=`CRITICAL`,e[e.HIGH=800]=`HIGH`,e[e.NORMAL=500]=`NORMAL`,e[e.LOW=200]=`LOW`,e[e.MINIMAL=100]=`MINIMAL`,e}({});const A={CREATED:`created`,EXECUTION_START:`execution_start`,EXECUTION_COMPLETE:`execution_complete`,EXECUTION_ERROR:`execution_error`,AGGREGATION_COMPLETE:`aggregation_complete`,CONFIG_UPDATED:`config_updated`},kt=`agent`,j={START:`start`,COMPLETE:`complete`,ERROR:`error`,ASSISTANT_MESSAGE_START:`assistant_message_start`,ASSISTANT_MESSAGE_COMPLETE:`assistant_message_complete`,USER_MESSAGE:`user_message`,TOOL_RESULTS_TO_LLM:`tool_results_to_llm`,TOOL_RESULTS_READY:`tool_results_ready`},At=`execution`,M={CALL_START:`call_start`,CALL_COMPLETE:`call_complete`,CALL_ERROR:`call_error`,CALL_RESPONSE_READY:`call_response_ready`},jt=`tool`,Mt=`unknown_tool`,Nt=`argument_decode_error`,Pt=`tool_call_skipped`,N=(e,t)=>`${e}.${t}`,Ft={START:N(At,j.START),COMPLETE:N(At,j.COMPLETE),ERROR:N(At,j.ERROR)},It={CALL_START:N(jt,M.CALL_START),CALL_COMPLETE:N(jt,M.CALL_COMPLETE),CALL_ERROR:N(jt,M.CALL_ERROR)},Lt={EXECUTION_START:N(kt,A.EXECUTION_START),EXECUTION_COMPLETE:N(kt,A.EXECUTION_COMPLETE),EXECUTION_ERROR:N(kt,A.EXECUTION_ERROR),CREATED:N(kt,A.CREATED)},P={EXECUTION_START:Ft.START,EXECUTION_COMPLETE:Ft.COMPLETE,EXECUTION_ERROR:Ft.ERROR,TOOL_BEFORE_EXECUTE:`tool.beforeExecute`,TOOL_AFTER_EXECUTE:`tool.afterExecute`,TOOL_SUCCESS:`tool.success`,TOOL_ERROR:It.CALL_ERROR,CONVERSATION_START:`conversation.start`,CONVERSATION_COMPLETE:`conversation.complete`,CONVERSATION_ERROR:`conversation.error`,AGENT_EXECUTION_START:Lt.EXECUTION_START,AGENT_EXECUTION_COMPLETE:Lt.EXECUTION_COMPLETE,AGENT_EXECUTION_ERROR:Lt.EXECUTION_ERROR,AGENT_CREATED:Lt.CREATED,AGENT_DESTROYED:`agent.destroyed`,PLUGIN_LOADED:`plugin.loaded`,PLUGIN_UNLOADED:`plugin.unloaded`,PLUGIN_ERROR:`plugin.error`,ERROR_OCCURRED:`error.occurred`,WARNING_OCCURRED:`warning.occurred`,MODULE_INITIALIZE_START:`module.initialize.start`,MODULE_INITIALIZE_COMPLETE:`module.initialize.complete`,MODULE_INITIALIZE_ERROR:`module.initialize.error`,MODULE_EXECUTION_START:`module.execution.start`,MODULE_EXECUTION_COMPLETE:`module.execution.complete`,MODULE_EXECUTION_ERROR:`module.execution.error`,MODULE_DISPOSE_START:`module.dispose.start`,MODULE_DISPOSE_COMPLETE:`module.dispose.complete`,MODULE_DISPOSE_ERROR:`module.dispose.error`,MODULE_REGISTERED:`module.registered`,MODULE_UNREGISTERED:`module.unregistered`,EXECUTION_HIERARCHY:`execution.hierarchy`,EXECUTION_REALTIME:`execution.realtime`,TOOL_REALTIME:`tool.realtime`,CUSTOM:`custom`};var Rt=class{enabled=!0;category=`custom`;priority=Ot.NORMAL;options;eventEmitter;subscribedEvents=[];eventHandlers=new Map;pluginLogger=O(`AbstractPlugin`);stats={calls:0,errors:0,moduleEventsReceived:0,lastActivity:void 0};async initialize(e){this.options=e,e&&`enabled`in e&&typeof e.enabled==`boolean`?this.enabled=e.enabled:this.enabled=!0,e?.category&&(this.category=e.category),e?.priority!==void 0&&(this.priority=(e.priority,e.priority))}async subscribeToModuleEvents(e){if(this.eventEmitter=e,!this.options)return;let t=[];this.options.subscribeToAllModuleEvents&&t.push(P.MODULE_INITIALIZE_START,P.MODULE_INITIALIZE_COMPLETE,P.MODULE_INITIALIZE_ERROR,P.MODULE_EXECUTION_START,P.MODULE_EXECUTION_COMPLETE,P.MODULE_EXECUTION_ERROR,P.MODULE_DISPOSE_START,P.MODULE_DISPOSE_COMPLETE,P.MODULE_DISPOSE_ERROR),this.options.moduleEvents&&t.push(...this.options.moduleEvents);for(let e of t){let t=this.eventEmitter.on(e,async t=>{try{this.stats.moduleEventsReceived++,this.stats.lastActivity=new Date,await this.onModuleEvent?.(e,t)}catch(t){this.stats.errors++;let n=t instanceof Error?t:Error(String(t));this.pluginLogger.error(`Plugin "${this.name}" failed to handle module event "${String(e)}"`,{plugin:this.name,eventType:String(e),error:n.message})}}),n=this.eventHandlers.get(e);n?n.push(t):this.eventHandlers.set(e,[t]),this.subscribedEvents.push(e)}}async unsubscribeFromModuleEvents(e){for(let[t,n]of this.eventHandlers.entries())for(let r of n)e.off(t,r);this.eventHandlers.clear(),this.subscribedEvents=[],this.eventEmitter=void 0}async dispose(){this.eventEmitter&&await this.unsubscribeFromModuleEvents(this.eventEmitter)}enable(){this.enabled=!0}disable(){this.enabled=!1}isEnabled(){return this.enabled}getConfig(){return{}}updateConfig(e){}getData(){return{name:this.name,version:this.version,enabled:this.enabled,category:this.category,priority:this.priority,subscribedEvents:[...this.subscribedEvents],metadata:{moduleEventsReceived:this.stats.moduleEventsReceived,totalCalls:this.stats.calls,totalErrors:this.stats.errors}}}getStatus(){return{name:this.name,version:this.version,enabled:this.enabled,initialized:!0,category:this.category,priority:this.priority,subscribedEventsCount:this.subscribedEvents.length,hasEventEmitter:!!this.eventEmitter}}getStats(){return{enabled:this.enabled,calls:this.stats.calls,errors:this.stats.errors,moduleEventsReceived:this.stats.moduleEventsReceived,...this.stats.lastActivity&&{lastActivity:this.stats.lastActivity}}}updateCallStats(){this.stats.calls++,this.stats.lastActivity=new Date}updateErrorStats(){this.stats.errors++,this.stats.lastActivity=new Date}},zt=class{logger;constructor(e=ht){this.logger=e}supportsTools(){return!1}validateConfig(){return!0}async dispose(){}async withRetry(e,t=3,n=1e3){let r;for(let i=0;i<=t;i++)try{return await e()}catch(e){r=e instanceof Error?e:Error(String(e)),i<t&&(this.logger.warn?.(`[${this.name}] Attempt ${i+1} failed, retrying in ${n}ms`,{error:r.message,attempt:i+1,maxRetries:t}),await this.delay(n))}throw r}withTimeout(e,t){let n;return Promise.race([e.then(e=>(clearTimeout(n),e)),new Promise((e,r)=>{n=setTimeout(()=>r(Error(`Operation timed out after ${t}ms`)),t)})])}delay(e){return new Promise(t=>setTimeout(t,e))}logDebug(e,t){this.logger.debug?.(`[${this.name}] ${e}`,t)}logError(e,t,n){this.logger.error?.(`[${this.name}] ${e}`,{error:t.message,stack:t.stack,...n})}validateRequest(e){if(!e.messages||e.messages.length===0)throw Error(`Request must include at least one message`);if(!e.provider)throw Error(`Request must specify a provider`);if(!e.model)throw Error(`Request must specify a model`)}validateResponse(e){if(!e.role)throw Error(`Response must have a role`);let t=e.role===`assistant`&&`toolCalls`in e&&Array.isArray(e.toolCalls)&&e.toolCalls.length>0;if(!e.content&&!t)throw Error(`Response must have content or tool calls`)}},Bt=class{provenance;logger;eventService;constructor(e={}){this.eventService=e.eventService,this.logger=e.logger??ht}setEventService(e){this.eventService=e}getEventService(){return this.eventService}emitEvent(e,t){this.eventService&&this.eventService.emit(e,t)}async execute(e,t){return await this.executeImpl(e,t)}validate(e){return(this.schema.parameters.required||[]).every(t=>t in e)}validateParameters(e){let t=this.schema.parameters.required||[],n=[],r=e;for(let e of t)e in r||n.push(`Missing required parameter: ${e}`);return{isValid:n.length===0,errors:n}}getDescription(){return this.schema.description}getName(){return this.schema.name}};function Vt(e){return typeof e==`object`&&!!e&&typeof e.name==`string`&&typeof e.message==`string`}function Ht(e,t){if(t?.aborted===!0)return!0;if(!Vt(e))return!1;if(e.name===`AbortError`)return!0;let n=e.cause;return Vt(n)&&n.name===`AbortError`}function Ut(e=`aborted`,t){let n=t===void 0?Error(e):Error(e,{cause:t});return n.name=`AbortError`,n}var Wt=class{static toProviderFormat(e,t,n={}){if(typeof t==`function`)return t(e);if(typeof t==`string`){let r=n[t];if(r!==void 0)return r(e)}return this.toUniversalFormat(e)}static toUniversalFormat(e){return e}static extractSystemMessage(e){return e.find(e=>e.role===`system`)?.content}static filterNonSystemMessages(e){return e.filter(e=>e.role!==`system`)}},Gt=class{static validateAgentConfig(e){let t=[],n=[];return e.name||t.push(`name is required`),(!e.aiProviders||e.aiProviders.length===0)&&t.push(`aiProviders array is required and must have at least one provider`),e.defaultModel?(e.defaultModel.provider||t.push(`defaultModel.provider is required`),e.defaultModel.model||t.push(`defaultModel.model is required`)):t.push(`defaultModel is required`),e.aiProviders&&e.defaultModel?.provider&&(e.aiProviders.map(e=>e.name).includes(e.defaultModel.provider)||t.push(`defaultModel.provider "${e.defaultModel.provider}" is not found in aiProviders list`)),e.defaultModel?.temperature!==void 0&&(typeof e.defaultModel.temperature!=`number`||e.defaultModel.temperature<0||e.defaultModel.temperature>2)&&t.push(`defaultModel.temperature must be a number between 0 and 2`),e.defaultModel?.maxTokens!==void 0&&(typeof e.defaultModel.maxTokens!=`number`||e.defaultModel.maxTokens<=0)&&t.push(`defaultModel.maxTokens must be a positive number`),e.systemMessage&&e.systemMessage.length>1e3&&n.push(`systemMessage is quite long, consider keeping it concise for better performance`),e.tools&&e.tools.length>20&&n.push(`Large number of tools may impact performance, consider grouping related tools`),{isValid:t.length===0,errors:t,warnings:n}}static validateUserInput(e){let t=[],n=[];return!e||typeof e!=`string`?t.push(`Input must be a non-empty string`):(e.trim().length===0&&t.push(`Input cannot be only whitespace`),e.length>1e4&&n.push(`Very long input may be truncated by AI providers`)),{isValid:t.length===0,errors:t,warnings:n}}static validateProviderName(e){let t=[];return!e||typeof e!=`string`?t.push(`Provider name must be a non-empty string`):/^[a-zA-Z][a-zA-Z0-9_-]*$/.test(e)||t.push(`Provider name must start with a letter and contain only letters, numbers, underscores, and hyphens`),{isValid:t.length===0,errors:t}}static validateModelName(e){let t=[];return!e||typeof e!=`string`?t.push(`Model name must be a non-empty string`):e.trim().length===0&&t.push(`Model name cannot be only whitespace`),{isValid:t.length===0,errors:t}}static validateApiKey(e){let t=[];return!e||typeof e!=`string`?(t.push(`API key must be a non-empty string`),{isValid:!1,errors:t}):(e.length<10&&t.push(`API key appears to be too short`),/\s/.test(e)&&t.push(`API key should not contain whitespace`),{isValid:t.length===0,errors:t,warnings:[]})}};const Kt=Gt.validateAgentConfig,qt=Gt.validateUserInput,Jt=Gt.validateProviderName,Yt=Gt.validateModelName,Xt=Gt.validateApiKey;var Zt=class{static isRecoverable(e){return e instanceof D&&e.recoverable}static getErrorCode(e){return e instanceof D?e.code:`UNKNOWN_ERROR`}static fromUnknown(e,t=`An unknown error occurred`){return e instanceof D?e:e instanceof Error?new m(e.message||t):new m(typeof e==`string`?e:t)}static wrapProviderError(e,t,n){let r=e instanceof Error?e:Error(String(e));return new f(`Failed to ${n}`,t,r,{operation:n})}},F=class extends Error{code=`EXECUTION_JOURNAL_FAILED`;recordId;kind;constructor(e,t){super(`Execution journal failed at ${e.kind}`,{cause:t}),this.name=`ExecutionJournalError`,this.recordId=e.recordId,this.kind=e.kind}},I=class extends Error{code=`EXECUTION_SUSPENDED`;requests;constructor(e){super(`Execution is waiting for correlated tool responses`),this.name=`ExecutionSuspendedError`,this.requests=structuredClone(e)}},L=class extends Error{code;actionIds;constructor(e,t,n=[]){super(t),this.code=e,this.actionIds=n,this.name=`ExecutionRecoveryError`}};function R(e){return e instanceof F||e instanceof L||e instanceof I}function Qt(e,t){return e instanceof F?e:t instanceof F?t:e instanceof L?e:t instanceof L?t:e instanceof I&&t instanceof I?new I([...new Map([...e.requests,...t.requests].map(e=>[e.requestId,e])).values()]):e instanceof I?e:t}const $t=new Set([`rate_limit_error`]),en=new Set([`overloaded_error`]),tn=new Set([`authentication_error`,`permission_error`]),nn=new Set([`model_not_found`]),rn=new Set([`ECONNRESET`,`ECONNREFUSED`,`ENOTFOUND`,`ETIMEDOUT`,`EPIPE`,`EAI_AGAIN`,`UND_ERR_SOCKET`,`UND_ERR_CONNECT_TIMEOUT`]),an=new Set([`APIConnectionError`,`APIConnectionTimeoutError`]),on=[/\bmodel:\s*\S/i,/\bmodels?\b[^.\n]{0,80}\b(?:not found|does not exist|doesn't exist|is not available|not available|unavailable|unrecognized|not recognized|unknown)\b/i,/\b(?:no such model|unknown model|invalid model|unrecognized model|model not found)\b/i];function sn(e){return on.some(t=>t.test(e))}const cn=`[^\\s,;)"]+`;function ln(e){return e.replace(RegExp(`\\bauthorization(")?\\s*[:=]\\s*(")?(?:(?:bearer|basic)\\s+)?${cn}`,`gi`),`Authorization$1: $2[REDACTED]`).replace(RegExp(`\\bbearer\\s+${cn}`,`gi`),`Bearer [REDACTED]`).replace(RegExp(`\\b(api[-_]?key)(")?\\s*[:=]\\s*(")?${cn}`,`gi`),`$1$2: $3[REDACTED]`).replace(RegExp(`\\bkey=${cn}`,`gi`),`key=[REDACTED]`).replace(/\bsk-[A-Za-z0-9_-]{8,}/gi,`[REDACTED]`).replace(/\bAIza[0-9A-Za-z_-]{35}\b/g,`[REDACTED]`)}function z(e){return typeof e==`object`&&e?e:void 0}function un(e,t){let n=e?.[t];return typeof n==`string`&&n.length>0?n:void 0}function dn(e){let t=z(e);if(t===void 0)return{};let n=typeof t.status==`number`?t.status:void 0,r=z(t.error),i=z(r?.error),a=un(r,`type`),o=un(t,`type`)??un(i,`type`)??(a===`error`?void 0:a)??(n!==void 0&&!(e instanceof D)?un(t,`code`):void 0);return{...n!==void 0&&{status:n},...o!==void 0&&{type:o}}}function fn(e){let t=z(e)?.constructor;if(typeof t!=`function`)return;let n=t.name;return typeof n==`string`&&n.length>0?n:void 0}function pn(e){return Ht(e)||fn(e)===`APIUserAbortError`}function mn(e){let t=z(e)?.headers,n=t instanceof Headers?t.get(`retry-after`):z(t)?.[`retry-after`]??z(t)?.[`Retry-After`];if(n==null||n.trim().length===0)return;let r=Number(n);if(Number.isFinite(r))return Math.max(0,r);let i=Date.parse(n);return Number.isNaN(i)?void 0:Math.max(0,Math.round((i-Date.now())/1e3))}function hn(e){if(e.status!==void 0||e.type!==void 0)return{...e.status!==void 0&&{status:e.status},...e.type!==void 0&&{type:e.type}}}function gn(e,t,n){if(e instanceof D||pn(e))return e;let r=e instanceof Error?e:Error(typeof e==`string`?e:``),i=dn(e),a=ln(r.message||`request failed`),o=hn(i);if(i.status===429||i.type!==void 0&&$t.has(i.type))return new c(a||`${t} rate limit exceeded.`,mn(e),t,o);if(i.status===401||i.status===403||i.type!==void 0&&tn.has(i.type))return new w(a,t,o);let s=i.status===void 0||i.status===400||i.status===404,l=bn(e)||i.type!==void 0&&nn.has(i.type)||sn(a);return s&&l?new se(void 0,t,void 0,{...o,originalMessage:a}):_n(e)?new g(a,r,o,t):new f(`${n}: ${a}`,t,r,void 0,i)}function _n(e){if(e instanceof g)return!0;let t=z(e);if(t===void 0)return!1;let n=un(t,`code`);if(n!==void 0&&rn.has(n))return!0;let r=fn(e);if(r!==void 0&&an.has(r))return!0;let i=un(t,`name`);return i!==void 0&&an.has(i)?!0:i===`TypeError`&&un(t,`message`)===`fetch failed`}function vn(e){let t=[],n=new Set,r=[e];for(let e=0;e<=8&&r.length>0;e++){let e=[];for(let i of r){if(i==null||n.has(i))continue;n.add(i),t.push(i);let r=z(i);r!==void 0&&e.push(r.originalError,r.cause)}r=e}return t}const B=(e,t)=>({kind:`definitive`,classification:{switchable:e,reason:t}});function yn(e){return e instanceof f?{...e.status!==void 0&&{status:e.status},...e.type!==void 0&&{type:e.type}}:dn(e)}function bn(e){if(e instanceof D)return!1;let t=un(z(e),`code`);return t!==void 0&&nn.has(t)}function xn(e){if(e instanceof c)return B(!1,`rate-limit`);if(e instanceof w)return B(!1,`authentication`);if(e instanceof se)return B(!0,`model-unavailable`);let{status:t,type:n}=yn(e);return t===429||n!==void 0&&$t.has(n)?B(!1,`rate-limit`):t===401||t===403||n!==void 0&&tn.has(n)?B(!1,`authentication`):t===402?B(!1,`billing`):(t===void 0||t===400||t===404)&&(bn(e)||n!==void 0&&nn.has(n))?B(!0,`model-unavailable`):_n(e)?B(!1,`network`):t===529||n!==void 0&&en.has(n)?B(!0,`overloaded`):t===503?B(!0,`service-unavailable`):t===500||t===502||t===504?B(!0,`server-error`):t===404?{kind:`tentative`,classification:{switchable:!0,reason:`model-unavailable`}}:t===400||t===413?{kind:`tentative`,classification:{switchable:!1,reason:`invalid-request`}}:{kind:`none`}}function Sn(e,t){let n=vn(e);if(t?.aborted===!0||n.some(e=>pn(e)))return{switchable:!1,reason:`aborted`};let r;for(let e of n){let t=xn(e);if(t.kind!==`none`){if(r===void 0&&t.kind===`definitive`)return t.classification;if(r===void 0){r=t.classification;continue}if(t.kind===`definitive`)return t.classification.reason===`model-unavailable`?t.classification:r}}return r??{switchable:!1,reason:`unknown`}}function Cn(e,t,n){return setInterval(()=>{(async()=>{try{await n()}catch(n){e.error(`Periodic task failed`,{task:t.name,error:n instanceof Error?n.message:String(n)})}})()},t.intervalMs)}function wn(e){e&&clearInterval(e)}async function V(e,t){try{await e.append(structuredClone(t))}catch(e){throw new F(t,e)}}function Tn(e){return{...e.model!==void 0&&{model:e.model},...e.tools!==void 0&&{tools:e.tools},...e.maxTokens!==void 0&&{maxTokens:e.maxTokens},...e.temperature!==void 0&&{temperature:e.temperature},...e.effort!==void 0&&{effort:e.effort},...e.toolChoice!==void 0&&{toolChoice:e.toolChoice},...e.nativeWebTools!==void 0&&{nativeWebTools:e.nativeWebTools},...e.responseFormat!==void 0&&{responseFormat:e.responseFormat}}}async function En(e,t,n,r){if(!r)return e(t,n);let{journal:i,executionId:a,callId:o}=r;await V(i,{kind:`model-request`,recordId:`${o}:request`,executionId:a,callId:o,...r.route(),messages:t,options:Tn(n),...r.checkpoint&&{checkpoint:r.checkpoint}}),n.signal?.throwIfAborted();let s;try{s=await e(t,n)}catch(e){throw await V(i,{kind:`model-failure`,recordId:`${o}:failure`,executionId:a,callId:o,...r.route(),error:{name:e instanceof Error?e.name:`Error`,message:e instanceof Error?e.message:String(e)}}),e}return await V(i,{kind:`model-response`,recordId:`${o}:response`,executionId:a,callId:o,...r.route(),response:s}),s}function Dn(e,t){if(t)return!0;switch(e.unknownKeys){case`passthrough`:case`strip`:return!0;case`strict`:return!1;default:return}}function On(e){let t=kn(e);return t.typeName===`ZodObject`?t:void 0}function kn(e){let t=e;for(let e=0;e<=64;e+=1){let e=t.typeName===`ZodEffects`?t.schema:t.typeName===`ZodOptional`||t.typeName===`ZodNullable`||t.typeName===`ZodDefault`?t.innerType:void 0;if(!e)return t;t=An(e,`${String(t.typeName)} inner type`)}throw Error(`Zod wrapper chain exceeds 64 levels; refusing to unwrap further (cyclic schema?).`)}function An(e,t){let n=e._def;if(!n)throw Error(`${t} is missing _def; cannot convert to JSON schema.`);return n}function jn(e){if(typeof e==`string`)return`string`;if(typeof e==`number`)return`number`;if(typeof e==`boolean`)return`boolean`;if(e===null)return`null`}function Mn(e){let t=e._def;if(!t)throw Error(`Zod schema is missing _def; cannot determine required fields.`);let n=t;for(let e=0;n.typeName===`ZodEffects`&&e<=64&&n.schema;e+=1)n=An(n.schema,`ZodEffects inner type`);return n.typeName!==`ZodOptional`&&n.typeName!==`ZodNullable`&&n.typeName!==`ZodDefault`}function Nn(e){let t=An(e,`Zod schema`);if(!t.values||!Array.isArray(t.values))throw Error(`ZodEnum schema is missing enum values; cannot extract enum values.`);return t.values}function Pn(e){let t=An(e,`Zod schema`);return!!(t.checks&&t.checks.length>0)}function Fn(e){let t=An(e,`Zod schema`);if(!t.typeName)throw Error(`Zod schema has empty typeName; cannot determine schema type name.`);return t.typeName}function In(e,t={}){let n=An(e,`Zod schema`),r=On(n);if(!r)throw Error(`Zod schema root must be an object; got ${String(n.typeName)}. Wrap the fields in z.object({ … }) before converting.`);return Ln(r,t.allowAdditionalProperties)}function Ln(e,t){let n={},r=[],i=typeof e.shape==`function`?e.shape():e.shape;for(let[e,a]of Object.entries(i??{}))n[e]=Rn(a,t),Mn(a)&&r.push(e);let a=Dn(e,t);return{type:`object`,properties:n,required:r,...a!==void 0&&{additionalProperties:a}}}function Rn(e,t){let n=An(e,`Zod type`),r={};switch(n.description&&(r.description=n.description),n.typeName){case`ZodString`:return{type:`string`,...r};case`ZodNumber`:return{type:`number`,...r};case`ZodBoolean`:return{type:`boolean`,...r};case`ZodArray`:if(!n.type)throw Error(`ZodArray is missing item type; cannot convert to JSON schema.`);return{type:`array`,items:Rn(n.type,t),...r};case`ZodObject`:return{...Ln(n,t),...r};case`ZodEnum`:{let e=n.values;if(!e||!Array.isArray(e))throw Error(`ZodEnum is missing enum values; cannot convert to JSON schema.`);return{type:`string`,enum:e,...r}}case`ZodNativeEnum`:return{...Bn(n.values),...r};case`ZodDate`:return{type:`string`,format:`date-time`,...r};case`ZodLiteral`:return{...zn(n.value),...r};case`ZodUnion`:case`ZodDiscriminatedUnion`:{let e=n.options;if(!e||!Array.isArray(e)||e.length===0)throw Error(`${String(n.typeName)} is missing options; cannot convert to JSON schema.`);return{anyOf:e.map(e=>Rn(e,t)),...r}}case`ZodEffects`:if(!n.schema)throw Error(`ZodEffects is missing schema; cannot convert to JSON schema.`);return{...Rn(n.schema,t),...r};case`ZodNullable`:if(!n.innerType)throw Error(`ZodNullable is missing innerType; cannot convert to JSON schema.`);return{anyOf:[Rn(n.innerType,t),{type:`null`}],...r};case`ZodOptional`:case`ZodDefault`:if(!n.innerType)throw Error(`${String(n.typeName)} is missing innerType; cannot convert to JSON schema.`);return{...Rn(n.innerType,t),...r};case`ZodRecord`:return n.valueType?{type:`object`,additionalProperties:Rn(n.valueType,t),...r}:{type:`object`,additionalProperties:{type:`string`},...r};default:throw Error(Hn(String(n.typeName)))}}function zn(e){let t=jn(e);if(!t)throw Error(`ZodLiteral value ${String(e)} is not a JSON primitive; cannot convert to JSON schema.`);return t===`null`?{type:`null`}:{type:t,enum:[e]}}function Bn(e){if(!e||typeof e!=`object`)throw Error(`ZodNativeEnum is missing enum values; cannot convert to JSON schema.`);let t=Array.isArray(e)?e:Object.values(e),n=t.filter(e=>typeof e==`number`),r=n.length>0?n:t;if(r.length===0)throw Error(`ZodNativeEnum declares no members; cannot convert to JSON schema.`);return{type:n.length>0?`number`:`string`,enum:r}}const Vn={ZodTuple:"a tuple needs positional `items`, and the subset models `items` as ONE schema — use `z.object({...})` for a fixed-shape record, or `z.array(z.union([...]))` if order genuinely does not matter",ZodIntersection:"an intersection needs `allOf` — merge the two object schemas yourself with `.merge()`, which produces a single object node the subset can carry",ZodLazy:"a recursive schema needs `$ref` — flatten the recursion to a fixed depth, or model the nested level as `z.record(...)`",ZodDate:"use `z.string()` (optionally with `.datetime()`), which is what a provider receives"};function Hn(e){return`${e} cannot be carried by the universal JSON-schema subset: ${Vn[e]??`it has no representation in the subset`}. The subset is the one language every provider mapper forwards intact; a construct outside it would be advertised to the model and enforced by nothing.`}function Un(e){return typeof e.safeParse==`function`&&typeof e.parse==`function`}function Wn(e){if(e&&typeof e==`object`&&`issues`in e){let t=e.issues;if(Array.isArray(t))return t.map(e=>{if(e&&typeof e==`object`&&`message`in e){let t=Array.isArray(e.path)?e.path.join(`.`):``,n=String(e.message);return t?`${t}: ${n}`:n}return String(e)})}return[String(e)]}function Gn(e){if(Un(e))return{name:`structured_output`,jsonSchema:In(e),validate:t=>{let n=e.safeParse(t);return n.success?{success:!0,value:n.data}:{success:!1,issues:Wn(n.error)}}};let{jsonSchema:t,name:n}=e;return{name:n??`structured_output`,jsonSchema:t,validate:e=>{let n=Kn(t,e,`$`);return n.length===0?{success:!0,value:e}:{success:!1,issues:n}}}}function Kn(e,t,n){let r=[],i=e.type;if(e.anyOf)return Jn(e.anyOf,t,n);switch(i){case`object`:{if(typeof t!=`object`||!t||Array.isArray(t))return[`${n}: expected object, got ${Yn(t)}`];let i=t,a=e.required??[];for(let e of a)e in i||r.push(`${n}.${e}: required property missing`);let o=e.properties??{};for(let[e,t]of Object.entries(o))e in i&&r.push(...Kn(t,i[e],`${n}.${e}`));let s=e.additionalProperties;if(qn(e))for(let e of Object.keys(i))e in o||r.push(`${n}.${e}: unexpected additional property`);else if(typeof s==`object`)for(let[e,t]of Object.entries(i))e in o||r.push(...Kn(s,t,`${n}.${e}`));return r}case`array`:{if(!Array.isArray(t))return[`${n}: expected array, got ${Yn(t)}`];let i=e.items;return i&&t.forEach((e,t)=>{r.push(...Kn(i,e,`${n}[${t}]`))}),r}case`string`:return typeof t==`string`?(e.enum&&!e.enum.some(e=>e===t)&&r.push(`${n}: value ${JSON.stringify(t)} is not one of the allowed enum values`),e.pattern&&!new RegExp(e.pattern).test(t)&&r.push(`${n}: value does not match pattern ${e.pattern}`),r):[`${n}: expected string, got ${Yn(t)}`];case`number`:case`integer`:return typeof t!=`number`||Number.isNaN(t)?[`${n}: expected number, got ${Yn(t)}`]:(i===`integer`&&!Number.isInteger(t)&&r.push(`${n}: expected integer, got non-integer number`),e.minimum!==void 0&&t<e.minimum&&r.push(`${n}: value ${t} is below minimum ${e.minimum}`),e.maximum!==void 0&&t>e.maximum&&r.push(`${n}: value ${t} is above maximum ${e.maximum}`),e.enum&&!e.enum.some(e=>e===t)&&r.push(`${n}: value ${t} is not one of the allowed enum values`),r);case`boolean`:return typeof t==`boolean`?r:[`${n}: expected boolean, got ${Yn(t)}`];case`null`:return t===null?r:[`${n}: expected null, got ${Yn(t)}`];default:return i===void 0?[`${n}: schema node declares neither a type nor anyOf`]:[`${n}: unsupported schema type ${String(i)}`]}}function qn(e){let t=e.additionalProperties;return t===!1||t===void 0&&e.properties!==void 0}function Jn(e,t,n){if(e.length===0)return[`${n}: anyOf declares no members`];let r=e.map((e,r)=>Kn(e,t,`${n}|anyOf[${r}]`));return r.some(e=>e.length===0)?[]:[`${n}: value matches none of the ${e.length} allowed shapes`,...r.flat()]}function Yn(e){return e===null?`null`:Array.isArray(e)?`array`:typeof e}function Xn(e){let t=e.trim(),n=/^```(?:json)?[^\S\n]*\n([\s\S]*?)\n?```$/.exec(t),r=n?n[1]:t;try{return{success:!0,value:JSON.parse(r)}}catch(e){return{success:!1,issue:`response is not valid JSON: ${e instanceof Error?e.message:String(e)}`}}}function Zn(e,t){return Oe(e,t,`json_schema`)===!0?`response_schema`:Oe(e,t,`json_object`)===!0?`json_object`:`none`}function Qn(e){let{table:t,model:n,endpointIsVendorDefault:r}=e;if(!t)return r===!1?{mechanism:`response_schema`,provenance:`unverified-endpoint`,reason:`a custom baseURL is configured and the provider declares no capability table, so nothing here can claim the endpoint enforces the schema`}:{mechanism:`response_schema`,provenance:`undeclared`,reason:`the provider declares no capability table, so the request is sent as asked — silence is not a denial`};let i=Zn(t,n),a=t.deviations?.[n]!==void 0;return r===!1?{mechanism:i,provenance:`unverified-endpoint`,reason:`a custom baseURL is configured, so the vendor capability table describes the protocol but not necessarily the endpoint serving it`}:{mechanism:i,provenance:a?`catalog`:`vendor-default`,...i===`none`&&{reason:`${n} declares no schema transport, so the schema travels in the prompt and is enforced by validation`},...i===`json_object`&&{reason:`${n} guarantees JSON but not its shape, so the schema travels in the prompt and is enforced by validation`}}}const $n=e=>process.env[e];function er(e){return t=>e[t]}function tr(e,t){for(let n of e??[]){let e=t(n);if(typeof e==`string`&&e.trim().length>0)return e.trim()}}function nr(e,t={},n=$n){let r=e.credentialRequirement,i=t.baseUrl??tr(r?.baseUrlEnvVars,n)??e.defaults?.baseUrl;if(r===void 0)return{ok:!0,config:{...i===void 0?{}:{baseUrl:i},...t.imageCapableModels===void 0?{}:{imageCapableModels:t.imageCapableModels}}};let a=tr(r.credentialEnvVars,n),o=[];return a===void 0&&o.push(...r.credentialEnvVars),r.requiresBaseUrl===!0&&i===void 0&&o.push(...r.baseUrlEnvVars??[]),o.length>0?{ok:!1,missing:o}:{ok:!0,config:{...a===void 0?{}:{credential:a},...i===void 0?{}:{baseUrl:i},...t.imageCapableModels===void 0?{}:{imageCapableModels:t.imageCapableModels}}}}function rr(e,t={},n=$n){if(e.createImageProvider===void 0)return;let r=nr(e,t,n);if(r.ok)try{let t=e.createImageProvider(r.config);return Ae(t)?t:void 0}catch{return}}function ir(e,t={},n=$n){if(e.createVideoProvider===void 0)return;let r=nr(e,t,n);if(r.ok)try{let t=e.createVideoProvider(r.config);return je(t)?t:void 0}catch{return}}const ar=`$ENV:`;function or(e){return e.startsWith(ar)}function sr(e){return`${ar}${e}`}function cr(e,t=$n){if(!or(e))return e;let n=e.slice(5).trim();if(n.length!==0)return t(n)}function lr(e,t=$n){return e===void 0||e.length===0?!1:cr(e,t)!==void 0}function ur(e,t,n=$n){let r=we(t,e.name)?.defaults??{},i=e.model??r.model;if(!i)throw Error(`Provider ${e.name} requires model`);if(e.apiKeyRef!==void 0&&e.apiKey!==void 0)throw Error(`Provider ${e.name} has conflicting credential origins`);if(e.apiKeyRef!==void 0&&(!e.apiKeyRef.service?.trim()||!e.apiKeyRef.account?.trim()))throw Error(`Provider ${e.name} has an invalid host credential reference`);let a=e.apiKeyRef===void 0?e.apiKey??r.apiKey:void 0,o=a!==void 0&&or(a)?a.slice(5).trim():void 0;if(o===``)throw Error(`Provider ${e.name} has an invalid API key environment reference; use $ENV:VARIABLE_NAME`);let s=e.options??r.options;return{name:e.name,model:i,apiKey:a===void 0?void 0:cr(a,n),...o?{apiKeyEnv:o}:{},...e.apiKeyRef===void 0?{}:{apiKeyRef:e.apiKeyRef},baseURL:e.baseURL??r.baseURL,timeout:e.timeout,...s!==void 0&&{options:s}}}function dr(e,t){if(e.apiKeyRef!==void 0&&!e.apiKey)throw Error(`Provider ${e.name} requires host credential resolution before construction`);let n=we(t,e.name);if(n===void 0)throw Error(`Unknown provider: ${e.name}. Currently supported: ${Te(t)}`);let r=Ee(n);if(r!==void 0&&!fr(e,r))throw Error(`Provider ${e.name} requires ${mr(r)}`);return n.createProvider(e)}function fr(e,t){return t.anyOf.some(t=>pr(e,t))}function pr(e,t){let n=e[t];return n!==void 0&&n.length>0}function mr(e){return e.anyOf.map(e=>e===`apiKey`?`apiKey (API key)`:e).join(` or `)}function H(){let e=globalThis.crypto;if(typeof e?.randomUUID==`function`)return e.randomUUID();if(typeof e?.getRandomValues==`function`){let t=e.getRandomValues(new Uint8Array(16));t[6]=(t[6]??0)&15|64,t[8]=(t[8]??0)&63|128;let n=Array.from(t,e=>e.toString(16).padStart(2,`0`)).join(``);return`${n.slice(0,8)}-${n.slice(8,12)}-${n.slice(12,16)}-${n.slice(16,20)}-${n.slice(20)}`}throw Error(`No cryptographic randomness is available on this platform (globalThis.crypto is missing both randomUUID and getRandomValues), so a unique identifier cannot be generated. This is not something to substitute Math.random for.`)}function hr(e,t){let n={id:H(),role:`user`,content:e,state:`complete`,timestamp:new Date};return t?.name&&(n.name=t.name),t?.metadata&&(n.metadata=t.metadata),t?.parts&&(n.parts=t.parts),n}function gr(e,t){let n={id:H(),role:`assistant`,content:e,state:t?.state??`complete`,timestamp:new Date};return t?.toolCalls&&(n.toolCalls=t.toolCalls),t?.metadata&&(n.metadata=t.metadata),t?.parts&&(n.parts=t.parts),n}function _r(e,t){let n={id:H(),role:`system`,content:e,state:`complete`,timestamp:new Date};return t?.name&&(n.name=t.name),t?.metadata&&(n.metadata=t.metadata),t?.parts&&(n.parts=t.parts),n}function vr(e,t){let n={id:H(),role:`tool`,content:e,toolCallId:t.toolCallId,state:`complete`,timestamp:new Date};return t.name&&(n.name=t.name),t.metadata&&(n.metadata=t.metadata),t.parts&&(n.parts=t.parts),n}var yr=class{maxMessages;entries=[];constructor(e){this.maxMessages=e?.maxMessages||0}addMessage(e){this.entries.push(it(e)),this.applyMessageLimit()}addEntry(e){this.entries.push(e)}getHistory(){return[...this.entries]}addUserMessage(e,t,n){this.addMessage(hr(e,{...t&&{metadata:t},...n&&{parts:n}}))}addAssistantMessage(e,t,n,r){this.addMessage(gr(e,{...t&&{toolCalls:t},...n&&{metadata:n},...r&&{parts:r}}))}addSystemMessage(e,t,n){this.addMessage(_r(e,{...t&&{metadata:t},...n&&{parts:n}}))}setSystemPrompt(e,t,n){let r=e=>nt(e)&&ct(rt(e)),i=this.entries.filter(e=>!r(e)),a=it(_r(e,{...t&&{metadata:t},...n&&{parts:n}}));i.unshift(a),this.entries=i}addToolMessageWithId(e,t,n,r,i){this.addMessage(vr(e,{toolCallId:t,name:n,...r&&{metadata:r},...i&&{parts:i}}))}getMessages(){return this.entries.filter(nt).map(rt)}getMessagesByRole(e){return this.getMessages().filter(t=>t.role===e)}getRecentMessages(e){return this.getMessages().slice(-e)}getMessageCount(){return this.entries.filter(nt).length}clear(){this.entries=[]}applyMessageLimit(){if(this.maxMessages<=0)return;let e=this.entries.filter(nt);if(e.length<=this.maxMessages)return;let t=e.map(rt),n=t.filter(ct),r=t.filter(e=>!ct(e)),i=Math.max(0,this.maxMessages-n.length),a=[...n,...r.slice(-i)],o=new Set(a.map(e=>e.id));this.entries=this.entries.filter(e=>!nt(e)||o.has(e.id))}},br=class{history;pendingAssistant=null;constructor(e=0){this.history=new yr({maxMessages:e})}addMessage(e){this.history.addMessage(e)}addUserMessage(e,t,n){this.history.addUserMessage(e,t,n)}addAssistantMessage(e,t,n,r){this.history.addAssistantMessage(e,t,n,r)}addSystemMessage(e,t,n){this.history.addSystemMessage(e,t,n)}setSystemPrompt(e,t,n){this.history.setSystemPrompt(e,t,n)}addToolMessage(e,t,n,r,i){this.history.addToolMessageWithId(e,t,n||`unknown`,r,i)}addToolMessageWithId(e,t,n,r,i){this.history.addToolMessageWithId(e,t,n,r,i)}addEntry(e){this.history.addEntry(e)}getHistory(){return this.history.getHistory()}getMessages(){return this.history.getMessages()}getMessagesByRole(e){return this.history.getMessagesByRole(e)}getRecentMessages(e){return this.history.getRecentMessages(e)}getMessageCount(){return this.history.getMessageCount()}beginAssistant(){this.pendingAssistant||={id:H(),content:``,toolCalls:[]}}appendStreaming(e){this.pendingAssistant||={id:H(),content:``,toolCalls:[]},this.pendingAssistant.content+=e}appendToolCall(e){this.pendingAssistant||={id:H(),content:``,toolCalls:[]},this.pendingAssistant.toolCalls.some(t=>t.id===e.id)||this.pendingAssistant.toolCalls.push(e)}commitAssistant(e,t){if(!this.pendingAssistant)return;let n=this.pendingAssistant,r=n.toolCalls.length>0,i=n.content,a={id:n.id,role:`assistant`,content:i,state:e,timestamp:new Date,...r&&{toolCalls:n.toolCalls},...t&&{metadata:t}};this.history.addMessage(a),this.pendingAssistant=null}discardPending(){this.pendingAssistant=null}hasPendingAssistant(){return this.pendingAssistant!==null}getPendingContent(){return this.pendingAssistant?.content??``}getMessagesForAPI(){return this.history.getMessages().map(e=>{let t={role:e.role,content:e.content};return st(e)&&e.state===`interrupted`&&(t.content=(t.content||``)+`
2
2
 
3
3
  [This response was interrupted by the user]`),st(e)&&e.toolCalls&&(t.tool_calls=e.toolCalls),lt(e)&&(t.tool_call_id=e.toolCallId),t})}clear(){this.history.clear()}},xr=class{conversations=new Map;logger;maxMessagesPerConversation;maxConversations;constructor(e={}){this.maxMessagesPerConversation=e.maxMessagesPerConversation||0,this.maxConversations=e.maxConversations||50,this.logger=O(`ConversationHistory`)}getConversationStore(e){return this.conversations.has(e)||(this.conversations.size>=this.maxConversations&&this.cleanupOldConversations(),this.conversations.set(e,new br(this.maxMessagesPerConversation))),this.conversations.get(e)}hasConversation(e){return this.conversations.has(e)}removeConversation(e){let t=this.conversations.delete(e);return t&&this.logger.debug(`Removed conversation`,{conversationId:e}),t}clearAll(){let e=this.conversations.size;this.conversations.clear(),this.logger.debug(`Cleared all conversations`,{removedCount:e})}getStats(){let e=Array.from(this.conversations.keys()),t=Array.from(this.conversations.values()).reduce((e,t)=>e+t.getMessageCount(),0);return{totalConversations:this.conversations.size,conversationIds:e,totalMessages:t}}cleanupOldConversations(){if(this.conversations.size===0)return;let e=this.conversations.keys().next().value;e&&this.conversations.delete(e)}};function Sr(){let e,t=0;return{observe(n){t+=1,t===1&&(e=n)},terminal(n){if(t>1)throw Error(`Provider "${n}" emitted ${t} model-effort outcomes`);return e}}}function Cr(e,t,n){if(n!==void 0&&t?.onModelEffortOutcome!==void 0)try{t.onModelEffortOutcome(n)}catch(t){e.warn(`Model-effort outcome observer failed`,{error:t instanceof Error?t.message:String(t)})}}var wr=class extends zt{name=`local`;version=`1.0.0`;providers=new Map;config;constructor(e={}){super(),this.config={timeout:3e4,maxRetries:3,retryDelay:1e3,enableLogging:!1,...e}}registerProvider(e,t){this.providers.set(e,t)}unregisterProvider(e){this.providers.delete(e)}getProvider(e){return this.providers.get(e)}async executeChat(e){this.validateRequest(e);let t=this.requireChatProvider(e);this.config.enableLogging&&this.logDebug(`Executing chat with provider: ${e.provider}, model: ${e.model}`);try{let n=Sr(),r=await this.withRetry(async()=>(n=Sr(),await this.withTimeout(t.chat(e.messages,{...e.options,model:e.model,tools:e.tools,onModelEffortOutcome:e=>{n.observe(e)}}),this.config.timeout)),this.config.maxRetries,this.config.retryDelay);if(r.role!==`assistant`)throw Error(`Expected assistant message, got ${r.role}`);let i=n.terminal(e.provider);return this.validateResponse(r),Cr(this.logger,e.options,i),{message:r,...i!==void 0&&{modelEffortOutcome:i}}}catch(t){let n=t instanceof Error?t:Error(String(t));throw this.logError(`Chat execution failed`,n,{provider:e.provider,model:e.model}),n}}async*executeChatStream(e){this.validateRequest(e);let t=this.providers.get(e.provider);if(!t)throw Error(`Provider "${e.provider}" not registered with LocalExecutor`);if(!t.chatStream)throw Error(`Provider "${e.provider}" does not implement chatStream method`);this.config.enableLogging&&this.logDebug(`Executing streaming chat with provider: ${e.provider}, model: ${e.model}`);try{let n=Sr(),r=t.chatStream(e.messages,{...e.options,model:e.model,tools:e.tools,onModelEffortOutcome:e=>{n.observe(e)}});for await(let e of r)this.validateResponse(e),yield{kind:`message`,message:e};let i=n.terminal(e.provider);Cr(this.logger,e.options,i),yield{kind:`terminal`,...i!==void 0&&{modelEffortOutcome:i}}}catch(t){let n=t instanceof Error?t:Error(String(t));throw this.logError(`Streaming chat execution failed`,n,{provider:e.provider,model:e.model}),n}}supportsTools(){for(let e of this.providers.values())if(e.supportsTools&&e.supportsTools())return!0;return!1}validateConfig(){try{if(this.config.timeout<=0||this.config.maxRetries<0||this.config.retryDelay<0)return!1;for(let e of this.providers.values())if(e.validateConfig&&!e.validateConfig())return!1;return!0}catch{return!1}}async dispose(){this.config.enableLogging&&this.logDebug(`Disposing ${this.providers.size} providers`);let e=[];for(let t of this.providers.values())t.dispose&&e.push(t.dispose());await Promise.all(e),this.providers.clear()}requireChatProvider(e){let t=this.providers.get(e.provider);if(!t)throw Error(`Provider "${e.provider}" not registered with LocalExecutor`);if(!t.chat)throw Error(`Provider "${e.provider}" does not implement chat method`);return t}};const Tr=/^[A-Za-z0-9_@%+:,./][A-Za-z0-9_@%+=:,./-]*$/;function Er(e){return Tr.test(e)?e:void 0}var Dr=class{totalEmitted=0;totalErrors=0;incrementEmitted(){this.totalEmitted+=1}incrementErrors(){this.totalErrors+=1}getSnapshot(){return{totalEmitted:this.totalEmitted,totalErrors:this.totalErrors}}};function Or(e,t){if(e.maxListeners!==void 0&&e.maxListeners<0)throw new oe(`Invalid maxListeners option: ${e.maxListeners}. Must be a non-negative number.`,t,{maxListeners:e.maxListeners});if(e.buffer!==void 0&&e.buffer.maxSize!==void 0&&e.buffer.maxSize<0)throw new oe(`Invalid buffer.maxSize option: ${e.buffer.maxSize}. Must be a non-negative number.`,t,{bufferMaxSize:e.buffer.maxSize});if(e.buffer!==void 0&&e.buffer.flushInterval!==void 0&&e.buffer.flushInterval<0)throw new oe(`Invalid buffer.flushInterval option: ${e.buffer.flushInterval}. Must be a non-negative number.`,t,{bufferFlushInterval:e.buffer.flushInterval})}async function kr(e,t,n,r,i){try{await e.listener(t)}catch(a){if(n.incrementErrors(),!r)throw a instanceof Error?a:Error(String(a));i.error(`Event handler error`,{eventType:t.type,handlerId:e.id,error:a instanceof Error?a.message:String(a)})}}async function Ar(e,t,n,r,i){let a=t.get(e.type);if(!a||a.length===0)return;let o=a.filter(t=>!t.filter||t.filter(e));if(o.length!==0){for(let t of o.filter(e=>e.once))r(e.type,t.id);if(n){await Promise.all(o.map(t=>i(t,e)));return}for(let t of o)await i(t,e)}}function jr(e){let t={},n=0;for(let[r,i]of e)t[r]=i.length,n+=i.length;return{listenerCounts:t,totalListeners:n}}function Mr(e,t,n,r){let{listenerCounts:i,totalListeners:a}=jr(t),o=r.getSnapshot();return{enabled:e.enabled,calls:e.calls,errors:e.errors,eventTypes:Array.from(t.keys()),listenerCounts:i,totalListeners:a,bufferedEvents:n,totalEmitted:o.totalEmitted,totalErrors:o.totalErrors}}function Nr(e,t,n,r,i,a,o){e.has(t)||e.set(t,[]);let s=e.get(t);if(s.length>=a)throw new oe(`Maximum listeners (${a}) exceeded for event type: ${t}`,o,{eventType:t,currentListeners:s.length});s.push({id:n,listener:r,once:i?.once??!1,...i?.filter&&{filter:i.filter}})}function Pr(e,t,n){let r=e.get(t);if(!r)return!1;let i=typeof n==`string`?r.findIndex(e=>e.id===n):r.findIndex(e=>e.listener===n);return i===-1?!1:(r.splice(i,1),!0)}function Fr(e,t,n){let r=t.result!==null&&t.result!==void 0;return{executionId:e.executionId,sessionId:e.sessionId,userId:e.userId,data:{toolName:t.name||``,toolId:t.id||``,toolResult:r?String(t.result):void 0,duration:n,success:r}}}var Ir=class extends Rt{name=`EventEmitterPlugin`;version=`1.0.0`;pluginOptions;logger;handlers=new Map;eventBuffer=[];nextHandlerId=1;bufferTimer;metrics;constructor(e={}){super(),this.logger=O(`EventEmitterPlugin`),this.metrics=e.metrics??new Dr,Or(e,this.name),this.pluginOptions={enabled:e.enabled??!0,events:e.events??[P.AGENT_EXECUTION_START,P.AGENT_EXECUTION_COMPLETE,P.AGENT_EXECUTION_ERROR,P.TOOL_BEFORE_EXECUTE,P.TOOL_AFTER_EXECUTE,P.TOOL_SUCCESS,P.TOOL_ERROR],maxListeners:e.maxListeners??100,async:e.async??!0,catchErrors:e.catchErrors??!0,filters:e.filters??{},buffer:e.buffer??{enabled:!1,maxSize:1e3,flushInterval:5e3},category:e.category??`event_processing`,priority:e.priority??Ot.HIGH,moduleEvents:e.moduleEvents??[],subscribeToAllModuleEvents:e.subscribeToAllModuleEvents??!1},this.pluginOptions.buffer.enabled&&(this.bufferTimer=setInterval(()=>{this.flushBuffer().catch(e=>{this.logger.error(`Buffered flush failed`,{error:e instanceof Error?e.message:String(e)})})},this.pluginOptions.buffer.flushInterval))}async beforeExecution(e){await this.emit(P.AGENT_EXECUTION_START,{executionId:e.executionId,sessionId:e.sessionId,userId:e.userId,data:{messageCount:e.messages?.length||0,...e.config&&{config:e.config}}})}async afterExecution(e,t){await this.emit(P.AGENT_EXECUTION_COMPLETE,{executionId:e.executionId,sessionId:e.sessionId,userId:e.userId,data:{duration:t?.duration,tokensUsed:t?.tokensUsed,toolsExecuted:t?.toolsExecuted}})}async beforeConversation(e){await this.emit(P.CONVERSATION_START,{executionId:e.executionId,sessionId:e.sessionId,userId:e.userId,data:{messages:e.messages?.map(e=>({role:e.role,content:e.content||``,timestamp:e.timestamp?e.timestamp.toISOString():new Date().toISOString()})),config:e.config}})}async afterConversation(e,t){await this.emit(P.CONVERSATION_COMPLETE,{executionId:e.executionId,sessionId:e.sessionId,userId:e.userId,data:{response:t.content||t.response,tokensUsed:t.usage?.totalTokens||t.tokensUsed,toolCalls:t.toolCalls?.map(e=>({id:e.id||``,name:e.name||``,arguments:JSON.stringify(e.arguments||{}),result:String(e.result||``)}))}})}async beforeToolExecution(e,t){t&&await this.emit(P.TOOL_BEFORE_EXECUTE,{executionId:e.executionId,sessionId:e.sessionId,userId:e.userId,data:{toolName:t.toolName,toolId:t.executionId,arguments:JSON.stringify(t.parameters??{})}})}async afterToolExecution(e,t){if(!(!t.toolCalls||t.toolCalls.length===0))for(let n of t.toolCalls){let r=n.result===null?P.TOOL_ERROR:P.TOOL_SUCCESS,i=Fr(e,n,t.duration);await this.emit(r,i),await this.emit(P.TOOL_AFTER_EXECUTE,{...i,data:{...i.data,toolResult:String(n.result||``)}})}}async onError(e,t){await this.emit(P.AGENT_EXECUTION_ERROR,{executionId:t?.executionId,sessionId:t?.sessionId,userId:t?.userId,error:e instanceof Error?e:Error(String(e)),data:{action:t?.action,tool:t?.tool,attempt:t?.attempt}})}on(e,t,n){let r=`handler_${this.nextHandlerId++}`;return Nr(this.handlers,e,r,t,n,this.pluginOptions.maxListeners,this.name),r}once(e,t,n){return this.on(e,t,{once:!0,...n&&{filter:n}})}off(e,t){return Pr(this.handlers,e,t)}async emit(e,t={}){if(!this.pluginOptions.events.includes(e))return;let n={type:e,timestamp:new Date,...t},r=this.pluginOptions.filters[e];if(!(r&&!r(n))){if(this.metrics.incrementEmitted(),this.pluginOptions.buffer.enabled){this.eventBuffer.push(n),this.eventBuffer.length>=this.pluginOptions.buffer.maxSize&&await this.flushBuffer();return}await this.processEvent(n)}}async processEvent(e){await Ar(e,this.handlers,this.pluginOptions.async,(e,t)=>this.off(e,t),(e,t)=>kr(e,t,this.metrics,this.pluginOptions.catchErrors,this.logger))}async flushBuffer(){if(this.eventBuffer.length===0)return;let e=[...this.eventBuffer];this.eventBuffer=[];for(let t of e)await this.processEvent(t)}getStats(){return Mr(super.getStats(),this.handlers,this.eventBuffer.length,this.metrics)}clearAllListeners(){this.handlers.clear()}async dispose(){this.bufferTimer&&clearInterval(this.bufferTimer),await this.flushBuffer(),this.clearAllListeners(),await super.dispose()}};const Lr=[`string`,`number`,`integer`,`boolean`,`array`,`object`,`null`];var Rr=class{tools=new Map;register(e){if(!e.schema?.name)throw new d(`Tool must have a valid schema with name`);let t=e.schema.name;this.validateToolSchema(e.schema),this.tools.has(t)&&k.warn(`Tool "${t}" is already registered, overriding`,{toolName:t,existingTool:this.tools.get(t)?.constructor.name}),this.tools.set(t,e),k.debug(`Tool "${t}" registered successfully`,{toolName:t,toolType:e.constructor.name,parameters:Object.keys(e.schema.parameters?.properties||{})})}unregister(e){if(!this.tools.has(e)){k.warn(`Attempted to unregister non-existent tool "${e}"`);return}this.tools.delete(e),k.debug(`Tool "${e}" unregistered successfully`)}get(e){return this.tools.get(e)}getAll(){return Array.from(this.tools.values())}getSchemas(){let e=this.getAll();return k.debug(`[TOOL-FLOW] ToolRegistry.getSchemas() - Tools before schema extraction`,{count:e.length,tools:e.map(e=>({name:e.schema?.name??`unnamed`,hasSchema:!!e.schema,schemaType:typeof e.schema,toolType:e.constructor?.name||`unknown`}))}),this.getAll().map(e=>e.schema)}has(e){return this.tools.has(e)}clear(){let e=this.tools.size;this.tools.clear(),k.debug(`Cleared ${e} tools from registry`)}getToolNames(){return Array.from(this.tools.keys())}getToolsByPattern(e){let t=typeof e==`string`?new RegExp(e):e;return this.getAll().filter(e=>t.test(e.schema.name))}size(){return this.tools.size}validateToolSchema(e){if(!e.name||typeof e.name!=`string`)throw new d(`Tool schema must have a valid name`);if(!e.description||typeof e.description!=`string`)throw new d(`Tool schema must have a description`);if(!e.parameters||typeof e.parameters!=`object`||e.parameters===null||Array.isArray(e.parameters))throw new d(`Tool schema must have parameters object`);if(e.parameters.type!==`object`)throw new d(`Tool parameters type must be "object"`);if(e.parameters.properties)for(let[t,n]of Object.entries(e.parameters.properties))zr(t,n);if(e.parameters.required){let t=e.parameters.properties||{};for(let n of e.parameters.required)if(!t[n])throw new d(`Required parameter "${n}" is not defined in properties`)}}};function zr(e,t){if(t?.anyOf){if(t.anyOf.length===0)throw new d(`Parameter "${e}" declares an empty anyOf`);t.anyOf.forEach((t,n)=>zr(`${e}|anyOf[${n}]`,t));return}if(!t?.type)throw new d(`Parameter "${e}" must declare a type or anyOf`);if(!Lr.includes(t.type))throw new d(`Parameter "${e}" has invalid type "${t.type}"`);if(t.properties)for(let[n,r]of Object.entries(t.properties))zr(`${e}.${n}`,r);t.items&&zr(`${e}[]`,t.items)}function Br(e,t,n){let r=Kn(n,t,`$`);if(r.length>0)throw new l(`output does not match the declared outputSchema: ${r.join(`; `)}`,e,void 0,{outputSchemaIssues:r})}function Vr(e,t,n){let r=Hr(e,t,n);return r?[r]:Kn(n,t,`Parameter "${e}"`)}function Hr(e,t,n){if(n.anyOf)return;let r=n.type;switch(r){case`string`:return typeof t==`string`?void 0:`Parameter "${e}" must be a string, got ${Ur(t)}`;case`number`:case`integer`:return typeof t==`number`&&!isNaN(t)?void 0:`Parameter "${e}" must be a number, got ${Ur(t)}`;case`boolean`:return typeof t==`boolean`?void 0:`Parameter "${e}" must be a boolean, got ${Ur(t)}`;case`array`:return Array.isArray(t)?void 0:`Parameter "${e}" must be an array, got ${Ur(t)}`;case`object`:return typeof t==`object`&&t&&!Array.isArray(t)?void 0:`Parameter "${e}" must be an object, got ${Ur(t)}`;case`null`:return;case void 0:return`Parameter "${e}" declares neither a type nor anyOf`;default:return`Parameter "${e}" has unsupported schema type "${String(r)}"`}}function Ur(e){return e===null?`null`:Array.isArray(e)?`array`:typeof e}function Wr(e,t,n,r){let i=[];for(let n of t)n in e||i.push(`Missing required parameter: ${n}`);for(let[t,a]of Object.entries(e)){let e=n[t];if(!e){if(r===!0)continue;if(r&&typeof r==`object`){i.push(...Vr(t,a,r));continue}i.push(`Unknown parameter: ${t}`);continue}i.push(...Vr(t,a,e))}return i}function Gr(e,t,n,r){let i=Wr(e,t,n,r);return{isValid:i.length===0,errors:i}}var Kr=class{listeners=new Set;subscribe(e){this.listeners.add(e)}unsubscribe(e){this.listeners.delete(e)}notifyListeners(e,t,n){for(let r of this.listeners)r(e,t,n)}},qr=class extends Kr{emit(e,t,n){}};const Jr=new qr;function Yr(e){return e===Jr||e instanceof qr}function Xr(e,t){if(!e||e.trim().length===0)throw Error(`[EVENTS] ownerType is required to compose event names.`);if(e.includes(`.`))throw Error(`[EVENTS] ownerType must not contain '.': "${e}"`);if(!t||t.trim().length===0)throw Error(`[EVENTS] local event name is required.`);if(t.includes(`.`))throw Error(`[EVENTS] Local event name must not contain '.': "${t}"`);return`${e}.${t}`}function Zr(){return`span_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,10)}`}var Qr=class extends Kr{base;binding;constructor(e,t){super(),this.base=e,this.binding=t}emit(e,t,n){if(e.includes(`.`))throw Error(`[EVENTS] Local event name must not contain '.': "${e}"`);let r={...n,ownerType:this.binding.ownerType,ownerId:this.binding.ownerId,ownerPath:this.binding.ownerPath,depth:this.binding.ownerPath.length,spanId:n?.spanId??Zr()},i=Xr(this.binding.ownerType,e);this.base.emit(i,t,r)}subscribe(e){this.base.subscribe(e)}unsubscribe(e){this.base.unsubscribe(e)}};function U(e,t){return new Qr(e,t)}function $r(e,t){return U(e,t)}var ei=class extends Kr{emit(e,t,n){this.notifyListeners(e,t,n)}};const ti={COMPLETED:`span_completed`},ni={COMPLETED:`provider_call_completed`},ri={SWITCHED:`provider_fallback`};function ii(e){let{fromProvider:t,fromModel:n,toProvider:r,toModel:i,reason:a}=e;if(typeof t==`string`&&typeof n==`string`&&typeof r==`string`&&typeof i==`string`&&typeof a==`string`)return{from:{provider:t,model:n},to:{provider:r,model:i},reason:a}}const ai={COMPLETED:`tool_body_completed`},oi={COMPLETED:`tool_queue_completed`},si={DECIDED:`tool_permission_decided`},ci=`span`;var li=class e{resultExecutor;schema;fn;eventService;constructor(e,t,n){this.resultExecutor=n,this.schema=e,this.fn=t,this.validateConstructorInputs()}static fromResult(t,n){return new e(t,async(e,r)=>{let i=await n(e,r);if(!i.success)throw new l(i.error??`Tool execution failed`,t.name);if(i.data===void 0)throw new l(`Tool execution succeeded but returned no data`,t.name);return i.data},n)}getName(){return this.schema.name}setEventService(e){this.eventService=e}async execute(e,t){let n=this.schema.name;if(!this.validate(e))throw new d(`Invalid parameters for tool "${n}": ${Wr(e,this.schema.parameters.required||[],this.schema.parameters.properties||{},this.schema.parameters.additionalProperties).join(`, `)}`);let r=Date.now(),i,a;try{this.resultExecutor?(a=await this.resultExecutor(e,t),i=a.data):i=await this.fn(e,t)}catch(r){throw R(r)||r instanceof l||r instanceof d?r:new l(`Function tool execution failed: ${r instanceof Error?r.message:String(r)}`,n,r instanceof Error?r:Error(String(r)),{parameterCount:Object.keys(e||{}).length,hasContext:!!t})}let o=Date.now()-r;this.schema.outputSchema&&(!a||a.success)&&Br(n,i,this.schema.outputSchema);let s=t?.instanceEventService??this.eventService;if(s){let e={timestamp:new Date,spanId:Zr(),durationMs:o,op:n};s.emit(ti.COMPLETED,e)}return a||{success:!0,data:i,metadata:{executionTime:o,toolName:n,parameters:e}}}validate(e){return Wr(e,this.schema.parameters.required||[],this.schema.parameters.properties||{},this.schema.parameters.additionalProperties).length===0}validateParameters(e){return Gr(e,this.schema.parameters.required||[],this.schema.parameters.properties||{},this.schema.parameters.additionalProperties)}getDescription(){return this.schema.description}validateConstructorInputs(){if(!this.schema)throw new d(`Tool schema is required`);if(!this.fn||typeof this.fn!=`function`)throw new d(`Tool function is required and must be a function`);if(!this.schema.name)throw new d(`Tool schema must have a name`)}};const ui=`at least one tool must stay resident; all tools cannot be deferred`,di=`a tool schema was withheld but no ${Pe} tool is offered; register the loader or turn tool search off`;function fi(e){return e.deferLoading===!0}function pi(e,t,n){if(n===`off`)return[...e];let r=e.filter(e=>!fi(e)||t.has(e.name));if(e.length>0&&r.length===0)throw Error(ui);if(r.length<e.length&&!r.some(e=>e.name===`ToolSearch`))throw Error(di);return r}function mi(e){if(e.length>0&&e.every(fi))throw Error(ui)}var hi=class extends Ye{moduleManager;pluginManager;get name(){return this.config.name}addPlugin(e){this.pluginManager.addPlugin(e)}removePlugin(e){return this.pluginManager.removePlugin(e)}getPlugin(e){return this.pluginManager.getPlugin(e)}getPlugins(){return this.pluginManager.getPlugins()}getPluginNames(){return this.pluginManager.getPluginNames()}async registerModule(e,t){return this.moduleManager.registerModule(e,t)}async unregisterModule(e){return this.moduleManager.unregisterModule(e)}getModule(e){return this.moduleManager.getModule(e)}getModulesByType(e){return this.moduleManager.getModulesByType(e)}getModules(){return this.moduleManager.getModules()}getModuleNames(){return this.moduleManager.getModuleNames()}hasModule(e){return this.moduleManager.hasModule(e)}async executeModule(e,t){return this.moduleManager.executeModule(e,t)}getModuleStats(e){return this.moduleManager.getModuleStats(e)}};async function gi(e,t,n){let{beforeToolEffect:r,...i}=n;return r?e.executeWithAdmission?e.executeWithAdmission(t,i,r):(await r(t),i.signal?.throwIfAborted(),e.execute(t,i)):e.execute(t,n)}function _i(e){if(!e.name)throw new m(`Agent name is required`,{component:`ConversationAgent`});if(!e.aiProviders||e.aiProviders.length===0)throw new m(`At least one AI provider is required`,{component:`ConversationAgent`});if(!e.defaultModel)throw new m(`Default model configuration is required`,{component:`ConversationAgent`});if(!e.defaultModel.provider||!e.defaultModel.model)throw new m(`Default model must specify both provider and model`,{component:`ConversationAgent`});let t=e.aiProviders.map(e=>e.name),n=t.filter((e,n)=>t.indexOf(e)!==n);if(n.length>0)throw new m(`Duplicate AI provider names: ${n.join(`, `)}`,{component:`ConversationAgent`,duplicates:n});if(!t.includes(e.defaultModel.provider))throw new m(`Default provider '${e.defaultModel.provider}' not found in AI providers list. Available: ${t.join(`, `)}`,{component:`ConversationAgent`,defaultProvider:e.defaultModel.provider,availableProviders:t})}var vi=class{logger;getAIProviders;getTools;getEventService;ensureReady;getConfig;setConfig;getConfigVersion;bumpConfigVersion;getConfigUpdatedAt;setConfigUpdatedAt;emitAgentEvent;constructor(e,t,n,r,i,a,o,s,c,l,u,d){this.logger=e,this.getAIProviders=t,this.getTools=n,this.getEventService=r,this.ensureReady=i,this.getConfig=a,this.setConfig=o,this.getConfigVersion=s,this.bumpConfigVersion=c,this.getConfigUpdatedAt=l,this.setConfigUpdatedAt=u,this.emitAgentEvent=d}async updateTools(e){if(await this.ensureReady(),!Array.isArray(e))throw new m(`updateTools: next must be an array of tools`);this.getTools().getRegistry().clear();let t=[],n=this.getEventService();for(let r of e){n&&r.setEventService(n),this.getTools().addResultTool(r.schema,async(e,t)=>{if(!t)throw Error(`[AGENT] Missing ToolExecutionContext for tool execution`);return gi(r,e,t)},r.provenance);let e=r.schema.name;typeof e==`string`&&e.length>0&&t.push(e)}let r=this.getConfig();r.tools=e,this.setConfig(r);let i=this.bumpConfigVersion();return this.setConfigUpdatedAt(Date.now()),this.emitAgentEvent(A.CONFIG_UPDATED,{parameters:{tools:t,systemMessage:r.systemMessage,provider:r.defaultModel.provider,model:r.defaultModel.model,temperature:r.defaultModel.temperature,maxTokens:r.defaultModel.maxTokens},metadata:{version:i}}),{version:i}}async updateConfiguration(e){if(e.tools)return this.updateTools(e.tools);if(e.name!==void 0){this.setConfig({...this.getConfig(),name:e.name});let t=this.bumpConfigVersion();return this.setConfigUpdatedAt(Date.now()),{version:t}}throw new m("updateConfiguration: only `tools` and `name` are supported")}async getConfiguration(){await this.ensureReady();let e=this.getTools().getTools().map(e=>({name:e.name,parameters:(()=>{let t=e.parameters?.properties;return t&&typeof t==`object`?Object.keys(t):void 0})()}));return{version:this.getConfigVersion(),tools:e,updatedAt:this.getConfigUpdatedAt(),metadata:void 0}}setModel(e){if(!e.provider||!e.model)throw new m(`Both provider and model are required`,{component:`ConversationAgent`});let t=this.getAIProviders(),n=t.getProviderNames();if(!n.includes(e.provider))throw new m(`AI Provider '${e.provider}' not found. Available: ${n.join(`, `)}`,{component:`ConversationAgent`,provider:e.provider,availableProviders:n});t.setCurrentProvider(e.provider,e.model);let r=this.getConfig();this.setConfig({...r,defaultModel:{...r.defaultModel,provider:e.provider,model:e.model,...e.temperature!==void 0&&{temperature:e.temperature},...e.maxTokens!==void 0&&{maxTokens:e.maxTokens},...e.topP!==void 0&&{topP:e.topP},...e.effort!==void 0&&{effort:e.effort}}}),this.logger.debug(`Model configuration updated`,e)}getModel(){let e=this.getAIProviders().getCurrentProvider();if(!e)throw new m(`No provider is currently set`,{component:`ConversationAgent`});let t=this.getConfig();return{provider:e.provider,model:e.model,...t.defaultModel.temperature!==void 0&&{temperature:t.defaultModel.temperature},...t.defaultModel.maxTokens!==void 0&&{maxTokens:t.defaultModel.maxTokens},...t.defaultModel.topP!==void 0&&{topP:t.defaultModel.topP},...t.defaultModel.effort!==void 0&&{effort:t.defaultModel.effort}}}setSystemMessage(e){let t=this.getConfig();t.systemMessage=e,this.setConfig(t),this.setConfigUpdatedAt(Date.now())}getSystemMessage(){return this.getConfig().systemMessage}registerTool(e,t){if(t.hasTool(e.schema.name))throw Error(`[STRICT-POLICY][EMITTER-CONTRACT] Duplicate tool registration attempted: ${e.schema.name}. Tool registration flow must provide a single authoritative registration path.`);t.addResultTool(e.schema,async(t,n)=>{if(!n)throw Error(`[AGENT] Missing ToolExecutionContext for tool execution`);return gi(e,t,n)},e.provenance),this.logger.debug(`Tool registered`,{toolName:e.schema.name})}},yi=class extends Xe{registry;allowedTools;resolveToolSearchMode;isToolVisible;loadedDeferredTools=new Set;constructor(e){super({readyOnConstruction:!0}),this.registry=new Rr,this.resolveToolSearchMode=e.resolveToolSearchMode,this.isToolVisible=e.isToolVisible??(()=>!0)}async doInitialize(){k.debug(`Tools initialized`)}async doDispose(){this.registry.clear(),this.loadedDeferredTools.clear(),delete this.allowedTools,k.debug(`Tools disposed`)}addTool(e,t){this.ensureInitialized();let n=new li(e,t);this.registry.register(n),k.debug(`Tool "${e.name}" registered successfully`)}addResultTool(e,t,n){this.ensureInitialized();let r=li.fromResult(e,t);Object.defineProperty(r,"provenance",{value:qe(n),enumerable:!0}),this.registry.register(r)}removeTool(e){this.ensureInitialized(),this.registry.unregister(e)}getTool(e){return this.ensureInitialized(),this.registry.get(e)}getToolSchema(e){return this.ensureInitialized(),this.registry.get(e)?.schema}getTools(){this.ensureInitialized();let e=this.registry.getSchemas().filter(e=>this.isToolVisible(e.name));return this.allowedTools?e.filter(e=>this.allowedTools.includes(e.name)):e}getOfferedTools(){return pi(this.getTools(),this.loadedDeferredTools,this.resolveToolSearchMode())}isToolOffered(e){return this.getOfferedTools().some(t=>t.name===e)}getLoadedDeferredTools(){return[...this.loadedDeferredTools].sort()}listDeferredTools(){return this.resolveToolSearchMode()===`off`?[]:this.getTools().filter(e=>fi(e)&&!this.loadedDeferredTools.has(e.name))}loadDeferredTools(e){this.ensureInitialized();let t=e.map(e=>{let t=this.isToolVisible(e)?this.registry.get(e)?.schema:void 0;if(!t)throw new l(`Tool "${e}" is not registered, so it cannot be loaded`,e);return t});for(let e of t)fi(e)&&this.loadedDeferredTools.add(e.name);return t}async executeTool(e,t,n){let r=await this.executeToolResult(e,t,n);if(!r.success)throw new l(r.error||`Tool execution failed`,e);if(r.data===void 0)throw new l(`Tool execution succeeded but returned no data`,e);return r.data}async executeToolResult(e,t,n){if(this.ensureInitialized(),this.allowedTools&&!this.allowedTools.includes(e))throw new l(`Tool "${e}" is not in the allowed tools list`,e);let r=this.registry.get(e);if(!r)throw new l(`Tool "${e}" is not registered`,e);let i=qe(r.provenance),a;try{a=await r.execute(t,n)}catch(t){throw R(t)?t:t instanceof Error?new l(t.message,e,t):new l(String(t),e)}return Je(a,i)}hasTool(e){return this.ensureInitialized(),this.registry.has(e)}setAllowedTools(e){this.ensureInitialized(),this.allowedTools=[...e],k.debug(`Set allowed tools: ${e.join(`, `)}`)}getAllowedTools(){return this.ensureInitialized(),this.allowedTools?[...this.allowedTools]:void 0}getRegistry(){return this.ensureInitialized(),this.registry}getToolCount(){return this.ensureInitialized(),this.registry.size()}};function bi(e){let t=xi(e.metadata),n=Ci(e.usage);return t??n}function xi(e){if(!e)return;let t=Ci({inputTokens:wi(e,`inputTokens`),outputTokens:wi(e,`outputTokens`),promptTokens:wi(e,`promptTokens`),completionTokens:wi(e,`completionTokens`),totalTokens:wi(e,`totalTokens`),cacheReadTokens:wi(e,`cacheReadTokens`)});if(t)return t;let n=e.usage;if(typeof n==`string`)return Si(n);if(Ei(n))return Ci(n)}function Si(e){try{return Ci(JSON.parse(e))}catch{return}}function Ci(e){if(!e)return;let t=Ti(e.inputTokens,e.promptTokens),n=Ti(e.outputTokens,e.completionTokens);if(t===void 0||n===void 0)return;let r=Ti(e.totalTokens),i=Ti(e.cacheReadTokens),a=i!==void 0&&i>=0&&i<=t;return{inputTokens:t,outputTokens:n,...r!==void 0&&{totalTokens:r},...a&&{cacheReadTokens:i}}}function wi(e,t){let n=e[t];return typeof n==`number`&&Number.isFinite(n)?n:void 0}function Ti(...e){return e.find(e=>typeof e==`number`&&Number.isFinite(e))}function Ei(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&Object.values(e).every(e=>typeof e==`number`&&Number.isFinite(e))}const Di=4;function Oi(e){return Math.ceil(JSON.stringify(e).length/4)}function ki(e){return e.length===0?0:Math.ceil(JSON.stringify(e).length/4)}function Ai(e,t={}){let n=Oi(e),r=ji(e),i=r?.tokens,a=Mi(t.usageFloorTokens);return{usedTokens:r?.index===e.length-1?Math.max(i??0,a??0):Math.max(n,i??0,a??0),serializedTokens:n,...i!==void 0&&{providerTokens:i},...a!==void 0&&{usageFloorTokens:a}}}function ji(e){for(let t=e.length-1;t>=0;t--){let n=bi(e[t]);if(n)return{tokens:n.totalTokens??n.inputTokens+n.outputTokens,index:t}}}function Mi(e){if(!(e===void 0||!Number.isFinite(e)||e<=0))return Math.ceil(e)}const Ni=O(`agent-core:models`),Pi=new Set;function Fi(e,t,n){let r=`${e}:${t}`;Pi.has(r)||(Pi.add(r),Ni.warn(`No metadata registered for model "${e}"; using the default ${t} of ${n}. This number belongs to a different vendor's models — register the model through registerModelMetadata() from the package that owns it. (NEUT-010)`))}const Ii=2e5,Li=new Map;function Ri(...e){for(let t of e){let e=Li.get(t.id);e&&!zi(e,t)&&Ni.warn(`Model "${t.id}" was already registered with different metadata (context window ${e.contextWindow} -> ${t.contextWindow}, max output ${e.maxOutput} -> ${t.maxOutput}). The later registration wins; one of the two owners is wrong. (NEUT-010)`),Li.set(t.id,t)}}function zi(e,t){return e.name===t.name&&e.contextWindow===t.contextWindow&&e.maxOutput===t.maxOutput}function Bi(e){return Li.get(e)}function Vi(e){let t=Bi(e)?.contextWindow;return t===void 0?(Fi(e,`context window`,Ii),Ii):t}const Hi=16384;function Ui(e){let t=Bi(e)?.maxOutput;return t===void 0?(Fi(e,`max output`,Hi),Hi):t}function Wi(e){return Bi(e)?.name??e}function Gi(e){if(e>=1e6){let t=e/1e6;return Number.isInteger(t)?`${t}M`:`${parseFloat(t.toFixed(1))}M`}if(e<=0)return`0K`;if(e<1e3)return`<1K`;let t=e/1e3;return Number.isInteger(t)?`${t}K`:`${parseFloat(t.toFixed(1))}K`}function Ki(e,t,n){let r=e.toolSearch??`auto`;if(r!==`auto`)return r;let i=n.filter(fi);return i.length===0?`off`:i.length>15||ki(i)/Vi(t)>=.1?`on`:`off`}function qi(e){return e.conversationId||`conv_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}function Ji(e){let t=new yi({resolveToolSearchMode:()=>{let n=e();return n.isToolVisible?.(`ToolSearch`)===!1?`off`:Ki(n,n.defaultModel.model,t.getTools())},isToolVisible:t=>e().isToolVisible?.(t)??!0});return t}var Yi=class{agentName;moduleRegistry;logger;isReady;ensureReady;constructor(e,t,n,r,i){this.agentName=e,this.moduleRegistry=t,this.logger=n,this.isReady=r,this.ensureReady=i}async registerModule(e,t){await this.ensureReady(),await this.moduleRegistry.registerModule(e,{autoInitialize:t?.autoInitialize??!0,validateDependencies:t?.validateDependencies??!0}),this.logger.info(`Module registered`,{moduleName:e.name,moduleType:e.getModuleType().type})}async unregisterModule(e){if(!this.isReady())return!1;let t=await this.moduleRegistry.unregisterModule(e);return t&&this.logger.info(`Module unregistered`,{moduleName:e}),t}getModule(e){if(this.isReady())return this.moduleRegistry.getModule(e)}getModulesByType(e){return this.isReady()?this.moduleRegistry.getModulesByType(e):[]}getModules(){return this.isReady()?this.moduleRegistry.getAllModules():[]}getModuleNames(){return this.isReady()?this.moduleRegistry.getModuleNames():[]}hasModule(e){return this.isReady()?this.moduleRegistry.hasModule(e):!1}async executeModule(e,t){await this.ensureReady();let n={agentName:this.agentName,...t.executionId&&{executionId:t.executionId},...t.sessionId&&{sessionId:t.sessionId},...t.userId&&{userId:t.userId},...t.metadata&&{metadata:t.metadata}};return await this.moduleRegistry.executeModule(e,n)}getModuleStats(e){if(this.isReady())return this.moduleRegistry.getModuleStats(e)}},Xi=class{logger;isReady;getExecutionService;constructor(e,t,n){this.logger=e,this.isReady=t,this.getExecutionService=n}addPlugin(e){let t=this.getExecutionService();if(!this.isReady()||!t)throw new m(`Cannot add plugin before agent is fully initialized. Await an operation like run() first, or pass plugins via the constructor config.`,{pluginName:e.name});t.registerPlugin(e),this.logger.debug(`Plugin added`,{pluginName:e.name})}removePlugin(e){let t=this.getExecutionService();if(!t)return!1;let n=t.removePlugin(e);return n&&this.logger.debug(`Plugin removed`,{pluginName:e}),n}getPlugin(e){let t=this.getExecutionService();if(t)return t.getPlugin(e)}getPlugins(){let e=this.getExecutionService();return e?e.getPlugins():[]}getPluginNames(){let e=this.getExecutionService();return!this.isReady()||!e?[]:e.getPlugins().map(e=>e.name)}};function Zi(e){return{moduleManager:new Yi(e.getName(),e.getModuleRegistry(),e.getLogger(),e.getIsFullyInitialized,e.ensureFullyInitialized),pluginManager:new Xi(e.getLogger(),e.getIsFullyInitialized,e.getExecutionService),configManager:new vi(e.getLogger(),e.getAiProviders,e.getTools,e.getEventService,e.ensureFullyInitialized,e.getConfig,t=>e.setConfig(t),e.getConfigVersion,e.incrementConfigVersion,e.getConfigUpdatedAt,t=>e.setConfigUpdatedAt(t),(t,n)=>e.emitAgentEvent(t,n))}}const Qi={ASSIGNED:`assigned`,COMPLETED:`completed`},$i=`task`,ea={MESSAGE:`message`,INPUT:`input`},ta=`user`;function na(e,t){let n=Array.isArray(e.tools)?e.tools.map(e=>{let t=e?.schema?.name;if(typeof t==`string`&&t.length>0)return t;let n=e?.name;return typeof n==`string`&&n.length>0?n:``}).filter(e=>typeof e==`string`&&e.length>0):[];t(A.CREATED,{parameters:{tools:n,systemMessage:e.systemMessage,provider:e.defaultModel.provider,model:e.defaultModel.model,temperature:e.defaultModel.temperature,maxTokens:e.defaultModel.maxTokens}})}function ra(e,t,n,r,i){Yr(e)||e.emit(r,{timestamp:new Date,...i},{ownerType:kt,ownerId:t,ownerPath:aa(t,n)})}function ia(){return new Ir({enabled:!0,events:[P.MODULE_INITIALIZE_START,P.MODULE_INITIALIZE_COMPLETE,P.MODULE_INITIALIZE_ERROR,P.MODULE_EXECUTION_START,P.MODULE_EXECUTION_COMPLETE,P.MODULE_EXECUTION_ERROR,P.MODULE_DISPOSE_START,P.MODULE_DISPOSE_COMPLETE,P.MODULE_DISPOSE_ERROR]})}function aa(e,t){return[...t?.ownerPath?.length?t.ownerPath.map(e=>({...e})):[],{type:`agent`,id:e}]}function oa(e,t){return{conversationId:e.conversationId,...t.sessionId&&{sessionId:t.sessionId},...t.userId&&{userId:t.userId},...t.driverId&&{driverId:t.driverId},...t.turnSource&&{turnSource:t.turnSource},...t.metadata&&{metadata:t.metadata},...t.signal&&{signal:t.signal},awaitProviderSettlement:t.awaitProviderSettlement,...t.onTextDelta&&{onTextDelta:t.onTextDelta},...t.onExecutionEvent&&{onExecutionEvent:t.onExecutionEvent},...t.executionJournal&&{executionJournal:t.executionJournal},...t.maxExecutionRounds!==void 0&&{maxExecutionRounds:t.maxExecutionRounds},...t.maxSameToolInputs!==void 0&&{maxSameToolInputs:t.maxSameToolInputs},...t.allowToolOnlyCompletion!==void 0&&{allowToolOnlyCompletion:t.allowToolOnlyCompletion},...t.maxTokens!==void 0&&{maxTokens:t.maxTokens},...t.temperature!==void 0&&{temperature:t.temperature},...t.toolChoice!==void 0&&{toolChoice:t.toolChoice},...t.withholdHostedTools===!0&&{withholdHostedTools:!0},...t.ephemeralSystemContext!==void 0&&{ephemeralSystemContext:t.ephemeralSystemContext},...t.traceContext!==void 0&&{traceContext:t.traceContext}}}async function sa(e,t,n={},r){try{e.emitAgentEvent(A.EXECUTION_START,{}),e.logger.debug(`Starting ConversationAgent execution`,{inputLength:t.length,conversationId:e.conversationId,sessionId:n.sessionId||`none`,userId:n.userId||`none`,hasMetadata:!!n.metadata});let i=e.getHistory(),a={...e.config,...r},o=await e.getExecutionService().execute(t,i,a,oa(e,n));if(e.logger.debug(`ConversationAgent execution completed`,{success:o.success,duration:o.duration,tokensUsed:o.tokensUsed,toolsExecuted:o.toolsExecuted,interrupted:o.interrupted}),o.interrupted)return e.emitAgentEvent(A.EXECUTION_COMPLETE,{}),o.response;if(!o.success)throw o.error??Error(`[STRICT-POLICY] Failed execution result missing error field — every success:false result must carry error`);return e.emitAgentEvent(A.EXECUTION_COMPLETE,{}),o.response}catch(t){throw t instanceof I?t:(e.logger.error(`ConversationAgent execution failed`,{error:t instanceof Error?t.message:String(t),conversationId:e.conversationId}),e.emitAgentEvent(A.EXECUTION_ERROR,{error:t instanceof Error?t.message:String(t)}),t)}}async function*ca(e,t,n={},r){let i=!1;try{e.emitAgentEvent(A.EXECUTION_START,{}),e.logger.debug(`Starting ConversationAgent streaming execution`,{inputLength:t.length,conversationId:e.conversationId,sessionId:n.sessionId||`none`,userId:n.userId||`none`,hasMetadata:!!n.metadata});let i=e.getHistory(),a={...e.config,...r},o=yield*e.getExecutionService().executeStream(t,i,a,oa(e,n));if(!o.success)throw o.error??Error(`[STRICT-POLICY] Failed execution result missing error field — every success:false result must carry error`);return o.response}catch(t){throw t instanceof I?(i=!0,t):(e.logger.error(`ConversationAgent streaming execution failed`,{error:t instanceof Error?t.message:String(t),conversationId:e.conversationId}),e.emitAgentEvent(A.EXECUTION_ERROR,{error:t instanceof Error?t.message:String(t)}),t)}finally{i||e.emitAgentEvent(A.EXECUTION_COMPLETE,{})}}function la(e){return{responseFormat:{type:`json_schema`,schema:e.jsonSchema,name:e.name}}}function ua(e,t){return[`Your previous response did not match the required JSON schema.`,`Validation issues:`,...t.map(e=>`- ${e}`),``,`Respond with ONLY a JSON object (no prose, no code fences) matching this JSON schema:`,JSON.stringify(e.jsonSchema)].join(`
4
4
  `)}async function da(e,t,n,r){let i=(n.outputRetries??2)+1,a=la(r),o=t,s=[];for(let t=1;t<=i;t++){let c=pa(r,await sa(e,o,n,a));if(c.success)return c.value;s=c.issues,e.logger.debug(`Structured output validation failed`,{attempt:t,maxAttempts:i,issues:s}),t<i&&(o=ua(r,s))}throw new u(`response failed schema validation after ${i} attempt(s)`,s,i)}async function*fa(e,t,n,r){let i=(n.outputRetries??2)+1,a=la(r),o=t,s=[];for(let t=1;t<=i;t++){let c=pa(r,yield*ca(e,o,n,a));if(c.success)return c.value;s=c.issues,e.logger.debug(`Structured output validation failed (stream)`,{attempt:t,maxAttempts:i,issues:s}),t<i&&(o=ua(r,s))}throw new u(`response failed schema validation after ${i} attempt(s)`,s,i)}function pa(e,t){let n=Xn(t);if(!n.success)return{success:!1,issues:[n.issue]};let r=e.validate(n.value);return r.success?{success:!0,value:r.value}:{success:!1,issues:r.issues}}function ma(e,t){return e.getConversationStore(t).getMessages().map(e=>({id:e.id,role:e.role,content:e.content,state:e.state,timestamp:e.timestamp,metadata:e.metadata,...e.parts===void 0?{}:{parts:structuredClone(e.parts)},...e.role===`assistant`&&`toolCalls`in e?{toolCalls:e.toolCalls}:{},...e.role===`tool`&&`toolCallId`in e?{toolCallId:e.toolCallId}:{},...e.role===`tool`&&`name`in e?{name:e.name}:{}}))}function ha(e,t){return e.getConversationStore(t).getHistory()}function ga(e,t,n){e.getConversationStore(t).addEntry(n)}function _a(e,t){e.getConversationStore(t).clear()}function va(e,t,n,r,i){let a=e.getConversationStore(t);n===`tool`&&i?.toolCallId?a.addToolMessageWithId(r,i.toolCallId,i.name??`unknown`):n===`assistant`?a.addAssistantMessage(r,[]):n===`system`?a.addSystemMessage(r):a.addUserMessage(r)}function ya(e,t,n){e.getConversationStore(t).addMessage(n)}var ba=class extends Xe{providers=new Map;currentProvider;currentModel;constructor(){super({readyOnConstruction:!0})}async doInitialize(){k.debug(`AIProviders initialized`)}async doDispose(){for(let[e,t]of this.providers)try{t.close&&await t.close(),k.debug(`Closed AI provider: ${e}`)}catch(t){k.warn(`Failed to close AI provider ${e}`,{error:t instanceof Error?t.message:String(t)})}this.providers.clear(),this.currentProvider=void 0,this.currentModel=void 0,k.debug(`AIProviders disposed`)}addProvider(e,t){this.ensureInitialized();let n=Gt.validateProviderName(e);if(!n.isValid)throw new d(`Invalid provider name: ${n.errors.join(`, `)}`);if(!t||typeof t!=`object`||Array.isArray(t))throw new d(`Provider must be a valid object instance`);if(!t.name||typeof t.name!=`string`)throw new d(`Provider must have a valid name`);if(typeof t.chat!=`function`)throw new d(`Provider must have a chat method`);this.providers.has(e)&&k.warn(`Provider "${e}" is already registered, overriding`,{providerName:e,existingProvider:this.providers.get(e)?.name}),this.providers.set(e,t),k.debug(`AI provider "${e}" registered successfully`,{providerName:e,version:t.version,supportsStreaming:typeof t.chatStream==`function`})}removeProvider(e){if(this.ensureInitialized(),!this.providers.has(e)){k.warn(`Attempted to remove non-existent provider "${e}"`);return}let t=this.providers.get(e);t?.close&&t.close().catch(t=>{k.warn(`Failed to close provider ${e}`,{error:t.message})}),this.providers.delete(e),this.currentProvider===e&&(this.currentProvider=void 0,this.currentModel=void 0,k.debug(`Cleared current provider selection after removing "${e}"`)),k.debug(`AI provider "${e}" removed successfully`)}getProvider(e){return this.ensureInitialized(),this.providers.get(e)}getProviders(){return this.ensureInitialized(),Object.fromEntries(this.providers)}setCurrentProvider(e,t){if(this.ensureInitialized(),!this.providers.get(e))throw new m(`Provider "${e}" is not registered`);this.currentProvider=e,this.currentModel=t,k.debug(`Current AI provider set to "${e}" with model "${t}"`)}getCurrentProvider(){if(this.ensureInitialized(),!(!this.currentProvider||!this.currentModel))return{provider:this.currentProvider,model:this.currentModel}}isConfigured(){return this.ensureInitialized(),!!(this.currentProvider&&this.currentModel&&this.providers.has(this.currentProvider))}getCurrentProviderInstance(){if(!(!this.isConfigured()||!this.currentProvider))return this.providers.get(this.currentProvider)}getProviderNames(){return this.ensureInitialized(),Array.from(this.providers.keys())}getProvidersByPattern(e){this.ensureInitialized();let t=typeof e==`string`?new RegExp(e):e,n={};for(let[e,r]of this.providers)t.test(e)&&(n[e]=r);return n}supportsStreaming(e){this.ensureInitialized();let t=e||this.currentProvider;if(!t)return!1;let n=this.providers.get(t);return!!(n&&typeof n.chatStream==`function`)}getProviderCount(){return this.ensureInitialized(),this.providers.size}},xa=class{build(e,t,n,r){let i=e.map(e=>({role:e.role,content:e.content})),a=JSON.stringify({messages:i,model:t,provider:n,temperature:r?.temperature,maxTokens:r?.maxTokens,effortCacheIdentity:r?.effortCacheIdentity??null});return{hash:this.sha256(a),model:t,provider:n}}computeIntegrityHash(e){return this.sha256(e)}sha256(e){let t=new de(`SHA-256`,`TEXT`);return t.update(e),t.getHash(`HEX`)}},Sa=class{cache=new Map;accessOrder=[];maxEntries;ttlMs;keyBuilder=new xa;hits=0;misses=0;constructor(e){this.maxEntries=e.maxEntries,this.ttlMs=e.ttlMs}get(e){let t=this.cache.get(e);if(!t){this.misses++;return}if(Date.now()-t.timestamp>this.ttlMs){this.cache.delete(e),this.removeFromAccessOrder(e),this.misses++;return}let n=this.keyBuilder.computeIntegrityHash(t.response);if(t.integrityHash!==n)throw this.cache.delete(e),this.removeFromAccessOrder(e),new x(`Integrity check failed for cache entry ${e}`,{hash:e,expected:n,actual:t.integrityHash});return this.touchAccessOrder(e),this.hits++,t}set(e){let t=e.key.hash;!this.cache.has(t)&&this.cache.size>=this.maxEntries&&this.evictLRU(),this.cache.set(t,e),this.touchAccessOrder(t)}delete(e){return this.cache.has(e)?(this.cache.delete(e),this.removeFromAccessOrder(e),!0):!1}clear(){this.cache.clear(),this.accessOrder.length=0,this.hits=0,this.misses=0}getStats(){let e=this.hits+this.misses;return{hits:this.hits,misses:this.misses,entries:this.cache.size,hitRate:e===0?0:this.hits/e}}touchAccessOrder(e){this.removeFromAccessOrder(e),this.accessOrder.push(e)}removeFromAccessOrder(e){let t=this.accessOrder.indexOf(e);t!==-1&&this.accessOrder.splice(t,1)}evictLRU(){let e=this.accessOrder.shift();e&&this.cache.delete(e)}},Ca=class{storage;keyBuilder;constructor(e,t){this.storage=e,this.keyBuilder=t}lookup(e,t,n,r){let i=this.keyBuilder.build(e,t,n,r),a=this.storage.get(i.hash);return a?a.response:void 0}store(e,t,n,r,i){let a=this.keyBuilder.build(e,t,n,i);this.storage.set({key:a,response:r,timestamp:Date.now(),integrityHash:this.keyBuilder.computeIntegrityHash(r)})}getStats(){return this.storage.getStats()}};function wa(e){return`executionId`in e||`toolName`in e}function Ta(e){let t=0,n=!1;for(let r=0;r<e.length;r++){let i=e[r]===` `||e[r]===` `||e[r]===`