@astralbeam/sdk 0.0.6 → 0.2.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/README.md +93 -131
- package/dist/client.d.ts +74 -16
- package/dist/client.js +1 -1
- package/dist/core-BVlttAaO.js +8245 -0
- package/dist/core.d.ts +2 -0
- package/dist/core.js +2 -0
- package/dist/debug-DyjRg3e0.js +1 -0
- package/dist/index-DtIS-V14.d.ts +3706 -0
- package/dist/react.d.ts +55 -24
- package/dist/react.js +92 -20
- package/dist/server.d.ts +30 -24
- package/dist/server.js +92 -41
- package/dist/vue.d.ts +1 -1
- package/dist/vue.js +1 -1
- package/dist/widget-CncI3L44.js +79 -0
- package/package.json +9 -2
- package/dist/chat-CXhDO2tI.js +0 -77
- package/dist/client-utils-CG2gIHHK.js +0 -1
|
@@ -0,0 +1,3706 @@
|
|
|
1
|
+
//#region node_modules/.deno/@standard-schema+spec@1.1.0/node_modules/@standard-schema/spec/dist/index.d.ts
|
|
2
|
+
/** The Standard Typed interface. This is a base type extended by other specs. */
|
|
3
|
+
interface StandardTypedV1<Input = unknown, Output = Input> {
|
|
4
|
+
/** The Standard properties. */
|
|
5
|
+
readonly "~standard": StandardTypedV1.Props<Input, Output>;
|
|
6
|
+
}
|
|
7
|
+
declare namespace StandardTypedV1 {
|
|
8
|
+
/** The Standard Typed properties interface. */
|
|
9
|
+
interface Props<Input = unknown, Output = Input> {
|
|
10
|
+
/** The version number of the standard. */
|
|
11
|
+
readonly version: 1;
|
|
12
|
+
/** The vendor name of the schema library. */
|
|
13
|
+
readonly vendor: string;
|
|
14
|
+
/** Inferred types associated with the schema. */
|
|
15
|
+
readonly types?: Types<Input, Output> | undefined;
|
|
16
|
+
}
|
|
17
|
+
/** The Standard Typed types interface. */
|
|
18
|
+
interface Types<Input = unknown, Output = Input> {
|
|
19
|
+
/** The input type of the schema. */
|
|
20
|
+
readonly input: Input;
|
|
21
|
+
/** The output type of the schema. */
|
|
22
|
+
readonly output: Output;
|
|
23
|
+
}
|
|
24
|
+
/** Infers the input type of a Standard Typed. */
|
|
25
|
+
type InferInput<Schema extends StandardTypedV1> = NonNullable<Schema["~standard"]["types"]>["input"];
|
|
26
|
+
/** Infers the output type of a Standard Typed. */
|
|
27
|
+
type InferOutput<Schema extends StandardTypedV1> = NonNullable<Schema["~standard"]["types"]>["output"];
|
|
28
|
+
}
|
|
29
|
+
/** The Standard Schema interface. */
|
|
30
|
+
interface StandardSchemaV1$1<Input = unknown, Output = Input> {
|
|
31
|
+
/** The Standard Schema properties. */
|
|
32
|
+
readonly "~standard": StandardSchemaV1$1.Props<Input, Output>;
|
|
33
|
+
}
|
|
34
|
+
declare namespace StandardSchemaV1$1 {
|
|
35
|
+
/** The Standard Schema properties interface. */
|
|
36
|
+
interface Props<Input = unknown, Output = Input> extends StandardTypedV1.Props<Input, Output> {
|
|
37
|
+
/** Validates unknown input values. */
|
|
38
|
+
readonly validate: (value: unknown, options?: StandardSchemaV1$1.Options | undefined) => Result<Output> | Promise<Result<Output>>;
|
|
39
|
+
}
|
|
40
|
+
/** The result interface of the validate function. */
|
|
41
|
+
type Result<Output> = SuccessResult<Output> | FailureResult;
|
|
42
|
+
/** The result interface if validation succeeds. */
|
|
43
|
+
interface SuccessResult<Output> {
|
|
44
|
+
/** The typed output value. */
|
|
45
|
+
readonly value: Output;
|
|
46
|
+
/** A falsy value for `issues` indicates success. */
|
|
47
|
+
readonly issues?: undefined;
|
|
48
|
+
}
|
|
49
|
+
interface Options {
|
|
50
|
+
/** Explicit support for additional vendor-specific parameters, if needed. */
|
|
51
|
+
readonly libraryOptions?: Record<string, unknown> | undefined;
|
|
52
|
+
}
|
|
53
|
+
/** The result interface if validation fails. */
|
|
54
|
+
interface FailureResult {
|
|
55
|
+
/** The issues of failed validation. */
|
|
56
|
+
readonly issues: ReadonlyArray<Issue>;
|
|
57
|
+
}
|
|
58
|
+
/** The issue interface of the failure output. */
|
|
59
|
+
interface Issue {
|
|
60
|
+
/** The error message of the issue. */
|
|
61
|
+
readonly message: string;
|
|
62
|
+
/** The path of the issue, if any. */
|
|
63
|
+
readonly path?: ReadonlyArray<PropertyKey | PathSegment> | undefined;
|
|
64
|
+
}
|
|
65
|
+
/** The path segment interface of the issue. */
|
|
66
|
+
interface PathSegment {
|
|
67
|
+
/** The key representing a path segment. */
|
|
68
|
+
readonly key: PropertyKey;
|
|
69
|
+
}
|
|
70
|
+
/** The Standard types interface. */
|
|
71
|
+
interface Types<Input = unknown, Output = Input> extends StandardTypedV1.Types<Input, Output> {}
|
|
72
|
+
/** Infers the input type of a Standard. */
|
|
73
|
+
type InferInput<Schema extends StandardTypedV1> = StandardTypedV1.InferInput<Schema>;
|
|
74
|
+
/** Infers the output type of a Standard. */
|
|
75
|
+
type InferOutput<Schema extends StandardTypedV1> = StandardTypedV1.InferOutput<Schema>;
|
|
76
|
+
}
|
|
77
|
+
/** The Standard JSON Schema interface. */
|
|
78
|
+
interface StandardJSONSchemaV1<Input = unknown, Output = Input> {
|
|
79
|
+
/** The Standard JSON Schema properties. */
|
|
80
|
+
readonly "~standard": StandardJSONSchemaV1.Props<Input, Output>;
|
|
81
|
+
}
|
|
82
|
+
declare namespace StandardJSONSchemaV1 {
|
|
83
|
+
/** The Standard JSON Schema properties interface. */
|
|
84
|
+
interface Props<Input = unknown, Output = Input> extends StandardTypedV1.Props<Input, Output> {
|
|
85
|
+
/** Methods for generating the input/output JSON Schema. */
|
|
86
|
+
readonly jsonSchema: StandardJSONSchemaV1.Converter;
|
|
87
|
+
}
|
|
88
|
+
/** The Standard JSON Schema converter interface. */
|
|
89
|
+
interface Converter {
|
|
90
|
+
/** Converts the input type to JSON Schema. May throw if conversion is not supported. */
|
|
91
|
+
readonly input: (options: StandardJSONSchemaV1.Options) => Record<string, unknown>;
|
|
92
|
+
/** Converts the output type to JSON Schema. May throw if conversion is not supported. */
|
|
93
|
+
readonly output: (options: StandardJSONSchemaV1.Options) => Record<string, unknown>;
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* The target version of the generated JSON Schema.
|
|
97
|
+
*
|
|
98
|
+
* It is *strongly recommended* that implementers support `"draft-2020-12"` and `"draft-07"`, as they are both in wide use. All other targets can be implemented on a best-effort basis. Libraries should throw if they don't support a specified target.
|
|
99
|
+
*
|
|
100
|
+
* The `"openapi-3.0"` target is intended as a standardized specifier for OpenAPI 3.0 which is a superset of JSON Schema `"draft-04"`.
|
|
101
|
+
*/
|
|
102
|
+
type Target = "draft-2020-12" | "draft-07" | "openapi-3.0" | ({} & string);
|
|
103
|
+
/** The options for the input/output methods. */
|
|
104
|
+
interface Options {
|
|
105
|
+
/** Specifies the target version of the generated JSON Schema. Support for all versions is on a best-effort basis. If a given version is not supported, the library should throw. */
|
|
106
|
+
readonly target: Target;
|
|
107
|
+
/** Explicit support for additional vendor-specific parameters, if needed. */
|
|
108
|
+
readonly libraryOptions?: Record<string, unknown> | undefined;
|
|
109
|
+
}
|
|
110
|
+
/** The Standard types interface. */
|
|
111
|
+
interface Types<Input = unknown, Output = Input> extends StandardTypedV1.Types<Input, Output> {}
|
|
112
|
+
/** Infers the input type of a Standard. */
|
|
113
|
+
type InferInput<Schema extends StandardTypedV1> = StandardTypedV1.InferInput<Schema>;
|
|
114
|
+
/** Infers the output type of a Standard. */
|
|
115
|
+
type InferOutput<Schema extends StandardTypedV1> = StandardTypedV1.InferOutput<Schema>;
|
|
116
|
+
}
|
|
117
|
+
//#endregion
|
|
118
|
+
//#region node_modules/.deno/@tanstack+ai@0.49.1/node_modules/@tanstack/ai/dist/esm/interrupts.d.ts
|
|
119
|
+
interface InterruptCorrelation {
|
|
120
|
+
threadId: string;
|
|
121
|
+
interruptedRunId: string;
|
|
122
|
+
generation: number;
|
|
123
|
+
submissionId?: string;
|
|
124
|
+
continuationRunId?: string;
|
|
125
|
+
}
|
|
126
|
+
type ItemInterruptErrorCode = 'invalid-payload' | 'invalid-edited-args' | 'invalid-tool-output' | 'invalid-response-schema' | 'unknown-interrupt' | 'expired' | 'stale' | 'conflict' | 'legacy-unsupported';
|
|
127
|
+
type BatchInterruptErrorCode = 'incomplete-batch' | 'item-validation-failed' | 'unsupported-bulk-operation' | 'async-resolver' | 'inactive-transaction' | 'mixed-provenance' | 'transport' | 'server' | 'protocol' | 'invalid-response-schema' | 'expired' | 'stale' | 'conflict' | 'legacy-submit-failed';
|
|
128
|
+
interface ItemInterruptError extends InterruptCorrelation {
|
|
129
|
+
scope: 'item';
|
|
130
|
+
interruptId: string;
|
|
131
|
+
code: ItemInterruptErrorCode;
|
|
132
|
+
message: string;
|
|
133
|
+
path?: ReadonlyArray<string | number>;
|
|
134
|
+
source: 'client' | 'server';
|
|
135
|
+
retryable: boolean;
|
|
136
|
+
}
|
|
137
|
+
interface BatchInterruptError extends InterruptCorrelation {
|
|
138
|
+
scope: 'batch';
|
|
139
|
+
code: BatchInterruptErrorCode;
|
|
140
|
+
message: string;
|
|
141
|
+
source: 'client' | 'server' | 'transport';
|
|
142
|
+
retryable: boolean;
|
|
143
|
+
interruptIds: ReadonlyArray<string>;
|
|
144
|
+
}
|
|
145
|
+
type InterruptSubmissionError = ItemInterruptError | BatchInterruptError;
|
|
146
|
+
/**
|
|
147
|
+
* Wire version of {@link InterruptBinding}.
|
|
148
|
+
*
|
|
149
|
+
* The binding is the only part of an AG-UI `Interrupt` that this package
|
|
150
|
+
* claims — it rides in `metadata` under
|
|
151
|
+
* {@link INTERRUPT_BINDING_METADATA_KEY} and tells the resume path how to
|
|
152
|
+
* correlate an answer back to a paused run. Producers stamp `v`; readers
|
|
153
|
+
* reject any version they don't understand rather than duck-typing the fields.
|
|
154
|
+
*
|
|
155
|
+
* That matters because an AG-UI `Interrupt` is a shared envelope. Another
|
|
156
|
+
* producer — a workflow engine projecting a durable approval, a third-party
|
|
157
|
+
* agent — can legitimately put its own binding in the same envelope. Versioning
|
|
158
|
+
* makes "not mine" a clean rejection instead of a partial match that resumes
|
|
159
|
+
* against the wrong owner.
|
|
160
|
+
*/
|
|
161
|
+
declare const INTERRUPT_BINDING_VERSION: 1;
|
|
162
|
+
interface InterruptBindingBase {
|
|
163
|
+
/** @see INTERRUPT_BINDING_VERSION */
|
|
164
|
+
v: typeof INTERRUPT_BINDING_VERSION;
|
|
165
|
+
interruptId: string;
|
|
166
|
+
interruptedRunId: string;
|
|
167
|
+
generation: number;
|
|
168
|
+
expiresAt?: string;
|
|
169
|
+
}
|
|
170
|
+
interface ResponseSchemaInterruptBindingBase extends InterruptBindingBase {
|
|
171
|
+
responseSchemaHash: string;
|
|
172
|
+
}
|
|
173
|
+
type InterruptBinding = (ResponseSchemaInterruptBindingBase & {
|
|
174
|
+
kind: 'tool-approval';
|
|
175
|
+
toolName: string;
|
|
176
|
+
toolCallId: string;
|
|
177
|
+
originalArgs: unknown;
|
|
178
|
+
inputSchemaHash: string;
|
|
179
|
+
approvalSchemaHash: string;
|
|
180
|
+
}) | (ResponseSchemaInterruptBindingBase & {
|
|
181
|
+
kind: 'client-tool-execution';
|
|
182
|
+
toolName: string;
|
|
183
|
+
toolCallId: string;
|
|
184
|
+
outputSchemaHash: string;
|
|
185
|
+
}) | (InterruptBindingBase & {
|
|
186
|
+
kind: 'generic'; /** Omitted when the generic interrupt accepts an unvalidated response. */
|
|
187
|
+
responseSchemaHash?: string; /** Present only for a first-party generic interrupt. */
|
|
188
|
+
definitionId?: string;
|
|
189
|
+
key?: string;
|
|
190
|
+
batchIndex?: number;
|
|
191
|
+
payloadSchemaHash?: string;
|
|
192
|
+
});
|
|
193
|
+
//#endregion
|
|
194
|
+
//#region node_modules/.deno/@tanstack+devtools-event-client@0.4.4/node_modules/@tanstack/devtools-event-client/dist/esm/plugin.d.ts
|
|
195
|
+
declare global {
|
|
196
|
+
var __TANSTACK_EVENT_TARGET__: EventTarget | null;
|
|
197
|
+
}
|
|
198
|
+
//#endregion
|
|
199
|
+
//#region node_modules/.deno/@tanstack+ai-event-client@0.10.0/node_modules/@tanstack/ai-event-client/dist/esm/envelope.d.ts
|
|
200
|
+
type AIDevtoolsEventSource = 'client' | 'server' | 'devtools';
|
|
201
|
+
type AIDevtoolsEventVisibility = 'user-visible' | 'client-state' | 'server-internal' | 'devtools-action';
|
|
202
|
+
interface AIDevtoolsEventEnvelope {
|
|
203
|
+
eventId: string;
|
|
204
|
+
eventType: string;
|
|
205
|
+
timestamp: number;
|
|
206
|
+
source: AIDevtoolsEventSource;
|
|
207
|
+
visibility: AIDevtoolsEventVisibility;
|
|
208
|
+
runtimeId?: string;
|
|
209
|
+
clientId?: string;
|
|
210
|
+
requestId?: string;
|
|
211
|
+
streamId?: string;
|
|
212
|
+
hookId?: string;
|
|
213
|
+
threadId?: string;
|
|
214
|
+
runId?: string;
|
|
215
|
+
messageId?: string;
|
|
216
|
+
toolCallId?: string;
|
|
217
|
+
sequence?: number;
|
|
218
|
+
correlationId?: string;
|
|
219
|
+
relatedEventId?: string;
|
|
220
|
+
}
|
|
221
|
+
declare global {
|
|
222
|
+
var __TANSTACK_AI_DEVTOOLS_RUNTIME_ID__: string | undefined;
|
|
223
|
+
}
|
|
224
|
+
//#endregion
|
|
225
|
+
//#region node_modules/.deno/@tanstack+ai-event-client@0.10.0/node_modules/@tanstack/ai-event-client/dist/esm/index.d.ts
|
|
226
|
+
/**
|
|
227
|
+
* Detailed breakdown of prompt/input token usage.
|
|
228
|
+
* Fields are populated based on provider support.
|
|
229
|
+
*/
|
|
230
|
+
interface PromptTokensDetails {
|
|
231
|
+
/** Tokens read from cache */
|
|
232
|
+
cachedTokens?: number;
|
|
233
|
+
/** Tokens written to cache */
|
|
234
|
+
cacheWriteTokens?: number;
|
|
235
|
+
/** Audio input tokens */
|
|
236
|
+
audioTokens?: number;
|
|
237
|
+
/** Video input tokens */
|
|
238
|
+
videoTokens?: number;
|
|
239
|
+
/** Image input tokens */
|
|
240
|
+
imageTokens?: number;
|
|
241
|
+
/** Text input tokens */
|
|
242
|
+
textTokens?: number;
|
|
243
|
+
/** Document input tokens (e.g. PDF inputs on Gemini) */
|
|
244
|
+
documentTokens?: number;
|
|
245
|
+
}
|
|
246
|
+
/**
|
|
247
|
+
* Detailed breakdown of completion/output token usage.
|
|
248
|
+
* Fields are populated based on provider support.
|
|
249
|
+
*/
|
|
250
|
+
interface CompletionTokensDetails {
|
|
251
|
+
/** Reasoning/thinking tokens */
|
|
252
|
+
reasoningTokens?: number;
|
|
253
|
+
/** Audio output tokens */
|
|
254
|
+
audioTokens?: number;
|
|
255
|
+
/** Video output tokens */
|
|
256
|
+
videoTokens?: number;
|
|
257
|
+
/** Image output tokens */
|
|
258
|
+
imageTokens?: number;
|
|
259
|
+
/** Text output tokens */
|
|
260
|
+
textTokens?: number;
|
|
261
|
+
/** Document output tokens */
|
|
262
|
+
documentTokens?: number;
|
|
263
|
+
}
|
|
264
|
+
/**
|
|
265
|
+
* Provider-reported cost breakdown for a single request, normalized onto a
|
|
266
|
+
* canonical shape so consumer code is portable across gateways. Each adapter's
|
|
267
|
+
* extractor maps its provider-specific wire keys (e.g. OpenRouter's
|
|
268
|
+
* `upstream_inference_prompt_cost`, `upstream_inference_input_cost`) onto these
|
|
269
|
+
* fields at runtime.
|
|
270
|
+
*/
|
|
271
|
+
interface UsageCostBreakdown {
|
|
272
|
+
/** Total cost the gateway paid the upstream provider. */
|
|
273
|
+
upstreamCost?: number;
|
|
274
|
+
/** Upstream cost for input (prompt) tokens. */
|
|
275
|
+
upstreamInputCost?: number;
|
|
276
|
+
/** Upstream cost for output (completion) tokens. */
|
|
277
|
+
upstreamOutputCost?: number;
|
|
278
|
+
}
|
|
279
|
+
/**
|
|
280
|
+
* Unit a billed quantity is counted in. The named members cover the units
|
|
281
|
+
* TanStack AI adapters bill in today; the `(string & {})` member keeps the
|
|
282
|
+
* union open for genuinely provider-specific units while preserving
|
|
283
|
+
* autocompletion for the common ones.
|
|
284
|
+
*/
|
|
285
|
+
type BillingUnit = 'tokens' | 'seconds' | 'characters' | 'images' | 'videos' | 'megapixels' | 'requests' | 'units' | (string & {});
|
|
286
|
+
/**
|
|
287
|
+
* A billed quantity paired with the unit it is counted in, so consumers can
|
|
288
|
+
* label and aggregate usage without out-of-band knowledge of the provider or
|
|
289
|
+
* activity. `unit: 'units'` marks an opaque provider-defined unit (e.g. fal's
|
|
290
|
+
* "fal units") whose price is only knowable from the provider's pricing page.
|
|
291
|
+
*/
|
|
292
|
+
interface BilledUsage {
|
|
293
|
+
/** Number of units billed. */
|
|
294
|
+
quantity: number;
|
|
295
|
+
/** The unit `quantity` is counted in. */
|
|
296
|
+
unit: BillingUnit;
|
|
297
|
+
}
|
|
298
|
+
/**
|
|
299
|
+
* Default value type for {@link TokenUsage.providerUsageDetails} when an adapter
|
|
300
|
+
* does not supply a specific shape. Values are constrained to non-nullish
|
|
301
|
+
* (`NonNullable<unknown>`, i.e. `{}`) rather than `unknown` so that `TokenUsage`
|
|
302
|
+
* stays assignable across JSON-serialization boundaries — e.g. TanStack Start's
|
|
303
|
+
* server-fn return types model serializable values as `{}` and reject `unknown`,
|
|
304
|
+
* which permits `null`/`undefined`.
|
|
305
|
+
*/
|
|
306
|
+
type ProviderUsageDetails = Record<string, NonNullable<unknown>>;
|
|
307
|
+
/**
|
|
308
|
+
* Canonical token usage for a run, with optional detailed breakdowns and
|
|
309
|
+
* provider-reported cost. This is the single source of truth re-exported by
|
|
310
|
+
* `@tanstack/ai`.
|
|
311
|
+
*
|
|
312
|
+
* Core fields (`promptTokens`, `completionTokens`, `totalTokens`) are always
|
|
313
|
+
* present. Detail fields are provider-dependent and absent when not reported,
|
|
314
|
+
* so consumers must treat them as optional.
|
|
315
|
+
*
|
|
316
|
+
* `providerUsageDetails` is parameterized via `TProviderDetails` so adapters can
|
|
317
|
+
* surface a strongly-typed bag (e.g. `TokenUsage<AnthropicProviderUsageDetails>`);
|
|
318
|
+
* it defaults to {@link ProviderUsageDetails} (an open, serializable record) for
|
|
319
|
+
* generic consumers.
|
|
320
|
+
*/
|
|
321
|
+
interface TokenUsage<TProviderDetails = ProviderUsageDetails> {
|
|
322
|
+
/** Total input/prompt tokens */
|
|
323
|
+
promptTokens: number;
|
|
324
|
+
/** Total output/completion tokens */
|
|
325
|
+
completionTokens: number;
|
|
326
|
+
/** Total tokens as reported by the provider; may exceed promptTokens +
|
|
327
|
+
* completionTokens when reasoning/cache/tool tokens are billed separately. */
|
|
328
|
+
totalTokens: number;
|
|
329
|
+
/** Detailed breakdown of prompt tokens by category */
|
|
330
|
+
promptTokensDetails?: PromptTokensDetails;
|
|
331
|
+
/** Detailed breakdown of completion tokens by category */
|
|
332
|
+
completionTokensDetails?: CompletionTokensDetails;
|
|
333
|
+
/**
|
|
334
|
+
* The primary non-token billed quantity, self-describing via its unit —
|
|
335
|
+
* e.g. `{ quantity: 8, unit: 'seconds' }` for a video generation or
|
|
336
|
+
* `{ quantity: 3, unit: 'units' }` for fal's opaque endpoint units. Absent
|
|
337
|
+
* when the activity bills purely in tokens (the token fields above are
|
|
338
|
+
* already self-describing). When a provider bills tokens *on top of* a media
|
|
339
|
+
* unit, the tokens stay in the token fields and `billed` carries the media
|
|
340
|
+
* unit. A quantity, distinct from the monetary `cost` / `costDetails`.
|
|
341
|
+
*/
|
|
342
|
+
billed?: BilledUsage;
|
|
343
|
+
/**
|
|
344
|
+
* @deprecated Read {@link TokenUsage.billed} instead, which pairs the same
|
|
345
|
+
* duration with an explicit `unit: 'seconds'`. Still populated alongside
|
|
346
|
+
* `billed` for backward compatibility; will be removed in a future release.
|
|
347
|
+
*/
|
|
348
|
+
durationSeconds?: number;
|
|
349
|
+
/**
|
|
350
|
+
* @deprecated Read {@link TokenUsage.billed} instead, which pairs the same
|
|
351
|
+
* count with the unit it is denominated in (`seconds`, `units`, …) — this
|
|
352
|
+
* bare count is ambiguous across providers. Still populated alongside
|
|
353
|
+
* `billed` for backward compatibility; will be removed in a future release.
|
|
354
|
+
*/
|
|
355
|
+
unitsBilled?: number;
|
|
356
|
+
/** Provider-specific usage details not covered by standard fields */
|
|
357
|
+
providerUsageDetails?: TProviderDetails;
|
|
358
|
+
/** Provider-reported cost for the request, when available. */
|
|
359
|
+
cost?: number;
|
|
360
|
+
/** Provider-reported cost breakdown, when available. */
|
|
361
|
+
costDetails?: UsageCostBreakdown;
|
|
362
|
+
}
|
|
363
|
+
//#endregion
|
|
364
|
+
//#region node_modules/.deno/@ag-ui+core@0.1.1-canary.beta.0/node_modules/@ag-ui/core/dist/events-JPFRVbr9.d.ts
|
|
365
|
+
//#region src/types.d.ts
|
|
366
|
+
interface FunctionCall {
|
|
367
|
+
name: string;
|
|
368
|
+
arguments: string;
|
|
369
|
+
}
|
|
370
|
+
interface ToolCall$1 {
|
|
371
|
+
id: string;
|
|
372
|
+
type: "function";
|
|
373
|
+
function: FunctionCall;
|
|
374
|
+
encryptedValue?: string;
|
|
375
|
+
}
|
|
376
|
+
interface TextInputContent {
|
|
377
|
+
type: "text";
|
|
378
|
+
text: string;
|
|
379
|
+
}
|
|
380
|
+
interface InputContentDataSource {
|
|
381
|
+
type: "data";
|
|
382
|
+
value: string;
|
|
383
|
+
mimeType: string;
|
|
384
|
+
}
|
|
385
|
+
interface InputContentUrlSource {
|
|
386
|
+
type: "url";
|
|
387
|
+
value: string;
|
|
388
|
+
mimeType?: string;
|
|
389
|
+
}
|
|
390
|
+
type InputContentSource = InputContentDataSource | InputContentUrlSource;
|
|
391
|
+
interface ImageInputContent {
|
|
392
|
+
type: "image";
|
|
393
|
+
source: InputContentSource;
|
|
394
|
+
metadata?: unknown;
|
|
395
|
+
}
|
|
396
|
+
interface AudioInputContent {
|
|
397
|
+
type: "audio";
|
|
398
|
+
source: InputContentSource;
|
|
399
|
+
metadata?: unknown;
|
|
400
|
+
}
|
|
401
|
+
interface VideoInputContent {
|
|
402
|
+
type: "video";
|
|
403
|
+
source: InputContentSource;
|
|
404
|
+
metadata?: unknown;
|
|
405
|
+
}
|
|
406
|
+
interface DocumentInputContent {
|
|
407
|
+
type: "document";
|
|
408
|
+
source: InputContentSource;
|
|
409
|
+
metadata?: unknown;
|
|
410
|
+
}
|
|
411
|
+
interface BinaryInputContent {
|
|
412
|
+
type: "binary";
|
|
413
|
+
mimeType: string;
|
|
414
|
+
id?: string;
|
|
415
|
+
url?: string;
|
|
416
|
+
data?: string;
|
|
417
|
+
filename?: string;
|
|
418
|
+
}
|
|
419
|
+
type InputContent = TextInputContent | ImageInputContent | AudioInputContent | VideoInputContent | DocumentInputContent | BinaryInputContent;
|
|
420
|
+
interface BaseMessageFields {
|
|
421
|
+
id: string;
|
|
422
|
+
name?: string;
|
|
423
|
+
encryptedValue?: string;
|
|
424
|
+
}
|
|
425
|
+
interface DeveloperMessage extends BaseMessageFields {
|
|
426
|
+
role: "developer";
|
|
427
|
+
content: string;
|
|
428
|
+
}
|
|
429
|
+
interface SystemMessage extends BaseMessageFields {
|
|
430
|
+
role: "system";
|
|
431
|
+
content: string;
|
|
432
|
+
}
|
|
433
|
+
interface AssistantMessage extends BaseMessageFields {
|
|
434
|
+
role: "assistant";
|
|
435
|
+
content?: string;
|
|
436
|
+
toolCalls?: ToolCall$1[];
|
|
437
|
+
}
|
|
438
|
+
interface UserMessage extends BaseMessageFields {
|
|
439
|
+
role: "user";
|
|
440
|
+
content: string | InputContent[];
|
|
441
|
+
}
|
|
442
|
+
interface ToolMessage {
|
|
443
|
+
id: string;
|
|
444
|
+
content: string;
|
|
445
|
+
role: "tool";
|
|
446
|
+
toolCallId: string;
|
|
447
|
+
error?: string;
|
|
448
|
+
encryptedValue?: string;
|
|
449
|
+
}
|
|
450
|
+
interface ActivityMessage {
|
|
451
|
+
id: string;
|
|
452
|
+
role: "activity";
|
|
453
|
+
activityType: string;
|
|
454
|
+
content: Record<string, any>;
|
|
455
|
+
}
|
|
456
|
+
interface ReasoningMessage {
|
|
457
|
+
id: string;
|
|
458
|
+
role: "reasoning";
|
|
459
|
+
content: string;
|
|
460
|
+
encryptedValue?: string;
|
|
461
|
+
}
|
|
462
|
+
type Message = DeveloperMessage | SystemMessage | AssistantMessage | UserMessage | ToolMessage | ActivityMessage | ReasoningMessage;
|
|
463
|
+
interface Context {
|
|
464
|
+
description: string;
|
|
465
|
+
value: string;
|
|
466
|
+
}
|
|
467
|
+
interface Tool$2 {
|
|
468
|
+
name: string;
|
|
469
|
+
description: string;
|
|
470
|
+
parameters?: any;
|
|
471
|
+
metadata?: Record<string, any>;
|
|
472
|
+
}
|
|
473
|
+
interface Interrupt$1 {
|
|
474
|
+
id: string;
|
|
475
|
+
reason: string;
|
|
476
|
+
message?: string;
|
|
477
|
+
toolCallId?: string;
|
|
478
|
+
responseSchema?: Record<string, any>;
|
|
479
|
+
expiresAt?: string;
|
|
480
|
+
metadata?: Record<string, any>;
|
|
481
|
+
}
|
|
482
|
+
type ResumeStatus = "resolved" | "cancelled";
|
|
483
|
+
interface ResumeEntry {
|
|
484
|
+
interruptId: string;
|
|
485
|
+
status: ResumeStatus;
|
|
486
|
+
payload?: any;
|
|
487
|
+
}
|
|
488
|
+
interface RunAgentInput {
|
|
489
|
+
threadId: string;
|
|
490
|
+
runId: string;
|
|
491
|
+
parentRunId?: string;
|
|
492
|
+
state?: any;
|
|
493
|
+
messages: Message[];
|
|
494
|
+
tools: Tool$2[];
|
|
495
|
+
context: Context[];
|
|
496
|
+
forwardedProps?: any;
|
|
497
|
+
resume?: ResumeEntry[];
|
|
498
|
+
}
|
|
499
|
+
//#endregion
|
|
500
|
+
//#region src/events.d.ts
|
|
501
|
+
declare enum EventType {
|
|
502
|
+
TEXT_MESSAGE_START = "TEXT_MESSAGE_START",
|
|
503
|
+
TEXT_MESSAGE_CONTENT = "TEXT_MESSAGE_CONTENT",
|
|
504
|
+
TEXT_MESSAGE_END = "TEXT_MESSAGE_END",
|
|
505
|
+
TEXT_MESSAGE_CHUNK = "TEXT_MESSAGE_CHUNK",
|
|
506
|
+
TOOL_CALL_START = "TOOL_CALL_START",
|
|
507
|
+
TOOL_CALL_ARGS = "TOOL_CALL_ARGS",
|
|
508
|
+
TOOL_CALL_END = "TOOL_CALL_END",
|
|
509
|
+
TOOL_CALL_CHUNK = "TOOL_CALL_CHUNK",
|
|
510
|
+
TOOL_CALL_RESULT = "TOOL_CALL_RESULT",
|
|
511
|
+
/** @deprecated Use REASONING_START instead. Will be removed in 1.0.0. */
|
|
512
|
+
THINKING_START = "THINKING_START",
|
|
513
|
+
/** @deprecated Use REASONING_END instead. Will be removed in 1.0.0. */
|
|
514
|
+
THINKING_END = "THINKING_END",
|
|
515
|
+
/** @deprecated Use REASONING_MESSAGE_START instead. Will be removed in 1.0.0. */
|
|
516
|
+
THINKING_TEXT_MESSAGE_START = "THINKING_TEXT_MESSAGE_START",
|
|
517
|
+
/** @deprecated Use REASONING_MESSAGE_CONTENT instead. Will be removed in 1.0.0. */
|
|
518
|
+
THINKING_TEXT_MESSAGE_CONTENT = "THINKING_TEXT_MESSAGE_CONTENT",
|
|
519
|
+
/** @deprecated Use REASONING_MESSAGE_END instead. Will be removed in 1.0.0. */
|
|
520
|
+
THINKING_TEXT_MESSAGE_END = "THINKING_TEXT_MESSAGE_END",
|
|
521
|
+
STATE_SNAPSHOT = "STATE_SNAPSHOT",
|
|
522
|
+
STATE_DELTA = "STATE_DELTA",
|
|
523
|
+
MESSAGES_SNAPSHOT = "MESSAGES_SNAPSHOT",
|
|
524
|
+
ACTIVITY_SNAPSHOT = "ACTIVITY_SNAPSHOT",
|
|
525
|
+
ACTIVITY_DELTA = "ACTIVITY_DELTA",
|
|
526
|
+
RAW = "RAW",
|
|
527
|
+
CUSTOM = "CUSTOM",
|
|
528
|
+
RUN_STARTED = "RUN_STARTED",
|
|
529
|
+
RUN_FINISHED = "RUN_FINISHED",
|
|
530
|
+
RUN_ERROR = "RUN_ERROR",
|
|
531
|
+
STEP_STARTED = "STEP_STARTED",
|
|
532
|
+
STEP_FINISHED = "STEP_FINISHED",
|
|
533
|
+
REASONING_START = "REASONING_START",
|
|
534
|
+
REASONING_MESSAGE_START = "REASONING_MESSAGE_START",
|
|
535
|
+
REASONING_MESSAGE_CONTENT = "REASONING_MESSAGE_CONTENT",
|
|
536
|
+
REASONING_MESSAGE_END = "REASONING_MESSAGE_END",
|
|
537
|
+
REASONING_MESSAGE_CHUNK = "REASONING_MESSAGE_CHUNK",
|
|
538
|
+
REASONING_END = "REASONING_END",
|
|
539
|
+
REASONING_ENCRYPTED_VALUE = "REASONING_ENCRYPTED_VALUE"
|
|
540
|
+
}
|
|
541
|
+
type TextMessageRole = "developer" | "system" | "assistant" | "user";
|
|
542
|
+
type ReasoningEncryptedValueSubtype = "tool-call" | "message";
|
|
543
|
+
interface BaseEvent {
|
|
544
|
+
type: EventType;
|
|
545
|
+
timestamp?: number;
|
|
546
|
+
rawEvent?: any;
|
|
547
|
+
[k: string]: unknown;
|
|
548
|
+
}
|
|
549
|
+
interface TextMessageStartEvent$1 extends BaseEvent {
|
|
550
|
+
type: EventType.TEXT_MESSAGE_START;
|
|
551
|
+
messageId: string;
|
|
552
|
+
role: TextMessageRole;
|
|
553
|
+
name?: string;
|
|
554
|
+
}
|
|
555
|
+
interface TextMessageContentEvent$1 extends BaseEvent {
|
|
556
|
+
type: EventType.TEXT_MESSAGE_CONTENT;
|
|
557
|
+
messageId: string;
|
|
558
|
+
delta: string;
|
|
559
|
+
}
|
|
560
|
+
interface TextMessageEndEvent$1 extends BaseEvent {
|
|
561
|
+
type: EventType.TEXT_MESSAGE_END;
|
|
562
|
+
messageId: string;
|
|
563
|
+
}
|
|
564
|
+
interface ToolCallStartEvent$1 extends BaseEvent {
|
|
565
|
+
type: EventType.TOOL_CALL_START;
|
|
566
|
+
toolCallId: string;
|
|
567
|
+
toolCallName: string;
|
|
568
|
+
parentMessageId?: string;
|
|
569
|
+
}
|
|
570
|
+
interface ToolCallArgsEvent$1 extends BaseEvent {
|
|
571
|
+
type: EventType.TOOL_CALL_ARGS;
|
|
572
|
+
toolCallId: string;
|
|
573
|
+
delta: string;
|
|
574
|
+
}
|
|
575
|
+
interface ToolCallEndEvent$1 extends BaseEvent {
|
|
576
|
+
type: EventType.TOOL_CALL_END;
|
|
577
|
+
toolCallId: string;
|
|
578
|
+
}
|
|
579
|
+
interface ToolCallResultEvent$1 extends BaseEvent {
|
|
580
|
+
messageId: string;
|
|
581
|
+
type: EventType.TOOL_CALL_RESULT;
|
|
582
|
+
toolCallId: string;
|
|
583
|
+
content: string;
|
|
584
|
+
role?: "tool";
|
|
585
|
+
}
|
|
586
|
+
interface StateSnapshotEvent$1 extends BaseEvent {
|
|
587
|
+
type: EventType.STATE_SNAPSHOT;
|
|
588
|
+
snapshot?: any;
|
|
589
|
+
}
|
|
590
|
+
interface StateDeltaEvent$1 extends BaseEvent {
|
|
591
|
+
type: EventType.STATE_DELTA;
|
|
592
|
+
delta: any[];
|
|
593
|
+
}
|
|
594
|
+
interface MessagesSnapshotEvent$1 extends BaseEvent {
|
|
595
|
+
type: EventType.MESSAGES_SNAPSHOT;
|
|
596
|
+
messages: Message[];
|
|
597
|
+
}
|
|
598
|
+
interface CustomEvent$1 extends BaseEvent {
|
|
599
|
+
type: EventType.CUSTOM;
|
|
600
|
+
name: string;
|
|
601
|
+
value?: any;
|
|
602
|
+
}
|
|
603
|
+
interface RunStartedEvent$1 extends BaseEvent {
|
|
604
|
+
type: EventType.RUN_STARTED;
|
|
605
|
+
threadId: string;
|
|
606
|
+
runId: string;
|
|
607
|
+
parentRunId?: string;
|
|
608
|
+
input?: RunAgentInput;
|
|
609
|
+
}
|
|
610
|
+
interface RunFinishedSuccessOutcome {
|
|
611
|
+
type: "success";
|
|
612
|
+
}
|
|
613
|
+
interface RunFinishedInterruptOutcome {
|
|
614
|
+
type: "interrupt";
|
|
615
|
+
interrupts: Interrupt$1[];
|
|
616
|
+
}
|
|
617
|
+
type RunFinishedOutcome = RunFinishedSuccessOutcome | RunFinishedInterruptOutcome;
|
|
618
|
+
interface RunFinishedEvent$1 extends BaseEvent {
|
|
619
|
+
type: EventType.RUN_FINISHED;
|
|
620
|
+
threadId: string;
|
|
621
|
+
runId: string;
|
|
622
|
+
result?: any;
|
|
623
|
+
outcome?: RunFinishedOutcome;
|
|
624
|
+
}
|
|
625
|
+
interface RunErrorEvent$1 extends BaseEvent {
|
|
626
|
+
type: EventType.RUN_ERROR;
|
|
627
|
+
message: string;
|
|
628
|
+
code?: string;
|
|
629
|
+
}
|
|
630
|
+
interface StepStartedEvent$1 extends BaseEvent {
|
|
631
|
+
type: EventType.STEP_STARTED;
|
|
632
|
+
stepName: string;
|
|
633
|
+
}
|
|
634
|
+
interface StepFinishedEvent$1 extends BaseEvent {
|
|
635
|
+
type: EventType.STEP_FINISHED;
|
|
636
|
+
stepName: string;
|
|
637
|
+
}
|
|
638
|
+
interface ReasoningStartEvent$1 extends BaseEvent {
|
|
639
|
+
type: EventType.REASONING_START;
|
|
640
|
+
messageId: string;
|
|
641
|
+
}
|
|
642
|
+
interface ReasoningMessageStartEvent$1 extends BaseEvent {
|
|
643
|
+
type: EventType.REASONING_MESSAGE_START;
|
|
644
|
+
messageId: string;
|
|
645
|
+
role: "reasoning";
|
|
646
|
+
}
|
|
647
|
+
interface ReasoningMessageContentEvent$1 extends BaseEvent {
|
|
648
|
+
type: EventType.REASONING_MESSAGE_CONTENT;
|
|
649
|
+
messageId: string;
|
|
650
|
+
delta: string;
|
|
651
|
+
}
|
|
652
|
+
interface ReasoningMessageEndEvent$1 extends BaseEvent {
|
|
653
|
+
type: EventType.REASONING_MESSAGE_END;
|
|
654
|
+
messageId: string;
|
|
655
|
+
}
|
|
656
|
+
interface ReasoningEndEvent$1 extends BaseEvent {
|
|
657
|
+
type: EventType.REASONING_END;
|
|
658
|
+
messageId: string;
|
|
659
|
+
}
|
|
660
|
+
interface ReasoningEncryptedValueEvent$1 extends BaseEvent {
|
|
661
|
+
type: EventType.REASONING_ENCRYPTED_VALUE;
|
|
662
|
+
subtype: ReasoningEncryptedValueSubtype;
|
|
663
|
+
entityId: string;
|
|
664
|
+
encryptedValue: string;
|
|
665
|
+
}
|
|
666
|
+
//#endregion
|
|
667
|
+
//#region node_modules/.deno/@tanstack+ai@0.49.1/node_modules/@tanstack/ai/dist/esm/utilities/ag-ui-usage.d.ts
|
|
668
|
+
/** AG-UI spec `usage[]` item (provider/model labels + token counts only). */
|
|
669
|
+
interface SpecTokenUsage {
|
|
670
|
+
provider?: string;
|
|
671
|
+
model?: string;
|
|
672
|
+
inputTokens?: number;
|
|
673
|
+
outputTokens?: number;
|
|
674
|
+
totalTokens?: number;
|
|
675
|
+
reasoningTokens?: number;
|
|
676
|
+
cachedInputTokens?: number;
|
|
677
|
+
}
|
|
678
|
+
/** TokenUsage fields that have no AG-UI `usage[]` equivalent. */
|
|
679
|
+
type TokenUsageLeftover = Omit<TokenUsage, 'promptTokens' | 'completionTokens' | 'totalTokens'>;
|
|
680
|
+
//#endregion
|
|
681
|
+
//#region node_modules/.deno/@tanstack+ai@0.49.1/node_modules/@tanstack/ai/dist/esm/types.d.ts
|
|
682
|
+
/**
|
|
683
|
+
* Tool call states - track the lifecycle of a tool call
|
|
684
|
+
*/
|
|
685
|
+
type ToolCallState$1 = 'awaiting-input' | 'input-streaming' | 'input-complete' | 'approval-requested' | 'approval-responded' | 'complete' | 'error';
|
|
686
|
+
/**
|
|
687
|
+
* Tool result states - track the lifecycle of a tool result
|
|
688
|
+
*/
|
|
689
|
+
type ToolResultState$1 = 'streaming' | 'complete' | 'error';
|
|
690
|
+
type ToolOutputState = 'output-available' | 'output-error';
|
|
691
|
+
/**
|
|
692
|
+
* JSON Schema type for defining tool input/output schemas as raw JSON Schema objects.
|
|
693
|
+
* This allows tools to be defined without schema libraries when you have JSON Schema definitions available.
|
|
694
|
+
*/
|
|
695
|
+
interface JSONSchema {
|
|
696
|
+
type?: string | Array<string>;
|
|
697
|
+
properties?: Record<string, JSONSchema>;
|
|
698
|
+
items?: JSONSchema | Array<JSONSchema>;
|
|
699
|
+
required?: Array<string>;
|
|
700
|
+
enum?: Array<unknown>;
|
|
701
|
+
const?: unknown;
|
|
702
|
+
description?: string;
|
|
703
|
+
default?: unknown;
|
|
704
|
+
$ref?: string;
|
|
705
|
+
$defs?: Record<string, JSONSchema>;
|
|
706
|
+
definitions?: Record<string, JSONSchema>;
|
|
707
|
+
allOf?: Array<JSONSchema>;
|
|
708
|
+
anyOf?: Array<JSONSchema>;
|
|
709
|
+
oneOf?: Array<JSONSchema>;
|
|
710
|
+
not?: JSONSchema;
|
|
711
|
+
if?: JSONSchema;
|
|
712
|
+
then?: JSONSchema;
|
|
713
|
+
else?: JSONSchema;
|
|
714
|
+
minimum?: number;
|
|
715
|
+
maximum?: number;
|
|
716
|
+
exclusiveMinimum?: number;
|
|
717
|
+
exclusiveMaximum?: number;
|
|
718
|
+
minLength?: number;
|
|
719
|
+
maxLength?: number;
|
|
720
|
+
pattern?: string;
|
|
721
|
+
format?: string;
|
|
722
|
+
minItems?: number;
|
|
723
|
+
maxItems?: number;
|
|
724
|
+
uniqueItems?: boolean;
|
|
725
|
+
additionalProperties?: boolean | JSONSchema;
|
|
726
|
+
additionalItems?: boolean | JSONSchema;
|
|
727
|
+
patternProperties?: Record<string, JSONSchema>;
|
|
728
|
+
propertyNames?: JSONSchema;
|
|
729
|
+
minProperties?: number;
|
|
730
|
+
maxProperties?: number;
|
|
731
|
+
title?: string;
|
|
732
|
+
examples?: Array<unknown>;
|
|
733
|
+
[key: string]: any;
|
|
734
|
+
}
|
|
735
|
+
/**
|
|
736
|
+
* Union type for schema input - can be any Standard Schema compliant validator,
|
|
737
|
+
* any Standard JSON Schema compliant schema, or a plain JSONSchema object.
|
|
738
|
+
*
|
|
739
|
+
* Standard JSON Schema compliant libraries (carry the JSON-schema converter):
|
|
740
|
+
* - Zod v4.2+ (natively supports StandardJSONSchemaV1)
|
|
741
|
+
* - ArkType v2.1.28+ (natively supports StandardJSONSchemaV1)
|
|
742
|
+
* - Valibot v1.2+ (via `toStandardJsonSchema()` from `@valibot/to-json-schema`)
|
|
743
|
+
*
|
|
744
|
+
* StandardSchemaV1 covers libraries whose published types only expose the
|
|
745
|
+
* validator surface — Zod's core `$ZodType['~standard']` is currently typed
|
|
746
|
+
* as `StandardSchemaV1.Props` even though the runtime attaches the
|
|
747
|
+
* `jsonSchema` converter, so this branch is what makes `InferSchemaType`
|
|
748
|
+
* recover the inferred type for callers using `z.ZodType<T>`.
|
|
749
|
+
*
|
|
750
|
+
* @see https://standardschema.dev/json-schema
|
|
751
|
+
*/
|
|
752
|
+
type SchemaInput = StandardJSONSchemaV1<any, any> | StandardSchemaV1$1<any, any> | JSONSchema;
|
|
753
|
+
/**
|
|
754
|
+
* Infer the TypeScript type from a schema.
|
|
755
|
+
* For Standard JSON Schema compliant schemas, extracts the input type.
|
|
756
|
+
* For Standard Schema validators (e.g. Zod's `~standard` surface), extracts
|
|
757
|
+
* the input type from the `StandardSchemaV1` shape.
|
|
758
|
+
* For plain JSONSchema, returns `unknown` since we can't infer types from
|
|
759
|
+
* JSON Schema at compile time.
|
|
760
|
+
*/
|
|
761
|
+
type InferSchemaType<T> = T extends StandardJSONSchemaV1<infer TInput, unknown> ? TInput : T extends StandardSchemaV1$1<infer TInput, unknown> ? TInput : unknown;
|
|
762
|
+
interface ToolCall<TMetadata = unknown> {
|
|
763
|
+
id: string;
|
|
764
|
+
type: 'function';
|
|
765
|
+
function: {
|
|
766
|
+
name: string;
|
|
767
|
+
arguments: string;
|
|
768
|
+
};
|
|
769
|
+
/** Provider-specific metadata to carry through the tool call lifecycle.
|
|
770
|
+
* Typed per-adapter via `TToolCallMetadata`. For example,
|
|
771
|
+
* `@tanstack/ai-gemini` sets this to `{ thoughtSignature?: string }`. */
|
|
772
|
+
metadata?: TMetadata;
|
|
773
|
+
}
|
|
774
|
+
/**
|
|
775
|
+
* Source specification for inline data content (base64).
|
|
776
|
+
* Requires a mimeType to ensure providers receive proper content type information.
|
|
777
|
+
*/
|
|
778
|
+
interface ContentPartDataSource {
|
|
779
|
+
/**
|
|
780
|
+
* Indicates this is inline data content.
|
|
781
|
+
*/
|
|
782
|
+
type: 'data';
|
|
783
|
+
/**
|
|
784
|
+
* The base64-encoded content value.
|
|
785
|
+
*/
|
|
786
|
+
value: string;
|
|
787
|
+
/**
|
|
788
|
+
* The MIME type of the content (e.g., 'image/png', 'audio/wav').
|
|
789
|
+
* Required for data sources to ensure proper handling by providers.
|
|
790
|
+
*/
|
|
791
|
+
mimeType: string;
|
|
792
|
+
}
|
|
793
|
+
/**
|
|
794
|
+
* Source specification for URL-based content.
|
|
795
|
+
* mimeType is optional as it can often be inferred from the URL or response headers.
|
|
796
|
+
*/
|
|
797
|
+
interface ContentPartUrlSource {
|
|
798
|
+
/**
|
|
799
|
+
* Indicates this is URL-referenced content.
|
|
800
|
+
*/
|
|
801
|
+
type: 'url';
|
|
802
|
+
/**
|
|
803
|
+
* HTTP(S) URL or data URI pointing to the content.
|
|
804
|
+
*/
|
|
805
|
+
value: string;
|
|
806
|
+
/**
|
|
807
|
+
* Optional MIME type hint for cases where providers can't infer it from the URL.
|
|
808
|
+
*/
|
|
809
|
+
mimeType?: string;
|
|
810
|
+
}
|
|
811
|
+
/**
|
|
812
|
+
* Source specification for multimodal content.
|
|
813
|
+
* Discriminated union supporting both inline data (base64) and URL-based content.
|
|
814
|
+
* - For 'data' sources: mimeType is required
|
|
815
|
+
* - For 'url' sources: mimeType is optional
|
|
816
|
+
*/
|
|
817
|
+
type ContentPartSource = ContentPartDataSource | ContentPartUrlSource;
|
|
818
|
+
/**
|
|
819
|
+
* Image content part for multimodal messages.
|
|
820
|
+
* @template TMetadata - Provider-specific metadata type (e.g., OpenAI's detail level)
|
|
821
|
+
*/
|
|
822
|
+
interface ImagePart<TMetadata = unknown> {
|
|
823
|
+
type: 'image';
|
|
824
|
+
/** Source of the image content */
|
|
825
|
+
source: ContentPartSource;
|
|
826
|
+
/** Provider-specific metadata (e.g., OpenAI's detail: 'auto' | 'low' | 'high') */
|
|
827
|
+
metadata?: TMetadata;
|
|
828
|
+
}
|
|
829
|
+
/**
|
|
830
|
+
* Audio content part for multimodal messages.
|
|
831
|
+
* @template TMetadata - Provider-specific metadata type
|
|
832
|
+
*/
|
|
833
|
+
interface AudioPart<TMetadata = unknown> {
|
|
834
|
+
type: 'audio';
|
|
835
|
+
/** Source of the audio content */
|
|
836
|
+
source: ContentPartSource;
|
|
837
|
+
/** Provider-specific metadata (e.g., format, sample rate) */
|
|
838
|
+
metadata?: TMetadata;
|
|
839
|
+
}
|
|
840
|
+
/**
|
|
841
|
+
* Video content part for multimodal messages.
|
|
842
|
+
* @template TMetadata - Provider-specific metadata type
|
|
843
|
+
*/
|
|
844
|
+
interface VideoPart<TMetadata = unknown> {
|
|
845
|
+
type: 'video';
|
|
846
|
+
/** Source of the video content */
|
|
847
|
+
source: ContentPartSource;
|
|
848
|
+
/** Provider-specific metadata (e.g., duration, resolution) */
|
|
849
|
+
metadata?: TMetadata;
|
|
850
|
+
}
|
|
851
|
+
/**
|
|
852
|
+
* Document content part for multimodal messages (e.g., PDFs).
|
|
853
|
+
* @template TMetadata - Provider-specific metadata type (e.g., Anthropic's media_type)
|
|
854
|
+
*/
|
|
855
|
+
interface DocumentPart<TMetadata = unknown> {
|
|
856
|
+
type: 'document';
|
|
857
|
+
/** Source of the document content */
|
|
858
|
+
source: ContentPartSource;
|
|
859
|
+
/** Provider-specific metadata (e.g., media_type for PDFs) */
|
|
860
|
+
metadata?: TMetadata;
|
|
861
|
+
}
|
|
862
|
+
/**
|
|
863
|
+
* Union type for all multimodal content parts.
|
|
864
|
+
* @template TImageMeta - Provider-specific image metadata type
|
|
865
|
+
* @template TAudioMeta - Provider-specific audio metadata type
|
|
866
|
+
* @template TVideoMeta - Provider-specific video metadata type
|
|
867
|
+
* @template TDocumentMeta - Provider-specific document metadata type
|
|
868
|
+
*/
|
|
869
|
+
type ContentPart<TTextMeta = unknown, TImageMeta = unknown, TAudioMeta = unknown, TVideoMeta = unknown, TDocumentMeta = unknown> = TextPart$1<TTextMeta> | ImagePart<TImageMeta> | AudioPart<TAudioMeta> | VideoPart<TVideoMeta> | DocumentPart<TDocumentMeta>;
|
|
870
|
+
interface ModelMessage<TContent extends string | null | Array<ContentPart> = string | null | Array<ContentPart>> {
|
|
871
|
+
role: 'user' | 'assistant' | 'tool';
|
|
872
|
+
content: TContent;
|
|
873
|
+
name?: string;
|
|
874
|
+
toolCalls?: Array<ToolCall>;
|
|
875
|
+
toolCallId?: string;
|
|
876
|
+
thinking?: Array<{
|
|
877
|
+
content: string;
|
|
878
|
+
signature?: string;
|
|
879
|
+
}>;
|
|
880
|
+
/**
|
|
881
|
+
* Completed structured output represented by this assistant message.
|
|
882
|
+
* `content` remains the provider-facing JSON text; this field preserves the
|
|
883
|
+
* typed UI part across persistence and message conversion.
|
|
884
|
+
*/
|
|
885
|
+
structuredOutput?: StructuredOutputPart;
|
|
886
|
+
/**
|
|
887
|
+
* Optional stable message id. Providers ignore it; it exists so a persisted
|
|
888
|
+
* transcript can retain the streaming `messageId` and survive the
|
|
889
|
+
* persist → hydrate round-trip. When present, `modelMessagesToUIMessages`
|
|
890
|
+
* reuses it instead of generating a fresh id, so a hydrated message keeps the
|
|
891
|
+
* same identity as its live stream — which is what lets a mid-stream reload
|
|
892
|
+
* resume the SAME message bubble in place (see `@tanstack/ai-persistence`).
|
|
893
|
+
*/
|
|
894
|
+
id?: string;
|
|
895
|
+
/**
|
|
896
|
+
* Optional message creation timestamp. When present, message converters
|
|
897
|
+
* preserve it across persist → hydrate round-trips.
|
|
898
|
+
*/
|
|
899
|
+
createdAt?: Date;
|
|
900
|
+
}
|
|
901
|
+
/**
|
|
902
|
+
* Message parts - building blocks of UIMessage
|
|
903
|
+
*/
|
|
904
|
+
interface TextPart$1<TMetadata = unknown> {
|
|
905
|
+
type: 'text';
|
|
906
|
+
content: string;
|
|
907
|
+
metadata?: TMetadata;
|
|
908
|
+
}
|
|
909
|
+
interface ToolCallPart$2<TMetadata = unknown> {
|
|
910
|
+
type: 'tool-call';
|
|
911
|
+
id: string;
|
|
912
|
+
name: string;
|
|
913
|
+
arguments: string;
|
|
914
|
+
/**
|
|
915
|
+
* Parsed tool input. Set from the parsed arguments once they are complete
|
|
916
|
+
* (`state: 'input-complete'` and later). `undefined` while the raw
|
|
917
|
+
* `arguments` string is still streaming, and may stay `undefined` for a call
|
|
918
|
+
* that terminates in an error state — the raw `arguments` string is always
|
|
919
|
+
* available as a fallback. Typed per-tool on the client `ToolCallPart` (see
|
|
920
|
+
* `@tanstack/ai-client`); `unknown` on this base type.
|
|
921
|
+
*/
|
|
922
|
+
input?: unknown;
|
|
923
|
+
state: ToolCallState$1;
|
|
924
|
+
/** Approval metadata if tool requires user approval */
|
|
925
|
+
approval?: {
|
|
926
|
+
id: string;
|
|
927
|
+
needsApproval: boolean;
|
|
928
|
+
approved?: boolean;
|
|
929
|
+
};
|
|
930
|
+
/** Tool execution output (for client tools or after approval) */
|
|
931
|
+
output?: any;
|
|
932
|
+
/** Provider-specific metadata that round-trips with the tool call.
|
|
933
|
+
* Typed per-adapter via `TToolCallMetadata`. May follow the
|
|
934
|
+
* {@link ProviderExecutedToolMetadata} convention to mark provider-executed
|
|
935
|
+
* server tools (e.g. Anthropic `web_search`). */
|
|
936
|
+
metadata?: TMetadata;
|
|
937
|
+
}
|
|
938
|
+
interface ToolResultPart$1 {
|
|
939
|
+
type: 'tool-result';
|
|
940
|
+
toolCallId: string;
|
|
941
|
+
content: string | Array<ContentPart>;
|
|
942
|
+
state: ToolResultState$1;
|
|
943
|
+
error?: string;
|
|
944
|
+
}
|
|
945
|
+
interface ThinkingPart$1 {
|
|
946
|
+
type: 'thinking';
|
|
947
|
+
content: string;
|
|
948
|
+
stepId?: string;
|
|
949
|
+
signature?: string;
|
|
950
|
+
}
|
|
951
|
+
/**
|
|
952
|
+
* Recursive `Partial` — every nested field becomes optional. Used as the
|
|
953
|
+
* `partial` type on a streaming structured-output part since the progressive
|
|
954
|
+
* JSON parse hands back objects whose fields are only filled in as bytes
|
|
955
|
+
* arrive. Defaulted in `DeepPartial<unknown>` → `unknown` so untyped parts
|
|
956
|
+
* keep their existing shape.
|
|
957
|
+
*/
|
|
958
|
+
type DeepPartial<T> = T extends ReadonlyArray<infer U> ? Array<DeepPartial<U>> : T extends object ? { [K in keyof T]?: DeepPartial<T[K]> } : T;
|
|
959
|
+
/**
|
|
960
|
+
* StructuredOutputPart — a typed structured response attached to the assistant
|
|
961
|
+
* message that produced it. Generic over the schema-inferred data type so
|
|
962
|
+
* consumers can thread `useChat({ outputSchema })`'s schema all the way down
|
|
963
|
+
* to `messages[i].parts[j].data`. Defaults to `unknown` so untyped consumers
|
|
964
|
+
* (e.g. internal codepaths that don't know about TSchema) keep working.
|
|
965
|
+
*/
|
|
966
|
+
interface StructuredOutputPart<TData = unknown> {
|
|
967
|
+
type: 'structured-output';
|
|
968
|
+
status: 'streaming' | 'complete' | 'error';
|
|
969
|
+
/** Progressive parse of `raw` via parsePartialJSON — populated while streaming and after complete. */
|
|
970
|
+
partial?: DeepPartial<TData>;
|
|
971
|
+
/** Validated final object — only set when `status === 'complete'`. */
|
|
972
|
+
data?: TData;
|
|
973
|
+
/** Accumulating JSON buffer. Source of truth for wire round-trip. */
|
|
974
|
+
raw: string;
|
|
975
|
+
/** Optional chain-of-thought surfaced by reasoning models alongside the structured output. */
|
|
976
|
+
reasoning?: string;
|
|
977
|
+
/** Populated when `status === 'error'`. */
|
|
978
|
+
errorMessage?: string;
|
|
979
|
+
}
|
|
980
|
+
interface UIResourcePart {
|
|
981
|
+
type: 'ui-resource';
|
|
982
|
+
/** The ui:// resource object in MCP-native shape — fed straight to the renderer. */
|
|
983
|
+
resource: {
|
|
984
|
+
uri: string;
|
|
985
|
+
mimeType: string;
|
|
986
|
+
text?: string;
|
|
987
|
+
blob?: string;
|
|
988
|
+
};
|
|
989
|
+
/** Pool prefix / config key — routes interactive calls to the right MCP server. */
|
|
990
|
+
serverId?: string;
|
|
991
|
+
/** Links the widget to the originating tool call — correlates it with the
|
|
992
|
+
* sibling ToolCallPart/ToolResultPart in the same message. */
|
|
993
|
+
toolCallId: string;
|
|
994
|
+
/** Server-native (unprefixed) MCP tool name whose UI this resource renders.
|
|
995
|
+
* Required by the renderer (`@mcp-ui/client`'s `AppRenderer` `toolName` prop). */
|
|
996
|
+
toolName: string;
|
|
997
|
+
/** Reserved for future passthrough of the resource/tool `_meta.ui` (e.g. frame-size hints).
|
|
998
|
+
* Currently always `undefined` — nothing populates this field yet. */
|
|
999
|
+
meta?: Record<string, unknown>;
|
|
1000
|
+
}
|
|
1001
|
+
type MessagePart$1<TData = unknown> = TextPart$1 | ImagePart | AudioPart | VideoPart | DocumentPart | ToolCallPart$2 | ToolResultPart$1 | ThinkingPart$1 | StructuredOutputPart<TData> | UIResourcePart;
|
|
1002
|
+
/**
|
|
1003
|
+
* Shape of `metadata.tanstack` on run events.
|
|
1004
|
+
*/
|
|
1005
|
+
interface TanStackRunMetadata {
|
|
1006
|
+
model?: string;
|
|
1007
|
+
finishReason?: 'stop' | 'length' | 'content_filter' | 'tool_calls' | null;
|
|
1008
|
+
/** TokenUsage fields that have no AG-UI `usage[]` equivalent. */
|
|
1009
|
+
usage?: TokenUsageLeftover;
|
|
1010
|
+
interruptErrors?: ReadonlyArray<InterruptSubmissionError>;
|
|
1011
|
+
threadId?: string;
|
|
1012
|
+
runId?: string;
|
|
1013
|
+
sessionId?: string;
|
|
1014
|
+
index?: number;
|
|
1015
|
+
state?: ToolOutputState;
|
|
1016
|
+
/** Parsed `TOOL_CALL_END` input. Spec `TOOL_CALL_END` has no top-level `input`. */
|
|
1017
|
+
input?: unknown;
|
|
1018
|
+
}
|
|
1019
|
+
/**
|
|
1020
|
+
* UIMessage - Domain-specific message format optimized for building chat UIs
|
|
1021
|
+
* Contains parts that can be text, tool calls, or tool results. Generic over
|
|
1022
|
+
* the structured-output data type so `useChat({ outputSchema })`'s schema
|
|
1023
|
+
* narrows `parts.find(p => p.type === 'structured-output').data` on the
|
|
1024
|
+
* consumer side without manual casts.
|
|
1025
|
+
*/
|
|
1026
|
+
interface UIMessage$1<TData = unknown> {
|
|
1027
|
+
id: string;
|
|
1028
|
+
role: 'system' | 'user' | 'assistant';
|
|
1029
|
+
parts: Array<MessagePart$1<TData>>;
|
|
1030
|
+
createdAt?: Date;
|
|
1031
|
+
/**
|
|
1032
|
+
* Optional AG-UI metadata bag. TanStack writes the `tanstack` key.
|
|
1033
|
+
* User keys stay at the top.
|
|
1034
|
+
*/
|
|
1035
|
+
metadata?: Record<string, any>;
|
|
1036
|
+
}
|
|
1037
|
+
type IsUnknown$1<T> = unknown extends T ? [T] extends [unknown] ? true : false : false;
|
|
1038
|
+
type RuntimeContextField<TContext> = IsUnknown$1<TContext> extends true ? {
|
|
1039
|
+
/**
|
|
1040
|
+
* Runtime context provided by the caller.
|
|
1041
|
+
*
|
|
1042
|
+
* This is request-local application state for tool and middleware
|
|
1043
|
+
* implementations, not the AG-UI `Context[]` protocol field.
|
|
1044
|
+
*/
|
|
1045
|
+
context?: TContext;
|
|
1046
|
+
} : {
|
|
1047
|
+
/**
|
|
1048
|
+
* Runtime context provided by the caller.
|
|
1049
|
+
*
|
|
1050
|
+
* This is request-local application state for tool and middleware
|
|
1051
|
+
* implementations, not the AG-UI `Context[]` protocol field.
|
|
1052
|
+
*/
|
|
1053
|
+
context: TContext;
|
|
1054
|
+
};
|
|
1055
|
+
/**
|
|
1056
|
+
* Context passed to tool execute functions, providing capabilities like
|
|
1057
|
+
* emitting custom events during execution.
|
|
1058
|
+
*/
|
|
1059
|
+
type ToolExecutionContext<TContext = unknown> = RuntimeContextField<TContext> & {
|
|
1060
|
+
/** The ID of the tool call being executed */toolCallId?: string;
|
|
1061
|
+
/**
|
|
1062
|
+
* Abort signal for the current chat run. Aborts when the run's
|
|
1063
|
+
* `abortController` fires (or middleware aborts). Long-running tools —
|
|
1064
|
+
* e.g. MCP `callTool` — should forward this to cancel in-flight work.
|
|
1065
|
+
*/
|
|
1066
|
+
abortSignal?: AbortSignal;
|
|
1067
|
+
/**
|
|
1068
|
+
* Emit a custom event during tool execution.
|
|
1069
|
+
* Events are streamed to the client in real-time as AG-UI CUSTOM events.
|
|
1070
|
+
*
|
|
1071
|
+
* @param eventName - Name of the custom event
|
|
1072
|
+
* @param value - Event payload value
|
|
1073
|
+
*
|
|
1074
|
+
* @example
|
|
1075
|
+
* ```ts
|
|
1076
|
+
* const tool = toolDefinition({ ... }).server(async (args, context) => {
|
|
1077
|
+
* context?.emitCustomEvent('progress', { step: 1, total: 3 })
|
|
1078
|
+
* // ... do work ...
|
|
1079
|
+
* context?.emitCustomEvent('progress', { step: 2, total: 3 })
|
|
1080
|
+
* // ... do more work ...
|
|
1081
|
+
* return result
|
|
1082
|
+
* })
|
|
1083
|
+
* ```
|
|
1084
|
+
*/
|
|
1085
|
+
emitCustomEvent: (eventName: string, value: Record<string, any>) => void;
|
|
1086
|
+
};
|
|
1087
|
+
type ToolExecuteFunction<TInput extends SchemaInput | undefined = SchemaInput, TOutput extends SchemaInput | undefined = SchemaInput, TContext = unknown> = undefined extends TContext ? (args: InferSchemaType<TInput>, context?: ToolExecutionContext<TContext>) => Promise<InferSchemaType<TOutput>> | InferSchemaType<TOutput> : (args: InferSchemaType<TInput>, context: ToolExecutionContext<TContext>) => Promise<InferSchemaType<TOutput>> | InferSchemaType<TOutput>;
|
|
1088
|
+
/**
|
|
1089
|
+
* Tool/Function definition for function calling.
|
|
1090
|
+
*
|
|
1091
|
+
* Tools allow the model to interact with external systems, APIs, or perform computations.
|
|
1092
|
+
* The model will decide when to call tools based on the user's request and the tool descriptions.
|
|
1093
|
+
*
|
|
1094
|
+
* Tools can use any Standard JSON Schema compliant library (Zod, ArkType, Valibot, etc.)
|
|
1095
|
+
* or plain JSON Schema objects for runtime validation and type safety.
|
|
1096
|
+
*
|
|
1097
|
+
* @see https://platform.openai.com/docs/guides/function-calling
|
|
1098
|
+
* @see https://docs.anthropic.com/claude/docs/tool-use
|
|
1099
|
+
* @see https://standardschema.dev/json-schema
|
|
1100
|
+
*/
|
|
1101
|
+
interface Tool$1<TInput extends SchemaInput | undefined = SchemaInput, TOutput extends SchemaInput | undefined = SchemaInput, TName extends string = string, TContext = unknown> {
|
|
1102
|
+
/**
|
|
1103
|
+
* Unique name of the tool (used by the model to call it).
|
|
1104
|
+
*
|
|
1105
|
+
* Should be descriptive and follow naming conventions (e.g., snake_case or camelCase).
|
|
1106
|
+
* Must be unique within the tools array.
|
|
1107
|
+
*
|
|
1108
|
+
* @example "get_weather", "search_database", "sendEmail"
|
|
1109
|
+
*/
|
|
1110
|
+
name: TName;
|
|
1111
|
+
/**
|
|
1112
|
+
* Clear description of what the tool does.
|
|
1113
|
+
*
|
|
1114
|
+
* This is crucial - the model uses this to decide when to call the tool.
|
|
1115
|
+
* Be specific about what the tool does, what parameters it needs, and what it returns.
|
|
1116
|
+
*
|
|
1117
|
+
* @example "Get the current weather in a given location. Returns temperature, conditions, and forecast."
|
|
1118
|
+
*/
|
|
1119
|
+
description: string;
|
|
1120
|
+
/**
|
|
1121
|
+
* Schema describing the tool's input parameters.
|
|
1122
|
+
*
|
|
1123
|
+
* Can be any Standard JSON Schema compliant schema (Zod, ArkType, Valibot, etc.) or a plain JSON Schema object.
|
|
1124
|
+
* Defines the structure and types of arguments the tool accepts.
|
|
1125
|
+
* The model will generate arguments matching this schema.
|
|
1126
|
+
* Standard JSON Schema compliant schemas are converted to JSON Schema for LLM providers.
|
|
1127
|
+
*
|
|
1128
|
+
* @see https://standardschema.dev/json-schema
|
|
1129
|
+
* @see https://json-schema.org/
|
|
1130
|
+
*
|
|
1131
|
+
* @example
|
|
1132
|
+
* // Using Zod v4+ schema (natively supports Standard JSON Schema)
|
|
1133
|
+
* import { z } from 'zod';
|
|
1134
|
+
* z.object({
|
|
1135
|
+
* location: z.string().describe("City name or coordinates"),
|
|
1136
|
+
* unit: z.enum(["celsius", "fahrenheit"]).optional()
|
|
1137
|
+
* })
|
|
1138
|
+
*
|
|
1139
|
+
* @example
|
|
1140
|
+
* // Using ArkType (natively supports Standard JSON Schema)
|
|
1141
|
+
* import { type } from 'arktype';
|
|
1142
|
+
* type({
|
|
1143
|
+
* location: 'string',
|
|
1144
|
+
* unit: "'celsius' | 'fahrenheit'"
|
|
1145
|
+
* })
|
|
1146
|
+
*
|
|
1147
|
+
* @example
|
|
1148
|
+
* // Using plain JSON Schema
|
|
1149
|
+
* {
|
|
1150
|
+
* type: 'object',
|
|
1151
|
+
* properties: {
|
|
1152
|
+
* location: { type: 'string', description: 'City name or coordinates' },
|
|
1153
|
+
* unit: { type: 'string', enum: ['celsius', 'fahrenheit'] }
|
|
1154
|
+
* },
|
|
1155
|
+
* required: ['location']
|
|
1156
|
+
* }
|
|
1157
|
+
*/
|
|
1158
|
+
inputSchema?: TInput;
|
|
1159
|
+
/**
|
|
1160
|
+
* Optional schema for validating tool output.
|
|
1161
|
+
*
|
|
1162
|
+
* Can be any Standard JSON Schema compliant schema or a plain JSON Schema object.
|
|
1163
|
+
* If provided with a Standard Schema compliant schema, tool results will be validated
|
|
1164
|
+
* against this schema before being sent back to the model. This catches bugs in tool
|
|
1165
|
+
* implementations and ensures consistent output formatting.
|
|
1166
|
+
*
|
|
1167
|
+
* Note: This is client-side validation only - not sent to LLM providers.
|
|
1168
|
+
* Note: Plain JSON Schema output validation is not performed at runtime.
|
|
1169
|
+
*
|
|
1170
|
+
* @example
|
|
1171
|
+
* // Using Zod
|
|
1172
|
+
* z.object({
|
|
1173
|
+
* temperature: z.number(),
|
|
1174
|
+
* conditions: z.string(),
|
|
1175
|
+
* forecast: z.array(z.string()).optional()
|
|
1176
|
+
* })
|
|
1177
|
+
*/
|
|
1178
|
+
outputSchema?: TOutput;
|
|
1179
|
+
/**
|
|
1180
|
+
* Optional function to execute when the model calls this tool.
|
|
1181
|
+
*
|
|
1182
|
+
* If provided, the SDK will automatically execute the function with the model's arguments
|
|
1183
|
+
* and feed the result back to the model. This enables autonomous tool use loops.
|
|
1184
|
+
*
|
|
1185
|
+
* Can return any value - will be automatically stringified if needed.
|
|
1186
|
+
*
|
|
1187
|
+
* @param args - The arguments parsed from the model's tool call (validated against inputSchema)
|
|
1188
|
+
* @returns Result to send back to the model (validated against outputSchema if provided)
|
|
1189
|
+
*
|
|
1190
|
+
* @example
|
|
1191
|
+
* execute: async (args) => {
|
|
1192
|
+
* const weather = await fetchWeather(args.location);
|
|
1193
|
+
* return weather; // Can return object or string
|
|
1194
|
+
* }
|
|
1195
|
+
*/
|
|
1196
|
+
execute?: ToolExecuteFunction<TInput, TOutput, TContext> | undefined;
|
|
1197
|
+
/** If true, tool execution requires user approval before running. Works with both server and client tools. */
|
|
1198
|
+
needsApproval?: boolean;
|
|
1199
|
+
/** If true, this tool is lazy and will only be sent to the LLM after being discovered via the lazy tool discovery mechanism. Works with both chat() (the synthetic discovery tool) and Code Mode (kept out of the system prompt and revealed via discover_tools). */
|
|
1200
|
+
lazy?: boolean;
|
|
1201
|
+
/** Additional metadata for adapters or custom extensions */
|
|
1202
|
+
metadata?: Record<string, any> | undefined;
|
|
1203
|
+
}
|
|
1204
|
+
/**
|
|
1205
|
+
* Emitted when a run starts.
|
|
1206
|
+
* This is the first event in any streaming response.
|
|
1207
|
+
*
|
|
1208
|
+
* @ag-ui/core provides: `threadId`, `runId`, `parentRunId?`, `input?`
|
|
1209
|
+
*/
|
|
1210
|
+
interface RunStartedEvent extends RunStartedEvent$1 {}
|
|
1211
|
+
type Interrupt = Interrupt$1;
|
|
1212
|
+
type RunAgentResumeItem = ResumeEntry & {
|
|
1213
|
+
/** AG-UI resume metadata. First-party generic requests ride here. */metadata?: Record<string, unknown>;
|
|
1214
|
+
};
|
|
1215
|
+
/**
|
|
1216
|
+
* Emitted when a run completes successfully.
|
|
1217
|
+
*
|
|
1218
|
+
* @ag-ui/core provides: `threadId`, `runId`, `result?`, `outcome?`
|
|
1219
|
+
* Spec `usage[]` is provider/model token counts. TanStack leftovers live in
|
|
1220
|
+
* `metadata.tanstack`.
|
|
1221
|
+
*/
|
|
1222
|
+
interface RunFinishedEvent extends Pick<RunFinishedEvent$1, 'threadId' | 'runId' | 'result' | 'outcome' | 'timestamp' | 'rawEvent'> {
|
|
1223
|
+
type: EventType.RUN_FINISHED;
|
|
1224
|
+
usage?: Array<SpecTokenUsage> | TokenUsage;
|
|
1225
|
+
/** Restored on the client from `metadata.tanstack`. */
|
|
1226
|
+
model?: string;
|
|
1227
|
+
/** Restored on the client from `metadata.tanstack`. */
|
|
1228
|
+
finishReason?: 'stop' | 'length' | 'content_filter' | 'tool_calls' | null;
|
|
1229
|
+
metadata?: {
|
|
1230
|
+
tanstack?: TanStackRunMetadata;
|
|
1231
|
+
} & Record<string, any>;
|
|
1232
|
+
}
|
|
1233
|
+
/**
|
|
1234
|
+
* Emitted when an error occurs during a run.
|
|
1235
|
+
*
|
|
1236
|
+
* @ag-ui/core provides: `message`, `code?`
|
|
1237
|
+
* Spec `usage[]` is provider/model token counts. Interrupt errors live in
|
|
1238
|
+
* `metadata.tanstack.interruptErrors`.
|
|
1239
|
+
*/
|
|
1240
|
+
interface RunErrorEvent extends Pick<RunErrorEvent$1, 'message' | 'code' | 'timestamp' | 'rawEvent'> {
|
|
1241
|
+
type: EventType.RUN_ERROR;
|
|
1242
|
+
usage?: Array<SpecTokenUsage> | TokenUsage;
|
|
1243
|
+
/** Restored on the client from `metadata.tanstack`. */
|
|
1244
|
+
threadId?: string;
|
|
1245
|
+
/** Restored on the client from `metadata.tanstack`. */
|
|
1246
|
+
runId?: string;
|
|
1247
|
+
/** Restored on the client from `metadata.tanstack`. */
|
|
1248
|
+
model?: string;
|
|
1249
|
+
/** Nested payload kept for in-process / durability consumers. */
|
|
1250
|
+
error?: {
|
|
1251
|
+
message: string;
|
|
1252
|
+
code?: string;
|
|
1253
|
+
};
|
|
1254
|
+
metadata?: {
|
|
1255
|
+
tanstack?: TanStackRunMetadata;
|
|
1256
|
+
} & Record<string, any>;
|
|
1257
|
+
}
|
|
1258
|
+
/**
|
|
1259
|
+
* Emitted when a text message starts.
|
|
1260
|
+
*
|
|
1261
|
+
* @ag-ui/core provides: `messageId`, `role?`, `name?`
|
|
1262
|
+
*/
|
|
1263
|
+
interface TextMessageStartEvent extends TextMessageStartEvent$1 {}
|
|
1264
|
+
/**
|
|
1265
|
+
* Emitted when text content is generated (streaming tokens).
|
|
1266
|
+
*
|
|
1267
|
+
* @ag-ui/core provides: `messageId`, `delta`
|
|
1268
|
+
*/
|
|
1269
|
+
interface TextMessageContentEvent extends TextMessageContentEvent$1 {}
|
|
1270
|
+
/**
|
|
1271
|
+
* Emitted when a text message completes.
|
|
1272
|
+
*
|
|
1273
|
+
* @ag-ui/core provides: `messageId`
|
|
1274
|
+
*/
|
|
1275
|
+
interface TextMessageEndEvent extends TextMessageEndEvent$1 {}
|
|
1276
|
+
/**
|
|
1277
|
+
* Emitted when a tool call starts.
|
|
1278
|
+
*
|
|
1279
|
+
* @ag-ui/core provides: `toolCallId`, `toolCallName`, `parentMessageId?`
|
|
1280
|
+
*
|
|
1281
|
+
* Field shapes are taken from AG-UI via `Pick` (not `extends`) so Zod
|
|
1282
|
+
* `.passthrough()` index signatures do not pollute the StreamChunk
|
|
1283
|
+
* discriminated union — required for {@link KnownCustomEvent} narrowing.
|
|
1284
|
+
*/
|
|
1285
|
+
interface ToolCallStartEvent extends Pick<ToolCallStartEvent$1, 'toolCallId' | 'toolCallName' | 'parentMessageId' | 'timestamp' | 'rawEvent'> {
|
|
1286
|
+
type: 'TOOL_CALL_START';
|
|
1287
|
+
/** Alias of `toolCallName`. Kept so existing stream readers still compile. */
|
|
1288
|
+
toolName?: string;
|
|
1289
|
+
/** Provider-specific metadata to carry into the ToolCall. */
|
|
1290
|
+
metadata?: Record<string, any>;
|
|
1291
|
+
}
|
|
1292
|
+
/**
|
|
1293
|
+
* Emitted when tool call arguments are streaming.
|
|
1294
|
+
*
|
|
1295
|
+
* @ag-ui/core provides: `toolCallId`, `delta`
|
|
1296
|
+
*/
|
|
1297
|
+
interface ToolCallArgsEvent extends ToolCallArgsEvent$1 {}
|
|
1298
|
+
/**
|
|
1299
|
+
* Emitted when a tool call completes.
|
|
1300
|
+
*
|
|
1301
|
+
* @ag-ui/core provides: `toolCallId`
|
|
1302
|
+
*
|
|
1303
|
+
* Same `Pick` (not `extends`) rationale as {@link ToolCallStartEvent}.
|
|
1304
|
+
*/
|
|
1305
|
+
interface ToolCallEndEvent extends Pick<ToolCallEndEvent$1, 'toolCallId' | 'timestamp' | 'rawEvent'> {
|
|
1306
|
+
type: 'TOOL_CALL_END';
|
|
1307
|
+
/** Parsed tool arguments when the adapter already parsed them. */
|
|
1308
|
+
input?: unknown;
|
|
1309
|
+
metadata?: Record<string, any>;
|
|
1310
|
+
}
|
|
1311
|
+
/**
|
|
1312
|
+
* Emitted when a tool call result is available.
|
|
1313
|
+
*
|
|
1314
|
+
* @ag-ui/core provides: `messageId`, `toolCallId`, `content`, `role?`
|
|
1315
|
+
*/
|
|
1316
|
+
interface ToolCallResultEvent extends ToolCallResultEvent$1 {}
|
|
1317
|
+
/**
|
|
1318
|
+
* Emitted when a thinking/reasoning step starts.
|
|
1319
|
+
*
|
|
1320
|
+
* @ag-ui/core provides: `stepName`
|
|
1321
|
+
*/
|
|
1322
|
+
interface StepStartedEvent extends StepStartedEvent$1 {}
|
|
1323
|
+
/**
|
|
1324
|
+
* Emitted when a thinking/reasoning step finishes.
|
|
1325
|
+
*
|
|
1326
|
+
* @ag-ui/core provides: `stepName`
|
|
1327
|
+
*/
|
|
1328
|
+
interface StepFinishedEvent extends StepFinishedEvent$1 {}
|
|
1329
|
+
/**
|
|
1330
|
+
* Emitted to provide a snapshot of all messages in a conversation.
|
|
1331
|
+
*
|
|
1332
|
+
* Unlike StateSnapshot (which carries arbitrary application state),
|
|
1333
|
+
* MessagesSnapshot specifically delivers the conversation transcript.
|
|
1334
|
+
*
|
|
1335
|
+
* @ag-ui/core provides: `messages` (as @ag-ui/core Message[])
|
|
1336
|
+
*
|
|
1337
|
+
* Note: The `messages` field uses the @ag-ui/core Message type.
|
|
1338
|
+
* Use converters to transform to/from TanStack UIMessage format.
|
|
1339
|
+
*/
|
|
1340
|
+
interface MessagesSnapshotEvent extends MessagesSnapshotEvent$1 {}
|
|
1341
|
+
/**
|
|
1342
|
+
* Emitted to provide a full state snapshot.
|
|
1343
|
+
*
|
|
1344
|
+
* @ag-ui/core provides: `snapshot` (any)
|
|
1345
|
+
*/
|
|
1346
|
+
interface StateSnapshotEvent extends StateSnapshotEvent$1 {}
|
|
1347
|
+
/**
|
|
1348
|
+
* Emitted to provide an incremental state update.
|
|
1349
|
+
*
|
|
1350
|
+
* @ag-ui/core provides: `delta` (any[] - JSON Patch RFC 6902)
|
|
1351
|
+
*/
|
|
1352
|
+
interface StateDeltaEvent extends StateDeltaEvent$1 {}
|
|
1353
|
+
/**
|
|
1354
|
+
* Custom event for extensibility.
|
|
1355
|
+
*
|
|
1356
|
+
* @ag-ui/core provides: `name`, `value`
|
|
1357
|
+
*
|
|
1358
|
+
* Uses `Pick` (not `extends`) so the Zod passthrough index signature does not
|
|
1359
|
+
* erase discriminant property access on {@link KnownCustomEvent} unions.
|
|
1360
|
+
*/
|
|
1361
|
+
interface CustomEvent extends Pick<CustomEvent$1, 'name' | 'value' | 'timestamp' | 'rawEvent'> {
|
|
1362
|
+
type: 'CUSTOM';
|
|
1363
|
+
metadata?: Record<string, any>;
|
|
1364
|
+
}
|
|
1365
|
+
/**
|
|
1366
|
+
* Emitted when reasoning starts for a message.
|
|
1367
|
+
*
|
|
1368
|
+
* @ag-ui/core provides: `messageId`
|
|
1369
|
+
*/
|
|
1370
|
+
interface ReasoningStartEvent extends ReasoningStartEvent$1 {}
|
|
1371
|
+
/**
|
|
1372
|
+
* Emitted when a reasoning message starts.
|
|
1373
|
+
*
|
|
1374
|
+
* @ag-ui/core provides: `messageId`, `role` ("reasoning")
|
|
1375
|
+
*/
|
|
1376
|
+
interface ReasoningMessageStartEvent extends ReasoningMessageStartEvent$1 {}
|
|
1377
|
+
/**
|
|
1378
|
+
* Emitted when reasoning message content is generated.
|
|
1379
|
+
*
|
|
1380
|
+
* @ag-ui/core provides: `messageId`, `delta`
|
|
1381
|
+
*/
|
|
1382
|
+
interface ReasoningMessageContentEvent extends ReasoningMessageContentEvent$1 {}
|
|
1383
|
+
/**
|
|
1384
|
+
* Emitted when a reasoning message ends.
|
|
1385
|
+
*
|
|
1386
|
+
* @ag-ui/core provides: `messageId`
|
|
1387
|
+
*/
|
|
1388
|
+
interface ReasoningMessageEndEvent extends ReasoningMessageEndEvent$1 {}
|
|
1389
|
+
/**
|
|
1390
|
+
* Emitted when reasoning ends for a message.
|
|
1391
|
+
*
|
|
1392
|
+
* @ag-ui/core provides: `messageId`
|
|
1393
|
+
*/
|
|
1394
|
+
interface ReasoningEndEvent extends ReasoningEndEvent$1 {}
|
|
1395
|
+
/**
|
|
1396
|
+
* Emitted for encrypted reasoning values.
|
|
1397
|
+
*
|
|
1398
|
+
* @ag-ui/core provides: `subtype`, `entityId`, `encryptedValue`
|
|
1399
|
+
*/
|
|
1400
|
+
interface ReasoningEncryptedValueEvent extends ReasoningEncryptedValueEvent$1 {}
|
|
1401
|
+
/**
|
|
1402
|
+
* Union of all AG-UI events.
|
|
1403
|
+
*/
|
|
1404
|
+
type AGUIEvent = RunStartedEvent | RunFinishedEvent | RunErrorEvent | TextMessageStartEvent | TextMessageContentEvent | TextMessageEndEvent | ToolCallStartEvent | ToolCallArgsEvent | ToolCallEndEvent | ToolCallResultEvent | StepStartedEvent | StepFinishedEvent | MessagesSnapshotEvent | StateSnapshotEvent | StateDeltaEvent | CustomEvent | ReasoningStartEvent | ReasoningMessageStartEvent | ReasoningMessageContentEvent | ReasoningMessageEndEvent | ReasoningEndEvent | ReasoningEncryptedValueEvent;
|
|
1405
|
+
/**
|
|
1406
|
+
* Chunk returned by the SDK during streaming chat completions.
|
|
1407
|
+
* Uses the AG-UI protocol event format.
|
|
1408
|
+
*/
|
|
1409
|
+
type StreamChunk = AGUIEvent;
|
|
1410
|
+
//#endregion
|
|
1411
|
+
//#region node_modules/.deno/@tanstack+ai@0.49.1/node_modules/@tanstack/ai/dist/esm/activities/chat/tools/tool-definition.d.ts
|
|
1412
|
+
/**
|
|
1413
|
+
* Type-level brand key for {@link ToolApprovalCapabilityMarker}. Only ever used
|
|
1414
|
+
* in type positions, but it must stay exported: a `unique symbol` referenced by
|
|
1415
|
+
* an exported interface has to be nameable in the emitted declarations.
|
|
1416
|
+
*
|
|
1417
|
+
* @public
|
|
1418
|
+
*/
|
|
1419
|
+
declare const toolApprovalCapability: unique symbol;
|
|
1420
|
+
interface ToolApprovalCapabilityMarker<TNeedsApproval extends boolean, TApprovalSchema> {
|
|
1421
|
+
readonly [toolApprovalCapability]?: {
|
|
1422
|
+
needsApproval: TNeedsApproval;
|
|
1423
|
+
approvalSchema: TApprovalSchema;
|
|
1424
|
+
};
|
|
1425
|
+
}
|
|
1426
|
+
type ApprovalSchemaConfig = SchemaInput | {
|
|
1427
|
+
approve: SchemaInput;
|
|
1428
|
+
reject?: SchemaInput;
|
|
1429
|
+
} | {
|
|
1430
|
+
approve?: SchemaInput;
|
|
1431
|
+
reject: SchemaInput;
|
|
1432
|
+
};
|
|
1433
|
+
type ApprovalCapabilityOf<TTool> = TTool extends ToolApprovalCapabilityMarker<infer TNeeds, unknown> ? TNeeds : false;
|
|
1434
|
+
type ApprovalSchemaOf<TTool> = TTool extends ToolApprovalCapabilityMarker<boolean, infer TSchema> ? TSchema : undefined;
|
|
1435
|
+
declare const noSchema: unique symbol;
|
|
1436
|
+
type NoSchema = typeof noSchema;
|
|
1437
|
+
type InputSchemaOf<TTool> = TTool extends {
|
|
1438
|
+
inputSchema: infer TInput;
|
|
1439
|
+
} ? TInput extends undefined ? NoSchema : TInput : NoSchema;
|
|
1440
|
+
/**
|
|
1441
|
+
* Marker type for client-side tools
|
|
1442
|
+
*/
|
|
1443
|
+
interface ClientTool<TInput extends SchemaInput | undefined = undefined, TOutput extends SchemaInput | undefined = undefined, TName extends string = string, TContext = unknown, TNeedsApproval extends boolean = false, TApprovalSchema extends ApprovalSchemaConfig | undefined = undefined> extends ToolApprovalCapabilityMarker<TNeedsApproval, TApprovalSchema> {
|
|
1444
|
+
__toolSide: 'client';
|
|
1445
|
+
name: TName;
|
|
1446
|
+
description: string;
|
|
1447
|
+
inputSchema?: TInput;
|
|
1448
|
+
outputSchema?: TOutput;
|
|
1449
|
+
needsApproval?: TNeedsApproval;
|
|
1450
|
+
approvalSchema?: TApprovalSchema;
|
|
1451
|
+
lazy?: boolean;
|
|
1452
|
+
metadata?: Record<string, unknown>;
|
|
1453
|
+
execute?: ToolExecuteFunction<TInput, TOutput, TContext>;
|
|
1454
|
+
}
|
|
1455
|
+
/**
|
|
1456
|
+
* Tool definition that can be used directly or instantiated for server/client
|
|
1457
|
+
*/
|
|
1458
|
+
interface ToolDefinitionInstance<TInput extends SchemaInput | undefined = undefined, TOutput extends SchemaInput | undefined = undefined, TName extends string = string, TContext = unknown, TNeedsApproval extends boolean = false, TApprovalSchema extends ApprovalSchemaConfig | undefined = undefined> extends Tool$1<TInput, TOutput, TName, TContext> {
|
|
1459
|
+
__toolSide: 'definition';
|
|
1460
|
+
inputSchema: TInput;
|
|
1461
|
+
outputSchema: TOutput;
|
|
1462
|
+
needsApproval?: TNeedsApproval;
|
|
1463
|
+
approvalSchema: TApprovalSchema;
|
|
1464
|
+
readonly [toolApprovalCapability]?: {
|
|
1465
|
+
needsApproval: TNeedsApproval;
|
|
1466
|
+
approvalSchema: TApprovalSchema;
|
|
1467
|
+
};
|
|
1468
|
+
}
|
|
1469
|
+
/**
|
|
1470
|
+
* Union type for any kind of client-side tool (client tool or definition)
|
|
1471
|
+
*/
|
|
1472
|
+
type AnyClientTool = (Omit<ClientTool<any, any, string, any, boolean, any>, 'execute'> & {
|
|
1473
|
+
execute?: ((args: any, context?: any) => any) | undefined;
|
|
1474
|
+
}) | (Omit<ToolDefinitionInstance<any, any, string, any, boolean, any>, 'execute'> & {
|
|
1475
|
+
execute?: ((args: any, context?: any) => any) | undefined;
|
|
1476
|
+
});
|
|
1477
|
+
/**
|
|
1478
|
+
* Extract the input type from a tool (inferred from Standard JSON Schema, or `unknown` for plain JSONSchema)
|
|
1479
|
+
*/
|
|
1480
|
+
type InferToolInput<T> = T extends {
|
|
1481
|
+
inputSchema?: infer TInput;
|
|
1482
|
+
} ? TInput extends JSONSchema ? unknown : InferSchemaType<TInput> : unknown;
|
|
1483
|
+
/**
|
|
1484
|
+
* Extract the output type from a tool (inferred from Standard JSON Schema, or `unknown` for plain JSONSchema)
|
|
1485
|
+
*/
|
|
1486
|
+
type InferToolOutput<T> = T extends {
|
|
1487
|
+
outputSchema?: infer TOutput;
|
|
1488
|
+
} ? TOutput extends StandardJSONSchemaV1<any, any> ? InferSchemaType<TOutput> : TOutput extends StandardSchemaV1$1<any, any> ? InferSchemaType<TOutput> : TOutput extends JSONSchema ? unknown : InferSchemaType<TOutput> : unknown;
|
|
1489
|
+
//#endregion
|
|
1490
|
+
//#region node_modules/.deno/@tanstack+ai@0.49.1/node_modules/@tanstack/ai/dist/esm/activities/chat/stream/types.d.ts
|
|
1491
|
+
/**
|
|
1492
|
+
* Strategy for determining when to emit text updates
|
|
1493
|
+
*/
|
|
1494
|
+
interface ChunkStrategy {
|
|
1495
|
+
/**
|
|
1496
|
+
* Called for each text chunk received
|
|
1497
|
+
* @param chunk - The new chunk of text (delta)
|
|
1498
|
+
* @param accumulated - All text accumulated so far
|
|
1499
|
+
* @returns true if an update should be emitted now
|
|
1500
|
+
*/
|
|
1501
|
+
shouldEmit: (chunk: string, accumulated: string) => boolean;
|
|
1502
|
+
/**
|
|
1503
|
+
* Optional: Reset strategy state (called when streaming starts)
|
|
1504
|
+
*/
|
|
1505
|
+
reset?: () => void;
|
|
1506
|
+
}
|
|
1507
|
+
//#endregion
|
|
1508
|
+
//#region node_modules/.deno/@tanstack+ai@0.49.1/node_modules/@tanstack/ai/dist/esm/interrupt-definition.d.ts
|
|
1509
|
+
type PortableSchema = StandardJSONSchemaV1<any, any> | StandardSchemaV1$1<any, any>;
|
|
1510
|
+
type InterruptInput<TPayloadSchema extends PortableSchema | undefined, TPayload = unknown> = {
|
|
1511
|
+
key: string;
|
|
1512
|
+
reason: string;
|
|
1513
|
+
message: string;
|
|
1514
|
+
expiresAt?: string;
|
|
1515
|
+
} & ([TPayloadSchema] extends [undefined] ? {} : {
|
|
1516
|
+
payload?: TPayload;
|
|
1517
|
+
});
|
|
1518
|
+
type GenericInterruptRequestBase<TDefinition extends InterruptDefinition<any, any, any, any>> = {
|
|
1519
|
+
readonly definition: TDefinition;
|
|
1520
|
+
readonly key: string;
|
|
1521
|
+
readonly reason: string;
|
|
1522
|
+
readonly message: string;
|
|
1523
|
+
readonly expiresAt?: string;
|
|
1524
|
+
};
|
|
1525
|
+
type GenericInterruptRequestFor<TDefinition extends InterruptDefinition<any, any, any, any>, TPayloadSchema extends PortableSchema | undefined, TPayload> = GenericInterruptRequestBase<TDefinition> & ([TPayloadSchema] extends [undefined] ? {} : {
|
|
1526
|
+
readonly payload: TPayload | undefined;
|
|
1527
|
+
});
|
|
1528
|
+
type InterruptInputKey = 'key' | 'reason' | 'message' | 'expiresAt' | 'payload';
|
|
1529
|
+
type RejectUnexpectedInputKeys<TInput> = Exclude<keyof TInput, InterruptInputKey> extends never ? unknown : { [K in Exclude<keyof TInput, InterruptInputKey>]: never };
|
|
1530
|
+
type RejectUnexpectedPayload<TInput> = 'payload' extends keyof TInput ? {
|
|
1531
|
+
payload: never;
|
|
1532
|
+
} : unknown;
|
|
1533
|
+
type ValidInterruptInput<TInput, TPayloadSchema extends PortableSchema | undefined, TPayload = unknown> = TInput extends InterruptInput<TPayloadSchema, TPayload> ? RejectUnexpectedInputKeys<TInput> & ([TPayloadSchema] extends [undefined] ? RejectUnexpectedPayload<TInput> : unknown) : never;
|
|
1534
|
+
/**
|
|
1535
|
+
* Extracting a class method preserves the intentional bivariant assignment
|
|
1536
|
+
* behavior of the public `interrupt` callback without exposing a method
|
|
1537
|
+
* signature in an interface.
|
|
1538
|
+
*/
|
|
1539
|
+
declare abstract class InterruptRequestMethodSignature<TId extends string, TPayloadSchema extends PortableSchema | undefined, TResponseSchema extends PortableSchema | undefined, TPayload, TPayloadInput> {
|
|
1540
|
+
abstract call<TInput>(input: TInput & ValidInterruptInput<TInput, TPayloadSchema, TPayloadInput>): GenericInterruptRequestFor<InterruptDefinition<TId, TPayloadSchema, TResponseSchema, TPayload, TPayloadInput>, TPayloadSchema, TPayload>;
|
|
1541
|
+
}
|
|
1542
|
+
type InterruptRequestMethod<TId extends string, TPayloadSchema extends PortableSchema | undefined, TResponseSchema extends PortableSchema | undefined, TPayload, TPayloadInput> = InterruptRequestMethodSignature<TId, TPayloadSchema, TResponseSchema, TPayload, TPayloadInput>['call'];
|
|
1543
|
+
interface InterruptDefinition<TId extends string, TPayloadSchema extends PortableSchema | undefined, TResponseSchema extends PortableSchema | undefined, TPayload = unknown, TPayloadInput = TPayload> {
|
|
1544
|
+
readonly id: TId;
|
|
1545
|
+
readonly payloadSchema: TPayloadSchema;
|
|
1546
|
+
readonly responseSchema: TResponseSchema;
|
|
1547
|
+
interrupt: InterruptRequestMethod<TId, TPayloadSchema, TResponseSchema, TPayload, TPayloadInput>;
|
|
1548
|
+
}
|
|
1549
|
+
//#endregion
|
|
1550
|
+
//#region node_modules/.deno/@tanstack+ai@0.49.1/node_modules/@tanstack/ai/dist/esm/byok/providers.d.ts
|
|
1551
|
+
/**
|
|
1552
|
+
* Provider ids are open slugs, not a closed catalog. `@tanstack/ai` does not
|
|
1553
|
+
* list adapters. Any matching string is a valid id and becomes `x-byok-<id>`.
|
|
1554
|
+
*/
|
|
1555
|
+
type ProviderId = string;
|
|
1556
|
+
//#endregion
|
|
1557
|
+
//#region node_modules/.deno/@tanstack+ai-client@0.28.0/node_modules/@tanstack/ai-client/dist/esm/byok/storage.d.ts
|
|
1558
|
+
type Keyring = Partial<Record<ProviderId, string>>;
|
|
1559
|
+
type KeyPreview = Partial<Record<ProviderId, string>>;
|
|
1560
|
+
interface KeyringStorage {
|
|
1561
|
+
readonly id: string;
|
|
1562
|
+
readonly label: string;
|
|
1563
|
+
readonly persistent: boolean;
|
|
1564
|
+
readonly unlockable?: boolean;
|
|
1565
|
+
readonly warning?: string;
|
|
1566
|
+
peek?: () => KeyPreview | Promise<KeyPreview>;
|
|
1567
|
+
load: () => Keyring | Promise<Keyring>;
|
|
1568
|
+
save: (keys: Keyring) => void | Promise<void>;
|
|
1569
|
+
clear: () => void | Promise<void>;
|
|
1570
|
+
}
|
|
1571
|
+
//#endregion
|
|
1572
|
+
//#region node_modules/.deno/@tanstack+ai-client@0.28.0/node_modules/@tanstack/ai-client/dist/esm/byok/client.d.ts
|
|
1573
|
+
type KeyStatus = {
|
|
1574
|
+
state: 'empty';
|
|
1575
|
+
} | {
|
|
1576
|
+
state: 'set';
|
|
1577
|
+
masked: string;
|
|
1578
|
+
} | {
|
|
1579
|
+
state: 'locked';
|
|
1580
|
+
masked: string;
|
|
1581
|
+
} | {
|
|
1582
|
+
state: 'error';
|
|
1583
|
+
masked: string;
|
|
1584
|
+
message: string;
|
|
1585
|
+
};
|
|
1586
|
+
type ByokPrompt = {
|
|
1587
|
+
provider: ProviderId;
|
|
1588
|
+
reason: 'missing' | 'locked';
|
|
1589
|
+
};
|
|
1590
|
+
type ByokSnapshot = {
|
|
1591
|
+
status: Partial<Record<string, KeyStatus>>;
|
|
1592
|
+
locked: boolean;
|
|
1593
|
+
prompt: ByokPrompt | null;
|
|
1594
|
+
storageError: string | null;
|
|
1595
|
+
};
|
|
1596
|
+
interface DefineByokOptions {
|
|
1597
|
+
storage?: KeyringStorage;
|
|
1598
|
+
}
|
|
1599
|
+
declare class ByokClient {
|
|
1600
|
+
#private;
|
|
1601
|
+
readonly storage: KeyringStorage;
|
|
1602
|
+
constructor(options?: DefineByokOptions);
|
|
1603
|
+
/** Resolves when constructor hydration (peek/load) finishes. */
|
|
1604
|
+
ready: () => Promise<void>;
|
|
1605
|
+
subscribe: (listener: () => void) => (() => void);
|
|
1606
|
+
getSnapshot: () => ByokSnapshot;
|
|
1607
|
+
keys(): Keyring;
|
|
1608
|
+
request(provider: ProviderId, reason: ByokPrompt['reason']): void;
|
|
1609
|
+
/**
|
|
1610
|
+
* `true` — the server can fill any slug from env.
|
|
1611
|
+
* `false` — no env coverage.
|
|
1612
|
+
* A record merges per-id flags and clears the all/none boolean.
|
|
1613
|
+
*/
|
|
1614
|
+
setServerCoverage(flags: boolean | Readonly<Record<string, boolean>>): void;
|
|
1615
|
+
headers(provider?: ProviderId): Record<string, string>;
|
|
1616
|
+
prepare(provider?: ProviderId): Promise<void>;
|
|
1617
|
+
update(providerOrKey: ProviderId | string, key?: string): Promise<void>;
|
|
1618
|
+
clear(provider?: ProviderId): Promise<void>;
|
|
1619
|
+
unlock(): Promise<void>;
|
|
1620
|
+
}
|
|
1621
|
+
//#endregion
|
|
1622
|
+
//#region node_modules/.deno/@tanstack+ai-client@0.28.0/node_modules/@tanstack/ai-client/dist/esm/events.d.ts
|
|
1623
|
+
interface ChatClientRunEventContext {
|
|
1624
|
+
threadId: string;
|
|
1625
|
+
runId: string;
|
|
1626
|
+
toolCallId?: string;
|
|
1627
|
+
}
|
|
1628
|
+
interface ChatClientEventContext {
|
|
1629
|
+
threadId?: string;
|
|
1630
|
+
runId?: string;
|
|
1631
|
+
toolCallId?: string;
|
|
1632
|
+
}
|
|
1633
|
+
interface ChatClientToolFixtureAppliedEvent {
|
|
1634
|
+
hookId: string;
|
|
1635
|
+
threadId: string;
|
|
1636
|
+
toolName: string;
|
|
1637
|
+
input: unknown;
|
|
1638
|
+
output: unknown;
|
|
1639
|
+
execute?: boolean;
|
|
1640
|
+
message?: {
|
|
1641
|
+
id: string;
|
|
1642
|
+
role: 'system' | 'user' | 'assistant';
|
|
1643
|
+
parts: Array<unknown>;
|
|
1644
|
+
createdAt?: number | string;
|
|
1645
|
+
};
|
|
1646
|
+
messageId: string;
|
|
1647
|
+
toolCallId: string;
|
|
1648
|
+
runId?: string;
|
|
1649
|
+
errorText?: string;
|
|
1650
|
+
}
|
|
1651
|
+
interface ChatClientStructuredOutputEvent {
|
|
1652
|
+
status: 'streaming' | 'complete' | 'error';
|
|
1653
|
+
raw?: string;
|
|
1654
|
+
partial?: unknown;
|
|
1655
|
+
data?: unknown;
|
|
1656
|
+
reasoning?: string;
|
|
1657
|
+
errorMessage?: string;
|
|
1658
|
+
delta?: string;
|
|
1659
|
+
}
|
|
1660
|
+
type ChatClientStructuredOutputEventName = 'structured-output:started' | 'structured-output:updated' | 'structured-output:completed' | 'structured-output:errored';
|
|
1661
|
+
/**
|
|
1662
|
+
* Abstract base class for ChatClient event emission
|
|
1663
|
+
*/
|
|
1664
|
+
declare abstract class ChatClientEventEmitter {
|
|
1665
|
+
protected clientId: string;
|
|
1666
|
+
constructor(clientId: string);
|
|
1667
|
+
/**
|
|
1668
|
+
* Protected abstract method for emitting events
|
|
1669
|
+
* Implementations should handle adding clientId and timestamp
|
|
1670
|
+
*/
|
|
1671
|
+
protected abstract emitEvent(eventName: string, data?: Record<string, unknown>): void;
|
|
1672
|
+
/**
|
|
1673
|
+
* Emit client created event
|
|
1674
|
+
*/
|
|
1675
|
+
clientCreated(initialMessageCount: number): void;
|
|
1676
|
+
/**
|
|
1677
|
+
* Emit loading state changed event
|
|
1678
|
+
*/
|
|
1679
|
+
loadingChanged(isLoading: boolean): void;
|
|
1680
|
+
/**
|
|
1681
|
+
* Emit error state changed event
|
|
1682
|
+
*/
|
|
1683
|
+
errorChanged(error: string | null): void;
|
|
1684
|
+
/**
|
|
1685
|
+
* Emit text update events (combines processor and client events)
|
|
1686
|
+
*/
|
|
1687
|
+
textUpdated(streamId: string, messageId: string, content: string, context?: ChatClientRunEventContext): void;
|
|
1688
|
+
/**
|
|
1689
|
+
* Emit tool call state change events (combines processor and client events)
|
|
1690
|
+
*/
|
|
1691
|
+
toolCallStateChanged(streamId: string, messageId: string, toolCallId: string, toolName: string, state: string, args: string, context?: ChatClientRunEventContext): void;
|
|
1692
|
+
/**
|
|
1693
|
+
* Emit tool result state change event
|
|
1694
|
+
*/
|
|
1695
|
+
/**
|
|
1696
|
+
* Emit thinking update event
|
|
1697
|
+
*/
|
|
1698
|
+
thinkingUpdated(streamId: string, messageId: string, content: string, delta?: string, context?: ChatClientRunEventContext): void;
|
|
1699
|
+
structuredOutputChanged(eventName: ChatClientStructuredOutputEventName, streamId: string, messageId: string, output: ChatClientStructuredOutputEvent, context?: ChatClientRunEventContext): void;
|
|
1700
|
+
/**
|
|
1701
|
+
* Emit approval requested event
|
|
1702
|
+
*/
|
|
1703
|
+
approvalRequested(streamId: string, messageId: string, toolCallId: string, toolName: string, input: unknown, approvalId: string, context?: ChatClientRunEventContext): void;
|
|
1704
|
+
/**
|
|
1705
|
+
* Emit message appended event
|
|
1706
|
+
*/
|
|
1707
|
+
messageAppended(uiMessage: UIMessage, streamId?: string, context?: ChatClientEventContext): void;
|
|
1708
|
+
/**
|
|
1709
|
+
* Emit message sent event.
|
|
1710
|
+
* Supports both simple string content and multimodal content arrays.
|
|
1711
|
+
*
|
|
1712
|
+
* @param messageId - The ID of the sent message
|
|
1713
|
+
* @param content - The message content (string or array of ContentPart for multimodal)
|
|
1714
|
+
*/
|
|
1715
|
+
messageSent(messageId: string, content: string | Array<ContentPart>): void;
|
|
1716
|
+
/**
|
|
1717
|
+
* Emit reloaded event
|
|
1718
|
+
*/
|
|
1719
|
+
reloaded(fromMessageIndex: number): void;
|
|
1720
|
+
/**
|
|
1721
|
+
* Emit stopped event
|
|
1722
|
+
*/
|
|
1723
|
+
stopped(): void;
|
|
1724
|
+
/**
|
|
1725
|
+
* Emit messages cleared event
|
|
1726
|
+
*/
|
|
1727
|
+
messagesCleared(): void;
|
|
1728
|
+
/**
|
|
1729
|
+
* Emit tool result added event
|
|
1730
|
+
*/
|
|
1731
|
+
toolResultAdded(toolCallId: string, toolName: string, output: unknown, state: string, context?: ChatClientEventContext): void;
|
|
1732
|
+
/**
|
|
1733
|
+
* Emit tool approval responded event
|
|
1734
|
+
*/
|
|
1735
|
+
toolApprovalResponded(approvalId: string, toolCallId: string, approved: boolean, context?: ChatClientRunEventContext): void;
|
|
1736
|
+
/**
|
|
1737
|
+
* Emit tool fixture applied event.
|
|
1738
|
+
*/
|
|
1739
|
+
toolFixtureApplied(fixture: ChatClientToolFixtureAppliedEvent): void;
|
|
1740
|
+
}
|
|
1741
|
+
//#endregion
|
|
1742
|
+
//#region node_modules/.deno/@tanstack+ai-client@0.28.0/node_modules/@tanstack/ai-client/dist/esm/devtools.d.ts
|
|
1743
|
+
interface AIDevtoolsDisplayOptions {
|
|
1744
|
+
name?: string;
|
|
1745
|
+
}
|
|
1746
|
+
interface AIDevtoolsClientMetadata extends AIDevtoolsDisplayOptions {
|
|
1747
|
+
framework?: string;
|
|
1748
|
+
hookName: string;
|
|
1749
|
+
outputKind?: 'chat' | 'text' | 'structured' | 'image' | 'video' | 'audio';
|
|
1750
|
+
}
|
|
1751
|
+
interface AIDevtoolsChatSnapshot {
|
|
1752
|
+
[key: string]: unknown;
|
|
1753
|
+
messages: Array<UIMessage>;
|
|
1754
|
+
status: ChatClientState;
|
|
1755
|
+
isLoading: boolean;
|
|
1756
|
+
isSubscribed: boolean;
|
|
1757
|
+
connectionStatus: ConnectionStatus;
|
|
1758
|
+
sessionGenerating: boolean;
|
|
1759
|
+
activeRunIds: Array<string>;
|
|
1760
|
+
queue?: Array<QueuedMessage>;
|
|
1761
|
+
error?: string;
|
|
1762
|
+
}
|
|
1763
|
+
interface AIDevtoolsToolFixture {
|
|
1764
|
+
fixtureId?: string;
|
|
1765
|
+
hookId?: string;
|
|
1766
|
+
threadId?: string;
|
|
1767
|
+
runId?: string;
|
|
1768
|
+
toolName: string;
|
|
1769
|
+
input: unknown;
|
|
1770
|
+
output: unknown;
|
|
1771
|
+
execute?: boolean;
|
|
1772
|
+
message?: {
|
|
1773
|
+
id: string;
|
|
1774
|
+
role: UIMessage['role'];
|
|
1775
|
+
parts: Array<unknown>;
|
|
1776
|
+
createdAt?: number | string;
|
|
1777
|
+
};
|
|
1778
|
+
toolCallId?: string;
|
|
1779
|
+
messageId?: string;
|
|
1780
|
+
errorText?: string;
|
|
1781
|
+
}
|
|
1782
|
+
type AIDevtoolsRunEventType = 'run:created' | 'run:started' | 'run:updated' | 'run:completed' | 'run:errored' | 'run:cancelled';
|
|
1783
|
+
type AIDevtoolsRunStatus = 'created' | 'started' | 'updated' | 'completed' | 'errored' | 'cancelled';
|
|
1784
|
+
interface AIDevtoolsBridgeOptions<TSnapshot extends object> {
|
|
1785
|
+
hookId: string;
|
|
1786
|
+
threadId?: string;
|
|
1787
|
+
clientId: string;
|
|
1788
|
+
metadata: AIDevtoolsClientMetadata;
|
|
1789
|
+
getSnapshot: () => TSnapshot;
|
|
1790
|
+
getTools?: () => Iterable<AnyClientTool>;
|
|
1791
|
+
applyToolFixture?: (fixture: AIDevtoolsToolFixture) => void | Promise<void>;
|
|
1792
|
+
}
|
|
1793
|
+
declare class ClientDevtoolsBridge<TSnapshot extends object> {
|
|
1794
|
+
protected readonly options: AIDevtoolsBridgeOptions<TSnapshot>;
|
|
1795
|
+
private readonly unsubscribers;
|
|
1796
|
+
private disposed;
|
|
1797
|
+
private superseded;
|
|
1798
|
+
private registered;
|
|
1799
|
+
constructor(options: AIDevtoolsBridgeOptions<TSnapshot>);
|
|
1800
|
+
emitRegistered(): void;
|
|
1801
|
+
emitUpdated(): void;
|
|
1802
|
+
emitSnapshot(): void;
|
|
1803
|
+
emitToolsRegistered(): void;
|
|
1804
|
+
emitRunLifecycle(eventType: AIDevtoolsRunEventType, runId: string, status: AIDevtoolsRunStatus, options?: {
|
|
1805
|
+
error?: string;
|
|
1806
|
+
}): void;
|
|
1807
|
+
deactivate(): void;
|
|
1808
|
+
supersede(): void;
|
|
1809
|
+
dispose(): void;
|
|
1810
|
+
private prepareForEmit;
|
|
1811
|
+
private prepareForMountEmit;
|
|
1812
|
+
private activate;
|
|
1813
|
+
private handleRequestState;
|
|
1814
|
+
/**
|
|
1815
|
+
* Extension hook for subclasses to replay any additional cached state on a
|
|
1816
|
+
* `devtools:request-state` (i.e. when a panel opens). Called only after the
|
|
1817
|
+
* base guards (disposed/superseded/targetHookId) pass. No-op by default.
|
|
1818
|
+
*/
|
|
1819
|
+
protected onReplayState(): void;
|
|
1820
|
+
private handleToolFixtureApply;
|
|
1821
|
+
private matchesFixtureTarget;
|
|
1822
|
+
protected createEnvelope(eventType: 'hook:registered' | 'hook:updated' | 'hook:unregistered' | 'hook:state-snapshot' | 'tools:registered' | 'memory:retrieve:started' | 'memory:retrieve:completed' | 'memory:snapshot' | AIDevtoolsRunEventType, visibility?: AIDevtoolsEventVisibility, context?: {
|
|
1823
|
+
runId?: string;
|
|
1824
|
+
}): AIDevtoolsEventEnvelope;
|
|
1825
|
+
private createMetadataPayload;
|
|
1826
|
+
}
|
|
1827
|
+
interface ChatDevtoolsBridgeOptions extends AIDevtoolsBridgeOptions<AIDevtoolsChatSnapshot> {
|
|
1828
|
+
getMessages: () => Array<UIMessage>;
|
|
1829
|
+
setMessages: (messages: Array<UIMessage>) => void;
|
|
1830
|
+
addToolResult: (toolCallId: string, output: unknown, errorText?: string) => void;
|
|
1831
|
+
generateId: (prefix: string) => string;
|
|
1832
|
+
}
|
|
1833
|
+
declare class ChatDevtoolsBridge extends ClientDevtoolsBridge<AIDevtoolsChatSnapshot> {
|
|
1834
|
+
readonly events: ChatClientEventEmitter;
|
|
1835
|
+
private readonly chatOptions;
|
|
1836
|
+
private currentRunId;
|
|
1837
|
+
private currentRunThreadId;
|
|
1838
|
+
private currentStreamId;
|
|
1839
|
+
private lastStreamId;
|
|
1840
|
+
private lastRunEventContext;
|
|
1841
|
+
/** Last transported `memory:state` value, replayed when a panel opens. */
|
|
1842
|
+
private lastMemoryStateValue;
|
|
1843
|
+
constructor(options: ChatDevtoolsBridgeOptions);
|
|
1844
|
+
setCurrentStreamId(streamId: string | null): void;
|
|
1845
|
+
/**
|
|
1846
|
+
* Called by the auto-attaching emitter every time it sees a non-empty
|
|
1847
|
+
* streamId pass through. Lets devtools track the latest stream id
|
|
1848
|
+
* without the chat client wiring it up explicitly.
|
|
1849
|
+
*/
|
|
1850
|
+
recordStreamId(streamId: string): void;
|
|
1851
|
+
mountWithTools(initialMessageCount: number): void;
|
|
1852
|
+
notifyToolsChanged(): void;
|
|
1853
|
+
getCurrentStreamId(): string | null;
|
|
1854
|
+
getLastStreamId(): string | null;
|
|
1855
|
+
resolveStreamId(): string;
|
|
1856
|
+
beginRun(runId: string, threadId: string): void;
|
|
1857
|
+
observeChunk(chunk: StreamChunk): void;
|
|
1858
|
+
/**
|
|
1859
|
+
* Record a transported `memory:state` value (the server memory middleware's
|
|
1860
|
+
* per-turn recall metrics + store snapshot). Called from the chat client's
|
|
1861
|
+
* `onCustomEvent` handler — the designated path for CUSTOM stream events —
|
|
1862
|
+
* NOT from `observeChunk`. Re-emits the browser `memory:*` events the devtools
|
|
1863
|
+
* store consumes, and caches the value so a panel opened later can replay it
|
|
1864
|
+
* (see {@link onReplayState}). Symmetric with the generation bridge's
|
|
1865
|
+
* `recordResultChange` / `recordProgressChange`.
|
|
1866
|
+
*/
|
|
1867
|
+
recordMemoryState(rawValue: unknown): void;
|
|
1868
|
+
/**
|
|
1869
|
+
* Re-emit the browser-side `memory:*` events from a transported
|
|
1870
|
+
* `memory:state` value. The devtools store consumes these to render the
|
|
1871
|
+
* Memory tab (operations timeline + live contents). The recall pair mirrors
|
|
1872
|
+
* the server middleware's own emits; the snapshot is included only when the
|
|
1873
|
+
* adapter supports introspection.
|
|
1874
|
+
*/
|
|
1875
|
+
private emitMemoryState;
|
|
1876
|
+
protected onReplayState(): void;
|
|
1877
|
+
getCurrentRunEventContext(): ChatClientRunEventContext | undefined;
|
|
1878
|
+
getCurrentOrLastRunEventContext(): ChatClientRunEventContext | undefined;
|
|
1879
|
+
findToolCallContext(toolCallId: string): ChatClientEventContext;
|
|
1880
|
+
/**
|
|
1881
|
+
* Entry point invoked when the devtools panel emits
|
|
1882
|
+
* `devtools:tool-fixture:apply`. The chat client never calls this
|
|
1883
|
+
* directly; it is wired through the base bridge's fixture subscription.
|
|
1884
|
+
*/
|
|
1885
|
+
applyFixture(fixture: AIDevtoolsToolFixture): Promise<void>;
|
|
1886
|
+
private executeFixture;
|
|
1887
|
+
private addToolResultForFixture;
|
|
1888
|
+
private createReplayMessageFromFixture;
|
|
1889
|
+
private cloneFixtureSourceMessage;
|
|
1890
|
+
private createFixtureToolCallIdMap;
|
|
1891
|
+
private resolveFixtureMessageId;
|
|
1892
|
+
private resolveFixtureToolCallId;
|
|
1893
|
+
private findClientTool;
|
|
1894
|
+
}
|
|
1895
|
+
//#endregion
|
|
1896
|
+
//#region node_modules/.deno/@tanstack+ai-client@0.28.0/node_modules/@tanstack/ai-client/dist/esm/devtools-noop.d.ts
|
|
1897
|
+
type ChatDevtoolsBridgeFactory = (options: ChatDevtoolsBridgeOptions) => ChatDevtoolsBridge;
|
|
1898
|
+
//#endregion
|
|
1899
|
+
//#region node_modules/.deno/@tanstack+ai-client@0.28.0/node_modules/@tanstack/ai-client/dist/esm/types.d.ts
|
|
1900
|
+
interface ChatResumeState {
|
|
1901
|
+
threadId: string;
|
|
1902
|
+
runId: string;
|
|
1903
|
+
}
|
|
1904
|
+
type ChatPendingInterrupt = Interrupt;
|
|
1905
|
+
/**
|
|
1906
|
+
* The durable pointer a chat keeps for the run it may need to rejoin, plus any
|
|
1907
|
+
* interrupt that run is waiting on.
|
|
1908
|
+
*
|
|
1909
|
+
* @internal
|
|
1910
|
+
*/
|
|
1911
|
+
interface ChatResumeSnapshot {
|
|
1912
|
+
resumeState: ChatResumeState;
|
|
1913
|
+
pendingInterrupts?: Array<ChatPendingInterrupt>;
|
|
1914
|
+
}
|
|
1915
|
+
type InterruptItemStatus = 'pending' | 'validating' | 'staged' | 'submitting' | 'error';
|
|
1916
|
+
interface BoundInterruptBase {
|
|
1917
|
+
readonly id: string;
|
|
1918
|
+
readonly interruptId: string;
|
|
1919
|
+
readonly reason: string;
|
|
1920
|
+
readonly message?: string;
|
|
1921
|
+
readonly responseSchema?: Readonly<Record<string, unknown>>;
|
|
1922
|
+
readonly expiresAt?: string;
|
|
1923
|
+
readonly metadata?: Readonly<Record<string, unknown>>;
|
|
1924
|
+
readonly threadId: string;
|
|
1925
|
+
readonly interruptedRunId: string;
|
|
1926
|
+
readonly generation: number;
|
|
1927
|
+
readonly status: InterruptItemStatus;
|
|
1928
|
+
readonly errors: ReadonlyArray<ItemInterruptError>;
|
|
1929
|
+
/** @deprecated Use `errors[0]`. */
|
|
1930
|
+
readonly error?: ItemInterruptError;
|
|
1931
|
+
/**
|
|
1932
|
+
* Whether the binding/schema allows resolution at hydrate time.
|
|
1933
|
+
* Does not flip on submit/expiry — gate UI on `status`, `resuming`, and
|
|
1934
|
+
* `errors` for those lifecycle states.
|
|
1935
|
+
*/
|
|
1936
|
+
readonly canResolve: boolean;
|
|
1937
|
+
cancel: () => void;
|
|
1938
|
+
clearResolution: () => void;
|
|
1939
|
+
}
|
|
1940
|
+
interface GenericAGUIInterrupt extends BoundInterruptBase {
|
|
1941
|
+
readonly kind: 'generic';
|
|
1942
|
+
readonly binding: Readonly<Extract<InterruptBinding, {
|
|
1943
|
+
kind: 'generic';
|
|
1944
|
+
}>>;
|
|
1945
|
+
resolveInterrupt: (payload: unknown) => void;
|
|
1946
|
+
}
|
|
1947
|
+
type InterruptResponseInput<TDefinition> = TDefinition extends InterruptDefinition<any, any, infer TResponseSchema, any> ? InferSchemaType<TResponseSchema> : never;
|
|
1948
|
+
type RegisteredGenericInterruptFor<TDefinition extends InterruptDefinition<any, any, any, any>> = TDefinition extends InterruptDefinition<infer TDefinitionId, any, any, infer TPayload> ? BoundInterruptBase & {
|
|
1949
|
+
readonly kind: 'generic';
|
|
1950
|
+
readonly definitionId: TDefinitionId;
|
|
1951
|
+
readonly key: string;
|
|
1952
|
+
readonly payload: TPayload | undefined;
|
|
1953
|
+
readonly binding: Readonly<Extract<InterruptBinding, {
|
|
1954
|
+
kind: 'generic';
|
|
1955
|
+
}> & {
|
|
1956
|
+
definitionId: TDefinitionId;
|
|
1957
|
+
key: string;
|
|
1958
|
+
batchIndex: number;
|
|
1959
|
+
}>;
|
|
1960
|
+
resolveInterrupt: (response: InterruptResponseInput<TDefinition>) => void;
|
|
1961
|
+
} : never;
|
|
1962
|
+
type RegisteredGenericInterrupt<TInterrupts extends ReadonlyArray<InterruptDefinition<any, any, any, any>>> = TInterrupts[number] extends infer TDefinition ? TDefinition extends InterruptDefinition<any, any, any, any> ? RegisteredGenericInterruptFor<TDefinition> : never : never;
|
|
1963
|
+
/**
|
|
1964
|
+
* An interrupt that arrived on the stream carrying no resume binding this
|
|
1965
|
+
* client understands — no `tanstack:interruptBinding`, or one written at a
|
|
1966
|
+
* protocol version we don't recognise.
|
|
1967
|
+
*
|
|
1968
|
+
* These are surfaced rather than hidden so a UI can show that the run is
|
|
1969
|
+
* paused, but they are never resolvable here: something else owns them. A
|
|
1970
|
+
* workflow engine's durable approval projected into the same AG-UI stream
|
|
1971
|
+
* lands in this bucket, and resolving it through the chat resume path would
|
|
1972
|
+
* send an answer no one is waiting for. Render it, or route it to whatever
|
|
1973
|
+
* actually owns the pause.
|
|
1974
|
+
*/
|
|
1975
|
+
interface UnboundInterrupt extends Omit<BoundInterruptBase, 'cancel' | 'clearResolution'> {
|
|
1976
|
+
readonly kind: 'unbound';
|
|
1977
|
+
readonly binding?: undefined;
|
|
1978
|
+
readonly canResolve: false;
|
|
1979
|
+
}
|
|
1980
|
+
type ApprovalBranchSchema<TTool, TBranch extends 'approve' | 'reject'> = ApprovalSchemaOf<TTool> extends infer TApproval ? TApproval extends {
|
|
1981
|
+
approve?: SchemaInput;
|
|
1982
|
+
reject?: SchemaInput;
|
|
1983
|
+
} ? Exclude<TApproval[TBranch], undefined> : TApproval extends SchemaInput ? TApproval : never : never;
|
|
1984
|
+
type ApprovalEdits<TTool> = InputSchemaOf<TTool> extends NoSchema ? {
|
|
1985
|
+
editedArgs?: never;
|
|
1986
|
+
} : {
|
|
1987
|
+
editedArgs?: InferToolInput<TTool>;
|
|
1988
|
+
};
|
|
1989
|
+
type ApprovalPayload<TSchema> = [TSchema] extends [never] ? {
|
|
1990
|
+
payload?: never;
|
|
1991
|
+
} : TSchema extends SchemaInput ? {
|
|
1992
|
+
payload: InferSchemaType<TSchema>;
|
|
1993
|
+
} : {
|
|
1994
|
+
payload?: never;
|
|
1995
|
+
};
|
|
1996
|
+
type ApproveArguments<TTool> = [ApprovalBranchSchema<TTool, 'approve'>] extends [never] ? InputSchemaOf<TTool> extends NoSchema ? [options?: never] : [options?: ApprovalEdits<TTool> & {
|
|
1997
|
+
payload?: never;
|
|
1998
|
+
}] : [options: ApprovalEdits<TTool> & ApprovalPayload<ApprovalBranchSchema<TTool, 'approve'>>];
|
|
1999
|
+
type RejectArguments<TTool> = [ApprovalBranchSchema<TTool, 'reject'>] extends [never] ? [options?: never] : [options: {
|
|
2000
|
+
editedArgs?: never;
|
|
2001
|
+
} & ApprovalPayload<ApprovalBranchSchema<TTool, 'reject'>>];
|
|
2002
|
+
type ToolApprovalInterrupt<TTool extends AnyClientTool = AnyClientTool> = TTool extends AnyClientTool ? BoundInterruptBase & {
|
|
2003
|
+
readonly kind: 'tool-approval';
|
|
2004
|
+
readonly binding: Readonly<Extract<InterruptBinding, {
|
|
2005
|
+
kind: 'tool-approval';
|
|
2006
|
+
}>>;
|
|
2007
|
+
readonly toolName: TTool['name'];
|
|
2008
|
+
readonly toolCallId: string;
|
|
2009
|
+
readonly originalArgs: InferToolInput<TTool>;
|
|
2010
|
+
resolveInterrupt: <TApproved extends boolean>(approved: TApproved, ...args: TApproved extends true ? ApproveArguments<TTool> : RejectArguments<TTool>) => void;
|
|
2011
|
+
} : never;
|
|
2012
|
+
type ApprovalInterrupts<TTools extends ReadonlyArray<AnyClientTool>> = TTools[number] extends infer TTool ? TTool extends AnyClientTool ? ApprovalCapabilityOf<TTool> extends true ? ToolApprovalInterrupt<TTool> : never : never : never;
|
|
2013
|
+
type ChatInterrupt<TTools extends ReadonlyArray<AnyClientTool> = ReadonlyArray<AnyClientTool>, TInterrupts extends ReadonlyArray<InterruptDefinition<any, any, any, any>> = readonly []> = GenericAGUIInterrupt | RegisteredGenericInterrupt<TInterrupts> | UnboundInterrupt | ApprovalInterrupts<TTools>;
|
|
2014
|
+
type ResolvableChatInterrupt<TTools extends ReadonlyArray<AnyClientTool> = ReadonlyArray<AnyClientTool>, TInterrupts extends ReadonlyArray<InterruptDefinition<any, any, any, any>> = readonly []> = GenericAGUIInterrupt | RegisteredGenericInterrupt<TInterrupts> | ApprovalInterrupts<TTools>;
|
|
2015
|
+
type BoundInterrupts<TTools extends ReadonlyArray<AnyClientTool> = ReadonlyArray<AnyClientTool>, TInterrupts extends ReadonlyArray<InterruptDefinition<any, any, any, any>> = readonly []> = ReadonlyArray<ChatInterrupt<TTools, TInterrupts>>;
|
|
2016
|
+
interface ChatInterruptState<TTools extends ReadonlyArray<AnyClientTool> = ReadonlyArray<AnyClientTool>, TInterrupts extends ReadonlyArray<InterruptDefinition<any, any, any, any>> = readonly []> {
|
|
2017
|
+
readonly interrupts: BoundInterrupts<TTools, TInterrupts>;
|
|
2018
|
+
/** @deprecated Use `interrupts`. Same snapshot today. */
|
|
2019
|
+
readonly pendingInterrupts: BoundInterrupts<TTools, TInterrupts>;
|
|
2020
|
+
readonly interruptErrors: ReadonlyArray<BatchInterruptError>;
|
|
2021
|
+
readonly resuming: boolean;
|
|
2022
|
+
}
|
|
2023
|
+
/**
|
|
2024
|
+
* `messages` is the full UIMessage history (not a delta). `data` is the
|
|
2025
|
+
* merged body — `ChatClientOptions.body` plus any per-call data passed to
|
|
2026
|
+
* `sendMessage(...)`. `threadId` / `runId` are the AG-UI correlation ids
|
|
2027
|
+
* the chat client uses to track this turn — forward them to your server
|
|
2028
|
+
* if it needs to correlate requests.
|
|
2029
|
+
*/
|
|
2030
|
+
interface ChatFetcherInput {
|
|
2031
|
+
messages: Array<UIMessage>;
|
|
2032
|
+
data?: Record<string, unknown>;
|
|
2033
|
+
threadId: string;
|
|
2034
|
+
runId: string;
|
|
2035
|
+
parentRunId?: string;
|
|
2036
|
+
resume?: Array<RunAgentResumeItem>;
|
|
2037
|
+
}
|
|
2038
|
+
interface ChatFetcherOptions {
|
|
2039
|
+
/** Fires when `stop()` is called or the request is superseded. */
|
|
2040
|
+
signal: AbortSignal;
|
|
2041
|
+
/** Extra request headers for this run (e.g. BYOK keys). */
|
|
2042
|
+
headers?: Record<string, string>;
|
|
2043
|
+
}
|
|
2044
|
+
/**
|
|
2045
|
+
* Direct function that performs a chat request. Mirrors
|
|
2046
|
+
* `GenerationFetcher`. Returns either a `Response` (SSE body parsed by the
|
|
2047
|
+
* chat client) or an `AsyncIterable<StreamChunk>` (yielded directly). May
|
|
2048
|
+
* return the value synchronously, as a `Promise`, or as an async generator
|
|
2049
|
+
* (`async function*`) — the chat client awaits whichever shape is returned.
|
|
2050
|
+
*
|
|
2051
|
+
* @example
|
|
2052
|
+
* ```ts
|
|
2053
|
+
* useChat({
|
|
2054
|
+
* fetcher: ({ messages }, { signal }) =>
|
|
2055
|
+
* chatFn({ data: { messages }, signal }),
|
|
2056
|
+
* })
|
|
2057
|
+
* ```
|
|
2058
|
+
*/
|
|
2059
|
+
type ChatFetcher = (input: ChatFetcherInput, options: ChatFetcherOptions) => Response | AsyncIterable<StreamChunk> | Promise<Response | AsyncIterable<StreamChunk>>;
|
|
2060
|
+
/**
|
|
2061
|
+
* Distributive `Omit` — applies `Omit<O, K>` per branch of a union so
|
|
2062
|
+
* discriminated unions survive omission. Plain `Omit` collapses unions
|
|
2063
|
+
* into a single object shape, which would erase the `ChatTransport` XOR
|
|
2064
|
+
* when framework hooks omit React-managed callbacks from
|
|
2065
|
+
* `ChatClientOptions`.
|
|
2066
|
+
*/
|
|
2067
|
+
type DistributedOmit<TObject, TKeys extends keyof any> = TObject extends unknown ? Omit<TObject, TKeys> : never;
|
|
2068
|
+
/**
|
|
2069
|
+
* Discriminated union enforcing that exactly one of `connection` or
|
|
2070
|
+
* `fetcher` is provided. Mirrors `GenerationTransport`.
|
|
2071
|
+
*/
|
|
2072
|
+
type ChatTransport = {
|
|
2073
|
+
connection: ConnectionAdapter;
|
|
2074
|
+
fetcher?: never;
|
|
2075
|
+
} | {
|
|
2076
|
+
fetcher: ChatFetcher;
|
|
2077
|
+
connection?: never;
|
|
2078
|
+
};
|
|
2079
|
+
/**
|
|
2080
|
+
* Tool call states - track the lifecycle of a tool call
|
|
2081
|
+
*/
|
|
2082
|
+
type ToolCallState = 'awaiting-input' | 'input-streaming' | 'input-complete' | 'approval-requested' | 'approval-responded' | 'complete' | 'error';
|
|
2083
|
+
/**
|
|
2084
|
+
* Tool result states - track the lifecycle of a tool result
|
|
2085
|
+
*/
|
|
2086
|
+
type ToolResultState = 'streaming' | 'complete' | 'error';
|
|
2087
|
+
/**
|
|
2088
|
+
* ChatClient state - track the lifecycle of a chat
|
|
2089
|
+
*/
|
|
2090
|
+
type ChatClientState = 'ready' | 'submitted' | 'streaming' | 'error';
|
|
2091
|
+
/**
|
|
2092
|
+
* Connection lifecycle state for the subscription loop.
|
|
2093
|
+
*/
|
|
2094
|
+
type ConnectionStatus = 'disconnected' | 'connecting' | 'connected' | 'error';
|
|
2095
|
+
/**
|
|
2096
|
+
* Multimodal content input for sending messages with rich media.
|
|
2097
|
+
* Allows sending text, images, audio, video, and documents to the LLM.
|
|
2098
|
+
*
|
|
2099
|
+
* @example
|
|
2100
|
+
* ```ts
|
|
2101
|
+
* // Send an image with a question
|
|
2102
|
+
* client.sendMessage({
|
|
2103
|
+
* content: [
|
|
2104
|
+
* { type: 'text', content: 'What is in this image?' },
|
|
2105
|
+
* { type: 'image', source: { type: 'url', value: 'https://example.com/photo.jpg' } }
|
|
2106
|
+
* ],
|
|
2107
|
+
* id: 'custom-message-id' // optional
|
|
2108
|
+
* })
|
|
2109
|
+
* ```
|
|
2110
|
+
*/
|
|
2111
|
+
interface MultimodalContent {
|
|
2112
|
+
/**
|
|
2113
|
+
* The content of the message.
|
|
2114
|
+
* Can be a simple string or an array of content parts for multimodal messages.
|
|
2115
|
+
*/
|
|
2116
|
+
content: string | Array<ContentPart>;
|
|
2117
|
+
/**
|
|
2118
|
+
* Optional custom ID for the message.
|
|
2119
|
+
* If not provided, a unique ID will be generated.
|
|
2120
|
+
*/
|
|
2121
|
+
id?: string;
|
|
2122
|
+
/**
|
|
2123
|
+
* Optional AG-UI metadata bag copied onto the resulting UIMessage.
|
|
2124
|
+
*
|
|
2125
|
+
* @example
|
|
2126
|
+
* ```ts
|
|
2127
|
+
* await client.sendMessage({
|
|
2128
|
+
* content: 'Show me failed logins',
|
|
2129
|
+
* metadata: { author: { id: 'user-42', name: 'Dana' } },
|
|
2130
|
+
* })
|
|
2131
|
+
* ```
|
|
2132
|
+
*/
|
|
2133
|
+
metadata?: Record<string, any>;
|
|
2134
|
+
}
|
|
2135
|
+
/**
|
|
2136
|
+
* Action taken when `sendMessage` is called while the client is busy
|
|
2137
|
+
* (streaming, claiming a send, or draining the queue).
|
|
2138
|
+
* - `queue`: hold the message; it auto-sends when the current run settles
|
|
2139
|
+
* **successfully**.
|
|
2140
|
+
* - `drop`: ignore the send (promise still resolves; does not throw).
|
|
2141
|
+
* - `interrupt`: abort the current stream and send immediately. Unlike
|
|
2142
|
+
* `stop()`, does **not** flush already-queued messages — they still drain
|
|
2143
|
+
* after the interrupting send settles successfully.
|
|
2144
|
+
*/
|
|
2145
|
+
type WhenBusy = 'queue' | 'drop' | 'interrupt';
|
|
2146
|
+
/**
|
|
2147
|
+
* Why the client is busy when a {@link QueueStrategy} runs.
|
|
2148
|
+
* - `streaming` — an LLM stream is active (`isLoading`).
|
|
2149
|
+
* - `sendInFlight` — a send has claimed the client but is not yet loading.
|
|
2150
|
+
* - `draining` — the queue drain loop is delivering pending messages.
|
|
2151
|
+
*/
|
|
2152
|
+
type QueueBusyReason = 'streaming' | 'sendInFlight' | 'draining';
|
|
2153
|
+
/**
|
|
2154
|
+
* A user message held in the send queue while a stream is active.
|
|
2155
|
+
* Rendered separately from `messages`; cancellable via `cancelQueued(id)`
|
|
2156
|
+
* until it drains.
|
|
2157
|
+
*/
|
|
2158
|
+
interface QueuedMessage {
|
|
2159
|
+
id: string;
|
|
2160
|
+
content: string | MultimodalContent;
|
|
2161
|
+
createdAt: number;
|
|
2162
|
+
}
|
|
2163
|
+
/**
|
|
2164
|
+
* Declarative queue policy.
|
|
2165
|
+
*/
|
|
2166
|
+
interface QueueConfig {
|
|
2167
|
+
/**
|
|
2168
|
+
* Action when the client is busy (streaming, claiming a send, or draining).
|
|
2169
|
+
* Default `'queue'`.
|
|
2170
|
+
*/
|
|
2171
|
+
whenBusy?: WhenBusy;
|
|
2172
|
+
/**
|
|
2173
|
+
* How queued items leave the queue.
|
|
2174
|
+
* - `'fifo'`: one at a time, in order (default).
|
|
2175
|
+
* - `'batch'`: merge all queued items into one send when the run settles
|
|
2176
|
+
* successfully.
|
|
2177
|
+
*/
|
|
2178
|
+
drain?: 'fifo' | 'batch';
|
|
2179
|
+
/** Max queued items. Unlimited when omitted. `0` means never queue. */
|
|
2180
|
+
maxSize?: number;
|
|
2181
|
+
/**
|
|
2182
|
+
* Behavior when `maxSize` is reached. Default `'reject'`.
|
|
2183
|
+
* `'reject'` silently discards the new send (does not throw);
|
|
2184
|
+
* `'drop-oldest'` evicts the oldest queued item to make room.
|
|
2185
|
+
* Only meaningful when `maxSize` is set.
|
|
2186
|
+
*/
|
|
2187
|
+
onOverflow?: 'reject' | 'drop-oldest';
|
|
2188
|
+
}
|
|
2189
|
+
/**
|
|
2190
|
+
* Escape hatch: decide the action for a single send. Drain stays FIFO for the
|
|
2191
|
+
* function form (no `batch` via function). Per-call `sendOptions.whenBusy`
|
|
2192
|
+
* overrides the strategy for that send.
|
|
2193
|
+
*
|
|
2194
|
+
* Actions match {@link WhenBusy}. Concurrent streams are not supported.
|
|
2195
|
+
* `pending.id` is the id that will be stored if the action is `'queue'`
|
|
2196
|
+
* (safe to pass to `cancelQueued`).
|
|
2197
|
+
*/
|
|
2198
|
+
type QueueStrategy = (ctx: {
|
|
2199
|
+
pending: QueuedMessage;
|
|
2200
|
+
busyReason: QueueBusyReason;
|
|
2201
|
+
queued: ReadonlyArray<QueuedMessage>;
|
|
2202
|
+
}) => {
|
|
2203
|
+
action: WhenBusy;
|
|
2204
|
+
};
|
|
2205
|
+
/** A `WhenBusy` shorthand, a full config, or a strategy function. */
|
|
2206
|
+
type QueueOption = WhenBusy | QueueConfig | QueueStrategy;
|
|
2207
|
+
/** Per-call overrides for `sendMessage`. */
|
|
2208
|
+
interface SendMessageOptions {
|
|
2209
|
+
/** Overrides the configured `whenBusy` for this one send. */
|
|
2210
|
+
whenBusy?: WhenBusy;
|
|
2211
|
+
/**
|
|
2212
|
+
* Extra JSON merged into this request's wire `forwardedProps`.
|
|
2213
|
+
* Shallow merge: `{ ...chatBody, ...positionalBody, ...body }`.
|
|
2214
|
+
* This field wins on key collisions.
|
|
2215
|
+
*
|
|
2216
|
+
* Framework hooks (`useChat`, `injectChat`, `createChat`) expose
|
|
2217
|
+
* `sendMessage(content, options)` with no positional body, so this field
|
|
2218
|
+
* is the per-call body channel on those surfaces.
|
|
2219
|
+
*/
|
|
2220
|
+
body?: Record<string, any>;
|
|
2221
|
+
}
|
|
2222
|
+
/**
|
|
2223
|
+
* Message parts - building blocks of UIMessage
|
|
2224
|
+
*/
|
|
2225
|
+
interface TextPart {
|
|
2226
|
+
type: 'text';
|
|
2227
|
+
content: string;
|
|
2228
|
+
}
|
|
2229
|
+
/**
|
|
2230
|
+
* Helper type that creates a tool-call part for a specific tool.
|
|
2231
|
+
* This is a conditional type to enable proper distribution over union types,
|
|
2232
|
+
* creating a discriminated union where `name` is the discriminant.
|
|
2233
|
+
*/
|
|
2234
|
+
type ToolCallPartForTool<T> = T extends AnyClientTool ? {
|
|
2235
|
+
type: 'tool-call';
|
|
2236
|
+
id: string;
|
|
2237
|
+
name: T['name'];
|
|
2238
|
+
arguments: string; /** Parsed tool input (typed from inputSchema) */
|
|
2239
|
+
input?: InferToolInput<T>;
|
|
2240
|
+
state: ToolCallState; /** Tool execution output (for client tools or after approval) */
|
|
2241
|
+
output?: InferToolOutput<T>;
|
|
2242
|
+
} & (NonNullable<T['needsApproval']> extends true ? {
|
|
2243
|
+
/**
|
|
2244
|
+
* Approval metadata — present only on tools defined with
|
|
2245
|
+
* `needsApproval: true`. Populated once the call reaches
|
|
2246
|
+
* `state: 'approval-requested'`. `needsApproval` is an optional
|
|
2247
|
+
* property on the tool, so we index into it (rather than
|
|
2248
|
+
* `T extends { needsApproval: true }`, which an optional property
|
|
2249
|
+
* never satisfies) and strip `undefined` before comparing to `true`.
|
|
2250
|
+
*/
|
|
2251
|
+
approval?: {
|
|
2252
|
+
id: string;
|
|
2253
|
+
needsApproval: boolean;
|
|
2254
|
+
approved?: boolean;
|
|
2255
|
+
};
|
|
2256
|
+
} : unknown) : never;
|
|
2257
|
+
/**
|
|
2258
|
+
* Fallback tool-call part type when tools are not typed
|
|
2259
|
+
*/
|
|
2260
|
+
type UntypedToolCallPart = {
|
|
2261
|
+
type: 'tool-call';
|
|
2262
|
+
id: string;
|
|
2263
|
+
name: string;
|
|
2264
|
+
arguments: string;
|
|
2265
|
+
input?: any;
|
|
2266
|
+
state: ToolCallState;
|
|
2267
|
+
approval?: {
|
|
2268
|
+
id: string;
|
|
2269
|
+
needsApproval: boolean;
|
|
2270
|
+
approved?: boolean;
|
|
2271
|
+
};
|
|
2272
|
+
output?: any;
|
|
2273
|
+
};
|
|
2274
|
+
/**
|
|
2275
|
+
* Tool call part that creates a proper discriminated union.
|
|
2276
|
+
* When TTools is typed, checking `part.name === 'toolName'` will narrow
|
|
2277
|
+
* `part.output` to the correct type for that tool.
|
|
2278
|
+
*
|
|
2279
|
+
* The discriminant is `name`, so code like:
|
|
2280
|
+
* ```ts
|
|
2281
|
+
* if (part.name === 'recommendGuitar') {
|
|
2282
|
+
* // part.output is now typed to the recommendGuitar tool's output
|
|
2283
|
+
* }
|
|
2284
|
+
* ```
|
|
2285
|
+
*/
|
|
2286
|
+
type ToolCallPart$1<TTools extends ReadonlyArray<AnyClientTool> = any> = [TTools] extends [never] ? UntypedToolCallPart : unknown extends TTools ? UntypedToolCallPart : TTools extends ReadonlyArray<infer Tool> ? Tool extends AnyClientTool ? ToolCallPartForTool<Tool> : UntypedToolCallPart : UntypedToolCallPart;
|
|
2287
|
+
interface ToolResultPart {
|
|
2288
|
+
type: 'tool-result';
|
|
2289
|
+
toolCallId: string;
|
|
2290
|
+
content: string | Array<ContentPart>;
|
|
2291
|
+
state: ToolResultState;
|
|
2292
|
+
error?: string;
|
|
2293
|
+
}
|
|
2294
|
+
interface ThinkingPart {
|
|
2295
|
+
type: 'thinking';
|
|
2296
|
+
content: string;
|
|
2297
|
+
}
|
|
2298
|
+
type MessagePart<TTools extends ReadonlyArray<AnyClientTool> = any, TData = unknown> = TextPart | ImagePart | AudioPart | VideoPart | DocumentPart | ToolCallPart$1<TTools> | ToolResultPart | ThinkingPart | StructuredOutputPart<TData> | UIResourcePart;
|
|
2299
|
+
/**
|
|
2300
|
+
* UIMessage - Domain-specific message format optimized for building chat UIs
|
|
2301
|
+
* Contains parts that can be text, tool calls, or tool results.
|
|
2302
|
+
*
|
|
2303
|
+
* `TTools` narrows the tool-call/result part types based on the registered
|
|
2304
|
+
* tools. `TData` is the schema-inferred type for any `structured-output` part
|
|
2305
|
+
* on the message — defaulted to `unknown` so untyped consumers (the core
|
|
2306
|
+
* stream processor, the wire converter) don't need to thread a schema generic
|
|
2307
|
+
* everywhere; the hook layer (`useChat({ outputSchema })`) substitutes it on
|
|
2308
|
+
* the public return so `m.parts.find(p => p.type === 'structured-output').data`
|
|
2309
|
+
* is typed without manual casts.
|
|
2310
|
+
*/
|
|
2311
|
+
interface UIMessage<TTools extends ReadonlyArray<AnyClientTool> = any, TData = unknown> {
|
|
2312
|
+
id: string;
|
|
2313
|
+
role: 'system' | 'user' | 'assistant';
|
|
2314
|
+
parts: Array<MessagePart<TTools, TData>>;
|
|
2315
|
+
createdAt?: Date;
|
|
2316
|
+
/**
|
|
2317
|
+
* Optional AG-UI metadata bag. TanStack writes the `tanstack` key.
|
|
2318
|
+
* User keys stay at the top.
|
|
2319
|
+
*/
|
|
2320
|
+
metadata?: Record<string, any>;
|
|
2321
|
+
}
|
|
2322
|
+
/**
|
|
2323
|
+
* The single record a `ChatClientPersistence` adapter stores per chat. It folds
|
|
2324
|
+
* the two things that must survive a full page reload into one blob under one
|
|
2325
|
+
* key: the message transcript and the optional resume snapshot (which run to
|
|
2326
|
+
* rejoin / which interrupts to rehydrate). One adapter, one key — see
|
|
2327
|
+
* {@link ChatClientPersistence}.
|
|
2328
|
+
*/
|
|
2329
|
+
interface ChatPersistedState<TTools extends ReadonlyArray<AnyClientTool> = any> {
|
|
2330
|
+
messages: Array<UIMessage<TTools>>;
|
|
2331
|
+
/** Present while a run is in flight or paused on an interrupt; absent otherwise. */
|
|
2332
|
+
resume?: ChatResumeSnapshot;
|
|
2333
|
+
}
|
|
2334
|
+
/**
|
|
2335
|
+
* Storage adapter for durable chat state. A single adapter persists both the
|
|
2336
|
+
* message transcript and the resume snapshot as one {@link ChatPersistedState}
|
|
2337
|
+
* record, so a full page reload restores the conversation AND can rejoin an
|
|
2338
|
+
* in-flight run / rehydrate pending interrupts.
|
|
2339
|
+
*
|
|
2340
|
+
* For backward compatibility `getItem` may also return a bare `UIMessage[]`
|
|
2341
|
+
* (the legacy messages-only format); the client normalizes it to
|
|
2342
|
+
* `{ messages }`. `setItem` always writes the combined record.
|
|
2343
|
+
*/
|
|
2344
|
+
interface ChatClientPersistence<TTools extends ReadonlyArray<AnyClientTool> = any> {
|
|
2345
|
+
getItem: (id: string) => ChatPersistedState<TTools> | Array<UIMessage<TTools>> | null | undefined | Promise<ChatPersistedState<TTools> | Array<UIMessage<TTools>> | null | undefined>;
|
|
2346
|
+
setItem: (id: string, state: ChatPersistedState<TTools>) => void | Promise<void>;
|
|
2347
|
+
removeItem: (id: string) => void | Promise<void>;
|
|
2348
|
+
}
|
|
2349
|
+
/**
|
|
2350
|
+
* The `persistence` / `threadId` pairing for `ChatClient` and the chat hooks.
|
|
2351
|
+
*
|
|
2352
|
+
* Persistence that is on (`true` or a storage adapter) requires a `threadId`.
|
|
2353
|
+
* A minted id changes every reload, so nothing would restore. The compiler
|
|
2354
|
+
* asks for the conversation id instead.
|
|
2355
|
+
*
|
|
2356
|
+
* Omit `persistence`, or set it to `false`, and `threadId` stays optional.
|
|
2357
|
+
* The client then mints one after mount for the wire and DevTools.
|
|
2358
|
+
*
|
|
2359
|
+
* Intersect this onto `ChatClientOptions`. Do not apply a later plain `Omit`
|
|
2360
|
+
* to that type: it collapses the union and the requirement disappears. Use
|
|
2361
|
+
* {@link DistributedOmit}.
|
|
2362
|
+
*/
|
|
2363
|
+
type ChatPersistenceOptions<TTools extends ReadonlyArray<AnyClientTool> = any> = {
|
|
2364
|
+
persistence: true;
|
|
2365
|
+
threadId: string;
|
|
2366
|
+
} | {
|
|
2367
|
+
persistence: ChatClientPersistence<TTools>;
|
|
2368
|
+
threadId: string;
|
|
2369
|
+
} | {
|
|
2370
|
+
persistence?: false | undefined;
|
|
2371
|
+
threadId?: string;
|
|
2372
|
+
};
|
|
2373
|
+
type IsUnknown<T> = unknown extends T ? [T] extends [unknown] ? true : false : false;
|
|
2374
|
+
type KnownContext<T> = IsUnknown<T> extends true ? never : T;
|
|
2375
|
+
type MergeContext<TLeft, TRight> = [TLeft] extends [never] ? TRight : [TRight] extends [never] ? TLeft : TLeft & TRight;
|
|
2376
|
+
type UnionToIntersection<T> = [T] extends [never] ? never : (T extends unknown ? (value: T) => void : never) extends ((value: infer TIntersection) => void) ? TIntersection : never;
|
|
2377
|
+
type DefinedContext<T> = Exclude<T, undefined>;
|
|
2378
|
+
type ContextFromExecute<T> = T extends ((...args: any) => any) ? NonNullable<Parameters<T>[1]> extends {
|
|
2379
|
+
context: infer TContext;
|
|
2380
|
+
} ? KnownContext<TContext> : never : never;
|
|
2381
|
+
type ContextFromClientTool<T> = T extends AnyClientTool ? T extends {
|
|
2382
|
+
execute?: infer TExecute;
|
|
2383
|
+
} ? ContextFromExecute<TExecute> : never : never;
|
|
2384
|
+
type RequiredContextFromClientToolUnion<T> = T extends unknown ? undefined extends ContextFromClientTool<T> ? never : ContextFromClientTool<T> : never;
|
|
2385
|
+
type ContextFromClientToolUnion<T> = [UnionToIntersection<DefinedContext<ContextFromClientTool<T>>>] extends [never] ? never : [RequiredContextFromClientToolUnion<T>] extends [never] ? UnionToIntersection<DefinedContext<ContextFromClientTool<T>>> | undefined : UnionToIntersection<DefinedContext<ContextFromClientTool<T>>>;
|
|
2386
|
+
type ContextFromClientTools<TTools> = IsUnknown<TTools> extends true ? never : TTools extends readonly [infer THead, ...infer TTail] ? MergeContext<ContextFromClientTool<THead>, ContextFromClientTools<TTail>> : TTools extends ReadonlyArray<infer TItem> ? ContextFromClientToolUnion<TItem> : never;
|
|
2387
|
+
type InferredClientContext<TTools> = [ContextFromClientTools<TTools>] extends [never] ? unknown : ContextFromClientTools<TTools>;
|
|
2388
|
+
type ClientContextOptionFromTools<TTools, TContext> = [ContextFromClientTools<TTools>] extends [never] ? {
|
|
2389
|
+
context?: TContext;
|
|
2390
|
+
} : undefined extends ContextFromClientTools<TTools> ? {
|
|
2391
|
+
context?: TContext & ContextFromClientTools<TTools>;
|
|
2392
|
+
} : {
|
|
2393
|
+
context: TContext & ContextFromClientTools<TTools>;
|
|
2394
|
+
};
|
|
2395
|
+
/**
|
|
2396
|
+
* Base options for `ChatClient`, excluding the transport (`connection` or
|
|
2397
|
+
* `fetcher`) which is supplied separately via `ChatTransport` so the XOR
|
|
2398
|
+
* is preserved when composing the final `ChatClientOptions` type.
|
|
2399
|
+
*/
|
|
2400
|
+
interface ChatClientBaseOptions<TTools extends ReadonlyArray<AnyClientTool> = any, TContext = unknown, TInterrupts extends ReadonlyArray<InterruptDefinition<any, any, any, any>> = readonly []> {
|
|
2401
|
+
/**
|
|
2402
|
+
* Initial messages to populate the chat
|
|
2403
|
+
*/
|
|
2404
|
+
initialMessages?: Array<UIMessage<TTools>>;
|
|
2405
|
+
/**
|
|
2406
|
+
* Initial resumable run state, useful when rehydrating a persisted client
|
|
2407
|
+
* after a full page reload. This restores the client-side interrupt
|
|
2408
|
+
* descriptors needed to send AG-UI resume entries.
|
|
2409
|
+
*/
|
|
2410
|
+
initialResumeSnapshot?: ChatResumeSnapshot;
|
|
2411
|
+
/**
|
|
2412
|
+
* Arbitrary client-controlled JSON forwarded to the server in the
|
|
2413
|
+
* AG-UI `RunAgentInput.forwardedProps` field. Use this for per-session
|
|
2414
|
+
* options like provider/model selection or feature flags that the
|
|
2415
|
+
* server endpoint should read.
|
|
2416
|
+
*
|
|
2417
|
+
* Replaces the legacy `body` option. If both are provided,
|
|
2418
|
+
* `forwardedProps` wins on key collision.
|
|
2419
|
+
*/
|
|
2420
|
+
forwardedProps?: Record<string, any>;
|
|
2421
|
+
/**
|
|
2422
|
+
* @deprecated Use `forwardedProps` instead. `body` continues to work
|
|
2423
|
+
* unchanged — its values are merged into the AG-UI
|
|
2424
|
+
* `RunAgentInput.forwardedProps` field on the wire and are also
|
|
2425
|
+
* mirrored under the legacy `data` field for servers that have not
|
|
2426
|
+
* migrated yet. Will be removed in a future major release.
|
|
2427
|
+
*/
|
|
2428
|
+
body?: Record<string, any>;
|
|
2429
|
+
/**
|
|
2430
|
+
* Optional BYOK keyring. On each send the client prepares the resolved
|
|
2431
|
+
* provider and stamps `x-byok-*` request headers. Keys never go in the body.
|
|
2432
|
+
*/
|
|
2433
|
+
byok?: ByokClient;
|
|
2434
|
+
/**
|
|
2435
|
+
* Optional provider id for this chat. If it returns a provider slug,
|
|
2436
|
+
* only that key is prepared and sent. Otherwise the merged `provider`
|
|
2437
|
+
* from `forwardedProps`, `body`, and per-call `sendMessage` `body` is
|
|
2438
|
+
* used. Later sources win. If no slug resolves, the send throws
|
|
2439
|
+
* instead of attaching every stored key.
|
|
2440
|
+
*/
|
|
2441
|
+
byokProvider?: () => string | undefined;
|
|
2442
|
+
/**
|
|
2443
|
+
* Client-local runtime context passed to client tool implementations.
|
|
2444
|
+
*
|
|
2445
|
+
* This value is not serialized to the server. Use `forwardedProps` for
|
|
2446
|
+
* explicit client-to-server handoff of serializable values.
|
|
2447
|
+
*/
|
|
2448
|
+
context?: TContext;
|
|
2449
|
+
/**
|
|
2450
|
+
* Callback when a response is received
|
|
2451
|
+
*/
|
|
2452
|
+
onResponse?: (response?: Response) => void | Promise<void>;
|
|
2453
|
+
/**
|
|
2454
|
+
* Callback when a stream chunk is received
|
|
2455
|
+
*/
|
|
2456
|
+
onChunk?: (chunk: StreamChunk) => void;
|
|
2457
|
+
/**
|
|
2458
|
+
* Callback when the response is finished
|
|
2459
|
+
*/
|
|
2460
|
+
onFinish?: (message: UIMessage<TTools>) => void;
|
|
2461
|
+
/**
|
|
2462
|
+
* Callback when an error occurs
|
|
2463
|
+
*/
|
|
2464
|
+
onError?: (error: Error) => void;
|
|
2465
|
+
/**
|
|
2466
|
+
* Callback when messages change
|
|
2467
|
+
*/
|
|
2468
|
+
onMessagesChange?: (messages: Array<UIMessage<TTools>>) => void;
|
|
2469
|
+
/**
|
|
2470
|
+
* Callback when loading state changes
|
|
2471
|
+
*/
|
|
2472
|
+
onLoadingChange?: (isLoading: boolean) => void;
|
|
2473
|
+
/**
|
|
2474
|
+
* Callback when error state changes
|
|
2475
|
+
*/
|
|
2476
|
+
onErrorChange?: (error: Error | undefined) => void;
|
|
2477
|
+
/**
|
|
2478
|
+
* Callback when chat status changes
|
|
2479
|
+
*/
|
|
2480
|
+
onStatusChange?: (status: ChatClientState) => void;
|
|
2481
|
+
/**
|
|
2482
|
+
* Callback when subscription lifecycle changes.
|
|
2483
|
+
* This is independent from request lifecycle (`isLoading`, `status`).
|
|
2484
|
+
*/
|
|
2485
|
+
onSubscriptionChange?: (isSubscribed: boolean) => void;
|
|
2486
|
+
/**
|
|
2487
|
+
* Callback when connection lifecycle changes.
|
|
2488
|
+
*/
|
|
2489
|
+
onConnectionStatusChange?: (status: ConnectionStatus) => void;
|
|
2490
|
+
/**
|
|
2491
|
+
* Callback when session generation activity changes.
|
|
2492
|
+
* Derived from stream run events (RUN_STARTED / RUN_FINISHED / RUN_ERROR).
|
|
2493
|
+
* Unlike `onLoadingChange` (request-local), this reflects shared generation
|
|
2494
|
+
* activity visible to all subscribers (e.g. across tabs/devices).
|
|
2495
|
+
*/
|
|
2496
|
+
onSessionGeneratingChange?: (isGenerating: boolean) => void;
|
|
2497
|
+
/**
|
|
2498
|
+
* Policy for messages sent while the client is busy (streaming, claiming
|
|
2499
|
+
* a send, or draining the queue). Accepts a `WhenBusy` string, a
|
|
2500
|
+
* `QueueConfig`, or a `QueueStrategy` function.
|
|
2501
|
+
* Default: `{ whenBusy: 'queue', drain: 'fifo' }`.
|
|
2502
|
+
* Queued items auto-send only after a **successful** settle; they are
|
|
2503
|
+
* discarded on error/abort, `stop()`, `clear()`, `unsubscribe()`, and
|
|
2504
|
+
* `reload()`.
|
|
2505
|
+
*/
|
|
2506
|
+
queue?: QueueOption;
|
|
2507
|
+
/**
|
|
2508
|
+
* Callback when the pending send queue changes (enqueue, cancel, drain,
|
|
2509
|
+
* or flush).
|
|
2510
|
+
*/
|
|
2511
|
+
onQueueChange?: (queue: Array<QueuedMessage>) => void;
|
|
2512
|
+
/**
|
|
2513
|
+
* Callback when resumable run state or pending interrupts change.
|
|
2514
|
+
*/
|
|
2515
|
+
onResumeStateChange?: (resumeState: ChatResumeState | null, pendingInterrupts: BoundInterrupts<TTools, TInterrupts>) => void;
|
|
2516
|
+
/**
|
|
2517
|
+
* Callback when the id of the run this client has in flight changes: the new
|
|
2518
|
+
* id when a run starts (a send, or a `joinRun` rejoin), `null` when it settles.
|
|
2519
|
+
*/
|
|
2520
|
+
onRunIdChange?: (runId: string | null) => void;
|
|
2521
|
+
/**
|
|
2522
|
+
* Callback when the immutable interrupt state snapshot changes.
|
|
2523
|
+
* Snapshot restoration passes `{ source: 'hydrate' }`; streamed and
|
|
2524
|
+
* client-initiated updates pass `{ source: 'live' }`.
|
|
2525
|
+
*/
|
|
2526
|
+
onInterruptStateChange?: (state: ChatInterruptState<TTools, TInterrupts>, context: {
|
|
2527
|
+
source: 'hydrate' | 'live';
|
|
2528
|
+
}) => void;
|
|
2529
|
+
/**
|
|
2530
|
+
* Callback when a custom event is received from a server-side tool.
|
|
2531
|
+
* Custom events are emitted by tools using `context.emitCustomEvent()` during execution.
|
|
2532
|
+
*
|
|
2533
|
+
* @param eventType - The name of the custom event
|
|
2534
|
+
* @param data - The event payload data
|
|
2535
|
+
* @param context - Additional context including the toolCallId that emitted the event
|
|
2536
|
+
*/
|
|
2537
|
+
onCustomEvent?: (eventType: string, data: unknown, context: {
|
|
2538
|
+
toolCallId?: string;
|
|
2539
|
+
}) => void;
|
|
2540
|
+
/**
|
|
2541
|
+
* Client-side tools with execution logic
|
|
2542
|
+
* When provided, tools with execute functions will be called automatically
|
|
2543
|
+
*/
|
|
2544
|
+
tools?: TTools;
|
|
2545
|
+
/** First-party generic interrupts this client can type and resolve. */
|
|
2546
|
+
interrupts?: TInterrupts;
|
|
2547
|
+
/**
|
|
2548
|
+
* Devtools hook metadata for this client instance.
|
|
2549
|
+
*/
|
|
2550
|
+
devtools?: Partial<AIDevtoolsClientMetadata>;
|
|
2551
|
+
/**
|
|
2552
|
+
* Factory that constructs the devtools bridge. Default is a no-op
|
|
2553
|
+
* factory, which keeps `@tanstack/ai-client/devtools` (the heavy
|
|
2554
|
+
* bridge implementation) out of the main entry's bundle. Frameworks
|
|
2555
|
+
* that need live devtools should pass the real factory from
|
|
2556
|
+
* `@tanstack/ai-client/devtools`.
|
|
2557
|
+
*/
|
|
2558
|
+
devtoolsBridgeFactory?: ChatDevtoolsBridgeFactory;
|
|
2559
|
+
/**
|
|
2560
|
+
* Stream processing options (optional)
|
|
2561
|
+
* Configure chunking strategy
|
|
2562
|
+
*/
|
|
2563
|
+
streamProcessor?: {
|
|
2564
|
+
/**
|
|
2565
|
+
* Strategy for when to emit text updates
|
|
2566
|
+
* Defaults to ImmediateStrategy (every chunk)
|
|
2567
|
+
*/
|
|
2568
|
+
chunkStrategy?: ChunkStrategy;
|
|
2569
|
+
};
|
|
2570
|
+
}
|
|
2571
|
+
/**
|
|
2572
|
+
* Options for `ChatClient`. Exactly one of `connection` or `fetcher` must be
|
|
2573
|
+
* provided — the type-level XOR is enforced via `ChatTransport`. Persistence
|
|
2574
|
+
* that is on requires a `threadId` via {@link ChatPersistenceOptions}.
|
|
2575
|
+
*/
|
|
2576
|
+
type ChatClientOptions<TTools extends ReadonlyArray<AnyClientTool> = any, TContext = InferredClientContext<TTools>, TInterrupts extends ReadonlyArray<InterruptDefinition<any, any, any, any>> = readonly []> = DistributedOmit<ChatClientBaseOptions<TTools, TContext, TInterrupts>, 'context'> & ClientContextOptionFromTools<TTools, TContext> & ChatTransport & ChatPersistenceOptions<TTools>;
|
|
2577
|
+
//#endregion
|
|
2578
|
+
//#region node_modules/.deno/@tanstack+ai-client@0.28.0/node_modules/@tanstack/ai-client/dist/esm/connection-adapters.d.ts
|
|
2579
|
+
/**
|
|
2580
|
+
* Per-send context provided by the chat client to the connection adapter.
|
|
2581
|
+
* The adapter combines this with serialized messages to build a full
|
|
2582
|
+
* AG-UI `RunAgentInput` payload.
|
|
2583
|
+
*/
|
|
2584
|
+
interface RunAgentInputContext {
|
|
2585
|
+
threadId: string;
|
|
2586
|
+
runId: string;
|
|
2587
|
+
parentRunId?: string;
|
|
2588
|
+
/** AG-UI interrupt resume entries returned to the server on a follow-up run. */
|
|
2589
|
+
resume?: Array<RunAgentResumeItem>;
|
|
2590
|
+
/** Client-declared tools to advertise in the request payload. */
|
|
2591
|
+
clientTools?: Array<{
|
|
2592
|
+
name: string;
|
|
2593
|
+
description: string;
|
|
2594
|
+
parameters: unknown;
|
|
2595
|
+
}>;
|
|
2596
|
+
/** Arbitrary user-controlled passthrough data. */
|
|
2597
|
+
forwardedProps?: Record<string, unknown>;
|
|
2598
|
+
/** Extra request headers for this run (e.g. BYOK keys). POST only. */
|
|
2599
|
+
headers?: Record<string, string>;
|
|
2600
|
+
}
|
|
2601
|
+
interface ConnectConnectionAdapter {
|
|
2602
|
+
/**
|
|
2603
|
+
* Connect and return an async iterable of StreamChunks.
|
|
2604
|
+
*/
|
|
2605
|
+
connect: (messages: Array<UIMessage$1> | Array<ModelMessage>, data?: Record<string, any>, abortSignal?: AbortSignal, runContext?: RunAgentInputContext) => AsyncIterable<StreamChunk>;
|
|
2606
|
+
/**
|
|
2607
|
+
* Fetch server-driven hydration for a generation `threadId`: the last
|
|
2608
|
+
* generation's resume snapshot, plus a cursor to a run still generating if
|
|
2609
|
+
* one exists. The generation client calls this itself on mount when
|
|
2610
|
+
* `persistence: true` (no loader/prop) and repaints the snapshot — it never
|
|
2611
|
+
* auto-starts a run. Read-only JSON GET (`?threadId`), so it is
|
|
2612
|
+
* transport-agnostic. Optional and feature-detected exactly like the chat
|
|
2613
|
+
* `hydrate` handler.
|
|
2614
|
+
*/
|
|
2615
|
+
hydrateGeneration?: (threadId: string) => Promise<GenerationHydrationResult>;
|
|
2616
|
+
/**
|
|
2617
|
+
* Re-attach to a run that is still generating and replay it from the start
|
|
2618
|
+
* (read-only `?offset=-1&runId` against the delivery-durability log). The
|
|
2619
|
+
* generation client tails this on mount when hydration reports a run still in
|
|
2620
|
+
* flight, so a dropped connection or a full reload finishes the generation in
|
|
2621
|
+
* place — the same durability replay the chat client uses. Optional and
|
|
2622
|
+
* feature-detected; present on `fetchServerSentEvents` / `fetchHttpStream`.
|
|
2623
|
+
*/
|
|
2624
|
+
joinRun?: (runId: string, abortSignal?: AbortSignal) => AsyncIterable<StreamChunk>;
|
|
2625
|
+
/**
|
|
2626
|
+
* Fetch server-driven hydration for a chat `threadId`: the stored transcript
|
|
2627
|
+
* plus a cursor to an in-flight run and any pending interrupts. The chat
|
|
2628
|
+
* client calls this itself on mount when `persistence: true` (no loader/prop)
|
|
2629
|
+
* and repaints it — it never auto-sends. Read-only JSON GET (`?threadId`), so
|
|
2630
|
+
* it is transport-agnostic. Optional and feature-detected; present on
|
|
2631
|
+
* `fetchServerSentEvents` / `fetchHttpStream`, and on `stream()` /
|
|
2632
|
+
* `rpcStream()` when supplied via {@link StreamConnectionHandlers}.
|
|
2633
|
+
*/
|
|
2634
|
+
hydrate?: (threadId: string) => Promise<ChatHydrationResult>;
|
|
2635
|
+
}
|
|
2636
|
+
/**
|
|
2637
|
+
* Server-resolved hydration for a generation thread. `resumeSnapshot` is the
|
|
2638
|
+
* last generation's lightweight snapshot (validated client-side before it is
|
|
2639
|
+
* adopted); `activeRun` is a cursor to a run still generating for the thread
|
|
2640
|
+
* (or `null`).
|
|
2641
|
+
*
|
|
2642
|
+
* Field-for-field compatible with `@tanstack/ai-persistence`'s
|
|
2643
|
+
* `ReconstructedGeneration` (the body `reconstructGeneration` returns) — the
|
|
2644
|
+
* client never imports that package, so this is a structural contract, not a
|
|
2645
|
+
* shared type. Two deliberate widenings on this side: `schemaVersion` is
|
|
2646
|
+
* optional (the server always writes `1`, but a hand-written fixture need not),
|
|
2647
|
+
* and `status` also admits `'idle'`, which the server's mapper never emits.
|
|
2648
|
+
* Only a client-local snapshot reaches it, when `stop()` retires a cancelled
|
|
2649
|
+
* run.
|
|
2650
|
+
*/
|
|
2651
|
+
interface GenerationHydrationResult {
|
|
2652
|
+
resumeSnapshot: {
|
|
2653
|
+
schemaVersion?: 1;
|
|
2654
|
+
resumeState: {
|
|
2655
|
+
threadId: string;
|
|
2656
|
+
runId: string;
|
|
2657
|
+
} | null;
|
|
2658
|
+
status: 'idle' | 'running' | 'complete' | 'error';
|
|
2659
|
+
result?: unknown;
|
|
2660
|
+
error?: {
|
|
2661
|
+
message: string;
|
|
2662
|
+
code?: string;
|
|
2663
|
+
};
|
|
2664
|
+
activity?: string;
|
|
2665
|
+
} | null;
|
|
2666
|
+
activeRun: {
|
|
2667
|
+
runId: string;
|
|
2668
|
+
} | null;
|
|
2669
|
+
}
|
|
2670
|
+
/**
|
|
2671
|
+
* Server-resolved hydration for a thread. `messages` is the stored transcript;
|
|
2672
|
+
* `activeRun` is a cursor to a run still generating for the thread (or `null`).
|
|
2673
|
+
* Keyed on the STABLE thread id — the client never handles a run id, so a turn
|
|
2674
|
+
* that spans several runs (interrupt/tool continuations) reconnects correctly.
|
|
2675
|
+
*/
|
|
2676
|
+
interface ChatHydrationResult {
|
|
2677
|
+
messages: Array<UIMessage$1>;
|
|
2678
|
+
activeRun: {
|
|
2679
|
+
runId: string;
|
|
2680
|
+
} | null;
|
|
2681
|
+
/**
|
|
2682
|
+
* Pending human-in-the-loop interrupts for the thread and the run they paused,
|
|
2683
|
+
* so a reload (or another device) re-prompts the approval from the server. The
|
|
2684
|
+
* client restores them exactly as a persisted resume snapshot would.
|
|
2685
|
+
*/
|
|
2686
|
+
interrupts: {
|
|
2687
|
+
runId: string;
|
|
2688
|
+
pending: Array<ChatPendingInterrupt>;
|
|
2689
|
+
} | null;
|
|
2690
|
+
}
|
|
2691
|
+
interface SubscribeConnectionAdapter {
|
|
2692
|
+
/**
|
|
2693
|
+
* Subscribe to stream chunks.
|
|
2694
|
+
*/
|
|
2695
|
+
subscribe: (abortSignal?: AbortSignal) => AsyncIterable<StreamChunk>;
|
|
2696
|
+
/**
|
|
2697
|
+
* Send a request; chunks arrive through subscribe().
|
|
2698
|
+
*/
|
|
2699
|
+
send: (messages: Array<UIMessage$1> | Array<ModelMessage>, data?: Record<string, any>, abortSignal?: AbortSignal, runContext?: RunAgentInputContext) => Promise<void>;
|
|
2700
|
+
/**
|
|
2701
|
+
* Re-attach to an existing run by id, replaying its stream from the start off
|
|
2702
|
+
* the server's delivery-durability sink. Present only when the underlying
|
|
2703
|
+
* connection is resumable (a `ResumableConnectConnectionAdapter`). Used to
|
|
2704
|
+
* rejoin an in-flight run after a full page reload.
|
|
2705
|
+
*/
|
|
2706
|
+
joinRun?: (runId: string, abortSignal?: AbortSignal) => AsyncIterable<StreamChunk>;
|
|
2707
|
+
/**
|
|
2708
|
+
* Server-authoritative hydration for a thread (transcript + in-flight-run
|
|
2709
|
+
* cursor). Present only when the underlying connection supports it. The client
|
|
2710
|
+
* calls it on mount to re-hydrate without any app-side loader or prop.
|
|
2711
|
+
*/
|
|
2712
|
+
hydrate?: (threadId: string) => Promise<ChatHydrationResult>;
|
|
2713
|
+
}
|
|
2714
|
+
/**
|
|
2715
|
+
* Connection adapter union.
|
|
2716
|
+
* Provide either `connect`, or `subscribe` + `send`.
|
|
2717
|
+
*/
|
|
2718
|
+
type ConnectionAdapter = ConnectConnectionAdapter | SubscribeConnectionAdapter;
|
|
2719
|
+
//#endregion
|
|
2720
|
+
//#region node_modules/.deno/@tanstack+ai-client@0.28.0/node_modules/@tanstack/ai-client/dist/esm/chat-client.d.ts
|
|
2721
|
+
type ChatClientUpdateOptionsWithoutContext<TTools extends ReadonlyArray<AnyClientTool>, TInterrupts extends ReadonlyArray<InterruptDefinition<any, any, any, any>> = readonly []> = {
|
|
2722
|
+
connection?: ConnectionAdapter;
|
|
2723
|
+
fetcher?: ChatFetcher; /** @deprecated Use `forwardedProps` instead. */
|
|
2724
|
+
body?: Record<string, any>;
|
|
2725
|
+
forwardedProps?: Record<string, any>;
|
|
2726
|
+
byok?: ByokClient;
|
|
2727
|
+
byokProvider?: () => string | undefined;
|
|
2728
|
+
tools?: TTools;
|
|
2729
|
+
interrupts?: TInterrupts;
|
|
2730
|
+
queue?: QueueOption;
|
|
2731
|
+
onResponse?: (response?: Response) => void | Promise<void>;
|
|
2732
|
+
onChunk?: (chunk: StreamChunk) => void;
|
|
2733
|
+
onFinish?: (message: UIMessage) => void;
|
|
2734
|
+
onError?: (error: Error) => void;
|
|
2735
|
+
onSubscriptionChange?: (isSubscribed: boolean) => void;
|
|
2736
|
+
onConnectionStatusChange?: (status: ConnectionStatus) => void;
|
|
2737
|
+
onSessionGeneratingChange?: (isGenerating: boolean) => void;
|
|
2738
|
+
onQueueChange?: (queue: Array<QueuedMessage>) => void;
|
|
2739
|
+
onResumeStateChange?: (resumeState: ChatResumeState | null, pendingInterrupts: BoundInterrupts<TTools, TInterrupts>) => void;
|
|
2740
|
+
/**
|
|
2741
|
+
* Fires whenever the id of the run in flight changes: the new id when a run
|
|
2742
|
+
* starts (including a rejoin), `null` when it settles.
|
|
2743
|
+
*/
|
|
2744
|
+
onRunIdChange?: (runId: string | null) => void;
|
|
2745
|
+
onInterruptStateChange?: (state: ChatInterruptState<TTools, TInterrupts>, context: {
|
|
2746
|
+
source: 'hydrate' | 'live';
|
|
2747
|
+
}) => void;
|
|
2748
|
+
onCustomEvent?: (eventType: string, data: unknown, context: {
|
|
2749
|
+
toolCallId?: string;
|
|
2750
|
+
}) => void;
|
|
2751
|
+
};
|
|
2752
|
+
type ClientToolResult = {
|
|
2753
|
+
toolCallId: string;
|
|
2754
|
+
tool: string;
|
|
2755
|
+
output: any;
|
|
2756
|
+
state?: 'output-available' | 'output-error';
|
|
2757
|
+
errorText?: string;
|
|
2758
|
+
};
|
|
2759
|
+
declare class ChatClient<TTools extends ReadonlyArray<AnyClientTool> = any, TContext = unknown, TInterrupts extends ReadonlyArray<InterruptDefinition<any, any, any, any>> = any> {
|
|
2760
|
+
private readonly processor;
|
|
2761
|
+
private connection;
|
|
2762
|
+
private uniqueId;
|
|
2763
|
+
private threadId;
|
|
2764
|
+
private readonly persistor?;
|
|
2765
|
+
private readonly clearedStreamTracker;
|
|
2766
|
+
private currentRunId;
|
|
2767
|
+
private lastResume;
|
|
2768
|
+
private rejoinedRunId;
|
|
2769
|
+
private readonly interruptManager;
|
|
2770
|
+
private activeInterruptSubmission;
|
|
2771
|
+
private interruptSubmissionFailure;
|
|
2772
|
+
private readonly joinedRunWaiters;
|
|
2773
|
+
private pendingResumeParentRunId;
|
|
2774
|
+
private pendingResumeThreadId;
|
|
2775
|
+
private pendingResumeItems;
|
|
2776
|
+
private activeResumeThreadId;
|
|
2777
|
+
private activeResumeRunId;
|
|
2778
|
+
private bodyOption;
|
|
2779
|
+
private forwardedPropsOption;
|
|
2780
|
+
private byok;
|
|
2781
|
+
private byokProvider;
|
|
2782
|
+
private context;
|
|
2783
|
+
private pendingMessageBody;
|
|
2784
|
+
private queueConfig;
|
|
2785
|
+
private messageQueue;
|
|
2786
|
+
/**
|
|
2787
|
+
* True from the moment `sendMessage` claims the client until its
|
|
2788
|
+
* `streamResponse` settles. Closes the race where concurrent callers both
|
|
2789
|
+
* see `isLoading === false`, both append a user message, and only one stream
|
|
2790
|
+
* actually runs (leaving stranded user messages with no reply).
|
|
2791
|
+
*/
|
|
2792
|
+
private sendInFlight;
|
|
2793
|
+
/**
|
|
2794
|
+
* True while `drainQueue` is delivering queued messages. Concurrent
|
|
2795
|
+
* `sendMessage` calls during a drain are treated as busy and follow
|
|
2796
|
+
* `whenBusy` (default: queue).
|
|
2797
|
+
*/
|
|
2798
|
+
private messageQueueDraining;
|
|
2799
|
+
/**
|
|
2800
|
+
* Set by `whenBusy: 'interrupt'` so an in-progress FIFO drain loop stops
|
|
2801
|
+
* before starting the next queued item (the interrupting send owns the client).
|
|
2802
|
+
*/
|
|
2803
|
+
private stopMessageQueueDrain;
|
|
2804
|
+
/**
|
|
2805
|
+
* Sync claim held for the duration of `deliverMessage` so concurrent
|
|
2806
|
+
* deliverers cannot both append a user message before only one stream runs.
|
|
2807
|
+
*/
|
|
2808
|
+
private deliverClaim;
|
|
2809
|
+
private isLoading;
|
|
2810
|
+
private isSubscribed;
|
|
2811
|
+
private error;
|
|
2812
|
+
private status;
|
|
2813
|
+
private connectionStatus;
|
|
2814
|
+
private abortController;
|
|
2815
|
+
private readonly clientToolsRef;
|
|
2816
|
+
private readonly devtoolsBridge;
|
|
2817
|
+
/**
|
|
2818
|
+
* Alias for `this.events`. The bridge installs an
|
|
2819
|
+
* emitter that auto-attaches run/thread context and auto-emits a
|
|
2820
|
+
* snapshot after every event, so chat-client only ever calls
|
|
2821
|
+
* `this.events.X(...)` exactly like it did before devtools landed.
|
|
2822
|
+
*/
|
|
2823
|
+
private readonly events;
|
|
2824
|
+
private currentStreamId;
|
|
2825
|
+
private currentMessageId;
|
|
2826
|
+
private readonly postStreamActions;
|
|
2827
|
+
private readonly pendingToolExecutions;
|
|
2828
|
+
private activeClientTools;
|
|
2829
|
+
private activeContext;
|
|
2830
|
+
private continuationPending;
|
|
2831
|
+
private subscriptionAbortController;
|
|
2832
|
+
private processingResolve;
|
|
2833
|
+
private errorReportedGeneration;
|
|
2834
|
+
private streamGeneration;
|
|
2835
|
+
private continuationSkipped;
|
|
2836
|
+
private draining;
|
|
2837
|
+
private sessionGenerating;
|
|
2838
|
+
private readonly activeRunIds;
|
|
2839
|
+
/** Latched by `dispose()`; stops any late async callback starting new work. */
|
|
2840
|
+
private disposed;
|
|
2841
|
+
/** Whether a view is currently watching. See `attach` / `detach`. */
|
|
2842
|
+
private tailing;
|
|
2843
|
+
/** Constructor inputs `attach()` needs on every re-attach, not just the first. */
|
|
2844
|
+
private readonly rejoinRunId;
|
|
2845
|
+
private readonly cachesMessages;
|
|
2846
|
+
private devtoolsMounted;
|
|
2847
|
+
private readonly callbacksRef;
|
|
2848
|
+
constructor(options: ChatClientOptions<TTools, TContext, TInterrupts>);
|
|
2849
|
+
/**
|
|
2850
|
+
* START TAILING: re-attach to an in-flight run so its chunks arrive here.
|
|
2851
|
+
*
|
|
2852
|
+
* Called by the constructor, and again by a UI wrapper every time its view
|
|
2853
|
+
* mounts. Idempotent — attaching while already attached does nothing — so the
|
|
2854
|
+
* constructor call and a wrapper's first mount cost one attach between them.
|
|
2855
|
+
*
|
|
2856
|
+
* Pairs with {@link detach}. The pair exists because tailing used to begin ONLY
|
|
2857
|
+
* in the constructor, which meant a view could never stop tailing and then
|
|
2858
|
+
* resume: unmount had to either keep the connection open or lose it for good.
|
|
2859
|
+
* Keeping it open is what starved the page — a browser allows ~6 connections per
|
|
2860
|
+
* origin, and one long-lived stream per view reaches that after a handful of
|
|
2861
|
+
* views, after which every other request queues (measured: an in-page fetch took
|
|
2862
|
+
* over two minutes while the same request from outside the browser took 17ms).
|
|
2863
|
+
*/
|
|
2864
|
+
attach(): void;
|
|
2865
|
+
/**
|
|
2866
|
+
* STOP TAILING: drop the connection, keep everything else.
|
|
2867
|
+
*
|
|
2868
|
+
* Called by a UI wrapper when its view unmounts. The transcript, the resume
|
|
2869
|
+
* pointer and the run id all stay, so a later {@link attach} repaints instantly
|
|
2870
|
+
* and re-tails from the durable log — nothing is lost, because the run keeps
|
|
2871
|
+
* going server-side and its log holds every chunk.
|
|
2872
|
+
*
|
|
2873
|
+
* Deliberately NOT `dispose()`: this client is expected back. And deliberately
|
|
2874
|
+
* not `stop()`, which means "the user ended this run" — detaching says only that
|
|
2875
|
+
* nobody is watching right now.
|
|
2876
|
+
*
|
|
2877
|
+
* `rejoinedRunId` is cleared so the next `attach` can re-join the same run;
|
|
2878
|
+
* without that reset the guard in {@link maybeRejoinInFlight} would treat the
|
|
2879
|
+
* run as already joined and the view would come back silent.
|
|
2880
|
+
*/
|
|
2881
|
+
detach(): void;
|
|
2882
|
+
private applyResumeSnapshot;
|
|
2883
|
+
/**
|
|
2884
|
+
* Apply a resume snapshot read from durable storage. Restores interrupt state,
|
|
2885
|
+
* and for a bare in-flight run (no pending interrupts) also rejoins it. This is
|
|
2886
|
+
* the async-store counterpart to the synchronous rejoin in the constructor:
|
|
2887
|
+
* `applyResumeSnapshot` alone only handles interrupts, so an async store
|
|
2888
|
+
* (`indexedDBPersistence`) would otherwise never rejoin a mid-stream run.
|
|
2889
|
+
*/
|
|
2890
|
+
private applyPersistedResume;
|
|
2891
|
+
/**
|
|
2892
|
+
* Rejoin a persisted in-flight run, guarded so it fires at most once and never
|
|
2893
|
+
* while another run is already active. Skipped when the connection is not
|
|
2894
|
+
* resumable (`joinRun` absent), so a non-durable transport is a no-op.
|
|
2895
|
+
*/
|
|
2896
|
+
private maybeRejoinInFlight;
|
|
2897
|
+
/**
|
|
2898
|
+
* Server-authoritative mount hydration (`persistence: true`). The client holds
|
|
2899
|
+
* no transcript and no run pointer; on mount it asks the server — keyed by the
|
|
2900
|
+
* stable threadId — for the stored transcript and whether a run is still
|
|
2901
|
+
* generating. The transcript repaints immediately; an in-flight run is tailed
|
|
2902
|
+
* through the same durability rejoin as a reload. Best-effort and
|
|
2903
|
+
* non-blocking: a failure leaves the client empty rather than throwing, and a
|
|
2904
|
+
* send that starts first owns the client (hydration then backs off).
|
|
2905
|
+
*/
|
|
2906
|
+
private hydrateFromServer;
|
|
2907
|
+
mountDevtools(): void;
|
|
2908
|
+
private ensureThreadId;
|
|
2909
|
+
/**
|
|
2910
|
+
* Drain a runId-less RUN_ERROR that belongs to a cleared run the client is
|
|
2911
|
+
* still tracking. The persistor owns the cleared-run bookkeeping; the client
|
|
2912
|
+
* owns the active-run / session / processing state.
|
|
2913
|
+
*/
|
|
2914
|
+
private drainIgnoredRunlessChunk;
|
|
2915
|
+
private retireIgnoredClearedTerminalChunk;
|
|
2916
|
+
private updateRunLifecycle;
|
|
2917
|
+
/**
|
|
2918
|
+
* Track interrupt state off the stream's terminal events. A RUN_FINISHED with
|
|
2919
|
+
* an interrupt outcome records the pending interrupts + the run/thread to
|
|
2920
|
+
* resume; any other terminal event for the tracked/current run clears that
|
|
2921
|
+
* state. This is interrupt (state) resume — there is no delivery cursor.
|
|
2922
|
+
*/
|
|
2923
|
+
private observeInterruptState;
|
|
2924
|
+
/**
|
|
2925
|
+
* The interrupt-resume state for the active/interrupted run (its run/thread
|
|
2926
|
+
* ids), or null when there is nothing to resume. Apps can persist this to
|
|
2927
|
+
* resume interrupts across a full reload.
|
|
2928
|
+
*/
|
|
2929
|
+
getResumeState(): ChatResumeState | null;
|
|
2930
|
+
/**
|
|
2931
|
+
* The id of the run this client has in flight — one it started via a send or
|
|
2932
|
+
* rejoined via `joinRun` — or null when there is none. Unlike
|
|
2933
|
+
* {@link getResumeState}, this tracks ordinary runs too, not only one that is
|
|
2934
|
+
* interrupted or being resumed. A run another client started and that arrives
|
|
2935
|
+
* over a live subscription is not this client's run and is not reported here.
|
|
2936
|
+
*/
|
|
2937
|
+
getCurrentRunId(): string | null;
|
|
2938
|
+
private setCurrentRunId;
|
|
2939
|
+
getInterruptState(): ChatInterruptState<TTools, TInterrupts>;
|
|
2940
|
+
getInterrupts(): BoundInterrupts<TTools, TInterrupts>;
|
|
2941
|
+
/** @deprecated Use getInterrupts(). */
|
|
2942
|
+
getPendingInterrupts(): BoundInterrupts<TTools, TInterrupts>;
|
|
2943
|
+
resolveInterrupts(approved: boolean): void;
|
|
2944
|
+
resolveInterrupts(resolver: (interrupt: ResolvableChatInterrupt<TTools, TInterrupts>) => undefined): void;
|
|
2945
|
+
cancelInterrupts(): void;
|
|
2946
|
+
retryInterrupts(): void;
|
|
2947
|
+
/** Unsafe low-level resume escape hatch. Prefer bound interrupt methods. */
|
|
2948
|
+
resumeInterruptsUnsafe(resume: Array<RunAgentResumeItem>, state?: ChatResumeState): Promise<boolean>;
|
|
2949
|
+
/** @deprecated Use bound interrupt methods or resumeInterruptsUnsafe(). */
|
|
2950
|
+
resumeInterrupts(resume: Array<RunAgentResumeItem>, state?: ChatResumeState): Promise<boolean>;
|
|
2951
|
+
private submitInterruptBatch;
|
|
2952
|
+
private takeInterruptSubmissionFailure;
|
|
2953
|
+
private interruptGeneration;
|
|
2954
|
+
private generateUniqueId;
|
|
2955
|
+
private setIsLoading;
|
|
2956
|
+
private setStatus;
|
|
2957
|
+
private setIsSubscribed;
|
|
2958
|
+
private setConnectionStatus;
|
|
2959
|
+
private setSessionGenerating;
|
|
2960
|
+
private notifyResumeStateChange;
|
|
2961
|
+
/**
|
|
2962
|
+
* Build the durable resume snapshot from the current resume state + pending
|
|
2963
|
+
* interrupt descriptors and hand it to the persistor (null clears it).
|
|
2964
|
+
*/
|
|
2965
|
+
private persistResumeSnapshot;
|
|
2966
|
+
private resetSessionGenerating;
|
|
2967
|
+
private setError;
|
|
2968
|
+
private buildDevtoolsBridgeOptions;
|
|
2969
|
+
private getDevtoolsSnapshot;
|
|
2970
|
+
private findMessageIdForToolCall;
|
|
2971
|
+
private abortSubscriptionLoop;
|
|
2972
|
+
private resolveProcessing;
|
|
2973
|
+
private cancelInFlightStream;
|
|
2974
|
+
private reportStreamError;
|
|
2975
|
+
/**
|
|
2976
|
+
* Start the background subscription loop.
|
|
2977
|
+
*/
|
|
2978
|
+
private startSubscription;
|
|
2979
|
+
/**
|
|
2980
|
+
* Consume chunks from the connection subscription.
|
|
2981
|
+
*/
|
|
2982
|
+
private consumeSubscription;
|
|
2983
|
+
/**
|
|
2984
|
+
* Re-attach to an in-flight run after a full page reload, replaying its stream
|
|
2985
|
+
* from the server's delivery-durability log via `joinRun` (which returns the
|
|
2986
|
+
* whole run so far, then tails live to completion).
|
|
2987
|
+
*
|
|
2988
|
+
* The log is the single source of truth for the run, so we rebuild the
|
|
2989
|
+
* in-flight assistant bubble from it rather than trying to reconcile the
|
|
2990
|
+
* server-hydrated partial with the replay: on the first chunk that actually
|
|
2991
|
+
* (re)builds a message we drop the hydrated in-flight assistant, and the
|
|
2992
|
+
* replay reconstructs one clean bubble. Dropping only on real content (not on
|
|
2993
|
+
* `RUN_STARTED`) means a rejoin that connects but delivers nothing can never
|
|
2994
|
+
* leave an empty bubble behind.
|
|
2995
|
+
*
|
|
2996
|
+
* Bounded connect: a durable backend keeps a from-start join open waiting for
|
|
2997
|
+
* a producer, so a stale pointer to an unknown/evicted run would otherwise pin
|
|
2998
|
+
* the UI in a loading state for the backend's full first-chunk deadline. We
|
|
2999
|
+
* give up after {@link REJOIN_CONNECT_DEADLINE_MS} if no chunk arrives and
|
|
3000
|
+
* clear the dead pointer so it does not retry on the next load.
|
|
3001
|
+
*
|
|
3002
|
+
* Replay chunks are processed WITHOUT the per-chunk yield the live path uses,
|
|
3003
|
+
* so the buffered prefix snaps in and only the genuinely-live tail streams at
|
|
3004
|
+
* network speed — a reload looks like the run continued, not like it re-typed.
|
|
3005
|
+
*/
|
|
3006
|
+
private resumeInFlightRun;
|
|
3007
|
+
/**
|
|
3008
|
+
* Drop a hydrated, still-in-flight assistant turn so a resume replay can
|
|
3009
|
+
* rebuild it cleanly. Only touches a trailing assistant message (the shape a
|
|
3010
|
+
* reload-mid-stream leaves); a thread whose last turn is a user message (run
|
|
3011
|
+
* never produced, or already settled) is left untouched.
|
|
3012
|
+
*/
|
|
3013
|
+
private dropTrailingInFlightAssistant;
|
|
3014
|
+
private processIncomingChunk;
|
|
3015
|
+
private isActiveInterruptSubmissionFailure;
|
|
3016
|
+
private resolveJoinedRun;
|
|
3017
|
+
/**
|
|
3018
|
+
* Ensure subscription loop is running, starting it if needed.
|
|
3019
|
+
*/
|
|
3020
|
+
private ensureSubscription;
|
|
3021
|
+
/**
|
|
3022
|
+
* Create a promise that resolves when onStreamEnd fires.
|
|
3023
|
+
* Used by streamResponse to await processing completion.
|
|
3024
|
+
*/
|
|
3025
|
+
private waitForProcessing;
|
|
3026
|
+
/**
|
|
3027
|
+
* Send a message and stream the response.
|
|
3028
|
+
* Supports both simple string content and multimodal content (images, audio, video, documents).
|
|
3029
|
+
*
|
|
3030
|
+
* @param content - The message content. Can be:
|
|
3031
|
+
* - A simple string for text-only messages
|
|
3032
|
+
* - A MultimodalContent object with content array and optional custom ID
|
|
3033
|
+
* @param body - Optional body parameters to merge with the client's base body for this request.
|
|
3034
|
+
* Uses shallow merge with per-message body taking priority.
|
|
3035
|
+
* @param sendOptions - Per-call overrides. `{ whenBusy }` overrides the
|
|
3036
|
+
* queue policy for this one send. `{ body }`
|
|
3037
|
+
* shallow-merges with `body` and with the chat-level
|
|
3038
|
+
* `body` / `forwardedProps`. `sendOptions.body` wins
|
|
3039
|
+
* on key collisions. Framework hooks forward this
|
|
3040
|
+
* object as their second argument.
|
|
3041
|
+
*
|
|
3042
|
+
* @example
|
|
3043
|
+
* ```ts
|
|
3044
|
+
* // Simple text message
|
|
3045
|
+
* await client.sendMessage('Hello!')
|
|
3046
|
+
*
|
|
3047
|
+
* // Text message with custom body params
|
|
3048
|
+
* await client.sendMessage('Hello!', { temperature: 0.7 })
|
|
3049
|
+
*
|
|
3050
|
+
* // Per-call whenBusy override
|
|
3051
|
+
* await client.sendMessage('Urgent', undefined, { whenBusy: 'interrupt' })
|
|
3052
|
+
*
|
|
3053
|
+
* // Per-call body via options. Same effect as the positional arg.
|
|
3054
|
+
* // This is the shape the framework hooks (`useChat`, `injectChat`) forward.
|
|
3055
|
+
* await client.sendMessage('Hello!', undefined, { body: { temperature: 0.7 } })
|
|
3056
|
+
*
|
|
3057
|
+
* // Multimodal message with image
|
|
3058
|
+
* await client.sendMessage({
|
|
3059
|
+
* content: [
|
|
3060
|
+
* { type: 'text', content: 'What is in this image?' },
|
|
3061
|
+
* { type: 'image', source: { type: 'url', value: 'https://example.com/photo.jpg' } }
|
|
3062
|
+
* ]
|
|
3063
|
+
* })
|
|
3064
|
+
*
|
|
3065
|
+
* // Multimodal message with custom ID and body params
|
|
3066
|
+
* await client.sendMessage(
|
|
3067
|
+
* {
|
|
3068
|
+
* content: [
|
|
3069
|
+
* { type: 'text', content: 'Describe this audio' },
|
|
3070
|
+
* { type: 'audio', source: { type: 'data', value: 'base64...' } }
|
|
3071
|
+
* ],
|
|
3072
|
+
* id: 'custom-message-id'
|
|
3073
|
+
* },
|
|
3074
|
+
* { model: 'gpt-5.5' }
|
|
3075
|
+
* )
|
|
3076
|
+
* ```
|
|
3077
|
+
*/
|
|
3078
|
+
sendMessage(content: string | MultimodalContent, body?: Record<string, any>, sendOptions?: SendMessageOptions): Promise<void>;
|
|
3079
|
+
/** True while interrupt descriptors still own continuation. */
|
|
3080
|
+
private hasPendingInterrupts;
|
|
3081
|
+
/** True while an interrupt batch owns the next user turn. */
|
|
3082
|
+
private hasBlockingInterrupts;
|
|
3083
|
+
/** True while a stream is active, a send is claiming the client, or the queue is draining. */
|
|
3084
|
+
private isSendBusy;
|
|
3085
|
+
private resolveBusyReason;
|
|
3086
|
+
/**
|
|
3087
|
+
* Append a user message and run the stream. Used by both direct sends and
|
|
3088
|
+
* queue drains — callers are responsible for busy/queue policy.
|
|
3089
|
+
*
|
|
3090
|
+
* Claims delivery synchronously before appending so concurrent callers
|
|
3091
|
+
* cannot both add a user message when only one stream can run.
|
|
3092
|
+
*/
|
|
3093
|
+
private deliverMessage;
|
|
3094
|
+
/**
|
|
3095
|
+
* Resolve the effective action for a send that arrives while busy.
|
|
3096
|
+
* The returned `id` is the id that will be stored if the action is `queue`.
|
|
3097
|
+
*/
|
|
3098
|
+
private decideWhenBusy;
|
|
3099
|
+
private enqueueMessage;
|
|
3100
|
+
/**
|
|
3101
|
+
* Normalize the message input to extract content, optional id, and
|
|
3102
|
+
* optional metadata. String form has no metadata. Trims string content.
|
|
3103
|
+
*/
|
|
3104
|
+
private normalizeMessageInput;
|
|
3105
|
+
/**
|
|
3106
|
+
* Append a message and stream the response
|
|
3107
|
+
*/
|
|
3108
|
+
append(message: UIMessage | ModelMessage): Promise<void>;
|
|
3109
|
+
/**
|
|
3110
|
+
* Stream a response from the LLM.
|
|
3111
|
+
* Returns true if the stream completed successfully, false on abort or error.
|
|
3112
|
+
*/
|
|
3113
|
+
private streamResponse;
|
|
3114
|
+
/**
|
|
3115
|
+
* Start the client subscription loop.
|
|
3116
|
+
* This controls the connection lifecycle independently from request lifecycle.
|
|
3117
|
+
*/
|
|
3118
|
+
subscribe(options?: {
|
|
3119
|
+
restart?: boolean;
|
|
3120
|
+
}): void;
|
|
3121
|
+
/**
|
|
3122
|
+
* Unsubscribe and fully tear down live behavior.
|
|
3123
|
+
* This aborts an in-flight request and the subscription loop.
|
|
3124
|
+
*/
|
|
3125
|
+
unsubscribe(): void;
|
|
3126
|
+
/**
|
|
3127
|
+
* Reload the last assistant message
|
|
3128
|
+
*/
|
|
3129
|
+
reload(): Promise<void>;
|
|
3130
|
+
/**
|
|
3131
|
+
* Stop the current stream
|
|
3132
|
+
*/
|
|
3133
|
+
stop(): void;
|
|
3134
|
+
/**
|
|
3135
|
+
* Clear all messages
|
|
3136
|
+
*/
|
|
3137
|
+
clear(): void;
|
|
3138
|
+
/**
|
|
3139
|
+
* Add the result of a client-side tool execution
|
|
3140
|
+
*/
|
|
3141
|
+
addToolResult(result: ClientToolResult): Promise<void>;
|
|
3142
|
+
private addToolResultForClientTool;
|
|
3143
|
+
private validateClientToolOutput;
|
|
3144
|
+
/**
|
|
3145
|
+
* Respond to a tool approval request
|
|
3146
|
+
*/
|
|
3147
|
+
addToolApprovalResponse(response: {
|
|
3148
|
+
id: string;
|
|
3149
|
+
approved: boolean;
|
|
3150
|
+
}): Promise<void>;
|
|
3151
|
+
/**
|
|
3152
|
+
* Queue an action to be executed after the current stream ends
|
|
3153
|
+
*/
|
|
3154
|
+
private queuePostStreamAction;
|
|
3155
|
+
/**
|
|
3156
|
+
* Drain and execute all queued post-stream actions
|
|
3157
|
+
*/
|
|
3158
|
+
private drainPostStreamActions;
|
|
3159
|
+
/**
|
|
3160
|
+
* Check if we should continue the flow and do so if needed
|
|
3161
|
+
*/
|
|
3162
|
+
private checkForContinuation;
|
|
3163
|
+
/**
|
|
3164
|
+
* Check if all tool calls are complete and we should auto-send.
|
|
3165
|
+
* Requires that there is at least one tool call in the last assistant message;
|
|
3166
|
+
* a text-only response has nothing to auto-send.
|
|
3167
|
+
*/
|
|
3168
|
+
private shouldAutoSend;
|
|
3169
|
+
/**
|
|
3170
|
+
* Get current messages
|
|
3171
|
+
*/
|
|
3172
|
+
getMessages(): Array<UIMessage<TTools>>;
|
|
3173
|
+
/**
|
|
3174
|
+
* True when an interrupt (or another direct send) claimed the client during
|
|
3175
|
+
* a drain. Read via a method so cross-await mutations are not constant-folded
|
|
3176
|
+
* by control-flow analysis.
|
|
3177
|
+
*/
|
|
3178
|
+
private shouldAbortMessageQueueDrain;
|
|
3179
|
+
/**
|
|
3180
|
+
* Deliver queued messages after a successful settle.
|
|
3181
|
+
* - `batch`: merge everything currently queued into one send, looping so
|
|
3182
|
+
* messages enqueued during that batch stream are not stranded.
|
|
3183
|
+
* - `fifo`: walk the queue in a loop, one stream at a time, until empty
|
|
3184
|
+
* (or until another send claims the client via interrupt).
|
|
3185
|
+
*
|
|
3186
|
+
* Uses `deliverMessage` directly so drains do not re-enter `sendMessage`'s
|
|
3187
|
+
* busy/queue policy (which would re-queue items and strand the rest).
|
|
3188
|
+
*/
|
|
3189
|
+
private drainQueue;
|
|
3190
|
+
/**
|
|
3191
|
+
* Drop any in-flight send claim and discard pending queued messages
|
|
3192
|
+
* (stop / error / clear / unsubscribe / reload).
|
|
3193
|
+
*/
|
|
3194
|
+
private discardPendingSends;
|
|
3195
|
+
/**
|
|
3196
|
+
* Get the current send queue (messages held while a stream was in flight).
|
|
3197
|
+
*/
|
|
3198
|
+
getQueue(): Array<QueuedMessage>;
|
|
3199
|
+
private emitQueueChange;
|
|
3200
|
+
/**
|
|
3201
|
+
* Remove a queued message by id before it drains.
|
|
3202
|
+
*/
|
|
3203
|
+
cancelQueued(id: string): void;
|
|
3204
|
+
/**
|
|
3205
|
+
* Discard all pending queued messages (stop / error / clear / unsubscribe /
|
|
3206
|
+
* reload). Does not send them. Emits `onQueueChange([])` when anything was
|
|
3207
|
+
* removed.
|
|
3208
|
+
*/
|
|
3209
|
+
private flushQueue;
|
|
3210
|
+
/**
|
|
3211
|
+
* Get loading state
|
|
3212
|
+
*/
|
|
3213
|
+
getIsLoading(): boolean;
|
|
3214
|
+
/**
|
|
3215
|
+
* Get current status
|
|
3216
|
+
*/
|
|
3217
|
+
getStatus(): ChatClientState;
|
|
3218
|
+
/**
|
|
3219
|
+
* Get whether the subscription loop is active
|
|
3220
|
+
*/
|
|
3221
|
+
getIsSubscribed(): boolean;
|
|
3222
|
+
/**
|
|
3223
|
+
* Get current connection lifecycle status
|
|
3224
|
+
*/
|
|
3225
|
+
getConnectionStatus(): ConnectionStatus;
|
|
3226
|
+
/**
|
|
3227
|
+
* Whether the shared session is actively generating.
|
|
3228
|
+
* Derived from stream run events (RUN_STARTED / RUN_FINISHED / RUN_ERROR).
|
|
3229
|
+
* Unlike `isLoading` (request-local), this reflects shared generation
|
|
3230
|
+
* activity visible to all subscribers (e.g. across tabs/devices).
|
|
3231
|
+
*/
|
|
3232
|
+
getSessionGenerating(): boolean;
|
|
3233
|
+
/**
|
|
3234
|
+
* Get current error
|
|
3235
|
+
*/
|
|
3236
|
+
getError(): Error | undefined;
|
|
3237
|
+
/**
|
|
3238
|
+
* Manually set messages
|
|
3239
|
+
*/
|
|
3240
|
+
setMessagesManually(messages: Array<UIMessage<TTools>>): void;
|
|
3241
|
+
/**
|
|
3242
|
+
* Update options refs (for use in React hooks to avoid recreating client)
|
|
3243
|
+
*/
|
|
3244
|
+
updateOptions(options: ChatClientUpdateOptionsWithoutContext<TTools>): void;
|
|
3245
|
+
updateOptions(options: ChatClientUpdateOptionsWithoutContext<TTools> & Pick<ChatClientOptions<TTools, TContext>, 'context'>): void;
|
|
3246
|
+
dispose(): void;
|
|
3247
|
+
}
|
|
3248
|
+
//#endregion
|
|
3249
|
+
//#region src/lib/types.d.ts
|
|
3250
|
+
interface StandardSchemaV1<Input = unknown, Output = Input> {
|
|
3251
|
+
readonly "~standard": {
|
|
3252
|
+
readonly version: 1;
|
|
3253
|
+
readonly vendor: string;
|
|
3254
|
+
readonly validate: (value: unknown) => unknown; /** Type-level only; the spec keeps it undefined at runtime. */
|
|
3255
|
+
readonly types?: {
|
|
3256
|
+
readonly input: Input;
|
|
3257
|
+
readonly output: Output;
|
|
3258
|
+
} | undefined;
|
|
3259
|
+
};
|
|
3260
|
+
}
|
|
3261
|
+
/**
|
|
3262
|
+
* Input type `defineTool`/`defineWidget` derive from a `parameters` schema: a Standard Schema's
|
|
3263
|
+
* validated output, or untyped props for a plain JSON Schema, which nothing validates in the browser.
|
|
3264
|
+
*/
|
|
3265
|
+
type InferParameters<S extends ParametersSchema> = S extends StandardSchemaV1<any, infer O> ? O : Record<string, unknown>;
|
|
3266
|
+
/** A plain JSON Schema object, the same shape tool definitions use for their parameters. */
|
|
3267
|
+
interface JsonSchemaObject {
|
|
3268
|
+
type: "object";
|
|
3269
|
+
properties?: Record<string, unknown>;
|
|
3270
|
+
required?: string[];
|
|
3271
|
+
[keyword: string]: unknown;
|
|
3272
|
+
}
|
|
3273
|
+
/** Schema of the input the agent supplies to a widget or tool, like a tool definition's parameters. */
|
|
3274
|
+
type ParametersSchema = StandardSchemaV1 | JsonSchemaObject;
|
|
3275
|
+
interface WidgetDefinition {
|
|
3276
|
+
/** Tells the agent what the widget shows so it can decide when to render it. */
|
|
3277
|
+
description: string;
|
|
3278
|
+
/**
|
|
3279
|
+
* Forwarded to the agent as JSON Schema. Only a Standard Schema also validates the
|
|
3280
|
+
* props before `render` runs; with a plain JSON Schema, treat the props as untrusted.
|
|
3281
|
+
*/
|
|
3282
|
+
parameters?: ParametersSchema;
|
|
3283
|
+
/**
|
|
3284
|
+
* Draws the widget with the agent-chosen props into `container`, a light-DOM child of
|
|
3285
|
+
* the mount target. May return a cleanup, called before a re-render and on unmount.
|
|
3286
|
+
*/
|
|
3287
|
+
render: (props: Record<string, unknown>, container: HTMLElement) => (() => void) | void;
|
|
3288
|
+
}
|
|
3289
|
+
interface ToolDefinition {
|
|
3290
|
+
/** Tells the agent what the tool does so it can decide when to call it. */
|
|
3291
|
+
description: string;
|
|
3292
|
+
/**
|
|
3293
|
+
* Forwarded verbatim as the tool definition's metadata. A string `title` labels the tool's
|
|
3294
|
+
* transcript entry instead of its registry name (`refresh_invoices` reads as "Refresh invoices").
|
|
3295
|
+
*/
|
|
3296
|
+
metadata?: Record<string, unknown> | undefined;
|
|
3297
|
+
/**
|
|
3298
|
+
* Forwarded to the agent as JSON Schema. Only a Standard Schema also validates the
|
|
3299
|
+
* input before `execute` runs; with a plain JSON Schema, treat the input as untrusted.
|
|
3300
|
+
*/
|
|
3301
|
+
parameters?: ParametersSchema;
|
|
3302
|
+
/**
|
|
3303
|
+
* Runs in the host page with the agent-chosen input. The resolved value is returned
|
|
3304
|
+
* to the agent as the tool result; a thrown error is returned as a tool error.
|
|
3305
|
+
*/
|
|
3306
|
+
execute: (input: Record<string, unknown>) => unknown | Promise<unknown>;
|
|
3307
|
+
}
|
|
3308
|
+
//#endregion
|
|
3309
|
+
//#region src/lib/debug.d.ts
|
|
3310
|
+
declare const CATEGORY_COLORS: {
|
|
3311
|
+
readonly mount: "#7c3aed";
|
|
3312
|
+
readonly auth: "#be185d";
|
|
3313
|
+
readonly theme: "#8b5cf6";
|
|
3314
|
+
readonly send: "#2563eb";
|
|
3315
|
+
readonly run: "#0891b2";
|
|
3316
|
+
readonly stream: "#0e7490";
|
|
3317
|
+
readonly text: "#16a34a";
|
|
3318
|
+
readonly reasoning: "#64748b";
|
|
3319
|
+
readonly tool: "#d97706";
|
|
3320
|
+
readonly widget: "#db2777";
|
|
3321
|
+
readonly attachment: "#0d9488";
|
|
3322
|
+
readonly sandbox: "#0369a1";
|
|
3323
|
+
readonly questionnaire: "#9333ea";
|
|
3324
|
+
readonly status: "#475569";
|
|
3325
|
+
readonly error: "#dc2626";
|
|
3326
|
+
};
|
|
3327
|
+
/** Category of a debug line, each with its own badge color; a typo fails the typecheck. */
|
|
3328
|
+
type DebugCategory = keyof typeof CATEGORY_COLORS;
|
|
3329
|
+
/** Logs one debug line: a colored category badge, a summary, and the full data. */
|
|
3330
|
+
type DebugLogger = (category: DebugCategory, summary: string, data?: unknown) => void;
|
|
3331
|
+
//#endregion
|
|
3332
|
+
//#region src/core/types.d.ts
|
|
3333
|
+
interface RenderWidgetInput {
|
|
3334
|
+
/** Key into the `widgets` object passed at mount. */
|
|
3335
|
+
widget: string;
|
|
3336
|
+
props?: Record<string, unknown>;
|
|
3337
|
+
}
|
|
3338
|
+
/** Sandbox provisioning progress, as the endpoint's CUSTOM status event reports it. */
|
|
3339
|
+
type SandboxStatus = "starting" | "ready" | "error";
|
|
3340
|
+
/** One file the agent wrote into the sandbox, read back out of its own tool call. */
|
|
3341
|
+
interface SandboxFileWrite {
|
|
3342
|
+
toolCallId: string;
|
|
3343
|
+
/** Absolute path in the sandbox, which is also what one file is identified by. */
|
|
3344
|
+
path: string;
|
|
3345
|
+
/** The same path as a row should show it: workspace-relative when the endpoint said so. */
|
|
3346
|
+
label: string;
|
|
3347
|
+
content: string;
|
|
3348
|
+
lines: number;
|
|
3349
|
+
/** False while the content is still streaming, or if the write was refused. */
|
|
3350
|
+
written: boolean;
|
|
3351
|
+
}
|
|
3352
|
+
/** One command the agent ran in the sandbox, with whatever of its result has arrived. */
|
|
3353
|
+
interface SandboxCommandRun {
|
|
3354
|
+
toolCallId: string;
|
|
3355
|
+
command: string;
|
|
3356
|
+
cwd?: string | undefined;
|
|
3357
|
+
/** Absent while the command is still running, and when it timed out. */
|
|
3358
|
+
exitCode?: number | undefined;
|
|
3359
|
+
/** Combined output on providers whose blocking exec has no separate stderr channel. */
|
|
3360
|
+
stdout: string;
|
|
3361
|
+
stderr: string;
|
|
3362
|
+
durationMs?: number | undefined;
|
|
3363
|
+
timedOut: boolean;
|
|
3364
|
+
/** The endpoint elided the middle of the output to keep the run bounded. */
|
|
3365
|
+
truncated: boolean;
|
|
3366
|
+
finished: boolean;
|
|
3367
|
+
}
|
|
3368
|
+
/** One file the agent published for the user, with the ticket its download is authorized by. */
|
|
3369
|
+
interface SandboxArtifact {
|
|
3370
|
+
toolCallId: string;
|
|
3371
|
+
path: string;
|
|
3372
|
+
label: string;
|
|
3373
|
+
mimeType: string | undefined;
|
|
3374
|
+
size: number | undefined;
|
|
3375
|
+
/** Capability the files endpoint accepts in its query; the whole download authorization. */
|
|
3376
|
+
ticket: string | undefined;
|
|
3377
|
+
published: boolean;
|
|
3378
|
+
}
|
|
3379
|
+
/** Everything the sandbox did in this conversation, derived from the transcript. */
|
|
3380
|
+
interface SandboxActivity {
|
|
3381
|
+
/** Latest write per path, in the order the paths were first written. */
|
|
3382
|
+
files: SandboxFileWrite[];
|
|
3383
|
+
commands: SandboxCommandRun[];
|
|
3384
|
+
}
|
|
3385
|
+
//#endregion
|
|
3386
|
+
//#region src/core/agent-tools.d.ts
|
|
3387
|
+
type RenderWidget = (input: RenderWidgetInput, toolCallId: string) => Promise<{
|
|
3388
|
+
widget: string;
|
|
3389
|
+
rendered: boolean;
|
|
3390
|
+
}>;
|
|
3391
|
+
/** What declaring a widget to the agent needs; `render` stays with whoever draws it. */
|
|
3392
|
+
type WidgetDeclaration = Pick<WidgetDefinition, "description" | "parameters">;
|
|
3393
|
+
/** The full tool set declared to the agent; `render_widget` only when widgets are registered. */
|
|
3394
|
+
declare function buildAgentTools(widgets: Record<string, WidgetDeclaration>, hostTools: Record<string, ToolDefinition>, renderWidget: RenderWidget, debug?: DebugLogger): ((ClientTool<{
|
|
3395
|
+
type: "object";
|
|
3396
|
+
properties: {
|
|
3397
|
+
widget: {
|
|
3398
|
+
type: string;
|
|
3399
|
+
enum: string[];
|
|
3400
|
+
description: string;
|
|
3401
|
+
};
|
|
3402
|
+
props: {
|
|
3403
|
+
type: string;
|
|
3404
|
+
description: string;
|
|
3405
|
+
};
|
|
3406
|
+
};
|
|
3407
|
+
required: string[];
|
|
3408
|
+
}, undefined, "render_widget", unknown, false, undefined> & {
|
|
3409
|
+
inputSchema: {
|
|
3410
|
+
type: "object";
|
|
3411
|
+
properties: {
|
|
3412
|
+
widget: {
|
|
3413
|
+
type: string;
|
|
3414
|
+
enum: string[];
|
|
3415
|
+
description: string;
|
|
3416
|
+
};
|
|
3417
|
+
props: {
|
|
3418
|
+
type: string;
|
|
3419
|
+
description: string;
|
|
3420
|
+
};
|
|
3421
|
+
};
|
|
3422
|
+
required: string[];
|
|
3423
|
+
};
|
|
3424
|
+
outputSchema: undefined;
|
|
3425
|
+
approvalSchema: undefined;
|
|
3426
|
+
}) | (ClientTool<{
|
|
3427
|
+
type: "object";
|
|
3428
|
+
properties: {
|
|
3429
|
+
items: {
|
|
3430
|
+
type: string;
|
|
3431
|
+
minItems: number;
|
|
3432
|
+
description: string;
|
|
3433
|
+
items: {
|
|
3434
|
+
type: string;
|
|
3435
|
+
properties: {
|
|
3436
|
+
name: {
|
|
3437
|
+
type: string;
|
|
3438
|
+
description: string;
|
|
3439
|
+
};
|
|
3440
|
+
title: {
|
|
3441
|
+
type: string;
|
|
3442
|
+
description: string;
|
|
3443
|
+
};
|
|
3444
|
+
description: {
|
|
3445
|
+
type: string;
|
|
3446
|
+
description: string;
|
|
3447
|
+
};
|
|
3448
|
+
required: {
|
|
3449
|
+
type: string;
|
|
3450
|
+
description: string;
|
|
3451
|
+
};
|
|
3452
|
+
multiple: {
|
|
3453
|
+
type: string;
|
|
3454
|
+
description: string;
|
|
3455
|
+
};
|
|
3456
|
+
choices: {
|
|
3457
|
+
type: string;
|
|
3458
|
+
minItems: number;
|
|
3459
|
+
items: {
|
|
3460
|
+
type: string;
|
|
3461
|
+
properties: {
|
|
3462
|
+
value: {
|
|
3463
|
+
type: string;
|
|
3464
|
+
};
|
|
3465
|
+
label: {
|
|
3466
|
+
type: string;
|
|
3467
|
+
};
|
|
3468
|
+
description: {
|
|
3469
|
+
type: string;
|
|
3470
|
+
};
|
|
3471
|
+
};
|
|
3472
|
+
required: string[];
|
|
3473
|
+
};
|
|
3474
|
+
};
|
|
3475
|
+
input: {
|
|
3476
|
+
type: string;
|
|
3477
|
+
description: string;
|
|
3478
|
+
properties: {
|
|
3479
|
+
label: {
|
|
3480
|
+
type: string;
|
|
3481
|
+
};
|
|
3482
|
+
placeholder: {
|
|
3483
|
+
type: string;
|
|
3484
|
+
};
|
|
3485
|
+
};
|
|
3486
|
+
required: string[];
|
|
3487
|
+
};
|
|
3488
|
+
};
|
|
3489
|
+
required: string[];
|
|
3490
|
+
};
|
|
3491
|
+
};
|
|
3492
|
+
};
|
|
3493
|
+
required: string[];
|
|
3494
|
+
}, undefined, "ask_questionnaire", unknown, false, undefined> & {
|
|
3495
|
+
inputSchema: {
|
|
3496
|
+
type: "object";
|
|
3497
|
+
properties: {
|
|
3498
|
+
items: {
|
|
3499
|
+
type: string;
|
|
3500
|
+
minItems: number;
|
|
3501
|
+
description: string;
|
|
3502
|
+
items: {
|
|
3503
|
+
type: string;
|
|
3504
|
+
properties: {
|
|
3505
|
+
name: {
|
|
3506
|
+
type: string;
|
|
3507
|
+
description: string;
|
|
3508
|
+
};
|
|
3509
|
+
title: {
|
|
3510
|
+
type: string;
|
|
3511
|
+
description: string;
|
|
3512
|
+
};
|
|
3513
|
+
description: {
|
|
3514
|
+
type: string;
|
|
3515
|
+
description: string;
|
|
3516
|
+
};
|
|
3517
|
+
required: {
|
|
3518
|
+
type: string;
|
|
3519
|
+
description: string;
|
|
3520
|
+
};
|
|
3521
|
+
multiple: {
|
|
3522
|
+
type: string;
|
|
3523
|
+
description: string;
|
|
3524
|
+
};
|
|
3525
|
+
choices: {
|
|
3526
|
+
type: string;
|
|
3527
|
+
minItems: number;
|
|
3528
|
+
items: {
|
|
3529
|
+
type: string;
|
|
3530
|
+
properties: {
|
|
3531
|
+
value: {
|
|
3532
|
+
type: string;
|
|
3533
|
+
};
|
|
3534
|
+
label: {
|
|
3535
|
+
type: string;
|
|
3536
|
+
};
|
|
3537
|
+
description: {
|
|
3538
|
+
type: string;
|
|
3539
|
+
};
|
|
3540
|
+
};
|
|
3541
|
+
required: string[];
|
|
3542
|
+
};
|
|
3543
|
+
};
|
|
3544
|
+
input: {
|
|
3545
|
+
type: string;
|
|
3546
|
+
description: string;
|
|
3547
|
+
properties: {
|
|
3548
|
+
label: {
|
|
3549
|
+
type: string;
|
|
3550
|
+
};
|
|
3551
|
+
placeholder: {
|
|
3552
|
+
type: string;
|
|
3553
|
+
};
|
|
3554
|
+
};
|
|
3555
|
+
required: string[];
|
|
3556
|
+
};
|
|
3557
|
+
};
|
|
3558
|
+
required: string[];
|
|
3559
|
+
};
|
|
3560
|
+
};
|
|
3561
|
+
};
|
|
3562
|
+
required: string[];
|
|
3563
|
+
};
|
|
3564
|
+
outputSchema: undefined;
|
|
3565
|
+
approvalSchema: undefined;
|
|
3566
|
+
}) | (ClientTool<SchemaInput, undefined, string, unknown, false, undefined> & {
|
|
3567
|
+
inputSchema: SchemaInput;
|
|
3568
|
+
outputSchema: undefined;
|
|
3569
|
+
approvalSchema: undefined;
|
|
3570
|
+
}))[];
|
|
3571
|
+
//#endregion
|
|
3572
|
+
//#region src/core/auth.d.ts
|
|
3573
|
+
type ChatAuthenticationState = {
|
|
3574
|
+
status: "loading";
|
|
3575
|
+
} | {
|
|
3576
|
+
status: "ready";
|
|
3577
|
+
} | {
|
|
3578
|
+
status: "error";
|
|
3579
|
+
error: Error;
|
|
3580
|
+
};
|
|
3581
|
+
//#endregion
|
|
3582
|
+
//#region src/core/session.d.ts
|
|
3583
|
+
/** A widget render the agent requested, handed to the host's `onRenderWidget`. */
|
|
3584
|
+
interface WidgetRenderRequest {
|
|
3585
|
+
widget: string;
|
|
3586
|
+
props: Record<string, unknown>;
|
|
3587
|
+
/** Keys the render: a repeat of the same call replaces its own render, not another's. */
|
|
3588
|
+
toolCallId: string;
|
|
3589
|
+
}
|
|
3590
|
+
interface AstralBeamChatCoreOptions {
|
|
3591
|
+
/** Public ID of the organization-owned agent; omitted, the organization's default answers. */
|
|
3592
|
+
agentId?: string | undefined;
|
|
3593
|
+
/** Base URL of the AstralBeam API; `/chat` hangs off it. Default the hosted cloud. */
|
|
3594
|
+
apiUrl?: string | undefined;
|
|
3595
|
+
/** The application endpoint that mints short-lived chat JWTs. Default `/api/astralbeam/token`. */
|
|
3596
|
+
authTokenUrl?: string | undefined;
|
|
3597
|
+
/** Host tools the agent can call; `execute` runs wherever this session lives. */
|
|
3598
|
+
tools?: Record<string, ToolDefinition> | undefined;
|
|
3599
|
+
/** Widgets declared to the agent; `onRenderWidget` is asked to draw them. */
|
|
3600
|
+
widgets?: Record<string, WidgetDeclaration> | undefined;
|
|
3601
|
+
/** Draws an agent-requested widget however the host wants; may return a cleanup. */
|
|
3602
|
+
onRenderWidget?: ((request: WidgetRenderRequest) => (() => void) | void) | undefined;
|
|
3603
|
+
/** Logs every action to the console and asks the endpoint to log its side too. */
|
|
3604
|
+
debug?: boolean | undefined;
|
|
3605
|
+
}
|
|
3606
|
+
interface AstralBeamChatState {
|
|
3607
|
+
messages: UIMessage[];
|
|
3608
|
+
/** The underlying chat client status: "ready", "submitted", "streaming", or "error". */
|
|
3609
|
+
status: ChatClientState;
|
|
3610
|
+
error: Error | undefined;
|
|
3611
|
+
auth: ChatAuthenticationState;
|
|
3612
|
+
/** What the resolved agent grants; the UI should render only that. */
|
|
3613
|
+
capabilities: {
|
|
3614
|
+
attachments: boolean;
|
|
3615
|
+
};
|
|
3616
|
+
sandboxStatus: SandboxStatus | undefined;
|
|
3617
|
+
sandbox: SandboxActivity;
|
|
3618
|
+
}
|
|
3619
|
+
interface AstralBeamChatCore {
|
|
3620
|
+
getState: () => AstralBeamChatState;
|
|
3621
|
+
/** Notifies on every state change; returns the unsubscribe. */
|
|
3622
|
+
subscribe: (listener: () => void) => () => void;
|
|
3623
|
+
/** Sends a message, first settling any dangling tool calls so the run can proceed. */
|
|
3624
|
+
sendMessage: (content: string | MultimodalContent) => Promise<void>;
|
|
3625
|
+
/** Resolves a client tool call the host executed itself (a questionnaire, an approval). */
|
|
3626
|
+
addToolResult: ChatClient["addToolResult"];
|
|
3627
|
+
/** Stops the in-flight generation; the transcript keeps what already streamed. */
|
|
3628
|
+
stop: () => void;
|
|
3629
|
+
/** Re-runs the last exchange. */
|
|
3630
|
+
reload: () => Promise<void>;
|
|
3631
|
+
/** Clears the conversation and disposes live widget renders. */
|
|
3632
|
+
reset: () => void;
|
|
3633
|
+
/** Tears the session down: the connection, authentication, and widget renders. */
|
|
3634
|
+
dispose: () => void;
|
|
3635
|
+
}
|
|
3636
|
+
/**
|
|
3637
|
+
* The headless AstralBeam chat session: authentication, transport, the tool protocol, and
|
|
3638
|
+
* transcript state, with no markup. The drop-in widget is one consumer; a host that owns its
|
|
3639
|
+
* whole UI is another.
|
|
3640
|
+
*/
|
|
3641
|
+
declare function createAstralBeamChat(options: AstralBeamChatCoreOptions): AstralBeamChatCore;
|
|
3642
|
+
//#endregion
|
|
3643
|
+
//#region src/core/messages.d.ts
|
|
3644
|
+
declare function isSettledToolCall(part: {
|
|
3645
|
+
state: string;
|
|
3646
|
+
output?: unknown;
|
|
3647
|
+
}): boolean;
|
|
3648
|
+
declare function lastPartInProgress(messages: UIMessage[]): boolean;
|
|
3649
|
+
declare function hasPendingToolRun(messages: UIMessage[], toolNames: ReadonlySet<string>): boolean;
|
|
3650
|
+
//#endregion
|
|
3651
|
+
//#region src/core/sandbox.d.ts
|
|
3652
|
+
/**
|
|
3653
|
+
* Everything the widget knows about the sandbox is read back out of the transcript: a
|
|
3654
|
+
* `sandbox_write_file` call carries the file in its own input, a `sandbox_run_command` call the log
|
|
3655
|
+
* in its output. One source of truth, so a reset clears it and a re-render cannot double-count.
|
|
3656
|
+
* Tool input is partially parsed JSON while it streams, so every field is checked before it is read.
|
|
3657
|
+
*/
|
|
3658
|
+
type ToolCallPart = Extract<MessagePart, {
|
|
3659
|
+
type: "tool-call";
|
|
3660
|
+
}>;
|
|
3661
|
+
declare function isSandboxTool(name: string): boolean;
|
|
3662
|
+
/** The agent asked for something the endpoint would not do; its reason is the only useful output. */
|
|
3663
|
+
declare function sandboxRefusal(part: ToolCallPart): string | undefined;
|
|
3664
|
+
/** A `sandbox_write_file` call, readable while its content is still streaming in. */
|
|
3665
|
+
declare function readSandboxFileWrite(part: ToolCallPart): SandboxFileWrite | undefined;
|
|
3666
|
+
/** A `sandbox_publish_artifact` call whose output carries the download ticket. */
|
|
3667
|
+
declare function readSandboxArtifact(part: ToolCallPart): SandboxArtifact | undefined;
|
|
3668
|
+
/** A `sandbox_run_command` call. `stdout` holds combined output on providers with no stderr. */
|
|
3669
|
+
declare function readSandboxCommandRun(part: ToolCallPart): SandboxCommandRun | undefined;
|
|
3670
|
+
/**
|
|
3671
|
+
* The whole conversation's sandbox work, for the panel. A path written more than once appears
|
|
3672
|
+
* once, holding its latest content, because the panel answers "what is in the sandbox now".
|
|
3673
|
+
*/
|
|
3674
|
+
declare function collectSandboxActivity(messages: UIMessage[]): SandboxActivity;
|
|
3675
|
+
/** The one-line summary a finished command carries, in its row's label and under its log. */
|
|
3676
|
+
declare function describeSandboxCommandRun(run: SandboxCommandRun): string;
|
|
3677
|
+
//#endregion
|
|
3678
|
+
//#region src/core/protocol.d.ts
|
|
3679
|
+
declare const RENDER_WIDGET_TOOL = "render_widget";
|
|
3680
|
+
declare const ASK_QUESTIONNAIRE_TOOL = "ask_questionnaire";
|
|
3681
|
+
declare const SANDBOX_WRITE_FILE_TOOL = "sandbox_write_file";
|
|
3682
|
+
declare const SANDBOX_PUBLISH_ARTIFACT_TOOL = "sandbox_publish_artifact";
|
|
3683
|
+
declare const SANDBOX_READ_FILE_TOOL = "sandbox_read_file";
|
|
3684
|
+
declare const SANDBOX_LIST_FILES_TOOL = "sandbox_list_files";
|
|
3685
|
+
declare const SANDBOX_RUN_COMMAND_TOOL = "sandbox_run_command";
|
|
3686
|
+
/** CUSTOM stream event carrying sandbox provisioning progress, which no tool result can report. */
|
|
3687
|
+
declare const SANDBOX_STATUS_EVENT = "astralbeam.sandbox.status";
|
|
3688
|
+
//#endregion
|
|
3689
|
+
//#region src/lib/define.d.ts
|
|
3690
|
+
interface TypedToolDefinition<S extends ParametersSchema = JsonSchemaObject> {
|
|
3691
|
+
description: string;
|
|
3692
|
+
metadata?: Record<string, unknown> | undefined;
|
|
3693
|
+
parameters?: S;
|
|
3694
|
+
execute: (input: InferParameters<S>) => unknown | Promise<unknown>;
|
|
3695
|
+
}
|
|
3696
|
+
interface TypedWidgetDefinition<S extends ParametersSchema = JsonSchemaObject> {
|
|
3697
|
+
description: string;
|
|
3698
|
+
parameters?: S;
|
|
3699
|
+
render: (props: InferParameters<S>, container: HTMLElement) => (() => void) | void;
|
|
3700
|
+
}
|
|
3701
|
+
/** Declares a host tool; a Standard Schema `parameters` types (and validates) `execute`'s input. */
|
|
3702
|
+
declare function defineTool<const S extends ParametersSchema = JsonSchemaObject>(tool: TypedToolDefinition<S>): ToolDefinition;
|
|
3703
|
+
/** Declares a host widget; a Standard Schema `parameters` types (and validates) `render`'s props. */
|
|
3704
|
+
declare function defineWidget<const S extends ParametersSchema = JsonSchemaObject>(widget: TypedWidgetDefinition<S>): WidgetDefinition;
|
|
3705
|
+
//#endregion
|
|
3706
|
+
export { SandboxActivity as A, AstralBeamChatState as C, WidgetDeclaration as D, ChatAuthenticationState as E, InferParameters as F, JsonSchemaObject as I, ParametersSchema as L, SandboxCommandRun as M, SandboxFileWrite as N, buildAgentTools as O, SandboxStatus as P, StandardSchemaV1 as R, AstralBeamChatCoreOptions as S, createAstralBeamChat as T, sandboxRefusal as _, SANDBOX_LIST_FILES_TOOL as a, lastPartInProgress as b, SANDBOX_RUN_COMMAND_TOOL as c, collectSandboxActivity as d, describeSandboxCommandRun as f, readSandboxFileWrite as g, readSandboxCommandRun as h, RENDER_WIDGET_TOOL as i, SandboxArtifact as j, RenderWidgetInput as k, SANDBOX_STATUS_EVENT as l, readSandboxArtifact as m, defineWidget as n, SANDBOX_PUBLISH_ARTIFACT_TOOL as o, isSandboxTool as p, ASK_QUESTIONNAIRE_TOOL as r, SANDBOX_READ_FILE_TOOL as s, defineTool as t, SANDBOX_WRITE_FILE_TOOL as u, hasPendingToolRun as v, WidgetRenderRequest as w, AstralBeamChatCore as x, isSettledToolCall as y, ToolDefinition as z };
|