@dudousxd/nestjs-agent-core 0.36.0 → 0.38.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.ts CHANGED
@@ -82,6 +82,12 @@ declare const AGENT_MEMORY: unique symbol;
82
82
  * lazily by the bound {@link AGENT_SKILLS} provider — discovery runs after DI has built it.
83
83
  */
84
84
  declare const AGENT_SKILL_SOURCES: unique symbol;
85
+ /**
86
+ * The `ConfirmTokenStore` that makes a `defineConfirmedTool` confirmation single use. Bound by the
87
+ * store modules (`DrizzleAgentStoreModule`, `MikroOrmAgentStoreModule`); inject it into the factory
88
+ * that builds the tool (`provideAgentTool(factory, [AGENT_CONFIRM_TOKEN_STORE])`).
89
+ */
90
+ declare const AGENT_CONFIRM_TOKEN_STORE: unique symbol;
85
91
 
86
92
  /**
87
93
  * The "data plane": live token transport, decoupled from the durable control plane.
@@ -101,6 +107,13 @@ interface SinkWriter {
101
107
  * — so the transport can surface a typed failure frame instead of leaking it as assistant text.
102
108
  */
103
109
  fail(error: StreamError): void | Promise<void>;
110
+ /**
111
+ * OPTIONAL: write out anything this writer is still holding back, without ending the stream. Only
112
+ * a sink that gathers frames before writing them (the SQL sink coalesces text) has anything to do
113
+ * here; a delegated run's child writer calls it where it would have ended the stream, so nothing
114
+ * of the delegate's is still held back when its parent — possibly on another replica — writes next.
115
+ */
116
+ flush?(): void | Promise<void>;
104
117
  }
105
118
  /** A machine-readable stream failure. `code` is a stable slug; `message` is human-facing. */
106
119
  interface StreamError {
@@ -3562,4 +3575,385 @@ declare class InMemoryAgentStore implements AgentStore, ChatQueueStore {
3562
3575
  private toSummary;
3563
3576
  }
3564
3577
 
3565
- 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 AgentRunStartOptions, type AgentRunStarted, type AgentRunner, type AgentSkillsResolved, type AgentSpanEvent, AgentStore, AgentStreamError, AgentStreamEvent, type AgentStructuredOutputSpan, type AgentToolCallEvent, type AgentToolExecutionSpan, type AgentToolRetry, AgentUiComponent, AiToolCtx, AppendMessageInput, type ApprovalDecisionRef, type ApprovalPolicy, type ApprovalRequirement, type ApprovalThreadRef, type ApprovalToolRef, type ApprovalWhere, type AttachmentRef, type AttachmentStagingDescription, type AttachmentStagingStore, type BufferedModelTurnResult, type BuildMemoryBlockInput, ChatQueueStore, ClosedRolesPolicy, type CostUsage, 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 EmptyRoles, EnqueueMessageInput, type ForgetMemoryInput, type FrameBuffer, GLOBAL_SCOPE, type GovernanceMessageRow, type GovernancePage, type GovernancePageQuery, type GovernancePendingApprovalRow, type GovernanceRange, type GovernanceRunDetail, type GovernanceRunRow, type GovernanceThreadDetail, type GovernanceThreadDetailQuery, type GovernanceThreadRow, type GovernanceToolCallRow, type GovernanceUsageInput, type GovernanceUsageRow, HistoryPolicy, HumanReply, InMemoryAgentStore, 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 ModelCatalogLock, 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, QueuePause, QueuedMessage, QueuedMessagePatch, type QuotaBlock, QuotaExceededError, type QuotaPeriod, type QuotaProvider, type QuotaQuery, type QuotaReport, QuotaState, type QuotaStore, type QuotaWarning, type QuotaWindow, REMEMBER_TOOL_DESCRIPTION, REMEMBER_TOOL_NAME, REQUESTER_APPROVER, RUN_FAILED_MESSAGE, RUN_NOT_ACTIVE_CODE, RUN_NOT_ACTIVE_MESSAGE, RUN_NO_LONGER_RUNNING, type RecentRunRow, RecordRunStartInput, RecordToolCallInput, RecordUsageInput, type RememberToolInput, type RerankOptions, type Reranker, type ResolveAttachmentInput, type ResolveMemoryDigestInput, type ResolvedDelegation, type RetrieveOptions, type Retriever, type RolesPolicy, type RolesPolicyOptions, 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 SettleDeadRunInput, 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 ThreadUsageRollup, type ThreadWhere, type TokenStreamSink, type ToolCallActivityRow, ToolCallApproval, type ToolCallApprovalColumns, ToolCallApprovalState, ToolCallOutcome, 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, UpdateThreadInput, UpdateToolCallInput, type UsageTrendPoint, type WindowHistoryOptions, type WithMemoryToolInput, type WriteMemoryInput, actorScope, agentDiagnosticKey, agentFailureCode, bucketByActor, bucketByModel, bucketByThread, bucketUsageTrend, buildMemoryBlock, buildSkillsBlock, canActorUseTool, closeEmptyRoles, compositeSkillProvider, createFrameBuffer, createIncrementalGate, createNoopEmitUi, createUiCollector, dayBoundsUtc, defaultCanDecide, defaultScopeResolver, detachedDelivered, detachedStarted, detachedUnsettled, estimateCost, estimateMessageTokens, exhaustedWindow, exposeStreamErrorDetails, 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, quotaUsedRatio, quotaWarning, releaseGatedFrames, rememberInputSchema, rememberToolDefinition, repairInstruction, resolveGateLookback, resolveMemoryDigest, resolveOutputGateMode, resolveSkillCatalog, rollupThreadUsage, runAgentLoop, runInputProcessors, runOutputProcessors, seedModelPrices, settleAll, settleDeadRun, settleUnsettledDelegation, skillInputSchema, skillToolDefinition, skillWriteVerdict, stampToolKinds, staticModelCatalog, staticSkillProvider, streamFailure, summarizeWithModel, tenantScope, toolCallApprovalFromRow, toolCallContext, traceLlmTurn, traceToolExecution, truncateDetailContent, unwrapToolStepOutput, validateStructured, windowHistory, withAskTool, withMemoryTool, withSelectedModel, withSkillTool, withToolTimeout, withTurnFrames, wrapToolStepOutput, writeMemory };
3578
+ /** One confirmation being spent — what {@link ConfirmTokenStore.claim} records. */
3579
+ interface ConfirmTokenClaim {
3580
+ /** SHA-256 (hex) of the token. The token itself is never stored. */
3581
+ hash: string;
3582
+ /** `ctx.actor.id` of the confirming actor. */
3583
+ actorRef: string;
3584
+ /** The tool the token was issued for. */
3585
+ tool: string;
3586
+ /** Epoch-ms the token stops being valid — after it the mark is dead weight and can be purged. */
3587
+ expiresAt: number;
3588
+ }
3589
+ /**
3590
+ * Makes a confirm token single use (see `defineConfirmedTool`). A signed token is stateless, so on
3591
+ * its own it stays valid until it expires: a double tap, a network retry or a model repeating the
3592
+ * call would commit twice inside that window. The store remembers which tokens were spent.
3593
+ *
3594
+ * Only the token's hash, the actor and the tool name are kept — never an argument or a value.
3595
+ */
3596
+ interface ConfirmTokenStore {
3597
+ /**
3598
+ * Spend the token. `true` = this caller holds it and may commit; `false` = it was already spent.
3599
+ * MUST be atomic: of two concurrent claims for one hash, exactly one gets `true`.
3600
+ */
3601
+ claim(input: ConfirmTokenClaim): Promise<boolean>;
3602
+ /** Give the token back — the commit failed after the claim, so the caller may try again. */
3603
+ release(hash: string): Promise<void>;
3604
+ /** Drop the marks of tokens that expired before `now` (epoch-ms, default the clock). Returns how many. */
3605
+ purgeExpired?(now?: number): Promise<number>;
3606
+ }
3607
+
3608
+ /** How long a preview stays confirmable unless the tool says otherwise. */
3609
+ declare const DEFAULT_CONFIRM_TTL_MS: number;
3610
+ /** What a confirm token is bound to. Change any of it and the token stops matching. */
3611
+ interface ConfirmTokenSubject {
3612
+ /** The tool's name. */
3613
+ tool: string;
3614
+ /** `ctx.actor.id`. */
3615
+ actorId: string;
3616
+ /** `ctx.actor.tenantRef`; absent and `''` sign the same. */
3617
+ tenantRef?: string;
3618
+ /** The call's arguments, WITHOUT `confirm` / `confirmToken`. */
3619
+ args: unknown;
3620
+ }
3621
+ /**
3622
+ * JSON with object keys sorted at every depth, so two argument objects that differ only in key
3623
+ * order produce the same text. `undefined` properties are dropped (as `JSON.stringify` does); a
3624
+ * bare `undefined` and an `undefined` array element are `null`.
3625
+ */
3626
+ declare function canonicalJson(value: unknown): string;
3627
+ /**
3628
+ * Issue a confirm token: `<expiresAt>.<signature>`, an HMAC-SHA256 (keyed by `secret`) over the tool,
3629
+ * the actor, the tenant, the expiry and the canonical arguments. Stateless — nothing is stored — and
3630
+ * useless for another actor, tenant, tool or argument, or after `expiresAt` (epoch-ms).
3631
+ */
3632
+ declare function signConfirmToken(subject: ConfirmTokenSubject, options: {
3633
+ secret: string;
3634
+ expiresAt: number;
3635
+ }): string;
3636
+ /** The expiry (epoch-ms) a token carries, or `undefined` for a malformed one. Not a verification. */
3637
+ declare function confirmTokenExpiry(token: string): number | undefined;
3638
+ /** Was this token issued for exactly this subject, with this secret, and is it still valid at `now`? */
3639
+ declare function verifyConfirmToken(token: string | null | undefined, subject: ConfirmTokenSubject, options: {
3640
+ secret: string;
3641
+ now?: number;
3642
+ }): boolean;
3643
+ /** SHA-256 (hex) of a token — what a {@link ConfirmTokenStore} keys on, so the token is never stored. */
3644
+ declare function hashConfirmToken(token: string): string;
3645
+ /**
3646
+ * A single-process {@link ConfirmTokenStore}: tests, scripts, and a deployment that runs ONE replica.
3647
+ * With more than one, a token spent on replica A is still fresh on replica B — use the Drizzle or
3648
+ * MikroORM store (`AGENT_CONFIRM_TOKEN_STORE`, bound by their modules).
3649
+ * Expired marks are dropped lazily, on the next claim.
3650
+ */
3651
+ declare class InMemoryConfirmTokenStore implements ConfirmTokenStore {
3652
+ private readonly claims;
3653
+ claim(input: ConfirmTokenClaim): Promise<boolean>;
3654
+ release(hash: string): Promise<void>;
3655
+ purgeExpired(now?: number): Promise<number>;
3656
+ /** How many tokens are currently marked as spent. */
3657
+ get size(): number;
3658
+ }
3659
+
3660
+ /** The two fields {@link defineConfirmedTool} adds to a tool's input. */
3661
+ interface ConfirmFields {
3662
+ /** `true` to commit; absent (or `false`) to preview. */
3663
+ confirm?: boolean;
3664
+ /** The `confirmToken` the preview returned. */
3665
+ confirmToken?: string;
3666
+ }
3667
+ /** The words a confirmed tool says to the model. Each has an English default. */
3668
+ interface ConfirmedToolMessages {
3669
+ /** Sent with every preview: how to confirm. `{minutes}` is replaced with the token's lifetime. */
3670
+ confirm?: string;
3671
+ /** Thrown for a missing, tampered, mismatched or expired token. */
3672
+ invalid?: string;
3673
+ /** Thrown for a token that already committed. */
3674
+ used?: string;
3675
+ }
3676
+ /** Thrown by a confirmed tool that refused a confirmation. Nothing was written. */
3677
+ declare class ConfirmTokenError extends Error {
3678
+ /** `invalid`: missing, tampered, mismatched or expired. `used`: it already committed once. */
3679
+ readonly reason: 'invalid' | 'used';
3680
+ constructor(
3681
+ /** `invalid`: missing, tampered, mismatched or expired. `used`: it already committed once. */
3682
+ reason: 'invalid' | 'used', message: string);
3683
+ }
3684
+ /** What {@link defineConfirmedTool} takes: the usual spec fields (no `kind`), plus the gate's own. */
3685
+ interface ConfirmedToolOptions extends Omit<ToolSpec, 'kind' | 'inputSchema' | 'targetAgent' | 'detached' | 'terminal'> {
3686
+ /** The app's own input schema. `confirm` / `confirmToken` are added by {@link withConfirmFields}. */
3687
+ input: StandardSchemaV1;
3688
+ /**
3689
+ * The HMAC key the tokens are signed with — the app's secret (`ConfigService.getOrThrow(...)`), or
3690
+ * one of its own. A function is read on every call. Required: there is no default, and an empty
3691
+ * one throws.
3692
+ */
3693
+ secret: string | (() => string);
3694
+ /** How long a preview stays confirmable. Default 15 minutes. */
3695
+ ttlMs?: number;
3696
+ /**
3697
+ * Makes a token single use. WITHOUT a store a token commits as many times as it is sent until it
3698
+ * expires — a retry or a repeated call writes twice. The store modules bind one to
3699
+ * `AGENT_CONFIRM_TOKEN_STORE`; `InMemoryConfirmTokenStore` is for one replica.
3700
+ */
3701
+ store?: ConfirmTokenStore;
3702
+ messages?: ConfirmedToolMessages;
3703
+ }
3704
+ /** What a step reports: a sentence for the model to relay, and the structured detail behind it. */
3705
+ interface ConfirmedToolOutcome {
3706
+ summary: string;
3707
+ data?: unknown;
3708
+ }
3709
+ /** The three steps of a confirmed write. */
3710
+ interface ConfirmedToolSteps<Args, Prepared> {
3711
+ /**
3712
+ * Resolve and validate everything the write needs, applying the SAME rules the commit relies on.
3713
+ * Throw to refuse. Writes nothing. Runs for the preview AND again for the confirmation — state may
3714
+ * have changed in between — and a refusal here does not spend the token.
3715
+ */
3716
+ prepare(args: Args, ctx: AiToolCtx): Promise<Prepared> | Prepared;
3717
+ /** What is about to happen. Writes nothing. */
3718
+ preview(prepared: Prepared, ctx: AiToolCtx): Promise<ConfirmedToolOutcome> | ConfirmedToolOutcome;
3719
+ /** Write, and say what was written. A throw gives the token back. */
3720
+ commit(prepared: Prepared, ctx: AiToolCtx): Promise<ConfirmedToolOutcome> | ConfirmedToolOutcome;
3721
+ }
3722
+ /** A confirmed tool's answer to a call without `confirm`. */
3723
+ interface ConfirmedToolPreview {
3724
+ status: 'preview';
3725
+ summary: string;
3726
+ data?: unknown;
3727
+ confirmToken: string;
3728
+ /** ISO-8601 instant the token stops working. */
3729
+ expiresAt: string;
3730
+ /** Instructions for the model: show the preview, then call again with the token. */
3731
+ confirm: string;
3732
+ }
3733
+ /** A confirmed tool's answer to a confirmation that committed. */
3734
+ interface ConfirmedToolDone {
3735
+ status: 'done';
3736
+ summary: string;
3737
+ data?: unknown;
3738
+ }
3739
+ type ConfirmedToolResult = ConfirmedToolPreview | ConfirmedToolDone;
3740
+ /** The JSON Schema of {@link ConfirmFields}, merged into the schema the model is shown. */
3741
+ declare const CONFIRM_JSON_SCHEMA_PROPERTIES: {
3742
+ readonly confirm: {
3743
+ readonly type: "boolean";
3744
+ readonly description: "Omit to get a preview (nothing is written). Send true, with confirmToken, to commit.";
3745
+ };
3746
+ readonly confirmToken: {
3747
+ readonly type: "string";
3748
+ readonly description: "The confirmToken the preview returned. Required when confirm is true.";
3749
+ };
3750
+ };
3751
+ /**
3752
+ * Marks a schema that is ANOTHER schema plus a few JSON Schema properties. A converter that knows the
3753
+ * inner schema better than the wrapper can (a Zod 3 schema has no Standard JSON Schema extension, so
3754
+ * only the AI SDK's or the MCP SDK's own converter can describe it) converts `base` and adds
3755
+ * `properties`. `@dudousxd/nestjs-agent-ai-sdk` and `-mcp-server` both read it.
3756
+ */
3757
+ declare const SCHEMA_EXTENSION: unique symbol;
3758
+ interface SchemaExtension {
3759
+ base: StandardSchemaV1;
3760
+ properties: Record<string, unknown>;
3761
+ }
3762
+ /** The {@link SchemaExtension} a schema carries, if any. */
3763
+ declare function schemaExtensionOf(schema: StandardSchemaV1): SchemaExtension | undefined;
3764
+ /**
3765
+ * Wrap a tool's input schema so it also accepts {@link ConfirmFields}, without the app declaring
3766
+ * them. `validate` takes the two fields off, checks them itself, hands the REST to the app's schema
3767
+ * (so a strict schema never sees a key it did not declare) and puts them back on the validated value.
3768
+ *
3769
+ * The wrapper always carries the Standard JSON Schema extension: the app schema's own JSON Schema
3770
+ * plus the two properties. A schema without the extension (Zod 3, a bare Standard Schema) degrades
3771
+ * there to a permissive object that still declares the two fields — but the wrapper also carries a
3772
+ * {@link SchemaExtension}, so the AI SDK adapter and the MCP server convert a Zod 3 schema with their
3773
+ * own converters and show the model its real shape. `validate` stays the authority either way.
3774
+ */
3775
+ declare function withConfirmFields<Schema extends StandardSchemaV1>(schema: Schema): StandardSchemaV1<StandardSchemaV1.InferInput<Schema> & ConfirmFields, StandardSchemaV1.InferOutput<Schema> & ConfirmFields>;
3776
+ /**
3777
+ * A write with a human gate that lives INSIDE the tool: preview first, commit on confirmation.
3778
+ *
3779
+ * - Called without `confirm`: runs `prepare`, writes nothing, and returns the `preview` with a signed
3780
+ * `confirmToken`.
3781
+ * - Called again with the SAME arguments, `confirm: true` and that token: runs `prepare` again, then
3782
+ * `commit`.
3783
+ *
3784
+ * The token is an HMAC over the tool, `ctx.actor.id`, `ctx.actor.tenantRef`, the expiry and the
3785
+ * canonical arguments, so it cannot be replayed by another actor, in another tenant, on another
3786
+ * tool or with a changed argument. With a `store` it is also single use: it is claimed right before
3787
+ * `commit` (a refusal in `prepare` does not spend it) and released if `commit` throws.
3788
+ *
3789
+ * Registered as `kind: 'read'` on purpose. An `action` parks on the loop's HITL approval, which an
3790
+ * MCP caller cannot answer — `AgentMcpServerModule` keeps `action` tools off the surface, and MCP clients
3791
+ * without elicitation have no other channel. The gate being in the handler is what lets the same
3792
+ * tool serve the chat loop and MCP; the user sees the preview because the model has to relay it to
3793
+ * get a token it can confirm with.
3794
+ *
3795
+ * ```ts
3796
+ * provideAgentTool(
3797
+ * (store: ConfirmTokenStore, config: ConfigService, orders: OrdersService) =>
3798
+ * defineConfirmedTool(
3799
+ * { name: 'refund_order', description: '...', input: z.object({ orderId: z.string() }),
3800
+ * secret: () => config.getOrThrow('CONFIRM_SECRET'), store },
3801
+ * {
3802
+ * prepare: ({ orderId }, ctx) => orders.loadRefundable(orderId, ctx.actor),
3803
+ * preview: (order) => ({ summary: `Refund ${order.total} to ${order.customer}?`, data: order }),
3804
+ * commit: async (order) => ({ summary: 'Refunded.', data: await orders.refund(order) }),
3805
+ * },
3806
+ * ),
3807
+ * [AGENT_CONFIRM_TOKEN_STORE, ConfigService, OrdersService],
3808
+ * );
3809
+ * ```
3810
+ *
3811
+ * `input` is the app's own schema: `confirm` and `confirmToken` are added by
3812
+ * {@link withConfirmFields}, and `prepare` receives the arguments without them.
3813
+ */
3814
+ declare function defineConfirmedTool<Args = unknown, Prepared = unknown>(options: ConfirmedToolOptions, steps: ConfirmedToolSteps<Args, Prepared>): ConfirmedTool;
3815
+ /**
3816
+ * What {@link defineConfirmedTool} returns: a functional tool (`{ spec, handler }`) — pass it to
3817
+ * `AgentModule.forRoot({ tools })`, or build it in `provideAgentTool(factory, inject)` when it
3818
+ * needs injected services (the confirm-token store, the secret from `ConfigService`).
3819
+ */
3820
+ interface ConfirmedTool {
3821
+ spec: ToolSpec;
3822
+ handler: ToolHandler;
3823
+ }
3824
+
3825
+ /** One stored row of a run's stream. `frame` is `null` on the terminal row. */
3826
+ interface StreamFrameRow {
3827
+ seq: number;
3828
+ /** One NDJSON line (`{...}\n`) as the writer wrote it; `null` marks the end of the run. */
3829
+ frame: string | null;
3830
+ /** On the terminal row of a FAILED run: the `StreamError` as JSON. `null` otherwise. */
3831
+ error: string | null;
3832
+ }
3833
+ /**
3834
+ * The table a {@link SqlTokenStreamSink} keeps its rows in — the only part of it that speaks SQL, so
3835
+ * a store package implements this and inherits the rest (coalescing, ordering, polling, TTL).
3836
+ * `@dudousxd/nestjs-agent-store-drizzle` and `-store-mikro-orm` ship one each, over
3837
+ * `agent_stream_frame` (`run_id`, `seq`, `frame`, `error`, `created_at`; primary key
3838
+ * `(run_id, seq)`).
3839
+ */
3840
+ interface StreamFrameTable {
3841
+ /**
3842
+ * Insert the run's NEXT row: `seq = MAX(seq) + 1` for the run, taken in the SAME statement as the
3843
+ * insert, so the `(run_id, seq)` primary key settles two writers that ask at once. Throws on that
3844
+ * collision ({@link isUniqueViolation} says which errors are one) — the sink retries.
3845
+ */
3846
+ append(runId: string, row: {
3847
+ frame: string | null;
3848
+ error: string | null;
3849
+ createdAt: number;
3850
+ }): Promise<void>;
3851
+ /** The run's rows with `seq > after`, ascending, at most `limit`. */
3852
+ read(runId: string, after: number, limit: number): Promise<StreamFrameRow[]>;
3853
+ /** Does the table hold any row for the run? */
3854
+ has(runId: string): Promise<boolean>;
3855
+ /** Delete every row of these runs. */
3856
+ remove(runIds: readonly string[]): Promise<void>;
3857
+ /** Runs whose LAST row was written before `cutoff` (epoch-ms). */
3858
+ lapsedRuns(cutoff: number): Promise<string[]>;
3859
+ /** Is this error a lost race for a `(run_id, seq)` — and nothing else (a missing table, a dead connection)? */
3860
+ isUniqueViolation(error: unknown): boolean;
3861
+ }
3862
+ interface SqlTokenStreamSinkOptions {
3863
+ /**
3864
+ * Gap (ms) between two reads of a run a subscriber is following — the most a frame waits in the
3865
+ * table before a browser sees it. Default 250.
3866
+ */
3867
+ pollIntervalMs?: number;
3868
+ /**
3869
+ * Gap (ms) between two reads once the run has written nothing for five seconds (parked on a
3870
+ * person, a slow tool), so an open SSE connection on a quiet run costs one query a second. The
3871
+ * first frame to arrive puts the subscriber back on `pollIntervalMs`. Default 1000; never below
3872
+ * `pollIntervalMs`.
3873
+ */
3874
+ idlePollIntervalMs?: number;
3875
+ /**
3876
+ * Window (ms) consecutive `text` frames are gathered over and written as ONE row — a model
3877
+ * streams token by token, and a row per token is more writes than a database should take for a
3878
+ * chat answer. Any other frame, `end()`, `fail()` and `flush()` write what is gathered first, so
3879
+ * order is kept. Default 50. `0` writes every frame as its own row.
3880
+ */
3881
+ flushMs?: number;
3882
+ /**
3883
+ * TTL (seconds) of a run's rows, counted from its LAST write — a long run stays, a run that
3884
+ * crashed without ending still lapses. {@link SqlTokenStreamSink.purgeExpired} deletes them.
3885
+ * Default 3600 (1h). `0` keeps rows until `close()`.
3886
+ */
3887
+ ttlSeconds?: number;
3888
+ /**
3889
+ * Purge lapsed runs as a side effect of ending a run, at most once a minute, so the table stays
3890
+ * bounded in an app that never schedules {@link SqlTokenStreamSink.purgeExpired}. Default `true`.
3891
+ */
3892
+ autoPurge?: boolean;
3893
+ }
3894
+ /**
3895
+ * A multi-replica {@link TokenStreamSink} over the app's SQL database — for a deployment with
3896
+ * several replicas and NO Redis. The replica running the turn appends each frame as a row; any
3897
+ * replica serves the run's SSE by reading the rows past its cursor, in order, until the terminal
3898
+ * row. A late subscriber replays from the first row, as with the in-process and Redis sinks, and a
3899
+ * run that `fail()`ed throws its {@link AgentStreamError} after the replay.
3900
+ *
3901
+ * Two things differ from the Redis sink, both the price of having no broker:
3902
+ *
3903
+ * - **Delivery is polled** — a frame waits up to `pollIntervalMs` before a browser sees it.
3904
+ * - **Text is coalesced on the way in.** Consecutive `text` frames written within `flushMs` are
3905
+ * stored as ONE `text` frame. The stored rows ARE the run's stream: every subscriber, on every
3906
+ * replica, reads the same rows in the same order, so the SSE ids `chat/:runId/stream` numbers
3907
+ * them with — and an `?after=` cursor — stay exact across replicas.
3908
+ *
3909
+ * Sequence numbers are per run, start at 1 and have no gaps (see {@link StreamFrameTable.append}).
3910
+ * Text a writer is still gathering lives in the process for at most `flushMs`; a process that dies
3911
+ * in that window loses it from the LIVE stream (the persisted message is unaffected).
3912
+ *
3913
+ * Framework- and dialect-free: the SQL is the {@link StreamFrameTable}'s. Use
3914
+ * `DrizzleTokenStreamSink` / `MikroOrmTokenStreamSink` from the store packages.
3915
+ */
3916
+ declare class SqlTokenStreamSink implements TokenStreamSink {
3917
+ private readonly table;
3918
+ private readonly pollIntervalMs;
3919
+ private readonly idlePollIntervalMs;
3920
+ private readonly flushMs;
3921
+ private readonly ttlSeconds;
3922
+ private readonly autoPurge;
3923
+ private readonly writes;
3924
+ private lastAutoPurge;
3925
+ constructor(table: StreamFrameTable, options?: SqlTokenStreamSinkOptions);
3926
+ private runWrites;
3927
+ /** Forget a run's write state once nothing is gathered, queued or left to report. */
3928
+ private release;
3929
+ /** Queue `work` behind every write already queued for the run, so rows land in call order. */
3930
+ private enqueue;
3931
+ /** Queue the gathered text (if any) as one `text` row. */
3932
+ private flushText;
3933
+ /** Raise, once, a gathered write that failed with nobody awaiting it. */
3934
+ private raiseFailure;
3935
+ /** Append one row — a frame, or the terminal row (`frame: null`, with `error` on a failure). */
3936
+ private append;
3937
+ /** Write out what is gathered, then a terminal row; raise a failure nobody saw. */
3938
+ private terminate;
3939
+ /**
3940
+ * The run's writer. Writers opened for the same run in one process share what they are gathering,
3941
+ * so a delegated run's text (forwarded through a child writer) and its parent's next frame keep
3942
+ * the order they were written in.
3943
+ */
3944
+ open(runId: string): SinkWriter;
3945
+ subscribe(runId: string): AsyncIterable<Uint8Array>;
3946
+ /** Does the table hold anything for the run — a frame, or its end? */
3947
+ has(runId: string): Promise<boolean>;
3948
+ close(runId: string): Promise<void>;
3949
+ /**
3950
+ * Delete every run whose last write is older than `ttlSeconds` at `now` (epoch-ms) — ended runs
3951
+ * past their replay window and runs that crashed without ending alike. Returns how many runs went.
3952
+ * Safe from any replica, and from several at once. A no-op under `ttlSeconds: 0`.
3953
+ */
3954
+ purgeExpired(now?: number): Promise<number>;
3955
+ /** {@link purgeExpired}, unawaited and at most once a minute. Its failure is not the run's. */
3956
+ private purgeInBackground;
3957
+ }
3958
+
3959
+ export { AGENT_ACTOR_DIRECTORY, AGENT_ACTOR_RESOLVER, AGENT_APPROVAL_PORT, AGENT_ATTACHMENT_STAGING, AGENT_CONFIRM_TOKEN_STORE, 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 AgentRunStartOptions, type AgentRunStarted, type AgentRunner, type AgentSkillsResolved, type AgentSpanEvent, AgentStore, AgentStreamError, AgentStreamEvent, type AgentStructuredOutputSpan, type AgentToolCallEvent, type AgentToolExecutionSpan, type AgentToolRetry, AgentUiComponent, AiToolCtx, AppendMessageInput, type ApprovalDecisionRef, type ApprovalPolicy, type ApprovalRequirement, type ApprovalThreadRef, type ApprovalToolRef, type ApprovalWhere, type AttachmentRef, type AttachmentStagingDescription, type AttachmentStagingStore, type BufferedModelTurnResult, type BuildMemoryBlockInput, CONFIRM_JSON_SCHEMA_PROPERTIES, ChatQueueStore, ClosedRolesPolicy, type ConfirmFields, type ConfirmTokenClaim, ConfirmTokenError, type ConfirmTokenStore, type ConfirmTokenSubject, type ConfirmedTool, type ConfirmedToolDone, type ConfirmedToolMessages, type ConfirmedToolOptions, type ConfirmedToolOutcome, type ConfirmedToolPreview, type ConfirmedToolResult, type ConfirmedToolSteps, type CostUsage, CreateThreadInput, type CurrentModelPrice, DEFAULT_CONFIRM_TTL_MS, 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 EmptyRoles, EnqueueMessageInput, type ForgetMemoryInput, type FrameBuffer, GLOBAL_SCOPE, type GovernanceMessageRow, type GovernancePage, type GovernancePageQuery, type GovernancePendingApprovalRow, type GovernanceRange, type GovernanceRunDetail, type GovernanceRunRow, type GovernanceThreadDetail, type GovernanceThreadDetailQuery, type GovernanceThreadRow, type GovernanceToolCallRow, type GovernanceUsageInput, type GovernanceUsageRow, HistoryPolicy, HumanReply, InMemoryAgentStore, InMemoryConfirmTokenStore, 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 ModelCatalogLock, 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, QueuePause, QueuedMessage, QueuedMessagePatch, type QuotaBlock, QuotaExceededError, type QuotaPeriod, type QuotaProvider, type QuotaQuery, type QuotaReport, QuotaState, type QuotaStore, type QuotaWarning, type QuotaWindow, REMEMBER_TOOL_DESCRIPTION, REMEMBER_TOOL_NAME, REQUESTER_APPROVER, RUN_FAILED_MESSAGE, RUN_NOT_ACTIVE_CODE, RUN_NOT_ACTIVE_MESSAGE, RUN_NO_LONGER_RUNNING, type RecentRunRow, RecordRunStartInput, RecordToolCallInput, RecordUsageInput, type RememberToolInput, type RerankOptions, type Reranker, type ResolveAttachmentInput, type ResolveMemoryDigestInput, type ResolvedDelegation, type RetrieveOptions, type Retriever, type RolesPolicy, type RolesPolicyOptions, type RunAgentBreakdownRow, RunCancelledError, type RunErrorBreakdownRow, type RunMetrics, type RunToolCallRow, type RunTrendPoint, type RunWhere, SCHEMA_EXTENSION, SKILL_TOOL_DESCRIPTION, SKILL_TOOL_NAME, type SchemaExtension, type ScopeContext, type ScopeResolver, type SearchMemoriesInput, type SettleDeadRunInput, 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, SqlTokenStreamSink, type SqlTokenStreamSinkOptions, type StageAttachmentInput, type StagedAttachment, type StoreMemoryInput, StoredMessage, type StreamError, type StreamFrameRow, type StreamFrameTable, type StructuredOutcome, StructuredOutputError, THREAD_DETAIL_CONTENT_CHARS, type ThreadActivityRow, ThreadDetail, type ThreadMessageRow, type ThreadMeta, type ThreadSpendRow, ThreadSummary, type ThreadUsageRollup, type ThreadWhere, type TokenStreamSink, type ToolCallActivityRow, ToolCallApproval, type ToolCallApprovalColumns, ToolCallApprovalState, ToolCallOutcome, 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, UpdateThreadInput, UpdateToolCallInput, type UsageTrendPoint, type WindowHistoryOptions, type WithMemoryToolInput, type WriteMemoryInput, actorScope, agentDiagnosticKey, agentFailureCode, bucketByActor, bucketByModel, bucketByThread, bucketUsageTrend, buildMemoryBlock, buildSkillsBlock, canActorUseTool, canonicalJson, closeEmptyRoles, compositeSkillProvider, confirmTokenExpiry, createFrameBuffer, createIncrementalGate, createNoopEmitUi, createUiCollector, dayBoundsUtc, defaultCanDecide, defaultScopeResolver, defineConfirmedTool, detachedDelivered, detachedStarted, detachedUnsettled, estimateCost, estimateMessageTokens, exhaustedWindow, exposeStreamErrorDetails, extractJson, filterToolsByAllowList, filterToolsByCanUse, filterToolsByEnabled, filterToolsByRole, findCatalogModel, gateFollowUps, gateTail, hashConfirmToken, 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, quotaUsedRatio, quotaWarning, releaseGatedFrames, rememberInputSchema, rememberToolDefinition, repairInstruction, resolveGateLookback, resolveMemoryDigest, resolveOutputGateMode, resolveSkillCatalog, rollupThreadUsage, runAgentLoop, runInputProcessors, runOutputProcessors, schemaExtensionOf, seedModelPrices, settleAll, settleDeadRun, settleUnsettledDelegation, signConfirmToken, skillInputSchema, skillToolDefinition, skillWriteVerdict, stampToolKinds, staticModelCatalog, staticSkillProvider, streamFailure, summarizeWithModel, tenantScope, toolCallApprovalFromRow, toolCallContext, traceLlmTurn, traceToolExecution, truncateDetailContent, unwrapToolStepOutput, validateStructured, verifyConfirmToken, windowHistory, withAskTool, withConfirmFields, withMemoryTool, withSelectedModel, withSkillTool, withToolTimeout, withTurnFrames, wrapToolStepOutput, writeMemory };