@dudousxd/nestjs-agent-core 0.33.0 → 0.34.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,8 +1,8 @@
1
- import { M as ModelMessage, c as ToolDefinition, d as ToolCallRequest, e as MessageUsage, f as AgentUiComponent, A as Actor, g as AiToolCtx, h as AgentStreamEvent, T as ToolSpec, Q as QuotaState, i as AgentRunInput, H as HumanReply, j as MessageAttachment, k as ToolKind, l as ToolCallStatus, m as ToolCallApproval, a as ToolHandler, n as HistoryPolicy, P as PageContext, o as AgentDefinition, p as AgentDelegation, q as AgentStore, D as DetachedDelivery, r as ToolDescribeScope, s as PromptBuilder, t as PromptContributor, u as ToolTransientRetrySetting, v as AgentIntake, w as Decision, E as ElicitationRequest, L as LlmStepEnvelope, x as ToolStepEnvelope, C as ChatQueueStore, y as CreateThreadInput, z as ThreadSummary, B as ThreadDetail, F as ToolCallApprovalState, U as UpdateThreadInput, R as RecordRunStartInput, G as EnqueueMessageInput, I as QueuedMessage, J as QueuedMessagePatch, K as QueuePause, N as AppendMessageInput, S as StoredMessage, O as ToolResult, V as MessageFeedback, W as RecordToolCallInput, X as UpdateToolCallInput, Y as RecordUsageInput } from './tool-CMTuoJ2v.cjs';
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 AskToolInput, a7 as ChatQueueState, a8 as DEFAULT_INTAKE_PREAMBLE, a9 as DEFAULT_TOOL_TRANSIENT_RETRY_ATTEMPTS, aa as DEFAULT_TOOL_TRANSIENT_RETRY_BACKOFF_MS, ab as ELICITATION_INPUT_TYPES, ac as ElicitationInput, ad as ElicitationInputType, ae as ElicitationOption, af as ElicitationOutcome, ag as ElicitationQuestion, ah as ElicitationReply, ai as ElicitationResult, aj as HistoryPolicyContext, ak as HistorySelection, al as HistorySummary, am as InvokeWithTransientRetryOptions, an as MAX_ASK_QUESTIONS, ao as MessageFeedbackValue, ap as MessageRole, aq as PromptContext, ar as QueuePauseReason, as as QueuedMessageView, at as QuotaView, au as RecordRunEndInput, av as ThreadTurnPage, aw as ThreadTurnQuery, ax as ThreadTurnReader, ay as ToolCallApprovalStatus, az as ToolCatalogEntry, aA as ToolConfirmation, aB as ToolDescription, b as ToolPresentation, aC as ToolPresentationTone, aD as ToolResultField, aE as ToolResultView, aF as ToolStepCtx, aG as ToolTransientRetryNumbers, aH as ToolTransientRetryOptions, aI as UsagePurpose, aJ as askInputSchema, aK as askToolDefinition, aL as decodeStreamEvent, aM as encodeStreamEvent, aN as invokeWithTransientRetry, aO as isChatQueueStore, aP as isTransientToolError, aQ as isTypedQuestion, aR as normalizeElicitationReply, aS as questionOptions, aT as queuedMessageView, aU as readElicitationInput, aV as readElicitationQuestions, aW as releaseThreadRun, aX as renderElicitationAnswers, aY as resolveElicitation, aZ as resolveToolTransientRetryNumbers, a_ as settleElicitation, a$ as validateElicitationAnswer, b0 as validateElicitationValue } from './tool-CMTuoJ2v.cjs';
1
+ import { M as ModelMessage, c as ToolDefinition, d as ToolCallRequest, e as MessageUsage, f as AgentUiComponent, A as Actor, g as AiToolCtx, h as AgentStreamEvent, T as ToolSpec, Q as QuotaState, i as AgentRunInput, H as HumanReply, j as MessageAttachment, k as ToolKind, l as ToolCallStatus, m as ToolCallApproval, a as ToolHandler, n as HistoryPolicy, P as PageContext, o as AgentDefinition, p as AgentStore, q as AgentDelegation, D as DetachedDelivery, r as ToolDescribeScope, s as PromptBuilder, t as PromptContributor, u as ToolTransientRetrySetting, v as AgentIntake, w as Decision, E as ElicitationRequest, L as LlmStepEnvelope, x as ToolStepEnvelope, C as ChatQueueStore, y as CreateThreadInput, z as ThreadSummary, B as ThreadDetail, F as ToolCallApprovalState, U as UpdateThreadInput, R as RecordRunStartInput, G as EnqueueMessageInput, I as QueuedMessage, J as QueuedMessagePatch, K as QueuePause, N as AppendMessageInput, S as StoredMessage, O as ToolResult, V as MessageFeedback, W as RecordToolCallInput, X as ToolCallOutcome, Y as UpdateToolCallInput, Z as RecordUsageInput } from './tool-C128TFWw.cjs';
2
+ export { _ as ALL_AGENTS, $ as ASK_TOOL_DESCRIPTION, a0 as ASK_TOOL_NAME, a1 as AgentApprovalRequest, a2 as AgentApprovalSettlement, a3 as AgentAttachmentConfig, a4 as AgentCatalogEntry, a5 as AgentClientConfig, a6 as AgentHistoryWindow, a7 as AgentStreamErrorCode, a8 as AskToolInput, a9 as ChatQueueState, aa as DEFAULT_INTAKE_PREAMBLE, ab as DEFAULT_TOOL_TRANSIENT_RETRY_ATTEMPTS, ac as DEFAULT_TOOL_TRANSIENT_RETRY_BACKOFF_MS, ad as ELICITATION_INPUT_TYPES, ae as ElicitationInput, af as ElicitationInputType, ag as ElicitationOption, ah as ElicitationOutcome, ai as ElicitationQuestion, aj as ElicitationReply, ak as ElicitationResult, al as HistoryPolicyContext, am as HistorySelection, an as HistorySummary, ao as InvokeWithTransientRetryOptions, ap as MAX_ASK_QUESTIONS, aq as MessageFeedbackValue, ar as MessageRole, 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, aE as ToolDescription, b as ToolPresentation, aF as ToolPresentationTone, aG as ToolResultField, aH as ToolResultView, aI as ToolStepCtx, aJ as ToolTransientRetryNumbers, aK as ToolTransientRetryOptions, aL as 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 './tool-C128TFWw.cjs';
3
3
  import { StandardSchemaV1 } from '@standard-schema/spec';
4
- import { O as OutputProcessor, P as ProcessorContext, I as InputProcessor, a as ProcessedPrompt, M as ModelAnswer } from './processors-DvZDW5zS.cjs';
5
- export { D as DEFAULT_INCREMENTAL_LOOKBACK_CHARS, b as IncrementalGating, c as OutputRejectedError, d as OutputVerdict, e as ProcessorFailedError } from './processors-DvZDW5zS.cjs';
4
+ import { O as OutputProcessor, P as ProcessorContext, I as InputProcessor, a as ProcessedPrompt, M as ModelAnswer } from './processors-Bm2DniQ8.cjs';
5
+ export { D as DEFAULT_INCREMENTAL_LOOKBACK_CHARS, b as IncrementalGating, c as OutputRejectedError, d as OutputVerdict, e as ProcessorFailedError } from './processors-Bm2DniQ8.cjs';
6
6
  import { ChannelRegistry } from '@dudousxd/nestjs-diagnostics';
7
7
 
8
8
  /**
@@ -2368,6 +2368,42 @@ declare function isReplayIntegrityError(error: unknown): boolean;
2368
2368
  */
2369
2369
  declare function isControlFlowSignal(error: unknown): boolean;
2370
2370
 
2371
+ /** The `code` a decision answers with when the run it was for is over (`409`). */
2372
+ declare const RUN_NOT_ACTIVE_CODE = "run_not_active";
2373
+ /** What a person is told when they decide on a request whose run is over. */
2374
+ declare const RUN_NOT_ACTIVE_MESSAGE = "This request is no longer waiting for an answer: the turn it belonged to has ended. Send the message again.";
2375
+ /** What is written on the row of a run that was found over without having said so itself. */
2376
+ declare const RUN_NO_LONGER_RUNNING = "the run is no longer running";
2377
+ interface SettleDeadRunInput {
2378
+ runId: string;
2379
+ /** Set for a thread's own turn: the thread is released if this run still holds it. */
2380
+ threadId?: string;
2381
+ /**
2382
+ * Settle the run ROW as `failed` with this. Pass it only where the caller KNOWS the run failed
2383
+ * (the run's own body, unwinding). `recordRunEnd` is last-write-wins, so a caller that only knows
2384
+ * the run is no longer running — it may have completed — must leave the row alone.
2385
+ */
2386
+ failure?: {
2387
+ code: string;
2388
+ message: string;
2389
+ };
2390
+ }
2391
+ /**
2392
+ * Leave nothing waiting on a run that is over and did not say so itself.
2393
+ *
2394
+ * A run normally settles its own row, its calls and its thread from inside its body. One that is
2395
+ * refused a checkpoint position, or whose worker died, never gets there: a call it had put to a
2396
+ * person stays `pending_approval` — an approval card that takes a "yes" and then does nothing, for
2397
+ * ever — and its thread stays pointed at it. Everything here is written straight to the store,
2398
+ * outside any checkpoint, because the callers are exactly the paths that have no journal left to
2399
+ * write to; each write is idempotent (only still-pending calls, a release conditional on the
2400
+ * holder), so doing it twice changes nothing.
2401
+ *
2402
+ * Best-effort on purpose: this runs while something else is already failing, and must not replace
2403
+ * that failure with one of its own.
2404
+ */
2405
+ declare function settleDeadRun(store: AgentStore, input: SettleDeadRunInput): Promise<void>;
2406
+
2371
2407
  /** An agent->agent edge with its awaited-or-not resolved, whichever form it was authored in. */
2372
2408
  interface ResolvedDelegation {
2373
2409
  agent: string;
@@ -2937,6 +2973,30 @@ declare class RunCancelledError extends Error {
2937
2973
  * page whoever is on call for model failures.
2938
2974
  */
2939
2975
  declare function agentFailureCode(error: unknown): string;
2976
+ /**
2977
+ * What a person is told when a run fails for a reason that is ours rather than theirs. The error's
2978
+ * own text is for whoever operates the deployment: it names run ids, checkpoint positions and
2979
+ * provider internals ("non-determinism at <uuid>#41 …", "No output generated. Check the stream for
2980
+ * errors."), which mean nothing to the person reading the chat and are not theirs to see.
2981
+ */
2982
+ declare const RUN_FAILED_MESSAGE = "The assistant could not finish this answer. Please try again.";
2983
+ /**
2984
+ * Whether an error frame carries the error's own message. Unset → only outside production
2985
+ * (`NODE_ENV !== 'production'`), where the person reading the stream is the one debugging it.
2986
+ * `true`/`false` decides it outright; `undefined` returns to the default.
2987
+ */
2988
+ declare function exposeStreamErrorDetails(expose: boolean | undefined): void;
2989
+ /**
2990
+ * The terminal a failed run closes its stream with — what `SinkWriter.fail` takes, and what the
2991
+ * transport sends as the `event: error` frame.
2992
+ *
2993
+ * The frame is what the PERSON sees. For a crash it carries a stable `code` (what a client branches
2994
+ * on, and translates) and {@link RUN_FAILED_MESSAGE}; the error itself belongs in the log and on the
2995
+ * run row, which is where the runners put it. Outside production the raw message rides the frame as
2996
+ * it always did (see {@link exposeStreamErrorDetails}). A message the library words itself
2997
+ * (`quota_exceeded`, `output_rejected`, `structured_output_invalid`) is sent as it is.
2998
+ */
2999
+ declare function streamFailure(error: unknown): StreamError;
2940
3000
  /** Reject if `work` doesn't settle within `ms`. The underlying work is left to finish on its own. */
2941
3001
  declare function withToolTimeout<T>(work: Promise<T>, ms: number, toolName: string): Promise<T>;
2942
3002
  /**
@@ -2985,6 +3045,16 @@ declare function withAskTool({ tools, ask, }: {
2985
3045
  tools: ToolDefinition[];
2986
3046
  ask: boolean | undefined;
2987
3047
  }): ToolDefinition[];
3048
+ /**
3049
+ * The per-CALL half of a tool's context: which call this is, and the key that stays the same for
3050
+ * every execution of it (see {@link AiToolCtx.idempotencyKey}).
3051
+ */
3052
+ declare function toolCallContext<T extends {
3053
+ runId: string;
3054
+ }>(ctx: T, toolCallId: string): T & {
3055
+ toolCallId: string;
3056
+ idempotencyKey: string;
3057
+ };
2988
3058
  /** The reason an expired call is denied with — on the row, the stream frame and the result. */
2989
3059
  declare const APPROVAL_EXPIRED_REASON = "approval expired";
2990
3060
  /**
@@ -3403,6 +3473,8 @@ declare class InMemoryAgentStore implements AgentStore, ChatQueueStore {
3403
3473
  */
3404
3474
  referencedMediaIds(actorRef: string, mediaIds: readonly string[]): Promise<string[]>;
3405
3475
  recordToolCall(input: RecordToolCallInput): Promise<void>;
3476
+ toolCallOutcomes(toolCallIds: readonly string[]): Promise<ToolCallOutcome[]>;
3477
+ failUnsettledToolCalls(runId: string, error: string): Promise<number>;
3406
3478
  updateToolCall(input: UpdateToolCallInput): Promise<void>;
3407
3479
  recordUsage(input: RecordUsageInput): Promise<void>;
3408
3480
  quotaToday(actorRef: string, day: string): Promise<{
@@ -3454,4 +3526,4 @@ declare class InMemoryAgentStore implements AgentStore, ChatQueueStore {
3454
3526
  private toSummary;
3455
3527
  }
3456
3528
 
3457
- export { AGENT_ACTOR_DIRECTORY, AGENT_ACTOR_RESOLVER, AGENT_APPROVAL_PORT, AGENT_ATTACHMENT_STAGING, AGENT_DEPS_FACTORY, AGENT_DIAGNOSTIC_EVENTS, AGENT_DURABLE_RUNNER, AGENT_EMBEDDING_PROVIDER, AGENT_GOVERNANCE_QUERIES, AGENT_MEMORY, AGENT_MODEL, AGENT_MODEL_CATALOG, AGENT_OPTIONS, AGENT_PRICING_STORE, AGENT_PROMPT_CONTRIBUTORS, AGENT_QUOTA_PROVIDER, AGENT_QUOTA_STORE, AGENT_REGISTRY, AGENT_RETRIEVER, AGENT_ROLES_POLICY, AGENT_RUNNER, AGENT_SINK, AGENT_SKILLS, AGENT_SKILL_SOURCES, AGENT_SPAN_EVENTS, AGENT_STORE, AGENT_TOOL_REGISTRY, APPROVAL_EXPIRED_REASON, Actor, type ActorDirectory, type ActorResolver, type ActorSpendRow, type AgentApprovalPort, AgentDefinition, type AgentDelegated, AgentDelegation, type AgentDiagnosticEvent, type AgentDiagnosticKey, type AgentFollowUpsSpan, type AgentGovernanceQueries, AgentIntake, type AgentLlmTurnSpan, type AgentLoopDeps, type AgentLoopHooks, type AgentLoopResult, type AgentMemoryResolved, type AgentMemoryWritten, type AgentMessageEvent, type AgentPricingStore, type AgentQuotaExceeded, AgentRegistry, type AgentRetrievalSpan, type AgentRetrieved, type AgentRunFailed, type AgentRunFinished, AgentRunInput, type AgentRunStartOptions, type AgentRunStarted, type AgentRunner, type AgentSkillsResolved, type AgentSpanEvent, AgentStore, AgentStreamError, AgentStreamEvent, type AgentStructuredOutputSpan, type AgentToolCallEvent, type AgentToolExecutionSpan, type AgentToolRetry, AgentUiComponent, AiToolCtx, AppendMessageInput, type ApprovalDecisionRef, type ApprovalPolicy, type ApprovalRequirement, type ApprovalThreadRef, type ApprovalToolRef, type ApprovalWhere, type AttachmentRef, type AttachmentStagingDescription, type AttachmentStagingStore, type BufferedModelTurnResult, type BuildMemoryBlockInput, ChatQueueStore, type CostUsage, CreateThreadInput, type CurrentModelPrice, DEFAULT_HISTORY_SUMMARY_INSTRUCTION, DEFAULT_MAX_FACT_CHARS, DEFAULT_MAX_MEMORIES, DEFAULT_MAX_SKILLS, DEFAULT_REFUSAL_REASON, DEFAULT_STRUCTURED_OUTPUT_INSTRUCTION, Decision, DefaultApprovalPolicy, DefaultRolesPolicy, type DetachedDelegationOutcome, type DetachedDelegationReceipt, DetachedDelivery, type DetailThreadRef, ElicitationRequest, type EmbeddingProvider, type EmitUi, EnqueueMessageInput, type ForgetMemoryInput, type FrameBuffer, GLOBAL_SCOPE, type GovernanceMessageRow, type GovernancePage, type GovernancePageQuery, type GovernancePendingApprovalRow, type GovernanceRange, type GovernanceRunDetail, type GovernanceRunRow, type GovernanceThreadDetail, type GovernanceThreadDetailQuery, type GovernanceThreadRow, type GovernanceToolCallRow, type GovernanceUsageInput, type GovernanceUsageRow, HistoryPolicy, HumanReply, InMemoryAgentStore, type IncrementalGate, InputProcessor, type ListMemoriesInput, type ListSkillsInput, type ListStagedAttachmentsInput, LlmStepEnvelope, type LoadSkillInput, type MemoryAuthor, type MemoryConfig, type MemoryDigest, type MemoryDigestEntry, type MemoryFact, type MemoryForgetRequest, type MemoryOrigin, type MemoryProvider, type MemoryRecord, type MemoryVerdict, type MemoryWriteOutcome, type MemoryWriteRequest, MessageAttachment, MessageFeedback, MessageUsage, ModelAnswer, type ModelCatalog, type ModelCatalogEntry, type ModelCatalogLock, type ModelCatalogProviderGroup, type ModelCatalogQuery, type ModelCatalogView, ModelMessage, type ModelPrice, type ModelPriceInput, type ModelProvider, type ModelSpendRow, type ModelTurnArgs, type ModelTurnResult, type ObservedTurnFrames, type OfferMemoriesInput, type OutputGateMode, type OutputGateResult, OutputProcessor, type OverriddenMemory, PageContext, type Passage, type PendingApprovalRow, ProcessedPrompt, ProcessorContext, PromptBuilder, PromptContributor, QueuePause, QueuedMessage, QueuedMessagePatch, type QuotaBlock, QuotaExceededError, type QuotaPeriod, type QuotaProvider, type QuotaQuery, type QuotaReport, QuotaState, type QuotaStore, type QuotaWarning, type QuotaWindow, REMEMBER_TOOL_DESCRIPTION, REMEMBER_TOOL_NAME, REQUESTER_APPROVER, type RecentRunRow, RecordRunStartInput, RecordToolCallInput, 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 ThreadUsageRollup, type ThreadWhere, type TokenStreamSink, type ToolCallActivityRow, ToolCallApproval, type ToolCallApprovalColumns, ToolCallApprovalState, ToolCallRequest, ToolCallStatus, type ToolCallWhere, ToolDefinition, ToolDescribeScope, ToolDisabledError, ToolForbiddenError, ToolHandler, ToolInputInvalidError, ToolKind, type ToolKindDeps, ToolNotFoundError, ToolRegistry, ToolResult, ToolSpec, type ToolStatRow, ToolStepEnvelope, ToolTransientRetrySetting, type TurnFrameSummary, type UiCollector, UpdateThreadInput, UpdateToolCallInput, type UsageTrendPoint, type WindowHistoryOptions, type WithMemoryToolInput, type WriteMemoryInput, actorScope, agentDiagnosticKey, agentFailureCode, bucketByActor, bucketByModel, bucketByThread, bucketUsageTrend, buildMemoryBlock, buildSkillsBlock, canActorUseTool, compositeSkillProvider, createFrameBuffer, createIncrementalGate, createNoopEmitUi, createUiCollector, dayBoundsUtc, defaultCanDecide, defaultScopeResolver, detachedDelivered, detachedStarted, detachedUnsettled, estimateCost, estimateMessageTokens, exhaustedWindow, extractJson, filterToolsByAllowList, filterToolsByCanUse, filterToolsByEnabled, filterToolsByRole, findCatalogModel, gateFollowUps, gateTail, isControlFlowSignal, isReplayIntegrityError, isToolEnabled, loadSkill, mayDecideApproval, memoryForgetVerdict, memoryWriteVerdict, mergeUi, normalizeDelegation, observeTurnFrames, offerMemories, offerSkills, publishAgentDelegated, publishAgentMemoryResolved, publishAgentMemoryWritten, publishAgentMessage, publishAgentQuotaExceeded, publishAgentRetrieved, publishAgentRunFailed, publishAgentRunFinished, publishAgentRunStarted, publishAgentSkillsResolved, publishAgentToolCall, publishAgentToolRetry, quotaPeriodRange, quotaUsedRatio, quotaWarning, releaseGatedFrames, rememberInputSchema, rememberToolDefinition, repairInstruction, resolveGateLookback, resolveMemoryDigest, resolveOutputGateMode, resolveSkillCatalog, rollupThreadUsage, runAgentLoop, runInputProcessors, runOutputProcessors, seedModelPrices, settleAll, settleUnsettledDelegation, skillInputSchema, skillToolDefinition, skillWriteVerdict, stampToolKinds, staticModelCatalog, staticSkillProvider, summarizeWithModel, tenantScope, toolCallApprovalFromRow, traceLlmTurn, traceToolExecution, truncateDetailContent, unwrapToolStepOutput, validateStructured, windowHistory, withAskTool, withMemoryTool, withSelectedModel, withSkillTool, withToolTimeout, withTurnFrames, wrapToolStepOutput, writeMemory };
3529
+ export { AGENT_ACTOR_DIRECTORY, AGENT_ACTOR_RESOLVER, AGENT_APPROVAL_PORT, AGENT_ATTACHMENT_STAGING, AGENT_DEPS_FACTORY, AGENT_DIAGNOSTIC_EVENTS, AGENT_DURABLE_RUNNER, AGENT_EMBEDDING_PROVIDER, AGENT_GOVERNANCE_QUERIES, AGENT_MEMORY, AGENT_MODEL, AGENT_MODEL_CATALOG, AGENT_OPTIONS, AGENT_PRICING_STORE, AGENT_PROMPT_CONTRIBUTORS, AGENT_QUOTA_PROVIDER, AGENT_QUOTA_STORE, AGENT_REGISTRY, AGENT_RETRIEVER, AGENT_ROLES_POLICY, AGENT_RUNNER, AGENT_SINK, AGENT_SKILLS, AGENT_SKILL_SOURCES, AGENT_SPAN_EVENTS, AGENT_STORE, AGENT_TOOL_REGISTRY, APPROVAL_EXPIRED_REASON, Actor, type ActorDirectory, type ActorResolver, type ActorSpendRow, type AgentApprovalPort, AgentDefinition, type AgentDelegated, AgentDelegation, type AgentDiagnosticEvent, type AgentDiagnosticKey, type AgentFollowUpsSpan, type AgentGovernanceQueries, AgentIntake, type AgentLlmTurnSpan, type AgentLoopDeps, type AgentLoopHooks, type AgentLoopResult, type AgentMemoryResolved, type AgentMemoryWritten, type AgentMessageEvent, type AgentPricingStore, type AgentQuotaExceeded, AgentRegistry, type AgentRetrievalSpan, type AgentRetrieved, type AgentRunFailed, type AgentRunFinished, AgentRunInput, type AgentRunStartOptions, type AgentRunStarted, type AgentRunner, type AgentSkillsResolved, type AgentSpanEvent, AgentStore, AgentStreamError, AgentStreamEvent, type AgentStructuredOutputSpan, type AgentToolCallEvent, type AgentToolExecutionSpan, type AgentToolRetry, AgentUiComponent, AiToolCtx, AppendMessageInput, type ApprovalDecisionRef, type ApprovalPolicy, type ApprovalRequirement, type ApprovalThreadRef, type ApprovalToolRef, type ApprovalWhere, type AttachmentRef, type AttachmentStagingDescription, type AttachmentStagingStore, type BufferedModelTurnResult, type BuildMemoryBlockInput, ChatQueueStore, type CostUsage, CreateThreadInput, type CurrentModelPrice, DEFAULT_HISTORY_SUMMARY_INSTRUCTION, DEFAULT_MAX_FACT_CHARS, DEFAULT_MAX_MEMORIES, DEFAULT_MAX_SKILLS, DEFAULT_REFUSAL_REASON, DEFAULT_STRUCTURED_OUTPUT_INSTRUCTION, Decision, DefaultApprovalPolicy, DefaultRolesPolicy, type DetachedDelegationOutcome, type DetachedDelegationReceipt, DetachedDelivery, type DetailThreadRef, ElicitationRequest, type EmbeddingProvider, type EmitUi, EnqueueMessageInput, type ForgetMemoryInput, type FrameBuffer, GLOBAL_SCOPE, type GovernanceMessageRow, type GovernancePage, type GovernancePageQuery, type GovernancePendingApprovalRow, type GovernanceRange, type GovernanceRunDetail, type GovernanceRunRow, type GovernanceThreadDetail, type GovernanceThreadDetailQuery, type GovernanceThreadRow, type GovernanceToolCallRow, type GovernanceUsageInput, type GovernanceUsageRow, HistoryPolicy, HumanReply, InMemoryAgentStore, type IncrementalGate, InputProcessor, type ListMemoriesInput, type ListSkillsInput, type ListStagedAttachmentsInput, LlmStepEnvelope, type LoadSkillInput, type MemoryAuthor, type MemoryConfig, type MemoryDigest, type MemoryDigestEntry, type MemoryFact, type MemoryForgetRequest, type MemoryOrigin, type MemoryProvider, type MemoryRecord, type MemoryVerdict, type MemoryWriteOutcome, type MemoryWriteRequest, MessageAttachment, MessageFeedback, MessageUsage, ModelAnswer, type ModelCatalog, type ModelCatalogEntry, type ModelCatalogLock, type ModelCatalogProviderGroup, type ModelCatalogQuery, type ModelCatalogView, ModelMessage, type ModelPrice, type ModelPriceInput, type ModelProvider, type ModelSpendRow, type ModelTurnArgs, type ModelTurnResult, type ObservedTurnFrames, type OfferMemoriesInput, type OutputGateMode, type OutputGateResult, OutputProcessor, type OverriddenMemory, PageContext, type Passage, type PendingApprovalRow, ProcessedPrompt, ProcessorContext, PromptBuilder, PromptContributor, QueuePause, QueuedMessage, QueuedMessagePatch, type QuotaBlock, QuotaExceededError, type QuotaPeriod, type QuotaProvider, type QuotaQuery, type QuotaReport, QuotaState, type QuotaStore, type QuotaWarning, type QuotaWindow, REMEMBER_TOOL_DESCRIPTION, REMEMBER_TOOL_NAME, REQUESTER_APPROVER, RUN_FAILED_MESSAGE, RUN_NOT_ACTIVE_CODE, RUN_NOT_ACTIVE_MESSAGE, RUN_NO_LONGER_RUNNING, type RecentRunRow, RecordRunStartInput, RecordToolCallInput, RecordUsageInput, type RememberToolInput, type RerankOptions, type Reranker, type ResolveAttachmentInput, type ResolveMemoryDigestInput, type ResolvedDelegation, type RetrieveOptions, type Retriever, type RolesPolicy, type RunAgentBreakdownRow, RunCancelledError, type RunErrorBreakdownRow, type RunMetrics, type RunToolCallRow, type RunTrendPoint, type RunWhere, SKILL_TOOL_DESCRIPTION, SKILL_TOOL_NAME, type ScopeContext, type ScopeResolver, type SearchMemoriesInput, type SettleDeadRunInput, type SettledTask, type SinkWriter, type Skill, type SkillAuthor, type SkillCatalogEntry, type SkillContext, type SkillLoadOutcome, type SkillOffer, type SkillProvider, type SkillSummary, type SkillToolInput, type SkillWriteRequest, type SkillWriteVerdict, type SkillsConfig, type StageAttachmentInput, type StagedAttachment, type StoreMemoryInput, StoredMessage, type StreamError, type StructuredOutcome, StructuredOutputError, THREAD_DETAIL_CONTENT_CHARS, type ThreadActivityRow, ThreadDetail, type ThreadMessageRow, type ThreadMeta, type ThreadSpendRow, ThreadSummary, type ThreadUsageRollup, type ThreadWhere, type TokenStreamSink, type ToolCallActivityRow, ToolCallApproval, type ToolCallApprovalColumns, ToolCallApprovalState, ToolCallOutcome, ToolCallRequest, ToolCallStatus, type ToolCallWhere, ToolDefinition, ToolDescribeScope, ToolDisabledError, ToolForbiddenError, ToolHandler, ToolInputInvalidError, ToolKind, type ToolKindDeps, ToolNotFoundError, ToolRegistry, ToolResult, ToolSpec, type ToolStatRow, ToolStepEnvelope, ToolTransientRetrySetting, type TurnFrameSummary, type UiCollector, UpdateThreadInput, UpdateToolCallInput, type UsageTrendPoint, type WindowHistoryOptions, type WithMemoryToolInput, type WriteMemoryInput, actorScope, agentDiagnosticKey, agentFailureCode, bucketByActor, bucketByModel, bucketByThread, bucketUsageTrend, buildMemoryBlock, buildSkillsBlock, canActorUseTool, compositeSkillProvider, createFrameBuffer, createIncrementalGate, createNoopEmitUi, createUiCollector, dayBoundsUtc, defaultCanDecide, defaultScopeResolver, detachedDelivered, detachedStarted, detachedUnsettled, estimateCost, estimateMessageTokens, exhaustedWindow, exposeStreamErrorDetails, extractJson, filterToolsByAllowList, filterToolsByCanUse, filterToolsByEnabled, filterToolsByRole, findCatalogModel, gateFollowUps, gateTail, isControlFlowSignal, isReplayIntegrityError, isToolEnabled, loadSkill, mayDecideApproval, memoryForgetVerdict, memoryWriteVerdict, mergeUi, normalizeDelegation, observeTurnFrames, offerMemories, offerSkills, publishAgentDelegated, publishAgentMemoryResolved, publishAgentMemoryWritten, publishAgentMessage, publishAgentQuotaExceeded, publishAgentRetrieved, publishAgentRunFailed, publishAgentRunFinished, publishAgentRunStarted, publishAgentSkillsResolved, publishAgentToolCall, publishAgentToolRetry, quotaPeriodRange, quotaUsedRatio, quotaWarning, releaseGatedFrames, rememberInputSchema, rememberToolDefinition, repairInstruction, resolveGateLookback, resolveMemoryDigest, resolveOutputGateMode, resolveSkillCatalog, rollupThreadUsage, runAgentLoop, runInputProcessors, runOutputProcessors, seedModelPrices, settleAll, settleDeadRun, settleUnsettledDelegation, skillInputSchema, skillToolDefinition, skillWriteVerdict, stampToolKinds, staticModelCatalog, staticSkillProvider, streamFailure, summarizeWithModel, tenantScope, toolCallApprovalFromRow, toolCallContext, traceLlmTurn, traceToolExecution, truncateDetailContent, unwrapToolStepOutput, validateStructured, windowHistory, withAskTool, withMemoryTool, withSelectedModel, withSkillTool, withToolTimeout, withTurnFrames, wrapToolStepOutput, writeMemory };
package/dist/index.d.ts CHANGED
@@ -1,8 +1,8 @@
1
- import { M as ModelMessage, c as ToolDefinition, d as ToolCallRequest, e as MessageUsage, f as AgentUiComponent, A as Actor, g as AiToolCtx, h as AgentStreamEvent, T as ToolSpec, Q as QuotaState, i as AgentRunInput, H as HumanReply, j as MessageAttachment, k as ToolKind, l as ToolCallStatus, m as ToolCallApproval, a as ToolHandler, n as HistoryPolicy, P as PageContext, o as AgentDefinition, p as AgentDelegation, q as AgentStore, D as DetachedDelivery, r as ToolDescribeScope, s as PromptBuilder, t as PromptContributor, u as ToolTransientRetrySetting, v as AgentIntake, w as Decision, E as ElicitationRequest, L as LlmStepEnvelope, x as ToolStepEnvelope, C as ChatQueueStore, y as CreateThreadInput, z as ThreadSummary, B as ThreadDetail, F as ToolCallApprovalState, U as UpdateThreadInput, R as RecordRunStartInput, G as EnqueueMessageInput, I as QueuedMessage, J as QueuedMessagePatch, K as QueuePause, N as AppendMessageInput, S as StoredMessage, O as ToolResult, V as MessageFeedback, W as RecordToolCallInput, X as UpdateToolCallInput, Y as RecordUsageInput } from './tool-CMTuoJ2v.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 AskToolInput, a7 as ChatQueueState, a8 as DEFAULT_INTAKE_PREAMBLE, a9 as DEFAULT_TOOL_TRANSIENT_RETRY_ATTEMPTS, aa as DEFAULT_TOOL_TRANSIENT_RETRY_BACKOFF_MS, ab as ELICITATION_INPUT_TYPES, ac as ElicitationInput, ad as ElicitationInputType, ae as ElicitationOption, af as ElicitationOutcome, ag as ElicitationQuestion, ah as ElicitationReply, ai as ElicitationResult, aj as HistoryPolicyContext, ak as HistorySelection, al as HistorySummary, am as InvokeWithTransientRetryOptions, an as MAX_ASK_QUESTIONS, ao as MessageFeedbackValue, ap as MessageRole, aq as PromptContext, ar as QueuePauseReason, as as QueuedMessageView, at as QuotaView, au as RecordRunEndInput, av as ThreadTurnPage, aw as ThreadTurnQuery, ax as ThreadTurnReader, ay as ToolCallApprovalStatus, az as ToolCatalogEntry, aA as ToolConfirmation, aB as ToolDescription, b as ToolPresentation, aC as ToolPresentationTone, aD as ToolResultField, aE as ToolResultView, aF as ToolStepCtx, aG as ToolTransientRetryNumbers, aH as ToolTransientRetryOptions, aI as UsagePurpose, aJ as askInputSchema, aK as askToolDefinition, aL as decodeStreamEvent, aM as encodeStreamEvent, aN as invokeWithTransientRetry, aO as isChatQueueStore, aP as isTransientToolError, aQ as isTypedQuestion, aR as normalizeElicitationReply, aS as questionOptions, aT as queuedMessageView, aU as readElicitationInput, aV as readElicitationQuestions, aW as releaseThreadRun, aX as renderElicitationAnswers, aY as resolveElicitation, aZ as resolveToolTransientRetryNumbers, a_ as settleElicitation, a$ as validateElicitationAnswer, b0 as validateElicitationValue } from './tool-CMTuoJ2v.js';
1
+ import { M as ModelMessage, c as ToolDefinition, d as ToolCallRequest, e as MessageUsage, f as AgentUiComponent, A as Actor, g as AiToolCtx, h as AgentStreamEvent, T as ToolSpec, Q as QuotaState, i as AgentRunInput, H as HumanReply, j as MessageAttachment, k as ToolKind, l as ToolCallStatus, m as ToolCallApproval, a as ToolHandler, n as HistoryPolicy, P as PageContext, o as AgentDefinition, p as AgentStore, q as AgentDelegation, D as DetachedDelivery, r as ToolDescribeScope, s as PromptBuilder, t as PromptContributor, u as ToolTransientRetrySetting, v as AgentIntake, w as Decision, E as ElicitationRequest, L as LlmStepEnvelope, x as ToolStepEnvelope, C as ChatQueueStore, y as CreateThreadInput, z as ThreadSummary, B as ThreadDetail, F as ToolCallApprovalState, U as UpdateThreadInput, R as RecordRunStartInput, G as EnqueueMessageInput, I as QueuedMessage, J as QueuedMessagePatch, K as QueuePause, N as AppendMessageInput, S as StoredMessage, O as ToolResult, V as MessageFeedback, W as RecordToolCallInput, X as ToolCallOutcome, Y as UpdateToolCallInput, Z as RecordUsageInput } from './tool-C128TFWw.js';
2
+ export { _ as ALL_AGENTS, $ as ASK_TOOL_DESCRIPTION, a0 as ASK_TOOL_NAME, a1 as AgentApprovalRequest, a2 as AgentApprovalSettlement, a3 as AgentAttachmentConfig, a4 as AgentCatalogEntry, a5 as AgentClientConfig, a6 as AgentHistoryWindow, a7 as AgentStreamErrorCode, a8 as AskToolInput, a9 as ChatQueueState, aa as DEFAULT_INTAKE_PREAMBLE, ab as DEFAULT_TOOL_TRANSIENT_RETRY_ATTEMPTS, ac as DEFAULT_TOOL_TRANSIENT_RETRY_BACKOFF_MS, ad as ELICITATION_INPUT_TYPES, ae as ElicitationInput, af as ElicitationInputType, ag as ElicitationOption, ah as ElicitationOutcome, ai as ElicitationQuestion, aj as ElicitationReply, ak as ElicitationResult, al as HistoryPolicyContext, am as HistorySelection, an as HistorySummary, ao as InvokeWithTransientRetryOptions, ap as MAX_ASK_QUESTIONS, aq as MessageFeedbackValue, ar as MessageRole, 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, aE as ToolDescription, b as ToolPresentation, aF as ToolPresentationTone, aG as ToolResultField, aH as ToolResultView, aI as ToolStepCtx, aJ as ToolTransientRetryNumbers, aK as ToolTransientRetryOptions, aL as 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 './tool-C128TFWw.js';
3
3
  import { StandardSchemaV1 } from '@standard-schema/spec';
4
- import { O as OutputProcessor, P as ProcessorContext, I as InputProcessor, a as ProcessedPrompt, M as ModelAnswer } from './processors-C1jir8eB.js';
5
- export { D as DEFAULT_INCREMENTAL_LOOKBACK_CHARS, b as IncrementalGating, c as OutputRejectedError, d as OutputVerdict, e as ProcessorFailedError } from './processors-C1jir8eB.js';
4
+ import { O as OutputProcessor, P as ProcessorContext, I as InputProcessor, a as ProcessedPrompt, M as ModelAnswer } from './processors-CtrfAA0B.js';
5
+ export { D as DEFAULT_INCREMENTAL_LOOKBACK_CHARS, b as IncrementalGating, c as OutputRejectedError, d as OutputVerdict, e as ProcessorFailedError } from './processors-CtrfAA0B.js';
6
6
  import { ChannelRegistry } from '@dudousxd/nestjs-diagnostics';
7
7
 
8
8
  /**
@@ -2368,6 +2368,42 @@ declare function isReplayIntegrityError(error: unknown): boolean;
2368
2368
  */
2369
2369
  declare function isControlFlowSignal(error: unknown): boolean;
2370
2370
 
2371
+ /** The `code` a decision answers with when the run it was for is over (`409`). */
2372
+ declare const RUN_NOT_ACTIVE_CODE = "run_not_active";
2373
+ /** What a person is told when they decide on a request whose run is over. */
2374
+ declare const RUN_NOT_ACTIVE_MESSAGE = "This request is no longer waiting for an answer: the turn it belonged to has ended. Send the message again.";
2375
+ /** What is written on the row of a run that was found over without having said so itself. */
2376
+ declare const RUN_NO_LONGER_RUNNING = "the run is no longer running";
2377
+ interface SettleDeadRunInput {
2378
+ runId: string;
2379
+ /** Set for a thread's own turn: the thread is released if this run still holds it. */
2380
+ threadId?: string;
2381
+ /**
2382
+ * Settle the run ROW as `failed` with this. Pass it only where the caller KNOWS the run failed
2383
+ * (the run's own body, unwinding). `recordRunEnd` is last-write-wins, so a caller that only knows
2384
+ * the run is no longer running — it may have completed — must leave the row alone.
2385
+ */
2386
+ failure?: {
2387
+ code: string;
2388
+ message: string;
2389
+ };
2390
+ }
2391
+ /**
2392
+ * Leave nothing waiting on a run that is over and did not say so itself.
2393
+ *
2394
+ * A run normally settles its own row, its calls and its thread from inside its body. One that is
2395
+ * refused a checkpoint position, or whose worker died, never gets there: a call it had put to a
2396
+ * person stays `pending_approval` — an approval card that takes a "yes" and then does nothing, for
2397
+ * ever — and its thread stays pointed at it. Everything here is written straight to the store,
2398
+ * outside any checkpoint, because the callers are exactly the paths that have no journal left to
2399
+ * write to; each write is idempotent (only still-pending calls, a release conditional on the
2400
+ * holder), so doing it twice changes nothing.
2401
+ *
2402
+ * Best-effort on purpose: this runs while something else is already failing, and must not replace
2403
+ * that failure with one of its own.
2404
+ */
2405
+ declare function settleDeadRun(store: AgentStore, input: SettleDeadRunInput): Promise<void>;
2406
+
2371
2407
  /** An agent->agent edge with its awaited-or-not resolved, whichever form it was authored in. */
2372
2408
  interface ResolvedDelegation {
2373
2409
  agent: string;
@@ -2937,6 +2973,30 @@ declare class RunCancelledError extends Error {
2937
2973
  * page whoever is on call for model failures.
2938
2974
  */
2939
2975
  declare function agentFailureCode(error: unknown): string;
2976
+ /**
2977
+ * What a person is told when a run fails for a reason that is ours rather than theirs. The error's
2978
+ * own text is for whoever operates the deployment: it names run ids, checkpoint positions and
2979
+ * provider internals ("non-determinism at <uuid>#41 …", "No output generated. Check the stream for
2980
+ * errors."), which mean nothing to the person reading the chat and are not theirs to see.
2981
+ */
2982
+ declare const RUN_FAILED_MESSAGE = "The assistant could not finish this answer. Please try again.";
2983
+ /**
2984
+ * Whether an error frame carries the error's own message. Unset → only outside production
2985
+ * (`NODE_ENV !== 'production'`), where the person reading the stream is the one debugging it.
2986
+ * `true`/`false` decides it outright; `undefined` returns to the default.
2987
+ */
2988
+ declare function exposeStreamErrorDetails(expose: boolean | undefined): void;
2989
+ /**
2990
+ * The terminal a failed run closes its stream with — what `SinkWriter.fail` takes, and what the
2991
+ * transport sends as the `event: error` frame.
2992
+ *
2993
+ * The frame is what the PERSON sees. For a crash it carries a stable `code` (what a client branches
2994
+ * on, and translates) and {@link RUN_FAILED_MESSAGE}; the error itself belongs in the log and on the
2995
+ * run row, which is where the runners put it. Outside production the raw message rides the frame as
2996
+ * it always did (see {@link exposeStreamErrorDetails}). A message the library words itself
2997
+ * (`quota_exceeded`, `output_rejected`, `structured_output_invalid`) is sent as it is.
2998
+ */
2999
+ declare function streamFailure(error: unknown): StreamError;
2940
3000
  /** Reject if `work` doesn't settle within `ms`. The underlying work is left to finish on its own. */
2941
3001
  declare function withToolTimeout<T>(work: Promise<T>, ms: number, toolName: string): Promise<T>;
2942
3002
  /**
@@ -2985,6 +3045,16 @@ declare function withAskTool({ tools, ask, }: {
2985
3045
  tools: ToolDefinition[];
2986
3046
  ask: boolean | undefined;
2987
3047
  }): ToolDefinition[];
3048
+ /**
3049
+ * The per-CALL half of a tool's context: which call this is, and the key that stays the same for
3050
+ * every execution of it (see {@link AiToolCtx.idempotencyKey}).
3051
+ */
3052
+ declare function toolCallContext<T extends {
3053
+ runId: string;
3054
+ }>(ctx: T, toolCallId: string): T & {
3055
+ toolCallId: string;
3056
+ idempotencyKey: string;
3057
+ };
2988
3058
  /** The reason an expired call is denied with — on the row, the stream frame and the result. */
2989
3059
  declare const APPROVAL_EXPIRED_REASON = "approval expired";
2990
3060
  /**
@@ -3403,6 +3473,8 @@ declare class InMemoryAgentStore implements AgentStore, ChatQueueStore {
3403
3473
  */
3404
3474
  referencedMediaIds(actorRef: string, mediaIds: readonly string[]): Promise<string[]>;
3405
3475
  recordToolCall(input: RecordToolCallInput): Promise<void>;
3476
+ toolCallOutcomes(toolCallIds: readonly string[]): Promise<ToolCallOutcome[]>;
3477
+ failUnsettledToolCalls(runId: string, error: string): Promise<number>;
3406
3478
  updateToolCall(input: UpdateToolCallInput): Promise<void>;
3407
3479
  recordUsage(input: RecordUsageInput): Promise<void>;
3408
3480
  quotaToday(actorRef: string, day: string): Promise<{
@@ -3454,4 +3526,4 @@ declare class InMemoryAgentStore implements AgentStore, ChatQueueStore {
3454
3526
  private toSummary;
3455
3527
  }
3456
3528
 
3457
- export { AGENT_ACTOR_DIRECTORY, AGENT_ACTOR_RESOLVER, AGENT_APPROVAL_PORT, AGENT_ATTACHMENT_STAGING, AGENT_DEPS_FACTORY, AGENT_DIAGNOSTIC_EVENTS, AGENT_DURABLE_RUNNER, AGENT_EMBEDDING_PROVIDER, AGENT_GOVERNANCE_QUERIES, AGENT_MEMORY, AGENT_MODEL, AGENT_MODEL_CATALOG, AGENT_OPTIONS, AGENT_PRICING_STORE, AGENT_PROMPT_CONTRIBUTORS, AGENT_QUOTA_PROVIDER, AGENT_QUOTA_STORE, AGENT_REGISTRY, AGENT_RETRIEVER, AGENT_ROLES_POLICY, AGENT_RUNNER, AGENT_SINK, AGENT_SKILLS, AGENT_SKILL_SOURCES, AGENT_SPAN_EVENTS, AGENT_STORE, AGENT_TOOL_REGISTRY, APPROVAL_EXPIRED_REASON, Actor, type ActorDirectory, type ActorResolver, type ActorSpendRow, type AgentApprovalPort, AgentDefinition, type AgentDelegated, AgentDelegation, type AgentDiagnosticEvent, type AgentDiagnosticKey, type AgentFollowUpsSpan, type AgentGovernanceQueries, AgentIntake, type AgentLlmTurnSpan, type AgentLoopDeps, type AgentLoopHooks, type AgentLoopResult, type AgentMemoryResolved, type AgentMemoryWritten, type AgentMessageEvent, type AgentPricingStore, type AgentQuotaExceeded, AgentRegistry, type AgentRetrievalSpan, type AgentRetrieved, type AgentRunFailed, type AgentRunFinished, AgentRunInput, type AgentRunStartOptions, type AgentRunStarted, type AgentRunner, type AgentSkillsResolved, type AgentSpanEvent, AgentStore, AgentStreamError, AgentStreamEvent, type AgentStructuredOutputSpan, type AgentToolCallEvent, type AgentToolExecutionSpan, type AgentToolRetry, AgentUiComponent, AiToolCtx, AppendMessageInput, type ApprovalDecisionRef, type ApprovalPolicy, type ApprovalRequirement, type ApprovalThreadRef, type ApprovalToolRef, type ApprovalWhere, type AttachmentRef, type AttachmentStagingDescription, type AttachmentStagingStore, type BufferedModelTurnResult, type BuildMemoryBlockInput, ChatQueueStore, type CostUsage, CreateThreadInput, type CurrentModelPrice, DEFAULT_HISTORY_SUMMARY_INSTRUCTION, DEFAULT_MAX_FACT_CHARS, DEFAULT_MAX_MEMORIES, DEFAULT_MAX_SKILLS, DEFAULT_REFUSAL_REASON, DEFAULT_STRUCTURED_OUTPUT_INSTRUCTION, Decision, DefaultApprovalPolicy, DefaultRolesPolicy, type DetachedDelegationOutcome, type DetachedDelegationReceipt, DetachedDelivery, type DetailThreadRef, ElicitationRequest, type EmbeddingProvider, type EmitUi, EnqueueMessageInput, type ForgetMemoryInput, type FrameBuffer, GLOBAL_SCOPE, type GovernanceMessageRow, type GovernancePage, type GovernancePageQuery, type GovernancePendingApprovalRow, type GovernanceRange, type GovernanceRunDetail, type GovernanceRunRow, type GovernanceThreadDetail, type GovernanceThreadDetailQuery, type GovernanceThreadRow, type GovernanceToolCallRow, type GovernanceUsageInput, type GovernanceUsageRow, HistoryPolicy, HumanReply, InMemoryAgentStore, type IncrementalGate, InputProcessor, type ListMemoriesInput, type ListSkillsInput, type ListStagedAttachmentsInput, LlmStepEnvelope, type LoadSkillInput, type MemoryAuthor, type MemoryConfig, type MemoryDigest, type MemoryDigestEntry, type MemoryFact, type MemoryForgetRequest, type MemoryOrigin, type MemoryProvider, type MemoryRecord, type MemoryVerdict, type MemoryWriteOutcome, type MemoryWriteRequest, MessageAttachment, MessageFeedback, MessageUsage, ModelAnswer, type ModelCatalog, type ModelCatalogEntry, type ModelCatalogLock, type ModelCatalogProviderGroup, type ModelCatalogQuery, type ModelCatalogView, ModelMessage, type ModelPrice, type ModelPriceInput, type ModelProvider, type ModelSpendRow, type ModelTurnArgs, type ModelTurnResult, type ObservedTurnFrames, type OfferMemoriesInput, type OutputGateMode, type OutputGateResult, OutputProcessor, type OverriddenMemory, PageContext, type Passage, type PendingApprovalRow, ProcessedPrompt, ProcessorContext, PromptBuilder, PromptContributor, QueuePause, QueuedMessage, QueuedMessagePatch, type QuotaBlock, QuotaExceededError, type QuotaPeriod, type QuotaProvider, type QuotaQuery, type QuotaReport, QuotaState, type QuotaStore, type QuotaWarning, type QuotaWindow, REMEMBER_TOOL_DESCRIPTION, REMEMBER_TOOL_NAME, REQUESTER_APPROVER, type RecentRunRow, RecordRunStartInput, RecordToolCallInput, 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 ThreadUsageRollup, type ThreadWhere, type TokenStreamSink, type ToolCallActivityRow, ToolCallApproval, type ToolCallApprovalColumns, ToolCallApprovalState, ToolCallRequest, ToolCallStatus, type ToolCallWhere, ToolDefinition, ToolDescribeScope, ToolDisabledError, ToolForbiddenError, ToolHandler, ToolInputInvalidError, ToolKind, type ToolKindDeps, ToolNotFoundError, ToolRegistry, ToolResult, ToolSpec, type ToolStatRow, ToolStepEnvelope, ToolTransientRetrySetting, type TurnFrameSummary, type UiCollector, UpdateThreadInput, UpdateToolCallInput, type UsageTrendPoint, type WindowHistoryOptions, type WithMemoryToolInput, type WriteMemoryInput, actorScope, agentDiagnosticKey, agentFailureCode, bucketByActor, bucketByModel, bucketByThread, bucketUsageTrend, buildMemoryBlock, buildSkillsBlock, canActorUseTool, compositeSkillProvider, createFrameBuffer, createIncrementalGate, createNoopEmitUi, createUiCollector, dayBoundsUtc, defaultCanDecide, defaultScopeResolver, detachedDelivered, detachedStarted, detachedUnsettled, estimateCost, estimateMessageTokens, exhaustedWindow, extractJson, filterToolsByAllowList, filterToolsByCanUse, filterToolsByEnabled, filterToolsByRole, findCatalogModel, gateFollowUps, gateTail, isControlFlowSignal, isReplayIntegrityError, isToolEnabled, loadSkill, mayDecideApproval, memoryForgetVerdict, memoryWriteVerdict, mergeUi, normalizeDelegation, observeTurnFrames, offerMemories, offerSkills, publishAgentDelegated, publishAgentMemoryResolved, publishAgentMemoryWritten, publishAgentMessage, publishAgentQuotaExceeded, publishAgentRetrieved, publishAgentRunFailed, publishAgentRunFinished, publishAgentRunStarted, publishAgentSkillsResolved, publishAgentToolCall, publishAgentToolRetry, quotaPeriodRange, quotaUsedRatio, quotaWarning, releaseGatedFrames, rememberInputSchema, rememberToolDefinition, repairInstruction, resolveGateLookback, resolveMemoryDigest, resolveOutputGateMode, resolveSkillCatalog, rollupThreadUsage, runAgentLoop, runInputProcessors, runOutputProcessors, seedModelPrices, settleAll, settleUnsettledDelegation, skillInputSchema, skillToolDefinition, skillWriteVerdict, stampToolKinds, staticModelCatalog, staticSkillProvider, summarizeWithModel, tenantScope, toolCallApprovalFromRow, traceLlmTurn, traceToolExecution, truncateDetailContent, unwrapToolStepOutput, validateStructured, windowHistory, withAskTool, withMemoryTool, withSelectedModel, withSkillTool, withToolTimeout, withTurnFrames, wrapToolStepOutput, writeMemory };
3529
+ export { AGENT_ACTOR_DIRECTORY, AGENT_ACTOR_RESOLVER, AGENT_APPROVAL_PORT, AGENT_ATTACHMENT_STAGING, AGENT_DEPS_FACTORY, AGENT_DIAGNOSTIC_EVENTS, AGENT_DURABLE_RUNNER, AGENT_EMBEDDING_PROVIDER, AGENT_GOVERNANCE_QUERIES, AGENT_MEMORY, AGENT_MODEL, AGENT_MODEL_CATALOG, AGENT_OPTIONS, AGENT_PRICING_STORE, AGENT_PROMPT_CONTRIBUTORS, AGENT_QUOTA_PROVIDER, AGENT_QUOTA_STORE, AGENT_REGISTRY, AGENT_RETRIEVER, AGENT_ROLES_POLICY, AGENT_RUNNER, AGENT_SINK, AGENT_SKILLS, AGENT_SKILL_SOURCES, AGENT_SPAN_EVENTS, AGENT_STORE, AGENT_TOOL_REGISTRY, APPROVAL_EXPIRED_REASON, Actor, type ActorDirectory, type ActorResolver, type ActorSpendRow, type AgentApprovalPort, AgentDefinition, type AgentDelegated, AgentDelegation, type AgentDiagnosticEvent, type AgentDiagnosticKey, type AgentFollowUpsSpan, type AgentGovernanceQueries, AgentIntake, type AgentLlmTurnSpan, type AgentLoopDeps, type AgentLoopHooks, type AgentLoopResult, type AgentMemoryResolved, type AgentMemoryWritten, type AgentMessageEvent, type AgentPricingStore, type AgentQuotaExceeded, AgentRegistry, type AgentRetrievalSpan, type AgentRetrieved, type AgentRunFailed, type AgentRunFinished, AgentRunInput, type AgentRunStartOptions, type AgentRunStarted, type AgentRunner, type AgentSkillsResolved, type AgentSpanEvent, AgentStore, AgentStreamError, AgentStreamEvent, type AgentStructuredOutputSpan, type AgentToolCallEvent, type AgentToolExecutionSpan, type AgentToolRetry, AgentUiComponent, AiToolCtx, AppendMessageInput, type ApprovalDecisionRef, type ApprovalPolicy, type ApprovalRequirement, type ApprovalThreadRef, type ApprovalToolRef, type ApprovalWhere, type AttachmentRef, type AttachmentStagingDescription, type AttachmentStagingStore, type BufferedModelTurnResult, type BuildMemoryBlockInput, ChatQueueStore, type CostUsage, CreateThreadInput, type CurrentModelPrice, DEFAULT_HISTORY_SUMMARY_INSTRUCTION, DEFAULT_MAX_FACT_CHARS, DEFAULT_MAX_MEMORIES, DEFAULT_MAX_SKILLS, DEFAULT_REFUSAL_REASON, DEFAULT_STRUCTURED_OUTPUT_INSTRUCTION, Decision, DefaultApprovalPolicy, DefaultRolesPolicy, type DetachedDelegationOutcome, type DetachedDelegationReceipt, DetachedDelivery, type DetailThreadRef, ElicitationRequest, type EmbeddingProvider, type EmitUi, EnqueueMessageInput, type ForgetMemoryInput, type FrameBuffer, GLOBAL_SCOPE, type GovernanceMessageRow, type GovernancePage, type GovernancePageQuery, type GovernancePendingApprovalRow, type GovernanceRange, type GovernanceRunDetail, type GovernanceRunRow, type GovernanceThreadDetail, type GovernanceThreadDetailQuery, type GovernanceThreadRow, type GovernanceToolCallRow, type GovernanceUsageInput, type GovernanceUsageRow, HistoryPolicy, HumanReply, InMemoryAgentStore, type IncrementalGate, InputProcessor, type ListMemoriesInput, type ListSkillsInput, type ListStagedAttachmentsInput, LlmStepEnvelope, type LoadSkillInput, type MemoryAuthor, type MemoryConfig, type MemoryDigest, type MemoryDigestEntry, type MemoryFact, type MemoryForgetRequest, type MemoryOrigin, type MemoryProvider, type MemoryRecord, type MemoryVerdict, type MemoryWriteOutcome, type MemoryWriteRequest, MessageAttachment, MessageFeedback, MessageUsage, ModelAnswer, type ModelCatalog, type ModelCatalogEntry, type ModelCatalogLock, type ModelCatalogProviderGroup, type ModelCatalogQuery, type ModelCatalogView, ModelMessage, type ModelPrice, type ModelPriceInput, type ModelProvider, type ModelSpendRow, type ModelTurnArgs, type ModelTurnResult, type ObservedTurnFrames, type OfferMemoriesInput, type OutputGateMode, type OutputGateResult, OutputProcessor, type OverriddenMemory, PageContext, type Passage, type PendingApprovalRow, ProcessedPrompt, ProcessorContext, PromptBuilder, PromptContributor, QueuePause, QueuedMessage, QueuedMessagePatch, type QuotaBlock, QuotaExceededError, type QuotaPeriod, type QuotaProvider, type QuotaQuery, type QuotaReport, QuotaState, type QuotaStore, type QuotaWarning, type QuotaWindow, REMEMBER_TOOL_DESCRIPTION, REMEMBER_TOOL_NAME, REQUESTER_APPROVER, RUN_FAILED_MESSAGE, RUN_NOT_ACTIVE_CODE, RUN_NOT_ACTIVE_MESSAGE, RUN_NO_LONGER_RUNNING, type RecentRunRow, RecordRunStartInput, RecordToolCallInput, RecordUsageInput, type RememberToolInput, type RerankOptions, type Reranker, type ResolveAttachmentInput, type ResolveMemoryDigestInput, type ResolvedDelegation, type RetrieveOptions, type Retriever, type RolesPolicy, type RunAgentBreakdownRow, RunCancelledError, type RunErrorBreakdownRow, type RunMetrics, type RunToolCallRow, type RunTrendPoint, type RunWhere, SKILL_TOOL_DESCRIPTION, SKILL_TOOL_NAME, type ScopeContext, type ScopeResolver, type SearchMemoriesInput, type SettleDeadRunInput, type SettledTask, type SinkWriter, type Skill, type SkillAuthor, type SkillCatalogEntry, type SkillContext, type SkillLoadOutcome, type SkillOffer, type SkillProvider, type SkillSummary, type SkillToolInput, type SkillWriteRequest, type SkillWriteVerdict, type SkillsConfig, type StageAttachmentInput, type StagedAttachment, type StoreMemoryInput, StoredMessage, type StreamError, type StructuredOutcome, StructuredOutputError, THREAD_DETAIL_CONTENT_CHARS, type ThreadActivityRow, ThreadDetail, type ThreadMessageRow, type ThreadMeta, type ThreadSpendRow, ThreadSummary, type ThreadUsageRollup, type ThreadWhere, type TokenStreamSink, type ToolCallActivityRow, ToolCallApproval, type ToolCallApprovalColumns, ToolCallApprovalState, ToolCallOutcome, ToolCallRequest, ToolCallStatus, type ToolCallWhere, ToolDefinition, ToolDescribeScope, ToolDisabledError, ToolForbiddenError, ToolHandler, ToolInputInvalidError, ToolKind, type ToolKindDeps, ToolNotFoundError, ToolRegistry, ToolResult, ToolSpec, type ToolStatRow, ToolStepEnvelope, ToolTransientRetrySetting, type TurnFrameSummary, type UiCollector, UpdateThreadInput, UpdateToolCallInput, type UsageTrendPoint, type WindowHistoryOptions, type WithMemoryToolInput, type WriteMemoryInput, actorScope, agentDiagnosticKey, agentFailureCode, bucketByActor, bucketByModel, bucketByThread, bucketUsageTrend, buildMemoryBlock, buildSkillsBlock, canActorUseTool, compositeSkillProvider, createFrameBuffer, createIncrementalGate, createNoopEmitUi, createUiCollector, dayBoundsUtc, defaultCanDecide, defaultScopeResolver, detachedDelivered, detachedStarted, detachedUnsettled, estimateCost, estimateMessageTokens, exhaustedWindow, exposeStreamErrorDetails, extractJson, filterToolsByAllowList, filterToolsByCanUse, filterToolsByEnabled, filterToolsByRole, findCatalogModel, gateFollowUps, gateTail, isControlFlowSignal, isReplayIntegrityError, isToolEnabled, loadSkill, mayDecideApproval, memoryForgetVerdict, memoryWriteVerdict, mergeUi, normalizeDelegation, observeTurnFrames, offerMemories, offerSkills, publishAgentDelegated, publishAgentMemoryResolved, publishAgentMemoryWritten, publishAgentMessage, publishAgentQuotaExceeded, publishAgentRetrieved, publishAgentRunFailed, publishAgentRunFinished, publishAgentRunStarted, publishAgentSkillsResolved, publishAgentToolCall, publishAgentToolRetry, quotaPeriodRange, quotaUsedRatio, quotaWarning, releaseGatedFrames, rememberInputSchema, rememberToolDefinition, repairInstruction, resolveGateLookback, resolveMemoryDigest, resolveOutputGateMode, resolveSkillCatalog, rollupThreadUsage, runAgentLoop, runInputProcessors, runOutputProcessors, seedModelPrices, settleAll, settleDeadRun, settleUnsettledDelegation, skillInputSchema, skillToolDefinition, skillWriteVerdict, stampToolKinds, staticModelCatalog, staticSkillProvider, streamFailure, summarizeWithModel, tenantScope, toolCallApprovalFromRow, toolCallContext, traceLlmTurn, traceToolExecution, truncateDetailContent, unwrapToolStepOutput, validateStructured, windowHistory, withAskTool, withMemoryTool, withSelectedModel, withSkillTool, withToolTimeout, withTurnFrames, wrapToolStepOutput, writeMemory };
package/dist/index.js CHANGED
@@ -2348,6 +2348,123 @@ function isControlFlowSignal(error) {
2348
2348
  }
2349
2349
  __name(isControlFlowSignal, "isControlFlowSignal");
2350
2350
 
2351
+ // src/dangling-tool-calls.ts
2352
+ var UNFINISHED_TOOL_CALL = "This tool call was never completed: the turn it belonged to ended unexpectedly before it was settled. Do not assume it ran, and do not assume it did not \u2014 check the current state with a read tool if one exists, tell the person plainly what is and is not confirmed, and do it again only if they still want it.";
2353
+ var RUN_ENDED_BEFORE_TOOL_CALL = "the run ended before this tool call was settled";
2354
+ var DECLINED = "The person was asked to approve this action and declined it. Nothing ran and nothing changed.";
2355
+ var EXPIRED = "This action needed approval, and the request expired before anyone decided. Nothing ran.";
2356
+ function danglingToolCallIds(messages) {
2357
+ const ids = [];
2358
+ for (const message of messages) {
2359
+ const calls = message.toolCalls ?? [];
2360
+ if (message.role !== "assistant" || calls.length === 0) {
2361
+ continue;
2362
+ }
2363
+ const settled = new Set((message.toolResults ?? []).map((result) => result.id));
2364
+ for (const call of calls) {
2365
+ if (!settled.has(call.id)) {
2366
+ ids.push(call.id);
2367
+ }
2368
+ }
2369
+ }
2370
+ return ids;
2371
+ }
2372
+ __name(danglingToolCallIds, "danglingToolCallIds");
2373
+ function resultFor(call, outcome) {
2374
+ const base = {
2375
+ id: call.id,
2376
+ name: call.name
2377
+ };
2378
+ switch (outcome?.status) {
2379
+ case "executed":
2380
+ case "auto_executed":
2381
+ return {
2382
+ ...base,
2383
+ output: outcome.output ?? null
2384
+ };
2385
+ case "failed":
2386
+ return {
2387
+ ...base,
2388
+ output: null,
2389
+ error: outcome.error ?? UNFINISHED_TOOL_CALL
2390
+ };
2391
+ case "rejected":
2392
+ return {
2393
+ ...base,
2394
+ output: {
2395
+ rejected: true
2396
+ },
2397
+ denied: true,
2398
+ error: DECLINED
2399
+ };
2400
+ case "expired":
2401
+ return {
2402
+ ...base,
2403
+ output: {
2404
+ rejected: true,
2405
+ expired: true
2406
+ },
2407
+ denied: true,
2408
+ expired: true,
2409
+ error: EXPIRED
2410
+ };
2411
+ default:
2412
+ return {
2413
+ ...base,
2414
+ output: null,
2415
+ error: UNFINISHED_TOOL_CALL
2416
+ };
2417
+ }
2418
+ }
2419
+ __name(resultFor, "resultFor");
2420
+ function settleDanglingToolCalls(messages, outcomes = []) {
2421
+ const known = new Map(outcomes.map((outcome) => [
2422
+ outcome.id,
2423
+ outcome
2424
+ ]));
2425
+ return messages.map((message) => {
2426
+ const calls = message.toolCalls ?? [];
2427
+ if (message.role !== "assistant" || calls.length === 0) {
2428
+ return message;
2429
+ }
2430
+ const results = message.toolResults ?? [];
2431
+ const settled = new Set(results.map((result) => result.id));
2432
+ const missing = calls.filter((call) => !settled.has(call.id));
2433
+ if (missing.length === 0) {
2434
+ return message;
2435
+ }
2436
+ return {
2437
+ ...message,
2438
+ toolResults: [
2439
+ ...results,
2440
+ ...missing.map((call) => resultFor(call, known.get(call.id)))
2441
+ ]
2442
+ };
2443
+ });
2444
+ }
2445
+ __name(settleDanglingToolCalls, "settleDanglingToolCalls");
2446
+
2447
+ // src/dead-run.ts
2448
+ var RUN_NOT_ACTIVE_CODE = "run_not_active";
2449
+ var RUN_NOT_ACTIVE_MESSAGE = "This request is no longer waiting for an answer: the turn it belonged to has ended. Send the message again.";
2450
+ var RUN_NO_LONGER_RUNNING = "the run is no longer running";
2451
+ async function settleDeadRun(store, input) {
2452
+ const failure = input.failure;
2453
+ if (failure !== void 0) {
2454
+ await Promise.resolve(store.recordRunEnd?.({
2455
+ runId: input.runId,
2456
+ status: "failed",
2457
+ errorCode: failure.code,
2458
+ errorMessage: failure.message
2459
+ })).catch(() => void 0);
2460
+ }
2461
+ await Promise.resolve(store.failUnsettledToolCalls?.(input.runId, RUN_ENDED_BEFORE_TOOL_CALL)).catch(() => 0);
2462
+ if (input.threadId !== void 0) {
2463
+ await releaseThreadRun(store, input.threadId, input.runId).catch(() => void 0);
2464
+ }
2465
+ }
2466
+ __name(settleDeadRun, "settleDeadRun");
2467
+
2351
2468
  // src/delegation.ts
2352
2469
  function normalizeDelegation(entry) {
2353
2470
  return typeof entry === "string" ? {
@@ -2812,9 +2929,46 @@ function agentFailureCode(error) {
2812
2929
  if (error instanceof StructuredOutputError) {
2813
2930
  return "structured_output_invalid";
2814
2931
  }
2815
- return "run_failed";
2932
+ if (isReplayIntegrityError(error)) {
2933
+ return "replay_diverged";
2934
+ }
2935
+ return isNoOutputError(error) ? "model_no_output" : "run_failed";
2816
2936
  }
2817
2937
  __name(agentFailureCode, "agentFailureCode");
2938
+ function isNoOutputError(error) {
2939
+ if (!(error instanceof Error)) {
2940
+ return false;
2941
+ }
2942
+ return error.name === "AI_NoOutputGeneratedError" || error.name === "NoOutputGeneratedError" || error.message.startsWith("No output generated");
2943
+ }
2944
+ __name(isNoOutputError, "isNoOutputError");
2945
+ var RUN_FAILED_MESSAGE = "The assistant could not finish this answer. Please try again.";
2946
+ var streamErrorDetails;
2947
+ function exposeStreamErrorDetails(expose) {
2948
+ streamErrorDetails = expose;
2949
+ }
2950
+ __name(exposeStreamErrorDetails, "exposeStreamErrorDetails");
2951
+ var WORDED_CODES = /* @__PURE__ */ new Set([
2952
+ "quota_exceeded",
2953
+ "output_rejected",
2954
+ "structured_output_invalid"
2955
+ ]);
2956
+ function streamFailure(error) {
2957
+ const detail = error instanceof Error ? error.message : String(error);
2958
+ const code = agentFailureCode(error);
2959
+ if (WORDED_CODES.has(code)) {
2960
+ return {
2961
+ code,
2962
+ message: detail
2963
+ };
2964
+ }
2965
+ const exposed = streamErrorDetails ?? process.env.NODE_ENV !== "production";
2966
+ return {
2967
+ code,
2968
+ message: exposed ? detail : RUN_FAILED_MESSAGE
2969
+ };
2970
+ }
2971
+ __name(streamFailure, "streamFailure");
2818
2972
  var MAX_DELEGATION_DEPTH = 5;
2819
2973
  var DEFAULT_MAX_AGENT_APPEARANCES = 1;
2820
2974
  function delegationRefusal(args) {
@@ -3006,9 +3160,9 @@ function splitHistory(policy, input, messages) {
3006
3160
  }
3007
3161
  __name(splitHistory, "splitHistory");
3008
3162
  async function loadSelectedHistory(deps, input, hooks) {
3009
- return hooks.step("load:thread", async () => {
3163
+ const recorded = await hooks.step("load:thread", async () => {
3010
3164
  const thread = await readThreadForTurn(deps, input.threadId);
3011
- const { keep, drop } = splitHistory(deps.historyPolicy, input, toModelMessages(thread.messages));
3165
+ const { keep, drop } = splitHistory(deps.historyPolicy, input, await settleHistory(deps, toModelMessages(thread.messages)));
3012
3166
  return {
3013
3167
  messages: keep,
3014
3168
  dropped: deps.historyPolicy?.summarize === void 0 ? [] : drop,
@@ -3016,8 +3170,21 @@ async function loadSelectedHistory(deps, input, hooks) {
3016
3170
  hasAssistantMessage: thread.hasAssistantMessage
3017
3171
  };
3018
3172
  });
3173
+ return {
3174
+ ...recorded,
3175
+ messages: settleDanglingToolCalls(recorded.messages)
3176
+ };
3019
3177
  }
3020
3178
  __name(loadSelectedHistory, "loadSelectedHistory");
3179
+ async function settleHistory(deps, messages) {
3180
+ const dangling = danglingToolCallIds(messages);
3181
+ if (dangling.length === 0) {
3182
+ return messages;
3183
+ }
3184
+ const outcomes = await Promise.resolve(deps.store.toolCallOutcomes?.(dangling) ?? []).catch(() => []);
3185
+ return settleDanglingToolCalls(messages, outcomes);
3186
+ }
3187
+ __name(settleHistory, "settleHistory");
3021
3188
  async function readThreadForTurn(deps, threadId) {
3022
3189
  const windowing = deps.store;
3023
3190
  if (typeof windowing.loadThreadForTurn === "function") {
@@ -3057,7 +3224,7 @@ __name(turnMessageLimit, "turnMessageLimit");
3057
3224
  async function loadWholeThread(deps, input, hooks) {
3058
3225
  const thread = await hooks.step("load:thread", () => deps.store.getThread(input.threadId));
3059
3226
  const stored = thread?.messages ?? [];
3060
- const { keep, drop } = splitHistory(deps.historyPolicy, input, toModelMessages(stored));
3227
+ const { keep, drop } = splitHistory(deps.historyPolicy, input, settleDanglingToolCalls(toModelMessages(stored)));
3061
3228
  return {
3062
3229
  messages: keep,
3063
3230
  dropped: drop,
@@ -3240,6 +3407,14 @@ async function awaitElicitation(hooks, request, ctx) {
3240
3407
  }, ctx));
3241
3408
  }
3242
3409
  __name(awaitElicitation, "awaitElicitation");
3410
+ function toolCallContext(ctx, toolCallId) {
3411
+ return {
3412
+ ...ctx,
3413
+ toolCallId,
3414
+ idempotencyKey: `${ctx.runId}:${toolCallId}`
3415
+ };
3416
+ }
3417
+ __name(toolCallContext, "toolCallContext");
3243
3418
  function toolContext(deps, input, hooks) {
3244
3419
  return {
3245
3420
  actor: input.actor,
@@ -3679,7 +3854,7 @@ async function invokeClaimedTool(turn, claimed) {
3679
3854
  }, () => invokeWithTransientRetry(() => {
3680
3855
  ui2.restart();
3681
3856
  return deps.registry.invoke(call.name, call.input, {
3682
- ...ctx,
3857
+ ...toolCallContext(ctx, call.id),
3683
3858
  emitUi: ui2.emit
3684
3859
  }, deps.rolesPolicy);
3685
3860
  }, deps.toolTransientRetry ?? {}, {
@@ -5277,6 +5452,36 @@ var InMemoryAgentStore = class {
5277
5452
  } : {}
5278
5453
  });
5279
5454
  }
5455
+ async toolCallOutcomes(toolCallIds) {
5456
+ const outcomes = [];
5457
+ for (const id of toolCallIds) {
5458
+ const row = this.toolCalls.get(id);
5459
+ if (row !== void 0) {
5460
+ outcomes.push({
5461
+ id,
5462
+ status: row.status,
5463
+ ...row.output !== void 0 ? {
5464
+ output: row.output
5465
+ } : {},
5466
+ ...row.error !== void 0 ? {
5467
+ error: row.error
5468
+ } : {}
5469
+ });
5470
+ }
5471
+ }
5472
+ return outcomes;
5473
+ }
5474
+ async failUnsettledToolCalls(runId, error) {
5475
+ let settled = 0;
5476
+ for (const row of this.toolCalls.values()) {
5477
+ if (row.runId === runId && row.status === "pending_approval") {
5478
+ row.status = "failed";
5479
+ row.error = error;
5480
+ settled += 1;
5481
+ }
5482
+ }
5483
+ return settled;
5484
+ }
5280
5485
  async updateToolCall(input) {
5281
5486
  const row = this.toolCalls.get(input.toolCallId);
5282
5487
  if (row === void 0) {
@@ -5603,6 +5808,11 @@ export {
5603
5808
  REMEMBER_TOOL_DESCRIPTION,
5604
5809
  REMEMBER_TOOL_NAME,
5605
5810
  REQUESTER_APPROVER,
5811
+ RUN_ENDED_BEFORE_TOOL_CALL,
5812
+ RUN_FAILED_MESSAGE,
5813
+ RUN_NOT_ACTIVE_CODE,
5814
+ RUN_NOT_ACTIVE_MESSAGE,
5815
+ RUN_NO_LONGER_RUNNING,
5606
5816
  RunCancelledError,
5607
5817
  SKILL_TOOL_DESCRIPTION,
5608
5818
  SKILL_TOOL_NAME,
@@ -5613,6 +5823,7 @@ export {
5613
5823
  ToolInputInvalidError,
5614
5824
  ToolNotFoundError,
5615
5825
  ToolRegistry,
5826
+ UNFINISHED_TOOL_CALL,
5616
5827
  actorScope,
5617
5828
  agentDiagnosticKey,
5618
5829
  agentFailureCode,
@@ -5630,6 +5841,7 @@ export {
5630
5841
  createIncrementalGate,
5631
5842
  createNoopEmitUi,
5632
5843
  createUiCollector,
5844
+ danglingToolCallIds,
5633
5845
  dayBoundsUtc,
5634
5846
  decodeStreamEvent,
5635
5847
  defaultCanDecide,
@@ -5641,6 +5853,7 @@ export {
5641
5853
  estimateCost,
5642
5854
  estimateMessageTokens,
5643
5855
  exhaustedWindow,
5856
+ exposeStreamErrorDetails,
5644
5857
  extractJson,
5645
5858
  filterToolsByAllowList,
5646
5859
  filterToolsByCanUse,
@@ -5703,6 +5916,8 @@ export {
5703
5916
  runOutputProcessors,
5704
5917
  seedModelPrices,
5705
5918
  settleAll,
5919
+ settleDanglingToolCalls,
5920
+ settleDeadRun,
5706
5921
  settleElicitation,
5707
5922
  settleUnsettledDelegation,
5708
5923
  skillInputSchema,
@@ -5711,9 +5926,11 @@ export {
5711
5926
  stampToolKinds,
5712
5927
  staticModelCatalog,
5713
5928
  staticSkillProvider,
5929
+ streamFailure,
5714
5930
  summarizeWithModel,
5715
5931
  tenantScope,
5716
5932
  toolCallApprovalFromRow,
5933
+ toolCallContext,
5717
5934
  traceLlmTurn,
5718
5935
  traceToolExecution,
5719
5936
  truncateDetailContent,