@better-agent/client 0.1.0-canary.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.
@@ -0,0 +1,266 @@
1
+ import { A as getEventErrorMessage, B as SubmitToolApprovalRequest, C as ToolCallPart, D as UIMessagePart, E as UIMessage, F as InferClient, G as AgentContext, H as ToolCallContext, I as OnToolCall, J as AgentsFromApp, K as AgentNameFromApp, L as ReplayInput, M as BetterAgentClient, N as ClientConfig, O as VideoPart, P as ClientEvent, Q as TextInputShorthandForAgent, R as RequestOptions, S as TextPart, T as TranscriptPart, U as ToolCallRequest, V as SubmitToolResultRequest, W as ToolHandlers, X as NormalizeClientApp, Y as ModalitiesForAgent, Z as RunInputForAgent, _ as EmbeddingPart, a as ControllerRunInput, b as PendingToolApproval, c as ResumeOption, d as SendMessageOptions, f as SendResult, g as AudioPart, h as UIMessageInput, i as ApproveToolCallParams, j as toAgentClientError, k as AgentClientError, l as RetryResult, m as SubmitInput, n as AgentChatSnapshot, o as OnFinishParams, p as SetMessagesInput, q as AgentRunInput, r as AgentStatus, s as PrepareMessages, t as AgentChatControllerOptions, v as FilePart, w as ToolResultPart, x as ReasoningPart, y as ImagePart, z as StreamRequestOptions } from "./controller-CJ79_cSR.mjs";
2
+ import { pruneInputByCapabilities } from "@better-agent/core";
3
+ import { ConversationItem, GenerativeModelInputItem } from "@better-agent/core/providers";
4
+
5
+ //#region src/core/client/index.d.ts
6
+ /**
7
+ * Creates a Better Agent client.
8
+ *
9
+ * @param config Client configuration.
10
+ * @returns A typed client.
11
+ *
12
+ * @example
13
+ * ```ts
14
+ * import { createClient } from "@better-agent/client";
15
+ *
16
+ * const client = createClient({
17
+ * baseURL: "http://localhost:3000/api",
18
+ * secret: "dev_secret",
19
+ * });
20
+ *
21
+ * const result = await client.run("helloAgent", {
22
+ * input: "Write one short sentence about TypeScript.",
23
+ * });
24
+ * ```
25
+ *
26
+ * @example
27
+ * ```ts
28
+ * import type ba from "./better-agent/server";
29
+ * import { createClient } from "@better-agent/client";
30
+ *
31
+ * const client = createClient<typeof ba>({
32
+ * baseURL: "http://localhost:3000/api",
33
+ * secret: "dev_secret",
34
+ * toolHandlers: {
35
+ * getClientTime: () => ({ now: new Date().toISOString() }),
36
+ * },
37
+ * });
38
+ *
39
+ * for await (const event of client.stream("helloAgent", {
40
+ * input: "Use tools if needed.",
41
+ * })) {
42
+ * console.log(event.type);
43
+ * }
44
+ * ```
45
+ */
46
+ declare const createClient: <TApp = unknown>(config: ClientConfig<TApp>) => BetterAgentClient<NormalizeClientApp<TApp>>;
47
+ //#endregion
48
+ //#region src/core/controller.d.ts
49
+ /**
50
+ * Framework-agnostic controller for one agent conversation.
51
+ */
52
+ declare class AgentChatController<TApp = unknown, TAgentName extends AgentNameFromApp<TApp> = AgentNameFromApp<TApp>> {
53
+ private client;
54
+ private readonly id;
55
+ private state;
56
+ private status;
57
+ private error;
58
+ private lastStreamId;
59
+ private lastRunId;
60
+ private lastResponse;
61
+ private lastStructured;
62
+ private lastAppliedSeq;
63
+ private lastAppliedSeqByStream;
64
+ private initialMessages;
65
+ private listeners;
66
+ private destroyed;
67
+ private initialized;
68
+ private warnedHistoryCombo;
69
+ private options;
70
+ private activeAbortController;
71
+ constructor(client: BetterAgentClient<TApp>, options: AgentChatControllerOptions<TApp, TAgentName>);
72
+ /** Returns the current messages. */
73
+ getMessages(): UIMessage[];
74
+ /** Returns the current status. */
75
+ getStatus(): AgentStatus;
76
+ /** Returns the latest client error. */
77
+ getError(): AgentClientError | undefined;
78
+ /** Returns the latest stream id. */
79
+ getStreamId(): string | undefined;
80
+ /** Returns the latest run id. */
81
+ getRunId(): string | undefined;
82
+ /** True while a request is active. */
83
+ get isLoading(): boolean;
84
+ /** True while stream events are being consumed. */
85
+ get isStreaming(): boolean;
86
+ /** Returns pending tool approvals. */
87
+ getPendingToolApprovals(): PendingToolApproval[];
88
+ /** Returns an immutable snapshot. */
89
+ getSnapshot(): AgentChatSnapshot;
90
+ /** Stops the active run or stream. */
91
+ stop(): void;
92
+ /** Replaces the transport client. */
93
+ updateClient(client: BetterAgentClient<TApp>): void;
94
+ /**
95
+ * Subscribes to state updates.
96
+ */
97
+ subscribe(listener: () => void): () => void;
98
+ /** Calls each subscribed listener after controller state changes. */
99
+ private notify;
100
+ /** Stores run and stream ids from response headers. */
101
+ private updateResponseIds;
102
+ /** Starts hydration or resume behavior. */
103
+ init(): void;
104
+ /** Starts resume behavior, even with messages when allowed. */
105
+ private initResume;
106
+ /** Hydrates from server history before resuming. */
107
+ private hydrateFromServer;
108
+ /** Sends one message. */
109
+ sendMessage(input: ControllerRunInput, options?: SendMessageOptions): Promise<SendResult>;
110
+ /** Retries a user message by local id. */
111
+ retryMessage(localId: string): Promise<RetryResult>;
112
+ /** Resumes an existing stream. */
113
+ resumeStream(options: {
114
+ streamId: string;
115
+ afterSeq?: number;
116
+ }): Promise<void>;
117
+ /** Resumes the active stream for the current conversation. */
118
+ resumeConversation(options?: {
119
+ afterSeq?: number;
120
+ }): Promise<void>;
121
+ /** Submits a tool approval decision. */
122
+ approveToolCall(params: ApproveToolCallParams): Promise<void>;
123
+ /** Clears the current error. */
124
+ clearError(): void;
125
+ /** Resets local state to the initial snapshot. */
126
+ reset(): void;
127
+ /** Replaces local messages. */
128
+ setMessages(value: SetMessagesInput): void;
129
+ /** Merges new options into the controller configuration. */
130
+ updateOptions(partial: Partial<AgentChatControllerOptions<TApp, TAgentName>>): void;
131
+ /** Destroys the controller. */
132
+ destroy(): void;
133
+ /** Applies one streamed event to local state. */
134
+ private applyEvent;
135
+ /** Reads streamed events until the stream finishes or a terminal event appears. */
136
+ private consumeStreamUntilTerminal;
137
+ /** Reads terminal state from one streamed event. */
138
+ private getTerminalStateFromEvent;
139
+ /** Sends one request through final or stream delivery. */
140
+ private submitWithInternalOptions;
141
+ /** Builds the mutable context for one submission. */
142
+ private createSubmissionContext;
143
+ /** Warns when client history will replace stored server history. */
144
+ private warnIfClientHistoryReplacesConversation;
145
+ /** Applies retry replacement or optimistic user insertion. */
146
+ private applyLocalSubmissionState;
147
+ /** Builds the request input for the next transport call. */
148
+ private buildRequestInput;
149
+ /** Runs one request through final delivery. */
150
+ private runFinalDelivery;
151
+ /** Runs one request through streamed delivery. */
152
+ private runStreamDelivery;
153
+ /** Handles aborts, fallback-to-run, and terminal submission errors. */
154
+ private handleSubmissionFailure;
155
+ /** Marks the optimistic user message as sent after a successful request. */
156
+ private markOptimisticMessageSent;
157
+ /** Applies optimistic-message failure handling. */
158
+ private applyOptimisticFailure;
159
+ /** Stores the latest run result from final delivery. */
160
+ private captureNormalizedRunResult;
161
+ private setStatus;
162
+ /** Stores the latest controller error without notifying listeners. */
163
+ private setError;
164
+ /** Normalizes unknown failures into an `Error` with a fallback message. */
165
+ private toError;
166
+ /** Starts one controller operation. */
167
+ private startOperation;
168
+ /** Clears the tracked active operation if it matches the provided controller. */
169
+ private finishOperation;
170
+ /** Aborts and forgets any in-flight controller operation. */
171
+ private cancelActiveWork;
172
+ /** Merges the controller abort signal with an optional external signal. */
173
+ private mergeSignals;
174
+ /** Throws an abort-shaped error when the given signal has already aborted. */
175
+ private throwIfAborted;
176
+ /** Rejects work after the controller has been destroyed. */
177
+ private throwIfDestroyed;
178
+ /** Returns `true` when a failure should be treated as an abort. */
179
+ private isAbortError;
180
+ /** Returns true when a failure came from stream disconnection. */
181
+ private isStreamDisconnectError;
182
+ /** Returns true when the page is being torn down during navigation or refresh. */
183
+ private isPageTeardownLike;
184
+ /** Converts an abort reason into a standard `AbortError` instance. */
185
+ private toAbortError;
186
+ /** Wraps one failure as a stream disconnect. */
187
+ private toStreamDisconnectError;
188
+ /** Binds an already-visible current user turn to the replay run identity. */
189
+ private reconcileReplayUserMessage;
190
+ /** Reconstructs the replayed current user turn from one RUN_STARTED event. */
191
+ private toReplayUserMessage;
192
+ /** Detects one structured replay message item. */
193
+ private isSingleReplayMessageInput;
194
+ /** Matches one already-visible user turn to its replayed equivalent. */
195
+ private isSameUserTurn;
196
+ /** Generates a local message id using the configured factory when present. */
197
+ private generateMessageId;
198
+ /** Ensures every incoming UI message has a stable local id. */
199
+ private normalizeMessages;
200
+ /** Detects option changes that require resetting conversation session state. */
201
+ private hasSessionConfigurationChanged;
202
+ /** Resets controller state after a session-defining option changes. */
203
+ private resetForSessionChange;
204
+ /** Reads the initial resume stream id from controller options. */
205
+ private getConfiguredInitialStreamId;
206
+ /** Returns one message by local id from the current message state. */
207
+ private getMessageByLocalId;
208
+ /** Updates one message by local id and notifies listeners when found. */
209
+ private updateMessageByLocalId;
210
+ /** Removes one local message from state and notifies listeners. */
211
+ private removeMessageByLocalId;
212
+ /** Resolves the effective delivery mode for the next submission. */
213
+ private shouldUseStreamDelivery;
214
+ /** Detects stream capability errors that should retry through `run()`. */
215
+ private shouldFallbackToRun;
216
+ /** Appends model response messages to local state after final delivery. */
217
+ private appendResponseMessages;
218
+ /** Normalizes supported final-run response shapes into one controller shape. */
219
+ private normalizeFinalRunResult;
220
+ /** Builds the input payload, optionally serializing client history into it. */
221
+ private prepareInputForRequest;
222
+ /** Builds the run payload for one request. */
223
+ private createRunPayload;
224
+ /** Builds stream request hooks for ids, callbacks, and optimistic updates. */
225
+ private buildStreamRequestOptions;
226
+ /** Replaces one user message slot with a pending retry version. */
227
+ private replaceRetryMessage;
228
+ /** Derives a pending user message from retry input when possible. */
229
+ private createPendingUserMessage;
230
+ /** Normalizes supported input shapes into input items when possible. */
231
+ private normalizeInputItems;
232
+ /** Returns true when input is safely representable as one optimistic user turn. */
233
+ private canOptimisticallyRenderUserTurn;
234
+ /** Returns true when serialized history can reuse the optimistic user turn. */
235
+ private canOmitSubmittedInputFromSerializedHistory;
236
+ /** Calls `onFinish` with the latest completion data. */
237
+ private emitFinish;
238
+ }
239
+ /**
240
+ * Creates an `AgentChatController`.
241
+ */
242
+ declare function createAgentChatController<TApp, TAgentName extends AgentNameFromApp<TApp> = AgentNameFromApp<TApp>>(client: BetterAgentClient<TApp>, options: AgentChatControllerOptions<TApp, TAgentName>): AgentChatController<TApp, TAgentName>;
243
+ //#endregion
244
+ //#region src/core/utils.d.ts
245
+ /** Converts UI messages into model input messages. */
246
+ declare const toModelMessages: (msgs: UIMessage[]) => Array<GenerativeModelInputItem<{
247
+ inputModalities: {
248
+ text: true;
249
+ audio: true;
250
+ image: true;
251
+ file: true;
252
+ video: true;
253
+ };
254
+ additionalSupportedRoles: readonly string[];
255
+ }>>;
256
+ /** Converts model input messages back into UI messages. */
257
+ declare const fromModelMessages: (messages: GenerativeModelInputItem[], options?: {
258
+ generateId?: () => string;
259
+ }) => UIMessage[];
260
+ /** Converts durable conversation items back into UI messages. */
261
+ declare const fromConversationItems: (items: ConversationItem[], options?: {
262
+ generateId?: () => string;
263
+ }) => UIMessage[];
264
+ //#endregion
265
+ export { type AgentChatController, type AgentChatControllerOptions, type AgentChatSnapshot, type AgentClientError, type AgentContext, type AgentNameFromApp, type AgentRunInput, type AgentStatus, type AgentsFromApp, type ApproveToolCallParams, type AudioPart, type BetterAgentClient, type ClientConfig, type ClientEvent, type EmbeddingPart, type FilePart, type ImagePart, type InferClient, type ModalitiesForAgent, type NormalizeClientApp, type OnFinishParams, type OnToolCall, type PendingToolApproval, type PrepareMessages, type ReasoningPart, type ReplayInput, type RequestOptions, type ResumeOption, type RetryResult, type RunInputForAgent, type SendMessageOptions, type SendResult, type SetMessagesInput, type StreamRequestOptions, type SubmitInput, type SubmitToolApprovalRequest, type SubmitToolResultRequest, type TextInputShorthandForAgent, type TextPart, type ToolCallContext, type ToolCallPart, type ToolCallRequest, type ToolHandlers, type ToolResultPart, type TranscriptPart, type UIMessage, type UIMessageInput, type UIMessagePart, type VideoPart, createAgentChatController, createClient, fromConversationItems, fromModelMessages, getEventErrorMessage, pruneInputByCapabilities, toAgentClientError, toModelMessages };
266
+ //# sourceMappingURL=index.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../src/core/client/index.ts","../src/core/controller.ts","../src/core/utils.ts"],"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