@dudousxd/nestjs-agent-core 0.15.1 → 0.15.3

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
@@ -440,15 +440,24 @@ interface ToolCallRequest {
440
440
  name: string;
441
441
  input: unknown;
442
442
  /**
443
- * The tool's declared kind (`ToolSpec.kind`), stamped by the loop from the tool registry so
444
- * thread-read consumers know a call's kind without hardcoding a tool-name allowlist. Undefined
445
- * only for a call the loop couldn't resolve against the registry (defensively treated as `read`
446
- * wherever a definite value is required).
443
+ * The tool's declared kind (`ToolSpec.kind`), stamped where the tool was OFFERED — inside the llm
444
+ * checkpoint, by the process that built the definition list the model chose from. It travels with
445
+ * the call from there, so thread-read consumers know a call's kind without hardcoding a tool-name
446
+ * allowlist, and the approval branch does not depend on which process replays the turn.
447
+ * Undefined only for a call that predates the stamp, or one no registry could resolve
448
+ * (defensively treated as `read` wherever a definite value is required).
447
449
  */
448
450
  kind?: ToolKind;
449
451
  }
450
452
  /** Result of running a tool. */
451
453
  interface ToolResult {
454
+ /**
455
+ * A person declined this action, so the tool never ran. Set INSTEAD of a failure, and read by
456
+ * every consumer that has to tell the two apart — the stream frame, the replayed transcript. The
457
+ * `error` field still carries what the MODEL is told, because that is the channel a model reads a
458
+ * tool's outcome on; this flag is what everything else reads.
459
+ */
460
+ denied?: true;
452
461
  id: string;
453
462
  name: string;
454
463
  output: unknown;
@@ -1102,6 +1111,18 @@ type AgentStreamEvent = {
1102
1111
  id: string;
1103
1112
  error: string;
1104
1113
  }
1114
+ /**
1115
+ * A person was asked to approve an action tool and declined it. Its own frame, NOT
1116
+ * `tool-output-error`: a refusal is a decision with a known outcome — nothing ran — while a
1117
+ * failure is an outcome nobody chose and whose effects are unknown. Rendering them the same way
1118
+ * tells an operator their own "no" was a malfunction. Maps onto the SDK's `output-denied` tool
1119
+ * part state, which a client reads without knowing any tool's name.
1120
+ */
1121
+ | {
1122
+ kind: 'tool-output-denied';
1123
+ id: string;
1124
+ reason?: string;
1125
+ }
1105
1126
  /**
1106
1127
  * The run has put a question set to the user and is parked until someone answers it (or skips).
1107
1128
  * Written by the LOOP for both elicitation surfaces — the configured intake and the model's `ask`
@@ -3909,6 +3930,28 @@ declare function traceToolExecution<T>(runId: string, call: {
3909
3930
  toolName: string;
3910
3931
  toolType: 'read' | 'action';
3911
3932
  }, run: () => Promise<T>): Promise<T>;
3933
+ /**
3934
+ * What resolving a call's kind needs: the registry, plus the three config flags whose reserved names
3935
+ * have no `ToolSpec` to look up. Narrow on purpose — {@link stampToolKinds} is called from a
3936
+ * dispatched step handler, which holds the host's own deps rather than a loop's.
3937
+ */
3938
+ type ToolKindDeps = Pick<AgentLoopDeps, 'registry' | 'ask' | 'skills' | 'memory'>;
3939
+ /**
3940
+ * Stamp each of a model turn's calls with the kind declared WHERE THE TOOL WAS OFFERED.
3941
+ *
3942
+ * A call exists only because some process put that tool's definition in front of the model, so that
3943
+ * process is the one that certainly knows the tool. Another process might not: a deployment that
3944
+ * splits its pods by role has one that serves HTTP and replays run bodies without registering the
3945
+ * tool classes, and its registry answers `undefined`. Stamping here, INSIDE the llm checkpoint, is
3946
+ * what puts the kind in the journal — so the branch a call takes is a fact about the turn rather
3947
+ * than about whichever process happened to replay it (see {@link claimToolCall}).
3948
+ *
3949
+ * Only unstamped calls are touched: a kind already on a call was settled upstream, and a process
3950
+ * further down never second-guesses it.
3951
+ */
3952
+ declare function stampToolKinds<T extends {
3953
+ toolCalls: ToolCallRequest[];
3954
+ }>(result: T, deps: ToolKindDeps): T;
3912
3955
  /**
3913
3956
  * Append the built-in `ask` definition to a turn's tool list. Exported because the dispatched llm
3914
3957
  * step re-derives the tool list on a worker and has to reach the same list the loop would have.
@@ -3917,6 +3960,12 @@ declare function withAskTool({ tools, ask, }: {
3917
3960
  tools: ToolDefinition[];
3918
3961
  ask: boolean | undefined;
3919
3962
  }): ToolDefinition[];
3963
+ /**
3964
+ * Stored as the reason when someone declines without giving one. It is a placeholder, not something
3965
+ * a person said, so every reader has to filter it out — which is why it is exported rather than
3966
+ * spelled again wherever a refusal is read back.
3967
+ */
3968
+ declare const DEFAULT_REFUSAL_REASON = "rejected by user";
3920
3969
  /** What a turn answered with: the assistant text, plus the validated `outputSchema` value if any. */
3921
3970
  interface AgentLoopResult<TOutput = unknown> {
3922
3971
  text: string;
@@ -4162,4 +4211,4 @@ type AgentDiagnosticKey = `agent:${AgentDiagnosticEvent}`;
4162
4211
  */
4163
4212
  declare function agentDiagnosticKey(event: AgentDiagnosticEvent): AgentDiagnosticKey;
4164
4213
 
4165
- 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, ASK_TOOL_DESCRIPTION, ASK_TOOL_NAME, type Actor, type ActorDirectory, type ActorResolver, type ActorSpendRow, type AgentApprovalPort, type AgentCatalogEntry, type AgentDefinition, type AgentDelegated, type AgentDelegation, type AgentDiagnosticEvent, type AgentDiagnosticKey, type AgentFollowUpsSpan, type AgentGovernanceQueries, type AgentHistoryWindow, type 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, type AgentRunInput, type AgentRunStarted, type AgentRunner, type AgentSkillsResolved, type AgentSpanEvent, type AgentStore, AgentStreamError, type AgentStreamEvent, type AgentStructuredOutputSpan, type AgentToolCallEvent, type AgentToolExecutionSpan, type AgentToolRetry, type AiToolCtx, type AppendMessageInput, type ApprovalWhere, type AskToolInput, type AttachmentRef, type AttachmentStagingStore, type BufferedModelTurnResult, type BuildMemoryBlockInput, type CostUsage, type CreateThreadInput, type CurrentModelPrice, DEFAULT_HISTORY_SUMMARY_INSTRUCTION, DEFAULT_INCREMENTAL_LOOKBACK_CHARS, DEFAULT_INTAKE_PREAMBLE, DEFAULT_MAX_FACT_CHARS, DEFAULT_MAX_MEMORIES, DEFAULT_MAX_SKILLS, DEFAULT_STRUCTURED_OUTPUT_INSTRUCTION, DEFAULT_TOOL_TRANSIENT_RETRY_ATTEMPTS, DEFAULT_TOOL_TRANSIENT_RETRY_BACKOFF_MS, type Decision, DefaultRolesPolicy, type DetachedDelegationOutcome, type DetachedDelegationReceipt, type DetachedDelivery, type DetailThreadRef, type ElicitationOption, type ElicitationOutcome, type ElicitationQuestion, type ElicitationReply, type ElicitationRequest, type ElicitationResult, type EmbeddingProvider, type ForgetMemoryInput, type FrameBuffer, GLOBAL_SCOPE, type GovernancePage, type GovernancePageQuery, type GovernanceRange, type GovernanceRunDetail, type GovernanceThreadDetail, type GovernanceThreadDetailQuery, type GovernanceUsageInput, type HistoryPolicy, type HistoryPolicyContext, type HistorySelection, type HistorySummary, type HumanReply, type IncrementalGate, type IncrementalGating, type InputProcessor, type InvokeWithTransientRetryOptions, type ListMemoriesInput, type ListSkillsInput, type ListStagedAttachmentsInput, type LlmStepEnvelope, type LoadSkillInput, MAX_ASK_QUESTIONS, type MemoryAuthor, type MemoryConfig, type MemoryDigest, type MemoryDigestEntry, type MemoryFact, type MemoryForgetRequest, type MemoryOrigin, type MemoryProvider, type MemoryRecord, type MemoryVerdict, type MemoryWriteOutcome, type MemoryWriteRequest, type MessageAttachment, type MessageRole, type MessageUsage, type ModelAnswer, type ModelMessage, type ModelPrice, type ModelPriceInput, type ModelProvider, type ModelSpendRow, type ModelTurnArgs, type ModelTurnResult, type OfferMemoriesInput, type OutputGateMode, type OutputGateResult, type OutputProcessor, OutputRejectedError, type OutputVerdict, type OverriddenMemory, type PageContext, type Passage, type PendingApprovalRow, type ProcessedPrompt, type ProcessorContext, ProcessorFailedError, type PromptBuilder, type PromptContext, type PromptContributor, QuotaExceededError, type QuotaState, type QuotaStore, type QuotaView, REMEMBER_TOOL_DESCRIPTION, REMEMBER_TOOL_NAME, 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, type StoredMessage, type StreamError, type StructuredOutcome, StructuredOutputError, THREAD_DETAIL_CONTENT_CHARS, type ThreadActivityRow, type ThreadDetail, type ThreadMessageRow, type ThreadMeta, type ThreadSpendRow, type ThreadSummary, type ThreadTurnPage, type ThreadTurnQuery, type ThreadTurnReader, type ThreadUsageRollup, type ThreadWhere, type TokenStreamSink, type ToolCallActivityRow, type ToolCallRequest, type ToolCallStatus, type ToolCallWhere, type ToolDefinition, ToolDisabledError, ToolForbiddenError, type ToolHandler, ToolInputInvalidError, type ToolKind, ToolNotFoundError, ToolRegistry, type ToolResult, type ToolSpec, type ToolStatRow, type ToolStepCtx, type ToolStepEnvelope, type ToolTransientRetryNumbers, type ToolTransientRetryOptions, type ToolTransientRetrySetting, type UpdateThreadInput, type UpdateToolCallInput, type UsagePurpose, type UsageTrendPoint, type WindowHistoryOptions, type WithMemoryToolInput, type WriteMemoryInput, actorScope, agentDiagnosticKey, agentFailureCode, askInputSchema, askToolDefinition, bucketByActor, bucketByModel, bucketByThread, bucketUsageTrend, buildMemoryBlock, buildSkillsBlock, canActorUseTool, compositeSkillProvider, createFrameBuffer, createIncrementalGate, dayBoundsUtc, decodeStreamEvent, defaultScopeResolver, detachedDelivered, detachedStarted, detachedUnsettled, encodeStreamEvent, estimateCost, estimateMessageTokens, extractJson, filterToolsByAllowList, filterToolsByCanUse, filterToolsByEnabled, filterToolsByRole, gateFollowUps, gateTail, invokeWithTransientRetry, isControlFlowSignal, isReplayIntegrityError, isToolEnabled, isTransientToolError, loadSkill, memoryForgetVerdict, memoryWriteVerdict, normalizeDelegation, normalizeElicitationReply, offerMemories, offerSkills, publishAgentDelegated, publishAgentMemoryResolved, publishAgentMemoryWritten, publishAgentMessage, publishAgentQuotaExceeded, publishAgentRetrieved, publishAgentRunFailed, publishAgentRunFinished, publishAgentRunStarted, publishAgentSkillsResolved, publishAgentToolCall, publishAgentToolRetry, releaseGatedFrames, rememberInputSchema, rememberToolDefinition, renderElicitationAnswers, repairInstruction, resolveElicitation, resolveGateLookback, resolveMemoryDigest, resolveOutputGateMode, resolveSkillCatalog, resolveToolTransientRetryNumbers, rollupThreadUsage, runAgentLoop, runInputProcessors, runOutputProcessors, seedModelPrices, settleAll, settleElicitation, settleUnsettledDelegation, skillInputSchema, skillToolDefinition, skillWriteVerdict, staticSkillProvider, summarizeWithModel, tenantScope, traceLlmTurn, traceToolExecution, truncateDetailContent, validateStructured, windowHistory, withAskTool, withMemoryTool, withSkillTool, withToolTimeout, writeMemory };
4214
+ 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, ASK_TOOL_DESCRIPTION, ASK_TOOL_NAME, type Actor, type ActorDirectory, type ActorResolver, type ActorSpendRow, type AgentApprovalPort, type AgentCatalogEntry, type AgentDefinition, type AgentDelegated, type AgentDelegation, type AgentDiagnosticEvent, type AgentDiagnosticKey, type AgentFollowUpsSpan, type AgentGovernanceQueries, type AgentHistoryWindow, type 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, type AgentRunInput, type AgentRunStarted, type AgentRunner, type AgentSkillsResolved, type AgentSpanEvent, type AgentStore, AgentStreamError, type AgentStreamEvent, type AgentStructuredOutputSpan, type AgentToolCallEvent, type AgentToolExecutionSpan, type AgentToolRetry, type AiToolCtx, type AppendMessageInput, type ApprovalWhere, type AskToolInput, type AttachmentRef, type AttachmentStagingStore, type BufferedModelTurnResult, type BuildMemoryBlockInput, type CostUsage, type CreateThreadInput, type CurrentModelPrice, DEFAULT_HISTORY_SUMMARY_INSTRUCTION, DEFAULT_INCREMENTAL_LOOKBACK_CHARS, DEFAULT_INTAKE_PREAMBLE, DEFAULT_MAX_FACT_CHARS, DEFAULT_MAX_MEMORIES, DEFAULT_MAX_SKILLS, DEFAULT_REFUSAL_REASON, DEFAULT_STRUCTURED_OUTPUT_INSTRUCTION, DEFAULT_TOOL_TRANSIENT_RETRY_ATTEMPTS, DEFAULT_TOOL_TRANSIENT_RETRY_BACKOFF_MS, type Decision, DefaultRolesPolicy, type DetachedDelegationOutcome, type DetachedDelegationReceipt, type DetachedDelivery, type DetailThreadRef, type ElicitationOption, type ElicitationOutcome, type ElicitationQuestion, type ElicitationReply, type ElicitationRequest, type ElicitationResult, type EmbeddingProvider, type ForgetMemoryInput, type FrameBuffer, GLOBAL_SCOPE, type GovernancePage, type GovernancePageQuery, type GovernanceRange, type GovernanceRunDetail, type GovernanceThreadDetail, type GovernanceThreadDetailQuery, type GovernanceUsageInput, type HistoryPolicy, type HistoryPolicyContext, type HistorySelection, type HistorySummary, type HumanReply, type IncrementalGate, type IncrementalGating, type InputProcessor, type InvokeWithTransientRetryOptions, type ListMemoriesInput, type ListSkillsInput, type ListStagedAttachmentsInput, type LlmStepEnvelope, type LoadSkillInput, MAX_ASK_QUESTIONS, type MemoryAuthor, type MemoryConfig, type MemoryDigest, type MemoryDigestEntry, type MemoryFact, type MemoryForgetRequest, type MemoryOrigin, type MemoryProvider, type MemoryRecord, type MemoryVerdict, type MemoryWriteOutcome, type MemoryWriteRequest, type MessageAttachment, type MessageRole, type MessageUsage, type ModelAnswer, type ModelMessage, type ModelPrice, type ModelPriceInput, type ModelProvider, type ModelSpendRow, type ModelTurnArgs, type ModelTurnResult, type OfferMemoriesInput, type OutputGateMode, type OutputGateResult, type OutputProcessor, OutputRejectedError, type OutputVerdict, type OverriddenMemory, type PageContext, type Passage, type PendingApprovalRow, type ProcessedPrompt, type ProcessorContext, ProcessorFailedError, type PromptBuilder, type PromptContext, type PromptContributor, QuotaExceededError, type QuotaState, type QuotaStore, type QuotaView, REMEMBER_TOOL_DESCRIPTION, REMEMBER_TOOL_NAME, 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, type StoredMessage, type StreamError, type StructuredOutcome, StructuredOutputError, THREAD_DETAIL_CONTENT_CHARS, type ThreadActivityRow, type ThreadDetail, type ThreadMessageRow, type ThreadMeta, type ThreadSpendRow, type ThreadSummary, type ThreadTurnPage, type ThreadTurnQuery, type ThreadTurnReader, type ThreadUsageRollup, type ThreadWhere, type TokenStreamSink, type ToolCallActivityRow, type ToolCallRequest, type ToolCallStatus, type ToolCallWhere, type ToolDefinition, ToolDisabledError, ToolForbiddenError, type ToolHandler, ToolInputInvalidError, type ToolKind, type ToolKindDeps, ToolNotFoundError, ToolRegistry, type ToolResult, type ToolSpec, type ToolStatRow, type ToolStepCtx, type ToolStepEnvelope, type ToolTransientRetryNumbers, type ToolTransientRetryOptions, type ToolTransientRetrySetting, type UpdateThreadInput, type UpdateToolCallInput, type UsagePurpose, type UsageTrendPoint, type WindowHistoryOptions, type WithMemoryToolInput, type WriteMemoryInput, actorScope, agentDiagnosticKey, agentFailureCode, askInputSchema, askToolDefinition, bucketByActor, bucketByModel, bucketByThread, bucketUsageTrend, buildMemoryBlock, buildSkillsBlock, canActorUseTool, compositeSkillProvider, createFrameBuffer, createIncrementalGate, dayBoundsUtc, decodeStreamEvent, defaultScopeResolver, detachedDelivered, detachedStarted, detachedUnsettled, encodeStreamEvent, estimateCost, estimateMessageTokens, extractJson, filterToolsByAllowList, filterToolsByCanUse, filterToolsByEnabled, filterToolsByRole, gateFollowUps, gateTail, invokeWithTransientRetry, isControlFlowSignal, isReplayIntegrityError, isToolEnabled, isTransientToolError, loadSkill, memoryForgetVerdict, memoryWriteVerdict, normalizeDelegation, normalizeElicitationReply, offerMemories, offerSkills, publishAgentDelegated, publishAgentMemoryResolved, publishAgentMemoryWritten, publishAgentMessage, publishAgentQuotaExceeded, publishAgentRetrieved, publishAgentRunFailed, publishAgentRunFinished, publishAgentRunStarted, publishAgentSkillsResolved, publishAgentToolCall, publishAgentToolRetry, releaseGatedFrames, rememberInputSchema, rememberToolDefinition, renderElicitationAnswers, repairInstruction, resolveElicitation, resolveGateLookback, resolveMemoryDigest, resolveOutputGateMode, resolveSkillCatalog, resolveToolTransientRetryNumbers, rollupThreadUsage, runAgentLoop, runInputProcessors, runOutputProcessors, seedModelPrices, settleAll, settleElicitation, settleUnsettledDelegation, skillInputSchema, skillToolDefinition, skillWriteVerdict, stampToolKinds, staticSkillProvider, summarizeWithModel, tenantScope, traceLlmTurn, traceToolExecution, truncateDetailContent, validateStructured, windowHistory, withAskTool, withMemoryTool, withSkillTool, withToolTimeout, writeMemory };
package/dist/index.d.ts CHANGED
@@ -440,15 +440,24 @@ interface ToolCallRequest {
440
440
  name: string;
441
441
  input: unknown;
442
442
  /**
443
- * The tool's declared kind (`ToolSpec.kind`), stamped by the loop from the tool registry so
444
- * thread-read consumers know a call's kind without hardcoding a tool-name allowlist. Undefined
445
- * only for a call the loop couldn't resolve against the registry (defensively treated as `read`
446
- * wherever a definite value is required).
443
+ * The tool's declared kind (`ToolSpec.kind`), stamped where the tool was OFFERED — inside the llm
444
+ * checkpoint, by the process that built the definition list the model chose from. It travels with
445
+ * the call from there, so thread-read consumers know a call's kind without hardcoding a tool-name
446
+ * allowlist, and the approval branch does not depend on which process replays the turn.
447
+ * Undefined only for a call that predates the stamp, or one no registry could resolve
448
+ * (defensively treated as `read` wherever a definite value is required).
447
449
  */
448
450
  kind?: ToolKind;
449
451
  }
450
452
  /** Result of running a tool. */
451
453
  interface ToolResult {
454
+ /**
455
+ * A person declined this action, so the tool never ran. Set INSTEAD of a failure, and read by
456
+ * every consumer that has to tell the two apart — the stream frame, the replayed transcript. The
457
+ * `error` field still carries what the MODEL is told, because that is the channel a model reads a
458
+ * tool's outcome on; this flag is what everything else reads.
459
+ */
460
+ denied?: true;
452
461
  id: string;
453
462
  name: string;
454
463
  output: unknown;
@@ -1102,6 +1111,18 @@ type AgentStreamEvent = {
1102
1111
  id: string;
1103
1112
  error: string;
1104
1113
  }
1114
+ /**
1115
+ * A person was asked to approve an action tool and declined it. Its own frame, NOT
1116
+ * `tool-output-error`: a refusal is a decision with a known outcome — nothing ran — while a
1117
+ * failure is an outcome nobody chose and whose effects are unknown. Rendering them the same way
1118
+ * tells an operator their own "no" was a malfunction. Maps onto the SDK's `output-denied` tool
1119
+ * part state, which a client reads without knowing any tool's name.
1120
+ */
1121
+ | {
1122
+ kind: 'tool-output-denied';
1123
+ id: string;
1124
+ reason?: string;
1125
+ }
1105
1126
  /**
1106
1127
  * The run has put a question set to the user and is parked until someone answers it (or skips).
1107
1128
  * Written by the LOOP for both elicitation surfaces — the configured intake and the model's `ask`
@@ -3909,6 +3930,28 @@ declare function traceToolExecution<T>(runId: string, call: {
3909
3930
  toolName: string;
3910
3931
  toolType: 'read' | 'action';
3911
3932
  }, run: () => Promise<T>): Promise<T>;
3933
+ /**
3934
+ * What resolving a call's kind needs: the registry, plus the three config flags whose reserved names
3935
+ * have no `ToolSpec` to look up. Narrow on purpose — {@link stampToolKinds} is called from a
3936
+ * dispatched step handler, which holds the host's own deps rather than a loop's.
3937
+ */
3938
+ type ToolKindDeps = Pick<AgentLoopDeps, 'registry' | 'ask' | 'skills' | 'memory'>;
3939
+ /**
3940
+ * Stamp each of a model turn's calls with the kind declared WHERE THE TOOL WAS OFFERED.
3941
+ *
3942
+ * A call exists only because some process put that tool's definition in front of the model, so that
3943
+ * process is the one that certainly knows the tool. Another process might not: a deployment that
3944
+ * splits its pods by role has one that serves HTTP and replays run bodies without registering the
3945
+ * tool classes, and its registry answers `undefined`. Stamping here, INSIDE the llm checkpoint, is
3946
+ * what puts the kind in the journal — so the branch a call takes is a fact about the turn rather
3947
+ * than about whichever process happened to replay it (see {@link claimToolCall}).
3948
+ *
3949
+ * Only unstamped calls are touched: a kind already on a call was settled upstream, and a process
3950
+ * further down never second-guesses it.
3951
+ */
3952
+ declare function stampToolKinds<T extends {
3953
+ toolCalls: ToolCallRequest[];
3954
+ }>(result: T, deps: ToolKindDeps): T;
3912
3955
  /**
3913
3956
  * Append the built-in `ask` definition to a turn's tool list. Exported because the dispatched llm
3914
3957
  * step re-derives the tool list on a worker and has to reach the same list the loop would have.
@@ -3917,6 +3960,12 @@ declare function withAskTool({ tools, ask, }: {
3917
3960
  tools: ToolDefinition[];
3918
3961
  ask: boolean | undefined;
3919
3962
  }): ToolDefinition[];
3963
+ /**
3964
+ * Stored as the reason when someone declines without giving one. It is a placeholder, not something
3965
+ * a person said, so every reader has to filter it out — which is why it is exported rather than
3966
+ * spelled again wherever a refusal is read back.
3967
+ */
3968
+ declare const DEFAULT_REFUSAL_REASON = "rejected by user";
3920
3969
  /** What a turn answered with: the assistant text, plus the validated `outputSchema` value if any. */
3921
3970
  interface AgentLoopResult<TOutput = unknown> {
3922
3971
  text: string;
@@ -4162,4 +4211,4 @@ type AgentDiagnosticKey = `agent:${AgentDiagnosticEvent}`;
4162
4211
  */
4163
4212
  declare function agentDiagnosticKey(event: AgentDiagnosticEvent): AgentDiagnosticKey;
4164
4213
 
4165
- 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, ASK_TOOL_DESCRIPTION, ASK_TOOL_NAME, type Actor, type ActorDirectory, type ActorResolver, type ActorSpendRow, type AgentApprovalPort, type AgentCatalogEntry, type AgentDefinition, type AgentDelegated, type AgentDelegation, type AgentDiagnosticEvent, type AgentDiagnosticKey, type AgentFollowUpsSpan, type AgentGovernanceQueries, type AgentHistoryWindow, type 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, type AgentRunInput, type AgentRunStarted, type AgentRunner, type AgentSkillsResolved, type AgentSpanEvent, type AgentStore, AgentStreamError, type AgentStreamEvent, type AgentStructuredOutputSpan, type AgentToolCallEvent, type AgentToolExecutionSpan, type AgentToolRetry, type AiToolCtx, type AppendMessageInput, type ApprovalWhere, type AskToolInput, type AttachmentRef, type AttachmentStagingStore, type BufferedModelTurnResult, type BuildMemoryBlockInput, type CostUsage, type CreateThreadInput, type CurrentModelPrice, DEFAULT_HISTORY_SUMMARY_INSTRUCTION, DEFAULT_INCREMENTAL_LOOKBACK_CHARS, DEFAULT_INTAKE_PREAMBLE, DEFAULT_MAX_FACT_CHARS, DEFAULT_MAX_MEMORIES, DEFAULT_MAX_SKILLS, DEFAULT_STRUCTURED_OUTPUT_INSTRUCTION, DEFAULT_TOOL_TRANSIENT_RETRY_ATTEMPTS, DEFAULT_TOOL_TRANSIENT_RETRY_BACKOFF_MS, type Decision, DefaultRolesPolicy, type DetachedDelegationOutcome, type DetachedDelegationReceipt, type DetachedDelivery, type DetailThreadRef, type ElicitationOption, type ElicitationOutcome, type ElicitationQuestion, type ElicitationReply, type ElicitationRequest, type ElicitationResult, type EmbeddingProvider, type ForgetMemoryInput, type FrameBuffer, GLOBAL_SCOPE, type GovernancePage, type GovernancePageQuery, type GovernanceRange, type GovernanceRunDetail, type GovernanceThreadDetail, type GovernanceThreadDetailQuery, type GovernanceUsageInput, type HistoryPolicy, type HistoryPolicyContext, type HistorySelection, type HistorySummary, type HumanReply, type IncrementalGate, type IncrementalGating, type InputProcessor, type InvokeWithTransientRetryOptions, type ListMemoriesInput, type ListSkillsInput, type ListStagedAttachmentsInput, type LlmStepEnvelope, type LoadSkillInput, MAX_ASK_QUESTIONS, type MemoryAuthor, type MemoryConfig, type MemoryDigest, type MemoryDigestEntry, type MemoryFact, type MemoryForgetRequest, type MemoryOrigin, type MemoryProvider, type MemoryRecord, type MemoryVerdict, type MemoryWriteOutcome, type MemoryWriteRequest, type MessageAttachment, type MessageRole, type MessageUsage, type ModelAnswer, type ModelMessage, type ModelPrice, type ModelPriceInput, type ModelProvider, type ModelSpendRow, type ModelTurnArgs, type ModelTurnResult, type OfferMemoriesInput, type OutputGateMode, type OutputGateResult, type OutputProcessor, OutputRejectedError, type OutputVerdict, type OverriddenMemory, type PageContext, type Passage, type PendingApprovalRow, type ProcessedPrompt, type ProcessorContext, ProcessorFailedError, type PromptBuilder, type PromptContext, type PromptContributor, QuotaExceededError, type QuotaState, type QuotaStore, type QuotaView, REMEMBER_TOOL_DESCRIPTION, REMEMBER_TOOL_NAME, 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, type StoredMessage, type StreamError, type StructuredOutcome, StructuredOutputError, THREAD_DETAIL_CONTENT_CHARS, type ThreadActivityRow, type ThreadDetail, type ThreadMessageRow, type ThreadMeta, type ThreadSpendRow, type ThreadSummary, type ThreadTurnPage, type ThreadTurnQuery, type ThreadTurnReader, type ThreadUsageRollup, type ThreadWhere, type TokenStreamSink, type ToolCallActivityRow, type ToolCallRequest, type ToolCallStatus, type ToolCallWhere, type ToolDefinition, ToolDisabledError, ToolForbiddenError, type ToolHandler, ToolInputInvalidError, type ToolKind, ToolNotFoundError, ToolRegistry, type ToolResult, type ToolSpec, type ToolStatRow, type ToolStepCtx, type ToolStepEnvelope, type ToolTransientRetryNumbers, type ToolTransientRetryOptions, type ToolTransientRetrySetting, type UpdateThreadInput, type UpdateToolCallInput, type UsagePurpose, type UsageTrendPoint, type WindowHistoryOptions, type WithMemoryToolInput, type WriteMemoryInput, actorScope, agentDiagnosticKey, agentFailureCode, askInputSchema, askToolDefinition, bucketByActor, bucketByModel, bucketByThread, bucketUsageTrend, buildMemoryBlock, buildSkillsBlock, canActorUseTool, compositeSkillProvider, createFrameBuffer, createIncrementalGate, dayBoundsUtc, decodeStreamEvent, defaultScopeResolver, detachedDelivered, detachedStarted, detachedUnsettled, encodeStreamEvent, estimateCost, estimateMessageTokens, extractJson, filterToolsByAllowList, filterToolsByCanUse, filterToolsByEnabled, filterToolsByRole, gateFollowUps, gateTail, invokeWithTransientRetry, isControlFlowSignal, isReplayIntegrityError, isToolEnabled, isTransientToolError, loadSkill, memoryForgetVerdict, memoryWriteVerdict, normalizeDelegation, normalizeElicitationReply, offerMemories, offerSkills, publishAgentDelegated, publishAgentMemoryResolved, publishAgentMemoryWritten, publishAgentMessage, publishAgentQuotaExceeded, publishAgentRetrieved, publishAgentRunFailed, publishAgentRunFinished, publishAgentRunStarted, publishAgentSkillsResolved, publishAgentToolCall, publishAgentToolRetry, releaseGatedFrames, rememberInputSchema, rememberToolDefinition, renderElicitationAnswers, repairInstruction, resolveElicitation, resolveGateLookback, resolveMemoryDigest, resolveOutputGateMode, resolveSkillCatalog, resolveToolTransientRetryNumbers, rollupThreadUsage, runAgentLoop, runInputProcessors, runOutputProcessors, seedModelPrices, settleAll, settleElicitation, settleUnsettledDelegation, skillInputSchema, skillToolDefinition, skillWriteVerdict, staticSkillProvider, summarizeWithModel, tenantScope, traceLlmTurn, traceToolExecution, truncateDetailContent, validateStructured, windowHistory, withAskTool, withMemoryTool, withSkillTool, withToolTimeout, writeMemory };
4214
+ 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, ASK_TOOL_DESCRIPTION, ASK_TOOL_NAME, type Actor, type ActorDirectory, type ActorResolver, type ActorSpendRow, type AgentApprovalPort, type AgentCatalogEntry, type AgentDefinition, type AgentDelegated, type AgentDelegation, type AgentDiagnosticEvent, type AgentDiagnosticKey, type AgentFollowUpsSpan, type AgentGovernanceQueries, type AgentHistoryWindow, type 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, type AgentRunInput, type AgentRunStarted, type AgentRunner, type AgentSkillsResolved, type AgentSpanEvent, type AgentStore, AgentStreamError, type AgentStreamEvent, type AgentStructuredOutputSpan, type AgentToolCallEvent, type AgentToolExecutionSpan, type AgentToolRetry, type AiToolCtx, type AppendMessageInput, type ApprovalWhere, type AskToolInput, type AttachmentRef, type AttachmentStagingStore, type BufferedModelTurnResult, type BuildMemoryBlockInput, type CostUsage, type CreateThreadInput, type CurrentModelPrice, DEFAULT_HISTORY_SUMMARY_INSTRUCTION, DEFAULT_INCREMENTAL_LOOKBACK_CHARS, DEFAULT_INTAKE_PREAMBLE, DEFAULT_MAX_FACT_CHARS, DEFAULT_MAX_MEMORIES, DEFAULT_MAX_SKILLS, DEFAULT_REFUSAL_REASON, DEFAULT_STRUCTURED_OUTPUT_INSTRUCTION, DEFAULT_TOOL_TRANSIENT_RETRY_ATTEMPTS, DEFAULT_TOOL_TRANSIENT_RETRY_BACKOFF_MS, type Decision, DefaultRolesPolicy, type DetachedDelegationOutcome, type DetachedDelegationReceipt, type DetachedDelivery, type DetailThreadRef, type ElicitationOption, type ElicitationOutcome, type ElicitationQuestion, type ElicitationReply, type ElicitationRequest, type ElicitationResult, type EmbeddingProvider, type ForgetMemoryInput, type FrameBuffer, GLOBAL_SCOPE, type GovernancePage, type GovernancePageQuery, type GovernanceRange, type GovernanceRunDetail, type GovernanceThreadDetail, type GovernanceThreadDetailQuery, type GovernanceUsageInput, type HistoryPolicy, type HistoryPolicyContext, type HistorySelection, type HistorySummary, type HumanReply, type IncrementalGate, type IncrementalGating, type InputProcessor, type InvokeWithTransientRetryOptions, type ListMemoriesInput, type ListSkillsInput, type ListStagedAttachmentsInput, type LlmStepEnvelope, type LoadSkillInput, MAX_ASK_QUESTIONS, type MemoryAuthor, type MemoryConfig, type MemoryDigest, type MemoryDigestEntry, type MemoryFact, type MemoryForgetRequest, type MemoryOrigin, type MemoryProvider, type MemoryRecord, type MemoryVerdict, type MemoryWriteOutcome, type MemoryWriteRequest, type MessageAttachment, type MessageRole, type MessageUsage, type ModelAnswer, type ModelMessage, type ModelPrice, type ModelPriceInput, type ModelProvider, type ModelSpendRow, type ModelTurnArgs, type ModelTurnResult, type OfferMemoriesInput, type OutputGateMode, type OutputGateResult, type OutputProcessor, OutputRejectedError, type OutputVerdict, type OverriddenMemory, type PageContext, type Passage, type PendingApprovalRow, type ProcessedPrompt, type ProcessorContext, ProcessorFailedError, type PromptBuilder, type PromptContext, type PromptContributor, QuotaExceededError, type QuotaState, type QuotaStore, type QuotaView, REMEMBER_TOOL_DESCRIPTION, REMEMBER_TOOL_NAME, 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, type StoredMessage, type StreamError, type StructuredOutcome, StructuredOutputError, THREAD_DETAIL_CONTENT_CHARS, type ThreadActivityRow, type ThreadDetail, type ThreadMessageRow, type ThreadMeta, type ThreadSpendRow, type ThreadSummary, type ThreadTurnPage, type ThreadTurnQuery, type ThreadTurnReader, type ThreadUsageRollup, type ThreadWhere, type TokenStreamSink, type ToolCallActivityRow, type ToolCallRequest, type ToolCallStatus, type ToolCallWhere, type ToolDefinition, ToolDisabledError, ToolForbiddenError, type ToolHandler, ToolInputInvalidError, type ToolKind, type ToolKindDeps, ToolNotFoundError, ToolRegistry, type ToolResult, type ToolSpec, type ToolStatRow, type ToolStepCtx, type ToolStepEnvelope, type ToolTransientRetryNumbers, type ToolTransientRetryOptions, type ToolTransientRetrySetting, type UpdateThreadInput, type UpdateToolCallInput, type UsagePurpose, type UsageTrendPoint, type WindowHistoryOptions, type WithMemoryToolInput, type WriteMemoryInput, actorScope, agentDiagnosticKey, agentFailureCode, askInputSchema, askToolDefinition, bucketByActor, bucketByModel, bucketByThread, bucketUsageTrend, buildMemoryBlock, buildSkillsBlock, canActorUseTool, compositeSkillProvider, createFrameBuffer, createIncrementalGate, dayBoundsUtc, decodeStreamEvent, defaultScopeResolver, detachedDelivered, detachedStarted, detachedUnsettled, encodeStreamEvent, estimateCost, estimateMessageTokens, extractJson, filterToolsByAllowList, filterToolsByCanUse, filterToolsByEnabled, filterToolsByRole, gateFollowUps, gateTail, invokeWithTransientRetry, isControlFlowSignal, isReplayIntegrityError, isToolEnabled, isTransientToolError, loadSkill, memoryForgetVerdict, memoryWriteVerdict, normalizeDelegation, normalizeElicitationReply, offerMemories, offerSkills, publishAgentDelegated, publishAgentMemoryResolved, publishAgentMemoryWritten, publishAgentMessage, publishAgentQuotaExceeded, publishAgentRetrieved, publishAgentRunFailed, publishAgentRunFinished, publishAgentRunStarted, publishAgentSkillsResolved, publishAgentToolCall, publishAgentToolRetry, releaseGatedFrames, rememberInputSchema, rememberToolDefinition, renderElicitationAnswers, repairInstruction, resolveElicitation, resolveGateLookback, resolveMemoryDigest, resolveOutputGateMode, resolveSkillCatalog, resolveToolTransientRetryNumbers, rollupThreadUsage, runAgentLoop, runInputProcessors, runOutputProcessors, seedModelPrices, settleAll, settleElicitation, settleUnsettledDelegation, skillInputSchema, skillToolDefinition, skillWriteVerdict, stampToolKinds, staticSkillProvider, summarizeWithModel, tenantScope, traceLlmTurn, traceToolExecution, truncateDetailContent, validateStructured, windowHistory, withAskTool, withMemoryTool, withSkillTool, withToolTimeout, writeMemory };
package/dist/index.js CHANGED
@@ -2446,6 +2446,16 @@ async function structureAnswer(schema, deps, input, hooks, messages, step) {
2446
2446
  throw new StructuredOutputError(issues, text, maxAttempts);
2447
2447
  }
2448
2448
  __name(structureAnswer, "structureAnswer");
2449
+ function stampToolKinds(result, deps) {
2450
+ return {
2451
+ ...result,
2452
+ toolCalls: result.toolCalls.map((call) => call.kind === void 0 ? {
2453
+ ...call,
2454
+ kind: declaredKind(deps, call.name)
2455
+ } : call)
2456
+ };
2457
+ }
2458
+ __name(stampToolKinds, "stampToolKinds");
2449
2459
  function declaredKind(deps, name) {
2450
2460
  if (deps.ask === true && name === ASK_TOOL_NAME) {
2451
2461
  return "ask";
@@ -2646,7 +2656,7 @@ async function claimToolCall(turn, call) {
2646
2656
  const { deps, input, hooks, messageId } = turn;
2647
2657
  const persisted = await hooks.step(`persist:toolcall:${call.id}`, async () => {
2648
2658
  const spec = deps.registry.spec(call.name);
2649
- const kind = declaredKind(deps, call.name);
2659
+ const kind = call.kind ?? declaredKind(deps, call.name);
2650
2660
  const awaitsHuman = kind === "action" || kind === "ask";
2651
2661
  await deps.store.recordToolCall({
2652
2662
  toolCallId: call.id,
@@ -3066,15 +3076,58 @@ async function runClaimedToolCall(turn, claimed) {
3066
3076
  name: call.name,
3067
3077
  output: {
3068
3078
  rejected: true,
3069
- reason: decision.reason ?? "rejected by user"
3079
+ reason: decision.reason ?? DEFAULT_REFUSAL_REASON
3070
3080
  },
3071
- error: "rejected"
3081
+ denied: true,
3082
+ // What the MODEL is told. It used to be the bare word `rejected`, which names no actor and
3083
+ // reads exactly like a tool that blew up — so the answer that followed would speculate about
3084
+ // causes ("the key may not exist", "there may be permission restrictions") and offer to try
3085
+ // again. A person's decision is not a fault to diagnose, so this says who decided, that
3086
+ // nothing ran, and what not to do next.
3087
+ error: refusalNarrative(decision.reason)
3072
3088
  };
3073
3089
  }
3074
3090
  }
3075
3091
  return recordToolOutcome(turn, claimed, await invokeClaimedTool(turn, claimed), deciderRef);
3076
3092
  }
3077
3093
  __name(runClaimedToolCall, "runClaimedToolCall");
3094
+ function outputFrame(result) {
3095
+ if (result.denied === true) {
3096
+ const reason = refusalReason(result);
3097
+ return {
3098
+ kind: "tool-output-denied",
3099
+ id: result.id,
3100
+ ...reason !== void 0 ? {
3101
+ reason
3102
+ } : {}
3103
+ };
3104
+ }
3105
+ return result.error !== void 0 ? {
3106
+ kind: "tool-output-error",
3107
+ id: result.id,
3108
+ error: result.error
3109
+ } : {
3110
+ kind: "tool-output",
3111
+ id: result.id,
3112
+ output: result.output
3113
+ };
3114
+ }
3115
+ __name(outputFrame, "outputFrame");
3116
+ function refusalReason(result) {
3117
+ const { output } = result;
3118
+ if (output !== null && typeof output === "object" && "reason" in output) {
3119
+ const reason = output.reason;
3120
+ return typeof reason === "string" && reason !== DEFAULT_REFUSAL_REASON ? reason : void 0;
3121
+ }
3122
+ return void 0;
3123
+ }
3124
+ __name(refusalReason, "refusalReason");
3125
+ var DEFAULT_REFUSAL_REASON = "rejected by user";
3126
+ function refusalNarrative(reason) {
3127
+ const base = "The person was asked to approve this action and declined it. Nothing ran and nothing changed. This is their decision, not an error, a missing record or a permissions problem \u2014 do not explain it as one, do not guess at causes, and do not run this action again or reach for another way to do the same thing. Acknowledge the decision and ask what they would like instead.";
3128
+ return reason === void 0 ? base : `${base} They said: ${reason}`;
3129
+ }
3130
+ __name(refusalNarrative, "refusalNarrative");
3078
3131
  async function invokeClaimedToolsTogether(turn, parallel, claimed) {
3079
3132
  const settled = await parallel(claimed.map((entry) => () => invokeClaimedTool(turn, entry)));
3080
3133
  for (const outcome of settled) {
@@ -3310,12 +3363,12 @@ ${block}`;
3310
3363
  writer
3311
3364
  }) : void 0;
3312
3365
  const buffer = gateMode === "whole" ? createFrameBuffer() : void 0;
3313
- const result = await traceLlmTurn(hooks.runId, i, () => deps.model.runTurn({
3366
+ const result = stampToolKinds(await traceLlmTurn(hooks.runId, i, () => deps.model.runTurn({
3314
3367
  system: prompt.system,
3315
3368
  messages: prompt.messages,
3316
3369
  tools,
3317
3370
  sink: incremental?.writer ?? buffer?.writer ?? writer
3318
- }));
3371
+ })), deps);
3319
3372
  if (incremental !== void 0) {
3320
3373
  await incremental.settled();
3321
3374
  const refusal = incremental.rejection();
@@ -3374,7 +3427,7 @@ ${block}`;
3374
3427
  const costUsd = resolveCostUsd(turn.usage, turn.costUsd, priceByModel.get(resolvedModelId));
3375
3428
  const toolCallsWithKind = turn.toolCalls.map((call) => ({
3376
3429
  ...call,
3377
- kind: declaredKind(deps, call.name)
3430
+ kind: call.kind ?? declaredKind(deps, call.name)
3378
3431
  }));
3379
3432
  await hooks.step(`persist:usage:${i}`, () => deps.store.recordUsage({
3380
3433
  threadId: input.threadId,
@@ -3606,15 +3659,7 @@ ${block}`;
3606
3659
  await hooks.step(`stream:tool-outputs:${i}`, async () => {
3607
3660
  await deps.store.setMessageToolResults(assistant.id, settledResults);
3608
3661
  for (const result of results) {
3609
- await writer.write(encodeStreamEvent(result.error !== void 0 ? {
3610
- kind: "tool-output-error",
3611
- id: result.id,
3612
- error: result.error
3613
- } : {
3614
- kind: "tool-output",
3615
- id: result.id,
3616
- output: result.output
3617
- }));
3662
+ await writer.write(encodeStreamEvent(outputFrame(result)));
3618
3663
  }
3619
3664
  });
3620
3665
  await hooks.step(`stream:step-finish:${i}`, async () => {
@@ -3712,6 +3757,7 @@ export {
3712
3757
  DEFAULT_MAX_FACT_CHARS,
3713
3758
  DEFAULT_MAX_MEMORIES,
3714
3759
  DEFAULT_MAX_SKILLS,
3760
+ DEFAULT_REFUSAL_REASON,
3715
3761
  DEFAULT_STRUCTURED_OUTPUT_INSTRUCTION,
3716
3762
  DEFAULT_TOOL_TRANSIENT_RETRY_ATTEMPTS,
3717
3763
  DEFAULT_TOOL_TRANSIENT_RETRY_BACKOFF_MS,
@@ -3810,6 +3856,7 @@ export {
3810
3856
  skillInputSchema,
3811
3857
  skillToolDefinition,
3812
3858
  skillWriteVerdict,
3859
+ stampToolKinds,
3813
3860
  staticSkillProvider,
3814
3861
  summarizeWithModel,
3815
3862
  tenantScope,