ai-functions 2.1.1 → 2.3.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 (286) hide show
  1. package/.turbo/turbo-build.log +1 -4
  2. package/CHANGELOG.md +68 -1
  3. package/README.md +397 -157
  4. package/dist/ai-promise.d.ts +50 -3
  5. package/dist/ai-promise.d.ts.map +1 -1
  6. package/dist/ai-promise.js +410 -51
  7. package/dist/ai-promise.js.map +1 -1
  8. package/dist/ai-schemas.d.ts +56 -0
  9. package/dist/ai-schemas.d.ts.map +1 -0
  10. package/dist/ai-schemas.js +53 -0
  11. package/dist/ai-schemas.js.map +1 -0
  12. package/dist/ai.d.ts +16 -242
  13. package/dist/ai.d.ts.map +1 -1
  14. package/dist/ai.js +54 -837
  15. package/dist/ai.js.map +1 -1
  16. package/dist/batch/anthropic.d.ts +6 -4
  17. package/dist/batch/anthropic.d.ts.map +1 -1
  18. package/dist/batch/anthropic.js +83 -145
  19. package/dist/batch/anthropic.js.map +1 -1
  20. package/dist/batch/bedrock.d.ts +8 -30
  21. package/dist/batch/bedrock.d.ts.map +1 -1
  22. package/dist/batch/bedrock.js +155 -338
  23. package/dist/batch/bedrock.js.map +1 -1
  24. package/dist/batch/cloudflare.d.ts +8 -20
  25. package/dist/batch/cloudflare.d.ts.map +1 -1
  26. package/dist/batch/cloudflare.js +68 -189
  27. package/dist/batch/cloudflare.js.map +1 -1
  28. package/dist/batch/google.d.ts +6 -20
  29. package/dist/batch/google.d.ts.map +1 -1
  30. package/dist/batch/google.js +70 -238
  31. package/dist/batch/google.js.map +1 -1
  32. package/dist/batch/index.d.ts +4 -1
  33. package/dist/batch/index.d.ts.map +1 -1
  34. package/dist/batch/index.js +4 -1
  35. package/dist/batch/index.js.map +1 -1
  36. package/dist/batch/memory.d.ts +1 -1
  37. package/dist/batch/memory.d.ts.map +1 -1
  38. package/dist/batch/memory.js +14 -10
  39. package/dist/batch/memory.js.map +1 -1
  40. package/dist/batch/openai.d.ts +11 -14
  41. package/dist/batch/openai.d.ts.map +1 -1
  42. package/dist/batch/openai.js +52 -156
  43. package/dist/batch/openai.js.map +1 -1
  44. package/dist/batch/provider.d.ts +111 -0
  45. package/dist/batch/provider.d.ts.map +1 -0
  46. package/dist/batch/provider.js +233 -0
  47. package/dist/batch/provider.js.map +1 -0
  48. package/dist/batch-map.d.ts.map +1 -1
  49. package/dist/batch-map.js +23 -17
  50. package/dist/batch-map.js.map +1 -1
  51. package/dist/batch-queue.d.ts +65 -0
  52. package/dist/batch-queue.d.ts.map +1 -1
  53. package/dist/batch-queue.js +169 -14
  54. package/dist/batch-queue.js.map +1 -1
  55. package/dist/budget.d.ts +272 -0
  56. package/dist/budget.d.ts.map +1 -0
  57. package/dist/budget.js +513 -0
  58. package/dist/budget.js.map +1 -0
  59. package/dist/cache.d.ts +295 -0
  60. package/dist/cache.d.ts.map +1 -0
  61. package/dist/cache.js +433 -0
  62. package/dist/cache.js.map +1 -0
  63. package/dist/context.d.ts +42 -8
  64. package/dist/context.d.ts.map +1 -1
  65. package/dist/context.js +64 -62
  66. package/dist/context.js.map +1 -1
  67. package/dist/digital-objects-registry.d.ts +229 -0
  68. package/dist/digital-objects-registry.d.ts.map +1 -0
  69. package/dist/digital-objects-registry.js +617 -0
  70. package/dist/digital-objects-registry.js.map +1 -0
  71. package/dist/embeddings.d.ts +2 -2
  72. package/dist/embeddings.d.ts.map +1 -1
  73. package/dist/errors.d.ts +22 -0
  74. package/dist/errors.d.ts.map +1 -0
  75. package/dist/errors.js +35 -0
  76. package/dist/errors.js.map +1 -0
  77. package/dist/eval/runner.d.ts +10 -1
  78. package/dist/eval/runner.d.ts.map +1 -1
  79. package/dist/eval/runner.js +41 -35
  80. package/dist/eval/runner.js.map +1 -1
  81. package/dist/eval-log/in-memory.d.ts +34 -0
  82. package/dist/eval-log/in-memory.d.ts.map +1 -0
  83. package/dist/eval-log/in-memory.js +84 -0
  84. package/dist/eval-log/in-memory.js.map +1 -0
  85. package/dist/eval-log/index.d.ts +29 -0
  86. package/dist/eval-log/index.d.ts.map +1 -0
  87. package/dist/eval-log/index.js +39 -0
  88. package/dist/eval-log/index.js.map +1 -0
  89. package/dist/eval-log/types.d.ts +101 -0
  90. package/dist/eval-log/types.d.ts.map +1 -0
  91. package/dist/eval-log/types.js +16 -0
  92. package/dist/eval-log/types.js.map +1 -0
  93. package/dist/function-registry.d.ts +116 -0
  94. package/dist/function-registry.d.ts.map +1 -0
  95. package/dist/function-registry.js +546 -0
  96. package/dist/function-registry.js.map +1 -0
  97. package/dist/generate.d.ts +9 -3
  98. package/dist/generate.d.ts.map +1 -1
  99. package/dist/generate.js +18 -22
  100. package/dist/generate.js.map +1 -1
  101. package/dist/index.d.ts +35 -20
  102. package/dist/index.d.ts.map +1 -1
  103. package/dist/index.js +89 -42
  104. package/dist/index.js.map +1 -1
  105. package/dist/logger.d.ts +118 -0
  106. package/dist/logger.d.ts.map +1 -0
  107. package/dist/logger.js +187 -0
  108. package/dist/logger.js.map +1 -0
  109. package/dist/middleware/budget.d.ts +84 -0
  110. package/dist/middleware/budget.d.ts.map +1 -0
  111. package/dist/middleware/budget.js +110 -0
  112. package/dist/middleware/budget.js.map +1 -0
  113. package/dist/middleware/cache.d.ts +103 -0
  114. package/dist/middleware/cache.d.ts.map +1 -0
  115. package/dist/middleware/cache.js +228 -0
  116. package/dist/middleware/cache.js.map +1 -0
  117. package/dist/middleware/embed-cache.d.ts +99 -0
  118. package/dist/middleware/embed-cache.d.ts.map +1 -0
  119. package/dist/middleware/embed-cache.js +128 -0
  120. package/dist/middleware/embed-cache.js.map +1 -0
  121. package/dist/middleware/index.d.ts +11 -0
  122. package/dist/middleware/index.d.ts.map +1 -0
  123. package/dist/middleware/index.js +11 -0
  124. package/dist/middleware/index.js.map +1 -0
  125. package/dist/middleware/trace.d.ts +103 -0
  126. package/dist/middleware/trace.d.ts.map +1 -0
  127. package/dist/middleware/trace.js +176 -0
  128. package/dist/middleware/trace.js.map +1 -0
  129. package/dist/primitives.d.ts +120 -1
  130. package/dist/primitives.d.ts.map +1 -1
  131. package/dist/primitives.js +398 -26
  132. package/dist/primitives.js.map +1 -1
  133. package/dist/retry.d.ts +368 -0
  134. package/dist/retry.d.ts.map +1 -0
  135. package/dist/retry.js +646 -0
  136. package/dist/retry.js.map +1 -0
  137. package/dist/schema.d.ts.map +1 -1
  138. package/dist/schema.js +2 -10
  139. package/dist/schema.js.map +1 -1
  140. package/dist/telemetry.d.ts +128 -0
  141. package/dist/telemetry.d.ts.map +1 -0
  142. package/dist/telemetry.js +285 -0
  143. package/dist/telemetry.js.map +1 -0
  144. package/dist/template.d.ts.map +1 -1
  145. package/dist/template.js +6 -1
  146. package/dist/template.js.map +1 -1
  147. package/dist/tool-orchestration.d.ts +453 -0
  148. package/dist/tool-orchestration.d.ts.map +1 -0
  149. package/dist/tool-orchestration.js +763 -0
  150. package/dist/tool-orchestration.js.map +1 -0
  151. package/dist/type-guards.d.ts +28 -0
  152. package/dist/type-guards.d.ts.map +1 -0
  153. package/dist/type-guards.js +29 -0
  154. package/dist/type-guards.js.map +1 -0
  155. package/dist/types.d.ts +135 -17
  156. package/dist/types.d.ts.map +1 -1
  157. package/dist/types.js +36 -1
  158. package/dist/types.js.map +1 -1
  159. package/dist/wrap-for-v3.d.ts +80 -0
  160. package/dist/wrap-for-v3.d.ts.map +1 -0
  161. package/dist/wrap-for-v3.js +89 -0
  162. package/dist/wrap-for-v3.js.map +1 -0
  163. package/examples/00-quickstart.ts +232 -0
  164. package/examples/01-rag-chatbot.ts +212 -0
  165. package/examples/02-multi-agent-research.ts +290 -0
  166. package/examples/03-email-classification.ts +379 -0
  167. package/examples/04-content-moderation.ts +400 -0
  168. package/examples/05-document-extraction.ts +455 -0
  169. package/examples/06-streaming-chat-nextjs.ts +437 -0
  170. package/examples/07-cloudflare-worker.ts +483 -0
  171. package/examples/08-batch-processing.ts +491 -0
  172. package/examples/09-budget-constrained.ts +527 -0
  173. package/examples/10-tool-orchestration.ts +565 -0
  174. package/examples/11-retry-resilience.ts +403 -0
  175. package/examples/12-caching-strategies.ts +422 -0
  176. package/examples/README.md +145 -0
  177. package/package.json +10 -6
  178. package/src/ai-promise.ts +528 -99
  179. package/src/ai-schemas.ts +122 -0
  180. package/src/ai.ts +69 -1153
  181. package/src/batch/anthropic.ts +96 -161
  182. package/src/batch/bedrock.ts +203 -454
  183. package/src/batch/cloudflare.ts +99 -282
  184. package/src/batch/google.ts +91 -297
  185. package/src/batch/index.ts +4 -1
  186. package/src/batch/memory.ts +15 -10
  187. package/src/batch/openai.ts +65 -193
  188. package/src/batch/provider.ts +336 -0
  189. package/src/batch-map.ts +29 -24
  190. package/src/batch-queue.ts +200 -11
  191. package/src/budget.ts +740 -0
  192. package/src/cache.ts +681 -0
  193. package/src/context.ts +122 -76
  194. package/src/digital-objects-registry.ts +750 -0
  195. package/src/errors.ts +37 -0
  196. package/src/eval/runner.ts +63 -38
  197. package/src/eval-log/in-memory.ts +90 -0
  198. package/src/eval-log/index.ts +46 -0
  199. package/src/eval-log/types.ts +110 -0
  200. package/src/function-registry.ts +671 -0
  201. package/src/generate.ts +33 -33
  202. package/src/index.ts +325 -49
  203. package/src/logger.ts +232 -0
  204. package/src/middleware/budget.ts +171 -0
  205. package/src/middleware/cache.ts +299 -0
  206. package/src/middleware/embed-cache.ts +195 -0
  207. package/src/middleware/index.ts +23 -0
  208. package/src/middleware/trace.ts +248 -0
  209. package/src/primitives.ts +589 -62
  210. package/src/retry.ts +902 -0
  211. package/src/schema.ts +8 -17
  212. package/src/telemetry.ts +403 -0
  213. package/src/template.ts +8 -4
  214. package/src/tool-orchestration.ts +1173 -0
  215. package/src/type-guards.ts +31 -0
  216. package/src/types.ts +164 -25
  217. package/src/wrap-for-v3.ts +105 -0
  218. package/test/ai-promise.test.ts +1080 -0
  219. package/test/ai-proxy.test.ts +1 -1
  220. package/test/backward-compat.test.ts +147 -0
  221. package/test/batch-autosubmit-errors.test.ts +610 -0
  222. package/test/batch-blog-posts.test.ts +87 -129
  223. package/test/budget-tracking.test.ts +800 -0
  224. package/test/cache.test.ts +712 -0
  225. package/test/context-isolation.test.ts +687 -0
  226. package/test/core-functions.test.ts +183 -579
  227. package/test/decide.test.ts +154 -322
  228. package/test/define.test.ts +211 -8
  229. package/test/digital-objects-registry.test.ts +760 -0
  230. package/test/embedding-cache-middleware.test.ts +140 -0
  231. package/test/evals/deterministic.eval.test.ts +376 -0
  232. package/test/generate-core.test.ts +140 -229
  233. package/test/implicit-batch.test.ts +22 -65
  234. package/test/json-parse-error-handling.test.ts +463 -0
  235. package/test/retry-policy-integration.test.ts +117 -0
  236. package/test/retry.test.ts +1016 -0
  237. package/test/schema.test.ts +55 -19
  238. package/test/streaming.test.ts +316 -0
  239. package/test/template.test.ts +1164 -0
  240. package/test/tool-orchestration.test.ts +1040 -0
  241. package/test/wrap-for-v3.test.ts +612 -0
  242. package/vitest.config.js +6 -0
  243. package/vitest.config.ts +20 -0
  244. package/dist/rpc/auth.d.ts +0 -69
  245. package/dist/rpc/auth.d.ts.map +0 -1
  246. package/dist/rpc/auth.js +0 -136
  247. package/dist/rpc/auth.js.map +0 -1
  248. package/dist/rpc/client.d.ts +0 -62
  249. package/dist/rpc/client.d.ts.map +0 -1
  250. package/dist/rpc/client.js +0 -103
  251. package/dist/rpc/client.js.map +0 -1
  252. package/dist/rpc/deferred.d.ts +0 -60
  253. package/dist/rpc/deferred.d.ts.map +0 -1
  254. package/dist/rpc/deferred.js +0 -96
  255. package/dist/rpc/deferred.js.map +0 -1
  256. package/dist/rpc/index.d.ts +0 -22
  257. package/dist/rpc/index.d.ts.map +0 -1
  258. package/dist/rpc/index.js +0 -38
  259. package/dist/rpc/index.js.map +0 -1
  260. package/dist/rpc/local.d.ts +0 -42
  261. package/dist/rpc/local.d.ts.map +0 -1
  262. package/dist/rpc/local.js +0 -50
  263. package/dist/rpc/local.js.map +0 -1
  264. package/dist/rpc/server.d.ts +0 -165
  265. package/dist/rpc/server.d.ts.map +0 -1
  266. package/dist/rpc/server.js +0 -405
  267. package/dist/rpc/server.js.map +0 -1
  268. package/dist/rpc/session.d.ts +0 -32
  269. package/dist/rpc/session.d.ts.map +0 -1
  270. package/dist/rpc/session.js +0 -43
  271. package/dist/rpc/session.js.map +0 -1
  272. package/dist/rpc/transport.d.ts +0 -306
  273. package/dist/rpc/transport.d.ts.map +0 -1
  274. package/dist/rpc/transport.js +0 -731
  275. package/dist/rpc/transport.js.map +0 -1
  276. package/src/batch/anthropic.js +0 -256
  277. package/src/batch/bedrock.js +0 -584
  278. package/src/batch/cloudflare.js +0 -287
  279. package/src/batch/google.js +0 -359
  280. package/src/batch/index.js +0 -30
  281. package/src/batch/memory.js +0 -187
  282. package/src/batch/openai.js +0 -402
  283. package/src/eval/index.js +0 -7
  284. package/src/eval/models.js +0 -119
  285. package/src/eval/runner.js +0 -147
  286. package/test/schema.test.js +0 -96
@@ -0,0 +1,116 @@
1
+ /**
2
+ * Function Registry - Storage and management of defined AI functions
3
+ *
4
+ * This module provides the registry for storing and retrieving defined functions,
5
+ * including the global registry and factory for creating isolated registries.
6
+ */
7
+ import type { JSONSchema, FunctionDefinition, DefinedFunction, CodeGenerationDefinition, FunctionRegistry } from './types.js';
8
+ /**
9
+ * Convert args schema to JSON Schema
10
+ */
11
+ export declare function convertArgsToJSONSchema(args: unknown): JSONSchema;
12
+ /**
13
+ * Fill template with values
14
+ */
15
+ export declare function fillTemplate(template: string, args: Record<string, unknown>): string;
16
+ /**
17
+ * Author code with a model — the explicit, opt-in code-*generation* path.
18
+ *
19
+ * This is the behavior `type: 'code'` used to have implicitly at call time.
20
+ * It has been split out so that `Code` functions can be deterministic. Calling
21
+ * this **does** consult a model and returns the generated source as a string;
22
+ * it does not produce a deterministic, repeatable handler.
23
+ *
24
+ * @param definition - The code-authoring spec ({@link CodeGenerationDefinition})
25
+ * @param args - Concrete inputs / refinements for the requested code
26
+ * @returns The generated source code as a string
27
+ *
28
+ * @example
29
+ * ```ts
30
+ * import { generateCode } from 'ai-functions'
31
+ *
32
+ * const src = await generateCode(
33
+ * { name: 'calculateTax', args: { amount: '(number)', rate: '(number)' }, language: 'typescript' },
34
+ * { amount: 100, rate: 0.2 }
35
+ * )
36
+ * ```
37
+ */
38
+ export declare function generateCode<TInput>(definition: CodeGenerationDefinition<TInput>, args?: TInput): Promise<string>;
39
+ /**
40
+ * Create a defined function from a function definition
41
+ */
42
+ export declare function createDefinedFunction<TOutput, TInput>(definition: FunctionDefinition<TOutput, TInput>): DefinedFunction<TOutput, TInput>;
43
+ /**
44
+ * Standalone function for defining AI functions
45
+ *
46
+ * @example
47
+ * ```ts
48
+ * import { defineFunction } from 'ai-functions'
49
+ *
50
+ * const summarize = defineFunction({
51
+ * type: 'generative',
52
+ * name: 'summarize',
53
+ * args: { text: 'Text to summarize' },
54
+ * output: 'string',
55
+ * promptTemplate: 'Summarize: {{text}}',
56
+ * })
57
+ *
58
+ * const result = await summarize.call({ text: 'Long article...' })
59
+ * ```
60
+ */
61
+ export declare function defineFunction<TOutput, TInput>(definition: FunctionDefinition<TOutput, TInput>): DefinedFunction<TOutput, TInput>;
62
+ /**
63
+ * Factory function to create a new isolated function registry instance.
64
+ *
65
+ * Use this when you need:
66
+ * - Test isolation: Each test can have its own registry
67
+ * - Scoped registries: Different parts of an app can have separate registries
68
+ * - Custom lifecycle management: Control when registries are created/destroyed
69
+ *
70
+ * @example
71
+ * ```ts
72
+ * // Create isolated registry for tests
73
+ * const registry = createFunctionRegistry()
74
+ * const fn = defineFunction({ ... })
75
+ * registry.set('myFunc', fn)
76
+ *
77
+ * // Later, registry can be discarded without affecting global state
78
+ * ```
79
+ *
80
+ * @returns A new FunctionRegistry instance
81
+ */
82
+ export declare function createFunctionRegistry(): FunctionRegistry;
83
+ /**
84
+ * Global function registry
85
+ *
86
+ * Note: This is in-memory only. For persistence, use mdxai or mdxdb packages.
87
+ *
88
+ * **Lifecycle:**
89
+ * - Created once at module load time
90
+ * - Shared across the entire application
91
+ * - Use `resetGlobalRegistry()` in tests to clear state between test runs
92
+ * - For isolated registries, use `createFunctionRegistry()` instead
93
+ */
94
+ export declare const functions: FunctionRegistry;
95
+ /**
96
+ * Reset the global function registry to a clean state.
97
+ *
98
+ * **Important:** This is primarily intended for test cleanup to ensure
99
+ * test isolation. In production code, prefer using `createFunctionRegistry()`
100
+ * for isolated registries.
101
+ *
102
+ * @example
103
+ * ```ts
104
+ * // In test setup/teardown
105
+ * beforeEach(() => {
106
+ * resetGlobalRegistry()
107
+ * })
108
+ *
109
+ * // Or after each test
110
+ * afterEach(() => {
111
+ * resetGlobalRegistry()
112
+ * })
113
+ * ```
114
+ */
115
+ export declare function resetGlobalRegistry(): void;
116
+ //# sourceMappingURL=function-registry.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"function-registry.d.ts","sourceRoot":"","sources":["../src/function-registry.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAIH,OAAO,KAAK,EAEV,UAAU,EACV,kBAAkB,EAClB,eAAe,EAEf,wBAAwB,EAKxB,gBAAgB,EACjB,MAAM,YAAY,CAAA;AASnB;;GAEG;AACH,wBAAgB,uBAAuB,CAAC,IAAI,EAAE,OAAO,GAAG,UAAU,CAuBjE;AAuDD;;GAEG;AACH,wBAAgB,YAAY,CAAC,QAAQ,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,MAAM,CAEpF;AAqFD;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,wBAAsB,YAAY,CAAC,MAAM,EACvC,UAAU,EAAE,wBAAwB,CAAC,MAAM,CAAC,EAC5C,IAAI,CAAC,EAAE,MAAM,GACZ,OAAO,CAAC,MAAM,CAAC,CA6BjB;AAwQD;;GAEG;AACH,wBAAgB,qBAAqB,CAAC,OAAO,EAAE,MAAM,EACnD,UAAU,EAAE,kBAAkB,CAAC,OAAO,EAAE,MAAM,CAAC,GAC9C,eAAe,CAAC,OAAO,EAAE,MAAM,CAAC,CA0BlC;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,cAAc,CAAC,OAAO,EAAE,MAAM,EAC5C,UAAU,EAAE,kBAAkB,CAAC,OAAO,EAAE,MAAM,CAAC,GAC9C,eAAe,CAAC,OAAO,EAAE,MAAM,CAAC,CAElC;AAqCD;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAgB,sBAAsB,IAAI,gBAAgB,CAEzD;AAED;;;;;;;;;;GAUG;AACH,eAAO,MAAM,SAAS,EAAE,gBAAiD,CAAA;AAEzE;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAgB,mBAAmB,IAAI,IAAI,CAE1C"}
@@ -0,0 +1,546 @@
1
+ /**
2
+ * Function Registry - Storage and management of defined AI functions
3
+ *
4
+ * This module provides the registry for storing and retrieving defined functions,
5
+ * including the global registry and factory for creating isolated registries.
6
+ */
7
+ import { generateObject } from './generate.js';
8
+ import { PENDING_HUMAN_RESULT_SYMBOL } from './types.js';
9
+ import { schema as convertSchema } from './schema.js';
10
+ import { getLogger } from './logger.js';
11
+ // ============================================================================
12
+ // JSON Schema Conversion
13
+ // ============================================================================
14
+ /**
15
+ * Convert args schema to JSON Schema
16
+ */
17
+ export function convertArgsToJSONSchema(args) {
18
+ // If it's already a JSON schema-like object
19
+ if (typeof args === 'object' && args !== null && 'type' in args) {
20
+ return args;
21
+ }
22
+ // Convert SimpleSchema to JSON Schema
23
+ const properties = {};
24
+ const required = [];
25
+ if (typeof args === 'object' && args !== null) {
26
+ for (const [key, value] of Object.entries(args)) {
27
+ required.push(key); // All properties required for cross-provider compatibility
28
+ properties[key] = convertValueToJSONSchema(value);
29
+ }
30
+ }
31
+ return {
32
+ type: 'object',
33
+ properties,
34
+ required,
35
+ additionalProperties: false, // Required for OpenAI compatibility
36
+ };
37
+ }
38
+ /**
39
+ * Convert a single value to JSON Schema
40
+ */
41
+ function convertValueToJSONSchema(value) {
42
+ if (typeof value === 'string') {
43
+ // Check for type hints: 'description (number)', 'description (boolean)', etc.
44
+ const typeMatch = value.match(/^(.+?)\s*\((number|boolean|integer|date)\)$/i);
45
+ if (typeMatch) {
46
+ const description = typeMatch[1];
47
+ const type = typeMatch[2];
48
+ switch (type.toLowerCase()) {
49
+ case 'number':
50
+ return { type: 'number', description: description.trim() };
51
+ case 'integer':
52
+ return { type: 'integer', description: description.trim() };
53
+ case 'boolean':
54
+ return { type: 'boolean', description: description.trim() };
55
+ case 'date':
56
+ return { type: 'string', format: 'date-time', description: description.trim() };
57
+ }
58
+ }
59
+ // Check for enum: 'option1 | option2 | option3'
60
+ if (value.includes(' | ')) {
61
+ const options = value.split(' | ').map((s) => s.trim());
62
+ return { type: 'string', enum: options };
63
+ }
64
+ return { type: 'string', description: value };
65
+ }
66
+ if (Array.isArray(value) && value.length === 1) {
67
+ const [desc] = value;
68
+ if (typeof desc === 'string') {
69
+ return { type: 'array', items: { type: 'string' }, description: desc };
70
+ }
71
+ if (typeof desc === 'number') {
72
+ return { type: 'array', items: { type: 'number' } };
73
+ }
74
+ return { type: 'array', items: convertValueToJSONSchema(desc) };
75
+ }
76
+ if (typeof value === 'object' && value !== null) {
77
+ return convertArgsToJSONSchema(value);
78
+ }
79
+ return { type: 'string' };
80
+ }
81
+ // ============================================================================
82
+ // Template Utilities
83
+ // ============================================================================
84
+ /**
85
+ * Fill template with values
86
+ */
87
+ export function fillTemplate(template, args) {
88
+ return template.replace(/\{\{(\w+)\}\}/g, (_, key) => String(args[key] ?? ''));
89
+ }
90
+ // ============================================================================
91
+ // Function Executors
92
+ // ============================================================================
93
+ /**
94
+ * Execute a **deterministic** code function.
95
+ *
96
+ * `Code` is the deterministic kind: no model is consulted at call time. This
97
+ * invokes the definition's `handler` (canonical) or, if only an inline `code`
98
+ * body was supplied, deterministically compiles and runs it. The result is
99
+ * returned directly.
100
+ *
101
+ * This is a deliberate change from the previous behavior, where `type: 'code'`
102
+ * LLM-generated source at call time. That code-*authoring* behavior now lives
103
+ * in {@link generateCode} (and the `generate('code', …)` primitive), so that
104
+ * `Code` can carry the "deterministic handler" contract consumers depend on
105
+ * (ADR-0033). See the package README migration note.
106
+ *
107
+ * @throws if neither `handler` nor `code` is provided, or if an inline `code`
108
+ * body is in a non-evaluable language.
109
+ */
110
+ async function executeCodeFunction(definition, args) {
111
+ const { handler, code, language = 'typescript', name } = definition;
112
+ if (typeof handler === 'function') {
113
+ return await handler(args);
114
+ }
115
+ if (typeof code === 'string' && code.length > 0) {
116
+ return await runInlineCode(code, args, language, name);
117
+ }
118
+ throw new Error(`Code function '${name}' has no handler or inline code. ` +
119
+ `'code' functions are deterministic and require a handler: (input) => output ` +
120
+ `(or an inline 'code' body). To have a model *author* code instead, use ` +
121
+ `generateCode() or define a 'generative' function.`);
122
+ }
123
+ /**
124
+ * Deterministically compile and run an inline `code` body for a Code function.
125
+ *
126
+ * The body is treated as a function whose single parameter is the parsed
127
+ * `args` object and whose `return` value is the result. Only the
128
+ * JS/TS-compatible languages can be evaluated in-process; other languages are
129
+ * carried as metadata for an external runtime and are rejected here.
130
+ *
131
+ * No model is involved — this is a pure `new Function(...)` compile of the
132
+ * supplied source, so the same body always produces the same behavior.
133
+ */
134
+ async function runInlineCode(code, args, language, name) {
135
+ if (language !== 'typescript' && language !== 'javascript') {
136
+ throw new Error(`Code function '${name}' has an inline 'code' body in language '${language}', ` +
137
+ `which cannot be evaluated in-process. Pass a 'handler' instead, or run it ` +
138
+ `in an external deterministic runtime.`);
139
+ }
140
+ const body = /\breturn\b/.test(code) ? code : `return (${code})`;
141
+ let fn;
142
+ try {
143
+ // eslint-disable-next-line @typescript-eslint/no-implied-eval
144
+ fn = new Function('args', `"use strict";\n${body}`);
145
+ }
146
+ catch (e) {
147
+ throw new Error(`Code function '${name}' has an invalid inline 'code' body: ${e.message}`);
148
+ }
149
+ return await fn(args);
150
+ }
151
+ /**
152
+ * Author code with a model — the explicit, opt-in code-*generation* path.
153
+ *
154
+ * This is the behavior `type: 'code'` used to have implicitly at call time.
155
+ * It has been split out so that `Code` functions can be deterministic. Calling
156
+ * this **does** consult a model and returns the generated source as a string;
157
+ * it does not produce a deterministic, repeatable handler.
158
+ *
159
+ * @param definition - The code-authoring spec ({@link CodeGenerationDefinition})
160
+ * @param args - Concrete inputs / refinements for the requested code
161
+ * @returns The generated source code as a string
162
+ *
163
+ * @example
164
+ * ```ts
165
+ * import { generateCode } from 'ai-functions'
166
+ *
167
+ * const src = await generateCode(
168
+ * { name: 'calculateTax', args: { amount: '(number)', rate: '(number)' }, language: 'typescript' },
169
+ * { amount: 100, rate: 0.2 }
170
+ * )
171
+ * ```
172
+ */
173
+ export async function generateCode(definition, args) {
174
+ const { name, description, language = 'typescript', instructions, returnType, model = 'sonnet' } = definition;
175
+ const argsDescription = JSON.stringify(args ?? definition.args, null, 2);
176
+ const result = await generateObject({
177
+ model,
178
+ schema: {
179
+ code: `The complete ${language} implementation code. Output ONLY the raw code without markdown formatting or code blocks.`,
180
+ },
181
+ system: `You are an expert ${language} developer. Generate clean, well-documented, production-ready code. Output ONLY the code itself, without any markdown code fences or language tags.`,
182
+ prompt: `Generate a ${language} function/query with the following specification:
183
+
184
+ Name: ${name}
185
+ Description: ${description || 'No description provided'}
186
+ Arguments: ${argsDescription}
187
+ Return Type: ${JSON.stringify(returnType)}
188
+
189
+ ${instructions ? `Additional Instructions: ${instructions}` : ''}
190
+
191
+ Requirements:
192
+ - Include appropriate comments/documentation
193
+ - Follow best practices for ${language}
194
+ - Handle edge cases appropriately
195
+ - Return ONLY the code without markdown formatting`,
196
+ });
197
+ return result.object.code;
198
+ }
199
+ /**
200
+ * Execute a generative function - uses AI to generate content
201
+ */
202
+ async function executeGenerativeFunction(definition, args) {
203
+ const { output, system, promptTemplate, model = 'sonnet', temperature, returnType } = definition;
204
+ const prompt = promptTemplate
205
+ ? fillTemplate(promptTemplate, args)
206
+ : JSON.stringify(args);
207
+ switch (output) {
208
+ case 'string': {
209
+ const result = await generateObject({
210
+ model,
211
+ schema: { text: 'The generated text response' },
212
+ prompt,
213
+ ...(system !== undefined && { system }),
214
+ ...(temperature !== undefined && { temperature }),
215
+ });
216
+ return result.object.text;
217
+ }
218
+ case 'object': {
219
+ const objectSchema = returnType || { result: 'The generated result' };
220
+ const result = await generateObject({
221
+ model,
222
+ schema: objectSchema,
223
+ prompt,
224
+ ...(system !== undefined && { system }),
225
+ ...(temperature !== undefined && { temperature }),
226
+ });
227
+ return result.object;
228
+ }
229
+ case 'image':
230
+ throw new Error('Image generation via generative functions is not yet implemented. ' +
231
+ 'Use the image() primitive directly instead.');
232
+ case 'video':
233
+ throw new Error('Video generation via generative functions is not yet implemented. ' +
234
+ 'Use the video() primitive directly instead.');
235
+ default:
236
+ throw new Error(`Unknown output type: ${output}`);
237
+ }
238
+ }
239
+ /**
240
+ * Execute an agentic function - runs in a loop with tools
241
+ */
242
+ async function executeAgenticFunction(definition, args) {
243
+ const { instructions, promptTemplate, tools = [], maxIterations = 10, model = 'sonnet', returnType, } = definition;
244
+ const prompt = promptTemplate
245
+ ? fillTemplate(promptTemplate, args)
246
+ : JSON.stringify(args);
247
+ // Build system prompt with tool descriptions
248
+ const toolDescriptions = tools.map((t) => `- ${t.name}: ${t.description}`).join('\n');
249
+ const systemPrompt = `${instructions}
250
+
251
+ Available tools:
252
+ ${toolDescriptions || 'No tools available'}
253
+
254
+ Work step by step to accomplish the task. When you have completed the task, provide your final result.`;
255
+ let iteration = 0;
256
+ const toolResults = [];
257
+ // Simple agent loop
258
+ while (iteration < maxIterations) {
259
+ iteration++;
260
+ const result = await generateObject({
261
+ model,
262
+ schema: {
263
+ thinking: 'Your step-by-step reasoning',
264
+ toolCall: {
265
+ name: 'Tool to call (or "done" if finished)',
266
+ arguments: 'Arguments for the tool as JSON string',
267
+ },
268
+ finalResult: returnType || 'The final result if done',
269
+ },
270
+ system: systemPrompt,
271
+ prompt: `Task: ${prompt}
272
+
273
+ Previous tool results:
274
+ ${toolResults.map((r, i) => `Step ${i + 1}: ${JSON.stringify(r)}`).join('\n') || 'None yet'}
275
+
276
+ What is your next step?`,
277
+ });
278
+ const response = result.object;
279
+ if (response.toolCall.name === 'done' || response.finalResult) {
280
+ return response.finalResult;
281
+ }
282
+ // Execute tool call
283
+ const tool = tools.find((t) => t.name === response.toolCall.name);
284
+ if (tool) {
285
+ let toolArgs;
286
+ try {
287
+ toolArgs = JSON.parse(response.toolCall.arguments || '{}');
288
+ }
289
+ catch (e) {
290
+ toolResults.push({
291
+ error: `Invalid tool arguments: ${e.message}`,
292
+ });
293
+ continue;
294
+ }
295
+ const toolResult = await tool.handler(toolArgs);
296
+ toolResults.push({ tool: response.toolCall.name, result: toolResult });
297
+ }
298
+ else {
299
+ toolResults.push({ error: `Tool not found: ${response.toolCall.name}` });
300
+ }
301
+ }
302
+ throw new Error(`Agent exceeded maximum iterations (${maxIterations})`);
303
+ }
304
+ /**
305
+ * Execute a human function - generates UI and waits for human input
306
+ *
307
+ * **Note: This function currently returns a pending placeholder.**
308
+ *
309
+ * In a complete implementation, this function would:
310
+ * 1. Generate channel-specific UI (Slack blocks, email templates, web forms, etc.)
311
+ * 2. Send the generated UI to the appropriate channel
312
+ * 3. Wait for human response with optional timeout
313
+ * 4. Validate and return the human's response
314
+ *
315
+ * The current implementation generates the UI artifacts but returns a pending
316
+ * placeholder instead of actually sending to the channel and waiting for response.
317
+ * This allows testing the UI generation without requiring actual channel integrations.
318
+ *
319
+ * **Important:** Use `isPendingHumanResult()` to check if the result is pending
320
+ * before attempting to use it as the expected output type.
321
+ *
322
+ * @param definition - The human function definition with channel and instructions
323
+ * @param args - Arguments to pass to the function
324
+ * @returns Either the actual TOutput from human input, or a HumanFunctionPending placeholder
325
+ *
326
+ * @example
327
+ * ```ts
328
+ * import { isPendingHumanResult } from 'ai-functions'
329
+ *
330
+ * const result = await approveRefund({ amount: 500 })
331
+ *
332
+ * if (isPendingHumanResult(result)) {
333
+ * // Handle pending state
334
+ * console.log('Awaiting human approval via:', result.channel)
335
+ * return { status: 'pending' }
336
+ * }
337
+ *
338
+ * // result is the actual approval response
339
+ * console.log('Approved:', result.approved)
340
+ * ```
341
+ */
342
+ async function executeHumanFunction(definition, args) {
343
+ const { channel, instructions, promptTemplate, returnType } = definition;
344
+ const prompt = promptTemplate
345
+ ? fillTemplate(promptTemplate, args)
346
+ : JSON.stringify(args);
347
+ // Generate channel-specific UI
348
+ const uiSchema = {
349
+ // New HumanChannel types
350
+ chat: {
351
+ message: 'Chat message to send',
352
+ options: ['Response options if applicable'],
353
+ },
354
+ email: {
355
+ subject: 'Email subject',
356
+ html: 'Email HTML body',
357
+ text: 'Plain text fallback',
358
+ },
359
+ phone: {
360
+ script: 'Phone call script',
361
+ keyPoints: ['Key points to cover'],
362
+ },
363
+ sms: {
364
+ text: 'SMS message text (max 160 chars)',
365
+ },
366
+ workspace: {
367
+ blocks: ['Workspace/Slack BlockKit blocks as JSON array'],
368
+ text: 'Plain text fallback',
369
+ },
370
+ web: {
371
+ component: 'React component code for the form',
372
+ schema: 'JSON schema for the form fields',
373
+ },
374
+ // Legacy fallback
375
+ custom: {
376
+ data: 'Structured data for custom implementation',
377
+ instructions: 'Instructions for the human',
378
+ },
379
+ };
380
+ const result = await generateObject({
381
+ model: 'sonnet',
382
+ schema: uiSchema[channel] ?? uiSchema['custom'],
383
+ system: `Generate ${channel} UI/content for a human-in-the-loop task.`,
384
+ prompt: `Task: ${instructions}
385
+
386
+ Input data:
387
+ ${prompt}
388
+
389
+ Expected response format:
390
+ ${JSON.stringify(returnType)}
391
+
392
+ Generate the appropriate ${channel} UI/content to collect this response from a human.`,
393
+ });
394
+ // Runtime warning for developers
395
+ getLogger().warn(`[HumanFunction] Returning pending placeholder for channel '${channel}'. ` +
396
+ `Use isPendingHumanResult() to check before using the result. ` +
397
+ `Full channel integration is not yet implemented.`);
398
+ // Return a properly typed pending result
399
+ // The symbol marker allows isPendingHumanResult() to reliably identify this
400
+ const pendingResult = {
401
+ [PENDING_HUMAN_RESULT_SYMBOL]: true,
402
+ _pending: true,
403
+ channel,
404
+ artifacts: result.object,
405
+ expectedResponseType: returnType,
406
+ };
407
+ return pendingResult;
408
+ }
409
+ // ============================================================================
410
+ // Defined Function Creation
411
+ // ============================================================================
412
+ /**
413
+ * Create a defined function from a function definition
414
+ */
415
+ export function createDefinedFunction(definition) {
416
+ const call = async (args) => {
417
+ switch (definition.type) {
418
+ case 'code':
419
+ return executeCodeFunction(definition, args);
420
+ case 'generative':
421
+ return executeGenerativeFunction(definition, args);
422
+ case 'agentic':
423
+ return executeAgenticFunction(definition, args);
424
+ case 'human':
425
+ return executeHumanFunction(definition, args);
426
+ default:
427
+ throw new Error(`Unknown function type: ${definition.type}`);
428
+ }
429
+ };
430
+ const asTool = () => {
431
+ return {
432
+ name: definition.name,
433
+ description: definition.description || `Execute ${definition.name}`,
434
+ parameters: convertArgsToJSONSchema(definition.args),
435
+ handler: call,
436
+ };
437
+ };
438
+ return { definition, call, asTool };
439
+ }
440
+ /**
441
+ * Standalone function for defining AI functions
442
+ *
443
+ * @example
444
+ * ```ts
445
+ * import { defineFunction } from 'ai-functions'
446
+ *
447
+ * const summarize = defineFunction({
448
+ * type: 'generative',
449
+ * name: 'summarize',
450
+ * args: { text: 'Text to summarize' },
451
+ * output: 'string',
452
+ * promptTemplate: 'Summarize: {{text}}',
453
+ * })
454
+ *
455
+ * const result = await summarize.call({ text: 'Long article...' })
456
+ * ```
457
+ */
458
+ export function defineFunction(definition) {
459
+ return createDefinedFunction(definition);
460
+ }
461
+ // ============================================================================
462
+ // Function Registry Implementation
463
+ // ============================================================================
464
+ /**
465
+ * In-memory function registry
466
+ */
467
+ class InMemoryFunctionRegistry {
468
+ functions = new Map();
469
+ get(name) {
470
+ return this.functions.get(name);
471
+ }
472
+ set(name, fn) {
473
+ this.functions.set(name, fn);
474
+ }
475
+ has(name) {
476
+ return this.functions.has(name);
477
+ }
478
+ list() {
479
+ return Array.from(this.functions.keys());
480
+ }
481
+ delete(name) {
482
+ return this.functions.delete(name);
483
+ }
484
+ clear() {
485
+ this.functions.clear();
486
+ }
487
+ }
488
+ /**
489
+ * Factory function to create a new isolated function registry instance.
490
+ *
491
+ * Use this when you need:
492
+ * - Test isolation: Each test can have its own registry
493
+ * - Scoped registries: Different parts of an app can have separate registries
494
+ * - Custom lifecycle management: Control when registries are created/destroyed
495
+ *
496
+ * @example
497
+ * ```ts
498
+ * // Create isolated registry for tests
499
+ * const registry = createFunctionRegistry()
500
+ * const fn = defineFunction({ ... })
501
+ * registry.set('myFunc', fn)
502
+ *
503
+ * // Later, registry can be discarded without affecting global state
504
+ * ```
505
+ *
506
+ * @returns A new FunctionRegistry instance
507
+ */
508
+ export function createFunctionRegistry() {
509
+ return new InMemoryFunctionRegistry();
510
+ }
511
+ /**
512
+ * Global function registry
513
+ *
514
+ * Note: This is in-memory only. For persistence, use mdxai or mdxdb packages.
515
+ *
516
+ * **Lifecycle:**
517
+ * - Created once at module load time
518
+ * - Shared across the entire application
519
+ * - Use `resetGlobalRegistry()` in tests to clear state between test runs
520
+ * - For isolated registries, use `createFunctionRegistry()` instead
521
+ */
522
+ export const functions = new InMemoryFunctionRegistry();
523
+ /**
524
+ * Reset the global function registry to a clean state.
525
+ *
526
+ * **Important:** This is primarily intended for test cleanup to ensure
527
+ * test isolation. In production code, prefer using `createFunctionRegistry()`
528
+ * for isolated registries.
529
+ *
530
+ * @example
531
+ * ```ts
532
+ * // In test setup/teardown
533
+ * beforeEach(() => {
534
+ * resetGlobalRegistry()
535
+ * })
536
+ *
537
+ * // Or after each test
538
+ * afterEach(() => {
539
+ * resetGlobalRegistry()
540
+ * })
541
+ * ```
542
+ */
543
+ export function resetGlobalRegistry() {
544
+ functions.clear();
545
+ }
546
+ //# sourceMappingURL=function-registry.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"function-registry.js","sourceRoot":"","sources":["../src/function-registry.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAAE,cAAc,EAAE,MAAM,eAAe,CAAA;AAe9C,OAAO,EAAE,2BAA2B,EAAE,MAAM,YAAY,CA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