@tanstack/ai 0.36.0 → 0.37.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.
Files changed (205) hide show
  1. package/dist/esm/activities/chat/adapter.d.ts +163 -0
  2. package/dist/esm/activities/chat/adapter.js +17 -0
  3. package/dist/esm/activities/chat/adapter.js.map +1 -0
  4. package/dist/esm/activities/chat/agent-loop-strategies.d.ts +59 -0
  5. package/dist/esm/activities/chat/agent-loop-strategies.js +23 -0
  6. package/dist/esm/activities/chat/agent-loop-strategies.js.map +1 -0
  7. package/dist/esm/activities/chat/index.d.ts +270 -0
  8. package/dist/esm/activities/chat/index.js +1724 -0
  9. package/dist/esm/activities/chat/index.js.map +1 -0
  10. package/dist/esm/activities/chat/mcp/manager.d.ts +25 -0
  11. package/dist/esm/activities/chat/mcp/manager.js +71 -0
  12. package/dist/esm/activities/chat/mcp/manager.js.map +1 -0
  13. package/dist/esm/activities/chat/mcp/types.d.ts +56 -0
  14. package/dist/esm/activities/chat/messages.d.ts +78 -0
  15. package/dist/esm/activities/chat/messages.js +374 -0
  16. package/dist/esm/activities/chat/messages.js.map +1 -0
  17. package/dist/esm/activities/chat/middleware/builder.d.ts +46 -0
  18. package/dist/esm/activities/chat/middleware/builder.js +17 -0
  19. package/dist/esm/activities/chat/middleware/builder.js.map +1 -0
  20. package/dist/esm/activities/chat/middleware/capabilities.d.ts +93 -0
  21. package/dist/esm/activities/chat/middleware/capabilities.js +45 -0
  22. package/dist/esm/activities/chat/middleware/capabilities.js.map +1 -0
  23. package/dist/esm/activities/chat/middleware/compose.d.ts +87 -0
  24. package/dist/esm/activities/chat/middleware/compose.js +510 -0
  25. package/dist/esm/activities/chat/middleware/compose.js.map +1 -0
  26. package/dist/esm/activities/chat/middleware/define.d.ts +20 -0
  27. package/dist/esm/activities/chat/middleware/define.js +7 -0
  28. package/dist/esm/activities/chat/middleware/define.js.map +1 -0
  29. package/dist/esm/activities/chat/middleware/index.d.ts +10 -0
  30. package/dist/esm/activities/chat/middleware/tool-cache-middleware.d.ts +89 -0
  31. package/dist/esm/activities/chat/middleware/tool-cache-middleware.js +76 -0
  32. package/dist/esm/activities/chat/middleware/tool-cache-middleware.js.map +1 -0
  33. package/dist/esm/activities/chat/middleware/types.d.ts +405 -0
  34. package/dist/esm/activities/chat/middleware/validate.d.ts +19 -0
  35. package/dist/esm/activities/chat/middleware/validate.js +30 -0
  36. package/dist/esm/activities/chat/middleware/validate.js.map +1 -0
  37. package/dist/esm/activities/chat/runtime-context-types.d.ts +43 -0
  38. package/dist/esm/activities/chat/stream/index.d.ts +11 -0
  39. package/dist/esm/activities/chat/stream/json-parser.d.ts +38 -0
  40. package/dist/esm/activities/chat/stream/json-parser.js +28 -0
  41. package/dist/esm/activities/chat/stream/json-parser.js.map +1 -0
  42. package/dist/esm/activities/chat/stream/message-updaters.d.ts +81 -0
  43. package/dist/esm/activities/chat/stream/message-updaters.js +253 -0
  44. package/dist/esm/activities/chat/stream/message-updaters.js.map +1 -0
  45. package/dist/esm/activities/chat/stream/processor.d.ts +439 -0
  46. package/dist/esm/activities/chat/stream/processor.js +1426 -0
  47. package/dist/esm/activities/chat/stream/processor.js.map +1 -0
  48. package/dist/esm/activities/chat/stream/strategies.d.ts +43 -0
  49. package/dist/esm/activities/chat/stream/strategies.js +54 -0
  50. package/dist/esm/activities/chat/stream/strategies.js.map +1 -0
  51. package/dist/esm/activities/chat/stream/types.d.ts +90 -0
  52. package/dist/esm/activities/chat/tools/lazy-tool-manager.d.ts +82 -0
  53. package/dist/esm/activities/chat/tools/lazy-tool-manager.js +194 -0
  54. package/dist/esm/activities/chat/tools/lazy-tool-manager.js.map +1 -0
  55. package/dist/esm/activities/chat/tools/lazy-tools.d.ts +15 -0
  56. package/dist/esm/activities/chat/tools/lazy-tools.js +16 -0
  57. package/dist/esm/activities/chat/tools/lazy-tools.js.map +1 -0
  58. package/dist/esm/activities/chat/tools/schema-converter.d.ts +140 -0
  59. package/dist/esm/activities/chat/tools/schema-converter.js +167 -0
  60. package/dist/esm/activities/chat/tools/schema-converter.js.map +1 -0
  61. package/dist/esm/activities/chat/tools/tool-calls.d.ts +140 -0
  62. package/dist/esm/activities/chat/tools/tool-calls.js +512 -0
  63. package/dist/esm/activities/chat/tools/tool-calls.js.map +1 -0
  64. package/dist/esm/activities/chat/tools/tool-definition.d.ts +135 -0
  65. package/dist/esm/activities/chat/tools/tool-definition.js +25 -0
  66. package/dist/esm/activities/chat/tools/tool-definition.js.map +1 -0
  67. package/dist/esm/activities/error-payload.d.ts +30 -0
  68. package/dist/esm/activities/error-payload.js +54 -0
  69. package/dist/esm/activities/error-payload.js.map +1 -0
  70. package/dist/esm/activities/generateAudio/adapter.d.ts +62 -0
  71. package/dist/esm/activities/generateAudio/adapter.js +16 -0
  72. package/dist/esm/activities/generateAudio/adapter.js.map +1 -0
  73. package/dist/esm/activities/generateAudio/index.d.ts +85 -0
  74. package/dist/esm/activities/generateAudio/index.js +114 -0
  75. package/dist/esm/activities/generateAudio/index.js.map +1 -0
  76. package/dist/esm/activities/generateImage/adapter.d.ts +78 -0
  77. package/dist/esm/activities/generateImage/adapter.js +16 -0
  78. package/dist/esm/activities/generateImage/adapter.js.map +1 -0
  79. package/dist/esm/activities/generateImage/index.d.ts +134 -0
  80. package/dist/esm/activities/generateImage/index.js +121 -0
  81. package/dist/esm/activities/generateImage/index.js.map +1 -0
  82. package/dist/esm/activities/generateSpeech/adapter.d.ts +62 -0
  83. package/dist/esm/activities/generateSpeech/adapter.js +16 -0
  84. package/dist/esm/activities/generateSpeech/adapter.js.map +1 -0
  85. package/dist/esm/activities/generateSpeech/index.d.ts +96 -0
  86. package/dist/esm/activities/generateSpeech/index.js +119 -0
  87. package/dist/esm/activities/generateSpeech/index.js.map +1 -0
  88. package/dist/esm/activities/generateTranscription/adapter.d.ts +62 -0
  89. package/dist/esm/activities/generateTranscription/adapter.js +16 -0
  90. package/dist/esm/activities/generateTranscription/adapter.js.map +1 -0
  91. package/dist/esm/activities/generateTranscription/index.d.ts +109 -0
  92. package/dist/esm/activities/generateTranscription/index.js +109 -0
  93. package/dist/esm/activities/generateTranscription/index.js.map +1 -0
  94. package/dist/esm/activities/generateVideo/adapter.d.ts +145 -0
  95. package/dist/esm/activities/generateVideo/adapter.js +30 -0
  96. package/dist/esm/activities/generateVideo/adapter.js.map +1 -0
  97. package/dist/esm/activities/generateVideo/index.d.ts +223 -0
  98. package/dist/esm/activities/generateVideo/index.js +295 -0
  99. package/dist/esm/activities/generateVideo/index.js.map +1 -0
  100. package/dist/esm/activities/generateVideo/snap.d.ts +14 -0
  101. package/dist/esm/activities/generateVideo/snap.js +54 -0
  102. package/dist/esm/activities/generateVideo/snap.js.map +1 -0
  103. package/dist/esm/activities/index.d.ts +27 -0
  104. package/dist/esm/activities/index.js +43 -0
  105. package/dist/esm/activities/index.js.map +1 -0
  106. package/dist/esm/activities/middleware/index.d.ts +2 -0
  107. package/dist/esm/activities/middleware/run.d.ts +20 -0
  108. package/dist/esm/activities/middleware/run.js +42 -0
  109. package/dist/esm/activities/middleware/run.js.map +1 -0
  110. package/dist/esm/activities/middleware/types.d.ts +118 -0
  111. package/dist/esm/activities/stream-generation-result.d.ts +15 -0
  112. package/dist/esm/activities/stream-generation-result.js +49 -0
  113. package/dist/esm/activities/stream-generation-result.js.map +1 -0
  114. package/dist/esm/activities/summarize/adapter.d.ts +74 -0
  115. package/dist/esm/activities/summarize/adapter.js +16 -0
  116. package/dist/esm/activities/summarize/adapter.js.map +1 -0
  117. package/dist/esm/activities/summarize/chat-stream-summarize.d.ts +45 -0
  118. package/dist/esm/activities/summarize/chat-stream-summarize.js +212 -0
  119. package/dist/esm/activities/summarize/chat-stream-summarize.js.map +1 -0
  120. package/dist/esm/activities/summarize/index.d.ts +108 -0
  121. package/dist/esm/activities/summarize/index.js +113 -0
  122. package/dist/esm/activities/summarize/index.js.map +1 -0
  123. package/dist/esm/adapter-internals.d.ts +5 -0
  124. package/dist/esm/adapter-internals.js +10 -0
  125. package/dist/esm/adapter-internals.js.map +1 -0
  126. package/dist/esm/client.d.ts +44 -0
  127. package/dist/esm/client.js +67 -0
  128. package/dist/esm/client.js.map +1 -0
  129. package/dist/esm/extend-adapter.d.ts +152 -0
  130. package/dist/esm/extend-adapter.js +21 -0
  131. package/dist/esm/extend-adapter.js.map +1 -0
  132. package/dist/esm/index.d.ts +45 -0
  133. package/dist/esm/index.js +109 -0
  134. package/dist/esm/index.js.map +1 -0
  135. package/dist/esm/logger/console-logger.d.ts +29 -0
  136. package/dist/esm/logger/console-logger.js +83 -0
  137. package/dist/esm/logger/console-logger.js.map +1 -0
  138. package/dist/esm/logger/internal-logger.d.ts +41 -0
  139. package/dist/esm/logger/internal-logger.js +86 -0
  140. package/dist/esm/logger/internal-logger.js.map +1 -0
  141. package/dist/esm/logger/resolve.d.ts +14 -0
  142. package/dist/esm/logger/resolve.js +54 -0
  143. package/dist/esm/logger/resolve.js.map +1 -0
  144. package/dist/esm/logger/types.d.ts +75 -0
  145. package/dist/esm/middlewares/content-guard.d.ts +77 -0
  146. package/dist/esm/middlewares/content-guard.js +156 -0
  147. package/dist/esm/middlewares/content-guard.js.map +1 -0
  148. package/dist/esm/middlewares/index.d.ts +2 -0
  149. package/dist/esm/middlewares/index.js +7 -0
  150. package/dist/esm/middlewares/index.js.map +1 -0
  151. package/dist/esm/middlewares/otel.d.ts +81 -0
  152. package/dist/esm/middlewares/otel.js +745 -0
  153. package/dist/esm/middlewares/otel.js.map +1 -0
  154. package/dist/esm/middlewares/tool-cache.d.ts +1 -0
  155. package/dist/esm/middlewares/usage-attributes.d.ts +24 -0
  156. package/dist/esm/middlewares/usage-attributes.js +43 -0
  157. package/dist/esm/middlewares/usage-attributes.js.map +1 -0
  158. package/dist/esm/realtime/index.d.ts +28 -0
  159. package/dist/esm/realtime/index.js +8 -0
  160. package/dist/esm/realtime/index.js.map +1 -0
  161. package/dist/esm/realtime/types.d.ts +282 -0
  162. package/dist/esm/stream-to-response.d.ts +102 -0
  163. package/dist/esm/stream-to-response.js +121 -0
  164. package/dist/esm/stream-to-response.js.map +1 -0
  165. package/dist/esm/strip-to-spec-middleware.d.ts +18 -0
  166. package/dist/esm/strip-to-spec-middleware.js +20 -0
  167. package/dist/esm/strip-to-spec-middleware.js.map +1 -0
  168. package/dist/esm/system-prompts.d.ts +66 -0
  169. package/dist/esm/system-prompts.js +23 -0
  170. package/dist/esm/system-prompts.js.map +1 -0
  171. package/dist/esm/tool-registry.d.ts +81 -0
  172. package/dist/esm/tool-registry.js +49 -0
  173. package/dist/esm/tool-registry.js.map +1 -0
  174. package/dist/esm/tools/provider-tool.d.ts +30 -0
  175. package/dist/esm/tools/provider-tool.js +7 -0
  176. package/dist/esm/tools/provider-tool.js.map +1 -0
  177. package/dist/esm/types.d.ts +1594 -0
  178. package/dist/esm/utilities/ag-ui-wire.d.ts +44 -0
  179. package/dist/esm/utilities/ag-ui-wire.js +107 -0
  180. package/dist/esm/utilities/ag-ui-wire.js.map +1 -0
  181. package/dist/esm/utilities/chat-params.d.ts +85 -0
  182. package/dist/esm/utilities/chat-params.js +100 -0
  183. package/dist/esm/utilities/chat-params.js.map +1 -0
  184. package/dist/esm/utilities/errors.d.ts +13 -0
  185. package/dist/esm/utilities/errors.js +22 -0
  186. package/dist/esm/utilities/errors.js.map +1 -0
  187. package/dist/esm/utilities/media-prompt.d.ts +35 -0
  188. package/dist/esm/utilities/media-prompt.js +43 -0
  189. package/dist/esm/utilities/media-prompt.js.map +1 -0
  190. package/dist/esm/utilities/numbers.d.ts +8 -0
  191. package/dist/esm/utilities/numbers.js +12 -0
  192. package/dist/esm/utilities/numbers.js.map +1 -0
  193. package/dist/esm/utilities/sampling-keys.d.ts +20 -0
  194. package/dist/esm/utilities/sampling-keys.js +20 -0
  195. package/dist/esm/utilities/sampling-keys.js.map +1 -0
  196. package/dist/esm/utilities/tool-result.d.ts +21 -0
  197. package/dist/esm/utilities/tool-result.js +37 -0
  198. package/dist/esm/utilities/tool-result.js.map +1 -0
  199. package/dist/esm/utilities/usage.d.ts +31 -0
  200. package/dist/esm/utilities/usage.js +11 -0
  201. package/dist/esm/utilities/usage.js.map +1 -0
  202. package/dist/esm/utils.d.ts +17 -0
  203. package/dist/esm/utils.js +20 -0
  204. package/dist/esm/utils.js.map +1 -0
  205. package/package.json +3 -3
@@ -0,0 +1,163 @@
1
+ import { DefaultMessageMetadataByModality, JSONSchema, Modality, StreamChunk, TextOptions, TokenUsage } from '../../types.js';
2
+ import { CapabilityHandle } from './middleware/capabilities.js';
3
+ /**
4
+ * Configuration for adapter instances
5
+ */
6
+ export interface TextAdapterConfig {
7
+ apiKey?: string;
8
+ baseUrl?: string;
9
+ timeout?: number;
10
+ maxRetries?: number;
11
+ headers?: Record<string, string>;
12
+ }
13
+ /**
14
+ * Options for structured output generation.
15
+ *
16
+ * The internal logger is threaded through `chatOptions.logger` (inherited from
17
+ * `TextOptions`). Adapter implementations must call `logger.request()` before
18
+ * SDK calls, `logger.provider()` for each chunk received, and `logger.errors()`
19
+ * in catch blocks.
20
+ */
21
+ export interface StructuredOutputOptions<TProviderOptions extends object> {
22
+ /** Text options for the request */
23
+ chatOptions: TextOptions<TProviderOptions>;
24
+ /** JSON Schema for structured output - already converted from Zod in the ai layer */
25
+ outputSchema: JSONSchema;
26
+ }
27
+ /**
28
+ * Result from structured output generation
29
+ */
30
+ export interface StructuredOutputResult<T = unknown> {
31
+ /** The parsed data conforming to the schema */
32
+ data: T;
33
+ /** The raw text response from the model before parsing */
34
+ rawText: string;
35
+ /** Token usage information (if provided by the adapter) */
36
+ usage?: TokenUsage;
37
+ }
38
+ /**
39
+ * Text adapter interface with pre-resolved generics.
40
+ *
41
+ * An adapter is created by a provider function: `provider('model')` → `adapter`
42
+ * All type resolution happens at the provider call site, not in this interface.
43
+ *
44
+ * Generic parameters:
45
+ * - TModel: The specific model name (e.g., 'gpt-4o')
46
+ * - TProviderOptions: Provider-specific options for this model (already resolved)
47
+ * - TInputModalities: Supported input modalities for this model (already resolved)
48
+ * - TMessageMetadata: Metadata types for content parts (already resolved)
49
+ * - TToolCapabilities: Tuple of tool-kind strings supported by this model, resolved from `supports.tools`
50
+ * - TToolCallMetadata: Metadata type that round-trips with tool calls (e.g. Gemini's `thoughtSignature`)
51
+ * - TSystemPromptMetadata: Provider-typed metadata accepted on each
52
+ * `systemPrompts[i]` entry (e.g. Anthropic `cache_control`). Defaults to
53
+ * `never` — adapters without per-prompt metadata reject the `metadata`
54
+ * field at the call site.
55
+ */
56
+ export interface TextAdapter<TModel extends string, TProviderOptions extends Record<string, any>, TInputModalities extends ReadonlyArray<Modality>, TMessageMetadataByModality extends DefaultMessageMetadataByModality, TToolCapabilities extends ReadonlyArray<string> = ReadonlyArray<string>, TToolCallMetadata = unknown, TSystemPromptMetadata = never> {
57
+ /** Discriminator for adapter kind */
58
+ readonly kind: 'text';
59
+ /** Provider name identifier (e.g., 'openai', 'anthropic') */
60
+ readonly name: string;
61
+ /** The model this adapter is configured for */
62
+ readonly model: TModel;
63
+ /**
64
+ * Capabilities this adapter requires at runtime. `chat()` validates that the
65
+ * configured middleware provides each one. Model adapters omit this; harness
66
+ * adapters (e.g. a future `claudeCode()`) declare e.g. `[sandboxCapability]`.
67
+ * Runtime access to capabilities from inside the adapter is not yet wired —
68
+ * this is the declaration/validation surface only.
69
+ */
70
+ readonly requires?: ReadonlyArray<CapabilityHandle>;
71
+ /**
72
+ * @internal Type-only properties for inference. Not assigned at runtime.
73
+ */
74
+ '~types': {
75
+ providerOptions: TProviderOptions;
76
+ inputModalities: TInputModalities;
77
+ messageMetadataByModality: TMessageMetadataByModality;
78
+ toolCapabilities: TToolCapabilities;
79
+ toolCallMetadata: TToolCallMetadata;
80
+ systemPromptMetadata: TSystemPromptMetadata;
81
+ };
82
+ /**
83
+ * Stream text completions from the model
84
+ */
85
+ chatStream: (options: TextOptions<TProviderOptions>) => AsyncIterable<StreamChunk>;
86
+ /**
87
+ * Generate structured output using the provider's native structured output API.
88
+ * This method uses stream: false and sends the JSON schema to the provider
89
+ * to ensure the response conforms to the expected structure.
90
+ *
91
+ * @param options - Structured output options containing chat options and JSON schema
92
+ * @returns Promise with the raw data (validation is done in the chat function)
93
+ */
94
+ structuredOutput: (options: StructuredOutputOptions<TProviderOptions>) => Promise<StructuredOutputResult<unknown>>;
95
+ /**
96
+ * Stream structured output using the provider's native streaming structured
97
+ * output API (stream + response_format json_schema in a single request).
98
+ *
99
+ * Optional — adapters without native streaming JSON omit this method and the
100
+ * activity layer synthesizes a stream around the non-streaming
101
+ * `structuredOutput` call.
102
+ *
103
+ * Implementations must emit standard AG-UI lifecycle events (RUN_STARTED,
104
+ * TEXT_MESSAGE_*, RUN_FINISHED) carrying raw JSON text deltas, plus a final
105
+ * `CUSTOM` event named `structured-output.complete` whose `value` is
106
+ * `{ object, raw, reasoning? }`.
107
+ */
108
+ structuredOutputStream?: (options: StructuredOutputOptions<TProviderOptions>) => AsyncIterable<StreamChunk>;
109
+ /**
110
+ * Declares whether the adapter supports combining `tools` and a
111
+ * schema-constrained final answer in a single streaming request.
112
+ *
113
+ * When `true`, the engine wires `outputSchema` into the regular
114
+ * `chatStream()` call and skips the separate `runStructuredFinalization`
115
+ * round-trip. The model's natural final turn carries the
116
+ * schema-constrained JSON text and the engine harvests it from the agent
117
+ * loop's accumulated content.
118
+ *
119
+ * When `false`, `undefined`, or the method is omitted, the engine runs
120
+ * the agent loop without `outputSchema` and then issues a separate
121
+ * `structuredOutput` / `structuredOutputStream` call against the JSON
122
+ * schema for finalization (the legacy path).
123
+ *
124
+ * The method receives the per-call `modelOptions` so providers whose
125
+ * support depends on the resolved upstream model (e.g. OpenRouter) can
126
+ * answer per-request. Most adapters can return a constant.
127
+ */
128
+ supportsCombinedToolsAndSchema?: (modelOptions?: TProviderOptions | undefined) => boolean;
129
+ }
130
+ /**
131
+ * A TextAdapter with any/unknown type parameters.
132
+ * Useful as a constraint in generic functions and interfaces.
133
+ */
134
+ export type AnyTextAdapter = TextAdapter<any, any, any, any, any, any, any>;
135
+ /**
136
+ * Abstract base class for text adapters.
137
+ * Extend this class to implement a text adapter for a specific provider.
138
+ *
139
+ * Generic parameters match TextAdapter - all pre-resolved by the provider function.
140
+ */
141
+ export declare abstract class BaseTextAdapter<TModel extends string, TProviderOptions extends Record<string, any>, TInputModalities extends ReadonlyArray<Modality>, TMessageMetadataByModality extends DefaultMessageMetadataByModality, TToolCapabilities extends ReadonlyArray<string> = ReadonlyArray<string>, TToolCallMetadata = unknown, TSystemPromptMetadata = never> implements TextAdapter<TModel, TProviderOptions, TInputModalities, TMessageMetadataByModality, TToolCapabilities, TToolCallMetadata, TSystemPromptMetadata> {
142
+ readonly kind: "text";
143
+ abstract readonly name: string;
144
+ readonly model: TModel;
145
+ readonly requires?: ReadonlyArray<CapabilityHandle>;
146
+ '~types': {
147
+ providerOptions: TProviderOptions;
148
+ inputModalities: TInputModalities;
149
+ messageMetadataByModality: TMessageMetadataByModality;
150
+ toolCapabilities: TToolCapabilities;
151
+ toolCallMetadata: TToolCallMetadata;
152
+ systemPromptMetadata: TSystemPromptMetadata;
153
+ };
154
+ protected config: TextAdapterConfig;
155
+ constructor(config: TextAdapterConfig | undefined, model: TModel);
156
+ abstract chatStream(options: TextOptions<TProviderOptions>): AsyncIterable<StreamChunk>;
157
+ /**
158
+ * Generate structured output using the provider's native structured output API.
159
+ * Concrete implementations should override this to use provider-specific structured output.
160
+ */
161
+ abstract structuredOutput(options: StructuredOutputOptions<TProviderOptions>): Promise<StructuredOutputResult<unknown>>;
162
+ protected generateId(): string;
163
+ }
@@ -0,0 +1,17 @@
1
+ class BaseTextAdapter {
2
+ kind = "text";
3
+ model;
4
+ requires = void 0;
5
+ config;
6
+ constructor(config = {}, model) {
7
+ this.config = config;
8
+ this.model = model;
9
+ }
10
+ generateId() {
11
+ return `${this.name}-${Date.now()}-${Math.random().toString(36).substring(7)}`;
12
+ }
13
+ }
14
+ export {
15
+ BaseTextAdapter
16
+ };
17
+ //# sourceMappingURL=adapter.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"adapter.js","sources":["../../../../src/activities/chat/adapter.ts"],"sourcesContent":["import type {\n DefaultMessageMetadataByModality,\n JSONSchema,\n Modality,\n StreamChunk,\n TextOptions,\n TokenUsage,\n} from '../../types'\nimport type { CapabilityHandle } from './middleware/capabilities'\n\n/**\n * Configuration for adapter instances\n */\nexport interface TextAdapterConfig {\n apiKey?: string\n baseUrl?: string\n timeout?: number\n maxRetries?: number\n headers?: Record<string, string>\n}\n\n/**\n * Options for structured output generation.\n *\n * The internal logger is threaded through `chatOptions.logger` (inherited from\n * `TextOptions`). Adapter implementations must call `logger.request()` before\n * SDK calls, `logger.provider()` for each chunk received, and `logger.errors()`\n * in catch blocks.\n */\nexport interface StructuredOutputOptions<TProviderOptions extends object> {\n /** Text options for the request */\n chatOptions: TextOptions<TProviderOptions>\n /** JSON Schema for structured output - already converted from Zod in the ai layer */\n outputSchema: JSONSchema\n}\n\n/**\n * Result from structured output generation\n */\nexport interface StructuredOutputResult<T = unknown> {\n /** The parsed data conforming to the schema */\n data: T\n /** The raw text response from the model before parsing */\n rawText: string\n /** Token usage information (if provided by the adapter) */\n usage?: TokenUsage\n}\n\n/**\n * Text adapter interface with pre-resolved generics.\n *\n * An adapter is created by a provider function: `provider('model')` → `adapter`\n * All type resolution happens at the provider call site, not in this interface.\n *\n * Generic parameters:\n * - TModel: The specific model name (e.g., 'gpt-4o')\n * - TProviderOptions: Provider-specific options for this model (already resolved)\n * - TInputModalities: Supported input modalities for this model (already resolved)\n * - TMessageMetadata: Metadata types for content parts (already resolved)\n * - TToolCapabilities: Tuple of tool-kind strings supported by this model, resolved from `supports.tools`\n * - TToolCallMetadata: Metadata type that round-trips with tool calls (e.g. Gemini's `thoughtSignature`)\n * - TSystemPromptMetadata: Provider-typed metadata accepted on each\n * `systemPrompts[i]` entry (e.g. Anthropic `cache_control`). Defaults to\n * `never` — adapters without per-prompt metadata reject the `metadata`\n * field at the call site.\n */\nexport interface TextAdapter<\n TModel extends string,\n TProviderOptions extends Record<string, any>,\n TInputModalities extends ReadonlyArray<Modality>,\n TMessageMetadataByModality extends DefaultMessageMetadataByModality,\n TToolCapabilities extends ReadonlyArray<string> = ReadonlyArray<string>,\n TToolCallMetadata = unknown,\n TSystemPromptMetadata = never,\n> {\n /** Discriminator for adapter kind */\n readonly kind: 'text'\n /** Provider name identifier (e.g., 'openai', 'anthropic') */\n readonly name: string\n /** The model this adapter is configured for */\n readonly model: TModel\n\n /**\n * Capabilities this adapter requires at runtime. `chat()` validates that the\n * configured middleware provides each one. Model adapters omit this; harness\n * adapters (e.g. a future `claudeCode()`) declare e.g. `[sandboxCapability]`.\n * Runtime access to capabilities from inside the adapter is not yet wired —\n * this is the declaration/validation surface only.\n */\n readonly requires?: ReadonlyArray<CapabilityHandle>\n\n /**\n * @internal Type-only properties for inference. Not assigned at runtime.\n */\n '~types': {\n providerOptions: TProviderOptions\n inputModalities: TInputModalities\n messageMetadataByModality: TMessageMetadataByModality\n toolCapabilities: TToolCapabilities\n toolCallMetadata: TToolCallMetadata\n systemPromptMetadata: TSystemPromptMetadata\n }\n\n /**\n * Stream text completions from the model\n */\n chatStream: (\n options: TextOptions<TProviderOptions>,\n ) => AsyncIterable<StreamChunk>\n\n /**\n * Generate structured output using the provider's native structured output API.\n * This method uses stream: false and sends the JSON schema to the provider\n * to ensure the response conforms to the expected structure.\n *\n * @param options - Structured output options containing chat options and JSON schema\n * @returns Promise with the raw data (validation is done in the chat function)\n */\n structuredOutput: (\n options: StructuredOutputOptions<TProviderOptions>,\n ) => Promise<StructuredOutputResult<unknown>>\n\n /**\n * Stream structured output using the provider's native streaming structured\n * output API (stream + response_format json_schema in a single request).\n *\n * Optional — adapters without native streaming JSON omit this method and the\n * activity layer synthesizes a stream around the non-streaming\n * `structuredOutput` call.\n *\n * Implementations must emit standard AG-UI lifecycle events (RUN_STARTED,\n * TEXT_MESSAGE_*, RUN_FINISHED) carrying raw JSON text deltas, plus a final\n * `CUSTOM` event named `structured-output.complete` whose `value` is\n * `{ object, raw, reasoning? }`.\n */\n structuredOutputStream?: (\n options: StructuredOutputOptions<TProviderOptions>,\n ) => AsyncIterable<StreamChunk>\n\n /**\n * Declares whether the adapter supports combining `tools` and a\n * schema-constrained final answer in a single streaming request.\n *\n * When `true`, the engine wires `outputSchema` into the regular\n * `chatStream()` call and skips the separate `runStructuredFinalization`\n * round-trip. The model's natural final turn carries the\n * schema-constrained JSON text and the engine harvests it from the agent\n * loop's accumulated content.\n *\n * When `false`, `undefined`, or the method is omitted, the engine runs\n * the agent loop without `outputSchema` and then issues a separate\n * `structuredOutput` / `structuredOutputStream` call against the JSON\n * schema for finalization (the legacy path).\n *\n * The method receives the per-call `modelOptions` so providers whose\n * support depends on the resolved upstream model (e.g. OpenRouter) can\n * answer per-request. Most adapters can return a constant.\n */\n supportsCombinedToolsAndSchema?: (\n modelOptions?: TProviderOptions | undefined,\n ) => boolean\n}\n\n/**\n * A TextAdapter with any/unknown type parameters.\n * Useful as a constraint in generic functions and interfaces.\n */\nexport type AnyTextAdapter = TextAdapter<any, any, any, any, any, any, any>\n\n/**\n * Abstract base class for text adapters.\n * Extend this class to implement a text adapter for a specific provider.\n *\n * Generic parameters match TextAdapter - all pre-resolved by the provider function.\n */\nexport abstract class BaseTextAdapter<\n TModel extends string,\n TProviderOptions extends Record<string, any>,\n TInputModalities extends ReadonlyArray<Modality>,\n TMessageMetadataByModality extends DefaultMessageMetadataByModality,\n TToolCapabilities extends ReadonlyArray<string> = ReadonlyArray<string>,\n TToolCallMetadata = unknown,\n TSystemPromptMetadata = never,\n> implements TextAdapter<\n TModel,\n TProviderOptions,\n TInputModalities,\n TMessageMetadataByModality,\n TToolCapabilities,\n TToolCallMetadata,\n TSystemPromptMetadata\n> {\n readonly kind = 'text' as const\n abstract readonly name: string\n readonly model: TModel\n readonly requires?: ReadonlyArray<CapabilityHandle> = undefined\n\n // Type-only property - never assigned at runtime\n declare '~types': {\n providerOptions: TProviderOptions\n inputModalities: TInputModalities\n messageMetadataByModality: TMessageMetadataByModality\n toolCapabilities: TToolCapabilities\n toolCallMetadata: TToolCallMetadata\n systemPromptMetadata: TSystemPromptMetadata\n }\n\n protected config: TextAdapterConfig\n\n constructor(config: TextAdapterConfig = {}, model: TModel) {\n this.config = config\n this.model = model\n }\n\n abstract chatStream(\n options: TextOptions<TProviderOptions>,\n ): AsyncIterable<StreamChunk>\n\n /**\n * Generate structured output using the provider's native structured output API.\n * Concrete implementations should override this to use provider-specific structured output.\n */\n abstract structuredOutput(\n options: StructuredOutputOptions<TProviderOptions>,\n ): Promise<StructuredOutputResult<unknown>>\n\n protected generateId(): string {\n return `${this.name}-${Date.now()}-${Math.random().toString(36).substring(7)}`\n }\n}\n"],"names":[],"mappings":"AA+KO,MAAe,gBAgBpB;AAAA,EACS,OAAO;AAAA,EAEP;AAAA,EACA,WAA6C;AAAA,EAY5C;AAAA,EAEV,YAAY,SAA4B,CAAA,GAAI,OAAe;AACzD,SAAK,SAAS;AACd,SAAK,QAAQ;AAAA,EACf;AAAA,EAcU,aAAqB;AAC7B,WAAO,GAAG,KAAK,IAAI,IAAI,KAAK,KAAK,IAAI,KAAK,OAAA,EAAS,SAAS,EAAE,EAAE,UAAU,CAAC,CAAC;AAAA,EAC9E;AACF;"}
@@ -0,0 +1,59 @@
1
+ import { AgentLoopStrategy } from '../../types.js';
2
+ /**
3
+ * Creates a strategy that continues for a maximum number of iterations
4
+ *
5
+ * @param max - Maximum number of iterations to allow
6
+ * @returns AgentLoopStrategy that stops after max iterations
7
+ *
8
+ * @example
9
+ * ```typescript
10
+ * const stream = chat({
11
+ * adapter: openaiText(),
12
+ * model: "gpt-4o",
13
+ * messages: [...],
14
+ * tools: [weatherTool],
15
+ * agentLoopStrategy: maxIterations(3), // Max 3 iterations
16
+ * });
17
+ * ```
18
+ */
19
+ export declare function maxIterations(max: number): AgentLoopStrategy;
20
+ /**
21
+ * Creates a strategy that continues until a specific finish reason is encountered
22
+ *
23
+ * @param stopReasons - Finish reasons that should stop the loop
24
+ * @returns AgentLoopStrategy that stops on specific finish reasons
25
+ *
26
+ * @example
27
+ * ```typescript
28
+ * const stream = chat({
29
+ * adapter: openaiText(),
30
+ * model: "gpt-4o",
31
+ * messages: [...],
32
+ * tools: [weatherTool],
33
+ * agentLoopStrategy: untilFinishReason(["stop", "length"]),
34
+ * });
35
+ * ```
36
+ */
37
+ export declare function untilFinishReason(stopReasons: Array<string>): AgentLoopStrategy;
38
+ /**
39
+ * Creates a strategy that combines multiple strategies with AND logic
40
+ * All strategies must return true to continue
41
+ *
42
+ * @param strategies - Array of strategies to combine
43
+ * @returns AgentLoopStrategy that continues only if all strategies return true
44
+ *
45
+ * @example
46
+ * ```typescript
47
+ * const stream = chat({
48
+ * adapter: openaiText(),
49
+ * model: "gpt-4o",
50
+ * messages: [...],
51
+ * tools: [weatherTool],
52
+ * agentLoopStrategy: combineStrategies([
53
+ * maxIterations(10),
54
+ * ({ messages }) => messages.length < 100,
55
+ * ]),
56
+ * });
57
+ * ```
58
+ */
59
+ export declare function combineStrategies(strategies: Array<AgentLoopStrategy>): AgentLoopStrategy;
@@ -0,0 +1,23 @@
1
+ function maxIterations(max) {
2
+ return ({ iterationCount }) => iterationCount < max;
3
+ }
4
+ function untilFinishReason(stopReasons) {
5
+ return ({ finishReason, iterationCount }) => {
6
+ if (iterationCount === 0) return true;
7
+ if (finishReason && stopReasons.includes(finishReason)) {
8
+ return false;
9
+ }
10
+ return true;
11
+ };
12
+ }
13
+ function combineStrategies(strategies) {
14
+ return (state) => {
15
+ return strategies.every((strategy) => strategy(state));
16
+ };
17
+ }
18
+ export {
19
+ combineStrategies,
20
+ maxIterations,
21
+ untilFinishReason
22
+ };
23
+ //# sourceMappingURL=agent-loop-strategies.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"agent-loop-strategies.js","sources":["../../../../src/activities/chat/agent-loop-strategies.ts"],"sourcesContent":["import type { AgentLoopStrategy } from '../../types'\n\n/**\n * Creates a strategy that continues for a maximum number of iterations\n *\n * @param max - Maximum number of iterations to allow\n * @returns AgentLoopStrategy that stops after max iterations\n *\n * @example\n * ```typescript\n * const stream = chat({\n * adapter: openaiText(),\n * model: \"gpt-4o\",\n * messages: [...],\n * tools: [weatherTool],\n * agentLoopStrategy: maxIterations(3), // Max 3 iterations\n * });\n * ```\n */\nexport function maxIterations(max: number): AgentLoopStrategy {\n return ({ iterationCount }) => iterationCount < max\n}\n\n/**\n * Creates a strategy that continues until a specific finish reason is encountered\n *\n * @param stopReasons - Finish reasons that should stop the loop\n * @returns AgentLoopStrategy that stops on specific finish reasons\n *\n * @example\n * ```typescript\n * const stream = chat({\n * adapter: openaiText(),\n * model: \"gpt-4o\",\n * messages: [...],\n * tools: [weatherTool],\n * agentLoopStrategy: untilFinishReason([\"stop\", \"length\"]),\n * });\n * ```\n */\nexport function untilFinishReason(\n stopReasons: Array<string>,\n): AgentLoopStrategy {\n return ({ finishReason, iterationCount }) => {\n // Always allow at least one iteration\n if (iterationCount === 0) return true\n\n // Stop if we hit a stop reason\n if (finishReason && stopReasons.includes(finishReason)) {\n return false\n }\n\n // Otherwise continue\n return true\n }\n}\n\n/**\n * Creates a strategy that combines multiple strategies with AND logic\n * All strategies must return true to continue\n *\n * @param strategies - Array of strategies to combine\n * @returns AgentLoopStrategy that continues only if all strategies return true\n *\n * @example\n * ```typescript\n * const stream = chat({\n * adapter: openaiText(),\n * model: \"gpt-4o\",\n * messages: [...],\n * tools: [weatherTool],\n * agentLoopStrategy: combineStrategies([\n * maxIterations(10),\n * ({ messages }) => messages.length < 100,\n * ]),\n * });\n * ```\n */\nexport function combineStrategies(\n strategies: Array<AgentLoopStrategy>,\n): AgentLoopStrategy {\n return (state) => {\n return strategies.every((strategy) => strategy(state))\n }\n}\n"],"names":[],"mappings":"AAmBO,SAAS,cAAc,KAAgC;AAC5D,SAAO,CAAC,EAAE,qBAAqB,iBAAiB;AAClD;AAmBO,SAAS,kBACd,aACmB;AACnB,SAAO,CAAC,EAAE,cAAc,qBAAqB;AAE3C,QAAI,mBAAmB,EAAG,QAAO;AAGjC,QAAI,gBAAgB,YAAY,SAAS,YAAY,GAAG;AACtD,aAAO;AAAA,IACT;AAGA,WAAO;AAAA,EACT;AACF;AAuBO,SAAS,kBACd,YACmB;AACnB,SAAO,CAAC,UAAU;AAChB,WAAO,WAAW,MAAM,CAAC,aAAa,SAAS,KAAK,CAAC;AAAA,EACvD;AACF;"}
@@ -0,0 +1,270 @@
1
+ import { AnyTextAdapter } from './adapter.js';
2
+ import { AnyTool, ConstrainedModelMessage, InferSchemaType, LazyToolsConfig, ModelMessage, SchemaInput, StreamChunk, StructuredOutputStream, TextOptions, UIMessage } from '../../types.js';
3
+ import { AnyChatMiddleware, ChatMiddleware } from './middleware/types.js';
4
+ import { CheckCoverage } from './middleware/builder.js';
5
+ import { SystemPrompt } from '../../system-prompts.js';
6
+ import { DebugOption } from '../../logger/types.js';
7
+ import { ProviderTool } from '../../tools/provider-tool.js';
8
+ import { ContextFromMiddleware, ContextFromTool, DefinedContext, MergeContext, UnionToIntersection } from './runtime-context-types.js';
9
+ import { ChatMCPOptions } from './mcp/types.js';
10
+ /** The adapter kind this activity handles */
11
+ export declare const kind: "text";
12
+ type AnyRuntimeTool = AnyTool;
13
+ type ContextFromConsumer<T> = ContextFromTool<T> | ContextFromMiddleware<T>;
14
+ type RequiredContextFromConsumerUnion<T> = T extends unknown ? undefined extends ContextFromConsumer<T> ? never : ContextFromConsumer<T> : never;
15
+ type ContextFromConsumerUnion<T> = [
16
+ UnionToIntersection<DefinedContext<ContextFromConsumer<T>>>
17
+ ] extends [never] ? never : [RequiredContextFromConsumerUnion<T>] extends [never] ? UnionToIntersection<DefinedContext<ContextFromConsumer<T>>> | undefined : UnionToIntersection<DefinedContext<ContextFromConsumer<T>>>;
18
+ type ContextFromArray<T> = T extends readonly [infer THead, ...infer TTail] ? MergeContext<ContextFromConsumer<THead>, ContextFromArray<TTail>> : T extends ReadonlyArray<infer TItem> ? ContextFromConsumerUnion<TItem> : never;
19
+ type ContextFromInputs<TTools, TMiddleware> = MergeContext<ContextFromArray<NonNullable<TTools>>, ContextFromArray<NonNullable<TMiddleware>>>;
20
+ type InferredContext<TTools, TMiddleware> = [
21
+ ContextFromInputs<TTools, TMiddleware>
22
+ ] extends [never] ? unknown : ContextFromInputs<TTools, TMiddleware>;
23
+ type RequiredContextFromInputs<TTools, TMiddleware> = [
24
+ ContextFromInputs<TTools, TMiddleware>
25
+ ] extends [never] ? {
26
+ context?: unknown;
27
+ } : undefined extends ContextFromInputs<TTools, TMiddleware> ? {
28
+ context?: ContextFromInputs<TTools, TMiddleware>;
29
+ } : {
30
+ context: ContextFromInputs<TTools, TMiddleware>;
31
+ };
32
+ type TextActivityOptionsWithContext<TAdapter extends AnyTextAdapter, TSchema extends SchemaInput | undefined, TStream extends boolean, TTools extends TextActivityOptions<TAdapter, TSchema, TStream, any>['tools'], TMiddleware extends TextActivityOptions<TAdapter, TSchema, TStream, any>['middleware']> = Omit<TextActivityOptions<TAdapter, TSchema, TStream, any>, 'tools' | 'middleware' | 'context'> & {
33
+ tools?: TTools;
34
+ middleware?: TMiddleware & CheckCoverage<Extract<TMiddleware, ReadonlyArray<AnyChatMiddleware>>>;
35
+ } & RequiredContextFromInputs<TTools, TMiddleware>;
36
+ /**
37
+ * Options for the text activity.
38
+ * Types are extracted directly from the adapter (which has pre-resolved generics).
39
+ *
40
+ * @template TAdapter - The text adapter type (created by a provider function)
41
+ * @template TSchema - Optional Standard Schema for structured output
42
+ * @template TStream - Whether to stream the output (default: true)
43
+ */
44
+ export interface TextActivityOptions<TAdapter extends AnyTextAdapter, TSchema extends SchemaInput | undefined, TStream extends boolean, TContext = unknown> {
45
+ /** The text adapter to use (created by a provider function like openaiText('gpt-4o')) */
46
+ adapter: TAdapter;
47
+ /**
48
+ * Conversation messages. Accepts:
49
+ * - `ConstrainedModelMessage` — content types constrained by the adapter's input modalities.
50
+ * - `ModelMessage` — unconstrained model message (e.g., forwarded from an AG-UI wire payload).
51
+ * - `UIMessage` — parts-based UI representation; converted internally via `convertMessagesToModelMessages`.
52
+ *
53
+ * The three shapes can be mixed in a single array (e.g., when forwarding a wire payload that includes both anchor UIMessages and AG-UI fan-out ModelMessages).
54
+ */
55
+ messages?: Array<UIMessage | ModelMessage | ConstrainedModelMessage<{
56
+ inputModalities: TAdapter['~types']['inputModalities'];
57
+ messageMetadataByModality: TAdapter['~types']['messageMetadataByModality'];
58
+ }>> | undefined;
59
+ /**
60
+ * System prompts to prepend to the conversation.
61
+ *
62
+ * Accepts plain strings or `{ content, metadata }` objects. The `metadata`
63
+ * field is typed by the adapter — Anthropic narrows it to
64
+ * `AnthropicSystemPromptMetadata` (with `cache_control` for prompt
65
+ * caching), providers without per-prompt metadata reject the field
66
+ * entirely.
67
+ */
68
+ systemPrompts?: Array<SystemPrompt<TAdapter['~types']['systemPromptMetadata']>> | undefined;
69
+ /**
70
+ * Tools for function calling (auto-executed when called).
71
+ *
72
+ * Accepts two shapes:
73
+ * - User-defined tools via `toolDefinition()` — plain `Tool`, always assignable.
74
+ * - Provider tools from `@tanstack/ai-<provider>/tools` (e.g. `webSearchTool`)
75
+ * — branded and type-checked against the selected model's
76
+ * `supports.tools` list. Passing an unsupported tool produces a
77
+ * compile-time error on the array element.
78
+ */
79
+ tools?: Array<(AnyRuntimeTool & {
80
+ readonly '~toolKind'?: never;
81
+ }) | ProviderTool<string, TAdapter['~types']['toolCapabilities'][number]>> | undefined;
82
+ /**
83
+ * Hand MCP clients/pools to chat(): their tools are discovered at run start
84
+ * and merged into the run; `connection` controls whether chat() closes them
85
+ * when the run ends. See docs/tools/mcp.md "Managing MCP clients with chat()".
86
+ */
87
+ mcp?: ChatMCPOptions;
88
+ /** Additional metadata to attach to the request. */
89
+ metadata?: TextOptions['metadata'];
90
+ /** Model-specific provider options (type comes from adapter) */
91
+ modelOptions?: TAdapter['~types']['providerOptions'];
92
+ /** AbortController for cancellation */
93
+ abortController?: TextOptions['abortController'];
94
+ /** Strategy for controlling the agent loop */
95
+ agentLoopStrategy?: TextOptions['agentLoopStrategy'];
96
+ /**
97
+ * Optional configuration for lazy-tool discovery (tools marked `lazy: true`).
98
+ * Tunes how much of each lazy tool's description appears in the discovery
99
+ * catalog. Optional — defaults to `{ includeDescription: 'none' }`.
100
+ */
101
+ lazyToolsConfig?: LazyToolsConfig;
102
+ /** Unique conversation identifier for tracking */
103
+ conversationId?: TextOptions['conversationId'];
104
+ /** Thread/conversation ID for AG-UI protocol. Auto-generated if not provided. */
105
+ threadId?: TextOptions['threadId'];
106
+ /** Run ID override for AG-UI protocol. Auto-generated by adapter if not provided. */
107
+ runId?: TextOptions['runId'];
108
+ /** Parent run ID for AG-UI protocol nested run correlation. */
109
+ parentRunId?: TextOptions['parentRunId'];
110
+ /**
111
+ * Optional Standard Schema for structured output.
112
+ * When provided, the activity will:
113
+ * 1. Run the full agentic loop (executing tools as needed)
114
+ * 2. Once complete, return a Promise with the parsed output matching the schema
115
+ *
116
+ * Supports any Standard Schema compliant library (Zod v4+, ArkType, Valibot, etc.)
117
+ *
118
+ * @example
119
+ * ```ts
120
+ * const result = await chat({
121
+ * adapter: openaiText('gpt-4o'),
122
+ * messages: [{ role: 'user', content: 'Generate a person' }],
123
+ * outputSchema: z.object({ name: z.string(), age: z.number() })
124
+ * })
125
+ * // result is { name: string, age: number }
126
+ * ```
127
+ */
128
+ outputSchema?: TSchema;
129
+ /**
130
+ * Whether to stream the text result.
131
+ * When true (default), returns an AsyncIterable<StreamChunk> for streaming output.
132
+ * When false, returns a Promise<string> with the collected text content.
133
+ *
134
+ * Note: If outputSchema is provided, this option is ignored and the result
135
+ * is always a Promise<InferSchemaType<TSchema>>.
136
+ *
137
+ * @default true
138
+ *
139
+ * @example Non-streaming text
140
+ * ```ts
141
+ * const text = await chat({
142
+ * adapter: openaiText('gpt-4o'),
143
+ * messages: [{ role: 'user', content: 'Hello!' }],
144
+ * stream: false
145
+ * })
146
+ * // text is a string with the full response
147
+ * ```
148
+ */
149
+ stream?: TStream;
150
+ /**
151
+ * Optional middleware array for observing/transforming chat behavior.
152
+ * Middleware hooks are called in array order. See {@link ChatMiddleware} for available hooks.
153
+ *
154
+ * @example
155
+ * ```ts
156
+ * const stream = chat({
157
+ * adapter: openaiText('gpt-4o'),
158
+ * messages: [...],
159
+ * middleware: [loggingMiddleware, redactionMiddleware],
160
+ * })
161
+ * ```
162
+ */
163
+ middleware?: Array<ChatMiddleware<TContext>>;
164
+ /**
165
+ * Runtime context value passed to middleware hooks and server tools.
166
+ */
167
+ context?: TContext;
168
+ /**
169
+ * Enable debug logging. Pass `true` to enable all categories with the default
170
+ * console logger, `false` to silence everything, or a `DebugConfig` object for
171
+ * granular control and/or a custom `Logger`. Defaults to `undefined`, which
172
+ * means only the `errors` category is active.
173
+ */
174
+ debug?: DebugOption;
175
+ }
176
+ /**
177
+ * Create typed options for the chat() function without executing.
178
+ * This is useful for pre-defining configurations with full type inference.
179
+ *
180
+ * @example
181
+ * ```ts
182
+ * const chatOptions = createChatOptions({
183
+ * adapter: anthropicText('claude-sonnet-4-5'),
184
+ * })
185
+ *
186
+ * const stream = chat({ ...chatOptions, messages })
187
+ * ```
188
+ */
189
+ export declare function createChatOptions<TAdapter extends AnyTextAdapter, TSchema extends SchemaInput | undefined = undefined, TStream extends boolean = true, const TTools extends TextActivityOptions<TAdapter, TSchema, TStream, any>['tools'] = TextActivityOptions<TAdapter, TSchema, TStream, any>['tools'], const TMiddleware extends TextActivityOptions<TAdapter, TSchema, TStream, any>['middleware'] = TextActivityOptions<TAdapter, TSchema, TStream, any>['middleware']>(options: TextActivityOptionsWithContext<TAdapter, TSchema, TStream, TTools, TMiddleware>): TextActivityOptions<TAdapter, TSchema, TStream, InferredContext<TTools, TMiddleware>>;
190
+ /**
191
+ * Result type for the text activity.
192
+ * - If outputSchema is provided AND stream is explicitly true:
193
+ * StructuredOutputStream<InferSchemaType<TSchema>> — yields raw JSON deltas
194
+ * via TEXT_MESSAGE_CONTENT plus a terminal StructuredOutputCompleteEvent
195
+ * carrying the validated object.
196
+ * - If outputSchema is provided without explicit stream:true:
197
+ * Promise<InferSchemaType<TSchema>>.
198
+ * - If stream is explicitly false (no schema): Promise<string>.
199
+ * - Otherwise (default): AsyncIterable<StreamChunk>.
200
+ *
201
+ * `[TStream] extends [true]` is used (not `TStream extends true`) so that the
202
+ * default `boolean` value of `TStream` does *not* match the streaming branch.
203
+ * Without this, plain `chat({ outputSchema })` would type as a stream while
204
+ * the runtime returns a Promise — see issue #526.
205
+ */
206
+ export type TextActivityResult<TSchema extends SchemaInput | undefined, TStream extends boolean = boolean> = TSchema extends SchemaInput ? [TStream] extends [true] ? StructuredOutputStream<InferSchemaType<TSchema>> : Promise<InferSchemaType<TSchema>> : [TStream] extends [false] ? Promise<string> : AsyncIterable<StreamChunk>;
207
+ /**
208
+ * Text activity - handles agentic text generation, one-shot text generation, and agentic structured output.
209
+ *
210
+ * This activity supports four modes:
211
+ * 1. **Streaming agentic text**: Stream responses with automatic tool execution
212
+ * 2. **Streaming one-shot text**: Simple streaming request/response without tools
213
+ * 3. **Non-streaming text**: Returns collected text as a string (stream: false)
214
+ * 4. **Agentic structured output**: Run tools, then return structured data
215
+ *
216
+ * @example Full agentic text (streaming with tools)
217
+ * ```ts
218
+ * import { chat } from '@tanstack/ai'
219
+ * import { openaiText } from '@tanstack/ai-openai'
220
+ *
221
+ * for await (const chunk of chat({
222
+ * adapter: openaiText('gpt-4o'),
223
+ * messages: [{ role: 'user', content: 'What is the weather?' }],
224
+ * tools: [weatherTool]
225
+ * })) {
226
+ * if (chunk.type === 'TEXT_MESSAGE_CONTENT') {
227
+ * console.log(chunk.delta)
228
+ * }
229
+ * }
230
+ * ```
231
+ *
232
+ * @example One-shot text (streaming without tools)
233
+ * ```ts
234
+ * for await (const chunk of chat({
235
+ * adapter: openaiText('gpt-4o'),
236
+ * messages: [{ role: 'user', content: 'Hello!' }]
237
+ * })) {
238
+ * console.log(chunk)
239
+ * }
240
+ * ```
241
+ *
242
+ * @example Non-streaming text (stream: false)
243
+ * ```ts
244
+ * const text = await chat({
245
+ * adapter: openaiText('gpt-4o'),
246
+ * messages: [{ role: 'user', content: 'Hello!' }],
247
+ * stream: false
248
+ * })
249
+ * // text is a string with the full response
250
+ * ```
251
+ *
252
+ * @example Agentic structured output (tools + structured response)
253
+ * ```ts
254
+ * import { z } from 'zod'
255
+ *
256
+ * const result = await chat({
257
+ * adapter: openaiText('gpt-4o'),
258
+ * messages: [{ role: 'user', content: 'Research and summarize the topic' }],
259
+ * tools: [researchTool, analyzeTool],
260
+ * outputSchema: z.object({
261
+ * summary: z.string(),
262
+ * keyPoints: z.array(z.string())
263
+ * })
264
+ * })
265
+ * // result is { summary: string, keyPoints: string[] }
266
+ * ```
267
+ */
268
+ export declare function chat<TAdapter extends AnyTextAdapter, TSchema extends SchemaInput | undefined = undefined, TStream extends boolean = boolean, const TTools extends TextActivityOptions<TAdapter, TSchema, TStream, any>['tools'] = TextActivityOptions<TAdapter, TSchema, TStream, any>['tools'], const TMiddleware extends TextActivityOptions<TAdapter, TSchema, TStream, any>['middleware'] = TextActivityOptions<TAdapter, TSchema, TStream, any>['middleware']>(options: TextActivityOptionsWithContext<TAdapter, TSchema, TStream, TTools, TMiddleware>): TextActivityResult<TSchema, TStream>;
269
+ export type { TextAdapter, TextAdapterConfig, StructuredOutputOptions, StructuredOutputResult, } from './adapter.js';
270
+ export { BaseTextAdapter } from './adapter.js';