@codemation/core-nodes 0.4.3 → 0.7.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 (55) hide show
  1. package/CHANGELOG.md +237 -0
  2. package/dist/index.cjs +3541 -470
  3. package/dist/index.cjs.map +1 -1
  4. package/dist/index.d.cts +1843 -685
  5. package/dist/index.d.ts +1843 -685
  6. package/dist/index.js +3498 -465
  7. package/dist/index.js.map +1 -1
  8. package/package.json +8 -5
  9. package/src/authoring/defineRestNode.types.ts +204 -0
  10. package/src/chatModels/OpenAIChatModelFactory.ts +17 -8
  11. package/src/chatModels/OpenAiStrictJsonSchemaFactory.ts +123 -0
  12. package/src/credentials/ApiKeyCredentialType.ts +60 -0
  13. package/src/credentials/BasicAuthCredentialType.ts +51 -0
  14. package/src/credentials/BearerTokenCredentialType.ts +40 -0
  15. package/src/credentials/OAuth2ClientCredentialsTypeFactory.ts +117 -0
  16. package/src/credentials/OAuth2TokenExchangeFactory.ts +52 -0
  17. package/src/credentials/index.ts +4 -0
  18. package/src/http/HttpBodyBuilder.ts +118 -0
  19. package/src/http/HttpRequestExecutor.ts +153 -0
  20. package/src/http/HttpUrlBuilder.ts +22 -0
  21. package/src/http/httpRequest.types.ts +96 -0
  22. package/src/index.ts +10 -1
  23. package/src/nodes/AIAgentExecutionHelpersFactory.ts +45 -59
  24. package/src/nodes/AIAgentNode.ts +391 -288
  25. package/src/nodes/AgentMessageFactory.ts +57 -49
  26. package/src/nodes/AgentStructuredOutputRunner.ts +65 -71
  27. package/src/nodes/AgentToolExecutionCoordinator.ts +31 -16
  28. package/src/nodes/AssertionNode.ts +42 -0
  29. package/src/nodes/CronTriggerFactory.ts +45 -0
  30. package/src/nodes/CronTriggerNode.ts +40 -0
  31. package/src/nodes/HttpRequestNodeFactory.ts +160 -16
  32. package/src/nodes/IsTestRunNode.ts +25 -0
  33. package/src/nodes/NodeBackedToolRuntime.ts +40 -4
  34. package/src/nodes/TestTriggerNode.ts +33 -0
  35. package/src/nodes/WebhookTriggerFactory.ts +1 -1
  36. package/src/nodes/aggregate.ts +1 -1
  37. package/src/nodes/aiAgentSupport.types.ts +22 -2
  38. package/src/nodes/assertion.ts +42 -0
  39. package/src/nodes/collections/collectionDeleteNode.types.ts +23 -0
  40. package/src/nodes/collections/collectionFindOneNode.types.ts +26 -0
  41. package/src/nodes/collections/collectionGetNode.types.ts +26 -0
  42. package/src/nodes/collections/collectionInsertNode.types.ts +22 -0
  43. package/src/nodes/collections/collectionListNode.types.ts +30 -0
  44. package/src/nodes/collections/collectionUpdateNode.types.ts +23 -0
  45. package/src/nodes/collections/index.ts +6 -0
  46. package/src/nodes/httpRequest.ts +106 -1
  47. package/src/nodes/if.ts +1 -1
  48. package/src/nodes/isTestRun.ts +24 -0
  49. package/src/nodes/mapData.ts +1 -0
  50. package/src/nodes/merge.ts +1 -1
  51. package/src/nodes/noOp.ts +1 -0
  52. package/src/nodes/split.ts +1 -1
  53. package/src/nodes/testTrigger.ts +72 -0
  54. package/src/nodes/wait.ts +1 -0
  55. package/src/chatModels/OpenAIStructuredOutputMethodFactory.ts +0 -46
package/dist/index.js CHANGED
@@ -1,184 +1,570 @@
1
- import { AgentConfigInspector, AgentConnectionNodeCollector, AgentGuardrailDefaults, AgentMessageConfigNormalizer, CallableToolConfig, CodemationTelemetryAttributeNames, CodemationTelemetryMetricNames, ConnectionInvocationIdFactory, ConnectionNodeIdFactory, CoreTokens, DefinedNodeRegistry, GenAiTelemetryAttributeNames, ItemExprResolver, ItemsInputNormalizer, NodeBackedToolConfig, NodeOutputNormalizer, RetryPolicy, RunnableOutputBehaviorResolver, WorkflowBuilder, chatModel, emitPorts, getOriginIndexFromItem, inject, injectable, isPortsEmission, node } from "@codemation/core";
2
- import { ChatOpenAI } from "@langchain/openai";
3
- import { AIMessage, HumanMessage, SystemMessage, ToolMessage } from "@langchain/core/messages";
4
- import { isInteropZodSchema } from "@langchain/core/utils/types";
5
- import { toJsonSchema } from "@langchain/core/utils/json_schema";
6
- import { DynamicStructuredTool } from "@langchain/core/tools";
1
+ import { AgentConfigInspector, AgentConnectionNodeCollector, AgentGuardrailDefaults, AgentMessageConfigNormalizer, CallableToolConfig, ChildExecutionScopeFactory, CodemationTelemetryAttributeNames, CodemationTelemetryMetricNames, ConnectionInvocationIdFactory, ConnectionNodeIdFactory, CoreTokens, DefinedNodeRegistry, GenAiTelemetryAttributeNames, ItemExprResolver, ItemsInputNormalizer, NodeBackedToolConfig, NodeOutputNormalizer, RetryPolicy, RunnableOutputBehaviorResolver, WorkflowBuilder, chatModel, defineCredential, defineNode, emitPorts, getOriginIndexFromItem, inject, injectable, isPortsEmission, node } from "@codemation/core";
2
+ import { createOpenAI } from "@ai-sdk/openai";
7
3
  import { CredentialResolverFactory } from "@codemation/core/bootstrap";
4
+ import { Output, generateText, jsonSchema } from "ai";
5
+ import { Cron } from "croner";
8
6
 
9
- //#region \0@oxc-project+runtime@0.95.0/helpers/decorate.js
10
- function __decorate(decorators, target, key, desc) {
11
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
12
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
13
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
14
- return c > 3 && r && Object.defineProperty(target, key, r), r;
15
- }
7
+ //#region src/credentials/ApiKeyCredentialType.ts
8
+ /**
9
+ * API key credential that injects a key either as an HTTP header or a query parameter.
10
+ */
11
+ const apiKeyCredentialType = defineCredential({
12
+ key: "core-nodes.api-key",
13
+ label: "API Key",
14
+ description: "Authenticates requests by injecting an API key into a header or query parameter.",
15
+ public: {
16
+ placement: {
17
+ label: "Placement",
18
+ type: "string",
19
+ helpText: "Where to send the key: \"header\" (default) or \"query\".",
20
+ placeholder: "header"
21
+ },
22
+ name: {
23
+ label: "Parameter name",
24
+ type: "string",
25
+ helpText: "Header or query param name. Defaults to \"X-API-Key\" for headers, \"api_key\" for query.",
26
+ placeholder: "X-API-Key"
27
+ }
28
+ },
29
+ secret: { apiKey: {
30
+ label: "API Key",
31
+ type: "password",
32
+ required: true,
33
+ helpText: "The secret API key value."
34
+ } },
35
+ async createSession(args) {
36
+ const apiKey = String(args.material.apiKey ?? "");
37
+ if (!apiKey) throw new Error("API key credential material is incomplete: apiKey is required.");
38
+ const isQuery = String(args.publicConfig.placement ?? "header").toLowerCase() === "query";
39
+ const defaultName = isQuery ? "api_key" : "X-API-Key";
40
+ const paramName = String(args.publicConfig.name ?? "").trim() || defaultName;
41
+ return { applyToRequest: (_spec) => {
42
+ if (isQuery) return { query: { [paramName]: apiKey } };
43
+ return { headers: { [paramName]: apiKey } };
44
+ } };
45
+ },
46
+ async test(args) {
47
+ const apiKey = String(args.material.apiKey ?? "");
48
+ return {
49
+ status: apiKey.length > 0 ? "healthy" : "failing",
50
+ message: apiKey.length > 0 ? "API key is configured." : "API key is missing.",
51
+ testedAt: (/* @__PURE__ */ new Date()).toISOString()
52
+ };
53
+ }
54
+ });
16
55
 
17
56
  //#endregion
18
- //#region src/chatModels/OpenAIChatModelFactory.ts
19
- let OpenAIChatModelFactory = class OpenAIChatModelFactory$1 {
57
+ //#region src/credentials/BasicAuthCredentialType.ts
58
+ /**
59
+ * HTTP Basic authentication credential.
60
+ * Session sets `Authorization: Basic <base64(username:password)>`.
61
+ */
62
+ const basicAuthCredentialType = defineCredential({
63
+ key: "core-nodes.basic-auth",
64
+ label: "Basic Auth",
65
+ description: "Authenticates requests using HTTP Basic Authentication (username + password).",
66
+ public: { username: {
67
+ label: "Username",
68
+ type: "string",
69
+ required: true,
70
+ helpText: "The username for HTTP Basic Authentication."
71
+ } },
72
+ secret: { password: {
73
+ label: "Password",
74
+ type: "password",
75
+ required: true,
76
+ helpText: "The password for HTTP Basic Authentication."
77
+ } },
78
+ async createSession(args) {
79
+ const username = String(args.publicConfig.username ?? "");
80
+ const password = String(args.material.password ?? "");
81
+ if (!username) throw new Error("Basic Auth credential is incomplete: username is required.");
82
+ const encoded = Buffer.from(`${username}:${password}`).toString("base64");
83
+ return { applyToRequest: (_spec) => ({ headers: { authorization: `Basic ${encoded}` } }) };
84
+ },
85
+ async test(args) {
86
+ const username = String(args.publicConfig.username ?? "");
87
+ const password = String(args.material.password ?? "");
88
+ const ok = username.length > 0 && password.length > 0;
89
+ return {
90
+ status: ok ? "healthy" : "failing",
91
+ message: ok ? "Basic Auth credentials are configured." : "Username or password is missing.",
92
+ testedAt: (/* @__PURE__ */ new Date()).toISOString()
93
+ };
94
+ }
95
+ });
96
+
97
+ //#endregion
98
+ //#region src/credentials/BearerTokenCredentialType.ts
99
+ /**
100
+ * Simple Bearer token credential.
101
+ * Session sets `Authorization: Bearer <token>` on every request.
102
+ */
103
+ const bearerTokenCredentialType = defineCredential({
104
+ key: "core-nodes.bearer-token",
105
+ label: "Bearer Token",
106
+ description: "Authenticates requests using a static Bearer token in the Authorization header.",
107
+ public: {},
108
+ secret: { token: {
109
+ label: "Token",
110
+ type: "password",
111
+ required: true,
112
+ helpText: "The Bearer token to include in the Authorization header."
113
+ } },
114
+ async createSession(args) {
115
+ const token = String(args.material.token ?? "");
116
+ if (!token) throw new Error("Bearer token credential material is incomplete: token is required.");
117
+ return { applyToRequest: (_spec) => ({ headers: { authorization: `Bearer ${token}` } }) };
118
+ },
119
+ async test(args) {
120
+ const token = String(args.material.token ?? "");
121
+ return {
122
+ status: token.length > 0 ? "healthy" : "failing",
123
+ message: token.length > 0 ? "Bearer token is configured." : "Token is missing.",
124
+ testedAt: (/* @__PURE__ */ new Date()).toISOString()
125
+ };
126
+ }
127
+ });
128
+
129
+ //#endregion
130
+ //#region src/credentials/OAuth2TokenExchangeFactory.ts
131
+ var OAuth2TokenExchangeFactory = class {
20
132
  async create(args) {
21
- const session = await args.ctx.getCredential(args.config.credentialSlotKey);
22
- return new ChatOpenAI({
23
- apiKey: session.apiKey,
24
- model: args.config.model,
25
- temperature: args.config.options?.temperature,
26
- maxTokens: args.config.options?.maxTokens,
27
- configuration: session.baseUrl ? { baseURL: session.baseUrl } : void 0
133
+ const body = new URLSearchParams({
134
+ grant_type: "client_credentials",
135
+ client_id: args.clientId
28
136
  });
137
+ if (args.scopes) body.set("scope", args.scopes);
138
+ if (args.audience) body.set("audience", args.audience);
139
+ const encoded = Buffer.from(`${args.clientId}:${args.clientSecret}`).toString("base64");
140
+ const response = await globalThis.fetch(args.tokenUrl, {
141
+ method: "POST",
142
+ headers: {
143
+ "content-type": "application/x-www-form-urlencoded",
144
+ authorization: `Basic ${encoded}`
145
+ },
146
+ body: body.toString()
147
+ });
148
+ if (!response.ok) {
149
+ const text = await response.text().catch(() => "");
150
+ throw new Error(`Token exchange failed (${response.status} ${response.statusText}): ${text}`);
151
+ }
152
+ const json = await response.json();
153
+ const token = String(json["access_token"] ?? "");
154
+ if (!token) throw new Error("Token exchange response did not include an access_token.");
155
+ return token;
29
156
  }
30
157
  };
31
- OpenAIChatModelFactory = __decorate([chatModel({ packageName: "@codemation/core-nodes" })], OpenAIChatModelFactory);
32
158
 
33
159
  //#endregion
34
- //#region src/chatModels/OpenAIStructuredOutputMethodFactory.ts
35
- var _OpenAIStructuredOutputMethodFactory;
36
- let OpenAIStructuredOutputMethodFactory = class OpenAIStructuredOutputMethodFactory$1 {
37
- static {
38
- _OpenAIStructuredOutputMethodFactory = this;
160
+ //#region src/credentials/OAuth2ClientCredentialsTypeFactory.ts
161
+ /**
162
+ * OAuth2 client-credentials flow credential.
163
+ *
164
+ * This is a machine-to-machine flow: no user redirect occurs. The session
165
+ * POSTs to the configured `tokenUrl` with `client_credentials` grant, caches
166
+ * the resulting access token for the duration of the session, and injects it
167
+ * as `Authorization: Bearer <token>` on each request.
168
+ *
169
+ * Token caching is per-session only (one createSession call = one token fetch
170
+ * at most). Cross-session caching would require host-level state and is out of
171
+ * scope here. Because the engine creates a fresh session per execution, a new
172
+ * token is fetched once per node activation.
173
+ *
174
+ * NOTE: `auth` is intentionally omitted from the definition. The OAuth2
175
+ * `auth: { kind: "oauth2" }` shape signals an authorization-code / user-redirect
176
+ * flow; using it here would cause the host UI to render an OAuth consent button
177
+ * that goes nowhere. Client-credentials is a purely server-side flow.
178
+ */
179
+ const oauth2ClientCredentialsType = defineCredential({
180
+ key: "core-nodes.oauth2-client-credentials",
181
+ label: "OAuth2 Client Credentials",
182
+ description: "Machine-to-machine OAuth2 using the client_credentials grant. Exchanges client ID and secret for a bearer token before each workflow execution.",
183
+ public: {
184
+ tokenUrl: {
185
+ label: "Token URL",
186
+ type: "string",
187
+ required: true,
188
+ helpText: "The token endpoint URL, e.g. https://auth.example.com/oauth/token."
189
+ },
190
+ scopes: {
191
+ label: "Scopes",
192
+ type: "string",
193
+ helpText: "Space-separated list of OAuth2 scopes to request (optional)."
194
+ },
195
+ audience: {
196
+ label: "Audience",
197
+ type: "string",
198
+ helpText: "Optional audience parameter sent to the token endpoint.",
199
+ visibility: "advanced"
200
+ }
201
+ },
202
+ secret: {
203
+ clientId: {
204
+ label: "Client ID",
205
+ type: "string",
206
+ required: true
207
+ },
208
+ clientSecret: {
209
+ label: "Client Secret",
210
+ type: "password",
211
+ required: true
212
+ }
213
+ },
214
+ async createSession(args) {
215
+ const tokenUrl = String(args.publicConfig.tokenUrl ?? "");
216
+ const clientId = String(args.material.clientId ?? "");
217
+ const clientSecret = String(args.material.clientSecret ?? "");
218
+ if (!tokenUrl || !clientId || !clientSecret) throw new Error("OAuth2 client credentials are incomplete: tokenUrl, clientId, and clientSecret are required.");
219
+ const accessToken = await new OAuth2TokenExchangeFactory().create({
220
+ tokenUrl,
221
+ clientId,
222
+ clientSecret,
223
+ scopes: String(args.publicConfig.scopes ?? ""),
224
+ audience: String(args.publicConfig.audience ?? "")
225
+ });
226
+ return { applyToRequest: (_spec) => ({ headers: { authorization: `Bearer ${accessToken}` } }) };
227
+ },
228
+ async test(args) {
229
+ const tokenUrl = String(args.publicConfig.tokenUrl ?? "");
230
+ const clientId = String(args.material.clientId ?? "");
231
+ const clientSecret = String(args.material.clientSecret ?? "");
232
+ if (!tokenUrl || !clientId || !clientSecret) return {
233
+ status: "failing",
234
+ message: "tokenUrl, clientId, and clientSecret are all required.",
235
+ testedAt: (/* @__PURE__ */ new Date()).toISOString()
236
+ };
237
+ try {
238
+ await new OAuth2TokenExchangeFactory().create({
239
+ tokenUrl,
240
+ clientId,
241
+ clientSecret,
242
+ scopes: String(args.publicConfig.scopes ?? ""),
243
+ audience: String(args.publicConfig.audience ?? "")
244
+ });
245
+ return {
246
+ status: "healthy",
247
+ message: "Token exchange succeeded.",
248
+ testedAt: (/* @__PURE__ */ new Date()).toISOString()
249
+ };
250
+ } catch (error) {
251
+ return {
252
+ status: "failing",
253
+ message: error instanceof Error ? error.message : String(error),
254
+ testedAt: (/* @__PURE__ */ new Date()).toISOString()
255
+ };
256
+ }
39
257
  }
40
- static isoDatePattern = /^\d{4}-\d{2}-\d{2}$/;
41
- create(chatModelConfig) {
42
- if (chatModelConfig.type !== OpenAIChatModelFactory) return;
43
- const model = this.readModelName(chatModelConfig);
44
- if (!model) return {
45
- method: "functionCalling",
46
- strict: true
258
+ });
259
+
260
+ //#endregion
261
+ //#region src/http/HttpRequestExecutor.ts
262
+ /**
263
+ * Executes a single HTTP request described by {@link HttpRequestSpec}.
264
+ *
265
+ * - Credential sessions provide header/query deltas via `applyToRequest`.
266
+ * - Body encoding is delegated to {@link HttpBodyBuilder}.
267
+ * - URL query merging is delegated to {@link HttpUrlBuilder}.
268
+ * - Binary response bodies: when `download.mode` triggers binary attach, the
269
+ * `bodyBinaryName` field is set in the result but the body is NOT read here.
270
+ * Callers that need binary attachment should use `buildRequest` to get the
271
+ * resolved URL + init and make the fetch + binary attach themselves.
272
+ *
273
+ * Collaborators (`fetch`, body builder, url builder) are injected so callers
274
+ * own construction at composition roots and tests can supply deterministic stubs.
275
+ */
276
+ var HttpRequestExecutor = class {
277
+ constructor(fetchFn, bodyBuilder, urlBuilder) {
278
+ this.fetchFn = fetchFn;
279
+ this.bodyBuilder = bodyBuilder;
280
+ this.urlBuilder = urlBuilder;
281
+ }
282
+ /**
283
+ * Builds the fetch init (headers, query, body) from the spec + credential delta,
284
+ * returning both the resolved URL and the RequestInit so callers can make the
285
+ * actual fetch call themselves (useful for streaming / binary attach).
286
+ */
287
+ async buildRequest(spec, item) {
288
+ const credentialDelta = spec.credential?.applyToRequest(spec) ?? {};
289
+ const mergedHeaders = {
290
+ ...spec.headers ?? {},
291
+ ...credentialDelta.headers ?? {}
292
+ };
293
+ const mergedQuery = {
294
+ ...spec.query ?? {},
295
+ ...credentialDelta.query ?? {}
47
296
  };
297
+ const encodedBody = await this.bodyBuilder.build(spec.body, item, spec.ctx);
298
+ const hasExplicitContentType = Object.keys(mergedHeaders).some((k) => k.toLowerCase() === "content-type");
299
+ if (encodedBody && encodedBody.contentType && !hasExplicitContentType) mergedHeaders["content-type"] = encodedBody.contentType;
300
+ return {
301
+ url: this.urlBuilder.build(spec.url, mergedQuery),
302
+ init: {
303
+ method: spec.method,
304
+ headers: mergedHeaders,
305
+ ...encodedBody ? { body: encodedBody.body } : {}
306
+ }
307
+ };
308
+ }
309
+ /**
310
+ * Executes an HTTP request and returns parsed result.
311
+ * For binary downloads (when `shouldAttachBody` is true), the body is NOT consumed
312
+ * and callers must call `ctx.binary.attach` directly using the resolved URL + init
313
+ * (available via `buildRequest`).
314
+ */
315
+ async execute(spec, item) {
316
+ const { url: resolvedUrl, init } = await this.buildRequest(spec, item);
317
+ const response = await this.fetchFn(resolvedUrl, init);
318
+ const responseHeaders = this.readHeaders(response.headers);
319
+ const mimeType = this.resolveMimeType(responseHeaders);
320
+ const downloadMode = spec.download?.mode ?? "auto";
321
+ const binaryName = spec.download?.binaryName ?? "body";
322
+ const shouldDownload = this.shouldAttachBody(downloadMode, mimeType);
323
+ const isJson = this.isJsonMimeType(mimeType);
324
+ let json;
325
+ let text;
326
+ let bodyBinaryName;
327
+ if (shouldDownload) bodyBinaryName = binaryName;
328
+ else if (isJson) try {
329
+ json = await response.json();
330
+ } catch {
331
+ text = await response.text();
332
+ }
333
+ else text = await response.text();
48
334
  return {
49
- method: this.supportsJsonSchema(model) ? "jsonSchema" : "functionCalling",
50
- strict: true
335
+ url: resolvedUrl,
336
+ method: spec.method.toUpperCase(),
337
+ status: response.status,
338
+ ok: response.ok,
339
+ statusText: response.statusText,
340
+ mimeType,
341
+ headers: responseHeaders,
342
+ ...json !== void 0 ? { json } : {},
343
+ ...text !== void 0 ? { text } : {},
344
+ ...bodyBinaryName !== void 0 ? { bodyBinaryName } : {}
51
345
  };
52
346
  }
53
- readModelName(chatModelConfig) {
54
- const candidate = chatModelConfig;
55
- return typeof candidate.model === "string" ? candidate.model : void 0;
347
+ readHeaders(headers) {
348
+ const values = {};
349
+ headers.forEach((value, key) => {
350
+ values[key] = value;
351
+ });
352
+ return values;
353
+ }
354
+ resolveMimeType(headers) {
355
+ const contentType = headers["content-type"];
356
+ if (!contentType) return "application/octet-stream";
357
+ return contentType.split(";")[0]?.trim() || "application/octet-stream";
56
358
  }
57
- supportsJsonSchema(model) {
58
- if (model === "gpt-4o" || model === "gpt-4o-mini") return true;
59
- return this.supportsSnapshotAtOrAfter(model, "gpt-4o-", "2024-08-06") || this.supportsSnapshotAtOrAfter(model, "gpt-4o-mini-", "2024-07-18");
359
+ isJsonMimeType(mimeType) {
360
+ return mimeType === "application/json" || mimeType.endsWith("+json");
60
361
  }
61
- supportsSnapshotAtOrAfter(model, prefix, minimumSnapshotDate) {
62
- if (!model.startsWith(prefix)) return false;
63
- const snapshotDate = model.slice(prefix.length);
64
- return _OpenAIStructuredOutputMethodFactory.isoDatePattern.test(snapshotDate) && snapshotDate >= minimumSnapshotDate;
362
+ shouldAttachBody(mode, mimeType) {
363
+ if (mode === "always") return true;
364
+ if (mode === "never") return false;
365
+ return mimeType.startsWith("image/") || mimeType.startsWith("audio/") || mimeType.startsWith("video/") || mimeType === "application/pdf";
65
366
  }
66
367
  };
67
- OpenAIStructuredOutputMethodFactory = _OpenAIStructuredOutputMethodFactory = __decorate([injectable()], OpenAIStructuredOutputMethodFactory);
68
368
 
69
369
  //#endregion
70
- //#region src/chatModels/openAiChatModelConfig.ts
71
- var OpenAIChatModelConfig = class {
72
- type = OpenAIChatModelFactory;
73
- presentation;
74
- provider = "openai";
75
- modelName;
76
- constructor(name, model, credentialSlotKey = "openai", presentationIn, options) {
77
- this.name = name;
78
- this.model = model;
79
- this.credentialSlotKey = credentialSlotKey;
80
- this.options = options;
81
- this.modelName = model;
82
- this.presentation = presentationIn ?? {
83
- icon: "builtin:openai",
84
- label: name
370
+ //#region src/http/HttpBodyBuilder.ts
371
+ /**
372
+ * Builds a fetch-compatible `BodyInit` + Content-Type pair from an {@link HttpBodySpec}.
373
+ * Multipart binaries are read from `item.binary` via `ctx.binary.openReadStream`.
374
+ */
375
+ var HttpBodyBuilder = class {
376
+ async build(spec, item, ctx) {
377
+ if (!spec || spec.kind === "none") return;
378
+ if (spec.kind === "json") return {
379
+ body: JSON.stringify(spec.data),
380
+ contentType: "application/json"
85
381
  };
382
+ if (spec.kind === "form") {
383
+ const params = new URLSearchParams();
384
+ for (const [key, value] of Object.entries(spec.data)) params.append(key, value);
385
+ return {
386
+ body: params.toString(),
387
+ contentType: "application/x-www-form-urlencoded"
388
+ };
389
+ }
390
+ if (spec.kind === "multipart") {
391
+ const formData = new FormData();
392
+ for (const [key, value] of Object.entries(spec.fields)) formData.append(key, value);
393
+ if (spec.binaries) for (const [fieldName, binaryRef] of Object.entries(spec.binaries)) {
394
+ const attachment = item.binary?.[binaryRef];
395
+ if (attachment) {
396
+ const readResult = await ctx.binary.openReadStream(attachment);
397
+ if (readResult) {
398
+ const merged = await this.readStreamToBuffer(readResult.body);
399
+ const blob = new Blob([merged], { type: attachment.mimeType });
400
+ formData.append(fieldName, blob, attachment.filename ?? binaryRef);
401
+ }
402
+ }
403
+ }
404
+ return {
405
+ body: formData,
406
+ contentType: ""
407
+ };
408
+ }
409
+ if (spec.kind === "binary") {
410
+ const attachment = item.binary?.[spec.slot];
411
+ if (!attachment) throw new Error(`HttpRequest bodyFormat "binary": no binary attachment found at slot "${spec.slot}". Ensure a previous node attached binary data at that slot.`);
412
+ const readResult = await ctx.binary.openReadStream(attachment);
413
+ if (!readResult) throw new Error(`HttpRequest bodyFormat "binary": could not open read stream for slot "${spec.slot}".`);
414
+ return {
415
+ body: readResult.body,
416
+ contentType: attachment.mimeType
417
+ };
418
+ }
86
419
  }
87
- getCredentialRequirements() {
88
- return [{
89
- slotKey: this.credentialSlotKey,
90
- label: "OpenAI API key",
91
- acceptedTypes: ["openai.apiKey"]
92
- }];
420
+ async readStreamToBuffer(stream) {
421
+ const reader = stream.getReader();
422
+ const chunks = [];
423
+ let done = false;
424
+ while (!done) {
425
+ const result = await reader.read();
426
+ done = result.done;
427
+ if (result.value) chunks.push(result.value);
428
+ }
429
+ const totalLength = chunks.reduce((acc, chunk) => acc + chunk.length, 0);
430
+ const merged = new Uint8Array(new ArrayBuffer(totalLength));
431
+ let offset = 0;
432
+ for (const chunk of chunks) {
433
+ merged.set(chunk, offset);
434
+ offset += chunk.length;
435
+ }
436
+ return merged;
93
437
  }
94
438
  };
95
439
 
96
440
  //#endregion
97
- //#region src/chatModels/OpenAiChatModelPresetsFactory.ts
441
+ //#region src/http/HttpUrlBuilder.ts
98
442
  /**
99
- * Default OpenAI chat model configs for scaffolds and demos (icon + label match {@link OpenAIChatModelConfig} defaults).
100
- * Prefer importing {@link openAiChatModelPresets} from here or from the consumer template re-export
101
- * instead of repeating {@link OpenAIChatModelConfig} construction in app workflows.
443
+ * Merges query parameters into a base URL.
444
+ * Handles both scalar and array values, and preserves any existing params.
102
445
  */
103
- var OpenAiChatModelPresets = class {
104
- demoGpt4oMini = new OpenAIChatModelConfig("OpenAI", "gpt-4o-mini");
105
- demoGpt41 = new OpenAIChatModelConfig("OpenAI", "gpt-4.1");
446
+ var HttpUrlBuilder = class {
447
+ build(baseUrl, query) {
448
+ if (!query || Object.keys(query).length === 0) return baseUrl;
449
+ const parsed = new URL(baseUrl);
450
+ for (const [key, value] of Object.entries(query)) if (Array.isArray(value)) for (const entry of value) parsed.searchParams.append(key, entry);
451
+ else parsed.searchParams.append(key, value);
452
+ return parsed.toString();
453
+ }
106
454
  };
107
- const openAiChatModelPresets = new OpenAiChatModelPresets();
108
455
 
109
456
  //#endregion
110
- //#region src/nodes/AgentMessageFactory.ts
111
- var AgentMessageFactory = class {
112
- static createPromptMessages(messages) {
113
- return messages.map((message) => this.createPromptMessage(message));
114
- }
115
- static createSystemPrompt(systemMessage) {
116
- return new SystemMessage(systemMessage);
117
- }
118
- static createUserPrompt(prompt) {
119
- return new HumanMessage(prompt);
120
- }
121
- static createAssistantPrompt(prompt) {
122
- return new AIMessage(prompt);
123
- }
124
- static createToolMessage(toolCallId, content) {
125
- return new ToolMessage({
126
- tool_call_id: toolCallId,
127
- content
128
- });
129
- }
130
- static extractContent(message) {
131
- if (typeof message === "string") return message;
132
- if (!this.isRecord(message)) return String(message);
133
- const content = message.content;
134
- if (typeof content === "string") return content;
135
- if (Array.isArray(content)) return content.map((part) => {
136
- if (typeof part === "string") return part;
137
- if (this.isRecord(part) && typeof part.text === "string") return part.text;
138
- return JSON.stringify(part);
139
- }).join("\n");
140
- return JSON.stringify(content);
141
- }
142
- static extractToolCalls(message) {
143
- if (!this.isRecord(message)) return [];
144
- const toolCalls = message.tool_calls;
145
- if (!Array.isArray(toolCalls)) return [];
146
- return toolCalls.filter((toolCall) => this.isRecord(toolCall) && typeof toolCall.name === "string").map((toolCall) => ({
147
- id: typeof toolCall.id === "string" ? toolCall.id : void 0,
148
- name: toolCall.name,
149
- input: this.isRecord(toolCall) && "args" in toolCall ? toolCall.args : void 0
150
- }));
151
- }
152
- static isRecord(value) {
153
- return typeof value === "object" && value !== null;
154
- }
155
- static createPromptMessage(message) {
156
- if (message.role === "system") return this.createSystemPrompt(message.content);
157
- if (message.role === "assistant") return this.createAssistantPrompt(message.content);
158
- return this.createUserPrompt(message.content);
159
- }
160
- };
457
+ //#region src/authoring/defineRestNode.types.ts
458
+ /**
459
+ * Substitutes `{name}` placeholders in a path template using values from `params`.
460
+ */
461
+ function substitutePath(template, params) {
462
+ return template.replace(/\{([^}]+)}/g, (_match, key) => {
463
+ const value = params[key];
464
+ return value !== void 0 ? String(value) : `{${key}}`;
465
+ });
466
+ }
467
+ /**
468
+ * Declarative helper for creating thin API-wrapper nodes.
469
+ *
470
+ * Usage:
471
+ * ```ts
472
+ * export const postMessage = defineRestNode({
473
+ * key: "slack.post-message",
474
+ * title: "Send Slack message",
475
+ * icon: "si:slack",
476
+ * api: { baseUrl: "https://slack.com/api", path: "/chat.postMessage", method: "POST" },
477
+ * credentials: { auth: bearerTokenCredentialType },
478
+ * inputSchema: z.object({ channel: z.string(), text: z.string() }),
479
+ * request: ({ input }) => ({
480
+ * body: { kind: "json", data: { channel: input.channel, text: input.text } },
481
+ * }),
482
+ * response: ({ json }) => ({ messageTs: (json as any).ts }),
483
+ * });
484
+ * ```
485
+ *
486
+ * - `defineRestNode` is a thin wrapper over `defineNode`; it does not introduce a new runtime kind.
487
+ * - Credential sessions are resolved via the `credentials` binding map (same as `defineNode`).
488
+ * - Path `{placeholder}` substitution is applied from `input` keys before the request is made.
489
+ * - Non-2xx responses throw an `Error` by default (`errorPolicy: "throw"`).
490
+ */
491
+ function defineRestNode(options) {
492
+ const errorPolicy = options.errorPolicy ?? "throw";
493
+ return defineNode({
494
+ key: options.key,
495
+ title: options.title,
496
+ description: options.description,
497
+ icon: options.icon,
498
+ credentials: options.credentials,
499
+ inputSchema: options.inputSchema,
500
+ async execute({ input, item, ctx }, { credentials }) {
501
+ const credentialSlot = options.credentials ? Object.keys(options.credentials)[0] : void 0;
502
+ const credential = credentialSlot ? await credentials[credentialSlot]?.() : void 0;
503
+ const inputRecord = input ?? {};
504
+ const requestShape = options.request ? await options.request({ input }) : {};
505
+ const pathParams = {
506
+ ...inputRecord,
507
+ ...requestShape.pathParams ?? {}
508
+ };
509
+ const resolvedPath = substitutePath(options.api.path, pathParams);
510
+ const resolvedUrl = `${options.api.baseUrl}${resolvedPath}`;
511
+ const result = await new HttpRequestExecutor(globalThis.fetch, new HttpBodyBuilder(), new HttpUrlBuilder()).execute({
512
+ url: resolvedUrl,
513
+ method: (options.api.method ?? "GET").toUpperCase(),
514
+ headers: requestShape.headers,
515
+ query: requestShape.query,
516
+ body: requestShape.body,
517
+ credential,
518
+ ctx
519
+ }, item);
520
+ if (errorPolicy === "throw" && !result.ok) throw new Error(`HTTP ${result.status} ${result.statusText} for ${result.method} ${result.url}`);
521
+ const responseCtx = {
522
+ status: result.status,
523
+ ok: result.ok,
524
+ statusText: result.statusText,
525
+ mimeType: result.mimeType,
526
+ headers: result.headers,
527
+ ...result.json !== void 0 ? { json: result.json } : {},
528
+ ...result.text !== void 0 ? { text: result.text } : {}
529
+ };
530
+ if (options.response) return await options.response({
531
+ ...responseCtx,
532
+ input
533
+ });
534
+ return { json: responseCtx };
535
+ }
536
+ });
537
+ }
161
538
 
162
539
  //#endregion
163
- //#region src/nodes/AgentOutputFactory.ts
164
- var AgentOutputFactory = class {
165
- static fromUnknown(value) {
166
- return { main: [{ json: value }] };
167
- }
168
- static replaceJson(item, value) {
540
+ //#region \0@oxc-project+runtime@0.95.0/helpers/decorate.js
541
+ function __decorate(decorators, target, key, desc) {
542
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
543
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
544
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
545
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
546
+ }
547
+
548
+ //#endregion
549
+ //#region src/chatModels/OpenAIChatModelFactory.ts
550
+ let OpenAIChatModelFactory = class OpenAIChatModelFactory$1 {
551
+ async create(args) {
552
+ const session = await args.ctx.getCredential(args.config.credentialSlotKey);
169
553
  return {
170
- ...item,
171
- json: value
554
+ languageModel: createOpenAI({
555
+ apiKey: session.apiKey,
556
+ baseURL: session.baseUrl
557
+ }).chat(args.config.model),
558
+ modelName: args.config.model,
559
+ provider: "openai",
560
+ defaultCallOptions: {
561
+ maxOutputTokens: args.config.options?.maxTokens,
562
+ temperature: args.config.options?.temperature
563
+ }
172
564
  };
173
565
  }
174
- static fromAgentContent(content) {
175
- try {
176
- return JSON.parse(content);
177
- } catch {
178
- return { output: content };
179
- }
180
- }
181
566
  };
567
+ OpenAIChatModelFactory = __decorate([chatModel({ packageName: "@codemation/core-nodes" })], OpenAIChatModelFactory);
182
568
 
183
569
  //#endregion
184
570
  //#region ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/core.js
@@ -269,10 +655,21 @@ function cleanRegex(source) {
269
655
  const end = source.endsWith("$") ? source.length - 1 : source.length;
270
656
  return source.slice(start, end);
271
657
  }
658
+ function floatSafeRemainder(val, step) {
659
+ const valDecCount = (val.toString().split(".")[1] || "").length;
660
+ const stepString = step.toString();
661
+ let stepDecCount = (stepString.split(".")[1] || "").length;
662
+ if (stepDecCount === 0 && /\d?e-\d?/.test(stepString)) {
663
+ const match = stepString.match(/\d?e-(\d?)/);
664
+ if (match?.[1]) stepDecCount = Number.parseInt(match[1]);
665
+ }
666
+ const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
667
+ return Number.parseInt(val.toFixed(decCount).replace(".", "")) % Number.parseInt(step.toFixed(decCount).replace(".", "")) / 10 ** decCount;
668
+ }
272
669
  const EVALUATING = Symbol("evaluating");
273
- function defineLazy(object, key, getter) {
670
+ function defineLazy(object$1, key, getter) {
274
671
  let value = void 0;
275
- Object.defineProperty(object, key, {
672
+ Object.defineProperty(object$1, key, {
276
673
  get() {
277
674
  if (value === EVALUATING) return;
278
675
  if (value === void 0) {
@@ -282,11 +679,19 @@ function defineLazy(object, key, getter) {
282
679
  return value;
283
680
  },
284
681
  set(v) {
285
- Object.defineProperty(object, key, { value: v });
682
+ Object.defineProperty(object$1, key, { value: v });
286
683
  },
287
684
  configurable: true
288
685
  });
289
686
  }
687
+ function assignProp(target, prop, value) {
688
+ Object.defineProperty(target, prop, {
689
+ value,
690
+ writable: true,
691
+ enumerable: true,
692
+ configurable: true
693
+ });
694
+ }
290
695
  function mergeDefs(...defs) {
291
696
  const mergedDescriptors = {};
292
697
  for (const def of defs) {
@@ -295,6 +700,12 @@ function mergeDefs(...defs) {
295
700
  }
296
701
  return Object.defineProperties({}, mergedDescriptors);
297
702
  }
703
+ function esc(str) {
704
+ return JSON.stringify(str);
705
+ }
706
+ function slugify(input) {
707
+ return input.toLowerCase().trim().replace(/[^\w\s-]/g, "").replace(/[\s_-]+/g, "-").replace(/^-+|-+$/g, "");
708
+ }
298
709
  const captureStackTrace = "captureStackTrace" in Error ? Error.captureStackTrace : (..._args) => {};
299
710
  function isObject(data) {
300
711
  return typeof data === "object" && data !== null && !Array.isArray(data);
@@ -323,6 +734,14 @@ function shallowClone(o) {
323
734
  if (Array.isArray(o)) return [...o];
324
735
  return o;
325
736
  }
737
+ const propertyKeyTypes = new Set([
738
+ "string",
739
+ "number",
740
+ "symbol"
741
+ ]);
742
+ function escapeRegex(str) {
743
+ return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
744
+ }
326
745
  function clone(inst, def, params) {
327
746
  const cl = new inst._zod.constr(def ?? inst._zod.def);
328
747
  if (!def || params?.parent) cl._zod.parent = inst;
@@ -343,6 +762,11 @@ function normalizeParams(_params) {
343
762
  };
344
763
  return params;
345
764
  }
765
+ function optionalKeys(shape) {
766
+ return Object.keys(shape).filter((k) => {
767
+ return shape[k]._zod.optin === "optional" && shape[k]._zod.optout === "optional";
768
+ });
769
+ }
346
770
  const NUMBER_FORMAT_RANGES = {
347
771
  safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER],
348
772
  int32: [-2147483648, 2147483647],
@@ -350,6 +774,130 @@ const NUMBER_FORMAT_RANGES = {
350
774
  float32: [-34028234663852886e22, 34028234663852886e22],
351
775
  float64: [-Number.MAX_VALUE, Number.MAX_VALUE]
352
776
  };
777
+ function pick(schema, mask) {
778
+ const currDef = schema._zod.def;
779
+ const checks = currDef.checks;
780
+ if (checks && checks.length > 0) throw new Error(".pick() cannot be used on object schemas containing refinements");
781
+ return clone(schema, mergeDefs(schema._zod.def, {
782
+ get shape() {
783
+ const newShape = {};
784
+ for (const key in mask) {
785
+ if (!(key in currDef.shape)) throw new Error(`Unrecognized key: "${key}"`);
786
+ if (!mask[key]) continue;
787
+ newShape[key] = currDef.shape[key];
788
+ }
789
+ assignProp(this, "shape", newShape);
790
+ return newShape;
791
+ },
792
+ checks: []
793
+ }));
794
+ }
795
+ function omit(schema, mask) {
796
+ const currDef = schema._zod.def;
797
+ const checks = currDef.checks;
798
+ if (checks && checks.length > 0) throw new Error(".omit() cannot be used on object schemas containing refinements");
799
+ return clone(schema, mergeDefs(schema._zod.def, {
800
+ get shape() {
801
+ const newShape = { ...schema._zod.def.shape };
802
+ for (const key in mask) {
803
+ if (!(key in currDef.shape)) throw new Error(`Unrecognized key: "${key}"`);
804
+ if (!mask[key]) continue;
805
+ delete newShape[key];
806
+ }
807
+ assignProp(this, "shape", newShape);
808
+ return newShape;
809
+ },
810
+ checks: []
811
+ }));
812
+ }
813
+ function extend(schema, shape) {
814
+ if (!isPlainObject(shape)) throw new Error("Invalid input to extend: expected a plain object");
815
+ const checks = schema._zod.def.checks;
816
+ if (checks && checks.length > 0) {
817
+ const existingShape = schema._zod.def.shape;
818
+ for (const key in shape) if (Object.getOwnPropertyDescriptor(existingShape, key) !== void 0) throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.");
819
+ }
820
+ return clone(schema, mergeDefs(schema._zod.def, { get shape() {
821
+ const _shape = {
822
+ ...schema._zod.def.shape,
823
+ ...shape
824
+ };
825
+ assignProp(this, "shape", _shape);
826
+ return _shape;
827
+ } }));
828
+ }
829
+ function safeExtend(schema, shape) {
830
+ if (!isPlainObject(shape)) throw new Error("Invalid input to safeExtend: expected a plain object");
831
+ return clone(schema, mergeDefs(schema._zod.def, { get shape() {
832
+ const _shape = {
833
+ ...schema._zod.def.shape,
834
+ ...shape
835
+ };
836
+ assignProp(this, "shape", _shape);
837
+ return _shape;
838
+ } }));
839
+ }
840
+ function merge(a, b) {
841
+ return clone(a, mergeDefs(a._zod.def, {
842
+ get shape() {
843
+ const _shape = {
844
+ ...a._zod.def.shape,
845
+ ...b._zod.def.shape
846
+ };
847
+ assignProp(this, "shape", _shape);
848
+ return _shape;
849
+ },
850
+ get catchall() {
851
+ return b._zod.def.catchall;
852
+ },
853
+ checks: []
854
+ }));
855
+ }
856
+ function partial(Class, schema, mask) {
857
+ const checks = schema._zod.def.checks;
858
+ if (checks && checks.length > 0) throw new Error(".partial() cannot be used on object schemas containing refinements");
859
+ return clone(schema, mergeDefs(schema._zod.def, {
860
+ get shape() {
861
+ const oldShape = schema._zod.def.shape;
862
+ const shape = { ...oldShape };
863
+ if (mask) for (const key in mask) {
864
+ if (!(key in oldShape)) throw new Error(`Unrecognized key: "${key}"`);
865
+ if (!mask[key]) continue;
866
+ shape[key] = Class ? new Class({
867
+ type: "optional",
868
+ innerType: oldShape[key]
869
+ }) : oldShape[key];
870
+ }
871
+ else for (const key in oldShape) shape[key] = Class ? new Class({
872
+ type: "optional",
873
+ innerType: oldShape[key]
874
+ }) : oldShape[key];
875
+ assignProp(this, "shape", shape);
876
+ return shape;
877
+ },
878
+ checks: []
879
+ }));
880
+ }
881
+ function required(Class, schema, mask) {
882
+ return clone(schema, mergeDefs(schema._zod.def, { get shape() {
883
+ const oldShape = schema._zod.def.shape;
884
+ const shape = { ...oldShape };
885
+ if (mask) for (const key in mask) {
886
+ if (!(key in shape)) throw new Error(`Unrecognized key: "${key}"`);
887
+ if (!mask[key]) continue;
888
+ shape[key] = new Class({
889
+ type: "nonoptional",
890
+ innerType: oldShape[key]
891
+ });
892
+ }
893
+ else for (const key in oldShape) shape[key] = new Class({
894
+ type: "nonoptional",
895
+ innerType: oldShape[key]
896
+ });
897
+ assignProp(this, "shape", shape);
898
+ return shape;
899
+ } }));
900
+ }
353
901
  function aborted(x, startIndex = 0) {
354
902
  if (x.aborted === true) return true;
355
903
  for (let i = startIndex; i < x.issues.length; i++) if (x.issues[i]?.continue !== true) return true;
@@ -555,6 +1103,64 @@ const _safeDecodeAsync = (_Err) => async (schema, value, _ctx) => {
555
1103
  };
556
1104
  const safeDecodeAsync$1 = /* @__PURE__ */ _safeDecodeAsync($ZodRealError);
557
1105
 
1106
+ //#endregion
1107
+ //#region ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/regexes.js
1108
+ const cuid = /^[cC][^\s-]{8,}$/;
1109
+ const cuid2 = /^[0-9a-z]+$/;
1110
+ const ulid = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/;
1111
+ const xid = /^[0-9a-vA-V]{20}$/;
1112
+ const ksuid = /^[A-Za-z0-9]{27}$/;
1113
+ const nanoid = /^[a-zA-Z0-9_-]{21}$/;
1114
+ /** ISO 8601-1 duration regex. Does not support the 8601-2 extensions like negative durations or fractional/negative components. */
1115
+ const duration$1 = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;
1116
+ /** A regex for any UUID-like identifier: 8-4-4-4-12 hex pattern */
1117
+ const guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/;
1118
+ /** Returns a regex for validating an RFC 9562/4122 UUID.
1119
+ *
1120
+ * @param version Optionally specify a version 1-8. If no version is specified, all versions are supported. */
1121
+ const uuid = (version$1) => {
1122
+ if (!version$1) return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;
1123
+ return /* @__PURE__ */ new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version$1}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`);
1124
+ };
1125
+ /** Practical email validation */
1126
+ const email = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;
1127
+ const _emoji$1 = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
1128
+ function emoji() {
1129
+ return new RegExp(_emoji$1, "u");
1130
+ }
1131
+ const ipv4 = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;
1132
+ const ipv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/;
1133
+ const cidrv4 = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/;
1134
+ const cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;
1135
+ const base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/;
1136
+ const base64url = /^[A-Za-z0-9_-]*$/;
1137
+ const e164 = /^\+[1-9]\d{6,14}$/;
1138
+ const dateSource = `(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`;
1139
+ const date$1 = /* @__PURE__ */ new RegExp(`^${dateSource}$`);
1140
+ function timeSource(args) {
1141
+ const hhmm = `(?:[01]\\d|2[0-3]):[0-5]\\d`;
1142
+ return typeof args.precision === "number" ? args.precision === -1 ? `${hhmm}` : args.precision === 0 ? `${hhmm}:[0-5]\\d` : `${hhmm}:[0-5]\\d\\.\\d{${args.precision}}` : `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`;
1143
+ }
1144
+ function time$1(args) {
1145
+ return /* @__PURE__ */ new RegExp(`^${timeSource(args)}$`);
1146
+ }
1147
+ function datetime$1(args) {
1148
+ const time$2 = timeSource({ precision: args.precision });
1149
+ const opts = ["Z"];
1150
+ if (args.local) opts.push("");
1151
+ if (args.offset) opts.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`);
1152
+ const timeRegex = `${time$2}(?:${opts.join("|")})`;
1153
+ return /* @__PURE__ */ new RegExp(`^${dateSource}T(?:${timeRegex})$`);
1154
+ }
1155
+ const string$1 = (params) => {
1156
+ const regex = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`;
1157
+ return /* @__PURE__ */ new RegExp(`^${regex}$`);
1158
+ };
1159
+ const integer = /^-?\d+$/;
1160
+ const number$1 = /^-?\d+(?:\.\d+)?$/;
1161
+ const lowercase = /^[^A-Z]*$/;
1162
+ const uppercase = /^[^a-z]*$/;
1163
+
558
1164
  //#endregion
559
1165
  //#region ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/checks.js
560
1166
  const $ZodCheck = /* @__PURE__ */ $constructor("$ZodCheck", (inst, def) => {
@@ -563,25 +1169,164 @@ const $ZodCheck = /* @__PURE__ */ $constructor("$ZodCheck", (inst, def) => {
563
1169
  inst._zod.def = def;
564
1170
  (_a$1 = inst._zod).onattach ?? (_a$1.onattach = []);
565
1171
  });
566
- const $ZodCheckMaxLength = /* @__PURE__ */ $constructor("$ZodCheckMaxLength", (inst, def) => {
567
- var _a$1;
1172
+ const numericOriginMap = {
1173
+ number: "number",
1174
+ bigint: "bigint",
1175
+ object: "date"
1176
+ };
1177
+ const $ZodCheckLessThan = /* @__PURE__ */ $constructor("$ZodCheckLessThan", (inst, def) => {
568
1178
  $ZodCheck.init(inst, def);
569
- (_a$1 = inst._zod.def).when ?? (_a$1.when = (payload) => {
570
- const val = payload.value;
571
- return !nullish(val) && val.length !== void 0;
572
- });
1179
+ const origin = numericOriginMap[typeof def.value];
573
1180
  inst._zod.onattach.push((inst$1) => {
574
- const curr = inst$1._zod.bag.maximum ?? Number.POSITIVE_INFINITY;
575
- if (def.maximum < curr) inst$1._zod.bag.maximum = def.maximum;
1181
+ const bag = inst$1._zod.bag;
1182
+ const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY;
1183
+ if (def.value < curr) if (def.inclusive) bag.maximum = def.value;
1184
+ else bag.exclusiveMaximum = def.value;
576
1185
  });
577
1186
  inst._zod.check = (payload) => {
578
- const input = payload.value;
579
- if (input.length <= def.maximum) return;
580
- const origin = getLengthableOrigin(input);
1187
+ if (def.inclusive ? payload.value <= def.value : payload.value < def.value) return;
581
1188
  payload.issues.push({
582
1189
  origin,
583
1190
  code: "too_big",
584
- maximum: def.maximum,
1191
+ maximum: typeof def.value === "object" ? def.value.getTime() : def.value,
1192
+ input: payload.value,
1193
+ inclusive: def.inclusive,
1194
+ inst,
1195
+ continue: !def.abort
1196
+ });
1197
+ };
1198
+ });
1199
+ const $ZodCheckGreaterThan = /* @__PURE__ */ $constructor("$ZodCheckGreaterThan", (inst, def) => {
1200
+ $ZodCheck.init(inst, def);
1201
+ const origin = numericOriginMap[typeof def.value];
1202
+ inst._zod.onattach.push((inst$1) => {
1203
+ const bag = inst$1._zod.bag;
1204
+ const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY;
1205
+ if (def.value > curr) if (def.inclusive) bag.minimum = def.value;
1206
+ else bag.exclusiveMinimum = def.value;
1207
+ });
1208
+ inst._zod.check = (payload) => {
1209
+ if (def.inclusive ? payload.value >= def.value : payload.value > def.value) return;
1210
+ payload.issues.push({
1211
+ origin,
1212
+ code: "too_small",
1213
+ minimum: typeof def.value === "object" ? def.value.getTime() : def.value,
1214
+ input: payload.value,
1215
+ inclusive: def.inclusive,
1216
+ inst,
1217
+ continue: !def.abort
1218
+ });
1219
+ };
1220
+ });
1221
+ const $ZodCheckMultipleOf = /* @__PURE__ */ $constructor("$ZodCheckMultipleOf", (inst, def) => {
1222
+ $ZodCheck.init(inst, def);
1223
+ inst._zod.onattach.push((inst$1) => {
1224
+ var _a$1;
1225
+ (_a$1 = inst$1._zod.bag).multipleOf ?? (_a$1.multipleOf = def.value);
1226
+ });
1227
+ inst._zod.check = (payload) => {
1228
+ if (typeof payload.value !== typeof def.value) throw new Error("Cannot mix number and bigint in multiple_of check.");
1229
+ if (typeof payload.value === "bigint" ? payload.value % def.value === BigInt(0) : floatSafeRemainder(payload.value, def.value) === 0) return;
1230
+ payload.issues.push({
1231
+ origin: typeof payload.value,
1232
+ code: "not_multiple_of",
1233
+ divisor: def.value,
1234
+ input: payload.value,
1235
+ inst,
1236
+ continue: !def.abort
1237
+ });
1238
+ };
1239
+ });
1240
+ const $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat", (inst, def) => {
1241
+ $ZodCheck.init(inst, def);
1242
+ def.format = def.format || "float64";
1243
+ const isInt = def.format?.includes("int");
1244
+ const origin = isInt ? "int" : "number";
1245
+ const [minimum, maximum] = NUMBER_FORMAT_RANGES[def.format];
1246
+ inst._zod.onattach.push((inst$1) => {
1247
+ const bag = inst$1._zod.bag;
1248
+ bag.format = def.format;
1249
+ bag.minimum = minimum;
1250
+ bag.maximum = maximum;
1251
+ if (isInt) bag.pattern = integer;
1252
+ });
1253
+ inst._zod.check = (payload) => {
1254
+ const input = payload.value;
1255
+ if (isInt) {
1256
+ if (!Number.isInteger(input)) {
1257
+ payload.issues.push({
1258
+ expected: origin,
1259
+ format: def.format,
1260
+ code: "invalid_type",
1261
+ continue: false,
1262
+ input,
1263
+ inst
1264
+ });
1265
+ return;
1266
+ }
1267
+ if (!Number.isSafeInteger(input)) {
1268
+ if (input > 0) payload.issues.push({
1269
+ input,
1270
+ code: "too_big",
1271
+ maximum: Number.MAX_SAFE_INTEGER,
1272
+ note: "Integers must be within the safe integer range.",
1273
+ inst,
1274
+ origin,
1275
+ inclusive: true,
1276
+ continue: !def.abort
1277
+ });
1278
+ else payload.issues.push({
1279
+ input,
1280
+ code: "too_small",
1281
+ minimum: Number.MIN_SAFE_INTEGER,
1282
+ note: "Integers must be within the safe integer range.",
1283
+ inst,
1284
+ origin,
1285
+ inclusive: true,
1286
+ continue: !def.abort
1287
+ });
1288
+ return;
1289
+ }
1290
+ }
1291
+ if (input < minimum) payload.issues.push({
1292
+ origin: "number",
1293
+ input,
1294
+ code: "too_small",
1295
+ minimum,
1296
+ inclusive: true,
1297
+ inst,
1298
+ continue: !def.abort
1299
+ });
1300
+ if (input > maximum) payload.issues.push({
1301
+ origin: "number",
1302
+ input,
1303
+ code: "too_big",
1304
+ maximum,
1305
+ inclusive: true,
1306
+ inst,
1307
+ continue: !def.abort
1308
+ });
1309
+ };
1310
+ });
1311
+ const $ZodCheckMaxLength = /* @__PURE__ */ $constructor("$ZodCheckMaxLength", (inst, def) => {
1312
+ var _a$1;
1313
+ $ZodCheck.init(inst, def);
1314
+ (_a$1 = inst._zod.def).when ?? (_a$1.when = (payload) => {
1315
+ const val = payload.value;
1316
+ return !nullish(val) && val.length !== void 0;
1317
+ });
1318
+ inst._zod.onattach.push((inst$1) => {
1319
+ const curr = inst$1._zod.bag.maximum ?? Number.POSITIVE_INFINITY;
1320
+ if (def.maximum < curr) inst$1._zod.bag.maximum = def.maximum;
1321
+ });
1322
+ inst._zod.check = (payload) => {
1323
+ const input = payload.value;
1324
+ if (input.length <= def.maximum) return;
1325
+ const origin = getLengthableOrigin(input);
1326
+ payload.issues.push({
1327
+ origin,
1328
+ code: "too_big",
1329
+ maximum: def.maximum,
585
1330
  inclusive: true,
586
1331
  input,
587
1332
  inst,
@@ -651,6 +1396,123 @@ const $ZodCheckLengthEquals = /* @__PURE__ */ $constructor("$ZodCheckLengthEqual
651
1396
  });
652
1397
  };
653
1398
  });
1399
+ const $ZodCheckStringFormat = /* @__PURE__ */ $constructor("$ZodCheckStringFormat", (inst, def) => {
1400
+ var _a$1, _b;
1401
+ $ZodCheck.init(inst, def);
1402
+ inst._zod.onattach.push((inst$1) => {
1403
+ const bag = inst$1._zod.bag;
1404
+ bag.format = def.format;
1405
+ if (def.pattern) {
1406
+ bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set());
1407
+ bag.patterns.add(def.pattern);
1408
+ }
1409
+ });
1410
+ if (def.pattern) (_a$1 = inst._zod).check ?? (_a$1.check = (payload) => {
1411
+ def.pattern.lastIndex = 0;
1412
+ if (def.pattern.test(payload.value)) return;
1413
+ payload.issues.push({
1414
+ origin: "string",
1415
+ code: "invalid_format",
1416
+ format: def.format,
1417
+ input: payload.value,
1418
+ ...def.pattern ? { pattern: def.pattern.toString() } : {},
1419
+ inst,
1420
+ continue: !def.abort
1421
+ });
1422
+ });
1423
+ else (_b = inst._zod).check ?? (_b.check = () => {});
1424
+ });
1425
+ const $ZodCheckRegex = /* @__PURE__ */ $constructor("$ZodCheckRegex", (inst, def) => {
1426
+ $ZodCheckStringFormat.init(inst, def);
1427
+ inst._zod.check = (payload) => {
1428
+ def.pattern.lastIndex = 0;
1429
+ if (def.pattern.test(payload.value)) return;
1430
+ payload.issues.push({
1431
+ origin: "string",
1432
+ code: "invalid_format",
1433
+ format: "regex",
1434
+ input: payload.value,
1435
+ pattern: def.pattern.toString(),
1436
+ inst,
1437
+ continue: !def.abort
1438
+ });
1439
+ };
1440
+ });
1441
+ const $ZodCheckLowerCase = /* @__PURE__ */ $constructor("$ZodCheckLowerCase", (inst, def) => {
1442
+ def.pattern ?? (def.pattern = lowercase);
1443
+ $ZodCheckStringFormat.init(inst, def);
1444
+ });
1445
+ const $ZodCheckUpperCase = /* @__PURE__ */ $constructor("$ZodCheckUpperCase", (inst, def) => {
1446
+ def.pattern ?? (def.pattern = uppercase);
1447
+ $ZodCheckStringFormat.init(inst, def);
1448
+ });
1449
+ const $ZodCheckIncludes = /* @__PURE__ */ $constructor("$ZodCheckIncludes", (inst, def) => {
1450
+ $ZodCheck.init(inst, def);
1451
+ const escapedRegex = escapeRegex(def.includes);
1452
+ const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position}}${escapedRegex}` : escapedRegex);
1453
+ def.pattern = pattern;
1454
+ inst._zod.onattach.push((inst$1) => {
1455
+ const bag = inst$1._zod.bag;
1456
+ bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set());
1457
+ bag.patterns.add(pattern);
1458
+ });
1459
+ inst._zod.check = (payload) => {
1460
+ if (payload.value.includes(def.includes, def.position)) return;
1461
+ payload.issues.push({
1462
+ origin: "string",
1463
+ code: "invalid_format",
1464
+ format: "includes",
1465
+ includes: def.includes,
1466
+ input: payload.value,
1467
+ inst,
1468
+ continue: !def.abort
1469
+ });
1470
+ };
1471
+ });
1472
+ const $ZodCheckStartsWith = /* @__PURE__ */ $constructor("$ZodCheckStartsWith", (inst, def) => {
1473
+ $ZodCheck.init(inst, def);
1474
+ const pattern = /* @__PURE__ */ new RegExp(`^${escapeRegex(def.prefix)}.*`);
1475
+ def.pattern ?? (def.pattern = pattern);
1476
+ inst._zod.onattach.push((inst$1) => {
1477
+ const bag = inst$1._zod.bag;
1478
+ bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set());
1479
+ bag.patterns.add(pattern);
1480
+ });
1481
+ inst._zod.check = (payload) => {
1482
+ if (payload.value.startsWith(def.prefix)) return;
1483
+ payload.issues.push({
1484
+ origin: "string",
1485
+ code: "invalid_format",
1486
+ format: "starts_with",
1487
+ prefix: def.prefix,
1488
+ input: payload.value,
1489
+ inst,
1490
+ continue: !def.abort
1491
+ });
1492
+ };
1493
+ });
1494
+ const $ZodCheckEndsWith = /* @__PURE__ */ $constructor("$ZodCheckEndsWith", (inst, def) => {
1495
+ $ZodCheck.init(inst, def);
1496
+ const pattern = /* @__PURE__ */ new RegExp(`.*${escapeRegex(def.suffix)}$`);
1497
+ def.pattern ?? (def.pattern = pattern);
1498
+ inst._zod.onattach.push((inst$1) => {
1499
+ const bag = inst$1._zod.bag;
1500
+ bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set());
1501
+ bag.patterns.add(pattern);
1502
+ });
1503
+ inst._zod.check = (payload) => {
1504
+ if (payload.value.endsWith(def.suffix)) return;
1505
+ payload.issues.push({
1506
+ origin: "string",
1507
+ code: "invalid_format",
1508
+ format: "ends_with",
1509
+ suffix: def.suffix,
1510
+ input: payload.value,
1511
+ inst,
1512
+ continue: !def.abort
1513
+ });
1514
+ };
1515
+ });
654
1516
  const $ZodCheckOverwrite = /* @__PURE__ */ $constructor("$ZodCheckOverwrite", (inst, def) => {
655
1517
  $ZodCheck.init(inst, def);
656
1518
  inst._zod.check = (payload) => {
@@ -658,6 +1520,38 @@ const $ZodCheckOverwrite = /* @__PURE__ */ $constructor("$ZodCheckOverwrite", (i
658
1520
  };
659
1521
  });
660
1522
 
1523
+ //#endregion
1524
+ //#region ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/doc.js
1525
+ var Doc = class {
1526
+ constructor(args = []) {
1527
+ this.content = [];
1528
+ this.indent = 0;
1529
+ if (this) this.args = args;
1530
+ }
1531
+ indented(fn) {
1532
+ this.indent += 1;
1533
+ fn(this);
1534
+ this.indent -= 1;
1535
+ }
1536
+ write(arg) {
1537
+ if (typeof arg === "function") {
1538
+ arg(this, { execution: "sync" });
1539
+ arg(this, { execution: "async" });
1540
+ return;
1541
+ }
1542
+ const lines = arg.split("\n").filter((x) => x);
1543
+ const minIndent = Math.min(...lines.map((x) => x.length - x.trimStart().length));
1544
+ const dedented = lines.map((x) => x.slice(minIndent)).map((x) => " ".repeat(this.indent * 2) + x);
1545
+ for (const line of dedented) this.content.push(line);
1546
+ }
1547
+ compile() {
1548
+ const F = Function;
1549
+ const args = this?.args;
1550
+ const lines = [...(this?.content ?? [``]).map((x) => ` ${x}`)];
1551
+ return new F(...args, lines.join("\n"));
1552
+ }
1553
+ };
1554
+
661
1555
  //#endregion
662
1556
  //#region ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/versions.js
663
1557
  const version = {
@@ -756,10 +1650,308 @@ const $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => {
756
1650
  version: 1
757
1651
  }));
758
1652
  });
1653
+ const $ZodString = /* @__PURE__ */ $constructor("$ZodString", (inst, def) => {
1654
+ $ZodType.init(inst, def);
1655
+ inst._zod.pattern = [...inst?._zod.bag?.patterns ?? []].pop() ?? string$1(inst._zod.bag);
1656
+ inst._zod.parse = (payload, _) => {
1657
+ if (def.coerce) try {
1658
+ payload.value = String(payload.value);
1659
+ } catch (_$1) {}
1660
+ if (typeof payload.value === "string") return payload;
1661
+ payload.issues.push({
1662
+ expected: "string",
1663
+ code: "invalid_type",
1664
+ input: payload.value,
1665
+ inst
1666
+ });
1667
+ return payload;
1668
+ };
1669
+ });
1670
+ const $ZodStringFormat = /* @__PURE__ */ $constructor("$ZodStringFormat", (inst, def) => {
1671
+ $ZodCheckStringFormat.init(inst, def);
1672
+ $ZodString.init(inst, def);
1673
+ });
1674
+ const $ZodGUID = /* @__PURE__ */ $constructor("$ZodGUID", (inst, def) => {
1675
+ def.pattern ?? (def.pattern = guid);
1676
+ $ZodStringFormat.init(inst, def);
1677
+ });
1678
+ const $ZodUUID = /* @__PURE__ */ $constructor("$ZodUUID", (inst, def) => {
1679
+ if (def.version) {
1680
+ const v = {
1681
+ v1: 1,
1682
+ v2: 2,
1683
+ v3: 3,
1684
+ v4: 4,
1685
+ v5: 5,
1686
+ v6: 6,
1687
+ v7: 7,
1688
+ v8: 8
1689
+ }[def.version];
1690
+ if (v === void 0) throw new Error(`Invalid UUID version: "${def.version}"`);
1691
+ def.pattern ?? (def.pattern = uuid(v));
1692
+ } else def.pattern ?? (def.pattern = uuid());
1693
+ $ZodStringFormat.init(inst, def);
1694
+ });
1695
+ const $ZodEmail = /* @__PURE__ */ $constructor("$ZodEmail", (inst, def) => {
1696
+ def.pattern ?? (def.pattern = email);
1697
+ $ZodStringFormat.init(inst, def);
1698
+ });
1699
+ const $ZodURL = /* @__PURE__ */ $constructor("$ZodURL", (inst, def) => {
1700
+ $ZodStringFormat.init(inst, def);
1701
+ inst._zod.check = (payload) => {
1702
+ try {
1703
+ const trimmed = payload.value.trim();
1704
+ const url = new URL(trimmed);
1705
+ if (def.hostname) {
1706
+ def.hostname.lastIndex = 0;
1707
+ if (!def.hostname.test(url.hostname)) payload.issues.push({
1708
+ code: "invalid_format",
1709
+ format: "url",
1710
+ note: "Invalid hostname",
1711
+ pattern: def.hostname.source,
1712
+ input: payload.value,
1713
+ inst,
1714
+ continue: !def.abort
1715
+ });
1716
+ }
1717
+ if (def.protocol) {
1718
+ def.protocol.lastIndex = 0;
1719
+ if (!def.protocol.test(url.protocol.endsWith(":") ? url.protocol.slice(0, -1) : url.protocol)) payload.issues.push({
1720
+ code: "invalid_format",
1721
+ format: "url",
1722
+ note: "Invalid protocol",
1723
+ pattern: def.protocol.source,
1724
+ input: payload.value,
1725
+ inst,
1726
+ continue: !def.abort
1727
+ });
1728
+ }
1729
+ if (def.normalize) payload.value = url.href;
1730
+ else payload.value = trimmed;
1731
+ return;
1732
+ } catch (_) {
1733
+ payload.issues.push({
1734
+ code: "invalid_format",
1735
+ format: "url",
1736
+ input: payload.value,
1737
+ inst,
1738
+ continue: !def.abort
1739
+ });
1740
+ }
1741
+ };
1742
+ });
1743
+ const $ZodEmoji = /* @__PURE__ */ $constructor("$ZodEmoji", (inst, def) => {
1744
+ def.pattern ?? (def.pattern = emoji());
1745
+ $ZodStringFormat.init(inst, def);
1746
+ });
1747
+ const $ZodNanoID = /* @__PURE__ */ $constructor("$ZodNanoID", (inst, def) => {
1748
+ def.pattern ?? (def.pattern = nanoid);
1749
+ $ZodStringFormat.init(inst, def);
1750
+ });
1751
+ const $ZodCUID = /* @__PURE__ */ $constructor("$ZodCUID", (inst, def) => {
1752
+ def.pattern ?? (def.pattern = cuid);
1753
+ $ZodStringFormat.init(inst, def);
1754
+ });
1755
+ const $ZodCUID2 = /* @__PURE__ */ $constructor("$ZodCUID2", (inst, def) => {
1756
+ def.pattern ?? (def.pattern = cuid2);
1757
+ $ZodStringFormat.init(inst, def);
1758
+ });
1759
+ const $ZodULID = /* @__PURE__ */ $constructor("$ZodULID", (inst, def) => {
1760
+ def.pattern ?? (def.pattern = ulid);
1761
+ $ZodStringFormat.init(inst, def);
1762
+ });
1763
+ const $ZodXID = /* @__PURE__ */ $constructor("$ZodXID", (inst, def) => {
1764
+ def.pattern ?? (def.pattern = xid);
1765
+ $ZodStringFormat.init(inst, def);
1766
+ });
1767
+ const $ZodKSUID = /* @__PURE__ */ $constructor("$ZodKSUID", (inst, def) => {
1768
+ def.pattern ?? (def.pattern = ksuid);
1769
+ $ZodStringFormat.init(inst, def);
1770
+ });
1771
+ const $ZodISODateTime = /* @__PURE__ */ $constructor("$ZodISODateTime", (inst, def) => {
1772
+ def.pattern ?? (def.pattern = datetime$1(def));
1773
+ $ZodStringFormat.init(inst, def);
1774
+ });
1775
+ const $ZodISODate = /* @__PURE__ */ $constructor("$ZodISODate", (inst, def) => {
1776
+ def.pattern ?? (def.pattern = date$1);
1777
+ $ZodStringFormat.init(inst, def);
1778
+ });
1779
+ const $ZodISOTime = /* @__PURE__ */ $constructor("$ZodISOTime", (inst, def) => {
1780
+ def.pattern ?? (def.pattern = time$1(def));
1781
+ $ZodStringFormat.init(inst, def);
1782
+ });
1783
+ const $ZodISODuration = /* @__PURE__ */ $constructor("$ZodISODuration", (inst, def) => {
1784
+ def.pattern ?? (def.pattern = duration$1);
1785
+ $ZodStringFormat.init(inst, def);
1786
+ });
1787
+ const $ZodIPv4 = /* @__PURE__ */ $constructor("$ZodIPv4", (inst, def) => {
1788
+ def.pattern ?? (def.pattern = ipv4);
1789
+ $ZodStringFormat.init(inst, def);
1790
+ inst._zod.bag.format = `ipv4`;
1791
+ });
1792
+ const $ZodIPv6 = /* @__PURE__ */ $constructor("$ZodIPv6", (inst, def) => {
1793
+ def.pattern ?? (def.pattern = ipv6);
1794
+ $ZodStringFormat.init(inst, def);
1795
+ inst._zod.bag.format = `ipv6`;
1796
+ inst._zod.check = (payload) => {
1797
+ try {
1798
+ new URL(`http://[${payload.value}]`);
1799
+ } catch {
1800
+ payload.issues.push({
1801
+ code: "invalid_format",
1802
+ format: "ipv6",
1803
+ input: payload.value,
1804
+ inst,
1805
+ continue: !def.abort
1806
+ });
1807
+ }
1808
+ };
1809
+ });
1810
+ const $ZodCIDRv4 = /* @__PURE__ */ $constructor("$ZodCIDRv4", (inst, def) => {
1811
+ def.pattern ?? (def.pattern = cidrv4);
1812
+ $ZodStringFormat.init(inst, def);
1813
+ });
1814
+ const $ZodCIDRv6 = /* @__PURE__ */ $constructor("$ZodCIDRv6", (inst, def) => {
1815
+ def.pattern ?? (def.pattern = cidrv6);
1816
+ $ZodStringFormat.init(inst, def);
1817
+ inst._zod.check = (payload) => {
1818
+ const parts = payload.value.split("/");
1819
+ try {
1820
+ if (parts.length !== 2) throw new Error();
1821
+ const [address, prefix] = parts;
1822
+ if (!prefix) throw new Error();
1823
+ const prefixNum = Number(prefix);
1824
+ if (`${prefixNum}` !== prefix) throw new Error();
1825
+ if (prefixNum < 0 || prefixNum > 128) throw new Error();
1826
+ new URL(`http://[${address}]`);
1827
+ } catch {
1828
+ payload.issues.push({
1829
+ code: "invalid_format",
1830
+ format: "cidrv6",
1831
+ input: payload.value,
1832
+ inst,
1833
+ continue: !def.abort
1834
+ });
1835
+ }
1836
+ };
1837
+ });
1838
+ function isValidBase64(data) {
1839
+ if (data === "") return true;
1840
+ if (data.length % 4 !== 0) return false;
1841
+ try {
1842
+ atob(data);
1843
+ return true;
1844
+ } catch {
1845
+ return false;
1846
+ }
1847
+ }
1848
+ const $ZodBase64 = /* @__PURE__ */ $constructor("$ZodBase64", (inst, def) => {
1849
+ def.pattern ?? (def.pattern = base64);
1850
+ $ZodStringFormat.init(inst, def);
1851
+ inst._zod.bag.contentEncoding = "base64";
1852
+ inst._zod.check = (payload) => {
1853
+ if (isValidBase64(payload.value)) return;
1854
+ payload.issues.push({
1855
+ code: "invalid_format",
1856
+ format: "base64",
1857
+ input: payload.value,
1858
+ inst,
1859
+ continue: !def.abort
1860
+ });
1861
+ };
1862
+ });
1863
+ function isValidBase64URL(data) {
1864
+ if (!base64url.test(data)) return false;
1865
+ const base64$1 = data.replace(/[-_]/g, (c) => c === "-" ? "+" : "/");
1866
+ return isValidBase64(base64$1.padEnd(Math.ceil(base64$1.length / 4) * 4, "="));
1867
+ }
1868
+ const $ZodBase64URL = /* @__PURE__ */ $constructor("$ZodBase64URL", (inst, def) => {
1869
+ def.pattern ?? (def.pattern = base64url);
1870
+ $ZodStringFormat.init(inst, def);
1871
+ inst._zod.bag.contentEncoding = "base64url";
1872
+ inst._zod.check = (payload) => {
1873
+ if (isValidBase64URL(payload.value)) return;
1874
+ payload.issues.push({
1875
+ code: "invalid_format",
1876
+ format: "base64url",
1877
+ input: payload.value,
1878
+ inst,
1879
+ continue: !def.abort
1880
+ });
1881
+ };
1882
+ });
1883
+ const $ZodE164 = /* @__PURE__ */ $constructor("$ZodE164", (inst, def) => {
1884
+ def.pattern ?? (def.pattern = e164);
1885
+ $ZodStringFormat.init(inst, def);
1886
+ });
1887
+ function isValidJWT(token, algorithm = null) {
1888
+ try {
1889
+ const tokensParts = token.split(".");
1890
+ if (tokensParts.length !== 3) return false;
1891
+ const [header] = tokensParts;
1892
+ if (!header) return false;
1893
+ const parsedHeader = JSON.parse(atob(header));
1894
+ if ("typ" in parsedHeader && parsedHeader?.typ !== "JWT") return false;
1895
+ if (!parsedHeader.alg) return false;
1896
+ if (algorithm && (!("alg" in parsedHeader) || parsedHeader.alg !== algorithm)) return false;
1897
+ return true;
1898
+ } catch {
1899
+ return false;
1900
+ }
1901
+ }
1902
+ const $ZodJWT = /* @__PURE__ */ $constructor("$ZodJWT", (inst, def) => {
1903
+ $ZodStringFormat.init(inst, def);
1904
+ inst._zod.check = (payload) => {
1905
+ if (isValidJWT(payload.value, def.alg)) return;
1906
+ payload.issues.push({
1907
+ code: "invalid_format",
1908
+ format: "jwt",
1909
+ input: payload.value,
1910
+ inst,
1911
+ continue: !def.abort
1912
+ });
1913
+ };
1914
+ });
1915
+ const $ZodNumber = /* @__PURE__ */ $constructor("$ZodNumber", (inst, def) => {
1916
+ $ZodType.init(inst, def);
1917
+ inst._zod.pattern = inst._zod.bag.pattern ?? number$1;
1918
+ inst._zod.parse = (payload, _ctx) => {
1919
+ if (def.coerce) try {
1920
+ payload.value = Number(payload.value);
1921
+ } catch (_) {}
1922
+ const input = payload.value;
1923
+ if (typeof input === "number" && !Number.isNaN(input) && Number.isFinite(input)) return payload;
1924
+ const received = typeof input === "number" ? Number.isNaN(input) ? "NaN" : !Number.isFinite(input) ? "Infinity" : void 0 : void 0;
1925
+ payload.issues.push({
1926
+ expected: "number",
1927
+ code: "invalid_type",
1928
+ input,
1929
+ inst,
1930
+ ...received ? { received } : {}
1931
+ });
1932
+ return payload;
1933
+ };
1934
+ });
1935
+ const $ZodNumberFormat = /* @__PURE__ */ $constructor("$ZodNumberFormat", (inst, def) => {
1936
+ $ZodCheckNumberFormat.init(inst, def);
1937
+ $ZodNumber.init(inst, def);
1938
+ });
759
1939
  const $ZodUnknown = /* @__PURE__ */ $constructor("$ZodUnknown", (inst, def) => {
760
1940
  $ZodType.init(inst, def);
761
1941
  inst._zod.parse = (payload) => payload;
762
1942
  });
1943
+ const $ZodNever = /* @__PURE__ */ $constructor("$ZodNever", (inst, def) => {
1944
+ $ZodType.init(inst, def);
1945
+ inst._zod.parse = (payload, _ctx) => {
1946
+ payload.issues.push({
1947
+ expected: "never",
1948
+ code: "invalid_type",
1949
+ input: payload.value,
1950
+ inst
1951
+ });
1952
+ return payload;
1953
+ };
1954
+ });
763
1955
  function handleArrayResult(result, final, index) {
764
1956
  if (result.issues.length) final.issues.push(...prefixIssues(index, result.issues));
765
1957
  final.value[index] = result.value;
@@ -768,28 +1960,229 @@ const $ZodArray = /* @__PURE__ */ $constructor("$ZodArray", (inst, def) => {
768
1960
  $ZodType.init(inst, def);
769
1961
  inst._zod.parse = (payload, ctx) => {
770
1962
  const input = payload.value;
771
- if (!Array.isArray(input)) {
1963
+ if (!Array.isArray(input)) {
1964
+ payload.issues.push({
1965
+ expected: "array",
1966
+ code: "invalid_type",
1967
+ input,
1968
+ inst
1969
+ });
1970
+ return payload;
1971
+ }
1972
+ payload.value = Array(input.length);
1973
+ const proms = [];
1974
+ for (let i = 0; i < input.length; i++) {
1975
+ const item = input[i];
1976
+ const result = def.element._zod.run({
1977
+ value: item,
1978
+ issues: []
1979
+ }, ctx);
1980
+ if (result instanceof Promise) proms.push(result.then((result$1) => handleArrayResult(result$1, payload, i)));
1981
+ else handleArrayResult(result, payload, i);
1982
+ }
1983
+ if (proms.length) return Promise.all(proms).then(() => payload);
1984
+ return payload;
1985
+ };
1986
+ });
1987
+ function handlePropertyResult(result, final, key, input, isOptionalOut) {
1988
+ if (result.issues.length) {
1989
+ if (isOptionalOut && !(key in input)) return;
1990
+ final.issues.push(...prefixIssues(key, result.issues));
1991
+ }
1992
+ if (result.value === void 0) {
1993
+ if (key in input) final.value[key] = void 0;
1994
+ } else final.value[key] = result.value;
1995
+ }
1996
+ function normalizeDef(def) {
1997
+ const keys = Object.keys(def.shape);
1998
+ for (const k of keys) if (!def.shape?.[k]?._zod?.traits?.has("$ZodType")) throw new Error(`Invalid element at key "${k}": expected a Zod schema`);
1999
+ const okeys = optionalKeys(def.shape);
2000
+ return {
2001
+ ...def,
2002
+ keys,
2003
+ keySet: new Set(keys),
2004
+ numKeys: keys.length,
2005
+ optionalKeys: new Set(okeys)
2006
+ };
2007
+ }
2008
+ function handleCatchall(proms, input, payload, ctx, def, inst) {
2009
+ const unrecognized = [];
2010
+ const keySet = def.keySet;
2011
+ const _catchall = def.catchall._zod;
2012
+ const t = _catchall.def.type;
2013
+ const isOptionalOut = _catchall.optout === "optional";
2014
+ for (const key in input) {
2015
+ if (keySet.has(key)) continue;
2016
+ if (t === "never") {
2017
+ unrecognized.push(key);
2018
+ continue;
2019
+ }
2020
+ const r = _catchall.run({
2021
+ value: input[key],
2022
+ issues: []
2023
+ }, ctx);
2024
+ if (r instanceof Promise) proms.push(r.then((r$1) => handlePropertyResult(r$1, payload, key, input, isOptionalOut)));
2025
+ else handlePropertyResult(r, payload, key, input, isOptionalOut);
2026
+ }
2027
+ if (unrecognized.length) payload.issues.push({
2028
+ code: "unrecognized_keys",
2029
+ keys: unrecognized,
2030
+ input,
2031
+ inst
2032
+ });
2033
+ if (!proms.length) return payload;
2034
+ return Promise.all(proms).then(() => {
2035
+ return payload;
2036
+ });
2037
+ }
2038
+ const $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => {
2039
+ $ZodType.init(inst, def);
2040
+ if (!Object.getOwnPropertyDescriptor(def, "shape")?.get) {
2041
+ const sh = def.shape;
2042
+ Object.defineProperty(def, "shape", { get: () => {
2043
+ const newSh = { ...sh };
2044
+ Object.defineProperty(def, "shape", { value: newSh });
2045
+ return newSh;
2046
+ } });
2047
+ }
2048
+ const _normalized = cached(() => normalizeDef(def));
2049
+ defineLazy(inst._zod, "propValues", () => {
2050
+ const shape = def.shape;
2051
+ const propValues = {};
2052
+ for (const key in shape) {
2053
+ const field = shape[key]._zod;
2054
+ if (field.values) {
2055
+ propValues[key] ?? (propValues[key] = /* @__PURE__ */ new Set());
2056
+ for (const v of field.values) propValues[key].add(v);
2057
+ }
2058
+ }
2059
+ return propValues;
2060
+ });
2061
+ const isObject$1 = isObject;
2062
+ const catchall = def.catchall;
2063
+ let value;
2064
+ inst._zod.parse = (payload, ctx) => {
2065
+ value ?? (value = _normalized.value);
2066
+ const input = payload.value;
2067
+ if (!isObject$1(input)) {
2068
+ payload.issues.push({
2069
+ expected: "object",
2070
+ code: "invalid_type",
2071
+ input,
2072
+ inst
2073
+ });
2074
+ return payload;
2075
+ }
2076
+ payload.value = {};
2077
+ const proms = [];
2078
+ const shape = value.shape;
2079
+ for (const key of value.keys) {
2080
+ const el = shape[key];
2081
+ const isOptionalOut = el._zod.optout === "optional";
2082
+ const r = el._zod.run({
2083
+ value: input[key],
2084
+ issues: []
2085
+ }, ctx);
2086
+ if (r instanceof Promise) proms.push(r.then((r$1) => handlePropertyResult(r$1, payload, key, input, isOptionalOut)));
2087
+ else handlePropertyResult(r, payload, key, input, isOptionalOut);
2088
+ }
2089
+ if (!catchall) return proms.length ? Promise.all(proms).then(() => payload) : payload;
2090
+ return handleCatchall(proms, input, payload, ctx, _normalized.value, inst);
2091
+ };
2092
+ });
2093
+ const $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) => {
2094
+ $ZodObject.init(inst, def);
2095
+ const superParse = inst._zod.parse;
2096
+ const _normalized = cached(() => normalizeDef(def));
2097
+ const generateFastpass = (shape) => {
2098
+ const doc = new Doc([
2099
+ "shape",
2100
+ "payload",
2101
+ "ctx"
2102
+ ]);
2103
+ const normalized = _normalized.value;
2104
+ const parseStr = (key) => {
2105
+ const k = esc(key);
2106
+ return `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`;
2107
+ };
2108
+ doc.write(`const input = payload.value;`);
2109
+ const ids = Object.create(null);
2110
+ let counter = 0;
2111
+ for (const key of normalized.keys) ids[key] = `key_${counter++}`;
2112
+ doc.write(`const newResult = {};`);
2113
+ for (const key of normalized.keys) {
2114
+ const id = ids[key];
2115
+ const k = esc(key);
2116
+ const isOptionalOut = shape[key]?._zod?.optout === "optional";
2117
+ doc.write(`const ${id} = ${parseStr(key)};`);
2118
+ if (isOptionalOut) doc.write(`
2119
+ if (${id}.issues.length) {
2120
+ if (${k} in input) {
2121
+ payload.issues = payload.issues.concat(${id}.issues.map(iss => ({
2122
+ ...iss,
2123
+ path: iss.path ? [${k}, ...iss.path] : [${k}]
2124
+ })));
2125
+ }
2126
+ }
2127
+
2128
+ if (${id}.value === undefined) {
2129
+ if (${k} in input) {
2130
+ newResult[${k}] = undefined;
2131
+ }
2132
+ } else {
2133
+ newResult[${k}] = ${id}.value;
2134
+ }
2135
+
2136
+ `);
2137
+ else doc.write(`
2138
+ if (${id}.issues.length) {
2139
+ payload.issues = payload.issues.concat(${id}.issues.map(iss => ({
2140
+ ...iss,
2141
+ path: iss.path ? [${k}, ...iss.path] : [${k}]
2142
+ })));
2143
+ }
2144
+
2145
+ if (${id}.value === undefined) {
2146
+ if (${k} in input) {
2147
+ newResult[${k}] = undefined;
2148
+ }
2149
+ } else {
2150
+ newResult[${k}] = ${id}.value;
2151
+ }
2152
+
2153
+ `);
2154
+ }
2155
+ doc.write(`payload.value = newResult;`);
2156
+ doc.write(`return payload;`);
2157
+ const fn = doc.compile();
2158
+ return (payload, ctx) => fn(shape, payload, ctx);
2159
+ };
2160
+ let fastpass;
2161
+ const isObject$1 = isObject;
2162
+ const jit = !globalConfig.jitless;
2163
+ const allowsEval$1 = allowsEval;
2164
+ const fastEnabled = jit && allowsEval$1.value;
2165
+ const catchall = def.catchall;
2166
+ let value;
2167
+ inst._zod.parse = (payload, ctx) => {
2168
+ value ?? (value = _normalized.value);
2169
+ const input = payload.value;
2170
+ if (!isObject$1(input)) {
772
2171
  payload.issues.push({
773
- expected: "array",
2172
+ expected: "object",
774
2173
  code: "invalid_type",
775
2174
  input,
776
2175
  inst
777
2176
  });
778
2177
  return payload;
779
2178
  }
780
- payload.value = Array(input.length);
781
- const proms = [];
782
- for (let i = 0; i < input.length; i++) {
783
- const item = input[i];
784
- const result = def.element._zod.run({
785
- value: item,
786
- issues: []
787
- }, ctx);
788
- if (result instanceof Promise) proms.push(result.then((result$1) => handleArrayResult(result$1, payload, i)));
789
- else handleArrayResult(result, payload, i);
2179
+ if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) {
2180
+ if (!fastpass) fastpass = generateFastpass(def.shape);
2181
+ payload = fastpass(payload, ctx);
2182
+ if (!catchall) return payload;
2183
+ return handleCatchall([], input, payload, ctx, value, inst);
790
2184
  }
791
- if (proms.length) return Promise.all(proms).then(() => payload);
792
- return payload;
2185
+ return superParse(payload, ctx);
793
2186
  };
794
2187
  });
795
2188
  function handleUnionResults(results, final, inst, ctx) {
@@ -947,6 +2340,115 @@ function handleIntersectionResults(result, left, right) {
947
2340
  result.value = merged.data;
948
2341
  return result;
949
2342
  }
2343
+ const $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => {
2344
+ $ZodType.init(inst, def);
2345
+ inst._zod.parse = (payload, ctx) => {
2346
+ const input = payload.value;
2347
+ if (!isPlainObject(input)) {
2348
+ payload.issues.push({
2349
+ expected: "record",
2350
+ code: "invalid_type",
2351
+ input,
2352
+ inst
2353
+ });
2354
+ return payload;
2355
+ }
2356
+ const proms = [];
2357
+ const values = def.keyType._zod.values;
2358
+ if (values) {
2359
+ payload.value = {};
2360
+ const recordKeys = /* @__PURE__ */ new Set();
2361
+ for (const key of values) if (typeof key === "string" || typeof key === "number" || typeof key === "symbol") {
2362
+ recordKeys.add(typeof key === "number" ? key.toString() : key);
2363
+ const result = def.valueType._zod.run({
2364
+ value: input[key],
2365
+ issues: []
2366
+ }, ctx);
2367
+ if (result instanceof Promise) proms.push(result.then((result$1) => {
2368
+ if (result$1.issues.length) payload.issues.push(...prefixIssues(key, result$1.issues));
2369
+ payload.value[key] = result$1.value;
2370
+ }));
2371
+ else {
2372
+ if (result.issues.length) payload.issues.push(...prefixIssues(key, result.issues));
2373
+ payload.value[key] = result.value;
2374
+ }
2375
+ }
2376
+ let unrecognized;
2377
+ for (const key in input) if (!recordKeys.has(key)) {
2378
+ unrecognized = unrecognized ?? [];
2379
+ unrecognized.push(key);
2380
+ }
2381
+ if (unrecognized && unrecognized.length > 0) payload.issues.push({
2382
+ code: "unrecognized_keys",
2383
+ input,
2384
+ inst,
2385
+ keys: unrecognized
2386
+ });
2387
+ } else {
2388
+ payload.value = {};
2389
+ for (const key of Reflect.ownKeys(input)) {
2390
+ if (key === "__proto__") continue;
2391
+ let keyResult = def.keyType._zod.run({
2392
+ value: key,
2393
+ issues: []
2394
+ }, ctx);
2395
+ if (keyResult instanceof Promise) throw new Error("Async schemas not supported in object keys currently");
2396
+ if (typeof key === "string" && number$1.test(key) && keyResult.issues.length) {
2397
+ const retryResult = def.keyType._zod.run({
2398
+ value: Number(key),
2399
+ issues: []
2400
+ }, ctx);
2401
+ if (retryResult instanceof Promise) throw new Error("Async schemas not supported in object keys currently");
2402
+ if (retryResult.issues.length === 0) keyResult = retryResult;
2403
+ }
2404
+ if (keyResult.issues.length) {
2405
+ if (def.mode === "loose") payload.value[key] = input[key];
2406
+ else payload.issues.push({
2407
+ code: "invalid_key",
2408
+ origin: "record",
2409
+ issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())),
2410
+ input: key,
2411
+ path: [key],
2412
+ inst
2413
+ });
2414
+ continue;
2415
+ }
2416
+ const result = def.valueType._zod.run({
2417
+ value: input[key],
2418
+ issues: []
2419
+ }, ctx);
2420
+ if (result instanceof Promise) proms.push(result.then((result$1) => {
2421
+ if (result$1.issues.length) payload.issues.push(...prefixIssues(key, result$1.issues));
2422
+ payload.value[keyResult.value] = result$1.value;
2423
+ }));
2424
+ else {
2425
+ if (result.issues.length) payload.issues.push(...prefixIssues(key, result.issues));
2426
+ payload.value[keyResult.value] = result.value;
2427
+ }
2428
+ }
2429
+ }
2430
+ if (proms.length) return Promise.all(proms).then(() => payload);
2431
+ return payload;
2432
+ };
2433
+ });
2434
+ const $ZodEnum = /* @__PURE__ */ $constructor("$ZodEnum", (inst, def) => {
2435
+ $ZodType.init(inst, def);
2436
+ const values = getEnumValues(def.entries);
2437
+ const valuesSet = new Set(values);
2438
+ inst._zod.values = valuesSet;
2439
+ inst._zod.pattern = /* @__PURE__ */ new RegExp(`^(${values.filter((k) => propertyKeyTypes.has(typeof k)).map((o) => typeof o === "string" ? escapeRegex(o) : o.toString()).join("|")})$`);
2440
+ inst._zod.parse = (payload, _ctx) => {
2441
+ const input = payload.value;
2442
+ if (valuesSet.has(input)) return payload;
2443
+ payload.issues.push({
2444
+ code: "invalid_value",
2445
+ values,
2446
+ input,
2447
+ inst
2448
+ });
2449
+ return payload;
2450
+ };
2451
+ });
950
2452
  const $ZodTransform = /* @__PURE__ */ $constructor("$ZodTransform", (inst, def) => {
951
2453
  $ZodType.init(inst, def);
952
2454
  inst._zod.parse = (payload, ctx) => {
@@ -1216,14 +2718,353 @@ var $ZodRegistry = class {
1216
2718
  function registry() {
1217
2719
  return new $ZodRegistry();
1218
2720
  }
1219
- (_a = globalThis).__zod_globalRegistry ?? (_a.__zod_globalRegistry = registry());
1220
- const globalRegistry = globalThis.__zod_globalRegistry;
1221
-
1222
- //#endregion
1223
- //#region ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/api.js
2721
+ (_a = globalThis).__zod_globalRegistry ?? (_a.__zod_globalRegistry = registry());
2722
+ const globalRegistry = globalThis.__zod_globalRegistry;
2723
+
2724
+ //#endregion
2725
+ //#region ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/api.js
2726
+ /* @__NO_SIDE_EFFECTS__ */
2727
+ function _string(Class, params) {
2728
+ return new Class({
2729
+ type: "string",
2730
+ ...normalizeParams(params)
2731
+ });
2732
+ }
2733
+ /* @__NO_SIDE_EFFECTS__ */
2734
+ function _email(Class, params) {
2735
+ return new Class({
2736
+ type: "string",
2737
+ format: "email",
2738
+ check: "string_format",
2739
+ abort: false,
2740
+ ...normalizeParams(params)
2741
+ });
2742
+ }
2743
+ /* @__NO_SIDE_EFFECTS__ */
2744
+ function _guid(Class, params) {
2745
+ return new Class({
2746
+ type: "string",
2747
+ format: "guid",
2748
+ check: "string_format",
2749
+ abort: false,
2750
+ ...normalizeParams(params)
2751
+ });
2752
+ }
2753
+ /* @__NO_SIDE_EFFECTS__ */
2754
+ function _uuid(Class, params) {
2755
+ return new Class({
2756
+ type: "string",
2757
+ format: "uuid",
2758
+ check: "string_format",
2759
+ abort: false,
2760
+ ...normalizeParams(params)
2761
+ });
2762
+ }
2763
+ /* @__NO_SIDE_EFFECTS__ */
2764
+ function _uuidv4(Class, params) {
2765
+ return new Class({
2766
+ type: "string",
2767
+ format: "uuid",
2768
+ check: "string_format",
2769
+ abort: false,
2770
+ version: "v4",
2771
+ ...normalizeParams(params)
2772
+ });
2773
+ }
2774
+ /* @__NO_SIDE_EFFECTS__ */
2775
+ function _uuidv6(Class, params) {
2776
+ return new Class({
2777
+ type: "string",
2778
+ format: "uuid",
2779
+ check: "string_format",
2780
+ abort: false,
2781
+ version: "v6",
2782
+ ...normalizeParams(params)
2783
+ });
2784
+ }
2785
+ /* @__NO_SIDE_EFFECTS__ */
2786
+ function _uuidv7(Class, params) {
2787
+ return new Class({
2788
+ type: "string",
2789
+ format: "uuid",
2790
+ check: "string_format",
2791
+ abort: false,
2792
+ version: "v7",
2793
+ ...normalizeParams(params)
2794
+ });
2795
+ }
2796
+ /* @__NO_SIDE_EFFECTS__ */
2797
+ function _url(Class, params) {
2798
+ return new Class({
2799
+ type: "string",
2800
+ format: "url",
2801
+ check: "string_format",
2802
+ abort: false,
2803
+ ...normalizeParams(params)
2804
+ });
2805
+ }
2806
+ /* @__NO_SIDE_EFFECTS__ */
2807
+ function _emoji(Class, params) {
2808
+ return new Class({
2809
+ type: "string",
2810
+ format: "emoji",
2811
+ check: "string_format",
2812
+ abort: false,
2813
+ ...normalizeParams(params)
2814
+ });
2815
+ }
2816
+ /* @__NO_SIDE_EFFECTS__ */
2817
+ function _nanoid(Class, params) {
2818
+ return new Class({
2819
+ type: "string",
2820
+ format: "nanoid",
2821
+ check: "string_format",
2822
+ abort: false,
2823
+ ...normalizeParams(params)
2824
+ });
2825
+ }
2826
+ /* @__NO_SIDE_EFFECTS__ */
2827
+ function _cuid(Class, params) {
2828
+ return new Class({
2829
+ type: "string",
2830
+ format: "cuid",
2831
+ check: "string_format",
2832
+ abort: false,
2833
+ ...normalizeParams(params)
2834
+ });
2835
+ }
2836
+ /* @__NO_SIDE_EFFECTS__ */
2837
+ function _cuid2(Class, params) {
2838
+ return new Class({
2839
+ type: "string",
2840
+ format: "cuid2",
2841
+ check: "string_format",
2842
+ abort: false,
2843
+ ...normalizeParams(params)
2844
+ });
2845
+ }
2846
+ /* @__NO_SIDE_EFFECTS__ */
2847
+ function _ulid(Class, params) {
2848
+ return new Class({
2849
+ type: "string",
2850
+ format: "ulid",
2851
+ check: "string_format",
2852
+ abort: false,
2853
+ ...normalizeParams(params)
2854
+ });
2855
+ }
2856
+ /* @__NO_SIDE_EFFECTS__ */
2857
+ function _xid(Class, params) {
2858
+ return new Class({
2859
+ type: "string",
2860
+ format: "xid",
2861
+ check: "string_format",
2862
+ abort: false,
2863
+ ...normalizeParams(params)
2864
+ });
2865
+ }
2866
+ /* @__NO_SIDE_EFFECTS__ */
2867
+ function _ksuid(Class, params) {
2868
+ return new Class({
2869
+ type: "string",
2870
+ format: "ksuid",
2871
+ check: "string_format",
2872
+ abort: false,
2873
+ ...normalizeParams(params)
2874
+ });
2875
+ }
2876
+ /* @__NO_SIDE_EFFECTS__ */
2877
+ function _ipv4(Class, params) {
2878
+ return new Class({
2879
+ type: "string",
2880
+ format: "ipv4",
2881
+ check: "string_format",
2882
+ abort: false,
2883
+ ...normalizeParams(params)
2884
+ });
2885
+ }
2886
+ /* @__NO_SIDE_EFFECTS__ */
2887
+ function _ipv6(Class, params) {
2888
+ return new Class({
2889
+ type: "string",
2890
+ format: "ipv6",
2891
+ check: "string_format",
2892
+ abort: false,
2893
+ ...normalizeParams(params)
2894
+ });
2895
+ }
2896
+ /* @__NO_SIDE_EFFECTS__ */
2897
+ function _cidrv4(Class, params) {
2898
+ return new Class({
2899
+ type: "string",
2900
+ format: "cidrv4",
2901
+ check: "string_format",
2902
+ abort: false,
2903
+ ...normalizeParams(params)
2904
+ });
2905
+ }
2906
+ /* @__NO_SIDE_EFFECTS__ */
2907
+ function _cidrv6(Class, params) {
2908
+ return new Class({
2909
+ type: "string",
2910
+ format: "cidrv6",
2911
+ check: "string_format",
2912
+ abort: false,
2913
+ ...normalizeParams(params)
2914
+ });
2915
+ }
2916
+ /* @__NO_SIDE_EFFECTS__ */
2917
+ function _base64(Class, params) {
2918
+ return new Class({
2919
+ type: "string",
2920
+ format: "base64",
2921
+ check: "string_format",
2922
+ abort: false,
2923
+ ...normalizeParams(params)
2924
+ });
2925
+ }
2926
+ /* @__NO_SIDE_EFFECTS__ */
2927
+ function _base64url(Class, params) {
2928
+ return new Class({
2929
+ type: "string",
2930
+ format: "base64url",
2931
+ check: "string_format",
2932
+ abort: false,
2933
+ ...normalizeParams(params)
2934
+ });
2935
+ }
2936
+ /* @__NO_SIDE_EFFECTS__ */
2937
+ function _e164(Class, params) {
2938
+ return new Class({
2939
+ type: "string",
2940
+ format: "e164",
2941
+ check: "string_format",
2942
+ abort: false,
2943
+ ...normalizeParams(params)
2944
+ });
2945
+ }
2946
+ /* @__NO_SIDE_EFFECTS__ */
2947
+ function _jwt(Class, params) {
2948
+ return new Class({
2949
+ type: "string",
2950
+ format: "jwt",
2951
+ check: "string_format",
2952
+ abort: false,
2953
+ ...normalizeParams(params)
2954
+ });
2955
+ }
2956
+ /* @__NO_SIDE_EFFECTS__ */
2957
+ function _isoDateTime(Class, params) {
2958
+ return new Class({
2959
+ type: "string",
2960
+ format: "datetime",
2961
+ check: "string_format",
2962
+ offset: false,
2963
+ local: false,
2964
+ precision: null,
2965
+ ...normalizeParams(params)
2966
+ });
2967
+ }
2968
+ /* @__NO_SIDE_EFFECTS__ */
2969
+ function _isoDate(Class, params) {
2970
+ return new Class({
2971
+ type: "string",
2972
+ format: "date",
2973
+ check: "string_format",
2974
+ ...normalizeParams(params)
2975
+ });
2976
+ }
2977
+ /* @__NO_SIDE_EFFECTS__ */
2978
+ function _isoTime(Class, params) {
2979
+ return new Class({
2980
+ type: "string",
2981
+ format: "time",
2982
+ check: "string_format",
2983
+ precision: null,
2984
+ ...normalizeParams(params)
2985
+ });
2986
+ }
2987
+ /* @__NO_SIDE_EFFECTS__ */
2988
+ function _isoDuration(Class, params) {
2989
+ return new Class({
2990
+ type: "string",
2991
+ format: "duration",
2992
+ check: "string_format",
2993
+ ...normalizeParams(params)
2994
+ });
2995
+ }
2996
+ /* @__NO_SIDE_EFFECTS__ */
2997
+ function _number(Class, params) {
2998
+ return new Class({
2999
+ type: "number",
3000
+ checks: [],
3001
+ ...normalizeParams(params)
3002
+ });
3003
+ }
3004
+ /* @__NO_SIDE_EFFECTS__ */
3005
+ function _int(Class, params) {
3006
+ return new Class({
3007
+ type: "number",
3008
+ check: "number_format",
3009
+ abort: false,
3010
+ format: "safeint",
3011
+ ...normalizeParams(params)
3012
+ });
3013
+ }
3014
+ /* @__NO_SIDE_EFFECTS__ */
3015
+ function _unknown(Class) {
3016
+ return new Class({ type: "unknown" });
3017
+ }
3018
+ /* @__NO_SIDE_EFFECTS__ */
3019
+ function _never(Class, params) {
3020
+ return new Class({
3021
+ type: "never",
3022
+ ...normalizeParams(params)
3023
+ });
3024
+ }
3025
+ /* @__NO_SIDE_EFFECTS__ */
3026
+ function _lt(value, params) {
3027
+ return new $ZodCheckLessThan({
3028
+ check: "less_than",
3029
+ ...normalizeParams(params),
3030
+ value,
3031
+ inclusive: false
3032
+ });
3033
+ }
3034
+ /* @__NO_SIDE_EFFECTS__ */
3035
+ function _lte(value, params) {
3036
+ return new $ZodCheckLessThan({
3037
+ check: "less_than",
3038
+ ...normalizeParams(params),
3039
+ value,
3040
+ inclusive: true
3041
+ });
3042
+ }
3043
+ /* @__NO_SIDE_EFFECTS__ */
3044
+ function _gt(value, params) {
3045
+ return new $ZodCheckGreaterThan({
3046
+ check: "greater_than",
3047
+ ...normalizeParams(params),
3048
+ value,
3049
+ inclusive: false
3050
+ });
3051
+ }
1224
3052
  /* @__NO_SIDE_EFFECTS__ */
1225
- function _unknown(Class) {
1226
- return new Class({ type: "unknown" });
3053
+ function _gte(value, params) {
3054
+ return new $ZodCheckGreaterThan({
3055
+ check: "greater_than",
3056
+ ...normalizeParams(params),
3057
+ value,
3058
+ inclusive: true
3059
+ });
3060
+ }
3061
+ /* @__NO_SIDE_EFFECTS__ */
3062
+ function _multipleOf(value, params) {
3063
+ return new $ZodCheckMultipleOf({
3064
+ check: "multiple_of",
3065
+ ...normalizeParams(params),
3066
+ value
3067
+ });
1227
3068
  }
1228
3069
  /* @__NO_SIDE_EFFECTS__ */
1229
3070
  function _maxLength(maximum, params) {
@@ -1250,6 +3091,58 @@ function _length(length, params) {
1250
3091
  });
1251
3092
  }
1252
3093
  /* @__NO_SIDE_EFFECTS__ */
3094
+ function _regex(pattern, params) {
3095
+ return new $ZodCheckRegex({
3096
+ check: "string_format",
3097
+ format: "regex",
3098
+ ...normalizeParams(params),
3099
+ pattern
3100
+ });
3101
+ }
3102
+ /* @__NO_SIDE_EFFECTS__ */
3103
+ function _lowercase(params) {
3104
+ return new $ZodCheckLowerCase({
3105
+ check: "string_format",
3106
+ format: "lowercase",
3107
+ ...normalizeParams(params)
3108
+ });
3109
+ }
3110
+ /* @__NO_SIDE_EFFECTS__ */
3111
+ function _uppercase(params) {
3112
+ return new $ZodCheckUpperCase({
3113
+ check: "string_format",
3114
+ format: "uppercase",
3115
+ ...normalizeParams(params)
3116
+ });
3117
+ }
3118
+ /* @__NO_SIDE_EFFECTS__ */
3119
+ function _includes(includes, params) {
3120
+ return new $ZodCheckIncludes({
3121
+ check: "string_format",
3122
+ format: "includes",
3123
+ ...normalizeParams(params),
3124
+ includes
3125
+ });
3126
+ }
3127
+ /* @__NO_SIDE_EFFECTS__ */
3128
+ function _startsWith(prefix, params) {
3129
+ return new $ZodCheckStartsWith({
3130
+ check: "string_format",
3131
+ format: "starts_with",
3132
+ ...normalizeParams(params),
3133
+ prefix
3134
+ });
3135
+ }
3136
+ /* @__NO_SIDE_EFFECTS__ */
3137
+ function _endsWith(suffix, params) {
3138
+ return new $ZodCheckEndsWith({
3139
+ check: "string_format",
3140
+ format: "ends_with",
3141
+ ...normalizeParams(params),
3142
+ suffix
3143
+ });
3144
+ }
3145
+ /* @__NO_SIDE_EFFECTS__ */
1253
3146
  function _overwrite(tx) {
1254
3147
  return new $ZodCheckOverwrite({
1255
3148
  check: "overwrite",
@@ -1257,6 +3150,26 @@ function _overwrite(tx) {
1257
3150
  });
1258
3151
  }
1259
3152
  /* @__NO_SIDE_EFFECTS__ */
3153
+ function _normalize(form) {
3154
+ return /* @__PURE__ */ _overwrite((input) => input.normalize(form));
3155
+ }
3156
+ /* @__NO_SIDE_EFFECTS__ */
3157
+ function _trim() {
3158
+ return /* @__PURE__ */ _overwrite((input) => input.trim());
3159
+ }
3160
+ /* @__NO_SIDE_EFFECTS__ */
3161
+ function _toLowerCase() {
3162
+ return /* @__PURE__ */ _overwrite((input) => input.toLowerCase());
3163
+ }
3164
+ /* @__NO_SIDE_EFFECTS__ */
3165
+ function _toUpperCase() {
3166
+ return /* @__PURE__ */ _overwrite((input) => input.toUpperCase());
3167
+ }
3168
+ /* @__NO_SIDE_EFFECTS__ */
3169
+ function _slugify() {
3170
+ return /* @__PURE__ */ _overwrite((input) => slugify(input));
3171
+ }
3172
+ /* @__NO_SIDE_EFFECTS__ */
1260
3173
  function _array(Class, element, params) {
1261
3174
  return new Class({
1262
3175
  type: "array",
@@ -2100,53 +4013,35 @@ let AIAgentExecutionHelpersFactory = class AIAgentExecutionHelpersFactory$1 {
2100
4013
  createConnectionCredentialExecutionContextFactory(credentialSessions) {
2101
4014
  return new ConnectionCredentialExecutionContextFactory(credentialSessions);
2102
4015
  }
2103
- createDynamicStructuredTool(entry, toolCredentialContext, item, itemIndex, items) {
2104
- if (entry.runtime.inputSchema == null) throw new Error(`Cannot create LangChain tool "${entry.config.name}": missing inputSchema (broken tool runtime resolution).`);
2105
- const schemaForOpenAi = this.createJsonSchemaRecord(entry.runtime.inputSchema, {
2106
- schemaName: entry.config.name,
2107
- requireObjectRoot: true
2108
- });
2109
- return new DynamicStructuredTool({
2110
- name: entry.config.name,
2111
- description: entry.config.description ?? entry.runtime.defaultDescription,
2112
- schema: schemaForOpenAi,
2113
- func: async (input) => {
2114
- const result = await entry.runtime.execute({
2115
- config: entry.config,
2116
- input,
2117
- ctx: toolCredentialContext,
2118
- item,
2119
- itemIndex,
2120
- items
2121
- });
2122
- return JSON.stringify(result);
2123
- }
2124
- });
2125
- }
2126
4016
  /**
2127
- * Produces a plain JSON Schema object for OpenAI tool parameters and LangChain tool invocation:
2128
- * - **Zod** `toJSONSchema(..., { target: "draft-07" })` so shapes match what `@cfworker/json-schema`
2129
- * expects (`required` must be an array; draft 2020-12 output can break validation).
2130
- * - Otherwise LangChain `toJsonSchema` (Standard Schema + JSON passthrough); if the result is still Zod
2131
- * (duplicate `zod` copies), fall back to Zod `toJSONSchema` with draft-07.
2132
- * - Strip root `$schema` for OpenAI; normalize invalid `required` keywords for cfworker; ensure `properties`.
4017
+ * Produces a plain JSON Schema object (`draft-07`) from a Zod schema, as needed by
4018
+ * OpenAI tool-parameter schemas and the structured-output repair prompt.
4019
+ * - Prefers the schema's **instance** `toJSONSchema(...)` method so we stay inside the Zod
4020
+ * instance that created the schema (works across consumer/framework tsx namespaces see
4021
+ * {@link ZodInstanceToJsonSchema}). Falls back to the framework-imported module function.
4022
+ * - Strips root `$schema` (OpenAI ignores it).
4023
+ * - Sanitizes `required` for cfworker json-schema compatibility (must be a string array or absent).
2133
4024
  */
2134
4025
  createJsonSchemaRecord(inputSchema, options) {
2135
- const draft07Params = { target: "draft-07" };
2136
- let converted;
2137
- if (isInteropZodSchema(inputSchema)) converted = toJSONSchema(inputSchema, draft07Params);
2138
- else {
2139
- converted = toJsonSchema(inputSchema);
2140
- if (isInteropZodSchema(converted)) converted = toJSONSchema(inputSchema, draft07Params);
2141
- }
2142
- const { $schema: _draftSchemaOmitted,...rest } = converted;
2143
- if (options.requireObjectRoot && rest.type !== "object") throw new Error(`Cannot create LangChain tool "${options.schemaName}": tool input schema must be a JSON Schema object type (got type=${String(rest.type)}).`);
2144
- if (options.requireObjectRoot && rest.properties !== void 0 && (typeof rest.properties !== "object" || Array.isArray(rest.properties))) throw new Error(`Cannot create LangChain tool "${options.schemaName}": tool input schema "properties" must be an object (got ${JSON.stringify(rest.properties)}).`);
4026
+ const { $schema: _draftSchemaOmitted,...rest } = this.convertZodSchemaToJsonSchema(inputSchema, { target: "draft-07" });
4027
+ if (options.requireObjectRoot && rest.type !== "object") throw new Error(`Cannot create tool "${options.schemaName}": tool input schema must be a JSON Schema object type (got type=${String(rest.type)}).`);
4028
+ if (options.requireObjectRoot && rest.properties !== void 0 && (typeof rest.properties !== "object" || Array.isArray(rest.properties))) throw new Error(`Cannot create tool "${options.schemaName}": tool input schema "properties" must be an object (got ${JSON.stringify(rest.properties)}).`);
2145
4029
  if (options.requireObjectRoot && rest.properties === void 0) rest.properties = {};
2146
4030
  this.sanitizeJsonSchemaRequiredKeywordsForCfworker(rest);
2147
4031
  return rest;
2148
4032
  }
2149
4033
  /**
4034
+ * Runs Zod's `toJSONSchema` via the schema's own instance method when available, so consumer
4035
+ * schemas loaded under a different tsx namespace still convert correctly. If the caller handed us
4036
+ * a payload that lacks that method (e.g. a plain JSON Schema record or a Zod instance whose
4037
+ * prototype was stripped), we fall back to the framework-bundled module function.
4038
+ */
4039
+ convertZodSchemaToJsonSchema(inputSchema, params) {
4040
+ const candidate = inputSchema.toJSONSchema;
4041
+ if (typeof candidate === "function") return candidate.call(inputSchema, params);
4042
+ return toJSONSchema(inputSchema, params);
4043
+ }
4044
+ /**
2150
4045
  * `@cfworker/json-schema` iterates `schema.required` with `for...of`; it must be a string array or absent.
2151
4046
  */
2152
4047
  sanitizeJsonSchemaRequiredKeywordsForCfworker(node$1) {
@@ -2193,6 +4088,214 @@ function __decorateParam(paramIndex, decorator) {
2193
4088
  };
2194
4089
  }
2195
4090
 
4091
+ //#endregion
4092
+ //#region src/chatModels/OpenAiStrictJsonSchemaFactory.ts
4093
+ var _ref$5;
4094
+ let OpenAiStrictJsonSchemaFactory = class OpenAiStrictJsonSchemaFactory$1 {
4095
+ constructor(executionHelpers) {
4096
+ this.executionHelpers = executionHelpers;
4097
+ }
4098
+ createStructuredOutputRecord(schema, options) {
4099
+ const record$1 = this.executionHelpers.createJsonSchemaRecord(schema, {
4100
+ schemaName: options.schemaName,
4101
+ requireObjectRoot: false
4102
+ });
4103
+ this.strictifyRecursive(record$1);
4104
+ if (options.title !== void 0) record$1.title = options.title;
4105
+ return record$1;
4106
+ }
4107
+ strictifyRecursive(node$1) {
4108
+ if (!node$1 || typeof node$1 !== "object" || Array.isArray(node$1)) return;
4109
+ const o = node$1;
4110
+ this.stripOpenAiRejectedKeywords(o);
4111
+ if (this.isObjectNode(o)) {
4112
+ const props = this.readPropertiesObject(o);
4113
+ o.properties = props;
4114
+ o.additionalProperties = false;
4115
+ o.required = Object.keys(props);
4116
+ for (const value of Object.values(props)) this.strictifyRecursive(value);
4117
+ }
4118
+ this.recurseIntoComposites(o);
4119
+ }
4120
+ stripOpenAiRejectedKeywords(o) {
4121
+ delete o["$schema"];
4122
+ delete o["unevaluatedProperties"];
4123
+ delete o["default"];
4124
+ }
4125
+ isObjectNode(o) {
4126
+ const typeIsObject = o.type === "object" || Array.isArray(o.type) && o.type.includes("object");
4127
+ const hasObjectProperties = o.properties !== void 0 && typeof o.properties === "object" && !Array.isArray(o.properties);
4128
+ return typeIsObject || hasObjectProperties;
4129
+ }
4130
+ readPropertiesObject(o) {
4131
+ if (o.properties && typeof o.properties === "object" && !Array.isArray(o.properties)) return o.properties;
4132
+ return {};
4133
+ }
4134
+ recurseIntoComposites(o) {
4135
+ for (const key of [
4136
+ "allOf",
4137
+ "anyOf",
4138
+ "oneOf",
4139
+ "prefixItems"
4140
+ ]) {
4141
+ const branch = o[key];
4142
+ if (Array.isArray(branch)) for (const sub of branch) this.strictifyRecursive(sub);
4143
+ }
4144
+ if (o.not) this.strictifyRecursive(o.not);
4145
+ if (o.items) if (Array.isArray(o.items)) for (const sub of o.items) this.strictifyRecursive(sub);
4146
+ else this.strictifyRecursive(o.items);
4147
+ for (const key of [
4148
+ "if",
4149
+ "then",
4150
+ "else"
4151
+ ]) if (o[key]) this.strictifyRecursive(o[key]);
4152
+ for (const key of ["$defs", "definitions"]) {
4153
+ const defs = o[key];
4154
+ if (defs && typeof defs === "object" && !Array.isArray(defs)) for (const sub of Object.values(defs)) this.strictifyRecursive(sub);
4155
+ }
4156
+ }
4157
+ };
4158
+ OpenAiStrictJsonSchemaFactory = __decorate([
4159
+ injectable(),
4160
+ __decorateParam(0, inject(AIAgentExecutionHelpersFactory)),
4161
+ __decorateMetadata("design:paramtypes", [typeof (_ref$5 = typeof AIAgentExecutionHelpersFactory !== "undefined" && AIAgentExecutionHelpersFactory) === "function" ? _ref$5 : Object])
4162
+ ], OpenAiStrictJsonSchemaFactory);
4163
+
4164
+ //#endregion
4165
+ //#region src/chatModels/openAiChatModelConfig.ts
4166
+ var OpenAIChatModelConfig = class {
4167
+ type = OpenAIChatModelFactory;
4168
+ presentation;
4169
+ provider = "openai";
4170
+ modelName;
4171
+ constructor(name, model, credentialSlotKey = "openai", presentationIn, options) {
4172
+ this.name = name;
4173
+ this.model = model;
4174
+ this.credentialSlotKey = credentialSlotKey;
4175
+ this.options = options;
4176
+ this.modelName = model;
4177
+ this.presentation = presentationIn ?? {
4178
+ icon: "builtin:openai",
4179
+ label: name
4180
+ };
4181
+ }
4182
+ getCredentialRequirements() {
4183
+ return [{
4184
+ slotKey: this.credentialSlotKey,
4185
+ label: "OpenAI API key",
4186
+ acceptedTypes: ["openai.apiKey"]
4187
+ }];
4188
+ }
4189
+ };
4190
+
4191
+ //#endregion
4192
+ //#region src/chatModels/OpenAiChatModelPresetsFactory.ts
4193
+ /**
4194
+ * Default OpenAI chat model configs for scaffolds and demos (icon + label match {@link OpenAIChatModelConfig} defaults).
4195
+ * Prefer importing {@link openAiChatModelPresets} from here or from the consumer template re-export
4196
+ * instead of repeating {@link OpenAIChatModelConfig} construction in app workflows.
4197
+ */
4198
+ var OpenAiChatModelPresets = class {
4199
+ demoGpt4oMini = new OpenAIChatModelConfig("OpenAI", "gpt-4o-mini");
4200
+ demoGpt41 = new OpenAIChatModelConfig("OpenAI", "gpt-4.1");
4201
+ };
4202
+ const openAiChatModelPresets = new OpenAiChatModelPresets();
4203
+
4204
+ //#endregion
4205
+ //#region src/nodes/AgentMessageFactory.ts
4206
+ /**
4207
+ * AI-SDK-shaped message construction for the AIAgent stack. Emits plain `ModelMessage[]`
4208
+ * ( `{ role: 'system' | 'user' | 'assistant' | 'tool', content: ... }` ) as consumed by
4209
+ * `generateText({ messages })` from the `ai` package.
4210
+ */
4211
+ var AgentMessageFactory = class AgentMessageFactory {
4212
+ static createPromptMessages(messages) {
4213
+ return messages.map((message) => this.createPromptMessage(message));
4214
+ }
4215
+ /**
4216
+ * Builds the assistant message that contains optional text plus one or more tool-call parts,
4217
+ * matching the shape AI SDK emits between steps.
4218
+ */
4219
+ static createAssistantWithToolCalls(text, toolCalls) {
4220
+ const content = [];
4221
+ if (text && text.length > 0) content.push({
4222
+ type: "text",
4223
+ text
4224
+ });
4225
+ for (const toolCall of toolCalls) content.push({
4226
+ type: "tool-call",
4227
+ toolCallId: toolCall.id ?? toolCall.name,
4228
+ toolName: toolCall.name,
4229
+ input: toolCall.input ?? {}
4230
+ });
4231
+ return {
4232
+ role: "assistant",
4233
+ content
4234
+ };
4235
+ }
4236
+ /**
4237
+ * Builds the `{ role: "tool", content: [{ type: "tool-result", ... }, ...] }` message returned
4238
+ * to the model after each tool round.
4239
+ */
4240
+ static createToolResultsMessage(executedToolCalls) {
4241
+ return {
4242
+ role: "tool",
4243
+ content: executedToolCalls.map((executed) => ({
4244
+ type: "tool-result",
4245
+ toolCallId: executed.toolCallId,
4246
+ toolName: executed.toolName,
4247
+ output: {
4248
+ type: "json",
4249
+ value: AgentMessageFactory.toToolResultJson(executed.result)
4250
+ }
4251
+ }))
4252
+ };
4253
+ }
4254
+ static toToolResultJson(value) {
4255
+ if (value === void 0) return null;
4256
+ try {
4257
+ return JSON.parse(JSON.stringify(value));
4258
+ } catch {
4259
+ return String(value);
4260
+ }
4261
+ }
4262
+ static createPromptMessage(message) {
4263
+ if (message.role === "system") return {
4264
+ role: "system",
4265
+ content: message.content
4266
+ };
4267
+ if (message.role === "assistant") return {
4268
+ role: "assistant",
4269
+ content: message.content
4270
+ };
4271
+ return {
4272
+ role: "user",
4273
+ content: message.content
4274
+ };
4275
+ }
4276
+ };
4277
+
4278
+ //#endregion
4279
+ //#region src/nodes/AgentOutputFactory.ts
4280
+ var AgentOutputFactory = class {
4281
+ static fromUnknown(value) {
4282
+ return { main: [{ json: value }] };
4283
+ }
4284
+ static replaceJson(item, value) {
4285
+ return {
4286
+ ...item,
4287
+ json: value
4288
+ };
4289
+ }
4290
+ static fromAgentContent(content) {
4291
+ try {
4292
+ return JSON.parse(content);
4293
+ } catch {
4294
+ return { output: content };
4295
+ }
4296
+ }
4297
+ };
4298
+
2196
4299
  //#endregion
2197
4300
  //#region src/nodes/AgentStructuredOutputRepairPromptFactory.ts
2198
4301
  var _ref$4, _AgentStructuredOutputRepairPromptFactory;
@@ -2233,6 +4336,37 @@ AgentStructuredOutputRepairPromptFactory = _AgentStructuredOutputRepairPromptFac
2233
4336
  __decorateMetadata("design:paramtypes", [typeof (_ref$4 = typeof AIAgentExecutionHelpersFactory !== "undefined" && AIAgentExecutionHelpersFactory) === "function" ? _ref$4 : Object])
2234
4337
  ], AgentStructuredOutputRepairPromptFactory);
2235
4338
 
4339
+ //#endregion
4340
+ //#region ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/iso.js
4341
+ const ZodISODateTime = /* @__PURE__ */ $constructor("ZodISODateTime", (inst, def) => {
4342
+ $ZodISODateTime.init(inst, def);
4343
+ ZodStringFormat.init(inst, def);
4344
+ });
4345
+ function datetime(params) {
4346
+ return _isoDateTime(ZodISODateTime, params);
4347
+ }
4348
+ const ZodISODate = /* @__PURE__ */ $constructor("ZodISODate", (inst, def) => {
4349
+ $ZodISODate.init(inst, def);
4350
+ ZodStringFormat.init(inst, def);
4351
+ });
4352
+ function date(params) {
4353
+ return _isoDate(ZodISODate, params);
4354
+ }
4355
+ const ZodISOTime = /* @__PURE__ */ $constructor("ZodISOTime", (inst, def) => {
4356
+ $ZodISOTime.init(inst, def);
4357
+ ZodStringFormat.init(inst, def);
4358
+ });
4359
+ function time(params) {
4360
+ return _isoTime(ZodISOTime, params);
4361
+ }
4362
+ const ZodISODuration = /* @__PURE__ */ $constructor("ZodISODuration", (inst, def) => {
4363
+ $ZodISODuration.init(inst, def);
4364
+ ZodStringFormat.init(inst, def);
4365
+ });
4366
+ function duration(params) {
4367
+ return _isoDuration(ZodISODuration, params);
4368
+ }
4369
+
2236
4370
  //#endregion
2237
4371
  //#region ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/errors.js
2238
4372
  const initializer = (inst, issues) => {
@@ -2350,6 +4484,181 @@ const ZodType = /* @__PURE__ */ $constructor("ZodType", (inst, def) => {
2350
4484
  inst.apply = (fn) => fn(inst);
2351
4485
  return inst;
2352
4486
  });
4487
+ /** @internal */
4488
+ const _ZodString = /* @__PURE__ */ $constructor("_ZodString", (inst, def) => {
4489
+ $ZodString.init(inst, def);
4490
+ ZodType.init(inst, def);
4491
+ inst._zod.processJSONSchema = (ctx, json, params) => stringProcessor(inst, ctx, json, params);
4492
+ const bag = inst._zod.bag;
4493
+ inst.format = bag.format ?? null;
4494
+ inst.minLength = bag.minimum ?? null;
4495
+ inst.maxLength = bag.maximum ?? null;
4496
+ inst.regex = (...args) => inst.check(_regex(...args));
4497
+ inst.includes = (...args) => inst.check(_includes(...args));
4498
+ inst.startsWith = (...args) => inst.check(_startsWith(...args));
4499
+ inst.endsWith = (...args) => inst.check(_endsWith(...args));
4500
+ inst.min = (...args) => inst.check(_minLength(...args));
4501
+ inst.max = (...args) => inst.check(_maxLength(...args));
4502
+ inst.length = (...args) => inst.check(_length(...args));
4503
+ inst.nonempty = (...args) => inst.check(_minLength(1, ...args));
4504
+ inst.lowercase = (params) => inst.check(_lowercase(params));
4505
+ inst.uppercase = (params) => inst.check(_uppercase(params));
4506
+ inst.trim = () => inst.check(_trim());
4507
+ inst.normalize = (...args) => inst.check(_normalize(...args));
4508
+ inst.toLowerCase = () => inst.check(_toLowerCase());
4509
+ inst.toUpperCase = () => inst.check(_toUpperCase());
4510
+ inst.slugify = () => inst.check(_slugify());
4511
+ });
4512
+ const ZodString = /* @__PURE__ */ $constructor("ZodString", (inst, def) => {
4513
+ $ZodString.init(inst, def);
4514
+ _ZodString.init(inst, def);
4515
+ inst.email = (params) => inst.check(_email(ZodEmail, params));
4516
+ inst.url = (params) => inst.check(_url(ZodURL, params));
4517
+ inst.jwt = (params) => inst.check(_jwt(ZodJWT, params));
4518
+ inst.emoji = (params) => inst.check(_emoji(ZodEmoji, params));
4519
+ inst.guid = (params) => inst.check(_guid(ZodGUID, params));
4520
+ inst.uuid = (params) => inst.check(_uuid(ZodUUID, params));
4521
+ inst.uuidv4 = (params) => inst.check(_uuidv4(ZodUUID, params));
4522
+ inst.uuidv6 = (params) => inst.check(_uuidv6(ZodUUID, params));
4523
+ inst.uuidv7 = (params) => inst.check(_uuidv7(ZodUUID, params));
4524
+ inst.nanoid = (params) => inst.check(_nanoid(ZodNanoID, params));
4525
+ inst.guid = (params) => inst.check(_guid(ZodGUID, params));
4526
+ inst.cuid = (params) => inst.check(_cuid(ZodCUID, params));
4527
+ inst.cuid2 = (params) => inst.check(_cuid2(ZodCUID2, params));
4528
+ inst.ulid = (params) => inst.check(_ulid(ZodULID, params));
4529
+ inst.base64 = (params) => inst.check(_base64(ZodBase64, params));
4530
+ inst.base64url = (params) => inst.check(_base64url(ZodBase64URL, params));
4531
+ inst.xid = (params) => inst.check(_xid(ZodXID, params));
4532
+ inst.ksuid = (params) => inst.check(_ksuid(ZodKSUID, params));
4533
+ inst.ipv4 = (params) => inst.check(_ipv4(ZodIPv4, params));
4534
+ inst.ipv6 = (params) => inst.check(_ipv6(ZodIPv6, params));
4535
+ inst.cidrv4 = (params) => inst.check(_cidrv4(ZodCIDRv4, params));
4536
+ inst.cidrv6 = (params) => inst.check(_cidrv6(ZodCIDRv6, params));
4537
+ inst.e164 = (params) => inst.check(_e164(ZodE164, params));
4538
+ inst.datetime = (params) => inst.check(datetime(params));
4539
+ inst.date = (params) => inst.check(date(params));
4540
+ inst.time = (params) => inst.check(time(params));
4541
+ inst.duration = (params) => inst.check(duration(params));
4542
+ });
4543
+ function string(params) {
4544
+ return _string(ZodString, params);
4545
+ }
4546
+ const ZodStringFormat = /* @__PURE__ */ $constructor("ZodStringFormat", (inst, def) => {
4547
+ $ZodStringFormat.init(inst, def);
4548
+ _ZodString.init(inst, def);
4549
+ });
4550
+ const ZodEmail = /* @__PURE__ */ $constructor("ZodEmail", (inst, def) => {
4551
+ $ZodEmail.init(inst, def);
4552
+ ZodStringFormat.init(inst, def);
4553
+ });
4554
+ const ZodGUID = /* @__PURE__ */ $constructor("ZodGUID", (inst, def) => {
4555
+ $ZodGUID.init(inst, def);
4556
+ ZodStringFormat.init(inst, def);
4557
+ });
4558
+ const ZodUUID = /* @__PURE__ */ $constructor("ZodUUID", (inst, def) => {
4559
+ $ZodUUID.init(inst, def);
4560
+ ZodStringFormat.init(inst, def);
4561
+ });
4562
+ const ZodURL = /* @__PURE__ */ $constructor("ZodURL", (inst, def) => {
4563
+ $ZodURL.init(inst, def);
4564
+ ZodStringFormat.init(inst, def);
4565
+ });
4566
+ const ZodEmoji = /* @__PURE__ */ $constructor("ZodEmoji", (inst, def) => {
4567
+ $ZodEmoji.init(inst, def);
4568
+ ZodStringFormat.init(inst, def);
4569
+ });
4570
+ const ZodNanoID = /* @__PURE__ */ $constructor("ZodNanoID", (inst, def) => {
4571
+ $ZodNanoID.init(inst, def);
4572
+ ZodStringFormat.init(inst, def);
4573
+ });
4574
+ const ZodCUID = /* @__PURE__ */ $constructor("ZodCUID", (inst, def) => {
4575
+ $ZodCUID.init(inst, def);
4576
+ ZodStringFormat.init(inst, def);
4577
+ });
4578
+ const ZodCUID2 = /* @__PURE__ */ $constructor("ZodCUID2", (inst, def) => {
4579
+ $ZodCUID2.init(inst, def);
4580
+ ZodStringFormat.init(inst, def);
4581
+ });
4582
+ const ZodULID = /* @__PURE__ */ $constructor("ZodULID", (inst, def) => {
4583
+ $ZodULID.init(inst, def);
4584
+ ZodStringFormat.init(inst, def);
4585
+ });
4586
+ const ZodXID = /* @__PURE__ */ $constructor("ZodXID", (inst, def) => {
4587
+ $ZodXID.init(inst, def);
4588
+ ZodStringFormat.init(inst, def);
4589
+ });
4590
+ const ZodKSUID = /* @__PURE__ */ $constructor("ZodKSUID", (inst, def) => {
4591
+ $ZodKSUID.init(inst, def);
4592
+ ZodStringFormat.init(inst, def);
4593
+ });
4594
+ const ZodIPv4 = /* @__PURE__ */ $constructor("ZodIPv4", (inst, def) => {
4595
+ $ZodIPv4.init(inst, def);
4596
+ ZodStringFormat.init(inst, def);
4597
+ });
4598
+ const ZodIPv6 = /* @__PURE__ */ $constructor("ZodIPv6", (inst, def) => {
4599
+ $ZodIPv6.init(inst, def);
4600
+ ZodStringFormat.init(inst, def);
4601
+ });
4602
+ const ZodCIDRv4 = /* @__PURE__ */ $constructor("ZodCIDRv4", (inst, def) => {
4603
+ $ZodCIDRv4.init(inst, def);
4604
+ ZodStringFormat.init(inst, def);
4605
+ });
4606
+ const ZodCIDRv6 = /* @__PURE__ */ $constructor("ZodCIDRv6", (inst, def) => {
4607
+ $ZodCIDRv6.init(inst, def);
4608
+ ZodStringFormat.init(inst, def);
4609
+ });
4610
+ const ZodBase64 = /* @__PURE__ */ $constructor("ZodBase64", (inst, def) => {
4611
+ $ZodBase64.init(inst, def);
4612
+ ZodStringFormat.init(inst, def);
4613
+ });
4614
+ const ZodBase64URL = /* @__PURE__ */ $constructor("ZodBase64URL", (inst, def) => {
4615
+ $ZodBase64URL.init(inst, def);
4616
+ ZodStringFormat.init(inst, def);
4617
+ });
4618
+ const ZodE164 = /* @__PURE__ */ $constructor("ZodE164", (inst, def) => {
4619
+ $ZodE164.init(inst, def);
4620
+ ZodStringFormat.init(inst, def);
4621
+ });
4622
+ const ZodJWT = /* @__PURE__ */ $constructor("ZodJWT", (inst, def) => {
4623
+ $ZodJWT.init(inst, def);
4624
+ ZodStringFormat.init(inst, def);
4625
+ });
4626
+ const ZodNumber = /* @__PURE__ */ $constructor("ZodNumber", (inst, def) => {
4627
+ $ZodNumber.init(inst, def);
4628
+ ZodType.init(inst, def);
4629
+ inst._zod.processJSONSchema = (ctx, json, params) => numberProcessor(inst, ctx, json, params);
4630
+ inst.gt = (value, params) => inst.check(_gt(value, params));
4631
+ inst.gte = (value, params) => inst.check(_gte(value, params));
4632
+ inst.min = (value, params) => inst.check(_gte(value, params));
4633
+ inst.lt = (value, params) => inst.check(_lt(value, params));
4634
+ inst.lte = (value, params) => inst.check(_lte(value, params));
4635
+ inst.max = (value, params) => inst.check(_lte(value, params));
4636
+ inst.int = (params) => inst.check(int(params));
4637
+ inst.safe = (params) => inst.check(int(params));
4638
+ inst.positive = (params) => inst.check(_gt(0, params));
4639
+ inst.nonnegative = (params) => inst.check(_gte(0, params));
4640
+ inst.negative = (params) => inst.check(_lt(0, params));
4641
+ inst.nonpositive = (params) => inst.check(_lte(0, params));
4642
+ inst.multipleOf = (value, params) => inst.check(_multipleOf(value, params));
4643
+ inst.step = (value, params) => inst.check(_multipleOf(value, params));
4644
+ inst.finite = () => inst;
4645
+ const bag = inst._zod.bag;
4646
+ inst.minValue = Math.max(bag.minimum ?? Number.NEGATIVE_INFINITY, bag.exclusiveMinimum ?? Number.NEGATIVE_INFINITY) ?? null;
4647
+ inst.maxValue = Math.min(bag.maximum ?? Number.POSITIVE_INFINITY, bag.exclusiveMaximum ?? Number.POSITIVE_INFINITY) ?? null;
4648
+ inst.isInt = (bag.format ?? "").includes("int") || Number.isSafeInteger(bag.multipleOf ?? .5);
4649
+ inst.isFinite = true;
4650
+ inst.format = bag.format ?? null;
4651
+ });
4652
+ function number(params) {
4653
+ return _number(ZodNumber, params);
4654
+ }
4655
+ const ZodNumberFormat = /* @__PURE__ */ $constructor("ZodNumberFormat", (inst, def) => {
4656
+ $ZodNumberFormat.init(inst, def);
4657
+ ZodNumber.init(inst, def);
4658
+ });
4659
+ function int(params) {
4660
+ return _int(ZodNumberFormat, params);
4661
+ }
2353
4662
  const ZodUnknown = /* @__PURE__ */ $constructor("ZodUnknown", (inst, def) => {
2354
4663
  $ZodUnknown.init(inst, def);
2355
4664
  ZodType.init(inst, def);
@@ -2358,6 +4667,14 @@ const ZodUnknown = /* @__PURE__ */ $constructor("ZodUnknown", (inst, def) => {
2358
4667
  function unknown() {
2359
4668
  return _unknown(ZodUnknown);
2360
4669
  }
4670
+ const ZodNever = /* @__PURE__ */ $constructor("ZodNever", (inst, def) => {
4671
+ $ZodNever.init(inst, def);
4672
+ ZodType.init(inst, def);
4673
+ inst._zod.processJSONSchema = (ctx, json, params) => neverProcessor(inst, ctx, json, params);
4674
+ });
4675
+ function never(params) {
4676
+ return _never(ZodNever, params);
4677
+ }
2361
4678
  const ZodArray = /* @__PURE__ */ $constructor("ZodArray", (inst, def) => {
2362
4679
  $ZodArray.init(inst, def);
2363
4680
  ZodType.init(inst, def);
@@ -2372,6 +4689,53 @@ const ZodArray = /* @__PURE__ */ $constructor("ZodArray", (inst, def) => {
2372
4689
  function array(element, params) {
2373
4690
  return _array(ZodArray, element, params);
2374
4691
  }
4692
+ const ZodObject = /* @__PURE__ */ $constructor("ZodObject", (inst, def) => {
4693
+ $ZodObjectJIT.init(inst, def);
4694
+ ZodType.init(inst, def);
4695
+ inst._zod.processJSONSchema = (ctx, json, params) => objectProcessor(inst, ctx, json, params);
4696
+ defineLazy(inst, "shape", () => {
4697
+ return def.shape;
4698
+ });
4699
+ inst.keyof = () => _enum(Object.keys(inst._zod.def.shape));
4700
+ inst.catchall = (catchall) => inst.clone({
4701
+ ...inst._zod.def,
4702
+ catchall
4703
+ });
4704
+ inst.passthrough = () => inst.clone({
4705
+ ...inst._zod.def,
4706
+ catchall: unknown()
4707
+ });
4708
+ inst.loose = () => inst.clone({
4709
+ ...inst._zod.def,
4710
+ catchall: unknown()
4711
+ });
4712
+ inst.strict = () => inst.clone({
4713
+ ...inst._zod.def,
4714
+ catchall: never()
4715
+ });
4716
+ inst.strip = () => inst.clone({
4717
+ ...inst._zod.def,
4718
+ catchall: void 0
4719
+ });
4720
+ inst.extend = (incoming) => {
4721
+ return extend(inst, incoming);
4722
+ };
4723
+ inst.safeExtend = (incoming) => {
4724
+ return safeExtend(inst, incoming);
4725
+ };
4726
+ inst.merge = (other) => merge(inst, other);
4727
+ inst.pick = (mask) => pick(inst, mask);
4728
+ inst.omit = (mask) => omit(inst, mask);
4729
+ inst.partial = (...args) => partial(ZodOptional, inst, args[0]);
4730
+ inst.required = (...args) => required(ZodNonOptional, inst, args[0]);
4731
+ });
4732
+ function object(shape, params) {
4733
+ return new ZodObject({
4734
+ type: "object",
4735
+ shape: shape ?? {},
4736
+ ...normalizeParams(params)
4737
+ });
4738
+ }
2375
4739
  const ZodUnion = /* @__PURE__ */ $constructor("ZodUnion", (inst, def) => {
2376
4740
  $ZodUnion.init(inst, def);
2377
4741
  ZodType.init(inst, def);
@@ -2397,6 +4761,58 @@ function intersection(left, right) {
2397
4761
  right
2398
4762
  });
2399
4763
  }
4764
+ const ZodRecord = /* @__PURE__ */ $constructor("ZodRecord", (inst, def) => {
4765
+ $ZodRecord.init(inst, def);
4766
+ ZodType.init(inst, def);
4767
+ inst._zod.processJSONSchema = (ctx, json, params) => recordProcessor(inst, ctx, json, params);
4768
+ inst.keyType = def.keyType;
4769
+ inst.valueType = def.valueType;
4770
+ });
4771
+ function record(keyType, valueType, params) {
4772
+ return new ZodRecord({
4773
+ type: "record",
4774
+ keyType,
4775
+ valueType,
4776
+ ...normalizeParams(params)
4777
+ });
4778
+ }
4779
+ const ZodEnum = /* @__PURE__ */ $constructor("ZodEnum", (inst, def) => {
4780
+ $ZodEnum.init(inst, def);
4781
+ ZodType.init(inst, def);
4782
+ inst._zod.processJSONSchema = (ctx, json, params) => enumProcessor(inst, ctx, json, params);
4783
+ inst.enum = def.entries;
4784
+ inst.options = Object.values(def.entries);
4785
+ const keys = new Set(Object.keys(def.entries));
4786
+ inst.extract = (values, params) => {
4787
+ const newEntries = {};
4788
+ for (const value of values) if (keys.has(value)) newEntries[value] = def.entries[value];
4789
+ else throw new Error(`Key ${value} not found in enum`);
4790
+ return new ZodEnum({
4791
+ ...def,
4792
+ checks: [],
4793
+ ...normalizeParams(params),
4794
+ entries: newEntries
4795
+ });
4796
+ };
4797
+ inst.exclude = (values, params) => {
4798
+ const newEntries = { ...def.entries };
4799
+ for (const value of values) if (keys.has(value)) delete newEntries[value];
4800
+ else throw new Error(`Key ${value} not found in enum`);
4801
+ return new ZodEnum({
4802
+ ...def,
4803
+ checks: [],
4804
+ ...normalizeParams(params),
4805
+ entries: newEntries
4806
+ });
4807
+ };
4808
+ });
4809
+ function _enum(values, params) {
4810
+ return new ZodEnum({
4811
+ type: "enum",
4812
+ entries: Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values,
4813
+ ...normalizeParams(params)
4814
+ });
4815
+ }
2400
4816
  const ZodTransform = /* @__PURE__ */ $constructor("ZodTransform", (inst, def) => {
2401
4817
  $ZodTransform.init(inst, def);
2402
4818
  ZodType.init(inst, def);
@@ -2571,31 +4987,26 @@ let AgentStructuredOutputRunner = class AgentStructuredOutputRunner$1 {
2571
4987
  _AgentStructuredOutputRunner = this;
2572
4988
  }
2573
4989
  static repairAttemptCount = 2;
2574
- constructor(repairPromptFactory, openAiStructuredOutputMethodFactory) {
4990
+ static structuredOutputSchemaName = "agent_output";
4991
+ constructor(repairPromptFactory, openAiStrictJsonSchemaFactory) {
2575
4992
  this.repairPromptFactory = repairPromptFactory;
2576
- this.openAiStructuredOutputMethodFactory = openAiStructuredOutputMethodFactory;
4993
+ this.openAiStrictJsonSchemaFactory = openAiStrictJsonSchemaFactory;
2577
4994
  }
2578
4995
  async resolve(args) {
2579
4996
  let lastFailure;
2580
- if (args.rawFinalResponse) {
2581
- const directResult = this.tryParseAndValidate(AgentMessageFactory.extractContent(args.rawFinalResponse), args.schema);
2582
- if (directResult.ok) return directResult.value;
2583
- lastFailure = directResult;
2584
- } else if (!this.supportsNativeStructuredOutput(args.model)) {
2585
- const rawResponse = await args.invokeTextModel(args.conversation);
2586
- const directResult = this.tryParseAndValidate(AgentMessageFactory.extractContent(rawResponse), args.schema);
4997
+ if (args.rawFinalText !== void 0) {
4998
+ const directResult = this.tryParseAndValidate(args.rawFinalText, args.schema);
2587
4999
  if (directResult.ok) return directResult.value;
2588
5000
  lastFailure = directResult;
2589
5001
  }
2590
5002
  try {
2591
- const nativeStructuredModel = this.createStructuredOutputModel(args.model, args.chatModelConfig, args.schema);
2592
- if (nativeStructuredModel) {
2593
- const nativeResult = this.tryValidateStructuredValue(await args.invokeStructuredModel(nativeStructuredModel, args.conversation), args.schema);
2594
- if (nativeResult.ok) return nativeResult.value;
2595
- lastFailure = nativeResult;
2596
- }
5003
+ const structuredOptions = this.resolveStructuredOutputOptions(args.chatModelConfig);
5004
+ const schemaForModel = this.resolveOutputSchemaForModel(args.schema, structuredOptions);
5005
+ const nativeResult = this.tryValidateStructuredValue(await args.invokeStructuredModel(schemaForModel, args.conversation, structuredOptions), args.schema);
5006
+ if (nativeResult.ok) return nativeResult.value;
5007
+ lastFailure = nativeResult;
2597
5008
  } catch (error) {
2598
- lastFailure = {
5009
+ lastFailure = lastFailure ?? {
2599
5010
  ok: false,
2600
5011
  invalidContent: "",
2601
5012
  validationError: `Native structured output failed: ${this.summarizeError(error)}`
@@ -2619,22 +5030,26 @@ let AgentStructuredOutputRunner = class AgentStructuredOutputRunner$1 {
2619
5030
  validationError: failure.validationError
2620
5031
  }))];
2621
5032
  const repairResponse = await args.invokeTextModel(repairMessages);
2622
- const repairResult = this.tryParseAndValidate(AgentMessageFactory.extractContent(repairResponse), args.schema);
5033
+ const repairResult = this.tryParseAndValidate(repairResponse.text, args.schema);
2623
5034
  if (repairResult.ok) return repairResult.value;
2624
5035
  failure = repairResult;
2625
5036
  }
2626
5037
  throw new Error(`Structured output required for AIAgent "${args.agentName}" (${args.nodeId}) but validation still failed after ${_AgentStructuredOutputRunner.repairAttemptCount} repair attempts: ${failure.validationError}`);
2627
5038
  }
2628
- createStructuredOutputModel(model, chatModelConfig, schema) {
2629
- if (!this.supportsNativeStructuredOutput(model)) return;
2630
- const options = this.getStructuredOutputOptions(chatModelConfig);
2631
- return model.withStructuredOutput(schema, options);
2632
- }
2633
- getStructuredOutputOptions(chatModelConfig) {
2634
- return this.openAiStructuredOutputMethodFactory.create(chatModelConfig) ?? { strict: true };
5039
+ /**
5040
+ * Chooses strict mode for OpenAI chat-model configs, off otherwise. Extendable in future for
5041
+ * other providers that adopt the same "supply a JSON Schema record directly" contract.
5042
+ */
5043
+ resolveStructuredOutputOptions(chatModelConfig) {
5044
+ if (chatModelConfig.type !== OpenAIChatModelFactory) return;
5045
+ return {
5046
+ strict: true,
5047
+ schemaName: _AgentStructuredOutputRunner.structuredOutputSchemaName
5048
+ };
2635
5049
  }
2636
- supportsNativeStructuredOutput(model) {
2637
- return typeof model.withStructuredOutput === "function";
5050
+ resolveOutputSchemaForModel(schema, options) {
5051
+ if (!options?.strict) return schema;
5052
+ return this.openAiStrictJsonSchemaFactory.createStructuredOutputRecord(schema, { schemaName: options.schemaName ?? _AgentStructuredOutputRunner.structuredOutputSchemaName });
2638
5053
  }
2639
5054
  tryParseAndValidate(content, schema) {
2640
5055
  try {
@@ -2668,7 +5083,7 @@ let AgentStructuredOutputRunner = class AgentStructuredOutputRunner$1 {
2668
5083
  }
2669
5084
  toJson(value) {
2670
5085
  try {
2671
- return JSON.stringify(value);
5086
+ return JSON.stringify(value) ?? String(value);
2672
5087
  } catch (error) {
2673
5088
  return `<<unserializable: ${this.summarizeError(error)}>>`;
2674
5089
  }
@@ -2677,8 +5092,8 @@ let AgentStructuredOutputRunner = class AgentStructuredOutputRunner$1 {
2677
5092
  AgentStructuredOutputRunner = _AgentStructuredOutputRunner = __decorate([
2678
5093
  injectable(),
2679
5094
  __decorateParam(0, inject(AgentStructuredOutputRepairPromptFactory)),
2680
- __decorateParam(1, inject(OpenAIStructuredOutputMethodFactory)),
2681
- __decorateMetadata("design:paramtypes", [typeof (_ref$3 = typeof AgentStructuredOutputRepairPromptFactory !== "undefined" && AgentStructuredOutputRepairPromptFactory) === "function" ? _ref$3 : Object, typeof (_ref2$3 = typeof OpenAIStructuredOutputMethodFactory !== "undefined" && OpenAIStructuredOutputMethodFactory) === "function" ? _ref2$3 : Object])
5095
+ __decorateParam(1, inject(OpenAiStrictJsonSchemaFactory)),
5096
+ __decorateMetadata("design:paramtypes", [typeof (_ref$3 = typeof AgentStructuredOutputRepairPromptFactory !== "undefined" && AgentStructuredOutputRepairPromptFactory) === "function" ? _ref$3 : Object, typeof (_ref2$3 = typeof OpenAiStrictJsonSchemaFactory !== "undefined" && OpenAiStrictJsonSchemaFactory) === "function" ? _ref2$3 : Object])
2682
5097
  ], AgentStructuredOutputRunner);
2683
5098
 
2684
5099
  //#endregion
@@ -2815,7 +5230,7 @@ let AgentToolExecutionCoordinator = class AgentToolExecutionCoordinator$1 {
2815
5230
  async executePlannedToolCall(args) {
2816
5231
  const { plannedToolCall, ctx } = args;
2817
5232
  const toolCallInputsByPort = AgentToolCallPortMap.fromInput(plannedToolCall.toolCall.input ?? {});
2818
- const invocationId = ConnectionInvocationIdFactory.create();
5233
+ const invocationId = plannedToolCall.invocationId;
2819
5234
  const startedAt = /* @__PURE__ */ new Date();
2820
5235
  const span = ctx.telemetry.startChildSpan({
2821
5236
  name: "agent.tool.call",
@@ -2823,7 +5238,10 @@ let AgentToolExecutionCoordinator = class AgentToolExecutionCoordinator$1 {
2823
5238
  startedAt,
2824
5239
  attributes: {
2825
5240
  [CodemationTelemetryAttributeNames.connectionInvocationId]: invocationId,
2826
- [CodemationTelemetryAttributeNames.toolName]: plannedToolCall.binding.config.name
5241
+ [CodemationTelemetryAttributeNames.toolName]: plannedToolCall.binding.config.name,
5242
+ ...ctx.iterationId ? { [CodemationTelemetryAttributeNames.iterationId]: ctx.iterationId } : {},
5243
+ ...typeof ctx.itemIndex === "number" ? { [CodemationTelemetryAttributeNames.iterationIndex]: ctx.itemIndex } : {},
5244
+ ...ctx.parentInvocationId ? { [CodemationTelemetryAttributeNames.parentInvocationId]: ctx.parentInvocationId } : {}
2827
5245
  }
2828
5246
  });
2829
5247
  await ctx.nodeState?.markRunning({
@@ -2831,9 +5249,24 @@ let AgentToolExecutionCoordinator = class AgentToolExecutionCoordinator$1 {
2831
5249
  activationId: ctx.activationId,
2832
5250
  inputsByPort: toolCallInputsByPort
2833
5251
  });
5252
+ await ctx.nodeState?.appendConnectionInvocation({
5253
+ invocationId,
5254
+ connectionNodeId: plannedToolCall.nodeId,
5255
+ parentAgentNodeId: ctx.nodeId,
5256
+ parentAgentActivationId: ctx.activationId,
5257
+ status: "running",
5258
+ managedInput: this.toJsonValue(plannedToolCall.toolCall.input),
5259
+ queuedAt: startedAt.toISOString(),
5260
+ startedAt: startedAt.toISOString(),
5261
+ iterationId: ctx.iterationId,
5262
+ parentInvocationId: ctx.parentInvocationId
5263
+ });
2834
5264
  try {
2835
- const serialized = await plannedToolCall.binding.langChainTool.invoke(plannedToolCall.toolCall.input ?? {});
2836
- const result = this.parseToolOutput(serialized);
5265
+ const result = await plannedToolCall.binding.execute(plannedToolCall.toolCall.input ?? {}, {
5266
+ parentSpan: span,
5267
+ parentInvocationId: invocationId
5268
+ });
5269
+ const serialized = typeof result === "string" ? result : JSON.stringify(result);
2837
5270
  const finishedAt = /* @__PURE__ */ new Date();
2838
5271
  await ctx.nodeState?.markCompleted({
2839
5272
  nodeId: plannedToolCall.nodeId,
@@ -2865,7 +5298,9 @@ let AgentToolExecutionCoordinator = class AgentToolExecutionCoordinator$1 {
2865
5298
  managedOutput: this.toJsonValue(result),
2866
5299
  queuedAt: startedAt.toISOString(),
2867
5300
  startedAt: startedAt.toISOString(),
2868
- finishedAt: finishedAt.toISOString()
5301
+ finishedAt: finishedAt.toISOString(),
5302
+ iterationId: ctx.iterationId,
5303
+ parentInvocationId: ctx.parentInvocationId
2869
5304
  });
2870
5305
  return {
2871
5306
  toolName: plannedToolCall.binding.config.name,
@@ -2877,7 +5312,7 @@ let AgentToolExecutionCoordinator = class AgentToolExecutionCoordinator$1 {
2877
5312
  const classification = this.errorClassifier.classify({
2878
5313
  error,
2879
5314
  toolName: plannedToolCall.binding.config.name,
2880
- schema: plannedToolCall.binding.langChainTool.schema
5315
+ schema: plannedToolCall.binding.inputSchema
2881
5316
  });
2882
5317
  if (classification.kind !== "repairable_validation_error") {
2883
5318
  const effectiveError = classification.effectiveError;
@@ -3006,7 +5441,9 @@ let AgentToolExecutionCoordinator = class AgentToolExecutionCoordinator$1 {
3006
5441
  },
3007
5442
  queuedAt: args.startedAt.toISOString(),
3008
5443
  startedAt: args.startedAt.toISOString(),
3009
- finishedAt: finishedAt.toISOString()
5444
+ finishedAt: finishedAt.toISOString(),
5445
+ iterationId: args.ctx.iterationId,
5446
+ parentInvocationId: args.ctx.parentInvocationId
3010
5447
  });
3011
5448
  }
3012
5449
  createRepairPayload(args) {
@@ -3040,14 +5477,6 @@ let AgentToolExecutionCoordinator = class AgentToolExecutionCoordinator$1 {
3040
5477
  if (!firstIssue) return `Your previous tool call for "${toolName}" was invalid and did not match the expected schema.`;
3041
5478
  return `Your previous tool call for "${toolName}" was invalid because field "${firstIssue.path.length > 0 ? firstIssue.path.join(".") : "<root>"}" failed validation: ${firstIssue.message}`;
3042
5479
  }
3043
- parseToolOutput(serialized) {
3044
- if (typeof serialized !== "string") return serialized;
3045
- try {
3046
- return JSON.parse(serialized);
3047
- } catch {
3048
- return serialized;
3049
- }
3050
- }
3051
5480
  toJsonValue(value) {
3052
5481
  if (value === void 0) return;
3053
5482
  return JSON.parse(JSON.stringify(value));
@@ -3075,13 +5504,14 @@ AgentToolExecutionCoordinator = __decorate([
3075
5504
 
3076
5505
  //#endregion
3077
5506
  //#region src/nodes/NodeBackedToolRuntime.ts
3078
- var _ref$1, _ref2$1, _ref3$1;
5507
+ var _ref$1, _ref2$1, _ref3$1, _ref4$1;
3079
5508
  let NodeBackedToolRuntime = class NodeBackedToolRuntime$1 {
3080
- constructor(nodeResolver, itemExprResolver, outputNormalizer, outputBehaviorResolver) {
5509
+ constructor(nodeResolver, itemExprResolver, outputNormalizer, outputBehaviorResolver, childExecutionScopeFactory) {
3081
5510
  this.nodeResolver = nodeResolver;
3082
5511
  this.itemExprResolver = itemExprResolver;
3083
5512
  this.outputNormalizer = outputNormalizer;
3084
5513
  this.outputBehaviorResolver = outputBehaviorResolver;
5514
+ this.childExecutionScopeFactory = childExecutionScopeFactory;
3085
5515
  }
3086
5516
  async execute(config$1, args) {
3087
5517
  const nodeInput = config$1.toNodeItem({
@@ -3092,10 +5522,7 @@ let NodeBackedToolRuntime = class NodeBackedToolRuntime$1 {
3092
5522
  ctx: args.ctx,
3093
5523
  node: config$1.node
3094
5524
  });
3095
- const nodeCtx = {
3096
- ...args.ctx,
3097
- config: config$1.node
3098
- };
5525
+ const nodeCtx = this.resolveNodeCtx(config$1, args);
3099
5526
  const resolvedNode = this.nodeResolver.resolve(config$1.node.type);
3100
5527
  const outputs = await this.executeResolvedNode(resolvedNode, nodeInput, nodeCtx);
3101
5528
  return config$1.toToolOutput({
@@ -3108,6 +5535,35 @@ let NodeBackedToolRuntime = class NodeBackedToolRuntime$1 {
3108
5535
  outputs
3109
5536
  });
3110
5537
  }
5538
+ /**
5539
+ * Returns a re-rooted child ctx for nested-agent tools (so their LLM/tool connection ids derive
5540
+ * from the tool connection node, telemetry parents under the tool-call span, and connection
5541
+ * invocations carry `parentInvocationId`). Plain runnable tools (non-agent) keep the orchestrator
5542
+ * ctx with only `config` swapped — no nesting concern.
5543
+ *
5544
+ * The caller (`AIAgentNode.createItemScopedTools`) already wraps the orchestrator ctx via
5545
+ * `ConnectionCredentialExecutionContextFactory.forConnectionNode`, so `args.ctx.nodeId` is the
5546
+ * tool's own connection node id (e.g. `AIAgentNode:2__conn__tool__searchInMail`). We pass that
5547
+ * through as the sub-agent's `nodeId`; deriving another `toolConnectionNodeId(args.ctx.nodeId,
5548
+ * config.name)` here would prepend a duplicate `__conn__tool__<name>` segment and exponentially
5549
+ * deepen ids on each invocation, which also breaks credential resolution because user-provided
5550
+ * bindings sit on the single-level connection node id.
5551
+ */
5552
+ resolveNodeCtx(config$1, args) {
5553
+ const isNestedAgent = AgentConfigInspector.isAgentNodeConfig(config$1.node);
5554
+ const hooks = args.hooks;
5555
+ if (!isNestedAgent || !hooks?.parentSpan || !hooks.parentInvocationId) return {
5556
+ ...args.ctx,
5557
+ config: config$1.node
5558
+ };
5559
+ return this.childExecutionScopeFactory.forSubAgent({
5560
+ parentCtx: args.ctx,
5561
+ childNodeId: args.ctx.nodeId,
5562
+ childConfig: config$1.node,
5563
+ parentInvocationId: hooks.parentInvocationId,
5564
+ parentSpan: hooks.parentSpan
5565
+ });
5566
+ }
3111
5567
  async executeResolvedNode(resolvedNode, nodeInput, ctx) {
3112
5568
  if (this.isMultiInputNode(resolvedNode)) return await resolvedNode.executeMulti({ in: [nodeInput] }, ctx);
3113
5569
  if (this.isRunnableNode(resolvedNode)) {
@@ -3145,11 +5601,13 @@ NodeBackedToolRuntime = __decorate([
3145
5601
  __decorateParam(1, inject(ItemExprResolver)),
3146
5602
  __decorateParam(2, inject(NodeOutputNormalizer)),
3147
5603
  __decorateParam(3, inject(RunnableOutputBehaviorResolver)),
5604
+ __decorateParam(4, inject(ChildExecutionScopeFactory)),
3148
5605
  __decorateMetadata("design:paramtypes", [
3149
5606
  Object,
3150
5607
  typeof (_ref$1 = typeof ItemExprResolver !== "undefined" && ItemExprResolver) === "function" ? _ref$1 : Object,
3151
5608
  typeof (_ref2$1 = typeof NodeOutputNormalizer !== "undefined" && NodeOutputNormalizer) === "function" ? _ref2$1 : Object,
3152
- typeof (_ref3$1 = typeof RunnableOutputBehaviorResolver !== "undefined" && RunnableOutputBehaviorResolver) === "function" ? _ref3$1 : Object
5609
+ typeof (_ref3$1 = typeof RunnableOutputBehaviorResolver !== "undefined" && RunnableOutputBehaviorResolver) === "function" ? _ref3$1 : Object,
5610
+ typeof (_ref4$1 = typeof ChildExecutionScopeFactory !== "undefined" && ChildExecutionScopeFactory) === "function" ? _ref4$1 : Object
3153
5611
  ])
3154
5612
  ], NodeBackedToolRuntime);
3155
5613
 
@@ -3167,14 +5625,8 @@ var _ref, _ref2, _ref3, _ref4;
3167
5625
  let AIAgentNode = class AIAgentNode$1 {
3168
5626
  kind = "node";
3169
5627
  outputPorts = ["main"];
3170
- /**
3171
- * Engine validates {@link RunnableNodeConfig.inputSchema} (Zod) on {@code item.json} before enqueue, then resolves
3172
- * per-item **`itemExpr`** leaves on config before {@link #execute}. Prefer modeling prompts as
3173
- * {@code { messages: [{ role, content }, ...] }} (on input or config) so persisted inputs are visible in the UI.
3174
- */
3175
5628
  inputSchema = unknown();
3176
5629
  connectionCredentialExecutionContextFactory;
3177
- /** One resolved model/tools bundle per activation context (same ctx across items in a batch). */
3178
5630
  preparedByExecutionContext = /* @__PURE__ */ new WeakMap();
3179
5631
  constructor(nodeResolver, credentialSessions, nodeBackedToolRuntime, executionHelpers, structuredOutputRunner, toolExecutionCoordinator) {
3180
5632
  this.nodeResolver = nodeResolver;
@@ -3205,9 +5657,6 @@ let AIAgentNode = class AIAgentNode$1 {
3205
5657
  throw error;
3206
5658
  }
3207
5659
  }
3208
- /**
3209
- * Resolves the chat model and tools once per activation, then reuses for every item in the batch.
3210
- */
3211
5660
  async prepareExecution(ctx) {
3212
5661
  const chatModelFactory = this.nodeResolver.resolve(ctx.config.chatModel.type);
3213
5662
  const languageModelCredentialContext = this.connectionCredentialExecutionContextFactory.forConnectionNode(ctx, {
@@ -3225,9 +5674,6 @@ let AIAgentNode = class AIAgentNode$1 {
3225
5674
  languageModelConnectionNodeId: ConnectionNodeIdFactory.languageModelConnectionNodeId(ctx.nodeId)
3226
5675
  };
3227
5676
  }
3228
- /**
3229
- * One item: build prompts, optionally bind tools, run the multi-turn loop, map the final model message to workflow JSON.
3230
- */
3231
5677
  async runAgentForItem(prepared, item, itemIndex, items) {
3232
5678
  const { ctx } = prepared;
3233
5679
  const itemInputsByPort = AgentItemPortMap.fromItem(item);
@@ -3241,8 +5687,8 @@ let AIAgentNode = class AIAgentNode$1 {
3241
5687
  conversation,
3242
5688
  agentName: this.getAgentDisplayName(ctx),
3243
5689
  nodeId: ctx.nodeId,
3244
- invokeTextModel: async (messages) => await this.invokeModel(prepared.model, prepared.languageModelConnectionNodeId, messages, ctx, itemInputsByPort, prepared.guardrails.modelInvocationOptions),
3245
- invokeStructuredModel: async (structuredModel, messages) => await this.invokeStructuredModel(structuredModel, prepared.languageModelConnectionNodeId, messages, ctx, itemInputsByPort, prepared.guardrails.modelInvocationOptions)
5690
+ invokeTextModel: async (messages) => await this.invokeTextTurn(prepared, itemInputsByPort, messages, []),
5691
+ invokeStructuredModel: async (schema, messages, structuredOptions) => await this.invokeStructuredTurn(prepared, itemInputsByPort, schema, messages, structuredOptions)
3246
5692
  });
3247
5693
  await ctx.telemetry.recordMetric({
3248
5694
  name: CodemationTelemetryMetricNames.agentTurns,
@@ -3254,13 +5700,11 @@ let AIAgentNode = class AIAgentNode$1 {
3254
5700
  });
3255
5701
  return this.buildOutputItem(item, structuredOutput);
3256
5702
  }
3257
- const modelWithTools = this.bindToolsToModel(prepared.model, itemScopedTools);
3258
5703
  const loopResult = await this.runTurnLoopUntilFinalAnswer({
3259
5704
  prepared,
3260
5705
  itemInputsByPort,
3261
5706
  itemScopedTools,
3262
- conversation,
3263
- modelWithTools
5707
+ conversation
3264
5708
  });
3265
5709
  await ctx.telemetry.recordMetric({
3266
5710
  name: CodemationTelemetryMetricNames.agentTurns,
@@ -3270,30 +5714,34 @@ let AIAgentNode = class AIAgentNode$1 {
3270
5714
  name: CodemationTelemetryMetricNames.agentToolCalls,
3271
5715
  value: loopResult.toolCallCount
3272
5716
  });
3273
- const outputJson = await this.resolveFinalOutputJson(prepared, itemInputsByPort, conversation, loopResult.finalResponse, itemScopedTools.length > 0);
5717
+ const outputJson = await this.resolveFinalOutputJson(prepared, itemInputsByPort, conversation, loopResult.finalText, itemScopedTools.length > 0);
3274
5718
  return this.buildOutputItem(item, outputJson);
3275
5719
  }
3276
5720
  /**
3277
- * Repeatedly invokes the model until it returns without tool calls, or guardrails end the loop.
5721
+ * Multi-turn loop:
5722
+ * - Each turn is a single `generateText` call with tools exposed but **not auto-executed**
5723
+ * (we control tool dispatch so that {@link AgentToolExecutionCoordinator} drives repair /
5724
+ * connection-invocation recording / transient-error handling exactly like before).
5725
+ * - When the model returns no tool calls the loop ends with the model's text as the final answer.
5726
+ * - Respects `guardrails.maxTurns` and `guardrails.onTurnLimitReached`.
3278
5727
  */
3279
5728
  async runTurnLoopUntilFinalAnswer(args) {
3280
- const { prepared, itemInputsByPort, itemScopedTools, conversation, modelWithTools } = args;
3281
- const { ctx, guardrails, languageModelConnectionNodeId } = prepared;
3282
- let finalResponse;
5729
+ const { prepared, itemInputsByPort, itemScopedTools, conversation } = args;
5730
+ const { ctx, guardrails } = prepared;
5731
+ let finalText = "";
3283
5732
  let toolCallCount = 0;
3284
5733
  let turnCount = 0;
3285
5734
  const repairAttemptsByToolName = /* @__PURE__ */ new Map();
3286
5735
  for (let turn = 1; turn <= guardrails.maxTurns; turn++) {
3287
5736
  turnCount = turn;
3288
- const response = await this.invokeModel(modelWithTools, languageModelConnectionNodeId, conversation, ctx, itemInputsByPort, guardrails.modelInvocationOptions);
3289
- finalResponse = response;
3290
- const toolCalls = AgentMessageFactory.extractToolCalls(response);
3291
- if (toolCalls.length === 0) break;
5737
+ const result = await this.invokeTextTurn(prepared, itemInputsByPort, conversation, itemScopedTools);
5738
+ finalText = result.text;
5739
+ if (result.toolCalls.length === 0) break;
3292
5740
  if (this.cannotExecuteAnotherToolRound(turn, guardrails)) {
3293
5741
  this.finishOrThrowWhenTurnCapHitWithToolCalls(ctx, guardrails);
3294
5742
  break;
3295
5743
  }
3296
- const plannedToolCalls = this.planToolCalls(itemScopedTools, toolCalls, ctx.nodeId);
5744
+ const plannedToolCalls = this.planToolCalls(itemScopedTools, result.toolCalls, ctx.nodeId);
3297
5745
  toolCallCount += plannedToolCalls.length;
3298
5746
  await this.markQueuedTools(plannedToolCalls, ctx);
3299
5747
  const executedToolCalls = await this.toolExecutionCoordinator.execute({
@@ -3302,11 +5750,10 @@ let AIAgentNode = class AIAgentNode$1 {
3302
5750
  agentName: this.getAgentDisplayName(ctx),
3303
5751
  repairAttemptsByToolName
3304
5752
  });
3305
- this.appendAssistantAndToolMessages(conversation, response, executedToolCalls);
5753
+ this.appendAssistantAndToolMessages(conversation, result.assistantMessage, result.text, result.toolCalls, executedToolCalls);
3306
5754
  }
3307
- if (!finalResponse) throw new Error(`AIAgent "${ctx.config.name ?? ctx.nodeId}" did not produce a model response.`);
3308
5755
  return {
3309
- finalResponse,
5756
+ finalText,
3310
5757
  turnCount,
3311
5758
  toolCallCount
3312
5759
  };
@@ -3318,30 +5765,30 @@ let AIAgentNode = class AIAgentNode$1 {
3318
5765
  if (guardrails.onTurnLimitReached === "respondWithLastMessage") return;
3319
5766
  throw new Error(`AIAgent "${ctx.config.name ?? ctx.nodeId}" reached maxTurns=${guardrails.maxTurns} before producing a final response.`);
3320
5767
  }
3321
- appendAssistantAndToolMessages(conversation, assistantMessage, executedToolCalls) {
3322
- conversation.push(assistantMessage, ...executedToolCalls.map((toolCall) => AgentMessageFactory.createToolMessage(toolCall.toolCallId, toolCall.serialized)));
5768
+ appendAssistantAndToolMessages(conversation, assistantMessage, text, toolCalls, executedToolCalls) {
5769
+ conversation.push(assistantMessage ?? AgentMessageFactory.createAssistantWithToolCalls(text, toolCalls), AgentMessageFactory.createToolResultsMessage(executedToolCalls));
3323
5770
  }
3324
- async resolveFinalOutputJson(prepared, itemInputsByPort, conversation, finalResponse, wasToolEnabledRun) {
3325
- if (!prepared.ctx.config.outputSchema) return AgentOutputFactory.fromAgentContent(AgentMessageFactory.extractContent(finalResponse));
5771
+ async resolveFinalOutputJson(prepared, itemInputsByPort, conversation, finalText, wasToolEnabledRun) {
5772
+ if (!prepared.ctx.config.outputSchema) return AgentOutputFactory.fromAgentContent(finalText);
5773
+ const conversationWithFinal = wasToolEnabledRun ? [...conversation, {
5774
+ role: "assistant",
5775
+ content: finalText
5776
+ }] : conversation;
3326
5777
  return await this.structuredOutputRunner.resolve({
3327
5778
  model: prepared.model,
3328
5779
  chatModelConfig: prepared.ctx.config.chatModel,
3329
5780
  schema: prepared.ctx.config.outputSchema,
3330
- conversation: wasToolEnabledRun ? [...conversation, finalResponse] : conversation,
3331
- rawFinalResponse: finalResponse,
5781
+ conversation: conversationWithFinal,
5782
+ rawFinalText: finalText,
3332
5783
  agentName: this.getAgentDisplayName(prepared.ctx),
3333
5784
  nodeId: prepared.ctx.nodeId,
3334
- invokeTextModel: async (messages) => await this.invokeModel(prepared.model, prepared.languageModelConnectionNodeId, messages, prepared.ctx, itemInputsByPort, prepared.guardrails.modelInvocationOptions),
3335
- invokeStructuredModel: async (structuredModel, messages) => await this.invokeStructuredModel(structuredModel, prepared.languageModelConnectionNodeId, messages, prepared.ctx, itemInputsByPort, prepared.guardrails.modelInvocationOptions)
5785
+ invokeTextModel: async (messages) => await this.invokeTextTurn(prepared, itemInputsByPort, messages, []),
5786
+ invokeStructuredModel: async (schema, messages, structuredOptions) => await this.invokeStructuredTurn(prepared, itemInputsByPort, schema, messages, structuredOptions)
3336
5787
  });
3337
5788
  }
3338
5789
  buildOutputItem(item, outputJson) {
3339
5790
  return AgentOutputFactory.replaceJson(item, outputJson);
3340
5791
  }
3341
- bindToolsToModel(model, itemScopedTools) {
3342
- if (itemScopedTools.length === 0 || !model.bindTools) return model;
3343
- return model.bindTools(itemScopedTools.map((entry) => entry.langChainTool));
3344
- }
3345
5792
  resolveTools(toolConfigs) {
3346
5793
  const resolvedTools = toolConfigs.map((config$1) => ({
3347
5794
  config: config$1,
@@ -3360,38 +5807,120 @@ let AIAgentNode = class AIAgentNode$1 {
3360
5807
  connectionNodeId: ConnectionNodeIdFactory.toolConnectionNodeId(ctx.nodeId, entry.config.name),
3361
5808
  getCredentialRequirements: () => entry.config.getCredentialRequirements?.() ?? []
3362
5809
  });
3363
- const langChainTool = this.executionHelpers.createDynamicStructuredTool(entry, toolCredentialContext, item, itemIndex, items);
3364
5810
  return {
3365
5811
  config: entry.config,
3366
- langChainTool
5812
+ inputSchema: entry.runtime.inputSchema,
5813
+ execute: async (input, hooks) => {
5814
+ const validated = entry.runtime.inputSchema.parse(input);
5815
+ return await entry.runtime.execute({
5816
+ config: entry.config,
5817
+ input: validated,
5818
+ ctx: toolCredentialContext,
5819
+ item,
5820
+ itemIndex,
5821
+ items,
5822
+ hooks
5823
+ });
5824
+ }
3367
5825
  };
3368
5826
  });
3369
5827
  }
3370
- async invokeModel(model, nodeId, messages, ctx, inputsByPort, options) {
5828
+ /**
5829
+ * Builds an AI SDK {@link ToolSet} where every tool ships a pre-converted JSON Schema (via
5830
+ * {@link jsonSchema}) — not the raw Zod schema — and carries **no** `execute`. Two reasons:
5831
+ *
5832
+ * 1. Codemation owns tool dispatch + the per-tool repair loop (see {@link AgentToolExecutionCoordinator}),
5833
+ * so the AI SDK must surface tool calls back to us instead of auto-running them.
5834
+ * 2. The AI SDK's `asSchema` helper discriminates between Zod v3 / Zod v4 / Standard Schema via
5835
+ * runtime feature-detection (`~standard`, `_zod`, etc.). Handing it a pre-built
5836
+ * {@link jsonSchema} record — which is tagged with `Symbol.for('vercel.ai.schema')` — skips all
5837
+ * of that detection and guarantees the provider receives a draft-07 JSON Schema with
5838
+ * `additionalProperties: false` at every object depth (see {@link OpenAiStrictJsonSchemaFactory}
5839
+ * for the same logic applied to structured-output schemas). Codemation still runs its own Zod
5840
+ * validation on tool inputs before execute — the schema handed to the model is advisory.
5841
+ */
5842
+ buildToolSet(itemScopedTools) {
5843
+ if (itemScopedTools.length === 0) return void 0;
5844
+ const toolSet = {};
5845
+ for (const entry of itemScopedTools) {
5846
+ const schemaRecord = this.executionHelpers.createJsonSchemaRecord(entry.inputSchema, {
5847
+ schemaName: entry.config.name,
5848
+ requireObjectRoot: true
5849
+ });
5850
+ toolSet[entry.config.name] = {
5851
+ description: entry.config.description,
5852
+ inputSchema: jsonSchema(schemaRecord)
5853
+ };
5854
+ }
5855
+ return toolSet;
5856
+ }
5857
+ /**
5858
+ * One `generateText` turn (no auto tool execution) with Codemation-owned child-span telemetry
5859
+ * and connection-invocation state recording.
5860
+ */
5861
+ async invokeTextTurn(prepared, itemInputsByPort, messages, itemScopedTools) {
3371
5862
  const invocationId = ConnectionInvocationIdFactory.create();
3372
5863
  const startedAt = /* @__PURE__ */ new Date();
3373
5864
  const summarizedInput = this.summarizeLlmMessages(messages);
5865
+ const { ctx, model, languageModelConnectionNodeId, guardrails } = prepared;
3374
5866
  const span = this.createModelInvocationSpan(ctx, invocationId, startedAt);
3375
5867
  await ctx.nodeState?.markQueued({
3376
- nodeId,
5868
+ nodeId: languageModelConnectionNodeId,
3377
5869
  activationId: ctx.activationId,
3378
- inputsByPort
5870
+ inputsByPort: itemInputsByPort
5871
+ });
5872
+ await ctx.nodeState?.appendConnectionInvocation({
5873
+ invocationId,
5874
+ connectionNodeId: languageModelConnectionNodeId,
5875
+ parentAgentNodeId: ctx.nodeId,
5876
+ parentAgentActivationId: ctx.activationId,
5877
+ status: "queued",
5878
+ managedInput: summarizedInput,
5879
+ queuedAt: startedAt.toISOString(),
5880
+ iterationId: ctx.iterationId,
5881
+ itemIndex: ctx.itemIndex,
5882
+ parentInvocationId: ctx.parentInvocationId
3379
5883
  });
3380
5884
  await ctx.nodeState?.markRunning({
3381
- nodeId,
5885
+ nodeId: languageModelConnectionNodeId,
3382
5886
  activationId: ctx.activationId,
3383
- inputsByPort
5887
+ inputsByPort: itemInputsByPort
5888
+ });
5889
+ await ctx.nodeState?.appendConnectionInvocation({
5890
+ invocationId,
5891
+ connectionNodeId: languageModelConnectionNodeId,
5892
+ parentAgentNodeId: ctx.nodeId,
5893
+ parentAgentActivationId: ctx.activationId,
5894
+ status: "running",
5895
+ managedInput: summarizedInput,
5896
+ queuedAt: startedAt.toISOString(),
5897
+ startedAt: startedAt.toISOString(),
5898
+ iterationId: ctx.iterationId,
5899
+ itemIndex: ctx.itemIndex,
5900
+ parentInvocationId: ctx.parentInvocationId
3384
5901
  });
3385
5902
  try {
3386
- const response = await model.invoke(messages, options);
5903
+ const tools = this.buildToolSet(itemScopedTools);
5904
+ const callOptions = this.resolveCallOptions(model, guardrails.modelInvocationOptions);
5905
+ const result = await generateText({
5906
+ model: model.languageModel,
5907
+ messages: [...messages],
5908
+ tools,
5909
+ toolChoice: tools ? "auto" : void 0,
5910
+ maxOutputTokens: callOptions.maxOutputTokens,
5911
+ temperature: callOptions.temperature,
5912
+ providerOptions: callOptions.providerOptions,
5913
+ maxRetries: 0
5914
+ });
5915
+ const turnResult = this.extractTurnResult(result);
3387
5916
  const finishedAt = /* @__PURE__ */ new Date();
5917
+ const managedOutput = this.summarizeTurnOutput(turnResult);
3388
5918
  await ctx.nodeState?.markCompleted({
3389
- nodeId,
5919
+ nodeId: languageModelConnectionNodeId,
3390
5920
  activationId: ctx.activationId,
3391
- inputsByPort,
3392
- outputs: AgentOutputFactory.fromUnknown({ content: AgentMessageFactory.extractContent(response) })
5921
+ inputsByPort: itemInputsByPort,
5922
+ outputs: AgentOutputFactory.fromUnknown(managedOutput)
3393
5923
  });
3394
- const content = AgentMessageFactory.extractContent(response);
3395
5924
  await span.attachArtifact({
3396
5925
  kind: "ai.messages",
3397
5926
  contentType: "application/json",
@@ -3400,26 +5929,29 @@ let AIAgentNode = class AIAgentNode$1 {
3400
5929
  await span.attachArtifact({
3401
5930
  kind: "ai.response",
3402
5931
  contentType: "application/json",
3403
- previewJson: content
5932
+ previewJson: turnResult.text
3404
5933
  });
3405
- await this.recordModelUsageMetrics(span, response, ctx);
5934
+ await this.recordModelUsageMetrics(span, turnResult.usage, ctx);
3406
5935
  await span.end({
3407
5936
  status: "ok",
3408
5937
  endedAt: finishedAt
3409
5938
  });
3410
5939
  await ctx.nodeState?.appendConnectionInvocation({
3411
5940
  invocationId,
3412
- connectionNodeId: nodeId,
5941
+ connectionNodeId: languageModelConnectionNodeId,
3413
5942
  parentAgentNodeId: ctx.nodeId,
3414
5943
  parentAgentActivationId: ctx.activationId,
3415
5944
  status: "completed",
3416
5945
  managedInput: summarizedInput,
3417
- managedOutput: content,
5946
+ managedOutput,
3418
5947
  queuedAt: startedAt.toISOString(),
3419
5948
  startedAt: startedAt.toISOString(),
3420
- finishedAt: finishedAt.toISOString()
5949
+ finishedAt: finishedAt.toISOString(),
5950
+ iterationId: ctx.iterationId,
5951
+ itemIndex: ctx.itemIndex,
5952
+ parentInvocationId: ctx.parentInvocationId
3421
5953
  });
3422
- return response;
5954
+ return turnResult;
3423
5955
  } catch (error) {
3424
5956
  await span.end({
3425
5957
  status: "error",
@@ -3430,36 +5962,78 @@ let AIAgentNode = class AIAgentNode$1 {
3430
5962
  error,
3431
5963
  invocationId,
3432
5964
  startedAt,
3433
- nodeId,
5965
+ nodeId: languageModelConnectionNodeId,
3434
5966
  ctx,
3435
- inputsByPort,
3436
- managedInput: this.summarizeLlmMessages(messages)
5967
+ inputsByPort: itemInputsByPort,
5968
+ managedInput: summarizedInput
3437
5969
  });
3438
5970
  }
3439
5971
  }
3440
- async invokeStructuredModel(model, nodeId, messages, ctx, inputsByPort, options) {
5972
+ /**
5973
+ * Structured-output turn: runs `generateText({ output: Output.object({ schema }) })` via the
5974
+ * structured-output runner. We keep this as a separate helper because the runner needs the raw
5975
+ * validated value (not just text) back, and must be able to retry on Zod failures.
5976
+ */
5977
+ async invokeStructuredTurn(prepared, itemInputsByPort, schema, messages, structuredOptions) {
3441
5978
  const invocationId = ConnectionInvocationIdFactory.create();
3442
5979
  const startedAt = /* @__PURE__ */ new Date();
3443
5980
  const summarizedInput = this.summarizeLlmMessages(messages);
5981
+ const { ctx, model, languageModelConnectionNodeId, guardrails } = prepared;
3444
5982
  const span = this.createModelInvocationSpan(ctx, invocationId, startedAt);
3445
5983
  await ctx.nodeState?.markQueued({
3446
- nodeId,
5984
+ nodeId: languageModelConnectionNodeId,
3447
5985
  activationId: ctx.activationId,
3448
- inputsByPort
5986
+ inputsByPort: itemInputsByPort
5987
+ });
5988
+ await ctx.nodeState?.appendConnectionInvocation({
5989
+ invocationId,
5990
+ connectionNodeId: languageModelConnectionNodeId,
5991
+ parentAgentNodeId: ctx.nodeId,
5992
+ parentAgentActivationId: ctx.activationId,
5993
+ status: "queued",
5994
+ managedInput: summarizedInput,
5995
+ queuedAt: startedAt.toISOString(),
5996
+ iterationId: ctx.iterationId,
5997
+ itemIndex: ctx.itemIndex,
5998
+ parentInvocationId: ctx.parentInvocationId
3449
5999
  });
3450
6000
  await ctx.nodeState?.markRunning({
3451
- nodeId,
6001
+ nodeId: languageModelConnectionNodeId,
3452
6002
  activationId: ctx.activationId,
3453
- inputsByPort
6003
+ inputsByPort: itemInputsByPort
6004
+ });
6005
+ await ctx.nodeState?.appendConnectionInvocation({
6006
+ invocationId,
6007
+ connectionNodeId: languageModelConnectionNodeId,
6008
+ parentAgentNodeId: ctx.nodeId,
6009
+ parentAgentActivationId: ctx.activationId,
6010
+ status: "running",
6011
+ managedInput: summarizedInput,
6012
+ queuedAt: startedAt.toISOString(),
6013
+ startedAt: startedAt.toISOString(),
6014
+ iterationId: ctx.iterationId,
6015
+ itemIndex: ctx.itemIndex,
6016
+ parentInvocationId: ctx.parentInvocationId
3454
6017
  });
3455
6018
  try {
3456
- const response = await model.invoke(messages, options);
6019
+ const callOptions = this.resolveCallOptions(model, guardrails.modelInvocationOptions);
6020
+ const outputSchema = structuredOptions?.strict && !this.isZodSchema(schema) ? Output.object({ schema: jsonSchema(schema) }) : Output.object({ schema });
6021
+ const result = await generateText({
6022
+ model: model.languageModel,
6023
+ messages: [...messages],
6024
+ experimental_output: outputSchema,
6025
+ maxOutputTokens: callOptions.maxOutputTokens,
6026
+ temperature: callOptions.temperature,
6027
+ providerOptions: callOptions.providerOptions,
6028
+ maxRetries: 0
6029
+ });
6030
+ const turnResult = this.extractTurnResult(result);
3457
6031
  const finishedAt = /* @__PURE__ */ new Date();
3458
6032
  await ctx.nodeState?.markCompleted({
3459
- nodeId,
6033
+ nodeId: languageModelConnectionNodeId,
3460
6034
  activationId: ctx.activationId,
3461
- inputsByPort,
3462
- outputs: AgentOutputFactory.fromUnknown(response)
6035
+ inputsByPort: itemInputsByPort,
6036
+ outputs: AgentOutputFactory.fromUnknown(result.experimental_output)
3463
6037
  });
3464
6038
  await span.attachArtifact({
3465
6039
  kind: "ai.messages",
@@ -3469,26 +6043,29 @@ let AIAgentNode = class AIAgentNode$1 {
3469
6043
  await span.attachArtifact({
3470
6044
  kind: "ai.response.structured",
3471
6045
  contentType: "application/json",
3472
- previewJson: this.resultToJsonValue(response)
6046
+ previewJson: this.resultToJsonValue(result.experimental_output)
3473
6047
  });
3474
- await this.recordModelUsageMetrics(span, response, ctx);
6048
+ await this.recordModelUsageMetrics(span, turnResult.usage, ctx);
3475
6049
  await span.end({
3476
6050
  status: "ok",
3477
6051
  endedAt: finishedAt
3478
6052
  });
3479
6053
  await ctx.nodeState?.appendConnectionInvocation({
3480
6054
  invocationId,
3481
- connectionNodeId: nodeId,
6055
+ connectionNodeId: languageModelConnectionNodeId,
3482
6056
  parentAgentNodeId: ctx.nodeId,
3483
6057
  parentAgentActivationId: ctx.activationId,
3484
6058
  status: "completed",
3485
6059
  managedInput: summarizedInput,
3486
- managedOutput: this.resultToJsonValue(response),
6060
+ managedOutput: this.resultToJsonValue(result.experimental_output),
3487
6061
  queuedAt: startedAt.toISOString(),
3488
6062
  startedAt: startedAt.toISOString(),
3489
- finishedAt: finishedAt.toISOString()
6063
+ finishedAt: finishedAt.toISOString(),
6064
+ iterationId: ctx.iterationId,
6065
+ itemIndex: ctx.itemIndex,
6066
+ parentInvocationId: ctx.parentInvocationId
3490
6067
  });
3491
- return response;
6068
+ return result.experimental_output;
3492
6069
  } catch (error) {
3493
6070
  await span.end({
3494
6071
  status: "error",
@@ -3499,13 +6076,77 @@ let AIAgentNode = class AIAgentNode$1 {
3499
6076
  error,
3500
6077
  invocationId,
3501
6078
  startedAt,
3502
- nodeId,
6079
+ nodeId: languageModelConnectionNodeId,
3503
6080
  ctx,
3504
- inputsByPort,
3505
- managedInput: this.summarizeLlmMessages(messages)
6081
+ inputsByPort: itemInputsByPort,
6082
+ managedInput: summarizedInput
3506
6083
  });
3507
6084
  }
3508
6085
  }
6086
+ isZodSchema(schema) {
6087
+ return typeof schema.parse === "function";
6088
+ }
6089
+ resolveCallOptions(model, overrides) {
6090
+ const defaults = model.defaultCallOptions ?? {};
6091
+ return {
6092
+ maxOutputTokens: overrides?.maxTokens ?? defaults.maxOutputTokens,
6093
+ temperature: defaults.temperature,
6094
+ providerOptions: overrides?.providerOptions ?? defaults.providerOptions
6095
+ };
6096
+ }
6097
+ /**
6098
+ * Build a no-code-friendly output payload for an LLM round.
6099
+ *
6100
+ * Always includes `content` (matching the canvas snapshot shape used elsewhere) and adds a
6101
+ * `toolCalls` array when the round produced tool calls so the execution inspector surfaces the
6102
+ * planned calls instead of just an empty `""` for tool-only rounds.
6103
+ */
6104
+ summarizeTurnOutput(turnResult) {
6105
+ if (turnResult.toolCalls.length === 0) return { content: turnResult.text };
6106
+ const toolCalls = turnResult.toolCalls.map((toolCall) => ({
6107
+ name: toolCall.name,
6108
+ args: this.resultToJsonValue(toolCall.input) ?? null
6109
+ }));
6110
+ return {
6111
+ content: turnResult.text,
6112
+ toolCalls
6113
+ };
6114
+ }
6115
+ extractTurnResult(result) {
6116
+ const usage = this.extractUsageFromResult(result);
6117
+ const text = result.text;
6118
+ const toolCalls = result.toolCalls.map((toolCall) => ({
6119
+ id: toolCall.toolCallId,
6120
+ name: toolCall.toolName,
6121
+ input: toolCall.input
6122
+ }));
6123
+ return {
6124
+ assistantMessage: this.extractAssistantMessage(result),
6125
+ text,
6126
+ toolCalls,
6127
+ usage
6128
+ };
6129
+ }
6130
+ extractAssistantMessage(result) {
6131
+ const assistantMessages = result.response.messages.filter((m) => m.role === "assistant");
6132
+ return assistantMessages[assistantMessages.length - 1];
6133
+ }
6134
+ extractUsageFromResult(result) {
6135
+ const usage = result.usage;
6136
+ const inputTokens = this.toFiniteNumber(usage.inputTokens);
6137
+ const outputTokens = this.toFiniteNumber(usage.outputTokens);
6138
+ return {
6139
+ inputTokens,
6140
+ outputTokens,
6141
+ totalTokens: this.toFiniteNumber(usage.totalTokens) ?? (inputTokens !== void 0 && outputTokens !== void 0 ? inputTokens + outputTokens : void 0),
6142
+ cachedInputTokens: this.toFiniteNumber(usage.cachedInputTokens),
6143
+ reasoningTokens: this.toFiniteNumber(usage.reasoningTokens)
6144
+ };
6145
+ }
6146
+ toFiniteNumber(value) {
6147
+ if (typeof value !== "number" || !Number.isFinite(value)) return void 0;
6148
+ return value;
6149
+ }
3509
6150
  createModelInvocationSpan(ctx, invocationId, startedAt) {
3510
6151
  return ctx.telemetry.startChildSpan({
3511
6152
  name: "gen_ai.chat.completion",
@@ -3514,13 +6155,22 @@ let AIAgentNode = class AIAgentNode$1 {
3514
6155
  attributes: {
3515
6156
  [CodemationTelemetryAttributeNames.connectionInvocationId]: invocationId,
3516
6157
  [GenAiTelemetryAttributeNames.operationName]: "chat",
3517
- [GenAiTelemetryAttributeNames.requestModel]: this.resolveChatModelName(ctx.config.chatModel)
6158
+ [GenAiTelemetryAttributeNames.requestModel]: this.resolveChatModelName(ctx.config.chatModel),
6159
+ ...ctx.iterationId ? { [CodemationTelemetryAttributeNames.iterationId]: ctx.iterationId } : {},
6160
+ ...typeof ctx.itemIndex === "number" ? { [CodemationTelemetryAttributeNames.iterationIndex]: ctx.itemIndex } : {},
6161
+ ...ctx.parentInvocationId ? { [CodemationTelemetryAttributeNames.parentInvocationId]: ctx.parentInvocationId } : {}
3518
6162
  }
3519
6163
  });
3520
6164
  }
3521
- async recordModelUsageMetrics(span, response, ctx) {
3522
- const usage = this.extractModelUsageMetrics(response);
3523
- for (const [name, value] of Object.entries(usage)) {
6165
+ async recordModelUsageMetrics(span, usage, ctx) {
6166
+ const entries = [
6167
+ [GenAiTelemetryAttributeNames.usageInputTokens, usage.inputTokens],
6168
+ [GenAiTelemetryAttributeNames.usageOutputTokens, usage.outputTokens],
6169
+ [GenAiTelemetryAttributeNames.usageTotalTokens, usage.totalTokens],
6170
+ [GenAiTelemetryAttributeNames.usageCacheReadInputTokens, usage.cachedInputTokens],
6171
+ [GenAiTelemetryAttributeNames.usageReasoningTokens, usage.reasoningTokens]
6172
+ ];
6173
+ for (const [name, value] of entries) {
3524
6174
  if (value === void 0) continue;
3525
6175
  await span.recordMetric({
3526
6176
  name,
@@ -3535,99 +6185,49 @@ let AIAgentNode = class AIAgentNode$1 {
3535
6185
  const provider = ctx.config.chatModel.provider;
3536
6186
  const pricingKey = ctx.config.chatModel.modelName;
3537
6187
  if (!provider || !pricingKey) return;
3538
- const inputTokens = usage[GenAiTelemetryAttributeNames.usageInputTokens];
3539
- const outputTokens = usage[GenAiTelemetryAttributeNames.usageOutputTokens];
3540
- if (inputTokens !== void 0) await costTracking.captureUsage({
6188
+ if (usage.inputTokens !== void 0) await costTracking.captureUsage({
3541
6189
  component: "chat",
3542
6190
  provider,
3543
6191
  operation: "completion.input",
3544
6192
  pricingKey,
3545
6193
  usageUnit: "input_tokens",
3546
- quantity: inputTokens,
6194
+ quantity: usage.inputTokens,
3547
6195
  modelName: pricingKey
3548
6196
  });
3549
- if (outputTokens !== void 0) await costTracking.captureUsage({
6197
+ if (usage.outputTokens !== void 0) await costTracking.captureUsage({
3550
6198
  component: "chat",
3551
6199
  provider,
3552
6200
  operation: "completion.output",
3553
6201
  pricingKey,
3554
6202
  usageUnit: "output_tokens",
3555
- quantity: outputTokens,
6203
+ quantity: usage.outputTokens,
3556
6204
  modelName: pricingKey
3557
6205
  });
3558
6206
  }
3559
6207
  resolveChatModelName(chatModel$1) {
3560
6208
  return chatModel$1.modelName ?? chatModel$1.name;
3561
6209
  }
3562
- extractModelUsageMetrics(response) {
3563
- const usage = this.extractUsageObject(response);
3564
- const inputTokens = this.readUsageNumber(usage, [
3565
- "input_tokens",
3566
- "inputTokens",
3567
- "prompt_tokens",
3568
- "promptTokens"
3569
- ]);
3570
- const outputTokens = this.readUsageNumber(usage, [
3571
- "output_tokens",
3572
- "outputTokens",
3573
- "completion_tokens",
3574
- "completionTokens"
3575
- ]);
3576
- const totalTokens = this.readUsageNumber(usage, ["total_tokens", "totalTokens"]) ?? (inputTokens !== void 0 && outputTokens !== void 0 ? inputTokens + outputTokens : void 0);
3577
- const cachedInputTokens = this.readUsageNumber(usage, [
3578
- "cache_read_input_tokens",
3579
- "cacheReadInputTokens",
3580
- "input_token_details.cached_tokens"
3581
- ]);
3582
- const reasoningTokens = this.readUsageNumber(usage, [
3583
- "reasoning_tokens",
3584
- "reasoningTokens",
3585
- "output_token_details.reasoning_tokens"
3586
- ]);
3587
- return {
3588
- [GenAiTelemetryAttributeNames.usageInputTokens]: inputTokens,
3589
- [GenAiTelemetryAttributeNames.usageOutputTokens]: outputTokens,
3590
- [GenAiTelemetryAttributeNames.usageTotalTokens]: totalTokens,
3591
- [GenAiTelemetryAttributeNames.usageCacheReadInputTokens]: cachedInputTokens,
3592
- [GenAiTelemetryAttributeNames.usageReasoningTokens]: reasoningTokens
3593
- };
3594
- }
3595
- extractUsageObject(response) {
3596
- if (!this.isRecord(response)) return;
3597
- const usageMetadata = response["usage_metadata"];
3598
- if (this.isRecord(usageMetadata)) return usageMetadata;
3599
- const responseMetadata = response["response_metadata"];
3600
- if (this.isRecord(responseMetadata)) {
3601
- const tokenUsage = responseMetadata["tokenUsage"];
3602
- if (this.isRecord(tokenUsage)) return tokenUsage;
3603
- const usage = responseMetadata["usage"];
3604
- if (this.isRecord(usage)) return usage;
3605
- }
3606
- }
3607
- readUsageNumber(source, keys) {
3608
- for (const key of keys) {
3609
- const value = this.readNestedUsageValue(source, key);
3610
- if (typeof value === "number" && Number.isFinite(value)) return value;
3611
- }
3612
- }
3613
- readNestedUsageValue(source, dottedKey) {
3614
- if (!source) return;
3615
- let current = source;
3616
- for (const segment of dottedKey.split(".")) {
3617
- if (!this.isRecord(current)) return;
3618
- current = current[segment];
3619
- }
3620
- return current;
3621
- }
3622
- isRecord(value) {
3623
- return typeof value === "object" && value !== null;
3624
- }
3625
6210
  async markQueuedTools(plannedToolCalls, ctx) {
3626
- for (const plannedToolCall of plannedToolCalls) await ctx.nodeState?.markQueued({
3627
- nodeId: plannedToolCall.nodeId,
3628
- activationId: ctx.activationId,
3629
- inputsByPort: AgentToolCallPortMap.fromInput(plannedToolCall.toolCall.input ?? {})
3630
- });
6211
+ const queuedAt = (/* @__PURE__ */ new Date()).toISOString();
6212
+ for (const plannedToolCall of plannedToolCalls) {
6213
+ await ctx.nodeState?.markQueued({
6214
+ nodeId: plannedToolCall.nodeId,
6215
+ activationId: ctx.activationId,
6216
+ inputsByPort: AgentToolCallPortMap.fromInput(plannedToolCall.toolCall.input ?? {})
6217
+ });
6218
+ await ctx.nodeState?.appendConnectionInvocation({
6219
+ invocationId: plannedToolCall.invocationId,
6220
+ connectionNodeId: plannedToolCall.nodeId,
6221
+ parentAgentNodeId: ctx.nodeId,
6222
+ parentAgentActivationId: ctx.activationId,
6223
+ status: "queued",
6224
+ managedInput: this.resultToJsonValue(plannedToolCall.toolCall.input),
6225
+ queuedAt,
6226
+ iterationId: ctx.iterationId,
6227
+ itemIndex: ctx.itemIndex,
6228
+ parentInvocationId: ctx.parentInvocationId
6229
+ });
6230
+ }
3631
6231
  }
3632
6232
  planToolCalls(bindings, toolCalls, parentNodeId) {
3633
6233
  const invocationCountByToolName = /* @__PURE__ */ new Map();
@@ -3640,7 +6240,8 @@ let AIAgentNode = class AIAgentNode$1 {
3640
6240
  binding,
3641
6241
  toolCall,
3642
6242
  invocationIndex,
3643
- nodeId: ConnectionNodeIdFactory.toolConnectionNodeId(parentNodeId, binding.config.name)
6243
+ nodeId: ConnectionNodeIdFactory.toolConnectionNodeId(parentNodeId, binding.config.name),
6244
+ invocationId: ConnectionInvocationIdFactory.create()
3644
6245
  };
3645
6246
  });
3646
6247
  }
@@ -3668,7 +6269,10 @@ let AIAgentNode = class AIAgentNode$1 {
3668
6269
  },
3669
6270
  queuedAt: args.startedAt.toISOString(),
3670
6271
  startedAt: args.startedAt.toISOString(),
3671
- finishedAt: finishedAt.toISOString()
6272
+ finishedAt: finishedAt.toISOString(),
6273
+ iterationId: args.ctx.iterationId,
6274
+ itemIndex: args.ctx.itemIndex,
6275
+ parentInvocationId: args.ctx.parentInvocationId
3672
6276
  });
3673
6277
  return effectiveError;
3674
6278
  }
@@ -3681,7 +6285,7 @@ let AIAgentNode = class AIAgentNode$1 {
3681
6285
  };
3682
6286
  }
3683
6287
  resultToJsonValue(value) {
3684
- if (value === void 0) return;
6288
+ if (value === void 0) return void 0;
3685
6289
  const json = JSON.stringify(value);
3686
6290
  return JSON.parse(json);
3687
6291
  }
@@ -3696,7 +6300,7 @@ let AIAgentNode = class AIAgentNode$1 {
3696
6300
  resolveToolRuntime(config$1) {
3697
6301
  if (this.isNodeBackedToolConfig(config$1)) {
3698
6302
  const inputSchema = config$1.getInputSchema();
3699
- if (inputSchema == null) throw new Error(`AIAgent tool "${config$1.name}": node-backed tool is missing inputSchema (cannot build LangChain tool).`);
6303
+ if (inputSchema == null) throw new Error(`AIAgent tool "${config$1.name}": node-backed tool is missing inputSchema (cannot build AI SDK tool).`);
3700
6304
  return {
3701
6305
  defaultDescription: `Run workflow node "${config$1.node.name ?? config$1.name}" as an AI tool.`,
3702
6306
  inputSchema,
@@ -3705,7 +6309,7 @@ let AIAgentNode = class AIAgentNode$1 {
3705
6309
  }
3706
6310
  if (this.isCallableToolConfig(config$1)) {
3707
6311
  const inputSchema = config$1.getInputSchema();
3708
- if (inputSchema == null) throw new Error(`AIAgent tool "${config$1.name}": callable tool is missing inputSchema (cannot build LangChain tool).`);
6312
+ if (inputSchema == null) throw new Error(`AIAgent tool "${config$1.name}": callable tool is missing inputSchema (cannot build AI SDK tool).`);
3709
6313
  return {
3710
6314
  defaultDescription: config$1.description ?? `Callable tool "${config$1.name}".`,
3711
6315
  inputSchema,
@@ -3723,17 +6327,9 @@ let AIAgentNode = class AIAgentNode$1 {
3723
6327
  execute: async (args) => await Promise.resolve(tool.execute(args))
3724
6328
  };
3725
6329
  }
3726
- /**
3727
- * Consumer apps can resolve two copies of `@codemation/core`, breaking `instanceof NodeBackedToolConfig` and
3728
- * sending node-backed tools down the plugin-tool branch with `inputSchema: undefined` (LangChain then crashes in
3729
- * json-schema validation). {@link NodeBackedToolConfig#toolKind} is stable across copies.
3730
- */
3731
6330
  isNodeBackedToolConfig(config$1) {
3732
6331
  return config$1 instanceof NodeBackedToolConfig || typeof config$1 === "object" && config$1 !== null && config$1.toolKind === "nodeBacked";
3733
6332
  }
3734
- /**
3735
- * Callable tools use {@link CallableToolConfig#toolKind} for cross-package / JSON round-trip safety.
3736
- */
3737
6333
  isCallableToolConfig(config$1) {
3738
6334
  return config$1 instanceof CallableToolConfig || typeof config$1 === "object" && config$1 !== null && config$1.toolKind === "callable";
3739
6335
  }
@@ -3804,6 +6400,52 @@ var AIAgent = class {
3804
6400
  }
3805
6401
  };
3806
6402
 
6403
+ //#endregion
6404
+ //#region src/nodes/AssertionNode.ts
6405
+ let AssertionNode = class AssertionNode$1 {
6406
+ kind = "node";
6407
+ outputPorts = ["main"];
6408
+ async execute(args) {
6409
+ const ctx = args.ctx;
6410
+ const config$1 = ctx.config;
6411
+ try {
6412
+ return [...await config$1.assertions(args.item, ctx)];
6413
+ } catch (err) {
6414
+ const message = err instanceof Error ? err.message : String(err);
6415
+ return [{
6416
+ name: config$1.name ?? "assertion",
6417
+ score: 0,
6418
+ errored: true,
6419
+ message
6420
+ }];
6421
+ }
6422
+ }
6423
+ };
6424
+ AssertionNode = __decorate([node({ packageName: "@codemation/core-nodes" })], AssertionNode);
6425
+
6426
+ //#endregion
6427
+ //#region src/nodes/assertion.ts
6428
+ /**
6429
+ * Generic assertion node — the "callback" form. For declarative shorthands (StringEquals,
6430
+ * JudgeByAgent) compose this with helpers added in later phases. Sets `emitsAssertions: true`
6431
+ * so host-side persisters know to record its outputs as `TestAssertion` rows.
6432
+ */
6433
+ var Assertion = class {
6434
+ kind = "node";
6435
+ type = AssertionNode;
6436
+ icon;
6437
+ name;
6438
+ id;
6439
+ emitsAssertions = true;
6440
+ assertions;
6441
+ constructor(options) {
6442
+ this.name = options.name ?? "Assertion";
6443
+ this.id = options.id;
6444
+ this.icon = options.icon ?? "lucide:check-circle";
6445
+ this.assertions = options.assertions;
6446
+ }
6447
+ };
6448
+
3807
6449
  //#endregion
3808
6450
  //#region src/nodes/CallbackResultNormalizerFactory.ts
3809
6451
  var CallbackResultNormalizer = class {
@@ -3873,32 +6515,113 @@ let HttpRequestNode = class HttpRequestNode$1 {
3873
6515
  }
3874
6516
  async executeItem(item, ctx) {
3875
6517
  const url = this.resolveUrl(item, ctx);
3876
- const response = await fetch(url, { method: ctx.config.method });
6518
+ const credential = await this.resolveCredential(ctx);
6519
+ const spec = {
6520
+ url,
6521
+ method: ctx.config.method,
6522
+ headers: ctx.config.args.headers,
6523
+ query: ctx.config.args.query,
6524
+ body: ctx.config.args.body,
6525
+ credential,
6526
+ download: {
6527
+ mode: ctx.config.downloadMode,
6528
+ binaryName: ctx.config.binaryName
6529
+ },
6530
+ responseFormat: ctx.config.responseFormat,
6531
+ responseBinarySlot: ctx.config.responseBinarySlot,
6532
+ responseSizeCapBytes: ctx.config.responseSizeCapBytes,
6533
+ ctx
6534
+ };
6535
+ const { url: resolvedUrl, init } = await new HttpRequestExecutor(globalThis.fetch, new HttpBodyBuilder(), new HttpUrlBuilder()).buildRequest(spec, item);
6536
+ const response = await globalThis.fetch(resolvedUrl, init);
3877
6537
  const headers = this.readHeaders(response.headers);
3878
6538
  const mimeType = this.resolveMimeType(headers);
3879
- const bodyBinaryName = ctx.config.binaryName;
3880
- const shouldAttachBody = this.shouldAttachBody(ctx.config.downloadMode, mimeType);
3881
- let outputItem = { json: {
3882
- url,
6539
+ if (ctx.config.responseFormat === "binary") return await this.handleBinaryResponse(response, resolvedUrl, headers, mimeType, ctx);
6540
+ const binaryName = ctx.config.binaryName;
6541
+ if (this.shouldAttachBody(ctx.config.downloadMode, mimeType)) {
6542
+ const outputJson = {
6543
+ url: resolvedUrl,
6544
+ method: ctx.config.method,
6545
+ ok: response.ok,
6546
+ status: response.status,
6547
+ statusText: response.statusText,
6548
+ mimeType,
6549
+ headers,
6550
+ bodyBinaryName: binaryName
6551
+ };
6552
+ const attachment = await ctx.binary.attach({
6553
+ name: binaryName,
6554
+ body: response.body ? response.body : new Uint8Array(await response.arrayBuffer()),
6555
+ mimeType,
6556
+ filename: this.resolveFilename(resolvedUrl, headers)
6557
+ });
6558
+ let outputItem = { json: outputJson };
6559
+ outputItem = ctx.binary.withAttachment(outputItem, binaryName, attachment);
6560
+ return outputItem;
6561
+ }
6562
+ const isJson = this.isJsonMimeType(mimeType);
6563
+ let json;
6564
+ let text;
6565
+ if (isJson) try {
6566
+ json = await response.json();
6567
+ } catch {
6568
+ text = await response.text();
6569
+ }
6570
+ else text = await response.text();
6571
+ return { json: {
6572
+ url: resolvedUrl,
3883
6573
  method: ctx.config.method,
3884
6574
  ok: response.ok,
3885
6575
  status: response.status,
3886
6576
  statusText: response.statusText,
3887
6577
  mimeType,
3888
6578
  headers,
3889
- ...shouldAttachBody ? { bodyBinaryName } : {}
6579
+ ...json !== void 0 ? { json } : {},
6580
+ ...text !== void 0 ? { text } : {}
3890
6581
  } };
3891
- if (!shouldAttachBody) return outputItem;
6582
+ }
6583
+ async handleBinaryResponse(response, resolvedUrl, headers, mimeType, ctx) {
6584
+ const slotName = ctx.config.responseBinarySlot;
6585
+ const sizeCap = ctx.config.responseSizeCapBytes;
6586
+ const contentLengthHeader = headers["content-length"];
6587
+ if (contentLengthHeader) {
6588
+ const declaredSize = parseInt(contentLengthHeader, 10);
6589
+ if (!isNaN(declaredSize) && declaredSize > sizeCap) throw new Error(`HttpRequest responseFormat "binary": response Content-Length (${declaredSize} bytes) exceeds responseSizeCapBytes (${sizeCap} bytes).`);
6590
+ }
6591
+ const filename = this.resolveFilename(resolvedUrl, headers);
3892
6592
  const attachment = await ctx.binary.attach({
3893
- name: bodyBinaryName,
6593
+ name: slotName,
3894
6594
  body: response.body ? response.body : new Uint8Array(await response.arrayBuffer()),
3895
6595
  mimeType,
3896
- filename: this.resolveFilename(url, headers)
6596
+ filename
3897
6597
  });
3898
- outputItem = ctx.binary.withAttachment(outputItem, bodyBinaryName, attachment);
6598
+ let outputItem = { json: {
6599
+ url: resolvedUrl,
6600
+ method: ctx.config.method,
6601
+ ok: response.ok,
6602
+ status: response.status,
6603
+ statusText: response.statusText,
6604
+ headers,
6605
+ binarySlot: slotName,
6606
+ contentType: mimeType,
6607
+ size: attachment.size,
6608
+ ...filename !== void 0 ? { filename } : {}
6609
+ } };
6610
+ outputItem = ctx.binary.withAttachment(outputItem, slotName, attachment);
3899
6611
  return outputItem;
3900
6612
  }
6613
+ async resolveCredential(ctx) {
6614
+ const slotKey = ctx.config.args.credentialSlot;
6615
+ if (!slotKey) return;
6616
+ try {
6617
+ return await ctx.getCredential(slotKey);
6618
+ } catch {
6619
+ return;
6620
+ }
6621
+ }
3901
6622
  resolveUrl(item, ctx) {
6623
+ const literalUrl = ctx.config.args.url;
6624
+ if (literalUrl && literalUrl.trim().length > 0) return literalUrl.trim();
3902
6625
  const candidate = this.asRecord(item.json)[ctx.config.urlField];
3903
6626
  if (typeof candidate !== "string" || candidate.trim() === "") throw new Error(`HttpRequest node expected item.json.${ctx.config.urlField} to contain a URL string.`);
3904
6627
  return candidate;
@@ -3919,6 +6642,9 @@ let HttpRequestNode = class HttpRequestNode$1 {
3919
6642
  if (!contentType) return "application/octet-stream";
3920
6643
  return contentType.split(";")[0]?.trim() || "application/octet-stream";
3921
6644
  }
6645
+ isJsonMimeType(mimeType) {
6646
+ return mimeType === "application/json" || mimeType.endsWith("+json");
6647
+ }
3922
6648
  shouldAttachBody(mode, mimeType) {
3923
6649
  if (mode === "always") return true;
3924
6650
  if (mode === "never") return false;
@@ -3945,10 +6671,23 @@ HttpRequestNode = __decorate([node({ packageName: "@codemation/core-nodes" })],
3945
6671
 
3946
6672
  //#endregion
3947
6673
  //#region src/nodes/httpRequest.ts
6674
+ /**
6675
+ * The built-in HTTP request credential type IDs accepted by the `HttpRequest` node.
6676
+ * These match the four generic credential types shipped with `@codemation/core-nodes`.
6677
+ */
6678
+ const HTTP_REQUEST_ACCEPTED_CREDENTIAL_TYPES = [
6679
+ bearerTokenCredentialType.definition.typeId,
6680
+ apiKeyCredentialType.definition.typeId,
6681
+ basicAuthCredentialType.definition.typeId,
6682
+ oauth2ClientCredentialsType.definition.typeId
6683
+ ];
6684
+ /** Default maximum response size for binary mode: 100 MiB. */
6685
+ const DEFAULT_RESPONSE_SIZE_CAP_BYTES = 100 * 1024 * 1024;
3948
6686
  var HttpRequest = class {
3949
6687
  kind = "node";
3950
6688
  type = HttpRequestNode;
3951
6689
  execution = { hint: "local" };
6690
+ icon = "lucide:globe";
3952
6691
  constructor(name, args = {}, retryPolicy = RetryPolicy.defaultForHttp) {
3953
6692
  this.name = name;
3954
6693
  this.args = args;
@@ -3969,6 +6708,25 @@ var HttpRequest = class {
3969
6708
  get downloadMode() {
3970
6709
  return this.args.downloadMode ?? "auto";
3971
6710
  }
6711
+ get responseFormat() {
6712
+ return this.args.responseFormat;
6713
+ }
6714
+ get responseBinarySlot() {
6715
+ return this.args.responseBinarySlot ?? "response";
6716
+ }
6717
+ get responseSizeCapBytes() {
6718
+ return this.args.responseSizeCapBytes ?? DEFAULT_RESPONSE_SIZE_CAP_BYTES;
6719
+ }
6720
+ getCredentialRequirements() {
6721
+ if (!this.args.credentialSlot) return [];
6722
+ return [{
6723
+ slotKey: this.args.credentialSlot,
6724
+ label: "Authentication",
6725
+ acceptedTypes: HTTP_REQUEST_ACCEPTED_CREDENTIAL_TYPES,
6726
+ optional: true,
6727
+ helpText: "Optional credential for authenticating the HTTP request."
6728
+ }];
6729
+ }
3972
6730
  };
3973
6731
 
3974
6732
  //#endregion
@@ -3990,7 +6748,7 @@ var Aggregate = class {
3990
6748
  type = AggregateNode;
3991
6749
  execution = { hint: "local" };
3992
6750
  keepBinaries = true;
3993
- icon = "lucide:layers";
6751
+ icon = "builtin:aggregate-rows";
3994
6752
  constructor(name, aggregate, id) {
3995
6753
  this.name = name;
3996
6754
  this.aggregate = aggregate;
@@ -4085,7 +6843,7 @@ var If = class {
4085
6843
  kind = "node";
4086
6844
  type = IfNode;
4087
6845
  execution = { hint: "local" };
4088
- icon = "lucide:split";
6846
+ icon = "lucide:split@rot=90";
4089
6847
  declaredOutputPorts = ["true", "false"];
4090
6848
  constructor(name, predicate, id) {
4091
6849
  this.name = name;
@@ -4094,6 +6852,40 @@ var If = class {
4094
6852
  }
4095
6853
  };
4096
6854
 
6855
+ //#endregion
6856
+ //#region src/nodes/IsTestRunNode.ts
6857
+ let IsTestRunNode = class IsTestRunNode$1 {
6858
+ kind = "node";
6859
+ execute(args) {
6860
+ const isTest = args.ctx.testContext !== void 0;
6861
+ return emitPorts({
6862
+ true: isTest ? [args.item] : [],
6863
+ false: isTest ? [] : [args.item]
6864
+ });
6865
+ }
6866
+ };
6867
+ IsTestRunNode = __decorate([node({ packageName: "@codemation/core-nodes" })], IsTestRunNode);
6868
+
6869
+ //#endregion
6870
+ //#region src/nodes/isTestRun.ts
6871
+ /**
6872
+ * Branches per-item on whether the current run is a test run. Output ports: `true`, `false`.
6873
+ * The wire payload is unchanged — this is a router, not a transform.
6874
+ */
6875
+ var IsTestRun = class {
6876
+ kind = "node";
6877
+ type = IsTestRunNode;
6878
+ execution = { hint: "local" };
6879
+ icon = "lucide:flask-conical";
6880
+ declaredOutputPorts = ["true", "false"];
6881
+ name;
6882
+ id;
6883
+ constructor(name = "Is test run?", id) {
6884
+ this.name = name;
6885
+ this.id = id;
6886
+ }
6887
+ };
6888
+
4097
6889
  //#endregion
4098
6890
  //#region src/nodes/SwitchNode.ts
4099
6891
  let SwitchNode = class SwitchNode$1 {
@@ -4150,7 +6942,7 @@ var Split = class {
4150
6942
  * Mirrors {@link MapData}'s empty-output behavior.
4151
6943
  */
4152
6944
  continueWhenEmptyOutput = true;
4153
- icon = "lucide:ungroup";
6945
+ icon = "builtin:split-rows";
4154
6946
  constructor(name, getElements, id) {
4155
6947
  this.name = name;
4156
6948
  this.getElements = getElements;
@@ -4158,6 +6950,75 @@ var Split = class {
4158
6950
  }
4159
6951
  };
4160
6952
 
6953
+ //#endregion
6954
+ //#region src/nodes/CronTriggerNode.ts
6955
+ let CronTriggerNode = class CronTriggerNode$1 {
6956
+ kind = "trigger";
6957
+ outputPorts = ["main"];
6958
+ async setup(ctx) {
6959
+ const job = ctx.config.createJob(async (self) => {
6960
+ const scheduledFor = self.currentRun()?.toISOString() ?? ctx.now().toISOString();
6961
+ await ctx.emit([{ json: {
6962
+ firedAt: ctx.now().toISOString(),
6963
+ scheduledFor
6964
+ } }]);
6965
+ });
6966
+ ctx.registerCleanup({ stop: () => {
6967
+ job.stop();
6968
+ } });
6969
+ }
6970
+ async execute(items, _ctx) {
6971
+ return { main: items };
6972
+ }
6973
+ async getTestItems(ctx) {
6974
+ const nowIso = ctx.now().toISOString();
6975
+ return [{ json: {
6976
+ firedAt: nowIso,
6977
+ scheduledFor: nowIso
6978
+ } }];
6979
+ }
6980
+ };
6981
+ CronTriggerNode = __decorate([node({ packageName: "@codemation/core-nodes" })], CronTriggerNode);
6982
+
6983
+ //#endregion
6984
+ //#region src/nodes/CronTriggerFactory.ts
6985
+ /**
6986
+ * Schedules a workflow on a standard cron expression.
6987
+ *
6988
+ * Each tick emits one item: `{ firedAt: string, scheduledFor: string }` — both ISO-8601 timestamps.
6989
+ * `firedAt` is the wall-clock moment the callback ran; `scheduledFor` is the cron-computed
6990
+ * firing instant (these differ when the job was delayed).
6991
+ *
6992
+ * Timezone defaults to UTC when omitted — cron without an explicit TZ is a DST footgun.
6993
+ */
6994
+ var CronTrigger = class {
6995
+ kind = "trigger";
6996
+ type = CronTriggerNode;
6997
+ icon = "lucide:clock";
6998
+ id;
6999
+ constructor(name, args, id) {
7000
+ this.name = name;
7001
+ this.args = args;
7002
+ new Cron(args.schedule, {
7003
+ paused: true,
7004
+ timezone: args.timezone
7005
+ });
7006
+ this.id = id;
7007
+ }
7008
+ get schedule() {
7009
+ return this.args.schedule;
7010
+ }
7011
+ get timezone() {
7012
+ return this.args.timezone;
7013
+ }
7014
+ createJob(callback) {
7015
+ return new Cron(this.args.schedule, {
7016
+ timezone: this.args.timezone,
7017
+ protect: true
7018
+ }, callback);
7019
+ }
7020
+ };
7021
+
4161
7022
  //#endregion
4162
7023
  //#region src/nodes/ManualTriggerNode.ts
4163
7024
  let ManualTriggerNode = class ManualTriggerNode$1 {
@@ -4221,6 +7082,7 @@ var MapData = class {
4221
7082
  execution = { hint: "local" };
4222
7083
  /** Zero mapped items should still allow downstream nodes to run. */
4223
7084
  continueWhenEmptyOutput = true;
7085
+ icon = "lucide:square-pen";
4224
7086
  keepBinaries;
4225
7087
  constructor(name, map, options = {}) {
4226
7088
  this.name = name;
@@ -4290,7 +7152,7 @@ MergeNode = __decorate([node({ packageName: "@codemation/core-nodes" })], MergeN
4290
7152
  var Merge = class {
4291
7153
  kind = "node";
4292
7154
  type = MergeNode;
4293
- icon = "lucide:git-merge";
7155
+ icon = "lucide:merge@rot=90";
4294
7156
  constructor(name, cfg = { mode: "passThrough" }, id) {
4295
7157
  this.name = name;
4296
7158
  this.cfg = cfg;
@@ -4315,6 +7177,7 @@ var NoOp = class {
4315
7177
  kind = "node";
4316
7178
  type = NoOpNode;
4317
7179
  execution = { hint: "local" };
7180
+ icon = "lucide:circle-dashed";
4318
7181
  constructor(name = "NoOp", id) {
4319
7182
  this.name = name;
4320
7183
  this.id = id;
@@ -4387,6 +7250,52 @@ var SubWorkflow = class {
4387
7250
  }
4388
7251
  };
4389
7252
 
7253
+ //#endregion
7254
+ //#region src/nodes/TestTriggerNode.ts
7255
+ let TestTriggerNode = class TestTriggerNode$1 {
7256
+ kind = "trigger";
7257
+ outputPorts = ["main"];
7258
+ async setup(_ctx) {}
7259
+ async execute(items, _ctx) {
7260
+ return { main: items };
7261
+ }
7262
+ };
7263
+ TestTriggerNode = __decorate([node({ packageName: "@codemation/core-nodes" })], TestTriggerNode);
7264
+
7265
+ //#endregion
7266
+ //#region src/nodes/testTrigger.ts
7267
+ /**
7268
+ * Trigger config for a test fixture source. Drop one (or more) of these on the canvas alongside
7269
+ * a workflow's live triggers; clicking "Run tests" on the Tests tab invokes
7270
+ * {@link TestTriggerOptions.generateItems} via the TestSuiteOrchestrator.
7271
+ */
7272
+ var TestTrigger = class {
7273
+ kind = "trigger";
7274
+ triggerKind = "test";
7275
+ type = TestTriggerNode;
7276
+ icon;
7277
+ name;
7278
+ id;
7279
+ concurrency;
7280
+ description;
7281
+ generateItems;
7282
+ caseLabel;
7283
+ credentialRequirements;
7284
+ constructor(options) {
7285
+ this.name = options.name ?? "Test trigger";
7286
+ this.id = options.id;
7287
+ this.icon = options.icon ?? "lucide:flask-conical";
7288
+ this.concurrency = options.concurrency;
7289
+ this.description = options.description;
7290
+ this.credentialRequirements = options.credentialRequirements ?? [];
7291
+ this.generateItems = options.generateItems;
7292
+ this.caseLabel = options.caseLabel;
7293
+ }
7294
+ getCredentialRequirements() {
7295
+ return this.credentialRequirements;
7296
+ }
7297
+ };
7298
+
4390
7299
  //#endregion
4391
7300
  //#region src/nodes/WaitDurationFactory.ts
4392
7301
  var WaitDuration = class {
@@ -4420,6 +7329,7 @@ var Wait = class {
4420
7329
  execution = { hint: "local" };
4421
7330
  /** Pass-through empty batches should still advance to downstream nodes. */
4422
7331
  continueWhenEmptyOutput = true;
7332
+ icon = "lucide:hourglass";
4423
7333
  constructor(name, milliseconds, id) {
4424
7334
  this.name = name;
4425
7335
  this.milliseconds = milliseconds;
@@ -4470,7 +7380,7 @@ WebhookTriggerNode = __decorate([node({ packageName: "@codemation/core-nodes" })
4470
7380
  var WebhookTrigger = class WebhookTrigger {
4471
7381
  kind = "trigger";
4472
7382
  type = WebhookTriggerNode;
4473
- icon = "lucide:globe";
7383
+ icon = "lucide:webhook";
4474
7384
  constructor(name, args, handler = WebhookTrigger.defaultHandler, id) {
4475
7385
  this.name = name;
4476
7386
  this.args = args;
@@ -4566,10 +7476,10 @@ var WorkflowDefinedNodeResolver = class {
4566
7476
  //#endregion
4567
7477
  //#region src/workflowAuthoring/WorkflowDurationParser.types.ts
4568
7478
  var WorkflowDurationParser = class {
4569
- static parse(duration) {
4570
- if (typeof duration === "number") return Number.isFinite(duration) && duration > 0 ? Math.floor(duration) : 0;
4571
- const match = duration.trim().toLowerCase().match(/^(\d+)(ms|s|m|h)$/);
4572
- if (!match) throw new Error(`Unsupported wait duration "${duration}". Use a number of milliseconds or values like "500ms", "2s", "5m".`);
7479
+ static parse(duration$2) {
7480
+ if (typeof duration$2 === "number") return Number.isFinite(duration$2) && duration$2 > 0 ? Math.floor(duration$2) : 0;
7481
+ const match = duration$2.trim().toLowerCase().match(/^(\d+)(ms|s|m|h)$/);
7482
+ if (!match) throw new Error(`Unsupported wait duration "${duration$2}". Use a number of milliseconds or values like "500ms", "2s", "5m".`);
4573
7483
  const value = Number(match[1]);
4574
7484
  const unit = match[2];
4575
7485
  if (unit === "ms") return value;
@@ -4595,8 +7505,8 @@ var WorkflowBranchBuilder = class WorkflowBranchBuilder {
4595
7505
  }
4596
7506
  wait(nameOrDuration, durationOrUndefined, id) {
4597
7507
  const name = typeof nameOrDuration === "string" && durationOrUndefined !== void 0 ? nameOrDuration : "Wait";
4598
- const duration = durationOrUndefined ?? nameOrDuration;
4599
- return this.then(new Wait(name, WorkflowDurationParser.parse(duration), id));
7508
+ const duration$2 = durationOrUndefined ?? nameOrDuration;
7509
+ return this.then(new Wait(name, WorkflowDurationParser.parse(duration$2), id));
4600
7510
  }
4601
7511
  split(nameOrGetter, getElementsOrUndefined, id) {
4602
7512
  const name = typeof nameOrGetter === "string" ? nameOrGetter : "Split";
@@ -4641,8 +7551,8 @@ var WorkflowChain = class WorkflowChain {
4641
7551
  }
4642
7552
  wait(nameOrDuration, durationOrUndefined, id) {
4643
7553
  const name = typeof nameOrDuration === "string" && durationOrUndefined !== void 0 ? nameOrDuration : "Wait";
4644
- const duration = durationOrUndefined ?? nameOrDuration;
4645
- return this.then(new Wait(name, WorkflowDurationParser.parse(duration), id));
7554
+ const duration$2 = durationOrUndefined ?? nameOrDuration;
7555
+ return this.then(new Wait(name, WorkflowDurationParser.parse(duration$2), id));
4646
7556
  }
4647
7557
  split(nameOrGetter, getElementsOrUndefined, id) {
4648
7558
  const name = typeof nameOrGetter === "string" ? nameOrGetter : "Split";
@@ -4824,5 +7734,128 @@ var ConnectionCredentialNodeConfigFactory = class {
4824
7734
  };
4825
7735
 
4826
7736
  //#endregion
4827
- export { AIAgent, AIAgentConnectionWorkflowExpander, AIAgentExecutionHelpersFactory, AIAgentNode, AgentItemPortMap, AgentMessageFactory, AgentOutputFactory, AgentStructuredOutputRepairPromptFactory, AgentStructuredOutputRunner, AgentToolCallPortMap, AgentToolErrorClassifier, AgentToolExecutionCoordinator, AgentToolRepairExhaustedError, AgentToolRepairPolicy, Aggregate, AggregateNode, Callback, CallbackNode, CallbackResultNormalizer, ConnectionCredentialExecutionContextFactory, ConnectionCredentialNode, ConnectionCredentialNodeConfig, ConnectionCredentialNodeConfigFactory, Filter, FilterNode, HttpRequest, HttpRequestNode, If, IfNode, ManualTrigger, ManualTriggerNode, MapData, MapDataNode, Merge, MergeNode, NoOp, NoOpNode, OpenAIChatModelConfig, OpenAIChatModelFactory, OpenAIStructuredOutputMethodFactory, OpenAiChatModelPresets, Split, SplitNode, SubWorkflow, SubWorkflowNode, Switch, SwitchNode, Wait, WaitDuration, WaitNode, WebhookRespondNowAndContinueError, WebhookRespondNowError, WebhookTrigger, WebhookTriggerNode, WorkflowAuthoringBuilder, WorkflowBranchBuilder, WorkflowChain, createWorkflowBuilder, openAiChatModelPresets, registerCoreNodes, workflow };
7737
+ //#region src/nodes/collections/collectionInsertNode.types.ts
7738
+ const collectionInsertNode = defineNode({
7739
+ key: "collection-insert",
7740
+ title: "Collection: Insert",
7741
+ description: "Insert a new row into a collection.",
7742
+ icon: "lucide:boxes",
7743
+ configSchema: object({
7744
+ collectionName: string(),
7745
+ data: record(string(), unknown())
7746
+ }),
7747
+ async execute(_args, { config: config$1, execution }) {
7748
+ const store = execution.collections?.[config$1.collectionName];
7749
+ if (!store) throw new Error(`Collection "${config$1.collectionName}" is not registered. Add defineCollection to your codemation config.`);
7750
+ return await store.insert(config$1.data);
7751
+ }
7752
+ });
7753
+
7754
+ //#endregion
7755
+ //#region src/nodes/collections/collectionGetNode.types.ts
7756
+ const collectionGetNode = defineNode({
7757
+ key: "collection-get",
7758
+ title: "Collection: Get",
7759
+ description: "Get a single row by id from a collection.",
7760
+ icon: "lucide:layers",
7761
+ configSchema: object({
7762
+ collectionName: string(),
7763
+ id: string()
7764
+ }),
7765
+ async execute(_args, { config: config$1, execution }) {
7766
+ const store = execution.collections?.[config$1.collectionName];
7767
+ if (!store) throw new Error(`Collection "${config$1.collectionName}" is not registered. Add defineCollection to your codemation config.`);
7768
+ const row = await store.get(config$1.id);
7769
+ if (row === null) return [];
7770
+ return row;
7771
+ }
7772
+ });
7773
+
7774
+ //#endregion
7775
+ //#region src/nodes/collections/collectionFindOneNode.types.ts
7776
+ const collectionFindOneNode = defineNode({
7777
+ key: "collection-find-one",
7778
+ title: "Collection: Find One",
7779
+ description: "Find a single row matching a filter in a collection.",
7780
+ icon: "lucide:filter",
7781
+ configSchema: object({
7782
+ collectionName: string(),
7783
+ where: record(string(), unknown())
7784
+ }),
7785
+ async execute(_args, { config: config$1, execution }) {
7786
+ const store = execution.collections?.[config$1.collectionName];
7787
+ if (!store) throw new Error(`Collection "${config$1.collectionName}" is not registered. Add defineCollection to your codemation config.`);
7788
+ const row = await store.findOne(config$1.where);
7789
+ if (row === null) return [];
7790
+ return row;
7791
+ }
7792
+ });
7793
+
7794
+ //#endregion
7795
+ //#region src/nodes/collections/collectionListNode.types.ts
7796
+ const collectionListNode = defineNode({
7797
+ key: "collection-list",
7798
+ title: "Collection: List",
7799
+ description: "List rows from a collection with optional pagination and filtering.",
7800
+ icon: "lucide:split",
7801
+ configSchema: object({
7802
+ collectionName: string(),
7803
+ limit: number().int().positive().optional(),
7804
+ offset: number().int().nonnegative().optional(),
7805
+ where: record(string(), unknown()).optional()
7806
+ }),
7807
+ async execute(_args, { config: config$1, execution }) {
7808
+ const store = execution.collections?.[config$1.collectionName];
7809
+ if (!store) throw new Error(`Collection "${config$1.collectionName}" is not registered. Add defineCollection to your codemation config.`);
7810
+ const { rows } = await store.list({
7811
+ limit: config$1.limit,
7812
+ offset: config$1.offset,
7813
+ where: config$1.where
7814
+ });
7815
+ return [...rows];
7816
+ }
7817
+ });
7818
+
7819
+ //#endregion
7820
+ //#region src/nodes/collections/collectionUpdateNode.types.ts
7821
+ const collectionUpdateNode = defineNode({
7822
+ key: "collection-update",
7823
+ title: "Collection: Update",
7824
+ description: "Update a row by id in a collection.",
7825
+ icon: "lucide:square-pen",
7826
+ configSchema: object({
7827
+ collectionName: string(),
7828
+ id: string(),
7829
+ patch: record(string(), unknown())
7830
+ }),
7831
+ async execute(_args, { config: config$1, execution }) {
7832
+ const store = execution.collections?.[config$1.collectionName];
7833
+ if (!store) throw new Error(`Collection "${config$1.collectionName}" is not registered. Add defineCollection to your codemation config.`);
7834
+ return await store.update(config$1.id, config$1.patch);
7835
+ }
7836
+ });
7837
+
7838
+ //#endregion
7839
+ //#region src/nodes/collections/collectionDeleteNode.types.ts
7840
+ const collectionDeleteNode = defineNode({
7841
+ key: "collection-delete",
7842
+ title: "Collection: Delete",
7843
+ description: "Delete a row by id from a collection.",
7844
+ icon: "lucide:braces",
7845
+ configSchema: object({
7846
+ collectionName: string(),
7847
+ id: string()
7848
+ }),
7849
+ async execute(_args, { config: config$1, execution }) {
7850
+ const store = execution.collections?.[config$1.collectionName];
7851
+ if (!store) throw new Error(`Collection "${config$1.collectionName}" is not registered. Add defineCollection to your codemation config.`);
7852
+ return {
7853
+ deleted: (await store.delete(config$1.id)).deleted,
7854
+ id: config$1.id
7855
+ };
7856
+ }
7857
+ });
7858
+
7859
+ //#endregion
7860
+ export { AIAgent, AIAgentConnectionWorkflowExpander, AIAgentExecutionHelpersFactory, AIAgentNode, AgentItemPortMap, AgentMessageFactory, AgentOutputFactory, AgentStructuredOutputRepairPromptFactory, AgentStructuredOutputRunner, AgentToolCallPortMap, AgentToolErrorClassifier, AgentToolExecutionCoordinator, AgentToolRepairExhaustedError, AgentToolRepairPolicy, Aggregate, AggregateNode, Assertion, AssertionNode, Callback, CallbackNode, CallbackResultNormalizer, ConnectionCredentialExecutionContextFactory, ConnectionCredentialNode, ConnectionCredentialNodeConfig, ConnectionCredentialNodeConfigFactory, CronTrigger, CronTriggerNode, Filter, FilterNode, HTTP_REQUEST_ACCEPTED_CREDENTIAL_TYPES, HttpRequest, HttpRequestNode, If, IfNode, IsTestRun, IsTestRunNode, ManualTrigger, ManualTriggerNode, MapData, MapDataNode, Merge, MergeNode, NoOp, NoOpNode, OpenAIChatModelConfig, OpenAIChatModelFactory, OpenAiChatModelPresets, OpenAiStrictJsonSchemaFactory, Split, SplitNode, SubWorkflow, SubWorkflowNode, Switch, SwitchNode, TestTrigger, TestTriggerNode, Wait, WaitDuration, WaitNode, WebhookRespondNowAndContinueError, WebhookRespondNowError, WebhookTrigger, WebhookTriggerNode, WorkflowAuthoringBuilder, WorkflowBranchBuilder, WorkflowChain, apiKeyCredentialType, basicAuthCredentialType, bearerTokenCredentialType, collectionDeleteNode, collectionFindOneNode, collectionGetNode, collectionInsertNode, collectionListNode, collectionUpdateNode, createWorkflowBuilder, defineRestNode, oauth2ClientCredentialsType, openAiChatModelPresets, registerCoreNodes, workflow };
4828
7861
  //# sourceMappingURL=index.js.map