@tanstack/ai 0.0.3 → 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.
Files changed (146) hide show
  1. package/README.md +26 -0
  2. package/dist/esm/activities/chat/adapter.d.ts +100 -0
  3. package/dist/esm/activities/chat/adapter.js +14 -0
  4. package/dist/esm/activities/chat/adapter.js.map +1 -0
  5. package/dist/esm/{utilities → activities/chat}/agent-loop-strategies.d.ts +4 -4
  6. package/dist/esm/activities/chat/agent-loop-strategies.js.map +1 -0
  7. package/dist/esm/activities/chat/index.d.ts +166 -0
  8. package/dist/esm/{core/chat.js → activities/chat/index.js} +131 -33
  9. package/dist/esm/activities/chat/index.js.map +1 -0
  10. package/dist/esm/{message-converters.d.ts → activities/chat/messages.d.ts} +1 -1
  11. package/dist/esm/{message-converters.js → activities/chat/messages.js} +7 -7
  12. package/dist/esm/activities/chat/messages.js.map +1 -0
  13. package/dist/esm/activities/chat/stream/json-parser.js.map +1 -0
  14. package/dist/esm/{stream → activities/chat/stream}/message-updaters.d.ts +1 -1
  15. package/dist/esm/activities/chat/stream/message-updaters.js.map +1 -0
  16. package/dist/esm/{stream → activities/chat/stream}/processor.d.ts +1 -1
  17. package/dist/esm/{stream → activities/chat/stream}/processor.js +1 -1
  18. package/dist/esm/activities/chat/stream/processor.js.map +1 -0
  19. package/dist/esm/activities/chat/stream/strategies.js.map +1 -0
  20. package/dist/esm/{stream → activities/chat/stream}/types.d.ts +2 -9
  21. package/dist/esm/activities/chat/tools/schema-converter.d.ts +116 -0
  22. package/dist/esm/activities/chat/tools/schema-converter.js +115 -0
  23. package/dist/esm/activities/chat/tools/schema-converter.js.map +1 -0
  24. package/dist/esm/{tools → activities/chat/tools}/tool-calls.d.ts +1 -1
  25. package/dist/esm/{tools → activities/chat/tools}/tool-calls.js +23 -30
  26. package/dist/esm/activities/chat/tools/tool-calls.js.map +1 -0
  27. package/dist/esm/{tools → activities/chat/tools}/tool-definition.d.ts +22 -18
  28. package/dist/esm/activities/chat/tools/tool-definition.js.map +1 -0
  29. package/dist/esm/activities/generateImage/adapter.d.ts +68 -0
  30. package/dist/esm/activities/generateImage/adapter.js +14 -0
  31. package/dist/esm/activities/generateImage/adapter.js.map +1 -0
  32. package/dist/esm/activities/generateImage/index.d.ts +89 -0
  33. package/dist/esm/activities/generateImage/index.js +15 -0
  34. package/dist/esm/activities/generateImage/index.js.map +1 -0
  35. package/dist/esm/activities/generateSpeech/adapter.d.ts +62 -0
  36. package/dist/esm/activities/generateSpeech/adapter.js +14 -0
  37. package/dist/esm/activities/generateSpeech/adapter.js.map +1 -0
  38. package/dist/esm/activities/generateSpeech/index.d.ts +69 -0
  39. package/dist/esm/activities/generateSpeech/index.js +15 -0
  40. package/dist/esm/activities/generateSpeech/index.js.map +1 -0
  41. package/dist/esm/activities/generateTranscription/adapter.d.ts +62 -0
  42. package/dist/esm/activities/generateTranscription/adapter.js +14 -0
  43. package/dist/esm/activities/generateTranscription/adapter.js.map +1 -0
  44. package/dist/esm/activities/generateTranscription/index.d.ts +71 -0
  45. package/dist/esm/activities/generateTranscription/index.js +15 -0
  46. package/dist/esm/activities/generateTranscription/index.js.map +1 -0
  47. package/dist/esm/activities/generateVideo/adapter.d.ts +80 -0
  48. package/dist/esm/activities/generateVideo/adapter.js +14 -0
  49. package/dist/esm/activities/generateVideo/adapter.js.map +1 -0
  50. package/dist/esm/activities/generateVideo/index.d.ts +136 -0
  51. package/dist/esm/activities/generateVideo/index.js +47 -0
  52. package/dist/esm/activities/generateVideo/index.js.map +1 -0
  53. package/dist/esm/activities/index.d.ts +22 -0
  54. package/dist/esm/activities/index.js +34 -0
  55. package/dist/esm/activities/index.js.map +1 -0
  56. package/dist/esm/activities/summarize/adapter.d.ts +74 -0
  57. package/dist/esm/activities/summarize/adapter.js +14 -0
  58. package/dist/esm/activities/summarize/adapter.js.map +1 -0
  59. package/dist/esm/activities/summarize/index.d.ts +100 -0
  60. package/dist/esm/activities/summarize/index.js +90 -0
  61. package/dist/esm/activities/summarize/index.js.map +1 -0
  62. package/dist/esm/event-client.d.ts +4 -18
  63. package/dist/esm/event-client.js.map +1 -1
  64. package/dist/esm/index.d.ts +16 -14
  65. package/dist/esm/index.js +29 -20
  66. package/dist/esm/stream-to-response.d.ts +95 -0
  67. package/dist/esm/stream-to-response.js +118 -0
  68. package/dist/esm/stream-to-response.js.map +1 -0
  69. package/dist/esm/types.d.ts +370 -133
  70. package/package.json +7 -6
  71. package/src/activities/chat/adapter.ts +150 -0
  72. package/src/{utilities → activities/chat}/agent-loop-strategies.ts +4 -4
  73. package/src/{core/chat.ts → activities/chat/index.ts} +435 -79
  74. package/src/{message-converters.ts → activities/chat/messages.ts} +10 -13
  75. package/src/{stream → activities/chat/stream}/message-updaters.ts +1 -1
  76. package/src/{stream → activities/chat/stream}/processor.ts +2 -5
  77. package/src/{stream → activities/chat/stream}/types.ts +8 -18
  78. package/src/activities/chat/tools/schema-converter.ts +332 -0
  79. package/src/{tools → activities/chat/tools}/tool-calls.ts +63 -44
  80. package/src/{tools → activities/chat/tools}/tool-definition.ts +51 -38
  81. package/src/activities/generateImage/adapter.ts +104 -0
  82. package/src/activities/generateImage/index.ts +162 -0
  83. package/src/activities/generateSpeech/adapter.ts +87 -0
  84. package/src/activities/generateSpeech/index.ts +122 -0
  85. package/src/activities/generateTranscription/adapter.ts +89 -0
  86. package/src/activities/generateTranscription/index.ts +132 -0
  87. package/src/activities/generateVideo/adapter.ts +116 -0
  88. package/src/activities/generateVideo/index.ts +261 -0
  89. package/src/activities/index.ts +164 -0
  90. package/src/activities/summarize/adapter.ts +107 -0
  91. package/src/activities/summarize/index.ts +287 -0
  92. package/src/event-client.ts +5 -21
  93. package/src/index.ts +60 -15
  94. package/src/stream-to-response.ts +237 -0
  95. package/src/types.ts +429 -284
  96. package/dist/esm/base-adapter.d.ts +0 -36
  97. package/dist/esm/base-adapter.js +0 -12
  98. package/dist/esm/base-adapter.js.map +0 -1
  99. package/dist/esm/core/chat-common-options.d.ts +0 -52
  100. package/dist/esm/core/chat.d.ts +0 -30
  101. package/dist/esm/core/chat.js.map +0 -1
  102. package/dist/esm/core/embedding.d.ts +0 -8
  103. package/dist/esm/core/embedding.js +0 -33
  104. package/dist/esm/core/embedding.js.map +0 -1
  105. package/dist/esm/core/summarize.d.ts +0 -9
  106. package/dist/esm/core/summarize.js +0 -36
  107. package/dist/esm/core/summarize.js.map +0 -1
  108. package/dist/esm/message-converters.js.map +0 -1
  109. package/dist/esm/stream/json-parser.js.map +0 -1
  110. package/dist/esm/stream/message-updaters.js.map +0 -1
  111. package/dist/esm/stream/processor.js.map +0 -1
  112. package/dist/esm/stream/strategies.js.map +0 -1
  113. package/dist/esm/tools/tool-calls.js.map +0 -1
  114. package/dist/esm/tools/tool-definition.js.map +0 -1
  115. package/dist/esm/tools/zod-converter.d.ts +0 -30
  116. package/dist/esm/tools/zod-converter.js +0 -36
  117. package/dist/esm/tools/zod-converter.js.map +0 -1
  118. package/dist/esm/utilities/agent-loop-strategies.js.map +0 -1
  119. package/dist/esm/utilities/chat-options.d.ts +0 -6
  120. package/dist/esm/utilities/chat-options.js +0 -7
  121. package/dist/esm/utilities/chat-options.js.map +0 -1
  122. package/dist/esm/utilities/messages.d.ts +0 -30
  123. package/dist/esm/utilities/messages.js +0 -7
  124. package/dist/esm/utilities/messages.js.map +0 -1
  125. package/dist/esm/utilities/stream-to-response.d.ts +0 -48
  126. package/dist/esm/utilities/stream-to-response.js +0 -62
  127. package/dist/esm/utilities/stream-to-response.js.map +0 -1
  128. package/src/base-adapter.ts +0 -86
  129. package/src/core/chat-common-options.ts +0 -55
  130. package/src/core/embedding.ts +0 -54
  131. package/src/core/summarize.ts +0 -56
  132. package/src/tools/zod-converter.ts +0 -85
  133. package/src/utilities/chat-options.ts +0 -35
  134. package/src/utilities/messages.ts +0 -63
  135. package/src/utilities/stream-to-response.ts +0 -116
  136. /package/dist/esm/{utilities → activities/chat}/agent-loop-strategies.js +0 -0
  137. /package/dist/esm/{stream → activities/chat/stream}/index.d.ts +0 -0
  138. /package/dist/esm/{stream → activities/chat/stream}/json-parser.d.ts +0 -0
  139. /package/dist/esm/{stream → activities/chat/stream}/json-parser.js +0 -0
  140. /package/dist/esm/{stream → activities/chat/stream}/message-updaters.js +0 -0
  141. /package/dist/esm/{stream → activities/chat/stream}/strategies.d.ts +0 -0
  142. /package/dist/esm/{stream → activities/chat/stream}/strategies.js +0 -0
  143. /package/dist/esm/{tools → activities/chat/tools}/tool-definition.js +0 -0
  144. /package/src/{stream → activities/chat/stream}/index.ts +0 -0
  145. /package/src/{stream → activities/chat/stream}/json-parser.ts +0 -0
  146. /package/src/{stream → activities/chat/stream}/strategies.ts +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"schema-converter.js","sources":["../../../../../src/activities/chat/tools/schema-converter.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-unnecessary-condition */\n\nimport type {\n StandardJSONSchemaV1,\n StandardSchemaV1,\n} from '@standard-schema/spec'\nimport type { JSONSchema, SchemaInput } from '../../../types'\n\n/**\n * Check if a value is a Standard JSON Schema compliant schema.\n * Standard JSON Schema compliant libraries (Zod v4+, ArkType, Valibot with toStandardJsonSchema, etc.)\n * implement the '~standard' property with jsonSchema converter methods.\n */\nexport function isStandardJSONSchema(\n schema: unknown,\n): schema is StandardJSONSchemaV1 {\n return (\n typeof schema === 'object' &&\n schema !== null &&\n '~standard' in schema &&\n typeof (schema as StandardJSONSchemaV1)['~standard'] === 'object' &&\n (schema as StandardJSONSchemaV1)['~standard'].version === 1 &&\n typeof (schema as StandardJSONSchemaV1)['~standard'].jsonSchema ===\n 'object' &&\n typeof (schema as StandardJSONSchemaV1)['~standard'].jsonSchema.input ===\n 'function'\n )\n}\n\n/**\n * Check if a value is a Standard Schema compliant schema (for validation).\n * Standard Schema compliant libraries implement the '~standard' property with a validate function.\n */\nexport function isStandardSchema(schema: unknown): schema is StandardSchemaV1 {\n return (\n typeof schema === 'object' &&\n schema !== null &&\n '~standard' in schema &&\n typeof schema['~standard'] === 'object' &&\n schema !== null &&\n schema['~standard'] !== null &&\n 'version' in schema['~standard'] &&\n schema['~standard'].version === 1 &&\n 'validate' in schema['~standard'] &&\n typeof schema['~standard'].validate === 'function'\n )\n}\n\n/**\n * Transform a JSON schema to be compatible with OpenAI's structured output requirements.\n * OpenAI requires:\n * - All properties must be in the `required` array\n * - Optional fields should have null added to their type union\n * - additionalProperties must be false for objects\n *\n * @param schema - JSON schema to transform\n * @param originalRequired - Original required array (to know which fields were optional)\n * @returns Transformed schema compatible with OpenAI structured output\n */\nfunction makeStructuredOutputCompatible(\n schema: Record<string, any>,\n originalRequired: Array<string> = [],\n): Record<string, any> {\n const result = { ...schema }\n\n // Handle object types\n if (result.type === 'object' && result.properties) {\n const properties = { ...result.properties }\n const allPropertyNames = Object.keys(properties)\n\n // Transform each property\n for (const propName of allPropertyNames) {\n const prop = properties[propName]\n const wasOptional = !originalRequired.includes(propName)\n\n // Recursively transform nested objects/arrays\n if (prop.type === 'object' && prop.properties) {\n properties[propName] = makeStructuredOutputCompatible(\n prop,\n prop.required || [],\n )\n } else if (prop.type === 'array' && prop.items) {\n properties[propName] = {\n ...prop,\n items: makeStructuredOutputCompatible(\n prop.items,\n prop.items.required || [],\n ),\n }\n } else if (wasOptional) {\n // Make optional fields nullable by adding null to the type\n if (prop.type && !Array.isArray(prop.type)) {\n properties[propName] = {\n ...prop,\n type: [prop.type, 'null'],\n }\n } else if (Array.isArray(prop.type) && !prop.type.includes('null')) {\n properties[propName] = {\n ...prop,\n type: [...prop.type, 'null'],\n }\n }\n }\n }\n\n result.properties = properties\n // ALL properties must be required for OpenAI structured output\n result.required = allPropertyNames\n // additionalProperties must be false\n result.additionalProperties = false\n }\n\n // Handle array types with object items\n if (result.type === 'array' && result.items) {\n result.items = makeStructuredOutputCompatible(\n result.items,\n result.items.required || [],\n )\n }\n\n return result\n}\n\n/**\n * Options for schema conversion\n */\nexport interface ConvertSchemaOptions {\n /**\n * When true, transforms the schema to be compatible with OpenAI's structured output requirements:\n * - All properties are added to the `required` array\n * - Optional fields get null added to their type union\n * - additionalProperties is set to false for all objects\n *\n * @default false\n */\n forStructuredOutput?: boolean\n}\n\n/**\n * Converts a Standard JSON Schema compliant schema or plain JSONSchema to JSON Schema format\n * compatible with LLM providers.\n *\n * Supports any schema library that implements the Standard JSON Schema spec (v1):\n * - Zod v4+ (natively supports StandardJSONSchemaV1)\n * - ArkType (natively supports StandardJSONSchemaV1)\n * - Valibot (via `toStandardJsonSchema()` from `@valibot/to-json-schema`)\n *\n * If the input is already a plain JSONSchema object, it is returned as-is.\n *\n * @param schema - Standard JSON Schema compliant schema or plain JSONSchema object to convert\n * @param options - Conversion options\n * @returns JSON Schema object that can be sent to LLM providers\n *\n * @example\n * ```typescript\n * // Using Zod v4+ (natively supports Standard JSON Schema)\n * import * as z from 'zod';\n *\n * const zodSchema = z.object({\n * location: z.string().describe('City name'),\n * unit: z.enum(['celsius', 'fahrenheit']).optional()\n * });\n *\n * const jsonSchema = convertSchemaToJsonSchema(zodSchema);\n *\n * @example\n * // Using ArkType (natively supports Standard JSON Schema)\n * import { type } from 'arktype';\n *\n * const arkSchema = type({\n * location: 'string',\n * unit: \"'celsius' | 'fahrenheit'\"\n * });\n *\n * const jsonSchema = convertSchemaToJsonSchema(arkSchema);\n *\n * @example\n * // Using Valibot (via toStandardJsonSchema)\n * import * as v from 'valibot';\n * import { toStandardJsonSchema } from '@valibot/to-json-schema';\n *\n * const valibotSchema = toStandardJsonSchema(v.object({\n * location: v.string(),\n * unit: v.optional(v.picklist(['celsius', 'fahrenheit']))\n * }));\n *\n * const jsonSchema = convertSchemaToJsonSchema(valibotSchema);\n *\n * @example\n * // Using JSONSchema directly (passes through unchanged)\n * const rawSchema = {\n * type: 'object',\n * properties: { location: { type: 'string' } },\n * required: ['location']\n * };\n * const result = convertSchemaToJsonSchema(rawSchema);\n * ```\n */\nexport function convertSchemaToJsonSchema(\n schema: SchemaInput | undefined,\n options: ConvertSchemaOptions = {},\n): JSONSchema | undefined {\n if (!schema) return undefined\n\n const { forStructuredOutput = false } = options\n\n // If it's a Standard JSON Schema compliant schema, use the standard interface\n if (isStandardJSONSchema(schema)) {\n const jsonSchema = schema['~standard'].jsonSchema.input({\n target: 'draft-07',\n })\n\n let result = jsonSchema\n\n if (typeof result === 'object' && '$schema' in result) {\n // Remove $schema property as it's not needed for LLM providers\n const { $schema, ...rest } = result\n result = rest\n }\n\n // Ensure object schemas always have type: \"object\"\n\n if (typeof result === 'object') {\n // If it has properties (even empty), it should be an object type\n if ('properties' in result && !result.type) {\n result.type = 'object'\n }\n\n // Ensure properties exists for object types (even if empty)\n if (result.type === 'object' && !('properties' in result)) {\n result.properties = {}\n }\n\n // Ensure required exists for object types (even if empty array)\n if (result.type === 'object' && !('required' in result)) {\n result.required = []\n }\n\n // Apply structured output transformation if requested\n if (forStructuredOutput) {\n result = makeStructuredOutputCompatible(\n result,\n (result.required as Array<string>) || [],\n )\n }\n }\n\n return result as JSONSchema\n }\n\n // If it's not a Standard JSON Schema, assume it's already a JSONSchema and pass through\n // Still apply structured output transformation if requested\n\n if (forStructuredOutput && typeof schema === 'object') {\n return makeStructuredOutputCompatible(\n schema as Record<string, any>,\n ((schema as JSONSchema).required as Array<string>) || [],\n ) as JSONSchema\n }\n\n return schema as JSONSchema\n}\n\n/**\n * Validates data against a Standard Schema compliant schema.\n *\n * @param schema - Standard Schema compliant schema\n * @param data - Data to validate\n * @returns Validation result with success status, data or issues\n */\nexport async function validateWithStandardSchema<T>(\n schema: unknown,\n data: unknown,\n): Promise<\n | { success: true; data: T }\n | { success: false; issues: Array<{ message: string; path?: Array<string> }> }\n> {\n if (!isStandardSchema(schema)) {\n // If it's not a Standard Schema, just return the data as-is\n return { success: true, data: data as T }\n }\n\n const result = await schema['~standard'].validate(data)\n\n if (!result.issues) {\n return { success: true, data: result.value as T }\n }\n\n return {\n success: false,\n issues: result.issues.map((issue) => ({\n message: issue.message || 'Validation failed',\n path: issue.path?.map(String),\n })),\n }\n}\n\n/**\n * Synchronously validates data against a Standard Schema compliant schema.\n * Note: Some Standard Schema implementations may only support async validation.\n * In those cases, this function will throw.\n *\n * @param schema - Standard Schema compliant schema\n * @param data - Data to validate\n * @returns Parsed/validated data\n * @throws Error if validation fails or if the schema only supports async validation\n */\nexport function parseWithStandardSchema<T>(schema: unknown, data: unknown): T {\n if (!isStandardSchema(schema)) {\n // If it's not a Standard Schema, just return the data as-is\n return data as T\n }\n\n const result = schema['~standard'].validate(data)\n\n // Handle async result (Promise)\n if (result instanceof Promise) {\n throw new Error(\n 'Schema validation returned a Promise. Use validateWithStandardSchema for async validation.',\n )\n }\n // Standard Schema validation returns { value } for success or { issues } for failure\n if (!result.issues) {\n return result.value as T\n }\n\n // invalid validation, throw error with all issues\n const errorMessages = result.issues\n .map((issue) => issue.message || 'Validation failed')\n .join(', ')\n throw new Error(`Validation failed: ${errorMessages}`)\n}\n"],"names":[],"mappings":"AAaO,SAAS,qBACd,QACgC;AAChC,SACE,OAAO,WAAW,YAClB,WAAW,QACX,eAAe,UACf,OAAQ,OAAgC,WAAW,MAAM,YACxD,OAAgC,WAAW,EAAE,YAAY,KAC1D,OAAQ,OAAgC,WAAW,EAAE,eACnD,YACF,OAAQ,OAAgC,WAAW,EAAE,WAAW,UAC9D;AAEN;AAMO,SAAS,iBAAiB,QAA6C;AAC5E,SACE,OAAO,WAAW,YAClB,WAAW,QACX,eAAe,UACf,OAAO,OAAO,WAAW,MAAM,YAC/B,WAAW,QACX,OAAO,WAAW,MAAM,QACxB,aAAa,OAAO,WAAW,KAC/B,OAAO,WAAW,EAAE,YAAY,KAChC,cAAc,OAAO,WAAW,KAChC,OAAO,OAAO,WAAW,EAAE,aAAa;AAE5C;AAaA,SAAS,+BACP,QACA,mBAAkC,IACb;AACrB,QAAM,SAAS,EAAE,GAAG,OAAA;AAGpB,MAAI,OAAO,SAAS,YAAY,OAAO,YAAY;AACjD,UAAM,aAAa,EAAE,GAAG,OAAO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oneStreamChunk, ModelMessage, Tool, ToolCall, ToolResultStreamChunk } from '../types.js';
1
+ import { DoneStreamChunk, ModelMessage, Tool, ToolCall, ToolResultStreamChunk } from '../../../types.js';
2
2
  /**
3
3
  * Manages tool call accumulation and execution for the chat() method's automatic tool execution loop.
4
4
  *
@@ -1,3 +1,4 @@
1
+ import { isStandardSchema, parseWithStandardSchema } from "./schema-converter.js";
1
2
  class ToolCallManager {
2
3
  constructor(tools) {
3
4
  this.toolCallsMap = /* @__PURE__ */ new Map();
@@ -64,28 +65,31 @@ class ToolCallManager {
64
65
  `Failed to parse tool arguments as JSON: ${toolCall.function.arguments}`
65
66
  );
66
67
  }
67
- if (tool.inputSchema) {
68
+ if (tool.inputSchema && isStandardSchema(tool.inputSchema)) {
68
69
  try {
69
- args = tool.inputSchema.parse(args);
70
+ args = parseWithStandardSchema(tool.inputSchema, args);
70
71
  } catch (validationError) {
72
+ const message = validationError instanceof Error ? validationError.message : "Validation failed";
71
73
  throw new Error(
72
- `Input validation failed for tool ${tool.name}: ${validationError.message}`
74
+ `Input validation failed for tool ${tool.name}: ${message}`
73
75
  );
74
76
  }
75
77
  }
76
78
  let result = await tool.execute(args);
77
- if (tool.outputSchema && result !== void 0 && result !== null) {
79
+ if (tool.outputSchema && isStandardSchema(tool.outputSchema) && result !== void 0 && result !== null) {
78
80
  try {
79
- result = tool.outputSchema.parse(result);
81
+ result = parseWithStandardSchema(tool.outputSchema, result);
80
82
  } catch (validationError) {
83
+ const message = validationError instanceof Error ? validationError.message : "Validation failed";
81
84
  throw new Error(
82
- `Output validation failed for tool ${tool.name}: ${validationError.message}`
85
+ `Output validation failed for tool ${tool.name}: ${message}`
83
86
  );
84
87
  }
85
88
  }
86
89
  toolResultContent = typeof result === "string" ? result : JSON.stringify(result);
87
90
  } catch (error) {
88
- toolResultContent = `Error executing tool: ${error.message}`;
91
+ const message = error instanceof Error ? error.message : "Unknown error";
92
+ toolResultContent = `Error executing tool: ${message}`;
89
93
  }
90
94
  } else {
91
95
  toolResultContent = `Tool ${toolCall.function.name} does not have an execute function`;
@@ -142,15 +146,16 @@ async function executeToolCalls(toolCalls, tools, approvals = /* @__PURE__ */ ne
142
146
  throw new Error(`Failed to parse tool arguments as JSON: ${argsStr}`);
143
147
  }
144
148
  }
145
- if (tool.inputSchema) {
149
+ if (tool.inputSchema && isStandardSchema(tool.inputSchema)) {
146
150
  try {
147
- input = tool.inputSchema.parse(input);
151
+ input = parseWithStandardSchema(tool.inputSchema, input);
148
152
  } catch (validationError) {
153
+ const message = validationError instanceof Error ? validationError.message : "Validation failed";
149
154
  results.push({
150
155
  toolCallId: toolCall.id,
151
156
  toolName,
152
157
  result: {
153
- error: `Input validation failed for tool ${tool.name}: ${validationError.message}`
158
+ error: `Input validation failed for tool ${tool.name}: ${message}`
154
159
  },
155
160
  state: "output-error"
156
161
  });
@@ -218,15 +223,8 @@ async function executeToolCalls(toolCalls, tools, approvals = /* @__PURE__ */ ne
218
223
  try {
219
224
  let result = await tool.execute(input);
220
225
  const duration = Date.now() - startTime2;
221
- if (tool.outputSchema && result !== void 0 && result !== null) {
222
- const parsed = tool.outputSchema.safeParse(result);
223
- if (parsed.success) {
224
- result = parsed.data;
225
- } else {
226
- throw new Error(
227
- `Output validation failed for tool ${tool.name}: ${parsed.error.message}`
228
- );
229
- }
226
+ if (tool.outputSchema && isStandardSchema(tool.outputSchema) && result !== void 0 && result !== null) {
227
+ result = parseWithStandardSchema(tool.outputSchema, result);
230
228
  }
231
229
  results.push({
232
230
  toolCallId: toolCall.id,
@@ -236,10 +234,11 @@ async function executeToolCalls(toolCalls, tools, approvals = /* @__PURE__ */ ne
236
234
  });
237
235
  } catch (error) {
238
236
  const duration = Date.now() - startTime2;
237
+ const message = error instanceof Error ? error.message : "Unknown error";
239
238
  results.push({
240
239
  toolCallId: toolCall.id,
241
240
  toolName,
242
- result: { error: error.message },
241
+ result: { error: message },
243
242
  state: "output-error",
244
243
  duration
245
244
  });
@@ -266,15 +265,8 @@ async function executeToolCalls(toolCalls, tools, approvals = /* @__PURE__ */ ne
266
265
  try {
267
266
  let result = await tool.execute(input);
268
267
  const duration = Date.now() - startTime;
269
- if (tool.outputSchema && result !== void 0 && result !== null) {
270
- const parsed = tool.outputSchema.safeParse(result);
271
- if (parsed.success) {
272
- result = parsed.data;
273
- } else {
274
- throw new Error(
275
- `Output validation failed for tool ${tool.name}: ${parsed.error.message}`
276
- );
277
- }
268
+ if (tool.outputSchema && isStandardSchema(tool.outputSchema) && result !== void 0 && result !== null) {
269
+ result = parseWithStandardSchema(tool.outputSchema, result);
278
270
  }
279
271
  results.push({
280
272
  toolCallId: toolCall.id,
@@ -284,10 +276,11 @@ async function executeToolCalls(toolCalls, tools, approvals = /* @__PURE__ */ ne
284
276
  });
285
277
  } catch (error) {
286
278
  const duration = Date.now() - startTime;
279
+ const message = error instanceof Error ? error.message : "Unknown error";
287
280
  results.push({
288
281
  toolCallId: toolCall.id,
289
282
  toolName,
290
- result: { error: error.message },
283
+ result: { error: message },
291
284
  state: "output-error",
292
285
  duration
293
286
  });
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tool-calls.js","sources":["../../../../../src/activities/chat/tools/tool-calls.ts"],"sourcesContent":["import { isStandardSchema, parseWithStandardSchema } from './schema-converter'\nimport type {\n DoneStreamChunk,\n ModelMessage,\n Tool,\n ToolCall,\n ToolResultStreamChunk,\n} from '../../../types'\n\n/**\n * Manages tool call accumulation and execution for the chat() method's automatic tool execution loop.\n *\n * Responsibilities:\n * - Accumulates streaming tool call chunks (ID, name, arguments)\n * - Validates tool calls (filters out incomplete ones)\n * - Executes tool `execute` functions with parsed arguments\n * - Emits `tool_result` chunks for client visibility\n * - Returns tool result messages for conversation history\n *\n * This class is used internally by the AI.chat() method to handle the automatic\n * tool execution loop. It can also be used independently for custom tool execution logic.\n *\n * @example\n * ```typescript\n * const manager = new ToolCallManager(tools);\n *\n * // During streaming, accumulate tool calls\n * for await (const chunk of stream) {\n * if (chunk.type === \"tool_call\") {\n * manager.addToolCallChunk(chunk);\n * }\n * }\n *\n * // After stream completes, execute tools\n * if (manager.hasToolCalls()) {\n * const toolResults = yield* manager.executeTools(doneChunk);\n * messages = [...messages, ...toolResults];\n * manager.clear();\n * }\n * ```\n */\nexport class ToolCallManager {\n private toolCallsMap = new Map<number, ToolCall>()\n private tools: ReadonlyArray<Tool>\n\n constructor(tools: ReadonlyArray<Tool>) {\n this.tools = tools\n }\n\n /**\n * Add a tool call chunk to the accumulator\n * Handles streaming tool calls by accumulating arguments\n */\n addToolCallChunk(chunk: {\n toolCall: {\n id: string\n type: 'function'\n function: {\n name: string\n arguments: string\n }\n }\n index: number\n }): void {\n const index = chunk.index\n const existing = this.toolCallsMap.get(index)\n\n if (!existing) {\n // Only create entry if we have a tool call ID and name\n if (chunk.toolCall.id && chunk.toolCall.function.name) {\n this.toolCallsMap.set(index, {\n id: chunk.toolCall.id,\n type: 'function',\n function: {\n name: chunk.toolCall.function.name,\n arguments: chunk.toolCall.function.arguments || '',\n },\n })\n }\n } else {\n // Update name if it wasn't set before\n if (chunk.toolCall.function.name && !existing.function.name) {\n existing.function.name = chunk.toolCall.function.name\n }\n // Accumulate arguments for streaming tool calls\n if (chunk.toolCall.function.arguments) {\n existing.function.arguments += chunk.toolCall.function.arguments\n }\n }\n }\n\n /**\n * Check if there are any complete tool calls to execute\n */\n hasToolCalls(): boolean {\n return this.getToolCalls().length > 0\n }\n\n /**\n * Get all complete tool calls (filtered for valid ID and name)\n */\n getToolCalls(): Array<ToolCall> {\n return Array.from(this.toolCallsMap.values()).filter(\n (tc) => tc.id && tc.function.name && tc.function.name.trim().length > 0,\n )\n }\n\n /**\n * Execute all tool calls and return tool result messages\n * Also yields tool_result chunks for streaming\n */\n async *executeTools(\n doneChunk: DoneStreamChunk,\n ): AsyncGenerator<ToolResultStreamChunk, Array<ModelMessage>, void> {\n const toolCallsArray = this.getToolCalls()\n const toolResults: Array<ModelMessage> = []\n\n for (const toolCall of toolCallsArray) {\n const tool = this.tools.find((t) => t.name === toolCall.function.name)\n\n let toolResultContent: string\n if (tool?.execute) {\n try {\n // Parse arguments\n let args: unknown\n try {\n args = JSON.parse(toolCall.function.arguments)\n } catch (parseError) {\n throw new Error(\n `Failed to parse tool arguments as JSON: ${toolCall.function.arguments}`,\n )\n }\n\n // Validate input against inputSchema (for Standard Schema compliant schemas)\n if (tool.inputSchema && isStandardSchema(tool.inputSchema)) {\n try {\n args = parseWithStandardSchema(tool.inputSchema, args)\n } catch (validationError: unknown) {\n const message =\n validationError instanceof Error\n ? validationError.message\n : 'Validation failed'\n throw new Error(\n `Input validation failed for tool ${tool.name}: ${message}`,\n )\n }\n }\n\n // Execute the tool\n let result = await tool.execute(args)\n\n // Validate output against outputSchema if provided (for Standard Schema compliant schemas)\n if (\n tool.outputSchema &&\n isStandardSchema(tool.outputSchema) &&\n result !== undefined &&\n result !== null\n ) {\n try {\n result = parseWithStandardSchema(tool.outputSchema, result)\n } catch (validationError: unknown) {\n const message =\n validationError instanceof Error\n ? validationError.message\n : 'Validation failed'\n throw new Error(\n `Output validation failed for tool ${tool.name}: ${message}`,\n )\n }\n }\n\n toolResultContent =\n typeof result === 'string' ? result : JSON.stringify(result)\n } catch (error: unknown) {\n // If tool execution fails, add error message\n const message =\n error instanceof Error ? error.message : 'Unknown error'\n toolResultContent = `Error executing tool: ${message}`\n }\n } else {\n // Tool doesn't have execute function, add placeholder\n toolResultContent = `Tool ${toolCall.function.name} does not have an execute function`\n }\n\n // Emit tool_result chunk so callers can track tool execution\n yield {\n type: 'tool_result',\n id: doneChunk.id,\n model: doneChunk.model,\n timestamp: Date.now(),\n toolCallId: toolCall.id,\n content: toolResultContent,\n }\n\n // Add tool result message\n toolResults.push({\n role: 'tool',\n content: toolResultContent,\n toolCallId: toolCall.id,\n })\n }\n\n return toolResults\n }\n\n /**\n * Clear the tool calls map for the next iteration\n */\n clear(): void {\n this.toolCallsMap.clear()\n }\n}\n\nexport interface ToolResult {\n toolCallId: string\n toolName: string\n result: any\n state?: 'output-available' | 'output-error'\n /** Duration of tool execution in milliseconds (only for server-executed tools) */\n duration?: number\n}\n\nexport interface ApprovalRequest {\n toolCallId: string\n toolName: string\n input: any\n approvalId: string\n}\n\nexport interface ClientToolRequest {\n toolCallId: string\n toolName: string\n input: any\n}\n\ninterface ExecuteToolCallsResult {\n /** Tool results ready to send to LLM */\n results: Array<ToolResult>\n /** Tools that need user approval before execution */\n needsApproval: Array<ApprovalRequest>\n /** Tools that need client-side execution */\n needsClientExecution: Array<ClientToolRequest>\n}\n\n/**\n * Execute tool calls based on their configuration\n *\n * Handles three cases:\n * 1. Client tools (no execute) - request client to execute\n * 2. Server tools with approval - check approval before executing\n * 3. Normal server tools - execute immediately\n *\n * @param toolCalls - Tool calls from the LLM\n * @param tools - Available tools with their configurations\n * @param approvals - Map of approval decisions (approval.id -> approved boolean)\n * @param clientResults - Map of client-side execution results (toolCallId -> result)\n */\nexport async function executeToolCalls(\n toolCalls: Array<ToolCall>,\n tools: ReadonlyArray<Tool>,\n approvals: Map<string, boolean> = new Map(),\n clientResults: Map<string, any> = new Map(),\n): Promise<ExecuteToolCallsResult> {\n const results: Array<ToolResult> = []\n const needsApproval: Array<ApprovalRequest> = []\n const needsClientExecution: Array<ClientToolRequest> = []\n\n // Create tool lookup map\n const toolMap = new Map<string, Tool>()\n for (const tool of tools) {\n toolMap.set(tool.name, tool)\n }\n\n for (const toolCall of toolCalls) {\n const tool = toolMap.get(toolCall.function.name)\n const toolName = toolCall.function.name\n\n if (!tool) {\n // Unknown tool - return error\n results.push({\n toolCallId: toolCall.id,\n toolName,\n result: { error: `Unknown tool: ${toolName}` },\n state: 'output-error',\n })\n continue\n }\n\n // Parse arguments, throwing error if invalid JSON\n let input: unknown = {}\n const argsStr = toolCall.function.arguments.trim() || '{}'\n if (argsStr) {\n try {\n input = JSON.parse(argsStr)\n } catch (parseError) {\n // If parsing fails, throw error to fail fast\n throw new Error(`Failed to parse tool arguments as JSON: ${argsStr}`)\n }\n }\n\n // Validate input against inputSchema (for Standard Schema compliant schemas)\n if (tool.inputSchema && isStandardSchema(tool.inputSchema)) {\n try {\n input = parseWithStandardSchema(tool.inputSchema, input)\n } catch (validationError: unknown) {\n const message =\n validationError instanceof Error\n ? validationError.message\n : 'Validation failed'\n results.push({\n toolCallId: toolCall.id,\n toolName,\n result: {\n error: `Input validation failed for tool ${tool.name}: ${message}`,\n },\n state: 'output-error',\n })\n continue\n }\n }\n\n // CASE 1: Client-side tool (no execute function)\n if (!tool.execute) {\n // Check if tool needs approval\n if (tool.needsApproval) {\n const approvalId = `approval_${toolCall.id}`\n\n // Check if approval decision exists\n if (approvals.has(approvalId)) {\n const approved = approvals.get(approvalId)\n\n if (approved) {\n // Approved - check if client has executed\n if (clientResults.has(toolCall.id)) {\n results.push({\n toolCallId: toolCall.id,\n toolName,\n result: clientResults.get(toolCall.id),\n })\n } else {\n // Approved but not executed yet - request client execution\n needsClientExecution.push({\n toolCallId: toolCall.id,\n toolName,\n input,\n })\n }\n } else {\n // User declined\n results.push({\n toolCallId: toolCall.id,\n toolName,\n result: { error: 'User declined tool execution' },\n state: 'output-error',\n })\n }\n } else {\n // Need approval first\n needsApproval.push({\n toolCallId: toolCall.id,\n toolName: toolCall.function.name,\n input,\n approvalId,\n })\n }\n } else {\n // No approval needed - check if client has executed\n if (clientResults.has(toolCall.id)) {\n results.push({\n toolCallId: toolCall.id,\n toolName,\n result: clientResults.get(toolCall.id),\n })\n } else {\n // Request client execution\n needsClientExecution.push({\n toolCallId: toolCall.id,\n toolName,\n input,\n })\n }\n }\n continue\n }\n\n // CASE 2: Server tool with approval required\n if (tool.needsApproval) {\n const approvalId = `approval_${toolCall.id}`\n\n // Check if approval decision exists\n if (approvals.has(approvalId)) {\n const approved = approvals.get(approvalId)\n\n if (approved) {\n // Execute after approval\n const startTime = Date.now()\n try {\n let result = await tool.execute(input)\n const duration = Date.now() - startTime\n\n // Validate output against outputSchema if provided (for Standard Schema compliant schemas)\n if (\n tool.outputSchema &&\n isStandardSchema(tool.outputSchema) &&\n result !== undefined &&\n result !== null\n ) {\n result = parseWithStandardSchema(tool.outputSchema, result)\n }\n\n results.push({\n toolCallId: toolCall.id,\n toolName,\n result:\n typeof result === 'string'\n ? JSON.parse(result)\n : result || null,\n duration,\n })\n } catch (error: unknown) {\n const duration = Date.now() - startTime\n const message =\n error instanceof Error ? error.message : 'Unknown error'\n results.push({\n toolCallId: toolCall.id,\n toolName,\n result: { error: message },\n state: 'output-error',\n duration,\n })\n }\n } else {\n // User declined\n results.push({\n toolCallId: toolCall.id,\n toolName,\n result: { error: 'User declined tool execution' },\n state: 'output-error',\n })\n }\n } else {\n // Need approval\n needsApproval.push({\n toolCallId: toolCall.id,\n toolName,\n input,\n approvalId,\n })\n }\n continue\n }\n\n // CASE 3: Normal server tool - execute immediately\n const startTime = Date.now()\n try {\n let result = await tool.execute(input)\n const duration = Date.now() - startTime\n\n // Validate output against outputSchema if provided (for Standard Schema compliant schemas)\n if (\n tool.outputSchema &&\n isStandardSchema(tool.outputSchema) &&\n result !== undefined &&\n result !== null\n ) {\n result = parseWithStandardSchema(tool.outputSchema, result)\n }\n\n results.push({\n toolCallId: toolCall.id,\n toolName,\n result:\n typeof result === 'string' ? JSON.parse(result) : result || null,\n duration,\n })\n } catch (error: unknown) {\n const duration = Date.now() - startTime\n const message = error instanceof Error ? error.message : 'Unknown error'\n results.push({\n toolCallId: toolCall.id,\n toolName,\n result: { error: message },\n state: 'output-error',\n duration,\n })\n }\n }\n\n return { results, needsApproval, needsClientExecution }\n}\n"],"names":["startTime"],"mappings":";AAyCO,MAAM,gBAAgB;AAAA,EAI3B,YAAY,OAA4B;AAHxC,SAAQ,mCAAmB,IAAA;AAIzB,SAAK,QAAQ;AAAA,EACf;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,iBAAiB,OAUR;AACP,UAAM,QAAQ,MAAM;AACpB,UAAM,WAAW,KAAK,aAAa,IAAI,KAAK;AAE5C,QAAI,CAAC,UAAU;AAEb,UAAI,MAAM,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S,OAAgB;AACvB,YAAM,WAAW,KAAK,IAAA,IAAQ;AAC9B,YAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU;AACzD,cAAQ,KAAK;AAAA,QACX,YAAY,SAAS;AAAA,QACrB;AAAA,QACA,QAAQ,EAAE,OAAO,QAAA;AAAA,QACjB,OAAO;AAAA,QACP;AAAA,MAAA,CACD;AAAA,IACH;AAAA,EACF;AAEA,SAAO,EAAE,SAAS,eAAe,qBAAA;AACnC;"}
@@ -1,34 +1,34 @@
1
- import { z } from 'zod';
2
- import { Tool } from '../types.js';
1
+ import { StandardJSONSchemaV1 } from '@standard-schema/spec';
2
+ import { InferSchemaType, JSONSchema, SchemaInput, Tool } from '../../../types.js';
3
3
  /**
4
4
  * Marker type for server-side tools
5
5
  */
6
- export interface ServerTool<TInput extends z.ZodType = z.ZodType, TOutput extends z.ZodType = z.ZodType, TName extends string = string> extends Tool<TInput, TOutput, TName> {
6
+ export interface ServerTool<TInput extends SchemaInput = SchemaInput, TOutput extends SchemaInput = SchemaInput, TName extends string = string> extends Tool<TInput, TOutput, TName> {
7
7
  __toolSide: 'server';
8
8
  }
9
9
  /**
10
10
  * Marker type for client-side tools
11
11
  */
12
- export interface ClientTool<TInput extends z.ZodType = z.ZodType, TOutput extends z.ZodType = z.ZodType, TName extends string = string> {
12
+ export interface ClientTool<TInput extends SchemaInput = SchemaInput, TOutput extends SchemaInput = SchemaInput, TName extends string = string> {
13
13
  __toolSide: 'client';
14
14
  name: TName;
15
15
  description: string;
16
16
  inputSchema?: TInput;
17
17
  outputSchema?: TOutput;
18
18
  needsApproval?: boolean;
19
- metadata?: Record<string, any>;
20
- execute?: (args: z.infer<TInput>) => Promise<z.infer<TOutput>> | z.infer<TOutput>;
19
+ metadata?: Record<string, unknown>;
20
+ execute?: (args: InferSchemaType<TInput>) => Promise<InferSchemaType<TOutput>> | InferSchemaType<TOutput>;
21
21
  }
22
22
  /**
23
23
  * Tool definition that can be used directly or instantiated for server/client
24
24
  */
25
- export interface ToolDefinitionInstance<TInput extends z.ZodType = z.ZodType, TOutput extends z.ZodType = z.ZodType, TName extends string = string> extends Tool<TInput, TOutput, TName> {
25
+ export interface ToolDefinitionInstance<TInput extends SchemaInput = SchemaInput, TOutput extends SchemaInput = SchemaInput, TName extends string = string> extends Tool<TInput, TOutput, TName> {
26
26
  __toolSide: 'definition';
27
27
  }
28
28
  /**
29
29
  * Union type for any kind of client-side tool (client tool or definition)
30
30
  */
31
- export type AnyClientTool = ClientTool<any, any> | ToolDefinitionInstance<any, any>;
31
+ export type AnyClientTool = ClientTool<SchemaInput, SchemaInput> | ToolDefinitionInstance<SchemaInput, SchemaInput>;
32
32
  /**
33
33
  * Extract the tool name as a literal type
34
34
  */
@@ -36,40 +36,40 @@ export type InferToolName<T> = T extends {
36
36
  name: infer N;
37
37
  } ? N : never;
38
38
  /**
39
- * Extract the input type from a tool (inferred from Zod schema)
39
+ * Extract the input type from a tool (inferred from Standard JSON Schema, or `unknown` for plain JSONSchema)
40
40
  */
41
41
  export type InferToolInput<T> = T extends {
42
42
  inputSchema?: infer TInput;
43
- } ? TInput extends z.ZodType ? z.infer<TInput> : any : any;
43
+ } ? TInput extends StandardJSONSchemaV1<infer TInferred, unknown> ? TInferred : TInput extends JSONSchema ? unknown : unknown : unknown;
44
44
  /**
45
- * Extract the output type from a tool (inferred from Zod schema)
45
+ * Extract the output type from a tool (inferred from Standard JSON Schema, or `unknown` for plain JSONSchema)
46
46
  */
47
47
  export type InferToolOutput<T> = T extends {
48
48
  outputSchema?: infer TOutput;
49
- } ? TOutput extends z.ZodType ? z.infer<TOutput> : any : any;
49
+ } ? TOutput extends StandardJSONSchemaV1<infer TInferred, unknown> ? TInferred : TOutput extends JSONSchema ? unknown : unknown : unknown;
50
50
  /**
51
51
  * Tool definition configuration
52
52
  */
53
- export interface ToolDefinitionConfig<TInput extends z.ZodType = z.ZodType, TOutput extends z.ZodType = z.ZodType, TName extends string = string> {
53
+ export interface ToolDefinitionConfig<TInput extends SchemaInput = SchemaInput, TOutput extends SchemaInput = SchemaInput, TName extends string = string> {
54
54
  name: TName;
55
55
  description: string;
56
56
  inputSchema?: TInput;
57
57
  outputSchema?: TOutput;
58
58
  needsApproval?: boolean;
59
- metadata?: Record<string, any>;
59
+ metadata?: Record<string, unknown>;
60
60
  }
61
61
  /**
62
62
  * Tool definition builder that allows creating server or client tools from a shared definition
63
63
  */
64
- export interface ToolDefinition<TInput extends z.ZodType = z.ZodType, TOutput extends z.ZodType = z.ZodType, TName extends string = string> extends ToolDefinitionInstance<TInput, TOutput, TName> {
64
+ export interface ToolDefinition<TInput extends SchemaInput = SchemaInput, TOutput extends SchemaInput = SchemaInput, TName extends string = string> extends ToolDefinitionInstance<TInput, TOutput, TName> {
65
65
  /**
66
66
  * Create a server-side tool with execute function
67
67
  */
68
- server: (execute: (args: z.infer<TInput>) => Promise<z.infer<TOutput>> | z.infer<TOutput>) => ServerTool<TInput, TOutput, TName>;
68
+ server: (execute: (args: InferSchemaType<TInput>) => Promise<InferSchemaType<TOutput>> | InferSchemaType<TOutput>) => ServerTool<TInput, TOutput, TName>;
69
69
  /**
70
70
  * Create a client-side tool with optional execute function
71
71
  */
72
- client: (execute?: (args: z.infer<TInput>) => Promise<z.infer<TOutput>> | z.infer<TOutput>) => ClientTool<TInput, TOutput, TName>;
72
+ client: (execute?: (args: InferSchemaType<TInput>) => Promise<InferSchemaType<TOutput>> | InferSchemaType<TOutput>) => ClientTool<TInput, TOutput, TName>;
73
73
  }
74
74
  /**
75
75
  * Create an isomorphic tool definition that can be used directly or instantiated for server/client
@@ -79,11 +79,15 @@ export interface ToolDefinition<TInput extends z.ZodType = z.ZodType, TOutput ex
79
79
  * 2. Instantiated as a server tool with .server()
80
80
  * 3. Instantiated as a client tool with .client()
81
81
  *
82
+ * Supports any Standard JSON Schema compliant library (Zod v4+, ArkType, Valibot, etc.)
83
+ * or plain JSON Schema objects.
84
+ *
82
85
  * @example
83
86
  * ```typescript
84
87
  * import { toolDefinition } from '@tanstack/ai';
85
88
  * import { z } from 'zod';
86
89
  *
90
+ * // Using Zod (natively supports Standard JSON Schema)
87
91
  * const addToCartTool = toolDefinition({
88
92
  * name: 'addToCart',
89
93
  * description: 'Add a guitar to the shopping cart (requires approval)',
@@ -122,4 +126,4 @@ export interface ToolDefinition<TInput extends z.ZodType = z.ZodType, TOutput ex
122
126
  * });
123
127
  * ```
124
128
  */
125
- export declare function toolDefinition<TInput extends z.ZodType = z.ZodAny, TOutput extends z.ZodType = z.ZodAny, TName extends string = string>(config: ToolDefinitionConfig<TInput, TOutput, TName>): ToolDefinition<TInput, TOutput, TName>;
129
+ export declare function toolDefinition<TInput extends SchemaInput = SchemaInput, TOutput extends SchemaInput = SchemaInput, TName extends string = string>(config: ToolDefinitionConfig<TInput, TOutput, TName>): ToolDefinition<TInput, TOutput, TName>;
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tool-definition.js","sources":["../../../../../src/activities/chat/tools/tool-definition.ts"],"sourcesContent":["import type { StandardJSONSchemaV1 } from '@standard-schema/spec'\nimport type {\n InferSchemaType,\n JSONSchema,\n SchemaInput,\n Tool,\n} from '../../../types'\n\n/**\n * Marker type for server-side tools\n */\nexport interface ServerTool<\n TInput extends SchemaInput = SchemaInput,\n TOutput extends SchemaInput = SchemaInput,\n TName extends string = string,\n> extends Tool<TInput, TOutput, TName> {\n __toolSide: 'server'\n}\n\n/**\n * Marker type for client-side tools\n */\nexport interface ClientTool<\n TInput extends SchemaInput = SchemaInput,\n TOutput extends SchemaInput = SchemaInput,\n TName extends string = string,\n> {\n __toolSide: 'client'\n name: TName\n description: string\n inputSchema?: TInput\n outputSchema?: TOutput\n needsApproval?: boolean\n metadata?: Record<string, unknown>\n execute?: (\n args: InferSchemaType<TInput>,\n ) => Promise<InferSchemaType<TOutput>> | InferSchemaType<TOutput>\n}\n\n/**\n * Tool definition that can be used directly or instantiated for server/client\n */\nexport interface ToolDefinitionInstance<\n TInput extends SchemaInput = SchemaInput,\n TOutput extends SchemaInput = SchemaInput,\n TName extends string = string,\n> extends Tool<TInput, TOutput, TName> {\n __toolSide: 'definition'\n}\n\n/**\n * Union type for any kind of client-side tool (client tool or definition)\n */\nexport type AnyClientTool =\n | ClientTool<SchemaInput, SchemaInput>\n | ToolDefinitionInstance<SchemaInput, SchemaInput>\n\n/**\n * Extract the tool name as a literal type\n */\nexport type InferToolName<T> = T extends { name: infer N } ? N : never\n\n/**\n * Extract the input type from a tool (inferred from Standard JSON Schema, or `unknown` for plain JSONSchema)\n */\nexport type InferToolInput<T> = T extends { inputSchema?: infer TInput }\n ? TInput extends StandardJSONSchemaV1<infer TInferred, unknown>\n ? TInferred\n : TInput extends JSONSchema\n ? unknown\n : unknown\n : unknown\n\n/**\n * Extract the output type from a tool (inferred from Standard JSON Schema, or `unknown` for plain JSONSchema)\n */\nexport type InferToolOutput<T> = T extends { outputSchema?: infer TOutput }\n ? TOutput extends StandardJSONSchemaV1<infer TInferred, unknown>\n ? TInferred\n : TOutput extends JSONSchema\n ? unknown\n : unknown\n : unknown\n\n/**\n * Tool definition configuration\n */\nexport interface ToolDefinitionConfig<\n TInput extends SchemaInput = SchemaInput,\n TOutput extends SchemaInput = SchemaInput,\n TName extends string = string,\n> {\n name: TName\n description: string\n inputSchema?: TInput\n outputSchema?: TOutput\n needsApproval?: boolean\n metadata?: Record<string, unknown>\n}\n\n/**\n * Tool definition builder that allows creating server or client tools from a shared definition\n */\nexport interface ToolDefinition<\n TInput extends SchemaInput = SchemaInput,\n TOutput extends SchemaInput = SchemaInput,\n TName extends string = string,\n> extends ToolDefinitionInstance<TInput, TOutput, TName> {\n /**\n * Create a server-side tool with execute function\n */\n server: (\n execute: (\n args: InferSchemaType<TInput>,\n ) => Promise<InferSchemaType<TOutput>> | InferSchemaType<TOutput>,\n ) => ServerTool<TInput, TOutput, TName>\n\n /**\n * Create a client-side tool with optional execute function\n */\n client: (\n execute?: (\n args: InferSchemaType<TInput>,\n ) => Promise<InferSchemaType<TOutput>> | InferSchemaType<TOutput>,\n ) => ClientTool<TInput, TOutput, TName>\n}\n\n/**\n * Create an isomorphic tool definition that can be used directly or instantiated for server/client\n *\n * The definition contains all tool metadata (name, description, schemas) and can be:\n * 1. Used directly in chat() on the server (as a tool definition without execute)\n * 2. Instantiated as a server tool with .server()\n * 3. Instantiated as a client tool with .client()\n *\n * Supports any Standard JSON Schema compliant library (Zod v4+, ArkType, Valibot, etc.)\n * or plain JSON Schema objects.\n *\n * @example\n * ```typescript\n * import { toolDefinition } from '@tanstack/ai';\n * import { z } from 'zod';\n *\n * // Using Zod (natively supports Standard JSON Schema)\n * const addToCartTool = toolDefinition({\n * name: 'addToCart',\n * description: 'Add a guitar to the shopping cart (requires approval)',\n * needsApproval: true,\n * inputSchema: z.object({\n * guitarId: z.string(),\n * quantity: z.number(),\n * }),\n * outputSchema: z.object({\n * success: z.boolean(),\n * cartId: z.string(),\n * totalItems: z.number(),\n * }),\n * });\n *\n * // Use directly in chat (server-side, no execute function)\n * chat({\n * tools: [addToCartTool],\n * // ...\n * });\n *\n * // Or create server-side implementation\n * const addToCartServer = addToCartTool.server(async (args) => {\n * // args is typed as { guitarId: string; quantity: number }\n * return {\n * success: true,\n * cartId: 'CART_' + Date.now(),\n * totalItems: args.quantity,\n * };\n * });\n *\n * // Or create client-side implementation\n * const addToCartClient = addToCartTool.client(async (args) => {\n * // Client-specific logic (e.g., localStorage)\n * return { success: true, cartId: 'local', totalItems: 1 };\n * });\n * ```\n */\nexport function toolDefinition<\n TInput extends SchemaInput = SchemaInput,\n TOutput extends SchemaInput = SchemaInput,\n TName extends string = string,\n>(\n config: ToolDefinitionConfig<TInput, TOutput, TName>,\n): ToolDefinition<TInput, TOutput, TName> {\n const definition: ToolDefinition<TInput, TOutput, TName> = {\n __toolSide: 'definition',\n ...config,\n server(\n execute: (\n args: InferSchemaType<TInput>,\n ) => Promise<InferSchemaType<TOutput>> | InferSchemaType<TOutput>,\n ): ServerTool<TInput, TOutput, TName> {\n return {\n __toolSide: 'server',\n ...config,\n execute,\n }\n },\n\n client(\n execute?: (\n args: InferSchemaType<TInput>,\n ) => Promise<InferSchemaType<TOutput>> | InferSchemaType<TOutput>,\n ): ClientTool<TInput, TOutput, TName> {\n return {\n __toolSide: 'client',\n ...config,\n execute,\n }\n },\n }\n\n return definition\n}\n"],"names":[],"mappings":"AAsLO,SAAS,eAKd,QACwC;AACxC,QAAM,aAAqD;AAAA,IACzD,YAAY;AAAA,IACZ,GAAG;AAAA,IACH,OACE,SAGoC;AACpC,aAAO;AAAA,QACL,YAAY;AAAA,QACZ,GAAG;AAAA,QACH;AAAA,MAAA;AAAA,IAEJ;AAAA,IAEA,OACE,SAGoC;AACpC,aAAO;AAAA,QACL,YAAY;AAAA,QACZ,GAAG;AAAA,QACH;AAAA,MAAA;AAAA,IAEJ;AAAA,EAAA;AAGF,SAAO;AACT;"}
@@ -0,0 +1,68 @@
1
+ import { ImageGenerationOptions, ImageGenerationResult } from '../../types.js';
2
+ /**
3
+ * Configuration for image adapter instances
4
+ */
5
+ export interface ImageAdapterConfig {
6
+ apiKey?: string;
7
+ baseUrl?: string;
8
+ timeout?: number;
9
+ maxRetries?: number;
10
+ headers?: Record<string, string>;
11
+ }
12
+ /**
13
+ * Image adapter interface with pre-resolved generics.
14
+ *
15
+ * An adapter is created by a provider function: `provider('model')` → `adapter`
16
+ * All type resolution happens at the provider call site, not in this interface.
17
+ *
18
+ * Generic parameters:
19
+ * - TModel: The specific model name (e.g., 'dall-e-3')
20
+ * - TProviderOptions: Base provider-specific options (already resolved)
21
+ * - TModelProviderOptionsByName: Map from model name to its specific provider options
22
+ * - TModelSizeByName: Map from model name to its supported sizes
23
+ */
24
+ export interface ImageAdapter<TModel extends string = string, TProviderOptions extends object = Record<string, unknown>, TModelProviderOptionsByName extends Record<string, any> = Record<string, any>, TModelSizeByName extends Record<string, string> = Record<string, string>> {
25
+ /** Discriminator for adapter kind - used by generate() to determine API shape */
26
+ readonly kind: 'image';
27
+ /** Adapter name identifier */
28
+ readonly name: string;
29
+ /** The model this adapter is configured for */
30
+ readonly model: TModel;
31
+ /**
32
+ * @internal Type-only properties for inference. Not assigned at runtime.
33
+ */
34
+ '~types': {
35
+ providerOptions: TProviderOptions;
36
+ modelProviderOptionsByName: TModelProviderOptionsByName;
37
+ modelSizeByName: TModelSizeByName;
38
+ };
39
+ /**
40
+ * Generate images from a prompt
41
+ */
42
+ generateImages: (options: ImageGenerationOptions<TProviderOptions>) => Promise<ImageGenerationResult>;
43
+ }
44
+ /**
45
+ * An ImageAdapter with any/unknown type parameters.
46
+ * Useful as a constraint in generic functions and interfaces.
47
+ */
48
+ export type AnyImageAdapter = ImageAdapter<any, any, any, any>;
49
+ /**
50
+ * Abstract base class for image generation adapters.
51
+ * Extend this class to implement an image adapter for a specific provider.
52
+ *
53
+ * Generic parameters match ImageAdapter - all pre-resolved by the provider function.
54
+ */
55
+ export declare abstract class BaseImageAdapter<TModel extends string = string, TProviderOptions extends object = Record<string, unknown>, TModelProviderOptionsByName extends Record<string, any> = Record<string, any>, TModelSizeByName extends Record<string, string> = Record<string, string>> implements ImageAdapter<TModel, TProviderOptions, TModelProviderOptionsByName, TModelSizeByName> {
56
+ readonly kind: "image";
57
+ abstract readonly name: string;
58
+ readonly model: TModel;
59
+ '~types': {
60
+ providerOptions: TProviderOptions;
61
+ modelProviderOptionsByName: TModelProviderOptionsByName;
62
+ modelSizeByName: TModelSizeByName;
63
+ };
64
+ protected config: ImageAdapterConfig;
65
+ constructor(config: ImageAdapterConfig | undefined, model: TModel);
66
+ abstract generateImages(options: ImageGenerationOptions<TProviderOptions>): Promise<ImageGenerationResult>;
67
+ protected generateId(): string;
68
+ }
@@ -0,0 +1,14 @@
1
+ class BaseImageAdapter {
2
+ constructor(config = {}, model) {
3
+ this.kind = "image";
4
+ this.config = config;
5
+ this.model = model;
6
+ }
7
+ generateId() {
8
+ return `${this.name}-${Date.now()}-${Math.random().toString(36).substring(7)}`;
9
+ }
10
+ }
11
+ export {
12
+ BaseImageAdapter
13
+ };
14
+ //# sourceMappingURL=adapter.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"adapter.js","sources":["../../../../src/activities/generateImage/adapter.ts"],"sourcesContent":["import type { ImageGenerationOptions, ImageGenerationResult } from '../../types'\n\n/**\n * Configuration for image adapter instances\n */\nexport interface ImageAdapterConfig {\n apiKey?: string\n baseUrl?: string\n timeout?: number\n maxRetries?: number\n headers?: Record<string, string>\n}\n\n/**\n * Image 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., 'dall-e-3')\n * - TProviderOptions: Base provider-specific options (already resolved)\n * - TModelProviderOptionsByName: Map from model name to its specific provider options\n * - TModelSizeByName: Map from model name to its supported sizes\n */\nexport interface ImageAdapter<\n TModel extends string = string,\n TProviderOptions extends object = Record<string, unknown>,\n TModelProviderOptionsByName extends Record<string, any> = Record<string, any>,\n TModelSizeByName extends Record<string, string> = Record<string, string>,\n> {\n /** Discriminator for adapter kind - used by generate() to determine API shape */\n readonly kind: 'image'\n /** Adapter name identifier */\n readonly name: string\n /** The model this adapter is configured for */\n readonly model: TModel\n\n /**\n * @internal Type-only properties for inference. Not assigned at runtime.\n */\n '~types': {\n providerOptions: TProviderOptions\n modelProviderOptionsByName: TModelProviderOptionsByName\n modelSizeByName: TModelSizeByName\n }\n\n /**\n * Generate images from a prompt\n */\n generateImages: (\n options: ImageGenerationOptions<TProviderOptions>,\n ) => Promise<ImageGenerationResult>\n}\n\n/**\n * An ImageAdapter with any/unknown type parameters.\n * Useful as a constraint in generic functions and interfaces.\n */\nexport type AnyImageAdapter = ImageAdapter<any, any, any, any>\n\n/**\n * Abstract base class for image generation adapters.\n * Extend this class to implement an image adapter for a specific provider.\n *\n * Generic parameters match ImageAdapter - all pre-resolved by the provider function.\n */\nexport abstract class BaseImageAdapter<\n TModel extends string = string,\n TProviderOptions extends object = Record<string, unknown>,\n TModelProviderOptionsByName extends Record<string, any> = Record<string, any>,\n TModelSizeByName extends Record<string, string> = Record<string, string>,\n> implements ImageAdapter<\n TModel,\n TProviderOptions,\n TModelProviderOptionsByName,\n TModelSizeByName\n> {\n readonly kind = 'image' as const\n abstract readonly name: string\n readonly model: TModel\n\n // Type-only property - never assigned at runtime\n declare '~types': {\n providerOptions: TProviderOptions\n modelProviderOptionsByName: TModelProviderOptionsByName\n modelSizeByName: TModelSizeByName\n }\n\n protected config: ImageAdapterConfig\n\n constructor(config: ImageAdapterConfig = {}, model: TModel) {\n this.config = config\n this.model = model\n }\n\n abstract generateImages(\n options: ImageGenerationOptions<TProviderOptions>,\n ): Promise<ImageGenerationResult>\n\n protected generateId(): string {\n return `${this.name}-${Date.now()}-${Math.random().toString(36).substring(7)}`\n }\n}\n"],"names":[],"mappings":"AAmEO,MAAe,iBAUpB;AAAA,EAcA,YAAY,SAA6B,CAAA,GAAI,OAAe;AAb5D,SAAS,OAAO;AAcd,SAAK,SAAS;AACd,SAAK,QAAQ;AAAA,EACf;AAAA,EAMU,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,89 @@
1
+ import { ImageAdapter } from './adapter.js';
2
+ import { ImageGenerationResult } from '../../types.js';
3
+ /** The adapter kind this activity handles */
4
+ export declare const kind: "image";
5
+ /**
6
+ * Extract model-specific provider options from an ImageAdapter via ~types.
7
+ * If the model has specific options defined in ModelProviderOptions (and not just via index signature),
8
+ * use those; otherwise fall back to base provider options.
9
+ */
10
+ export type ImageProviderOptionsForModel<TAdapter, TModel extends string> = TAdapter extends ImageAdapter<any, infer BaseOptions, infer ModelOptions, any> ? string extends keyof ModelOptions ? BaseOptions : TModel extends keyof ModelOptions ? ModelOptions[TModel] : BaseOptions : object;
11
+ /**
12
+ * Extract model-specific size options from an ImageAdapter via ~types.
13
+ * If the model has specific sizes defined, use those; otherwise fall back to string.
14
+ */
15
+ export type ImageSizeForModel<TAdapter, TModel extends string> = TAdapter extends ImageAdapter<any, any, any, infer SizeByName> ? string extends keyof SizeByName ? string : TModel extends keyof SizeByName ? SizeByName[TModel] : string : string;
16
+ /**
17
+ * Options for the image activity.
18
+ * The model is extracted from the adapter's model property.
19
+ *
20
+ * @template TAdapter - The image adapter type
21
+ */
22
+ export interface ImageActivityOptions<TAdapter extends ImageAdapter<string, object, any, any>> {
23
+ /** The image adapter to use (must be created with a model) */
24
+ adapter: TAdapter & {
25
+ kind: typeof kind;
26
+ };
27
+ /** Text description of the desired image(s) */
28
+ prompt: string;
29
+ /** Number of images to generate (default: 1) */
30
+ numberOfImages?: number;
31
+ /** Image size in WIDTHxHEIGHT format (e.g., "1024x1024") */
32
+ size?: ImageSizeForModel<TAdapter, TAdapter['model']>;
33
+ /** Provider-specific options for image generation */
34
+ modelOptions?: ImageProviderOptionsForModel<TAdapter, TAdapter['model']>;
35
+ }
36
+ /** Result type for the image activity */
37
+ export type ImageActivityResult = Promise<ImageGenerationResult>;
38
+ /**
39
+ * Image activity - generates images from text prompts.
40
+ *
41
+ * Uses AI image generation models to create images based on natural language descriptions.
42
+ *
43
+ * @example Generate a single image
44
+ * ```ts
45
+ * import { generateImage } from '@tanstack/ai'
46
+ * import { openaiImage } from '@tanstack/ai-openai'
47
+ *
48
+ * const result = await generateImage({
49
+ * adapter: openaiImage('dall-e-3'),
50
+ * prompt: 'A serene mountain landscape at sunset'
51
+ * })
52
+ *
53
+ * console.log(result.images[0].url)
54
+ * ```
55
+ *
56
+ * @example Generate multiple images
57
+ * ```ts
58
+ * const result = await generateImage({
59
+ * adapter: openaiImage('dall-e-2'),
60
+ * prompt: 'A cute robot mascot',
61
+ * numberOfImages: 4,
62
+ * size: '512x512'
63
+ * })
64
+ *
65
+ * result.images.forEach((image, i) => {
66
+ * console.log(`Image ${i + 1}: ${image.url}`)
67
+ * })
68
+ * ```
69
+ *
70
+ * @example With provider-specific options
71
+ * ```ts
72
+ * const result = await generateImage({
73
+ * adapter: openaiImage('dall-e-3'),
74
+ * prompt: 'A professional headshot photo',
75
+ * size: '1024x1024',
76
+ * modelOptions: {
77
+ * quality: 'hd',
78
+ * style: 'natural'
79
+ * }
80
+ * })
81
+ * ```
82
+ */
83
+ export declare function generateImage<TAdapter extends ImageAdapter<string, object, any, any>>(options: ImageActivityOptions<TAdapter>): ImageActivityResult;
84
+ /**
85
+ * Create typed options for the generateImage() function without executing.
86
+ */
87
+ export declare function createImageOptions<TAdapter extends ImageAdapter<string, object, any, any>>(options: ImageActivityOptions<TAdapter>): ImageActivityOptions<TAdapter>;
88
+ export type { ImageAdapter, ImageAdapterConfig, AnyImageAdapter, } from './adapter.js';
89
+ export { BaseImageAdapter } from './adapter.js';
@@ -0,0 +1,15 @@
1
+ const kind = "image";
2
+ async function generateImage(options) {
3
+ const { adapter, ...rest } = options;
4
+ const model = adapter.model;
5
+ return adapter.generateImages({ ...rest, model });
6
+ }
7
+ function createImageOptions(options) {
8
+ return options;
9
+ }
10
+ export {
11
+ createImageOptions,
12
+ generateImage,
13
+ kind
14
+ };
15
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sources":["../../../../src/activities/generateImage/index.ts"],"sourcesContent":["/**\n * Image Activity\n *\n * Generates images from text prompts.\n * This is a self-contained module with implementation, types, and JSDoc.\n */\n\nimport type { ImageAdapter } from './adapter'\nimport type { ImageGenerationResult } from '../../types'\n\n// ===========================\n// Activity Kind\n// ===========================\n\n/** The adapter kind this activity handles */\nexport const kind = 'image' as const\n\n// ===========================\n// Type Extraction Helpers\n// ===========================\n\n/**\n * Extract model-specific provider options from an ImageAdapter via ~types.\n * If the model has specific options defined in ModelProviderOptions (and not just via index signature),\n * use those; otherwise fall back to base provider options.\n */\nexport type ImageProviderOptionsForModel<TAdapter, TModel extends string> =\n TAdapter extends ImageAdapter<any, infer BaseOptions, infer ModelOptions, any>\n ? string extends keyof ModelOptions\n ? // ModelOptions is Record<string, unknown> or has index signature - use BaseOptions\n BaseOptions\n : // ModelOptions has explicit keys - check if TModel is one of them\n TModel extends keyof ModelOptions\n ? ModelOptions[TModel]\n : BaseOptions\n : object\n\n/**\n * Extract model-specific size options from an ImageAdapter via ~types.\n * If the model has specific sizes defined, use those; otherwise fall back to string.\n */\nexport type ImageSizeForModel<TAdapter, TModel extends string> =\n TAdapter extends ImageAdapter<any, any, any, infer SizeByName>\n ? string extends keyof SizeByName\n ? // SizeByName has index signature - fall back to string\n string\n : // SizeByName has explicit keys - check if TModel is one of them\n TModel extends keyof SizeByName\n ? SizeByName[TModel]\n : string\n : string\n\n// ===========================\n// Activity Options Type\n// ===========================\n\n/**\n * Options for the image activity.\n * The model is extracted from the adapter's model property.\n *\n * @template TAdapter - The image adapter type\n */\nexport interface ImageActivityOptions<\n TAdapter extends ImageAdapter<string, object, any, any>,\n> {\n /** The image adapter to use (must be created with a model) */\n adapter: TAdapter & { kind: typeof kind }\n /** Text description of the desired image(s) */\n prompt: string\n /** Number of images to generate (default: 1) */\n numberOfImages?: number\n /** Image size in WIDTHxHEIGHT format (e.g., \"1024x1024\") */\n size?: ImageSizeForModel<TAdapter, TAdapter['model']>\n /** Provider-specific options for image generation */\n modelOptions?: ImageProviderOptionsForModel<TAdapter, TAdapter['model']>\n}\n\n// ===========================\n// Activity Result Type\n// ===========================\n\n/** Result type for the image activity */\nexport type ImageActivityResult = Promise<ImageGenerationResult>\n\n// ===========================\n// Activity Implementation\n// ===========================\n\n/**\n * Image activity - generates images from text prompts.\n *\n * Uses AI image generation models to create images based on natural language descriptions.\n *\n * @example Generate a single image\n * ```ts\n * import { generateImage } from '@tanstack/ai'\n * import { openaiImage } from '@tanstack/ai-openai'\n *\n * const result = await generateImage({\n * adapter: openaiImage('dall-e-3'),\n * prompt: 'A serene mountain landscape at sunset'\n * })\n *\n * console.log(result.images[0].url)\n * ```\n *\n * @example Generate multiple images\n * ```ts\n * const result = await generateImage({\n * adapter: openaiImage('dall-e-2'),\n * prompt: 'A cute robot mascot',\n * numberOfImages: 4,\n * size: '512x512'\n * })\n *\n * result.images.forEach((image, i) => {\n * console.log(`Image ${i + 1}: ${image.url}`)\n * })\n * ```\n *\n * @example With provider-specific options\n * ```ts\n * const result = await generateImage({\n * adapter: openaiImage('dall-e-3'),\n * prompt: 'A professional headshot photo',\n * size: '1024x1024',\n * modelOptions: {\n * quality: 'hd',\n * style: 'natural'\n * }\n * })\n * ```\n */\nexport async function generateImage<\n TAdapter extends ImageAdapter<string, object, any, any>,\n>(options: ImageActivityOptions<TAdapter>): ImageActivityResult {\n const { adapter, ...rest } = options\n const model = adapter.model\n\n return adapter.generateImages({ ...rest, model })\n}\n\n// ===========================\n// Options Factory\n// ===========================\n\n/**\n * Create typed options for the generateImage() function without executing.\n */\nexport function createImageOptions<\n TAdapter extends ImageAdapter<string, object, any, any>,\n>(options: ImageActivityOptions<TAdapter>): ImageActivityOptions<TAdapter> {\n return options\n}\n\n// Re-export adapter types\nexport type {\n ImageAdapter,\n ImageAdapterConfig,\n AnyImageAdapter,\n} from './adapter'\nexport { BaseImageAdapter } from './adapter'\n"],"names":[],"mappings":"AAeO,MAAM,OAAO;AAsHpB,eAAsB,cAEpB,SAA8D;AAC9D,QAAM,EAAE,SAAS,GAAG,KAAA,IAAS;AAC7B,QAAM,QAAQ,QAAQ;AAEtB,SAAO,QAAQ,eAAe,EAAE,GAAG,MAAM,OAAO;AAClD;AASO,SAAS,mBAEd,SAAyE;AACzE,SAAO;AACT;"}
@@ -0,0 +1,62 @@
1
+ import { TTSOptions, TTSResult } from '../../types.js';
2
+ /**
3
+ * Configuration for TTS adapter instances
4
+ */
5
+ export interface TTSAdapterConfig {
6
+ apiKey?: string;
7
+ baseUrl?: string;
8
+ timeout?: number;
9
+ maxRetries?: number;
10
+ headers?: Record<string, string>;
11
+ }
12
+ /**
13
+ * TTS adapter interface with pre-resolved generics.
14
+ *
15
+ * An adapter is created by a provider function: `provider('model')` → `adapter`
16
+ * All type resolution happens at the provider call site, not in this interface.
17
+ *
18
+ * Generic parameters:
19
+ * - TModel: The specific model name (e.g., 'tts-1')
20
+ * - TProviderOptions: Provider-specific options (already resolved)
21
+ */
22
+ export interface TTSAdapter<TModel extends string = string, TProviderOptions extends object = Record<string, unknown>> {
23
+ /** Discriminator for adapter kind - used to determine API shape */
24
+ readonly kind: 'tts';
25
+ /** Adapter name identifier */
26
+ readonly name: string;
27
+ /** The model this adapter is configured for */
28
+ readonly model: TModel;
29
+ /**
30
+ * @internal Type-only properties for inference. Not assigned at runtime.
31
+ */
32
+ '~types': {
33
+ providerOptions: TProviderOptions;
34
+ };
35
+ /**
36
+ * Generate speech from text
37
+ */
38
+ generateSpeech: (options: TTSOptions<TProviderOptions>) => Promise<TTSResult>;
39
+ }
40
+ /**
41
+ * A TTSAdapter with any/unknown type parameters.
42
+ * Useful as a constraint in generic functions and interfaces.
43
+ */
44
+ export type AnyTTSAdapter = TTSAdapter<any, any>;
45
+ /**
46
+ * Abstract base class for text-to-speech adapters.
47
+ * Extend this class to implement a TTS adapter for a specific provider.
48
+ *
49
+ * Generic parameters match TTSAdapter - all pre-resolved by the provider function.
50
+ */
51
+ export declare abstract class BaseTTSAdapter<TModel extends string = string, TProviderOptions extends object = Record<string, unknown>> implements TTSAdapter<TModel, TProviderOptions> {
52
+ readonly kind: "tts";
53
+ abstract readonly name: string;
54
+ readonly model: TModel;
55
+ '~types': {
56
+ providerOptions: TProviderOptions;
57
+ };
58
+ protected config: TTSAdapterConfig;
59
+ constructor(config: TTSAdapterConfig | undefined, model: TModel);
60
+ abstract generateSpeech(options: TTSOptions<TProviderOptions>): Promise<TTSResult>;
61
+ protected generateId(): string;
62
+ }