@dudousxd/nestjs-agent-core 0.21.0 → 0.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.cts CHANGED
@@ -1,5 +1,5 @@
1
- import { M as ModelMessage, a as ToolDefinition, b as ToolCallRequest, c as MessageUsage, d as AgentUiComponent, A as Actor, e as ThreadSummary, f as ThreadDetail, S as StoredMessage, g as ToolResult, h as MessageAttachment, i as ToolCallStatus, U as UsagePurpose, j as ToolSpec, Q as QuotaState, k as AgentRunInput, H as HumanReply, l as ToolKind, m as ToolCallApproval, T as ToolHandler, n as HistoryPolicy, O as OutputProcessor, P as ProcessorContext, I as InputProcessor, o as ProcessedPrompt, p as ModelAnswer, q as PageContext, r as AgentDefinition, s as AgentDelegation, D as DetachedDelivery, t as AiToolCtx, u as PromptBuilder, v as PromptContributor, w as ToolTransientRetrySetting, x as AgentIntake, y as Decision, E as ElicitationRequest, L as LlmStepEnvelope, z as ToolStepEnvelope } from './tool-CwXibnce.cjs';
2
- export { B as ASK_TOOL_DESCRIPTION, C as ASK_TOOL_NAME, F as AgentApprovalRequest, G as AgentApprovalSettlement, J as AgentCatalogEntry, K as AgentHistoryWindow, N as AgentStreamEvent, R as AskToolInput, V as DEFAULT_INCREMENTAL_LOOKBACK_CHARS, W as DEFAULT_INTAKE_PREAMBLE, X as DEFAULT_TOOL_TRANSIENT_RETRY_ATTEMPTS, Y as DEFAULT_TOOL_TRANSIENT_RETRY_BACKOFF_MS, Z as ELICITATION_INPUT_TYPES, _ as ElicitationInput, $ as ElicitationInputType, a0 as ElicitationOption, a1 as ElicitationOutcome, a2 as ElicitationQuestion, a3 as ElicitationReply, a4 as ElicitationResult, a5 as HistoryPolicyContext, a6 as HistorySelection, a7 as HistorySummary, a8 as IncrementalGating, a9 as InvokeWithTransientRetryOptions, aa as MAX_ASK_QUESTIONS, ab as MessageRole, ac as OutputRejectedError, ad as OutputVerdict, ae as ProcessorFailedError, af as PromptContext, ag as QuotaView, ah as ToolCallApprovalStatus, ai as ToolCatalogEntry, aj as ToolConfirmation, ak as ToolPresentation, al as ToolPresentationTone, am as ToolResultField, an as ToolResultView, ao as ToolStepCtx, ap as ToolTransientRetryNumbers, aq as ToolTransientRetryOptions, ar as askInputSchema, as as askToolDefinition, at as decodeStreamEvent, au as encodeStreamEvent, av as invokeWithTransientRetry, aw as isTransientToolError, ax as isTypedQuestion, ay as normalizeElicitationReply, az as questionOptions, aA as readElicitationInput, aB as readElicitationQuestions, aC as renderElicitationAnswers, aD as resolveElicitation, aE as resolveToolTransientRetryNumbers, aF as settleElicitation, aG as validateElicitationAnswer, aH as validateElicitationValue } from './tool-CwXibnce.cjs';
1
+ import { M as ModelMessage, a as ToolDefinition, b as ToolCallRequest, c as MessageUsage, d as AgentUiComponent, e as AiToolCtx, f as AgentStreamEvent, A as Actor, g as ThreadSummary, h as ThreadDetail, S as StoredMessage, i as ToolResult, j as MessageAttachment, k as ToolCallStatus, U as UsagePurpose, l as ToolSpec, Q as QuotaState, m as AgentRunInput, H as HumanReply, n as ToolKind, o as ToolCallApproval, T as ToolHandler, p as HistoryPolicy, O as OutputProcessor, P as ProcessorContext, I as InputProcessor, q as ProcessedPrompt, r as ModelAnswer, s as PageContext, t as AgentDefinition, u as AgentDelegation, D as DetachedDelivery, v as PromptBuilder, w as PromptContributor, x as ToolTransientRetrySetting, y as AgentIntake, z as Decision, E as ElicitationRequest, L as LlmStepEnvelope, B as ToolStepEnvelope } from './tool-BQqFt06V.cjs';
2
+ export { C as ASK_TOOL_DESCRIPTION, F as ASK_TOOL_NAME, G as AgentApprovalRequest, J as AgentApprovalSettlement, K as AgentCatalogEntry, N as AgentHistoryWindow, R as AskToolInput, V as DEFAULT_INCREMENTAL_LOOKBACK_CHARS, W as DEFAULT_INTAKE_PREAMBLE, X as DEFAULT_TOOL_TRANSIENT_RETRY_ATTEMPTS, Y as DEFAULT_TOOL_TRANSIENT_RETRY_BACKOFF_MS, Z as ELICITATION_INPUT_TYPES, _ as ElicitationInput, $ as ElicitationInputType, a0 as ElicitationOption, a1 as ElicitationOutcome, a2 as ElicitationQuestion, a3 as ElicitationReply, a4 as ElicitationResult, a5 as HistoryPolicyContext, a6 as HistorySelection, a7 as HistorySummary, a8 as IncrementalGating, a9 as InvokeWithTransientRetryOptions, aa as MAX_ASK_QUESTIONS, ab as MessageRole, ac as OutputRejectedError, ad as OutputVerdict, ae as ProcessorFailedError, af as PromptContext, ag as QuotaView, ah as ToolCallApprovalStatus, ai as ToolCatalogEntry, aj as ToolConfirmation, ak as ToolPresentation, al as ToolPresentationTone, am as ToolResultField, an as ToolResultView, ao as ToolStepCtx, ap as ToolTransientRetryNumbers, aq as ToolTransientRetryOptions, ar as askInputSchema, as as askToolDefinition, at as decodeStreamEvent, au as encodeStreamEvent, av as invokeWithTransientRetry, aw as isTransientToolError, ax as isTypedQuestion, ay as normalizeElicitationReply, az as questionOptions, aA as readElicitationInput, aB as readElicitationQuestions, aC as renderElicitationAnswers, aD as resolveElicitation, aE as resolveToolTransientRetryNumbers, aF as settleElicitation, aG as validateElicitationAnswer, aH as validateElicitationValue } from './tool-BQqFt06V.cjs';
3
3
  import { StandardSchemaV1 } from '@standard-schema/spec';
4
4
  import { ChannelRegistry } from '@dudousxd/nestjs-diagnostics';
5
5
 
@@ -239,6 +239,33 @@ declare function observeTurnFrames(writer: SinkWriter, now?: () => number): Obse
239
239
  /** Fill what a provider did not report from what its frames showed. A provider's own value wins. */
240
240
  declare function withTurnFrames<T extends ModelTurnResult>(result: T, frames: TurnFrameSummary): T;
241
241
 
242
+ /** The tool step's journaled result: the bare output, or the output plus the components it pushed. */
243
+ declare function wrapToolStepOutput(output: unknown, ui: readonly AgentUiComponent[]): unknown;
244
+ /** Read a tool step's result back — either shape. */
245
+ declare function unwrapToolStepOutput(raw: unknown): {
246
+ output: unknown;
247
+ ui: AgentUiComponent[];
248
+ };
249
+ type EmitUi = NonNullable<AiToolCtx['emitUi']>;
250
+ /** Collects what one tool invocation pushes, streaming each push as it happens. */
251
+ interface UiCollector {
252
+ emit: EmitUi;
253
+ /** Everything pushed so far: first-seen order, last props per id. */
254
+ components(): AgentUiComponent[];
255
+ /**
256
+ * A new ATTEMPT of the same call (a transient retry): numbering restarts, so the retry's pushes
257
+ * reuse — and replace — the ids the failed attempt used.
258
+ */
259
+ restart(): void;
260
+ }
261
+ /**
262
+ * `write` streams one frame; omit it where there is no live stream (the component is still
263
+ * collected and persisted).
264
+ */
265
+ declare function createUiCollector(toolCallId: string, write?: (event: AgentStreamEvent) => void | Promise<void>): UiCollector;
266
+ /** Merge component lists: first-seen order, the last props for each id. */
267
+ declare function mergeUi(...lists: readonly (readonly AgentUiComponent[] | undefined)[]): AgentUiComponent[];
268
+
242
269
  interface CreateThreadInput {
243
270
  actor: Actor;
244
271
  transient?: boolean;
@@ -473,6 +500,17 @@ interface AgentStore {
473
500
  * fail to compile instead.
474
501
  */
475
502
  setMessageToolResults(messageId: string, results: ToolResult[]): Promise<void>;
503
+ /**
504
+ * Replace the components persisted on an already-appended message (see {@link StoredMessage.ui}).
505
+ * The loop calls it once per step, after the step's tools ran, with every component the step
506
+ * showed — the model turn's own `ui` frames first, then what its tools pushed through
507
+ * `ctx.emitUi`, in call order, deduplicated by `id`. A full replacement, never an append, so a
508
+ * repeated call writes the same value.
509
+ *
510
+ * OPTIONAL: a store without it still streams tool-pushed components live; a reload then shows
511
+ * only the ones the model turn itself produced.
512
+ */
513
+ setMessageUi?(messageId: string, ui: AgentUiComponent[]): Promise<void>;
476
514
  truncateFrom(threadId: string, messageId: string): Promise<void>;
477
515
  recordToolCall(input: RecordToolCallInput): Promise<void>;
478
516
  updateToolCall(input: UpdateToolCallInput): Promise<void>;
@@ -3293,4 +3331,4 @@ type AgentDiagnosticKey = `agent:${AgentDiagnosticEvent}`;
3293
3331
  */
3294
3332
  declare function agentDiagnosticKey(event: AgentDiagnosticEvent): AgentDiagnosticKey;
3295
3333
 
3296
- 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_OPTIONS, AGENT_PRICING_STORE, AGENT_PROMPT_CONTRIBUTORS, AGENT_QUOTA_STORE, AGENT_REGISTRY, AGENT_RETRIEVER, AGENT_ROLES_POLICY, AGENT_RUNNER, AGENT_SINK, AGENT_SKILLS, AGENT_SKILL_SOURCES, AGENT_SPAN_EVENTS, AGENT_STORE, AGENT_TOOL_REGISTRY, APPROVAL_EXPIRED_REASON, Actor, type ActorDirectory, type ActorResolver, type ActorSpendRow, type AgentApprovalPort, AgentDefinition, type AgentDelegated, AgentDelegation, type AgentDiagnosticEvent, type AgentDiagnosticKey, type AgentFollowUpsSpan, type AgentGovernanceQueries, AgentIntake, type AgentLlmTurnSpan, type AgentLoopDeps, type AgentLoopHooks, type AgentLoopResult, type AgentMemoryResolved, type AgentMemoryWritten, type AgentMessageEvent, type AgentPricingStore, type AgentQuotaExceeded, AgentRegistry, type AgentRetrievalSpan, type AgentRetrieved, type AgentRunFailed, type AgentRunFinished, AgentRunInput, type AgentRunStarted, type AgentRunner, type AgentSkillsResolved, type AgentSpanEvent, type AgentStore, AgentStreamError, type AgentStructuredOutputSpan, type AgentToolCallEvent, type AgentToolExecutionSpan, type AgentToolRetry, AgentUiComponent, AiToolCtx, type AppendMessageInput, type ApprovalDecisionRef, type ApprovalPolicy, type ApprovalRequirement, type ApprovalThreadRef, type ApprovalToolRef, type ApprovalWhere, type AttachmentRef, type AttachmentStagingStore, type BufferedModelTurnResult, type BuildMemoryBlockInput, type CostUsage, type CreateThreadInput, type CurrentModelPrice, DEFAULT_HISTORY_SUMMARY_INSTRUCTION, DEFAULT_MAX_FACT_CHARS, DEFAULT_MAX_MEMORIES, DEFAULT_MAX_SKILLS, DEFAULT_REFUSAL_REASON, DEFAULT_STRUCTURED_OUTPUT_INSTRUCTION, Decision, DefaultApprovalPolicy, DefaultRolesPolicy, type DetachedDelegationOutcome, type DetachedDelegationReceipt, DetachedDelivery, type DetailThreadRef, ElicitationRequest, type EmbeddingProvider, type ForgetMemoryInput, type FrameBuffer, GLOBAL_SCOPE, type GovernancePage, type GovernancePageQuery, type GovernanceRange, type GovernanceRunDetail, type GovernanceThreadDetail, type GovernanceThreadDetailQuery, type GovernanceUsageInput, HistoryPolicy, HumanReply, type IncrementalGate, InputProcessor, type ListMemoriesInput, type ListSkillsInput, type ListStagedAttachmentsInput, LlmStepEnvelope, type LoadSkillInput, type MemoryAuthor, type MemoryConfig, type MemoryDigest, type MemoryDigestEntry, type MemoryFact, type MemoryForgetRequest, type MemoryOrigin, type MemoryProvider, type MemoryRecord, type MemoryVerdict, type MemoryWriteOutcome, type MemoryWriteRequest, MessageAttachment, MessageUsage, ModelAnswer, ModelMessage, type ModelPrice, type ModelPriceInput, type ModelProvider, type ModelSpendRow, type ModelTurnArgs, type ModelTurnResult, type ObservedTurnFrames, type OfferMemoriesInput, type OutputGateMode, type OutputGateResult, OutputProcessor, type OverriddenMemory, PageContext, type Passage, type PendingApprovalRow, ProcessedPrompt, ProcessorContext, PromptBuilder, PromptContributor, QuotaExceededError, QuotaState, type QuotaStore, REMEMBER_TOOL_DESCRIPTION, REMEMBER_TOOL_NAME, REQUESTER_APPROVER, type RecentRunRow, type RecordRunEndInput, type RecordRunStartInput, type RecordToolCallInput, type RecordUsageInput, type RememberToolInput, type RerankOptions, type Reranker, type ResolveAttachmentInput, type ResolveMemoryDigestInput, type ResolvedDelegation, type RetrieveOptions, type Retriever, type RolesPolicy, type RunAgentBreakdownRow, RunCancelledError, type RunErrorBreakdownRow, type RunMetrics, type RunToolCallRow, type RunTrendPoint, type RunWhere, SKILL_TOOL_DESCRIPTION, SKILL_TOOL_NAME, type ScopeContext, type ScopeResolver, type SearchMemoriesInput, type SettledTask, type SinkWriter, type Skill, type SkillAuthor, type SkillCatalogEntry, type SkillContext, type SkillLoadOutcome, type SkillOffer, type SkillProvider, type SkillSummary, type SkillToolInput, type SkillWriteRequest, type SkillWriteVerdict, type SkillsConfig, type StageAttachmentInput, type StagedAttachment, type StoreMemoryInput, StoredMessage, type StreamError, type StructuredOutcome, StructuredOutputError, THREAD_DETAIL_CONTENT_CHARS, type ThreadActivityRow, ThreadDetail, type ThreadMessageRow, type ThreadMeta, type ThreadSpendRow, ThreadSummary, type ThreadTurnPage, type ThreadTurnQuery, type ThreadTurnReader, type ThreadUsageRollup, type ThreadWhere, type TokenStreamSink, type ToolCallActivityRow, ToolCallApproval, type ToolCallApprovalColumns, type ToolCallApprovalState, ToolCallRequest, ToolCallStatus, type ToolCallWhere, ToolDefinition, ToolDisabledError, ToolForbiddenError, ToolHandler, ToolInputInvalidError, ToolKind, type ToolKindDeps, ToolNotFoundError, ToolRegistry, ToolResult, ToolSpec, type ToolStatRow, ToolStepEnvelope, ToolTransientRetrySetting, type TurnFrameSummary, type UpdateThreadInput, type UpdateToolCallInput, UsagePurpose, type UsageTrendPoint, type WindowHistoryOptions, type WithMemoryToolInput, type WriteMemoryInput, actorScope, agentDiagnosticKey, agentFailureCode, bucketByActor, bucketByModel, bucketByThread, bucketUsageTrend, buildMemoryBlock, buildSkillsBlock, canActorUseTool, compositeSkillProvider, createFrameBuffer, createIncrementalGate, dayBoundsUtc, defaultCanDecide, defaultScopeResolver, detachedDelivered, detachedStarted, detachedUnsettled, estimateCost, estimateMessageTokens, extractJson, filterToolsByAllowList, filterToolsByCanUse, filterToolsByEnabled, filterToolsByRole, gateFollowUps, gateTail, isControlFlowSignal, isReplayIntegrityError, isToolEnabled, loadSkill, mayDecideApproval, memoryForgetVerdict, memoryWriteVerdict, normalizeDelegation, observeTurnFrames, offerMemories, offerSkills, publishAgentDelegated, publishAgentMemoryResolved, publishAgentMemoryWritten, publishAgentMessage, publishAgentQuotaExceeded, publishAgentRetrieved, publishAgentRunFailed, publishAgentRunFinished, publishAgentRunStarted, publishAgentSkillsResolved, publishAgentToolCall, publishAgentToolRetry, releaseGatedFrames, rememberInputSchema, rememberToolDefinition, repairInstruction, resolveGateLookback, resolveMemoryDigest, resolveOutputGateMode, resolveSkillCatalog, rollupThreadUsage, runAgentLoop, runInputProcessors, runOutputProcessors, seedModelPrices, settleAll, settleUnsettledDelegation, skillInputSchema, skillToolDefinition, skillWriteVerdict, stampToolKinds, staticSkillProvider, summarizeWithModel, tenantScope, toolCallApprovalFromRow, traceLlmTurn, traceToolExecution, truncateDetailContent, validateStructured, windowHistory, withAskTool, withMemoryTool, withSkillTool, withToolTimeout, withTurnFrames, writeMemory };
3334
+ 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_OPTIONS, AGENT_PRICING_STORE, AGENT_PROMPT_CONTRIBUTORS, AGENT_QUOTA_STORE, AGENT_REGISTRY, AGENT_RETRIEVER, AGENT_ROLES_POLICY, AGENT_RUNNER, AGENT_SINK, AGENT_SKILLS, AGENT_SKILL_SOURCES, AGENT_SPAN_EVENTS, AGENT_STORE, AGENT_TOOL_REGISTRY, APPROVAL_EXPIRED_REASON, Actor, type ActorDirectory, type ActorResolver, type ActorSpendRow, type AgentApprovalPort, AgentDefinition, type AgentDelegated, AgentDelegation, type AgentDiagnosticEvent, type AgentDiagnosticKey, type AgentFollowUpsSpan, type AgentGovernanceQueries, AgentIntake, type AgentLlmTurnSpan, type AgentLoopDeps, type AgentLoopHooks, type AgentLoopResult, type AgentMemoryResolved, type AgentMemoryWritten, type AgentMessageEvent, type AgentPricingStore, type AgentQuotaExceeded, AgentRegistry, type AgentRetrievalSpan, type AgentRetrieved, type AgentRunFailed, type AgentRunFinished, AgentRunInput, type AgentRunStarted, type AgentRunner, type AgentSkillsResolved, type AgentSpanEvent, type AgentStore, AgentStreamError, AgentStreamEvent, type AgentStructuredOutputSpan, type AgentToolCallEvent, type AgentToolExecutionSpan, type AgentToolRetry, AgentUiComponent, AiToolCtx, type AppendMessageInput, type ApprovalDecisionRef, type ApprovalPolicy, type ApprovalRequirement, type ApprovalThreadRef, type ApprovalToolRef, type ApprovalWhere, type AttachmentRef, type AttachmentStagingStore, type BufferedModelTurnResult, type BuildMemoryBlockInput, type CostUsage, type CreateThreadInput, type CurrentModelPrice, DEFAULT_HISTORY_SUMMARY_INSTRUCTION, DEFAULT_MAX_FACT_CHARS, DEFAULT_MAX_MEMORIES, DEFAULT_MAX_SKILLS, DEFAULT_REFUSAL_REASON, DEFAULT_STRUCTURED_OUTPUT_INSTRUCTION, Decision, DefaultApprovalPolicy, DefaultRolesPolicy, type DetachedDelegationOutcome, type DetachedDelegationReceipt, DetachedDelivery, type DetailThreadRef, ElicitationRequest, type EmbeddingProvider, type EmitUi, type ForgetMemoryInput, type FrameBuffer, GLOBAL_SCOPE, type GovernancePage, type GovernancePageQuery, type GovernanceRange, type GovernanceRunDetail, type GovernanceThreadDetail, type GovernanceThreadDetailQuery, type GovernanceUsageInput, HistoryPolicy, HumanReply, type IncrementalGate, InputProcessor, type ListMemoriesInput, type ListSkillsInput, type ListStagedAttachmentsInput, LlmStepEnvelope, type LoadSkillInput, type MemoryAuthor, type MemoryConfig, type MemoryDigest, type MemoryDigestEntry, type MemoryFact, type MemoryForgetRequest, type MemoryOrigin, type MemoryProvider, type MemoryRecord, type MemoryVerdict, type MemoryWriteOutcome, type MemoryWriteRequest, MessageAttachment, MessageUsage, ModelAnswer, ModelMessage, type ModelPrice, type ModelPriceInput, type ModelProvider, type ModelSpendRow, type ModelTurnArgs, type ModelTurnResult, type ObservedTurnFrames, type OfferMemoriesInput, type OutputGateMode, type OutputGateResult, OutputProcessor, type OverriddenMemory, PageContext, type Passage, type PendingApprovalRow, ProcessedPrompt, ProcessorContext, PromptBuilder, PromptContributor, QuotaExceededError, QuotaState, type QuotaStore, REMEMBER_TOOL_DESCRIPTION, REMEMBER_TOOL_NAME, REQUESTER_APPROVER, type RecentRunRow, type RecordRunEndInput, type RecordRunStartInput, type RecordToolCallInput, type RecordUsageInput, type RememberToolInput, type RerankOptions, type Reranker, type ResolveAttachmentInput, type ResolveMemoryDigestInput, type ResolvedDelegation, type RetrieveOptions, type Retriever, type RolesPolicy, type RunAgentBreakdownRow, RunCancelledError, type RunErrorBreakdownRow, type RunMetrics, type RunToolCallRow, type RunTrendPoint, type RunWhere, SKILL_TOOL_DESCRIPTION, SKILL_TOOL_NAME, type ScopeContext, type ScopeResolver, type SearchMemoriesInput, type SettledTask, type SinkWriter, type Skill, type SkillAuthor, type SkillCatalogEntry, type SkillContext, type SkillLoadOutcome, type SkillOffer, type SkillProvider, type SkillSummary, type SkillToolInput, type SkillWriteRequest, type SkillWriteVerdict, type SkillsConfig, type StageAttachmentInput, type StagedAttachment, type StoreMemoryInput, StoredMessage, type StreamError, type StructuredOutcome, StructuredOutputError, THREAD_DETAIL_CONTENT_CHARS, type ThreadActivityRow, ThreadDetail, type ThreadMessageRow, type ThreadMeta, type ThreadSpendRow, ThreadSummary, type ThreadTurnPage, type ThreadTurnQuery, type ThreadTurnReader, type ThreadUsageRollup, type ThreadWhere, type TokenStreamSink, type ToolCallActivityRow, ToolCallApproval, type ToolCallApprovalColumns, type ToolCallApprovalState, ToolCallRequest, ToolCallStatus, type ToolCallWhere, ToolDefinition, ToolDisabledError, ToolForbiddenError, ToolHandler, ToolInputInvalidError, ToolKind, type ToolKindDeps, ToolNotFoundError, ToolRegistry, ToolResult, ToolSpec, type ToolStatRow, ToolStepEnvelope, ToolTransientRetrySetting, type TurnFrameSummary, type UiCollector, type UpdateThreadInput, type UpdateToolCallInput, UsagePurpose, type UsageTrendPoint, type WindowHistoryOptions, type WithMemoryToolInput, type WriteMemoryInput, actorScope, agentDiagnosticKey, agentFailureCode, bucketByActor, bucketByModel, bucketByThread, bucketUsageTrend, buildMemoryBlock, buildSkillsBlock, canActorUseTool, compositeSkillProvider, createFrameBuffer, createIncrementalGate, createUiCollector, dayBoundsUtc, defaultCanDecide, defaultScopeResolver, detachedDelivered, detachedStarted, detachedUnsettled, estimateCost, estimateMessageTokens, extractJson, filterToolsByAllowList, filterToolsByCanUse, filterToolsByEnabled, filterToolsByRole, gateFollowUps, gateTail, isControlFlowSignal, isReplayIntegrityError, isToolEnabled, loadSkill, mayDecideApproval, memoryForgetVerdict, memoryWriteVerdict, mergeUi, normalizeDelegation, observeTurnFrames, offerMemories, offerSkills, publishAgentDelegated, publishAgentMemoryResolved, publishAgentMemoryWritten, publishAgentMessage, publishAgentQuotaExceeded, publishAgentRetrieved, publishAgentRunFailed, publishAgentRunFinished, publishAgentRunStarted, publishAgentSkillsResolved, publishAgentToolCall, publishAgentToolRetry, releaseGatedFrames, rememberInputSchema, rememberToolDefinition, repairInstruction, resolveGateLookback, resolveMemoryDigest, resolveOutputGateMode, resolveSkillCatalog, rollupThreadUsage, runAgentLoop, runInputProcessors, runOutputProcessors, seedModelPrices, settleAll, settleUnsettledDelegation, skillInputSchema, skillToolDefinition, skillWriteVerdict, stampToolKinds, staticSkillProvider, summarizeWithModel, tenantScope, toolCallApprovalFromRow, traceLlmTurn, traceToolExecution, truncateDetailContent, unwrapToolStepOutput, validateStructured, windowHistory, withAskTool, withMemoryTool, withSkillTool, withToolTimeout, withTurnFrames, wrapToolStepOutput, writeMemory };
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { M as ModelMessage, a as ToolDefinition, b as ToolCallRequest, c as MessageUsage, d as AgentUiComponent, A as Actor, e as ThreadSummary, f as ThreadDetail, S as StoredMessage, g as ToolResult, h as MessageAttachment, i as ToolCallStatus, U as UsagePurpose, j as ToolSpec, Q as QuotaState, k as AgentRunInput, H as HumanReply, l as ToolKind, m as ToolCallApproval, T as ToolHandler, n as HistoryPolicy, O as OutputProcessor, P as ProcessorContext, I as InputProcessor, o as ProcessedPrompt, p as ModelAnswer, q as PageContext, r as AgentDefinition, s as AgentDelegation, D as DetachedDelivery, t as AiToolCtx, u as PromptBuilder, v as PromptContributor, w as ToolTransientRetrySetting, x as AgentIntake, y as Decision, E as ElicitationRequest, L as LlmStepEnvelope, z as ToolStepEnvelope } from './tool-CwXibnce.js';
2
- export { B as ASK_TOOL_DESCRIPTION, C as ASK_TOOL_NAME, F as AgentApprovalRequest, G as AgentApprovalSettlement, J as AgentCatalogEntry, K as AgentHistoryWindow, N as AgentStreamEvent, R as AskToolInput, V as DEFAULT_INCREMENTAL_LOOKBACK_CHARS, W as DEFAULT_INTAKE_PREAMBLE, X as DEFAULT_TOOL_TRANSIENT_RETRY_ATTEMPTS, Y as DEFAULT_TOOL_TRANSIENT_RETRY_BACKOFF_MS, Z as ELICITATION_INPUT_TYPES, _ as ElicitationInput, $ as ElicitationInputType, a0 as ElicitationOption, a1 as ElicitationOutcome, a2 as ElicitationQuestion, a3 as ElicitationReply, a4 as ElicitationResult, a5 as HistoryPolicyContext, a6 as HistorySelection, a7 as HistorySummary, a8 as IncrementalGating, a9 as InvokeWithTransientRetryOptions, aa as MAX_ASK_QUESTIONS, ab as MessageRole, ac as OutputRejectedError, ad as OutputVerdict, ae as ProcessorFailedError, af as PromptContext, ag as QuotaView, ah as ToolCallApprovalStatus, ai as ToolCatalogEntry, aj as ToolConfirmation, ak as ToolPresentation, al as ToolPresentationTone, am as ToolResultField, an as ToolResultView, ao as ToolStepCtx, ap as ToolTransientRetryNumbers, aq as ToolTransientRetryOptions, ar as askInputSchema, as as askToolDefinition, at as decodeStreamEvent, au as encodeStreamEvent, av as invokeWithTransientRetry, aw as isTransientToolError, ax as isTypedQuestion, ay as normalizeElicitationReply, az as questionOptions, aA as readElicitationInput, aB as readElicitationQuestions, aC as renderElicitationAnswers, aD as resolveElicitation, aE as resolveToolTransientRetryNumbers, aF as settleElicitation, aG as validateElicitationAnswer, aH as validateElicitationValue } from './tool-CwXibnce.js';
1
+ import { M as ModelMessage, a as ToolDefinition, b as ToolCallRequest, c as MessageUsage, d as AgentUiComponent, e as AiToolCtx, f as AgentStreamEvent, A as Actor, g as ThreadSummary, h as ThreadDetail, S as StoredMessage, i as ToolResult, j as MessageAttachment, k as ToolCallStatus, U as UsagePurpose, l as ToolSpec, Q as QuotaState, m as AgentRunInput, H as HumanReply, n as ToolKind, o as ToolCallApproval, T as ToolHandler, p as HistoryPolicy, O as OutputProcessor, P as ProcessorContext, I as InputProcessor, q as ProcessedPrompt, r as ModelAnswer, s as PageContext, t as AgentDefinition, u as AgentDelegation, D as DetachedDelivery, v as PromptBuilder, w as PromptContributor, x as ToolTransientRetrySetting, y as AgentIntake, z as Decision, E as ElicitationRequest, L as LlmStepEnvelope, B as ToolStepEnvelope } from './tool-BQqFt06V.js';
2
+ export { C as ASK_TOOL_DESCRIPTION, F as ASK_TOOL_NAME, G as AgentApprovalRequest, J as AgentApprovalSettlement, K as AgentCatalogEntry, N as AgentHistoryWindow, R as AskToolInput, V as DEFAULT_INCREMENTAL_LOOKBACK_CHARS, W as DEFAULT_INTAKE_PREAMBLE, X as DEFAULT_TOOL_TRANSIENT_RETRY_ATTEMPTS, Y as DEFAULT_TOOL_TRANSIENT_RETRY_BACKOFF_MS, Z as ELICITATION_INPUT_TYPES, _ as ElicitationInput, $ as ElicitationInputType, a0 as ElicitationOption, a1 as ElicitationOutcome, a2 as ElicitationQuestion, a3 as ElicitationReply, a4 as ElicitationResult, a5 as HistoryPolicyContext, a6 as HistorySelection, a7 as HistorySummary, a8 as IncrementalGating, a9 as InvokeWithTransientRetryOptions, aa as MAX_ASK_QUESTIONS, ab as MessageRole, ac as OutputRejectedError, ad as OutputVerdict, ae as ProcessorFailedError, af as PromptContext, ag as QuotaView, ah as ToolCallApprovalStatus, ai as ToolCatalogEntry, aj as ToolConfirmation, ak as ToolPresentation, al as ToolPresentationTone, am as ToolResultField, an as ToolResultView, ao as ToolStepCtx, ap as ToolTransientRetryNumbers, aq as ToolTransientRetryOptions, ar as askInputSchema, as as askToolDefinition, at as decodeStreamEvent, au as encodeStreamEvent, av as invokeWithTransientRetry, aw as isTransientToolError, ax as isTypedQuestion, ay as normalizeElicitationReply, az as questionOptions, aA as readElicitationInput, aB as readElicitationQuestions, aC as renderElicitationAnswers, aD as resolveElicitation, aE as resolveToolTransientRetryNumbers, aF as settleElicitation, aG as validateElicitationAnswer, aH as validateElicitationValue } from './tool-BQqFt06V.js';
3
3
  import { StandardSchemaV1 } from '@standard-schema/spec';
4
4
  import { ChannelRegistry } from '@dudousxd/nestjs-diagnostics';
5
5
 
@@ -239,6 +239,33 @@ declare function observeTurnFrames(writer: SinkWriter, now?: () => number): Obse
239
239
  /** Fill what a provider did not report from what its frames showed. A provider's own value wins. */
240
240
  declare function withTurnFrames<T extends ModelTurnResult>(result: T, frames: TurnFrameSummary): T;
241
241
 
242
+ /** The tool step's journaled result: the bare output, or the output plus the components it pushed. */
243
+ declare function wrapToolStepOutput(output: unknown, ui: readonly AgentUiComponent[]): unknown;
244
+ /** Read a tool step's result back — either shape. */
245
+ declare function unwrapToolStepOutput(raw: unknown): {
246
+ output: unknown;
247
+ ui: AgentUiComponent[];
248
+ };
249
+ type EmitUi = NonNullable<AiToolCtx['emitUi']>;
250
+ /** Collects what one tool invocation pushes, streaming each push as it happens. */
251
+ interface UiCollector {
252
+ emit: EmitUi;
253
+ /** Everything pushed so far: first-seen order, last props per id. */
254
+ components(): AgentUiComponent[];
255
+ /**
256
+ * A new ATTEMPT of the same call (a transient retry): numbering restarts, so the retry's pushes
257
+ * reuse — and replace — the ids the failed attempt used.
258
+ */
259
+ restart(): void;
260
+ }
261
+ /**
262
+ * `write` streams one frame; omit it where there is no live stream (the component is still
263
+ * collected and persisted).
264
+ */
265
+ declare function createUiCollector(toolCallId: string, write?: (event: AgentStreamEvent) => void | Promise<void>): UiCollector;
266
+ /** Merge component lists: first-seen order, the last props for each id. */
267
+ declare function mergeUi(...lists: readonly (readonly AgentUiComponent[] | undefined)[]): AgentUiComponent[];
268
+
242
269
  interface CreateThreadInput {
243
270
  actor: Actor;
244
271
  transient?: boolean;
@@ -473,6 +500,17 @@ interface AgentStore {
473
500
  * fail to compile instead.
474
501
  */
475
502
  setMessageToolResults(messageId: string, results: ToolResult[]): Promise<void>;
503
+ /**
504
+ * Replace the components persisted on an already-appended message (see {@link StoredMessage.ui}).
505
+ * The loop calls it once per step, after the step's tools ran, with every component the step
506
+ * showed — the model turn's own `ui` frames first, then what its tools pushed through
507
+ * `ctx.emitUi`, in call order, deduplicated by `id`. A full replacement, never an append, so a
508
+ * repeated call writes the same value.
509
+ *
510
+ * OPTIONAL: a store without it still streams tool-pushed components live; a reload then shows
511
+ * only the ones the model turn itself produced.
512
+ */
513
+ setMessageUi?(messageId: string, ui: AgentUiComponent[]): Promise<void>;
476
514
  truncateFrom(threadId: string, messageId: string): Promise<void>;
477
515
  recordToolCall(input: RecordToolCallInput): Promise<void>;
478
516
  updateToolCall(input: UpdateToolCallInput): Promise<void>;
@@ -3293,4 +3331,4 @@ type AgentDiagnosticKey = `agent:${AgentDiagnosticEvent}`;
3293
3331
  */
3294
3332
  declare function agentDiagnosticKey(event: AgentDiagnosticEvent): AgentDiagnosticKey;
3295
3333
 
3296
- 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_OPTIONS, AGENT_PRICING_STORE, AGENT_PROMPT_CONTRIBUTORS, AGENT_QUOTA_STORE, AGENT_REGISTRY, AGENT_RETRIEVER, AGENT_ROLES_POLICY, AGENT_RUNNER, AGENT_SINK, AGENT_SKILLS, AGENT_SKILL_SOURCES, AGENT_SPAN_EVENTS, AGENT_STORE, AGENT_TOOL_REGISTRY, APPROVAL_EXPIRED_REASON, Actor, type ActorDirectory, type ActorResolver, type ActorSpendRow, type AgentApprovalPort, AgentDefinition, type AgentDelegated, AgentDelegation, type AgentDiagnosticEvent, type AgentDiagnosticKey, type AgentFollowUpsSpan, type AgentGovernanceQueries, AgentIntake, type AgentLlmTurnSpan, type AgentLoopDeps, type AgentLoopHooks, type AgentLoopResult, type AgentMemoryResolved, type AgentMemoryWritten, type AgentMessageEvent, type AgentPricingStore, type AgentQuotaExceeded, AgentRegistry, type AgentRetrievalSpan, type AgentRetrieved, type AgentRunFailed, type AgentRunFinished, AgentRunInput, type AgentRunStarted, type AgentRunner, type AgentSkillsResolved, type AgentSpanEvent, type AgentStore, AgentStreamError, type AgentStructuredOutputSpan, type AgentToolCallEvent, type AgentToolExecutionSpan, type AgentToolRetry, AgentUiComponent, AiToolCtx, type AppendMessageInput, type ApprovalDecisionRef, type ApprovalPolicy, type ApprovalRequirement, type ApprovalThreadRef, type ApprovalToolRef, type ApprovalWhere, type AttachmentRef, type AttachmentStagingStore, type BufferedModelTurnResult, type BuildMemoryBlockInput, type CostUsage, type CreateThreadInput, type CurrentModelPrice, DEFAULT_HISTORY_SUMMARY_INSTRUCTION, DEFAULT_MAX_FACT_CHARS, DEFAULT_MAX_MEMORIES, DEFAULT_MAX_SKILLS, DEFAULT_REFUSAL_REASON, DEFAULT_STRUCTURED_OUTPUT_INSTRUCTION, Decision, DefaultApprovalPolicy, DefaultRolesPolicy, type DetachedDelegationOutcome, type DetachedDelegationReceipt, DetachedDelivery, type DetailThreadRef, ElicitationRequest, type EmbeddingProvider, type ForgetMemoryInput, type FrameBuffer, GLOBAL_SCOPE, type GovernancePage, type GovernancePageQuery, type GovernanceRange, type GovernanceRunDetail, type GovernanceThreadDetail, type GovernanceThreadDetailQuery, type GovernanceUsageInput, HistoryPolicy, HumanReply, type IncrementalGate, InputProcessor, type ListMemoriesInput, type ListSkillsInput, type ListStagedAttachmentsInput, LlmStepEnvelope, type LoadSkillInput, type MemoryAuthor, type MemoryConfig, type MemoryDigest, type MemoryDigestEntry, type MemoryFact, type MemoryForgetRequest, type MemoryOrigin, type MemoryProvider, type MemoryRecord, type MemoryVerdict, type MemoryWriteOutcome, type MemoryWriteRequest, MessageAttachment, MessageUsage, ModelAnswer, ModelMessage, type ModelPrice, type ModelPriceInput, type ModelProvider, type ModelSpendRow, type ModelTurnArgs, type ModelTurnResult, type ObservedTurnFrames, type OfferMemoriesInput, type OutputGateMode, type OutputGateResult, OutputProcessor, type OverriddenMemory, PageContext, type Passage, type PendingApprovalRow, ProcessedPrompt, ProcessorContext, PromptBuilder, PromptContributor, QuotaExceededError, QuotaState, type QuotaStore, REMEMBER_TOOL_DESCRIPTION, REMEMBER_TOOL_NAME, REQUESTER_APPROVER, type RecentRunRow, type RecordRunEndInput, type RecordRunStartInput, type RecordToolCallInput, type RecordUsageInput, type RememberToolInput, type RerankOptions, type Reranker, type ResolveAttachmentInput, type ResolveMemoryDigestInput, type ResolvedDelegation, type RetrieveOptions, type Retriever, type RolesPolicy, type RunAgentBreakdownRow, RunCancelledError, type RunErrorBreakdownRow, type RunMetrics, type RunToolCallRow, type RunTrendPoint, type RunWhere, SKILL_TOOL_DESCRIPTION, SKILL_TOOL_NAME, type ScopeContext, type ScopeResolver, type SearchMemoriesInput, type SettledTask, type SinkWriter, type Skill, type SkillAuthor, type SkillCatalogEntry, type SkillContext, type SkillLoadOutcome, type SkillOffer, type SkillProvider, type SkillSummary, type SkillToolInput, type SkillWriteRequest, type SkillWriteVerdict, type SkillsConfig, type StageAttachmentInput, type StagedAttachment, type StoreMemoryInput, StoredMessage, type StreamError, type StructuredOutcome, StructuredOutputError, THREAD_DETAIL_CONTENT_CHARS, type ThreadActivityRow, ThreadDetail, type ThreadMessageRow, type ThreadMeta, type ThreadSpendRow, ThreadSummary, type ThreadTurnPage, type ThreadTurnQuery, type ThreadTurnReader, type ThreadUsageRollup, type ThreadWhere, type TokenStreamSink, type ToolCallActivityRow, ToolCallApproval, type ToolCallApprovalColumns, type ToolCallApprovalState, ToolCallRequest, ToolCallStatus, type ToolCallWhere, ToolDefinition, ToolDisabledError, ToolForbiddenError, ToolHandler, ToolInputInvalidError, ToolKind, type ToolKindDeps, ToolNotFoundError, ToolRegistry, ToolResult, ToolSpec, type ToolStatRow, ToolStepEnvelope, ToolTransientRetrySetting, type TurnFrameSummary, type UpdateThreadInput, type UpdateToolCallInput, UsagePurpose, type UsageTrendPoint, type WindowHistoryOptions, type WithMemoryToolInput, type WriteMemoryInput, actorScope, agentDiagnosticKey, agentFailureCode, bucketByActor, bucketByModel, bucketByThread, bucketUsageTrend, buildMemoryBlock, buildSkillsBlock, canActorUseTool, compositeSkillProvider, createFrameBuffer, createIncrementalGate, dayBoundsUtc, defaultCanDecide, defaultScopeResolver, detachedDelivered, detachedStarted, detachedUnsettled, estimateCost, estimateMessageTokens, extractJson, filterToolsByAllowList, filterToolsByCanUse, filterToolsByEnabled, filterToolsByRole, gateFollowUps, gateTail, isControlFlowSignal, isReplayIntegrityError, isToolEnabled, loadSkill, mayDecideApproval, memoryForgetVerdict, memoryWriteVerdict, normalizeDelegation, observeTurnFrames, offerMemories, offerSkills, publishAgentDelegated, publishAgentMemoryResolved, publishAgentMemoryWritten, publishAgentMessage, publishAgentQuotaExceeded, publishAgentRetrieved, publishAgentRunFailed, publishAgentRunFinished, publishAgentRunStarted, publishAgentSkillsResolved, publishAgentToolCall, publishAgentToolRetry, releaseGatedFrames, rememberInputSchema, rememberToolDefinition, repairInstruction, resolveGateLookback, resolveMemoryDigest, resolveOutputGateMode, resolveSkillCatalog, rollupThreadUsage, runAgentLoop, runInputProcessors, runOutputProcessors, seedModelPrices, settleAll, settleUnsettledDelegation, skillInputSchema, skillToolDefinition, skillWriteVerdict, stampToolKinds, staticSkillProvider, summarizeWithModel, tenantScope, toolCallApprovalFromRow, traceLlmTurn, traceToolExecution, truncateDetailContent, validateStructured, windowHistory, withAskTool, withMemoryTool, withSkillTool, withToolTimeout, withTurnFrames, writeMemory };
3334
+ 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_OPTIONS, AGENT_PRICING_STORE, AGENT_PROMPT_CONTRIBUTORS, AGENT_QUOTA_STORE, AGENT_REGISTRY, AGENT_RETRIEVER, AGENT_ROLES_POLICY, AGENT_RUNNER, AGENT_SINK, AGENT_SKILLS, AGENT_SKILL_SOURCES, AGENT_SPAN_EVENTS, AGENT_STORE, AGENT_TOOL_REGISTRY, APPROVAL_EXPIRED_REASON, Actor, type ActorDirectory, type ActorResolver, type ActorSpendRow, type AgentApprovalPort, AgentDefinition, type AgentDelegated, AgentDelegation, type AgentDiagnosticEvent, type AgentDiagnosticKey, type AgentFollowUpsSpan, type AgentGovernanceQueries, AgentIntake, type AgentLlmTurnSpan, type AgentLoopDeps, type AgentLoopHooks, type AgentLoopResult, type AgentMemoryResolved, type AgentMemoryWritten, type AgentMessageEvent, type AgentPricingStore, type AgentQuotaExceeded, AgentRegistry, type AgentRetrievalSpan, type AgentRetrieved, type AgentRunFailed, type AgentRunFinished, AgentRunInput, type AgentRunStarted, type AgentRunner, type AgentSkillsResolved, type AgentSpanEvent, type AgentStore, AgentStreamError, AgentStreamEvent, type AgentStructuredOutputSpan, type AgentToolCallEvent, type AgentToolExecutionSpan, type AgentToolRetry, AgentUiComponent, AiToolCtx, type AppendMessageInput, type ApprovalDecisionRef, type ApprovalPolicy, type ApprovalRequirement, type ApprovalThreadRef, type ApprovalToolRef, type ApprovalWhere, type AttachmentRef, type AttachmentStagingStore, type BufferedModelTurnResult, type BuildMemoryBlockInput, type CostUsage, type CreateThreadInput, type CurrentModelPrice, DEFAULT_HISTORY_SUMMARY_INSTRUCTION, DEFAULT_MAX_FACT_CHARS, DEFAULT_MAX_MEMORIES, DEFAULT_MAX_SKILLS, DEFAULT_REFUSAL_REASON, DEFAULT_STRUCTURED_OUTPUT_INSTRUCTION, Decision, DefaultApprovalPolicy, DefaultRolesPolicy, type DetachedDelegationOutcome, type DetachedDelegationReceipt, DetachedDelivery, type DetailThreadRef, ElicitationRequest, type EmbeddingProvider, type EmitUi, type ForgetMemoryInput, type FrameBuffer, GLOBAL_SCOPE, type GovernancePage, type GovernancePageQuery, type GovernanceRange, type GovernanceRunDetail, type GovernanceThreadDetail, type GovernanceThreadDetailQuery, type GovernanceUsageInput, HistoryPolicy, HumanReply, type IncrementalGate, InputProcessor, type ListMemoriesInput, type ListSkillsInput, type ListStagedAttachmentsInput, LlmStepEnvelope, type LoadSkillInput, type MemoryAuthor, type MemoryConfig, type MemoryDigest, type MemoryDigestEntry, type MemoryFact, type MemoryForgetRequest, type MemoryOrigin, type MemoryProvider, type MemoryRecord, type MemoryVerdict, type MemoryWriteOutcome, type MemoryWriteRequest, MessageAttachment, MessageUsage, ModelAnswer, ModelMessage, type ModelPrice, type ModelPriceInput, type ModelProvider, type ModelSpendRow, type ModelTurnArgs, type ModelTurnResult, type ObservedTurnFrames, type OfferMemoriesInput, type OutputGateMode, type OutputGateResult, OutputProcessor, type OverriddenMemory, PageContext, type Passage, type PendingApprovalRow, ProcessedPrompt, ProcessorContext, PromptBuilder, PromptContributor, QuotaExceededError, QuotaState, type QuotaStore, REMEMBER_TOOL_DESCRIPTION, REMEMBER_TOOL_NAME, REQUESTER_APPROVER, type RecentRunRow, type RecordRunEndInput, type RecordRunStartInput, type RecordToolCallInput, type RecordUsageInput, type RememberToolInput, type RerankOptions, type Reranker, type ResolveAttachmentInput, type ResolveMemoryDigestInput, type ResolvedDelegation, type RetrieveOptions, type Retriever, type RolesPolicy, type RunAgentBreakdownRow, RunCancelledError, type RunErrorBreakdownRow, type RunMetrics, type RunToolCallRow, type RunTrendPoint, type RunWhere, SKILL_TOOL_DESCRIPTION, SKILL_TOOL_NAME, type ScopeContext, type ScopeResolver, type SearchMemoriesInput, type SettledTask, type SinkWriter, type Skill, type SkillAuthor, type SkillCatalogEntry, type SkillContext, type SkillLoadOutcome, type SkillOffer, type SkillProvider, type SkillSummary, type SkillToolInput, type SkillWriteRequest, type SkillWriteVerdict, type SkillsConfig, type StageAttachmentInput, type StagedAttachment, type StoreMemoryInput, StoredMessage, type StreamError, type StructuredOutcome, StructuredOutputError, THREAD_DETAIL_CONTENT_CHARS, type ThreadActivityRow, ThreadDetail, type ThreadMessageRow, type ThreadMeta, type ThreadSpendRow, ThreadSummary, type ThreadTurnPage, type ThreadTurnQuery, type ThreadTurnReader, type ThreadUsageRollup, type ThreadWhere, type TokenStreamSink, type ToolCallActivityRow, ToolCallApproval, type ToolCallApprovalColumns, type ToolCallApprovalState, ToolCallRequest, ToolCallStatus, type ToolCallWhere, ToolDefinition, ToolDisabledError, ToolForbiddenError, ToolHandler, ToolInputInvalidError, ToolKind, type ToolKindDeps, ToolNotFoundError, ToolRegistry, ToolResult, ToolSpec, type ToolStatRow, ToolStepEnvelope, ToolTransientRetrySetting, type TurnFrameSummary, type UiCollector, type UpdateThreadInput, type UpdateToolCallInput, UsagePurpose, type UsageTrendPoint, type WindowHistoryOptions, type WithMemoryToolInput, type WriteMemoryInput, actorScope, agentDiagnosticKey, agentFailureCode, bucketByActor, bucketByModel, bucketByThread, bucketUsageTrend, buildMemoryBlock, buildSkillsBlock, canActorUseTool, compositeSkillProvider, createFrameBuffer, createIncrementalGate, createUiCollector, dayBoundsUtc, defaultCanDecide, defaultScopeResolver, detachedDelivered, detachedStarted, detachedUnsettled, estimateCost, estimateMessageTokens, extractJson, filterToolsByAllowList, filterToolsByCanUse, filterToolsByEnabled, filterToolsByRole, gateFollowUps, gateTail, isControlFlowSignal, isReplayIntegrityError, isToolEnabled, loadSkill, mayDecideApproval, memoryForgetVerdict, memoryWriteVerdict, mergeUi, normalizeDelegation, observeTurnFrames, offerMemories, offerSkills, publishAgentDelegated, publishAgentMemoryResolved, publishAgentMemoryWritten, publishAgentMessage, publishAgentQuotaExceeded, publishAgentRetrieved, publishAgentRunFailed, publishAgentRunFinished, publishAgentRunStarted, publishAgentSkillsResolved, publishAgentToolCall, publishAgentToolRetry, releaseGatedFrames, rememberInputSchema, rememberToolDefinition, repairInstruction, resolveGateLookback, resolveMemoryDigest, resolveOutputGateMode, resolveSkillCatalog, rollupThreadUsage, runAgentLoop, runInputProcessors, runOutputProcessors, seedModelPrices, settleAll, settleUnsettledDelegation, skillInputSchema, skillToolDefinition, skillWriteVerdict, stampToolKinds, staticSkillProvider, summarizeWithModel, tenantScope, toolCallApprovalFromRow, traceLlmTurn, traceToolExecution, truncateDetailContent, unwrapToolStepOutput, validateStructured, windowHistory, withAskTool, withMemoryTool, withSkillTool, withToolTimeout, withTurnFrames, wrapToolStepOutput, writeMemory };
package/dist/index.js CHANGED
@@ -157,6 +157,95 @@ function withTurnFrames(result, frames) {
157
157
  }
158
158
  __name(withTurnFrames, "withTurnFrames");
159
159
 
160
+ // src/tool-ui.ts
161
+ var TOOL_STEP_UI = "@@nestjs-agent/tool-step-ui";
162
+ function wrapToolStepOutput(output, ui) {
163
+ if (ui.length === 0) {
164
+ return output;
165
+ }
166
+ const wrapped = {
167
+ [TOOL_STEP_UI]: 1,
168
+ output,
169
+ ui: [
170
+ ...ui
171
+ ]
172
+ };
173
+ return wrapped;
174
+ }
175
+ __name(wrapToolStepOutput, "wrapToolStepOutput");
176
+ function unwrapToolStepOutput(raw) {
177
+ if (typeof raw === "object" && raw !== null && raw[TOOL_STEP_UI] === 1) {
178
+ const wrapped = raw;
179
+ return {
180
+ output: wrapped.output,
181
+ ui: Array.isArray(wrapped.ui) ? wrapped.ui : []
182
+ };
183
+ }
184
+ return {
185
+ output: raw,
186
+ ui: []
187
+ };
188
+ }
189
+ __name(unwrapToolStepOutput, "unwrapToolStepOutput");
190
+ function createUiCollector(toolCallId, write) {
191
+ const pushed = /* @__PURE__ */ new Map();
192
+ let next = 0;
193
+ const emit2 = /* @__PURE__ */ __name(async (component, props, options = {}) => {
194
+ if (typeof component !== "string" || component.length === 0) {
195
+ throw new Error("emitUi: component must be a non-empty string");
196
+ }
197
+ if (typeof props !== "object" || props === null || Array.isArray(props)) {
198
+ throw new Error("emitUi: props must be a JSON object");
199
+ }
200
+ let id = options.id;
201
+ if (id === void 0) {
202
+ id = `${toolCallId}:ui:${next}`;
203
+ next += 1;
204
+ }
205
+ const entry = {
206
+ id,
207
+ component,
208
+ // Snapshot: the frame and the persisted value are what the tool pushed at THIS moment, not
209
+ // whatever the object it handed over looks like when the step settles.
210
+ props: JSON.parse(JSON.stringify(props)),
211
+ ...options.version !== void 0 ? {
212
+ version: options.version
213
+ } : {},
214
+ toolCallId
215
+ };
216
+ pushed.set(id, entry);
217
+ await write?.({
218
+ kind: "ui",
219
+ ...entry
220
+ });
221
+ return {
222
+ id
223
+ };
224
+ }, "emit");
225
+ return {
226
+ emit: emit2,
227
+ components: /* @__PURE__ */ __name(() => [
228
+ ...pushed.values()
229
+ ], "components"),
230
+ restart: /* @__PURE__ */ __name(() => {
231
+ next = 0;
232
+ }, "restart")
233
+ };
234
+ }
235
+ __name(createUiCollector, "createUiCollector");
236
+ function mergeUi(...lists) {
237
+ const merged = /* @__PURE__ */ new Map();
238
+ for (const list of lists) {
239
+ for (const component of list ?? []) {
240
+ merged.set(component.id, component);
241
+ }
242
+ }
243
+ return [
244
+ ...merged.values()
245
+ ];
246
+ }
247
+ __name(mergeUi, "mergeUi");
248
+
160
249
  // src/spi/pricing-store.ts
161
250
  async function seedModelPrices(store, prices) {
162
251
  for (const price of prices) {
@@ -3171,6 +3260,11 @@ async function claimToolCall(turn, call) {
3171
3260
  ...spec?.detached === true ? {
3172
3261
  detached: true
3173
3262
  } : {},
3263
+ // Same for `terminal`: absent unless declared, so a deployment with no terminal tool writes
3264
+ // the bytes it always has, and a replay reads the branch back instead of re-deciding it.
3265
+ ...spec?.terminal === true ? {
3266
+ terminal: true
3267
+ } : {},
3174
3268
  ...approval !== void 0 ? {
3175
3269
  approval
3176
3270
  } : {}
@@ -3192,6 +3286,9 @@ async function claimToolCall(turn, call) {
3192
3286
  ...persisted?.detached === true ? {
3193
3287
  detached: true
3194
3288
  } : {},
3289
+ ...persisted?.terminal === true ? {
3290
+ terminal: true
3291
+ } : {},
3195
3292
  ...toolType === "action" && persisted?.approval !== void 0 ? {
3196
3293
  approval: persisted.approval
3197
3294
  } : {},
@@ -3358,7 +3455,7 @@ async function invokeClaimedTool(turn, claimed) {
3358
3455
  if (claimed.toolType === "memory") {
3359
3456
  return await rememberIntoTurn(turn, claimed, startedAt);
3360
3457
  }
3361
- let output;
3458
+ let raw;
3362
3459
  if (hooks.dispatchTool) {
3363
3460
  const stepCtx = {
3364
3461
  actor: input.actor,
@@ -3381,28 +3478,47 @@ async function invokeClaimedTool(turn, claimed) {
3381
3478
  } : {},
3382
3479
  // Numeric-only: the handler applies withToolTimeout AND its own local `classify` — see
3383
3480
  // ToolStepEnvelope.transientRetry.
3384
- transientRetry: resolveToolTransientRetryNumbers(deps.toolTransientRetry)
3481
+ transientRetry: resolveToolTransientRetryNumbers(deps.toolTransientRetry),
3482
+ // The handler hands back what the tool pushed through `ctx.emitUi` with its output.
3483
+ collectUi: true
3385
3484
  };
3386
- output = await hooks.dispatchTool(resolvedCall, envelope);
3485
+ raw = await hooks.dispatchTool(resolvedCall, envelope);
3387
3486
  } else {
3388
- const invocation = hooks.step(`tool:${call.id}`, () => traceToolExecution(hooks.runId, {
3389
- toolCallId: call.id,
3390
- toolName: call.name,
3391
- toolType
3392
- }, () => invokeWithTransientRetry(() => deps.registry.invoke(call.name, call.input, ctx, deps.rolesPolicy), deps.toolTransientRetry ?? {}, {
3393
- ...hooks.isControlFlowError !== void 0 ? {
3394
- isControlFlowError: hooks.isControlFlowError
3395
- } : {},
3396
- onRetry: /* @__PURE__ */ __name((attempt, retryError) => {
3397
- publishAgentToolRetry({
3398
- toolName: call.name,
3399
- toolCallId: call.id,
3400
- attempt,
3401
- message: retryError instanceof Error ? retryError.message : String(retryError)
3402
- });
3403
- }, "onRetry")
3404
- })));
3405
- output = deps.toolTimeoutMs !== void 0 ? await withToolTimeout(invocation, deps.toolTimeoutMs, call.name) : await invocation;
3487
+ const invocation = hooks.step(`tool:${call.id}`, async () => {
3488
+ const ui2 = createUiCollector(call.id, (event) => turn.writer.write(encodeStreamEvent(event)));
3489
+ const output2 = await traceToolExecution(hooks.runId, {
3490
+ toolCallId: call.id,
3491
+ toolName: call.name,
3492
+ toolType
3493
+ }, () => invokeWithTransientRetry(() => {
3494
+ ui2.restart();
3495
+ return deps.registry.invoke(call.name, call.input, {
3496
+ ...ctx,
3497
+ emitUi: ui2.emit
3498
+ }, deps.rolesPolicy);
3499
+ }, deps.toolTransientRetry ?? {}, {
3500
+ ...hooks.isControlFlowError !== void 0 ? {
3501
+ isControlFlowError: hooks.isControlFlowError
3502
+ } : {},
3503
+ onRetry: /* @__PURE__ */ __name((attempt, retryError) => {
3504
+ publishAgentToolRetry({
3505
+ toolName: call.name,
3506
+ toolCallId: call.id,
3507
+ attempt,
3508
+ message: retryError instanceof Error ? retryError.message : String(retryError)
3509
+ });
3510
+ }, "onRetry")
3511
+ }));
3512
+ return wrapToolStepOutput(output2, ui2.components());
3513
+ });
3514
+ raw = deps.toolTimeoutMs !== void 0 ? await withToolTimeout(invocation, deps.toolTimeoutMs, call.name) : await invocation;
3515
+ }
3516
+ const { output, ui } = unwrapToolStepOutput(raw);
3517
+ if (ui.length > 0) {
3518
+ turn.toolUi.set(call.id, ui);
3519
+ }
3520
+ if (claimed.terminal === true) {
3521
+ turn.halt.terminal = true;
3406
3522
  }
3407
3523
  return {
3408
3524
  status: "executed",
@@ -4300,6 +4416,10 @@ ${block}`;
4300
4416
  hooks,
4301
4417
  messageId: assistant.id,
4302
4418
  writer,
4419
+ toolUi: /* @__PURE__ */ new Map(),
4420
+ halt: {
4421
+ terminal: false
4422
+ },
4303
4423
  ...skillOffer !== void 0 ? {
4304
4424
  skills: skillOffer
4305
4425
  } : {},
@@ -4332,6 +4452,10 @@ ${block}`;
4332
4452
  assistantMessage.toolResults = settledResults;
4333
4453
  await hooks.step(`stream:tool-outputs:${i}`, async () => {
4334
4454
  await deps.store.setMessageToolResults(assistant.id, settledResults);
4455
+ const toolUi = toolCallsWithKind.flatMap((call) => turnCalls.toolUi.get(call.id) ?? []);
4456
+ if (toolUi.length > 0) {
4457
+ await deps.store.setMessageUi?.(assistant.id, mergeUi(turn.ui, toolUi));
4458
+ }
4335
4459
  for (const result of results) {
4336
4460
  await writer.write(encodeStreamEvent(outputFrame(result)));
4337
4461
  }
@@ -4346,6 +4470,9 @@ ${block}`;
4346
4470
  } : {}
4347
4471
  }));
4348
4472
  });
4473
+ if (turnCalls.halt.terminal) {
4474
+ break;
4475
+ }
4349
4476
  }
4350
4477
  if (history.title === "" || history.title === "New chat") {
4351
4478
  await hooks.step("persist:title", () => deps.store.setTitle(input.threadId, deriveTitle(input.userText)));
@@ -4475,6 +4602,7 @@ export {
4475
4602
  compositeSkillProvider,
4476
4603
  createFrameBuffer,
4477
4604
  createIncrementalGate,
4605
+ createUiCollector,
4478
4606
  dayBoundsUtc,
4479
4607
  decodeStreamEvent,
4480
4608
  defaultCanDecide,
@@ -4502,6 +4630,7 @@ export {
4502
4630
  mayDecideApproval,
4503
4631
  memoryForgetVerdict,
4504
4632
  memoryWriteVerdict,
4633
+ mergeUi,
4505
4634
  normalizeDelegation,
4506
4635
  normalizeElicitationReply,
4507
4636
  observeTurnFrames,
@@ -4552,6 +4681,7 @@ export {
4552
4681
  traceLlmTurn,
4553
4682
  traceToolExecution,
4554
4683
  truncateDetailContent,
4684
+ unwrapToolStepOutput,
4555
4685
  validateElicitationAnswer,
4556
4686
  validateElicitationValue,
4557
4687
  validateStructured,
@@ -4561,6 +4691,7 @@ export {
4561
4691
  withSkillTool,
4562
4692
  withToolTimeout,
4563
4693
  withTurnFrames,
4694
+ wrapToolStepOutput,
4564
4695
  writeMemory
4565
4696
  };
4566
4697
  //# sourceMappingURL=index.js.map