@plotday/twister 0.47.0 → 0.48.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 (72) hide show
  1. package/bin/commands/generate.js +5 -5
  2. package/bin/commands/generate.js.map +1 -1
  3. package/bin/utils/bundle.js +14 -0
  4. package/bin/utils/bundle.js.map +1 -1
  5. package/dist/docs/assets/hierarchy.js +1 -1
  6. package/dist/docs/assets/search.js +1 -1
  7. package/dist/docs/classes/index.Connector.html +1 -1
  8. package/dist/docs/classes/index.Imap.html +1 -1
  9. package/dist/docs/classes/index.Options.html +1 -1
  10. package/dist/docs/classes/index.Smtp.html +1 -1
  11. package/dist/docs/classes/tools_network.Network.html +1 -1
  12. package/dist/docs/classes/tools_plot.Plot.html +1 -1
  13. package/dist/docs/classes/tools_store.Store.html +1 -1
  14. package/dist/docs/classes/tools_tasks.Tasks.html +1 -1
  15. package/dist/docs/documents/CLI_Reference.html +6 -4
  16. package/dist/docs/enums/tools_integrations.AuthProvider.html +3 -1
  17. package/dist/docs/hierarchy.html +1 -1
  18. package/dist/docs/types/tools_integrations.AuthToken.html +4 -4
  19. package/dist/docs/types/tools_integrations.Authorization.html +4 -4
  20. package/dist/llm-docs/tools/integrations.d.ts +1 -1
  21. package/dist/llm-docs/tools/integrations.d.ts.map +1 -1
  22. package/dist/llm-docs/tools/integrations.js +1 -1
  23. package/dist/llm-docs/tools/integrations.js.map +1 -1
  24. package/dist/tools/integrations.d.ts +3 -1
  25. package/dist/tools/integrations.d.ts.map +1 -1
  26. package/dist/tools/integrations.js +2 -0
  27. package/dist/tools/integrations.js.map +1 -1
  28. package/package.json +2 -1
  29. package/src/connector.ts +366 -0
  30. package/src/creator-docs.ts +29 -0
  31. package/src/index.ts +10 -0
  32. package/src/llm-docs/connector.ts +8 -0
  33. package/src/llm-docs/index.ts +48 -0
  34. package/src/llm-docs/options.ts +8 -0
  35. package/src/llm-docs/plot.ts +8 -0
  36. package/src/llm-docs/schedule.ts +8 -0
  37. package/src/llm-docs/tag.ts +8 -0
  38. package/src/llm-docs/tool.ts +8 -0
  39. package/src/llm-docs/tools/ai.ts +8 -0
  40. package/src/llm-docs/tools/callbacks.ts +8 -0
  41. package/src/llm-docs/tools/imap.ts +8 -0
  42. package/src/llm-docs/tools/integrations.ts +8 -0
  43. package/src/llm-docs/tools/network.ts +8 -0
  44. package/src/llm-docs/tools/plot.ts +8 -0
  45. package/src/llm-docs/tools/smtp.ts +8 -0
  46. package/src/llm-docs/tools/store.ts +8 -0
  47. package/src/llm-docs/tools/tasks.ts +8 -0
  48. package/src/llm-docs/tools/twists.ts +8 -0
  49. package/src/llm-docs/twist-guide-template.ts +8 -0
  50. package/src/llm-docs/twist.ts +8 -0
  51. package/src/options.ts +115 -0
  52. package/src/plot.ts +1068 -0
  53. package/src/schedule.ts +203 -0
  54. package/src/tag.ts +44 -0
  55. package/src/tool.ts +377 -0
  56. package/src/tools/ai.ts +845 -0
  57. package/src/tools/callbacks.ts +134 -0
  58. package/src/tools/imap.ts +266 -0
  59. package/src/tools/index.ts +10 -0
  60. package/src/tools/integrations.ts +328 -0
  61. package/src/tools/network.ts +240 -0
  62. package/src/tools/plot.ts +692 -0
  63. package/src/tools/smtp.ts +166 -0
  64. package/src/tools/store.ts +149 -0
  65. package/src/tools/tasks.ts +137 -0
  66. package/src/tools/twists.ts +228 -0
  67. package/src/twist-guide.ts +9 -0
  68. package/src/twist.ts +435 -0
  69. package/src/utils/hash.ts +8 -0
  70. package/src/utils/serializable.ts +54 -0
  71. package/src/utils/types.ts +130 -0
  72. package/src/utils/uuid.ts +9 -0
@@ -0,0 +1,845 @@
1
+ import type { Static, TSchema } from "typebox";
2
+
3
+ import { ITool } from "..";
4
+
5
+ /**
6
+ * Built-in tool for prompting Large Language Models (LLMs).
7
+ *
8
+ * The AI tool provides twists and tools with access to LLM capabilities
9
+ * for natural language processing, text generation, data extraction,
10
+ * and intelligent decision making within their workflows.
11
+ *
12
+ * **Features:**
13
+ * - Access to multiple AI providers (OpenAI, Anthropic, Google, Workers AI)
14
+ * - Multi-turn conversation support with `messages`
15
+ * - Tool calling with automatic execution
16
+ * - Structured output with Typebox schemas via `outputSchema`
17
+ * - Unified API across all models via Vercel AI SDK
18
+ * - Automatic response parsing and validation with full type inference
19
+ *
20
+ * @example
21
+ * ```typescript
22
+ * import { Type } from "typebox";
23
+ *
24
+ * class SmartEmailTool extends Tool {
25
+ * private ai: AI;
26
+ *
27
+ * constructor(id: string, tools: ToolBuilder) {
28
+ * super();
29
+ * this.ai = tools.get(AI);
30
+ * }
31
+ *
32
+ * async categorizeEmail(emailContent: string) {
33
+ * // Define the output schema using Typebox
34
+ * const schema = Type.Object({
35
+ * category: Type.Union([
36
+ * Type.Literal("work"),
37
+ * Type.Literal("personal"),
38
+ * Type.Literal("spam"),
39
+ * Type.Literal("promotional")
40
+ * ]),
41
+ * confidence: Type.Number({ minimum: 0, maximum: 1 }),
42
+ * reasoning: Type.Optional(Type.String())
43
+ * });
44
+ *
45
+ * const response = await this.ai.prompt({
46
+ * model: { speed: "fast", cost: "medium" },
47
+ * system: "Classify emails into categories: work, personal, spam, or promotional.",
48
+ * prompt: `Categorize this email: ${emailContent}`,
49
+ * outputSchema: schema
50
+ * });
51
+ *
52
+ * return response.output;
53
+ * }
54
+ *
55
+ * async generateResponse(emailContent: string) {
56
+ * const response = await this.ai.prompt({
57
+ * model: { speed: "fast", cost: "medium" },
58
+ * system: "Generate professional email responses that are helpful and concise.",
59
+ * prompt: `Write a response to: ${emailContent}`
60
+ * });
61
+ *
62
+ * return response.text;
63
+ * }
64
+ * }
65
+ * ```
66
+ */
67
+ export abstract class AI extends ITool {
68
+ /**
69
+ * Returns which AI capabilities are currently available.
70
+ * Check this before calling prompt() or embed() to gracefully
71
+ * handle cases where AI is disabled by the user.
72
+ */
73
+ abstract available(): AICapabilities;
74
+
75
+ /**
76
+ * Sends a request to an AI model and returns the response using the Vercel AI SDK.
77
+ *
78
+ * Supports text generation, multi-turn conversations, structured outputs,
79
+ * and tool calling across multiple AI providers via Cloudflare AI Gateway.
80
+ *
81
+ * @param request - AI request with model, prompt/messages, and optional configuration
82
+ * @returns Promise resolving to the AI response with generated text and metadata
83
+ *
84
+ * @example
85
+ * ```typescript
86
+ * // Simple text generation
87
+ * const response = await ai.prompt({
88
+ * model: { speed: "fast", cost: "medium" },
89
+ * prompt: "Explain quantum computing in simple terms"
90
+ * });
91
+ * console.log(response.text);
92
+ *
93
+ * // Fast and cheap for simple tasks
94
+ * const response = await ai.prompt({
95
+ * model: { speed: "fast", cost: "low" },
96
+ * prompt: "Summarize this text..."
97
+ * });
98
+ * console.log(response.text);
99
+ *
100
+ * // With system instructions for complex reasoning
101
+ * const response = await ai.prompt({
102
+ * model: { speed: "capable", cost: "high" },
103
+ * system: "You are a helpful physics tutor.",
104
+ * prompt: "Explain quantum entanglement"
105
+ * });
106
+ * console.log(response.text);
107
+ *
108
+ * // Multi-turn conversation
109
+ * const response = await ai.prompt({
110
+ * model: { speed: "balanced", cost: "medium" },
111
+ * messages: [
112
+ * { role: "user", content: "What is 2+2?" },
113
+ * { role: "assistant", content: "2+2 equals 4." },
114
+ * { role: "user", content: "What about 3+3?" }
115
+ * ]
116
+ * });
117
+ * console.log(response.text);
118
+ *
119
+ * // Structured output with Typebox schema
120
+ * const response = await ai.prompt({
121
+ * model: { speed: "fast", cost: "medium" },
122
+ * prompt: "Extract information: John is 30 years old",
123
+ * outputSchema: Type.Object({
124
+ * name: Type.String(),
125
+ * age: Type.Number()
126
+ * })
127
+ * });
128
+ * console.log(response.output); // { name: "John", age: 30 }
129
+ *
130
+ * // Tool calling
131
+ * const response = await ai.prompt({
132
+ * model: { speed: "balanced", cost: "medium" },
133
+ * prompt: "What's the weather in San Francisco?",
134
+ * tools: {
135
+ * getWeather: {
136
+ * description: "Get weather for a city",
137
+ * parameters: Type.Object({
138
+ * city: Type.String()
139
+ * }),
140
+ * execute: async ({ city }) => {
141
+ * return { temp: 72, condition: "sunny" };
142
+ * }
143
+ * }
144
+ * }
145
+ * });
146
+ * console.log(response.text); // Model's response using tool results
147
+ * console.log(response.toolCalls); // Array of tool calls made
148
+ * ```
149
+ */
150
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
151
+ abstract prompt<TOOLS extends AIToolSet, SCHEMA extends TSchema = never>(
152
+ request: AIRequest<TOOLS, SCHEMA>
153
+ ): Promise<AIResponse<TOOLS, SCHEMA>>;
154
+ }
155
+
156
+ /** Options for configuring AI tool usage in a twist. */
157
+ export type AIOptions = {
158
+ /** Whether AI is required for this twist to function. Default: true */
159
+ required?: boolean;
160
+ };
161
+
162
+ /** Describes which AI capabilities are currently available to this twist. */
163
+ export type AICapabilities = {
164
+ /** Whether AI prompting (text generation) is available. */
165
+ prompt: boolean;
166
+ /** Whether AI embedding generation is available. */
167
+ embed: boolean;
168
+ };
169
+
170
+ /**
171
+ * Model preferences for selecting an AI model based on performance and cost requirements.
172
+ * This allows Plot to match those preferences with user preferences (such as preferred or
173
+ * disallowed providers), as well as availability of newer and better models.
174
+ *
175
+ * @example
176
+ * ```typescript
177
+ * // Fast and cheap - uses Workers AI models like Llama 3.2 1B
178
+ * const response = await ai.prompt({
179
+ * model: { speed: "fast", cost: "low" },
180
+ * prompt: "Summarize this in one sentence: ..."
181
+ * });
182
+ *
183
+ * // Balanced performance - uses GPT-5 Mini or Gemini 2.5 Flash
184
+ * const response = await ai.prompt({
185
+ * model: { speed: "balanced", cost: "medium" },
186
+ * prompt: "Analyze this data..."
187
+ * });
188
+ *
189
+ * // Most capable - uses Claude Sonnet 4.5 or Opus 4.1
190
+ * const response = await ai.prompt({
191
+ * model: { speed: "capable", cost: "high" },
192
+ * prompt: "Solve this complex reasoning problem..."
193
+ * });
194
+ *
195
+ * // Request a specific model with a hint
196
+ * const response = await ai.prompt({
197
+ * model: { speed: "balanced", cost: "medium", hint: AIModel.CLAUDE_SONNET_45 },
198
+ * prompt: "..."
199
+ * });
200
+ * ```
201
+ */
202
+ export type ModelPreferences = {
203
+ /**
204
+ * Desired speed tier:
205
+ * - "fast": Optimized for low latency and quick responses
206
+ * - "balanced": Good balance of speed and capability
207
+ * - "capable": Maximum reasoning and problem-solving ability
208
+ */
209
+ speed: "fast" | "balanced" | "capable";
210
+
211
+ /**
212
+ * Desired cost tier:
213
+ * - "low": Minimal cost, often using Workers AI models (free/very cheap)
214
+ * - "medium": Moderate pricing for good performance
215
+ * - "high": Premium pricing for best-in-class models
216
+ */
217
+ cost: "low" | "medium" | "high";
218
+
219
+ /**
220
+ * Optional hint to suggest a specific model. The system will use this
221
+ * model if possible, but may override it based on user preferences.
222
+ */
223
+ hint?: AIModel;
224
+ };
225
+
226
+ /**
227
+ * Supported AI models available through Cloudflare AI Gateway and Workers AI.
228
+ *
229
+ * Models are organized by provider:
230
+ * - **OpenAI**: Latest GPT models via AI Gateway
231
+ * - **Anthropic**: Claude models via AI Gateway (prefix with "anthropic/")
232
+ * - **Google**: Gemini models via AI Gateway (prefix with "google-ai-studio/")
233
+ * - **Workers AI**: Models running on Cloudflare's network (free/low cost)
234
+ */
235
+ export enum AIModel {
236
+ // OpenAI models - Latest GPT and reasoning models
237
+ GPT_5 = "openai/gpt-5",
238
+ GPT_5_PRO = "openai/gpt-5-pro",
239
+ GPT_5_MINI = "openai/gpt-5-mini",
240
+ GPT_5_NANO = "openai/gpt-5-nano",
241
+ GPT_4O = "openai/gpt-4o",
242
+ GPT_4O_MINI = "openai/gpt-4o-mini",
243
+ O3 = "openai/o3",
244
+ O3_MINI = "openai/o3-mini",
245
+
246
+ // Anthropic models - Claude 4.x series
247
+ CLAUDE_OPUS_46 = "anthropic/claude-opus-4-6",
248
+ CLAUDE_SONNET_46 = "anthropic/claude-sonnet-4-6",
249
+ CLAUDE_HAIKU_45 = "anthropic/claude-haiku-4-5",
250
+
251
+ // Google models - Gemini 2.x series
252
+ GEMINI_25_PRO = "google/gemini-2.5-pro",
253
+ GEMINI_25_FLASH = "google/gemini-2.5-flash",
254
+ GEMINI_25_FLASH_LITE = "google/gemini-2.5-flash-lite",
255
+ GEMINI_20_FLASH = "google/gemini-2.0-flash",
256
+ GEMINI_20_FLASH_LITE = "google/gemini-2.0-flash-lite",
257
+
258
+ // Cloudflare Workers AI models - Free/low-cost models running on Cloudflare's network
259
+ LLAMA_4_SCOUT_17B = "meta/llama-4-scout-17b-16e-instruct",
260
+ LLAMA_33_70B = "meta/llama-3.3-70b-instruct-fp8-fast",
261
+ LLAMA_31_8B = "meta/llama-3.1-8b-instruct-fp8",
262
+ LLAMA_32_1B = "meta/llama-3.2-1b-instruct",
263
+ DEEPSEEK_R1_32B = "deepseek-ai/deepseek-r1-distill-qwen-32b",
264
+ }
265
+
266
+ /**
267
+ * Request parameters for AI text generation, matching Vercel AI SDK's generateText() function.
268
+ */
269
+ export interface AIRequest<
270
+ TOOLS extends AIToolSet,
271
+ SCHEMA extends TSchema = never
272
+ > {
273
+ /**
274
+ * Model selection preferences based on desired speed and cost characteristics.
275
+ * Plot will automatically select the best available model matching these preferences.
276
+ *
277
+ * @example
278
+ * // Fast and cheap - good for simple tasks
279
+ * model: { speed: "fast", cost: "low" }
280
+ *
281
+ * @example
282
+ * // Balanced performance - general purpose
283
+ * model: { speed: "balanced", cost: "medium" }
284
+ *
285
+ * @example
286
+ * // Maximum capability - complex reasoning
287
+ * model: { speed: "capable", cost: "high" }
288
+ *
289
+ * @example
290
+ * // With a specific model hint
291
+ * model: { speed: "balanced", cost: "medium", hint: "anthropic/claude-sonnet-4-6" }
292
+ */
293
+ model: ModelPreferences;
294
+
295
+ /**
296
+ * System instructions to guide the model's behavior.
297
+ */
298
+ system?: string;
299
+
300
+ /**
301
+ * The user's input prompt. Can be a simple string or an array of messages for multi-turn conversations.
302
+ */
303
+ prompt?: string;
304
+
305
+ /**
306
+ * Conversation messages for multi-turn interactions.
307
+ * Replaces 'prompt' for more complex conversations.
308
+ */
309
+ messages?: AIMessage[];
310
+
311
+ /**
312
+ * Tools that the model can call during generation.
313
+ * Each tool definition includes a description, input schema, and optional execute function.
314
+ */
315
+ tools?: TOOLS;
316
+
317
+ /**
318
+ * Controls which tools the model can use.
319
+ * - "auto": Model decides whether to use tools
320
+ * - "none": Model cannot use tools
321
+ * - "required": Model must use at least one tool
322
+ * - { type: "tool", toolName: string }: Model must use specific tool
323
+ */
324
+ toolChoice?: ToolChoice<TOOLS>;
325
+
326
+ /**
327
+ * Structured output schema using Typebox.
328
+ * Typebox schemas are JSON Schema objects that provide full TypeScript type inference.
329
+ */
330
+ outputSchema?: SCHEMA;
331
+
332
+ /**
333
+ * Maximum number of tokens to generate.
334
+ */
335
+ maxOutputTokens?: number;
336
+
337
+ /**
338
+ * Temperature for controlling randomness (0-2).
339
+ * Higher values make output more random, lower values more deterministic.
340
+ */
341
+ temperature?: number;
342
+
343
+ /**
344
+ * Top P sampling parameter (0-1).
345
+ * Controls diversity by limiting to top probability tokens.
346
+ */
347
+ topP?: number;
348
+ }
349
+
350
+ /**
351
+ * Response from AI text generation, matching Vercel AI SDK's GenerateTextResult.
352
+ */
353
+ export interface AIResponse<
354
+ TOOLS extends AIToolSet,
355
+ SCHEMA extends TSchema = never
356
+ > {
357
+ /**
358
+ * The generated text.
359
+ */
360
+ text: string;
361
+
362
+ /**
363
+ * Tool calls made by the model during generation.
364
+ */
365
+ toolCalls?: ToolCallArray<TOOLS>;
366
+
367
+ /**
368
+ * Results from tool executions.
369
+ */
370
+ toolResults?: ToolResultArray<TOOLS>;
371
+
372
+ /**
373
+ * Reason why the model stopped generating.
374
+ */
375
+ finishReason:
376
+ | "stop"
377
+ | "length"
378
+ | "content-filter"
379
+ | "tool-calls"
380
+ | "error"
381
+ | "other"
382
+ | "unknown";
383
+
384
+ /**
385
+ * Token usage information for this generation.
386
+ */
387
+ usage: AIUsage;
388
+
389
+ /**
390
+ * Sources used by the model (if supported).
391
+ */
392
+ sources?: Array<AISource>;
393
+
394
+ /**
395
+ * Structured output when using outputSchema.
396
+ * Type is automatically inferred from the Typebox schema.
397
+ */
398
+ output?: Static<SCHEMA>;
399
+
400
+ /**
401
+ * Response metadata including messages.
402
+ */
403
+ response?: {
404
+ id?: string;
405
+ timestamp?: Date;
406
+ modelId?: string;
407
+ messages?: AIMessage[];
408
+ };
409
+ }
410
+
411
+ // ============================================================================
412
+ // Message Types
413
+ // ============================================================================
414
+
415
+ /**
416
+ * A system message. It can contain system information.
417
+ *
418
+ * Note: using the "system" part of the prompt is strongly preferred
419
+ * to increase the resilience against prompt injection attacks,
420
+ * and because not all providers support several system messages.
421
+ */
422
+ export type AISystemMessage = {
423
+ role: "system";
424
+ content: string;
425
+ };
426
+
427
+ /**
428
+ * A user message. It can contain text or a combination of text and images.
429
+ */
430
+ export type AIUserMessage = {
431
+ role: "user";
432
+ content: string | Array<TextPart | ImagePart | FilePart>;
433
+ };
434
+
435
+ /**
436
+ * An assistant message. It can contain text, tool calls, or a combination of text and tool calls.
437
+ */
438
+ export type AIAssistantMessage = {
439
+ role: "assistant";
440
+ content:
441
+ | string
442
+ | Array<
443
+ TextPart | FilePart | ReasoningPart | ToolCallPart | ToolResultPart
444
+ >;
445
+ };
446
+
447
+ /**
448
+ * A tool message. It contains the result of one or more tool calls.
449
+ */
450
+ export type AIToolMessage = {
451
+ role: "tool";
452
+ content: Array<ToolResultPart>;
453
+ };
454
+
455
+ /**
456
+ * A message that can be used in the `messages` field of a prompt.
457
+ * It can be a user message, an assistant message, or a tool message.
458
+ */
459
+ export type AIMessage =
460
+ | AISystemMessage
461
+ | AIUserMessage
462
+ | AIAssistantMessage
463
+ | AIToolMessage;
464
+
465
+ // ============================================================================
466
+ // Usage & Sources
467
+ // ============================================================================
468
+
469
+ /**
470
+ * Represents the number of tokens used in a prompt and completion.
471
+ */
472
+ export type AIUsage = {
473
+ /**
474
+ * The number of tokens used in the prompt.
475
+ */
476
+ inputTokens?: number;
477
+ /**
478
+ * The number of tokens used in the completion.
479
+ */
480
+ outputTokens?: number;
481
+ /**
482
+ * The total number of tokens used (promptTokens + completionTokens).
483
+ */
484
+ totalTokens?: number;
485
+ /**
486
+ * The number of reasoning tokens used in the completion.
487
+ */
488
+ reasoningTokens?: number;
489
+ };
490
+
491
+ /**
492
+ * A source that has been used as input to generate the response.
493
+ */
494
+ export type AISource =
495
+ | {
496
+ type: "source";
497
+ /**
498
+ * A URL source. This is returned by web search RAG models.
499
+ */
500
+ sourceType: "url";
501
+ /**
502
+ * The ID of the source.
503
+ */
504
+ id: string;
505
+ /**
506
+ * The URL of the source.
507
+ */
508
+ url: string;
509
+ /**
510
+ * The title of the source.
511
+ */
512
+ title?: string;
513
+ }
514
+ | {
515
+ type: "source";
516
+ /**
517
+ * The type of source - document sources reference files/documents.
518
+ */
519
+ sourceType: "document";
520
+ /**
521
+ * The ID of the source.
522
+ */
523
+ id: string;
524
+ /**
525
+ * IANA media type of the document (e.g., 'application/pdf').
526
+ */
527
+ mediaType: string;
528
+ /**
529
+ * The title of the document.
530
+ */
531
+ title: string;
532
+ /**
533
+ * Optional filename of the document.
534
+ */
535
+ filename?: string;
536
+ };
537
+
538
+ // ============================================================================
539
+ // Content Parts
540
+ // ============================================================================
541
+
542
+ /**
543
+ * Text content part of a prompt. It contains a string of text.
544
+ */
545
+ export interface TextPart {
546
+ type: "text";
547
+ /**
548
+ * The text content.
549
+ */
550
+ text: string;
551
+ }
552
+
553
+ /**
554
+ * Data content. Can either be a base64-encoded string, a Uint8Array, or an ArrayBuffer.
555
+ */
556
+ export type DataContent = string | Uint8Array | ArrayBuffer;
557
+
558
+ /**
559
+ * Image content part of a prompt. It contains an image.
560
+ */
561
+ export interface ImagePart {
562
+ type: "image";
563
+ /**
564
+ * Image data. Can either be:
565
+ *
566
+ * - data: a base64-encoded string, a Uint8Array, an ArrayBuffer, or a Buffer
567
+ * - URL: a URL that points to the image
568
+ */
569
+ image: DataContent | URL;
570
+ /**
571
+ * Optional mime type of the image.
572
+ */
573
+ mimeType?: string;
574
+ }
575
+
576
+ /**
577
+ * File content part of a prompt. It contains a file.
578
+ */
579
+ export interface FilePart {
580
+ type: "file";
581
+ /**
582
+ * File data. Can either be:
583
+ *
584
+ * - data: a base64-encoded string, a Uint8Array, an ArrayBuffer, or a Buffer
585
+ * - URL: a URL that points to the file
586
+ */
587
+ data: DataContent | URL;
588
+ /**
589
+ * Optional filename of the file.
590
+ */
591
+ filename?: string;
592
+ /**
593
+ * IANA media type of the file.
594
+ *
595
+ * @see https://www.iana.org/assignments/media-types/media-types.xhtml
596
+ */
597
+ mediaType: string;
598
+ }
599
+
600
+ /**
601
+ * Reasoning content part of a prompt. It contains a reasoning.
602
+ */
603
+ export interface ReasoningPart {
604
+ type: "reasoning";
605
+ /**
606
+ * The reasoning text.
607
+ */
608
+ text: string;
609
+ /**
610
+ * An optional signature for verifying that the reasoning originated from the model.
611
+ */
612
+ signature?: string;
613
+ }
614
+
615
+ /**
616
+ * Redacted reasoning content part of a prompt.
617
+ */
618
+ export interface RedactedReasoningPart {
619
+ type: "redacted-reasoning";
620
+ /**
621
+ * Redacted reasoning data.
622
+ */
623
+ data: string;
624
+ }
625
+
626
+ /**
627
+ * Tool call content part of a prompt. It contains a tool call (usually generated by the AI model).
628
+ */
629
+ export interface ToolCallPart {
630
+ type: "tool-call";
631
+ /**
632
+ * ID of the tool call. This ID is used to match the tool call with the tool result.
633
+ */
634
+ toolCallId: string;
635
+ /**
636
+ * Name of the tool that is being called.
637
+ */
638
+ toolName: string;
639
+ /**
640
+ * Arguments of the tool call. This is a JSON-serializable object that matches the tool's input schema.
641
+ */
642
+ input: unknown;
643
+ }
644
+
645
+ type JSONValue = null | string | number | boolean | JSONObject | JSONArray;
646
+ type JSONObject = {
647
+ [key: string]: JSONValue;
648
+ };
649
+ type JSONArray = JSONValue[];
650
+
651
+ /**
652
+ * Tool result content part of a prompt. It contains the result of the tool call with the matching ID.
653
+ */
654
+ export interface ToolResultPart {
655
+ type: "tool-result";
656
+ /**
657
+ * ID of the tool call that this result is associated with.
658
+ */
659
+ toolCallId: string;
660
+ /**
661
+ * Name of the tool that generated this result.
662
+ */
663
+ toolName: string;
664
+ /**
665
+ * Result of the tool call. This is a JSON-serializable object.
666
+ */
667
+ output:
668
+ | {
669
+ type: "text";
670
+ value: string;
671
+ }
672
+ | {
673
+ type: "json";
674
+ value: JSONValue;
675
+ }
676
+ | {
677
+ type: "error-text";
678
+ value: string;
679
+ }
680
+ | {
681
+ type: "error-json";
682
+ value: JSONValue;
683
+ }
684
+ | {
685
+ type: "content";
686
+ value: Array<
687
+ | {
688
+ type: "text";
689
+ /**
690
+ Text content.
691
+ */
692
+ text: string;
693
+ }
694
+ | {
695
+ type: "media";
696
+ /**
697
+ Base-64 encoded media data.
698
+ */
699
+ data: string;
700
+ /**
701
+ IANA media type.
702
+ @see https://www.iana.org/assignments/media-types/media-types.xhtml
703
+ */
704
+ mediaType: string;
705
+ }
706
+ >;
707
+ };
708
+ }
709
+
710
+ // ============================================================================
711
+ // Tool Types
712
+ // ============================================================================
713
+
714
+ type ToolParameters = TSchema;
715
+
716
+ type inferParameters<PARAMETERS extends ToolParameters> = Static<PARAMETERS>;
717
+
718
+ /**
719
+ * Options passed to tool execution functions.
720
+ */
721
+ export interface ToolExecutionOptions {
722
+ /**
723
+ * The ID of the tool call. You can use it e.g. when sending tool-call related information with stream data.
724
+ */
725
+ toolCallId: string;
726
+ /**
727
+ * Messages that were sent to the language model to initiate the response that contained the tool call.
728
+ * The messages **do not** include the system prompt nor the assistant response that contained the tool call.
729
+ */
730
+ messages: AIMessage[];
731
+ /**
732
+ * An optional abort signal that indicates that the overall operation should be aborted.
733
+ */
734
+ abortSignal?: AbortSignal;
735
+ }
736
+
737
+ /**
738
+ * A tool contains the description and the schema of the input that the tool expects.
739
+ * This enables the language model to generate the input.
740
+ *
741
+ * The tool can also contain an optional execute function for the actual execution function of the tool.
742
+ */
743
+ export type AITool<PARAMETERS extends ToolParameters = any, RESULT = any> = {
744
+ /**
745
+ * The schema of the input that the tool expects. The language model will use this to generate the input.
746
+ * It is also used to validate the output of the language model.
747
+ * Use descriptions to make the input understandable for the language model.
748
+ */
749
+ parameters: PARAMETERS;
750
+ /**
751
+ * The schema of the input that the tool expects. The language model will use this to generate the input.
752
+ * It is also used to validate the output of the language model.
753
+ * Use descriptions to make the input understandable for the language model.
754
+ */
755
+ inputSchema: TSchema;
756
+ /**
757
+ * An optional description of what the tool does.
758
+ * Will be used by the language model to decide whether to use the tool.
759
+ * Not used for provider-defined tools.
760
+ */
761
+ description?: string;
762
+ /**
763
+ * An async function that is called with the arguments from the tool call and produces a result.
764
+ * If not provided, the tool will not be executed automatically.
765
+ *
766
+ * @param args - The input of the tool call
767
+ * @param options - Execution options including abort signal and messages
768
+ */
769
+ execute?: (
770
+ args: inferParameters<PARAMETERS>,
771
+ options: ToolExecutionOptions
772
+ ) => PromiseLike<RESULT>;
773
+ } & (
774
+ | {
775
+ /**
776
+ * Function tool.
777
+ */
778
+ type?: undefined | "function";
779
+ }
780
+ | {
781
+ /**
782
+ * Provider-defined tool.
783
+ */
784
+ type: "provider-defined";
785
+ /**
786
+ * The ID of the tool. Should follow the format `<provider-name>.<tool-name>`.
787
+ */
788
+ id: `${string}.${string}`;
789
+ /**
790
+ * The arguments for configuring the tool. Must match the expected arguments defined by the provider for this tool.
791
+ */
792
+ args: Record<string, unknown>;
793
+ }
794
+ );
795
+
796
+ /**
797
+ * Tool choice for the generation. It supports the following settings:
798
+ *
799
+ * - `auto` (default): the model can choose whether and which tools to call.
800
+ * - `required`: the model must call a tool. It can choose which tool to call.
801
+ * - `none`: the model must not call tools
802
+ * - `{ type: 'tool', toolName: string (typed) }`: the model must call the specified tool
803
+ */
804
+ type ToolChoice<TOOLS extends Record<string, unknown>> =
805
+ | "auto"
806
+ | "none"
807
+ | "required"
808
+ | {
809
+ type: "tool";
810
+ toolName: Extract<keyof TOOLS, string>;
811
+ };
812
+
813
+ export type AIToolSet = Record<
814
+ string,
815
+ (
816
+ | AITool<never, never>
817
+ | AITool<any, any>
818
+ | AITool<any, never>
819
+ | AITool<never, any>
820
+ ) &
821
+ Pick<AITool<any, any>, "execute">
822
+ >;
823
+
824
+ // ============================================================================
825
+ // Internal Helper Types
826
+ // ============================================================================
827
+
828
+ type ToolCallUnion<_TOOLS extends AIToolSet> = {
829
+ type: "tool-call";
830
+ toolCallId: string;
831
+ toolName: string;
832
+ args?: unknown;
833
+ };
834
+
835
+ type ToolCallArray<TOOLS extends AIToolSet> = Array<ToolCallUnion<TOOLS>>;
836
+
837
+ type ToolResultUnion<_TOOLS extends AIToolSet> = {
838
+ type: "tool-result";
839
+ toolCallId: string;
840
+ toolName: string;
841
+ args?: unknown;
842
+ result?: unknown;
843
+ };
844
+
845
+ type ToolResultArray<TOOLS extends AIToolSet> = Array<ToolResultUnion<TOOLS>>;