@dudousxd/nestjs-agent-core 0.24.0 → 0.26.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.cts CHANGED
@@ -1,6 +1,8 @@
1
- import { M as ModelMessage, a as ToolDefinition, b as ToolCallRequest, c as MessageUsage, d as AgentUiComponent, A as Actor, e as AiToolCtx, f as AgentStreamEvent, g as ThreadSummary, h as ThreadDetail, S as StoredMessage, i as ToolResult, j as MessageAttachment, k as MessageFeedback, l as ToolCallStatus, U as UsagePurpose, m as ToolSpec, Q as QuotaState, n as AgentRunInput, H as HumanReply, o as ToolKind, p as ToolCallApproval, T as ToolHandler, q as HistoryPolicy, O as OutputProcessor, P as ProcessorContext, I as InputProcessor, r as ProcessedPrompt, s as ModelAnswer, t as PageContext, u as AgentDefinition, v as AgentDelegation, D as DetachedDelivery, w as PromptBuilder, x as PromptContributor, y as ToolTransientRetrySetting, z as AgentIntake, B as Decision, E as ElicitationRequest, L as LlmStepEnvelope, C as ToolStepEnvelope } from './tool-fLRLs_f3.cjs';
2
- export { F as ASK_TOOL_DESCRIPTION, G as ASK_TOOL_NAME, J as AgentApprovalRequest, K as AgentApprovalSettlement, N as AgentCatalogEntry, R as AgentHistoryWindow, V as AskToolInput, W as DEFAULT_INCREMENTAL_LOOKBACK_CHARS, X as DEFAULT_INTAKE_PREAMBLE, Y as DEFAULT_TOOL_TRANSIENT_RETRY_ATTEMPTS, Z as DEFAULT_TOOL_TRANSIENT_RETRY_BACKOFF_MS, _ as ELICITATION_INPUT_TYPES, $ as ElicitationInput, a0 as ElicitationInputType, a1 as ElicitationOption, a2 as ElicitationOutcome, a3 as ElicitationQuestion, a4 as ElicitationReply, a5 as ElicitationResult, a6 as HistoryPolicyContext, a7 as HistorySelection, a8 as HistorySummary, a9 as IncrementalGating, aa as InvokeWithTransientRetryOptions, ab as MAX_ASK_QUESTIONS, ac as MessageFeedbackValue, ad as MessageRole, ae as OutputRejectedError, af as OutputVerdict, ag as ProcessorFailedError, ah as PromptContext, ai as QuotaView, aj as ToolCallApprovalStatus, ak as ToolCatalogEntry, al as ToolConfirmation, am as ToolPresentation, an as ToolPresentationTone, ao as ToolResultField, ap as ToolResultView, aq as ToolStepCtx, ar as ToolTransientRetryNumbers, as as ToolTransientRetryOptions, at as askInputSchema, au as askToolDefinition, av as decodeStreamEvent, aw as encodeStreamEvent, ax as invokeWithTransientRetry, ay as isTransientToolError, az as isTypedQuestion, aA as normalizeElicitationReply, aB as questionOptions, aC as readElicitationInput, aD as readElicitationQuestions, aE as renderElicitationAnswers, aF as resolveElicitation, aG as resolveToolTransientRetryNumbers, aH as settleElicitation, aI as validateElicitationAnswer, aJ as validateElicitationValue } from './tool-fLRLs_f3.cjs';
1
+ import { M as ModelMessage, c as ToolDefinition, d as ToolCallRequest, e as MessageUsage, f as AgentUiComponent, A as Actor, g as AiToolCtx, h as AgentStreamEvent, i as ThreadSummary, j as ThreadDetail, S as StoredMessage, k as ToolResult, l as MessageAttachment, m as MessageFeedback, n as ToolCallStatus, U as UsagePurpose, T as ToolSpec, Q as QuotaState, o as AgentRunInput, H as HumanReply, p as ToolKind, q as ToolCallApproval, a as ToolHandler, r as HistoryPolicy, P as PageContext, s as AgentDefinition, t as AgentDelegation, D as DetachedDelivery, u as ToolDescribeScope, v as PromptBuilder, w as PromptContributor, x as ToolTransientRetrySetting, y as AgentIntake, z as Decision, E as ElicitationRequest, L as LlmStepEnvelope, B as ToolStepEnvelope } from './tool-BXKG2xSm.cjs';
2
+ export { C as ASK_TOOL_DESCRIPTION, F as ASK_TOOL_NAME, G as AgentApprovalRequest, I as AgentApprovalSettlement, J as AgentCatalogEntry, K as AgentHistoryWindow, N as AskToolInput, O as DEFAULT_INTAKE_PREAMBLE, R as DEFAULT_TOOL_TRANSIENT_RETRY_ATTEMPTS, V as DEFAULT_TOOL_TRANSIENT_RETRY_BACKOFF_MS, W as ELICITATION_INPUT_TYPES, X as ElicitationInput, Y as ElicitationInputType, Z as ElicitationOption, _ as ElicitationOutcome, $ as ElicitationQuestion, a0 as ElicitationReply, a1 as ElicitationResult, a2 as HistoryPolicyContext, a3 as HistorySelection, a4 as HistorySummary, a5 as InvokeWithTransientRetryOptions, a6 as MAX_ASK_QUESTIONS, a7 as MessageFeedbackValue, a8 as MessageRole, a9 as PromptContext, aa as QuotaView, ab as ToolCallApprovalStatus, ac as ToolCatalogEntry, ad as ToolConfirmation, ae as ToolDescription, b as ToolPresentation, af as ToolPresentationTone, ag as ToolResultField, ah as ToolResultView, ai as ToolStepCtx, aj as ToolTransientRetryNumbers, ak as ToolTransientRetryOptions, al as askInputSchema, am as askToolDefinition, an as decodeStreamEvent, ao as encodeStreamEvent, ap as invokeWithTransientRetry, aq as isTransientToolError, ar as isTypedQuestion, as as normalizeElicitationReply, at as questionOptions, au as readElicitationInput, av as readElicitationQuestions, aw as renderElicitationAnswers, ax as resolveElicitation, ay as resolveToolTransientRetryNumbers, az as settleElicitation, aA as validateElicitationAnswer, aB as validateElicitationValue } from './tool-BXKG2xSm.cjs';
3
3
  import { StandardSchemaV1 } from '@standard-schema/spec';
4
+ import { O as OutputProcessor, P as ProcessorContext, I as InputProcessor, a as ProcessedPrompt, M as ModelAnswer } from './processors-Bf1fYLbY.cjs';
5
+ export { D as DEFAULT_INCREMENTAL_LOOKBACK_CHARS, b as IncrementalGating, c as OutputRejectedError, d as OutputVerdict, e as ProcessorFailedError } from './processors-Bf1fYLbY.cjs';
4
6
  import { ChannelRegistry } from '@dudousxd/nestjs-diagnostics';
5
7
 
6
8
  /**
@@ -32,6 +34,8 @@ declare const AGENT_REGISTRY: unique symbol;
32
34
  declare const AGENT_ACTOR_RESOLVER: unique symbol;
33
35
  /** The governance read-model (usage/spend/threads), consumed by the dashboard + telescope surfaces. */
34
36
  declare const AGENT_GOVERNANCE_QUERIES: unique symbol;
37
+ /** The `QuotaProvider` behind `GET <base>/quota` (and, when the host binds one, the send gate). */
38
+ declare const AGENT_QUOTA_PROVIDER: unique symbol;
35
39
  /** The `ModelCatalog` behind `GET <base>/models` and the model a send may name. Optional. */
36
40
  declare const AGENT_MODEL_CATALOG: unique symbol;
37
41
  /** The pricing WRITE side (`AgentPricingStore`) — seeds/updates the per-model rates cost is priced against. */
@@ -309,7 +313,13 @@ declare function unwrapToolStepOutput(raw: unknown): {
309
313
  output: unknown;
310
314
  ui: AgentUiComponent[];
311
315
  };
312
- type EmitUi = NonNullable<AiToolCtx['emitUi']>;
316
+ type EmitUi = AiToolCtx['emitUi'];
317
+ /**
318
+ * `ctx.emitUi` where there is no conversation to push into (the MCP server, a direct
319
+ * `registry.invoke`): nothing is streamed or persisted, but the call resolves to an id — the one it
320
+ * was given, else `<scope>:ui:<n>` — so a tool never has to test for the capability.
321
+ */
322
+ declare function createNoopEmitUi(scope?: string): EmitUi;
313
323
  /** Collects what one tool invocation pushes, streaming each push as it happens. */
314
324
  interface UiCollector {
315
325
  emit: EmitUi;
@@ -644,6 +654,15 @@ interface AgentStore {
644
654
  usedTokens: number;
645
655
  costUsd: number;
646
656
  }>;
657
+ /**
658
+ * OPTIONAL: the actor's spend over the UTC days `fromDay`..`toDay` (`YYYY-MM-DD`, inclusive) —
659
+ * {@link quotaToday} over a range. Feeds the monthly window of `GET <base>/quota`; absent → that
660
+ * window is left out.
661
+ */
662
+ usageBetween?(actorRef: string, fromDay: string, toDay: string): Promise<{
663
+ usedTokens: number;
664
+ costUsd: number;
665
+ }>;
647
666
  }
648
667
 
649
668
  /**
@@ -668,6 +687,57 @@ interface QuotaStore {
668
687
  bump(actorRef: string, day: string, tokens: number): Promise<void>;
669
688
  }
670
689
 
690
+ /** The span a quota window counts over, in UTC. */
691
+ type QuotaPeriod = 'day' | 'month';
692
+ /** One budget window: what was spent in it, and the ceiling when there is one. */
693
+ interface QuotaWindow {
694
+ period: QuotaPeriod;
695
+ usedTokens: number;
696
+ /** Absent → no token ceiling on this window. */
697
+ limitTokens?: number;
698
+ usedUsd: number;
699
+ /** Absent → no spend ceiling on this window. */
700
+ limitUsd?: number;
701
+ /** ISO-8601 instant the window starts over (next UTC midnight, first of next month). */
702
+ resetsAt?: string;
703
+ }
704
+ /** Which window stopped the actor, when one did. */
705
+ interface QuotaBlock {
706
+ period: QuotaPeriod;
707
+ /** Words a client can show ("Monthly AI budget reached"). */
708
+ reason?: string;
709
+ }
710
+ /** What `GET <base>/quota` answers. */
711
+ interface QuotaReport {
712
+ windows: QuotaWindow[];
713
+ /** Present when a window is exhausted — a send will be refused until it resets. */
714
+ blocked?: QuotaBlock;
715
+ }
716
+ interface QuotaQuery {
717
+ actor: Actor;
718
+ /** The instant to report for; defaults to now. */
719
+ now?: Date;
720
+ }
721
+ /**
722
+ * The actor's budget across windows — the read behind `GET <base>/quota` and, when the host binds
723
+ * one (`AgentModule.forRoot({ quotaProvider })`), the gate a send passes: a report with `blocked`
724
+ * refuses the turn with `429` before it starts.
725
+ *
726
+ * The default reads the usage ledger (`LedgerQuotaProvider` in `@dudousxd/nestjs-agent`); a host
727
+ * with its own budget (an AI-gateway spend cap, a plan's monthly allowance) implements this.
728
+ */
729
+ interface QuotaProvider {
730
+ report(query: QuotaQuery): Promise<QuotaReport>;
731
+ }
732
+ /** The first window whose token or spend ceiling is reached, as a {@link QuotaBlock}. */
733
+ declare function exhaustedWindow(windows: readonly QuotaWindow[]): QuotaBlock | undefined;
734
+ /** The UTC day range (`YYYY-MM-DD`, inclusive) and reset instant of `period` around `now`. */
735
+ declare function quotaPeriodRange(period: QuotaPeriod, now: Date): {
736
+ fromDay: string;
737
+ toDay: string;
738
+ resetsAt: string;
739
+ };
740
+
671
741
  /**
672
742
  * The WRITE side of the pricing table the {@link import('./governance-queries.js').AgentGovernanceQueries}
673
743
  * read-model prices usage against. Cost is $0 for an unpriced model, so an app seeds its models'
@@ -2688,13 +2758,14 @@ declare class ToolRegistry {
2688
2758
  * feature-flag store, an MCP server — and this runs once per model step. Asking those about a
2689
2759
  * tool the allow-list has already excluded is a call whose answer nothing reads.
2690
2760
  */
2691
- definitionsFor(actor: Actor, policy: RolesPolicy, allowedTools?: string[]): Promise<ToolDefinition[]>;
2761
+ definitionsFor(actor: Actor, policy: RolesPolicy, allowedTools?: string[], scope?: Omit<ToolDescribeScope, 'actor'>): Promise<ToolDefinition[]>;
2692
2762
  /**
2693
2763
  * The specs {@link definitionsFor} offers the model, whole — the same four gates (allow-list,
2694
2764
  * enabled, role, `canUse`) in the same order. For a surface that lists what an actor can reach
2695
2765
  * (`GET <base>/tools`), which must never disagree with what the model is actually shown.
2696
2766
  */
2697
2767
  visibleSpecs(actor: Actor, policy: RolesPolicy, allowedTools?: string[]): Promise<ToolSpec[]>;
2768
+ private visibleEntries;
2698
2769
  /**
2699
2770
  * Run a tool. Re-checks that the tool is enabled and that the role allows it (defense-in-depth —
2700
2771
  * a call can reach here from a replayed durable step or an approval granted before the flag
@@ -3408,4 +3479,4 @@ type AgentDiagnosticKey = `agent:${AgentDiagnosticEvent}`;
3408
3479
  */
3409
3480
  declare function agentDiagnosticKey(event: AgentDiagnosticEvent): AgentDiagnosticKey;
3410
3481
 
3411
- export { AGENT_ACTOR_DIRECTORY, AGENT_ACTOR_RESOLVER, AGENT_APPROVAL_PORT, AGENT_ATTACHMENT_STAGING, AGENT_DEPS_FACTORY, AGENT_DIAGNOSTIC_EVENTS, AGENT_DURABLE_RUNNER, AGENT_EMBEDDING_PROVIDER, AGENT_GOVERNANCE_QUERIES, AGENT_MEMORY, AGENT_MODEL, AGENT_MODEL_CATALOG, AGENT_OPTIONS, AGENT_PRICING_STORE, AGENT_PROMPT_CONTRIBUTORS, AGENT_QUOTA_STORE, AGENT_REGISTRY, AGENT_RETRIEVER, AGENT_ROLES_POLICY, AGENT_RUNNER, AGENT_SINK, AGENT_SKILLS, AGENT_SKILL_SOURCES, AGENT_SPAN_EVENTS, AGENT_STORE, AGENT_TOOL_REGISTRY, APPROVAL_EXPIRED_REASON, Actor, type ActorDirectory, type ActorResolver, type ActorSpendRow, type AgentApprovalPort, AgentDefinition, type AgentDelegated, AgentDelegation, type AgentDiagnosticEvent, type AgentDiagnosticKey, type AgentFollowUpsSpan, type AgentGovernanceQueries, AgentIntake, type AgentLlmTurnSpan, type AgentLoopDeps, type AgentLoopHooks, type AgentLoopResult, type AgentMemoryResolved, type AgentMemoryWritten, type AgentMessageEvent, type AgentPricingStore, type AgentQuotaExceeded, AgentRegistry, type AgentRetrievalSpan, type AgentRetrieved, type AgentRunFailed, type AgentRunFinished, AgentRunInput, type AgentRunStarted, type AgentRunner, type AgentSkillsResolved, type AgentSpanEvent, type AgentStore, AgentStreamError, AgentStreamEvent, type AgentStructuredOutputSpan, type AgentToolCallEvent, type AgentToolExecutionSpan, type AgentToolRetry, AgentUiComponent, AiToolCtx, type AppendMessageInput, type ApprovalDecisionRef, type ApprovalPolicy, type ApprovalRequirement, type ApprovalThreadRef, type ApprovalToolRef, type ApprovalWhere, type AttachmentRef, type AttachmentStagingStore, type BufferedModelTurnResult, type BuildMemoryBlockInput, type CostUsage, type CreateThreadInput, type CurrentModelPrice, DEFAULT_HISTORY_SUMMARY_INSTRUCTION, DEFAULT_MAX_FACT_CHARS, DEFAULT_MAX_MEMORIES, DEFAULT_MAX_SKILLS, DEFAULT_REFUSAL_REASON, DEFAULT_STRUCTURED_OUTPUT_INSTRUCTION, Decision, DefaultApprovalPolicy, DefaultRolesPolicy, type DetachedDelegationOutcome, type DetachedDelegationReceipt, DetachedDelivery, type DetailThreadRef, ElicitationRequest, type EmbeddingProvider, type EmitUi, type ForgetMemoryInput, type FrameBuffer, GLOBAL_SCOPE, type GovernancePage, type GovernancePageQuery, type GovernanceRange, type GovernanceRunDetail, type GovernanceThreadDetail, type GovernanceThreadDetailQuery, type GovernanceUsageInput, HistoryPolicy, HumanReply, type IncrementalGate, InputProcessor, type ListMemoriesInput, type ListSkillsInput, type ListStagedAttachmentsInput, LlmStepEnvelope, type LoadSkillInput, type MemoryAuthor, type MemoryConfig, type MemoryDigest, type MemoryDigestEntry, type MemoryFact, type MemoryForgetRequest, type MemoryOrigin, type MemoryProvider, type MemoryRecord, type MemoryVerdict, type MemoryWriteOutcome, type MemoryWriteRequest, MessageAttachment, MessageFeedback, MessageUsage, ModelAnswer, type ModelCatalog, type ModelCatalogEntry, type ModelCatalogProviderGroup, type ModelCatalogQuery, type ModelCatalogView, ModelMessage, type ModelPrice, type ModelPriceInput, type ModelProvider, type ModelSpendRow, type ModelTurnArgs, type ModelTurnResult, type ObservedTurnFrames, type OfferMemoriesInput, type OutputGateMode, type OutputGateResult, OutputProcessor, type OverriddenMemory, PageContext, type Passage, type PendingApprovalRow, ProcessedPrompt, ProcessorContext, PromptBuilder, PromptContributor, QuotaExceededError, QuotaState, type QuotaStore, REMEMBER_TOOL_DESCRIPTION, REMEMBER_TOOL_NAME, REQUESTER_APPROVER, type RecentRunRow, type RecordRunEndInput, type RecordRunStartInput, type RecordToolCallInput, type RecordUsageInput, type RememberToolInput, type RerankOptions, type Reranker, type ResolveAttachmentInput, type ResolveMemoryDigestInput, type ResolvedDelegation, type RetrieveOptions, type Retriever, type RolesPolicy, type RunAgentBreakdownRow, RunCancelledError, type RunErrorBreakdownRow, type RunMetrics, type RunToolCallRow, type RunTrendPoint, type RunWhere, SKILL_TOOL_DESCRIPTION, SKILL_TOOL_NAME, type ScopeContext, type ScopeResolver, type SearchMemoriesInput, type SettledTask, type SinkWriter, type Skill, type SkillAuthor, type SkillCatalogEntry, type SkillContext, type SkillLoadOutcome, type SkillOffer, type SkillProvider, type SkillSummary, type SkillToolInput, type SkillWriteRequest, type SkillWriteVerdict, type SkillsConfig, type StageAttachmentInput, type StagedAttachment, type StoreMemoryInput, StoredMessage, type StreamError, type StructuredOutcome, StructuredOutputError, THREAD_DETAIL_CONTENT_CHARS, type ThreadActivityRow, ThreadDetail, type ThreadMessageRow, type ThreadMeta, type ThreadSpendRow, ThreadSummary, type ThreadTurnPage, type ThreadTurnQuery, type ThreadTurnReader, type ThreadUsageRollup, type ThreadWhere, type TokenStreamSink, type ToolCallActivityRow, ToolCallApproval, type ToolCallApprovalColumns, type ToolCallApprovalState, ToolCallRequest, ToolCallStatus, type ToolCallWhere, ToolDefinition, ToolDisabledError, ToolForbiddenError, ToolHandler, ToolInputInvalidError, ToolKind, type ToolKindDeps, ToolNotFoundError, ToolRegistry, ToolResult, ToolSpec, type ToolStatRow, ToolStepEnvelope, ToolTransientRetrySetting, type TurnFrameSummary, type UiCollector, type UpdateThreadInput, type UpdateToolCallInput, UsagePurpose, type UsageTrendPoint, type WindowHistoryOptions, type WithMemoryToolInput, type WriteMemoryInput, actorScope, agentDiagnosticKey, agentFailureCode, bucketByActor, bucketByModel, bucketByThread, bucketUsageTrend, buildMemoryBlock, buildSkillsBlock, canActorUseTool, compositeSkillProvider, createFrameBuffer, createIncrementalGate, createUiCollector, dayBoundsUtc, defaultCanDecide, defaultScopeResolver, detachedDelivered, detachedStarted, detachedUnsettled, estimateCost, estimateMessageTokens, extractJson, filterToolsByAllowList, filterToolsByCanUse, filterToolsByEnabled, filterToolsByRole, findCatalogModel, gateFollowUps, gateTail, isControlFlowSignal, isReplayIntegrityError, isToolEnabled, loadSkill, mayDecideApproval, memoryForgetVerdict, memoryWriteVerdict, mergeUi, normalizeDelegation, observeTurnFrames, offerMemories, offerSkills, publishAgentDelegated, publishAgentMemoryResolved, publishAgentMemoryWritten, publishAgentMessage, publishAgentQuotaExceeded, publishAgentRetrieved, publishAgentRunFailed, publishAgentRunFinished, publishAgentRunStarted, publishAgentSkillsResolved, publishAgentToolCall, publishAgentToolRetry, releaseGatedFrames, rememberInputSchema, rememberToolDefinition, repairInstruction, resolveGateLookback, resolveMemoryDigest, resolveOutputGateMode, resolveSkillCatalog, rollupThreadUsage, runAgentLoop, runInputProcessors, runOutputProcessors, seedModelPrices, settleAll, settleUnsettledDelegation, skillInputSchema, skillToolDefinition, skillWriteVerdict, stampToolKinds, staticModelCatalog, staticSkillProvider, summarizeWithModel, tenantScope, toolCallApprovalFromRow, traceLlmTurn, traceToolExecution, truncateDetailContent, unwrapToolStepOutput, validateStructured, windowHistory, withAskTool, withMemoryTool, withSelectedModel, withSkillTool, withToolTimeout, withTurnFrames, wrapToolStepOutput, writeMemory };
3482
+ export { AGENT_ACTOR_DIRECTORY, AGENT_ACTOR_RESOLVER, AGENT_APPROVAL_PORT, AGENT_ATTACHMENT_STAGING, AGENT_DEPS_FACTORY, AGENT_DIAGNOSTIC_EVENTS, AGENT_DURABLE_RUNNER, AGENT_EMBEDDING_PROVIDER, AGENT_GOVERNANCE_QUERIES, AGENT_MEMORY, AGENT_MODEL, AGENT_MODEL_CATALOG, AGENT_OPTIONS, AGENT_PRICING_STORE, AGENT_PROMPT_CONTRIBUTORS, AGENT_QUOTA_PROVIDER, AGENT_QUOTA_STORE, AGENT_REGISTRY, AGENT_RETRIEVER, AGENT_ROLES_POLICY, AGENT_RUNNER, AGENT_SINK, AGENT_SKILLS, AGENT_SKILL_SOURCES, AGENT_SPAN_EVENTS, AGENT_STORE, AGENT_TOOL_REGISTRY, APPROVAL_EXPIRED_REASON, Actor, type ActorDirectory, type ActorResolver, type ActorSpendRow, type AgentApprovalPort, AgentDefinition, type AgentDelegated, AgentDelegation, type AgentDiagnosticEvent, type AgentDiagnosticKey, type AgentFollowUpsSpan, type AgentGovernanceQueries, AgentIntake, type AgentLlmTurnSpan, type AgentLoopDeps, type AgentLoopHooks, type AgentLoopResult, type AgentMemoryResolved, type AgentMemoryWritten, type AgentMessageEvent, type AgentPricingStore, type AgentQuotaExceeded, AgentRegistry, type AgentRetrievalSpan, type AgentRetrieved, type AgentRunFailed, type AgentRunFinished, AgentRunInput, type AgentRunStarted, type AgentRunner, type AgentSkillsResolved, type AgentSpanEvent, type AgentStore, AgentStreamError, AgentStreamEvent, type AgentStructuredOutputSpan, type AgentToolCallEvent, type AgentToolExecutionSpan, type AgentToolRetry, AgentUiComponent, AiToolCtx, type AppendMessageInput, type ApprovalDecisionRef, type ApprovalPolicy, type ApprovalRequirement, type ApprovalThreadRef, type ApprovalToolRef, type ApprovalWhere, type AttachmentRef, type AttachmentStagingStore, type BufferedModelTurnResult, type BuildMemoryBlockInput, type CostUsage, type CreateThreadInput, type CurrentModelPrice, DEFAULT_HISTORY_SUMMARY_INSTRUCTION, DEFAULT_MAX_FACT_CHARS, DEFAULT_MAX_MEMORIES, DEFAULT_MAX_SKILLS, DEFAULT_REFUSAL_REASON, DEFAULT_STRUCTURED_OUTPUT_INSTRUCTION, Decision, DefaultApprovalPolicy, DefaultRolesPolicy, type DetachedDelegationOutcome, type DetachedDelegationReceipt, DetachedDelivery, type DetailThreadRef, ElicitationRequest, type EmbeddingProvider, type EmitUi, type ForgetMemoryInput, type FrameBuffer, GLOBAL_SCOPE, type GovernancePage, type GovernancePageQuery, type GovernanceRange, type GovernanceRunDetail, type GovernanceThreadDetail, type GovernanceThreadDetailQuery, type GovernanceUsageInput, HistoryPolicy, HumanReply, type IncrementalGate, InputProcessor, type ListMemoriesInput, type ListSkillsInput, type ListStagedAttachmentsInput, LlmStepEnvelope, type LoadSkillInput, type MemoryAuthor, type MemoryConfig, type MemoryDigest, type MemoryDigestEntry, type MemoryFact, type MemoryForgetRequest, type MemoryOrigin, type MemoryProvider, type MemoryRecord, type MemoryVerdict, type MemoryWriteOutcome, type MemoryWriteRequest, MessageAttachment, MessageFeedback, MessageUsage, ModelAnswer, type ModelCatalog, type ModelCatalogEntry, type ModelCatalogProviderGroup, type ModelCatalogQuery, type ModelCatalogView, ModelMessage, type ModelPrice, type ModelPriceInput, type ModelProvider, type ModelSpendRow, type ModelTurnArgs, type ModelTurnResult, type ObservedTurnFrames, type OfferMemoriesInput, type OutputGateMode, type OutputGateResult, OutputProcessor, type OverriddenMemory, PageContext, type Passage, type PendingApprovalRow, ProcessedPrompt, ProcessorContext, PromptBuilder, PromptContributor, type QuotaBlock, QuotaExceededError, type QuotaPeriod, type QuotaProvider, type QuotaQuery, type QuotaReport, QuotaState, type QuotaStore, type QuotaWindow, REMEMBER_TOOL_DESCRIPTION, REMEMBER_TOOL_NAME, REQUESTER_APPROVER, type RecentRunRow, type RecordRunEndInput, type RecordRunStartInput, type RecordToolCallInput, type RecordUsageInput, type RememberToolInput, type RerankOptions, type Reranker, type ResolveAttachmentInput, type ResolveMemoryDigestInput, type ResolvedDelegation, type RetrieveOptions, type Retriever, type RolesPolicy, type RunAgentBreakdownRow, RunCancelledError, type RunErrorBreakdownRow, type RunMetrics, type RunToolCallRow, type RunTrendPoint, type RunWhere, SKILL_TOOL_DESCRIPTION, SKILL_TOOL_NAME, type ScopeContext, type ScopeResolver, type SearchMemoriesInput, type SettledTask, type SinkWriter, type Skill, type SkillAuthor, type SkillCatalogEntry, type SkillContext, type SkillLoadOutcome, type SkillOffer, type SkillProvider, type SkillSummary, type SkillToolInput, type SkillWriteRequest, type SkillWriteVerdict, type SkillsConfig, type StageAttachmentInput, type StagedAttachment, type StoreMemoryInput, StoredMessage, type StreamError, type StructuredOutcome, StructuredOutputError, THREAD_DETAIL_CONTENT_CHARS, type ThreadActivityRow, ThreadDetail, type ThreadMessageRow, type ThreadMeta, type ThreadSpendRow, ThreadSummary, type ThreadTurnPage, type ThreadTurnQuery, type ThreadTurnReader, type ThreadUsageRollup, type ThreadWhere, type TokenStreamSink, type ToolCallActivityRow, ToolCallApproval, type ToolCallApprovalColumns, type ToolCallApprovalState, ToolCallRequest, ToolCallStatus, type ToolCallWhere, ToolDefinition, ToolDescribeScope, ToolDisabledError, ToolForbiddenError, ToolHandler, ToolInputInvalidError, ToolKind, type ToolKindDeps, ToolNotFoundError, ToolRegistry, ToolResult, ToolSpec, type ToolStatRow, ToolStepEnvelope, ToolTransientRetrySetting, type TurnFrameSummary, type UiCollector, type UpdateThreadInput, type UpdateToolCallInput, UsagePurpose, type UsageTrendPoint, type WindowHistoryOptions, type WithMemoryToolInput, type WriteMemoryInput, actorScope, agentDiagnosticKey, agentFailureCode, bucketByActor, bucketByModel, bucketByThread, bucketUsageTrend, buildMemoryBlock, buildSkillsBlock, canActorUseTool, compositeSkillProvider, createFrameBuffer, createIncrementalGate, createNoopEmitUi, createUiCollector, dayBoundsUtc, defaultCanDecide, defaultScopeResolver, detachedDelivered, detachedStarted, detachedUnsettled, estimateCost, estimateMessageTokens, exhaustedWindow, extractJson, filterToolsByAllowList, filterToolsByCanUse, filterToolsByEnabled, filterToolsByRole, findCatalogModel, gateFollowUps, gateTail, isControlFlowSignal, isReplayIntegrityError, isToolEnabled, loadSkill, mayDecideApproval, memoryForgetVerdict, memoryWriteVerdict, mergeUi, normalizeDelegation, observeTurnFrames, offerMemories, offerSkills, publishAgentDelegated, publishAgentMemoryResolved, publishAgentMemoryWritten, publishAgentMessage, publishAgentQuotaExceeded, publishAgentRetrieved, publishAgentRunFailed, publishAgentRunFinished, publishAgentRunStarted, publishAgentSkillsResolved, publishAgentToolCall, publishAgentToolRetry, quotaPeriodRange, releaseGatedFrames, rememberInputSchema, rememberToolDefinition, repairInstruction, resolveGateLookback, resolveMemoryDigest, resolveOutputGateMode, resolveSkillCatalog, rollupThreadUsage, runAgentLoop, runInputProcessors, runOutputProcessors, seedModelPrices, settleAll, settleUnsettledDelegation, skillInputSchema, skillToolDefinition, skillWriteVerdict, stampToolKinds, staticModelCatalog, staticSkillProvider, summarizeWithModel, tenantScope, toolCallApprovalFromRow, traceLlmTurn, traceToolExecution, truncateDetailContent, unwrapToolStepOutput, validateStructured, windowHistory, withAskTool, withMemoryTool, withSelectedModel, withSkillTool, withToolTimeout, withTurnFrames, wrapToolStepOutput, writeMemory };
package/dist/index.d.ts CHANGED
@@ -1,6 +1,8 @@
1
- import { M as ModelMessage, a as ToolDefinition, b as ToolCallRequest, c as MessageUsage, d as AgentUiComponent, A as Actor, e as AiToolCtx, f as AgentStreamEvent, g as ThreadSummary, h as ThreadDetail, S as StoredMessage, i as ToolResult, j as MessageAttachment, k as MessageFeedback, l as ToolCallStatus, U as UsagePurpose, m as ToolSpec, Q as QuotaState, n as AgentRunInput, H as HumanReply, o as ToolKind, p as ToolCallApproval, T as ToolHandler, q as HistoryPolicy, O as OutputProcessor, P as ProcessorContext, I as InputProcessor, r as ProcessedPrompt, s as ModelAnswer, t as PageContext, u as AgentDefinition, v as AgentDelegation, D as DetachedDelivery, w as PromptBuilder, x as PromptContributor, y as ToolTransientRetrySetting, z as AgentIntake, B as Decision, E as ElicitationRequest, L as LlmStepEnvelope, C as ToolStepEnvelope } from './tool-fLRLs_f3.js';
2
- export { F as ASK_TOOL_DESCRIPTION, G as ASK_TOOL_NAME, J as AgentApprovalRequest, K as AgentApprovalSettlement, N as AgentCatalogEntry, R as AgentHistoryWindow, V as AskToolInput, W as DEFAULT_INCREMENTAL_LOOKBACK_CHARS, X as DEFAULT_INTAKE_PREAMBLE, Y as DEFAULT_TOOL_TRANSIENT_RETRY_ATTEMPTS, Z as DEFAULT_TOOL_TRANSIENT_RETRY_BACKOFF_MS, _ as ELICITATION_INPUT_TYPES, $ as ElicitationInput, a0 as ElicitationInputType, a1 as ElicitationOption, a2 as ElicitationOutcome, a3 as ElicitationQuestion, a4 as ElicitationReply, a5 as ElicitationResult, a6 as HistoryPolicyContext, a7 as HistorySelection, a8 as HistorySummary, a9 as IncrementalGating, aa as InvokeWithTransientRetryOptions, ab as MAX_ASK_QUESTIONS, ac as MessageFeedbackValue, ad as MessageRole, ae as OutputRejectedError, af as OutputVerdict, ag as ProcessorFailedError, ah as PromptContext, ai as QuotaView, aj as ToolCallApprovalStatus, ak as ToolCatalogEntry, al as ToolConfirmation, am as ToolPresentation, an as ToolPresentationTone, ao as ToolResultField, ap as ToolResultView, aq as ToolStepCtx, ar as ToolTransientRetryNumbers, as as ToolTransientRetryOptions, at as askInputSchema, au as askToolDefinition, av as decodeStreamEvent, aw as encodeStreamEvent, ax as invokeWithTransientRetry, ay as isTransientToolError, az as isTypedQuestion, aA as normalizeElicitationReply, aB as questionOptions, aC as readElicitationInput, aD as readElicitationQuestions, aE as renderElicitationAnswers, aF as resolveElicitation, aG as resolveToolTransientRetryNumbers, aH as settleElicitation, aI as validateElicitationAnswer, aJ as validateElicitationValue } from './tool-fLRLs_f3.js';
1
+ import { M as ModelMessage, c as ToolDefinition, d as ToolCallRequest, e as MessageUsage, f as AgentUiComponent, A as Actor, g as AiToolCtx, h as AgentStreamEvent, i as ThreadSummary, j as ThreadDetail, S as StoredMessage, k as ToolResult, l as MessageAttachment, m as MessageFeedback, n as ToolCallStatus, U as UsagePurpose, T as ToolSpec, Q as QuotaState, o as AgentRunInput, H as HumanReply, p as ToolKind, q as ToolCallApproval, a as ToolHandler, r as HistoryPolicy, P as PageContext, s as AgentDefinition, t as AgentDelegation, D as DetachedDelivery, u as ToolDescribeScope, v as PromptBuilder, w as PromptContributor, x as ToolTransientRetrySetting, y as AgentIntake, z as Decision, E as ElicitationRequest, L as LlmStepEnvelope, B as ToolStepEnvelope } from './tool-BXKG2xSm.js';
2
+ export { C as ASK_TOOL_DESCRIPTION, F as ASK_TOOL_NAME, G as AgentApprovalRequest, I as AgentApprovalSettlement, J as AgentCatalogEntry, K as AgentHistoryWindow, N as AskToolInput, O as DEFAULT_INTAKE_PREAMBLE, R as DEFAULT_TOOL_TRANSIENT_RETRY_ATTEMPTS, V as DEFAULT_TOOL_TRANSIENT_RETRY_BACKOFF_MS, W as ELICITATION_INPUT_TYPES, X as ElicitationInput, Y as ElicitationInputType, Z as ElicitationOption, _ as ElicitationOutcome, $ as ElicitationQuestion, a0 as ElicitationReply, a1 as ElicitationResult, a2 as HistoryPolicyContext, a3 as HistorySelection, a4 as HistorySummary, a5 as InvokeWithTransientRetryOptions, a6 as MAX_ASK_QUESTIONS, a7 as MessageFeedbackValue, a8 as MessageRole, a9 as PromptContext, aa as QuotaView, ab as ToolCallApprovalStatus, ac as ToolCatalogEntry, ad as ToolConfirmation, ae as ToolDescription, b as ToolPresentation, af as ToolPresentationTone, ag as ToolResultField, ah as ToolResultView, ai as ToolStepCtx, aj as ToolTransientRetryNumbers, ak as ToolTransientRetryOptions, al as askInputSchema, am as askToolDefinition, an as decodeStreamEvent, ao as encodeStreamEvent, ap as invokeWithTransientRetry, aq as isTransientToolError, ar as isTypedQuestion, as as normalizeElicitationReply, at as questionOptions, au as readElicitationInput, av as readElicitationQuestions, aw as renderElicitationAnswers, ax as resolveElicitation, ay as resolveToolTransientRetryNumbers, az as settleElicitation, aA as validateElicitationAnswer, aB as validateElicitationValue } from './tool-BXKG2xSm.js';
3
3
  import { StandardSchemaV1 } from '@standard-schema/spec';
4
+ import { O as OutputProcessor, P as ProcessorContext, I as InputProcessor, a as ProcessedPrompt, M as ModelAnswer } from './processors-CK1RWv0D.js';
5
+ export { D as DEFAULT_INCREMENTAL_LOOKBACK_CHARS, b as IncrementalGating, c as OutputRejectedError, d as OutputVerdict, e as ProcessorFailedError } from './processors-CK1RWv0D.js';
4
6
  import { ChannelRegistry } from '@dudousxd/nestjs-diagnostics';
5
7
 
6
8
  /**
@@ -32,6 +34,8 @@ declare const AGENT_REGISTRY: unique symbol;
32
34
  declare const AGENT_ACTOR_RESOLVER: unique symbol;
33
35
  /** The governance read-model (usage/spend/threads), consumed by the dashboard + telescope surfaces. */
34
36
  declare const AGENT_GOVERNANCE_QUERIES: unique symbol;
37
+ /** The `QuotaProvider` behind `GET <base>/quota` (and, when the host binds one, the send gate). */
38
+ declare const AGENT_QUOTA_PROVIDER: unique symbol;
35
39
  /** The `ModelCatalog` behind `GET <base>/models` and the model a send may name. Optional. */
36
40
  declare const AGENT_MODEL_CATALOG: unique symbol;
37
41
  /** The pricing WRITE side (`AgentPricingStore`) — seeds/updates the per-model rates cost is priced against. */
@@ -309,7 +313,13 @@ declare function unwrapToolStepOutput(raw: unknown): {
309
313
  output: unknown;
310
314
  ui: AgentUiComponent[];
311
315
  };
312
- type EmitUi = NonNullable<AiToolCtx['emitUi']>;
316
+ type EmitUi = AiToolCtx['emitUi'];
317
+ /**
318
+ * `ctx.emitUi` where there is no conversation to push into (the MCP server, a direct
319
+ * `registry.invoke`): nothing is streamed or persisted, but the call resolves to an id — the one it
320
+ * was given, else `<scope>:ui:<n>` — so a tool never has to test for the capability.
321
+ */
322
+ declare function createNoopEmitUi(scope?: string): EmitUi;
313
323
  /** Collects what one tool invocation pushes, streaming each push as it happens. */
314
324
  interface UiCollector {
315
325
  emit: EmitUi;
@@ -644,6 +654,15 @@ interface AgentStore {
644
654
  usedTokens: number;
645
655
  costUsd: number;
646
656
  }>;
657
+ /**
658
+ * OPTIONAL: the actor's spend over the UTC days `fromDay`..`toDay` (`YYYY-MM-DD`, inclusive) —
659
+ * {@link quotaToday} over a range. Feeds the monthly window of `GET <base>/quota`; absent → that
660
+ * window is left out.
661
+ */
662
+ usageBetween?(actorRef: string, fromDay: string, toDay: string): Promise<{
663
+ usedTokens: number;
664
+ costUsd: number;
665
+ }>;
647
666
  }
648
667
 
649
668
  /**
@@ -668,6 +687,57 @@ interface QuotaStore {
668
687
  bump(actorRef: string, day: string, tokens: number): Promise<void>;
669
688
  }
670
689
 
690
+ /** The span a quota window counts over, in UTC. */
691
+ type QuotaPeriod = 'day' | 'month';
692
+ /** One budget window: what was spent in it, and the ceiling when there is one. */
693
+ interface QuotaWindow {
694
+ period: QuotaPeriod;
695
+ usedTokens: number;
696
+ /** Absent → no token ceiling on this window. */
697
+ limitTokens?: number;
698
+ usedUsd: number;
699
+ /** Absent → no spend ceiling on this window. */
700
+ limitUsd?: number;
701
+ /** ISO-8601 instant the window starts over (next UTC midnight, first of next month). */
702
+ resetsAt?: string;
703
+ }
704
+ /** Which window stopped the actor, when one did. */
705
+ interface QuotaBlock {
706
+ period: QuotaPeriod;
707
+ /** Words a client can show ("Monthly AI budget reached"). */
708
+ reason?: string;
709
+ }
710
+ /** What `GET <base>/quota` answers. */
711
+ interface QuotaReport {
712
+ windows: QuotaWindow[];
713
+ /** Present when a window is exhausted — a send will be refused until it resets. */
714
+ blocked?: QuotaBlock;
715
+ }
716
+ interface QuotaQuery {
717
+ actor: Actor;
718
+ /** The instant to report for; defaults to now. */
719
+ now?: Date;
720
+ }
721
+ /**
722
+ * The actor's budget across windows — the read behind `GET <base>/quota` and, when the host binds
723
+ * one (`AgentModule.forRoot({ quotaProvider })`), the gate a send passes: a report with `blocked`
724
+ * refuses the turn with `429` before it starts.
725
+ *
726
+ * The default reads the usage ledger (`LedgerQuotaProvider` in `@dudousxd/nestjs-agent`); a host
727
+ * with its own budget (an AI-gateway spend cap, a plan's monthly allowance) implements this.
728
+ */
729
+ interface QuotaProvider {
730
+ report(query: QuotaQuery): Promise<QuotaReport>;
731
+ }
732
+ /** The first window whose token or spend ceiling is reached, as a {@link QuotaBlock}. */
733
+ declare function exhaustedWindow(windows: readonly QuotaWindow[]): QuotaBlock | undefined;
734
+ /** The UTC day range (`YYYY-MM-DD`, inclusive) and reset instant of `period` around `now`. */
735
+ declare function quotaPeriodRange(period: QuotaPeriod, now: Date): {
736
+ fromDay: string;
737
+ toDay: string;
738
+ resetsAt: string;
739
+ };
740
+
671
741
  /**
672
742
  * The WRITE side of the pricing table the {@link import('./governance-queries.js').AgentGovernanceQueries}
673
743
  * read-model prices usage against. Cost is $0 for an unpriced model, so an app seeds its models'
@@ -2688,13 +2758,14 @@ declare class ToolRegistry {
2688
2758
  * feature-flag store, an MCP server — and this runs once per model step. Asking those about a
2689
2759
  * tool the allow-list has already excluded is a call whose answer nothing reads.
2690
2760
  */
2691
- definitionsFor(actor: Actor, policy: RolesPolicy, allowedTools?: string[]): Promise<ToolDefinition[]>;
2761
+ definitionsFor(actor: Actor, policy: RolesPolicy, allowedTools?: string[], scope?: Omit<ToolDescribeScope, 'actor'>): Promise<ToolDefinition[]>;
2692
2762
  /**
2693
2763
  * The specs {@link definitionsFor} offers the model, whole — the same four gates (allow-list,
2694
2764
  * enabled, role, `canUse`) in the same order. For a surface that lists what an actor can reach
2695
2765
  * (`GET <base>/tools`), which must never disagree with what the model is actually shown.
2696
2766
  */
2697
2767
  visibleSpecs(actor: Actor, policy: RolesPolicy, allowedTools?: string[]): Promise<ToolSpec[]>;
2768
+ private visibleEntries;
2698
2769
  /**
2699
2770
  * Run a tool. Re-checks that the tool is enabled and that the role allows it (defense-in-depth —
2700
2771
  * a call can reach here from a replayed durable step or an approval granted before the flag
@@ -3408,4 +3479,4 @@ type AgentDiagnosticKey = `agent:${AgentDiagnosticEvent}`;
3408
3479
  */
3409
3480
  declare function agentDiagnosticKey(event: AgentDiagnosticEvent): AgentDiagnosticKey;
3410
3481
 
3411
- export { AGENT_ACTOR_DIRECTORY, AGENT_ACTOR_RESOLVER, AGENT_APPROVAL_PORT, AGENT_ATTACHMENT_STAGING, AGENT_DEPS_FACTORY, AGENT_DIAGNOSTIC_EVENTS, AGENT_DURABLE_RUNNER, AGENT_EMBEDDING_PROVIDER, AGENT_GOVERNANCE_QUERIES, AGENT_MEMORY, AGENT_MODEL, AGENT_MODEL_CATALOG, AGENT_OPTIONS, AGENT_PRICING_STORE, AGENT_PROMPT_CONTRIBUTORS, AGENT_QUOTA_STORE, AGENT_REGISTRY, AGENT_RETRIEVER, AGENT_ROLES_POLICY, AGENT_RUNNER, AGENT_SINK, AGENT_SKILLS, AGENT_SKILL_SOURCES, AGENT_SPAN_EVENTS, AGENT_STORE, AGENT_TOOL_REGISTRY, APPROVAL_EXPIRED_REASON, Actor, type ActorDirectory, type ActorResolver, type ActorSpendRow, type AgentApprovalPort, AgentDefinition, type AgentDelegated, AgentDelegation, type AgentDiagnosticEvent, type AgentDiagnosticKey, type AgentFollowUpsSpan, type AgentGovernanceQueries, AgentIntake, type AgentLlmTurnSpan, type AgentLoopDeps, type AgentLoopHooks, type AgentLoopResult, type AgentMemoryResolved, type AgentMemoryWritten, type AgentMessageEvent, type AgentPricingStore, type AgentQuotaExceeded, AgentRegistry, type AgentRetrievalSpan, type AgentRetrieved, type AgentRunFailed, type AgentRunFinished, AgentRunInput, type AgentRunStarted, type AgentRunner, type AgentSkillsResolved, type AgentSpanEvent, type AgentStore, AgentStreamError, AgentStreamEvent, type AgentStructuredOutputSpan, type AgentToolCallEvent, type AgentToolExecutionSpan, type AgentToolRetry, AgentUiComponent, AiToolCtx, type AppendMessageInput, type ApprovalDecisionRef, type ApprovalPolicy, type ApprovalRequirement, type ApprovalThreadRef, type ApprovalToolRef, type ApprovalWhere, type AttachmentRef, type AttachmentStagingStore, type BufferedModelTurnResult, type BuildMemoryBlockInput, type CostUsage, type CreateThreadInput, type CurrentModelPrice, DEFAULT_HISTORY_SUMMARY_INSTRUCTION, DEFAULT_MAX_FACT_CHARS, DEFAULT_MAX_MEMORIES, DEFAULT_MAX_SKILLS, DEFAULT_REFUSAL_REASON, DEFAULT_STRUCTURED_OUTPUT_INSTRUCTION, Decision, DefaultApprovalPolicy, DefaultRolesPolicy, type DetachedDelegationOutcome, type DetachedDelegationReceipt, DetachedDelivery, type DetailThreadRef, ElicitationRequest, type EmbeddingProvider, type EmitUi, type ForgetMemoryInput, type FrameBuffer, GLOBAL_SCOPE, type GovernancePage, type GovernancePageQuery, type GovernanceRange, type GovernanceRunDetail, type GovernanceThreadDetail, type GovernanceThreadDetailQuery, type GovernanceUsageInput, HistoryPolicy, HumanReply, type IncrementalGate, InputProcessor, type ListMemoriesInput, type ListSkillsInput, type ListStagedAttachmentsInput, LlmStepEnvelope, type LoadSkillInput, type MemoryAuthor, type MemoryConfig, type MemoryDigest, type MemoryDigestEntry, type MemoryFact, type MemoryForgetRequest, type MemoryOrigin, type MemoryProvider, type MemoryRecord, type MemoryVerdict, type MemoryWriteOutcome, type MemoryWriteRequest, MessageAttachment, MessageFeedback, MessageUsage, ModelAnswer, type ModelCatalog, type ModelCatalogEntry, type ModelCatalogProviderGroup, type ModelCatalogQuery, type ModelCatalogView, ModelMessage, type ModelPrice, type ModelPriceInput, type ModelProvider, type ModelSpendRow, type ModelTurnArgs, type ModelTurnResult, type ObservedTurnFrames, type OfferMemoriesInput, type OutputGateMode, type OutputGateResult, OutputProcessor, type OverriddenMemory, PageContext, type Passage, type PendingApprovalRow, ProcessedPrompt, ProcessorContext, PromptBuilder, PromptContributor, QuotaExceededError, QuotaState, type QuotaStore, REMEMBER_TOOL_DESCRIPTION, REMEMBER_TOOL_NAME, REQUESTER_APPROVER, type RecentRunRow, type RecordRunEndInput, type RecordRunStartInput, type RecordToolCallInput, type RecordUsageInput, type RememberToolInput, type RerankOptions, type Reranker, type ResolveAttachmentInput, type ResolveMemoryDigestInput, type ResolvedDelegation, type RetrieveOptions, type Retriever, type RolesPolicy, type RunAgentBreakdownRow, RunCancelledError, type RunErrorBreakdownRow, type RunMetrics, type RunToolCallRow, type RunTrendPoint, type RunWhere, SKILL_TOOL_DESCRIPTION, SKILL_TOOL_NAME, type ScopeContext, type ScopeResolver, type SearchMemoriesInput, type SettledTask, type SinkWriter, type Skill, type SkillAuthor, type SkillCatalogEntry, type SkillContext, type SkillLoadOutcome, type SkillOffer, type SkillProvider, type SkillSummary, type SkillToolInput, type SkillWriteRequest, type SkillWriteVerdict, type SkillsConfig, type StageAttachmentInput, type StagedAttachment, type StoreMemoryInput, StoredMessage, type StreamError, type StructuredOutcome, StructuredOutputError, THREAD_DETAIL_CONTENT_CHARS, type ThreadActivityRow, ThreadDetail, type ThreadMessageRow, type ThreadMeta, type ThreadSpendRow, ThreadSummary, type ThreadTurnPage, type ThreadTurnQuery, type ThreadTurnReader, type ThreadUsageRollup, type ThreadWhere, type TokenStreamSink, type ToolCallActivityRow, ToolCallApproval, type ToolCallApprovalColumns, type ToolCallApprovalState, ToolCallRequest, ToolCallStatus, type ToolCallWhere, ToolDefinition, ToolDisabledError, ToolForbiddenError, ToolHandler, ToolInputInvalidError, ToolKind, type ToolKindDeps, ToolNotFoundError, ToolRegistry, ToolResult, ToolSpec, type ToolStatRow, ToolStepEnvelope, ToolTransientRetrySetting, type TurnFrameSummary, type UiCollector, type UpdateThreadInput, type UpdateToolCallInput, UsagePurpose, type UsageTrendPoint, type WindowHistoryOptions, type WithMemoryToolInput, type WriteMemoryInput, actorScope, agentDiagnosticKey, agentFailureCode, bucketByActor, bucketByModel, bucketByThread, bucketUsageTrend, buildMemoryBlock, buildSkillsBlock, canActorUseTool, compositeSkillProvider, createFrameBuffer, createIncrementalGate, createUiCollector, dayBoundsUtc, defaultCanDecide, defaultScopeResolver, detachedDelivered, detachedStarted, detachedUnsettled, estimateCost, estimateMessageTokens, extractJson, filterToolsByAllowList, filterToolsByCanUse, filterToolsByEnabled, filterToolsByRole, findCatalogModel, gateFollowUps, gateTail, isControlFlowSignal, isReplayIntegrityError, isToolEnabled, loadSkill, mayDecideApproval, memoryForgetVerdict, memoryWriteVerdict, mergeUi, normalizeDelegation, observeTurnFrames, offerMemories, offerSkills, publishAgentDelegated, publishAgentMemoryResolved, publishAgentMemoryWritten, publishAgentMessage, publishAgentQuotaExceeded, publishAgentRetrieved, publishAgentRunFailed, publishAgentRunFinished, publishAgentRunStarted, publishAgentSkillsResolved, publishAgentToolCall, publishAgentToolRetry, releaseGatedFrames, rememberInputSchema, rememberToolDefinition, repairInstruction, resolveGateLookback, resolveMemoryDigest, resolveOutputGateMode, resolveSkillCatalog, rollupThreadUsage, runAgentLoop, runInputProcessors, runOutputProcessors, seedModelPrices, settleAll, settleUnsettledDelegation, skillInputSchema, skillToolDefinition, skillWriteVerdict, stampToolKinds, staticModelCatalog, staticSkillProvider, summarizeWithModel, tenantScope, toolCallApprovalFromRow, traceLlmTurn, traceToolExecution, truncateDetailContent, unwrapToolStepOutput, validateStructured, windowHistory, withAskTool, withMemoryTool, withSelectedModel, withSkillTool, withToolTimeout, withTurnFrames, wrapToolStepOutput, writeMemory };
3482
+ export { AGENT_ACTOR_DIRECTORY, AGENT_ACTOR_RESOLVER, AGENT_APPROVAL_PORT, AGENT_ATTACHMENT_STAGING, AGENT_DEPS_FACTORY, AGENT_DIAGNOSTIC_EVENTS, AGENT_DURABLE_RUNNER, AGENT_EMBEDDING_PROVIDER, AGENT_GOVERNANCE_QUERIES, AGENT_MEMORY, AGENT_MODEL, AGENT_MODEL_CATALOG, AGENT_OPTIONS, AGENT_PRICING_STORE, AGENT_PROMPT_CONTRIBUTORS, AGENT_QUOTA_PROVIDER, AGENT_QUOTA_STORE, AGENT_REGISTRY, AGENT_RETRIEVER, AGENT_ROLES_POLICY, AGENT_RUNNER, AGENT_SINK, AGENT_SKILLS, AGENT_SKILL_SOURCES, AGENT_SPAN_EVENTS, AGENT_STORE, AGENT_TOOL_REGISTRY, APPROVAL_EXPIRED_REASON, Actor, type ActorDirectory, type ActorResolver, type ActorSpendRow, type AgentApprovalPort, AgentDefinition, type AgentDelegated, AgentDelegation, type AgentDiagnosticEvent, type AgentDiagnosticKey, type AgentFollowUpsSpan, type AgentGovernanceQueries, AgentIntake, type AgentLlmTurnSpan, type AgentLoopDeps, type AgentLoopHooks, type AgentLoopResult, type AgentMemoryResolved, type AgentMemoryWritten, type AgentMessageEvent, type AgentPricingStore, type AgentQuotaExceeded, AgentRegistry, type AgentRetrievalSpan, type AgentRetrieved, type AgentRunFailed, type AgentRunFinished, AgentRunInput, type AgentRunStarted, type AgentRunner, type AgentSkillsResolved, type AgentSpanEvent, type AgentStore, AgentStreamError, AgentStreamEvent, type AgentStructuredOutputSpan, type AgentToolCallEvent, type AgentToolExecutionSpan, type AgentToolRetry, AgentUiComponent, AiToolCtx, type AppendMessageInput, type ApprovalDecisionRef, type ApprovalPolicy, type ApprovalRequirement, type ApprovalThreadRef, type ApprovalToolRef, type ApprovalWhere, type AttachmentRef, type AttachmentStagingStore, type BufferedModelTurnResult, type BuildMemoryBlockInput, type CostUsage, type CreateThreadInput, type CurrentModelPrice, DEFAULT_HISTORY_SUMMARY_INSTRUCTION, DEFAULT_MAX_FACT_CHARS, DEFAULT_MAX_MEMORIES, DEFAULT_MAX_SKILLS, DEFAULT_REFUSAL_REASON, DEFAULT_STRUCTURED_OUTPUT_INSTRUCTION, Decision, DefaultApprovalPolicy, DefaultRolesPolicy, type DetachedDelegationOutcome, type DetachedDelegationReceipt, DetachedDelivery, type DetailThreadRef, ElicitationRequest, type EmbeddingProvider, type EmitUi, type ForgetMemoryInput, type FrameBuffer, GLOBAL_SCOPE, type GovernancePage, type GovernancePageQuery, type GovernanceRange, type GovernanceRunDetail, type GovernanceThreadDetail, type GovernanceThreadDetailQuery, type GovernanceUsageInput, HistoryPolicy, HumanReply, type IncrementalGate, InputProcessor, type ListMemoriesInput, type ListSkillsInput, type ListStagedAttachmentsInput, LlmStepEnvelope, type LoadSkillInput, type MemoryAuthor, type MemoryConfig, type MemoryDigest, type MemoryDigestEntry, type MemoryFact, type MemoryForgetRequest, type MemoryOrigin, type MemoryProvider, type MemoryRecord, type MemoryVerdict, type MemoryWriteOutcome, type MemoryWriteRequest, MessageAttachment, MessageFeedback, MessageUsage, ModelAnswer, type ModelCatalog, type ModelCatalogEntry, type ModelCatalogProviderGroup, type ModelCatalogQuery, type ModelCatalogView, ModelMessage, type ModelPrice, type ModelPriceInput, type ModelProvider, type ModelSpendRow, type ModelTurnArgs, type ModelTurnResult, type ObservedTurnFrames, type OfferMemoriesInput, type OutputGateMode, type OutputGateResult, OutputProcessor, type OverriddenMemory, PageContext, type Passage, type PendingApprovalRow, ProcessedPrompt, ProcessorContext, PromptBuilder, PromptContributor, type QuotaBlock, QuotaExceededError, type QuotaPeriod, type QuotaProvider, type QuotaQuery, type QuotaReport, QuotaState, type QuotaStore, type QuotaWindow, REMEMBER_TOOL_DESCRIPTION, REMEMBER_TOOL_NAME, REQUESTER_APPROVER, type RecentRunRow, type RecordRunEndInput, type RecordRunStartInput, type RecordToolCallInput, type RecordUsageInput, type RememberToolInput, type RerankOptions, type Reranker, type ResolveAttachmentInput, type ResolveMemoryDigestInput, type ResolvedDelegation, type RetrieveOptions, type Retriever, type RolesPolicy, type RunAgentBreakdownRow, RunCancelledError, type RunErrorBreakdownRow, type RunMetrics, type RunToolCallRow, type RunTrendPoint, type RunWhere, SKILL_TOOL_DESCRIPTION, SKILL_TOOL_NAME, type ScopeContext, type ScopeResolver, type SearchMemoriesInput, type SettledTask, type SinkWriter, type Skill, type SkillAuthor, type SkillCatalogEntry, type SkillContext, type SkillLoadOutcome, type SkillOffer, type SkillProvider, type SkillSummary, type SkillToolInput, type SkillWriteRequest, type SkillWriteVerdict, type SkillsConfig, type StageAttachmentInput, type StagedAttachment, type StoreMemoryInput, StoredMessage, type StreamError, type StructuredOutcome, StructuredOutputError, THREAD_DETAIL_CONTENT_CHARS, type ThreadActivityRow, ThreadDetail, type ThreadMessageRow, type ThreadMeta, type ThreadSpendRow, ThreadSummary, type ThreadTurnPage, type ThreadTurnQuery, type ThreadTurnReader, type ThreadUsageRollup, type ThreadWhere, type TokenStreamSink, type ToolCallActivityRow, ToolCallApproval, type ToolCallApprovalColumns, type ToolCallApprovalState, ToolCallRequest, ToolCallStatus, type ToolCallWhere, ToolDefinition, ToolDescribeScope, ToolDisabledError, ToolForbiddenError, ToolHandler, ToolInputInvalidError, ToolKind, type ToolKindDeps, ToolNotFoundError, ToolRegistry, ToolResult, ToolSpec, type ToolStatRow, ToolStepEnvelope, ToolTransientRetrySetting, type TurnFrameSummary, type UiCollector, type UpdateThreadInput, type UpdateToolCallInput, UsagePurpose, type UsageTrendPoint, type WindowHistoryOptions, type WithMemoryToolInput, type WriteMemoryInput, actorScope, agentDiagnosticKey, agentFailureCode, bucketByActor, bucketByModel, bucketByThread, bucketUsageTrend, buildMemoryBlock, buildSkillsBlock, canActorUseTool, compositeSkillProvider, createFrameBuffer, createIncrementalGate, createNoopEmitUi, createUiCollector, dayBoundsUtc, defaultCanDecide, defaultScopeResolver, detachedDelivered, detachedStarted, detachedUnsettled, estimateCost, estimateMessageTokens, exhaustedWindow, extractJson, filterToolsByAllowList, filterToolsByCanUse, filterToolsByEnabled, filterToolsByRole, findCatalogModel, gateFollowUps, gateTail, isControlFlowSignal, isReplayIntegrityError, isToolEnabled, loadSkill, mayDecideApproval, memoryForgetVerdict, memoryWriteVerdict, mergeUi, normalizeDelegation, observeTurnFrames, offerMemories, offerSkills, publishAgentDelegated, publishAgentMemoryResolved, publishAgentMemoryWritten, publishAgentMessage, publishAgentQuotaExceeded, publishAgentRetrieved, publishAgentRunFailed, publishAgentRunFinished, publishAgentRunStarted, publishAgentSkillsResolved, publishAgentToolCall, publishAgentToolRetry, quotaPeriodRange, releaseGatedFrames, rememberInputSchema, rememberToolDefinition, repairInstruction, resolveGateLookback, resolveMemoryDigest, resolveOutputGateMode, resolveSkillCatalog, rollupThreadUsage, runAgentLoop, runInputProcessors, runOutputProcessors, seedModelPrices, settleAll, settleUnsettledDelegation, skillInputSchema, skillToolDefinition, skillWriteVerdict, stampToolKinds, staticModelCatalog, staticSkillProvider, summarizeWithModel, tenantScope, toolCallApprovalFromRow, traceLlmTurn, traceToolExecution, truncateDetailContent, unwrapToolStepOutput, validateStructured, windowHistory, withAskTool, withMemoryTool, withSelectedModel, withSkillTool, withToolTimeout, withTurnFrames, wrapToolStepOutput, writeMemory };
package/dist/index.js CHANGED
@@ -14,6 +14,7 @@ var AGENT_TOOL_REGISTRY = /* @__PURE__ */ Symbol.for("@dudousxd/nestjs-agent:too
14
14
  var AGENT_REGISTRY = /* @__PURE__ */ Symbol.for("@dudousxd/nestjs-agent:agent-registry");
15
15
  var AGENT_ACTOR_RESOLVER = /* @__PURE__ */ Symbol.for("@dudousxd/nestjs-agent:actor-resolver");
16
16
  var AGENT_GOVERNANCE_QUERIES = /* @__PURE__ */ Symbol.for("@dudousxd/nestjs-agent:governance-queries");
17
+ var AGENT_QUOTA_PROVIDER = /* @__PURE__ */ Symbol.for("@dudousxd/nestjs-agent:quota-provider");
17
18
  var AGENT_MODEL_CATALOG = /* @__PURE__ */ Symbol.for("@dudousxd/nestjs-agent:model-catalog");
18
19
  var AGENT_PRICING_STORE = /* @__PURE__ */ Symbol.for("@dudousxd/nestjs-agent:pricing-store");
19
20
  var AGENT_RETRIEVER = /* @__PURE__ */ Symbol.for("@dudousxd/nestjs-agent:retriever");
@@ -213,6 +214,22 @@ function unwrapToolStepOutput(raw) {
213
214
  };
214
215
  }
215
216
  __name(unwrapToolStepOutput, "unwrapToolStepOutput");
217
+ function createNoopEmitUi(scope = "noop") {
218
+ let next = 0;
219
+ return async (_component, _props, options = {}) => {
220
+ if (options.id !== void 0) {
221
+ return {
222
+ id: options.id
223
+ };
224
+ }
225
+ const id = `${scope}:ui:${next}`;
226
+ next += 1;
227
+ return {
228
+ id
229
+ };
230
+ };
231
+ }
232
+ __name(createNoopEmitUi, "createNoopEmitUi");
216
233
  function createUiCollector(toolCallId, write) {
217
234
  const pushed = /* @__PURE__ */ new Map();
218
235
  let next = 0;
@@ -272,6 +289,43 @@ function mergeUi(...lists) {
272
289
  }
273
290
  __name(mergeUi, "mergeUi");
274
291
 
292
+ // src/spi/quota-provider.ts
293
+ function exhaustedWindow(windows) {
294
+ for (const window of windows) {
295
+ const tokensOut = window.limitTokens !== void 0 && window.usedTokens >= window.limitTokens;
296
+ const spendOut = window.limitUsd !== void 0 && window.usedUsd >= window.limitUsd;
297
+ if (tokensOut || spendOut) {
298
+ return {
299
+ period: window.period,
300
+ reason: `${window.period === "day" ? "Daily" : "Monthly"} ${spendOut ? "spend" : "token"} limit reached`
301
+ };
302
+ }
303
+ }
304
+ return void 0;
305
+ }
306
+ __name(exhaustedWindow, "exhaustedWindow");
307
+ function quotaPeriodRange(period, now) {
308
+ const year = now.getUTCFullYear();
309
+ const month = now.getUTCMonth();
310
+ const day = now.toISOString().slice(0, 10);
311
+ if (period === "day") {
312
+ const next = new Date(Date.UTC(year, month, now.getUTCDate() + 1));
313
+ return {
314
+ fromDay: day,
315
+ toDay: day,
316
+ resetsAt: next.toISOString()
317
+ };
318
+ }
319
+ const first = new Date(Date.UTC(year, month, 1));
320
+ const last = new Date(Date.UTC(year, month + 1, 0));
321
+ return {
322
+ fromDay: first.toISOString().slice(0, 10),
323
+ toDay: last.toISOString().slice(0, 10),
324
+ resetsAt: new Date(Date.UTC(year, month + 1, 1)).toISOString()
325
+ };
326
+ }
327
+ __name(quotaPeriodRange, "quotaPeriodRange");
328
+
275
329
  // src/spi/pricing-store.ts
276
330
  async function seedModelPrices(store, prices) {
277
331
  for (const price of prices) {
@@ -2360,12 +2414,19 @@ var ToolRegistry = class {
2360
2414
  * feature-flag store, an MCP server — and this runs once per model step. Asking those about a
2361
2415
  * tool the allow-list has already excluded is a call whose answer nothing reads.
2362
2416
  */
2363
- async definitionsFor(actor, policy, allowedTools) {
2364
- return (await this.visibleSpecs(actor, policy, allowedTools)).map((spec) => ({
2365
- name: spec.name,
2366
- kind: spec.kind,
2367
- description: spec.description,
2368
- inputSchema: spec.inputSchema
2417
+ async definitionsFor(actor, policy, allowedTools, scope = {}) {
2418
+ const visible = await this.visibleEntries(actor, policy, allowedTools);
2419
+ return Promise.all(visible.map(async ({ spec, handler }) => {
2420
+ const override = handler.describe === void 0 ? void 0 : await handler.describe({
2421
+ actor,
2422
+ ...scope
2423
+ });
2424
+ return {
2425
+ name: spec.name,
2426
+ kind: spec.kind,
2427
+ description: override?.description ?? spec.description,
2428
+ inputSchema: override?.inputSchema ?? spec.inputSchema
2429
+ };
2369
2430
  }));
2370
2431
  }
2371
2432
  /**
@@ -2374,6 +2435,9 @@ var ToolRegistry = class {
2374
2435
  * (`GET <base>/tools`), which must never disagree with what the model is actually shown.
2375
2436
  */
2376
2437
  async visibleSpecs(actor, policy, allowedTools) {
2438
+ return (await this.visibleEntries(actor, policy, allowedTools)).map(({ spec }) => spec);
2439
+ }
2440
+ async visibleEntries(actor, policy, allowedTools) {
2377
2441
  const pinnedNames = new Set(filterToolsByAllowList(this.allSpecs(), allowedTools).map((spec) => spec.name));
2378
2442
  const pinned = [
2379
2443
  ...this.entries.values()
@@ -2381,8 +2445,7 @@ var ToolRegistry = class {
2381
2445
  const live = await filterToolsByEnabled(pinned);
2382
2446
  const allowedByRole = new Set((await filterToolsByRole(live.map((entry) => entry.spec), actor, policy)).map((spec) => spec.name));
2383
2447
  const roleScoped = live.filter((entry) => allowedByRole.has(entry.spec.name));
2384
- const actorScoped = await filterToolsByCanUse(roleScoped, actor);
2385
- return actorScoped.map(({ spec }) => spec);
2448
+ return filterToolsByCanUse(roleScoped, actor);
2386
2449
  }
2387
2450
  /**
2388
2451
  * Run a tool. Re-checks that the tool is enabled and that the role allows it (defense-in-depth —
@@ -2407,7 +2470,11 @@ var ToolRegistry = class {
2407
2470
  if (validation.issues !== void 0) {
2408
2471
  throw new ToolInputInvalidError(name, validation.issues);
2409
2472
  }
2410
- return entry.handler.execute(validation.value, ctx);
2473
+ const withEmit = typeof ctx.emitUi === "function" ? ctx : {
2474
+ ...ctx,
2475
+ emitUi: createNoopEmitUi(ctx.requestId)
2476
+ };
2477
+ return entry.handler.execute(validation.value, withEmit);
2411
2478
  }
2412
2479
  };
2413
2480
  var DefaultRolesPolicy = class {
@@ -3097,7 +3164,10 @@ function toolContext(deps, input, hooks) {
3097
3164
  } : {},
3098
3165
  ...deps.host !== void 0 ? {
3099
3166
  host: deps.host
3100
- } : {}
3167
+ } : {},
3168
+ // Replaced per tool call by the call's own collector (see the tool step); this one only serves
3169
+ // what runs outside a call — the elicitation wait.
3170
+ emitUi: createNoopEmitUi(hooks.runId)
3101
3171
  };
3102
3172
  }
3103
3173
  __name(toolContext, "toolContext");
@@ -4148,6 +4218,7 @@ ${block}`;
4148
4218
  system: prompt.system,
4149
4219
  messages: prompt.messages,
4150
4220
  actor: input.actor,
4221
+ threadId: input.threadId,
4151
4222
  ...gated ? {
4152
4223
  bufferOutput: true
4153
4224
  } : {},
@@ -4159,7 +4230,12 @@ ${block}`;
4159
4230
  const tools = withMemoryTool({
4160
4231
  tools: withSkillTool({
4161
4232
  tools: withAskTool({
4162
- tools: await deps.registry.definitionsFor(input.actor, deps.rolesPolicy, deps.toolAllowList),
4233
+ tools: await deps.registry.definitionsFor(input.actor, deps.rolesPolicy, deps.toolAllowList, {
4234
+ threadId: input.threadId,
4235
+ ...input.agentName !== void 0 ? {
4236
+ agentName: input.agentName
4237
+ } : {}
4238
+ }),
4163
4239
  ask: deps.ask
4164
4240
  }),
4165
4241
  enabled: deps.skills !== void 0
@@ -4575,6 +4651,7 @@ export {
4575
4651
  AGENT_OPTIONS,
4576
4652
  AGENT_PRICING_STORE,
4577
4653
  AGENT_PROMPT_CONTRIBUTORS,
4654
+ AGENT_QUOTA_PROVIDER,
4578
4655
  AGENT_QUOTA_STORE,
4579
4656
  AGENT_REGISTRY,
4580
4657
  AGENT_RETRIEVER,
@@ -4637,6 +4714,7 @@ export {
4637
4714
  compositeSkillProvider,
4638
4715
  createFrameBuffer,
4639
4716
  createIncrementalGate,
4717
+ createNoopEmitUi,
4640
4718
  createUiCollector,
4641
4719
  dayBoundsUtc,
4642
4720
  decodeStreamEvent,
@@ -4648,6 +4726,7 @@ export {
4648
4726
  encodeStreamEvent,
4649
4727
  estimateCost,
4650
4728
  estimateMessageTokens,
4729
+ exhaustedWindow,
4651
4730
  extractJson,
4652
4731
  filterToolsByAllowList,
4653
4732
  filterToolsByCanUse,
@@ -4685,6 +4764,7 @@ export {
4685
4764
  publishAgentToolCall,
4686
4765
  publishAgentToolRetry,
4687
4766
  questionOptions,
4767
+ quotaPeriodRange,
4688
4768
  readElicitationInput,
4689
4769
  readElicitationQuestions,
4690
4770
  releaseGatedFrames,