ai-functions 2.1.3 → 2.4.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 (284) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/CHANGELOG.md +90 -1
  3. package/README.md +38 -0
  4. package/dist/ai-promise.d.ts +3 -3
  5. package/dist/ai-promise.d.ts.map +1 -1
  6. package/dist/ai-promise.js +135 -64
  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 +51 -858
  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.map +1 -1
  56. package/dist/budget.js +27 -14
  57. package/dist/budget.js.map +1 -1
  58. package/dist/cache.d.ts +23 -0
  59. package/dist/cache.d.ts.map +1 -1
  60. package/dist/cache.js +36 -15
  61. package/dist/cache.js.map +1 -1
  62. package/dist/context.d.ts +26 -8
  63. package/dist/context.d.ts.map +1 -1
  64. package/dist/context.js +64 -62
  65. package/dist/context.js.map +1 -1
  66. package/dist/digital-objects-registry.d.ts +229 -0
  67. package/dist/digital-objects-registry.d.ts.map +1 -0
  68. package/dist/digital-objects-registry.js +617 -0
  69. package/dist/digital-objects-registry.js.map +1 -0
  70. package/dist/embeddings.d.ts +2 -2
  71. package/dist/embeddings.d.ts.map +1 -1
  72. package/dist/errors.d.ts +22 -0
  73. package/dist/errors.d.ts.map +1 -0
  74. package/dist/errors.js +35 -0
  75. package/dist/errors.js.map +1 -0
  76. package/dist/eval/runner.d.ts +8 -0
  77. package/dist/eval/runner.d.ts.map +1 -1
  78. package/dist/eval/runner.js +41 -35
  79. package/dist/eval/runner.js.map +1 -1
  80. package/dist/eval-log/in-memory.d.ts +34 -0
  81. package/dist/eval-log/in-memory.d.ts.map +1 -0
  82. package/dist/eval-log/in-memory.js +84 -0
  83. package/dist/eval-log/in-memory.js.map +1 -0
  84. package/dist/eval-log/index.d.ts +29 -0
  85. package/dist/eval-log/index.d.ts.map +1 -0
  86. package/dist/eval-log/index.js +39 -0
  87. package/dist/eval-log/index.js.map +1 -0
  88. package/dist/eval-log/types.d.ts +101 -0
  89. package/dist/eval-log/types.d.ts.map +1 -0
  90. package/dist/eval-log/types.js +16 -0
  91. package/dist/eval-log/types.js.map +1 -0
  92. package/dist/function-registry.d.ts +176 -0
  93. package/dist/function-registry.d.ts.map +1 -0
  94. package/dist/function-registry.js +685 -0
  95. package/dist/function-registry.js.map +1 -0
  96. package/dist/generate.d.ts +9 -3
  97. package/dist/generate.d.ts.map +1 -1
  98. package/dist/generate.js +18 -18
  99. package/dist/generate.js.map +1 -1
  100. package/dist/index.d.ts +18 -11
  101. package/dist/index.d.ts.map +1 -1
  102. package/dist/index.js +35 -18
  103. package/dist/index.js.map +1 -1
  104. package/dist/logger.d.ts +118 -0
  105. package/dist/logger.d.ts.map +1 -0
  106. package/dist/logger.js +187 -0
  107. package/dist/logger.js.map +1 -0
  108. package/dist/middleware/budget.d.ts +84 -0
  109. package/dist/middleware/budget.d.ts.map +1 -0
  110. package/dist/middleware/budget.js +110 -0
  111. package/dist/middleware/budget.js.map +1 -0
  112. package/dist/middleware/cache.d.ts +103 -0
  113. package/dist/middleware/cache.d.ts.map +1 -0
  114. package/dist/middleware/cache.js +228 -0
  115. package/dist/middleware/cache.js.map +1 -0
  116. package/dist/middleware/embed-cache.d.ts +99 -0
  117. package/dist/middleware/embed-cache.d.ts.map +1 -0
  118. package/dist/middleware/embed-cache.js +128 -0
  119. package/dist/middleware/embed-cache.js.map +1 -0
  120. package/dist/middleware/index.d.ts +11 -0
  121. package/dist/middleware/index.d.ts.map +1 -0
  122. package/dist/middleware/index.js +11 -0
  123. package/dist/middleware/index.js.map +1 -0
  124. package/dist/middleware/trace.d.ts +103 -0
  125. package/dist/middleware/trace.d.ts.map +1 -0
  126. package/dist/middleware/trace.js +176 -0
  127. package/dist/middleware/trace.js.map +1 -0
  128. package/dist/primitives.d.ts +120 -1
  129. package/dist/primitives.d.ts.map +1 -1
  130. package/dist/primitives.js +398 -26
  131. package/dist/primitives.js.map +1 -1
  132. package/dist/retry.d.ts +66 -1
  133. package/dist/retry.d.ts.map +1 -1
  134. package/dist/retry.js +115 -8
  135. package/dist/retry.js.map +1 -1
  136. package/dist/sandbox.d.ts +36 -0
  137. package/dist/sandbox.d.ts.map +1 -0
  138. package/dist/sandbox.js +44 -0
  139. package/dist/sandbox.js.map +1 -0
  140. package/dist/schema.js +2 -2
  141. package/dist/schema.js.map +1 -1
  142. package/dist/telemetry.d.ts +128 -0
  143. package/dist/telemetry.d.ts.map +1 -0
  144. package/dist/telemetry.js +285 -0
  145. package/dist/telemetry.js.map +1 -0
  146. package/dist/template.d.ts.map +1 -1
  147. package/dist/template.js +6 -1
  148. package/dist/template.js.map +1 -1
  149. package/dist/tool-orchestration.d.ts +66 -4
  150. package/dist/tool-orchestration.d.ts.map +1 -1
  151. package/dist/tool-orchestration.js +123 -23
  152. package/dist/tool-orchestration.js.map +1 -1
  153. package/dist/type-guards.d.ts +28 -0
  154. package/dist/type-guards.d.ts.map +1 -0
  155. package/dist/type-guards.js +29 -0
  156. package/dist/type-guards.js.map +1 -0
  157. package/dist/types.d.ts +155 -19
  158. package/dist/types.d.ts.map +1 -1
  159. package/dist/types.js +36 -1
  160. package/dist/types.js.map +1 -1
  161. package/dist/wrap-for-v3.d.ts +80 -0
  162. package/dist/wrap-for-v3.d.ts.map +1 -0
  163. package/dist/wrap-for-v3.js +89 -0
  164. package/dist/wrap-for-v3.js.map +1 -0
  165. package/examples/00-quickstart.ts +232 -0
  166. package/examples/01-rag-chatbot.ts +212 -0
  167. package/examples/02-multi-agent-research.ts +290 -0
  168. package/examples/03-email-classification.ts +379 -0
  169. package/examples/04-content-moderation.ts +400 -0
  170. package/examples/05-document-extraction.ts +455 -0
  171. package/examples/06-streaming-chat-nextjs.ts +437 -0
  172. package/examples/07-cloudflare-worker.ts +483 -0
  173. package/examples/08-batch-processing.ts +491 -0
  174. package/examples/09-budget-constrained.ts +527 -0
  175. package/examples/10-tool-orchestration.ts +565 -0
  176. package/examples/11-retry-resilience.ts +403 -0
  177. package/examples/12-caching-strategies.ts +422 -0
  178. package/examples/README.md +145 -0
  179. package/package.json +29 -25
  180. package/src/ai-promise.ts +226 -140
  181. package/src/ai-schemas.ts +122 -0
  182. package/src/ai.ts +71 -1176
  183. package/src/batch/anthropic.ts +96 -161
  184. package/src/batch/bedrock.ts +203 -454
  185. package/src/batch/cloudflare.ts +99 -282
  186. package/src/batch/google.ts +91 -297
  187. package/src/batch/index.ts +4 -1
  188. package/src/batch/memory.ts +15 -10
  189. package/src/batch/openai.ts +65 -193
  190. package/src/batch/provider.ts +336 -0
  191. package/src/batch-map.ts +29 -24
  192. package/src/batch-queue.ts +200 -11
  193. package/src/budget.ts +31 -18
  194. package/src/cache.ts +45 -17
  195. package/src/context.ts +106 -77
  196. package/src/digital-objects-registry.ts +750 -0
  197. package/src/errors.ts +37 -0
  198. package/src/eval/runner.ts +60 -36
  199. package/src/eval-log/in-memory.ts +90 -0
  200. package/src/eval-log/index.ts +46 -0
  201. package/src/eval-log/types.ts +110 -0
  202. package/src/function-registry.ts +874 -0
  203. package/src/generate.ts +33 -28
  204. package/src/index.ts +122 -21
  205. package/src/logger.ts +232 -0
  206. package/src/middleware/budget.ts +171 -0
  207. package/src/middleware/cache.ts +299 -0
  208. package/src/middleware/embed-cache.ts +195 -0
  209. package/src/middleware/index.ts +23 -0
  210. package/src/middleware/trace.ts +248 -0
  211. package/src/primitives.ts +589 -62
  212. package/src/retry.ts +144 -18
  213. package/src/sandbox.ts +52 -0
  214. package/src/schema.ts +8 -8
  215. package/src/telemetry.ts +403 -0
  216. package/src/template.ts +8 -4
  217. package/src/tool-orchestration.ts +213 -48
  218. package/src/type-guards.ts +31 -0
  219. package/src/types.ts +186 -27
  220. package/src/wrap-for-v3.ts +105 -0
  221. package/test/ai-promise.test.ts +1080 -0
  222. package/test/ai-proxy.test.ts +1 -1
  223. package/test/batch-autosubmit-errors.test.ts +49 -37
  224. package/test/batch-blog-posts.test.ts +87 -129
  225. package/test/core-functions.test.ts +183 -579
  226. package/test/decide.test.ts +154 -322
  227. package/test/define.test.ts +211 -8
  228. package/test/digital-objects-registry.test.ts +760 -0
  229. package/test/embedding-cache-middleware.test.ts +140 -0
  230. package/test/fill-template.test.ts +89 -0
  231. package/test/generate-core.test.ts +140 -229
  232. package/test/implicit-batch.test.ts +22 -65
  233. package/test/retry-policy-integration.test.ts +117 -0
  234. package/test/sandbox-execution.test.ts +155 -0
  235. package/test/schema.test.ts +55 -19
  236. package/test/template.test.ts +1164 -0
  237. package/test/tool-orchestration.test.ts +270 -0
  238. package/test/wrap-for-v3.test.ts +612 -0
  239. package/vitest.config.js +6 -0
  240. package/vitest.config.ts +20 -0
  241. package/LICENSE +0 -21
  242. package/dist/rpc/auth.d.ts +0 -69
  243. package/dist/rpc/auth.d.ts.map +0 -1
  244. package/dist/rpc/auth.js +0 -136
  245. package/dist/rpc/auth.js.map +0 -1
  246. package/dist/rpc/client.d.ts +0 -62
  247. package/dist/rpc/client.d.ts.map +0 -1
  248. package/dist/rpc/client.js +0 -103
  249. package/dist/rpc/client.js.map +0 -1
  250. package/dist/rpc/deferred.d.ts +0 -60
  251. package/dist/rpc/deferred.d.ts.map +0 -1
  252. package/dist/rpc/deferred.js +0 -96
  253. package/dist/rpc/deferred.js.map +0 -1
  254. package/dist/rpc/index.d.ts +0 -22
  255. package/dist/rpc/index.d.ts.map +0 -1
  256. package/dist/rpc/index.js +0 -38
  257. package/dist/rpc/index.js.map +0 -1
  258. package/dist/rpc/local.d.ts +0 -42
  259. package/dist/rpc/local.d.ts.map +0 -1
  260. package/dist/rpc/local.js +0 -50
  261. package/dist/rpc/local.js.map +0 -1
  262. package/dist/rpc/server.d.ts +0 -165
  263. package/dist/rpc/server.d.ts.map +0 -1
  264. package/dist/rpc/server.js +0 -405
  265. package/dist/rpc/server.js.map +0 -1
  266. package/dist/rpc/session.d.ts +0 -32
  267. package/dist/rpc/session.d.ts.map +0 -1
  268. package/dist/rpc/session.js +0 -43
  269. package/dist/rpc/session.js.map +0 -1
  270. package/dist/rpc/transport.d.ts +0 -306
  271. package/dist/rpc/transport.d.ts.map +0 -1
  272. package/dist/rpc/transport.js +0 -731
  273. package/dist/rpc/transport.js.map +0 -1
  274. package/src/batch/anthropic.js +0 -256
  275. package/src/batch/bedrock.js +0 -584
  276. package/src/batch/cloudflare.js +0 -287
  277. package/src/batch/google.js +0 -359
  278. package/src/batch/index.js +0 -30
  279. package/src/batch/memory.js +0 -187
  280. package/src/batch/openai.js +0 -402
  281. package/src/eval/index.js +0 -7
  282. package/src/eval/models.js +0 -119
  283. package/src/eval/runner.js +0 -147
  284. package/test/schema.test.js +0 -96
@@ -0,0 +1,685 @@
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
+ import { runInSandbox } from './sandbox.js';
12
+ // ============================================================================
13
+ // JSON Schema Conversion
14
+ // ============================================================================
15
+ /**
16
+ * Convert args schema to JSON Schema
17
+ */
18
+ export function convertArgsToJSONSchema(args) {
19
+ // If it's already a JSON schema-like object
20
+ if (typeof args === 'object' && args !== null && 'type' in args) {
21
+ return args;
22
+ }
23
+ // Convert SimpleSchema to JSON Schema
24
+ const properties = {};
25
+ const required = [];
26
+ if (typeof args === 'object' && args !== null) {
27
+ for (const [key, value] of Object.entries(args)) {
28
+ required.push(key); // All properties required for cross-provider compatibility
29
+ properties[key] = convertValueToJSONSchema(value);
30
+ }
31
+ }
32
+ return {
33
+ type: 'object',
34
+ properties,
35
+ required,
36
+ additionalProperties: false, // Required for OpenAI compatibility
37
+ };
38
+ }
39
+ /**
40
+ * Convert a single value to JSON Schema
41
+ */
42
+ function convertValueToJSONSchema(value) {
43
+ if (typeof value === 'string') {
44
+ // Check for type hints: 'description (number)', 'description (boolean)', etc.
45
+ const typeMatch = value.match(/^(.+?)\s*\((number|boolean|integer|date)\)$/i);
46
+ if (typeMatch) {
47
+ const description = typeMatch[1];
48
+ const type = typeMatch[2];
49
+ switch (type.toLowerCase()) {
50
+ case 'number':
51
+ return { type: 'number', description: description.trim() };
52
+ case 'integer':
53
+ return { type: 'integer', description: description.trim() };
54
+ case 'boolean':
55
+ return { type: 'boolean', description: description.trim() };
56
+ case 'date':
57
+ return { type: 'string', format: 'date-time', description: description.trim() };
58
+ }
59
+ }
60
+ // Check for enum: 'option1 | option2 | option3'
61
+ if (value.includes(' | ')) {
62
+ const options = value.split(' | ').map((s) => s.trim());
63
+ return { type: 'string', enum: options };
64
+ }
65
+ return { type: 'string', description: value };
66
+ }
67
+ if (Array.isArray(value) && value.length === 1) {
68
+ const [desc] = value;
69
+ if (typeof desc === 'string') {
70
+ return { type: 'array', items: { type: 'string' }, description: desc };
71
+ }
72
+ if (typeof desc === 'number') {
73
+ return { type: 'array', items: { type: 'number' } };
74
+ }
75
+ return { type: 'array', items: convertValueToJSONSchema(desc) };
76
+ }
77
+ if (typeof value === 'object' && value !== null) {
78
+ return convertArgsToJSONSchema(value);
79
+ }
80
+ return { type: 'string' };
81
+ }
82
+ // ============================================================================
83
+ // Template Utilities
84
+ // ============================================================================
85
+ /**
86
+ * Fill template with values
87
+ */
88
+ export function fillTemplate(template, args) {
89
+ return template.replace(/\{\{(\w+)\}\}/g, (_, key) => {
90
+ const v = args[key] ?? '';
91
+ if (typeof v === 'object' && v !== null) {
92
+ return JSON.stringify(v);
93
+ }
94
+ return String(v);
95
+ });
96
+ }
97
+ // ============================================================================
98
+ // Function Executors
99
+ // ============================================================================
100
+ /**
101
+ * Execute a **deterministic** code function.
102
+ *
103
+ * `Code` is the deterministic kind: no model is consulted at call time. This
104
+ * invokes the definition's `handler` (canonical) or, if only an inline `code`
105
+ * body was supplied, deterministically compiles and runs it. The result is
106
+ * returned directly.
107
+ *
108
+ * This is a deliberate change from the previous behavior, where `type: 'code'`
109
+ * LLM-generated source at call time. That code-*authoring* behavior now lives
110
+ * in {@link generateAndRunCode} (and the `generate('code', …)` primitive), so
111
+ * that `Code` can carry the "deterministic handler" contract consumers depend
112
+ * on (ADR-0033). See the package README migration note.
113
+ *
114
+ * Inline `code` bodies are executed in ai-evaluate's V8-isolate sandbox — never
115
+ * via `new Function`/`eval`. Execution stays deterministic: no model is ever
116
+ * consulted on this path.
117
+ *
118
+ * @param env - Optional host Workers env (carrying `LOADER`) for the sandbox;
119
+ * when omitted the inline-code path falls back to the Miniflare-backed Node
120
+ * runtime. Ignored when a `handler` is supplied (direct call, no sandbox).
121
+ *
122
+ * @throws if neither `handler` nor `code` is provided, or if an inline `code`
123
+ * body is in a non-evaluable language.
124
+ */
125
+ async function executeCodeFunction(definition, args, env) {
126
+ const { handler, code, language = 'typescript', name } = definition;
127
+ if (typeof handler === 'function') {
128
+ return await handler(args);
129
+ }
130
+ if (typeof code === 'string' && code.length > 0) {
131
+ return await runInlineCode(code, args, language, name, env);
132
+ }
133
+ throw new Error(`Code function '${name}' has no handler or inline code. ` +
134
+ `'code' functions are deterministic and require a handler: (input) => output ` +
135
+ `(or an inline 'code' body). To have a model *author* code instead, use ` +
136
+ `generateAndRunCode() / generateCode() or define a 'generative' function.`);
137
+ }
138
+ /**
139
+ * Deterministically run an inline `code` body for a Code function in the
140
+ * ai-evaluate V8-isolate sandbox.
141
+ *
142
+ * The body is treated as a function whose `return` value is the result; the
143
+ * parsed `args` are exposed as a top-level `args` binding inside the sandbox.
144
+ * Only the JS/TS-compatible languages can be evaluated; other languages are
145
+ * carried as metadata for an external runtime and are rejected here.
146
+ *
147
+ * No model is involved — the same body always produces the same behavior. This
148
+ * replaces the former `new Function(...)` path: `new Function`/`eval` are
149
+ * banned in this package (broken under Workers, unsandboxed under Node).
150
+ *
151
+ * Limitation: `args` are injected by JSON-serializing them into the sandbox
152
+ * script (`JSON.parse(<json>)`), so only JSON-serializable inputs are
153
+ * supported on the inline-`code` path. Pass a `handler` for non-serializable
154
+ * inputs (functions, class instances, etc.).
155
+ *
156
+ * @param env - Optional host Workers env (carrying `LOADER`) for the sandbox;
157
+ * when omitted, runs against the Miniflare-backed Node runtime.
158
+ */
159
+ async function runInlineCode(code, args, language, name, env) {
160
+ if (language !== 'typescript' && language !== 'javascript') {
161
+ throw new Error(`Code function '${name}' has an inline 'code' body in language '${language}', ` +
162
+ `which cannot be evaluated in the sandbox. Pass a 'handler' instead, or run it ` +
163
+ `in an external deterministic runtime.`);
164
+ }
165
+ const body = /\breturn\b/.test(code) ? code : `return (${code})`;
166
+ // Inject args deterministically by serializing them into the sandbox script.
167
+ // (JSON-serializable inputs only — see the doc comment.)
168
+ let argsJson;
169
+ try {
170
+ argsJson = JSON.stringify(args ?? null);
171
+ }
172
+ catch (e) {
173
+ throw new Error(`Code function '${name}' received non-JSON-serializable args for its inline 'code' ` +
174
+ `body: ${e.message}. Pass a 'handler' for non-serializable inputs.`);
175
+ }
176
+ const script = `const args = JSON.parse(${JSON.stringify(argsJson)});\n${body}`;
177
+ const result = await runInSandbox({ script }, env);
178
+ if (result.success === false) {
179
+ throw new Error(`Code function '${name}' failed in the sandbox: ${result.error ?? 'unknown error'}`);
180
+ }
181
+ return result.value;
182
+ }
183
+ /**
184
+ * Author code with a model — the explicit, opt-in code-*generation* path.
185
+ *
186
+ * This is the behavior `type: 'code'` used to have implicitly at call time.
187
+ * It has been split out so that `Code` functions can be deterministic. Calling
188
+ * this **does** consult a model and returns the generated source as a string;
189
+ * it does not produce a deterministic, repeatable handler.
190
+ *
191
+ * @param definition - The code-authoring spec ({@link CodeGenerationDefinition})
192
+ * @param args - Concrete inputs / refinements for the requested code
193
+ * @returns The generated source code as a string
194
+ *
195
+ * @example
196
+ * ```ts
197
+ * import { generateCode } from 'ai-functions'
198
+ *
199
+ * const src = await generateCode(
200
+ * { name: 'calculateTax', args: { amount: '(number)', rate: '(number)' }, language: 'typescript' },
201
+ * { amount: 100, rate: 0.2 }
202
+ * )
203
+ * ```
204
+ */
205
+ export async function generateCode(definition, args) {
206
+ const { name, description, language = 'typescript', instructions, returnType, model = 'sonnet', } = definition;
207
+ const argsDescription = JSON.stringify(args ?? definition.args, null, 2);
208
+ const result = await generateObject({
209
+ model,
210
+ schema: {
211
+ code: `The complete ${language} implementation code. Output ONLY the raw code without markdown formatting or code blocks.`,
212
+ },
213
+ 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.`,
214
+ prompt: `Generate a ${language} function/query with the following specification:
215
+
216
+ Name: ${name}
217
+ Description: ${description || 'No description provided'}
218
+ Arguments: ${argsDescription}
219
+ Return Type: ${JSON.stringify(returnType)}
220
+
221
+ ${instructions ? `Additional Instructions: ${instructions}` : ''}
222
+
223
+ Requirements:
224
+ - Include appropriate comments/documentation
225
+ - Follow best practices for ${language}
226
+ - Handle edge cases appropriately
227
+ - Return ONLY the code without markdown formatting`,
228
+ });
229
+ return result.object.code;
230
+ }
231
+ /**
232
+ * The **non-deterministic** generate → run → test → return capability.
233
+ *
234
+ * This is the headline of the `generate('code', …)` primitive: a model
235
+ * **authors** code, that code is **run** in ai-evaluate's V8-isolate sandbox,
236
+ * optionally **tested** there, and the executed **result** is returned (not
237
+ * just the source). This is deliberately separate from `type: 'code'`, which is
238
+ * deterministic and never consults a model — so determinism is never blurred.
239
+ *
240
+ * Unlike {@link generateCode} (which only returns source text), this runs the
241
+ * authored code. The authored module is expected to `export function ${name}`
242
+ * (a NAMED export — the sandbox's module loader does not support `export
243
+ * default`); the sandbox script invokes `${name}(args)` and returns its result.
244
+ *
245
+ * @param definition - The code-authoring spec ({@link CodeGenerationDefinition}).
246
+ * Set `includeTests: false` to skip test authoring (default: tests included).
247
+ * @param args - Concrete inputs the authored code is invoked with.
248
+ * @param env - Optional host Workers env. When it carries `LOADER` **and**
249
+ * `TEST`, tests run on the real Dynamic Workers loader; otherwise execution
250
+ * falls back to the Miniflare-backed Node runtime (whose dev worker has its
251
+ * own embedded test runner and needs no live `TEST` binding).
252
+ * @returns The executed result plus authored artifacts.
253
+ *
254
+ * @example
255
+ * ```ts
256
+ * import { generateAndRunCode } from 'ai-functions'
257
+ *
258
+ * const { value } = await generateAndRunCode(
259
+ * { name: 'calculateTax', args: { amount: '(number)', rate: '(number)' } },
260
+ * { amount: 100, rate: 0.2 }
261
+ * )
262
+ * // value === 20 (the model authored the code, the sandbox ran it)
263
+ * ```
264
+ */
265
+ export async function generateAndRunCode(definition, args, env) {
266
+ const { name, description, language = 'typescript', instructions, returnType, includeTests = true, model = 'sonnet', } = definition;
267
+ const argsDescription = JSON.stringify(args ?? definition.args, null, 2);
268
+ // Step 1 — model AUTHORS the module (+ optional tests). Non-deterministic.
269
+ const codeSpec = `The complete ${language} module. It MUST contain a NAMED export 'export function ${name}(args) { ... }' (NOT a default export) that takes a single arguments object and returns the result. Output ONLY raw code, no markdown fences.`;
270
+ const schema = includeTests
271
+ ? {
272
+ code: codeSpec,
273
+ tests: `vitest-style tests using global describe/it/expect. The function '${name}' is already in scope (do not import it). Output ONLY raw code, no markdown fences.`,
274
+ }
275
+ : {
276
+ code: codeSpec,
277
+ };
278
+ const authored = await generateObject({
279
+ model,
280
+ schema,
281
+ system: `You are an expert ${language} developer. Generate clean, production-ready code. The module MUST expose a NAMED export 'export function ${name}(args)' taking one arguments object — do NOT use 'export default'. Output ONLY raw code, no markdown code fences or language tags.`,
282
+ prompt: `Author a ${language} module with the following specification:
283
+
284
+ Name: ${name}
285
+ Description: ${description || 'No description provided'}
286
+ Arguments: ${argsDescription}
287
+ Return Type: ${JSON.stringify(returnType)}
288
+
289
+ ${instructions ? `Additional Instructions: ${instructions}` : ''}
290
+
291
+ Requirements:
292
+ - Expose 'export function ${name}(args) { ... }' (a NAMED export, not default), taking one arguments object.
293
+ - Handle edge cases appropriately.
294
+ - Return ONLY raw code without markdown formatting.`,
295
+ });
296
+ const authoredObj = authored.object;
297
+ const code = authoredObj.code;
298
+ const tests = includeTests ? authoredObj.tests : undefined;
299
+ // Step 2 — RUN the authored code in the sandbox and capture its return value.
300
+ // The module's default export is invoked with the JSON-injected args; the
301
+ // result is returned by the sandbox script. Tests (if any) run in the same
302
+ // sandbox via the worker template's test runner.
303
+ let argsJson;
304
+ try {
305
+ argsJson = JSON.stringify(args ?? null);
306
+ }
307
+ catch (e) {
308
+ throw new Error(`generateAndRunCode('${name}'): args are not JSON-serializable: ${e.message}`);
309
+ }
310
+ // The named export `${name}` is exposed as a top-level binding by the worker
311
+ // template (`const { ${name} } = exports`). The script calls it with the
312
+ // JSON-injected args and returns the result.
313
+ const result = await runInSandbox({
314
+ module: code,
315
+ script: `const __args__ = JSON.parse(${JSON.stringify(argsJson)}); if (typeof ${name} !== 'function') { throw new Error("authored module did not export a callable '${name}'"); } return await ${name}(__args__);`,
316
+ ...(tests !== undefined && { tests }),
317
+ }, env);
318
+ if (result.success === false) {
319
+ throw new Error(`generateAndRunCode('${name}') failed in the sandbox: ${result.error ?? 'unknown error'}`);
320
+ }
321
+ return {
322
+ value: result.value,
323
+ code,
324
+ ...(tests !== undefined && { tests }),
325
+ ...(result.testResults && {
326
+ testResults: {
327
+ total: result.testResults.total,
328
+ passed: result.testResults.passed,
329
+ failed: result.testResults.failed,
330
+ skipped: result.testResults.skipped,
331
+ },
332
+ }),
333
+ logs: result.logs.map((l) => ({ level: l.level, message: l.message })),
334
+ };
335
+ }
336
+ /**
337
+ * Execute a generative function - uses AI to generate content
338
+ */
339
+ async function executeGenerativeFunction(definition, args) {
340
+ const { output, system, promptTemplate, model = 'sonnet', temperature, returnType } = definition;
341
+ const prompt = promptTemplate
342
+ ? fillTemplate(promptTemplate, args)
343
+ : JSON.stringify(args);
344
+ switch (output) {
345
+ case 'string': {
346
+ const result = await generateObject({
347
+ model,
348
+ schema: { text: 'The generated text response' },
349
+ prompt,
350
+ ...(system !== undefined && { system }),
351
+ ...(temperature !== undefined && { temperature }),
352
+ });
353
+ return result.object.text;
354
+ }
355
+ case 'object': {
356
+ const objectSchema = returnType || { result: 'The generated result' };
357
+ const result = await generateObject({
358
+ model,
359
+ schema: objectSchema,
360
+ prompt,
361
+ ...(system !== undefined && { system }),
362
+ ...(temperature !== undefined && { temperature }),
363
+ });
364
+ return result.object;
365
+ }
366
+ case 'image':
367
+ throw new Error('Image generation via generative functions is not yet implemented. ' +
368
+ 'Use the image() primitive directly instead.');
369
+ case 'video':
370
+ throw new Error('Video generation via generative functions is not yet implemented. ' +
371
+ 'Use the video() primitive directly instead.');
372
+ default:
373
+ throw new Error(`Unknown output type: ${output}`);
374
+ }
375
+ }
376
+ /**
377
+ * Execute an agentic function - runs in a loop with tools
378
+ */
379
+ async function executeAgenticFunction(definition, args) {
380
+ const { instructions, promptTemplate, tools = [], maxIterations = 10, model = 'sonnet', returnType, } = definition;
381
+ const prompt = promptTemplate
382
+ ? fillTemplate(promptTemplate, args)
383
+ : JSON.stringify(args);
384
+ // Build system prompt with tool descriptions
385
+ const toolDescriptions = tools.map((t) => `- ${t.name}: ${t.description}`).join('\n');
386
+ const systemPrompt = `${instructions}
387
+
388
+ Available tools:
389
+ ${toolDescriptions || 'No tools available'}
390
+
391
+ Work step by step to accomplish the task. When you have completed the task, provide your final result.`;
392
+ let iteration = 0;
393
+ const toolResults = [];
394
+ // Simple agent loop
395
+ while (iteration < maxIterations) {
396
+ iteration++;
397
+ const result = await generateObject({
398
+ model,
399
+ schema: {
400
+ thinking: 'Your step-by-step reasoning',
401
+ toolCall: {
402
+ name: 'Tool to call (or "done" if finished)',
403
+ arguments: 'Arguments for the tool as JSON string',
404
+ },
405
+ finalResult: returnType || 'The final result if done',
406
+ },
407
+ system: systemPrompt,
408
+ prompt: `Task: ${prompt}
409
+
410
+ Previous tool results:
411
+ ${toolResults.map((r, i) => `Step ${i + 1}: ${JSON.stringify(r)}`).join('\n') || 'None yet'}
412
+
413
+ What is your next step?`,
414
+ });
415
+ const response = result.object;
416
+ if (response.toolCall.name === 'done' || response.finalResult) {
417
+ return response.finalResult;
418
+ }
419
+ // Execute tool call
420
+ const tool = tools.find((t) => t.name === response.toolCall.name);
421
+ if (tool) {
422
+ let toolArgs;
423
+ try {
424
+ toolArgs = JSON.parse(response.toolCall.arguments || '{}');
425
+ }
426
+ catch (e) {
427
+ toolResults.push({
428
+ error: `Invalid tool arguments: ${e.message}`,
429
+ });
430
+ continue;
431
+ }
432
+ const toolResult = await tool.handler(toolArgs);
433
+ toolResults.push({ tool: response.toolCall.name, result: toolResult });
434
+ }
435
+ else {
436
+ toolResults.push({ error: `Tool not found: ${response.toolCall.name}` });
437
+ }
438
+ }
439
+ throw new Error(`Agent exceeded maximum iterations (${maxIterations})`);
440
+ }
441
+ /**
442
+ * Execute a human function - generates UI and waits for human input
443
+ *
444
+ * **Note: This function currently returns a pending placeholder.**
445
+ *
446
+ * In a complete implementation, this function would:
447
+ * 1. Generate channel-specific UI (Slack blocks, email templates, web forms, etc.)
448
+ * 2. Send the generated UI to the appropriate channel
449
+ * 3. Wait for human response with optional timeout
450
+ * 4. Validate and return the human's response
451
+ *
452
+ * The current implementation generates the UI artifacts but returns a pending
453
+ * placeholder instead of actually sending to the channel and waiting for response.
454
+ * This allows testing the UI generation without requiring actual channel integrations.
455
+ *
456
+ * **Important:** Use `isPendingHumanResult()` to check if the result is pending
457
+ * before attempting to use it as the expected output type.
458
+ *
459
+ * @param definition - The human function definition with channel and instructions
460
+ * @param args - Arguments to pass to the function
461
+ * @returns Either the actual TOutput from human input, or a HumanFunctionPending placeholder
462
+ *
463
+ * @example
464
+ * ```ts
465
+ * import { isPendingHumanResult } from 'ai-functions'
466
+ *
467
+ * const result = await approveRefund({ amount: 500 })
468
+ *
469
+ * if (isPendingHumanResult(result)) {
470
+ * // Handle pending state
471
+ * console.log('Awaiting human approval via:', result.channel)
472
+ * return { status: 'pending' }
473
+ * }
474
+ *
475
+ * // result is the actual approval response
476
+ * console.log('Approved:', result.approved)
477
+ * ```
478
+ */
479
+ async function executeHumanFunction(definition, args) {
480
+ const { channel, instructions, promptTemplate, returnType } = definition;
481
+ const prompt = promptTemplate
482
+ ? fillTemplate(promptTemplate, args)
483
+ : JSON.stringify(args);
484
+ // Generate channel-specific UI
485
+ const uiSchema = {
486
+ // New HumanChannel types
487
+ chat: {
488
+ message: 'Chat message to send',
489
+ options: ['Response options if applicable'],
490
+ },
491
+ email: {
492
+ subject: 'Email subject',
493
+ html: 'Email HTML body',
494
+ text: 'Plain text fallback',
495
+ },
496
+ phone: {
497
+ script: 'Phone call script',
498
+ keyPoints: ['Key points to cover'],
499
+ },
500
+ sms: {
501
+ text: 'SMS message text (max 160 chars)',
502
+ },
503
+ workspace: {
504
+ blocks: ['Workspace/Slack BlockKit blocks as JSON array'],
505
+ text: 'Plain text fallback',
506
+ },
507
+ web: {
508
+ component: 'React component code for the form',
509
+ schema: 'JSON schema for the form fields',
510
+ },
511
+ // Legacy fallback
512
+ custom: {
513
+ data: 'Structured data for custom implementation',
514
+ instructions: 'Instructions for the human',
515
+ },
516
+ };
517
+ const result = await generateObject({
518
+ model: 'sonnet',
519
+ schema: uiSchema[channel] ?? uiSchema['custom'],
520
+ system: `Generate ${channel} UI/content for a human-in-the-loop task.`,
521
+ prompt: `Task: ${instructions}
522
+
523
+ Input data:
524
+ ${prompt}
525
+
526
+ Expected response format:
527
+ ${JSON.stringify(returnType)}
528
+
529
+ Generate the appropriate ${channel} UI/content to collect this response from a human.`,
530
+ });
531
+ // Runtime warning for developers
532
+ getLogger().warn(`[HumanFunction] Returning pending placeholder for channel '${channel}'. ` +
533
+ `Use isPendingHumanResult() to check before using the result. ` +
534
+ `Full channel integration is not yet implemented.`);
535
+ // Return a properly typed pending result
536
+ // The symbol marker allows isPendingHumanResult() to reliably identify this
537
+ const pendingResult = {
538
+ [PENDING_HUMAN_RESULT_SYMBOL]: true,
539
+ _pending: true,
540
+ channel,
541
+ artifacts: result.object,
542
+ expectedResponseType: returnType,
543
+ };
544
+ return pendingResult;
545
+ }
546
+ // ============================================================================
547
+ // Defined Function Creation
548
+ // ============================================================================
549
+ /**
550
+ * Create a defined function from a function definition
551
+ */
552
+ export function createDefinedFunction(definition) {
553
+ const call = async (args, env) => {
554
+ switch (definition.type) {
555
+ case 'code':
556
+ // Optional host Workers env threads through to the sandbox for inline
557
+ // `code` bodies; ignored for `handler` (direct call) and other types.
558
+ return executeCodeFunction(definition, args, env);
559
+ case 'generative':
560
+ return executeGenerativeFunction(definition, args);
561
+ case 'agentic':
562
+ return executeAgenticFunction(definition, args);
563
+ case 'human':
564
+ return executeHumanFunction(definition, args);
565
+ default:
566
+ throw new Error(`Unknown function type: ${definition.type}`);
567
+ }
568
+ };
569
+ const asTool = () => {
570
+ return {
571
+ name: definition.name,
572
+ description: definition.description || `Execute ${definition.name}`,
573
+ parameters: convertArgsToJSONSchema(definition.args),
574
+ handler: call,
575
+ };
576
+ };
577
+ return { definition, call, asTool };
578
+ }
579
+ /**
580
+ * Standalone function for defining AI functions
581
+ *
582
+ * @example
583
+ * ```ts
584
+ * import { defineFunction } from 'ai-functions'
585
+ *
586
+ * const summarize = defineFunction({
587
+ * type: 'generative',
588
+ * name: 'summarize',
589
+ * args: { text: 'Text to summarize' },
590
+ * output: 'string',
591
+ * promptTemplate: 'Summarize: {{text}}',
592
+ * })
593
+ *
594
+ * const result = await summarize.call({ text: 'Long article...' })
595
+ * ```
596
+ */
597
+ export function defineFunction(definition) {
598
+ return createDefinedFunction(definition);
599
+ }
600
+ // ============================================================================
601
+ // Function Registry Implementation
602
+ // ============================================================================
603
+ /**
604
+ * In-memory function registry
605
+ */
606
+ class InMemoryFunctionRegistry {
607
+ functions = new Map();
608
+ get(name) {
609
+ return this.functions.get(name);
610
+ }
611
+ set(name, fn) {
612
+ this.functions.set(name, fn);
613
+ }
614
+ has(name) {
615
+ return this.functions.has(name);
616
+ }
617
+ list() {
618
+ return Array.from(this.functions.keys());
619
+ }
620
+ delete(name) {
621
+ return this.functions.delete(name);
622
+ }
623
+ clear() {
624
+ this.functions.clear();
625
+ }
626
+ }
627
+ /**
628
+ * Factory function to create a new isolated function registry instance.
629
+ *
630
+ * Use this when you need:
631
+ * - Test isolation: Each test can have its own registry
632
+ * - Scoped registries: Different parts of an app can have separate registries
633
+ * - Custom lifecycle management: Control when registries are created/destroyed
634
+ *
635
+ * @example
636
+ * ```ts
637
+ * // Create isolated registry for tests
638
+ * const registry = createFunctionRegistry()
639
+ * const fn = defineFunction({ ... })
640
+ * registry.set('myFunc', fn)
641
+ *
642
+ * // Later, registry can be discarded without affecting global state
643
+ * ```
644
+ *
645
+ * @returns A new FunctionRegistry instance
646
+ */
647
+ export function createFunctionRegistry() {
648
+ return new InMemoryFunctionRegistry();
649
+ }
650
+ /**
651
+ * Global function registry
652
+ *
653
+ * Note: This is in-memory only. For persistence, use mdxai or mdxdb packages.
654
+ *
655
+ * **Lifecycle:**
656
+ * - Created once at module load time
657
+ * - Shared across the entire application
658
+ * - Use `resetGlobalRegistry()` in tests to clear state between test runs
659
+ * - For isolated registries, use `createFunctionRegistry()` instead
660
+ */
661
+ export const functions = new InMemoryFunctionRegistry();
662
+ /**
663
+ * Reset the global function registry to a clean state.
664
+ *
665
+ * **Important:** This is primarily intended for test cleanup to ensure
666
+ * test isolation. In production code, prefer using `createFunctionRegistry()`
667
+ * for isolated registries.
668
+ *
669
+ * @example
670
+ * ```ts
671
+ * // In test setup/teardown
672
+ * beforeEach(() => {
673
+ * resetGlobalRegistry()
674
+ * })
675
+ *
676
+ * // Or after each test
677
+ * afterEach(() => {
678
+ * resetGlobalRegistry()
679
+ * })
680
+ * ```
681
+ */
682
+ export function resetGlobalRegistry() {
683
+ functions.clear();
684
+ }
685
+ //# sourceMappingURL=function-registry.js.map