@dudousxd/nestjs-agent-react 0.28.0 → 0.29.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,13 +1,49 @@
1
1
  import * as ai from 'ai';
2
2
  import { ChatTransport, UIMessage, UIMessageChunk, DataUIPart, UIDataTypes } from 'ai';
3
- import { A as AgentBackend, U as UploadAttachmentOptions, H as HttpErrorListener, a as AttachmentUploadStrategy } from './client-CKwSMitS.cjs';
4
- export { b as AgentBackendUnsupportedError, c as AgentClient, d as AgentClientOptions, e as AgentConnection, f as AgentHttpError, g as AgentRequestError, C as CancelResult, h as ChatStreamRequest, i as ChatStreamResponse, M as MessageFeedbackInput, Q as QueuedMessageUpdate, j as QueuedSendResult, R as ResumeStreamRequest, T as ThreadPatch, r as requireBackendMethod } from './client-CKwSMitS.cjs';
3
+ import { A as AgentRequestError, a as AgentBackend, U as UploadAttachmentOptions, H as HttpErrorListener, b as AttachmentUploadStrategy } from './client-DhHEJi7c.cjs';
4
+ export { c as AgentBackendUnsupportedError, d as AgentClient, e as AgentClientOptions, f as AgentConnection, g as AgentHttpError, C as CancelResult, h as ChatStreamRequest, i as ChatStreamResponse, M as MessageFeedbackInput, Q as QueuedMessageUpdate, j as QueuedSendResult, R as ResumeStreamRequest, T as ThreadPatch, r as requireBackendMethod } from './client-DhHEJi7c.cjs';
5
5
  import { MessageAttachment, AgentClientConfig, AgentCatalogEntry, ModelCatalogEntry, ModelCatalogView, ModelCatalogLock, QuotaReport, QuotaWindow, QuotaBlock, QuotaWarning, MessageFeedback, MessageFeedbackValue, ThreadSummary, StoredMessage, QueuePause, ToolCatalogEntry } from '@dudousxd/nestjs-agent-core';
6
6
  export { ALL_AGENTS, ChatQueueState, ElicitationInput, ElicitationInputType, QueuePause, QueuePauseReason, QueuedMessageView, validateElicitationAnswer as validateAnswer, validateElicitationValue as validateAnswerValue } from '@dudousxd/nestjs-agent-core';
7
7
  import * as React from 'react';
8
8
  import React__default, { ReactNode, Context } from 'react';
9
- import { o as GenuiProviderValue, T as TranscriptUiBlock, A as ApproveOptions, t as TranscriptBlock, U as UsageSummary, v as TimestampInfo, C as ChatStatus, w as TranscriptFile, M as MessageUsageInfo, x as ToolCatalog, y as AnyToolUIPart } from './generative-ui-jT9TYfCi.cjs';
10
- export { z as ApprovalBlockOptions, B as BuildBlocksOptions, D as CoercibleQuestion, E as DescribeToolCallOptions, F as ElicitationBlockOptions, H as GroupToolActivityOptions, I as RawAnswer, J as ResolvedReading, K as ResolvedResultView, L as RetrievedPassage, S as SettleAction, N as ToolActivityGroup, O as ToolCallDescription, P as ToolCallState, Q as ToolCallStatus, V as TranscriptApproval, W as TranscriptApprovalStatus, X as TranscriptElicitationBlock, Y as TranscriptElicitationOutcome, Z as TranscriptFilesBlock, _ as TranscriptQuestion, $ as TranscriptQuestionOption, a0 as TranscriptReasoningBlock, a1 as TranscriptSettleState, a2 as TranscriptSource, a3 as TranscriptSourcesBlock, a4 as TranscriptTextBlock, a5 as TranscriptToolBlock, a6 as TranscriptToolCall, a7 as buildTranscriptBlocks, a8 as coerceAnswer, a9 as correctedCallIds, aa as describeTimestamp, ab as describeToolCall, ac as describeUsage, ad as extractMessageText, ae as fillTemplate, af as formatRelativeTime, ag as groupToolActivity, ah as inferResultView, ai as isActionCall, aj as phraseFor, ak as readPath, al as resolveResultView, am as toolCallState, an as toolCatalogFrom } from './generative-ui-jT9TYfCi.cjs';
9
+ import { o as GenuiProviderValue, T as TranscriptUiBlock, A as ApproveOptions, t as TranscriptBlock, U as UsageSummary, v as TimestampInfo, C as ChatStatus, w as TranscriptFile, M as MessageUsageInfo, x as ToolCatalog, y as AnyToolUIPart } from './generative-ui-VTZ1EADD.cjs';
10
+ export { z as ApprovalBlockOptions, B as BuildBlocksOptions, D as CoercibleQuestion, E as DescribeToolCallOptions, F as ElicitationBlockOptions, H as GroupToolActivityOptions, I as RawAnswer, J as ResolvedReading, K as ResolvedResultView, L as RetrievedPassage, S as SettleAction, N as ToolActivityGroup, O as ToolCallDescription, P as ToolCallState, Q as ToolCallStatus, V as TranscriptApproval, W as TranscriptApprovalStatus, X as TranscriptElicitationBlock, Y as TranscriptElicitationOutcome, Z as TranscriptFilesBlock, _ as TranscriptQuestion, $ as TranscriptQuestionOption, a0 as TranscriptReasoningBlock, a1 as TranscriptSettleState, a2 as TranscriptSource, a3 as TranscriptSourcesBlock, a4 as TranscriptTextBlock, a5 as TranscriptToolBlock, a6 as TranscriptToolCall, a7 as buildTranscriptBlocks, a8 as coerceAnswer, a9 as correctedCallIds, aa as describeTimestamp, ab as describeToolCall, ac as describeUsage, ad as extractMessageText, ae as fillTemplate, af as formatRelativeTime, ag as groupToolActivity, ah as inferResultView, ai as isActionCall, aj as phraseFor, ak as readPath, al as resolveResultView, am as toolCallState, an as toolCatalogFrom } from './generative-ui-VTZ1EADD.cjs';
11
+
12
+ /**
13
+ * The `code`s this library's own loop closes a failed run's stream with (`event: error`). A client
14
+ * branches on the code and words the failure itself — the frame's `message` is a sentence in
15
+ * English, and for a crash deliberately a generic one.
16
+ *
17
+ * - `quota_exceeded` — the actor's budget is spent; `message` says which.
18
+ * - `output_rejected` — an output processor refused the answer.
19
+ * - `structured_output_invalid` — the answer never satisfied the agent's output schema.
20
+ * - `replay_diverged` — the durable runtime refused to resume the run (its journal and the
21
+ * deployed code disagree). The turn is over; sending again starts a new one.
22
+ * - `model_no_output` — a model call ended without producing anything.
23
+ * - `run_failed` — anything else.
24
+ *
25
+ * A host's own runner may send codes of its own, which is why {@link AgentRunFailure.code} is a
26
+ * plain string.
27
+ */
28
+ declare const AGENT_RUN_ERROR_CODES: readonly ["quota_exceeded", "output_rejected", "structured_output_invalid", "replay_diverged", "model_no_output", "run_failed"];
29
+ type AgentRunErrorCode = (typeof AGENT_RUN_ERROR_CODES)[number];
30
+ /** How a run's stream said it failed: the `event: error` frame, read. */
31
+ interface AgentRunFailure {
32
+ /** The frame's machine-readable `code`; `undefined` when the server sent none. */
33
+ code: AgentRunErrorCode | (string & {}) | undefined;
34
+ /** The frame's `message` — the server's words, safe to show but not translated. */
35
+ message: string;
36
+ /** The run that failed, when the stream had named it. */
37
+ runId?: string;
38
+ }
39
+ /** The `code` a decision is refused with when the run it was for has ended (`409`). */
40
+ declare const RUN_NOT_ACTIVE_CODE = "run_not_active";
41
+ /**
42
+ * Whether `error` is the server refusing an approve / reject / answer / skip because the turn that
43
+ * asked is over (`409 { code: 'run_not_active' }`): nothing is waiting for the decision, and nothing
44
+ * will run. The card it was made on is stale — say so, and let the person send the message again.
45
+ */
46
+ declare function isRunNotActiveError(error: unknown): error is AgentRequestError;
11
47
 
12
48
  /** Identity surfaced by the backend's `meta` SSE frame / response headers. */
13
49
  interface AgentStreamMeta {
@@ -100,6 +136,12 @@ interface AgentChatTransportOptions {
100
136
  * what the run wrote — `useAgentChat` re-reads the thread.
101
137
  */
102
138
  onResumeGone?: (runId: string) => void;
139
+ /**
140
+ * The run's stream ended with the backend's `event: error` frame — called with its `code` and
141
+ * `message` right before the stream is closed with an error chunk. The chunk can only carry the
142
+ * text; this is where the `code` reaches a caller, so it can word the failure itself.
143
+ */
144
+ onRunError?: (failure: AgentRunFailure) => void;
103
145
  /** Injectable for tests / non-browser runtimes. Defaults to global fetch. */
104
146
  fetch?: typeof fetch;
105
147
  }
@@ -1814,6 +1856,13 @@ declare function useAgentChat<B extends AgentBackend = AgentBackend>(options?: U
1814
1856
  isLoadingHistory: boolean;
1815
1857
  /** Reading the thread's history failed. */
1816
1858
  historyError: Error | null;
1859
+ /**
1860
+ * How the last run's stream said it failed — the `event: error` frame's `code` and `message` —
1861
+ * or `null`. Cleared when the next attempt starts and when the chat moves to another thread.
1862
+ * `chat.error` still carries the message; this is where the `code` is, so the app can word each
1863
+ * failure itself (`replay_diverged`, `model_no_output`, `run_failed`, `quota_exceeded`, …).
1864
+ */
1865
+ runError: AgentRunFailure | null;
1817
1866
  /**
1818
1867
  * The thread this chat is on right now: the `threadId` option, else the one the backend created
1819
1868
  * on the first send. A getter, because the created id is learned mid-stream.
@@ -1867,4 +1916,4 @@ declare class QuotaBlockedError extends Error {
1867
1916
  constructor(block: QuotaBlock);
1868
1917
  }
1869
1918
 
1870
- export { AgentBackend, AgentChatTransport, type AgentChatTransportOptions, type AgentConfigState, type AgentMessageMetadata, AgentProvider, type AgentProviderProps, type AgentStreamMeta, type AgentsState, type AggregatedTurnUsage, type AmbientRenderUi, AmbientRenderUiContext, type AnswerInput, AnyToolUIPart, type ApprovalCountdown, type ApproveInput, ApproveOptions, type AttachmentRejection, AttachmentUploadStrategy, type AttachmentsState, type AutocompleteInputProps, type AutocompleteItem, type AutocompleteListboxProps, type AutocompleteOptionProps, type AutocompleteSource, type BackgroundRun, type ChatBackground, ChatInput, type ChatInputProps, type ChatQueue, ChatStatus, type ChatTranscript, type ClipboardLikeEvent, type CompletionEdit, type ComposerAutocomplete, DEFAULT_SPEECH_LANG, type DragLikeEvent, type EditSubmitInput, HttpErrorListener, type MessageActionInput, type MessageFeedbackState, type MessageFile, type MessageFileKind, MessageItem, type MessageItemClassNames, type MessageItemProps, MessageItemView, type MessageItemViewProps, MessageList, type MessageListClassNames, type MessageListProps, MessageUsageInfo, type ModelOption, type ModelsState, type QueuedChatMessage, QuotaBlockedError, type QuotaState, type ReconnectOptions, type RejectInput, type RenderFilesFn, type RenderReasoningFn, type RenderTextFn, type RenderToolGroupFn, type RenderToolPartFn, type RenderUiFn, SPEECH_LANGUAGES, type SendWhileRunning, type SkillSuggestionData, type SkillsSourceOptions, type SkipInput, type SpeechLanguage, type SpeechRecognitionHook, type StagedAttachment, type StagedAttachmentStatus, type StickToBottom, type StickToBottomOptions, type StoredTurnMetadata, type StreamConnectionState, type ThreadsEvent, type ThreadsState, TimestampInfo, ToolCatalog, type ToolCatalogState, type TranscriptActionState, TranscriptBlock, type TranscriptCopyState, type TranscriptEditState, TranscriptFile, type TranscriptItem, type TranscriptItemOptions, type TranscriptQueuedFile, type TranscriptQueuedItem, type TranscriptStopState, TranscriptUiBlock, type TranscriptWindow, type TriggerMatch, type TriggerPosition, UploadAttachmentOptions, UsageSummary, type UseAgentChatOptions, type UseAgentConfigOptions, type UseAgentsOptions, type UseApprovalCountdownOptions, type UseAttachmentsOptions, type UseChatTranscriptOptions, type UseComposerAutocompleteOptions, type UseElapsedOptions, type UseMessageFeedbackOptions, type UseModelsOptions, type UseQuotaOptions, type UseSpeechRecognitionOptions, type UseThreadsOptions, type UseToolCatalogOptions, type UseTranscriptItemOptions, type WhileRunning, acceptsFile, applyCompletion, approvalCountdown, attachmentFile, backgroundRunsFromThread, createSkillsSource, dragHasFiles, fileKind, filesFromClipboard, filterAutocompleteItems, findActiveTrigger, formatElapsed, loadStoredSpeechLang, messageFiles, notifyThreads, onThreadsEvent, persistSpeechLang, readReasoningMs, storedMessageToUiMessage, storedThreadToUiMessages, useAgentBackend, useAgentChat, useAgentConfig, useAgents, useAmbientRenderUi, useApprovalCountdown, useAttachments, useChatTranscript, useComposerAutocomplete, useElapsed, useMessageFeedback, useModels, useQuota, useSpeechRecognition, useStickToBottom, useThreads, useToolCatalog, useTranscriptItem };
1919
+ export { AGENT_RUN_ERROR_CODES, AgentBackend, AgentChatTransport, type AgentChatTransportOptions, type AgentConfigState, type AgentMessageMetadata, AgentProvider, type AgentProviderProps, AgentRequestError, type AgentRunErrorCode, type AgentRunFailure, type AgentStreamMeta, type AgentsState, type AggregatedTurnUsage, type AmbientRenderUi, AmbientRenderUiContext, type AnswerInput, AnyToolUIPart, type ApprovalCountdown, type ApproveInput, ApproveOptions, type AttachmentRejection, AttachmentUploadStrategy, type AttachmentsState, type AutocompleteInputProps, type AutocompleteItem, type AutocompleteListboxProps, type AutocompleteOptionProps, type AutocompleteSource, type BackgroundRun, type ChatBackground, ChatInput, type ChatInputProps, type ChatQueue, ChatStatus, type ChatTranscript, type ClipboardLikeEvent, type CompletionEdit, type ComposerAutocomplete, DEFAULT_SPEECH_LANG, type DragLikeEvent, type EditSubmitInput, HttpErrorListener, type MessageActionInput, type MessageFeedbackState, type MessageFile, type MessageFileKind, MessageItem, type MessageItemClassNames, type MessageItemProps, MessageItemView, type MessageItemViewProps, MessageList, type MessageListClassNames, type MessageListProps, MessageUsageInfo, type ModelOption, type ModelsState, type QueuedChatMessage, QuotaBlockedError, type QuotaState, RUN_NOT_ACTIVE_CODE, type ReconnectOptions, type RejectInput, type RenderFilesFn, type RenderReasoningFn, type RenderTextFn, type RenderToolGroupFn, type RenderToolPartFn, type RenderUiFn, SPEECH_LANGUAGES, type SendWhileRunning, type SkillSuggestionData, type SkillsSourceOptions, type SkipInput, type SpeechLanguage, type SpeechRecognitionHook, type StagedAttachment, type StagedAttachmentStatus, type StickToBottom, type StickToBottomOptions, type StoredTurnMetadata, type StreamConnectionState, type ThreadsEvent, type ThreadsState, TimestampInfo, ToolCatalog, type ToolCatalogState, type TranscriptActionState, TranscriptBlock, type TranscriptCopyState, type TranscriptEditState, TranscriptFile, type TranscriptItem, type TranscriptItemOptions, type TranscriptQueuedFile, type TranscriptQueuedItem, type TranscriptStopState, TranscriptUiBlock, type TranscriptWindow, type TriggerMatch, type TriggerPosition, UploadAttachmentOptions, UsageSummary, type UseAgentChatOptions, type UseAgentConfigOptions, type UseAgentsOptions, type UseApprovalCountdownOptions, type UseAttachmentsOptions, type UseChatTranscriptOptions, type UseComposerAutocompleteOptions, type UseElapsedOptions, type UseMessageFeedbackOptions, type UseModelsOptions, type UseQuotaOptions, type UseSpeechRecognitionOptions, type UseThreadsOptions, type UseToolCatalogOptions, type UseTranscriptItemOptions, type WhileRunning, acceptsFile, applyCompletion, approvalCountdown, attachmentFile, backgroundRunsFromThread, createSkillsSource, dragHasFiles, fileKind, filesFromClipboard, filterAutocompleteItems, findActiveTrigger, formatElapsed, isRunNotActiveError, loadStoredSpeechLang, messageFiles, notifyThreads, onThreadsEvent, persistSpeechLang, readReasoningMs, storedMessageToUiMessage, storedThreadToUiMessages, useAgentBackend, useAgentChat, useAgentConfig, useAgents, useAmbientRenderUi, useApprovalCountdown, useAttachments, useChatTranscript, useComposerAutocomplete, useElapsed, useMessageFeedback, useModels, useQuota, useSpeechRecognition, useStickToBottom, useThreads, useToolCatalog, useTranscriptItem };
package/dist/index.d.ts CHANGED
@@ -1,13 +1,49 @@
1
1
  import * as ai from 'ai';
2
2
  import { ChatTransport, UIMessage, UIMessageChunk, DataUIPart, UIDataTypes } from 'ai';
3
- import { A as AgentBackend, U as UploadAttachmentOptions, H as HttpErrorListener, a as AttachmentUploadStrategy } from './client-CKwSMitS.js';
4
- export { b as AgentBackendUnsupportedError, c as AgentClient, d as AgentClientOptions, e as AgentConnection, f as AgentHttpError, g as AgentRequestError, C as CancelResult, h as ChatStreamRequest, i as ChatStreamResponse, M as MessageFeedbackInput, Q as QueuedMessageUpdate, j as QueuedSendResult, R as ResumeStreamRequest, T as ThreadPatch, r as requireBackendMethod } from './client-CKwSMitS.js';
3
+ import { A as AgentRequestError, a as AgentBackend, U as UploadAttachmentOptions, H as HttpErrorListener, b as AttachmentUploadStrategy } from './client-DhHEJi7c.js';
4
+ export { c as AgentBackendUnsupportedError, d as AgentClient, e as AgentClientOptions, f as AgentConnection, g as AgentHttpError, C as CancelResult, h as ChatStreamRequest, i as ChatStreamResponse, M as MessageFeedbackInput, Q as QueuedMessageUpdate, j as QueuedSendResult, R as ResumeStreamRequest, T as ThreadPatch, r as requireBackendMethod } from './client-DhHEJi7c.js';
5
5
  import { MessageAttachment, AgentClientConfig, AgentCatalogEntry, ModelCatalogEntry, ModelCatalogView, ModelCatalogLock, QuotaReport, QuotaWindow, QuotaBlock, QuotaWarning, MessageFeedback, MessageFeedbackValue, ThreadSummary, StoredMessage, QueuePause, ToolCatalogEntry } from '@dudousxd/nestjs-agent-core';
6
6
  export { ALL_AGENTS, ChatQueueState, ElicitationInput, ElicitationInputType, QueuePause, QueuePauseReason, QueuedMessageView, validateElicitationAnswer as validateAnswer, validateElicitationValue as validateAnswerValue } from '@dudousxd/nestjs-agent-core';
7
7
  import * as React from 'react';
8
8
  import React__default, { ReactNode, Context } from 'react';
9
- import { o as GenuiProviderValue, T as TranscriptUiBlock, A as ApproveOptions, t as TranscriptBlock, U as UsageSummary, v as TimestampInfo, C as ChatStatus, w as TranscriptFile, M as MessageUsageInfo, x as ToolCatalog, y as AnyToolUIPart } from './generative-ui-jT9TYfCi.js';
10
- export { z as ApprovalBlockOptions, B as BuildBlocksOptions, D as CoercibleQuestion, E as DescribeToolCallOptions, F as ElicitationBlockOptions, H as GroupToolActivityOptions, I as RawAnswer, J as ResolvedReading, K as ResolvedResultView, L as RetrievedPassage, S as SettleAction, N as ToolActivityGroup, O as ToolCallDescription, P as ToolCallState, Q as ToolCallStatus, V as TranscriptApproval, W as TranscriptApprovalStatus, X as TranscriptElicitationBlock, Y as TranscriptElicitationOutcome, Z as TranscriptFilesBlock, _ as TranscriptQuestion, $ as TranscriptQuestionOption, a0 as TranscriptReasoningBlock, a1 as TranscriptSettleState, a2 as TranscriptSource, a3 as TranscriptSourcesBlock, a4 as TranscriptTextBlock, a5 as TranscriptToolBlock, a6 as TranscriptToolCall, a7 as buildTranscriptBlocks, a8 as coerceAnswer, a9 as correctedCallIds, aa as describeTimestamp, ab as describeToolCall, ac as describeUsage, ad as extractMessageText, ae as fillTemplate, af as formatRelativeTime, ag as groupToolActivity, ah as inferResultView, ai as isActionCall, aj as phraseFor, ak as readPath, al as resolveResultView, am as toolCallState, an as toolCatalogFrom } from './generative-ui-jT9TYfCi.js';
9
+ import { o as GenuiProviderValue, T as TranscriptUiBlock, A as ApproveOptions, t as TranscriptBlock, U as UsageSummary, v as TimestampInfo, C as ChatStatus, w as TranscriptFile, M as MessageUsageInfo, x as ToolCatalog, y as AnyToolUIPart } from './generative-ui-VTZ1EADD.js';
10
+ export { z as ApprovalBlockOptions, B as BuildBlocksOptions, D as CoercibleQuestion, E as DescribeToolCallOptions, F as ElicitationBlockOptions, H as GroupToolActivityOptions, I as RawAnswer, J as ResolvedReading, K as ResolvedResultView, L as RetrievedPassage, S as SettleAction, N as ToolActivityGroup, O as ToolCallDescription, P as ToolCallState, Q as ToolCallStatus, V as TranscriptApproval, W as TranscriptApprovalStatus, X as TranscriptElicitationBlock, Y as TranscriptElicitationOutcome, Z as TranscriptFilesBlock, _ as TranscriptQuestion, $ as TranscriptQuestionOption, a0 as TranscriptReasoningBlock, a1 as TranscriptSettleState, a2 as TranscriptSource, a3 as TranscriptSourcesBlock, a4 as TranscriptTextBlock, a5 as TranscriptToolBlock, a6 as TranscriptToolCall, a7 as buildTranscriptBlocks, a8 as coerceAnswer, a9 as correctedCallIds, aa as describeTimestamp, ab as describeToolCall, ac as describeUsage, ad as extractMessageText, ae as fillTemplate, af as formatRelativeTime, ag as groupToolActivity, ah as inferResultView, ai as isActionCall, aj as phraseFor, ak as readPath, al as resolveResultView, am as toolCallState, an as toolCatalogFrom } from './generative-ui-VTZ1EADD.js';
11
+
12
+ /**
13
+ * The `code`s this library's own loop closes a failed run's stream with (`event: error`). A client
14
+ * branches on the code and words the failure itself — the frame's `message` is a sentence in
15
+ * English, and for a crash deliberately a generic one.
16
+ *
17
+ * - `quota_exceeded` — the actor's budget is spent; `message` says which.
18
+ * - `output_rejected` — an output processor refused the answer.
19
+ * - `structured_output_invalid` — the answer never satisfied the agent's output schema.
20
+ * - `replay_diverged` — the durable runtime refused to resume the run (its journal and the
21
+ * deployed code disagree). The turn is over; sending again starts a new one.
22
+ * - `model_no_output` — a model call ended without producing anything.
23
+ * - `run_failed` — anything else.
24
+ *
25
+ * A host's own runner may send codes of its own, which is why {@link AgentRunFailure.code} is a
26
+ * plain string.
27
+ */
28
+ declare const AGENT_RUN_ERROR_CODES: readonly ["quota_exceeded", "output_rejected", "structured_output_invalid", "replay_diverged", "model_no_output", "run_failed"];
29
+ type AgentRunErrorCode = (typeof AGENT_RUN_ERROR_CODES)[number];
30
+ /** How a run's stream said it failed: the `event: error` frame, read. */
31
+ interface AgentRunFailure {
32
+ /** The frame's machine-readable `code`; `undefined` when the server sent none. */
33
+ code: AgentRunErrorCode | (string & {}) | undefined;
34
+ /** The frame's `message` — the server's words, safe to show but not translated. */
35
+ message: string;
36
+ /** The run that failed, when the stream had named it. */
37
+ runId?: string;
38
+ }
39
+ /** The `code` a decision is refused with when the run it was for has ended (`409`). */
40
+ declare const RUN_NOT_ACTIVE_CODE = "run_not_active";
41
+ /**
42
+ * Whether `error` is the server refusing an approve / reject / answer / skip because the turn that
43
+ * asked is over (`409 { code: 'run_not_active' }`): nothing is waiting for the decision, and nothing
44
+ * will run. The card it was made on is stale — say so, and let the person send the message again.
45
+ */
46
+ declare function isRunNotActiveError(error: unknown): error is AgentRequestError;
11
47
 
12
48
  /** Identity surfaced by the backend's `meta` SSE frame / response headers. */
13
49
  interface AgentStreamMeta {
@@ -100,6 +136,12 @@ interface AgentChatTransportOptions {
100
136
  * what the run wrote — `useAgentChat` re-reads the thread.
101
137
  */
102
138
  onResumeGone?: (runId: string) => void;
139
+ /**
140
+ * The run's stream ended with the backend's `event: error` frame — called with its `code` and
141
+ * `message` right before the stream is closed with an error chunk. The chunk can only carry the
142
+ * text; this is where the `code` reaches a caller, so it can word the failure itself.
143
+ */
144
+ onRunError?: (failure: AgentRunFailure) => void;
103
145
  /** Injectable for tests / non-browser runtimes. Defaults to global fetch. */
104
146
  fetch?: typeof fetch;
105
147
  }
@@ -1814,6 +1856,13 @@ declare function useAgentChat<B extends AgentBackend = AgentBackend>(options?: U
1814
1856
  isLoadingHistory: boolean;
1815
1857
  /** Reading the thread's history failed. */
1816
1858
  historyError: Error | null;
1859
+ /**
1860
+ * How the last run's stream said it failed — the `event: error` frame's `code` and `message` —
1861
+ * or `null`. Cleared when the next attempt starts and when the chat moves to another thread.
1862
+ * `chat.error` still carries the message; this is where the `code` is, so the app can word each
1863
+ * failure itself (`replay_diverged`, `model_no_output`, `run_failed`, `quota_exceeded`, …).
1864
+ */
1865
+ runError: AgentRunFailure | null;
1817
1866
  /**
1818
1867
  * The thread this chat is on right now: the `threadId` option, else the one the backend created
1819
1868
  * on the first send. A getter, because the created id is learned mid-stream.
@@ -1867,4 +1916,4 @@ declare class QuotaBlockedError extends Error {
1867
1916
  constructor(block: QuotaBlock);
1868
1917
  }
1869
1918
 
1870
- export { AgentBackend, AgentChatTransport, type AgentChatTransportOptions, type AgentConfigState, type AgentMessageMetadata, AgentProvider, type AgentProviderProps, type AgentStreamMeta, type AgentsState, type AggregatedTurnUsage, type AmbientRenderUi, AmbientRenderUiContext, type AnswerInput, AnyToolUIPart, type ApprovalCountdown, type ApproveInput, ApproveOptions, type AttachmentRejection, AttachmentUploadStrategy, type AttachmentsState, type AutocompleteInputProps, type AutocompleteItem, type AutocompleteListboxProps, type AutocompleteOptionProps, type AutocompleteSource, type BackgroundRun, type ChatBackground, ChatInput, type ChatInputProps, type ChatQueue, ChatStatus, type ChatTranscript, type ClipboardLikeEvent, type CompletionEdit, type ComposerAutocomplete, DEFAULT_SPEECH_LANG, type DragLikeEvent, type EditSubmitInput, HttpErrorListener, type MessageActionInput, type MessageFeedbackState, type MessageFile, type MessageFileKind, MessageItem, type MessageItemClassNames, type MessageItemProps, MessageItemView, type MessageItemViewProps, MessageList, type MessageListClassNames, type MessageListProps, MessageUsageInfo, type ModelOption, type ModelsState, type QueuedChatMessage, QuotaBlockedError, type QuotaState, type ReconnectOptions, type RejectInput, type RenderFilesFn, type RenderReasoningFn, type RenderTextFn, type RenderToolGroupFn, type RenderToolPartFn, type RenderUiFn, SPEECH_LANGUAGES, type SendWhileRunning, type SkillSuggestionData, type SkillsSourceOptions, type SkipInput, type SpeechLanguage, type SpeechRecognitionHook, type StagedAttachment, type StagedAttachmentStatus, type StickToBottom, type StickToBottomOptions, type StoredTurnMetadata, type StreamConnectionState, type ThreadsEvent, type ThreadsState, TimestampInfo, ToolCatalog, type ToolCatalogState, type TranscriptActionState, TranscriptBlock, type TranscriptCopyState, type TranscriptEditState, TranscriptFile, type TranscriptItem, type TranscriptItemOptions, type TranscriptQueuedFile, type TranscriptQueuedItem, type TranscriptStopState, TranscriptUiBlock, type TranscriptWindow, type TriggerMatch, type TriggerPosition, UploadAttachmentOptions, UsageSummary, type UseAgentChatOptions, type UseAgentConfigOptions, type UseAgentsOptions, type UseApprovalCountdownOptions, type UseAttachmentsOptions, type UseChatTranscriptOptions, type UseComposerAutocompleteOptions, type UseElapsedOptions, type UseMessageFeedbackOptions, type UseModelsOptions, type UseQuotaOptions, type UseSpeechRecognitionOptions, type UseThreadsOptions, type UseToolCatalogOptions, type UseTranscriptItemOptions, type WhileRunning, acceptsFile, applyCompletion, approvalCountdown, attachmentFile, backgroundRunsFromThread, createSkillsSource, dragHasFiles, fileKind, filesFromClipboard, filterAutocompleteItems, findActiveTrigger, formatElapsed, loadStoredSpeechLang, messageFiles, notifyThreads, onThreadsEvent, persistSpeechLang, readReasoningMs, storedMessageToUiMessage, storedThreadToUiMessages, useAgentBackend, useAgentChat, useAgentConfig, useAgents, useAmbientRenderUi, useApprovalCountdown, useAttachments, useChatTranscript, useComposerAutocomplete, useElapsed, useMessageFeedback, useModels, useQuota, useSpeechRecognition, useStickToBottom, useThreads, useToolCatalog, useTranscriptItem };
1919
+ export { AGENT_RUN_ERROR_CODES, AgentBackend, AgentChatTransport, type AgentChatTransportOptions, type AgentConfigState, type AgentMessageMetadata, AgentProvider, type AgentProviderProps, AgentRequestError, type AgentRunErrorCode, type AgentRunFailure, type AgentStreamMeta, type AgentsState, type AggregatedTurnUsage, type AmbientRenderUi, AmbientRenderUiContext, type AnswerInput, AnyToolUIPart, type ApprovalCountdown, type ApproveInput, ApproveOptions, type AttachmentRejection, AttachmentUploadStrategy, type AttachmentsState, type AutocompleteInputProps, type AutocompleteItem, type AutocompleteListboxProps, type AutocompleteOptionProps, type AutocompleteSource, type BackgroundRun, type ChatBackground, ChatInput, type ChatInputProps, type ChatQueue, ChatStatus, type ChatTranscript, type ClipboardLikeEvent, type CompletionEdit, type ComposerAutocomplete, DEFAULT_SPEECH_LANG, type DragLikeEvent, type EditSubmitInput, HttpErrorListener, type MessageActionInput, type MessageFeedbackState, type MessageFile, type MessageFileKind, MessageItem, type MessageItemClassNames, type MessageItemProps, MessageItemView, type MessageItemViewProps, MessageList, type MessageListClassNames, type MessageListProps, MessageUsageInfo, type ModelOption, type ModelsState, type QueuedChatMessage, QuotaBlockedError, type QuotaState, RUN_NOT_ACTIVE_CODE, type ReconnectOptions, type RejectInput, type RenderFilesFn, type RenderReasoningFn, type RenderTextFn, type RenderToolGroupFn, type RenderToolPartFn, type RenderUiFn, SPEECH_LANGUAGES, type SendWhileRunning, type SkillSuggestionData, type SkillsSourceOptions, type SkipInput, type SpeechLanguage, type SpeechRecognitionHook, type StagedAttachment, type StagedAttachmentStatus, type StickToBottom, type StickToBottomOptions, type StoredTurnMetadata, type StreamConnectionState, type ThreadsEvent, type ThreadsState, TimestampInfo, ToolCatalog, type ToolCatalogState, type TranscriptActionState, TranscriptBlock, type TranscriptCopyState, type TranscriptEditState, TranscriptFile, type TranscriptItem, type TranscriptItemOptions, type TranscriptQueuedFile, type TranscriptQueuedItem, type TranscriptStopState, TranscriptUiBlock, type TranscriptWindow, type TriggerMatch, type TriggerPosition, UploadAttachmentOptions, UsageSummary, type UseAgentChatOptions, type UseAgentConfigOptions, type UseAgentsOptions, type UseApprovalCountdownOptions, type UseAttachmentsOptions, type UseChatTranscriptOptions, type UseComposerAutocompleteOptions, type UseElapsedOptions, type UseMessageFeedbackOptions, type UseModelsOptions, type UseQuotaOptions, type UseSpeechRecognitionOptions, type UseThreadsOptions, type UseToolCatalogOptions, type UseTranscriptItemOptions, type WhileRunning, acceptsFile, applyCompletion, approvalCountdown, attachmentFile, backgroundRunsFromThread, createSkillsSource, dragHasFiles, fileKind, filesFromClipboard, filterAutocompleteItems, findActiveTrigger, formatElapsed, isRunNotActiveError, loadStoredSpeechLang, messageFiles, notifyThreads, onThreadsEvent, persistSpeechLang, readReasoningMs, storedMessageToUiMessage, storedThreadToUiMessages, useAgentBackend, useAgentChat, useAgentConfig, useAgents, useAmbientRenderUi, useApprovalCountdown, useAttachments, useChatTranscript, useComposerAutocomplete, useElapsed, useMessageFeedback, useModels, useQuota, useSpeechRecognition, useStickToBottom, useThreads, useToolCatalog, useTranscriptItem };
package/dist/index.js CHANGED
@@ -615,6 +615,15 @@ var AgentChatTransport = class {
615
615
  const backend = this.backend;
616
616
  const policy = this.reconnectPolicy();
617
617
  const notify = (state) => this.options.onConnectionChange?.(state);
618
+ const reportRunError = (failure) => {
619
+ try {
620
+ this.options.onRunError?.({
621
+ ...failure,
622
+ ...streamRunId !== void 0 ? { runId: streamRunId } : {}
623
+ });
624
+ } catch {
625
+ }
626
+ };
618
627
  const aborted = () => cancelled || context.signal?.aborted === true;
619
628
  const canResume = () => policy !== null && lastSeq !== void 0 && streamRunId !== void 0 && !aborted();
620
629
  const resume = async () => {
@@ -939,7 +948,9 @@ var AgentChatTransport = class {
939
948
  return;
940
949
  }
941
950
  if (frame.event === "error") {
942
- fail(parseErrorText(frame.data));
951
+ const failure = parseErrorFrame(frame.data);
952
+ reportRunError(failure);
953
+ fail(failure.message);
943
954
  return;
944
955
  }
945
956
  if (frame.event === "meta") {
@@ -1006,16 +1017,21 @@ function parseMeta(data) {
1006
1017
  }
1007
1018
  return null;
1008
1019
  }
1009
- function parseErrorText(data) {
1010
- if (!data) return "Agent run failed";
1020
+ function parseErrorFrame(data) {
1021
+ const fallback2 = { code: void 0, message: "Agent run failed" };
1022
+ if (!data) return fallback2;
1011
1023
  try {
1012
1024
  const parsed = JSON.parse(data);
1013
- if (parsed !== null && typeof parsed === "object" && "message" in parsed && typeof parsed.message === "string") {
1014
- return parsed.message;
1025
+ if (parsed !== null && typeof parsed === "object") {
1026
+ const record = parsed;
1027
+ return {
1028
+ code: typeof record.code === "string" && record.code !== "" ? record.code : void 0,
1029
+ message: typeof record.message === "string" && record.message !== "" ? record.message : fallback2.message
1030
+ };
1015
1031
  }
1016
1032
  } catch {
1017
1033
  }
1018
- return "Agent run failed";
1034
+ return fallback2;
1019
1035
  }
1020
1036
  function parseEvent(data) {
1021
1037
  try {
@@ -2872,7 +2888,8 @@ function buildToolCall(part, options, approval, catalog) {
2872
2888
  isSubmitting: sending === "reject",
2873
2889
  run: () => options?.reject(toolCallId)
2874
2890
  },
2875
- error: options?.errorOf(toolCallId) ?? null
2891
+ error: options?.errorOf(toolCallId) ?? null,
2892
+ errorCode: options?.errorCodeOf?.(toolCallId) ?? null
2876
2893
  };
2877
2894
  }
2878
2895
  function readElicitationRequest(part) {
@@ -3003,6 +3020,7 @@ function buildElicitationBlock(key, part, request, options) {
3003
3020
  isValid: questions.every((question) => question.error === null),
3004
3021
  outcome,
3005
3022
  error: options.errorOf(toolCallId),
3023
+ errorCode: options.errorCodeOf?.(toolCallId) ?? null,
3006
3024
  answer: {
3007
3025
  available: isPending && options.canAnswer,
3008
3026
  isSubmitting: sending === "answer",
@@ -3471,10 +3489,10 @@ function useTranscriptItems({
3471
3489
  return next;
3472
3490
  });
3473
3491
  setSettleErrors(
3474
- (current) => new Map(current).set(
3475
- toolCallId,
3476
- error instanceof Error ? error.message : "Could not settle this"
3477
- )
3492
+ (current) => new Map(current).set(toolCallId, {
3493
+ message: error instanceof Error ? error.message : "Could not settle this",
3494
+ code: settleErrorCode(error)
3495
+ })
3478
3496
  );
3479
3497
  };
3480
3498
  try {
@@ -3655,7 +3673,8 @@ function useTranscriptItems({
3655
3673
  answer,
3656
3674
  skip,
3657
3675
  submitting: (toolCallId) => settling.get(toolCallId) ?? null,
3658
- errorOf: (toolCallId) => settleErrors.get(toolCallId) ?? null
3676
+ errorOf: (toolCallId) => settleErrors.get(toolCallId)?.message ?? null,
3677
+ errorCodeOf: (toolCallId) => settleErrors.get(toolCallId)?.code ?? null
3659
3678
  }
3660
3679
  } : {},
3661
3680
  ...handlers.onApprove !== void 0 || handlers.onReject !== void 0 ? {
@@ -3665,7 +3684,8 @@ function useTranscriptItems({
3665
3684
  approve,
3666
3685
  reject,
3667
3686
  submitting: (toolCallId) => settling.get(toolCallId) ?? null,
3668
- errorOf: (toolCallId) => settleErrors.get(toolCallId) ?? null
3687
+ errorOf: (toolCallId) => settleErrors.get(toolCallId)?.message ?? null,
3688
+ errorCodeOf: (toolCallId) => settleErrors.get(toolCallId)?.code ?? null
3669
3689
  }
3670
3690
  } : {}
3671
3691
  }),
@@ -3785,6 +3805,10 @@ function contentSignature(messages) {
3785
3805
  }
3786
3806
  return `${messages.length}|${last.id}|${last.parts?.length ?? 0}|${length}`;
3787
3807
  }
3808
+ function settleErrorCode(error) {
3809
+ const code = error?.code;
3810
+ return typeof code === "string" && code !== "" ? code : null;
3811
+ }
3788
3812
 
3789
3813
  // src/components/message-item.tsx
3790
3814
  import { jsx as jsx4, jsxs as jsxs2 } from "react/jsx-runtime";
@@ -4854,6 +4878,7 @@ function useAgentChat(options = {}) {
4854
4878
  const [activeRunId, setActiveRunId] = useState15(null);
4855
4879
  const [historyFor, setHistoryFor] = useState15(void 0);
4856
4880
  const [historyError, setHistoryError] = useState15(null);
4881
+ const [runError, setRunError] = useState15(null);
4857
4882
  const [threadModel, setThreadModel] = useState15(null);
4858
4883
  const [pickedModel, setPickedModel] = useState15(void 0);
4859
4884
  const pickedModelRef = useRef12(pickedModel);
@@ -4929,7 +4954,9 @@ function useAgentChat(options = {}) {
4929
4954
  onMeta,
4930
4955
  onAttemptStart: () => {
4931
4956
  settlingRunIdRef.current = void 0;
4957
+ setRunError(null);
4932
4958
  },
4959
+ onRunError: (failure) => setRunError(failure),
4933
4960
  // A queued turn this chat went to attach to had already finished: read what it wrote.
4934
4961
  onResumeGone: () => {
4935
4962
  void resyncFromThread();
@@ -5048,6 +5075,7 @@ function useAgentChat(options = {}) {
5048
5075
  setPickedModel(void 0);
5049
5076
  setBackgroundRuns([]);
5050
5077
  setHistoryError(null);
5078
+ setRunError(null);
5051
5079
  autoResumeRunIdRef.current = void 0;
5052
5080
  pendingPin.current = void 0;
5053
5081
  applyQueue(EMPTY_QUEUE);
@@ -5651,6 +5679,13 @@ function useAgentChat(options = {}) {
5651
5679
  isLoadingHistory,
5652
5680
  /** Reading the thread's history failed. */
5653
5681
  historyError,
5682
+ /**
5683
+ * How the last run's stream said it failed — the `event: error` frame's `code` and `message` —
5684
+ * or `null`. Cleared when the next attempt starts and when the chat moves to another thread.
5685
+ * `chat.error` still carries the message; this is where the `code` is, so the app can word each
5686
+ * failure itself (`replay_diverged`, `model_no_output`, `run_failed`, `quota_exceeded`, …).
5687
+ */
5688
+ runError,
5654
5689
  /**
5655
5690
  * The thread this chat is on right now: the `threadId` option, else the one the backend created
5656
5691
  * on the first send. A getter, because the created id is learned mid-stream.
@@ -5692,7 +5727,22 @@ var QuotaBlockedError = class extends Error {
5692
5727
  }
5693
5728
  block;
5694
5729
  };
5730
+
5731
+ // src/run-errors.ts
5732
+ var AGENT_RUN_ERROR_CODES = [
5733
+ "quota_exceeded",
5734
+ "output_rejected",
5735
+ "structured_output_invalid",
5736
+ "replay_diverged",
5737
+ "model_no_output",
5738
+ "run_failed"
5739
+ ];
5740
+ var RUN_NOT_ACTIVE_CODE = "run_not_active";
5741
+ function isRunNotActiveError(error) {
5742
+ return error instanceof Error && error.status === 409 && error.code === RUN_NOT_ACTIVE_CODE;
5743
+ }
5695
5744
  export {
5745
+ AGENT_RUN_ERROR_CODES,
5696
5746
  ALL_AGENTS,
5697
5747
  AgentBackendUnsupportedError,
5698
5748
  AgentChatTransport,
@@ -5706,6 +5756,7 @@ export {
5706
5756
  MessageItemView,
5707
5757
  MessageList,
5708
5758
  QuotaBlockedError,
5759
+ RUN_NOT_ACTIVE_CODE,
5709
5760
  SPEECH_LANGUAGES,
5710
5761
  acceptsFile,
5711
5762
  applyCompletion,
@@ -5731,6 +5782,7 @@ export {
5731
5782
  groupToolActivity,
5732
5783
  inferResultView,
5733
5784
  isActionCall,
5785
+ isRunNotActiveError,
5734
5786
  loadStoredSpeechLang,
5735
5787
  messageFiles,
5736
5788
  notifyThreads,