@dudousxd/nestjs-agent-core 0.39.0 → 0.41.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.
Files changed (40) hide show
  1. package/README.md +7 -0
  2. package/dist/ag-ui/index.cjs +123 -9
  3. package/dist/ag-ui/index.cjs.map +1 -1
  4. package/dist/ag-ui/index.d.cts +19 -3
  5. package/dist/ag-ui/index.d.ts +19 -3
  6. package/dist/ag-ui/index.js +122 -9
  7. package/dist/ag-ui/index.js.map +1 -1
  8. package/dist/{catalog-CrzetM3_.d.cts → catalog-BKS3Yxo6.d.cts} +2 -0
  9. package/dist/{catalog-CrzetM3_.d.ts → catalog-BKS3Yxo6.d.ts} +2 -0
  10. package/dist/genui/builtins.cjs +2 -0
  11. package/dist/genui/builtins.cjs.map +1 -1
  12. package/dist/genui/builtins.d.cts +1 -1
  13. package/dist/genui/builtins.d.ts +1 -1
  14. package/dist/genui/builtins.js +2 -0
  15. package/dist/genui/builtins.js.map +1 -1
  16. package/dist/genui/index.cjs +780 -106
  17. package/dist/genui/index.cjs.map +1 -1
  18. package/dist/genui/index.d.cts +5 -5
  19. package/dist/genui/index.d.ts +5 -5
  20. package/dist/genui/index.js +770 -105
  21. package/dist/genui/index.js.map +1 -1
  22. package/dist/guardrails/index.cjs +3 -1
  23. package/dist/guardrails/index.cjs.map +1 -1
  24. package/dist/guardrails/index.d.cts +5 -4
  25. package/dist/guardrails/index.d.ts +5 -4
  26. package/dist/guardrails/index.js +3 -1
  27. package/dist/guardrails/index.js.map +1 -1
  28. package/dist/index.cjs +3324 -380
  29. package/dist/index.cjs.map +1 -1
  30. package/dist/index.d.cts +388 -96
  31. package/dist/index.d.ts +388 -96
  32. package/dist/index.js +3279 -377
  33. package/dist/index.js.map +1 -1
  34. package/dist/{processors-6p9nrqEi.d.cts → processors-BXM-MNga.d.cts} +1 -1
  35. package/dist/{processors-Bp5XmF6V.d.ts → processors-ByDr5POu.d.ts} +1 -1
  36. package/dist/{stream-events-CbVEowYb.d.cts → stream-events-BGKLD6RX.d.ts} +664 -86
  37. package/dist/{stream-events-CbVEowYb.d.ts → stream-events-CF-6-Y6L.d.cts} +664 -86
  38. package/package.json +1 -1
  39. package/dist/tool-DZYLEKnl.d.cts +0 -121
  40. package/dist/tool-_iq4xRyk.d.ts +0 -121
package/dist/index.d.ts CHANGED
@@ -1,10 +1,9 @@
1
- import { M as ModelMessage, c as ToolDefinition, d as ToolCallRequest, e as MessageUsage, f as AgentUiComponent, a as Actor, A as AgentStreamEvent, T as ToolSpec, Q as QuotaState, g as AgentRunInput, H as HumanReply, h as MessageAttachment, i as ToolKind, j as ToolCallStatus, k as ToolCallApproval, l as AgentDefinition, P as Persona, m as PersonaCatalogEntry, n as HistoryPolicy, o as PageContext, p as AgentStore, q as AgentDelegation, D as DetachedDelivery, r as PromptBuilder, s as PromptContributor, t as ToolTransientRetrySetting, u as AgentIntake, v as Decision, E as ElicitationRequest, L as LlmStepEnvelope, w as ToolStepEnvelope, C as ChatQueueStore, x as CreateThreadInput, y as ThreadSummary, z as ThreadDetail, B as ToolCallApprovalState, U as UpdateThreadInput, R as RecordRunStartInput, F as EnqueueMessageInput, G as QueuedMessage, I as QueuedMessagePatch, J as QueuePause, K as AppendMessageInput, S as StoredMessage, N as ToolResult, O as MessageFeedback, V as RecordToolCallInput, W as ToolCallOutcome, X as UpdateToolCallInput, Y as RecordUsageInput } from './stream-events-CbVEowYb.js';
2
- export { Z as ALL_AGENTS, _ as ASK_TOOL_DESCRIPTION, $ as ASK_TOOL_NAME, a0 as AgentApprovalRequest, a1 as AgentApprovalSettlement, a2 as AgentAttachmentConfig, a3 as AgentCatalogEntry, a4 as AgentClientConfig, a5 as AgentHistoryWindow, a6 as AgentStreamErrorCode, a7 as AskToolInput, a8 as ChatQueueState, a9 as DEFAULT_INTAKE_PREAMBLE, aa as DEFAULT_TOOL_TRANSIENT_RETRY_ATTEMPTS, ab as DEFAULT_TOOL_TRANSIENT_RETRY_BACKOFF_MS, ac as ELICITATION_INPUT_TYPES, ad as ElicitationInput, ae as ElicitationInputType, af as ElicitationOption, ag as ElicitationOutcome, ah as ElicitationQuestion, ai as ElicitationReply, aj as ElicitationResult, ak as HistoryPolicyContext, al as HistorySelection, am as HistorySummary, an as InvokeWithTransientRetryOptions, ao as MAX_ASK_QUESTIONS, ap as MessageFeedbackValue, aq as MessageRole, ar as PersonaRef, as as PromptContext, at as QueuePauseReason, au as QueuedMessageView, av as QuotaView, aw as RUN_ENDED_BEFORE_TOOL_CALL, ax as RecordRunEndInput, ay as ThreadTurnPage, az as ThreadTurnQuery, aA as ThreadTurnReader, aB as ToolCallApprovalStatus, aC as ToolCatalogEntry, aD as ToolConfirmation, b as ToolPresentation, aE as ToolPresentationTone, aF as ToolResultField, aG as ToolResultView, aH as ToolStepCtx, aI as ToolTransientRetryNumbers, aJ as ToolTransientRetryOptions, aK as TurnPersona, aL as UNFINISHED_TOOL_CALL, aM as UsagePurpose, aN as askInputSchema, aO as askToolDefinition, aP as danglingToolCallIds, aQ as decodeStreamEvent, aR as encodeStreamEvent, aS as invokeWithTransientRetry, aT as isChatQueueStore, aU as isTransientToolError, aV as isTypedQuestion, aW as normalizeElicitationReply, aX as questionOptions, aY as queuedMessageView, aZ as readElicitationInput, a_ as readElicitationQuestions, a$ as releaseThreadRun, b0 as renderElicitationAnswers, b1 as resolveElicitation, b2 as resolveToolTransientRetryNumbers, b3 as settleDanglingToolCalls, b4 as settleElicitation, b5 as validateElicitationAnswer, b6 as validateElicitationValue } from './stream-events-CbVEowYb.js';
3
- import { A as AiToolCtx, T as ToolHandler, a as ToolDescribeScope } from './tool-_iq4xRyk.js';
4
- export { b as ToolDescription } from './tool-_iq4xRyk.js';
1
+ import { M as ModelMessage, q as ToolDefinition, r as ToolCallRequest, u as MessageUsage, w as AgentUiComponent, a as Actor, x as AiToolCtx, A as AgentStreamEvent, T as ToolSpec, Q as QuotaState, y as AgentRunInput, H as HumanReply, z as MessageAttachment, B as ActionProposalMutationResult, D as ActionProposal, E as ActionProposalExecution, F as ActionProposalOutcomeDelivery, b as ToolHandler, G as AgentDefinition, I as Persona, J as PersonaCatalogEntry, K as HistoryPolicy, L as PageContext, N as AgentStore, O as AgentDelegation, R as DetachedDelivery, S as ToolDescribeScope, V as ToolPreflightResult, W as ApprovalPolicy, X as PromptBuilder, Y as PromptContributor, Z as ToolTransientRetrySetting, _ as AgentIntake, $ as Decision, a0 as ElicitationRequest, a1 as LlmStepEnvelope, a2 as ToolStepEnvelope, a3 as ClaimActionProposal, a4 as ActionProposalStore, a5 as ActionProposalStoreOptions, a6 as CreateActionProposal, a7 as CreateActionProposalResult, a8 as ActionProposalScope, a9 as ListActionProposals, aa as ActionProposalDecisionCommand, ab as ExtendActionProposalLease, ac as SettleActionProposal, ad as ActionProposalOutcome, ae as ActionProposalOutcomeLease, af as ToolCallStatus, ag as ChatQueueStore, ah as ActionProposalOutcomeStore, ai as CreateThreadInput, aj as ThreadSummary, ak as ThreadDetail, al as ToolCallApprovalState, am as UpdateThreadInput, an as RecordRunStartInput, ao as EnqueueMessageInput, ap as QueuedMessage, aq as QueuedMessagePatch, ar as QueuePause, as as AppendMessageInput, at as StoredMessage, au as ToolResult, av as MessageFeedback, aw as RecordToolCallInput, ax as ToolCallOutcome, ay as UpdateToolCallInput, az as RecordUsageInput, aA as ToolConfirmation, aB as ActionProposalDecision, aC as ActionProposalSupersessionStore } from './stream-events-BGKLD6RX.js';
2
+ export { aD as ALL_AGENTS, aE as ASK_TOOL_DESCRIPTION, aF as ASK_TOOL_NAME, aG as ActionProposalDecisionAudit, aH as ActionProposalExecutionContext, aI as ActionProposalLease, aJ as AgentApprovalRequest, aK as AgentApprovalSettlement, aL as AgentAttachmentConfig, aM as AgentCatalogEntry, aN as AgentClientConfig, aO as AgentHistoryWindow, aP as AgentStreamErrorCode, aQ as ApprovalDecisionRef, aR as ApprovalRequirement, aS as ApprovalThreadRef, aT as ApprovalToolRef, aU as AskToolInput, aV as ChatQueueState, aW as ClaimedActionApproval, aX as DEFAULT_INTAKE_PREAMBLE, aY as DEFAULT_TOOL_TRANSIENT_RETRY_ATTEMPTS, aZ as DEFAULT_TOOL_TRANSIENT_RETRY_BACKOFF_MS, a_ as DefaultApprovalPolicy, a$ as ELICITATION_INPUT_TYPES, b0 as ElicitationInput, b1 as ElicitationInputType, b2 as ElicitationOption, b3 as ElicitationOutcome, b4 as ElicitationQuestion, b5 as ElicitationReply, b6 as ElicitationResult, b7 as EmitUiOptions, b8 as HistoryPolicyContext, b9 as HistorySelection, ba as HistorySummary, bb as InvokeWithTransientRetryOptions, bc as MAX_ASK_QUESTIONS, bd as MessageFeedbackValue, be as MessageRole, bf as PersonaRef, bg as PromptContext, bh as QueuePauseReason, bi as QueuedMessageView, bj as QuotaView, bk as REQUESTER_APPROVER, bl as RUN_ENDED_BEFORE_TOOL_CALL, bm as RecordRunEndInput, bn as ResolveActionProposalApprovalInput, bo as ThreadTurnPage, bp as ThreadTurnQuery, bq as ThreadTurnReader, br as ToolCallApproval, bs as ToolCallApprovalColumns, bt as ToolCallApprovalStatus, bu as ToolCatalogEntry, bv as ToolDescription, bw as ToolKind, bx as ToolPreflightOptions, c as ToolPresentation, by as ToolPresentationTone, bz as ToolResultField, bA as ToolResultView, bB as ToolStepCtx, bC as ToolTransientRetryNumbers, bD as ToolTransientRetryOptions, bE as TurnPersona, bF as UNFINISHED_TOOL_CALL, bG as UsagePurpose, bH as askInputSchema, bI as askToolDefinition, bJ as danglingToolCallIds, bK as decodeStreamEvent, bL as defaultCanDecide, bM as encodeStreamEvent, bN as invokeWithTransientRetry, bO as isChatQueueStore, bP as isTransientToolError, bQ as isTypedQuestion, bR as mayDecideApproval, bS as normalizeElicitationReply, bT as questionOptions, bU as queuedMessageView, bV as readElicitationInput, bW as readElicitationQuestions, bX as releaseThreadRun, bY as renderElicitationAnswers, bZ as resolveActionProposalApproval, b_ as resolveElicitation, b$ as resolveToolTransientRetryNumbers, c0 as settleDanglingToolCalls, c1 as settleElicitation, c2 as toolCallApprovalFromRow, c3 as validateElicitationAnswer, c4 as validateElicitationValue } from './stream-events-BGKLD6RX.js';
5
3
  import { StandardSchemaV1 } from '@standard-schema/spec';
6
- import { O as OutputProcessor, P as ProcessorContext, I as InputProcessor, a as ProcessedPrompt, M as ModelAnswer } from './processors-Bp5XmF6V.js';
7
- export { D as DEFAULT_INCREMENTAL_LOOKBACK_CHARS, b as IncrementalGating, c as OutputRejectedError, d as OutputVerdict, e as ProcessorFailedError } from './processors-Bp5XmF6V.js';
4
+ import { O as OutputProcessor, P as ProcessorContext, I as InputProcessor, a as ProcessedPrompt, M as ModelAnswer } from './processors-ByDr5POu.js';
5
+ export { D as DEFAULT_INCREMENTAL_LOOKBACK_CHARS, b as IncrementalGating, c as OutputRejectedError, d as OutputVerdict, e as ProcessorFailedError } from './processors-ByDr5POu.js';
6
+ import { a as Catalog } from './catalog-BKS3Yxo6.js';
8
7
  import { ChannelRegistry } from '@dudousxd/nestjs-diagnostics';
9
8
 
10
9
  /**
@@ -30,6 +29,11 @@ declare const AGENT_DURABLE_RUNNER: unique symbol;
30
29
  declare const AGENT_SINK: unique symbol;
31
30
  declare const AGENT_MODEL: unique symbol;
32
31
  declare const AGENT_ROLES_POLICY: unique symbol;
32
+ /**
33
+ * @deprecated Nothing binds or injects this token since the quota rework (#230): `AgentModule`
34
+ * enforces and reports the budget through {@link AGENT_QUOTA_PROVIDER}, configured with
35
+ * `AgentModule.forRoot({ quota })`. Inject `AGENT_QUOTA_PROVIDER` instead. Removed in the next major.
36
+ */
33
37
  declare const AGENT_QUOTA_STORE: unique symbol;
34
38
  declare const AGENT_TOOL_REGISTRY: unique symbol;
35
39
  declare const AGENT_REGISTRY: unique symbol;
@@ -335,11 +339,15 @@ declare function observeTurnFrames(writer: SinkWriter, now?: () => number): Obse
335
339
  declare function withTurnFrames<T extends ModelTurnResult>(result: T, frames: TurnFrameSummary): T;
336
340
 
337
341
  /** The tool step's journaled result: the bare output, or the output plus the components it pushed. */
338
- declare function wrapToolStepOutput(output: unknown, ui: readonly AgentUiComponent[]): unknown;
342
+ declare function wrapToolStepOutput(output: unknown, ui: readonly AgentUiComponent[], text?: string): unknown;
343
+ /** Carry domain refusal across a remote step without losing its type in error serialization. */
344
+ declare function wrapToolPreflightDenied(reason: string): unknown;
339
345
  /** Read a tool step's result back — either shape. */
340
346
  declare function unwrapToolStepOutput(raw: unknown): {
341
347
  output: unknown;
342
348
  ui: AgentUiComponent[];
349
+ preflightDenied?: string;
350
+ text?: string;
343
351
  };
344
352
  type EmitUi = AiToolCtx['emitUi'];
345
353
  /**
@@ -366,6 +374,8 @@ interface UiCollector {
366
374
  declare function createUiCollector(toolCallId: string, write?: (event: AgentStreamEvent) => void | Promise<void>): UiCollector;
367
375
  /** Merge component lists: first-seen order, the last props for each id. */
368
376
  declare function mergeUi(...lists: readonly (readonly AgentUiComponent[] | undefined)[]): AgentUiComponent[];
377
+ /** Escape code units native PostgreSQL/MySQL TEXT cannot store; retain ordinary prose and emoji. */
378
+ declare function escapeUnsafeToolUiText(text: string): string;
369
379
 
370
380
  /**
371
381
  * Decides whether an actor may invoke a tool. The default impl checks the actor's role
@@ -444,7 +454,7 @@ interface QuotaQuery {
444
454
  }
445
455
  /**
446
456
  * The actor's budget across windows — the read behind `GET <base>/quota` and, when the host binds
447
- * one (`AgentModule.forRoot({ quotaProvider })`), the gate a send passes: a report with `blocked`
457
+ * one (`AgentModule.forRoot({ quota })`), the gate a send passes: a report with `blocked`
448
458
  * refuses the turn with `429` before it starts.
449
459
  *
450
460
  * The default reads the usage ledger (`LedgerQuotaProvider` in `@dudousxd/nestjs-agent`); a host
@@ -1131,12 +1141,48 @@ interface AttachmentStagingDescription {
1131
1141
  upload?: 'multipart' | 'resumable';
1132
1142
  }
1133
1143
 
1144
+ /**
1145
+ * What leaves the server about a proposal — the routes, a text decision's answer, AG-UI, the approval
1146
+ * port. The stored row minus what only the worker and the store may hold: the execution and
1147
+ * delivery leases (whose token lets a holder settle the work), the idempotency key the tool's side
1148
+ * effect is keyed on, and the execution address (the original preparation input and the request's
1149
+ * context).
1150
+ */
1151
+ interface ActionProposalView extends Omit<ActionProposal, 'execution' | 'outcomeDelivery' | 'idempotencyKey' | 'preparationInput' | 'executionContext'> {
1152
+ execution: Omit<ActionProposalExecution, 'lease'> | null;
1153
+ outcomeDelivery?: Omit<ActionProposalOutcomeDelivery, 'lease'>;
1154
+ }
1155
+ /** {@link ActionProposalMutationResult} with its proposal as an {@link ActionProposalView}. */
1156
+ interface ActionProposalMutationView extends Omit<ActionProposalMutationResult, 'proposal'> {
1157
+ proposal?: ActionProposalView;
1158
+ }
1159
+ /** The public view of a stored proposal. See {@link ActionProposalView}. */
1160
+ declare function toActionProposalView(proposal: ActionProposal): ActionProposalView;
1161
+ /** The public view of a mutation's answer. See {@link ActionProposalView}. */
1162
+ declare function toActionProposalMutationView(result: ActionProposalMutationResult): ActionProposalMutationView;
1163
+
1134
1164
  /**
1135
1165
  * Console-side HITL decisions. Implemented by the agent runtime (the nestjs package binds it to
1136
1166
  * the same signal path chat approvals use); the dashboard injects it OPTIONALLY — absent = the
1137
1167
  * approvals inbox renders read-only.
1138
1168
  */
1139
1169
  interface AgentApprovalPort {
1170
+ approveActionProposal?(actor: Actor, target: {
1171
+ kind: 'proposal';
1172
+ threadId: string;
1173
+ proposalId: string;
1174
+ }, opts?: {
1175
+ remember?: boolean;
1176
+ decidedVia?: string;
1177
+ }): Promise<ActionProposalMutationView>;
1178
+ rejectActionProposal?(actor: Actor, target: {
1179
+ kind: 'proposal';
1180
+ threadId: string;
1181
+ proposalId: string;
1182
+ }, opts?: {
1183
+ reason?: string;
1184
+ decidedVia?: string;
1185
+ }): Promise<ActionProposalMutationView>;
1140
1186
  /**
1141
1187
  * `remember` approves later calls of the same tool in the same thread; `decidedVia` names the
1142
1188
  * surface the decision came through (`'console'`, `'slack'`, …) and is persisted with the call.
@@ -1153,89 +1199,6 @@ interface AgentApprovalPort {
1153
1199
  }): Promise<void>;
1154
1200
  }
1155
1201
 
1156
- /** The approver that means "the person the run is acting for" — the thread's own actor. */
1157
- declare const REQUESTER_APPROVER = "requester";
1158
- /** The tool a requirement is asked about. `spec` is absent where this process cannot resolve it. */
1159
- interface ApprovalToolRef {
1160
- name: string;
1161
- kind: ToolKind;
1162
- spec?: ToolSpec;
1163
- }
1164
- /** Where the call is being made. */
1165
- interface ApprovalThreadRef {
1166
- threadId: string;
1167
- runId: string;
1168
- agentName?: string;
1169
- }
1170
- /**
1171
- * What an action tool call needs before it runs.
1172
- *
1173
- * - `required: false` → the call runs without asking anyone (it is still recorded as an action).
1174
- * - `approver` → who may decide: {@link REQUESTER_APPROVER} (the thread's own actor — the default)
1175
- * or any other string, which the default {@link ApprovalPolicy.canDecide} reads as a ROLE the
1176
- * decider must hold. Streamed on `approval-requested` and persisted on the call.
1177
- * - `ttlMs` → how long the request stays open. When it lapses the call settles `expired` and the
1178
- * model is told nobody approved it. Absent → it waits indefinitely.
1179
- */
1180
- interface ApprovalRequirement {
1181
- required: boolean;
1182
- approver: string;
1183
- ttlMs?: number;
1184
- }
1185
- /** A decision about to be taken on a call, as {@link ApprovalPolicy.canDecide} sees it. */
1186
- interface ApprovalDecisionRef {
1187
- toolCallId: string;
1188
- /** The approver recorded on the call when it was put to a person. */
1189
- approver: string;
1190
- /** The actorRef the run is acting for — the owner of the call's thread. */
1191
- requesterRef: string;
1192
- }
1193
- /**
1194
- * Who has to approve an action tool call, and for how long the request stays open.
1195
- *
1196
- * Consulted by the LOOP once per `action` call, inside the call's `persist:toolcall` checkpoint — so
1197
- * a durable run reads the answer back on every replay instead of re-deciding it against a policy
1198
- * that may have changed while it was parked. Only `action` calls are asked about: a policy cannot
1199
- * put a `read` behind an approval, and an `ask` (a question set) is always the requester's.
1200
- */
1201
- interface ApprovalPolicy {
1202
- requirementFor(tool: ApprovalToolRef, actor: Actor, thread: ApprovalThreadRef): ApprovalRequirement | Promise<ApprovalRequirement>;
1203
- /**
1204
- * May `actor` settle this call? Checked by the approve/reject routes before a decision is
1205
- * signalled. Absent → {@link defaultCanDecide}: the requester approver means the thread's own
1206
- * actor, anything else is a role the actor must hold. Plug an authz Gate here for abilities.
1207
- */
1208
- canDecide?(actor: Actor, decision: ApprovalDecisionRef): boolean | Promise<boolean>;
1209
- }
1210
- /**
1211
- * The behaviour the lib always had: every `action` call waits on the person who asked, with no
1212
- * expiry.
1213
- */
1214
- declare class DefaultApprovalPolicy implements ApprovalPolicy {
1215
- requirementFor(tool: ApprovalToolRef): ApprovalRequirement;
1216
- }
1217
- /** The default decider rule — see {@link ApprovalPolicy.canDecide}. */
1218
- declare function defaultCanDecide(actor: Actor, decision: ApprovalDecisionRef): boolean;
1219
- /** Resolve whether `actor` may decide, through the policy's own rule when it has one. */
1220
- declare function mayDecideApproval(policy: ApprovalPolicy | undefined, actor: Actor, decision: ApprovalDecisionRef): Promise<boolean>;
1221
- /** The columns a store keeps for one call's approval, however it names them. */
1222
- interface ToolCallApprovalColumns {
1223
- toolCallId: string;
1224
- status: ToolCallStatus;
1225
- approver: string | null | undefined;
1226
- expiresAt: string | Date | null | undefined;
1227
- remember: boolean | null | undefined;
1228
- executedByRef: string | null | undefined;
1229
- decidedVia: string | null | undefined;
1230
- error: string | null | undefined;
1231
- }
1232
- /**
1233
- * Read a tool-call row back as the {@link ToolCallApproval} a thread carries, or `null` for a call
1234
- * no policy put to anyone (no approver recorded). Shared by every store so they agree on the
1235
- * status mapping: a call that ran — or ran and failed — after a decision was APPROVED.
1236
- */
1237
- declare function toolCallApprovalFromRow(row: ToolCallApprovalColumns): ToolCallApproval | null;
1238
-
1239
1202
  /**
1240
1203
  * The pure aggregation core shared by every {@link import('../spi/governance-queries.js').AgentGovernanceQueries}
1241
1204
  * adapter (MikroORM, Drizzle, in-memory). An adapter's only job is the DB-specific row fetch; the
@@ -2553,6 +2516,17 @@ declare class ToolInputInvalidError extends Error {
2553
2516
  readonly issues: readonly StandardSchemaV1.Issue[];
2554
2517
  constructor(toolName: string, issues: readonly StandardSchemaV1.Issue[]);
2555
2518
  }
2519
+ /** An action refused by its current domain state, rather than by a person. */
2520
+ declare class ToolPreflightDeniedError extends Error {
2521
+ readonly toolName: string;
2522
+ readonly reason: string;
2523
+ constructor(toolName: string, reason: string);
2524
+ }
2525
+ /** Trusted preparation or a fresh schema parse changed the approved JSON input. */
2526
+ declare class ToolInputDriftError extends Error {
2527
+ readonly toolName: string;
2528
+ constructor(toolName: string);
2529
+ }
2556
2530
  /**
2557
2531
  * Holds every registered tool and gates invocation.
2558
2532
  *
@@ -2563,6 +2537,10 @@ declare class ToolInputInvalidError extends Error {
2563
2537
  declare class ToolRegistry {
2564
2538
  private readonly entries;
2565
2539
  register(spec: ToolSpec, handler: ToolHandler): void;
2540
+ /** Whether a successful preflight shortcut has UI to journal. */
2541
+ hasPresentation(name: string): boolean;
2542
+ /** Present an already authorized successful domain result without executing its action again. */
2543
+ presentOutput(name: string, output: unknown, ctx: AiToolCtx): Promise<void>;
2566
2544
  has(name: string): boolean;
2567
2545
  /**
2568
2546
  * Give a name back, and report whether it was held. For an importer that registered tools on
@@ -2601,6 +2579,11 @@ declare class ToolRegistry {
2601
2579
  * moved, neither of which went through `definitionsFor` again) and re-parses the input via Zod.
2602
2580
  */
2603
2581
  invoke(name: string, input: unknown, ctx: AiToolCtx, policy: RolesPolicy, options?: InvokeOptions): Promise<unknown>;
2582
+ /** Authorize and validate without executing. The caller journals this result before approval. */
2583
+ prepare(name: string, input: unknown, ctx: AiToolCtx, policy: RolesPolicy, options?: PrepareOptions): Promise<ToolPreflightResult>;
2584
+ /** Expose the single schema parse; snapshotInput opts proposal callers into immutable JSON. */
2585
+ prepareValidated(name: string, input: unknown, ctx: AiToolCtx, policy: RolesPolicy, options?: PrepareOptions): Promise<ToolPreparationResult>;
2586
+ private validated;
2604
2587
  }
2605
2588
  /** Per-call narrowing for {@link ToolRegistry.invoke}. */
2606
2589
  interface InvokeOptions {
@@ -2609,6 +2592,16 @@ interface InvokeOptions {
2609
2592
  * roles policy and `canUse`. Undefined → no such check (every caller predating personas).
2610
2593
  */
2611
2594
  allowedTools?: readonly string[];
2595
+ /** Trusted normalized JSON input. Own-property presence requires comparison even if undefined. */
2596
+ approvedInput?: unknown;
2597
+ }
2598
+ interface PrepareOptions extends InvokeOptions {
2599
+ /** Preserve a detached normalized JSON snapshot and refuse mutation by the prepare hook. */
2600
+ snapshotInput?: boolean;
2601
+ }
2602
+ interface ToolPreparationResult {
2603
+ input: unknown;
2604
+ preflight: ToolPreflightResult;
2612
2605
  }
2613
2606
  /**
2614
2607
  * Default gate: a tool that names `roles` is callable by an actor holding one of them; a tool that
@@ -2617,6 +2610,10 @@ interface InvokeOptions {
2617
2610
  * visitor included, when no resolver is configured); restrict with `@AiTool({ roles })` per tool,
2618
2611
  * `AgentModule.forRoot({ defaultRoles })` module-wide, or a `rolesPolicy` of your own. `action`
2619
2612
  * tools still park on approval either way.
2613
+ *
2614
+ * A tool gated by an `ability` and naming no `roles` is refused: this policy cannot evaluate an
2615
+ * ability, and falling through to the open default would hand the tool to everyone. Bind an
2616
+ * ability-aware policy (`AgentAuthzModule`) to reach it — or give the tool `roles` as well.
2620
2617
  */
2621
2618
  declare class DefaultRolesPolicy implements RolesPolicy {
2622
2619
  readonly defaultRoles: string[];
@@ -2658,7 +2655,27 @@ declare class ClosedRolesPolicy extends DefaultRolesPolicy {
2658
2655
  */
2659
2656
  declare function closeEmptyRoles(inner: RolesPolicy): RolesPolicy;
2660
2657
 
2658
+ type ActionApprovalMode = 'blocking' | 'independent';
2659
+ type ActionProposalTarget = {
2660
+ kind: 'proposal';
2661
+ proposalId: string;
2662
+ };
2663
+ interface ActionProposalReceipt {
2664
+ proposalId: string;
2665
+ status: 'pending';
2666
+ executed: false;
2667
+ }
2668
+ declare function actionProposalReceipt(proposalId: string): ActionProposalReceipt;
2669
+
2670
+ type ResolveToolUiCatalog = (scope: ToolDescribeScope) => Catalog | Promise<Catalog>;
2671
+ interface NegotiatedUiCollector extends UiCollector {
2672
+ text(): string;
2673
+ }
2674
+ declare function createNegotiatedUiCollector(toolCallId: string, scope: ToolDescribeScope, resolveCatalog?: ResolveToolUiCatalog, write?: (event: AgentStreamEvent) => void | Promise<void>): NegotiatedUiCollector;
2675
+
2661
2676
  interface AgentLoopDeps<TOutput = unknown> {
2677
+ actionApprovalMode?: ActionApprovalMode;
2678
+ resolveUiCatalog?: ResolveToolUiCatalog;
2662
2679
  model: ModelProvider;
2663
2680
  store: AgentStore;
2664
2681
  registry: ToolRegistry;
@@ -3188,10 +3205,22 @@ interface AgentToolCallEvent {
3188
3205
  status: string;
3189
3206
  durationMs?: number;
3190
3207
  }
3208
+ /**
3209
+ * A turn refused for budget. Published by the send gate (`429`) and the message queue when a
3210
+ * `QuotaProvider` reports `blocked`, and by the loop's own per-day `QuotaStore` gate. The figures
3211
+ * are the exhausted window's: a window that does not count tokens (a USD-only spend cap) carries no
3212
+ * token figures, never a made-up `0`.
3213
+ */
3191
3214
  interface AgentQuotaExceeded {
3192
3215
  actorId: string;
3193
- usedTokens: number;
3194
- limitTokens: number;
3216
+ /** The window that ran out. Absent from the loop's per-day `QuotaStore` gate. */
3217
+ period?: QuotaPeriod;
3218
+ /** The provider's words for the block, when it gave some. */
3219
+ reason?: string;
3220
+ usedTokens?: number;
3221
+ limitTokens?: number;
3222
+ usedUsd?: number;
3223
+ limitUsd?: number;
3195
3224
  }
3196
3225
  interface AgentRunFinished {
3197
3226
  runId: string;
@@ -3399,6 +3428,51 @@ type AgentDiagnosticKey = `agent:${AgentDiagnosticEvent}`;
3399
3428
  */
3400
3429
  declare function agentDiagnosticKey(event: AgentDiagnosticEvent): AgentDiagnosticKey;
3401
3430
 
3431
+ /** Privileged worker-only discovery; never expose this unscoped capability on public routes. */
3432
+ interface ActionProposalWorkerStore {
3433
+ /** Claim one queued or expired-lease action across scopes; null means no claim was won. */
3434
+ claimNextActionProposal(command: ClaimActionProposal): Promise<ActionProposal | null>;
3435
+ /** Expire at most limit (1..1000) due pending proposals using the store's trusted clock. */
3436
+ expireActionProposals(command: {
3437
+ limit: number;
3438
+ }): Promise<number>;
3439
+ }
3440
+ /** SQL upgrade capability. Run bounded batches after additive DDL and before starting workers. */
3441
+ interface ActionProposalDiscoveryIndexStore {
3442
+ backfillActionProposalDiscoveryIndex(command: {
3443
+ limit: number;
3444
+ }): Promise<number>;
3445
+ }
3446
+
3447
+ /** Reference single-process implementation; durable adapters use the same transitions under CAS. */
3448
+ declare class InMemoryActionProposalStore implements ActionProposalStore, ActionProposalWorkerStore {
3449
+ protected readonly rows: Map<string, ActionProposal>;
3450
+ protected readonly clock: () => number;
3451
+ constructor(options?: ActionProposalStoreOptions);
3452
+ createActionProposal(input: CreateActionProposal): Promise<CreateActionProposalResult>;
3453
+ getActionProposal(scope: ActionProposalScope, id: string): Promise<ActionProposal | null>;
3454
+ listActionProposals(scope: ActionProposalScope, query?: ListActionProposals): Promise<ActionProposal[]>;
3455
+ private mutate;
3456
+ decideActionProposal(scope: ActionProposalScope, id: string, command: ActionProposalDecisionCommand): Promise<ActionProposalMutationResult>;
3457
+ claimActionProposal(scope: ActionProposalScope, id: string, command: ClaimActionProposal): Promise<ActionProposalMutationResult>;
3458
+ extendActionProposalLease(scope: ActionProposalScope, id: string, command: ExtendActionProposalLease): Promise<ActionProposalMutationResult>;
3459
+ settleActionProposal(scope: ActionProposalScope, id: string, command: SettleActionProposal): Promise<ActionProposalMutationResult>;
3460
+ claimNextActionProposal(command: ClaimActionProposal): Promise<ActionProposal | null>;
3461
+ expireActionProposals(command: {
3462
+ limit: number;
3463
+ }): Promise<number>;
3464
+ claimNextActionProposalOutcome(command: ClaimActionProposal): Promise<{
3465
+ outcome: ActionProposalOutcome;
3466
+ lease: ActionProposalOutcomeLease;
3467
+ } | null>;
3468
+ createReplacingActionProposal(input: CreateActionProposal): Promise<CreateActionProposalResult>;
3469
+ supersedeActionProposal(scope: ActionProposalScope, id: string, command: {
3470
+ replacementProposalId: string;
3471
+ actorRef: string;
3472
+ via: string;
3473
+ }): Promise<ActionProposalMutationResult>;
3474
+ }
3475
+
3402
3476
  /** A recorded usage row exposed to the governance read-model (input/output split + thread/day). */
3403
3477
  interface GovernanceUsageRow {
3404
3478
  actorRef: string;
@@ -3484,7 +3558,7 @@ interface GovernanceRunRow {
3484
3558
  parentRunId?: string;
3485
3559
  }
3486
3560
  /** A fully in-memory `AgentStore` for tests and the offline demo. */
3487
- declare class InMemoryAgentStore implements AgentStore, ChatQueueStore {
3561
+ declare class InMemoryAgentStore extends InMemoryActionProposalStore implements AgentStore, ChatQueueStore, ActionProposalOutcomeStore {
3488
3562
  private readonly threads;
3489
3563
  /** Each thread's waiting messages, in run order. */
3490
3564
  private readonly queues;
@@ -3553,6 +3627,8 @@ declare class InMemoryAgentStore implements AgentStore, ChatQueueStore {
3553
3627
  queuePause(threadId: string): Promise<QueuePause | null>;
3554
3628
  setQueuePause(threadId: string, pause: QueuePause | null): Promise<void>;
3555
3629
  private findQueued;
3630
+ getThreadActionProposalScope(threadId: string): Promise<ActionProposalScope | null>;
3631
+ admitActionProposalOutcome(command: ActionProposalOutcomeLease): ReturnType<ActionProposalOutcomeStore['admitActionProposalOutcome']>;
3556
3632
  appendMessage(input: AppendMessageInput): Promise<StoredMessage>;
3557
3633
  setMessageToolResults(messageId: string, results: ToolResult[]): Promise<void>;
3558
3634
  setMessageUi(messageId: string, ui: AgentUiComponent[]): Promise<void>;
@@ -3901,7 +3977,11 @@ interface StreamFrameTable {
3901
3977
  remove(runIds: readonly string[]): Promise<void>;
3902
3978
  /** Runs whose LAST row was written before `cutoff` (epoch-ms). */
3903
3979
  lapsedRuns(cutoff: number): Promise<string[]>;
3904
- /** Is this error a lost race for a `(run_id, seq)` — and nothing else (a missing table, a dead connection)? */
3980
+ /**
3981
+ * Is this error a lost race for a `(run_id, seq)` — a duplicate key, or the database rolling this
3982
+ * writer back as a deadlock victim (InnoDB's way of settling two concurrent `INSERT … SELECT`) —
3983
+ * and nothing else (a missing table, a dead connection)?
3984
+ */
3905
3985
  isUniqueViolation(error: unknown): boolean;
3906
3986
  }
3907
3987
  interface SqlTokenStreamSinkOptions {
@@ -4001,4 +4081,216 @@ declare class SqlTokenStreamSink implements TokenStreamSink {
4001
4081
  private purgeInBackground;
4002
4082
  }
4003
4083
 
4004
- 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 InvokeOptions, 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, Persona, type PersonaAlias, PersonaCatalogEntry, 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, findPersona, gateFollowUps, gateTail, hashConfirmToken, intersectAllowLists, isControlFlowSignal, isReplayIntegrityError, isToolEnabled, loadSkill, mayDecideApproval, memoryForgetVerdict, memoryWriteVerdict, mergeUi, normalizeDelegation, observeTurnFrames, offerMemories, offerSkills, personaCatalogEntry, publishAgentDelegated, publishAgentMemoryResolved, publishAgentMemoryWritten, publishAgentMessage, publishAgentQuotaExceeded, publishAgentRetrieved, publishAgentRunFailed, publishAgentRunFinished, publishAgentRunStarted, publishAgentSkillsResolved, publishAgentToolCall, publishAgentToolRetry, quotaPeriodRange, quotaUsedRatio, quotaWarning, releaseGatedFrames, rememberInputSchema, rememberToolDefinition, repairInstruction, resolveGateLookback, resolveMemoryDigest, resolveOutputGateMode, resolvePersonaAlias, 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 };
4084
+ declare function validateActionProposalCreation(input: CreateActionProposal): void;
4085
+ declare function validateActionProposalListQuery(query?: ListActionProposals): number;
4086
+ /** Canonical JSON snapshots keep replay equality independent of object key insertion order. */
4087
+ declare function canonicalActionProposalJson(value: unknown): string;
4088
+ declare function snapshotActionProposal<T>(value: T): T;
4089
+ declare function actionProposalScopeMatches(row: ActionProposalScope, scope: ActionProposalScope): boolean;
4090
+ declare function initialActionProposal(input: CreateActionProposal, now: number): ActionProposal;
4091
+ declare function actionProposalCreationMatches(row: ActionProposal, input: CreateActionProposal): boolean;
4092
+ declare function transitionActionProposalDecision(row: ActionProposal, command: ActionProposalDecisionCommand, now: number): ActionProposalMutationResult;
4093
+ declare function transitionActionProposalClaim(row: ActionProposal, command: ClaimActionProposal, now: number, token: string): ActionProposalMutationResult;
4094
+ declare function transitionActionProposalLease(row: ActionProposal, command: ExtendActionProposalLease, now: number): ActionProposalMutationResult;
4095
+ declare function transitionActionProposalSettlement(row: ActionProposal, command: SettleActionProposal, now: number): ActionProposalMutationResult;
4096
+ /** Caller must obtain the replacement through the same full scope and persistence authority. */
4097
+ declare function transitionActionProposalSupersession(row: ActionProposal, replacement: ActionProposal, command: {
4098
+ replacementProposalId: string;
4099
+ actorRef: string;
4100
+ via: string;
4101
+ }, now: number): ActionProposalMutationResult;
4102
+
4103
+ /** Trusted producer path: retain the original JSON and the exact data shown for approval. */
4104
+ declare function prepareActionProposal(registry: ToolRegistry, name: string, input: unknown, ctx: AiToolCtx, policy: RolesPolicy, options?: InvokeOptions): Promise<{
4105
+ preparationInput: unknown;
4106
+ input: unknown;
4107
+ preflight: {
4108
+ status: "ready";
4109
+ confirmation?: ToolConfirmation;
4110
+ } | {
4111
+ status: "denied";
4112
+ reason: string;
4113
+ } | {
4114
+ status: "completed";
4115
+ output: unknown;
4116
+ };
4117
+ replacementKey?: string;
4118
+ }>;
4119
+
4120
+ declare function validateActionProposalWorkerClaim(command: ClaimActionProposal, now: number): void;
4121
+ declare function validateActionProposalExpiryBatch(command: {
4122
+ limit: number;
4123
+ }, now: number): void;
4124
+ declare function validateActionProposalDiscoveryIndexBatch(command: {
4125
+ limit: number;
4126
+ }): void;
4127
+
4128
+ /** Resolves current server authority; persisted role snapshots are never execution authority. */
4129
+ interface BackgroundActorResolver {
4130
+ resolve(ref: {
4131
+ actorRef: string;
4132
+ tenantRef: string | null;
4133
+ }): Promise<Actor | null>;
4134
+ }
4135
+
4136
+ declare function attachActionProposalOutcome(row: ActionProposal, now: number, ui?: AgentUiComponent[], text?: string): ActionProposal;
4137
+ declare function claimActionProposalOutcome(row: ActionProposal, command: {
4138
+ workerId: string;
4139
+ leaseMs: number;
4140
+ }, now: number, token: string): ActionProposal | null;
4141
+ declare function actionProposalOutcomeFenceValid(row: ActionProposal, command: ActionProposalOutcomeLease, now: number): boolean;
4142
+ declare function actionProposalOutcomeScope(outcome: ActionProposalOutcome): ActionProposalScope;
4143
+ declare function actionProposalOutcomeText(outcome: ActionProposalOutcome): string;
4144
+
4145
+ interface TextActionProposalCandidate {
4146
+ id: string;
4147
+ decision: ActionProposalDecision;
4148
+ }
4149
+ type TextActionProposalResolution = {
4150
+ status: 'unmatched';
4151
+ } | {
4152
+ status: 'ambiguous';
4153
+ proposalIds: string[];
4154
+ } | {
4155
+ status: 'decision';
4156
+ proposalId: string;
4157
+ decision: 'approved' | 'rejected';
4158
+ remember: boolean;
4159
+ };
4160
+ /**
4161
+ * Recognizes complete, explicit decision messages. This grants no authority: callers must
4162
+ * resolve the authenticated actor and use the normal scoped decision service with via=text.
4163
+ * Never feed model output here or consume an unmatched message as an approval.
4164
+ */
4165
+ declare function resolveTextActionProposalDecision(text: string, proposals: readonly TextActionProposalCandidate[], vocabulary?: TextActionProposalVocabulary): TextActionProposalResolution;
4166
+ type TextActionProposalCommand = {
4167
+ status: 'unmatched';
4168
+ } | {
4169
+ status: 'command';
4170
+ decision: 'approved' | 'rejected';
4171
+ remember: boolean;
4172
+ proposalId?: string;
4173
+ };
4174
+ /**
4175
+ * The words a whole chat message must consist of to decide a proposal by text. Matched
4176
+ * case-insensitively, as the complete message (an optional trailing `.`/`!`, an optional `#ID`).
4177
+ */
4178
+ interface TextActionProposalVocabulary {
4179
+ /** Approve, e.g. `sim`, `yes`. */
4180
+ approve: readonly string[];
4181
+ /** Reject, e.g. `não`, `no`. */
4182
+ reject: readonly string[];
4183
+ /** The phrase after an approve word that also approves later calls of the tool in this thread. */
4184
+ remember: readonly string[];
4185
+ }
4186
+ /**
4187
+ * English. Portuguese ships as {@link ptBrActionProposalText}; any other language through
4188
+ * `AgentModule.forRoot({ actionProposalText })`.
4189
+ */
4190
+ declare const DEFAULT_TEXT_ACTION_PROPOSAL_VOCABULARY: TextActionProposalVocabulary;
4191
+ /** What the agent answers to a text decision. Every field has an English default. */
4192
+ interface TextActionProposalReplies {
4193
+ approved: string;
4194
+ rejected: string;
4195
+ expired: string;
4196
+ /** The proposal could not change (already decided by someone else, superseded, …). */
4197
+ unchanged: string;
4198
+ /** More than one pending proposal could be meant: ask for the `#ID`. */
4199
+ ambiguous(proposalIds: readonly string[]): string;
4200
+ /** Too many pending proposals to pick one without an explicit `#ID`. */
4201
+ tooMany: string;
4202
+ }
4203
+ declare const DEFAULT_TEXT_ACTION_PROPOSAL_REPLIES: TextActionProposalReplies;
4204
+ /** `AgentModule.forRoot({ actionProposalText })`: either part replaces the default it names. */
4205
+ interface TextActionProposalConfig {
4206
+ vocabulary?: Partial<TextActionProposalVocabulary>;
4207
+ replies?: Partial<TextActionProposalReplies>;
4208
+ }
4209
+ /** The reply to a decision the store answered with `result`. */
4210
+ declare function textActionProposalReply(result: Pick<ActionProposalMutationResult, 'status'> & {
4211
+ proposal?: {
4212
+ decision: ActionProposalDecision;
4213
+ };
4214
+ }, decision: 'approved' | 'rejected', replies?: TextActionProposalReplies): string;
4215
+ /** Parse exact consent syntax only. Authentication and target lookup remain the caller's responsibility. */
4216
+ declare function parseTextActionProposalCommand(text: string, vocabulary?: TextActionProposalVocabulary): TextActionProposalCommand;
4217
+ /**
4218
+ * Brazilian Portuguese text decisions — `AgentModule.forRoot({ actionProposalText: ptBrActionProposalText })`.
4219
+ * Commands in Portuguese (English ones still work), replies in Portuguese.
4220
+ */
4221
+ declare const ptBrActionProposalText: Required<TextActionProposalConfig>;
4222
+
4223
+ interface ActionProposalExecutionDeps {
4224
+ registry: ToolRegistry;
4225
+ rolesPolicy: RolesPolicy;
4226
+ allowedTools?: string[];
4227
+ host?: unknown;
4228
+ resolveUiCatalog?: ResolveToolUiCatalog;
4229
+ }
4230
+ interface ActionProposalExecutorOptions {
4231
+ resolver: BackgroundActorResolver;
4232
+ /** Resolve exact recorded agent/persona against current configuration; throw if it disappeared. */
4233
+ resolveExecution(proposal: ActionProposal, actor: Actor): Promise<ActionProposalExecutionDeps>;
4234
+ }
4235
+ type ActionProposalExecutionResult = {
4236
+ status: 'succeeded';
4237
+ result?: unknown;
4238
+ ui: AgentUiComponent[];
4239
+ text?: string;
4240
+ } | {
4241
+ status: 'failed';
4242
+ error: string;
4243
+ ui: AgentUiComponent[];
4244
+ text?: string;
4245
+ };
4246
+ declare class ActionProposalExecutor {
4247
+ private readonly options;
4248
+ constructor(options: ActionProposalExecutorOptions);
4249
+ execute(proposal: ActionProposal): Promise<ActionProposalExecutionResult>;
4250
+ }
4251
+
4252
+ interface ActionProposalWorkerOptions {
4253
+ store: ActionProposalStore & ActionProposalWorkerStore & ActionProposalOutcomeStore;
4254
+ executor: ActionProposalExecutor;
4255
+ workerId: string;
4256
+ pollIntervalMs?: number;
4257
+ leaseMs?: number;
4258
+ maxConcurrency?: number;
4259
+ onError?(error: unknown): void;
4260
+ onSettled?(proposal: ActionProposal): Promise<void>;
4261
+ }
4262
+ declare class ActionProposalWorker {
4263
+ private readonly options;
4264
+ private readonly leaseMs;
4265
+ private readonly pollIntervalMs;
4266
+ private readonly maxConcurrency;
4267
+ private timer?;
4268
+ private stopped;
4269
+ private readonly renewals;
4270
+ private active;
4271
+ constructor(options: ActionProposalWorkerOptions);
4272
+ start(): void;
4273
+ stop(): Promise<void>;
4274
+ runOnce(): Promise<void>;
4275
+ private tick;
4276
+ private execute;
4277
+ }
4278
+
4279
+ type ActionProposalRuntimeStore = AgentStore & ActionProposalStore & ActionProposalWorkerStore & ActionProposalOutcomeStore & ActionProposalSupersessionStore;
4280
+ declare function assertIndependentActionCapabilities(store: AgentStore, resolver: BackgroundActorResolver | undefined): asserts store is ActionProposalRuntimeStore;
4281
+
4282
+ interface FunctionalTool<I = unknown, O = unknown> {
4283
+ spec: ToolSpec;
4284
+ handler: ToolHandler<I, O>;
4285
+ }
4286
+ type FunctionalToolDefinition<I, O> = Omit<ToolSpec, 'inputSchema' | 'kind'> & {
4287
+ input: StandardSchemaV1<unknown, I>;
4288
+ kind?: ToolSpec['kind'];
4289
+ } & ToolHandler<I, O>;
4290
+ /** Framework-independent authoring; every method keeps the author's object as its receiver. */
4291
+ declare function createFunctionalTool<I, O>(definition: FunctionalToolDefinition<I, O>): FunctionalTool<I, O>;
4292
+
4293
+ /** Presentation failures must never cause a successful side effect to be retried. */
4294
+ declare function emitToolPresentations<I, O>(handler: ToolHandler<I, O>, output: O, ctx: AiToolCtx, toolName: string): Promise<void>;
4295
+
4296
+ 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, type ActionApprovalMode, ActionProposal, ActionProposalDecision, ActionProposalDecisionCommand, type ActionProposalDiscoveryIndexStore, ActionProposalExecution, type ActionProposalExecutionDeps, type ActionProposalExecutionResult, ActionProposalExecutor, type ActionProposalExecutorOptions, ActionProposalMutationResult, type ActionProposalMutationView, ActionProposalOutcome, ActionProposalOutcomeDelivery, ActionProposalOutcomeLease, ActionProposalOutcomeStore, type ActionProposalReceipt, type ActionProposalRuntimeStore, ActionProposalScope, ActionProposalStore, ActionProposalStoreOptions, ActionProposalSupersessionStore, type ActionProposalTarget, type ActionProposalView, ActionProposalWorker, type ActionProposalWorkerOptions, type ActionProposalWorkerStore, 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, ApprovalPolicy, type ApprovalWhere, type AttachmentRef, type AttachmentStagingDescription, type AttachmentStagingStore, type BackgroundActorResolver, type BufferedModelTurnResult, type BuildMemoryBlockInput, CONFIRM_JSON_SCHEMA_PROPERTIES, ChatQueueStore, ClaimActionProposal, 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, CreateActionProposal, CreateActionProposalResult, 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, DEFAULT_TEXT_ACTION_PROPOSAL_REPLIES, DEFAULT_TEXT_ACTION_PROPOSAL_VOCABULARY, Decision, DefaultRolesPolicy, type DetachedDelegationOutcome, type DetachedDelegationReceipt, DetachedDelivery, type DetailThreadRef, ElicitationRequest, type EmbeddingProvider, type EmitUi, type EmptyRoles, EnqueueMessageInput, ExtendActionProposalLease, type ForgetMemoryInput, type FrameBuffer, type FunctionalTool, type FunctionalToolDefinition, 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, InMemoryActionProposalStore, InMemoryAgentStore, InMemoryConfirmTokenStore, type IncrementalGate, InputProcessor, type InvokeOptions, ListActionProposals, 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 NegotiatedUiCollector, type ObservedTurnFrames, type OfferMemoriesInput, type OutputGateMode, type OutputGateResult, OutputProcessor, type OverriddenMemory, PageContext, type Passage, type PendingApprovalRow, Persona, type PersonaAlias, PersonaCatalogEntry, type PrepareOptions, 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, 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 ResolveToolUiCatalog, 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, SettleActionProposal, 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 TextActionProposalCandidate, type TextActionProposalCommand, type TextActionProposalConfig, type TextActionProposalReplies, type TextActionProposalResolution, type TextActionProposalVocabulary, type ThreadActivityRow, ThreadDetail, type ThreadMessageRow, type ThreadMeta, type ThreadSpendRow, ThreadSummary, type ThreadUsageRollup, type ThreadWhere, type TokenStreamSink, type ToolCallActivityRow, ToolCallApprovalState, ToolCallOutcome, ToolCallRequest, ToolCallStatus, type ToolCallWhere, ToolConfirmation, ToolDefinition, ToolDescribeScope, ToolDisabledError, ToolForbiddenError, ToolHandler, ToolInputDriftError, ToolInputInvalidError, type ToolKindDeps, ToolNotFoundError, ToolPreflightDeniedError, ToolPreflightResult, type ToolPreparationResult, ToolRegistry, ToolResult, ToolSpec, type ToolStatRow, ToolStepEnvelope, ToolTransientRetrySetting, type TurnFrameSummary, type UiCollector, UpdateThreadInput, UpdateToolCallInput, type UsageTrendPoint, type WindowHistoryOptions, type WithMemoryToolInput, type WriteMemoryInput, actionProposalCreationMatches, actionProposalOutcomeFenceValid, actionProposalOutcomeScope, actionProposalOutcomeText, actionProposalReceipt, actionProposalScopeMatches, actorScope, agentDiagnosticKey, agentFailureCode, assertIndependentActionCapabilities, attachActionProposalOutcome, bucketByActor, bucketByModel, bucketByThread, bucketUsageTrend, buildMemoryBlock, buildSkillsBlock, canActorUseTool, canonicalActionProposalJson, canonicalJson, claimActionProposalOutcome, closeEmptyRoles, compositeSkillProvider, confirmTokenExpiry, createFrameBuffer, createFunctionalTool, createIncrementalGate, createNegotiatedUiCollector, createNoopEmitUi, createUiCollector, dayBoundsUtc, defaultScopeResolver, defineConfirmedTool, detachedDelivered, detachedStarted, detachedUnsettled, emitToolPresentations, escapeUnsafeToolUiText, estimateCost, estimateMessageTokens, exhaustedWindow, exposeStreamErrorDetails, extractJson, filterToolsByAllowList, filterToolsByCanUse, filterToolsByEnabled, filterToolsByRole, findCatalogModel, findPersona, gateFollowUps, gateTail, hashConfirmToken, initialActionProposal, intersectAllowLists, isControlFlowSignal, isReplayIntegrityError, isToolEnabled, loadSkill, memoryForgetVerdict, memoryWriteVerdict, mergeUi, normalizeDelegation, observeTurnFrames, offerMemories, offerSkills, parseTextActionProposalCommand, personaCatalogEntry, prepareActionProposal, ptBrActionProposalText, publishAgentDelegated, publishAgentMemoryResolved, publishAgentMemoryWritten, publishAgentMessage, publishAgentQuotaExceeded, publishAgentRetrieved, publishAgentRunFailed, publishAgentRunFinished, publishAgentRunStarted, publishAgentSkillsResolved, publishAgentToolCall, publishAgentToolRetry, quotaPeriodRange, quotaUsedRatio, quotaWarning, releaseGatedFrames, rememberInputSchema, rememberToolDefinition, repairInstruction, resolveGateLookback, resolveMemoryDigest, resolveOutputGateMode, resolvePersonaAlias, resolveSkillCatalog, resolveTextActionProposalDecision, rollupThreadUsage, runAgentLoop, runInputProcessors, runOutputProcessors, schemaExtensionOf, seedModelPrices, settleAll, settleDeadRun, settleUnsettledDelegation, signConfirmToken, skillInputSchema, skillToolDefinition, skillWriteVerdict, snapshotActionProposal, stampToolKinds, staticModelCatalog, staticSkillProvider, streamFailure, summarizeWithModel, tenantScope, textActionProposalReply, toActionProposalMutationView, toActionProposalView, toolCallContext, traceLlmTurn, traceToolExecution, transitionActionProposalClaim, transitionActionProposalDecision, transitionActionProposalLease, transitionActionProposalSettlement, transitionActionProposalSupersession, truncateDetailContent, unwrapToolStepOutput, validateActionProposalCreation, validateActionProposalDiscoveryIndexBatch, validateActionProposalExpiryBatch, validateActionProposalListQuery, validateActionProposalWorkerClaim, validateStructured, verifyConfirmToken, windowHistory, withAskTool, withConfirmFields, withMemoryTool, withSelectedModel, withSkillTool, withToolTimeout, withTurnFrames, wrapToolPreflightDenied, wrapToolStepOutput, writeMemory };